Skip to content

Instantly share code, notes, and snippets.

@BasPH
Created December 11, 2018 19:53
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save BasPH/5e665273d5e4cb8a8eefb6f9d43b0b6d to your computer and use it in GitHub Desktop.
Save BasPH/5e665273d5e4cb8a8eefb6f9d43b0b6d to your computer and use it in GitHub Desktop.
Black on selection
#!/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
@imcomking
Copy link

imcomking commented Feb 4, 2020

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

@mrezzamoradi
Copy link

Great script! thank you @BasPH

By the way < $input_file part in line 11 is missing in the script in your post.

@GitHK
Copy link

GitHK commented Apr 16, 2020

thanks for the script. it's a lifesaver

@josebama
Copy link

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

@levsa
Copy link

levsa commented May 7, 2020

I think the deletion of the original lines deletes one extra line. It should delete until "$end_line - 1"

@nauman-chaudhary
Copy link

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