|
7 | 7 | import toml
|
8 | 8 | from pylsp import hookimpl
|
9 | 9 |
|
| 10 | +from pylsp_black._utils import get_eol_chars |
| 11 | + |
10 | 12 | logger = logging.getLogger(__name__)
|
11 | 13 |
|
| 14 | + |
12 | 15 | GLOBAL_CONFIG: Optional[Path] = None
|
13 | 16 | try:
|
14 | 17 | if os.name == "nt":
|
@@ -68,8 +71,25 @@ def format_text(*, text, config):
|
68 | 71 | string_normalization=not config["skip_string_normalization"],
|
69 | 72 | )
|
70 | 73 | try:
|
71 |
| - # will raise black.NothingChanged, we want to bubble that exception up |
72 |
| - return black.format_file_contents(text, fast=config["fast"], mode=mode) |
| 74 | + # Black's format_file_contents only works reliably when eols are '\n'. It gives |
| 75 | + # an error for '\r' and produces wrong formatting for '\r\n'. So we replace |
| 76 | + # those eols by '\n' before formatting and restore them afterwards. |
| 77 | + replace_eols = False |
| 78 | + eol_chars = get_eol_chars(text) |
| 79 | + if eol_chars is not None and eol_chars != "\n": |
| 80 | + replace_eols = True |
| 81 | + text = text.replace(eol_chars, "\n") |
| 82 | + |
| 83 | + # Will raise black.NothingChanged, we want to bubble that exception up |
| 84 | + formatted_text = black.format_file_contents( |
| 85 | + text, fast=config["fast"], mode=mode |
| 86 | + ) |
| 87 | + |
| 88 | + # Restore eols if necessary. |
| 89 | + if replace_eols: |
| 90 | + formatted_text = formatted_text.replace("\n", eol_chars) |
| 91 | + |
| 92 | + return formatted_text |
73 | 93 | except (
|
74 | 94 | # raised when the file has syntax errors
|
75 | 95 | ValueError,
|
|
0 commit comments