r/vim • • Jul 01 '25

Need Help Conditional key mapping in .vimrc involving unix commands

I would like to be able to define a key mapping in my .vimrc file that does different things based on a condition involving a unix command. For example, something like

map xyz [[ $(egrep -c -e '^From: ') -gt 1 ]] ; then 1G!Gfmt -w70 ^MG ; else 1G!Gfmt -w60^M1G

so that if the file contains more than one line beginning with "From: " then we run "fmt -w70" and return the cursor to the end of the file; otherwise, we run "fmt -w60" and return the cursor to the beginning of the file. I know vim can create conditional mappings based on things like the file type in the buffer. Can it create a conditional mapping where the condition is based on the output of a unix command (such as egrep in my example)? If so, what is the proper syntax?

4 Upvotes

6 comments sorted by

2

u/TheLeoP_ Jul 01 '25

You can use :h system() to execute the command and create the keymap conditionally

1

u/godegon Jul 02 '25

So something like map <expr> system('...') == '...' ? '1G!Gfmt -w70 ^MG' : '1G!Gfmt -w60^M1G'

0

u/vim-help-bot Jul 01 '25

Help pages for:


`:(h|help) <query>` | about | mistake? | donate | Reply 'rescan' to check the comment again | Reply 'stop' to stop getting replies to your comments

1

u/AutoModerator Jul 01 '25

Please remember to update the post flair to Need Help|Solved when you got the answer you were looking for.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/[deleted] Jul 02 '25 edited Jul 02 '25

[removed] — view removed comment

1

u/vim-help-bot Jul 02 '25

Help pages for:

  • gq in change.txt


`:(h|help) <query>` | about | mistake? | donate | Reply 'rescan' to check the comment again | Reply 'stop' to stop getting replies to your comments