【tp脚本】在移动端编辑列表时插入软换行

功能:在编辑列表时插入软换行; 支持制表符或空格缩进。
效果:
Screenshot_Obsidian_演示 - Hisol_251115003303

使用方法

方法1: templater插件

  1. 启用templater插件
  2. 添加一个新模板,使用时插入模板。
<%* 
// 插入下面的 [[#脚本]]
%>

方法2: 使用note toolbar

  1. 启用note toolbar插件
  2. 添加任意工具栏项目
  3. 复制下面的脚本 ,然后在note toolbar中注册命令
  4. 可以在移动端工具栏添加这个命令。或者直接在note toolbar工具栏中点击使用

脚本

// 设置:如果是使用空格缩进的,可以设置换行之后追加多少个空格(仅列表后第一行)
const SPACE_INDENT = 2;

// 通过Note Toolbar执行:智能列表缩进软换行
const editor = app.workspace.activeEditor?.editor;

if (editor) {
    // 获取当前光标位置和当前行文本
    const cursor = editor.getCursor();
    const line = editor.getLine(cursor.line);
    
    // 提取前导空白字符和剩余内容
    const leadingWhitespace = line.match(/^\s*/)[0];
    const contentAfterWhitespace = line.substring(leadingWhitespace.length);
        
    // 检查是否是Markdown列表项
    const isList = /^(\+ |- |\* |\d+\. )/.test(contentAfterWhitespace);
    
    // 判断是否需要添加额外缩进
    let extraIndent = "";
    if (isList) {
        if (leadingWhitespace.includes('\t')) {
            // 如果包含制表符,添加一个制表符作为额外缩进
            extraIndent = '\t';
        } else {
            // 如果只有空格,添加指定数量的空格作为额外缩进
            extraIndent = ' '.repeat(SPACE_INDENT);
        }
    }
    
    // 插入换行、原有缩进和可能的额外缩进
    editor.replaceSelection("\n" + leadingWhitespace + extraIndent);
    
} else {
    new Notice('Note Toolbar Script: 无法获取编辑器对象');
}