Generate Link @ Cursor Position

Update: When the cursor is located inside a header, produce the format [[pageName#headerName]] rather than [[pageName@pos]].

command.define {
  name = "Cursor: Copy Reference",
  key = "Shift-Alt-c",
  run = function()
    local currentLine = editor.getCurrentLine().textWithCursor:gsub("|%^|", "")
    local pageName = editor.getCurrentPage()
    local pos = editor.getCursor()
    local headerMarks, headerName = string.match(currentLine, "^(#+) +(.+)$")
    -- editor.flashNotification(headerMarks .. headerName)
    local ref
    if headerMarks and headerName and headerName:match("%S") then
      headerName = headerName:match("^%s*(.+)")
      ref = string.format("[[%s#%s]]", pageName, headerName)
      editor.flashNotification("Copied header reference: " .. ref, "info")
    else
      ref = string.format("[[%s@%d]]", pageName, pos)
      editor.flashNotification("Copied cursor reference: " .. ref, "info")
    end

    editor.copyToClipboard(ref)
  end
}

Borrowed some tech editor.getCurrentLine().textWithCursor:gsub("|%^|", "") (see editor) from Copy the nearest Format around Cursor - #2 by ChenZhu-Xie