vimtex: force } and { not to skip empty lines - vim

When I use } and {, vimtex+vim jumps somewhat randomly in the document, skipping several empty lines. See below.
How to restore the default vim behaviour not to skip the empty lines?

Find if there are any mappings for } using
:map }
Now, you can unmap any mappings you find with
:unmap }
If you wanna put this in your .vimrc, I'd suggest doing it in the after directory for that plugin.
like ~/.vim/after/plugin

Short answer
The fact that the skipping happens pretty randomly indicates that the empty lines are not really empty. They contain a whitespace or other special characters.
Move the cursor to these 'empty' lines and press $ to see if they are really empty.
How to avoid such problems:
(Yes, others had your problem too.)
Make vim show whitespace characters
Vim has a way to show these characters. Use set list and define listchars. From the vim help for listchars:
Strings to use in 'list' mode and for the :list command. It is a
comma separated list of string settings.
[...]
lcs-space
space:c Character to show for a space. When omitted, spaces
are left blank.
lcs-trail
trail:c Character to show for trailing spaces. When omitted,
trailing spaces are blank. Overrides the "space"
setting for trailing spaces.
See :help :list and :help listchars for more information.
Highlight trailing whitespace
I find it quite annoying to always have a character displayed for any space and my eyes are too bad to see a little dot at the end of a line (for trailing spaces). Therefore I use a highlight group to show all trailing whitespace characters:
" Show trailing whitespace
highlight ExtraWhitespace ctermbg=red " define highlight group
match ExtraWhitespace /\s\+$/ " define pattern
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/ " apply match to all buffers
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\#<!$/ " don't match while in insert
autocmd InsertLeave * match ExtraWhitespace /\s\+$/
autocmd BufWinLeave * call clearmatches() " It's good for the RAM
Auto-remove trailing whitespace
There is also a way to automagically delete those characters when writing the buffer -- but there are some caveats (think of markdown's double trailing whitespace for line breaks).
Vim wiki has a good explanation.
The simplest (but maybe not the best) solution is to add
autocmd BufWritePre * %s/\s\+$//e
to your .vimrc or to the corresponding ftplugin files.
I personally have a function in my vimrc and disable it for file types, where I don't want/need it.
You may also be interested in Make { and } ignore lines containing only whitespace
Disclaimer
There might be characters that are not whitespace, but are also not shown by vim by default. I never had this problem, but what I said under 'Short Answer' still does apply.

Related

Display-only character substitution in VIM

Is there any way to set VIM that it substitutes characters in the displayed text without changing the underlying file?
To be specific, I would like to substitute SOH characters (displayed as ^A by default) for tab to make the FIX protocol log files more readable.
I'm partially fine with a workaround
:highlight SpecialKey guifg=#ffffff
what makes the ^A invisible on white background but the substitution for tab would be much better.
Update:
I've almost found the solution:
:syntax match SOH /^A/ conceal cchar=_
:set conceallevel=2
:hi conceal guibg=NONE
Unfortunately I haven't found the way how to escape tab to the cchar parameter (instead of the underscore).
I do face the problem while opening log files.
I use autocommands to do such substitutions and leave files without saving.
:au BufEnter *.log :%s/^M/\r/g
This autocommand will replace all ^M characters with newlines while opening a log file.
So, the text like ADM-DEVICE : logged in^MADM-DEVICE : in prompt will be shown correctly as
ADM-DEVICE : logged in
ADM-DEVICE : in prompt.
Similarly, other control characters can be replaced. One thing I would do is changing '^[' to ` for better understanding.
Log files should not be edited and saved manually. So, for that I will use another autocommand.
:au BufWrite *.log :q!
This autocommand will exit the file if I try to save it. Autocommands will be the best choice to do automatically what you wanted to do.

How to make two user-defined highlights work together

I would like to highlight overlong lines in Vim (like here: https://stackoverflow.com/a/235970/1329844) as well as trailing whitespace (like here: https://stackoverflow.com/a/4617156/1329844). However, whenever I use both highlights, only the last one is applied.
I have the following code in my .vimrc:
highlight OverLength ctermbg=0 ctermfg=197
match OverLength /\%>80v.\+/
highlight ExtraWhitespace ctermbg=0
match ExtraWhitespace /\s\+$/
When I open a file, only trailing whitespace is highlighted. If I exchange the order of the two highlight/match pairs, only overlength lines are highlighted. What do I need to change so that both patterns are matched and highlighted?
The :match command can only have one active pattern. If both of your highlights used the same colors, you could combine the patterns with \|. Here, you have to use one of the two alternative commands: either :2match or :3match, or you can use the (newer) matchadd() function, where you can specify arbitrary numbers (> 3) as the (last) {id} argument.
:call matchadd('OverLength', '\%>80v.\+', 10, 4)
:call matchadd('ExtraWhitespace', '\s\+$', 10, 5)
I think, Ingos solution is to be prefered, but nevertheless, you can use this:
:match MyCustomHighlight /\%(\s\+$\)\|\(\%>30v.\+\)/
:highlight MyCustomHighlight ctermbg=0 ctermfg=197

Run a command each time a file opens, or general syntax

I have a syntax rule that highlights trailing whitespace:
highlight Badspace ctermfg=red ctermbg=red
match Badspace /\s\+$/
This is in my .vimrc. It works fine, but the problem is I use splits a lot, and it seems that the match is only run on the first file you open, as well it should because the .vimrc should only run once.
Anyway, how can I get the above syntax to match any file that is opened? Is there a "general" syntax file? Is there any other way to run match each time a file opens rather than just once? I'd like to know both because I could end up using either one in the future.
The :match command applies the highlighting to a window, so you can use the WinEnter event to define an :autocmd.
:autocmd WinEnter * match Badspace /\s\+$/
Note that there are already a number of plugins for this purpose, most based on this VimTip: http://vim.wikia.com/wiki/Highlight_unwanted_spaces
They handle all that for you, and turn off the highlighting in insert mode; some can also automatically delete the whitespace. In fact, I have written a set of plugins for that, too: ShowTrailingWhitespace plugin.
You could accomplish this by using an autocmd:
highlight Badspace ctermfg=red ctermbg=red
autocmd BufEnter * match Badspace /\s\+$/
However, there's another way to accomplish your specific goal of marking trailing whitespace. Vim has a built-in feature for highlighting "special" whitespace, which includes tabs (to differentiate from spaces), trailing whitespace, and non-breaking spaces (character 160, which looks like a normal space but isn't).
See :help list and :help listchars. Here's what I use:
set list listchars=tab:>·,trail:·,nbsp:·,extends:>
listchars has the benefit of working with any file type, and marking up multiple whitespace types that are of interest. It is also a lot faster (match will be noticeably slow on giant files) and built-in already.
(Note that those are funky non-ASCII dot characters, which should work fine for you if you cut-and-paste into a UTF8-capable Vim. If they don't work for you, you can use any characters you like there, such as periods or underscores).
Here's what it looks like for me:
The correct approach to this problem is actually to use :syntax to define a custom syn-match.
Try putting this in your vimrc:
augroup BadWhitespace
au!
au Syntax * syn match customBadWhitespace /\s\+$/ containedin=ALL | hi link customBadWhitespace Error
augroup END
Edit: It should also be noted that there is built-in support for highlighting trailing whitespace with the 'list' option; see :help 'listchars' and :h hl-SpecialKey (SpecialKey is the highlight group used to highlight trailing whitespace characters when 'list' is on).
This is accomplished using autocmd. The events you're looking for are BufWinEnter and VimEnter. From the Vim manual:
BufWinEnter
After a buffer is displayed in a window. This
can be when the buffer is loaded (after
processing the modelines) or when a hidden
buffer is displayed in a window (and is no
longer hidden).
Does not happen for |:split| without
arguments, since you keep editing the same
buffer, or ":split" with a file that's already
open in a window, because it re-uses an
existing buffer. But it does happen for a
":split" with the name of the current buffer,
since it reloads that buffer.
VimEnter
After doing all the startup stuff, including
loading .vimrc files, executing the "-c cmd"
arguments, creating all windows and loading
the buffers in them.
Try putting this in your vimrc:
augroup BadWhitespace
au!
au VimEnter,BufWinEnter * match Badspace /\s\+$/
augroup END
Do :help autocmd for more info.
This is completely wrong because :match is window-local, not buffer-local. Ingo Karkat has the right idea. Unfortunately, there is no good way to avoid triggering the autocmd every time you enter the window.
More to the point, though, this is a job for a custom syntax, not match.

How to add color to parenthesis and brackets in vim using molokai

I am using molokai in vim to code in python/html/css/javascript. When I edit python files (or javascript) parenthesis are not colored. This is not true for simple scripts (like molokai.vim itself) where parenthesis are colored gray.
I edited molokai.vim and added
hi parens guifg=#999999
and then I edited .vimrc and added:
syn match parens /[(){}]/
but parenthesis and brackets remain white.
What am I doing wrong?
Never use :syn to highlight all filetypes, there is matchadd() for this. Using :syn can easily break highlighting, matchadd() is an overlay.
Syntax highlighting is being overridden when Syntax event fires. More, it has effect only on the current buffer. So just syn in vimrc will never work, you have to use autocommands
autocmd! Syntax python :syntax match Parens /[(){}]/
(for python it is safe as parenthesis and figure brackets are not matched by any other syntax element).
In javascript parenthesis (()) are already matched by javaScriptParens highlighting group. Thus you have to use
hi def link javaScriptParens Parens
(in colorscheme). Braces are matched by javaScriptBraces and require similar command.
To determine what highlighting is used for specific symbol I place cursor on this symbol and launch
echo 'Normal '.join(map(synstack(line('.'), col('.')), 'synIDattr(v:val, "name")'))
, the last displayed word is normally what you need. If only Normal is displayed then symbol is not highlighted and you have to go 2., otherwise you have to go 3.
For universal solution disregarding currently used highlighting you may use matchadd() as I already said. But it is local to window so if you are working with multiple windows/tabs you can’t go without autocmd:
autocmd! WinEnter * :if !exists('w:parens_match_id') | let w:parens_match_id=matchadd('Parens', '[(){}]') | endif
All autocommands are to be surrounded with
augroup HighlightParens
autocmd! …
augroup END

No more messing up whitespace in VIM

I have an BufWritePre hook added to my .vimrc that trims trailing whitespace before a buffer is saved. This is very convenient for me when editing my own code or that of others who also have a policy to always remove trailing whitespace. However, this makes me sometimes mess up the whitespace of others, which doesn't look very nice in version control.
I have two ideas how this could be solved in general, both of which I have specific problems with:
Option 1
After opening a file (maybe using a BufReadPost hook), detect whether there is trailing whitespace in the file. If yes, set a buffer-local flag to signal this. If the flag is set, disable the trimming before a save.
The problem I have with this approach is that I don't seem to figure out how I can detect whether there is trailing whitespace in the buffer. I know about =~, but how do I get the buffer contents as a string? Or even better, I can do a search using /\s+$<cr>, but how can I check if the search was successful (if there are hits)?
Option 2 (more intelligent)
It would be even better if the whitespace trimming would only happen on the lines that were actually modified. This way I could have the benefit of not having to care about trailing whitespace in my code but still not messing up the rest of the file. This raises the question: can I somehow get the line numbers of the lines I added or modified?
I'm new to Vimscript, so I'd appreciate any hints or tips :)
UPDATE: I settled with option 1 now:
" configure list facility
highlight SpecialKey term=standout ctermbg=yellow guibg=yellow
set listchars=tab:>-,trail:~
" determine whether the current file has trailing whitespace
function! SetWhitespaceMode()
let b:has_trailing_whitespace=!!search('\v\s+$', 'cwn')
if b:has_trailing_whitespace
" if yes, we want to enable list for this file
set list
else
set nolist
endif
endfunction
" trim trailing whitespace in the current file
function! RTrim()
%s/\v\s+$//e
noh
endfunction
" trim trailing whitespace in the given range
function! RTrimRange() range
exec a:firstline.",".a:lastline."substitute /\\v\\s+$//e"
endfunction
" after opening and saving files, check the whitespace mode
autocmd BufReadPost * call SetWhitespaceMode()
autocmd BufWritePost * call SetWhitespaceMode()
" on save, remove trailing whitespace if there was already trailing whitespace
" in the file before
autocmd BufWritePre * if !b:has_trailing_whitespace | call RTrim() | endif
" strip whitespace manually
nmap <silent> <leader>W :call RTrim()<cr>
vmap <silent> <leader>W :call RTrimRange()<cr>
Option 1 can benefit from search() function, like so:
let b:has_trailing_spaces=!!search('\v\s+$', 'cwn')
search() function returns a number of matched line (they start from 1) or 0 if nothing was found, !! turns it to either 1 or 0, dropping information about on which line search() found trailing whitespace. Without n flag search() moves the cursor which is, I guess, undesired. Without w it may search only in the part of buffer that is after the cursor (really depends on 'wrapscan' option).
Proposed option 2 implementation is a hack that uses InsertLeave and '[, '] markers:
augroup CleanInsertedTrailingSpaces
autocmd!
autocmd InsertLeave * let wv=winsaveview() | keepjumps lockmarks '[,']s/\s\+$//e | call winrestview(wv)
augroup END
It assumes that you only add trailing whitespaces after typing. It will break if you move your cursor across the lines in insert mode. You can also try adding
autocmd CursorHold * if getpos("'.")[1]!=0 | let wv=winsaveview() | keepjumps lockmarks '.s/\s\+$//e | call winrestview(wv) | endif
, this should remove trailing spaces at the line of last change (only one line, '[ and '] can’t be used here because they point to first and last lines to often to be useful). Both autocommands should add information to undo tree.
There is a second option for the option 2: git annotate is able to annotate current state of the file thus you can use grep to filter out lines that have both trailing spaces and uncommitted changes and use a hook to purge unwanted spaces from them before commit. Sad, but hg annotate is not able to do so and thus you will have to write something more complex, possibly in python. I can’t say anything about other VC systems.
I guess it would be better if you used set list listchars+=trail:- to see such spaces and thus be able to remove them manually if they accidentally appear (personally I can’t remember myself constantly adding trailing spaces by accident, though in comments and documentation they are used by me intentionally to indicate that paragraph continues). What do you do so that this problem appears?
I tend not to let vim automatically trim anything. As you say, this can be a nightmare if dealing with other peoples code, and can lead to unnecessary conflicts. The approach I take, to keep my own code tidy is to make whitespace visible. With vim this can be achieved by adding the following to your ~/.vimrc file:
highlight SpecialKey ctermfg=DarkGray
set listchars=tab:>-,trail:~
set list
The result is to show whitespace like this:
This allows me to keep files clean whilst I write them. Most other (GUI) editors have the ability to show whitespace too.
" Show trailing whitepace and spaces before a tab:
:highlight ExtraWhitespace ctermbg=red guibg=red
:match ExtraWhitespace /\s\+$\| \+\ze\t/
:autocmd ColorScheme * highlight ExtraWhitespace ctermbg=red guibg=red
This way any bad whitespace will glow in red. It's quite hard to miss.

Resources