1

Is it possible to add a thousands separator to a number or a selection of numbers?

Before

42
4815162342

After

42
4.815.162.342

I have to perform this operation quite often, which is why I would like for it to be automated and easy to repeat.

1

As I am still relatively new to vim, if there is a better alternative or if there are improvements to be made, please do let me know.

Setup

The solution I ended up with makes use of a regular expression that is saved to a separate regex.vim file, which is sourced in init.vim. The full explanation can be found here:

init.vim

" Regular expressions
source ~/.config/nvim/regex.vim

regex.vim

" Inserts a thousand separator after \0
let sep = 's/\d\(\%\(\d\{3\}\)\+\(\d\)\@!\)\@=/\0'

Source the added regex.vim before continuing.

Usage

  1. Upon visually selecting a number or multiple numbers with v, press : to enter Command-line mode.

  2. Press Ctrl + r, followed by = to allow for an expression to be entered. Type the name that you gave to the regular expression in regex.vim, e.g. sep and press Enter.

As displayed below, entering any character after the above operation should add it as the separator.

Animation showing the usage of aforementioned script

2
  • 3
    It could be slightly easier to define a custom command... more details to follow – D. Ben Knoble Mar 9 '20 at 14:09
  • 1
    Ok, details: to make a custom command, you can do something like command Thousands s/\d\(\%\(\d\{3\}\)\+\(\d\)\@!\)\@=/\0—then you could just do :Thousands to run your substitute. There are more options (like arguments and !s and stuff) in :help user-commands – D. Ben Knoble Mar 11 '20 at 2:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.