1

I ran into this doing a quick conversion of markdown into JIRA markdown.

- A standard markdown list
  - hierarchical
  - easy to read
    - tidy

- A JIRA markdown list
-- Hierarchical
-- Somewhat more annoying to read
--- Why, JIRA, why?

Expressed in English, what I needed to do was:

On any line beginning with spaces followed by a hyphen followed by at least one space, replace "^ " (two leading spaces) with "-" repeatedly for all instances of two spaces up to the hyphen.

What I actually did, which comes close, was:

:g/^\s\+- /s/  /-/g

But, if there are any instances of two consecutive spaces elsewhere in the line (after the first hyphen), this will incorrectly convert them to a hyphen.

Is there any way to make :s match not globally, but only on some specified part of the line? Perhaps on a backreference?

Imaginary syntax for applying a substitute command globally, but only to the part of the line captured in a backreference:

:g/g/^\s\+- / /^\(\s\+\)/ \1s/  /-/g
Wildcard
  • 4,409
  • 26
  • 49

1 Answers1

2

In this specific case, you want to replace leading matches of with an equal number of -:

:g/^\s\+- /s:^\(  \)*:\=repeat('-', strlen(submatch(0))/2):g

Source:

More generally, you can use expressions (in particular, the subtitute() function) in the replacement in combination with \zs/\ze (or lookaheads and lookbehinds) (as seen in the example in this answer), to act only on a section of the line:

s:^\(  \)*:\=substitute(submatch(0), '  ', '-', 'g'):g

Here, the section is well-anchored already, and there was no need for \zs or lookarounds.

muru
  • 24,838
  • 8
  • 82
  • 143