2

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 to check if the line starts with #:

  • if yes, add # to it,
  • if not, add # and a 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.

1 Answer 1

1

This is what I would do:

local obsidianSettingsGroup = vim.api.nvim_create_augroup('Obsidian Group', { clear = true })
vim.api.nvim_create_autocmd('FileType', {
  pattern = {'markdown'}, 
  callback = function()

    function entitle()
      print("bob")
      local current_line = vim.api.nvim_get_current_line()

      if string.sub(current_line, 1, 1) == '#' then 
          vim.api.nvim_command("normal! I#")
      else 
          vim.api.nvim_command("normal! I# ")
      end 
    end

    local keymap = vim.api.nvim_buf_set_keymap
    local opts = {noremap = true, silent = true, callback = entitle}
    keymap(0, "n", "<C-s>", "", opts)
  end,
  group = obsidianSettingsGroup,
})

Here are three remarks about the original code that lead me to a working solution.

To compare the string you have to use string.sub(current_line, 1, 1) == '#' instead of just current_line[0] == '#'

If you intend to use a callback it has to be set in the opts argument and not as a right hand side (rhs argument).

The callback argument is not like the Vim <expr> it is function that intend to modify the buffer itself (the return value is discarded).

3
  • 1
    It didn't work, neither first form nor second form. Mar 2 at 5:19
  • I have corrected the answer. This one I tested and should work fine. Mar 2 at 5:32
  • 1
    I am very sorry for my rudeness, but it is still not working :/ Mar 2 at 5:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.