Vim Highlight Without Getting Into VisualMode 2022_11_22_17:14:09
seen from United States

seen from United Kingdom
seen from Brazil
seen from United States

seen from Australia
seen from Germany
seen from China
seen from United States
seen from United States
seen from United States
seen from United States

seen from Malaysia
seen from China
seen from China
seen from China
seen from United States
seen from United States
seen from China

seen from United States

seen from Netherlands
Vim Highlight Without Getting Into VisualMode 2022_11_22_17:14:09
To change the shape of the cursor in different modes, you can add the following into your vimrc: "Mode Settings let&t_SI.="\e[5 q" "SI= INSERT mode let&t_SR.="\e[4 q" "SR= REPLACE mode let&t_EI.="\e[1 q" "EI= NORMAL mode (ELSE) "Cursor settings: " 1 -> blinking block " 2 -> solid block " 3 -> blinking underscore " 4 -> solid underscore " 5 -> blinking vertical bar " 6 -> solid vertical bar let&t_SI= "\]50;CursorShape=1\x7" let&t_SR= "\]50;CursorShape=2\x7" let&t_EI...
완벽한 Mac 작업환경 세팅하기 (vim, zsh, iterm)
그동안 개인 컴퓨터로도 수많은 프로그래밍 언어와 작업 환경을 만들었고, 회사에서도 수많은 인턴분들과 뉴커머들이 오고가면서 그들의 작업환경을 세팅해주고 가이드라인 해줬다, 필자는 최대한 많은 트릭과 신텍틱 슈거, 그리고 불필요한 노동시간을 줄이기위해 깊이있게 파고들고 또 파고드는 것을 좋아한다.
이번 시간에서는 맥 환경에서 작업하는 주 작업자들을 위해 여러분의 노동시간을 줄일 수 있는 몇가지 팁들을 소개하려고 한다. 이 글에서 tmux에 대한 내용까지 담으려고 했지만 tmux만 해도 내용이 너무 방대하므로 iTerm의 Split View기능으로 대체하고 tmux는 다음 시간에 다른 포스트에서 자세히 다루도록 하겠다.
Vim - Menus
Our beloved Vim offers some possibilities to create and use menus to execute various kinds of commands. I know the following solutions ...
the menu command family
the confirm function
the insert user completion (completefunc)
I will not bother you with a detailed tutorial. For more information I always recommend the best place to learn about Vim - the integrated help.
:menu
Let's start with the most obvious one, the menu commands. The menu commands can be used to create menus that can be called via GUI (mouse and keyboard) and via ex-mode. A good use-case is to create menus entries for commands that are not needed often, for which a mapping would be a waste of valueable key combinations and which can probably not be remembered anyway as they are used less frequently.
I'll keep it short here and as there are already tutorials out there. And of course the Vim help is the best place to read about it. :h creating-menus
Vim offers several menu commands. Depending on the current Vim mode your menu changes accordingly. Means if you are in normal mode you will see your normal mode menus, in visual mode you can see only the menus that make sense in visual mode, and so on.
Let's say we want to have a command in the menu that removes duplicate lines and keeps only one. We want that in normal mode the command runs for the whole file and that in visual mode, by selecting a range of lines, the command shall run only for the selected lines. We could put the following lines in our vimrc.
nmenu Utils.DelMultDuplLines :%s/^\(.*\)\(\n\1\)\+$/\1/<cr> vmenu Utils.DelMultDuplLines :s/^\(.*\)\(\n\1\)\+$/\1/<cr>
The here used commands are quite simple. After the menu command you see only 2 parameters. First one is the menu path. I say path because by using the period you can nest your menus. Here it is only the command directly under the Utils menu entry. The second parameter is the command to be executed just like you would do from normal mode.
There are 2 special characters that can be used in the first parameter. & and <tab>. & can be used to add a shortcut key to the menu and <tab> to add a right aligned text in the menu. Try it out!
Remember that you can access the menu also via ex-mode.
:menu Utils.DelMultDuplLines
But please don't type all the text and use the tabulator key to do the autocompletion for you. ;-)
confirm()
The confirm function. Luckily I already wrote about this possibility. So instead of copy-pasting the text I just link to it.
vim-confirm-function
set completefunc
Let's get dirty now. I guess the insert completion pop-up menu is well known by everyone. But did you know that you can misuse it for more than just auto-completion? I did not. I will show you what I mean.
Usually the auto-completion is triggered by pressing Ctrl-n, Ctrl-p or Ctrl-x Ctrl-something in insert mode. One of these key mappings is Ctrl-x Ctrl-u which triggers an user specific function. Means we can write a function that does what we want and assign it to the completefunc option. Let's check what we need to consider when writing such a function.
The completefunc you have to write has 2 parameters. And the function gets called twice by Vim. When calling the function the first time, Vim passes the parameters 1 and empty. In this case it is your task to usually find the beginning of the word you want to complete and return the start column. One the second call Vim passes 0 and the word the shall be completed.
function! MyCompleteFunc(findstart, base) if a:findstart " write code to find beginning of the word else " write code to create a list of possible completions end endfunction set completefunc=MyCompleteFunc
For more information and an example check :h complete-functions.
Now let's re-create the LaTeX example using the completefunc. Here is a possible solution that supports nested menus, so for 1 level menus the code can be reduced a lot.
https://gist.github.com/marcotrosi/e2918579bce82613c504e7d1cae2e3c0
Okay let's go through it step by step.
In the beginning you see 2 variables. InitMenu and NextMenu. InitMenu defines the menu entry point and NextMenu remembers the name of the next menu. I just wanted to have nested menus and that's what is this for.
Next is the completefunc we have to write. I called mine LatexFont. As shown before it consists of an if-else-block, where the if-true-block gets the word before the cursor and the else-block will return a list that contains some information. In the simplest form this would only be a list of strings that would be the popup-menu-entries. See the CompleteMonths example from the Vim help. But I added some more information. Let's see what it is.
The basic idea is to have one initial menu and many sub-menus, they are all stored in a single dictionary name menus and are somehow connected and I want to decide which one to return. As I initialized my InitMenu variable with "Font" this must be my entry point. After the declaration of the local menus dictionary you can see an if clause that checks if s:NextMenu is empty. So if s:NextMenu is empty it will be initialized with my init value I defined in the very beginning. And at the end I return one of the menus so that Vim can display it as a popup menu.
Now let's have a closer look at the big dictionary. You can see 4 lists named Font, FontFamily, FontStyle and FontSize. Each list contains the popup-menu entries. I use the key user_data to decide whether I want to attach a sub-menu or if the given menu is the last in the chain. To attach a sub-menu I just provide the name of the menu and when the menu ends there I use the string "_END_". So the restriction is that you can't name a menu "_END_" as it is reserved now. By the way, I didn't try it, but I guess that user_data could be of any datatype and is probably not limited to strings.
Let's see what the other keys contain. There are the keys word, abbr and dup. word contains the string that replaces the word before the cursor, which is also stored in a:base. abbr contains the string that is used for display in the popup-menu. From the insert auto-completion we are used to the word displayed is also the word to be inserted. Luckily Vim can distinguish that. This gives me the possibility to display a menu (like FontFamily, FontStyle, FontSize) but at the same time keeping the original unchanged word before the cursor. This is basically the whole trick. Plus the additional user_data key that allows me to store any kind of information for re-use and decisions. With the dup key I tell Vim to display also duplicate entries. For more information on supported keys check :h complete-items.
Now let's get to the rest of the nested menu implementation. Imagine you have selected an entry of the initial menu. You confirm by pressing SPACE and now I want to open the sub-menu automatically. To achieve that I use a Vim event named CompleteDone which triggers my LatexFontContinue function, and the CompleteDone event is triggered when closing the popup menu either by selecting a menu entry or by aborting. Within that function I decide whether to trigger the user completion again or to quit. Beside the CompleteDone event Vim also has a variable named v:completed_item that contains a dictionary with the information about the selected menu item. The first thing I do is saving the user_data value in a function local variable.
let l:NextMenu = get(v:completed_item, 'user_data', '')
The last parameter is the default value for the get function and is an empty string just in case the user aborted the popup-menu in which case no user_data would be available.
One more info - this line ...
inoremap <expr><esc> pumvisible() ? "\<c-e>" : "\<esc>"
... allows the user to abort the menu by pressing the ESC key intead of Ctrl-e.
And last but not least the if clause that either sets the script variable s:NextMenu to empty string when the local l:NextMenu is empty or "_END_" and quits the function without doing anything else, or the else branch that stores the next menu string in s:NextMenu and re-triggers the user completion.
The rest of the file is self-explanatory.
I'm sure we can change the code a bit to execute also other command types, e.g. by storing a command as a string and executing it.
Let me know what you did with it.
How to delete whitespaces on save in `vim`/`vi`
This code, added to the ~/.vimrc file, will delete all whitespaces on save:
func! DeleteTrailingWS() exe "normal mz" %s/\s\+$//ge exe "normal `z" endfunc autocmd BufWrite * :call DeleteTrailingWS()
Additionally, you can update the BufWrite to make it work for certain file types only, like this:
autocmd BufWrite *.js :call DeleteTrailingWS()
“ more convenient settings set encoding=utf-8 “ no need to be compatible with vi! set nocompatible set history=100
” tab settings set tabstop=4 set shiftwidth=4 set softtabstop=4 set expandtab
set scrolljump=5 set scrolloff=3 set autoindent set smartindent set visualbell set cursorline set backspace=indent,eol,start "set hidden means dont't close the buffer but just hide them set hidden "convinient file name autocompletion set wildmenu set wildmode=list:longest "display the current col and ro posoition of cursor set ruler set laststatus=2 set showmode set autowrite set showcmd
“ highlight search results set incsearch set hlsearch ” set searching and moving “ if search all-lower or all-upper case word, it will be case-sensitive ” else it will be case insensitive set ignorecase set smartcase set showmatch set matchtime=3
"set diff options set diffopt+=iwhite ” to show invisible characters set list set listchars=tab:▸\ ,eol:¬
“Invisible character colors highlight NonText guifg=#4a4a59 highlight SpecialKey guifg=#4a4a59
“ set working directory the same as the file you are editing. set autochdir
" map K to split lines, the opposite of J nmap K i<cr><esc>k$ nnoremap ; : inoremap jj <esc> nmap <tab> % vmap <tab> % ” Press space to clear search highlighting and any message nnoremap <silent> <Space> :silent noh<bar>echo<CR>
“remap the window switching, and with window effect map <C-j> <C-w>j<C-w>_ map <C-k> <C-w>k<C-w>_ map <C-h> <C-w>h<C-w>_ map <C-l> <C-w>l<C-w>_
“set no autowrap when inserting set wrap set linebreak set textwidth=0 set wrapmargin=0
"change leader key to Space let mapleader = ” “ "map tab switch command nnoremap <Leader>t gt "turn off backup set nobackup set noswapfile “set folding set foldmethod=marker set foldcolumn=4
“synctax highlighting syntax on
"map ctrlp plugin invoking nnoremap <Leader>p :CtrlP<CR> "match window position: 0 at top of screen, 1 at bottom let g:ctrlp_match_window_bottom = 0 "set max height of match window let g:ctrlp_max_height = 12 "if a file is already opened in a window somewhere, CtrlP will try "to jump to it instead of opening a new instance. let g:ctrlp_switch_buffer = 'Et' "starting working directory mode let g:ctrlp_working_path_mode = 'ra' "set user's root markers, will choose first ancestors including the markers(parent "of the marker) let g:ctrlp_root_markers = ['/verif/'] "the maximum number of files to scan, set to 0 for no limit let g:ctrlp_max_files = 0; "the maximum depth of a directory tree to recurse into let g:ctrlp_max_depth = 40
"let vim display some ascii art echo ”(/._.)/(._.)
"for matchit.vim settings, import for SV and verilog files "enable filetype detect aufiletype plugin on source ~/.vim/plugin/matchit.vim au Filetype verilog_systemverilog \let b:match_words=\ '\<begin\>:\<end\>,' . \ '\<if\>:\<else\>,' . \ '\<module\>:\<endmodule\>,' . \ '\<class\>:\<endclass\>,' . \ '\<program\>:\<endprogram\>,' . \ '\<clocking\>:\<endclocking\>,' . \ '\<property\>:\<endproperty\>,' . \ '\<sequence\>:\<endsequence\>,' . \ '\<package\>:\<endpackage\>,' . \ '\<covergroup\>:\<endgroup\>,' . \ '\<primitive\>:\<endprimitive\>,' . \ '\<specify\>:\<endspecify\>,' . \ '\<generate\>:\<endgenerate\>,' . \ '\<interface\>:\<endinterface\>,' . \ '\<function\>:\<endfunction\>,' . \ '\<task\>:\<endtask\>,' . \ '\<case\>\|\<casex\>\|\<casez\>:\<endcase\>,' . \ '\<fork\>:\<join\>\|\<join_any\>\|\<join_none\>,' . \ '`ifdef\>:`else\>:`endif\>,'
"ctags set tags=./tags set tags+=~/.vim/tags/UVM/tags set tags+=$PROJECT_DV_HOME/verif/tags nnoremap <M-[> <C-T> nnoremap <M-]> <C-]>
"GUI related "set display of line number au FocusLost * :set number au FocusGained * :set relativenumber autocmd InsertEnter * :set number autocmd InsertLeave * :set relativenumber
” set font if has(‘gui_running’) set guifont=Consolas:h10:cANSI endif
colorscheme zenburn
let g:zenburn_high_Contrast=1 set background=dark
More vim config linkdump
This unlogic link has a nice snippet showing how to define a vim autocmd highlight group:
augroup vimrc_autocmds autocmd! " highlight characters past column 120 autocmd FileType python highlight Excess ctermbg=DarkGrey guibg=Black autocmd FileType python match Excess /\%120v.*/ autocmd FileType python set nowrap augroup END
Failure to define highlight groups results in the editor choking with a message similar to
Error detected while processing BufRead Auto commands for "*.py": E28: No such highlight group name: BadWhitespace
This StackOverflow response shows how to define said highlight groups before calling them ith a match command.
This is using vundle as the package manager, but the rest of the advice is good and adapatable with the exception that it does not handle the group highlighting issue clearly.
This is a great compilation of advice https://www.fullstackpython.com/vim.html
Vim
Why vim
Once you get muscle memory for key binding then you get 100 times faster than before
Simple and Fast
Many options and functions
Lots of plugins
How to start setting vim configuration
If you are beginner, just run vimtutor.
If you have experience, go to vimwiki, usevim.org.
If you are expert, just copy other guys configurations, combime them, select your own.