Warm tip: This article is reproduced from stackoverflow.com, please click
python jupyter-notebook

Stop Jupyter auto-indenting new lines a large, non-integer amount of tabs?

发布于 2020-03-27 10:30:42

Running Jupyter (core:4.4.0, notebooks:5.7.8) python3 notebooks on OSX.

The notebook seems to get easily confused about how to auto-indent new lines. Specifically, my more complex cells that have nested indentations for defs, ifs, whiles (etc) cause Jupyter to use a weird 4.5-tab auto-indent that doesn't match any of my indentation levels and leads to lots of wasted keypresses to fix the indent on EVERY. SINGLE. NEW. LINE.

To be clear, I'm not asking how to change the default tab spacing, I'm asking how to stop jupyter autoindenting to something insane when I hit 'return' to make a new line.

One potential source of error is my use of f-strings; Jupyter sometimes screws up the syntax highlighting for hashes and nested quotes eg. print(f"Output for #{myNum} | {myDict['namedItem']}").

Any tips on what might cause the issue would welcome.

Questioner
Mark_Anderson
Viewed
23
Mark_Anderson 2020-01-22 03:31

Answer: Yes it is f-string literals. Nested quotations in an f-string will screw up the indentation in cell, setting the new line default to start of the quote in the f-string.

eg.

print(f"Output for #{myNum} | {myDict['namedItem']}")
                                      # Newline starts here
                                      # and here
# Manual de-indent here for readibility.
x=5 # and manually force python code to an indent where it actually runs
                                      # Default newline is still here though  
                                      # And will stay here for the rest of the cell

f-strings generically break the CodeMirror syntax highlighter underlying jupyter notebooks, known since Jan 2017. There have been some minor fixes to make it break less badly, but the problem is not fixed -- see recent Git issues

EDIT: Since Jan 2020 jupyter 6.0.2, this should be fixed via an update to CodeMirror 5.48.4.