дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-27 21:12:34 +02:00
Порівняти коміти
19
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
2e5d7c0c79 | ||
|
|
3beadbcf63 | ||
|
|
ac58b3380b | ||
|
|
c9bf8a3502 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a |
No files matched your search
@@ -30,7 +30,7 @@ jobs:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
@@ -111,9 +111,10 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-latest, ubuntu-latest, windows-latest]
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ matrix.os == 'ubuntu-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || matrix.os }}
|
||||
# Self-hosted runners (scripts/selfhost-runner for Linux, a Mac with the macOS/ARM64 labels) only
|
||||
# for trusted events, and only while the SELFHOSTED_RUNNERS repository variable is 'true':
|
||||
# runs-on cannot fall back when none is online. Windows always runs GitHub-hosted.
|
||||
runs-on: ${{ matrix.os != 'windows-latest' && vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && (matrix.os == 'macos-latest' && fromJSON('["self-hosted", "macOS", "ARM64"]') || fromJSON('["self-hosted", "openidea-selfhosted"]')) || matrix.os }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -137,6 +138,12 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
echo "CARGO_INCREMENTAL=1" >> "$GITHUB_ENV"
|
||||
# The Linux runner containers set CARGO_TARGET_DIR; elsewhere keep it next to the checkout,
|
||||
# which actions/checkout cleans on every run.
|
||||
if [ -z "${CARGO_TARGET_DIR:-}" ]; then
|
||||
CARGO_TARGET_DIR="$(dirname "$RUNNER_WORKSPACE")/cargo-target"
|
||||
echo "CARGO_TARGET_DIR=$CARGO_TARGET_DIR" >> "$GITHUB_ENV"
|
||||
fi
|
||||
size=$(du -sm "$CARGO_TARGET_DIR" 2>/dev/null | cut -f1 || true)
|
||||
if [ "${size:-0}" -gt 40000 ]; then
|
||||
echo "$CARGO_TARGET_DIR is ${size} MB; clearing it"
|
||||
@@ -216,7 +223,7 @@ jobs:
|
||||
name: Rust checks
|
||||
needs: [changes, rust]
|
||||
if: always()
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- env:
|
||||
@@ -327,7 +334,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.deny == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
@@ -339,7 +346,8 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.frontend == 'true'
|
||||
timeout-minutes: 30
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
# Chromium and vitest need more CPU than the light runners have; GitHub-hosted runners are faster here.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
# scripts/smoke-paths.test.ts runs `cargo metadata`, which is not preinstalled in the runner container.
|
||||
@@ -366,7 +374,7 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.catalog == 'true'
|
||||
timeout-minutes: 15
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v5
|
||||
@@ -384,7 +392,8 @@ jobs:
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
timeout-minutes: 45
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
# Chromium and vitest need more CPU than the light runners have; GitHub-hosted runners are faster here.
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
|
||||
@@ -78,7 +78,7 @@ jobs:
|
||||
name: Changes
|
||||
# Self-hosted runners (scripts/selfhost-runner) only for trusted events, and only while the
|
||||
# SELFHOSTED_RUNNERS repository variable is 'true': runs-on cannot fall back when none is online.
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted"]') || 'ubuntu-latest' }}
|
||||
runs-on: ${{ vars.SELFHOSTED_RUNNERS == 'true' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) && fromJSON('["self-hosted", "openidea-selfhosted-light"]') || 'ubuntu-latest' }}
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
pull-requests: read
|
||||
|
||||
Створено
+48
-48
@@ -4154,7 +4154,7 @@ checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
|
||||
|
||||
[[package]]
|
||||
name = "ide-agent"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4182,7 +4182,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-analysis"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ast-grep-core",
|
||||
"ide-core",
|
||||
@@ -4194,7 +4194,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-android"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4205,7 +4205,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-build"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chardetng",
|
||||
@@ -4223,7 +4223,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-cli"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"serde",
|
||||
@@ -4237,7 +4237,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-clipboard"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4248,7 +4248,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-command"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"proc-macro2",
|
||||
@@ -4259,7 +4259,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-core"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4281,7 +4281,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-coverage"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-run",
|
||||
@@ -4294,7 +4294,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-dap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"futures",
|
||||
@@ -4323,7 +4323,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-db"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"bb8",
|
||||
@@ -4362,7 +4362,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-docker"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"serde",
|
||||
@@ -4375,7 +4375,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-drag-out"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"gtk",
|
||||
"objc2 0.6.5",
|
||||
@@ -4389,7 +4389,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-extension"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4409,7 +4409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-flutter"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-android",
|
||||
"ide-core",
|
||||
@@ -4420,7 +4420,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-fonts"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"objc2-core-foundation",
|
||||
"objc2-core-text",
|
||||
@@ -4432,7 +4432,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-github"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vcs",
|
||||
@@ -4444,7 +4444,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-heap"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4463,7 +4463,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-host"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
@@ -4544,7 +4544,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-http"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
@@ -4563,7 +4563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-index"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4586,7 +4586,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jdwp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-jvm-inspect",
|
||||
"proptest",
|
||||
@@ -4598,7 +4598,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jsonrpc"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"encoding_rs",
|
||||
"ide-core",
|
||||
@@ -4614,7 +4614,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-attach"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"tempfile",
|
||||
@@ -4623,7 +4623,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-jvm-inspect"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"serde",
|
||||
@@ -4634,7 +4634,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-language"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"criterion",
|
||||
@@ -4693,7 +4693,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-lsp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"dunce",
|
||||
@@ -4722,7 +4722,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-mcp"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dunce",
|
||||
@@ -4741,7 +4741,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-notebook"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
@@ -4762,7 +4762,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-plugin"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -4784,7 +4784,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-profiler"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-jvm-attach",
|
||||
@@ -4798,7 +4798,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-remote"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"futures",
|
||||
@@ -4818,7 +4818,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-run"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dunce",
|
||||
"encoding_rs",
|
||||
@@ -4843,7 +4843,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-scaffold"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-tools",
|
||||
@@ -4859,7 +4859,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-sdk"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"dirs 6.0.0",
|
||||
@@ -4885,7 +4885,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-search"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"encoding_rs",
|
||||
@@ -4906,7 +4906,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-spell"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"parking_lot 0.12.5",
|
||||
@@ -4919,7 +4919,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-ssh"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"flate2",
|
||||
@@ -4944,7 +4944,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-streams"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4957,7 +4957,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-syntax"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"ide-language",
|
||||
@@ -4972,7 +4972,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-terminal"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"ide-core",
|
||||
"libc",
|
||||
@@ -4986,7 +4986,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-text"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"criterion",
|
||||
"ide-core",
|
||||
@@ -4999,7 +4999,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-tools"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"hex",
|
||||
@@ -5022,7 +5022,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vcs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -5044,7 +5044,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-vfs"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"chardetng",
|
||||
"dunce",
|
||||
@@ -5071,7 +5071,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-web"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"dirs 6.0.0",
|
||||
"ide-core",
|
||||
@@ -5087,7 +5087,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "ide-workspace"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"dunce",
|
||||
@@ -6726,7 +6726,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "openidea"
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
dependencies = [
|
||||
"base64 0.22.1",
|
||||
"blake3",
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -562,6 +562,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -572,10 +591,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save(doc)).await?;
|
||||
host.blocking(move || {
|
||||
project.documents.save(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
|
||||
#[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?;
|
||||
let saved = host
|
||||
.blocking(move || {
|
||||
let saved = project.documents.autosave(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(saved)
|
||||
})
|
||||
.await?;
|
||||
if saved {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
|
||||
}
|
||||
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save_all()).await?;
|
||||
host.blocking(move || {
|
||||
let saved = project.documents.save_all();
|
||||
remember_saved_encodings(&project);
|
||||
saved
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use crate::project::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
|
||||
/// editor buffer, so syntax features and language-server requests work in it.
|
||||
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
|
||||
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
|
||||
}
|
||||
|
||||
/// Keeps the encoding the user chose for a project file in the project's File Encodings
|
||||
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
|
||||
/// until then its file is still in the old encoding. Nothing is kept for a document without
|
||||
/// a file in the project.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
|
||||
return Ok(());
|
||||
}
|
||||
remember_encoding(&project, &info.path, &info.encoding)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Keeps the encodings of the converted documents a save has just written.
|
||||
pub(super) fn remember_saved_encodings(project: &Project) {
|
||||
for (path, encoding) in project.documents.take_saved_encodings() {
|
||||
if let Err(e) = remember_encoding(project, &path, &encoding) {
|
||||
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
|
||||
const MAPPINGS: &str = "editor.encodings.mappings";
|
||||
if project.light {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
|
||||
return Ok(());
|
||||
};
|
||||
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
|
||||
return Ok(());
|
||||
}
|
||||
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
|
||||
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
@@ -263,6 +308,7 @@ ide_command::domain!(
|
||||
doc_outline,
|
||||
doc_python_facts,
|
||||
doc_rearrange,
|
||||
doc_remember_encoding,
|
||||
doc_selection_ranges,
|
||||
doc_set_bom,
|
||||
doc_set_encoding,
|
||||
|
||||
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
|
||||
f.sync().await;
|
||||
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
|
||||
|
||||
impl Fixture {
|
||||
fn project_settings(&self) -> PathBuf {
|
||||
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
|
||||
}
|
||||
|
||||
fn mappings_changed(&self) -> usize {
|
||||
let events = self.events.lock();
|
||||
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
assert!(!settings.exists());
|
||||
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
let written = std::fs::read_to_string(&settings).unwrap();
|
||||
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
// The same choice again leaves the file alone.
|
||||
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
|
||||
// A file outside the project has no place in the project's settings.
|
||||
let outside = f.open(&f.outside).await;
|
||||
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
|
||||
assert!(!settings.exists());
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
|
||||
|
||||
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&settings).unwrap(),
|
||||
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
|
||||
);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
// Later saves keep nothing more.
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", reopened.id).await.unwrap();
|
||||
let again = f.open(&f.path).await;
|
||||
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
|
||||
std::fs::write(&settings, "[editor\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
|
||||
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
|
||||
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
|
||||
assert_eq!(f.mappings_changed(), 0);
|
||||
}
|
||||
@@ -110,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
|
||||
/// crate's and the desktop's) call it after writing the value.
|
||||
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
|
||||
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
|
||||
/// re-reads its effective settings.
|
||||
@@ -122,17 +138,7 @@ pub fn settings_set(
|
||||
value: String,
|
||||
) -> IdeResult<Settings> {
|
||||
let applied = set_settings(host, window, scope, &key, &value)?;
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(&key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
apply_setting(host, window, &key);
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
|
||||
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
|
||||
_ => true,
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let defaults = project.documents.file_defaults();
|
||||
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
|
||||
// Search's UTF-8 fast path does not need to resolve the configured encoding.
|
||||
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
|
||||
@@ -1530,8 +1530,7 @@ impl Project {
|
||||
}
|
||||
|
||||
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
|
||||
let defaults = self.documents.file_defaults();
|
||||
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
|
||||
let charset = self.documents.detect_encoding(path, bytes);
|
||||
self.vcs_text_encoding(path, charset)
|
||||
}
|
||||
|
||||
|
||||
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
|
||||
project.documents.set_file_defaults(defaults);
|
||||
assert!(find(&host, "中文搜索验证").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
|
||||
let files = find(&host, "ação €").await;
|
||||
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
|
||||
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
|
||||
}
|
||||
@@ -447,7 +447,7 @@ impl Http {
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) fn gh_path(&self) -> Option<&Path> {
|
||||
self.gh.as_deref()
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::editorconfig::{EditorConfig, EditorConfigProps};
|
||||
use crate::file_defaults::FileDefaults;
|
||||
use crate::file_defaults::{EncodingSource, FileDefaults};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
|
||||
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
|
||||
@@ -168,6 +168,8 @@ struct DocState {
|
||||
can_reload_encoding: bool,
|
||||
/// The user picked `encoding`; reloads keep it instead of detecting again.
|
||||
encoding_chosen: bool,
|
||||
/// The user converted the text to `encoding`; it is theirs to keep once a save writes it.
|
||||
encoding_unsaved: bool,
|
||||
/// Disk state we last loaded or wrote; changes matching it are our own.
|
||||
disk_mtime: f64,
|
||||
disk_len: u64,
|
||||
@@ -247,19 +249,25 @@ fn disk_len(path: &Path) -> u64 {
|
||||
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn editorconfig_label(editorconfig: Option<&EditorConfigProps>, detected: &str, ascii: bool) -> Option<&'static str> {
|
||||
let (charset, _) = editorconfig?.encoding()?;
|
||||
let compatible = encoding_rs::Encoding::for_label(detected.as_bytes()).is_some_and(|e| e.is_ascii_compatible());
|
||||
(ascii && compatible && !charset.starts_with("utf-16")).then_some(charset)
|
||||
}
|
||||
|
||||
fn apply_editorconfig_charset(loaded: &mut ide_vfs::LoadedText, editorconfig: Option<&EditorConfigProps>) {
|
||||
if loaded.binary {
|
||||
return;
|
||||
}
|
||||
if let Some(charset) = editorconfig_label(editorconfig, &loaded.encoding, !loaded.has_bom && loaded.text.is_ascii())
|
||||
{
|
||||
loaded.encoding = charset.to_owned();
|
||||
/// EditorConfig takes precedence over File Encodings for legacy text and ASCII labels.
|
||||
/// UTF-16 is detected, not assumed; invalid UTF-8 still uses the File Encodings fallback.
|
||||
fn configured_fallback<'a>(
|
||||
defaults: &'a FileDefaults,
|
||||
path: &Path,
|
||||
editorconfig: Option<&EditorConfigProps>,
|
||||
) -> Option<ide_vfs::Fallback<'a>> {
|
||||
let path = absolute(path);
|
||||
let charset = editorconfig.filter(|_| defaults.editorconfig).and_then(EditorConfigProps::encoding);
|
||||
let inherited = defaults.inherited_encoding_for(&path);
|
||||
let fallback = if inherited.source == EncodingSource::Folder && charset.is_some() {
|
||||
defaults.project_encoding_for(&path).fallback()
|
||||
} else {
|
||||
inherited.fallback()
|
||||
};
|
||||
match charset {
|
||||
Some(("utf-8", _)) => fallback.map(|f| ide_vfs::Fallback { ascii: false, ..f }),
|
||||
Some((encoding, _)) if !encoding.starts_with("utf-16") => Some(ide_vfs::Fallback { encoding, ascii: true }),
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -365,17 +373,21 @@ impl Documents {
|
||||
/// Closed-file readers use the same decoding as document opening.
|
||||
pub fn load_file(&self, path: &Path) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let defaults = self.file_defaults();
|
||||
Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())
|
||||
Ok(Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())?.0)
|
||||
}
|
||||
|
||||
/// Encoding of `bytes`, a revision of `path`, with the same rules as opening the file.
|
||||
pub fn detect_encoding(&self, path: &Path, bytes: &[u8]) -> &'static encoding_rs::Encoding {
|
||||
let defaults = self.file_defaults();
|
||||
let detected = ide_vfs::detect_encoding(bytes, defaults.fallback_for(&absolute(path)));
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
editorconfig_label(editorconfig.as_ref(), detected.name(), bytes.is_ascii())
|
||||
.and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
|
||||
.unwrap_or(detected)
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
if configured.source == EncodingSource::File
|
||||
&& let Some(enc) = encoding_rs::Encoding::for_label(configured.label.as_bytes())
|
||||
&& !enc.decode_with_bom_removal(bytes).0.contains(char::REPLACEMENT_CHARACTER)
|
||||
{
|
||||
return enc;
|
||||
}
|
||||
ide_vfs::detect_encoding(bytes, configured_fallback(&defaults, path, editorconfig.as_ref()))
|
||||
}
|
||||
|
||||
fn editorconfig_for(&self, path: &Path, defaults: &FileDefaults) -> Option<EditorConfigProps> {
|
||||
@@ -385,11 +397,23 @@ impl Documents {
|
||||
self.editorconfig.resolve(&absolute(path))
|
||||
}
|
||||
|
||||
/// Fallback encoding for closed-file search; ASCII relabelling does not affect its text.
|
||||
pub fn configured_encoding_for(&self, path: &Path) -> Option<String> {
|
||||
let defaults = self.file_defaults();
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
if configured.source == EncodingSource::File {
|
||||
return Some(configured.label.to_owned());
|
||||
}
|
||||
configured_fallback(&defaults, path, editorconfig.as_ref()).map(|f| f.encoding.to_owned())
|
||||
}
|
||||
|
||||
/// Bounded closed-file snapshots use the same project defaults as open documents.
|
||||
pub fn load_file_bounded(&self, path: &Path, max_bytes: usize) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let defaults = self.file_defaults();
|
||||
let mut loaded = ide_vfs::load_text_bounded(path, defaults.fallback_for(&absolute(path)), max_bytes)?;
|
||||
apply_editorconfig_charset(&mut loaded, self.editorconfig_for(path, &defaults).as_ref());
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let mut loaded =
|
||||
ide_vfs::load_text_bounded(path, configured_fallback(&defaults, path, editorconfig.as_ref()), max_bytes)?;
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
@@ -400,17 +424,30 @@ impl Documents {
|
||||
Self::load_as(path, encoding, self.native_to_ascii_for(path))
|
||||
}
|
||||
|
||||
/// Loads `path` as the settings say. `true`: decoded in the encoding chosen for this
|
||||
/// very file, as "Reload with Encoding" does, instead of detecting it.
|
||||
fn load_with_defaults(
|
||||
path: &Path,
|
||||
defaults: &FileDefaults,
|
||||
editorconfig: Option<&EditorConfigProps>,
|
||||
) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let mut loaded = ide_vfs::load_text_with_fallback(path, defaults.fallback_for(&absolute(path)))?;
|
||||
apply_editorconfig_charset(&mut loaded, editorconfig);
|
||||
) -> IdeResult<(ide_vfs::LoadedText, bool)> {
|
||||
let path_abs = absolute(path);
|
||||
let configured = defaults.configured_encoding_for(&path_abs);
|
||||
if configured.source == EncodingSource::File {
|
||||
let loaded = Self::load_as(path, configured.label, defaults.native_to_ascii_for(path))?;
|
||||
// The bytes are not text in that encoding (the file changed outside the IDE):
|
||||
// open it as if nothing was chosen, rather than show and save broken characters.
|
||||
// A single-byte encoding decodes any bytes, so this only catches the others.
|
||||
if !loaded.text.contains(char::REPLACEMENT_CHARACTER) {
|
||||
return Ok((loaded, true));
|
||||
}
|
||||
}
|
||||
let fallback = configured_fallback(defaults, path, editorconfig);
|
||||
let mut loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
Ok(loaded)
|
||||
Ok((loaded, false))
|
||||
}
|
||||
|
||||
pub fn file_defaults(&self) -> FileDefaults {
|
||||
@@ -492,7 +529,7 @@ impl Documents {
|
||||
}
|
||||
let defaults = self.file_defaults();
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let loaded = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
|
||||
let (loaded, encoding_chosen) = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
|
||||
let editorconfig = editorconfig.filter(|_| !loaded.binary);
|
||||
let language = (self.detect_language)(path, loaded.text.lines().next());
|
||||
let ui_mode = (self.detect_ui_mode)(path, &language);
|
||||
@@ -508,8 +545,14 @@ impl Documents {
|
||||
// An empty file has nothing to detect: Code Style / File Encodings defaults apply.
|
||||
if empty_file && !loaded.binary {
|
||||
doc.set_line_ending(defaults.line_ending);
|
||||
encoding = defaults.encoding.clone();
|
||||
has_bom = defaults.encoding == "utf-8" && defaults.utf8_bom;
|
||||
if !encoding_chosen {
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
encoding = match configured.source {
|
||||
EncodingSource::Folder => configured.label.to_owned(),
|
||||
_ => defaults.encoding.clone(),
|
||||
};
|
||||
has_bom = encoding == "utf-8" && defaults.utf8_bom;
|
||||
}
|
||||
}
|
||||
if let Some(ec) = &editorconfig {
|
||||
if let Some(le) = ec.end_of_line {
|
||||
@@ -517,6 +560,7 @@ impl Documents {
|
||||
}
|
||||
if let Some((enc, bom)) = ec.encoding()
|
||||
&& empty_file
|
||||
&& !encoding_chosen
|
||||
{
|
||||
(encoding, has_bom) = (enc.to_owned(), bom);
|
||||
}
|
||||
@@ -539,7 +583,8 @@ impl Documents {
|
||||
binary: loaded.binary,
|
||||
dirty: false,
|
||||
can_reload_encoding: true,
|
||||
encoding_chosen: false,
|
||||
encoding_chosen,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: loaded.mtime_ms,
|
||||
disk_len: disk_len(path),
|
||||
disk_conflict: false,
|
||||
@@ -617,6 +662,7 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
@@ -678,6 +724,7 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding: false,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
@@ -1291,6 +1338,30 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the encoding the user chose for `doc` is still to reach its file: the text was
|
||||
/// converted and not saved. It is then reported by [`Documents::take_saved_encodings`]
|
||||
/// once a save has written it.
|
||||
pub fn keep_encoding_when_saved(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
st.encoding_unsaved = st.dirty;
|
||||
Ok(st.dirty)
|
||||
})
|
||||
}
|
||||
|
||||
/// The files saved in the encoding their text was converted to since
|
||||
/// [`Documents::keep_encoding_when_saved`], with that encoding. Each is reported once.
|
||||
pub fn take_saved_encodings(&self) -> Vec<(PathBuf, String)> {
|
||||
let ids: Vec<DocId> = self.registry.lock().docs.keys().copied().collect();
|
||||
let saved = |id| {
|
||||
self.with_doc(id, |st| {
|
||||
let saved = st.encoding_unsaved && !st.dirty;
|
||||
st.encoding_unsaved &= st.dirty;
|
||||
Ok(saved.then(|| (st.path.clone(), st.encoding.clone())))
|
||||
})
|
||||
};
|
||||
ids.into_iter().filter_map(|id| saved(id).ok().flatten()).collect()
|
||||
}
|
||||
|
||||
/// Load Changes from Disk: drops the buffer's unsaved changes and reads its file again in
|
||||
/// the buffer's encoding, after the file changed on disk (`IdeEvent::DocDiskConflict`).
|
||||
pub fn discard_and_reload(&self, doc: DocId) -> IdeResult<()> {
|
||||
@@ -1300,6 +1371,7 @@ impl Documents {
|
||||
}
|
||||
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.encoding_unsaved = false;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
self.set_dirty(doc, st, false);
|
||||
@@ -1470,7 +1542,7 @@ impl Documents {
|
||||
let loaded = if st.encoding_chosen {
|
||||
Self::load_as(&st.path, &st.encoding, native_to_ascii)?
|
||||
} else {
|
||||
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?
|
||||
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?.0
|
||||
};
|
||||
st.native_to_ascii = native_to_ascii;
|
||||
loaded
|
||||
|
||||
@@ -850,7 +850,7 @@ impl Documents {
|
||||
let loaded = if state.encoding_chosen {
|
||||
Self::load_as(path, &state.encoding, native_to_ascii)?
|
||||
} else {
|
||||
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?
|
||||
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?.0
|
||||
};
|
||||
state.native_to_ascii = native_to_ascii;
|
||||
self.replace_locked(id, state, &loaded.text)?;
|
||||
|
||||
@@ -34,7 +34,8 @@ pub struct EditorConfigProps {
|
||||
pub indent_size: Option<u32>,
|
||||
pub tab_width: Option<u32>,
|
||||
pub end_of_line: Option<LineEnding>,
|
||||
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be` or `latin1`.
|
||||
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be`, `latin1` or an encoding
|
||||
/// Settings › Editor › File Encodings lists (`iso-8859-15`, `windows-1252`, `gbk`, …).
|
||||
pub charset: Option<String>,
|
||||
pub trim_trailing_whitespace: Option<bool>,
|
||||
pub insert_final_newline: Option<bool>,
|
||||
@@ -48,17 +49,31 @@ impl EditorConfigProps {
|
||||
|
||||
/// WHATWG encoding label and BOM flag for `charset`.
|
||||
pub fn encoding(&self) -> Option<(&'static str, bool)> {
|
||||
Some(match self.charset.as_deref()? {
|
||||
"utf-8" => ("utf-8", false),
|
||||
"utf-8-bom" => ("utf-8", true),
|
||||
"utf-16le" => ("utf-16le", true),
|
||||
"utf-16be" => ("utf-16be", true),
|
||||
"latin1" => ("windows-1252", false),
|
||||
_ => return None,
|
||||
})
|
||||
charset_encoding(self.charset.as_deref()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// WHATWG label and BOM flag of a lower-cased `charset` value: the five the spec
|
||||
/// defines and the other encodings Settings › Editor › File Encodings lists.
|
||||
fn charset_encoding(charset: &str) -> Option<(&'static str, bool)> {
|
||||
Some(match charset {
|
||||
"utf-8" => ("utf-8", false),
|
||||
"utf-8-bom" => ("utf-8", true),
|
||||
"utf-16le" => ("utf-16le", true),
|
||||
"utf-16be" => ("utf-16be", true),
|
||||
// WHATWG decodes ISO-8859-1 as windows-1252.
|
||||
"latin1" | "iso-8859-1" | "windows-1252" => ("windows-1252", false),
|
||||
"iso-8859-15" => ("iso-8859-15", false),
|
||||
"gbk" => ("gbk", false),
|
||||
"gb18030" => ("gb18030", false),
|
||||
"big5" => ("big5", false),
|
||||
"shift_jis" => ("shift_jis", false),
|
||||
"euc-kr" => ("euc-kr", false),
|
||||
"koi8-r" => ("koi8-r", false),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raw `key = value` pairs (keys lower-cased) in application order.
|
||||
type Pairs = Vec<(String, String)>;
|
||||
|
||||
@@ -200,8 +215,7 @@ fn props_from(map: &HashMap<String, String>) -> EditorConfigProps {
|
||||
Some("cr") => Some(LineEnding::Cr),
|
||||
_ => None,
|
||||
};
|
||||
let charset =
|
||||
get("charset").filter(|c| matches!(c.as_str(), "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be" | "latin1"));
|
||||
let charset = get("charset").filter(|c| charset_encoding(c).is_some());
|
||||
let max_line_length = get("max_line_length").and_then(|v| v.parse::<u32>().ok());
|
||||
EditorConfigProps {
|
||||
indent_style,
|
||||
@@ -406,4 +420,34 @@ mod tests {
|
||||
assert!(std::fs::read(r.join("new.l1")).unwrap().is_empty());
|
||||
assert!(create_file(&ec, &r.join("new.txt")).is_err(), "never truncates");
|
||||
}
|
||||
|
||||
/// The labels of `ENCODING_CHOICES` in `src/platform/editorSettings.ts`, copied by hand.
|
||||
#[test]
|
||||
fn charset_maps_the_listed_encodings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let r = tmp.path().canonicalize().unwrap();
|
||||
let listed = [
|
||||
("utf-8", "utf-8"),
|
||||
("utf-16le", "utf-16le"),
|
||||
("utf-16be", "utf-16be"),
|
||||
("gbk", "gbk"),
|
||||
("gb18030", "gb18030"),
|
||||
("big5", "big5"),
|
||||
("shift_jis", "shift_jis"),
|
||||
("euc-kr", "euc-kr"),
|
||||
("windows-1252", "windows-1252"),
|
||||
("iso-8859-1", "windows-1252"),
|
||||
("ISO-8859-15", "iso-8859-15"),
|
||||
("koi8-r", "koi8-r"),
|
||||
];
|
||||
let sections: String =
|
||||
listed.iter().enumerate().map(|(i, (c, _))| format!("[*.e{i}]\ncharset = {c}\n")).collect();
|
||||
write(&r.join(".editorconfig"), &format!("root = true\n{sections}"));
|
||||
let ec = EditorConfig::new();
|
||||
for (i, (charset, label)) in listed.iter().enumerate() {
|
||||
let encoding = ec.resolve(&r.join(format!("a.e{i}"))).and_then(|p| p.encoding());
|
||||
assert_eq!(encoding.map(|(label, _)| label), Some(*label), "charset = {charset}");
|
||||
assert!(encoding_rs::Encoding::for_label(label.as_bytes()).is_some(), "{label} is a WHATWG label");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
use ide_core::settings::Settings;
|
||||
use ide_text::LineEnding;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FileDefaults {
|
||||
@@ -21,6 +22,34 @@ pub struct FileDefaults {
|
||||
pub native_to_ascii: bool,
|
||||
pub editorconfig: bool,
|
||||
pub root: Option<PathBuf>,
|
||||
/// File Encodings mappings: a file's or a folder's path with its encoding. An entry
|
||||
/// naming the file itself is the user's choice for it; one naming a folder above it
|
||||
/// covers the files inside.
|
||||
pub mappings: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
/// Where the encoding configured for a file comes from, strongest first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EncodingSource {
|
||||
File,
|
||||
Properties,
|
||||
Folder,
|
||||
Project,
|
||||
Global,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ConfiguredEncoding<'a> {
|
||||
pub label: &'a str,
|
||||
pub source: EncodingSource,
|
||||
}
|
||||
|
||||
impl<'a> ConfiguredEncoding<'a> {
|
||||
/// The label for files that are not valid UTF-8 or are plain ASCII (`None`: detect).
|
||||
pub fn fallback(self) -> Option<ide_vfs::Fallback<'a>> {
|
||||
(self.label != "utf-8")
|
||||
.then_some(ide_vfs::Fallback { encoding: self.label, ascii: self.source != EncodingSource::Properties })
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FileDefaults {
|
||||
@@ -51,20 +80,47 @@ impl FileDefaults {
|
||||
native_to_ascii: enc.native_to_ascii,
|
||||
editorconfig: style.editorconfig,
|
||||
root: root.map(Path::to_path_buf),
|
||||
mappings: root.map(|root| mappings(root, &enc.mappings)).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding for `path` when it is not valid UTF-8 (`None`: detect). The project and
|
||||
/// global encodings also label plain ASCII; the properties encoding only decodes.
|
||||
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
|
||||
let (label, ascii) = if path.extension().is_some_and(|e| e == "properties") {
|
||||
(&self.properties_fallback, false)
|
||||
} else if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
|
||||
(&self.project_fallback, true)
|
||||
} else {
|
||||
(&self.global_fallback, true)
|
||||
/// The encoding the settings give `path`: the one chosen for the file itself, else the
|
||||
/// one it [inherits](Self::inherited_encoding_for).
|
||||
pub fn configured_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
match self.mappings.iter().find(|(mapped, _)| path == mapped) {
|
||||
Some((_, label)) => ConfiguredEncoding { label, source: EncodingSource::File },
|
||||
None => self.inherited_encoding_for(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// The encoding of `path` without a choice for the file itself: the `.properties`
|
||||
/// default, the nearest mapped folder above it, then the project's or the global one.
|
||||
pub fn inherited_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
let folder = || {
|
||||
let above = self.mappings.iter().filter(|(mapped, _)| path != mapped && path.starts_with(mapped));
|
||||
above.max_by_key(|(mapped, _)| mapped.components().count())
|
||||
};
|
||||
(label != "utf-8").then_some(ide_vfs::Fallback { encoding: label, ascii })
|
||||
if path.extension().is_some_and(|e| e == "properties") {
|
||||
ConfiguredEncoding { label: &self.properties_fallback, source: EncodingSource::Properties }
|
||||
} else if let Some((_, label)) = folder() {
|
||||
ConfiguredEncoding { label, source: EncodingSource::Folder }
|
||||
} else {
|
||||
self.project_encoding_for(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's encoding for a file inside it, the global one for any other.
|
||||
pub fn project_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
|
||||
ConfiguredEncoding { label: &self.project_fallback, source: EncodingSource::Project }
|
||||
} else {
|
||||
ConfiguredEncoding { label: &self.global_fallback, source: EncodingSource::Global }
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding for `path` when it is not valid UTF-8 or is plain ASCII (`None`: detect).
|
||||
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
|
||||
self.configured_encoding_for(path).fallback()
|
||||
}
|
||||
|
||||
pub fn native_to_ascii_for(&self, path: &Path) -> bool {
|
||||
@@ -81,6 +137,49 @@ impl FileDefaults {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `[editor.encodings.mappings]` key of `path`: its path inside the project `root`,
|
||||
/// with `/` separators. `None` for anything else.
|
||||
pub fn mapping_key(root: &Path, path: &Path) -> Option<String> {
|
||||
let segments: Option<Vec<&str>> = path
|
||||
.strip_prefix(root)
|
||||
.ok()?
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
Component::Normal(name) => name.to_str(),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
segments.filter(|s| !s.is_empty()).map(|s| s.join("/"))
|
||||
}
|
||||
|
||||
/// The mapped paths under `root`. An entry whose key is not such a path, or whose value is
|
||||
/// not an encoding label, is left out.
|
||||
fn mappings(root: &Path, entries: &BTreeMap<String, String>) -> Vec<(PathBuf, String)> {
|
||||
let path_of = |key: &str| {
|
||||
let mut path = root.to_path_buf();
|
||||
for segment in key.strip_suffix('/').unwrap_or(key).split('/') {
|
||||
let mut components = Path::new(segment).components();
|
||||
let plain = matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none();
|
||||
if !plain || segment.contains('\\') {
|
||||
return None;
|
||||
}
|
||||
path.push(segment);
|
||||
}
|
||||
Some(path)
|
||||
};
|
||||
let mapping = |(key, label): (&String, &String)| {
|
||||
let label = normalize(label);
|
||||
match (path_of(key), ide_vfs::encode("", &label, false)) {
|
||||
(Some(path), Ok(_)) => Some((path, label)),
|
||||
_ => {
|
||||
tracing::warn!("ignoring the encoding mapping {key:?} = {label:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
entries.iter().filter_map(mapping).collect()
|
||||
}
|
||||
|
||||
fn normalize(label: &str) -> String {
|
||||
let l = label.trim().to_ascii_lowercase();
|
||||
match l.as_str() {
|
||||
@@ -108,4 +207,106 @@ mod tests {
|
||||
assert_eq!(d.fallback_for(Path::new("/p/a.properties")), fallback("iso-8859-1", false));
|
||||
assert!(d.new_file_bytes().is_empty(), "BOM only for UTF-8 new files");
|
||||
}
|
||||
|
||||
fn mapped(entries: &[(&str, &str)], root: &Path) -> FileDefaults {
|
||||
let mut s = Settings::default();
|
||||
s.editor.encodings.project = "gbk".into();
|
||||
s.editor.encodings.mappings = entries.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
FileDefaults::from_settings(&s, Some(root))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_resolve_a_file_before_its_folders_and_the_project() {
|
||||
let root = Path::new("/p");
|
||||
let d = mapped(
|
||||
&[
|
||||
("src", "ISO-8859-15"),
|
||||
("src/legacy", "koi8-r"),
|
||||
("src/legacy/A.java", "windows-1252"),
|
||||
("src/utf", "utf-8"),
|
||||
("src/app.properties", "big5"),
|
||||
],
|
||||
root,
|
||||
);
|
||||
let fallback = |rel: &str| d.fallback_for(&root.join(rel));
|
||||
assert_eq!(fallback("src/legacy/A.java"), Some(ide_vfs::Fallback { encoding: "windows-1252", ascii: true }));
|
||||
assert_eq!(
|
||||
fallback("src/legacy/B.java"),
|
||||
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true }),
|
||||
"the longest folder wins"
|
||||
);
|
||||
assert_eq!(fallback("src/main/C.java"), Some(ide_vfs::Fallback { encoding: "iso-8859-15", ascii: true }));
|
||||
assert_eq!(
|
||||
fallback("srcs/C.java"),
|
||||
Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }),
|
||||
"a folder is matched by whole path segments"
|
||||
);
|
||||
assert_eq!(fallback("other/C.java"), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
|
||||
assert_eq!(fallback("src/utf/D.java"), None, "a UTF-8 mapping does not fall through to the project");
|
||||
// `.properties` keep their own default inside a mapped folder; only their own entry overrides it.
|
||||
assert_eq!(
|
||||
fallback("src/legacy/b.properties"),
|
||||
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
|
||||
);
|
||||
assert_eq!(fallback("src/app.properties"), Some(ide_vfs::Fallback { encoding: "big5", ascii: true }));
|
||||
assert_eq!(d.fallback_for(Path::new("/elsewhere/src/C.java")), None);
|
||||
|
||||
let source = |rel: &str| d.configured_encoding_for(&root.join(rel)).source;
|
||||
assert_eq!(source("src/legacy/A.java"), EncodingSource::File);
|
||||
assert_eq!(source("src/legacy/B.java"), EncodingSource::Folder);
|
||||
assert_eq!(source("src/legacy/b.properties"), EncodingSource::Properties);
|
||||
assert_eq!(source("other/C.java"), EncodingSource::Project);
|
||||
assert_eq!(d.configured_encoding_for(Path::new("/elsewhere/C.java")).source, EncodingSource::Global);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_encoding_mappings_are_dropped() {
|
||||
let root = Path::new("/p");
|
||||
let d = mapped(
|
||||
&[
|
||||
("ok", "iso-8859-15"),
|
||||
("unknown", "klingon-1"),
|
||||
("", "koi8-r"),
|
||||
("/abs", "koi8-r"),
|
||||
("../up", "koi8-r"),
|
||||
("a/./b", "koi8-r"),
|
||||
("a//b", "koi8-r"),
|
||||
("back\\slash", "koi8-r"),
|
||||
],
|
||||
root,
|
||||
);
|
||||
assert_eq!(d.mappings, [(root.join("ok"), "iso-8859-15".to_owned())]);
|
||||
assert_eq!(d.fallback_for(&root.join("up/A.java")), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
|
||||
assert!(mapped(&[("ok", "iso-8859-15")], root).mappings.len() == 1);
|
||||
// Without a project there is nothing the paths are relative to.
|
||||
let mut s = Settings::default();
|
||||
s.editor.encodings.mappings.insert("ok".into(), "gbk".into());
|
||||
assert!(FileDefaults::from_settings(&s, None).mappings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_key_is_the_path_inside_the_project_with_slashes() {
|
||||
let root = Path::new("/p");
|
||||
assert_eq!(mapping_key(root, &root.join("src").join("a.b").join("A.java")).as_deref(), Some("src/a.b/A.java"));
|
||||
assert_eq!(mapping_key(root, Path::new("/elsewhere/A.java")), None);
|
||||
assert_eq!(mapping_key(root, root), None);
|
||||
assert_eq!(mapping_key(root, Path::new("untitled:Untitled-1")), None);
|
||||
let d = mapped(&[("src/a.b/A.java", "koi8-r")], root);
|
||||
assert_eq!(
|
||||
d.fallback_for(&root.join("src/a.b/A.java")),
|
||||
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_mapped_resolves_as_before() {
|
||||
let d = FileDefaults::from_settings(&Settings::default(), Some(Path::new("/p")));
|
||||
assert!(d.mappings.is_empty());
|
||||
assert_eq!(d.fallback_for(Path::new("/p/src/A.java")), None);
|
||||
assert_eq!(
|
||||
d.fallback_for(Path::new("/p/a.properties")),
|
||||
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
|
||||
);
|
||||
assert_eq!(d.configured_encoding_for(Path::new("/p/src/A.java")).label, "utf-8");
|
||||
}
|
||||
}
|
||||
@@ -392,8 +392,35 @@ impl SettingsStore {
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
|
||||
}
|
||||
self.set_segments(scope, key, &key.split('.').collect::<Vec<_>>(), value)
|
||||
}
|
||||
|
||||
/// Sets (`null`: removes) the `entry` of the map setting `map`, e.g. `editor.encodings.mappings`.
|
||||
/// Unlike a dotted key of [`set`](Self::set), `entry` may hold dots: a file path.
|
||||
pub fn set_map_entry(
|
||||
&self,
|
||||
scope: SettingsScope,
|
||||
map: &str,
|
||||
entry: &str,
|
||||
value: serde_json::Value,
|
||||
) -> IdeResult<Settings> {
|
||||
if scope == SettingsScope::Project
|
||||
&& let Some(setting) = user_only_setting(map, &serde_json::json!({ entry: value }))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
|
||||
}
|
||||
let segments: Vec<&str> = map.split('.').chain([entry]).collect();
|
||||
self.set_segments(scope, &format!("{map}.{entry}"), &segments, value)
|
||||
}
|
||||
|
||||
fn set_segments(
|
||||
&self,
|
||||
scope: SettingsScope,
|
||||
key: &str,
|
||||
segments: &[&str],
|
||||
value: serde_json::Value,
|
||||
) -> IdeResult<Settings> {
|
||||
let file = self.file(scope).ok_or_else(|| IdeError::invalid("no project is open"))?.to_path_buf();
|
||||
let segments: Vec<&str> = key.split('.').collect();
|
||||
if segments.iter().any(|s| s.is_empty()) {
|
||||
return Err(IdeError::invalid(format!("invalid settings key {key:?}")));
|
||||
}
|
||||
@@ -421,7 +448,7 @@ impl SettingsStore {
|
||||
.parse()
|
||||
.map_err(|e| IdeError::invalid(format!("{} is not valid TOML; fix it first: {e}", file.display())))?;
|
||||
let new_value = if value.is_null() { None } else { Some(json_to_toml(&value)?) };
|
||||
set_in_document(&mut doc, &segments, new_value, map_entry);
|
||||
set_in_document(&mut doc, segments, new_value, map_entry);
|
||||
let new_text = doc.to_string();
|
||||
|
||||
// Validate the resulting stack before touching the disk.
|
||||
@@ -792,6 +819,52 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_entry_named_by_a_path_is_written_under_its_table() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cfg = tmp.path().join("cfg");
|
||||
let proj = tmp.path().join("proj");
|
||||
let file = proj.join(".openidea/settings.toml");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, "[editor]\ntabSize = 8 # wide\n").unwrap();
|
||||
let store = SettingsStore::load(&cfg, Some(&proj));
|
||||
|
||||
let key = "editor.encodings.mappings";
|
||||
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
|
||||
assert_eq!(s.editor.encodings.mappings.get("src/a.b/A.java").map(String::as_str), Some("iso-8859-15"));
|
||||
assert_eq!(s.editor.tab_size, 8);
|
||||
let written =
|
||||
"[editor]\ntabSize = 8 # wide\n\n[editor.encodings.mappings]\n\"src/a.b/A.java\" = \"iso-8859-15\"\n";
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
|
||||
|
||||
// Setting it again changes nothing; another entry joins the table; `null` removes one.
|
||||
store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
|
||||
store.set_map_entry(SettingsScope::Project, key, "web", json!("gbk")).unwrap();
|
||||
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", Json::Null).unwrap();
|
||||
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("web".into(), "gbk".into())]);
|
||||
|
||||
for (map, entry) in [("editor.encodings.nope", "a"), (key, "")] {
|
||||
let err = store.set_map_entry(SettingsScope::Project, map, entry, json!("gbk")).unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_encoding_mapping_that_is_not_a_label_does_not_drop_the_project_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let proj = tmp.path().join("proj");
|
||||
std::fs::create_dir_all(proj.join(".openidea")).unwrap();
|
||||
std::fs::write(
|
||||
proj.join(".openidea/settings.toml"),
|
||||
"[editor]\ntabSize = 8\n[editor.encodings.mappings]\nsrc = \"gbk\"\ncount = 5\n",
|
||||
)
|
||||
.unwrap();
|
||||
let s = SettingsStore::load(&tmp.path().join("cfg"), Some(&proj)).effective();
|
||||
assert_eq!(s.editor.tab_size, 8);
|
||||
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("src".into(), "gbk".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_console_log_colors() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -1567,3 +1567,298 @@ fn undo_back_to_the_disk_text_reloads_on_checkout() {
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, "checked out\n");
|
||||
}
|
||||
|
||||
fn project_encoding(f: &Fixture, label: &str) {
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = label.into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
}
|
||||
|
||||
fn latin9_editorconfig(f: &Fixture) {
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_applies_to_an_existing_ascii_file_over_the_project_encoding() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "iso-8859-15");
|
||||
f.docs.edit(doc.id, doc.version, change(0, 0, "// ação €\n")).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"// a\xe7\xe3o \xa4\nclass A {}\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_decodes_a_legacy_file_over_the_project_encoding() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
let bytes = b"// a\xe7\xe3o \xa4\n";
|
||||
fs::write(&path, bytes).unwrap();
|
||||
|
||||
assert_eq!(f.docs.detect_encoding(&path, bytes), encoding_rs::ISO_8859_15);
|
||||
for loaded in [f.docs.load_file(&path).unwrap(), f.docs.load_file_bounded(&path, 1024).unwrap()] {
|
||||
assert_eq!((loaded.text.as_str(), loaded.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_survives_a_reload_from_disk() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
let reloaded = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_without_a_usable_charset_leaves_the_encoding_alone() {
|
||||
let open = |project: Option<&str>, editorconfig: &str, enabled: bool| {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
if let Some(project) = project {
|
||||
defaults.project_fallback = project.into();
|
||||
}
|
||||
defaults.editorconfig = enabled;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), format!("root = true\n[*.java]\n{editorconfig}\n")).unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
f.docs.open(&path).unwrap().encoding
|
||||
};
|
||||
|
||||
assert_eq!(open(None, "indent_size = 2", true), "utf-8", "nothing configured");
|
||||
assert_eq!(open(None, "charset = ebcdic", true), "utf-8", "unknown charset");
|
||||
assert_eq!(open(Some("iso-8859-15"), "indent_size = 2", true), "iso-8859-15", "no charset: the project's");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = ebcdic", true), "iso-8859-15", "unknown charset: the project's");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = gbk", false), "iso-8859-15", "EditorConfig support is off");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = utf-16le", true), "iso-8859-15", "UTF-16 is detected, not assumed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_text_without_a_bom_keeps_utf16_under_a_utf8_charset() {
|
||||
let f = fixture();
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, ide_vfs::encode("class A {}\n", "utf-16le", false).unwrap()).unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("class A {}\n", "utf-16le"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_utf8_text_keeps_utf8_under_a_legacy_charset() {
|
||||
let f = fixture();
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, "// ação\n").unwrap();
|
||||
|
||||
assert_eq!(f.docs.open(&path).unwrap().encoding, "utf-8");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_utf8_charset_survives_a_reload_from_disk() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
let reloaded = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "utf-8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_wins_over_the_properties_encoding() {
|
||||
let f = fixture();
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.properties]\ncharset = iso-8859-15\n").unwrap();
|
||||
let path = f.root.join("messages.properties");
|
||||
fs::write(&path, b"price=10 \xa4\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("price=10 €\n", "iso-8859-15"));
|
||||
assert_eq!(f.docs.detect_encoding(&path, b"price=10\n"), encoding_rs::ISO_8859_15);
|
||||
assert_eq!(f.docs.detect_encoding(&f.root.join("unmatched.txt"), b"price=10\n"), encoding_rs::UTF_8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_editorconfig_support_off_stops_the_charset_on_reload() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.editorconfig = false;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
assert_eq!(f.docs.snapshot(doc.id).unwrap().encoding, "gbk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_declared_utf8_that_is_not_utf8_is_decoded_with_the_project_encoding() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
/// `[editor.encodings.mappings]` as the host hands it over: project paths with their labels.
|
||||
fn encoding_mappings(f: &Fixture, entries: &[(&str, &str)]) {
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.mappings = entries.iter().map(|(rel, label)| (in_root(f, rel), (*label).to_owned())).collect();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
}
|
||||
|
||||
fn in_root(f: &Fixture, rel: &str) -> PathBuf {
|
||||
rel.split('/').fold(f.root.clone(), |path, segment| path.join(segment))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_survives_closing_and_reopening_it() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, "// ação\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
f.docs.set_encoding(doc.id, "iso-8859-15", true).unwrap();
|
||||
let chosen = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!(chosen.text, "// ação\n");
|
||||
f.docs.close(doc.id);
|
||||
|
||||
encoding_mappings(&f, &[("A.java", "iso-8859-15")]);
|
||||
let reopened = f.docs.open(&path).unwrap();
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", chosen.text.as_str()));
|
||||
// A later change on disk is read in the remembered encoding too.
|
||||
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let reloaded = f.docs.snapshot(reopened.id).unwrap();
|
||||
assert_eq!((reloaded.encoding.as_str(), reloaded.text.as_str()), ("iso-8859-15", "// ação €\n"));
|
||||
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "iso-8859-15", "closed-file readers agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_to_utf8_holds_in_a_latin_project() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
encoding_mappings(&f, &[("A.java", "utf-8")]);
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
f.docs.edit(doc.id, doc.version, change(0, 0, "// é\n")).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), "// é\nclass A {}\n".as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_beats_editorconfig_and_a_folder_mapping_loses_to_it() {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\nend_of_line = crlf\n").unwrap();
|
||||
fs::create_dir(f.root.join("src")).unwrap();
|
||||
for name in ["src/A.java", "src/B.java", "src/notes.txt", "other.txt"] {
|
||||
fs::write(in_root(&f, name), b"plain ascii\n").unwrap();
|
||||
}
|
||||
fs::write(in_root(&f, "src/new.txt"), b"").unwrap();
|
||||
fs::write(in_root(&f, "src/latin.txt"), b"a\xe7\xe3o \xa4\n").unwrap();
|
||||
encoding_mappings(&f, &[("src", "iso-8859-15"), ("src/A.java", "koi8-r")]);
|
||||
let open = |name: &str| f.docs.open(&in_root(&f, name)).unwrap();
|
||||
|
||||
let file = open("src/A.java");
|
||||
assert_eq!(file.encoding, "koi8-r", "the file's own mapping beats .editorconfig");
|
||||
assert_eq!(file.line_ending, LineEnding::CrLf, ".editorconfig still sets the rest");
|
||||
assert_eq!(open("src/B.java").encoding, "windows-1252", ".editorconfig beats the folder mapping");
|
||||
assert_eq!(open("src/notes.txt").encoding, "iso-8859-15", "the folder mapping beats the project encoding");
|
||||
assert_eq!(open("src/new.txt").encoding, "iso-8859-15", "a new file takes its folder's encoding");
|
||||
assert_eq!(open("other.txt").encoding, "gbk");
|
||||
let latin = open("src/latin.txt");
|
||||
assert_eq!((latin.encoding.as_str(), latin.text.as_str()), ("iso-8859-15", "ação €\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_folder_is_left_out_where_editorconfig_sets_the_charset() {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\n").unwrap();
|
||||
fs::create_dir(f.root.join("src")).unwrap();
|
||||
let path = in_root(&f, "src/B.java");
|
||||
fs::write(&path, b"// \xd6\xd0\n").unwrap();
|
||||
let unmapped = f.docs.open(&path).unwrap();
|
||||
f.docs.close(unmapped.id);
|
||||
|
||||
encoding_mappings(&f, &[("src", "koi8-r")]);
|
||||
let mapped = f.docs.open(&path).unwrap();
|
||||
assert_eq!((mapped.encoding, mapped.text), (unmapped.encoding, unmapped.text));
|
||||
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "windows-1252", "closed-file readers agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_a_file_no_longer_decodes_in_falls_back_to_detection() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"// a\xe7\xe3o\n").unwrap();
|
||||
encoding_mappings(&f, &[("A.java", "utf-8")]);
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!((doc.encoding.as_str(), doc.text.as_str()), ("iso-8859-15", "// ação\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_encoding_mappings_files_open_as_before() {
|
||||
let f = fixture();
|
||||
let settings = ide_core::settings::Settings::default();
|
||||
f.docs.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&f.root)));
|
||||
assert!(f.docs.file_defaults().mappings.is_empty());
|
||||
for (name, bytes) in [
|
||||
("ascii.java", &b"class A {}\n"[..]),
|
||||
("utf8.java", "// ação\n".as_bytes()),
|
||||
("latin.java", &b"// a\xe7\xe3o de gra\xe7a, cora\xe7\xe3o\n"[..]),
|
||||
("empty.java", &b""[..]),
|
||||
] {
|
||||
let path = f.root.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let detected = ide_vfs::load_text(&path).unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!((doc.encoding, doc.text), (detected.encoding, detected.text), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -241,6 +241,21 @@ fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
|
||||
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abcé", "windows-1252"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_the_editorconfig_charset_of_a_file_opened_after_the_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join(".editorconfig"), "root = true\n[*.txt]\ncharset = iso-8859-15\n").unwrap();
|
||||
let path = tmp.path().join("legacy.txt");
|
||||
std::fs::write(&path, b"abc\xA4").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
let info = docs.open(&path).unwrap();
|
||||
assert_eq!((info.text.as_str(), info.encoding.as_str()), ("new€", "iso-8859-15"));
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
let snapshot = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abc€", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_document_version_rejects_the_whole_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -140,6 +140,16 @@ Settings › Appearance & Behavior › Appearance, unless noted.
|
||||
|
||||
Sub-tables such as `[editor.general]`, `[editor.appearance]`, `[editor.completion]`, `[editor.tabs]`, `[editor.codeStyle]` and `[editor.encodings]` hold the options of the matching Editor pages.
|
||||
|
||||
`[editor.encodings.mappings]` in a project's `.openidea/settings.toml` gives a file or a folder its own encoding. Keys are paths relative to the project, with `/` separators. Choosing an encoding in the status bar adds the file here; after **Convert**, once the file is saved.
|
||||
|
||||
```toml
|
||||
[editor.encodings.mappings]
|
||||
"src/main/java" = "iso-8859-15" # every file in the folder
|
||||
"web/legacy/index.jsp" = "windows-1252"
|
||||
```
|
||||
|
||||
A file's own entry wins over `.editorconfig`. A folder's entry applies where `.editorconfig` sets no `charset`, and wins over the project encoding; the nearest folder wins. An entry with an unknown encoding or a path outside the project is ignored.
|
||||
|
||||
### `[files]`
|
||||
|
||||
| Key | Default | Description |
|
||||
|
||||
@@ -140,6 +140,16 @@ exclude = ["**/.git", "**/node_modules", "**/target", "**/dist"]
|
||||
|
||||
`[editor.general]`、`[editor.appearance]`、`[editor.completion]`、`[editor.tabs]`、`[editor.codeStyle]`、`[editor.encodings]` 等子表保存对应编辑器页面的选项。
|
||||
|
||||
项目 `.openidea/settings.toml` 中的 `[editor.encodings.mappings]` 为单个文件或文件夹指定编码。键是相对于项目的路径,使用 `/` 分隔。在状态栏中选择编码时,该文件会被添加到这里;使用 **Convert** 时,在保存文件之后添加。
|
||||
|
||||
```toml
|
||||
[editor.encodings.mappings]
|
||||
"src/main/java" = "iso-8859-15" # 文件夹中的所有文件
|
||||
"web/legacy/index.jsp" = "windows-1252"
|
||||
```
|
||||
|
||||
文件自身的条目优先于 `.editorconfig`。文件夹的条目在 `.editorconfig` 未设置 `charset` 时生效,并优先于项目编码;最近的文件夹优先。编码未知或路径在项目之外的条目会被忽略。
|
||||
|
||||
### `[files]`
|
||||
|
||||
| 键 | 默认值 | 说明 |
|
||||
|
||||
@@ -23,7 +23,7 @@ test("file tab actions are grouped around the tab the menu was opened from", asy
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
expect(groups.slice(0, 4)).toEqual([
|
||||
expect(groups.slice(0, 5)).toEqual([
|
||||
[
|
||||
"Close",
|
||||
"Close Other Tabs",
|
||||
@@ -32,6 +32,7 @@ test("file tab actions are grouped around the tab the menu was opened from", asy
|
||||
"Close Tabs to the Left",
|
||||
"Close Tabs to the Right",
|
||||
],
|
||||
["File Color"],
|
||||
["Copy Path/Reference…"],
|
||||
["Split Right", "Split and Move Right", "Split Down", "Split and Move Down"],
|
||||
["Pin Tab", "Open in New Window", "Configure Editor Tabs…"],
|
||||
|
||||
@@ -65,7 +65,8 @@ test("Git Log commit choices fit their rows and navigate by keyboard after filte
|
||||
await expect(filter).toBeFocused();
|
||||
await expect(options).toHaveCount(2);
|
||||
const before = (await chooser.boundingBox())!;
|
||||
expect(before.height).toBeLessThan(200);
|
||||
// Two rows under the title, and the Close button a macOS sheet without buttons gets.
|
||||
expect(before.height).toBeLessThan(260);
|
||||
const first = options.filter({ hasText: firstSubject });
|
||||
const subject = first.getByText(firstSubject, { exact: true });
|
||||
const author = first.getByText("Priya Kapoor", { exact: true });
|
||||
|
||||
@@ -56,7 +56,7 @@ test("an SVG file opens as its source with the image beside it", async ({ workbe
|
||||
// Not an SVG yet: the preview says so, and draws the source once it is typed.
|
||||
await expect(page.getByText("The SVG source is not valid.", { exact: true })).toBeVisible();
|
||||
await page.locator(".cm-content").click();
|
||||
await page.keyboard.press("ControlOrMeta+A");
|
||||
await page.keyboard.press("Meta+A");
|
||||
await page.keyboard.insertText(
|
||||
'<svg xmlns="http://www.w3.org/2000/svg" width="128" height="96"><rect width="128" height="96"/></svg>',
|
||||
);
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
"name": "openidea",
|
||||
"private": true,
|
||||
"description": "An open-source IDE inspired by IntelliJ IDEA",
|
||||
"version": "0.1.53",
|
||||
"version": "0.1.54",
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Runs _N_ persistent, isolated GitHub Actions runners via Docker Compose on a single Docker named volume (`runner-persist`) without requiring repository admin Personal Access Tokens.
|
||||
|
||||
In `.github/workflows/ci.yml` and `.github/workflows/language-smoke.yml`, every Linux job routes to `["self-hosted", "openidea-selfhosted"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, fall back to `ubuntu-latest`. Workflows triggered on `pull_request_target` with write-scoped `GITHUB_TOKEN` permissions (`pr-check.yml`, `cancel-on-close.yml`) stay on `ubuntu-latest`.
|
||||
In `.github/workflows/ci.yml` and `.github/workflows/language-smoke.yml`, Linux jobs that compile Rust route to `["self-hosted", "openidea-selfhosted"]` and the short jobs that don't (`changes`, `rust-checks`, `deny`, `catalog`) route to `["self-hosted", "openidea-selfhosted-light"]` on trusted events (`push`, `merge_group`, `workflow_dispatch`, and same-repo pull requests) while the `SELFHOSTED_RUNNERS` repository variable is `true`. Fork pull requests, and every run while the variable is unset, fall back to `ubuntu-latest`. `frontend` and `e2e` always run on `ubuntu-latest`: they are CPU-bound and finish faster there. Workflows triggered on `pull_request_target` with write-scoped `GITHUB_TOKEN` permissions (`pr-check.yml`, `cancel-on-close.yml`) stay on `ubuntu-latest`.
|
||||
|
||||
> **Availability requirement:** GitHub Actions `runs-on` cannot fall back to GitHub-hosted runners when no matching self-hosted runner is online; jobs stay queued until one connects. Set `SELFHOSTED_RUNNERS=true` (**Settings → Secrets and variables → Actions → Variables**) only once the runners are up, and delete it before taking the host down.
|
||||
|
||||
@@ -86,13 +86,15 @@ Run all commands from `scripts/selfhost-runner/`:
|
||||
|
||||
You can pass variables on the command line or place them in a local `.env` file in this directory (git-ignored):
|
||||
|
||||
| Variable | Default | Description |
|
||||
| -------------------- | ------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `RUNNER_COUNT` | `4` | Number of concurrent runner replicas |
|
||||
| `RUNNER_NAME_PREFIX` | `openidea-runner` | Runner name prefix; registers as `<prefix>-1`, `<prefix>-2`, … |
|
||||
| `RUNNER_LABELS` | `openidea-selfhosted` | Comma-separated labels attached to each runner |
|
||||
| `REPO_URL` | `https://github.com/l0ng-ai/openidea` | Target GitHub repository URL |
|
||||
| `RUNNER_TOKEN` | _(empty)_ | One-time registration token (required only when registering new slots) |
|
||||
| Variable | Default | Description |
|
||||
| -------------------- | --------------------- | -------------------------------------------------------------- |
|
||||
| `RUNNER_COUNT` | `4` | Number of concurrent runner replicas |
|
||||
| `RUNNER_NAME_PREFIX` | `openidea-runner` | Runner name prefix; registers as `<prefix>-1`, `<prefix>-2`, … |
|
||||
| `RUNNER_LABELS` | `openidea-selfhosted` | Comma-separated labels attached to each runner |
|
||||
|
||||
A host with little disk can take only the lightweight jobs with `RUNNER_LABELS=openidea-selfhosted-light`; a host that should take both kinds uses `RUNNER_LABELS=openidea-selfhosted,openidea-selfhosted-light`.
|
||||
| `REPO_URL` | `https://github.com/l0ng-ai/openidea` | Target GitHub repository URL |
|
||||
| `RUNNER_TOKEN` | _(empty)_ | One-time registration token (required only when registering new slots) |
|
||||
|
||||
## Troubleshooting & Tips
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ services:
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
replicas: ${RUNNER_COUNT:-4}
|
||||
# Docker's 64 MB default /dev/shm starves Chromium: e2e pages render slowly enough to time out.
|
||||
shm_size: 2gb
|
||||
|
||||
environment:
|
||||
RUNNER_SCOPE: repo
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package openidea:[email protected];
|
||||
|
||||
/// Forking recorded native agent sessions into new tasks (API 1.18). Requires
|
||||
/// the `agents` capability. The session must belong to the invoking window's
|
||||
/// project and have been recorded in `cwd`; the host builds the fork invocation
|
||||
/// and names the fork's id for claude (codex assigns its own).
|
||||
interface agents {
|
||||
use types.{error};
|
||||
/// Fork the recorded session `session-id` of `agent` (a native provider,
|
||||
/// `claude` or `codex`) into a new task in the open project, returning the
|
||||
/// new task id. `cwd` must be where the session was recorded. The first
|
||||
/// turn continues the recording as the agent's own fork.
|
||||
fork-session: func(agent: string, session-id: string, cwd: string) -> result<string, error>;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// The commit being prepared in the window the current command or event came
|
||||
/// from (the Commit tool window, or the Commit dialog while it is open): the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Optional export (API 1.16, world `plugin-completion-list`): completion that
|
||||
/// can say its list is incomplete. A plugin exporting it is called instead of
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Plugin-owned project data sources. Requires database.sources and project trust.
|
||||
/// Runs on the Database subsystem's host, including on remote project servers.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Editor and project-tree decorations (API 1.4). Requires project.read. An editor set
|
||||
/// follows its file: the file's own project, or the nearest one when it is outside them all.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// What the pane beside the Services tree shows for a plugin's node.
|
||||
interface detail-types {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Optional export (world `plugin-diagnostics`): problems in the current,
|
||||
/// possibly unsaved document, for the languages declared with the
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// HTTP endpoints found in a project (`[[contributes.endpoints]]`).
|
||||
interface endpoints-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Workbench events, delivered in batches to `event-handler.handle`.
|
||||
interface events {
|
||||
@@ -39,20 +39,52 @@ interface events {
|
||||
/// 0-based UTF-16 positions, when the caret moves in the focused editor;
|
||||
/// `settled` is true for the final position once the caret rests, so costly
|
||||
/// work waits for it; it requires `events`) through `other`.
|
||||
/// API 1.18 also delivers `project-closed` (JSON project root string) and
|
||||
/// `watched-files-changed` (see `watch-paths`) through `other`.
|
||||
/// Kinds: `file-opened`, `file-saved`, `document-changed` (versioned UTF-16
|
||||
/// replacements from explicit path subscriptions), `websocket-ready`
|
||||
/// (a host-owned connection has messages to drain), `caret-moved`, `files-changed` (batched disk changes
|
||||
/// as `other`, with created/modified/removed path lists in JSON), `editor-focused` (the focused editor
|
||||
/// changed), `vcs-changed` (a repository's state changed: commit,
|
||||
/// checkout, fetch…), `action-performed` (an IDE action ran) and
|
||||
/// checkout, fetch…), `action-performed` (an IDE action ran),
|
||||
/// `project-closed` (a project closed) and
|
||||
/// `scheduled` (the `on-schedule` period elapsed); later IDEs add more,
|
||||
/// and an IDE that doesn't know one fails with `invalid`.
|
||||
/// Requires `events` (`events.input` for `action-performed`).
|
||||
subscribe: func(kind: string) -> result<_, error>;
|
||||
/// Options for file path subscriptions (API 1.18).
|
||||
record subscription-options {
|
||||
globs: list<string>,
|
||||
/// Debounce quiet window in milliseconds before delivering changes (API 1.18).
|
||||
/// When omitted, changes are delivered immediately without debounce.
|
||||
debounce-ms: option<u32>,
|
||||
}
|
||||
|
||||
/// Replaces this kind's subscription with project-relative globs (OR).
|
||||
/// Empty globs pause delivery; `subscribe` restores unfiltered delivery.
|
||||
/// Kinds: file-opened, file-saved, document-changed, files-changed. Requires `events`.
|
||||
subscribe-paths: func(kind: string, globs: list<string>) -> result<_, error>;
|
||||
/// Replaces this kind's subscription with project-relative globs and options (API 1.18).
|
||||
/// Kinds: file-opened, file-saved, document-changed, files-changed. Requires `events`.
|
||||
subscribe-paths-with-options: func(kind: string, options: subscription-options) -> result<_, error>;
|
||||
/// Watches files and directories outside the invoking window's project (API 1.18),
|
||||
/// replacing what this plugin watched for that project; an empty list stops.
|
||||
/// Each path is absolute (or `~/…`), exists, and is readable through an
|
||||
/// `fs.read:<path>` grant, checked where it really is: a link out of the grant
|
||||
/// is `denied` (naming the capability). Paths inside the project are `invalid`
|
||||
/// (they come with `files-changed`); at most 32. A file is watched where it is,
|
||||
/// across atomic saves, removal and re-creation; a directory for its own entries,
|
||||
/// not recursively. Changes arrive as `watched-files-changed` events through
|
||||
/// `other`: JSON {project, created, modified, removed} like `files-changed`,
|
||||
/// debounced and coalesced, so read the files again rather than replaying
|
||||
/// steps; a rename is the old path removed and the new one created. A removed
|
||||
/// watched directory is reported once and no longer watched: call again once
|
||||
/// it exists. Watches end when the project or its window closes, or the plugin
|
||||
/// stops (disabled, updated, or a grant revoked); idle reclaim keeps them, and
|
||||
/// an event activates the plugin again. Nothing is watched over the network:
|
||||
/// remote files need the plugin's own refresh. Requires `events` and a call
|
||||
/// that serves a window's project (a command or event).
|
||||
watch-paths: func(paths: list<string>) -> result<_, error>;
|
||||
unsubscribe: func(kind: string);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
interface lifecycle {
|
||||
use types.{context, error};
|
||||
@@ -74,6 +74,57 @@ interface syntax-provider {
|
||||
folding: func(language: string, text: string) -> list<fold>;
|
||||
}
|
||||
|
||||
/// Optional Run Anything (Ctrl Ctrl) entries and command lines for the prefixes
|
||||
/// the plugin declares under `[[contributes.runAnything]]` (API 1.18).
|
||||
interface run-anything-provider {
|
||||
record run-anything-item {
|
||||
/// What the list shows, such as `task build`.
|
||||
label: string,
|
||||
/// Grey text after the label.
|
||||
detail: option<string>,
|
||||
/// The line Tab completes in the field and Enter runs (default: `label`).
|
||||
line: option<string>,
|
||||
}
|
||||
/// Entries for `text`, the field's text, which starts with the declared `prefix`
|
||||
/// (or is the start of it). Answer from what the plugin already knows: the IDE
|
||||
/// asks while the user types, keeps the first 100 entries, and drops an answer
|
||||
/// that comes after the text changed or takes longer than 300 ms.
|
||||
suggest: func(project: string, prefix: string, text: string) -> list<run-anything-item>;
|
||||
/// Runs `line`, whose first word is `prefix`, from the invoking window: the
|
||||
/// plugin starts it through its own host calls (`run.start`, terminals), with
|
||||
/// their trust and grant checks. True claims the line; false leaves it to the
|
||||
/// IDE's other entries and finally the shell. A failed call claims the line
|
||||
/// too, so it never runs in the shell instead.
|
||||
run: func(project: string, prefix: string, line: string) -> bool;
|
||||
}
|
||||
|
||||
/// Optional completion in the fields of this plugin's own run configurations, in
|
||||
/// the Run/Debug Configurations dialog (API 1.18).
|
||||
interface run-configuration-completion {
|
||||
record completion-item {
|
||||
/// What the list shows, such as `build`.
|
||||
label: string,
|
||||
/// Grey text after the label, such as the file the entry comes from.
|
||||
detail: option<string>,
|
||||
/// The text that replaces `[replace-start, replace-end)` (default: `label`).
|
||||
insert: option<string>,
|
||||
/// UTF-16 offsets into `text`; the caret ends after the inserted text.
|
||||
replace-start: u32,
|
||||
replace-end: u32,
|
||||
}
|
||||
/// Completions for `field` of the configuration `config` (its id as this plugin
|
||||
/// reported it) in `project`. `field` is `arguments` today: the field splits like a
|
||||
/// shell command line (whitespace separates arguments, `'` and `"` quote). Later
|
||||
/// IDEs may ask for other fields, so answer none for a field you don't know.
|
||||
/// `text` is the field as typed and `caret` a UTF-16 offset into it. Replace only
|
||||
/// the token being completed, so the other options, quoted values and arguments
|
||||
/// after `--` stay as they are. Answer from what the plugin already knows (no
|
||||
/// process per keystroke): the IDE asks while the user types, keeps the first 200
|
||||
/// items, drops an item whose range is outside `text`, and drops an answer that
|
||||
/// comes after the text changed or takes longer than 300 ms.
|
||||
complete: func(project: string, config: string, field: string, text: string, caret: u32) -> list<completion-item>;
|
||||
}
|
||||
|
||||
/// Optional pre-launch gate for targets owned by this plugin (API 1.5).
|
||||
interface run-target-validation {
|
||||
enum operation { run, test }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// What other plugins contributed to the extension points this plugin declares
|
||||
/// (`[[extension-points]]` in `plugin.toml`; the contributors list this plugin
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Optional export (world `plugin-file-actions`): quick fixes and
|
||||
/// refactorings that create, rename or delete files, next to the text edits
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Files outside the open projects: the configuration of the program a
|
||||
/// plugin integrates with, a tool installed elsewhere, a licence file.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Writes to the IDE log, tagged with the plugin id.
|
||||
interface log {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Optional export (world `plugin-hover-actions`): clickable actions rendered
|
||||
/// at the left edge of a line and revealed while the pointer is in the leftmost
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Optional export (world `plugin-hover`): Markdown added to the hover of
|
||||
/// documents of the languages declared with the `hover` provider kind,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Cross-file associations a plugin publishes for the files it declares under
|
||||
/// `[[contributes.documentIndexers]]`. The host calls `index` in cancellable
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Embedded languages. The host routes plugin providers and configured language
|
||||
/// servers inside these ranges, preserving host-document UTF-16 coordinates.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Optional export (world `plugin-inlay-hints`): inline hints in documents of
|
||||
/// the languages declared with the `inlay-hints` provider kind, including
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Problems in files, shown in the editor and the Problems view.
|
||||
interface diagnostics {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Additional language features, called only for declared API 1.4 provider kinds.
|
||||
/// Editor calls have a 50 ms soft / 500 ms hard budget; formatting has 5 seconds.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Discovery of the IDE's built-in MCP server; never exposes its URL or token.
|
||||
interface mcp {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
/// `fs` and `workspace`, and everything else goes through the imports below,
|
||||
/// gated by the capabilities granted in `plugin.toml` (a missing one returns
|
||||
/// `error::denied`).
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
world plugin {
|
||||
import log;
|
||||
@@ -40,6 +40,7 @@ world plugin {
|
||||
import mcp;
|
||||
import settings;
|
||||
import extensions;
|
||||
import agents;
|
||||
|
||||
export lifecycle;
|
||||
export commands;
|
||||
@@ -189,6 +190,10 @@ world configurations-provider { export run-configurations; }
|
||||
world plugin-launch-configurations { include plugin; export launch-configurations; }
|
||||
/// Export-only launch configurations world, composed with plugin by SDK macros.
|
||||
world launch-configurations-provider { export launch-configurations; }
|
||||
/// A plugin that exports configurations with environment, debugger, and output mode (API 1.18).
|
||||
world plugin-execution-configurations { include plugin; export execution-configurations; }
|
||||
/// Export-only execution configurations world, composed with plugin by SDK macros.
|
||||
world execution-configurations-provider { export execution-configurations; }
|
||||
/// A plugin that parses its test output.
|
||||
world plugin-test-results { include plugin; export test-results; }
|
||||
/// Export-only test parser world, composed with plugin by SDK macros.
|
||||
@@ -213,6 +218,16 @@ world plugin-run-target-validation { include plugin; export run-target-validatio
|
||||
/// Export-only validation, composed with the base plugin world.
|
||||
world run-target-validator { export run-target-validation; }
|
||||
|
||||
/// A plugin with Run Anything entries for its prefixes (API 1.18).
|
||||
world plugin-run-anything { include plugin; export run-anything-provider; }
|
||||
/// Export-only Run Anything provider, composed with the base plugin world.
|
||||
world run-anything-exports { export run-anything-provider; }
|
||||
|
||||
/// A plugin completing fields of its own run configurations (API 1.18).
|
||||
world plugin-run-configuration-completion { include plugin; export run-configuration-completion; }
|
||||
/// Export-only run configuration completion, composed with the base plugin world.
|
||||
world run-configuration-completion-exports { export run-configuration-completion; }
|
||||
|
||||
/// A plugin with custom Search Everywhere categories.
|
||||
world plugin-search { include plugin; export search-provider; }
|
||||
/// Optional export composed with the base plugin by the SDK.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Editor features a plugin provides for the languages it declares under
|
||||
/// `[[contributes.providers]]` (the host calls only declared kinds). They run
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Project-scoped targets owned by the registering plugin (API 1.4).
|
||||
interface run-targets {
|
||||
|
||||
@@ -1,11 +1,29 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Launches this plugin's configurations in the invoking window's Run tool window.
|
||||
interface run {
|
||||
use types.{error};
|
||||
/// Output stream transport for a plugin-owned run configuration (API 1.18).
|
||||
/// Ordinary pseudo-terminals combine stdout and stderr and can change
|
||||
/// buffering, input handling, and terminal behavior.
|
||||
enum output-mode {
|
||||
/// Separate stdout and stderr pipes in the Run console (default).
|
||||
pipes,
|
||||
/// Pseudo-terminal ("Emulate terminal in output console").
|
||||
pty,
|
||||
}
|
||||
/// Per-launch options for `start-with-options` (API 1.18).
|
||||
record start-options {
|
||||
debug: bool,
|
||||
/// Optional per-invocation override. A user-saved override wins over
|
||||
/// this value, which wins over the plugin configuration default.
|
||||
output-mode: option<output-mode>,
|
||||
}
|
||||
/// Starts an owned configuration, appending args. Debug requires a debugger.
|
||||
/// Only from a window command/event. The returned id receives run-exited.
|
||||
start: func(config: string, args: list<string>, debug: bool) -> result<string, error>;
|
||||
/// Starts an owned configuration with launch options, appending args (API 1.18).
|
||||
start-with-options: func(config: string, args: list<string>, options: start-options) -> result<string, error>;
|
||||
}
|
||||
|
||||
/// Optional dynamic configurations, refreshed alongside run detectors.
|
||||
@@ -64,6 +82,32 @@ interface launch-configurations {
|
||||
configurations: func(project-root: string) -> list<launch-configuration>;
|
||||
}
|
||||
|
||||
/// Optional dynamic configurations with environment, debugger, and output mode (API 1.18).
|
||||
/// When exported, the IDE uses this instead of `launch-configurations` and `run-configurations`.
|
||||
interface execution-configurations {
|
||||
use launch-configurations.{debugger};
|
||||
use run.{output-mode};
|
||||
/// `launch-configuration` with a default output transport mode.
|
||||
record execution-configuration {
|
||||
id: string,
|
||||
name: string,
|
||||
program: string,
|
||||
args: list<string>,
|
||||
cwd: option<string>,
|
||||
test: bool,
|
||||
framework: option<string>,
|
||||
/// Variables added to the run's environment (at most 64). A name the IDE's own
|
||||
/// environment already has, such as `PATH`, is refused like in `process`.
|
||||
env: list<tuple<string, string>>,
|
||||
/// None: Debug infers the debugger from a source file in `args`, as before.
|
||||
debugger: option<debugger>,
|
||||
/// Default output stream mode (`pipes` or `pty`).
|
||||
output-mode: output-mode,
|
||||
}
|
||||
/// Returns the complete set for this project root.
|
||||
configurations: func(project-root: string) -> list<execution-configuration>;
|
||||
}
|
||||
|
||||
/// Optional parser for test configurations whose framework is plugin.
|
||||
interface test-results {
|
||||
use types.{location, extension};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// On-demand results for `[[contributes.searchCategories]]`. Optional, API 1.13.
|
||||
interface search-provider {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Optional export (world `plugin-semantic-tokens`): semantic colouring of
|
||||
/// documents of the languages declared with the `semantic-tokens` provider
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Shared types. Positions are 0-based lines and UTF-16 code unit columns,
|
||||
/// as in the editor and LSP.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
/// Declarative views: tool windows declared
|
||||
/// under `[[contributes.views]]` and custom editors under
|
||||
@@ -147,6 +147,12 @@ interface views {
|
||||
/// Opens or focuses a running session with this key; env is append-only.
|
||||
/// Only from a window command/event; the id receives one terminal-exited.
|
||||
open-terminal-session: func(key: string, title: string, cmd: command) -> result<string, error>;
|
||||
/// `open-terminal-session` started in `cwd` (API 1.18): a directory of the invoking
|
||||
/// window's project, relative to its root (`""` is the root). It must exist and stay
|
||||
/// inside the project once symlinks are resolved; `invalid` otherwise. Trust and the
|
||||
/// approved program are the project's, whatever the directory. A running session with
|
||||
/// this key is focused as it is, without moving it.
|
||||
open-terminal-session-in: func(key: string, title: string, cmd: command, cwd: string) -> result<string, error>;
|
||||
/// Writes to this plugin's running keyed terminal in the invoking window.
|
||||
write-terminal: func(key: string, text: string) -> result<_, error>;
|
||||
/// Opens the existing content editor protocol without a web view.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package openidea:[email protected]7.0;
|
||||
package openidea:[email protected]8.0;
|
||||
|
||||
interface workspace {
|
||||
use types.{error, location};
|
||||
@@ -12,6 +12,12 @@ interface workspace {
|
||||
/// Reading the returned project still requires `project.read`.
|
||||
project-of: func(path: string) -> option<project>;
|
||||
|
||||
/// The project of the window this call serves (API 1.18): the invoking window's for
|
||||
/// commands and events, the editor's window's for `gutter-actions` and `hover-actions`.
|
||||
/// `none` when the call serves no window. Unlike `project-of`, it tells overlapping
|
||||
/// projects apart. Reading the returned project still requires `project.read`.
|
||||
invoking-project: func() -> option<project>;
|
||||
|
||||
/// What a path inside a project is.
|
||||
enum file-kind {
|
||||
file,
|
||||
@@ -103,6 +109,10 @@ interface workspace {
|
||||
/// the current call's deadline fails. A closed project is not-found.
|
||||
/// Requires `project.read`.
|
||||
symbols: func(query: string, limit: u32) -> result<list<symbol-info>, error>;
|
||||
/// Monotonically increasing project state generation (API 1.18).
|
||||
/// Increments on project file changes. Fails with `not-found` when closed.
|
||||
/// Requires `project.read`.
|
||||
generation: func() -> result<u64, error>;
|
||||
}
|
||||
|
||||
/// Projects open in any window. Requires `project.read`.
|
||||
|
||||
@@ -69,10 +69,7 @@ fn output_mode_precedence_and_disallowed_combinations() {
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
mock.configuration_run_options()
|
||||
.into_iter()
|
||||
.map(|(id, _, _, _, mode)| (id, mode))
|
||||
.collect::<Vec<_>>(),
|
||||
mock.configuration_run_options().into_iter().map(|(id, _, _, _, mode)| (id, mode)).collect::<Vec<_>>(),
|
||||
vec![
|
||||
(id1, OutputMode::Pty),
|
||||
(id2, OutputMode::Pipes),
|
||||
@@ -85,34 +82,46 @@ fn output_mode_precedence_and_disallowed_combinations() {
|
||||
|
||||
// Debug with None forces pipes; explicit Pty with debug is rejected.
|
||||
mock.set_user_run_output_override("pty-default", None);
|
||||
let debug_id = host::start_run_with_options(
|
||||
"pty-default",
|
||||
&[],
|
||||
&RunStartOptions { debug: true, output_mode: None },
|
||||
)
|
||||
.unwrap();
|
||||
let debug_id =
|
||||
host::start_run_with_options("pty-default", &[], &RunStartOptions { debug: true, output_mode: None }).unwrap();
|
||||
assert_eq!(mock.configuration_run_options().last().unwrap().0, debug_id);
|
||||
assert_eq!(mock.configuration_run_options().last().unwrap().4, OutputMode::Pipes);
|
||||
assert!(matches!(
|
||||
host::start_run_with_options("pty-default", &[], &RunStartOptions { debug: true, output_mode: Some(OutputMode::Pty) }),
|
||||
host::start_run_with_options(
|
||||
"pty-default",
|
||||
&[],
|
||||
&RunStartOptions { debug: true, output_mode: Some(OutputMode::Pty) }
|
||||
),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
|
||||
// Disallowed combinations: test, stdin redirection, remote target.
|
||||
assert!(matches!(
|
||||
host::start_run_with_options("test-pipes", &[], &RunStartOptions { debug: false, output_mode: Some(OutputMode::Pty) }),
|
||||
host::start_run_with_options(
|
||||
"test-pipes",
|
||||
&[],
|
||||
&RunStartOptions { debug: false, output_mode: Some(OutputMode::Pty) }
|
||||
),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
mock.set_run_configuration_stdin_file("pipes-default", true);
|
||||
mock.set_user_run_output_override("pipes-default", None);
|
||||
assert!(matches!(
|
||||
host::start_run_with_options("pipes-default", &[], &RunStartOptions { debug: false, output_mode: Some(OutputMode::Pty) }),
|
||||
host::start_run_with_options(
|
||||
"pipes-default",
|
||||
&[],
|
||||
&RunStartOptions { debug: false, output_mode: Some(OutputMode::Pty) }
|
||||
),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
mock.set_run_configuration_stdin_file("pipes-default", false);
|
||||
mock.set_run_configuration_remote_target("pipes-default", true);
|
||||
assert!(matches!(
|
||||
host::start_run_with_options("pipes-default", &[], &RunStartOptions { debug: false, output_mode: Some(OutputMode::Pty) }),
|
||||
host::start_run_with_options(
|
||||
"pipes-default",
|
||||
&[],
|
||||
&RunStartOptions { debug: false, output_mode: Some(OutputMode::Pty) }
|
||||
),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
}
|
||||
@@ -240,9 +240,7 @@ fn settings_set_now(
|
||||
value: &str,
|
||||
) -> IdeResult<Settings> {
|
||||
let applied = ide_host::ops::project::set_settings(&state.host, window, scope, key, value)?;
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
state.host.mcp.apply(&state.host);
|
||||
}
|
||||
ide_host::ops::project::apply_setting(&state.host, window, key);
|
||||
if key == "toolDownloads" || key.starts_with("toolDownloads.") {
|
||||
state.plugins.set_downloads(state.host.global_settings.effective().tool_downloads);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "OpenIDEA",
|
||||
"version": "0.1.53",
|
||||
"version": "0.1.54",
|
||||
"identifier": "ai.l0ng.openidea",
|
||||
"build": {
|
||||
"beforeDevCommand": "pnpm dev",
|
||||
|
||||
@@ -244,6 +244,7 @@ doc_outline always project_host bin
|
||||
doc_python_facts always project_host bindings async
|
||||
doc_rearrange always project_host bindings async
|
||||
doc_reload_from_disk always project_host bindings async
|
||||
doc_remember_encoding always project_host bindings async
|
||||
doc_save always project_host bindings async
|
||||
doc_save_all always project_host bindings async
|
||||
doc_save_as always project_host bindings async
|
||||
|
||||
+41
-4
@@ -623,6 +623,13 @@ export const commands = {
|
||||
docRearrange: (doc: DocId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("doc_rearrange", { doc })),
|
||||
/** Load Changes from Disk: discards the buffer's unsaved changes and reads its file again. */
|
||||
docReloadFromDisk: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_reload_from_disk", { doc })),
|
||||
/**
|
||||
* Keeps the encoding the user chose for a project file in the project's File Encodings
|
||||
* mappings, so the file opens in it again. A converted document is kept once it is saved:
|
||||
* until then its file is still in the old encoding. Nothing is kept for a document without
|
||||
* a file in the project.
|
||||
*/
|
||||
docRememberEncoding: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_remember_encoding", { doc })),
|
||||
docSave: (doc: DocId) => typedError<null, IdeError>(__TAURI_INVOKE("doc_save", { doc })),
|
||||
docSaveAll: () => typedError<null, IdeError>(__TAURI_INVOKE("doc_save_all")),
|
||||
/**
|
||||
@@ -6737,7 +6744,10 @@ export type EditorConfigProps = {
|
||||
indentSize: number | null,
|
||||
tabWidth: number | null,
|
||||
endOfLine: LineEnding | null,
|
||||
/** `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be` or `latin1`. */
|
||||
/**
|
||||
* `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be`, `latin1` or an encoding
|
||||
* Settings › Editor › File Encodings lists (`iso-8859-15`, `windows-1252`, `gbk`, …).
|
||||
*/
|
||||
charset: string | null,
|
||||
trimTrailingWhitespace: boolean | null,
|
||||
insertFinalNewline: boolean | null,
|
||||
@@ -6864,7 +6874,7 @@ export type EditorSettings_Deserialize = {
|
||||
gutterIconsDisabled?: string[],
|
||||
showGutterIcons?: boolean,
|
||||
codeStyle?: CodeStyleSettings_Deserialize,
|
||||
encodings?: EncodingSettings,
|
||||
encodings?: EncodingSettings_Deserialize,
|
||||
};
|
||||
|
||||
export type EditorSettings_Serialize = {
|
||||
@@ -6924,7 +6934,7 @@ export type EditorSettings_Serialize = {
|
||||
gutterIconsDisabled: string[],
|
||||
showGutterIcons: boolean,
|
||||
codeStyle: CodeStyleSettings_Serialize,
|
||||
encodings: EncodingSettings,
|
||||
encodings: EncodingSettings_Serialize,
|
||||
};
|
||||
|
||||
/** Editor › General › Editor Tabs. */
|
||||
@@ -6957,7 +6967,10 @@ export type EditorTabsSettings = {
|
||||
export type EmptyCherryPickAction = "skip" | "createEmpty";
|
||||
|
||||
/** Editor › File Encodings. */
|
||||
export type EncodingSettings = {
|
||||
export type EncodingSettings = EncodingSettings_Serialize | EncodingSettings_Deserialize;
|
||||
|
||||
/** Editor › File Encodings. */
|
||||
export type EncodingSettings_Deserialize = {
|
||||
/** Fallback for files outside the project that are not valid UTF-8 (WHATWG label). */
|
||||
global?: string,
|
||||
/** Encoding of new files and fallback for project files that are not valid UTF-8. */
|
||||
@@ -6968,6 +6981,30 @@ export type EncodingSettings = {
|
||||
nativeToAscii?: boolean,
|
||||
/** Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows). */
|
||||
utf8Bom?: string,
|
||||
/**
|
||||
* Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
* relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
*/
|
||||
mappings?: { [key in string]: string },
|
||||
};
|
||||
|
||||
/** Editor › File Encodings. */
|
||||
export type EncodingSettings_Serialize = {
|
||||
/** Fallback for files outside the project that are not valid UTF-8 (WHATWG label). */
|
||||
global: string,
|
||||
/** Encoding of new files and fallback for project files that are not valid UTF-8. */
|
||||
project: string,
|
||||
/** Fallback for `.properties` files. */
|
||||
properties: string,
|
||||
/** Display properties Unicode escapes as characters and save non-ASCII as escapes. */
|
||||
nativeToAscii: boolean,
|
||||
/** Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows). */
|
||||
utf8Bom: string,
|
||||
/**
|
||||
* Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
* relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
*/
|
||||
mappings: { [key in string]: string },
|
||||
};
|
||||
|
||||
export type EntryKind = "file" | "dir" | "symlink";
|
||||
|
||||
@@ -60,6 +60,8 @@ export interface DocBackend {
|
||||
setLineEnding(doc: DocId, lineEnding: LineEnding): Promise<void>;
|
||||
/** "Reload with Encoding" (`reload`) or "Convert to Encoding"; resolves to the new encoding and BOM state. */
|
||||
setEncoding(doc: DocId, encoding: string, reload: boolean): Promise<DocumentEncoding>;
|
||||
/** Keeps the encoding the user chose for a project file in the project's settings, for the next time it opens. */
|
||||
rememberEncoding?(doc: DocId): Promise<void>;
|
||||
/** Adds or removes the BOM on a UTF-8 document; the change is written on save. */
|
||||
setBom(doc: DocId, hasBom: boolean): Promise<DocumentEncoding>;
|
||||
outline(doc: DocId): Promise<OutlineItem[]>;
|
||||
@@ -106,6 +108,7 @@ export const ipcBackend: DocBackend = {
|
||||
snapshot: (doc) => call(commands.docSnapshot(doc)),
|
||||
setLineEnding: async (doc, le) => void (await call(commands.docSetLineEnding(doc, le))),
|
||||
setEncoding: (doc, encoding, reload) => call(commands.docSetEncoding(doc, encoding, reload)),
|
||||
rememberEncoding: async (doc) => void (await call(commands.docRememberEncoding(doc))),
|
||||
setBom: (doc, hasBom) => call(commands.docSetBom(doc, hasBom)),
|
||||
outline: (doc) => call(commands.docOutline(doc)),
|
||||
folding: (doc) => call(commands.docFolding(doc)),
|
||||
|
||||
@@ -534,12 +534,20 @@ function EncodingPicker({ meta }: { meta: DocMeta }) {
|
||||
setTarget(null);
|
||||
const model = editorController().manager.get(meta.path);
|
||||
if (!model || !(reload ? canReload : canConvert)) return;
|
||||
void editorController()
|
||||
.manager.backend.setEncoding(meta.doc, encoding, reload)
|
||||
const { backend } = editorController().manager;
|
||||
void backend
|
||||
.setEncoding(meta.doc, encoding, reload)
|
||||
.then((enc) => {
|
||||
model.setMeta({ encoding: enc.encoding, hasBom: enc.hasBom, ...(reload ? {} : { dirty: true }) });
|
||||
// Reopening the tab must fetch the re-decoded contents, not the old cache.
|
||||
if (reload && isVirtualUri(meta.path)) invalidateVirtualDocument(meta.path);
|
||||
backend.rememberEncoding?.(meta.doc).catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: tx("The encoding was not saved to the project settings"),
|
||||
body: e instanceof Error ? e.message : String(e),
|
||||
}),
|
||||
);
|
||||
})
|
||||
.catch((e: unknown) =>
|
||||
notifications().notify({
|
||||
|
||||
@@ -4,13 +4,15 @@ import type { EditorStatus } from "../controller";
|
||||
import type { DocMeta } from "../model/document";
|
||||
|
||||
const setEncoding = vi.fn();
|
||||
const rememberEncoding = vi.fn();
|
||||
const setMeta = vi.fn();
|
||||
const notify = vi.fn();
|
||||
|
||||
vi.mock("../controller", async () => {
|
||||
const { create } = await import("zustand");
|
||||
return {
|
||||
editorController: () => ({
|
||||
manager: { get: () => ({ setMeta }), backend: { setEncoding } },
|
||||
manager: { get: () => ({ setMeta }), backend: { setEncoding, rememberEncoding } },
|
||||
slots: new Map(),
|
||||
}),
|
||||
useEditorStatus: create<{ status: EditorStatus | null }>(() => ({ status: null })),
|
||||
@@ -20,6 +22,11 @@ vi.mock("../controller", async () => {
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/workbench/contributions", async (original) => ({
|
||||
...(await original<typeof import("@/workbench/contributions")>()),
|
||||
notifications: () => ({ notify }),
|
||||
}));
|
||||
|
||||
vi.mock("@/platform/virtualDocs", () => ({
|
||||
isVirtualUri: (s: string) => s.startsWith("jdt:") || s.startsWith("jar:"),
|
||||
invalidateVirtualDocument: vi.fn(),
|
||||
@@ -63,6 +70,7 @@ const button = (name: string) => screen.getByRole<HTMLButtonElement>("button", {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
rememberEncoding.mockResolvedValue(undefined);
|
||||
useDocMeta.setState({}, true);
|
||||
useEditorStatus.setState({ status: null });
|
||||
});
|
||||
@@ -142,3 +150,45 @@ it("offers ISO-8859-15, the Latin-9 encoding of legacy Western European projects
|
||||
expect(setEncoding).toHaveBeenCalledWith(1, "iso-8859-15", false);
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
describe("remembering the chosen encoding", () => {
|
||||
const pick = (action: "Reload" | "Convert") => {
|
||||
const view = openPicker(meta({ path: "/p/Main.java", readOnly: false }));
|
||||
choose("ISO-8859-15");
|
||||
fireEvent.click(button(action));
|
||||
return view;
|
||||
};
|
||||
|
||||
it.each(["Reload", "Convert"] as const)("keeps the choice once %s has applied it", async (action) => {
|
||||
setEncoding.mockResolvedValue({ encoding: "iso-8859-15", hasBom: false });
|
||||
const view = pick(action);
|
||||
expect(rememberEncoding).not.toHaveBeenCalled();
|
||||
await waitFor(() => expect(rememberEncoding).toHaveBeenCalledWith(1));
|
||||
expect(rememberEncoding).toHaveBeenCalledTimes(1);
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("keeps nothing when the encoding could not be applied", async () => {
|
||||
setEncoding.mockRejectedValue(new Error("unmappable character"));
|
||||
const view = pick("Convert");
|
||||
await waitFor(() => expect(notify).toHaveBeenCalledWith(expect.objectContaining({ level: "error" })));
|
||||
expect(rememberEncoding).not.toHaveBeenCalled();
|
||||
view.unmount();
|
||||
});
|
||||
|
||||
it("keeps the new encoding and warns when the project settings cannot be written", async () => {
|
||||
setEncoding.mockResolvedValue({ encoding: "iso-8859-15", hasBom: false });
|
||||
rememberEncoding.mockRejectedValue(new Error("settings.toml is not valid TOML"));
|
||||
const view = pick("Convert");
|
||||
await waitFor(() =>
|
||||
expect(notify).toHaveBeenCalledWith({
|
||||
level: "warning",
|
||||
title: "The encoding was not saved to the project settings",
|
||||
body: "settings.toml is not valid TOML",
|
||||
}),
|
||||
);
|
||||
expect(setMeta).toHaveBeenCalledWith({ encoding: "iso-8859-15", hasBom: false, dirty: true });
|
||||
view.unmount();
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,7 @@ export function authorSummary(blame: readonly BlameLine[], from: number, to: num
|
||||
}
|
||||
|
||||
/**
|
||||
* The date exactly as the blame gutter renders it (`features/vcs/model.ts` `formatDate`): the user's
|
||||
* The date as the blame gutter renders it: the user's
|
||||
* pattern when the Date Formats override is on, the system's compact date otherwise. One commit then
|
||||
* reads the same in the gutter, the hints and the Git log.
|
||||
*/
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
width: 100%;
|
||||
height: 300px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
border-radius: var(--radius-small);
|
||||
background: var(--bg-editor, var(--bg));
|
||||
overflow: hidden;
|
||||
padding: 6px 8px;
|
||||
|
||||
@@ -339,109 +339,120 @@ function TaskChanges({ task, tabKey }: { task: AgentTask; tabKey: string }) {
|
||||
});
|
||||
}
|
||||
};
|
||||
const items = useDiffItems(task, rows, grouped, scope);
|
||||
// Running, the task is published again with every token count: its diffs only need these fields.
|
||||
const { id: taskId, base, isolation, branch, cwd } = task;
|
||||
const diffTask = useMemo(
|
||||
() => ({ id: taskId, base, isolation, branch, cwd }),
|
||||
[taskId, base, isolation, branch, cwd],
|
||||
);
|
||||
const items = useDiffItems(diffTask, rows, grouped, scope);
|
||||
const diff = useRef<CombinedDiffHandle>(null);
|
||||
const busy = task.status === "starting" || task.status === "running";
|
||||
const fileTree =
|
||||
changes === null ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Tree<ChangeRow>
|
||||
key={view}
|
||||
aria-label="Changed files"
|
||||
roots={rows}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) =>
|
||||
n.type === "file"
|
||||
? basename(n.change.path)
|
||||
: n.type === "commit"
|
||||
? n.commit.summary
|
||||
: n.type === "repo"
|
||||
? basename(n.root)
|
||||
: n.label
|
||||
}
|
||||
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
|
||||
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
|
||||
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
|
||||
activateExpandable={(n) => n.type === "commit"}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead) => {
|
||||
if (lead?.type === "file" && !lead.commit) setSelected(sel);
|
||||
// The diff follows the tree: a row shows its first file.
|
||||
const first = lead && firstFile(lead);
|
||||
if (first) diff.current?.reveal(first);
|
||||
}}
|
||||
onActivate={(n) => {
|
||||
const first = firstFile(n);
|
||||
if (first) diff.current?.reveal(first);
|
||||
}}
|
||||
renderNode={(n) => {
|
||||
if (n.type === "group") {
|
||||
// Memoized like the diffs: a task update (every token count while it runs) mustn't render every row again.
|
||||
const loading = changes === null;
|
||||
const fileTree = useMemo(
|
||||
() =>
|
||||
loading ? (
|
||||
<Spinner />
|
||||
) : (
|
||||
<Tree<ChangeRow>
|
||||
key={view}
|
||||
aria-label="Changed files"
|
||||
roots={rows}
|
||||
getKey={(n) => n.key}
|
||||
getLabel={(n) =>
|
||||
n.type === "file"
|
||||
? basename(n.change.path)
|
||||
: n.type === "commit"
|
||||
? n.commit.summary
|
||||
: n.type === "repo"
|
||||
? basename(n.root)
|
||||
: n.label
|
||||
}
|
||||
getChildren={(n) => (n.type === "file" ? undefined : n.children)}
|
||||
isExpandable={(n) => n.type !== "file" && n.children.length > 0}
|
||||
defaultExpanded={[...(grouped ? ["group:uncommitted", "group:committed"] : []), ...repositoryKeys(rows)]}
|
||||
activateExpandable={(n) => n.type === "commit"}
|
||||
selected={selected}
|
||||
onSelectionChange={(sel, lead) => {
|
||||
if (lead?.type === "file" && !lead.commit) setSelection({ view, keys: sel });
|
||||
// The diff follows the tree: a row shows its first file.
|
||||
const first = lead && firstFile(lead);
|
||||
if (first) diff.current?.reveal(first);
|
||||
}}
|
||||
onActivate={(n) => {
|
||||
const first = firstFile(n);
|
||||
if (first) diff.current?.reveal(first);
|
||||
}}
|
||||
renderNode={(n) => {
|
||||
if (n.type === "group") {
|
||||
return (
|
||||
<span className={styles.changeGroup}>
|
||||
<span className={styles.changeGroupName}>
|
||||
{n.label === "Uncommitted" ? <T>Uncommitted</T> : <T>Committed</T>}
|
||||
</span>
|
||||
<span className={styles.muted}>
|
||||
{n.label === "Committed"
|
||||
? tx(n.count === 1 ? "1 commit" : "{count} commits").replace("{count}", String(n.count))
|
||||
: `${n.count} ${tx(n.count === 1 ? "file" : "files")}`}
|
||||
</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.added > 0 && <span className={styles.added}>+{n.added}</span>}{" "}
|
||||
{n.removed > 0 && <span className={styles.removed}>−{n.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "repo") {
|
||||
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
|
||||
const stats = statsOf(files);
|
||||
return (
|
||||
<span className={styles.changeGroup} title={n.root}>
|
||||
<Icon name="folder" size={14} />
|
||||
<span className={styles.changeGroupName}>{basename(n.root)}</span>
|
||||
<span className={styles.muted}>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "commit") {
|
||||
const stats = statsOf(n.commit.files);
|
||||
return (
|
||||
<span className={styles.changeCommit} title={n.commit.message}>
|
||||
<Icon name="commit" size={14} />
|
||||
<span className={styles.changeCommitHash}>{n.commit.shortId}</span>
|
||||
<span className={styles.changeCommitSummary}>{n.commit.summary}</span>
|
||||
{n.commit.timeMs != null && (
|
||||
<span className={styles.changeCommitTime}>{formatSentAt(n.commit.timeMs)}</span>
|
||||
)}
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className={styles.changeGroup}>
|
||||
<span className={styles.changeGroupName}>
|
||||
{n.label === "Uncommitted" ? <T>Uncommitted</T> : <T>Committed</T>}
|
||||
</span>
|
||||
<span className={styles.muted}>
|
||||
{n.label === "Committed"
|
||||
? tx(n.count === 1 ? "1 commit" : "{count} commits").replace("{count}", String(n.count))
|
||||
: `${n.count} ${tx(n.count === 1 ? "file" : "files")}`}
|
||||
<span className={styles.change} title={n.change.relPath}>
|
||||
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} />
|
||||
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
|
||||
{basename(n.change.path)}
|
||||
</span>
|
||||
<span className={styles.changeDir}>{changeDir(diffTask, n.change)}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.added > 0 && <span className={styles.added}>+{n.added}</span>}{" "}
|
||||
{n.removed > 0 && <span className={styles.removed}>−{n.removed}</span>}
|
||||
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
|
||||
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "repo") {
|
||||
const files = n.children.flatMap((c) => (c.type === "file" ? [c.change] : []));
|
||||
const stats = statsOf(files);
|
||||
return (
|
||||
<span className={styles.changeGroup} title={n.root}>
|
||||
<Icon name="folder" size={14} />
|
||||
<span className={styles.changeGroupName}>{basename(n.root)}</span>
|
||||
<span className={styles.muted}>{`${files.length} ${tx(files.length === 1 ? "file" : "files")}`}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (n.type === "commit") {
|
||||
const stats = statsOf(n.commit.files);
|
||||
return (
|
||||
<span className={styles.changeCommit} title={n.commit.message}>
|
||||
<Icon name="commit" size={14} />
|
||||
<span className={styles.changeCommitHash}>{n.commit.shortId}</span>
|
||||
<span className={styles.changeCommitSummary}>{n.commit.summary}</span>
|
||||
{n.commit.timeMs != null && (
|
||||
<span className={styles.changeCommitTime}>{formatSentAt(n.commit.timeMs)}</span>
|
||||
)}
|
||||
<span className={styles.changeStat}>
|
||||
{stats.added > 0 && <span className={styles.added}>+{stats.added}</span>}{" "}
|
||||
{stats.removed > 0 && <span className={styles.removed}>−{stats.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span className={styles.change} title={n.change.relPath}>
|
||||
<Icon name={fileIconName(basename(n.change.path), n.change.path)} size={16} />
|
||||
<span className={styles.changeName} style={{ color: KIND_COLOR[n.change.kind] }}>
|
||||
{basename(n.change.path)}
|
||||
</span>
|
||||
<span className={styles.changeDir}>{changeDir(task, n.change)}</span>
|
||||
<span className={styles.changeStat}>
|
||||
{n.change.added > 0 && <span className={styles.added}>+{n.change.added}</span>}{" "}
|
||||
{n.change.removed > 0 && <span className={styles.removed}>−{n.change.removed}</span>}
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
[loading, view, rows, grouped, selected, diffTask],
|
||||
);
|
||||
return (
|
||||
<section className={styles.changes} aria-label={tx("Changes")}>
|
||||
<CombinedDiffView
|
||||
@@ -542,6 +553,9 @@ function TaskChanges({ task, tabKey }: { task: AgentTask; tabKey: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
/** What a task's diffs are built from. */
|
||||
type DiffTask = Pick<AgentTask, "id" | "base" | "isolation" | "branch" | "cwd">;
|
||||
|
||||
/** Key of the first file row at or under `row`: what the diff scrolls to for it. */
|
||||
function firstFile(row: ChangeRow): string | null {
|
||||
if (row.type === "file") return row.key;
|
||||
@@ -563,7 +577,7 @@ function fileRows(rows: readonly ChangeRow[]): Extract<ChangeRow, { type: "file"
|
||||
* whose diff is unchanged keeps its object, so its block doesn't load again as the task works.
|
||||
*/
|
||||
function useDiffItems(
|
||||
task: AgentTask,
|
||||
task: DiffTask,
|
||||
rows: readonly ChangeRow[],
|
||||
grouped: boolean,
|
||||
scope: ChangesScope,
|
||||
@@ -598,8 +612,11 @@ function useDiffItems(
|
||||
? before
|
||||
: item;
|
||||
});
|
||||
// Unchanged, the list keeps its array too: a new one renders every block again.
|
||||
setItems((before) =>
|
||||
before && before.length === kept.length && kept.every((item, i) => item === before[i]) ? before : kept,
|
||||
);
|
||||
previous.current = new Map(kept.map((item) => [item.key, item]));
|
||||
setItems(kept);
|
||||
});
|
||||
return () => {
|
||||
live = false;
|
||||
@@ -609,14 +626,14 @@ function useDiffItems(
|
||||
}
|
||||
|
||||
/** The folder of a changed file, as the tree names it. */
|
||||
function changeDir(task: AgentTask, change: AgentChange): string {
|
||||
function changeDir(task: Pick<AgentTask, "cwd">, change: AgentChange): string {
|
||||
if (!change.repo) return relativeDir(task.cwd, change.path);
|
||||
return change.relPath.includes("/") ? dirname(change.relPath) : "";
|
||||
}
|
||||
|
||||
/** Diff of `path` between the task's start (or its last turn's) and now. */
|
||||
async function changeDiffData(
|
||||
task: AgentTask,
|
||||
task: DiffTask,
|
||||
path: string,
|
||||
scope: ChangesScope,
|
||||
kind?: AgentChange["kind"],
|
||||
@@ -653,7 +670,7 @@ export async function openChangeDiff(task: AgentTask, path: string, scope: Chang
|
||||
}
|
||||
|
||||
/** Diff of `path` in the grouped view: `HEAD` ↔ the working file. */
|
||||
function uncommittedDiffData(task: AgentTask, change: AgentChange): DiffData {
|
||||
function uncommittedDiffData(task: DiffTask, change: AgentChange): DiffData {
|
||||
const left: DiffData["left"] =
|
||||
change.kind === "added" || change.kind === "untracked"
|
||||
? { type: "text", text: "", label: "(does not exist)", absent: true }
|
||||
@@ -674,14 +691,14 @@ function uncommittedDiffData(task: AgentTask, change: AgentChange): DiffData {
|
||||
}
|
||||
|
||||
/** Registration needed before a diff reads revisions inside the task's own worktree. */
|
||||
async function ensureTaskRepo(task: AgentTask) {
|
||||
async function ensureTaskRepo(task: DiffTask) {
|
||||
// A worktree is its own repository, outside the project's: `vcs_file_at` reads it only once
|
||||
// it is registered as an external log for this window.
|
||||
if (task.isolation === "worktree") await call(commands.vcsOpenExternalLog(task.cwd)).catch(() => undefined);
|
||||
}
|
||||
|
||||
/** Diff of a file of one of the task's commits: `parent ↔ commit`. */
|
||||
function commitFileDiff(task: AgentTask, commit: AgentCommit, file: AgentChange): DiffData {
|
||||
function commitFileDiff(task: DiffTask, commit: AgentCommit, file: AgentChange): DiffData {
|
||||
return commitFileDiffData(
|
||||
{
|
||||
id: commit.id,
|
||||
|
||||
@@ -197,6 +197,16 @@ it("leaves the backend alone while no project is open", async () => {
|
||||
expect(ipc.debugReplaceBreakpoints).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("doesn't sync the closed project's files once no project is open", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
addBreakpoint("/p/Main.java", 4);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(ipc.debugSetBreakpoints).toHaveBeenCalledOnce();
|
||||
loadBreakpoints(null);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(ipc.debugSetBreakpoints).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("flushes persisted breakpoints immediately after project loading", async () => {
|
||||
ipc.debugSetBreakpoints.mockResolvedValue({ status: "ok", data: [] });
|
||||
localStorage.setItem(
|
||||
|
||||
@@ -159,8 +159,10 @@ export function syncFile(path: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function sendFile(path: string) {
|
||||
if (!isTauri() || useProject.getState().project?.trusted === false) return;
|
||||
const { byFile, muted } = useBreakpoints.getState();
|
||||
// After the project closes, the files it had breakpoints in are rescheduled with empty lists;
|
||||
// the backend no longer has the project to clear them in.
|
||||
const { root, byFile, muted } = useBreakpoints.getState();
|
||||
if (!isTauri() || root === null || useProject.getState().project?.trusted === false) return;
|
||||
const list = byFile[path] ?? [];
|
||||
sent.set(
|
||||
path,
|
||||
|
||||
@@ -9,8 +9,9 @@ const scheme = (parent: string, ...options: string[]) =>
|
||||
describe("annotation colour of a theme plugin's scheme (#6108)", () => {
|
||||
it("keeps Darcula's annotation colour when the file only changes DEFAULT_METADATA", () => {
|
||||
const { tokens } = convertIcls(scheme("Darcula", opt("DEFAULT_METADATA", "1d8711")));
|
||||
// Java annotations are drawn with --syn-decorator.
|
||||
expect(tokens["--syn-annotation"]).toBe("#bbb529");
|
||||
expect(tokens["--syn-decorator"]).toBe("#1d8711");
|
||||
expect(tokens["--syn-decorator"]).toBe("#bbb529");
|
||||
});
|
||||
|
||||
it("takes the file's annotation key for annotations", () => {
|
||||
@@ -18,10 +19,20 @@ describe("annotation colour of a theme plugin's scheme (#6108)", () => {
|
||||
scheme("Darcula", opt("DEFAULT_METADATA", "1d8711"), opt("ANNOTATION_NAME_ATTRIBUTES", "9e880d")),
|
||||
);
|
||||
expect(tokens["--syn-annotation"]).toBe("#9e880d");
|
||||
expect(tokens["--syn-decorator"]).toBe("#9e880d");
|
||||
});
|
||||
|
||||
it("falls back to DEFAULT_METADATA without a bundled parent", () => {
|
||||
const { tokens } = convertIcls(
|
||||
`<scheme name="t" version="142"><attributes>${opt("DEFAULT_METADATA", "1d8711")}</attributes></scheme>`,
|
||||
);
|
||||
expect(tokens["--syn-annotation"]).toBe("#1d8711");
|
||||
expect(tokens["--syn-decorator"]).toBe("#1d8711");
|
||||
});
|
||||
|
||||
it("leaves a light parent's annotation colour to the base theme", () => {
|
||||
const { tokens } = convertIcls(scheme("Default", opt("DEFAULT_METADATA", "1d8711")));
|
||||
expect(tokens["--syn-annotation"]).toBeUndefined();
|
||||
expect(tokens["--syn-decorator"]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -163,9 +163,16 @@ export const ICLS_ATTRIBUTES: Record<string, Array<[Part, string]>> = {
|
||||
DEFAULT_PARAMETER: [["FOREGROUND", "--syn-param"]],
|
||||
DEFAULT_GLOBAL_VARIABLE: [["FOREGROUND", "--syn-global"]],
|
||||
DEFAULT_PREDEFINED_SYMBOL: [["FOREGROUND", "--syn-builtin"]],
|
||||
// Java annotations take the scheme's (or its parent's) annotation key, not DEFAULT_METADATA.
|
||||
ANNOTATION_NAME_ATTRIBUTES: [["FOREGROUND", "--syn-annotation"]],
|
||||
DEFAULT_METADATA: [["FOREGROUND", "--syn-decorator"]],
|
||||
// Java annotations (drawn with --syn-decorator, as decorators are) take the annotation key; DEFAULT_METADATA
|
||||
// only stands in for it (see `convertIcls`).
|
||||
ANNOTATION_NAME_ATTRIBUTES: [
|
||||
["FOREGROUND", "--syn-annotation"],
|
||||
["FOREGROUND", "--syn-decorator"],
|
||||
],
|
||||
DEFAULT_METADATA: [
|
||||
["FOREGROUND", "--syn-annotation"],
|
||||
["FOREGROUND", "--syn-decorator"],
|
||||
],
|
||||
DEFAULT_OPERATION_SIGN: [["FOREGROUND", "--syn-punct"]],
|
||||
DEFAULT_VALID_STRING_ESCAPE: [["FOREGROUND", "--syn-escape"]],
|
||||
DEFAULT_TAG: [["FOREGROUND", "--syn-tag"]],
|
||||
@@ -304,6 +311,9 @@ function resolveColor(value: string, named: Map<string, string>, depth = 0): str
|
||||
return ref !== undefined && depth < 8 ? resolveColor(ref, named, depth + 1) : null;
|
||||
}
|
||||
|
||||
/** IntelliJ's bundled schemes, which set ANNOTATION_NAME_ATTRIBUTES themselves. */
|
||||
const BUNDLED_PARENTS = new Set(["Default", "Darcula"]);
|
||||
|
||||
const attr = (tag: string, name: string) => new RegExp(`${name}="([^"]*)"`).exec(tag)?.[1];
|
||||
|
||||
/** Parses the colours and attributes of an `.icls` file into tokens. */
|
||||
@@ -339,10 +349,13 @@ export function convertIcls(xml: string): { name: string; dark: boolean | null;
|
||||
}
|
||||
attributes.set(m[1]!, parts);
|
||||
}
|
||||
// The annotation key falls back to DEFAULT_METADATA only where neither the file nor its bundled parent
|
||||
// (both set it) defines it, as for imported schemes (`platform/icls.ts`).
|
||||
const metadataUnused = attributes.has("ANNOTATION_NAME_ATTRIBUTES") || BUNDLED_PARENTS.has(parent);
|
||||
const textForeground = iclsColor(attributes.get("TEXT")?.get("FOREGROUND"));
|
||||
for (const [key, parts] of attributes) {
|
||||
const map = ICLS_ATTRIBUTES[key];
|
||||
if (!map) continue;
|
||||
if (!map || (key === "DEFAULT_METADATA" && metadataUnused)) continue;
|
||||
// `<value />` defines the key without colours, so the parent scheme's don't apply: it shows as plain text.
|
||||
if (empty.has(key)) {
|
||||
for (const [part, token] of map) if (part === "FOREGROUND") set([token], textForeground);
|
||||
@@ -356,7 +369,9 @@ export function convertIcls(xml: string): { name: string; dark: boolean | null;
|
||||
}
|
||||
if (parent === "Darcula") {
|
||||
// IntelliJ replaces a parent's attribute as a whole: what the file names, even empty or by baseAttributes, wins.
|
||||
const keys = [...body.matchAll(/<option name="([^"]+)"/g)].map((m) => m[1]!);
|
||||
const keys = [...body.matchAll(/<option name="([^"]+)"/g)]
|
||||
.map((m) => m[1]!)
|
||||
.filter((key) => key !== "DEFAULT_METADATA");
|
||||
const own = new Set(keys.flatMap((key) => (ICLS_ATTRIBUTES[key] ?? []).map(([, t]) => t)));
|
||||
for (const [token, value] of Object.entries(DARCULA_TOKENS)) if (!own.has(token)) tokens[token] ??= value;
|
||||
}
|
||||
|
||||
@@ -50,10 +50,11 @@
|
||||
min-height: 0;
|
||||
}
|
||||
.scroll {
|
||||
--scroll-pad-top: var(--space-2);
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
padding: var(--scroll-pad-top) var(--space-3) var(--space-2);
|
||||
}
|
||||
/* Only the blocks near the viewport are rendered, each at its offset in the full height. */
|
||||
.blocks {
|
||||
@@ -71,24 +72,50 @@
|
||||
border-radius: var(--radius-popup-large);
|
||||
background: var(--bg-editor);
|
||||
}
|
||||
/* The file's header stays at the top while its diff scrolls by. */
|
||||
/* The file's header stays at the top while its diff scrolls by. It sticks flush with the top
|
||||
edge (past the list's top padding) and draws its own top border over the block's, so a stuck
|
||||
header still reads as the top of a card. */
|
||||
.header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
top: calc(-1 * var(--scroll-pad-top));
|
||||
z-index: 3;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
margin: -1px -1px 0;
|
||||
padding: var(--space-3) 10px;
|
||||
background: var(--bg-editor);
|
||||
border-bottom: 1px solid var(--border);
|
||||
border: 1px solid var(--border);
|
||||
border-start-start-radius: inherit;
|
||||
border-start-end-radius: inherit;
|
||||
font-size: var(--fs-ui);
|
||||
}
|
||||
/* Covers the diff scrolling by above a stuck header and outside its rounded corners. */
|
||||
.header::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
top: calc(-1px - var(--scroll-pad-top));
|
||||
left: -1px;
|
||||
right: -1px;
|
||||
height: calc(var(--scroll-pad-top) + var(--radius-popup-large) + 1px);
|
||||
background: var(--bg-app);
|
||||
}
|
||||
/* The header's own background, painted over the cover. */
|
||||
.header::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
inset: 0;
|
||||
border-start-start-radius: calc(var(--radius-popup-large) - 1px);
|
||||
border-start-end-radius: calc(var(--radius-popup-large) - 1px);
|
||||
background: var(--bg-editor);
|
||||
}
|
||||
.block[data-collapsed] .header::after {
|
||||
border-radius: calc(var(--radius-popup-large) - 1px);
|
||||
}
|
||||
.block[data-collapsed] .header {
|
||||
margin-bottom: -1px;
|
||||
border-radius: inherit;
|
||||
border-bottom: 0;
|
||||
}
|
||||
.file {
|
||||
display: flex;
|
||||
@@ -138,7 +165,8 @@
|
||||
padding-block: 1px;
|
||||
}
|
||||
:global(:root[data-compact]) .scroll {
|
||||
padding: var(--space-1) var(--space-1-5);
|
||||
--scroll-pad-top: var(--space-1);
|
||||
padding: var(--scroll-pad-top) var(--space-1-5) var(--space-1);
|
||||
}
|
||||
:global(:root[data-compact]) .header {
|
||||
padding-block: 7px;
|
||||
|
||||
@@ -243,6 +243,8 @@ export function CombinedDiffView({
|
||||
const [viewStates] = useState(() => new Map<string, DiffViewState>());
|
||||
const [entriesCache] = useState<DiffEntriesCache>(() => new Map());
|
||||
const keys = useMemo(() => entries.map((e) => e.key), [entries]);
|
||||
// Each diff's own key, hashing its texts: worked out once, not on every scroll frame.
|
||||
const diffKeys = useMemo(() => items.map((item) => diffInput(item).key), [items]);
|
||||
|
||||
// Blocks that stay mounted when scrolled away: the one holding the keyboard focus, so typing still
|
||||
// reaches it, and with autosave off those with unsaved staged edits, which unmounting would save.
|
||||
@@ -253,12 +255,12 @@ export function CombinedDiffView({
|
||||
const slot = scrollRef.current?.contains(active) ? active?.closest<HTMLElement>("[data-index]") : null;
|
||||
if (slot) shown.add(Number(slot.dataset.index));
|
||||
if (useProject.getState().settings?.files?.autoSave === false)
|
||||
items.forEach((item, index) => {
|
||||
if (ownedStagedDocument(combinedDiffDocumentOwner(tabKey, diffInput(item).key))?.dirty) shown.add(index);
|
||||
diffKeys.forEach((key, index) => {
|
||||
if (ownedStagedDocument(combinedDiffDocumentOwner(tabKey, key))?.dirty) shown.add(index);
|
||||
});
|
||||
return [...shown].sort((a, b) => a - b);
|
||||
},
|
||||
[items, tabKey],
|
||||
[diffKeys, tabKey],
|
||||
);
|
||||
const virtualizer = useVirtualizer({
|
||||
count: items.length,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/** Pure VCS model helpers: effective file status, colours, decorations. */
|
||||
import type { ChangeKind, FileStatus } from "@/bindings";
|
||||
import type { FileDecoration } from "@/workbench/contributions";
|
||||
import { formatDay, formatTimestamp } from "@/platform/dateFormat";
|
||||
import { formatTimestamp } from "@/platform/dateFormat";
|
||||
import { tx, txPart } from "@/platform/i18n";
|
||||
|
||||
/** What a file looks like in IDEA's change lists (one kind per file). */
|
||||
@@ -137,10 +137,6 @@ export function formatTime(ms: number | null | undefined, now = Date.now()): str
|
||||
return ms ? formatTimestamp(ms, now) : "";
|
||||
}
|
||||
|
||||
export function formatDate(ms: number | null | undefined): string {
|
||||
return ms ? formatDay(new Date(ms), undefined, true) : "";
|
||||
}
|
||||
|
||||
export function formatSize(n: number): string {
|
||||
if (n < 1024) return `${n} B`;
|
||||
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
|
||||
|
||||
@@ -157,9 +157,18 @@ export function ImageViewer({ input, source }: { input: EditorInput; source?: st
|
||||
useForwardFocus(live ? NO_FOCUS_TARGET : rootRef);
|
||||
|
||||
const onLoad = (img: HTMLImageElement) => {
|
||||
if (!live) return applyNatural(img.naturalWidth, img.naturalHeight);
|
||||
// WebKit keeps the old natural size when a sized <img> gets a new SVG src; measure a detached copy.
|
||||
const loaded = img.src;
|
||||
const probe = new Image();
|
||||
probe.onload = () => img.src === loaded && applyNatural(probe.naturalWidth, probe.naturalHeight);
|
||||
probe.src = loaded;
|
||||
};
|
||||
|
||||
const applyNatural = (naturalW: number, naturalH: number) => {
|
||||
// SVGs without intrinsic size report 0×0; show them at a usable size.
|
||||
const w = img.naturalWidth || 300;
|
||||
const h = img.naturalHeight || 150;
|
||||
const w = naturalW || 300;
|
||||
const h = naturalH || 150;
|
||||
setNatural({ w, h });
|
||||
const a = available();
|
||||
const el = canvasRef.current;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
/** Markdown editor layout per editor tab: Editor only / Editor and Preview / Preview only. */
|
||||
import { createLayoutModes, modeOf, type LayoutMode } from "../layoutModes";
|
||||
import { createLayoutModes, modeOf } from "../layoutModes";
|
||||
|
||||
export type MarkdownMode = LayoutMode;
|
||||
export { modeOf };
|
||||
|
||||
const markdown = createLayoutModes("openidea.markdown.defaultMode");
|
||||
|
||||
@@ -72,6 +72,39 @@ describe("SVG editor", () => {
|
||||
expect(screen.queryByText("The SVG source is not valid.")).toBeNull();
|
||||
});
|
||||
|
||||
it("measures a retyped SVG's size from a fresh image, not the sized <img>", () => {
|
||||
// WebKit reports the previous natural size on the shown <img>; a detached Image reports the new one.
|
||||
const probes: { onload: (() => void) | null; src: string; naturalWidth: number; naturalHeight: number }[] = [];
|
||||
vi.stubGlobal(
|
||||
"Image",
|
||||
class {
|
||||
onload: (() => void) | null = null;
|
||||
naturalWidth = 360;
|
||||
naturalHeight = 300;
|
||||
set src(value: string) {
|
||||
this._src = value;
|
||||
probes.push(this);
|
||||
}
|
||||
get src() {
|
||||
return this._src;
|
||||
}
|
||||
_src = "";
|
||||
},
|
||||
);
|
||||
try {
|
||||
const source = '<svg xmlns="http://www.w3.org/2000/svg" width="360" height="300"/>';
|
||||
render(<ImageViewer input={imageInput(PATH)} source={source} />);
|
||||
Object.defineProperty(image(), "naturalWidth", { value: 400 });
|
||||
Object.defineProperty(image(), "naturalHeight", { value: 300 });
|
||||
fireEvent.load(image());
|
||||
expect(probes.map((p) => p.src)).toEqual([svgDataUrl(source)]);
|
||||
act(() => probes[0]?.onload?.());
|
||||
expect(screen.getByText("360 × 300")).toBeInTheDocument();
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the SVG layout apart from Markdown's, and the layout actions set the tab's own", async () => {
|
||||
const off = activateViewers();
|
||||
setContext("textEditorActive", true);
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { EDITOR_EXTRA_DEFAULTS, validateEditorExtras } from "./editorSettings";
|
||||
|
||||
it("has no encoding mappings unless the settings name some", () => {
|
||||
expect(EDITOR_EXTRA_DEFAULTS.encodings.mappings).toEqual({});
|
||||
expect(validateEditorExtras(undefined).encodings.mappings).toEqual({});
|
||||
expect(validateEditorExtras({ encodings: { mappings: "gbk" } }).encodings.mappings).toEqual({});
|
||||
});
|
||||
|
||||
it("keeps the encoding mappings that name a label", () => {
|
||||
const raw = {
|
||||
encodings: { project: "gbk", mappings: { "src/main/java": "iso-8859-15", "src/A.java": 5, lib: null } },
|
||||
};
|
||||
const { encodings } = validateEditorExtras(raw);
|
||||
expect(encodings.mappings).toEqual({ "src/main/java": "iso-8859-15" });
|
||||
expect(encodings.project).toBe("gbk");
|
||||
});
|
||||
@@ -260,7 +260,15 @@ export const EDITOR_EXTRA_DEFAULTS = {
|
||||
formatterOnTag: "@formatter:on",
|
||||
formatterTagsRegexp: false,
|
||||
},
|
||||
encodings: { global: "utf-8", project: "utf-8", properties: "iso-8859-1", nativeToAscii: false, utf8Bom: "never" },
|
||||
encodings: {
|
||||
global: "utf-8",
|
||||
project: "utf-8",
|
||||
properties: "iso-8859-1",
|
||||
nativeToAscii: false,
|
||||
utf8Bom: "never",
|
||||
/** Project-relative path of a file or folder (`/` separators) to its encoding label. */
|
||||
mappings: {} as Record<string, string>,
|
||||
},
|
||||
};
|
||||
|
||||
export type EditorExtras = typeof EDITOR_EXTRA_DEFAULTS;
|
||||
@@ -326,6 +334,9 @@ export function validateEditorExtras(raw: unknown): EditorExtras {
|
||||
if (!DOCSTRING_FORMATS.includes(out.docstringFormat)) out.docstringFormat = "rest";
|
||||
for (const k of ["codeVisionUsagesPosition", "codeVisionAuthorPosition"] as const)
|
||||
if (!["top", "right"].includes(out.inlay[k])) out.inlay[k] = "top";
|
||||
out.encodings.mappings = Object.fromEntries(
|
||||
Object.entries(out.encodings.mappings).filter(([, label]) => typeof label === "string"),
|
||||
);
|
||||
out.rainbowBracketColors = Math.min(5, Math.max(2, Math.round(out.rainbowBracketColors)));
|
||||
out.fontWeight = fontWeightOf(out.fontWeight, EDITOR_EXTRA_DEFAULTS.fontWeight);
|
||||
out.boldFontWeight = fontWeightOf(out.boldFontWeight, EDITOR_EXTRA_DEFAULTS.boldFontWeight);
|
||||
|
||||
@@ -896,6 +896,7 @@
|
||||
"Add UTF-8 BOM": "Add UTF-8 BOM",
|
||||
"Remove UTF-8 BOM": "Remove UTF-8 BOM",
|
||||
"Cannot change the UTF-8 BOM": "Cannot change the UTF-8 BOM",
|
||||
"The encoding was not saved to the project settings": "The encoding was not saved to the project settings",
|
||||
"Convert to cURL and Copy": "Convert to cURL and Copy",
|
||||
"Add Environment to Public File": "Add Environment to Public File",
|
||||
"Add Environment to Private File": "Add Environment to Private File",
|
||||
|
||||
@@ -1606,6 +1606,7 @@
|
||||
"Add UTF-8 BOM": "添加 UTF-8 BOM",
|
||||
"Remove UTF-8 BOM": "移除 UTF-8 BOM",
|
||||
"Cannot change the UTF-8 BOM": "无法更改 UTF-8 BOM",
|
||||
"The encoding was not saved to the project settings": "编码未保存到项目设置",
|
||||
"Copied code keeps the editor's syntax colors and font when pasted into documents and mail.": "复制的代码粘贴到文档和邮件中时会保留编辑器的语法颜色和字体。",
|
||||
"Copy": "复制",
|
||||
"Copy / Paste Special": "复制/选择性粘贴",
|
||||
|
||||
Reference in new issue
Заблокувати користувача