@@ -64,29 +64,33 @@ 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+ lines = [(range ["start" ]["line" ] + 1 , range ["end" ]["line" ])] if range else ()
70+
71+ try :
72+ formatted_text = format_text (text = text , config = config , lines = lines )
73+ except black .NothingChanged :
74+ # raised when the file is already formatted correctly
75+ return []
76+
6777 if range :
78+ formatted_lines = formatted_text .splitlines (True )
79+
6880 start = range ["start" ]["line" ]
69- end = range ["end" ]["line" ]
70- text = "" .join (document .lines [start :end ])
81+ end = range ["end" ]["line" ] + (len (formatted_lines ) - len (document .lines ))
82+
83+ formatted_text = "" .join (formatted_lines [start :end ])
7184 else :
72- text = document .source
7385 range = {
7486 "start" : {"line" : 0 , "character" : 0 },
7587 "end" : {"line" : len (document .lines ), "character" : 0 },
7688 }
7789
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-
8690 return [{"range" : range , "newText" : formatted_text }]
8791
8892
89- def format_text (* , text , config ):
93+ def format_text (* , text , config , lines ):
9094 mode = black .FileMode (
9195 target_versions = config ["target_version" ],
9296 line_length = config ["line_length" ],
@@ -107,7 +111,7 @@ def format_text(*, text, config):
107111
108112 # Will raise black.NothingChanged, we want to bubble that exception up
109113 formatted_text = black .format_file_contents (
110- text , fast = config ["fast" ], mode = mode
114+ text , fast = config ["fast" ], mode = mode , lines = lines
111115 )
112116
113117 # Restore eols if necessary.
0 commit comments