首页 > 解决方案 > Ace 编辑器,toUpperCase 函数有效,但 toggleCommentLines 无效

问题描述

给定一个带有 ace 编辑器块的网页(包含一些代码行)。在 pageLoad 上,我想自动大写并注释第 1 到 2 行。

我像这样简单地实例化 ace 编辑器:

let editor = ace.edit(editorElement); // editorElement is an html element containing some code lines
editor.setOptions({
    maxLines: Infinity,
});
editor.getSession().setMode("ace/mode/python");

这是在 pageLoad 之后执行的代码:

require('ace-builds');
require('ace-builds/webpack-resolver'); // my project is managed by symfony 5 and webpack encore

let Range = require('ace-builds').Range;
editor.getSelection().setRange(new Range(0,0,2,0));

editor.toggleCommentLines(); // does nothing...why ?
editor.toUpperCase(); // its work !
// editor.clearSelection();

结果是:

在此处输入图像描述

第 1 行和第 2 行按预期使用大写,但未注释行,我不明白为什么......

我不会“只是”添加一个 '#' 字符,因为生成的 ace 编辑器的模式可能会改变。例如,模式可能是 'ace/mode/sql',并且 sql 中的注释不要使用 '#' 字符

谢谢你的帮助 :)

标签: javascriptace-editor

解决方案


在这里解决:)

设置模式需要一段时间,当我调用时它没有加载 editor.toggleCommentLines();。下面的代码适用于我:

editor.session.setMode("ace/mode/python", function() {
    editor.toggleCommentLines();
});

感谢ace git repo上的@nightwing :)


推荐阅读