Skip to content

Instantly share code, notes, and snippets.

@epakai
Created January 17, 2023 20:42
Show Gist options
  • Select an option

  • Save epakai/570ea459cde7af97de8912be16def1b7 to your computer and use it in GitHub Desktop.

Select an option

Save epakai/570ea459cde7af97de8912be16def1b7 to your computer and use it in GitHub Desktop.
Close all vim buffers with files under a path
Your vim needs to be compiled with clientserver support. You can check:
vim --version|grep +clientserver
Set up an alias so regular vim starts with a server (add it to your shell aliases):
alias vim='vim --servername "VIM"'
#!/bin/bash
help="Closes all vim buffers with files under given path.\n\
Modified buffer contents will be written out."
if [ $# -eq 0 ]
then
echo -e "$help"
echo "Usage: $0 PATH"
exit
fi
close_path="$1"
abs_path=$(readlink -f "$close_path")
expand_tilde()
{
case "$1" in
(\~) echo "$HOME";;
(\~/*) echo "$HOME/${1#\~/}";;
(\~[^/]*/*) local user=$(eval echo ${1%%/*})
echo "$user/${1#*/}";;
(\~[^/]*) eval echo ${1};;
(*) echo "$1";;
esac
}
for SERVER in $(vim --serverlist)
do
vim --servername "$SERVER" --remote-expr \
"execute('cd /')" > /dev/null
IFS='
'
vim --servername "$SERVER" --remote-expr "execute('buffers\!')" |
while read -r line; do
if [ x"$line" != x ]
then
preamble=$(echo "$line" | cut -d \" -f 1)
bufnum=$(echo "$preamble"|tr -s ' '|cut -d " " -f 2)
noncanonical=$(echo "$line" | cut -d \" -f 2)
expanded=$(expand_tilde "$noncanonical")
filename=$(readlink -f "$expanded")
if [[ $filename == $abs_path* ]]
then
if [[ $preamble == *"+"* ]]; then
vim --servername "$SERVER" --remote-expr \
"execute('${bufnum}bufdo! :w')"
fi
vim --servername "$SERVER" --remote-expr \
"execute('bd $bufnum')"
fi
fi
done
vim --servername "$SERVER" --remote-expr \
"execute('cd -')" > /dev/null
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment