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

如何限制Monaco Editor的最大行数为100?是否支持限制最大单词数?

限制Monaco Editor的最大行数与单词数

一、限制最大行数(100行)

你提到的lineNumber属性仅用于控制行号的显示逻辑,无法限制编辑器的实际行数。要实现行数限制,需要监听编辑器内容变化事件,实时检查行数并截断超出部分:

const editor = monaco.editor.create(document.getElementById('container'), {
  value: '',
  language: 'javascript',
  scrollBeyondLastLine: false // 禁用超出最后一行的滚动,增强限制感
});

// 监听内容变化
editor.onDidChangeModelContent(() => {
  const model = editor.getModel();
  const currentLineCount = model.getLineCount();
  
  if (currentLineCount > 100) {
    // 获取前100行的完整内容
    const truncatedContent = model.getValueInRange({
      startLineNumber: 1,
      startColumn: 1,
      endLineNumber: 100,
      endColumn: model.getLineLength(100) + 1
    });
    
    // 替换内容,避免触发无限循环
    editor.executeEdits('', [{
      range: model.getFullModelRange(),
      text: truncatedContent
    }]);
  }
});

scrollBeyondLastLine: false可以让编辑器无法滚动到100行之外,进一步强化行数限制的体验。

二、限制最大单词数

Monaco Editor没有内置的单词数限制配置,但同样可以通过内容监听实现。核心是自定义单词的判定逻辑,实时计算单词数量并截断:

const MAX_ALLOWED_WORDS = 500; // 自定义最大单词数

editor.onDidChangeModelContent(() => {
  const model = editor.getModel();
  const fullContent = model.getValue();
  
  // 简单的单词分割逻辑:按非单词字符分割,过滤空字符串
  const wordList = fullContent.trim().split(/\W+/).filter(word => word.length > 0);
  
  if (wordList.length > MAX_ALLOWED_WORDS) {
    let currentWordCount = 0;
    let newContent = '';
    const lines = fullContent.split('\n');
    
    // 逐行处理,避免截断到单词中间
    for (const line of lines) {
      const lineWords = line.trim().split(/\W+/).filter(word => word.length > 0);
      
      if (currentWordCount + lineWords.length <= MAX_ALLOWED_WORDS) {
        newContent += line + '\n';
        currentWordCount += lineWords.length;
      } else {
        const remainingWords = MAX_ALLOWED_WORDS - currentWordCount;
        const lineSegments = line.split(/(\W+)/); // 保留分隔符,避免破坏格式
        let truncatedLine = '';
        let wordCounter = 0;
        
        for (const segment of lineSegments) {
          if (/^\w+$/.test(segment)) {
            if (wordCounter < remainingWords) {
              truncatedLine += segment;
              wordCounter++;
            } else {
              break;
            }
          } else {
            if (wordCounter < remainingWords) {
              truncatedLine += segment;
            } else {
              break;
            }
          }
        }
        
        newContent += truncatedLine;
        break;
      }
    }
    
    // 移除末尾多余的换行符
    newContent = newContent.trimEnd();
    
    // 更新编辑器内容
    editor.executeEdits('', [{
      range: model.getFullModelRange(),
      text: newContent
    }]);
  }
});

注意:上述单词分割逻辑适用于英文场景,如果需要支持中文或其他语言,需要替换为对应的分词逻辑(比如使用中文分词库)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:22:27