• 请不要在回答技术问题时复制粘贴 AI 生成的内容
wxaxiaoyao
V2EX  ›  程序员

codemirror TAB 缩进问题记录

  •  
  •   wxaxiaoyao · Jul 31, 2019 · 1671 views
    This topic created in 2500 days ago, the information mentioned may be changed or developed.

    codemirror 默认 TAB 键是支持缩进的, 但在没有选择文本时, 缩进是一个 Tab 键而不是 indexUnit 对应的空格数. 默认也不支持 Shift - Tab 往回缩进, 这个在排版文本是非常麻烦的. 为了解决这两个问题我们需要重新定义这两个快捷键的实现, 具体伪代码如下:

    { // 此对象为 codemirror 配置选项对象, 下面仅对选项的快捷键相关部分做说明
        extraKeys: {
            Tab: (cm) => {
                if (cm.somethingSelected()) {      // 存在文本选择
                    cm.indentSelection('add');    // 正向缩进文本
                } else {                    // 无文本选择  
                    //cm.indentLine(cm.getCursor().line, "add");  // 整行缩进 不符合预期
                    cm.replaceSelection(Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input");  // 光标处插入 indentUnit 个空格
                }   
            },  
            "Shift-Tab": (cm) => {              // 反向缩进   
                if (cm.somethingSelected()) {
                    cm.indentSelection('subtract');  // 反向缩进
                } else {
                    // cm.indentLine(cm.getCursor().line, "subtract");  // 直接缩进整行
                    const cursor = cm.getCursor();
                    cm.setCursor({line: cursor.line, ch: cursor.ch - 4});  // 光标回退 indexUnit 字符
                }   
                return ;
            },  
        }
    }
    

    原文链接 wxaxiaoyao.cn/article/53

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3124 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 53ms · UTC 13:36 · PVG 21:36 · LAX 06:36 · JFK 09:36
    ♥ Do have faith in what you're doing.