0

What I want to achieve is simply set up some auto command that will detect anytime I create a new file and based on the name of the file I want to insert a couple of lines of text in that file. So if the file name matches my string it will insert lines of text.

I know how to insert text if a new a file was created via vim myfile but if within vim I do tabnew myfile nothing happens.

Hope I was clear, thanks!

  • I’m not sure what happened to the earlier comment here, but you cannot append text to a tab, only to a buffer (memory-representation of textual content, usually linked to a file; may be displayed in one or more windows, which are be in one or more tapages). Can you please edit your question to more clearly specify what your goals are and what you’ve attempted? – D. Ben Knoble Dec 29 '19 at 0:06
  • @D.BenKnoble I edited my question. – Moshe Rabaev Dec 29 '19 at 4:33
  • I know how to insert text if a new a file was created via Please, be more scrupulous. As for now, it looks like you're trying to do something with autocommands (an advanced topic), while not knowing what's a buffer name and filetype and how to change them (a basic topic). Also read :h :tabnew to see what's a proper syntax of this command. – Matt Dec 29 '19 at 6:14
  • @Matt no need to be so harsh; OP is trying to learn... we were all there at one time or another. – D. Ben Knoble Dec 29 '19 at 13:30
  • @D.BenKnoble I'm not, or, at least, I don't intend to be. But I just don't get what is the question about even after the edit. – Matt Dec 29 '19 at 13:53
2

As a first resource on files, buffers, tabs, etc., I recommend this QA and the many links to be found there.


As for autocommands, they are indeed an advanced topic, so having a good grasp of the fundamentals is crucial. In particular, when you start editing a file in a new tab (such as via :tabedit), either BufRead or BufNewFile should fire (Learn Vimscript the Hard Way has a great resource on autocommands, but I do recommend getting used to :help first).

So you can use something like

augroup MyGroup
  au!
  au BufRead,BufNewFile myPat normal! GAmy text
augroup END

You can also use the append(), though from mobile I don’t have the syntax offhand (something like call append(line('$'), 'my text')).

Lastly, if your specific filename is actually detected as a filetype, and you want to trigger for all filetypes, I would recommend reading about filetype-plugins. Start with the help, and then there are some great resources here (search ftplugin).

| improve this answer | |
  • Thanks for giving me the syntax and suggesting the resources before I dabble with auto commands, Excellent answer! – Moshe Rabaev Dec 29 '19 at 18:20
  • Is myPat supposed to be a regex pattern? – Moshe Rabaev Dec 29 '19 at 18:26
  • @MosheRabaev not exactly—see :help file-pattern – D. Ben Knoble Dec 29 '19 at 18:27

Not the answer you're looking for? Browse other questions tagged or ask your own question.