A few days ago, I posted two translations on our official account, giving a basic introduction to Jupyter Notebook. Although it is fairly basic, and the second article is not a high reading volume, I think it is useful for others who do not know much about Notebook.
- Jupyter Notebook Quick Start (1)
- Jupyter Notebook Quick Start (2)
Today, I want to share a trick for configuring a Notebook that supports the use of Sublime Text shortcuts in Notebook. Since I use ST3 a lot, I’m used to some of its shortcuts, and if I could use them in Notebook programming, it would make Notebook writing a lot more efficient.
After some searching, I came up with the following steps and code to do what we wanted.
Step 1: Find the address of the custom.js file
Under MacOS and Linux system, the file is the default address ~ /. Jupyter/custom/custom. Js. If you are configuring this file for the first time, it probably does not exist at this address. Alternatively, you can run the following code in the Notebook to determine the path and contents of Custom.js:
Paths import jupyter_config_DIR jupyter_config_dir = jupyter_config_dir() Import os.path custom_js_path = os.path.join(jupyter_dir, 'custom', 'custom.js') print(custom_js_path) # If os.path.isfile(custom_js_path): with open(custom_js_path) as f: print(f.read()) else: print("You don't have a custom.js file")Copy the code
If custom.js is not in the target path, create the file first. To make sure the custom.js file does its job, add a line of code at the beginning of the file:
alert("hello world from custom.js")
Copy the code
Then restart the Jupyter Notebook. If all goes well, you should see a dialog box pop up after you restart your browser.
Add code for configuring shortcut keys
Next, you can comment out the js code above. Then add the following code to the custom.js file:
require(["codemirror/keymap/sublime", "notebook/js/cell", "base/js/namespace"], function(sublime_keymap, cell, IPython) { // setTimeout(function(){ // uncomment line to fake race-condition cell.Cell.options_default.cm_config.keyMap = 'sublime'; var cells = IPython.notebook.get_cells(); for(var cl=0; cl< cells.length ; cl++){ cells[cl].code_mirror.setOption('keyMap', 'sublime'); } // }, 1000)// uncomment line to fake race condition } );Copy the code
Then restart the Jupyter Notebook again.
Enter some text and code, then try pressing Ctrl + D or Ctrl + L. With luck, you’ll be able to use the Sublime Text shortcut in Notebook!
instructions
This feature is made possible by the use of CodeMirror, a javascript-based text editor component, in newer versions of Jupyter Notebook. In addition to ST, CodeMirror also supports Vim and Emacs key bindings.
If you’re interested, try turning on the Vim or Emacs binding.