在注释和文档字符串中使用较短的文本宽度
来自强大的 PEP 8:
[P]请限制所有行最多 79 个字符。对于流动的长文本块(文档字符串或注释),建议将长度限制为 72 个字符。
在 Vim 中编辑 Python 代码时,我将 textwidth
设置为 79,当我达到字符限制时,Vim 会自动为我换行长行 Python 代码。但在注释和文档字符串中,我需要将文本换行为 72 个字符。
有没有办法让 Vim 在我处于注释或文档字符串时自动将 textwidth
设置为 72,并在完成后将其设置回来?
From the mighty PEP 8:
[P]lease limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended.
When editing Python code in Vim, I set my textwidth
to 79, and Vim automatically wraps long lines of Python code for me when I hit the character limit. But in comments and docstrings, I need to wrap text at 72 characters instead.
Is there any way to make Vim automatically set textwidth
to 72 when I'm in a comment or docstring, and set it back when I'm done?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所以,我以前从未做过任何 Vim 脚本编写,但是基于 这个关于在 C 中执行类似的操作 和此提示用于检查您当前是否在评论中,我已经拼凑了一个解决方案。
默认情况下,这对普通行使用 PEP8 建议的 79 个字符的宽度,对注释使用 72 个字符的宽度,但您可以通过
let
tingg:python_normal_text_width
或来覆盖它们>g:python_comment_text_width
变量,分别。 (就我个人而言,我将正常行换行为 78 个字符。)将此宝贝放入您的 .vimrc 中,您应该可以开始了。稍后我可能会将其打包为插件。
So, I've never done any Vim scripting before, but based on this question about doing something similar in C and this tip for checking if you're currently in a comment, I've hacked together a solution.
By default, this uses the PEP8-suggested widths of 79 characters for normal lines and 72 characters for comments, but you can override them by
let
tingg:python_normal_text_width
org:python_comment_text_width
variables, respectively. (Personally, I wrap normal lines at 78 characters.)Drop this baby in your .vimrc and you should be good to go. I may package this up as a plugin later.
接受的答案很棒!然而,它不支持我格式化/编辑注释的习惯:我进行编辑,然后使用 gqj 命令,本质上是“重新格式化当前行与下一行”。然后我点击了“。”对每一行重复该操作(命令本身将光标移动到下一行)。我不太了解 vim 脚本语言,因此有人可能可以在已接受的答案中添加对此的支持。与此同时,我所做的是映射功能键 (F6) 将文本宽度更改为 72,格式化该行,然后将文本宽度更改回 79。
现在,当我在文档字符串中时,我只需进行编辑, (ESC),然后重复按 F6,直到所有行的格式都正确。
我将地图命令和接受的应答脚本添加到我的 .vim/after/ftplugin/python.vim 中。
The accepted answer is great! It does not, however, support the habit I have for formatting/editing comments: I make my edits and then use the gqj command, which is essentially, "reformat the current line combined with the next". Then I hit '.' to repeat that for each line (the command itself advances the cursor to the next line). I don't know the vim scripting language very well, so someone may be able to add support for this to the accepted answer. In the meantime, what I have done is map a function key (F6) to change the textwidth to 72, format the line and then change the textwidth back to 79.
Now, when I'm in a docstring, I just make the edit, (ESC) and then hit F6 repeatedly until all the lines are properly formatted.
I added my map command and the accepted answer script to my .vim/after/ftplugin/python.vim.