You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:调整Ace Editor toggleCommentLines函数的注释字符位置

解决Ace Editor中Pick/BASIC注释符需放在行首的问题

要让Ace Editor的注释功能把*直接放在行首而非制表符后面,你可以通过重写注释相关方法来实现自定义逻辑,下面是两种可行方案:

方案1:直接重写编辑器的toggleCommentLines方法

针对已创建的编辑器实例,替换默认的注释切换逻辑,强制将注释符加到行首:

// 获取你的Ace编辑器实例
const editor = ace.edit("editor");

// 重写注释切换方法
editor.toggleCommentLines = function() {
    const session = this.getSession();
    const selectionRange = this.getSelectionRange();
    const startRow = selectionRange.start.row;
    const endRow = selectionRange.end.row;

    // 遍历选中的每一行
    for (let row = startRow; row <= endRow; row++) {
        const lineContent = session.getLine(row);
        // 判断当前行是否已用*注释(行首就是*)
        if (/^\*/.test(lineContent)) {
            // 移除行首的*及后续空格(匹配示例里的注释格式)
            const removeLength = lineContent.startsWith("* ") ? 2 : 1;
            session.replace(new ace.Range(row, 0, row, removeLength), '');
        } else {
            // 在行首插入*和空格
            session.replace(new ace.Range(row, 0, row, 0), '* ');
        }
    }
};

方案2:在自定义Pick/BASIC语法mode中重写toggleComment

如果你是基于Ace的自定义mode开发语法高亮,直接在mode文件里重写注释逻辑,更贴合语法上下文:

define(function(require, exports, module) {
    const oop = require("ace/lib/oop");
    const TextMode = require("ace/mode/text").Mode;
    const PickBasicHighlightRules = require("./pick_basic_highlight_rules").PickBasicHighlightRules;

    const Mode = function() {
        this.HighlightRules = PickBasicHighlightRules;
        this.lineCommentStart = "*"; // 保留原有配置,仅重写注释逻辑
    };
    oop.inherits(Mode, TextMode);

    // 重写mode的注释切换方法
    Mode.prototype.toggleComment = function(session, startRow, endRow) {
        for (let row = startRow; row <= endRow; row++) {
            const line = session.getLine(row);
            if (/^\*/.test(line)) {
                // 移除行首的注释符
                const trimLength = line.startsWith("* ") ? 2 : 1;
                session.replace(new ace.Range(row, 0, row, trimLength), '');
            } else {
                // 行首插入注释符
                session.replace(new ace.Range(row, 0, row, 0), "* ");
            }
        }
    };

    exports.Mode = Mode;
});

两种方案都会让注释符严格出现在行首,完全匹配你给出的有效注释格式。

内容的提问来源于stack exchange,提问作者Möbius Dickus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 12:24:19