介绍
快速开始
简单使用
var editor = ace.edit("editor");
设置主题和语言模式
要更改主题,请为编辑器配置要使用的主题路径。主题文件将按需加载:editor.setTheme("ace/theme/twilight");
默认情况下,编辑器为纯文本模式。但是,所有其他语言模式都可以作为单独的模块使用。语言模式也将按需加载:editor.session.setMode("ace/mode/javascript");
编辑器状态
Ace将所有编辑器状态(选择,滚动位置等)保留在editor.session中, 这对于制作可切换式编辑器非常有用:var EditSession = require("ace/edit_session").EditSession
var js = new EditSession("some js code")
var css = new EditSession(["some", "css", "code here"])
// 要将文档加载到编辑器中,只需这样调用
editor.setSession(js)
在项目中配置Ace// 将代码模式配置到ace选项
ace.edit(element, {
mode: "ace/mode/javascript",
selectionStyle: "text"
})
// 使用setOptions方法一次设置多个选项
editor.setOptions({
autoScrollEditorIntoView: true,
copyWithEmptySelection: true,
});
// 单独设置setOptions方法
editor.setOption("mergeUndoDeltas", "always");
// 一些选项也直接设置,例如:
editor.setTheme(...)
// 获取选项设置值
editor.getOption("optionName");
// 核心Ace组件包括(editor, session, renderer, mouseHandler)
setOption(optionName, optionValue)
setOptions({
optionName : optionValue
})
getOption(optionName)
getOptions()
设置和获取内容:`editor.setValue("the new text here"); // 或 session.setValue
editor.getValue(); // 或 session.getValue
获取选定的文本:editor.session.getTextRange(editor.getSelectionRange());
在光标处插入:editor.insert("Something cool");
获取当前光标所在的行和列:editor.selection.getCursor();
转到某一行:editor.gotoLine(lineNumber);
获取总行数:editor.session.getLength();
设置默认标签大小:editor.getSession().setTabSize(4);
使用软标签:editor.getSession().setUseSoftTabs(true);
设置字体大小:document.getElementById('editor').style.fontSize='12px';
切换自动换行:editor.getSession().setUseWrapMode(true);
设置行高亮显示:editor.setHighlightActiveLine(false);
设置打印边距可见性:editor.setShowPrintMargin(false);
设置编辑器为只读:editor.setReadOnly(true); // false为可编辑
窗口自适应
编辑器仅在resize事件触发时时调整自身大小。要想以其他方式调整编辑器div的大小,并且需要调整编辑器大小,请使用以下命令:editor.resize()
在代码中搜索
主要的ACE编辑器搜索功能在 search.js.中定义。以下选项可用于搜索参数:needle: 要查找的字符串或正则表达式
backwards: 是否从当前光标所在的位置向后搜索。默认为“false”
wrap: 当搜索到达结尾时,是否将搜索返回到开头。默认为“false
caseSensitive: 搜索是否应该区分大小写。默认为“false”
wholeWord: 搜索是否只匹配整个单词。默认为“false”
range: 搜索匹配范围,要搜索整个文档则设置为空
regExp: 搜索是否为正则表达式。默认为“false”
start: 开始搜索的起始范围或光标位置
skipCurrent: 是否在搜索中包含当前行。默认为“false”
下面是一个如何在编辑器对象上设置搜索的示例:editor.find('needle',{
backwards: false,
wrap: false,
caseSensitive: false,
wholeWord: false,
regExp: false
});
editor.findNext();
editor.findPrevious();
这是执行替换的方法:editor.find('foo');
editor.replace('bar');
这是全部替换:editor.replaceAll('bar');
editor.replaceAll使用前需要先调用editor.find('needle', ...)
事件监听
onchange:editor.getSession().on('change', callback);
selection变化:editor.getSession().selection.on('changeSelection', callback);
cursor变化:editor.getSession().selection.on('changeCursor', callback);
添加新的命令和绑定
将指定键绑定并分配给自定义功能:editor.commands.addCommand({
name: 'myCommand',
bindKey: {win: 'Ctrl-M', mac: 'Command-M'},
exec: function(editor) {
//...
}
});
主要配置项
- editor选项
- renderer选项
- mouseHandler选项
- session选项
- 扩展选项