Is there a way to define keymap shortcuts for external tools depending on the file type, in PyCharm?

393 Views Asked by At

One use case would be to have the black code formatter for python files, and the sqlfluff code formatter for SQL files, and to use the same keyboard shortcut for both tools.

Currently, both are set up in Preferences -> Tools -> External Tools, following black documentation.

2

There are 2 best solutions below

1
On BEST ANSWER

Sadly no. You cannot assign one shortcut and invoke a different External Tool based on the file extension.

But you can workaround it pretty easily:

  • You will need to have a single External Tools entry instead of the current two.
  • Make a shell/batch script that will do the actual formatting (will call the actual formatter tool).
  • Use that script as an External Tools command.
  • In that custom script detect what extension the file has and execute the most appropriate formatter there (black for Python files and sqlfluff for SQL files).
0
On

Thanks to LazyOne advice, I wrote this small shell script to run either black or sqlfluff depending on the file extension:

#!/bin/sh

file_path="$1"
file_name=$(basename -- "$file_path")
extension="${file_name##*.}"

echo "Formatting file $file_path"
echo "With extension $extension"

if [ "$extension" = "py" ]; then
  /Users/alexandre/.local/bin/black "$file_path"
elif [ "$extension" = "sql" ]; then
  /Users/alexandre/.local/bin/sqlfluff fix -f --dialect postgres "$file_path"
else
  exit 2
fi

Make sure to change the paths to your actual installation paths (outputs of which black and which sqlfluff).

You can save the script in a file (e.g. code_formatter.sh), and make it executable:

chmod +x code_formatter.sh

Then configure it as an external tool in Pycharm settings, and don't forget the "$FilePath$" argument:

enter image description here

You can now define a single keyboard shortcut for the "my code formatter" external tool, that should work on both sql and python files.