如何在给定文件扩展名的情况下自动为 Ace Editor 选择“模式”

问题描述 投票:0回答:3

我正在开发一个使用 java/scala 后端的项目(准确地说,是 Lift,尽管这不应该影响这个问题),作为前端的一部分,我们使用 Ace Editor。我已经用谷歌搜索了一段时间,但尚未找到这个问题的答案:

给定文件扩展名(例如

js
c
cpp
h
java
rb
等),我如何自动为适当的语言选择 Ace“模式”?

我希望避免手动创建地图,la

js -> javascript, c -> c_cpp, java -> java
。有可用的 java/scala 库吗?或者更好的是,Ace 是否以某种方式内置了此功能?

javascript syntax-highlighting ace-editor
3个回答
40
投票

Ace 现在提供了 modelist 扩展来执行此操作。

var modelist = ace.require("ace/ext/modelist")
var filePath = "blahblah/weee/some.js"
var mode = modelist.getModeForPath(filePath).mode
editor.session.setMode(mode) // mode now contains "ace/mode/javascript".

请注意,如果您使用 ace 的 prebuilt 版本,您需要在页面中包含

ace.js
ext-modelist.js
文件。
使用源版本,您需要将
ace.require
替换为
require
,require.js 将自动加载所有依赖项。

请参阅 https://github.com/ajaxorg/ace/blob/master/demo/modelist.htmlhttps://github.com/ajaxorg/ace-builds/blob/master/demo/modelist.html 有关如何使用它的示例


0
投票

这是我解决问题的方法。这是我在 Django 项目中使用的更新版本。

    <script src="{% static 'ace/src-noconflict/ace.js' %}" type="text/javascript" charset="utf-8"></script>
<script src="{% static 'ace/src-noconflict/ext-modelist.js' %}"></script>
<script src="{% static 'ace/src-noconflict/ext-language_tools.js' %}"></script>
<script>
    var modelist = ace.require("ace/ext/modelist");
    var editor = ace.edit("editor");
    editor.renderer.setScrollMargin(40, 150)
    document.getElementById('editor').style.fontSize = '15px';
    editor.setTheme("ace/theme/dracula");

    var full_path = "{{ file.directory_path }}";
    document.getElementById("demo").innerHTML = full_path
    var mode = modelist.getModeForPath(full_path);//mode
    console.log(mode);
    editor.session.setMode(mode.mode);
    //Ace editor autocompletion
    editor.setOptions({
        enableBasicAutocompletion: true,
        enableSnippets: true,
        enableLiveAutocompletion: true
    });

</script>

0
投票

关键是editor.session.setMode(mode.mode);

<!-- ace editor -->
<script src="/ace/v1_4_11/ace.js"></script>
<script src="/ace/v1_4_11/ext-modelist.js"></script>
<script src="/ace/v1_4_11/ext-language_tools.js"></script>

let editor = null;      // reference to the Ace editor
let aceModeList = null; // used by the Ace editor

function initializeAceEditor() {
    aceModeList = ace.require("ace/ext/modelist");
    editor = ace.edit("aceEditorDiv");
}

// load the file and set the file-extension specific mode
let mode = aceModeList.getModeForPath(fileName); // detects for example .xml - or any other file extebsion
console.log(`Ace: selected mode = ${mode.mode}`);
try {
    editor.session.setMode(mode.mode);
} catch (e) {
    console.log("Ace: No specific mode available for file extension");
}

editor.getSession().setValue(Base64.decode(fileContentB64));

无需在浏览器中预加载特定模式 *.js 文件,例如“mode-xml.js”。根据需要自动加载相应的模式文件。

© www.soinside.com 2019 - 2024. All rights reserved.