2

If I'm anywhere on a line that contains e.g.:

[text1](link to text1)

How do I cut from [ to ) ?

2
  • If by cut you mean delete, then something like :%s:\v\[.{-}\)::g should work. But if you mean cut and put it in clipboard, then that'd require different approach.
    – 3N4N
    Oct 7, 2022 at 4:10
  • Note that Markdown links' parentheses are balanced (in CommonMark, at least), so this cannot be done with a regular expression. See [Disambiguation](https://en.wikipedia.org/wiki/Disambiguation_(disambiguation))Disambiguation.
    – wizzwizz4
    Oct 7, 2022 at 15:56

3 Answers 3

5

I'd just do this in normal mode: 0f[df).

If this is something you're doing a lot, then you could create a mapping:

:nnoremap <leader>d 0f[df)

But once you're going that far, you probably want something a bit more sophisticated, such as a custom text object, or, ideally, a pair of them so you can handle whitespace appropriately (like how iw and aw work for words).

3
  • 1
    Notice that 0f[ fails the criteria "If I'm anywhere on a line" if the markdown link starts at the very beginning of the line and the line contains the [ elsewhere.
    – hlovdal
    Oct 7, 2022 at 17:23
  • @hlovdal Good point! But in practice, if my cursor were already on the [ I wouldn’t press 0. In fact, in practice, I’d never press 0! I’d just use f/F accordingly.
    – Rich
    Oct 7, 2022 at 18:12
  • @hlovdal I guess $F[ solves the start of line problem, but not the “another [ in the way” problem. :(
    – Rich
    Oct 7, 2022 at 18:48
1

This command copy the first Markdown link of the current line:

exe 's/\[.*)/&/' | norm gny

This command copy the next Markdown link:

exe "norm /\[.*)\<CR>gny"

The first bit (exe 's/[.*)/&/) search for the link on the current line and replace by itself.

The second part (norm gny) select the match and yank it.

If you prefer to cut you could do:

exe 's/\[.*)/&/' | norm gnd

This command cut the next Markdown link:

exe "norm /\[.*)\<CR>gnd"
2
  • For cut, gnd would suffice.
    – D. Ben Knoble
    Oct 7, 2022 at 11:47
  • Indeed. Thanks for the hint :-). I believe the solution of @Rich is better ;-) Oct 7, 2022 at 12:08
1

Assuming your position is at the starting [1, I would use d%. (or d%d%).


1Actually you can have the cursor a bit in front as well if there is any connected preceding text you want, e.g.

The [question](https://vi.stackexchange.com/q/38796/843), the [answer](https://vi.stackexchange.com/a/38807/843).

after 0f, then d%. gives

The [question](https://vi.stackexchange.com/q/38796/843).

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.