How do I change the autoindent to 2 space in IPython notebook

Based on this question and the options found here:
In your custom.js file (location depends on your OS) put

IPython.Cell.options_default.cm_config.indentUnit = 2;

On my machine the file is located in ~/.ipython/profile_default/static/custom

Update:

In IPython 3 the plain call does not work any more, thus it is required to place the setting within an appropriate event handler. A possible solution could look like

define([
    'base/js/namespace',
    'base/js/events'
    ],
    function(IPython, events) {
        events.on("app_initialized.NotebookApp",
            function () {
                IPython.Cell.options_default.cm_config.indentUnit = 2;
            }
        );
    }
);

From the official documentation for CodeMirror Code Cells:

  1. Open an Ipython Notebook
  2. Create a Code Cell e.g. by pressing b
  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)
  1. Reload the notebook page in the browser e.g. by pressing F5

This will fix it permanently. I assume this works only on recent versions, not sure though!


AdamAL's answer is correct. It worked for me.

However it only changes the indentation in the Jupyter Notebook and leaves the indentation in the Jupyter Editor unaffected.

A more direct way to change the indentation is to directly edit the Jupyter config files in the .jupyter/nbconfig directory. This directory contains 2 files:

edit.json
notebook.json

The option you must set in either one is indentUnit. Here is the content of my Jupyter config files:

edit.json:

{
  "Editor": {
    "codemirror_options": {
      "indentUnit": 2,
      "vimMode": false, 
      "keyMap": "default"
    }
  }
}

notebook.json:

{
  "CodeCell": {
    "cm_config": {
      "indentUnit": 2
    }
  }
}

With this approach I've set the default indentation to 2 in both the Jupyter Notebook and the Jupyter Editor.


The official documentation has an example answering this specific question. This worked for me with IPython 4.

Summary: Paste the following into your browser's javascript console

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

The setting is persisted. You can roll back by exchanging : 2 for : null.