@@ -64,29 +64,33 @@ def pylsp_settings():
64
64
65
65
66
66
def 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
+
67
77
if range :
78
+ formatted_lines = formatted_text .splitlines (True )
79
+
68
80
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 ])
71
84
else :
72
- text = document .source
73
85
range = {
74
86
"start" : {"line" : 0 , "character" : 0 },
75
87
"end" : {"line" : len (document .lines ), "character" : 0 },
76
88
}
77
89
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
-
86
90
return [{"range" : range , "newText" : formatted_text }]
87
91
88
92
89
- def format_text (* , text , config ):
93
+ def format_text (* , text , config , lines ):
90
94
mode = black .FileMode (
91
95
target_versions = config ["target_version" ],
92
96
line_length = config ["line_length" ],
@@ -107,7 +111,7 @@ def format_text(*, text, config):
107
111
108
112
# Will raise black.NothingChanged, we want to bubble that exception up
109
113
formatted_text = black .format_file_contents (
110
- text , fast = config ["fast" ], mode = mode
114
+ text , fast = config ["fast" ], mode = mode , lines = lines
111
115
)
112
116
113
117
# Restore eols if necessary.
0 commit comments