How to create my custom vim snippets? - vim

I want to create some snippets when writting c++.
for example:
create a file, cpp.snippets.
priority -1
snippet exam
This is an example!
endsnippet
and put it in ~/.vim/my-snippets/snippets/.
then, add following statement in ~/.vimrc:
set runtimepath+=~/.vim/my-snippets/
let g:UltiSnipsSnippetsDir='~/.vim/my-snippets/'
let g:UltiSnipsSnippetDirectories=["snippets"]
But it not work, how can i fix it ?

UltiSnips plugin includes detailed documentation. Have you read the following help page?
:help UltiSnips-snippet-search-path
Update:
One of the things that was obvious when I read that help section was that in UltiSnips the name "snippets" can't be used in g:UltiSnipsSnippetDirectories because it is reserved for snipMate compatible snippets. This does not happen in the link shared in the comment below, where the name "my-snippets" is used instead.
I do not use UltiSnips, but from the documentation I would suggest the following approach:
Do not set g:UltiSnipsSnippetsDir nor g:UltiSnipsSnippetDirectories.
Keep the runtimepath+= configuration.
Create the following directory: ~/.vim/my-snippets/UltiSnips.
Place the personal snippets under this new directory.
Reasoning:
By default UltiSnips searches for all UltiSnips directories under your runtime paths, so no configuration is required if this name is used.
Although the runtime setting is required for personal snippets, this configuration is automatically maintained if a plugin manager is used.
The last point allows the installation of vim plugins that contain snippets. For example, this plugin contains various snippets for both snipMate and UltiSnips, including C++.

If you are using the sirver/ultisnips plugin (UltiSnips) the correct way to do this is simply run the :UltiSnipsEdit command which opens up a custom snippets file for the current language / filetype.

I had so much grief with this. Here is an answer for future reference for those of you who do not want to suffer headaches.
I have a shared .vimrc served on a samba share. Both Windows gViM and ViM use this file.
Relevant Part of .vimrc for Windows
I have a samba share mounted under L:. Note that I actually had to use POSIX for the path, not Windows backslashes \ despite being a path for Windows.
if has('win32') || has('win64') "If gVim under Windows"
let g:UltiSnipsSnippetDirectories=["L:/.vim/custom_snippets"]
endif
Relevant Part of .vimrc for Unix
My terminal opens xterm-256color for more colors, but you could exchange that with xterm. Here the path can expand ~ correctly, since this is the real home directory where my ``.vim` lives.
if $TERM == "xterm-256color"
let g:UltiSnipsSnippetDirectories=["~/.vim/custom_snippets"]
endif
Finishing Touches to Load custom_snippets
You don't need any! The following changes are NOT necessary:
"let g:UltiSnipsSnippetDirectories=["custom_snippets"]
"let g:UltiSnipsSnippetsDir="~/.vim/snippets_custom/"
However, Putty does not pass the tab key or control key properly it seems, despite all paths working fine. I tested the paths with :UltiSnipsEdit while in a file type environment set ft=tex and it took me to ~/.vim/snippets_custom/tex.snippets as it should (both in gvim on Windows and from my unix console).
Perhaps Useful for enabling in Putty
Patch: Creating a ctrl+tab keybinding in PuTTY
How to solve the collision of TAB key mapping of `UltiSnips` plugin in the Vim
https://unix.stackexchange.com/questions/53581/sending-function-keys-f1-f12-over-ssh

Related

Opening a file via Vim on GIT

I'm following a tutorial on Uniswap forking (just to learn how this works) and I'm stuck a particular step.
How does one go from:
vim migrations/2_deploy_contracts.js
to
I'm only able to see:
How do I see the folders and directories ?
The user in that particular video is using the NERDTree plugin for Vim. Vim is very powerful and extensible, and it's possible to load a variety of extensions written in Vimscript to customize the interface, add editor features (such as LSP support), or various other functionality.
They're also using a custom colorscheme which is probably based on the Solarized palette. You can also load a custom colorscheme with the :colorscheme ex command.
There is another thing to notice, besides mentioned NerdTree plugin.
I think you are running your command from the wrong place.
vim migrations/2_deploy_contracts.js
This command tries to open the file set by relative path, or creates a new file, if that does not exist. As we see from your screenshots - the file exists in the tutorial, but it does not exist on your machine (the [+] mark after the filename on the second screenshot shows that).
My guess you need to cd to the right directory first (tutorial project root) and then only run your vim command to open the file.
As for your question about seeing the files and directories, you can do it without NerdTree plugin, using built-in netrw. Just type :Ex in vim normal mode.

vim81 configuration wrong after I added .vimrc

I uninstalled vim74 and compiled vim81 and installed it. However I found it strange, comparing to vim74. When there's no .vimrc file under HOME dir, I open a c++ file and syntax highlight is working and I can use Backspace to delete letters. However when I add a .vimrc under HOME dir and just put set number into it, when the c++ source file is opened, no highlight, and Backspace not working. Why is that ? I used to add some configurations in .vimrc under vim74 before, and this situation never happens.
After complaints that Vim in its default configuration is hard to use (especially for beginners), it was decided to enable a default configuration if the user hasn't created his own ~/.vimrc (yet). This was introduced with Vim 8.0, and explains what you're seeing (namely: syntax highlighting and sensible backspace behavior). Read more about the details at :help defaults.vim.
The help also has instructions how to keep the defaults when adding your own ~/.vimrc configuration:
If you create your own .vimrc, it is recommended to add these lines somewhere
near the top:
unlet! skip_defaults_vim
source $VIMRUNTIME/defaults.vim
Then Vim works like before you had a .vimrc.
Tip: Don't go all crazy with adding various snippets (especially not those you don't fully understand) and plugins to your ~/.vimrc, even though the Internet is full of them. Rather, build it up gradually, depending on needs, and back up your understanding with careful studying of the excellent :help. Also, avoid pre-packaged Vim distributions; they're even worse.

vim snippet default snippet file issue

I installed Vundle, got the snippetMate running. But when vim launched, the snippet it loaded is _.snippets. With my Understanding, it is the default for snippet. However, i want to use other snippet such as sh.snippets and tex.snippets. I try to run the SnippetMateOpenFile in Vim to locate the snippets file It doesn't appear. I checked and see that all of the snippet file is there.
Yes, the _.snippets contains the global snippets. In order to use the other ones, the correct filetype has to be set. The snippet plugin reuses the same mechanism that Vim uses for syntax highlighting and settings (like indent) that are specific to a certain programming language. Usually, filetype detection works automatically; you can check with
:verbose setlocal filetype?
This needs to print sh for shell scripts, to use sh.snippets. If it doesn't, you have to fix / enable filetype detection (see :help filetype-detect), or, for a one-time fix, set it manually:
:setf sh
(I'm not sure about your particular snippet plugin; I guess it's snipMate, but there are multiple variants around.)
I found out what happened. the snippets won't recognize the snippet files rightaway. So i saved and exit the text and reopen vim again. It works, yet seems like there must be a certain tag in order for vim to recognize the format of the file.

Latex and Vim usage

How can I use Latex effectively in VIM?
Is there a way to configure compile errors by highlighting the line in vim?
I have syntax highlight. What are other recommended add-ons? Is a makefile the recommended way to compile a latex file to pdf?
TexWorks lets you open and replace the opened pdf everytime it's recompiled. Is there a plugin to do something similar in vim?
I've just begun playing around with LaTeX-Box. It seems like a good plugin. I, also used VIM-LaTeX for a while, but I didn't really like the key mappings, and it seemed a bit to heavyweight as Jeet described.
I like LaTeX-Box so far because it used latexmk to compile, which is what I was using anyway. Latexmk will sit in the background and watch your .tex file for changes, and then automatically compile for you. And if you use a pdf viewer which refreshed changes (such as evince on Linux) you can see updates every time you change. Adding
let g:LatexBox_latexmk_options = "-pvc -pdfps"
to my .vimrc got latexmk working properly. You also need the latexmk script somewhere on you PATH. The key mapping to start latexmk is the same as Vim-Latex's compile: '\ll' (that's lowercase LL).
I also use SuperTab plugin for completions, which is great. And I took the dictionary files from Vim-LaTeX so I have a ton of auto completion words to use. This dictionary file is: ftplugin/latex-suite/dictionaries/dictionary in the vim-latex files. What I did was copy this file into ~/.vim/dictionaries/ and renamed it 'tex' then I added these lines to my .vimrc file:
set filetype on
au FileType * exec("setlocal dictionary+=".$HOME."/.vim/dictionaries/".expand('<amatch>'))
set complete+=k
Then if I type the beginning of a latex command and hit 'tab' I will get a list of completions. Pretty handy. BTW that 'au' command in the vimrc will also load dictionaries for any other filetypes if you want. A useful trick.
check out vim latex
If you use vim latex put the following in your .vimrc:
let g:Tex_DefaultTargetFormat='pdf'
and it should compile to pdf by default. (I think the default compilation key
is \ll).
You can also check AutomaticLatexPlugin, it has many nice features (see the features list).
Its main point is to compile the document in the background using autocommands, so that you are free from compilation cycle. This works nicely on Linux and MacOs. It contains (extended version of) Latex-Box.
vim-latex is great. But I found it too heavyweight for my tastes. I prefer more of a "Vim with LaTeX compile & view" approach, rather than "A LaTeX IDE with Vim key-bindings". So I rolled my own: 'TeX-PDF: Lightweight "stay-out-of-your-way" TeX-to-PDF development support'.
Also check out: "LaTeX Help : Help for LaTeX in vim.help format" for calling up help of LaTeX from within Vim.
I personally can get by on:
autocmd BufNewFile,BufRead *.tex set makeprg=pdflatex\ %\ &&\ open\ %:r.pdf
where open is Mac OS X specific. Linux users will want a different command to view their compiled file after running make. This works best if you have mapped a key to write and then run make (and you should - once you have single key save and compile, you'll never go back).

Vim: apply settings on files in directory

How do I specify Vim settings for all files under the current directory?
The ideal solution would be if Vim searched for and read a .vimrc in the current directory before searching for ~/.vimrc, and apply the settings there for the entire tree.
I've seen a plugin, but this means the applied settings aren't transparent since they require the plugin to be installed. In contrast, a modeline is transparent since regardless of a user's vimrc or specific vim invocation the modeline settings will be applied for that file.
Things I tried are
placing a .vimrc in the working directory
:so vimrc in the modeline.
I suppose both don't work for security reasons. I don't need the full power of a vimrc; being bound to settings acceptable by a modeline would suffice. My goal is to make it easier for vimmers to adopt coding standards in a project.
You can put something like this in $VIM/vimrc
autocmd BufNewFile,BufRead /path/to/files/* set nowrap tabstop=4 shiftwidth=4
I'd strongly suggest not using set exrc
Even with set secure, under *nix, vim will still run autocommands, shell, et al, if you own the file. So if you happend to edit a file in that tarball I sent you with a .vimrc containing:
autocmd BufEnter * :silent! !echo rm -rf ~/
you'll probably be less amused than I will.
I'm an advocate of the plugin way.
For several reasons:
Modelines are particularly limited: we can't set variables (that tunes other (ft)plugins, like "should the braces of the for-snippet be on a newline ?"), or call function from them (I don't limit myself to coding standards, I also set the makefile to use depending on the current directory)
DRY: with modelines, a setting needs to be repeated in every file, if there are too many things to set or tunings to change, it will quickly become difficult to maintain, moreover, it will require the use of a template-expander plugin (which you should consider if you have several vimmers in your project).
Not every one uses vim to develop. I don't want to be bothered by other people editor settings, why should I parasite theirs?
It's easier to ask vimmers to install a same plugin, instead of asking them to copy-paste, and maintain, the same lines in their .vimrc
The settings can be saved with the other project files (cvs/svn/git/whatever)
It's really easy to have a configuration file per project -- with the plugin, I have a global configuration file for the coding standards of the overall project, and specific configuration files for each sub-project (which makefile to use, which executable to call, ...)
BTW, sth's solution can be used to source a single configuration file. This is very similar to the plugin approach except the .vimrc has to be parasited with non global options, and it does not support easily multiple/shared configuration files.
This question is old, but it seems like a pretty natural and persistent concern.
My solution is pretty simple. I place a .vimrc file in the root directory of my projects. The first line of the .vimrc file usually sources ~/.vimrc, and then adds the particular configuration I want. I alias tvim='vim -u .vimrc', and use tvim in my personal project directories. "tvim" for "trusted vim," meaning that if I execute it in a directory with a .vimrc file and something goes wrong, I've got no one to blame but myself, since I explicitly said I trusted it. Also, I keep a group of these stored away so that I can sometimes just softlink the one I want for a particular kind of project.
Placing a .vimrc in the working directory actually is supported, only disabled by default. See :h 'exrc' and :h startup for details, setting 'exrc' will enable reading .vimrc from the current directory.
It's also recommended to :set secure when using this. This locks down :autocmd, shell and write commands for .vimrc in the current directory.
Another thing that might be worth looking at is setting up a session (:h session) with a standard view and settings for the project.
All that said, I would probably go with the plugin option detailed by Luc Hermitte myself.
To minimize security risks with ANY "autorun" features for ANYTHING these days, may I advise you to utilize vim's existing features instead of plugins (portability baggage)?
Eg.
My local folder's vimrc file is named "_gvimrc" (on purpose). This reduces the hope for people like phen from amusing himself at our expense. :-)
In my $VIM/.vimrc file, I inserted:
if filereadable("_gvimrc")
source _gvimrc
endif
at the end.
I use "filereadable()" over "fileexists()" as the later has some quirkiness when tortured with opening multiple (10+) files simultaneously, (not sure why).
Of course, you can give your own unique filename to obfuscate potential trouble-makers further. Such as "_mygvimrc", "_gobbledygook", etc. You just need to settle on one standardized name and source it accordingly in your $VIM/.vimrc. Relying on vi/vim internals for this rules out portability issues. BUT, DO NOT name it .vimrc (or _vimrc) to prevent recursive sourcing in case you're editing the $VIM/.vimrc file with vim later.
Been using this since Windoze 98SE, through Windork XP Pro, and now Windorkier 7 (5+ years already). I'll mark a list of .txt files in Explorer and then use "Edit with multiple Vim", resulting in multiple vim windows opening simultaneously. For my work, I do this several times a day, daily. All files got treated with what I set in my local _gvimrc.
Use "editorconfig"
If the kinds of coding standards you would like to enforce are related to indentation style, tab size, file format and charset, then you might want to look into "editorconfig", which is a cross-editor standard to specify this kind of settings in a specific project, and have all editors follow that configuration.
The "editorconfig" specification allows projects to request different settings depending on file extensions or names within the project. (So you can have Makefiles using TABs, your Python scripts using 4 spaces and your shell scripts using 2 spaces for indentation.)
You need a plug-in to use "editorconfig" in Vim. The official website provides one, but personally I'd recommend sgur/vim-editorconfig, which is written in pure Vimscript, so you don't need to worry about external dependencies too much.
Since "editorconfig" aims at cross-editor compatibility, it's quite limited in what it does, so if you want is consistent whitespace, file format (DOS vs. Unix) and encoding (Unicode utf-8, etc.), then "editorconfig" is for you.
Assuming people aren't adding files every few days, you can probably add a modeline at the top of each file. In fact, if your version control system allows it, you could probably enforce a rule that says that each file must have a modeline when it's checked in.
I agree with the plugin approach for security reasons.
There is a very good plugin which has not been mentioned yet. It lets you use a .lvimrc in your project directories.
Try "localvimrc" out:
http://www.vim.org/scripts/script.php?script_id=441
https://github.com/embear/vim-localvimrc
Try vim-localrc
~/
|- .local.vimrc (1)
`- project/
|- .local.vimrc (2)
`- src/
|- .local.vimrc (3)
`- main.c
https://github.com/thinca/vim-localrc/blob/master/doc/localrc.txt
I looked at the plugins that existed and didn't really fancy any of them, so I wrote a simple function that piggy backs on vim-fugitive. The advantage of this is that it knows the root of the project is always the root of the repository, and additionally I can hash the file to keep a trust table. Just put the following in your .vimrc file.
function LoadRepoVimrc()
let l:path = fugitive#repo().tree('.vimrc')
if filereadable(l:path)
let l:sha1 = fugitive#repo().git_chomp('hash-object',l:path)
if !exists('g:SAFE_VIMRC') | let g:SAFE_VIMRC = {} | endif
if has_key(g:SAFE_VIMRC,l:path) && g:SAFE_VIMRC[l:path] ==? l:sha1
execute 'source '.fnameescape(l:path)
elseif confirm("Trust ".l:path."?", "&Yes\n&No",2) == 1
let g:SAFE_VIMRC[l:path] = l:sha1
execute 'source '.fnameescape(l:path)
else
execute 'sandbox source '.fnameescape(l:path)
endif
endif
endfunction
autocmd User FugitiveBoot call LoadRepoVimrc()
set viminfo ^= !
If the ! option is set on the viminfo setting, then the SAFE_VIMRC dictionary will be preserved between runs (note the ^ to prepend the option so it doesn't mess up the n option).

Resources