The Ultimate Vim Setup (My 2024 vimrc ) : Essential Commands, Configurations, and Plugin Tips
Category: vim
Date: 8 months ago
Views: 1.34K
Are you ready to level up your text editing game? If you're a Linux or Windows user looking to harness the power of Vim, you're in the right place. Vim is a highly customizable text editor known for its efficiency and versatility. However, it can be intimidating for beginners. Fear not! In this guide, we'll walk you through the process of setting up Vim for the first time, catering to both Linux and Windows users.
Table of Contents
- Installing Vim
- For Linux Users
- For Windows Users
- Essential Vim Commands
- Configuring Vim
- 1: Vimrc File
- 2: Vim Plugins
- 4: History, Undo, Redo
- 5: More Settings
- 6: Color Highlighting
- 7: Search and Additional Settings
- 8: Custom Functions for File and Command History Management
- Plugin Configurations
- 1: FZF Settings
- 2: Completion and YouCompleteMe
- Filetype Specific Configurations
- Conclusion
Installing Vim
For Linux Users:
Installing Vim on Linux is a breeze. Simply open your terminal and enter the following command:
# debian based distributions
sudo apt-get install vim
# Arch based distributions
sudo pacman -S vim
For Windows Users:
Windows users can download Vim from its official website (https://www.vim.org/download.php) or use package managers like Chocolatey (https://chocolatey.org/packages/vim).
Essential Vim Commands
One of the most distinctive features that sets Vim apart from other text editors is its powerful and efficient text manipulation capabilities, primarily driven by Vim motions. These commands streamline the editing process, allowing users to navigate, edit, and manipulate text with remarkable speed and precision.
i: Enter insert mode
Esc: Exit insert mode
:w: Save changes
:q: Quit Vim
:wq: Save and quit
h, j, k, l: Navigate left, down, up, right respectively
yy: Copy current line
dd: Delete current line
p: Paste copied/deleted text
Mastering these essential Vim commands is the first step towards becoming proficient with this powerful text editor. With practice, users can harness the efficiency and flexibility of Vim motions to edit text swiftly and effectively.
Configuring Vim
1: Vimrc File
The .vimrc
file is a key component for configuring Vim according to your preferences. It contains settings, key mappings, and customizations to tailor Vim to your workflow.
On Linux systems, including Ubuntu, Debian, Fedora, and others, the .vimrc
file is typically located in the user's home directory. You can access it using a text editor or via the command line. Here's the path:
/home/your_username/.vimrc
Replace your_username
with your actual username.
For Windows users, the location of the .vimrc
file may vary depending on the Vim installation method:
•If you installed Vim using the installer, the .vimrc
file is usually located in the user's home directory:
C:\Users\YourUsername\_vimrc
•If you are using the Vim distribution called "Cream," the _vimrc
file may be located in:
C:\Program Files\Vim\_vimrc
Remember to use a text editor or the command line to edit the .vimrc
file and add your desired configurations.
2: Vim Plugins
Vim plugins enhance the functionality of the editor by adding features, customizations, and themes. They allow users to tailor Vim to their specific needs and preferences.
Vim-Plug is a popular plugin manager for Vim that simplifies the process of installing and managing plugins. Here's how to set it up:
Download Vim-Plug: Visit the Vim-Plug GitHub repository at https://github.com/junegunn/vim-plug.
Copy Vim-Plug: Depending on your operating system:
For Windows: Download the
plug.vim
file from the Vim-Plug GitHub repository. Then, copy the downloaded file to the%USERPROFILE%\vimfiles\autoload
directory.For Linux: Download the
plug.vim
file from the Vim-Plug GitHub repository. Then, copy the downloaded file to the~/.vim/autoload
directory.
With Vim-Plug installed, you're ready to start adding and managing plugins for your Vim editor.
Below is an example of configuring Vim plugins using Vim-Plug
:
" enable syntax highlighting and filetype detection
syntax on
filetype plugin indent on
" Specify a directory for plugins.
call plug#begin('~/.vim/bundle')
" Gruvbox theme.
Plug 'gruvbox-community/gruvbox'
" fzf
Plug 'junegunn/fzf', { 'do': { -> fzf#install() } }
Plug 'junegunn/fzf.vim'
" Briefly highlight which text was yanked.
Plug 'machakann/vim-highlightedyank'
" Modify * to also work with visual selections.
Plug 'nelstrom/vim-visual-star-search'
" Better display unwanted whitespace.
Plug 'ntpeters/vim-better-whitespace'
" A bunch of useful language related snippets (ultisnips is the engine).
Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'
"C family languages completion
Plug 'Valloric/YouCompleteMe'
" IDE-like bar
Plug 'bagrat/vim-buffet'
"
"Plug 'lervag/vimtex'
call plug#end()
In the example above, the Vim-Plug plugin manager is used to manage plugins. Each Plug
command specifies a plugin to install or manage. After adding the desired plugins to your .vimrc
file, save it and reload Vim to apply the changes. You can then install the plugins by running :PlugInstall
command within Vim.
For Windows users, ensure that you name the bundle directory appropriately. In the example above, the directory is named bundle
. However, on Windows systems, the directory separator is typically a backslash (\) instead of a forward slash (/). Therefore, you should name the directory bundle
or bundle\
accordingly to avoid any path-related issues.
Experiment with different plugins to discover ones that best suit your workflow and enhance your Vim experience.
For the plugin "YouCompleteMe," additional steps are required for both Linux and Windows users. Firstly, ensure that Python is installed and added to the system's PATH environment variable. This step is necessary because YouCompleteMe relies on Python for its functionality. Additionally, Git should also be installed and added to the PATH, as YouCompleteMe requires Git for fetching and updating its dependencies.
After running :PlugInstall
to install the plugins, users need to navigate to the YouCompleteMe plugin directory and execute the installation script manually. This is typically located in the .vim/bundle/YouCompleteMe
directory. Follow the instructions provided in the plugin's documentation or README file to complete the installation process.
General settings in Vim allow users to customize various aspects of the editor's behavior and appearance to suit their preferences. These settings cover a wide range of functionalities, from enabling features like backspace navigation in insert mode and cursor line highlighting to configuring auto-reading of files changed outside of Vim. Users can also adjust settings related to cursor behavior, encoding, syntax highlighting, and more to create a personalized editing environment. Experimenting with these settings can significantly enhance productivity and streamline the editing experience in Vim.
In Vim, the "leader" key serves as a customizable prefix for creating custom key mappings. By default, the backslash (\) key is designated as the leader key, but users can redefine it to any other key of their choice. The leader key is often used in combination with other keys to create shortcuts for frequently used commands or custom functions. This allows users to streamline their workflow and increase efficiency by assigning intuitive and memorable key combinations for specific tasks. Utilizing the leader key effectively can significantly enhance productivity and make Vim usage more ergonomic and tailored to individual preferences.
" leader
" -----------------------------------------------------------------------------
let mapleader=";"
noremap cc :gg"+yG " copy the entire document to system clipboard
noremap y yiW
" General Config
" -----------------------------------------------------------------------------
set backspace=indent,eol,start "Allow backspace in insert mode
set showcmd "Show incomplete cmds down the bottom
set showmode "Show current mode down the bottom
set gcr=a:blinkon0 "Disable cursor blink
set visualbell "No sounds
set autoread "Reload files changed outside vim
set hidden
set cursorline
set modeline
set mouse=n
set encoding=utf-8
set isfname+=32
set showmatch "highlight matching [{{{()}}}]
set lazyredraw
set tw=100
set complete+=kspell
"set colorcolumn=100
set formatoptions=tcqrn1
set matchpairs+=<:> " Use % to jump between pairs
set nocompatible
set noerrorbells visualbell t_vb=
set noshiftround
"set nospell
set nostartofline
set regexpengine=1
set ruler
set ttimeout
set whichwrap=b,s,<,>
set t_Co=256
set title titlestring=
set completeopt-=preview
set splitbelow
set splitright
set formatoptions-=tc " turn off breaking long lines
set showtabline=0
set wildoptions=pum
4: History, Undo, Redo
In Vim, managing history, undo, and redo functionalities is crucial for efficient editing and reverting changes. By adjusting settings related to history, undo, and redo, users can customize Vim to suit their workflow and preferences.
Below are some settings commonly used to configure history, undo, and redo in Vim:
" history, undo, redo and backup
" -----------------------------------------------------------------------------
set history=10000
set undofile
set undodir=~/.vim/undo
set undolevels=1000
set undoreload=10000
set backupdir=~/.vim/backup
set directory=~/.vim/backup
set viminfo='1000000
"redo
nnoremap r <C-r>
In the provided configuration, Vim is set to maintain a history of 10,000 commands. Undo information is saved to a file using the undofile
option, with the directory specified as ~/.vim/undo
. Additionally, Vim is configured to maintain a high level of undo information with 1,000 levels and to reload undo files up to 10,000 bytes in size. Backup files are stored in ~/.vim/backup
, and the viminfo
option is set to a large value for storing various information about the editing session.
Furthermore, a mapping is created to allow for easy redoing of changes using the r
key combined with Ctrl+r
.
Customizing these settings enables users to effectively manage history, undo, and redo operations in Vim, enhancing productivity and providing greater control over the editing process. It's worth noting that Vim's history and undo/redo functionalities persist even after closing and reopening documents. With settings configured to retain thousands of history actions, users can seamlessly navigate through the editing history of their documents, ensuring a comprehensive and efficient editing experience.
5: More Settings
Additional settings in Vim allow users to further customize their editing environment and workflow. These settings can range from defining custom key mappings for specific tasks to configuring autocmds and functions to automate certain actions.
Below are some additional settings commonly used to enhance the Vim experience:
" more settings
" -----------------------------------------------------------------------------
"
nnoremap <silent><leader>l :set number! relativenumber!<CR>
autocmd FocusGained * !terminal_transparency set 90
function! EngType()
" To switch back from Arabic
set spell
set spelllang=en_us
set spellcapcheck
endfunction
function! FrType()
set spell
set spelllang=fr
set spellfile+=~/.vim/spell/fr.utf-8.add
endfunction
" cycle through buffers
nnoremap <Tab> :bnext<CR>
"window mouvements
nnoremap <down> <C-W><C-J>
nnoremap <up> <C-W><C-K>
nnoremap <right> <C-W><C-L>
nnoremap <left> <C-W><C-H>
In the provided configuration, custom key mappings are defined to toggle line numbers and relative line numbers using <leader>l
, and to cycle through buffers using <Tab>
. Autocommands are utilized to adjust terminal transparency upon regaining focus, and functions are defined to switch between English and French spell checking modes. Additionally, custom mappings are set for window movements using <down>
, <up>
, <right>
, and <left>
keys.
These additional settings offer users greater flexibility and efficiency in their editing tasks, allowing for a more personalized and streamlined Vim experience.
6: Color Highlighting
Color highlighting in Vim plays a significant role in enhancing readability and visual appeal, making it easier for users to distinguish between different elements within the editor. By configuring color schemes and defining custom highlight groups, users can customize the appearance of various components such as the cursor, cursor line, status line, search results, and more.
Below are some settings commonly used to configure color highlighting in Vim:
" highlighting and cursor
" -----------------------------------------------------------------------------
"
colorscheme gruvbox
hi CursorLine ctermbg=darkgrey ctermfg=none term=bold cterm=bold
hi CursorColumn ctermbg=darkred ctermfg=white term=bold cterm=bold
hi StatusLine ctermbg=darkred ctermfg=white term=bold cterm=bold
hi Normal ctermbg=black ctermfg=none term=bold cterm=bold
hi Visual ctermbg=lightred ctermfg=black term=bold cterm=bold
hi Folded ctermbg=black ctermfg=red term=bold cterm=bold
hi FoldColumn ctermbg=green ctermfg=yellow term=bold cterm=bold
hi Search ctermbg=yellow ctermfg=black term=bold cterm=bold
hi Cursor ctermbg=yellow ctermfg=yellow term=bold cterm=bold
hi iCursor ctermbg=yellow ctermfg=yellow term=bold cterm=bold
hi SpellBad cterm=underline ctermfg=black ctermbg=red
hi SpellLocal cterm=underline ctermfg=black ctermbg=red
hi SpellRare cterm=underline ctermfg=black ctermbg=red
hi SpellCap cterm=underline ctermfg=black ctermbg=green
"make block cursor
let &t_ti.="\e[1 q"
let &t_SI.="\e[5 q"
let &t_EI.="\e[1 q"
let &t_te.="\e[0 q"
In the provided configuration, the Gruvbox color scheme is used to define various highlight groups for different elements such as the cursor line, cursor column, status line, search results, and more. Additionally, custom mappings are set to make the cursor block-shaped.
Customizing color highlighting settings allows users to create a visually appealing and personalized editing environment in Vim, enhancing readability and productivity.
7: Search and Additional Settings
Search functionality in Vim is essential for navigating through documents and finding specific text patterns efficiently. By configuring search settings, users can enhance their searching experience and streamline their workflow. Additionally, there are various other settings that can further customize Vim to suit individual preferences and automate certain tasks.
Below are some search-related settings and additional configurations commonly used in Vim:
" Search
set incsearch " Find the next match as we type the search
set hlsearch " Highlight searches by default
set ignorecase " Ignore case when searching...
set smartcase " ...unless we type a capital
" even more settings
" -----------------------------------------------------------------------------
"
" Automatically deletes all trailing whitespace on save.
autocmd BufWritePre * %s/\s\+$//e
" remember last position
if has("autocmd")
au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif
endif
" set current directory to the directory of the current file
autocmd BufEnter * if expand("%:p:h") !~ '^/tmp' | silent! lcd %:p:h | endif
" IDE BAR
nnoremap <silent><leader>k :execute 'set showtabline=' . (&showtabline ==# 2 ? 0 : 2)<CR>
" wordcount
function! WC()
let filename = expand("%")
let cmd = "detex " . filename . " | wc -w | tr -d '[:space:]'"
let result = system(cmd)
echo result . " words"
endfunction
command WC call WC()
In the provided configuration, search settings such as incsearch
and hlsearch
are enabled to enhance the search experience by highlighting matches and displaying search results as you type. Additionally, settings like ignorecase
and smartcase
are configured to ignore case when searching, except when typing capital letters.
Furthermore, additional settings are applied to automate tasks such as deleting trailing whitespace on save and remembering the last cursor position when reopening files.
Customizing these settings allows users to optimize their searching experience and tailor Vim to their specific preferences and workflow.
8: Custom Functions for File and Command History Management
In Vim, custom functions provide a powerful way to automate tasks and enhance productivity. Below are three custom functions designed to streamline file and command history management:
" this function is a great way to open old files
function! Output()
enew | 0put =v:oldfiles| nnoremap <buffer> <CR> :e <C-r>=getline('.')<CR><CR>|normal gg<CR>
setlocal buftype=nofile bufhidden=wipe noswapfile nowrap
nnoremap <buffer> <down> j
nnoremap <buffer> <up> k
endfunction
:command! Mm call Output()
:command! MM call Output()
function! OutputCommands()
let history = []
for i in range(histnr(':'), 1, -1)
call add(history, histget(':', i))
endfor
enew
call append(0, history)
normal gg
setlocal buftype=nofile bufhidden=wipe noswapfile nowrap
"nnoremap <buffer> <CR> :call setreg('+', getline('.'))<CR>
nnoremap <buffer> <CR> :let command = getline('.') | bnext | execute command<CR>
nnoremap <buffer> <down> j
nnoremap <buffer> <up> k
endfunction
:command! Cc call OutputCommands()
:command! CC call OutputCommands()
function! OutputRegs()
" Create a new buffer
enew
setlocal buftype=nofile bufhidden=wipe noswapfile nowrap
" Append content of non-empty registers a to z
for reg in range(char2nr('a'), char2nr('z'))
let reg_char = nr2char(reg)
let reg_content = getreg(reg_char)
if !empty(reg_content)
call append(line('$'), [reg_char .":" , reg_content])
call append(line('$'), "")
endif
endfor
" Move the cursor to the beginning of the buffer
normal gg
" Output message
echo "Contents of registers a to z "
endfunction
:command! Rr call OutputRegs()
:command! RR call OutputRegs()
•Output: This function opens a new buffer to display a list of old files, allowing easy navigation and reopening of previous documents.
•OutputCommands: This function creates a new buffer to display the command history, enabling users to review and execute previous commands.
•OutputRegs: This function generates a new buffer to display the contents of registers a to z, providing a convenient way to access and manage stored text snippets.
These custom functions offer efficient ways to handle file and command history, as well as manage text snippets stored in registers. For detailed explanations and usage examples of each function, refer to the following articles:
•Exploring the Output Function For a Better Vim Old Files
•Mastering OutputCommands for Command History Management
•Understanding Vim Registers and Advanced Usage
•Deep Dive into OutputRegs for Register Management
By incorporating these custom functions into your Vim workflow, you can optimize your editing experience and maximize efficiency.
Plugin Configurations
1: FZF Settings
FZF is a powerful command-line fuzzy finder that integrates seamlessly with Vim, providing quick and efficient file and buffer navigation. Below are some configurations commonly used to enhance the FZF experience:
" fzf settings
" -----------------------------------------------------------------------------
"
" Map a few common things to do with FZF.
nnoremap <silent> <Leader>, :Buffers<CR>
nnoremap <silent> <Leader>s :Files<CR>
nnoremap <silent> <Leader>j :Lines<CR>
nnoremap <silent> <Leader>h :Commands<CR>
nnoremap <silent> <Leader><leader> :History<CR>
" set filetypes
autocmd BufEnter,BufNew,BufNewFile,BufRead *.tex set ft=tex
autocmd BufEnter,BufNew,BufNewFile,BufRead *.cpp set ft=cpp
autocmd BufEnter,BufNew,BufNewFile,BufRead *.c set ft=c
In the provided configuration, key mappings are defined to quickly access FZF functionality for navigating buffers, files, lines, and command history. Additionally, filetypes are set automatically for specific file extensions to ensure proper syntax highlighting and formatting in Vim.
These configurations streamline the usage of FZF within Vim, enabling faster and more intuitive navigation through buffers and files.
2: Completion and YouCompleteMe
Completion in Vim is essential for enhancing productivity by providing suggestions and auto-completion for commands, keywords, and file paths. YouCompleteMe (YCM) is a popular plugin that offers intelligent code completion capabilities in Vim. Below are configurations commonly used to optimize completion settings and integrate YouCompleteMe:
" Completion
" .............................................................................
set wildmode=list:longest
set wildmenu "enable ctrl-n and ctrl-p to scroll thru matches
set wildignore=*.o,*.obj,*~ "stuff to ignore when tab completing
set wildignore+=*vim/backups*
set wildignore+=*sass-cache*
set wildignore+=*DS_Store*
set wildignore+=vendor/rails/**
set wildignore+=vendor/cache/**
set wildignore+=*.gem
set wildignore+=log/**
set wildignore+=tmp/**
set wildignore+=*.png,*.jpg,*.gif
" YouCompleteMe
" .............................................................................
let g:ycm_global_ycm_extra_conf = '~/.vim/bundle/YouCompleteMe/.ycm_extra_conf.py'
let g:ycm_add_preview_to_completeopt = 0
"let g:ycm_autoclose_preview_window_after_insertion = 1
"let g:ycm_autoclose_preview_window_after_completion = 1
let g:ycm_collect_identifiers_from_tags_files = 1
"set tags+=~/.vim/tags/testtags
let g:ycm_key_list_select_completion = ['<Down>']
let g:ycm_key_list_previous_completion = ['<C-k>', '<Up>']
let g:ycm_key_list_accept_completion = ['<C-y>']
" Additional YouCompleteMe config.
let g:ycm_complete_in_comments = 1
let g:ycm_collect_identifiers_from_comments_and_strings = 1
let g:ycm_seed_identifiers_with_syntax = 1
let g:ycm_server_python_interpreter='python3'
map <leader>g :YcmCompleter GoToDefinitionElseDeclaration<CR>
In the provided configuration, completion settings such as wildmode
and wildmenu
are adjusted to enable enhanced tab completion behavior and ignore certain file patterns. YouCompleteMe integration settings are also defined to customize key mappings and enable additional completion features.
By configuring completion settings and integrating YouCompleteMe, Vim users can enjoy enhanced code completion capabilities and improved productivity in their editing workflows.
Filetype Specific Configurations
Filetype-specific configurations in Vim allow users to customize editor behavior and settings based on the type of file being edited. By organizing configurations into directories such as .vim/after/ftplugin
and .vim/ftplugin
, users can maintain clean and structured configuration files tailored to specific filetypes.
In the .vim/after/ftplugin
directory, users can place configuration files that are sourced after the default filetype plugins. This allows for overriding or extending settings specific to certain filetypes, such as "C" and "C++". Similarly, the .vim/ftplugin
directory contains filetype-specific configuration files that are sourced when editing files of corresponding types. For example, configuration files for filetypes like "tex", "php", "sh", "html", and others can be organized here.
Additionally, users can create a .vim/mysnippets
folder to store filetype-specific code snippets. These snippets can be quickly inserted into files while editing, providing shortcuts for commonly used code patterns or structures.
If you're interested in delving deeper into each of these filetype-specific configurations, we invite you to keep an eye on this article. We'll continue updating it with more content and detailed explanations, ensuring you have access to the latest insights and configurations for optimizing your Vim experience.
•Exploring Vim Configuration for C and C++ Files (Pending)
•Mastering Vim Configuration for Tex Files (Pending)
•Advanced Vim Configuration for PHP Files (Pending)
•Customizing Vim Configuration for Shell Scripts (Pending)
•Optimizing Vim Configuration for HTML Files (Pending)
Conclusion
In conclusion, Vim is a powerful and versatile text editor that offers extensive customization options to suit individual preferences and workflows. By mastering essential commands, configuring plugins, and leveraging filetype-specific settings, users can optimize their Vim experience for maximum productivity.
Whether you're a seasoned Vim user or just getting started, exploring and experimenting with different configurations can help you tailor Vim to your specific needs and enhance your editing efficiency.
Remember, Vim is more than just a text editor—it's a customizable toolkit that adapts to your workflow and empowers you to edit text like a pro.
Thank you for joining us on this journey through Vim customization. Happy editing!
0 Comments, latest
No comments.