有没有办法在Java中强制使用制表符而不是空格?

发布于 2024-11-01 09:38:38 字数 350 浏览 1 评论 0原文

CheckStyle 提供检查空格使用的一致性,但遗憾的是缺乏相反的想法:强制源代码使用制表符。有什么方法可以添加这个功能吗?它不一定是 CheckStyle,其他工具也可以。

这个问题相同,但对于爪哇。

编辑

我不需要代码美化器,因为代码库的正常状态将是所有选项卡。我只需要一个可以报告替代缩进的存在的工具。这样我就可以设置一个新的连续构建配置,当引入空格时该配置将失败。

CheckStyle offers to check for consistent use of spaces, but sadly lacks the opposite idea: Force source code to use tabs. Is there some way to add this functionality? It does not have to be CheckStyle, other tools are welcome as well.

Same as this question but for Java.

EDIT

I don't need a code beautifier, since the normal state of the codebase will be all tabs. I just need a tool which can report the presence of alternate indentation. That way I can set up a new continuous build configuration which will fail when spaces are introduced.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

绅士风度i 2024-11-08 09:38:38

尽管 Checkstyle 没有对此进行内置检查,但您可以使用 RegexpSinglelineJava 检查强制执行仅制表符缩进。请注意,这仅检查哪个字符用于缩进,而不是检查正确的缩进级别

无耻地从 Hibernate OGM 源代码窃取:

<module name="RegexpSinglelineJava">
    <property name="format" value="^\t* +\t*\S"/>
    <property name="message" value="Line has leading space characters; indentation should be performed with tabs only."/>
    <property name="ignoreComments" value="true"/>
</module>

Although Checkstyle has no builtin check for this, you can enforce tabs-only indentation using the RegexpSinglelineJava check. Note that this only checks which character is used for indentation, not for the correct level of indentation.

Shamelessly stolen from the Hibernate OGM source:

<module name="RegexpSinglelineJava">
    <property name="format" value="^\t* +\t*\S"/>
    <property name="message" value="Line has leading space characters; indentation should be performed with tabs only."/>
    <property name="ignoreComments" value="true"/>
</module>
往日情怀 2024-11-08 09:38:38

首选使用空格而不是制表符进行缩进,因为它可以在所有编辑器/查看器之间提供布局的一致性。
但如果您仍然需要它,您始终可以对 checkstyle 进行自定义检查或自定义 Maven 插件 /ant 任务。
逻辑应该也不难实现 - 您只需检查任何行上的前导空格是否大于制表符长度。

编辑:包括一个蚂蚁的例子。
自从你发帖以来已经两周了,你仍然不高兴,而我有一些空闲时间:)
所以我为你准备了一个蚂蚁自定义任务解决方案。

Ant 任务

public class SpaceDetectorTask extends Task {
    public static final String REGEX = "^[ ]+";
    public static final Pattern p = Pattern.compile(REGEX);

    private FileSet fileSet;
    private boolean failOnDetection;

    // Usual getters/setters

    public void addFileSet(FileSet fileSet) {
        this.fileSet = fileSet;
    }

    public void execute() {
        DirectoryScanner ds = fileSet.getDirectoryScanner();
        String[] files = ds.getIncludedFiles();
        for (int x = 0; x <= files.length -1; x++) {
            process(ds.getBasedir(), files[x]);
        }
    }

    public void process(File dir, String file) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(dir, file)));
            String line;
            int linecount = 0;
            System.out.println("File: " + file);
            boolean ignore = false;
            while((line = reader.readLine()) != null) {
                linecount++;

                // exclude comment blocks
                if (line.contains("/**") || line.contains("*/")) {
                    ignore = !ignore;
                    continue;
                }

                if (!ignore) {
                    if (p.matcher(line).find()) {
                        int spcCount = line.length() - (line.replaceAll(REGEX, "")).length();
                        if (spcCount >= 4) { // break whenever 4 leading spaces are detected. Configure as you need.
                            String msg = "File: "+ file + " is using spaces as indentation.";
                            if (failOnDetection) {
                                throw new BuildException(msg);
                            } else {
                                getProject().log(msg);
                            }
                        }
                    }
                    reader.close();
                }
            }
        } catch (IOException e) {
            if (failOnDetection) {
                throw new BuildException(e);
            } else {
                getProject().log("File: " + file + "\n" + e.getMessage());
            }
        }
    }

在 ant build.xml

  1. 首先编译任务
  2. 声明它

    
            <类路径>
                
                <文件集目录=“C:/apache-ant-1.7.1/lib”>
                    >
                
            
    
    
  3. 使用它

    <目标名称=“rules.spaces”>
        <检测空间
            failOnDetection="true">
            <文件集目录=“${dir.src.java}”>
                ;
            
        
    
    

编写一个 maven/checkstyle 插件也不应该很困难。

Using spaces instead of tabs to indent is preferred because it offers consistency of layout across all editors/viewers.
But if you still want it, you can always make your own custom check for checkstyle or a custom maven plugin /ant task.
Logic shouldnt be difficult to implement either - all you have to check whether leading space on any line is greater than the tab length.

Edit: including an ant example.
Its two weeks now since you posted and you're still not happy, and I had some free time :)
So I cooked up a little ant custom task solution for you.

The Ant task

public class SpaceDetectorTask extends Task {
    public static final String REGEX = "^[ ]+";
    public static final Pattern p = Pattern.compile(REGEX);

    private FileSet fileSet;
    private boolean failOnDetection;

    // Usual getters/setters

    public void addFileSet(FileSet fileSet) {
        this.fileSet = fileSet;
    }

    public void execute() {
        DirectoryScanner ds = fileSet.getDirectoryScanner();
        String[] files = ds.getIncludedFiles();
        for (int x = 0; x <= files.length -1; x++) {
            process(ds.getBasedir(), files[x]);
        }
    }

    public void process(File dir, String file) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(new File(dir, file)));
            String line;
            int linecount = 0;
            System.out.println("File: " + file);
            boolean ignore = false;
            while((line = reader.readLine()) != null) {
                linecount++;

                // exclude comment blocks
                if (line.contains("/**") || line.contains("*/")) {
                    ignore = !ignore;
                    continue;
                }

                if (!ignore) {
                    if (p.matcher(line).find()) {
                        int spcCount = line.length() - (line.replaceAll(REGEX, "")).length();
                        if (spcCount >= 4) { // break whenever 4 leading spaces are detected. Configure as you need.
                            String msg = "File: "+ file + " is using spaces as indentation.";
                            if (failOnDetection) {
                                throw new BuildException(msg);
                            } else {
                                getProject().log(msg);
                            }
                        }
                    }
                    reader.close();
                }
            }
        } catch (IOException e) {
            if (failOnDetection) {
                throw new BuildException(e);
            } else {
                getProject().log("File: " + file + "\n" + e.getMessage());
            }
        }
    }

In ant build.xml

  1. Compile the task first
  2. Declare it

    <taskdef name="detect-spaces"
             classname="com.blah.blah.build.tools.SpaceDetectorTask">
            <classpath>
                <pathelement path="${dir.classes}"/>
                <fileset dir="C:/apache-ant-1.7.1/lib">
                    <include name="**/*.jar"/>
                </fileset>
            </classpath>
    </taskdef>
    
  3. use it

    <target name="rules.spaces">
        <detect-spaces
            failOnDetection="true">
            <fileset dir="${dir.src.java}">
                <include name="**/*.java"/>
            </fileset>
        </detect-spaces>
    </target>
    

Writing up a maven/checkstyle plugin shoulnt be difficult either.

活雷疯 2024-11-08 09:38:38

这种方法比其他提出的方法简单得多。

在 Miscellaneous 组下创建 Regexp 测试,并设置

Format : ^[ \t]*
消息:缩进必须是制表符
非法模式:(选中)

This way is a lot simpler than other proposed methods.

Create a Regexp test under Miscellaneous group, and set

Format : ^[ \t]*
Message : Indentations must be tabs
Illegal Pattern : (checked)

黑色毁心梦 2024-11-08 09:38:38

使用以下命令搜索前导空格:

grep -e "^\t* " `find . -name *.java`

然后翻转退出状态。

Search for a leading space using this command:

grep -e "^\t* " `find . -name *.java`

Then flip the exit status.

老街孤人 2024-11-08 09:38:38

Jalopy 可能就是您所寻找的。它已经有一段时间没有更新了,但应该仍然可以工作。 Triemax 还提供商业版本。

Jalopy might be what your looking for. It hasn't been updated for a while but it should still work. There is also a commercial version available from Triemax.

稚气少女 2024-11-08 09:38:38

我们的 Java Formatter 将直接执行此操作。 JavaFormatter 漂亮打印源文本(对于漂亮打印的某些定义:-),并在逻辑上缩进每个嵌套块固定数量的空格(例如, indent=3 [作为默认值])。

可以强制 Java 格式化程序在左边距使用 TAB 字符作为空白,并且它将使用 TAB 跳到与用户指定的制表位列号供应相对应的下一列。如果将制表位定义为与缩进距离具有相同的间隔,则只需格式化代码即可为每个缩进获得一个制表符。如果您定义 indent=8,每 8 列(1,9,17,...)使用制表符停止位,您往往会获得可与许多编辑器一起使用的制表符,因为制表符的默认解释是“每 8 列”。

Our Java Formatter will do this directly. The JavaFormatter prettyprints source text (for some definition of prettyprint :-) and indents blocks logically a fixed number of spaces per nested block (e.g., indent=3 [as a default]).

It is possible to force the Java Formatter to use TAB characters at the left margin for white space, and it will use a TAB to skip to the the next column that corresponds to a user-specificed supply of tab stop column numbers. If you define tab stops to have the same separation as the indent distance, you will get one tab character per indent, just by formatting the code. If you define indent=8, with tab stops every 8 columns (1,9,17,...) you tend to get tabs that work with many editors, as the default interpretation of tabs is "every 8 columns".

如梦初醒的夏天 2024-11-08 09:38:38

在 IntelliJ 中,我让它在签入时将代码格式化为标准格式。这样您输入时可以有空格/制表符,但代码会定期更改为标准格式,并且在版本控制中始终正确(其中必须共享)

在没有 IntelliJ 的情况下,您一定可以做类似的事情,例如预签入脚本。

在 80 年代使用制表符代替空格是个好主意,但你真的认为这在 10 年代重要吗?这肯定与磁盘空间无关!

In IntelliJ, I have it perform a code formatting to the standard format on check in. That way you can have spaces/tabs as you enter, but the code is changed to the standard format periodically and is always correct in version control (where it must be shared)

There must be something similar you can do without IntelliJ like a pre-check in script.

Using tabs instead of spaces was a good idea in the 80's but do you really think it matters in the 10's? This can't be about disk space surely!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文