0

Lets say I have a list like this:

marcus1235lt
jonas3456lt
       ^Cursor is here
thomas345pt

how can I yank the number under the cursor, in this case 3456, without getting any characters?

1
  • From the beginning of the number y/\D/e-<enter>
    – D. Ben Knoble
    Commented Mar 17, 2023 at 0:03

2 Answers 2

3
/\d\+

searches for one or more digits, as many as possible.

N

repeats the search in the opposite direction because / moved the cursor to the next match.

ygn

yanks the current match of the previous search. See :help gn.

Combined, you get a relatively simple mapping that yanks the number under the cursor:

nnoremap <key> /\d\+<CR>Nygn

But text objects are one of my favorite Vim feature. Here is a crude alternative to the plugins mentioned in the other answer, if you feel like travelling light:

function! VisualNumber()
    call search('\d\([^0-9\.]\|$\)', 'cW')
    normal v
    call search('\(^\|[^0-9\.]\d\)', 'becW')
endfunction
xnoremap in :<C-u>call VisualNumber()<CR>
onoremap in :<C-u>normal vin<CR>
2
  • You can use ? instead of / followed by a N. Also I'd cancel the search highlight so I think we can use :nnoremap <silent> yin ?\d\+<CR>ygn:nohls<CR>
    – Hoblovski
    Commented Mar 17, 2023 at 7:29
  • 2
    No. ? only works the way you want when the cursor is in a number. When it is on the first digit, the cursor jumps to the previous number and you need N to come back. Meaning that ? can have different outcomes, which have to be dealt with in the mapping. On the other hand, / always has the same outcome, no matter where the cursor is in the number, so it always requires a N, which makes things much simpler.
    – romainl
    Commented Mar 17, 2023 at 7:54
2

If you consider installing plug-ins for this purpose, look into:

Or:

Both of them add a in text object for numerical strings, so you can use yin to yank the number under the cursor with any of these two plug-ins installed.

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.