How to choose Jupyter syntax highlighting language

Viewed 924

I regularly read and edit .cu files (cuda) in Jupyter. Is there a way to get Jupyter to use C++ syntax highlighting for .cu files? (They are basically C++ files)

2 Answers

You can create a JupyterLab extension (guide, tutorial), there are some examples out there like jupyterlab_robotmode (this and this part) and this comment. You will want to reuse CodeMirror's clike mode, probably incorporating these c++ bits. It would roughly look like this:

import { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application';
import { ICodeMirror } from '@jupyterlab/codemirror';


const extension: JupyterFrontEndPlugin<void> = {
  id: 'jupyterlab-cuda-mode',
  autoStart: true,
  requires: [ICodeMirror],
  activate: (app: JupyterFrontEnd, codeMirrorToken: ICodeMirror) => {
    const cm = codeMirrorToken.CodeMirror as any;
    cm.defineMIME(
      "text/x-cuda",
      {
        name: "clike",
        // add more configuration below
        namespaceSeparator: "::",
        modeProps: {fold: ["brace", "include"]}
      }
    );
    // add more keywords
    cm.registerHelper('hintWords', 'text/x-cuda', {'__global__': true});
    cm.modeInfo.push({
      ext: ["cu"],
      mime: "text/x-cuda",
      mode: "clike",
      name: "cuda"
    });
  }
};

export default extension;

Now if you also want to have nice icon in the lanucher you would need to register it with the DocumentRegistry like the builtin file types are here

Of note, JupyterLab 4.0 and Jupyter Notebook 7.0 will use CodeMirror 6 which has a reworked parser. The old modes will still be supported via a legacy shim, but if you are thinking about developing a new mode, you might want to target lazer parser from CodeMirror 6.

An easy way without any extension can be using Markdown in Jupyter Notebook and Markdown Syntax Highlighting. You can use it for most of the languages but a drawback of this, you cannot see highlighting while you are editing code, just you can see after run. If your purpose is to see highlighted code between other blocks then it is useful. An example usage:

```c++

// your code goes here

```

Then, run markdown block.

Related