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?
/\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>
?
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>
Commented
Mar 17, 2023 at 7:29
?
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.
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.
y/\D/e-<enter>