Delete all spaces and tabs at the end of my lines - vim

Any idea on how to delete all the spaces and tabs at the end of all my lines in my code using vim? I sometimes use commands to add things at the end of my lines, but sometimes, because of these unexpected blanks (that is, I put these blanks there inadvertently while coding), which serve no purpose whatsoever, these commands don't do the right job... so i'd like to get rid of the blanks once and for all using some vim command. Thanks in advance!

In vim:
:%s/\s\+$//
Explanation:
: command
% apply to entire file
s search and replace
/\s\+$/ regex for one or more whitespace characters followed by the end of a line
// replacement value of an empty string

I use this function :
func! DeleteTrailingWS()
exe "normal mz"
%s/\s\+$//ge
exe "normal `z"
endfunc
Leader,w to remove trailing white spaces
noremap <leader>w :call DeleteTrailingWS()<CR>
Remove trailing white spaces when saving a python file:
autocmd BufWrite *.py :call DeleteTrailingWS()

Related

Map :%s/^M//g in vimrc

I'm trying to map a command in my vimrc to remove the carriage return character ^M that I sometimes see in files. :%s/^M//g (^M from ctrl-v, ctrl-m) works pretty easily when I'm in the file, but when I save that in my vimrc, it's no good.
nmap ,dm :%s/^M//g <cr>
I'm guessing it's because ^M is interpretted differently when mapped via vimrc, so I tried escaping it with \, to no avail. How can I map this command so that it removes the carriage return characters?
FWIW, I'm using gVim on Windows.
Almost every vim user reaches a moment he wants to solve this issue elegantly and one thing I figured out is that we also need a solution to get rid of ^M and keep the cursor position at once.
Personally I use a function to preserve my cursor position, because when we get rid of ^M the cursor position will change:
" preserve function
if !exists('*Preserve')
function! Preserve(command)
try
let l:win_view = winsaveview()
"silent! keepjumps keeppatterns execute a:command
silent! execute 'keeppatterns keepjumps ' . a:command
finally
call winrestview(l:win_view)
endtry
endfunction
endif
The propper function to get rid of ^M
" dos2unix ^M
if !exists('*Dos2unixFunction')
fun! Dos2unixFunction() abort
"call Preserve('%s/ $//ge')
call Preserve(":%s/\x0D$//e")
set ff=unix
set bomb
set encoding=utf-8
set fileencoding=utf-8
endfun
endif
com! Dos2Unix :call Dos2unixFunction()
As you can see we are using \x0D$ instead of ^M, which is the hexadecimal code for the ^M
The option set bomb helps considering the file as UTF-8 help here. It helps solving encoding issues.
The function "Preserve" can also be used to many other stuff like reindenting the whole file without "moving" our cursor
command! -nargs=0 Reindent :call Preserve('exec "normal! gg=G"')
The above line will set a "Reindent" command with no arguments "-nargs=0". By the way feel free to stell some pieces of my init.vim here
NOTE: It is worth mention the "ifs" preceding the two functions above, it is called guard, it helps us to avoid loading functions twice in the memory, thus, keeping our vim/neovim responsible as much as possible.

vim key mapping with execute normal not working

I want to highlight trailing space at the end of a line in vim. The following command works:
:match Error /\v\s+\n/
But I'm having trouble mapping this to a key:
nnoremap <leader>w :execute "normal! :match Error " . '/\v\s+\n/' . "\<cr>"
Vim responds with:
E114: Missing quote: "\
E15: Invalid expression: "normal! :match Error " . '/\v\s+\n/' . "\
Update:
Having just seen this: http://vim.wikia.com/wiki/Highlight_unwanted_spaces I've got the mapping working, by just writing:
nnoremap <leader>w :match Error /\v\s+\n/<cr>
Can anyone explaing what the problem is with the original execute normal! ... construct which prevents it from working?
your mapping
I think it should be
nnoremap <leader>w :execute "normal! :match Error " . '/\v\s+\n/' . "\<lt>cr>"<cr>
:help <lt> I am not super aware of exactly why this is needed (once upon a time, my executes, too, were not working, as I had \<esc> and \<cr> in my execute "normal! .."s. Just know that in place or <cr>, you need to use \<lt>cr> for <cr> in this construct.
You also need the <cr> at the end to actually run the :execute ".."<cr> command.
easier solution
Also, I think it's easier to just put
set listchars=trail:·
set list
in your vimrc, and then you will be able to see trailing white space.
Personally, I have set listchars=trail:·,tab:»\ ,extends:» in my vimrc.
and an easy regex search (/\s\+$) reveals the white space, which you can easily delete with d$ ("delete 'till end"). Then once you do that, you can press n. to "go to next" then "repeat" the d$.
cool tip
Once you highlight your search pattern, you can even dgn to "select next occurrence and delete it" in one go -- then you can just repeatedly press . until nothing happens ... :help gn. Also, mess around with cgn; it's pretty neat stuff.
Cheers.

What is wrong with this line? nnoremap <C-[> :execute "normal! A{{{\<Esc>"<CR>

I am trying to add this to my vimrc but I am getting problems one it inserts {{{ at the beginning of my vimrc whenever I open it and also it apparently has 'c' in the regiser as the last pressed key so it deletes the first 2 lines when I press j
And when I run the command it complains that
"A{{{\ is missing a quotation mark and is not a command.
This gave me tip. map execute command vim
You don't need use :execute "normal! ..." if you are using nnoremap. This will work.
nnoremap <C-[> A{{{<Esc><CR>

How could I remove trailing blank lines on save, in Vim?

I want to remove trailing blank lines (blank lines could also be just a bunch of tabs and spaces).
In my .vimrc I have:
autocmd BufWritePre * :%s#\($\n\s*\)\+\%$## " trim white spaces at the end of file
This works, however if a file has already had its trailing blank lines removed, I get the following error message:
Error detected while processing BufWrite Auto commands for "*":
How may I fix this?
From :help :s_flags:
[e] When the search pattern fails, do not issue an error message.
So you could try:
:%s#\($\n\s*\)\+\%$##e

Vim unwanted jump to end of file after write

When I write to a file with :w, vim sometimes (NOT ALWAYS) jumps to the end of the file after the write operation is complete. I don't understand why this happens. I've been going through my .vimrc to see if I have some kind of bug. My .vimrc is quite large so I don't include the full source here, I think the only parts of my .vimrc which are perhaps relevant to this question are the following parts:
nore ; :
inoremap jj <Esc>
" Automatically remove all trailing whitespace.
" Every time the user issues a :w command, Vim will automatically remove all
" trailing whitespace before saving
autocmd BufWritePre * :%s/\s\+$//e
" Restore cursor position
au BufReadPost *
\ if line("'\"") > 0|
\ if line("'\"") <= line("$")|
\ exe("norm '\"")|
\else|
\exe "norm $"|
\endif|
\endif
However I don't see how these parts of my .vimrc can cause the jump behavior after writing, a full source of my .vimrc is available here. I hope somebody has an idea about what is causing the unwanted jump.
Here is a command from my ~/.vimrc:
command! -range=% TR mark `|execute <line1> . ',' . <line2> . 's/\s\+$//'|normal! ``
The trick is to create mark ` before the trimming and jump back to it afterward.
You can change your autocmd to:
autocmd BufWritePre * :mark `|%s/\s\+$//e|normal! ``
Even with #romainl's addition of the mark, this still isn't fully transparent:
the view (of displayed lines) may still change (winsaveview() instead of a mark would fix that)
the :s command clobbers the last search pattern
A plugin (like my DeleteTrailingWhitespace plugin) would provide a more robust solution. (The plugin page has links to alternative plugins.)

Resources