当前位置: 首页 > 工具软件 > ACE Editor > 使用案例 >

【实战】React 必会第三方插件 —— Ace editor 自定义语法提示

尉迟跃
2023-12-01


  • [【笔记】Ace editor]:(https://blog.csdn.net/qq_32682301/article/details/128801120)

一、基础设置

ace编辑器语法提示最基础设置如下:

{
    enableBasicAutocompletion: false, //boolean 或 completer 数组
    enableLiveAutocompletion: false, //boolean 或 completer 数组
}

completer,就是拥有一个 getCompletions(editor, session, pos, prefix, callback) 属性的 object,自定义语法提示可以通过 callback(null, tipsData) 回传

相关逻辑源码:https://github.com/ajaxorg/ace/blob/v1.1.4/lib/ace/ext/language_tools.js

如果 enableBasicAutocompletion 和 enableLiveAutocompletion 的值为 completer 数组,就会覆盖编辑器默认的 completers,不推荐使用

1.enableBasicAutocompletion

设置 enableBasicAutocompletion = true,就会在全局 commands 中增加Autocomplete.startCommand 命令(startCommand.bindKey = “Ctrl-Space|Ctrl-Shift-Space|Alt-Space”)。

2.enableLiveAutocompletion

设置enableLiveAutocompletion = true,就会在输入内容时,弹出语法提示框,但是逻辑代码中忽略了一些情况,如删除(vscode也存在此问题。。。)。所以如果交互要求变动就弹出提示的话,可以在editor绑定的onChange事件中触发命令:

editor.execCommand("startAutocomplete");

二、自定义语法提示

// name 显示的名称;value 插入的值;score 权重(数值越大,提示越靠前);meta 描述
let tipsData = [{meta: "table", caption: "table", value: "table", score: 100}]
let tipsCompleter = {
    getCompletions: (editor, session, pos, prefix, callback) => {
        callback(null, tipsData)
    }
}

1.方法一

editor.completers.push(tipsCompleter);

2.方法二

const langTools = ace.require("ace/ext/language_tools");
langTools.addCompleter(tipsCompleter);

3.方法三

和方法二原理一样:

ace.config.loadModule('ace/ext/language_tools', langTools => {
    langTools.addCompleter(tipsCompleter)
});
  • https://github.com/ajaxorg/ace/issues/4941

4.方法四

import { addCompleter } from 'ace-builds/src-noconflict/ext-language_tools';

addCompleter(tipsCompleter);
  • https://github.com/securingsincity/react-ace/issues/338#issuecomment-580086476

三、其他定制化

1.insertMatch

这个方法怎么用文档中并没有找到,在 github 的 issue 中见到几种用法,尝试后记录如下:

我的理解是用于快捷输入模板,例如 sql 输入 s* 插入 select * from table:

let tipsData = [ ...otherTipsData, { value: 's*', meta: "select 模板", insert: 'select * from table', completer: {
	insertMatch: (editor, data) => {
        editor.completer.insertMatch(data.insert)
        // 以下两种方式(姑且看做两种)虽然可插入,但是已输入部分不会覆盖
        // editor.forEachSelection(function() {
        //     editor.insert(data.insert);
        // })
        // 直接执行可也,效果同上(或许有不同,暂未发现)
        // editor.insert(data.insert);
        
        // 根据插入结尾关键字,自动提示表名
        editor.execCommand('startAutocomplete')
        // 若要对提示内容进行操作,下面即是
        // editor.completer.completions.filtered
	}
}]

tips: 以上代码搭配语法提示(addCompleter)使用

哈哈,思路打开后可以进行 模板选择 + 表名选择 等 的 连招


未完待续。。。欢迎留言一起学习探讨


  • https://github.com/securingsincity/react-ace/issues/338#issuecomment-940487234
  • https://stackoverflow.com/questions/27245959/values-and-captions-in-ace-editor-autocomplete

关键文件:

  • https://github.com/ajaxorg/ace/blob/v1.1.4/lib/ace/ext/language_tools.js

四、拓展学习

1.AceEditor

示例demo:https://securingsincity.github.io/react-ace/

在 react 中使用 AceEditor 需要引入以下两个依赖:

npm install react-ace ace-builds

yarn add react-ace ace-builds

截止2023.02.20,最新版本号为:

  • react-ace:10.1.0
  • ace-builds:1.15.2

代码仓库地址:

  • react-ace:https://github.com/securingsincity/react-ace
  • ace-builds:https://github.com/ajaxorg/ace

使用样例:

// 核心组件
import AceEditor from 'react-ace'
// 引入对应的语言
import 'ace-builds/src-noconflict/mode-javascript'
//以下import的是风格
import 'ace-builds/src-noconflict/theme-eclipse'
// 代码提示
import 'ace-builds/src-noconflict/ext-language_tools'
import 'ace-builds/webpack-resolver'
import './code.less'
 
const CodeView = () => {
  return (
	<AceEditor
      // name类似于id和key需要保持唯一性
      name='myCodeView'
      // 字体大小
      fontSize={16}
      style={{ width: '80%', height: '80%', minHeight: 80 }}
      mode='javascript'
	  theme='eclipse'
	 />
  )
}
 
export default CodeView

常用属性:

mode:编辑器的整体模式或样式,这里取值为 markdown,表明需要用这个编辑器来输入 markdown文本,这样编辑器就会进行相应的初始设置。
theme:编辑器主题,这里使用了 github这个主题。
wrapEnabled:当输入的一句文本比一行的长度要长时,是否允许换行。
tabSize:使用几个空格来表示表示一次 Tab按键。
fontSize:文本的字体大小
height:编辑器的高度,单位为 px。
width:编辑器的宽度,单位为 px。
debounceChangePeriod:多长时间对输入响应一次,单位为 ms,类似于节流。
onChange:文本框内容发生变化时的回调函数。
onScroll:文本框内容发生滚动时的回调函数。
name:编辑器的 id。
editorProps:当在文本框内输入内容时,是否需要滚动条进行响应的滚动定位。

全部属性:

PropDefaultTypeDescription
name‘ace-editor’StringUnique Id to be used for the editor
placeholdernullStringPlaceholder text to be displayed when editor is empty
mode‘’StringLanguage for parsing and code highlighting
theme‘’Stringtheme to use
value‘’Stringvalue you want to populate in the code highlighter
defaultValue‘’StringDefault value of the editor
height‘500px’StringCSS value for height
width‘500px’StringCSS value for width
classNameStringcustom className
fontSize12Numberpixel value for font-size
showGuttertrueBooleanshow gutter
showPrintMargintrueBooleanshow print margin
highlightActiveLinetrueBooleanhighlight active line
focusfalseBooleanwhether to focus
cursorStart1Numberthe location of the cursor
wrapEnabledfalseBooleanWrapping lines
readOnlyfalseBooleanmake the editor read only
minLinesNumberMinimum number of lines to be displayed
maxLinesNumberMaximum number of lines to be displayed
enableBasicAutocompletionfalseBooleanEnable basic autocompletion
enableLiveAutocompletionfalseBooleanEnable live autocompletion
enableSnippetsfalseBooleanEnable snippets
tabSize4NumbertabSize
debounceChangePeriodnullNumberA debounce delay period for the onChange event
onLoadFunctioncalled on editor load. The first argument is the instance of the editor
onBeforeLoadFunctioncalled before editor load. the first argument is an instance of ace
onChangeFunctionoccurs on document change it has 2 arguments the value and the event.
onCopyFunctiontriggered by editor copy event, and passes text as argument
onPasteFunctionTriggered by editor paste event, and passes text as argument
onSelectionChangeFunctiontriggered by editor selectionChange event, and passes a Selection as it’s first argument and the event as the second
onCursorChangeFunctiontriggered by editor changeCursor event, and passes a Selection as it’s first argument and the event as the second
onFocusFunctiontriggered by editor focus event
onBlurFunctiontriggered by editor blur event.It has two arguments event and editor
onInputFunctiontriggered by editor input event
onScrollFunctiontriggered by editor scroll event
onValidateFunctiontriggered, when annotations are changed
editorPropsObjectproperties to apply directly to the Ace editor instance
setOptionsObjectoptions to apply directly to the Ace editor instance
keyboardHandlerStringcorresponding to the keybinding mode to set (such as vim or emacs)
commandsArraynew commands to add to the editor
annotationsArrayannotations to show in the editor i.e. [{ row: 0, column: 2, type: 'error', text: 'Some error.'}], displayed in the gutter.(type:‘error’,‘info’,‘warning’)
markersArraymarkers to show in the editor, i.e. [{ startRow: 0, startCol: 2, endRow: 1, endCol: 20, className: 'error-marker', type: 'background' }]. Make sure to define the class (eg. “.error-marker”) and set position: absolute for it.
styleObjectcamelCased properties

不同文件中可以引入不同的语言支持包:

import 'brace/mode/javascript';//
import 'brace/mode/html';//
import 'brace/mode/java';//
import 'brace/mode/python';//
import 'brace/mode/lua';//
import 'brace/mode/xml';//
import 'brace/mode/ruby';//
import 'brace/mode/sass';
import 'brace/mode/markdown';//
import 'brace/mode/mysql';
import 'brace/mode/json';//
import 'brace/mode/css';//
import 'brace/mode/typescript';

2.其他代码编辑器

CodeMirror

  • 官网:https://codemirror.net/
  • github:https://github.com/codemirror/CodeMirror
  • 示例代码:https://uiwjs.github.io/react-codemirror/

Monaco

  • github:https://github.com/microsoft/monaco-editor

diff2html

  • 官网:https://diff2html.xyz/
  • gitbub:https://github.com/rtfpessoa/diff2html
 类似资料: