Extra details, The whole code:
local obsidianSettingsGroup = vim.api.nvim_create_augroup('Obsidian Group', { clear = true })
vim.api.nvim_create_autocmd('FileType', {
pattern = {'markdown'},
callback = function()
function entitle()
local current_line = vim.api.nvim_get_current_line()
if current_line[0] == '#' then
return "I#<Esc>A<Esc>"
else
return "I# <Esc>A<Esc>"
end
end
local keymap = vim.api.nvim_buf_set_keymap
local opts = {noremap = true, silent}
keymap(0, 'n', '<C-S-p>', ':ObsidianWorkspace<CR>', opts)
keymap(0, 'n', '<C-p>', ':ObsidianQuickSwitch<CR>', opts)
keymap(0, 'n', '=', entitle(), opts)
end,
group = obsidianSettingsGroup,
})
So the goal is, check if line starts with #
if yes, add #
to it, if not, add #
with space after it.
Everything in the code works except the condition, which always returns false. Mind you it still runs, it just gives me the wrong thing.
I have checked around the internet for various things but didn't find anything like this, or rather everybody who went about matching and replacing used very similar code but never in conditionals, dunno what I am doing wrong.
I'm totally ignorant of Lua or NeoVim. However, you can't say NeoVim without also saying Vim. The plain Vim way to accomplish what you're trying to do would be the following one-line command:
:s/^\s*\zs\ze\(.\)/\=submatch(1)=='#'?'#':'# '
This uses the :substitute
command to match from the beginning of the line ^
, any number of whitespace \s*
. Now, \zs
starts the match and \ze
immediately ends it (we're using this as a poor man's lookaround) and \(.\)
matches any character and puts it in a capture group. To put it in plain English: we match in front of the first non-whitespace character in a line and capture said character.
See :help :substitute
, :help pattern
and :help /\zs
.
To have a condition, we use \=
to evaluate the replacement as an expression. Our expression is a ternary condition. If the captured character submatch(1)
is a "#", put another "#" in front of it, else put "# ".
References: :help sub-replace-expression
, :help submatch()
and :help ternary
.
Going forward with this command, you could create a mapping, you could call it from a function or you could create a user command.