mprobst / ClangFormatIJ

clang-format for IntelliJ based IDEs
Apache License 2.0
15 stars 9 forks source link

Feature Suggestion: use Intellij's default reformat action when file extension is not supported by Clang-format #12

Open wumo opened 5 years ago

wumo commented 5 years ago

This is a great tool to replace clion's integrated reformatting function. So I set a global hotkey for clang-format. But clang-format will also reformat python files even though it doesn't know how to reformat python code. So my suggestion is: Add file extension filters, and let clang-format only runs on supported file extensions and redirect non-supported file to Intellij's default reformat action.

RalphSteinhagen commented 4 years ago

This is a very useful plugin. The feature/bug may be caused by how the plugin calls internally clang-format.

Through re-routing through a custom script I found that the -assume-filename option is being used

 $CLANG_FORMAT -style=file -output-replacements-xml -assume-filename=<file name> -cursor=<cursor position>

which according to (this)[https://releases.llvm.org/10.0.0/tools/clang/docs/ClangFormatStyleOptions.html#configuring-style-with-clang-format] seems to force the formatter to be executed regardless if the language extension is supported:

[..] When formatting standard input or a file that doesn’t have the extension corresponding to its language, 
`-assume-filename=` option can be used to override the file name clang-format uses to detect the language. [..] 

The -i <file names> option does not have this issue.

@mprobst how may we entice you to either add a regular expression filtering on thee supported filenames prior to invoking clang-format and/or to use the -i option instead? I'd offer a :beer: and a free tour of our facility. Many thanks in advance.

RalphSteinhagen commented 4 years ago

For those who need a workaround for this issue:

The following script may be usefull (N.B. needs executable flags, in the user's $PATH and e.g. named clang-format or clang-format-custom with the setting in the IDE adjusted accordingly):

#/bin/bash
arg3=$3
arg4=$4
newarg3=${arg3#*=}
newarg4=${arg4#*=}
match=$(echo $newarg3 | grep -Ei "\.(cc|cpp|cxx|c\+\+|h|hh|hpp|hxx|h\+\+|java)")
if [ -n "$match" ]; then 
  /usr/bin/clang-format $1 $2 $4 -i $newarg3
else  
  echo "<?xml version='1.0'?>"
  echo "<replacements xml:space='preserve' incomplete_format='false'>"
  echo "<cursor>${newarg4}</cursor>"
  echo "</replacements>"
fi

Enjoy! :smile: