Vim에 자동으로 일치하는 중괄호 삽입
내가 보내는 방법으로 가장 십오처럼 빔 닫는 중괄호를 처리하지 못하기 때문에 주위 멍청이 너무 많은 시간을. 내가 원하는 것은 다음과 같습니다.
이것을 입력하십시오 :
if( whatever )
{ <CR>
그리고 이것을 얻으십시오 :
if( whatever )
{
|
}
여기서 <CR>
의미는 ENTER키를 누르고 |
커서의 위치입니다. 이것이 Eclipse가하는 일입니다. Visual Studio가하는 일입니다. 이것이 제가 Vim이하기를 바라는 것입니다.
나는 몇 가지 플러그인을 보았고 몇 가지를 시도했지만 그중 어느 것도 나 에게이 동작을주지 않는 것 같습니다. 확실히 내가 이것을 원하는 최초의 프로그래머가 될 수는 없습니다.
VimL에서는 {
원하는대로 정확하게 할 일을 매핑 할 수 있습니다 .
inoremap { {<CR>}<Esc>ko
자동 들여 쓰기 설정에 따라 <BS>
뒤에 추가 할 수 있습니다 <CR>
.
보다 완벽한 솔루션을 위해 Luc Hermitte의 vim 플러그인을 살펴 보시기 바랍니다 . 그들은 지금까지 나를 실패한 적이 없습니다.
새 줄의 닫는 괄호와 두 괄호 사이의 줄에 커서를 가져 오려면 괄호 및 괄호 처리를 더 쉽게 만들기 라는 제목의 기사에서 첫 번째 주석의 제안을 따르십시오 .
다음과 같이 자동 닫기를 사용하면 올바르게 작동합니다.
inoremap {<CR> {<CR>}<C-o>O
이것은 적어도 내 시스템에 해당됩니다 (Mac OS X의 Unix 터미널).
내 vimrc에있는 내용은 다음과 같습니다.
let s:pairs={
\'<': '>',
\'{': '}',
\'[': ']',
\'(': ')',
\'«': '»',
\'„': '“',
\'“': '”',
\'‘': '’',
\}
call map(copy(s:pairs), 'extend(s:pairs, {v:val : v:key}, "keep")')
function! InsertPair(left, ...)
let rlist=reverse(map(split(a:left, '\zs'), 'get(s:pairs, v:val, v:val)'))
let opts=get(a:000, 0, {})
let start = get(opts, 'start', '')
let lmiddle = get(opts, 'lmiddle', '')
let rmiddle = get(opts, 'rmiddle', '')
let end = get(opts, 'end', '')
let prefix = get(opts, 'prefix', '')
let start.=prefix
let rmiddle.=prefix
let left=start.a:left.lmiddle
let right=rmiddle.join(rlist, '').end
let moves=repeat("\<Left>", len(split(right, '\zs')))
return left.right.moves
endfunction
noremap! <expr> ,f InsertPair('{')
noremap! <expr> ,h InsertPair('[')
noremap! <expr> ,s InsertPair('(')
noremap! <expr> ,u InsertPair('<')
그리고 일부 파일 형식의 경우 :
inoremap {<CR> {<C-o>o}<C-o>O
// InsertPair 함수가 사소하다는 것을 알고 있지만 많은 <Left>
s 를 작성하지 않고도 하나의 명령으로 명령 및 일반 모드 매핑을 모두 정의 할 수 있기 때문에 시간이 절약됩니다 .
중간에 탭이있는 중괄호, 괄호 및 괄호에 대한 솔루션입니다.
" Automatically closing braces
inoremap {<CR> {<CR>}<Esc>ko<tab>
inoremap [<CR> [<CR>]<Esc>ko<tab>
inoremap (<CR> (<CR>)<Esc>ko<tab>
결과:
function() {
|
}
내가 한 것처럼 이것을 실행하고 AutoClose보다 최근에 업데이트 된 것을 찾고 있던 사람을 위해 : delimitMate AutoClose에 대한 바람직한 솔루션 일뿐 만 아니라 행동 측면에서도 활발한 개발 중입니다. vim.org 에 따르면 AutoClose는 2009 년 이후로 업데이트되지 않았습니다.
당신은에서 볼 수 있듯이 익명 팁 :이 재발 질문에 대한 많은 솔루션이 있습니다 (난이 내 ).
그것은 대괄호 쌍으로 자신을 제한하는 경우입니다. 여기에 제어문의 컨텍스트가 있습니다. 따라서 "if"문을 입력 할 때 ") {"를 입력하지 않는 스 니펫 시스템을 찾을 가능성이 더 큽니다. Vim 단축키는 귀하의 질문에서 읽은 것보다 짧은 경향이 있습니다. 여기에도 많은 선택 사항이 있으며, 가장 가능성이 높은 Snipmate를 찾을 수 있으며 내 C & C ++ 제품군 일 수 있습니다.
.vimrc 파일에 다음을 넣으십시오.
inoremap { {}<ESC>ha
{
삽입 모드에서 를 누를 때마다 {}
가 생성되고 커서를 오른쪽 중괄호에 놓으면 바로 입력을 시작할 수 있습니다. 다른 줄이 아닌 순서대로 중괄호를 넣으면 탭을 }
수동으로 앞에 놓을 수 있습니다. 이렇게하면 앞에 잘못된 양의 탭이 표시되지 않습니다.
Perhaps someone can figure out how to count the amount of tabs the cursor is on, and then generate an equal amount of tabs in front of the }
on a new line.
delimitMate has a setting for this.
I have tried different plugins but I found most accurate and most easy to use auto-pairs. It is really intuitive and when you install it you get what you've expected out of the box.
Vim patch 7.4.849 added a binding to allow for cursor movements without restarting the undo sequence. Once updated to >= 7.4.849 then something like this works great.
inoremap ( ()<C-G>U<Left>
Note that I grabbed that straight from the documentation included in the patch. Best simple solution for this feature yet.
- commit for patch 7.4.849: https://github.com/vim/vim/commit/8b5f65a527c353b9942e362e719687c3a7592309
- mailing list thread: http://vim.1045645.n5.nabble.com/Any-automatic-bracket-insertion-plugins-not-breaking-undo-td5723654.html
I've always preferred something like what sublime text does where it appends the closing brace as the next character, so I added the following to my .vimrc:
inoremap ( ()<ESC>hli
which moves the cursor to between the two braces.
Install and use Vim script AutoClose as recommended in the article titled Automatically append closing characters.
Just a note to @Bob.
Karl Guertin's AutoClose has a function named ``double brace'', that is, you can type curly brace twice, as below.
int func_name(void) {{ ==> Type `{' twice here.
would result in:
int func_name(void) {
| ==> Cursor here.
}
Then, you can type a single Tab, to get indented according to your `shiftwidth' setting, then type.
inoremap ( ()<ESC>i
inoremap " ""<ESC>i
inoremap ' ''<ESC>i
inoremap { {<Cr>}<Esc>O
You do not need a special plugin to do this - but it is a two-step process.
First, add the following to your .vimrc
to eat the triggering character:
" eat characters after abbreviation
function! Eatchar(pat)
let c = nr2char(getchar(0))
return (c =~ a:pat) ? '' : c
endfunction
and then add this abbreviation to your .vimrc
:
inoreabbr <silent> { {
\<cr><space><space>
\<cr><esc>0i}<esc>k$i<c-r>=Eatchar('\m\s\<bar>\r')<cr>
The \
at the start of lines two and three is just a line continuation character. You could have done this all on one line, however and i added it so that i could spread the abbreviation out in a way that mirrors the output you're looking for -- just so things are a little more intuitive.
My solution:
inoremap <expr> <CR> InsertMapForEnter()
function! InsertMapForEnter()
if pumvisible()
return "\<C-y>"
elseif strcharpart(getline('.'),getpos('.')[2]-1,1) == '}'
return "\<CR>\<Esc>O"
elseif strcharpart(getline('.'),getpos('.')[2]-1,2) == '</'
return "\<CR>\<Esc>O"
else
return "\<CR>"
endif
endfunction
Explaination:
The code above first check if you are using Enter
to do confirm a code completion, if not it will indent the {|}
when you type Enter
. Also, it provides html tags auto indent.
Examples:
if( whatever ){|}
press Enter
and you will get
if( whatever )
{
|
}
This also works for html file. See the following example
<html>|<html>
press Enter
and you will get
<html>
|
</html>
참고URL : https://stackoverflow.com/questions/4521818/automatically-insert-a-matching-brace-in-vim
'program story' 카테고리의 다른 글
Markdown에서 오른쪽 정렬 및 양쪽 정렬 방법은 무엇입니까? (0) | 2020.11.21 |
---|---|
디버그 메시지 "리소스가 다른 것으로 해석되었지만 MIME 유형 application / javascript로 전송 됨" (0) | 2020.11.21 |
"localhost"포트 25에서 메일 서버에 연결하지 못했습니다. (0) | 2020.11.21 |
API 보안 : SSL 및 HTTP 기본 인증과 서명 (0) | 2020.11.21 |
모바일 사파리 : 입력 필드의 Javascript focus () 메서드는 클릭으로 만 작동합니까? (0) | 2020.11.21 |