Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a bash script to open multiple files in Vim using splits and tabs?

Tags:

bash

vim

I am trying to automate some manual labor, using a bash script. Basically I open multiple files with Vim in 1 terminal-window (and only one terminal-tab), using several splits, vsplits and tabs. I will now describe a general case to explain what I usually do manually.

I use 3 tabs (referring from here on as A, B and C) and I open 4 files in each tab in a 2x2 layout:

bash:~$ cd ~/Workspace/
bash:~/Workspace$ vim A11.m
:vsplit A12.m
:hsplit A22.m
"move cursor to A12.m"
:hsplit A21.m
:tabedit B11.m
:vsplit B12.m
:hsplit B22.m
"move cursor to B12.m"
:hsplit B21.m
:tabedit C11.m
:vsplit C12.m
:hsplit C22.m
"move cursor to C12.m"
:hsplit C21.m

What I would like to create is a shell script into which the file names and location(s) are hard-coded, which upon execution would do all the above. Can anyone suggest to me an approach which would make this possible (if possible at all)? Thanks in advance!

ps: In my .vimrc I have added some configurations such that :split opens the new file beneath (instead of above) the current file and :vsplit opens the new file to the right (instead of to the left).

like image 517
Aeronaelius Avatar asked Dec 06 '22 12:12

Aeronaelius


2 Answers

What about :help mksession?

  1. Set up all your tabs and windows.

  2. Do :mks /path/to/mysession.vim to save the current settings and layout into /path/to/mysession.vim.

  3. Quit Vim.

  4. Open Vim with $ vim -S /path/to/mysession.vim to restore your workspace.


You can also restore your session with $ vim -c "so /path/to/mysession.vim" or, when Vim is already runing, with :so /path/to/mysession.vim.

like image 156
romainl Avatar answered Dec 14 '22 22:12

romainl


There are at least four ways to do this:

  1. vim -s <(echo $':vsplit A12.m\n:hsplit A22.m\n…')
    
  2. vim -S <(echo $'vsplit A12.m\nhsplit A22.m\n…')
    

    it is similar to what @romainl, but you create the script by yourself and do not use any file besides the bash script itself (can be as well just an alias or a line in history). It is possible to use HERE-strings in bash, they are more readable:

    vim -S <(cat <<<EOF
    vsplit A12.m
    hsplit A22.m
    …
    EOF
    )
    
  3. vim -c 'vsplit A12.m | hsplit A22.m | …'
    

    You can have multiple -c keys which are run in sequence, but not more then ten thus you have to join commands in one -c with bar.

  4. Instead of a bash script use vim one:

    #!/usr/bin/vim -S
    vsplit A12.m
    hsplit A22.m
    …
    

    . Then you can chmod +x it and run like any other executed file. Vim treats #! as a comment leader just for that reason.

like image 43
ZyX Avatar answered Dec 15 '22 00:12

ZyX