Wrap code/text into multiple Lines in Jupyter Notebook

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
3 min

banner

# Wrap code/text into multiple Lines in Jupyter Notebook

By default, when writing code in Jupyter Notebook, text and code are not wrapped into multiple lines.

jupyter notebook horizontal scrollbar

Notice that a horizontal scrollbar is shown instead of wrapping the text.

Instead of having to scroll every time your line exceeds the screen's width, you could wrap the text as shown in the following screenshot.

jupyter notebook without horizontal scrollbar

To wrap code/text so it appears on multiple lines in Jupyter Notebook:

  1. Use the jupyter --config-dir command to print where your configuration directory is located.
shell
jupyter --config-dir

get jupyter config directory

  1. In my case, the configuration directory is ~/.jupyter which is equivalent to /home/<user>/.jupyter.

  2. Open your config directory and create a nbconfig folder in it (assuming it doesn't already exist).

  3. In my case, the nbconfig folder is located under ~/.jupyter/nbconfig which is equivalent to /home/<user>/.jupyter/nbconfig.

  4. Create a notebook.json file in your nbconfig directory.

create notebook json file in nbconfig directory

  1. Add the following code to your notebook.json file.
~/.jupyter/nbconfig/notebook.json
{ "MarkdownCell": { "cm_config": { "lineWrapping": true } }, "CodeCell": { "cm_config": { "lineWrapping": true } } }

add code to notebook json file

Make sure the code in your notebook.json file is valid JSON.

All properties should be double-quoted and you shouldn't have any trailing commas.

  1. Stop your Jupyter Notebook server and rerun the jupyter-notebook command.

  2. After you restart the kernel, code/text will wrap into multiple lines.

jupyter notebook without horizontal scrollbar

# Using Jupyter Notebook in Visual Studio Code

If you use Jupyter Notebook in Visual Studio Code, you can also enable the "Word Wrap" setting directly in the IDE.

  1. Press Ctrl + Shift + P (or Command + Shift + P on macOS).
Note: you can also press F1 to open the Command Palette.
  1. Type user settings and select Preferences: Open User Settings.

open user settings

You can also open the settings screen by pressing Ctrl + , on Windows and Linux or Cmd + , on macOS.

  1. Type word wrap in the search field.

  2. Set the Editor: Word Wrap setting to on.

enable editor word wrap

I've also written an article on How to add a new line in a Jupyter Notebook markdown cell.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.