Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 4867c99734 fix(ci): use a Windows-absolute devshell path in the project environment test 2026-11-18 15:06:51 +08:00
200 змінених файлів з 1496 додано та 6580 видалено

No files matched your search

+15 -65
Переглянути файл
@@ -32,12 +32,7 @@ jobs:
pull-requests: read
outputs:
rust: ${{ steps.classify.outputs.rust }}
server: ${{ steps.classify.outputs.server }}
plugins: ${{ steps.classify.outputs.plugins }}
deny: ${{ steps.classify.outputs.deny }}
frontend: ${{ steps.classify.outputs.frontend }}
e2e: ${{ steps.classify.outputs.e2e }}
catalog: ${{ steps.classify.outputs.catalog }}
steps:
- id: classify
env:
@@ -45,55 +40,26 @@ jobs:
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
jobs="rust server plugins deny frontend e2e catalog"
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
for job in $jobs; do echo "$job=true" >> "$GITHUB_OUTPUT"; done
echo "rust=true" >> "$GITHUB_OUTPUT"
echo "frontend=true" >> "$GITHUB_OUTPUT"
exit 0
fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# A change to CI itself runs everything.
ci='^\.github/(workflows/ci\.yml|actions/)'
docs='^(docs/|\.agents/|\.claude/|\.idea/|\.github/ISSUE_TEMPLATE/|\.github/pull_request_template\.md$|[^/]+\.md$|LICENSE$|NOTICE$)'
# Frontend-only paths. The Rust code embeds a few files under src/; those stay out.
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|evals/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
web='^(src/|e2e/|perf/|public/|scripts/|smoke/|index\.html$|vite\.config\.ts$|tsconfig[^/]*\.json$|knip\.ts$|playwright\.config\.ts$|\.oxlintrc\.json$|\.oxfmtrc\.json$)'
embedded='^src/(bindings\.ts|styles/tokens\.css|features/plugins/views/frame-bridge\.js|platform/keymaps/)'
# Plugin web pages are their own pnpm projects, checked by the Plugins job only.
plugin_web='^plugins/official/[^/]+/web-src/'
# Paths the frontend checks never read...
backend='^(crates/|src-tauri/|sdk/|wit/|java/|fixtures/|Cargo\.(toml|lock)$|deny\.toml$|rustfmt\.toml$|rust-toolchain(\.toml)?$|\.cargo/)'
# ...except these, which frontend tests and e2e fixtures load.
read_by_web='^(fixtures/(folding|django-app)/|crates/ide-plugin/tests/fixtures/|crates/ide-db/(src|tests/fixtures)/snowflake/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# What the browser app and its e2e tests are built from.
app='^(src/|e2e/|public/|index\.html$|vite\.config\.ts$|tsconfig\.json$|playwright\.config\.ts$|package\.json$|pnpm-(lock|workspace)\.yaml$|crates/ide-plugin/tests/fixtures/|src-tauri/(icons|capabilities)/|src-tauri/tauri\.conf\.json$)'
# The plugin workspaces: the SDK, the plugins, their interface and the host's fixture plugins.
plugin_ws='^(sdk/|plugins/|wit/|crates/ide-plugin/tests/fixtures/|rust-toolchain(\.toml)?$)'
# Never compiled into the openidea-server binary.
not_server='^(src-tauri/|sdk/|fixtures/|crates/[^/]+/(tests|benches)/)'
deps='(^|/)Cargo\.(toml|lock)$|^deny\.toml$'
# The text catalog test reads the string literals of every Rust source.
rust_source='^(crates|src-tauri/src)/.*\.rs$'
any() { grep -Eq "$1" files.txt; }
outside() { [ -n "$(grep -Ev "$1" files.txt || true)" ]; }
set_job() { echo "$1=$2" | tee -a "$GITHUB_OUTPUT"; }
if any "$ci"; then
for job in $jobs; do set_job "$job" true; done
exit 0
fi
on() { if "${@:2}"; then set_job "$1" true; else set_job "$1" false; fi; }
rust_build() { outside "$1" || any "$embedded"; }
web_checks() { outside "$docs|$plugin_web|$backend" || any "$read_by_web"; }
catalog_only() { ! web_checks && any "$rust_source"; }
on rust rust_build "$docs|$web|$plugin_web"
on server rust_build "$docs|$web|$plugin_web|$not_server"
on plugins any "$plugin_ws"
on deny any "$deps"
on frontend web_checks
on e2e any "$app"
on catalog catalog_only
# A job runs when any changed file falls outside the paths that can't affect it.
rust=false
if grep -Ev "$docs|$web" files.txt | grep -q . || grep -Eq "$embedded" files.txt; then rust=true; fi
frontend=false
if grep -Ev "$docs" files.txt | grep -q .; then frontend=true; fi
echo "rust=$rust frontend=$frontend"
echo "rust=$rust" >> "$GITHUB_OUTPUT"
echo "frontend=$frontend" >> "$GITHUB_OUTPUT"
rust:
name: Rust (${{ matrix.os }})
@@ -145,7 +111,7 @@ jobs:
server:
name: Remote server (linux musl)
needs: changes
if: needs.changes.outputs.server == 'true'
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 40
runs-on: ubuntu-22.04
steps:
@@ -163,7 +129,7 @@ jobs:
plugins:
name: Plugins (SDK, official, fixtures)
needs: changes
if: needs.changes.outputs.plugins == 'true'
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 30
runs-on: ubuntu-22.04
env:
@@ -215,7 +181,7 @@ jobs:
deny:
name: Cargo deny
needs: changes
if: needs.changes.outputs.deny == 'true'
if: needs.changes.outputs.rust == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
@@ -244,26 +210,10 @@ jobs:
- run: pnpm test
- run: pnpm build
# A backend-only change can still drop a string the text catalog uses: run that one test.
catalog:
name: Text catalog
needs: changes
if: needs.changes.outputs.catalog == 'true'
timeout-minutes: 15
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v5
with: { version: 11 }
- uses: actions/setup-node@v5
with: { node-version: 22, cache: pnpm }
- run: pnpm install --frozen-lockfile
- run: pnpm vitest run src/platform/locales/textCatalog.test.ts
e2e:
name: E2E (${{ matrix.shard }}/2)
needs: changes
if: needs.changes.outputs.e2e == 'true'
if: needs.changes.outputs.frontend == 'true'
timeout-minutes: 30
runs-on: ubuntu-24.04
strategy:
+1 -67
Переглянути файл
@@ -15,7 +15,6 @@ on:
- "crates/**"
- "languages/**"
- "fixtures/**"
- "java/**"
- "Cargo.toml"
- "Cargo.lock"
- "src/features/run/**"
@@ -42,77 +41,12 @@ env:
CARGO_INCREMENTAL: 0
jobs:
# The languages a pull request can affect: a change to one language's fixture, definition or
# JDT LS bundle runs that language; crates the smoke doesn't exercise and other crates' tests
# run none; anything else runs them all. Pushes and manual runs always run them all.
changes:
name: Changes
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: read
outputs:
languages: ${{ steps.classify.outputs.languages }}
steps:
- id: classify
env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
run: |
set -euo pipefail
all="typescript python rust go java kotlin php c cpp"
emit() { tr ' ' '\n' <<< "$1" | { grep . || true; } | sort -u | jq -Rsc 'split("\n") | map(select(. != ""))'; }
if [ "$GITHUB_EVENT_NAME" != pull_request ]; then
echo "languages=$(emit "$all")" | tee -a "$GITHUB_OUTPUT"
exit 0
fi
gh api --paginate "repos/$GITHUB_REPOSITORY/pulls/$PR/files" \
--jq '.[] | .filename, (.previous_filename // empty)' > files.txt
cat files.txt
# Crates outside what the smoke runs (language servers, debuggers, run configurations,
# SDKs, build tools and the project model): cargo metadata, deps of ide-lsp/dap/run/sdk/tools.
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-search|ide-spell|ide-ssh|ide-streams|ide-vcs|ide-web)/'
# The workflow's paths, less those handled per language below.
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger)/|src/platform/|smoke/|package\.json$|pnpm-lock\.yaml$|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
langs=""
while read -r f; do
case "$f" in
crates/ide-host/tests/language_smoke.rs | crates/ide-host/tests/project_smoke.rs) langs="$all"; break ;;
crates/*/tests/* | crates/*/benches/*) ;;
fixtures/ts-app/*) langs+=" typescript" ;;
fixtures/python-app/*) langs+=" python" ;;
fixtures/rust-app/*) langs+=" rust" ;;
fixtures/go-app/*) langs+=" go" ;;
fixtures/java-app/*) langs+=" java" ;;
fixtures/kotlin-gradle/*) langs+=" kotlin" ;;
fixtures/php-app/*) langs+=" php" ;;
fixtures/c-app/*) langs+=" c cpp" ;;
fixtures/*) ;;
languages/typescript.toml | languages/typescriptreact.toml | languages/javascript.toml | languages/javascriptreact.toml) langs+=" typescript" ;;
languages/python.toml) langs+=" python" ;;
languages/rust.toml) langs+=" rust" ;;
languages/go.toml | languages/gomod.toml | languages/gowork.toml) langs+=" go" ;;
languages/java.toml) langs+=" java" ;;
languages/kotlin.toml) langs+=" kotlin" ;;
languages/php.toml) langs+=" php" ;;
languages/c.toml) langs+=" c" ;;
languages/cpp.toml) langs+=" cpp" ;;
languages/*) ;;
java/kotlin-bridge/*) langs+=" kotlin" ;;
java/*) langs+=" java kotlin" ;;
*) if grep -Eq "$smoke" <<< "$f" && ! grep -Eq "$unused" <<< "$f"; then langs="$all"; break; fi ;;
esac
done < files.txt
echo "languages=$(emit "$langs")" | tee -a "$GITHUB_OUTPUT"
smoke:
name: Language smoke (${{ matrix.language }})
needs: changes
if: needs.changes.outputs.languages != '[]'
strategy:
fail-fast: false
matrix:
language: ${{ fromJSON(needs.changes.outputs.languages) }}
language: [typescript, python, rust, go, java, kotlin, php, c, cpp]
# C/C++ debug with GDB, whose DAP interpreter needs 14+: 22.04 ships 12.1, 24.04 ships 15.
runs-on: ${{ (matrix.language == 'c' || matrix.language == 'cpp') && 'ubuntu-24.04' || 'ubuntu-22.04' }}
timeout-minutes: 40
+51 -438
Переглянути файл
@@ -399,429 +399,163 @@ pub fn apply_save_json(
Ok(saved_names)
}
const COPILOT_PLUGIN_MANIFESTS: &[&str] = &[
".github/plugin/plugin.json",
".plugin/plugin.json",
".claude-plugin/plugin.json",
".cursor-plugin/plugin.json",
"plugin.json",
];
#[derive(Clone, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum SourceFormat {
Jsonc,
CodexToml,
CopilotPlugin { root: PathBuf },
}
#[derive(Clone)]
struct SourceSpec {
id: String,
label: String,
id: &'static str,
label: &'static str,
path: PathBuf,
format: SourceFormat,
suggested_scope: McpScope,
native_provider: Option<&'static str>,
claude_project_lookup: bool,
disabled_servers: std::sync::Arc<BTreeSet<String>>,
}
#[derive(Default)]
struct CopilotSettings {
disabled_mcp_servers: std::sync::Arc<BTreeSet<String>>,
disabled_plugins: BTreeSet<String>,
}
fn external_source_specs(home_dir: Option<&Path>, workspace_root: Option<&Path>) -> Vec<SourceSpec> {
let mut specs = Vec::new();
let no_disabled: std::sync::Arc<BTreeSet<String>> = std::sync::Arc::new(BTreeSet::new());
if let Some(root) = workspace_root {
specs.push(SourceSpec {
id: "workspace-mcp".into(),
label: "Project (.mcp.json)".into(),
id: "workspace-mcp",
label: "Project (.mcp.json)",
path: root.join(".mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("claude"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "vscode-mcp".into(),
label: "VS Code (.vscode/mcp.json)".into(),
id: "vscode-mcp",
label: "VS Code (.vscode/mcp.json)",
path: root.join(".vscode").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor-project".into(),
label: "Cursor Project (.cursor/mcp.json)".into(),
id: "cursor-project",
label: "Cursor Project (.cursor/mcp.json)",
path: root.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex-project".into(),
label: "Codex Project (.codex/config.toml)".into(),
id: "codex-project",
label: "Codex Project (.codex/config.toml)",
path: root.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::Workspace,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini-project".into(),
label: "Gemini Project (.gemini/settings.json)".into(),
id: "gemini-project",
label: "Gemini Project (.gemini/settings.json)",
path: root.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::Workspace,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
}
if let Some(home) = home_dir {
let copilot_dir = home.join(".copilot");
let copilot_settings = read_copilot_settings(&copilot_dir);
specs.push(SourceSpec {
id: "copilot-cli".into(),
label: "GitHub Copilot CLI".into(),
path: copilot_dir.join("mcp-config.json"),
id: "copilot-cli",
label: "GitHub Copilot CLI",
path: home.join(".copilot").join("mcp-config.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: copilot_settings.disabled_mcp_servers.clone(),
});
specs.extend(copilot_plugin_source_specs(&copilot_dir, &copilot_settings));
specs.push(SourceSpec {
id: "claude-code".into(),
label: "Claude Code".into(),
id: "claude-code",
label: "Claude Code",
path: home.join(".claude.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("claude"),
claude_project_lookup: true,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "codex".into(),
label: "Codex".into(),
id: "codex",
label: "Codex",
path: home.join(".codex").join("config.toml"),
format: SourceFormat::CodexToml,
suggested_scope: McpScope::User,
native_provider: Some("codex"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "cursor".into(),
label: "Cursor".into(),
id: "cursor",
label: "Cursor",
path: home.join(".cursor").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("cursor"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "gemini".into(),
label: "Gemini CLI".into(),
id: "gemini",
label: "Gemini CLI",
path: home.join(".gemini").join("settings.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: Some("gemini"),
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "jetbrains-air".into(),
label: "JetBrains Air".into(),
id: "jetbrains-air",
label: "JetBrains Air",
path: home.join(".jetbrains").join("mcp").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled.clone(),
});
specs.push(SourceSpec {
id: "copilot-intellij".into(),
label: "GitHub Copilot (JetBrains)".into(),
id: "copilot-intellij",
label: "GitHub Copilot (JetBrains)",
path: home.join(".config").join("github-copilot").join("intellij").join("mcp.json"),
format: SourceFormat::Jsonc,
suggested_scope: McpScope::User,
native_provider: None,
claude_project_lookup: false,
disabled_servers: no_disabled,
});
}
specs
}
fn read_copilot_settings(copilot_dir: &Path) -> CopilotSettings {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("settings.json")) else {
return CopilotSettings::default();
};
let Ok(root) = parse_jsonc_value(&text) else {
return CopilotSettings::default();
};
let disabled_mcp_servers = root
.get("disabledMcpServers")
.and_then(Value::as_array)
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned))
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
let disabled_plugins = root
.get("enabledPlugins")
.and_then(Value::as_object)
.map(|obj| {
obj.iter()
.filter(|(_, v)| v.as_bool() == Some(false))
.map(|(k, _)| k.trim().to_owned())
.filter(|k| !k.is_empty())
.collect::<BTreeSet<_>>()
})
.unwrap_or_default();
CopilotSettings { disabled_mcp_servers: std::sync::Arc::new(disabled_mcp_servers), disabled_plugins }
}
fn copilot_plugin_source_specs(copilot_dir: &Path, settings: &CopilotSettings) -> Vec<SourceSpec> {
let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json")) else {
return Vec::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return Vec::new();
};
let Some(installed) = root.get("installedPlugins").and_then(Value::as_array) else {
return Vec::new();
};
let mut seen_ids = HashSet::new();
let mut specs = Vec::new();
for entry in installed {
let Some(obj) = entry.as_object() else { continue };
if obj.get("enabled").and_then(Value::as_bool) == Some(false) {
continue;
}
let Some(name) = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) else {
continue;
};
let marketplace = obj.get("marketplace").and_then(Value::as_str).map(str::trim).unwrap_or_default();
if settings.disabled_plugins.contains(name)
|| (!marketplace.is_empty()
&& (settings.disabled_plugins.contains(&format!("{name}@{marketplace}"))
|| settings.disabled_plugins.contains(&format!("{marketplace}/{name}"))))
{
continue;
}
let Some(raw_cache) = obj.get("cache_path").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())
else {
continue;
};
let plugin_root =
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
if !plugin_root.is_dir() {
continue;
}
let Some((manifest_path, _)) = read_copilot_plugin_servers(&plugin_root) else {
continue;
};
let base_id = if marketplace.is_empty() {
format!("copilot-plugin:{name}")
} else {
format!("copilot-plugin:{marketplace}/{name}")
};
let mut id = base_id.clone();
let mut suffix = 2usize;
while !seen_ids.insert(id.clone()) {
id = format!("{base_id}#{suffix}");
suffix += 1;
}
let label = if marketplace.is_empty() {
format!("GitHub Copilot Plugin ({name})")
} else {
format!("GitHub Copilot Plugin ({name} · {marketplace})")
};
specs.push(SourceSpec {
id,
label,
path: manifest_path,
format: SourceFormat::CopilotPlugin { root: plugin_root },
suggested_scope: McpScope::User,
native_provider: Some("copilot"),
claude_project_lookup: false,
disabled_servers: settings.disabled_mcp_servers.clone(),
});
}
specs
}
fn resolve_within_dir(base_dir: &Path, candidate: &Path) -> Option<PathBuf> {
if candidate.as_os_str().is_empty() {
return None;
}
let base_canon = dunce::canonicalize(base_dir).ok()?;
let clean = candidate.strip_prefix(".").unwrap_or(candidate);
let joined = if clean.is_relative() { base_dir.join(clean) } else { clean.to_path_buf() };
let meta = std::fs::metadata(&joined).ok()?;
if !meta.is_file() {
return None;
}
let target_canon = dunce::canonicalize(&joined).ok()?;
target_canon.starts_with(&base_canon).then_some(joined)
}
fn expand_plugin_root_vars(value: &str, root: &str) -> String {
value.replace("${COPILOT_PLUGIN_ROOT}", root).replace("${CLAUDE_PLUGIN_ROOT}", root).replace("${PLUGIN_ROOT}", root)
}
fn expand_plugin_servers(servers: &mut BTreeMap<String, AgentMcpServer>, plugin_root: &Path) {
let root = plugin_root.to_string_lossy();
for srv in servers.values_mut() {
if let Some(cmd) = srv.command.as_mut() {
*cmd = expand_plugin_root_vars(cmd, &root);
}
for arg in &mut srv.args {
*arg = expand_plugin_root_vars(arg, &root);
}
if let Some(url) = srv.url.as_mut() {
*url = expand_plugin_root_vars(url, &root);
}
for val in srv.env.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
for val in srv.headers.values_mut() {
*val = expand_plugin_root_vars(val, &root);
}
}
}
fn extract_plugin_manifest_servers(
plugin_root: &Path,
manifest_path: &Path,
mcp_val: &Value,
) -> (PathBuf, BTreeMap<String, AgentMcpServer>) {
match mcp_val {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
return (path, map);
}
(manifest_path.to_path_buf(), BTreeMap::new())
}
Value::Object(_) => {
let wrapper = json!({ "mcpServers": mcp_val });
(manifest_path.to_path_buf(), extract_servers_from_root(&wrapper, None))
}
Value::Array(items) => {
let mut merged = BTreeMap::new();
let mut first_path: Option<PathBuf> = None;
for item in items {
match item {
Value::String(rel) => {
if let Some(path) = resolve_within_dir(plugin_root, Path::new(rel.trim())) {
let map = read_external_file(&path);
if !map.is_empty() && first_path.is_none() {
first_path = Some(path);
}
merged.extend(map);
}
}
Value::Object(_) => {
let map = extract_servers_from_root(item, None);
if !map.is_empty() && first_path.is_none() {
first_path = Some(manifest_path.to_path_buf());
}
merged.extend(map);
}
_ => {}
}
}
(first_path.unwrap_or_else(|| manifest_path.to_path_buf()), merged)
}
_ => (manifest_path.to_path_buf(), BTreeMap::new()),
}
}
fn read_copilot_plugin_servers(plugin_root: &Path) -> Option<(PathBuf, BTreeMap<String, AgentMcpServer>)> {
if let Some(dot_mcp) = resolve_within_dir(plugin_root, Path::new(".mcp.json")) {
let mut servers = read_external_file(&dot_mcp);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((dot_mcp, servers));
}
}
for rel in COPILOT_PLUGIN_MANIFESTS {
let Some(manifest_path) = resolve_within_dir(plugin_root, Path::new(rel)) else {
continue;
};
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
continue;
};
let Ok(manifest) = parse_jsonc_value(&text) else {
continue;
};
let Some(mcp_val) = manifest.get("mcpServers") else {
continue;
};
let (source_path, mut servers) = extract_plugin_manifest_servers(plugin_root, &manifest_path, mcp_val);
if !servers.is_empty() {
expand_plugin_servers(&mut servers, plugin_root);
return Some((source_path, servers));
}
}
None
}
fn read_source_servers(spec: &SourceSpec, workspace_root: Option<&Path>) -> BTreeMap<String, AgentMcpServer> {
let mut servers = match &spec.format {
SourceFormat::CopilotPlugin { root } => {
read_copilot_plugin_servers(root).map(|(_, map)| map).unwrap_or_default()
}
SourceFormat::CodexToml => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
parse_codex_toml_servers(&text)
}
SourceFormat::Jsonc => {
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut map = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches =
Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
map.insert(name, srv);
}
}
let Ok(text) = std::fs::read_to_string(&spec.path) else {
return BTreeMap::new();
};
if spec.format == SourceFormat::CodexToml {
return parse_codex_toml_servers(&text);
}
let Ok(root) = parse_jsonc_value(&text) else {
return BTreeMap::new();
};
let mut servers = extract_servers_from_root(&root, None);
if spec.claude_project_lookup
&& let Some(ws) = workspace_root
&& let Some(projects) = root.get("projects").and_then(Value::as_object)
{
let ws_canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.to_path_buf());
for (proj_key, proj_val) in projects {
let matches = Path::new(proj_key) == ws || dunce::canonicalize(proj_key).is_ok_and(|c| c == ws_canon);
if matches {
for (name, srv) in extract_servers_from_root(proj_val, None) {
servers.insert(name, srv);
}
}
map
}
};
for name in spec.disabled_servers.iter() {
if let Some(srv) = servers.get_mut(name) {
srv.enabled = false;
}
}
servers
@@ -878,8 +612,8 @@ pub fn discover_external_sources(home_dir: Option<&Path>, workspace_root: Option
})
.collect();
out.push(McpExternalSource {
id: spec.id,
label: spec.label,
id: spec.id.to_owned(),
label: spec.label.to_owned(),
path: IpcPath(spec.path),
suggested_scope: spec.suggested_scope,
native_provider: spec.native_provider.map(str::to_owned),
@@ -907,7 +641,7 @@ pub fn apply_import_selected(
let mut by_source: BTreeMap<&str, BTreeMap<String, AgentMcpServer>> = BTreeMap::new();
for spec in &specs {
if selections.iter().any(|s| s.source_id == spec.id) {
by_source.insert(spec.id.as_str(), read_source_servers(spec, workspace_root));
by_source.insert(spec.id, read_source_servers(spec, workspace_root));
}
}
let target = match scope {
@@ -1636,125 +1370,4 @@ mod tests {
assert_eq!(workspace["events-sse"].transport, McpTransport::Sse);
assert_eq!(workspace["events-sse"].url.as_deref(), Some("https://sse.example.com/events"));
}
#[test]
fn discovers_and_imports_copilot_installed_plugin_mcp_servers() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
let copilot = home.join(".copilot");
let azure_root = copilot.join("installed-plugins/_direct/azure-skills");
let inline_root = copilot.join("installed-plugins/awesome-copilot/inline-tools");
let disabled_root = copilot.join("installed-plugins/_direct/disabled-plug");
let outside_root = tmp.path().join("outside");
std::fs::create_dir_all(azure_root.join(".plugin")).unwrap();
std::fs::create_dir_all(inline_root.join(".claude-plugin")).unwrap();
std::fs::create_dir_all(&disabled_root).unwrap();
std::fs::create_dir_all(&outside_root).unwrap();
std::fs::write(
azure_root.join(".plugin/plugin.json"),
r#"{"name":"azure","version":"1.2.106","mcpServers":"./.mcp.json"}"#,
)
.unwrap();
std::fs::write(
azure_root.join(".mcp.json"),
r#"{"mcpServers":{"azure":{"command":"npx","args":["-y","@azure/mcp@latest","${COPILOT_PLUGIN_ROOT}/cfg"],"env":{"PLUG_DIR":"${CLAUDE_PLUGIN_ROOT}"}}}}"#,
)
.unwrap();
std::fs::write(
inline_root.join(".claude-plugin/plugin.json"),
r#"{"name":"inline-tools","version":"0.1.0","mcpServers":{"inline-srv":{"command":"${PLUGIN_ROOT}/bin/run","args":["--stdio"]},"muted-srv":{"command":"echo","args":["off"]}}}"#,
)
.unwrap();
std::fs::write(
disabled_root.join(".mcp.json"),
r#"{"mcpServers":{"never":{"command":"npx","args":["never"]}}}"#,
)
.unwrap();
std::fs::write(outside_root.join("secret.json"), r#"{"mcpServers":{"escaped":{"command":"sh"}}}"#).unwrap();
let escape_root = copilot.join("installed-plugins/_direct/escape-plug");
std::fs::create_dir_all(escape_root.join(".plugin")).unwrap();
std::fs::write(
escape_root.join(".plugin/plugin.json"),
r#"{"name":"escape-plug","mcpServers":"../../../../outside/secret.json"}"#,
)
.unwrap();
// `~/.copilot/config.json` includes leading `//` comments in Copilot CLI.
let config_json = format!(
"// Managed automatically.\n{}",
serde_json::json!({
"installedPlugins": [
{
"name": "azure",
"marketplace": "",
"enabled": true,
"cache_path": azure_root,
},
{
"name": "inline-tools",
"marketplace": "awesome-copilot",
"enabled": true,
"cache_path": inline_root,
},
{
"name": "disabled-plug",
"marketplace": "",
"enabled": false,
"cache_path": disabled_root,
},
{
"name": "escape-plug",
"marketplace": "",
"enabled": true,
"cache_path": escape_root,
}
]
})
);
std::fs::write(copilot.join("config.json"), config_json).unwrap();
std::fs::write(copilot.join("settings.json"), r#"{"disabledMcpServers":["muted-srv"]}"#).unwrap();
let sources = discover_external_sources(Some(&home), None);
assert_eq!(sources.len(), 2);
let azure_src = sources.iter().find(|s| s.id == "copilot-plugin:azure").unwrap();
assert_eq!(azure_src.label, "GitHub Copilot Plugin (azure)");
assert_eq!(azure_src.native_provider.as_deref(), Some("copilot"));
assert_eq!(azure_src.path.0, azure_root.join(".mcp.json"));
assert_eq!(azure_src.servers.len(), 1);
assert!(azure_src.servers[0].enabled);
assert_eq!(
azure_src.servers[0].args,
vec!["-y", "@azure/mcp@latest", &format!("{}/cfg", azure_root.display())]
);
let inline_src = sources.iter().find(|s| s.id == "copilot-plugin:awesome-copilot/inline-tools").unwrap();
assert_eq!(inline_src.label, "GitHub Copilot Plugin (inline-tools · awesome-copilot)");
assert_eq!(inline_src.path.0, inline_root.join(".claude-plugin/plugin.json"));
let active = inline_src.servers.iter().find(|s| s.name == "inline-srv").unwrap();
assert!(active.enabled);
assert_eq!(active.command.as_deref(), Some(format!("{}/bin/run", inline_root.display()).as_str()));
let muted = inline_src.servers.iter().find(|s| s.name == "muted-srv").unwrap();
assert!(!muted.enabled);
let mut user = BTreeMap::new();
let mut workspace = BTreeMap::new();
let imported = apply_import_selected(
&mut user,
&mut workspace,
Some(&home),
None,
McpScope::User,
&[McpImportSelection { source_id: "copilot-plugin:azure".into(), name: "azure".into() }],
false,
)
.unwrap();
assert_eq!(imported, vec!["azure".to_string()]);
assert_eq!(user["azure"].env.get("PLUG_DIR").map(String::as_str), Some(azure_root.to_str().unwrap()));
}
}
-6
Переглянути файл
@@ -446,12 +446,6 @@ 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<bool>,
/// 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<bool>,
/// PHP: align `=` of consecutive assignment statements after formatting.
#[serde(skip_serializing_if = "Option::is_none")]
pub align_consecutive_assignments: Option<bool>,
}
/// Editor › Code Style (General tab + per-language overrides).
-4
Переглянути файл
@@ -1504,10 +1504,6 @@ pub struct MavenSettings {
pub active_profiles: String,
/// Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ).
pub delegate_build: bool,
/// Download `-sources.jar` of dependencies when the Java language server imports the
/// project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
/// from a library class's Download Sources banner.
pub download_sources: bool,
}
impl MavenSettings {
+6 -42
Переглянути файл
@@ -912,7 +912,7 @@ fn on_reverse_request(mgr: &Arc<DebugManager>, s: &Arc<Session>, seq: i64, comma
/// A `runInTerminal` program and the pseudo-terminal it runs in.
pub(crate) struct ProgramTerminal {
writer: Arc<ide_core::input::InputWriter>,
writer: ide_core::input::InputWriter,
killer: Box<dyn portable_pty::ChildKiller + Send + Sync>,
#[cfg_attr(not(unix), allow(dead_code))]
pid: Option<u32>,
@@ -1025,12 +1025,10 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
let _ = child.wait();
})
.map_err(|e| format!("terminal input worker: {e}"))?;
let writer = Arc::new(writer);
let pid = child.process_id();
forward_terminal_output(
s,
reader,
writer.clone(),
#[cfg(unix)]
wait_readable,
);
@@ -1045,35 +1043,10 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
Ok(json!({ "processId": pid }))
}
/// A terminal's cursor position query (DSR). ConPTY sends one when it starts and runs the program
/// only once the terminal answers; programs that lay out a prompt ask it too.
const CURSOR_QUERY: &[u8] = b"\x1b[6n";
/// `chunk` without its cursor position queries, and how many there were.
pub(crate) fn take_cursor_queries(chunk: &[u8]) -> (Vec<u8>, usize) {
let mut out = Vec::with_capacity(chunk.len());
let mut queries = 0;
let mut rest = chunk;
while let Some(at) = rest.windows(CURSOR_QUERY.len()).position(|w| w == CURSOR_QUERY) {
out.extend_from_slice(&rest[..at]);
rest = &rest[at + CURSOR_QUERY.len()..];
queries += 1;
}
out.extend_from_slice(rest);
(out, queries)
}
/// Length of the end of `pending` that may begin a cursor position query the next read completes.
pub(crate) fn partial_cursor_query(pending: &[u8]) -> usize {
(1..CURSOR_QUERY.len()).rev().find(|&n| pending.ends_with(&CURSOR_QUERY[..n])).unwrap_or(0)
}
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept). The debug
/// console is no terminal, so cursor position queries are answered here (top-left corner).
/// The program's terminal output, as stdout lines (`\r\n` as `\n`; colours are kept).
fn forward_terminal_output(
s: &Session,
mut reader: Box<dyn std::io::Read + Send>,
answer: Arc<ide_core::input::InputWriter>,
#[cfg(unix)] mut wait_readable: impl FnMut() -> std::io::Result<()> + Send + 'static,
) {
let session = s.id;
@@ -1105,20 +1078,11 @@ fn forward_terminal_output(
break;
}
}
let (rest, queries) = take_cursor_queries(&pending);
pending = rest;
for _ in 0..queries {
if let Err(e) = answer.write(b"\x1b[1;1R") {
tracing::warn!(%session, "debug terminal cursor position: {e}");
}
}
// Keep incomplete UTF-8 sequences, a `\r` that may start a `\r\n`, and the start of
// a cursor position query for the next chunk.
let keep = partial_cursor_query(&pending);
let mut valid = match std::str::from_utf8(&pending[..pending.len() - keep]) {
Ok(_) => pending.len() - keep,
// Keep incomplete UTF-8 sequences, and a `\r` that may start a `\r\n`, for the next chunk.
let mut valid = match std::str::from_utf8(&pending) {
Ok(_) => pending.len(),
Err(e) if e.error_len().is_none() => e.valid_up_to(),
Err(_) => pending.len() - keep,
Err(_) => pending.len(),
};
if valid > 0 && pending[valid - 1] == b'\r' {
valid -= 1;
-38
Переглянути файл
@@ -1010,44 +1010,6 @@ async fn run_in_terminal_spawns_debuggee() {
assert!(response["body"]["processId"].as_u64().unwrap() > 0);
}
/// The debug console answers a terminal's cursor position query: ConPTY asks one before it runs
/// the program at all (Windows debuggees never started), and programs that lay out a prompt ask too.
#[tokio::test]
async fn run_in_terminal_answers_cursor_position_queries() {
#[cfg(unix)]
let program = vec![
"sh".into(),
"-c".into(),
r"stty -echo -icanon min 6; printf '\033[6n'; reply=$(dd bs=6 count=1 2>/dev/null); stty sane; case $reply in *'[1;1R') echo answered;; esac".into(),
];
#[cfg(windows)]
let program = vec!["cmd".into(), "/c".into(), "echo answered".into()];
let h = harness(Script { run_in_terminal: Some(program), ..Script::default() });
h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Output { output, .. } if output.contains("answered"))).await;
let output: String = h
.events
.lock()
.iter()
.filter_map(|e| match e {
IdeEvent::Debug { event: DebugEvent::Output { output, .. }, .. } => Some(output.clone()),
_ => None,
})
.collect();
assert!(!output.contains("\x1b[6n"), "{output:?}");
}
#[test]
fn cursor_position_queries_are_taken_out_of_the_output() {
use crate::session::{partial_cursor_query, take_cursor_queries};
assert_eq!(take_cursor_queries(b"a\x1b[6nb\x1b[6n"), (b"ab".to_vec(), 2));
assert_eq!(take_cursor_queries(b"\x1b[0mtext"), (b"\x1b[0mtext".to_vec(), 0));
assert_eq!(partial_cursor_query(b"text\x1b["), 2);
assert_eq!(partial_cursor_query(b"text\x1b[6"), 3);
assert_eq!(partial_cursor_query(b"text\x1b[0m"), 0);
assert_eq!(partial_cursor_query(b"text"), 0);
}
#[cfg(unix)]
#[tokio::test]
async fn run_in_terminal_program_reads_typed_input() {
-31
Переглянути файл
@@ -916,37 +916,6 @@ impl DbManager {
self.tunnels.lock().remove(id);
}
/// Creates a database on the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `template`, the database
/// the server copies (PostgreSQL and SQL Server refuse to copy one that has sessions).
pub async fn create_database(&self, id: &str, template: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
self.disconnect(&format!("{id}:{template}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// Drops `database` of the server of data source `id` by running `statement` on the data
/// source's own database, after closing the IDE's connections to `database`.
/// Refuses the database the data source connects to and read-only data sources.
pub async fn drop_database(&self, id: &str, database: &str, statement: &str) -> IdeResult<()> {
let id = split_target(id).0;
if self.source(id)?.read_only {
return Err(IdeError::new(ErrorKind::PermissionDenied, "the data source is read-only"));
}
if self.databases(id).await?.current == database {
return Err(IdeError::invalid(format!("the data source connects to {database}; it cannot drop it")));
}
self.disconnect(&format!("{id}:{database}")).await;
self.pool(id).await?.execute(statement, 0, &CancellationToken::new()).await?;
self.remember_statement(id, statement);
Ok(())
}
/// The databases of the server of data source `id` (PostgreSQL), the connected one first.
pub async fn databases(&self, id: &str) -> IdeResult<Databases> {
let id = split_target(id).0;
-38
Переглянути файл
@@ -230,44 +230,6 @@ async fn opening_a_table_reads_multi_column_keys_in_order() -> IdeResult<()> {
}
/// Runs `job` with the newest installed copy of its tool, the way the dialogs do.
#[tokio::test]
async fn drops_a_database_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_drop_me", 0, &c).await?;
db.execute("p", "CREATE DATABASE oi_drop_me TEMPLATE template0", 0, &c).await?;
// What the tree and a manual-commit console leave open on the database.
db.schemas("p:oi_drop_me").await?;
db.set_manual_commit("p:oi_drop_me", true).await?;
db.execute("p:oi_drop_me", "SELECT 1", 1, &c).await?;
db.drop_database("p", "oi_drop_me", "drop database oi_drop_me").await?;
assert!(!db.is_connected("p:oi_drop_me"));
assert!(!db.databases("p").await?.names.iter().any(|n| n == "oi_drop_me"));
let current = db.databases("p").await?.current;
let refused = db.drop_database("p", &current, &format!("drop database \"{current}\"")).await;
assert!(refused.is_err());
Ok(())
}
#[tokio::test]
async fn creates_a_database_from_a_template_the_ide_holds_connections_to() -> IdeResult<()> {
let tmp = tempfile::tempdir().unwrap();
let Some(db) = manager(&tmp).await else { return Ok(()) };
let c = CancellationToken::new();
db.execute("p", "DROP DATABASE IF EXISTS oi_from_template", 0, &c).await?;
db.schemas("p:template1").await?;
db.create_database("p", "template1", "create database oi_from_template").await?;
assert!(!db.is_connected("p:template1"));
assert!(db.databases("p").await?.names.iter().any(|n| n == "oi_from_template"));
db.execute("p", "DROP DATABASE oi_from_template", 0, &c).await?;
Ok(())
}
async fn run_tool(db: &DbManager, target: &str, job: ide_db::tools::DbToolJob) -> IdeResult<()> {
let install = ide_db::tools::find_installs(job.tool()).into_iter().next().expect("installed");
let mut lines = Vec::new();
-41
Переглянути файл
@@ -95,44 +95,3 @@ async fn sqlserver_values_paging_transactions_and_cancellation() {
task.await.unwrap();
assert_eq!(pool.rows("SELECT 1", 1).await.unwrap()[0][0].as_deref(), Some("1"));
}
#[tokio::test]
async fn sqlserver_creates_from_a_held_model_and_force_drops_a_held_database() {
let Ok(server) = std::env::var("OPENIDEA_TEST_SQLSERVER") else { return };
let mut parts = server.splitn(4, ':');
let (host, port, user, password) = (
parts.next().unwrap(),
parts.next().unwrap().parse().unwrap(),
parts.next().unwrap(),
parts.next().unwrap_or(""),
);
let source = |database: &str| DataSource {
id: "s".into(),
name: "sqlserver".into(),
driver: DbDriver::SqlServer,
host: host.into(),
port: Some(port),
user: user.into(),
database: database.into(),
ssl: DbSslMode::Disable,
..Default::default()
};
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().to_path_buf();
let ssh = std::sync::Arc::new(ide_ssh::SshManager::new(root.join("ssh-passwords.json")));
let db = ide_db::DbManager::new(root.clone(), root.join("passwords.json"), root.join("history.json"), ssh);
db.save_sources(vec![source("master")]).await.unwrap();
db.set_password("s", Some(password.into()), false).await.unwrap();
let name = format!("oi_force_drop_{}", std::process::id());
// The tree's connection to `model` would keep SQL Server from copying it.
db.schemas("s:model").await.unwrap();
db.create_database("s", "model", &format!("create database {name};")).await.unwrap();
assert!(!db.is_connected("s:model"));
let other = Pool::connect(&source(&name), Some(password), None).await.unwrap();
let held = Held::acquire(&other).await.unwrap();
let force = format!("alter database {name} set single_user with rollback immediate;\ndrop database {name};");
db.drop_database("s", &name, &force).await.unwrap();
assert!(!db.databases("s").await.unwrap().names.contains(&name));
drop(held);
}
+11 -198
Переглянути файл
@@ -2,9 +2,9 @@
use crate::Host;
use ide_core::event::NotifyLevel;
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_core::settings::{ExternalFormatter, LanguagesSettings};
use ide_core::{DocId, IdeError, IdeEvent, IdeResult, Pos, Range, TextEdit};
use ide_language::LanguageConfig;
use ide_lsp::types::FormatOptions;
use ide_tools::{Tools, formatter};
use std::path::Path;
@@ -129,101 +129,12 @@ 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<TextEdit>,
range: Option<Range>,
alignment: PhpAlignment,
) -> IdeResult<Vec<TextEdit>> {
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<Range>,
options: FormatOptions,
) -> IdeResult<Option<Vec<TextEdit>>> {
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(None);
return Ok(Vec::new());
}
if snap.read_only {
return Err(IdeError::invalid("The file is read-only"));
@@ -249,8 +160,7 @@ async fn provider_edits(
)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
.map(Some);
.map_err(|e| IdeError::internal(e.to_string()))?;
}
// A committed PHP-CS-Fixer configuration takes over Reformat Code for `.php` files.
if options.tool.is_none()
@@ -258,7 +168,7 @@ async fn provider_edits(
&& let Some(fixer) = formatter::php_cs_fixer(&snap.path)
{
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
return Ok(Vec::new());
}
host.require_trust(window)?;
if snap.read_only {
@@ -278,7 +188,7 @@ async fn provider_edits(
body: Some("PHP-CS-Fixer does not support selection formatting; formatted the whole file".into()),
});
}
return Ok(Some(edits));
return Ok(edits);
}
let mut selected = external_tool(options.tool, language.as_ref(), &snap.path, &settings.languages)?;
if let Some(tool) = selected
@@ -290,13 +200,13 @@ async fn provider_edits(
}
let Some(selected) = selected else {
if options.on_save && !settings.editor.format_on_save {
return Ok(None);
return Ok(Vec::new());
}
return project.lsp.format(doc, range, options).await.map(Some);
return project.lsp.format(doc, range, options).await;
};
let tool_settings = settings.languages.formatter(selected);
if options.on_save && !tool_settings.run_on_save {
return Ok(None);
return Ok(Vec::new());
}
host.require_trust(window)?;
if snap.read_only {
@@ -352,7 +262,7 @@ async fn provider_edits(
)),
});
}
edits.map(Some).map_err(|e| e.with_tool(tool))
edits.map_err(|e| e.with_tool(tool))
}
#[cfg(test)]
@@ -503,103 +413,6 @@ 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<TextEdit> {
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 = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n";
let edits = align_formatted(&syntax, &php, text, Vec::new(), None, ALIGN).unwrap();
assert_eq!(after(text, &edits), "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n");
// The language server re-indents the array: the alignment applies to its result.
let text = "<?php\n$a = [\n'a' => 1,\n'bbb' => 2,\n];\n";
let formatted = "<?php\n$a = [\n 'a' => 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), "<?php\n$a = [\n 'a' => 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 = "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 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!("<?php\n\ndeclare(strict_types=1);\n{}", &text["<?php\n".len()..]);
let edits = whole_file(text, &formatted);
// Lines 3..=6 select the array, up to the start of the line after it.
let range = Range::new(Pos::new(3, 0), Pos::new(7, 0));
let aligned = align_formatted(&syntax, &php, text, edits, Some(range), ALIGN).unwrap();
assert_eq!(aligned.len(), 2, "one edit per changed region: {aligned:?}");
assert_eq!(
after(text, &aligned),
"<?php\n\ndeclare(strict_types=1);\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 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), "<?php\n$x = 1;\n$yyy = 2;\n$a = [\n 'a' => 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");
-10
Переглянути файл
@@ -253,16 +253,6 @@ impl Host {
self.project(window)?.require_trust()
}
/// [`Self::require_trust`] for IDE-wide toolchain work (SDK detection, tool installs) that
/// also runs from a window without a project, such as Settings opened from the Welcome
/// screen: there is no project there to trust.
pub fn require_trust_if_project(&self, window: &str) -> IdeResult<()> {
match self.project(window) {
Ok(project) => project.require_trust(),
Err(_) => Ok(()),
}
}
/// The window that owns what `window` starts.
pub fn owner_window<'a>(&self, window: &'a str) -> &'a str {
(self.owner)(window)
-216
Переглянути файл
@@ -356,13 +356,6 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
t.drain(..cut);
}
});
let config = match resolve_jvm_application(call, config, errors).await? {
Ok(config) => config,
Err(reason) => {
errors.process_outputs.push(reason);
return Ok(false);
}
};
let info = crate::ops::run::run_start(&call.host(), call.window(), config, emit, None).await?;
let exit = wait_exit(call, info.id, None).await?.flatten();
if exit == Some(0) {
@@ -374,177 +367,6 @@ async fn run_to_end(call: &Call, config: RunConfig, errors: &mut BuildErrors) ->
Ok(false)
}
/// Run configuration kinds launched as a JVM main class (`JVM_APPLICATION_KINDS` in the UI).
const JVM_APPLICATION_KINDS: [&str; 2] = ["application", "spring-boot"];
const CLASSPATH: &str = "${classpath}";
const TEST_CLASSPATH: &str = "${testClasspath}";
/// `java` options whose value is the next argument (`parseJavaArgs` in the UI).
const JAVA_OPTIONS_WITH_VALUE: [&str; 13] = [
"-cp",
"-classpath",
"--class-path",
"-p",
"--module-path",
"--upgrade-module-path",
"--add-modules",
"--add-opens",
"--add-exports",
"--add-reads",
"--patch-module",
"--limit-modules",
"--enable-native-access",
];
/// The main class of `java` arguments and which classpath placeholder they use (`Some(true)`:
/// `${testClasspath}`; `None`: an explicit classpath or none).
fn java_main_class(args: &[String]) -> (Option<&str>, Option<bool>) {
let mut test = None;
let mut i = 0;
while i < args.len() {
let a = args[i].as_str();
if a == "-jar" {
return (None, test);
}
if matches!(a, "-cp" | "-classpath" | "--class-path") {
match args.get(i + 1).map(String::as_str) {
Some(CLASSPATH) => test = Some(false),
Some(TEST_CLASSPATH) => test = Some(true),
_ => {}
}
i += 2;
continue;
}
if JAVA_OPTIONS_WITH_VALUE.contains(&a) {
i += 2;
continue;
}
if !a.starts_with('-') {
return (Some(a), test);
}
i += 1;
}
(None, test)
}
/// `args` with the classpath placeholders replaced and the module path added (`resolveJavaCommand`).
fn resolved_java_args(args: &[String], info: &ide_lsp::jdtls::JavaLaunchInfo) -> Vec<String> {
let cp = info.class_paths.join(&info.path_list_separator);
let mut out = Vec::with_capacity(args.len() + 2);
if !info.module_paths.is_empty() && !args.iter().any(|a| a == "-p" || a == "--module-path") {
out.push("--module-path".to_owned());
out.push(info.module_paths.join(&info.path_list_separator));
}
out.extend(args.iter().map(|a| if a == CLASSPATH || a == TEST_CLASSPATH { cp.clone() } else { a.clone() }));
out
}
/// The module (relative to the project root) of a JVM source file: the part before
/// `src/<set>/<language>/` (`jvmModuleDir` without a build model).
fn jvm_module_of(rel: &str) -> Option<String> {
let rel = rel.replace('\\', "/");
let parts: Vec<&str> = rel.split('/').collect();
(0..parts.len().saturating_sub(3)).find_map(|i| {
(parts[i] == "src" && matches!(parts[i + 2], "java" | "kotlin" | "scala" | "groovy"))
.then(|| parts[..i].join("/"))
})
}
/// The module of a configuration saved without one, found from its main class's source
/// (`findJavaModule`): `None` unless exactly one module declares it.
async fn find_java_module(call: &Call, main: &str) -> IdeResult<Option<String>> {
let outer = main.split('$').next().unwrap_or(main);
let (pkg, simple) = outer.rsplit_once('.').unwrap_or(("", outer));
let mut names = vec![format!("{simple}.java"), format!("{simple}.kt")];
if let Some(stem) = simple.strip_suffix("Kt") {
names.push(format!("{stem}.kt"));
}
let mut modules = std::collections::BTreeSet::new();
for name in names {
for path in crate::ops::nav::find_files_named(&call.host(), call.window(), name).await? {
let path = std::path::PathBuf::from(path);
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let declared = text
.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix("package "))
.map(|p| p.trim_end_matches(';').trim())
.unwrap_or("");
if declared != pkg {
continue;
}
let rel = path.strip_prefix(call.root()).unwrap_or(&path).to_string_lossy().into_owned();
modules.insert(jvm_module_of(&rel).unwrap_or_default());
}
}
Ok((modules.len() == 1).then(|| modules.into_iter().next().unwrap_or_default()))
}
/// A JVM application configuration ready to start, as the Run tool window launches it:
/// built per its before-launch build policy, with `${classpath}` / `${testClasspath}`, the
/// module path and the module's `java` resolved through jdtls. `Err` says why it cannot start
/// (compile errors are added to `errors`). Other configurations are returned as they are.
async fn resolve_jvm_application(
call: &Call,
config: RunConfig,
errors: &mut BuildErrors,
) -> IdeResult<Result<RunConfig, String>> {
if !JVM_APPLICATION_KINDS.contains(&config.kind.as_str()) {
return Ok(Ok(config));
}
let (main, test) = java_main_class(&config.args);
let Some(main) = main.map(str::to_owned) else {
return Ok(Err(format!("No main class in '{}'", config.name)));
};
let module = match config.extras.module.clone() {
Some(module) => module,
None => match find_java_module(call, &main).await? {
Some(module) => module,
None => return Ok(Err(format!("Cannot determine the module for main class '{main}'"))),
},
};
let policy = config.extras.build_policy.unwrap_or_default();
let cancel = ide_core::CancellationToken::new();
let host = call.host();
let info = crate::ops::java::resolve_launch(
&host,
call.window(),
std::path::PathBuf::from(&module),
test == Some(true),
policy,
&cancel,
)
.await?;
use ide_lsp::jdtls::JavaBuildStatus;
if matches!(info.build, Some(JavaBuildStatus::Failed | JavaBuildStatus::WithErrors))
&& policy != ide_run::BuildPolicy::MakeAndContinueOnErrors
{
for e in &info.errors {
errors.errors.push(format!(
"{}:{}: {}",
std::path::PathBuf::from(e.path.clone()).display(),
e.line,
e.message
));
}
let reason = if info.build == Some(JavaBuildStatus::Failed) {
format!("Build failed; '{}' was not started.", config.name)
} else {
format!("Build has compile errors; '{}' was not started.", config.name)
};
return Ok(Err(reason));
}
if test.is_some() && info.class_paths.is_empty() {
return Ok(Err("The classpath is empty: is the module imported by the Java language server?".to_owned()));
}
let args = resolved_java_args(&config.args, &info);
let command = match (&info.java_exec, config.command.as_str()) {
(Some(exec), "java") => exec.clone(),
_ => config.command.clone(),
};
Ok(Ok(RunConfig { command, args, ..config }))
}
/// The configuration's before-launch tasks, as the Run tool window runs them; returns why
/// the launch is aborted, if it is. Tool windows are not activated.
async fn before_launch(
@@ -786,10 +608,6 @@ one by one",
if let Some(reason) = before_launch(&call, &config, &configs, &mut Vec::new(), &mut errors).await? {
return Err(execution_failed(&[errors.text(), Some(reason)]));
}
let config = match resolve_jvm_application(&call, config, &mut errors).await? {
Ok(config) => config,
Err(reason) => return Err(execution_failed(&[errors.text(), Some(reason)])),
};
let collector = Arc::new(Mutex::new(OutputCollector::create(&config.name)?));
let output_path = collector.lock().path.clone();
let sink = collector.clone();
@@ -866,40 +684,6 @@ provided, values are merged over existing env.",
mod tests {
use super::*;
fn strings(args: &[&str]) -> Vec<String> {
args.iter().map(|a| (*a).to_owned()).collect()
}
#[test]
fn java_arguments_name_the_main_class_and_classpath_placeholder() {
let run = strings(&["-Xmx1g", "-cp", CLASSPATH, "--add-opens", "a/b=ALL-UNNAMED", "com.example.App", "x"]);
assert_eq!(java_main_class(&run), (Some("com.example.App"), Some(false)));
assert_eq!(java_main_class(&strings(&["-classpath", TEST_CLASSPATH, "T"])), (Some("T"), Some(true)));
assert_eq!(java_main_class(&strings(&["-cp", "lib/*", "Main"])), (Some("Main"), None));
assert_eq!(java_main_class(&strings(&["-jar", "app.jar"])), (None, None));
}
#[test]
fn resolved_java_arguments_replace_the_placeholder_and_add_the_module_path() {
let info = ide_lsp::jdtls::JavaLaunchInfo {
class_paths: vec!["/p/target/classes".into(), "/m2/a.jar".into()],
module_paths: vec!["/m2/mod.jar".into()],
path_list_separator: ":".into(),
..Default::default()
};
assert_eq!(
resolved_java_args(&strings(&["-cp", CLASSPATH, "App"]), &info),
strings(&["--module-path", "/m2/mod.jar", "-cp", "/p/target/classes:/m2/a.jar", "App"])
);
}
#[test]
fn a_source_file_belongs_to_the_module_before_its_source_set() {
assert_eq!(jvm_module_of("repro-dto/src/main/java/com/example/App.java").as_deref(), Some("repro-dto"));
assert_eq!(jvm_module_of("src/test/kotlin/AppTest.kt").as_deref(), Some(""));
assert_eq!(jvm_module_of("scripts/App.java"), None);
}
fn config() -> RunConfig {
RunConfig {
id: "user:x".into(),
-28
Переглянути файл
@@ -139,32 +139,6 @@ pub async fn db_disconnect(host: &Host, window: &str, id: String) -> IdeResult<(
Ok(())
}
#[command(trust = trusted)]
pub async fn db_create_database(
host: &Host,
window: &str,
id: String,
template: String,
statement: String,
) -> IdeResult<()> {
// Creates a database on the server of data source `id` with `statement`, copied from `template` (New › Database).
let db = host.project(window)?.db.clone();
db.create_database(&id, &template, &statement).await
}
#[command(trust = trusted)]
pub async fn db_drop_database(
host: &Host,
window: &str,
id: String,
database: String,
statement: String,
) -> IdeResult<()> {
// Drops `database` of the server of data source `id` with `statement` (Drop… on a database node).
let db = host.project(window)?.db.clone();
db.drop_database(&id, &database, &statement).await
}
#[command(trust = trusted)]
pub async fn db_databases(host: &Host, window: &str, id: String) -> IdeResult<Databases> {
// Databases of the server of data source `id` (PostgreSQL); connect to one as `<id>:<database>`.
@@ -504,12 +478,10 @@ ide_command::domain!(
db_connected,
db_console_path,
db_consoles,
db_create_database,
db_database_catalog,
db_databases,
db_ddl,
db_disconnect,
db_drop_database,
db_execute,
db_explain,
db_finish_transaction,
-13
Переглянути файл
@@ -70,18 +70,6 @@ pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
}
/// An automatic save: `false` (nothing written) when the file changed on disk after the
/// buffer was edited, which only an explicit save overwrites.
#[command(trust = always)]
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
let project = host.project(window)?;
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
if saved {
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
}
Ok(saved)
}
#[command(trust = always)]
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
let project = host.project(window)?;
@@ -121,7 +109,6 @@ ide_command::domain!(
doc_open,
doc_open_untitled,
doc_save,
doc_autosave,
doc_save_all,
doc_save_as,
doc_snapshot,
-5
Переглянути файл
@@ -311,11 +311,6 @@ async fn shutdown_does_not_wait_forever_for_a_stuck_capture() {
shutdown_within(&f.host, std::time::Duration::from_millis(200)).await;
assert!(started.elapsed() < std::time::Duration::from_secs(5));
assert!(cancel.is_cancelled());
// The cleanup is only waited for briefly and finishes in the background on a busy machine.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
while stuck_dir.exists() && std::time::Instant::now() < deadline {
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
}
assert!(!stuck_dir.exists(), "its directory is removed once the wait is over");
}
+1 -1
Переглянути файл
@@ -34,7 +34,7 @@ pub async fn java_resolve_launch(
result
}
pub(crate) async fn resolve_launch(
async fn resolve_launch(
host: &Host,
window: &str,
module: PathBuf,
+12 -12
Переглянути файл
@@ -34,9 +34,9 @@ pub struct ProjectInterpreter {
}
/// Installed interpreters / toolchains of `kind`; project-local ones first.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<Vec<Sdk>> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let project = host.project(window).ok();
if kind == SdkKind::Jdk {
host.apply_added_jdks();
@@ -63,10 +63,10 @@ pub async fn sdk_detect(host: &Host, window: &str, kind: SdkKind) -> IdeResult<V
}
/// The Python interpreters of the recently opened projects, each with its project.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeResult<Vec<ProjectInterpreter>> {
// Newest first. The open project is skipped: `sdk_detect` lists its own.
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let current = host.project(window).ok().map(|p| p.root.clone());
let config = host.config_dir.clone();
// Probing runs the project's interpreter (and its settings may name any program): only
@@ -111,9 +111,9 @@ pub async fn sdk_python_project_interpreters(host: &Host, window: &str) -> IdeRe
}
/// An existing Python executable or virtualenv folder as an SDK; `None` if Python cannot run.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_interpreter(host: &Host, window: &str, path: PathBuf) -> IdeResult<Option<Sdk>> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let root = host.project(window).ok().map(|p| p.root.clone());
tokio::task::spawn_blocking(move || Ok(ide_sdk::python_interpreter_sdk(&path, root.as_deref())))
.await
@@ -320,7 +320,7 @@ pub async fn sdk_locate_tools(
}
/// Creates a Python environment with `tool` (`venv` / `uv` / `poetry`); output streams through `on_output`.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_create_venv(
host: &Host,
window: &str,
@@ -330,7 +330,7 @@ pub async fn sdk_python_create_venv(
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<Sdk> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
ide_sdk::python::create_venv(tool, &base, &location, &cancel, &|line| {
@@ -343,14 +343,14 @@ pub async fn sdk_python_create_venv(
result?
}
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_packages(
host: &Host,
window: &str,
python: PathBuf,
request: RequestId,
) -> IdeResult<Vec<PythonPackage>> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let cancel = host.begin_project_request(window, request);
let result =
tokio::task::spawn_blocking(move || ide_sdk::python::list_packages(&python, &cancel)).await.map_err(join_err);
@@ -360,7 +360,7 @@ pub async fn sdk_python_packages(
/// Installs (`uninstall = false`) or removes a package; output streams through `on_output`.
#[allow(clippy::too_many_arguments)]
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn sdk_python_pip(
host: &Host,
window: &str,
@@ -371,7 +371,7 @@ pub async fn sdk_python_pip(
request: RequestId,
on_output: Channel<String>,
) -> IdeResult<()> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let project_root = host.project(window).ok().map(|p| p.root.clone());
let cancel = host.begin_project_request(window, request);
let result = tokio::task::spawn_blocking(move || {
+5 -5
Переглянути файл
@@ -11,7 +11,7 @@ use std::path::PathBuf;
/// The installer, reporting the executables chosen in the window's settings.
fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
host.require_trust_if_project(window)?;
host.require_trust(window)?;
let data = host.local_data_dir.clone();
let (settings, root) = match host.project(window) {
Ok(project) => (project.settings.effective(), project.root.clone()),
@@ -56,7 +56,7 @@ fn reconfigure_servers(host: &Host) {
}
/// Status of every known language server / debug adapter and the languages using it.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
let tools = tools(host, window)?;
let langs = languages(host, window);
@@ -65,7 +65,7 @@ pub async fn tools_list(host: &Host, window: &str) -> IdeResult<Vec<ToolInfo>> {
/// Installs (or reinstalls) a tool into `<app-data>/tools`, streaming output through
/// `on_event`. Cancel with `cancel_request(request)`.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_install(
host: &Host,
window: &str,
@@ -93,7 +93,7 @@ pub async fn tools_install(
/// Newer versions of the tools the IDE installed (release downloads and npm packages).
/// Cancel with `cancel_request(request)`.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> IdeResult<Vec<ToolUpdate>> {
let tools = tools(host, window)?;
let cancel = host.begin_request(request);
@@ -103,7 +103,7 @@ pub async fn tools_updates(host: &Host, window: &str, request: RequestId) -> Ide
}
/// Removes a tool the IDE installed.
#[command(trust = outside_restricted)]
#[command(trust = trusted)]
pub async fn tools_uninstall(host: &Host, window: &str, name: String) -> IdeResult<ToolInfo> {
let tools = tools(host, window)?;
let langs = languages(host, window);
+3 -10
Переглянути файл
@@ -47,19 +47,12 @@ pub async fn serves_page(url: &str) -> bool {
response.status().is_success() && html
}
/// The built-in server's URL for `path` (started on first use). A file whose language is
/// HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
/// The built-in server's URL for `path` (started on first use).
#[command(trust = always)]
pub async fn web_url(host: &Host, window: &str, path: IpcPath) -> IdeResult<String> {
// Under the window's project when it holds the file.
let project = host.project(window).ok();
let root = project.as_ref().map(|p| p.root.as_path());
let languages = project.as_ref().map_or(&host.languages, |p| &p.languages);
if matches!(languages.detect(&path, None).as_str(), "html" | "django-html") {
host.web.page_url_for(root, &path).await
} else {
host.web.url_for(root, &path).await
}
let root = host.project(window).ok().map(|p| p.root.clone());
host.web.url_for(root.as_deref(), &path).await
}
#[cfg(test)]
-3
Переглянути файл
@@ -272,7 +272,6 @@ impl Host {
lombok.jar(),
);
ide_sdk::apply::configure_gradle_runtime(cfg, root, server_root, &effective);
ide_sdk::apply::configure_maven_sources(cfg, &effective);
ide_sdk::jdtls::launch_directly(cfg);
}
ide_sdk::apply::server_protocol_overrides(cfg, &effective);
@@ -286,8 +285,6 @@ impl Host {
effective.languages.java.gradle.linked_projects.as_deref(),
build_files.as_deref(),
);
// After the import settings: they extend the workspace folder's name.
ide_sdk::jdtls_workspaces::use_own_temp(cfg, &data_dir);
}
}));
}
+5 -11
Переглянути файл
@@ -879,15 +879,16 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
// Room for activation (about 3_100 on macOS, more on Windows). A background task gets ten
// times it (5 s / 500 ms): enough for each step of `patient` with its CPU work (32_000 to
// 80_000), not for the whole run without the refill on each report.
let limits = Limits {
let f = fixture(Limits {
fuel: 40_000,
timeout: Duration::from_millis(500),
background: Duration::from_millis(5_000),
..Limits::default()
};
let f = fixture(limits);
});
f.install(&misbehave_pkg());
f.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
if f.host.set_capability("misbehave", "process:git", true).is_err() {
return;
}
// Warm up activation in its own call so `patient` starts with a fresh budget.
assert_eq!(f.run("misbehave", "echo", Some("warm")).unwrap().as_deref(), Some("warm"));
@@ -896,13 +897,6 @@ fn background_tasks_scale_and_renew_cpu_fuel_budget() {
let err = f.run("misbehave", "spin", None).unwrap_err();
assert!(err.contains("exceeded its CPU budget (40000 fuel per call)"), "{err}");
// Beginning a task alone must not renew its scaled budget.
let quiet = fixture(limits);
quiet.install(&misbehave_pkg());
quiet.host.set_capability("misbehave", "process:git", true).expect("grant Git capability");
let err = quiet.run("misbehave", "patient", Some("quiet:4000")).unwrap_err();
assert!(err.contains("exceeded its CPU budget (400000 fuel per call)"), "{err}");
}
#[test]
-3
Переглянути файл
@@ -45,9 +45,6 @@ async fn a_commands_trust_class_decides_where_it_runs() {
assert_eq!(allowed("main", class), in_restricted, "{class:?} in Restricted Mode");
assert_eq!(allowed("welcome", class), without_project, "{class:?} without a project");
}
// Toolchain detection runs from Settings opened on the Welcome screen, but not in Restricted Mode.
assert!(ide_host::ops::sdk::sdk_detect(&host, "welcome", ide_sdk::SdkKind::Zig).await.is_ok());
assert!(ide_host::ops::sdk::sdk_detect(&host, "main", ide_sdk::SdkKind::Zig).await.is_err());
// These requests validate the vendor before any network access, independently of project trust.
let error = ide_host::ops::tools::jdk_download_releases(&host, "unknown-vendor".into(), ide_core::RequestId(901))
.await
+1 -1
Переглянути файл
@@ -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, PhpAlignment, PythonClassFacts, PythonFacts, PythonMethodFacts};
pub use syntax::{MethodBody, PythonClassFacts, PythonFacts, PythonMethodFacts};
/// Parsed form of `languages/<id>.toml`. Backend-only; the UI gets [`LanguageInfo`].
#[derive(Clone, Debug, Serialize, Deserialize)]
-2
Переглянути файл
@@ -10,7 +10,6 @@ mod inheritance;
pub(crate) mod lines;
mod literals;
mod outline;
mod php_align;
mod python_facts;
mod rst;
mod selection;
@@ -29,7 +28,6 @@ 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;
-368
Переглянути файл
@@ -1,368 +0,0 @@
//! 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<String> {
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<String> {
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<Entry>) -> Vec<Option<Entry>> {
let mut out: Vec<Option<Entry>> = Vec::new();
let mut previous_end: Option<usize> = 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<Entry>]) -> Vec<Vec<Entry>> {
let mut out: Vec<Vec<Entry>> = Vec::new();
let mut current: Vec<Entry> = 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<Entry> {
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<Entry> {
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<Entry> {
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<Syntax> = 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::<String>();
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,
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
"<?php\nreturn [\n 'name' => 'demo',\n 'description' => 'x',\n 'id' => 1,\n];\n",
);
check(
PAIRS,
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
"<?php\n$a = array(\n 1 => 'a',\n 1234 => 'b',\n);\n",
);
}
#[test]
fn nested_arrays_align_per_level_and_a_multi_line_value_ends_a_block() {
check(
PAIRS,
"<?php\n$config = [\n 'a' => 1,\n 'bbb' => 2,\n 'nested' => [\n 'x' => 1,\n 'yyyy' => 2,\n ],\n 'c' => 3,\n 'dd' => 4,\n];\n",
"<?php\n$config = [\n 'a' => 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,
"<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n\n 'ccc' => 3,\n // section\n 'dddd' => 4,\n 'e' => 5,\n 6,\n 'ff' => 7,\n];\n",
"<?php\n$a = [\n 'a' => 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,
"<?php\n$a = [\n 'a' => 1, // first\n 'bb' => 2, /* second */\n 'ccc' => 3,\n];\n",
"<?php\n$a = [\n 'a' => 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 [
"<?php\n$a = ['a' => 1, 'bbb' => 2];\n",
"<?php\n$a = [\n 'a' => 1, 'bbb' => 2,\n 'cc' => 3,\n];\n",
"<?php\n$a = ['a' => 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 = "<?php\n\
$s = 'a => 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 = <<<EOT\n 'a' => 1,\n 'bbb' => 2,\nEOT;\n";
let out = aligned(text, None, PAIRS);
assert_eq!(out, text);
}
#[test]
fn aligns_consecutive_assignments() {
check(
ASSIGNMENTS,
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
"<?php\n$y = foo($x);\n$i = foo($i);\n$result = $result . $y . $i;\n$this->name = 'n';\n$ref = &$y;\n",
);
}
#[test]
fn other_statements_blank_lines_and_multi_line_assignments_end_a_block() {
check(
ASSIGNMENTS,
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
"<?php\nfunction f() {\n $a = 1;\n $bb = 2;\n echo $a;\n $ccc = 3;\n $d = 4;\n\n $eeeee = 5;\n $f = 6;\n $g .= 'x';\n $hh = 7;\n $i = [\n 1,\n ];\n $jjj = 8;\n $k = 9;\n}\n",
);
}
#[test]
fn assignments_sharing_a_line_and_declarations_stay_as_they_are() {
let text = "<?php\n$a = 1; $bbb = 2;\n$cc = 3;\nclass C {\n public $x = 1;\n public $yyy = 2;\n const A = 1;\n const BBB = 2;\n}\n";
assert_eq!(aligned(text, None, ASSIGNMENTS), text);
}
#[test]
fn each_option_aligns_only_its_operator() {
let text = "<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n";
assert_eq!(
aligned(text, None, PAIRS),
"<?php\n$a = [\n 'a' => 1,\n 'bbb' => 2,\n];\n$x = 1;\n$yyy = 2;\n"
);
assert_eq!(
aligned(text, None, ASSIGNMENTS),
"<?php\n$a = [\n 'a' => 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 = "<?php\n$a = [\n 'a' => 1,\n 'bb' => 2,\n 'cccc' => 3,\n];\n";
assert_eq!(
aligned(text, Some((2, 3)), PAIRS),
"<?php\n$a = [\n 'a' => 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,
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
"<?php\n$a = [\n '名前' => 1,\n 'name' => 2,\n];\n",
);
}
#[test]
fn code_with_syntax_errors_is_aligned_only_where_it_parses() {
let text = "<?php\n$a = [\n 'a' => 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,
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
"<html>\n<?php\n$a = 1;\n$bbb = 2;\n?>\n<p>x = y</p>\n",
);
}
}
-8
Переглянути файл
@@ -435,14 +435,6 @@ impl ClientHandler {
.find_map(|base| section.split('.').try_fold(base, |v, key| v.get(key)))
.cloned()
.unwrap_or(Value::Null),
None if self.server.name == "eslint" => {
let mut settings = options.clone();
settings["workspaceFolder"] = json!({
"uri": crate::uri::path_to_uri(&self.server.root),
"name": self.server.root.file_name().map_or_else(|| "root".into(), |name| name.to_string_lossy().into_owned()),
});
settings
}
None => options.clone(),
})
.collect(),
+14 -44
Переглянути файл
@@ -1833,11 +1833,8 @@ impl LspManager {
/// the same class from its Java model instead, decompiled with method bodies and navigable.
/// Its documents belong to jdtls ([`Self::virtual_document`] records it).
async fn jdt_library_classes(&self, snap: &DocSnap, pos: Pos, locs: Vec<Location>) -> Vec<Location> {
let lib_class = |u: &str| {
(u.starts_with("jar:") && u.ends_with(".class"))
|| (u.starts_with("jdt://contents/") && u.contains(".class"))
};
if !locs.iter().any(|l| l.uri.as_deref().is_some_and(lib_class))
let jar_class = |l: &Location| l.uri.as_deref().is_some_and(|u| u.starts_with("jar:") && u.ends_with(".class"));
if !locs.iter().any(jar_class)
|| !self.servers.lock().iter().any(|s| s.name == jdtls::SERVER && s.running().is_some())
{
return locs;
@@ -1845,54 +1842,27 @@ impl LspManager {
let name = library_source::identifier_at(snap.text.line(pos.line as usize), pos.col).map(str::to_owned);
let mut out = Vec::with_capacity(locs.len());
for loc in locs {
let Some(original) = loc.uri.as_deref().filter(|u| lib_class(u)) else {
let entry = loc.uri.as_deref().filter(|_| jar_class(&loc)).and_then(library_source::parse);
let Some(entry) = entry else {
out.push(loc);
continue;
};
let jdt = original.starts_with("jdt:");
let uri = if !jdt {
let Some(entry) = library_source::parse(original) else {
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
let uri = match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
out.push(loc);
continue;
};
// The Kotlin server may name the jar by another path than jdtls (its own copy of a
// `system`-scope jar): its stub would be all the user gets, so take jdtls' only class
// of that name.
match self.archive_class(entry.jar, entry.entry, true).await {
Ok(uri) => uri,
Err(e) => {
tracing::info!("library class stays a stub: {}", e.message);
out.push(loc);
continue;
}
}
} else {
original.to_owned()
};
let doc = self.virtual_document(&uri).await.ok();
let range = match (&name, &doc) {
// jdtls' own class: its range is exact (overloads included) unless it maps a
// Lombok-generated member onto the annotation or class header, which doesn't
// name the member; only then look the declaration up in the source.
(Some(name), Some(doc)) if jdt => {
let line = doc.text.lines().nth(loc.range.start.line as usize).unwrap_or_default();
if library_source::identifier_at(line, loc.range.start.col) == Some(name.as_str()) {
loc.range
} else {
Some(library_source::declaration_range(&doc.text, name))
.filter(|r| *r != Range::default())
.unwrap_or(loc.range)
}
}
(Some(name), Some(doc)) => library_source::declaration_range(&doc.text, name),
_ if jdt => loc.range,
let range = match (&name, self.virtual_document(&uri).await) {
(Some(name), Ok(doc)) => library_source::declaration_range(&doc.text, name),
_ => Range::default(),
};
out.push(if jdt {
Location { range, ..loc }
} else {
Location { path: uri.clone().into(), range, uri: Some(uri) }
});
out.push(Location { path: uri.clone().into(), range, uri: Some(uri) });
}
out
}
+1 -62
Переглянути файл
@@ -180,7 +180,6 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
const KEYWORDS: [&str; 9] = ["fun", "class", "interface", "object", "val", "var", "typealias", "enum", "record"];
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let mut fallback = None;
let mut field = None;
let mut block_comment = false;
for (line_no, line) in text.lines().enumerate() {
let trimmed = line.trim_start();
@@ -224,40 +223,9 @@ pub(crate) fn declaration_range(text: &str, name: &str) -> Range {
if java_member && fallback.is_none() {
fallback = Some(range);
}
// A Java field (`private String name;`, `int age = 5;`): Lombok sources declare only
// the field, the accessors exist solely in the compiled class. A method of that name
// still wins, so a same-named local declared before it is not taken.
let java_field = matches!(line[end..].trim_start().chars().next(), Some(';' | '=' | ','))
&& !head.trim_end().ends_with('.')
&& !head.trim().is_empty()
&& !head.contains(['=', '('])
&& !words.iter().any(|w| matches!(*w, "return" | "throw" | "new" | "yield" | "assert"));
if java_field && field.is_none() {
field = Some(range);
}
}
}
if let Some(range) = fallback.or(field) {
return range;
}
accessor_field(name).map(|field| declaration_range(text, &field)).unwrap_or_default()
}
/// The field a Lombok/bean accessor stands for (`getName`/`setName` → `name`,
/// `isActive` → `active`); `None` for names that are not accessors.
fn accessor_field(name: &str) -> Option<String> {
let rest = ["get", "set", "is"]
.iter()
.find_map(|p| name.strip_prefix(p))
.filter(|r| r.chars().next().is_some_and(|c| c.is_uppercase()))?;
let mut chars = rest.chars();
let first = chars.next()?;
// Bean convention: `getURL` → `URL`, `getName` → `name`.
if rest.chars().nth(1).is_some_and(|c| c.is_uppercase()) {
Some(rest.to_owned())
} else {
Some(first.to_lowercase().collect::<String>() + chars.as_str())
}
fallback.unwrap_or_default()
}
/// The identifier around `col` (UTF-16) of `line`.
@@ -620,35 +588,6 @@ mod tests {
assert_eq!(declared_package("class A"), "");
}
#[test]
fn lombok_accessors_and_java_fields_locate_the_field() {
// Lombok sources declare only the field; the accessors exist only in the
// compiled class, so navigation must fall back to the underlying field.
let lombok = "package example.entity;\n\nimport lombok.Getter;\nimport lombok.Setter;\n\n@Getter\n@Setter\npublic class UserEntity {\n private String name;\n private int age;\n private boolean active;\n}\n";
for (name, line, col) in [
("getName", 8, 19),
("setName", 8, 19),
("name", 8, 19),
("getAge", 9, 16),
("isActive", 10, 20),
("active", 10, 20),
] {
let r = declaration_range(lombok, name);
assert_eq!((r.start.line, r.start.col), (line, col), "{name}");
}
// An explicitly declared accessor still wins over the field.
let plain = "class Plain {\n private String name;\n public String getName() { return name; }\n}\n";
assert_eq!(declaration_range(plain, "getName").start.line, 2);
// Initialized fields count; a method beats a same-named local declared before it.
let init = "class Init {\n private int count = 0;\n void a() {\n int size = 1;\n }\n int size() { return 2; }\n}\n";
assert_eq!(declaration_range(init, "getCount").start.line, 1);
assert_eq!(declaration_range(init, "size").start.line, 5);
// Bean convention keeps acronyms; non-accessors are not remapped.
assert_eq!(accessor_field("getURL").as_deref(), Some("URL"));
assert_eq!(accessor_field("getter"), None);
assert_eq!(declaration_range(lombok, "missing"), Range::default());
}
#[test]
fn locates_declarations_in_kotlin_and_java_sources() {
let at = |text: &str, name: &str| {
-29
Переглянути файл
@@ -2568,35 +2568,6 @@ async fn configuration_answer_resyncs_open_documents_of_opted_in_servers() {
assert_eq!(s.launches.load(Ordering::SeqCst), 1);
}
#[tokio::test(flavor = "multi_thread")]
async fn eslint_configuration_includes_workspace_folder() {
let h = harness_configured("mock", "mk", &[("eslint", incremental_caps()), ("mock", incremental_caps())], |cfg| {
if cfg.name == "eslint" {
cfg.settings = Some(json!({ "workingDirectory": { "mode": "auto" } }));
}
});
h.open("a.mk", "x");
h.wait_status("eslint", ServerStatus::Ready).await;
h.wait_status("mock", ServerStatus::Ready).await;
let items = json!({ "items": [{ "section": "" }] });
let eslint: Value =
h.launcher.state("eslint").peer().request("workspace/configuration", items.clone(), None).await.unwrap();
assert_eq!(
eslint,
json!([{
"flag": true,
"nested": { "deep": 1 },
"workingDirectory": { "mode": "auto" },
"workspaceFolder": {
"uri": uri_of(&h.root),
"name": h.root.file_name().unwrap().to_string_lossy(),
},
}])
);
let other: Value = h.launcher.state("mock").peer().request("workspace/configuration", items, None).await.unwrap();
assert_eq!(other, json!([{ "flag": true, "nested": { "deep": 1 } }]));
}
#[tokio::test(flavor = "multi_thread")]
async fn settings_changes_reach_servers_without_restarts() {
let h = harness(&[("mock", incremental_caps()), ("extra", incremental_caps())]);
Бінарний файл не відображається.
+1 -1
Переглянути файл
@@ -1 +1 @@
b24fb8d5161006104698fb07a43432601b4f16fdc4a34cc70058cbef7e973066
1056d650117bc2216ac518aa26b27cf898f58db62369ae285b9d8925ada74dff
+3 -9
Переглянути файл
@@ -181,13 +181,9 @@ impl commands::Guest for Misbehave {
};
let child = process::start(&cmd, None)?;
// CPU work per step (loop iterations), for fuel budget tests.
let arg = arg.as_deref().unwrap_or("");
let report = !arg.starts_with("quiet:");
let work: u64 = arg.strip_prefix("quiet:").unwrap_or(arg).parse().unwrap_or(0);
let work: u64 = arg.as_deref().and_then(|a| a.parse().ok()).unwrap_or(0);
for step in 0..25 {
if report {
task.report(step, Some(25), Some("waiting"));
}
task.report(step, Some(25), Some("waiting"));
let mut x: u64 = 0;
for _ in 0..work {
x = std::hint::black_box(x.wrapping_add(1));
@@ -199,9 +195,7 @@ impl commands::Guest for Misbehave {
// Let it finish on its own: no kill, no slow teardown.
child.close_stdin()?;
let _ = child.wait(5_000);
if report {
task.report(25, Some(25), Some("done"));
}
task.report(25, Some(25), Some("done"));
Ok(Some("still here".into()))
}
// `editor.write` is not granted: an error, not a trap.
-29
Переглянути файл
@@ -537,16 +537,6 @@ pub fn configure_gradle_runtime(cfg: &mut LanguageServerConfig, root: &Path, bui
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"import": {"gradle": gradle}}}));
}
/// Settings › Build Tools › Maven › Automatically download sources → jdtls
/// `java.maven.downloadSources`.
pub fn configure_maven_sources(cfg: &mut LanguageServerConfig, s: &Settings) {
if cfg.name != "jdtls" {
return;
}
let download = s.languages.java.maven.download_sources;
merge(cfg.settings.get_or_insert_with(|| json!({})), json!({"java": {"maven": {"downloadSources": download}}}));
}
/// Maven options from settings, placed before the goals: `-s <settings.xml>`,
/// `-t <toolchains.xml>`, `-Dmaven.repo.local=<dir>`, `-T <count>` and `-P <profiles>`.
pub fn maven_options(root: &Path, s: &Settings) -> Vec<String> {
@@ -2360,25 +2350,6 @@ mod maven_linkage_tests {
assert_eq!(default_maven_repository_in(home), Some(home.join(".m2/repository")));
}
#[test]
fn maven_sources_download_follows_the_setting() {
let mut settings = Settings::default();
let mut cfg = custom_server("jdtls", &LanguageServerSettings::default());
cfg.settings = Some(json!({"java": {"maven": {"downloadSources": true, "updateSnapshots": false}}}));
configure_maven_sources(&mut cfg, &settings);
assert_eq!(
cfg.settings,
Some(json!({"java": {"maven": {"downloadSources": false, "updateSnapshots": false}}}))
);
settings.languages.java.maven.download_sources = true;
configure_maven_sources(&mut cfg, &settings);
assert_eq!(cfg.settings.unwrap()["java"]["maven"]["downloadSources"], json!(true));
let mut other = custom_server("kotlin", &LanguageServerSettings::default());
configure_maven_sources(&mut other, &settings);
assert_eq!(other.settings, None);
}
#[test]
fn gradle_import_runs_the_gradle_the_ide_builds_with() {
let root = Path::new("/p");
+3 -93
Переглянути файл
@@ -21,63 +21,10 @@ fn root(data_dir: &Path) -> PathBuf {
data_dir.join("lsp").join("jdtls")
}
/// jdtls' temporary folder, inside its workspace.
const TEMP_DIR: &str = ".tmp";
fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> {
cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new)
}
fn temp_arg(workspace: &Path) -> String {
format!("-Djava.io.tmpdir={}", workspace.join(TEMP_DIR).to_string_lossy())
}
/// Gives jdtls a temporary folder inside a workspace of ours (`<workspace>/.tmp`) unless the
/// user's JVM arguments choose one. JDT APT copies a project's annotation processor jars into a
/// new `jdt-apt-*` folder for each processor class loader and deletes it only when the JVM exits
/// normally — never on Windows, where the jars are still open then — so in the system temp
/// folder they pile up with every start; [`mark_used`] empties this one before each start.
pub fn use_own_temp(cfg: &mut LanguageServerConfig, data_dir: &Path) {
if cfg.name != "jdtls" || cfg.args.iter().any(|a| a.contains("-Djava.io.tmpdir=")) {
return;
}
let Some(arg) = workspace(cfg).filter(|w| w.starts_with(root(data_dir))).map(temp_arg) else { return };
// Launched directly, JVM options go before `-jar`; through the script, as `--jvm-arg=`.
match cfg.args.iter().position(|a| a == "-jar") {
Some(jar) => cfg.args.insert(jar, arg),
None => cfg.args.push(format!("--jvm-arg={arg}")),
}
}
/// Empties the temporary folder [`use_own_temp`] gave the workspace. Best effort: files a server
/// still has open on Windows stay until a later start.
fn clear_temp(cfg: &LanguageServerConfig, workspace: &Path) {
let arg = temp_arg(workspace);
if !cfg.args.iter().any(|a| a.strip_prefix("--jvm-arg=").unwrap_or(a) == arg) {
return;
}
let temp = workspace.join(TEMP_DIR);
for entry in std::fs::read_dir(&temp).into_iter().flatten().flatten() {
let path = entry.path();
let removed = if entry.file_type().is_ok_and(|t| t.is_dir()) {
std::fs::remove_dir_all(&path)
} else {
std::fs::remove_file(&path)
};
if let Err(e) = removed {
tracing::debug!("jdtls: cannot remove temporary {}: {e}", path.display());
}
}
if let Err(e) = std::fs::create_dir_all(&temp) {
tracing::warn!("jdtls: cannot create its temporary folder {}: {e}", temp.display());
}
}
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder), and empties
/// the workspace's temporary folder.
/// Records that jdtls is starting on the workspace of `cfg` (its `-data` folder).
pub fn mark_used(cfg: &LanguageServerConfig) {
let Some(dir) = workspace(cfg) else { return };
clear_temp(cfg, dir);
let Some(dir) = cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)) else { return };
let dir = Path::new(dir);
if let Err(e) = std::fs::create_dir_all(dir).and_then(|()| {
let marker = std::fs::File::create(dir.join(USED_MARKER))?;
marker.set_modified(SystemTime::now())
@@ -195,43 +142,6 @@ mod tests {
assert!(ws.exists());
}
#[test]
fn jdtls_keeps_its_temporary_files_in_its_workspace_and_starts_with_none() {
let tmp = tempfile::tempdir().unwrap();
let ws = root(tmp.path()).join("p");
let temp = format!("-Djava.io.tmpdir={}", ws.join(TEMP_DIR).to_string_lossy());
// Through the launcher script.
let mut script = cfg(&ws);
use_own_temp(&mut script, tmp.path());
assert_eq!(script.args.last(), Some(&format!("--jvm-arg={temp}")));
// Launched directly: a JVM option, before `-jar`.
let mut direct = cfg(&ws);
direct.args.splice(0..0, ["-Xmx2G".to_owned(), "-jar".to_owned(), "launcher.jar".to_owned()]);
use_own_temp(&mut direct, tmp.path());
assert_eq!(direct.args[..3], ["-Xmx2G".to_owned(), temp.clone(), "-jar".to_owned()]);
let stale = ws.join(TEMP_DIR).join("jdt-apt-1");
std::fs::create_dir_all(&stale).unwrap();
std::fs::write(stale.join("0_processor.jar"), "").unwrap();
std::fs::write(ws.join(TEMP_DIR).join("file.tmp"), "").unwrap();
mark_used(&direct);
assert!(ws.join(TEMP_DIR).is_dir());
assert_eq!(std::fs::read_dir(ws.join(TEMP_DIR)).unwrap().count(), 0);
// The user's own choice, and a workspace that is not ours, are left alone.
let mut own = cfg(&ws);
own.args.push("--jvm-arg=-Djava.io.tmpdir=/elsewhere".into());
use_own_temp(&mut own, tmp.path());
assert_eq!(own.args.iter().filter(|a| a.contains("java.io.tmpdir")).count(), 1);
let mut theirs = cfg(&tmp.path().join("their-workspace"));
use_own_temp(&mut theirs, tmp.path());
assert!(!theirs.args.iter().any(|a| a.contains("java.io.tmpdir")));
std::fs::create_dir_all(ws.join(TEMP_DIR).join("kept")).unwrap();
mark_used(&cfg(&ws));
assert!(ws.join(TEMP_DIR).join("kept").exists());
}
#[cfg(unix)]
#[test]
fn a_workspace_from_before_markers_is_judged_by_its_folders_and_log() {
+1 -21
Переглянути файл
@@ -86,25 +86,5 @@ fn excluded_subtrees(c: &mut Criterion) {
group.finish();
}
// Lockfile-sized files with a hit on every line, one per folder so every walker
// thread is inside its own dense file when the 10 000-match default limit is reached.
fn dense_files(c: &mut Criterion) {
let dir = tempfile::tempdir().unwrap();
for module in 0..24 {
let sub = dir.path().join(format!("packages/p{module}"));
std::fs::create_dir_all(&sub).unwrap();
let mut text = String::with_capacity(2 << 20);
for i in 0..40_000u32 {
text.push_str(&format!(" \"version\": \"{}.{}.{module}\",\n", i / 100, i % 100));
}
std::fs::write(sub.join("package-lock.json"), text).unwrap();
}
let q = query("version", false);
let mut group = c.benchmark_group("search_dense_files");
group.sample_size(15);
group.bench_function("24x40k_limit", |b| b.iter(|| black_box(run(dir.path(), &q))));
group.finish();
}
criterion_group!(benches, bench, excluded_subtrees, dense_files);
criterion_group!(benches, bench, excluded_subtrees);
criterion_main!(benches);
+20 -109
Переглянути файл
@@ -22,9 +22,6 @@ pub(crate) const DEFAULT_MAX_MATCHES: u32 = 10_000;
/// How many matched lines a sink handles between cancellation-token checks
/// (reads from disk check on every buffer refill).
const CANCEL_CHECK_LINES: u32 = 256;
/// How many matches a file keeps before claiming them from the shared budget: each file
/// searched in parallel holds about this many unclaimed matches at most, not up to the whole budget.
const CLAIM_BATCH: u32 = 64;
pub(crate) struct Request<'a> {
pub root: &'a Path,
@@ -90,11 +87,6 @@ impl Control<'_> {
}
}
}
/// Returns matches claimed for a file whose matches are then dropped.
fn release(&self, n: u32) {
self.matches.fetch_sub(n, Relaxed);
}
}
struct Ctx<'a> {
@@ -330,16 +322,24 @@ impl Ctx<'_> {
None => self.search_disk(path, matcher, searcher, &mut sink),
},
};
if let Err(err) = result
&& !self.ctl.stopped()
{
tracing::debug!("search {}: {err}", path.display());
if let Err(err) = result {
if !self.ctl.stopped() {
tracing::debug!("search {}: {err}", path.display());
}
if sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
return;
}
}
if sink.binary || sink.lines.is_empty() || self.ctl.cancelled.load(Relaxed) {
self.ctl.release(sink.claimed);
return;
}
sink.settle();
let found = u32::try_from(sink.count).unwrap_or(u32::MAX);
let granted = self.ctl.reserve(found);
if granted < found {
self.ctl.limit_hit.store(true, Relaxed);
self.ctl.stop.store(true, Relaxed);
truncate(&mut sink.lines, granted as usize);
}
if sink.lines.is_empty() {
return;
}
@@ -364,17 +364,14 @@ impl Ctx<'_> {
} else {
!reader.is_utf8()
};
// A stopped search needs the decoded text only to fill what the byte search claimed.
if !decode || (self.ctl.stopped() && sink.claimed == 0) {
if !decode || self.ctl.stopped() {
return result;
}
let Some(text) = (self.text.decode)(path, &std::fs::read(path)?) else {
sink.binary = true;
return Ok(());
};
let claimed = sink.claimed;
*sink = FileSink::new(matcher, &self.ctl, None);
sink.claimed = claimed;
searcher.search_slice(matcher, text.as_bytes(), sink)
}
}
@@ -392,11 +389,8 @@ struct FileSink<'a> {
matcher: &'a RegexMatcher,
ctl: &'a Control<'a>,
lines: Vec<LineMatch>,
/// Match ranges kept so far.
count: u32,
/// Matches claimed from the shared budget: up to `count`, or more while a decoded
/// file is searched again under the claim of its byte search.
claimed: u32,
/// Match ranges collected so far.
count: usize,
binary: bool,
ticks: u32,
/// Scratch buffers reused across lines.
@@ -417,7 +411,6 @@ impl<'a> FileSink<'a> {
ctl,
lines: Vec::new(),
count: 0,
claimed: 0,
binary: false,
ticks: 0,
found: Vec::new(),
@@ -425,36 +418,6 @@ impl<'a> FileSink<'a> {
context,
}
}
/// Claims the matches kept since the last claim. When the budget cannot take them
/// all, keeps the ones it can, marks the limit hit and returns false.
fn claim(&mut self) -> bool {
if self.count <= self.claimed {
return true;
}
let unclaimed = self.count - self.claimed;
let granted = self.ctl.reserve(unclaimed);
self.claimed += granted;
if granted == unclaimed {
return true;
}
self.ctl.limit_hit.store(true, Relaxed);
self.ctl.stop.store(true, Relaxed);
truncate(&mut self.lines, self.claimed as usize);
self.count = self.claimed;
false
}
/// Makes the claim match the matches kept once the file is done: claims the rest, or
/// gives back the part of a byte search's claim the decoded text did not use.
fn settle(&mut self) {
if self.count < self.claimed {
self.ctl.release(self.claimed - self.count);
self.claimed = self.count;
} else {
self.claim();
}
}
}
/// Kind of the comment or string literal containing byte `pos` (`literals` sorted).
@@ -468,9 +431,7 @@ impl Sink for FileSink<'_> {
fn matched(&mut self, _searcher: &Searcher, m: &SinkMatch<'_>) -> Result<bool, io::Error> {
self.ticks += 1;
let stop = self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop());
// Unless cancelled, a decoded file still fills the claim its byte search took.
if stop && (self.count >= self.claimed || self.ctl.cancelled.load(Relaxed)) {
if self.ctl.stopped() || (self.ticks.is_multiple_of(CANCEL_CHECK_LINES) && self.ctl.should_stop()) {
return Ok(false);
}
let buffer = m.buffer();
@@ -514,7 +475,7 @@ impl Sink for FileSink<'_> {
ranges.push((a - line_start, b - line_start));
}
if !ranges.is_empty() {
self.count = self.count.saturating_add(u32::try_from(ranges.len()).unwrap_or(u32::MAX));
self.count += ranges.len();
let line_no = u32::try_from(line_no).unwrap_or(u32::MAX);
self.lines.push(line_match(line_no, &block[line_start..content_end], &ranges));
}
@@ -524,8 +485,7 @@ impl Sink for FileSink<'_> {
self.found = found;
self.ranges = ranges;
// One match beyond the remaining budget is enough to know the limit is hit.
let unclaimed = self.count.saturating_sub(self.claimed);
Ok(if unclaimed >= CLAIM_BATCH || unclaimed > self.ctl.remaining() { self.claim() } else { true })
Ok(self.count <= self.ctl.remaining() as usize)
}
fn binary_data(&mut self, _searcher: &Searcher, _offset: u64) -> Result<bool, io::Error> {
@@ -682,52 +642,3 @@ mod walk_tests {
assert!(seen.lock().unwrap().is_empty());
}
}
#[cfg(test)]
mod budget_tests {
use super::*;
fn control(cancel: &CancellationToken, max: u32) -> Control<'_> {
Control {
cancel,
stop: AtomicBool::new(false),
cancelled: AtomicBool::new(false),
limit_hit: AtomicBool::new(false),
matches: AtomicU32::new(0),
files: AtomicU32::new(0),
max,
}
}
/// Searches `lines` matching lines without finishing the file, like a walker thread mid-file.
fn scan<'a>(ctl: &'a Control<'a>, matcher: &'a RegexMatcher, lines: usize) -> FileSink<'a> {
let mut sink = FileSink::new(matcher, ctl, None);
let mut searcher = SearcherBuilder::new().line_number(true).build();
searcher.search_slice(matcher, "x\n".repeat(lines).as_bytes(), &mut sink).unwrap();
sink
}
#[test]
fn files_in_flight_never_hold_more_matches_than_the_budget() {
let cancel = CancellationToken::new();
let ctl = control(&cancel, 100);
let matcher = RegexMatcher::new("x").unwrap();
let (first, second) = (scan(&ctl, &matcher, 150), scan(&ctl, &matcher, 150));
assert_eq!((first.lines.len(), second.lines.len()), (100, 0));
assert_eq!(ctl.matches.load(Relaxed), 100);
assert!(ctl.limit_hit.load(Relaxed));
}
#[test]
fn unclaimed_matches_of_a_file_in_flight_stay_within_the_budget() {
let cancel = CancellationToken::new();
let ctl = control(&cancel, 1000);
let matcher = RegexMatcher::new("x").unwrap();
let mut first = scan(&ctl, &matcher, 40);
let second = scan(&ctl, &matcher, 2000);
assert_eq!((first.lines.len(), second.lines.len()), (40, 1000));
assert!(!first.claim());
assert_eq!((first.lines.len(), ctl.matches.load(Relaxed)), (0, 1000));
assert!(ctl.limit_hit.load(Relaxed));
}
}
-44
Переглянути файл
@@ -314,25 +314,6 @@ fn match_limit() {
assert_eq!(summary.matches, 14);
}
#[test]
fn match_limit_across_parallel_files() {
// One file per folder, so several walker threads search at once.
let content = "x\n".repeat(50);
let names: Vec<String> = (0..16).map(|i| format!("m{i}/a.txt")).collect();
let files: Vec<(&str, &[u8])> = names.iter().map(|n| (n.as_str(), content.as_bytes())).collect();
let p = project(&files);
for _ in 0..20 {
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 800, ..query("x") });
assert!(!summary.limit_hit);
assert_eq!((total(&views), summary.matches, summary.files), (800, 800, 16));
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 799, ..query("x") });
assert!(summary.limit_hit);
assert_eq!((total(&views), summary.matches), (799, 799));
assert_eq!(summary.files as usize, views.len());
}
}
#[test]
fn default_limit_is_ten_thousand() {
let content = "a\n".repeat(10_050);
@@ -794,31 +775,6 @@ fn non_utf8_files_are_searched_as_text() {
assert_eq!(views[0].matches[0].ranges, [(13, 20), (21, 28), (29, 36)]);
}
#[test]
fn dropped_matches_give_back_their_budget() {
// Matches claimed before a late NUL (binary) or late GBK bytes (searched again as text).
let head = b"needle\n".repeat(100);
let filler = b"a".repeat(200_000);
let binary = [head.as_slice(), &filler, b"\0\n"].concat();
let late_gbk = [head.as_slice(), &filler, b"\n", &gbk("中文\n")].concat();
// One project each: a thread's searcher keeps its grown buffer for the next file.
for (file, bytes, found) in [("bin.dat", binary, 0), ("late.txt", late_gbk, 100)] {
let p = project(&[(file, &bytes)]);
let (views, summary) = run(p.path(), &query("needle"));
assert_eq!((total(&views), summary.matches), (found, found as u32), "{file}");
assert!(!summary.limit_hit);
}
}
#[test]
fn non_utf8_files_past_the_limit_show_decoded_text() {
let p = project(&[("a.txt", &gbk(&"x 中文\n".repeat(200)))]);
let (views, summary) = run(p.path(), &SearchQuery { max_matches: 100, ..query("x") });
assert!(summary.limit_hit);
assert_eq!((total(&views), summary.matches), (100, 100));
assert!(views[0].matches.iter().all(|m| m.text == "x 中文"));
}
#[test]
fn non_utf8_files_use_the_given_decoder() {
// Text too short to detect reliably decodes with the configured encoding.
+6 -12
Переглянути файл
@@ -1,15 +1,14 @@
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document
//! (and a 5 MB one where whole-document copies would show).
//! `cargo bench -p ide-text`: change sets and coordinate conversion on a 1 MB document.
use criterion::{BatchSize, Criterion, black_box, criterion_group, criterion_main};
use ide_core::{ChangeSet, Pos, TextChange};
use ide_text::Document;
/// ~`bytes` of code-like text with some non-ASCII content.
fn sample_text(bytes: usize) -> String {
let mut s = String::with_capacity(bytes);
/// ~1 MB of code-like text with some non-ASCII content.
fn sample_text() -> String {
let mut s = String::with_capacity(1 << 20);
let mut i = 0u32;
while s.len() < bytes {
while s.len() < 1 << 20 {
s.push_str(&format!(" let value_{i} = compute(\"héllo 😀\", {i}) + other_{i};\n"));
i += 1;
}
@@ -48,7 +47,7 @@ fn change_set(doc: &Document, rng: &mut Lcg, n: usize) -> ChangeSet {
}
fn bench(c: &mut Criterion) {
let text = sample_text(1 << 20);
let text = sample_text();
c.bench_function("text/open_1mb", |b| b.iter(|| Document::new(black_box(&text))));
let base = Document::new(&text);
@@ -78,11 +77,6 @@ fn bench(c: &mut Criterion) {
c.bench_function("text/diff_two_edits_1mb", |b| b.iter(|| base.diff(black_box(&two_edits))));
let every_line = text.replace("compute", "calculate");
c.bench_function("text/diff_every_line_1mb", |b| b.iter(|| base.diff(black_box(&every_line))));
let large_text = sample_text(5 << 20);
let large = Document::new(&large_text);
let one_edit = large_text.replacen("value_40000 ", "renamed_40000 ", 1);
assert_ne!(one_edit, large_text);
c.bench_function("text/diff_one_edit_5mb", |b| b.iter(|| large.diff(black_box(&one_edit))));
c.bench_function("text/offset_to_pos_round_trip", |b| {
let mut rng = Lcg(3);
let len = base.len_utf16();
+4 -112
Переглянути файл
@@ -93,54 +93,6 @@ fn common_ends(a: &str, b: &str) -> (usize, usize) {
(prefix, suffix)
}
/// [`common_ends`] of the rope's text and `b`, walking the rope's chunks instead
/// of copying it: whole chunks compare as slices, bytes only around the mismatch.
fn rope_common_ends(rope: &ropey::Rope, b: &str) -> (usize, usize) {
let bb = b.as_bytes();
let mut prefix = 0;
for chunk in rope.chunks() {
let n = common_prefix_len(chunk.as_bytes(), &bb[prefix..]);
prefix += n;
if n < chunk.len() {
break;
}
}
prefix = rope.char_to_byte(rope.byte_to_char(prefix));
let len = rope.len_bytes();
let limit = len.min(bb.len()) - prefix;
let mut suffix = 0;
let mut chunks = rope.chunks_at_byte(len).0.reversed();
while suffix < limit {
let Some(chunk) = chunks.next() else { break };
let n = common_suffix_len(chunk.as_bytes(), &bb[..bb.len() - suffix]).min(limit - suffix);
suffix += n;
if n < chunk.len() {
break;
}
}
let ch = rope.byte_to_char(len - suffix);
if rope.char_to_byte(ch) < len - suffix {
suffix = len - rope.char_to_byte(ch + 1);
}
(prefix, suffix)
}
fn common_prefix_len(a: &[u8], b: &[u8]) -> usize {
let n = a.len().min(b.len());
if a[..n] == b[..n] {
return n;
}
a.iter().zip(b).take_while(|(x, y)| x == y).count()
}
fn common_suffix_len(a: &[u8], b: &[u8]) -> usize {
let n = a.len().min(b.len());
if a[a.len() - n..] == b[b.len() - n..] {
return n;
}
a.iter().rev().zip(b.iter().rev()).take_while(|(x, y)| x == y).count()
}
/// Byte offset of each line, then the total length.
fn line_starts(lines: &[&str]) -> Vec<usize> {
let mut at = 0;
@@ -444,8 +396,9 @@ impl Document {
/// Past `deadline` the regions get coarser, never wrong.
fn diff_until(&self, text: &str, deadline: Instant) -> ChangeSet {
let new = normalize_line_endings(text);
let (prefix, suffix) = rope_common_ends(&self.rope, &new);
let old_rest = String::from(self.rope.byte_slice(prefix..self.rope.len_bytes() - suffix));
let old = self.rope.to_string();
let (prefix, suffix) = common_ends(&old, &new);
let old_rest = &old[prefix..old.len() - suffix];
let new_rest = &new[prefix..new.len() - suffix];
let old_lines: Vec<&str> = old_rest.split_inclusive('\n').collect();
@@ -454,7 +407,7 @@ impl Document {
let new_starts = line_starts(&new_lines);
let mut changes = Vec::new();
let mut utf16_at = self.byte_to_offset(prefix);
let mut utf16_at = utf16_len(&old[..prefix]);
let mut old_at = 0;
let mut region: Option<(LineRange, LineRange)> = None;
let ops =
@@ -757,67 +710,6 @@ mod tests {
assert_eq!(set.changes, vec![tc(3, 6, "ONE"), tc(15, 18, "TWO")]);
}
/// The rope scan must trim exactly what `common_ends` trims on the copied text.
fn assert_rope_ends(old: &str, new: &str) {
let doc = Document::new(old);
let (prefix, suffix) = rope_common_ends(&doc.rope, new);
assert_eq!((prefix, suffix), common_ends(old, new), "{old:?} -> {new:?}");
assert_eq!(doc.byte_to_offset(prefix), utf16_len(&old[..prefix]));
}
#[test]
fn rope_common_ends_matches_common_ends() {
let unit = "héllo 😀 wörld, ©\n";
let base = unit.repeat(400);
assert!(Document::new(&base).rope.chunks().count() > 4, "spans several chunks");
for (old, new) in [("", ""), ("", "abc"), ("abc", ""), ("é", "è"), ("😀", "😁"), ("é", "©")] {
assert_rope_ends(old, new);
}
assert_rope_ends(&base, &base);
assert_rope_ends(&base, "");
assert_rope_ends("", &base);
assert_rope_ends(&base, &format!("{base}tail"));
assert_rope_ends(&format!("{base}tail"), &base);
assert_rope_ends(&base, &base[unit.len()..]);
assert_rope_ends(&"a".repeat(5000), &"a".repeat(4999));
assert_rope_ends(&"ab".repeat(3000), &"ab".repeat(3001));
assert_rope_ends(&"😀".repeat(2000), &"😀".repeat(1999));
let boundaries: Vec<usize> = base.char_indices().map(|(i, _)| i).step_by(7).collect();
for at in boundaries {
let c = base[at..].chars().next().unwrap();
let rest = &base[at + c.len_utf8()..];
let swapped = match c {
'é' => 'è', // same lead byte
'😀' => '😁', // differs in the last byte only
'©' => 'é', // same trailing byte
_ => 'X',
};
let swap = format!("{}{swapped}{rest}", &base[..at]);
assert_rope_ends(&base, &swap);
// Deleting a char further on stops the suffix scan far from the prefix.
let mut far = at + (swap.len() - at) / 2;
while !swap.is_char_boundary(far) {
far += 1;
}
let gone = swap[far..].chars().next().unwrap().len_utf8();
assert_rope_ends(&base, &format!("{}{}", &swap[..far], &swap[far + gone..]));
assert_rope_ends(&base, &format!("{}{rest}", &base[..at]));
assert_rope_ends(&base, &format!("{}é{c}{rest}", &base[..at]));
}
}
#[test]
fn diff_of_a_large_document_counts_utf16_and_normalizes_crlf() {
let old = "😀 héllo\n".repeat(2000);
let at = old.len() / 2;
let new = format!("{}X{}", &old[..at], &old[at..]);
let doc = Document::new(&old);
let expected = vec![tc(utf16_len(&old[..at]), utf16_len(&old[..at]), "X")];
assert_eq!(doc.diff(&new).changes, expected);
assert_eq!(doc.diff(&new.replace('\n', "\r\n")).changes, expected);
assert!(doc.diff(&old.replace('\n', "\r\n")).changes.is_empty());
}
#[test]
fn diff_past_its_deadline_is_coarser_but_still_correct() {
let old = numbered_lines(5000);
+5 -44
Переглянути файл
@@ -1,8 +1,8 @@
use ide_core::{IdeError, IdeResult};
use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode};
use std::collections::{HashMap, HashSet};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
@@ -42,9 +42,6 @@ struct Root {
dir: PathBuf,
port: u16,
serves: Serves,
/// Files handed out by [`WebServer::page_url_for`], as requested. They stay here until
/// the app quits, even if the file stops being HTML: only its content type depends on it.
pages: Mutex<HashSet<PathBuf>>,
}
/// What of its directory a root serves.
@@ -90,18 +87,6 @@ impl WebServer {
/// A project that is the home folder, or holds it, is no boundary to serve whole: its
/// files are served like files outside a project.
pub async fn url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
Ok(self.locate(root, file).await?.1)
}
/// [`Self::url_for`] of a file that is an HTML page whatever its name (Settings › File
/// Types): it is served as HTML from now on.
pub async fn page_url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult<String> {
let (served, url) = self.locate(root, file).await?;
served.pages.lock().unwrap_or_else(PoisonError::into_inner).insert(file.to_path_buf());
Ok(url)
}
async fn locate(&self, root: Option<&Path>, file: &Path) -> IdeResult<(Arc<Root>, String)> {
let (base, serves) = match root {
Some(r) if file.starts_with(r) && file != r && self.holds_home(r).await != Some(true) => (r, Serves::All),
_ => {
@@ -117,7 +102,7 @@ impl WebServer {
url.push('/');
url.push_str(&enc(&c.as_os_str().to_string_lossy()));
}
Ok((root, url))
Ok(url)
}
/// Whether `dir` is the home folder or lies above it; `None` when that cannot be told.
@@ -168,7 +153,6 @@ impl WebServer {
dir: dir.to_path_buf(),
port,
serves,
pages: Mutex::default(),
});
tokio::spawn(accept(listener, root.clone()));
tracing::info!("built-in web server on 127.0.0.1:{} for {}", root.port, dir.display());
@@ -336,9 +320,7 @@ async fn resolve(root: &Root, target: &str) -> Response {
_ => NOT_FOUND,
};
}
let page = root.pages.lock().unwrap_or_else(PoisonError::into_inner).contains(&file);
let mime = if page { HTML } else { content_type(&file) };
Response::File { path: real, len: meta.len(), mime }
Response::File { path: real, len: meta.len(), mime: content_type(&file) }
}
/// `path` with every symlink resolved, if `root` serves it: it lies inside `real_root`
@@ -361,12 +343,10 @@ fn dec(s: &str) -> Option<String> {
percent_decode_str(s).decode_utf8().ok().map(|s| s.into_owned())
}
const HTML: &str = "text/html; charset=utf-8";
fn content_type(path: &Path) -> &'static str {
let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
match ext.as_str() {
"html" | "htm" | "xhtml" => HTML,
"html" | "htm" | "xhtml" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" | "mjs" | "cjs" => "text/javascript; charset=utf-8",
"json" | "map" | "webmanifest" => "application/json; charset=utf-8",
@@ -415,25 +395,6 @@ mod tests {
out
}
#[tokio::test]
async fn a_page_is_html_whatever_its_name() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("site");
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("page.foo"), "<h1>hi</h1>").unwrap();
std::fs::write(root.join("other.foo"), "<h1>no</h1>").unwrap();
let server = server();
let plain = server.url_for(Some(&root), &root.join("page.foo")).await.unwrap();
assert!(get(&plain, None).await.contains("application/octet-stream"));
let page = server.page_url_for(Some(&root), &root.join("page.foo")).await.unwrap();
assert_eq!(page, plain);
assert!(get(&page, None).await.contains("Content-Type: text/html"));
let other = page.replace("page.foo", "other.foo");
assert!(get(&other, None).await.contains("application/octet-stream"), "only the named file");
}
#[tokio::test]
async fn serves_project_files() {
let dir = tempfile::tempdir().unwrap();
+2 -30
Переглянути файл
@@ -172,9 +172,6 @@ struct DocState {
/// Disk state we last loaded or wrote; changes matching it are our own.
disk_mtime: f64,
disk_len: u64,
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
/// alone until the user saves explicitly or the buffer is reloaded.
disk_conflict: bool,
closed: bool,
/// URI of a virtual document (no file behind it).
uri: Option<String>,
@@ -267,7 +264,6 @@ impl Documents {
st.native_to_ascii = enabled;
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
Ok(())
});
if let Err(e) = result {
@@ -461,7 +457,6 @@ impl Documents {
encoding_chosen: false,
disk_mtime: loaded.mtime_ms,
disk_len: disk_len(path),
disk_conflict: false,
closed: false,
uri: None,
};
@@ -534,7 +529,6 @@ impl Documents {
encoding_chosen: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
closed: false,
uri: Some(uri.to_owned()),
};
@@ -593,7 +587,6 @@ impl Documents {
encoding_chosen: false,
disk_mtime: 0.0,
disk_len: 0,
disk_conflict: false,
closed: false,
uri: Some(key.to_string_lossy().into_owned()),
};
@@ -660,8 +653,6 @@ impl Documents {
};
let mut st = slot.lock();
st.closed = true;
// A buffer closed with changes (Don't Save) has nothing left to save.
self.set_dirty(doc, &mut st, false);
if st.observed {
for o in self.observers() {
o.closed(doc, &st.path);
@@ -819,22 +810,7 @@ impl Documents {
/// Writes the document with its original encoding, BOM and line ending.
/// A clean document is not rewritten.
pub fn save(&self, doc: DocId) -> IdeResult<()> {
self.with_doc(doc, |st| self.write(doc, st))
}
/// An automatic save (switching tabs, the window losing focus): `false` when the file changed
/// on disk after this buffer was edited, which only an explicit save may overwrite.
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
self.with_doc(doc, |st| {
if st.dirty && st.disk_conflict {
return Ok(false);
}
self.write(doc, st).map(|()| true)
})
}
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
{
if !st.dirty || st.uri.is_some() {
return Ok(());
}
@@ -846,7 +822,6 @@ impl Documents {
};
st.disk_mtime = mtime;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
self.set_dirty(doc, st, false);
if st.observed {
let text = st.doc.text();
@@ -855,7 +830,7 @@ impl Documents {
}
}
Ok(())
}
})
}
/// Save As for an untitled buffer: writes it to `target` (creating missing
@@ -1115,7 +1090,6 @@ impl Documents {
st.has_bom = loaded.has_bom;
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
self.replace_locked(doc, st, &loaded.text)?;
// Reloading is not an edit: the buffer matches the file again.
self.set_dirty(doc, st, false);
@@ -1288,14 +1262,13 @@ impl Documents {
if st.dirty {
st.disk_mtime = mtime;
st.disk_len = meta.len();
st.disk_conflict = true;
let name = st.path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
self.sink.emit(IdeEvent::Notify {
level: NotifyLevel::Warning,
title: format!("{name} changed on disk"),
body: Some(format!(
"{} was modified externally but has unsaved changes in the editor. \
Saving explicitly will overwrite the external changes; autosave leaves the file alone.",
Saving will overwrite the external changes.",
st.path.display()
)),
});
@@ -1316,7 +1289,6 @@ impl Documents {
};
st.disk_mtime = loaded.mtime_ms;
st.disk_len = disk_len(&st.path);
st.disk_conflict = false;
if loaded.binary || st.binary {
return Ok(());
}
-33
Переглянути файл
@@ -228,39 +228,6 @@ fn dirty_events(events: &[IdeEvent]) -> Vec<bool> {
events.iter().filter_map(|e| if let IdeEvent::DocDirty { dirty, .. } = e { Some(*dirty) } else { None }).collect()
}
#[test]
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
let f = fixture();
let path = f.root.join("notes.txt");
fs::write(&path, "alpha\nbeta\n").unwrap();
let info = f.docs.open(&path).unwrap();
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(&path, "alpha\nbeta external\n").unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert!(!f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "alpha\nbeta external\n");
assert!(f.docs.snapshot(info.id).unwrap().dirty);
// An explicit save overwrites, as the warning says; autosave works again after it.
f.docs.save(info.id).unwrap();
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
f.docs.edit(info.id, 1, change(0, 0, "x")).unwrap();
assert!(f.docs.autosave(info.id).unwrap());
assert_eq!(fs::read_to_string(&path).unwrap(), "xedited\nbeta\n");
}
#[test]
fn closing_a_modified_buffer_reports_it_clean() {
let f = fixture();
let info = f.docs.open_untitled(None).unwrap();
f.docs.edit(info.id, 0, change(0, 0, "draft")).unwrap();
assert_eq!(dirty_events(&f.events.lock()), vec![true]);
f.docs.close(info.id);
assert_eq!(dirty_events(&f.events.lock()), vec![true, false]);
}
#[test]
fn open_edit_save_close() {
let f = fixture();
+1 -1
Переглянути файл
@@ -131,7 +131,7 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
- **Global (`User`)**: saved in `settings.toml` with environment variable and HTTP header values stored in the OS credential store, shared across projects and agents (or scoped to selected agents).
- **Project (`Workspace`)**: saved in `.openidea/settings.toml`; entries with the same name override Global servers, and servers added outside OpenIDEA stay off until approved.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json` (and installed Copilot CLI plugins), `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Agent Configs**: discovers servers already configured in `~/.copilot/mcp-config.json`, `~/.claude.json`, `~/.codex/config.toml`, `~/.cursor/mcp.json`, `~/.gemini/settings.json`, `~/.jetbrains/mcp/mcp.json`, `.mcp.json`, and `.vscode/mcp.json` so you can import them into Global or Project settings with one click. You can also add or edit servers via structured fields or raw `mcpServers` JSON (**Add from JSON**), and run **Test Connection** to inspect the tools a server advertises.
- **Per-session (`MCP` / `/mcp`)**: in both **New Agent Task** and active task conversations, open **MCP** in the composer toolbar (or run `/mcp`) to enable or disable individual servers—including the built-in `openidea` server—for that task only, or click **Reset** to return to the inherited defaults.
While the agent works, the line under the conversation says what it is doing: thinking, reading, editing, running a command, writing its reply. **Settings › Agents › Working Status** can show playful words for what it does there instead; they are off by default. Once turned on, they take turns from the moment the work changes, or only after the agent reports nothing new for a number of seconds (0 to 600, 0 by default); screen readers still hear what the agent is doing. Each word stays eight seconds while the agent keeps at the same work, and at least three when it moves on, so the line doesn't flicker. The same page replaces the words: pick what the status says (**Reading…**, **Running a command…**…) and add or remove its words. **Restore Built-in Words** brings back OpenIDEA's; an activity left without words keeps its plain status.
-1
Переглянути файл
@@ -97,7 +97,6 @@ Open **Run › Edit Configurations…** (also in the run widget menu). The **Run
| **Gradle** / **Maven** | Gradle tasks or Maven goals, optionally through the wrapper |
| **Application** / **JAR Application** / **Spring Boot** | A Java main class, an executable JAR, a Spring Boot application |
| **Tomcat Server** | A WAR application in a local Tomcat |
| **Python** | A Python script or `-m` module |
| **pytest** / **Django tests** | pytest tests, `manage.py test` |
| **Ruby** / **Rake** / **RSpec** | A Ruby script, a Rake task, RSpec examples |
| **PHPUnit** | PHPUnit tests |
-1
Переглянути файл
@@ -57,7 +57,6 @@ 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
+1 -1
Переглянути файл
@@ -105,7 +105,7 @@ In the editor, gutter icons run or debug:
A test file runs with pytest even when the project declares no test setup (`python -m pytest` with the project interpreter, so pytest must be installed there). In a Django project, `TestCase` tests can also run with `manage.py test`. Results of pytest and of Django's unittest runner appear in the test tree, where **Rerun Failed Tests** runs only the failures.
You can also create **Python** (a script or module), **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
You can also create **pytest** and **Django tests** configurations in **Run › Edit Configurations…**. See [Run configurations](/en/guide/run) and [Testing](/en/guide/testing).
| Action | macOS | Windows / Linux |
| --------------------------- | ----- | ---------------- |
+1 -4
Переглянути файл
@@ -238,8 +238,7 @@ The full table is `UI_KEYS` in
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
@@ -520,8 +519,6 @@ conventionally go in the theme file, groups marked _editor scheme_ in the scheme
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
+1 -1
Переглянути файл
@@ -131,7 +131,7 @@ agent 运行过一个任务后,新任务会以它自动批准所有操作的
- **全局(`用户`)**:保存在 `settings.toml` 中,环境变量与 HTTP 请求头的值保存在系统凭据存储里,跨项目与各智能体共享(也可限定给选定的智能体)。
- **项目(`工作区`)**:保存在 `.openidea/settings.toml` 中,同名服务器覆盖全局配置;在 OpenIDEA 外部写入的项目服务器在批准启用前保持关闭。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`(及已安装的 Copilot CLI 插件)、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **智能体配置**:自动发现 `~/.copilot/mcp-config.json`、`~/.claude.json`、`~/.codex/config.toml`、`~/.cursor/mcp.json`、`~/.gemini/settings.json`、`~/.jetbrains/mcp/mcp.json`、`.mcp.json` 和 `.vscode/mcp.json` 中已配置的服务器,可一键导入到全局或项目设置。添加或编辑服务器时既可使用表单,也可直接粘贴 `mcpServers` JSON(**从 JSON 添加**),并可通过 **测试连接** 查看服务器声明的工具列表。
- **按会话覆盖(`MCP` / `/mcp`)**:在 **新建 Agent 任务** 和进行中的任务对话中,单击输入框工具栏的 **MCP**(或输入 `/mcp`),即可仅针对当前任务开启或关闭任意服务器(包括内置的 `openidea` 服务器),或点击 **重置** 恢复继承的默认状态。
agent 工作时,对话下方的状态行显示它正在做什么:思考、读取、编辑、运行命令、输出回复。在 **设置 › 智能体 › 工作状态** 中可以让这里改为显示与当前工作相关的趣味文字,默认关闭。开启后,工作一变化就轮换显示,也可以设置在 agent 无新进展多少秒后才显示(0 到 600,默认 0);屏幕阅读器读出的仍是 agent 实际在做的事。agent 持续做同一类工作时,每条文字停留八秒;转向其他工作时也至少停留三秒,状态行不会频繁跳动。同一页面还可以替换这些文字:选择状态(**正在读取…**、**正在运行命令…**…),再添加或移除对应的文字。**恢复内置文字** 会换回 OpenIDEA 自带的文字;没有任何文字的状态只显示实际进展。
-1
Переглянути файл
@@ -93,7 +93,6 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
| **Gradle** / **Maven** | Gradle 任务或 Maven 目标,可选择通过 wrapper 运行 |
| **应用程序** / **JAR 应用程序** / **Spring Boot** | Java 主类、可执行 JAR、Spring Boot 应用 |
| **Tomcat 服务器** | 在本地 Tomcat 里运行 WAR 应用 |
| **Python** | Python 脚本或 `-m` 模块 |
| **pytest** / **Django 测试** | pytest 测试、`manage.py test` |
| **Ruby 语言** / **Rake 任务** / **RSpec 测试** | Ruby 脚本、Rake 任务、RSpec 用例 |
| **PHPUnit** | PHPUnit 测试 |
-1
Переглянути файл
@@ -57,7 +57,6 @@ 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 格式化之后生效,保存时格式化也一样;格式化选区时只作用于选中的行。空行、注释行、其他语句或跨多行的值会开始新的一组,嵌套数组单独对齐。
## 运行与测试
+1 -1
Переглянути файл
@@ -105,7 +105,7 @@ Ruff 只为位于 Ruff 配置之下的文件启动:`ruff.toml`、`.ruff.toml`
即使项目没有声明任何测试配置,测试文件也可以用 pytest 运行(用项目解释器执行 `python -m pytest`,因此该解释器里要装有 pytest)。在 Django 项目中,`TestCase` 测试也可以用 `manage.py test` 运行。pytest 和 Django unittest 运行器的结果显示在测试树中,**重新运行失败的测试** 只重跑失败的用例。
也可以在 **运行 › 编辑配置…** 中新建 **Python**(脚本或模块)、**pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
也可以在 **运行 › 编辑配置…** 中新建 **pytest** 和 **Django 测试** 配置。详见[运行配置](/zh/guide/run)和[测试](/zh/guide/testing)。
| 操作 | macOS | Windows / Linux |
| -------------- | ----- | ---------------- |
+1 -4
Переглянути файл
@@ -211,8 +211,7 @@ pnpm theme:import-intellij path/to/MyTheme.theme.json path/to/MyTheme.icls --out
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5`(语义高亮) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES`(效果颜色) |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT`(`CONSOLE_DARKGRAY_OUTPUT` 为亮黑,`CONSOLE_GRAY_OUTPUT` 为白色) |
@@ -486,8 +485,6 @@ VS Code 主题(扩展中的 `themes/*.json`)包含 `type`(`dark` / `light`
| `--fg-unused` | `#6f737a` | `#8c8c8c` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
-1
Переглянути файл
@@ -416,7 +416,6 @@ test("dragging the Changes pane's edge resizes it for the next session too", asy
// The next session starts with the dragged width.
await page.reload();
await expect(page.getByRole("tree", { name: "Project" })).toBeVisible();
await seedTasks(page, "editor");
await seedChanges(page);
await expect.poll(async () => Math.round((await changes.boundingBox())!.width)).toBe(Math.round(widened));
-34
Переглянути файл
@@ -1024,37 +1024,3 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
});
test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => {
const reply = await openReply(
page,
[
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.",
"",
"$$",
"\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}",
"$$",
"",
"```math",
"\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}",
"```",
].join("\n"),
);
await expect(reply.locator(".katex")).toHaveCount(4);
await expect(reply.locator(".katex-display")).toHaveCount(2);
await expect(reply).toContainText("prices $5 and $10 stay plain.");
const layout = await reply.evaluate((el) => {
const firstKatex = el.querySelector<HTMLElement>(".katex")!;
const display = el.querySelectorAll<HTMLElement>(".katex-display");
const font = getComputedStyle(firstKatex).fontFamily;
return {
font,
height: firstKatex.getBoundingClientRect().height,
overflowX: getComputedStyle(display[1]!).overflowX,
};
});
expect(layout.font).toContain("KaTeX_Main");
expect(layout.height).toBeGreaterThan(10);
expect(layout.overflowX).toBe("auto");
});
+1 -1
Переглянути файл
@@ -102,7 +102,7 @@ test("stripe themes inherit base tooltip tokens and keep shortcut text readable"
delete root.dataset.colorTheme;
root.dataset.theme = kind;
root.dataset.pluginTheme = "test/base-tooltip";
const path = "/src/features/plugins/themeRuntime.ts";
const path = "/src/features/plugins/bridge.ts";
const { pluginThemeCss } = await import(/* @vite-ignore */ path);
const style = document.createElement("style");
style.id = "test-plugin-theme";
+1 -1
Переглянути файл
@@ -47,7 +47,7 @@ moveRefactoringSupport = true
[language-servers.initialization-options.settings.java]
autobuild = { enabled = true }
contentProvider = { preferred = "fernflowerContentProvider" }
maven = { downloadSources = false, updateSnapshots = false }
maven = { downloadSources = true, updateSnapshots = false }
eclipse = { downloadSources = true }
references = { includeDecompiledSources = true }
# The editor's usage lenses count usages; the server's own lenses would search every
-1
Переглянути файл
@@ -80,7 +80,6 @@
"dompurify": "^3.4.17",
"emmet": "2.4.11",
"immer": "^11.1.21",
"katex": "^0.19.1",
"marked": "^18.1.1",
"mermaid": "12.1.0",
"react": "^19.1.0",
-2
Переглянути файл
@@ -116,7 +116,6 @@
"text/apply_100_changes_1mb": 1000,
"text/diff_two_edits_1mb": 10000,
"text/diff_every_line_1mb": 100000,
"text/diff_one_edit_5mb": 2000,
"text/offset_to_pos_round_trip": 5,
"text/pos_to_byte": 5,
"text/text_for_save_crlf_1mb": 1000,
@@ -142,7 +141,6 @@
"search_5k/literal": 100000,
"search_5k/regex": 100000,
"search_5k/dense_limit": 20000,
"search_dense_files/24x40k_limit": 20000,
"plugins/load_50": 20000,
"plugins/cold_activation": 30000,
-2
Переглянути файл
@@ -104,8 +104,6 @@
"--fg-deprecated": "#8c8f95",
"--bg-identifier-under-caret": "#2e353f",
"--bg-identifier-under-caret-write": "#402f33",
"--fg-identifier-under-caret": "inherit",
"--fg-identifier-under-caret-write": "inherit",
"--fg-inlay": "#75869d",
"--bg-inlay": "#303944",
"--wave-typo": "#59a869",
+2 -5
Переглянути файл
@@ -232,8 +232,7 @@ The full table is `UI_KEYS` in [`src/features/plugins/intellijTheme.ts`](../src/
| `--syn-tag`, `--syn-attribute`, `--syn-todo`, `--syn-invalid` | `DEFAULT_TAG`, `DEFAULT_ATTRIBUTE`, `TODO_DEFAULT_ATTRIBUTES`, `BAD_CHARACTER` |
| `--syn-rainbow-1` … `--syn-rainbow-5` (Semantic highlighting, rainbow indent guides) | `RAINBOW_COLOR1` … `RAINBOW_COLOR5` |
| `--wave-error`, `--wave-warning` | `ERRORS_ATTRIBUTES`, `WARNING_ATTRIBUTES` (effect colour) |
| `--bg-matched-brace`, `--bg-identifier-under-caret`, `--fg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-identifier-under-caret-write`, `--fg-identifier-under-caret-write` | `WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-matched-brace`, `--bg-identifier-under-caret` | `MATCHED_BRACE_ATTRIBUTES`, `IDENTIFIER_UNDER_CARET_ATTRIBUTES` |
| `--bg-text-search-result`, `--bg-search-result` | `TEXT_SEARCH_RESULT_ATTRIBUTES`, `SEARCH_RESULT_ATTRIBUTES` |
| `--syn-self`, `--syn-keyword-arg`, `--syn-docstring`, `--syn-predefined` | `PY.SELF_PARAMETER`, `PY.KEYWORD_ARGUMENT`, `PY.DOC_COMMENT`, `PY.BUILTIN_NAME` |
| `--ansi-*` | `CONSOLE_*_OUTPUT` (`CONSOLE_DARKGRAY_OUTPUT` is bright black, `CONSOLE_GRAY_OUTPUT` white) |
@@ -333,7 +332,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
271 themeable tokens: 125 in the UI theme file, 146 in the editor colour scheme file.
269 themeable tokens: 125 in the UI theme file, 144 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -529,8 +528,6 @@ a token.
| `--fg-deprecated` | `#8c8f95` | `#6c707e` |
| `--bg-identifier-under-caret` | `#373b39` | `#edebfc` |
| `--bg-identifier-under-caret-write` | `#402f33` | `#fce8f4` |
| `--fg-identifier-under-caret` | `inherit` | `inherit` |
| `--fg-identifier-under-caret-write` | `inherit` | `inherit` |
| `--fg-inlay` | `#868a91` | `#73767c` |
| `--bg-inlay` | `#393b40` | `#00000012` |
| `--wave-error` | `#fa6675` | `#f50000` |
Створено
-11
Переглянути файл
@@ -119,9 +119,6 @@ importers:
immer:
specifier: ^11.1.21
version: 11.1.21
katex:
specifier: ^0.19.1
version: 0.19.1
marked:
specifier: ^18.1.1
version: 18.1.1
@@ -1802,10 +1799,6 @@ packages:
resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==}
hasBin: true
[email protected]:
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
@@ -3799,10 +3792,6 @@ snapshots:
dependencies:
commander: 15.1.0
[email protected]:
dependencies:
commander: 15.1.0
[email protected]: {}
[email protected]:
-17
Переглянути файл
@@ -170,23 +170,6 @@ describe("IntelliJ theme import", () => {
});
});
it("maps the caret identifier foregrounds (#4109)", () => {
const s = convertIcls(`<scheme name="Caret" version="142" parent_scheme="Darcula"><attributes>
<option name="IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
<option name="FOREGROUND" value="aa0000" /><option name="BACKGROUND" value="220000" />
</value></option>
<option name="WRITE_IDENTIFIER_UNDER_CARET_ATTRIBUTES"><value>
<option name="FOREGROUND" value="00aa00" /><option name="BACKGROUND" value="002200" />
</value></option>
</attributes></scheme>`);
expect(s.tokens).toMatchObject({
"--fg-identifier-under-caret": "#aa0000",
"--bg-identifier-under-caret": "#220000",
"--fg-identifier-under-caret-write": "#00aa00",
"--bg-identifier-under-caret-write": "#002200",
});
});
it("only targets tokens that exist in tokens.css", () => {
const declared = new Set([...css.matchAll(/(--[a-z0-9-]+)\s*:/g)].map((m) => m[1]!));
// Read with a fallback by the editor (no tokens.css default), still themeable.
+10 -13
Переглянути файл
@@ -93,12 +93,10 @@ db_connect trusted project_host bin
db_connected trusted project_host bindings sync
db_console_path always project_host bindings sync
db_consoles always project_host bindings sync
db_create_database trusted project_host bindings async
db_database_catalog trusted project_host bindings async
db_databases trusted project_host bindings async
db_ddl trusted project_host bindings async
db_disconnect trusted project_host bindings async
db_drop_database trusted project_host bindings async
db_dump_info trusted desktop bindings async
db_execute trusted project_host bindings async
db_explain trusted project_host bindings async
@@ -196,7 +194,6 @@ deploy_sync trusted project_host bin
deploy_test_connection always project_host bindings async
deploy_upload trusted project_host bindings async
diff_external_tool always desktop bindings async
doc_autosave always project_host bindings async
doc_close always project_host bindings async
doc_edit always project_host bindings async
doc_folding always project_host bindings async
@@ -539,7 +536,7 @@ scaffold_options always project_host bin
scaffold_requirements always project_host bindings async
sdk_container_python trusted project_host bindings sync
sdk_container_python_refresh trusted project_host bindings async
sdk_detect outside_restricted project_host bindings async
sdk_detect trusted project_host bindings async
sdk_jdk_at trusted project_host bindings async
sdk_locate_tools trusted project_host bindings async
sdk_php_composer_install trusted project_host bindings async
@@ -547,12 +544,12 @@ sdk_php_effective trusted project_host bin
sdk_php_language_level trusted project_host bindings async
sdk_php_xdebug trusted project_host bindings async
sdk_project_libraries trusted project_host bindings async
sdk_python_create_venv outside_restricted project_host bindings async
sdk_python_create_venv trusted project_host bindings async
sdk_python_effective trusted project_host bindings sync
sdk_python_interpreter outside_restricted project_host bindings async
sdk_python_packages outside_restricted project_host bindings async
sdk_python_pip outside_restricted project_host bindings async
sdk_python_project_interpreters outside_restricted project_host bindings async
sdk_python_interpreter trusted project_host bindings async
sdk_python_packages trusted project_host bindings async
sdk_python_pip trusted project_host bindings async
sdk_python_project_interpreters trusted project_host bindings async
search_start always project_host bindings async
search_validate always project_host bindings sync
set_recent_project_groups always desktop bindings sync
@@ -598,10 +595,10 @@ term_resize always project_host bin
term_spawn always project_host bindings async
term_store_image always project_host bindings async
term_write always project_host bindings sync
tools_install outside_restricted project_host bindings async
tools_list outside_restricted project_host bindings async
tools_uninstall outside_restricted project_host bindings async
tools_updates outside_restricted project_host bindings async
tools_install trusted project_host bindings async
tools_list trusted project_host bindings async
tools_uninstall trusted project_host bindings async
tools_updates trusted project_host bindings async
undo_workspace_edit always project_host bindings async
user_font_data always desktop - async
vcs_add_to_ignore trusted project_host bindings async
-29
Переглянути файл
@@ -1,29 +0,0 @@
import type { AuxKind } from "./platform/auxWindow";
import { mountWindowRoot } from "./windowBoot";
import { activateSecondaryWindow } from "./workbench/activateSecondary";
export async function bootAuxiliaryWindow(aux: { kind: AuxKind; parent: string }): Promise<void> {
activateSecondaryWindow();
switch (aux.kind) {
case "settings": {
const { bootSettingsWindow } = await import("./settingsWindowBoot");
mountWindowRoot(bootSettingsWindow(aux.parent));
return;
}
case "comparison": {
const { bootComparisonWindow } = await import("./comparisonWindowBoot");
mountWindowRoot(bootComparisonWindow(aux.parent));
return;
}
case "diff": {
const { bootDiffWindow } = await import("./diffWindowBoot");
mountWindowRoot(bootDiffWindow(aux.parent));
return;
}
case "deployment": {
const { bootDeploymentWindow } = await import("./deploymentWindowBoot");
mountWindowRoot(bootDeploymentWindow(aux.parent));
return;
}
}
}
+1 -25
Переглянути файл
@@ -272,12 +272,10 @@ export const commands = {
dbConsolePath: (id: string) => typedError<IpcPath, IdeError>(__TAURI_INVOKE("db_console_path", { id })),
/** The query consoles of data source `id`; `create` adds the next one first. */
dbConsoles: (id: string, create: boolean) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("db_consoles", { id, create })),
dbCreateDatabase: (id: string, template: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_create_database", { id, template, statement })),
dbDatabaseCatalog: (id: string, database: string) => typedError<DbCatalogSchema[], IdeError>(__TAURI_INVOKE("db_database_catalog", { id, database })),
dbDatabases: (id: string) => typedError<DbDatabases, IdeError>(__TAURI_INVOKE("db_databases", { id })),
dbDdl: (id: string, schema: string, table: string) => typedError<string, IdeError>(__TAURI_INVOKE("db_ddl", { id, schema, table })),
dbDisconnect: (id: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_disconnect", { id })),
dbDropDatabase: (id: string, database: string, statement: string) => typedError<null, IdeError>(__TAURI_INVOKE("db_drop_database", { id, database, statement })),
/** What made the dump at `path` and whether it creates its own database (from its first bytes). */
dbDumpInfo: (path: string) => typedError<DbDumpInfo, IdeError>(__TAURI_INVOKE("db_dump_info", { path })),
dbExecute: (request: RequestId, id: string, statements: SqlStatement[], skip: number, maxRows: number, schema: string | null) => typedError<DbStatementOutcome[], IdeError>(__TAURI_INVOKE("db_execute", { request, id, statements, skip, maxRows, schema })),
@@ -454,11 +452,6 @@ export const commands = {
* (a remote window passes the sides as text).
*/
diffExternalTool: (left: ExternalDiffSide, right: ExternalDiffSide, title: string) => typedError<null, IdeError>(__TAURI_INVOKE("diff_external_tool", { left, right, title })),
/**
* An automatic save: `false` (nothing written) when the file changed on disk after the
* buffer was edited, which only an explicit save overwrites.
*/
docAutosave: (doc: DocId) => typedError<boolean, IdeError>(__TAURI_INVOKE("doc_autosave", { doc })),
docClose: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_close", { doc })),
/**
* Applies a CodeMirror change set; returns the new version. Rejects with
@@ -1817,10 +1810,7 @@ export const commands = {
webServesPage: (url: string) => typedError<boolean, IdeError>(__TAURI_INVOKE("web_serves_page", { url })),
/** Paths in an HTML document or stylesheet that name no existing file. */
webUnresolvedReferences: (doc: DocId) => typedError<FileReference[], IdeError>(__TAURI_INVOKE("web_unresolved_references", { doc })),
/**
* The built-in server's URL for `path` (started on first use). A file whose language is
* HTML (Settings › File Types can make it so) is served as a page, whatever its extension.
*/
/** The built-in server's URL for `path` (started on first use). */
webUrl: (path: IpcPath) => typedError<string, IdeError>(__TAURI_INVOKE("web_url", { path })),
windowCloseContext: () => __TAURI_INVOKE<CloseContext>("window_close_context"),
/** Release the opening window's reservation after navigation or cancellation. */
@@ -7427,10 +7417,6 @@ 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 › <Language> › Tabs and Indents (unset fields inherit). */
@@ -7447,10 +7433,6 @@ 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`. */
@@ -8105,12 +8087,6 @@ export type MavenSettings = {
activeProfiles?: string,
/** Delegate IDE build/run actions to Maven: launches build with Maven (`javac`) instead of jdtls (ECJ). */
delegateBuild?: boolean,
/**
* Download `-sources.jar` of dependencies when the Java language server imports the
* project (jdtls `java.maven.downloadSources`). Off: sources are fetched on demand
* from a library class's Download Sources banner.
*/
downloadSources?: boolean,
};
/** Summary of one server discovered inside an external MCP configuration file. */
-27
Переглянути файл
@@ -1,27 +0,0 @@
import type { ComponentType } from "react";
import { activate as editor } from "./editor/core";
import { confirmLeave } from "./features/app/closeGuard";
import { installLocaleSync } from "./features/app/locale";
import { installMenuBridge } from "./features/app/menuBridge";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activate as vcs } from "./features/vcs";
import { activateComparisonWindow, ComparisonWindow } from "./features/vcs/ComparisonWindow";
import { installKeyboardDispatcher } from "./platform/keymap";
import { activateList } from "./windowBoot";
/**
* Comparison window of project window `parent`: changed files between two
* revisions and their diffs, with the editor and Git but no workbench.
*/
export function bootComparisonWindow(parent: string): ComponentType {
activateList("comparison window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["menu", installMenuBridge],
["editor", editor],
["vcs", vcs],
["comparison", () => activateComparisonWindow(parent, (project) => confirmLeave(undefined, project))],
]);
installKeyboardDispatcher();
return ComparisonWindow;
}
-20
Переглянути файл
@@ -1,20 +0,0 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { activateDeploymentWindow, DeploymentWindow } from "./features/deployment/window";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activateDiffViewer } from "./features/vcs/diffViewer";
import { activateList } from "./windowBoot";
/**
* Sync with Deployed window of project window `parent`: local files next to
* their copies on a deployment server, with the diff viewer but no workbench.
*/
export function bootDeploymentWindow(parent: string): ComponentType {
activateList("deployment window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["diff", activateDiffViewer],
["deployment", () => activateDeploymentWindow(parent)],
]);
return DeploymentWindow;
}
-24
Переглянути файл
@@ -1,24 +0,0 @@
import type { ComponentType } from "react";
import { installLocaleSync } from "./features/app/locale";
import { installMenuBridge } from "./features/app/menuBridge";
import { trackRuntimeSettings } from "./features/settings/runtime";
import { activate as vcs } from "./features/vcs";
import { activateDiffWindow, DiffWindow } from "./features/vcs/DiffWindow";
import { installKeyboardDispatcher } from "./platform/keymap";
import { activateList } from "./windowBoot";
/**
* Diff window of project window `parent`: one file's diff, with Git and its own
* documents but no workbench.
*/
export function bootDiffWindow(parent: string): ComponentType {
activateList("diff window", [
["locale", installLocaleSync],
["settings", trackRuntimeSettings],
["menu", installMenuBridge],
["vcs", vcs],
["diff", () => activateDiffWindow(parent)],
]);
installKeyboardDispatcher();
return DiffWindow;
}
-3
Переглянути файл
@@ -49,8 +49,6 @@ export interface DocBackend {
close(doc: DocId): Promise<void>;
edit(doc: DocId, baseVersion: number, changes: TextChange[]): Promise<number>;
save(doc: DocId): Promise<void>;
/** An automatic save; `false` when the file changed on disk after the buffer was edited (nothing written). */
autosave?(doc: DocId): Promise<boolean>;
/** Re-check every open file for external changes missed by file watchers. */
syncFromDisk?(): Promise<void>;
snapshot(doc: DocId): Promise<DocumentInfo>;
@@ -94,7 +92,6 @@ export const ipcBackend: DocBackend = {
close: async (doc) => void (await call(commands.docClose(doc))),
edit: (doc, baseVersion, changes) => call(commands.docEdit(doc, baseVersion, { changes })),
save: async (doc) => void (await call(commands.docSave(doc))),
autosave: (doc) => call(commands.docAutosave(doc)),
syncFromDisk: async () => void (await call(commands.docSyncFromDisk())),
snapshot: (doc) => call(commands.docSnapshot(doc)),
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
+1 -45
Переглянути файл
@@ -1,11 +1,10 @@
import { afterEach, describe, expect, it } from "vitest";
import { EditorSelection, EditorState, Prec } from "@codemirror/state";
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { Decoration, EditorView } from "@codemirror/view";
import { setSearchQuery } from "@codemirror/search";
import { StreamLanguage } from "@codemirror/language";
import { literalKindAt } from "./literals";
import { selectionMarks } from "./selectionMarks";
import { findStyles, markWidgetStyles } from "./theme";
import {
countMatches,
findResultLines,
@@ -42,49 +41,6 @@ function make(doc: string, o: Partial<FindOptions>, scope?: { from: number; to:
const sel = (v: EditorView) => [v.state.selection.main.from, v.state.selection.main.to];
class TextWidget extends WidgetType {
toDOM() {
const el = document.createElement("span");
el.className = "widget";
el.textContent = "hint";
return el;
}
}
describe("widgets inside find matches", () => {
it.each([
["before the cursor side", Decoration.widget({ widget: new TextWidget(), side: -1 }).range(3)],
["after the cursor side", Decoration.widget({ widget: new TextWidget(), side: 1 }).range(3)],
["replacing text", Decoration.replace({ widget: new TextWidget() }).range(2, 4)],
])("keep their own colour %s", (_name, widget) => {
const view = new EditorView({
parent: document.body,
doc: "Session",
extensions: [
// At the top precedence, as only then does the match wrap the widget.
Prec.highest(EditorView.decorations.of(Decoration.set(widget))),
findExtension(),
],
});
views.push(view);
view.dispatch({
effects: [
setFindOpen.of(true),
setSearchQuery.of(
makeQuery({ search: "Session", caseSensitive: true, wholeWord: false, regexp: false, replace: "" }),
),
],
});
const el = view.contentDOM.querySelector<HTMLElement>(".cm-openidea-findMatch .widget")!;
// Browsers reflect this property to the attribute; jsdom does not.
el.setAttribute("contenteditable", el.contentEditable);
expect(el.matches(Object.keys(markWidgetStyles)[0]!)).toBe(true);
expect(Object.values(markWidgetStyles)[0]!.WebkitTextFillColor).toBe("currentcolor");
// A text fill of `--fg-search-match` here would reach every widget in the match.
expect(findStyles[".cm-openidea-findMatch"].WebkitTextFillColor).toBe("currentcolor");
});
});
describe("find backgrounds", () => {
it.each([
["semantic", Prec.highest],
+2 -122
Переглянути файл
@@ -1,17 +1,12 @@
import { describe, expect, it } from "vitest";
import { EditorState } from "@codemirror/state";
import { codeFolding, foldEffect, foldService, foldable, foldedRanges } from "@codemirror/language";
import { EditorView } from "@codemirror/view";
import { codeFolding, foldEffect, foldService, foldedRanges } from "@codemirror/language";
import {
backendFoldingChanged,
backendFolds,
enclosingFoldRange,
expandToLevelEffects,
foldSelectionEffects,
foldsFromRanges,
foldingExtension,
foldToExpand,
setBackendFolds,
foldsFromRanges,
} from "./folding";
/** Folds `{ … }` blocks whose header line ends with `{`. */
@@ -73,29 +68,6 @@ describe("foldToExpand", () => {
describe("foldsFromRanges", () => {
const fold = (start_line: number, end_line: number) => ({ start_line, end_line, kind: "region" as const });
it("collapses an import group beginning with a multiline statement to import only", () => {
const s = EditorState.create({
doc: [
"import Widget, {",
" Formatter,",
" parseValue,",
"} from './format.js';",
"import { render } from './view.js';",
"",
].join("\n"),
extensions: [foldingExtension(false)],
});
const ranges = [{ start_line: 0, end_line: 4, kind: "imports" as const }];
const [f] = foldsFromRanges(s, ranges);
expect(f).toEqual({ from: "import ".length, to: s.doc.line(5).to, kind: "imports" });
const state = s.update({ effects: setBackendFolds.of(ranges) }).state;
expect(foldable(state, state.doc.line(1).from, state.doc.line(1).to)).toEqual({ from: f!.from, to: f!.to });
const view = new EditorView({ state, parent: document.createElement("div") });
view.dispatch({ effects: foldEffect.of({ from: f!.from, to: f!.to }) });
expect(view.dom.querySelector(".cm-line")?.textContent).toBe("import …");
view.destroy();
});
it("starts an Allman block's fold on its declaration line", () => {
const s = EditorState.create({ doc: "namespace Demo\n{\n class A\n {\n }\n}\n" });
const folds = foldsFromRanges(s, [fold(1, 5), fold(3, 4)]);
@@ -187,95 +159,3 @@ describe("expandToLevelEffects", () => {
expect(folded(s.update({ effects: expandToLevelEffects(s, 2) }).state)).toEqual([]);
});
});
describe("fold gutter chevrons", () => {
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
it("backendFoldingChanged fires when backend folds arrive, not on selection moves", () => {
let changed = false;
const view = new EditorView({
state: EditorState.create({
doc,
extensions: [
foldingExtension(true),
// The same predicate the fold gutter's foldingChanged hook uses.
EditorView.updateListener.of((u) => {
if (backendFoldingChanged(u)) changed = true;
}),
],
}),
parent: document.body,
});
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
expect(changed).toBe(true);
changed = false;
view.dispatch({ selection: { anchor: 0 } });
expect(changed).toBe(false);
view.destroy();
});
it("the gutter shows a chevron after backend folds arrive", () => {
const view = new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
parent: document.body,
});
const markers = () =>
Array.from(view.dom.querySelectorAll<HTMLElement>(".cm-foldGutter .cm-gutterElement")).map(
(el) => el.firstElementChild?.className ?? "",
);
const before = markers();
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
const after = markers();
expect(after.join("|")).not.toBe(before.join("|"));
view.destroy();
});
});
describe("fold placeholder chip", () => {
const doc = ["def f():", ' """doc', " more", ' """', " pass"].join("\n");
function foldedView() {
const view = new EditorView({
state: EditorState.create({ doc, extensions: [foldingExtension(true)] }),
parent: document.body,
});
view.dispatch({ effects: setBackendFolds.of([{ start_line: 1, end_line: 3, kind: "comment" }]) });
return view;
}
function folded(view: ReturnType<typeof foldedView>) {
const out: Array<[number, number]> = [];
foldedRanges(view.state).between(0, view.state.doc.length, (a, b) => void out.push([a, b]));
return out;
}
function fold(view: ReturnType<typeof foldedView>) {
const [f] = view.state.field(backendFolds);
view.dispatch({ effects: foldEffect.of({ from: f!.from, to: f!.to }) });
}
it("clicking the chip expands the fold, repeatedly", () => {
const view = foldedView();
for (let i = 0; i < 3; i++) {
fold(view);
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder");
expect(chip, `iteration ${i}`).not.toBeNull();
chip!.click();
expect(folded(view), `iteration ${i}`).toEqual([]);
}
view.destroy();
});
it("a chip whose position is the fold's start line still expands", () => {
const view = foldedView();
const [f] = view.state.field(backendFolds);
// A docstring fold starts at the end of its header line: a chip resolved
// through the line block would land on that line and find no fold.
expect(view.state.doc.lineAt(f!.from).to).toBe(f!.from);
fold(view);
const chip = view.dom.querySelector<HTMLElement>(".cm-foldPlaceholder")!;
chip.click();
expect(folded(view)).toEqual([]);
view.destroy();
});
});
+7 -27
Переглянути файл
@@ -12,7 +12,7 @@ import {
type Extension,
type Line,
} from "@codemirror/state";
import type { EditorView, ViewUpdate } from "@codemirror/view";
import type { EditorView } from "@codemirror/view";
import {
codeFolding,
foldEffect,
@@ -64,14 +64,12 @@ export function foldsFromRanges(state: EditorState, ranges: readonly FoldRange[]
continue;
}
const start = allmanHeader(state, first);
const importHead = r.kind === "imports" && /^\s*import\s+/.exec(first.text);
const from = importHead && /(?:\{|,)\s*$/.test(first.text) ? first.from + importHead[0].length : start.to;
const trimmed = end.text.trimStart();
// `}` / `)` / `]` on the last line stays visible after the placeholder, like IDEA. An import
// run ending in `} from '…'` hides that whole statement; a bare `)` / `};` still shows.
const delimiter = r.kind === "imports" ? /^[}\])]+[;,]?$/.test(trimmed.trimEnd()) : /^[}\])]/.test(trimmed);
const to = delimiter ? end.from + (end.text.length - trimmed.length) : end.to;
if (to > from) out.push({ from, to, kind: r.kind });
if (to > start.to) out.push({ from: start.to, to, kind: r.kind });
}
return out.sort((a, b) => a.from - b.from || b.to - a.to);
}
@@ -103,8 +101,8 @@ function foldAtLine(folds: readonly BackendFold[], lineStart: number, lineEnd: n
let best: BackendFold | null = null;
for (let i = lo; i < folds.length && folds[i]!.from <= lineEnd; i++) {
const f = folds[i]!;
// Multiline import groups and custom regions can start within their header line.
if ((f.from === lineEnd || f.custom || f.kind === "imports") && (!best || f.to > best.to)) best = f;
// Only folds whose header ends on this line (custom regions: on this line); keep the widest.
if ((f.from === lineEnd || f.custom) && (!best || f.to > best.to)) best = f;
}
return best;
}
@@ -394,40 +392,22 @@ function chevron(open: boolean): HTMLElement {
return span;
}
/**
* Backend folds arrive asynchronously (`setBackendFolds`) and are not a document,
* viewport or language change, so CodeMirror's fold gutter keeps the chevrons it
* built before they arrived. A click then hits a gutter element at a stale line
* and silently does nothing. Rebuild the markers whenever the backend field changes.
*/
export function backendFoldingChanged(update: ViewUpdate): boolean {
return update.startState.field(backendFolds, false) !== update.state.field(backendFolds, false);
}
export function foldingExtension(showOutline = true): Extension {
return [
// The chevron column sits right of contributed icon gutters (IDEA new UI).
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron, foldingChanged: backendFoldingChanged })) : [],
showOutline ? Prec.lowest(foldGutter({ markerDOM: chevron })) : [],
backendFolds,
backendFoldService,
codeFolding({
// A folded custom region shows its name, as in IDEA.
preparePlaceholder: (state, range) => regionNameAt(state, range.from),
placeholderDOM: (view, onclick, name: string | null) => {
placeholderDOM: (_view, onclick, name: string | null) => {
const el = document.createElement("span");
el.className = "cm-foldPlaceholder";
el.textContent = name ?? "…";
el.title = "Expand";
el.setAttribute("aria-label", "folded code");
el.onclick = (event) => {
// CodeMirror's own handler resolves the fold through the clicked line
// block, which can miss a fold starting at a line boundary (docstring,
// Allman header). Resolving at the chip's own position cannot miss.
const folded = foldToExpand(view.state, view.posAtDOM(el));
if (folded) view.dispatch({ effects: unfoldEffect.of(folded) });
else onclick(event);
event.preventDefault();
};
el.onclick = onclick;
return el;
},
}),
-1
Переглянути файл
@@ -46,7 +46,6 @@ const theme = EditorView.baseTheme({
boxDecorationBreak: "clone",
// Unset (the default `inherit`): the declaration drops and the syntax colours show through.
color: "var(--fg-editor-selection)",
WebkitTextFillColor: "var(--fg-editor-selection)",
},
"&.cm-focused .cm-openidea-selected": {
"--openidea-selected-bg": "var(--editor-selection, var(--bg-editor-selection))",
-10
Переглянути файл
@@ -24,8 +24,6 @@ export const findStyles = {
".cm-openidea-findMatch": {
backgroundColor: "var(--editor-search)",
color: "var(--fg-search-match, inherit)",
// Its own colour, over the text fill of an identifier highlight around the match.
WebkitTextFillColor: "currentcolor",
borderRadius: "2px",
},
".cm-openidea-findExcluded": {
@@ -42,11 +40,6 @@ export const findStyles = {
},
};
/** Marks colour text with an inherited text fill; widgets inside them keep their own colours. */
export const markWidgetStyles = {
'.cm-content [contenteditable="false"]': { WebkitTextFillColor: "currentcolor" },
};
/** The caret and Settings › Editor › General › Appearance caret options (`caretExtension`), also for viewers. */
export const caretStyles = {
".cm-cursor, .cm-dropCursor": {
@@ -226,8 +219,6 @@ export const openideaTheme = EditorView.theme({
".cm-selectionMatch": {
backgroundColor: "var(--bg-identifier-under-caret, color-mix(in srgb, var(--fg) 9%, transparent))",
},
// IDEA paints these with IDENTIFIER_UNDER_CARET_ATTRIBUTES, except the selection itself.
".cm-selectionMatch:not(.cm-selectionMatch-main)": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
// IDEA's MATCHED_BRACE_ATTRIBUTES (bold in dark schemes only) and MATCHED_TAG_NAME (never bold).
".cm-matchingBracket, &.cm-focused .cm-matchingBracket": {
backgroundColor: "var(--editor-brace)",
@@ -352,7 +343,6 @@ export const openideaTheme = EditorView.theme({
// Find in file (cm/find.ts)
...findStyles,
...markWidgetStyles,
// Find in Files preview matches (search/find/parts.tsx)
".cm-openidea-searchResult": { backgroundColor: "var(--bg-search-result)" },
-41
Переглянути файл
@@ -271,26 +271,6 @@ describe("DocumentManager + slots", () => {
}
});
it("keeps the buffer dirty when the backend declines an autosave", async () => {
const { backend, manager } = setup({ "/p/a.txt": "abc" });
const model = await manager.acquire("/p/a.txt");
const slot = new EditorSlot(model, "t1", host);
slot.dispatchLocal({ changes: { from: 0, to: 1, insert: "X" } });
backend.autosave = vi.fn(async () => false);
const save = vi.spyOn(backend, "save");
try {
await model.save("auto");
expect(backend.autosave).toHaveBeenCalledTimes(1);
expect(save).not.toHaveBeenCalled();
expect(model.getMeta().dirty).toBe(true);
await model.save("explicit");
expect(save).toHaveBeenCalledTimes(1);
expect(model.getMeta().dirty).toBe(false);
} finally {
manager.stop();
}
});
it("closes the backend document when the last slot goes away", async () => {
const { backend, manager } = setup({ "/p/a.txt": "x" });
const model = await manager.acquire("/p/a.txt");
@@ -348,27 +328,6 @@ describe("DocumentManager + slots", () => {
manager.stop();
});
it("keeps a modified file open when its last tab closes without autosave, and reopens it with the changes", async () => {
const { backend, manager } = setup({ "/p/a.txt": "a\n", "/p/b.txt": "b\n" }, { files: { autoSave: false } });
try {
const a = await manager.acquire("/p/a.txt");
const slot = new EditorSlot(a, "t1", host);
backend.patch(a.doc, [{ from: 0, to: 0, insert: "changed " }]);
slot.dispose();
const b = await manager.acquire("/p/b.txt");
new EditorSlot(b, "t2", host).dispose();
await new Promise((r) => setTimeout(r, 0));
expect(backend.files.get("/p/a.txt")).toBe("a\n");
expect(await manager.acquire("/p/a.txt")).toBe(a);
expect(a.getMeta().dirty).toBe(true);
expect(manager.byPath.has("/p/b.txt")).toBe(false);
await manager.saveAll("explicit");
expect(backend.files.get("/p/a.txt")).toBe("changed a\n");
} finally {
manager.stop();
}
});
it("Save All rejects a failed document save after saving the remaining dirty documents", async () => {
const { backend, manager } = setup({ "/p/a.txt": "a\n", "/p/b.txt": "b\n" }, { files: { autoSave: false } });
try {
+1 -9
Переглянути файл
@@ -711,11 +711,7 @@ export class DocModel {
if (await this.manager.saveAs(this)) this.modified.clear();
return;
}
const backend = this.manager.backend;
// Autosave never overwrites external changes made after the buffer was edited.
if (reason === "auto" && backend.autosave) {
if (!(await backend.autosave(this.doc))) return;
} else await backend.save(this.doc);
await this.manager.backend.save(this.doc);
this.modified.clear();
this.setMeta({ dirty: false });
_emitEditorEvent({ type: "docSaved", doc: this.doc, path: this.path });
@@ -903,10 +899,6 @@ export class DocumentManager {
console.warn(`autosave of ${model.path} failed`, e);
}
}
// As in IDEA, a file whose changes are not saved (autosave off, or a failed save) stays
// open without a tab: reopening shows the changes, and Save All and the exit check still
// cover them. An untitled buffer was asked about when its tab closed.
if (model.getMeta().dirty && !isUntitledUri(model.path)) return;
if (model.inUse()) return;
await model.sync.whenIdle();
if (model.inUse()) return;
-8
Переглянути файл
@@ -69,14 +69,6 @@ describe("markdown rendering", () => {
expect(md.markupToHtml({ kind: "markdown", value: "`x`" })).toBe("<p><code>x</code></p>\n");
expect(md.markupToHtml({ kind: "plaintext", value: "<b>" })).toBe('<p class="cm-lsp-plain">&#60;b&#62;</p>');
});
it("renders LaTeX math in LSP / documentation markdown", async () => {
const md = await freshMarkdown();
await md.loadMarkdown();
const root = document.createElement("div");
root.innerHTML = md.markupToHtml({ kind: "markdown", value: "Complexity $O(n \\log n)$" });
expect(root.querySelector(".katex")).not.toBeNull();
});
});
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
-13
Переглянути файл
@@ -1,13 +0,0 @@
.katex {
overflow-wrap: normal;
}
.katex-display {
overflow-x: auto;
overflow-y: hidden;
padding: 2px 0;
}
.katex-error {
color: var(--danger) !important;
}
-85
Переглянути файл
@@ -1,85 +0,0 @@
import { describe, expect, it } from "vitest";
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension, renderMath } from "./markdownMath";
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
function parseSafe(md: string): HTMLElement {
const html = marked.parse(md, { async: false }) as string;
const root = DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
ADD_ATTR: ["data-math"],
FORBID_TAGS: ["style", "form"],
FORBID_ATTR: ["style"],
RETURN_DOM: true,
}) as HTMLElement;
renderMath(root);
return root;
}
describe("markdown LaTeX math", () => {
it("renders inline $...$ and avoids currency false positives", () => {
const root = parseSafe(
"Energy $E = mc^2$ and CJK 设$x=1$时.\n\nPrices: $5 and $10, or $5-$10, or $ 5 $, or \\$x\\$.",
);
expect(root.querySelectorAll(".katex")).toHaveLength(2);
expect(root.querySelectorAll(".katex-display")).toHaveLength(0);
const paras = [...root.querySelectorAll("p")];
expect(paras[1]!.textContent).toBe("Prices: $5 and $10, or $5-$10, or $ 5 $, or $x$.");
});
it("prevents * and _ inside math from triggering emphasis while allowing emphasis around math", () => {
const root = parseSafe("Formula $(a)_1 + (b)_2$ and $a * b$ and $c * d$, plus **$x^2$**.");
expect(root.querySelector("em")).toBeNull();
expect(root.querySelectorAll(".katex")).toHaveLength(4);
expect(root.querySelector("strong .katex")).not.toBeNull();
});
it("renders multi-line, single-line, inline, and adjacent $$...$$ blocks", () => {
const root = parseSafe(
"Para\n$$\n\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}\n$$\n\n$$E = mc^2$$\n\n$$a$$ and $$b$$",
);
expect(root.querySelectorAll(".katex-display")).toHaveLength(4);
expect(root.querySelector("p")?.textContent).toBe("Para");
const lastP = [...root.querySelectorAll("p")].at(-1)!;
expect(lastP.querySelectorAll(".katex-display")).toHaveLength(2);
expect(lastP.textContent).toContain("and");
});
it("renders \\(...\\) and \\[...\\] without breaking escaped links", () => {
const root = parseSafe("Inline \\(x + y\\).\n\n\\[\nx^2 + y^2 = z^2\n\\]\n\n\\[text\\](https://example.com)");
expect(root.querySelectorAll(".katex")).toHaveLength(2);
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
const lastP = [...root.querySelectorAll("p")].at(-1)!;
expect(lastP.textContent).toBe("[text](https://example.com)");
});
it("renders ```math code blocks while keeping ```latex and inline code literal", () => {
const root = parseSafe("```math\n\\int_0^1 x^2 dx\n```\n\n```latex\n$x$\n```\n\nInline `$y$`.");
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
expect(root.querySelector("pre > code.language-latex")?.textContent).toBe("$x$\n");
expect(root.querySelector("p > code")?.textContent).toBe("$y$");
});
it("renders invalid LaTeX as an error node instead of throwing", () => {
const root = parseSafe("Bad $\\unknowncommand{x}$ and $$\\frac{1$$");
expect(root.querySelectorAll(".katex")).toHaveLength(1);
expect(root.querySelector(".katex-error")).not.toBeNull();
expect(root.textContent).toContain("\\unknowncommand");
});
it("blocks unsafe LaTeX trust commands and raw HTML style/script injection", () => {
const root = parseSafe(
[
"$\\href{javascript:alert(1)}{click}$",
'<div style="position:fixed">x</div>',
'<span data-math="inline"><img src=x onerror=alert(1)>a</span>',
].join("\n\n"),
);
expect(root.querySelector("a")).toBeNull();
expect(root.querySelector("img")).toBeNull();
expect(root.querySelector("div[style]")).toBeNull();
expect(root.querySelectorAll(".katex")).toHaveLength(2);
});
});
-215
Переглянути файл
@@ -1,215 +0,0 @@
/**
* LaTeX math support for Markdown (`marked` + `DOMPurify` + KaTeX).
*
* `mathExtension()` tokenizes `$$...$$`, `$...$`, `\[...\]`, `\(...\)`, and
* ```` ```math ```` blocks into sanitized-safe `<div|span data-math="display|inline">`
* placeholders, which survive `DOMPurify` (with `data-math` allowed) and are
* rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization.
*/
import katex from "katex";
import "katex/dist/katex.min.css";
import "./markdownMath.css";
import type { MarkedExtension, Tokens } from "marked";
interface MathToken extends Tokens.Generic {
type: "blockMath" | "inlineMath";
raw: string;
text: string;
display: boolean;
}
const escapeHtml = (s: string) =>
s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
export function mathPlaceholder(tex: string, display: boolean, block = display): string {
const tag = block ? "div" : "span";
const mode = display ? "display" : "inline";
return `<${tag} data-math="${mode}">${escapeHtml(tex)}</${tag}>`;
}
/** Finds the closing `delim` (`$$`, `\)`, or `\]`) skipping `\` escapes. Returns content end index or -1. */
function findClosingDelimiter(src: string, from: number, delim: string): number {
for (let i = from; i < src.length; i++) {
if (src.startsWith(delim, i)) return i;
if (src[i] === "\\") {
i++;
continue;
}
}
return -1;
}
/**
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
* like `$5 and $10` or `$5-$10` stays plain text while `$x$`, `设$x=1$`, etc. match.
*/
function matchInlineDollar(src: string): { end: number; text: string } | null {
if (src[0] !== "$" || src[1] === "$" || !src[1] || /\s/.test(src[1])) return null;
for (let i = 1; i < src.length; i++) {
const ch = src[i]!;
if (ch === "\\") {
i++;
continue;
}
if (ch === "\n" && (src[i + 1] === "\n" || (src[i + 1] === "\r" && src[i + 2] === "\n"))) {
return null;
}
if (ch === "$") {
if (i <= 1 || /\s/.test(src[i - 1]!)) continue;
const next = src[i + 1] ?? "";
if (next === "$" || /\d/.test(next)) return null;
const text = src.slice(1, i);
if (!text.trim()) return null;
return { end: i + 1, text };
}
}
return null;
}
/** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */
function matchInlineMath(src: string): { raw: string; text: string; display: boolean } | null {
if (src.startsWith("$$")) {
const close = findClosingDelimiter(src, 2, "$$");
if (close > 2) {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
}
return null;
}
if (src[0] === "$") {
const m = matchInlineDollar(src);
return m ? { raw: src.slice(0, m.end), text: m.text, display: false } : null;
}
if (src.startsWith("\\(")) {
const close = findClosingDelimiter(src, 2, "\\)");
if (close > 2) {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: false };
}
return null;
}
if (src.startsWith("\\[")) {
const close = findClosingDelimiter(src, 2, "\\]");
if (close > 2 && src[close + 2] !== "(") {
const text = src.slice(2, close);
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
}
return null;
}
return null;
}
const BLOCK_DOLLAR_MULTI = /^ {0,3}\$\$[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\$\$[ \t]*(?:\r?\n+|$)/;
const BLOCK_DOLLAR_SINGLE = /^ {0,3}\$\$((?:\\[\s\S]|[^$\n]|\$(?!\$))+?)\$\$[ \t]*(?:\r?\n+|$)/;
const BLOCK_BRACKET_MULTI = /^ {0,3}\\\[[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\\\][ \t]*(?:\r?\n+|$)/;
const BLOCK_BRACKET_SINGLE = /^ {0,3}\\\[((?:\\[\s\S]|[^\\\n]|\\(?!\]))+?)\\\][ \t]*(?:\r?\n+|$)/;
function matchBlockMath(src: string): { raw: string; text: string } | null {
for (const re of [BLOCK_DOLLAR_MULTI, BLOCK_DOLLAR_SINGLE, BLOCK_BRACKET_MULTI, BLOCK_BRACKET_SINGLE]) {
const m = re.exec(src);
if (m && m[1]!.trim()) return { raw: m[0], text: m[1]! };
}
return null;
}
/** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */
function maskInlineMath(src: string): string {
let out = "";
let i = 0;
while (i < src.length) {
if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") {
out += src.slice(i, i + 2);
i += 2;
continue;
}
if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) {
const m = matchInlineMath(src.slice(i));
if (m) {
out += m.raw.replace(/[^\r\n]/g, "a");
i += m.raw.length;
continue;
}
}
out += src[i]!;
i++;
}
return out;
}
export function mathExtension(): MarkedExtension {
return {
hooks: {
emStrongMask(src) {
return maskInlineMath(src);
},
},
renderer: {
code({ text, lang }) {
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "math") return false;
return `${mathPlaceholder(text, true, true)}\n`;
},
},
extensions: [
{
name: "blockMath",
level: "block",
start(src) {
const m = /\n {0,3}(?:\$\$|\\\[)/.exec(src);
return m ? m.index : undefined;
},
tokenizer(src): MathToken | undefined {
const m = matchBlockMath(src);
if (!m) return undefined;
return { type: "blockMath", raw: m.raw, text: m.text, display: true };
},
renderer(token) {
const t = token as MathToken;
return `${mathPlaceholder(t.text, true, true)}\n`;
},
},
{
name: "inlineMath",
level: "inline",
start(src) {
for (let i = 0; i < src.length; i++) {
const ch = src[i]!;
if (ch === "\\") {
const next = src[i + 1];
if (next === "(" || next === "[") return i;
i++;
continue;
}
if (ch === "$") return i;
}
return undefined;
},
tokenizer(src): MathToken | undefined {
const m = matchInlineMath(src);
if (!m) return undefined;
return { type: "inlineMath", raw: m.raw, text: m.text, display: m.display };
},
renderer(token) {
const t = token as MathToken;
return mathPlaceholder(t.text, t.display, false);
},
},
],
};
}
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
export function renderMath(root: ParentNode): void {
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
const mode = el.getAttribute("data-math");
el.removeAttribute("data-math");
if (mode !== "inline" && mode !== "display") return;
const tex = (el.textContent ?? "").trim();
if (!tex) return;
katex.render(tex, el, {
displayMode: mode === "display",
throwOnError: false,
strict: false,
trust: false,
});
});
}
+3 -8
Переглянути файл
@@ -1,24 +1,19 @@
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { mathExtension, renderMath } from "./markdownMath";
/** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */
const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
const marked = new Marked({ gfm: true, breaks: false });
export function markdownToSafeHtml(markdown: string): string {
const html = marked.parse(markdown, { async: false }) as string;
// Comments and docs come from anyone; a `<style>` here would restyle the whole IDE.
const root = DOMPurify.sanitize(html, {
return DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
ALLOWED_URI_REGEXP: ALLOWED_URI,
ADD_ATTR: ["data-math"],
FORBID_TAGS: ["style", "form"],
FORBID_ATTR: ["style"],
RETURN_DOM: true,
}) as HTMLElement;
renderMath(root);
return root.innerHTML;
});
}
+1 -7
Переглянути файл
@@ -1240,12 +1240,6 @@ const marks = {
read: Decoration.mark({ class: KIND_CLASS.read }),
write: Decoration.mark({ class: KIND_CLASS.write }),
};
/** The text a multi-line highlight paints with line backgrounds: a line class would also colour its indent. */
const lineText = {
text: Decoration.mark({ class: "cm-lsp-occurrence-text" }),
read: Decoration.mark({ class: "cm-lsp-occurrence-text" }),
write: Decoration.mark({ class: "cm-lsp-occurrence-text cm-lsp-occurrence-text-write" }),
};
const fullLines = {
text: Decoration.line({ class: KIND_CLASS.text }),
read: Decoration.line({ class: KIND_CLASS.read }),
@@ -1272,7 +1266,7 @@ function highlightDeco(doc: Text, tabSize: number, items: readonly HighlightItem
class: i.kind === "write" ? "cm-lsp-occurrence-tail cm-lsp-occurrence-tail-write" : "cm-lsp-occurrence-tail",
attributes: { style: `--lsp-occurrence-from: calc(${LINE_INSET}px + ${col}ch)` },
});
out.push(tail.range(first.from), lineText[i.kind].range(i.from, last.from));
out.push(tail.range(first.from));
for (let n = first.number + 1; n < last.number; n++) out.push(fullLines[i.kind].range(doc.line(n).from));
if (i.to > last.from) out.push(marks[i.kind].range(last.from, i.to));
}
-7
Переглянути файл
@@ -314,7 +314,6 @@ export const lspTheme = EditorView.theme({
// --- navigation ---------------------------------------------------------
".cm-lsp-link": {
color: "var(--link)",
WebkitTextFillColor: "currentcolor",
textDecoration: "underline",
textUnderlineOffset: "2px",
cursor: "pointer",
@@ -326,12 +325,6 @@ export const lspTheme = EditorView.theme({
"--lsp-occurrence-bg": "var(--bg-identifier-under-caret-write, color-mix(in srgb, var(--danger) 12%, transparent))",
},
".cm-lsp-occurrence": { backgroundColor: "var(--lsp-occurrence-bg)" },
// Text fill, not `color`: it reaches the syntax and semantic spans nested inside, and with the
// variable unset the declaration drops, so they keep their own colours.
"span.cm-lsp-occurrence, .cm-lsp-occurrence-text": { WebkitTextFillColor: "var(--fg-identifier-under-caret)" },
"span.cm-lsp-occurrence-write, .cm-lsp-occurrence-text-write": {
WebkitTextFillColor: "var(--fg-identifier-under-caret-write)",
},
// First line of a highlight over several lines: from its start column to the right edge,
// over the line's own background (the caret row's).
".cm-lsp-occurrence-tail": {
-20
Переглянути файл
@@ -72,26 +72,6 @@ describe("highlights of the element at the caret", () => {
expect(lines(v)[4]!.className).not.toContain("cm-lsp-occurrence");
});
it.each([
["text", ""],
["write", "-write"],
] as const)(
"marks exactly the text of a %s highlight over several lines for its foreground",
async (kind, suffix) => {
cmd.lspDocumentHighlights.mockImplementation(() => ok([{ range: range(1, 4, 3, 13), kind }]));
const v = editor(at(1, 4));
highlightUsages(v);
await vi.waitFor(() => expect(v.contentDOM.querySelector(".cm-lsp-occurrence-text")).not.toBeNull());
const text = (line: number) =>
[...lines(v)[line]!.querySelectorAll(`.cm-lsp-occurrence-text${suffix}`)].map((e) => e.textContent).join("");
// Not the indent before the start column; the last line is the highlight's own mark.
expect(text(1)).toBe("return a");
expect(text(2)).toBe(" .b()");
expect(text(3)).toBe("");
expect(lines(v)[3]!.querySelector(`span.cm-lsp-occurrence${suffix}`)?.textContent).toBe(" .c();");
},
);
it("keeps a single-line highlight on its text", async () => {
cmd.lspDocumentHighlights.mockImplementation(() => ok([{ range: range(6, 11, 6, 12), kind: "read" }]));
const v = editor(at(6, 11));
-11
Переглянути файл
@@ -369,17 +369,6 @@ describe("streamed replies", () => {
expect(container.querySelector("details p")?.textContent).toBe("text");
});
it("renders LaTeX math across streamed blocks", () => {
const text = "Inline $a + b$.\n\n$$\n\\frac{1}{2}\n$$\n\nTail";
const blocks = markdownBlocks(text);
expect(blocks).toHaveLength(3);
expect(blocks.join("")).toBe(text);
const { container } = render(<Markdown text={text} cwd="/repo" />);
expect(container.querySelectorAll(".katex")).toHaveLength(2);
expect(container.querySelector(".katex-display")).not.toBeNull();
expect(screen.queryByRole("button", { name: "Copy Code" })).toBeNull();
});
it("cuts only what streamed on after the blocks that ended", () => {
const before = markdownBlocks("One.\n\nTwo.\n\nThr");
const after = markdownBlocks("One.\n\nTwo.\n\nThree.\n\n- a", before);
+3 -5
Переглянути файл
@@ -11,7 +11,6 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
import { Marked } from "marked";
import DOMPurify from "dompurify";
import { highlightInto } from "@/editor/lsp/markdown";
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
import { iconNode } from "@/ui/iconNode";
import { tx } from "@/platform/i18n";
import { openExternalUrl } from "@/platform/openUrl";
@@ -38,7 +37,7 @@ const marked = new Marked({
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
},
},
}).use(mathExtension());
});
/** Rendered messages by text, least recently used first: reopening a conversation renders it again. */
const rendered = new Map<string, string>();
@@ -134,11 +133,10 @@ function renderHtml(text: string): string {
FORBID_TAGS: ["style", "form", "source"],
FORBID_ATTR: ["style", "srcset"],
ALLOW_DATA_ATTR: false,
// Only the mermaid and math placeholders written by the renderer above; data attributes
// Only the mermaid placeholder written by the renderer above; data attributes
// quoted in a reply stay out.
ADD_ATTR: ["data-mermaid", "data-math"],
ADD_ATTR: ["data-mermaid"],
}) as HTMLElement;
renderMath(root);
root.querySelectorAll("li").forEach(wrapLooseText);
// WebKit cuts controls inside <pre> out of a text selection, even when transparent.
root.querySelectorAll("pre").forEach((pre) => {
+52 -3
Переглянути файл
@@ -17,13 +17,24 @@ import {
registerMenuGroup,
registerMenuSlotItem,
registerOverlay,
registerSettingsPages,
registerStatusItem,
registerToolWindow,
toolWindowService,
} from "@/workbench/contributions";
import { AgentsStatus } from "./AgentsStatus";
import { activateSettingsPages } from "./settingsPages";
import { HOME_KIND, MCP_PAGE, REGISTRY_PAGE, SESSION_KIND, TASK_DRAG, TOOL_WINDOW, providerIcon } from "./model";
import {
AGENTS_GROUP,
HOME_KIND,
MCP_PAGE,
POLICY_PAGE,
REGISTRY_PAGE,
SESSION_KIND,
TASK_DRAG,
TOOL_WINDOW,
WORKING_STATUS_PAGE,
providerIcon,
} from "./model";
import { sendPaths, sendSelection, trackEditorCopies } from "./references";
import { focusedSession, inputSession } from "./sessionFocus";
import { cycleFocusedEffort } from "./effortFocus";
@@ -43,7 +54,45 @@ import { TaskStatusMark } from "./TaskStatusMark";
import { taskActions, useAgentsHeaderMenu } from "./taskActions";
import { replyActions } from "./replyActions";
export { activateSettingsPages } from "./settingsPages";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: WORKING_STATUS_PAGE,
title: "Working Status",
group: AGENTS_GROUP,
// After Chat.
order: 465,
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
}
export function activate(): () => void {
const sync = (root: string | null | undefined) => {
-43
Переглянути файл
@@ -1,43 +0,0 @@
import { lazyComponent } from "@/ui";
import { registerSettingsPages } from "@/workbench/contributions";
import { AGENTS_GROUP, MCP_PAGE, POLICY_PAGE, REGISTRY_PAGE, WORKING_STATUS_PAGE } from "./model";
/** Settings › Agents › Coding Agents and Settings › Agents › External MCP Servers (also used by the Settings window). */
export function activateSettingsPages(): () => void {
return registerSettingsPages([
{
id: REGISTRY_PAGE,
title: "Coding Agents",
group: AGENTS_GROUP,
// First in Agents, which sits after Languages & Frameworks and before Tools.
order: 450,
keywords: ["agent", "acp", "registry", "install", "update", "coding agent"],
component: lazyComponent(() => import("./AgentRegistryPage").then((m) => m.AgentRegistryPage)),
},
{
id: WORKING_STATUS_PAGE,
title: "Working Status",
group: AGENTS_GROUP,
// After Chat.
order: 465,
keywords: ["agent", "status", "playful", "words", "working", "spinner", "fun", "delay", "seconds"],
component: lazyComponent(() => import("./WorkingStatusPage").then((m) => m.WorkingStatusPage)),
},
{
id: MCP_PAGE,
title: "External MCP Servers",
group: AGENTS_GROUP,
order: 475,
keywords: ["mcp", "model context protocol", "servers", "tools", "agent"],
component: lazyComponent(() => import("./McpServersPage").then((m) => m.McpServersPage)),
},
{
id: POLICY_PAGE,
title: "Command Permissions",
group: AGENTS_GROUP,
order: 490,
keywords: ["agent", "policy", "security", "whitelist", "blacklist", "permission", "command", "exec"],
component: lazyComponent(() => import("./AgentPolicyPage").then((m) => m.AgentPolicyPage)),
},
]);
}
+6
Переглянути файл
@@ -22,6 +22,12 @@ import { installLaunchHandling, installLightEditAutoClose, windowActions } from
import { WorkspaceDialogHost } from "./WorkspaceDialog";
import { installWindowGroups } from "@/platform/windowGroups";
/** The UI locale of a secondary (Settings, comparison) window. */
export const activateLocale = installLocaleSync;
/** Native menu items of a secondary window that runs actions itself (comparison). */
export const activateMenuBridge = installMenuBridge;
export { confirmLeave } from "./closeGuard";
export function activate(): () => void {
const disposers = [
installLocaleSync(),
+31 -62
Переглянути файл
@@ -40,7 +40,6 @@ import {
producerFor,
sortProblems,
useProblems,
type FileDiagnostics,
type ProblemOrder,
type ProblemsMap,
} from "./problemsStore";
@@ -114,8 +113,9 @@ export function useProblemsHeaderMenu(): MenuItem[] {
const group = (s: Severity): "error" | "warning" | "info" => (s === "hint" ? "info" : s);
type FileNode = { kind: "file"; key: string; path: string; items: Diagnostic[]; error: boolean };
type Node = FileNode | { kind: "diag"; key: string; path: string; d: Diagnostic };
type Node =
| { kind: "file"; key: string; path: string; items: Diagnostic[] }
| { kind: "diag"; key: string; path: string; d: Diagnostic };
/** The inspection that reported `d` (for Disable inspection / Change Severity). */
export function diagInspection(map: ProblemsMap, path: string, d: Diagnostic): InspectionRef | null {
@@ -129,64 +129,23 @@ const plural = (n: number, word: string) => (n ? `${n} ${word}${n === 1 ? "" : "
const SEVERITY_ICON: Record<Severity, string> = { error: "error", warning: "warning", info: "info", hint: "info" };
interface CachedFileNode {
path: string;
show: ViewState["show"];
order: ProblemOrder;
node: FileNode | null;
}
// Keyed by the file's sources map, which the store replaces only when that file's diagnostics
// change: a single-file update re-filters and re-sorts that file alone.
const fileNodes = new WeakMap<FileDiagnostics, CachedFileNode>();
function fileNode(map: ProblemsMap, path: string, show: ViewState["show"], order: ProblemOrder): FileNode | null {
const sources = map.get(path);
if (!sources) return null;
const hit = fileNodes.get(sources);
if (
hit?.path === path &&
hit.show.error === show.error &&
hit.show.warning === show.warning &&
hit.show.info === show.info &&
hit.order.bySeverity === order.bySeverity &&
hit.order.byName === order.byName
)
return hit.node;
const items = sortProblems(
fileDiagnostics(map, path).filter((d) => show[group(d.severity)]),
order,
);
const node: FileNode | null = items.length
? { kind: "file", key: path, path, items, error: items.some((d) => d.severity === "error") }
: null;
fileNodes.set(sources, { path, show: { ...show }, order: { ...order }, node });
return node;
}
export function buildProblemNodes(
map: ProblemsMap,
paths: readonly string[],
show: ViewState["show"],
order: ProblemOrder = DEFAULT_PROBLEM_ORDER,
): FileNode[] {
const files: FileNode[] = [];
): Node[] {
const files: Node[] = [];
for (const path of paths) {
const node = fileNode(map, path, show, order);
if (node) files.push(node);
const items = sortProblems(
fileDiagnostics(map, path).filter((d) => show[group(d.severity)]),
order,
);
if (!items.length) continue;
files.push({ kind: "file", key: path, path, items });
}
return files.sort((a, b) => Number(!a.error) - Number(!b.error) || a.path.localeCompare(b.path));
}
const diagNodes = new WeakMap<FileNode, Node[]>();
function diagChildren(n: FileNode): Node[] {
let children = diagNodes.get(n);
if (!children) {
children = n.items.map((d, i) => ({ kind: "diag", key: `${n.path}\u0000${i}`, path: n.path, d }));
diagNodes.set(n, children);
}
return children;
const rank = (n: Node) => (n.kind === "file" ? (n.items.some((d) => d.severity === "error") ? 0 : 1) : 2);
return files.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path));
}
function open(path: string, d: Diagnostic, focus = true): Promise<void> {
@@ -241,15 +200,19 @@ export function ProblemsHeaderActions() {
/** Scope tabs in the tool window header: "File: name 2" / "Project Errors". */
export function ProblemsTabs() {
const map = useProblems((s) => s.map);
const tab = useProblemsView((s) => s.tab);
const setTab = useProblemsView((s) => s.setTab);
const current = useCurrentPath();
const fileCount = useProblems((s) => {
if (!current) return 0;
const c = countSeverities(filePaths(s.map, current).flatMap((path) => fileDiagnostics(s.map, path)));
return c.error + c.warning;
});
const projectErrors = useProblems((s) => s.counts.error);
const fileCount = current
? countSeverities(filePaths(map, current).flatMap((path) => fileDiagnostics(map, path)))
: null;
const projectErrors = useMemo(() => {
let n = 0;
for (const sources of map.values())
for (const items of sources.values()) n += items.filter((d) => d.severity === "error").length;
return n;
}, [map]);
return (
<Tabs
variant="compact"
@@ -268,7 +231,10 @@ export function ProblemsTabs() {
"File"
),
text: "File",
trailing: fileCount > 0 ? <span className={styles.tabCount}>{fileCount}</span> : undefined,
trailing:
fileCount && fileCount.error + fileCount.warning > 0 ? (
<span className={styles.tabCount}>{fileCount.error + fileCount.warning}</span>
) : undefined,
},
{
id: "project",
@@ -331,7 +297,10 @@ export function ProblemsView() {
);
const getChildren = useCallback(
(n: Node): Node[] | undefined => (n.kind === "file" ? diagChildren(n) : undefined),
(n: Node): Node[] | undefined =>
n.kind === "file"
? n.items.map((d, i) => ({ kind: "diag", key: `${n.path}\u0000${i}`, path: n.path, d }) as Node)
: undefined,
[],
);
+6 -1
Переглянути файл
@@ -29,7 +29,12 @@ import { installWorkspaceEditUndo } from "./workspaceUndo";
const EDITOR_WHEN = "textEditorActive && (editorFocus || !toolWindowFocus)";
function useErrorBadge(): number | null {
return useProblems((s) => s.counts.error || null);
return useProblems((s) => {
let n = 0;
for (const sources of s.map.values())
for (const items of sources.values()) for (const d of items) if (d.severity === "error") n++;
return n || null;
});
}
export function activate(): () => void {
-52
Переглянути файл
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it } from "vitest";
import type { Diagnostic } from "@/bindings";
import { useProject } from "@/platform/project";
import {
applyDiagnosticsEvent,
clearProblems,
@@ -8,7 +7,6 @@ import {
currentProblemsPath,
fileDiagnostics,
filePaths,
installProblemsEvents,
mergeDiagnostics,
problemsReport,
profiledProblems,
@@ -153,53 +151,3 @@ describe("problemsReport", () => {
expect(problemsReport(mergeDiagnostics(new Map(), "/p/a", "x", [d(0, "info")]), "/p")).toBeNull();
});
});
describe("incremental bookkeeping", () => {
let seed = 7;
const random = (n: number) => (seed = (seed * 48271) % 2147483647) % n;
const SEVERITIES = ["error", "warning", "info", "hint"] as const;
const items = (): Diagnostic[] =>
Array.from({ length: random(5) }, () => ({
...d(random(3), SEVERITIES[random(4)]),
range: { start: { line: random(3), col: random(2) }, end: { line: 3, col: 0 } },
code: String(random(1000)),
}));
// The merge as it was before it was cached.
const fullMerge = (map: ReturnType<typeof useProblems.getState>["map"], path: string) =>
[...(map.get(path)?.values() ?? [])]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity),
);
it("keeps the project counts and each file's merged list equal to a full rescan", () => {
clearProblems();
useProject.setState({ settings: {} as never });
const off = installProblemsEvents();
try {
for (let step = 0; step < 400; step++) {
if (step === 150)
useProject.setState({
settings: { inspections: { default: { "lsp:eslint": { enabled: false } } } } as never,
});
if (step === 250)
useProject.setState({
settings: { inspections: { default: { "lsp:ra": { severity: "weakWarning" } } } } as never,
});
if (step === 300) clearProblems();
const path = `/p/${random(12)}.rs`;
applyDiagnosticsEvent(path, ["ra", "eslint"][random(2)]!, items());
const { map, counts } = useProblems.getState();
expect(counts).toEqual(projectCounts(map));
for (const p of map.keys()) expect(fileDiagnostics(map, p)).toEqual(fullMerge(map, p));
}
} finally {
off();
useProject.setState({ settings: {} as never });
clearProblems();
}
});
});
+13 -37
Переглянути файл
@@ -49,26 +49,18 @@ export function mergeDiagnostics(
const SEVERITY_ORDER: Record<Severity, number> = { error: 0, warning: 1, info: 2, hint: 3 };
// A file's sources map is replaced whenever its diagnostics change, so it keys the merged list.
const merged = new WeakMap<FileDiagnostics, readonly Diagnostic[]>();
/** All diagnostics of a file across sources, ordered by position then severity. */
export function fileDiagnostics(map: ProblemsMap, path: string): readonly Diagnostic[] {
export function fileDiagnostics(map: ProblemsMap, path: string): Diagnostic[] {
const sources = map.get(path);
if (!sources) return [];
let items = merged.get(sources);
if (!items) {
items = [...sources.values()]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity],
);
merged.set(sources, items);
}
return items;
return [...sources.values()]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity],
);
}
/** The producer (inspection) that reported `d`, one of `path`'s problems in `map`. */
@@ -166,34 +158,21 @@ interface ProblemsState {
raw: ProblemsMap;
/** What the views show. */
map: ProblemsMap;
/** `projectCounts(map)`, kept up to date per event. */
counts: SeverityCounts;
}
const NO_COUNTS: SeverityCounts = { error: 0, warning: 0, info: 0, hint: 0 };
export const useProblems = create<ProblemsState>(() => ({ raw: new Map(), map: new Map(), counts: NO_COUNTS }));
function recount(counts: SeverityCounts, removed: readonly Diagnostic[], added: readonly Diagnostic[]) {
const c = { ...counts };
for (const d of removed) c[d.severity]--;
for (const d of added) c[d.severity]++;
return c;
}
export const useProblems = create<ProblemsState>(() => ({ raw: new Map(), map: new Map() }));
export function applyDiagnosticsEvent(path: string, source: string, items: readonly Diagnostic[]) {
useProblems.setState((s) => {
const raw = mergeDiagnostics(s.raw, path, source, items);
if (raw === s.raw) return s;
const map = mergeDiagnostics(s.map, path, source, applyProfile(inspectionProfile(), source, items));
if (map === s.map) return { raw };
const before = s.map.get(path)?.get(source) ?? [];
return { raw, map, counts: recount(s.counts, before, map.get(path)?.get(source) ?? []) };
return { raw, map };
});
}
export function clearProblems() {
useProblems.setState({ raw: new Map(), map: new Map(), counts: NO_COUNTS });
useProblems.setState({ raw: new Map(), map: new Map() });
}
export function installProblemsEvents(): () => void {
@@ -201,10 +180,7 @@ export function installProblemsEvents(): () => void {
// Typo, file references, SQL: inspections the editor runs itself.
const offLocal = onLocalDiagnostics(applyDiagnosticsEvent);
const offProfile = subscribeInspectionProfile(() =>
useProblems.setState((s) => {
const map = profiledProblems(s.raw, inspectionProfile());
return { map, counts: projectCounts(map) };
}),
useProblems.setState((s) => ({ map: profiledProblems(s.raw, inspectionProfile()) })),
);
return () => {
off();
-92
Переглянути файл
@@ -1,92 +0,0 @@
/**
* Problems tool window under a diagnostics storm: a workspace of 2,000 files with 30,000
* diagnostics, then 200 single-file updates, each rendered by the mounted header tabs and list.
* One sample is the time for all 200 updates; prints each sample and the median.
* Skipped unless asked for:
*
* PROBLEMS_BENCH=1 pnpm vitest run src/features/code-insight/problemsStorm.bench.test.tsx --silent=false
*/
import { act, render } from "@testing-library/react";
import { describe, it } from "vitest";
import type { Diagnostic, Severity } from "@/bindings";
import { ProblemsTabs, ProblemsView, useProblemsView } from "./ProblemsView";
import { applyDiagnosticsEvent, clearProblems } from "./problemsStore";
const FILES = 2000;
const LSP_PER_FILE = 10;
const LINT_PER_FILE = 5;
const UPDATES = 200;
let seed = 1;
const random = () => (seed = (seed * 1103515245 + 12345) % 2 ** 31) / 2 ** 31;
const SEVERITIES: Severity[] = ["error", "warning", "warning", "info", "hint"];
function diagnostics(count: number, salt: number): Diagnostic[] {
return Array.from({ length: count }, (_, i) => {
const line = Math.floor(random() * 400);
const col = Math.floor(random() * 80);
return {
range: { start: { line, col }, end: { line, col: col + 4 } },
severity: SEVERITIES[(i + salt) % SEVERITIES.length]!,
message: `Problem ${Math.floor(random() * 500)} near symbol${salt}_${i}`,
source: null,
code: null,
} as Diagnostic;
});
}
const paths = Array.from({ length: FILES }, (_, i) => `/p/src/module${i % 40}/File${i}.ts`);
const initial = paths.map((path, i) => ({
path,
lsp: diagnostics(LSP_PER_FILE, i),
lint: diagnostics(LINT_PER_FILE, i + 1),
}));
const updates = Array.from({ length: UPDATES }, (_, k) => ({
path: paths[Math.floor(random() * FILES)]!,
items: diagnostics(LSP_PER_FILE, k + 7),
}));
function loadWorkspace() {
clearProblems();
for (const f of initial) {
applyDiagnosticsEvent(f.path, "lsp", f.lsp);
applyDiagnosticsEvent(f.path, "eslint", f.lint);
}
}
function storm(tab: "file" | "project") {
loadWorkspace();
useProblemsView.setState({ tab });
const view = render(
<>
<ProblemsTabs />
<ProblemsView />
</>,
);
// Only the updates are timed, not loading the workspace or the first render.
const start = performance.now();
for (const u of updates) act(() => applyDiagnosticsEvent(u.path, "lsp", u.items));
const ms = performance.now() - start;
view.unmount();
return ms;
}
const RUNS = 7;
function measure(tab: "file" | "project") {
storm(tab); // warm-up
const samples = Array.from({ length: RUNS }, () => storm(tab)).sort((a, b) => a - b);
const median = samples[RUNS >> 1]!;
console.log(
`${tab} tab: median ${median.toFixed(1)} ms per ${UPDATES} updates (${(median / UPDATES).toFixed(2)} ms/update); ` +
`samples ${samples.map((s) => s.toFixed(1)).join(", ")}`,
);
}
describe.skipIf(!process.env.PROBLEMS_BENCH)(
`Problems: ${FILES} files, ${FILES * (LSP_PER_FILE + LINT_PER_FILE)} diagnostics, ${UPDATES} single-file updates`,
() => {
it("Project Errors tab", () => measure("project"), 600_000);
it("File tab", () => measure("file"), 600_000);
},
);
+1 -82
Переглянути файл
@@ -2,8 +2,7 @@ import { describe, expect, it } from "vitest";
import { groupUsages, trimPreview, usageCount } from "./usages";
import { serversSummary, type ServerEntry } from "./servers";
import { buildProblemNodes } from "./ProblemsView";
import type { Diagnostic } from "@/bindings";
import { mergeDiagnostics, sortProblems, type ProblemOrder, type ProblemsMap } from "./problemsStore";
import { mergeDiagnostics, sortProblems } from "./problemsStore";
import { toggleExcludedUsages } from "./UsagesView";
import { childId, directionLabel } from "./hierarchy";
@@ -67,86 +66,6 @@ describe("buildProblemNodes", () => {
expect(errorsOnly.map((n) => n.key)).toEqual(["/b"]);
expect(errorsOnly[0]!.kind === "file" && errorsOnly[0]!.items.length).toBe(1);
});
it("matches a full rebuild across single-file updates, filters and sort orders", () => {
let seed = 11;
const random = (n: number) => (seed = (seed * 48271) % 2147483647) % n;
const SEVERITIES = ["error", "warning", "info", "hint"] as const;
const MESSAGES = ["alpha", "Alpha", "beta 2", "beta 10"];
const items = (): Diagnostic[] =>
Array.from({ length: random(6) }, () => ({
range: { start: { line: random(3), col: random(2) }, end: { line: 3, col: 0 } },
severity: SEVERITIES[random(4)]!,
message: MESSAGES[random(4)]!,
source: null,
code: String(random(1000)),
}));
// buildProblemNodes as it was before per-file caching.
const rebuild = (map: ProblemsMap, paths: string[], show: Record<string, boolean>, order: ProblemOrder) => {
const files = paths.flatMap((path) => {
const all = [...(map.get(path)?.values() ?? [])]
.flat()
.sort(
(a, b) =>
a.range.start.line - b.range.start.line ||
a.range.start.col - b.range.start.col ||
SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity),
);
const shown = sortProblems(
all.filter((d) => show[d.severity === "hint" ? "info" : d.severity]),
order,
);
return shown.length ? [{ path, items: shown }] : [];
});
const rank = (f: { items: Diagnostic[] }) => (f.items.some((d) => d.severity === "error") ? 0 : 1);
return files.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path));
};
// Neighbours differ in one flag, so a cache that ignored any of them would serve stale nodes.
const shows = ["111", "101", "100", "000", "010", "011"].map(([e, w, i]) => ({
error: e === "1",
warning: w === "1",
info: i === "1",
}));
const orders = ["10", "00", "01", "11"].map(([s, n]) => ({ bySeverity: s === "1", byName: n === "1" }));
let map: ProblemsMap = new Map();
for (let step = 0; step < 300; step++) {
const path = `/p/${["b", "A", "a", "c10", "c2"][random(5)]}/${random(4)}.ts`;
map = mergeDiagnostics(map, path, ["lsp", "eslint"][random(2)]!, items());
const show = shows[Math.floor(step / 20) % shows.length]!;
const order = orders[Math.floor(step / 35) % orders.length]!;
const paths = [...map.keys()];
const nodes = buildProblemNodes(map, paths, { ...show }, { ...order });
expect(nodes.map((n) => ({ path: n.path, items: n.items }))).toEqual(rebuild(map, paths, show, order));
const some = paths.filter((_, i) => i % 3 === 0);
expect(buildProblemNodes(map, some, show, order).map((n) => ({ path: n.path, items: n.items }))).toEqual(
rebuild(map, some, show, order),
);
}
});
it("reuses the nodes of files an update didn't touch", () => {
const diag = (line: number) => ({
range: { start: { line, col: 0 }, end: { line, col: 1 } },
severity: "error" as const,
message: "x",
source: null,
code: null,
});
const show = { error: true, warning: true, info: true };
let map = mergeDiagnostics(new Map(), "/a", "s", [diag(1)]);
map = mergeDiagnostics(map, "/b", "s", [diag(2)]);
const [a, b] = buildProblemNodes(map, ["/a", "/b"], show);
map = mergeDiagnostics(map, "/b", "s", [diag(3)]);
const [a2, b2] = buildProblemNodes(map, ["/a", "/b"], show);
expect(a2).toBe(a);
expect(b2).not.toBe(b);
const shared = map.get("/a")!;
const twice = new Map([
["/a", shared],
["/c", shared],
]);
expect(buildProblemNodes(twice, ["/a", "/c"], show).map((n) => n.path)).toEqual(["/a", "/c"]);
});
});
describe("hierarchy", () => {
-3
Переглянути файл
@@ -370,9 +370,6 @@
font-size: var(--fs-small);
color: var(--fg-muted);
}
.formFull {
grid-column: 1 / -1;
}
.paramInput {
font-family: var(--openidea-editor-font, var(--font-mono));
font-weight: var(--fw-code);
+1 -1
Переглянути файл
@@ -454,7 +454,7 @@ export function DatabaseView() {
case "source":
return sourceIcon(n.source);
case "database":
return "db-database";
return "database";
case "schema":
return "db-schema";
case "folder":
+6 -184
Переглянути файл
@@ -1,42 +1,34 @@
/**
* Dialogs of the Database tree's object actions, after IDEA's: Rename, Confirm
* Drop, Truncate, Modify Table / New Table, New Database / New Schema (with a
* Preview of the SQL they run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
* Drop, Truncate, Modify Table / New Table (with a Preview of the SQL they
* run), Remove Data Source, Data Source from URL, and the Quick Documentation popup.
*/
import { useEffect, useMemo, useRef, useState } from "react";
import { call, commands, type DbColumnInfo, type DbDriver } from "@/platform/ipc";
import { highlightInto } from "@/editor/lsp/markdown";
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, Select, T, type SelectOption } from "@/ui";
import { Button, Checkbox, Dialog, IconButton, Input, Popup, Icon, T } from "@/ui";
import { parseSourceUrl, sourceLabel, splitTarget } from "./model";
import { nodeTarget, schemaObjectOf, tableOf, type DbNode } from "./nodes";
import {
alterTableSql,
canAlterColumn,
createDatabaseSql,
createSchemaSql,
createTableSql,
draftOf,
dropDatabaseSql,
dropSql,
ident,
reference,
renameSql,
truncateSql,
type ColumnDraft,
templateOf,
type CreateOptions,
type DbObjectRef,
} from "./objects";
import {
closeDialog,
detailsKey,
connectedTargets,
createDatabase,
dropDatabase,
loadDetails,
openSourceDialog,
readableDdl,
refresh,
renameSource,
runSql,
sourceById,
@@ -88,15 +80,14 @@ function objectName(o: DbObjectRef): string {
function useRunner() {
const [busy, setBusy] = useState(false);
const running = useRef(false);
const runAndClose = async (id: string, statements: string[]): Promise<boolean> => {
if (running.current) return false;
const runAndClose = async (id: string, statements: string[]) => {
if (running.current) return;
running.current = true;
setBusy(true);
const ok = await runSql(id, statements);
running.current = false;
setBusy(false);
if (ok) closeDialog();
return ok;
};
return { busy, runAndClose };
}
@@ -125,7 +116,7 @@ function RenameDialog({ id, object }: { id: string; object: DbObjectRef | null }
width={480}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: () => void submit() },
{ label: "Refactor", role: "default", disabled: busy || !name.trim(), onClick: submit },
]}
>
<div className={styles.dialogBody}>
@@ -222,169 +213,6 @@ function TruncateDialog({ id, schema, table }: { id: string; schema: string; tab
);
}
// ---- New Database / New Schema / Drop database ---------------------------------
const TEMPLATES: SelectOption[] = [
{ value: "", label: "Server default" },
...["template0", "template1"].map((name) => ({ value: name, label: name, verbatim: true })),
];
/** An optional text field of the create dialogs: empty leaves it to the server. */
function OptionField({
id,
label,
value,
onChange,
}: {
id: string;
label: string;
value: string;
onChange: (value: string) => void;
}) {
return (
<>
<label className={styles.formLabel} htmlFor={id}>
{tx(label)}
</label>
<Input id={id} placeholder="Server default" value={value} onChange={(e) => onChange(e.target.value)} />
</>
);
}
/** New › Database (`database`) or New › Schema (`schema`) in target `id`. */
function CreateDialog({ id, what }: { id: string; what: "database" | "schema" }) {
const driver = driverOf(id);
const [name, setName] = useState("");
const [opts, setOpts] = useState<CreateOptions>({});
const { busy: running, runAndClose } = useRunner();
const [creating, setCreating] = useState(false);
const busy = running || creating;
const sql = (what === "database" ? createDatabaseSql : createSchemaSql)(driver, name.trim() || "<name>", opts);
const submit = async () => {
if (what === "schema") {
if (await runAndClose(id, [sql])) void refresh(id);
return;
}
setCreating(true);
if (await createDatabase(id, templateOf(driver, opts), sql)) closeDialog();
else setCreating(false);
};
const field = (key: keyof CreateOptions, label: string) => (
<OptionField
id={`db-new-${key}`}
label={label}
value={opts[key] ?? ""}
onChange={(value) => setOpts((o) => ({ ...o, [key]: value }))}
/>
);
return (
<Dialog
open
onClose={closeDialog}
title={what === "database" ? "New Database" : "New Schema"}
width={560}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "OK", role: "default", disabled: busy || !name.trim(), onClick: submit },
]}
>
<div className={styles.form}>
<label className={styles.formLabel} htmlFor="db-new-name">
<T>Name:</T>
</label>
<Input id="db-new-name" autoFocus value={name} onChange={(e) => setName(e.target.value)} />
{what === "database" && driver === "postgres" && (
<>
{field("owner", "Owner:")}
<label className={styles.formLabel} htmlFor="db-new-template">
<T>Template:</T>
</label>
<Select
id="db-new-template"
value={opts.template ?? ""}
options={TEMPLATES}
onChange={(template) => setOpts((o) => ({ ...o, template }))}
/>
<span />
<span className={styles.formHint}>
<T>Restoring a dump needs template0: template1 can already hold extensions and schemas.</T>
</span>
{field("encoding", "Encoding:")}
{field("tablespace", "Tablespace:")}
</>
)}
{what === "database" && driver === "sqlServer" && field("collation", "Collation:")}
{what === "schema" && driver === "mysql" && (
<>
{field("charset", "Character set:")}
{field("collation", "Collation:")}
</>
)}
{what === "schema" && driver !== "mysql" && field("owner", "Owner:")}
<div className={styles.formFull}>
<SqlPreview sql={sql} />
</div>
</div>
</Dialog>
);
}
/** PostgreSQL 13 added `drop database … with (force)`. */
const PG_FORCE_DROP = 130000;
function DropDatabaseDialog({ id, database }: { id: string; database: string }) {
const driver = driverOf(id);
const [force, setForce] = useState(false);
const [version, setVersion] = useState<number | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
if (driver !== "postgres") return;
let live = true;
void withConnection(id, () => call(commands.dbServerVersion(id)))
.then((v) => live && setVersion(v))
.catch(() => {});
return () => {
live = false;
};
}, [id, driver]);
const canForce = driver === "sqlServer" || (version ?? 0) >= PG_FORCE_DROP;
const sql = dropDatabaseSql(driver, database, force && canForce);
const submit = async () => {
setBusy(true);
if (await dropDatabase(id, database, sql)) closeDialog();
else setBusy(false);
};
return (
<Dialog
open
onClose={closeDialog}
title="Confirm Drop"
width={520}
buttons={[
{ label: "Cancel", role: "cancel" },
{ label: "OK", role: "default", disabled: busy, onClick: () => void submit() },
]}
>
<div className={styles.dialogBody}>
<div className={styles.dialogLead}>
{tx`Drop database`} <strong>{database}</strong>
{tx`? This cannot be undone.`}
</div>
<span className={styles.formHint}>
<T>The IDE closes its own connections to the database first.</T>
</span>
<Checkbox
checked={force && canForce}
onChange={setForce}
disabled={!canForce}
label="Close the sessions of other clients"
/>
<SqlPreview sql={sql} />
</div>
</Dialog>
);
}
// ---- Modify Table / New Table -----------------------------------------------
const TYPES: Record<DbDriver, string[]> = {
@@ -898,12 +726,6 @@ export function ObjectDialogs() {
return <DropDialog id={dialog.id} object={dialog.object} />;
case "truncate":
return <TruncateDialog id={dialog.id} schema={dialog.schema} table={dialog.table} />;
case "createDatabase":
return <CreateDialog id={dialog.id} what="database" />;
case "createSchema":
return <CreateDialog id={dialog.id} what="schema" />;
case "dropDatabase":
return <DropDatabaseDialog id={dialog.id} database={dialog.database} />;
case "modifyTable":
return (
<ModifyTableDialog
+5 -33
Переглянути файл
@@ -39,41 +39,13 @@ const PAGE_SIZES = ["100", "500", "1000", "5000"];
export { tableTitle } from "./tableInput";
/** WHERE, ORDER BY and page of a table tab, kept when a tab that is no longer kept alive mounts again. */
interface TableViewState {
offset: number;
limit: number;
sort: DbSortKey[];
filterText: string;
filter: string;
}
const MAX_VIEW_STATES = 100;
const viewStates = new Map<string, TableViewState>();
function rememberViewState(key: string, state: TableViewState) {
viewStates.delete(key);
viewStates.set(key, state);
if (viewStates.size > MAX_VIEW_STATES) viewStates.delete(viewStates.keys().next().value!);
}
/** Test hook: forget the remembered table view states. */
export function _resetTableViewStates() {
viewStates.clear();
}
export function TableEditor({ input }: { input: EditorInput }) {
const ref = input.data as TableRef;
const [initial] = useState(() => viewStates.get(input.key));
const [offset, setOffset] = useState(initial?.offset ?? 0);
const [limit, setLimit] = useState(initial?.limit ?? 500);
const [sort, setSort] = useState<DbSortKey[]>(initial?.sort ?? []);
const [filterText, setFilterText] = useState(initial?.filterText ?? "");
const [filter, setFilter] = useState(initial?.filter ?? "");
useEffect(
() => rememberViewState(input.key, { offset, limit, sort, filterText, filter }),
[input.key, offset, limit, sort, filterText, filter],
);
const [offset, setOffset] = useState(0);
const [limit, setLimit] = useState(500);
const [sort, setSort] = useState<DbSortKey[]>([]);
const [filterText, setFilterText] = useState("");
const [filter, setFilter] = useState("");
const [nonce, setNonce] = useState(0);
const [edits, setEdits] = useState<PendingEdits>(emptyEdits);
const [panel, setPanel] = useState<DataPanel | null>(null);
Loaded 100 of 200 files, more files were not shown because too many files have changed in this diff. Show more