0

The following commands work fine when I issue them from the command mode in Vim:

:%s/\(^\s\+\)\(\S\+.*)\s*\){$/\1\2\r\1{/g
:g/^\s*\/\/$/d

But when I run the above commands as a script as below:

vim -c "commands.vim" myfile.c

I get errors:

enter image description here

Note: I am aware of this question: How to use "-c" command line option? but it has not helped with the error.

Sabuncu
  • 145
  • 1
  • 6

2 Answers2

2

Vim's -s {scriptin} command line argument* allows you to supply a file the contents of which will be interpreted as if you had typed them in, character by character.

This can be used for normal mode commands, but because you also generally enter command-line mode commands by typing them in, it works fine for ex commands too, so long as you include the colons at the start of each line (as you have).

vim -s commands.vim myfile.c

See :help -s for more details.

* Not to be confused with Vim's other -s argument, which only applies when ex mode is also specified: see :help -s-ex

Rich
  • 31,891
  • 3
  • 72
  • 139
0

Based on comment from ChristianBraband, I found a solution, with help from this page: https://en.wikibooks.org/wiki/Learning_the_vi_Editor/Vim/Modes

Modify the commands.vim script so that file update and quit are included at the end:

:%s/\(^\s\+\)\(\S\+.*)\s*\){$/\1\2\r\1{/g
:g/^\s*\/\/$/d
:update
:quit

Run from the command line as follows:

vim -c "source commands.vim" myfile.c

Update: Removed the unnecessary -E option per comment from @Rich.

Sabuncu
  • 145
  • 1
  • 6
  • 1
    vim -s commands.vim myfile.c is a bit simpler. See :h -s (and note difference from :h -s-ex). – Rich Nov 23 '17 at 16:33
  • @Rich Yes, this works and it is what I was after originally. If you can post it as an answer, I'll accept. Thank you. – Sabuncu Nov 23 '17 at 17:36
  • @Rich By the way, what a poor command-line design, having -s-ex and -s! – Sabuncu Nov 23 '17 at 20:09
  • I concur! Note that with your solution you don't need the colons at the start of each line (although it works fine with them). – Rich Nov 23 '17 at 23:20
  • @Rich Yet colons are required for -s (scriptin)! Another inconsistency. When I tried -s (scriptin) without colons, the whole thing exploded and the script itself got inserted into the file. – Sabuncu Nov 24 '17 at 08:09
  • That's because the two solutions work in different ways. Yours, using "source" via a -c parameter, is running ex commands. -s is emulating you actually typing the commands in. – Rich Nov 24 '17 at 10:44
  • Note also that the -E in your command is unnecessary. The commands in your file are run as Vimscript by your source command, so there's no reason to use ex-mode. – Rich Nov 24 '17 at 10:50
  • @Rich Thank you, this exchange has really been invaluable. – Sabuncu Nov 24 '17 at 11:57