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