Black on selection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -x | |
black=$1 | |
input_file=$2 | |
start_line=$3 | |
end_line=$4 | |
# Read selected lines and write to tmpfile | |
selection=$(sed -n "$start_line, $end_line p; $(($end_line+1)) q" < $input_file) | |
tmpfile=$(mktemp) | |
echo "$selection" > "$tmpfile" | |
# Apply Black formatting to tmpfile | |
$black $tmpfile | |
# Delete original lines from file | |
sed -i "" "$start_line,$end_line d" $input_file | |
# And insert newly formatted lines | |
sed -i "" "$(($start_line-1)) r $tmpfile" $input_file |
Hello, I really appreciate for your cool and nice work!
I made a python version to utilize your 'partial black" in Windows OS and complied it to exe.
https://gist.github.com/imcomking/04d8ce30b6ac444e413392ab675b1d2c
thanks for the script. it's a lifesaver
Really cool, it's exactly what I was looking for.
I think it would be good to also add set -e
to the script so that if black fails, we don't risk overwriting anything
I think the deletion of the original lines deletes one extra line. It should delete until "$end_line - 1"
Any idea about this? @BasPH
error: cannot format /var/folders/bf/5_lvbmr539v26pk7qbrdrnd5drn_gd/T/tmp.8S3OqTW5: cannot use --safe with this file; failed to parse source file AST: unexpected indent (<unknown>, line 1)
This could be caused by running Black with an older Python version that does not support new syntax used in your source file.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are a saviour @BasPH ! I found your article on partial formatting with Black and it was very helpful! I guess I'll finally start using Pycharm after this.