Tips: Copy inline code text with one shortcut key

There is a FR thread: Simple way to copy inline code - Feature requests - Obsidian Forum

And I want to share a simple way to copy inline code text:
48f7b017-9a99-4b75-8c21-9bdbfe6c7984

How to achive this

Just paste the code below into a note and use Templater plugin to call it.

And you can register a hotkey for this command:
image

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}]]`
  
  // 对同名一级标题使用的时候
  if (selectedHeading == linkAlias) headingReferenceLink = `[[${filename}|${linkAlias}]]`

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

await linkHeading();
%>

Bonus feature

You can also use the same key to copy the link for a heading:
fd255803-e81d-4f23-9d68-5be555c1a471

The link would be [[Note#Heading|Heading]] - which is shorter with using heading as display text

1 Like