Skip to content

Instantly share code, notes, and snippets.

Created December 11, 2018 19:53
  • Star 10 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save BasPH/5e665273d5e4cb8a8eefb6f9d43b0b6d to your computer and use it in GitHub Desktop.
Black on selection
#!/usr/bin/env bash
set -x
# Read selected lines and write to tmpfile
selection=$(sed -n "$start_line, $end_line p; $(($end_line+1)) q" < $input_file)
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
Copy link

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.

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.

Copy link

Great script! thank you @BasPH

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

Copy link

GitHK commented Apr 16, 2020

thanks for the script. it's a lifesaver

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

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"

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