From 029fe05a5f1e0fefcd6b51f13bc5b44494b9c8d4 Mon Sep 17 00:00:00 2001 From: Micha Reiser Date: Thu, 20 Jul 2023 11:25:27 +0200 Subject: [PATCH] Playground: Fix escaped quotes handling (#5906) Co-authored-by: konsti --- .../src/format_element/document.rs | 42 ++++++++++++++++++- playground/src/Editor/setupMonaco.tsx | 3 ++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/crates/ruff_formatter/src/format_element/document.rs b/crates/ruff_formatter/src/format_element/document.rs index 7eb1c37156..e4dbdb8d4d 100644 --- a/crates/ruff_formatter/src/format_element/document.rs +++ b/crates/ruff_formatter/src/format_element/document.rs @@ -255,11 +255,35 @@ impl Format> for &[FormatElement] { in_text = true; + fn write_escaped( + element: &FormatElement, + f: &mut Formatter, + ) -> FormatResult<()> { + let text = match element { + FormatElement::StaticText { text } => text, + FormatElement::DynamicText { text } => text.as_ref(), + FormatElement::SourceCodeSlice { slice, .. } => { + slice.text(f.context().source_code()) + } + _ => unreachable!(), + }; + + if text.contains('"') { + f.write_element(FormatElement::DynamicText { + text: text.replace('"', r#"\""#).into(), + }) + } else { + f.write_element(element.clone()) + } + } + match element { FormatElement::Space => { write!(f, [text(" ")])?; } - element if element.is_text() => f.write_element(element.clone())?, + element if element.is_text() => { + write_escaped(element, f)?; + } _ => unreachable!(), } @@ -787,6 +811,22 @@ mod tests { ); } + #[test] + fn escapes_quotes() { + let formatted = format!( + SimpleFormatContext::default(), + [text(r#""""Python docstring""""#)] + ) + .unwrap(); + + let document = formatted.into_document(); + + assert_eq!( + &std::format!("{}", document.display(SourceCode::default())), + r#"["\"\"\"Python docstring\"\"\""]"# + ); + } + #[test] fn display_elements_with_source_text_slice() { let source_code = "Some longer content\nThat should ultimately break"; diff --git a/playground/src/Editor/setupMonaco.tsx b/playground/src/Editor/setupMonaco.tsx index 3d43b55b00..5585319c75 100644 --- a/playground/src/Editor/setupMonaco.tsx +++ b/playground/src/Editor/setupMonaco.tsx @@ -596,6 +596,7 @@ function defineRustPythonAstLanguage(monaco: Monaco) { ], string: [ [/[^\\"]+/, "string"], + [/\\[\\"]/, "string.escape"], [/"/, { token: "string.quote", bracket: "@close", next: "@pop" }], ], }, @@ -650,6 +651,7 @@ function defineRustPythonTokensLanguage(monaco: Monaco) { ], string: [ [/[^\\"]+/, "string"], + [/\\[\\"]/, "string.escape"], [/"/, { token: "string.quote", bracket: "@close", next: "@pop" }], ], }, @@ -695,6 +697,7 @@ function defineFirLanguage(monaco: Monaco) { ], string: [ [/[^\\"]+/, "string"], + [/\\[\\"]/, "string.escape"], [/"/, { token: "string.quote", bracket: "@close", next: "@pop" }], ], },