源代码格式化程序/缩进器

我正在使用Ubuntu 12.04。由于这是公司的机器,我没有任何root或sudo权限。

在Ubuntu 12.04的正常安装中,是否有任何终端程序可以将丑陋的源代码(缺乏缩进)转换为漂亮的代码?

再次强调,我无法安装任何软件包,所以我需要一个已经随Ubuntu一起提供的工具,如果有的话。

例如:

    int main()
    {
test(1);
another_function(1);
}

然后将其转换为:
int main()
{
    test(1);
    another_function(1);
}

你用什么工具来查看或编辑代码?我猜你希望在编辑器中进行缩进,对吗?还是你想通过命令行来处理多个文件? - terdon
你是指像一个在线工具吗? - Braiam
1Gedit会自动缩进,而Kate则会根据文件类型进行高亮和缩进,如果你有能力切换到KDE的话。 - eyoung100
6个回答

clang-format是你的好朋友!它易于使用且非常有用。
以下是一些关于它的信息。

使用方法

$ clang-format file > formattedfile

或者:

$ clang-format -i file
逐步指南

1. 糟糕格式的代码

#include <iostream>
  using namespace std;
    int main() {
         cout << "Oh";
      cout << "clang format rulez!";       
             }

主要.cc

2. 神奇命令

$ clang-format -i main.cc

3. 良好格式化的代码
#include <iostream>
using namespace std;
int main() {
  cout << "Oh";
  cout << "clang format rulez!";
}

main.cc

4. 快乐

安装

如果你喜欢它,你可以使用以下方式进行安装:

$ sudo apt-get install clang-format

命令。


如果您已经安装了vim编辑器,请使用vim file.c命令打开文件,并输入=G来对整个文件进行缩进。然后使用:wq保存文件。
在默认安装中,会安装vi(而不是vim),因此它将没有所需的ident软件包(正如karel所提到的)。

打开终端并运行:
sudo apt-get install indent
indent -linux -l120 -i4 -nut unformatted-source-code.cpp

...其中unformatted-source-code.cpp是包含未格式化C++源代码的文件,例如您示例中的代码。

或者如果您无法安装它,可以使用apt-get download indent下载该软件包并提取它:dpkg-deb -x indent*.deb fs/,indent二进制文件位于fs/usr/bin/中,其中fs是您主目录中的任何目录。如果您将unformatted-source-code.cpp文件复制到相同位置fs/usr/bin/,然后在终端中缩进代码的命令如下:

cd path/to/fs/usr/bin/  # change directories to the location of "indent" executable
./indent -linux -l120 -i4 -nut unformatted-source-code.cpp

这些命令可以作为普通用户运行,不必以root身份运行。

2我没有任何根或sudo权限,因为这是公司的机器。 - user9993
5@user9993 你可以使用 apt-get download indent 命令下载该软件包,并解压缩它:dpkg-deb -x indent*.deb fs/,indent 可执行文件位于 fs/usr/bin/ 目录下。 - Lekensteyn

默认情况下,Ubuntu 应该已安装 nano。

您可以使用 nano -i 文件 启用自动缩进进行编辑。

这可能不会更改现有行的缩进,如果需要,您可能需要手动缩进。

参见:http://www.nano-editor.org/dist/v2.0/nano.html


astyleindent在脑海中浮现,但默认的Ubuntu安装中都没有包含它们。当然,如果你有一个C编译器,你可以编译它们并将它们安装在自己的路径中。

# Something like -
./configure --prefix=$HOME/tools
make
make install
PATH=$PATH:$HOME/tools/bin

emacs:

  • 打开C文件

  • 选择全部内容

  • 缩进(使用Tab键)

  • 保存文件

希望对你有所帮助