This is really a newbie question - but basically, how do I enable a template for certain filetypes.
Basically, I just want the template to insert a header of sorts, that is with some functions that I find useful, and libraries loaded etc.
I interpret
:help template
the way that I should place this in my vimrc
au BufNewFile,BufRead ~/.vim/skeleton.R
Running a R script then shows that something could happen, but apparently does not:
--- Auto-Commands ---
This may be because a template consists of commands (and there are no such in skeleton.R) - and in this case I just want it to insert a text header (which skelton.R consist of).
Sorry if this question is mind boggeling stupid ;-/
The command that you've suggested is not going to work: what this will do is run no Vim command whenever you open ~/.vim/skeleton.R
A crude way of achieving what you want would be to use:
:au BufNewFile *.R r ~/.vim/skeleton.R
This will read (:r) your file whenever a new *.R file is created. You want to avoid having BufRead in the autocmd, or it will read the skeleton file into your working file every time you open the file!
There are many plugins that add a lot more control to this process. Being the author and therefore completely biased, I'd recommend this one, but there are plenty of others listed here.
Shameless plug:
They all work in a relatively similar way, but to explain my script:
You install the plugin as described on the linked page and then create some templates in ~/.vim/templates. These templates should have the same extension as the 'target' file, so if it's a template for .R files, call it something like skeleton.R. In your .vimrc, add something like this:
let g:file_template_default = {}
let g:file_template_default['R'] = 'skeleton'
Then create your new .R file (with a filename, so save it if it's new) and enter:
:LoadFileTemplate
You can also skip the .vimrc editing and just do:
:LoadFileTemplate skeleton
See the website for more details.
Assume that your skeletons are in your ~/.vim/templates/ directory, you can put this
snippet in your vimrc file.
augroup templates
au!
" read in templates files
autocmd BufNewFile *.* silent! execute '0r ~/.vim/templates/skeleton.'.expand("<afile>:e")
augroup END
Some explanation,
BufNewFile . = each time we edit a new file
silent! execute = execute silently, no error messages if failed
0r = read file and insert content at top (0) in the new file
expand(":e") = get extension of current filename
see also http://vim.wikia.com/wiki/Use_eval_to_create_dynamic_templates
*fixed missing dot in file path
Create a templates subdirectory in your ~/.vim folder
$ mkdir -p ~/.vim/templates
Create a new file in subdirectory called R.skeleton and put in the header and/or other stuff you want to automagically load upon creating a new ".R " file.
$ vim ~/.vim/templates/R.skeleton
Then, add the following to your ~/.vimrc file, which may have been suggested in a way by "guest"
autocmd BufNewFile * silent! 0r $HOME/.vim/templates/%:e.skeleton
Have a look at my github repository for some more details and other options.
It's just a trick I used to use .
It's cheap but If you ain't know nothing about vim and it's commands it's easy to handle.
make a directory like this :
~/.vim/templates/barney.cpp
and as you konw barney.cpp should be your template code .
then add a function like ForUncleBarney() to end of your .vimrc file located in ~/.vimrc
it should be like
function ForBarneyStinson()
:read ~/.vim/templates/barney.cpp
endfunction
then just use this command in vim
:call ForBarneyStinson()
then you see your template
as an example I already have two templates for .cpp files
:call ForBarney()
:call ACM()
sorry said too much,
Coding's awesome ! :)
Also take a look at https://github.com/aperezdc/vim-template.git.
I use it and have contributed some patches to it and would argue its relatively full featured.
What about using the snipmate plugin? See here
There exist many template-file expanders -- you'll also find there explanations on how to implement a rudimentary template-file expander.
For my part, I'm maintaining the fork of muTemplate. For a simple start, just drop a {ft}.template file into {rtp}/template/. If you want to use any (viml) variable or expression, just do. You can even put vim code (and now even functions) into the template-file if you wish. Several smart decisions are already implemented for C++ and vim files.
Related
I want not to type
#include
using namespace std
int main()
...
everytime, so what I want is like when I type like this in cmd
gvim -option hello.cpp
gvim starts with this code automatically
#include <iostream>
using namespace std;
...
Can I do this?
Noah Frederick has a very interesting article entitled: "File Templates with UltiSnips and Projectionist" and it combines file templates with ultisnips
Basically, if the new file is empty it inserts a snippet _skel automatically. The advantage of this method is that a template is dynamic instead of a static template.
OBS: I am not sharing the code here to give Noah the credit, I believe it is worth reading the whole article.
Yes you can do even better
short answer: take a look at this plugin https://github.com/sirver/UltiSnips
see :h vimrc
long answer: vim is very customizable editor you have option to create your own mapping see :help map-commands
and with help of read see :help read you can read content of any file or external command
now with combining these two things lets say you create a simple file in ~/.vim/snips folder called cppHello.snip and you place content inside it
now you create a mapping let's say nnoremap <leader>hw :read ~/.vim/snips/cppHello.snip<cr> ( see :h <Leader>) now everytime you type <leader>hw vim will place the content of above file in your current buffer bellow your cursor position
There's no need for additional plugins as vim's autocmd can be used for use-cases like this. See :h autocmd for more info.
Here's how you do it. Add the following lines to your vimrc file, if you don't have a vimrc file already, lookup how to add one using :h vimrc
augroup CppContext
autocmd BufNewFile *.cpp execute 'silent! 1s/.*/#include\rusing namespace std\rint main()'
augroup end
Reopen vim using vim your_file_name.cpp and you should have the lines mentioned added automatically.
Explanation
using BufNewFile event, you can execute steps/commands when starting to edit a non-existent file
With *.cpp we're using file globbing and matching only .cpp files
And everything to the right of the *.cpp is the command, which basically enters the text you wanted.
I'm looking for a way to determine the filetype of a file in vim and set the syntax highlighting based on the filetype. The only catch is I cannot use the file extension for determining the filetype.
This is my scenario: I use vimdiff or gvimdiff as my P4DIFF tool, which shows the changes between the files in my local copy and the ones from the perforce server. Perforce seems to bring in the files from the perforce server into the /tmp directory and uses the PID to name the file, for example:
/tmp/tmp.24673.23
This was for a C++ source file.
The most frequent filetypes I encounter in the perforce repository are C/C++ sources and header files, Makefiles, python scripts, perl scripts, ruby scripts, and tcl scripts.
I've looked into using modeline, but most of the sources in our tree do not have this information embedded in the file.
This post mentions about a possible approach to search and identify a magic pattern. I could not find any consistent magic pattern that I could get a high success rate with.
Tried using the file binary on my linux box to see what results I get. It seems to identify C/C++ sources well, but fails for Makefiles and even python scripts (which don't have the hashbang)
One good thing is that, among the 2 files that are compared, the file on the right is from my local copy and hence has the correct file name with extension, thereby syntax highlighting is enabled correctly for the file on the right.
Is there a way I could leverage this to set the same syntax highlighting for the file displayed on the left ?
Any alternate solutions to this problem are also welcome.
This was an interesting puzzle. :)
aug SmartDiffType
au!
au VimEnter * :if &diff && len(&ft) | call setwinvar(2/winnr(),'&ft',&ft) | elseif &diff | let &ft=getwinvar(2/winnr(),'&ft') | endif
aug END
Notes:
Of the 4 lines above, you only need the au VimEnter line, but it is generally a good practice to put autocommands in some autocommand group with a reset (au!) at the top.
Autocommand on VimEnter because otherwise diff or the windows are not properly intialized yet
vimdiff might have been triggered with the old file on the right or the left of the split, so we consider both cases.
The 2/winnr() is a math trick to flip between 1 and 2 (2/2 = 1, 2/1=2)
Assuming that you have open only the 2 splits and the split on the left is your local file you can do the following
:windo let &ft = getwinvar(1, '&ft')
This will set the filetype to the value of the top left most window for all windows.
For more help see:
:h :windo
:h 'ft'
:h getwinvar(
I'm trying to have the command
let b:match_words='<:>,<\#<=\([^/][^ \t>]*\)[^>]*\%(>\|$\):<\#<=/\1>'
run every time I open an html file. I tried putting the line
autocmd FileType html let b:match_words='<:>,<\#<=\([^/][^ \t>]*\)[^>]*\%(>\|$\):<\#<=/\1>'
in a file named html.vim in both my ftdetect and ftplugin folders and nothing happened. How do I have the command run everytime I'mm in an html file?
The command is to change the matching behavior of matchit btw.
In general, your autocmd is alright; the problem is that you're trying to redefine the b:match_words definition done in $VIMRUNTIME/ftplugin/html.vim, so the execution order becomes important.
The place for these customizations is in the after directory, i.e. ~/.vim/after/ftplugin/html.vim; just create a new file and put the :let command in there.
You can observe the sequence of sourced scripts via :scriptnames. In other cases, when you're not overriding default behavior, the :autocmd FileType is alright, but I prefer putting these (e.g. custom mappings) into ~/.vim/ftplugin/html_mymappings.vim, as it provides better separation and helps keeping your .vimrc short and understandable.
The ftdetect subdirectory is for filetype detection, i.e. inspecting file path / name / contents to determine the correct filetype. It doesn't apply here, as the filetype is html.
I'm after a means by which I can add additional commands to a text file via vim. For example, just as you can do something like this:
# vim:syntax=foo
I'd like to do something like:
# vim:option call matchadd('Special', '\(REQUIRED\|OPTIONAL\)')
Any ideas? I know I can write a syntax file, but this is not what I'm after for now.
Vim modeline syntax (see :help modeline) is not intended to specify commands
to execute during file opening. That is exactly what autocommands is for (see
:help autocommand). What you are trying to do should be an autocommand
similar the following.
autocmd FileType foo call matchadd('Special', '\(REQUIRED\|OPTIONAL\)')
or
autocmd BufReadPost *.foo call matchadd('Special', '\(REQUIRED\|OPTIONAL\)')
(Here instead of *.foo you can use any pattern that matches path or filename
(or both) of the target file.)
If the configuration you are setting up is local to some files or a project,
and you don't want to pollute your .vimrc with those autocmds, use
localvimrc plugin. It allows you to have a "local" .vimrc file next to
your target file or project folder. Script stored in that .lvimrc is
executed when you open files in the same directory where the "local" .vimrc
is, or in its subdirectories. Autocommands shown above (or any other
configurations) can be stored in a .lvimrc file local the project. For
details about localvimrc configuration see the homepage of the plugin.
This isn't an answer to your question, but I have also searched for Truth, and this question here is the closest one to it:
Vim: How to execute selected text as vim commands
It isn't automatic, but potentially only one keypress away it's close enough. :)
My ModelineCommands plugin extends Vim's built-in modelines to execute any Ex command(s) when a file is opened. A set of configurable validators examine the commands and can verify the correctness of an optional command digest, in order to prevent the execution of potentially malicious commands from unknown sources. (That's the main reason why Vim doesn't offer this feature!) This way, you could restrict the commands to only simple :let, or have the plugin query you to confirm execution of anything that isn't signed with your own secret key.
I am trying to create a new snippet to my snipMate plugin.
I work with some files called (i.e.) myfile.endfile
All .endfile files should have the same "snippet" like .html files.
So I did
cp html.snippet endfile.snippet
in my ~/.vim/snippets directory.
SnipMate is working with all present snippets, but not with my new created one.
Any suggestions for this problem?
(Btw: after creating the new .snippet file, I ran :helptags ~/.vim/doc command in an vim instance.)
It is because Snipmate works with filetype, which is a Vim option set when opening a file of a particular type.
For exemple, if you are opening, "index.html" the filetype is automatically set to html.
To see how it works, do :
:e $VIMRUNTIME/filetype.vim
As a preliminary test, you can :
1. open test.endfile
2. type :set ft=endfile or :set filetype=endfile
3. Check if your defined snippets now work
To do that automatically add the following in your .vimrc :
au BufNewFile,BufRead *.endfile set filetype=endfile
It means that every time you read or create a new file ending in endfilethe filetype option is set to endfile.
(The filetype is an arbitrary string it doesn't have to be identical to the file extension)
You can assign snippets without altering the filetype (which is desirable, because altering the filetype breaks syntax highlighting).
I believe the proper way to do this in the maintained fork of snipmate is to set g:snipMate.scope_aliases.
In your example, assuming you have an 'endfile.snippet' file, I believe adding the following to your .vimrc would work:
let g:snipMate = {}
let g:snipMate.scope_aliases = {}
let g:snipMate.scope_aliases['html'] = 'endfile'
If you want both html and endfile snippets to work for files of filetype='html', then use:
let g:snipMate = {}
let g:snipMate.scope_aliases = {}
let g:snipMate.scope_aliases['html'] = 'html,endfile'
I've added a pull request to snipmate to have their documentation updated. Edit: It has now been merged.
I found it convenient to use global snippets when using snippets that have uncommon name.endfile.
When you put your snippets in _.snippets file inside snippets folder they become global and are accessible in every filetype.
Maybe this is not directly answer to the question but a lot of users with similar problem can find this convenient. Specially if they don't have need to have everything organised in various files and are happy to have their own snippets in one file that is accessible everywhere.