我想使用vim作为通用源代码压头.
这是我对shell函数的初步尝试,它根据filetype和shiftwidth参数包装vim的调用以使vim重新生成STDIN:
vim-indent () {
local ext=$1
local width=$2
local file=$(mktemp --suffix=."$ext")
cat >| "$file"
vim -E +"set sw=$width|normal! gg=G" +'x' -- "$file" >/dev/null
cat "$file"
}
Run Code Online (Sandbox Code Playgroud)
vim-indent c 2 << "EOF"
int main(int argc, char** argv) {
char operator;
printf("Enter an operator (+, -): ");
scanf("%c", &operator);
switch (operator) {
case '+':
case '-':
printf(operator);
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
EOF
Run Code Online (Sandbox Code Playgroud)
成功.c源重新缩进,有2个空格缩进:
int main(int argc, char** argv) {
char operator;
printf("Enter an operator (+, -): ");
scanf("%c", &operator);
switch (operator) ?{
case '+':
case '-':
printf(operator);
break;
default:
printf("Error! operator is not correct");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
vim-indent sh 2 << "EOF"
#!/usr/bin/bash
hello() {
echo "Hello World"
}
if true; then
echo "It is true"
fi
EOF
Run Code Online (Sandbox Code Playgroud)
失败.函数体正确缩进,但不是if语句:
#!/usr/bin/bash
hello() {
echo "Hello World"
}
if true; then
echo "It is true"
fi
Run Code Online (Sandbox Code Playgroud)
vim-indent html 2 << "EOF"
<html>
<body>
<div>
<p>Hello</p>
</div>
</body>
</html>
EOF
Run Code Online (Sandbox Code Playgroud)
失败.根本没有缩进:
<html>
<body>
<div>
<p>Hello</p>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我在vim中编辑 bash和html文件时,我可以很好地重新使用它们.
为什么上述试验成功c的源代码,但失败bash和html源代码?
我结合了答案中的建议并创建了一个工作shell脚本(作为下面的答案提交),我可以将其用作通用源代码压缩器.
将此添加到.vimrc:
filetype plugin indent on
Run Code Online (Sandbox Code Playgroud)
根据您的html缩进首选项,您可能还需要将此行添加到.vimrc:
let g:html_indent_inctags="html,body,head"
Run Code Online (Sandbox Code Playgroud)
这条线是因为在某些版本的Vim默认的HTML缩进文件(位于所需:e $VIMRUNTIME/indent/html.vim)将不会内缩线<html>,<body>和<head>标签.