How do I stop vim reading in the default syntax? - vim

I have defined my own javascript syntax file, which is in ~/.vim/syntax/after/
The problem is that the default syntax file that exists in /usr/share/vim/vim82/syntax is loaded along side my custom syntax file (it seems to be loaded before my custom syntax).
The result is that it conflicts with my custom syntax.
How do I ONLY load my custom syntax file? Not the default one.
Of course I could just delete the default one (which works), but that seems like a not very robust fix to the problem considering it will just be put back there when vim is updated.
I have "syntax clear" at the top of my custom file but it doesn't help.
I also note that the default syntax file has the following at the top:
if !exists("main_syntax")
" quit when a syntax file was already loaded
if exists("b:current_syntax")
finish
endif
let main_syntax = 'javascript'
elseif exists("b:current_syntax") && b:current_syntax == "javascript"
finish
endif
But that doesn't do anything either.
I have also tried putting the syntax folder in .vim/syntax, as suggested on the official vim page, but that doesn't seem to do anything at all (as in, it's not read at all).
Thankyou.

In principle, the order in which syntax scripts are sourced is the following:
~/.vim/syntax/foo.vim
$VIMRUNTIME/syntax/foo.vim
~/.vim/after/syntax/foo.vim
~/.vim/after/syntax/ comes last. It is not a good place if you are writing a complete replacement of a built-in syntax script because you have at least one syntax script sourced before yours. On the other hand, it is a good place if what you want to do is either add your own stuff or selectively override stuff that has been set earlier.
$VIMRUNTIME/syntax/ is not a good place either, because it is a systemwide location. Your customisation is supposed to happen in your $HOME, right?.
~/.vim/syntax/ comes first so it is the ideal place for custom syntax scripts, if you add the following line:
let b:current_syntax = "javascript"
This is because $VIMRUNTIME/syntax/javascript.vim begins with the following boilerplate:
if !exists("main_syntax")
" quit when a syntax file was already loaded
if exists("b:current_syntax")
finish
endif
let main_syntax = 'javascript'
elseif exists("b:current_syntax") && b:current_syntax == "javascript"
finish
endif
which, essentially, throws the towel if b:current_syntax is set, and ends with:
let b:current_syntax = "javascript"
to "mark its territory", if you will.
You don't have to check for anything because you come first, but you still have to tell other syntax scripts to mind their own business.
Note that bad mannered syntax scripts may not check for that buffer-local variable so it is entirely possible to still have conflicts even if you are doing the right thing. But that's the nature of Vim.

Related

vim automatic hard wrap for fortran with line-continuation

I'm a Fortran programmer who uses both free-form and fixed form. Since I have to mix them, usually I write code in a common form between free and fixed format, so in this way I can tell to vim that all my files are in the free format.
Vim is great in doing things like autoindentation, but I would like to type and let vim automatically wrap my code, and placing the Fortran continuation character & at column 73 (or greater), and at column 6 in the new line. Is it possible, or does it exist a plugin for this?
Currently I'm using textwidth=72 in fortran files to hard wrap the lines.
Thanks in advance.
One way to make vim insert text when going to a new line is to use formatexpr. Set it so to capture the line and replace it with itself with & and new line appended, when at/beyond a given column. In this case you are handling line breaks and textwidth does not apply. I didn't yet get to test some simple code for it, but here is a related example.
Another way would be to write general code so that when in a given column it inserts & and <CR>.
However, making any such approach respect Fortran-specific exclusions (comments, for one thing) will make it more complicated. The best solution would be to find suitable existing option(s) for Fortran, but I haven't so far.
This is a comment on indentation in general. It should allow you to directly set up a desired rule for a new line. Here is one standard set of files that set up a lot of indentation rules and features.
The usual entry point is this vim script, which requires another standard set of files. The link given on that page for the other files is broken though, so here is where to find them: unpack this zip file (found on this page), right into your ~/.vim/ directory. It will create subdirectories indent/, syntax/, and ftpplugin/, or put files into them if they exist, so be careful if you have stuff there already.
Then you can put the first script linked above into .vim/after/indent/. In this file, there are specific calculations of where to put the cursor when a new line is entered. Find the right place(s) and change to your desired indent, or preferably set up a snippet from it in another file (so not to change this file). In this case you also need to set things up so that it overrides settings from the first file.
A useful resource is indentexpr (or :help indentexpr).
Here is also a tutorial on that.
These are comments on syntax in general, posted initially. They contain items of help related to what you want and should be generally useful, but probably have not much to say about adding &.
There are plugins for fortran. Here is the syntax file, with many things to tweak.
This may already be on your system. (It was on mine.) Thus I would go through and pick and choose things to add to your .vimrc. Here are a few options that are directly related
syn match fortranContinueMark display "&"
syn sync linecont "&" minlines=20
Here are paragraphs that seem to me relevant in their entirety
if (b:fortran_fixed_source == 1)
if !exists("fortran_have_tabs")
"Flag items beyond column 72
syn match fortranSerialNumber excludenl "^.\{73,}$"lc=72
"Flag left margin errors
syn match fortranLabelError "^.\{-,4}[^0-9 ]" contains=fortranTab
syn match fortranLabelError "^.\{4}\d\S"
endif
syn match fortranComment excludenl "^[!c*].*$" contains=#fortranCommentGroup
syn match fortranLeftMargin transparent "^ \{5}"
syn match fortranContinueMark display "^.\{5}\S"lc=5
else
syn match fortranContinueMark display "&"
endif
if b:fortran_dialect != "f77"
syn match fortranComment excludenl "!.*$" contains=#fortranCommentGroup,#spell
endif
Then a block of syn match statements follow for common cpp-like settings, and then
"Synchronising limits assume that comment and continuation lines are not mixed
if exists("fortran_fold") || exists("fortran_more_precise")
syn sync fromstart
elseif (b:fortran_fixed_source == 0)
syn sync linecont "&" minlines=20
else
syn sync minlines=20
endif
By your question it appears that you know how to set up .vimrc but here are a few comments.
Syntax support need be enabled with appropriate enable and autogroup statements, for example
syntax enable
" au BufRead,BufNewFile *.f90 FileType=fortran
au FileType fortran setlocal ...
Here are some common formatting options that I have for fortran
autocmd FileType fortran setlocal formatoptions=croql comments=:/!/
There can also be a t among options, for textwidth
Here are some specific settings I have, which I see in this syntax file with far more sophistication
let fortran_free_source=1
" Said to need fortran.vim and/or fortran support packages (they work)
let fortran_do_enddo=1
let fortran_more_precise=1
Standard vim help is of course extensive, but try :help fortran -- it has a number of useful settings right up front and is not overwhelming at all. Also see ft-fortran-syntax from help.
See this post with some troubleshooting if things aren't working right. Here is another useful post, even as it appears unrelated by its title.

Trojan in vim's latex_suite?

I was going through some code for latex_suite called vim_latex (http://vim-latex.sourceforge.net/) and I found few interesting lines in the file called "templates.vim":
" Back-Door to trojans !!!
function! <SID>Compute(what)
exe a:what
if exists('s:comTemp')
return s:comTemp.s:comTemp
else
return ''
endif
endfunction
Well, I'm not an expert on vim code, so I cannot interpret these lines except for the comment that freak me up a bit. Do you guys have an idea about what is happening ?
Edit:
The function seems to be called only by the following one:
" ProcessTemplate: processes the special characters in template file. {{{
" This implementation follows from Gergely Kontra's
" mu-template.vim
" http://vim.sourceforge.net/scripts/script.php?script_id=222
function! <SID>ProcessTemplate()
if exists('s:phsTemp') && s:phsTemp != ''
exec 'silent! %s/^'.s:comTemp.'\(\_.\{-}\)'.s:comTemp.'$/\=<SID>Compute(submatch(1))/ge'
exec 'silent! %s/'.s:exeTemp.'\(.\{-}\)'.s:exeTemp.'/\=<SID>Exec(submatch(1))/ge'
exec 'silent! g/'.s:comTemp.s:comTemp.'/d'
" A function only puts one item into the search history...
call Tex_CleanSearchHistory()
endif
endfunction
According to the header file description, the aim of these functions is to handle templates located into a specific directory.
I think the comment is intended as a warning. The function <SID>ProcessTemplate() goes through a template file, looks for certain (configurable) patterns, and calls <SID>Compute(what) where the argument what is text extracted from the template. Note the line :exe a:what.
If you install a template file from an untrusted source, then bad things can happen.
Of course, if you install a vim plugin from an untrusted source, equally bad things can happen. Putting malware in a template file adds a few levels of indirection, making it harder to implement and harder to diagnose.
It is possible that this code was written before the :sandbox command was added to vim, and that might be an easy way to make this code safer. I have not looked at what is allowed in the sandbox and compared it to the intended use of this template processing.

Indenting Fortran code in Vim

I have a fortran code which looks like this:
open(2,file=filenm(i),status='unknown')
do j=1,num_lines
do k=1,dime
read(2,*) z(k)
enddo
if( j .ge. 1000 ) then
do k=1,dime
sumz(k)=sumz(k)+z(k)
enddo
nsteps=nsteps+1.0
endif
enddo
close(2)
as you can see the indentation is not even, I would like to have something
like this:
open(2,file=filenm(i),status='unknown')
do j=1,num_lines
do k=1,dime
read(2,*) z(k)
enddo
if( j .ge. 1000 ) then
do k=1,dime
sumz(k)=sumz(k)+z(k)
enddo
nsteps=nsteps+1.0
endif
enddo
close(2)
I can go line by line fixing the indentation but the code is kind of big.
I appreciate any comment.
I've gone through a very similar process of trying to get Fortran indenting to work in vim. I still don't have it great, but I've made some progress. The script that arutaku posted (http://www.vim.org/scripts/script.php?script_id=2299) is where I started, but you need to make sure that filetype plugin indent on is in your vimrc.
I also needed a script for determining if I was using fixed-form or free-form syntax, since in my environment I use both. This is recommended in the documentation (http://vimdoc.sourceforge.net/htmldoc/syntax.html#ft-fortran-syntax). As it specifies, I put this script in ~/.vim/ftplugin/fortran.vim:
let s:extfname = expand("%:e")
if s:extfname ==? "f90"
let fortran_free_source=1
unlet! fortran_fixed_source
else
let fortran_fixed_source=1
unlet! fortran_free_source
endif
I also use a script so that I can press F7 to automatically complete certain constructs: http://www.vim.org/scripts/script.php?script_id=2487. I also put that in ~/.vim/ftplugin/.
I also have these in my vimrc to try to improve things further:
let fortran_do_enddo=1
let fortran_more_precise=1
let fortran_have_tabs=1
I believe those are supposed to interact with the first script to control its behavior, but I'm not convinced that they all work for me. I know the first is supposed to properly indent do/enddo blocks. The issue there is that since old-style Fortran allows a do without a matching enddo, the script can't indent them properly unless you can guarantee that you won't use unmatched 'do' statements. The let fortran_do_enddo=1 is supposed to be that guarantee, but it doesn't seem to work for me. The last one is supposed to allow usage of the tab character, which old Fortran considered bad, so it prevents them from being marked as errors. That one appears to work for me. And to be honest, I don't remember what the middle one is supposed to do nor if it works for me.
Edit:
I discovered that there was an older version of the the first script in my vim installation directory (/usr/share/vim/vim70/indent/ in my case) to which I do not have access rights. You might have those rights, and if it's causing you problems, overwrite or delete it. If, like me, you can't edit it, you can get the version in your $HOME to overwrite the functions from the first. I did this by doing two things. First I had to remove the checks to see if the functions already exist (the statements like if exists("*FortranGetFixedIndent")) and then I had to change all the function declarations to force overwriting by using the ! character, i.e. function! SebuFortranGetFreeIndent(). As far as I can tell, everything now works roughly as I would expect!
Does gg=G work?
gg: go to top
=: indent...
G: ... until the end
Try: https://sourceforge.net/projects/findent/files/
From the README:
findent: indents/beautifies/converts Fortran sources
findent supports Fortran-2008
findent can convert from fixed form to free form
binaries for Unix and Windows (findent and findent.exe respectively)
wrapper for processing one or more files in one call available for Unix and Windows (wfindent and wfindent.bat respectively)
(g)vim users: findent can act as a plug-in to format your edit file with the '=' command
gui frontent available in a separate package: jfindent
You can use auto-indentation writing <x>== (in command mode) where x is the number of lines to be indented.
If vim does not have fortran indentation you can load the following plugin and try the == combination: http://www.vim.org/scripts/script.php?script_id=2299

conflict in configuration file paths between Linux and Windows

I have this line in my .vimrc file:
set directory=~/.vim/swapfiles//
(Note that one extra slash makes the directory names to be included instead of just file names to reduce conflict)
The above config works fine on my Linux machine, but the problem is when I use the same file on Windows I get some warning about the file cannot be read. That's probably because vim is looking for ~/.vim/swapfiles/ directory, which Windows unfortunately don't have.
Is there any way to store my swap files on Windows somewhere (better if it could be in C:\Program Files\Vim\vimfiles\)?
CASE #2
If you got answer for my above question, here is the another one. I also have some lines similar to this:
autocmd filetype python source ~/path/to/file/python.vim
Windows confuses at this point too. How can I patch up?
If you don't want to introduce a $MYVIM variable as ZyX suggests, maybe an alternative is placing the runtime files in $HOME/.vim instead of the default $HOME/vimfiles on Windows. You can then use ~/.vim/... everywhere. This also helps with synchronizing the files across multiple mixed-platform machines.
" On Windows, also use '.vim' instead of 'vimfiles'; this makes synchronization
" across (heterogeneous) systems easier.
if has('win32') || has('win64')
set runtimepath=$HOME/.vim,$VIM/vimfiles,$VIMRUNTIME,$VIM/vimfiles/after,$HOME/.vim/after
endif
Maybe what you want is to have directory set based on the entries in runtimepath? Try this:
let &directory = substitute(&rtp, ",", "/swapfiles//,", "g")
With the default runtimepath setting on Unix-y systems you get
$HOME/.vim/swapfiles//,
$VIM/vimfiles/swapfiles//,
$VIMRUNTIME/swapfiles//,
$VIM/vimruntime/after/swapfiles//,
$HOME/.vim/after//
and on Windows
$HOME/vimfiles/swapfiles//,
$VIM/vimfiles/swapfiles//,
$VIMRUNTIME/swapfiles//,
$VIM/vimfiles/after/swapfiles//,
$HOME/vimfiles/after/swapfiles//
I agree, the after directories are unwanted, but vim will pick the first directory that exists and allows file creation so if you don't create the swapfiles sub-directory they won't be touched.
You might want to consider prepending these to the default value instead of replacing it so the defaults are available as a fallback if none of the directories exist.
I don't understand why you have the auto commands you mention. The default settings of runtimepath with filetype plugin on should take care of that for you.
Of course you always have the option of explicitly checking the platform and using different settings as in
if has("win32")
" settings for windows
elif has("win32unix")
" settings for cygwin
elif has("unix")
" settings for unix
elif has("macunix")
" settings for macosx
endif
If you want to avoid an error if a file does not exist then you can use the following definitions in your vimrc
func! Source(file)
if filereadable(a:file)
exec "source " . fnameescape(a:file)
endif
endfunction
com! -nargs=1 -complete=file Source call Source(<f-args>)
and change source to Source when the file might not exist.
First of all, vim translates all forward slashes to backward on windows thus it won’t hurt having slashes. Just in case you think it can be a source of trouble.
Second, it is not impossible to have ~/.vim and all other directories on windows, just some programs don’t want to work with names that start with a dot. You may just add this to runtimepath as it is not there by default on windows and move all user configuration there.
Third, in most places you have a filename you may use $ENV_VAR. It includes setting &rtp, &directory and using :source. So the solution may be the following:
if has('win16') || has('win95') || has('win32') || has('win64')
let $MYVIM=$HOME.'/vimfiles'
else
let $MYVIM=$HOME.'/.vim'
endif
set directory=$MYVIM/swapfiles
autocmd FileType python :source $MYVIM/after/ftplugin/python.vim
(though I agree with #Geoff Reedy that there should be no need in using the last line).
And last, modifying and storing something in C:\Program Files is not the best idea, neither for you nor for the program itself (by the way, vim won’t modify or store something there unless you told it to). It is to be modified by installation, update and uninstallation processes, not by anything else.
I fully agree with Geoff Reedy that the autocmd shouldn't be necessary. In other cases, you can use :runtime instead of :source. It will automatically search all (user and system directories in 'runtimepath'.

In VIM, how can I mix syntax/ident rules of both jinja and javascript in the same file?

I'm using jinja template language to generate html and javascript for a website. How can I make vim understand that everything between '{{'/'}}' and '{%'/'%}' is Jinja code and the rest it javascript code? Is there a simple way of doing that?
There is a relatively easy way to have different regions in your code that use different syntax files, by using the "syntax include" command and a "syntax region" command to define each region. Below is some code I have to syntax highlight different regions of Perl, R, and Python in a single document. The 'unlet' statments are necessary because the syntax files often depend on b:current_syntax not existing when they are first run. Yours would be similar, but define the 'start' and 'end' for the jinja and javascript regions using the delimiters you listed in your question. Check help for "syn-region" and "syn-include" to get more info:
let b:current_syntax = ''
unlet b:current_syntax
syntax include #Perlcode $VIMRUNTIME\syntax\perl.vim
syntax region rgnPerl start='^src-Perl' end='^end-Perl' contains=#Perlcode
let b:current_syntax = ''
unlet b:current_syntax
syntax include #rinvim $VIMRUNTIME\syntax\r.vim
syntax region rgnR matchgroup=Snip start="^src-R" end="^end-R" keepend contains=#rinvim
let b:current_syntax = ''
unlet b:current_syntax
syntax include #python $VIMRUNTIME\syntax\python.vim
syntax region rgnPython matchgroup=Snip start="^src-Python" end="^end-Python" keepend contains=#python
let b:current_syntax='combined'
I'm not sure about how to get different auto-indenting in the regions, that's a question I was going to look into myself. I think one solution would be to consolidate all of the languages indent files into one and have an if structure that processes according to which region it finds itself in. Maybe there's a simpler way than that, though.
For the syntax, my SyntaxRange plugin makes the setup as simple as a single function call.
For different filetype settings like indentation options, you have to install an :autocmd CursorMoved,CursorMovedI that checks into which region the current line falls (maybe using the syntax for hints, e.g. with synID()), and then swaps the option values depending on the result.
Edit: For your particular use case, that would be something like:
:call SyntaxRange#Include('{{', '}}', 'jinja')
:call SyntaxRange#Include('{%', '%}', 'jinja')
which you could put into ~/.vim/after/syntax/javascript.vim to apply it automatically to all JavaScript files.

Resources