Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -650,7 +650,6 @@ or removing a command fails until the table changes in the same commit.
| `editor.planTextEdits` | Validate and order a plugin document edit batch into UTF-16 offsets with the document's line ending |
| `editor.parseNavigationInput` | Parse a bounded line or line:column input into zero-based editor coordinates |
| `editor.navigationHistory.reduce` | Reduce one bounded back/forward navigation history event and return the next state plus the location to open |
| `editor.lineCommentToken` | Resolve the line comment token for a file extension or language id |
| `network.proxyPolicy` | Normalize the stored proxy settings into the policy a network stack must apply (mode, server, credentials, exclusion rules) |
| `lsp.plainSnippet` | Convert LSP snippet insert text into plain editor text |
| `lsp.builtinCompletions` | Return lightweight current-file identifier completions |
Expand Down Expand Up @@ -2400,7 +2399,7 @@ destination cannot be opened. See
`rust/fixtures/editor/navigation-history-v1.json`.

`editor.lineEdit` applies one deterministic line-level transform. All offsets
are UTF-16 code units so both hosts can feed the result straight into their
are UTF-16 code units so hosts can feed the result straight into their
text engines. The payload is `{ "operation": "toggleLineComment" |
"duplicateLine" | "deleteLine" | "moveLineUp" | "moveLineDown" | "copyLineUp" |
"copyLineDown", "source": string, "selectionStart": 0, "selectionLength": 0,
Expand All @@ -2414,16 +2413,10 @@ to restore. `applied: false` with every other field omitted marks a legitimate
no-op such as moving the first line up; callers must leave their text view
unchanged and must not consume the keyboard shortcut.

`editor.lineCommentToken` accepts `{ "identifier": "py" }` (case
insensitive; the identifier may be a file extension, a file name including
dotfiles such as `.env`, or a language id — extensions, dotfile basenames,
and language ids share one table) and returns `{ "token": "#" }` or
`{ "token": null }` for file types without a line comment token.

macOS consumes both commands today. Windows still uses its local TypeScript
implementations (`comment-toggle.ts`, `line-operations.ts`) and is expected
to adopt the same contract in a follow-up change; the fixture pins the
canonical behavior for that migration. Deterministic cases are pinned by
Core does not know which token a language uses: the host resolves
`commentToken` from its language registry, where every language — bundled or
contributed by a plugin through `languages[].configuration.lineComment` —
declares its own comments. Deterministic cases are pinned by
`rust/fixtures/editor/line-edit-v1.json`.

`network.proxyPolicy` normalizes the stored proxy settings into the policy a
Expand Down
4 changes: 0 additions & 4 deletions rust/crates/core/src/protocol/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -608,9 +608,6 @@ pub enum EditorCommand {
/// Reduces one bounded back/forward navigation history event
/// (`editor.navigationHistory.reduce`).
NavigationHistoryReduce,
/// Resolves the line comment token for a file extension
/// (`editor.lineCommentToken`).
LineCommentToken,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -1328,7 +1325,6 @@ impl CoreCommand {
"editor.navigationHistory.reduce" => {
Some(Self::Editor(EditorCommand::NavigationHistoryReduce))
}
"editor.lineCommentToken" => Some(Self::Editor(EditorCommand::LineCommentToken)),
"network.proxyPolicy" => Some(Self::NetworkProxyPolicy),
"lsp.plainSnippet" => Some(Self::Lsp(LspCommand::PlainSnippet)),
"lsp.builtinCompletions" => Some(Self::Lsp(LspCommand::BuiltinCompletions)),
Expand Down
18 changes: 0 additions & 18 deletions rust/crates/core/src/runtime/dispatcher/editor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,23 +63,5 @@ pub(super) fn dispatch(
Err(error) => CoreResponse::failure(id, error),
}
}
EditorCommand::LineCommentToken => {
match serde_json::from_value::<lithe_editor::LineCommentTokenRequest>(payload)
.map_err(|error| {
CoreError::new(
ErrorCode::InvalidRequest,
"Invalid editor line comment token request",
)
.with_details(error.to_string())
})
.map(lithe_editor::line_comment_token)
{
Ok(data) => CoreResponse::success(
id,
serde_json::to_value(data).expect("Comment token response should encode"),
),
Err(error) => CoreResponse::failure(id, error),
}
}
}
}
8 changes: 4 additions & 4 deletions rust/crates/editor/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Editor commands owned by Rust Core: deterministic line edits and the
//! comment-token table, find, plugin text edit plans, navigation input and
//! history, editor preferences, recent files and crash-recovery decisions.
//! Editor commands owned by Rust Core: deterministic line edits, find,
//! plugin text edit plans, navigation input and history, editor
//! preferences, recent files and crash-recovery decisions.
//!
//! Hosts apply the returned replacements and states through their own text
//! engine. The `editor.*` JSON commands are dispatched by `lithe-core`.
Expand All @@ -14,7 +14,7 @@ pub mod recent;
pub mod recovery;
pub mod text_edit_plan;

pub use line_edit::{line_comment_token, line_edit, LineCommentTokenRequest, LineEditRequest};
pub use line_edit::{line_edit, LineEditRequest};

#[cfg(test)]
mod tests;
56 changes: 0 additions & 56 deletions rust/crates/editor/src/line_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,15 +49,6 @@ pub struct LineEditRequest {
pub comment_token: Option<String>,
}

/// Request for `editor.lineCommentToken`.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LineCommentTokenRequest {
/// File extension, file name (including dotfiles such as `.env`), or
/// language id, matched case-insensitively.
pub identifier: String,
}

/// Result of `editor.lineEdit`. When `applied` is false the operation is a
/// no-op (for example moving the first line up) and the caller must not
/// modify its text view. Otherwise `text` replaces
Expand Down Expand Up @@ -115,53 +106,6 @@ impl LineEditOutcome {
}
}

/// Result of `editor.lineCommentToken`. `token` is `None` for file types
/// without a line comment token; callers must not intercept the shortcut.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LineCommentToken {
/// Line comment token, such as `//` or `#`.
pub token: Option<String>,
}

/// Resolves the line comment token for a file extension, file name, or
/// language id. The table is the single shared source of truth; it covers
/// file extensions (`swift`, `py`), language ids (`python`, `javascript`),
/// and dotfile names whose basename matches an entry (`.env`).
pub fn line_comment_token(request: LineCommentTokenRequest) -> LineCommentToken {
let key = request.identifier.to_lowercase();
let token = lookup_line_comment_token(&key).or_else(|| {
// Dotfiles report an empty pathExtension on macOS, so callers pass
// the basename: fall back to the segment after the last dot so
// `.env` resolves through `env` and `Foo.py` through `py`.
let last_segment = key.rsplit('.').next()?;
if last_segment.is_empty() || last_segment == key {
return None;
}
lookup_line_comment_token(last_segment)
});
LineCommentToken {
token: token.map(str::to_string),
}
}

fn lookup_line_comment_token(identifier: &str) -> Option<&'static str> {
match identifier {
// C family and other double-slash languages
"c" | "h" | "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "kt" | "kts" | "swift" | "js"
| "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "go" | "rs" | "cs" | "csharp" | "php" | "dart"
| "scala" | "groovy" | "m" | "mm" | "zig" | "javascript" | "javascriptreact"
| "typescript" | "typescriptreact" | "kotlin" | "rust" => Some("//"),
// Hash languages
"py" | "python" | "rb" | "ruby" | "sh" | "bash" | "zsh" | "shell" | "yml" | "yaml"
| "toml" | "ini" | "cfg" | "conf" | "properties" | "env" | "dotenv" | "r" | "rmarkdown"
| "pl" | "elixir" | "ex" => Some("#"),
// Dash languages
"sql" | "lua" | "hs" | "haskell" => Some("--"),
_ => None,
}
}

/// Applies a line-level editing operation. Returns a no-op outcome instead of
/// an error for legitimate boundary cases such as moving the first line up.
pub fn line_edit(request: LineEditRequest) -> Result<LineEditOutcome, CoreError> {
Expand Down
88 changes: 10 additions & 78 deletions rust/crates/editor/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
//! Tests for the deterministic line-editing transforms and the comment
//! token table. Expected values were pinned against IDEA semantics and the
//! review regressions from PR #642.
//! Tests for the deterministic line-editing transforms. Expected values
//! were pinned against IDEA semantics and the review regressions from
//! PR #642.

use serde_json::{json, Value};

use super::line_edit::{line_comment_token, line_edit, LineCommentTokenRequest, LineEditRequest};
use super::line_edit::{line_edit, LineEditRequest};

fn edit(
operation: &str,
Expand Down Expand Up @@ -500,65 +500,6 @@ fn copy_line_down_behaves_like_duplicate() {
assert_eq!(outcome["selectionStart"], json!(5));
}

// MARK: Comment token table

#[test]
fn line_comment_token_maps_common_extensions_and_language_ids() {
for (extension, expected) in [
("swift", "//"),
("Swift", "//"),
("ts", "//"),
("csharp", "//"),
("zig", "//"),
("rust", "//"),
("javascript", "//"),
("javascriptreact", "//"),
("typescript", "//"),
("typescriptreact", "//"),
("kotlin", "//"),
("py", "#"),
("python", "#"),
("ruby", "#"),
("yaml", "#"),
("properties", "#"),
("shell", "#"),
("dotenv", "#"),
("sql", "--"),
("lua", "--"),
] {
let token = line_comment_token(LineCommentTokenRequest {
identifier: extension.to_string(),
});
assert_eq!(
token.token.as_deref(),
Some(expected),
"extension {extension}"
);
}
}

#[test]
fn line_comment_token_returns_none_for_unknown_extension() {
for extension in ["json", ""] {
let token = line_comment_token(LineCommentTokenRequest {
identifier: extension.to_string(),
});
assert_eq!(token.token, None, "extension {extension}");
}
}

#[test]
fn line_comment_token_resolves_dotfile_basenames() {
// Regression: macOS pathExtension is empty for dotfiles such as .env,
// so callers pass the basename and Core resolves the last dot segment.
for (name, expected) in [(".env", Some("#")), ("Foo.py", Some("#")), ("README", None)] {
let token = line_comment_token(LineCommentTokenRequest {
identifier: name.to_string(),
});
assert_eq!(token.token.as_deref(), expected, "file name {name}");
}
}

#[test]
fn move_down_maps_crlf_separator_caret_to_valid_selection() {
// Regression: a caret between \r and \n once mapped to an offset
Expand Down Expand Up @@ -655,21 +596,12 @@ fn shared_fixture_cases_match_core_outcomes() {
.expect("line edit fixture should be valid JSON");
for case_value in fixture["cases"].as_array().expect("cases") {
let name = case_value["name"].as_str().expect("case name");
// The fixture covers both editor commands; dispatch on the request
// shape so one file pins the whole editor contract.
let outcome = if case_value["request"].get("operation").is_some() {
let request: LineEditRequest = serde_json::from_value(case_value["request"].clone())
.unwrap_or_else(|error| panic!("{name}: {error:?}"));
serde_json::to_value(
line_edit(request).unwrap_or_else(|error| panic!("{name}: {error:?}")),
)
.expect("outcome should serialize")
} else {
let request: LineCommentTokenRequest =
serde_json::from_value(case_value["request"].clone())
.unwrap_or_else(|error| panic!("{name}: {error:?}"));
serde_json::to_value(line_comment_token(request)).expect("token should serialize")
};
let request: LineEditRequest = serde_json::from_value(case_value["request"].clone())
.unwrap_or_else(|error| panic!("{name}: {error:?}"));
let outcome = serde_json::to_value(
line_edit(request).unwrap_or_else(|error| panic!("{name}: {error:?}")),
)
.expect("outcome should serialize");
assert_eq!(outcome, case_value["expected"], "case {name}");
}
}
36 changes: 0 additions & 36 deletions rust/fixtures/editor/line-edit-v1.json
Original file line number Diff line number Diff line change
Expand Up @@ -356,24 +356,6 @@
"selectionLength": 0
}
},
{
"name": "resolve line comment token for extension",
"request": {
"identifier": "py"
},
"expected": {
"token": "#"
}
},
{
"name": "resolve line comment token for unknown extension",
"request": {
"identifier": "json"
},
"expected": {
"token": null
}
},
{
"name": "move down normalizes a caret inside a CRLF separator",
"request": {
Expand All @@ -391,15 +373,6 @@
"selectionLength": 0
}
},
{
"name": "resolve line comment token for dotfile basename",
"request": {
"identifier": ".env"
},
"expected": {
"token": "#"
}
},
{
"name": "duplicate preserves selection end across CRLF normalization",
"request": {
Expand All @@ -416,15 +389,6 @@
"selectionStart": 4,
"selectionLength": 3
}
},
{
"name": "resolve line comment token for the rust language id",
"request": {
"identifier": "rust"
},
"expected": {
"token": "//"
}
}
]
}
Loading