My VS code settings

coding
tools
Author

Sam Vaughan

Published

May 5, 2023

I’ve been playing around with my VS code settings to make its integration with the IPython terminal a little better. I’ve never really liked Jupyter notebooks, so all of my coding involves me editing in a python script and sending code to an IPython terminal, or sometimes working in a Quarto notebook.

Whilst working with R in VSCode, I’ve really liked being able to send individual lines to the radian R console using cmd+enter and running the entire script using cmd+shift+s. It was actually a bit tricky to get the same behavious in VSCode with IPython: I’m documenting it here for posterity!

The following comes from a comment on this very helpful stackoverflow question and this Github gist. Using this Macro extension for VScode, I added the following to my settings.json:

    "macros.list": {
        "runInIPythonTerminal": [
            {"command": "workbench.action.terminal.sendSequence","args": { "text": "%run \"${file}\""}},
            {"command": "$delay","args": {"delay": 100}},
            {"command": "workbench.action.terminal.sendSequence","args": { "text": "\r" }},
            ],
    },

which makes a new macro to send %run {current_python_filename} to the terminal. I then map this to a new keybinding:


  {
    "key": "shift+cmd+s",
    "command": "macros.runInIPythonTerminal",
    "when": "editorTextFocus && !findInputFocussed && !jupyter.ownsSelection && !notebookEditorFocused && !replaceInputFocussed && editorLangId == 'python'"
  }

where the “when” section tells VSCode to only run this command under certain circumstances (i.e. when I’m in the text editor and working on a python file). I’ve also added this to run a single line:


  {
    "key": "cmd+enter",
    "command": "python.execSelectionInTerminal",
    "when": "editorTextFocus && !findInputFocussed && !jupyter.ownsSelection && !notebookEditorFocused && !replaceInputFocussed && editorLangId == 'python'"
  },

and unmapped the default shift+enter.

Note that this isn’t perfect- it doesn’t work for sending multiple lines to IPython at once. For example, pressing cmd+enter on first of the following lines

# | eval : false

# fmt: off
data = dict(
    a=1, 
    b=2, 
    c=3
    )

should be smart enough to send the entire snippet to IPython- it works very nicely in R with theradian shell- but instead it will only send data = dict( and leave you hanging. You’ll need to highlight the entire three lines, and then press cmd+enter for it to work.

It looks like there is a feature request open on Github, so perhaps it might be in the works at some point.