diff --git a/crates/ide-core/src/editor_settings.rs b/crates/ide-core/src/editor_settings.rs index 17eb49e97..d926ab520 100644 --- a/crates/ide-core/src/editor_settings.rs +++ b/crates/ide-core/src/editor_settings.rs @@ -446,6 +446,12 @@ pub struct LanguageCodeStyle { /// Comment Code › Add a space at line comment start. #[serde(skip_serializing_if = "Option::is_none")] pub line_comment_add_space: Option, + /// PHP: align `=>` in multi-line arrays after formatting (other languages ignore it). + #[serde(skip_serializing_if = "Option::is_none")] + pub align_key_value_pairs: Option, + /// PHP: align `=` of consecutive assignment statements after formatting. + #[serde(skip_serializing_if = "Option::is_none")] + pub align_consecutive_assignments: Option, } /// Editor › Code Style (General tab + per-language overrides). diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index ad3416ac5..ca4fd05b6 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -2,9 +2,9 @@ use crate::Host; use ide_core::event::NotifyLevel; -use ide_core::settings::{ExternalFormatter, LanguagesSettings}; -use ide_core::{DocId, IdeError, IdeEvent, IdeResult, Pos, Range, TextEdit}; -use ide_language::LanguageConfig; +use ide_core::settings::{ExternalFormatter, LanguagesSettings, Settings}; +use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, Pos, Range, TextEdit}; +use ide_language::{LanguageConfig, PhpAlignment, Syntax}; use ide_lsp::types::FormatOptions; use ide_tools::{Tools, formatter}; use std::path::Path; @@ -129,12 +129,101 @@ pub async fn format( let project = host.project(window)?; let snap = project.documents.snapshot(doc)?; let settings = project.settings.effective(); + let alignment = php_alignment(&settings, &snap.language); + let original = alignment.any().then(|| (snap.language.clone(), snap.text.clone())); + let Some(edits) = provider_edits(host, window, &project, snap, settings, range, options).await? else { + return Ok(Vec::new()); + }; + let Some((language, text)) = original else { + return Ok(edits); + }; + let syntax = host.syntax(); + tokio::task::spawn_blocking(move || align_formatted(&syntax, &language, &text, edits, range, alignment)) + .await + .map_err(|e| IdeError::internal(e.to_string()))? +} + +/// PHP Code Style › Align key-value pairs / Align consecutive assignments (off by default, as in PhpStorm). +fn php_alignment(settings: &Settings, language: &LanguageId) -> PhpAlignment { + let style = settings.editor.code_style.languages.get(language.as_str()); + PhpAlignment { + key_value_pairs: style.and_then(|s| s.align_key_value_pairs).unwrap_or(false), + assignments: style.and_then(|s| s.align_consecutive_assignments).unwrap_or(false), + } +} + +/// The formatter's `edits` to `text` followed by the alignment, as one set of edits to `text`. +/// With a `range`, only its lines (where the formatter left them) are aligned. +fn align_formatted( + syntax: &Syntax, + language: &LanguageId, + text: &str, + edits: Vec, + range: Option, + alignment: PhpAlignment, +) -> IdeResult> { + let mut formatted = ide_text::Document::new(text); + // Edits the editor has to sort out itself (overlapping ones) are passed on unaligned. + let Ok((changes, _)) = formatted.apply_edits(&edits) else { + return Ok(edits); + }; + let lines = range.map(|range| { + let original = ide_text::Document::new(text); + let start = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.start), false)); + let end = formatted.offset_to_pos(map_offset(&changes, original.pos_to_offset(range.end), true)); + let last = if end.col == 0 && end.line > start.line { end.line - 1 } else { end.line }; + (start.line as usize, last as usize) + }); + let Some(aligned) = syntax.align_php(language, &formatted.text(), lines, alignment) else { + return Ok(edits); + }; + let original = ide_text::Document::new(text); + Ok(original + .diff(&aligned) + .changes + .into_iter() + .map(|c| TextEdit { + range: Range::new(original.offset_to_pos(c.from), original.offset_to_pos(c.to)), + new_text: c.insert, + }) + .collect()) +} + +/// Where UTF-16 `offset` of the text before `changes` ends up after them; inside a replaced +/// part, at its start or (`end`) its end. +fn map_offset(changes: &ChangeSet, offset: u32, end: bool) -> u32 { + let mut shift: i64 = 0; + for c in &changes.changes { + let inserted = c.insert.encode_utf16().count() as i64; + if c.to < offset || (c.to == offset && (c.from < c.to || end)) { + shift += inserted - i64::from(c.to - c.from); + } else if c.from < offset { + return (i64::from(c.from) + shift + if end { inserted } else { 0 }) as u32; + } else { + break; + } + } + (i64::from(offset) + shift) as u32 +} + +/// The edits of the formatter that handles the document; `None` when it doesn't run +/// (formatting on save is off for it). +async fn provider_edits( + host: &Host, + window: &str, + project: &crate::Project, + snap: ide_workspace::documents::DocumentInfo, + settings: Settings, + range: Option, + options: FormatOptions, +) -> IdeResult>> { + let doc = snap.id; let language = project.languages.get(&snap.language); if options.tool.is_none() && let Some(id) = settings.languages.plugin_formatters.get(snap.language.as_str()).filter(|s| !s.is_empty()) { if options.on_save && !settings.editor.format_on_save { - return Ok(Vec::new()); + return Ok(None); } if snap.read_only { return Err(IdeError::invalid("The file is read-only")); @@ -160,7 +249,8 @@ pub async fn format( ) }) .await - .map_err(|e| IdeError::internal(e.to_string()))?; + .map_err(|e| IdeError::internal(e.to_string()))? + .map(Some); } // A committed PHP-CS-Fixer configuration takes over Reformat Code for `.php` files. if options.tool.is_none() @@ -168,7 +258,7 @@ pub async fn format( && let Some(fixer) = formatter::php_cs_fixer(&snap.path) { if options.on_save && !settings.editor.format_on_save { - return Ok(Vec::new()); + return Ok(None); } host.require_trust(window)?; if snap.read_only { @@ -188,7 +278,7 @@ pub async fn format( body: Some("PHP-CS-Fixer does not support selection formatting; formatted the whole file".into()), }); } - return Ok(edits); + return Ok(Some(edits)); } let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?; if let Some(tool) = selected @@ -200,13 +290,13 @@ pub async fn format( } let Some(selected) = selected else { if options.on_save && !settings.editor.format_on_save { - return Ok(Vec::new()); + return Ok(None); } - return project.lsp.format(doc, range, options).await; + return project.lsp.format(doc, range, options).await.map(Some); }; let tool_settings = settings.languages.formatter(selected); if options.on_save && !tool_settings.run_on_save { - return Ok(Vec::new()); + return Ok(None); } host.require_trust(window)?; if snap.read_only { @@ -262,7 +352,7 @@ pub async fn format( )), }); } - edits.map_err(|e| e.with_tool(tool)) + edits.map(Some).map_err(|e| e.with_tool(tool)) } #[cfg(test)] @@ -413,6 +503,103 @@ mod tests { ); } + fn after(text: &str, edits: &[TextEdit]) -> String { + let mut doc = ide_text::Document::new(text); + doc.apply_edits(edits).unwrap(); + doc.text() + } + + fn whole_file(text: &str, formatted: &str) -> Vec { + let doc = ide_text::Document::new(text); + doc.diff(formatted) + .changes + .into_iter() + .map(|c| TextEdit { + range: Range::new(doc.offset_to_pos(c.from), doc.offset_to_pos(c.to)), + new_text: c.insert, + }) + .collect() + } + + const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true }; + + #[test] + fn php_alignment_is_off_unless_the_php_code_style_turns_it_on() { + let php = LanguageId::new("php"); + let mut settings = Settings::default(); + assert_eq!(php_alignment(&settings, &php), PhpAlignment::default()); + let style = + ide_core::editor_settings::LanguageCodeStyle { align_key_value_pairs: Some(true), ..Default::default() }; + settings.editor.code_style.languages.insert("php".into(), style); + assert_eq!(php_alignment(&settings, &php), PhpAlignment { key_value_pairs: true, assignments: false }); + assert_eq!(php_alignment(&settings, &LanguageId::new("javascript")), PhpAlignment::default()); + } + + #[test] + fn alignment_follows_the_formatter_edits_even_when_there_are_none() { + let syntax = Syntax::new(); + let php = LanguageId::new("php"); + let text = " 1,\n 'bbb' => 2,\n];\n"; + let edits = align_formatted(&syntax, &php, text, Vec::new(), None, ALIGN).unwrap(); + assert_eq!(after(text, &edits), " 1,\n 'bbb' => 2,\n];\n"); + + // The language server re-indents the array: the alignment applies to its result. + let text = " 1,\n'bbb' => 2,\n];\n"; + let formatted = " 1,\n 'bbb' => 2,\n];\n"; + let edits = align_formatted(&syntax, &php, text, whole_file(text, formatted), None, ALIGN).unwrap(); + assert_eq!(after(text, &edits), " 1,\n 'bbb' => 2,\n];\n"); + + let unchanged = whole_file(text, formatted); + let off = align_formatted(&syntax, &php, text, unchanged.clone(), None, PhpAlignment::default()).unwrap(); + assert_eq!(off, unchanged); + + let overlapping = vec![ + TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 4)), new_text: "x".into() }, + TextEdit { range: Range::new(Pos::new(1, 2), Pos::new(1, 6)), new_text: "y".into() }, + ]; + let passed = align_formatted(&syntax, &php, text, overlapping.clone(), None, ALIGN).unwrap(); + assert_eq!(passed, overlapping); + } + + #[test] + fn a_selection_aligns_only_its_lines_whatever_the_formatter_changed() { + let syntax = Syntax::new(); + let php = LanguageId::new("php"); + let text = " 1,\n 'bbb' => 2,\n];\n"; + // PHP-CS-Fixer formats the whole file (here: adds a line at the top) whatever the selection. + let formatted = format!(" 1,\n 'bbb' => 2,\n];\n" + ); + let range = Range::new(Pos::new(1, 0), Pos::new(2, 9)); + let aligned = align_formatted(&syntax, &php, text, Vec::new(), Some(range), ALIGN).unwrap(); + assert_eq!(after(text, &aligned), " 1,\n 'bbb' => 2,\n];\n"); + } + + #[test] + fn offsets_map_through_changes() { + let changes = ChangeSet { + changes: vec![ + ide_core::TextChange { from: 2, to: 2, insert: "ab".into() }, + ide_core::TextChange { from: 5, to: 8, insert: "x".into() }, + ], + }; + assert_eq!(map_offset(&changes, 0, false), 0); + assert_eq!(map_offset(&changes, 2, false), 2); + assert_eq!(map_offset(&changes, 2, true), 4); + assert_eq!(map_offset(&changes, 4, false), 6); + assert_eq!(map_offset(&changes, 6, false), 7); + assert_eq!(map_offset(&changes, 6, true), 8); + assert_eq!(map_offset(&changes, 8, false), 8); + assert_eq!(map_offset(&changes, 10, false), 10); + } + #[test] fn ruff_ranges_are_one_based_unicode_columns() { let text = ide_text::Document::new("😀x = 1\ny = 2\n"); diff --git a/crates/ide-language/src/lib.rs b/crates/ide-language/src/lib.rs index 093e2f660..b203040f1 100644 --- a/crates/ide-language/src/lib.rs +++ b/crates/ide-language/src/lib.rs @@ -28,7 +28,7 @@ pub use syntax::{ VueComponentImport, VueRefAccess, VueRefElement, WebReference, WebReferenceKind, merge_visibility, set_external_syntax, shift_pos, shift_range, }; -pub use syntax::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts}; +pub use syntax::{MethodBody, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts}; /// Parsed form of `languages/.toml`. Backend-only; the UI gets [`LanguageInfo`]. #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/crates/ide-language/src/syntax/mod.rs b/crates/ide-language/src/syntax/mod.rs index 8734d62f1..9ff2cf058 100644 --- a/crates/ide-language/src/syntax/mod.rs +++ b/crates/ide-language/src/syntax/mod.rs @@ -10,6 +10,7 @@ mod inheritance; pub(crate) mod lines; mod literals; mod outline; +mod php_align; mod python_facts; mod rst; mod selection; @@ -28,6 +29,7 @@ pub use inheritance::ClassBases; pub use lines::{shift_pos, shift_range}; pub use literals::{Literal, LiteralKind, SpellingKind, SpellingRegion}; pub use outline::merge_visibility; +pub use php_align::PhpAlignment; pub use python_facts::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts}; use std::cell::RefCell; use std::collections::HashMap; diff --git a/crates/ide-language/src/syntax/php_align.rs b/crates/ide-language/src/syntax/php_align.rs new file mode 100644 index 000000000..6e2afc76b --- /dev/null +++ b/crates/ide-language/src/syntax/php_align.rs @@ -0,0 +1,368 @@ +//! PHP Code Style › Align key-value pairs and Align consecutive assignments (PhpStorm's +//! options of the same names), applied to text a formatter has already formatted. +//! +//! A block is a run of array elements, or of assignment statements, on consecutive lines of +//! the same array or statement list, one per line and each on a single line. A blank line, +//! a comment line, another statement or element, or one spanning several lines ends it. +//! Within a block the operators line up one space after the longest left-hand side; nested +//! arrays form blocks of their own. Only the whitespace before an operator token of the +//! syntax tree changes, so `=>` and `=` inside strings and comments are never touched. + +use crate::{LanguageId, Syntax}; +use tree_sitter::{Node, Tree}; + +/// Which alignments to apply. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct PhpAlignment { + /// `=>` of the elements of multi-line arrays. + pub key_value_pairs: bool, + /// `=` of consecutive assignment statements. + pub assignments: bool, +} + +impl PhpAlignment { + pub fn any(self) -> bool { + self.key_value_pairs || self.assignments + } +} + +impl Syntax { + /// `text` with its PHP alignment applied, changing only lines `lines` (0-based, inclusive; + /// `None`: all). A block reaching outside them still aligns with its lines there. + /// `None` when nothing changes or `lang` is not parsed with the PHP grammar. + pub fn align_php( + &self, + lang: &LanguageId, + text: &str, + lines: Option<(usize, usize)>, + options: PhpAlignment, + ) -> Option { + if !options.any() { + return None; + } + self.analyze(lang, text, |g, tree, text| (g.spec.name == "php").then(|| align(tree, text, lines, options))) + .flatten() + } +} + +/// One line's operator: the whitespace `gap` before it and the width of the line up to it. +#[derive(Clone, Copy, Debug)] +struct Entry { + line: usize, + gap: (usize, usize), + /// Characters from the start of the line to the end of the left-hand side. + width: usize, +} + +fn align(tree: &Tree, text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> Option { + let mut gaps: Vec<(usize, usize, usize)> = Vec::new(); + let mut cursor = tree.walk(); + visit(&mut cursor, &mut |node| { + // Error recovery can read string content as code, where whitespace matters. + if node.is_error() { + return; + } + let entries = match node.kind() { + "array_creation_expression" if options.key_value_pairs => run(node, text, key_value), + _ if options.assignments => run(node, text, assignment), + _ => return, + }; + for block in blocks(&entries) { + let column = block.iter().map(|e| e.width).max().unwrap_or(0) + 1; + for e in block { + if lines.is_none_or(|(first, last)| (first..=last).contains(&e.line)) { + gaps.push((e.gap.0, e.gap.1, column - e.width)); + } + } + } + }); + gaps.sort_unstable(); + let mut out = String::with_capacity(text.len()); + let mut at = 0; + let mut changed = false; + for (from, to, spaces) in gaps { + if text[from..to].len() == spaces && text[from..to].bytes().all(|b| b == b' ') { + continue; + } + out.push_str(&text[at..from]); + out.extend(std::iter::repeat_n(' ', spaces)); + at = to; + changed = true; + } + if !changed { + return None; + } + out.push_str(&text[at..]); + Some(out) +} + +/// The named children of `parent` as alignment candidates in order: `None` breaks a block. +/// A comment ending the line of the child before it (`'a' => 1, // why`) is skipped; two +/// children sharing a line are both left alone. +fn run(parent: Node, text: &str, entry: fn(Node, &str) -> Option) -> Vec> { + let mut out: Vec> = Vec::new(); + let mut previous_end: Option = None; + let mut cursor = parent.walk(); + for child in parent.named_children(&mut cursor) { + let start = child.start_position().row; + let shares_line = previous_end == Some(start); + if child.kind() == "comment" && shares_line { + continue; + } + if shares_line && let Some(last) = out.last_mut() { + *last = None; + } + out.push(if shares_line { None } else { entry(child, text) }); + previous_end = Some(child.end_position().row); + } + out +} + +/// Runs of entries on consecutive lines. +fn blocks(entries: &[Option]) -> Vec> { + let mut out: Vec> = Vec::new(); + let mut current: Vec = Vec::new(); + for entry in entries { + match entry { + Some(e) if current.last().is_none_or(|last| last.line + 1 == e.line) => current.push(*e), + Some(e) => out.push(std::mem::replace(&mut current, vec![*e])), + None if current.is_empty() => {} + None => out.push(std::mem::take(&mut current)), + } + } + if !current.is_empty() { + out.push(current); + } + out +} + +/// `'key' => value` alone on one line. +fn key_value(element: Node, text: &str) -> Option { + if element.kind() != "array_element_initializer" { + return None; + } + let mut cursor = element.walk(); + let arrow = element.children(&mut cursor).find(|c| c.kind() == "=>")?; + let key = arrow.prev_sibling()?; + entry(element, key, arrow, text) +} + +/// `$left = value;` (or `= &value`) alone on one line. +fn assignment(statement: Node, text: &str) -> Option { + if statement.kind() != "expression_statement" { + return None; + } + let expression = statement.named_child(0)?; + if !matches!(expression.kind(), "assignment_expression" | "reference_assignment_expression") { + return None; + } + let left = expression.child_by_field_name("left")?; + let mut cursor = expression.walk(); + let operator = expression.children(&mut cursor).find(|c| c.kind() == "=")?; + entry(statement, left, operator, text) +} + +fn entry(whole: Node, left: Node, operator: Node, text: &str) -> Option { + let line = whole.start_position().row; + if whole.has_error() || whole.end_position().row != line { + return None; + } + let line_start = whole.start_byte() - whole.start_position().column; + let starts_line = text[line_start..whole.start_byte()].bytes().all(|b| b == b' ' || b == b'\t'); + let gap = (left.end_byte(), operator.start_byte()); + let blank_gap = text[gap.0..gap.1].bytes().all(|b| b == b' ' || b == b'\t'); + (starts_line && blank_gap).then(|| Entry { line, gap, width: text[line_start..gap.0].chars().count() }) +} + +fn visit(cursor: &mut tree_sitter::TreeCursor, f: &mut impl FnMut(Node)) { + loop { + f(cursor.node()); + if cursor.goto_first_child() { + continue; + } + loop { + if cursor.goto_next_sibling() { + break; + } + if !cursor.goto_parent() { + return; + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::OnceLock; + + const BOTH: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true }; + const PAIRS: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: false }; + const ASSIGNMENTS: PhpAlignment = PhpAlignment { key_value_pairs: false, assignments: true }; + + fn syntax() -> &'static Syntax { + static S: OnceLock = OnceLock::new(); + S.get_or_init(Syntax::new) + } + + fn aligned(text: &str, lines: Option<(usize, usize)>, options: PhpAlignment) -> String { + let out = syntax().align_php(&LanguageId::new("php"), text, lines, options); + let result = out.clone().unwrap_or_else(|| text.to_owned()); + let strip = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::(); + assert_eq!(strip(&result), strip(text), "only whitespace changes"); + assert_eq!( + syntax().align_php(&LanguageId::new("php"), &result, lines, options), + None, + "aligning again changes nothing:\n{result}" + ); + result + } + + fn check(options: PhpAlignment, before: &str, after: &str) { + assert_eq!(aligned(before, None, options), after); + } + + #[test] + fn aligns_the_arrows_of_a_multi_line_array() { + check( + PAIRS, + " 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n", + " 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n", + ); + check( + PAIRS, + " 'a',\n 1234 => 'b',\n);\n", + " 'a',\n 1234 => 'b',\n);\n", + ); + } + + #[test] + fn nested_arrays_align_per_level_and_a_multi_line_value_ends_a_block() { + check( + PAIRS, + " 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n", + " 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n", + ); + } + + #[test] + fn blank_lines_comment_lines_and_elements_without_a_key_end_a_block() { + check( + PAIRS, + " 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n", + " 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n", + ); + } + + #[test] + fn a_comment_at_the_end_of_a_line_keeps_the_block() { + check( + PAIRS, + " 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n", + " 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n", + ); + } + + #[test] + fn single_line_arrays_and_elements_sharing_a_line_stay_as_they_are() { + for text in [ + " 1, 'bbb' => 2];\n", + " 1, 'bbb' => 2,\n 'cc' => 3,\n];\n", + " 1,\n 'bbb' => 2];\n", + ] { + assert_eq!(aligned(text, None, BOTH), text); + } + } + + #[test] + fn arrows_and_equals_signs_outside_arrays_and_assignments_are_not_touched() { + let text = " b';\n\ + $t = \"x = y\";\n\ + // 'k' => 1, $v = 2\n\ + /* 'kk' => 1 */\n\ + foreach ($items as $key => $value) {}\n\ + $f = fn($x) => $x;\n\ + $m = match ($x) {\n 1 => 'a',\n 100 => 'b',\n};\n\ + for ($i = 0; $i < 3; $i++) {}\n\ + function g($a = 1, $bbb = 2) {}\n\ + g(a: 1, bbb: 2);\n\ + $h = << 1,\n 'bbb' => 2,\nEOT;\n"; + let out = aligned(text, None, PAIRS); + assert_eq!(out, text); + } + + #[test] + fn aligns_consecutive_assignments() { + check( + ASSIGNMENTS, + "name = 'n';\n$ref = &$y;\n", + "name = 'n';\n$ref = &$y;\n", + ); + } + + #[test] + fn other_statements_blank_lines_and_multi_line_assignments_end_a_block() { + check( + ASSIGNMENTS, + " 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"; + assert_eq!( + aligned(text, None, PAIRS), + " 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n" + ); + assert_eq!( + aligned(text, None, ASSIGNMENTS), + " 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n" + ); + assert_eq!(syntax().align_php(&LanguageId::new("php"), text, None, PhpAlignment::default()), None); + assert_eq!(syntax().align_php(&LanguageId::new("javascript"), "a = {\n b: 1,\n};\n", None, BOTH), None); + } + + #[test] + fn only_the_given_lines_change_and_they_align_with_the_whole_block() { + let text = " 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n"; + assert_eq!( + aligned(text, Some((2, 3)), PAIRS), + " 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n" + ); + assert_eq!(aligned(text, Some((5, 5)), PAIRS), text); + } + + #[test] + fn widths_count_characters_not_bytes() { + check( + PAIRS, + " 1,\n 'name' => 2,\n];\n", + " 1,\n 'name' => 2,\n];\n", + ); + } + + #[test] + fn code_with_syntax_errors_is_aligned_only_where_it_parses() { + let text = " 1,\n 'bbb' => ,\n 'cc' => 3,\n];\n"; + let out = aligned(text, None, PAIRS); + assert!(out.contains("'bbb' => ,"), "{out}"); + } + + #[test] + fn php_inside_html() { + check( + BOTH, + "\n\n

x = y

\n", + "\n\n

x = y

\n", + ); + } +} diff --git a/docs/en/languages/php.mdx b/docs/en/languages/php.mdx index 66b727555..35f1ddca3 100644 --- a/docs/en/languages/php.mdx +++ b/docs/en/languages/php.mdx @@ -57,6 +57,7 @@ In a Composer project without `vendor/`, or whose installed packages differ from - **PHPStan**: when the project has `vendor/bin/phpstan`, saved files are checked with it and its findings appear as diagnostics. The **PHPStan › Configuration file** setting picks the config; empty uses `phpstan.neon`, `phpstan.neon.dist` or `phpstan.dist.neon` in the project root. - **PHP-CS-Fixer**: when a folder above the file has `.php-cs-fixer.php` or `.php-cs-fixer.dist.php` and the project has `vendor/bin/php-cs-fixer`, **Reformat Code** (`⌥⌘L` / `Ctrl+Alt+L`) uses PHP-CS-Fixer instead of the language server. +- **Alignment**: **Settings › Editor › Code Style › PHP › Alignment** has PhpStorm's **Align key-value pairs** (`=>` in multi-line arrays) and **Align consecutive assignments** (`=` in assignment statements on consecutive lines), both off by default. They apply after the language server or PHP-CS-Fixer formats, on save too; for a selection, only to its lines. A blank line, a comment line, another statement or a value spanning several lines starts a new group, and nested arrays align on their own. ## Run and test diff --git a/docs/zh/languages/php.mdx b/docs/zh/languages/php.mdx index 4870f1eda..276034bfd 100644 --- a/docs/zh/languages/php.mdx +++ b/docs/zh/languages/php.mdx @@ -57,6 +57,7 @@ Composer 项目没有 `vendor/`,或已安装的包与 `composer.lock` 不一 - **PHPStan**:项目中有 `vendor/bin/phpstan` 时,保存的文件会交给它检查,结果显示为诊断。**PHPStan › 配置文件** 用于指定配置;留空则使用项目根目录下的 `phpstan.neon`、`phpstan.neon.dist` 或 `phpstan.dist.neon`。 - **PHP-CS-Fixer**:当文件上层目录中有 `.php-cs-fixer.php` 或 `.php-cs-fixer.dist.php`,且项目有 `vendor/bin/php-cs-fixer` 时,**重新格式化代码**(`⌥⌘L` / `Ctrl+Alt+L`)改用 PHP-CS-Fixer,而不是语言服务器。 +- **对齐**:**设置 › 编辑器 › 代码样式 › PHP › 对齐** 提供与 PhpStorm 相同的 **对齐键值对**(多行数组中的 `=>`)和 **对齐连续赋值**(相邻行赋值语句中的 `=`),默认都关闭。它们在语言服务器或 PHP-CS-Fixer 格式化之后生效,保存时格式化也一样;格式化选区时只作用于选中的行。空行、注释行、其他语句或跨多行的值会开始新的一组,嵌套数组单独对齐。 ## 运行与测试 diff --git a/src/bindings.ts b/src/bindings.ts index 6ff6f51c9..ea671d0b3 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -7425,6 +7425,10 @@ export type LanguageCodeStyle_Deserialize = { lineCommentAtFirstColumn?: boolean | null, /** Comment Code › Add a space at line comment start. */ lineCommentAddSpace?: boolean | null, + /** PHP: align `=>` in multi-line arrays after formatting (other languages ignore it). */ + alignKeyValuePairs?: boolean | null, + /** PHP: align `=` of consecutive assignment statements after formatting. */ + alignConsecutiveAssignments?: boolean | null, }; /** Editor › Code Style › › Tabs and Indents (unset fields inherit). */ @@ -7441,6 +7445,10 @@ export type LanguageCodeStyle_Serialize = { lineCommentAtFirstColumn?: boolean | null, /** Comment Code › Add a space at line comment start. */ lineCommentAddSpace?: boolean | null, + /** PHP: align `=>` in multi-line arrays after formatting (other languages ignore it). */ + alignKeyValuePairs?: boolean | null, + /** PHP: align `=` of consecutive assignment statements after formatting. */ + alignConsecutiveAssignments?: boolean | null, }; /** Language identifier, e.g. `rust`, `typescript`, `kotlin`. Matches LSP `languageId`. */ diff --git a/src/features/settings/__tests__/phpAlignment.test.tsx b/src/features/settings/__tests__/phpAlignment.test.tsx new file mode 100644 index 000000000..f610b9dcb --- /dev/null +++ b/src/features/settings/__tests__/phpAlignment.test.tsx @@ -0,0 +1,66 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { useProject } from "@/platform/project"; +import { PageContext } from "../components/context"; +import { DEFAULT_SETTINGS } from "../model/schema"; +import { openSettings, stagedValue, useSettingsDialog } from "../model/staging"; +import { codeStyleLanguagePages } from "../pages/editor/codeStyle"; + +vi.mock("@/platform/ipc", async (original) => { + const actual = await original(); + return { + ...actual, + isTauri: () => true, + commands: { + ...actual.commands, + languages: async () => [ + { id: "php", name: "PHP", indent: { tabSize: 4, insertSpaces: true }, lineComment: "//" }, + { id: "javascript", name: "JavaScript", lineComment: "//" }, + ], + }, + }; +}); + +beforeEach(() => { + useProject.setState({ settings: structuredClone(DEFAULT_SETTINGS), project: null }); + openSettings("editor.codeStyle.php"); +}); +afterEach(cleanup); + +async function page(language: string) { + const pages = await codeStyleLanguagePages(); + const spec = pages.find((p) => p.id === `editor.codeStyle.${language}`)!; + const Page = spec.component!; + render( + + + , + ); + return spec; +} +const value = () => stagedValue(useSettingsDialog.getState(), "global", "editor.codeStyle.languages"); +const box = (name: string) => screen.getByRole("checkbox", { name }) as HTMLInputElement; + +describe("PHP alignment", () => { + it("is off by default and stages each option on the PHP code style", async () => { + const spec = await page("php"); + expect(spec.keywords).toEqual(expect.arrayContaining(["Align key-value pairs", "Align consecutive assignments"])); + expect(box("Align key-value pairs").checked).toBe(false); + expect(box("Align consecutive assignments").checked).toBe(false); + fireEvent.click(box("Align key-value pairs")); + expect(value()).toEqual({ php: { alignKeyValuePairs: true } }); + fireEvent.click(box("Align consecutive assignments")); + expect(value()).toEqual({ php: { alignKeyValuePairs: true, alignConsecutiveAssignments: true } }); + expect(box("Align key-value pairs").checked).toBe(true); + fireEvent.click(box("Align key-value pairs")); + expect(value()).toEqual({ php: { alignKeyValuePairs: false, alignConsecutiveAssignments: true } }); + fireEvent.click(screen.getByRole("button", { name: "Reset to Language Defaults" })); + expect(value()).toEqual({}); + }); + + it("is offered for PHP only", async () => { + const spec = await page("javascript"); + expect(screen.queryByRole("checkbox", { name: "Align key-value pairs" })).toBeNull(); + expect(spec.keywords).not.toContain("Align key-value pairs"); + }); +}); diff --git a/src/features/settings/pages/editor/codeStyle.tsx b/src/features/settings/pages/editor/codeStyle.tsx index f1660c982..b1a23d91b 100644 --- a/src/features/settings/pages/editor/codeStyle.tsx +++ b/src/features/settings/pages/editor/codeStyle.tsx @@ -204,6 +204,32 @@ function LanguageStyle({ lang }: { lang: LanguageInfo }) { /> + {lang.id === "php" && ( +
+
+ Alignment +
+
+ set({ alignKeyValuePairs: v })} + label="Align key-value pairs" + /> +
+
+ set({ alignConsecutiveAssignments: v })} + label="Align consecutive assignments" + /> +
+
+ {tx( + "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.", + )} +
+
+ )} {lang.lineComment && (
@@ -321,6 +347,7 @@ export async function codeStyleLanguagePages(): Promise { ...(lang.id === "java" ? ["Formatting profile", "IntelliJ IDEA", "Custom Eclipse formatter XML", "Eclipse formatter XML"] : []), + ...(lang.id === "php" ? ["Alignment", "Align key-value pairs", "Align consecutive assignments"] : []), ], component: () => , })); diff --git a/src/platform/editorSettings.ts b/src/platform/editorSettings.ts index 36aedc2df..517a12cdc 100644 --- a/src/platform/editorSettings.ts +++ b/src/platform/editorSettings.ts @@ -38,6 +38,10 @@ export interface LanguageCodeStyle { /** Code Generation › Comment Code (unset: the language's default, see `lineCommentDefaults`). */ lineCommentAtFirstColumn?: boolean; lineCommentAddSpace?: boolean; + /** PHP: align `=>` in multi-line arrays after formatting (PhpStorm's option; off by default). */ + alignKeyValuePairs?: boolean; + /** PHP: align `=` of consecutive assignment statements after formatting. */ + alignConsecutiveAssignments?: boolean; } /** diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 5d7138c36..c3c51c1e8 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2457,5 +2457,9 @@ "Skip": "Skip", "Resize Markdown preview": "Resize Markdown preview", "Run a Python script or module": "Run a Python script or module", - "Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.": "Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed." + "Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.": "Replace every occurrence of '{pattern}' with '{replacement}' in the scope? The search hit its limit, so it runs again to find the occurrences not listed.", + "Alignment": "Alignment", + "Align key-value pairs": "Align key-value pairs", + "Align consecutive assignments": "Align consecutive assignments", + "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 7feac73fa..7437c8a65 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -8832,5 +8832,9 @@ "Add as Maven Project": "添加为 Maven 项目", "This Maven project is not loaded": "此 Maven 项目尚未加载", "Load Maven Project": "加载 Maven 项目", - "Resize Markdown preview": "调整 Markdown 预览宽度" + "Resize Markdown preview": "调整 Markdown 预览宽度", + "Alignment": "对齐", + "Align key-value pairs": "对齐键值对", + "Align consecutive assignments": "对齐连续赋值", + "Lines up => in multi-line arrays and = in consecutive assignments after the language server or PHP-CS-Fixer formats the file; for a selection, only its lines.": "在语言服务器或 PHP-CS-Fixer 格式化文件后,对齐多行数组中的 => 和连续赋值语句中的 =;格式化选区时只对齐选中的行。" }