Vim:如何删除空行中的空格?

问题描述 投票:1回答:2

如何使用vim检测包含空格的空行并删除空格?

例如,我使用来表示空格:

def⎵function(foo):
⎵⎵⎵⎵print(foo) 
⎵⎵
⎵
function(1)

是否有一个vim命令将上面的代码转换为以下代码?

def⎵function(foo):
⎵⎵⎵⎵print(foo) 


function(1)
vim vi
2个回答
2
投票
:g/^\s\+$/s/\s\+//

说明:

g — execute the command globally (for all lines)
/^\s\+$/ — search lines that contain only whitespaces
s/\s\+// — for every found line execute this
           search and replace command:
           search whitespaces and replace with an empty string.

可以简化为

:%s/^\s\+$//

% — execute for all lines
s/^\s\+$// — search and replace command:
             search lines that only have whitespaces
             and replace with an empty string.

2
投票

我有一个功能,可以解决这个问题并保持光标位置

if !exists('*StripTrailingWhitespace')
    function! StripTrailingWhitespace()
        if !&binary && &filetype != 'diff'
            let b:win_view = winsaveview()
            silent! keepjumps keeppatterns %s/\s\+$//e
            call winrestview(b:win_view)
        endif
    endfunction
endif
command! Cls call StripTrailingWhitespace()
cnoreabbrev cls Cls
cnoreabbrev StripTrailingSpace Cls
nnoremap <Leader>s :call StripTrailingWhitespace()

您可以使用命令:cls或快捷方式<leader>s。实际上你可以改变它以满足你的需求。

© www.soinside.com 2019 - 2024. All rights reserved.