用astyle格式化代码
有时候从网上copy来的代码格式不怎么友好,一行行的改,我实在不乐意。之前在windows下用VS自带的ALT + F8着实爽了一把,当然还有CodeBlocks的astyle……
现在linux下我也想这样,VS是不用想了,astyle倒是可以……
1、astyle介绍
网址:http://astyle.sourceforge.net/
这里有源码,自己下载后解压安装下就可以了。
风格选项:

Bracket Style Options: ---------------------- --style=allman OR --style=ansi OR --style=bsd OR --style=break OR -A1 Allman style formatting/indenting. Broken brackets. --style=java OR --style=attach OR -A2 Java style formatting/indenting. Attached brackets. --style=kr OR --style=k&r OR --style=k/r OR -A3 Kernighan & Ritchie style formatting/indenting. Linux brackets. --style=stroustrup OR -A4 Stroustrup style formatting/indenting. Stroustrup brackets. --style=whitesmith OR -A5 Whitesmith style formatting/indenting. Broken, indented brackets. Indented class blocks and switch blocks. --style=banner OR -A6 Banner style formatting/indenting. Attached, indented brackets. Indented class blocks and switch blocks. --style=gnu OR -A7 GNU style formatting/indenting. Broken brackets, indented blocks. --style=linux OR -A8 Linux style formatting/indenting. Linux brackets, minimum conditional indent is one-half indent. --style=horstmann OR -A9 Horstmann style formatting/indenting. Run-in brackets, indented switches. --style=1tbs OR --style=otbs OR -A10 One True Brace Style formatting/indenting. Linux brackets, add brackets to all conditionals. --style=pico OR -A11 Pico style formatting/indenting. Run-in opening brackets and attached closing brackets. Uses keep one line blocks and keep one line statements. --style=lisp OR -A12 Lisp style formatting/indenting. Attached opening brackets and attached closing brackets. Uses keep one line statements.
2、bash中使用
如下源码:

#include <stdio.h> int main() {int i;printf("Just a test!\n");for(i=0;i<10;++i)printf("%d\n",i);}return 0;}
执行命令:astyle test1.c
效果如下:

#include <stdio.h> int main() { int i; printf("Just a test!\n"); for(i=0; i<10; ++i) { printf("%d\n",i); } return 0; }
当然还有其他选项:
astyle --style=bsd test1.c
astyle --style=gnu test1.c
……
3、在vim中使用
:%!astyle (simple case - astyle default mode is C/C++)
或者
:%!astyle --mode=c --style=ansi -s2 (ansi C++ style, use two spaces per indent level)
或者
:1,40!astyle --mode=c --style=ansi (ansi C++ style, filter only lines 1-40)
4、批量格式化
bash命令如下:
for f in $(find . -name '*.c' -or -name '*.cpp' -type f); do astyle $f; done
即如下bash脚本:

#! /bin/bash for f in $(find . -name '*.c' -or -name '*.cpp' -type f) do astyle $f done
好,就这些了,希望对你有帮助。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)