92

I am using jupyter-notebooks for python coding. Is there a way to wrap text/code in a jupyter notebook code cell?

Picture provided below.

Text not wrapping

By wrap text means "how text is wrapped in MS-word"

Anuj Gupta
  • 6,328
  • 7
  • 36
  • 55
  • You could try the answer(s) provided [here](http://stackoverflow.com/questions/20672537/how-to-enable-line-wrapping-in-ipython-notebook). If it works out, you could answer your own question so others who search for this know that it still works in jupyter notebooks – M.T Apr 05 '16 at 07:42
  • @M.T : these steps are for Ipython notebook. I came across thread like https://groups.google.com/forum/#!topic/jupyter/AczTdZqStoM but I am unable to find files like ~/.jupyter/custom/custom.js – Anuj Gupta Apr 07 '16 at 04:59

9 Answers9

128

Find your configuration directory via jupyter --config-dir (mine is ~/.jupyter). Then edit or create nbconfig/notebook.json to add the following:

{
  "MarkdownCell": {
    "cm_config": {
      "lineWrapping": true
    }
  },
  "CodeCell": {
    "cm_config": {
      "lineWrapping": true
    }
  }
}

(If you have something else in it, ensure you have valid JSON with no trailing commas after }s.)

Restart Jupyter and reload your notebook.

Source: https://github.com/jupyter/notebook/issues/106

Dan
  • 2,766
  • 3
  • 27
  • 28
  • 1
    This approach is not working for me. nbconfig should be a new subdirectory to .jupyter and notebook.json should be a textfile stored in it? – J Kelly May 15 '17 at 13:52
  • 1
    This didn't work for me either--until I realized the `json` file format doesn't like `#` comments. It's my habit of quoting the source of my edits in config files, such as this post's URL. – xtian Aug 06 '17 at 16:14
  • 3
    @ J Kelly. That's correct, you can create the `nbconfig` with `mkdir nbconfig`, then `nano notebook.json` to create an empty file named `notebook.json` in which you will paste the code. – BCArg Mar 08 '18 at 14:28
  • 2
    This works. my notebook config file is located at `/home/username/anaconda3/etc/jupyter/nbconfig/notebook.json` – Jason Apr 22 '19 at 18:49
  • Extensions were not enabled by default on my system. After enabling them using the command `jupyter nbextension enable --py widgetsnbextension`, it is working fine. For more [details](https://github.com/jupyter/help/issues/186#issuecomment-359049200) – gaganso Sep 25 '19 at 03:23
  • Any idea how to get this to work in Google colab? I can't find the config file in question. – Davebs Jul 25 '20 at 14:07
  • If you want to do it directly from the notebook you can use the following 3 lines of code: `from notebook.services.config import ConfigManager` `c = ConfigManager()` `c.update('notebook', {"CodeCell": {"cm_config": {"lineWrapping": True}}})` – Louis Gagnon Mar 08 '21 at 08:17
  • I have two questions: 1) Where do I enter ```jupyter --config-dir```? 2) How do I access the file ```nbconfig/notebook.json```? (Sorry for the newbie questions...) – Leonidas Nov 11 '21 at 17:48
  • What about Google Colab? I tried `from notebook.services.config import ConfigManager ...` but it does not take effect. – HappyFace Jan 17 '22 at 19:46
  • Instead of doing both "MarkdownCell" and "CodeCell", I just did "Cell". It's one less thing to worry about. – Funny Geeks Mar 07 '22 at 02:13
29

In addition to Dan's answer, you can apply line wrapping for all cells (code or markdown) by specifying the top object as Cell. Adding the code below to your ~/.jupyter/nbconfig/notebook.json

{
  "Cell": {
    "cm_config": {
      "lineWrapping": true
    }
  }
}

Ex: This is my cell config

{
  "Cell": {
    "cm_config": {
      "lineNumbers": false,
      "lineWrapping": true
    }
  }
}
eden
  • 5,876
  • 2
  • 28
  • 43
9

enter image description here

In VS Code, go to File > Preferences > Settings > Search "wrap" > check the "Notebook > Output: Word Wrap" box, as shown in the screenshot

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Dave Chong
  • 405
  • 4
  • 4
8

When using jupyter-lab (rather than jupyter notebook) the solution is much simpler.

You can do:

Settings > Advanced setting Editor > TextEditor > checkbox enable Line Wrap.

Advanced settings editor

Tom
  • 133
  • 8
2

I am working with Jupyter notebook (.ipynb) through VSC Visual Studio Code, and I did find out that setting line/word wrapping could be set as follows:

  1. hit F1
  2. choose Preferences: Open Settings (UI)
  3. start typing in wrap
  4. Editor: Word Wrap Controls how lines should wrap pops up, change to On

It works for code (Python cells). Markdown cells work fine even without changing above setting.

heniczyna
  • 137
  • 1
  • 4
1

Easiest for me was this, straightforward and does not require a pip install:

from textwrap import wrap
long_str = 'I rip wrap unravel when I time travel, with beats in my head'
lines = wrap(long_str, 20) #wrap outputs a list of lines
print('\n'.join(lines))    #so join 'em with newline

#prints: 
#I rip wrap unravel
#when I time travel,
#with beats in my
#head
keymasta
  • 11
  • 3
  • This does not concern directly to how Jupyter Notebook wraps any input as in the question context. This does not answer the question. – Azhar May 27 '22 at 09:40
0

This may not be as satisfactory of an answer but while working Google Colab, I use the three single quote marks above and below the line of comments. Once quote marks are in place, I can hit return where I see fit.

Original comment:

# Using the number of rows from the original concatenated dataframe and the trimmed dataframe, quantify the percent difference between the number of rows lost

Solution:

''' Using the number of rows from the original concatenated dataframe and the trimmed dataframe, quantify the percent difference between the number of rows lost '''

Here is a screen grab of the solution: enter image description here

  • This won't work for the lines of code, moreover the OP never asked for how to split the code in lines using `'\'` or comments using `''' '''`. Rather what he is looking for is to *"wrap"* the content on the cells automatically. – Shubham Srivastava Oct 27 '21 at 07:31
0

Since none of these solutions worked for me, I opted for a different approach and wrote a simple column-wrapping print function that you can use to manually guarantee that the lines of any string will remain in view, for simple output checking scenarios.

def printwr( item, wrapCol=70 ):
    """ wrap printing to column limit """
    posit = 0
    while True:
        # if remaining legnth eq/less than wrapCol, print and rturn
        if len(item[posit:]) <= wrapCol: print(item[posit:]); return
        # else take wrapCol chars from last index
        llim = posit+wrapCol+1
        # if more than one item, drop last contiguous non-space sequence (word)
        lineSpl = item[posit:llim].split(' ')
        segment = ' '.join(lineSpl[:-1]) if len(lineSpl)>1 else lineSpl
        # print segment and increment posit by length segment
        posit += len(segment)+1
        print(segment)

For example, for

exampleStr = "populations tend to cluster in the foothills and periphery of the rugged Hindu Kush range; smaller groups are found in many of the country's interior valleys; in general, the east is more densely settled, while the south is sparsely populated"

printwr(exampleStr) 

produces:

populations tend to cluster in the foothills and periphery of the rugged Hindu Kush range; smaller groups are found in many of the country's interior valleys; in general, the east is more densely settled, while the south is sparsely populated

-6

Shortest Answer Ever

Try adding a ' \ ' in between the lines of code you need to split.

This allows you to split your code over different lines and helps it look prettier.

Community
  • 1
  • 1
  • This requires user to makes change to code (insert '\'). A better solution (if any) would let the tool (jupyter) handle it. – Anuj Gupta Oct 25 '17 at 08:18