如何在Vim中一次评论所选的代码块?

时间:2017-11-18 15:57:37

标签: python vim

我知道如何评论一行,这很容易

:autocmd FileType python nnoremap <buffer> <leader>c I#<esc>

但是如何通过映射快捷方式一次注释多行?我想不出来

即,我进入v模式并选择一个代码块,我可以使用映射快捷方式一次评论它们吗?

代码块的注释意味着,将#放在所选块的每一行,如

a = 2
b = 3
c = 4 

#a = 2
#b = 3
#c = 4

2 个答案:

答案 0 :(得分:3)

您需要一个可视模式映射来操作视觉选择。普通模式映射以def default_3way_compare(v, w): # Yes, this is how Python 2 sorted things :) tv, tw = type(v), type(w) if tv is tw: return -1 if id(v) < id(w) else (1 if id(v) > id(w) else 0) if v is None: return -1 if w is None: return 1 if isinstance(v, (int, float)): vname = '' else: vname = type(v).__name__ if isinstance(w, (int, float)): wname = '' else: wname = type(w).__name__ if vname < wname: return -1 if vname > wname: return 1 return -1 if id(type(v)) < id(type(w)) else 1 def py2key(func=None): # based on cmp_to_key class K(object): __slots__ = ['obj'] __hash__ = None def __init__(self, obj): self.obj = func(obj) if func else obj def __lt__(self, other): try: return self.obj < other.obj except TypeError: return default_3way_compare(self.obj, other.obj) < 0 def __gt__(self, other): try: return self.obj > other.obj except TypeError: return default_3way_compare(self.obj, other.obj) > 0 def __eq__(self, other): try: return self.obj == other.obj except TypeError: return default_3way_compare(self.obj, other.obj) == 0 def __le__(self, other): try: return self.obj <= other.obj except TypeError: return default_3way_compare(self.obj, other.obj) <= 0 def __ge__(self, other): try: return self.obj >= other.obj except TypeError: return default_3way_compare(self.obj, other.obj) >= 0 return K 开头,插入模式映射以n开头,可视模式映射以i开头(是啊......)。

为此,您需要x在给定范围内的每一行执行正常模式命令:

:help :normal

因此...

xnoremap <leader>c :normal I#<CR>

答案 1 :(得分:0)

对于它的价值,您可能需要查看NERDCommenter,它可以帮助您解决所有问题。