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

如何用jQuery在Monaco Editor中获取排除注释行的有效行号?

获取Monaco Editor中未注释行的序号(jQuery实现)

实现思路

要拿到排除注释后的行号,核心逻辑是从第1行遍历到光标所在行,逐个判断每行是否为注释行,统计非注释行的总数。这里用Monaco自带的语法分析能力判断注释,比单纯正则匹配更适配不同语言的注释规则。

代码实现

// 假设你的Monaco Editor实例已保存到editor变量中
function getUncommentedLineNumber() {
    const currentLine = editor.getPosition().lineNumber;
    let uncommentedCount = 0;

    // 遍历从第1行到当前行的所有行
    for (let i = 1; i <= currentLine; i++) {
        const lineContent = editor.getLineContent(i).trim();
        // 跳过空行,不需要的话可以删除这行判断
        if (!lineContent) {
            continue;
        }

        // 获取行首的语法token,判断是否为注释类型
        const token = editor.getTokenAtPosition({ lineNumber: i, column: 1 });
        const isComment = token?.type.includes('comment');

        if (!isComment) {
            uncommentedCount++;
        }
    }

    return uncommentedCount;
}

// 实时获取示例:用jQuery监听编辑器的光标变动事件
$(document).on('mousemove keyup', '.monaco-editor', function() {
    const targetLine = getUncommentedLineNumber();
    console.log('当前未注释行序号:', targetLine);
});

关键说明

  • editor.getTokenAtPosition():Monaco会返回对应位置的语法token,type字段会包含注释标识(比如JS里是comment.line.double-slash.js,Python里是comment.line.number-sign.python),通过判断是否包含comment就能准确识别注释行。
  • 空行处理:代码里默认跳过空行,如果需要把空行算入非注释行,直接删掉if (!lineContent) continue;即可。
  • 事件监听:用jQuery绑定鼠标移动和按键事件,实现光标变动时实时更新结果。

内容的提问来源于stack exchange,提问作者ani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 10:00:00