본문 바로가기
Linux/VIM

vim 코드 자동 완성 coc.nvim

by khd0801 2024. 1. 15.
반응형

 1.  coc.nvim 이란?

coc.nvim은 vim 편집기에서 사용 할 수 있는 플러그인으로 실시간 코드 자동 완성 및 다양한 개발 도구를 통합하는 목적으로 만들어진 플러그인이다. "Conquer of Completion"의 약자로 아래와 같은 기능과 장점을 가지고 있다.

  1. 코드 완성 및 제안
    • 코드 작성시 자동 완성 및 코드 제안 기능을 제공하여 빠르고 정확한 코드를 작성 할 수 있도록 도와준다. 이는 개발자가 코드를 더 빠르게 작성하고, 오타를 줄일 수 있도록 도와준다.
  2. LSP(Language Server Protocol) 지원
    •  LSP를 통한 통합 개발 환경을 지원하여 다양한 언어와 프레임워크에 대한 일관된 기능을 제공한다. 코드 분석, 자동 완성, 오류 표시등을 LSP를 통해 효과적으로 활용 할 수 있다.
  3. 정적 분석 및 오류 표시
    • 코드 작성 중에 발생하는 오류나 경고를 실시간으로 표시하여 개발자가 빠르게 문제를 파악하고 해결할 수 있도록 도와준다. 이는 코드 품질을 향상 시키고 버그를 더 빨리 찾을 수 있도록 도움을 준다.
  4. 코드 스니펫 및 코드 포맷팅
    • 코드 스니펫을 활용하여 자주 사용되는 코드들을 빠르게 삽입 할 수 있다. 

 

 2. .vimrc에 Plugin  추가

call vundle#begin()

    Plugin 'neoclide/coc.nvim', {'branch': 'release'}

call vundle#end()

Plugin 추가 후 vim 켠 후 :PluginInstall 명령을 실행.

 

vim Plugin 사용방법

 

 3.  설정

주의사항

vim의 버전이 v8.1.1719 이상이여야 하며, nodejs이 버전 16.18.0 이상 되어야 한다.

nodejs 설치는 아래 명령어를 이용하여 설치한다.
 $ curl -sL install-node.vercel.app/lts | sudo $SHELL

 

주의사항에 있는 명령어를 입력하면 아래와 같이 nodejs이 설치 된다.

nodejs 설치

$ curl -sL install-node.vercel.app/lts | sudo $SHELL

Configuration
> Version: v20.11.0 (resolved from lts)
> Prefix: /usr/local
> Platform: linux
> Arch: x64
> Tarball URL: https://nodejs.org/dist/v20.11.0/node-v20.11.0-linux-x64.tar.gz
? Install Node.js v20.11.0 to /usr/local? [yN] y
> Installing Node.js, please wait…
✓ Done
 

 

만약 PluginInstall 후 또는 vim 창을 열 때 아래와 같은 에러 메세지가 나온다면 ~/.vim/bundle/coc.nvim 폴더로 들어가서 nmp install 명령어를 실행한다.

[coc.nvim] build/index.js not found, please install dependencies and compile coc.nvim by: npm ci
Press ENTER or type command to continue

 

npm install

~/.vim/bundle/coc.nvim$ npm install

> coc.nvim-master@0.0.82 prepare
> node esbuild.js
added 587 packages, and audited 588 packages in 25s
75 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
npm notice
npm notice New minor version of npm available! 10.2.4 -> 10.3.0
npm notice Changelog: https://github.com/npm/cli/releases/tag/v10.3.0
npm notice Run npm install -g npm@10.3.0 to update!
npm notice

 

위 설치가 끝난뒤 vim 재실행하여 아래와 같은 화면이 뜬다면 설치가 완료된 것이다.

coc.nvim plugin 설치 완료

 

LSP 등록

LSP(Language Server Protocol)는 IDE(Integrated Development Environment)와 Language Server 사이의 데이터 전송 통신규약(프로토콜)이다. 보통 자동 완성, 변수 또는 함수 정의로 이동, 모든 참조 검색등의 기능을 제공한다. 

coc의 Language Server 설치는 명령어 한줄로 비교적 쉽게 설치가 가능한다. 아래 화면과 같이 vim에서 Cocinstall coc-clangd 명령어로 설치가 가능하다.

CoC 언어 서버 설치

 

만약 vim 실행시 아래와 사진과 같은 에러가 발생된다면 clangd가 설치가 안된것이라 sudo apt install clangd 명령어를 통해 clangd를 설치하도록 한다.

clangd가 설치 되어 있지 않음.

 

$ sudo apt install clangd

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
clangd-10 lib32gcc-s1 lib32stdc++6 libc6-i386 libclang-common-10-dev libclang-cpp10 libllvm10
The following NEW packages will be installed:
clangd clangd-10 lib32gcc-s1 lib32stdc++6 libc6-i386 libclang-common-10-dev libclang-cpp10
libllvm10
0 upgraded, 8 newly installed, 0 to remove and 79 not upgraded.
Need to get 35.2 MB of archives.
After this operation, 202 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://kr.archive.ubuntu.com/ubuntu focal/main amd64 libllvm10 amd64 1:10.0.0-4ubuntu1 [15.3 MB]
Get:2 http://kr.archive.ubuntu.com/ubuntu focal/universe amd64 libclang-cpp10 amd64 1:10.0.0-4ubuntu1 [9,944 kB]
Get:3 http://kr.archive.ubuntu.com/ubuntu focal-updates/main amd64 libc6-i386 amd64 2.31-0ubuntu9.14 [2,726 kB]
Get:4 http://kr.archive.ubuntu.com/ubuntu focal-updates/main amd64 lib32gcc-s1 amd64 10.5.0-1ubuntu1~20.04 [49.1 kB]
Get:5 http://kr.archive.ubuntu.com/ubuntu focal-updates/main amd64 lib32stdc++6 amd64 10.5.0-1ubuntu1~20.04 [522 kB]
Get:6 http://kr.archive.ubuntu.com/ubuntu focal/universe amd64 libclang-common-10-dev amd64 1:10.0.0-4ubuntu1 [5,012 kB]
Get:7 http://kr.archive.ubuntu.com/ubuntu focal/universe amd64 clangd-10 amd64 1:10.0.0-4ubuntu1 [1,638 kB]
Get:8 http://kr.archive.ubuntu.com/ubuntu focal/universe amd64 clangd amd64 1:10.0-50~exp1 [2,948 B]
Fetched 35.2 MB in 7s (5,254 kB/s)
Selecting previously unselected package libllvm10:amd64.
(Reading database ... 227657 files and directories currently installed.)
Preparing to unpack .../0-libllvm10_1%3a10.0.0-4ubuntu1_amd64.deb ...
Unpacking libllvm10:amd64 (1:10.0.0-4ubuntu1) ...
Selecting previously unselected package libclang-cpp10.
Preparing to unpack .../1-libclang-cpp10_1%3a10.0.0-4ubuntu1_amd64.deb ...
Unpacking libclang-cpp10 (1:10.0.0-4ubuntu1) ...
Selecting previously unselected package libc6-i386.
Preparing to unpack .../2-libc6-i386_2.31-0ubuntu9.14_amd64.deb ...
Unpacking libc6-i386 (2.31-0ubuntu9.14) ...
Selecting previously unselected package lib32gcc-s1.
Preparing to unpack .../3-lib32gcc-s1_10.5.0-1ubuntu1~20.04_amd64.deb ...
Unpacking lib32gcc-s1 (10.5.0-1ubuntu1~20.04) ...
Selecting previously unselected package lib32stdc++6.
Preparing to unpack .../4-lib32stdc++6_10.5.0-1ubuntu1~20.04_amd64.deb ...
Unpacking lib32stdc++6 (10.5.0-1ubuntu1~20.04) ...
Selecting previously unselected package libclang-common-10-dev.
Preparing to unpack .../5-libclang-common-10-dev_1%3a10.0.0-4ubuntu1_amd64.deb ...
Unpacking libclang-common-10-dev (1:10.0.0-4ubuntu1) ...
Selecting previously unselected package clangd-10.
Preparing to unpack .../6-clangd-10_1%3a10.0.0-4ubuntu1_amd64.deb ...
Unpacking clangd-10 (1:10.0.0-4ubuntu1) ...
Selecting previously unselected package clangd.
Preparing to unpack .../7-clangd_1%3a10.0-50~exp1_amd64.deb ...
Unpacking clangd (1:10.0-50~exp1) ...
Setting up libllvm10:amd64 (1:10.0.0-4ubuntu1) ...
Setting up libc6-i386 (2.31-0ubuntu9.14) ...
Setting up libclang-cpp10 (1:10.0.0-4ubuntu1) ...
Setting up lib32gcc-s1 (10.5.0-1ubuntu1~20.04) ...
Setting up lib32stdc++6 (10.5.0-1ubuntu1~20.04) ...
Setting up libclang-common-10-dev (1:10.0.0-4ubuntu1) ...
Setting up clangd-10 (1:10.0.0-4ubuntu1) ...
Setting up clangd (1:10.0-50~exp1) ...
Processing triggers for man-db (2.9.1-1) ...
Processing triggers for libc-bin (2.31-0ubuntu9.14) ...

 

원하는 다른 Language의 서버를 설치하고 싶다면 아래 링크 내용을 참고하여 설치하면 된다

Coc Language Servers 

coc config

설치가 완료 되었으면, coc.vnim에서 cland를 사용할 수 있도록 config파일을 수정해야 된다.

vim을 실행 한 뒤 :Conconfig 명령어를 입력하고 새로뜬 창에 coc-clangd에 대하여 설정 값을 입력한다.

CocConfig 입력

 

coc-cland 등록

c언어에 대한 등록 설정 값

"languageserver": {
  "clangd": {
    "command": "clangd",
    "rootPatterns": ["compile_flags.txt", "compile_commands.json"],
    "filetypes": ["c", "cc", "cpp", "c++", "objc", "objcpp"]
  }
}

 

다른 languageser에 대한 등록을 하고 싶다면 아래 링크를 참고 하길 바란다.

CoC Language Servers Configuration

Indexing 정보 제공

clangd는 rootPatterns에 명시된 파일의 패턴을 기준으로 프로젝트 전체를 인덱싱하여 정보를 제공한다. 이 패턴을 생성하는 방법은 2가지가 있으면 아래와 같다. 

 

1. Cmake 이용

$  ls

blog-vim cmake coc vim
$ mkdir build
$  cd build/
$  cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON ../blog-vim/
-- The C compiler identification is GNU 9.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/khd0801/work/vim/build
$  cd ../blog-vim/
$  ln -s ../build/compile_commands.json .
$  ls -l compile_commands.json
lrwxrwxrwx 1 khd0801 khd0801 30 1월 28 00:58 compile_commands.json -> ../build/compile_commands.json
 
2. bear 설치 및 사용

$sudo apt install bear

Reading package lists... Done
Building dependency tree
Reading state information... Done
The following NEW packages will be installed:
bear
0 upgraded, 1 newly installed, 0 to remove and 83 not upgraded.
Need to get 13.1 kB of archives.
After this operation, 57.3 kB of additional disk space will be used.
Get:1 http://kr.archive.ubuntu.com/ubuntu focal/universe amd64 bear all 2.4.3-1 [13.1 kB]
Fetched 13.1 kB in 6s (2,356 B/s)
Selecting previously unselected package bear.
(Reading database ... 235859 files and directories currently installed.)
Preparing to unpack .../archives/bear_2.4.3-1_all.deb ...
Unpacking bear (2.4.3-1) ...
Setting up bear (2.4.3-1) ...
Processing triggers for man-db (2.9.1-1) ...

$ bear make

make all-recursive
make[1]: Entering directory '/home/ubuntu/amhello'
Making all in lib
make[2]: Entering directory '/home/ubuntu/amhello/lib'
/bin/bash ../libtool --tag=CC --mode=compile gcc -DHAVE_CONFIG_H -I. -I.. -g -O2 -MT greeting.lo -MD -MP -MF .deps/greeting.Tpo -c -o greeting.lo greeting.c
libtool: compile: gcc -DHAVE_CONFIG_H -I. -I.. -g -O2 -MT greeting.lo -MD -MP -MF .deps/greeting.Tpo -c greeting.c -fPIC -DPIC -o .libs/greeting.o
libtool: compile: gcc -DHAVE_CONFIG_H -I. -I.. -g -O2 -MT greeting.lo -MD -MP -MF .deps/greeting.Tpo -c greeting.c -o greeting.o >/dev/null 2>&1
mv -f .deps/greeting.Tpo .deps/greeting.Plo
/bin/bash ../libtool --tag=CC --mode=link gcc -g -O2 -version-info 0:0:0 -o libgreeting.la -rpath /usr/local/lib greeting.lo
libtool: link: gcc -shared -fPIC -DPIC .libs/greeting.o -g -O2 -Wl,-soname -Wl,libgreeting.so.0 -o .libs/libgreeting.so.0.0.0
libtool: link: (cd ".libs" && rm -f "libgreeting.so.0" && ln -s "libgreeting.so.0.0.0" "libgreeting.so.0")
libtool: link: (cd ".libs" && rm -f "libgreeting.so" && ln -s "libgreeting.so.0.0.0" "libgreeting.so")
libtool: link: ar cr .libs/libgreeting.a greeting.o
libtool: link: ranlib .libs/libgreeting.a
...

 

 

 

.vimrc 설정

" Some servers have issues with backup files, see #649
set nobackup

" Having longer updatetime (default is 4000 ms = 4s) leads to noticeable
" delays and poor user experience
set updatetime=1000

" Always show the signcolumn, otherwise it would shift the text each time
" diagnostics appear/become resolved
set signcolumn=yes

" Use tab for trigger completion with characters ahead and navigate
" NOTE: There's always complete item selected by default, you may want to enable
" no select by `"suggest.noselect": true` in your configuration file
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config
inoremap <silent><expr> <TAB>
      \ coc#pum#visible() ? coc#pum#next(1) :
      \ CheckBackspace() ? "\<Tab>" :
      \ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"

" Make <CR> to accept selected completion item or notify coc.nvim to format
" <C-g>u breaks current undo, please make your own choice
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
                              \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

function! CheckBackspace() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion
inoremap <silent><expr> <C-@> coc#refresh()

" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window
nnoremap <silent> S :call ShowDocumentation()<CR>

function! ShowDocumentation()
  if CocAction('hasProvider', 'hover')
    call CocActionAsync('doHover')
  else
    call feedkeys('K', 'in')
  endif
endfunction

" Symbol renaming
nmap <leader>rn <Plug>(coc-rename)

" Remap keys for applying refactor code actions
nmap <silent> <leader>re <Plug>(coc-codeaction-refactor)
xmap <silent> <leader>r  <Plug>(coc-codeaction-refactor-selected)
"nmap <silent> <leader>r  <Plug>(coc-codeaction-refactor-selected)

" Run the Code Lens action on the current line
nmap <leader>cl  <Plug>(coc-codelens-action)

" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)


" Use CTRL-S for selections ranges
" Requires 'textDocument/selectionRange' support of language server
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)

" Add (Neo)Vim's native statusline support
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Mappings for CoCList
" Show all diagnostics
nnoremap <silent><nowait> <space>a  :<C-u>CocList diagnostics<cr>
" Manage extensions
nnoremap <silent><nowait> <space>e  :<C-u>CocList extensions<cr>
" Show commands
nnoremap <silent><nowait> <space>c  :<C-u>CocList commands<cr>
" Find symbol of current document
nnoremap <silent><nowait> <space>o  :<C-u>CocList outline<cr>
" Search workspace symbols
nnoremap <silent><nowait> <space>s  :<C-u>CocList -I symbols<cr>
" Do default action for next item
nnoremap <silent><nowait> <space>j  :<C-u>CocNext<CR>
" Do default action for previous item
nnoremap <silent><nowait> <space>k  :<C-u>CocPrev<CR>
" Resume latest coc list
nnoremap <silent><nowait> <space>p  :<C-u>CocListResume<CR>

 

Line Number 설정 설명
2번째 줄 set nobackup vim으로 연 파일의 backup 파일을 만들지 않는다.
Default 셋팅이 nobackup이며, set backup 설정시 backup 파일을 생성.
ex) vim main.c 열고 저장할 경우 같은 디렉토리 안에 main.c~ backup 파일이 생성 된다.
6번째 줄 set updatetime=1000 vim 자동 저장과 관련된 동작 옵션으로 updatetime에 설정된 시간 간격(ms)으로 .swp 파일에 자동 저장을 수행, 현재 설정은 사용자가 마지막으로 입력한 후 1000ms(1초)동안 입력이 없으면 vim은 변경된 내용을 .swp 파일에 기록한다.
17~21번째 줄 inoremap <silent><expr> <TAB>
...
...
inoremap <expr><S-TAB> 
...
Tab키와 Shift + Tab키를 이용하여 자동 완성 추천 목록의 위, 아래로 이동이 가능하다.
<silent> : 해당 key mapping sequence가 실행 될 때, vim에 어떤 메시지도 보여주지 않는다.
<expr> : <TAB> 키를 눌렀을 때, <TAB> 키 뒤의 조건부 실행 구문들을 실행한다.
25~26번째 줄 inoremap <silent><expr> <CR>
...
자동 완성 추천 목록의 Highlight 부분에서 엔터 입력시 정의된데로 자동 완성된다.
28~31번째 줄 function! CheckBackspace() 
...
endfunction
17~21번 째 줄에서 쓰인 CheckBackspace() 함수에 대한 내용이다.
34번째 줄   inoremap <silent><expr>
<C-@> coc#refresh()
자동 추천 항목을 새롭게 갱신한다.
38번째 줄 nmap <silent> [g <Plug>
(coc-diagnostic-prev)

현재 커서 위치에서 위쪽으로 diagnostic 탐색을 진행한다. 
39번째 줄 nmap <silent> ]g <Plug>
(coc-diagnostic-next)
현재 커서 위치에서 아래쪽으로 diagnostic 탐색을 진행한다.
42번째 줄 nmap <silent> gd <Plug>
(coc-definition)
변수 또는 함수가 정의된 곳으로 이동한다.
43번째 줄 nmap <silent> gy <Plug>(coc-type-definition) 구조체 변수의 변수명에서 gy를 누르게 되면 해당 구조체가 저의된 곳으로 이동 한다.
44번째 줄 nmap <silent> gr <Plug>(coc-references) 화면 아래에 window를 하나 떠 띄우고 해당 되는 변수 또는 함수의 위치 정보를 알려준다.
47번째 줄   nnoremap <silent> K :call ShowDocumentation()<CR> 변수나 함수의 정보를 미니창을 띄워 알려준다.
49~55번째 줄 function! ShowDocumentation()
...
endfunction
47째 줄의 ShowDocumentations 함수의 구현 부.
61번째 줄  nmap <leader>rn <Plug>(coc-rename) 변수명이나 함수명의 이름을 rename 할 수 있다. 
해당 기능으로 수정하면 전체 코드에 반영이 된다.
64~66번째 줄 nmap <silent> <leader>re <Plug>(coc-codeaction-refactor)
xmap <silent> <leader>r  <Plug>(coc-codeaction-refactor-selected)
nmap <silent> <leader>r  <Plug>(coc-codeaction-refactor-selected)

코드 리팩토링 기능으로 C언어에서는 그다지 효용성을 느끼지 못한다.
69번째 줄   nmap <leader>cl  <Plug>(coc-codelens-action) codelens 기능.
73번째 줄 xmap if <Plug>(coc-funcobj-i) VISUAL 모드에서 cusor가 function이름 또는 안에 있을 때 "if"키를 차례로 누르면 function 안의 내용들이 VISUAL 모드로 전체 선택한다.
74번째 줄 omap if <Plug>(coc-funcobj-i) operation + "if" 기능으로 예를 들어 function 이름에서 "dif" 키를 차례로 누르게 되면 function 안 내용들이 다 삭제 된다.
function 내용을 다 복사하려면 "yif"키를 차례로 누르면 된다.
75번째 줄 xmap af <Plug>(coc-funcobj-a) xxline의 내용과 유사하며, function의 선언부까지 포함되어 선택된다.
76번째 줄 omap af <Plug>(coc-funcobj-a) xxline의 내용과 유사하며, fucntions의 선언부까지 포함되어진다.
77번째 줄 xmap ic <Plug>(coc-classobj-i) 클래스 또는 구조체의 내용을 VISUAL 모드로 전체 선택한다.
78번째 줄 omap ic <Plug>(coc-classobj-i) operation + "if" 기능으로 예를 들어 구조체 이름에서 "dif" 키를 차례로 누르게 되면 구조체 안 내용들이 다 삭제 된다.
구조체 내용을 다 복사하려면 "yif"키를 차례로 누르면 된다.
79번째 줄 xmap ac <Plug>(coc-classobj-a) xxline의 내용과 유사하며, 구조체의 선언부까지 포함되어 선택된다.
80번째 줄 omap ac <Plug>(coc-classobj-a) xxline의 내용과 유사하며, 구조체의 선언부까지 포함되어진다.
85~86번째 줄 nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)
선택한 함수의 함수 선언과 전체 내용을 VISUAL 모드로 선택 함.
함수 내의 함수 호출에서 해당 기능을 실행하면 해당 함수의 함수명만 VISUAL 모드로 선택 됨.
95번째 줄 nnoremap <silent><nowait> <space>a  :<C-u>CocList diagnostics<cr> space+a 키를 누르면 현재 파일의 diagnostics 발생 리스트를 화면 아래에 새 창을 띄워 보여 줌.
97번째 줄 nnoremap <silent><nowait> <space>e  :<C-u>CocList extensions<cr> space+e 키를 누르면 현재 설치된 extensions의 리스트들을 화면 아래에 새 창을 띄워 보염 줌.
99번째 줄 nnoremap <silent><nowait> <space>c  :<C-u>CocList commands<cr> space+c 키를 누르면 coc.nvim에서 실행 가능한 commands의 리스트를 화면 아래에 새 창을 띄워 보여 줌.
101번째 줄 nnoremap <silent><nowait> <space>o  :<C-u>CocList outline<cr> space+o 키를 누르면 현재 파일의 함수와, 전역변수의 심볼 정보 리스트들을 화면 아래 새 창을 띄워 보여 줌.
103번째 줄 nnoremap <silent><nowait> <space>s  :<C-u>CocList -I symbols<cr> workspace에 있는 심볼 정보 리스트들을 화면 아래 새 창을 띄워 보여 줌.
105번째 줄 nnoremap <silent><nowait> <space>j  :<C-u>CocNext<CR> 이전에 실행 했었던 Coc관련 액션을 재 실행 한다.
107번째 줄 nnoremap <silent><nowait> <space>k  :<C-u>CocPrev<CR> 이전 실행 했었던 CoC 관련 액션의 다음 액션을 재 실행 한다.
109번째 줄   nnoremap <silent><nowait> <space>p  :<C-u>CocListResume<CR> 최근 실행한 Coc list의 내용을 재 실행 한다.

 

ubuntu 20.04에서 apt install clangd로 설치하면 clangd-10이 설치되게 된다. 이렇게 되면 43번쨰 줄의 gy(coc-type-definition)의 기능은 clangd의 버전이 낮아서 실행이 안된다. coc-type-definition의 기능을 활용하고 싶다면 버전이 높은 clangd를 설치하길 바란다.

 

CLAND의 버전 업 방법

$ wget https://apt.llvm.org/llvm.sh

$ sudo chmod u+x llvm.sh

$ sudo ./llvm.sh 17

$ cland-17 --version

Ubuntu clangd version 17.0.6 (++20231208085846+6009708b4367-1~exp1~20231208085949.74)
Features: linux
Platform: x86_64-pc-linux-gnu

$ cd /usr/bin/

$ sudo rm -rf clangd

$ ln -s clangd-17 clangd

 

 

keymaping에 대해서 더 자세히 알고 싶다면 아래 블로그를 참고하길 바란다.

관련글

 

 4. 현재까지의 설정이 적용된 .vimrc 내용

"-----------------------------------------------------------------------"
" Vundle 환경설정
"------------------------------------------------------------------------"
filetype off                   " required!
set shell=/bin/bash
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
	" let Vundle manage Vundle
	" required!
	Plugin 'VundleVim/Vundle.vim'

	" vim 하단에 파일 정보 띄우기
	Plugin 'vim-airline/vim-airline'
	Plugin 'vim-airline/vim-airline-themes'
   
	"vim corlor/scheme 수정
	Plugin 'morhetz/gruvbox'
	
	" 파일 및 폴더 탐색
	Plugin 'ctrlpvim/ctrlp.vim'

	" vim 사용중 git 명령어 사용
	Plugin 'tpope/vim-fugitive'

	"vim 하단에 커서가 있는 함수나 변수의 정의 부분을 출력
	Plugin 'wesleyche/srcexpl'

	"명령어 자동완성 플러그인(inc + <C-a> : #include<>)
	Plugin 'SirVer/ultisnips'
	Plugin 'honza/vim-snippets'

	" [] {} 등 괄호 입력시 자동으로 닫아주는 플러그인
	Plugin 'jiangmiao/auto-pairs' 

	Plugin 'junegunn/fzf', { 'do': { -> fzf#install() } }
	Plugin 'junegunn/fzf.vim'

	Plugin 'preservim/nerdtree'
	Plugin 'Xuyuanp/nerdtree-git-plugin'
	Plugin 'ryanoasis/vim-devicons'
	Plugin 'tiagofumo/vim-nerdtree-syntax-highlight'

	Plugin 'neoclide/coc.nvim', {'branch': 'release'}

	" ...
call vundle#end()
filetype plugin indent on     " required!
	"
	" Brief help
	" :BundleList          - list configured bundles
	" :BundleInstall(!)    - install(update) bundles
	" :BundleSearch(!) foo - search(or refresh cache first) for foo
	" :BundleClean(!)      - confirm(or auto-approve) removal of unused bundles
	"
	" see :h vundle for more details or wiki for FAQ
	" NOTE: comments after Bundle command are not allowed..

"-----------------------------------------------------------------------"
"vim 환경설정
"-----------------------------------------------------------------------"

	" Vim 전용 기능 사용
	set nocompatible "Vim Using

	"파일 타입 설정
	set encoding=utf-8
	set fencs=utf-8,cp949,cp932,euc-jp,shift-jis,big5,ucs-2le,latin1

	" 명령어 기록 갯수
	set hi=1000

	" 백스페이스 사용
	set bs=indent,eol,start

	" 오른쪽 하단 커서 위치 항상 보이기
	set ru "same ruler

	" 줄번호 표시
	set nu

	" 줄 번호 표시 너비 설정
	set nuw=5

	" 탭 크기 설정
	set ts=4 "same tabstop
	set sw=4 "same shiftwidth
	set sts=0 "same softtabstop

	autocmd FileType make setlocal noexpandtab "Makefile은 tab 문법이기 때문에 스페이스 대체 안함.
	" 탭 >> 공백 변환 사용안함
	"set noet

	" 자동 줄바꿈 안함
	"set nowrap
	set linebreak
	set showbreak=+++\

	" 들여쓰기 설정
	set autoindent
	set cindent

	" 스마트 셋팅
	set smartcase
	set smarttab
	set smartindent

	" magic 기능 사용
	set magic

	" 이동 동작시 줄의 시작으로 자동 이동
	set sol

	" 비쥬얼 모드 동작 설정
	set sel=exclusive

	" 괄호짝 찾기에서 <> 도 찾도록 추가
	set mps+=<:>

	" 검색어 강조
	set hls

	" 검색시 파일 끝에서 되돌리기 안함
	set nows

	" 스마트한 대소문자 구별 기능 사용
	set scs

	"대소문자 구분(구분 없이 할 때 i 옵션 또는 ignorecase)
	set noignorecase

	" 항상 status 라인을 표시
	set ls=2

	"파일 형식에 따른 신택스 하이라이팅 켜기
	sy enable

	"괄호 매치
	set showmatch

	"마우스 자동
	set mouse=a

	"클립보드 복사
	"set clipboard=unnamed "use OS clipboard
	set clipboard=unnamedplus "use OS clipboard

	" 키워드 입력시 점진적 검색
	set incsearch
	set spell

"-----------------------------------------------------------------------"
" User Key Setting
"-----------------------------------------------------------------------"
let mapleader = ","

" 새로운 파일을 열때 사용, 경로를 입력해야 한다. 
nmap <leader>n :e
" 가로로 새로운 윈도우를 열 때 사용, 파일 경로 입력 필요
nmap <leader>s :sp
" 세로로 새로운 윈도우를 열 때 사용, 파일 경로 입력 필요
nmap <leader>v :vsp
" 다음 버퍼로 이동
nnoremap <leader>z :bp<CR>
" 이전 버퍼로 이동
nnoremap <leader>x :bn<CR>
" 현재 버퍼를 닫고 이전 버퍼로 이동
nmap <leader>bz :bp <BAR> bd #<CR>
" 모든 버퍼와 각 버퍼 상태 출력
nmap <leader>bl :ls<CR>

"fzf excute
nmap <leader>f :FZF<cr>

"Rg excute
"Input Pattern
nmap <leader>r :RG<Space>
"Input cursor location
nmap <leader>R :RG <C-R>=expand("<cword>")<CR><CR>

" Key Setting - resize windows
nnoremap <silent> <Leader>= :exe "resize +3"<CR>
nnoremap <silent> <Leader>- :exe "resize -3"<CR>
nnoremap <silent> <Leader>] :exe "vertical resize +8"<CR>
nnoremap <silent> <Leader>[ :exe "vertical resize -8"<CR>

nnoremap <silent> <Leader>+ :exe "resize " . (winheight(0) * 3/2)<CR>
nnoremap <silent> <Leader>_ :exe "resize " . (winheight(0) * 2/3)<CR>
nnoremap <silent> <Leader>} :exe "vertical resize " . (winheight(0) * 3/2)<CR>
nnoremap <silent> <Leader>{ :exe "vertical resize " . (winheight(0) * 2/3)<CR>

nnoremap K kzz
nnoremap J jzz

nnoremap <Leader>h :noh<CR>

"-----------------------------------------------------------------------"
" User  환경설정
"-----------------------------------------------------------------------"
" F2 [], {} 괄호에 대한 폴딩 실행
nmap <F2> v]}zf
nmap <F3> :Git blame<cr>
" F4 누를 경우 컴파일(Makeile 있어야 함.)
nmap <F4> :w<cr> : make<cr> : ccl<cr>  cw<cr>
" F5 누를시 현재 라인 주석, 범위 설정 후 누르면 범위 주석
nmap <F5> :norm I//<cr>
" F6 누를시 주석 해제
nmap <F6> :norm ^xx<cr>
" F7 key = Tag List Toggle
nmap <F7> :TlistToggle<CR>
" F8 key = SrcExpl Toggle
nmap <F8> :SrcExplToggle<CR>
"nmap  <F9> :NERDTreeToggle<CR>	" F9 Key = NERD Tree Toggle
"nmap <F10> :let g:view_source = 0<CR>
nmap <F10> :!rm -rf cscope.files <CR> :!find . 
	\ \( -name '*.c' -o -name '*.cpp' -o -name '*.cc'
	\ -o -name '*.h' -o -name '*.s' -o -name '*.S' \) 
	\ -print > cscope.files <CR> :!cscope -i cscope.files <CR><CR>
" F12 tags 생성
nmap <F12> :!ctags -R --c++-kinds=+p --fields=+iaS --extra=+q ./ <CR><CR>

"----------------------------------------------------------------------"
" AirLine
"----------------------------------------------------------------------"
set laststatus=2
let g:airline#extensions#tabline#enabled = 1 "버퍼 목록 켜기
let g:airline#extensions#tabline#left_sep = ' '
let g:airline#extensions#tabline#left_alt_sep = '|'
" 파일명만 출력
let g:airline#extensions#tabline#fnamemod = ':t'
let g:airline_highlighting_cache = 1

let g:airline_powerline_fonts = 1
let g:airline_theme= 'minimalist'
"let g:airline_section_y = ''
"let g:airline_section_warning= '' "마지막 status창 사용 안함
" 버퍼 목록 켜기
" 이 옵션은 버퍼를 수정한 직후 버퍼를 감춰지도록 한다.
" 이 방법으로 버퍼를 사용하려면 거의 필수다.
set hidden


"----------------------------------------------------------------------"
" gruvbox 설정
"----------------------------------------------------------------------"
set background=dark
let g:gruvbox_contrast_dark = 'soft'
"let g:gruvbox_contrast_light = 'soft'
"let g:gruvbox_transparent_bg = '1'
let g:gruvbox_italic = 1
"let g:gruvbox_underline=1
"let g:gruvbox_undercurl=1
"let g:gruvbox_termcolors=16
"let g:gruvbox_number_column='aqua'
"let g:gruvbox_sign_column='aqua'
"let g:gruvbox_color_column='aqua'

" Force to use underline for spell check results
augroup SpellUnderline
  autocmd!
  autocmd ColorScheme *
    \ highlight SpellBad
    \   cterm=Underline
    \   ctermfg=NONE
    \   ctermbg=NONE
    \   term=Reverse
    \   gui=Undercurl
    \   guisp=Red
  autocmd ColorScheme *
    \ highlight SpellCap
    \   cterm=Underline
    \   ctermfg=NONE
    \   ctermbg=NONE
    \   term=Reverse
    \   gui=Undercurl
    \   guisp=Red
  autocmd ColorScheme *
    \ highlight SpellLocal
    \   cterm=Underline
    \   ctermfg=NONE
    \   ctermbg=NONE
    \   term=Reverse
    \   gui=Undercurl
    \   guisp=Red
  autocmd ColorScheme *
    \ highlight SpellRare
    \   cterm=Underline
    \   ctermfg=NONE
    \   ctermbg=NONE
    \   term=Reverse
    \   gui=Undercurl
    \   guisp=Red
  augroup END
set termguicolors
colorscheme gruvbox


"----------------------------------------------------------------------"
" ctrlp.vim 설정(파일 탐색 속도 향상)
"----------------------------------------------------------------------"
set wildignore+=*/tmp/*,*.so,*.a,*.swp,*.zip,*.obj  " MacOSX/Linux
set wildignore+=*\\tmp\\*,*.swp,*.zip,*.exe  		" Windows

let g:ctrlp_custom_ignore = '\v[\/]\.(git|hg|svn)$'
let g:ctrlp_custom_ignore = {
  \ 'dir':  '\.git$\|public$\|log$\|tmp$\|vendor$',
  \ 'file': '\v\.(exe|so|dll|a)$',
  \ 'link': 'some_bad_symbolic_links'
\ }
let g:ctrlp_max_files = 10000
let g:ctrlp_max_depth = 30
let g:ctrlp_follow_symlinks = 1
"let g:ctrlp_user_command = ['.git', 'cd %s && git ls-files -co --exclude-standard']
"let g:ctrlp_use_readdir = 0
let g:ctrlp_root_markers = ['ctrlp-marker']

" <c-f>, <c-b> 모드 변환(MRU(Most Recently Used)내 검색, file 전체 검색, buffers내 검색)
" <c-d> path내 검색어가 포함되어 검색 또는 오직 파일내 검색어만 포함 검색 
" <c-r> 정규 표현식 모드 전환(검색어와 완전히 일치한 파일만 보여 줌)
" <c-j>, <c-k> 검색결과내 커서 위아래 이동
" <c-t>, <c-v>, <c-x> 파일을 새로운 tab으로 열거나 창을 분활하여 파일을 염.
" <c-n>, <n-p> 검색 history의 next/previous 문자열 선택
" <c-z>, <c-o> 검색된 결과물에 <c-z>로 마크를 하고 <c-o>로 오픈(멀티마크 가능) 
" <c-y> 검색입력어로 된 파일을 만든다. 파일 위치는 검색 폴더의 최상위 위치
" :help ctrlp-mappings 키 맵핑에 관한 설명


"-----------------------------------------------------------------------"
" Source Explorer 환경설정
"-----------------------------------------------------------------------"
nmap <F8> :SrcExplToggle<CR>		" F8 key = SrcExpl TOggle

let g:SrcExpl_winHeight = 12		" SrcExpl 윈도우 높이 지정
let g:SrcExpl_refreshTime = 100		" refreshing time = 100ms
let g:SrcExpl_jumpKey = "<ENTER>"		" 해당 definition으로 jump
let g:SrcExpl_gobackKey = "<SPACE>"		" back
let g:SrcExpl_pluginList = [
        \ "__Tag_List__",
        \ "_NERD_tree_",
        \ "Source_Explorer"
        \ ]

" // The color schemes used by Source Explorer. There are five color schemes
" // supported for now - Red, Cyan, Green, Yellow and Magenta. Source Explorer
let g:SrcExpl_colorSchemeList = [
        \ "Cyan",
    \ ]

" // Enable/Disable the local definition searching, and note that this is not
" // guaranteed to work, the Source Explorer doesn't check the syntax for now.
" // It only searches for a match with the keyword according to command 'gd'
let g:SrcExpl_searchLocalDef = 1 

" // Workaround for Vim bug @https://goo.gl/TLPK4K as any plugins using autocmd for
" // BufReadPre might have conflicts with Source Explorer. e.g. YCM, Syntastic etc.
let g:SrcExpl_nestedAutoCmd = 1

" // Do not let the Source Explorer update the tags file when opening
let g:SrcExpl_isUpdateTags = 0

" // Use 'Exuberant Ctags' with '--sort=foldcase -R .' or '-L cscope.files' to
" // create/update the tags file
let g:SrcExpl_updateTagsCmd = "ctags --sort=foldcase -R ."

" // Set "<F12>" key for updating the tags file artificially
let g:SrcExpl_updateTagsKey = "<F12>"

" // Set "<F3>" key for displaying the previous definition in the jump list
let g:SrcExpl_prevDefKey = "<S-J>"

" // Set "<F4>" key for displaying the next definition in the jump list
let g:SrcExpl_nextDefKey = "<S-K>"


"-----------------------------------------------------------------------"
" ultisnips&vim-snippets Trigger Configuration
"-----------------------------------------------------------------------"
" Trigger configuration. You need to change this to something other than <tab>
" if you use one of the following:
" " - https://github.com/Valloric/YouCompleteMe
" " - https://github.com/nvim-lua/completion-nvim
let g:UltiSnipsExpandTrigger="<C-a>"
let g:UltiSnipsJumpForwardTrigger="<tab>"
let g:UltiSnipsJumpBackwardTrigger="<s-tab>"
" If you want :UltiSnipsEdit to split your window.
let g:UltiSnipsEditSplit="vertical"
" let g:UltiSnipsSnippetDirectories = ['~/.vim/UltiSnips']


"-----------------------------------------------------------------------"
" fzf layout
"-----------------------------------------------------------------------"
" An action can be a reference to a function that processes selected lines
function! s:build_quickfix_list(lines)
  call setqflist(map(copy(a:lines), '{ "filename": v:val, "lnum": 1 }'))
  copen
  cc
endfunction

let g:fzf_action = {
  \ 'ctrl-q': function('s:build_quickfix_list'),
  \ 'ctrl-t': 'tab split',
  \ 'ctrl-x': 'split',
  \ 'ctrl-v': 'vsplit' }

"let g:fzf_layout = { 'window': { 'width': 0.9, 'height': 0.9,'yoffset':0.5,'xoffset': 0.5 } }

" - down / up / left / right
"let g:fzf_layout = { 'left': '50%' }

let $FZF_DEFAULT_OPTS = '--layout=reverse --inline-info'
let $FZF_DEFAULT_COMMAND="rg --files --hidden --glob '!.git/**'"

" Customize fzf colors to match your color scheme
" - fzf#wrap translates this to a set of `--color` options
let g:fzf_colors =
\ { 'fg':      ['fg', 'Normal'],
  \ 'bg':      ['bg', 'Normal'],
  \ 'hl':      ['fg', 'Comment'],
  \ 'fg+':     ['fg', 'CursorLine', 'CursorColumn', 'Normal'],
  \ 'bg+':     ['bg', 'CursorLine', 'CursorColumn'],
  \ 'hl+':     ['fg', 'Statement'],
  \ 'info':    ['fg', 'PreProc'],
  \ 'border':  ['fg', 'Ignore'],
  \ 'prompt':  ['fg', 'Conditional'],
  \ 'pointer': ['fg', 'Exception'],
  \ 'marker':  ['fg', 'Keyword'],
  \ 'spinner': ['fg', 'Label'],
  \ 'header':  ['fg', 'Comment'] }

"Get Files
command! -bang -nargs=? -complete=dir Files
    \ call fzf#vim#files(<q-args>, fzf#vim#with_preview({'options': ['--layout=reverse', '--inline-info']}), <bang>0)

" Get text in files with Rg
" Make Ripgrep ONLY search file contents and not filenames
" Ripgrep advanced
function! RipgrepFzf(query, fullscreen)
  let command_fmt = "rg --column --line-number --no-heading --color=always --glob '!tags' --smart-case --case-sensitive %s || true"
  let initial_command = printf(command_fmt, shellescape(a:query))
  let reload_command = printf(command_fmt, '{q}')
  let spec = {'options': ['--phony', '--query', a:query, '--bind', 'change:reload:'.reload_command]}
  call fzf#vim#grep(initial_command, 1, fzf#vim#with_preview(spec), a:fullscreen)
endfunction

command! -nargs=* -bang RG call RipgrepFzf(<q-args>, <bang>0)


"-----------------------------------------------------------------------"
" NERD Tree Key 설정
"-----------------------------------------------------------------------"
let NERDTreeWinPos = "left"		" NERD Tree위치 = 왼쪽
nmap  <C-f> :NERDTreeFind<CR> " Ctrl + f  NERDtree Toggle
nmap  <C-e> :NERDTreeToggle<CR> " Ctrl + e  NERDtree Toggle

"-----------------------------------------------------------------------"
" NERDTree 환경 설정
"-----------------------------------------------------------------------"
let g:NERDTreeGitStatusIndicatorMapCustom = {
	\ 'Modified'  :'✹',
	\ 'Staged'    :'✚',
	\ 'Untracked' :'✭',
	\ 'Renamed'   :'➜',
	\ 'Unmerged'  :'═',
	\ 'Deleted'   :'✖',
	\ 'Dirty'     :'✗',
	\ 'Ignored'   :'☒',
	\ 'Clean'     :'✔︎',
	\ 'Unknown'   :'?',
\ }
let g:NERDTreeDirArrowCollapsible = ''
let g:NERDTreeDirArrowExpandable = ''
let g:DevIconsDefaultFolderOpenSymbol = ''
let g:WebDevIconsUnicodeDecorateFolderNodesDefaultSymbol = ''

"let g:NERDTreeDirArrowCollapsible = ''
"let g:NERDTreeDirArrowExpandable = ''

" you can add these colors to your .vimrc to help customizing
let s:brown = "905532"
let s:aqua =  "3AFFDB"
let s:blue = "689FB6"
let s:darkBlue = "44788E"
let s:purple = "834F79"
let s:lightPurple = "834F79"
let s:red = "AE403F"
let s:beige = "F5C06F"
let s:yellow = "F09F17"
let s:orange = "D4843E"
let s:darkOrange = "F16529"
let s:pink = "CB6F6F"
let s:salmon = "EE6E73"
let s:green = "8FAA54"
let s:lightGreen = "31B53E"
let s:white = "FFFFFF"
let s:rspec_red = 'FE405F'
let s:git_orange = 'F54D27'

let g:NERDTreeExtensionHighlightColor = {} " this line is needed to avoid error
let g:NERDTreeExactMatchHighlightColor = {} " this line is needed to avoid error
let g:NERDTreePatternMatchHighlightColor = {} " this line is needed to avoid error

let g:NERDTreeExtensionHighlightColor['c'] = s:lightGreen " sets the color of css files to blue
let g:NERDTreeExtensionHighlightColor['h'] = s:brown " sets the color of css files to blue
let g:NERDTreeExactMatchHighlightColor['.gitignore'] = s:git_orange " sets the color for .gitignore files
let g:NERDTreePatternMatchHighlightColor['.*_spec\.rb$'] = s:rspec_red " sets the color for files ending with _spec.rb

let g:WebDevIconsDefaultFolderSymbolColor = s:beige " sets the color for folders that did not match any rule
let g:WebDevIconsDefaultFileSymbolColor = s:blue " sets the color for files that did not match any rule

let g:NERDTreeFileExtensionHighlightFullName = 1
let g:NERDTreeExactMatchHighlightFullName = 1
let g:NERDTreePatternMatchHighlightFullName = 1
" Exit Vim if NERDTree is the only window remaining in the only tab.
autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | quit | endif

" If another buffer tries to replace NERDTree, put it in the other window, and bring back NERDTree.
autocmd BufEnter * if bufname('#') =~ 'NERD_tree_\d\+' && bufname('%') !~ 'NERD_tree_\d\+' && winnr('$') > 1 |
    \ let buf=bufnr() | buffer# | execute "normal! \<C-W>w" | execute 'buffer'.buf | endif

"-----------------------------------------------------------------------"
" coc.nvim 환경 설정
"-----------------------------------------------------------------------"
" Some servers have issues with backup files, see #649
set nobackup

" Having longer updatetime (default is 4000 ms = 4s) leads to noticeable
" delays and poor user experience
set updatetime=300

" Use tab for trigger completion with characters ahead and navigate
" NOTE: There's always complete item selected by default, you may want to enable
" no select by `"suggest.noselect": true` in your configuration file
" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
" other plugin before putting this into your config
inoremap <silent><expr> <TAB>
      \ coc#pum#visible() ? coc#pum#next(1) :
      \ CheckBackspace() ? "\<Tab>" :
      \ coc#refresh()
inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"

" Make <CR> to accept selected completion item or notify coc.nvim to format
" <C-g>u breaks current undo, please make your own choice
inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
                              \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"

function! CheckBackspace() abort
  let col = col('.') - 1
  return !col || getline('.')[col - 1]  =~# '\s'
endfunction

" Use <c-space> to trigger completion
inoremap <silent><expr> <C-@> coc#refresh()

" Use `[g` and `]g` to navigate diagnostics
" Use `:CocDiagnostics` to get all diagnostics of current buffer in location list
nmap <silent> [g <Plug>(coc-diagnostic-prev)
nmap <silent> ]g <Plug>(coc-diagnostic-next)

" GoTo code navigation
nmap <silent> gd <Plug>(coc-definition)
nmap <silent> gy <Plug>(coc-type-definition)
nmap <silent> gr <Plug>(coc-references)

" Use K to show documentation in preview window
nnoremap <silent> S :call ShowDocumentation()<CR>

function! ShowDocumentation()
  if CocAction('hasProvider', 'hover')
    call CocActionAsync('doHover')
  else
    call feedkeys('K', 'in')
  endif
endfunction

" Highlight the symbol and its references when holding the cursor
autocmd CursorHold * silent call CocActionAsync('highlight')

" Symbol renaming
nmap <leader>rn <Plug>(coc-rename)

" Remap keys for applying refactor code actions
nmap <silent> <leader>re <Plug>(coc-codeaction-refactor)
"xmap <silent> <leader>r  <Plug>(coc-codeaction-refactor-selected)
nmap <silent> <leader>r  <Plug>(coc-codeaction-refactor-selected)

" Run the Code Lens action on the current line
nmap <leader>cl  <Plug>(coc-codelens-action)

" Map function and class text objects
" NOTE: Requires 'textDocument.documentSymbol' support from the language server
xmap if <Plug>(coc-funcobj-i)
omap if <Plug>(coc-funcobj-i)
xmap af <Plug>(coc-funcobj-a)
omap af <Plug>(coc-funcobj-a)
xmap ic <Plug>(coc-classobj-i)
omap ic <Plug>(coc-classobj-i)
xmap ac <Plug>(coc-classobj-a)
omap ac <Plug>(coc-classobj-a)

" Use CTRL-S for selections ranges
" Requires 'textDocument/selectionRange' support of language server
nmap <silent> <C-s> <Plug>(coc-range-select)
xmap <silent> <C-s> <Plug>(coc-range-select)

" Add (Neo)Vim's native statusline support
" NOTE: Please see `:h coc-status` for integrations with external plugins that
" provide custom statusline: lightline.vim, vim-airline
set statusline^=%{coc#status()}%{get(b:,'coc_current_function','')}

" Mappings for CoCList
" Show all diagnostics
nnoremap <silent><nowait> <space>a  :<C-u>CocList diagnostics<cr>
" Manage extensions
nnoremap <silent><nowait> <space>e  :<C-u>CocList extensions<cr>
" Show commands
nnoremap <silent><nowait> <space>c  :<C-u>CocList commands<cr>
" Find symbol of current document
nnoremap <silent><nowait> <space>o  :<C-u>CocList outline<cr>
" Search workspace symbols
nnoremap <silent><nowait> <space>s  :<C-u>CocList -I symbols<cr>
" Do default action for next item
nnoremap <silent><nowait> <space>j  :<C-u>CocNext<CR>
" Do default action for previous item
nnoremap <silent><nowait> <space>k  :<C-u>CocPrev<CR>
" Resume latest coc list
nnoremap <silent><nowait> <space>p  :<C-u>CocListResume<CR>

 

 

 5. 현재까지의 설정이 적용된 vim 코드 뷰

문법 오류 검사

 

자동완성 추천

 

 

함수 rename

 

Show Documentation

반응형

댓글