Use CodeMirror to build the IDE used by data scientists

1. Introduction to codemirror

CodeMirror is a general text editor implemented with JavaScript. It is specially used for code editing. It has built-in multiple development language modes and plug-ins, and supports code highlighting, automatic completion, search, shortcut keys, etc.

CodeMirror is an open source project licensed by MIT. At present, it has been used as a development tool for Firefox, Chrome and Safari, as well as an editor for other projects such as Light Table, Adobe Brackets and Bitbucket.

The core advantage of CodeMirror is that it is widely compatible with Firefox, Chrome, Safari, Internet Explorer/Edge and Opera browsers, and supports plug-ins. It can be flexibly customized according to its own needs. It is very convenient to develop an editor for online IDE.

2. How to use

The latest official version of CodeMirror is CodeMirror 6, which is still in the testing stage. You can choose to use a more mature and stable version CodeMirror 5 for development.

The WEB development framework can choose to use React, and a React application can be quickly created through create React app.

During model development, data scientists generally use the interactive programming method of Jupyter. In the process of model development, multiple code editing boxes are required to write code, so codemirror is simply encapsulated into a public React component for subsequent calls. First, execute yarn add codemirror, install the codemirror library, and then create a new one in the src folder/ components/CodeEditor.jsx file, the code content is as follows:

import { useRef, useEffect } from 'react';
import * as CodeMirror from 'codemirror';

export const CodeEditor = (props) => {
  const { onInputRead, options } = props
  const editorRef = useRef()

  useEffect(() => {
    let editor = CodeMirror(editorRef.current, options)
    editor.on('inputRead', (cm, event) => {
      onInputRead(editor, event)
    })
  }, [])

  return (
    <div ref={editorRef}>
    </div>
  );
}

The configuration of CodeMirror can be directly transmitted through the parent component, which is relatively flexible. You can add some listening events to the component to expose the event callback interface, which is controlled by the caller. The above code listens to the "inputRead" event, which can be used to intelligently complete the code. How to configure it will be described later.

On app JS uses the encapsulated codeeditor component.

import { CodeEditor } from './components/CodeEditor';
import 'codemirror/lib/codemirror';
import 'codemirror/keymap/sublime';
import "codemirror/mode/python/python";
import 'codemirror/addon/hint/show-hint';
import './App.css';

function App() {
  return (
    <div>
      <CodeEditor
        onInputRead={(editor, event) => editor.showHint()}
        options={{
          lineNumbers: true,
          theme: 'xq-light',
          keyMap: 'sublime',
          extraKeys: {},
          mode: 'python',
          hintOptions: {
            completeSingle: false,
          }
        }}
      />
    </div>
  );
}

export default App;

Configuration Description:

lineNumbers: whether to display line numbers on the left side of the editor.

Theme: configure the theme of the editor. There are built-in optional themes. You can view the css list in the / codemirror/theme directory. It supports more than 60 themes. You need to import the corresponding css files before use.

keymap: configure the shortcut keys to be used, support sublime, vim and emacs, and import the corresponding js file before use. You can also customize shortcut keys through extraKeys.

Mode: configure the mode to be used, which is related to the language, such as highlighting, formatting, annotation, etc. There are more than 100 built-in modes. You can view the supported modes through the / codemirror/mode directory. CodeMirror provides a function to obtain mode through the suffix of the file name.

import * as codemirror from 'codemirror';
const meta = codemirror.findModeByFileName(this.path);
const mode = meta ? meta.mode : '';

hintOptions: automatic prompt configuration. When a word is entered, a completion prompt will be given automatically. Show hint. Is required JS plug-in, and show hint needs to be introduced CSS file. Set the inputRead event callback function, using editor Showhint() pops up an option prompt box. The built-in prompt of CodeMirror is to match the preset keywords, and the keyword list is stored in the corresponding "mode" file in the / codemirror/mode / directory. For example, the mode set in the above code is python, and the keyword is in / codemirror/mode / Python / python JS file:

var commonKeywords = ["as", "assert", "break", "class", "continue",
                        "def", "del", "elif", "else", "except", "finally",
                        "for", "from", "global", "if", "import",
                        "lambda", "pass", "raise", "return",
                        "try", "while", "with", "yield", "in"];
var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr",
                        "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod",
                        "enumerate", "eval", "filter", "float", "format", "frozenset",
                        "getattr", "globals", "hasattr", "hash", "help", "hex", "id",
                        "input", "int", "isinstance", "issubclass", "iter", "len",
                        "list", "locals", "map", "max", "memoryview", "min", "next",
                        "object", "oct", "open", "ord", "pow", "property", "range",
                        "repr", "reversed", "round", "set", "setattr", "slice",
                        "sorted", "staticmethod", "str", "sum", "super", "tuple",
                        "type", "vars", "zip", "__import__", "NotImplemented",
                        "Ellipsis", "__debug__"];
CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins));

There are limitations in using keyword matching to prompt, and the customized or referenced variables and functions in the code cannot be prompted for completion. To solve this problem, you can use lsp to push the prompt option from the back end. How to use lsp to complete the code will be introduced in the subsequent official account.

Completeingle: whether to automatically select completion when there is only one prompt option. The default is true. It is recommended to change it to false. Manually select the prompt item for completion.

On app Import related css files into css:

@import 'codemirror/lib/codemirror.css';
@import "codemirror/theme/xq-light.css";
@import 'codemirror/addon/hint/show-hint.css';

3. Effect view

The first step of the IDE code editor is completed. After executing yarn start, open the page in the browser and enter some python code to see the effect:

pleasantly surprised:
Want to start a better coding experience without independent configuration? You can apply to try the new generation cloud native AI development and production platform IDP
https://www.baihai.co/invitation

Keywords: Front-end Pycharm Algorithm Machine Learning AI

Added by keyur.delhi on Mon, 24 Jan 2022 12:50:48 +0200