ABC - Accurate 🖇️ Bi-directional 🖱️ Cursor-level linking system

:linked_paperclips: Bi-directional Refs @ Cursor Level :computer_mouse: (Prototype)

Thanks to @zef’s space-lua API & JIT, I made made made it it it ! :star_struck:

~ 100% human-written & human-consumable codes:

function usrPrompt(hinText)
  local input = editor.prompt(hinText, "")
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "🔵" -- 🐳💧 ➖ 🗨
local suffixBlabel = "🟣" -- 🐈‍⬛🍆 ➕ 🗯
local F = " ➡️ " -- >> » 🔜 🢧
local B = " 🔙 " -- << « 🔙 🡄

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true) -- no Regex
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backrefStat(Flabel)
  return (tableBack(Flabel)).length
end

function backRefs(Flabel)
  -- local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}]]​^${_.thBlabel}^​]==])
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}]]​==${_.thBlabel}==​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "insert: Forthanchor + Backrefs",
  key = "Ctrl-,",
  run = function()
    local Flabel = usrPrompt('Enter: label (to be Referred)')
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|]]"
    local backrefStat = '${backrefStat("' .. Flabel .. '")}*~Σ~*'
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backrefStat .. B .. backRefs
    editor.insertAtPos(fullText, editor.getCursor(), true)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new[==[​[[${_.ref}]]​]==])
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "insert: Backanchor + Forthref",
  key = "Ctrl-.",
  run = function()
    local Flabel = usrPrompt('Jump to: label')
    if not Flabel then return end
    local aspiringPageBack = Flabel .. suffixBlabel
    local backAnchor = "[[" .. aspiringPageBack .. "||^|]]"
    -- local thBlabel = "^" .. (tableBack(Flabel)).length + 1 .. "^"
    local thBlabel = "==" .. (tableBack(Flabel)).length + 1 .. "=="
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backrefStat = '${backrefStat("' .. Flabel .. '")}*~Σ~*'
    local fullText = backAnchor .. thBlabel .. F .. forthRef .. backrefStat
    editor.insertAtPos(fullText, editor.getCursor(), true)
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        -- return tonumber(string.match(self.snippet, "%^([0-9]+)%^"))
        return tonumber(string.match(self.snippet, "==([0-9]+)=="))
      end
    end
  }
}

Ubiquitous: Variants of the code can be applied to every widget.
Singularity: Beyond making these limitations historical, backlink-precision has been elevated to its peak, shaping the future of bi-directional/spider-web info management.
Infrastructure: Considering integration into SB’s official DNA :dna: ?

2 Likes

I have no idea what I’m looking at…I might need a Phd to understand what is going on in this script

I even asked ChatGPT of what this script does, it tried to explain it me but I still didn’t understood anything. This is what it said in the end;

It’s like a DIY cross-reference system for SilverBullet, elegant, slightly deranged, but very effective. it’s a bit like building a grandfather clock out of chewing gum and mirrors.

1 Like

Bro, you’re really riding the latest wave XD

The issue arises due to the edgest version of edge.

@zef is standardizing everything, so (tableBack(Flabel)).length in the code above is no longer supported and must be replaced with #tableBack(Flabel).

I guess your ver is 2.2.1-ec9fcd1ced6dac6b6a5513497930747df28d6533
2.2.1-ec9fcd1ced6dac6b6a5513497930747df28d6533

previous mine is 2.2.1-7d9f8a41f9d6093eab85a28a783f02310ec4a2be
2.2.1-7d9f8a41f9d6093eab85a28a783f02310ec4a2be

new code below may work now :sparkling_heart:

function usrPrompt(hinText)
  local input = editor.prompt(hinText, "")
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "🔵" -- 🐳💧 ➖ 🗨
local suffixBlabel = "🟣" -- 🐈‍⬛🍆 ➕ 🗯
local F = " ➡️ " -- >> » 🔜 🢧
local B = " 🔙 " -- << « 🔙 🡄

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true) -- no Regex
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backrefStat(Flabel)
  -- return (tableBack(Flabel)).length
  return #tableBack(Flabel)
end

function backRefs(Flabel)
  -- local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}]]​^${_.thBlabel}^​]==])
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}]]​==${_.thBlabel}==​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "insert: Forthanchor + Backrefs",
  key = "Ctrl-,",
  run = function()
    local Flabel = usrPrompt('Enter: label (to be Referred)')
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|]]"
    local backrefStat = '${backrefStat("' .. Flabel .. '")}*~Σ~*'
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backrefStat .. B .. backRefs
    editor.insertAtPos(fullText, editor.getCursor(), true)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new[==[​[[${_.ref}]]​]==])
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "insert: Backanchor + Forthref",
  key = "Ctrl-.",
  run = function()
    local Flabel = usrPrompt('Jump to: label')
    if not Flabel then return end
    local aspiringPageBack = Flabel .. suffixBlabel
    local backAnchor = "[[" .. aspiringPageBack .. "||^|]]"
    -- local thBlabel = "^" .. (backrefStat(Flabel) + 1) .. "^"
    local thBlabel = "==" .. (backrefStat(Flabel) + 1) .. "=="
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backrefStat = '${backrefStat("' .. Flabel .. '")}*~Σ~*'
    local fullText = backAnchor .. thBlabel .. F .. forthRef .. backrefStat
    editor.insertAtPos(fullText, editor.getCursor(), true)
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        -- return tonumber(string.match(self.snippet, "%^([0-9]+)%^"))
        return tonumber(string.match(self.snippet, "==([0-9]+)=="))
      end
    end
  }
}

Indeed, AI is almost entirely incapable of drafting or even assisting with this code above. Conceptually and technically, it understands neither the theoretical framework of ABC, nor the coding details of space-lua.

About a year and a half ago, I spent an entire week in continuous dialogue with Perplexity.ai to fully implement ABC in LaTeX. Hard to make it grasp my intent, just guide it to built blocks step by step (BTW, Perplexity.ai is good at LaTeX even TeX, at least at that moment).


In fact, we can surmise why: this code is a “language l∞p” both in its abstract conceptual logic = textual semantic description, as well as in the implementation details of the code itself (note that there are two kinds of text — the descriptive text of the code and the code as text).

It resembles a “snake biting its own tail,” like《Predestination》(a film), or more precisely, a Klein bottle or Möbius strip of ∞ — if you trace the connections Forth Anchor/LabelBack Refs/LinksBack Anchor/LabelForth Ref/Link, and finally back to the beginning → Forth Anchor/Label.

LLMs are, first and foremost, language models; however, once recursion involving “self-reference”/“self-referential” stuff or rather “close enough but totally different meanings” arises in both the latent semantic space and the surface code text, they fail catastrophically.

I’m always on the edge/beta builds of
Software. Be it phone, computer Silverbullet you name it.

As for the code snippet. I’m sure it’s impressive and complicated. I still trying to figure out where and how could i use this in my daily life.
I’m more for simple things like 1+1.
Congrats for the success, I’ve been following your journey with this code and your perseverence is admirable.

If i follow you, is like a symlink a position of md file ( label)?
Is working with multipage?
Label in page one and link in page 2?

I think I understand what @ChenZhu-Xie is getting it, it’s a cool concept and I think it shows that one of SB’s biggest strengths is that it allows people to try out new ideas, whether they make sense to other people or not — if it it helps you, go do it :smile:

1 Like

for @Mr.Red

Haha @Mr.Red, your approach and tone align remarkably with the “German” qualities I have always envisioned — principled in process, accountable for results, and fundamentally altruistic in intent (though not every German fits this image).

I have long admired such traits. In my discipline, Germany’s leadership in crystal optics, quantum optics, and both theoretical and applied optics has persisted for nearly two centuries. Maxwell’s equations, together with constitutive relations, render the physical world’s complexity comparable to that of human-devised programming systems. Physicists therefore not only explore nature’s intrinsic “programming”, but also maintain a deep sense of respect for both natural law and computational structure.

There are also some more “personal” analogies:

  • My heritage is Chinese, yet my training has instilled in me a distinctly German rigor in logic (as a practitioner of theoretical optics);
  • I am from Sichuan, so naturally I enjoy chili — and Sichuan pepper as well;
  • I am fond of science fiction, e.g. Liu Cixin’s《The Three-Body Problem》;
  • I love trance music, and if I remember correctly, it originated in Germany, Denmark, or perhaps the Netherlands?

for @zef

If I were to draw an analogy within optics, @zef reminds me of ASML — the Dutch company that has fused foundational optical theory with advanced engineering, elevating both to extraordinary heights. From a product standpoint, @zef’s SilverBullet is analogous to ASML’s lithography machines: the former is foundational infrastructure for the metaphoric realm of information management and virtual entities, while the latter anchors the physical world of semiconductor manufacturing and real materials.

I had intended to sponsor @SilverBullet, yet my GitHub account was labeled “Chinese” by the platform, leaving me unable to sponsor anyone or to receive any sponsorship, and my attempts to dispute this were ineffective. GitHub’s policies seem influenced by strange currents of American politics; paradoxically, even their adversaries’ willing to support people outside their own country — including Americans — are banned too. Ironically, how could any rational subject reject others’ donations? Perhaps it is time for me to manage a second GitHub account, like a second SB instance, but way more inconvenient.

So for now, I have chosen to support @zef through concrete actions, since emotional value is also a universal currency — if you have a girlfriend or a wife, you would understand -_-||.

for @SilverBullet

One person’s capacity is inherently limited. Five and a half years ago, a Chinese innovator launched a similar revolution in bidirectional-linked documentation, but he lasted fewer than four years — advancing entirely alone. The time has come to continue his legacy, but this time as a community rather than a solitary figure.

The temptation of building a definitive effective information-management system is immense. Moreover, a logically optimal solution exists. Anyone with ambition seeks to grasp this ultimate “Devil Fruit” (see《One Piece》) within their lifetime, yet its price is unmistakable: like the sun, it consumes those who fly too close.

Thus — rest when you must, step back when you need to. Advance steadily, refine patiently. Both the technological foundations of @zef and the flourishing conceptual landscape surrounding bidirectional knowledge systems are deeply intricate. One must maintain strategic foresight while ensuring sustainable execution, avoiding burnout at all costs.


Technically, highly granular bidirectional links significantly increase the load on indexing. This might be why Tana enbraces a cloud graph database and why SiYuan exhibits slower indexing performance. SilverBullet’s current preference for page-level backlinks is a judicious approach. Having explored numerous outline-oriented bidirectional-link systems and still finding myself back with SilverBullet, I have begun to contemplate the contrast between (see also https://enlarge-the-percentage.fly.dev/Daydream/📄🧑🏻‍💻%20页面内,大纲%20<%20标题) the long-validated page-level heading model, optimized for human readability since the dawn of the internet, and the emerging structure of indented outline nodes.

for @malys

As for @malys, I cannot quite deduce your nationality… but let me respond to your question first. :slight_smile:

YES, go to + go back to/from anywhere you've been to/from, even inside an Object.

(Ah, Spain! I later discovered the clue from the education section of your personal website. I once developed an auxiliary tool for DDTank, a game that was also once immensely popular in Spain:)

3 Likes

refer to and backlink from anywhere in your space to anywhere in your space bypassing page links, if i got it right (my apologizes for approximation), at least it does that in my space :))
Thank you sir :)) - and also for the beautiful journey through the delights of scholarly imagination

1 Like

Update: Faster (less input) + Organized (more ordered) + Fixed (less bug) Version

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "🔵"
local suffixBlabel = "🟣"
local F = " ➡️ "
local B = " 🔙 "

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backrefStat(Flabel)
  return #tableBack(Flabel)
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}]]​==${_.thBlabel}==​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "insert: Forthanchor + Backrefs",
  key = "Ctrl-,",
  run = function()
    local iniText = getSelectedText()
    -- local Flabel = usrPrompt('Enter: label (to be Referred)', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|]]"
    local backrefStat = '${backrefStat("' .. Flabel .. '")}*~Σ~*'
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backrefStat .. B .. backRefs
    if iniText and iniText ~= "" then
      setSelectedText("") -- Delete selected iniText
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new[==[​[[${_.ref}]]​]==])
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "insert: Backanchor + Forthref",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText()
    local iniText = js.window.navigator.clipboard.readText()
    -- local Flabel = usrPrompt('Jump to: label', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = backrefStat(Flabel) + 1
    local aspiringPageBack = Flabel .. suffixBlabel .. thBlabelNum
    local backAnchor = "[[" .. aspiringPageBack .. "||^|]]"
    local theBlabel = "==" .. thBlabelNum .."=="
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backrefStat = '${backrefStat("' .. Flabel .. '")}*~Σ~*'
    local fullText = backAnchor .. theBlabel .. F .. forthRef .. backrefStat
    if alias and alias ~= "" then
      setSelectedText("") -- Delete selected alias
    else
      alias = Flabel .. suffixBlabel -- alias = ''
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.toPage, ".+" .. suffixBlabel .. "([0-9]+)"))
      end
    end
  }
}

A more minimal and universally applicable template:

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "🔵"
local suffixBlabel = "🟣"
local F = " ➡️ "
local B = " 🔙 "

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backrefStat(Flabel)
  return #tableBack(Flabel)
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}]]~${_.thBlabel}~]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "insert: Forthanchor + Backrefs",
  key = "Ctrl-,",
  run = function()
    local iniText = getSelectedText()
    -- local Flabel = usrPrompt('Enter: label (to be Referred)', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|]]"
    local backrefStat = '${backrefStat("' .. Flabel .. '")}'
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backrefStat .. B .. backRefs
    if iniText and iniText ~= "" then
      setSelectedText("") -- Delete selected iniText
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new[==[​[[${_.ref}]]​]==])
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "insert: Backanchor + Forthref",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText()
    local iniText = js.window.navigator.clipboard.readText()
    -- local Flabel = usrPrompt('Jump to: label', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = backrefStat(Flabel) + 1
    local aspiringPageBack = Flabel .. suffixBlabel .. thBlabelNum
    local backAnchor = "[[" .. aspiringPageBack .. "||^|]]"
    local theBlabel = "~" .. thBlabelNum .."~"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backrefStat = '${backrefStat("' .. Flabel .. '")}'
    local fullText = backAnchor .. theBlabel .. F .. forthRef .. backrefStat
    if alias and alias ~= "" then
      setSelectedText("") -- Delete selected alias
    else
      alias = Flabel .. suffixBlabel -- alias = ''
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.toPage, ".+" .. suffixBlabel .. "([0-9]+)"))
      end
    end
  }
}

for the sake of the image it’s on the same page, but it works from/to anywhere.
thank you :))

1 Like

Two variants designed to minimize visual distraction, potentially offering greater clarity:

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "🔵"
local suffixBlabel = "🟣"
local F = '➡️'
local B = '🔙'

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backrefStat(Flabel)
  return #tableBack(Flabel)
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "Insert: ForthAnchor + BackRefs",
  key = "Ctrl-,",
  run = function()
    local iniText = getSelectedText()
    -- local Flabel = usrPrompt('Enter: label (to be Referred)', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|" .. suffixFlabel .. "]]"
    local backrefStat = '${backrefStat("' .. Flabel .. '")}'
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backrefStat .. B .. backRefs
    if iniText and iniText ~= "" then
      setSelectedText("") -- Delete selected iniText
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel, thBlabelNum)
  local str = template.each(tableForth(Flabel), template.new("[[${_.ref}|​" .. thBlabelNum .. "​]]"))
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "Insert: BackAnchor + ForthRef",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText()
    local iniText = js.window.navigator.clipboard.readText()
    -- local Flabel = usrPrompt('Jump to: label', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = backrefStat(Flabel) + 1
    local aspiringPageBack = Flabel .. suffixBlabel .. thBlabelNum
    local backAnchor = "[[" .. aspiringPageBack .. "||^|" .. suffixBlabel .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local backrefStat = '${backrefStat("' .. Flabel .. '")}'
    local fullText = backAnchor .. forthRef .. F .. backrefStat
    if alias and alias ~= "" then
      setSelectedText("") -- Delete selected alias
    else
      alias = ''
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.toPage, ".+" .. suffixBlabel .. "([0-9]+)"))
      end
    end
  }
}

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "🔵"
local suffixBlabel = "🟣"
local F = '➡️'
local B = '🔙'

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backrefStat(Flabel)
  return #tableBack(Flabel)
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "Insert: ForthAnchor + BackRefs",
  key = "Ctrl-,",
  run = function()
    local iniText = getSelectedText()
    -- local Flabel = usrPrompt('Enter: label (to be Referred)', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|" .. suffixFlabel .. "]]"
    local backrefStat = '${backrefStat("' .. Flabel .. '")}'
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backrefStat .. B .. backRefs
    if iniText and iniText ~= "" then
      setSelectedText("") -- Delete selected iniText
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new("[[${_.ref}|​" .. backrefStat(Flabel) .. "​]]"))
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "Insert: BackAnchor + ForthRef",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText()
    local iniText = js.window.navigator.clipboard.readText()
    -- local Flabel = usrPrompt('Jump to: label', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = backrefStat(Flabel) + 1
    local aspiringPageBack = Flabel .. suffixBlabel .. thBlabelNum
    local backAnchor = "[[" .. aspiringPageBack .. "||^|" .. suffixBlabel .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local fullText = backAnchor .. thBlabelNum .. F .. forthRef
    if alias and alias ~= "" then
      setSelectedText("") -- Delete selected alias
    else
      alias = ''
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.toPage, ".+" .. suffixBlabel .. "([0-9]+)"))
      end
    end
  }
}

Furthermore, all anchors, in principle, can be hidden, and the statistics discarded…
approaching a final form — though perhaps no true final version exists,
given the abundance of possible variants…

3 Likes

This looks so much better and cleaner than the a attempts before.
If you could also make the back and forward buttons more uniform:

Proposal 1: :left_arrow: (backward), :right_arrow: (forward).

Proposal 2: :reverse_button: (backward), :play_button: (forward).

Proposal 3: :fast_reverse_button: (backward), :fast_forward_button: (forward).

Proposal 4: :right_arrow_curving_left: (backward), :left_arrow_curving_right: (forward).

Proposal 5: :backhand_index_pointing_left: (backward), :backhand_index_pointing_right: (forward).

Or other three alternative pairs:

Proposal 69: :eggplant: (backward), :sweat_droplets: (forward).

Proposal 420: :peach: (backward), :waving_hand: (forward).

Proposal 5318008: :hot_dog: (backward), :doughnut: (forward).

1 Like

Thank you for providing the schema that uses reverse arrows in the same color.

My original plan was to treat :soon_arrow: as the forward counterpart of :back_arrow:, but the added label “SOON” failed to evoke the sense of “Forth”.

After adopting :right_arrow: (instead of :soon_arrow:), I found the outcome unexpectedly successful: using differently colored arrows for forward and reverse directions significantly strengthens their visual contrast.

Thus, by coincidence, this evolved into one of my guiding design philosophies.
In the language of physics: asymmetry matters ;).
More precisely, logo pairs should form an asymmetric ∞ loop:

l[1] r[2]
F l B r
X
B l F r

or ◻ loop:

F[3] B[4]
F l B r
| |
F r B l

wherein,

F = For(ward/th)
B = Back(ward)
l = label
r = reference


Below are two more refined versions; the final one may well be definitive.

This first version is already distilled to its essence; it seems impossible to reduce it any further (aside from removing the icons as well -_-||).

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "➡️"
local suffixBlabel = "🔙"

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "Insert: ForthAnchor + BackRefs",
  key = "Ctrl-,",
  run = function()
    local iniText = getSelectedText()
    -- local Flabel = usrPrompt('Enter: label (to be Referred)', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|" .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    if iniText and iniText ~= "" then
      setSelectedText("") -- Delete selected iniText
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel, thBlabelNum)
  local str = template.each(tableForth(Flabel), template.new("[[${_.ref}|​" .. thBlabelNum .. "​]]"))
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "Insert: BackAnchor + ForthRef",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText()
    local iniText = js.window.navigator.clipboard.readText()
    -- local Flabel = usrPrompt('Jump to: label', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPageBack = Flabel .. suffixBlabel .. thBlabelNum
    local backAnchor = "[[" .. aspiringPageBack .. "||^|" .. suffixFlabel .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef
    if alias and alias ~= "" then
      setSelectedText("") -- Delete selected alias
    else
      alias = ''
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.toPage, ".+" .. suffixBlabel .. "([0-9]+)"))
      end
    end
  }
}

The following second version builds upon the minimal form by adding siblings: it allows users to jump directly to other backward labels — those referencing the same forward label — without first navigating to the forward label itself, thereby eliminating yet another click.

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local suffixFlabel = "➡️"
local suffixBlabel = "🔙"
local siblings = "🧑‍🤝‍🧑"

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "Insert: ForthAnchor + BackRefs",
  key = "Ctrl-,",
  run = function()
    local iniText = getSelectedText()
    -- local Flabel = usrPrompt('Enter: label (to be Referred)', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPageForth = Flabel .. suffixFlabel
    local forthAnchor = "[[" .. aspiringPageForth .. "||^|" .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    if iniText and iniText ~= "" then
      setSelectedText("") -- Delete selected iniText
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableBack_noSelf(Flabel, thBlabelNum)
  local aspiringPageBack = Flabel .. suffixBlabel
  return query[[
    from index.tag "link"
    where toPage and toPage:find(aspiringPageBack, 1, true) and thBlabelNum ~= _.thBlabel
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs_noSelf(Flabel, thBlabelNum)
  local str = template.each(tableBack_noSelf(Flabel, thBlabelNum), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "No Sibling" end
  return str
end

local function tableForth(Flabel)
  local aspiringPageForth = Flabel .. suffixFlabel
  return query[[
    from index.tag "link"
    where toPage == aspiringPageForth
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel, thBlabelNum)
  local str = template.each(tableForth(Flabel), template.new("[[${_.ref}|​" .. thBlabelNum .. "​]]"))
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "Insert: BackAnchor + ForthRef",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText()
    local iniText = js.window.navigator.clipboard.readText()
    -- local Flabel = usrPrompt('Jump to: label', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPageBack = Flabel .. suffixBlabel .. thBlabelNum
    local backAnchor = "[[" .. aspiringPageBack .. "||^|" .. suffixFlabel .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local backRefs_noSelf = '${backRefs_noSelf("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef .. siblings .. backRefs_noSelf
    if alias and alias ~= "" then
      setSelectedText("") -- Delete selected alias
    else
      alias = ''
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.toPage, ".+" .. suffixBlabel .. "([0-9]+)"))
      end
    end
  }
}

  1. label ↩︎

  2. reference ↩︎

  3. For(ward/th) ↩︎

  4. Back(ward) ↩︎

3 Likes

I recently discovered that Obsidian offers a rudimentary anchor feature, [[^^...]], which mimics precise linking.

However, this has 2 limitations:

  1. It lacks backlinks, not to mention automatic backlink updates and dinamic positional accuracy.
  2. It cannot pinpoint the cursor position and at best resolves only to the line containing the anchor text.

Nevertheless, Obsidian also has 2 advantages:

  1. By virtue of the second limitation, anchors can be embedded in a line-retrieval manner via [[^^.
  2. It is easy to develop plugins for OB as well (though not as easy as SB), including porting the functionality discussed in this post into Obsidian — although I remain skeptical, as the larger and more complex the software, the more challenging it becomes to alter its underlying behavior[1]. SilverBullet, by contrast, naturally has this advantage at the bottom, which is why this plugin happens first in SB and not in other apps.

In fact, any ‘born/bare’[2] bi-directional (most electron-based) app among Tana[3], SiYuan[4], RoamResearch[5], RoamEdit[6], RemNote[7], Workflowy[8], LogSeq[9], Orca Note[10], and AnyType[11] that supports line/list/bullet/outline/node/block-level precision for forward and backward links inevitably exhibits the second drawback and the first advantage. These two characteristics represent fundamentally distinct paradigms that are almost impossible to modify.

Yet this also suggests a future in which the current LaTeX-style “manual precise anchors + automatic precise backlinks” model and the those bi-directional-apps-style “retrieval-based automatic anchor line text + automatic line backlinks” model may be fused into one:

What if this plugin were allowed to first locate candidate lines by searching for anchor text, and then let the user select the exact anchor position with the mouse? :wink:


  1. This is precisely why SB ought to embed this behavior, or more broadly the ethos of bidirectional linking (at least any object-level, including line/paragraph-level), into its early-stage roadmap. To this day, OB has yet to join the ranks of truly bullet-level bidirectionally-linked note-taking frameworks. It is already too bulky and massive to move forward. The same holds for Notion, though its ample financial resources largely offset the limitation -_-||. ↩︎

  2. OB is ‘bi-’, but not that ‘born bi-’… based on its history… the same is true of Notion… ↩︎

  3. database king, non-file system king ↩︎

  4. In truth, SilverBullet more closely resembles SiYuan v1 than Obsidian (in terms of the ‘behavior’)? which is why I once affectionately described it as “SB = SY + OB”, see 💎🚅_OB_vs_SB ↩︎

  5. Ancient King ↩︎

  6. Ancient Chinese king of kings, super fast + vast I/O, supporting custom CSS and JS scripts like SB ↩︎

  7. flash card & pdf king ↩︎

  8. beautiful & lightweight ↩︎

  9. LogSeq ALSO have big issues:SLOW, leaves a lot of unnessary texts, text format is NOT pure markdown, using explicit block-id, which makes it less like a born/bare bi-di app. ↩︎

  10. a young Chinese successor of Logseq ↩︎

  11. still only reach object- or page-level granularity. but… since it can convert a block/line or rather a non-object into a real-object, and that real-object have precise backlinks like SB’s page, then by clicking 2 times, one can still have line-level backlinks -_-||… ↩︎

A discovery while experimenting with AnyType
revealed a conceptual equivalence to SilverBullet:

promoting a plain paragraph in AnyType to a named object mirrors
converting an ordinary text in SilverBullet’s editor into an [[aspiring-page]].

Opening that created object in AT (or [[aspiring-page]] in SB) shows backlinks
one of which (back)links to the originating article at line level (at least),
while others point to other pages at line level (as well).

From a higher-level perspective,
this pattern constitutes a cursor–page–cursor bidirectional link:
the page functions as an intermediary that permits cursor-to-cursor connections.

Conclusion: a single [[aspiring-page]] suffices to establish cursor–cursor links;

nevertheless, the earlier code pattern required n+1 distinct [[aspiring-pages]] for 1 forward + n inverse labels.

Inspired by this, I refactored the final code snippet above to minimize anchors/labels, thereby reducing SB’s indexing overhead and better reflecting some essence of graph theory.

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local anchorSymbol = "⚓"
local suffixFlabel = "➡️"
local suffixBlabel = "🔙"
local siblings = "🧑‍🤝‍🧑"

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixFlabel, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "No BackRef" end
  return str
end

command.define {
  name = "Insert: ForthAnchor + BackRefs",
  key = "Ctrl-,",
  run = function()
    local iniText = getSelectedText()
    -- local Flabel = usrPrompt('Enter: label (to be Referred)', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPage = Flabel .. anchorSymbol
    local forthAnchor = "[[" .. aspiringPage .. "||^|" .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    if iniText and iniText ~= "" then
      setSelectedText("") -- Delete selected iniText
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableBack_noSelf(Flabel, thBlabelNum)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixFlabel, 1, true) and thBlabelNum ~= _.thBlabel
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs_noSelf(Flabel, thBlabelNum)
  local str = template.each(tableBack_noSelf(Flabel, thBlabelNum), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "No Sibling" end
  return str
end

local function tableForth(Flabel)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixBlabel, 1, true)
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new("[[${_.ref}|​" .. siblings .. "​]]"))
  if #str == 0 then return "No such Anchor" end
  return str
end

command.define {
  name = "Insert: BackAnchor + ForthRef",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText()
    local iniText = js.window.navigator.clipboard.readText()
    -- local Flabel = usrPrompt('Jump to: label', iniText)
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPage = Flabel .. anchorSymbol
    local backAnchor = "[[" .. aspiringPage .. "||^|" .. suffixFlabel .. thBlabelNum .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backRefs_noSelf = '${backRefs_noSelf("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef .. backRefs_noSelf
    if alias and alias ~= "" then
      setSelectedText("") -- Delete selected alias
    else
      alias = ''
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.alias, suffixFlabel .. "([0-9]+)"))
      end
    end
  }
}

Now the forward jump is be triggered through the siblings emoji :people_holding_hands: (previously numbers ahead of :people_holding_hands:) — an undeniably odd interaction — but the trade-off is a likely improvement in indexing performance.


While experimenting with these apps, I drafted a comparison table that is neither rigorous[1] nor entirely fair[2]:

App Core RAM Tech
SilverBullet ~ 24 MB Go + TS + Lua
RoamEdit ~ 44 MB Custom Web Stack ?
Workflowy ~ 73 MB ? Custom Web Stack ?
RoamResearch -[3] Electron + …
RemNote -[4] Electron + …
Tana ~ 233 MB Electron ? + …
SiYuan ~ 231 MB Electron + Go + TS
AnyType 170 ~ 330 MB Electron + TS
LogSeq ~ 230 MB Electron + Clojure + TS
Orca ~ 200 MB Electron + …
Obsidian ~ 160 MB Electron + TS ?

My fondness for Sublime and Zed over VS Code has left me slightly biased against Electron, which influenced the table above; my apologies if it seems offensive. Note that the above is not a ranking (i.e. an ordered list) but an unordered list.


  1. since I am not a computer specialist ↩︎

  2. it does not account for the RAM inside browser tabs consumed by SB and RE ↩︎

  3. not tested ↩︎

  4. not tested ↩︎

1 Like

With links not only between anchor and references but also between “siblings” !!

May I ?
. to my eyes, the “No Sibling” adds unnecessary noise, you have to know what those numbers and emojis represents anyway, there is no point to “explain”, so nothing or a 0 maybe ?
. you have to be very rigorous in the procedure to establish cross references, i had to to do some manual edits, mainly because of the interaction with the clipboard … confusing but that might be because of my limits :slight_smile:

Thank you

1 Like

Yes, after this verson.

Good logic, I adopted and applied this change.

clip-board / auto-paste behavior is now removed from Ctrl-<> and moved to Ctrl-Shift-<>

Ctrl- Ctrl-Shift-
, (<) [[prompt | (selection) C]], copy:L [[selection (or prompt) | C]], copy:L
. (>) [[prompt | (selection) C]], copy:L [[paste (or prompt) | (selection) C]], copy:L

[1] [2]

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

local anchorSymbol = "⚓"
local suffixFlabel = "🧑‍🤝‍🧑"
local suffixBlabel = "🔙"
local siblings = "➡️"

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixFlabel, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "​" end
  return str
end

command.define {
  name = "Insert: ForthAnchor + BackRefs (sel: label)",
  key = "Ctrl-Shift-,",
  run = function()
    local iniText = getSelectedText() or ""
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPage = Flabel .. anchorSymbol
    local forthAnchor = "[[" .. aspiringPage .. "||^|" .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    if iniText and iniText ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.invokeCommand("Widgets: Refresh All")
  end
}

command.define {
  name = "Insert: ForthAnchor + BackRefs (sel: alias)",
  key = "Ctrl-,",
  run = function()
    local alias = getSelectedText() or ""
    local Flabel = usrPrompt('Enter: label (to be Referred)', '')
    if not Flabel then return end
    local aspiringPage = Flabel .. anchorSymbol
    local forthAnchor = "[[" .. aspiringPage .. "||^|" .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    if alias and alias ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableBack_noSelf(Flabel, thBlabelNum)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixFlabel, 1, true) and thBlabelNum ~= _.thBlabel
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs_noSelf(Flabel, thBlabelNum)
  local str = template.each(tableBack_noSelf(Flabel, thBlabelNum), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "​" end
  return str
end

local function tableForth(Flabel)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixBlabel, 1, true)
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new("[[${_.ref}|​" .. siblings .. "​]]"))
  if #str == 0 then return "​" end
  return str
end

command.define {
  name = "Insert: BackAnchor + ForthRef (label: input)",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText() or ""
    local Flabel = usrPrompt('Jump to: label', '')
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPage = Flabel .. anchorSymbol
    local backAnchor = "[[" .. aspiringPage .. "||^|" .. suffixFlabel .. thBlabelNum .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backRefs_noSelf = '${backRefs_noSelf("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef .. backRefs_noSelf
    if alias and alias ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

command.define {
  name = "Insert: BackAnchor + ForthRef (label: clip)",
  key = "Ctrl-Shift-.",
  run = function()
    local alias = getSelectedText() or ""
    local iniText = js.window.navigator.clipboard.readText()
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Jump to: label', '')
    end
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPage = Flabel .. anchorSymbol
    local backAnchor = "[[" .. aspiringPage .. "||^|" .. suffixFlabel .. thBlabelNum .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backRefs_noSelf = '${backRefs_noSelf("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef .. backRefs_noSelf
    if alias and alias ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.alias, suffixFlabel .. "([0-9]+)"))
      end
    end
  }
}

  1. C: Cursor ↩︎

  2. L: Label, more precisely, Forward Label ↩︎

1 Like

Very nice !!!

going back and forth through the emojis arrows is better indeed.

less confusing to me now, but with a surgical knife it’s expected from the user to pay some attention to what he is doing :))

In case you are dangerously roaming around the dreaded realm of boredom i have some idea to keep you entertained: is it possible to, say by means of right-click or something, to copy into the clipboard the label of a referred before jumping into that far away page where you want to create a reference, because of the virtual page link on the referred at the moment it’s a bit cumbersome for us poor lazy creatures.
Ok nothing important just throwing a seed into a so fertile ground, something i noticed while testing :slight_smile:

EDIT:
Probably better and simpler (if at all possible) is to have a choice in the prompt when creating a reference, it would mean a simple lookup in one of the maintained tables …

1 Like

Yes(, but currently not possible through right-click):

I added a function “magneto copy: the nearest label”, i.e. alt-m to help realize your dream (idea coming from Copy the nearest Format around Cursor).

when creating a Flabel+Backrefs, now could switch from Prompt to Label Picker through Ctrl-Alt-,
when creating a Blabel+Forthref, now every Prompt is replaced by Label Picker by default.

, (<) . (>)
Ctrl- [[prompt | (select)C]] copy:L[1] [[picker | (select)C]] copy:L
Ctrl-Alt- [[pickerC | (select)]] copy:L(A[2]) [[picker | (paste)C]] copy:Nothing
Ctrl-Shift- [[select (or prompt) | C]] copy:L [[paste (or picker) | (select)C]] copy:L
Alt- GoTo: Flabel GoTo: Blabel
Alt-M Cursor: Copy Nearest Label

function getSelectedText()
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  local text = editor.getText()
  return text:sub(sel.from + 1, sel.to)
end

function setSelectedText(newText)
  local sel = editor.getSelection()
  if not sel or sel.from == sel.to then return nil end
  editor.replaceRange(sel.from, sel.to, newText)
end

function usrPrompt(hinText, iniText)
  local iniText = iniText or ""
  local input = editor.prompt(hinText, iniText)
  if not input then
    editor.flashNotification("Cancelled", "warn")
  end
  return input
end

function pickerBox_labelName(hinText, iniText)
  local iniText = iniText or ""
  local allLabels = query[[
    from index.tag "link"
    where toPage and toPage:find(anchorSymbol, 1, true) and alias:find(suffixBlabel, 1, true)
    order by _.toPage
  ]]
  local labels = query[[from allLabels select {name = _.toPage:gsub(anchorSymbol, ""), description = _.page .. "@" .. _.pos}]]
  local sel = editor.filterBox("🔌 Insert", labels, hinText, iniText)
  if sel then return sel.name end
  if not sel then
    editor.flashNotification("Cancelled", "warn")
  end
  return nil
end

function pickerBox_FlabelRef(hinText, iniText)
  local iniText = iniText or ""
  local allFlabels = query[[
    from index.tag "link"
    where toPage and toPage:find(anchorSymbol, 1, true) and alias:find(suffixBlabel, 1, true)
    order by _.toPage
  ]]
  local Flabels = query[[from allFlabels select {name = _.toPage:gsub(anchorSymbol, "") .. suffixBlabel .. _.alias:gsub(suffixBlabel, ""), description = _.page .. "@" .. _.pos, Flabel = _.toPage:gsub(anchorSymbol, "")}]]
  local sel = editor.filterBox("🔎 Flabel", Flabels, hinText, iniText)
  if sel then return sel.description, sel.Flabel end
  if not sel then
    editor.flashNotification("Cancelled", "warn")
  end
  return nil, nil
end

function pickerBox_BlabelRef(hinText, iniText)
  local iniText = iniText or ""
  local allBlabels = query[[
    from index.tag "link"
    where toPage and toPage:find(anchorSymbol, 1, true) and alias:find(suffixFlabel, 1, true)
    order by _.toPage .. alias
  ]]
  local Blabels = query[[from allBlabels select {name = _.toPage:gsub(anchorSymbol, "") .. siblings .. _.alias, description = _.page .. "@" .. _.pos, Flabel = _.toPage:gsub(anchorSymbol, "")}]]
  local sel = editor.filterBox("🔎 Blabel", Blabels, hinText, iniText)
  if sel then return sel.description, sel.Flabel end
  if not sel then
    editor.flashNotification("Cancelled", "warn")
  end
  return nil, nil
end

command.define {
  name = "Go to: Forth Anchor",
  key = "Alt-,",
  run = function()
    local FlabelRef, Flabel = pickerBox_FlabelRef('Select: Flabel (to GOTO)', js.window.navigator.clipboard.readText())
    if not FlabelRef then return end
    -- editor.flashNotification(FlabelRef)
    editor.navigate(FlabelRef)
    -- local pos = tonumber(FlabelRef:match("@(.*)$"))
    -- if pos then
    --     editor.moveCursor(pos, true)
    -- end
    editor.invokeCommand("Navigate: Center Cursor")
    editor.copyToClipboard(Flabel)
  end
}

command.define {
  name = "Go to: Back Anchor",
  key = "Alt-.",
  run = function()
    local BlabelRef, Flabel = pickerBox_BlabelRef('GOTO: Blabel', js.window.navigator.clipboard.readText())
    if not BlabelRef then return end
    -- editor.flashNotification(BlabelRef)
    editor.navigate(BlabelRef)
    -- local pos = tonumber(BlabelRef:match("@(.*)$"))
    -- if pos then
    --     editor.moveCursor(pos, true)
    -- end
    editor.invokeCommand("Navigate: Center Cursor")
    editor.copyToClipboard(Flabel)
  end
}

local anchorSymbol = "⚓"
local suffixFlabel = "🧑‍🤝‍🧑"
local suffixBlabel = "🔙"
local siblings = "➡️"

-- =========== Forth Anchor + Back Refs ==================

local function tableBack(Flabel)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixFlabel, 1, true)
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs(Flabel)
  local str = template.each(tableBack(Flabel), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "​" end
  return str
end

command.define {
  name = "Insert: ForthAnchor + BackRefs (sel: alias)",
  key = "Ctrl-,",
  run = function()
    local alias = getSelectedText() or ""
    local Flabel = usrPrompt('Enter: label (to be Referred)', '')
    if not Flabel then return end
    local aspiringPage = Flabel .. anchorSymbol
    local forthAnchor = "[[" .. aspiringPage .. "||^|" .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    if alias and alias ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

command.define {
  name = "Insert: ForthAnchor + BackRefs (pick: label)",
  key = "Ctrl-Alt-,",
  run = function()
    local alias = getSelectedText() or ""
    local Flabel = pickerBox_labelName('Enter: label (to be Referred)', js.window.navigator.clipboard.readText())
    if not Flabel then return end
    Flabel = usrPrompt('Enter: label (to be Referred)', Flabel)
    if not Flabel then return end
    local forthAnchor = "[[" .. Flabel .. "|^|" .. anchorSymbol .. "|" .. alias .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    editor.copyToClipboard(Flabel)
    if alias and alias ~= "" then
      setSelectedText("")
      editor.copyToClipboard(alias)
    end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    -- editor.copyToClipboard(Flabel)
    -- editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

command.define {
  name = "Insert: ForthAnchor + BackRefs (sel: label)",
  key = "Ctrl-Shift-,",
  run = function()
    local iniText = getSelectedText() or ""
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = usrPrompt('Enter: label (to be Referred)', '')
    end
    if not Flabel then return end
    local aspiringPage = Flabel .. anchorSymbol
    local forthAnchor = "[[" .. aspiringPage .. "||^|" .. suffixBlabel .. "]]"
    local backRefs = '${backRefs("' .. Flabel .. '")}'
    local fullText = forthAnchor .. backRefs
    if iniText and iniText ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.invokeCommand("Widgets: Refresh All")
  end
}

-- =========== Back Anchor + Forth Ref ==================

local function tableBack_noSelf(Flabel, thBlabelNum)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixFlabel, 1, true) and thBlabelNum ~= _.thBlabel
    order by _.thBlabel
    select {ref=_.ref, thBlabel=_.thBlabel}
  ]]
end

function backRefs_noSelf(Flabel, thBlabelNum)
  local str = template.each(tableBack_noSelf(Flabel, thBlabelNum), template.new[==[​[[${_.ref}|${_.thBlabel}]]​]==])
  if #str == 0 then return "​" end
  return str
end

local function tableForth(Flabel)
  local aspiringPage = Flabel .. anchorSymbol
  return query[[
    from index.tag "link"
    where toPage == aspiringPage and alias:find(suffixBlabel, 1, true)
    select {ref=_.ref}
  ]]
end

function forthRef(Flabel)
  local str = template.each(tableForth(Flabel), template.new("[[${_.ref}|​" .. siblings .. "​]]"))
  if #str == 0 then return "​" end
  return str
end

command.define {
  name = "Insert: BackAnchor + ForthRef (label: pick)",
  key = "Ctrl-.",
  run = function()
    local alias = getSelectedText() or ""
    local Flabel = pickerBox_labelName('Pick: label (to Compose)', js.window.navigator.clipboard.readText())
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPage = Flabel .. anchorSymbol
    local backAnchor = "[[" .. aspiringPage .. "||^|" .. suffixFlabel .. thBlabelNum .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backRefs_noSelf = '${backRefs_noSelf("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef .. backRefs_noSelf
    if alias and alias ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

command.define {
  name = "Insert: BackAnchor + ForthRef (alias: paste)",
  key = "Ctrl-Alt-.",
  run = function()
    local iniText = getSelectedText() or ""
    local alias = js.window.navigator.clipboard.readText()
    local Flabel = pickerBox_labelName('Pick: label (to Compose)', iniText)
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPage = Flabel .. anchorSymbol
    local backAnchor = "[[" .. aspiringPage .. "||^|" .. suffixFlabel .. thBlabelNum .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backRefs_noSelf = '${backRefs_noSelf("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef .. backRefs_noSelf
    if iniText and iniText ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    -- editor.copyToClipboard(Flabel)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

command.define {
  name = "Insert: BackAnchor + ForthRef (label: paste)",
  key = "Ctrl-Shift-.",
  run = function()
    local alias = getSelectedText() or ""
    local iniText = js.window.navigator.clipboard.readText()
    local Flabel
    if iniText and iniText ~= "" then
      Flabel = iniText
    else
      Flabel = pickerBox_labelName('Pick: label (to Build)', '')
    end
    if not Flabel then return end
    local thBlabelNum = #tableBack(Flabel) + 1
    local aspiringPage = Flabel .. anchorSymbol
    local backAnchor = "[[" .. aspiringPage .. "||^|" .. suffixFlabel .. thBlabelNum .. "]]"
    local forthRef = '${forthRef("' .. Flabel .. '")}'
    local backRefs_noSelf = '${backRefs_noSelf("' .. Flabel .. '",' .. thBlabelNum .. ')}'
    local fullText = backAnchor .. forthRef .. backRefs_noSelf
    if alias and alias ~= "" then setSelectedText("") end
    editor.insertAtPos(fullText, editor.getCursor(), true)
    editor.copyToClipboard(Flabel)
    editor.insertAtCursor(alias, false) -- scrollIntoView?
    editor.invokeCommand("Widgets: Refresh All")
  end
}

index.defineTag {
  name = "link",
  metatable = {
    __index = function(self, attr)
      if attr == "thBlabel" then
        return tonumber(string.match(self.alias, suffixFlabel .. "([0-9]+)"))
      end
    end
  }
}

-- =========== Magneto Copy: Nearest Label ==================

function SelectiondistanceToCursor(startPos, endPos, cursorPos)
  if cursorPos < startPos then return startPos - cursorPos end
  if cursorPos > endPos   then return cursorPos - endPos   end
  return 0
end

function getCursorPos()
  local cur = editor.getCursor() 
  local cursor_pos = (type(cur) == "table" and cur.pos) or cur
  return cursor_pos
end

function findNearestLabel()
  local pageText = editor.getText()
  local curPos = getCursorPos()

  local pattern = "%[%[[^\n%]]+" .. anchorSymbol .. "|"
  local nearest = nil

  local init = 1
  local ok, err = pcall(function()
    while true do
      local s, e = pageText:find(pattern, init)
      if not s then break end
      
      local dist = SelectiondistanceToCursor(s, e, curPos)
      if not nearest or dist < nearest.dist then
        nearest = { start = s, stop = e, text = pageText:sub(s, e), dist = dist }
      end
      
      init = (e >= init) and (e + 1) or (init + 1)
    end
  end)

  return nearest
end

command.define{
  name = "Cursor: Copy Nearest Label",
  description = "Copy the raw page name of the nearest Wiki Link",
  key = "Alt-m",
  run = function()
    local match = findNearestLabel()
    
    if not match then
      editor.flashNotification("No Label found.")
      return
    end

    local inner = match.text:sub(3, -3)
    editor.copyToClipboard(inner)
    editor.flashNotification(inner .. anchorSymbol)
  end
}

Edit: Alt-m (marker) and Ctrl-Shift-. (quote selection) is system CMDs by default, one needs to update them like https://github.com/ChenZhu-Xie/xczphysics_SilverBullet/blob/main/STYLE/Builtin_Formats.md


  1. label ↩︎

  2. alias ↩︎

1 Like