@@ -64,29 +64,34 @@ def pylsp_settings():
6464
6565
6666def format_document (client_config , document , range = None ):
67+ text = document .source
68+ config = load_config (document .path , client_config )
69+ # Black lines indices are "1-based and inclusive on both ends"
70+ lines = [(range ["start" ]["line" ] + 1 , range ["end" ]["line" ])] if range else ()
71+
72+ try :
73+ formatted_text = format_text (text = text , config = config , lines = lines )
74+ except black .NothingChanged :
75+ # raised when the file is already formatted correctly
76+ return []
77+
6778 if range :
79+ formatted_lines = formatted_text .splitlines (True )
80+
6881 start = range ["start" ]["line" ]
69- end = range ["end" ]["line" ]
70- text = "" .join (document .lines [start :end ])
82+ end = range ["end" ]["line" ] + (len (formatted_lines ) - len (document .lines ))
83+
84+ formatted_text = "" .join (formatted_lines [start :end ])
7185 else :
72- text = document .source
7386 range = {
7487 "start" : {"line" : 0 , "character" : 0 },
7588 "end" : {"line" : len (document .lines ), "character" : 0 },
7689 }
7790
78- config = load_config (document .path , client_config )
79-
80- try :
81- formatted_text = format_text (text = text , config = config )
82- except black .NothingChanged :
83- # raised when the file is already formatted correctly
84- return []
85-
8691 return [{"range" : range , "newText" : formatted_text }]
8792
8893
89- def format_text (* , text , config ):
94+ def format_text (* , text , config , lines ):
9095 mode = black .FileMode (
9196 target_versions = config ["target_version" ],
9297 line_length = config ["line_length" ],
@@ -107,7 +112,7 @@ def format_text(*, text, config):
107112
108113 # Will raise black.NothingChanged, we want to bubble that exception up
109114 formatted_text = black .format_file_contents (
110- text , fast = config ["fast" ], mode = mode
115+ text , fast = config ["fast" ], mode = mode , lines = lines
111116 )
112117
113118 # Restore eols if necessary.
0 commit comments