31

Is this a syntax highlighting issue in my iPython notebook? Can I remove it? This happens in some of my cells, but not others.

ipython red text

I'm viewing this iPython notebook.

Matt
  • 27,170
  • 6
  • 80
  • 74
Matt
  • 4,815
  • 5
  • 39
  • 40
  • Certainly looks like a syntax highlighting issue. The javascript parser might be messed-up. That's the only reason I can think of. Not sure what you are looking for as far as an answer goes... – OneCricketeer Feb 11 '16 at 04:39
  • I'm not familiar with how iPython notebooks handle syntax highlighting -- how is a js parser involved? I see nothing in my juypter config related to syntax highlighting. Answers could point out why this is happening or how to futz with the syntax highlighter. – Matt Feb 11 '16 at 04:43
  • iPython (now Jupyter) notebooks run with a Tornado (a Python framework) web-server. The HTML and CSS are doing the display stuff, but the dynamic syntax highlighting is all ran by Javascript. – OneCricketeer Feb 11 '16 at 04:55

2 Answers2

49

This is because the indentation is screwed up. For consistency the codemirror parser will make a red line if it's not indented 4 spaces (or if it's indented with tabs, depending on codemirror version). The parser has some edge case that indeed highlight only a few of theses lines in red, I won't go into details, but if you indent 4 spaces it will work.

You can either:

  • select the block of code and press tab
  • use alt-click'n'drag vertically to place multiple cursors in front of your code, and press space enough time to make the correct indent 4 space.

Setting the indent to 2 is possible, but complex and not recommended. 4 space is the python norm.

Matt
  • 27,170
  • 6
  • 80
  • 74
  • I'm building off of notebooks that use the 2-space convention, so I ended up changing the indent via [this answer](http://stackoverflow.com/a/24615436/232638). – Matt Mar 08 '16 at 23:42
  • That's a bad thing to do. You better have to convert the notebook to use 4 tabs. Notebook files are json so easy to process. – Matt Mar 09 '16 at 17:39
2

This is the official solution from the Jupyter Notebook documentation:

  1. Open a Jupyter Notebook
  2. Select a Code Cell
  3. Open your browser's JavaScript console and run the following snippet:

    var cell = Jupyter.notebook.get_selected_cell();
    var config = cell.config;
    var patch = {
          CodeCell:{
            cm_config:{indentUnit:2}
          }
        }
    config.update(patch)
    
  4. Reload the Notebook page

This fix is permanent.

To reverse the change repeat the process running this snippet:

var cell = Jupyter.notebook.get_selected_cell();
var config = cell.config;
var patch = {
      CodeCell:{
        cm_config:{indentUnit: null} # only change here.
      }
    }
config.update(patch)