Search code examples
vimautocmd

Autocmd bufnewfile causing "Trailing characters" error on relative paths


I am having issue with my .vimrc file. I have completed an autocommand for all python and sh files. I have included both below. All works as expected when using a direct path ie:

gvim test.py

If I use a path relative to the cwd, however, such as:

gvim ../test.py

I receive the following error:

Error detected while processing BufNewFile Auto commands for "*.{py,sh}"

E488: Trailing characters

Any ideas on how to fix this problem?

autocmd bufnewfile *.{py,sh}
\ let path = expand("~/bin/Templates/")|
\ let extension = expand("%:e")|
\ let template = path . extension|
\ let name = "John Doe" |
\ if filereadable(template)|
\   execute "silent! 0r" . template|
\   execute "1," . 10 . "g/# File Name:.*/s//# File Name: " .expand("%")|
\   execute "1," . 10 . "g/# Creation Date:.*/s//# Creation Date: " .strftime("%b-%d-%Y")|
\   execute "1," . 10 . "g/Created By:.*/s//Created By: " . name|
\   execute "normal Gdd/CURSOR\<CR>dw"|
\ endif|
\ startinsert!

autocmd bufwritepre,filewritepre *.{py,sh}
\ execute "normal ma"|
\ execute "1," . 10 . "g/# Last Modified:.*/s/# Last Modified:.*/# Last Modified: " 
\ .strftime("%b-%d-%Y")

autocmd bufwritepost,filewritepost *.{py,sh}
\ execute "normal 'a"

The template for python files is as follows:

#!/usr/bin/python
# File Name: <filename>
# Creation Date: <date>
# Last Modified: <N/A>
# Created By: <Name> 
# Description: CURSOR

Solution

  • First of all, let's have a look at :help 10.2:

    The general form of the `:substitute` command is as follows:
         :[range]substitute/from/to/[flags]
    

    Please keep /[flags] in mind. Now when you enter gvim test.py in the command line, the following command is executed in Vim:

    :s//# File Name: test.py
    

    But when you enter gvim ../test.py Vim executes:

    :s//# File Name: ../test.py
    

    so Vim uses test.py as :substitute's flags and that's not the desired behavior.

    What you need is to replace expand("%") with expand("%:t") to get only the file name. See :help expand() for details.