What is the CodeMirror

CodeMirror is a text editor implemented through JavaScript. Designed for editing code, with extensive language patterns and more advanced plug-in capabilities.

A rich programming API and CSS theme system can be used to customize CodeMirror to make it more suitable for your application and extend new features.

Use CodeMirror

Let’s start with the next basic example, showing a code editor.

First we create an index.html and install CodeMirror into the project either via NPM or directly, using NPM setup here.

npm install --save codemirror
Copy the code

Once installed, introduce it into the page, and the following code will implement a basic code editor.

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="./node_modules/codemirror/lib//codemirror.css">
    <script src="./node_modules/codemirror/lib//codemirror.js"></script>
</head>

<body>
    <textarea id="root"></textarea>
    <script>
        var editor = CodeMirror.fromTextArea(document.getElementById('root'), {
            lineNumbers: true.// Display the line number
        });
    </script>
</body>

</html>
Copy the code

Support SQL

Our goal is to implement a code editor that supports the SQL experience, so let’s configure SQL.

The introduction of Mode

As mentioned above, CodeMirror supports a very large number of language modes. To make it recognize and highlight SQL, you need to introduce SQL modes.

<! SQL > select * from 'SQL';
<script src="./node_modules/codemirror/mode/sql/sql.js"></script>
Copy the code

So here we go in the editor and we say SELECT * FROM TABLE; You can see that the code editor already highlights the correct keywords.

Next, let’s improve the code editor experience with support for parenthesis matching, auto-completion, and so on.

Parentheses matching

<! -- Parenthesis matching -->
<script src="./node_modules/codemirror/addon/edit/matchbrackets.js"></script>
Copy the code

After introducing the corresponding plug-in, add matchBrackets: True to the incoming configuration item to enable bracket matching.

Automatic completion

Introduce intelligent prompt related plug-ins.

<! -- Auto complete -->
<link rel="stylesheet" href="./node_modules/codemirror/addon/hint/show-hint.css">
<script src="./node_modules/codemirror/addon/hint/show-hint.js"></script>
<script src="./node_modules/codemirror/addon/hint/sql-hint.js"></script>
Copy the code

/** * Ignore automatic prompt token */
const ignore = [' '.The '#'.'! '.The '-'.'='.The '@'.'$'.The '%'.'&'.'+'.'; '.'('.') '.The '*'];
const ignoreToken = (text) = > {
  if (text && text[0]) {
    for (const pre in ignore) {
      if (ignore[pre] === text[0]) {
        return true; }}}else {
    return true;
  }
  return false;
};

editor.on("change".function (editor, change) {
  if (change.origin == "+input") {
    var text = change.text;
    / / no prompt
    if(! ignoreToken(text))setTimeout(function () { 
        editor.execCommand("autocomplete");
      }, 20); }});Copy the code

The complete code is shown below

<! DOCTYPEhtml>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="./node_modules/codemirror/lib//codemirror.css">
    <script src="./node_modules/codemirror/lib//codemirror.js"></script>
    <! SQL > select * from 'SQL';
    <script src="./node_modules/codemirror/mode/sql/sql.js"></script>
    <! -- Parenthesis matching -->
    <script src="./node_modules/codemirror/addon/edit/matchbrackets.js"></script>
    <! -- Auto complete -->
    <link rel="stylesheet" href="./node_modules/codemirror/addon/hint/show-hint.css">
    <script src="./node_modules/codemirror/addon/hint/show-hint.js"></script>
    <script src="./node_modules/codemirror/addon/hint/sql-hint.js"></script>
</head>

<body>
    <textarea id="root"></textarea>
    <script>
    var editor = CodeMirror.fromTextArea(document.getElementById('root'), {
	mode: 'text/x-mysql'.lineNumbers: true.matchBrackets: true.hintOptions: {
            tables: {
		table1: ['name'.'score'.'birthDate'].table2: ['name'.'population'.'size']}}});/** * Ignore automatic prompt token */
	const ignore = [' '.The '#'.'! '.The '-'.'='.The '@'.'$'.The '%'.'&'.'+'.'; '.'('.') '.The '*'];
	const ignoreToken = (text) = > {
	if (text && text[0]) {
		for (const pre in ignore) {
			if (ignore[pre] === text[0]) {
				return true; }}}else {
		return true;
	}
            return false;
        };

	editor.on("change".function (editor, change) {// Any key triggers autocomplete
            if (change.origin == "+input") {
		var text = change.text;
		if(! ignoreToken(text))/ / no prompt
                    setTimeout(function () { editor.execCommand("autocomplete"); }, 20); }});</script>
</body>

</html>
Copy the code

Through the above configuration, when we enter SQL statements, we can see the automatic prompt code completion function, so if our general SQL input requirements are based on the relevant database information to prompt, the above default prompt information can not meet our needs. So let’s take a look at how to implement custom smart hints.

Custom hint

SQL hints provided by CodeMirror are sufficient for most scenarios, but the business needs to continue to improve the user experience. If only database, table, and field names are supported, the default SQL-hint can no longer meet the requirements. Therefore, we can replace the default SQL-hint or customize a hint to meet our requirements.

CodeMirror provides a static method to support custom Hint functionality.

CodeMirror.registerHelper('hint'.'custom'.function (editor, options) {
  return {
    list: ['custom-hint'].from: CodeMirror.Pos(cur.line, curr.start),
    to: CodeMirror.Pos(cur.line, curr.end),
  };
});
Copy the code

You can see that one of the simplest custom hints is complete. Based on this, we can obtain the current token based on the getValue method provided by the Editor, and then return the custom value we want through analysis to achieve better intelligent prompt effect.

reference

  • CodeMirror