author: Chenzhu-Xie name: Library/xczphysics/CONFIG/Nearest_Pattern/Unwrap tags: meta/library

pageDecoration.prefix: "๐Ÿ“ฆ "

Unwrap and Copy Nearest Pattern

Page Ver

-- ่พ…ๅŠฉๅ‡ฝๆ•ฐ๏ผšๆๅ–ไธๅŒๆจกๅผไธ‹็š„โ€œๆ ธโ€ (Content)
local function extractCore(name, text)
  if name == "Wiki Link" then
    -- ๅŒน้… [wiki](wiki) ๆˆ– [wiki|alias](wiki|alias)๏ผŒๅ– wiki
    local core = text:match("%[%[([^%]]+)%]%]")
    if core and core:find("|") then core = core:match("^([^|]+)|") end
    return core
  elseif name == "Fields" then
    return text:match("%[([^:]+:[^%]]+)%]") -- ๅ– [key:value] ไธญ็š„ key:value
  elseif name == "Image" then
    return text:match("!%[^%](^%)-%]%(([^)]+)%)") -- ๅ– src ๆ–‡ๅญ—
  elseif name == "Markdown Link" then
    return text:match("%[^%](^%)+%]%(([^)]+)%)") -- ๅ– [text](url) ไธญ็š„ url
  elseif name == "Color Func" then
    return text:match("%([\"\']([^\"\']+)[\"\']%)") -- ๅ– ${Color("value")} ไธญ็š„ value
  elseif name == "Bold" then
    return text:match("%*%*([^\n%*]+)%*%*")
  elseif name == "Italic" then
    return text:match("_([^\n_]+)_")
  elseif name == "Sup" then
    return text:match("%^([^ \n%^]+)%^")
  elseif name == "Strikethrough" then
    return text:match("~~([^\n]+)~~")
  elseif name == "Sub" then
    return text:match("~([^ \n~]+)~")
  elseif name == "Marker" then
    return text:match("==([^\n]+)==")
  elseif name == "Inline Code" then
    return text:match("`([^\n`]+)`")
  elseif name == "Lua Block" or name == "Script Block" then
    return text:match("```%a+\n?(.*)```")
  elseif name == "Header" then
    return text:match("#+ (.*)")
  elseif name == "Tag" then
    return text:sub(2) -- ๅŽปๆމๅ‰้ข็š„ #
  end
  return text -- ้ป˜่ฎค่ฟ”ๅ›žๅŽŸๆ ท
end

command.define{
  name = "Cursor: Unwrap Nearest Pattern",
  description = "Remove the format of the nearest pattern",
  key = "Alt-w",
  run = function()
    local match = findNearestInlinePattern()
    if not match then
      editor.flashNotification("No pattern matched.")
      return
    end

    local core = extractCore(match.name, match.text)
    if not core then
      editor.flashNotification("Failed to extract core from " .. match.name)
      return
    end

    editor.copyToClipboard(core)
    editor.replaceRange(match.start - 1, match.stop, core)

    editor.flashNotification(match.name .. ": Unwrapped โœ…")
    if not match.name:find"Block" then 
      editor.flashNotification(core)
    end
  end
}