Simple way to copy inline code

Just figured out a new way to fast copy inline code.

Preview:
f1a72194-2c9b-4c7e-8312-e8175f6190ee

Save this code into a md file and use it as Templater Plugin’s template:

<%*
// 2024.06.05 增加了对行内代码 inline code 的兼容

function getInlineCode(str, cursor){
    let start = str.lastIndexOf('`', cursor - 1);
    let end = str.indexOf('`', cursor);

    if (start === -1 || end === -1) {
        return null;
    }

    return str.substring(start + 1, end);
}

async function linkHeading() {
  const curView = app.workspace.activeLeaf.view;
  const curFile = curView.file;
  const curEditor = curView.editor;
  const curLine = curEditor.getLine(curEditor.getCursor().line);

  if (!curLine.startsWith('#') || !curLine.includes('# ')) {
    if (!curLine.includes("`")) {
      new Notice("当前光标处没有标题");
      return;
    } else {
      const curCh = curEditor.getCursor().ch;
      let inlineCode = getInlineCode(curLine, curCh)
      if (inlineCode) {
        navigator.clipboard.writeText(inlineCode)
        new Notice("Inline Code Copied!");
        return;
      }
    
    }
    
  }

  let selectedHeading = curLine.replace(/#+ /, "#")
  const filename = curFile.name;
  let linkAlias = selectedHeading.replace(/# ?/, "")

  let headingReferenceLink = `[[${filename}${selectedHeading}|${linkAlias}]]`

  navigator.clipboard.writeText(headingReferenceLink)
  new Notice("Heading Copied!");
}

await linkHeading();
%>

Then just call this TP with cursor inside Inline code.

I use Commander Plugin to add this TP command into Right Mouse Menu, but you can choose whatever way you like ; )

(Initially it’s used to easily copy Heading, just add the new function to be capable to copy inline code, too)

2 Likes