gpt4 book ai didi

c# - Vim [m 运动与 c#

转载 作者:可可西里 更新时间:2023-11-01 08:10:25 25 4
gpt4 key购买 nike

Vim 提供了非常有用的移动命令来跳转到下一个方法的开始/结束:]m、]M、[m 和 ]m。

这些适用于 Java 或类似的结构化语言。(如 :help ]m 和 :help 29.3 中所述)

将最外面的一对花括号视为类似乎可行声明和下一级花括号作为方法声明。

当有一对大括号时,这些运动命令不起作用围绕类定义,这在 C# 等语言中有些常见。

我想知道是否有一些技巧可以使这些命令(单独和以运算符为前缀,例如 y[m, V]M) 处理此代码:

namespace ABC.DEF
{
class A
{
protected string strID;
public string PortID { get { return strID; } set { strID = value; } }

protected MyType x;
public MyType X
{
get { return x; }
set { x = value; if ( x != null ) func1(); }
}


int func1()
{
return 1;
}

int func2(int flag)
{
if (flag == 0)
return flag;


if (flag > 3)
{
return flag;
}
return 2;
}

int func3()
{
return 3;
}
}
}

最佳答案

我不认为 ]m 映射系列可以自定义。在这种情况下,通常的做法是用自定义逻辑覆盖它。我想出了一些 vimscript,应该做你描述的事情。基本上,它会跳过大括号并查看相关行来决定要做什么。在这种情况下,它只是忽略“类”和“命名空间”声明。

nnoremap <buffer> ]m :<c-u>call <SID>JumpMethod('{', 'W',  'n')<cr>
nnoremap <buffer> [m :<c-u>call <SID>JumpMethod('{', 'Wb', 'n')<cr>
nnoremap <buffer> ]M :<c-u>call <SID>JumpMethod('}', 'W', 'n')<cr>
nnoremap <buffer> [M :<c-u>call <SID>JumpMethod('}', 'Wb', 'n')<cr>

xnoremap <buffer> ]m :<c-u>call <SID>JumpMethod('{', 'W', 'v')<cr>
xnoremap <buffer> [m :<c-u>call <SID>JumpMethod('{', 'Wb', 'v')<cr>
xnoremap <buffer> ]M :<c-u>call <SID>JumpMethod('}', 'W', 'v')<cr>
xnoremap <buffer> [M :<c-u>call <SID>JumpMethod('}', 'Wb', 'v')<cr>

onoremap <buffer> ]m :<c-u>call <SID>JumpMethod('{', 'W', 'o')<cr>
onoremap <buffer> [m :<c-u>call <SID>JumpMethod('{', 'Wb', 'o')<cr>
onoremap <buffer> ]M :<c-u>call <SID>JumpMethod('}', 'W', 'o')<cr>
onoremap <buffer> [M :<c-u>call <SID>JumpMethod('}', 'Wb', 'o')<cr>

function! s:JumpMethod(char, flags, mode)
let original_cursor = getpos('.')

if a:mode == 'v'
normal! gv
elseif a:mode == 'o'
normal! v
endif

while search(a:char, a:flags) > 0
if a:char == '}'
" jump to the opening one to analyze the definition
normal! %
endif

let current_line = line('.')

if getline(current_line) =~ '^\s*{'
" it's alone on the line, check the above one
let method_line = current_line - 1
else
let method_line = current_line
endif

let method_line_body = getline(method_line)

if method_line_body =~ '\k\+\s*(.*)' && method_line_body !~ '\<\(for\|foreach\|if\|while\|switch\|using\|catch\|get\|set\)\>'
" it's probably a function call

if a:char == '}'
" we need to go back to the closing bracket
normal! %
endif

echo
return
else
if a:char == '}'
" we still need to go back to the closing bracket
normal! %
endif
endif
endwhile

" if we're here, the search has failed, restore cursor position
echo
call setpos('.', original_cursor)
endfunction

请记住,我对 C# 的了解并不多,因此它可能无法在所有情况下正常工作,但如果您给我一些中断的示例,我可能会想出一些办法。

要尝试它,你应该把它放在你的 vimfiles 目录中的 "ftplugin"下的某个地方,作为 "cs.vim"。任何其他以“cs”开头并以“.vim”结尾的文件名也很好,如果你已经有一个“cs.vim”文件的话。

关于c# - Vim [m 运动与 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6849679/

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