Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete surrounding whitespace in vim

Tags:

vim

I'm using the awesome https://github.com/tpope/vim-surround plugin to surround words with parenthesis, for example I often use: viws<space><space> to surround a word with spaces.

What I'm missing is the opposite of this, that is, deleting surrounding spaces around a word.

The most common use for me is function arguments like foo(bar) vs foo( bar ) depending on code style.

Does anyone know a nice way to do this?

like image 492
Andreas Fliesberg Avatar asked Feb 28 '12 10:02

Andreas Fliesberg


People also ask

How do I delete a space in vi?

To delete one character, position the cursor over the character to be deleted and type x . The x command also deletes the space the character occupied—when a letter is removed from the middle of a word, the remaining letters will close up, leaving no gap. You can also delete blank spaces in a line with the x command.

How do I remove trailing spaces from a file?

Method One: sed A simple command line approach to remove unwanted whitespaces is via sed . The following command deletes all spaces and tabs at the end of each line in input. java . If there are multiple files that need trailing whitespaces removed, you can use a combination of find and sed commands.

What is trim trailing whitespace?

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline. In your posted question, there is one extra space after try: , and there are 12 extra spaces after pass : >>> post_text = '''\ ...

How do I get rid of extra spaces in Linux?

s/[[:space:]]//g; – as before, the s command removes all whitespace from the text in the current pattern space.


3 Answers

Note: This solution requires the surround plugin referenced in the question.

For your specific situation you could do the following:

cs()

This changes foo( bar ) to foo(bar), however, it is not a general solution to your problem.

like image 153
Randy Morris Avatar answered Oct 16 '22 06:10

Randy Morris


I often productively procrastinate in search of vim plugins too, when I could just define a mapping for this.

nnoremap <leader>dd F<space>xf<space>x

EDIT more information

  • <leader> common key for user defined mappings (, is a good one)

  • dd combination to use (any other mnemonic one will suffice)

  • F<space>x search backwards for a space, then remove it

  • f<space>x search forwards for a space, then remove it

like image 30
puk Avatar answered Oct 16 '22 04:10

puk


Maybe just BXElx in normal mode.

like image 33
Benoit Avatar answered Oct 16 '22 06:10

Benoit