gpt4 book ai didi

python - 在注释和文档字符串中使用较短的文本宽度

转载 作者:IT老高 更新时间:2023-10-28 22:19:20 26 4
gpt4 key购买 nike

来自强大的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.

在 Vim 中编辑 Python 代码时,我将我的 textwidth 设置为 79,当我达到字符数限制时,Vim 会自动为我换行较长的 Python 代码行。但在注释和文档字符串中,我需要将文本换成 72 个字符。

有什么方法可以让 Vim 在我在注释或文档字符串中自动将 textwidth 设置为 72,并在我完成后将其设置回来?

最佳答案

所以,我以前从未编写过任何 Vim 脚本,但基于 this question about doing something similar in Cthis tip for checking if you're currently in a comment ,我想出了一个解决方案。

默认情况下,这使用 PEP8 建议的 79 个字符用于普通行和 72 个字符用于注释的宽度,但您可以通过 letting g:python_normal_text_width 覆盖它们或 g:python_comment_text_width 变量,分别。 (就我个人而言,我在 78 个字符处换行。)

把这个宝贝放到你的 .vimrc 中,你就可以开始了。稍后我可能会将其打包为插件。

function! GetPythonTextWidth()
if !exists('g:python_normal_text_width')
let normal_text_width = 79
else
let normal_text_width = g:python_normal_text_width
endif

if !exists('g:python_comment_text_width')
let comment_text_width = 72
else
let comment_text_width = g:python_comment_text_width
endif

let cur_syntax = synIDattr(synIDtrans(synID(line("."), col("."), 0)), "name")
if cur_syntax == "Comment"
return comment_text_width
elseif cur_syntax == "String"
" Check to see if we're in a docstring
let lnum = line(".")
while lnum >= 1 && (synIDattr(synIDtrans(synID(lnum, col([lnum, "$"]) - 1, 0)), "name") == "String" || match(getline(lnum), '\v^\s*$') > -1)
if match(getline(lnum), "\\('''\\|\"\"\"\\)") > -1
" Assume that any longstring is a docstring
return comment_text_width
endif
let lnum -= 1
endwhile
endif

return normal_text_width
endfunction

augroup pep8
au!
autocmd CursorMoved,CursorMovedI * :if &ft == 'python' | :exe 'setlocal textwidth='.GetPythonTextWidth() | :endif
augroup END

关于python - 在注释和文档字符串中使用较短的文本宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4027222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com