1

The use case is to copy citations from pdf files to markdown documents in vim. I'd create a dotted list of important copied text and then I'd like to replace the end of line hyphenation that appears in the copy text as such

- "bla bla bla bla bla bla bla bla bla bla, ex- cept bla bla bla bla bla bla bla bla 
bla bla bla bla bla bla bla bla bla bla bla. re- sult bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla bla bla bla bla."

When I use the following command on selected text :'<,'>s/\(\i\)- /\1/g it returns what I expect:

- “bla bla bla bla bla bla bla bla bla bla, except bla bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla bla bla bla. result bla bla bla bla bla bla bla
bla bla bla bla bla bla bla bla bla bla bla bla.”

To avoid memorizing and entering this pattern each time I need it, I tried to place this into a command called Hyphen in my .vimrc

command! -range=% Hyphen "s/\(\i\)- /\1/g"

Using :'<,'>Hyphen on selected text doesn't work. What am I missing?

2 Answers 2

2

You have to adjust your command:

  1. remove quotes -- otherwise you command tries to execute a comment (" starts a comment in legacy vimscript)
  2. specify range passed to s command, <line1> is a starting line of a command range, <line2> is the last line. Check :h <line1>.
command! -range=% Hyphen <line1>,<line2>s/\(\i\)- /\1/g
2
  • I don't believe ! is necessary.
    – D. Ben Knoble
    Oct 3, 2022 at 14:01
  • @D.BenKnoble 1) It was in original question 2) I personally think that it is needed if you're reloading your configuration or do :.source to change behaviour and recreate a command.
    – Maxim Kim
    Oct 3, 2022 at 14:17
2
  1. Vim uses " as comment leader. Since your RHS starts with a " the rest of the command is ignored and the whole thing does nothing.

    Fixed:

    :command! -range=% Hyphen s/\(\i\)- /\1/g
    
  2. The RHS doesn't implicitly consume the line numbers so you must handle them explicitly.

    Fixed:

    :command! -range=% Hyphen execute '<line1>,<line2>s/\(\i\)- /\1/'
    
3
  • I don't believe execute is needed here, since <line1> and such are handled automatically by command.
    – D. Ben Knoble
    Oct 3, 2022 at 14:01
  • And ! isn't needed, also
    – D. Ben Knoble
    Oct 3, 2022 at 14:01
  • I kept the ! from the original question and it is needed in some situations. :execute is indeed not needed, as shown in the first fix, and the accepted answer is better and simpler for that. FWIW, I could have used :help execute() instead, and maybe sprinkle some string concatenation on top. All perfectly valid approaches.
    – romainl
    Oct 3, 2022 at 14:25

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.