1

So I'm trying to have a function type out a space which goes as follows:

function! UnderlineHeading(level)
  if a:level == 1
    normal! yypVr=
  elseif a:level == 2
    normal! yypVr-
  else
    normal! I###<Space><Esc>
  endif
endfunction

nnoremap <leader>u3 :call UnderlineHeading(3)<cr>

However, when I press <leader>u3 in normal mode, the function enters <Space> instead of an actual space. I have tried making the word space all lowercase (in vain). What causes this to happen and how should I go about fixing it?

If can be of any importance for this question, I use neovim.

1

2 Answers 2

2

It turns out that commands such as :normal! don't really recognize and expand key sequences such as <Space> or even <Esc>.

Simply adding an actual space character would do the job here (normal! I### ), but this means you would have a trailing space in your command-line.

(Note that you don't really need an actual <Esc> character to leave insert mode from a :normal! command, since it will always end Insert mode implicitly at the end of its execution.)

The alternative to that is to use :execute, which allows you to assemble the :normal! command from a string, in which case you can use:

execute 'normal! I### '

That way the space is very clear.

Using :execute also allows you to use a double quoted string, where you can use key codes such as <Esc> as long as you use a backslash escaped < to initiate it. An example:

execute "normal! I### \<Esc>"

(Or, equivalently, execute "normal! I### \e", since \e is also a valid escape for the <Esc> character. But then, again, you don't really need an explicit <Esc> in a :normal! command.)

2
  • 1
    Nice timing! :P
    – D. Ben Knoble
    Commented Dec 9, 2020 at 20:53
  • 1
    @D.BenKnoble When that happens, I'm always glad when our answers are in agreement. :-) Also I hadn't caught that ### was part of what was being inserted, so glad to see that in your answer and correct mine.
    – filbranden
    Commented Dec 9, 2020 at 20:55
2

:normal doesn't (?) interpret <> sequences. You could use

normal! I### 

But the hidden space turns me off; I prefer

execute 'normal! I### '

in this case because it makes the spacing apparent.

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.