C 개발환경 설정

Linux(Ubuntu) + vim + cscope + ctags


python3, clipboard를 지원하는 vim 9.1 빌드

  • commit hash - 35699f17497dcdcfdd747fedaef28f208ac6eb5f
  • branch - master
  • Ubuntu 22.04 기준
  • python3-distutils python3 python3-dev libncurses-dev 등의 dependency 설치
  • clipboard, python3을 지원하는 vim을 빌드하기 위해 configure 파일 실행
sudo apt-get update
sudo apt-get install -y python3-distutils python3-dev python3 \
         libx11-dev libxt-dev libgtk2.0-dev
git clone --depth=1 https://github.com/vim/vim.git
cd vim/src
./configure --with-features=huge \
            --enable-python3interp \
            --enable-gui=gtk2 \
            --enable-fail-if-missing \
            --with-python3-command=/usr/bin/python3 \
            --with-python3-config-dir=/usr/lib/python3.10/config-3.10-x86_64-linux-gnu
make
sudo make install

cscope, ctags DB 생성 스크립트

#!/bin/bash
rm -rf tags cscope.out
find . \( -name '*.c' -o -name '*.cpp' -o -name '*.cc' -o -name '*.h' -o -name '*.s' -o -name '*S' \) -print > cscope.files
ctags -R .
cscope -i cscope.files
rm cscope.files

vimrc

set ruler
syntax on
filetype plugin indent on
set nocompatible
set cindent
set termguicolors
set ts=4 sw=4
set clipboard=unnamedplus
set showmatch
set incsearch
set hlsearch
set formatoptions=cro " c: Auto-wrap comments,
" r: Auto insert the current comment leader after 'Enter'
" o: Auto insert the current comment leader after 'o' or 'O'
set colorcolumn=80 " coloring on the N'th column
set cursorline
set nowrap
set foldmethod=manual
set backspace=indent,eol,start

" Google style guide
" C++ 파일에 대한 기본 설정
autocmd FileType cpp setlocal expandtab shiftwidth=2 softtabstop=2
" 자동 들여쓰기, 괄호 스타일, 탭 대신 스페이스 사용
set tabstop=2        " 탭을 스페이스 2개로 설정
set shiftwidth=2     " 자동 들여쓰기 시 스페이스 2칸 사용
set expandtab        " 탭 대신 스페이스 사용
" 공백 제거, 트레일링 공백 자동 제거
autocmd BufWritePre *.cpp,*.h :%s/\s\+$//e
" 괄호 자동 맞추기
set smartindent
set autoindent
" 자동 줄바꿈
" set textwidth=80
set colorcolumn=80   " 80번째 열에 컬럼 가이드 표시
highlight ColorColumn ctermbg=lightgrey  " 컬럼 가이드 색상 설정

map <leader>1 :b!1<CR>
map <leader>2 :b!2<CR>
map <leader>3 :b!3<CR>
map <leader>4 :b!4<CR>
map <leader>5 :b!5<CR>
map <leader>6 :b!6<CR>
map <leader>7 :b!7<CR>
map <leader>8 :b!8<CR>
map <leader>9 :b!9<CR>
map <leader>0 :b!0<CR>
map <Tab>h :bp<CR>
map <Tab>l :bn<CR>

inoremap {<CR> {<CR>}<Esc>O
inoremap { {}<left>
inoremap {} {}<left>
inoremap ( ()<left>
inoremap () ()<left>
inoremap [ []<left>
inoremap [] []<left>
inoremap " ""<left>
inoremap ' ''<left>
inoremap ` ``<left>

"""""""""""""""""""""""""""" plugins
set rtp+=$HOME/.vim/bundle/Vundle.vim
call vundle#begin()
" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
Plugin 'vim-airline/vim-airline'
Plugin 'preservim/nerdtree'
Plugin 'preservim/tagbar'
Plugin 'Donaldttt/fuzzyy'
Plugin 'tpope/vim-fugitive'
Plugin 'airblade/vim-gitgutter'
Plugin 'neoclide/coc.nvim'
Plugin 'rhysd/vim-clang-format'
call vundle#end()

" Brief help
" :PluginList       - lists configured plugins
" :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append `!` to refresh local cache
" :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal

"""""""""""""""""""""""""""" shortcuts
map <Space> <leader>
nmap <leader>t :TagbarToggle<CR>
nnoremap <leader>n :NERDTreeToggle<CR>
nnoremap <silent> <leader>fc :FuzzyColors<CR>
nnoremap <silent> <leader>ff :FuzzyFiles<CR>

" airline
let g:airline#extensions#tabline#enabled = 1

" GitGutter
let g:gitgutter_enabled = 1
set updatetime=100

" DoxygenToolkit
let g:DoxygenToolkit_briefTag_pre="@brief  "
let g:DoxygenToolkit_paramTag_pre="@param "
let g:DoxygenToolkit_returnTag="@returns   "
let g:DoxygenToolkit_authorName="Minkeun Park"

" cscope
if filereadable("./cscope.out")
    cs add cscope.out
endif

" coc.nvim
" CocInstall coc-clangd
" 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>"
set pumwidth=5

" 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
if has('nvim')
  inoremap <silent><expr> <c-space> coc#refresh()
else
  inoremap <silent><expr> <c-@> coc#refresh()
endif

" 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> gi <Plug>(coc-implementation)
nmap <silent> gr <Plug>(coc-references)

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

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

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

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

" Formatting selected code
xmap <leader>f  <Plug>(coc-format-selected)
nmap <leader>f  <Plug>(coc-format-selected)

augroup mygroup
  autocmd!
  " Setup formatexpr specified filetype(s)
  autocmd FileType typescript,json setl formatexpr=CocAction('formatSelected')
  " Update signature help on jump placeholder
  autocmd User CocJumpPlaceholder call CocActionAsync('showSignatureHelp')
augroup end

" Applying code actions to the selected code block
" Example: `<leader>aap` for current paragraph
xmap <leader>a  <Plug>(coc-codeaction-selected)
nmap <leader>a  <Plug>(coc-codeaction-selected)

" Remap keys for applying code actions at the cursor position
nmap <leader>ac  <Plug>(coc-codeaction-cursor)
" Remap keys for apply code actions affect whole buffer
nmap <leader>as  <Plug>(coc-codeaction-source)
" Apply the most preferred quickfix action to fix diagnostic on the current line
nmap <leader>qf  <Plug>(coc-fix-current)

" 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)

" Remap <C-f> and <C-b> to scroll float windows/popups
if has('nvim-0.4.0') || has('patch-8.2.0750')
  nnoremap <silent><nowait><expr> <C-j> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  nnoremap <silent><nowait><expr> <C-k> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
  inoremap <silent><nowait><expr> <C-j> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(1)\<cr>" : "\<Right>"
  inoremap <silent><nowait><expr> <C-k> coc#float#has_scroll() ? "\<c-r>=coc#float#scroll(0)\<cr>" : "\<Left>"
  vnoremap <silent><nowait><expr> <C-j> coc#float#has_scroll() ? coc#float#scroll(1) : "\<C-f>"
  vnoremap <silent><nowait><expr> <C-k> coc#float#has_scroll() ? coc#float#scroll(0) : "\<C-b>"
endif

" 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 `:Format` command to format current buffer
command! -nargs=0 Format :call CocActionAsync('format')

" Add `:Fold` command to fold current buffer
command! -nargs=? Fold :call     CocAction('fold', <f-args>)

" Add `:OR` command for organize imports of the current buffer
command! -nargs=0 OR   :call     CocActionAsync('runCommand', 'editor.action.organizeImport')

" 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>

" vim-clang-format
let g:clang_format#style_options = {
      \ 'BasedOnStyle': 'Google',
      \ 'IndentWidth': 2,
      \ }


colorscheme koehler
hi ColorColumn guibg=#555555
set signcolumn=yes
hi SignColumn guibg=#555555

references