4

Let's say I have these lines:

a
# c
b
## d

and i want to insert # on a line starting with a # so that I get this:

a
## c
b
### d

I was not able to find anything in the vim help, but I was able to get this far: g/^#/ - what should come after the second /?

Dylanthepiguy
  • 395
  • 5
  • 13
  • 2
    While the question is technically not the same, I suspect your need is identical to one expressed in that Q/A (https://vi.stackexchange.com/questions/13065/how-to-decrease-markdown-header-level-in-visual-mode-without-a-plugin). Am I right? – Luc Hermitte Aug 17 '17 at 00:31
  • Using substitute Isn't exactly the samebecause if there is a hash in the middle of the line and that would also be changed – Dylanthepiguy Aug 17 '17 at 03:42
  • 2
    No it won't. The pattern to search isn't # but ^#. :substitute really is the way to go. Beside that wasn't my question. My question is: what's your exact need? Is it about refactoring markdown? – Luc Hermitte Aug 17 '17 at 07:15
  • Ah I see, my bad. And yes I am refactoring markdown. I guess it is almost duplicate question then? – Dylanthepiguy Aug 17 '17 at 19:28
  • In spirit yes. Other people may be interested in the technical solution that mixes global + normal, though. What's interesting in the other question, is that the objective is more extensively covered. For instance, I provide a non trivial way to refactor headings while leaving shebangs and # comments intact in code snippets when that matters. – Luc Hermitte Aug 17 '17 at 22:26

1 Answers1

11

What comes after the second / is an Ex command. In this case you could use the :normal command, which executes its argument as if you typed it in normal mode (see :help :normal)

:g/^#/normal I#

or the :substitute command (see :help :substitute)

:g/^#/substitute/^/#/
" Or just
:g/^#/s/^/#/

but also you could use the :substitute command without the :g like so:

:%s/^\ze#/#/
" or
:%s/^#/#&/

See :help /\ze and :help s/\& for more information.

Karl Yngve Lervåg
  • 9,494
  • 25
  • 35
Jair López
  • 1,854
  • 1
  • 15
  • 24