엄마가 말하지 않은 Vim의 어두운 구석은 무엇입니까? [닫은]
사람들이 일반적인 트릭, 특히 " Vim + ctags 팁과 트릭 "에 대해 이야기하는 많은 질문이 있습니다.
그러나 Vim을 처음 접하는 사람이 멋지다고 생각하는 일반적으로 사용되는 바로 가기는 언급하지 않습니다. 나는 노련한 유닉스 사용자 (개발자, 관리자, 둘 다 등)에 대해 이야기하고 있는데, 우리 중 99 %가 결코 듣거나 꿈꾸지 못한 것을 알고 있다고 생각합니다. 작업을 더 쉽게 할뿐만 아니라 COOL하고 hackish . 결국 Vim 은 세계에서 가장 어두운 구석이 풍부한 OS에 상주하므로 소수의 특권층 만이 알고 공유하고 싶은 복잡함이 있어야합니다.
Vim 사용자의 99 %가 모르는 것이 아닐 수도 있지만, 매일 사용하는 것이고 Linux + Vim 파워 유저라면 반드시 알아야 할 것입니다.
기본 명령이지만 매우 유용합니다.
:w !sudo tee %
쓰기 권한이없는 파일을 편집하기 전에 sudo를 자주 잊어 버립니다. 해당 파일을 저장하고 권한 오류가 발생하면 해당 파일을 임시 파일에 저장하지 않고 저장하기 위해 vim 명령을 실행 한 다음 다시 복사합니다.
분명히 sudo가 설치된 시스템에 있어야하고 sudo 권한이 있어야합니다.
최근에 발견 한 것이 매우 멋지다고 생각했습니다.
:earlier 15m
문서를 15 분 전의 상태로 되돌립니다. 롤백하려는 시간에 대해 다양한 인수를 사용할 수 있으며 실행 취소 수준에 따라 다릅니다. 반대 명령으로 되돌릴 수 있습니다.:later
:! [command]
Vim에있는 동안 외부 명령을 실행합니다.
그러나 콜론 뒤에 점을 추가 :.! [command]
하면 명령의 출력이 현재 창에 덤프됩니다. 그건: . !
예를 들면 :
:.! ls
입력중인 문서에 현재 날짜를 추가하는 것과 같은 작업에 많이 사용합니다.
:.! date
정확히 모호하지는 않지만 매우 유용한 몇 가지 "delete in"명령이 있습니다.
diw
현재 단어를 삭제하려면di(
현재 괄호 내에서 삭제di"
따옴표 사이의 텍스트를 삭제하려면
기타는 다음에서 찾을 수 있습니다. :help text-objects
de 를 눌러 단어 끝까지 모든 것을 삭제합니다. 당신의 마음의 욕망에.
ci (xyz [Esc] -이것은 이상한 것입니다. 여기서 'i'는 삽입 모드를 의미하지 않습니다. 대신 괄호 내부를 의미합니다. 따라서이 시퀀스는 서있는 괄호 안의 텍스트를 잘라내어 . "XYZ"는 또한 내부 광장과 그림 괄호를 작동 -.. 단지 CI [또는 CI를 {방금 입력 아무것도하지 않고 모든 텍스트를 삭제하려면 상응 당연히, 당신은 (디를 할 수있는 당신도 할 수있는 할 a
대신에 i
당신이 경우 괄호 안의 텍스트뿐만 아니라 괄호도 삭제하고 싶습니다.
ci " -현재 따옴표로 텍스트를 자릅니다.
ciw- 현재 단어를 자릅니다. 이것은 (
로 대체 된다는 점을 제외하고 는 이전 것과 동일하게 작동합니다 w
.
C- 나머지 줄을 자르고 삽입 모드로 전환합니다.
ZZ- 현재 파일을 저장하고 닫습니다 (현재 탭을 닫으려면 Ctrl-F4보다 빠릅니다!)
ddp- 현재 행을 한 행 아래로 이동
xp- 현재 캐릭터를 오른쪽으로 한 위치 이동
U- 대문자이므로 viwU
단어를 대문자로 표시
~ -대 / 소문자를 전환하므로 viw~
전체 단어의 대 / 소문자 가 반전됩니다.
Ctrl + u / Ctrl + d 화면의 절반을 위 또는 아래로 스크롤합니다. 이것은 두 화면이 어떻게 관련되어 있는지 쉽게 볼 수 있도록하므로 일반적인 전체 화면 페이징보다 더 유용합니다. 한 번에 전체 화면을 계속 스크롤하려는 경우 앞으로 Ctrl + f, 뒤로 Ctrl + b가 있습니다. Ctrl + Y 및 Ctrl + E는 한 번에 한 줄씩 아래 또는 위로 스크롤합니다.
미쳤지 만 매우 유용한 명령은 zz입니다 . 화면을 스크롤하여이 줄이 중간에 나타나도록합니다. 이것은 작업중인 코드를주의 중심에 두는 데 탁월합니다. 형제 명령 (zt 및 zb)은이 줄을 sreen의 맨 위 또는 맨 아래 줄로 만들어 그다지 유용하지 않습니다.
% 는 일치하는 괄호를 찾아서 이동합니다.
de- 커서에서 단어 끝까지 dE
삭제 (다음 공백까지 삭제할 수도 있음 )
bde- 왼쪽에서 오른쪽 구분 기호로 현재 단어를 삭제합니다.
df [space] -다음 공간까지 삭제
dt. -다음 점까지 삭제
dd- 전체 라인 삭제
ye (또는 yE) -여기에서 단어의 끝까지 텍스트를 잡아 당깁니다.
ce- 단어의 끝을 자릅니다.
안녕 -현재 단어를 복사합니다 ( "hi"가 무엇을하는지 궁금합니다!)
yy- 현재 행을 복사합니다.
cc- 현재 줄을 자르고 S
대신 할 수도 있습니다 . s
현재 캐릭터를 자르고 삽입 모드로 전환하는 하단 캡도 있습니다.
viwy 또는 viwc . 현재 단어를 Yank하거나 변경합니다. w
다음 단어를 계속 선택하려면 여러 번 누르십시오. b
뒤로 이동 하려면 사용하십시오.
vi { -숫자 괄호 안의 모든 텍스트를 선택합니다. va {-{}를 포함한 모든 텍스트 선택
vi (p- () 안의 모든 것을 강조하고 붙여 넣은 텍스트로 바꿉니다.
b and e move the cursor word-by-word, similarly to how Ctrl+Arrows normally do. The definition of word is a little different though, as several consecutive delmiters are treated as one word. If you start at the middle of a word, pressing b will always get you to the beginning of the current word, and each consecutive b will jump to the beginning of the next word. Similarly, and easy to remember, e
gets the cursor to the end of the current, and each subsequent, word.
similar to b
/e
, capital B
and E
move the cursor word-by-word using only whitespaces as delimiters.
capital D (take a deep breath) Deletes the rest of the line to the right of the cursor, same as Shift+End/Del in normal editors (notice 2 keypresses -- Shift+D -- instead of 3)
One that I rarely find in most Vim tutorials, but it's INCREDIBLY useful (at least to me), is the
g; and g,
to move (forward, backward) through the changelist.
Let me show how I use it. Sometimes I need to copy and paste a piece of code or string, say a hex color code in a CSS file, so I search, jump (not caring where the match is), copy it and then jump back (g;) to where I was editing the code to finally paste it. No need to create marks. Simpler.
Just my 2cents.
:%!xxd
Make vim into a hex editor.
:%!xxd -r
Revert.
Warning: If you don't edit with binary (-b), you might damage the file. – Josh Lee in the comments.
gv
Reselects last visual selection.
Sometimes a setting in your .vimrc will get overridden by a plugin or autocommand. To debug this a useful trick is to use the :verbose command in conjunction with :set. For example, to figure out where cindent got set/unset:
:verbose set cindent?
This will output something like:
cindent
Last set from /usr/share/vim/vim71/indent/c.vim
This also works with maps and highlights. (Thanks joeytwiddle for pointing this out.) For example:
:verbose nmap U
n U <C-R>
Last set from ~/.vimrc
:verbose highlight Normal
Normal xxx guifg=#dddddd guibg=#111111 font=Inconsolata Medium 14
Last set from ~/src/vim-holodark/colors/holodark.vim
:%TOhtml
Creates an html rendering of the current file.
Not sure if this counts as dark-corner-ish at all, but I've only just learnt it...
:g/match/y A
will yank (copy) all lines containing "match" into the "a
/@a
register. (The capitalization as A
makes vim append yankings instead of replacing the previous register contents.) I used it a lot recently when making Internet Explorer stylesheets.
Want to look at your :command history?
q:
Then browse, edit and finally to execute the command.
Ever make similar changes to two files and switch back and forth between them? (Say, source and header files?)
:set hidden
:map <TAB> :e#<CR>
Then tab back and forth between those files.
Vim will open a URL, for example
vim http://stackoverflow.com/
Nice when you need to pull up the source of a page for reference.
Macros can call other macros, and can also call itself.
eg:
qq0dwj@qq@q
...will delete the first word from every line until the end of the file.
This is quite a simple example but it demonstrates a very powerful feature of vim
Assuming you have Perl and/or Ruby support compiled in, :rubydo
and :perldo
will run a Ruby or Perl one-liner on every line in a range (defaults to entire buffer), with $_
bound to the text of the current line (minus the newline). Manipulating $_
will change the text of that line.
You can use this to do certain things that are easy to do in a scripting language but not so obvious using Vim builtins. For example to reverse the order of the words in a line:
:perldo $_ = join ' ', reverse split
To insert a random string of 8 characters (A-Z) at the end of every line:
:rubydo $_ += ' ' + (1..8).collect{('A'..'Z').to_a[rand 26]}.join
You are limited to acting on one line at a time and you can't add newlines.
^O and ^I
Go to older/newer position. When you are moving through the file (by searching, moving commands etc.) vim rember these "jumps", so you can repeat these jumps backward (^O - O for old) and forward (^I - just next to I on keyboard). I find it very useful when writing code and performing a lot of searches.
gi
Go to position where Insert mode was stopped last. I find myself often editing and then searching for something. To return to editing place press gi.
gf
put cursor on file name (e.g. include header file), press gf and the file is opened
gF
similar to gf but recognizes format "[file name]:[line number]". Pressing gF will open [file name] and set cursor to [line number].
^P and ^N
Auto complete text while editing (^P - previous match and ^N next match)
^X^L
While editing completes to the same line (useful for programming). You write code and then you recall that you have the same code somewhere in file. Just press ^X^L and the full line completed
^X^F
Complete file names. You write "/etc/pass" Hmm. You forgot the file name. Just press ^X^F and the filename is completed
^Z or :sh
Move temporary to the shell. If you need a quick bashing:
- press ^Z (to put vi in background) to return to original shell and press fg to return to vim back
- press :sh to go to sub shell and press ^D/exit to return to vi back
This is a nice trick to reopen the current file with a different encoding:
:e ++enc=cp1250 %:p
Useful when you have to work with legacy encodings. The supported encodings are listed in a table under encoding-values
(see help
encoding-values
). Similar thing also works for ++ff
, so that you can reopen file with Windows/Unix line ends if you get it wrong for the first time (see help
ff
).
" insert range ip's
"
" ( O O )
" =======oOO=(_)==OOo======
:for i in range(1,255) | .put='10.0.0.'.i | endfor
Typing == will correct the indentation of the current line based on the line above.
Actually, you can do one = sign followed by any movement command. ={movement}
For example, you can use the % movement which moves between matching braces. Position the cursor on the { in the following code:
if (thisA == that) {
//not indented
if (some == other) {
x = y;
}
}
And press =% to instantly get this:
if (thisA == that) {
//not indented
if (some == other) {
x = y;
}
}
Alternately, you could do =a{ within the code block, rather than positioning yourself right on the { character.
imap jj <esc>
Let's see some pretty little IDE editor do column transposition.
:%s/\(.*\)^I\(.*\)/\2^I\1/
Explanation
\(
and \)
is how to remember stuff in regex-land. And \1
, \2
etc is how to retrieve the remembered stuff.
>>> \(.*\)^I\(.*\)
Remember everything followed by ^I
(tab) followed by everything.
>>> \2^I\1
Replace the above stuff with "2nd stuff you remembered" followed by "1st stuff you remembered" - essentially doing a transpose.
Not exactly a dark secret, but I like to put the following mapping into my .vimrc file, so I can hit "-" (minus) anytime to open the file explorer to show files adjacent to the one I just edit. In the file explorer, I can hit another "-" to move up one directory, providing seamless browsing of a complex directory structures (like the ones used by the MVC frameworks nowadays):
map - :Explore<cr>
These may be also useful for somebody. I like to scroll the screen and advance the cursor at the same time:
map <c-j> j<c-e>
map <c-k> k<c-y>
Tab navigation - I love tabs and I need to move easily between them:
map <c-l> :tabnext<enter>
map <c-h> :tabprevious<enter>
Only on Mac OS X: Safari-like tab navigation:
map <S-D-Right> :tabnext<cr>
map <S-D-Left> :tabprevious<cr>
I like to use 'sudo bash', and my sysadmin hates this. He locked down 'sudo' so it could only be used with a handful of commands (ls, chmod, chown, vi, etc), but I was able to use vim to get a root shell anyway:
bash$ sudo vi +'silent !bash' +q
Password: ******
root#
Often, I like changing current directories while editing - so I have to specify paths less.
cd %:h
I often use many windows when I work on a project and sometimes I need to resize them. Here's what I use:
map + <C-W>+
map - <C-W>-
These mappings allow to increase and decrease the size of the current window. It's quite simple but it's fast.
:r! <command>
pastes the output of an external command into the buffer.
Do some math and get the result directly in the text:
:r! echo $((3 + 5 + 8))
Get the list of files to compile when writing a Makefile:
:r! ls *.c
Don't look up that fact you read on wikipedia, have it directly pasted into the document you are writing:
:r! lynx -dump http://en.wikipedia.org/wiki/Whatever
Not an obscure feature, but very useful and time saving.
If you want to save a session of your open buffers, tabs, markers and other settings, you can issue the following:
mksession session.vim
You can open your session using:
vim -S session.vim
Map F5 to quickly ROT13 your buffer:
map <F5> ggg?G``
You can use it as a boss key :).
I just found this one today via NSFAQ:
Comment blocks of code.
Enter Blockwise Visual mode by hitting CTRL-V.
Mark the block you wish to comment.
Hit I (capital I) and enter your comment string at the beginning of the line. (// for C++)
Hit ESC and all lines selected will have // prepended to the front of the line.
I use vim for just about any text editing I do, so I often times use copy and paste. The problem is that vim by default will often times distort imported text via paste. The way to stop this is to use
:set paste
before pasting in your data. This will keep it from messing up.
Note that you will have to issue :set nopaste
to recover auto-indentation. Alternative ways of pasting pre-formatted text are the clipboard registers (*
and +
), and :r!cat
(you will have to end the pasted fragment with ^D).
It is also sometimes helpful to turn on a high contrast color scheme. This can be done with
:color blue
I've noticed that it does not work on all the versions of vim I use but it does on most.
'developer tip' 카테고리의 다른 글
AngularJS 컨트롤러에서보기에 HTML 삽입 (0) | 2020.09.29 |
---|---|
base64 문자열을 어떻게 인코딩하고 디코딩합니까? (0) | 2020.09.29 |
Android에서 내 애플리케이션의 메모리 사용량을 어떻게 확인합니까? (0) | 2020.09.29 |
쉘 명령이 실행될 때 에코하는 방법 (0) | 2020.09.29 |
기존 Heroku 앱과 폴더를 연결하는 방법 (0) | 2020.09.29 |