vim - 使 vim 在循环时正确缩进管道

标签 vim indentation

我一直在用这行代码读取ip_list.txt中的ip 1.1.1.1,存入变量line然后打印出来:

if [ true == false ]; then # Example
ip="1.1.1.1"
grep -r $ip ip_list.txt | while read -r line ; do
echo "Line is: $line"
done
fi

代码运行良好,但 vim 无法正确缩进此代码。当我这样做时,g=GG,您可以看到 done 语法应该排在 grep 语法下方,但它用 if 语句。它在 vim 中会像这样缩进:

if [ true == false ]; then
    ip="1.1.1.1"
    grep -r $ip ip_list.txt | while read -r line ; do
    echo "Line is: $line"
done # Went to the left. Not lined up with grep
fi

即使我删除了 ; ,并让 do 在底部像这样:

if [ true == false ]; then # Example
ip="1.1.1.1"
grep -r $ip ip_list.txt | while read -r line
do
echo "Line is: $line"
done
fi

done 语法在 vim 代码编辑器中仍然没有正确缩进(现在如果我做 g=GG):

if [ true == false ]; then
        ip="1.1.1.1"
        grep -r $ip ip_list.txt | while read -r line
do
        echo "Line is: $line"
done # not lined up with grep syntax
fi

有什么方法可以编辑此代码以便 vim 可以正确缩进它?

预期的输出应该是:

if [ true == false ]; then
    ip="1.1.1.1"
    grep -r $ip ip_list.txt | while read -r line ; do
        echo "Line is: $line"
    done
fi

或者应该是

if [ true == false ]; then
    ip="1.1.1.1"
    grep -r $ip ip_list.txt | while read -r line
    do
        echo "Line is: $line"
    done
fi

最佳答案

vim 的缩进正则表达式不够智能。如果您愿意,可以自己编辑语法文件:使用 :scriptnames 查看 vim 加载的文件 查看 syntax/sh.vim 的完整路径> 文件。

一个更简单的方法是改变你的 bash 语法:

if [ true == false ]; then # Example
ip="1.1.1.1"
while read -r line; do
echo "Line is: $line"
done < <(grep -r $ip ip_list.txt )
fi

正确缩进到

if [ true == false ]; then # Example
  ip="1.1.1.1"
  while read -r line; do
    echo "Line is: $line"
  done < <(grep -r $ip ip_list.txt )
fi

关于vim - 使 vim 在循环时正确缩进管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64339467/

相关文章:

java - 自动缩进 Java 和 HTML 文件的脚本或程序

python - Eclipse,使用外部工具直接编辑文本

visual-studio-code - prettier-vscode 忽略了我的标签设置

vim - 使用 vim 处理文件缓存而不是实际文件的方法?

list - ViM:如何将输入对话框中的字符串放入列表中

vim - 将 VIM 设置为 256 色

vim - 如何在 Vim 中一次性将文件中所有指定单词从大写更改为小写?

vim - 如何在 vim 或 emacs 等编辑器中的 Web 浏览器(例如 Firefox)中打开文件?

vim - 如何在 Vim 中快速选择(内部)行

python - Emacs 24.3 python : Can't guess python-indent-offset, 使用默认值 4