📦 Turbo Python
6fc62ea added
.github/workflows/release.yml +137 -0 | new file mode 100644 | ||
| @@ -0,0 +1,137 @@ | ||
| 1 | +name: Release | |
| 2 | + | |
| 3 | +# Publishes a release with the staged binaries whenever a tag v* is pushed — | |
| 4 | +# what ./01-release.tag.sh does at its last line. They are built by | |
| 5 | +# ./02-build-releases.sh, the same script one runs on a laptop, so a local | |
| 6 | +# build and a published one are the same pipeline. | |
| 7 | +# | |
| 8 | +# The tag alone already publishes the module: `go install …@TAG` works the | |
| 9 | +# moment 01 has run, with or without this workflow. What this adds is the page | |
| 10 | +# a person reads, and one binary per platform with a checksum to verify it | |
| 11 | +# against — the thing somebody without a Go toolchain needs. | |
| 12 | +# | |
| 13 | +# Rickub runs this as an ordinary GitHub Actions workflow. Two platform facts | |
| 14 | +# matter here: the job's GITHUB_TOKEN is the ONLY credential the release API | |
| 15 | +# (the /gh shim behind $GITHUB_API_URL) accepts — a personal token is refused — | |
| 16 | +# and it is read-only unless the workflow asks for `contents: write` below. | |
| 17 | +# That is why there is no longer a token file to keep out of git, and no | |
| 18 | +# 02-release.publish.sh or 04-release.upload-binaries.sh to run by hand. | |
| 19 | +# | |
| 20 | +# No workflow_dispatch on purpose: Rickub's dispatch API fires EVERY | |
| 21 | +# dispatchable workflow of a ref, so a repository should declare at most one. | |
| 22 | +on: | |
| 23 | + push: | |
| 24 | + tags: | |
| 25 | + - "v*" | |
| 26 | + | |
| 27 | +permissions: | |
| 28 | + contents: write | |
| 29 | + | |
| 30 | +concurrency: | |
| 31 | + group: release-${{ github.ref_name }} | |
| 32 | + cancel-in-progress: false | |
| 33 | + | |
| 34 | +jobs: | |
| 35 | + release: | |
| 36 | + name: publish ${{ github.ref_name }} | |
| 37 | + runs-on: ubuntu-latest | |
| 38 | + steps: | |
| 39 | + - name: Checkout | |
| 40 | + uses: actions/checkout@v4 | |
| 41 | + with: | |
| 42 | + # The whole history and the tags: the release notes below are read | |
| 43 | + # from the annotated tag's message, and the Makefile's default | |
| 44 | + # version comes from `git describe`. | |
| 45 | + fetch-depth: 0 | |
| 46 | + | |
| 47 | + - name: Set up Go | |
| 48 | + uses: actions/setup-go@v5 | |
| 49 | + with: | |
| 50 | + go-version-file: go.mod | |
| 51 | + cache: true | |
| 52 | + | |
| 53 | + - name: go test | |
| 54 | + # The suite includes tests that run ./01-release.tag.sh against a | |
| 55 | + # throwaway clone. They skip themselves when they see this, exactly as | |
| 56 | + # they do when the script itself calls make check — without it, a | |
| 57 | + # release job would start a release inside itself. | |
| 58 | + env: | |
| 59 | + TURBO_PYTHON_RELEASING: "1" | |
| 60 | + run: go test ./... -count=1 | |
| 61 | + | |
| 62 | + - name: Build the release | |
| 63 | + # release.env is git-ignored, so the tag is passed explicitly and the | |
| 64 | + # script falls back to "Turbo Python <tag>" for the description. | |
| 65 | + run: bash ./02-build-releases.sh "${GITHUB_REF_NAME}" | |
| 66 | + | |
| 67 | + - name: Release notes | |
| 68 | + id: notes | |
| 69 | + # The message ./01-release.tag.sh put on the annotated tag (ABOUT in | |
| 70 | + # release.env), then the two ways to get the editor and the links to | |
| 71 | + # the documentation AT THAT TAG — a release page is not inside the | |
| 72 | + # repository tree, so a relative path from it 404s, and a link to the | |
| 73 | + # branch would rot as the branch moves. A lightweight tag has no | |
| 74 | + # message: the tag name stands in. | |
| 75 | + run: | | |
| 76 | + set -euo pipefail | |
| 77 | + message="$(git for-each-ref "refs/tags/${GITHUB_REF_NAME}" --format='%(contents)' | sed '/^-----BEGIN PGP SIGNATURE-----/,$d')" | |
| 78 | + if [ -z "$(printf '%s' "${message}" | tr -d '[:space:]')" ]; then | |
| 79 | + message="Turbo Python ${GITHUB_REF_NAME}" | |
| 80 | + fi | |
| 81 | + tree="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/${GITHUB_REF_NAME}" | |
| 82 | + version="${GITHUB_REF_NAME#v}" | |
| 83 | + { | |
| 84 | + printf '%s\n\n' "${message}" | |
| 85 | + echo "Download the binary for your platform below, or install from the module proxy:" | |
| 86 | + echo | |
| 87 | + echo '```bash' | |
| 88 | + echo "go install $(go list -m)@${GITHUB_REF_NAME}" | |
| 89 | + echo '```' | |
| 90 | + echo | |
| 91 | + echo "Documentation: [English](${tree}/docs/en/README.md) · [Français](${tree}/docs/fr/README.md) · [how to install](${tree}/docs/en/how-to/install.md)" | |
| 92 | + echo | |
| 93 | + echo "- Commit: \`${GITHUB_SHA}\`" | |
| 94 | + echo "- Published by the Release workflow, run #${GITHUB_RUN_NUMBER}, with $(go env GOVERSION)" | |
| 95 | + echo | |
| 96 | + echo '## Running a download' | |
| 97 | + echo | |
| 98 | + echo '```bash' | |
| 99 | + echo "chmod +x turbo-python-${version}-<platform>" | |
| 100 | + echo "./turbo-python-${version}-<platform> main.py" | |
| 101 | + echo '```' | |
| 102 | + echo | |
| 103 | + echo "On macOS, an unsigned download is quarantined until you say otherwise: \`xattr -d com.apple.quarantine turbo-python-${version}-darwin-arm64\`." | |
| 104 | + echo | |
| 105 | + echo '## Checksums' | |
| 106 | + echo | |
| 107 | + echo 'Verify a download with `sha256sum -c SHA256SUMS --ignore-missing` (`shasum -a 256 -c` on macOS).' | |
| 108 | + echo | |
| 109 | + echo '```' | |
| 110 | + cat "release/${GITHUB_REF_NAME}/SHA256SUMS" | |
| 111 | + echo '```' | |
| 112 | + } > "${RUNNER_TEMP}/notes.md" | |
| 113 | + echo "path=${RUNNER_TEMP}/notes.md" >> "$GITHUB_OUTPUT" | |
| 114 | + | |
| 115 | + - name: Keep the binaries as a run artifact | |
| 116 | + # Downloadable from the run page even if the publish step below fails | |
| 117 | + # (an old CI node that does not forward /gh answers 403 there). | |
| 118 | + uses: actions/upload-artifact@v4 | |
| 119 | + with: | |
| 120 | + name: turbo-python-${{ github.ref_name }} | |
| 121 | + path: release/${{ github.ref_name }}/ | |
| 122 | + if-no-files-found: error | |
| 123 | + retention-days: 14 | |
| 124 | + | |
| 125 | + - name: Publish the release | |
| 126 | + uses: softprops/action-gh-release@v2 | |
| 127 | + with: | |
| 128 | + tag_name: ${{ github.ref_name }} | |
| 129 | + name: ${{ github.ref_name }} | |
| 130 | + body_path: ${{ steps.notes.outputs.path }} | |
| 131 | + draft: false | |
| 132 | + prerelease: ${{ contains(github.ref_name, '-') }} | |
| 133 | + files: | | |
| 134 | + release/${{ github.ref_name }}/turbo-python-* | |
| 135 | + release/${{ github.ref_name }}/SHA256SUMS | |
| 136 | + release/${{ github.ref_name }}/README.md | |
| 137 | + fail_on_unmatched_files: true | |
| new file mode 100644 | |||
| @@ -0,0 +1,137 @@ | |||
| 1 | +name: Release | ||
| 2 | + | ||
| 3 | +# Publishes a release with the staged binaries whenever a tag v* is pushed — | ||
| 4 | +# what ./01-release.tag.sh does at its last line. They are built by | ||
| 5 | +# ./02-build-releases.sh, the same script one runs on a laptop, so a local | ||
| 6 | +# build and a published one are the same pipeline. | ||
| 7 | +# | ||
| 8 | +# The tag alone already publishes the module: `go install …@TAG` works the | ||
| 9 | +# moment 01 has run, with or without this workflow. What this adds is the page | ||
| 10 | +# a person reads, and one binary per platform with a checksum to verify it | ||
| 11 | +# against — the thing somebody without a Go toolchain needs. | ||
| 12 | +# | ||
| 13 | +# Rickub runs this as an ordinary GitHub Actions workflow. Two platform facts | ||
| 14 | +# matter here: the job's GITHUB_TOKEN is the ONLY credential the release API | ||
| 15 | +# (the /gh shim behind $GITHUB_API_URL) accepts — a personal token is refused — | ||
| 16 | +# and it is read-only unless the workflow asks for `contents: write` below. | ||
| 17 | +# That is why there is no longer a token file to keep out of git, and no | ||
| 18 | +# 02-release.publish.sh or 04-release.upload-binaries.sh to run by hand. | ||
| 19 | +# | ||
| 20 | +# No workflow_dispatch on purpose: Rickub's dispatch API fires EVERY | ||
| 21 | +# dispatchable workflow of a ref, so a repository should declare at most one. | ||
| 22 | +on: | ||
| 23 | + push: | ||
| 24 | + tags: | ||
| 25 | + - "v*" | ||
| 26 | + | ||
| 27 | +permissions: | ||
| 28 | + contents: write | ||
| 29 | + | ||
| 30 | +concurrency: | ||
| 31 | + group: release-${{ github.ref_name }} | ||
| 32 | + cancel-in-progress: false | ||
| 33 | + | ||
| 34 | +jobs: | ||
| 35 | + release: | ||
| 36 | + name: publish ${{ github.ref_name }} | ||
| 37 | + runs-on: ubuntu-latest | ||
| 38 | + steps: | ||
| 39 | + - name: Checkout | ||
| 40 | + uses: actions/checkout@v4 | ||
| 41 | + with: | ||
| 42 | + # The whole history and the tags: the release notes below are read | ||
| 43 | + # from the annotated tag's message, and the Makefile's default | ||
| 44 | + # version comes from `git describe`. | ||
| 45 | + fetch-depth: 0 | ||
| 46 | + | ||
| 47 | + - name: Set up Go | ||
| 48 | + uses: actions/setup-go@v5 | ||
| 49 | + with: | ||
| 50 | + go-version-file: go.mod | ||
| 51 | + cache: true | ||
| 52 | + | ||
| 53 | + - name: go test | ||
| 54 | + # The suite includes tests that run ./01-release.tag.sh against a | ||
| 55 | + # throwaway clone. They skip themselves when they see this, exactly as | ||
| 56 | + # they do when the script itself calls make check — without it, a | ||
| 57 | + # release job would start a release inside itself. | ||
| 58 | + env: | ||
| 59 | + TURBO_PYTHON_RELEASING: "1" | ||
| 60 | + run: go test ./... -count=1 | ||
| 61 | + | ||
| 62 | + - name: Build the release | ||
| 63 | + # release.env is git-ignored, so the tag is passed explicitly and the | ||
| 64 | + # script falls back to "Turbo Python <tag>" for the description. | ||
| 65 | + run: bash ./02-build-releases.sh "${GITHUB_REF_NAME}" | ||
| 66 | + | ||
| 67 | + - name: Release notes | ||
| 68 | + id: notes | ||
| 69 | + # The message ./01-release.tag.sh put on the annotated tag (ABOUT in | ||
| 70 | + # release.env), then the two ways to get the editor and the links to | ||
| 71 | + # the documentation AT THAT TAG — a release page is not inside the | ||
| 72 | + # repository tree, so a relative path from it 404s, and a link to the | ||
| 73 | + # branch would rot as the branch moves. A lightweight tag has no | ||
| 74 | + # message: the tag name stands in. | ||
| 75 | + run: | | ||
| 76 | + set -euo pipefail | ||
| 77 | + message="$(git for-each-ref "refs/tags/${GITHUB_REF_NAME}" --format='%(contents)' | sed '/^-----BEGIN PGP SIGNATURE-----/,$d')" | ||
| 78 | + if [ -z "$(printf '%s' "${message}" | tr -d '[:space:]')" ]; then | ||
| 79 | + message="Turbo Python ${GITHUB_REF_NAME}" | ||
| 80 | + fi | ||
| 81 | + tree="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/blob/${GITHUB_REF_NAME}" | ||
| 82 | + version="${GITHUB_REF_NAME#v}" | ||
| 83 | + { | ||
| 84 | + printf '%s\n\n' "${message}" | ||
| 85 | + echo "Download the binary for your platform below, or install from the module proxy:" | ||
| 86 | + echo | ||
| 87 | + echo '```bash' | ||
| 88 | + echo "go install $(go list -m)@${GITHUB_REF_NAME}" | ||
| 89 | + echo '```' | ||
| 90 | + echo | ||
| 91 | + echo "Documentation: [English](${tree}/docs/en/README.md) · [Français](${tree}/docs/fr/README.md) · [how to install](${tree}/docs/en/how-to/install.md)" | ||
| 92 | + echo | ||
| 93 | + echo "- Commit: \`${GITHUB_SHA}\`" | ||
| 94 | + echo "- Published by the Release workflow, run #${GITHUB_RUN_NUMBER}, with $(go env GOVERSION)" | ||
| 95 | + echo | ||
| 96 | + echo '## Running a download' | ||
| 97 | + echo | ||
| 98 | + echo '```bash' | ||
| 99 | + echo "chmod +x turbo-python-${version}-<platform>" | ||
| 100 | + echo "./turbo-python-${version}-<platform> main.py" | ||
| 101 | + echo '```' | ||
| 102 | + echo | ||
| 103 | + echo "On macOS, an unsigned download is quarantined until you say otherwise: \`xattr -d com.apple.quarantine turbo-python-${version}-darwin-arm64\`." | ||
| 104 | + echo | ||
| 105 | + echo '## Checksums' | ||
| 106 | + echo | ||
| 107 | + echo 'Verify a download with `sha256sum -c SHA256SUMS --ignore-missing` (`shasum -a 256 -c` on macOS).' | ||
| 108 | + echo | ||
| 109 | + echo '```' | ||
| 110 | + cat "release/${GITHUB_REF_NAME}/SHA256SUMS" | ||
| 111 | + echo '```' | ||
| 112 | + } > "${RUNNER_TEMP}/notes.md" | ||
| 113 | + echo "path=${RUNNER_TEMP}/notes.md" >> "$GITHUB_OUTPUT" | ||
| 114 | + | ||
| 115 | + - name: Keep the binaries as a run artifact | ||
| 116 | + # Downloadable from the run page even if the publish step below fails | ||
| 117 | + # (an old CI node that does not forward /gh answers 403 there). | ||
| 118 | + uses: actions/upload-artifact@v4 | ||
| 119 | + with: | ||
| 120 | + name: turbo-python-${{ github.ref_name }} | ||
| 121 | + path: release/${{ github.ref_name }}/ | ||
| 122 | + if-no-files-found: error | ||
| 123 | + retention-days: 14 | ||
| 124 | + | ||
| 125 | + - name: Publish the release | ||
| 126 | + uses: softprops/action-gh-release@v2 | ||
| 127 | + with: | ||
| 128 | + tag_name: ${{ github.ref_name }} | ||
| 129 | + name: ${{ github.ref_name }} | ||
| 130 | + body_path: ${{ steps.notes.outputs.path }} | ||
| 131 | + draft: false | ||
| 132 | + prerelease: ${{ contains(github.ref_name, '-') }} | ||
| 133 | + files: | | ||
| 134 | + release/${{ github.ref_name }}/turbo-python-* | ||
| 135 | + release/${{ github.ref_name }}/SHA256SUMS | ||
| 136 | + release/${{ github.ref_name }}/README.md | ||
| 137 | + fail_on_unmatched_files: true | ||
added
.gitignore +10 -0 | new file mode 100644 | ||
| @@ -0,0 +1,10 @@ | ||
| 1 | +bin/ | |
| 2 | +kits | |
| 3 | +*.env | |
| 4 | +release | |
| 5 | + | |
| 6 | +# A go.work pointing at the checkout beside this one is how you build against an | |
| 7 | +# unreleased turbo-core. It is one person's local wiring, never the project's: | |
| 8 | +# committed, it would break every clone that has no such checkout. | |
| 9 | +go.work | |
| 10 | +go.work.sum | |
| new file mode 100644 | |||
| @@ -0,0 +1,10 @@ | |||
| 1 | +bin/ | ||
| 2 | +kits | ||
| 3 | +*.env | ||
| 4 | +release | ||
| 5 | + | ||
| 6 | +# A go.work pointing at the checkout beside this one is how you build against an | ||
| 7 | +# unreleased turbo-core. It is one person's local wiring, never the project's: | ||
| 8 | +# committed, it would break every clone that has no such checkout. | ||
| 9 | +go.work | ||
| 10 | +go.work.sum | ||
added
.memory/README.md +11 -0 | new file mode 100644 | ||
| @@ -0,0 +1,11 @@ | ||
| 1 | +# .memory | |
| 2 | + | |
| 3 | +The project's durable record, committed to the repository on purpose. | |
| 4 | + | |
| 5 | +| File | What it is | How it is maintained | | |
| 6 | +| --- | --- | --- | | |
| 7 | +| `summary.md` | A snapshot of the present: what this is, how it is built, the decisions in force | **Edited in place.** Only what a session establishes or invalidates changes; the rest is left byte for byte. | | |
| 8 | +| `history.md` | One dated entry per session, in order | **Append only.** Never rewritten, never tidied. A history you edit is not a history. | | |
| 9 | +| `handoffs/` | One file per session: state, work in flight, next steps, traps | Written at the end of a session. Never overwrite somebody else's. | | |
| 10 | + | |
| 11 | +`.memory/` is for whoever *continues building* this. `docs/` is for whoever *uses* it. Keep the two apart. | |
| new file mode 100644 | |||
| @@ -0,0 +1,11 @@ | |||
| 1 | +# .memory | ||
| 2 | + | ||
| 3 | +The project's durable record, committed to the repository on purpose. | ||
| 4 | + | ||
| 5 | +| File | What it is | How it is maintained | | ||
| 6 | +| --- | --- | --- | | ||
| 7 | +| `summary.md` | A snapshot of the present: what this is, how it is built, the decisions in force | **Edited in place.** Only what a session establishes or invalidates changes; the rest is left byte for byte. | | ||
| 8 | +| `history.md` | One dated entry per session, in order | **Append only.** Never rewritten, never tidied. A history you edit is not a history. | | ||
| 9 | +| `handoffs/` | One file per session: state, work in flight, next steps, traps | Written at the end of a session. Never overwrite somebody else's. | | ||
| 10 | + | ||
| 11 | +`.memory/` is for whoever *continues building* this. `docs/` is for whoever *uses* it. Keep the two apart. | ||
added
.memory/handoffs/2026-09-03-first-editor.md +82 -0 | new file mode 100644 | ||
| @@ -0,0 +1,82 @@ | ||
| 1 | +# Handoff — 2026-09-03 — Turbo Python, first build | |
| 2 | + | |
| 3 | +## Where this stopped | |
| 4 | + | |
| 5 | +The editor is **complete and verified**. Suite green, quality gate PASS, documentation | |
| 6 | +complete in both languages, `.memory/` written, the family updated in turbo-core and in the | |
| 7 | +other two editors. Nothing is in flight. | |
| 8 | + | |
| 9 | +## What the next session must know | |
| 10 | + | |
| 11 | +**Nothing is committed.** The whole tree is untracked on `main` at `efb533c` | |
| 12 | +(`Initial commit`). The user commits, tags and releases; do not do it for them. A proposed | |
| 13 | +first commit message is at the bottom of this file. | |
| 14 | + | |
| 15 | +**Four repositories were touched, not one.** If the user commits only `turbo-python`, the | |
| 16 | +family updates in `turbo-core`, `turbo-go` and `turbo-rust` stay uncommitted beside it: | |
| 17 | + | |
| 18 | +| Repository | Changed | | |
| 19 | +| --- | --- | | |
| 20 | +| `turbo-core` | `README.md`, `docs/{en,fr}/README.md`, `profile/profile.go` (a comment), `docs/{en,fr}/how-to/{release-the-library,test-without-publishing,write-the-starter-files}.md`, `docs/{en,fr}/explanation/architecture.md`, `.memory/summary.md` | | |
| 21 | +| `turbo-go` | `docs/{en,fr}/explanation/architecture.md`, plus three claims a pty run showed were stale: the tutorial's menu bar listing, its "→ four times" count, and `reference/menus.md`'s opening sentence | | |
| 22 | +| `turbo-rust` | the same three, plus the English `reference/menus.md` saying project menus appear "between **Go** and Help" in an editor whose menu is called Rust | | |
| 23 | + | |
| 24 | +Each of those three repositories has its own `.memory/` history entry and handoff for what | |
| 25 | +was done to it. | |
| 26 | + | |
| 27 | +None of those is an API change, so **no turbo-core release is needed**. turbo-python pins | |
| 28 | +`v0.4.0`, which is published, and needed no library change at all. | |
| 29 | + | |
| 30 | +## Traps met here, so they are not met again | |
| 31 | + | |
| 32 | +- **A copied binary is the wrong architecture.** This sandbox is Linux, the user is on | |
| 33 | + macOS, and both see the same files. Everything built here went to `/tmp`, and nothing was | |
| 34 | + left in `bin/`. `make build` recreates it. | |
| 35 | +- **Adapting is not substituting.** The documentation came from Turbo Rust's and a | |
| 36 | + mechanical pass left a dozen defects no test could see — a diagram labelled | |
| 37 | + `internal/rustlang`, a tutorial that had the reader type Rust, `crate` in five pages, | |
| 38 | + `golangci-lint` in the *French* explanation whose English twin was correct, and the | |
| 39 | + English menus reference saying "between Go and Help". Grep for the editor you copied from | |
| 40 | + **and read every hit**; then grep for the *language*, in prose, which is where the ones | |
| 41 | + that survive hide. | |
| 42 | +- **The diagram is a file nothing imports**, so nothing noticed it was Turbo Rust's. | |
| 43 | + `diagram_test.go` now holds it to `go list`. Adopt that test in the other editors if you | |
| 44 | + ever touch their diagrams. | |
| 45 | +- **A tutorial's key counts go stale when the library grows a menu.** "Press → four times to | |
| 46 | + reach Options" was written before the Code menu existed. Re-count them in a pty rather | |
| 47 | + than trusting them. | |
| 48 | +- **Two `uv` commands in the copied docs did not exist.** Run the toolchain commands you | |
| 49 | + document; `uv update` has never been a thing. | |
| 50 | + | |
| 51 | +## If you pick this up next | |
| 52 | + | |
| 53 | +Nothing is required. Things that would be worth doing, in rough order: | |
| 54 | + | |
| 55 | +1. **Let the user commit and tag `v0.1.0`**, then `03-build-releases.sh` and | |
| 56 | + `04-release.upload-binaries.sh`. None of the four scripts has been run for real from here. | |
| 57 | +2. **Try pyright or ruff-lsp** against the same profile — the profile takes a command and | |
| 58 | + arguments, so it is a two-line experiment, and it would tell us whether the "seven of | |
| 59 | + nine questions" note is about pylsp or about Python. | |
| 60 | +3. **Time the scanner on a large file.** It has never been measured. | |
| 61 | +4. **A `Problems…` entry for the tutorial** was considered and left out; the tutorial | |
| 62 | + mentions the gutter mark instead. | |
| 63 | + | |
| 64 | +## Proposed first commit message | |
| 65 | + | |
| 66 | +``` | |
| 67 | +Turbo Python: a Turbo C-style editor for Python on turbo-core | |
| 68 | + | |
| 69 | +The command, the profile and a hand-written Python scanner — everything | |
| 70 | +else is turbo-core v0.4.0, required from the module proxy with no replace. | |
| 71 | + | |
| 72 | +Scanner: all six string prefixes, both triple quotes carried across line | |
| 73 | +breaks, line continuations, decorators, soft keywords, and PEP 8's two | |
| 74 | +name shapes told apart — SCREAMING_SNAKE_CASE is a constant, CapWords a | |
| 75 | +type, even when called. | |
| 76 | + | |
| 77 | +Language server: pylsp, looked for in the active virtualenv, ~/.local/bin, | |
| 78 | +pyenv's shims and macOS' per-version script directories as well as PATH. | |
| 79 | + | |
| 80 | +129 tests, five of them against a real pylsp. Quality gate PASS. | |
| 81 | +Documentation in English and French, 33 pages each. | |
| 82 | +``` | |
| new file mode 100644 | |||
| @@ -0,0 +1,82 @@ | |||
| 1 | +# Handoff — 2026-09-03 — Turbo Python, first build | ||
| 2 | + | ||
| 3 | +## Where this stopped | ||
| 4 | + | ||
| 5 | +The editor is **complete and verified**. Suite green, quality gate PASS, documentation | ||
| 6 | +complete in both languages, `.memory/` written, the family updated in turbo-core and in the | ||
| 7 | +other two editors. Nothing is in flight. | ||
| 8 | + | ||
| 9 | +## What the next session must know | ||
| 10 | + | ||
| 11 | +**Nothing is committed.** The whole tree is untracked on `main` at `efb533c` | ||
| 12 | +(`Initial commit`). The user commits, tags and releases; do not do it for them. A proposed | ||
| 13 | +first commit message is at the bottom of this file. | ||
| 14 | + | ||
| 15 | +**Four repositories were touched, not one.** If the user commits only `turbo-python`, the | ||
| 16 | +family updates in `turbo-core`, `turbo-go` and `turbo-rust` stay uncommitted beside it: | ||
| 17 | + | ||
| 18 | +| Repository | Changed | | ||
| 19 | +| --- | --- | | ||
| 20 | +| `turbo-core` | `README.md`, `docs/{en,fr}/README.md`, `profile/profile.go` (a comment), `docs/{en,fr}/how-to/{release-the-library,test-without-publishing,write-the-starter-files}.md`, `docs/{en,fr}/explanation/architecture.md`, `.memory/summary.md` | | ||
| 21 | +| `turbo-go` | `docs/{en,fr}/explanation/architecture.md`, plus three claims a pty run showed were stale: the tutorial's menu bar listing, its "→ four times" count, and `reference/menus.md`'s opening sentence | | ||
| 22 | +| `turbo-rust` | the same three, plus the English `reference/menus.md` saying project menus appear "between **Go** and Help" in an editor whose menu is called Rust | | ||
| 23 | + | ||
| 24 | +Each of those three repositories has its own `.memory/` history entry and handoff for what | ||
| 25 | +was done to it. | ||
| 26 | + | ||
| 27 | +None of those is an API change, so **no turbo-core release is needed**. turbo-python pins | ||
| 28 | +`v0.4.0`, which is published, and needed no library change at all. | ||
| 29 | + | ||
| 30 | +## Traps met here, so they are not met again | ||
| 31 | + | ||
| 32 | +- **A copied binary is the wrong architecture.** This sandbox is Linux, the user is on | ||
| 33 | + macOS, and both see the same files. Everything built here went to `/tmp`, and nothing was | ||
| 34 | + left in `bin/`. `make build` recreates it. | ||
| 35 | +- **Adapting is not substituting.** The documentation came from Turbo Rust's and a | ||
| 36 | + mechanical pass left a dozen defects no test could see — a diagram labelled | ||
| 37 | + `internal/rustlang`, a tutorial that had the reader type Rust, `crate` in five pages, | ||
| 38 | + `golangci-lint` in the *French* explanation whose English twin was correct, and the | ||
| 39 | + English menus reference saying "between Go and Help". Grep for the editor you copied from | ||
| 40 | + **and read every hit**; then grep for the *language*, in prose, which is where the ones | ||
| 41 | + that survive hide. | ||
| 42 | +- **The diagram is a file nothing imports**, so nothing noticed it was Turbo Rust's. | ||
| 43 | + `diagram_test.go` now holds it to `go list`. Adopt that test in the other editors if you | ||
| 44 | + ever touch their diagrams. | ||
| 45 | +- **A tutorial's key counts go stale when the library grows a menu.** "Press → four times to | ||
| 46 | + reach Options" was written before the Code menu existed. Re-count them in a pty rather | ||
| 47 | + than trusting them. | ||
| 48 | +- **Two `uv` commands in the copied docs did not exist.** Run the toolchain commands you | ||
| 49 | + document; `uv update` has never been a thing. | ||
| 50 | + | ||
| 51 | +## If you pick this up next | ||
| 52 | + | ||
| 53 | +Nothing is required. Things that would be worth doing, in rough order: | ||
| 54 | + | ||
| 55 | +1. **Let the user commit and tag `v0.1.0`**, then `03-build-releases.sh` and | ||
| 56 | + `04-release.upload-binaries.sh`. None of the four scripts has been run for real from here. | ||
| 57 | +2. **Try pyright or ruff-lsp** against the same profile — the profile takes a command and | ||
| 58 | + arguments, so it is a two-line experiment, and it would tell us whether the "seven of | ||
| 59 | + nine questions" note is about pylsp or about Python. | ||
| 60 | +3. **Time the scanner on a large file.** It has never been measured. | ||
| 61 | +4. **A `Problems…` entry for the tutorial** was considered and left out; the tutorial | ||
| 62 | + mentions the gutter mark instead. | ||
| 63 | + | ||
| 64 | +## Proposed first commit message | ||
| 65 | + | ||
| 66 | +``` | ||
| 67 | +Turbo Python: a Turbo C-style editor for Python on turbo-core | ||
| 68 | + | ||
| 69 | +The command, the profile and a hand-written Python scanner — everything | ||
| 70 | +else is turbo-core v0.4.0, required from the module proxy with no replace. | ||
| 71 | + | ||
| 72 | +Scanner: all six string prefixes, both triple quotes carried across line | ||
| 73 | +breaks, line continuations, decorators, soft keywords, and PEP 8's two | ||
| 74 | +name shapes told apart — SCREAMING_SNAKE_CASE is a constant, CapWords a | ||
| 75 | +type, even when called. | ||
| 76 | + | ||
| 77 | +Language server: pylsp, looked for in the active virtualenv, ~/.local/bin, | ||
| 78 | +pyenv's shims and macOS' per-version script directories as well as PATH. | ||
| 79 | + | ||
| 80 | +129 tests, five of them against a real pylsp. Quality gate PASS. | ||
| 81 | +Documentation in English and French, 33 pages each. | ||
| 82 | +``` | ||
added
.memory/handoffs/2026-09-03-released-v0.1.0.md +45 -0 | new file mode 100644 | ||
| @@ -0,0 +1,45 @@ | ||
| 1 | +# Handoff — 2026-09-03 (later) — released, and the state of the family after it | |
| 2 | + | |
| 3 | +## Where this stopped | |
| 4 | + | |
| 5 | +`v0.1.0` is out and everything is green here. Nothing in flight in this repository. | |
| 6 | + | |
| 7 | +## The family, as of this scan | |
| 8 | + | |
| 9 | +| Repository | HEAD | Tag | Tree | Suite | | |
| 10 | +| --- | --- | --- | --- | --- | | |
| 11 | +| turbo-core | `4f93fb0` | `v0.4.1` | clean | green | | |
| 12 | +| turbo-go | `ab30ec6` | `v0.4.2` | clean | **red** | | |
| 13 | +| turbo-rust | `9b90655` | `v0.4.2` | clean | **red** | | |
| 14 | +| turbo-python | `bccbb0b` | `v0.1.0` | clean | green | | |
| 15 | + | |
| 16 | +All three editors pin turbo-core `v0.4.1`, none has an active `replace`. | |
| 17 | + | |
| 18 | +## The thing to know before touching anything else | |
| 19 | + | |
| 20 | +**turbo-go v0.4.2 and turbo-rust v0.4.2 are tagged releases whose test suites fail.** The | |
| 21 | +failures were there before this editor existed and are now inside a release: | |
| 22 | + | |
| 23 | +- **turbo-go**, four in `internal/golang/templates_test.go` — the starter tools file holds | |
| 24 | + **eight** tools where the test wants five (`Echo`, `Grep` and `Init module` were added | |
| 25 | + deliberately, to teach the `menu` key and the `{{placeholder}}` syntax); `Grep` goes to | |
| 26 | + `editor` and `Echo` to `terminal` where the test wants `popup`; two starter commands take | |
| 27 | + a value where the test asserts none does; and the snippets file no longer has the | |
| 28 | + `if err != nil` snippet the test looks for. | |
| 29 | +- **turbo-rust**, two in `internal/rustlang/templates_test.go` — six tools where the test | |
| 30 | + wants five, and `Echo` in a terminal. (A third failure, about the Rust menu being named | |
| 31 | + Go, went away when the user committed their in-flight template edit.) | |
| 32 | + | |
| 33 | +**The templates are right and the assertions are stale**, which is why this is a small job | |
| 34 | +rather than a design question: turbo-python's equivalent tests count their own `Echo` tool, | |
| 35 | +and the `turbo-new-editor` skill prescribes showing a placeholder and the `menu` key in the | |
| 36 | +starter file. It was left alone here because it belongs to those repositories' own cycle — | |
| 37 | +but a release that does not pass its own `make check` is worth fixing before the next one, | |
| 38 | +and `01-release.tag.sh` runs `make check`, so the next tag in either will refuse to be cut. | |
| 39 | + | |
| 40 | +## Also worth doing, unchanged from the previous handoff | |
| 41 | + | |
| 42 | +- `docs/diagrams/packages.drawio` is unheld in turbo-go and turbo-rust. This repository's | |
| 43 | + `diagram_test.go` holds it to `go list`; copying it across is perhaps twenty minutes each. | |
| 44 | +- Try pyright or ruff-lsp against this profile — two lines, and it would say whether "pylsp | |
| 45 | + answers seven of nine questions" is about pylsp or about Python. | |
| new file mode 100644 | |||
| @@ -0,0 +1,45 @@ | |||
| 1 | +# Handoff — 2026-09-03 (later) — released, and the state of the family after it | ||
| 2 | + | ||
| 3 | +## Where this stopped | ||
| 4 | + | ||
| 5 | +`v0.1.0` is out and everything is green here. Nothing in flight in this repository. | ||
| 6 | + | ||
| 7 | +## The family, as of this scan | ||
| 8 | + | ||
| 9 | +| Repository | HEAD | Tag | Tree | Suite | | ||
| 10 | +| --- | --- | --- | --- | --- | | ||
| 11 | +| turbo-core | `4f93fb0` | `v0.4.1` | clean | green | | ||
| 12 | +| turbo-go | `ab30ec6` | `v0.4.2` | clean | **red** | | ||
| 13 | +| turbo-rust | `9b90655` | `v0.4.2` | clean | **red** | | ||
| 14 | +| turbo-python | `bccbb0b` | `v0.1.0` | clean | green | | ||
| 15 | + | ||
| 16 | +All three editors pin turbo-core `v0.4.1`, none has an active `replace`. | ||
| 17 | + | ||
| 18 | +## The thing to know before touching anything else | ||
| 19 | + | ||
| 20 | +**turbo-go v0.4.2 and turbo-rust v0.4.2 are tagged releases whose test suites fail.** The | ||
| 21 | +failures were there before this editor existed and are now inside a release: | ||
| 22 | + | ||
| 23 | +- **turbo-go**, four in `internal/golang/templates_test.go` — the starter tools file holds | ||
| 24 | + **eight** tools where the test wants five (`Echo`, `Grep` and `Init module` were added | ||
| 25 | + deliberately, to teach the `menu` key and the `{{placeholder}}` syntax); `Grep` goes to | ||
| 26 | + `editor` and `Echo` to `terminal` where the test wants `popup`; two starter commands take | ||
| 27 | + a value where the test asserts none does; and the snippets file no longer has the | ||
| 28 | + `if err != nil` snippet the test looks for. | ||
| 29 | +- **turbo-rust**, two in `internal/rustlang/templates_test.go` — six tools where the test | ||
| 30 | + wants five, and `Echo` in a terminal. (A third failure, about the Rust menu being named | ||
| 31 | + Go, went away when the user committed their in-flight template edit.) | ||
| 32 | + | ||
| 33 | +**The templates are right and the assertions are stale**, which is why this is a small job | ||
| 34 | +rather than a design question: turbo-python's equivalent tests count their own `Echo` tool, | ||
| 35 | +and the `turbo-new-editor` skill prescribes showing a placeholder and the `menu` key in the | ||
| 36 | +starter file. It was left alone here because it belongs to those repositories' own cycle — | ||
| 37 | +but a release that does not pass its own `make check` is worth fixing before the next one, | ||
| 38 | +and `01-release.tag.sh` runs `make check`, so the next tag in either will refuse to be cut. | ||
| 39 | + | ||
| 40 | +## Also worth doing, unchanged from the previous handoff | ||
| 41 | + | ||
| 42 | +- `docs/diagrams/packages.drawio` is unheld in turbo-go and turbo-rust. This repository's | ||
| 43 | + `diagram_test.go` holds it to `go list`; copying it across is perhaps twenty minutes each. | ||
| 44 | +- Try pyright or ruff-lsp against this profile — two lines, and it would say whether "pylsp | ||
| 45 | + answers seven of nine questions" is about pylsp or about Python. | ||
added
.memory/handoffs/2026-09-09-alt-t-fix.md +23 -0 | new file mode 100644 | ||
| @@ -0,0 +1,23 @@ | ||
| 1 | +# Handoff — 2026-09-09 — a wrong hot key, found by the next editor | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +Ten documentation files changed, both languages, uncommitted. Nothing else in this repository was touched and its suite was not re-run. | |
| 6 | + | |
| 7 | +## What was wrong | |
| 8 | + | |
| 9 | +Every page that named the Python menu's hot key said `Alt-T`. The menu is `~P~ython`; it answers to `Alt-P`. `Alt-T` is Turbo Rust's, from `Rus~t~`, and it reached these pages through the mechanical substitution that produced them — the identifiers were all changed and the key was not, because a key is not an identifier. It shipped in `v0.1.0` and `v0.1.1`. | |
| 10 | + | |
| 11 | +A second sentence was wrong for the same reason: "`Tools` gets `Alt-T`. `Format` gets `Alt-M`" in `how-to/run-uv-commands.md` was Turbo Rust's arithmetic about which letters are free. | |
| 12 | + | |
| 13 | +`explanation/architecture.md` also said "all three editors" in both languages. It is four now. | |
| 14 | + | |
| 15 | +## Next steps | |
| 16 | + | |
| 17 | +1. Commit. | |
| 18 | +2. **Copy `TestTheToolsReferenceMatchesTheStarterFile` from turbo-moonbit** (`internal/moonbitlang/templates_test.go`). It reads the tools table out of `docs/{en,fr}/reference/*-tools.md` and holds every row to the file `tools.Create` actually writes, and it checks the menu's hot key by name. It is what would have caught this. Perhaps twenty minutes. | |
| 19 | +3. While there: this repository's `docs/diagrams/packages.drawio` **is** already held to `go list` by `diagram_test.go`. turbo-go and turbo-rust still are not — that item is from the previous handoff and is still open. | |
| 20 | + | |
| 21 | +## Watch out for | |
| 22 | + | |
| 23 | +- The previous handoff's finding stands: **turbo-go v0.4.2 and turbo-rust v0.4.2 are tagged releases whose suites fail**, on stale template assertions. `01-release.tag.sh` runs `make check`, so the next tag in either will refuse to be cut. | |
| new file mode 100644 | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | +# Handoff — 2026-09-09 — a wrong hot key, found by the next editor | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +Ten documentation files changed, both languages, uncommitted. Nothing else in this repository was touched and its suite was not re-run. | ||
| 6 | + | ||
| 7 | +## What was wrong | ||
| 8 | + | ||
| 9 | +Every page that named the Python menu's hot key said `Alt-T`. The menu is `~P~ython`; it answers to `Alt-P`. `Alt-T` is Turbo Rust's, from `Rus~t~`, and it reached these pages through the mechanical substitution that produced them — the identifiers were all changed and the key was not, because a key is not an identifier. It shipped in `v0.1.0` and `v0.1.1`. | ||
| 10 | + | ||
| 11 | +A second sentence was wrong for the same reason: "`Tools` gets `Alt-T`. `Format` gets `Alt-M`" in `how-to/run-uv-commands.md` was Turbo Rust's arithmetic about which letters are free. | ||
| 12 | + | ||
| 13 | +`explanation/architecture.md` also said "all three editors" in both languages. It is four now. | ||
| 14 | + | ||
| 15 | +## Next steps | ||
| 16 | + | ||
| 17 | +1. Commit. | ||
| 18 | +2. **Copy `TestTheToolsReferenceMatchesTheStarterFile` from turbo-moonbit** (`internal/moonbitlang/templates_test.go`). It reads the tools table out of `docs/{en,fr}/reference/*-tools.md` and holds every row to the file `tools.Create` actually writes, and it checks the menu's hot key by name. It is what would have caught this. Perhaps twenty minutes. | ||
| 19 | +3. While there: this repository's `docs/diagrams/packages.drawio` **is** already held to `go list` by `diagram_test.go`. turbo-go and turbo-rust still are not — that item is from the previous handoff and is still open. | ||
| 20 | + | ||
| 21 | +## Watch out for | ||
| 22 | + | ||
| 23 | +- The previous handoff's finding stands: **turbo-go v0.4.2 and turbo-rust v0.4.2 are tagged releases whose suites fail**, on stale template assertions. `01-release.tag.sh` runs `make check`, so the next tag in either will refuse to be cut. | ||
added
.memory/handoffs/2026-09-14-family-count.md +3 -0 | new file mode 100644 | ||
| @@ -0,0 +1,3 @@ | ||
| 1 | +# 2026-09-14 — "all four editors" → five | |
| 2 | + | |
| 3 | +One sentence in `docs/{en,fr}/explanation/architecture.md`, because Turbo Golo now exists. Uncommitted, on `main` at `v0.5.0`. Nothing else was read or changed here; commit it with the next change or on its own. | |
| new file mode 100644 | |||
| @@ -0,0 +1,3 @@ | |||
| 1 | +# 2026-09-14 — "all four editors" → five | ||
| 2 | + | ||
| 3 | +One sentence in `docs/{en,fr}/explanation/architecture.md`, because Turbo Golo now exists. Uncommitted, on `main` at `v0.5.0`. Nothing else was read or changed here; commit it with the next change or on its own. | ||
added
.memory/handoffs/2026-09-15-acp-commands-mentions.md +20 -0 | new file mode 100644 | ||
| @@ -0,0 +1,20 @@ | ||
| 1 | +# Handoff — 2026-09-15 — `/` commands and `@` mentions, documented | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +Docs EN + FR and the starter template describe the `/` command list and the `@` file list that turbo-core's agent window gained on 2026-09-15. **Uncommitted.** Code unchanged here; suite green. | |
| 6 | + | |
| 7 | +## Next steps | |
| 8 | + | |
| 9 | +1. Wait for turbo-core to be tagged, then `go get codeberg.org/turbo-editors/turbo-core@vX.Y.Z`, `GOWORK=off make check`, tag. | |
| 10 | +2. Try `/` and `@` in a window by hand — nothing has been touched by a person. turbo-core's handoff of the same date has the list. | |
| 11 | + | |
| 12 | +## Watch out for | |
| 13 | + | |
| 14 | +- The six doc pages were edited by a script shared with four other editors, anchored on sentences that are identical across them. If you reword one of those sentences here, the next cross-editor edit will miss this repository — grep the other editors before rewording. | |
| 15 | + | |
| 16 | +## 2026-09-16 | |
| 17 | + | |
| 18 | +Added the `TURBO_ACP_TRACE` section and the "commands do not appear" bullet, EN + FR. The cause of the user's missing commands is still open — see turbo-core's handoff of 2026-09-15, "In flight". | |
| 19 | + | |
| 20 | +`.turbo-python/acp.toml` + `agent.yaml` were added the same day: Bob (docker agent) and mini-me (`mm -acp`). They load; nobody has opened them. Decide whether they are committed with the docs or kept local. | |
| new file mode 100644 | |||
| @@ -0,0 +1,20 @@ | |||
| 1 | +# Handoff — 2026-09-15 — `/` commands and `@` mentions, documented | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +Docs EN + FR and the starter template describe the `/` command list and the `@` file list that turbo-core's agent window gained on 2026-09-15. **Uncommitted.** Code unchanged here; suite green. | ||
| 6 | + | ||
| 7 | +## Next steps | ||
| 8 | + | ||
| 9 | +1. Wait for turbo-core to be tagged, then `go get codeberg.org/turbo-editors/turbo-core@vX.Y.Z`, `GOWORK=off make check`, tag. | ||
| 10 | +2. Try `/` and `@` in a window by hand — nothing has been touched by a person. turbo-core's handoff of the same date has the list. | ||
| 11 | + | ||
| 12 | +## Watch out for | ||
| 13 | + | ||
| 14 | +- The six doc pages were edited by a script shared with four other editors, anchored on sentences that are identical across them. If you reword one of those sentences here, the next cross-editor edit will miss this repository — grep the other editors before rewording. | ||
| 15 | + | ||
| 16 | +## 2026-09-16 | ||
| 17 | + | ||
| 18 | +Added the `TURBO_ACP_TRACE` section and the "commands do not appear" bullet, EN + FR. The cause of the user's missing commands is still open — see turbo-core's handoff of 2026-09-15, "In flight". | ||
| 19 | + | ||
| 20 | +`.turbo-python/acp.toml` + `agent.yaml` were added the same day: Bob (docker agent) and mini-me (`mm -acp`). They load; nobody has opened them. Decide whether they are committed with the docs or kept local. | ||
added
.memory/handoffs/2026-09-15-acp.md +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +# Handoff — 2026-09-15 — ACP agent windows, ported | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +**Done.** Branch `feature/acp`, local, **not committed and not pushed**. | |
| 6 | + | |
| 7 | +The feature is turbo-core's; this repository contributes `internal/*/acp.toml.tmpl` and one line in the profile. Tests green, quality gate PASS, documentation EN + FR. | |
| 8 | + | |
| 9 | +Read **turbo-core's** handoff of the same date first: it holds the design, and every trap worth knowing. | |
| 10 | + | |
| 11 | +## In flight | |
| 12 | + | |
| 13 | +Nothing. | |
| 14 | + | |
| 15 | +## Next steps | |
| 16 | + | |
| 17 | +1. **turbo-core must be released first.** This repository cannot build against an unreleased library from a clean clone. Order: tag and release turbo-core → `go get codeberg.org/turbo-editors/turbo-core@vX.Y.Z` here → **`GOWORK=off make check`** → tag and release this. | |
| 18 | +2. Open the editor, press `Alt-A`, and talk to an agent. Nobody has done that from **this** editor — only from turbo-go. | |
| 19 | + | |
| 20 | +## Watch out for | |
| 21 | + | |
| 22 | +- **`go.work` is what makes this build against the local turbo-core**, and it is gitignored. `GOWORK=off` is the only way to see what a clean clone sees. | |
| 23 | +- **The sandbox's filesystem corrupts `cp` for some recently-written inodes** — a file reads correctly through `cat`, `git` and `go build`, and comes out of `cp` as the right number of NUL bytes. It bit this port twice. Never use `cp` or a cross-filesystem `mv` to back a file up here; use `cat`. | |
| 24 | +- **One sentence in the starter file is about this editor and not the protocol** — the ```python fence and the file extension beside it. `TestTheCreatedAgentsFileNamesThisEditorsOwnLanguage` is what stops a future copy-paste leaving another editor's language in it. | |
| 25 | +- **The documentation was adapted, not copied.** The slug, the language name, the fence, the build command and the language server were all replaced. If you add a page, do the same rather than translating turbo-go's wholesale. | |
| 26 | + | |
| 27 | +## Never touched by a human, here | |
| 28 | + | |
| 29 | +Everything. The agent window has only ever been opened from turbo-go. | |
| new file mode 100644 | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | +# Handoff — 2026-09-15 — ACP agent windows, ported | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +**Done.** Branch `feature/acp`, local, **not committed and not pushed**. | ||
| 6 | + | ||
| 7 | +The feature is turbo-core's; this repository contributes `internal/*/acp.toml.tmpl` and one line in the profile. Tests green, quality gate PASS, documentation EN + FR. | ||
| 8 | + | ||
| 9 | +Read **turbo-core's** handoff of the same date first: it holds the design, and every trap worth knowing. | ||
| 10 | + | ||
| 11 | +## In flight | ||
| 12 | + | ||
| 13 | +Nothing. | ||
| 14 | + | ||
| 15 | +## Next steps | ||
| 16 | + | ||
| 17 | +1. **turbo-core must be released first.** This repository cannot build against an unreleased library from a clean clone. Order: tag and release turbo-core → `go get codeberg.org/turbo-editors/turbo-core@vX.Y.Z` here → **`GOWORK=off make check`** → tag and release this. | ||
| 18 | +2. Open the editor, press `Alt-A`, and talk to an agent. Nobody has done that from **this** editor — only from turbo-go. | ||
| 19 | + | ||
| 20 | +## Watch out for | ||
| 21 | + | ||
| 22 | +- **`go.work` is what makes this build against the local turbo-core**, and it is gitignored. `GOWORK=off` is the only way to see what a clean clone sees. | ||
| 23 | +- **The sandbox's filesystem corrupts `cp` for some recently-written inodes** — a file reads correctly through `cat`, `git` and `go build`, and comes out of `cp` as the right number of NUL bytes. It bit this port twice. Never use `cp` or a cross-filesystem `mv` to back a file up here; use `cat`. | ||
| 24 | +- **One sentence in the starter file is about this editor and not the protocol** — the ```python fence and the file extension beside it. `TestTheCreatedAgentsFileNamesThisEditorsOwnLanguage` is what stops a future copy-paste leaving another editor's language in it. | ||
| 25 | +- **The documentation was adapted, not copied.** The slug, the language name, the fence, the build command and the language server were all replaced. If you add a page, do the same rather than translating turbo-go's wholesale. | ||
| 26 | + | ||
| 27 | +## Never touched by a human, here | ||
| 28 | + | ||
| 29 | +Everything. The agent window has only ever been opened from turbo-go. | ||
added
.memory/handoffs/2026-09-16-family-count.md +9 -0 | new file mode 100644 | ||
| @@ -0,0 +1,9 @@ | ||
| 1 | +# Handoff — 2026-09-16 — family count | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +One-word edits in 2 documentation page(s) so that the family is counted at six editors (Turbo Go, Rust, Python, MoonBit, Golo, JS). Uncommitted. Nothing in flight. | |
| 6 | + | |
| 7 | +## Next steps | |
| 8 | + | |
| 9 | +1. Commit with whatever else is pending here. No release needed: the pages describe the family, not this editor's behaviour. | |
| new file mode 100644 | |||
| @@ -0,0 +1,9 @@ | |||
| 1 | +# Handoff — 2026-09-16 — family count | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +One-word edits in 2 documentation page(s) so that the family is counted at six editors (Turbo Go, Rust, Python, MoonBit, Golo, JS). Uncommitted. Nothing in flight. | ||
| 6 | + | ||
| 7 | +## Next steps | ||
| 8 | + | ||
| 9 | +1. Commit with whatever else is pending here. No release needed: the pages describe the family, not this editor's behaviour. | ||
added
.memory/handoffs/2026-09-17-windows-terminal-docs.md +15 -0 | new file mode 100644 | ||
| @@ -0,0 +1,15 @@ | ||
| 1 | +# Handoff — 2026-09-17 — Windows terminal windows: documentation ahead of the binary | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +Six documentation pages per language and the README now say terminal windows and the tools menu work on Windows (pseudo-console, cmd.exe via `%COMSPEC%`). The binary built from this checkout still pins turbo-core **v0.8.0**, which has neither. Uncommitted. Nothing else in flight. | |
| 6 | + | |
| 7 | +## Next steps | |
| 8 | + | |
| 9 | +1. Wait for turbo-core `v0.9.0` (the Windows work sits uncommitted on turbo-core's `main` — see its `handoffs/2026-09-17-windows-terminal.md`). | |
| 10 | +2. `go get codeberg.org/turbo-editors/turbo-core@v0.9.0 && go mod tidy && GOWORK=off make check`, then tag. `tools.Shell` became `tools.Shell()`; nothing in this repository calls it, so the re-pin should be one line. | |
| 11 | +3. The first `F8` on a Windows machine, by whoever has one: the five checks are in `docs/*/how-to/use-a-terminal.md`. | |
| 12 | + | |
| 13 | +## Watch out for | |
| 14 | + | |
| 15 | +- The docs claim Windows support that **has never been run by the authors**, and say so in every place they claim it. Do not soften the wording until somebody has pressed `F8` on Windows. | |
| new file mode 100644 | |||
| @@ -0,0 +1,15 @@ | |||
| 1 | +# Handoff — 2026-09-17 — Windows terminal windows: documentation ahead of the binary | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +Six documentation pages per language and the README now say terminal windows and the tools menu work on Windows (pseudo-console, cmd.exe via `%COMSPEC%`). The binary built from this checkout still pins turbo-core **v0.8.0**, which has neither. Uncommitted. Nothing else in flight. | ||
| 6 | + | ||
| 7 | +## Next steps | ||
| 8 | + | ||
| 9 | +1. Wait for turbo-core `v0.9.0` (the Windows work sits uncommitted on turbo-core's `main` — see its `handoffs/2026-09-17-windows-terminal.md`). | ||
| 10 | +2. `go get codeberg.org/turbo-editors/turbo-core@v0.9.0 && go mod tidy && GOWORK=off make check`, then tag. `tools.Shell` became `tools.Shell()`; nothing in this repository calls it, so the re-pin should be one line. | ||
| 11 | +3. The first `F8` on a Windows machine, by whoever has one: the five checks are in `docs/*/how-to/use-a-terminal.md`. | ||
| 12 | + | ||
| 13 | +## Watch out for | ||
| 14 | + | ||
| 15 | +- The docs claim Windows support that **has never been run by the authors**, and say so in every place they claim it. Do not soften the wording until somebody has pressed `F8` on Windows. | ||
added
.memory/handoffs/2026-09-18-untitled-lsp-docs.md +13 -0 | new file mode 100644 | ||
| @@ -0,0 +1,13 @@ | ||
| 1 | +# Handoff — 2026-09-18 — Untitled-window LSP fix: docs added, re-pin pending | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +turbo-core fixed the "window that started Untitled has no LSP until a restart" defect (its `.memory/handoffs/2026-09-18-first-launch-lsp.md` has the whole story). Here, only `docs/{en,fr}/how-to/enable-completion.md` gained the matching variant, inserted right after the `-no-lsp` block. Not committed. | |
| 6 | + | |
| 7 | +## Next steps | |
| 8 | + | |
| 9 | +1. When turbo-core is tagged and released: bump the `require` in `go.mod`, `go mod tidy`, rebuild, and drive it once — type into an Untitled window, save it under the language's extension, ask for a completion. | |
| 10 | + | |
| 11 | +## Watch out for | |
| 12 | + | |
| 13 | +- **The docs are ahead of the binary until that re-pin**: an editor built from the current pin still has the defect the new variant says is gone. | |
| new file mode 100644 | |||
| @@ -0,0 +1,13 @@ | |||
| 1 | +# Handoff — 2026-09-18 — Untitled-window LSP fix: docs added, re-pin pending | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +turbo-core fixed the "window that started Untitled has no LSP until a restart" defect (its `.memory/handoffs/2026-09-18-first-launch-lsp.md` has the whole story). Here, only `docs/{en,fr}/how-to/enable-completion.md` gained the matching variant, inserted right after the `-no-lsp` block. Not committed. | ||
| 6 | + | ||
| 7 | +## Next steps | ||
| 8 | + | ||
| 9 | +1. When turbo-core is tagged and released: bump the `require` in `go.mod`, `go mod tidy`, rebuild, and drive it once — type into an Untitled window, save it under the language's extension, ask for a completion. | ||
| 10 | + | ||
| 11 | +## Watch out for | ||
| 12 | + | ||
| 13 | +- **The docs are ahead of the binary until that re-pin**: an editor built from the current pin still has the defect the new variant says is gone. | ||
added
.memory/handoffs/2026-09-19-rickub-release-workflow.md +21 -0 | new file mode 100644 | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +# Handoff — 2026-09-19 — Rickub migration and the Release workflow | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +- Module `rickub.com/turbo-editors/turbo-python`, pinned to `rickub.com/turbo-editors/turbo-core v1.0.0`; `GOWORK=off make check` green. | |
| 6 | +- Releases: `./01-release.tag.sh` tags; the tag push runs `.github/workflows/release.yml`, which builds with `./02-build-releases.sh` and publishes the page with the binaries. `02-release.publish.sh` and `04-release.upload-binaries.sh` are deleted. No token needed. | |
| 7 | +- **Nothing is committed.** Fresh `git init`, `origin` at `ssh://git@rickub.com/turbo-editors/turbo-python.git`, no commit; the sandbox cannot reach the remote. | |
| 8 | + | |
| 9 | +## Next steps | |
| 10 | + | |
| 11 | +1. Check `release.env` (`TAG="v1.0.0"`, `ABOUT="Turbo Python"`) and run `./01-release.tag.sh` from a machine that reaches Rickub. It makes the root commit, pushes `main`, tags, pushes the tag. | |
| 12 | +2. Watch the Release workflow on the Actions tab. turbo-go's identical workflow has run and published; this one has not yet. | |
| 13 | +3. If the publish step answers 403, the binaries are on the run page as the `turbo-python-<tag>` artifact (14 days). | |
| 14 | +4. `turbo-python.token.env` was deleted on 2026-09-19; nothing read it any more. | |
| 15 | + | |
| 16 | +## Traps | |
| 17 | + | |
| 18 | +- `go.work` beside this checkout (where there is one) points at `../turbo-core`. Check the *published* shape with `GOWORK=off`; the release tests already do for their children. | |
| 19 | +- Do not `go get …/turbo-core@v0.9.0` under the new path: the proxy has it, but its `go.mod` declares the Codeberg path. v1.0.0 is the first usable version. | |
| 20 | +- `release/` holds the Codeberg-era binaries (hundreds of MB). Gitignored; the tests skip it when copying the module. | |
| 21 | +- `sed -i` on this filesystem drops the execute bit; `chmod 755` the scripts after any such edit. | |
| new file mode 100644 | |||
| @@ -0,0 +1,21 @@ | |||
| 1 | +# Handoff — 2026-09-19 — Rickub migration and the Release workflow | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +- Module `rickub.com/turbo-editors/turbo-python`, pinned to `rickub.com/turbo-editors/turbo-core v1.0.0`; `GOWORK=off make check` green. | ||
| 6 | +- Releases: `./01-release.tag.sh` tags; the tag push runs `.github/workflows/release.yml`, which builds with `./02-build-releases.sh` and publishes the page with the binaries. `02-release.publish.sh` and `04-release.upload-binaries.sh` are deleted. No token needed. | ||
| 7 | +- **Nothing is committed.** Fresh `git init`, `origin` at `ssh://git@rickub.com/turbo-editors/turbo-python.git`, no commit; the sandbox cannot reach the remote. | ||
| 8 | + | ||
| 9 | +## Next steps | ||
| 10 | + | ||
| 11 | +1. Check `release.env` (`TAG="v1.0.0"`, `ABOUT="Turbo Python"`) and run `./01-release.tag.sh` from a machine that reaches Rickub. It makes the root commit, pushes `main`, tags, pushes the tag. | ||
| 12 | +2. Watch the Release workflow on the Actions tab. turbo-go's identical workflow has run and published; this one has not yet. | ||
| 13 | +3. If the publish step answers 403, the binaries are on the run page as the `turbo-python-<tag>` artifact (14 days). | ||
| 14 | +4. `turbo-python.token.env` was deleted on 2026-09-19; nothing read it any more. | ||
| 15 | + | ||
| 16 | +## Traps | ||
| 17 | + | ||
| 18 | +- `go.work` beside this checkout (where there is one) points at `../turbo-core`. Check the *published* shape with `GOWORK=off`; the release tests already do for their children. | ||
| 19 | +- Do not `go get …/turbo-core@v0.9.0` under the new path: the proxy has it, but its `go.mod` declares the Codeberg path. v1.0.0 is the first usable version. | ||
| 20 | +- `release/` holds the Codeberg-era binaries (hundreds of MB). Gitignored; the tests skip it when copying the module. | ||
| 21 | +- `sed -i` on this filesystem drops the execute bit; `chmod 755` the scripts after any such edit. | ||
added
.memory/history.md +104 -0 | new file mode 100644 | ||
| @@ -0,0 +1,104 @@ | ||
| 1 | +# History | |
| 2 | + | |
| 3 | +One dated entry per session, appended. Never rewritten. | |
| 4 | + | |
| 5 | +## 2026-09-03 — Turbo Python built, from an empty repository to a complete editor | |
| 6 | + | |
| 7 | +- **Goal**: `/turbo-new-editor Python ./turbo-python` — a third editor in the family, on turbo-core v0.4.0, without forking anything. | |
| 8 | +- **Shape**: Python has no Go lexer worth using, so this followed `turbo-rust/internal/rustlang` — a hand-written scanner against `syntax.LineScanner`, a line at a time, rather than turbo-go's byte-offset conversion. | |
| 9 | +- **Decisions put to the user**: the menu label `~P~ython` over `P~y~thon`/`Py~t~hon`; `pylsp` over pyright and ruff-lsp; `pyproject.toml` then `setup.py` then `setup.cfg` as root markers; and the six starter commands, all through `uv`. | |
| 10 | +- **Changes**: `main.go`; `internal/pythonlang/` (profile, `scan.go`, `literals.go`, `words.go`, three embedded `.tmpl` starter files); `Makefile`, `scripts/install.sh`, `scripts/check-version.sh` and the four numbered release scripts; 33 documentation pages in each of EN and FR; a root `README.md`. | |
| 11 | +- **Scanner decisions**: a name wholly in capitals is a **constant**, any other capitalised name a **type** — Turbo Rust has only the second rule and documents `SCREAMING_SNAKE_CASE` as a known wrong answer, and PEP 8 separates the conventions well enough that the wrong answer was worth removing rather than inheriting. A capitalised name is a type **even when it is called**, which is the one rule the two editors deliberately order differently. `self` and `cls` are builtins although the language does not name them. An f-string is **one span**, braces included. | |
| 12 | +- **The `[all]` in the install hint is not cosmetic**: installed bare, pylsp starts, completes and jumps, and publishes an *empty* diagnostics list for a file that does not parse, because the linters that produce them are extras. A gutter blank for want of a linter and a gutter blank for want of a bug look identical. | |
| 13 | +- **Four server directories besides `PATH`** — the active virtualenv, `~/.local/bin`, pyenv's shims, and every `~/Library/Python/<version>/bin` that exists. `Profile()` is a function rather than a variable because of the first: a variable would freeze whatever `VIRTUAL_ENV` said at link time. | |
| 14 | +- **Tests**: 129, including one entry per line, spans in order and non-overlapping, broken source still colouring, one per construct and one per thing the scanner deliberately refuses; the templates' formatting contract counted and filled; and five that drive a **real pylsp** end to end — completion typed into the buffer rather than read off disk, references, the file's symbols, diagnostics on a file that does not parse, and an assertion that pylsp answers neither implementations nor project-wide symbols. | |
| 15 | +- **Quality**: PASS 0/0/0, total complexity 91. One smell in the first run, gone in the second. | |
| 16 | +- **The documentation was adapted from Turbo Rust's, and adapting is not substituting.** A mechanical pass left, invisibly to every test: a package diagram still labelled `internal/rustlang` and "the Rust scanner" with `host="turbo-rust"`; a tutorial that had the reader type **Rust code** into a Python file and claimed Rust's colours for it; `crate`/`caisse` in five pages; `golangci-lint` and `go vet` in the tools how-to and in the *French* tools explanation, whose English twin had been rewritten properly; `switch` and `if err != nil` in the snippets explanation; and — the mirror image of the defect the skill warns about — the **English** menus reference saying project menus appear "between Go and Help" while the French one said Python. All fixed in both languages. | |
| 17 | +- **Three claims were stale because the library moved**, not because of the copy: the menu bar listing omitted the **Code** menu in both languages and in the tutorial, and the tutorial's "press → four times to reach Options" was one press short for the same reason. | |
| 18 | +- **Two commands in the docs did not exist**: `uv update` and `uv init --bin`. Replaced with `uv lock --upgrade` and `uv init --app`, checked against `uv 0.9.26`. | |
| 19 | +- **The tutorial was rewritten and then run**, verbatim, in a pty against a real `uv init` project: every colour claim read back off the terminal as an SGR code, every key count re-counted, `uv run main.py`'s real first-run output pasted in, and a new paragraph explaining the `!` the language server puts in the gutter for `E305`. | |
| 20 | +- **A Python-specific fact the copied text hid**: `Enter` copies the current line's indentation and does **not** add a level after a colon. In a language whose blocks *are* indentation, that is worth a sentence in the tutorial and a rewritten paragraph in the snippets explanation, where re-indenting is a correctness matter rather than a nicety. | |
| 21 | +- **`diagram_test.go` is new**, and holds the drawio to `go list`: the boxes are exactly the packages the module imports, every arrow out of our two packages is a real import, the `host` attribute names this project, and no label names another editor's language. All four falsified against the four ways the copied diagram was wrong. | |
| 22 | +- **Verified in a real pty**, beyond the tests: the Python menu under `Alt-P` with `Create tools file` at `30;42` and `Open tools file` greyed at `90;47`; the About box reading "A Turbo C-style editor for **Python**"; a triple-quoted f-string carried across a line break; `Ctrl-Y` deleting a line; the theme dialog opening on the current theme; the server found in `~/.local/bin` with `PATH` stripped, and the install hint on the status bar when it is not findable at all. And **a file that does not parse, opened by a relative path**, showing `×` in the gutter and `⚠ invalid syntax` on the status bar — the failure mode Turbo Go shipped with for months. | |
| 23 | +- **Registered in the family**: turbo-core's `README.md`, `docs/{en,fr}/README.md`, `profile/profile.go`'s package comment, `how-to/release-the-library.md`, `how-to/test-without-publishing.md`, `how-to/write-the-starter-files.md`, `explanation/architecture.md` and `.memory/summary.md`; plus the "both editors" claims in turbo-go's and turbo-rust's architecture explanations. History in those repositories was left alone: "wrong the moment there were two editors" is a true sentence about the past. | |
| 24 | +- **turbo-core's `.go` strings were swept** for hardcoded language names. Every hit was a false positive (`Go to definition`), a doc-comment example of the seam, or a true statement about the implementation (`written in Go.`). Nothing to fix — the About box's language had already been moved into the profile. | |
| 25 | +- **The adaptation found defects in the editor it was adapted from.** turbo-rust's English `reference/menus.md` said project menus appear "between **Go** and Help", twice; both siblings' tutorials listed a menu bar without the Code menu and told the reader to press `→` four times to reach Options, which has been five since that menu shipped; turbo-go's listing was missing Snippets and its own Go menu as well. All fixed in both languages, in both repositories, each with its own history entry and handoff. | |
| 26 | +- **Left for the user**: nothing is committed, here or in the three repositories beside it. This tree is untracked on `main` at `efb533c`. | |
| 27 | + | |
| 28 | +## 2026-09-03 (later) — released as v0.1.0, and re-verified against turbo-core v0.4.1 | |
| 29 | + | |
| 30 | +- The user committed, tagged and pushed all four repositories between sessions: turbo-python **v0.1.0** (`bccbb0b`), turbo-core **v0.4.1** (`4f93fb0`), turbo-go **v0.4.2**, turbo-rust **v0.4.2**. Everything written in the entry above is in those tags. | |
| 31 | +- **turbo-core v0.4.1 changes one `.go` file and it is a comment** — `profile/profile.go`'s package doc, which counted the editors. No behaviour change, so nothing in this editor's documentation is affected by the bump. | |
| 32 | +- **Re-verified at the new HEAD**: `go.mod` now requires `v0.4.1` with no active `replace`; `gofmt -l` clean, `go build ./...` clean, `go test ./...` green in both packages against the freshly downloaded module. | |
| 33 | +- `.memory/summary.md` corrected in place: the pinned version, and the two claims that had become false — "nothing is committed" and "no release". The handoff was left alone, because a handoff records what was true when it was written. | |
| 34 | + | |
| 35 | +## 2026-09-09 — a documentation defect a fourth editor exposed | |
| 36 | + | |
| 37 | +- **Goal**: none of its own. This repository was the worked example for turbo-moonbit, and adapting it surfaced a defect here. | |
| 38 | +- **Changes**: `Alt-T` → `Alt-P` in ten files across both languages — `reference/python-tools.md`, `reference/menus.md`, `reference/keyboard.md` and `how-to/run-uv-commands.md`. The Python menu is `~P~ython` and answers to `Alt-P`; `Alt-T` is Turbo Rust's, from `Rus~t~`, and it survived the mechanical substitution that produced these pages because it is not an identifier. A sentence about custom-menu hot keys ("`Format` gets `Alt-M`") was wrong for the same reason and was rewritten. "all three editors" → "all four" in the architecture explanation, both languages. | |
| 39 | +- **Decisions**: fixed here rather than left, because it is a two-line-per-file correction in somebody else's repository — exactly the kind of change that is invisible afterwards if it is not written down. | |
| 40 | +- **Tests**: none added here. turbo-moonbit gained `TestTheToolsReferenceMatchesTheStarterFile`, which reads the tools table out of its own reference pages and holds it to the file the editor writes, hot key included. **Copying that test across is the way to stop this recurring**, and it is perhaps twenty minutes. | |
| 41 | +- **Not done**: nothing else in this repository was touched, and its suite was not re-run. | |
| 42 | + | |
| 43 | +## 2026-09-09 (later) — the theme list gained three entries | |
| 44 | + | |
| 45 | +- **Goal**: none of its own. turbo-core gained `monochrome-light`, `darcula` and `intellij-light`, and renamed `monochrome` to `monochrome-dark`; this repository's documentation had to follow. Eleven themes ship now. | |
| 46 | +- **Changes**: `docs/{en,fr}/reference/themes.md` — the embedded list, three new table rows, and a new "a name a theme used to answer to" section saying `monochrome` still loads; `docs/{en,fr}/how-to/write-a-theme.md` — the inherit-from advice and the shipped-theme count; `README.md`'s themes bullet. No code change. | |
| 47 | +- **History was left alone**: "comments were the dimmest colour in six of the eight shipped themes" in `write-a-theme.md` is a true sentence about when that rule was written. | |
| 48 | +- **Not yet true of the binary.** This repository pins turbo-core v0.4.2, which ships eight themes. The documentation is ahead until turbo-core is tagged and the `go.mod` here is bumped — see turbo-core's handoff of the same date. | |
| 49 | + | |
| 50 | +## 2026-09-14 — the family count moved from four to five | |
| 51 | + | |
| 52 | +- **Asked**: nothing of this repository. Turbo Golo was built beside it, and `docs/{en,fr}/explanation/architecture.md` said the library's packages are used unchanged by "all four editors". | |
| 53 | +- **Changes**: that one sentence, in both languages — four → five. No code touched; no tests run. | |
| 54 | + | |
| 55 | +## 2026-09-15 — ACP agent windows, ported from turbo-go | |
| 56 | + | |
| 57 | +- **Goal**: carry the Agent Client Protocol support to this editor. The feature itself is turbo-core's — the protocol client, the conversation model, the window widget, the `Agent` menu and the permission dialog all live there. See turbo-core's history for the same date. | |
| 58 | +- **Changes**: `internal/*/acp.toml.tmpl`, embedded in `templates.go` and wired into `profile.Templates.Agents`. That is the entire code change — one file and one line. Plus six documentation pages (EN + FR: how-to, reference, explanation) and their index entries. | |
| 59 | +- **Decisions**: the example agent is `docker agent`, as in every other editor, because the protocol is the point and the agent is the user's choice; the one sentence in the starter file that is about **this** editor names its own fence, and a test holds it to that — a starter file copied from another editor and left naming that editor's language is the obvious way to get this port wrong. | |
| 60 | +- **Tests**: 5 new in `internal/*`: both blanks filled with no `%!` marker, the file loads back as exactly one agent, it explains its keys, it names this editor's own language, and creating it twice leaves the first alone. | |
| 61 | +- **Quality**: PASS 0/0/0. | |
| 62 | +- **Docs**: adapted rather than copied — the slug, the language, the fence, the build command and the language server all differ from turbo-go's, and each was replaced. | |
| 63 | +- Not committed. | |
| 64 | + | |
| 65 | +## 2026-09-15 (night) — slash commands and `@` mentions, documented | |
| 66 | + | |
| 67 | +- **Documentation and the starter file only in this repository**; the code is turbo-core's (see its `.memory/` of the same date). The user asked for the ACP changes that let an agent's commands be discovered the way Zed discovers them, then for `@` as a file selector. | |
| 68 | +- **Changes**: `docs/{en,fr}/reference/acp.md` — seven key rows for the list, a **Commands and mentions** section, the `session/prompt` and `available_commands_update` rows, the Limits bullet; `docs/{en,fr}/how-to/talk-to-an-agent.md` — "Use the agent's own commands" and "Point the agent at a file"; `docs/{en,fr}/explanation/agent-windows.md` — the "left out" bullet narrowed to images, two sections appended; the embedded `acp.toml.tmpl` — two key lines. Applied by one script across the five editors with an exactly-once anchor check. | |
| 69 | +- **Tests**: `go test ./...` green (the template change is a comment; the tests that read the created file still pass). | |
| 70 | +- **Ahead of the binary**: this repository pins turbo-core v0.7.0, which has none of this. The pages are true once turbo-core is tagged and the pin moved. | |
| 71 | +- Not committed. | |
| 72 | + | |
| 73 | +## 2026-09-16 — the trace variable and a troubleshooting bullet, documented | |
| 74 | + | |
| 75 | +- turbo-core gained `TURBO_ACP_TRACE=<file>` and an "update this editor could not read" line in Agent status, because the user saw no `/` commands from their own agent and nothing on screen could say why. Documented here EN + FR: a bullet in the how-to's Variants, a section in `reference/acp.md`. Docs only; not committed. | |
| 76 | +- **Later on 2026-09-16**: `.turbo-python/acp.toml` (and `agent.yaml`, docker agent's config copied from turbo-go) now hold two agents — **Bob (llama.cpp)** via `docker agent serve acp`, and the user's **mini-me (llama.cpp)** (`mm -acp`, `AGENT_CONFIG` env) — placed where this repository's demo project already keeps its settings. Verified to load as two agents with this editor's own `Profile()`; not opened, `mm` and `docker` are on the user's Mac. Working files for trying the `/` picker, not part of the feature. | |
| 77 | + | |
| 78 | +## 2026-09-16 — family count: a sixth editor, Turbo JS | |
| 79 | + | |
| 80 | +- **Asked**: nothing of this repository directly. Turbo JS was built beside it, and the sentences here that count the family went false the moment it existed. | |
| 81 | +- **Changes**: `docs/en/explanation/architecture.md`, `docs/fr/explanation/architecture.md` — "five editors" → six. Nothing else touched; history left as it was. | |
| 82 | +- **Tests**: none affected — documentation only. | |
| 83 | + | |
| 84 | +## 2026-09-17 — documentation: terminal windows and tools on Windows | |
| 85 | + | |
| 86 | +- **Asked**: nothing of this repository directly. turbo-core gained pseudo-console (ConPTY) terminal windows and a per-platform tools shell (cmd.exe on Windows); the pages here that said "Linux and macOS" or `/bin/sh -c` went false the moment that landed. | |
| 87 | +- **Changes** (EN + FR): `README.md` (terminal windows: Linux, macOS and Windows), `docs/*/reference/terminal.md` (shell row, controlling-terminal row, platform table, error row), `docs/*/explanation/terminal-windows.md` (the Windows section rewritten: a pseudo-console and why it is a file of its own, built and vetted but not yet run), `docs/*/how-to/use-a-terminal.md` (`%COMSPEC%`, the five things to try first on Windows), `docs/*/reference/python-tools.md` (shell row, cmd.exe's globs and `;`, error row), `docs/*/explanation/python-tools.md` (`cmd.exe /S /C`). Applied by one script across the six editors, one anchor per file. | |
| 88 | +- **Not changed**: code, `go.mod`. **The documentation is ahead of the binary** until turbo-core is tagged (v0.9.0) and re-pinned here; the feature has never been run on Windows by anyone. | |
| 89 | +- **Tests**: none affected — documentation only. | |
| 90 | + | |
| 91 | +## 2026-09-18 — the "Untitled window has no LSP" fix: docs variant added, fix is turbo-core's | |
| 92 | + | |
| 93 | +- **Asked**: propagate to every editor the fix made in turbo-core the same day — saving now announces a document the server does not know (a window that started Untitled gets LSP from its first save), and Save As under a new name closes the old document. See turbo-core's `.memory/history.md` of 2026-09-18 for the defect and the fix. | |
| 94 | +- **Changes here**: `docs/{en,fr}/how-to/enable-completion.md` gain one variant — completion in a window that started without a name works from its first save, no relaunch needed. No code in this repository is involved. | |
| 95 | +- **Quality**: gate not re-run — a Markdown-only change; the gate measures the Go code. | |
| 96 | +- **Docs ahead of the binary**: the behaviour arrives only when turbo-core is tagged and this editor re-pinned. Not committed. | |
| 97 | + | |
| 98 | +## 2026-09-19 — moved to Rickub: turbo-core v1.0.0 re-pinned, releases published by a workflow | |
| 99 | + | |
| 100 | +- **Asked**: the same migration turbo-go received the same day, for all five remaining editors — turbo-core moved to `rickub.com` and was published as v1.0.0 with a Release workflow. | |
| 101 | +- **Changes, module**: `codeberg.org/turbo-editors` → `rickub.com/turbo-editors` in `go.mod`, every `.go` file, `Makefile`, `scripts/install.sh`, `README.md`, `docs/{en,fr}`, `.memory/summary.md` (turbo-core deep links also from Codeberg's `src/branch/main/` to `blob/main/`). `require rickub.com/turbo-editors/turbo-core v1.0.0`; `go mod tidy` with `GOWORK=off` rewrote `go.sum` from the proxy. | |
| 102 | +- **Changes, release tooling**: `.github/workflows/release.yml` (new), `01-release.tag.sh` (rewritten), `03-build-releases.sh` → `02-build-releases.sh` (tag from `$1`, validation, `replace` check, fresh `release/${TAG}/`, `go install` line in the README, no hand-off to 04), `02-release.publish.sh` and `04-release.upload-binaries.sh` deleted, `release.env` rewritten (`TAG="v1.0.0"`, `ABOUT="Turbo Python"`). All generated from turbo-go's final files with the names substituted; the README paragraph naming this editor's language server and the example file (`main.py`) kept from the old 03. Docs: the release section and the wrong-commit variant of `docs/{en,fr}/how-to/make-a-release.md` rewritten. | |
| 103 | +- **Tests**: `release_test.go` regenerated from turbo-go's — see `summary.md`. The file-writing helper is `writeTestFile` because turbo-python's `main_test.go` owns `writeFile`, and the command helper `runOrFail` because `main.go` owns `run`. | |
| 104 | +- **Not done**: nothing committed or pushed — no commit exists yet and `origin` is unreachable from the sandbox. The workflow has not run on Rickub for this editor; turbo-go's identical one has, and published. | |
| new file mode 100644 | |||
| @@ -0,0 +1,104 @@ | |||
| 1 | +# History | ||
| 2 | + | ||
| 3 | +One dated entry per session, appended. Never rewritten. | ||
| 4 | + | ||
| 5 | +## 2026-09-03 — Turbo Python built, from an empty repository to a complete editor | ||
| 6 | + | ||
| 7 | +- **Goal**: `/turbo-new-editor Python ./turbo-python` — a third editor in the family, on turbo-core v0.4.0, without forking anything. | ||
| 8 | +- **Shape**: Python has no Go lexer worth using, so this followed `turbo-rust/internal/rustlang` — a hand-written scanner against `syntax.LineScanner`, a line at a time, rather than turbo-go's byte-offset conversion. | ||
| 9 | +- **Decisions put to the user**: the menu label `~P~ython` over `P~y~thon`/`Py~t~hon`; `pylsp` over pyright and ruff-lsp; `pyproject.toml` then `setup.py` then `setup.cfg` as root markers; and the six starter commands, all through `uv`. | ||
| 10 | +- **Changes**: `main.go`; `internal/pythonlang/` (profile, `scan.go`, `literals.go`, `words.go`, three embedded `.tmpl` starter files); `Makefile`, `scripts/install.sh`, `scripts/check-version.sh` and the four numbered release scripts; 33 documentation pages in each of EN and FR; a root `README.md`. | ||
| 11 | +- **Scanner decisions**: a name wholly in capitals is a **constant**, any other capitalised name a **type** — Turbo Rust has only the second rule and documents `SCREAMING_SNAKE_CASE` as a known wrong answer, and PEP 8 separates the conventions well enough that the wrong answer was worth removing rather than inheriting. A capitalised name is a type **even when it is called**, which is the one rule the two editors deliberately order differently. `self` and `cls` are builtins although the language does not name them. An f-string is **one span**, braces included. | ||
| 12 | +- **The `[all]` in the install hint is not cosmetic**: installed bare, pylsp starts, completes and jumps, and publishes an *empty* diagnostics list for a file that does not parse, because the linters that produce them are extras. A gutter blank for want of a linter and a gutter blank for want of a bug look identical. | ||
| 13 | +- **Four server directories besides `PATH`** — the active virtualenv, `~/.local/bin`, pyenv's shims, and every `~/Library/Python/<version>/bin` that exists. `Profile()` is a function rather than a variable because of the first: a variable would freeze whatever `VIRTUAL_ENV` said at link time. | ||
| 14 | +- **Tests**: 129, including one entry per line, spans in order and non-overlapping, broken source still colouring, one per construct and one per thing the scanner deliberately refuses; the templates' formatting contract counted and filled; and five that drive a **real pylsp** end to end — completion typed into the buffer rather than read off disk, references, the file's symbols, diagnostics on a file that does not parse, and an assertion that pylsp answers neither implementations nor project-wide symbols. | ||
| 15 | +- **Quality**: PASS 0/0/0, total complexity 91. One smell in the first run, gone in the second. | ||
| 16 | +- **The documentation was adapted from Turbo Rust's, and adapting is not substituting.** A mechanical pass left, invisibly to every test: a package diagram still labelled `internal/rustlang` and "the Rust scanner" with `host="turbo-rust"`; a tutorial that had the reader type **Rust code** into a Python file and claimed Rust's colours for it; `crate`/`caisse` in five pages; `golangci-lint` and `go vet` in the tools how-to and in the *French* tools explanation, whose English twin had been rewritten properly; `switch` and `if err != nil` in the snippets explanation; and — the mirror image of the defect the skill warns about — the **English** menus reference saying project menus appear "between Go and Help" while the French one said Python. All fixed in both languages. | ||
| 17 | +- **Three claims were stale because the library moved**, not because of the copy: the menu bar listing omitted the **Code** menu in both languages and in the tutorial, and the tutorial's "press → four times to reach Options" was one press short for the same reason. | ||
| 18 | +- **Two commands in the docs did not exist**: `uv update` and `uv init --bin`. Replaced with `uv lock --upgrade` and `uv init --app`, checked against `uv 0.9.26`. | ||
| 19 | +- **The tutorial was rewritten and then run**, verbatim, in a pty against a real `uv init` project: every colour claim read back off the terminal as an SGR code, every key count re-counted, `uv run main.py`'s real first-run output pasted in, and a new paragraph explaining the `!` the language server puts in the gutter for `E305`. | ||
| 20 | +- **A Python-specific fact the copied text hid**: `Enter` copies the current line's indentation and does **not** add a level after a colon. In a language whose blocks *are* indentation, that is worth a sentence in the tutorial and a rewritten paragraph in the snippets explanation, where re-indenting is a correctness matter rather than a nicety. | ||
| 21 | +- **`diagram_test.go` is new**, and holds the drawio to `go list`: the boxes are exactly the packages the module imports, every arrow out of our two packages is a real import, the `host` attribute names this project, and no label names another editor's language. All four falsified against the four ways the copied diagram was wrong. | ||
| 22 | +- **Verified in a real pty**, beyond the tests: the Python menu under `Alt-P` with `Create tools file` at `30;42` and `Open tools file` greyed at `90;47`; the About box reading "A Turbo C-style editor for **Python**"; a triple-quoted f-string carried across a line break; `Ctrl-Y` deleting a line; the theme dialog opening on the current theme; the server found in `~/.local/bin` with `PATH` stripped, and the install hint on the status bar when it is not findable at all. And **a file that does not parse, opened by a relative path**, showing `×` in the gutter and `⚠ invalid syntax` on the status bar — the failure mode Turbo Go shipped with for months. | ||
| 23 | +- **Registered in the family**: turbo-core's `README.md`, `docs/{en,fr}/README.md`, `profile/profile.go`'s package comment, `how-to/release-the-library.md`, `how-to/test-without-publishing.md`, `how-to/write-the-starter-files.md`, `explanation/architecture.md` and `.memory/summary.md`; plus the "both editors" claims in turbo-go's and turbo-rust's architecture explanations. History in those repositories was left alone: "wrong the moment there were two editors" is a true sentence about the past. | ||
| 24 | +- **turbo-core's `.go` strings were swept** for hardcoded language names. Every hit was a false positive (`Go to definition`), a doc-comment example of the seam, or a true statement about the implementation (`written in Go.`). Nothing to fix — the About box's language had already been moved into the profile. | ||
| 25 | +- **The adaptation found defects in the editor it was adapted from.** turbo-rust's English `reference/menus.md` said project menus appear "between **Go** and Help", twice; both siblings' tutorials listed a menu bar without the Code menu and told the reader to press `→` four times to reach Options, which has been five since that menu shipped; turbo-go's listing was missing Snippets and its own Go menu as well. All fixed in both languages, in both repositories, each with its own history entry and handoff. | ||
| 26 | +- **Left for the user**: nothing is committed, here or in the three repositories beside it. This tree is untracked on `main` at `efb533c`. | ||
| 27 | + | ||
| 28 | +## 2026-09-03 (later) — released as v0.1.0, and re-verified against turbo-core v0.4.1 | ||
| 29 | + | ||
| 30 | +- The user committed, tagged and pushed all four repositories between sessions: turbo-python **v0.1.0** (`bccbb0b`), turbo-core **v0.4.1** (`4f93fb0`), turbo-go **v0.4.2**, turbo-rust **v0.4.2**. Everything written in the entry above is in those tags. | ||
| 31 | +- **turbo-core v0.4.1 changes one `.go` file and it is a comment** — `profile/profile.go`'s package doc, which counted the editors. No behaviour change, so nothing in this editor's documentation is affected by the bump. | ||
| 32 | +- **Re-verified at the new HEAD**: `go.mod` now requires `v0.4.1` with no active `replace`; `gofmt -l` clean, `go build ./...` clean, `go test ./...` green in both packages against the freshly downloaded module. | ||
| 33 | +- `.memory/summary.md` corrected in place: the pinned version, and the two claims that had become false — "nothing is committed" and "no release". The handoff was left alone, because a handoff records what was true when it was written. | ||
| 34 | + | ||
| 35 | +## 2026-09-09 — a documentation defect a fourth editor exposed | ||
| 36 | + | ||
| 37 | +- **Goal**: none of its own. This repository was the worked example for turbo-moonbit, and adapting it surfaced a defect here. | ||
| 38 | +- **Changes**: `Alt-T` → `Alt-P` in ten files across both languages — `reference/python-tools.md`, `reference/menus.md`, `reference/keyboard.md` and `how-to/run-uv-commands.md`. The Python menu is `~P~ython` and answers to `Alt-P`; `Alt-T` is Turbo Rust's, from `Rus~t~`, and it survived the mechanical substitution that produced these pages because it is not an identifier. A sentence about custom-menu hot keys ("`Format` gets `Alt-M`") was wrong for the same reason and was rewritten. "all three editors" → "all four" in the architecture explanation, both languages. | ||
| 39 | +- **Decisions**: fixed here rather than left, because it is a two-line-per-file correction in somebody else's repository — exactly the kind of change that is invisible afterwards if it is not written down. | ||
| 40 | +- **Tests**: none added here. turbo-moonbit gained `TestTheToolsReferenceMatchesTheStarterFile`, which reads the tools table out of its own reference pages and holds it to the file the editor writes, hot key included. **Copying that test across is the way to stop this recurring**, and it is perhaps twenty minutes. | ||
| 41 | +- **Not done**: nothing else in this repository was touched, and its suite was not re-run. | ||
| 42 | + | ||
| 43 | +## 2026-09-09 (later) — the theme list gained three entries | ||
| 44 | + | ||
| 45 | +- **Goal**: none of its own. turbo-core gained `monochrome-light`, `darcula` and `intellij-light`, and renamed `monochrome` to `monochrome-dark`; this repository's documentation had to follow. Eleven themes ship now. | ||
| 46 | +- **Changes**: `docs/{en,fr}/reference/themes.md` — the embedded list, three new table rows, and a new "a name a theme used to answer to" section saying `monochrome` still loads; `docs/{en,fr}/how-to/write-a-theme.md` — the inherit-from advice and the shipped-theme count; `README.md`'s themes bullet. No code change. | ||
| 47 | +- **History was left alone**: "comments were the dimmest colour in six of the eight shipped themes" in `write-a-theme.md` is a true sentence about when that rule was written. | ||
| 48 | +- **Not yet true of the binary.** This repository pins turbo-core v0.4.2, which ships eight themes. The documentation is ahead until turbo-core is tagged and the `go.mod` here is bumped — see turbo-core's handoff of the same date. | ||
| 49 | + | ||
| 50 | +## 2026-09-14 — the family count moved from four to five | ||
| 51 | + | ||
| 52 | +- **Asked**: nothing of this repository. Turbo Golo was built beside it, and `docs/{en,fr}/explanation/architecture.md` said the library's packages are used unchanged by "all four editors". | ||
| 53 | +- **Changes**: that one sentence, in both languages — four → five. No code touched; no tests run. | ||
| 54 | + | ||
| 55 | +## 2026-09-15 — ACP agent windows, ported from turbo-go | ||
| 56 | + | ||
| 57 | +- **Goal**: carry the Agent Client Protocol support to this editor. The feature itself is turbo-core's — the protocol client, the conversation model, the window widget, the `Agent` menu and the permission dialog all live there. See turbo-core's history for the same date. | ||
| 58 | +- **Changes**: `internal/*/acp.toml.tmpl`, embedded in `templates.go` and wired into `profile.Templates.Agents`. That is the entire code change — one file and one line. Plus six documentation pages (EN + FR: how-to, reference, explanation) and their index entries. | ||
| 59 | +- **Decisions**: the example agent is `docker agent`, as in every other editor, because the protocol is the point and the agent is the user's choice; the one sentence in the starter file that is about **this** editor names its own fence, and a test holds it to that — a starter file copied from another editor and left naming that editor's language is the obvious way to get this port wrong. | ||
| 60 | +- **Tests**: 5 new in `internal/*`: both blanks filled with no `%!` marker, the file loads back as exactly one agent, it explains its keys, it names this editor's own language, and creating it twice leaves the first alone. | ||
| 61 | +- **Quality**: PASS 0/0/0. | ||
| 62 | +- **Docs**: adapted rather than copied — the slug, the language, the fence, the build command and the language server all differ from turbo-go's, and each was replaced. | ||
| 63 | +- Not committed. | ||
| 64 | + | ||
| 65 | +## 2026-09-15 (night) — slash commands and `@` mentions, documented | ||
| 66 | + | ||
| 67 | +- **Documentation and the starter file only in this repository**; the code is turbo-core's (see its `.memory/` of the same date). The user asked for the ACP changes that let an agent's commands be discovered the way Zed discovers them, then for `@` as a file selector. | ||
| 68 | +- **Changes**: `docs/{en,fr}/reference/acp.md` — seven key rows for the list, a **Commands and mentions** section, the `session/prompt` and `available_commands_update` rows, the Limits bullet; `docs/{en,fr}/how-to/talk-to-an-agent.md` — "Use the agent's own commands" and "Point the agent at a file"; `docs/{en,fr}/explanation/agent-windows.md` — the "left out" bullet narrowed to images, two sections appended; the embedded `acp.toml.tmpl` — two key lines. Applied by one script across the five editors with an exactly-once anchor check. | ||
| 69 | +- **Tests**: `go test ./...` green (the template change is a comment; the tests that read the created file still pass). | ||
| 70 | +- **Ahead of the binary**: this repository pins turbo-core v0.7.0, which has none of this. The pages are true once turbo-core is tagged and the pin moved. | ||
| 71 | +- Not committed. | ||
| 72 | + | ||
| 73 | +## 2026-09-16 — the trace variable and a troubleshooting bullet, documented | ||
| 74 | + | ||
| 75 | +- turbo-core gained `TURBO_ACP_TRACE=<file>` and an "update this editor could not read" line in Agent status, because the user saw no `/` commands from their own agent and nothing on screen could say why. Documented here EN + FR: a bullet in the how-to's Variants, a section in `reference/acp.md`. Docs only; not committed. | ||
| 76 | +- **Later on 2026-09-16**: `.turbo-python/acp.toml` (and `agent.yaml`, docker agent's config copied from turbo-go) now hold two agents — **Bob (llama.cpp)** via `docker agent serve acp`, and the user's **mini-me (llama.cpp)** (`mm -acp`, `AGENT_CONFIG` env) — placed where this repository's demo project already keeps its settings. Verified to load as two agents with this editor's own `Profile()`; not opened, `mm` and `docker` are on the user's Mac. Working files for trying the `/` picker, not part of the feature. | ||
| 77 | + | ||
| 78 | +## 2026-09-16 — family count: a sixth editor, Turbo JS | ||
| 79 | + | ||
| 80 | +- **Asked**: nothing of this repository directly. Turbo JS was built beside it, and the sentences here that count the family went false the moment it existed. | ||
| 81 | +- **Changes**: `docs/en/explanation/architecture.md`, `docs/fr/explanation/architecture.md` — "five editors" → six. Nothing else touched; history left as it was. | ||
| 82 | +- **Tests**: none affected — documentation only. | ||
| 83 | + | ||
| 84 | +## 2026-09-17 — documentation: terminal windows and tools on Windows | ||
| 85 | + | ||
| 86 | +- **Asked**: nothing of this repository directly. turbo-core gained pseudo-console (ConPTY) terminal windows and a per-platform tools shell (cmd.exe on Windows); the pages here that said "Linux and macOS" or `/bin/sh -c` went false the moment that landed. | ||
| 87 | +- **Changes** (EN + FR): `README.md` (terminal windows: Linux, macOS and Windows), `docs/*/reference/terminal.md` (shell row, controlling-terminal row, platform table, error row), `docs/*/explanation/terminal-windows.md` (the Windows section rewritten: a pseudo-console and why it is a file of its own, built and vetted but not yet run), `docs/*/how-to/use-a-terminal.md` (`%COMSPEC%`, the five things to try first on Windows), `docs/*/reference/python-tools.md` (shell row, cmd.exe's globs and `;`, error row), `docs/*/explanation/python-tools.md` (`cmd.exe /S /C`). Applied by one script across the six editors, one anchor per file. | ||
| 88 | +- **Not changed**: code, `go.mod`. **The documentation is ahead of the binary** until turbo-core is tagged (v0.9.0) and re-pinned here; the feature has never been run on Windows by anyone. | ||
| 89 | +- **Tests**: none affected — documentation only. | ||
| 90 | + | ||
| 91 | +## 2026-09-18 — the "Untitled window has no LSP" fix: docs variant added, fix is turbo-core's | ||
| 92 | + | ||
| 93 | +- **Asked**: propagate to every editor the fix made in turbo-core the same day — saving now announces a document the server does not know (a window that started Untitled gets LSP from its first save), and Save As under a new name closes the old document. See turbo-core's `.memory/history.md` of 2026-09-18 for the defect and the fix. | ||
| 94 | +- **Changes here**: `docs/{en,fr}/how-to/enable-completion.md` gain one variant — completion in a window that started without a name works from its first save, no relaunch needed. No code in this repository is involved. | ||
| 95 | +- **Quality**: gate not re-run — a Markdown-only change; the gate measures the Go code. | ||
| 96 | +- **Docs ahead of the binary**: the behaviour arrives only when turbo-core is tagged and this editor re-pinned. Not committed. | ||
| 97 | + | ||
| 98 | +## 2026-09-19 — moved to Rickub: turbo-core v1.0.0 re-pinned, releases published by a workflow | ||
| 99 | + | ||
| 100 | +- **Asked**: the same migration turbo-go received the same day, for all five remaining editors — turbo-core moved to `rickub.com` and was published as v1.0.0 with a Release workflow. | ||
| 101 | +- **Changes, module**: `codeberg.org/turbo-editors` → `rickub.com/turbo-editors` in `go.mod`, every `.go` file, `Makefile`, `scripts/install.sh`, `README.md`, `docs/{en,fr}`, `.memory/summary.md` (turbo-core deep links also from Codeberg's `src/branch/main/` to `blob/main/`). `require rickub.com/turbo-editors/turbo-core v1.0.0`; `go mod tidy` with `GOWORK=off` rewrote `go.sum` from the proxy. | ||
| 102 | +- **Changes, release tooling**: `.github/workflows/release.yml` (new), `01-release.tag.sh` (rewritten), `03-build-releases.sh` → `02-build-releases.sh` (tag from `$1`, validation, `replace` check, fresh `release/${TAG}/`, `go install` line in the README, no hand-off to 04), `02-release.publish.sh` and `04-release.upload-binaries.sh` deleted, `release.env` rewritten (`TAG="v1.0.0"`, `ABOUT="Turbo Python"`). All generated from turbo-go's final files with the names substituted; the README paragraph naming this editor's language server and the example file (`main.py`) kept from the old 03. Docs: the release section and the wrong-commit variant of `docs/{en,fr}/how-to/make-a-release.md` rewritten. | ||
| 103 | +- **Tests**: `release_test.go` regenerated from turbo-go's — see `summary.md`. The file-writing helper is `writeTestFile` because turbo-python's `main_test.go` owns `writeFile`, and the command helper `runOrFail` because `main.go` owns `run`. | ||
| 104 | +- **Not done**: nothing committed or pushed — no commit exists yet and `origin` is unreachable from the sandbox. The workflow has not run on Rickub for this editor; turbo-go's identical one has, and published. | ||
added
.memory/summary.md +143 -0 | new file mode 100644 | ||
| @@ -0,0 +1,143 @@ | ||
| 1 | +# turbo-python — summary | |
| 2 | + | |
| 3 | +A snapshot of the present. Edited in place; the history is in `history.md`. | |
| 4 | + | |
| 5 | +## What this is | |
| 6 | + | |
| 7 | +A Turbo C-style terminal IDE for Python, written in Go, built on | |
| 8 | +**[turbo-core](https://rickub.com/turbo-editors/turbo-core)** — the library Turbo Go and | |
| 9 | +Turbo Rust already share. This repository holds the command, the profile that says the | |
| 10 | +editor is for Python, and the Python scanner. Everything else — the event loop, the | |
| 11 | +windows, the dialogs, the themes, the LSP client, the terminal emulator, the project tree, | |
| 12 | +the snippets and tools machinery — is the library's, and none of it is copied here. | |
| 13 | + | |
| 14 | +Module `rickub.com/turbo-editors/turbo-python`, `require`ing turbo-core **v0.4.1** from | |
| 15 | +the module proxy with **no active `replace`**. The commented-out `replace` at the bottom of | |
| 16 | +`go.mod` documents the escape hatch without being one; `01-release.tag.sh` refuses to tag a | |
| 17 | +release whose `go.mod` carries a live one. | |
| 18 | + | |
| 19 | +## Layout | |
| 20 | + | |
| 21 | +| | | | |
| 22 | +| --- | --- | | |
| 23 | +| `main.go` | flags, the terminal, `pythonlang.Register()`, the profile, the loop | | |
| 24 | +| `internal/pythonlang/pythonlang.go` | `Name`, `Slug`, `Language`, `Profile()`, `Register()`, the four server directories | | |
| 25 | +| `internal/pythonlang/scan.go` | the scanner's dispatcher, comments, decorators | | |
| 26 | +| `internal/pythonlang/literals.go` | strings — all six prefixes, both triple quotes, line continuations | | |
| 27 | +| `internal/pythonlang/words.go` | numbers, keywords, soft keywords, the name-shape rules | | |
| 28 | +| `internal/pythonlang/*.toml.tmpl` | the three starter files, embedded by `templates.go` | | |
| 29 | +| `diagram_test.go` | holds `docs/diagrams/packages.drawio` to `go list` | | |
| 30 | +| `docs/{en,fr}/` | 33 pages each (README included), Diátaxis | | |
| 31 | + | |
| 32 | +## How to build, test and measure | |
| 33 | + | |
| 34 | +```bash | |
| 35 | +make check # fmt, vet, then the whole suite — what a commit should pass | |
| 36 | +make build # into bin/turbo-python, then check the binary reports its version | |
| 37 | +make install # build, install onto PATH, report what it found | |
| 38 | +go test ./... # 129 tests; the pylsp ones skip themselves without a server | |
| 39 | +``` | |
| 40 | + | |
| 41 | +Quality gate, separate from the tests: | |
| 42 | + | |
| 43 | +```bash | |
| 44 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | |
| 45 | +``` | |
| 46 | + | |
| 47 | +To build against a turbo-core you have changed but not released: | |
| 48 | + | |
| 49 | +```bash | |
| 50 | +go work init . ../turbo-core | |
| 51 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app # must NOT be under pkg/mod | |
| 52 | +``` | |
| 53 | + | |
| 54 | +`go.work` and `go.work.sum` are gitignored. **Everything still builds and still passes** | |
| 55 | +while testing the published library instead of your changes, so run that second line. | |
| 56 | + | |
| 57 | +## Decisions in force | |
| 58 | + | |
| 59 | +- **The toolchain menu is `~P~ython`, not `uv`.** `P` is free — the fixed menus take F, E, | |
| 60 | + S, R, C, O, W, N and H. Named after the language because the menu holds whatever the | |
| 61 | + project put in its tools file, and a menu called `uv` holding `docker compose up` is a lie | |
| 62 | + about what the menu is. | |
| 63 | +- **The language server is `pylsp`, and the install hint says `pipx install | |
| 64 | + "python-lsp-server[all]"`.** The `[all]` is load-bearing: installed bare, pylsp starts, | |
| 65 | + completes and jumps, and publishes an **empty** diagnostics list for a file that does not | |
| 66 | + parse, because the linters are extras. A gutter blank for want of a linter looks exactly | |
| 67 | + like a gutter blank for want of a bug. | |
| 68 | +- **pylsp answers seven of turbo-core's nine questions.** It advertises neither | |
| 69 | + `implementation` nor `workspace/symbol`, so those two items report nothing found. That is | |
| 70 | + documented rather than worked around, and a test asserts it so a future pylsp gaining them | |
| 71 | + is noticed. | |
| 72 | +- **`Profile()` is a function, not a variable**, because `Server.Dirs` reads the | |
| 73 | + environment, and a variable would freeze whatever `VIRTUAL_ENV` said at link time — for a | |
| 74 | + Python tool, the one value most likely to change between two runs in the same shell. | |
| 75 | +- **Four places are searched for the server besides `PATH`**: the active virtual | |
| 76 | + environment's `bin`, `~/.local/bin`, pyenv's shims, and every | |
| 77 | + `~/Library/Python/<version>/bin` that exists. The last is read rather than guessed, and is | |
| 78 | + on nobody's `PATH` on macOS. | |
| 79 | +- **Root markers, in order: `pyproject.toml`, `setup.py`, `setup.cfg`.** | |
| 80 | +- **A name wholly in capitals is a constant; any other capitalised name is a type.** Turbo | |
| 81 | + Rust has only the second rule and documents `SCREAMING_SNAKE_CASE` as a known wrong | |
| 82 | + answer; PEP 8 separates the two conventions well enough that the wrong answer was worth | |
| 83 | + removing rather than inheriting. The cost is a class named `HTTP`. | |
| 84 | +- **A capitalised name is a type even when it is called.** `ValueError("nope")` and | |
| 85 | + `parse("nope")` are the same shape. This is the one rule Turbo Python and Turbo Rust order | |
| 86 | + differently, on purpose. | |
| 87 | +- **`self` and `cls` are coloured as builtins** although the language does not name them. | |
| 88 | +- **An f-string is one string span**, `{…}` included. Finding where an expression ends | |
| 89 | + inside a literal needs a parser; this is a scanner. | |
| 90 | +- **The starter templates are embedded files, not Go constants**, with the `.tmpl` suffix | |
| 91 | + because `settings.toml.tmpl` holds `theme = %q`, which is not valid TOML. | |
| 92 | +- **`autosave = true` in the starter settings file, `false` in `settings.Default()`.** Two | |
| 93 | + statements in two places on purpose: a project that created a settings file has said what | |
| 94 | + it wants; a directory somebody merely started the editor in has not. | |
| 95 | +- **Agent windows are turbo-core's, and what belongs here is the starter file.** `acp.toml.tmpl` is the fourth embedded template, and `profile.Templates.Agents` is the whole of Turbo Python's contribution to the feature. The example agent is `docker agent serve acp .turbo-python/agent.yaml`; the only other thing about this editor in it is the sentence saying a ```python fence is coloured by the scanner this editor colours its own files with. Every other editor got agent windows the same way — one file, one line. The reasoning, and why it could not have been built here, is in `docs/*/explanation/agent-windows.md`. | |
| 96 | +- **The starter agents file teaches the window's keyboard as well as the format.** `Enter`, `Alt-Enter`, `Tab`, `Esc`, `Ctrl-W` and the copying keys are all in its comments, because a file the editor hands you is the one document a user is guaranteed to see. | |
| 97 | + | |
| 98 | +## State as of 2026-09-03 | |
| 99 | + | |
| 100 | +- **Complete and green.** `go test ./...` passes; `gofmt -l` and `go vet` are clean. | |
| 101 | +- **Quality gate: PASS.** 0 errors, 0 warnings, 0 smells; total complexity 91. | |
| 102 | +- **Documentation**: 33 files × EN + FR (32 pages plus each language's README), a `README.md` at the root, and | |
| 103 | + `docs/diagrams/packages.drawio` checked against `go list` by `diagram_test.go`. | |
| 104 | +- **Verified in a real pty**, not only by tests: the Python menu under `Alt-P` with | |
| 105 | + `Create tools file` available (`30;42`) and `Open tools file` greyed (`90;47`); `def` | |
| 106 | + `97;44;1`, a called name `93;44;1`, `print` `96;44;1`, strings `92;44`, comments | |
| 107 | + `38;2;143;143;143`; a triple-quoted f-string carried across a line break; the About box | |
| 108 | + reading **"A Turbo C-style editor for Python, / written in Go."**; `Ctrl-Y` deleting a | |
| 109 | + line; the theme dialog opening on the current theme; and — the one that matters — | |
| 110 | + **a file that does not parse, opened by a relative path, showing `×` in the gutter and | |
| 111 | + `⚠ invalid syntax` on the status bar**, which is the failure mode Turbo Go shipped with | |
| 112 | + for months. | |
| 113 | +- **The server is found outside `PATH`.** Verified by running the binary with `PATH` | |
| 114 | + stripped to `/usr/bin:/bin`: it still said `LSP: ready`, from `~/.local/bin`. With `HOME` | |
| 115 | + moved too it says `LSP: no pylsp — pipx install "python-lsp-server[all]"`. | |
| 116 | +- **The editor is registered in the family.** turbo-core's `README.md`, both doc `README`s, | |
| 117 | + `profile/profile.go`'s package comment, the release and workspace how-tos in both | |
| 118 | + languages, both architecture explanations and `.memory/summary.md` now count three | |
| 119 | + editors. turbo-core's `.go` strings were swept for hardcoded language names; every hit was | |
| 120 | + a false positive, a doc-comment example, or a true statement about the implementation. | |
| 121 | +- **Released as `v0.1.0`**, tagged and pushed at `bccbb0b` on `main`, working tree clean. | |
| 122 | + turbo-core was tagged `v0.4.1` the same day — a docs-and-comment release, no behaviour | |
| 123 | + change — and all three editors now pin it. | |
| 124 | + | |
| 125 | +## Not yet established | |
| 126 | + | |
| 127 | +- **Agent windows have never been opened in this editor.** The feature is turbo-core's and was driven end to end from turbo-go against a real `docker agent` and a real llama.cpp; what is here is the starter file, covered by tests that create it, load it back and check it names this editor's own language. Nobody has run `turbo-python`, pressed `Alt-A` and talked to an agent from it. | |
| 128 | + | |
| 129 | + | |
| 130 | +- **Never run on macOS or Windows.** Everything here was verified on Linux. The user's | |
| 131 | + machine is macOS, so a binary built in this sandbox is an ELF they cannot run. | |
| 132 | +- **No CI.** There is no pipeline configuration in the repository. | |
| 133 | +- **The release scripts have never been run from this sandbox.** `v0.1.0` exists, tagged by the user; `01`–`04` have only ever been read here. | |
| 134 | +- **Performance on a large file is unmeasured.** The scanner is a line at a time and carries | |
| 135 | + three pieces of state, but nothing has been timed. | |
| 136 | +- **Only pylsp has been tried.** pyright and ruff-lsp would both fit the profile; neither | |
| 137 | + has been pointed at. | |
| 138 | + | |
| 139 | +## State as of 2026-09-19 — moved to Rickub, released by a workflow | |
| 140 | + | |
| 141 | +- **Module path `rickub.com/turbo-editors/turbo-python`**, depending on `rickub.com/turbo-editors/turbo-core v1.0.0` — the first turbo-core version published under that path (`v0.9.0` on the proxy still declares the Codeberg path and cannot be required as `rickub.com/…`). Every import, the Makefile's `VERSION_PKG`, `scripts/install.sh`, the README and the docs say `rickub.com`. `GOWORK=off make check` green. The repository on this side is a fresh `git init` with `origin` at `ssh://git@rickub.com/turbo-editors/turbo-python.git` and **no commit yet**; `01-release.tag.sh` makes the first one. | |
| 142 | +- **Releases are one script and one workflow**, modelled on turbo-core's and identical to turbo-go's. `01-release.tag.sh` runs `make check` under `TURBO_PYTHON_RELEASING=1`, refuses a tag taken locally or on origin (bump, never move), refuses a `replace` in `go.mod`, commits, pushes the current branch, then tags and pushes the tag. That push starts `.github/workflows/release.yml`: `go test` with `TURBO_PYTHON_RELEASING=1`, `./02-build-releases.sh "${GITHUB_REF_NAME}"`, release notes from the tag message, a run artifact, then `softprops/action-gh-release@v2` attaching `turbo-python-*`, `SHA256SUMS` and `README.md` with the job's own `GITHUB_TOKEN` — the only credential Rickub's release API accepts. **`02-release.publish.sh` and `04-release.upload-binaries.sh` are gone**; the build script is now `02-build-releases.sh`, takes the tag as `$1` (CI has no `release.env`), validates it, refuses a `replace`, and starts from an empty `release/${TAG}/`. `release.env` holds only `TAG` and `ABOUT`; `turbo-python.token.env` is read by nothing. | |
| 143 | +- **`release_test.go`** runs `01` for real against a throwaway bare remote (publishes, then refuses the same tag), runs `02` alone to see it refuse `v0.o.0`, and asserts the workflow's trigger, `contents: write`, `./02-build-releases.sh`, `fail_on_unmatched_files`, docs linked at the tag, no `secrets.`, and `TURBO_PYTHON_RELEASING`. The copy of the module for the clone leaves out `.git`, `bin`, `release`, `kits`, `demo`, `demos`, `*.env` and `go.work*`; children run with `GOWORK=off`. | |
| new file mode 100644 | |||
| @@ -0,0 +1,143 @@ | |||
| 1 | +# turbo-python — summary | ||
| 2 | + | ||
| 3 | +A snapshot of the present. Edited in place; the history is in `history.md`. | ||
| 4 | + | ||
| 5 | +## What this is | ||
| 6 | + | ||
| 7 | +A Turbo C-style terminal IDE for Python, written in Go, built on | ||
| 8 | +**[turbo-core](https://rickub.com/turbo-editors/turbo-core)** — the library Turbo Go and | ||
| 9 | +Turbo Rust already share. This repository holds the command, the profile that says the | ||
| 10 | +editor is for Python, and the Python scanner. Everything else — the event loop, the | ||
| 11 | +windows, the dialogs, the themes, the LSP client, the terminal emulator, the project tree, | ||
| 12 | +the snippets and tools machinery — is the library's, and none of it is copied here. | ||
| 13 | + | ||
| 14 | +Module `rickub.com/turbo-editors/turbo-python`, `require`ing turbo-core **v0.4.1** from | ||
| 15 | +the module proxy with **no active `replace`**. The commented-out `replace` at the bottom of | ||
| 16 | +`go.mod` documents the escape hatch without being one; `01-release.tag.sh` refuses to tag a | ||
| 17 | +release whose `go.mod` carries a live one. | ||
| 18 | + | ||
| 19 | +## Layout | ||
| 20 | + | ||
| 21 | +| | | | ||
| 22 | +| --- | --- | | ||
| 23 | +| `main.go` | flags, the terminal, `pythonlang.Register()`, the profile, the loop | | ||
| 24 | +| `internal/pythonlang/pythonlang.go` | `Name`, `Slug`, `Language`, `Profile()`, `Register()`, the four server directories | | ||
| 25 | +| `internal/pythonlang/scan.go` | the scanner's dispatcher, comments, decorators | | ||
| 26 | +| `internal/pythonlang/literals.go` | strings — all six prefixes, both triple quotes, line continuations | | ||
| 27 | +| `internal/pythonlang/words.go` | numbers, keywords, soft keywords, the name-shape rules | | ||
| 28 | +| `internal/pythonlang/*.toml.tmpl` | the three starter files, embedded by `templates.go` | | ||
| 29 | +| `diagram_test.go` | holds `docs/diagrams/packages.drawio` to `go list` | | ||
| 30 | +| `docs/{en,fr}/` | 33 pages each (README included), Diátaxis | | ||
| 31 | + | ||
| 32 | +## How to build, test and measure | ||
| 33 | + | ||
| 34 | +```bash | ||
| 35 | +make check # fmt, vet, then the whole suite — what a commit should pass | ||
| 36 | +make build # into bin/turbo-python, then check the binary reports its version | ||
| 37 | +make install # build, install onto PATH, report what it found | ||
| 38 | +go test ./... # 129 tests; the pylsp ones skip themselves without a server | ||
| 39 | +``` | ||
| 40 | + | ||
| 41 | +Quality gate, separate from the tests: | ||
| 42 | + | ||
| 43 | +```bash | ||
| 44 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | ||
| 45 | +``` | ||
| 46 | + | ||
| 47 | +To build against a turbo-core you have changed but not released: | ||
| 48 | + | ||
| 49 | +```bash | ||
| 50 | +go work init . ../turbo-core | ||
| 51 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app # must NOT be under pkg/mod | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +`go.work` and `go.work.sum` are gitignored. **Everything still builds and still passes** | ||
| 55 | +while testing the published library instead of your changes, so run that second line. | ||
| 56 | + | ||
| 57 | +## Decisions in force | ||
| 58 | + | ||
| 59 | +- **The toolchain menu is `~P~ython`, not `uv`.** `P` is free — the fixed menus take F, E, | ||
| 60 | + S, R, C, O, W, N and H. Named after the language because the menu holds whatever the | ||
| 61 | + project put in its tools file, and a menu called `uv` holding `docker compose up` is a lie | ||
| 62 | + about what the menu is. | ||
| 63 | +- **The language server is `pylsp`, and the install hint says `pipx install | ||
| 64 | + "python-lsp-server[all]"`.** The `[all]` is load-bearing: installed bare, pylsp starts, | ||
| 65 | + completes and jumps, and publishes an **empty** diagnostics list for a file that does not | ||
| 66 | + parse, because the linters are extras. A gutter blank for want of a linter looks exactly | ||
| 67 | + like a gutter blank for want of a bug. | ||
| 68 | +- **pylsp answers seven of turbo-core's nine questions.** It advertises neither | ||
| 69 | + `implementation` nor `workspace/symbol`, so those two items report nothing found. That is | ||
| 70 | + documented rather than worked around, and a test asserts it so a future pylsp gaining them | ||
| 71 | + is noticed. | ||
| 72 | +- **`Profile()` is a function, not a variable**, because `Server.Dirs` reads the | ||
| 73 | + environment, and a variable would freeze whatever `VIRTUAL_ENV` said at link time — for a | ||
| 74 | + Python tool, the one value most likely to change between two runs in the same shell. | ||
| 75 | +- **Four places are searched for the server besides `PATH`**: the active virtual | ||
| 76 | + environment's `bin`, `~/.local/bin`, pyenv's shims, and every | ||
| 77 | + `~/Library/Python/<version>/bin` that exists. The last is read rather than guessed, and is | ||
| 78 | + on nobody's `PATH` on macOS. | ||
| 79 | +- **Root markers, in order: `pyproject.toml`, `setup.py`, `setup.cfg`.** | ||
| 80 | +- **A name wholly in capitals is a constant; any other capitalised name is a type.** Turbo | ||
| 81 | + Rust has only the second rule and documents `SCREAMING_SNAKE_CASE` as a known wrong | ||
| 82 | + answer; PEP 8 separates the two conventions well enough that the wrong answer was worth | ||
| 83 | + removing rather than inheriting. The cost is a class named `HTTP`. | ||
| 84 | +- **A capitalised name is a type even when it is called.** `ValueError("nope")` and | ||
| 85 | + `parse("nope")` are the same shape. This is the one rule Turbo Python and Turbo Rust order | ||
| 86 | + differently, on purpose. | ||
| 87 | +- **`self` and `cls` are coloured as builtins** although the language does not name them. | ||
| 88 | +- **An f-string is one string span**, `{…}` included. Finding where an expression ends | ||
| 89 | + inside a literal needs a parser; this is a scanner. | ||
| 90 | +- **The starter templates are embedded files, not Go constants**, with the `.tmpl` suffix | ||
| 91 | + because `settings.toml.tmpl` holds `theme = %q`, which is not valid TOML. | ||
| 92 | +- **`autosave = true` in the starter settings file, `false` in `settings.Default()`.** Two | ||
| 93 | + statements in two places on purpose: a project that created a settings file has said what | ||
| 94 | + it wants; a directory somebody merely started the editor in has not. | ||
| 95 | +- **Agent windows are turbo-core's, and what belongs here is the starter file.** `acp.toml.tmpl` is the fourth embedded template, and `profile.Templates.Agents` is the whole of Turbo Python's contribution to the feature. The example agent is `docker agent serve acp .turbo-python/agent.yaml`; the only other thing about this editor in it is the sentence saying a ```python fence is coloured by the scanner this editor colours its own files with. Every other editor got agent windows the same way — one file, one line. The reasoning, and why it could not have been built here, is in `docs/*/explanation/agent-windows.md`. | ||
| 96 | +- **The starter agents file teaches the window's keyboard as well as the format.** `Enter`, `Alt-Enter`, `Tab`, `Esc`, `Ctrl-W` and the copying keys are all in its comments, because a file the editor hands you is the one document a user is guaranteed to see. | ||
| 97 | + | ||
| 98 | +## State as of 2026-09-03 | ||
| 99 | + | ||
| 100 | +- **Complete and green.** `go test ./...` passes; `gofmt -l` and `go vet` are clean. | ||
| 101 | +- **Quality gate: PASS.** 0 errors, 0 warnings, 0 smells; total complexity 91. | ||
| 102 | +- **Documentation**: 33 files × EN + FR (32 pages plus each language's README), a `README.md` at the root, and | ||
| 103 | + `docs/diagrams/packages.drawio` checked against `go list` by `diagram_test.go`. | ||
| 104 | +- **Verified in a real pty**, not only by tests: the Python menu under `Alt-P` with | ||
| 105 | + `Create tools file` available (`30;42`) and `Open tools file` greyed (`90;47`); `def` | ||
| 106 | + `97;44;1`, a called name `93;44;1`, `print` `96;44;1`, strings `92;44`, comments | ||
| 107 | + `38;2;143;143;143`; a triple-quoted f-string carried across a line break; the About box | ||
| 108 | + reading **"A Turbo C-style editor for Python, / written in Go."**; `Ctrl-Y` deleting a | ||
| 109 | + line; the theme dialog opening on the current theme; and — the one that matters — | ||
| 110 | + **a file that does not parse, opened by a relative path, showing `×` in the gutter and | ||
| 111 | + `⚠ invalid syntax` on the status bar**, which is the failure mode Turbo Go shipped with | ||
| 112 | + for months. | ||
| 113 | +- **The server is found outside `PATH`.** Verified by running the binary with `PATH` | ||
| 114 | + stripped to `/usr/bin:/bin`: it still said `LSP: ready`, from `~/.local/bin`. With `HOME` | ||
| 115 | + moved too it says `LSP: no pylsp — pipx install "python-lsp-server[all]"`. | ||
| 116 | +- **The editor is registered in the family.** turbo-core's `README.md`, both doc `README`s, | ||
| 117 | + `profile/profile.go`'s package comment, the release and workspace how-tos in both | ||
| 118 | + languages, both architecture explanations and `.memory/summary.md` now count three | ||
| 119 | + editors. turbo-core's `.go` strings were swept for hardcoded language names; every hit was | ||
| 120 | + a false positive, a doc-comment example, or a true statement about the implementation. | ||
| 121 | +- **Released as `v0.1.0`**, tagged and pushed at `bccbb0b` on `main`, working tree clean. | ||
| 122 | + turbo-core was tagged `v0.4.1` the same day — a docs-and-comment release, no behaviour | ||
| 123 | + change — and all three editors now pin it. | ||
| 124 | + | ||
| 125 | +## Not yet established | ||
| 126 | + | ||
| 127 | +- **Agent windows have never been opened in this editor.** The feature is turbo-core's and was driven end to end from turbo-go against a real `docker agent` and a real llama.cpp; what is here is the starter file, covered by tests that create it, load it back and check it names this editor's own language. Nobody has run `turbo-python`, pressed `Alt-A` and talked to an agent from it. | ||
| 128 | + | ||
| 129 | + | ||
| 130 | +- **Never run on macOS or Windows.** Everything here was verified on Linux. The user's | ||
| 131 | + machine is macOS, so a binary built in this sandbox is an ELF they cannot run. | ||
| 132 | +- **No CI.** There is no pipeline configuration in the repository. | ||
| 133 | +- **The release scripts have never been run from this sandbox.** `v0.1.0` exists, tagged by the user; `01`–`04` have only ever been read here. | ||
| 134 | +- **Performance on a large file is unmeasured.** The scanner is a line at a time and carries | ||
| 135 | + three pieces of state, but nothing has been timed. | ||
| 136 | +- **Only pylsp has been tried.** pyright and ruff-lsp would both fit the profile; neither | ||
| 137 | + has been pointed at. | ||
| 138 | + | ||
| 139 | +## State as of 2026-09-19 — moved to Rickub, released by a workflow | ||
| 140 | + | ||
| 141 | +- **Module path `rickub.com/turbo-editors/turbo-python`**, depending on `rickub.com/turbo-editors/turbo-core v1.0.0` — the first turbo-core version published under that path (`v0.9.0` on the proxy still declares the Codeberg path and cannot be required as `rickub.com/…`). Every import, the Makefile's `VERSION_PKG`, `scripts/install.sh`, the README and the docs say `rickub.com`. `GOWORK=off make check` green. The repository on this side is a fresh `git init` with `origin` at `ssh://git@rickub.com/turbo-editors/turbo-python.git` and **no commit yet**; `01-release.tag.sh` makes the first one. | ||
| 142 | +- **Releases are one script and one workflow**, modelled on turbo-core's and identical to turbo-go's. `01-release.tag.sh` runs `make check` under `TURBO_PYTHON_RELEASING=1`, refuses a tag taken locally or on origin (bump, never move), refuses a `replace` in `go.mod`, commits, pushes the current branch, then tags and pushes the tag. That push starts `.github/workflows/release.yml`: `go test` with `TURBO_PYTHON_RELEASING=1`, `./02-build-releases.sh "${GITHUB_REF_NAME}"`, release notes from the tag message, a run artifact, then `softprops/action-gh-release@v2` attaching `turbo-python-*`, `SHA256SUMS` and `README.md` with the job's own `GITHUB_TOKEN` — the only credential Rickub's release API accepts. **`02-release.publish.sh` and `04-release.upload-binaries.sh` are gone**; the build script is now `02-build-releases.sh`, takes the tag as `$1` (CI has no `release.env`), validates it, refuses a `replace`, and starts from an empty `release/${TAG}/`. `release.env` holds only `TAG` and `ABOUT`; `turbo-python.token.env` is read by nothing. | ||
| 143 | +- **`release_test.go`** runs `01` for real against a throwaway bare remote (publishes, then refuses the same tag), runs `02` alone to see it refuse `v0.o.0`, and asserts the workflow's trigger, `contents: write`, `./02-build-releases.sh`, `fail_on_unmatched_files`, docs linked at the tag, no `secrets.`, and `TURBO_PYTHON_RELEASING`. The copy of the module for the clone leaves out `.git`, `bin`, `release`, `kits`, `demo`, `demos`, `*.env` and `go.work*`; children run with `GOWORK=off`. | ||
added
.qlty/.gitignore +7 -0 | new file mode 100644 | ||
| @@ -0,0 +1,7 @@ | ||
| 1 | +* | |
| 2 | +!configs | |
| 3 | +!configs/** | |
| 4 | +!hooks | |
| 5 | +!hooks/** | |
| 6 | +!qlty.toml | |
| 7 | +!.gitignore | |
| new file mode 100644 | |||
| @@ -0,0 +1,7 @@ | |||
| 1 | +* | ||
| 2 | +!configs | ||
| 3 | +!configs/** | ||
| 4 | +!hooks | ||
| 5 | +!hooks/** | ||
| 6 | +!qlty.toml | ||
| 7 | +!.gitignore | ||
added
.qlty/qlty.toml +65 -0 | new file mode 100644 | ||
| @@ -0,0 +1,65 @@ | ||
| 1 | +# This file was automatically generated by `qlty init`. | |
| 2 | +# You can modify it to suit your needs. | |
| 3 | +# We recommend you to commit this file to your repository. | |
| 4 | +# | |
| 5 | +# This configuration is used by both Qlty CLI and Qlty Cloud. | |
| 6 | +# | |
| 7 | +# Qlty CLI -- Code quality toolkit for developers | |
| 8 | +# Qlty Cloud -- Fully automated Code Health Platform | |
| 9 | +# | |
| 10 | +# Try Qlty Cloud: https://qlty.sh | |
| 11 | +# | |
| 12 | +# For a guide to configuration, visit https://qlty.sh/d/config | |
| 13 | +# Or for a full reference, visit https://qlty.sh/d/qlty-toml | |
| 14 | +config_version = "0" | |
| 15 | + | |
| 16 | +exclude_patterns = [ | |
| 17 | + "*_min.*", | |
| 18 | + "*-min.*", | |
| 19 | + "*.min.*", | |
| 20 | + "**/.yarn/**", | |
| 21 | + "**/*.d.ts", | |
| 22 | + "**/assets/**", | |
| 23 | + "**/bower_components/**", | |
| 24 | + "**/build/**", | |
| 25 | + "**/cache/**", | |
| 26 | + "**/config/**", | |
| 27 | + "**/db/**", | |
| 28 | + "**/deps/**", | |
| 29 | + "**/dist/**", | |
| 30 | + "**/extern/**", | |
| 31 | + "**/external/**", | |
| 32 | + "**/generated/**", | |
| 33 | + "**/Godeps/**", | |
| 34 | + "**/gradlew/**", | |
| 35 | + "**/mvnw/**", | |
| 36 | + "**/node_modules/**", | |
| 37 | + "**/protos/**", | |
| 38 | + "**/seed/**", | |
| 39 | + "**/target/**", | |
| 40 | + "**/templates/**", | |
| 41 | + "**/testdata/**", | |
| 42 | + "**/vendor/**", | |
| 43 | +] | |
| 44 | + | |
| 45 | +test_patterns = [ | |
| 46 | + "**/test/**", | |
| 47 | + "**/spec/**", | |
| 48 | + "**/*.test.*", | |
| 49 | + "**/*.spec.*", | |
| 50 | + "**/*_test.*", | |
| 51 | + "**/*_spec.*", | |
| 52 | + "**/test_*.*", | |
| 53 | + "**/spec_*.*", | |
| 54 | +] | |
| 55 | + | |
| 56 | +[smells] | |
| 57 | +mode = "comment" | |
| 58 | + | |
| 59 | +[[source]] | |
| 60 | +name = "default" | |
| 61 | +default = true | |
| 62 | + | |
| 63 | + | |
| 64 | +[[plugin]] | |
| 65 | +name = "trufflehog" | |
| new file mode 100644 | |||
| @@ -0,0 +1,65 @@ | |||
| 1 | +# This file was automatically generated by `qlty init`. | ||
| 2 | +# You can modify it to suit your needs. | ||
| 3 | +# We recommend you to commit this file to your repository. | ||
| 4 | +# | ||
| 5 | +# This configuration is used by both Qlty CLI and Qlty Cloud. | ||
| 6 | +# | ||
| 7 | +# Qlty CLI -- Code quality toolkit for developers | ||
| 8 | +# Qlty Cloud -- Fully automated Code Health Platform | ||
| 9 | +# | ||
| 10 | +# Try Qlty Cloud: https://qlty.sh | ||
| 11 | +# | ||
| 12 | +# For a guide to configuration, visit https://qlty.sh/d/config | ||
| 13 | +# Or for a full reference, visit https://qlty.sh/d/qlty-toml | ||
| 14 | +config_version = "0" | ||
| 15 | + | ||
| 16 | +exclude_patterns = [ | ||
| 17 | + "*_min.*", | ||
| 18 | + "*-min.*", | ||
| 19 | + "*.min.*", | ||
| 20 | + "**/.yarn/**", | ||
| 21 | + "**/*.d.ts", | ||
| 22 | + "**/assets/**", | ||
| 23 | + "**/bower_components/**", | ||
| 24 | + "**/build/**", | ||
| 25 | + "**/cache/**", | ||
| 26 | + "**/config/**", | ||
| 27 | + "**/db/**", | ||
| 28 | + "**/deps/**", | ||
| 29 | + "**/dist/**", | ||
| 30 | + "**/extern/**", | ||
| 31 | + "**/external/**", | ||
| 32 | + "**/generated/**", | ||
| 33 | + "**/Godeps/**", | ||
| 34 | + "**/gradlew/**", | ||
| 35 | + "**/mvnw/**", | ||
| 36 | + "**/node_modules/**", | ||
| 37 | + "**/protos/**", | ||
| 38 | + "**/seed/**", | ||
| 39 | + "**/target/**", | ||
| 40 | + "**/templates/**", | ||
| 41 | + "**/testdata/**", | ||
| 42 | + "**/vendor/**", | ||
| 43 | +] | ||
| 44 | + | ||
| 45 | +test_patterns = [ | ||
| 46 | + "**/test/**", | ||
| 47 | + "**/spec/**", | ||
| 48 | + "**/*.test.*", | ||
| 49 | + "**/*.spec.*", | ||
| 50 | + "**/*_test.*", | ||
| 51 | + "**/*_spec.*", | ||
| 52 | + "**/test_*.*", | ||
| 53 | + "**/spec_*.*", | ||
| 54 | +] | ||
| 55 | + | ||
| 56 | +[smells] | ||
| 57 | +mode = "comment" | ||
| 58 | + | ||
| 59 | +[[source]] | ||
| 60 | +name = "default" | ||
| 61 | +default = true | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +[[plugin]] | ||
| 65 | +name = "trufflehog" | ||
added
.quality/history.jsonl +4 -0 | new file mode 100644 | ||
| @@ -0,0 +1,4 @@ | ||
| 1 | +{"branch": "main", "breaches": ["code smells: 1 (max 0)"], "commit": "efb533c", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 2, "complex": 91, "cyclo": 186, "fields": 8, "funcs": 42, "lcom": 0, "lines": 1025, "loc": 521}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 1, "smells": 1, "timestamp": "2026-09-03T05:03:05Z"} | |
| 2 | +{"branch": "main", "breaches": [], "commit": "efb533c", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 91, "cyclo": 185, "fields": 10, "funcs": 42, "lcom": 0, "lines": 1036, "loc": 525}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 2, "smells": 0, "timestamp": "2026-09-03T05:03:25Z"} | |
| 3 | +{"branch": "main", "breaches": [], "commit": "efb533c", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 91, "cyclo": 185, "fields": 10, "funcs": 42, "lcom": 0, "lines": 1036, "loc": 525}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 3, "smells": 0, "timestamp": "2026-09-03T05:33:53Z"} | |
| 4 | +{"branch": "feature/acp", "breaches": [], "commit": "38eb724", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 91, "cyclo": 185, "fields": 10, "funcs": 42, "lcom": 0, "lines": 1046, "loc": 527}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 4, "smells": 0, "timestamp": "2026-09-15T16:54:11Z"} | |
| new file mode 100644 | |||
| @@ -0,0 +1,4 @@ | |||
| 1 | +{"branch": "main", "breaches": ["code smells: 1 (max 0)"], "commit": "efb533c", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 2, "complex": 91, "cyclo": 186, "fields": 8, "funcs": 42, "lcom": 0, "lines": 1025, "loc": 521}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 1, "smells": 1, "timestamp": "2026-09-03T05:03:05Z"} | ||
| 2 | +{"branch": "main", "breaches": [], "commit": "efb533c", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 91, "cyclo": 185, "fields": 10, "funcs": 42, "lcom": 0, "lines": 1036, "loc": 525}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 2, "smells": 0, "timestamp": "2026-09-03T05:03:25Z"} | ||
| 3 | +{"branch": "main", "breaches": [], "commit": "efb533c", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 91, "cyclo": 185, "fields": 10, "funcs": 42, "lcom": 0, "lines": 1036, "loc": 525}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 3, "smells": 0, "timestamp": "2026-09-03T05:33:53Z"} | ||
| 4 | +{"branch": "feature/acp", "breaches": [], "commit": "38eb724", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 91, "cyclo": 185, "fields": 10, "funcs": 42, "lcom": 0, "lines": 1046, "loc": 527}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 4, "smells": 0, "timestamp": "2026-09-15T16:54:11Z"} | ||
added
.quality/report-20260903T050305Z.md +60 -0 | new file mode 100644 | ||
| @@ -0,0 +1,60 @@ | ||
| 1 | +# Quality report — 2026-09-03T05:03:05Z | |
| 2 | + | |
| 3 | +- **Gate**: ❌ **FAIL** | |
| 4 | +- **Commit**: `efb533c` on `main` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #1 (first recorded run) | |
| 7 | + | |
| 8 | +## Gate violations | |
| 9 | + | |
| 10 | +- code smells: 1 (max 0) | |
| 11 | + | |
| 12 | +## Lint issues (`qlty check`) | |
| 13 | + | |
| 14 | +_none_ | |
| 15 | + | |
| 16 | +### Top rules | |
| 17 | + | |
| 18 | +_none_ | |
| 19 | + | |
| 20 | +### Most affected files | |
| 21 | + | |
| 22 | +_none_ | |
| 23 | + | |
| 24 | +## Code smells (`qlty smells`) | |
| 25 | + | |
| 26 | +Total: **1** (vs previous: —) | |
| 27 | + | |
| 28 | +| smell | file | line | detail | | |
| 29 | +|---|---|---|---| | |
| 30 | +| qlty:return-statements | internal/pythonlang/words.go | 105 | Function with many returns (count = 6): classOfWord | | |
| 31 | + | |
| 32 | +## Metrics (`qlty metrics`) | |
| 33 | + | |
| 34 | +| metric | total | vs previous | | |
| 35 | +|---|---|---| | |
| 36 | +| funcs | 42 | — | | |
| 37 | +| classes | 2 | — | | |
| 38 | +| fields | 8 | — | | |
| 39 | +| cyclo | 186 | — | | |
| 40 | +| complex | 91 | — | | |
| 41 | +| lcom | 0 | — | | |
| 42 | +| lines | 1025 | — | | |
| 43 | +| loc | 521 | — | | |
| 44 | + | |
| 45 | +### Most complex files | |
| 46 | + | |
| 47 | +| file | complex | cyclo | loc | | |
| 48 | +|---|---|---|---| | |
| 49 | +| internal/pythonlang/words.go | 33 | 64 | 136 | | |
| 50 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | |
| 51 | +| main.go | 16 | 32 | 132 | | |
| 52 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | |
| 53 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 90 | | |
| 54 | +| internal/pythonlang/templates.go | 0 | 1 | 5 | | |
| 55 | + | |
| 56 | +## Trend | |
| 57 | + | |
| 58 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 59 | +|---|---|---|---|---|---|---| | |
| 60 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | |
| new file mode 100644 | |||
| @@ -0,0 +1,60 @@ | |||
| 1 | +# Quality report — 2026-09-03T05:03:05Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ❌ **FAIL** | ||
| 4 | +- **Commit**: `efb533c` on `main` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #1 (first recorded run) | ||
| 7 | + | ||
| 8 | +## Gate violations | ||
| 9 | + | ||
| 10 | +- code smells: 1 (max 0) | ||
| 11 | + | ||
| 12 | +## Lint issues (`qlty check`) | ||
| 13 | + | ||
| 14 | +_none_ | ||
| 15 | + | ||
| 16 | +### Top rules | ||
| 17 | + | ||
| 18 | +_none_ | ||
| 19 | + | ||
| 20 | +### Most affected files | ||
| 21 | + | ||
| 22 | +_none_ | ||
| 23 | + | ||
| 24 | +## Code smells (`qlty smells`) | ||
| 25 | + | ||
| 26 | +Total: **1** (vs previous: —) | ||
| 27 | + | ||
| 28 | +| smell | file | line | detail | | ||
| 29 | +|---|---|---|---| | ||
| 30 | +| qlty:return-statements | internal/pythonlang/words.go | 105 | Function with many returns (count = 6): classOfWord | | ||
| 31 | + | ||
| 32 | +## Metrics (`qlty metrics`) | ||
| 33 | + | ||
| 34 | +| metric | total | vs previous | | ||
| 35 | +|---|---|---| | ||
| 36 | +| funcs | 42 | — | | ||
| 37 | +| classes | 2 | — | | ||
| 38 | +| fields | 8 | — | | ||
| 39 | +| cyclo | 186 | — | | ||
| 40 | +| complex | 91 | — | | ||
| 41 | +| lcom | 0 | — | | ||
| 42 | +| lines | 1025 | — | | ||
| 43 | +| loc | 521 | — | | ||
| 44 | + | ||
| 45 | +### Most complex files | ||
| 46 | + | ||
| 47 | +| file | complex | cyclo | loc | | ||
| 48 | +|---|---|---|---| | ||
| 49 | +| internal/pythonlang/words.go | 33 | 64 | 136 | | ||
| 50 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | ||
| 51 | +| main.go | 16 | 32 | 132 | | ||
| 52 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | ||
| 53 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 90 | | ||
| 54 | +| internal/pythonlang/templates.go | 0 | 1 | 5 | | ||
| 55 | + | ||
| 56 | +## Trend | ||
| 57 | + | ||
| 58 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 59 | +|---|---|---|---|---|---|---| | ||
| 60 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | ||
added
.quality/report-20260903T050325Z.md +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +# Quality report — 2026-09-03T05:03:25Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `efb533c` on `main` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #2 (previous: 2026-09-03T05:03:05Z) | |
| 7 | + | |
| 8 | +## Lint issues (`qlty check`) | |
| 9 | + | |
| 10 | +_none_ | |
| 11 | + | |
| 12 | +### Top rules | |
| 13 | + | |
| 14 | +_none_ | |
| 15 | + | |
| 16 | +### Most affected files | |
| 17 | + | |
| 18 | +_none_ | |
| 19 | + | |
| 20 | +## Code smells (`qlty smells`) | |
| 21 | + | |
| 22 | +Total: **0** (vs previous: -1) | |
| 23 | + | |
| 24 | +_none_ | |
| 25 | + | |
| 26 | +## Metrics (`qlty metrics`) | |
| 27 | + | |
| 28 | +| metric | total | vs previous | | |
| 29 | +|---|---|---| | |
| 30 | +| funcs | 42 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 10 | +2 | | |
| 33 | +| cyclo | 185 | -1 | | |
| 34 | +| complex | 91 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1036 | +11 | | |
| 37 | +| loc | 525 | +4 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | |
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | |
| 45 | +| main.go | 16 | 32 | 132 | | |
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | |
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 90 | | |
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 5 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | |
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +# Quality report — 2026-09-03T05:03:25Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `efb533c` on `main` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #2 (previous: 2026-09-03T05:03:05Z) | ||
| 7 | + | ||
| 8 | +## Lint issues (`qlty check`) | ||
| 9 | + | ||
| 10 | +_none_ | ||
| 11 | + | ||
| 12 | +### Top rules | ||
| 13 | + | ||
| 14 | +_none_ | ||
| 15 | + | ||
| 16 | +### Most affected files | ||
| 17 | + | ||
| 18 | +_none_ | ||
| 19 | + | ||
| 20 | +## Code smells (`qlty smells`) | ||
| 21 | + | ||
| 22 | +Total: **0** (vs previous: -1) | ||
| 23 | + | ||
| 24 | +_none_ | ||
| 25 | + | ||
| 26 | +## Metrics (`qlty metrics`) | ||
| 27 | + | ||
| 28 | +| metric | total | vs previous | | ||
| 29 | +|---|---|---| | ||
| 30 | +| funcs | 42 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 10 | +2 | | ||
| 33 | +| cyclo | 185 | -1 | | ||
| 34 | +| complex | 91 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1036 | +11 | | ||
| 37 | +| loc | 525 | +4 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | ||
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | ||
| 45 | +| main.go | 16 | 32 | 132 | | ||
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | ||
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 90 | | ||
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 5 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | ||
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | ||
added
.quality/report-20260903T053353Z.md +56 -0 | new file mode 100644 | ||
| @@ -0,0 +1,56 @@ | ||
| 1 | +# Quality report — 2026-09-03T05:33:53Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `efb533c` on `main` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #3 (previous: 2026-09-03T05:03:25Z) | |
| 7 | + | |
| 8 | +## Lint issues (`qlty check`) | |
| 9 | + | |
| 10 | +_none_ | |
| 11 | + | |
| 12 | +### Top rules | |
| 13 | + | |
| 14 | +_none_ | |
| 15 | + | |
| 16 | +### Most affected files | |
| 17 | + | |
| 18 | +_none_ | |
| 19 | + | |
| 20 | +## Code smells (`qlty smells`) | |
| 21 | + | |
| 22 | +Total: **0** (vs previous: ±0) | |
| 23 | + | |
| 24 | +_none_ | |
| 25 | + | |
| 26 | +## Metrics (`qlty metrics`) | |
| 27 | + | |
| 28 | +| metric | total | vs previous | | |
| 29 | +|---|---|---| | |
| 30 | +| funcs | 42 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 10 | ±0 | | |
| 33 | +| cyclo | 185 | ±0 | | |
| 34 | +| complex | 91 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1036 | ±0 | | |
| 37 | +| loc | 525 | ±0 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | |
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | |
| 45 | +| main.go | 16 | 32 | 132 | | |
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | |
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 90 | | |
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 5 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | |
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | |
| 56 | +| 3 | 2026-09-03T05:33:53Z | 0 | 0 | 0 | 91 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,56 @@ | |||
| 1 | +# Quality report — 2026-09-03T05:33:53Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `efb533c` on `main` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #3 (previous: 2026-09-03T05:03:25Z) | ||
| 7 | + | ||
| 8 | +## Lint issues (`qlty check`) | ||
| 9 | + | ||
| 10 | +_none_ | ||
| 11 | + | ||
| 12 | +### Top rules | ||
| 13 | + | ||
| 14 | +_none_ | ||
| 15 | + | ||
| 16 | +### Most affected files | ||
| 17 | + | ||
| 18 | +_none_ | ||
| 19 | + | ||
| 20 | +## Code smells (`qlty smells`) | ||
| 21 | + | ||
| 22 | +Total: **0** (vs previous: ±0) | ||
| 23 | + | ||
| 24 | +_none_ | ||
| 25 | + | ||
| 26 | +## Metrics (`qlty metrics`) | ||
| 27 | + | ||
| 28 | +| metric | total | vs previous | | ||
| 29 | +|---|---|---| | ||
| 30 | +| funcs | 42 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 10 | ±0 | | ||
| 33 | +| cyclo | 185 | ±0 | | ||
| 34 | +| complex | 91 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1036 | ±0 | | ||
| 37 | +| loc | 525 | ±0 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | ||
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | ||
| 45 | +| main.go | 16 | 32 | 132 | | ||
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | ||
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 90 | | ||
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 5 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | ||
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | ||
| 56 | +| 3 | 2026-09-03T05:33:53Z | 0 | 0 | 0 | 91 | PASS | | ||
added
.quality/report-20260915T165411Z.md +57 -0 | new file mode 100644 | ||
| @@ -0,0 +1,57 @@ | ||
| 1 | +# Quality report — 2026-09-15T16:54:11Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `38eb724` on `feature/acp` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #4 (previous: 2026-09-03T05:33:53Z) | |
| 7 | + | |
| 8 | +## Lint issues (`qlty check`) | |
| 9 | + | |
| 10 | +_none_ | |
| 11 | + | |
| 12 | +### Top rules | |
| 13 | + | |
| 14 | +_none_ | |
| 15 | + | |
| 16 | +### Most affected files | |
| 17 | + | |
| 18 | +_none_ | |
| 19 | + | |
| 20 | +## Code smells (`qlty smells`) | |
| 21 | + | |
| 22 | +Total: **0** (vs previous: ±0) | |
| 23 | + | |
| 24 | +_none_ | |
| 25 | + | |
| 26 | +## Metrics (`qlty metrics`) | |
| 27 | + | |
| 28 | +| metric | total | vs previous | | |
| 29 | +|---|---|---| | |
| 30 | +| funcs | 42 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 10 | ±0 | | |
| 33 | +| cyclo | 185 | ±0 | | |
| 34 | +| complex | 91 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1046 | +10 | | |
| 37 | +| loc | 527 | +2 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | |
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | |
| 45 | +| main.go | 16 | 32 | 132 | | |
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | |
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 91 | | |
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 6 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | |
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | |
| 56 | +| 3 | 2026-09-03T05:33:53Z | 0 | 0 | 0 | 91 | PASS | | |
| 57 | +| 4 | 2026-09-15T16:54:11Z | 0 | 0 | 0 | 91 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | +# Quality report — 2026-09-15T16:54:11Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `38eb724` on `feature/acp` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #4 (previous: 2026-09-03T05:33:53Z) | ||
| 7 | + | ||
| 8 | +## Lint issues (`qlty check`) | ||
| 9 | + | ||
| 10 | +_none_ | ||
| 11 | + | ||
| 12 | +### Top rules | ||
| 13 | + | ||
| 14 | +_none_ | ||
| 15 | + | ||
| 16 | +### Most affected files | ||
| 17 | + | ||
| 18 | +_none_ | ||
| 19 | + | ||
| 20 | +## Code smells (`qlty smells`) | ||
| 21 | + | ||
| 22 | +Total: **0** (vs previous: ±0) | ||
| 23 | + | ||
| 24 | +_none_ | ||
| 25 | + | ||
| 26 | +## Metrics (`qlty metrics`) | ||
| 27 | + | ||
| 28 | +| metric | total | vs previous | | ||
| 29 | +|---|---|---| | ||
| 30 | +| funcs | 42 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 10 | ±0 | | ||
| 33 | +| cyclo | 185 | ±0 | | ||
| 34 | +| complex | 91 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1046 | +10 | | ||
| 37 | +| loc | 527 | +2 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | ||
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | ||
| 45 | +| main.go | 16 | 32 | 132 | | ||
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | ||
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 91 | | ||
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 6 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | ||
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | ||
| 56 | +| 3 | 2026-09-03T05:33:53Z | 0 | 0 | 0 | 91 | PASS | | ||
| 57 | +| 4 | 2026-09-15T16:54:11Z | 0 | 0 | 0 | 91 | PASS | | ||
added
.quality/report-latest.md +57 -0 | new file mode 100644 | ||
| @@ -0,0 +1,57 @@ | ||
| 1 | +# Quality report — 2026-09-15T16:54:11Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `38eb724` on `feature/acp` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #4 (previous: 2026-09-03T05:33:53Z) | |
| 7 | + | |
| 8 | +## Lint issues (`qlty check`) | |
| 9 | + | |
| 10 | +_none_ | |
| 11 | + | |
| 12 | +### Top rules | |
| 13 | + | |
| 14 | +_none_ | |
| 15 | + | |
| 16 | +### Most affected files | |
| 17 | + | |
| 18 | +_none_ | |
| 19 | + | |
| 20 | +## Code smells (`qlty smells`) | |
| 21 | + | |
| 22 | +Total: **0** (vs previous: ±0) | |
| 23 | + | |
| 24 | +_none_ | |
| 25 | + | |
| 26 | +## Metrics (`qlty metrics`) | |
| 27 | + | |
| 28 | +| metric | total | vs previous | | |
| 29 | +|---|---|---| | |
| 30 | +| funcs | 42 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 10 | ±0 | | |
| 33 | +| cyclo | 185 | ±0 | | |
| 34 | +| complex | 91 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1046 | +10 | | |
| 37 | +| loc | 527 | +2 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | |
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | |
| 45 | +| main.go | 16 | 32 | 132 | | |
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | |
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 91 | | |
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 6 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | |
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | |
| 56 | +| 3 | 2026-09-03T05:33:53Z | 0 | 0 | 0 | 91 | PASS | | |
| 57 | +| 4 | 2026-09-15T16:54:11Z | 0 | 0 | 0 | 91 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | +# Quality report — 2026-09-15T16:54:11Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `38eb724` on `feature/acp` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #4 (previous: 2026-09-03T05:33:53Z) | ||
| 7 | + | ||
| 8 | +## Lint issues (`qlty check`) | ||
| 9 | + | ||
| 10 | +_none_ | ||
| 11 | + | ||
| 12 | +### Top rules | ||
| 13 | + | ||
| 14 | +_none_ | ||
| 15 | + | ||
| 16 | +### Most affected files | ||
| 17 | + | ||
| 18 | +_none_ | ||
| 19 | + | ||
| 20 | +## Code smells (`qlty smells`) | ||
| 21 | + | ||
| 22 | +Total: **0** (vs previous: ±0) | ||
| 23 | + | ||
| 24 | +_none_ | ||
| 25 | + | ||
| 26 | +## Metrics (`qlty metrics`) | ||
| 27 | + | ||
| 28 | +| metric | total | vs previous | | ||
| 29 | +|---|---|---| | ||
| 30 | +| funcs | 42 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 10 | ±0 | | ||
| 33 | +| cyclo | 185 | ±0 | | ||
| 34 | +| complex | 91 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1046 | +10 | | ||
| 37 | +| loc | 527 | +2 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/pythonlang/words.go | 33 | 63 | 140 | | ||
| 44 | +| internal/pythonlang/scan.go | 20 | 51 | 84 | | ||
| 45 | +| main.go | 16 | 32 | 132 | | ||
| 46 | +| internal/pythonlang/literals.go | 13 | 23 | 74 | | ||
| 47 | +| internal/pythonlang/pythonlang.go | 9 | 15 | 91 | | ||
| 48 | +| internal/pythonlang/templates.go | 0 | 1 | 6 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-03T05:03:05Z | 0 | 0 | 1 | 91 | FAIL | | ||
| 55 | +| 2 | 2026-09-03T05:03:25Z | 0 | 0 | 0 | 91 | PASS | | ||
| 56 | +| 3 | 2026-09-03T05:33:53Z | 0 | 0 | 0 | 91 | PASS | | ||
| 57 | +| 4 | 2026-09-15T16:54:11Z | 0 | 0 | 0 | 91 | PASS | | ||
added
.turbo-python/acp.toml +14 -0 | new file mode 100644 | ||
| @@ -0,0 +1,14 @@ | ||
| 1 | +[[agent]] | |
| 2 | +name = "Bob (llama.cpp)" | |
| 3 | +command = "docker" | |
| 4 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | |
| 5 | +env = { TELEMETRY_ENABLED = "false" } | |
| 6 | + | |
| 7 | +# The user's own agent, the one Zed runs as "mini-me": it speaks the protocol | |
| 8 | +# on stdin/stdout when started with -acp, and announces slash commands the | |
| 9 | +# editor lists when / is typed at the start of the box. | |
| 10 | +[[agent]] | |
| 11 | +name = "mini-me (llama.cpp)" | |
| 12 | +command = "mm" | |
| 13 | +args = ["-acp"] | |
| 14 | +env = { AGENT_CONFIG = "/Users/k33g/kDrive/Rickub/bots-garden/mini-me/agent.llamacpp.yaml" } | |
| new file mode 100644 | |||
| @@ -0,0 +1,14 @@ | |||
| 1 | +[[agent]] | ||
| 2 | +name = "Bob (llama.cpp)" | ||
| 3 | +command = "docker" | ||
| 4 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | ||
| 5 | +env = { TELEMETRY_ENABLED = "false" } | ||
| 6 | + | ||
| 7 | +# The user's own agent, the one Zed runs as "mini-me": it speaks the protocol | ||
| 8 | +# on stdin/stdout when started with -acp, and announces slash commands the | ||
| 9 | +# editor lists when / is typed at the start of the box. | ||
| 10 | +[[agent]] | ||
| 11 | +name = "mini-me (llama.cpp)" | ||
| 12 | +command = "mm" | ||
| 13 | +args = ["-acp"] | ||
| 14 | +env = { AGENT_CONFIG = "/Users/k33g/kDrive/Rickub/bots-garden/mini-me/agent.llamacpp.yaml" } | ||
added
.turbo-python/agent.yaml +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +# /Users/k33g/CodeBerg/turbo-editors/turbo-python/turbo-python/.turbo-python/agent.yaml | |
| 2 | +providers: | |
| 3 | + llamacpp: | |
| 4 | + api_type: openai_chatcompletions | |
| 5 | + base_url: http://host.docker.internal:8080/v1 | |
| 6 | + | |
| 7 | +models: | |
| 8 | + mellum2: | |
| 9 | + provider: llamacpp | |
| 10 | + model: JetBrains/Mellum2-12B-A2.5B-Instruct-GGUF-Q4_K_M:Q4_K_M | |
| 11 | + #max_tokens: 8192 | |
| 12 | + temperature: 0.7 | |
| 13 | + provider_opts: | |
| 14 | + context_size: 262144 | |
| 15 | + | |
| 16 | +agents: | |
| 17 | + root: | |
| 18 | + model: mellum2 | |
| 19 | + description: A helpful AI assistant running on a local llama.cpp server | |
| 20 | + instruction: | | |
| 21 | + You name is Bob 🤓, you are a knowledgeable code assistant that helps users with various tasks. | |
| 22 | + Be helpful, accurate, and concise in your responses. | |
| 23 | + You have access to the local filesystem and shell: use these tools | |
| 24 | + welcome_message: | | |
| 25 | + 🤖 Local Assistant propulsed by **llama.cpp** 🦙 | |
| 26 | + | |
| 27 | + toolsets: | |
| 28 | + - type: filesystem | |
| 29 | + - type: shell | |
| new file mode 100644 | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | +# /Users/k33g/CodeBerg/turbo-editors/turbo-python/turbo-python/.turbo-python/agent.yaml | ||
| 2 | +providers: | ||
| 3 | + llamacpp: | ||
| 4 | + api_type: openai_chatcompletions | ||
| 5 | + base_url: http://host.docker.internal:8080/v1 | ||
| 6 | + | ||
| 7 | +models: | ||
| 8 | + mellum2: | ||
| 9 | + provider: llamacpp | ||
| 10 | + model: JetBrains/Mellum2-12B-A2.5B-Instruct-GGUF-Q4_K_M:Q4_K_M | ||
| 11 | + #max_tokens: 8192 | ||
| 12 | + temperature: 0.7 | ||
| 13 | + provider_opts: | ||
| 14 | + context_size: 262144 | ||
| 15 | + | ||
| 16 | +agents: | ||
| 17 | + root: | ||
| 18 | + model: mellum2 | ||
| 19 | + description: A helpful AI assistant running on a local llama.cpp server | ||
| 20 | + instruction: | | ||
| 21 | + You name is Bob 🤓, you are a knowledgeable code assistant that helps users with various tasks. | ||
| 22 | + Be helpful, accurate, and concise in your responses. | ||
| 23 | + You have access to the local filesystem and shell: use these tools | ||
| 24 | + welcome_message: | | ||
| 25 | + 🤖 Local Assistant propulsed by **llama.cpp** 🦙 | ||
| 26 | + | ||
| 27 | + toolsets: | ||
| 28 | + - type: filesystem | ||
| 29 | + - type: shell | ||
added
.vscode/extensions.json +9 -0 | new file mode 100644 | ||
| @@ -0,0 +1,9 @@ | ||
| 1 | +{ | |
| 2 | + "recommendations": [ | |
| 3 | + "ms-azuretools.vscode-docker", | |
| 4 | + "pkief.material-icon-theme", | |
| 5 | + "pkief.material-product-icons", | |
| 6 | + "aaron-bond.better-comments", | |
| 7 | + "bierner.markdown-mermaid", | |
| 8 | + ] | |
| 9 | +} | |
| \ No newline at end of file | ||
| new file mode 100644 | |||
| @@ -0,0 +1,9 @@ | |||
| 1 | +{ | ||
| 2 | + "recommendations": [ | ||
| 3 | + "ms-azuretools.vscode-docker", | ||
| 4 | + "pkief.material-icon-theme", | ||
| 5 | + "pkief.material-product-icons", | ||
| 6 | + "aaron-bond.better-comments", | ||
| 7 | + "bierner.markdown-mermaid", | ||
| 8 | + ] | ||
| 9 | +} | ||
| \ No newline at end of file | \ No newline at end of file | ||
added
.vscode/settings.json +90 -0 | new file mode 100644 | ||
| @@ -0,0 +1,90 @@ | ||
| 1 | +{ | |
| 2 | + "workbench.iconTheme": "material-icon-theme", | |
| 3 | + "workbench.colorTheme": "GitHub Light Colorblind (Beta)", | |
| 4 | + "editor.fontSize": 14, | |
| 5 | + "terminal.integrated.fontSize": 14, | |
| 6 | + "editor.insertSpaces": true, | |
| 7 | + "editor.tabSize": 4, | |
| 8 | + "editor.detectIndentation": true, | |
| 9 | + "files.autoSave": "afterDelay", | |
| 10 | + "files.autoSaveDelay": 1000, | |
| 11 | + // "editor.defaultFormatter": "esbenp.prettier-vscode", | |
| 12 | + "editor.formatOnSave": true, | |
| 13 | + "workbench.tree.indent": 20, | |
| 14 | + //"workbench.activityBar.location": "top", | |
| 15 | + "workbench.editor.showTabs": "multiple", | |
| 16 | + "window.zoomLevel": 0.0, | |
| 17 | + "[markdown]": { | |
| 18 | + "editor.unicodeHighlight.ambiguousCharacters": false, | |
| 19 | + "editor.unicodeHighlight.invisibleCharacters": false, | |
| 20 | + "diffEditor.ignoreTrimWhitespace": false, | |
| 21 | + "editor.fontWeight": "normal", | |
| 22 | + "editor.fontFamily": "'Droid Sans Mono', 'monospace', monospace", | |
| 23 | + "editor.fontSize": 14, | |
| 24 | + "editor.wordWrap": "on", | |
| 25 | + "editor.quickSuggestions": { | |
| 26 | + "comments": "off", | |
| 27 | + "strings": "off", | |
| 28 | + "other": "off" | |
| 29 | + } | |
| 30 | + }, | |
| 31 | + "markdown.preview.fontSize": 14, | |
| 32 | + // "workbench.editorAssociations": { | |
| 33 | + // "*.md": "vscode.markdown.preview.editor" | |
| 34 | + // }, | |
| 35 | + "markdown.marp.html": "all", | |
| 36 | + "[dockerfile]": { | |
| 37 | + "editor.fontSize": 14 | |
| 38 | + }, | |
| 39 | + "[dockercompose]": { | |
| 40 | + "editor.fontSize": 14 | |
| 41 | + }, | |
| 42 | + "[json]": { | |
| 43 | + "editor.fontSize": 14 | |
| 44 | + }, | |
| 45 | + "[yaml]": { | |
| 46 | + "editor.fontSize": 14 | |
| 47 | + }, | |
| 48 | + "[go]": { | |
| 49 | + "editor.fontSize": 14, | |
| 50 | + "editor.defaultFormatter": "golang.go", | |
| 51 | + "editor.codeActionsOnSave": { | |
| 52 | + "source.organizeImports": "explicit" | |
| 53 | + } | |
| 54 | + }, | |
| 55 | + "go.lintTool": "golangci-lint", | |
| 56 | + "go.lintOnSave": "package", | |
| 57 | + "go.formatTool": "goimports", | |
| 58 | + "go.useLanguageServer": true, | |
| 59 | + "gopls": { | |
| 60 | + "ui.semanticTokens": true, | |
| 61 | + "ui.completion.usePlaceholders": true | |
| 62 | + }, | |
| 63 | + | |
| 64 | + "workbench.colorCustomizations": { | |
| 65 | + "activityBar.activeBackground": "#ffffff", | |
| 66 | + "activityBar.background": "#ffffff", | |
| 67 | + "activityBar.foreground": "#15202b", | |
| 68 | + "activityBar.inactiveForeground": "#15202b99", | |
| 69 | + "activityBarBadge.background": "#b8a8e8", | |
| 70 | + "activityBarBadge.foreground": "#15202b", | |
| 71 | + "commandCenter.border": "#15202b99", | |
| 72 | + "sash.hoverBorder": "#ffffff", | |
| 73 | + "statusBar.background": "#b8a8e8", | |
| 74 | + "statusBar.foreground": "#15202b", | |
| 75 | + "statusBarItem.hoverBackground": "#a4f5b0", | |
| 76 | + "statusBarItem.remoteBackground": "#9c8cf2", | |
| 77 | + "statusBarItem.remoteForeground": "#15202b", | |
| 78 | + "titleBar.activeBackground": "#b8a8e8", | |
| 79 | + "titleBar.activeForeground": "#15202b", | |
| 80 | + "titleBar.inactiveBackground": "#b8a8e8", | |
| 81 | + "titleBar.inactiveForeground": "#15202b99", | |
| 82 | + "activityBarTop.activeBackground": "#ffffff", | |
| 83 | + "activityBarTop.background": "#ffffff", | |
| 84 | + "activityBarTop.foreground": "#15202b", | |
| 85 | + "activityBarTop.inactiveForeground": "#15202b99", | |
| 86 | + "commandCenter.foreground": "#15202b", | |
| 87 | + "statusBar.debuggingBackground": "#b8a8e8", | |
| 88 | + "statusBar.debuggingForeground": "#15202b" | |
| 89 | + } | |
| 90 | +} | |
| \ No newline at end of file | ||
| new file mode 100644 | |||
| @@ -0,0 +1,90 @@ | |||
| 1 | +{ | ||
| 2 | + "workbench.iconTheme": "material-icon-theme", | ||
| 3 | + "workbench.colorTheme": "GitHub Light Colorblind (Beta)", | ||
| 4 | + "editor.fontSize": 14, | ||
| 5 | + "terminal.integrated.fontSize": 14, | ||
| 6 | + "editor.insertSpaces": true, | ||
| 7 | + "editor.tabSize": 4, | ||
| 8 | + "editor.detectIndentation": true, | ||
| 9 | + "files.autoSave": "afterDelay", | ||
| 10 | + "files.autoSaveDelay": 1000, | ||
| 11 | + // "editor.defaultFormatter": "esbenp.prettier-vscode", | ||
| 12 | + "editor.formatOnSave": true, | ||
| 13 | + "workbench.tree.indent": 20, | ||
| 14 | + //"workbench.activityBar.location": "top", | ||
| 15 | + "workbench.editor.showTabs": "multiple", | ||
| 16 | + "window.zoomLevel": 0.0, | ||
| 17 | + "[markdown]": { | ||
| 18 | + "editor.unicodeHighlight.ambiguousCharacters": false, | ||
| 19 | + "editor.unicodeHighlight.invisibleCharacters": false, | ||
| 20 | + "diffEditor.ignoreTrimWhitespace": false, | ||
| 21 | + "editor.fontWeight": "normal", | ||
| 22 | + "editor.fontFamily": "'Droid Sans Mono', 'monospace', monospace", | ||
| 23 | + "editor.fontSize": 14, | ||
| 24 | + "editor.wordWrap": "on", | ||
| 25 | + "editor.quickSuggestions": { | ||
| 26 | + "comments": "off", | ||
| 27 | + "strings": "off", | ||
| 28 | + "other": "off" | ||
| 29 | + } | ||
| 30 | + }, | ||
| 31 | + "markdown.preview.fontSize": 14, | ||
| 32 | + // "workbench.editorAssociations": { | ||
| 33 | + // "*.md": "vscode.markdown.preview.editor" | ||
| 34 | + // }, | ||
| 35 | + "markdown.marp.html": "all", | ||
| 36 | + "[dockerfile]": { | ||
| 37 | + "editor.fontSize": 14 | ||
| 38 | + }, | ||
| 39 | + "[dockercompose]": { | ||
| 40 | + "editor.fontSize": 14 | ||
| 41 | + }, | ||
| 42 | + "[json]": { | ||
| 43 | + "editor.fontSize": 14 | ||
| 44 | + }, | ||
| 45 | + "[yaml]": { | ||
| 46 | + "editor.fontSize": 14 | ||
| 47 | + }, | ||
| 48 | + "[go]": { | ||
| 49 | + "editor.fontSize": 14, | ||
| 50 | + "editor.defaultFormatter": "golang.go", | ||
| 51 | + "editor.codeActionsOnSave": { | ||
| 52 | + "source.organizeImports": "explicit" | ||
| 53 | + } | ||
| 54 | + }, | ||
| 55 | + "go.lintTool": "golangci-lint", | ||
| 56 | + "go.lintOnSave": "package", | ||
| 57 | + "go.formatTool": "goimports", | ||
| 58 | + "go.useLanguageServer": true, | ||
| 59 | + "gopls": { | ||
| 60 | + "ui.semanticTokens": true, | ||
| 61 | + "ui.completion.usePlaceholders": true | ||
| 62 | + }, | ||
| 63 | + | ||
| 64 | + "workbench.colorCustomizations": { | ||
| 65 | + "activityBar.activeBackground": "#ffffff", | ||
| 66 | + "activityBar.background": "#ffffff", | ||
| 67 | + "activityBar.foreground": "#15202b", | ||
| 68 | + "activityBar.inactiveForeground": "#15202b99", | ||
| 69 | + "activityBarBadge.background": "#b8a8e8", | ||
| 70 | + "activityBarBadge.foreground": "#15202b", | ||
| 71 | + "commandCenter.border": "#15202b99", | ||
| 72 | + "sash.hoverBorder": "#ffffff", | ||
| 73 | + "statusBar.background": "#b8a8e8", | ||
| 74 | + "statusBar.foreground": "#15202b", | ||
| 75 | + "statusBarItem.hoverBackground": "#a4f5b0", | ||
| 76 | + "statusBarItem.remoteBackground": "#9c8cf2", | ||
| 77 | + "statusBarItem.remoteForeground": "#15202b", | ||
| 78 | + "titleBar.activeBackground": "#b8a8e8", | ||
| 79 | + "titleBar.activeForeground": "#15202b", | ||
| 80 | + "titleBar.inactiveBackground": "#b8a8e8", | ||
| 81 | + "titleBar.inactiveForeground": "#15202b99", | ||
| 82 | + "activityBarTop.activeBackground": "#ffffff", | ||
| 83 | + "activityBarTop.background": "#ffffff", | ||
| 84 | + "activityBarTop.foreground": "#15202b", | ||
| 85 | + "activityBarTop.inactiveForeground": "#15202b99", | ||
| 86 | + "commandCenter.foreground": "#15202b", | ||
| 87 | + "statusBar.debuggingBackground": "#b8a8e8", | ||
| 88 | + "statusBar.debuggingForeground": "#15202b" | ||
| 89 | + } | ||
| 90 | +} | ||
| \ No newline at end of file | \ No newline at end of file | ||
added
01-release.tag.sh +115 -0 | new file mode 100755 | ||
| @@ -0,0 +1,115 @@ | ||
| 1 | +#!/bin/bash | |
| 2 | +: <<'COMMENT' | |
| 3 | +Releasing turbo-python is tagging it. Pushing the tag starts the Release workflow, | |
| 4 | +which builds the binaries and publishes the release page with them. | |
| 5 | + | |
| 6 | +1. Set TAG and ABOUT in release.env | |
| 7 | +2. Run this script: ./01-release.tag.sh (make check, commit, push, tag, push the tag) | |
| 8 | +3. Watch the "Release" workflow on Rickub (Actions tab): the tag push starts | |
| 9 | + it; it cross-compiles the binaries with ./02-build-releases.sh and publishes | |
| 10 | + the release page with them, using the job's own token. No personal token is | |
| 11 | + needed, and nothing else has to be run by hand. | |
| 12 | +COMMENT | |
| 13 | + | |
| 14 | +# Without this, a failing step is ignored and the next one runs anyway. That is | |
| 15 | +# not theoretical: `git tag` refusing a tag that already existed was skipped in | |
| 16 | +# silence, and the `git push` below then pushed the OLD tag — so a release was | |
| 17 | +# cut from a commit nobody meant, and 02 was left to notice. | |
| 18 | +set -euo pipefail | |
| 19 | + | |
| 20 | +if [ ! -f release.env ]; then | |
| 21 | + echo "❌ release.env is missing" | |
| 22 | + echo "💡 Create it with the version you are publishing:" | |
| 23 | + echo ' TAG=v1.0.0' | |
| 24 | + echo ' ABOUT="Turbo Python"' | |
| 25 | + exit 1 | |
| 26 | +fi | |
| 27 | + | |
| 28 | +set -o allexport | |
| 29 | +# shellcheck source=/dev/null | |
| 30 | +source release.env | |
| 31 | +set +o allexport | |
| 32 | + | |
| 33 | +echo "Releasing turbo-python ${TAG}: ${ABOUT}" | |
| 34 | + | |
| 35 | +# A tag that is not vMAJOR.MINOR.PATCH[-prerelease] is a typo — and worse than | |
| 36 | +# a typo: the workflow only starts on v*, and the module proxy will not serve | |
| 37 | +# `go install …@TAG` for a tag it cannot read as a version. | |
| 38 | +if ! [[ "${TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then | |
| 39 | + echo "❌ TAG must look like v1.2.3 or v1.2.3-rc.1, got '${TAG}' (check release.env)" | |
| 40 | + exit 1 | |
| 41 | +fi | |
| 42 | + | |
| 43 | +# The whole suite has to pass before a version exists that people will | |
| 44 | +# download. A tag the proxy has cached is the wrong place to find out. | |
| 45 | +# | |
| 46 | +# The marker matters: the suite includes tests that run *this script* against a | |
| 47 | +# throwaway clone, and without it `make check` would run those, which would run | |
| 48 | +# this script, which would run `make check`. They skip themselves when they see | |
| 49 | +# it. Exported, so it reaches the test binary through make and go test. | |
| 50 | +export TURBO_PYTHON_RELEASING=1 | |
| 51 | +echo "→ make check" | |
| 52 | +make --no-print-directory check | |
| 53 | + | |
| 54 | +# tagExists reports whether TAG is already taken, here or on the remote. The | |
| 55 | +# remote matters on its own: a tag deleted locally after a failed attempt still | |
| 56 | +# exists there, and pushing a new one at a different commit is rejected. | |
| 57 | +tagExists() { | |
| 58 | + if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then | |
| 59 | + printf 'locally, on %s\n' "$(git rev-parse --short "${TAG}^{commit}")" | |
| 60 | + return 0 | |
| 61 | + fi | |
| 62 | + if ! remote="$(git ls-remote --tags origin "refs/tags/${TAG}" 2>/dev/null)"; then | |
| 63 | + return 1 # the remote is unreachable; the push below will say so | |
| 64 | + fi | |
| 65 | + if [ -n "${remote}" ]; then | |
| 66 | + # No commit is named here on purpose: for an annotated tag ls-remote | |
| 67 | + # gives the tag object, not the commit, and printing that as if it were | |
| 68 | + # the commit sends the reader looking for a SHA they will never find. | |
| 69 | + printf 'on origin\n' | |
| 70 | + return 0 | |
| 71 | + fi | |
| 72 | + return 1 | |
| 73 | +} | |
| 74 | + | |
| 75 | +if where="$(tagExists)"; then | |
| 76 | + echo "❌ ${TAG} already exists ${where}" | |
| 77 | + echo "💡 A published version is not yours to move: the module proxy caches" | |
| 78 | + echo " what it fetched for \`go install\`, and the release page already" | |
| 79 | + echo " carries binaries with that number. Bump TAG in release.env instead." | |
| 80 | + exit 1 | |
| 81 | +fi | |
| 82 | + | |
| 83 | +# The editor must not be published with a replace directive in it: the module | |
| 84 | +# proxy serves the go.mod as written, and `go install …@TAG` would then look | |
| 85 | +# for turbo-core in a directory that does not exist on the installer's machine. | |
| 86 | +if grep -qE '^[[:space:]]*replace[[:space:]]' go.mod; then | |
| 87 | + echo "❌ go.mod has a replace directive, which a published module must not" | |
| 88 | + grep -nE '^[[:space:]]*replace[[:space:]]' go.mod | |
| 89 | + exit 1 | |
| 90 | +fi | |
| 91 | + | |
| 92 | +find . -name '.DS_Store' -type f -delete | |
| 93 | + | |
| 94 | +git add . | |
| 95 | + | |
| 96 | +# Nothing to commit is not a failure — the work may already be committed — but | |
| 97 | +# under `set -e` a plain `git commit` would stop the release right here. | |
| 98 | +if git diff --cached --quiet; then | |
| 99 | + echo "Nothing to commit; releasing what is already on HEAD" | |
| 100 | +else | |
| 101 | + git commit -m "📦 ${ABOUT}" | |
| 102 | +fi | |
| 103 | + | |
| 104 | +git push origin "$(git rev-parse --abbrev-ref HEAD)" | |
| 105 | + | |
| 106 | +# The tag goes on after the push, so a rejected push never leaves a tag behind | |
| 107 | +# pointing at a commit the remote has never seen. | |
| 108 | +git tag -a "${TAG}" -m "${ABOUT}" | |
| 109 | +git push origin "${TAG}" | |
| 110 | + | |
| 111 | +echo "✅ turbo-python ${TAG} published" | |
| 112 | +echo "💡 The tag push started the Release workflow; it builds the binaries and" | |
| 113 | +echo " creates the release page. Watch it on the repository's Actions tab." | |
| 114 | +echo "💡 To see what it will build without publishing anything:" | |
| 115 | +echo " ./02-build-releases.sh ${TAG}" | |
| new file mode 100755 | |||
| @@ -0,0 +1,115 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +: <<'COMMENT' | ||
| 3 | +Releasing turbo-python is tagging it. Pushing the tag starts the Release workflow, | ||
| 4 | +which builds the binaries and publishes the release page with them. | ||
| 5 | + | ||
| 6 | +1. Set TAG and ABOUT in release.env | ||
| 7 | +2. Run this script: ./01-release.tag.sh (make check, commit, push, tag, push the tag) | ||
| 8 | +3. Watch the "Release" workflow on Rickub (Actions tab): the tag push starts | ||
| 9 | + it; it cross-compiles the binaries with ./02-build-releases.sh and publishes | ||
| 10 | + the release page with them, using the job's own token. No personal token is | ||
| 11 | + needed, and nothing else has to be run by hand. | ||
| 12 | +COMMENT | ||
| 13 | + | ||
| 14 | +# Without this, a failing step is ignored and the next one runs anyway. That is | ||
| 15 | +# not theoretical: `git tag` refusing a tag that already existed was skipped in | ||
| 16 | +# silence, and the `git push` below then pushed the OLD tag — so a release was | ||
| 17 | +# cut from a commit nobody meant, and 02 was left to notice. | ||
| 18 | +set -euo pipefail | ||
| 19 | + | ||
| 20 | +if [ ! -f release.env ]; then | ||
| 21 | + echo "❌ release.env is missing" | ||
| 22 | + echo "💡 Create it with the version you are publishing:" | ||
| 23 | + echo ' TAG=v1.0.0' | ||
| 24 | + echo ' ABOUT="Turbo Python"' | ||
| 25 | + exit 1 | ||
| 26 | +fi | ||
| 27 | + | ||
| 28 | +set -o allexport | ||
| 29 | +# shellcheck source=/dev/null | ||
| 30 | +source release.env | ||
| 31 | +set +o allexport | ||
| 32 | + | ||
| 33 | +echo "Releasing turbo-python ${TAG}: ${ABOUT}" | ||
| 34 | + | ||
| 35 | +# A tag that is not vMAJOR.MINOR.PATCH[-prerelease] is a typo — and worse than | ||
| 36 | +# a typo: the workflow only starts on v*, and the module proxy will not serve | ||
| 37 | +# `go install …@TAG` for a tag it cannot read as a version. | ||
| 38 | +if ! [[ "${TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then | ||
| 39 | + echo "❌ TAG must look like v1.2.3 or v1.2.3-rc.1, got '${TAG}' (check release.env)" | ||
| 40 | + exit 1 | ||
| 41 | +fi | ||
| 42 | + | ||
| 43 | +# The whole suite has to pass before a version exists that people will | ||
| 44 | +# download. A tag the proxy has cached is the wrong place to find out. | ||
| 45 | +# | ||
| 46 | +# The marker matters: the suite includes tests that run *this script* against a | ||
| 47 | +# throwaway clone, and without it `make check` would run those, which would run | ||
| 48 | +# this script, which would run `make check`. They skip themselves when they see | ||
| 49 | +# it. Exported, so it reaches the test binary through make and go test. | ||
| 50 | +export TURBO_PYTHON_RELEASING=1 | ||
| 51 | +echo "→ make check" | ||
| 52 | +make --no-print-directory check | ||
| 53 | + | ||
| 54 | +# tagExists reports whether TAG is already taken, here or on the remote. The | ||
| 55 | +# remote matters on its own: a tag deleted locally after a failed attempt still | ||
| 56 | +# exists there, and pushing a new one at a different commit is rejected. | ||
| 57 | +tagExists() { | ||
| 58 | + if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then | ||
| 59 | + printf 'locally, on %s\n' "$(git rev-parse --short "${TAG}^{commit}")" | ||
| 60 | + return 0 | ||
| 61 | + fi | ||
| 62 | + if ! remote="$(git ls-remote --tags origin "refs/tags/${TAG}" 2>/dev/null)"; then | ||
| 63 | + return 1 # the remote is unreachable; the push below will say so | ||
| 64 | + fi | ||
| 65 | + if [ -n "${remote}" ]; then | ||
| 66 | + # No commit is named here on purpose: for an annotated tag ls-remote | ||
| 67 | + # gives the tag object, not the commit, and printing that as if it were | ||
| 68 | + # the commit sends the reader looking for a SHA they will never find. | ||
| 69 | + printf 'on origin\n' | ||
| 70 | + return 0 | ||
| 71 | + fi | ||
| 72 | + return 1 | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +if where="$(tagExists)"; then | ||
| 76 | + echo "❌ ${TAG} already exists ${where}" | ||
| 77 | + echo "💡 A published version is not yours to move: the module proxy caches" | ||
| 78 | + echo " what it fetched for \`go install\`, and the release page already" | ||
| 79 | + echo " carries binaries with that number. Bump TAG in release.env instead." | ||
| 80 | + exit 1 | ||
| 81 | +fi | ||
| 82 | + | ||
| 83 | +# The editor must not be published with a replace directive in it: the module | ||
| 84 | +# proxy serves the go.mod as written, and `go install …@TAG` would then look | ||
| 85 | +# for turbo-core in a directory that does not exist on the installer's machine. | ||
| 86 | +if grep -qE '^[[:space:]]*replace[[:space:]]' go.mod; then | ||
| 87 | + echo "❌ go.mod has a replace directive, which a published module must not" | ||
| 88 | + grep -nE '^[[:space:]]*replace[[:space:]]' go.mod | ||
| 89 | + exit 1 | ||
| 90 | +fi | ||
| 91 | + | ||
| 92 | +find . -name '.DS_Store' -type f -delete | ||
| 93 | + | ||
| 94 | +git add . | ||
| 95 | + | ||
| 96 | +# Nothing to commit is not a failure — the work may already be committed — but | ||
| 97 | +# under `set -e` a plain `git commit` would stop the release right here. | ||
| 98 | +if git diff --cached --quiet; then | ||
| 99 | + echo "Nothing to commit; releasing what is already on HEAD" | ||
| 100 | +else | ||
| 101 | + git commit -m "📦 ${ABOUT}" | ||
| 102 | +fi | ||
| 103 | + | ||
| 104 | +git push origin "$(git rev-parse --abbrev-ref HEAD)" | ||
| 105 | + | ||
| 106 | +# The tag goes on after the push, so a rejected push never leaves a tag behind | ||
| 107 | +# pointing at a commit the remote has never seen. | ||
| 108 | +git tag -a "${TAG}" -m "${ABOUT}" | ||
| 109 | +git push origin "${TAG}" | ||
| 110 | + | ||
| 111 | +echo "✅ turbo-python ${TAG} published" | ||
| 112 | +echo "💡 The tag push started the Release workflow; it builds the binaries and" | ||
| 113 | +echo " creates the release page. Watch it on the repository's Actions tab." | ||
| 114 | +echo "💡 To see what it will build without publishing anything:" | ||
| 115 | +echo " ./02-build-releases.sh ${TAG}" | ||
added
02-build-releases.sh +209 -0 | new file mode 100755 | ||
| @@ -0,0 +1,209 @@ | ||
| 1 | +#!/bin/bash | |
| 2 | +: <<'COMMENT' | |
| 3 | +Build the release binaries and stage them under release/${TAG}/ | |
| 4 | + | |
| 5 | +Usage: | |
| 6 | + ./02-build-releases.sh # TAG and ABOUT come from release.env | |
| 7 | + ./02-build-releases.sh v1.0.0 # override the tag for this run (what CI does) | |
| 8 | + | |
| 9 | +This is the script the Release workflow runs when ./01-release.tag.sh pushes a | |
| 10 | +tag; the workflow then attaches everything staged here to the release page. | |
| 11 | +Nothing here publishes anything, so it is also the way to see what a release | |
| 12 | +will contain before cutting it, or to build the binaries by hand. | |
| 13 | + | |
| 14 | +Only the Go toolchain and git are needed. The same command works on a laptop | |
| 15 | +and in a Rickub CI job. | |
| 16 | + | |
| 17 | +What ends up in release/${TAG}/: | |
| 18 | + turbo-python-<version>-<os>-<arch>[.exe] one binary per platform in PLATFORMS | |
| 19 | + SHA256SUMS checksums of every binary | |
| 20 | + README.md the downloads, how to run and verify them | |
| 21 | +COMMENT | |
| 22 | + | |
| 23 | +set -euo pipefail | |
| 24 | + | |
| 25 | +# release.env carries TAG ("v1.0.0") and ABOUT (the one-line description). It | |
| 26 | +# is git-ignored (*.env), so a CI job does not have it: there the tag comes | |
| 27 | +# from the command line and ABOUT from the environment, or defaults to the | |
| 28 | +# tag. A tag given on the command line always wins, so a test build never | |
| 29 | +# edits the file. | |
| 30 | +if [ -f release.env ]; then | |
| 31 | + # shellcheck source=/dev/null | |
| 32 | + source release.env | |
| 33 | +fi | |
| 34 | +TAG="${1:-${TAG:-}}" | |
| 35 | +ABOUT="${ABOUT:-Turbo Python ${TAG}}" | |
| 36 | + | |
| 37 | +# A tag that is not vMAJOR.MINOR.PATCH[-prerelease] is a typo — and for a Go | |
| 38 | +# module it is worse than a typo: the proxy will not serve a tag it cannot read | |
| 39 | +# as a version, so `go install` would fail on a release that built perfectly. | |
| 40 | +if ! [[ "${TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then | |
| 41 | + echo "❌ TAG must look like v1.2.3 or v1.2.3-rc.1, got '${TAG}' (check release.env)" | |
| 42 | + exit 1 | |
| 43 | +fi | |
| 44 | + | |
| 45 | +# 01 refuses this too, but CI runs *this* script on a tag that is already | |
| 46 | +# pushed, without ever running 01. The proxy serves go.mod as written, so a | |
| 47 | +# published editor carrying a replace tells `go install` to look for turbo-core | |
| 48 | +# in a directory that does not exist on the installer's machine. | |
| 49 | +if grep -qE '^[[:space:]]*replace[[:space:]]' go.mod; then | |
| 50 | + echo "❌ go.mod has a replace directive, which a published module must not" | |
| 51 | + grep -nE '^[[:space:]]*replace[[:space:]]' go.mod | |
| 52 | + exit 1 | |
| 53 | +fi | |
| 54 | + | |
| 55 | +# The platforms a release is built for. Add or remove a line and everything | |
| 56 | +# below follows: the builds, the checksums and the README. | |
| 57 | +PLATFORMS=( | |
| 58 | + "darwin/arm64" | |
| 59 | + "linux/amd64" | |
| 60 | + "linux/arm64" | |
| 61 | + "windows/amd64" | |
| 62 | + "windows/arm64" | |
| 63 | +) | |
| 64 | + | |
| 65 | +echo "🚀 Building Turbo Python ${TAG} — ${ABOUT}" | |
| 66 | +echo "🐹 $(go version)" | |
| 67 | + | |
| 68 | +RELEASES_DIR="release/${TAG}" | |
| 69 | + | |
| 70 | +# The tag is "v1.0.0"; the assets carry the bare version, "1.0.0". | |
| 71 | +VERSION="${TAG#v}" | |
| 72 | + | |
| 73 | +# Where the Makefile puts the binary for this machine. | |
| 74 | +BUILT="bin/turbo-python" | |
| 75 | + | |
| 76 | +# The release is ${TAG}, so ${TAG} is what every binary here reports. The | |
| 77 | +# Makefile's own default comes from `git describe`, which answers a different | |
| 78 | +# question — where HEAD is — and disagrees the moment you commit after tagging. | |
| 79 | +# Overriding VERSION keeps the -X paths defined in one place all the same. | |
| 80 | +LDFLAGS="$(make --no-print-directory ldflags VERSION="${TAG}")" | |
| 81 | + | |
| 82 | +# A fresh directory, so a binary left by an earlier run for a platform since | |
| 83 | +# removed from PLATFORMS cannot end up on the release page. | |
| 84 | +rm -rf "${RELEASES_DIR}" | |
| 85 | +mkdir -p "${RELEASES_DIR}" | |
| 86 | + | |
| 87 | +# The host build comes first: it is the quickest way to find a compile error, | |
| 88 | +# before spending five cross-compiles on it. | |
| 89 | +make build VERSION="${TAG}" | |
| 90 | + | |
| 91 | +if [ ! -f "${BUILT}" ]; then | |
| 92 | + echo "❌ make build produced no ${BUILT}" | |
| 93 | + exit 1 | |
| 94 | +fi | |
| 95 | + | |
| 96 | +# assetName returns what the binary for a platform is called once staged. | |
| 97 | +# Windows executables carry .exe, or Windows will not run them. | |
| 98 | +assetName() { | |
| 99 | + local goos=$1 goarch=$2 | |
| 100 | + local name="turbo-python-${VERSION}-${goos}-${goarch}" | |
| 101 | + | |
| 102 | + if [ "${goos}" = "windows" ]; then | |
| 103 | + name="${name}.exe" | |
| 104 | + fi | |
| 105 | + printf '%s\n' "${name}" | |
| 106 | +} | |
| 107 | + | |
| 108 | +echo "" | |
| 109 | +echo "🔨 Cross-compiling for ${#PLATFORMS[@]} platforms..." | |
| 110 | + | |
| 111 | +for platform in "${PLATFORMS[@]}"; do | |
| 112 | + goos="${platform%/*}" | |
| 113 | + goarch="${platform#*/}" | |
| 114 | + asset="$(assetName "${goos}" "${goarch}")" | |
| 115 | + | |
| 116 | + # CGO_ENABLED=0 because there is nothing to link against on the other side | |
| 117 | + # of a cross-compile, and this project needs no C at all: tcell and toml | |
| 118 | + # are both pure Go. | |
| 119 | + # | |
| 120 | + # -trimpath keeps the paths of this machine out of a binary that goes to | |
| 121 | + # strangers. | |
| 122 | + # | |
| 123 | + # -ldflags is what makes a downloaded binary agree with the release it came | |
| 124 | + # from. Without it the Go build system names the build itself, and every | |
| 125 | + # asset here would report "devel" while the release page says ${TAG}. | |
| 126 | + if ! CGO_ENABLED=0 GOOS="${goos}" GOARCH="${goarch}" \ | |
| 127 | + go build -trimpath -ldflags "${LDFLAGS}" -o "${RELEASES_DIR}/${asset}" .; then | |
| 128 | + echo " ❌ ${platform}" | |
| 129 | + exit 1 | |
| 130 | + fi | |
| 131 | + echo " ✅ ${asset}" | |
| 132 | +done | |
| 133 | + | |
| 134 | +# The staged asset for this machine is the only one that can be run here, and | |
| 135 | +# running it is the only proof that what ships carries the version rather than | |
| 136 | +# that the flags looked right. | |
| 137 | +# The number has to *equal* the tag, not merely appear in the output: "0.2.0" | |
| 138 | +# is a substring of "10.2.0" and of a commit hash that happens to contain it, | |
| 139 | +# and a stamp that is nearly right is the failure worth catching. | |
| 140 | +HOST_ASSET="$(assetName "$(go env GOOS)" "$(go env GOARCH)")" | |
| 141 | +if [ -x "${RELEASES_DIR}/${HOST_ASSET}" ]; then | |
| 142 | + if ! reported="$(scripts/check-version.sh "${RELEASES_DIR}/${HOST_ASSET}" "${TAG}")"; then | |
| 143 | + exit 1 | |
| 144 | + fi | |
| 145 | + echo " ✅ ${HOST_ASSET} reports ${reported}" | |
| 146 | +fi | |
| 147 | + | |
| 148 | +# checksum runs whichever of the two tools this machine has: sha256sum on | |
| 149 | +# Linux, shasum on macOS. | |
| 150 | +checksum() { | |
| 151 | + if command -v sha256sum >/dev/null 2>&1; then | |
| 152 | + sha256sum "$@" | |
| 153 | + else | |
| 154 | + shasum -a 256 "$@" | |
| 155 | + fi | |
| 156 | +} | |
| 157 | + | |
| 158 | +# The workflow attaches SHA256SUMS beside the binaries, so it is written here. | |
| 159 | +# One file covers every platform, which is what "sha256sum -c" expects to | |
| 160 | +# read, and the names carry no directory so it works next to the downloads. | |
| 161 | +(cd "${RELEASES_DIR}" && checksum turbo-python-"${VERSION}"-* >SHA256SUMS) | |
| 162 | +echo " ✅ SHA256SUMS" | |
| 163 | + | |
| 164 | +# downloadTable lists the platforms as a Markdown table, so the README grows | |
| 165 | +# and shrinks with PLATFORMS rather than repeating it by hand. | |
| 166 | +downloadTable() { | |
| 167 | + printf '| Platform | Download |\n|---|---|\n' | |
| 168 | + for platform in "${PLATFORMS[@]}"; do | |
| 169 | + local goos="${platform%/*}" goarch="${platform#*/}" | |
| 170 | + printf '| %s | `%s` |\n' "${platform}" "$(assetName "${goos}" "${goarch}")" | |
| 171 | + done | |
| 172 | +} | |
| 173 | + | |
| 174 | +cat >"${RELEASES_DIR}/README.md" <<EOM | |
| 175 | +# Turbo Python ${TAG} | |
| 176 | + | |
| 177 | +${ABOUT} | |
| 178 | + | |
| 179 | +Built with $(go env GOVERSION). No runtime dependencies; \`pylsp\` is optional and | |
| 180 | +only completion and error marks need it. | |
| 181 | + | |
| 182 | +$(downloadTable) | |
| 183 | + | |
| 184 | +## Running it | |
| 185 | + | |
| 186 | + chmod +x turbo-python-${VERSION}-<platform> | |
| 187 | + ./turbo-python-${VERSION}-<platform> main.py | |
| 188 | + | |
| 189 | +On macOS, an unsigned download is quarantined until you say otherwise: | |
| 190 | + | |
| 191 | + xattr -d com.apple.quarantine turbo-python-${VERSION}-darwin-arm64 | |
| 192 | + | |
| 193 | +## Installing from the module proxy instead | |
| 194 | + | |
| 195 | + go install $(go list -m)@${TAG} | |
| 196 | + | |
| 197 | +## Verifying the download | |
| 198 | + | |
| 199 | + sha256sum -c SHA256SUMS --ignore-missing # shasum -a 256 -c on macOS | |
| 200 | + | |
| 201 | +EOM | |
| 202 | +echo " ✅ README.md" | |
| 203 | + | |
| 204 | +echo "" | |
| 205 | +echo "✨ Build complete!" | |
| 206 | +ls -lh "${RELEASES_DIR}" | |
| 207 | +echo "" | |
| 208 | +echo "💡 Nothing was published. The Release workflow runs this same script when" | |
| 209 | +echo " ./01-release.tag.sh pushes ${TAG}, and attaches release/${TAG}/ to the release page." | |
| new file mode 100755 | |||
| @@ -0,0 +1,209 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +: <<'COMMENT' | ||
| 3 | +Build the release binaries and stage them under release/${TAG}/ | ||
| 4 | + | ||
| 5 | +Usage: | ||
| 6 | + ./02-build-releases.sh # TAG and ABOUT come from release.env | ||
| 7 | + ./02-build-releases.sh v1.0.0 # override the tag for this run (what CI does) | ||
| 8 | + | ||
| 9 | +This is the script the Release workflow runs when ./01-release.tag.sh pushes a | ||
| 10 | +tag; the workflow then attaches everything staged here to the release page. | ||
| 11 | +Nothing here publishes anything, so it is also the way to see what a release | ||
| 12 | +will contain before cutting it, or to build the binaries by hand. | ||
| 13 | + | ||
| 14 | +Only the Go toolchain and git are needed. The same command works on a laptop | ||
| 15 | +and in a Rickub CI job. | ||
| 16 | + | ||
| 17 | +What ends up in release/${TAG}/: | ||
| 18 | + turbo-python-<version>-<os>-<arch>[.exe] one binary per platform in PLATFORMS | ||
| 19 | + SHA256SUMS checksums of every binary | ||
| 20 | + README.md the downloads, how to run and verify them | ||
| 21 | +COMMENT | ||
| 22 | + | ||
| 23 | +set -euo pipefail | ||
| 24 | + | ||
| 25 | +# release.env carries TAG ("v1.0.0") and ABOUT (the one-line description). It | ||
| 26 | +# is git-ignored (*.env), so a CI job does not have it: there the tag comes | ||
| 27 | +# from the command line and ABOUT from the environment, or defaults to the | ||
| 28 | +# tag. A tag given on the command line always wins, so a test build never | ||
| 29 | +# edits the file. | ||
| 30 | +if [ -f release.env ]; then | ||
| 31 | + # shellcheck source=/dev/null | ||
| 32 | + source release.env | ||
| 33 | +fi | ||
| 34 | +TAG="${1:-${TAG:-}}" | ||
| 35 | +ABOUT="${ABOUT:-Turbo Python ${TAG}}" | ||
| 36 | + | ||
| 37 | +# A tag that is not vMAJOR.MINOR.PATCH[-prerelease] is a typo — and for a Go | ||
| 38 | +# module it is worse than a typo: the proxy will not serve a tag it cannot read | ||
| 39 | +# as a version, so `go install` would fail on a release that built perfectly. | ||
| 40 | +if ! [[ "${TAG}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then | ||
| 41 | + echo "❌ TAG must look like v1.2.3 or v1.2.3-rc.1, got '${TAG}' (check release.env)" | ||
| 42 | + exit 1 | ||
| 43 | +fi | ||
| 44 | + | ||
| 45 | +# 01 refuses this too, but CI runs *this* script on a tag that is already | ||
| 46 | +# pushed, without ever running 01. The proxy serves go.mod as written, so a | ||
| 47 | +# published editor carrying a replace tells `go install` to look for turbo-core | ||
| 48 | +# in a directory that does not exist on the installer's machine. | ||
| 49 | +if grep -qE '^[[:space:]]*replace[[:space:]]' go.mod; then | ||
| 50 | + echo "❌ go.mod has a replace directive, which a published module must not" | ||
| 51 | + grep -nE '^[[:space:]]*replace[[:space:]]' go.mod | ||
| 52 | + exit 1 | ||
| 53 | +fi | ||
| 54 | + | ||
| 55 | +# The platforms a release is built for. Add or remove a line and everything | ||
| 56 | +# below follows: the builds, the checksums and the README. | ||
| 57 | +PLATFORMS=( | ||
| 58 | + "darwin/arm64" | ||
| 59 | + "linux/amd64" | ||
| 60 | + "linux/arm64" | ||
| 61 | + "windows/amd64" | ||
| 62 | + "windows/arm64" | ||
| 63 | +) | ||
| 64 | + | ||
| 65 | +echo "🚀 Building Turbo Python ${TAG} — ${ABOUT}" | ||
| 66 | +echo "🐹 $(go version)" | ||
| 67 | + | ||
| 68 | +RELEASES_DIR="release/${TAG}" | ||
| 69 | + | ||
| 70 | +# The tag is "v1.0.0"; the assets carry the bare version, "1.0.0". | ||
| 71 | +VERSION="${TAG#v}" | ||
| 72 | + | ||
| 73 | +# Where the Makefile puts the binary for this machine. | ||
| 74 | +BUILT="bin/turbo-python" | ||
| 75 | + | ||
| 76 | +# The release is ${TAG}, so ${TAG} is what every binary here reports. The | ||
| 77 | +# Makefile's own default comes from `git describe`, which answers a different | ||
| 78 | +# question — where HEAD is — and disagrees the moment you commit after tagging. | ||
| 79 | +# Overriding VERSION keeps the -X paths defined in one place all the same. | ||
| 80 | +LDFLAGS="$(make --no-print-directory ldflags VERSION="${TAG}")" | ||
| 81 | + | ||
| 82 | +# A fresh directory, so a binary left by an earlier run for a platform since | ||
| 83 | +# removed from PLATFORMS cannot end up on the release page. | ||
| 84 | +rm -rf "${RELEASES_DIR}" | ||
| 85 | +mkdir -p "${RELEASES_DIR}" | ||
| 86 | + | ||
| 87 | +# The host build comes first: it is the quickest way to find a compile error, | ||
| 88 | +# before spending five cross-compiles on it. | ||
| 89 | +make build VERSION="${TAG}" | ||
| 90 | + | ||
| 91 | +if [ ! -f "${BUILT}" ]; then | ||
| 92 | + echo "❌ make build produced no ${BUILT}" | ||
| 93 | + exit 1 | ||
| 94 | +fi | ||
| 95 | + | ||
| 96 | +# assetName returns what the binary for a platform is called once staged. | ||
| 97 | +# Windows executables carry .exe, or Windows will not run them. | ||
| 98 | +assetName() { | ||
| 99 | + local goos=$1 goarch=$2 | ||
| 100 | + local name="turbo-python-${VERSION}-${goos}-${goarch}" | ||
| 101 | + | ||
| 102 | + if [ "${goos}" = "windows" ]; then | ||
| 103 | + name="${name}.exe" | ||
| 104 | + fi | ||
| 105 | + printf '%s\n' "${name}" | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +echo "" | ||
| 109 | +echo "🔨 Cross-compiling for ${#PLATFORMS[@]} platforms..." | ||
| 110 | + | ||
| 111 | +for platform in "${PLATFORMS[@]}"; do | ||
| 112 | + goos="${platform%/*}" | ||
| 113 | + goarch="${platform#*/}" | ||
| 114 | + asset="$(assetName "${goos}" "${goarch}")" | ||
| 115 | + | ||
| 116 | + # CGO_ENABLED=0 because there is nothing to link against on the other side | ||
| 117 | + # of a cross-compile, and this project needs no C at all: tcell and toml | ||
| 118 | + # are both pure Go. | ||
| 119 | + # | ||
| 120 | + # -trimpath keeps the paths of this machine out of a binary that goes to | ||
| 121 | + # strangers. | ||
| 122 | + # | ||
| 123 | + # -ldflags is what makes a downloaded binary agree with the release it came | ||
| 124 | + # from. Without it the Go build system names the build itself, and every | ||
| 125 | + # asset here would report "devel" while the release page says ${TAG}. | ||
| 126 | + if ! CGO_ENABLED=0 GOOS="${goos}" GOARCH="${goarch}" \ | ||
| 127 | + go build -trimpath -ldflags "${LDFLAGS}" -o "${RELEASES_DIR}/${asset}" .; then | ||
| 128 | + echo " ❌ ${platform}" | ||
| 129 | + exit 1 | ||
| 130 | + fi | ||
| 131 | + echo " ✅ ${asset}" | ||
| 132 | +done | ||
| 133 | + | ||
| 134 | +# The staged asset for this machine is the only one that can be run here, and | ||
| 135 | +# running it is the only proof that what ships carries the version rather than | ||
| 136 | +# that the flags looked right. | ||
| 137 | +# The number has to *equal* the tag, not merely appear in the output: "0.2.0" | ||
| 138 | +# is a substring of "10.2.0" and of a commit hash that happens to contain it, | ||
| 139 | +# and a stamp that is nearly right is the failure worth catching. | ||
| 140 | +HOST_ASSET="$(assetName "$(go env GOOS)" "$(go env GOARCH)")" | ||
| 141 | +if [ -x "${RELEASES_DIR}/${HOST_ASSET}" ]; then | ||
| 142 | + if ! reported="$(scripts/check-version.sh "${RELEASES_DIR}/${HOST_ASSET}" "${TAG}")"; then | ||
| 143 | + exit 1 | ||
| 144 | + fi | ||
| 145 | + echo " ✅ ${HOST_ASSET} reports ${reported}" | ||
| 146 | +fi | ||
| 147 | + | ||
| 148 | +# checksum runs whichever of the two tools this machine has: sha256sum on | ||
| 149 | +# Linux, shasum on macOS. | ||
| 150 | +checksum() { | ||
| 151 | + if command -v sha256sum >/dev/null 2>&1; then | ||
| 152 | + sha256sum "$@" | ||
| 153 | + else | ||
| 154 | + shasum -a 256 "$@" | ||
| 155 | + fi | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +# The workflow attaches SHA256SUMS beside the binaries, so it is written here. | ||
| 159 | +# One file covers every platform, which is what "sha256sum -c" expects to | ||
| 160 | +# read, and the names carry no directory so it works next to the downloads. | ||
| 161 | +(cd "${RELEASES_DIR}" && checksum turbo-python-"${VERSION}"-* >SHA256SUMS) | ||
| 162 | +echo " ✅ SHA256SUMS" | ||
| 163 | + | ||
| 164 | +# downloadTable lists the platforms as a Markdown table, so the README grows | ||
| 165 | +# and shrinks with PLATFORMS rather than repeating it by hand. | ||
| 166 | +downloadTable() { | ||
| 167 | + printf '| Platform | Download |\n|---|---|\n' | ||
| 168 | + for platform in "${PLATFORMS[@]}"; do | ||
| 169 | + local goos="${platform%/*}" goarch="${platform#*/}" | ||
| 170 | + printf '| %s | `%s` |\n' "${platform}" "$(assetName "${goos}" "${goarch}")" | ||
| 171 | + done | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +cat >"${RELEASES_DIR}/README.md" <<EOM | ||
| 175 | +# Turbo Python ${TAG} | ||
| 176 | + | ||
| 177 | +${ABOUT} | ||
| 178 | + | ||
| 179 | +Built with $(go env GOVERSION). No runtime dependencies; \`pylsp\` is optional and | ||
| 180 | +only completion and error marks need it. | ||
| 181 | + | ||
| 182 | +$(downloadTable) | ||
| 183 | + | ||
| 184 | +## Running it | ||
| 185 | + | ||
| 186 | + chmod +x turbo-python-${VERSION}-<platform> | ||
| 187 | + ./turbo-python-${VERSION}-<platform> main.py | ||
| 188 | + | ||
| 189 | +On macOS, an unsigned download is quarantined until you say otherwise: | ||
| 190 | + | ||
| 191 | + xattr -d com.apple.quarantine turbo-python-${VERSION}-darwin-arm64 | ||
| 192 | + | ||
| 193 | +## Installing from the module proxy instead | ||
| 194 | + | ||
| 195 | + go install $(go list -m)@${TAG} | ||
| 196 | + | ||
| 197 | +## Verifying the download | ||
| 198 | + | ||
| 199 | + sha256sum -c SHA256SUMS --ignore-missing # shasum -a 256 -c on macOS | ||
| 200 | + | ||
| 201 | +EOM | ||
| 202 | +echo " ✅ README.md" | ||
| 203 | + | ||
| 204 | +echo "" | ||
| 205 | +echo "✨ Build complete!" | ||
| 206 | +ls -lh "${RELEASES_DIR}" | ||
| 207 | +echo "" | ||
| 208 | +echo "💡 Nothing was published. The Release workflow runs this same script when" | ||
| 209 | +echo " ./01-release.tag.sh pushes ${TAG}, and attaches release/${TAG}/ to the release page." | ||
added
LICENSE +18 -0 | new file mode 100644 | ||
| @@ -0,0 +1,18 @@ | ||
| 1 | +MIT License | |
| 2 | + | |
| 3 | +Copyright (c) 2026 turbo-editors | |
| 4 | + | |
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and | |
| 6 | +associated documentation files (the "Software"), to deal in the Software without restriction, including | |
| 7 | +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 8 | +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the | |
| 9 | +following conditions: | |
| 10 | + | |
| 11 | +The above copyright notice and this permission notice shall be included in all copies or substantial | |
| 12 | +portions of the Software. | |
| 13 | + | |
| 14 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT | |
| 15 | +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO | |
| 16 | +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | |
| 17 | +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
| 18 | +USE OR OTHER DEALINGS IN THE SOFTWARE. | |
| new file mode 100644 | |||
| @@ -0,0 +1,18 @@ | |||
| 1 | +MIT License | ||
| 2 | + | ||
| 3 | +Copyright (c) 2026 turbo-editors | ||
| 4 | + | ||
| 5 | +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and | ||
| 6 | +associated documentation files (the "Software"), to deal in the Software without restriction, including | ||
| 7 | +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| 8 | +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the | ||
| 9 | +following conditions: | ||
| 10 | + | ||
| 11 | +The above copyright notice and this permission notice shall be included in all copies or substantial | ||
| 12 | +portions of the Software. | ||
| 13 | + | ||
| 14 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT | ||
| 15 | +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO | ||
| 16 | +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | ||
| 17 | +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
| 18 | +USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
added
Makefile +75 -0 | new file mode 100644 | ||
| @@ -0,0 +1,75 @@ | ||
| 1 | +BINARY := turbo-python | |
| 2 | +BUILD_DIR := bin | |
| 3 | + | |
| 4 | +# The version the binary reports is stamped in by the linker, so that a release | |
| 5 | +# cannot ship an About box still naming the previous one. git describe gives | |
| 6 | +# the last tag, how far past it this is, and the commit; a checkout with no | |
| 7 | +# tags, or no git at all, falls back to "devel". | |
| 8 | +VERSION_PKG := rickub.com/turbo-editors/turbo-core/version | |
| 9 | +VERSION := $(shell git describe --tags --dirty 2>/dev/null || echo devel) | |
| 10 | +COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null) | |
| 11 | +BUILT := $(shell date -u +%Y-%m-%dT%H:%M:%SZ) | |
| 12 | +LDFLAGS := -X '$(VERSION_PKG).stamp=$(VERSION)' \ | |
| 13 | + -X '$(VERSION_PKG).commit=$(COMMIT)' \ | |
| 14 | + -X '$(VERSION_PKG).built=$(BUILT)' | |
| 15 | + | |
| 16 | +.DEFAULT_GOAL := help | |
| 17 | + | |
| 18 | +## help: list the available targets | |
| 19 | +help: | |
| 20 | + @grep -E '^## ' $(MAKEFILE_LIST) | sed 's/## //' | |
| 21 | + | |
| 22 | +## test: run the whole test suite | |
| 23 | +test: | |
| 24 | + go test ./... | |
| 25 | + | |
| 26 | +## test-verbose: run the whole test suite, naming every test | |
| 27 | +test-verbose: | |
| 28 | + go test -v ./... | |
| 29 | + | |
| 30 | +## cover: run the tests and report statement coverage per package | |
| 31 | +cover: | |
| 32 | + go test -cover ./... | |
| 33 | + | |
| 34 | +## build: compile the editor into bin/turbo-python, then check it reports its version | |
| 35 | +build: | |
| 36 | + go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY) . | |
| 37 | + @scripts/check-version.sh $(BUILD_DIR)/$(BINARY) "$(VERSION)" "$(COMMIT)" | |
| 38 | + | |
| 39 | +## version: print the version this checkout would build | |
| 40 | +version: | |
| 41 | + @echo "$(VERSION) ($(COMMIT))" | |
| 42 | + | |
| 43 | +## ldflags: print the linker flags a stamped build uses | |
| 44 | +## (03-build-releases.sh reads this, so the stamp is defined once) | |
| 45 | +ldflags: | |
| 46 | + @printf '%s\n' "$(LDFLAGS)" | |
| 47 | + | |
| 48 | +## install: build and install turbo-python where your shell can find it | |
| 49 | +install: | |
| 50 | + @scripts/install.sh | |
| 51 | + | |
| 52 | +## uninstall: remove an installed turbo-python | |
| 53 | +uninstall: | |
| 54 | + @scripts/install.sh --uninstall | |
| 55 | + | |
| 56 | +## run: build and start the editor (make run FILE=main.go) | |
| 57 | +run: build | |
| 58 | + ./$(BUILD_DIR)/$(BINARY) $(FILE) | |
| 59 | + | |
| 60 | +## fmt: format every Go file in place | |
| 61 | +fmt: | |
| 62 | + go fmt ./... | |
| 63 | + | |
| 64 | +## vet: run the standard Go static checks | |
| 65 | +vet: | |
| 66 | + go vet ./... | |
| 67 | + | |
| 68 | +## check: format, vet and test — what to run before committing | |
| 69 | +check: fmt vet test | |
| 70 | + | |
| 71 | +## clean: remove build artefacts | |
| 72 | +clean: | |
| 73 | + rm -rf $(BUILD_DIR) | |
| 74 | + | |
| 75 | +.PHONY: help test test-verbose cover build version ldflags install uninstall run fmt vet check clean | |
| new file mode 100644 | |||
| @@ -0,0 +1,75 @@ | |||
| 1 | +BINARY := turbo-python | ||
| 2 | +BUILD_DIR := bin | ||
| 3 | + | ||
| 4 | +# The version the binary reports is stamped in by the linker, so that a release | ||
| 5 | +# cannot ship an About box still naming the previous one. git describe gives | ||
| 6 | +# the last tag, how far past it this is, and the commit; a checkout with no | ||
| 7 | +# tags, or no git at all, falls back to "devel". | ||
| 8 | +VERSION_PKG := rickub.com/turbo-editors/turbo-core/version | ||
| 9 | +VERSION := $(shell git describe --tags --dirty 2>/dev/null || echo devel) | ||
| 10 | +COMMIT := $(shell git rev-parse --short HEAD 2>/dev/null) | ||
| 11 | +BUILT := $(shell date -u +%Y-%m-%dT%H:%M:%SZ) | ||
| 12 | +LDFLAGS := -X '$(VERSION_PKG).stamp=$(VERSION)' \ | ||
| 13 | + -X '$(VERSION_PKG).commit=$(COMMIT)' \ | ||
| 14 | + -X '$(VERSION_PKG).built=$(BUILT)' | ||
| 15 | + | ||
| 16 | +.DEFAULT_GOAL := help | ||
| 17 | + | ||
| 18 | +## help: list the available targets | ||
| 19 | +help: | ||
| 20 | + @grep -E '^## ' $(MAKEFILE_LIST) | sed 's/## //' | ||
| 21 | + | ||
| 22 | +## test: run the whole test suite | ||
| 23 | +test: | ||
| 24 | + go test ./... | ||
| 25 | + | ||
| 26 | +## test-verbose: run the whole test suite, naming every test | ||
| 27 | +test-verbose: | ||
| 28 | + go test -v ./... | ||
| 29 | + | ||
| 30 | +## cover: run the tests and report statement coverage per package | ||
| 31 | +cover: | ||
| 32 | + go test -cover ./... | ||
| 33 | + | ||
| 34 | +## build: compile the editor into bin/turbo-python, then check it reports its version | ||
| 35 | +build: | ||
| 36 | + go build -ldflags "$(LDFLAGS)" -o $(BUILD_DIR)/$(BINARY) . | ||
| 37 | + @scripts/check-version.sh $(BUILD_DIR)/$(BINARY) "$(VERSION)" "$(COMMIT)" | ||
| 38 | + | ||
| 39 | +## version: print the version this checkout would build | ||
| 40 | +version: | ||
| 41 | + @echo "$(VERSION) ($(COMMIT))" | ||
| 42 | + | ||
| 43 | +## ldflags: print the linker flags a stamped build uses | ||
| 44 | +## (03-build-releases.sh reads this, so the stamp is defined once) | ||
| 45 | +ldflags: | ||
| 46 | + @printf '%s\n' "$(LDFLAGS)" | ||
| 47 | + | ||
| 48 | +## install: build and install turbo-python where your shell can find it | ||
| 49 | +install: | ||
| 50 | + @scripts/install.sh | ||
| 51 | + | ||
| 52 | +## uninstall: remove an installed turbo-python | ||
| 53 | +uninstall: | ||
| 54 | + @scripts/install.sh --uninstall | ||
| 55 | + | ||
| 56 | +## run: build and start the editor (make run FILE=main.go) | ||
| 57 | +run: build | ||
| 58 | + ./$(BUILD_DIR)/$(BINARY) $(FILE) | ||
| 59 | + | ||
| 60 | +## fmt: format every Go file in place | ||
| 61 | +fmt: | ||
| 62 | + go fmt ./... | ||
| 63 | + | ||
| 64 | +## vet: run the standard Go static checks | ||
| 65 | +vet: | ||
| 66 | + go vet ./... | ||
| 67 | + | ||
| 68 | +## check: format, vet and test — what to run before committing | ||
| 69 | +check: fmt vet test | ||
| 70 | + | ||
| 71 | +## clean: remove build artefacts | ||
| 72 | +clean: | ||
| 73 | + rm -rf $(BUILD_DIR) | ||
| 74 | + | ||
| 75 | +.PHONY: help test test-verbose cover build version ldflags install uninstall run fmt vet check clean | ||
added
README.md +115 -0 | new file mode 100644 | ||
| @@ -0,0 +1,115 @@ | ||
| 1 | +# turbo-python | |
| 2 | + | |
| 3 | +A Turbo C-style editor for Python, written in Go. | |
| 4 | + | |
| 5 | +Built on **[turbo-core](https://rickub.com/turbo-editors/turbo-core)**, the library every Turbo editor shares. What is in this repository is the command, the profile that says this editor is for Python, and the Python scanner — about seven hundred lines. Everything else lives in the library. | |
| 6 | + | |
| 7 | +A full-screen terminal IDE with the Borland furniture — a menu bar with hot keys, movable windows that cast shadows, modal dialogs, a clickable status bar — and the things a Python editor needs today: syntax colouring that carries triple-quoted strings across lines and tells a constant from a class, loadable colour themes, completion and diagnostics from `pylsp`, shell windows, per-project settings, a project tree, snippets, and the uv toolchain a menu away. | |
| 8 | + | |
| 9 | +``` | |
| 10 | + File Edit Search Run Code Options Window Snippets Python Help | |
| 11 | +╔═[x]═════════════════════════════ shapes.py ═══════════════════════════════1═[■]╗ | |
| 12 | +║ 1 """A demo module.""" ▲║ | |
| 13 | +║ 2 from abc import ABC, abstractmethod ▓║ | |
| 14 | +║ 3 ░║ | |
| 15 | +║ 4 ░║ | |
| 16 | +║ 5 class Shape(ABC): ░║ | |
| 17 | +║ 6 @abstractmethod ░║ | |
| 18 | +║ 7 def area(self) -> float: ... ░║ | |
| 19 | +║ 8 ░║ | |
| 20 | +║ 9 MAX_SIDES = 0x1f_ff ▼║ | |
| 21 | +║◄▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░►║ | |
| 22 | +╚════════════════════════════════════════════════════════════════════════════════╝ | |
| 23 | + F1 Describe F2 Save F3 Open F6 Window F7 Next F10 Menu 1:1 LSP: ready | |
| 24 | +``` | |
| 25 | + | |
| 26 | +## Getting started | |
| 27 | + | |
| 28 | +```bash | |
| 29 | +make install | |
| 30 | +``` | |
| 31 | + | |
| 32 | +That builds the editor, puts it where your shell looks for commands, and reports what it found — the Go version it built with, where the binary went, whether that directory is on your `PATH`, and whether `pylsp` is installed. Then, from any Python project: | |
| 33 | + | |
| 34 | +```bash | |
| 35 | +turbo-python main.py | |
| 36 | +``` | |
| 37 | + | |
| 38 | +To build without installing, `make build` leaves the binary in `bin/turbo-python`. From the module proxy instead of a checkout: `go install rickub.com/turbo-editors/turbo-python@latest`. | |
| 39 | + | |
| 40 | +For completion and diagnostics, install the Python language server as well — the editor works without it, and says so on the status bar: | |
| 41 | + | |
| 42 | +```bash | |
| 43 | +pipx install "python-lsp-server[all]" | |
| 44 | +``` | |
| 45 | + | |
| 46 | +The `[all]` is not optional if you want the gutter to show anything: the linters that produce diagnostics are extras, and without them the server has nothing to report. | |
| 47 | + | |
| 48 | +The [tutorial](docs/en/tutorials/getting-started.md) walks through a first session in about ten minutes. | |
| 49 | + | |
| 50 | +## Features | |
| 51 | + | |
| 52 | +- **Every build knows what it is** — `turbo-python -version` and **Help ▸ About** name the version, the commit and the build date, stamped in by the linker from `git describe` rather than read from a constant somebody forgot to bump | |
| 53 | +- **Turbo Vision interface** — menu bar with `Alt`-letter hot keys, overlapping movable and resizable windows, modal dialogs, mouse support throughout | |
| 54 | +- **Syntax colouring for nine languages** — Python by a hand-written scanner that carries triple-quoted strings and line continuations exactly, knows all six string prefixes, and separates `SCREAMING_SNAKE_CASE` constants from `CapWords` classes; plus TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell scripts from turbo-core | |
| 55 | +- **Themes** in TOML, eleven embedded — Borland navy, dark grey, paper white, espresso, Catppuccin Frappé and Latte, cobalt, Darcula and IntelliJ Light, and a hueless monochrome in both polarities — and any number of your own, with inheritance between files and between style keys. Every shipped theme is held to its contrast by tests | |
| 56 | +- **Per-project settings** in `.turbo-python/settings.toml` — pin a theme, turn on automatic saving — created from a menu item, never by itself, and re-read on every save so a change takes effect without a restart | |
| 57 | +- **Completion, hover, go-to-definition, references and diagnostics** from `pylsp`, entirely optional. The server is looked for in the active virtual environment, `~/.local/bin`, pyenv's shims and macOS' per-version script directories as well as on `PATH` | |
| 58 | +- **Terminal windows** — `F8` opens a real shell in a window, with its own VT/ANSI emulator, scrollback and job control (Linux, macOS and Windows) | |
| 59 | +- **Project tree** — `F9` shows the project's files in a window; walk it with the arrows and press Enter to open one | |
| 60 | +- **Snippets** — a `Snippets` menu built from `.turbo-python/snippets.toml`, grouped into submenus and filtered by the file you are in; the chosen text is inserted at the cursor, re-indented to match — which in Python is a correctness matter and not a nicety | |
| 61 | +- **The uv toolchain a menu away** — `Alt-P` runs `uv venv`, `uv sync`, `ruff format`, `ruff check`, `pytest` and your script from `.turbo-python/tools.toml`, each showing its output where the tool asked: a popup that fills in as it goes, a terminal window, or an editing window to search. Files the command rewrote are re-read for you, and a tool naming a `menu` of its own gets that menu on the bar | |
| 62 | +- **Editing** with word movement, block indent, a shared clipboard, and undo that merges a run of typing into one step | |
| 63 | +- **Faithful files** — line endings and the trailing newline are preserved, and saving is atomic | |
| 64 | +- **Automatic saving**, off by default, writing a short while after you stop typing | |
| 65 | + | |
| 66 | +## Commands | |
| 67 | + | |
| 68 | +| Command | What it does | | |
| 69 | +| --- | --- | | |
| 70 | +| `make install` | Build and install onto your `PATH` | | |
| 71 | +| `make build` | Compile into `bin/turbo-python` | | |
| 72 | +| `make test` | Run the whole test suite | | |
| 73 | +| `make check` | `fmt`, `vet`, then the tests — what a commit should pass | | |
| 74 | +| `make run FILE=x.py` | Build and start the editor on a file | | |
| 75 | +| `make help` | List every target | | |
| 76 | + | |
| 77 | +```bash | |
| 78 | +turbo-python [-theme name] [-no-lsp] [file...] | |
| 79 | +turbo-python -list-themes | |
| 80 | +``` | |
| 81 | + | |
| 82 | +## Documentation | |
| 83 | + | |
| 84 | +Full documentation in **[English](docs/en/)** and **[French](docs/fr/)**, organised by the [Diátaxis](https://diataxis.fr) method: | |
| 85 | + | |
| 86 | +| | | | |
| 87 | +| --- | --- | | |
| 88 | +| **Tutorial** | [Your first file in Turbo Python](docs/en/tutorials/getting-started.md) | | |
| 89 | +| **How-to** | [install](docs/en/how-to/install.md) · [run the tests](docs/en/how-to/run-the-tests.md) · [enable completion](docs/en/how-to/enable-completion.md) · [write a theme](docs/en/how-to/write-a-theme.md) · [move around a file](docs/en/how-to/navigate-code.md) · [ask about code](docs/en/how-to/ask-about-code.md) · [use a terminal](docs/en/how-to/use-a-terminal.md) · [configure a project](docs/en/how-to/configure-a-project.md) · [browse a project](docs/en/how-to/browse-a-project.md) · [use snippets](docs/en/how-to/use-snippets.md) · [run uv commands](docs/en/how-to/run-uv-commands.md) · [make a release](docs/en/how-to/make-a-release.md) | | |
| 90 | +| **Reference** | [command line](docs/en/reference/cli.md) · [keyboard](docs/en/reference/keyboard.md) · [menus](docs/en/reference/menus.md) · [theme format](docs/en/reference/themes.md) · [terminal windows](docs/en/reference/terminal.md) · [project settings](docs/en/reference/project-settings.md) · [project tree](docs/en/reference/project-tree.md) · [languages](docs/en/reference/languages.md) · [snippets](docs/en/reference/snippets.md) · [Python tools](docs/en/reference/python-tools.md) · [the version number](docs/en/reference/versioning.md) | | |
| 91 | +| **Explanation** | [architecture](docs/en/explanation/architecture.md) · [design decisions](docs/en/explanation/design-decisions.md) · [colouring and completion](docs/en/explanation/colouring-and-completion.md) · [terminal windows](docs/en/explanation/terminal-windows.md) · [project settings](docs/en/explanation/project-settings.md) · [project tree](docs/en/explanation/project-tree.md) · [snippets](docs/en/explanation/snippets.md) · [Python tools](docs/en/explanation/python-tools.md) | | |
| 92 | + | |
| 93 | +The library's packages each carry their own `README.md` beside the code, in [turbo-core](https://rickub.com/turbo-editors/turbo-core). | |
| 94 | + | |
| 95 | +## Where the code is | |
| 96 | + | |
| 97 | +| | | | |
| 98 | +| --- | --- | | |
| 99 | +| `main.go` | flags, the terminal, the wiring | | |
| 100 | +| `internal/pythonlang` | the profile, the Python scanner, the three starter files | | |
| 101 | +| everything else | [turbo-core](https://rickub.com/turbo-editors/turbo-core) | | |
| 102 | + | |
| 103 | +The dependency graph is drawn in [`docs/diagrams/packages.drawio`](docs/diagrams/packages.drawio), checked against `go list` by `diagram_test.go`. | |
| 104 | + | |
| 105 | +## Design in one line | |
| 106 | + | |
| 107 | +Two dependencies — `tcell/v2` and `BurntSushi/toml` — and everything else from the standard library, including the scanner toolkit and the Language Server Protocol client. Both come through turbo-core; this repository adds none of its own. The [design decisions](docs/en/explanation/design-decisions.md) page explains why. | |
| 108 | + | |
| 109 | +## Requirements | |
| 110 | + | |
| 111 | +Go 1.26 or later to build it — the editor is written in Go even though it is an editor for Python. A terminal with mouse reporting, which is all of them. `pylsp` is optional. | |
| 112 | + | |
| 113 | +## Licence | |
| 114 | + | |
| 115 | +See [LICENSE](LICENSE). | |
| new file mode 100644 | |||
| @@ -0,0 +1,115 @@ | |||
| 1 | +# turbo-python | ||
| 2 | + | ||
| 3 | +A Turbo C-style editor for Python, written in Go. | ||
| 4 | + | ||
| 5 | +Built on **[turbo-core](https://rickub.com/turbo-editors/turbo-core)**, the library every Turbo editor shares. What is in this repository is the command, the profile that says this editor is for Python, and the Python scanner — about seven hundred lines. Everything else lives in the library. | ||
| 6 | + | ||
| 7 | +A full-screen terminal IDE with the Borland furniture — a menu bar with hot keys, movable windows that cast shadows, modal dialogs, a clickable status bar — and the things a Python editor needs today: syntax colouring that carries triple-quoted strings across lines and tells a constant from a class, loadable colour themes, completion and diagnostics from `pylsp`, shell windows, per-project settings, a project tree, snippets, and the uv toolchain a menu away. | ||
| 8 | + | ||
| 9 | +``` | ||
| 10 | + File Edit Search Run Code Options Window Snippets Python Help | ||
| 11 | +╔═[x]═════════════════════════════ shapes.py ═══════════════════════════════1═[■]╗ | ||
| 12 | +║ 1 """A demo module.""" ▲║ | ||
| 13 | +║ 2 from abc import ABC, abstractmethod ▓║ | ||
| 14 | +║ 3 ░║ | ||
| 15 | +║ 4 ░║ | ||
| 16 | +║ 5 class Shape(ABC): ░║ | ||
| 17 | +║ 6 @abstractmethod ░║ | ||
| 18 | +║ 7 def area(self) -> float: ... ░║ | ||
| 19 | +║ 8 ░║ | ||
| 20 | +║ 9 MAX_SIDES = 0x1f_ff ▼║ | ||
| 21 | +║◄▓░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░►║ | ||
| 22 | +╚════════════════════════════════════════════════════════════════════════════════╝ | ||
| 23 | + F1 Describe F2 Save F3 Open F6 Window F7 Next F10 Menu 1:1 LSP: ready | ||
| 24 | +``` | ||
| 25 | + | ||
| 26 | +## Getting started | ||
| 27 | + | ||
| 28 | +```bash | ||
| 29 | +make install | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +That builds the editor, puts it where your shell looks for commands, and reports what it found — the Go version it built with, where the binary went, whether that directory is on your `PATH`, and whether `pylsp` is installed. Then, from any Python project: | ||
| 33 | + | ||
| 34 | +```bash | ||
| 35 | +turbo-python main.py | ||
| 36 | +``` | ||
| 37 | + | ||
| 38 | +To build without installing, `make build` leaves the binary in `bin/turbo-python`. From the module proxy instead of a checkout: `go install rickub.com/turbo-editors/turbo-python@latest`. | ||
| 39 | + | ||
| 40 | +For completion and diagnostics, install the Python language server as well — the editor works without it, and says so on the status bar: | ||
| 41 | + | ||
| 42 | +```bash | ||
| 43 | +pipx install "python-lsp-server[all]" | ||
| 44 | +``` | ||
| 45 | + | ||
| 46 | +The `[all]` is not optional if you want the gutter to show anything: the linters that produce diagnostics are extras, and without them the server has nothing to report. | ||
| 47 | + | ||
| 48 | +The [tutorial](docs/en/tutorials/getting-started.md) walks through a first session in about ten minutes. | ||
| 49 | + | ||
| 50 | +## Features | ||
| 51 | + | ||
| 52 | +- **Every build knows what it is** — `turbo-python -version` and **Help ▸ About** name the version, the commit and the build date, stamped in by the linker from `git describe` rather than read from a constant somebody forgot to bump | ||
| 53 | +- **Turbo Vision interface** — menu bar with `Alt`-letter hot keys, overlapping movable and resizable windows, modal dialogs, mouse support throughout | ||
| 54 | +- **Syntax colouring for nine languages** — Python by a hand-written scanner that carries triple-quoted strings and line continuations exactly, knows all six string prefixes, and separates `SCREAMING_SNAKE_CASE` constants from `CapWords` classes; plus TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell scripts from turbo-core | ||
| 55 | +- **Themes** in TOML, eleven embedded — Borland navy, dark grey, paper white, espresso, Catppuccin Frappé and Latte, cobalt, Darcula and IntelliJ Light, and a hueless monochrome in both polarities — and any number of your own, with inheritance between files and between style keys. Every shipped theme is held to its contrast by tests | ||
| 56 | +- **Per-project settings** in `.turbo-python/settings.toml` — pin a theme, turn on automatic saving — created from a menu item, never by itself, and re-read on every save so a change takes effect without a restart | ||
| 57 | +- **Completion, hover, go-to-definition, references and diagnostics** from `pylsp`, entirely optional. The server is looked for in the active virtual environment, `~/.local/bin`, pyenv's shims and macOS' per-version script directories as well as on `PATH` | ||
| 58 | +- **Terminal windows** — `F8` opens a real shell in a window, with its own VT/ANSI emulator, scrollback and job control (Linux, macOS and Windows) | ||
| 59 | +- **Project tree** — `F9` shows the project's files in a window; walk it with the arrows and press Enter to open one | ||
| 60 | +- **Snippets** — a `Snippets` menu built from `.turbo-python/snippets.toml`, grouped into submenus and filtered by the file you are in; the chosen text is inserted at the cursor, re-indented to match — which in Python is a correctness matter and not a nicety | ||
| 61 | +- **The uv toolchain a menu away** — `Alt-P` runs `uv venv`, `uv sync`, `ruff format`, `ruff check`, `pytest` and your script from `.turbo-python/tools.toml`, each showing its output where the tool asked: a popup that fills in as it goes, a terminal window, or an editing window to search. Files the command rewrote are re-read for you, and a tool naming a `menu` of its own gets that menu on the bar | ||
| 62 | +- **Editing** with word movement, block indent, a shared clipboard, and undo that merges a run of typing into one step | ||
| 63 | +- **Faithful files** — line endings and the trailing newline are preserved, and saving is atomic | ||
| 64 | +- **Automatic saving**, off by default, writing a short while after you stop typing | ||
| 65 | + | ||
| 66 | +## Commands | ||
| 67 | + | ||
| 68 | +| Command | What it does | | ||
| 69 | +| --- | --- | | ||
| 70 | +| `make install` | Build and install onto your `PATH` | | ||
| 71 | +| `make build` | Compile into `bin/turbo-python` | | ||
| 72 | +| `make test` | Run the whole test suite | | ||
| 73 | +| `make check` | `fmt`, `vet`, then the tests — what a commit should pass | | ||
| 74 | +| `make run FILE=x.py` | Build and start the editor on a file | | ||
| 75 | +| `make help` | List every target | | ||
| 76 | + | ||
| 77 | +```bash | ||
| 78 | +turbo-python [-theme name] [-no-lsp] [file...] | ||
| 79 | +turbo-python -list-themes | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +## Documentation | ||
| 83 | + | ||
| 84 | +Full documentation in **[English](docs/en/)** and **[French](docs/fr/)**, organised by the [Diátaxis](https://diataxis.fr) method: | ||
| 85 | + | ||
| 86 | +| | | | ||
| 87 | +| --- | --- | | ||
| 88 | +| **Tutorial** | [Your first file in Turbo Python](docs/en/tutorials/getting-started.md) | | ||
| 89 | +| **How-to** | [install](docs/en/how-to/install.md) · [run the tests](docs/en/how-to/run-the-tests.md) · [enable completion](docs/en/how-to/enable-completion.md) · [write a theme](docs/en/how-to/write-a-theme.md) · [move around a file](docs/en/how-to/navigate-code.md) · [ask about code](docs/en/how-to/ask-about-code.md) · [use a terminal](docs/en/how-to/use-a-terminal.md) · [configure a project](docs/en/how-to/configure-a-project.md) · [browse a project](docs/en/how-to/browse-a-project.md) · [use snippets](docs/en/how-to/use-snippets.md) · [run uv commands](docs/en/how-to/run-uv-commands.md) · [make a release](docs/en/how-to/make-a-release.md) | | ||
| 90 | +| **Reference** | [command line](docs/en/reference/cli.md) · [keyboard](docs/en/reference/keyboard.md) · [menus](docs/en/reference/menus.md) · [theme format](docs/en/reference/themes.md) · [terminal windows](docs/en/reference/terminal.md) · [project settings](docs/en/reference/project-settings.md) · [project tree](docs/en/reference/project-tree.md) · [languages](docs/en/reference/languages.md) · [snippets](docs/en/reference/snippets.md) · [Python tools](docs/en/reference/python-tools.md) · [the version number](docs/en/reference/versioning.md) | | ||
| 91 | +| **Explanation** | [architecture](docs/en/explanation/architecture.md) · [design decisions](docs/en/explanation/design-decisions.md) · [colouring and completion](docs/en/explanation/colouring-and-completion.md) · [terminal windows](docs/en/explanation/terminal-windows.md) · [project settings](docs/en/explanation/project-settings.md) · [project tree](docs/en/explanation/project-tree.md) · [snippets](docs/en/explanation/snippets.md) · [Python tools](docs/en/explanation/python-tools.md) | | ||
| 92 | + | ||
| 93 | +The library's packages each carry their own `README.md` beside the code, in [turbo-core](https://rickub.com/turbo-editors/turbo-core). | ||
| 94 | + | ||
| 95 | +## Where the code is | ||
| 96 | + | ||
| 97 | +| | | | ||
| 98 | +| --- | --- | | ||
| 99 | +| `main.go` | flags, the terminal, the wiring | | ||
| 100 | +| `internal/pythonlang` | the profile, the Python scanner, the three starter files | | ||
| 101 | +| everything else | [turbo-core](https://rickub.com/turbo-editors/turbo-core) | | ||
| 102 | + | ||
| 103 | +The dependency graph is drawn in [`docs/diagrams/packages.drawio`](docs/diagrams/packages.drawio), checked against `go list` by `diagram_test.go`. | ||
| 104 | + | ||
| 105 | +## Design in one line | ||
| 106 | + | ||
| 107 | +Two dependencies — `tcell/v2` and `BurntSushi/toml` — and everything else from the standard library, including the scanner toolkit and the Language Server Protocol client. Both come through turbo-core; this repository adds none of its own. The [design decisions](docs/en/explanation/design-decisions.md) page explains why. | ||
| 108 | + | ||
| 109 | +## Requirements | ||
| 110 | + | ||
| 111 | +Go 1.26 or later to build it — the editor is written in Go even though it is an editor for Python. A terminal with mouse reporting, which is all of them. `pylsp` is optional. | ||
| 112 | + | ||
| 113 | +## Licence | ||
| 114 | + | ||
| 115 | +See [LICENSE](LICENSE). | ||
added
diagram_test.go +201 -0 | new file mode 100644 | ||
| @@ -0,0 +1,201 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "encoding/xml" | |
| 5 | + "html" | |
| 6 | + "os" | |
| 7 | + "os/exec" | |
| 8 | + "regexp" | |
| 9 | + "sort" | |
| 10 | + "strings" | |
| 11 | + "testing" | |
| 12 | +) | |
| 13 | + | |
| 14 | +// The package diagram is drawn by hand and read by people, so nothing in the | |
| 15 | +// build notices when it stops describing the code. It started as Turbo Rust's | |
| 16 | +// and shipped naming internal/rustlang and "the Rust scanner" — an error no | |
| 17 | +// test could see, because a diagram is a file nothing imports. | |
| 18 | +// | |
| 19 | +// These tests hold it to `go list`: the boxes are the packages this module | |
| 20 | +// actually imports, and the arrows between the two boxes that are ours are the | |
| 21 | +// imports that really exist. | |
| 22 | + | |
| 23 | +// diagramFile is the drawio the documentation links to. | |
| 24 | +const diagramFile = "docs/diagrams/packages.drawio" | |
| 25 | + | |
| 26 | +// mxFile is as much of drawio's format as these tests need: every cell, with | |
| 27 | +// its label, and — for an arrow — the two cells it joins. | |
| 28 | +type mxFile struct { | |
| 29 | + Host string `xml:"host,attr"` | |
| 30 | + Cells []mxCell `xml:"diagram>mxGraphModel>root>mxCell"` | |
| 31 | +} | |
| 32 | + | |
| 33 | +type mxCell struct { | |
| 34 | + ID string `xml:"id,attr"` | |
| 35 | + Value string `xml:"value,attr"` | |
| 36 | + Edge string `xml:"edge,attr"` | |
| 37 | + Source string `xml:"source,attr"` | |
| 38 | + Target string `xml:"target,attr"` | |
| 39 | +} | |
| 40 | + | |
| 41 | +// boldLabel is the package name inside a box: drawio stores the label as | |
| 42 | +// escaped HTML, and the name is the part in bold. | |
| 43 | +var boldLabel = regexp.MustCompile(`(?s)<b>(.*?)</b>`) | |
| 44 | + | |
| 45 | +// readDiagram parses the diagram, failing the test rather than returning an | |
| 46 | +// error — a diagram that will not parse is not a case any caller can handle. | |
| 47 | +func readDiagram(t *testing.T) mxFile { | |
| 48 | + t.Helper() | |
| 49 | + | |
| 50 | + raw, err := os.ReadFile(diagramFile) | |
| 51 | + if err != nil { | |
| 52 | + t.Fatalf("reading %s: %v", diagramFile, err) | |
| 53 | + } | |
| 54 | + | |
| 55 | + var file mxFile | |
| 56 | + if err := xml.Unmarshal(raw, &file); err != nil { | |
| 57 | + t.Fatalf("parsing %s: %v", diagramFile, err) | |
| 58 | + } | |
| 59 | + return file | |
| 60 | +} | |
| 61 | + | |
| 62 | +// boxes maps each box's package name to the id the arrows use for it. | |
| 63 | +func boxes(t *testing.T, file mxFile) map[string]string { | |
| 64 | + t.Helper() | |
| 65 | + | |
| 66 | + found := map[string]string{} | |
| 67 | + for _, cell := range file.Cells { | |
| 68 | + if cell.Edge == "1" || cell.Value == "" { | |
| 69 | + continue | |
| 70 | + } | |
| 71 | + label := html.UnescapeString(cell.Value) | |
| 72 | + // A box's package name is the part in bold, where there is one; the | |
| 73 | + // third-party box carries its name plain, with nothing to tell apart | |
| 74 | + // from it. | |
| 75 | + if match := boldLabel.FindStringSubmatch(label); match != nil { | |
| 76 | + label = match[1] | |
| 77 | + } | |
| 78 | + found[label] = cell.ID | |
| 79 | + } | |
| 80 | + return found | |
| 81 | +} | |
| 82 | + | |
| 83 | +// imports asks the toolchain what a package imports, shortened to the names the | |
| 84 | +// diagram uses: the last element for a turbo-core package, the module-relative | |
| 85 | +// path for one of ours, and "tcell/v2" for the one third-party dependency. | |
| 86 | +func imports(t *testing.T, pkg string) []string { | |
| 87 | + t.Helper() | |
| 88 | + | |
| 89 | + out, err := exec.Command("go", "list", "-f", `{{join .Imports "\n"}}`, pkg).Output() | |
| 90 | + if err != nil { | |
| 91 | + t.Fatalf("go list %s: %v", pkg, err) | |
| 92 | + } | |
| 93 | + | |
| 94 | + var names []string | |
| 95 | + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { | |
| 96 | + switch { | |
| 97 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-core/"): | |
| 98 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-core/")) | |
| 99 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-python/"): | |
| 100 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-python/")) | |
| 101 | + case strings.HasPrefix(line, "github.com/gdamore/tcell/"): | |
| 102 | + names = append(names, "tcell/v2") | |
| 103 | + } | |
| 104 | + } | |
| 105 | + sort.Strings(names) | |
| 106 | + return names | |
| 107 | +} | |
| 108 | + | |
| 109 | +// The boxes are exactly the packages the two packages of this module import, | |
| 110 | +// plus the two packages themselves. A box for a package nothing imports is as | |
| 111 | +// wrong as a missing one: both tell a reader something untrue about the code. | |
| 112 | +func TestTheDiagramDrawsExactlyThePackagesThisModuleImports(t *testing.T) { | |
| 113 | + drawn := boxes(t, readDiagram(t)) | |
| 114 | + | |
| 115 | + want := map[string]bool{"main": true, "internal/pythonlang": true} | |
| 116 | + for _, pkg := range append(imports(t, "."), imports(t, "./internal/pythonlang")...) { | |
| 117 | + want[pkg] = true | |
| 118 | + } | |
| 119 | + | |
| 120 | + for name := range want { | |
| 121 | + if _, ok := drawn[name]; !ok { | |
| 122 | + t.Errorf("%s draws no box for %q", diagramFile, name) | |
| 123 | + } | |
| 124 | + } | |
| 125 | + for name := range drawn { | |
| 126 | + if !want[name] { | |
| 127 | + t.Errorf("%s draws a box for %q, which nothing in this module imports", diagramFile, name) | |
| 128 | + } | |
| 129 | + } | |
| 130 | +} | |
| 131 | + | |
| 132 | +// Every arrow leaving one of our two boxes is an import that exists. This is | |
| 133 | +// the half that caught the copied diagram: an arrow drawn out of a box labelled | |
| 134 | +// internal/rustlang cannot be checked at all until the box is named right. | |
| 135 | +func TestEveryArrowOutOfOurPackagesIsARealImport(t *testing.T) { | |
| 136 | + file := readDiagram(t) | |
| 137 | + drawn := boxes(t, file) | |
| 138 | + | |
| 139 | + byID := map[string]string{} | |
| 140 | + for name, id := range drawn { | |
| 141 | + byID[id] = name | |
| 142 | + } | |
| 143 | + | |
| 144 | + ours := map[string]string{"main": ".", "internal/pythonlang": "./internal/pythonlang"} | |
| 145 | + for _, cell := range file.Cells { | |
| 146 | + if cell.Edge != "1" { | |
| 147 | + continue | |
| 148 | + } | |
| 149 | + from, ok := byID[cell.Source] | |
| 150 | + if !ok { | |
| 151 | + t.Errorf("%s draws an arrow out of unknown cell %q", diagramFile, cell.Source) | |
| 152 | + continue | |
| 153 | + } | |
| 154 | + pkg, ok := ours[from] | |
| 155 | + if !ok { | |
| 156 | + continue | |
| 157 | + } | |
| 158 | + | |
| 159 | + to := byID[cell.Target] | |
| 160 | + if to == "internal/pythonlang" && from == "main" { | |
| 161 | + continue // main imports it under its full path, already shortened | |
| 162 | + } | |
| 163 | + if !slicesContain(imports(t, pkg), to) { | |
| 164 | + t.Errorf("%s draws %s → %s, but %s imports no such package", diagramFile, from, to, from) | |
| 165 | + } | |
| 166 | + } | |
| 167 | +} | |
| 168 | + | |
| 169 | +// The file's host attribute names the project it was drawn for. It is the one | |
| 170 | +// field a reader never sees and a copy always keeps. | |
| 171 | +func TestTheDiagramSaysWhichProjectItWasDrawnFor(t *testing.T) { | |
| 172 | + if host := readDiagram(t).Host; host != "turbo-python" { | |
| 173 | + t.Errorf("%s was drawn for %q, not turbo-python", diagramFile, host) | |
| 174 | + } | |
| 175 | +} | |
| 176 | + | |
| 177 | +// No label anywhere in the diagram names another editor in the family, or the | |
| 178 | +// language it edits. The copied diagram said "the Rust scanner" in prose that | |
| 179 | +// no identifier check would have looked at. | |
| 180 | +func TestNoLabelInTheDiagramNamesAnotherEditorsLanguage(t *testing.T) { | |
| 181 | + for _, cell := range readDiagram(t).Cells { | |
| 182 | + label := html.UnescapeString(cell.Value) | |
| 183 | + for _, other := range []string{"rustlang", "golang", "Rust", "Go ", "turbo-rust", "turbo-go"} { | |
| 184 | + if strings.Contains(label, other) { | |
| 185 | + t.Errorf("%s labels a cell %q, which names %q", diagramFile, label, other) | |
| 186 | + } | |
| 187 | + } | |
| 188 | + } | |
| 189 | +} | |
| 190 | + | |
| 191 | +// slicesContain says whether a sorted list holds a value. It is here rather | |
| 192 | +// than from the standard library's slices package so the test reads the same | |
| 193 | +// way in a checkout of any Go version this module supports. | |
| 194 | +func slicesContain(list []string, want string) bool { | |
| 195 | + for _, got := range list { | |
| 196 | + if got == want { | |
| 197 | + return true | |
| 198 | + } | |
| 199 | + } | |
| 200 | + return false | |
| 201 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,201 @@ | |||
| 1 | +package main | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "encoding/xml" | ||
| 5 | + "html" | ||
| 6 | + "os" | ||
| 7 | + "os/exec" | ||
| 8 | + "regexp" | ||
| 9 | + "sort" | ||
| 10 | + "strings" | ||
| 11 | + "testing" | ||
| 12 | +) | ||
| 13 | + | ||
| 14 | +// The package diagram is drawn by hand and read by people, so nothing in the | ||
| 15 | +// build notices when it stops describing the code. It started as Turbo Rust's | ||
| 16 | +// and shipped naming internal/rustlang and "the Rust scanner" — an error no | ||
| 17 | +// test could see, because a diagram is a file nothing imports. | ||
| 18 | +// | ||
| 19 | +// These tests hold it to `go list`: the boxes are the packages this module | ||
| 20 | +// actually imports, and the arrows between the two boxes that are ours are the | ||
| 21 | +// imports that really exist. | ||
| 22 | + | ||
| 23 | +// diagramFile is the drawio the documentation links to. | ||
| 24 | +const diagramFile = "docs/diagrams/packages.drawio" | ||
| 25 | + | ||
| 26 | +// mxFile is as much of drawio's format as these tests need: every cell, with | ||
| 27 | +// its label, and — for an arrow — the two cells it joins. | ||
| 28 | +type mxFile struct { | ||
| 29 | + Host string `xml:"host,attr"` | ||
| 30 | + Cells []mxCell `xml:"diagram>mxGraphModel>root>mxCell"` | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +type mxCell struct { | ||
| 34 | + ID string `xml:"id,attr"` | ||
| 35 | + Value string `xml:"value,attr"` | ||
| 36 | + Edge string `xml:"edge,attr"` | ||
| 37 | + Source string `xml:"source,attr"` | ||
| 38 | + Target string `xml:"target,attr"` | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +// boldLabel is the package name inside a box: drawio stores the label as | ||
| 42 | +// escaped HTML, and the name is the part in bold. | ||
| 43 | +var boldLabel = regexp.MustCompile(`(?s)<b>(.*?)</b>`) | ||
| 44 | + | ||
| 45 | +// readDiagram parses the diagram, failing the test rather than returning an | ||
| 46 | +// error — a diagram that will not parse is not a case any caller can handle. | ||
| 47 | +func readDiagram(t *testing.T) mxFile { | ||
| 48 | + t.Helper() | ||
| 49 | + | ||
| 50 | + raw, err := os.ReadFile(diagramFile) | ||
| 51 | + if err != nil { | ||
| 52 | + t.Fatalf("reading %s: %v", diagramFile, err) | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + var file mxFile | ||
| 56 | + if err := xml.Unmarshal(raw, &file); err != nil { | ||
| 57 | + t.Fatalf("parsing %s: %v", diagramFile, err) | ||
| 58 | + } | ||
| 59 | + return file | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +// boxes maps each box's package name to the id the arrows use for it. | ||
| 63 | +func boxes(t *testing.T, file mxFile) map[string]string { | ||
| 64 | + t.Helper() | ||
| 65 | + | ||
| 66 | + found := map[string]string{} | ||
| 67 | + for _, cell := range file.Cells { | ||
| 68 | + if cell.Edge == "1" || cell.Value == "" { | ||
| 69 | + continue | ||
| 70 | + } | ||
| 71 | + label := html.UnescapeString(cell.Value) | ||
| 72 | + // A box's package name is the part in bold, where there is one; the | ||
| 73 | + // third-party box carries its name plain, with nothing to tell apart | ||
| 74 | + // from it. | ||
| 75 | + if match := boldLabel.FindStringSubmatch(label); match != nil { | ||
| 76 | + label = match[1] | ||
| 77 | + } | ||
| 78 | + found[label] = cell.ID | ||
| 79 | + } | ||
| 80 | + return found | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +// imports asks the toolchain what a package imports, shortened to the names the | ||
| 84 | +// diagram uses: the last element for a turbo-core package, the module-relative | ||
| 85 | +// path for one of ours, and "tcell/v2" for the one third-party dependency. | ||
| 86 | +func imports(t *testing.T, pkg string) []string { | ||
| 87 | + t.Helper() | ||
| 88 | + | ||
| 89 | + out, err := exec.Command("go", "list", "-f", `{{join .Imports "\n"}}`, pkg).Output() | ||
| 90 | + if err != nil { | ||
| 91 | + t.Fatalf("go list %s: %v", pkg, err) | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + var names []string | ||
| 95 | + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { | ||
| 96 | + switch { | ||
| 97 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-core/"): | ||
| 98 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-core/")) | ||
| 99 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-python/"): | ||
| 100 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-python/")) | ||
| 101 | + case strings.HasPrefix(line, "github.com/gdamore/tcell/"): | ||
| 102 | + names = append(names, "tcell/v2") | ||
| 103 | + } | ||
| 104 | + } | ||
| 105 | + sort.Strings(names) | ||
| 106 | + return names | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +// The boxes are exactly the packages the two packages of this module import, | ||
| 110 | +// plus the two packages themselves. A box for a package nothing imports is as | ||
| 111 | +// wrong as a missing one: both tell a reader something untrue about the code. | ||
| 112 | +func TestTheDiagramDrawsExactlyThePackagesThisModuleImports(t *testing.T) { | ||
| 113 | + drawn := boxes(t, readDiagram(t)) | ||
| 114 | + | ||
| 115 | + want := map[string]bool{"main": true, "internal/pythonlang": true} | ||
| 116 | + for _, pkg := range append(imports(t, "."), imports(t, "./internal/pythonlang")...) { | ||
| 117 | + want[pkg] = true | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + for name := range want { | ||
| 121 | + if _, ok := drawn[name]; !ok { | ||
| 122 | + t.Errorf("%s draws no box for %q", diagramFile, name) | ||
| 123 | + } | ||
| 124 | + } | ||
| 125 | + for name := range drawn { | ||
| 126 | + if !want[name] { | ||
| 127 | + t.Errorf("%s draws a box for %q, which nothing in this module imports", diagramFile, name) | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +// Every arrow leaving one of our two boxes is an import that exists. This is | ||
| 133 | +// the half that caught the copied diagram: an arrow drawn out of a box labelled | ||
| 134 | +// internal/rustlang cannot be checked at all until the box is named right. | ||
| 135 | +func TestEveryArrowOutOfOurPackagesIsARealImport(t *testing.T) { | ||
| 136 | + file := readDiagram(t) | ||
| 137 | + drawn := boxes(t, file) | ||
| 138 | + | ||
| 139 | + byID := map[string]string{} | ||
| 140 | + for name, id := range drawn { | ||
| 141 | + byID[id] = name | ||
| 142 | + } | ||
| 143 | + | ||
| 144 | + ours := map[string]string{"main": ".", "internal/pythonlang": "./internal/pythonlang"} | ||
| 145 | + for _, cell := range file.Cells { | ||
| 146 | + if cell.Edge != "1" { | ||
| 147 | + continue | ||
| 148 | + } | ||
| 149 | + from, ok := byID[cell.Source] | ||
| 150 | + if !ok { | ||
| 151 | + t.Errorf("%s draws an arrow out of unknown cell %q", diagramFile, cell.Source) | ||
| 152 | + continue | ||
| 153 | + } | ||
| 154 | + pkg, ok := ours[from] | ||
| 155 | + if !ok { | ||
| 156 | + continue | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + to := byID[cell.Target] | ||
| 160 | + if to == "internal/pythonlang" && from == "main" { | ||
| 161 | + continue // main imports it under its full path, already shortened | ||
| 162 | + } | ||
| 163 | + if !slicesContain(imports(t, pkg), to) { | ||
| 164 | + t.Errorf("%s draws %s → %s, but %s imports no such package", diagramFile, from, to, from) | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +// The file's host attribute names the project it was drawn for. It is the one | ||
| 170 | +// field a reader never sees and a copy always keeps. | ||
| 171 | +func TestTheDiagramSaysWhichProjectItWasDrawnFor(t *testing.T) { | ||
| 172 | + if host := readDiagram(t).Host; host != "turbo-python" { | ||
| 173 | + t.Errorf("%s was drawn for %q, not turbo-python", diagramFile, host) | ||
| 174 | + } | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +// No label anywhere in the diagram names another editor in the family, or the | ||
| 178 | +// language it edits. The copied diagram said "the Rust scanner" in prose that | ||
| 179 | +// no identifier check would have looked at. | ||
| 180 | +func TestNoLabelInTheDiagramNamesAnotherEditorsLanguage(t *testing.T) { | ||
| 181 | + for _, cell := range readDiagram(t).Cells { | ||
| 182 | + label := html.UnescapeString(cell.Value) | ||
| 183 | + for _, other := range []string{"rustlang", "golang", "Rust", "Go ", "turbo-rust", "turbo-go"} { | ||
| 184 | + if strings.Contains(label, other) { | ||
| 185 | + t.Errorf("%s labels a cell %q, which names %q", diagramFile, label, other) | ||
| 186 | + } | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | +} | ||
| 190 | + | ||
| 191 | +// slicesContain says whether a sorted list holds a value. It is here rather | ||
| 192 | +// than from the standard library's slices package so the test reads the same | ||
| 193 | +// way in a checkout of any Go version this module supports. | ||
| 194 | +func slicesContain(list []string, want string) bool { | ||
| 195 | + for _, got := range list { | ||
| 196 | + if got == want { | ||
| 197 | + return true | ||
| 198 | + } | ||
| 199 | + } | ||
| 200 | + return false | ||
| 201 | +} | ||
added
docs/README.md +10 -0 | new file mode 100644 | ||
| @@ -0,0 +1,10 @@ | ||
| 1 | +# Turbo Python — documentation | |
| 2 | + | |
| 3 | +Choose your language / Choisissez votre langue : | |
| 4 | + | |
| 5 | +- 🇬🇧 **[English](en/)** | |
| 6 | +- 🇫🇷 **[Français](fr/)** | |
| 7 | + | |
| 8 | +Both are complete and organised the same way, following the [Diátaxis](https://diataxis.fr) method: tutorials, how-to guides, reference, explanation. | |
| 9 | + | |
| 10 | +The [package dependency diagram](diagrams/packages.drawio) is language-neutral and shared by both. | |
| new file mode 100644 | |||
| @@ -0,0 +1,10 @@ | |||
| 1 | +# Turbo Python — documentation | ||
| 2 | + | ||
| 3 | +Choose your language / Choisissez votre langue : | ||
| 4 | + | ||
| 5 | +- 🇬🇧 **[English](en/)** | ||
| 6 | +- 🇫🇷 **[Français](fr/)** | ||
| 7 | + | ||
| 8 | +Both are complete and organised the same way, following the [Diátaxis](https://diataxis.fr) method: tutorials, how-to guides, reference, explanation. | ||
| 9 | + | ||
| 10 | +The [package dependency diagram](diagrams/packages.drawio) is language-neutral and shared by both. | ||
added
docs/diagrams/packages.drawio +28 -0 | new file mode 100644 | ||
| @@ -0,0 +1,28 @@ | ||
| 1 | +<mxfile host="turbo-python" modified="" agent="generated from go list -deps"> | |
| 2 | + <diagram name="packages" id="packages"> | |
| 3 | + <mxGraphModel dx="1400" dy="900" grid="0" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1169" pageHeight="826" math="0" shadow="0"> | |
| 4 | + <root> | |
| 5 | + <mxCell id="0"/> | |
| 6 | + <mxCell id="1" parent="0"/> | |
| 7 | + <mxCell id="2" value="<b>main</b><br/><font style='font-size:10px'>flags, terminal, wiring</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;fontSize=12;" vertex="1" parent="1"><mxGeometry x="-95" y="0" width="190" height="54" as="geometry"/></mxCell> | |
| 8 | + <mxCell id="3" value="<b>internal/pythonlang</b><br/><font style='font-size:10px'>the profile and the Python scanner</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;fontSize=12;" vertex="1" parent="1"><mxGeometry x="-95" y="130" width="190" height="54" as="geometry"/></mxCell> | |
| 9 | + <mxCell id="4" value="<b>app</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-519" y="260" width="190" height="54" as="geometry"/></mxCell> | |
| 10 | + <mxCell id="5" value="<b>profile</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-307" y="260" width="190" height="54" as="geometry"/></mxCell> | |
| 11 | + <mxCell id="6" value="<b>settings</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-95" y="260" width="190" height="54" as="geometry"/></mxCell> | |
| 12 | + <mxCell id="7" value="<b>syntax</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="117" y="260" width="190" height="54" as="geometry"/></mxCell> | |
| 13 | + <mxCell id="8" value="<b>theme</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="329" y="260" width="190" height="54" as="geometry"/></mxCell> | |
| 14 | + <mxCell id="9" value="<b>version</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-95" y="390" width="190" height="54" as="geometry"/></mxCell> | |
| 15 | + <mxCell id="10" value="tcell/v2" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#999999;dashed=1;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-95" y="520" width="190" height="54" as="geometry"/></mxCell> | |
| 16 | + <mxCell id="e11" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="3" target="5"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 17 | + <mxCell id="e12" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="3" target="7"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 18 | + <mxCell id="e13" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="3"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 19 | + <mxCell id="e14" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="10"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 20 | + <mxCell id="e15" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="4"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 21 | + <mxCell id="e16" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="5"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 22 | + <mxCell id="e17" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="6"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 23 | + <mxCell id="e18" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="8"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 24 | + <mxCell id="e19" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="9"><mxGeometry relative="1" as="geometry"/></mxCell> | |
| 25 | + </root> | |
| 26 | + </mxGraphModel> | |
| 27 | + </diagram> | |
| 28 | +</mxfile> | |
| new file mode 100644 | |||
| @@ -0,0 +1,28 @@ | |||
| 1 | +<mxfile host="turbo-python" modified="" agent="generated from go list -deps"> | ||
| 2 | + <diagram name="packages" id="packages"> | ||
| 3 | + <mxGraphModel dx="1400" dy="900" grid="0" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1169" pageHeight="826" math="0" shadow="0"> | ||
| 4 | + <root> | ||
| 5 | + <mxCell id="0"/> | ||
| 6 | + <mxCell id="1" parent="0"/> | ||
| 7 | + <mxCell id="2" value="<b>main</b><br/><font style='font-size:10px'>flags, terminal, wiring</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;fontSize=12;" vertex="1" parent="1"><mxGeometry x="-95" y="0" width="190" height="54" as="geometry"/></mxCell> | ||
| 8 | + <mxCell id="3" value="<b>internal/pythonlang</b><br/><font style='font-size:10px'>the profile and the Python scanner</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;fontSize=12;" vertex="1" parent="1"><mxGeometry x="-95" y="130" width="190" height="54" as="geometry"/></mxCell> | ||
| 9 | + <mxCell id="4" value="<b>app</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-519" y="260" width="190" height="54" as="geometry"/></mxCell> | ||
| 10 | + <mxCell id="5" value="<b>profile</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-307" y="260" width="190" height="54" as="geometry"/></mxCell> | ||
| 11 | + <mxCell id="6" value="<b>settings</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-95" y="260" width="190" height="54" as="geometry"/></mxCell> | ||
| 12 | + <mxCell id="7" value="<b>syntax</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="117" y="260" width="190" height="54" as="geometry"/></mxCell> | ||
| 13 | + <mxCell id="8" value="<b>theme</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="329" y="260" width="190" height="54" as="geometry"/></mxCell> | ||
| 14 | + <mxCell id="9" value="<b>version</b><br/><font style='font-size:9px'>turbo-core</font>" style="rounded=0;whiteSpace=wrap;html=1;fillColor=#e1d5e7;strokeColor=#9673a6;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-95" y="390" width="190" height="54" as="geometry"/></mxCell> | ||
| 15 | + <mxCell id="10" value="tcell/v2" style="rounded=1;whiteSpace=wrap;html=1;fillColor=#f5f5f5;strokeColor=#999999;dashed=1;fontSize=11;" vertex="1" parent="1"><mxGeometry x="-95" y="520" width="190" height="54" as="geometry"/></mxCell> | ||
| 16 | + <mxCell id="e11" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="3" target="5"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 17 | + <mxCell id="e12" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="3" target="7"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 18 | + <mxCell id="e13" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="3"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 19 | + <mxCell id="e14" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="10"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 20 | + <mxCell id="e15" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="4"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 21 | + <mxCell id="e16" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="5"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 22 | + <mxCell id="e17" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="6"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 23 | + <mxCell id="e18" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="8"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 24 | + <mxCell id="e19" style="edgeStyle=orthogonalEdgeStyle;rounded=0;html=1;endArrow=block;endFill=1;strokeColor=#6c8ebf;" edge="1" parent="1" source="2" target="9"><mxGeometry relative="1" as="geometry"/></mxCell> | ||
| 25 | + </root> | ||
| 26 | + </mxGraphModel> | ||
| 27 | + </diagram> | ||
| 28 | +</mxfile> | ||
added
docs/en/README.md +59 -0 | new file mode 100644 | ||
| @@ -0,0 +1,59 @@ | ||
| 1 | +# Turbo Python — documentation | |
| 2 | + | |
| 3 | +Turbo Python is a Turbo C-style editor for Python: a full-screen terminal IDE with menus, movable windows, syntax colouring for nine languages, themes, completion from `pylsp`, shell windows, per-project settings, a project tree, snippets, and the uv toolchain a menu away. | |
| 4 | + | |
| 5 | +This documentation follows the [Diátaxis](https://diataxis.fr) method. Four kinds of page, four different needs — go to the one that matches what you want right now. | |
| 6 | + | |
| 7 | +| I want to… | Go to | | |
| 8 | +| --- | --- | | |
| 9 | +| **learn** the editor by using it | [Tutorials](tutorials/) | | |
| 10 | +| **do** something specific | [How-to guides](how-to/) | | |
| 11 | +| **look up** an exact detail | [Reference](reference/) | | |
| 12 | +| **understand** how and why it works | [Explanation](explanation/) | | |
| 13 | + | |
| 14 | +## Tutorials — learning by doing | |
| 15 | + | |
| 16 | +- [Your first file in Turbo Python](tutorials/getting-started.md) — build, open the editor, type a Python program, colour it, save it and run it. | |
| 17 | + | |
| 18 | +## How-to guides — recipes for a task | |
| 19 | + | |
| 20 | +- [How to install and build Turbo Python](how-to/install.md) | |
| 21 | +- [How to run the tests](how-to/run-the-tests.md) | |
| 22 | +- [How to enable Python completion](how-to/enable-completion.md) | |
| 23 | +- [How to write your own theme](how-to/write-a-theme.md) | |
| 24 | +- [How to move around a file](how-to/navigate-code.md) | |
| 25 | +- [How to ask what the code means](how-to/ask-about-code.md) | |
| 26 | +- [How to run shell commands without leaving the editor](how-to/use-a-terminal.md) | |
| 27 | +- [How to give a project its own settings](how-to/configure-a-project.md) | |
| 28 | +- [How to browse a project and open files from a tree](how-to/browse-a-project.md) | |
| 29 | +- [How to insert snippets from a menu](how-to/use-snippets.md) | |
| 30 | +- [How to run uv commands from the editor](how-to/run-uv-commands.md) | |
| 31 | +- [How to make a release](how-to/make-a-release.md) | |
| 32 | +- [How to talk to a coding agent from the editor](how-to/talk-to-an-agent.md) | |
| 33 | + | |
| 34 | +## Reference — the exact details | |
| 35 | + | |
| 36 | +- [Command line](reference/cli.md) | |
| 37 | +- [Keyboard](reference/keyboard.md) | |
| 38 | +- [Menus](reference/menus.md) | |
| 39 | +- [Theme file format](reference/themes.md) | |
| 40 | +- [Terminal windows](reference/terminal.md) | |
| 41 | +- [Project settings](reference/project-settings.md) | |
| 42 | +- [Project tree](reference/project-tree.md) | |
| 43 | +- [Languages coloured](reference/languages.md) | |
| 44 | +- [Snippets](reference/snippets.md) | |
| 45 | +- [Python tools](reference/python-tools.md) | |
| 46 | +- [The version number](reference/versioning.md) | |
| 47 | +- [Agents and ACP](reference/acp.md) | |
| 48 | + | |
| 49 | +## Explanation — understanding | |
| 50 | + | |
| 51 | +- [Architecture](explanation/architecture.md) | |
| 52 | +- [Design decisions](explanation/design-decisions.md) | |
| 53 | +- [Colouring and completion](explanation/colouring-and-completion.md) | |
| 54 | +- [Terminal windows](explanation/terminal-windows.md) | |
| 55 | +- [Project settings](explanation/project-settings.md) | |
| 56 | +- [Project tree](explanation/project-tree.md) | |
| 57 | +- [Snippets](explanation/snippets.md) | |
| 58 | +- [Python tools](explanation/python-tools.md) | |
| 59 | +- [Agent windows](explanation/agent-windows.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | +# Turbo Python — documentation | ||
| 2 | + | ||
| 3 | +Turbo Python is a Turbo C-style editor for Python: a full-screen terminal IDE with menus, movable windows, syntax colouring for nine languages, themes, completion from `pylsp`, shell windows, per-project settings, a project tree, snippets, and the uv toolchain a menu away. | ||
| 4 | + | ||
| 5 | +This documentation follows the [Diátaxis](https://diataxis.fr) method. Four kinds of page, four different needs — go to the one that matches what you want right now. | ||
| 6 | + | ||
| 7 | +| I want to… | Go to | | ||
| 8 | +| --- | --- | | ||
| 9 | +| **learn** the editor by using it | [Tutorials](tutorials/) | | ||
| 10 | +| **do** something specific | [How-to guides](how-to/) | | ||
| 11 | +| **look up** an exact detail | [Reference](reference/) | | ||
| 12 | +| **understand** how and why it works | [Explanation](explanation/) | | ||
| 13 | + | ||
| 14 | +## Tutorials — learning by doing | ||
| 15 | + | ||
| 16 | +- [Your first file in Turbo Python](tutorials/getting-started.md) — build, open the editor, type a Python program, colour it, save it and run it. | ||
| 17 | + | ||
| 18 | +## How-to guides — recipes for a task | ||
| 19 | + | ||
| 20 | +- [How to install and build Turbo Python](how-to/install.md) | ||
| 21 | +- [How to run the tests](how-to/run-the-tests.md) | ||
| 22 | +- [How to enable Python completion](how-to/enable-completion.md) | ||
| 23 | +- [How to write your own theme](how-to/write-a-theme.md) | ||
| 24 | +- [How to move around a file](how-to/navigate-code.md) | ||
| 25 | +- [How to ask what the code means](how-to/ask-about-code.md) | ||
| 26 | +- [How to run shell commands without leaving the editor](how-to/use-a-terminal.md) | ||
| 27 | +- [How to give a project its own settings](how-to/configure-a-project.md) | ||
| 28 | +- [How to browse a project and open files from a tree](how-to/browse-a-project.md) | ||
| 29 | +- [How to insert snippets from a menu](how-to/use-snippets.md) | ||
| 30 | +- [How to run uv commands from the editor](how-to/run-uv-commands.md) | ||
| 31 | +- [How to make a release](how-to/make-a-release.md) | ||
| 32 | +- [How to talk to a coding agent from the editor](how-to/talk-to-an-agent.md) | ||
| 33 | + | ||
| 34 | +## Reference — the exact details | ||
| 35 | + | ||
| 36 | +- [Command line](reference/cli.md) | ||
| 37 | +- [Keyboard](reference/keyboard.md) | ||
| 38 | +- [Menus](reference/menus.md) | ||
| 39 | +- [Theme file format](reference/themes.md) | ||
| 40 | +- [Terminal windows](reference/terminal.md) | ||
| 41 | +- [Project settings](reference/project-settings.md) | ||
| 42 | +- [Project tree](reference/project-tree.md) | ||
| 43 | +- [Languages coloured](reference/languages.md) | ||
| 44 | +- [Snippets](reference/snippets.md) | ||
| 45 | +- [Python tools](reference/python-tools.md) | ||
| 46 | +- [The version number](reference/versioning.md) | ||
| 47 | +- [Agents and ACP](reference/acp.md) | ||
| 48 | + | ||
| 49 | +## Explanation — understanding | ||
| 50 | + | ||
| 51 | +- [Architecture](explanation/architecture.md) | ||
| 52 | +- [Design decisions](explanation/design-decisions.md) | ||
| 53 | +- [Colouring and completion](explanation/colouring-and-completion.md) | ||
| 54 | +- [Terminal windows](explanation/terminal-windows.md) | ||
| 55 | +- [Project settings](explanation/project-settings.md) | ||
| 56 | +- [Project tree](explanation/project-tree.md) | ||
| 57 | +- [Snippets](explanation/snippets.md) | ||
| 58 | +- [Python tools](explanation/python-tools.md) | ||
| 59 | +- [Agent windows](explanation/agent-windows.md) | ||
added
docs/en/explanation/agent-windows.md +114 -0 | new file mode 100644 | ||
| @@ -0,0 +1,114 @@ | ||
| 1 | +# Agent windows | |
| 2 | + | |
| 3 | +This page is about why talking to an agent is shaped the way it is. For how to do it, see [How to talk to a coding agent](../how-to/talk-to-an-agent.md); for the exact keys and file format, [Agents and ACP](../reference/acp.md). | |
| 4 | + | |
| 5 | +## Why a protocol rather than a provider | |
| 6 | + | |
| 7 | +An editor that wanted to offer a chat window had two ways to get one. It could speak to model providers directly — an HTTP client per provider, a set of API keys to store, a tool-calling loop to write, and a new one of each every time somebody wants a provider the editor has never heard of. Or it could speak one protocol to whatever program the user already trusts to do that work. | |
| 8 | + | |
| 9 | +The [Agent Client Protocol](https://agentclientprotocol.com) is the second. The agent is a child process; the editor sends it prompts and draws what comes back. The editor holds no API key, knows no provider, and implements no tool-calling loop — and the same code talks to `docker agent` against a local llama.cpp, to a cloud agent, or to something you wrote this afternoon. | |
| 10 | + | |
| 11 | +It also means the editor is not the place a new model lands. Support for one is a line in *your* agent's configuration file, which is a file this editor does not read. | |
| 12 | + | |
| 13 | +## Why this lives in turbo-core | |
| 14 | + | |
| 15 | +Turbo Python is [a command, a profile and a scanner](architecture.md); everything else is the library every Turbo editor shares. An agent window is a window, a menu, a modal dialog and a turn of the event loop — all four of which belong to `turbo-core/app`. Building it here would have meant adding a general "let an editor add a window and a menu from outside" seam to the library and then using it exactly once. | |
| 16 | + | |
| 17 | +So the protocol client, the conversation model and the window are `turbo-core/acp`, beside `terminal` and `filetree`, which are the same shape. What Turbo Python contributes is the starter `acp.toml` it offers to write — the one part of this that is about Python projects. Turbo Rust and Turbo Golo get agent windows by writing a starter file of their own, and nothing else. | |
| 18 | + | |
| 19 | +## Why a window, not a panel | |
| 20 | + | |
| 21 | +The same reasoning the [project tree](project-tree.md) settled. A docked panel would mean the desktop growing a notion of reserved edges, and `fitInto`, the grow modes, maximising, tiling and cascading all having to respect them — a change to the foundation of the interface for one widget. As an ordinary window an agent gets `F6`, `Alt`-digits, `[x]`, `[■]` and Tile for free. | |
| 22 | + | |
| 23 | +It also makes "several agents at once" fall out rather than being designed: two windows are two processes and two conversations, and Tile puts a fast local model beside a careful slow one. A panel would have had to grow tabs to do that. | |
| 24 | + | |
| 25 | +## Why one process per window, started when the window opens | |
| 26 | + | |
| 27 | +An agent is a conversation, and a conversation has a beginning. Starting the process with the window means the agent's working directory, its environment and its session all belong to that window, and closing it is an unambiguous end — the same bargain [terminal windows](terminal-windows.md) make, and for the same reason: what the window holds is a running process, not unsaved work, so closing it asks nothing. | |
| 28 | + | |
| 29 | +The alternative — one long-lived agent multiplexed across several windows — would have meant the editor deciding which window a `session/update` belonged to, and what to do with a window whose session had gone away while the process lived on. Two processes are cheaper than that bookkeeping. | |
| 30 | + | |
| 31 | +## Why the permission dialog is opened from the event loop, not from the message | |
| 32 | + | |
| 33 | +`session/request_permission` arrives on the connection's reading goroutine, and the answer comes from a dialog the user has to look at. The reply therefore cannot be made where the request is handled, and the dialog cannot be opened there either: everything that draws belongs to the main goroutine. | |
| 34 | + | |
| 35 | +So the request is *recorded*, and the event loop notices it on its next turn and opens the dialog. This is the fourth time this project has reached the same conclusion — [autosave](project-settings.md), the language server's re-announcement, and the terminal's redraws are the others — and the reason is always the same: `PostEvent` is allowed to drop what does not fit, so an event may cause a turn of the loop but must never be the only thing that carries a fact. | |
| 36 | + | |
| 37 | +That is why the JSON-RPC layer had to learn to answer a request *later*. It is also the whole of why `jsonrpc` was extracted out of `lsp`: a language server's questions can all be answered on the spot, and an agent's cannot. | |
| 38 | + | |
| 39 | +## Why the agent is offered the buffer rather than the file | |
| 40 | + | |
| 41 | +When the agent reads a file you have open and have not saved, it is given the text you can see, not the text on disk. The alternative is an agent that reviews the version you have just moved past, which is wrong precisely when you are most likely to be asking — you changed something and want to know about the change. | |
| 42 | + | |
| 43 | +The cost is that the agent sees text that no other tool can see, so an answer quoting a line number may not match what `uv run ruff check .` says. That is accepted: the same is already true of completion, which has answered from the buffer since the editor learnt to talk to `pylsp`. | |
| 44 | + | |
| 45 | +Writes go the same way, into the buffer, marked modified. An agent that edits a file leaves the change in front of you, undoable with `Ctrl-Z` and unsaved until you press `F2`. An agent quietly rewriting a file under a window you have open would be the worst possible version of this feature. | |
| 46 | + | |
| 47 | +## Why the colours are the syntax classes, and not new theme keys | |
| 48 | + | |
| 49 | +The [project tree](project-tree.md) needed theme keys of its own, because it would otherwise have borrowed `list.selected`, a colour chosen against a *dialog* background, and drawn its selected row in the colour underneath it. Nothing like that is true here: an agent window's body is `window.body`, which is what the syntax classes are already chosen against and already tested against for contrast. | |
| 50 | + | |
| 51 | +So a speaker's name is drawn in the keyword style, a thought in the comment style, a tool call in the type style, and code in whatever its own scanner says. Eleven themes therefore colour agent windows correctly without being touched, and a theme somebody wrote last year does too. | |
| 52 | + | |
| 53 | +What is given up is expressiveness: a theme cannot make thoughts quiet without also making comments quiet, because they are the same key. If that turns out to matter in use, `agent.*` keys can be added later — the contrast rules and the completeness test are the cost, and they are worth paying only if somebody wants the distinction. | |
| 54 | + | |
| 55 | +## Why the transcript is a model the window merely draws | |
| 56 | + | |
| 57 | +The agent sends tokens: `"I"`, `" found"`, `" agent"`, `".yaml"`. A window that appended each one to a list of lines would be a window that could not reflow, could not tell prose from a fenced code block, and could not be tested without a live agent. | |
| 58 | + | |
| 59 | +So the conversation is a value — `acp.Transcript` — that coalesces chunks into entries, folds each `tool_call_update` onto the `tool_call` its id matches, and hands the window a list of blocks that are either prose or code-in-a-named-language. It knows nothing about a terminal, which is what lets it be tested by calling functions and comparing values, the same organising rule `buffer`, `lsp` and `syntax` follow. | |
| 60 | + | |
| 61 | +It is also what makes the drawing tests deterministic. The project has been bitten before by tests that asserted on a screen while a live process wrote to it, and that hid a real fault for a whole session; a window drawn from a fixed transcript cannot race anything. | |
| 62 | + | |
| 63 | +## What was deliberately left out | |
| 64 | + | |
| 65 | +- **Session resume.** `session/load` exists, and using it would mean deciding where conversations are stored, how long they are kept, and what happens when the project moved. That is a feature in its own right. | |
| 66 | +- **Authentication.** An agent that needs a login is told to log in with its own CLI. Storing a credential is a responsibility this editor has so far avoided entirely, and one protocol method is not a good reason to start. | |
| 67 | +- **The terminal capability.** An agent can already have a shell through its own toolsets, as `docker agent` does. Advertising `terminal` would mean the editor running commands on the agent's behalf and owning the output — the tools menu already does that, better, for commands *you* chose. | |
| 68 | +- **Images in prompts.** The editor has text and files to send, and a terminal to draw in. | |
| 69 | + | |
| 70 | +## See also | |
| 71 | + | |
| 72 | +- [Architecture](architecture.md) — what is here and what is in the library | |
| 73 | +- [Terminal windows](terminal-windows.md) — the other window holding a live process | |
| 74 | +- [Project tree](project-tree.md) — where the window-not-a-panel argument was first made | |
| 75 | + | |
| 76 | +## Why copying goes to two clipboards | |
| 77 | + | |
| 78 | +"Copy this so I can use it elsewhere" usually means *elsewhere entirely* — another window, a browser, a message to a colleague. A clipboard that only worked inside this editor would answer the smaller half of the request, and the half you were least likely to be asking about. | |
| 79 | + | |
| 80 | +So a copy goes to both: the editor's own, which `Shift-Ins` pastes from, and the system's, reached by asking the terminal through OSC 52. Nothing verifies the second, because there is nothing to verify — the sequence has no reply, a terminal may refuse it for security, and some need it turned on. A message promising something that did not happen would be worse than one that stays quiet, so the status bar says only how many lines were copied, which is true either way. | |
| 81 | + | |
| 82 | +## Why copying with nothing selected copies a whole block | |
| 83 | + | |
| 84 | +The thing somebody wants out of a conversation is almost always a code block. Making them select it first — six keystrokes, or a drag they have to aim — is work the editor already has the information to do for them: it laid the conversation out, so it knows exactly where that block starts and ends. | |
| 85 | + | |
| 86 | +So the lines carry a **region**: one fenced code block, one passage of prose, one tool call's output. With nothing selected, `Ctrl-C` copies the region the cursor is on. A speaker's label and a tool call's heading are furniture and get regions of their own, which is what keeps `‣ Bob (llama.cpp)` out of a block pasted into a source file. | |
| 87 | + | |
| 88 | +That last part was not designed; it was found. The first version copied the label along with the code, and it was caught by copying from the real binary and reading the OSC 52 payload back off the wire. | |
| 89 | + | |
| 90 | +## Why the spinner is drawn from the clock | |
| 91 | + | |
| 92 | +An agent thinking for twenty seconds sends nothing at all, and a window that looked frozen would be indistinguishable from one that was. The spinner is the cheapest possible answer to "is this still working?". | |
| 93 | + | |
| 94 | +It is a function of the time — `Spinner(now)` — rather than a counter something increments. Nothing has to be reset when a turn begins, two windows thinking at once turn in step, and a test can assert on a frame without waiting for one, which is the same reason `editor.View` and `app.App` both take an injectable clock. | |
| 95 | + | |
| 96 | +Drawing from the clock means something else has to *cause* the redraw, so a session running a turn wakes the event loop at the spinner's own rate. That is allowed to be a ticker precisely because a dropped tick cannot strand anything: it asks for a turn of the loop and never carries a fact — the rule this project has now reached five times. | |
| 97 | + | |
| 98 | +The window's **title** deliberately does not animate. It is also what the window list and the `Alt`-digit menu show, and a name that changed eight times a second would make both of them flicker for no gain. | |
| 99 | + | |
| 100 | +## Why commands are a popup in the box, and not a menu | |
| 101 | + | |
| 102 | +An agent's commands arrive over the wire as a list — `available_commands_update` — and may change during the session. A menu built from them would have to be rebuilt on every update, would sit far from where the command is typed, and would still have to end by putting `/web ` into the box, because that is the only thing the protocol lets a client send: a command is a text prompt the agent recognises by its first word. | |
| 103 | + | |
| 104 | +So the list opens where the text is, on the character that starts a command, and closes when the word is complete. It is the same shape as the completion popup over a file, for the same reason: what you are choosing is what you are typing. Using `/` and `@` rather than keys of the editor's own is deliberate — they are the characters Zed uses, so an agent's own documentation is true here without a translation table. | |
| 105 | + | |
| 106 | +`Enter` has two meanings on the list, ordered by how finished the word is: it completes an unfinished one, and sends a finished one. The alternative — `Enter` always completes, a second `Enter` sends — costs a keystroke on every command and gains nothing, because a word that already reads exactly as a command has nothing left to complete. | |
| 107 | + | |
| 108 | +## Why a mention carries the file, when it can | |
| 109 | + | |
| 110 | +The protocol offers two ways to name a file in a prompt: a `resource_link`, which is a URI the agent fetches for itself, and an embedded `resource`, which is the URI *and the text*. The specification calls the second "the preferred way to include context", and the reason is the same one that makes `fs/read_text_file` answer from the buffer: the editor knows things about the file that the disk does not. An agent following a link to a file you have edited and not saved reads the version you have just moved past, which is wrong precisely when you are most likely to be asking. | |
| 111 | + | |
| 112 | +So the editor sends the text when the agent declared `promptCapabilities.embeddedContext`, read through the same path `fs/read_text_file` uses, and a link otherwise — never nothing. A file that cannot be read goes as a link too, so the agent is at least told which file was meant. | |
| 113 | + | |
| 114 | +The mention replaces the name in the text rather than travelling beside it. Sending `explain @main.go` as the text *and* an attachment would give the agent the name twice and leave it to match them; putting the block where the name was gives it the file where the sentence needs it. The conversation, on the other hand, keeps the line as typed: that is what you said, and the window is a record of the conversation, not of the wire. | |
| new file mode 100644 | |||
| @@ -0,0 +1,114 @@ | |||
| 1 | +# Agent windows | ||
| 2 | + | ||
| 3 | +This page is about why talking to an agent is shaped the way it is. For how to do it, see [How to talk to a coding agent](../how-to/talk-to-an-agent.md); for the exact keys and file format, [Agents and ACP](../reference/acp.md). | ||
| 4 | + | ||
| 5 | +## Why a protocol rather than a provider | ||
| 6 | + | ||
| 7 | +An editor that wanted to offer a chat window had two ways to get one. It could speak to model providers directly — an HTTP client per provider, a set of API keys to store, a tool-calling loop to write, and a new one of each every time somebody wants a provider the editor has never heard of. Or it could speak one protocol to whatever program the user already trusts to do that work. | ||
| 8 | + | ||
| 9 | +The [Agent Client Protocol](https://agentclientprotocol.com) is the second. The agent is a child process; the editor sends it prompts and draws what comes back. The editor holds no API key, knows no provider, and implements no tool-calling loop — and the same code talks to `docker agent` against a local llama.cpp, to a cloud agent, or to something you wrote this afternoon. | ||
| 10 | + | ||
| 11 | +It also means the editor is not the place a new model lands. Support for one is a line in *your* agent's configuration file, which is a file this editor does not read. | ||
| 12 | + | ||
| 13 | +## Why this lives in turbo-core | ||
| 14 | + | ||
| 15 | +Turbo Python is [a command, a profile and a scanner](architecture.md); everything else is the library every Turbo editor shares. An agent window is a window, a menu, a modal dialog and a turn of the event loop — all four of which belong to `turbo-core/app`. Building it here would have meant adding a general "let an editor add a window and a menu from outside" seam to the library and then using it exactly once. | ||
| 16 | + | ||
| 17 | +So the protocol client, the conversation model and the window are `turbo-core/acp`, beside `terminal` and `filetree`, which are the same shape. What Turbo Python contributes is the starter `acp.toml` it offers to write — the one part of this that is about Python projects. Turbo Rust and Turbo Golo get agent windows by writing a starter file of their own, and nothing else. | ||
| 18 | + | ||
| 19 | +## Why a window, not a panel | ||
| 20 | + | ||
| 21 | +The same reasoning the [project tree](project-tree.md) settled. A docked panel would mean the desktop growing a notion of reserved edges, and `fitInto`, the grow modes, maximising, tiling and cascading all having to respect them — a change to the foundation of the interface for one widget. As an ordinary window an agent gets `F6`, `Alt`-digits, `[x]`, `[■]` and Tile for free. | ||
| 22 | + | ||
| 23 | +It also makes "several agents at once" fall out rather than being designed: two windows are two processes and two conversations, and Tile puts a fast local model beside a careful slow one. A panel would have had to grow tabs to do that. | ||
| 24 | + | ||
| 25 | +## Why one process per window, started when the window opens | ||
| 26 | + | ||
| 27 | +An agent is a conversation, and a conversation has a beginning. Starting the process with the window means the agent's working directory, its environment and its session all belong to that window, and closing it is an unambiguous end — the same bargain [terminal windows](terminal-windows.md) make, and for the same reason: what the window holds is a running process, not unsaved work, so closing it asks nothing. | ||
| 28 | + | ||
| 29 | +The alternative — one long-lived agent multiplexed across several windows — would have meant the editor deciding which window a `session/update` belonged to, and what to do with a window whose session had gone away while the process lived on. Two processes are cheaper than that bookkeeping. | ||
| 30 | + | ||
| 31 | +## Why the permission dialog is opened from the event loop, not from the message | ||
| 32 | + | ||
| 33 | +`session/request_permission` arrives on the connection's reading goroutine, and the answer comes from a dialog the user has to look at. The reply therefore cannot be made where the request is handled, and the dialog cannot be opened there either: everything that draws belongs to the main goroutine. | ||
| 34 | + | ||
| 35 | +So the request is *recorded*, and the event loop notices it on its next turn and opens the dialog. This is the fourth time this project has reached the same conclusion — [autosave](project-settings.md), the language server's re-announcement, and the terminal's redraws are the others — and the reason is always the same: `PostEvent` is allowed to drop what does not fit, so an event may cause a turn of the loop but must never be the only thing that carries a fact. | ||
| 36 | + | ||
| 37 | +That is why the JSON-RPC layer had to learn to answer a request *later*. It is also the whole of why `jsonrpc` was extracted out of `lsp`: a language server's questions can all be answered on the spot, and an agent's cannot. | ||
| 38 | + | ||
| 39 | +## Why the agent is offered the buffer rather than the file | ||
| 40 | + | ||
| 41 | +When the agent reads a file you have open and have not saved, it is given the text you can see, not the text on disk. The alternative is an agent that reviews the version you have just moved past, which is wrong precisely when you are most likely to be asking — you changed something and want to know about the change. | ||
| 42 | + | ||
| 43 | +The cost is that the agent sees text that no other tool can see, so an answer quoting a line number may not match what `uv run ruff check .` says. That is accepted: the same is already true of completion, which has answered from the buffer since the editor learnt to talk to `pylsp`. | ||
| 44 | + | ||
| 45 | +Writes go the same way, into the buffer, marked modified. An agent that edits a file leaves the change in front of you, undoable with `Ctrl-Z` and unsaved until you press `F2`. An agent quietly rewriting a file under a window you have open would be the worst possible version of this feature. | ||
| 46 | + | ||
| 47 | +## Why the colours are the syntax classes, and not new theme keys | ||
| 48 | + | ||
| 49 | +The [project tree](project-tree.md) needed theme keys of its own, because it would otherwise have borrowed `list.selected`, a colour chosen against a *dialog* background, and drawn its selected row in the colour underneath it. Nothing like that is true here: an agent window's body is `window.body`, which is what the syntax classes are already chosen against and already tested against for contrast. | ||
| 50 | + | ||
| 51 | +So a speaker's name is drawn in the keyword style, a thought in the comment style, a tool call in the type style, and code in whatever its own scanner says. Eleven themes therefore colour agent windows correctly without being touched, and a theme somebody wrote last year does too. | ||
| 52 | + | ||
| 53 | +What is given up is expressiveness: a theme cannot make thoughts quiet without also making comments quiet, because they are the same key. If that turns out to matter in use, `agent.*` keys can be added later — the contrast rules and the completeness test are the cost, and they are worth paying only if somebody wants the distinction. | ||
| 54 | + | ||
| 55 | +## Why the transcript is a model the window merely draws | ||
| 56 | + | ||
| 57 | +The agent sends tokens: `"I"`, `" found"`, `" agent"`, `".yaml"`. A window that appended each one to a list of lines would be a window that could not reflow, could not tell prose from a fenced code block, and could not be tested without a live agent. | ||
| 58 | + | ||
| 59 | +So the conversation is a value — `acp.Transcript` — that coalesces chunks into entries, folds each `tool_call_update` onto the `tool_call` its id matches, and hands the window a list of blocks that are either prose or code-in-a-named-language. It knows nothing about a terminal, which is what lets it be tested by calling functions and comparing values, the same organising rule `buffer`, `lsp` and `syntax` follow. | ||
| 60 | + | ||
| 61 | +It is also what makes the drawing tests deterministic. The project has been bitten before by tests that asserted on a screen while a live process wrote to it, and that hid a real fault for a whole session; a window drawn from a fixed transcript cannot race anything. | ||
| 62 | + | ||
| 63 | +## What was deliberately left out | ||
| 64 | + | ||
| 65 | +- **Session resume.** `session/load` exists, and using it would mean deciding where conversations are stored, how long they are kept, and what happens when the project moved. That is a feature in its own right. | ||
| 66 | +- **Authentication.** An agent that needs a login is told to log in with its own CLI. Storing a credential is a responsibility this editor has so far avoided entirely, and one protocol method is not a good reason to start. | ||
| 67 | +- **The terminal capability.** An agent can already have a shell through its own toolsets, as `docker agent` does. Advertising `terminal` would mean the editor running commands on the agent's behalf and owning the output — the tools menu already does that, better, for commands *you* chose. | ||
| 68 | +- **Images in prompts.** The editor has text and files to send, and a terminal to draw in. | ||
| 69 | + | ||
| 70 | +## See also | ||
| 71 | + | ||
| 72 | +- [Architecture](architecture.md) — what is here and what is in the library | ||
| 73 | +- [Terminal windows](terminal-windows.md) — the other window holding a live process | ||
| 74 | +- [Project tree](project-tree.md) — where the window-not-a-panel argument was first made | ||
| 75 | + | ||
| 76 | +## Why copying goes to two clipboards | ||
| 77 | + | ||
| 78 | +"Copy this so I can use it elsewhere" usually means *elsewhere entirely* — another window, a browser, a message to a colleague. A clipboard that only worked inside this editor would answer the smaller half of the request, and the half you were least likely to be asking about. | ||
| 79 | + | ||
| 80 | +So a copy goes to both: the editor's own, which `Shift-Ins` pastes from, and the system's, reached by asking the terminal through OSC 52. Nothing verifies the second, because there is nothing to verify — the sequence has no reply, a terminal may refuse it for security, and some need it turned on. A message promising something that did not happen would be worse than one that stays quiet, so the status bar says only how many lines were copied, which is true either way. | ||
| 81 | + | ||
| 82 | +## Why copying with nothing selected copies a whole block | ||
| 83 | + | ||
| 84 | +The thing somebody wants out of a conversation is almost always a code block. Making them select it first — six keystrokes, or a drag they have to aim — is work the editor already has the information to do for them: it laid the conversation out, so it knows exactly where that block starts and ends. | ||
| 85 | + | ||
| 86 | +So the lines carry a **region**: one fenced code block, one passage of prose, one tool call's output. With nothing selected, `Ctrl-C` copies the region the cursor is on. A speaker's label and a tool call's heading are furniture and get regions of their own, which is what keeps `‣ Bob (llama.cpp)` out of a block pasted into a source file. | ||
| 87 | + | ||
| 88 | +That last part was not designed; it was found. The first version copied the label along with the code, and it was caught by copying from the real binary and reading the OSC 52 payload back off the wire. | ||
| 89 | + | ||
| 90 | +## Why the spinner is drawn from the clock | ||
| 91 | + | ||
| 92 | +An agent thinking for twenty seconds sends nothing at all, and a window that looked frozen would be indistinguishable from one that was. The spinner is the cheapest possible answer to "is this still working?". | ||
| 93 | + | ||
| 94 | +It is a function of the time — `Spinner(now)` — rather than a counter something increments. Nothing has to be reset when a turn begins, two windows thinking at once turn in step, and a test can assert on a frame without waiting for one, which is the same reason `editor.View` and `app.App` both take an injectable clock. | ||
| 95 | + | ||
| 96 | +Drawing from the clock means something else has to *cause* the redraw, so a session running a turn wakes the event loop at the spinner's own rate. That is allowed to be a ticker precisely because a dropped tick cannot strand anything: it asks for a turn of the loop and never carries a fact — the rule this project has now reached five times. | ||
| 97 | + | ||
| 98 | +The window's **title** deliberately does not animate. It is also what the window list and the `Alt`-digit menu show, and a name that changed eight times a second would make both of them flicker for no gain. | ||
| 99 | + | ||
| 100 | +## Why commands are a popup in the box, and not a menu | ||
| 101 | + | ||
| 102 | +An agent's commands arrive over the wire as a list — `available_commands_update` — and may change during the session. A menu built from them would have to be rebuilt on every update, would sit far from where the command is typed, and would still have to end by putting `/web ` into the box, because that is the only thing the protocol lets a client send: a command is a text prompt the agent recognises by its first word. | ||
| 103 | + | ||
| 104 | +So the list opens where the text is, on the character that starts a command, and closes when the word is complete. It is the same shape as the completion popup over a file, for the same reason: what you are choosing is what you are typing. Using `/` and `@` rather than keys of the editor's own is deliberate — they are the characters Zed uses, so an agent's own documentation is true here without a translation table. | ||
| 105 | + | ||
| 106 | +`Enter` has two meanings on the list, ordered by how finished the word is: it completes an unfinished one, and sends a finished one. The alternative — `Enter` always completes, a second `Enter` sends — costs a keystroke on every command and gains nothing, because a word that already reads exactly as a command has nothing left to complete. | ||
| 107 | + | ||
| 108 | +## Why a mention carries the file, when it can | ||
| 109 | + | ||
| 110 | +The protocol offers two ways to name a file in a prompt: a `resource_link`, which is a URI the agent fetches for itself, and an embedded `resource`, which is the URI *and the text*. The specification calls the second "the preferred way to include context", and the reason is the same one that makes `fs/read_text_file` answer from the buffer: the editor knows things about the file that the disk does not. An agent following a link to a file you have edited and not saved reads the version you have just moved past, which is wrong precisely when you are most likely to be asking. | ||
| 111 | + | ||
| 112 | +So the editor sends the text when the agent declared `promptCapabilities.embeddedContext`, read through the same path `fs/read_text_file` uses, and a link otherwise — never nothing. A file that cannot be read goes as a link too, so the agent is at least told which file was meant. | ||
| 113 | + | ||
| 114 | +The mention replaces the name in the text rather than travelling beside it. Sending `explain @main.go` as the text *and* an attachment would give the agent the name twice and leave it to match them; putting the block where the name was gives it the file where the sentence needs it. The conversation, on the other hand, keeps the line as typed: that is what you said, and the window is a record of the conversation, not of the wire. | ||
added
docs/en/explanation/architecture.md +97 -0 | new file mode 100644 | ||
| @@ -0,0 +1,97 @@ | ||
| 1 | +# Architecture — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +Turbo Python is a command, a profile and a scanner. Everything else — the editing widget, the windows, the menus, the dialogs, the themes, the terminal emulator, the file tree, the LSP client — is [turbo-core](https://rickub.com/turbo-editors/turbo-core), the library every Turbo editor is built on. | |
| 6 | + | |
| 7 | +This page is about that split: what is here, what is there, and why the line falls where it does. | |
| 8 | + | |
| 9 | +## What is in this repository | |
| 10 | + | |
| 11 | +``` | |
| 12 | +main.go flags, the terminal, and the wiring | |
| 13 | +internal/pythonlang the whole of what makes this Turbo Python | |
| 14 | + pythonlang.go the profile: name, menu, server, root markers, where pylsp hides | |
| 15 | + scan.go the scanner's dispatcher, comments, decorators | |
| 16 | + literals.go the sixteen spellings of a string literal | |
| 17 | + words.go numbers, keywords, builtins, the naming conventions | |
| 18 | + templates.go three //go:embed declarations | |
| 19 | + *.toml.tmpl the three starter files a project gets, embedded | |
| 20 | +``` | |
| 21 | + | |
| 22 | +About eight hundred lines, of which six hundred are the scanner. There is no `internal/app`, no `internal/ui`, no `internal/buffer` — those exist once, in the library, and all six editors use them unchanged. | |
| 23 | + | |
| 24 | +## What `main` does | |
| 25 | + | |
| 26 | +Six things, in this order: | |
| 27 | + | |
| 28 | +1. Parses the flags. | |
| 29 | +2. Calls `pythonlang.Register()`, which teaches the library to colour `.py` files. | |
| 30 | +3. Builds `pythonlang.Profile()` — the value that says this editor is Turbo Python. | |
| 31 | +4. Reads `.turbo-python/settings.toml` from the working directory, if there is one. | |
| 32 | +5. Opens the terminal and hands the screen, the theme name and the profile to `app.New`. | |
| 33 | +6. Starts pylsp in the project root, and runs the event loop. | |
| 34 | + | |
| 35 | +That is the whole command. Every decision it makes — which theme wins, which files to open, whether to start a language server — is about *this run*, not about Python. | |
| 36 | + | |
| 37 | +## The profile is the seam | |
| 38 | + | |
| 39 | +```go | |
| 40 | +profile.Profile{ | |
| 41 | + Name: "Turbo Python", | |
| 42 | + Slug: "turbo-python", | |
| 43 | + Language: "Python", | |
| 44 | + ToolsMenu: "~P~ython", | |
| 45 | + RootMarkers: []string{"pyproject.toml", "setup.py", "setup.cfg"}, | |
| 46 | + Server: profile.Server{Command: "pylsp", …}, | |
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | |
| 48 | +} | |
| 49 | +``` | |
| 50 | + | |
| 51 | +Everything that would otherwise be a hardcoded `"turbo-python"`, `"pylsp"` or `"pyproject.toml"` somewhere in eleven thousand lines is one field here. The library reads them; nothing in the library knows what any of them mean. | |
| 52 | + | |
| 53 | +`Slug` carries more than it looks. The binary is `turbo-python`, the project directory is `.turbo-python`, the user's own configuration lives in `~/.config/turbo-python`, and the environment variables that override it are `TURBO_PYTHON_THEME_DIR` and `TURBO_PYTHON_SNIPPET_DIR` — all derived from that one word. | |
| 54 | + | |
| 55 | +## Why the scanner is here and not in the library | |
| 56 | + | |
| 57 | +turbo-core colours eight languages itself: TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell. Those are the ones every editor meets whatever it is for — a project's configuration is TOML or YAML, its documentation is Markdown, its scripts are shell, its image build a Dockerfile. | |
| 58 | + | |
| 59 | +Python is not one of them, and neither are Go and Rust. The language that *defines* an editor is registered by that editor, which is why a `.rs` file opens as plain text here and a `.py` file opens as plain text in Turbo Rust. | |
| 60 | + | |
| 61 | +That could have gone the other way. Putting all three scanners in the library would let any editor colour any of the languages, at no cost in dependencies — a Python scanner is ordinary Go. It was rejected because it would mean the library grows a language every time somebody builds an editor, and because "what does this editor register?" would stop being the first question about a new one. | |
| 62 | + | |
| 63 | +## Why the toolchain menu is `~P~ython` and not `~U~v` | |
| 64 | + | |
| 65 | +The hot key was the easy part. Nine letters are taken by the fixed menus — F, E, S, R, C, O, W, N and H — and `P` is not one of them, so it lands on the first letter of the word, which costs nobody a second glance. Turbo Rust had no such luck and ended up on `Rus~t~`. | |
| 66 | + | |
| 67 | +The name was the real decision, and it went the same way Turbo Rust's did. The menu holds whatever the project put in its tools file, and that is not always uv: the first tools file anybody writes outgrows the language's own toolchain, because a project's commands include containers, databases and a `Makefile` target somebody added in 2019. A menu called **uv** holding `docker compose up` is a lie about what the menu is, in exactly the way the library's own documentation warns about. `Python` is the language, and the language is what this editor is for. | |
| 68 | + | |
| 69 | +## Why the tests drive the real editor | |
| 70 | + | |
| 71 | +`internal/pythonlang/editor_test.go` builds a whole Turbo Python on a simulated terminal — `app.New(screen, "turbo-classic", pythonlang.Profile())` — opens a file and checks the colouring, the menu bar and the hot keys. It uses only the library's public API. | |
| 72 | + | |
| 73 | +That is deliberate. The library's own suite proves the library works; what these tests prove is that *this editor is assembled correctly* — that `Register` was called, that the profile reached the menu bar, that a `.py` file comes out coloured. A bug where `main` forgot to register Python would pass every test in turbo-core. | |
| 74 | + | |
| 75 | +The same file drives a **real pylsp** end to end, four times over. It writes a project, opens a file, starts the server, and then: | |
| 76 | + | |
| 77 | +- **types text that exists only in the buffer** and asks for a completion — text already on disk proves nothing, because the server answers from disk for anything it has not been told is open; | |
| 78 | +- asks for the **references** of a name used in three places, which is the answer shape that used to be truncated to one; | |
| 79 | +- asks for the **file's symbols**, which is a different answer shape again; | |
| 80 | +- opens a file that **does not parse** and waits for a diagnostic to arrive unasked — the one feature whose failure looks exactly like success, because an editor with no error to show and one that cannot find the error are the same blank gutter. | |
| 81 | + | |
| 82 | +A fifth test pins what pylsp *cannot* do: it advertises neither `implementation` nor `workspace/symbol`, the documentation says so, and the test fails if a future pylsp starts answering — so the page gets revisited rather than quietly going stale. | |
| 83 | + | |
| 84 | +## Rejected alternatives | |
| 85 | + | |
| 86 | +**Forking Turbo Rust.** The obvious way to get a third editor, and the reason the library exists instead: three copies of eleven thousand lines drift within a month, and every fix has to be made three times by somebody who remembers there are three. | |
| 87 | + | |
| 88 | +**A plugin system.** Turbo Python is a Go program that imports a library. There is no dynamic loading and no ABI. Adding one would mean freezing the API of every package in turbo-core rather than of the handful a profile touches. | |
| 89 | + | |
| 90 | +**A configuration file instead of a profile.** The profile could have been TOML read at start-up, which would make a new editor a file rather than a program. It would also make the scanner inexpressible, and a half-configurable editor — everything but the colouring — is worse than either whole answer. | |
| 91 | + | |
| 92 | +## How it relates to the rest | |
| 93 | + | |
| 94 | +- What each of the library's packages does: [turbo-core's package reference](https://rickub.com/turbo-editors/turbo-core/blob/main/docs/en/reference/packages.md) | |
| 95 | +- How the colouring works here: [Colouring and completion](colouring-and-completion.md) | |
| 96 | +- Why the tools menu is data: [Python tools](python-tools.md) | |
| 97 | +- The decisions that outlived the refactoring: [Design decisions](design-decisions.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,97 @@ | |||
| 1 | +# Architecture — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +Turbo Python is a command, a profile and a scanner. Everything else — the editing widget, the windows, the menus, the dialogs, the themes, the terminal emulator, the file tree, the LSP client — is [turbo-core](https://rickub.com/turbo-editors/turbo-core), the library every Turbo editor is built on. | ||
| 6 | + | ||
| 7 | +This page is about that split: what is here, what is there, and why the line falls where it does. | ||
| 8 | + | ||
| 9 | +## What is in this repository | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +main.go flags, the terminal, and the wiring | ||
| 13 | +internal/pythonlang the whole of what makes this Turbo Python | ||
| 14 | + pythonlang.go the profile: name, menu, server, root markers, where pylsp hides | ||
| 15 | + scan.go the scanner's dispatcher, comments, decorators | ||
| 16 | + literals.go the sixteen spellings of a string literal | ||
| 17 | + words.go numbers, keywords, builtins, the naming conventions | ||
| 18 | + templates.go three //go:embed declarations | ||
| 19 | + *.toml.tmpl the three starter files a project gets, embedded | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +About eight hundred lines, of which six hundred are the scanner. There is no `internal/app`, no `internal/ui`, no `internal/buffer` — those exist once, in the library, and all six editors use them unchanged. | ||
| 23 | + | ||
| 24 | +## What `main` does | ||
| 25 | + | ||
| 26 | +Six things, in this order: | ||
| 27 | + | ||
| 28 | +1. Parses the flags. | ||
| 29 | +2. Calls `pythonlang.Register()`, which teaches the library to colour `.py` files. | ||
| 30 | +3. Builds `pythonlang.Profile()` — the value that says this editor is Turbo Python. | ||
| 31 | +4. Reads `.turbo-python/settings.toml` from the working directory, if there is one. | ||
| 32 | +5. Opens the terminal and hands the screen, the theme name and the profile to `app.New`. | ||
| 33 | +6. Starts pylsp in the project root, and runs the event loop. | ||
| 34 | + | ||
| 35 | +That is the whole command. Every decision it makes — which theme wins, which files to open, whether to start a language server — is about *this run*, not about Python. | ||
| 36 | + | ||
| 37 | +## The profile is the seam | ||
| 38 | + | ||
| 39 | +```go | ||
| 40 | +profile.Profile{ | ||
| 41 | + Name: "Turbo Python", | ||
| 42 | + Slug: "turbo-python", | ||
| 43 | + Language: "Python", | ||
| 44 | + ToolsMenu: "~P~ython", | ||
| 45 | + RootMarkers: []string{"pyproject.toml", "setup.py", "setup.cfg"}, | ||
| 46 | + Server: profile.Server{Command: "pylsp", …}, | ||
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | ||
| 48 | +} | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +Everything that would otherwise be a hardcoded `"turbo-python"`, `"pylsp"` or `"pyproject.toml"` somewhere in eleven thousand lines is one field here. The library reads them; nothing in the library knows what any of them mean. | ||
| 52 | + | ||
| 53 | +`Slug` carries more than it looks. The binary is `turbo-python`, the project directory is `.turbo-python`, the user's own configuration lives in `~/.config/turbo-python`, and the environment variables that override it are `TURBO_PYTHON_THEME_DIR` and `TURBO_PYTHON_SNIPPET_DIR` — all derived from that one word. | ||
| 54 | + | ||
| 55 | +## Why the scanner is here and not in the library | ||
| 56 | + | ||
| 57 | +turbo-core colours eight languages itself: TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell. Those are the ones every editor meets whatever it is for — a project's configuration is TOML or YAML, its documentation is Markdown, its scripts are shell, its image build a Dockerfile. | ||
| 58 | + | ||
| 59 | +Python is not one of them, and neither are Go and Rust. The language that *defines* an editor is registered by that editor, which is why a `.rs` file opens as plain text here and a `.py` file opens as plain text in Turbo Rust. | ||
| 60 | + | ||
| 61 | +That could have gone the other way. Putting all three scanners in the library would let any editor colour any of the languages, at no cost in dependencies — a Python scanner is ordinary Go. It was rejected because it would mean the library grows a language every time somebody builds an editor, and because "what does this editor register?" would stop being the first question about a new one. | ||
| 62 | + | ||
| 63 | +## Why the toolchain menu is `~P~ython` and not `~U~v` | ||
| 64 | + | ||
| 65 | +The hot key was the easy part. Nine letters are taken by the fixed menus — F, E, S, R, C, O, W, N and H — and `P` is not one of them, so it lands on the first letter of the word, which costs nobody a second glance. Turbo Rust had no such luck and ended up on `Rus~t~`. | ||
| 66 | + | ||
| 67 | +The name was the real decision, and it went the same way Turbo Rust's did. The menu holds whatever the project put in its tools file, and that is not always uv: the first tools file anybody writes outgrows the language's own toolchain, because a project's commands include containers, databases and a `Makefile` target somebody added in 2019. A menu called **uv** holding `docker compose up` is a lie about what the menu is, in exactly the way the library's own documentation warns about. `Python` is the language, and the language is what this editor is for. | ||
| 68 | + | ||
| 69 | +## Why the tests drive the real editor | ||
| 70 | + | ||
| 71 | +`internal/pythonlang/editor_test.go` builds a whole Turbo Python on a simulated terminal — `app.New(screen, "turbo-classic", pythonlang.Profile())` — opens a file and checks the colouring, the menu bar and the hot keys. It uses only the library's public API. | ||
| 72 | + | ||
| 73 | +That is deliberate. The library's own suite proves the library works; what these tests prove is that *this editor is assembled correctly* — that `Register` was called, that the profile reached the menu bar, that a `.py` file comes out coloured. A bug where `main` forgot to register Python would pass every test in turbo-core. | ||
| 74 | + | ||
| 75 | +The same file drives a **real pylsp** end to end, four times over. It writes a project, opens a file, starts the server, and then: | ||
| 76 | + | ||
| 77 | +- **types text that exists only in the buffer** and asks for a completion — text already on disk proves nothing, because the server answers from disk for anything it has not been told is open; | ||
| 78 | +- asks for the **references** of a name used in three places, which is the answer shape that used to be truncated to one; | ||
| 79 | +- asks for the **file's symbols**, which is a different answer shape again; | ||
| 80 | +- opens a file that **does not parse** and waits for a diagnostic to arrive unasked — the one feature whose failure looks exactly like success, because an editor with no error to show and one that cannot find the error are the same blank gutter. | ||
| 81 | + | ||
| 82 | +A fifth test pins what pylsp *cannot* do: it advertises neither `implementation` nor `workspace/symbol`, the documentation says so, and the test fails if a future pylsp starts answering — so the page gets revisited rather than quietly going stale. | ||
| 83 | + | ||
| 84 | +## Rejected alternatives | ||
| 85 | + | ||
| 86 | +**Forking Turbo Rust.** The obvious way to get a third editor, and the reason the library exists instead: three copies of eleven thousand lines drift within a month, and every fix has to be made three times by somebody who remembers there are three. | ||
| 87 | + | ||
| 88 | +**A plugin system.** Turbo Python is a Go program that imports a library. There is no dynamic loading and no ABI. Adding one would mean freezing the API of every package in turbo-core rather than of the handful a profile touches. | ||
| 89 | + | ||
| 90 | +**A configuration file instead of a profile.** The profile could have been TOML read at start-up, which would make a new editor a file rather than a program. It would also make the scanner inexpressible, and a half-configurable editor — everything but the colouring — is worse than either whole answer. | ||
| 91 | + | ||
| 92 | +## How it relates to the rest | ||
| 93 | + | ||
| 94 | +- What each of the library's packages does: [turbo-core's package reference](https://rickub.com/turbo-editors/turbo-core/blob/main/docs/en/reference/packages.md) | ||
| 95 | +- How the colouring works here: [Colouring and completion](colouring-and-completion.md) | ||
| 96 | +- Why the tools menu is data: [Python tools](python-tools.md) | ||
| 97 | +- The decisions that outlived the refactoring: [Design decisions](design-decisions.md) | ||
added
docs/en/explanation/colouring-and-completion.md +103 -0 | new file mode 100644 | ||
| @@ -0,0 +1,103 @@ | ||
| 1 | +# Colouring and completion — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +The two features that make Turbo Python an editor *for Python* rather than a text editor that happens to open `.py` files: syntax colouring, and completion from a language server. They work quite differently, and the difference is instructive. | |
| 6 | + | |
| 7 | +## Colouring is ours; completion is not | |
| 8 | + | |
| 9 | +Colouring is done here, in about six hundred lines of hand-written Go. Completion is done by python-lsp-server, and Turbo Python only asks and draws. | |
| 10 | + | |
| 11 | +That split is not an accident of effort. Colouring has to be **instant and tolerant**: it runs on every keystroke, on text that is invalid most of the time it is being typed, and a highlighter that stops to think or gives up on broken input is worse than no highlighter. Completion has to be **correct**, which for Python means following imports, resolving a name through the class hierarchy it was assigned in, and reading every installed package's public surface — and nothing that has to be instant can also be that. | |
| 12 | + | |
| 13 | +So the editor draws colours it computed itself, and shows completions somebody else computed. | |
| 14 | + | |
| 15 | +## Why Python is scanned by hand | |
| 16 | + | |
| 17 | +Go has a lexer in its standard library, and Turbo Go uses it: `go/scanner` is the same code the compiler uses, so the editor and the compiler agree about what a token is, with nothing to keep in step. | |
| 18 | + | |
| 19 | +Python has no such thing available here. CPython's tokeniser is C, `tokenize` is a Python module, and jedi's parser is a Python package. The choices were a hand-written scanner, or starting a Python process on every keystroke. | |
| 20 | + | |
| 21 | +The scanner it is. Some six hundred lines, one file each for the dispatcher, the literals and the words — and no attempt at a general engine. There is no pattern language, no grammar format and no table of regular expressions: it is ordinary Go that a reader can follow, which is the same rule the eight scanners in turbo-core follow. | |
| 22 | + | |
| 23 | +## The one thing that crosses a line break | |
| 24 | + | |
| 25 | +Almost everything in Python can be decided from the line in front of you. **A string is the only exception**, and it is an exception in two different ways — which is why what gets carried is a small structure rather than a flag. | |
| 26 | + | |
| 27 | +**A triple-quoted string runs until its three closing quotes**, however many lines away that is. Every docstring is one, so this is not an edge case; it is most of what a Python file contains that is not code. | |
| 28 | + | |
| 29 | +**A single-quoted string runs on only when the line ends with a backslash**, which escapes the newline. That is a real, if uncommon, construct — and it is the reason a single-quoted string that simply *runs out* of line gets dropped instead. Source under the cursor is unbalanced most of the time it is being typed, and an unterminated `"` carried forward paints the rest of the file green. | |
| 30 | + | |
| 31 | +**Which quote opened it is carried too.** A literal opened with three double quotes and one opened with three apostrophes are different strings, and the closer of one appearing inside the other closes nothing. A docstring that quotes anything at all — `"""say "hi" now"""` — is the case that catches a scanner carrying only "a string is open". | |
| 32 | + | |
| 33 | +**Rawness deliberately is not carried.** `r"\""` is one complete string: in a raw string the backslash stays in the value, but it still stops the quote after it from ending the literal. Termination is therefore the same rule for raw and ordinary strings, and a flag saying otherwise would be a flag nothing reads. | |
| 34 | + | |
| 35 | +## Where the scanner leans on convention | |
| 36 | + | |
| 37 | +Python's syntax leaves three questions open that its *conventions* answer, and the scanner reads the conventions rather than pretending the questions are not there. | |
| 38 | + | |
| 39 | +**A class is called exactly the way a function is.** `ValueError("nope")` and `parse("nope")` have the same shape; a parenthesis cannot tell a constructor from a call. What can is PEP 8: a class is `CapWords` and nothing else is. So a capitalised name is a type whether or not a parenthesis follows it — which is the one rule Turbo Python and Turbo Rust deliberately order differently, because in Rust a capitalised name before a parenthesis is usually a variant the language itself names. | |
| 40 | + | |
| 41 | +**A constant looks nothing like a class.** `MAX_SIZE` and `Measurement` are both "capitalised", and PEP 8 keeps them clearly apart: a module-level constant is `SCREAMING_SNAKE_CASE`. Turbo Rust has only the capital rule and documents `SCREAMING_SNAKE_CASE` constants coloured as types as a known wrong answer. Python's conventions are separated well enough that the wrong answer is worth removing rather than inheriting, so a name written wholly in capitals is a constant here. What it costs is a class named `HTTP`, which is rare enough to write down. | |
| 42 | + | |
| 43 | +**`self` is not the language's, and every reader treats it as if it were.** A method may name its first parameter anything; the compiler does not care. But a Python reader reads `self` the way a Rust reader reads `Some` — as a thing the language provides — and every other highlighter agrees. It is coloured as a builtin for that reason, and the honest cost is a plain function that happens to name a parameter `self`. | |
| 44 | + | |
| 45 | +## The one genuine ambiguity | |
| 46 | + | |
| 47 | +`match` and `case` were added to Python without being reserved. `match x:` opens a match statement; `match = re.match(pattern, text)` assigns a variable, and both are ordinary, common Python. | |
| 48 | + | |
| 49 | +Nothing about the word settles it, so the *shape of the statement* does: the word opens the line, and the line ends with the colon that opens its block. Both conditions must hold, which gets every match statement anybody writes and leaves `match` as a name everywhere else. | |
| 50 | + | |
| 51 | +It has a boundary, and the boundary is documented rather than removed. The colon is found by reading backwards from the end of the line — which is what makes the question cheap enough to ask of every word — and a trailing comment hides it, so `match value: # dispatch` colours `match` as a name. Telling a real trailing comment from a `#` inside a string means scanning the line forwards, which is the work reading backwards exists to avoid. It is also the safe direction to be wrong in: a keyword shown as a name is a shade too plain, where a name shown as a keyword is a lie. | |
| 52 | + | |
| 53 | +## What the scanner refuses to guess | |
| 54 | + | |
| 55 | +Where a construct cannot be recognised from what one line holds, it is left alone rather than approximated. A highlighter that is wrong is worse than one that is quiet: | |
| 56 | + | |
| 57 | +| Not recognised | Because | | |
| 58 | +| --- | --- | | |
| 59 | +| The `{expression}` inside an f-string | Since Python 3.12 it may contain anything at all — nested quotes of the same kind, comments, another f-string. Colouring it properly means running the whole scanner inside itself; colouring it half-properly ends `f"{n:{width}}"` at the inner brace. One flat run of string is the honest answer | | |
| 60 | +| A docstring as anything but a string | It *is* a string — `help()` reads it back as one — and the moment somebody assigns one to a name, a scanner that called it a comment is visibly wrong | | |
| 61 | +| Whether a name is bound in this scope | Nothing here reads more than one line at a time. That is the language server's question | | |
| 62 | + | |
| 63 | +## The other eight languages come free | |
| 64 | + | |
| 65 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell are coloured by turbo-core, not here. A Python project has a `pyproject.toml`, a `README.md`, some scripts, a CI workflow in YAML and often a Dockerfile, and an editor that coloured only the `.py` files would make you leave it for the rest. | |
| 66 | + | |
| 67 | +That they are shared rather than copied is the point of the library: they were written once, for Turbo Go, and Turbo Python got them by importing a package. | |
| 68 | + | |
| 69 | +## Completion, and why it can fail silently | |
| 70 | + | |
| 71 | +Turbo Python knows nothing about Python's type system and does not try to. It asks pylsp over the Language Server Protocol and draws the answer. | |
| 72 | + | |
| 73 | +Three things about that are worth knowing, because all three look like "completion is broken": | |
| 74 | + | |
| 75 | +**pylsp answers nothing until it has indexed enough of the project.** jedi resolves a name by following imports outwards, which on a first request into a large dependency means reading a great deal of somebody else's code. What you see meanwhile is an empty list. | |
| 76 | + | |
| 77 | +**A server given the wrong root loads the wrong code, and then answers nothing at all — with no error.** That is why the editor walks up from the file to the nearest `pyproject.toml`, `setup.py` or `setup.cfg` rather than using the working directory, and it is the single most confusing way completion can fail. | |
| 78 | + | |
| 79 | +**A server installed without its extras answers questions but never volunteers a problem.** pylsp's linters are optional dependencies; installed bare, it completes and jumps perfectly well and publishes an *empty* list of diagnostics for a file that does not even parse. A blank gutter because the server has no linter and a blank gutter because the code is fine look identical. That is why [the install command names the extras](../how-to/enable-completion.md) and why the installer checks for them. | |
| 80 | + | |
| 81 | +The editor's answer to the first two is [Run ▸ Language server status](../reference/menus.md), which says what it found, where it started it and whether it is ready — because "nothing happened" is not something a user can act on. | |
| 82 | + | |
| 83 | +## Nine questions, one connection — and the two pylsp does not answer | |
| 84 | + | |
| 85 | +Completion is the loudest thing the language server does and the least revealing. The same connection asks eight more questions, and they divide into three kinds by what comes back. | |
| 86 | + | |
| 87 | +**Something to read.** `hover` — what is this? — drawn in a box. | |
| 88 | + | |
| 89 | +**Places in the code.** `definition`, `typeDefinition`, `implementation`, `references`. One request each, one answer shape between them, which is why they are one function underneath. A single place is opened; several are offered as a list, because a single answer is the exception rather than the rule — a method used across a package has as many references as somebody cared to write, and for a long time this editor took the first and threw the rest away. | |
| 90 | + | |
| 91 | +**Names.** `documentSymbol` for a file's own outline, `workspace/symbol` for a search across the project. The protocol has three shapes for a symbol and the editor wants one, so the flattening is done where the answers arrive rather than where they are drawn. | |
| 92 | + | |
| 93 | +And one thing nobody asks for at all: **`publishDiagnostics` arrives unbidden**, whenever the server has an opinion, for whatever files it has loaded — which are usually more than the one in front of you. That is why Problems lists every file rather than the current one, and why the mark in the gutter appears without anything being pressed. | |
| 94 | + | |
| 95 | +**Two of the nine come back empty with pylsp, and that is the server's boundary rather than the editor's.** pylsp advertises neither `implementation` nor `workspace/symbol`, so **Code ▸ Find implementations** and **Code ▸ Symbol in project** report nothing found. Everything else works. This is written down rather than hidden because the alternative — greying out two menu items depending on what a server said at start-up — makes the menu a different shape on different machines, and a user who has read this page knows more than one who found a greyed item. | |
| 96 | + | |
| 97 | +The editor asks for none of this until the server says it is ready, and says which of those it is when a question cannot be answered. "Nothing found" and "I have not finished loading" are the same empty answer and very different news; conflating them is the most confusing way completion has ever failed here. | |
| 98 | + | |
| 99 | +## How it relates to the rest | |
| 100 | + | |
| 101 | +- Exactly what is recognised: [Languages coloured](../reference/languages.md) | |
| 102 | +- Getting completion working: [How to enable Python completion](../how-to/enable-completion.md) | |
| 103 | +- Where the scanner lives and why: [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | +# Colouring and completion — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +The two features that make Turbo Python an editor *for Python* rather than a text editor that happens to open `.py` files: syntax colouring, and completion from a language server. They work quite differently, and the difference is instructive. | ||
| 6 | + | ||
| 7 | +## Colouring is ours; completion is not | ||
| 8 | + | ||
| 9 | +Colouring is done here, in about six hundred lines of hand-written Go. Completion is done by python-lsp-server, and Turbo Python only asks and draws. | ||
| 10 | + | ||
| 11 | +That split is not an accident of effort. Colouring has to be **instant and tolerant**: it runs on every keystroke, on text that is invalid most of the time it is being typed, and a highlighter that stops to think or gives up on broken input is worse than no highlighter. Completion has to be **correct**, which for Python means following imports, resolving a name through the class hierarchy it was assigned in, and reading every installed package's public surface — and nothing that has to be instant can also be that. | ||
| 12 | + | ||
| 13 | +So the editor draws colours it computed itself, and shows completions somebody else computed. | ||
| 14 | + | ||
| 15 | +## Why Python is scanned by hand | ||
| 16 | + | ||
| 17 | +Go has a lexer in its standard library, and Turbo Go uses it: `go/scanner` is the same code the compiler uses, so the editor and the compiler agree about what a token is, with nothing to keep in step. | ||
| 18 | + | ||
| 19 | +Python has no such thing available here. CPython's tokeniser is C, `tokenize` is a Python module, and jedi's parser is a Python package. The choices were a hand-written scanner, or starting a Python process on every keystroke. | ||
| 20 | + | ||
| 21 | +The scanner it is. Some six hundred lines, one file each for the dispatcher, the literals and the words — and no attempt at a general engine. There is no pattern language, no grammar format and no table of regular expressions: it is ordinary Go that a reader can follow, which is the same rule the eight scanners in turbo-core follow. | ||
| 22 | + | ||
| 23 | +## The one thing that crosses a line break | ||
| 24 | + | ||
| 25 | +Almost everything in Python can be decided from the line in front of you. **A string is the only exception**, and it is an exception in two different ways — which is why what gets carried is a small structure rather than a flag. | ||
| 26 | + | ||
| 27 | +**A triple-quoted string runs until its three closing quotes**, however many lines away that is. Every docstring is one, so this is not an edge case; it is most of what a Python file contains that is not code. | ||
| 28 | + | ||
| 29 | +**A single-quoted string runs on only when the line ends with a backslash**, which escapes the newline. That is a real, if uncommon, construct — and it is the reason a single-quoted string that simply *runs out* of line gets dropped instead. Source under the cursor is unbalanced most of the time it is being typed, and an unterminated `"` carried forward paints the rest of the file green. | ||
| 30 | + | ||
| 31 | +**Which quote opened it is carried too.** A literal opened with three double quotes and one opened with three apostrophes are different strings, and the closer of one appearing inside the other closes nothing. A docstring that quotes anything at all — `"""say "hi" now"""` — is the case that catches a scanner carrying only "a string is open". | ||
| 32 | + | ||
| 33 | +**Rawness deliberately is not carried.** `r"\""` is one complete string: in a raw string the backslash stays in the value, but it still stops the quote after it from ending the literal. Termination is therefore the same rule for raw and ordinary strings, and a flag saying otherwise would be a flag nothing reads. | ||
| 34 | + | ||
| 35 | +## Where the scanner leans on convention | ||
| 36 | + | ||
| 37 | +Python's syntax leaves three questions open that its *conventions* answer, and the scanner reads the conventions rather than pretending the questions are not there. | ||
| 38 | + | ||
| 39 | +**A class is called exactly the way a function is.** `ValueError("nope")` and `parse("nope")` have the same shape; a parenthesis cannot tell a constructor from a call. What can is PEP 8: a class is `CapWords` and nothing else is. So a capitalised name is a type whether or not a parenthesis follows it — which is the one rule Turbo Python and Turbo Rust deliberately order differently, because in Rust a capitalised name before a parenthesis is usually a variant the language itself names. | ||
| 40 | + | ||
| 41 | +**A constant looks nothing like a class.** `MAX_SIZE` and `Measurement` are both "capitalised", and PEP 8 keeps them clearly apart: a module-level constant is `SCREAMING_SNAKE_CASE`. Turbo Rust has only the capital rule and documents `SCREAMING_SNAKE_CASE` constants coloured as types as a known wrong answer. Python's conventions are separated well enough that the wrong answer is worth removing rather than inheriting, so a name written wholly in capitals is a constant here. What it costs is a class named `HTTP`, which is rare enough to write down. | ||
| 42 | + | ||
| 43 | +**`self` is not the language's, and every reader treats it as if it were.** A method may name its first parameter anything; the compiler does not care. But a Python reader reads `self` the way a Rust reader reads `Some` — as a thing the language provides — and every other highlighter agrees. It is coloured as a builtin for that reason, and the honest cost is a plain function that happens to name a parameter `self`. | ||
| 44 | + | ||
| 45 | +## The one genuine ambiguity | ||
| 46 | + | ||
| 47 | +`match` and `case` were added to Python without being reserved. `match x:` opens a match statement; `match = re.match(pattern, text)` assigns a variable, and both are ordinary, common Python. | ||
| 48 | + | ||
| 49 | +Nothing about the word settles it, so the *shape of the statement* does: the word opens the line, and the line ends with the colon that opens its block. Both conditions must hold, which gets every match statement anybody writes and leaves `match` as a name everywhere else. | ||
| 50 | + | ||
| 51 | +It has a boundary, and the boundary is documented rather than removed. The colon is found by reading backwards from the end of the line — which is what makes the question cheap enough to ask of every word — and a trailing comment hides it, so `match value: # dispatch` colours `match` as a name. Telling a real trailing comment from a `#` inside a string means scanning the line forwards, which is the work reading backwards exists to avoid. It is also the safe direction to be wrong in: a keyword shown as a name is a shade too plain, where a name shown as a keyword is a lie. | ||
| 52 | + | ||
| 53 | +## What the scanner refuses to guess | ||
| 54 | + | ||
| 55 | +Where a construct cannot be recognised from what one line holds, it is left alone rather than approximated. A highlighter that is wrong is worse than one that is quiet: | ||
| 56 | + | ||
| 57 | +| Not recognised | Because | | ||
| 58 | +| --- | --- | | ||
| 59 | +| The `{expression}` inside an f-string | Since Python 3.12 it may contain anything at all — nested quotes of the same kind, comments, another f-string. Colouring it properly means running the whole scanner inside itself; colouring it half-properly ends `f"{n:{width}}"` at the inner brace. One flat run of string is the honest answer | | ||
| 60 | +| A docstring as anything but a string | It *is* a string — `help()` reads it back as one — and the moment somebody assigns one to a name, a scanner that called it a comment is visibly wrong | | ||
| 61 | +| Whether a name is bound in this scope | Nothing here reads more than one line at a time. That is the language server's question | | ||
| 62 | + | ||
| 63 | +## The other eight languages come free | ||
| 64 | + | ||
| 65 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell are coloured by turbo-core, not here. A Python project has a `pyproject.toml`, a `README.md`, some scripts, a CI workflow in YAML and often a Dockerfile, and an editor that coloured only the `.py` files would make you leave it for the rest. | ||
| 66 | + | ||
| 67 | +That they are shared rather than copied is the point of the library: they were written once, for Turbo Go, and Turbo Python got them by importing a package. | ||
| 68 | + | ||
| 69 | +## Completion, and why it can fail silently | ||
| 70 | + | ||
| 71 | +Turbo Python knows nothing about Python's type system and does not try to. It asks pylsp over the Language Server Protocol and draws the answer. | ||
| 72 | + | ||
| 73 | +Three things about that are worth knowing, because all three look like "completion is broken": | ||
| 74 | + | ||
| 75 | +**pylsp answers nothing until it has indexed enough of the project.** jedi resolves a name by following imports outwards, which on a first request into a large dependency means reading a great deal of somebody else's code. What you see meanwhile is an empty list. | ||
| 76 | + | ||
| 77 | +**A server given the wrong root loads the wrong code, and then answers nothing at all — with no error.** That is why the editor walks up from the file to the nearest `pyproject.toml`, `setup.py` or `setup.cfg` rather than using the working directory, and it is the single most confusing way completion can fail. | ||
| 78 | + | ||
| 79 | +**A server installed without its extras answers questions but never volunteers a problem.** pylsp's linters are optional dependencies; installed bare, it completes and jumps perfectly well and publishes an *empty* list of diagnostics for a file that does not even parse. A blank gutter because the server has no linter and a blank gutter because the code is fine look identical. That is why [the install command names the extras](../how-to/enable-completion.md) and why the installer checks for them. | ||
| 80 | + | ||
| 81 | +The editor's answer to the first two is [Run ▸ Language server status](../reference/menus.md), which says what it found, where it started it and whether it is ready — because "nothing happened" is not something a user can act on. | ||
| 82 | + | ||
| 83 | +## Nine questions, one connection — and the two pylsp does not answer | ||
| 84 | + | ||
| 85 | +Completion is the loudest thing the language server does and the least revealing. The same connection asks eight more questions, and they divide into three kinds by what comes back. | ||
| 86 | + | ||
| 87 | +**Something to read.** `hover` — what is this? — drawn in a box. | ||
| 88 | + | ||
| 89 | +**Places in the code.** `definition`, `typeDefinition`, `implementation`, `references`. One request each, one answer shape between them, which is why they are one function underneath. A single place is opened; several are offered as a list, because a single answer is the exception rather than the rule — a method used across a package has as many references as somebody cared to write, and for a long time this editor took the first and threw the rest away. | ||
| 90 | + | ||
| 91 | +**Names.** `documentSymbol` for a file's own outline, `workspace/symbol` for a search across the project. The protocol has three shapes for a symbol and the editor wants one, so the flattening is done where the answers arrive rather than where they are drawn. | ||
| 92 | + | ||
| 93 | +And one thing nobody asks for at all: **`publishDiagnostics` arrives unbidden**, whenever the server has an opinion, for whatever files it has loaded — which are usually more than the one in front of you. That is why Problems lists every file rather than the current one, and why the mark in the gutter appears without anything being pressed. | ||
| 94 | + | ||
| 95 | +**Two of the nine come back empty with pylsp, and that is the server's boundary rather than the editor's.** pylsp advertises neither `implementation` nor `workspace/symbol`, so **Code ▸ Find implementations** and **Code ▸ Symbol in project** report nothing found. Everything else works. This is written down rather than hidden because the alternative — greying out two menu items depending on what a server said at start-up — makes the menu a different shape on different machines, and a user who has read this page knows more than one who found a greyed item. | ||
| 96 | + | ||
| 97 | +The editor asks for none of this until the server says it is ready, and says which of those it is when a question cannot be answered. "Nothing found" and "I have not finished loading" are the same empty answer and very different news; conflating them is the most confusing way completion has ever failed here. | ||
| 98 | + | ||
| 99 | +## How it relates to the rest | ||
| 100 | + | ||
| 101 | +- Exactly what is recognised: [Languages coloured](../reference/languages.md) | ||
| 102 | +- Getting completion working: [How to enable Python completion](../how-to/enable-completion.md) | ||
| 103 | +- Where the scanner lives and why: [Architecture](architecture.md) | ||
added
docs/en/explanation/design-decisions.md +109 -0 | new file mode 100644 | ||
| @@ -0,0 +1,109 @@ | ||
| 1 | +# Design decisions — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +The choices that shaped Turbo Python, what the alternatives were, and why they were turned down. This is the page to read before changing something that looks arbitrary. | |
| 6 | + | |
| 7 | +## Two dependencies, and no more | |
| 8 | + | |
| 9 | +Turbo Python depends on `tcell/v2` and `BurntSushi/toml`. Everything else is the standard library — including the tokeniser, the JSON-RPC client, the LSP framing and the file handling. | |
| 10 | + | |
| 11 | +**What was rejected.** `go.lsp.dev/jsonrpc2` would have saved perhaps three hundred lines of `internal/lsp`. `rivo/tview` would have saved rather more of `internal/ui`. A syntax-highlighting library would have brought fifty languages instead of one. | |
| 12 | + | |
| 13 | +**Why.** An editor is a program you keep for years and change often. Every dependency is a piece of it you cannot change, cannot fully test, and have to track. The protocol is simple enough to write down, and writing it down put the whole conversation somewhere a reader can follow. Three hundred lines you understand beat three hundred you inherit. | |
| 14 | + | |
| 15 | +The exception proves the rule: `tcell` is not a convenience, it is the terminal-compatibility database, and reimplementing that would be neither small nor honest work. | |
| 16 | + | |
| 17 | +## The widget framework is hand-written | |
| 18 | + | |
| 19 | +`tview` has widgets. `bubbletea` has an architecture. Neither has what Turbo Vision had: overlapping movable windows with shadows, a menu bar with hot keys, and modal dialogs, all drawn with box characters in sixteen colours. | |
| 20 | + | |
| 21 | +The Elm-style architecture that `bubbletea` uses re-renders the whole view on every message. That model is excellent for a form and awkward for a full-screen editor with windows stacked on top of each other and a cursor that has to be in one exact cell. | |
| 22 | + | |
| 23 | +Writing the framework cost roughly fifteen hundred lines. In exchange the editor looks like Turbo C rather than like a modern TUI wearing a blue background, and every drawing decision is one file away. | |
| 24 | + | |
| 25 | +## Bounds are absolute screen coordinates | |
| 26 | + | |
| 27 | +Every widget's `Bounds()` is where it really is on the terminal, not where it is relative to its parent. Hit-testing a mouse click is then a plain rectangle test, and no event ever needs translating on its way down. | |
| 28 | + | |
| 29 | +**The cost** is that containers place their children in screen space. **The alternative** — relative coordinates with a translation at each hop — moves the arithmetic from layout into event handling, where it is done far more often and is far easier to get wrong. Clipping still composes correctly because a painter intersects its parent's clip, so a child with wrong arithmetic draws nothing rather than drawing over its neighbours. | |
| 30 | + | |
| 31 | +## Every change goes through one function | |
| 32 | + | |
| 33 | +`buffer.ReplaceRange` is the only place the text is modified. Insert, backspace, delete, indent, paste and undo all funnel through it, and it is the only place the undo history, the modified flag, the revision counter and the cursor are maintained. | |
| 34 | + | |
| 35 | +The alternative — each operation maintaining its own bookkeeping — is how undo bugs are born. There is exactly one thing to get right, and it is tested directly. | |
| 36 | + | |
| 37 | +## Windows follow the terminal, they do not scale with it | |
| 38 | + | |
| 39 | +A window has a **grow mode**, which names the desktop edges it follows. A document window follows the right and bottom edges: its top-left corner stays where it is, and its far corner moves by exactly as much as the terminal's did. A window that filled the terminal therefore still fills it, and one you had cascaded keeps its offset. | |
| 40 | + | |
| 41 | +**The alternative was proportional scaling** — multiply every window's rectangle by the ratio of the old and new sizes. It was rejected because it moves windows the user deliberately placed, and because rounding makes it lossy: shrink and grow again and nothing is where it was. Turbo Vision used grow modes, and they are still the right answer. | |
| 42 | + | |
| 43 | +Whatever its grow mode, a window is then held to the desktop's own size. One larger than the desktop that holds it has parts nobody can reach. | |
| 44 | + | |
| 45 | + | |
| 46 | +## A window's boxes say what they will do, not what the window is | |
| 47 | + | |
| 48 | +The frame carries two boxes: `[x]` at the left closes the window, `[■]` at the right fills the desktop. | |
| 49 | + | |
| 50 | +The close box used to be `[■]` — Turbo Vision's own — and it had to move. Two boxes on one frame need to be told apart at a glance, and a filled block reads as "fill the screen" far more readily than as "close". `[x]` is what a close button has meant for thirty years; the block went to the job it actually looks like. | |
| 51 | + | |
| 52 | +The maximise box **changes with the window's state**: `[■]` while there is room to grow, `[▬]` once the window fills the desktop. The alternative was a fixed symbol, and it makes the button ambiguous exactly when you need it — you can see that the window is large, but not whether pressing the box will make it larger still or put it back. A control that shows its *current state* leaves you to work out the action; one that shows its *action* does not. | |
| 53 | + | |
| 54 | +A window with nowhere to maximise into shows **no box at all**, rather than one that does nothing. Only the desktop knows what area a window would fill, so a window that is not on one has nothing to offer. | |
| 55 | + | |
| 56 | +**Window ▸ Maximise is the same toggle**, not a one-way action. A menu item and a button that disagreed about what "maximise" means would be a bug people reported rather than a subtlety they appreciated. | |
| 57 | + | |
| 58 | +## Undo merges runs of typing | |
| 59 | + | |
| 60 | +Typing `func` and pressing Ctrl-Z removes all four letters. So does a run of backspaces. Moving the cursor ends the run, and typing never merges with deleting. | |
| 61 | + | |
| 62 | +Character-by-character undo is what a naive implementation gives you, and it is what Turbo C itself did. It is also what nobody wants any more. | |
| 63 | + | |
| 64 | +## Themes are TOML, with two kinds of inheritance | |
| 65 | + | |
| 66 | +**Between files**, `inherits` takes the parent's resolved styles as the starting point. A theme of your own can therefore be five lines. | |
| 67 | + | |
| 68 | +**Between keys**, along the dots: `syntax.keyword` falls back to `syntax`, and `syntax` to `default`. This happens twice — once at parse time, so an entry setting only `fg` inherits its `bg`, and once at lookup time, so a theme that never mentions `syntax.keyword` still colours keywords. | |
| 69 | + | |
| 70 | +That second one is what makes a partial theme a usable theme, and it is why there is no such thing as a theme that leaves half the screen unpainted. | |
| 71 | + | |
| 72 | +**Why TOML rather than JSON.** Comments. A theme is a file people edit by hand and annotate. | |
| 73 | + | |
| 74 | +**An unknown colour is an error**, not a silent fallback to the terminal default. A typo that quietly repaints half the screen is much harder to find than one that says so at load. | |
| 75 | + | |
| 76 | +## The language server is optional by construction | |
| 77 | + | |
| 78 | +`app.Language` wraps the whole pylsp conversation, and when there is no server every method is a no-op rather than an error. Nothing else in the editor asks whether a language server exists. | |
| 79 | + | |
| 80 | +The alternative — checking for `nil` at each of the twenty call sites — is twenty chances to forget. Here, forgetting is impossible: there is nothing to check. | |
| 81 | + | |
| 82 | +This is why `pylsp` is not bundled, not downloaded, and not required. It is looked for on `PATH` and in `GOPATH/bin`, and its absence is reported on the status bar with the one command that fixes it. | |
| 83 | + | |
| 84 | +## Saving is atomic, and byte-faithful | |
| 85 | + | |
| 86 | +A save writes to a temporary file in the same directory and renames it over the target, preserving the original's permissions. An interrupted save cannot leave a half-written source file. | |
| 87 | + | |
| 88 | +Separately, the line endings a file was read with and its trailing newline — or lack of one — are remembered, so opening and saving an untouched file reproduces it byte for byte. An editor that silently normalises line endings turns a one-line change into a whole-file diff. | |
| 89 | + | |
| 90 | +## The clipboard is the editor's own | |
| 91 | + | |
| 92 | +A terminal program cannot read the host clipboard portably. Rather than pretend, Turbo Python shares one clipboard between its own windows, which is what Turbo C did. | |
| 93 | + | |
| 94 | +## The version is a property of the build, not of the source | |
| 95 | + | |
| 96 | +The version used to be `const Version = "0.1.0"` in the editor's own source. It was accurate the day it was written and wrong for the fourteen commits after it, because nothing in the process of committing, tagging or installing touches a Go constant. An About box is where somebody looks when they are about to report a bug; a number there that names a release the binary is not is worse than no number, because it is believed. | |
| 97 | + | |
| 98 | +So the number is taken from the build. The linker stamps `git describe --tags --dirty` into `internal/version` from the Makefile and from the installer, which is what makes `make install` produce an editor that names the commit it came from. When nothing stamped it, the binary asks `runtime/debug.ReadBuildInfo()`, which covers the one path that cannot be stamped: `go install rickub.com/turbo-editors/turbo-python@v0.2.0`, where there is no Makefile in the picture and the Go tool knows the module version. Only when both are silent does it say `unknown` — deliberately not a number, because the whole failure being designed against is a plausible-looking version nobody set. | |
| 99 | + | |
| 100 | +Two things the build system cannot do explain the rest of the design. **It does not read git tags**, so a plain `go build .` can never report `0.1.0-14-g88a4c38` however clever the code is; it reports `devel` plus the commit, and the documentation says so rather than implying that every build is equal. And what it *does* report for such a build is a **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — which is shown as `devel` instead, because its `0.1.1` is a patch release that does not exist and would be read as one. | |
| 101 | + | |
| 102 | +`vcs.time` is deliberately unused. It is the commit's timestamp, and every binary is linked later than the commit it was built from, so labelling it "Built" would be false on all of them. A build date is shown only when a build actually stamped one, which is the same rule the About box follows throughout: **a fact nobody recorded gets no line**, rather than an empty one that reads as a failure to fill it in. | |
| 103 | + | |
| 104 | +Rejected: a `make release` target that tags, builds and pushes. Releasing is three git commands, and wrapping them hides which of them failed; the version stamping is the part that could not be done by hand reliably, and that is the part that was automated. | |
| 105 | + | |
| 106 | +## How it relates to the rest | |
| 107 | + | |
| 108 | +- What the packages are and how they fit: [Architecture](architecture.md) | |
| 109 | +- How the colouring and the completion work: [Colouring and completion](colouring-and-completion.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,109 @@ | |||
| 1 | +# Design decisions — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +The choices that shaped Turbo Python, what the alternatives were, and why they were turned down. This is the page to read before changing something that looks arbitrary. | ||
| 6 | + | ||
| 7 | +## Two dependencies, and no more | ||
| 8 | + | ||
| 9 | +Turbo Python depends on `tcell/v2` and `BurntSushi/toml`. Everything else is the standard library — including the tokeniser, the JSON-RPC client, the LSP framing and the file handling. | ||
| 10 | + | ||
| 11 | +**What was rejected.** `go.lsp.dev/jsonrpc2` would have saved perhaps three hundred lines of `internal/lsp`. `rivo/tview` would have saved rather more of `internal/ui`. A syntax-highlighting library would have brought fifty languages instead of one. | ||
| 12 | + | ||
| 13 | +**Why.** An editor is a program you keep for years and change often. Every dependency is a piece of it you cannot change, cannot fully test, and have to track. The protocol is simple enough to write down, and writing it down put the whole conversation somewhere a reader can follow. Three hundred lines you understand beat three hundred you inherit. | ||
| 14 | + | ||
| 15 | +The exception proves the rule: `tcell` is not a convenience, it is the terminal-compatibility database, and reimplementing that would be neither small nor honest work. | ||
| 16 | + | ||
| 17 | +## The widget framework is hand-written | ||
| 18 | + | ||
| 19 | +`tview` has widgets. `bubbletea` has an architecture. Neither has what Turbo Vision had: overlapping movable windows with shadows, a menu bar with hot keys, and modal dialogs, all drawn with box characters in sixteen colours. | ||
| 20 | + | ||
| 21 | +The Elm-style architecture that `bubbletea` uses re-renders the whole view on every message. That model is excellent for a form and awkward for a full-screen editor with windows stacked on top of each other and a cursor that has to be in one exact cell. | ||
| 22 | + | ||
| 23 | +Writing the framework cost roughly fifteen hundred lines. In exchange the editor looks like Turbo C rather than like a modern TUI wearing a blue background, and every drawing decision is one file away. | ||
| 24 | + | ||
| 25 | +## Bounds are absolute screen coordinates | ||
| 26 | + | ||
| 27 | +Every widget's `Bounds()` is where it really is on the terminal, not where it is relative to its parent. Hit-testing a mouse click is then a plain rectangle test, and no event ever needs translating on its way down. | ||
| 28 | + | ||
| 29 | +**The cost** is that containers place their children in screen space. **The alternative** — relative coordinates with a translation at each hop — moves the arithmetic from layout into event handling, where it is done far more often and is far easier to get wrong. Clipping still composes correctly because a painter intersects its parent's clip, so a child with wrong arithmetic draws nothing rather than drawing over its neighbours. | ||
| 30 | + | ||
| 31 | +## Every change goes through one function | ||
| 32 | + | ||
| 33 | +`buffer.ReplaceRange` is the only place the text is modified. Insert, backspace, delete, indent, paste and undo all funnel through it, and it is the only place the undo history, the modified flag, the revision counter and the cursor are maintained. | ||
| 34 | + | ||
| 35 | +The alternative — each operation maintaining its own bookkeeping — is how undo bugs are born. There is exactly one thing to get right, and it is tested directly. | ||
| 36 | + | ||
| 37 | +## Windows follow the terminal, they do not scale with it | ||
| 38 | + | ||
| 39 | +A window has a **grow mode**, which names the desktop edges it follows. A document window follows the right and bottom edges: its top-left corner stays where it is, and its far corner moves by exactly as much as the terminal's did. A window that filled the terminal therefore still fills it, and one you had cascaded keeps its offset. | ||
| 40 | + | ||
| 41 | +**The alternative was proportional scaling** — multiply every window's rectangle by the ratio of the old and new sizes. It was rejected because it moves windows the user deliberately placed, and because rounding makes it lossy: shrink and grow again and nothing is where it was. Turbo Vision used grow modes, and they are still the right answer. | ||
| 42 | + | ||
| 43 | +Whatever its grow mode, a window is then held to the desktop's own size. One larger than the desktop that holds it has parts nobody can reach. | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +## A window's boxes say what they will do, not what the window is | ||
| 47 | + | ||
| 48 | +The frame carries two boxes: `[x]` at the left closes the window, `[■]` at the right fills the desktop. | ||
| 49 | + | ||
| 50 | +The close box used to be `[■]` — Turbo Vision's own — and it had to move. Two boxes on one frame need to be told apart at a glance, and a filled block reads as "fill the screen" far more readily than as "close". `[x]` is what a close button has meant for thirty years; the block went to the job it actually looks like. | ||
| 51 | + | ||
| 52 | +The maximise box **changes with the window's state**: `[■]` while there is room to grow, `[▬]` once the window fills the desktop. The alternative was a fixed symbol, and it makes the button ambiguous exactly when you need it — you can see that the window is large, but not whether pressing the box will make it larger still or put it back. A control that shows its *current state* leaves you to work out the action; one that shows its *action* does not. | ||
| 53 | + | ||
| 54 | +A window with nowhere to maximise into shows **no box at all**, rather than one that does nothing. Only the desktop knows what area a window would fill, so a window that is not on one has nothing to offer. | ||
| 55 | + | ||
| 56 | +**Window ▸ Maximise is the same toggle**, not a one-way action. A menu item and a button that disagreed about what "maximise" means would be a bug people reported rather than a subtlety they appreciated. | ||
| 57 | + | ||
| 58 | +## Undo merges runs of typing | ||
| 59 | + | ||
| 60 | +Typing `func` and pressing Ctrl-Z removes all four letters. So does a run of backspaces. Moving the cursor ends the run, and typing never merges with deleting. | ||
| 61 | + | ||
| 62 | +Character-by-character undo is what a naive implementation gives you, and it is what Turbo C itself did. It is also what nobody wants any more. | ||
| 63 | + | ||
| 64 | +## Themes are TOML, with two kinds of inheritance | ||
| 65 | + | ||
| 66 | +**Between files**, `inherits` takes the parent's resolved styles as the starting point. A theme of your own can therefore be five lines. | ||
| 67 | + | ||
| 68 | +**Between keys**, along the dots: `syntax.keyword` falls back to `syntax`, and `syntax` to `default`. This happens twice — once at parse time, so an entry setting only `fg` inherits its `bg`, and once at lookup time, so a theme that never mentions `syntax.keyword` still colours keywords. | ||
| 69 | + | ||
| 70 | +That second one is what makes a partial theme a usable theme, and it is why there is no such thing as a theme that leaves half the screen unpainted. | ||
| 71 | + | ||
| 72 | +**Why TOML rather than JSON.** Comments. A theme is a file people edit by hand and annotate. | ||
| 73 | + | ||
| 74 | +**An unknown colour is an error**, not a silent fallback to the terminal default. A typo that quietly repaints half the screen is much harder to find than one that says so at load. | ||
| 75 | + | ||
| 76 | +## The language server is optional by construction | ||
| 77 | + | ||
| 78 | +`app.Language` wraps the whole pylsp conversation, and when there is no server every method is a no-op rather than an error. Nothing else in the editor asks whether a language server exists. | ||
| 79 | + | ||
| 80 | +The alternative — checking for `nil` at each of the twenty call sites — is twenty chances to forget. Here, forgetting is impossible: there is nothing to check. | ||
| 81 | + | ||
| 82 | +This is why `pylsp` is not bundled, not downloaded, and not required. It is looked for on `PATH` and in `GOPATH/bin`, and its absence is reported on the status bar with the one command that fixes it. | ||
| 83 | + | ||
| 84 | +## Saving is atomic, and byte-faithful | ||
| 85 | + | ||
| 86 | +A save writes to a temporary file in the same directory and renames it over the target, preserving the original's permissions. An interrupted save cannot leave a half-written source file. | ||
| 87 | + | ||
| 88 | +Separately, the line endings a file was read with and its trailing newline — or lack of one — are remembered, so opening and saving an untouched file reproduces it byte for byte. An editor that silently normalises line endings turns a one-line change into a whole-file diff. | ||
| 89 | + | ||
| 90 | +## The clipboard is the editor's own | ||
| 91 | + | ||
| 92 | +A terminal program cannot read the host clipboard portably. Rather than pretend, Turbo Python shares one clipboard between its own windows, which is what Turbo C did. | ||
| 93 | + | ||
| 94 | +## The version is a property of the build, not of the source | ||
| 95 | + | ||
| 96 | +The version used to be `const Version = "0.1.0"` in the editor's own source. It was accurate the day it was written and wrong for the fourteen commits after it, because nothing in the process of committing, tagging or installing touches a Go constant. An About box is where somebody looks when they are about to report a bug; a number there that names a release the binary is not is worse than no number, because it is believed. | ||
| 97 | + | ||
| 98 | +So the number is taken from the build. The linker stamps `git describe --tags --dirty` into `internal/version` from the Makefile and from the installer, which is what makes `make install` produce an editor that names the commit it came from. When nothing stamped it, the binary asks `runtime/debug.ReadBuildInfo()`, which covers the one path that cannot be stamped: `go install rickub.com/turbo-editors/turbo-python@v0.2.0`, where there is no Makefile in the picture and the Go tool knows the module version. Only when both are silent does it say `unknown` — deliberately not a number, because the whole failure being designed against is a plausible-looking version nobody set. | ||
| 99 | + | ||
| 100 | +Two things the build system cannot do explain the rest of the design. **It does not read git tags**, so a plain `go build .` can never report `0.1.0-14-g88a4c38` however clever the code is; it reports `devel` plus the commit, and the documentation says so rather than implying that every build is equal. And what it *does* report for such a build is a **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — which is shown as `devel` instead, because its `0.1.1` is a patch release that does not exist and would be read as one. | ||
| 101 | + | ||
| 102 | +`vcs.time` is deliberately unused. It is the commit's timestamp, and every binary is linked later than the commit it was built from, so labelling it "Built" would be false on all of them. A build date is shown only when a build actually stamped one, which is the same rule the About box follows throughout: **a fact nobody recorded gets no line**, rather than an empty one that reads as a failure to fill it in. | ||
| 103 | + | ||
| 104 | +Rejected: a `make release` target that tags, builds and pushes. Releasing is three git commands, and wrapping them hides which of them failed; the version stamping is the part that could not be done by hand reliably, and that is the part that was automated. | ||
| 105 | + | ||
| 106 | +## How it relates to the rest | ||
| 107 | + | ||
| 108 | +- What the packages are and how they fit: [Architecture](architecture.md) | ||
| 109 | +- How the colouring and the completion work: [Colouring and completion](colouring-and-completion.md) | ||
added
docs/en/explanation/project-settings.md +68 -0 | new file mode 100644 | ||
| @@ -0,0 +1,68 @@ | ||
| 1 | +# Project settings — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +A project can keep a `.turbo-python/settings.toml` beside its code, saying which theme to use and whether to save files automatically. This page is about the decisions inside that sentence: why the file is only ever looked for in one place, why creating it is a menu item rather than something that happens by itself, and why automatic saving works the way it does. | |
| 6 | + | |
| 7 | +## Why the directory is not searched for upwards | |
| 8 | + | |
| 9 | +`pyproject.toml` is found by walking up from the file you opened until one turns up, and the language server uses exactly that. The settings file deliberately does not. | |
| 10 | + | |
| 11 | +The walk is right for `pyproject.toml` because a module has a real boundary: the file is either above you or it is not, and being inside a module is a fact about the code. "The project" is not a fact about the code. It is where you decided to start working, and the same directory tree can be several projects depending on what you are doing in it — a monorepo's `services/api` is a project when you are working on the API and part of a larger one when you are not. | |
| 12 | + | |
| 13 | +A walk would also make the setting act at a distance. You open a file, and the editor's colours change because of a file three directories up that you did not know existed. Every explanation of that behaviour has to start with "well, it searches upwards", and the rule you would rather be able to state is the one that is now true: **the project is the directory you started the editor in.** | |
| 14 | + | |
| 15 | +The cost is real and worth naming. Start the editor from `internal/app` and the project's theme does not apply. The answer is to start from the project root, which is where you would run `go build` and `git` anyway. | |
| 16 | + | |
| 17 | +## Why creating the file is a menu item | |
| 18 | + | |
| 19 | +The alternative was tempting: the first time you pick a theme, write `.turbo-python/settings.toml` so the choice sticks. Every editor that stores workspace state does something like it. | |
| 20 | + | |
| 21 | +It was rejected because it puts a directory into someone's repository as a side effect of trying a colour. The user is one `git status` away from a change they did not make, in a project that may not be theirs, possibly in a review. A theme picked to look at for ten seconds should not leave anything behind. | |
| 22 | + | |
| 23 | +So the file is created only by **Options ▸ Create project settings**, and its existence means something: this project has settings on purpose. That is also what makes the write-back rule simple to state — **the theme is written to the file when the file exists, and not otherwise** — with no flag anywhere for "do you want to remember this?". | |
| 24 | + | |
| 25 | +## Why the theme is written in place rather than re-encoded | |
| 26 | + | |
| 27 | +Once the file exists, picking a theme rewrites it. Marshalling the `Settings` struct back to TOML would be four lines and would delete every comment in the file. | |
| 28 | + | |
| 29 | +That matters more here than it usually would, because this file is *meant* to be edited by hand. It is the reason TOML colouring exists in the editor at all; the created file is mostly comments explaining the keys; a team will add comments of their own saying why they chose what they chose. Losing all of it the first time someone tries a different theme would be a silent, surprising deletion of somebody's writing. | |
| 30 | + | |
| 31 | +So the rewrite finds the `theme` line inside the `[editor]` table and changes the value between the `=` and any trailing comment. Everything else in the file comes back byte for byte. It is about forty lines rather than four, and it is the difference between a file you can keep things in and a file that eats them. | |
| 32 | + | |
| 33 | +## Why automatic saving waits for a pause | |
| 34 | + | |
| 35 | +Three triggers were considered. | |
| 36 | + | |
| 37 | +**On a fixed interval** is the simplest and is wrong: it writes in the middle of an edit. Half a renamed identifier reaches disk, a file watcher rebuilds, and a test suite fails on code that never existed as anyone's intention. | |
| 38 | + | |
| 39 | +**On leaving the window** never writes while you work, which sounds safe and means the thing on disk can be an hour behind the thing on screen — precisely when it matters, because the reason to want autosave is usually a tool watching the file. | |
| 40 | + | |
| 41 | +**After a pause in typing** is what both other editors and this one settled on. Two seconds is long enough that a pause for thought is not a write, short enough that a rebuild follows a change closely. A run of typing is one write, not one per keystroke. | |
| 42 | + | |
| 43 | +There is one deadline for the whole editor rather than one per window, because "you stopped typing" is one event. A per-window deadline would save the file you have moved away from at a different moment from the one in front of you, which nobody could observe and which is more state to keep right. | |
| 44 | + | |
| 45 | +## Why the deadline is checked, and only nudged by a timer | |
| 46 | + | |
| 47 | +This is the same trap the language-server announcement and the terminal redraws both hit, and it is worth stating once more because it will come up again. | |
| 48 | + | |
| 49 | +The editor blocks in `PollEvent`. To notice a deadline while nothing is happening, something has to wake it, and the only way to wake it from a timer is `PostEvent` — which **drops** events when its queue is full. | |
| 50 | + | |
| 51 | +So the timer is not what decides. The deadline is state, checked at the top of every turn of the event loop, exactly as `announceOpenDocuments` checks whether the language server is ready. The timer's only job is to make sure a turn happens. A nudge that gets dropped costs a save that is late until the next keystroke or click; a design where the timer did the saving would lose it altogether. | |
| 52 | + | |
| 53 | +## Why a failed automatic save does not open a dialog | |
| 54 | + | |
| 55 | +An autosave nobody asked for should not interrupt with a modal, and a modal that reappears every two seconds because a file is read-only is worse than the problem it reports. It goes on the status bar instead, and the deadline is cleared *before* the write is attempted, so a file that cannot be written is tried once per edit rather than forever. | |
| 56 | + | |
| 57 | +## Why TOML colouring reuses the code classes | |
| 58 | + | |
| 59 | +Adding `syntax.tomlkey` and friends would have meant every theme — including the ones users have written — silently failing to colour TOML until it was updated. | |
| 60 | + | |
| 61 | +The classes already there fit: a table header names a structure, so it reads as a type; a key names a thing, so it reads as an identifier; `true` and `false` are constants because that is what they are. The result is that every theme that ever worked colours TOML correctly, with no change and no new keys. The scanner is hand-written for the same reason the terminal emulator is — TOML is a small, fully specified language, and it is one file against a third dependency. | |
| 62 | + | |
| 63 | +## How it relates to the rest | |
| 64 | + | |
| 65 | +- The exact keys and their defaults: [Project settings reference](../reference/project-settings.md) | |
| 66 | +- Setting one up: [How to give a project its own settings](../how-to/configure-a-project.md) | |
| 67 | +- The other TOML file the editor reads: [Theme file format](../reference/themes.md) | |
| 68 | +- Where `settings` sits among the packages: [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | +# Project settings — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +A project can keep a `.turbo-python/settings.toml` beside its code, saying which theme to use and whether to save files automatically. This page is about the decisions inside that sentence: why the file is only ever looked for in one place, why creating it is a menu item rather than something that happens by itself, and why automatic saving works the way it does. | ||
| 6 | + | ||
| 7 | +## Why the directory is not searched for upwards | ||
| 8 | + | ||
| 9 | +`pyproject.toml` is found by walking up from the file you opened until one turns up, and the language server uses exactly that. The settings file deliberately does not. | ||
| 10 | + | ||
| 11 | +The walk is right for `pyproject.toml` because a module has a real boundary: the file is either above you or it is not, and being inside a module is a fact about the code. "The project" is not a fact about the code. It is where you decided to start working, and the same directory tree can be several projects depending on what you are doing in it — a monorepo's `services/api` is a project when you are working on the API and part of a larger one when you are not. | ||
| 12 | + | ||
| 13 | +A walk would also make the setting act at a distance. You open a file, and the editor's colours change because of a file three directories up that you did not know existed. Every explanation of that behaviour has to start with "well, it searches upwards", and the rule you would rather be able to state is the one that is now true: **the project is the directory you started the editor in.** | ||
| 14 | + | ||
| 15 | +The cost is real and worth naming. Start the editor from `internal/app` and the project's theme does not apply. The answer is to start from the project root, which is where you would run `go build` and `git` anyway. | ||
| 16 | + | ||
| 17 | +## Why creating the file is a menu item | ||
| 18 | + | ||
| 19 | +The alternative was tempting: the first time you pick a theme, write `.turbo-python/settings.toml` so the choice sticks. Every editor that stores workspace state does something like it. | ||
| 20 | + | ||
| 21 | +It was rejected because it puts a directory into someone's repository as a side effect of trying a colour. The user is one `git status` away from a change they did not make, in a project that may not be theirs, possibly in a review. A theme picked to look at for ten seconds should not leave anything behind. | ||
| 22 | + | ||
| 23 | +So the file is created only by **Options ▸ Create project settings**, and its existence means something: this project has settings on purpose. That is also what makes the write-back rule simple to state — **the theme is written to the file when the file exists, and not otherwise** — with no flag anywhere for "do you want to remember this?". | ||
| 24 | + | ||
| 25 | +## Why the theme is written in place rather than re-encoded | ||
| 26 | + | ||
| 27 | +Once the file exists, picking a theme rewrites it. Marshalling the `Settings` struct back to TOML would be four lines and would delete every comment in the file. | ||
| 28 | + | ||
| 29 | +That matters more here than it usually would, because this file is *meant* to be edited by hand. It is the reason TOML colouring exists in the editor at all; the created file is mostly comments explaining the keys; a team will add comments of their own saying why they chose what they chose. Losing all of it the first time someone tries a different theme would be a silent, surprising deletion of somebody's writing. | ||
| 30 | + | ||
| 31 | +So the rewrite finds the `theme` line inside the `[editor]` table and changes the value between the `=` and any trailing comment. Everything else in the file comes back byte for byte. It is about forty lines rather than four, and it is the difference between a file you can keep things in and a file that eats them. | ||
| 32 | + | ||
| 33 | +## Why automatic saving waits for a pause | ||
| 34 | + | ||
| 35 | +Three triggers were considered. | ||
| 36 | + | ||
| 37 | +**On a fixed interval** is the simplest and is wrong: it writes in the middle of an edit. Half a renamed identifier reaches disk, a file watcher rebuilds, and a test suite fails on code that never existed as anyone's intention. | ||
| 38 | + | ||
| 39 | +**On leaving the window** never writes while you work, which sounds safe and means the thing on disk can be an hour behind the thing on screen — precisely when it matters, because the reason to want autosave is usually a tool watching the file. | ||
| 40 | + | ||
| 41 | +**After a pause in typing** is what both other editors and this one settled on. Two seconds is long enough that a pause for thought is not a write, short enough that a rebuild follows a change closely. A run of typing is one write, not one per keystroke. | ||
| 42 | + | ||
| 43 | +There is one deadline for the whole editor rather than one per window, because "you stopped typing" is one event. A per-window deadline would save the file you have moved away from at a different moment from the one in front of you, which nobody could observe and which is more state to keep right. | ||
| 44 | + | ||
| 45 | +## Why the deadline is checked, and only nudged by a timer | ||
| 46 | + | ||
| 47 | +This is the same trap the language-server announcement and the terminal redraws both hit, and it is worth stating once more because it will come up again. | ||
| 48 | + | ||
| 49 | +The editor blocks in `PollEvent`. To notice a deadline while nothing is happening, something has to wake it, and the only way to wake it from a timer is `PostEvent` — which **drops** events when its queue is full. | ||
| 50 | + | ||
| 51 | +So the timer is not what decides. The deadline is state, checked at the top of every turn of the event loop, exactly as `announceOpenDocuments` checks whether the language server is ready. The timer's only job is to make sure a turn happens. A nudge that gets dropped costs a save that is late until the next keystroke or click; a design where the timer did the saving would lose it altogether. | ||
| 52 | + | ||
| 53 | +## Why a failed automatic save does not open a dialog | ||
| 54 | + | ||
| 55 | +An autosave nobody asked for should not interrupt with a modal, and a modal that reappears every two seconds because a file is read-only is worse than the problem it reports. It goes on the status bar instead, and the deadline is cleared *before* the write is attempted, so a file that cannot be written is tried once per edit rather than forever. | ||
| 56 | + | ||
| 57 | +## Why TOML colouring reuses the code classes | ||
| 58 | + | ||
| 59 | +Adding `syntax.tomlkey` and friends would have meant every theme — including the ones users have written — silently failing to colour TOML until it was updated. | ||
| 60 | + | ||
| 61 | +The classes already there fit: a table header names a structure, so it reads as a type; a key names a thing, so it reads as an identifier; `true` and `false` are constants because that is what they are. The result is that every theme that ever worked colours TOML correctly, with no change and no new keys. The scanner is hand-written for the same reason the terminal emulator is — TOML is a small, fully specified language, and it is one file against a third dependency. | ||
| 62 | + | ||
| 63 | +## How it relates to the rest | ||
| 64 | + | ||
| 65 | +- The exact keys and their defaults: [Project settings reference](../reference/project-settings.md) | ||
| 66 | +- Setting one up: [How to give a project its own settings](../how-to/configure-a-project.md) | ||
| 67 | +- The other TOML file the editor reads: [Theme file format](../reference/themes.md) | ||
| 68 | +- Where `settings` sits among the packages: [Architecture](architecture.md) | ||
added
docs/en/explanation/project-tree.md +58 -0 | new file mode 100644 | ||
| @@ -0,0 +1,58 @@ | ||
| 1 | +# Project tree — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +`F9` opens a window listing the project's files, and pressing `Enter` on one opens it. This page is about the three decisions inside that: where the tree is rooted, why it is a window rather than a panel down the side, and why it does not notice files appearing on its own. | |
| 6 | + | |
| 7 | +## Why the root is the working directory | |
| 8 | + | |
| 9 | +The editor already contains two different answers to "what is the project". | |
| 10 | + | |
| 11 | +The language server walks up from the file you opened until it finds a `pyproject.toml`, because a module has a real boundary — being inside one is a fact about the code, and pylsp needs that exact directory to work in. The project settings file does not walk at all: `.turbo-python/settings.toml` is looked for in the working directory and nowhere else. | |
| 12 | + | |
| 13 | +The tree follows the settings file, and it is worth saying why the *other* rule was tempting. Walking up to the `pyproject.toml` would mean that opening a file from anywhere in a project shows the whole project, which is what an explorer usually does. But it also means the tree's root depends on a file three directories away that you may not have thought about, and it stops being predictable the moment a repository holds more than one module — a monorepo would show you whichever module the file you happened to open belongs to. | |
| 14 | + | |
| 15 | +The rule kept is the one that can be said in a sentence and is true everywhere in the editor: **the project is the directory you started the editor in.** It costs something, and the cost is named in the [how-to](../how-to/browse-a-project.md): start from a subdirectory and you get a tree of that subdirectory. The answer is to start from the project root, which is where you would run `go build` and `git` anyway. | |
| 16 | + | |
| 17 | +## Why `.git` is hidden and nothing else is | |
| 18 | + | |
| 19 | +The Open dialog hides every entry beginning with a dot. Copying that here was the obvious thing and would have been wrong. | |
| 20 | + | |
| 21 | +`.turbo-python/settings.toml` is a file this editor asks people to edit — it is why the editor colours TOML at all. `.gitignore` and `.qlty/qlty.toml` are files of the project too. A tree that hid them would make the editor's own configuration unreachable from the editor's own file browser, which is an odd place to end up. | |
| 22 | + | |
| 23 | +`.git` is different in kind rather than in spelling: nothing inside it is meant to be opened by hand, and it holds enough objects to bury everything else in the listing. One name, hidden for a reason that can be stated. Respecting `.gitignore` as well was considered and turned down for now: it would hide `bin/` and `release/`, which is genuinely nicer, and it costs a gitignore pattern engine — negation, `**`, anchoring — that is a feature in its own right rather than a detail of a tree. | |
| 24 | + | |
| 25 | +## Why it is a window, not a panel | |
| 26 | + | |
| 27 | +Every other editor puts its file tree in a fixed strip down the left. That was the alternative, and it was turned down because of what it would have cost the rest of the editor. | |
| 28 | + | |
| 29 | +A docked panel means the desktop is no longer a single rectangle that windows live in. `Desktop` would need a notion of reserved edges; `Window.fitInto` and the grow modes would have to respect them; maximising would mean "the whole desktop except the panel"; tiling and cascading would need to know about it. That is a change to the foundation of the whole interface, for one widget. | |
| 30 | + | |
| 31 | +As an ordinary window, the tree gets everything for free and behaves like everything else: `F6` reaches it, `Alt-2` raises it, `[x]` closes it, `[■]` fills the desktop with it, **Window ▸ Tile** puts it beside your file. Nothing in `ui` had to change. If a docked panel is wanted later, it is a `ui` feature to be designed on its own terms rather than something smuggled in with a file browser. | |
| 32 | + | |
| 33 | +## Why there is only one | |
| 34 | + | |
| 35 | +Two trees on the same project would be two views of one thing with nothing to tell them apart, and the project cannot change while the editor runs — the root is fixed at start-up. So `F9` on an open tree raises it rather than making another, the same way opening a file that is already open raises its window. | |
| 36 | + | |
| 37 | +## Why it does not watch the disk | |
| 38 | + | |
| 39 | +A tree that noticed `go build` producing `bin/` would be better. Doing it properly means watching the filesystem, and in Go that means `fsnotify` — a third dependency, against a project that has kept to two since it started and treats adding one as a decision to be argued for. | |
| 40 | + | |
| 41 | +It is not a small dependency in behaviour either: recursive watches, watch descriptors running out on large trees, and different semantics on every platform, in a feature whose failure mode is a stale line in a list. | |
| 42 | + | |
| 43 | +So the tree re-reads on demand, and the editor picks the moments it can be sure about. Saving a file is one: the editor did it, so it knows. `F5` and `Ctrl-R` are the other, because a build in a terminal window is something only the user knows has finished. Refreshing keeps the shape of the tree and re-reads only the directories that were actually opened, so it costs what is on screen rather than a walk of the project. | |
| 44 | + | |
| 45 | +## Why the tree has theme keys of its own | |
| 46 | + | |
| 47 | +The obvious economy was to draw it with the `list.*` keys — a tree is a list, after all, and it would have meant no new keys for user themes to miss. | |
| 48 | + | |
| 49 | +It does not work, and the reason is worth recording. `list.selected` is coloured to stand out against a **dialog**. In `turbo-classic` it is white on navy, and `window.body` is silver on **navy** — a tree in a window would have highlighted its selected row in exactly the background colour it sits on. The selection would have been invisible in the theme the editor ships as its default. | |
| 50 | + | |
| 51 | +So `tree.text`, `tree.directory`, `tree.selected` and `tree.unfocused` exist, and a test holds every shipped theme to a minimum contrast between the first and the third, in the same way the cursor colours are checked. A user theme that sets none of them falls back along the dots to `default`: a readable tree without the file-and-directory distinction, rather than nothing at all. | |
| 52 | + | |
| 53 | +## How it relates to the rest | |
| 54 | + | |
| 55 | +- Every key and every rule, exactly: [Project tree reference](../reference/project-tree.md) | |
| 56 | +- Using it: [How to browse a project and open files from a tree](../how-to/browse-a-project.md) | |
| 57 | +- The other place "the project" is defined the same way: [Project settings](project-settings.md) | |
| 58 | +- Where `filetree` sits among the packages: [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | +# Project tree — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +`F9` opens a window listing the project's files, and pressing `Enter` on one opens it. This page is about the three decisions inside that: where the tree is rooted, why it is a window rather than a panel down the side, and why it does not notice files appearing on its own. | ||
| 6 | + | ||
| 7 | +## Why the root is the working directory | ||
| 8 | + | ||
| 9 | +The editor already contains two different answers to "what is the project". | ||
| 10 | + | ||
| 11 | +The language server walks up from the file you opened until it finds a `pyproject.toml`, because a module has a real boundary — being inside one is a fact about the code, and pylsp needs that exact directory to work in. The project settings file does not walk at all: `.turbo-python/settings.toml` is looked for in the working directory and nowhere else. | ||
| 12 | + | ||
| 13 | +The tree follows the settings file, and it is worth saying why the *other* rule was tempting. Walking up to the `pyproject.toml` would mean that opening a file from anywhere in a project shows the whole project, which is what an explorer usually does. But it also means the tree's root depends on a file three directories away that you may not have thought about, and it stops being predictable the moment a repository holds more than one module — a monorepo would show you whichever module the file you happened to open belongs to. | ||
| 14 | + | ||
| 15 | +The rule kept is the one that can be said in a sentence and is true everywhere in the editor: **the project is the directory you started the editor in.** It costs something, and the cost is named in the [how-to](../how-to/browse-a-project.md): start from a subdirectory and you get a tree of that subdirectory. The answer is to start from the project root, which is where you would run `go build` and `git` anyway. | ||
| 16 | + | ||
| 17 | +## Why `.git` is hidden and nothing else is | ||
| 18 | + | ||
| 19 | +The Open dialog hides every entry beginning with a dot. Copying that here was the obvious thing and would have been wrong. | ||
| 20 | + | ||
| 21 | +`.turbo-python/settings.toml` is a file this editor asks people to edit — it is why the editor colours TOML at all. `.gitignore` and `.qlty/qlty.toml` are files of the project too. A tree that hid them would make the editor's own configuration unreachable from the editor's own file browser, which is an odd place to end up. | ||
| 22 | + | ||
| 23 | +`.git` is different in kind rather than in spelling: nothing inside it is meant to be opened by hand, and it holds enough objects to bury everything else in the listing. One name, hidden for a reason that can be stated. Respecting `.gitignore` as well was considered and turned down for now: it would hide `bin/` and `release/`, which is genuinely nicer, and it costs a gitignore pattern engine — negation, `**`, anchoring — that is a feature in its own right rather than a detail of a tree. | ||
| 24 | + | ||
| 25 | +## Why it is a window, not a panel | ||
| 26 | + | ||
| 27 | +Every other editor puts its file tree in a fixed strip down the left. That was the alternative, and it was turned down because of what it would have cost the rest of the editor. | ||
| 28 | + | ||
| 29 | +A docked panel means the desktop is no longer a single rectangle that windows live in. `Desktop` would need a notion of reserved edges; `Window.fitInto` and the grow modes would have to respect them; maximising would mean "the whole desktop except the panel"; tiling and cascading would need to know about it. That is a change to the foundation of the whole interface, for one widget. | ||
| 30 | + | ||
| 31 | +As an ordinary window, the tree gets everything for free and behaves like everything else: `F6` reaches it, `Alt-2` raises it, `[x]` closes it, `[■]` fills the desktop with it, **Window ▸ Tile** puts it beside your file. Nothing in `ui` had to change. If a docked panel is wanted later, it is a `ui` feature to be designed on its own terms rather than something smuggled in with a file browser. | ||
| 32 | + | ||
| 33 | +## Why there is only one | ||
| 34 | + | ||
| 35 | +Two trees on the same project would be two views of one thing with nothing to tell them apart, and the project cannot change while the editor runs — the root is fixed at start-up. So `F9` on an open tree raises it rather than making another, the same way opening a file that is already open raises its window. | ||
| 36 | + | ||
| 37 | +## Why it does not watch the disk | ||
| 38 | + | ||
| 39 | +A tree that noticed `go build` producing `bin/` would be better. Doing it properly means watching the filesystem, and in Go that means `fsnotify` — a third dependency, against a project that has kept to two since it started and treats adding one as a decision to be argued for. | ||
| 40 | + | ||
| 41 | +It is not a small dependency in behaviour either: recursive watches, watch descriptors running out on large trees, and different semantics on every platform, in a feature whose failure mode is a stale line in a list. | ||
| 42 | + | ||
| 43 | +So the tree re-reads on demand, and the editor picks the moments it can be sure about. Saving a file is one: the editor did it, so it knows. `F5` and `Ctrl-R` are the other, because a build in a terminal window is something only the user knows has finished. Refreshing keeps the shape of the tree and re-reads only the directories that were actually opened, so it costs what is on screen rather than a walk of the project. | ||
| 44 | + | ||
| 45 | +## Why the tree has theme keys of its own | ||
| 46 | + | ||
| 47 | +The obvious economy was to draw it with the `list.*` keys — a tree is a list, after all, and it would have meant no new keys for user themes to miss. | ||
| 48 | + | ||
| 49 | +It does not work, and the reason is worth recording. `list.selected` is coloured to stand out against a **dialog**. In `turbo-classic` it is white on navy, and `window.body` is silver on **navy** — a tree in a window would have highlighted its selected row in exactly the background colour it sits on. The selection would have been invisible in the theme the editor ships as its default. | ||
| 50 | + | ||
| 51 | +So `tree.text`, `tree.directory`, `tree.selected` and `tree.unfocused` exist, and a test holds every shipped theme to a minimum contrast between the first and the third, in the same way the cursor colours are checked. A user theme that sets none of them falls back along the dots to `default`: a readable tree without the file-and-directory distinction, rather than nothing at all. | ||
| 52 | + | ||
| 53 | +## How it relates to the rest | ||
| 54 | + | ||
| 55 | +- Every key and every rule, exactly: [Project tree reference](../reference/project-tree.md) | ||
| 56 | +- Using it: [How to browse a project and open files from a tree](../how-to/browse-a-project.md) | ||
| 57 | +- The other place "the project" is defined the same way: [Project settings](project-settings.md) | ||
| 58 | +- Where `filetree` sits among the packages: [Architecture](architecture.md) | ||
added
docs/en/explanation/python-tools.md +119 -0 | new file mode 100644 | ||
| @@ -0,0 +1,119 @@ | ||
| 1 | +# Python tools — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +A **Python** menu whose commands come from a TOML file, each run in a terminal window, and the open files re-read afterwards. This page is about why each of those three is the way it is. | |
| 6 | + | |
| 7 | +## Why the output has three places to go, and a popup by default | |
| 8 | + | |
| 9 | +The first version put every command in a terminal window, and it was the wrong default for five of the six. | |
| 10 | + | |
| 11 | +A terminal is the right answer when the program is *interactive or long*: `uv run` on a script that calls `input()` has to be answerable, and a `uv sync` that turns out to resolve half of PyPI has to be interruptible with `Ctrl-C`. Neither is true of `uv run ruff check .`, which prints four lines and ends. Giving that a whole window — one you then have to close, on a desktop where windows overlap and are numbered — is more ceremony than the result deserves. | |
| 12 | + | |
| 13 | +A popup is the right answer for a command you run, read and dismiss. It is modal, which is a real cost and is named in the [how-to](../how-to/run-uv-commands.md): a `uv sync` you did not expect to be slow holds the editor until it finishes or you press Escape. That cost was accepted on purpose, because the alternative — a dialog appearing unbidden three seconds later — swallows whatever was being typed at the moment it arrives. | |
| 14 | + | |
| 15 | +So the popup **opens immediately and fills in**. You see progress, nothing surprises you, and Escape both closes it and stops the command, which is the only way to interrupt something whose output is not in a terminal. | |
| 16 | + | |
| 17 | +An editing window is the right answer for output you are going to work through: a long `uv run pytest -v`, a coverage report. It is an ordinary buffer, so `Ctrl-F` searches it and `Save as` keeps it. It is filled once the command has ended rather than as it goes, because a buffer growing under the cursor while you search it is the opposite of what that mode is for. | |
| 18 | + | |
| 19 | +None of those three is right for everything, which is why `output` is in the file rather than in the code. `Run` is the worked example: it is the one command in the starter file that says `terminal`, and the comment beside it says why. | |
| 20 | + | |
| 21 | +## Why a terminal window is still there | |
| 22 | + | |
| 23 | +The editor already had one — a real pseudo-terminal with a VT emulator, built for the `F8` windows — so `output = "terminal"` costs one field on its options and buys colours, paging, `Ctrl-C`, keyboard input and scrollback for nothing, because they are the same mechanisms every other terminal uses. | |
| 24 | + | |
| 25 | +The window stays after the command exits, which is the point: the output is what you asked for, and a window that vanished with it would be useless. | |
| 26 | + | |
| 27 | +That needed a fix of its own. A terminal view consumed every key it was given and wrote it to the shell; once the shell had gone the write failed silently and the key was consumed anyway, so `Ctrl-W` could never close a finished window and the mouse was the only way out. A finished view now takes only the scrolling keys and lets the rest through to the editor. | |
| 28 | + | |
| 29 | +## Why the exit code is always in the title | |
| 30 | + | |
| 31 | +`uv sync` succeeding prints nothing at all. A popup with an empty body and a neutral title is indistinguishable from one whose command has not started, and the reader is left guessing at the one thing they wanted to know. | |
| 32 | + | |
| 33 | +So the title carries the verdict — `— ok` or `— exit 1` — and an empty body says `(no output)` once the command has ended. While it is still running the body stays blank, because "(no output)" is a verdict and a running command has not reached one. | |
| 34 | + | |
| 35 | +## Why the commands are in a file | |
| 36 | + | |
| 37 | +Six commands hardwired into the editor would have answered the request. They would also have been wrong within a week. | |
| 38 | + | |
| 39 | +Every command in the starter file goes through `uv`, which creates the environment, resolves the dependencies and runs the tools inside it — so none of them needs an environment to have been activated first. That is a defensible default and it is nobody's universal answer. A project on Poetry wants `poetry run`. One on pip and a hand-made `.venv` wants the bare command, with the environment already on PATH. One that has standardised on `black` and `flake8` wants those rather than `ruff`. `uv run pytest` assumes pytest; a project on `unittest` wants `python -m unittest`. A project with a `Makefile` wants `make check`. None of that is knowable from here, and all of it is one line in a file. | |
| 40 | + | |
| 41 | +So the six are **defaults, not code**: they are the contents of the starter file that **Python ▸ Create tools file** writes, and changing one is editing a file rather than rebuilding an editor. The file is read every time the menu opens, for the same reason the Snippets menu is: an edit should take effect at once, and the file is often open in the window behind the menu. | |
| 42 | + | |
| 43 | +Commands go to `sh -c` — `cmd.exe /S /C` on Windows — rather than being split into an argv here. The file is the user's own, so pipes, globs and `&&` are features rather than hazards, and one entry can be `uv run ruff format . && uv run ruff check . && uv run pytest`. Splitting an argv would mean inventing quoting rules for a string somebody wrote by hand. | |
| 44 | + | |
| 45 | +## Why there is no user-level tools file | |
| 46 | + | |
| 47 | +Snippets are read from two files — yours and the project's — because your snippets are your habits and should follow you between projects. | |
| 48 | + | |
| 49 | +Tools are not like that. They belong to a project's own toolchain: a global tools file would offer `uv run pytest` in a repository that has never heard of uv, and a project pinned to Poetry would get somebody else's habits in its menu. The file is per-project, and that is the whole of the rule. | |
| 50 | + | |
| 51 | +## Why a tool may name its own menu | |
| 52 | + | |
| 53 | +A menu called **Python** holding `docker compose up` is a lie about what the menu is. The first tools file anybody writes outgrows Python, because a project's commands are not all about the language it is written in: containers, databases, deploys, a `Makefile` target somebody added in 2019. | |
| 54 | + | |
| 55 | +Two shapes were considered. A **fixed second menu** called Tools — everything Python in Python, everything else in Tools — is one key in the format and no naming problem at all, but it only moves the lie: a Tools menu holding `docker compose up`, `psql`, and a deploy script is just as undifferentiated, and the moment there are ten entries nobody can find one. And a **second file**, `menus.toml`, keeps the tools file simple at the cost of two files that have to agree about which tools exist. | |
| 56 | + | |
| 57 | +So the menu is a **free-form name on the tool**, in the one file: `menu = "Docker"`. A name nothing else uses creates the menu; leaving the key out means Python. There is no list of allowed names, because a list would be a list of somebody else's projects. | |
| 58 | + | |
| 59 | +Python itself stays fixed on the bar rather than becoming just another name from the file. **Python ▸ Create tools file** has to be reachable in a project that has no tools file at all — which is exactly the project that needs it — and a menu that only exists once the file exists cannot offer to write the file. | |
| 60 | + | |
| 61 | +## Why the hot key is not the file's to choose | |
| 62 | + | |
| 63 | +The author of a tools file cannot know which letters are free. They can see `File`, `Edit`, `Search`, `Run`, `Code`, `Options`, `Window`, `Snippets`, `Python` and `Help` on the bar, but only by counting the underlines, and a project shared between people would then depend on nobody adding a menu that collides. | |
| 64 | + | |
| 65 | +Collisions here are **silent**, which is what makes them worth designing against. The bar answers the first menu whose hot key matches; a second menu claiming the same letter is not an error and draws normally — it simply never opens. That trap has already been sprung once in this editor: `Snippets` and `Search` both wanted `S`, `Snippets` was the unreachable one, and every test passed. The fix then was to move Snippets to `N` by hand. Letting a file name menus makes that a permanent hazard rather than a one-off mistake, so the assignment is done by the editor: the first letter of the name nothing else claims. | |
| 66 | + | |
| 67 | +Tildes written into the name are honoured **when the letter is free**, and quietly overridden when it is not. Refusing the file instead was the alternative, and it is worse: the clash depends on which menus exist, so a tools file that worked would break the day an editor release added a menu. Between a menu on a letter you did not ask for and a menu you cannot open, the first is the smaller loss. | |
| 68 | + | |
| 69 | +When every letter of a name is taken, the menu gets no hot key at all. `F10`, the arrow keys and the mouse still reach it, and the alternative — reaching for a letter that is not in the name — would put an underline under nothing. | |
| 70 | + | |
| 71 | +## Why the bar is rebuilt from a stat | |
| 72 | + | |
| 73 | +`Menu.OnOpen` refills a menu's items just before it drops down, which is how the Python and Snippets menus follow their files without a restart. It cannot help here: the *set* of menus is part of the bar, not part of any one menu, and adding `menu = "Docker"` to the file should put Docker on the bar. | |
| 74 | + | |
| 75 | +Reading and parsing the file on every turn of the event loop would do it, and would also be work done for nothing on every keystroke of a file nobody has edited. So the bar carries the size and modification time of the tools file it was built from, and one `stat` per turn decides whether to rebuild. Editing the file in the window in front of you, saving it, and watching the bar change is the case this is for. | |
| 76 | + | |
| 77 | +## Why open files are re-read, and only some of them | |
| 78 | + | |
| 79 | +`Format` rewrites files on disk — including the one you are looking at. Without anything further, the editor would sit on a stale copy, and the next `F2` would write your unformatted version back over `ruff format`'s work. That is not a rough edge; it is the feature quietly undoing itself. | |
| 80 | + | |
| 81 | +So when a command finishes, the editor re-reads every open file. The interesting part is which ones it refuses to touch. | |
| 82 | + | |
| 83 | +**A file with unsaved changes is left alone**, and the status bar says how many were skipped. Reloading it would throw away work the user has not saved, which no amount of convenience justifies. And the conflict is genuine: the formatter and the unsaved edit disagree about what the file should say, and the editor is not in a position to decide. Naming it and stopping is the honest outcome — the user can save and re-run, or keep editing and format later. | |
| 84 | + | |
| 85 | +Two smaller decisions inside that: | |
| 86 | + | |
| 87 | +- **The cursor stays where it was**, clamped into whatever the file now holds. A formatter moves lines about; putting the cursor back at the top would lose the reader's place for no reason. | |
| 88 | +- **The undo history is discarded.** Undoing back past a reload would restore text the file no longer has, which is worse than not being able to undo at all. | |
| 89 | + | |
| 90 | +## Why the reload happens on the event loop | |
| 91 | + | |
| 92 | +The command's exit is noticed on the goroutine reading the terminal, which may not touch a buffer or the desktop. So it sets a flag, and the reload runs at the top of the next turn of the event loop. | |
| 93 | + | |
| 94 | +This is the fourth thing in the library built that way — the language-server announcement, the terminal redraws, the autosave deadline, and now this. The rule they share is worth stating once more: **the wake-up may be lost, so the state must not be.** `PostEvent` drops what does not fit in its queue, so anything that depends on a message arriving is a bug waiting for a busy moment. A flag the loop checks for itself cannot go missing. | |
| 95 | + | |
| 96 | +## Why a command can ask for a value, and why it asks in double braces | |
| 97 | + | |
| 98 | +`uv venv` needs a directory. `uv run` needs a script. `uv add` needs a package name, and `pytest -k` needs a pattern. None of those can live in the tools file as a fixed string, because the answer is different every time — and a tool that cannot ask is a tool that has to be edited before each use, which is not a tool. | |
| 99 | + | |
| 100 | +So a `{{label}}` in a command is a value the editor asks for first, in a box titled after the tool. **Two of the six starter commands use it**, which is deliberate: a feature demonstrated in the file everybody gets is a feature people find, and one described only in a comment is not. | |
| 101 | + | |
| 102 | +The first of them is the reason this editor's tools file has six commands rather than five. **Creating the virtual environment** is the step in Python that has to happen before any of the others can, and the one a newcomer to a project most often has not done — so it is the first item in the menu, and it asks where to put it, because `.venv` is the usual answer and not the only one. | |
| 103 | + | |
| 104 | +**Single braces were the obvious spelling and are wrong.** `awk '{print $1}'` and `find . -exec rm {} +` are ordinary things to put in a tools file, and reading the first as a placeholder turns a working command into a box asking for "print $1". Double braces collide with almost nothing, and the one construct they do collide with — a nested block in awk — is rare enough to be written down rather than designed around. | |
| 105 | + | |
| 106 | +**The value is quoted by default**, because the alternative fails silently. A path with a space in it, substituted raw, becomes two arguments and the command reports something about a file that does not exist. Quoting makes that case work and makes the other case — "put these three flags on the end" — impossible, so `...` inside the braces asks for the value verbatim. Two behaviours, both documented, rather than one that is wrong half the time. | |
| 107 | + | |
| 108 | +**Nothing is remembered on disk.** The box starts from what was typed last time, for the session. Writing it into the project's own directory was considered and rejected: that directory holds what the project decided, and a filter somebody typed while chasing one test is not that. It would also be the first thing in there that changes without anybody editing it. | |
| 109 | + | |
| 110 | +**A file that cannot be parsed is refused when it is read**, not when the tool is chosen. An unclosed `{{` reaching the shell is a command failing with braces in it, which names neither the tool nor the file; refusing at load names both. That is the same rule an unknown `output` value already follows. | |
| 111 | + | |
| 112 | +**The dialog is refused when it will not fit.** A tool asking for more values than the terminal has rows would give a box whose OK button is below the bottom of the screen — answerable only by Escape, which cancels. Saying "this asks for twelve values and nine fit" is worse than nothing only if you would rather find out by trying. | |
| 113 | + | |
| 114 | +## How it relates to the rest | |
| 115 | + | |
| 116 | +- Every key of the file and every rule: [Python tools reference](../reference/python-tools.md) | |
| 117 | +- Using it: [How to run uv commands from the editor](../how-to/run-uv-commands.md) | |
| 118 | +- The windows `output = "terminal"` uses, and why they are real terminals: [Terminal windows](terminal-windows.md) | |
| 119 | +- The other menu built from a file: [Snippets](snippets.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,119 @@ | |||
| 1 | +# Python tools — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +A **Python** menu whose commands come from a TOML file, each run in a terminal window, and the open files re-read afterwards. This page is about why each of those three is the way it is. | ||
| 6 | + | ||
| 7 | +## Why the output has three places to go, and a popup by default | ||
| 8 | + | ||
| 9 | +The first version put every command in a terminal window, and it was the wrong default for five of the six. | ||
| 10 | + | ||
| 11 | +A terminal is the right answer when the program is *interactive or long*: `uv run` on a script that calls `input()` has to be answerable, and a `uv sync` that turns out to resolve half of PyPI has to be interruptible with `Ctrl-C`. Neither is true of `uv run ruff check .`, which prints four lines and ends. Giving that a whole window — one you then have to close, on a desktop where windows overlap and are numbered — is more ceremony than the result deserves. | ||
| 12 | + | ||
| 13 | +A popup is the right answer for a command you run, read and dismiss. It is modal, which is a real cost and is named in the [how-to](../how-to/run-uv-commands.md): a `uv sync` you did not expect to be slow holds the editor until it finishes or you press Escape. That cost was accepted on purpose, because the alternative — a dialog appearing unbidden three seconds later — swallows whatever was being typed at the moment it arrives. | ||
| 14 | + | ||
| 15 | +So the popup **opens immediately and fills in**. You see progress, nothing surprises you, and Escape both closes it and stops the command, which is the only way to interrupt something whose output is not in a terminal. | ||
| 16 | + | ||
| 17 | +An editing window is the right answer for output you are going to work through: a long `uv run pytest -v`, a coverage report. It is an ordinary buffer, so `Ctrl-F` searches it and `Save as` keeps it. It is filled once the command has ended rather than as it goes, because a buffer growing under the cursor while you search it is the opposite of what that mode is for. | ||
| 18 | + | ||
| 19 | +None of those three is right for everything, which is why `output` is in the file rather than in the code. `Run` is the worked example: it is the one command in the starter file that says `terminal`, and the comment beside it says why. | ||
| 20 | + | ||
| 21 | +## Why a terminal window is still there | ||
| 22 | + | ||
| 23 | +The editor already had one — a real pseudo-terminal with a VT emulator, built for the `F8` windows — so `output = "terminal"` costs one field on its options and buys colours, paging, `Ctrl-C`, keyboard input and scrollback for nothing, because they are the same mechanisms every other terminal uses. | ||
| 24 | + | ||
| 25 | +The window stays after the command exits, which is the point: the output is what you asked for, and a window that vanished with it would be useless. | ||
| 26 | + | ||
| 27 | +That needed a fix of its own. A terminal view consumed every key it was given and wrote it to the shell; once the shell had gone the write failed silently and the key was consumed anyway, so `Ctrl-W` could never close a finished window and the mouse was the only way out. A finished view now takes only the scrolling keys and lets the rest through to the editor. | ||
| 28 | + | ||
| 29 | +## Why the exit code is always in the title | ||
| 30 | + | ||
| 31 | +`uv sync` succeeding prints nothing at all. A popup with an empty body and a neutral title is indistinguishable from one whose command has not started, and the reader is left guessing at the one thing they wanted to know. | ||
| 32 | + | ||
| 33 | +So the title carries the verdict — `— ok` or `— exit 1` — and an empty body says `(no output)` once the command has ended. While it is still running the body stays blank, because "(no output)" is a verdict and a running command has not reached one. | ||
| 34 | + | ||
| 35 | +## Why the commands are in a file | ||
| 36 | + | ||
| 37 | +Six commands hardwired into the editor would have answered the request. They would also have been wrong within a week. | ||
| 38 | + | ||
| 39 | +Every command in the starter file goes through `uv`, which creates the environment, resolves the dependencies and runs the tools inside it — so none of them needs an environment to have been activated first. That is a defensible default and it is nobody's universal answer. A project on Poetry wants `poetry run`. One on pip and a hand-made `.venv` wants the bare command, with the environment already on PATH. One that has standardised on `black` and `flake8` wants those rather than `ruff`. `uv run pytest` assumes pytest; a project on `unittest` wants `python -m unittest`. A project with a `Makefile` wants `make check`. None of that is knowable from here, and all of it is one line in a file. | ||
| 40 | + | ||
| 41 | +So the six are **defaults, not code**: they are the contents of the starter file that **Python ▸ Create tools file** writes, and changing one is editing a file rather than rebuilding an editor. The file is read every time the menu opens, for the same reason the Snippets menu is: an edit should take effect at once, and the file is often open in the window behind the menu. | ||
| 42 | + | ||
| 43 | +Commands go to `sh -c` — `cmd.exe /S /C` on Windows — rather than being split into an argv here. The file is the user's own, so pipes, globs and `&&` are features rather than hazards, and one entry can be `uv run ruff format . && uv run ruff check . && uv run pytest`. Splitting an argv would mean inventing quoting rules for a string somebody wrote by hand. | ||
| 44 | + | ||
| 45 | +## Why there is no user-level tools file | ||
| 46 | + | ||
| 47 | +Snippets are read from two files — yours and the project's — because your snippets are your habits and should follow you between projects. | ||
| 48 | + | ||
| 49 | +Tools are not like that. They belong to a project's own toolchain: a global tools file would offer `uv run pytest` in a repository that has never heard of uv, and a project pinned to Poetry would get somebody else's habits in its menu. The file is per-project, and that is the whole of the rule. | ||
| 50 | + | ||
| 51 | +## Why a tool may name its own menu | ||
| 52 | + | ||
| 53 | +A menu called **Python** holding `docker compose up` is a lie about what the menu is. The first tools file anybody writes outgrows Python, because a project's commands are not all about the language it is written in: containers, databases, deploys, a `Makefile` target somebody added in 2019. | ||
| 54 | + | ||
| 55 | +Two shapes were considered. A **fixed second menu** called Tools — everything Python in Python, everything else in Tools — is one key in the format and no naming problem at all, but it only moves the lie: a Tools menu holding `docker compose up`, `psql`, and a deploy script is just as undifferentiated, and the moment there are ten entries nobody can find one. And a **second file**, `menus.toml`, keeps the tools file simple at the cost of two files that have to agree about which tools exist. | ||
| 56 | + | ||
| 57 | +So the menu is a **free-form name on the tool**, in the one file: `menu = "Docker"`. A name nothing else uses creates the menu; leaving the key out means Python. There is no list of allowed names, because a list would be a list of somebody else's projects. | ||
| 58 | + | ||
| 59 | +Python itself stays fixed on the bar rather than becoming just another name from the file. **Python ▸ Create tools file** has to be reachable in a project that has no tools file at all — which is exactly the project that needs it — and a menu that only exists once the file exists cannot offer to write the file. | ||
| 60 | + | ||
| 61 | +## Why the hot key is not the file's to choose | ||
| 62 | + | ||
| 63 | +The author of a tools file cannot know which letters are free. They can see `File`, `Edit`, `Search`, `Run`, `Code`, `Options`, `Window`, `Snippets`, `Python` and `Help` on the bar, but only by counting the underlines, and a project shared between people would then depend on nobody adding a menu that collides. | ||
| 64 | + | ||
| 65 | +Collisions here are **silent**, which is what makes them worth designing against. The bar answers the first menu whose hot key matches; a second menu claiming the same letter is not an error and draws normally — it simply never opens. That trap has already been sprung once in this editor: `Snippets` and `Search` both wanted `S`, `Snippets` was the unreachable one, and every test passed. The fix then was to move Snippets to `N` by hand. Letting a file name menus makes that a permanent hazard rather than a one-off mistake, so the assignment is done by the editor: the first letter of the name nothing else claims. | ||
| 66 | + | ||
| 67 | +Tildes written into the name are honoured **when the letter is free**, and quietly overridden when it is not. Refusing the file instead was the alternative, and it is worse: the clash depends on which menus exist, so a tools file that worked would break the day an editor release added a menu. Between a menu on a letter you did not ask for and a menu you cannot open, the first is the smaller loss. | ||
| 68 | + | ||
| 69 | +When every letter of a name is taken, the menu gets no hot key at all. `F10`, the arrow keys and the mouse still reach it, and the alternative — reaching for a letter that is not in the name — would put an underline under nothing. | ||
| 70 | + | ||
| 71 | +## Why the bar is rebuilt from a stat | ||
| 72 | + | ||
| 73 | +`Menu.OnOpen` refills a menu's items just before it drops down, which is how the Python and Snippets menus follow their files without a restart. It cannot help here: the *set* of menus is part of the bar, not part of any one menu, and adding `menu = "Docker"` to the file should put Docker on the bar. | ||
| 74 | + | ||
| 75 | +Reading and parsing the file on every turn of the event loop would do it, and would also be work done for nothing on every keystroke of a file nobody has edited. So the bar carries the size and modification time of the tools file it was built from, and one `stat` per turn decides whether to rebuild. Editing the file in the window in front of you, saving it, and watching the bar change is the case this is for. | ||
| 76 | + | ||
| 77 | +## Why open files are re-read, and only some of them | ||
| 78 | + | ||
| 79 | +`Format` rewrites files on disk — including the one you are looking at. Without anything further, the editor would sit on a stale copy, and the next `F2` would write your unformatted version back over `ruff format`'s work. That is not a rough edge; it is the feature quietly undoing itself. | ||
| 80 | + | ||
| 81 | +So when a command finishes, the editor re-reads every open file. The interesting part is which ones it refuses to touch. | ||
| 82 | + | ||
| 83 | +**A file with unsaved changes is left alone**, and the status bar says how many were skipped. Reloading it would throw away work the user has not saved, which no amount of convenience justifies. And the conflict is genuine: the formatter and the unsaved edit disagree about what the file should say, and the editor is not in a position to decide. Naming it and stopping is the honest outcome — the user can save and re-run, or keep editing and format later. | ||
| 84 | + | ||
| 85 | +Two smaller decisions inside that: | ||
| 86 | + | ||
| 87 | +- **The cursor stays where it was**, clamped into whatever the file now holds. A formatter moves lines about; putting the cursor back at the top would lose the reader's place for no reason. | ||
| 88 | +- **The undo history is discarded.** Undoing back past a reload would restore text the file no longer has, which is worse than not being able to undo at all. | ||
| 89 | + | ||
| 90 | +## Why the reload happens on the event loop | ||
| 91 | + | ||
| 92 | +The command's exit is noticed on the goroutine reading the terminal, which may not touch a buffer or the desktop. So it sets a flag, and the reload runs at the top of the next turn of the event loop. | ||
| 93 | + | ||
| 94 | +This is the fourth thing in the library built that way — the language-server announcement, the terminal redraws, the autosave deadline, and now this. The rule they share is worth stating once more: **the wake-up may be lost, so the state must not be.** `PostEvent` drops what does not fit in its queue, so anything that depends on a message arriving is a bug waiting for a busy moment. A flag the loop checks for itself cannot go missing. | ||
| 95 | + | ||
| 96 | +## Why a command can ask for a value, and why it asks in double braces | ||
| 97 | + | ||
| 98 | +`uv venv` needs a directory. `uv run` needs a script. `uv add` needs a package name, and `pytest -k` needs a pattern. None of those can live in the tools file as a fixed string, because the answer is different every time — and a tool that cannot ask is a tool that has to be edited before each use, which is not a tool. | ||
| 99 | + | ||
| 100 | +So a `{{label}}` in a command is a value the editor asks for first, in a box titled after the tool. **Two of the six starter commands use it**, which is deliberate: a feature demonstrated in the file everybody gets is a feature people find, and one described only in a comment is not. | ||
| 101 | + | ||
| 102 | +The first of them is the reason this editor's tools file has six commands rather than five. **Creating the virtual environment** is the step in Python that has to happen before any of the others can, and the one a newcomer to a project most often has not done — so it is the first item in the menu, and it asks where to put it, because `.venv` is the usual answer and not the only one. | ||
| 103 | + | ||
| 104 | +**Single braces were the obvious spelling and are wrong.** `awk '{print $1}'` and `find . -exec rm {} +` are ordinary things to put in a tools file, and reading the first as a placeholder turns a working command into a box asking for "print $1". Double braces collide with almost nothing, and the one construct they do collide with — a nested block in awk — is rare enough to be written down rather than designed around. | ||
| 105 | + | ||
| 106 | +**The value is quoted by default**, because the alternative fails silently. A path with a space in it, substituted raw, becomes two arguments and the command reports something about a file that does not exist. Quoting makes that case work and makes the other case — "put these three flags on the end" — impossible, so `...` inside the braces asks for the value verbatim. Two behaviours, both documented, rather than one that is wrong half the time. | ||
| 107 | + | ||
| 108 | +**Nothing is remembered on disk.** The box starts from what was typed last time, for the session. Writing it into the project's own directory was considered and rejected: that directory holds what the project decided, and a filter somebody typed while chasing one test is not that. It would also be the first thing in there that changes without anybody editing it. | ||
| 109 | + | ||
| 110 | +**A file that cannot be parsed is refused when it is read**, not when the tool is chosen. An unclosed `{{` reaching the shell is a command failing with braces in it, which names neither the tool nor the file; refusing at load names both. That is the same rule an unknown `output` value already follows. | ||
| 111 | + | ||
| 112 | +**The dialog is refused when it will not fit.** A tool asking for more values than the terminal has rows would give a box whose OK button is below the bottom of the screen — answerable only by Escape, which cancels. Saying "this asks for twelve values and nine fit" is worse than nothing only if you would rather find out by trying. | ||
| 113 | + | ||
| 114 | +## How it relates to the rest | ||
| 115 | + | ||
| 116 | +- Every key of the file and every rule: [Python tools reference](../reference/python-tools.md) | ||
| 117 | +- Using it: [How to run uv commands from the editor](../how-to/run-uv-commands.md) | ||
| 118 | +- The windows `output = "terminal"` uses, and why they are real terminals: [Terminal windows](terminal-windows.md) | ||
| 119 | +- The other menu built from a file: [Snippets](snippets.md) | ||
added
docs/en/explanation/snippets.md +62 -0 | new file mode 100644 | ||
| @@ -0,0 +1,62 @@ | ||
| 1 | +# Snippets — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +A **Snippets** menu whose contents come from a TOML file, and a chosen snippet dropped into the file you are editing. This page is about the three decisions that shape it: why the menu is rebuilt every time it opens, why the editor grew real submenus for it, and why insertion re-indents. | |
| 6 | + | |
| 7 | +## Why the menu is built at the moment it opens | |
| 8 | + | |
| 9 | +Every other menu in the editor is decided once, in `New()`. This one cannot be, and there are two independent reasons. | |
| 10 | + | |
| 11 | +The first is the file. Snippets live in TOML, and the whole point of that is that you edit it — often in this editor, in the window the **Create snippets file** item just opened for you. A menu built at start-up would show the state of the file when the editor launched, and you would have to restart to see a snippet you had just written. That is the kind of friction that stops people using a feature at all. | |
| 12 | + | |
| 13 | +The second is the front window. The menu is filtered by what you are editing, so it changes when you press `F6`. There is no start-up moment at which the answer exists. | |
| 14 | + | |
| 15 | +So `ui.Menu` grew an `OnOpen` field: a function the bar calls immediately before dropping a menu down, letting its owner refill `Items` first. It is the same upward-communication mechanism as everything else in this codebase — a function field, not an interface — and it runs at exactly the moment the contents are about to be seen and no more often. | |
| 16 | + | |
| 17 | +## Why the editor grew submenus | |
| 18 | + | |
| 19 | +`ui.MenuItem` had no nesting, and adding it was the largest single piece of this work: a second panel to place and draw, arrow keys that mean "further in" and "back out", the pointer opening a branch on hover and closing it on leaving, and a cascade that puts both panels away at once. | |
| 20 | + | |
| 21 | +The alternative was one flat panel with the groups as greyed-out captions between separators. It works, needs nothing new, and falls over on the case the feature is for: a project with thirty snippets gives a menu taller than the terminal. Grouping that only labels rather than folds does not solve the problem it appears to solve. | |
| 22 | + | |
| 23 | +It is deliberately **one level deep**. The format is groups containing snippets — exactly one level — and a general depth would mean replacing the bar's two indices with a path, in the widget every dialog and every menu test already depends on. That is speculative work on the most load-bearing part of the interface. | |
| 24 | + | |
| 25 | +Two details of the submenu are worth naming because they were chosen rather than fallen into: | |
| 26 | + | |
| 27 | +- **Right and left are asymmetric with Escape.** Right opens a branch, or moves to the next menu when the item has none, so it always means "further in" wherever you are. Left steps *out* of a submenu to its parent, while Escape puts the whole menu away — because cancel should mean cancel from anywhere. | |
| 28 | +- **The panel flips left, and is also capped to the screen.** A submenu that would run off the right edge is drawn on the other side of its parent instead. Flipping alone is not enough: a panel wider than the terminal cannot be made to fit by moving it, so the width is capped too and long labels are clipped by the painter. A frame with no right-hand edge looks broken in a way a truncated label does not. | |
| 29 | + | |
| 30 | +## Why insertion re-indents | |
| 31 | + | |
| 32 | +A snippet is text, and the obvious implementation is to insert it. That is right for a one-liner and wrong for everything else, which is most of what people keep in snippets. | |
| 33 | + | |
| 34 | +Dropped in verbatim, a multi-line body restarts at column zero. Inserted inside a method, inside a loop, inside a `with` block — which is where you insert a `try`/`except` — the result is text that no formatter, no reader and, in Python, no *parser* is happy with. In a language where the indentation **is** the block structure, a snippet at column zero does not merely look wrong: it closes every block above it. The first thing you do is re-indent it by hand, and a feature whose output needs fixing every time is not saving anyone anything. | |
| 35 | + | |
| 36 | +So the lines after the first get the leading whitespace of the line the cursor was on. That copies whatever the file already uses — tabs or spaces, however many — rather than imposing a choice, which matters in a project with a mixed history. | |
| 37 | + | |
| 38 | +Two smaller decisions inside that: | |
| 39 | + | |
| 40 | +- **A blank line in the body stays blank.** Padding it to the indent would put trailing whitespace in, which every formatter then strips — noise in the diff of the very next save. | |
| 41 | +- **It is one undo step.** A snippet is one action to the person who chose it, so `Ctrl-Z` should take all of it back. This falls out of doing the whole insertion in a single `ReplaceRange`, which is the rule the buffer already enforces for every other edit. | |
| 42 | + | |
| 43 | +Placeholders and tab stops — `${1:name}` and moving between them — were considered and left out. They are a second feature with their own state to keep across edits, and the thing being asked for was reusable text. | |
| 44 | + | |
| 45 | +## Why two files, and why the project wins | |
| 46 | + | |
| 47 | +Your own snippets belong to you and should follow you between projects; a project's belong to the project and should arrive with a checkout. Neither is the whole answer, so both are read. | |
| 48 | + | |
| 49 | +Where a name clashes in the same group, the project's replaces yours. It is the more specific of the two statements, and it is the one a team agreed on — the same reason a `-theme` flag beats a project's setting while a project's setting beats the built-in default. | |
| 50 | + | |
| 51 | +## Why an unreadable file is loud | |
| 52 | + | |
| 53 | +A typo in TOML could drop every snippet silently and leave a menu with nothing but **Create snippets file** — which looks exactly like a project that has no snippets, and sends you to create a file you already have. | |
| 54 | + | |
| 55 | +So the menu shows a greyed-out `Cannot read snippets` where the groups would be. It cannot be chosen, it is where you were looking, and the create item is still below it so there is a way forward either way. | |
| 56 | + | |
| 57 | +## How it relates to the rest | |
| 58 | + | |
| 59 | +- Every key and every rule: [Snippets reference](../reference/snippets.md) | |
| 60 | +- Setting them up: [How to insert snippets from a menu](../how-to/use-snippets.md) | |
| 61 | +- The other file in the same directory: [Project settings](project-settings.md) | |
| 62 | +- The language names `languages` uses: [Languages coloured](../reference/languages.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | +# Snippets — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +A **Snippets** menu whose contents come from a TOML file, and a chosen snippet dropped into the file you are editing. This page is about the three decisions that shape it: why the menu is rebuilt every time it opens, why the editor grew real submenus for it, and why insertion re-indents. | ||
| 6 | + | ||
| 7 | +## Why the menu is built at the moment it opens | ||
| 8 | + | ||
| 9 | +Every other menu in the editor is decided once, in `New()`. This one cannot be, and there are two independent reasons. | ||
| 10 | + | ||
| 11 | +The first is the file. Snippets live in TOML, and the whole point of that is that you edit it — often in this editor, in the window the **Create snippets file** item just opened for you. A menu built at start-up would show the state of the file when the editor launched, and you would have to restart to see a snippet you had just written. That is the kind of friction that stops people using a feature at all. | ||
| 12 | + | ||
| 13 | +The second is the front window. The menu is filtered by what you are editing, so it changes when you press `F6`. There is no start-up moment at which the answer exists. | ||
| 14 | + | ||
| 15 | +So `ui.Menu` grew an `OnOpen` field: a function the bar calls immediately before dropping a menu down, letting its owner refill `Items` first. It is the same upward-communication mechanism as everything else in this codebase — a function field, not an interface — and it runs at exactly the moment the contents are about to be seen and no more often. | ||
| 16 | + | ||
| 17 | +## Why the editor grew submenus | ||
| 18 | + | ||
| 19 | +`ui.MenuItem` had no nesting, and adding it was the largest single piece of this work: a second panel to place and draw, arrow keys that mean "further in" and "back out", the pointer opening a branch on hover and closing it on leaving, and a cascade that puts both panels away at once. | ||
| 20 | + | ||
| 21 | +The alternative was one flat panel with the groups as greyed-out captions between separators. It works, needs nothing new, and falls over on the case the feature is for: a project with thirty snippets gives a menu taller than the terminal. Grouping that only labels rather than folds does not solve the problem it appears to solve. | ||
| 22 | + | ||
| 23 | +It is deliberately **one level deep**. The format is groups containing snippets — exactly one level — and a general depth would mean replacing the bar's two indices with a path, in the widget every dialog and every menu test already depends on. That is speculative work on the most load-bearing part of the interface. | ||
| 24 | + | ||
| 25 | +Two details of the submenu are worth naming because they were chosen rather than fallen into: | ||
| 26 | + | ||
| 27 | +- **Right and left are asymmetric with Escape.** Right opens a branch, or moves to the next menu when the item has none, so it always means "further in" wherever you are. Left steps *out* of a submenu to its parent, while Escape puts the whole menu away — because cancel should mean cancel from anywhere. | ||
| 28 | +- **The panel flips left, and is also capped to the screen.** A submenu that would run off the right edge is drawn on the other side of its parent instead. Flipping alone is not enough: a panel wider than the terminal cannot be made to fit by moving it, so the width is capped too and long labels are clipped by the painter. A frame with no right-hand edge looks broken in a way a truncated label does not. | ||
| 29 | + | ||
| 30 | +## Why insertion re-indents | ||
| 31 | + | ||
| 32 | +A snippet is text, and the obvious implementation is to insert it. That is right for a one-liner and wrong for everything else, which is most of what people keep in snippets. | ||
| 33 | + | ||
| 34 | +Dropped in verbatim, a multi-line body restarts at column zero. Inserted inside a method, inside a loop, inside a `with` block — which is where you insert a `try`/`except` — the result is text that no formatter, no reader and, in Python, no *parser* is happy with. In a language where the indentation **is** the block structure, a snippet at column zero does not merely look wrong: it closes every block above it. The first thing you do is re-indent it by hand, and a feature whose output needs fixing every time is not saving anyone anything. | ||
| 35 | + | ||
| 36 | +So the lines after the first get the leading whitespace of the line the cursor was on. That copies whatever the file already uses — tabs or spaces, however many — rather than imposing a choice, which matters in a project with a mixed history. | ||
| 37 | + | ||
| 38 | +Two smaller decisions inside that: | ||
| 39 | + | ||
| 40 | +- **A blank line in the body stays blank.** Padding it to the indent would put trailing whitespace in, which every formatter then strips — noise in the diff of the very next save. | ||
| 41 | +- **It is one undo step.** A snippet is one action to the person who chose it, so `Ctrl-Z` should take all of it back. This falls out of doing the whole insertion in a single `ReplaceRange`, which is the rule the buffer already enforces for every other edit. | ||
| 42 | + | ||
| 43 | +Placeholders and tab stops — `${1:name}` and moving between them — were considered and left out. They are a second feature with their own state to keep across edits, and the thing being asked for was reusable text. | ||
| 44 | + | ||
| 45 | +## Why two files, and why the project wins | ||
| 46 | + | ||
| 47 | +Your own snippets belong to you and should follow you between projects; a project's belong to the project and should arrive with a checkout. Neither is the whole answer, so both are read. | ||
| 48 | + | ||
| 49 | +Where a name clashes in the same group, the project's replaces yours. It is the more specific of the two statements, and it is the one a team agreed on — the same reason a `-theme` flag beats a project's setting while a project's setting beats the built-in default. | ||
| 50 | + | ||
| 51 | +## Why an unreadable file is loud | ||
| 52 | + | ||
| 53 | +A typo in TOML could drop every snippet silently and leave a menu with nothing but **Create snippets file** — which looks exactly like a project that has no snippets, and sends you to create a file you already have. | ||
| 54 | + | ||
| 55 | +So the menu shows a greyed-out `Cannot read snippets` where the groups would be. It cannot be chosen, it is where you were looking, and the create item is still below it so there is a way forward either way. | ||
| 56 | + | ||
| 57 | +## How it relates to the rest | ||
| 58 | + | ||
| 59 | +- Every key and every rule: [Snippets reference](../reference/snippets.md) | ||
| 60 | +- Setting them up: [How to insert snippets from a menu](../how-to/use-snippets.md) | ||
| 61 | +- The other file in the same directory: [Project settings](project-settings.md) | ||
| 62 | +- The language names `languages` uses: [Languages coloured](../reference/languages.md) | ||
added
docs/en/explanation/terminal-windows.md +72 -0 | new file mode 100644 | ||
| @@ -0,0 +1,72 @@ | ||
| 1 | +# Terminal windows — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +`F8` opens a window with a shell in it. That sentence hides most of the work: to put a shell in a window, an editor has to become a terminal emulator, and this page is about what that involved and which of the cheaper alternatives were turned down on the way. | |
| 6 | + | |
| 7 | +## Why a real pseudo-terminal | |
| 8 | + | |
| 9 | +The obvious cheap version is to run a command with `exec.Command`, capture its output, and show it in a read-only pane. Many editors ship exactly that, and it fails on the things people actually want a terminal for. | |
| 10 | + | |
| 11 | +A program behaves differently when its output is a pipe rather than a terminal. `uv run pytest` drops its colours. `git log` does not page. `ls` prints one name per line. Nothing interactive works at all: no `vim`, no `ssh`, no `git rebase -i`, no answering a prompt, and no `Ctrl-C`, because with no controlling terminal there is no signal to send. | |
| 12 | + | |
| 13 | +So the shell gets a real pseudo-terminal: `/dev/ptmx` on both supported platforms, the child in a session of its own with the slave as its controlling terminal, and `TIOCSWINSZ` whenever the window is resized. That buys job control, `isatty`, `SIGWINCH` and colour, all for free, because they are the same mechanisms every other terminal uses. | |
| 14 | + | |
| 15 | +The cost is that the editor must then read back what a terminal is expected to understand — which is the emulator. | |
| 16 | + | |
| 17 | +## Why write the emulator rather than borrow one | |
| 18 | + | |
| 19 | +Go has terminal emulator libraries. Taking one would have meant a third dependency, against a project that has exactly two and a stated reluctance to add a third. | |
| 20 | + | |
| 21 | +The thing being weighed is not "emulator" against "no emulator" but against *how much* emulator. What a shell, `uv run pytest`, `git`, `less`, `htop` and `vim` need is a well-bounded list: cursor movement, the erase and insert-delete family, a scroll region, SGR in all three colour depths, the alternate screen, auto-wrap, cursor visibility and application cursor keys. That is about six hundred lines, it is written down in ECMA-48, and it is testable by writing bytes in and reading a grid out — no shell, no timing, no screen. | |
| 22 | + | |
| 23 | +Compare that with what a general-purpose library brings: character sets, mouse reporting protocols, sixel, bracketed paste, DEC status reports. All real, none of it needed here, and all of it surface to keep working. | |
| 24 | + | |
| 25 | +So the emulator is hand-written and deliberately partial, and the [reference](../reference/terminal.md) says exactly where it stops. A program that asks for something absent gets silence rather than corruption, which is the failure mode worth having: `htop` renders, `sixel` output simply does not appear. | |
| 26 | + | |
| 27 | +## Who gets the key press | |
| 28 | + | |
| 29 | +This is the decision with the most consequence for how the editor feels, and the first version got it wrong. | |
| 30 | + | |
| 31 | +The editor's global shortcuts are checked before the window in front sees anything. That is right for an editor and wrong the moment the window in front is a shell, because the two disagree about the same keys. `Ctrl-W` closes a window in Turbo C and deletes a word in every shell. `Ctrl-F` is Find here and forward-a-character in readline. `Ctrl-C` is copy, and also the only way to stop a runaway command. | |
| 32 | + | |
| 33 | +The rule chosen inverts the usual order, but only for the keys that are genuinely contested: | |
| 34 | + | |
| 35 | +**A focused terminal gets everything except the function keys, `Alt-X`, and `Alt-0`…`Alt-9`.** | |
| 36 | + | |
| 37 | +Those exceptions are not a compromise between the two claims — they are the way *out*. A full-screen program like `vim` covers the window and takes the mouse; without a reserved key there would be no way to reach the menu bar, switch windows or leave the editor short of quitting the program inside. Function keys are the natural reservation because a terminal user reaches for them least, and `Alt-X` because leaving an editor should never be in doubt. | |
| 38 | + | |
| 39 | +What this costs is real and worth naming: `Alt-B` and `Alt-F` reach the shell, so readline's word movement works, but a program inside a terminal window can never see `F1`…`F12`. `htop`'s function-key menu is unreachable. That is the trade, and it was made in favour of always being able to get out. | |
| 40 | + | |
| 41 | +## Why closing a terminal asks nothing | |
| 42 | + | |
| 43 | +Closing a modified file asks whether to save it. Closing a terminal does not ask anything at all, and that asymmetry is deliberate. | |
| 44 | + | |
| 45 | +A window with unsaved work holds something that would be *lost*. A terminal holds a running process, and closing the window is the ordinary way to say you are done with it — the same as closing a terminal emulator's tab. Asking "are you sure?" every time would train the answer out of anyone, which is the general problem with confirmations that fire on the common case. | |
| 46 | + | |
| 47 | +Leaving the editor closes every terminal for the same reason in reverse: a window is the only handle on those shells, so letting them outlive the editor would strand the processes with nothing able to reach them. | |
| 48 | + | |
| 49 | +## Why the redraws are on a clock | |
| 50 | + | |
| 51 | +The shell writes on a goroutine of its own; the editor draws on the main one. Waking the event loop per chunk of output looked obvious and was wrong twice over. | |
| 52 | + | |
| 53 | +A build writes far faster than a screen can usefully be repainted, so most of those redraws are wasted. Worse, the mechanism for waking the loop from another goroutine is tcell's `PostEvent`, which **drops** events when its queue is full — so the burst that most needs a redraw is the one whose final wake-up gets discarded, and the window freezes mid-build showing stale text. That exact bug had already been found once elsewhere in this editor, over the language server. | |
| 54 | + | |
| 55 | +So the view sets a flag and a ticker asks for a redraw sixty times a second while the flag is set. A dropped wake-up cannot strand anything, because the next tick is sixteen milliseconds away. | |
| 56 | + | |
| 57 | +## Windows: a pseudo-console, and why it is a file of its own | |
| 58 | + | |
| 59 | +Pseudo-terminals are the one part of this that is not portable. Linux and macOS both go through `/dev/ptmx` and differ only in which `ioctl` grants the slave. Windows has no such device: it has **pseudo-consoles** — ConPTY, since Windows 10 version 1809 — an object owned by `conhost.exe` and wired to two pipes of the editor's. What the shell prints arrives on one pipe as the same VT sequences a Unix shell writes to a pty, which is why the emulator on this side needed no Windows code at all; what the editor writes to the other pipe reaches the shell as keystrokes. | |
| 60 | + | |
| 61 | +Three things made it a file of its own rather than a variant of the Unix one. The process has to be created by hand, because attaching it to a pseudo-console takes an extended startup record that Go's `os/exec` cannot carry. The shell is `%COMSPEC%` — cmd.exe — rather than `$SHELL`, and cmd.exe reads its command line by rules of its own, so the line that runs a menu command is composed for it verbatim, the command inside one pair of quotes, rather than escaped the way every other program expects. And `conhost.exe` holds the output pipe open until the console is closed, whatever the shell does, so a goroutine waits for the shell to exit and then closes the console — that is what turns a command finishing into the end of input the window relies on to say so. Job control is cmd.exe's rather than the kernel's: `Ctrl-C` interrupts the running program as it would in a console window. | |
| 62 | + | |
| 63 | +The platform files stay split so that each platform has one honest implementation behind one small interface, and a platform with neither — the BSDs, today — gets `ErrUnsupported`, `F8` says so plainly, and nothing else in the editor is affected. | |
| 64 | + | |
| 65 | +**The Windows path has been built and vetted, not run.** turbo-core is developed on Linux and its author works on macOS. The pure parts — the environment block, the command line cmd.exe wants — are unit-tested on every platform, and the API calls compile and pass `go vet` under `GOOS=windows`; nobody has yet pressed `F8` on a Windows machine. [The how-to](../how-to/use-a-terminal.md) says what to try first. | |
| 66 | + | |
| 67 | +## How it relates to the rest | |
| 68 | + | |
| 69 | +- The exact list of what is implemented: [Terminal windows reference](../reference/terminal.md) | |
| 70 | +- Using one: [How to run shell commands without leaving the editor](../how-to/use-a-terminal.md) | |
| 71 | +- Where `terminal` sits among the packages, and why the graph runs one way: [Architecture](architecture.md) | |
| 72 | +- The dependency count this page keeps invoking: [Design decisions](design-decisions.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,72 @@ | |||
| 1 | +# Terminal windows — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +`F8` opens a window with a shell in it. That sentence hides most of the work: to put a shell in a window, an editor has to become a terminal emulator, and this page is about what that involved and which of the cheaper alternatives were turned down on the way. | ||
| 6 | + | ||
| 7 | +## Why a real pseudo-terminal | ||
| 8 | + | ||
| 9 | +The obvious cheap version is to run a command with `exec.Command`, capture its output, and show it in a read-only pane. Many editors ship exactly that, and it fails on the things people actually want a terminal for. | ||
| 10 | + | ||
| 11 | +A program behaves differently when its output is a pipe rather than a terminal. `uv run pytest` drops its colours. `git log` does not page. `ls` prints one name per line. Nothing interactive works at all: no `vim`, no `ssh`, no `git rebase -i`, no answering a prompt, and no `Ctrl-C`, because with no controlling terminal there is no signal to send. | ||
| 12 | + | ||
| 13 | +So the shell gets a real pseudo-terminal: `/dev/ptmx` on both supported platforms, the child in a session of its own with the slave as its controlling terminal, and `TIOCSWINSZ` whenever the window is resized. That buys job control, `isatty`, `SIGWINCH` and colour, all for free, because they are the same mechanisms every other terminal uses. | ||
| 14 | + | ||
| 15 | +The cost is that the editor must then read back what a terminal is expected to understand — which is the emulator. | ||
| 16 | + | ||
| 17 | +## Why write the emulator rather than borrow one | ||
| 18 | + | ||
| 19 | +Go has terminal emulator libraries. Taking one would have meant a third dependency, against a project that has exactly two and a stated reluctance to add a third. | ||
| 20 | + | ||
| 21 | +The thing being weighed is not "emulator" against "no emulator" but against *how much* emulator. What a shell, `uv run pytest`, `git`, `less`, `htop` and `vim` need is a well-bounded list: cursor movement, the erase and insert-delete family, a scroll region, SGR in all three colour depths, the alternate screen, auto-wrap, cursor visibility and application cursor keys. That is about six hundred lines, it is written down in ECMA-48, and it is testable by writing bytes in and reading a grid out — no shell, no timing, no screen. | ||
| 22 | + | ||
| 23 | +Compare that with what a general-purpose library brings: character sets, mouse reporting protocols, sixel, bracketed paste, DEC status reports. All real, none of it needed here, and all of it surface to keep working. | ||
| 24 | + | ||
| 25 | +So the emulator is hand-written and deliberately partial, and the [reference](../reference/terminal.md) says exactly where it stops. A program that asks for something absent gets silence rather than corruption, which is the failure mode worth having: `htop` renders, `sixel` output simply does not appear. | ||
| 26 | + | ||
| 27 | +## Who gets the key press | ||
| 28 | + | ||
| 29 | +This is the decision with the most consequence for how the editor feels, and the first version got it wrong. | ||
| 30 | + | ||
| 31 | +The editor's global shortcuts are checked before the window in front sees anything. That is right for an editor and wrong the moment the window in front is a shell, because the two disagree about the same keys. `Ctrl-W` closes a window in Turbo C and deletes a word in every shell. `Ctrl-F` is Find here and forward-a-character in readline. `Ctrl-C` is copy, and also the only way to stop a runaway command. | ||
| 32 | + | ||
| 33 | +The rule chosen inverts the usual order, but only for the keys that are genuinely contested: | ||
| 34 | + | ||
| 35 | +**A focused terminal gets everything except the function keys, `Alt-X`, and `Alt-0`…`Alt-9`.** | ||
| 36 | + | ||
| 37 | +Those exceptions are not a compromise between the two claims — they are the way *out*. A full-screen program like `vim` covers the window and takes the mouse; without a reserved key there would be no way to reach the menu bar, switch windows or leave the editor short of quitting the program inside. Function keys are the natural reservation because a terminal user reaches for them least, and `Alt-X` because leaving an editor should never be in doubt. | ||
| 38 | + | ||
| 39 | +What this costs is real and worth naming: `Alt-B` and `Alt-F` reach the shell, so readline's word movement works, but a program inside a terminal window can never see `F1`…`F12`. `htop`'s function-key menu is unreachable. That is the trade, and it was made in favour of always being able to get out. | ||
| 40 | + | ||
| 41 | +## Why closing a terminal asks nothing | ||
| 42 | + | ||
| 43 | +Closing a modified file asks whether to save it. Closing a terminal does not ask anything at all, and that asymmetry is deliberate. | ||
| 44 | + | ||
| 45 | +A window with unsaved work holds something that would be *lost*. A terminal holds a running process, and closing the window is the ordinary way to say you are done with it — the same as closing a terminal emulator's tab. Asking "are you sure?" every time would train the answer out of anyone, which is the general problem with confirmations that fire on the common case. | ||
| 46 | + | ||
| 47 | +Leaving the editor closes every terminal for the same reason in reverse: a window is the only handle on those shells, so letting them outlive the editor would strand the processes with nothing able to reach them. | ||
| 48 | + | ||
| 49 | +## Why the redraws are on a clock | ||
| 50 | + | ||
| 51 | +The shell writes on a goroutine of its own; the editor draws on the main one. Waking the event loop per chunk of output looked obvious and was wrong twice over. | ||
| 52 | + | ||
| 53 | +A build writes far faster than a screen can usefully be repainted, so most of those redraws are wasted. Worse, the mechanism for waking the loop from another goroutine is tcell's `PostEvent`, which **drops** events when its queue is full — so the burst that most needs a redraw is the one whose final wake-up gets discarded, and the window freezes mid-build showing stale text. That exact bug had already been found once elsewhere in this editor, over the language server. | ||
| 54 | + | ||
| 55 | +So the view sets a flag and a ticker asks for a redraw sixty times a second while the flag is set. A dropped wake-up cannot strand anything, because the next tick is sixteen milliseconds away. | ||
| 56 | + | ||
| 57 | +## Windows: a pseudo-console, and why it is a file of its own | ||
| 58 | + | ||
| 59 | +Pseudo-terminals are the one part of this that is not portable. Linux and macOS both go through `/dev/ptmx` and differ only in which `ioctl` grants the slave. Windows has no such device: it has **pseudo-consoles** — ConPTY, since Windows 10 version 1809 — an object owned by `conhost.exe` and wired to two pipes of the editor's. What the shell prints arrives on one pipe as the same VT sequences a Unix shell writes to a pty, which is why the emulator on this side needed no Windows code at all; what the editor writes to the other pipe reaches the shell as keystrokes. | ||
| 60 | + | ||
| 61 | +Three things made it a file of its own rather than a variant of the Unix one. The process has to be created by hand, because attaching it to a pseudo-console takes an extended startup record that Go's `os/exec` cannot carry. The shell is `%COMSPEC%` — cmd.exe — rather than `$SHELL`, and cmd.exe reads its command line by rules of its own, so the line that runs a menu command is composed for it verbatim, the command inside one pair of quotes, rather than escaped the way every other program expects. And `conhost.exe` holds the output pipe open until the console is closed, whatever the shell does, so a goroutine waits for the shell to exit and then closes the console — that is what turns a command finishing into the end of input the window relies on to say so. Job control is cmd.exe's rather than the kernel's: `Ctrl-C` interrupts the running program as it would in a console window. | ||
| 62 | + | ||
| 63 | +The platform files stay split so that each platform has one honest implementation behind one small interface, and a platform with neither — the BSDs, today — gets `ErrUnsupported`, `F8` says so plainly, and nothing else in the editor is affected. | ||
| 64 | + | ||
| 65 | +**The Windows path has been built and vetted, not run.** turbo-core is developed on Linux and its author works on macOS. The pure parts — the environment block, the command line cmd.exe wants — are unit-tested on every platform, and the API calls compile and pass `go vet` under `GOOS=windows`; nobody has yet pressed `F8` on a Windows machine. [The how-to](../how-to/use-a-terminal.md) says what to try first. | ||
| 66 | + | ||
| 67 | +## How it relates to the rest | ||
| 68 | + | ||
| 69 | +- The exact list of what is implemented: [Terminal windows reference](../reference/terminal.md) | ||
| 70 | +- Using one: [How to run shell commands without leaving the editor](../how-to/use-a-terminal.md) | ||
| 71 | +- Where `terminal` sits among the packages, and why the graph runs one way: [Architecture](architecture.md) | ||
| 72 | +- The dependency count this page keeps invoking: [Design decisions](design-decisions.md) | ||
added
docs/en/how-to/ask-about-code.md +69 -0 | new file mode 100644 | ||
| @@ -0,0 +1,69 @@ | ||
| 1 | +# How to ask what the code means | |
| 2 | + | |
| 3 | +This guide shows how to follow a name through a project: where it is declared, what implements it, everywhere it is used, and what is wrong with it. It assumes Turbo Python is installed and a language server is running — the status bar says `LSP: ready` when it is. | |
| 4 | + | |
| 5 | +For moving around a file — searching, jumping to a line, switching windows — see [How to move around a file](navigate-code.md) instead. | |
| 6 | + | |
| 7 | +## Put the cursor on a name | |
| 8 | + | |
| 9 | +Any character of it will do. Every question below asks about the **position of the cursor**, not about a selection, so there is nothing to highlight first. | |
| 10 | + | |
| 11 | +## Ask | |
| 12 | + | |
| 13 | +| To find | Do | Shortcut | | |
| 14 | +| --- | --- | --- | | |
| 15 | +| What it is | **Code ▸ Describe symbol** | `F1` | | |
| 16 | +| Where it is declared | **Code ▸ Go to definition** | `F12` | | |
| 17 | +| Where its *type* is declared | **Code ▸ Go to type definition** | | | |
| 18 | +| What implements it | **Code ▸ Find implementations…** | | | |
| 19 | +| Everywhere it is used | **Code ▸ Find references…** | `Shift-F12` | | |
| 20 | + | |
| 21 | +One answer takes you straight there. Several open a list showing each file, its line, and the text of that line: | |
| 22 | + | |
| 23 | +``` | |
| 24 | +Implementations (2) | |
| 25 | + french.py:4 impl Greeter for French { | |
| 26 | + english.py:4 impl Greeter for English { | |
| 27 | +``` | |
| 28 | + | |
| 29 | +Move with the arrow keys, `Enter` to go, `Esc` to stay where you are. | |
| 30 | + | |
| 31 | +## When nothing comes back | |
| 32 | + | |
| 33 | +Three different things look alike, and the status bar tells them apart: | |
| 34 | + | |
| 35 | +| It says | Meaning | | |
| 36 | +| --- | --- | | |
| 37 | +| `No references found` | The server answered, and there are none | | |
| 38 | +| Anything else, such as `Loading…` | The server has not finished indexing. Wait a moment and ask again. | | |
| 39 | +| `LSP: off` on the status bar | No server is running. See [How to enable completion](enable-completion.md). | | |
| 40 | + | |
| 41 | +The middle one is worth knowing: a server still indexing answers every question with nothing, and that is indistinguishable from a real answer unless the editor says so. | |
| 42 | + | |
| 43 | +## Find something by name instead | |
| 44 | + | |
| 45 | +- **Code ▸ Symbol in file…** lists what the file in front declares, indented, with each symbol's kind — an outline you can walk. | |
| 46 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) asks for a name and searches everywhere. What counts as a match is the server's decision; pylsp matches loosely, so a few letters usually do. | |
| 47 | + | |
| 48 | +## See what is wrong | |
| 49 | + | |
| 50 | +**Code ▸ Problems…** lists every problem the server has reported, for **every file it has loaded** — usually more than the one you are editing. Choosing one goes to the line. | |
| 51 | + | |
| 52 | +Lines with a problem carry a mark in the gutter, beside the line number: | |
| 53 | + | |
| 54 | +| Mark | Meaning | | |
| 55 | +| --- | --- | | |
| 56 | +| `×` | An error | | |
| 57 | +| `!` | A warning | | |
| 58 | +| `i` | Information | | |
| 59 | +| `·` | A hint | | |
| 60 | + | |
| 61 | +A line with more than one problem shows the worst of them. | |
| 62 | + | |
| 63 | +**The marks need the line numbers.** They sit in the column that separates the numbers from the text, so hiding the gutter with **Options ▸ Line numbers** hides them too. | |
| 64 | + | |
| 65 | +## See also | |
| 66 | + | |
| 67 | +- Every item and its key: [Menus](../reference/menus.md) | |
| 68 | +- Getting a server running: [How to enable completion](enable-completion.md) | |
| 69 | +- What the editor asks, and why: [Colouring and completion](../explanation/colouring-and-completion.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,69 @@ | |||
| 1 | +# How to ask what the code means | ||
| 2 | + | ||
| 3 | +This guide shows how to follow a name through a project: where it is declared, what implements it, everywhere it is used, and what is wrong with it. It assumes Turbo Python is installed and a language server is running — the status bar says `LSP: ready` when it is. | ||
| 4 | + | ||
| 5 | +For moving around a file — searching, jumping to a line, switching windows — see [How to move around a file](navigate-code.md) instead. | ||
| 6 | + | ||
| 7 | +## Put the cursor on a name | ||
| 8 | + | ||
| 9 | +Any character of it will do. Every question below asks about the **position of the cursor**, not about a selection, so there is nothing to highlight first. | ||
| 10 | + | ||
| 11 | +## Ask | ||
| 12 | + | ||
| 13 | +| To find | Do | Shortcut | | ||
| 14 | +| --- | --- | --- | | ||
| 15 | +| What it is | **Code ▸ Describe symbol** | `F1` | | ||
| 16 | +| Where it is declared | **Code ▸ Go to definition** | `F12` | | ||
| 17 | +| Where its *type* is declared | **Code ▸ Go to type definition** | | | ||
| 18 | +| What implements it | **Code ▸ Find implementations…** | | | ||
| 19 | +| Everywhere it is used | **Code ▸ Find references…** | `Shift-F12` | | ||
| 20 | + | ||
| 21 | +One answer takes you straight there. Several open a list showing each file, its line, and the text of that line: | ||
| 22 | + | ||
| 23 | +``` | ||
| 24 | +Implementations (2) | ||
| 25 | + french.py:4 impl Greeter for French { | ||
| 26 | + english.py:4 impl Greeter for English { | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +Move with the arrow keys, `Enter` to go, `Esc` to stay where you are. | ||
| 30 | + | ||
| 31 | +## When nothing comes back | ||
| 32 | + | ||
| 33 | +Three different things look alike, and the status bar tells them apart: | ||
| 34 | + | ||
| 35 | +| It says | Meaning | | ||
| 36 | +| --- | --- | | ||
| 37 | +| `No references found` | The server answered, and there are none | | ||
| 38 | +| Anything else, such as `Loading…` | The server has not finished indexing. Wait a moment and ask again. | | ||
| 39 | +| `LSP: off` on the status bar | No server is running. See [How to enable completion](enable-completion.md). | | ||
| 40 | + | ||
| 41 | +The middle one is worth knowing: a server still indexing answers every question with nothing, and that is indistinguishable from a real answer unless the editor says so. | ||
| 42 | + | ||
| 43 | +## Find something by name instead | ||
| 44 | + | ||
| 45 | +- **Code ▸ Symbol in file…** lists what the file in front declares, indented, with each symbol's kind — an outline you can walk. | ||
| 46 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) asks for a name and searches everywhere. What counts as a match is the server's decision; pylsp matches loosely, so a few letters usually do. | ||
| 47 | + | ||
| 48 | +## See what is wrong | ||
| 49 | + | ||
| 50 | +**Code ▸ Problems…** lists every problem the server has reported, for **every file it has loaded** — usually more than the one you are editing. Choosing one goes to the line. | ||
| 51 | + | ||
| 52 | +Lines with a problem carry a mark in the gutter, beside the line number: | ||
| 53 | + | ||
| 54 | +| Mark | Meaning | | ||
| 55 | +| --- | --- | | ||
| 56 | +| `×` | An error | | ||
| 57 | +| `!` | A warning | | ||
| 58 | +| `i` | Information | | ||
| 59 | +| `·` | A hint | | ||
| 60 | + | ||
| 61 | +A line with more than one problem shows the worst of them. | ||
| 62 | + | ||
| 63 | +**The marks need the line numbers.** They sit in the column that separates the numbers from the text, so hiding the gutter with **Options ▸ Line numbers** hides them too. | ||
| 64 | + | ||
| 65 | +## See also | ||
| 66 | + | ||
| 67 | +- Every item and its key: [Menus](../reference/menus.md) | ||
| 68 | +- Getting a server running: [How to enable completion](enable-completion.md) | ||
| 69 | +- What the editor asks, and why: [Colouring and completion](../explanation/colouring-and-completion.md) | ||
added
docs/en/how-to/browse-a-project.md +70 -0 | new file mode 100644 | ||
| @@ -0,0 +1,70 @@ | ||
| 1 | +# How to browse a project and open files from a tree | |
| 2 | + | |
| 3 | +This guide shows how to open the project tree, walk it, and open a file from it. It assumes Turbo Python is already installed. | |
| 4 | + | |
| 5 | +## Open the tree | |
| 6 | + | |
| 7 | +Start the editor **from the project's own directory**, then press `F9`, or choose **Window ▸ Project tree**. | |
| 8 | + | |
| 9 | +A window opens showing the project's files, named after the directory the editor was started in: | |
| 10 | + | |
| 11 | +``` | |
| 12 | +╔═[x]════════════ turbo-python ════════════2═[■]╗ | |
| 13 | +║ ▶ .turbo-python ║ | |
| 14 | +║ ▼ internal ║ | |
| 15 | +║ ▶ app ║ | |
| 16 | +║ ▼ ui ║ | |
| 17 | +║ window.go ║ | |
| 18 | +║ .gitignore ║ | |
| 19 | +║ pyproject.toml ║ | |
| 20 | +║ main.py ║ | |
| 21 | +╚══════════════════════════════════════════╝ | |
| 22 | +``` | |
| 23 | + | |
| 24 | +Directories come first, then files, each group sorted. `.git` is the only thing hidden — `.turbo-python`, `.gitignore` and the rest are files of your project, and you may well want to open them. | |
| 25 | + | |
| 26 | +Pressing `F9` again brings that window forward rather than opening a second tree. | |
| 27 | + | |
| 28 | +## Walk it | |
| 29 | + | |
| 30 | +| Key | Effect | | |
| 31 | +| --- | --- | | |
| 32 | +| `↑` `↓` | Move the highlight | | |
| 33 | +| `→` | Open a closed directory; on anything else, step to the next row | | |
| 34 | +| `←` | Close an open directory; on anything else, step out to the directory it is in | | |
| 35 | +| `Enter` | Open a file, or open and close a directory | | |
| 36 | +| `Home` `End` | First / last row | | |
| 37 | +| `PgUp` `PgDn` | A screenful at a time | | |
| 38 | + | |
| 39 | +A directory is read the first time you open it, so a tree on a large project costs one listing rather than a walk of everything. | |
| 40 | + | |
| 41 | +## Open a file | |
| 42 | + | |
| 43 | +Put the highlight on it and press `Enter`, or click it twice. | |
| 44 | + | |
| 45 | +The file opens in a window of its own, in front of the tree. A file that is already open is brought forward rather than opened twice. | |
| 46 | + | |
| 47 | +## See a file that was made after you opened the tree | |
| 48 | + | |
| 49 | +The tree does not watch the disk. Press **`F5`** or **`Ctrl-R`** with the tree focused, and it re-reads the project — keeping open whatever you had open, and keeping the highlight on the same entry. | |
| 50 | + | |
| 51 | +Saving a file refreshes the tree for you, so a **File ▸ Save as** into a new name shows up without asking. A file created another way — `go build` in a terminal window, or `git checkout` — needs the refresh key. | |
| 52 | + | |
| 53 | +## Work with the tree and a file side by side | |
| 54 | + | |
| 55 | +The tree is an ordinary window, so all the window commands apply: | |
| 56 | + | |
| 57 | +- **Window ▸ Tile** puts the tree and your file side by side. | |
| 58 | +- Drag its bottom-right corner to make it narrower once you know your way around. | |
| 59 | +- `[x]` closes it; `F9` brings it back. | |
| 60 | + | |
| 61 | +## Variants | |
| 62 | + | |
| 63 | +- **You started the editor from a subdirectory.** The tree is rooted there, showing only that part of the project. Start from the project's own directory instead — the same rule `.turbo-python/settings.toml` follows. | |
| 64 | +- **A directory shows as open but empty.** It could not be read, most often a permissions problem. The rest of the tree is unaffected; fix the permissions and press `F5`. | |
| 65 | + | |
| 66 | +## See also | |
| 67 | + | |
| 68 | +- Every key and what the tree shows, exactly: [Project tree reference](../reference/project-tree.md) | |
| 69 | +- Why it is a window rather than a docked panel, and why it does not watch the disk: [Project tree](../explanation/project-tree.md) | |
| 70 | +- Colouring it: [Theme file format](../reference/themes.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,70 @@ | |||
| 1 | +# How to browse a project and open files from a tree | ||
| 2 | + | ||
| 3 | +This guide shows how to open the project tree, walk it, and open a file from it. It assumes Turbo Python is already installed. | ||
| 4 | + | ||
| 5 | +## Open the tree | ||
| 6 | + | ||
| 7 | +Start the editor **from the project's own directory**, then press `F9`, or choose **Window ▸ Project tree**. | ||
| 8 | + | ||
| 9 | +A window opens showing the project's files, named after the directory the editor was started in: | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +╔═[x]════════════ turbo-python ════════════2═[■]╗ | ||
| 13 | +║ ▶ .turbo-python ║ | ||
| 14 | +║ ▼ internal ║ | ||
| 15 | +║ ▶ app ║ | ||
| 16 | +║ ▼ ui ║ | ||
| 17 | +║ window.go ║ | ||
| 18 | +║ .gitignore ║ | ||
| 19 | +║ pyproject.toml ║ | ||
| 20 | +║ main.py ║ | ||
| 21 | +╚══════════════════════════════════════════╝ | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +Directories come first, then files, each group sorted. `.git` is the only thing hidden — `.turbo-python`, `.gitignore` and the rest are files of your project, and you may well want to open them. | ||
| 25 | + | ||
| 26 | +Pressing `F9` again brings that window forward rather than opening a second tree. | ||
| 27 | + | ||
| 28 | +## Walk it | ||
| 29 | + | ||
| 30 | +| Key | Effect | | ||
| 31 | +| --- | --- | | ||
| 32 | +| `↑` `↓` | Move the highlight | | ||
| 33 | +| `→` | Open a closed directory; on anything else, step to the next row | | ||
| 34 | +| `←` | Close an open directory; on anything else, step out to the directory it is in | | ||
| 35 | +| `Enter` | Open a file, or open and close a directory | | ||
| 36 | +| `Home` `End` | First / last row | | ||
| 37 | +| `PgUp` `PgDn` | A screenful at a time | | ||
| 38 | + | ||
| 39 | +A directory is read the first time you open it, so a tree on a large project costs one listing rather than a walk of everything. | ||
| 40 | + | ||
| 41 | +## Open a file | ||
| 42 | + | ||
| 43 | +Put the highlight on it and press `Enter`, or click it twice. | ||
| 44 | + | ||
| 45 | +The file opens in a window of its own, in front of the tree. A file that is already open is brought forward rather than opened twice. | ||
| 46 | + | ||
| 47 | +## See a file that was made after you opened the tree | ||
| 48 | + | ||
| 49 | +The tree does not watch the disk. Press **`F5`** or **`Ctrl-R`** with the tree focused, and it re-reads the project — keeping open whatever you had open, and keeping the highlight on the same entry. | ||
| 50 | + | ||
| 51 | +Saving a file refreshes the tree for you, so a **File ▸ Save as** into a new name shows up without asking. A file created another way — `go build` in a terminal window, or `git checkout` — needs the refresh key. | ||
| 52 | + | ||
| 53 | +## Work with the tree and a file side by side | ||
| 54 | + | ||
| 55 | +The tree is an ordinary window, so all the window commands apply: | ||
| 56 | + | ||
| 57 | +- **Window ▸ Tile** puts the tree and your file side by side. | ||
| 58 | +- Drag its bottom-right corner to make it narrower once you know your way around. | ||
| 59 | +- `[x]` closes it; `F9` brings it back. | ||
| 60 | + | ||
| 61 | +## Variants | ||
| 62 | + | ||
| 63 | +- **You started the editor from a subdirectory.** The tree is rooted there, showing only that part of the project. Start from the project's own directory instead — the same rule `.turbo-python/settings.toml` follows. | ||
| 64 | +- **A directory shows as open but empty.** It could not be read, most often a permissions problem. The rest of the tree is unaffected; fix the permissions and press `F5`. | ||
| 65 | + | ||
| 66 | +## See also | ||
| 67 | + | ||
| 68 | +- Every key and what the tree shows, exactly: [Project tree reference](../reference/project-tree.md) | ||
| 69 | +- Why it is a window rather than a docked panel, and why it does not watch the disk: [Project tree](../explanation/project-tree.md) | ||
| 70 | +- Colouring it: [Theme file format](../reference/themes.md) | ||
added
docs/en/how-to/configure-a-project.md +83 -0 | new file mode 100644 | ||
| @@ -0,0 +1,83 @@ | ||
| 1 | +# How to give a project its own settings | |
| 2 | + | |
| 3 | +This guide shows how to pin a theme and turn on automatic saving for one project, so everyone who opens it gets the same editor. It assumes you already have Turbo Python installed. | |
| 4 | + | |
| 5 | +## Create the settings file | |
| 6 | + | |
| 7 | +Start the editor **from the project's own directory**, then choose **Options ▸ Create project settings**. | |
| 8 | + | |
| 9 | +That writes `.turbo-python/settings.toml`, filled in with the theme you are using right now, and opens it for editing — coloured, because Turbo Python colours TOML: | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +# turbo-python project settings. | |
| 13 | +# | |
| 14 | +# These apply to everyone who opens this project in turbo-python. Delete this file | |
| 15 | +# and the editor falls back to its own defaults. | |
| 16 | + | |
| 17 | +[editor] | |
| 18 | + | |
| 19 | +# The colour theme to start in. `turbo-python -list-themes` lists them all. | |
| 20 | +# A -theme flag on the command line overrides this. | |
| 21 | +theme = "turbo-classic" | |
| 22 | + | |
| 23 | +# Write modified files by themselves, a short while after you stop typing. | |
| 24 | +# On, because a project that has gone to the trouble of having a settings file | |
| 25 | +# has said what it wants; set it to false and save, and it stops at once. | |
| 26 | +autosave = true | |
| 27 | + | |
| 28 | +# How long that while is. Any Go duration: "500ms", "2s", "1m". | |
| 29 | +autosave_delay = "2s" | |
| 30 | +``` | |
| 31 | + | |
| 32 | +The file is read when the editor starts, and **again every time you save it** — so a change is in force the moment you press `F2`. The status bar confirms it: `Applied .turbo-python/settings.toml — autosave on (2s)`. | |
| 33 | + | |
| 34 | +That covers the settings this file holds, not the theme: **Options ▸ Theme** is the live way to change that, and writes your choice back here for you. | |
| 35 | + | |
| 36 | +The menu item you just used is now greyed out, and **Options ▸ Project settings…** beside it is not. That is the rule for all three of the project's files: you can create the one you have not got, and open the one you have. | |
| 37 | + | |
| 38 | +## Automatic saving | |
| 39 | + | |
| 40 | +It is already on: the file you were just given says `autosave = true`. | |
| 41 | + | |
| 42 | +Any file with a name is written two seconds after you stop typing. The status bar says `Saved main.py` when it happens. Nothing is written while you are still typing — each keystroke pushes the wait out again. | |
| 43 | + | |
| 44 | +Two things change as a consequence, both on purpose: | |
| 45 | + | |
| 46 | +- **Closing a window stops asking** whether to save. It was going to be saved anyway. | |
| 47 | +- **Leaving the editor stops asking** too, for the same reason. | |
| 48 | + | |
| 49 | +A file that has never been named is the exception: automatic saving never opens a dialog, so an untitled window keeps its `*` and is still asked about when you close it. | |
| 50 | + | |
| 51 | +To turn it off, set `autosave` to `false` and save; the status bar answers `autosave off`, and it stops there and then. To wait longer or less, change `autosave_delay`: | |
| 52 | + | |
| 53 | +```toml | |
| 54 | +autosave_delay = "500ms" | |
| 55 | +``` | |
| 56 | + | |
| 57 | +## Pin the theme | |
| 58 | + | |
| 59 | +Set `theme` to any name from `turbo-python -list-themes`, or simply pick one with **Options ▸ Theme** — with a settings file present, choosing a theme writes it into the file for you, keeping your comments and layout as they were. | |
| 60 | + | |
| 61 | +## Try a different theme without changing the file | |
| 62 | + | |
| 63 | +Pass `-theme` on the command line. It wins over the project's choice for that run only: | |
| 64 | + | |
| 65 | +```bash | |
| 66 | +turbo-python -theme turbo-dark main.py | |
| 67 | +``` | |
| 68 | + | |
| 69 | +## Edit the file later | |
| 70 | + | |
| 71 | +**Options ▸ Project settings…** opens it again. It is greyed out in a project that has none. | |
| 72 | + | |
| 73 | +## Variants | |
| 74 | + | |
| 75 | +- **You start the editor from a subdirectory.** The settings are not found: only `./.turbo-python` is looked at, with no walk up towards the project root. Start from the project's own directory, or pass `-theme` for that run. | |
| 76 | +- **The file has a mistake in it.** The editor says so on standard error and opens with its defaults, so you can fix the file in the editor itself. | |
| 77 | +- **You share the project.** `.turbo-python/settings.toml` is an ordinary file; commit it to agree on a theme across a team, or add it to `.gitignore` to keep it to yourself. | |
| 78 | + | |
| 79 | +## See also | |
| 80 | + | |
| 81 | +- Every key, with its type and default: [Project settings reference](../reference/project-settings.md) | |
| 82 | +- Why the file is not searched for in parent directories, and why autosave waits: [Project settings](../explanation/project-settings.md) | |
| 83 | +- Writing a theme to pin: [How to write your own theme](write-a-theme.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,83 @@ | |||
| 1 | +# How to give a project its own settings | ||
| 2 | + | ||
| 3 | +This guide shows how to pin a theme and turn on automatic saving for one project, so everyone who opens it gets the same editor. It assumes you already have Turbo Python installed. | ||
| 4 | + | ||
| 5 | +## Create the settings file | ||
| 6 | + | ||
| 7 | +Start the editor **from the project's own directory**, then choose **Options ▸ Create project settings**. | ||
| 8 | + | ||
| 9 | +That writes `.turbo-python/settings.toml`, filled in with the theme you are using right now, and opens it for editing — coloured, because Turbo Python colours TOML: | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +# turbo-python project settings. | ||
| 13 | +# | ||
| 14 | +# These apply to everyone who opens this project in turbo-python. Delete this file | ||
| 15 | +# and the editor falls back to its own defaults. | ||
| 16 | + | ||
| 17 | +[editor] | ||
| 18 | + | ||
| 19 | +# The colour theme to start in. `turbo-python -list-themes` lists them all. | ||
| 20 | +# A -theme flag on the command line overrides this. | ||
| 21 | +theme = "turbo-classic" | ||
| 22 | + | ||
| 23 | +# Write modified files by themselves, a short while after you stop typing. | ||
| 24 | +# On, because a project that has gone to the trouble of having a settings file | ||
| 25 | +# has said what it wants; set it to false and save, and it stops at once. | ||
| 26 | +autosave = true | ||
| 27 | + | ||
| 28 | +# How long that while is. Any Go duration: "500ms", "2s", "1m". | ||
| 29 | +autosave_delay = "2s" | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +The file is read when the editor starts, and **again every time you save it** — so a change is in force the moment you press `F2`. The status bar confirms it: `Applied .turbo-python/settings.toml — autosave on (2s)`. | ||
| 33 | + | ||
| 34 | +That covers the settings this file holds, not the theme: **Options ▸ Theme** is the live way to change that, and writes your choice back here for you. | ||
| 35 | + | ||
| 36 | +The menu item you just used is now greyed out, and **Options ▸ Project settings…** beside it is not. That is the rule for all three of the project's files: you can create the one you have not got, and open the one you have. | ||
| 37 | + | ||
| 38 | +## Automatic saving | ||
| 39 | + | ||
| 40 | +It is already on: the file you were just given says `autosave = true`. | ||
| 41 | + | ||
| 42 | +Any file with a name is written two seconds after you stop typing. The status bar says `Saved main.py` when it happens. Nothing is written while you are still typing — each keystroke pushes the wait out again. | ||
| 43 | + | ||
| 44 | +Two things change as a consequence, both on purpose: | ||
| 45 | + | ||
| 46 | +- **Closing a window stops asking** whether to save. It was going to be saved anyway. | ||
| 47 | +- **Leaving the editor stops asking** too, for the same reason. | ||
| 48 | + | ||
| 49 | +A file that has never been named is the exception: automatic saving never opens a dialog, so an untitled window keeps its `*` and is still asked about when you close it. | ||
| 50 | + | ||
| 51 | +To turn it off, set `autosave` to `false` and save; the status bar answers `autosave off`, and it stops there and then. To wait longer or less, change `autosave_delay`: | ||
| 52 | + | ||
| 53 | +```toml | ||
| 54 | +autosave_delay = "500ms" | ||
| 55 | +``` | ||
| 56 | + | ||
| 57 | +## Pin the theme | ||
| 58 | + | ||
| 59 | +Set `theme` to any name from `turbo-python -list-themes`, or simply pick one with **Options ▸ Theme** — with a settings file present, choosing a theme writes it into the file for you, keeping your comments and layout as they were. | ||
| 60 | + | ||
| 61 | +## Try a different theme without changing the file | ||
| 62 | + | ||
| 63 | +Pass `-theme` on the command line. It wins over the project's choice for that run only: | ||
| 64 | + | ||
| 65 | +```bash | ||
| 66 | +turbo-python -theme turbo-dark main.py | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +## Edit the file later | ||
| 70 | + | ||
| 71 | +**Options ▸ Project settings…** opens it again. It is greyed out in a project that has none. | ||
| 72 | + | ||
| 73 | +## Variants | ||
| 74 | + | ||
| 75 | +- **You start the editor from a subdirectory.** The settings are not found: only `./.turbo-python` is looked at, with no walk up towards the project root. Start from the project's own directory, or pass `-theme` for that run. | ||
| 76 | +- **The file has a mistake in it.** The editor says so on standard error and opens with its defaults, so you can fix the file in the editor itself. | ||
| 77 | +- **You share the project.** `.turbo-python/settings.toml` is an ordinary file; commit it to agree on a theme across a team, or add it to `.gitignore` to keep it to yourself. | ||
| 78 | + | ||
| 79 | +## See also | ||
| 80 | + | ||
| 81 | +- Every key, with its type and default: [Project settings reference](../reference/project-settings.md) | ||
| 82 | +- Why the file is not searched for in parent directories, and why autosave waits: [Project settings](../explanation/project-settings.md) | ||
| 83 | +- Writing a theme to pin: [How to write your own theme](write-a-theme.md) | ||
added
docs/en/how-to/enable-completion.md +95 -0 | new file mode 100644 | ||
| @@ -0,0 +1,95 @@ | ||
| 1 | +# How to enable Python completion | |
| 2 | + | |
| 3 | +This guide shows how to get completion, hovers and go-to-definition working. It assumes Turbo Python is already installed and that you know what a Python project is. | |
| 4 | + | |
| 5 | +Completion comes from **pylsp**, the official Python language server. Turbo Python does not bundle it: editing and colouring work without it, and only completion is lost. | |
| 6 | + | |
| 7 | +## 1. Install pylsp | |
| 8 | + | |
| 9 | +```bash | |
| 10 | +pipx component add pylsp | |
| 11 | +``` | |
| 12 | + | |
| 13 | +## 2. Make sure Turbo Python can find it | |
| 14 | + | |
| 15 | +Turbo Python looks on `PATH` first, then in `$GOBIN`, then in `$GOPATH/bin`. `go install` writes to the last of those, which is very often not on `PATH` — so this usually works without any further step. Check: | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +pylsp version | |
| 19 | +``` | |
| 20 | + | |
| 21 | +If that says "command not found" but Turbo Python still finds it, that is expected and fine. | |
| 22 | + | |
| 23 | +## 3. Open a file inside a module | |
| 24 | + | |
| 25 | +```bash | |
| 26 | +cd /path/to/your/module # the directory holding pyproject.toml | |
| 27 | +turbo-python main.py | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Turbo Python walks up from the file looking for `pyproject.toml` and starts pylsp in the directory it finds. **Outside a module, pylsp has very little to say** — this is the most common reason completion appears not to work. | |
| 31 | + | |
| 32 | +## 4. Ask for a completion | |
| 33 | + | |
| 34 | +Put the cursor after a dot and press **Ctrl-Space**: | |
| 35 | + | |
| 36 | +```go | |
| 37 | +fmt. | |
| 38 | +``` | |
| 39 | + | |
| 40 | +A list drops down under the cursor. Keep typing to narrow it, **↑ ↓** to walk it, **Enter** or **Tab** to accept, **Escape** to dismiss. | |
| 41 | + | |
| 42 | +Typing a `.` asks for a completion by itself, so most of the time you do not press anything. | |
| 43 | + | |
| 44 | +## Checking what the server is doing | |
| 45 | + | |
| 46 | +The right-hand end of the status bar shows the language server's state: `LSP: starting…`, `LSP: ready`, or why there is none. `Run ▸ Language server status` shows the same thing in a box. | |
| 47 | + | |
| 48 | +## Variants | |
| 49 | + | |
| 50 | +**You do not want a language server at all:** | |
| 51 | + | |
| 52 | +```bash | |
| 53 | +turbo-python -no-lsp main.py | |
| 54 | +``` | |
| 55 | + | |
| 56 | +**Completion is dead in a window that started without a name.** An Untitled window has no file to announce to pylsp until it is saved — press **F2** and give it a name ending in `.py`, somewhere under the project. From that save on, completion, hover and the error marks work in that window; there is no need to quit and relaunch. | |
| 57 | + | |
| 58 | +**Completion is empty in a file that does compile.** pylsp needs the file's package to build. Check `uv sync` first — a package that does not compile often yields nothing useful. | |
| 59 | + | |
| 60 | +**The first completion after opening a large module is slow.** pylsp is loading the module graph. The status bar says `LSP: starting…` until it is ready; requests made before then are refused rather than queued. | |
| 61 | + | |
| 62 | +**A request takes too long.** Every request gives up after three seconds, so a stuck server slows the editor but never freezes it. The status bar reports the failure. | |
| 63 | + | |
| 64 | +**The list is empty in a file that does not compile.** pylsp answers *nothing at all* — no error, an empty list — for a package it cannot load. A duplicate declaration or an unresolved import is enough. The editor now says which problem is in the way: | |
| 65 | + | |
| 66 | +``` | |
| 67 | +No completions — this file does not compile: main redeclared in this block | |
| 68 | +``` | |
| 69 | + | |
| 70 | +`Run ▸ Language server status` shows the same thing with the server's path, the workspace root, and whether it has been told about this file. Fix the package first — `uv sync` is the quickest check. | |
| 71 | + | |
| 72 | +**Ctrl-Space does nothing.** tmux, screen and IDE terminals frequently claim `Ctrl-Space` before the editor sees it. Type a `.` instead, which asks for a completion by itself, or use `Run ▸ Completion`. | |
| 73 | + | |
| 74 | +## What else the server gives you | |
| 75 | + | |
| 76 | +Completion is the loudest thing it does and the least of what it knows. The same connection answers eight more questions, all of them in the **Code** menu and all of them about the symbol under the cursor — no selection needed. | |
| 77 | + | |
| 78 | +| Key | What it does | | |
| 79 | +| --- | --- | | |
| 80 | +| **Ctrl-Space** | Completion list | | |
| 81 | +| **F1** | Describe the symbol under the cursor | | |
| 82 | +| **F12** | Jump to where it is declared | | |
| 83 | +| **Shift-F12** | List everywhere it is used | | |
| 84 | +| **Ctrl-T** | Find a symbol by name anywhere in the project | | |
| 85 | + | |
| 86 | +And, without a key: *Go to type definition*, *Find implementations…*, *Symbol in file…* and *Problems…*. | |
| 87 | + | |
| 88 | +Problems it finds arrive unasked. The first error in the file you are editing appears on the right of the status bar, prefixed with `⚠`; every line with a problem gets a mark in the gutter (`×` for an error, `!` for a warning); and **Code ▸ Problems…** lists all of them, for every file the server has loaded. | |
| 89 | + | |
| 90 | +[How to ask what the code means](ask-about-code.md) walks through all of it. | |
| 91 | + | |
| 92 | +## See also | |
| 93 | + | |
| 94 | +- Why the server is optional: [Colouring and completion](../explanation/colouring-and-completion.md) | |
| 95 | +- Every key: [keyboard reference](../reference/keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | +# How to enable Python completion | ||
| 2 | + | ||
| 3 | +This guide shows how to get completion, hovers and go-to-definition working. It assumes Turbo Python is already installed and that you know what a Python project is. | ||
| 4 | + | ||
| 5 | +Completion comes from **pylsp**, the official Python language server. Turbo Python does not bundle it: editing and colouring work without it, and only completion is lost. | ||
| 6 | + | ||
| 7 | +## 1. Install pylsp | ||
| 8 | + | ||
| 9 | +```bash | ||
| 10 | +pipx component add pylsp | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +## 2. Make sure Turbo Python can find it | ||
| 14 | + | ||
| 15 | +Turbo Python looks on `PATH` first, then in `$GOBIN`, then in `$GOPATH/bin`. `go install` writes to the last of those, which is very often not on `PATH` — so this usually works without any further step. Check: | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +pylsp version | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +If that says "command not found" but Turbo Python still finds it, that is expected and fine. | ||
| 22 | + | ||
| 23 | +## 3. Open a file inside a module | ||
| 24 | + | ||
| 25 | +```bash | ||
| 26 | +cd /path/to/your/module # the directory holding pyproject.toml | ||
| 27 | +turbo-python main.py | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Turbo Python walks up from the file looking for `pyproject.toml` and starts pylsp in the directory it finds. **Outside a module, pylsp has very little to say** — this is the most common reason completion appears not to work. | ||
| 31 | + | ||
| 32 | +## 4. Ask for a completion | ||
| 33 | + | ||
| 34 | +Put the cursor after a dot and press **Ctrl-Space**: | ||
| 35 | + | ||
| 36 | +```go | ||
| 37 | +fmt. | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +A list drops down under the cursor. Keep typing to narrow it, **↑ ↓** to walk it, **Enter** or **Tab** to accept, **Escape** to dismiss. | ||
| 41 | + | ||
| 42 | +Typing a `.` asks for a completion by itself, so most of the time you do not press anything. | ||
| 43 | + | ||
| 44 | +## Checking what the server is doing | ||
| 45 | + | ||
| 46 | +The right-hand end of the status bar shows the language server's state: `LSP: starting…`, `LSP: ready`, or why there is none. `Run ▸ Language server status` shows the same thing in a box. | ||
| 47 | + | ||
| 48 | +## Variants | ||
| 49 | + | ||
| 50 | +**You do not want a language server at all:** | ||
| 51 | + | ||
| 52 | +```bash | ||
| 53 | +turbo-python -no-lsp main.py | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +**Completion is dead in a window that started without a name.** An Untitled window has no file to announce to pylsp until it is saved — press **F2** and give it a name ending in `.py`, somewhere under the project. From that save on, completion, hover and the error marks work in that window; there is no need to quit and relaunch. | ||
| 57 | + | ||
| 58 | +**Completion is empty in a file that does compile.** pylsp needs the file's package to build. Check `uv sync` first — a package that does not compile often yields nothing useful. | ||
| 59 | + | ||
| 60 | +**The first completion after opening a large module is slow.** pylsp is loading the module graph. The status bar says `LSP: starting…` until it is ready; requests made before then are refused rather than queued. | ||
| 61 | + | ||
| 62 | +**A request takes too long.** Every request gives up after three seconds, so a stuck server slows the editor but never freezes it. The status bar reports the failure. | ||
| 63 | + | ||
| 64 | +**The list is empty in a file that does not compile.** pylsp answers *nothing at all* — no error, an empty list — for a package it cannot load. A duplicate declaration or an unresolved import is enough. The editor now says which problem is in the way: | ||
| 65 | + | ||
| 66 | +``` | ||
| 67 | +No completions — this file does not compile: main redeclared in this block | ||
| 68 | +``` | ||
| 69 | + | ||
| 70 | +`Run ▸ Language server status` shows the same thing with the server's path, the workspace root, and whether it has been told about this file. Fix the package first — `uv sync` is the quickest check. | ||
| 71 | + | ||
| 72 | +**Ctrl-Space does nothing.** tmux, screen and IDE terminals frequently claim `Ctrl-Space` before the editor sees it. Type a `.` instead, which asks for a completion by itself, or use `Run ▸ Completion`. | ||
| 73 | + | ||
| 74 | +## What else the server gives you | ||
| 75 | + | ||
| 76 | +Completion is the loudest thing it does and the least of what it knows. The same connection answers eight more questions, all of them in the **Code** menu and all of them about the symbol under the cursor — no selection needed. | ||
| 77 | + | ||
| 78 | +| Key | What it does | | ||
| 79 | +| --- | --- | | ||
| 80 | +| **Ctrl-Space** | Completion list | | ||
| 81 | +| **F1** | Describe the symbol under the cursor | | ||
| 82 | +| **F12** | Jump to where it is declared | | ||
| 83 | +| **Shift-F12** | List everywhere it is used | | ||
| 84 | +| **Ctrl-T** | Find a symbol by name anywhere in the project | | ||
| 85 | + | ||
| 86 | +And, without a key: *Go to type definition*, *Find implementations…*, *Symbol in file…* and *Problems…*. | ||
| 87 | + | ||
| 88 | +Problems it finds arrive unasked. The first error in the file you are editing appears on the right of the status bar, prefixed with `⚠`; every line with a problem gets a mark in the gutter (`×` for an error, `!` for a warning); and **Code ▸ Problems…** lists all of them, for every file the server has loaded. | ||
| 89 | + | ||
| 90 | +[How to ask what the code means](ask-about-code.md) walks through all of it. | ||
| 91 | + | ||
| 92 | +## See also | ||
| 93 | + | ||
| 94 | +- Why the server is optional: [Colouring and completion](../explanation/colouring-and-completion.md) | ||
| 95 | +- Every key: [keyboard reference](../reference/keyboard.md) | ||
added
docs/en/how-to/install.md +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 1 | +# How to install and build Turbo Python | |
| 2 | + | |
| 3 | +This guide shows how to get a working `turbo-python` binary. It assumes you have Go 1.26 or later and can use a terminal. | |
| 4 | + | |
| 5 | +## The short way, from a checkout | |
| 6 | + | |
| 7 | +```bash | |
| 8 | +git clone ssh://git@rickub.com/turbo-editors/turbo-python.git | |
| 9 | +cd turbo-python | |
| 10 | +make install | |
| 11 | +``` | |
| 12 | + | |
| 13 | +That builds the editor, puts it where your shell looks for commands, and tells you what it found: the Go version it built with, where the binary went, whether that directory is on your `PATH`, and whether `pylsp` is installed. The build goes to a temporary file first, so a failed build never replaces a working installation. | |
| 14 | + | |
| 15 | +Then, from any Python project: | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +turbo-python main.py | |
| 19 | +``` | |
| 20 | + | |
| 21 | +### Options | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +scripts/install.sh --prefix ~/bin # install somewhere of your choosing | |
| 25 | +scripts/install.sh --with-pylsp # install the language server too | |
| 26 | +scripts/install.sh --uninstall # remove it again (make uninstall) | |
| 27 | +scripts/install.sh --help | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Without `--prefix`, the editor goes where `go install` would put it: `$GOBIN`, or `$GOPATH/bin` when `GOBIN` is unset — usually `~/go/bin`. | |
| 31 | + | |
| 32 | +## Just build it, without installing | |
| 33 | + | |
| 34 | +```bash | |
| 35 | +make build | |
| 36 | +./bin/turbo-python main.py | |
| 37 | +``` | |
| 38 | + | |
| 39 | +## From the module proxy, without a checkout | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +go install rickub.com/turbo-editors/turbo-python@latest | |
| 43 | +``` | |
| 44 | + | |
| 45 | +If the command is then "not found", the install directory is not on your `PATH`: | |
| 46 | + | |
| 47 | +```bash | |
| 48 | +export PATH="$PATH:$(go env GOPATH)/bin" | |
| 49 | +``` | |
| 50 | + | |
| 51 | +## Check it works | |
| 52 | + | |
| 53 | +```bash | |
| 54 | +turbo-python -version | |
| 55 | +turbo-python -list-themes | |
| 56 | +``` | |
| 57 | + | |
| 58 | +The first names the commit the binary was built from, which is what to quote in a bug report; [the version number](../reference/versioning.md) explains what each form means. The second prints the themes compiled into the binary and tells you where your own would go. | |
| 59 | + | |
| 60 | +## Variants | |
| 61 | + | |
| 62 | +- **You only want to run it once**: `go run rickub.com/turbo-editors/turbo-python@latest src/main.py` | |
| 63 | +- **You want the binary somewhere specific**: `go build -o /usr/local/bin/turbo-python .` | |
| 64 | +- **Your terminal has no true colour**: use `turbo-python -theme turbo-classic`, which is built from the sixteen ANSI colours only. `turbo-dark` and `borland-light` use 24-bit colours. | |
| 65 | + | |
| 66 | +## When something goes wrong | |
| 67 | + | |
| 68 | +**`the installed binary does not run`.** The installer prints whatever the system said just above that line — read it first, because it names the actual problem. | |
| 69 | + | |
| 70 | +The installer replaces the binary rather than writing over the one that is there, so a reinstall gives the file a fresh identity. That matters on macOS, which caches a binary's code signature against its inode: writing new bytes into the old inode leaves the cached signature describing something else, and the kernel then refuses to run a binary that built and installed perfectly. If you have an older copy installed by something that used `cp`, removing it first clears any such state: | |
| 71 | + | |
| 72 | +```bash | |
| 73 | +scripts/install.sh --uninstall | |
| 74 | +scripts/install.sh | |
| 75 | +``` | |
| 76 | + | |
| 77 | +**`Go x.y or later is needed`.** The editor is written in Go, so building it needs a Go toolchain even though it is an editor for Python. The version comes from `go.mod`, so it cannot drift from what the code actually needs. | |
| 78 | + | |
| 79 | +**`build failed; nothing was installed`.** Your existing installation is untouched — the build goes to a temporary file first. The compiler's own output is printed above the message. | |
| 80 | + | |
| 81 | +## Terminal requirements | |
| 82 | + | |
| 83 | +Turbo Python needs a terminal that reports its size and supports mouse reporting — every mainstream one does. It reads `TERM` through tcell; if the display is wrong, check that `TERM` matches your terminal (`xterm-256color` is a safe default). | |
| 84 | + | |
| 85 | +## See also | |
| 86 | + | |
| 87 | +- Every flag: [command line reference](../reference/cli.md) | |
| 88 | +- Getting completion working: [How to enable Python completion](enable-completion.md) | |
| 89 | +- A guided first session: [Your first file in Turbo Python](../tutorials/getting-started.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# How to install and build Turbo Python | ||
| 2 | + | ||
| 3 | +This guide shows how to get a working `turbo-python` binary. It assumes you have Go 1.26 or later and can use a terminal. | ||
| 4 | + | ||
| 5 | +## The short way, from a checkout | ||
| 6 | + | ||
| 7 | +```bash | ||
| 8 | +git clone ssh://git@rickub.com/turbo-editors/turbo-python.git | ||
| 9 | +cd turbo-python | ||
| 10 | +make install | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +That builds the editor, puts it where your shell looks for commands, and tells you what it found: the Go version it built with, where the binary went, whether that directory is on your `PATH`, and whether `pylsp` is installed. The build goes to a temporary file first, so a failed build never replaces a working installation. | ||
| 14 | + | ||
| 15 | +Then, from any Python project: | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +turbo-python main.py | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +### Options | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +scripts/install.sh --prefix ~/bin # install somewhere of your choosing | ||
| 25 | +scripts/install.sh --with-pylsp # install the language server too | ||
| 26 | +scripts/install.sh --uninstall # remove it again (make uninstall) | ||
| 27 | +scripts/install.sh --help | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Without `--prefix`, the editor goes where `go install` would put it: `$GOBIN`, or `$GOPATH/bin` when `GOBIN` is unset — usually `~/go/bin`. | ||
| 31 | + | ||
| 32 | +## Just build it, without installing | ||
| 33 | + | ||
| 34 | +```bash | ||
| 35 | +make build | ||
| 36 | +./bin/turbo-python main.py | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +## From the module proxy, without a checkout | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +go install rickub.com/turbo-editors/turbo-python@latest | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +If the command is then "not found", the install directory is not on your `PATH`: | ||
| 46 | + | ||
| 47 | +```bash | ||
| 48 | +export PATH="$PATH:$(go env GOPATH)/bin" | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +## Check it works | ||
| 52 | + | ||
| 53 | +```bash | ||
| 54 | +turbo-python -version | ||
| 55 | +turbo-python -list-themes | ||
| 56 | +``` | ||
| 57 | + | ||
| 58 | +The first names the commit the binary was built from, which is what to quote in a bug report; [the version number](../reference/versioning.md) explains what each form means. The second prints the themes compiled into the binary and tells you where your own would go. | ||
| 59 | + | ||
| 60 | +## Variants | ||
| 61 | + | ||
| 62 | +- **You only want to run it once**: `go run rickub.com/turbo-editors/turbo-python@latest src/main.py` | ||
| 63 | +- **You want the binary somewhere specific**: `go build -o /usr/local/bin/turbo-python .` | ||
| 64 | +- **Your terminal has no true colour**: use `turbo-python -theme turbo-classic`, which is built from the sixteen ANSI colours only. `turbo-dark` and `borland-light` use 24-bit colours. | ||
| 65 | + | ||
| 66 | +## When something goes wrong | ||
| 67 | + | ||
| 68 | +**`the installed binary does not run`.** The installer prints whatever the system said just above that line — read it first, because it names the actual problem. | ||
| 69 | + | ||
| 70 | +The installer replaces the binary rather than writing over the one that is there, so a reinstall gives the file a fresh identity. That matters on macOS, which caches a binary's code signature against its inode: writing new bytes into the old inode leaves the cached signature describing something else, and the kernel then refuses to run a binary that built and installed perfectly. If you have an older copy installed by something that used `cp`, removing it first clears any such state: | ||
| 71 | + | ||
| 72 | +```bash | ||
| 73 | +scripts/install.sh --uninstall | ||
| 74 | +scripts/install.sh | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +**`Go x.y or later is needed`.** The editor is written in Go, so building it needs a Go toolchain even though it is an editor for Python. The version comes from `go.mod`, so it cannot drift from what the code actually needs. | ||
| 78 | + | ||
| 79 | +**`build failed; nothing was installed`.** Your existing installation is untouched — the build goes to a temporary file first. The compiler's own output is printed above the message. | ||
| 80 | + | ||
| 81 | +## Terminal requirements | ||
| 82 | + | ||
| 83 | +Turbo Python needs a terminal that reports its size and supports mouse reporting — every mainstream one does. It reads `TERM` through tcell; if the display is wrong, check that `TERM` matches your terminal (`xterm-256color` is a safe default). | ||
| 84 | + | ||
| 85 | +## See also | ||
| 86 | + | ||
| 87 | +- Every flag: [command line reference](../reference/cli.md) | ||
| 88 | +- Getting completion working: [How to enable Python completion](enable-completion.md) | ||
| 89 | +- A guided first session: [Your first file in Turbo Python](../tutorials/getting-started.md) | ||
added
docs/en/how-to/make-a-release.md +103 -0 | new file mode 100644 | ||
| @@ -0,0 +1,103 @@ | ||
| 1 | +# How to make a release | |
| 2 | + | |
| 3 | +This guide shows how to cut a release so that the editor reports its own version correctly. It assumes you can push to the repository. | |
| 4 | + | |
| 5 | +## Check what you are about to release | |
| 6 | + | |
| 7 | +```sh | |
| 8 | +make version | |
| 9 | +``` | |
| 10 | + | |
| 11 | +``` | |
| 12 | +v0.1.0-14-g88a4c38 (88a4c38) | |
| 13 | +``` | |
| 14 | + | |
| 15 | +Fourteen commits past `v0.1.0`. A `-dirty` on the end means you have uncommitted changes — commit or stash them first, or the release will carry that suffix for ever. | |
| 16 | + | |
| 17 | +## Tag it | |
| 18 | + | |
| 19 | +```sh | |
| 20 | +git tag -a v0.2.0 -m "v0.2.0" | |
| 21 | +git push origin v0.2.0 | |
| 22 | +``` | |
| 23 | + | |
| 24 | +The tag is what the version comes from, so it has to exist before you build anything you intend to hand out. Annotated (`-a`) rather than lightweight, because `git describe` prefers annotated tags. | |
| 25 | + | |
| 26 | +## Build the release binary | |
| 27 | + | |
| 28 | +```sh | |
| 29 | +make build | |
| 30 | +./bin/turbo-python -version | |
| 31 | +``` | |
| 32 | + | |
| 33 | +``` | |
| 34 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | |
| 35 | +``` | |
| 36 | + | |
| 37 | +No `-14-g…` suffix: you are exactly on the tag. That is what tells you the tag took. | |
| 38 | + | |
| 39 | +## Check the About box | |
| 40 | + | |
| 41 | +Start the editor and press `Alt-H`, then `A`. | |
| 42 | + | |
| 43 | +``` | |
| 44 | +Turbo Python 0.2.0 | |
| 45 | + | |
| 46 | +A Turbo C-style editor for Python, | |
| 47 | +written in Go. | |
| 48 | + | |
| 49 | +Commit: 88a4c38 | |
| 50 | +Built: 2026-08-31 18:04 UTC | |
| 51 | +Theme: Turbo Classic | |
| 52 | +``` | |
| 53 | + | |
| 54 | +## Or use the scripts and let the workflow publish | |
| 55 | + | |
| 56 | +That is the way a release is actually cut. Put the version and its one-line description in `release.env` — it is gitignored, so CI never sees it: | |
| 57 | + | |
| 58 | +```sh | |
| 59 | +TAG="v1.0.0" | |
| 60 | +ABOUT="Turbo Python" | |
| 61 | +``` | |
| 62 | + | |
| 63 | +Then run one script: | |
| 64 | + | |
| 65 | +```sh | |
| 66 | +./01-release.tag.sh | |
| 67 | +``` | |
| 68 | + | |
| 69 | +It runs `make check`, refuses a tag already taken locally or on `origin`, refuses a `go.mod` carrying a `replace` directive, commits anything outstanding, pushes the branch, and only then tags and pushes the tag. That order matters: a tag pushed before the branch points at a commit the remote has never seen, and a tag created before a failed push is left behind for somebody to find. | |
| 70 | + | |
| 71 | +That is the last thing you run by hand. Pushing the tag starts `.github/workflows/release.yml`; follow it on the repository's Actions tab. It runs the suite, cross-compiles the binaries with `./02-build-releases.sh` — the same script you can run on your machine — and creates the release page with them: the tag's message, the `go install` line, links to the documentation **at that tag**, one binary per platform, the `SHA256SUMS` and the README that describes the downloads. | |
| 72 | + | |
| 73 | +The job publishes with its own `GITHUB_TOKEN`, which is the only credential Rickub's release API accepts — a personal token is refused. There is nothing to configure and no secret to keep, which is why the old `02-release.publish.sh` and `04-release.upload-binaries.sh` are gone. | |
| 74 | + | |
| 75 | +`02-build-releases.sh` cross-compiles every platform and **stamps `TAG` itself**, by overriding the Makefile's version: `make ldflags VERSION=v1.0.0`. The release *is* `v1.0.0`, so that is what its binaries say — whatever `git describe` would have answered, and whether or not the tag has been created yet. It then runs the staged binary for this machine and checks it reports the version, which is the only proof that what ships carries it. | |
| 76 | + | |
| 77 | +You can see what the workflow will publish without publishing anything, or build the binaries by hand: | |
| 78 | + | |
| 79 | +```sh | |
| 80 | +./02-build-releases.sh v1.0.0 # writes release/v1.0.0/, pushes nothing | |
| 81 | +``` | |
| 82 | + | |
| 83 | +With no argument it reads `TAG` from `release.env`; the workflow has no `release.env`, so it passes the tag it was started by. | |
| 84 | + | |
| 85 | +The suite includes tests that run `01-release.tag.sh` against a throwaway clone. They skip themselves when `TURBO_PYTHON_RELEASING` is set, which the script exports before calling `make check` — removing that line makes a release recurse until something runs out. The workflow sets the same variable for its own `go test` step. | |
| 86 | + | |
| 87 | +## Variants | |
| 88 | + | |
| 89 | +- **You install rather than distribute a binary.** `make install` and `scripts/install.sh` stamp the same way, so an installed editor names the commit it came from. There is nothing extra to do. | |
| 90 | +- **Someone installs with `go install`.** `go install rickub.com/turbo-editors/turbo-python@v0.2.0` reports `0.2.0` from the module version, with no commit and no build date. That is the Go tool's own record; nothing needs stamping. | |
| 91 | +- **You tagged the wrong commit.** If the tag has not been pushed, delete it (`git tag -d v1.0.0`), tag the right one, and rebuild. Once it is on `origin`, do not move it: the module proxy has cached `go install …@v1.0.0` and the release page already carries binaries with that number, which is why `01-release.tag.sh` refuses a tag that exists. Bump `TAG` and release again. | |
| 92 | +- **About says `devel`.** The binary was built with a plain `go build .` rather than through `make`. Nothing is wrong with it; it simply has no tag stamped, because the Go build system does not read git tags. Use `make build`. | |
| 93 | +- **About says `unknown`.** Nothing named the build at all — a `uv run`, or a build from a directory with no git history. Use `make build` from the checkout. | |
| 94 | +- **You have no git at all**, having downloaded a source archive. `make build` still works and the binary reports `unknown`. Pass the version yourself if you need one: | |
| 95 | + ```sh | |
| 96 | + go build -ldflags "-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0'" -o bin/turbo-python . | |
| 97 | + ``` | |
| 98 | + | |
| 99 | +## See also | |
| 100 | + | |
| 101 | +- Every source of the number, and what each build reports: [The version number](../reference/versioning.md) | |
| 102 | +- Why there is no version constant in the source: [Design decisions](../explanation/design-decisions.md#the-version-is-a-property-of-the-build-not-of-the-source) | |
| 103 | +- Installing onto your PATH: [How to install and build Turbo Python](install.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | +# How to make a release | ||
| 2 | + | ||
| 3 | +This guide shows how to cut a release so that the editor reports its own version correctly. It assumes you can push to the repository. | ||
| 4 | + | ||
| 5 | +## Check what you are about to release | ||
| 6 | + | ||
| 7 | +```sh | ||
| 8 | +make version | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +v0.1.0-14-g88a4c38 (88a4c38) | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +Fourteen commits past `v0.1.0`. A `-dirty` on the end means you have uncommitted changes — commit or stash them first, or the release will carry that suffix for ever. | ||
| 16 | + | ||
| 17 | +## Tag it | ||
| 18 | + | ||
| 19 | +```sh | ||
| 20 | +git tag -a v0.2.0 -m "v0.2.0" | ||
| 21 | +git push origin v0.2.0 | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +The tag is what the version comes from, so it has to exist before you build anything you intend to hand out. Annotated (`-a`) rather than lightweight, because `git describe` prefers annotated tags. | ||
| 25 | + | ||
| 26 | +## Build the release binary | ||
| 27 | + | ||
| 28 | +```sh | ||
| 29 | +make build | ||
| 30 | +./bin/turbo-python -version | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +``` | ||
| 34 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | ||
| 35 | +``` | ||
| 36 | + | ||
| 37 | +No `-14-g…` suffix: you are exactly on the tag. That is what tells you the tag took. | ||
| 38 | + | ||
| 39 | +## Check the About box | ||
| 40 | + | ||
| 41 | +Start the editor and press `Alt-H`, then `A`. | ||
| 42 | + | ||
| 43 | +``` | ||
| 44 | +Turbo Python 0.2.0 | ||
| 45 | + | ||
| 46 | +A Turbo C-style editor for Python, | ||
| 47 | +written in Go. | ||
| 48 | + | ||
| 49 | +Commit: 88a4c38 | ||
| 50 | +Built: 2026-08-31 18:04 UTC | ||
| 51 | +Theme: Turbo Classic | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +## Or use the scripts and let the workflow publish | ||
| 55 | + | ||
| 56 | +That is the way a release is actually cut. Put the version and its one-line description in `release.env` — it is gitignored, so CI never sees it: | ||
| 57 | + | ||
| 58 | +```sh | ||
| 59 | +TAG="v1.0.0" | ||
| 60 | +ABOUT="Turbo Python" | ||
| 61 | +``` | ||
| 62 | + | ||
| 63 | +Then run one script: | ||
| 64 | + | ||
| 65 | +```sh | ||
| 66 | +./01-release.tag.sh | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +It runs `make check`, refuses a tag already taken locally or on `origin`, refuses a `go.mod` carrying a `replace` directive, commits anything outstanding, pushes the branch, and only then tags and pushes the tag. That order matters: a tag pushed before the branch points at a commit the remote has never seen, and a tag created before a failed push is left behind for somebody to find. | ||
| 70 | + | ||
| 71 | +That is the last thing you run by hand. Pushing the tag starts `.github/workflows/release.yml`; follow it on the repository's Actions tab. It runs the suite, cross-compiles the binaries with `./02-build-releases.sh` — the same script you can run on your machine — and creates the release page with them: the tag's message, the `go install` line, links to the documentation **at that tag**, one binary per platform, the `SHA256SUMS` and the README that describes the downloads. | ||
| 72 | + | ||
| 73 | +The job publishes with its own `GITHUB_TOKEN`, which is the only credential Rickub's release API accepts — a personal token is refused. There is nothing to configure and no secret to keep, which is why the old `02-release.publish.sh` and `04-release.upload-binaries.sh` are gone. | ||
| 74 | + | ||
| 75 | +`02-build-releases.sh` cross-compiles every platform and **stamps `TAG` itself**, by overriding the Makefile's version: `make ldflags VERSION=v1.0.0`. The release *is* `v1.0.0`, so that is what its binaries say — whatever `git describe` would have answered, and whether or not the tag has been created yet. It then runs the staged binary for this machine and checks it reports the version, which is the only proof that what ships carries it. | ||
| 76 | + | ||
| 77 | +You can see what the workflow will publish without publishing anything, or build the binaries by hand: | ||
| 78 | + | ||
| 79 | +```sh | ||
| 80 | +./02-build-releases.sh v1.0.0 # writes release/v1.0.0/, pushes nothing | ||
| 81 | +``` | ||
| 82 | + | ||
| 83 | +With no argument it reads `TAG` from `release.env`; the workflow has no `release.env`, so it passes the tag it was started by. | ||
| 84 | + | ||
| 85 | +The suite includes tests that run `01-release.tag.sh` against a throwaway clone. They skip themselves when `TURBO_PYTHON_RELEASING` is set, which the script exports before calling `make check` — removing that line makes a release recurse until something runs out. The workflow sets the same variable for its own `go test` step. | ||
| 86 | + | ||
| 87 | +## Variants | ||
| 88 | + | ||
| 89 | +- **You install rather than distribute a binary.** `make install` and `scripts/install.sh` stamp the same way, so an installed editor names the commit it came from. There is nothing extra to do. | ||
| 90 | +- **Someone installs with `go install`.** `go install rickub.com/turbo-editors/turbo-python@v0.2.0` reports `0.2.0` from the module version, with no commit and no build date. That is the Go tool's own record; nothing needs stamping. | ||
| 91 | +- **You tagged the wrong commit.** If the tag has not been pushed, delete it (`git tag -d v1.0.0`), tag the right one, and rebuild. Once it is on `origin`, do not move it: the module proxy has cached `go install …@v1.0.0` and the release page already carries binaries with that number, which is why `01-release.tag.sh` refuses a tag that exists. Bump `TAG` and release again. | ||
| 92 | +- **About says `devel`.** The binary was built with a plain `go build .` rather than through `make`. Nothing is wrong with it; it simply has no tag stamped, because the Go build system does not read git tags. Use `make build`. | ||
| 93 | +- **About says `unknown`.** Nothing named the build at all — a `uv run`, or a build from a directory with no git history. Use `make build` from the checkout. | ||
| 94 | +- **You have no git at all**, having downloaded a source archive. `make build` still works and the binary reports `unknown`. Pass the version yourself if you need one: | ||
| 95 | + ```sh | ||
| 96 | + go build -ldflags "-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0'" -o bin/turbo-python . | ||
| 97 | + ``` | ||
| 98 | + | ||
| 99 | +## See also | ||
| 100 | + | ||
| 101 | +- Every source of the number, and what each build reports: [The version number](../reference/versioning.md) | ||
| 102 | +- Why there is no version constant in the source: [Design decisions](../explanation/design-decisions.md#the-version-is-a-property-of-the-build-not-of-the-source) | ||
| 103 | +- Installing onto your PATH: [How to install and build Turbo Python](install.md) | ||
added
docs/en/how-to/run-the-tests.md +95 -0 | new file mode 100644 | ||
| @@ -0,0 +1,95 @@ | ||
| 1 | +# How to run the tests | |
| 2 | + | |
| 3 | +This guide shows how to run and read Turbo Python's test suite. It assumes you have a checkout and Go 1.26 or later. | |
| 4 | + | |
| 5 | +## The whole suite | |
| 6 | + | |
| 7 | +```bash | |
| 8 | +make test | |
| 9 | +``` | |
| 10 | + | |
| 11 | +That is the single documented command. It runs `uv run pytest` across every package. | |
| 12 | + | |
| 13 | +## Variants | |
| 14 | + | |
| 15 | +**See each test by name:** | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +make test-verbose | |
| 19 | +``` | |
| 20 | + | |
| 21 | +**Measure coverage per package:** | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +make cover | |
| 25 | +``` | |
| 26 | + | |
| 27 | +**One package only:** | |
| 28 | + | |
| 29 | +```bash | |
| 30 | +go test ./internal/buffer/ | |
| 31 | +``` | |
| 32 | + | |
| 33 | +**Without starting a language server.** One test in `internal/lsp` starts a real `pylsp` when it finds one. To skip it: | |
| 34 | + | |
| 35 | +```bash | |
| 36 | +go test -short ./... | |
| 37 | +``` | |
| 38 | + | |
| 39 | +**With the race detector.** The LSP client is concurrent, so this is worth running before touching it: | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +go test -race ./internal/lsp/ | |
| 43 | +``` | |
| 44 | + | |
| 45 | +**Everything a commit should pass:** | |
| 46 | + | |
| 47 | +```bash | |
| 48 | +make check | |
| 49 | +``` | |
| 50 | + | |
| 51 | +This runs `go fmt`, `go vet` and the tests, in that order. | |
| 52 | + | |
| 53 | +## What the suite covers | |
| 54 | + | |
| 55 | +No test needs a real terminal. The widgets and the editor are drawn onto tcell's `SimulationScreen` — a real `Screen` that draws into memory — so the assertions are made on the picture a terminal would actually show. The LSP client is driven against a language server running in the same process, over an in-memory pipe. | |
| 56 | + | |
| 57 | +The one exception is `TestAgainstRealGopls`, which starts the real thing. It **skips itself** when `pylsp` is not installed, so a checkout without one still has a green suite. | |
| 58 | + | |
| 59 | +## Testing against an unreleased turbo-core | |
| 60 | + | |
| 61 | +Most of Turbo Python is turbo-core, and this repository depends on it by version, from the module proxy: | |
| 62 | + | |
| 63 | +``` | |
| 64 | +require rickub.com/turbo-editors/turbo-core v0.2.0 | |
| 65 | +``` | |
| 66 | + | |
| 67 | +A change made in a turbo-core checkout beside this one is therefore invisible here until it is published. To test it before that, make a workspace: | |
| 68 | + | |
| 69 | +```bash | |
| 70 | +go work init . ../turbo-core | |
| 71 | +make test | |
| 72 | +``` | |
| 73 | + | |
| 74 | +Every import of the library now resolves to that checkout. Nothing in `go.mod` or `go.sum` changes, so there is no edit to undo. Check it took effect — this is the mistake worth guarding against, because everything still builds and still passes if it did not: | |
| 75 | + | |
| 76 | +```bash | |
| 77 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app | |
| 78 | +``` | |
| 79 | + | |
| 80 | +The answer should be your checkout, not a path under `pkg/mod`. When you are done, `rm go.work go.work.sum`; it is gitignored, so it cannot be committed by accident. | |
| 81 | + | |
| 82 | +## Code quality | |
| 83 | + | |
| 84 | +The test suite is not the whole gate. Quality is measured separately: | |
| 85 | + | |
| 86 | +```bash | |
| 87 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | |
| 88 | +``` | |
| 89 | + | |
| 90 | +It writes a report under `.quality/` and exits non-zero if the gate fails. | |
| 91 | + | |
| 92 | +## See also | |
| 93 | + | |
| 94 | +- Why the tests are shaped this way: [Architecture](../explanation/architecture.md) | |
| 95 | +- Every make target: [command line reference](../reference/cli.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | +# How to run the tests | ||
| 2 | + | ||
| 3 | +This guide shows how to run and read Turbo Python's test suite. It assumes you have a checkout and Go 1.26 or later. | ||
| 4 | + | ||
| 5 | +## The whole suite | ||
| 6 | + | ||
| 7 | +```bash | ||
| 8 | +make test | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +That is the single documented command. It runs `uv run pytest` across every package. | ||
| 12 | + | ||
| 13 | +## Variants | ||
| 14 | + | ||
| 15 | +**See each test by name:** | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +make test-verbose | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +**Measure coverage per package:** | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +make cover | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +**One package only:** | ||
| 28 | + | ||
| 29 | +```bash | ||
| 30 | +go test ./internal/buffer/ | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +**Without starting a language server.** One test in `internal/lsp` starts a real `pylsp` when it finds one. To skip it: | ||
| 34 | + | ||
| 35 | +```bash | ||
| 36 | +go test -short ./... | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +**With the race detector.** The LSP client is concurrent, so this is worth running before touching it: | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +go test -race ./internal/lsp/ | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +**Everything a commit should pass:** | ||
| 46 | + | ||
| 47 | +```bash | ||
| 48 | +make check | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +This runs `go fmt`, `go vet` and the tests, in that order. | ||
| 52 | + | ||
| 53 | +## What the suite covers | ||
| 54 | + | ||
| 55 | +No test needs a real terminal. The widgets and the editor are drawn onto tcell's `SimulationScreen` — a real `Screen` that draws into memory — so the assertions are made on the picture a terminal would actually show. The LSP client is driven against a language server running in the same process, over an in-memory pipe. | ||
| 56 | + | ||
| 57 | +The one exception is `TestAgainstRealGopls`, which starts the real thing. It **skips itself** when `pylsp` is not installed, so a checkout without one still has a green suite. | ||
| 58 | + | ||
| 59 | +## Testing against an unreleased turbo-core | ||
| 60 | + | ||
| 61 | +Most of Turbo Python is turbo-core, and this repository depends on it by version, from the module proxy: | ||
| 62 | + | ||
| 63 | +``` | ||
| 64 | +require rickub.com/turbo-editors/turbo-core v0.2.0 | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +A change made in a turbo-core checkout beside this one is therefore invisible here until it is published. To test it before that, make a workspace: | ||
| 68 | + | ||
| 69 | +```bash | ||
| 70 | +go work init . ../turbo-core | ||
| 71 | +make test | ||
| 72 | +``` | ||
| 73 | + | ||
| 74 | +Every import of the library now resolves to that checkout. Nothing in `go.mod` or `go.sum` changes, so there is no edit to undo. Check it took effect — this is the mistake worth guarding against, because everything still builds and still passes if it did not: | ||
| 75 | + | ||
| 76 | +```bash | ||
| 77 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +The answer should be your checkout, not a path under `pkg/mod`. When you are done, `rm go.work go.work.sum`; it is gitignored, so it cannot be committed by accident. | ||
| 81 | + | ||
| 82 | +## Code quality | ||
| 83 | + | ||
| 84 | +The test suite is not the whole gate. Quality is measured separately: | ||
| 85 | + | ||
| 86 | +```bash | ||
| 87 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | ||
| 88 | +``` | ||
| 89 | + | ||
| 90 | +It writes a report under `.quality/` and exits non-zero if the gate fails. | ||
| 91 | + | ||
| 92 | +## See also | ||
| 93 | + | ||
| 94 | +- Why the tests are shaped this way: [Architecture](../explanation/architecture.md) | ||
| 95 | +- Every make target: [command line reference](../reference/cli.md) | ||
added
docs/en/how-to/run-uv-commands.md +214 -0 | new file mode 100644 | ||
| @@ -0,0 +1,214 @@ | ||
| 1 | +# How to run uv commands from the editor | |
| 2 | + | |
| 3 | +This guide shows how to format, lint, build, test and run your project without leaving Turbo Python. It assumes the editor is installed and you have a Python project. | |
| 4 | + | |
| 5 | +## Get a starter file | |
| 6 | + | |
| 7 | +Start the editor **from the project's own directory**, then choose **Python ▸ Create tools file** (`Alt-P`, then `C`). | |
| 8 | + | |
| 9 | +That writes `.turbo-python/tools.toml` with the five commands a Python project runs before it commits, and opens it: | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[tool]] | |
| 13 | +name = "~F~ormat" | |
| 14 | +command = "uv run ruff format ." | |
| 15 | +output = "popup" | |
| 16 | + | |
| 17 | +[[tool]] | |
| 18 | +name = "~T~est" | |
| 19 | +command = "uv run pytest" | |
| 20 | +output = "popup" | |
| 21 | + | |
| 22 | +[[tool]] | |
| 23 | +name = "~R~un" | |
| 24 | +command = "uv run" | |
| 25 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | |
| 26 | +# be answered, and one that runs long has to be able to be interrupted. | |
| 27 | +output = "terminal" | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Each `[[tool]]` becomes one line of the **Python** menu, in the order they appear — unless it names a `menu` of its own, which the next-but-one section covers. The file is read every time the menu opens, so an edit takes effect immediately. | |
| 31 | + | |
| 32 | +## Run one | |
| 33 | + | |
| 34 | +`Alt-P`, then the letter between the tildes — `F` to format, `T` to test. | |
| 35 | + | |
| 36 | +A **popup** opens at once and fills in as the command runs. Its title carries the command and, once it has ended, how it went: | |
| 37 | + | |
| 38 | +``` | |
| 39 | +┌──────────── uv run ruff check . — exit 1 ────────────┐ | |
| 40 | +│ main.py:6:2: unreachable code │ | |
| 41 | +│ │ | |
| 42 | +│ [ Close ] │ | |
| 43 | +└───────────────────────────────────────────────┘ | |
| 44 | +``` | |
| 45 | + | |
| 46 | +| Key | Effect | | |
| 47 | +| --- | --- | | |
| 48 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Read through the output | | |
| 49 | +| `Escape` | Close it — and **stop the command** if it is still running | | |
| 50 | +| `Enter` | Close it | | |
| 51 | + | |
| 52 | +A command that succeeded silently shows `(no output)` rather than a blank box, so you can tell it from one that has not started. | |
| 53 | + | |
| 54 | +The popup follows the output as it arrives until you scroll back, and then leaves you where you are. | |
| 55 | + | |
| 56 | +## Choose where the output goes | |
| 57 | + | |
| 58 | +Set `output` on a tool: | |
| 59 | + | |
| 60 | +| `output` | What you get | | |
| 61 | +| --- | --- | | |
| 62 | +| `popup` | A dialog that fills in as it runs. The default. | | |
| 63 | +| `terminal` | A terminal window: colours, `Ctrl-C`, and the keyboard reaches the program | | |
| 64 | +| `editor` | An editing window once it has finished, to search with `Ctrl-F` | | |
| 65 | + | |
| 66 | +`Run` is `terminal` in the starter file, and it is the example of why the key exists: a popup cannot answer a program that reads from the keyboard, and cannot be interrupted with `Ctrl-C`. | |
| 67 | + | |
| 68 | +Reach for `editor` when the output is something to work through — a long `go test -v`, or a coverage report you want to search. | |
| 69 | + | |
| 70 | +## A long command holds the editor | |
| 71 | + | |
| 72 | +A popup is modal: while `go build` runs, you cannot type anywhere else. `Escape` closes it and stops the command. | |
| 73 | + | |
| 74 | +If that gets in the way for a particular command, give it `output = "terminal"` — the window is an ordinary one and you can carry on working beside it. That is what making the key configurable is for. | |
| 75 | + | |
| 76 | +## What happens to your open files | |
| 77 | + | |
| 78 | +`Format` rewrites files on disk — including the one you are looking at. When a command finishes, the editor **re-reads every open file that has no unsaved changes**, so the formatted version appears without you doing anything. The status bar says how many. | |
| 79 | + | |
| 80 | +A file with unsaved changes is **left alone**, and the status bar says so too: | |
| 81 | + | |
| 82 | +``` | |
| 83 | +Reloaded 2 files; 1 file with unsaved changes left alone | |
| 84 | +``` | |
| 85 | + | |
| 86 | +That is deliberate: your edit and the formatter genuinely disagree, and the editor is not the one that should decide which wins. Save first (`F2`) and run the command again, or keep editing and format later. | |
| 87 | + | |
| 88 | +## Add your own commands | |
| 89 | + | |
| 90 | +Edit `.turbo-python/tools.toml`. A command goes to `sh -c`, so one entry can be a whole sequence: | |
| 91 | + | |
| 92 | +```toml | |
| 93 | +[[tool]] | |
| 94 | +name = "~C~heck" | |
| 95 | +command = "uv run ruff format . && uv run ruff check . && uv run pytest" | |
| 96 | +output = "popup" | |
| 97 | + | |
| 98 | +[[tool]] | |
| 99 | +name = "~U~pgrade" | |
| 100 | +command = "uv lock --upgrade" | |
| 101 | +output = "popup" | |
| 102 | + | |
| 103 | +[[tool]] | |
| 104 | +name = "Cover~a~ge" | |
| 105 | +command = "uv run pytest --cov --cov-report=term-missing" | |
| 106 | +output = "editor" | |
| 107 | +``` | |
| 108 | + | |
| 109 | +Give each a hot key with tildes, and keep them distinct — the menu answers the first match it finds. | |
| 110 | + | |
| 111 | +## Put a tool in a menu of its own | |
| 112 | + | |
| 113 | +A tool that has nothing to do with Python does not belong in the Python menu. Give it a `menu`: | |
| 114 | + | |
| 115 | +```toml | |
| 116 | +[[tool]] | |
| 117 | +name = "~E~cho" | |
| 118 | +command = "echo TADA" | |
| 119 | +output = "terminal" | |
| 120 | +menu = "Tools" | |
| 121 | + | |
| 122 | +[[tool]] | |
| 123 | +name = "~U~p" | |
| 124 | +command = "docker compose up -d" | |
| 125 | +menu = "Docker" | |
| 126 | + | |
| 127 | +[[tool]] | |
| 128 | +name = "~D~own" | |
| 129 | +command = "docker compose down" | |
| 130 | +menu = "Docker" | |
| 131 | +``` | |
| 132 | + | |
| 133 | +That gives you a **Tools** menu and a **Docker** menu on the bar, between Python and Help, in the order the names first appear in the file. Docker holds both its tools. Nothing needs restarting: save the file and the bar follows. | |
| 134 | + | |
| 135 | +The name is yours to choose — there is no list to pick from. Leave `menu` out and the tool stays in Python, which is where all five starter commands are. | |
| 136 | + | |
| 137 | +### The hot key is chosen for you | |
| 138 | + | |
| 139 | +You cannot know, when writing the file, which letters the editor's own menus have taken. So it works it out: the first letter of the name that nothing else claims gets the tildes. | |
| 140 | + | |
| 141 | +`Tools` gets `Alt-T`, because `T` is free. A menu called `Format` would get `Alt-A`, because `F` is File's, `o` is Options' and `r` is Run's. | |
| 142 | + | |
| 143 | +Write the tildes yourself — `menu = "Doc~k~er"` — and a free letter is kept. A taken one is not: the bar answers the *first* menu matching a key, so honouring your choice would make one of the two menus unreachable. It picks another letter and says nothing. | |
| 144 | + | |
| 145 | +## Variants | |
| 146 | + | |
| 147 | +- **You want `black` and `flake8` instead of `ruff`.** Change the `Format` and `Lint` commands. `ruff` is the default because it is one tool for both jobs and `uv run` fetches it on demand; anything else is equally one line. | |
| 148 | +- **You started the editor from a subdirectory.** Commands run there, so `ruff check .` covers only that subtree — and `uv` looks for the `pyproject.toml` from there too. Start from the project root. | |
| 149 | +- **The file has a mistake in it.** The menu shows a greyed-out `Cannot read tools` where the commands would be, and **Create tools file** is still there. | |
| 150 | +- **A command is not installed.** The popup shows `command not found` and `— exit 127`, which is what a shell would have said. | |
| 151 | +- **You want a menu named after one that exists.** `menu = "File"` gives you a second File menu, further along the bar, with a different hot key. Nothing stops you; nothing recommends it either. | |
| 152 | +- **Your menu has no hot key.** Every letter in its name was already taken. `F10` and the arrow keys reach it, and so does the mouse. Rename it to something with a free letter. | |
| 153 | +- **You misspelt `output`'s value.** The whole file is refused and the menu says `Cannot read tools`, naming the tool and listing what it could have been. A silent fallback would have sent the output somewhere you did not ask for. | |
| 154 | + | |
| 155 | +## Ask for a value when the command runs | |
| 156 | + | |
| 157 | +Some commands need something typed each time: a module path, a project name, a test to filter on. Put a `{{label}}` where the value goes: | |
| 158 | + | |
| 159 | +```toml | |
| 160 | +[[tool]] | |
| 161 | +name = "~I~nit module" | |
| 162 | +command = "uv init --app {{project name}}" | |
| 163 | +output = "popup" | |
| 164 | +``` | |
| 165 | + | |
| 166 | +Choosing it now opens a box titled **Init module** with one field, labelled `module path`. Type the value and press Enter; the command runs with it. Escape, and nothing runs. | |
| 167 | + | |
| 168 | +The value is quoted, so a path with a space in it stays one argument. | |
| 169 | + | |
| 170 | +### Several values at once | |
| 171 | + | |
| 172 | +One field each, in the order they appear: | |
| 173 | + | |
| 174 | +```toml | |
| 175 | +[[tool]] | |
| 176 | +name = "~C~opy" | |
| 177 | +command = "cp {{from}} {{to}}" | |
| 178 | +``` | |
| 179 | + | |
| 180 | +**Tab** moves between the fields, **Enter** runs it. | |
| 181 | + | |
| 182 | +### One field standing for several arguments | |
| 183 | + | |
| 184 | +Quoting is wrong when you mean "put these flags on the end". Add `...` inside the braces and the value goes in verbatim: | |
| 185 | + | |
| 186 | +```toml | |
| 187 | +[[tool]] | |
| 188 | +name = "Test ~o~ne" | |
| 189 | +command = "uv run pytest {{extra flags...}}" | |
| 190 | +``` | |
| 191 | + | |
| 192 | +Type `--release parse` and all of it reaches the command as separate arguments. | |
| 193 | + | |
| 194 | +### The same value twice | |
| 195 | + | |
| 196 | +Write the label twice; you are asked once: | |
| 197 | + | |
| 198 | +```toml | |
| 199 | +[[tool]] | |
| 200 | +name = "~N~ew directory" | |
| 201 | +command = "mkdir {{name}} && cd {{name}}" | |
| 202 | +``` | |
| 203 | + | |
| 204 | +### Variants | |
| 205 | + | |
| 206 | +- **The value is the same most times.** Run it once and the box remembers what you typed, for the rest of the session. It is not written to disk. | |
| 207 | +- **Your command has braces in it already.** `awk '{print $1}'` and `find . -exec rm {} +` are left alone: only double braces ask for anything. | |
| 208 | +- **The command asks for more values than fit on screen.** The editor says so rather than opening a box whose OK button is below the bottom of the terminal. Make the terminal taller, or split the command into two tools. | |
| 209 | + | |
| 210 | +## See also | |
| 211 | + | |
| 212 | +- Every key of the file and every rule: [Python tools reference](../reference/python-tools.md) | |
| 213 | +- Why each command gets a terminal window, and why an unmodified file reloads: [Python tools](../explanation/python-tools.md) | |
| 214 | +- The windows the commands run in: [Terminal windows](../reference/terminal.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,214 @@ | |||
| 1 | +# How to run uv commands from the editor | ||
| 2 | + | ||
| 3 | +This guide shows how to format, lint, build, test and run your project without leaving Turbo Python. It assumes the editor is installed and you have a Python project. | ||
| 4 | + | ||
| 5 | +## Get a starter file | ||
| 6 | + | ||
| 7 | +Start the editor **from the project's own directory**, then choose **Python ▸ Create tools file** (`Alt-P`, then `C`). | ||
| 8 | + | ||
| 9 | +That writes `.turbo-python/tools.toml` with the five commands a Python project runs before it commits, and opens it: | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[tool]] | ||
| 13 | +name = "~F~ormat" | ||
| 14 | +command = "uv run ruff format ." | ||
| 15 | +output = "popup" | ||
| 16 | + | ||
| 17 | +[[tool]] | ||
| 18 | +name = "~T~est" | ||
| 19 | +command = "uv run pytest" | ||
| 20 | +output = "popup" | ||
| 21 | + | ||
| 22 | +[[tool]] | ||
| 23 | +name = "~R~un" | ||
| 24 | +command = "uv run" | ||
| 25 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | ||
| 26 | +# be answered, and one that runs long has to be able to be interrupted. | ||
| 27 | +output = "terminal" | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Each `[[tool]]` becomes one line of the **Python** menu, in the order they appear — unless it names a `menu` of its own, which the next-but-one section covers. The file is read every time the menu opens, so an edit takes effect immediately. | ||
| 31 | + | ||
| 32 | +## Run one | ||
| 33 | + | ||
| 34 | +`Alt-P`, then the letter between the tildes — `F` to format, `T` to test. | ||
| 35 | + | ||
| 36 | +A **popup** opens at once and fills in as the command runs. Its title carries the command and, once it has ended, how it went: | ||
| 37 | + | ||
| 38 | +``` | ||
| 39 | +┌──────────── uv run ruff check . — exit 1 ────────────┐ | ||
| 40 | +│ main.py:6:2: unreachable code │ | ||
| 41 | +│ │ | ||
| 42 | +│ [ Close ] │ | ||
| 43 | +└───────────────────────────────────────────────┘ | ||
| 44 | +``` | ||
| 45 | + | ||
| 46 | +| Key | Effect | | ||
| 47 | +| --- | --- | | ||
| 48 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Read through the output | | ||
| 49 | +| `Escape` | Close it — and **stop the command** if it is still running | | ||
| 50 | +| `Enter` | Close it | | ||
| 51 | + | ||
| 52 | +A command that succeeded silently shows `(no output)` rather than a blank box, so you can tell it from one that has not started. | ||
| 53 | + | ||
| 54 | +The popup follows the output as it arrives until you scroll back, and then leaves you where you are. | ||
| 55 | + | ||
| 56 | +## Choose where the output goes | ||
| 57 | + | ||
| 58 | +Set `output` on a tool: | ||
| 59 | + | ||
| 60 | +| `output` | What you get | | ||
| 61 | +| --- | --- | | ||
| 62 | +| `popup` | A dialog that fills in as it runs. The default. | | ||
| 63 | +| `terminal` | A terminal window: colours, `Ctrl-C`, and the keyboard reaches the program | | ||
| 64 | +| `editor` | An editing window once it has finished, to search with `Ctrl-F` | | ||
| 65 | + | ||
| 66 | +`Run` is `terminal` in the starter file, and it is the example of why the key exists: a popup cannot answer a program that reads from the keyboard, and cannot be interrupted with `Ctrl-C`. | ||
| 67 | + | ||
| 68 | +Reach for `editor` when the output is something to work through — a long `go test -v`, or a coverage report you want to search. | ||
| 69 | + | ||
| 70 | +## A long command holds the editor | ||
| 71 | + | ||
| 72 | +A popup is modal: while `go build` runs, you cannot type anywhere else. `Escape` closes it and stops the command. | ||
| 73 | + | ||
| 74 | +If that gets in the way for a particular command, give it `output = "terminal"` — the window is an ordinary one and you can carry on working beside it. That is what making the key configurable is for. | ||
| 75 | + | ||
| 76 | +## What happens to your open files | ||
| 77 | + | ||
| 78 | +`Format` rewrites files on disk — including the one you are looking at. When a command finishes, the editor **re-reads every open file that has no unsaved changes**, so the formatted version appears without you doing anything. The status bar says how many. | ||
| 79 | + | ||
| 80 | +A file with unsaved changes is **left alone**, and the status bar says so too: | ||
| 81 | + | ||
| 82 | +``` | ||
| 83 | +Reloaded 2 files; 1 file with unsaved changes left alone | ||
| 84 | +``` | ||
| 85 | + | ||
| 86 | +That is deliberate: your edit and the formatter genuinely disagree, and the editor is not the one that should decide which wins. Save first (`F2`) and run the command again, or keep editing and format later. | ||
| 87 | + | ||
| 88 | +## Add your own commands | ||
| 89 | + | ||
| 90 | +Edit `.turbo-python/tools.toml`. A command goes to `sh -c`, so one entry can be a whole sequence: | ||
| 91 | + | ||
| 92 | +```toml | ||
| 93 | +[[tool]] | ||
| 94 | +name = "~C~heck" | ||
| 95 | +command = "uv run ruff format . && uv run ruff check . && uv run pytest" | ||
| 96 | +output = "popup" | ||
| 97 | + | ||
| 98 | +[[tool]] | ||
| 99 | +name = "~U~pgrade" | ||
| 100 | +command = "uv lock --upgrade" | ||
| 101 | +output = "popup" | ||
| 102 | + | ||
| 103 | +[[tool]] | ||
| 104 | +name = "Cover~a~ge" | ||
| 105 | +command = "uv run pytest --cov --cov-report=term-missing" | ||
| 106 | +output = "editor" | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +Give each a hot key with tildes, and keep them distinct — the menu answers the first match it finds. | ||
| 110 | + | ||
| 111 | +## Put a tool in a menu of its own | ||
| 112 | + | ||
| 113 | +A tool that has nothing to do with Python does not belong in the Python menu. Give it a `menu`: | ||
| 114 | + | ||
| 115 | +```toml | ||
| 116 | +[[tool]] | ||
| 117 | +name = "~E~cho" | ||
| 118 | +command = "echo TADA" | ||
| 119 | +output = "terminal" | ||
| 120 | +menu = "Tools" | ||
| 121 | + | ||
| 122 | +[[tool]] | ||
| 123 | +name = "~U~p" | ||
| 124 | +command = "docker compose up -d" | ||
| 125 | +menu = "Docker" | ||
| 126 | + | ||
| 127 | +[[tool]] | ||
| 128 | +name = "~D~own" | ||
| 129 | +command = "docker compose down" | ||
| 130 | +menu = "Docker" | ||
| 131 | +``` | ||
| 132 | + | ||
| 133 | +That gives you a **Tools** menu and a **Docker** menu on the bar, between Python and Help, in the order the names first appear in the file. Docker holds both its tools. Nothing needs restarting: save the file and the bar follows. | ||
| 134 | + | ||
| 135 | +The name is yours to choose — there is no list to pick from. Leave `menu` out and the tool stays in Python, which is where all five starter commands are. | ||
| 136 | + | ||
| 137 | +### The hot key is chosen for you | ||
| 138 | + | ||
| 139 | +You cannot know, when writing the file, which letters the editor's own menus have taken. So it works it out: the first letter of the name that nothing else claims gets the tildes. | ||
| 140 | + | ||
| 141 | +`Tools` gets `Alt-T`, because `T` is free. A menu called `Format` would get `Alt-A`, because `F` is File's, `o` is Options' and `r` is Run's. | ||
| 142 | + | ||
| 143 | +Write the tildes yourself — `menu = "Doc~k~er"` — and a free letter is kept. A taken one is not: the bar answers the *first* menu matching a key, so honouring your choice would make one of the two menus unreachable. It picks another letter and says nothing. | ||
| 144 | + | ||
| 145 | +## Variants | ||
| 146 | + | ||
| 147 | +- **You want `black` and `flake8` instead of `ruff`.** Change the `Format` and `Lint` commands. `ruff` is the default because it is one tool for both jobs and `uv run` fetches it on demand; anything else is equally one line. | ||
| 148 | +- **You started the editor from a subdirectory.** Commands run there, so `ruff check .` covers only that subtree — and `uv` looks for the `pyproject.toml` from there too. Start from the project root. | ||
| 149 | +- **The file has a mistake in it.** The menu shows a greyed-out `Cannot read tools` where the commands would be, and **Create tools file** is still there. | ||
| 150 | +- **A command is not installed.** The popup shows `command not found` and `— exit 127`, which is what a shell would have said. | ||
| 151 | +- **You want a menu named after one that exists.** `menu = "File"` gives you a second File menu, further along the bar, with a different hot key. Nothing stops you; nothing recommends it either. | ||
| 152 | +- **Your menu has no hot key.** Every letter in its name was already taken. `F10` and the arrow keys reach it, and so does the mouse. Rename it to something with a free letter. | ||
| 153 | +- **You misspelt `output`'s value.** The whole file is refused and the menu says `Cannot read tools`, naming the tool and listing what it could have been. A silent fallback would have sent the output somewhere you did not ask for. | ||
| 154 | + | ||
| 155 | +## Ask for a value when the command runs | ||
| 156 | + | ||
| 157 | +Some commands need something typed each time: a module path, a project name, a test to filter on. Put a `{{label}}` where the value goes: | ||
| 158 | + | ||
| 159 | +```toml | ||
| 160 | +[[tool]] | ||
| 161 | +name = "~I~nit module" | ||
| 162 | +command = "uv init --app {{project name}}" | ||
| 163 | +output = "popup" | ||
| 164 | +``` | ||
| 165 | + | ||
| 166 | +Choosing it now opens a box titled **Init module** with one field, labelled `module path`. Type the value and press Enter; the command runs with it. Escape, and nothing runs. | ||
| 167 | + | ||
| 168 | +The value is quoted, so a path with a space in it stays one argument. | ||
| 169 | + | ||
| 170 | +### Several values at once | ||
| 171 | + | ||
| 172 | +One field each, in the order they appear: | ||
| 173 | + | ||
| 174 | +```toml | ||
| 175 | +[[tool]] | ||
| 176 | +name = "~C~opy" | ||
| 177 | +command = "cp {{from}} {{to}}" | ||
| 178 | +``` | ||
| 179 | + | ||
| 180 | +**Tab** moves between the fields, **Enter** runs it. | ||
| 181 | + | ||
| 182 | +### One field standing for several arguments | ||
| 183 | + | ||
| 184 | +Quoting is wrong when you mean "put these flags on the end". Add `...` inside the braces and the value goes in verbatim: | ||
| 185 | + | ||
| 186 | +```toml | ||
| 187 | +[[tool]] | ||
| 188 | +name = "Test ~o~ne" | ||
| 189 | +command = "uv run pytest {{extra flags...}}" | ||
| 190 | +``` | ||
| 191 | + | ||
| 192 | +Type `--release parse` and all of it reaches the command as separate arguments. | ||
| 193 | + | ||
| 194 | +### The same value twice | ||
| 195 | + | ||
| 196 | +Write the label twice; you are asked once: | ||
| 197 | + | ||
| 198 | +```toml | ||
| 199 | +[[tool]] | ||
| 200 | +name = "~N~ew directory" | ||
| 201 | +command = "mkdir {{name}} && cd {{name}}" | ||
| 202 | +``` | ||
| 203 | + | ||
| 204 | +### Variants | ||
| 205 | + | ||
| 206 | +- **The value is the same most times.** Run it once and the box remembers what you typed, for the rest of the session. It is not written to disk. | ||
| 207 | +- **Your command has braces in it already.** `awk '{print $1}'` and `find . -exec rm {} +` are left alone: only double braces ask for anything. | ||
| 208 | +- **The command asks for more values than fit on screen.** The editor says so rather than opening a box whose OK button is below the bottom of the terminal. Make the terminal taller, or split the command into two tools. | ||
| 209 | + | ||
| 210 | +## See also | ||
| 211 | + | ||
| 212 | +- Every key of the file and every rule: [Python tools reference](../reference/python-tools.md) | ||
| 213 | +- Why each command gets a terminal window, and why an unmodified file reloads: [Python tools](../explanation/python-tools.md) | ||
| 214 | +- The windows the commands run in: [Terminal windows](../reference/terminal.md) | ||
added
docs/en/how-to/talk-to-an-agent.md +177 -0 | new file mode 100644 | ||
| @@ -0,0 +1,177 @@ | ||
| 1 | +# How to talk to a coding agent from the editor | |
| 2 | + | |
| 3 | +This guide shows how to point Turbo Python at an agent that speaks the [Agent Client Protocol](https://agentclientprotocol.com), open a window onto it, and hold a conversation about the code you are editing. It assumes you already have Turbo Python running in a project. | |
| 4 | + | |
| 5 | +Turbo Python is an ACP **client**. It starts the agent as a child process and talks JSON-RPC to it over its standard input and output — the same arrangement Zed uses, so an agent that works there works here. | |
| 6 | + | |
| 7 | +## Tell the editor about an agent | |
| 8 | + | |
| 9 | +Agents are listed in `acp.toml`. Choose **Agent ▸ Create agents file** and the editor writes a starter one into `.turbo-python/acp.toml` and opens it. | |
| 10 | + | |
| 11 | +An agent is one `[[agent]]` block: | |
| 12 | + | |
| 13 | +```toml | |
| 14 | +[[agent]] | |
| 15 | +name = "Bob (llama.cpp)" | |
| 16 | +command = "docker" | |
| 17 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | |
| 18 | +env = { TELEMETRY_ENABLED = "false" } | |
| 19 | +``` | |
| 20 | + | |
| 21 | +`name` is what the Agent menu shows and what the window is called. `command` and `args` are how the agent is started. That is the whole of it — the file is read again every time you open a window, so you never restart the editor to try a change. | |
| 22 | + | |
| 23 | +List as many as you like. Each becomes its own line in the menu, and each window you open from it is a separate process with a conversation of its own. | |
| 24 | + | |
| 25 | +## Put the agent's own configuration beside it | |
| 26 | + | |
| 27 | +Most agents have a configuration file of their own, and `.turbo-python/` is a reasonable place to keep it so that it travels with the project. For `docker agent`, saving this as `.turbo-python/agent.yaml` is what the `args` above point at: | |
| 28 | + | |
| 29 | +```yaml | |
| 30 | +providers: | |
| 31 | + llamacpp: | |
| 32 | + api_type: openai_chatcompletions | |
| 33 | + base_url: http://localhost:8080/v1 | |
| 34 | + | |
| 35 | +models: | |
| 36 | + mellum2: | |
| 37 | + provider: llamacpp | |
| 38 | + model: JetBrains/Mellum2-12B-A2.5B-Instruct-GGUF-Q4_K_M:Q4_K_M | |
| 39 | + temperature: 0.7 | |
| 40 | + provider_opts: | |
| 41 | + context_size: 262144 | |
| 42 | + | |
| 43 | +agents: | |
| 44 | + root: | |
| 45 | + model: mellum2 | |
| 46 | + description: A helpful AI assistant running on a local llama.cpp server | |
| 47 | + instruction: | | |
| 48 | + You name is Bob 🤓, you are a knowledgeable code assistant. | |
| 49 | + Be helpful, accurate, and concise in your responses. | |
| 50 | + You have access to the local filesystem and shell: use these tools | |
| 51 | + toolsets: | |
| 52 | + - type: filesystem | |
| 53 | + - type: shell | |
| 54 | +``` | |
| 55 | + | |
| 56 | +## Open a window on it | |
| 57 | + | |
| 58 | +Press `Alt-A`, or choose **Agent** from the menu bar, and pick the agent by name. | |
| 59 | + | |
| 60 | +A window opens, split in two: the conversation above, and a box to type in below. The agent is started when the window opens and stopped when it closes. | |
| 61 | + | |
| 62 | +``` | |
| 63 | +┌ Bob (llama.cpp) ───────────────────────────────[■]┐ | |
| 64 | +│ ‣ You │ | |
| 65 | +│ What does buildMenus do? │ | |
| 66 | +│ │ | |
| 67 | +│ ‣ Shell ls -1 internal/ ✓ done │ | |
| 68 | +│ golang │ | |
| 69 | +│ │ | |
| 70 | +│ ‣ Bob │ | |
| 71 | +│ It assembles the menu bar. Here is the shape: │ | |
| 72 | +│ │ | |
| 73 | +│ ```python │ | |
| 74 | +│ func (a *App) buildMenus() *ui.MenuBar { │ | |
| 75 | +│ return ui.NewMenuBar(a.allMenus()...) │ | |
| 76 | +│ } │ | |
| 77 | +│ ``` │ | |
| 78 | +├───────────────────────────────────────────────────┤ | |
| 79 | +│ > _ │ | |
| 80 | +└───────────────────────────────────────────────────┘ | |
| 81 | +``` | |
| 82 | + | |
| 83 | +Code the agent sends inside a fenced block is coloured by the same scanners the editor uses for files, so a Python answer is coloured as Python and a shell answer as shell. A fence naming a language the editor does not colour is left plain rather than guessed at. | |
| 84 | + | |
| 85 | +## Hold the conversation | |
| 86 | + | |
| 87 | +| Key | Effect | | |
| 88 | +| --- | --- | | |
| 89 | +| `Enter` | Send what you have typed | | |
| 90 | +| `Alt-Enter` | Start a new line instead of sending | | |
| 91 | +| `Tab` | Move between the conversation and the input box | | |
| 92 | +| `PgUp` `PgDn` | Scroll the conversation a screenful at a time | | |
| 93 | +| `Esc` | Stop the turn in progress | | |
| 94 | +| `Ctrl-W` | Close the window, and stop the agent with it | | |
| 95 | + | |
| 96 | +While the agent is answering, its reply appears as it is written rather than all at once, and the rule between the two panes turns a spinner beside the word *thinking*. `Esc` interrupts it — the agent is told to stop, and what it had already said stays in the window. | |
| 97 | + | |
| 98 | +## Use the agent's own commands | |
| 99 | + | |
| 100 | +Some agents answer to commands — `/compact`, `/web`, `/plan` — and tell the editor which ones. Type `/` as the first character of the box and the list opens over the conversation: each command, what it does, and in angle brackets what it wants after its name. | |
| 101 | + | |
| 102 | +Type on to narrow it, `↑` `↓` to move, then `Tab` to complete. A command that takes something is completed with a space after it, ready for you to type the rest; press `Enter` when the line is what you mean. If nothing appears when you type `/`, the agent announced no commands — **Agent ▸ Agent status** says so — and `/` is only a character. | |
| 103 | + | |
| 104 | +## Point the agent at a file | |
| 105 | + | |
| 106 | +Type `@` anywhere in the box and the project's files appear. Type a few letters of the file's name to narrow the list, `Tab` to take the highlighted one: | |
| 107 | + | |
| 108 | +``` | |
| 109 | +> explain what @internal/scanner.go does | |
| 110 | +``` | |
| 111 | + | |
| 112 | +When you press `Enter`, the agent is given the **file**, not merely its name: its text when the agent accepts embedded context, a link to it otherwise. If the file is open in the editor with unsaved changes, it is your unsaved version that goes. The line stays in the conversation as you typed it. | |
| 113 | + | |
| 114 | +Several files in one prompt is several `@`. A word that begins with `@` but is not a file — an e-mail address — is left as text. | |
| 115 | + | |
| 116 | +## Take something out of the conversation | |
| 117 | + | |
| 118 | +Press `Tab` to put the cursor in the conversation. The rule changes to say what the keys now do. | |
| 119 | + | |
| 120 | +| Key | Effect | | |
| 121 | +| --- | --- | | |
| 122 | +| `↑` `↓` `PgUp` `PgDn` | Move the cursor through what was said | | |
| 123 | +| `Shift-↑` `Shift-↓` | Select whole lines | | |
| 124 | +| Drag with the mouse | The same, by hand | | |
| 125 | +| `Ctrl-C` | Copy | | |
| 126 | +| `Esc` | Drop the selection | | |
| 127 | +| `Tab` | Back to the box | | |
| 128 | + | |
| 129 | +**With nothing selected, `Ctrl-C` copies the block the cursor is on** — one fenced code block, one paragraph, one tool's output — without the speaker's label above it and without the sentence after it. That is almost always what you wanted, and it saves selecting it by hand. | |
| 130 | + | |
| 131 | +What is copied goes to **two** clipboards: this editor's, so `Shift-Ins` pastes it into a file you have open, and your system's, so `Ctrl-V` pastes it anywhere else. The indentation the conversation is drawn with is taken off, so pasted code lands flush against the margin. | |
| 132 | + | |
| 133 | +The system half travels through your terminal (an escape sequence called OSC 52). Most terminals do it; a few refuse it for security, and some need it turned on. If `Ctrl-V` elsewhere gives you nothing, that is where to look — the editor's own clipboard has the text either way. | |
| 134 | + | |
| 135 | +## Answer the agent when it asks permission | |
| 136 | + | |
| 137 | +An agent with a shell or a filesystem toolset asks before it uses one. A dialog names the tool and the exact command, and offers the choices the agent itself proposed — normally *Allow this action*, *Allow and remember my choice*, and *Skip this action*. | |
| 138 | + | |
| 139 | +``` | |
| 140 | +┌───────────── Bob (llama.cpp) wants to run ─────────────┐ | |
| 141 | +│ │ | |
| 142 | +│ Shell │ | |
| 143 | +│ ls -1 │ | |
| 144 | +│ │ | |
| 145 | +│ [ Allow ] [ Allow always ] [ Skip ] │ | |
| 146 | +└────────────────────────────────────────────────────────┘ | |
| 147 | +``` | |
| 148 | + | |
| 149 | +*Allow always* is remembered by the agent, not by the editor, so what it covers and how long it lasts are the agent's business. Escape is the same answer as *Skip*. | |
| 150 | + | |
| 151 | +Nothing runs before you answer. An agent waiting on a permission dialog is simply blocked, which is the point. | |
| 152 | + | |
| 153 | +## Let the agent see what you have not saved yet | |
| 154 | + | |
| 155 | +The editor offers the agent its own filesystem: when the agent reads a file you have open with unsaved changes, it is given **the text in the buffer**, not the older text on disk. That is usually what you want — you are asking about the edit you just made. | |
| 156 | + | |
| 157 | +When the agent writes a file, the change lands in the buffer and the window is marked modified, so you can read it, undo it with `Ctrl-Z`, or save it with `F2`. A file you do not have open is read from and written to disk directly. | |
| 158 | + | |
| 159 | +## Run several agents at once | |
| 160 | + | |
| 161 | +Each window is its own process and its own conversation. Opening the same agent twice gives two independent sessions, and opening two different agents lets you put a fast local model and a slower careful one side by side — **Window ▸ Tile** arranges them. | |
| 162 | + | |
| 163 | +Leaving the editor stops every agent. | |
| 164 | + | |
| 165 | +## Variants | |
| 166 | + | |
| 167 | +- **You want the agent to run somewhere other than the project root.** Add `cwd = "backend"` to its block. The path is relative to the project, and is both where the process starts and what the agent is told the working directory is. | |
| 168 | +- **The agent needs a credential.** Put it in `env`, or rely on it being in the environment you started the editor from — the agent inherits it. | |
| 169 | +- **The agent's commands do not appear when you type `/`.** Open **Agent ▸ Agent status** with the window in front. If it lists no commands, the agent announced none — or announced them in a shape this editor could not read, in which case the dialog names the update and the decoding error. To see exactly what went over the wire, start the editor with `TURBO_ACP_TRACE=/tmp/acp.log` and read the file: `->` is what the editor sent, `<-` what the agent answered. | |
| 170 | +- **The agent will not start.** **Agent ▸ Agent status** lists what was read from `acp.toml`, what each agent's command line came out as, and the error from anything that failed to start. Whatever the agent writes to its standard error is shown there too, which is where a misconfigured model endpoint reports itself. | |
| 171 | +- **You keep the same agent in every project.** Put the `[[agent]]` block in `~/.config/turbo-python/acp.toml` instead. A project's own file is read afterwards and an agent with the same `name` in it replaces yours. | |
| 172 | + | |
| 173 | +## See also | |
| 174 | + | |
| 175 | +- Every key of the file, and exactly how much of the protocol is implemented: [Agents and ACP reference](../reference/acp.md) | |
| 176 | +- Why an agent is a window rather than a panel, and why permissions are modal: [Agent windows](../explanation/agent-windows.md) | |
| 177 | +- The protocol itself: [agentclientprotocol.com](https://agentclientprotocol.com) | |
| new file mode 100644 | |||
| @@ -0,0 +1,177 @@ | |||
| 1 | +# How to talk to a coding agent from the editor | ||
| 2 | + | ||
| 3 | +This guide shows how to point Turbo Python at an agent that speaks the [Agent Client Protocol](https://agentclientprotocol.com), open a window onto it, and hold a conversation about the code you are editing. It assumes you already have Turbo Python running in a project. | ||
| 4 | + | ||
| 5 | +Turbo Python is an ACP **client**. It starts the agent as a child process and talks JSON-RPC to it over its standard input and output — the same arrangement Zed uses, so an agent that works there works here. | ||
| 6 | + | ||
| 7 | +## Tell the editor about an agent | ||
| 8 | + | ||
| 9 | +Agents are listed in `acp.toml`. Choose **Agent ▸ Create agents file** and the editor writes a starter one into `.turbo-python/acp.toml` and opens it. | ||
| 10 | + | ||
| 11 | +An agent is one `[[agent]]` block: | ||
| 12 | + | ||
| 13 | +```toml | ||
| 14 | +[[agent]] | ||
| 15 | +name = "Bob (llama.cpp)" | ||
| 16 | +command = "docker" | ||
| 17 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | ||
| 18 | +env = { TELEMETRY_ENABLED = "false" } | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +`name` is what the Agent menu shows and what the window is called. `command` and `args` are how the agent is started. That is the whole of it — the file is read again every time you open a window, so you never restart the editor to try a change. | ||
| 22 | + | ||
| 23 | +List as many as you like. Each becomes its own line in the menu, and each window you open from it is a separate process with a conversation of its own. | ||
| 24 | + | ||
| 25 | +## Put the agent's own configuration beside it | ||
| 26 | + | ||
| 27 | +Most agents have a configuration file of their own, and `.turbo-python/` is a reasonable place to keep it so that it travels with the project. For `docker agent`, saving this as `.turbo-python/agent.yaml` is what the `args` above point at: | ||
| 28 | + | ||
| 29 | +```yaml | ||
| 30 | +providers: | ||
| 31 | + llamacpp: | ||
| 32 | + api_type: openai_chatcompletions | ||
| 33 | + base_url: http://localhost:8080/v1 | ||
| 34 | + | ||
| 35 | +models: | ||
| 36 | + mellum2: | ||
| 37 | + provider: llamacpp | ||
| 38 | + model: JetBrains/Mellum2-12B-A2.5B-Instruct-GGUF-Q4_K_M:Q4_K_M | ||
| 39 | + temperature: 0.7 | ||
| 40 | + provider_opts: | ||
| 41 | + context_size: 262144 | ||
| 42 | + | ||
| 43 | +agents: | ||
| 44 | + root: | ||
| 45 | + model: mellum2 | ||
| 46 | + description: A helpful AI assistant running on a local llama.cpp server | ||
| 47 | + instruction: | | ||
| 48 | + You name is Bob 🤓, you are a knowledgeable code assistant. | ||
| 49 | + Be helpful, accurate, and concise in your responses. | ||
| 50 | + You have access to the local filesystem and shell: use these tools | ||
| 51 | + toolsets: | ||
| 52 | + - type: filesystem | ||
| 53 | + - type: shell | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +## Open a window on it | ||
| 57 | + | ||
| 58 | +Press `Alt-A`, or choose **Agent** from the menu bar, and pick the agent by name. | ||
| 59 | + | ||
| 60 | +A window opens, split in two: the conversation above, and a box to type in below. The agent is started when the window opens and stopped when it closes. | ||
| 61 | + | ||
| 62 | +``` | ||
| 63 | +┌ Bob (llama.cpp) ───────────────────────────────[■]┐ | ||
| 64 | +│ ‣ You │ | ||
| 65 | +│ What does buildMenus do? │ | ||
| 66 | +│ │ | ||
| 67 | +│ ‣ Shell ls -1 internal/ ✓ done │ | ||
| 68 | +│ golang │ | ||
| 69 | +│ │ | ||
| 70 | +│ ‣ Bob │ | ||
| 71 | +│ It assembles the menu bar. Here is the shape: │ | ||
| 72 | +│ │ | ||
| 73 | +│ ```python │ | ||
| 74 | +│ func (a *App) buildMenus() *ui.MenuBar { │ | ||
| 75 | +│ return ui.NewMenuBar(a.allMenus()...) │ | ||
| 76 | +│ } │ | ||
| 77 | +│ ``` │ | ||
| 78 | +├───────────────────────────────────────────────────┤ | ||
| 79 | +│ > _ │ | ||
| 80 | +└───────────────────────────────────────────────────┘ | ||
| 81 | +``` | ||
| 82 | + | ||
| 83 | +Code the agent sends inside a fenced block is coloured by the same scanners the editor uses for files, so a Python answer is coloured as Python and a shell answer as shell. A fence naming a language the editor does not colour is left plain rather than guessed at. | ||
| 84 | + | ||
| 85 | +## Hold the conversation | ||
| 86 | + | ||
| 87 | +| Key | Effect | | ||
| 88 | +| --- | --- | | ||
| 89 | +| `Enter` | Send what you have typed | | ||
| 90 | +| `Alt-Enter` | Start a new line instead of sending | | ||
| 91 | +| `Tab` | Move between the conversation and the input box | | ||
| 92 | +| `PgUp` `PgDn` | Scroll the conversation a screenful at a time | | ||
| 93 | +| `Esc` | Stop the turn in progress | | ||
| 94 | +| `Ctrl-W` | Close the window, and stop the agent with it | | ||
| 95 | + | ||
| 96 | +While the agent is answering, its reply appears as it is written rather than all at once, and the rule between the two panes turns a spinner beside the word *thinking*. `Esc` interrupts it — the agent is told to stop, and what it had already said stays in the window. | ||
| 97 | + | ||
| 98 | +## Use the agent's own commands | ||
| 99 | + | ||
| 100 | +Some agents answer to commands — `/compact`, `/web`, `/plan` — and tell the editor which ones. Type `/` as the first character of the box and the list opens over the conversation: each command, what it does, and in angle brackets what it wants after its name. | ||
| 101 | + | ||
| 102 | +Type on to narrow it, `↑` `↓` to move, then `Tab` to complete. A command that takes something is completed with a space after it, ready for you to type the rest; press `Enter` when the line is what you mean. If nothing appears when you type `/`, the agent announced no commands — **Agent ▸ Agent status** says so — and `/` is only a character. | ||
| 103 | + | ||
| 104 | +## Point the agent at a file | ||
| 105 | + | ||
| 106 | +Type `@` anywhere in the box and the project's files appear. Type a few letters of the file's name to narrow the list, `Tab` to take the highlighted one: | ||
| 107 | + | ||
| 108 | +``` | ||
| 109 | +> explain what @internal/scanner.go does | ||
| 110 | +``` | ||
| 111 | + | ||
| 112 | +When you press `Enter`, the agent is given the **file**, not merely its name: its text when the agent accepts embedded context, a link to it otherwise. If the file is open in the editor with unsaved changes, it is your unsaved version that goes. The line stays in the conversation as you typed it. | ||
| 113 | + | ||
| 114 | +Several files in one prompt is several `@`. A word that begins with `@` but is not a file — an e-mail address — is left as text. | ||
| 115 | + | ||
| 116 | +## Take something out of the conversation | ||
| 117 | + | ||
| 118 | +Press `Tab` to put the cursor in the conversation. The rule changes to say what the keys now do. | ||
| 119 | + | ||
| 120 | +| Key | Effect | | ||
| 121 | +| --- | --- | | ||
| 122 | +| `↑` `↓` `PgUp` `PgDn` | Move the cursor through what was said | | ||
| 123 | +| `Shift-↑` `Shift-↓` | Select whole lines | | ||
| 124 | +| Drag with the mouse | The same, by hand | | ||
| 125 | +| `Ctrl-C` | Copy | | ||
| 126 | +| `Esc` | Drop the selection | | ||
| 127 | +| `Tab` | Back to the box | | ||
| 128 | + | ||
| 129 | +**With nothing selected, `Ctrl-C` copies the block the cursor is on** — one fenced code block, one paragraph, one tool's output — without the speaker's label above it and without the sentence after it. That is almost always what you wanted, and it saves selecting it by hand. | ||
| 130 | + | ||
| 131 | +What is copied goes to **two** clipboards: this editor's, so `Shift-Ins` pastes it into a file you have open, and your system's, so `Ctrl-V` pastes it anywhere else. The indentation the conversation is drawn with is taken off, so pasted code lands flush against the margin. | ||
| 132 | + | ||
| 133 | +The system half travels through your terminal (an escape sequence called OSC 52). Most terminals do it; a few refuse it for security, and some need it turned on. If `Ctrl-V` elsewhere gives you nothing, that is where to look — the editor's own clipboard has the text either way. | ||
| 134 | + | ||
| 135 | +## Answer the agent when it asks permission | ||
| 136 | + | ||
| 137 | +An agent with a shell or a filesystem toolset asks before it uses one. A dialog names the tool and the exact command, and offers the choices the agent itself proposed — normally *Allow this action*, *Allow and remember my choice*, and *Skip this action*. | ||
| 138 | + | ||
| 139 | +``` | ||
| 140 | +┌───────────── Bob (llama.cpp) wants to run ─────────────┐ | ||
| 141 | +│ │ | ||
| 142 | +│ Shell │ | ||
| 143 | +│ ls -1 │ | ||
| 144 | +│ │ | ||
| 145 | +│ [ Allow ] [ Allow always ] [ Skip ] │ | ||
| 146 | +└────────────────────────────────────────────────────────┘ | ||
| 147 | +``` | ||
| 148 | + | ||
| 149 | +*Allow always* is remembered by the agent, not by the editor, so what it covers and how long it lasts are the agent's business. Escape is the same answer as *Skip*. | ||
| 150 | + | ||
| 151 | +Nothing runs before you answer. An agent waiting on a permission dialog is simply blocked, which is the point. | ||
| 152 | + | ||
| 153 | +## Let the agent see what you have not saved yet | ||
| 154 | + | ||
| 155 | +The editor offers the agent its own filesystem: when the agent reads a file you have open with unsaved changes, it is given **the text in the buffer**, not the older text on disk. That is usually what you want — you are asking about the edit you just made. | ||
| 156 | + | ||
| 157 | +When the agent writes a file, the change lands in the buffer and the window is marked modified, so you can read it, undo it with `Ctrl-Z`, or save it with `F2`. A file you do not have open is read from and written to disk directly. | ||
| 158 | + | ||
| 159 | +## Run several agents at once | ||
| 160 | + | ||
| 161 | +Each window is its own process and its own conversation. Opening the same agent twice gives two independent sessions, and opening two different agents lets you put a fast local model and a slower careful one side by side — **Window ▸ Tile** arranges them. | ||
| 162 | + | ||
| 163 | +Leaving the editor stops every agent. | ||
| 164 | + | ||
| 165 | +## Variants | ||
| 166 | + | ||
| 167 | +- **You want the agent to run somewhere other than the project root.** Add `cwd = "backend"` to its block. The path is relative to the project, and is both where the process starts and what the agent is told the working directory is. | ||
| 168 | +- **The agent needs a credential.** Put it in `env`, or rely on it being in the environment you started the editor from — the agent inherits it. | ||
| 169 | +- **The agent's commands do not appear when you type `/`.** Open **Agent ▸ Agent status** with the window in front. If it lists no commands, the agent announced none — or announced them in a shape this editor could not read, in which case the dialog names the update and the decoding error. To see exactly what went over the wire, start the editor with `TURBO_ACP_TRACE=/tmp/acp.log` and read the file: `->` is what the editor sent, `<-` what the agent answered. | ||
| 170 | +- **The agent will not start.** **Agent ▸ Agent status** lists what was read from `acp.toml`, what each agent's command line came out as, and the error from anything that failed to start. Whatever the agent writes to its standard error is shown there too, which is where a misconfigured model endpoint reports itself. | ||
| 171 | +- **You keep the same agent in every project.** Put the `[[agent]]` block in `~/.config/turbo-python/acp.toml` instead. A project's own file is read afterwards and an agent with the same `name` in it replaces yours. | ||
| 172 | + | ||
| 173 | +## See also | ||
| 174 | + | ||
| 175 | +- Every key of the file, and exactly how much of the protocol is implemented: [Agents and ACP reference](../reference/acp.md) | ||
| 176 | +- Why an agent is a window rather than a panel, and why permissions are modal: [Agent windows](../explanation/agent-windows.md) | ||
| 177 | +- The protocol itself: [agentclientprotocol.com](https://agentclientprotocol.com) | ||
added
docs/en/how-to/use-a-terminal.md +61 -0 | new file mode 100644 | ||
| @@ -0,0 +1,61 @@ | ||
| 1 | +# How to run shell commands without leaving the editor | |
| 2 | + | |
| 3 | +This guide shows how to open a terminal window, build and test the code you are editing in it, and get back to the file. It assumes you already have Turbo Python running with a file open. | |
| 4 | + | |
| 5 | +## Open a terminal | |
| 6 | + | |
| 7 | +Press `F8`, or choose **Window ▸ New terminal**. | |
| 8 | + | |
| 9 | +A new window opens running your shell, in the directory of the file you were editing. That is normally the directory you want: `uv sync` and `git diff` both act on the package you are looking at. | |
| 10 | + | |
| 11 | +The window is called after the shell, and renames itself when a program inside it sets a title — `vim`, `htop` and `ssh` all do. | |
| 12 | + | |
| 13 | +## Run something | |
| 14 | + | |
| 15 | +Type into it as you would into any terminal. The shell gets nearly every key, including the ones the editor would otherwise use: `Ctrl-C` interrupts, `Ctrl-W` deletes a word, `Ctrl-R` searches the history. | |
| 16 | + | |
| 17 | +What the editor keeps is short, and deliberate — it is the way back out: | |
| 18 | + | |
| 19 | +| Key | Effect, even with a terminal in front | | |
| 20 | +| --- | --- | | |
| 21 | +| `F8` | Open another terminal | | |
| 22 | +| `F6` | Move to the next window | | |
| 23 | +| `F10` | Open the menu bar | | |
| 24 | +| `F2` `F3` `F4` | Save, Open, New | | |
| 25 | +| `Alt-1` … `Alt-9` | Bring that window forward | | |
| 26 | +| `Alt-X` | Leave the editor | | |
| 27 | + | |
| 28 | +## Read back through what scrolled off | |
| 29 | + | |
| 30 | +`Shift-PgUp` and `Shift-PgDn` walk the history a screenful at a time; the mouse wheel moves three lines. Two thousand lines are kept. | |
| 31 | + | |
| 32 | +Typing anything brings you straight back to the live screen, so you never have to scroll back down before running the next command. | |
| 33 | + | |
| 34 | +## Work with the file and the shell side by side | |
| 35 | + | |
| 36 | +A terminal is an ordinary window, so the window commands all apply to it: | |
| 37 | + | |
| 38 | +- **Window ▸ Tile** puts the file and the terminal side by side. | |
| 39 | +- **Window ▸ Maximise**, or the `[■]` box at the right of its title bar, gives the terminal the whole desktop while a build runs. The box then reads `[▬]`, and pressing it puts the window back. | |
| 40 | +- Drag its bottom-right corner to resize it — the shell is told its new size, so `less` and `vim` reflow. | |
| 41 | + | |
| 42 | +## Close it | |
| 43 | + | |
| 44 | +`Ctrl-W` is the shell's, not the editor's, so closing a terminal is done another way: | |
| 45 | + | |
| 46 | +- **File ▸ Close**, or | |
| 47 | +- click the `[x]` box in its top-left corner. | |
| 48 | + | |
| 49 | +Either ends the shell running in it. Nothing is asked first: a terminal holds a running process, not unsaved work, and closing the window is how you say you have finished with it. Leaving the editor closes every terminal at once. | |
| 50 | + | |
| 51 | +## Variants | |
| 52 | + | |
| 53 | +- **You want a different shell.** The shell is taken from `$SHELL`, falling back to `/bin/sh`; on Windows from `%COMSPEC%`, falling back to `cmd.exe`. Start the editor with `SHELL=/bin/zsh turbo-python` to change it for that run. | |
| 54 | +- **No file is open.** The terminal starts in the directory the editor was started from. | |
| 55 | +- **You are on Windows.** Terminal windows run in a pseudo-console (ConPTY), which needs Windows 10 version 1809 or later, and the shell is `%COMSPEC%` — cmd.exe. This path has been built and vetted but not yet run by the authors, who work on Linux and macOS. The first time you use it, try the five things it has to get right — `F8`, type `dir`, resize the window, run a menu command that says `output = "terminal"`, and interrupt a long one with `Ctrl-C` — and report whatever did not behave. | |
| 56 | + | |
| 57 | +## See also | |
| 58 | + | |
| 59 | +- Everything the terminal implements, exactly: [Terminal windows reference](../reference/terminal.md) | |
| 60 | +- Why it runs a real shell rather than capturing command output: [Terminal windows](../explanation/terminal-windows.md) | |
| 61 | +- The colours it uses: [Theme file format](../reference/themes.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | +# How to run shell commands without leaving the editor | ||
| 2 | + | ||
| 3 | +This guide shows how to open a terminal window, build and test the code you are editing in it, and get back to the file. It assumes you already have Turbo Python running with a file open. | ||
| 4 | + | ||
| 5 | +## Open a terminal | ||
| 6 | + | ||
| 7 | +Press `F8`, or choose **Window ▸ New terminal**. | ||
| 8 | + | ||
| 9 | +A new window opens running your shell, in the directory of the file you were editing. That is normally the directory you want: `uv sync` and `git diff` both act on the package you are looking at. | ||
| 10 | + | ||
| 11 | +The window is called after the shell, and renames itself when a program inside it sets a title — `vim`, `htop` and `ssh` all do. | ||
| 12 | + | ||
| 13 | +## Run something | ||
| 14 | + | ||
| 15 | +Type into it as you would into any terminal. The shell gets nearly every key, including the ones the editor would otherwise use: `Ctrl-C` interrupts, `Ctrl-W` deletes a word, `Ctrl-R` searches the history. | ||
| 16 | + | ||
| 17 | +What the editor keeps is short, and deliberate — it is the way back out: | ||
| 18 | + | ||
| 19 | +| Key | Effect, even with a terminal in front | | ||
| 20 | +| --- | --- | | ||
| 21 | +| `F8` | Open another terminal | | ||
| 22 | +| `F6` | Move to the next window | | ||
| 23 | +| `F10` | Open the menu bar | | ||
| 24 | +| `F2` `F3` `F4` | Save, Open, New | | ||
| 25 | +| `Alt-1` … `Alt-9` | Bring that window forward | | ||
| 26 | +| `Alt-X` | Leave the editor | | ||
| 27 | + | ||
| 28 | +## Read back through what scrolled off | ||
| 29 | + | ||
| 30 | +`Shift-PgUp` and `Shift-PgDn` walk the history a screenful at a time; the mouse wheel moves three lines. Two thousand lines are kept. | ||
| 31 | + | ||
| 32 | +Typing anything brings you straight back to the live screen, so you never have to scroll back down before running the next command. | ||
| 33 | + | ||
| 34 | +## Work with the file and the shell side by side | ||
| 35 | + | ||
| 36 | +A terminal is an ordinary window, so the window commands all apply to it: | ||
| 37 | + | ||
| 38 | +- **Window ▸ Tile** puts the file and the terminal side by side. | ||
| 39 | +- **Window ▸ Maximise**, or the `[■]` box at the right of its title bar, gives the terminal the whole desktop while a build runs. The box then reads `[▬]`, and pressing it puts the window back. | ||
| 40 | +- Drag its bottom-right corner to resize it — the shell is told its new size, so `less` and `vim` reflow. | ||
| 41 | + | ||
| 42 | +## Close it | ||
| 43 | + | ||
| 44 | +`Ctrl-W` is the shell's, not the editor's, so closing a terminal is done another way: | ||
| 45 | + | ||
| 46 | +- **File ▸ Close**, or | ||
| 47 | +- click the `[x]` box in its top-left corner. | ||
| 48 | + | ||
| 49 | +Either ends the shell running in it. Nothing is asked first: a terminal holds a running process, not unsaved work, and closing the window is how you say you have finished with it. Leaving the editor closes every terminal at once. | ||
| 50 | + | ||
| 51 | +## Variants | ||
| 52 | + | ||
| 53 | +- **You want a different shell.** The shell is taken from `$SHELL`, falling back to `/bin/sh`; on Windows from `%COMSPEC%`, falling back to `cmd.exe`. Start the editor with `SHELL=/bin/zsh turbo-python` to change it for that run. | ||
| 54 | +- **No file is open.** The terminal starts in the directory the editor was started from. | ||
| 55 | +- **You are on Windows.** Terminal windows run in a pseudo-console (ConPTY), which needs Windows 10 version 1809 or later, and the shell is `%COMSPEC%` — cmd.exe. This path has been built and vetted but not yet run by the authors, who work on Linux and macOS. The first time you use it, try the five things it has to get right — `F8`, type `dir`, resize the window, run a menu command that says `output = "terminal"`, and interrupt a long one with `Ctrl-C` — and report whatever did not behave. | ||
| 56 | + | ||
| 57 | +## See also | ||
| 58 | + | ||
| 59 | +- Everything the terminal implements, exactly: [Terminal windows reference](../reference/terminal.md) | ||
| 60 | +- Why it runs a real shell rather than capturing command output: [Terminal windows](../explanation/terminal-windows.md) | ||
| 61 | +- The colours it uses: [Theme file format](../reference/themes.md) | ||
added
docs/en/how-to/use-snippets.md +93 -0 | new file mode 100644 | ||
| @@ -0,0 +1,93 @@ | ||
| 1 | +# How to insert snippets from a menu | |
| 2 | + | |
| 3 | +This guide shows how to set up reusable pieces of text and put them into a file at the cursor. It assumes Turbo Python is already installed. | |
| 4 | + | |
| 5 | +## Get a starter file | |
| 6 | + | |
| 7 | +Start the editor **from the project's own directory**, then choose **Snippets ▸ Create snippets file** (`Alt-N`, then `C`). | |
| 8 | + | |
| 9 | +That writes `.turbo-python/snippets.toml`, filled in with a few worked examples, and opens it — coloured, because Turbo Python colours TOML: | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[snippet]] | |
| 13 | +name = "if err != nil" | |
| 14 | +group = "Python" | |
| 15 | +languages = ["python"] | |
| 16 | +body = """ | |
| 17 | +if err != nil { | |
| 18 | + return err | |
| 19 | +}""" | |
| 20 | + | |
| 21 | +[[snippet]] | |
| 22 | +name = "TODO" | |
| 23 | +body = "TODO: " | |
| 24 | +``` | |
| 25 | + | |
| 26 | +Each `[[snippet]]` becomes one line of the menu. The file is read every time the menu opens, so editing it takes effect immediately — no restart. | |
| 27 | + | |
| 28 | +## Insert one | |
| 29 | + | |
| 30 | +Open **Snippets** (`Alt-N`). Snippets sharing a `group` appear together in a submenu of that name; one with no group goes into **General**. | |
| 31 | + | |
| 32 | +| Key | Effect | | |
| 33 | +| --- | --- | | |
| 34 | +| `Alt-N`, or `F10` then `→` to Snippets | Open the menu | | |
| 35 | +| `↑` `↓` | Move down the groups | | |
| 36 | +| `→`, or `Enter` | Open the highlighted group | | |
| 37 | +| `↑` `↓` then `Enter` | Insert the highlighted snippet | | |
| 38 | +| `←` | Back out of a group | | |
| 39 | +| `Escape` | Put the whole menu away | | |
| 40 | + | |
| 41 | +The snippet goes in at the cursor. **Lines after the first are indented to match the line you inserted it on**, so a multi-line snippet dropped into a nested block lands where you would have typed it: | |
| 42 | + | |
| 43 | +``` | |
| 44 | +func f() { | |
| 45 | + | ← cursor here | |
| 46 | +} | |
| 47 | +``` | |
| 48 | + | |
| 49 | +becomes | |
| 50 | + | |
| 51 | +``` | |
| 52 | +func f() { | |
| 53 | + if err != nil { | |
| 54 | + return err | |
| 55 | + } | |
| 56 | +} | |
| 57 | +``` | |
| 58 | + | |
| 59 | +It is one undo step: `Ctrl-Z` takes the whole snippet back out. | |
| 60 | + | |
| 61 | +## Keep snippets across every project | |
| 62 | + | |
| 63 | +Put them in `~/.config/turbo-python/snippets.toml` — the same directory your own themes go in. Those appear in every project, and a project's own file adds to them rather than replacing them. | |
| 64 | + | |
| 65 | +Where a project and you use the same `name` in the same `group`, **the project's wins**: it is the more specific statement of the two. | |
| 66 | + | |
| 67 | +## Show a snippet only where it makes sense | |
| 68 | + | |
| 69 | +Add `languages`, using the names the editor uses — `python`, `toml`, `markdown`, `javascript`, `html`, `bash`: | |
| 70 | + | |
| 71 | +```toml | |
| 72 | +[[snippet]] | |
| 73 | +name = "strict mode" | |
| 74 | +group = "Shell" | |
| 75 | +languages = ["bash"] | |
| 76 | +body = "set -euo pipefail" | |
| 77 | +``` | |
| 78 | + | |
| 79 | +That snippet then appears only when a shell script is the front window. Leave `languages` out and the snippet is offered everywhere, which is what you want for a licence header or a `TODO`. | |
| 80 | + | |
| 81 | +A group left with nothing after filtering does not appear at all. | |
| 82 | + | |
| 83 | +## Variants | |
| 84 | + | |
| 85 | +- **You started the editor from a subdirectory.** The project's file is not found: only `./.turbo-python` is looked at, the same rule `settings.toml` follows. Your own snippets still appear. | |
| 86 | +- **The file has a mistake in it.** The menu shows a greyed-out `Cannot read snippets` where the groups would be, and **Create snippets file** is still there. Open the file and fix it. | |
| 87 | +- **You want tabs in a body.** Write `\t`, as the starter file does — TOML turns it into a tab when it reads the file. | |
| 88 | + | |
| 89 | +## See also | |
| 90 | + | |
| 91 | +- Every key of the file and every rule: [Snippets reference](../reference/snippets.md) | |
| 92 | +- Why the menu is rebuilt each time it opens, and why insertion re-indents: [Snippets](../explanation/snippets.md) | |
| 93 | +- The other file in `.turbo-python`: [Project settings](../reference/project-settings.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# How to insert snippets from a menu | ||
| 2 | + | ||
| 3 | +This guide shows how to set up reusable pieces of text and put them into a file at the cursor. It assumes Turbo Python is already installed. | ||
| 4 | + | ||
| 5 | +## Get a starter file | ||
| 6 | + | ||
| 7 | +Start the editor **from the project's own directory**, then choose **Snippets ▸ Create snippets file** (`Alt-N`, then `C`). | ||
| 8 | + | ||
| 9 | +That writes `.turbo-python/snippets.toml`, filled in with a few worked examples, and opens it — coloured, because Turbo Python colours TOML: | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[snippet]] | ||
| 13 | +name = "if err != nil" | ||
| 14 | +group = "Python" | ||
| 15 | +languages = ["python"] | ||
| 16 | +body = """ | ||
| 17 | +if err != nil { | ||
| 18 | + return err | ||
| 19 | +}""" | ||
| 20 | + | ||
| 21 | +[[snippet]] | ||
| 22 | +name = "TODO" | ||
| 23 | +body = "TODO: " | ||
| 24 | +``` | ||
| 25 | + | ||
| 26 | +Each `[[snippet]]` becomes one line of the menu. The file is read every time the menu opens, so editing it takes effect immediately — no restart. | ||
| 27 | + | ||
| 28 | +## Insert one | ||
| 29 | + | ||
| 30 | +Open **Snippets** (`Alt-N`). Snippets sharing a `group` appear together in a submenu of that name; one with no group goes into **General**. | ||
| 31 | + | ||
| 32 | +| Key | Effect | | ||
| 33 | +| --- | --- | | ||
| 34 | +| `Alt-N`, or `F10` then `→` to Snippets | Open the menu | | ||
| 35 | +| `↑` `↓` | Move down the groups | | ||
| 36 | +| `→`, or `Enter` | Open the highlighted group | | ||
| 37 | +| `↑` `↓` then `Enter` | Insert the highlighted snippet | | ||
| 38 | +| `←` | Back out of a group | | ||
| 39 | +| `Escape` | Put the whole menu away | | ||
| 40 | + | ||
| 41 | +The snippet goes in at the cursor. **Lines after the first are indented to match the line you inserted it on**, so a multi-line snippet dropped into a nested block lands where you would have typed it: | ||
| 42 | + | ||
| 43 | +``` | ||
| 44 | +func f() { | ||
| 45 | + | ← cursor here | ||
| 46 | +} | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +becomes | ||
| 50 | + | ||
| 51 | +``` | ||
| 52 | +func f() { | ||
| 53 | + if err != nil { | ||
| 54 | + return err | ||
| 55 | + } | ||
| 56 | +} | ||
| 57 | +``` | ||
| 58 | + | ||
| 59 | +It is one undo step: `Ctrl-Z` takes the whole snippet back out. | ||
| 60 | + | ||
| 61 | +## Keep snippets across every project | ||
| 62 | + | ||
| 63 | +Put them in `~/.config/turbo-python/snippets.toml` — the same directory your own themes go in. Those appear in every project, and a project's own file adds to them rather than replacing them. | ||
| 64 | + | ||
| 65 | +Where a project and you use the same `name` in the same `group`, **the project's wins**: it is the more specific statement of the two. | ||
| 66 | + | ||
| 67 | +## Show a snippet only where it makes sense | ||
| 68 | + | ||
| 69 | +Add `languages`, using the names the editor uses — `python`, `toml`, `markdown`, `javascript`, `html`, `bash`: | ||
| 70 | + | ||
| 71 | +```toml | ||
| 72 | +[[snippet]] | ||
| 73 | +name = "strict mode" | ||
| 74 | +group = "Shell" | ||
| 75 | +languages = ["bash"] | ||
| 76 | +body = "set -euo pipefail" | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +That snippet then appears only when a shell script is the front window. Leave `languages` out and the snippet is offered everywhere, which is what you want for a licence header or a `TODO`. | ||
| 80 | + | ||
| 81 | +A group left with nothing after filtering does not appear at all. | ||
| 82 | + | ||
| 83 | +## Variants | ||
| 84 | + | ||
| 85 | +- **You started the editor from a subdirectory.** The project's file is not found: only `./.turbo-python` is looked at, the same rule `settings.toml` follows. Your own snippets still appear. | ||
| 86 | +- **The file has a mistake in it.** The menu shows a greyed-out `Cannot read snippets` where the groups would be, and **Create snippets file** is still there. Open the file and fix it. | ||
| 87 | +- **You want tabs in a body.** Write `\t`, as the starter file does — TOML turns it into a tab when it reads the file. | ||
| 88 | + | ||
| 89 | +## See also | ||
| 90 | + | ||
| 91 | +- Every key of the file and every rule: [Snippets reference](../reference/snippets.md) | ||
| 92 | +- Why the menu is rebuilt each time it opens, and why insertion re-indents: [Snippets](../explanation/snippets.md) | ||
| 93 | +- The other file in `.turbo-python`: [Project settings](../reference/project-settings.md) | ||
added
docs/en/how-to/write-a-theme.md +152 -0 | new file mode 100644 | ||
| @@ -0,0 +1,152 @@ | ||
| 1 | +# How to write your own theme | |
| 2 | + | |
| 3 | +This guide shows how to add a colour theme of your own. It assumes you know where your configuration directory is and can edit a TOML file. | |
| 4 | + | |
| 5 | +## 1. Find where themes go | |
| 6 | + | |
| 7 | +```bash | |
| 8 | +turbo-python -list-themes | |
| 9 | +``` | |
| 10 | + | |
| 11 | +The last line tells you the directory — `~/.config/turbo-python/themes` on Linux, `~/Library/Application Support/turbo-python/themes` on macOS. Create it: | |
| 12 | + | |
| 13 | +```bash | |
| 14 | +mkdir -p ~/.config/turbo-python/themes | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## 2. Start from an existing theme | |
| 18 | + | |
| 19 | +The quickest start is to inherit from one that already works and override only what you want: | |
| 20 | + | |
| 21 | +```toml | |
| 22 | +# ~/.config/turbo-python/themes/mine.toml | |
| 23 | +name = "Mine" | |
| 24 | +description = "Turbo Classic, but the comments are readable." | |
| 25 | +inherits = "turbo-classic" | |
| 26 | + | |
| 27 | +[colors] | |
| 28 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | |
| 29 | +"syntax.string" = { fg = "#87d7af" } | |
| 30 | +``` | |
| 31 | + | |
| 32 | +Everything you do not set is taken from `turbo-classic`. | |
| 33 | + | |
| 34 | +**Inherit from a theme whose ground is the same as yours.** The colours you leave out were chosen against the background of the theme you inherit from, so a dark theme built on `turbo-classic` will show, here and there, a colour picked for Borland navy. If you are writing a dark theme, inherit from `turbo-dark`, `cappuccino`, `catppuccin-frappe`, `cobalt`, `darcula` or `monochrome-dark`; if a light one, from `borland-light`, `catppuccin-latte`, `intellij-light` or `monochrome-light`. That is also why the eleven themes that ship in the binary each state their palette in full rather than inheriting most of it — a test holds them to it, because a shipped theme is one the project is answerable for. | |
| 35 | + | |
| 36 | +## 3. Use it | |
| 37 | + | |
| 38 | +```bash | |
| 39 | +turbo-python -theme mine main.py | |
| 40 | +``` | |
| 41 | + | |
| 42 | +Or from inside the editor: `Options ▸ Theme…`, which lists every theme it can find. | |
| 43 | + | |
| 44 | +## 4. Iterate | |
| 45 | + | |
| 46 | +Edit the file, then restart the editor. There is no live reload. | |
| 47 | + | |
| 48 | +If the theme fails to load, Turbo Python falls back to the default rather than refusing to start. To see *why* it failed: | |
| 49 | + | |
| 50 | +```bash | |
| 51 | +turbo-python -list-themes | |
| 52 | +``` | |
| 53 | + | |
| 54 | +A broken theme is listed with the parse error beside it — an unknown colour name is an error, not a silent fallback, so a typo is pointed at rather than quietly repainting half the screen. | |
| 55 | + | |
| 56 | +## 5. Check it stays readable | |
| 57 | + | |
| 58 | +The project holds every theme it ships to five measured rules, and they are worth applying to your own. `make test` runs them. | |
| 59 | + | |
| 60 | +| Rule | Why | | |
| 61 | +| --- | --- | | |
| 62 | +| The cursor is at least 64 apart from the line it sits on, in its strongest channel | A terminal draws its cursor over the cell; one that blends in cannot be found | | |
| 63 | +| The cursor is never a plain reversal of that line | A terminal that draws its cursor by inverting the cell would invert it back into invisibility | | |
| 64 | +| The current line is at least 16 from the page | `turbo-dark` once used ten, which is no highlight at all | | |
| 65 | +| Text you have to read is at least 64 from its background | Furniture — the desktop, a shadow, a scrollbar trough, a disabled entry — is exempt: it exists to recede | | |
| 66 | +| Comments read at 4.5:1 or better against their background, by WCAG relative luminance | A comment is prose, read word by word. `turbo-classic` drew them in `#808080` on its navy: 128 channel values apart, so the rule above waved it through, and 4.05:1 to read, which is below the W3C's floor for body text. Comments were the dimmest colour in six of the eight shipped themes. | | |
| 67 | + | |
| 68 | + | |
| 69 | +The contrast rule is applied to the six themes this project authors. The two Catppuccin themes are exempt, and the exemption is written where it is made: their colours are somebody else's published palette, faithfully copied, and Catppuccin puts comments at 2.87:1 in Frappé and 2.83:1 in Latte. A theme called Catppuccin that is not those exact values is a different theme wearing a borrowed name, so the fix — if anyone wants one — is upstream. | |
| 70 | + | |
| 71 | +It is applied to comments and to nothing else. `syntax.punctuation` is quieter still in several themes and stays that way: punctuation is recognised by shape, not read. | |
| 72 | + | |
| 73 | +A sixth rule catches the mistake no measurement finds: **two syntax classes a reader meets side by side must not be drawn identically**. `turbo-classic` once painted `syntax.link` the same lime as `syntax.string`, so a Markdown link and an inline code span were the same thing on screen — every colour readable, every key set, and the two simply equal. Both monochromes pass this rule with no hue at all, by using bold, italic and underline instead. | |
| 74 | + | |
| 75 | +## Variants | |
| 76 | + | |
| 77 | +**Override a shipped theme rather than adding one.** Name your file after it — `turbo-classic.toml` — and yours wins. The embedded one is not replaced, so deleting your file brings it back. | |
| 78 | + | |
| 79 | +**Start from scratch.** Leave `inherits` out. Set at least `default`; every key you do not set falls back along the dots to it, so a theme with one line is still a usable theme. | |
| 80 | + | |
| 81 | +**Colour only the syntax.** One key does it: | |
| 82 | + | |
| 83 | +```toml | |
| 84 | +[colors] | |
| 85 | +syntax = { fg = "silver" } | |
| 86 | +``` | |
| 87 | + | |
| 88 | +`syntax.keyword`, `syntax.string` and the rest all fall back to it. | |
| 89 | + | |
| 90 | +**Keep the terminal's own colours.** Use `default` as a colour value: | |
| 91 | + | |
| 92 | +```toml | |
| 93 | +[colors] | |
| 94 | +"editor.text" = { fg = "default", bg = "default" } | |
| 95 | +``` | |
| 96 | + | |
| 97 | +**Test it in a checkout without installing it.** Point the editor at any directory: | |
| 98 | + | |
| 99 | +```bash | |
| 100 | +TURBO_PYTHON_THEME_DIR=./my-themes turbo-python -theme mine main.py | |
| 101 | +``` | |
| 102 | + | |
| 103 | +**The cursor is hard to see.** `editor.cursor` does two things: its **background** is sent to the terminal as the cursor's own colour, and it also paints the cell underneath as a fallback for terminals that ignore that. Set it to something loud: | |
| 104 | + | |
| 105 | +```toml | |
| 106 | +[colors] | |
| 107 | +"editor.cursor" = { fg = "#000000", bg = "#ff8700" } | |
| 108 | +``` | |
| 109 | + | |
| 110 | +Two things make a cursor colour a bad one, and the test suite rejects both: a plain reversal of the line — which terminals that draw their cursor by inverting the cell turn back into invisibility — and anything less than 64 channel values away from the line it sits on. | |
| 111 | + | |
| 112 | +**The cursor's line is hard to find.** That is `editor.currentline`, and it is a different key. It has to differ from `editor.text` by at least 16 channel values to count as a highlight at all. | |
| 113 | + | |
| 114 | +**Markdown and HTML look plain.** Five keys belong to the markup languages and have no equivalent in Python, so a theme written before they existed does not set them: | |
| 115 | + | |
| 116 | +```toml | |
| 117 | +[colors] | |
| 118 | +"syntax.heading" = { fg = "white", bold = true } | |
| 119 | +"syntax.tag" = { fg = "aqua" } | |
| 120 | +"syntax.attribute" = { fg = "yellow" } | |
| 121 | +"syntax.emphasis" = { fg = "fuchsia", bold = true } | |
| 122 | +"syntax.link" = { fg = "aqua", underline = true } | |
| 123 | +``` | |
| 124 | + | |
| 125 | +Give `syntax.link` a different colour from `syntax.string`: a link and an inline `code` span sit side by side in most prose, and sharing a colour makes them one blur. The shipped `turbo-classic` had exactly that fault until it was looked at on a real terminal. | |
| 126 | + | |
| 127 | +**The project tree looks flat.** It has four keys of its own, and none of them falls back to `list`: | |
| 128 | + | |
| 129 | +```toml | |
| 130 | +[colors] | |
| 131 | +"tree.text" = { fg = "silver", bg = "navy" } | |
| 132 | +"tree.directory" = { fg = "white", bg = "navy", bold = true } | |
| 133 | +"tree.selected" = { fg = "black", bg = "aqua" } | |
| 134 | +"tree.unfocused" = { fg = "black", bg = "gray" } | |
| 135 | +``` | |
| 136 | + | |
| 137 | +Give `tree.text` the same background as `window.body`, so the tree looks like part of its window, and make `tree.selected` clearly different from it — the test suite holds every shipped theme to at least 64 channel values between the two, because a highlight the same colour as the page is no highlight. | |
| 138 | + | |
| 139 | +**Terminal windows look wrong.** They have two keys of their own, and neither falls back to `editor`: | |
| 140 | + | |
| 141 | +```toml | |
| 142 | +[colors] | |
| 143 | +"terminal.text" = { fg = "silver", bg = "black" } | |
| 144 | +"terminal.cursor" = { fg = "black", bg = "aqua" } | |
| 145 | +``` | |
| 146 | + | |
| 147 | +`terminal.text` is what a shell's output gets when it names no colour of its own — set it to something close to a real terminal rather than to your editor background, or `less` and `htop` will look out of place. A program that does name its colours keeps them either way. | |
| 148 | + | |
| 149 | +## See also | |
| 150 | + | |
| 151 | +- Every key you may set, and every colour name: [theme file reference](../reference/themes.md) | |
| 152 | +- Why the format is TOML with two kinds of inheritance: [Design decisions](../explanation/design-decisions.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,152 @@ | |||
| 1 | +# How to write your own theme | ||
| 2 | + | ||
| 3 | +This guide shows how to add a colour theme of your own. It assumes you know where your configuration directory is and can edit a TOML file. | ||
| 4 | + | ||
| 5 | +## 1. Find where themes go | ||
| 6 | + | ||
| 7 | +```bash | ||
| 8 | +turbo-python -list-themes | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +The last line tells you the directory — `~/.config/turbo-python/themes` on Linux, `~/Library/Application Support/turbo-python/themes` on macOS. Create it: | ||
| 12 | + | ||
| 13 | +```bash | ||
| 14 | +mkdir -p ~/.config/turbo-python/themes | ||
| 15 | +``` | ||
| 16 | + | ||
| 17 | +## 2. Start from an existing theme | ||
| 18 | + | ||
| 19 | +The quickest start is to inherit from one that already works and override only what you want: | ||
| 20 | + | ||
| 21 | +```toml | ||
| 22 | +# ~/.config/turbo-python/themes/mine.toml | ||
| 23 | +name = "Mine" | ||
| 24 | +description = "Turbo Classic, but the comments are readable." | ||
| 25 | +inherits = "turbo-classic" | ||
| 26 | + | ||
| 27 | +[colors] | ||
| 28 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | ||
| 29 | +"syntax.string" = { fg = "#87d7af" } | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +Everything you do not set is taken from `turbo-classic`. | ||
| 33 | + | ||
| 34 | +**Inherit from a theme whose ground is the same as yours.** The colours you leave out were chosen against the background of the theme you inherit from, so a dark theme built on `turbo-classic` will show, here and there, a colour picked for Borland navy. If you are writing a dark theme, inherit from `turbo-dark`, `cappuccino`, `catppuccin-frappe`, `cobalt`, `darcula` or `monochrome-dark`; if a light one, from `borland-light`, `catppuccin-latte`, `intellij-light` or `monochrome-light`. That is also why the eleven themes that ship in the binary each state their palette in full rather than inheriting most of it — a test holds them to it, because a shipped theme is one the project is answerable for. | ||
| 35 | + | ||
| 36 | +## 3. Use it | ||
| 37 | + | ||
| 38 | +```bash | ||
| 39 | +turbo-python -theme mine main.py | ||
| 40 | +``` | ||
| 41 | + | ||
| 42 | +Or from inside the editor: `Options ▸ Theme…`, which lists every theme it can find. | ||
| 43 | + | ||
| 44 | +## 4. Iterate | ||
| 45 | + | ||
| 46 | +Edit the file, then restart the editor. There is no live reload. | ||
| 47 | + | ||
| 48 | +If the theme fails to load, Turbo Python falls back to the default rather than refusing to start. To see *why* it failed: | ||
| 49 | + | ||
| 50 | +```bash | ||
| 51 | +turbo-python -list-themes | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +A broken theme is listed with the parse error beside it — an unknown colour name is an error, not a silent fallback, so a typo is pointed at rather than quietly repainting half the screen. | ||
| 55 | + | ||
| 56 | +## 5. Check it stays readable | ||
| 57 | + | ||
| 58 | +The project holds every theme it ships to five measured rules, and they are worth applying to your own. `make test` runs them. | ||
| 59 | + | ||
| 60 | +| Rule | Why | | ||
| 61 | +| --- | --- | | ||
| 62 | +| The cursor is at least 64 apart from the line it sits on, in its strongest channel | A terminal draws its cursor over the cell; one that blends in cannot be found | | ||
| 63 | +| The cursor is never a plain reversal of that line | A terminal that draws its cursor by inverting the cell would invert it back into invisibility | | ||
| 64 | +| The current line is at least 16 from the page | `turbo-dark` once used ten, which is no highlight at all | | ||
| 65 | +| Text you have to read is at least 64 from its background | Furniture — the desktop, a shadow, a scrollbar trough, a disabled entry — is exempt: it exists to recede | | ||
| 66 | +| Comments read at 4.5:1 or better against their background, by WCAG relative luminance | A comment is prose, read word by word. `turbo-classic` drew them in `#808080` on its navy: 128 channel values apart, so the rule above waved it through, and 4.05:1 to read, which is below the W3C's floor for body text. Comments were the dimmest colour in six of the eight shipped themes. | | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +The contrast rule is applied to the six themes this project authors. The two Catppuccin themes are exempt, and the exemption is written where it is made: their colours are somebody else's published palette, faithfully copied, and Catppuccin puts comments at 2.87:1 in Frappé and 2.83:1 in Latte. A theme called Catppuccin that is not those exact values is a different theme wearing a borrowed name, so the fix — if anyone wants one — is upstream. | ||
| 70 | + | ||
| 71 | +It is applied to comments and to nothing else. `syntax.punctuation` is quieter still in several themes and stays that way: punctuation is recognised by shape, not read. | ||
| 72 | + | ||
| 73 | +A sixth rule catches the mistake no measurement finds: **two syntax classes a reader meets side by side must not be drawn identically**. `turbo-classic` once painted `syntax.link` the same lime as `syntax.string`, so a Markdown link and an inline code span were the same thing on screen — every colour readable, every key set, and the two simply equal. Both monochromes pass this rule with no hue at all, by using bold, italic and underline instead. | ||
| 74 | + | ||
| 75 | +## Variants | ||
| 76 | + | ||
| 77 | +**Override a shipped theme rather than adding one.** Name your file after it — `turbo-classic.toml` — and yours wins. The embedded one is not replaced, so deleting your file brings it back. | ||
| 78 | + | ||
| 79 | +**Start from scratch.** Leave `inherits` out. Set at least `default`; every key you do not set falls back along the dots to it, so a theme with one line is still a usable theme. | ||
| 80 | + | ||
| 81 | +**Colour only the syntax.** One key does it: | ||
| 82 | + | ||
| 83 | +```toml | ||
| 84 | +[colors] | ||
| 85 | +syntax = { fg = "silver" } | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +`syntax.keyword`, `syntax.string` and the rest all fall back to it. | ||
| 89 | + | ||
| 90 | +**Keep the terminal's own colours.** Use `default` as a colour value: | ||
| 91 | + | ||
| 92 | +```toml | ||
| 93 | +[colors] | ||
| 94 | +"editor.text" = { fg = "default", bg = "default" } | ||
| 95 | +``` | ||
| 96 | + | ||
| 97 | +**Test it in a checkout without installing it.** Point the editor at any directory: | ||
| 98 | + | ||
| 99 | +```bash | ||
| 100 | +TURBO_PYTHON_THEME_DIR=./my-themes turbo-python -theme mine main.py | ||
| 101 | +``` | ||
| 102 | + | ||
| 103 | +**The cursor is hard to see.** `editor.cursor` does two things: its **background** is sent to the terminal as the cursor's own colour, and it also paints the cell underneath as a fallback for terminals that ignore that. Set it to something loud: | ||
| 104 | + | ||
| 105 | +```toml | ||
| 106 | +[colors] | ||
| 107 | +"editor.cursor" = { fg = "#000000", bg = "#ff8700" } | ||
| 108 | +``` | ||
| 109 | + | ||
| 110 | +Two things make a cursor colour a bad one, and the test suite rejects both: a plain reversal of the line — which terminals that draw their cursor by inverting the cell turn back into invisibility — and anything less than 64 channel values away from the line it sits on. | ||
| 111 | + | ||
| 112 | +**The cursor's line is hard to find.** That is `editor.currentline`, and it is a different key. It has to differ from `editor.text` by at least 16 channel values to count as a highlight at all. | ||
| 113 | + | ||
| 114 | +**Markdown and HTML look plain.** Five keys belong to the markup languages and have no equivalent in Python, so a theme written before they existed does not set them: | ||
| 115 | + | ||
| 116 | +```toml | ||
| 117 | +[colors] | ||
| 118 | +"syntax.heading" = { fg = "white", bold = true } | ||
| 119 | +"syntax.tag" = { fg = "aqua" } | ||
| 120 | +"syntax.attribute" = { fg = "yellow" } | ||
| 121 | +"syntax.emphasis" = { fg = "fuchsia", bold = true } | ||
| 122 | +"syntax.link" = { fg = "aqua", underline = true } | ||
| 123 | +``` | ||
| 124 | + | ||
| 125 | +Give `syntax.link` a different colour from `syntax.string`: a link and an inline `code` span sit side by side in most prose, and sharing a colour makes them one blur. The shipped `turbo-classic` had exactly that fault until it was looked at on a real terminal. | ||
| 126 | + | ||
| 127 | +**The project tree looks flat.** It has four keys of its own, and none of them falls back to `list`: | ||
| 128 | + | ||
| 129 | +```toml | ||
| 130 | +[colors] | ||
| 131 | +"tree.text" = { fg = "silver", bg = "navy" } | ||
| 132 | +"tree.directory" = { fg = "white", bg = "navy", bold = true } | ||
| 133 | +"tree.selected" = { fg = "black", bg = "aqua" } | ||
| 134 | +"tree.unfocused" = { fg = "black", bg = "gray" } | ||
| 135 | +``` | ||
| 136 | + | ||
| 137 | +Give `tree.text` the same background as `window.body`, so the tree looks like part of its window, and make `tree.selected` clearly different from it — the test suite holds every shipped theme to at least 64 channel values between the two, because a highlight the same colour as the page is no highlight. | ||
| 138 | + | ||
| 139 | +**Terminal windows look wrong.** They have two keys of their own, and neither falls back to `editor`: | ||
| 140 | + | ||
| 141 | +```toml | ||
| 142 | +[colors] | ||
| 143 | +"terminal.text" = { fg = "silver", bg = "black" } | ||
| 144 | +"terminal.cursor" = { fg = "black", bg = "aqua" } | ||
| 145 | +``` | ||
| 146 | + | ||
| 147 | +`terminal.text` is what a shell's output gets when it names no colour of its own — set it to something close to a real terminal rather than to your editor background, or `less` and `htop` will look out of place. A program that does name its colours keeps them either way. | ||
| 148 | + | ||
| 149 | +## See also | ||
| 150 | + | ||
| 151 | +- Every key you may set, and every colour name: [theme file reference](../reference/themes.md) | ||
| 152 | +- Why the format is TOML with two kinds of inheritance: [Design decisions](../explanation/design-decisions.md) | ||
added
docs/en/reference/acp.md +239 -0 | new file mode 100644 | ||
| @@ -0,0 +1,239 @@ | ||
| 1 | +# Agents and ACP | |
| 2 | + | |
| 3 | +Turbo Python is a client for the [Agent Client Protocol](https://agentclientprotocol.com). It starts each agent as a child process and exchanges JSON-RPC 2.0 messages with it over stdin and stdout, one message per line. | |
| 4 | + | |
| 5 | +## Where the file lives | |
| 6 | + | |
| 7 | +| Path | Read | Purpose | | |
| 8 | +| --- | --- | --- | | |
| 9 | +| `~/.config/turbo-python/acp.toml` | first | Agents you want in every project | | |
| 10 | +| `<project>/.turbo-python/acp.toml` | second | Agents belonging to this project | | |
| 11 | + | |
| 12 | +Both are optional. Where an agent's `name` appears in both, the project's replaces the user's, being the more specific statement — the same rule [snippets](snippets.md) follow. A missing file is not an error; a file that is present but unreadable is, and is reported under **Agent ▸ Agent status** rather than silently leaving the menu empty. | |
| 13 | + | |
| 14 | +`TURBO_PYTHON_DIR` overrides the directory the user-level file is looked for in. The project file is always `.turbo-python/acp.toml` under the directory the editor was started in — there is no walk up the tree, for the same reason [project settings](project-settings.md) do not walk up. | |
| 15 | + | |
| 16 | +## File format | |
| 17 | + | |
| 18 | +One `[[agent]]` block per agent, in the order you want them in the menu. | |
| 19 | + | |
| 20 | +```toml | |
| 21 | +[[agent]] | |
| 22 | +name = "Bob (llama.cpp)" | |
| 23 | +command = "docker" | |
| 24 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | |
| 25 | +env = { TELEMETRY_ENABLED = "false" } | |
| 26 | +cwd = "." | |
| 27 | +``` | |
| 28 | + | |
| 29 | +| Key | Type | Required | Meaning | | |
| 30 | +| --- | --- | --- | --- | | |
| 31 | +| `name` | string | **yes** | What the Agent menu shows and what the window is titled. Must be unique within the merged set. | | |
| 32 | +| `command` | string | **yes** | The executable to run. Looked up on `PATH` unless it contains a separator. | | |
| 33 | +| `args` | list of strings | no | Its arguments, passed as given — no shell, so no quoting, globbing or `&&`. | | |
| 34 | +| `env` | table of strings | no | Environment variables added to the ones the editor was started with. A name given here wins. | | |
| 35 | +| `cwd` | string | no | Where the process starts, and the `cwd` the agent is told about. Relative to the project root. Defaults to the project root. | | |
| 36 | + | |
| 37 | +`env` may also be written as a sub-table, which is the same thing: | |
| 38 | + | |
| 39 | +```toml | |
| 40 | +[[agent]] | |
| 41 | +name = "Bob (llama.cpp)" | |
| 42 | +command = "docker" | |
| 43 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | |
| 44 | + | |
| 45 | +[agent.env] | |
| 46 | +TELEMETRY_ENABLED = "false" | |
| 47 | +``` | |
| 48 | + | |
| 49 | +### What is refused | |
| 50 | + | |
| 51 | +The file is refused as a whole, rather than partly loaded, when any of these hold. A half-loaded menu offering three of your five agents is worse than an error saying why. | |
| 52 | + | |
| 53 | +| Problem | Message | | |
| 54 | +| --- | --- | | |
| 55 | +| an agent with no `name` | `reading …/acp.toml: agent 1 has no name` | | |
| 56 | +| an agent with no `command` | `reading …/acp.toml: agent "Bob" has no command` | | |
| 57 | +| two agents with the same `name` | `reading …/acp.toml: two agents are called "Bob"` | | |
| 58 | +| a key the format does not define | `reading …/acp.toml: agent.comand is not a key this file has` | | |
| 59 | + | |
| 60 | +The last one is deliberate: a misspelt key that was quietly ignored would look exactly like one that had no effect. | |
| 61 | + | |
| 62 | +## The Agent menu | |
| 63 | + | |
| 64 | +`Alt-A` opens it. It is on the bar whether or not any agent is configured, because that is where **Create agents file** has to be reachable from. | |
| 65 | + | |
| 66 | +| Item | Enabled when | Effect | | |
| 67 | +| --- | --- | --- | | |
| 68 | +| *one item per agent, by name* | always | Start that agent and open a window on it | | |
| 69 | +| **Create agents file** | no `acp.toml` in the project | Write the starter file and open it | | |
| 70 | +| **Cancel turn** | a turn is running in the front window | `session/cancel` | | |
| 71 | +| **Agent status** | always | What was loaded, what each command line is, and what failed | | |
| 72 | + | |
| 73 | +## Keys inside an agent window | |
| 74 | + | |
| 75 | +An agent window is an ordinary window: `F6`, `Alt-1`…`Alt-9`, Tile, Maximise, `[x]` and `[■]` all work on it. Inside it: | |
| 76 | + | |
| 77 | +| Key | Effect | | |
| 78 | +| --- | --- | | |
| 79 | +| `Enter` | Send the input box as a prompt | | |
| 80 | +| `Alt-Enter` | Insert a newline in the input box | | |
| 81 | +| `Tab` | Move focus between the conversation and the input box | | |
| 82 | +| `Ctrl-C`, `Ctrl-Ins` | Copy the selection, or the block the cursor is on | | |
| 83 | +| `Esc` | Drop the selection; with none, cancel the turn in progress | | |
| 84 | +| `Ctrl-W` | Close the window and stop the agent | | |
| 85 | + | |
| 86 | +With the **input box** focused: | |
| 87 | + | |
| 88 | +| Key | Effect | | |
| 89 | +| --- | --- | | |
| 90 | +| `↑` `↓` `←` `→` `Home` `End` | Move the cursor in what you are typing | | |
| 91 | +| `Backspace` `Delete` | Edit it; backspace at the start of a line joins it to the one above | | |
| 92 | +| `/` as the first character | Open the list of the agent's commands — see [Commands and mentions](#commands-and-mentions) | | |
| 93 | +| `@` | Open the list of the project's files, narrowed by what you type after it | | |
| 94 | +| `↑` `↓` `PgUp` `PgDn`, list open | Move through the list | | |
| 95 | +| `Tab`, list open | Take the highlighted entry | | |
| 96 | +| `Enter`, list open | Take the highlighted entry; on a word that is already complete, send | | |
| 97 | +| `Esc`, list open | Close the list until the text changes | | |
| 98 | + | |
| 99 | +With the **conversation** focused: | |
| 100 | + | |
| 101 | +| Key | Effect | | |
| 102 | +| --- | --- | | |
| 103 | +| `↑` `↓` | Move the cursor one line | | |
| 104 | +| `PgUp` `PgDn` | Move it a screenful | | |
| 105 | +| `Home` `End` | The start of the conversation, and the end | | |
| 106 | +| `Shift-` any of those | Extend the selection instead | | |
| 107 | +| Drag with button 1 | Select by hand | | |
| 108 | +| Wheel | Scroll three lines, leaving the cursor where it is | | |
| 109 | + | |
| 110 | +Unlike a terminal window, an agent window does **not** take the editor's shortcuts: there is no shell to need `Ctrl-F`, so it keeps its usual meaning. `Ctrl-C` is the exception, and only because nothing else in an agent window wants it. | |
| 111 | + | |
| 112 | +## Commands and mentions | |
| 113 | + | |
| 114 | +Two characters open a list over the bottom of the conversation while you type. They are the same two Zed uses, so an agent's own documentation — "type `/web` to search" — holds here too. | |
| 115 | + | |
| 116 | +### `/` — the agent's commands | |
| 117 | + | |
| 118 | +An agent may announce commands with `available_commands_update`, at the start of the session or at any point during it. Typing `/` as the **first character** of the box lists them: the name, the agent's description, and, in angle brackets, what it expects after the name when it expects something. Keep typing to narrow the list; the match is on the start of the name and ignores case. | |
| 119 | + | |
| 120 | +`Tab` completes the highlighted command. A command that takes input is completed with a trailing space, so the next thing you type is its argument; one that takes none is completed to the bare name. `Enter` completes too, except on a word that already reads exactly as a command, where it sends. | |
| 121 | + | |
| 122 | +On the wire a command is **text**: `/web agent client protocol` goes out as one text block, and the agent recognises it by its first word. That is the whole protocol for commands, and it is why a `/` anywhere but the start of the box is just a character. | |
| 123 | + | |
| 124 | +With no commands announced, `/` is a character and `Tab` keeps its ordinary meaning. **Agent ▸ Agent status** lists the commands with their descriptions. | |
| 125 | + | |
| 126 | +### `@` — a file from the project | |
| 127 | + | |
| 128 | +Typing `@` anywhere in the box lists the project's files, relative to the project root with forward slashes. What you type after the `@` narrows the list: files whose own name begins with it come first, then files whose path merely contains it. `Tab` or `Enter` completes the highlighted one and adds a space. | |
| 129 | + | |
| 130 | +When the prompt is sent, each `@name` that names a file the list knew becomes a content block **in place of the name**: | |
| 131 | + | |
| 132 | +| The agent declared | The block sent | | |
| 133 | +| --- | --- | | |
| 134 | +| `promptCapabilities.embeddedContext: true` | `resource` — the file's `uri`, `mimeType` and full `text`, read the way `fs/read_text_file` reads it: from the open buffer when the file is open and modified | | |
| 135 | +| anything else, or the file could not be read | `resource_link` — the `uri`, `name` and `mimeType`, for the agent to fetch itself | | |
| 136 | + | |
| 137 | +The words either side go as text blocks, so `explain @docs/README.md please` is three blocks: `explain `, the file, ` please`. The conversation keeps the line as you typed it. | |
| 138 | + | |
| 139 | +A word that begins with `@` and names no file stays text — an e-mail address in a prompt is not a file — and `@main.go` does not name `main.gopher`: the name has to end the word. | |
| 140 | + | |
| 141 | +The list is the project walked from its root, `.git` left out, at most 5 000 files, and at most 200 of them shown at once. Past either limit, type one more letter. It is walked afresh each time `@` opens the list, so a file the agent just created is in it. | |
| 142 | + | |
| 143 | +## Copying | |
| 144 | + | |
| 145 | +Selection is by **whole lines**. Nothing in a conversation is edited, so half a line is never what somebody means, and whole lines keep a copied code block's indentation intact. | |
| 146 | + | |
| 147 | +With nothing selected, copying takes the **region the cursor is on**: one fenced code block, one passage of prose, one tool call's output. A speaker's label and a tool call's heading are furniture and are regions of their own, so neither is ever copied with what it sits above. | |
| 148 | + | |
| 149 | +The indentation the conversation is drawn with is removed, so pasted code is flush. | |
| 150 | + | |
| 151 | +The text goes to two places at once: | |
| 152 | + | |
| 153 | +| Clipboard | How | Pasted with | | |
| 154 | +| --- | --- | --- | | |
| 155 | +| The editor's | directly | `Shift-Ins`, into a file open here | | |
| 156 | +| The system's | OSC 52, through the terminal | `Ctrl-V`, anywhere else | | |
| 157 | + | |
| 158 | +Nothing checks whether the terminal accepted the second: there is no reply to check, and a terminal may refuse OSC 52 for security or need it turned on. The editor's own clipboard has the text either way, and the status bar says how many lines were copied. | |
| 159 | + | |
| 160 | +## How much of the protocol is implemented | |
| 161 | + | |
| 162 | +Protocol version **1**. Turbo Python sends its version in `initialize` and accepts whatever version the agent answers with, provided it is one it knows. | |
| 163 | + | |
| 164 | +### What the editor calls on the agent | |
| 165 | + | |
| 166 | +| Method | Implemented | Notes | | |
| 167 | +| --- | --- | --- | | |
| 168 | +| `initialize` | yes | Advertises the `fs` capability below; `terminal` is not advertised | | |
| 169 | +| `session/new` | yes | `cwd` from the agent's `cwd` key; `mcpServers` is always empty — MCP servers are the agent's own business | | |
| 170 | +| `session/prompt` | yes | Text blocks, and one `resource` or `resource_link` block per file named with `@` — see [Commands and mentions](#commands-and-mentions) | | |
| 171 | +| `session/cancel` | yes | `Esc`, and **Agent ▸ Cancel turn** | | |
| 172 | +| `session/load` | **no** | Conversations do not survive closing the window | | |
| 173 | +| `authenticate` | **no** | An agent that lists `authMethods` is reported as needing a login the editor cannot perform | | |
| 174 | + | |
| 175 | +### What the agent may call on the editor | |
| 176 | + | |
| 177 | +| Method | Implemented | Notes | | |
| 178 | +| --- | --- | --- | | |
| 179 | +| `session/update` | yes | See the table below | | |
| 180 | +| `session/request_permission` | yes | A modal dialog carrying the agent's own options | | |
| 181 | +| `fs/read_text_file` | yes | From the open buffer when the file is open and modified, otherwise from disk | | |
| 182 | +| `fs/write_text_file` | yes | Into the open buffer when the file is open, otherwise to disk | | |
| 183 | +| `terminal/*` | **no** | Not advertised, so a conforming agent will not ask | | |
| 184 | + | |
| 185 | +### Session updates | |
| 186 | + | |
| 187 | +| `sessionUpdate` | Shown as | | |
| 188 | +| --- | --- | | |
| 189 | +| `agent_message_chunk` | The agent's reply, appended as it arrives | | |
| 190 | +| `agent_thought_chunk` | The same, in the comment colour, under a *thinking* label | | |
| 191 | +| `user_message_chunk` | Your own message, as the agent echoes it back | | |
| 192 | +| `tool_call` | A line naming the tool and its title, with its status | | |
| 193 | +| `tool_call_update` | Folded onto the line the `toolCallId` matches, carrying its output | | |
| 194 | +| `plan` | The entries as a list, each with its status | | |
| 195 | +| `available_commands_update` | The list `/` opens in the input box; also listed, with descriptions, by **Agent ▸ Agent status** | | |
| 196 | +| `usage_update` | The token count on the status bar while the window is in front | | |
| 197 | +| anything else | Ignored, and counted; the count is in **Agent status** | | |
| 198 | + | |
| 199 | +While a turn is running, the rule between the panes turns a spinner. It is drawn from the clock rather than from a counter, so two windows thinking at once turn in step and nothing has to be reset when a turn begins. The window's *title* deliberately does not animate: it is also what the window list and the `Alt`-digit menu show, and a name changing eight times a second makes both flicker. | |
| 200 | + | |
| 201 | +An unknown update is ignored rather than refused: the protocol grows, and an editor that stopped talking to an agent because it learnt a new kind of message would be wrong more often than it was right. | |
| 202 | + | |
| 203 | +## Colouring | |
| 204 | + | |
| 205 | +The conversation is drawn with keys every theme already sets, so none of them needed touching: | |
| 206 | + | |
| 207 | +| Part | Class | | |
| 208 | +| --- | --- | | |
| 209 | +| A speaker's name | `syntax.keyword` | | |
| 210 | +| A thought | `syntax.comment` | | |
| 211 | +| A tool call and its status | `syntax.type` | | |
| 212 | +| A failed tool call, and the editor's own notices | `diagnostic.error` | | |
| 213 | +| A selected line, and the cursor's bar | `editor.selection` | | |
| 214 | +| Code inside a fence | the scanner for the fence's language | | |
| 215 | +| Everything else | the window's plain text | | |
| 216 | + | |
| 217 | +A fenced block naming a language the editor colours — `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash` — is coloured by that scanner. One naming anything else, or nothing at all, is left plain. | |
| 218 | + | |
| 219 | +## Tracing the conversation with an agent | |
| 220 | + | |
| 221 | +| Variable | Effect | | |
| 222 | +| --- | --- | | |
| 223 | +| `TURBO_ACP_TRACE=<file>` | Append every message to and from every agent to that file, one per line, stamped with the time and marked `->` (sent) or `<-` (received) | | |
| 224 | + | |
| 225 | +It is for the one question the screen cannot answer — *what did the agent actually send?* An update this editor cannot decode is counted under **Agent ▸ Agent status**, which also names the last one and its error; the trace shows the message itself. A file that cannot be opened means no trace and nothing else: the trace is never allowed to break the editor. | |
| 226 | + | |
| 227 | +## Limits | |
| 228 | + | |
| 229 | +- **One session per window.** Closing the window ends the session; there is no resume. | |
| 230 | +- **Text and files only.** The editor sends text, and the files you name with `@`; not images or audio, whatever the agent's `promptCapabilities` say. | |
| 231 | +- **No authentication.** An agent that requires a login must be logged in by its own CLI before the editor starts it. | |
| 232 | +- **`args` are not a shell command.** `command = "sh"`, `args = ["-c", "…"]` is how to get one deliberately. | |
| 233 | +- **One entry is capped** at a megabyte of text. An agent printing a whole build log cannot make the window unusable; what was dropped is said in the entry itself. | |
| 234 | + | |
| 235 | +## See also | |
| 236 | + | |
| 237 | +- The task: [How to talk to a coding agent from the editor](../how-to/talk-to-an-agent.md) | |
| 238 | +- The reasoning: [Agent windows](../explanation/agent-windows.md) | |
| 239 | +- The protocol: [agentclientprotocol.com](https://agentclientprotocol.com) | |
| new file mode 100644 | |||
| @@ -0,0 +1,239 @@ | |||
| 1 | +# Agents and ACP | ||
| 2 | + | ||
| 3 | +Turbo Python is a client for the [Agent Client Protocol](https://agentclientprotocol.com). It starts each agent as a child process and exchanges JSON-RPC 2.0 messages with it over stdin and stdout, one message per line. | ||
| 4 | + | ||
| 5 | +## Where the file lives | ||
| 6 | + | ||
| 7 | +| Path | Read | Purpose | | ||
| 8 | +| --- | --- | --- | | ||
| 9 | +| `~/.config/turbo-python/acp.toml` | first | Agents you want in every project | | ||
| 10 | +| `<project>/.turbo-python/acp.toml` | second | Agents belonging to this project | | ||
| 11 | + | ||
| 12 | +Both are optional. Where an agent's `name` appears in both, the project's replaces the user's, being the more specific statement — the same rule [snippets](snippets.md) follow. A missing file is not an error; a file that is present but unreadable is, and is reported under **Agent ▸ Agent status** rather than silently leaving the menu empty. | ||
| 13 | + | ||
| 14 | +`TURBO_PYTHON_DIR` overrides the directory the user-level file is looked for in. The project file is always `.turbo-python/acp.toml` under the directory the editor was started in — there is no walk up the tree, for the same reason [project settings](project-settings.md) do not walk up. | ||
| 15 | + | ||
| 16 | +## File format | ||
| 17 | + | ||
| 18 | +One `[[agent]]` block per agent, in the order you want them in the menu. | ||
| 19 | + | ||
| 20 | +```toml | ||
| 21 | +[[agent]] | ||
| 22 | +name = "Bob (llama.cpp)" | ||
| 23 | +command = "docker" | ||
| 24 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | ||
| 25 | +env = { TELEMETRY_ENABLED = "false" } | ||
| 26 | +cwd = "." | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +| Key | Type | Required | Meaning | | ||
| 30 | +| --- | --- | --- | --- | | ||
| 31 | +| `name` | string | **yes** | What the Agent menu shows and what the window is titled. Must be unique within the merged set. | | ||
| 32 | +| `command` | string | **yes** | The executable to run. Looked up on `PATH` unless it contains a separator. | | ||
| 33 | +| `args` | list of strings | no | Its arguments, passed as given — no shell, so no quoting, globbing or `&&`. | | ||
| 34 | +| `env` | table of strings | no | Environment variables added to the ones the editor was started with. A name given here wins. | | ||
| 35 | +| `cwd` | string | no | Where the process starts, and the `cwd` the agent is told about. Relative to the project root. Defaults to the project root. | | ||
| 36 | + | ||
| 37 | +`env` may also be written as a sub-table, which is the same thing: | ||
| 38 | + | ||
| 39 | +```toml | ||
| 40 | +[[agent]] | ||
| 41 | +name = "Bob (llama.cpp)" | ||
| 42 | +command = "docker" | ||
| 43 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | ||
| 44 | + | ||
| 45 | +[agent.env] | ||
| 46 | +TELEMETRY_ENABLED = "false" | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +### What is refused | ||
| 50 | + | ||
| 51 | +The file is refused as a whole, rather than partly loaded, when any of these hold. A half-loaded menu offering three of your five agents is worse than an error saying why. | ||
| 52 | + | ||
| 53 | +| Problem | Message | | ||
| 54 | +| --- | --- | | ||
| 55 | +| an agent with no `name` | `reading …/acp.toml: agent 1 has no name` | | ||
| 56 | +| an agent with no `command` | `reading …/acp.toml: agent "Bob" has no command` | | ||
| 57 | +| two agents with the same `name` | `reading …/acp.toml: two agents are called "Bob"` | | ||
| 58 | +| a key the format does not define | `reading …/acp.toml: agent.comand is not a key this file has` | | ||
| 59 | + | ||
| 60 | +The last one is deliberate: a misspelt key that was quietly ignored would look exactly like one that had no effect. | ||
| 61 | + | ||
| 62 | +## The Agent menu | ||
| 63 | + | ||
| 64 | +`Alt-A` opens it. It is on the bar whether or not any agent is configured, because that is where **Create agents file** has to be reachable from. | ||
| 65 | + | ||
| 66 | +| Item | Enabled when | Effect | | ||
| 67 | +| --- | --- | --- | | ||
| 68 | +| *one item per agent, by name* | always | Start that agent and open a window on it | | ||
| 69 | +| **Create agents file** | no `acp.toml` in the project | Write the starter file and open it | | ||
| 70 | +| **Cancel turn** | a turn is running in the front window | `session/cancel` | | ||
| 71 | +| **Agent status** | always | What was loaded, what each command line is, and what failed | | ||
| 72 | + | ||
| 73 | +## Keys inside an agent window | ||
| 74 | + | ||
| 75 | +An agent window is an ordinary window: `F6`, `Alt-1`…`Alt-9`, Tile, Maximise, `[x]` and `[■]` all work on it. Inside it: | ||
| 76 | + | ||
| 77 | +| Key | Effect | | ||
| 78 | +| --- | --- | | ||
| 79 | +| `Enter` | Send the input box as a prompt | | ||
| 80 | +| `Alt-Enter` | Insert a newline in the input box | | ||
| 81 | +| `Tab` | Move focus between the conversation and the input box | | ||
| 82 | +| `Ctrl-C`, `Ctrl-Ins` | Copy the selection, or the block the cursor is on | | ||
| 83 | +| `Esc` | Drop the selection; with none, cancel the turn in progress | | ||
| 84 | +| `Ctrl-W` | Close the window and stop the agent | | ||
| 85 | + | ||
| 86 | +With the **input box** focused: | ||
| 87 | + | ||
| 88 | +| Key | Effect | | ||
| 89 | +| --- | --- | | ||
| 90 | +| `↑` `↓` `←` `→` `Home` `End` | Move the cursor in what you are typing | | ||
| 91 | +| `Backspace` `Delete` | Edit it; backspace at the start of a line joins it to the one above | | ||
| 92 | +| `/` as the first character | Open the list of the agent's commands — see [Commands and mentions](#commands-and-mentions) | | ||
| 93 | +| `@` | Open the list of the project's files, narrowed by what you type after it | | ||
| 94 | +| `↑` `↓` `PgUp` `PgDn`, list open | Move through the list | | ||
| 95 | +| `Tab`, list open | Take the highlighted entry | | ||
| 96 | +| `Enter`, list open | Take the highlighted entry; on a word that is already complete, send | | ||
| 97 | +| `Esc`, list open | Close the list until the text changes | | ||
| 98 | + | ||
| 99 | +With the **conversation** focused: | ||
| 100 | + | ||
| 101 | +| Key | Effect | | ||
| 102 | +| --- | --- | | ||
| 103 | +| `↑` `↓` | Move the cursor one line | | ||
| 104 | +| `PgUp` `PgDn` | Move it a screenful | | ||
| 105 | +| `Home` `End` | The start of the conversation, and the end | | ||
| 106 | +| `Shift-` any of those | Extend the selection instead | | ||
| 107 | +| Drag with button 1 | Select by hand | | ||
| 108 | +| Wheel | Scroll three lines, leaving the cursor where it is | | ||
| 109 | + | ||
| 110 | +Unlike a terminal window, an agent window does **not** take the editor's shortcuts: there is no shell to need `Ctrl-F`, so it keeps its usual meaning. `Ctrl-C` is the exception, and only because nothing else in an agent window wants it. | ||
| 111 | + | ||
| 112 | +## Commands and mentions | ||
| 113 | + | ||
| 114 | +Two characters open a list over the bottom of the conversation while you type. They are the same two Zed uses, so an agent's own documentation — "type `/web` to search" — holds here too. | ||
| 115 | + | ||
| 116 | +### `/` — the agent's commands | ||
| 117 | + | ||
| 118 | +An agent may announce commands with `available_commands_update`, at the start of the session or at any point during it. Typing `/` as the **first character** of the box lists them: the name, the agent's description, and, in angle brackets, what it expects after the name when it expects something. Keep typing to narrow the list; the match is on the start of the name and ignores case. | ||
| 119 | + | ||
| 120 | +`Tab` completes the highlighted command. A command that takes input is completed with a trailing space, so the next thing you type is its argument; one that takes none is completed to the bare name. `Enter` completes too, except on a word that already reads exactly as a command, where it sends. | ||
| 121 | + | ||
| 122 | +On the wire a command is **text**: `/web agent client protocol` goes out as one text block, and the agent recognises it by its first word. That is the whole protocol for commands, and it is why a `/` anywhere but the start of the box is just a character. | ||
| 123 | + | ||
| 124 | +With no commands announced, `/` is a character and `Tab` keeps its ordinary meaning. **Agent ▸ Agent status** lists the commands with their descriptions. | ||
| 125 | + | ||
| 126 | +### `@` — a file from the project | ||
| 127 | + | ||
| 128 | +Typing `@` anywhere in the box lists the project's files, relative to the project root with forward slashes. What you type after the `@` narrows the list: files whose own name begins with it come first, then files whose path merely contains it. `Tab` or `Enter` completes the highlighted one and adds a space. | ||
| 129 | + | ||
| 130 | +When the prompt is sent, each `@name` that names a file the list knew becomes a content block **in place of the name**: | ||
| 131 | + | ||
| 132 | +| The agent declared | The block sent | | ||
| 133 | +| --- | --- | | ||
| 134 | +| `promptCapabilities.embeddedContext: true` | `resource` — the file's `uri`, `mimeType` and full `text`, read the way `fs/read_text_file` reads it: from the open buffer when the file is open and modified | | ||
| 135 | +| anything else, or the file could not be read | `resource_link` — the `uri`, `name` and `mimeType`, for the agent to fetch itself | | ||
| 136 | + | ||
| 137 | +The words either side go as text blocks, so `explain @docs/README.md please` is three blocks: `explain `, the file, ` please`. The conversation keeps the line as you typed it. | ||
| 138 | + | ||
| 139 | +A word that begins with `@` and names no file stays text — an e-mail address in a prompt is not a file — and `@main.go` does not name `main.gopher`: the name has to end the word. | ||
| 140 | + | ||
| 141 | +The list is the project walked from its root, `.git` left out, at most 5 000 files, and at most 200 of them shown at once. Past either limit, type one more letter. It is walked afresh each time `@` opens the list, so a file the agent just created is in it. | ||
| 142 | + | ||
| 143 | +## Copying | ||
| 144 | + | ||
| 145 | +Selection is by **whole lines**. Nothing in a conversation is edited, so half a line is never what somebody means, and whole lines keep a copied code block's indentation intact. | ||
| 146 | + | ||
| 147 | +With nothing selected, copying takes the **region the cursor is on**: one fenced code block, one passage of prose, one tool call's output. A speaker's label and a tool call's heading are furniture and are regions of their own, so neither is ever copied with what it sits above. | ||
| 148 | + | ||
| 149 | +The indentation the conversation is drawn with is removed, so pasted code is flush. | ||
| 150 | + | ||
| 151 | +The text goes to two places at once: | ||
| 152 | + | ||
| 153 | +| Clipboard | How | Pasted with | | ||
| 154 | +| --- | --- | --- | | ||
| 155 | +| The editor's | directly | `Shift-Ins`, into a file open here | | ||
| 156 | +| The system's | OSC 52, through the terminal | `Ctrl-V`, anywhere else | | ||
| 157 | + | ||
| 158 | +Nothing checks whether the terminal accepted the second: there is no reply to check, and a terminal may refuse OSC 52 for security or need it turned on. The editor's own clipboard has the text either way, and the status bar says how many lines were copied. | ||
| 159 | + | ||
| 160 | +## How much of the protocol is implemented | ||
| 161 | + | ||
| 162 | +Protocol version **1**. Turbo Python sends its version in `initialize` and accepts whatever version the agent answers with, provided it is one it knows. | ||
| 163 | + | ||
| 164 | +### What the editor calls on the agent | ||
| 165 | + | ||
| 166 | +| Method | Implemented | Notes | | ||
| 167 | +| --- | --- | --- | | ||
| 168 | +| `initialize` | yes | Advertises the `fs` capability below; `terminal` is not advertised | | ||
| 169 | +| `session/new` | yes | `cwd` from the agent's `cwd` key; `mcpServers` is always empty — MCP servers are the agent's own business | | ||
| 170 | +| `session/prompt` | yes | Text blocks, and one `resource` or `resource_link` block per file named with `@` — see [Commands and mentions](#commands-and-mentions) | | ||
| 171 | +| `session/cancel` | yes | `Esc`, and **Agent ▸ Cancel turn** | | ||
| 172 | +| `session/load` | **no** | Conversations do not survive closing the window | | ||
| 173 | +| `authenticate` | **no** | An agent that lists `authMethods` is reported as needing a login the editor cannot perform | | ||
| 174 | + | ||
| 175 | +### What the agent may call on the editor | ||
| 176 | + | ||
| 177 | +| Method | Implemented | Notes | | ||
| 178 | +| --- | --- | --- | | ||
| 179 | +| `session/update` | yes | See the table below | | ||
| 180 | +| `session/request_permission` | yes | A modal dialog carrying the agent's own options | | ||
| 181 | +| `fs/read_text_file` | yes | From the open buffer when the file is open and modified, otherwise from disk | | ||
| 182 | +| `fs/write_text_file` | yes | Into the open buffer when the file is open, otherwise to disk | | ||
| 183 | +| `terminal/*` | **no** | Not advertised, so a conforming agent will not ask | | ||
| 184 | + | ||
| 185 | +### Session updates | ||
| 186 | + | ||
| 187 | +| `sessionUpdate` | Shown as | | ||
| 188 | +| --- | --- | | ||
| 189 | +| `agent_message_chunk` | The agent's reply, appended as it arrives | | ||
| 190 | +| `agent_thought_chunk` | The same, in the comment colour, under a *thinking* label | | ||
| 191 | +| `user_message_chunk` | Your own message, as the agent echoes it back | | ||
| 192 | +| `tool_call` | A line naming the tool and its title, with its status | | ||
| 193 | +| `tool_call_update` | Folded onto the line the `toolCallId` matches, carrying its output | | ||
| 194 | +| `plan` | The entries as a list, each with its status | | ||
| 195 | +| `available_commands_update` | The list `/` opens in the input box; also listed, with descriptions, by **Agent ▸ Agent status** | | ||
| 196 | +| `usage_update` | The token count on the status bar while the window is in front | | ||
| 197 | +| anything else | Ignored, and counted; the count is in **Agent status** | | ||
| 198 | + | ||
| 199 | +While a turn is running, the rule between the panes turns a spinner. It is drawn from the clock rather than from a counter, so two windows thinking at once turn in step and nothing has to be reset when a turn begins. The window's *title* deliberately does not animate: it is also what the window list and the `Alt`-digit menu show, and a name changing eight times a second makes both flicker. | ||
| 200 | + | ||
| 201 | +An unknown update is ignored rather than refused: the protocol grows, and an editor that stopped talking to an agent because it learnt a new kind of message would be wrong more often than it was right. | ||
| 202 | + | ||
| 203 | +## Colouring | ||
| 204 | + | ||
| 205 | +The conversation is drawn with keys every theme already sets, so none of them needed touching: | ||
| 206 | + | ||
| 207 | +| Part | Class | | ||
| 208 | +| --- | --- | | ||
| 209 | +| A speaker's name | `syntax.keyword` | | ||
| 210 | +| A thought | `syntax.comment` | | ||
| 211 | +| A tool call and its status | `syntax.type` | | ||
| 212 | +| A failed tool call, and the editor's own notices | `diagnostic.error` | | ||
| 213 | +| A selected line, and the cursor's bar | `editor.selection` | | ||
| 214 | +| Code inside a fence | the scanner for the fence's language | | ||
| 215 | +| Everything else | the window's plain text | | ||
| 216 | + | ||
| 217 | +A fenced block naming a language the editor colours — `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash` — is coloured by that scanner. One naming anything else, or nothing at all, is left plain. | ||
| 218 | + | ||
| 219 | +## Tracing the conversation with an agent | ||
| 220 | + | ||
| 221 | +| Variable | Effect | | ||
| 222 | +| --- | --- | | ||
| 223 | +| `TURBO_ACP_TRACE=<file>` | Append every message to and from every agent to that file, one per line, stamped with the time and marked `->` (sent) or `<-` (received) | | ||
| 224 | + | ||
| 225 | +It is for the one question the screen cannot answer — *what did the agent actually send?* An update this editor cannot decode is counted under **Agent ▸ Agent status**, which also names the last one and its error; the trace shows the message itself. A file that cannot be opened means no trace and nothing else: the trace is never allowed to break the editor. | ||
| 226 | + | ||
| 227 | +## Limits | ||
| 228 | + | ||
| 229 | +- **One session per window.** Closing the window ends the session; there is no resume. | ||
| 230 | +- **Text and files only.** The editor sends text, and the files you name with `@`; not images or audio, whatever the agent's `promptCapabilities` say. | ||
| 231 | +- **No authentication.** An agent that requires a login must be logged in by its own CLI before the editor starts it. | ||
| 232 | +- **`args` are not a shell command.** `command = "sh"`, `args = ["-c", "…"]` is how to get one deliberately. | ||
| 233 | +- **One entry is capped** at a megabyte of text. An agent printing a whole build log cannot make the window unusable; what was dropped is said in the entry itself. | ||
| 234 | + | ||
| 235 | +## See also | ||
| 236 | + | ||
| 237 | +- The task: [How to talk to a coding agent from the editor](../how-to/talk-to-an-agent.md) | ||
| 238 | +- The reasoning: [Agent windows](../explanation/agent-windows.md) | ||
| 239 | +- The protocol: [agentclientprotocol.com](https://agentclientprotocol.com) | ||
added
docs/en/reference/cli.md +100 -0 | new file mode 100644 | ||
| @@ -0,0 +1,100 @@ | ||
| 1 | +# Reference: command line | |
| 2 | + | |
| 3 | +> Neutral description of the `turbo-python` command, its flags, and the environment it reads. | |
| 4 | + | |
| 5 | +## Synopsis | |
| 6 | + | |
| 7 | +``` | |
| 8 | +turbo-python [flags] [file...] | |
| 9 | +``` | |
| 10 | + | |
| 11 | +Each `file` is opened in its own window. A file that does not exist yet is opened as an empty buffer bound to that path. With no file at all, one empty untitled window is opened. | |
| 12 | + | |
| 13 | +## Flags | |
| 14 | + | |
| 15 | +| Flag | Type | Default | Description | | |
| 16 | +| --- | --- | --- | --- | | |
| 17 | +| `-theme <name>` | string | the project's, else `turbo-classic` | Theme to start with, overriding the project's own. An unknown name falls back to the default without an error. | | |
| 18 | +| `-list-themes` | bool | `false` | Print every loadable theme with its description, then the user theme directory, and exit. | | |
| 19 | +| `-no-lsp` | bool | `false` | Do not start a language server. Colouring and editing are unaffected. | | |
| 20 | +| `-version` | bool | `false` | Print `Turbo Python <version>` on one line, with the commit and build date when the build recorded them, and exit. See [the version number](versioning.md). | | |
| 21 | +| `-h`, `-help` | bool | `false` | Print the flag list and exit. | | |
| 22 | + | |
| 23 | +## Environment | |
| 24 | + | |
| 25 | +| Variable | Read by | Effect | | |
| 26 | +| --- | --- | --- | | |
| 27 | +| `TURBO_PYTHON_THEME_DIR` | theme loading | Directory to read user themes from, instead of the platform configuration directory. | | |
| 28 | +| `TERM` | tcell | Which terminal description to use. | | |
| 29 | +| `GOBIN`, `GOPATH`, `HOME` | pylsp lookup | Searched, in that order, when `pylsp` is not on `PATH`. | | |
| 30 | + | |
| 31 | +## Files | |
| 32 | + | |
| 33 | +| Path | Purpose | | |
| 34 | +| --- | --- | | |
| 35 | +| `$TURBO_PYTHON_THEME_DIR/*.toml` | User themes, when the variable is set. | | |
| 36 | +| `./.turbo-python/settings.toml` | This project's settings, read once at start-up. See [project settings](project-settings.md). | | |
| 37 | +| `~/.config/turbo-python/themes/*.toml` | User themes on Linux (`os.UserConfigDir`). | | |
| 38 | +| `~/Library/Application Support/turbo-python/themes/*.toml` | User themes on macOS. | | |
| 39 | +| `<module>/pyproject.toml` | Located by walking up from the first file; its directory becomes the language server's root. | | |
| 40 | + | |
| 41 | +## Exit status | |
| 42 | + | |
| 43 | +| Status | Meaning | | |
| 44 | +| --- | --- | | |
| 45 | +| `0` | The editor exited normally, or an informational flag was used. | | |
| 46 | +| `1` | The terminal could not be opened or initialised. The reason is printed to standard error. | | |
| 47 | + | |
| 48 | +## Make targets | |
| 49 | + | |
| 50 | +Run from a checkout. | |
| 51 | + | |
| 52 | +| Target | What it runs | | |
| 53 | +| --- | --- | | |
| 54 | +| `make help` | List the targets. This is the default. | | |
| 55 | +| `make test` | `uv run pytest` | | |
| 56 | +| `make test-verbose` | `go test -v ./...` | | |
| 57 | +| `make cover` | `go test -cover ./...` | | |
| 58 | +| `make build` | `go build -o bin/turbo-python .` | | |
| 59 | +| `make install` | `scripts/install.sh` — build and install onto your PATH | | |
| 60 | +| `make uninstall` | `scripts/install.sh --uninstall` | | |
| 61 | +| `make run FILE=x.go` | `make build`, then `./bin/turbo-python x.go` | | |
| 62 | +| `make fmt` | `go fmt ./...` | | |
| 63 | +| `make vet` | `uv run ruff check .` | | |
| 64 | +| `make check` | `fmt`, then `vet`, then `test` | | |
| 65 | +| `make clean` | Remove `bin/` | | |
| 66 | + | |
| 67 | +## Examples | |
| 68 | + | |
| 69 | +```bash | |
| 70 | +turbo-python # one empty window | |
| 71 | +turbo-python main.py pyproject.toml # two windows | |
| 72 | +turbo-python -theme turbo-dark main.py # a different theme | |
| 73 | +turbo-python -no-lsp main.py # no language server | |
| 74 | +turbo-python -list-themes # what themes exist | |
| 75 | +``` | |
| 76 | + | |
| 77 | +## Installer | |
| 78 | + | |
| 79 | +`scripts/install.sh`, also reachable as `make install`. | |
| 80 | + | |
| 81 | +| Option | Description | | |
| 82 | +| --- | --- | | |
| 83 | +| `-p`, `--prefix DIR` | Install into `DIR` instead of `$GOBIN` or `$GOPATH/bin`. | | |
| 84 | +| `--with-pylsp` | Install `pylsp` as well, if it is not already there. | | |
| 85 | +| `--uninstall` | Remove an installed `turbo-python` and stop. | | |
| 86 | +| `-h`, `--help` | Print the options and stop. | | |
| 87 | + | |
| 88 | +| Exit status | Meaning | | |
| 89 | +| --- | --- | | |
| 90 | +| `0` | Installed, removed, or help printed. | | |
| 91 | +| `1` | Go missing or too old, the build failed, or the destination could not be written. Nothing is installed and an existing installation is left untouched. | | |
| 92 | + | |
| 93 | +## Errors | |
| 94 | + | |
| 95 | +| Message | Cause | | |
| 96 | +| --- | --- | | |
| 97 | +| `turbo-python: opening the terminal: …` | tcell could not open the terminal; usually `TERM` is unset or unknown. | | |
| 98 | +| `turbo-python: initialising the terminal: …` | The terminal was opened but could not be put into raw mode. | | |
| 99 | +| `Cannot open` (in a dialog) | The path is a directory, or is not readable. | | |
| 100 | +| `Cannot save` (in a dialog) | The directory does not exist, or is not writable. | | |
| new file mode 100644 | |||
| @@ -0,0 +1,100 @@ | |||
| 1 | +# Reference: command line | ||
| 2 | + | ||
| 3 | +> Neutral description of the `turbo-python` command, its flags, and the environment it reads. | ||
| 4 | + | ||
| 5 | +## Synopsis | ||
| 6 | + | ||
| 7 | +``` | ||
| 8 | +turbo-python [flags] [file...] | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +Each `file` is opened in its own window. A file that does not exist yet is opened as an empty buffer bound to that path. With no file at all, one empty untitled window is opened. | ||
| 12 | + | ||
| 13 | +## Flags | ||
| 14 | + | ||
| 15 | +| Flag | Type | Default | Description | | ||
| 16 | +| --- | --- | --- | --- | | ||
| 17 | +| `-theme <name>` | string | the project's, else `turbo-classic` | Theme to start with, overriding the project's own. An unknown name falls back to the default without an error. | | ||
| 18 | +| `-list-themes` | bool | `false` | Print every loadable theme with its description, then the user theme directory, and exit. | | ||
| 19 | +| `-no-lsp` | bool | `false` | Do not start a language server. Colouring and editing are unaffected. | | ||
| 20 | +| `-version` | bool | `false` | Print `Turbo Python <version>` on one line, with the commit and build date when the build recorded them, and exit. See [the version number](versioning.md). | | ||
| 21 | +| `-h`, `-help` | bool | `false` | Print the flag list and exit. | | ||
| 22 | + | ||
| 23 | +## Environment | ||
| 24 | + | ||
| 25 | +| Variable | Read by | Effect | | ||
| 26 | +| --- | --- | --- | | ||
| 27 | +| `TURBO_PYTHON_THEME_DIR` | theme loading | Directory to read user themes from, instead of the platform configuration directory. | | ||
| 28 | +| `TERM` | tcell | Which terminal description to use. | | ||
| 29 | +| `GOBIN`, `GOPATH`, `HOME` | pylsp lookup | Searched, in that order, when `pylsp` is not on `PATH`. | | ||
| 30 | + | ||
| 31 | +## Files | ||
| 32 | + | ||
| 33 | +| Path | Purpose | | ||
| 34 | +| --- | --- | | ||
| 35 | +| `$TURBO_PYTHON_THEME_DIR/*.toml` | User themes, when the variable is set. | | ||
| 36 | +| `./.turbo-python/settings.toml` | This project's settings, read once at start-up. See [project settings](project-settings.md). | | ||
| 37 | +| `~/.config/turbo-python/themes/*.toml` | User themes on Linux (`os.UserConfigDir`). | | ||
| 38 | +| `~/Library/Application Support/turbo-python/themes/*.toml` | User themes on macOS. | | ||
| 39 | +| `<module>/pyproject.toml` | Located by walking up from the first file; its directory becomes the language server's root. | | ||
| 40 | + | ||
| 41 | +## Exit status | ||
| 42 | + | ||
| 43 | +| Status | Meaning | | ||
| 44 | +| --- | --- | | ||
| 45 | +| `0` | The editor exited normally, or an informational flag was used. | | ||
| 46 | +| `1` | The terminal could not be opened or initialised. The reason is printed to standard error. | | ||
| 47 | + | ||
| 48 | +## Make targets | ||
| 49 | + | ||
| 50 | +Run from a checkout. | ||
| 51 | + | ||
| 52 | +| Target | What it runs | | ||
| 53 | +| --- | --- | | ||
| 54 | +| `make help` | List the targets. This is the default. | | ||
| 55 | +| `make test` | `uv run pytest` | | ||
| 56 | +| `make test-verbose` | `go test -v ./...` | | ||
| 57 | +| `make cover` | `go test -cover ./...` | | ||
| 58 | +| `make build` | `go build -o bin/turbo-python .` | | ||
| 59 | +| `make install` | `scripts/install.sh` — build and install onto your PATH | | ||
| 60 | +| `make uninstall` | `scripts/install.sh --uninstall` | | ||
| 61 | +| `make run FILE=x.go` | `make build`, then `./bin/turbo-python x.go` | | ||
| 62 | +| `make fmt` | `go fmt ./...` | | ||
| 63 | +| `make vet` | `uv run ruff check .` | | ||
| 64 | +| `make check` | `fmt`, then `vet`, then `test` | | ||
| 65 | +| `make clean` | Remove `bin/` | | ||
| 66 | + | ||
| 67 | +## Examples | ||
| 68 | + | ||
| 69 | +```bash | ||
| 70 | +turbo-python # one empty window | ||
| 71 | +turbo-python main.py pyproject.toml # two windows | ||
| 72 | +turbo-python -theme turbo-dark main.py # a different theme | ||
| 73 | +turbo-python -no-lsp main.py # no language server | ||
| 74 | +turbo-python -list-themes # what themes exist | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +## Installer | ||
| 78 | + | ||
| 79 | +`scripts/install.sh`, also reachable as `make install`. | ||
| 80 | + | ||
| 81 | +| Option | Description | | ||
| 82 | +| --- | --- | | ||
| 83 | +| `-p`, `--prefix DIR` | Install into `DIR` instead of `$GOBIN` or `$GOPATH/bin`. | | ||
| 84 | +| `--with-pylsp` | Install `pylsp` as well, if it is not already there. | | ||
| 85 | +| `--uninstall` | Remove an installed `turbo-python` and stop. | | ||
| 86 | +| `-h`, `--help` | Print the options and stop. | | ||
| 87 | + | ||
| 88 | +| Exit status | Meaning | | ||
| 89 | +| --- | --- | | ||
| 90 | +| `0` | Installed, removed, or help printed. | | ||
| 91 | +| `1` | Go missing or too old, the build failed, or the destination could not be written. Nothing is installed and an existing installation is left untouched. | | ||
| 92 | + | ||
| 93 | +## Errors | ||
| 94 | + | ||
| 95 | +| Message | Cause | | ||
| 96 | +| --- | --- | | ||
| 97 | +| `turbo-python: opening the terminal: …` | tcell could not open the terminal; usually `TERM` is unset or unknown. | | ||
| 98 | +| `turbo-python: initialising the terminal: …` | The terminal was opened but could not be put into raw mode. | | ||
| 99 | +| `Cannot open` (in a dialog) | The path is a directory, or is not readable. | | ||
| 100 | +| `Cannot save` (in a dialog) | The directory does not exist, or is not writable. | | ||
added
docs/en/reference/keyboard.md +187 -0 | new file mode 100644 | ||
| @@ -0,0 +1,187 @@ | ||
| 1 | +# Reference: keyboard | |
| 2 | + | |
| 3 | +> Complete list of the keys Turbo Python answers to, grouped by what has the focus. | |
| 4 | + | |
| 5 | +Where two spellings exist, both work: the Turbo C one and the modern one. | |
| 6 | + | |
| 7 | +## Global | |
| 8 | + | |
| 9 | +Handled wherever the focus is, unless a dialog or the completion popup is open. | |
| 10 | + | |
| 11 | +| Key | Action | | |
| 12 | +| --- | --- | | |
| 13 | +| `F1` | Describe the symbol under the cursor; with no file open, show the keyboard help | | |
| 14 | +| `F2` | Save | | |
| 15 | +| `F3` | Open | | |
| 16 | +| `F4` | New | | |
| 17 | +| `F6` | Next window | | |
| 18 | +| `F7` | Find next | | |
| 19 | +| `Shift-F7` | Find previous | | |
| 20 | +| `F8` | Open a terminal window | | |
| 21 | +| `F9` | Open the project tree | | |
| 22 | +| `F10` | Open the menu bar | | |
| 23 | +| `F12` | Go to definition | | |
| 24 | +| `Shift-F12` | Find references | | |
| 25 | +| `Ctrl-T` | Find a symbol anywhere in the project | | |
| 26 | +| `Ctrl-F` | Find | | |
| 27 | +| `Ctrl-G` | Go to line | | |
| 28 | +| `Ctrl-W` | Close the current window | | |
| 29 | +| `Alt-X` | Exit | | |
| 30 | +| `Alt-1` … `Alt-9` | Bring window 1…9 forward | | |
| 31 | +| `Alt-0` | List the open windows | | |
| 32 | +| `Alt-N` | Open the Snippets menu | | |
| 33 | +| `Alt-P` | Open the Python menu | | |
| 34 | +| `Alt-<letter>` | Open the menu whose title carries that letter | | |
| 35 | + | |
| 36 | +A menu the project's tools file adds gets its letter assigned rather than fixed, so it is never one of the above. The rules are in [Python tools](python-tools.md#hot-keys). | |
| 37 | + | |
| 38 | +## Editing | |
| 39 | + | |
| 40 | +Handled by the window that has the focus. | |
| 41 | + | |
| 42 | +### Movement | |
| 43 | + | |
| 44 | +| Key | Action | | |
| 45 | +| --- | --- | | |
| 46 | +| `←` `→` `↑` `↓` | One character or one line | | |
| 47 | +| `Ctrl-←` `Ctrl-→` | Start of the previous / next word | | |
| 48 | +| `Home` `End` | Start / end of the line | | |
| 49 | +| `Ctrl-Home` `Ctrl-End` | Start / end of the file | | |
| 50 | +| `PgUp` `PgDn` | One screenful | | |
| 51 | +| `Shift` + any of the above | The same movement, extending the selection | | |
| 52 | + | |
| 53 | +### Changing the text | |
| 54 | + | |
| 55 | +| Key | Action | | |
| 56 | +| --- | --- | | |
| 57 | +| any printable character | Insert it, replacing the selection | | |
| 58 | +| `Enter` | Split the line, copying the current line's indentation | | |
| 59 | +| `Backspace` | Delete the selection, or the character before the cursor | | |
| 60 | +| `Delete` | Delete the selection, or the character under the cursor | | |
| 61 | +| `Tab` | Insert a tab; with a selection, indent every line it touches | | |
| 62 | +| `Shift-Tab` | Remove one level of indentation from every line the selection touches | | |
| 63 | + | |
| 64 | +### Clipboard and history | |
| 65 | + | |
| 66 | +| Key | Also | Action | | |
| 67 | +| --- | --- | --- | | |
| 68 | +| `Ctrl-C` | `Ctrl-Ins` | Copy the selection | | |
| 69 | +| `Ctrl-X` | `Shift-Del` | Cut the selection | | |
| 70 | +| `Ctrl-V` | `Shift-Ins` | Paste | | |
| 71 | +| `Ctrl-A` | | Select the whole file | | |
| 72 | +| `Ctrl-Z` | | Undo | | |
| 73 | +| `Ctrl-R` | | Redo | | |
| 74 | +| `Ctrl-N` | | Insert a blank line above the cursor | | |
| 75 | +| `Ctrl-Y` | | Delete the line the cursor is on | | |
| 76 | + | |
| 77 | +A run of typed characters, or a run of backspaces, is a **single** undo step. Moving the cursor ends the run. | |
| 78 | + | |
| 79 | +### Language server | |
| 80 | + | |
| 81 | +| Key | Action | | |
| 82 | +| --- | --- | | |
| 83 | +| `Ctrl-Space` | Ask for a completion list | | |
| 84 | +| `.` | Ask for a completion list, as a side effect of typing it | | |
| 85 | +| `F1` | Describe the symbol under the cursor | | |
| 86 | +| `F12` | Go to the declaration | | |
| 87 | + | |
| 88 | +## Menu bar | |
| 89 | + | |
| 90 | +Once a menu is open. | |
| 91 | + | |
| 92 | +| Key | Action | | |
| 93 | +| --- | --- | | |
| 94 | +| `←` `→` | Previous / next menu | | |
| 95 | +| `↑` `↓` | Previous / next item, skipping separators and disabled items | | |
| 96 | +| `Enter` | Run the highlighted item | | |
| 97 | +| `<letter>` | Run the item whose label carries that letter | | |
| 98 | +| `Escape` | Close the menu | | |
| 99 | + | |
| 100 | +An item marked `▶` opens a submenu instead of running: | |
| 101 | + | |
| 102 | +| Key | Action | | |
| 103 | +| --- | --- | | |
| 104 | +| `→`, `Enter` | Open the highlighted submenu; `→` on an item without one moves to the next menu | | |
| 105 | +| `←` | Step back out to the parent menu | | |
| 106 | +| `Escape` | Close the whole menu, wherever you are | | |
| 107 | +| `↑` `↓` | Walk the submenu | | |
| 108 | +| `<letter>` | Run the submenu item whose label carries that letter | | |
| 109 | + | |
| 110 | +Any other key is swallowed, so stray typing never reaches the file behind. | |
| 111 | + | |
| 112 | +## Dialogs | |
| 113 | + | |
| 114 | +| Key | Action | | |
| 115 | +| --- | --- | | |
| 116 | +| `Tab` / `Shift-Tab` | Next / previous control | | |
| 117 | +| `↑` `↓` | Walk the focused list; when the focused control has no use for them, the next / previous control | | |
| 118 | +| `Enter` | Press the default button, from wherever the focus is | | |
| 119 | +| `Escape` | Cancel | | |
| 120 | +| `Alt-<letter>` | Press the button whose label carries that letter | | |
| 121 | +| `Ctrl-U` | Clear the focused input field | | |
| 122 | + | |
| 123 | +A dialog is modal: every key it does not use is swallowed rather than passed to the editor behind it. | |
| 124 | + | |
| 125 | +### The Open and Save As box | |
| 126 | + | |
| 127 | +| | | | |
| 128 | +| --- | --- | | |
| 129 | +| Focus on opening | The **Name** field, so a name can be typed straight away. The first `↓` therefore moves the focus to the list; the second moves the highlight. | | |
| 130 | +| Moving the highlight | Puts that entry's name into the **Name** field, so the field always says what **OK** will act on. Highlighting `../` clears it. | | |
| 131 | +| `Enter` on the list | Opens the highlighted file, or browses into the highlighted directory | | |
| 132 | +| **OK** | Acts on the **Name** field; when the field is empty, acts on whatever the list has highlighted | | |
| 133 | +| A name that is a directory | Browses into it rather than closing the dialog | | |
| 134 | +| Double click | The same as `Enter` on that entry | | |
| 135 | + | |
| 136 | +Dot-files are not listed. Directories come before files, each group sorted, with `../` first. | |
| 137 | + | |
| 138 | +## Completion popup | |
| 139 | + | |
| 140 | +| Key | Action | | |
| 141 | +| --- | --- | | |
| 142 | +| `↑` `↓` | Previous / next suggestion | | |
| 143 | +| `PgUp` `PgDn` | Eight at a time | | |
| 144 | +| `Enter`, `Tab` | Accept the highlighted suggestion | | |
| 145 | +| `Escape` | Dismiss the list | | |
| 146 | +| any printable character | Passed through to the editor; the list narrows to what still matches | | |
| 147 | + | |
| 148 | +## Terminal windows | |
| 149 | + | |
| 150 | +A terminal window in front gets **every key except** the function keys, `Alt-X` and `Alt-0`…`Alt-9`, which stay with the editor so there is always a way out of a full-screen program. `Ctrl-C`, `Ctrl-W`, `Ctrl-F` and `Alt-<letter>` therefore reach the shell rather than the editor. | |
| 151 | + | |
| 152 | +| Key | Action | | |
| 153 | +| --- | --- | | |
| 154 | +| `Shift-PgUp` `Shift-PgDn` | Read back / forward one screenful through the history | | |
| 155 | +| anything else not reserved above | Sent to the shell, returning the view to the live screen | | |
| 156 | + | |
| 157 | +The exact byte each key sends is in [Terminal windows](terminal.md). | |
| 158 | + | |
| 159 | +## Project tree | |
| 160 | + | |
| 161 | +Handled when the tree window has the focus. The full rules are in [Project tree](project-tree.md). | |
| 162 | + | |
| 163 | +| Key | Action | | |
| 164 | +| --- | --- | | |
| 165 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Move the highlight | | |
| 166 | +| `→` | Expand a closed directory, else step to the next row | | |
| 167 | +| `←` | Collapse an open directory, else step out to its directory | | |
| 168 | +| `Enter` | Open a file; expand or collapse a directory | | |
| 169 | +| `F5`, `Ctrl-R` | Re-read the project | | |
| 170 | + | |
| 171 | +## Mouse | |
| 172 | + | |
| 173 | +| Action | Effect | | |
| 174 | +| --- | --- | | |
| 175 | +| Click in the text | Place the cursor | | |
| 176 | +| Drag in the text | Select | | |
| 177 | +| Wheel | Scroll three lines | | |
| 178 | +| Click a menu title | Open or close that menu | | |
| 179 | +| Click a status-bar hint | Run it | | |
| 180 | +| Click a window | Bring it forward | | |
| 181 | +| Drag a title bar | Move the window | | |
| 182 | +| Drag the bottom-right corner | Resize the window | | |
| 183 | +| Click `[x]` | Close the window | | |
| 184 | +| Click `[■]` | Fill the desktop with the window | | |
| 185 | +| Click `[▬]` | Put a filled window back where it was | | |
| 186 | +| Wheel over a terminal | Scroll three lines through its history | | |
| 187 | +| Click a tree row | Highlight it; a second click opens it | | |
| new file mode 100644 | |||
| @@ -0,0 +1,187 @@ | |||
| 1 | +# Reference: keyboard | ||
| 2 | + | ||
| 3 | +> Complete list of the keys Turbo Python answers to, grouped by what has the focus. | ||
| 4 | + | ||
| 5 | +Where two spellings exist, both work: the Turbo C one and the modern one. | ||
| 6 | + | ||
| 7 | +## Global | ||
| 8 | + | ||
| 9 | +Handled wherever the focus is, unless a dialog or the completion popup is open. | ||
| 10 | + | ||
| 11 | +| Key | Action | | ||
| 12 | +| --- | --- | | ||
| 13 | +| `F1` | Describe the symbol under the cursor; with no file open, show the keyboard help | | ||
| 14 | +| `F2` | Save | | ||
| 15 | +| `F3` | Open | | ||
| 16 | +| `F4` | New | | ||
| 17 | +| `F6` | Next window | | ||
| 18 | +| `F7` | Find next | | ||
| 19 | +| `Shift-F7` | Find previous | | ||
| 20 | +| `F8` | Open a terminal window | | ||
| 21 | +| `F9` | Open the project tree | | ||
| 22 | +| `F10` | Open the menu bar | | ||
| 23 | +| `F12` | Go to definition | | ||
| 24 | +| `Shift-F12` | Find references | | ||
| 25 | +| `Ctrl-T` | Find a symbol anywhere in the project | | ||
| 26 | +| `Ctrl-F` | Find | | ||
| 27 | +| `Ctrl-G` | Go to line | | ||
| 28 | +| `Ctrl-W` | Close the current window | | ||
| 29 | +| `Alt-X` | Exit | | ||
| 30 | +| `Alt-1` … `Alt-9` | Bring window 1…9 forward | | ||
| 31 | +| `Alt-0` | List the open windows | | ||
| 32 | +| `Alt-N` | Open the Snippets menu | | ||
| 33 | +| `Alt-P` | Open the Python menu | | ||
| 34 | +| `Alt-<letter>` | Open the menu whose title carries that letter | | ||
| 35 | + | ||
| 36 | +A menu the project's tools file adds gets its letter assigned rather than fixed, so it is never one of the above. The rules are in [Python tools](python-tools.md#hot-keys). | ||
| 37 | + | ||
| 38 | +## Editing | ||
| 39 | + | ||
| 40 | +Handled by the window that has the focus. | ||
| 41 | + | ||
| 42 | +### Movement | ||
| 43 | + | ||
| 44 | +| Key | Action | | ||
| 45 | +| --- | --- | | ||
| 46 | +| `←` `→` `↑` `↓` | One character or one line | | ||
| 47 | +| `Ctrl-←` `Ctrl-→` | Start of the previous / next word | | ||
| 48 | +| `Home` `End` | Start / end of the line | | ||
| 49 | +| `Ctrl-Home` `Ctrl-End` | Start / end of the file | | ||
| 50 | +| `PgUp` `PgDn` | One screenful | | ||
| 51 | +| `Shift` + any of the above | The same movement, extending the selection | | ||
| 52 | + | ||
| 53 | +### Changing the text | ||
| 54 | + | ||
| 55 | +| Key | Action | | ||
| 56 | +| --- | --- | | ||
| 57 | +| any printable character | Insert it, replacing the selection | | ||
| 58 | +| `Enter` | Split the line, copying the current line's indentation | | ||
| 59 | +| `Backspace` | Delete the selection, or the character before the cursor | | ||
| 60 | +| `Delete` | Delete the selection, or the character under the cursor | | ||
| 61 | +| `Tab` | Insert a tab; with a selection, indent every line it touches | | ||
| 62 | +| `Shift-Tab` | Remove one level of indentation from every line the selection touches | | ||
| 63 | + | ||
| 64 | +### Clipboard and history | ||
| 65 | + | ||
| 66 | +| Key | Also | Action | | ||
| 67 | +| --- | --- | --- | | ||
| 68 | +| `Ctrl-C` | `Ctrl-Ins` | Copy the selection | | ||
| 69 | +| `Ctrl-X` | `Shift-Del` | Cut the selection | | ||
| 70 | +| `Ctrl-V` | `Shift-Ins` | Paste | | ||
| 71 | +| `Ctrl-A` | | Select the whole file | | ||
| 72 | +| `Ctrl-Z` | | Undo | | ||
| 73 | +| `Ctrl-R` | | Redo | | ||
| 74 | +| `Ctrl-N` | | Insert a blank line above the cursor | | ||
| 75 | +| `Ctrl-Y` | | Delete the line the cursor is on | | ||
| 76 | + | ||
| 77 | +A run of typed characters, or a run of backspaces, is a **single** undo step. Moving the cursor ends the run. | ||
| 78 | + | ||
| 79 | +### Language server | ||
| 80 | + | ||
| 81 | +| Key | Action | | ||
| 82 | +| --- | --- | | ||
| 83 | +| `Ctrl-Space` | Ask for a completion list | | ||
| 84 | +| `.` | Ask for a completion list, as a side effect of typing it | | ||
| 85 | +| `F1` | Describe the symbol under the cursor | | ||
| 86 | +| `F12` | Go to the declaration | | ||
| 87 | + | ||
| 88 | +## Menu bar | ||
| 89 | + | ||
| 90 | +Once a menu is open. | ||
| 91 | + | ||
| 92 | +| Key | Action | | ||
| 93 | +| --- | --- | | ||
| 94 | +| `←` `→` | Previous / next menu | | ||
| 95 | +| `↑` `↓` | Previous / next item, skipping separators and disabled items | | ||
| 96 | +| `Enter` | Run the highlighted item | | ||
| 97 | +| `<letter>` | Run the item whose label carries that letter | | ||
| 98 | +| `Escape` | Close the menu | | ||
| 99 | + | ||
| 100 | +An item marked `▶` opens a submenu instead of running: | ||
| 101 | + | ||
| 102 | +| Key | Action | | ||
| 103 | +| --- | --- | | ||
| 104 | +| `→`, `Enter` | Open the highlighted submenu; `→` on an item without one moves to the next menu | | ||
| 105 | +| `←` | Step back out to the parent menu | | ||
| 106 | +| `Escape` | Close the whole menu, wherever you are | | ||
| 107 | +| `↑` `↓` | Walk the submenu | | ||
| 108 | +| `<letter>` | Run the submenu item whose label carries that letter | | ||
| 109 | + | ||
| 110 | +Any other key is swallowed, so stray typing never reaches the file behind. | ||
| 111 | + | ||
| 112 | +## Dialogs | ||
| 113 | + | ||
| 114 | +| Key | Action | | ||
| 115 | +| --- | --- | | ||
| 116 | +| `Tab` / `Shift-Tab` | Next / previous control | | ||
| 117 | +| `↑` `↓` | Walk the focused list; when the focused control has no use for them, the next / previous control | | ||
| 118 | +| `Enter` | Press the default button, from wherever the focus is | | ||
| 119 | +| `Escape` | Cancel | | ||
| 120 | +| `Alt-<letter>` | Press the button whose label carries that letter | | ||
| 121 | +| `Ctrl-U` | Clear the focused input field | | ||
| 122 | + | ||
| 123 | +A dialog is modal: every key it does not use is swallowed rather than passed to the editor behind it. | ||
| 124 | + | ||
| 125 | +### The Open and Save As box | ||
| 126 | + | ||
| 127 | +| | | | ||
| 128 | +| --- | --- | | ||
| 129 | +| Focus on opening | The **Name** field, so a name can be typed straight away. The first `↓` therefore moves the focus to the list; the second moves the highlight. | | ||
| 130 | +| Moving the highlight | Puts that entry's name into the **Name** field, so the field always says what **OK** will act on. Highlighting `../` clears it. | | ||
| 131 | +| `Enter` on the list | Opens the highlighted file, or browses into the highlighted directory | | ||
| 132 | +| **OK** | Acts on the **Name** field; when the field is empty, acts on whatever the list has highlighted | | ||
| 133 | +| A name that is a directory | Browses into it rather than closing the dialog | | ||
| 134 | +| Double click | The same as `Enter` on that entry | | ||
| 135 | + | ||
| 136 | +Dot-files are not listed. Directories come before files, each group sorted, with `../` first. | ||
| 137 | + | ||
| 138 | +## Completion popup | ||
| 139 | + | ||
| 140 | +| Key | Action | | ||
| 141 | +| --- | --- | | ||
| 142 | +| `↑` `↓` | Previous / next suggestion | | ||
| 143 | +| `PgUp` `PgDn` | Eight at a time | | ||
| 144 | +| `Enter`, `Tab` | Accept the highlighted suggestion | | ||
| 145 | +| `Escape` | Dismiss the list | | ||
| 146 | +| any printable character | Passed through to the editor; the list narrows to what still matches | | ||
| 147 | + | ||
| 148 | +## Terminal windows | ||
| 149 | + | ||
| 150 | +A terminal window in front gets **every key except** the function keys, `Alt-X` and `Alt-0`…`Alt-9`, which stay with the editor so there is always a way out of a full-screen program. `Ctrl-C`, `Ctrl-W`, `Ctrl-F` and `Alt-<letter>` therefore reach the shell rather than the editor. | ||
| 151 | + | ||
| 152 | +| Key | Action | | ||
| 153 | +| --- | --- | | ||
| 154 | +| `Shift-PgUp` `Shift-PgDn` | Read back / forward one screenful through the history | | ||
| 155 | +| anything else not reserved above | Sent to the shell, returning the view to the live screen | | ||
| 156 | + | ||
| 157 | +The exact byte each key sends is in [Terminal windows](terminal.md). | ||
| 158 | + | ||
| 159 | +## Project tree | ||
| 160 | + | ||
| 161 | +Handled when the tree window has the focus. The full rules are in [Project tree](project-tree.md). | ||
| 162 | + | ||
| 163 | +| Key | Action | | ||
| 164 | +| --- | --- | | ||
| 165 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Move the highlight | | ||
| 166 | +| `→` | Expand a closed directory, else step to the next row | | ||
| 167 | +| `←` | Collapse an open directory, else step out to its directory | | ||
| 168 | +| `Enter` | Open a file; expand or collapse a directory | | ||
| 169 | +| `F5`, `Ctrl-R` | Re-read the project | | ||
| 170 | + | ||
| 171 | +## Mouse | ||
| 172 | + | ||
| 173 | +| Action | Effect | | ||
| 174 | +| --- | --- | | ||
| 175 | +| Click in the text | Place the cursor | | ||
| 176 | +| Drag in the text | Select | | ||
| 177 | +| Wheel | Scroll three lines | | ||
| 178 | +| Click a menu title | Open or close that menu | | ||
| 179 | +| Click a status-bar hint | Run it | | ||
| 180 | +| Click a window | Bring it forward | | ||
| 181 | +| Drag a title bar | Move the window | | ||
| 182 | +| Drag the bottom-right corner | Resize the window | | ||
| 183 | +| Click `[x]` | Close the window | | ||
| 184 | +| Click `[■]` | Fill the desktop with the window | | ||
| 185 | +| Click `[▬]` | Put a filled window back where it was | | ||
| 186 | +| Wheel over a terminal | Scroll three lines through its history | | ||
| 187 | +| Click a tree row | Highlight it; a second click opens it | | ||
added
docs/en/reference/languages.md +289 -0 | new file mode 100644 | ||
| @@ -0,0 +1,289 @@ | ||
| 1 | +# Reference: languages coloured | |
| 2 | + | |
| 3 | +> Neutral description of which files Turbo Python colours, how it decides, and what each scanner recognises. | |
| 4 | + | |
| 5 | +## Recognition | |
| 6 | + | |
| 7 | +A file's **extension** decides whenever it is one of these: | |
| 8 | + | |
| 9 | +| Extension | Language | | |
| 10 | +| --- | --- | | |
| 11 | +| `.py`, `.pyi`, `.pyw` | Python | | |
| 12 | +| `.toml` | TOML | | |
| 13 | +| `.yaml`, `.yml` | YAML | | |
| 14 | +| `.md`, `.markdown` | Markdown | | |
| 15 | +| `.js`, `.mjs`, `.cjs` | JavaScript | | |
| 16 | +| `.html`, `.htm` | HTML | | |
| 17 | +| `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, `.plist`, `.csproj`, `.pom` | XML | | |
| 18 | +| `.sh`, `.bash`, `.zsh` | Shell | | |
| 19 | +| `.dockerfile`, `.containerfile` | Dockerfile | | |
| 20 | + | |
| 21 | +Extensions are matched case-insensitively, and only the last one counts: `main.py.backup` is not Python. | |
| 22 | + | |
| 23 | +A file whose extension decides nothing is looked up by **name** next. Only files that carry no useful extension need this: | |
| 24 | + | |
| 25 | +| Name | Language | | |
| 26 | +| --- | --- | | |
| 27 | +| `Dockerfile`, `Containerfile` | Dockerfile | | |
| 28 | + | |
| 29 | +A name matches on the whole of it or on the part before the first dot, ignoring case — so `Dockerfile`, `dockerfile` and `Dockerfile.dev` are all recognised, while `Dockerfile.md` is Markdown, because the extension is consulted first. | |
| 30 | + | |
| 31 | +A file that neither table claims is read by its **first line**. A shebang naming `python` or `python3` makes it Python, and one naming a shell — `sh`, `bash`, `zsh`, `dash` or `ksh` — makes it a shell script. The interpreter is recognised as a path element or as the argument to `env`. That is what colours a script in a `bin` directory, a git hook, or `configure`. | |
| 32 | + | |
| 33 | +| First line | Result | | |
| 34 | +| --- | --- | | |
| 35 | +| `#!/bin/sh` | Shell | | |
| 36 | +| `#!/usr/bin/env bash` | Shell | | |
| 37 | +| `#!/usr/bin/env -S bash -e` | Shell | | |
| 38 | +| `#!/usr/bin/env python3` | Python | | |
| 39 | +| `#!/usr/bin/python` | Python | | |
| 40 | +| `#!/usr/bin/env node` | Not coloured | | |
| 41 | +| Anything not starting `#!` | Not coloured | | |
| 42 | + | |
| 43 | +The order is fixed — extension, then name, then first line — and the first to decide wins: a `.md` file starting with a Python shebang is Markdown. | |
| 44 | + | |
| 45 | +Everything else is shown in plain text. That is not an error — opening a PNG in the editor is not a mistake, it is just not coloured. | |
| 46 | + | |
| 47 | +## Classes | |
| 48 | + | |
| 49 | +Every scanner produces the same vocabulary of classes, and each maps to one theme key. | |
| 50 | + | |
| 51 | +| Class | Theme key | Produced by | | |
| 52 | +| --- | --- | --- | | |
| 53 | +| `identifier` | `syntax.identifier` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 54 | +| `keyword` | `syntax.keyword` | Python, JavaScript, shell, HTML (doctype), XML, Dockerfile | | |
| 55 | +| `type` | `syntax.type` | Python, TOML (table headers), YAML (tags) | | |
| 56 | +| `builtin` | `syntax.builtin` | Python (builtins, `self`, dunders), JavaScript, shell (builtins and expansions), YAML (anchors and aliases), Dockerfile (variables) | | |
| 57 | +| `constant` | `syntax.constant` | Python, TOML, JavaScript, shell, YAML, HTML and XML (entities) | | |
| 58 | +| `function` | `syntax.function` | Python, JavaScript, shell (the command) | | |
| 59 | +| `string` | `syntax.string` | all | | |
| 60 | +| `char` | `syntax.char` | nothing here; the class exists for languages that have a character type, and Python has none | | |
| 61 | +| `number` | `syntax.number` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 62 | +| `comment` | `syntax.comment` | Python, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | |
| 63 | +| `operator` | `syntax.operator` | Python, TOML, JavaScript, shell, HTML, YAML (block scalar headers), XML, Dockerfile | | |
| 64 | +| `punctuation` | `syntax.punctuation` | Python, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | |
| 65 | +| `heading` | `syntax.heading` | Markdown | | |
| 66 | +| `tag` | `syntax.tag` | HTML, XML | | |
| 67 | +| `attribute` | `syntax.attribute` | Python (decorators), HTML, XML, Dockerfile (flags) | | |
| 68 | +| `emphasis` | `syntax.emphasis` | Markdown | | |
| 69 | +| `link` | `syntax.link` | Markdown | | |
| 70 | + | |
| 71 | +## Python | |
| 72 | + | |
| 73 | +Hand-written, in `internal/pythonlang`. **Only a string crosses a line break**, and it does so in two ways: a triple-quoted one runs until the matching three quotes, and a single-quoted one runs on only when the line ends with a backslash. Which quote opened it is carried, because a literal opened with three double quotes and one opened with three apostrophes are different strings. | |
| 74 | + | |
| 75 | +| Recognised | As | | |
| 76 | +| --- | --- | | |
| 77 | +| `and`, `as`, `assert`, `async`, `await`, `break`, `class`, `continue`, `def`, `del`, `elif`, `else`, `except`, `finally`, `for`, `from`, `global`, `if`, `import`, `in`, `is`, `lambda`, `nonlocal`, `not`, `or`, `pass`, `raise`, `return`, `try`, `while`, `with`, `yield` | keyword | | |
| 78 | +| `match` and `case`, when they open the line and the line ends with `:` | keyword | | |
| 79 | +| `True`, `False`, `None`, `NotImplemented`, `Ellipsis`, `__debug__` | constant | | |
| 80 | +| `bool`, `bytearray`, `bytes`, `complex`, `dict`, `float`, `frozenset`, `int`, `list`, `memoryview`, `object`, `range`, `set`, `slice`, `str`, `tuple`, `type` | type | | |
| 81 | +| any other name starting with a capital — `ValueError`, `Measurement` | type | | |
| 82 | +| a name written wholly in capitals — `MAX_SIZE`, `PI`, `HTTP_PORT` | constant | | |
| 83 | +| `__init__`, `__repr__`, `__name__` and every other dunder | builtin | | |
| 84 | +| `print`, `len`, `open`, `sorted`, `isinstance`, … and `self`, `cls` | builtin | | |
| 85 | +| any other name immediately before `(` | function | | |
| 86 | +| `"…"` and `'…'`, with any prefix: `r`, `b`, `u`, `f`, `rb`, `br`, `fr`, `rf`, in either case | string | | |
| 87 | +| `"""…"""` and `'''…'''`, across as many lines as they take | string | | |
| 88 | +| a single-quoted string whose line ends with a backslash, onto the next line | string | | |
| 89 | +| `42`, `1_000`, `0xFF`, `0o17`, `0b1010`, `.5`, `1.`, `1.5e-3`, `1E+7`, `3j` | number | | |
| 90 | +| `#` to the end of the line, the shebang included | comment | | |
| 91 | +| `@property`, `@app.route`, `@pytest.mark.parametrize` — the name only | attribute | | |
| 92 | +| `:=` | operator | | |
| 93 | +| `:` everywhere else — a block, a slice, a dict, an annotation | punctuation | | |
| 94 | +| `@` anywhere but the start of a line | operator | | |
| 95 | +| a `\` ending a line | punctuation | | |
| 96 | +| runs of `+-*/%=<>!&\|^~?` | operator | | |
| 97 | +| `()[]{},;.` | punctuation | | |
| 98 | + | |
| 99 | +**`match` and `case` are keywords only where a match statement puts them.** They are reserved in no context at all — `match = re.match(pattern, text)` is ordinary Python — so the shape of the statement decides: the word opens the line, and the line ends with the colon that opens its block. Both conditions have to hold. | |
| 100 | + | |
| 101 | +**A name written wholly in capitals is a constant, and any other capitalised name is a type.** PEP 8 separates the two conventions clearly enough to read them: `MAX_SIZE` is a constant and `Measurement` is a class. Turbo Rust has only the second rule and documents `SCREAMING_SNAKE_CASE` as a known wrong answer; here that answer is worth removing rather than inheriting. | |
| 102 | + | |
| 103 | +**A capitalised name is a type even when it is called.** `ValueError("nope")` and `parse("nope")` are the same shape, because a class is called exactly the way a function is — so the parenthesis cannot tell them apart and the convention has to. This is the one rule Turbo Python and Turbo Rust order differently. | |
| 104 | + | |
| 105 | +**`self` and `cls` are coloured as builtins although the language does not name them.** They are a convention: a method may call its first parameter anything. But every Python reader reads `self` as the language's, the way a Rust reader reads `Some`, and every other highlighter agrees. The cost is a parameter honestly named `self` in a plain function being coloured too. | |
| 106 | + | |
| 107 | +**A decorator stops at its arguments.** `@pytest.mark.parametrize("n", [1, 2])` colours the dotted name as an attribute and the rest as ordinary Python, so the string and the list inside it keep their own colours. | |
| 108 | + | |
| 109 | +**A backslash takes the rune after it out of consideration in a raw string too.** `r"\""` is one complete string: in a raw string the backslash stays in the value, but it still stops the quote after it from ending the literal. Termination is the same rule for both, which is why rawness is not carried between lines. | |
| 110 | + | |
| 111 | +**A string that reaches the end of a line without either of the two reasons to carry on is dropped there.** It is coloured to the end of that line and the next line is code again — because a single-quoted string with no closing quote is source in the middle of being typed, and carrying it would paint the rest of the file. | |
| 112 | + | |
| 113 | +**Not recognised**, each for a stated reason: | |
| 114 | + | |
| 115 | +| Not recognised | Because | | |
| 116 | +| --- | --- | | |
| 117 | +| The `{expression}` inside an f-string | Since Python 3.12 it may hold anything — nested quotes, comments, another f-string. One flat run of string is the honest answer; colouring it half-properly ends `f"{n:{width}}"` at the inner brace | | |
| 118 | +| `match` or `case` on a line with a trailing comment | The colon is found by reading backwards from the end of the line, and a comment hides it, so `match value: # dispatch` colours `match` as a name. That is the safe direction to be wrong in | | |
| 119 | +| A docstring as anything but a string | It *is* a string — `help()` reads it back as one — and colouring it as a comment would be wrong the moment one is assigned to a name | | |
| 120 | +| A class whose name is all capitals | `HTTP` is coloured as a constant. That is the price of `MAX_SIZE` being coloured correctly, and the trade goes the way the commoner case does | | |
| 121 | +| `type` as the soft keyword of `type Alias = int` | It is also a builtin type, and reading as the type is right in both of its jobs | | |
| 122 | +| Whether a name is bound in this scope | Nothing here reads more than one line at a time; that is the language server's question, and [F1 answers it](../how-to/ask-about-code.md) | | |
| 123 | + | |
| 124 | +## TOML | |
| 125 | + | |
| 126 | +| Recognised | As | | |
| 127 | +| --- | --- | | |
| 128 | +| `# comment` | comment | | |
| 129 | +| `[table]`, `[[array]]` | the name as a type, the brackets as punctuation | | |
| 130 | +| `key =` | identifier, then operator | | |
| 131 | +| `"basic"`, `'literal'`, `"""multi-line"""`, `'''multi-line'''` | string | | |
| 132 | +| `true`, `false` | constant | | |
| 133 | +| numbers, dates, times, `inf`, `nan` | number | | |
| 134 | + | |
| 135 | +## YAML | |
| 136 | + | |
| 137 | +A compose file, a Kubernetes manifest and a CI workflow are all this: there is no separate dialect, because a dialect would be somebody else's schema to keep in step with. | |
| 138 | + | |
| 139 | +| Recognised | As | | |
| 140 | +| --- | --- | | |
| 141 | +| `# comment` | comment | | |
| 142 | +| `key:` before a space or the end of the line | the key as an identifier, the colon as punctuation | | |
| 143 | +| `"quoted": 1`, `'quoted': 1` | the quoted key as an identifier | | |
| 144 | +| `- ` opening a sequence entry | punctuation | | |
| 145 | +| `"…"`, `'…'` | string | | |
| 146 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constant, whatever their case | | |
| 147 | +| numbers, dates and times written without quotes | number | | |
| 148 | +| `&anchor`, `*alias` | builtin | | |
| 149 | +| `!!str`, `!Custom` | type | | |
| 150 | +| `---`, `...` | the whole line as punctuation | | |
| 151 | +| `{`, `}`, `[`, `]`, `,` | punctuation | | |
| 152 | +| `\|`, `>`, with their chomping and indentation indicators | the header as an operator, the body as a string | | |
| 153 | + | |
| 154 | +**A colon is a separator only when a space or the end of the line follows it.** `image: nginx:1.27` is a key and one value, and `url: http://example.com/x` is a key and one URL — colouring the inner colons as separators would put every image tag and every URL in three colours. | |
| 155 | + | |
| 156 | +**A block scalar's extent is decided by indentation**, not by a delimiter. The first content line after `|` or `>` fixes the block's indentation; every line indented at least that far belongs to it, and the first line that is not ends it. **A blank line inside a block stays inside it**: a literal scalar keeps its empty lines, and ending the block at the first paragraph break would cut a shell script in a CI file in half. | |
| 157 | + | |
| 158 | +**A `#` needs a space before it to start a comment**, so `colour: ff#00aa` is one scalar. | |
| 159 | + | |
| 160 | +| Not recognised | Because | | |
| 161 | +| --- | --- | | |
| 162 | +| The schema of a compose file, a manifest or a workflow | Colouring `services:` differently from any other key means carrying somebody else's schema, and it goes stale the day they add a key | | |
| 163 | +| Multi-document streams as separate documents | `---` is coloured, but nothing is reset at it; nothing in the colouring depends on document boundaries | | |
| 164 | +| Whether a bare word is a string or a number to a parser | `1.2.3` is a version to a reader and a string to YAML; the scanner colours what it looks like | | |
| 165 | + | |
| 166 | +## Markdown | |
| 167 | + | |
| 168 | +| Recognised | As | | |
| 169 | +| --- | --- | | |
| 170 | +| `# Heading` … `###### Heading` | the whole line as a heading | | |
| 171 | +| `**bold**`, `__bold__`, `*italic*`, `_italic_` | emphasis | | |
| 172 | +| `` `code` `` | string | | |
| 173 | +| `[text](target)`, `` | the whole thing as a link | | |
| 174 | +| `- `, `* `, `+ `, `1. `, `1) ` | the marker as punctuation | | |
| 175 | +| `>` | punctuation | | |
| 176 | +| `---`, `***`, `___` | punctuation | | |
| 177 | +| ` ``` ` and `~~~` fences | the whole block, opening and closing lines included, as a string | | |
| 178 | + | |
| 179 | +A fenced block is **one colour whatever language it announces**: ```` ```python ```` does not colour its contents as Python. The run of markers that opens a block must be matched by the same character to close it, so a backtick fence is not closed by a tilde one. An unclosed fence colours to the end of the file. | |
| 180 | + | |
| 181 | +The run of markers opening emphasis must be matched by a run of the same length, so `**bold**` is one span rather than two italics. | |
| 182 | + | |
| 183 | +## JavaScript | |
| 184 | + | |
| 185 | +| Recognised | As | | |
| 186 | +| --- | --- | | |
| 187 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | |
| 188 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | |
| 189 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | |
| 190 | +| a name immediately before `(` | function | | |
| 191 | +| `"…"`, `'…'` | string | | |
| 192 | +| `` `…` ``, interpolations included, across lines | string | | |
| 193 | +| `//` to end of line, `/* … */` across lines | comment | | |
| 194 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | |
| 195 | +| runs of `+-*/%=<>!&|^~?:` | operator | | |
| 196 | +| `()[]{},;.` | punctuation | | |
| 197 | + | |
| 198 | +**Regular-expression literals are not recognised.** Telling `/x/g` from a division needs to know whether the previous token could end an expression; a wrong guess colours the rest of a line as a string, which is worse than leaving a regex the colour of an operator. | |
| 199 | + | |
| 200 | +Globals are recognised by name, so a file that shadows `Math` still has it coloured as a builtin — the same rule Python's builtins follow here. | |
| 201 | + | |
| 202 | +## HTML | |
| 203 | + | |
| 204 | +| Recognised | As | | |
| 205 | +| --- | --- | | |
| 206 | +| `<tag`, `</tag`, `>`, `/>` | tag | | |
| 207 | +| attribute names, including `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | |
| 208 | +| `=` | operator | | |
| 209 | +| `"…"`, `'…'` | string | | |
| 210 | +| `<!-- … -->`, across lines | comment | | |
| 211 | +| `&`, `©` | constant | | |
| 212 | +| `<!DOCTYPE …>` and other declarations | keyword | | |
| 213 | + | |
| 214 | +Text between tags is not coloured. A bare `&` with no `;` within 32 characters is left alone, because it is legal text. | |
| 215 | + | |
| 216 | +**The contents of `<script>` and `<style>` are not coloured** as JavaScript and CSS. | |
| 217 | + | |
| 218 | +## XML | |
| 219 | + | |
| 220 | +Its own scanner rather than HTML's, for one reason that matters: CDATA. The whole point of `<![CDATA[ … ]]>` is that its contents are *not* markup, and colouring the tags inside one as tags is exactly backwards. | |
| 221 | + | |
| 222 | +| Recognised | As | | |
| 223 | +| --- | --- | | |
| 224 | +| `<?xml version="1.0"?>` and other processing instructions | the target and `?>` as keyword, the pairs between as attributes and strings | | |
| 225 | +| `<!DOCTYPE …>` and the other `<!` forms | keyword | | |
| 226 | +| `<!-- … -->`, across lines | comment | | |
| 227 | +| `<![CDATA[ … ]]>`, across lines | string | | |
| 228 | +| `<tag`, `</tag`, `>`, `/>` | tag | | |
| 229 | +| `<ns:tag>`, `xsi:type` | the prefix and the local name as **one** span | | |
| 230 | +| attribute names | attribute | | |
| 231 | +| `=` | operator | | |
| 232 | +| `"…"`, `'…'` | string | | |
| 233 | +| `&`, `©` | constant | | |
| 234 | + | |
| 235 | +**A comment and a CDATA section close on different delimiters**, and are carried separately: a `-->` inside a CDATA section does not end it. | |
| 236 | + | |
| 237 | +**A bare `&` with no semicolon within 32 characters is left alone**, because it is legal text in plenty of documents and swallowing the rest of the line would be the bigger mistake. | |
| 238 | + | |
| 239 | +Text between tags is not coloured. | |
| 240 | + | |
| 241 | +## Shell | |
| 242 | + | |
| 243 | +Applies to `sh`, `bash` and `zsh` alike: the keywords recognised are the ones they share. | |
| 244 | + | |
| 245 | +| Recognised | As | | |
| 246 | +| --- | --- | | |
| 247 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | |
| 248 | +| `true`, `false` | constant | | |
| 249 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | |
| 250 | +| `$NAME`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | |
| 251 | +| the **first bare word on a line** | function | | |
| 252 | +| every later bare word, and `NAME` in `NAME=value` | identifier | | |
| 253 | +| `'…'`, with nothing escaped or expanded inside | string | | |
| 254 | +| `"…"`, with the expansions inside it coloured as expansions | string | | |
| 255 | +| `#` to end of line | comment | | |
| 256 | + | |
| 257 | +`$(a $(b) c)` is one span: nesting is counted. An option such as `-euo` is one word, not a minus and a word. | |
| 258 | + | |
| 259 | +**Heredocs are not recognised.** `<<EOF` and the text after it are coloured as ordinary shell. | |
| 260 | + | |
| 261 | +## Dockerfile | |
| 262 | + | |
| 263 | +| Recognised | As | | |
| 264 | +| --- | --- | | |
| 265 | +| `FROM`, `RUN`, `COPY`, `ADD`, `ARG`, `ENV`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `LABEL`, `USER`, `VOLUME`, `WORKDIR`, `HEALTHCHECK`, `ONBUILD`, `SHELL`, `STOPSIGNAL`, `MAINTAINER` | keyword, in any case | | |
| 266 | +| `AS`, `NONE` | keyword | | |
| 267 | +| `# comment`, including the `# syntax=` and `# escape=` directives | comment | | |
| 268 | +| `--from=builder`, `--chown=me:me` | the flag name as an attribute | | |
| 269 | +| `$NAME`, `${NAME}`, `${NAME:-default}` | builtin, as one span to the closing brace | | |
| 270 | +| `"…"`, `'…'` | string | | |
| 271 | +| a trailing `\` | operator | | |
| 272 | +| numbers | number | | |
| 273 | +| paths and image references — `/usr/local/bin`, `golang:1.26-alpine` | identifier, as **one** span | | |
| 274 | + | |
| 275 | +**Only the first word of a line can be an instruction**, and a word that is not one is an argument — which is what keeps a continuation line's first word out of the keyword colour. | |
| 276 | + | |
| 277 | +**Nothing crosses a line break.** A `\` joins two lines for Docker, but each half still reads as a command and is coloured on its own. | |
| 278 | + | |
| 279 | +| Not recognised | Because | | |
| 280 | +| --- | --- | | |
| 281 | +| The shell inside a `RUN` | It would mean running the shell scanner over part of a line and mapping its columns out, and `RUN` may hold any language | | |
| 282 | +| Heredocs in a `RUN` | The same reason the shell scanner does not recognise them | | |
| 283 | +| Which stage a `--from` names | Nothing here reads the rest of the file | | |
| 284 | + | |
| 285 | +## See also | |
| 286 | + | |
| 287 | +- [Theme file format](themes.md) — every key these classes resolve to | |
| 288 | +- [Colouring and completion](../explanation/colouring-and-completion.md) — why the scanners are written this way | |
| 289 | +- [How to write your own theme](../how-to/write-a-theme.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,289 @@ | |||
| 1 | +# Reference: languages coloured | ||
| 2 | + | ||
| 3 | +> Neutral description of which files Turbo Python colours, how it decides, and what each scanner recognises. | ||
| 4 | + | ||
| 5 | +## Recognition | ||
| 6 | + | ||
| 7 | +A file's **extension** decides whenever it is one of these: | ||
| 8 | + | ||
| 9 | +| Extension | Language | | ||
| 10 | +| --- | --- | | ||
| 11 | +| `.py`, `.pyi`, `.pyw` | Python | | ||
| 12 | +| `.toml` | TOML | | ||
| 13 | +| `.yaml`, `.yml` | YAML | | ||
| 14 | +| `.md`, `.markdown` | Markdown | | ||
| 15 | +| `.js`, `.mjs`, `.cjs` | JavaScript | | ||
| 16 | +| `.html`, `.htm` | HTML | | ||
| 17 | +| `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, `.plist`, `.csproj`, `.pom` | XML | | ||
| 18 | +| `.sh`, `.bash`, `.zsh` | Shell | | ||
| 19 | +| `.dockerfile`, `.containerfile` | Dockerfile | | ||
| 20 | + | ||
| 21 | +Extensions are matched case-insensitively, and only the last one counts: `main.py.backup` is not Python. | ||
| 22 | + | ||
| 23 | +A file whose extension decides nothing is looked up by **name** next. Only files that carry no useful extension need this: | ||
| 24 | + | ||
| 25 | +| Name | Language | | ||
| 26 | +| --- | --- | | ||
| 27 | +| `Dockerfile`, `Containerfile` | Dockerfile | | ||
| 28 | + | ||
| 29 | +A name matches on the whole of it or on the part before the first dot, ignoring case — so `Dockerfile`, `dockerfile` and `Dockerfile.dev` are all recognised, while `Dockerfile.md` is Markdown, because the extension is consulted first. | ||
| 30 | + | ||
| 31 | +A file that neither table claims is read by its **first line**. A shebang naming `python` or `python3` makes it Python, and one naming a shell — `sh`, `bash`, `zsh`, `dash` or `ksh` — makes it a shell script. The interpreter is recognised as a path element or as the argument to `env`. That is what colours a script in a `bin` directory, a git hook, or `configure`. | ||
| 32 | + | ||
| 33 | +| First line | Result | | ||
| 34 | +| --- | --- | | ||
| 35 | +| `#!/bin/sh` | Shell | | ||
| 36 | +| `#!/usr/bin/env bash` | Shell | | ||
| 37 | +| `#!/usr/bin/env -S bash -e` | Shell | | ||
| 38 | +| `#!/usr/bin/env python3` | Python | | ||
| 39 | +| `#!/usr/bin/python` | Python | | ||
| 40 | +| `#!/usr/bin/env node` | Not coloured | | ||
| 41 | +| Anything not starting `#!` | Not coloured | | ||
| 42 | + | ||
| 43 | +The order is fixed — extension, then name, then first line — and the first to decide wins: a `.md` file starting with a Python shebang is Markdown. | ||
| 44 | + | ||
| 45 | +Everything else is shown in plain text. That is not an error — opening a PNG in the editor is not a mistake, it is just not coloured. | ||
| 46 | + | ||
| 47 | +## Classes | ||
| 48 | + | ||
| 49 | +Every scanner produces the same vocabulary of classes, and each maps to one theme key. | ||
| 50 | + | ||
| 51 | +| Class | Theme key | Produced by | | ||
| 52 | +| --- | --- | --- | | ||
| 53 | +| `identifier` | `syntax.identifier` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 54 | +| `keyword` | `syntax.keyword` | Python, JavaScript, shell, HTML (doctype), XML, Dockerfile | | ||
| 55 | +| `type` | `syntax.type` | Python, TOML (table headers), YAML (tags) | | ||
| 56 | +| `builtin` | `syntax.builtin` | Python (builtins, `self`, dunders), JavaScript, shell (builtins and expansions), YAML (anchors and aliases), Dockerfile (variables) | | ||
| 57 | +| `constant` | `syntax.constant` | Python, TOML, JavaScript, shell, YAML, HTML and XML (entities) | | ||
| 58 | +| `function` | `syntax.function` | Python, JavaScript, shell (the command) | | ||
| 59 | +| `string` | `syntax.string` | all | | ||
| 60 | +| `char` | `syntax.char` | nothing here; the class exists for languages that have a character type, and Python has none | | ||
| 61 | +| `number` | `syntax.number` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 62 | +| `comment` | `syntax.comment` | Python, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | ||
| 63 | +| `operator` | `syntax.operator` | Python, TOML, JavaScript, shell, HTML, YAML (block scalar headers), XML, Dockerfile | | ||
| 64 | +| `punctuation` | `syntax.punctuation` | Python, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | ||
| 65 | +| `heading` | `syntax.heading` | Markdown | | ||
| 66 | +| `tag` | `syntax.tag` | HTML, XML | | ||
| 67 | +| `attribute` | `syntax.attribute` | Python (decorators), HTML, XML, Dockerfile (flags) | | ||
| 68 | +| `emphasis` | `syntax.emphasis` | Markdown | | ||
| 69 | +| `link` | `syntax.link` | Markdown | | ||
| 70 | + | ||
| 71 | +## Python | ||
| 72 | + | ||
| 73 | +Hand-written, in `internal/pythonlang`. **Only a string crosses a line break**, and it does so in two ways: a triple-quoted one runs until the matching three quotes, and a single-quoted one runs on only when the line ends with a backslash. Which quote opened it is carried, because a literal opened with three double quotes and one opened with three apostrophes are different strings. | ||
| 74 | + | ||
| 75 | +| Recognised | As | | ||
| 76 | +| --- | --- | | ||
| 77 | +| `and`, `as`, `assert`, `async`, `await`, `break`, `class`, `continue`, `def`, `del`, `elif`, `else`, `except`, `finally`, `for`, `from`, `global`, `if`, `import`, `in`, `is`, `lambda`, `nonlocal`, `not`, `or`, `pass`, `raise`, `return`, `try`, `while`, `with`, `yield` | keyword | | ||
| 78 | +| `match` and `case`, when they open the line and the line ends with `:` | keyword | | ||
| 79 | +| `True`, `False`, `None`, `NotImplemented`, `Ellipsis`, `__debug__` | constant | | ||
| 80 | +| `bool`, `bytearray`, `bytes`, `complex`, `dict`, `float`, `frozenset`, `int`, `list`, `memoryview`, `object`, `range`, `set`, `slice`, `str`, `tuple`, `type` | type | | ||
| 81 | +| any other name starting with a capital — `ValueError`, `Measurement` | type | | ||
| 82 | +| a name written wholly in capitals — `MAX_SIZE`, `PI`, `HTTP_PORT` | constant | | ||
| 83 | +| `__init__`, `__repr__`, `__name__` and every other dunder | builtin | | ||
| 84 | +| `print`, `len`, `open`, `sorted`, `isinstance`, … and `self`, `cls` | builtin | | ||
| 85 | +| any other name immediately before `(` | function | | ||
| 86 | +| `"…"` and `'…'`, with any prefix: `r`, `b`, `u`, `f`, `rb`, `br`, `fr`, `rf`, in either case | string | | ||
| 87 | +| `"""…"""` and `'''…'''`, across as many lines as they take | string | | ||
| 88 | +| a single-quoted string whose line ends with a backslash, onto the next line | string | | ||
| 89 | +| `42`, `1_000`, `0xFF`, `0o17`, `0b1010`, `.5`, `1.`, `1.5e-3`, `1E+7`, `3j` | number | | ||
| 90 | +| `#` to the end of the line, the shebang included | comment | | ||
| 91 | +| `@property`, `@app.route`, `@pytest.mark.parametrize` — the name only | attribute | | ||
| 92 | +| `:=` | operator | | ||
| 93 | +| `:` everywhere else — a block, a slice, a dict, an annotation | punctuation | | ||
| 94 | +| `@` anywhere but the start of a line | operator | | ||
| 95 | +| a `\` ending a line | punctuation | | ||
| 96 | +| runs of `+-*/%=<>!&\|^~?` | operator | | ||
| 97 | +| `()[]{},;.` | punctuation | | ||
| 98 | + | ||
| 99 | +**`match` and `case` are keywords only where a match statement puts them.** They are reserved in no context at all — `match = re.match(pattern, text)` is ordinary Python — so the shape of the statement decides: the word opens the line, and the line ends with the colon that opens its block. Both conditions have to hold. | ||
| 100 | + | ||
| 101 | +**A name written wholly in capitals is a constant, and any other capitalised name is a type.** PEP 8 separates the two conventions clearly enough to read them: `MAX_SIZE` is a constant and `Measurement` is a class. Turbo Rust has only the second rule and documents `SCREAMING_SNAKE_CASE` as a known wrong answer; here that answer is worth removing rather than inheriting. | ||
| 102 | + | ||
| 103 | +**A capitalised name is a type even when it is called.** `ValueError("nope")` and `parse("nope")` are the same shape, because a class is called exactly the way a function is — so the parenthesis cannot tell them apart and the convention has to. This is the one rule Turbo Python and Turbo Rust order differently. | ||
| 104 | + | ||
| 105 | +**`self` and `cls` are coloured as builtins although the language does not name them.** They are a convention: a method may call its first parameter anything. But every Python reader reads `self` as the language's, the way a Rust reader reads `Some`, and every other highlighter agrees. The cost is a parameter honestly named `self` in a plain function being coloured too. | ||
| 106 | + | ||
| 107 | +**A decorator stops at its arguments.** `@pytest.mark.parametrize("n", [1, 2])` colours the dotted name as an attribute and the rest as ordinary Python, so the string and the list inside it keep their own colours. | ||
| 108 | + | ||
| 109 | +**A backslash takes the rune after it out of consideration in a raw string too.** `r"\""` is one complete string: in a raw string the backslash stays in the value, but it still stops the quote after it from ending the literal. Termination is the same rule for both, which is why rawness is not carried between lines. | ||
| 110 | + | ||
| 111 | +**A string that reaches the end of a line without either of the two reasons to carry on is dropped there.** It is coloured to the end of that line and the next line is code again — because a single-quoted string with no closing quote is source in the middle of being typed, and carrying it would paint the rest of the file. | ||
| 112 | + | ||
| 113 | +**Not recognised**, each for a stated reason: | ||
| 114 | + | ||
| 115 | +| Not recognised | Because | | ||
| 116 | +| --- | --- | | ||
| 117 | +| The `{expression}` inside an f-string | Since Python 3.12 it may hold anything — nested quotes, comments, another f-string. One flat run of string is the honest answer; colouring it half-properly ends `f"{n:{width}}"` at the inner brace | | ||
| 118 | +| `match` or `case` on a line with a trailing comment | The colon is found by reading backwards from the end of the line, and a comment hides it, so `match value: # dispatch` colours `match` as a name. That is the safe direction to be wrong in | | ||
| 119 | +| A docstring as anything but a string | It *is* a string — `help()` reads it back as one — and colouring it as a comment would be wrong the moment one is assigned to a name | | ||
| 120 | +| A class whose name is all capitals | `HTTP` is coloured as a constant. That is the price of `MAX_SIZE` being coloured correctly, and the trade goes the way the commoner case does | | ||
| 121 | +| `type` as the soft keyword of `type Alias = int` | It is also a builtin type, and reading as the type is right in both of its jobs | | ||
| 122 | +| Whether a name is bound in this scope | Nothing here reads more than one line at a time; that is the language server's question, and [F1 answers it](../how-to/ask-about-code.md) | | ||
| 123 | + | ||
| 124 | +## TOML | ||
| 125 | + | ||
| 126 | +| Recognised | As | | ||
| 127 | +| --- | --- | | ||
| 128 | +| `# comment` | comment | | ||
| 129 | +| `[table]`, `[[array]]` | the name as a type, the brackets as punctuation | | ||
| 130 | +| `key =` | identifier, then operator | | ||
| 131 | +| `"basic"`, `'literal'`, `"""multi-line"""`, `'''multi-line'''` | string | | ||
| 132 | +| `true`, `false` | constant | | ||
| 133 | +| numbers, dates, times, `inf`, `nan` | number | | ||
| 134 | + | ||
| 135 | +## YAML | ||
| 136 | + | ||
| 137 | +A compose file, a Kubernetes manifest and a CI workflow are all this: there is no separate dialect, because a dialect would be somebody else's schema to keep in step with. | ||
| 138 | + | ||
| 139 | +| Recognised | As | | ||
| 140 | +| --- | --- | | ||
| 141 | +| `# comment` | comment | | ||
| 142 | +| `key:` before a space or the end of the line | the key as an identifier, the colon as punctuation | | ||
| 143 | +| `"quoted": 1`, `'quoted': 1` | the quoted key as an identifier | | ||
| 144 | +| `- ` opening a sequence entry | punctuation | | ||
| 145 | +| `"…"`, `'…'` | string | | ||
| 146 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constant, whatever their case | | ||
| 147 | +| numbers, dates and times written without quotes | number | | ||
| 148 | +| `&anchor`, `*alias` | builtin | | ||
| 149 | +| `!!str`, `!Custom` | type | | ||
| 150 | +| `---`, `...` | the whole line as punctuation | | ||
| 151 | +| `{`, `}`, `[`, `]`, `,` | punctuation | | ||
| 152 | +| `\|`, `>`, with their chomping and indentation indicators | the header as an operator, the body as a string | | ||
| 153 | + | ||
| 154 | +**A colon is a separator only when a space or the end of the line follows it.** `image: nginx:1.27` is a key and one value, and `url: http://example.com/x` is a key and one URL — colouring the inner colons as separators would put every image tag and every URL in three colours. | ||
| 155 | + | ||
| 156 | +**A block scalar's extent is decided by indentation**, not by a delimiter. The first content line after `|` or `>` fixes the block's indentation; every line indented at least that far belongs to it, and the first line that is not ends it. **A blank line inside a block stays inside it**: a literal scalar keeps its empty lines, and ending the block at the first paragraph break would cut a shell script in a CI file in half. | ||
| 157 | + | ||
| 158 | +**A `#` needs a space before it to start a comment**, so `colour: ff#00aa` is one scalar. | ||
| 159 | + | ||
| 160 | +| Not recognised | Because | | ||
| 161 | +| --- | --- | | ||
| 162 | +| The schema of a compose file, a manifest or a workflow | Colouring `services:` differently from any other key means carrying somebody else's schema, and it goes stale the day they add a key | | ||
| 163 | +| Multi-document streams as separate documents | `---` is coloured, but nothing is reset at it; nothing in the colouring depends on document boundaries | | ||
| 164 | +| Whether a bare word is a string or a number to a parser | `1.2.3` is a version to a reader and a string to YAML; the scanner colours what it looks like | | ||
| 165 | + | ||
| 166 | +## Markdown | ||
| 167 | + | ||
| 168 | +| Recognised | As | | ||
| 169 | +| --- | --- | | ||
| 170 | +| `# Heading` … `###### Heading` | the whole line as a heading | | ||
| 171 | +| `**bold**`, `__bold__`, `*italic*`, `_italic_` | emphasis | | ||
| 172 | +| `` `code` `` | string | | ||
| 173 | +| `[text](target)`, `` | the whole thing as a link | | ||
| 174 | +| `- `, `* `, `+ `, `1. `, `1) ` | the marker as punctuation | | ||
| 175 | +| `>` | punctuation | | ||
| 176 | +| `---`, `***`, `___` | punctuation | | ||
| 177 | +| ` ``` ` and `~~~` fences | the whole block, opening and closing lines included, as a string | | ||
| 178 | + | ||
| 179 | +A fenced block is **one colour whatever language it announces**: ```` ```python ```` does not colour its contents as Python. The run of markers that opens a block must be matched by the same character to close it, so a backtick fence is not closed by a tilde one. An unclosed fence colours to the end of the file. | ||
| 180 | + | ||
| 181 | +The run of markers opening emphasis must be matched by a run of the same length, so `**bold**` is one span rather than two italics. | ||
| 182 | + | ||
| 183 | +## JavaScript | ||
| 184 | + | ||
| 185 | +| Recognised | As | | ||
| 186 | +| --- | --- | | ||
| 187 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | ||
| 188 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | ||
| 189 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | ||
| 190 | +| a name immediately before `(` | function | | ||
| 191 | +| `"…"`, `'…'` | string | | ||
| 192 | +| `` `…` ``, interpolations included, across lines | string | | ||
| 193 | +| `//` to end of line, `/* … */` across lines | comment | | ||
| 194 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | ||
| 195 | +| runs of `+-*/%=<>!&|^~?:` | operator | | ||
| 196 | +| `()[]{},;.` | punctuation | | ||
| 197 | + | ||
| 198 | +**Regular-expression literals are not recognised.** Telling `/x/g` from a division needs to know whether the previous token could end an expression; a wrong guess colours the rest of a line as a string, which is worse than leaving a regex the colour of an operator. | ||
| 199 | + | ||
| 200 | +Globals are recognised by name, so a file that shadows `Math` still has it coloured as a builtin — the same rule Python's builtins follow here. | ||
| 201 | + | ||
| 202 | +## HTML | ||
| 203 | + | ||
| 204 | +| Recognised | As | | ||
| 205 | +| --- | --- | | ||
| 206 | +| `<tag`, `</tag`, `>`, `/>` | tag | | ||
| 207 | +| attribute names, including `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | ||
| 208 | +| `=` | operator | | ||
| 209 | +| `"…"`, `'…'` | string | | ||
| 210 | +| `<!-- … -->`, across lines | comment | | ||
| 211 | +| `&`, `©` | constant | | ||
| 212 | +| `<!DOCTYPE …>` and other declarations | keyword | | ||
| 213 | + | ||
| 214 | +Text between tags is not coloured. A bare `&` with no `;` within 32 characters is left alone, because it is legal text. | ||
| 215 | + | ||
| 216 | +**The contents of `<script>` and `<style>` are not coloured** as JavaScript and CSS. | ||
| 217 | + | ||
| 218 | +## XML | ||
| 219 | + | ||
| 220 | +Its own scanner rather than HTML's, for one reason that matters: CDATA. The whole point of `<![CDATA[ … ]]>` is that its contents are *not* markup, and colouring the tags inside one as tags is exactly backwards. | ||
| 221 | + | ||
| 222 | +| Recognised | As | | ||
| 223 | +| --- | --- | | ||
| 224 | +| `<?xml version="1.0"?>` and other processing instructions | the target and `?>` as keyword, the pairs between as attributes and strings | | ||
| 225 | +| `<!DOCTYPE …>` and the other `<!` forms | keyword | | ||
| 226 | +| `<!-- … -->`, across lines | comment | | ||
| 227 | +| `<![CDATA[ … ]]>`, across lines | string | | ||
| 228 | +| `<tag`, `</tag`, `>`, `/>` | tag | | ||
| 229 | +| `<ns:tag>`, `xsi:type` | the prefix and the local name as **one** span | | ||
| 230 | +| attribute names | attribute | | ||
| 231 | +| `=` | operator | | ||
| 232 | +| `"…"`, `'…'` | string | | ||
| 233 | +| `&`, `©` | constant | | ||
| 234 | + | ||
| 235 | +**A comment and a CDATA section close on different delimiters**, and are carried separately: a `-->` inside a CDATA section does not end it. | ||
| 236 | + | ||
| 237 | +**A bare `&` with no semicolon within 32 characters is left alone**, because it is legal text in plenty of documents and swallowing the rest of the line would be the bigger mistake. | ||
| 238 | + | ||
| 239 | +Text between tags is not coloured. | ||
| 240 | + | ||
| 241 | +## Shell | ||
| 242 | + | ||
| 243 | +Applies to `sh`, `bash` and `zsh` alike: the keywords recognised are the ones they share. | ||
| 244 | + | ||
| 245 | +| Recognised | As | | ||
| 246 | +| --- | --- | | ||
| 247 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | ||
| 248 | +| `true`, `false` | constant | | ||
| 249 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | ||
| 250 | +| `$NAME`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | ||
| 251 | +| the **first bare word on a line** | function | | ||
| 252 | +| every later bare word, and `NAME` in `NAME=value` | identifier | | ||
| 253 | +| `'…'`, with nothing escaped or expanded inside | string | | ||
| 254 | +| `"…"`, with the expansions inside it coloured as expansions | string | | ||
| 255 | +| `#` to end of line | comment | | ||
| 256 | + | ||
| 257 | +`$(a $(b) c)` is one span: nesting is counted. An option such as `-euo` is one word, not a minus and a word. | ||
| 258 | + | ||
| 259 | +**Heredocs are not recognised.** `<<EOF` and the text after it are coloured as ordinary shell. | ||
| 260 | + | ||
| 261 | +## Dockerfile | ||
| 262 | + | ||
| 263 | +| Recognised | As | | ||
| 264 | +| --- | --- | | ||
| 265 | +| `FROM`, `RUN`, `COPY`, `ADD`, `ARG`, `ENV`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `LABEL`, `USER`, `VOLUME`, `WORKDIR`, `HEALTHCHECK`, `ONBUILD`, `SHELL`, `STOPSIGNAL`, `MAINTAINER` | keyword, in any case | | ||
| 266 | +| `AS`, `NONE` | keyword | | ||
| 267 | +| `# comment`, including the `# syntax=` and `# escape=` directives | comment | | ||
| 268 | +| `--from=builder`, `--chown=me:me` | the flag name as an attribute | | ||
| 269 | +| `$NAME`, `${NAME}`, `${NAME:-default}` | builtin, as one span to the closing brace | | ||
| 270 | +| `"…"`, `'…'` | string | | ||
| 271 | +| a trailing `\` | operator | | ||
| 272 | +| numbers | number | | ||
| 273 | +| paths and image references — `/usr/local/bin`, `golang:1.26-alpine` | identifier, as **one** span | | ||
| 274 | + | ||
| 275 | +**Only the first word of a line can be an instruction**, and a word that is not one is an argument — which is what keeps a continuation line's first word out of the keyword colour. | ||
| 276 | + | ||
| 277 | +**Nothing crosses a line break.** A `\` joins two lines for Docker, but each half still reads as a command and is coloured on its own. | ||
| 278 | + | ||
| 279 | +| Not recognised | Because | | ||
| 280 | +| --- | --- | | ||
| 281 | +| The shell inside a `RUN` | It would mean running the shell scanner over part of a line and mapping its columns out, and `RUN` may hold any language | | ||
| 282 | +| Heredocs in a `RUN` | The same reason the shell scanner does not recognise them | | ||
| 283 | +| Which stage a `--from` names | Nothing here reads the rest of the file | | ||
| 284 | + | ||
| 285 | +## See also | ||
| 286 | + | ||
| 287 | +- [Theme file format](themes.md) — every key these classes resolve to | ||
| 288 | +- [Colouring and completion](../explanation/colouring-and-completion.md) — why the scanners are written this way | ||
| 289 | +- [How to write your own theme](../how-to/write-a-theme.md) | ||
added
docs/en/reference/project-settings.md +111 -0 | new file mode 100644 | ||
| @@ -0,0 +1,111 @@ | ||
| 1 | +# Reference: project settings | |
| 2 | + | |
| 3 | +> Neutral description of `.turbo-python/settings.toml`: where it is looked for, what it may contain, and what writes to it. | |
| 4 | + | |
| 5 | +## Location | |
| 6 | + | |
| 7 | +| Property | Value | | |
| 8 | +| --- | --- | | |
| 9 | +| Directory | `.turbo-python` in the editor's working directory | | |
| 10 | +| File | `.turbo-python/settings.toml` | | |
| 11 | +| Search | The working directory only. Parent directories are **not** searched. | | |
| 12 | +| Read | When the editor starts, and again whenever the file is saved from inside the editor | | |
| 13 | +| Required | No. A project without one gets the defaults below. | | |
| 14 | + | |
| 15 | +## Keys | |
| 16 | + | |
| 17 | +Every key is optional, and every key lives in the `[editor]` table. A key that is absent keeps its default; a key present with any value overrides it, including a value equal to the default. | |
| 18 | + | |
| 19 | +| Key | Type | Default | Description | | |
| 20 | +| --- | --- | --- | --- | | |
| 21 | +| `theme` | string | the editor's own default (`turbo-classic`) | Name of the colour theme to start in, as listed by `turbo-python -list-themes` | | |
| 22 | +| `autosave` | boolean | `false` | Whether modified files are written without being asked. The file **Create project settings** writes sets it to `true`; the default here is what applies to a project with no settings file at all. | | |
| 23 | +| `autosave_delay` | string | `"2s"` | How long after the last keystroke to wait. A Go duration: `"500ms"`, `"2s"`, `"1m"`. Only consulted when `autosave` is true. | | |
| 24 | + | |
| 25 | +### Example | |
| 26 | + | |
| 27 | +```toml | |
| 28 | +[editor] | |
| 29 | +theme = "turbo-dark" | |
| 30 | +autosave = true | |
| 31 | +autosave_delay = "500ms" | |
| 32 | +``` | |
| 33 | + | |
| 34 | +## Theme precedence | |
| 35 | + | |
| 36 | +Highest first: | |
| 37 | + | |
| 38 | +| Source | Wins over | | |
| 39 | +| --- | --- | | |
| 40 | +| `-theme` on the command line | everything | | |
| 41 | +| `theme` in the settings file | the built-in default | | |
| 42 | +| The built-in default `turbo-classic` | — | | |
| 43 | + | |
| 44 | +An unknown theme name at any level falls back to the built-in default rather than failing. | |
| 45 | + | |
| 46 | +## When a change takes effect | |
| 47 | + | |
| 48 | +The file is read at start-up, and **again every time it is saved from inside the editor** — so a change made in the editor is in force the moment you press `F2`, with no restart. | |
| 49 | + | |
| 50 | +| Key | Re-applied on save | Why | | |
| 51 | +| --- | --- | --- | | |
| 52 | +| `autosave` | yes | | | |
| 53 | +| `autosave_delay` | yes | | | |
| 54 | +| `theme` | **no** | Options ▸ Theme is the live way to change it, and already writes the choice back here. A `-theme` flag given on the command line is the more explicit statement for that session and is not overridden by a file being saved. | | |
| 55 | + | |
| 56 | +| Outcome | Status bar | | |
| 57 | +| --- | --- | | |
| 58 | +| Read and applied | `Applied .turbo-python/settings.toml — autosave on (2s)` | | |
| 59 | +| Read and applied, autosave off | `Applied .turbo-python/settings.toml — autosave off` | | |
| 60 | +| Saved, but no longer valid TOML | `Saved, but not applied: …` — the previous values stay in force | | |
| 61 | + | |
| 62 | +Saving is saving, whoever did it: automatic saving writing the settings file re-applies them exactly as `F2` does. Editing the file **outside** the editor is not noticed; nothing watches it. | |
| 63 | + | |
| 64 | +## Automatic saving | |
| 65 | + | |
| 66 | +| Behaviour | Detail | | |
| 67 | +| --- | --- | | |
| 68 | +| Trigger | The delay elapsing with no edit in any window | | |
| 69 | +| Scope | Every open file with a name, not only the front one | | |
| 70 | +| Deadline | One for the whole editor, restarted by any edit in any window | | |
| 71 | +| Files with no name | Never saved; never asked about | | |
| 72 | +| Report | `Saved <name>` on the status bar | | |
| 73 | +| Failure | Reported on the status bar, never in a dialog, and not retried until the next edit | | |
| 74 | +| Closing a window | Saves instead of asking, when the file has a name | | |
| 75 | +| Leaving the editor | Saves instead of asking, when the file has a name | | |
| 76 | + | |
| 77 | +## Writes | |
| 78 | + | |
| 79 | +The settings file is written by exactly two actions. Nothing else in the editor writes to it, and nothing creates it by itself. | |
| 80 | + | |
| 81 | +| Action | Effect | | |
| 82 | +| --- | --- | | |
| 83 | +| **Options ▸ Create project settings** | Creates `.turbo-python/settings.toml` with the theme in use, `autosave = true`, and explanatory comments. Greyed out once the project has one, so it cannot be chosen twice. | | |
| 84 | +| **Options ▸ Theme** | Rewrites the `theme` value **only when the file already exists**. Comments, blank lines, key order and any trailing comment on the theme line are kept. | | |
| 85 | + | |
| 86 | +Both write through a temporary file in the same directory, renamed into place, so an interrupted write leaves the previous file intact. | |
| 87 | + | |
| 88 | +## Menu items | |
| 89 | + | |
| 90 | +| Item | Menu | Needs a file | Effect | | |
| 91 | +| --- | --- | --- | --- | | |
| 92 | +| Create project settings | Options | refuses the file | As above, then opens the file. Greyed out once the project has one. | | |
| 93 | +| Project settings… | Options | requires the file | Opens `.turbo-python/settings.toml`. Greyed out until the project has one. | | |
| 94 | + | |
| 95 | +## Errors | |
| 96 | + | |
| 97 | +| Message | Cause | | |
| 98 | +| --- | --- | | |
| 99 | +| `turbo-python: reading …/settings.toml: …` on standard error | The file is present but is not valid TOML. The editor opens with its defaults. | | |
| 100 | +| `reading …: autosave_delay "x" is not a duration such as "2s"` | `autosave_delay` is not a Go duration | | |
| 101 | +| `reading …: autosave_delay must be positive, not "0s"` | `autosave_delay` is zero or negative | | |
| 102 | +| `Already there: .turbo-python/settings.toml` on the status bar | Creating in a project that already has one. Unreachable from the menu, which greys the item out; still possible for a caller that is not a menu. | | |
| 103 | +| `Saved, but not applied: …` on the status bar | The settings file was written but no longer parses. The previous values stay in force. | | |
| 104 | +| `This project has no .turbo-python/settings.toml yet.` | **Project settings…** in a project that has none | | |
| 105 | +| `Theme set for this session only: …` | The theme changed but the settings file could not be written | | |
| 106 | + | |
| 107 | +## See also | |
| 108 | + | |
| 109 | +- [How to give a project its own settings](../how-to/configure-a-project.md) | |
| 110 | +- [Project settings](../explanation/project-settings.md) | |
| 111 | +- [Theme file format](themes.md) — a different file, in the same language | |
| new file mode 100644 | |||
| @@ -0,0 +1,111 @@ | |||
| 1 | +# Reference: project settings | ||
| 2 | + | ||
| 3 | +> Neutral description of `.turbo-python/settings.toml`: where it is looked for, what it may contain, and what writes to it. | ||
| 4 | + | ||
| 5 | +## Location | ||
| 6 | + | ||
| 7 | +| Property | Value | | ||
| 8 | +| --- | --- | | ||
| 9 | +| Directory | `.turbo-python` in the editor's working directory | | ||
| 10 | +| File | `.turbo-python/settings.toml` | | ||
| 11 | +| Search | The working directory only. Parent directories are **not** searched. | | ||
| 12 | +| Read | When the editor starts, and again whenever the file is saved from inside the editor | | ||
| 13 | +| Required | No. A project without one gets the defaults below. | | ||
| 14 | + | ||
| 15 | +## Keys | ||
| 16 | + | ||
| 17 | +Every key is optional, and every key lives in the `[editor]` table. A key that is absent keeps its default; a key present with any value overrides it, including a value equal to the default. | ||
| 18 | + | ||
| 19 | +| Key | Type | Default | Description | | ||
| 20 | +| --- | --- | --- | --- | | ||
| 21 | +| `theme` | string | the editor's own default (`turbo-classic`) | Name of the colour theme to start in, as listed by `turbo-python -list-themes` | | ||
| 22 | +| `autosave` | boolean | `false` | Whether modified files are written without being asked. The file **Create project settings** writes sets it to `true`; the default here is what applies to a project with no settings file at all. | | ||
| 23 | +| `autosave_delay` | string | `"2s"` | How long after the last keystroke to wait. A Go duration: `"500ms"`, `"2s"`, `"1m"`. Only consulted when `autosave` is true. | | ||
| 24 | + | ||
| 25 | +### Example | ||
| 26 | + | ||
| 27 | +```toml | ||
| 28 | +[editor] | ||
| 29 | +theme = "turbo-dark" | ||
| 30 | +autosave = true | ||
| 31 | +autosave_delay = "500ms" | ||
| 32 | +``` | ||
| 33 | + | ||
| 34 | +## Theme precedence | ||
| 35 | + | ||
| 36 | +Highest first: | ||
| 37 | + | ||
| 38 | +| Source | Wins over | | ||
| 39 | +| --- | --- | | ||
| 40 | +| `-theme` on the command line | everything | | ||
| 41 | +| `theme` in the settings file | the built-in default | | ||
| 42 | +| The built-in default `turbo-classic` | — | | ||
| 43 | + | ||
| 44 | +An unknown theme name at any level falls back to the built-in default rather than failing. | ||
| 45 | + | ||
| 46 | +## When a change takes effect | ||
| 47 | + | ||
| 48 | +The file is read at start-up, and **again every time it is saved from inside the editor** — so a change made in the editor is in force the moment you press `F2`, with no restart. | ||
| 49 | + | ||
| 50 | +| Key | Re-applied on save | Why | | ||
| 51 | +| --- | --- | --- | | ||
| 52 | +| `autosave` | yes | | | ||
| 53 | +| `autosave_delay` | yes | | | ||
| 54 | +| `theme` | **no** | Options ▸ Theme is the live way to change it, and already writes the choice back here. A `-theme` flag given on the command line is the more explicit statement for that session and is not overridden by a file being saved. | | ||
| 55 | + | ||
| 56 | +| Outcome | Status bar | | ||
| 57 | +| --- | --- | | ||
| 58 | +| Read and applied | `Applied .turbo-python/settings.toml — autosave on (2s)` | | ||
| 59 | +| Read and applied, autosave off | `Applied .turbo-python/settings.toml — autosave off` | | ||
| 60 | +| Saved, but no longer valid TOML | `Saved, but not applied: …` — the previous values stay in force | | ||
| 61 | + | ||
| 62 | +Saving is saving, whoever did it: automatic saving writing the settings file re-applies them exactly as `F2` does. Editing the file **outside** the editor is not noticed; nothing watches it. | ||
| 63 | + | ||
| 64 | +## Automatic saving | ||
| 65 | + | ||
| 66 | +| Behaviour | Detail | | ||
| 67 | +| --- | --- | | ||
| 68 | +| Trigger | The delay elapsing with no edit in any window | | ||
| 69 | +| Scope | Every open file with a name, not only the front one | | ||
| 70 | +| Deadline | One for the whole editor, restarted by any edit in any window | | ||
| 71 | +| Files with no name | Never saved; never asked about | | ||
| 72 | +| Report | `Saved <name>` on the status bar | | ||
| 73 | +| Failure | Reported on the status bar, never in a dialog, and not retried until the next edit | | ||
| 74 | +| Closing a window | Saves instead of asking, when the file has a name | | ||
| 75 | +| Leaving the editor | Saves instead of asking, when the file has a name | | ||
| 76 | + | ||
| 77 | +## Writes | ||
| 78 | + | ||
| 79 | +The settings file is written by exactly two actions. Nothing else in the editor writes to it, and nothing creates it by itself. | ||
| 80 | + | ||
| 81 | +| Action | Effect | | ||
| 82 | +| --- | --- | | ||
| 83 | +| **Options ▸ Create project settings** | Creates `.turbo-python/settings.toml` with the theme in use, `autosave = true`, and explanatory comments. Greyed out once the project has one, so it cannot be chosen twice. | | ||
| 84 | +| **Options ▸ Theme** | Rewrites the `theme` value **only when the file already exists**. Comments, blank lines, key order and any trailing comment on the theme line are kept. | | ||
| 85 | + | ||
| 86 | +Both write through a temporary file in the same directory, renamed into place, so an interrupted write leaves the previous file intact. | ||
| 87 | + | ||
| 88 | +## Menu items | ||
| 89 | + | ||
| 90 | +| Item | Menu | Needs a file | Effect | | ||
| 91 | +| --- | --- | --- | --- | | ||
| 92 | +| Create project settings | Options | refuses the file | As above, then opens the file. Greyed out once the project has one. | | ||
| 93 | +| Project settings… | Options | requires the file | Opens `.turbo-python/settings.toml`. Greyed out until the project has one. | | ||
| 94 | + | ||
| 95 | +## Errors | ||
| 96 | + | ||
| 97 | +| Message | Cause | | ||
| 98 | +| --- | --- | | ||
| 99 | +| `turbo-python: reading …/settings.toml: …` on standard error | The file is present but is not valid TOML. The editor opens with its defaults. | | ||
| 100 | +| `reading …: autosave_delay "x" is not a duration such as "2s"` | `autosave_delay` is not a Go duration | | ||
| 101 | +| `reading …: autosave_delay must be positive, not "0s"` | `autosave_delay` is zero or negative | | ||
| 102 | +| `Already there: .turbo-python/settings.toml` on the status bar | Creating in a project that already has one. Unreachable from the menu, which greys the item out; still possible for a caller that is not a menu. | | ||
| 103 | +| `Saved, but not applied: …` on the status bar | The settings file was written but no longer parses. The previous values stay in force. | | ||
| 104 | +| `This project has no .turbo-python/settings.toml yet.` | **Project settings…** in a project that has none | | ||
| 105 | +| `Theme set for this session only: …` | The theme changed but the settings file could not be written | | ||
| 106 | + | ||
| 107 | +## See also | ||
| 108 | + | ||
| 109 | +- [How to give a project its own settings](../how-to/configure-a-project.md) | ||
| 110 | +- [Project settings](../explanation/project-settings.md) | ||
| 111 | +- [Theme file format](themes.md) — a different file, in the same language | ||
added
docs/en/reference/project-tree.md +102 -0 | new file mode 100644 | ||
| @@ -0,0 +1,102 @@ | ||
| 1 | +# Reference: project tree | |
| 2 | + | |
| 3 | +> Neutral description of the project tree window: what it shows, what it hides, and the keys it answers to. | |
| 4 | + | |
| 5 | +## Opening | |
| 6 | + | |
| 7 | +| Route | Condition | | |
| 8 | +| --- | --- | | |
| 9 | +| `F9` | Always | | |
| 10 | +| **Window ▸ Project tree** | Always | | |
| 11 | + | |
| 12 | +Neither requires a file to be open. Both bring the existing tree forward when one is already open: there is at most one tree window. | |
| 13 | + | |
| 14 | +## Root | |
| 15 | + | |
| 16 | +| Property | Value | | |
| 17 | +| --- | --- | | |
| 18 | +| Rooted at | The directory the editor was started in (`os.Getwd()`) | | |
| 19 | +| Search | That directory only. Parent directories are **not** searched, the same rule `.turbo-python/settings.toml` follows. | | |
| 20 | +| Window title | The base name of that directory | | |
| 21 | +| Root row | Not shown; the first row is the first entry inside the project | | |
| 22 | + | |
| 23 | +## What is listed | |
| 24 | + | |
| 25 | +| Rule | Detail | | |
| 26 | +| --- | --- | | |
| 27 | +| Order | Directories first, then files; each group sorted by name | | |
| 28 | +| Hidden | `.git` only | | |
| 29 | +| Shown | Every other entry, dot-entries included — `.turbo-python`, `.gitignore`, `.qlty` | | |
| 30 | +| Reading | A directory is read the first time it is expanded, and not before | | |
| 31 | +| Unreadable directory | Shows as expanded and empty; the rest of the tree is unaffected | | |
| 32 | + | |
| 33 | +## Markers | |
| 34 | + | |
| 35 | +| Marker | Meaning | | |
| 36 | +| --- | --- | | |
| 37 | +| `▶ ` | A directory that is closed | | |
| 38 | +| `▼ ` | A directory that is open | | |
| 39 | +| (two spaces) | A file — indented by a marker's width so names line up | | |
| 40 | + | |
| 41 | +Each level of depth adds two more spaces of indentation. | |
| 42 | + | |
| 43 | +## Keys | |
| 44 | + | |
| 45 | +Handled when the tree window has the focus. | |
| 46 | + | |
| 47 | +| Key | Action | | |
| 48 | +| --- | --- | | |
| 49 | +| `↑` `↓` | Previous / next row | | |
| 50 | +| `PgUp` `PgDn` | A screenful at a time | | |
| 51 | +| `Home` `End` | First / last row | | |
| 52 | +| `→` | Expand a closed directory; otherwise move to the next row | | |
| 53 | +| `←` | Collapse an open directory; otherwise move to the directory this row is in | | |
| 54 | +| `Enter` | Open a file; expand or collapse a directory | | |
| 55 | +| `F5`, `Ctrl-R` | Re-read the project | | |
| 56 | + | |
| 57 | +The editor's own shortcuts apply as usual: `F6` moves to the next window, `Ctrl-W` closes the tree, `Alt-X` leaves. | |
| 58 | + | |
| 59 | +## Mouse | |
| 60 | + | |
| 61 | +| Action | Effect | | |
| 62 | +| --- | --- | | |
| 63 | +| Click a row | Move the highlight to it | | |
| 64 | +| Click the highlighted row | Act on it, as `Enter` does | | |
| 65 | +| Wheel up / down | Move the highlight three rows | | |
| 66 | + | |
| 67 | +## Refreshing | |
| 68 | + | |
| 69 | +| Trigger | Effect | | |
| 70 | +| --- | --- | | |
| 71 | +| `F5` or `Ctrl-R` | Re-reads every directory that has been opened | | |
| 72 | +| Saving a file | The same, automatically | | |
| 73 | +| Expanding a directory | Reads that directory, if it has not been read | | |
| 74 | + | |
| 75 | +Refreshing keeps the shape of the tree: a directory that was open stays open, one that has been deleted takes its branch with it, and directories nobody has opened stay unread. The highlight stays on the same entry, or on the nearest remaining row when that entry has gone. | |
| 76 | + | |
| 77 | +The tree does **not** watch the filesystem. A file created by a terminal window, or by `git checkout`, appears only after a refresh. | |
| 78 | + | |
| 79 | +## Colours | |
| 80 | + | |
| 81 | +| Theme key | What it colours | | |
| 82 | +| --- | --- | | |
| 83 | +| `tree.text` | A file's name, and the tree's background | | |
| 84 | +| `tree.directory` | A directory's name | | |
| 85 | +| `tree.selected` | The highlighted row, when the tree has the focus | | |
| 86 | +| `tree.unfocused` | The highlighted row, when it does not | | |
| 87 | + | |
| 88 | +These do not fall back to the `list.*` keys: dotted fallback runs along the dots and stops at `default`. See [Theme file format](themes.md). | |
| 89 | + | |
| 90 | +## Errors | |
| 91 | + | |
| 92 | +| Message | Cause | | |
| 93 | +| --- | --- | | |
| 94 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | |
| 95 | +| `reading …: …` | The project directory could not be read | | |
| 96 | +| `… is not a directory` | The root resolved to a file | | |
| 97 | + | |
| 98 | +## See also | |
| 99 | + | |
| 100 | +- [How to browse a project and open files from a tree](../how-to/browse-a-project.md) | |
| 101 | +- [Project tree](../explanation/project-tree.md) | |
| 102 | +- [Keyboard](keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,102 @@ | |||
| 1 | +# Reference: project tree | ||
| 2 | + | ||
| 3 | +> Neutral description of the project tree window: what it shows, what it hides, and the keys it answers to. | ||
| 4 | + | ||
| 5 | +## Opening | ||
| 6 | + | ||
| 7 | +| Route | Condition | | ||
| 8 | +| --- | --- | | ||
| 9 | +| `F9` | Always | | ||
| 10 | +| **Window ▸ Project tree** | Always | | ||
| 11 | + | ||
| 12 | +Neither requires a file to be open. Both bring the existing tree forward when one is already open: there is at most one tree window. | ||
| 13 | + | ||
| 14 | +## Root | ||
| 15 | + | ||
| 16 | +| Property | Value | | ||
| 17 | +| --- | --- | | ||
| 18 | +| Rooted at | The directory the editor was started in (`os.Getwd()`) | | ||
| 19 | +| Search | That directory only. Parent directories are **not** searched, the same rule `.turbo-python/settings.toml` follows. | | ||
| 20 | +| Window title | The base name of that directory | | ||
| 21 | +| Root row | Not shown; the first row is the first entry inside the project | | ||
| 22 | + | ||
| 23 | +## What is listed | ||
| 24 | + | ||
| 25 | +| Rule | Detail | | ||
| 26 | +| --- | --- | | ||
| 27 | +| Order | Directories first, then files; each group sorted by name | | ||
| 28 | +| Hidden | `.git` only | | ||
| 29 | +| Shown | Every other entry, dot-entries included — `.turbo-python`, `.gitignore`, `.qlty` | | ||
| 30 | +| Reading | A directory is read the first time it is expanded, and not before | | ||
| 31 | +| Unreadable directory | Shows as expanded and empty; the rest of the tree is unaffected | | ||
| 32 | + | ||
| 33 | +## Markers | ||
| 34 | + | ||
| 35 | +| Marker | Meaning | | ||
| 36 | +| --- | --- | | ||
| 37 | +| `▶ ` | A directory that is closed | | ||
| 38 | +| `▼ ` | A directory that is open | | ||
| 39 | +| (two spaces) | A file — indented by a marker's width so names line up | | ||
| 40 | + | ||
| 41 | +Each level of depth adds two more spaces of indentation. | ||
| 42 | + | ||
| 43 | +## Keys | ||
| 44 | + | ||
| 45 | +Handled when the tree window has the focus. | ||
| 46 | + | ||
| 47 | +| Key | Action | | ||
| 48 | +| --- | --- | | ||
| 49 | +| `↑` `↓` | Previous / next row | | ||
| 50 | +| `PgUp` `PgDn` | A screenful at a time | | ||
| 51 | +| `Home` `End` | First / last row | | ||
| 52 | +| `→` | Expand a closed directory; otherwise move to the next row | | ||
| 53 | +| `←` | Collapse an open directory; otherwise move to the directory this row is in | | ||
| 54 | +| `Enter` | Open a file; expand or collapse a directory | | ||
| 55 | +| `F5`, `Ctrl-R` | Re-read the project | | ||
| 56 | + | ||
| 57 | +The editor's own shortcuts apply as usual: `F6` moves to the next window, `Ctrl-W` closes the tree, `Alt-X` leaves. | ||
| 58 | + | ||
| 59 | +## Mouse | ||
| 60 | + | ||
| 61 | +| Action | Effect | | ||
| 62 | +| --- | --- | | ||
| 63 | +| Click a row | Move the highlight to it | | ||
| 64 | +| Click the highlighted row | Act on it, as `Enter` does | | ||
| 65 | +| Wheel up / down | Move the highlight three rows | | ||
| 66 | + | ||
| 67 | +## Refreshing | ||
| 68 | + | ||
| 69 | +| Trigger | Effect | | ||
| 70 | +| --- | --- | | ||
| 71 | +| `F5` or `Ctrl-R` | Re-reads every directory that has been opened | | ||
| 72 | +| Saving a file | The same, automatically | | ||
| 73 | +| Expanding a directory | Reads that directory, if it has not been read | | ||
| 74 | + | ||
| 75 | +Refreshing keeps the shape of the tree: a directory that was open stays open, one that has been deleted takes its branch with it, and directories nobody has opened stay unread. The highlight stays on the same entry, or on the nearest remaining row when that entry has gone. | ||
| 76 | + | ||
| 77 | +The tree does **not** watch the filesystem. A file created by a terminal window, or by `git checkout`, appears only after a refresh. | ||
| 78 | + | ||
| 79 | +## Colours | ||
| 80 | + | ||
| 81 | +| Theme key | What it colours | | ||
| 82 | +| --- | --- | | ||
| 83 | +| `tree.text` | A file's name, and the tree's background | | ||
| 84 | +| `tree.directory` | A directory's name | | ||
| 85 | +| `tree.selected` | The highlighted row, when the tree has the focus | | ||
| 86 | +| `tree.unfocused` | The highlighted row, when it does not | | ||
| 87 | + | ||
| 88 | +These do not fall back to the `list.*` keys: dotted fallback runs along the dots and stops at `default`. See [Theme file format](themes.md). | ||
| 89 | + | ||
| 90 | +## Errors | ||
| 91 | + | ||
| 92 | +| Message | Cause | | ||
| 93 | +| --- | --- | | ||
| 94 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | ||
| 95 | +| `reading …: …` | The project directory could not be read | | ||
| 96 | +| `… is not a directory` | The root resolved to a file | | ||
| 97 | + | ||
| 98 | +## See also | ||
| 99 | + | ||
| 100 | +- [How to browse a project and open files from a tree](../how-to/browse-a-project.md) | ||
| 101 | +- [Project tree](../explanation/project-tree.md) | ||
| 102 | +- [Keyboard](keyboard.md) | ||
added
docs/en/reference/python-tools.md +236 -0 | new file mode 100644 | ||
| @@ -0,0 +1,236 @@ | ||
| 1 | +# Reference: Python tools | |
| 2 | + | |
| 3 | +> Neutral description of `.turbo-python/tools.toml`, the Python menu, and what running a command does. | |
| 4 | + | |
| 5 | +## File | |
| 6 | + | |
| 7 | +| Property | Value | | |
| 8 | +| --- | --- | | |
| 9 | +| Path | `./.turbo-python/tools.toml` | | |
| 10 | +| Search | The working directory only. Parent directories are **not** searched. | | |
| 11 | +| Read | Every time one of its menus opens, for the items | | |
| 12 | +| Re-read | Whenever the file's size or modification time changes, for the **set** of menus | | |
| 13 | +| Missing file | Not an error | | |
| 14 | +| Unreadable file | An error, shown in the menu | | |
| 15 | +| User-level file | **None.** Unlike snippets, there is no `~/.config/turbo-python/tools.toml`. | | |
| 16 | + | |
| 17 | +## File format | |
| 18 | + | |
| 19 | +One `[[tool]]` table per command. | |
| 20 | + | |
| 21 | +| Key | Type | Required | Description | | |
| 22 | +| --- | --- | --- | --- | | |
| 23 | +| `name` | string | yes | What the menu shows. May carry a hot key written with tildes, as in `"~T~est"`. | | |
| 24 | +| `command` | string | yes | The shell command to run | | |
| 25 | +| `output` | string | no | Where its output goes: `popup`, `terminal` or `editor`. Absent means `popup`. | | |
| 26 | +| `menu` | string | no | Which menu it appears in. Absent means `Python`. Any name; the menu is created for you. May carry a hot key written with tildes. | | |
| 27 | + | |
| 28 | +`menu` is not checked against a list, because there is no list: a name that no other tool uses simply creates a menu. A tool with no `name`, no `command`, or an `output` naming something that does not exist makes the whole file an error. An unknown `output` is **refused rather than corrected**: `"termnial"` would otherwise look as though it had worked while sending the output somewhere else. | |
| 29 | + | |
| 30 | +### Example | |
| 31 | + | |
| 32 | +```toml | |
| 33 | +[[tool]] | |
| 34 | +name = "~T~est" | |
| 35 | +command = "uv run pytest" | |
| 36 | +output = "popup" | |
| 37 | + | |
| 38 | +[[tool]] | |
| 39 | +name = "~E~cho" | |
| 40 | +command = "echo TADA" | |
| 41 | +output = "terminal" | |
| 42 | +menu = "Tools" | |
| 43 | +``` | |
| 44 | + | |
| 45 | +## The starter file | |
| 46 | + | |
| 47 | +**Python ▸ Create tools file** writes these five, in this order: | |
| 48 | + | |
| 49 | +| Name | Command | Output | | |
| 50 | +| --- | --- | --- | | |
| 51 | +| Format | `uv run ruff format .` | `popup` | | |
| 52 | +| Lint | `uv run ruff check .` | `popup` | | |
| 53 | +| Build | `uv sync` | `popup` | | |
| 54 | +| Test | `uv run pytest` | `popup` | | |
| 55 | +| Run | `uv run` | `terminal` | | |
| 56 | + | |
| 57 | +None of them names a `menu`, so all five are in the Python menu. Every one names its `output`, including the four that name the default: the key is the interesting part of the format, and a file where it appears once is a file where nobody notices it exists. | |
| 58 | + | |
| 59 | +The item is greyed out once the project has a tools file, so it cannot overwrite one. The file is written through a temporary file in the same directory, renamed into place. | |
| 60 | + | |
| 61 | +## The Python menu | |
| 62 | + | |
| 63 | +Always on the bar, whether or not a tools file exists. Its hot key is `Alt-P`. | |
| 64 | + | |
| 65 | +| Item | Condition | | |
| 66 | +| --- | --- | | |
| 67 | +| One line per tool with no `menu`, in file order | The file holds at least one | | |
| 68 | +| `Cannot read tools`, greyed out | The file is present but unreadable | | |
| 69 | +| `Create tools file` | The project has no tools file | | |
| 70 | +| `Open tools file` | The project has one | | |
| 71 | + | |
| 72 | +## Menus a tool asks for | |
| 73 | + | |
| 74 | +A `menu` naming anything other than `Python` puts a menu of that name on the bar. | |
| 75 | + | |
| 76 | +| Property | Value | | |
| 77 | +| --- | --- | | |
| 78 | +| Position | Between Python and Help | | |
| 79 | +| Order | The order each name first appears in the file | | |
| 80 | +| Items | One line per tool naming that menu, in file order. Nothing else — `Create tools file` and `Open tools file` stay in Python. | | |
| 81 | +| Unreadable file | No menus at all; the Python menu carries the error | | |
| 82 | +| While the editor runs | Added, removed and renamed as the file changes, without restarting | | |
| 83 | + | |
| 84 | +### Hot keys | |
| 85 | + | |
| 86 | +Assigned automatically, because a name from a file cannot be checked against the fixed menus in advance. | |
| 87 | + | |
| 88 | +| Case | Result | | |
| 89 | +| --- | --- | | |
| 90 | +| No tildes in the name | The first letter no other menu has claimed is marked. `Format` becomes `For~m~at`: `F` is File's, `o` is Options', `r` is Run's. | | |
| 91 | +| Tildes naming a free letter | Kept as written. `Doc~k~er` answers to `Alt-K`. | | |
| 92 | +| Tildes naming a taken letter | Dropped, and a free letter chosen instead. `~F~oo` becomes `F~o~o`. | | |
| 93 | +| Every letter taken | No hot key. `F10` and the mouse still open it. | | |
| 94 | + | |
| 95 | +The letters the editor's own menus hold are `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` and `H`. | |
| 96 | + | |
| 97 | +## Running a command | |
| 98 | + | |
| 99 | +Common to every output: | |
| 100 | + | |
| 101 | +| Property | Value | | |
| 102 | +| --- | --- | | |
| 103 | +| Shell | `/bin/sh -c "<command>"` on Linux and macOS; `cmd.exe /S /C "<command>"` — the shell `%COMSPEC%` names — on Windows | | |
| 104 | +| Directory | The directory the editor was started in | | |
| 105 | +| Standard error | Merged into standard output, in the order the command wrote them | | |
| 106 | + | |
| 107 | +Going through a shell means pipes, globs, `&&` and `;` all work, so one tool can be a sequence. On Windows the shell is cmd.exe, which knows `&&`, `|` and `>` but does not expand globs, and where `;` is not a separator. | |
| 108 | + | |
| 109 | +### `output = "popup"` | |
| 110 | + | |
| 111 | +| Property | Value | | |
| 112 | +| --- | --- | | |
| 113 | +| Opens | Immediately, before the command has finished | | |
| 114 | +| Modal | Yes: nothing else in the editor can be used while it is up | | |
| 115 | +| Fills in | As output arrives, following it until you scroll back | | |
| 116 | +| Title while running | `<command> — running` | | |
| 117 | +| Title when finished | `<command> — ok`, or `<command> — exit <n>` | | |
| 118 | +| Empty output, finished | Shows `(no output)` | | |
| 119 | +| Empty output, running | Shows nothing | | |
| 120 | +| Output cap | 10000 lines; past it the oldest go and a `… n earlier lines dropped …` line says so | | |
| 121 | + | |
| 122 | +| Key | Effect | | |
| 123 | +| --- | --- | | |
| 124 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Read through the output | | |
| 125 | +| Wheel | The same | | |
| 126 | +| `Escape`, `Enter`, **Close** | Close it, **stopping the command** if it is still running | | |
| 127 | + | |
| 128 | +Closing stops the command because there is no other way to interrupt one whose output is not in a terminal. | |
| 129 | + | |
| 130 | +### `output = "terminal"` | |
| 131 | + | |
| 132 | +| Property | Value | | |
| 133 | +| --- | --- | | |
| 134 | +| Window | A terminal window of its own, titled with the command | | |
| 135 | +| Environment | The editor's own, with `TERM` set to `xterm-256color` | | |
| 136 | +| After it exits | The window stays, showing its output | | |
| 137 | +| Modal | No: the editor carries on beside it | | |
| 138 | + | |
| 139 | +Because it is a real terminal, colours, paging, `Ctrl-C` and reading from the keyboard all work. See [Terminal windows](terminal.md). | |
| 140 | + | |
| 141 | +Keys in a **finished** terminal window: | |
| 142 | + | |
| 143 | +| Key | Effect | | |
| 144 | +| --- | --- | | |
| 145 | +| `Shift-PgUp`, `Shift-PgDn` | Read back through the output | | |
| 146 | +| `Ctrl-W` | Close the window | | |
| 147 | +| Anything else | Reaches the editor, not the dead shell | | |
| 148 | + | |
| 149 | +### `output = "editor"` | |
| 150 | + | |
| 151 | +| Property | Value | | |
| 152 | +| --- | --- | | |
| 153 | +| Shows | A popup while it runs, as above | | |
| 154 | +| On closing the popup | An editing window holding the output, titled with the command | | |
| 155 | +| Filled | Once, when the command has finished — not as it goes | | |
| 156 | +| The window | An ordinary editing window with no file name: searchable with `Ctrl-F`, and `Save as` keeps it | | |
| 157 | + | |
| 158 | +## Reloading after a command | |
| 159 | + | |
| 160 | +When a command finishes, every open file is considered. | |
| 161 | + | |
| 162 | +| The file | What happens | | |
| 163 | +| --- | --- | | |
| 164 | +| Unmodified, and changed on disk | Re-read; its syntax is re-decided and its title refreshed | | |
| 165 | +| Unmodified, and unchanged on disk | Left alone, not counted | | |
| 166 | +| Has unsaved changes | Left alone and counted as skipped | | |
| 167 | +| Has never been named | Left alone | | |
| 168 | +| Has gone from disk | Left alone | | |
| 169 | + | |
| 170 | +The cursor stays where it was, clamped into whatever the file now holds. The undo history is discarded, because undoing back past a reload would restore text the file no longer has. | |
| 171 | + | |
| 172 | +The project tree is refreshed at the same moment. | |
| 173 | + | |
| 174 | +| Status bar | When | | |
| 175 | +| --- | --- | | |
| 176 | +| `Running <command>` | The window opens | | |
| 177 | +| `Reloaded 2 files` | Two files were re-read, none skipped | | |
| 178 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Some were skipped | | |
| 179 | +| `Command finished; 1 file with unsaved changes left alone` | Nothing was re-read, something was skipped | | |
| 180 | + | |
| 181 | +## Errors | |
| 182 | + | |
| 183 | +| Message | Cause | | |
| 184 | +| --- | --- | | |
| 185 | +| `Cannot read tools` in the menu | The file is present but not valid TOML, or holds a tool with no name or no command | | |
| 186 | +| `Already there: .turbo-python/tools.toml` | Creating in a project that already has one. Unreachable from the menu, which greys the item out; still possible for a caller that is not a menu. | | |
| 187 | +| `This project has no .turbo-python/tools.toml yet.` | Opening in a project that has none, likewise | | |
| 188 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | |
| 189 | +| `Terminal windows are not supported on this platform yet` | Running a command in a terminal needs a pseudo-terminal, which Linux, macOS and Windows have; see [Terminal windows](terminal.md) | | |
| 190 | + | |
| 191 | +## Asking for a value | |
| 192 | + | |
| 193 | +A `{{label}}` anywhere in a command is a value the editor asks for before it runs, in a box titled after the tool. The text between the braces is what the box asks for. | |
| 194 | + | |
| 195 | +| Written | Asked for | Substituted | | |
| 196 | +| --- | --- | --- | | |
| 197 | +| `{{module path}}` | `module path` | shell-quoted | | |
| 198 | +| `{{extra flags...}}` | `extra flags` | verbatim | | |
| 199 | + | |
| 200 | +A value is **shell-quoted** by default, so a path with a space in it stays one argument. A trailing `...` inside the braces asks for it verbatim instead, which is how one field can stand for several arguments. | |
| 201 | + | |
| 202 | +```toml | |
| 203 | +[[tool]] | |
| 204 | +name = "~I~nit module" | |
| 205 | +command = "go mod init {{module path}}" | |
| 206 | +output = "popup" | |
| 207 | +``` | |
| 208 | + | |
| 209 | +| Rule | Behaviour | | |
| 210 | +| --- | --- | | |
| 211 | +| Several placeholders | One box, one field each, in the order they appear in the command | | |
| 212 | +| The same label twice | One field; every occurrence gets what is typed into it | | |
| 213 | +| A label written both ways | Asked for once; each occurrence honours its own braces | | |
| 214 | +| Escape, or Cancel | The command does not run | | |
| 215 | +| A field left empty | Substituted as empty — the command reports its own complaint | | |
| 216 | +| Running the tool again | The box starts from what was typed last time, for this session only | | |
| 217 | +| More fields than fit on screen | Refused, with a message saying how many fit | | |
| 218 | + | |
| 219 | +**Double braces, not single.** `awk '{print $1}'` and `find . -exec rm {} +` are ordinary commands, and a single-brace syntax would read the first as a request for a value called `print $1`. | |
| 220 | + | |
| 221 | +Nothing is written to disk. A value somebody typed this afternoon is not a decision the project made, so it does not go in the project's own directory. | |
| 222 | + | |
| 223 | +### Errors | |
| 224 | + | |
| 225 | +| Error | Cause | | |
| 226 | +| --- | --- | | |
| 227 | +| `tool "X": "{{module" is never closed` | An opening `{{` with no `}}` after it | | |
| 228 | +| `tool "X": {{}} asks for a value but does not say what it is` | A placeholder with no label, or one that is only `...` | | |
| 229 | + | |
| 230 | +Both are refused when the file is read, so a half-typed placeholder never reaches the shell with its braces still in it. | |
| 231 | + | |
| 232 | +## See also | |
| 233 | + | |
| 234 | +- [How to run uv commands from the editor](../how-to/run-uv-commands.md) | |
| 235 | +- [Python tools](../explanation/python-tools.md) | |
| 236 | +- [Terminal windows](terminal.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,236 @@ | |||
| 1 | +# Reference: Python tools | ||
| 2 | + | ||
| 3 | +> Neutral description of `.turbo-python/tools.toml`, the Python menu, and what running a command does. | ||
| 4 | + | ||
| 5 | +## File | ||
| 6 | + | ||
| 7 | +| Property | Value | | ||
| 8 | +| --- | --- | | ||
| 9 | +| Path | `./.turbo-python/tools.toml` | | ||
| 10 | +| Search | The working directory only. Parent directories are **not** searched. | | ||
| 11 | +| Read | Every time one of its menus opens, for the items | | ||
| 12 | +| Re-read | Whenever the file's size or modification time changes, for the **set** of menus | | ||
| 13 | +| Missing file | Not an error | | ||
| 14 | +| Unreadable file | An error, shown in the menu | | ||
| 15 | +| User-level file | **None.** Unlike snippets, there is no `~/.config/turbo-python/tools.toml`. | | ||
| 16 | + | ||
| 17 | +## File format | ||
| 18 | + | ||
| 19 | +One `[[tool]]` table per command. | ||
| 20 | + | ||
| 21 | +| Key | Type | Required | Description | | ||
| 22 | +| --- | --- | --- | --- | | ||
| 23 | +| `name` | string | yes | What the menu shows. May carry a hot key written with tildes, as in `"~T~est"`. | | ||
| 24 | +| `command` | string | yes | The shell command to run | | ||
| 25 | +| `output` | string | no | Where its output goes: `popup`, `terminal` or `editor`. Absent means `popup`. | | ||
| 26 | +| `menu` | string | no | Which menu it appears in. Absent means `Python`. Any name; the menu is created for you. May carry a hot key written with tildes. | | ||
| 27 | + | ||
| 28 | +`menu` is not checked against a list, because there is no list: a name that no other tool uses simply creates a menu. A tool with no `name`, no `command`, or an `output` naming something that does not exist makes the whole file an error. An unknown `output` is **refused rather than corrected**: `"termnial"` would otherwise look as though it had worked while sending the output somewhere else. | ||
| 29 | + | ||
| 30 | +### Example | ||
| 31 | + | ||
| 32 | +```toml | ||
| 33 | +[[tool]] | ||
| 34 | +name = "~T~est" | ||
| 35 | +command = "uv run pytest" | ||
| 36 | +output = "popup" | ||
| 37 | + | ||
| 38 | +[[tool]] | ||
| 39 | +name = "~E~cho" | ||
| 40 | +command = "echo TADA" | ||
| 41 | +output = "terminal" | ||
| 42 | +menu = "Tools" | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +## The starter file | ||
| 46 | + | ||
| 47 | +**Python ▸ Create tools file** writes these five, in this order: | ||
| 48 | + | ||
| 49 | +| Name | Command | Output | | ||
| 50 | +| --- | --- | --- | | ||
| 51 | +| Format | `uv run ruff format .` | `popup` | | ||
| 52 | +| Lint | `uv run ruff check .` | `popup` | | ||
| 53 | +| Build | `uv sync` | `popup` | | ||
| 54 | +| Test | `uv run pytest` | `popup` | | ||
| 55 | +| Run | `uv run` | `terminal` | | ||
| 56 | + | ||
| 57 | +None of them names a `menu`, so all five are in the Python menu. Every one names its `output`, including the four that name the default: the key is the interesting part of the format, and a file where it appears once is a file where nobody notices it exists. | ||
| 58 | + | ||
| 59 | +The item is greyed out once the project has a tools file, so it cannot overwrite one. The file is written through a temporary file in the same directory, renamed into place. | ||
| 60 | + | ||
| 61 | +## The Python menu | ||
| 62 | + | ||
| 63 | +Always on the bar, whether or not a tools file exists. Its hot key is `Alt-P`. | ||
| 64 | + | ||
| 65 | +| Item | Condition | | ||
| 66 | +| --- | --- | | ||
| 67 | +| One line per tool with no `menu`, in file order | The file holds at least one | | ||
| 68 | +| `Cannot read tools`, greyed out | The file is present but unreadable | | ||
| 69 | +| `Create tools file` | The project has no tools file | | ||
| 70 | +| `Open tools file` | The project has one | | ||
| 71 | + | ||
| 72 | +## Menus a tool asks for | ||
| 73 | + | ||
| 74 | +A `menu` naming anything other than `Python` puts a menu of that name on the bar. | ||
| 75 | + | ||
| 76 | +| Property | Value | | ||
| 77 | +| --- | --- | | ||
| 78 | +| Position | Between Python and Help | | ||
| 79 | +| Order | The order each name first appears in the file | | ||
| 80 | +| Items | One line per tool naming that menu, in file order. Nothing else — `Create tools file` and `Open tools file` stay in Python. | | ||
| 81 | +| Unreadable file | No menus at all; the Python menu carries the error | | ||
| 82 | +| While the editor runs | Added, removed and renamed as the file changes, without restarting | | ||
| 83 | + | ||
| 84 | +### Hot keys | ||
| 85 | + | ||
| 86 | +Assigned automatically, because a name from a file cannot be checked against the fixed menus in advance. | ||
| 87 | + | ||
| 88 | +| Case | Result | | ||
| 89 | +| --- | --- | | ||
| 90 | +| No tildes in the name | The first letter no other menu has claimed is marked. `Format` becomes `For~m~at`: `F` is File's, `o` is Options', `r` is Run's. | | ||
| 91 | +| Tildes naming a free letter | Kept as written. `Doc~k~er` answers to `Alt-K`. | | ||
| 92 | +| Tildes naming a taken letter | Dropped, and a free letter chosen instead. `~F~oo` becomes `F~o~o`. | | ||
| 93 | +| Every letter taken | No hot key. `F10` and the mouse still open it. | | ||
| 94 | + | ||
| 95 | +The letters the editor's own menus hold are `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` and `H`. | ||
| 96 | + | ||
| 97 | +## Running a command | ||
| 98 | + | ||
| 99 | +Common to every output: | ||
| 100 | + | ||
| 101 | +| Property | Value | | ||
| 102 | +| --- | --- | | ||
| 103 | +| Shell | `/bin/sh -c "<command>"` on Linux and macOS; `cmd.exe /S /C "<command>"` — the shell `%COMSPEC%` names — on Windows | | ||
| 104 | +| Directory | The directory the editor was started in | | ||
| 105 | +| Standard error | Merged into standard output, in the order the command wrote them | | ||
| 106 | + | ||
| 107 | +Going through a shell means pipes, globs, `&&` and `;` all work, so one tool can be a sequence. On Windows the shell is cmd.exe, which knows `&&`, `|` and `>` but does not expand globs, and where `;` is not a separator. | ||
| 108 | + | ||
| 109 | +### `output = "popup"` | ||
| 110 | + | ||
| 111 | +| Property | Value | | ||
| 112 | +| --- | --- | | ||
| 113 | +| Opens | Immediately, before the command has finished | | ||
| 114 | +| Modal | Yes: nothing else in the editor can be used while it is up | | ||
| 115 | +| Fills in | As output arrives, following it until you scroll back | | ||
| 116 | +| Title while running | `<command> — running` | | ||
| 117 | +| Title when finished | `<command> — ok`, or `<command> — exit <n>` | | ||
| 118 | +| Empty output, finished | Shows `(no output)` | | ||
| 119 | +| Empty output, running | Shows nothing | | ||
| 120 | +| Output cap | 10000 lines; past it the oldest go and a `… n earlier lines dropped …` line says so | | ||
| 121 | + | ||
| 122 | +| Key | Effect | | ||
| 123 | +| --- | --- | | ||
| 124 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Read through the output | | ||
| 125 | +| Wheel | The same | | ||
| 126 | +| `Escape`, `Enter`, **Close** | Close it, **stopping the command** if it is still running | | ||
| 127 | + | ||
| 128 | +Closing stops the command because there is no other way to interrupt one whose output is not in a terminal. | ||
| 129 | + | ||
| 130 | +### `output = "terminal"` | ||
| 131 | + | ||
| 132 | +| Property | Value | | ||
| 133 | +| --- | --- | | ||
| 134 | +| Window | A terminal window of its own, titled with the command | | ||
| 135 | +| Environment | The editor's own, with `TERM` set to `xterm-256color` | | ||
| 136 | +| After it exits | The window stays, showing its output | | ||
| 137 | +| Modal | No: the editor carries on beside it | | ||
| 138 | + | ||
| 139 | +Because it is a real terminal, colours, paging, `Ctrl-C` and reading from the keyboard all work. See [Terminal windows](terminal.md). | ||
| 140 | + | ||
| 141 | +Keys in a **finished** terminal window: | ||
| 142 | + | ||
| 143 | +| Key | Effect | | ||
| 144 | +| --- | --- | | ||
| 145 | +| `Shift-PgUp`, `Shift-PgDn` | Read back through the output | | ||
| 146 | +| `Ctrl-W` | Close the window | | ||
| 147 | +| Anything else | Reaches the editor, not the dead shell | | ||
| 148 | + | ||
| 149 | +### `output = "editor"` | ||
| 150 | + | ||
| 151 | +| Property | Value | | ||
| 152 | +| --- | --- | | ||
| 153 | +| Shows | A popup while it runs, as above | | ||
| 154 | +| On closing the popup | An editing window holding the output, titled with the command | | ||
| 155 | +| Filled | Once, when the command has finished — not as it goes | | ||
| 156 | +| The window | An ordinary editing window with no file name: searchable with `Ctrl-F`, and `Save as` keeps it | | ||
| 157 | + | ||
| 158 | +## Reloading after a command | ||
| 159 | + | ||
| 160 | +When a command finishes, every open file is considered. | ||
| 161 | + | ||
| 162 | +| The file | What happens | | ||
| 163 | +| --- | --- | | ||
| 164 | +| Unmodified, and changed on disk | Re-read; its syntax is re-decided and its title refreshed | | ||
| 165 | +| Unmodified, and unchanged on disk | Left alone, not counted | | ||
| 166 | +| Has unsaved changes | Left alone and counted as skipped | | ||
| 167 | +| Has never been named | Left alone | | ||
| 168 | +| Has gone from disk | Left alone | | ||
| 169 | + | ||
| 170 | +The cursor stays where it was, clamped into whatever the file now holds. The undo history is discarded, because undoing back past a reload would restore text the file no longer has. | ||
| 171 | + | ||
| 172 | +The project tree is refreshed at the same moment. | ||
| 173 | + | ||
| 174 | +| Status bar | When | | ||
| 175 | +| --- | --- | | ||
| 176 | +| `Running <command>` | The window opens | | ||
| 177 | +| `Reloaded 2 files` | Two files were re-read, none skipped | | ||
| 178 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Some were skipped | | ||
| 179 | +| `Command finished; 1 file with unsaved changes left alone` | Nothing was re-read, something was skipped | | ||
| 180 | + | ||
| 181 | +## Errors | ||
| 182 | + | ||
| 183 | +| Message | Cause | | ||
| 184 | +| --- | --- | | ||
| 185 | +| `Cannot read tools` in the menu | The file is present but not valid TOML, or holds a tool with no name or no command | | ||
| 186 | +| `Already there: .turbo-python/tools.toml` | Creating in a project that already has one. Unreachable from the menu, which greys the item out; still possible for a caller that is not a menu. | | ||
| 187 | +| `This project has no .turbo-python/tools.toml yet.` | Opening in a project that has none, likewise | | ||
| 188 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | ||
| 189 | +| `Terminal windows are not supported on this platform yet` | Running a command in a terminal needs a pseudo-terminal, which Linux, macOS and Windows have; see [Terminal windows](terminal.md) | | ||
| 190 | + | ||
| 191 | +## Asking for a value | ||
| 192 | + | ||
| 193 | +A `{{label}}` anywhere in a command is a value the editor asks for before it runs, in a box titled after the tool. The text between the braces is what the box asks for. | ||
| 194 | + | ||
| 195 | +| Written | Asked for | Substituted | | ||
| 196 | +| --- | --- | --- | | ||
| 197 | +| `{{module path}}` | `module path` | shell-quoted | | ||
| 198 | +| `{{extra flags...}}` | `extra flags` | verbatim | | ||
| 199 | + | ||
| 200 | +A value is **shell-quoted** by default, so a path with a space in it stays one argument. A trailing `...` inside the braces asks for it verbatim instead, which is how one field can stand for several arguments. | ||
| 201 | + | ||
| 202 | +```toml | ||
| 203 | +[[tool]] | ||
| 204 | +name = "~I~nit module" | ||
| 205 | +command = "go mod init {{module path}}" | ||
| 206 | +output = "popup" | ||
| 207 | +``` | ||
| 208 | + | ||
| 209 | +| Rule | Behaviour | | ||
| 210 | +| --- | --- | | ||
| 211 | +| Several placeholders | One box, one field each, in the order they appear in the command | | ||
| 212 | +| The same label twice | One field; every occurrence gets what is typed into it | | ||
| 213 | +| A label written both ways | Asked for once; each occurrence honours its own braces | | ||
| 214 | +| Escape, or Cancel | The command does not run | | ||
| 215 | +| A field left empty | Substituted as empty — the command reports its own complaint | | ||
| 216 | +| Running the tool again | The box starts from what was typed last time, for this session only | | ||
| 217 | +| More fields than fit on screen | Refused, with a message saying how many fit | | ||
| 218 | + | ||
| 219 | +**Double braces, not single.** `awk '{print $1}'` and `find . -exec rm {} +` are ordinary commands, and a single-brace syntax would read the first as a request for a value called `print $1`. | ||
| 220 | + | ||
| 221 | +Nothing is written to disk. A value somebody typed this afternoon is not a decision the project made, so it does not go in the project's own directory. | ||
| 222 | + | ||
| 223 | +### Errors | ||
| 224 | + | ||
| 225 | +| Error | Cause | | ||
| 226 | +| --- | --- | | ||
| 227 | +| `tool "X": "{{module" is never closed` | An opening `{{` with no `}}` after it | | ||
| 228 | +| `tool "X": {{}} asks for a value but does not say what it is` | A placeholder with no label, or one that is only `...` | | ||
| 229 | + | ||
| 230 | +Both are refused when the file is read, so a half-typed placeholder never reaches the shell with its braces still in it. | ||
| 231 | + | ||
| 232 | +## See also | ||
| 233 | + | ||
| 234 | +- [How to run uv commands from the editor](../how-to/run-uv-commands.md) | ||
| 235 | +- [Python tools](../explanation/python-tools.md) | ||
| 236 | +- [Terminal windows](terminal.md) | ||
added
docs/en/reference/snippets.md +114 -0 | new file mode 100644 | ||
| @@ -0,0 +1,114 @@ | ||
| 1 | +# Reference: snippets | |
| 2 | + | |
| 3 | +> Neutral description of the snippets files, the Snippets menu, and how a snippet is inserted. | |
| 4 | + | |
| 5 | +## Files | |
| 6 | + | |
| 7 | +Both are read, and both are optional. | |
| 8 | + | |
| 9 | +| File | Holds | | |
| 10 | +| --- | --- | | |
| 11 | +| `./.turbo-python/snippets.toml` | The project's snippets | | |
| 12 | +| `$TURBO_PYTHON_SNIPPET_DIR/snippets.toml`, else `<user config>/turbo-python/snippets.toml` | Your own, shared across projects | | |
| 13 | + | |
| 14 | +`<user config>` is `os.UserConfigDir()`: `~/.config` on Linux, `~/Library/Application Support` on macOS. | |
| 15 | + | |
| 16 | +| Property | Value | | |
| 17 | +| --- | --- | | |
| 18 | +| Project search | The working directory only. Parent directories are **not** searched. | | |
| 19 | +| Read | Every time the Snippets menu opens | | |
| 20 | +| Order | Your own first, then the project's | | |
| 21 | +| Name clash | Same `group` **and** `name` → the project's replaces yours | | |
| 22 | +| Missing file | Not an error | | |
| 23 | +| Unreadable file | An error, shown in the menu | | |
| 24 | + | |
| 25 | +## File format | |
| 26 | + | |
| 27 | +One `[[snippet]]` table per snippet. | |
| 28 | + | |
| 29 | +| Key | Type | Required | Description | | |
| 30 | +| --- | --- | --- | --- | | |
| 31 | +| `name` | string | yes | What the menu shows | | |
| 32 | +| `body` | string | yes | The text inserted at the cursor | | |
| 33 | +| `group` | string | no | The submenu it goes in; absent means `General` | | |
| 34 | +| `languages` | array of strings | no | Restricts the snippet to those languages; absent means every file | | |
| 35 | + | |
| 36 | +`languages` uses the editor's own language names: `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash`. See [Languages coloured](languages.md). | |
| 37 | + | |
| 38 | +A snippet with no `name` or no `body` makes the whole file an error — it could not be shown or could not be inserted. | |
| 39 | + | |
| 40 | +### Example | |
| 41 | + | |
| 42 | +```toml | |
| 43 | +[[snippet]] | |
| 44 | +name = "if err != nil" | |
| 45 | +group = "Python" | |
| 46 | +languages = ["python"] | |
| 47 | +body = """ | |
| 48 | +if err != nil { | |
| 49 | + return err | |
| 50 | +}""" | |
| 51 | +``` | |
| 52 | + | |
| 53 | +TOML's `"""` strings drop the newline immediately after the opening quotes, and interpret `\t` as a tab. | |
| 54 | + | |
| 55 | +## The menu | |
| 56 | + | |
| 57 | +| Item | Condition | | |
| 58 | +| --- | --- | | |
| 59 | +| One submenu per group, in the order the groups first appear in the files | A group with at least one snippet applying to the front window | | |
| 60 | +| `Cannot read snippets`, greyed out | A file is present but unreadable | | |
| 61 | +| `Create snippets file` | The project has no snippets file | | |
| 62 | +| `Open snippets file` | The project has one | | |
| 63 | + | |
| 64 | +The menu's hot key is `Alt-N`, not `Alt-S`: Search already answers to S. | |
| 65 | + | |
| 66 | +Groups, and the snippets inside them, come out in the order they were read, so the menu matches the files. | |
| 67 | + | |
| 68 | +A snippet item is greyed out when there is no file open to insert into — a terminal or the project tree in front counts as no file. | |
| 69 | + | |
| 70 | +### Filtering | |
| 71 | + | |
| 72 | +| Front window | Snippets offered | | |
| 73 | +| --- | --- | | |
| 74 | +| A file of a recognised language | Those naming that language, plus those naming none | | |
| 75 | +| A file of no recognised language | Those naming none | | |
| 76 | +| A terminal, the project tree, or nothing | Those naming none | | |
| 77 | + | |
| 78 | +## Insertion | |
| 79 | + | |
| 80 | +| Behaviour | Detail | | |
| 81 | +| --- | --- | | |
| 82 | +| Position | At the cursor | | |
| 83 | +| First line | Inserted where the cursor is | | |
| 84 | +| Later lines | Prefixed with the leading whitespace of the line the cursor was on | | |
| 85 | +| Blank lines in the body | Left blank, not padded with whitespace | | |
| 86 | +| Undo | One step for the whole snippet | | |
| 87 | +| Cursor after | At the end of the inserted text | | |
| 88 | +| Report | `Snippet inserted` on the status bar | | |
| 89 | + | |
| 90 | +The indent copied is the **whitespace prefix of the current line**, tabs or spaces as they were, so a snippet follows whatever the file already uses. | |
| 91 | + | |
| 92 | +## Menu items | |
| 93 | + | |
| 94 | +| Item | Menu | Effect | | |
| 95 | +| --- | --- | --- | | |
| 96 | +| Create snippets file | Snippets | Writes `.turbo-python/snippets.toml` with worked examples, then opens it. Greyed out once the project has one. | | |
| 97 | +| Open snippets file | Snippets | Opens `.turbo-python/snippets.toml`. Greyed out until the project has one. Always the project's file, never your own — it is the file the item above it writes. | | |
| 98 | + | |
| 99 | +The file is written through a temporary file in the same directory, renamed into place, so an interrupted write leaves the previous file intact. | |
| 100 | + | |
| 101 | +## Errors | |
| 102 | + | |
| 103 | +| Message | Cause | | |
| 104 | +| --- | --- | | |
| 105 | +| `Cannot read snippets` in the menu | A snippets file is present but not valid TOML, or holds a snippet with no name or no body | | |
| 106 | +| `Already there: .turbo-python/snippets.toml` | Creating in a project that already has one. Unreachable from the menu, which greys the item out; still possible for a caller that is not a menu. | | |
| 107 | +| `This project has no .turbo-python/snippets.toml yet.` | Opening in a project that has none, likewise | | |
| 108 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | |
| 109 | + | |
| 110 | +## See also | |
| 111 | + | |
| 112 | +- [How to insert snippets from a menu](../how-to/use-snippets.md) | |
| 113 | +- [Snippets](../explanation/snippets.md) | |
| 114 | +- [Keyboard](keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,114 @@ | |||
| 1 | +# Reference: snippets | ||
| 2 | + | ||
| 3 | +> Neutral description of the snippets files, the Snippets menu, and how a snippet is inserted. | ||
| 4 | + | ||
| 5 | +## Files | ||
| 6 | + | ||
| 7 | +Both are read, and both are optional. | ||
| 8 | + | ||
| 9 | +| File | Holds | | ||
| 10 | +| --- | --- | | ||
| 11 | +| `./.turbo-python/snippets.toml` | The project's snippets | | ||
| 12 | +| `$TURBO_PYTHON_SNIPPET_DIR/snippets.toml`, else `<user config>/turbo-python/snippets.toml` | Your own, shared across projects | | ||
| 13 | + | ||
| 14 | +`<user config>` is `os.UserConfigDir()`: `~/.config` on Linux, `~/Library/Application Support` on macOS. | ||
| 15 | + | ||
| 16 | +| Property | Value | | ||
| 17 | +| --- | --- | | ||
| 18 | +| Project search | The working directory only. Parent directories are **not** searched. | | ||
| 19 | +| Read | Every time the Snippets menu opens | | ||
| 20 | +| Order | Your own first, then the project's | | ||
| 21 | +| Name clash | Same `group` **and** `name` → the project's replaces yours | | ||
| 22 | +| Missing file | Not an error | | ||
| 23 | +| Unreadable file | An error, shown in the menu | | ||
| 24 | + | ||
| 25 | +## File format | ||
| 26 | + | ||
| 27 | +One `[[snippet]]` table per snippet. | ||
| 28 | + | ||
| 29 | +| Key | Type | Required | Description | | ||
| 30 | +| --- | --- | --- | --- | | ||
| 31 | +| `name` | string | yes | What the menu shows | | ||
| 32 | +| `body` | string | yes | The text inserted at the cursor | | ||
| 33 | +| `group` | string | no | The submenu it goes in; absent means `General` | | ||
| 34 | +| `languages` | array of strings | no | Restricts the snippet to those languages; absent means every file | | ||
| 35 | + | ||
| 36 | +`languages` uses the editor's own language names: `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash`. See [Languages coloured](languages.md). | ||
| 37 | + | ||
| 38 | +A snippet with no `name` or no `body` makes the whole file an error — it could not be shown or could not be inserted. | ||
| 39 | + | ||
| 40 | +### Example | ||
| 41 | + | ||
| 42 | +```toml | ||
| 43 | +[[snippet]] | ||
| 44 | +name = "if err != nil" | ||
| 45 | +group = "Python" | ||
| 46 | +languages = ["python"] | ||
| 47 | +body = """ | ||
| 48 | +if err != nil { | ||
| 49 | + return err | ||
| 50 | +}""" | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +TOML's `"""` strings drop the newline immediately after the opening quotes, and interpret `\t` as a tab. | ||
| 54 | + | ||
| 55 | +## The menu | ||
| 56 | + | ||
| 57 | +| Item | Condition | | ||
| 58 | +| --- | --- | | ||
| 59 | +| One submenu per group, in the order the groups first appear in the files | A group with at least one snippet applying to the front window | | ||
| 60 | +| `Cannot read snippets`, greyed out | A file is present but unreadable | | ||
| 61 | +| `Create snippets file` | The project has no snippets file | | ||
| 62 | +| `Open snippets file` | The project has one | | ||
| 63 | + | ||
| 64 | +The menu's hot key is `Alt-N`, not `Alt-S`: Search already answers to S. | ||
| 65 | + | ||
| 66 | +Groups, and the snippets inside them, come out in the order they were read, so the menu matches the files. | ||
| 67 | + | ||
| 68 | +A snippet item is greyed out when there is no file open to insert into — a terminal or the project tree in front counts as no file. | ||
| 69 | + | ||
| 70 | +### Filtering | ||
| 71 | + | ||
| 72 | +| Front window | Snippets offered | | ||
| 73 | +| --- | --- | | ||
| 74 | +| A file of a recognised language | Those naming that language, plus those naming none | | ||
| 75 | +| A file of no recognised language | Those naming none | | ||
| 76 | +| A terminal, the project tree, or nothing | Those naming none | | ||
| 77 | + | ||
| 78 | +## Insertion | ||
| 79 | + | ||
| 80 | +| Behaviour | Detail | | ||
| 81 | +| --- | --- | | ||
| 82 | +| Position | At the cursor | | ||
| 83 | +| First line | Inserted where the cursor is | | ||
| 84 | +| Later lines | Prefixed with the leading whitespace of the line the cursor was on | | ||
| 85 | +| Blank lines in the body | Left blank, not padded with whitespace | | ||
| 86 | +| Undo | One step for the whole snippet | | ||
| 87 | +| Cursor after | At the end of the inserted text | | ||
| 88 | +| Report | `Snippet inserted` on the status bar | | ||
| 89 | + | ||
| 90 | +The indent copied is the **whitespace prefix of the current line**, tabs or spaces as they were, so a snippet follows whatever the file already uses. | ||
| 91 | + | ||
| 92 | +## Menu items | ||
| 93 | + | ||
| 94 | +| Item | Menu | Effect | | ||
| 95 | +| --- | --- | --- | | ||
| 96 | +| Create snippets file | Snippets | Writes `.turbo-python/snippets.toml` with worked examples, then opens it. Greyed out once the project has one. | | ||
| 97 | +| Open snippets file | Snippets | Opens `.turbo-python/snippets.toml`. Greyed out until the project has one. Always the project's file, never your own — it is the file the item above it writes. | | ||
| 98 | + | ||
| 99 | +The file is written through a temporary file in the same directory, renamed into place, so an interrupted write leaves the previous file intact. | ||
| 100 | + | ||
| 101 | +## Errors | ||
| 102 | + | ||
| 103 | +| Message | Cause | | ||
| 104 | +| --- | --- | | ||
| 105 | +| `Cannot read snippets` in the menu | A snippets file is present but not valid TOML, or holds a snippet with no name or no body | | ||
| 106 | +| `Already there: .turbo-python/snippets.toml` | Creating in a project that already has one. Unreachable from the menu, which greys the item out; still possible for a caller that is not a menu. | | ||
| 107 | +| `This project has no .turbo-python/snippets.toml yet.` | Opening in a project that has none, likewise | | ||
| 108 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | ||
| 109 | + | ||
| 110 | +## See also | ||
| 111 | + | ||
| 112 | +- [How to insert snippets from a menu](../how-to/use-snippets.md) | ||
| 113 | +- [Snippets](../explanation/snippets.md) | ||
| 114 | +- [Keyboard](keyboard.md) | ||
added
docs/en/reference/terminal.md +228 -0 | new file mode 100644 | ||
| @@ -0,0 +1,228 @@ | ||
| 1 | +# Reference: terminal windows | |
| 2 | + | |
| 3 | +> Neutral description of the terminal windows Turbo Python opens, the keys they answer to, and the escape sequences the emulator implements. | |
| 4 | + | |
| 5 | +## Opening | |
| 6 | + | |
| 7 | +| Route | Condition | | |
| 8 | +| --- | --- | | |
| 9 | +| `F8` | Always | | |
| 10 | +| **Window ▸ New terminal** | Always | | |
| 11 | + | |
| 12 | +Neither requires a file to be open. | |
| 13 | + | |
| 14 | +## The shell | |
| 15 | + | |
| 16 | +| Property | Value | | |
| 17 | +| --- | --- | | |
| 18 | +| Program | `$SHELL`, or `/bin/sh` when it is unset or empty; on Windows `%COMSPEC%`, or `cmd.exe` | | |
| 19 | +| Working directory | The directory of the file in the front window; the editor's working directory when no file is open | | |
| 20 | +| `TERM` | `xterm-256color`, always — replacing any inherited value | | |
| 21 | +| Environment | The editor's own, with `TERM` replaced | | |
| 22 | +| Controlling terminal | Yes: on Linux and macOS the shell runs in its own session with the pseudo-terminal as its controlling terminal; on Windows it is attached to a pseudo-console. Either way job control and `Ctrl-C` work | | |
| 23 | +| Initial size | The window's, updated whenever the window is resized | | |
| 24 | + | |
| 25 | +## Platform support | |
| 26 | + | |
| 27 | +| Platform | Behaviour | | |
| 28 | +| --- | --- | | |
| 29 | +| Linux | Supported (`/dev/ptmx`) | | |
| 30 | +| macOS | Supported (`/dev/ptmx`) | | |
| 31 | +| Windows | Supported (pseudo-console, ConPTY): Windows 10 version 1809 or later. Built and vetted; **not yet run by the authors** on a Windows machine | | |
| 32 | +| Others | `F8` opens a message saying terminal windows are not supported yet; nothing else changes | | |
| 33 | + | |
| 34 | +## Keys | |
| 35 | + | |
| 36 | +### After the program has gone | |
| 37 | + | |
| 38 | +A window whose command has finished keeps its output, but stops behaving like a terminal: only `Shift-PgUp` and `Shift-PgDn` are still taken, and every other key reaches the editor — which is what lets `Ctrl-W` close it. | |
| 39 | + | |
| 40 | +### Sent to the shell | |
| 41 | + | |
| 42 | +Every key not listed under "kept by the editor" below, encoded as a terminal expects it. | |
| 43 | + | |
| 44 | +| Key | Bytes sent | | |
| 45 | +| --- | --- | | |
| 46 | +| printable character | its UTF-8 encoding | | |
| 47 | +| `Alt-<key>` | `ESC` followed by that key's own bytes | | |
| 48 | +| `Ctrl-A` … `Ctrl-Z` | `0x01` … `0x1a` | | |
| 49 | +| `Enter` | `\r` | | |
| 50 | +| `Tab` | `\t` | | |
| 51 | +| `Shift-Tab` | `ESC [ Z` | | |
| 52 | +| `Backspace` | `0x7f` | | |
| 53 | +| `Escape` | `0x1b` | | |
| 54 | +| `↑` `↓` `→` `←` | `ESC [ A B C D`, or `ESC O A B C D` in application cursor mode | | |
| 55 | +| `Home` `End` | `ESC [ H`, `ESC [ F`, or the `ESC O` forms in application cursor mode | | |
| 56 | +| `Insert` `Delete` | `ESC [ 2~`, `ESC [ 3~` | | |
| 57 | +| `PgUp` `PgDn` | `ESC [ 5~`, `ESC [ 6~` | | |
| 58 | +| `F1` … `F4` | `ESC O P Q R S` | | |
| 59 | +| `F5` … `F12` | `ESC [ 15~ 17~ 18~ 19~ 20~ 21~ 23~ 24~` | | |
| 60 | + | |
| 61 | +A key with no terminal meaning sends nothing. | |
| 62 | + | |
| 63 | +### Kept by the editor | |
| 64 | + | |
| 65 | +| Key | Action | | |
| 66 | +| --- | --- | | |
| 67 | +| `F1` … `F12` | Their usual editor action | | |
| 68 | +| `Alt-X` | Exit | | |
| 69 | +| `Alt-0` … `Alt-9` | List windows / bring window 1…9 forward | | |
| 70 | + | |
| 71 | +Function keys therefore never reach a program inside a terminal window. | |
| 72 | + | |
| 73 | +### Handled by the terminal window itself | |
| 74 | + | |
| 75 | +| Key | Action | | |
| 76 | +| --- | --- | | |
| 77 | +| `Shift-PgUp` | Back one screenful through the history | | |
| 78 | +| `Shift-PgDn` | Forward one screenful | | |
| 79 | + | |
| 80 | +Any key sent to the shell also returns the view to the live screen. | |
| 81 | + | |
| 82 | +## Mouse | |
| 83 | + | |
| 84 | +| Action | Effect | | |
| 85 | +| --- | --- | | |
| 86 | +| Wheel up / down | Scroll three lines through the history | | |
| 87 | +| Click | Brings the window forward; not forwarded to the program | | |
| 88 | + | |
| 89 | +Mouse reporting is not implemented, so a program is never told about clicks. | |
| 90 | + | |
| 91 | +## History | |
| 92 | + | |
| 93 | +| Property | Value | | |
| 94 | +| --- | --- | | |
| 95 | +| Lines kept | 2000 | | |
| 96 | +| What is kept | Lines scrolled off the top of the primary screen only | | |
| 97 | +| Alternate screen | Not kept — a full-screen program leaves no history behind | | |
| 98 | + | |
| 99 | +## Emulation | |
| 100 | + | |
| 101 | +`TERM` is `xterm-256color`. What is implemented of it: | |
| 102 | + | |
| 103 | +### Control characters | |
| 104 | + | |
| 105 | +| Byte | Effect | | |
| 106 | +| --- | --- | | |
| 107 | +| `0x07` BEL | Noted; the editor does not sound it | | |
| 108 | +| `0x08` BS | Cursor left one column | | |
| 109 | +| `0x09` HT | To the next tab stop, every 8 columns | | |
| 110 | +| `0x0a` `0x0b` `0x0c` | Line feed | | |
| 111 | +| `0x0d` CR | To column 1 | | |
| 112 | + | |
| 113 | +### Escape sequences | |
| 114 | + | |
| 115 | +| Sequence | Name | Effect | | |
| 116 | +| --- | --- | --- | | |
| 117 | +| `ESC D` | IND | Line feed | | |
| 118 | +| `ESC E` | NEL | Carriage return and line feed | | |
| 119 | +| `ESC M` | RI | Reverse line feed, keeping the column | | |
| 120 | +| `ESC 7` | DECSC | Save cursor and style | | |
| 121 | +| `ESC 8` | DECRC | Restore cursor and style | | |
| 122 | +| `ESC c` | RIS | Full reset | | |
| 123 | + | |
| 124 | +### CSI sequences | |
| 125 | + | |
| 126 | +| Sequence | Name | Effect | | |
| 127 | +| --- | --- | --- | | |
| 128 | +| `CSI n A B C D` | CUU CUD CUF CUB | Move n cells up, down, right, left | | |
| 129 | +| `CSI n E F` | CNL CPL | n lines down / up, to column 1 | | |
| 130 | +| `CSI n G` | CHA | To column n | | |
| 131 | +| `CSI r ; c H`, `CSI r ; c f` | CUP HVP | To row r, column c | | |
| 132 | +| `CSI n d` | VPA | To row n | | |
| 133 | +| `CSI n J` | ED | Erase display: 0 to end, 1 to start, 2 or 3 all | | |
| 134 | +| `CSI n K` | EL | Erase line: 0 to end, 1 to start, 2 all | | |
| 135 | +| `CSI n L` | IL | Insert n blank lines at the cursor | | |
| 136 | +| `CSI n M` | DL | Delete n lines at the cursor | | |
| 137 | +| `CSI n @` | ICH | Insert n blank cells | | |
| 138 | +| `CSI n P` | DCH | Delete n cells | | |
| 139 | +| `CSI n X` | ECH | Erase n cells in place | | |
| 140 | +| `CSI n S` | SU | Scroll the region up n lines | | |
| 141 | +| `CSI n T` | SD | Scroll the region down n lines | | |
| 142 | +| `CSI t ; b r` | DECSTBM | Set the scroll region to rows t…b | | |
| 143 | +| `CSI s`, `CSI u` | SCP RCP | Save / restore the cursor | | |
| 144 | +| `CSI … m` | SGR | Colours and attributes, below | | |
| 145 | + | |
| 146 | +`IL` and `DL` do nothing when the cursor is outside the scroll region. | |
| 147 | + | |
| 148 | +### Private modes | |
| 149 | + | |
| 150 | +Set with `CSI ? n h`, cleared with `CSI ? n l`. | |
| 151 | + | |
| 152 | +| n | Name | Effect | | |
| 153 | +| --- | --- | --- | | |
| 154 | +| 1 | DECCKM | Application cursor keys: arrows send `ESC O x` | | |
| 155 | +| 7 | DECAWM | Auto-wrap at the right margin | | |
| 156 | +| 25 | DECTCEM | Show the cursor | | |
| 157 | +| 47, 1047 | | Alternate screen | | |
| 158 | +| 1048 | | Save / restore the cursor | | |
| 159 | +| 1049 | | Save the cursor, then the alternate screen | | |
| 160 | + | |
| 161 | +Any other mode is parsed and ignored. | |
| 162 | + | |
| 163 | +### SGR | |
| 164 | + | |
| 165 | +| Code | Effect | | |
| 166 | +| --- | --- | | |
| 167 | +| 0 | Reset | | |
| 168 | +| 1, 22 | Bold on / off | | |
| 169 | +| 2, 22 | Dim on / off | | |
| 170 | +| 3, 23 | Italic on / off | | |
| 171 | +| 4, 24 | Underline on / off | | |
| 172 | +| 5, 6, 25 | Blink on / off | | |
| 173 | +| 7, 27 | Reverse on / off | | |
| 174 | +| 9, 29 | Strike-through on / off | | |
| 175 | +| 30–37, 40–47 | The eight normal colours, foreground / background | | |
| 176 | +| 90–97, 100–107 | The eight bright colours, foreground / background | | |
| 177 | +| 38;5;n, 48;5;n | Palette colour n of 256 | | |
| 178 | +| 38;2;r;g;b, 48;2;r;g;b | 24-bit colour | | |
| 179 | +| 39, 49 | Back to the theme's colour | | |
| 180 | + | |
| 181 | +The sixteen named colours are tcell's, which means the palette the user's own terminal is configured with, not fixed hex values. An extended colour that runs out of parameters partway leaves the style unchanged. Any other code is ignored. | |
| 182 | + | |
| 183 | +### OSC | |
| 184 | + | |
| 185 | +| Sequence | Effect | | |
| 186 | +| --- | --- | | |
| 187 | +| `OSC 0 ; text BEL`, `OSC 2 ; text BEL` | Set the window title | | |
| 188 | +| `OSC … ST` | The `ESC \` terminator is accepted in place of BEL | | |
| 189 | + | |
| 190 | +The title is capped at 4096 bytes. Other OSC commands are parsed and ignored. | |
| 191 | + | |
| 192 | +### Consumed and ignored | |
| 193 | + | |
| 194 | +Parsed correctly, so they never appear as stray characters, but with no effect: | |
| 195 | + | |
| 196 | +| Sequence | Name | | |
| 197 | +| --- | --- | | |
| 198 | +| `ESC P …`, `ESC X …`, `ESC ^ …`, `ESC _ …` | DCS, SOS, PM, APC — read to their string terminator | | |
| 199 | +| `ESC (`, `ESC )`, `ESC *`, `ESC +`, `ESC %`, `ESC #`, `ESC <space>` | Character-set and line-size selectors — the emulator works in UTF-8 regardless | | |
| 200 | +| `CSI ? n h`, `CSI ? n l` for any other n | Private modes not listed above | | |
| 201 | +| Any other CSI final byte, SGR code, or OSC command | | | |
| 202 | + | |
| 203 | +### Not implemented | |
| 204 | + | |
| 205 | +Mouse reporting, bracketed paste, shift-in / shift-out, double-width lines, sixel and other graphics protocols, and the DEC status and device-attribute reports. A program that asks for one of these gets no reply, so a program that waits for one waits forever. | |
| 206 | + | |
| 207 | +## Colours | |
| 208 | + | |
| 209 | +| Theme key | What it colours | | |
| 210 | +| --- | --- | | |
| 211 | +| `terminal.text` | Every cell whose colour the program did not choose | | |
| 212 | +| `terminal.cursor` | The cell under the cursor, when the window has the focus | | |
| 213 | + | |
| 214 | +See [Theme file format](themes.md). | |
| 215 | + | |
| 216 | +## Errors | |
| 217 | + | |
| 218 | +| Message | Cause | | |
| 219 | +| --- | --- | | |
| 220 | +| Terminal windows are not supported on this platform yet | The build has no pseudo-terminal support: any platform other than Linux, macOS and Windows | | |
| 221 | +| `openpt: …`, `grantpt: …`, `ptsname: …` | The operating system refused to open a pseudo-terminal | | |
| 222 | +| `fork/exec …: no such file or directory` | `$SHELL` names a program that does not exist | | |
| 223 | + | |
| 224 | +## See also | |
| 225 | + | |
| 226 | +- [How to run shell commands without leaving the editor](../how-to/use-a-terminal.md) | |
| 227 | +- [Terminal windows](../explanation/terminal-windows.md) | |
| 228 | +- [Keyboard](keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,228 @@ | |||
| 1 | +# Reference: terminal windows | ||
| 2 | + | ||
| 3 | +> Neutral description of the terminal windows Turbo Python opens, the keys they answer to, and the escape sequences the emulator implements. | ||
| 4 | + | ||
| 5 | +## Opening | ||
| 6 | + | ||
| 7 | +| Route | Condition | | ||
| 8 | +| --- | --- | | ||
| 9 | +| `F8` | Always | | ||
| 10 | +| **Window ▸ New terminal** | Always | | ||
| 11 | + | ||
| 12 | +Neither requires a file to be open. | ||
| 13 | + | ||
| 14 | +## The shell | ||
| 15 | + | ||
| 16 | +| Property | Value | | ||
| 17 | +| --- | --- | | ||
| 18 | +| Program | `$SHELL`, or `/bin/sh` when it is unset or empty; on Windows `%COMSPEC%`, or `cmd.exe` | | ||
| 19 | +| Working directory | The directory of the file in the front window; the editor's working directory when no file is open | | ||
| 20 | +| `TERM` | `xterm-256color`, always — replacing any inherited value | | ||
| 21 | +| Environment | The editor's own, with `TERM` replaced | | ||
| 22 | +| Controlling terminal | Yes: on Linux and macOS the shell runs in its own session with the pseudo-terminal as its controlling terminal; on Windows it is attached to a pseudo-console. Either way job control and `Ctrl-C` work | | ||
| 23 | +| Initial size | The window's, updated whenever the window is resized | | ||
| 24 | + | ||
| 25 | +## Platform support | ||
| 26 | + | ||
| 27 | +| Platform | Behaviour | | ||
| 28 | +| --- | --- | | ||
| 29 | +| Linux | Supported (`/dev/ptmx`) | | ||
| 30 | +| macOS | Supported (`/dev/ptmx`) | | ||
| 31 | +| Windows | Supported (pseudo-console, ConPTY): Windows 10 version 1809 or later. Built and vetted; **not yet run by the authors** on a Windows machine | | ||
| 32 | +| Others | `F8` opens a message saying terminal windows are not supported yet; nothing else changes | | ||
| 33 | + | ||
| 34 | +## Keys | ||
| 35 | + | ||
| 36 | +### After the program has gone | ||
| 37 | + | ||
| 38 | +A window whose command has finished keeps its output, but stops behaving like a terminal: only `Shift-PgUp` and `Shift-PgDn` are still taken, and every other key reaches the editor — which is what lets `Ctrl-W` close it. | ||
| 39 | + | ||
| 40 | +### Sent to the shell | ||
| 41 | + | ||
| 42 | +Every key not listed under "kept by the editor" below, encoded as a terminal expects it. | ||
| 43 | + | ||
| 44 | +| Key | Bytes sent | | ||
| 45 | +| --- | --- | | ||
| 46 | +| printable character | its UTF-8 encoding | | ||
| 47 | +| `Alt-<key>` | `ESC` followed by that key's own bytes | | ||
| 48 | +| `Ctrl-A` … `Ctrl-Z` | `0x01` … `0x1a` | | ||
| 49 | +| `Enter` | `\r` | | ||
| 50 | +| `Tab` | `\t` | | ||
| 51 | +| `Shift-Tab` | `ESC [ Z` | | ||
| 52 | +| `Backspace` | `0x7f` | | ||
| 53 | +| `Escape` | `0x1b` | | ||
| 54 | +| `↑` `↓` `→` `←` | `ESC [ A B C D`, or `ESC O A B C D` in application cursor mode | | ||
| 55 | +| `Home` `End` | `ESC [ H`, `ESC [ F`, or the `ESC O` forms in application cursor mode | | ||
| 56 | +| `Insert` `Delete` | `ESC [ 2~`, `ESC [ 3~` | | ||
| 57 | +| `PgUp` `PgDn` | `ESC [ 5~`, `ESC [ 6~` | | ||
| 58 | +| `F1` … `F4` | `ESC O P Q R S` | | ||
| 59 | +| `F5` … `F12` | `ESC [ 15~ 17~ 18~ 19~ 20~ 21~ 23~ 24~` | | ||
| 60 | + | ||
| 61 | +A key with no terminal meaning sends nothing. | ||
| 62 | + | ||
| 63 | +### Kept by the editor | ||
| 64 | + | ||
| 65 | +| Key | Action | | ||
| 66 | +| --- | --- | | ||
| 67 | +| `F1` … `F12` | Their usual editor action | | ||
| 68 | +| `Alt-X` | Exit | | ||
| 69 | +| `Alt-0` … `Alt-9` | List windows / bring window 1…9 forward | | ||
| 70 | + | ||
| 71 | +Function keys therefore never reach a program inside a terminal window. | ||
| 72 | + | ||
| 73 | +### Handled by the terminal window itself | ||
| 74 | + | ||
| 75 | +| Key | Action | | ||
| 76 | +| --- | --- | | ||
| 77 | +| `Shift-PgUp` | Back one screenful through the history | | ||
| 78 | +| `Shift-PgDn` | Forward one screenful | | ||
| 79 | + | ||
| 80 | +Any key sent to the shell also returns the view to the live screen. | ||
| 81 | + | ||
| 82 | +## Mouse | ||
| 83 | + | ||
| 84 | +| Action | Effect | | ||
| 85 | +| --- | --- | | ||
| 86 | +| Wheel up / down | Scroll three lines through the history | | ||
| 87 | +| Click | Brings the window forward; not forwarded to the program | | ||
| 88 | + | ||
| 89 | +Mouse reporting is not implemented, so a program is never told about clicks. | ||
| 90 | + | ||
| 91 | +## History | ||
| 92 | + | ||
| 93 | +| Property | Value | | ||
| 94 | +| --- | --- | | ||
| 95 | +| Lines kept | 2000 | | ||
| 96 | +| What is kept | Lines scrolled off the top of the primary screen only | | ||
| 97 | +| Alternate screen | Not kept — a full-screen program leaves no history behind | | ||
| 98 | + | ||
| 99 | +## Emulation | ||
| 100 | + | ||
| 101 | +`TERM` is `xterm-256color`. What is implemented of it: | ||
| 102 | + | ||
| 103 | +### Control characters | ||
| 104 | + | ||
| 105 | +| Byte | Effect | | ||
| 106 | +| --- | --- | | ||
| 107 | +| `0x07` BEL | Noted; the editor does not sound it | | ||
| 108 | +| `0x08` BS | Cursor left one column | | ||
| 109 | +| `0x09` HT | To the next tab stop, every 8 columns | | ||
| 110 | +| `0x0a` `0x0b` `0x0c` | Line feed | | ||
| 111 | +| `0x0d` CR | To column 1 | | ||
| 112 | + | ||
| 113 | +### Escape sequences | ||
| 114 | + | ||
| 115 | +| Sequence | Name | Effect | | ||
| 116 | +| --- | --- | --- | | ||
| 117 | +| `ESC D` | IND | Line feed | | ||
| 118 | +| `ESC E` | NEL | Carriage return and line feed | | ||
| 119 | +| `ESC M` | RI | Reverse line feed, keeping the column | | ||
| 120 | +| `ESC 7` | DECSC | Save cursor and style | | ||
| 121 | +| `ESC 8` | DECRC | Restore cursor and style | | ||
| 122 | +| `ESC c` | RIS | Full reset | | ||
| 123 | + | ||
| 124 | +### CSI sequences | ||
| 125 | + | ||
| 126 | +| Sequence | Name | Effect | | ||
| 127 | +| --- | --- | --- | | ||
| 128 | +| `CSI n A B C D` | CUU CUD CUF CUB | Move n cells up, down, right, left | | ||
| 129 | +| `CSI n E F` | CNL CPL | n lines down / up, to column 1 | | ||
| 130 | +| `CSI n G` | CHA | To column n | | ||
| 131 | +| `CSI r ; c H`, `CSI r ; c f` | CUP HVP | To row r, column c | | ||
| 132 | +| `CSI n d` | VPA | To row n | | ||
| 133 | +| `CSI n J` | ED | Erase display: 0 to end, 1 to start, 2 or 3 all | | ||
| 134 | +| `CSI n K` | EL | Erase line: 0 to end, 1 to start, 2 all | | ||
| 135 | +| `CSI n L` | IL | Insert n blank lines at the cursor | | ||
| 136 | +| `CSI n M` | DL | Delete n lines at the cursor | | ||
| 137 | +| `CSI n @` | ICH | Insert n blank cells | | ||
| 138 | +| `CSI n P` | DCH | Delete n cells | | ||
| 139 | +| `CSI n X` | ECH | Erase n cells in place | | ||
| 140 | +| `CSI n S` | SU | Scroll the region up n lines | | ||
| 141 | +| `CSI n T` | SD | Scroll the region down n lines | | ||
| 142 | +| `CSI t ; b r` | DECSTBM | Set the scroll region to rows t…b | | ||
| 143 | +| `CSI s`, `CSI u` | SCP RCP | Save / restore the cursor | | ||
| 144 | +| `CSI … m` | SGR | Colours and attributes, below | | ||
| 145 | + | ||
| 146 | +`IL` and `DL` do nothing when the cursor is outside the scroll region. | ||
| 147 | + | ||
| 148 | +### Private modes | ||
| 149 | + | ||
| 150 | +Set with `CSI ? n h`, cleared with `CSI ? n l`. | ||
| 151 | + | ||
| 152 | +| n | Name | Effect | | ||
| 153 | +| --- | --- | --- | | ||
| 154 | +| 1 | DECCKM | Application cursor keys: arrows send `ESC O x` | | ||
| 155 | +| 7 | DECAWM | Auto-wrap at the right margin | | ||
| 156 | +| 25 | DECTCEM | Show the cursor | | ||
| 157 | +| 47, 1047 | | Alternate screen | | ||
| 158 | +| 1048 | | Save / restore the cursor | | ||
| 159 | +| 1049 | | Save the cursor, then the alternate screen | | ||
| 160 | + | ||
| 161 | +Any other mode is parsed and ignored. | ||
| 162 | + | ||
| 163 | +### SGR | ||
| 164 | + | ||
| 165 | +| Code | Effect | | ||
| 166 | +| --- | --- | | ||
| 167 | +| 0 | Reset | | ||
| 168 | +| 1, 22 | Bold on / off | | ||
| 169 | +| 2, 22 | Dim on / off | | ||
| 170 | +| 3, 23 | Italic on / off | | ||
| 171 | +| 4, 24 | Underline on / off | | ||
| 172 | +| 5, 6, 25 | Blink on / off | | ||
| 173 | +| 7, 27 | Reverse on / off | | ||
| 174 | +| 9, 29 | Strike-through on / off | | ||
| 175 | +| 30–37, 40–47 | The eight normal colours, foreground / background | | ||
| 176 | +| 90–97, 100–107 | The eight bright colours, foreground / background | | ||
| 177 | +| 38;5;n, 48;5;n | Palette colour n of 256 | | ||
| 178 | +| 38;2;r;g;b, 48;2;r;g;b | 24-bit colour | | ||
| 179 | +| 39, 49 | Back to the theme's colour | | ||
| 180 | + | ||
| 181 | +The sixteen named colours are tcell's, which means the palette the user's own terminal is configured with, not fixed hex values. An extended colour that runs out of parameters partway leaves the style unchanged. Any other code is ignored. | ||
| 182 | + | ||
| 183 | +### OSC | ||
| 184 | + | ||
| 185 | +| Sequence | Effect | | ||
| 186 | +| --- | --- | | ||
| 187 | +| `OSC 0 ; text BEL`, `OSC 2 ; text BEL` | Set the window title | | ||
| 188 | +| `OSC … ST` | The `ESC \` terminator is accepted in place of BEL | | ||
| 189 | + | ||
| 190 | +The title is capped at 4096 bytes. Other OSC commands are parsed and ignored. | ||
| 191 | + | ||
| 192 | +### Consumed and ignored | ||
| 193 | + | ||
| 194 | +Parsed correctly, so they never appear as stray characters, but with no effect: | ||
| 195 | + | ||
| 196 | +| Sequence | Name | | ||
| 197 | +| --- | --- | | ||
| 198 | +| `ESC P …`, `ESC X …`, `ESC ^ …`, `ESC _ …` | DCS, SOS, PM, APC — read to their string terminator | | ||
| 199 | +| `ESC (`, `ESC )`, `ESC *`, `ESC +`, `ESC %`, `ESC #`, `ESC <space>` | Character-set and line-size selectors — the emulator works in UTF-8 regardless | | ||
| 200 | +| `CSI ? n h`, `CSI ? n l` for any other n | Private modes not listed above | | ||
| 201 | +| Any other CSI final byte, SGR code, or OSC command | | | ||
| 202 | + | ||
| 203 | +### Not implemented | ||
| 204 | + | ||
| 205 | +Mouse reporting, bracketed paste, shift-in / shift-out, double-width lines, sixel and other graphics protocols, and the DEC status and device-attribute reports. A program that asks for one of these gets no reply, so a program that waits for one waits forever. | ||
| 206 | + | ||
| 207 | +## Colours | ||
| 208 | + | ||
| 209 | +| Theme key | What it colours | | ||
| 210 | +| --- | --- | | ||
| 211 | +| `terminal.text` | Every cell whose colour the program did not choose | | ||
| 212 | +| `terminal.cursor` | The cell under the cursor, when the window has the focus | | ||
| 213 | + | ||
| 214 | +See [Theme file format](themes.md). | ||
| 215 | + | ||
| 216 | +## Errors | ||
| 217 | + | ||
| 218 | +| Message | Cause | | ||
| 219 | +| --- | --- | | ||
| 220 | +| Terminal windows are not supported on this platform yet | The build has no pseudo-terminal support: any platform other than Linux, macOS and Windows | | ||
| 221 | +| `openpt: …`, `grantpt: …`, `ptsname: …` | The operating system refused to open a pseudo-terminal | | ||
| 222 | +| `fork/exec …: no such file or directory` | `$SHELL` names a program that does not exist | | ||
| 223 | + | ||
| 224 | +## See also | ||
| 225 | + | ||
| 226 | +- [How to run shell commands without leaving the editor](../how-to/use-a-terminal.md) | ||
| 227 | +- [Terminal windows](../explanation/terminal-windows.md) | ||
| 228 | +- [Keyboard](keyboard.md) | ||
added
docs/en/reference/themes.md +236 -0 | new file mode 100644 | ||
| @@ -0,0 +1,236 @@ | ||
| 1 | +# Reference: theme file format | |
| 2 | + | |
| 3 | +> Neutral, exhaustive description of a Turbo Python theme file. | |
| 4 | + | |
| 5 | +A theme is a TOML file. Themes are read from the user theme directory first, then from the ones embedded in the binary; a user file wins over an embedded theme of the same name. | |
| 6 | + | |
| 7 | +## Locations | |
| 8 | + | |
| 9 | +| Location | Notes | | |
| 10 | +| --- | --- | | |
| 11 | +| `$TURBO_PYTHON_THEME_DIR` | Used when the variable is set and non-empty. | | |
| 12 | +| `~/.config/turbo-python/themes` | Linux (`os.UserConfigDir`). | | |
| 13 | +| `~/Library/Application Support/turbo-python/themes` | macOS. | | |
| 14 | +| embedded | `turbo-classic`, `turbo-dark`, `borland-light`, `cappuccino`, `catppuccin-frappe`, `catppuccin-latte`, `cobalt`, `darcula`, `intellij-light`, `monochrome-dark`, `monochrome-light`. | | |
| 15 | + | |
| 16 | +A theme's **name** for `-theme` and for `Options ▸ Theme…` is its file name without `.toml`. It may not contain `/`, `\` or `..`. | |
| 17 | + | |
| 18 | +## The themes that ship | |
| 19 | + | |
| 20 | +| Name | Ground | For | | |
| 21 | +| --- | --- | --- | | |
| 22 | +| `turbo-classic` | Borland navy | The default: the palette Turbo C had | | |
| 23 | +| `turbo-dark` | Neutral dark grey | Modern terminals with true colour | | |
| 24 | +| `borland-light` | Paper white | Bright rooms and projectors | | |
| 25 | +| `cappuccino` | Espresso brown | The Turbo layout with the temperature up: milk in the text, caramel where Turbo Dark puts blue | | |
| 26 | +| `catppuccin-frappe` | Warm slate | The Catppuccin Frappé palette, unchanged: pastel accents on a soft dark ground | | |
| 27 | +| `catppuccin-latte` | Warm paper | The Catppuccin Latte palette, unchanged: the same mapping with the saturation a light ground needs | | |
| 28 | +| `cobalt` | Deep navy | The Cobalt palette, accents kept as loud as they are known for | | |
| 29 | +| `darcula` | Charcoal | After JetBrains' Darcula: orange keywords, green strings, and the orange punctuation that makes it recognisable | | |
| 30 | +| `intellij-light` | White | After JetBrains' IntelliJ Light: blue bold keywords, green bold strings | | |
| 31 | +| `monochrome-dark` | Black and greys | No hue at all — code told apart by lightness, bold, italic and underline | | |
| 32 | +| `monochrome-light` | Paper and greys | The same, the other way up: on paper the darkest grey is the loudest | | |
| 33 | + | |
| 34 | +Every one of them **states its whole palette** rather than inheriting most of it. A theme you write yourself may inherit; see [writing one](../how-to/write-a-theme.md). | |
| 35 | + | |
| 36 | +## A name a theme used to answer to | |
| 37 | + | |
| 38 | +`monochrome` still loads. It is what this theme shipped as before `monochrome-light` joined it and the pair was renamed, and a settings file or a `-theme` flag saying `monochrome` gets `monochrome-dark`. | |
| 39 | + | |
| 40 | +| Retired name | Loads | | |
| 41 | +| --- | --- | | |
| 42 | +| `monochrome` | `monochrome-dark` | | |
| 43 | + | |
| 44 | +A retired name is **not** listed by `-theme` or by **Options ▸ Theme…**, so each theme appears once, under the name it has now. A theme of your own called `monochrome.toml` still wins over it, exactly as it would for any other name. | |
| 45 | + | |
| 46 | +## Top-level fields | |
| 47 | + | |
| 48 | +| Field | Type | Default | Description | | |
| 49 | +| --- | --- | --- | --- | | |
| 50 | +| `name` | string | the file's base name | Display name, shown in the theme picker and the About box. | | |
| 51 | +| `description` | string | `""` | One line, shown by `-list-themes`. | | |
| 52 | +| `inherits` | string | none | Name of a theme to start from. Its resolved styles are the base; this file overrides what it names. Chains are capped at 16 hops. | | |
| 53 | +| `colors` | table | `{}` | The styles. Keys are the style keys below. | | |
| 54 | + | |
| 55 | +## Entry fields | |
| 56 | + | |
| 57 | +Each value under `[colors]` is an inline table: | |
| 58 | + | |
| 59 | +| Field | Type | Default | Description | | |
| 60 | +| --- | --- | --- | --- | | |
| 61 | +| `fg` | string | inherited | Foreground colour. | | |
| 62 | +| `bg` | string | inherited | Background colour. | | |
| 63 | +| `bold` | bool | `false` | Switch bold on. | | |
| 64 | +| `underline` | bool | `false` | Switch underline on. | | |
| 65 | +| `italic` | bool | `false` | Switch italic on. | | |
| 66 | +| `reverse` | bool | `false` | Swap foreground and background. | | |
| 67 | +| `dim` | bool | `false` | Switch dim on. | | |
| 68 | +| `blink` | bool | `false` | Switch blink on. | | |
| 69 | + | |
| 70 | +Attributes are only ever switched **on**; there is no way to switch an inherited attribute off other than by not inheriting it. | |
| 71 | + | |
| 72 | +## Colour values | |
| 73 | + | |
| 74 | +| Form | Example | Notes | | |
| 75 | +| --- | --- | --- | | |
| 76 | +| ANSI name | `navy`, `aqua`, `silver`, `fuchsia` | The sixteen names, plus the full W3C list. | | |
| 77 | +| Hex literal | `#5fafd7` | 24-bit; tcell approximates it on terminals without true colour. | | |
| 78 | +| `default` | `default` | Whatever the terminal itself uses. | | |
| 79 | +| `-` | `-` | Same as `default`. | | |
| 80 | +| `""` | `""` | Same as `default`. | | |
| 81 | + | |
| 82 | +The sixteen ANSI names: `black` `maroon` `green` `olive` `navy` `purple` `teal` `silver` `gray` `red` `lime` `yellow` `blue` `fuchsia` `aqua` `white`. | |
| 83 | + | |
| 84 | +An unrecognised colour is a **load error**, not a silent fallback. | |
| 85 | + | |
| 86 | +## Style keys | |
| 87 | + | |
| 88 | +Undefined keys fall back along the dots, and finally to `default`. | |
| 89 | + | |
| 90 | +### Base | |
| 91 | + | |
| 92 | +| Key | What it colours | | |
| 93 | +| --- | --- | | |
| 94 | +| `default` | The last resort of every lookup | | |
| 95 | +| `desktop` | The patterned backdrop behind the windows | | |
| 96 | +| `shadow` | The cells a window darkens behind itself | | |
| 97 | + | |
| 98 | +### Menu bar | |
| 99 | + | |
| 100 | +| Key | What it colours | | |
| 101 | +| --- | --- | | |
| 102 | +| `menu.bar` | The row of titles | | |
| 103 | +| `menu.item` | A drop-down entry | | |
| 104 | +| `menu.selected` | The highlighted entry | | |
| 105 | +| `menu.shortcut` | The hot letter of a label | | |
| 106 | +| `menu.disabled` | An entry that cannot be chosen | | |
| 107 | + | |
| 108 | +### Windows | |
| 109 | + | |
| 110 | +| Key | What it colours | | |
| 111 | +| --- | --- | | |
| 112 | +| `window.frame.active` | The frame of the focused window | | |
| 113 | +| `window.frame.inactive` | Every other frame | | |
| 114 | +| `window.title.active` | The focused window's title | | |
| 115 | +| `window.title.inactive` | Every other title | | |
| 116 | +| `window.body` | The interior, before its content draws | | |
| 117 | + | |
| 118 | +### Bars | |
| 119 | + | |
| 120 | +| Key | What it colours | | |
| 121 | +| --- | --- | | |
| 122 | +| `statusbar` | The bar itself | | |
| 123 | +| `statusbar.key` | The `Fn` part of a hint | | |
| 124 | +| `statusbar.hint` | The right-aligned text | | |
| 125 | +| `scrollbar` | A scroll bar's track | | |
| 126 | +| `scrollbar.thumb` | Its thumb and arrows | | |
| 127 | + | |
| 128 | +### Dialogs and controls | |
| 129 | + | |
| 130 | +| Key | What it colours | | |
| 131 | +| --- | --- | | |
| 132 | +| `dialog.frame` | A dialog's frame | | |
| 133 | +| `dialog.body` | Its interior | | |
| 134 | +| `dialog.title` | Its title | | |
| 135 | +| `dialog.label` | A line of static text | | |
| 136 | +| `button` | A button | | |
| 137 | +| `button.focused` | The focused button | | |
| 138 | +| `button.shortcut` | The hot letter of a button | | |
| 139 | +| `input` | An input field | | |
| 140 | +| `input.focused` | The focused input field | | |
| 141 | +| `input.selection` | Selected text in an input field | | |
| 142 | +| `list` | A list box | | |
| 143 | +| `list.selected` | Its highlighted line, when focused | | |
| 144 | +| `list.unfocused` | Its highlighted line, when not | | |
| 145 | +| `checkbox` | A check box | | |
| 146 | +| `checkbox.focused` | The focused check box | | |
| 147 | + | |
| 148 | +### Editor | |
| 149 | + | |
| 150 | +| Key | What it colours | | |
| 151 | +| --- | --- | | |
| 152 | +| `editor.text` | Text no other rule claims | | |
| 153 | +| `editor.selection` | Selected text | | |
| 154 | +| `editor.linenumber` | The line-number gutter | | |
| 155 | +| `editor.currentline` | The line the cursor is on | | |
| 156 | +| `editor.cursor` | The cursor. Its **background** is also sent to the terminal as its cursor colour, and its foreground paints the character underneath. | | |
| 157 | + | |
| 158 | +### Terminal | |
| 159 | + | |
| 160 | +| Key | What it colours | | |
| 161 | +| --- | --- | | |
| 162 | +| `terminal.text` | Every cell of a terminal window whose colour the program running in it did not choose | | |
| 163 | +| `terminal.cursor` | The cell under a terminal's cursor, when that window has the focus | | |
| 164 | + | |
| 165 | +A program that names its own colours keeps them: these two only fill in what it left unset. See [Terminal windows](terminal.md). | |
| 166 | + | |
| 167 | +### Project tree | |
| 168 | + | |
| 169 | +| Key | What it colours | | |
| 170 | +| --- | --- | | |
| 171 | +| `tree.text` | A file's name in the project tree, and the tree's background | | |
| 172 | +| `tree.directory` | A directory's name | | |
| 173 | +| `tree.selected` | The highlighted row, when the tree has the focus | | |
| 174 | +| `tree.unfocused` | The highlighted row, when it does not | | |
| 175 | + | |
| 176 | +These are separate from the `list.*` keys on purpose: a dialog's list is coloured against a dialog, and reusing it would highlight a tree row in the very colour a window's body already is. See [Project tree](project-tree.md). | |
| 177 | + | |
| 178 | +### Syntax | |
| 179 | + | |
| 180 | +| Key | What it colours | | |
| 181 | +| --- | --- | | |
| 182 | +| `syntax.identifier` | An ordinary name | | |
| 183 | +| `syntax.keyword` | `func`, `if`, `package`, … | | |
| 184 | +| `syntax.type` | `int`, `string`, and a name after `type` | | |
| 185 | +| `syntax.builtin` | `len`, `append`, `make`, … | | |
| 186 | +| `syntax.constant` | `true`, `false`, `nil`, `iota` | | |
| 187 | +| `syntax.function` | A name before `(`, or after `func` | | |
| 188 | +| `syntax.string` | A string literal | | |
| 189 | +| `syntax.char` | A rune literal | | |
| 190 | +| `syntax.number` | An integer, float or imaginary literal | | |
| 191 | +| `syntax.comment` | `//` and `/* */` | | |
| 192 | +| `syntax.operator` | `+`, `:=`, `<-`, … | | |
| 193 | +| `syntax.punctuation` | Brackets, commas, dots, semicolons | | |
| 194 | +| `syntax.heading` | A Markdown heading, whole line | | |
| 195 | +| `syntax.tag` | An HTML element name and its brackets | | |
| 196 | +| `syntax.attribute` | An HTML attribute's name | | |
| 197 | +| `syntax.emphasis` | Markdown bold and italic | | |
| 198 | +| `syntax.link` | A Markdown link or image | | |
| 199 | + | |
| 200 | +Which language produces which class is in [Languages coloured](languages.md). | |
| 201 | + | |
| 202 | +### Completion and diagnostics | |
| 203 | + | |
| 204 | +| Key | What it colours | | |
| 205 | +| --- | --- | | |
| 206 | +| `completion.frame` | The popup's frame | | |
| 207 | +| `completion.item` | A suggestion | | |
| 208 | +| `completion.selected` | The highlighted suggestion | | |
| 209 | +| `completion.detail` | The kind tag beside a suggestion | | |
| 210 | +| `diagnostic.error` | An error from the language server | | |
| 211 | +| `diagnostic.warning` | A warning | | |
| 212 | +| `diagnostic.info` | A note | | |
| 213 | + | |
| 214 | +## Example | |
| 215 | + | |
| 216 | +```toml | |
| 217 | +name = "Mine" | |
| 218 | +description = "Turbo Classic, with readable comments." | |
| 219 | +inherits = "turbo-classic" | |
| 220 | + | |
| 221 | +[colors] | |
| 222 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | |
| 223 | +"syntax.string" = { fg = "#87d7af" } | |
| 224 | +"editor.currentline" = { bg = "#00005f" } | |
| 225 | +``` | |
| 226 | + | |
| 227 | +## Errors | |
| 228 | + | |
| 229 | +| Message | Cause | | |
| 230 | +| --- | --- | | |
| 231 | +| `theme: not found: "x"` | No `x.toml` in the user directory or among the embedded themes. | | |
| 232 | +| `theme: not found: "…" is not a plain theme name` | The name contains `/`, `\` or `..`. | | |
| 233 | +| `invalid TOML: …` | The file is not valid TOML. | | |
| 234 | +| `colors."k": fg: unknown colour "…"` | The colour name is not recognised. | | |
| 235 | +| `inherits: chain deeper than 16, probably a loop` | Two themes inherit from each other, directly or through others. | | |
| 236 | +| `inherits "x": theme: not found` | The parent named does not exist. | | |
| new file mode 100644 | |||
| @@ -0,0 +1,236 @@ | |||
| 1 | +# Reference: theme file format | ||
| 2 | + | ||
| 3 | +> Neutral, exhaustive description of a Turbo Python theme file. | ||
| 4 | + | ||
| 5 | +A theme is a TOML file. Themes are read from the user theme directory first, then from the ones embedded in the binary; a user file wins over an embedded theme of the same name. | ||
| 6 | + | ||
| 7 | +## Locations | ||
| 8 | + | ||
| 9 | +| Location | Notes | | ||
| 10 | +| --- | --- | | ||
| 11 | +| `$TURBO_PYTHON_THEME_DIR` | Used when the variable is set and non-empty. | | ||
| 12 | +| `~/.config/turbo-python/themes` | Linux (`os.UserConfigDir`). | | ||
| 13 | +| `~/Library/Application Support/turbo-python/themes` | macOS. | | ||
| 14 | +| embedded | `turbo-classic`, `turbo-dark`, `borland-light`, `cappuccino`, `catppuccin-frappe`, `catppuccin-latte`, `cobalt`, `darcula`, `intellij-light`, `monochrome-dark`, `monochrome-light`. | | ||
| 15 | + | ||
| 16 | +A theme's **name** for `-theme` and for `Options ▸ Theme…` is its file name without `.toml`. It may not contain `/`, `\` or `..`. | ||
| 17 | + | ||
| 18 | +## The themes that ship | ||
| 19 | + | ||
| 20 | +| Name | Ground | For | | ||
| 21 | +| --- | --- | --- | | ||
| 22 | +| `turbo-classic` | Borland navy | The default: the palette Turbo C had | | ||
| 23 | +| `turbo-dark` | Neutral dark grey | Modern terminals with true colour | | ||
| 24 | +| `borland-light` | Paper white | Bright rooms and projectors | | ||
| 25 | +| `cappuccino` | Espresso brown | The Turbo layout with the temperature up: milk in the text, caramel where Turbo Dark puts blue | | ||
| 26 | +| `catppuccin-frappe` | Warm slate | The Catppuccin Frappé palette, unchanged: pastel accents on a soft dark ground | | ||
| 27 | +| `catppuccin-latte` | Warm paper | The Catppuccin Latte palette, unchanged: the same mapping with the saturation a light ground needs | | ||
| 28 | +| `cobalt` | Deep navy | The Cobalt palette, accents kept as loud as they are known for | | ||
| 29 | +| `darcula` | Charcoal | After JetBrains' Darcula: orange keywords, green strings, and the orange punctuation that makes it recognisable | | ||
| 30 | +| `intellij-light` | White | After JetBrains' IntelliJ Light: blue bold keywords, green bold strings | | ||
| 31 | +| `monochrome-dark` | Black and greys | No hue at all — code told apart by lightness, bold, italic and underline | | ||
| 32 | +| `monochrome-light` | Paper and greys | The same, the other way up: on paper the darkest grey is the loudest | | ||
| 33 | + | ||
| 34 | +Every one of them **states its whole palette** rather than inheriting most of it. A theme you write yourself may inherit; see [writing one](../how-to/write-a-theme.md). | ||
| 35 | + | ||
| 36 | +## A name a theme used to answer to | ||
| 37 | + | ||
| 38 | +`monochrome` still loads. It is what this theme shipped as before `monochrome-light` joined it and the pair was renamed, and a settings file or a `-theme` flag saying `monochrome` gets `monochrome-dark`. | ||
| 39 | + | ||
| 40 | +| Retired name | Loads | | ||
| 41 | +| --- | --- | | ||
| 42 | +| `monochrome` | `monochrome-dark` | | ||
| 43 | + | ||
| 44 | +A retired name is **not** listed by `-theme` or by **Options ▸ Theme…**, so each theme appears once, under the name it has now. A theme of your own called `monochrome.toml` still wins over it, exactly as it would for any other name. | ||
| 45 | + | ||
| 46 | +## Top-level fields | ||
| 47 | + | ||
| 48 | +| Field | Type | Default | Description | | ||
| 49 | +| --- | --- | --- | --- | | ||
| 50 | +| `name` | string | the file's base name | Display name, shown in the theme picker and the About box. | | ||
| 51 | +| `description` | string | `""` | One line, shown by `-list-themes`. | | ||
| 52 | +| `inherits` | string | none | Name of a theme to start from. Its resolved styles are the base; this file overrides what it names. Chains are capped at 16 hops. | | ||
| 53 | +| `colors` | table | `{}` | The styles. Keys are the style keys below. | | ||
| 54 | + | ||
| 55 | +## Entry fields | ||
| 56 | + | ||
| 57 | +Each value under `[colors]` is an inline table: | ||
| 58 | + | ||
| 59 | +| Field | Type | Default | Description | | ||
| 60 | +| --- | --- | --- | --- | | ||
| 61 | +| `fg` | string | inherited | Foreground colour. | | ||
| 62 | +| `bg` | string | inherited | Background colour. | | ||
| 63 | +| `bold` | bool | `false` | Switch bold on. | | ||
| 64 | +| `underline` | bool | `false` | Switch underline on. | | ||
| 65 | +| `italic` | bool | `false` | Switch italic on. | | ||
| 66 | +| `reverse` | bool | `false` | Swap foreground and background. | | ||
| 67 | +| `dim` | bool | `false` | Switch dim on. | | ||
| 68 | +| `blink` | bool | `false` | Switch blink on. | | ||
| 69 | + | ||
| 70 | +Attributes are only ever switched **on**; there is no way to switch an inherited attribute off other than by not inheriting it. | ||
| 71 | + | ||
| 72 | +## Colour values | ||
| 73 | + | ||
| 74 | +| Form | Example | Notes | | ||
| 75 | +| --- | --- | --- | | ||
| 76 | +| ANSI name | `navy`, `aqua`, `silver`, `fuchsia` | The sixteen names, plus the full W3C list. | | ||
| 77 | +| Hex literal | `#5fafd7` | 24-bit; tcell approximates it on terminals without true colour. | | ||
| 78 | +| `default` | `default` | Whatever the terminal itself uses. | | ||
| 79 | +| `-` | `-` | Same as `default`. | | ||
| 80 | +| `""` | `""` | Same as `default`. | | ||
| 81 | + | ||
| 82 | +The sixteen ANSI names: `black` `maroon` `green` `olive` `navy` `purple` `teal` `silver` `gray` `red` `lime` `yellow` `blue` `fuchsia` `aqua` `white`. | ||
| 83 | + | ||
| 84 | +An unrecognised colour is a **load error**, not a silent fallback. | ||
| 85 | + | ||
| 86 | +## Style keys | ||
| 87 | + | ||
| 88 | +Undefined keys fall back along the dots, and finally to `default`. | ||
| 89 | + | ||
| 90 | +### Base | ||
| 91 | + | ||
| 92 | +| Key | What it colours | | ||
| 93 | +| --- | --- | | ||
| 94 | +| `default` | The last resort of every lookup | | ||
| 95 | +| `desktop` | The patterned backdrop behind the windows | | ||
| 96 | +| `shadow` | The cells a window darkens behind itself | | ||
| 97 | + | ||
| 98 | +### Menu bar | ||
| 99 | + | ||
| 100 | +| Key | What it colours | | ||
| 101 | +| --- | --- | | ||
| 102 | +| `menu.bar` | The row of titles | | ||
| 103 | +| `menu.item` | A drop-down entry | | ||
| 104 | +| `menu.selected` | The highlighted entry | | ||
| 105 | +| `menu.shortcut` | The hot letter of a label | | ||
| 106 | +| `menu.disabled` | An entry that cannot be chosen | | ||
| 107 | + | ||
| 108 | +### Windows | ||
| 109 | + | ||
| 110 | +| Key | What it colours | | ||
| 111 | +| --- | --- | | ||
| 112 | +| `window.frame.active` | The frame of the focused window | | ||
| 113 | +| `window.frame.inactive` | Every other frame | | ||
| 114 | +| `window.title.active` | The focused window's title | | ||
| 115 | +| `window.title.inactive` | Every other title | | ||
| 116 | +| `window.body` | The interior, before its content draws | | ||
| 117 | + | ||
| 118 | +### Bars | ||
| 119 | + | ||
| 120 | +| Key | What it colours | | ||
| 121 | +| --- | --- | | ||
| 122 | +| `statusbar` | The bar itself | | ||
| 123 | +| `statusbar.key` | The `Fn` part of a hint | | ||
| 124 | +| `statusbar.hint` | The right-aligned text | | ||
| 125 | +| `scrollbar` | A scroll bar's track | | ||
| 126 | +| `scrollbar.thumb` | Its thumb and arrows | | ||
| 127 | + | ||
| 128 | +### Dialogs and controls | ||
| 129 | + | ||
| 130 | +| Key | What it colours | | ||
| 131 | +| --- | --- | | ||
| 132 | +| `dialog.frame` | A dialog's frame | | ||
| 133 | +| `dialog.body` | Its interior | | ||
| 134 | +| `dialog.title` | Its title | | ||
| 135 | +| `dialog.label` | A line of static text | | ||
| 136 | +| `button` | A button | | ||
| 137 | +| `button.focused` | The focused button | | ||
| 138 | +| `button.shortcut` | The hot letter of a button | | ||
| 139 | +| `input` | An input field | | ||
| 140 | +| `input.focused` | The focused input field | | ||
| 141 | +| `input.selection` | Selected text in an input field | | ||
| 142 | +| `list` | A list box | | ||
| 143 | +| `list.selected` | Its highlighted line, when focused | | ||
| 144 | +| `list.unfocused` | Its highlighted line, when not | | ||
| 145 | +| `checkbox` | A check box | | ||
| 146 | +| `checkbox.focused` | The focused check box | | ||
| 147 | + | ||
| 148 | +### Editor | ||
| 149 | + | ||
| 150 | +| Key | What it colours | | ||
| 151 | +| --- | --- | | ||
| 152 | +| `editor.text` | Text no other rule claims | | ||
| 153 | +| `editor.selection` | Selected text | | ||
| 154 | +| `editor.linenumber` | The line-number gutter | | ||
| 155 | +| `editor.currentline` | The line the cursor is on | | ||
| 156 | +| `editor.cursor` | The cursor. Its **background** is also sent to the terminal as its cursor colour, and its foreground paints the character underneath. | | ||
| 157 | + | ||
| 158 | +### Terminal | ||
| 159 | + | ||
| 160 | +| Key | What it colours | | ||
| 161 | +| --- | --- | | ||
| 162 | +| `terminal.text` | Every cell of a terminal window whose colour the program running in it did not choose | | ||
| 163 | +| `terminal.cursor` | The cell under a terminal's cursor, when that window has the focus | | ||
| 164 | + | ||
| 165 | +A program that names its own colours keeps them: these two only fill in what it left unset. See [Terminal windows](terminal.md). | ||
| 166 | + | ||
| 167 | +### Project tree | ||
| 168 | + | ||
| 169 | +| Key | What it colours | | ||
| 170 | +| --- | --- | | ||
| 171 | +| `tree.text` | A file's name in the project tree, and the tree's background | | ||
| 172 | +| `tree.directory` | A directory's name | | ||
| 173 | +| `tree.selected` | The highlighted row, when the tree has the focus | | ||
| 174 | +| `tree.unfocused` | The highlighted row, when it does not | | ||
| 175 | + | ||
| 176 | +These are separate from the `list.*` keys on purpose: a dialog's list is coloured against a dialog, and reusing it would highlight a tree row in the very colour a window's body already is. See [Project tree](project-tree.md). | ||
| 177 | + | ||
| 178 | +### Syntax | ||
| 179 | + | ||
| 180 | +| Key | What it colours | | ||
| 181 | +| --- | --- | | ||
| 182 | +| `syntax.identifier` | An ordinary name | | ||
| 183 | +| `syntax.keyword` | `func`, `if`, `package`, … | | ||
| 184 | +| `syntax.type` | `int`, `string`, and a name after `type` | | ||
| 185 | +| `syntax.builtin` | `len`, `append`, `make`, … | | ||
| 186 | +| `syntax.constant` | `true`, `false`, `nil`, `iota` | | ||
| 187 | +| `syntax.function` | A name before `(`, or after `func` | | ||
| 188 | +| `syntax.string` | A string literal | | ||
| 189 | +| `syntax.char` | A rune literal | | ||
| 190 | +| `syntax.number` | An integer, float or imaginary literal | | ||
| 191 | +| `syntax.comment` | `//` and `/* */` | | ||
| 192 | +| `syntax.operator` | `+`, `:=`, `<-`, … | | ||
| 193 | +| `syntax.punctuation` | Brackets, commas, dots, semicolons | | ||
| 194 | +| `syntax.heading` | A Markdown heading, whole line | | ||
| 195 | +| `syntax.tag` | An HTML element name and its brackets | | ||
| 196 | +| `syntax.attribute` | An HTML attribute's name | | ||
| 197 | +| `syntax.emphasis` | Markdown bold and italic | | ||
| 198 | +| `syntax.link` | A Markdown link or image | | ||
| 199 | + | ||
| 200 | +Which language produces which class is in [Languages coloured](languages.md). | ||
| 201 | + | ||
| 202 | +### Completion and diagnostics | ||
| 203 | + | ||
| 204 | +| Key | What it colours | | ||
| 205 | +| --- | --- | | ||
| 206 | +| `completion.frame` | The popup's frame | | ||
| 207 | +| `completion.item` | A suggestion | | ||
| 208 | +| `completion.selected` | The highlighted suggestion | | ||
| 209 | +| `completion.detail` | The kind tag beside a suggestion | | ||
| 210 | +| `diagnostic.error` | An error from the language server | | ||
| 211 | +| `diagnostic.warning` | A warning | | ||
| 212 | +| `diagnostic.info` | A note | | ||
| 213 | + | ||
| 214 | +## Example | ||
| 215 | + | ||
| 216 | +```toml | ||
| 217 | +name = "Mine" | ||
| 218 | +description = "Turbo Classic, with readable comments." | ||
| 219 | +inherits = "turbo-classic" | ||
| 220 | + | ||
| 221 | +[colors] | ||
| 222 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | ||
| 223 | +"syntax.string" = { fg = "#87d7af" } | ||
| 224 | +"editor.currentline" = { bg = "#00005f" } | ||
| 225 | +``` | ||
| 226 | + | ||
| 227 | +## Errors | ||
| 228 | + | ||
| 229 | +| Message | Cause | | ||
| 230 | +| --- | --- | | ||
| 231 | +| `theme: not found: "x"` | No `x.toml` in the user directory or among the embedded themes. | | ||
| 232 | +| `theme: not found: "…" is not a plain theme name` | The name contains `/`, `\` or `..`. | | ||
| 233 | +| `invalid TOML: …` | The file is not valid TOML. | | ||
| 234 | +| `colors."k": fg: unknown colour "…"` | The colour name is not recognised. | | ||
| 235 | +| `inherits: chain deeper than 16, probably a loop` | Two themes inherit from each other, directly or through others. | | ||
| 236 | +| `inherits "x": theme: not found` | The parent named does not exist. | | ||
added
docs/en/reference/versioning.md +150 -0 | new file mode 100644 | ||
| @@ -0,0 +1,150 @@ | ||
| 1 | +# Reference: the version number | |
| 2 | + | |
| 3 | +> Neutral description of where the version Turbo Python reports comes from, and what each way of building it produces. | |
| 4 | + | |
| 5 | +## Where the number comes from | |
| 6 | + | |
| 7 | +Three sources, consulted in this order. The first that answers wins. | |
| 8 | + | |
| 9 | +| Order | Source | Set by | | |
| 10 | +| --- | --- | --- | | |
| 11 | +| 1 | Linker stamps | `make build`, `make install`, `scripts/install.sh` | | |
| 12 | +| 2 | Go build information | The Go tool, automatically | | |
| 13 | +| 3 | `unknown` | Nothing — the value reported when no source could name the build | | |
| 14 | + | |
| 15 | +There is **no version constant in the source**. A number written into a `.go` file has to be edited as part of releasing, and is wrong the moment someone forgets. | |
| 16 | + | |
| 17 | +## Linker stamps | |
| 18 | + | |
| 19 | +Three package-level variables in `internal/version`, set with `-ldflags -X`. | |
| 20 | + | |
| 21 | +| Variable | Filled from | Example | | |
| 22 | +| --- | --- | --- | | |
| 23 | +| `stamp` | `git describe --tags --dirty` | `v0.1.0-14-g88a4c38` | | |
| 24 | +| `commit` | `git rev-parse --short HEAD` | `88a4c38` | | |
| 25 | +| `built` | `date -u +%Y-%m-%dT%H:%M:%SZ` | `2026-08-31T18:04:05Z` | | |
| 26 | + | |
| 27 | +```sh | |
| 28 | +go build -ldflags "\ | |
| 29 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' \ | |
| 30 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.commit=88a4c38' \ | |
| 31 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.built=2026-08-31T18:04:05Z'" . | |
| 32 | +``` | |
| 33 | + | |
| 34 | +A leading `v` is dropped for display: the tag is `v0.2.0`, the About box says `0.2.0`. | |
| 35 | + | |
| 36 | +## Go build information | |
| 37 | + | |
| 38 | +Read from `runtime/debug.ReadBuildInfo()` when nothing was stamped. | |
| 39 | + | |
| 40 | +| Field read | Used for | | |
| 41 | +| --- | --- | | |
| 42 | +| `Main.Version` | The number, unless it is empty, `(devel)`, or a pseudo-version | | |
| 43 | +| `vcs.revision` | The commit, abbreviated to seven characters | | |
| 44 | +| `vcs.modified` | Whether `-dirty` is appended | | |
| 45 | + | |
| 46 | +`vcs.time` is **not** used. It records when the commit was made, not when the binary was linked, so reporting it as a build date would be wrong on every binary built later than its own commit. | |
| 47 | + | |
| 48 | +A **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — is the Go tool naming a commit that no tag names. It is reported as `devel`, not shown as written: its `0.1.1` is a patch release that does not exist. | |
| 49 | + | |
| 50 | +## What each build reports | |
| 51 | + | |
| 52 | +| Built by | Number | Commit | Built | | |
| 53 | +| --- | --- | --- | --- | | |
| 54 | +| `make build`, `make install`, `scripts/install.sh` | `0.1.0-14-g88a4c38` | yes | yes | | |
| 55 | +| The same, on a tagged commit | `0.2.0` | yes | yes | | |
| 56 | +| The same, with uncommitted changes | `0.1.0-14-g88a4c38-dirty` | yes | yes | | |
| 57 | +| `go install rickub.com/turbo-editors/turbo-python@v0.2.0` | `0.2.0` | no | no | | |
| 58 | +| `go build .` in a checkout | `devel` | yes | no | | |
| 59 | +| `go build .` in a checkout with uncommitted changes | `devel-dirty` | yes | no | | |
| 60 | +| `uv run` | `unknown` | no | no | | |
| 61 | +| A checkout with no git, and no stamps | `unknown` | no | no | | |
| 62 | + | |
| 63 | +Only the stamped rows can report a tag: the Go build system does not read git tags. | |
| 64 | + | |
| 65 | +## Checked at build time | |
| 66 | + | |
| 67 | +A linker stamp is a string, and a wrong one is not an error. `-X` naming a symbol that does not exist links happily and stamps nothing; the binary then falls back to Go build information and reports a version the build never meant — often `devel`, on a binary attached to a release. Nothing but running the binary catches it, so every build that produces one runs it. | |
| 68 | + | |
| 69 | +`scripts/check-version.sh` is what runs. | |
| 70 | + | |
| 71 | +| Called by | On | A failure fails | | |
| 72 | +| --- | --- | --- | | |
| 73 | +| `make build` | `bin/turbo-python`, with `$(VERSION)` and `$(COMMIT)` | the build | | |
| 74 | +| `scripts/install.sh` | the staged binary, **before** it is installed | the install, leaving the binary already there untouched | | |
| 75 | +| `03-build-releases.sh` | the one staged asset this machine can run, with the tag | the release build | | |
| 76 | + | |
| 77 | +```sh | |
| 78 | +scripts/check-version.sh bin/turbo-python v0.2.0 88a4c38 # a stamped build | |
| 79 | +scripts/check-version.sh bin/turbo-python # nothing to expect | |
| 80 | +``` | |
| 81 | + | |
| 82 | +| Arguments | Passes when | | |
| 83 | +| --- | --- | | |
| 84 | +| binary, version, commit | the reported number **equals** the version with its leading `v` dropped, and the commit appears in the output | | |
| 85 | +| binary, version | the number equals it | | |
| 86 | +| binary | the number is anything but `unknown` | | |
| 87 | + | |
| 88 | +The version comparison is an equality, not a search. `0.2.0` is a substring of `10.2.0`, and of a commit hash that happens to contain it; a stamp that is nearly right is exactly what this exists to catch. | |
| 89 | + | |
| 90 | +| Exit | Meaning | | |
| 91 | +| --- | --- | | |
| 92 | +| `0` | The binary reports what the build meant. The line it printed is echoed. | | |
| 93 | +| `1` | It does not run, is not there, or reports something else. | | |
| 94 | +| `2` | No binary was named. | | |
| 95 | + | |
| 96 | +## Where it is shown | |
| 97 | + | |
| 98 | +### `-version` | |
| 99 | + | |
| 100 | +One line, carrying every part that is known. | |
| 101 | + | |
| 102 | +``` | |
| 103 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | |
| 104 | +Turbo Python 0.2.0 (88a4c38) | |
| 105 | +Turbo Python 0.2.0 | |
| 106 | +``` | |
| 107 | + | |
| 108 | +### Help ▸ About | |
| 109 | + | |
| 110 | +One line per known fact. A fact the build did not record has **no line**, rather than an empty one. | |
| 111 | + | |
| 112 | +``` | |
| 113 | +Turbo Python 0.2.0 | |
| 114 | + | |
| 115 | +A Turbo C-style editor for Python, | |
| 116 | +written in Go. | |
| 117 | + | |
| 118 | +Commit: 88a4c38 | |
| 119 | +Built: 2026-08-31 18:04 UTC | |
| 120 | +Theme: Turbo Classic | |
| 121 | +``` | |
| 122 | + | |
| 123 | +`Built` is rendered in UTC as `YYYY-MM-DD HH:MM UTC`. A stamp that is not valid RFC 3339 is shown exactly as it was given, rather than dropped. | |
| 124 | + | |
| 125 | +### `make version` | |
| 126 | + | |
| 127 | +Prints what this checkout would stamp, without building. | |
| 128 | + | |
| 129 | +``` | |
| 130 | +$ make version | |
| 131 | +v0.1.0-14-g88a4c38 (88a4c38) | |
| 132 | +``` | |
| 133 | + | |
| 134 | +### `make ldflags` | |
| 135 | + | |
| 136 | +Prints the linker flags a stamped build uses, so a script can reuse them instead of repeating the `-X` paths. | |
| 137 | + | |
| 138 | +``` | |
| 139 | +$ make ldflags | |
| 140 | +-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' -X '….commit=7f8b36a' -X '….built=2026-08-31T19:02:03Z' | |
| 141 | +``` | |
| 142 | + | |
| 143 | +`03-build-releases.sh` reads it for its cross-compiles, overriding the version with the tag it is releasing — `make ldflags VERSION=v0.2.0` — so the binaries say what the release says rather than what `git describe` says. A binary cross-compiled without it reports `devel`, whatever the release it is attached to says. | |
| 144 | + | |
| 145 | +## See also | |
| 146 | + | |
| 147 | +- Cutting a release so the number is right: [How to make a release](../how-to/make-a-release.md) | |
| 148 | +- What `-version` is **not** for: it is written for a person. A script that needs the number should compare with `grep -F`, or ask git, rather than reading a field out of it. | |
| 149 | +- Why there is no version constant: [Design decisions](../explanation/design-decisions.md#the-version-is-a-property-of-the-build-not-of-the-source) | |
| 150 | +- The `-version` flag among the others: [Command line](cli.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,150 @@ | |||
| 1 | +# Reference: the version number | ||
| 2 | + | ||
| 3 | +> Neutral description of where the version Turbo Python reports comes from, and what each way of building it produces. | ||
| 4 | + | ||
| 5 | +## Where the number comes from | ||
| 6 | + | ||
| 7 | +Three sources, consulted in this order. The first that answers wins. | ||
| 8 | + | ||
| 9 | +| Order | Source | Set by | | ||
| 10 | +| --- | --- | --- | | ||
| 11 | +| 1 | Linker stamps | `make build`, `make install`, `scripts/install.sh` | | ||
| 12 | +| 2 | Go build information | The Go tool, automatically | | ||
| 13 | +| 3 | `unknown` | Nothing — the value reported when no source could name the build | | ||
| 14 | + | ||
| 15 | +There is **no version constant in the source**. A number written into a `.go` file has to be edited as part of releasing, and is wrong the moment someone forgets. | ||
| 16 | + | ||
| 17 | +## Linker stamps | ||
| 18 | + | ||
| 19 | +Three package-level variables in `internal/version`, set with `-ldflags -X`. | ||
| 20 | + | ||
| 21 | +| Variable | Filled from | Example | | ||
| 22 | +| --- | --- | --- | | ||
| 23 | +| `stamp` | `git describe --tags --dirty` | `v0.1.0-14-g88a4c38` | | ||
| 24 | +| `commit` | `git rev-parse --short HEAD` | `88a4c38` | | ||
| 25 | +| `built` | `date -u +%Y-%m-%dT%H:%M:%SZ` | `2026-08-31T18:04:05Z` | | ||
| 26 | + | ||
| 27 | +```sh | ||
| 28 | +go build -ldflags "\ | ||
| 29 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' \ | ||
| 30 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.commit=88a4c38' \ | ||
| 31 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.built=2026-08-31T18:04:05Z'" . | ||
| 32 | +``` | ||
| 33 | + | ||
| 34 | +A leading `v` is dropped for display: the tag is `v0.2.0`, the About box says `0.2.0`. | ||
| 35 | + | ||
| 36 | +## Go build information | ||
| 37 | + | ||
| 38 | +Read from `runtime/debug.ReadBuildInfo()` when nothing was stamped. | ||
| 39 | + | ||
| 40 | +| Field read | Used for | | ||
| 41 | +| --- | --- | | ||
| 42 | +| `Main.Version` | The number, unless it is empty, `(devel)`, or a pseudo-version | | ||
| 43 | +| `vcs.revision` | The commit, abbreviated to seven characters | | ||
| 44 | +| `vcs.modified` | Whether `-dirty` is appended | | ||
| 45 | + | ||
| 46 | +`vcs.time` is **not** used. It records when the commit was made, not when the binary was linked, so reporting it as a build date would be wrong on every binary built later than its own commit. | ||
| 47 | + | ||
| 48 | +A **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — is the Go tool naming a commit that no tag names. It is reported as `devel`, not shown as written: its `0.1.1` is a patch release that does not exist. | ||
| 49 | + | ||
| 50 | +## What each build reports | ||
| 51 | + | ||
| 52 | +| Built by | Number | Commit | Built | | ||
| 53 | +| --- | --- | --- | --- | | ||
| 54 | +| `make build`, `make install`, `scripts/install.sh` | `0.1.0-14-g88a4c38` | yes | yes | | ||
| 55 | +| The same, on a tagged commit | `0.2.0` | yes | yes | | ||
| 56 | +| The same, with uncommitted changes | `0.1.0-14-g88a4c38-dirty` | yes | yes | | ||
| 57 | +| `go install rickub.com/turbo-editors/turbo-python@v0.2.0` | `0.2.0` | no | no | | ||
| 58 | +| `go build .` in a checkout | `devel` | yes | no | | ||
| 59 | +| `go build .` in a checkout with uncommitted changes | `devel-dirty` | yes | no | | ||
| 60 | +| `uv run` | `unknown` | no | no | | ||
| 61 | +| A checkout with no git, and no stamps | `unknown` | no | no | | ||
| 62 | + | ||
| 63 | +Only the stamped rows can report a tag: the Go build system does not read git tags. | ||
| 64 | + | ||
| 65 | +## Checked at build time | ||
| 66 | + | ||
| 67 | +A linker stamp is a string, and a wrong one is not an error. `-X` naming a symbol that does not exist links happily and stamps nothing; the binary then falls back to Go build information and reports a version the build never meant — often `devel`, on a binary attached to a release. Nothing but running the binary catches it, so every build that produces one runs it. | ||
| 68 | + | ||
| 69 | +`scripts/check-version.sh` is what runs. | ||
| 70 | + | ||
| 71 | +| Called by | On | A failure fails | | ||
| 72 | +| --- | --- | --- | | ||
| 73 | +| `make build` | `bin/turbo-python`, with `$(VERSION)` and `$(COMMIT)` | the build | | ||
| 74 | +| `scripts/install.sh` | the staged binary, **before** it is installed | the install, leaving the binary already there untouched | | ||
| 75 | +| `03-build-releases.sh` | the one staged asset this machine can run, with the tag | the release build | | ||
| 76 | + | ||
| 77 | +```sh | ||
| 78 | +scripts/check-version.sh bin/turbo-python v0.2.0 88a4c38 # a stamped build | ||
| 79 | +scripts/check-version.sh bin/turbo-python # nothing to expect | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +| Arguments | Passes when | | ||
| 83 | +| --- | --- | | ||
| 84 | +| binary, version, commit | the reported number **equals** the version with its leading `v` dropped, and the commit appears in the output | | ||
| 85 | +| binary, version | the number equals it | | ||
| 86 | +| binary | the number is anything but `unknown` | | ||
| 87 | + | ||
| 88 | +The version comparison is an equality, not a search. `0.2.0` is a substring of `10.2.0`, and of a commit hash that happens to contain it; a stamp that is nearly right is exactly what this exists to catch. | ||
| 89 | + | ||
| 90 | +| Exit | Meaning | | ||
| 91 | +| --- | --- | | ||
| 92 | +| `0` | The binary reports what the build meant. The line it printed is echoed. | | ||
| 93 | +| `1` | It does not run, is not there, or reports something else. | | ||
| 94 | +| `2` | No binary was named. | | ||
| 95 | + | ||
| 96 | +## Where it is shown | ||
| 97 | + | ||
| 98 | +### `-version` | ||
| 99 | + | ||
| 100 | +One line, carrying every part that is known. | ||
| 101 | + | ||
| 102 | +``` | ||
| 103 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | ||
| 104 | +Turbo Python 0.2.0 (88a4c38) | ||
| 105 | +Turbo Python 0.2.0 | ||
| 106 | +``` | ||
| 107 | + | ||
| 108 | +### Help ▸ About | ||
| 109 | + | ||
| 110 | +One line per known fact. A fact the build did not record has **no line**, rather than an empty one. | ||
| 111 | + | ||
| 112 | +``` | ||
| 113 | +Turbo Python 0.2.0 | ||
| 114 | + | ||
| 115 | +A Turbo C-style editor for Python, | ||
| 116 | +written in Go. | ||
| 117 | + | ||
| 118 | +Commit: 88a4c38 | ||
| 119 | +Built: 2026-08-31 18:04 UTC | ||
| 120 | +Theme: Turbo Classic | ||
| 121 | +``` | ||
| 122 | + | ||
| 123 | +`Built` is rendered in UTC as `YYYY-MM-DD HH:MM UTC`. A stamp that is not valid RFC 3339 is shown exactly as it was given, rather than dropped. | ||
| 124 | + | ||
| 125 | +### `make version` | ||
| 126 | + | ||
| 127 | +Prints what this checkout would stamp, without building. | ||
| 128 | + | ||
| 129 | +``` | ||
| 130 | +$ make version | ||
| 131 | +v0.1.0-14-g88a4c38 (88a4c38) | ||
| 132 | +``` | ||
| 133 | + | ||
| 134 | +### `make ldflags` | ||
| 135 | + | ||
| 136 | +Prints the linker flags a stamped build uses, so a script can reuse them instead of repeating the `-X` paths. | ||
| 137 | + | ||
| 138 | +``` | ||
| 139 | +$ make ldflags | ||
| 140 | +-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' -X '….commit=7f8b36a' -X '….built=2026-08-31T19:02:03Z' | ||
| 141 | +``` | ||
| 142 | + | ||
| 143 | +`03-build-releases.sh` reads it for its cross-compiles, overriding the version with the tag it is releasing — `make ldflags VERSION=v0.2.0` — so the binaries say what the release says rather than what `git describe` says. A binary cross-compiled without it reports `devel`, whatever the release it is attached to says. | ||
| 144 | + | ||
| 145 | +## See also | ||
| 146 | + | ||
| 147 | +- Cutting a release so the number is right: [How to make a release](../how-to/make-a-release.md) | ||
| 148 | +- What `-version` is **not** for: it is written for a person. A script that needs the number should compare with `grep -F`, or ask git, rather than reading a field out of it. | ||
| 149 | +- Why there is no version constant: [Design decisions](../explanation/design-decisions.md#the-version-is-a-property-of-the-build-not-of-the-source) | ||
| 150 | +- The `-version` flag among the others: [Command line](cli.md) | ||
added
docs/en/tutorials/getting-started.md +216 -0 | new file mode 100644 | ||
| @@ -0,0 +1,216 @@ | ||
| 1 | +# Tutorial: your first file in Turbo Python | |
| 2 | + | |
| 3 | +By the end of this tutorial, you will have built the editor, written a small Python program inside it, watched the keywords turn colour as you typed, saved the file, and run it. It takes about ten minutes. | |
| 4 | + | |
| 5 | +No prior knowledge of Turbo Python is needed. You need Go 1.26 or later to build the editor, and [uv](https://docs.astral.sh/uv/) to make and run the Python project. | |
| 6 | + | |
| 7 | +## Prerequisites | |
| 8 | + | |
| 9 | +Check that Go is there — the editor is written in Go, even though it is an editor for Python: | |
| 10 | + | |
| 11 | +```bash | |
| 12 | +go version | |
| 13 | +``` | |
| 14 | + | |
| 15 | +You should see something like: | |
| 16 | + | |
| 17 | +``` | |
| 18 | +go version go1.26.5 linux/arm64 | |
| 19 | +``` | |
| 20 | + | |
| 21 | +If that command fails, install Go first: https://go.dev/dl/ | |
| 22 | + | |
| 23 | +Check that uv is there too: | |
| 24 | + | |
| 25 | +```bash | |
| 26 | +uv --version | |
| 27 | +``` | |
| 28 | + | |
| 29 | +You should see something like: | |
| 30 | + | |
| 31 | +``` | |
| 32 | +uv 0.9.26 | |
| 33 | +``` | |
| 34 | + | |
| 35 | +If that command fails, install uv first: https://docs.astral.sh/uv/getting-started/installation/ | |
| 36 | + | |
| 37 | +## Step 1 — Build the editor | |
| 38 | + | |
| 39 | +From the project directory, type: | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +make build | |
| 43 | +``` | |
| 44 | + | |
| 45 | +You should see a `go build` line, then a line naming the version the binary reports. That last line is a check, not decoration: it runs the binary you just linked and refuses a build whose version stamp never reached it. | |
| 46 | + | |
| 47 | +We now have an executable at `bin/turbo-python`. Remember where it is, so we can start it from anywhere: | |
| 48 | + | |
| 49 | +```bash | |
| 50 | +export TURBO="$PWD/bin/turbo-python" | |
| 51 | +``` | |
| 52 | + | |
| 53 | +## Step 2 — Create a place to work | |
| 54 | + | |
| 55 | +Turbo Python is at its best inside a project, so let us make one: | |
| 56 | + | |
| 57 | +```bash | |
| 58 | +cd /tmp && uv init hello && cd hello | |
| 59 | +``` | |
| 60 | + | |
| 61 | +You should see: | |
| 62 | + | |
| 63 | +``` | |
| 64 | +Initialized project `hello` at `/tmp/hello` | |
| 65 | +``` | |
| 66 | + | |
| 67 | +`uv init` writes a `pyproject.toml`, a `README.md`, a `.python-version` and a `main.py` with a hello-world in it. `pyproject.toml` is what Turbo Python looks for to find the root of a project, and it is where `pylsp` will be started. We are going to replace `main.py`'s contents with our own. | |
| 68 | + | |
| 69 | +## Step 3 — Open the editor | |
| 70 | + | |
| 71 | +Start Turbo Python on the file uv made: | |
| 72 | + | |
| 73 | +```bash | |
| 74 | +$TURBO main.py | |
| 75 | +``` | |
| 76 | + | |
| 77 | +The screen fills with a blue desktop. You should see: | |
| 78 | + | |
| 79 | +- a **menu bar** across the top: `File Edit Search Run Code Options Window Snippets Python Help` | |
| 80 | +- a **window** framed in a double line, titled `main.py` | |
| 81 | +- a **status bar** along the bottom: `F1 Describe F2 Save F3 Open …` | |
| 82 | + | |
| 83 | +The cursor is blinking at line 1, column 1 — the status bar says `1:1` on the right. | |
| 84 | + | |
| 85 | +Beside it, the status bar says one of two things. `LSP: ready` means the language server was found and started. `LSP: no pylsp — pipx install "python-lsp-server[all]"` means it was not, and names the one command that installs it. Either way the rest of this tutorial works; the [completion guide](../how-to/enable-completion.md) is where to go if you want the second to become the first. | |
| 86 | + | |
| 87 | +We are inside the editor. | |
| 88 | + | |
| 89 | +## Step 4 — Clear the file and type a Python program | |
| 90 | + | |
| 91 | +Press **Ctrl-A** to select everything uv wrote, then **Delete** to remove it. The window is now empty and its title reads `main.py *` — the star means there are unsaved changes. | |
| 92 | + | |
| 93 | +Type this line and press **Enter**: | |
| 94 | + | |
| 95 | +```python | |
| 96 | +def greet(name): | |
| 97 | +``` | |
| 98 | + | |
| 99 | +Watch the colours as you type. `def` turns **white and bold** the moment the word ends: it is a keyword. `greet` turns **yellow and bold** as soon as you type the `(` after it, because that makes it a function. `name` stays plain **yellow**: it is an ordinary identifier. | |
| 100 | + | |
| 101 | +(Those are Turbo Classic's colours, the ones the editor starts in. Step 8 changes them.) | |
| 102 | + | |
| 103 | +Now type four spaces yourself, and then the next line: | |
| 104 | + | |
| 105 | +```python | |
| 106 | + message = f"Hello from {name}!" | |
| 107 | +``` | |
| 108 | + | |
| 109 | +**Enter copies the current line's indentation; it does not add a level after a colon.** Python's blocks are made of indentation, and where a new one starts is not something the editor tries to guess — so the four spaces are yours to type once, and every line after this one keeps them for free. | |
| 110 | + | |
| 111 | +`f"Hello from {name}!"` turns **green**, all of it, including the `{name}` in the middle. It is one string: what is inside the braces is Python, but it is not coloured as Python, because deciding where an expression ends inside a literal needs a parser and this is a scanner. That trade-off is written down in [Colouring and completion](../explanation/colouring-and-completion.md). | |
| 112 | + | |
| 113 | +Press **Enter** — the cursor lands under the `m`, already indented — and type: | |
| 114 | + | |
| 115 | +```python | |
| 116 | + print(message) | |
| 117 | +``` | |
| 118 | + | |
| 119 | +`print` turns **aqua and bold**: it is one of the builtins the language provides rather than a name from your code. | |
| 120 | + | |
| 121 | +Press **Enter**, then **Shift-Tab** to take the indent back off, and type the last line: | |
| 122 | + | |
| 123 | +```python | |
| 124 | +greet("Turbo Python") | |
| 125 | +``` | |
| 126 | + | |
| 127 | +We have just written a complete Python program, with the editor colouring it as we went. | |
| 128 | + | |
| 129 | +If the status bar said `LSP: ready` earlier, look at the left edge of the last line: there is a `!` in the gutter. The language server has an opinion about our file, and **Code ▸ Problems…** says what it is — `warning main.py:4 E305 expected 2 blank lines after class or function definition`. It is a style rule rather than an error, and leaving it is fine; the point is that the mark and the message are there, and they arrive without anybody asking. | |
| 130 | + | |
| 131 | +## Step 5 — Save it | |
| 132 | + | |
| 133 | +Press **F2**. | |
| 134 | + | |
| 135 | +The star disappears from the title, and the status bar shows, for a moment: | |
| 136 | + | |
| 137 | +``` | |
| 138 | +Saved main.py | |
| 139 | +``` | |
| 140 | + | |
| 141 | +It goes back to the key hints after that — the message is a confirmation, not a state. The title without its star is the state. | |
| 142 | + | |
| 143 | +## Step 6 — Look at the file from outside | |
| 144 | + | |
| 145 | +Leave the editor by pressing **Alt-X**. The terminal comes back as it was. | |
| 146 | + | |
| 147 | +Check what we wrote: | |
| 148 | + | |
| 149 | +```bash | |
| 150 | +cat main.py | |
| 151 | +``` | |
| 152 | + | |
| 153 | +You should see: | |
| 154 | + | |
| 155 | +```python | |
| 156 | +def greet(name): | |
| 157 | + message = f"Hello from {name}!" | |
| 158 | + print(message) | |
| 159 | +greet("Turbo Python") | |
| 160 | +``` | |
| 161 | + | |
| 162 | +## Step 7 — Run it | |
| 163 | + | |
| 164 | +```bash | |
| 165 | +uv run main.py | |
| 166 | +``` | |
| 167 | + | |
| 168 | +The first run makes the environment, so you should see a line or two from uv before the output: | |
| 169 | + | |
| 170 | +``` | |
| 171 | +Using CPython 3.14.4 interpreter at: /usr/bin/python3.14 | |
| 172 | +Creating virtual environment at: .venv | |
| 173 | +Hello from Turbo Python! | |
| 174 | +``` | |
| 175 | + | |
| 176 | +That is a working Python program, written entirely inside the editor. | |
| 177 | + | |
| 178 | +## Step 8 — Change the theme | |
| 179 | + | |
| 180 | +Open the file again: | |
| 181 | + | |
| 182 | +```bash | |
| 183 | +$TURBO main.py | |
| 184 | +``` | |
| 185 | + | |
| 186 | +Press **F10**. The `File` menu drops open. Press **→** five times: the menu walks along the bar to `Options`, whose first item, `Theme…`, is highlighted. Press **Enter**. | |
| 187 | + | |
| 188 | +A list of eleven appears, in alphabetical order, with the theme you are using already highlighted: | |
| 189 | + | |
| 190 | +``` | |
| 191 | +borland-light | |
| 192 | +cappuccino | |
| 193 | +catppuccin-frappe | |
| 194 | +catppuccin-latte | |
| 195 | +cobalt | |
| 196 | +darcula | |
| 197 | +intellij-light | |
| 198 | +monochrome-dark | |
| 199 | +monochrome-light | |
| 200 | +turbo-classic | |
| 201 | +turbo-dark | |
| 202 | +``` | |
| 203 | + | |
| 204 | +`turbo-classic` is the highlighted row, because that is the theme you are in. Press **↓** once to move to `turbo-dark`, then press **Enter**. | |
| 205 | + | |
| 206 | +The whole editor repaints in dark grey, and the status bar says `Theme: Turbo Dark`. | |
| 207 | + | |
| 208 | +Press **Alt-X** to leave. | |
| 209 | + | |
| 210 | +## What now? | |
| 211 | + | |
| 212 | +You have built the editor, written a Python program in it, saved it, run it, and changed how it looks. | |
| 213 | + | |
| 214 | +- To do specific things — enable completion, write a theme of your own, search a file → see the [how-to guides](../how-to/) | |
| 215 | +- To look up a key or a menu item → see the [reference](../reference/) | |
| 216 | +- To understand how the colouring and the completion actually work → see the [explanation](../explanation/) | |
| new file mode 100644 | |||
| @@ -0,0 +1,216 @@ | |||
| 1 | +# Tutorial: your first file in Turbo Python | ||
| 2 | + | ||
| 3 | +By the end of this tutorial, you will have built the editor, written a small Python program inside it, watched the keywords turn colour as you typed, saved the file, and run it. It takes about ten minutes. | ||
| 4 | + | ||
| 5 | +No prior knowledge of Turbo Python is needed. You need Go 1.26 or later to build the editor, and [uv](https://docs.astral.sh/uv/) to make and run the Python project. | ||
| 6 | + | ||
| 7 | +## Prerequisites | ||
| 8 | + | ||
| 9 | +Check that Go is there — the editor is written in Go, even though it is an editor for Python: | ||
| 10 | + | ||
| 11 | +```bash | ||
| 12 | +go version | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +You should see something like: | ||
| 16 | + | ||
| 17 | +``` | ||
| 18 | +go version go1.26.5 linux/arm64 | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +If that command fails, install Go first: https://go.dev/dl/ | ||
| 22 | + | ||
| 23 | +Check that uv is there too: | ||
| 24 | + | ||
| 25 | +```bash | ||
| 26 | +uv --version | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +You should see something like: | ||
| 30 | + | ||
| 31 | +``` | ||
| 32 | +uv 0.9.26 | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +If that command fails, install uv first: https://docs.astral.sh/uv/getting-started/installation/ | ||
| 36 | + | ||
| 37 | +## Step 1 — Build the editor | ||
| 38 | + | ||
| 39 | +From the project directory, type: | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +make build | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +You should see a `go build` line, then a line naming the version the binary reports. That last line is a check, not decoration: it runs the binary you just linked and refuses a build whose version stamp never reached it. | ||
| 46 | + | ||
| 47 | +We now have an executable at `bin/turbo-python`. Remember where it is, so we can start it from anywhere: | ||
| 48 | + | ||
| 49 | +```bash | ||
| 50 | +export TURBO="$PWD/bin/turbo-python" | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +## Step 2 — Create a place to work | ||
| 54 | + | ||
| 55 | +Turbo Python is at its best inside a project, so let us make one: | ||
| 56 | + | ||
| 57 | +```bash | ||
| 58 | +cd /tmp && uv init hello && cd hello | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +You should see: | ||
| 62 | + | ||
| 63 | +``` | ||
| 64 | +Initialized project `hello` at `/tmp/hello` | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +`uv init` writes a `pyproject.toml`, a `README.md`, a `.python-version` and a `main.py` with a hello-world in it. `pyproject.toml` is what Turbo Python looks for to find the root of a project, and it is where `pylsp` will be started. We are going to replace `main.py`'s contents with our own. | ||
| 68 | + | ||
| 69 | +## Step 3 — Open the editor | ||
| 70 | + | ||
| 71 | +Start Turbo Python on the file uv made: | ||
| 72 | + | ||
| 73 | +```bash | ||
| 74 | +$TURBO main.py | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +The screen fills with a blue desktop. You should see: | ||
| 78 | + | ||
| 79 | +- a **menu bar** across the top: `File Edit Search Run Code Options Window Snippets Python Help` | ||
| 80 | +- a **window** framed in a double line, titled `main.py` | ||
| 81 | +- a **status bar** along the bottom: `F1 Describe F2 Save F3 Open …` | ||
| 82 | + | ||
| 83 | +The cursor is blinking at line 1, column 1 — the status bar says `1:1` on the right. | ||
| 84 | + | ||
| 85 | +Beside it, the status bar says one of two things. `LSP: ready` means the language server was found and started. `LSP: no pylsp — pipx install "python-lsp-server[all]"` means it was not, and names the one command that installs it. Either way the rest of this tutorial works; the [completion guide](../how-to/enable-completion.md) is where to go if you want the second to become the first. | ||
| 86 | + | ||
| 87 | +We are inside the editor. | ||
| 88 | + | ||
| 89 | +## Step 4 — Clear the file and type a Python program | ||
| 90 | + | ||
| 91 | +Press **Ctrl-A** to select everything uv wrote, then **Delete** to remove it. The window is now empty and its title reads `main.py *` — the star means there are unsaved changes. | ||
| 92 | + | ||
| 93 | +Type this line and press **Enter**: | ||
| 94 | + | ||
| 95 | +```python | ||
| 96 | +def greet(name): | ||
| 97 | +``` | ||
| 98 | + | ||
| 99 | +Watch the colours as you type. `def` turns **white and bold** the moment the word ends: it is a keyword. `greet` turns **yellow and bold** as soon as you type the `(` after it, because that makes it a function. `name` stays plain **yellow**: it is an ordinary identifier. | ||
| 100 | + | ||
| 101 | +(Those are Turbo Classic's colours, the ones the editor starts in. Step 8 changes them.) | ||
| 102 | + | ||
| 103 | +Now type four spaces yourself, and then the next line: | ||
| 104 | + | ||
| 105 | +```python | ||
| 106 | + message = f"Hello from {name}!" | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +**Enter copies the current line's indentation; it does not add a level after a colon.** Python's blocks are made of indentation, and where a new one starts is not something the editor tries to guess — so the four spaces are yours to type once, and every line after this one keeps them for free. | ||
| 110 | + | ||
| 111 | +`f"Hello from {name}!"` turns **green**, all of it, including the `{name}` in the middle. It is one string: what is inside the braces is Python, but it is not coloured as Python, because deciding where an expression ends inside a literal needs a parser and this is a scanner. That trade-off is written down in [Colouring and completion](../explanation/colouring-and-completion.md). | ||
| 112 | + | ||
| 113 | +Press **Enter** — the cursor lands under the `m`, already indented — and type: | ||
| 114 | + | ||
| 115 | +```python | ||
| 116 | + print(message) | ||
| 117 | +``` | ||
| 118 | + | ||
| 119 | +`print` turns **aqua and bold**: it is one of the builtins the language provides rather than a name from your code. | ||
| 120 | + | ||
| 121 | +Press **Enter**, then **Shift-Tab** to take the indent back off, and type the last line: | ||
| 122 | + | ||
| 123 | +```python | ||
| 124 | +greet("Turbo Python") | ||
| 125 | +``` | ||
| 126 | + | ||
| 127 | +We have just written a complete Python program, with the editor colouring it as we went. | ||
| 128 | + | ||
| 129 | +If the status bar said `LSP: ready` earlier, look at the left edge of the last line: there is a `!` in the gutter. The language server has an opinion about our file, and **Code ▸ Problems…** says what it is — `warning main.py:4 E305 expected 2 blank lines after class or function definition`. It is a style rule rather than an error, and leaving it is fine; the point is that the mark and the message are there, and they arrive without anybody asking. | ||
| 130 | + | ||
| 131 | +## Step 5 — Save it | ||
| 132 | + | ||
| 133 | +Press **F2**. | ||
| 134 | + | ||
| 135 | +The star disappears from the title, and the status bar shows, for a moment: | ||
| 136 | + | ||
| 137 | +``` | ||
| 138 | +Saved main.py | ||
| 139 | +``` | ||
| 140 | + | ||
| 141 | +It goes back to the key hints after that — the message is a confirmation, not a state. The title without its star is the state. | ||
| 142 | + | ||
| 143 | +## Step 6 — Look at the file from outside | ||
| 144 | + | ||
| 145 | +Leave the editor by pressing **Alt-X**. The terminal comes back as it was. | ||
| 146 | + | ||
| 147 | +Check what we wrote: | ||
| 148 | + | ||
| 149 | +```bash | ||
| 150 | +cat main.py | ||
| 151 | +``` | ||
| 152 | + | ||
| 153 | +You should see: | ||
| 154 | + | ||
| 155 | +```python | ||
| 156 | +def greet(name): | ||
| 157 | + message = f"Hello from {name}!" | ||
| 158 | + print(message) | ||
| 159 | +greet("Turbo Python") | ||
| 160 | +``` | ||
| 161 | + | ||
| 162 | +## Step 7 — Run it | ||
| 163 | + | ||
| 164 | +```bash | ||
| 165 | +uv run main.py | ||
| 166 | +``` | ||
| 167 | + | ||
| 168 | +The first run makes the environment, so you should see a line or two from uv before the output: | ||
| 169 | + | ||
| 170 | +``` | ||
| 171 | +Using CPython 3.14.4 interpreter at: /usr/bin/python3.14 | ||
| 172 | +Creating virtual environment at: .venv | ||
| 173 | +Hello from Turbo Python! | ||
| 174 | +``` | ||
| 175 | + | ||
| 176 | +That is a working Python program, written entirely inside the editor. | ||
| 177 | + | ||
| 178 | +## Step 8 — Change the theme | ||
| 179 | + | ||
| 180 | +Open the file again: | ||
| 181 | + | ||
| 182 | +```bash | ||
| 183 | +$TURBO main.py | ||
| 184 | +``` | ||
| 185 | + | ||
| 186 | +Press **F10**. The `File` menu drops open. Press **→** five times: the menu walks along the bar to `Options`, whose first item, `Theme…`, is highlighted. Press **Enter**. | ||
| 187 | + | ||
| 188 | +A list of eleven appears, in alphabetical order, with the theme you are using already highlighted: | ||
| 189 | + | ||
| 190 | +``` | ||
| 191 | +borland-light | ||
| 192 | +cappuccino | ||
| 193 | +catppuccin-frappe | ||
| 194 | +catppuccin-latte | ||
| 195 | +cobalt | ||
| 196 | +darcula | ||
| 197 | +intellij-light | ||
| 198 | +monochrome-dark | ||
| 199 | +monochrome-light | ||
| 200 | +turbo-classic | ||
| 201 | +turbo-dark | ||
| 202 | +``` | ||
| 203 | + | ||
| 204 | +`turbo-classic` is the highlighted row, because that is the theme you are in. Press **↓** once to move to `turbo-dark`, then press **Enter**. | ||
| 205 | + | ||
| 206 | +The whole editor repaints in dark grey, and the status bar says `Theme: Turbo Dark`. | ||
| 207 | + | ||
| 208 | +Press **Alt-X** to leave. | ||
| 209 | + | ||
| 210 | +## What now? | ||
| 211 | + | ||
| 212 | +You have built the editor, written a Python program in it, saved it, run it, and changed how it looks. | ||
| 213 | + | ||
| 214 | +- To do specific things — enable completion, write a theme of your own, search a file → see the [how-to guides](../how-to/) | ||
| 215 | +- To look up a key or a menu item → see the [reference](../reference/) | ||
| 216 | +- To understand how the colouring and the completion actually work → see the [explanation](../explanation/) | ||
added
docs/fr/README.md +61 -0 | new file mode 100644 | ||
| @@ -0,0 +1,61 @@ | ||
| 1 | +# Turbo Python — documentation | |
| 2 | + | |
| 3 | +Turbo Python est un éditeur pour Python dans le style de Turbo C : un IDE plein écran en terminal, avec menus, fenêtres déplaçables, coloration syntaxique pour neuf langages, thèmes, complétion via `pylsp`, fenêtres shell, réglages par projet, arbre du projet, snippets, et la chaîne d'outils Python à un menu de distance. | |
| 4 | + | |
| 5 | +Il est bâti sur [turbo-core](https://rickub.com/turbo-editors/turbo-core), la bibliothèque que partage chaque éditeur Turbo. Si vous voulez construire votre propre éditeur, c'est là qu'il faut regarder. | |
| 6 | + | |
| 7 | +Cette documentation suit la méthode [Diátaxis](https://diataxis.fr). Quatre types de page, quatre besoins différents — allez directement à celui qui correspond à ce que vous cherchez. | |
| 8 | + | |
| 9 | +| Je veux… | Aller à | | |
| 10 | +| --- | --- | | |
| 11 | +| **apprendre** l'éditeur en l'utilisant | [Tutoriels](tutorials/) | | |
| 12 | +| **faire** quelque chose de précis | [Guides pratiques](how-to/) | | |
| 13 | +| **consulter** un détail exact | [Référence](reference/) | | |
| 14 | +| **comprendre** comment et pourquoi ça marche | [Explications](explanation/) | | |
| 15 | + | |
| 16 | +## Tutoriels — apprendre en faisant | |
| 17 | + | |
| 18 | +- [Votre premier fichier dans Turbo Python](tutorials/getting-started.md) — compiler, ouvrir l'éditeur, écrire un programme Python, le colorer, l'enregistrer et l'exécuter. | |
| 19 | + | |
| 20 | +## Guides pratiques — des recettes pour une tâche | |
| 21 | + | |
| 22 | +- [Installer et compiler Turbo Python](how-to/install.md) | |
| 23 | +- [Lancer les tests](how-to/run-the-tests.md) | |
| 24 | +- [Activer la complétion Python](how-to/enable-completion.md) | |
| 25 | +- [Écrire son propre thème](how-to/write-a-theme.md) | |
| 26 | +- [Se déplacer dans un fichier](how-to/navigate-code.md) | |
| 27 | +- [Interroger le code](how-to/ask-about-code.md) | |
| 28 | +- [Lancer des commandes shell sans quitter l'éditeur](how-to/use-a-terminal.md) | |
| 29 | +- [Donner ses propres réglages à un projet](how-to/configure-a-project.md) | |
| 30 | +- [Parcourir un projet et ouvrir des fichiers depuis un arbre](how-to/browse-a-project.md) | |
| 31 | +- [Insérer des snippets depuis un menu](how-to/use-snippets.md) | |
| 32 | +- [Lancer les commandes uv depuis l'éditeur](how-to/run-uv-commands.md) | |
| 33 | +- [Faire une release](how-to/make-a-release.md) | |
| 34 | +- [Dialoguer avec un agent de code depuis l'éditeur](how-to/talk-to-an-agent.md) | |
| 35 | + | |
| 36 | +## Référence — les détails exacts | |
| 37 | + | |
| 38 | +- [Ligne de commande](reference/cli.md) | |
| 39 | +- [Clavier](reference/keyboard.md) | |
| 40 | +- [Menus](reference/menus.md) | |
| 41 | +- [Format des fichiers de thème](reference/themes.md) | |
| 42 | +- [Fenêtres terminal](reference/terminal.md) | |
| 43 | +- [Réglages de projet](reference/project-settings.md) | |
| 44 | +- [Arbre du projet](reference/project-tree.md) | |
| 45 | +- [Langages colorés](reference/languages.md) | |
| 46 | +- [Snippets](reference/snippets.md) | |
| 47 | +- [Outils Python](reference/python-tools.md) | |
| 48 | +- [Le numéro de version](reference/versioning.md) | |
| 49 | +- [Agents et ACP](reference/acp.md) | |
| 50 | + | |
| 51 | +## Explications — comprendre | |
| 52 | + | |
| 53 | +- [Architecture](explanation/architecture.md) | |
| 54 | +- [Décisions de conception](explanation/design-decisions.md) | |
| 55 | +- [Coloration et complétion](explanation/colouring-and-completion.md) | |
| 56 | +- [Fenêtres terminal](explanation/terminal-windows.md) | |
| 57 | +- [Réglages de projet](explanation/project-settings.md) | |
| 58 | +- [Arbre du projet](explanation/project-tree.md) | |
| 59 | +- [Snippets](explanation/snippets.md) | |
| 60 | +- [Outils Python](explanation/python-tools.md) | |
| 61 | +- [Fenêtres agent](explanation/agent-windows.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | +# Turbo Python — documentation | ||
| 2 | + | ||
| 3 | +Turbo Python est un éditeur pour Python dans le style de Turbo C : un IDE plein écran en terminal, avec menus, fenêtres déplaçables, coloration syntaxique pour neuf langages, thèmes, complétion via `pylsp`, fenêtres shell, réglages par projet, arbre du projet, snippets, et la chaîne d'outils Python à un menu de distance. | ||
| 4 | + | ||
| 5 | +Il est bâti sur [turbo-core](https://rickub.com/turbo-editors/turbo-core), la bibliothèque que partage chaque éditeur Turbo. Si vous voulez construire votre propre éditeur, c'est là qu'il faut regarder. | ||
| 6 | + | ||
| 7 | +Cette documentation suit la méthode [Diátaxis](https://diataxis.fr). Quatre types de page, quatre besoins différents — allez directement à celui qui correspond à ce que vous cherchez. | ||
| 8 | + | ||
| 9 | +| Je veux… | Aller à | | ||
| 10 | +| --- | --- | | ||
| 11 | +| **apprendre** l'éditeur en l'utilisant | [Tutoriels](tutorials/) | | ||
| 12 | +| **faire** quelque chose de précis | [Guides pratiques](how-to/) | | ||
| 13 | +| **consulter** un détail exact | [Référence](reference/) | | ||
| 14 | +| **comprendre** comment et pourquoi ça marche | [Explications](explanation/) | | ||
| 15 | + | ||
| 16 | +## Tutoriels — apprendre en faisant | ||
| 17 | + | ||
| 18 | +- [Votre premier fichier dans Turbo Python](tutorials/getting-started.md) — compiler, ouvrir l'éditeur, écrire un programme Python, le colorer, l'enregistrer et l'exécuter. | ||
| 19 | + | ||
| 20 | +## Guides pratiques — des recettes pour une tâche | ||
| 21 | + | ||
| 22 | +- [Installer et compiler Turbo Python](how-to/install.md) | ||
| 23 | +- [Lancer les tests](how-to/run-the-tests.md) | ||
| 24 | +- [Activer la complétion Python](how-to/enable-completion.md) | ||
| 25 | +- [Écrire son propre thème](how-to/write-a-theme.md) | ||
| 26 | +- [Se déplacer dans un fichier](how-to/navigate-code.md) | ||
| 27 | +- [Interroger le code](how-to/ask-about-code.md) | ||
| 28 | +- [Lancer des commandes shell sans quitter l'éditeur](how-to/use-a-terminal.md) | ||
| 29 | +- [Donner ses propres réglages à un projet](how-to/configure-a-project.md) | ||
| 30 | +- [Parcourir un projet et ouvrir des fichiers depuis un arbre](how-to/browse-a-project.md) | ||
| 31 | +- [Insérer des snippets depuis un menu](how-to/use-snippets.md) | ||
| 32 | +- [Lancer les commandes uv depuis l'éditeur](how-to/run-uv-commands.md) | ||
| 33 | +- [Faire une release](how-to/make-a-release.md) | ||
| 34 | +- [Dialoguer avec un agent de code depuis l'éditeur](how-to/talk-to-an-agent.md) | ||
| 35 | + | ||
| 36 | +## Référence — les détails exacts | ||
| 37 | + | ||
| 38 | +- [Ligne de commande](reference/cli.md) | ||
| 39 | +- [Clavier](reference/keyboard.md) | ||
| 40 | +- [Menus](reference/menus.md) | ||
| 41 | +- [Format des fichiers de thème](reference/themes.md) | ||
| 42 | +- [Fenêtres terminal](reference/terminal.md) | ||
| 43 | +- [Réglages de projet](reference/project-settings.md) | ||
| 44 | +- [Arbre du projet](reference/project-tree.md) | ||
| 45 | +- [Langages colorés](reference/languages.md) | ||
| 46 | +- [Snippets](reference/snippets.md) | ||
| 47 | +- [Outils Python](reference/python-tools.md) | ||
| 48 | +- [Le numéro de version](reference/versioning.md) | ||
| 49 | +- [Agents et ACP](reference/acp.md) | ||
| 50 | + | ||
| 51 | +## Explications — comprendre | ||
| 52 | + | ||
| 53 | +- [Architecture](explanation/architecture.md) | ||
| 54 | +- [Décisions de conception](explanation/design-decisions.md) | ||
| 55 | +- [Coloration et complétion](explanation/colouring-and-completion.md) | ||
| 56 | +- [Fenêtres terminal](explanation/terminal-windows.md) | ||
| 57 | +- [Réglages de projet](explanation/project-settings.md) | ||
| 58 | +- [Arbre du projet](explanation/project-tree.md) | ||
| 59 | +- [Snippets](explanation/snippets.md) | ||
| 60 | +- [Outils Python](explanation/python-tools.md) | ||
| 61 | +- [Fenêtres agent](explanation/agent-windows.md) | ||
added
docs/fr/explanation/agent-windows.md +114 -0 | new file mode 100644 | ||
| @@ -0,0 +1,114 @@ | ||
| 1 | +# Fenêtres agent | |
| 2 | + | |
| 3 | +Cette page explique pourquoi dialoguer avec un agent prend cette forme-là. Pour savoir comment faire, voir [Dialoguer avec un agent de code](../how-to/talk-to-an-agent.md) ; pour les touches et le format de fichier exacts, [Agents et ACP](../reference/acp.md). | |
| 4 | + | |
| 5 | +## Pourquoi un protocole plutôt qu'un fournisseur | |
| 6 | + | |
| 7 | +Un éditeur qui voulait offrir une fenêtre de conversation avait deux façons de l'obtenir. Parler directement aux fournisseurs de modèles — un client HTTP par fournisseur, un jeu de clés d'API à stocker, une boucle d'appel d'outils à écrire, et un nouvel exemplaire de chaque dès que quelqu'un veut un fournisseur dont l'éditeur n'a jamais entendu parler. Ou parler un seul protocole au programme auquel l'utilisateur fait déjà confiance pour ce travail. | |
| 8 | + | |
| 9 | +L'[Agent Client Protocol](https://agentclientprotocol.com) est la seconde. L'agent est un processus fils ; l'éditeur lui envoie des invites et dessine ce qui revient. L'éditeur ne détient aucune clé d'API, ne connaît aucun fournisseur, et n'implémente aucune boucle d'appel d'outils — et le même code parle à `docker agent` devant un llama.cpp local, à un agent dans le nuage, ou à quelque chose que vous avez écrit cet après-midi. | |
| 10 | + | |
| 11 | +Cela veut aussi dire que l'éditeur n'est pas l'endroit où atterrit un nouveau modèle. Sa prise en charge est une ligne dans le fichier de configuration de *votre* agent, un fichier que cet éditeur ne lit pas. | |
| 12 | + | |
| 13 | +## Pourquoi cela vit dans turbo-core | |
| 14 | + | |
| 15 | +Turbo Python est [une commande, un profil et un analyseur](architecture.md) ; tout le reste est la bibliothèque que partagent tous les éditeurs Turbo. Une fenêtre agent est une fenêtre, un menu, une boîte modale et un tour de boucle d'événements — quatre choses qui appartiennent toutes à `turbo-core/app`. La construire ici aurait voulu dire ajouter à la bibliothèque une couture générale « laisser un éditeur ajouter une fenêtre et un menu depuis l'extérieur », puis s'en servir exactement une fois. | |
| 16 | + | |
| 17 | +Le client du protocole, le modèle de conversation et la fenêtre sont donc `turbo-core/acp`, à côté de `terminal` et `filetree`, qui ont la même forme. Ce que Turbo Python apporte, c'est l'`acp.toml` de départ qu'il propose d'écrire — la seule part de tout ceci qui parle de projets Python. Turbo Rust et Turbo Golo obtiendront des fenêtres agent en écrivant un fichier de départ à eux, et rien d'autre. | |
| 18 | + | |
| 19 | +## Pourquoi une fenêtre, et non un panneau | |
| 20 | + | |
| 21 | +Le même raisonnement que celui tranché pour l'[arbre de projet](project-tree.md). Un panneau ancré voudrait dire que le bureau acquiert la notion de bords réservés, et que `fitInto`, les modes d'agrandissement, la maximisation, la mosaïque et la cascade doivent tous les respecter — une modification des fondations de l'interface pour un seul widget. En tant que fenêtre ordinaire, un agent obtient `F6`, les `Alt`-chiffres, `[x]`, `[■]` et Tile gratuitement. | |
| 22 | + | |
| 23 | +Cela fait aussi tomber « plusieurs agents à la fois » au lieu de le concevoir : deux fenêtres sont deux processus et deux conversations, et Tile met un modèle local rapide à côté d'un modèle lent et soigneux. Un panneau aurait dû se doter d'onglets pour en faire autant. | |
| 24 | + | |
| 25 | +## Pourquoi un processus par fenêtre, démarré à l'ouverture | |
| 26 | + | |
| 27 | +Un agent est une conversation, et une conversation a un début. Démarrer le processus avec la fenêtre fait que le dossier de travail de l'agent, son environnement et sa session appartiennent tous à cette fenêtre, et que la fermer est une fin sans ambiguïté — le même marché que passent les [fenêtres terminal](terminal-windows.md), et pour la même raison : ce que la fenêtre contient est un processus en cours, pas un travail non enregistré, donc la fermer ne demande rien. | |
| 28 | + | |
| 29 | +L'autre solution — un agent unique et durable multiplexé sur plusieurs fenêtres — aurait voulu dire que l'éditeur décide à quelle fenêtre appartient un `session/update`, et quoi faire d'une fenêtre dont la session a disparu alors que le processus vit encore. Deux processus coûtent moins cher que cette comptabilité. | |
| 30 | + | |
| 31 | +## Pourquoi la boîte de permission est ouverte depuis la boucle d'événements, et non depuis le message | |
| 32 | + | |
| 33 | +`session/request_permission` arrive sur la goroutine de lecture de la connexion, et la réponse vient d'une boîte de dialogue que l'utilisateur doit regarder. La réponse ne peut donc pas être faite là où la requête est traitée, et la boîte ne peut pas non plus y être ouverte : tout ce qui dessine appartient à la goroutine principale. | |
| 34 | + | |
| 35 | +La requête est donc *enregistrée*, et la boucle d'événements la remarque à son tour suivant et ouvre la boîte. C'est la quatrième fois que ce projet arrive à la même conclusion — l'[enregistrement automatique](project-settings.md), la ré-annonce au serveur de langage et les redessins du terminal sont les autres — et la raison est toujours la même : `PostEvent` a le droit de jeter ce qui ne rentre pas, donc un événement peut provoquer un tour de boucle mais ne doit jamais être le seul porteur d'un fait. | |
| 36 | + | |
| 37 | +C'est pourquoi la couche JSON-RPC a dû apprendre à répondre à une requête *plus tard*. C'est aussi toute la raison pour laquelle `jsonrpc` a été extrait de `lsp` : les questions d'un serveur de langage peuvent toutes être répondues sur-le-champ, et celles d'un agent non. | |
| 38 | + | |
| 39 | +## Pourquoi l'agent reçoit le tampon plutôt que le fichier | |
| 40 | + | |
| 41 | +Quand l'agent lit un fichier que vous avez ouvert et pas enregistré, il reçoit le texte que vous avez sous les yeux, pas celui du disque. L'autre solution est un agent qui relit la version que vous venez de dépasser, ce qui est faux précisément au moment où vous avez le plus de chances de poser la question — vous avez changé quelque chose et vous voulez savoir ce qu'il en est. | |
| 42 | + | |
| 43 | +Le coût est que l'agent voit un texte qu'aucun autre outil ne voit, donc une réponse citant un numéro de ligne peut ne pas correspondre à ce que dit `uv run ruff check .`. C'est accepté : c'est déjà vrai de la complétion, qui répond depuis le tampon depuis que l'éditeur sait parler à `pylsp`. | |
| 44 | + | |
| 45 | +Les écritures suivent le même chemin, dans le tampon, marqué modifié. Un agent qui modifie un fichier laisse la modification sous vos yeux, annulable avec `Ctrl-Z` et non enregistrée jusqu'à ce que vous fassiez `F2`. Un agent réécrivant discrètement un fichier sous une fenêtre que vous avez ouverte serait la pire version possible de cette fonctionnalité. | |
| 46 | + | |
| 47 | +## Pourquoi les couleurs sont les classes syntaxiques, et non de nouvelles clés de thème | |
| 48 | + | |
| 49 | +L'[arbre de projet](project-tree.md) a eu besoin de clés de thème à lui, parce qu'il aurait sinon emprunté `list.selected`, une couleur choisie sur un fond de *dialogue*, et dessiné sa ligne sélectionnée dans la couleur qui se trouve dessous. Rien de tel ici : le corps d'une fenêtre agent est `window.body`, ce sur quoi les classes syntaxiques sont déjà choisies et déjà testées pour le contraste. | |
| 50 | + | |
| 51 | +Le nom d'un interlocuteur est donc dessiné dans le style des mots-clés, une réflexion dans celui des commentaires, un appel d'outil dans celui des types, et le code selon ce qu'en dit son propre analyseur. Onze thèmes colorent correctement les fenêtres agent sans avoir été touchés, et un thème écrit par quelqu'un l'an dernier aussi. | |
| 52 | + | |
| 53 | +Ce à quoi on renonce, c'est l'expressivité : un thème ne peut pas rendre les réflexions discrètes sans rendre aussi les commentaires discrets, puisque c'est la même clé. Si cela s'avère gênant à l'usage, des clés `agent.*` pourront être ajoutées plus tard — les règles de contraste et le test de complétude en sont le prix, et il ne vaut d'être payé que si quelqu'un veut la distinction. | |
| 54 | + | |
| 55 | +## Pourquoi la transcription est un modèle que la fenêtre se contente de dessiner | |
| 56 | + | |
| 57 | +L'agent envoie des jetons : `"I"`, `" found"`, `" agent"`, `".yaml"`. Une fenêtre qui ajouterait chacun à une liste de lignes serait une fenêtre incapable de reformater, incapable de distinguer la prose d'un bloc de code délimité, et impossible à tester sans agent vivant. | |
| 58 | + | |
| 59 | +La conversation est donc une valeur — `acp.Transcript` — qui fusionne les fragments en entrées, replie chaque `tool_call_update` sur le `tool_call` dont l'identifiant correspond, et remet à la fenêtre une liste de blocs qui sont soit de la prose, soit du code dans un langage nommé. Elle ne sait rien d'un terminal, ce qui permet de la tester en appelant des fonctions et en comparant des valeurs, la règle d'organisation que suivent déjà `buffer`, `lsp` et `syntax`. | |
| 60 | + | |
| 61 | +C'est aussi ce qui rend les tests de dessin déterministes. Le projet s'est déjà fait mordre par des tests qui portaient sur un écran pendant qu'un processus vivant y écrivait, et cela a caché un vrai défaut pendant toute une session ; une fenêtre dessinée à partir d'une transcription figée ne peut courir contre rien. | |
| 62 | + | |
| 63 | +## Ce qui a été volontairement laissé de côté | |
| 64 | + | |
| 65 | +- **La reprise de session.** `session/load` existe, et s'en servir voudrait dire décider où les conversations sont stockées, combien de temps elles sont gardées, et ce qui se passe quand le projet a déménagé. C'est une fonctionnalité à part entière. | |
| 66 | +- **L'authentification.** Un agent qui a besoin d'une connexion est prié de se connecter avec sa propre CLI. Stocker un identifiant est une responsabilité que cet éditeur a jusqu'ici entièrement évitée, et une méthode de protocole n'est pas une bonne raison de commencer. | |
| 67 | +- **La capacité `terminal`.** Un agent peut déjà avoir un shell par ses propres jeux d'outils, comme le fait `docker agent`. L'annoncer voudrait dire que l'éditeur lance des commandes pour le compte de l'agent et possède la sortie — le menu des outils fait déjà cela, et mieux, pour des commandes que *vous* avez choisies. | |
| 68 | +- **Les images dans les invites.** L'éditeur a du texte et des fichiers à envoyer, et un terminal pour dessiner. | |
| 69 | + | |
| 70 | +## Voir aussi | |
| 71 | + | |
| 72 | +- [Architecture](architecture.md) — ce qui est ici et ce qui est dans la bibliothèque | |
| 73 | +- [Fenêtres terminal](terminal-windows.md) — l'autre fenêtre qui contient un processus vivant | |
| 74 | +- [Arbre de projet](project-tree.md) — là où l'argument fenêtre-et-non-panneau a été posé la première fois | |
| 75 | + | |
| 76 | +## Pourquoi la copie va dans deux presse-papiers | |
| 77 | + | |
| 78 | +« Copie ça pour que je m'en serve ailleurs » veut généralement dire *complètement ailleurs* — une autre fenêtre, un navigateur, un message à un collègue. Un presse-papiers qui ne fonctionnerait qu'à l'intérieur de cet éditeur répondrait à la plus petite moitié de la demande, et à celle qu'on avait le moins de chances de poser. | |
| 79 | + | |
| 80 | +Une copie part donc dans les deux : celui de l'éditeur, d'où `Shift-Ins` colle, et celui du système, atteint en le demandant au terminal par OSC 52. Rien ne vérifie le second, parce qu'il n'y a rien à vérifier — la séquence n'a pas de réponse, un terminal peut la refuser par sécurité, et certains demandent qu'on l'active. Un message promettant quelque chose qui n'a pas eu lieu serait pire qu'un message qui se tait : la barre d'état dit seulement combien de lignes ont été copiées, ce qui est vrai dans les deux cas. | |
| 81 | + | |
| 82 | +## Pourquoi copier sans rien sélectionner copie un bloc entier | |
| 83 | + | |
| 84 | +Ce qu'on veut extraire d'une conversation, c'est presque toujours un bloc de code. Obliger à le sélectionner d'abord — six frappes, ou un glissement qu'il faut viser — est un travail que l'éditeur a déjà de quoi faire à votre place : c'est lui qui a mis la conversation en page, donc il sait exactement où ce bloc commence et finit. | |
| 85 | + | |
| 86 | +Les lignes portent donc une **région** : un bloc de code délimité, un passage de prose, la sortie d'un appel d'outil. Sans rien de sélectionné, `Ctrl-C` copie la région sur laquelle est le curseur. Le libellé d'un interlocuteur et l'en-tête d'un appel d'outil sont du mobilier et reçoivent des régions à eux, ce qui garde `‣ Bob (llama.cpp)` hors d'un bloc collé dans un fichier source. | |
| 87 | + | |
| 88 | +Cette dernière partie n'a pas été conçue, elle a été trouvée. La première version copiait le libellé avec le code ; c'est en copiant depuis le vrai binaire et en relisant la charge utile OSC 52 sur le fil qu'on s'en est aperçu. | |
| 89 | + | |
| 90 | +## Pourquoi l'indicateur d'activité est dessiné à partir de l'horloge | |
| 91 | + | |
| 92 | +Un agent qui réfléchit vingt secondes n'envoie strictement rien, et une fenêtre qui aurait l'air figée serait indiscernable d'une fenêtre réellement bloquée. L'indicateur est la réponse la moins chère possible à « est-ce que ça marche encore ? ». | |
| 93 | + | |
| 94 | +C'est une fonction du temps — `Spinner(now)` — et non un compteur que quelque chose incrémente. Rien n'a besoin d'être remis à zéro au début d'un tour, deux fenêtres qui réfléchissent en même temps tournent en phase, et un test peut porter sur une image sans attendre qu'elle arrive — la même raison pour laquelle `editor.View` et `app.App` ont tous deux une horloge injectable. | |
| 95 | + | |
| 96 | +Dessiner à partir de l'horloge veut dire qu'autre chose doit *provoquer* le redessin : une session en cours de tour réveille donc la boucle d'événements à la cadence de l'indicateur. Cela a le droit d'être un minuteur précisément parce qu'un battement perdu ne peut rien laisser en plan : il demande un tour de boucle et ne porte jamais de fait — la règle à laquelle ce projet est maintenant arrivé cinq fois. | |
| 97 | + | |
| 98 | +Le **titre** de la fenêtre, lui, n'est délibérément pas animé. C'est aussi ce qu'affichent la liste des fenêtres et le menu `Alt`-chiffre, et un nom qui changerait huit fois par seconde les ferait scintiller sans rien apporter. | |
| 99 | + | |
| 100 | +## Pourquoi les commandes sont une liste dans la zone de saisie, et non un menu | |
| 101 | + | |
| 102 | +Les commandes d'un agent arrivent sur le fil sous forme de liste — `available_commands_update` — et peuvent changer pendant la session. Un menu construit à partir d'elles devrait être reconstruit à chaque mise à jour, se trouverait loin de l'endroit où la commande se tape, et finirait quand même par mettre `/web ` dans la zone de saisie, parce que c'est la seule chose que le protocole laisse un client envoyer : une commande est une invite texte que l'agent reconnaît à son premier mot. | |
| 103 | + | |
| 104 | +La liste s'ouvre donc là où est le texte, sur le caractère qui commence une commande, et se ferme quand le mot est complet. C'est la même forme que la fenêtre de complétion au-dessus d'un fichier, pour la même raison : ce que vous choisissez est ce que vous tapez. Utiliser `/` et `@` plutôt que des touches propres à l'éditeur est délibéré — ce sont les caractères de Zed, si bien que la documentation d'un agent est vraie ici sans table de correspondance. | |
| 105 | + | |
| 106 | +`Entrée` a deux sens sur la liste, ordonnés par le degré d'achèvement du mot : elle complète un mot inachevé, et envoie un mot achevé. L'alternative — `Entrée` complète toujours, une seconde `Entrée` envoie — coûte une frappe à chaque commande et n'apporte rien, parce qu'un mot qui se lit déjà exactement comme une commande n'a plus rien à compléter. | |
| 107 | + | |
| 108 | +## Pourquoi une mention emporte le fichier, quand elle le peut | |
| 109 | + | |
| 110 | +Le protocole offre deux façons de nommer un fichier dans une invite : un `resource_link`, qui est une URI que l'agent va chercher lui-même, et une `resource` incorporée, qui est l'URI *et le texte*. La spécification appelle la seconde « la façon préférée d'inclure du contexte », et la raison est celle qui fait répondre `fs/read_text_file` depuis le tampon : l'éditeur sait sur le fichier des choses que le disque ignore. Un agent qui suit un lien vers un fichier que vous avez modifié sans l'enregistrer lit la version que vous venez de quitter, ce qui est faux précisément au moment où vous êtes le plus susceptible de demander. | |
| 111 | + | |
| 112 | +L'éditeur envoie donc le texte quand l'agent a déclaré `promptCapabilities.embeddedContext`, lu par le même chemin que `fs/read_text_file`, et un lien sinon — jamais rien. Un fichier qui ne peut pas être lu part aussi en lien, pour que l'agent sache au moins quel fichier était visé. | |
| 113 | + | |
| 114 | +La mention remplace le nom dans le texte plutôt que de voyager à côté. Envoyer `explique @main.go` comme texte *et* comme pièce jointe donnerait à l'agent le nom deux fois en le laissant les apparier ; mettre le bloc là où était le nom lui donne le fichier là où la phrase en a besoin. La conversation, elle, garde la ligne telle que tapée : c'est ce que vous avez dit, et la fenêtre est le compte rendu de la conversation, pas du fil. | |
| new file mode 100644 | |||
| @@ -0,0 +1,114 @@ | |||
| 1 | +# Fenêtres agent | ||
| 2 | + | ||
| 3 | +Cette page explique pourquoi dialoguer avec un agent prend cette forme-là. Pour savoir comment faire, voir [Dialoguer avec un agent de code](../how-to/talk-to-an-agent.md) ; pour les touches et le format de fichier exacts, [Agents et ACP](../reference/acp.md). | ||
| 4 | + | ||
| 5 | +## Pourquoi un protocole plutôt qu'un fournisseur | ||
| 6 | + | ||
| 7 | +Un éditeur qui voulait offrir une fenêtre de conversation avait deux façons de l'obtenir. Parler directement aux fournisseurs de modèles — un client HTTP par fournisseur, un jeu de clés d'API à stocker, une boucle d'appel d'outils à écrire, et un nouvel exemplaire de chaque dès que quelqu'un veut un fournisseur dont l'éditeur n'a jamais entendu parler. Ou parler un seul protocole au programme auquel l'utilisateur fait déjà confiance pour ce travail. | ||
| 8 | + | ||
| 9 | +L'[Agent Client Protocol](https://agentclientprotocol.com) est la seconde. L'agent est un processus fils ; l'éditeur lui envoie des invites et dessine ce qui revient. L'éditeur ne détient aucune clé d'API, ne connaît aucun fournisseur, et n'implémente aucune boucle d'appel d'outils — et le même code parle à `docker agent` devant un llama.cpp local, à un agent dans le nuage, ou à quelque chose que vous avez écrit cet après-midi. | ||
| 10 | + | ||
| 11 | +Cela veut aussi dire que l'éditeur n'est pas l'endroit où atterrit un nouveau modèle. Sa prise en charge est une ligne dans le fichier de configuration de *votre* agent, un fichier que cet éditeur ne lit pas. | ||
| 12 | + | ||
| 13 | +## Pourquoi cela vit dans turbo-core | ||
| 14 | + | ||
| 15 | +Turbo Python est [une commande, un profil et un analyseur](architecture.md) ; tout le reste est la bibliothèque que partagent tous les éditeurs Turbo. Une fenêtre agent est une fenêtre, un menu, une boîte modale et un tour de boucle d'événements — quatre choses qui appartiennent toutes à `turbo-core/app`. La construire ici aurait voulu dire ajouter à la bibliothèque une couture générale « laisser un éditeur ajouter une fenêtre et un menu depuis l'extérieur », puis s'en servir exactement une fois. | ||
| 16 | + | ||
| 17 | +Le client du protocole, le modèle de conversation et la fenêtre sont donc `turbo-core/acp`, à côté de `terminal` et `filetree`, qui ont la même forme. Ce que Turbo Python apporte, c'est l'`acp.toml` de départ qu'il propose d'écrire — la seule part de tout ceci qui parle de projets Python. Turbo Rust et Turbo Golo obtiendront des fenêtres agent en écrivant un fichier de départ à eux, et rien d'autre. | ||
| 18 | + | ||
| 19 | +## Pourquoi une fenêtre, et non un panneau | ||
| 20 | + | ||
| 21 | +Le même raisonnement que celui tranché pour l'[arbre de projet](project-tree.md). Un panneau ancré voudrait dire que le bureau acquiert la notion de bords réservés, et que `fitInto`, les modes d'agrandissement, la maximisation, la mosaïque et la cascade doivent tous les respecter — une modification des fondations de l'interface pour un seul widget. En tant que fenêtre ordinaire, un agent obtient `F6`, les `Alt`-chiffres, `[x]`, `[■]` et Tile gratuitement. | ||
| 22 | + | ||
| 23 | +Cela fait aussi tomber « plusieurs agents à la fois » au lieu de le concevoir : deux fenêtres sont deux processus et deux conversations, et Tile met un modèle local rapide à côté d'un modèle lent et soigneux. Un panneau aurait dû se doter d'onglets pour en faire autant. | ||
| 24 | + | ||
| 25 | +## Pourquoi un processus par fenêtre, démarré à l'ouverture | ||
| 26 | + | ||
| 27 | +Un agent est une conversation, et une conversation a un début. Démarrer le processus avec la fenêtre fait que le dossier de travail de l'agent, son environnement et sa session appartiennent tous à cette fenêtre, et que la fermer est une fin sans ambiguïté — le même marché que passent les [fenêtres terminal](terminal-windows.md), et pour la même raison : ce que la fenêtre contient est un processus en cours, pas un travail non enregistré, donc la fermer ne demande rien. | ||
| 28 | + | ||
| 29 | +L'autre solution — un agent unique et durable multiplexé sur plusieurs fenêtres — aurait voulu dire que l'éditeur décide à quelle fenêtre appartient un `session/update`, et quoi faire d'une fenêtre dont la session a disparu alors que le processus vit encore. Deux processus coûtent moins cher que cette comptabilité. | ||
| 30 | + | ||
| 31 | +## Pourquoi la boîte de permission est ouverte depuis la boucle d'événements, et non depuis le message | ||
| 32 | + | ||
| 33 | +`session/request_permission` arrive sur la goroutine de lecture de la connexion, et la réponse vient d'une boîte de dialogue que l'utilisateur doit regarder. La réponse ne peut donc pas être faite là où la requête est traitée, et la boîte ne peut pas non plus y être ouverte : tout ce qui dessine appartient à la goroutine principale. | ||
| 34 | + | ||
| 35 | +La requête est donc *enregistrée*, et la boucle d'événements la remarque à son tour suivant et ouvre la boîte. C'est la quatrième fois que ce projet arrive à la même conclusion — l'[enregistrement automatique](project-settings.md), la ré-annonce au serveur de langage et les redessins du terminal sont les autres — et la raison est toujours la même : `PostEvent` a le droit de jeter ce qui ne rentre pas, donc un événement peut provoquer un tour de boucle mais ne doit jamais être le seul porteur d'un fait. | ||
| 36 | + | ||
| 37 | +C'est pourquoi la couche JSON-RPC a dû apprendre à répondre à une requête *plus tard*. C'est aussi toute la raison pour laquelle `jsonrpc` a été extrait de `lsp` : les questions d'un serveur de langage peuvent toutes être répondues sur-le-champ, et celles d'un agent non. | ||
| 38 | + | ||
| 39 | +## Pourquoi l'agent reçoit le tampon plutôt que le fichier | ||
| 40 | + | ||
| 41 | +Quand l'agent lit un fichier que vous avez ouvert et pas enregistré, il reçoit le texte que vous avez sous les yeux, pas celui du disque. L'autre solution est un agent qui relit la version que vous venez de dépasser, ce qui est faux précisément au moment où vous avez le plus de chances de poser la question — vous avez changé quelque chose et vous voulez savoir ce qu'il en est. | ||
| 42 | + | ||
| 43 | +Le coût est que l'agent voit un texte qu'aucun autre outil ne voit, donc une réponse citant un numéro de ligne peut ne pas correspondre à ce que dit `uv run ruff check .`. C'est accepté : c'est déjà vrai de la complétion, qui répond depuis le tampon depuis que l'éditeur sait parler à `pylsp`. | ||
| 44 | + | ||
| 45 | +Les écritures suivent le même chemin, dans le tampon, marqué modifié. Un agent qui modifie un fichier laisse la modification sous vos yeux, annulable avec `Ctrl-Z` et non enregistrée jusqu'à ce que vous fassiez `F2`. Un agent réécrivant discrètement un fichier sous une fenêtre que vous avez ouverte serait la pire version possible de cette fonctionnalité. | ||
| 46 | + | ||
| 47 | +## Pourquoi les couleurs sont les classes syntaxiques, et non de nouvelles clés de thème | ||
| 48 | + | ||
| 49 | +L'[arbre de projet](project-tree.md) a eu besoin de clés de thème à lui, parce qu'il aurait sinon emprunté `list.selected`, une couleur choisie sur un fond de *dialogue*, et dessiné sa ligne sélectionnée dans la couleur qui se trouve dessous. Rien de tel ici : le corps d'une fenêtre agent est `window.body`, ce sur quoi les classes syntaxiques sont déjà choisies et déjà testées pour le contraste. | ||
| 50 | + | ||
| 51 | +Le nom d'un interlocuteur est donc dessiné dans le style des mots-clés, une réflexion dans celui des commentaires, un appel d'outil dans celui des types, et le code selon ce qu'en dit son propre analyseur. Onze thèmes colorent correctement les fenêtres agent sans avoir été touchés, et un thème écrit par quelqu'un l'an dernier aussi. | ||
| 52 | + | ||
| 53 | +Ce à quoi on renonce, c'est l'expressivité : un thème ne peut pas rendre les réflexions discrètes sans rendre aussi les commentaires discrets, puisque c'est la même clé. Si cela s'avère gênant à l'usage, des clés `agent.*` pourront être ajoutées plus tard — les règles de contraste et le test de complétude en sont le prix, et il ne vaut d'être payé que si quelqu'un veut la distinction. | ||
| 54 | + | ||
| 55 | +## Pourquoi la transcription est un modèle que la fenêtre se contente de dessiner | ||
| 56 | + | ||
| 57 | +L'agent envoie des jetons : `"I"`, `" found"`, `" agent"`, `".yaml"`. Une fenêtre qui ajouterait chacun à une liste de lignes serait une fenêtre incapable de reformater, incapable de distinguer la prose d'un bloc de code délimité, et impossible à tester sans agent vivant. | ||
| 58 | + | ||
| 59 | +La conversation est donc une valeur — `acp.Transcript` — qui fusionne les fragments en entrées, replie chaque `tool_call_update` sur le `tool_call` dont l'identifiant correspond, et remet à la fenêtre une liste de blocs qui sont soit de la prose, soit du code dans un langage nommé. Elle ne sait rien d'un terminal, ce qui permet de la tester en appelant des fonctions et en comparant des valeurs, la règle d'organisation que suivent déjà `buffer`, `lsp` et `syntax`. | ||
| 60 | + | ||
| 61 | +C'est aussi ce qui rend les tests de dessin déterministes. Le projet s'est déjà fait mordre par des tests qui portaient sur un écran pendant qu'un processus vivant y écrivait, et cela a caché un vrai défaut pendant toute une session ; une fenêtre dessinée à partir d'une transcription figée ne peut courir contre rien. | ||
| 62 | + | ||
| 63 | +## Ce qui a été volontairement laissé de côté | ||
| 64 | + | ||
| 65 | +- **La reprise de session.** `session/load` existe, et s'en servir voudrait dire décider où les conversations sont stockées, combien de temps elles sont gardées, et ce qui se passe quand le projet a déménagé. C'est une fonctionnalité à part entière. | ||
| 66 | +- **L'authentification.** Un agent qui a besoin d'une connexion est prié de se connecter avec sa propre CLI. Stocker un identifiant est une responsabilité que cet éditeur a jusqu'ici entièrement évitée, et une méthode de protocole n'est pas une bonne raison de commencer. | ||
| 67 | +- **La capacité `terminal`.** Un agent peut déjà avoir un shell par ses propres jeux d'outils, comme le fait `docker agent`. L'annoncer voudrait dire que l'éditeur lance des commandes pour le compte de l'agent et possède la sortie — le menu des outils fait déjà cela, et mieux, pour des commandes que *vous* avez choisies. | ||
| 68 | +- **Les images dans les invites.** L'éditeur a du texte et des fichiers à envoyer, et un terminal pour dessiner. | ||
| 69 | + | ||
| 70 | +## Voir aussi | ||
| 71 | + | ||
| 72 | +- [Architecture](architecture.md) — ce qui est ici et ce qui est dans la bibliothèque | ||
| 73 | +- [Fenêtres terminal](terminal-windows.md) — l'autre fenêtre qui contient un processus vivant | ||
| 74 | +- [Arbre de projet](project-tree.md) — là où l'argument fenêtre-et-non-panneau a été posé la première fois | ||
| 75 | + | ||
| 76 | +## Pourquoi la copie va dans deux presse-papiers | ||
| 77 | + | ||
| 78 | +« Copie ça pour que je m'en serve ailleurs » veut généralement dire *complètement ailleurs* — une autre fenêtre, un navigateur, un message à un collègue. Un presse-papiers qui ne fonctionnerait qu'à l'intérieur de cet éditeur répondrait à la plus petite moitié de la demande, et à celle qu'on avait le moins de chances de poser. | ||
| 79 | + | ||
| 80 | +Une copie part donc dans les deux : celui de l'éditeur, d'où `Shift-Ins` colle, et celui du système, atteint en le demandant au terminal par OSC 52. Rien ne vérifie le second, parce qu'il n'y a rien à vérifier — la séquence n'a pas de réponse, un terminal peut la refuser par sécurité, et certains demandent qu'on l'active. Un message promettant quelque chose qui n'a pas eu lieu serait pire qu'un message qui se tait : la barre d'état dit seulement combien de lignes ont été copiées, ce qui est vrai dans les deux cas. | ||
| 81 | + | ||
| 82 | +## Pourquoi copier sans rien sélectionner copie un bloc entier | ||
| 83 | + | ||
| 84 | +Ce qu'on veut extraire d'une conversation, c'est presque toujours un bloc de code. Obliger à le sélectionner d'abord — six frappes, ou un glissement qu'il faut viser — est un travail que l'éditeur a déjà de quoi faire à votre place : c'est lui qui a mis la conversation en page, donc il sait exactement où ce bloc commence et finit. | ||
| 85 | + | ||
| 86 | +Les lignes portent donc une **région** : un bloc de code délimité, un passage de prose, la sortie d'un appel d'outil. Sans rien de sélectionné, `Ctrl-C` copie la région sur laquelle est le curseur. Le libellé d'un interlocuteur et l'en-tête d'un appel d'outil sont du mobilier et reçoivent des régions à eux, ce qui garde `‣ Bob (llama.cpp)` hors d'un bloc collé dans un fichier source. | ||
| 87 | + | ||
| 88 | +Cette dernière partie n'a pas été conçue, elle a été trouvée. La première version copiait le libellé avec le code ; c'est en copiant depuis le vrai binaire et en relisant la charge utile OSC 52 sur le fil qu'on s'en est aperçu. | ||
| 89 | + | ||
| 90 | +## Pourquoi l'indicateur d'activité est dessiné à partir de l'horloge | ||
| 91 | + | ||
| 92 | +Un agent qui réfléchit vingt secondes n'envoie strictement rien, et une fenêtre qui aurait l'air figée serait indiscernable d'une fenêtre réellement bloquée. L'indicateur est la réponse la moins chère possible à « est-ce que ça marche encore ? ». | ||
| 93 | + | ||
| 94 | +C'est une fonction du temps — `Spinner(now)` — et non un compteur que quelque chose incrémente. Rien n'a besoin d'être remis à zéro au début d'un tour, deux fenêtres qui réfléchissent en même temps tournent en phase, et un test peut porter sur une image sans attendre qu'elle arrive — la même raison pour laquelle `editor.View` et `app.App` ont tous deux une horloge injectable. | ||
| 95 | + | ||
| 96 | +Dessiner à partir de l'horloge veut dire qu'autre chose doit *provoquer* le redessin : une session en cours de tour réveille donc la boucle d'événements à la cadence de l'indicateur. Cela a le droit d'être un minuteur précisément parce qu'un battement perdu ne peut rien laisser en plan : il demande un tour de boucle et ne porte jamais de fait — la règle à laquelle ce projet est maintenant arrivé cinq fois. | ||
| 97 | + | ||
| 98 | +Le **titre** de la fenêtre, lui, n'est délibérément pas animé. C'est aussi ce qu'affichent la liste des fenêtres et le menu `Alt`-chiffre, et un nom qui changerait huit fois par seconde les ferait scintiller sans rien apporter. | ||
| 99 | + | ||
| 100 | +## Pourquoi les commandes sont une liste dans la zone de saisie, et non un menu | ||
| 101 | + | ||
| 102 | +Les commandes d'un agent arrivent sur le fil sous forme de liste — `available_commands_update` — et peuvent changer pendant la session. Un menu construit à partir d'elles devrait être reconstruit à chaque mise à jour, se trouverait loin de l'endroit où la commande se tape, et finirait quand même par mettre `/web ` dans la zone de saisie, parce que c'est la seule chose que le protocole laisse un client envoyer : une commande est une invite texte que l'agent reconnaît à son premier mot. | ||
| 103 | + | ||
| 104 | +La liste s'ouvre donc là où est le texte, sur le caractère qui commence une commande, et se ferme quand le mot est complet. C'est la même forme que la fenêtre de complétion au-dessus d'un fichier, pour la même raison : ce que vous choisissez est ce que vous tapez. Utiliser `/` et `@` plutôt que des touches propres à l'éditeur est délibéré — ce sont les caractères de Zed, si bien que la documentation d'un agent est vraie ici sans table de correspondance. | ||
| 105 | + | ||
| 106 | +`Entrée` a deux sens sur la liste, ordonnés par le degré d'achèvement du mot : elle complète un mot inachevé, et envoie un mot achevé. L'alternative — `Entrée` complète toujours, une seconde `Entrée` envoie — coûte une frappe à chaque commande et n'apporte rien, parce qu'un mot qui se lit déjà exactement comme une commande n'a plus rien à compléter. | ||
| 107 | + | ||
| 108 | +## Pourquoi une mention emporte le fichier, quand elle le peut | ||
| 109 | + | ||
| 110 | +Le protocole offre deux façons de nommer un fichier dans une invite : un `resource_link`, qui est une URI que l'agent va chercher lui-même, et une `resource` incorporée, qui est l'URI *et le texte*. La spécification appelle la seconde « la façon préférée d'inclure du contexte », et la raison est celle qui fait répondre `fs/read_text_file` depuis le tampon : l'éditeur sait sur le fichier des choses que le disque ignore. Un agent qui suit un lien vers un fichier que vous avez modifié sans l'enregistrer lit la version que vous venez de quitter, ce qui est faux précisément au moment où vous êtes le plus susceptible de demander. | ||
| 111 | + | ||
| 112 | +L'éditeur envoie donc le texte quand l'agent a déclaré `promptCapabilities.embeddedContext`, lu par le même chemin que `fs/read_text_file`, et un lien sinon — jamais rien. Un fichier qui ne peut pas être lu part aussi en lien, pour que l'agent sache au moins quel fichier était visé. | ||
| 113 | + | ||
| 114 | +La mention remplace le nom dans le texte plutôt que de voyager à côté. Envoyer `explique @main.go` comme texte *et* comme pièce jointe donnerait à l'agent le nom deux fois en le laissant les apparier ; mettre le bloc là où était le nom lui donne le fichier là où la phrase en a besoin. La conversation, elle, garde la ligne telle que tapée : c'est ce que vous avez dit, et la fenêtre est le compte rendu de la conversation, pas du fil. | ||
added
docs/fr/explanation/architecture.md +97 -0 | new file mode 100644 | ||
| @@ -0,0 +1,97 @@ | ||
| 1 | +# Architecture — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Turbo Python est une commande, un profil et un analyseur. Tout le reste — le composant d'édition, les fenêtres, les menus, les dialogues, les thèmes, l'émulateur de terminal, l'arborescence de fichiers, le client LSP — est [turbo-core](https://rickub.com/turbo-editors/turbo-core), la bibliothèque sur laquelle repose chaque éditeur Turbo. | |
| 6 | + | |
| 7 | +Cette page parle de cette coupure : ce qui est ici, ce qui est là-bas, et pourquoi la ligne tombe où elle tombe. | |
| 8 | + | |
| 9 | +## Ce qu'il y a dans ce dépôt | |
| 10 | + | |
| 11 | +``` | |
| 12 | +main.go les drapeaux, le terminal, et le câblage | |
| 13 | +internal/pythonlang la totalité de ce qui fait Turbo Python | |
| 14 | + pythonlang.go le profil : nom, menu, serveur, marqueurs de racine, où pylsp se cache | |
| 15 | + scan.go l'aiguillage de l'analyseur, les commentaires, les décorateurs | |
| 16 | + literals.go les seize orthographes d'un littéral chaîne | |
| 17 | + words.go nombres, mots-clés, primitives, les conventions de nommage | |
| 18 | + templates.go trois déclarations //go:embed | |
| 19 | + *.toml.tmpl les trois fichiers de départ qu'un projet reçoit, embarqués | |
| 20 | +``` | |
| 21 | + | |
| 22 | +Environ huit cents lignes, dont six cents pour l'analyseur. Il n'y a pas d'`internal/app`, pas d'`internal/ui`, pas d'`internal/buffer` — ceux-là existent une fois, dans la bibliothèque, et les six éditeurs s'en servent sans les modifier. | |
| 23 | + | |
| 24 | +## Ce que fait `main` | |
| 25 | + | |
| 26 | +Six choses, dans cet ordre : | |
| 27 | + | |
| 28 | +1. Analyse les drapeaux. | |
| 29 | +2. Appelle `pythonlang.Register()`, qui apprend à la bibliothèque à colorer les fichiers `.py`. | |
| 30 | +3. Construit `pythonlang.Profile()` — la valeur qui dit que cet éditeur est Turbo Python. | |
| 31 | +4. Lit `.turbo-python/settings.toml` dans le répertoire courant, s'il y en a un. | |
| 32 | +5. Ouvre le terminal et passe l'écran, le nom du thème et le profil à `app.New`. | |
| 33 | +6. Démarre pylsp à la racine du projet, et lance la boucle d'événements. | |
| 34 | + | |
| 35 | +C'est toute la commande. Chaque décision qu'elle prend — quel thème l'emporte, quels fichiers ouvrir, faut-il démarrer un serveur de langage — porte sur *cette exécution*, pas sur Python. | |
| 36 | + | |
| 37 | +## Le profil est la couture | |
| 38 | + | |
| 39 | +```go | |
| 40 | +profile.Profile{ | |
| 41 | + Name: "Turbo Python", | |
| 42 | + Slug: "turbo-python", | |
| 43 | + Language: "Python", | |
| 44 | + ToolsMenu: "~P~ython", | |
| 45 | + RootMarkers: []string{"pyproject.toml", "setup.py", "setup.cfg"}, | |
| 46 | + Server: profile.Server{Command: "pylsp", …}, | |
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | |
| 48 | +} | |
| 49 | +``` | |
| 50 | + | |
| 51 | +Tout ce qui serait sinon un `"turbo-python"`, un `"pylsp"` ou un `"pyproject.toml"` en dur quelque part dans onze mille lignes est ici un champ. La bibliothèque les lit ; rien dans la bibliothèque ne sait ce qu'ils veulent dire. | |
| 52 | + | |
| 53 | +`Slug` porte plus qu'il n'y paraît. Le binaire est `turbo-python`, le répertoire de projet est `.turbo-python`, la configuration de l'utilisateur vit dans `~/.config/turbo-python`, et les variables d'environnement qui la remplacent sont `TURBO_PYTHON_THEME_DIR` et `TURBO_PYTHON_SNIPPET_DIR` — toutes dérivées de ce seul mot. | |
| 54 | + | |
| 55 | +## Pourquoi l'analyseur est ici et pas dans la bibliothèque | |
| 56 | + | |
| 57 | +turbo-core colore huit langages lui-même : TOML, YAML, Markdown, JavaScript, HTML, XML, les Dockerfiles et le shell. Ce sont ceux que tout éditeur rencontre quel que soit son objet — la configuration d'un projet est du TOML ou du YAML, sa documentation du Markdown, ses scripts du shell, sa construction d'image un Dockerfile. | |
| 58 | + | |
| 59 | +Python n'en fait pas partie, et Go et Rust non plus. Le langage qui *définit* un éditeur est enregistré par cet éditeur, ce qui explique qu'un fichier `.rs` s'ouvre ici en texte brut et qu'un fichier `.py` s'ouvre en texte brut dans Turbo Rust. | |
| 60 | + | |
| 61 | +L'inverse était possible. Mettre les trois analyseurs dans la bibliothèque permettrait à chaque éditeur de colorer n'importe lequel des langages, sans coût en dépendances — un analyseur Python n'est que du Go ordinaire. Cela a été rejeté parce que la bibliothèque gagnerait alors un langage chaque fois que quelqu'un construit un éditeur, et parce que « qu'est-ce que cet éditeur enregistre ? » cesserait d'être la première question qu'on pose sur un nouvel éditeur. | |
| 62 | + | |
| 63 | +## Pourquoi le menu de la chaîne d'outils est `~P~ython` et non `~U~v` | |
| 64 | + | |
| 65 | +La touche rapide était la partie facile. Neuf lettres sont prises par les menus fixes — F, E, S, R, C, O, W, N et H — et `P` n'en fait pas partie : elle tombe donc sur la première lettre du mot, ce qui ne coûte à personne un second regard. Turbo Rust n'a pas eu cette chance et a fini sur `Rus~t~`. | |
| 66 | + | |
| 67 | +Le nom, lui, était la vraie décision, et elle a tourné comme celle de Turbo Rust. Le menu contient ce que le projet a mis dans son fichier d'outils, et ce n'est pas toujours uv : le premier fichier d'outils que quiconque écrit déborde de la chaîne d'outils du langage, parce que les commandes d'un projet incluent des conteneurs, des bases de données et une cible de `Makefile` que quelqu'un a ajoutée en 2019. Un menu appelé uv contenant `docker compose up` est un mensonge sur ce qu'est le menu, exactement de la façon dont la documentation de la bibliothèque met en garde. `Python` est le langage, et le langage est ce pour quoi cet éditeur existe. | |
| 68 | + | |
| 69 | +## Pourquoi les tests pilotent le vrai éditeur | |
| 70 | + | |
| 71 | +`internal/pythonlang/editor_test.go` construit un Turbo Python entier sur un terminal simulé — `app.New(screen, "turbo-classic", pythonlang.Profile())` — ouvre un fichier et vérifie la coloration, la barre de menus et les touches rapides. Il n'utilise que l'API publique de la bibliothèque. | |
| 72 | + | |
| 73 | +C'est délibéré. La suite de la bibliothèque prouve que la bibliothèque marche ; ce que ces tests prouvent, c'est que *cet éditeur est correctement assemblé* — que `Register` a été appelé, que le profil a atteint la barre de menus, qu'un fichier `.py` ressort coloré. Un bug où `main` aurait oublié d'enregistrer Python passerait tous les tests de turbo-core. | |
| 74 | + | |
| 75 | +Le même fichier pilote un **vrai pylsp** de bout en bout, quatre fois. Il écrit un projet, ouvre un fichier, démarre le serveur, puis : | |
| 76 | + | |
| 77 | +- **tape un texte qui n'existe que dans le tampon** et demande une complétion — un texte déjà présent sur le disque ne prouverait rien, puisque le serveur répond depuis le disque pour tout ce qu'on ne lui a pas dit être ouvert ; | |
| 78 | +- demande les **références** d'un nom utilisé à trois endroits, c'est-à-dire la forme de réponse qui était autrefois tronquée à un seul élément ; | |
| 79 | +- demande les **symboles du fichier**, encore une autre forme de réponse ; | |
| 80 | +- ouvre un fichier qui **ne s'analyse pas** et attend qu'un diagnostic arrive de lui-même — la seule fonction dont l'échec ressemble exactement à la réussite, puisqu'un éditeur qui n'a aucune erreur à montrer et un éditeur incapable de trouver l'erreur ont la même gouttière vide. | |
| 81 | + | |
| 82 | +Un cinquième test épingle ce que pylsp *ne peut pas* faire : il n'annonce ni `implementation` ni `workspace/symbol`, la documentation le dit, et le test échoue si un futur pylsp se met à répondre — la page est alors relue plutôt que de vieillir en silence. | |
| 83 | + | |
| 84 | +## Alternatives rejetées | |
| 85 | + | |
| 86 | +**Forker Turbo Rust.** La façon évidente d'obtenir un troisième éditeur, et la raison pour laquelle la bibliothèque existe à la place : trois copies de onze mille lignes divergent en un mois, et chaque correctif doit être fait trois fois par quelqu'un qui se souvient qu'il y en a trois. | |
| 87 | + | |
| 88 | +**Un système de greffons.** Turbo Python est un programme Go qui importe une bibliothèque. Il n'y a ni chargement dynamique ni ABI. En ajouter un voudrait dire figer l'API de tous les paquets de turbo-core plutôt que de la poignée qu'un profil touche. | |
| 89 | + | |
| 90 | +**Un fichier de configuration au lieu d'un profil.** Le profil aurait pu être du TOML lu au démarrage, ce qui ferait d'un nouvel éditeur un fichier plutôt qu'un programme. Cela rendrait aussi l'analyseur inexprimable, et un éditeur à moitié configurable — tout sauf la coloration — est pire que l'une ou l'autre réponse entière. | |
| 91 | + | |
| 92 | +## Comment cela se relie au reste | |
| 93 | + | |
| 94 | +- Ce que fait chaque paquet de la bibliothèque : [la référence des paquets de turbo-core](https://rickub.com/turbo-editors/turbo-core/blob/main/docs/fr/reference/packages.md) | |
| 95 | +- Comment marche la coloration ici : [Coloration et complétion](colouring-and-completion.md) | |
| 96 | +- Pourquoi le menu d'outils est une donnée : [Outils Python](python-tools.md) | |
| 97 | +- Les décisions qui ont survécu au refactoring : [Décisions de conception](design-decisions.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,97 @@ | |||
| 1 | +# Architecture — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Turbo Python est une commande, un profil et un analyseur. Tout le reste — le composant d'édition, les fenêtres, les menus, les dialogues, les thèmes, l'émulateur de terminal, l'arborescence de fichiers, le client LSP — est [turbo-core](https://rickub.com/turbo-editors/turbo-core), la bibliothèque sur laquelle repose chaque éditeur Turbo. | ||
| 6 | + | ||
| 7 | +Cette page parle de cette coupure : ce qui est ici, ce qui est là-bas, et pourquoi la ligne tombe où elle tombe. | ||
| 8 | + | ||
| 9 | +## Ce qu'il y a dans ce dépôt | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +main.go les drapeaux, le terminal, et le câblage | ||
| 13 | +internal/pythonlang la totalité de ce qui fait Turbo Python | ||
| 14 | + pythonlang.go le profil : nom, menu, serveur, marqueurs de racine, où pylsp se cache | ||
| 15 | + scan.go l'aiguillage de l'analyseur, les commentaires, les décorateurs | ||
| 16 | + literals.go les seize orthographes d'un littéral chaîne | ||
| 17 | + words.go nombres, mots-clés, primitives, les conventions de nommage | ||
| 18 | + templates.go trois déclarations //go:embed | ||
| 19 | + *.toml.tmpl les trois fichiers de départ qu'un projet reçoit, embarqués | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +Environ huit cents lignes, dont six cents pour l'analyseur. Il n'y a pas d'`internal/app`, pas d'`internal/ui`, pas d'`internal/buffer` — ceux-là existent une fois, dans la bibliothèque, et les six éditeurs s'en servent sans les modifier. | ||
| 23 | + | ||
| 24 | +## Ce que fait `main` | ||
| 25 | + | ||
| 26 | +Six choses, dans cet ordre : | ||
| 27 | + | ||
| 28 | +1. Analyse les drapeaux. | ||
| 29 | +2. Appelle `pythonlang.Register()`, qui apprend à la bibliothèque à colorer les fichiers `.py`. | ||
| 30 | +3. Construit `pythonlang.Profile()` — la valeur qui dit que cet éditeur est Turbo Python. | ||
| 31 | +4. Lit `.turbo-python/settings.toml` dans le répertoire courant, s'il y en a un. | ||
| 32 | +5. Ouvre le terminal et passe l'écran, le nom du thème et le profil à `app.New`. | ||
| 33 | +6. Démarre pylsp à la racine du projet, et lance la boucle d'événements. | ||
| 34 | + | ||
| 35 | +C'est toute la commande. Chaque décision qu'elle prend — quel thème l'emporte, quels fichiers ouvrir, faut-il démarrer un serveur de langage — porte sur *cette exécution*, pas sur Python. | ||
| 36 | + | ||
| 37 | +## Le profil est la couture | ||
| 38 | + | ||
| 39 | +```go | ||
| 40 | +profile.Profile{ | ||
| 41 | + Name: "Turbo Python", | ||
| 42 | + Slug: "turbo-python", | ||
| 43 | + Language: "Python", | ||
| 44 | + ToolsMenu: "~P~ython", | ||
| 45 | + RootMarkers: []string{"pyproject.toml", "setup.py", "setup.cfg"}, | ||
| 46 | + Server: profile.Server{Command: "pylsp", …}, | ||
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | ||
| 48 | +} | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +Tout ce qui serait sinon un `"turbo-python"`, un `"pylsp"` ou un `"pyproject.toml"` en dur quelque part dans onze mille lignes est ici un champ. La bibliothèque les lit ; rien dans la bibliothèque ne sait ce qu'ils veulent dire. | ||
| 52 | + | ||
| 53 | +`Slug` porte plus qu'il n'y paraît. Le binaire est `turbo-python`, le répertoire de projet est `.turbo-python`, la configuration de l'utilisateur vit dans `~/.config/turbo-python`, et les variables d'environnement qui la remplacent sont `TURBO_PYTHON_THEME_DIR` et `TURBO_PYTHON_SNIPPET_DIR` — toutes dérivées de ce seul mot. | ||
| 54 | + | ||
| 55 | +## Pourquoi l'analyseur est ici et pas dans la bibliothèque | ||
| 56 | + | ||
| 57 | +turbo-core colore huit langages lui-même : TOML, YAML, Markdown, JavaScript, HTML, XML, les Dockerfiles et le shell. Ce sont ceux que tout éditeur rencontre quel que soit son objet — la configuration d'un projet est du TOML ou du YAML, sa documentation du Markdown, ses scripts du shell, sa construction d'image un Dockerfile. | ||
| 58 | + | ||
| 59 | +Python n'en fait pas partie, et Go et Rust non plus. Le langage qui *définit* un éditeur est enregistré par cet éditeur, ce qui explique qu'un fichier `.rs` s'ouvre ici en texte brut et qu'un fichier `.py` s'ouvre en texte brut dans Turbo Rust. | ||
| 60 | + | ||
| 61 | +L'inverse était possible. Mettre les trois analyseurs dans la bibliothèque permettrait à chaque éditeur de colorer n'importe lequel des langages, sans coût en dépendances — un analyseur Python n'est que du Go ordinaire. Cela a été rejeté parce que la bibliothèque gagnerait alors un langage chaque fois que quelqu'un construit un éditeur, et parce que « qu'est-ce que cet éditeur enregistre ? » cesserait d'être la première question qu'on pose sur un nouvel éditeur. | ||
| 62 | + | ||
| 63 | +## Pourquoi le menu de la chaîne d'outils est `~P~ython` et non `~U~v` | ||
| 64 | + | ||
| 65 | +La touche rapide était la partie facile. Neuf lettres sont prises par les menus fixes — F, E, S, R, C, O, W, N et H — et `P` n'en fait pas partie : elle tombe donc sur la première lettre du mot, ce qui ne coûte à personne un second regard. Turbo Rust n'a pas eu cette chance et a fini sur `Rus~t~`. | ||
| 66 | + | ||
| 67 | +Le nom, lui, était la vraie décision, et elle a tourné comme celle de Turbo Rust. Le menu contient ce que le projet a mis dans son fichier d'outils, et ce n'est pas toujours uv : le premier fichier d'outils que quiconque écrit déborde de la chaîne d'outils du langage, parce que les commandes d'un projet incluent des conteneurs, des bases de données et une cible de `Makefile` que quelqu'un a ajoutée en 2019. Un menu appelé uv contenant `docker compose up` est un mensonge sur ce qu'est le menu, exactement de la façon dont la documentation de la bibliothèque met en garde. `Python` est le langage, et le langage est ce pour quoi cet éditeur existe. | ||
| 68 | + | ||
| 69 | +## Pourquoi les tests pilotent le vrai éditeur | ||
| 70 | + | ||
| 71 | +`internal/pythonlang/editor_test.go` construit un Turbo Python entier sur un terminal simulé — `app.New(screen, "turbo-classic", pythonlang.Profile())` — ouvre un fichier et vérifie la coloration, la barre de menus et les touches rapides. Il n'utilise que l'API publique de la bibliothèque. | ||
| 72 | + | ||
| 73 | +C'est délibéré. La suite de la bibliothèque prouve que la bibliothèque marche ; ce que ces tests prouvent, c'est que *cet éditeur est correctement assemblé* — que `Register` a été appelé, que le profil a atteint la barre de menus, qu'un fichier `.py` ressort coloré. Un bug où `main` aurait oublié d'enregistrer Python passerait tous les tests de turbo-core. | ||
| 74 | + | ||
| 75 | +Le même fichier pilote un **vrai pylsp** de bout en bout, quatre fois. Il écrit un projet, ouvre un fichier, démarre le serveur, puis : | ||
| 76 | + | ||
| 77 | +- **tape un texte qui n'existe que dans le tampon** et demande une complétion — un texte déjà présent sur le disque ne prouverait rien, puisque le serveur répond depuis le disque pour tout ce qu'on ne lui a pas dit être ouvert ; | ||
| 78 | +- demande les **références** d'un nom utilisé à trois endroits, c'est-à-dire la forme de réponse qui était autrefois tronquée à un seul élément ; | ||
| 79 | +- demande les **symboles du fichier**, encore une autre forme de réponse ; | ||
| 80 | +- ouvre un fichier qui **ne s'analyse pas** et attend qu'un diagnostic arrive de lui-même — la seule fonction dont l'échec ressemble exactement à la réussite, puisqu'un éditeur qui n'a aucune erreur à montrer et un éditeur incapable de trouver l'erreur ont la même gouttière vide. | ||
| 81 | + | ||
| 82 | +Un cinquième test épingle ce que pylsp *ne peut pas* faire : il n'annonce ni `implementation` ni `workspace/symbol`, la documentation le dit, et le test échoue si un futur pylsp se met à répondre — la page est alors relue plutôt que de vieillir en silence. | ||
| 83 | + | ||
| 84 | +## Alternatives rejetées | ||
| 85 | + | ||
| 86 | +**Forker Turbo Rust.** La façon évidente d'obtenir un troisième éditeur, et la raison pour laquelle la bibliothèque existe à la place : trois copies de onze mille lignes divergent en un mois, et chaque correctif doit être fait trois fois par quelqu'un qui se souvient qu'il y en a trois. | ||
| 87 | + | ||
| 88 | +**Un système de greffons.** Turbo Python est un programme Go qui importe une bibliothèque. Il n'y a ni chargement dynamique ni ABI. En ajouter un voudrait dire figer l'API de tous les paquets de turbo-core plutôt que de la poignée qu'un profil touche. | ||
| 89 | + | ||
| 90 | +**Un fichier de configuration au lieu d'un profil.** Le profil aurait pu être du TOML lu au démarrage, ce qui ferait d'un nouvel éditeur un fichier plutôt qu'un programme. Cela rendrait aussi l'analyseur inexprimable, et un éditeur à moitié configurable — tout sauf la coloration — est pire que l'une ou l'autre réponse entière. | ||
| 91 | + | ||
| 92 | +## Comment cela se relie au reste | ||
| 93 | + | ||
| 94 | +- Ce que fait chaque paquet de la bibliothèque : [la référence des paquets de turbo-core](https://rickub.com/turbo-editors/turbo-core/blob/main/docs/fr/reference/packages.md) | ||
| 95 | +- Comment marche la coloration ici : [Coloration et complétion](colouring-and-completion.md) | ||
| 96 | +- Pourquoi le menu d'outils est une donnée : [Outils Python](python-tools.md) | ||
| 97 | +- Les décisions qui ont survécu au refactoring : [Décisions de conception](design-decisions.md) | ||
added
docs/fr/explanation/colouring-and-completion.md +103 -0 | new file mode 100644 | ||
| @@ -0,0 +1,103 @@ | ||
| 1 | +# Coloration et complétion — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Les deux fonctions qui font de Turbo Python un éditeur *pour Python* plutôt qu'un éditeur de texte qui ouvre des fichiers `.py` : la coloration syntaxique, et la complétion venue d'un serveur de langage. Elles fonctionnent très différemment, et la différence est instructive. | |
| 6 | + | |
| 7 | +## La coloration est à nous ; la complétion ne l'est pas | |
| 8 | + | |
| 9 | +La coloration se fait ici, en quelque six cents lignes de Go écrites à la main. La complétion est faite par python-lsp-server, et Turbo Python se contente de demander et de dessiner. | |
| 10 | + | |
| 11 | +Ce partage n'est pas un accident d'effort. La coloration doit être **instantanée et tolérante** : elle tourne à chaque frappe, sur du texte invalide la plupart du temps qu'on l'écrit, et un coloriseur qui s'arrête pour réfléchir ou qui abandonne devant du code cassé est pire que pas de coloriseur du tout. La complétion doit être **juste**, ce qui pour Python veut dire suivre les imports, résoudre un nom à travers la hiérarchie de classes où il a été affecté, et lire la surface publique de chaque paquet installé — et rien de ce qui doit être instantané ne peut être cela aussi. | |
| 12 | + | |
| 13 | +L'éditeur dessine donc des couleurs qu'il a calculées lui-même, et montre des complétions calculées par quelqu'un d'autre. | |
| 14 | + | |
| 15 | +## Pourquoi Python est analysé à la main | |
| 16 | + | |
| 17 | +Go a un analyseur lexical dans sa bibliothèque standard, et Turbo Go s'en sert : `go/scanner` est le code qu'utilise le compilateur, si bien que l'éditeur et le compilateur s'accordent sur ce qu'est un lexème, sans rien à tenir en phase. | |
| 18 | + | |
| 19 | +Python n'a rien de tel de disponible ici. Le tokeniseur de CPython est en C, `tokenize` est un module Python, et l'analyseur de jedi est un paquet Python. Le choix était donc : un scanner écrit à la main, ou lancer un processus Python à chaque frappe. | |
| 20 | + | |
| 21 | +Ce sera le scanner. Quelque six cents lignes, un fichier chacun pour le répartiteur, les littéraux et les mots — et aucune tentative de moteur général. Pas de langage de motifs, pas de format de grammaire, pas de table d'expressions régulières : c'est du Go ordinaire qu'un lecteur peut suivre, la règle même que suivent les huit scanners de turbo-core. | |
| 22 | + | |
| 23 | +## La seule chose qui franchit un saut de ligne | |
| 24 | + | |
| 25 | +Presque tout, en Python, se décide sur la ligne qu'on a sous les yeux. **Une chaîne est la seule exception**, et elle l'est de deux manières différentes — c'est pourquoi ce qui est reporté est une petite structure et non un drapeau. | |
| 26 | + | |
| 27 | +**Une chaîne à triple guillemet court jusqu'à ses trois guillemets fermants**, si loin soient-ils. Toute docstring en est une : ce n'est pas un cas limite, c'est l'essentiel de ce qu'un fichier Python contient qui ne soit pas du code. | |
| 28 | + | |
| 29 | +**Une chaîne à guillemet simple ne continue que si la ligne se termine par une contre-oblique**, qui échappe le saut de ligne. C'est une construction réelle, quoique rare — et c'est la raison pour laquelle une chaîne à guillemet simple qui *manque* simplement de ligne est abandonnée là. Le code sous le curseur est déséquilibré la plupart du temps qu'on l'écrit, et un `"` non fermé reporté peindrait tout le reste du fichier en vert. | |
| 30 | + | |
| 31 | +**Le guillemet qui l'a ouverte est reporté aussi.** Un littéral ouvert par trois guillemets doubles et un littéral ouvert par trois apostrophes sont deux chaînes différentes, et le terminateur de l'une, apparaissant dans l'autre, ne ferme rien. Une docstring qui cite quoi que ce soit — `"""dire "bonjour" ici"""` — est le cas qui piège un scanner ne reportant qu'« une chaîne est ouverte ». | |
| 32 | + | |
| 33 | +**Le caractère « brut » n'est délibérément pas reporté.** `r"\""` est une chaîne complète : dans une chaîne brute la contre-oblique reste dans la valeur, mais elle empêche toujours le guillemet suivant de terminer le littéral. La règle de terminaison est donc la même pour les chaînes brutes et ordinaires, et un drapeau prétendant le contraire serait un drapeau que rien ne lit. | |
| 34 | + | |
| 35 | +## Là où le scanner s'appuie sur les conventions | |
| 36 | + | |
| 37 | +La syntaxe de Python laisse ouvertes trois questions auxquelles ses *conventions* répondent, et le scanner lit les conventions plutôt que de faire comme si les questions n'existaient pas. | |
| 38 | + | |
| 39 | +**Une classe s'appelle exactement comme une fonction.** `ValueError("non")` et `parse("non")` ont la même forme ; une parenthèse ne peut pas distinguer un constructeur d'un appel. La PEP 8, si : une classe s'écrit en `CapWords` et rien d'autre ne s'écrit ainsi. Un nom capitalisé est donc un type, qu'une parenthèse suive ou non — c'est la seule règle que Turbo Python et Turbo Rust ordonnent délibérément différemment, parce qu'en Rust un nom capitalisé devant une parenthèse est le plus souvent une variante que le langage lui-même nomme. | |
| 40 | + | |
| 41 | +**Une constante ne ressemble en rien à une classe.** `MAX_SIZE` et `Measurement` sont toutes deux « capitalisées », et la PEP 8 les sépare nettement : une constante de module s'écrit en `SCREAMING_SNAKE_CASE`. Turbo Rust n'a que la règle de la majuscule et documente les constantes en majuscules colorées en types comme une réponse fausse connue. Les conventions de Python sont assez séparées pour que cette réponse mérite d'être supprimée plutôt qu'héritée : ici, un nom écrit entièrement en majuscules est une constante. Ce que cela coûte, c'est une classe nommée `HTTP`, assez rare pour être écrite noir sur blanc. | |
| 42 | + | |
| 43 | +**`self` n'appartient pas au langage, et tout lecteur le traite comme s'il lui appartenait.** Une méthode peut nommer son premier paramètre comme elle veut ; le compilateur s'en moque. Mais un lecteur de Python lit `self` comme un lecteur de Rust lit `Some` — comme une chose que le langage fournit — et tous les autres coloriseurs sont d'accord. Il est coloré en primitive pour cette raison, et le coût honnête est une fonction ordinaire qui nomme un paramètre `self`. | |
| 44 | + | |
| 45 | +## La seule vraie ambiguïté | |
| 46 | + | |
| 47 | +`match` et `case` ont été ajoutés à Python sans être réservés. `match x:` ouvre une instruction `match` ; `match = re.match(motif, texte)` affecte une variable, et les deux sont du Python ordinaire et courant. | |
| 48 | + | |
| 49 | +Rien dans le mot ne tranche, c'est donc la *forme de l'instruction* qui le fait : le mot ouvre la ligne, et la ligne se termine par le deux-points qui ouvre son bloc. Les deux conditions doivent tenir, ce qui attrape toutes les instructions `match` que l'on écrit et laisse `match` être un nom partout ailleurs. | |
| 50 | + | |
| 51 | +Cette règle a une frontière, et la frontière est documentée plutôt que supprimée. Le deux-points est cherché en remontant depuis la fin de la ligne — c'est ce qui rend la question assez bon marché pour être posée de chaque mot — et un commentaire de fin le masque : `match value: # aiguillage` colore donc `match` comme un nom. Distinguer un vrai commentaire de fin d'un `#` à l'intérieur d'une chaîne suppose de parcourir la ligne à l'endroit, c'est-à-dire exactement le travail que la lecture à rebours existe pour éviter. C'est aussi le bon sens de l'erreur : un mot-clé montré comme un nom est une nuance trop terne, tandis qu'un nom montré comme un mot-clé est un mensonge. | |
| 52 | + | |
| 53 | +## Ce que le scanner refuse de deviner | |
| 54 | + | |
| 55 | +Là où une construction ne peut pas être reconnue à partir de ce que contient une ligne, elle est laissée tranquille plutôt qu'approximée. Un coloriseur qui se trompe est pire qu'un coloriseur qui se tait : | |
| 56 | + | |
| 57 | +| Non reconnu | Parce que | | |
| 58 | +| --- | --- | | |
| 59 | +| L'`{expression}` à l'intérieur d'une f-string | Depuis Python 3.12 elle peut contenir absolument n'importe quoi — des guillemets imbriqués du même type, des commentaires, une autre f-string. La colorer correctement suppose de faire tourner le scanner entier à l'intérieur de lui-même ; la colorer à moitié termine `f"{n:{width}}"` sur l'accolade intérieure. Une seule plage de chaîne est la réponse honnête | | |
| 60 | +| Une docstring comme autre chose qu'une chaîne | C'en *est* une — `help()` la relit comme telle — et dès que quelqu'un en affecte une à un nom, un scanner qui l'appelait un commentaire a visiblement tort | | |
| 61 | +| Si un nom est lié dans cette portée | Rien ici ne lit plus d'une ligne à la fois. C'est la question du serveur de langage | | |
| 62 | + | |
| 63 | +## Les huit autres langages viennent gratuitement | |
| 64 | + | |
| 65 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfile et shell sont colorés par turbo-core, pas ici. Un projet Python a un `pyproject.toml`, un `README.md`, quelques scripts, un workflow CI en YAML et souvent un Dockerfile, et un éditeur qui ne colorerait que les fichiers `.py` obligerait à le quitter pour tout le reste. | |
| 66 | + | |
| 67 | +Qu'ils soient partagés plutôt que copiés est tout l'intérêt de la bibliothèque : ils ont été écrits une fois, pour Turbo Go, et Turbo Python les a obtenus en important un paquet. | |
| 68 | + | |
| 69 | +## La complétion, et pourquoi elle peut échouer en silence | |
| 70 | + | |
| 71 | +Turbo Python ne sait rien du système de types de Python et n'essaie pas d'en savoir. Il interroge pylsp par le Language Server Protocol et dessine la réponse. | |
| 72 | + | |
| 73 | +Trois choses méritent d'être connues, car toutes trois ressemblent à « la complétion est cassée » : | |
| 74 | + | |
| 75 | +**pylsp ne répond rien tant qu'il n'a pas indexé assez du projet.** jedi résout un nom en suivant les imports vers l'extérieur, ce qui, à la première demande touchant une grosse dépendance, veut dire lire beaucoup du code de quelqu'un d'autre. Ce que l'on voit en attendant, c'est une liste vide. | |
| 76 | + | |
| 77 | +**Un serveur lancé à la mauvaise racine charge le mauvais code, puis ne répond plus rien du tout — sans erreur.** C'est pourquoi l'éditeur remonte depuis le fichier jusqu'au `pyproject.toml`, `setup.py` ou `setup.cfg` le plus proche plutôt que d'utiliser le répertoire courant, et c'est la façon la plus déroutante dont la complétion peut échouer. | |
| 78 | + | |
| 79 | +**Un serveur installé sans ses extras répond aux questions mais ne signale jamais un problème de lui-même.** Les linters de pylsp sont des dépendances optionnelles ; installé nu, il complète et saute parfaitement bien, et publie une liste *vide* de diagnostics pour un fichier qui ne s'analyse même pas. Une gouttière vide parce que le serveur n'a pas de linter et une gouttière vide parce que le code est correct sont indiscernables. C'est pourquoi [la commande d'installation nomme les extras](../how-to/enable-completion.md) et pourquoi l'installateur les vérifie. | |
| 80 | + | |
| 81 | +La réponse de l'éditeur aux deux premières est [Run ▸ Language server status](../reference/menus.md), qui dit ce qu'il a trouvé, où il l'a lancé et s'il est prêt — parce que « rien ne s'est passé » n'est pas quelque chose sur quoi un utilisateur peut agir. | |
| 82 | + | |
| 83 | +## Neuf questions, une connexion — et les deux auxquelles pylsp ne répond pas | |
| 84 | + | |
| 85 | +La complétion est ce que le serveur de langage fait de plus bruyant et de moins révélateur. La même connexion pose huit questions de plus, et elles se répartissent en trois familles selon la forme de la réponse. | |
| 86 | + | |
| 87 | +**Quelque chose à lire.** `hover` — qu'est-ce que c'est ? — dessiné dans une boîte. | |
| 88 | + | |
| 89 | +**Des endroits dans le code.** `definition`, `typeDefinition`, `implementation`, `references`. Une requête chacun, une seule forme de réponse pour les quatre, ce qui explique qu'ils soient une seule fonction en dessous. Un seul endroit est ouvert ; plusieurs sont proposés en liste, parce qu'une réponse unique est l'exception plutôt que la règle — une méthode utilisée dans tout un paquet a autant de références que quelqu'un a pris la peine d'en écrire, et pendant longtemps cet éditeur prenait la première et jetait le reste. | |
| 90 | + | |
| 91 | +**Des noms.** `documentSymbol` pour le plan d'un fichier, `workspace/symbol` pour une recherche à travers le projet. Le protocole a trois formes pour un symbole et l'éditeur en veut une, si bien que l'aplatissement se fait là où les réponses arrivent plutôt que là où elles sont dessinées. | |
| 92 | + | |
| 93 | +Et une chose que personne ne demande : **`publishDiagnostics` arrive sans y être invité**, dès que le serveur a un avis, pour tous les fichiers qu'il a chargés — qui sont d'ordinaire plus nombreux que celui qu'on a sous les yeux. C'est pourquoi Problems liste tous les fichiers plutôt que le fichier courant, et pourquoi la marque dans la gouttière apparaît sans qu'on ait appuyé sur quoi que ce soit. | |
| 94 | + | |
| 95 | +**Deux des neuf reviennent vides avec pylsp, et c'est la frontière du serveur, pas celle de l'éditeur.** pylsp n'annonce ni `implementation` ni `workspace/symbol` : **Code ▸ Find implementations** et **Code ▸ Symbol in project** signalent donc n'avoir rien trouvé. Tout le reste fonctionne. C'est écrit ici plutôt que caché parce que l'alternative — griser deux entrées de menu selon ce qu'un serveur a annoncé au démarrage — donnerait au menu une forme différente d'une machine à l'autre, et un utilisateur qui a lu cette page en sait plus qu'un utilisateur tombé sur une entrée grisée. | |
| 96 | + | |
| 97 | +L'éditeur ne demande rien de tout cela avant que le serveur se soit dit prêt, et il dit de laquelle il s'agit quand une question ne peut pas trouver de réponse. « Rien trouvé » et « je n'ai pas fini de charger » sont la même réponse vide et deux nouvelles très différentes ; les confondre est la façon la plus déroutante dont la complétion ait jamais échoué ici. | |
| 98 | + | |
| 99 | +## Rapport avec le reste | |
| 100 | + | |
| 101 | +- Ce qui est reconnu exactement : [Langages colorés](../reference/languages.md) | |
| 102 | +- Faire marcher la complétion : [Comment activer la complétion Python](../how-to/enable-completion.md) | |
| 103 | +- Où vit le scanner et pourquoi : [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | +# Coloration et complétion — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Les deux fonctions qui font de Turbo Python un éditeur *pour Python* plutôt qu'un éditeur de texte qui ouvre des fichiers `.py` : la coloration syntaxique, et la complétion venue d'un serveur de langage. Elles fonctionnent très différemment, et la différence est instructive. | ||
| 6 | + | ||
| 7 | +## La coloration est à nous ; la complétion ne l'est pas | ||
| 8 | + | ||
| 9 | +La coloration se fait ici, en quelque six cents lignes de Go écrites à la main. La complétion est faite par python-lsp-server, et Turbo Python se contente de demander et de dessiner. | ||
| 10 | + | ||
| 11 | +Ce partage n'est pas un accident d'effort. La coloration doit être **instantanée et tolérante** : elle tourne à chaque frappe, sur du texte invalide la plupart du temps qu'on l'écrit, et un coloriseur qui s'arrête pour réfléchir ou qui abandonne devant du code cassé est pire que pas de coloriseur du tout. La complétion doit être **juste**, ce qui pour Python veut dire suivre les imports, résoudre un nom à travers la hiérarchie de classes où il a été affecté, et lire la surface publique de chaque paquet installé — et rien de ce qui doit être instantané ne peut être cela aussi. | ||
| 12 | + | ||
| 13 | +L'éditeur dessine donc des couleurs qu'il a calculées lui-même, et montre des complétions calculées par quelqu'un d'autre. | ||
| 14 | + | ||
| 15 | +## Pourquoi Python est analysé à la main | ||
| 16 | + | ||
| 17 | +Go a un analyseur lexical dans sa bibliothèque standard, et Turbo Go s'en sert : `go/scanner` est le code qu'utilise le compilateur, si bien que l'éditeur et le compilateur s'accordent sur ce qu'est un lexème, sans rien à tenir en phase. | ||
| 18 | + | ||
| 19 | +Python n'a rien de tel de disponible ici. Le tokeniseur de CPython est en C, `tokenize` est un module Python, et l'analyseur de jedi est un paquet Python. Le choix était donc : un scanner écrit à la main, ou lancer un processus Python à chaque frappe. | ||
| 20 | + | ||
| 21 | +Ce sera le scanner. Quelque six cents lignes, un fichier chacun pour le répartiteur, les littéraux et les mots — et aucune tentative de moteur général. Pas de langage de motifs, pas de format de grammaire, pas de table d'expressions régulières : c'est du Go ordinaire qu'un lecteur peut suivre, la règle même que suivent les huit scanners de turbo-core. | ||
| 22 | + | ||
| 23 | +## La seule chose qui franchit un saut de ligne | ||
| 24 | + | ||
| 25 | +Presque tout, en Python, se décide sur la ligne qu'on a sous les yeux. **Une chaîne est la seule exception**, et elle l'est de deux manières différentes — c'est pourquoi ce qui est reporté est une petite structure et non un drapeau. | ||
| 26 | + | ||
| 27 | +**Une chaîne à triple guillemet court jusqu'à ses trois guillemets fermants**, si loin soient-ils. Toute docstring en est une : ce n'est pas un cas limite, c'est l'essentiel de ce qu'un fichier Python contient qui ne soit pas du code. | ||
| 28 | + | ||
| 29 | +**Une chaîne à guillemet simple ne continue que si la ligne se termine par une contre-oblique**, qui échappe le saut de ligne. C'est une construction réelle, quoique rare — et c'est la raison pour laquelle une chaîne à guillemet simple qui *manque* simplement de ligne est abandonnée là. Le code sous le curseur est déséquilibré la plupart du temps qu'on l'écrit, et un `"` non fermé reporté peindrait tout le reste du fichier en vert. | ||
| 30 | + | ||
| 31 | +**Le guillemet qui l'a ouverte est reporté aussi.** Un littéral ouvert par trois guillemets doubles et un littéral ouvert par trois apostrophes sont deux chaînes différentes, et le terminateur de l'une, apparaissant dans l'autre, ne ferme rien. Une docstring qui cite quoi que ce soit — `"""dire "bonjour" ici"""` — est le cas qui piège un scanner ne reportant qu'« une chaîne est ouverte ». | ||
| 32 | + | ||
| 33 | +**Le caractère « brut » n'est délibérément pas reporté.** `r"\""` est une chaîne complète : dans une chaîne brute la contre-oblique reste dans la valeur, mais elle empêche toujours le guillemet suivant de terminer le littéral. La règle de terminaison est donc la même pour les chaînes brutes et ordinaires, et un drapeau prétendant le contraire serait un drapeau que rien ne lit. | ||
| 34 | + | ||
| 35 | +## Là où le scanner s'appuie sur les conventions | ||
| 36 | + | ||
| 37 | +La syntaxe de Python laisse ouvertes trois questions auxquelles ses *conventions* répondent, et le scanner lit les conventions plutôt que de faire comme si les questions n'existaient pas. | ||
| 38 | + | ||
| 39 | +**Une classe s'appelle exactement comme une fonction.** `ValueError("non")` et `parse("non")` ont la même forme ; une parenthèse ne peut pas distinguer un constructeur d'un appel. La PEP 8, si : une classe s'écrit en `CapWords` et rien d'autre ne s'écrit ainsi. Un nom capitalisé est donc un type, qu'une parenthèse suive ou non — c'est la seule règle que Turbo Python et Turbo Rust ordonnent délibérément différemment, parce qu'en Rust un nom capitalisé devant une parenthèse est le plus souvent une variante que le langage lui-même nomme. | ||
| 40 | + | ||
| 41 | +**Une constante ne ressemble en rien à une classe.** `MAX_SIZE` et `Measurement` sont toutes deux « capitalisées », et la PEP 8 les sépare nettement : une constante de module s'écrit en `SCREAMING_SNAKE_CASE`. Turbo Rust n'a que la règle de la majuscule et documente les constantes en majuscules colorées en types comme une réponse fausse connue. Les conventions de Python sont assez séparées pour que cette réponse mérite d'être supprimée plutôt qu'héritée : ici, un nom écrit entièrement en majuscules est une constante. Ce que cela coûte, c'est une classe nommée `HTTP`, assez rare pour être écrite noir sur blanc. | ||
| 42 | + | ||
| 43 | +**`self` n'appartient pas au langage, et tout lecteur le traite comme s'il lui appartenait.** Une méthode peut nommer son premier paramètre comme elle veut ; le compilateur s'en moque. Mais un lecteur de Python lit `self` comme un lecteur de Rust lit `Some` — comme une chose que le langage fournit — et tous les autres coloriseurs sont d'accord. Il est coloré en primitive pour cette raison, et le coût honnête est une fonction ordinaire qui nomme un paramètre `self`. | ||
| 44 | + | ||
| 45 | +## La seule vraie ambiguïté | ||
| 46 | + | ||
| 47 | +`match` et `case` ont été ajoutés à Python sans être réservés. `match x:` ouvre une instruction `match` ; `match = re.match(motif, texte)` affecte une variable, et les deux sont du Python ordinaire et courant. | ||
| 48 | + | ||
| 49 | +Rien dans le mot ne tranche, c'est donc la *forme de l'instruction* qui le fait : le mot ouvre la ligne, et la ligne se termine par le deux-points qui ouvre son bloc. Les deux conditions doivent tenir, ce qui attrape toutes les instructions `match` que l'on écrit et laisse `match` être un nom partout ailleurs. | ||
| 50 | + | ||
| 51 | +Cette règle a une frontière, et la frontière est documentée plutôt que supprimée. Le deux-points est cherché en remontant depuis la fin de la ligne — c'est ce qui rend la question assez bon marché pour être posée de chaque mot — et un commentaire de fin le masque : `match value: # aiguillage` colore donc `match` comme un nom. Distinguer un vrai commentaire de fin d'un `#` à l'intérieur d'une chaîne suppose de parcourir la ligne à l'endroit, c'est-à-dire exactement le travail que la lecture à rebours existe pour éviter. C'est aussi le bon sens de l'erreur : un mot-clé montré comme un nom est une nuance trop terne, tandis qu'un nom montré comme un mot-clé est un mensonge. | ||
| 52 | + | ||
| 53 | +## Ce que le scanner refuse de deviner | ||
| 54 | + | ||
| 55 | +Là où une construction ne peut pas être reconnue à partir de ce que contient une ligne, elle est laissée tranquille plutôt qu'approximée. Un coloriseur qui se trompe est pire qu'un coloriseur qui se tait : | ||
| 56 | + | ||
| 57 | +| Non reconnu | Parce que | | ||
| 58 | +| --- | --- | | ||
| 59 | +| L'`{expression}` à l'intérieur d'une f-string | Depuis Python 3.12 elle peut contenir absolument n'importe quoi — des guillemets imbriqués du même type, des commentaires, une autre f-string. La colorer correctement suppose de faire tourner le scanner entier à l'intérieur de lui-même ; la colorer à moitié termine `f"{n:{width}}"` sur l'accolade intérieure. Une seule plage de chaîne est la réponse honnête | | ||
| 60 | +| Une docstring comme autre chose qu'une chaîne | C'en *est* une — `help()` la relit comme telle — et dès que quelqu'un en affecte une à un nom, un scanner qui l'appelait un commentaire a visiblement tort | | ||
| 61 | +| Si un nom est lié dans cette portée | Rien ici ne lit plus d'une ligne à la fois. C'est la question du serveur de langage | | ||
| 62 | + | ||
| 63 | +## Les huit autres langages viennent gratuitement | ||
| 64 | + | ||
| 65 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfile et shell sont colorés par turbo-core, pas ici. Un projet Python a un `pyproject.toml`, un `README.md`, quelques scripts, un workflow CI en YAML et souvent un Dockerfile, et un éditeur qui ne colorerait que les fichiers `.py` obligerait à le quitter pour tout le reste. | ||
| 66 | + | ||
| 67 | +Qu'ils soient partagés plutôt que copiés est tout l'intérêt de la bibliothèque : ils ont été écrits une fois, pour Turbo Go, et Turbo Python les a obtenus en important un paquet. | ||
| 68 | + | ||
| 69 | +## La complétion, et pourquoi elle peut échouer en silence | ||
| 70 | + | ||
| 71 | +Turbo Python ne sait rien du système de types de Python et n'essaie pas d'en savoir. Il interroge pylsp par le Language Server Protocol et dessine la réponse. | ||
| 72 | + | ||
| 73 | +Trois choses méritent d'être connues, car toutes trois ressemblent à « la complétion est cassée » : | ||
| 74 | + | ||
| 75 | +**pylsp ne répond rien tant qu'il n'a pas indexé assez du projet.** jedi résout un nom en suivant les imports vers l'extérieur, ce qui, à la première demande touchant une grosse dépendance, veut dire lire beaucoup du code de quelqu'un d'autre. Ce que l'on voit en attendant, c'est une liste vide. | ||
| 76 | + | ||
| 77 | +**Un serveur lancé à la mauvaise racine charge le mauvais code, puis ne répond plus rien du tout — sans erreur.** C'est pourquoi l'éditeur remonte depuis le fichier jusqu'au `pyproject.toml`, `setup.py` ou `setup.cfg` le plus proche plutôt que d'utiliser le répertoire courant, et c'est la façon la plus déroutante dont la complétion peut échouer. | ||
| 78 | + | ||
| 79 | +**Un serveur installé sans ses extras répond aux questions mais ne signale jamais un problème de lui-même.** Les linters de pylsp sont des dépendances optionnelles ; installé nu, il complète et saute parfaitement bien, et publie une liste *vide* de diagnostics pour un fichier qui ne s'analyse même pas. Une gouttière vide parce que le serveur n'a pas de linter et une gouttière vide parce que le code est correct sont indiscernables. C'est pourquoi [la commande d'installation nomme les extras](../how-to/enable-completion.md) et pourquoi l'installateur les vérifie. | ||
| 80 | + | ||
| 81 | +La réponse de l'éditeur aux deux premières est [Run ▸ Language server status](../reference/menus.md), qui dit ce qu'il a trouvé, où il l'a lancé et s'il est prêt — parce que « rien ne s'est passé » n'est pas quelque chose sur quoi un utilisateur peut agir. | ||
| 82 | + | ||
| 83 | +## Neuf questions, une connexion — et les deux auxquelles pylsp ne répond pas | ||
| 84 | + | ||
| 85 | +La complétion est ce que le serveur de langage fait de plus bruyant et de moins révélateur. La même connexion pose huit questions de plus, et elles se répartissent en trois familles selon la forme de la réponse. | ||
| 86 | + | ||
| 87 | +**Quelque chose à lire.** `hover` — qu'est-ce que c'est ? — dessiné dans une boîte. | ||
| 88 | + | ||
| 89 | +**Des endroits dans le code.** `definition`, `typeDefinition`, `implementation`, `references`. Une requête chacun, une seule forme de réponse pour les quatre, ce qui explique qu'ils soient une seule fonction en dessous. Un seul endroit est ouvert ; plusieurs sont proposés en liste, parce qu'une réponse unique est l'exception plutôt que la règle — une méthode utilisée dans tout un paquet a autant de références que quelqu'un a pris la peine d'en écrire, et pendant longtemps cet éditeur prenait la première et jetait le reste. | ||
| 90 | + | ||
| 91 | +**Des noms.** `documentSymbol` pour le plan d'un fichier, `workspace/symbol` pour une recherche à travers le projet. Le protocole a trois formes pour un symbole et l'éditeur en veut une, si bien que l'aplatissement se fait là où les réponses arrivent plutôt que là où elles sont dessinées. | ||
| 92 | + | ||
| 93 | +Et une chose que personne ne demande : **`publishDiagnostics` arrive sans y être invité**, dès que le serveur a un avis, pour tous les fichiers qu'il a chargés — qui sont d'ordinaire plus nombreux que celui qu'on a sous les yeux. C'est pourquoi Problems liste tous les fichiers plutôt que le fichier courant, et pourquoi la marque dans la gouttière apparaît sans qu'on ait appuyé sur quoi que ce soit. | ||
| 94 | + | ||
| 95 | +**Deux des neuf reviennent vides avec pylsp, et c'est la frontière du serveur, pas celle de l'éditeur.** pylsp n'annonce ni `implementation` ni `workspace/symbol` : **Code ▸ Find implementations** et **Code ▸ Symbol in project** signalent donc n'avoir rien trouvé. Tout le reste fonctionne. C'est écrit ici plutôt que caché parce que l'alternative — griser deux entrées de menu selon ce qu'un serveur a annoncé au démarrage — donnerait au menu une forme différente d'une machine à l'autre, et un utilisateur qui a lu cette page en sait plus qu'un utilisateur tombé sur une entrée grisée. | ||
| 96 | + | ||
| 97 | +L'éditeur ne demande rien de tout cela avant que le serveur se soit dit prêt, et il dit de laquelle il s'agit quand une question ne peut pas trouver de réponse. « Rien trouvé » et « je n'ai pas fini de charger » sont la même réponse vide et deux nouvelles très différentes ; les confondre est la façon la plus déroutante dont la complétion ait jamais échoué ici. | ||
| 98 | + | ||
| 99 | +## Rapport avec le reste | ||
| 100 | + | ||
| 101 | +- Ce qui est reconnu exactement : [Langages colorés](../reference/languages.md) | ||
| 102 | +- Faire marcher la complétion : [Comment activer la complétion Python](../how-to/enable-completion.md) | ||
| 103 | +- Où vit le scanner et pourquoi : [Architecture](architecture.md) | ||
added
docs/fr/explanation/design-decisions.md +109 -0 | new file mode 100644 | ||
| @@ -0,0 +1,109 @@ | ||
| 1 | +# Décisions de conception — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Les choix qui ont façonné Turbo Python, quelles étaient les alternatives, et pourquoi elles ont été écartées. C'est la page à lire avant de modifier quelque chose qui paraît arbitraire. | |
| 6 | + | |
| 7 | +## Deux dépendances, pas une de plus | |
| 8 | + | |
| 9 | +Turbo Python dépend de `tcell/v2` et de `BurntSushi/toml`. Tout le reste est la bibliothèque standard — y compris le tokeniseur, le client JSON-RPC, le cadrage LSP et la gestion des fichiers. | |
| 10 | + | |
| 11 | +**Ce qui a été écarté.** `go.lsp.dev/jsonrpc2` aurait économisé peut-être trois cents lignes de `internal/lsp`. `rivo/tview` en aurait économisé bien davantage dans `internal/ui`. Une bibliothèque de coloration syntaxique aurait apporté cinquante langages au lieu d'un. | |
| 12 | + | |
| 13 | +**Pourquoi.** Un éditeur est un programme qu'on garde des années et qu'on modifie souvent. Chaque dépendance en est un morceau qu'on ne peut pas modifier, pas tester entièrement, et qu'il faut suivre. Le protocole est assez simple pour être écrit, et l'avoir écrit a placé toute la conversation à un endroit qu'un lecteur peut suivre. Trois cents lignes qu'on comprend valent mieux que trois cents qu'on hérite. | |
| 14 | + | |
| 15 | +L'exception confirme la règle : `tcell` n'est pas une commodité, c'est la base de compatibilité des terminaux, et la réimplémenter ne serait ni un petit travail ni un travail honnête. | |
| 16 | + | |
| 17 | +## Le framework de widgets est écrit à la main | |
| 18 | + | |
| 19 | +`tview` a des widgets. `bubbletea` a une architecture. Aucun des deux n'a ce qu'avait Turbo Vision : des fenêtres déplaçables qui se recouvrent avec des ombres, une barre de menus à lettres d'accès et des dialogues modaux, le tout dessiné en caractères semi-graphiques sur seize couleurs. | |
| 20 | + | |
| 21 | +L'architecture à la Elm de `bubbletea` redessine toute la vue à chaque message. Ce modèle est excellent pour un formulaire et malcommode pour un éditeur plein écran où les fenêtres s'empilent et où le curseur doit se trouver dans une cellule précise. | |
| 22 | + | |
| 23 | +Écrire le framework a coûté environ mille cinq cents lignes. En échange, l'éditeur ressemble à Turbo C plutôt qu'à une interface moderne portant un fond bleu, et chaque décision d'affichage se trouve à un fichier de distance. | |
| 24 | + | |
| 25 | +## Les rectangles sont en coordonnées écran absolues | |
| 26 | + | |
| 27 | +Le `Bounds()` de chaque widget indique où il se trouve réellement sur le terminal, pas où il se trouve par rapport à son parent. Tester si un clic l'atteint est alors un simple test de rectangle, et aucun événement n'a jamais besoin d'être traduit en descendant. | |
| 28 | + | |
| 29 | +**Le coût** est que les conteneurs placent leurs enfants dans l'espace de l'écran. **L'alternative** — des coordonnées relatives avec une traduction à chaque saut — déplace le calcul de la mise en page vers la gestion des événements, où il est fait bien plus souvent et où il est bien plus facile de se tromper. Le découpage se compose quand même correctement, puisqu'un peintre intersecte le découpage de son parent : un enfant dont le calcul est faux ne dessine rien plutôt que de dessiner par-dessus ses voisins. | |
| 30 | + | |
| 31 | +## Toute modification passe par une seule fonction | |
| 32 | + | |
| 33 | +`buffer.ReplaceRange` est le seul endroit où le texte est modifié. Insertion, retour arrière, suppression, indentation, collage et annulation y convergent tous, et c'est le seul endroit où sont maintenus l'historique d'annulation, le drapeau « modifié », le compteur de révision et le curseur. | |
| 34 | + | |
| 35 | +L'alternative — chaque opération tenant sa propre comptabilité — est la façon dont naissent les bugs d'annulation. Il y a exactement une chose à réussir, et elle est testée directement. | |
| 36 | + | |
| 37 | +## Les fenêtres suivent le terminal, elles ne s'y mettent pas à l'échelle | |
| 38 | + | |
| 39 | +Une fenêtre a un **mode de croissance**, qui nomme les bords du bureau qu'elle suit. Une fenêtre de document suit les bords droit et bas : son coin supérieur gauche reste où il est, et son coin opposé se déplace exactement autant que celui du terminal. Une fenêtre qui remplissait le terminal le remplit donc toujours, et une fenêtre que vous aviez décalée garde son décalage. | |
| 40 | + | |
| 41 | +**L'alternative était la mise à l'échelle proportionnelle** — multiplier le rectangle de chaque fenêtre par le rapport des tailles. Elle a été écartée parce qu'elle déplace des fenêtres que l'utilisateur a placées exprès, et parce que les arrondis la rendent destructive : réduisez puis agrandissez, et plus rien n'est où il était. Turbo Vision utilisait des modes de croissance, et c'est toujours la bonne réponse. | |
| 42 | + | |
| 43 | +Quel que soit son mode, une fenêtre est ensuite bornée à la taille du bureau. Une fenêtre plus grande que le bureau qui la contient a des parties que personne ne peut atteindre. | |
| 44 | + | |
| 45 | + | |
| 46 | +## Les cases d'une fenêtre disent ce qu'elles vont faire, pas ce que la fenêtre est | |
| 47 | + | |
| 48 | +Le cadre porte deux cases : `[x]` à gauche ferme la fenêtre, `[■]` à droite lui donne tout le bureau. | |
| 49 | + | |
| 50 | +La case de fermeture était `[■]` — celle de Turbo Vision — et il fallait qu'elle bouge. Deux cases sur un même cadre doivent se distinguer d'un coup d'œil, et un bloc plein se lit bien plus volontiers « remplir l'écran » que « fermer ». `[x]` veut dire fermer depuis trente ans ; le bloc est allé au travail auquel il ressemble. | |
| 51 | + | |
| 52 | +La case d'agrandissement **change avec l'état de la fenêtre** : `[■]` tant qu'il reste de la place, `[▬]` une fois que la fenêtre remplit le bureau. L'autre solution était un symbole fixe, et elle rend le bouton ambigu précisément au moment où l'on en a besoin : on voit bien que la fenêtre est grande, mais pas si l'actionner va l'agrandir encore ou la remettre en place. Un contrôle qui montre son *état* laisse déduire l'action ; un contrôle qui montre son *action*, non. | |
| 53 | + | |
| 54 | +Une fenêtre qui n'a nulle part où s'agrandir n'affiche **aucune case**, plutôt qu'une case sans effet. Seul le bureau sait quelle surface une fenêtre remplirait : une fenêtre qui n'est sur aucun bureau n'a rien à proposer. | |
| 55 | + | |
| 56 | +**Window ▸ Maximise est le même bascule**, pas une action à sens unique. Un menu et un bouton en désaccord sur le sens d'« agrandir » seraient un bug qu'on signale, pas une subtilité qu'on apprécie. | |
| 57 | + | |
| 58 | +## L'annulation fusionne les séries de frappe | |
| 59 | + | |
| 60 | +Taper `func` puis Ctrl-Z retire les quatre lettres. Une série de retours arrière aussi. Déplacer le curseur clôt la série, et la frappe ne fusionne jamais avec l'effacement. | |
| 61 | + | |
| 62 | +L'annulation caractère par caractère est ce que donne une implémentation naïve, et c'est ce que faisait Turbo C lui-même. C'est aussi ce dont plus personne ne veut. | |
| 63 | + | |
| 64 | +## Les thèmes sont en TOML, avec deux formes d'héritage | |
| 65 | + | |
| 66 | +**Entre fichiers**, `inherits` prend les styles résolus du parent comme point de départ. Un thème à vous peut donc tenir en cinq lignes. | |
| 67 | + | |
| 68 | +**Entre clés**, le long des points : `syntax.keyword` retombe sur `syntax`, et `syntax` sur `default`. Cela se produit deux fois — une fois à l'analyse, pour qu'une entrée ne définissant que `fg` hérite de son `bg`, et une fois à la lecture, pour qu'un thème qui ne mentionne jamais `syntax.keyword` colore quand même les mots-clés. | |
| 69 | + | |
| 70 | +C'est cette seconde forme qui fait qu'un thème partiel est un thème utilisable, et c'est pourquoi il n'existe pas de thème laissant la moitié de l'écran non peinte. | |
| 71 | + | |
| 72 | +**Pourquoi TOML plutôt que JSON.** Les commentaires. Un thème est un fichier que l'on modifie à la main et que l'on annote. | |
| 73 | + | |
| 74 | +**Une couleur inconnue est une erreur**, pas un repli silencieux sur la couleur par défaut du terminal. Une faute de frappe qui repeint discrètement la moitié de l'écran est bien plus difficile à trouver qu'une qui le dit au chargement. | |
| 75 | + | |
| 76 | +## Le serveur de langage est optionnel par construction | |
| 77 | + | |
| 78 | +`app.Language` enveloppe toute la conversation avec pylsp, et lorsqu'il n'y a pas de serveur, chaque méthode ne fait rien plutôt que d'échouer. Rien d'autre dans l'éditeur ne se demande si un serveur de langage existe. | |
| 79 | + | |
| 80 | +L'alternative — vérifier `nil` à chacun des vingt points d'appel — offre vingt occasions d'oublier. Ici, oublier est impossible : il n'y a rien à vérifier. | |
| 81 | + | |
| 82 | +C'est pourquoi `pylsp` n'est ni embarqué, ni téléchargé, ni requis. Il est cherché dans le `PATH` et dans `GOPATH/bin`, et son absence est signalée sur la barre d'état avec l'unique commande qui la corrige. | |
| 83 | + | |
| 84 | +## L'enregistrement est atomique, et fidèle à l'octet près | |
| 85 | + | |
| 86 | +Un enregistrement écrit dans un fichier temporaire du même répertoire puis le renomme sur la cible, en conservant les permissions d'origine. Un enregistrement interrompu ne peut pas laisser un fichier source à moitié écrit. | |
| 87 | + | |
| 88 | +Par ailleurs, les fins de ligne avec lesquelles un fichier a été lu et son saut de ligne final — ou son absence — sont mémorisés : ouvrir puis enregistrer un fichier non modifié le reproduit octet pour octet. Un éditeur qui normalise silencieusement les fins de ligne transforme une modification d'une ligne en un diff du fichier entier. | |
| 89 | + | |
| 90 | +## Le presse-papier est celui de l'éditeur | |
| 91 | + | |
| 92 | +Un programme en terminal ne peut pas lire le presse-papier du système de façon portable. Plutôt que de faire semblant, Turbo Python partage un presse-papier entre ses propres fenêtres, ce que faisait Turbo C. | |
| 93 | + | |
| 94 | +## La version est une propriété du build, pas des sources | |
| 95 | + | |
| 96 | +La version était autrefois `const Version = "0.1.0"` dans le source de l'éditeur. Elle était juste le jour où elle a été écrite et fausse pendant les quatorze commits suivants, parce que rien dans le fait de valider, taguer ou installer ne touche à une constante Go. Une boîte About, c'est ce que l'on regarde au moment de signaler un bug ; un numéro qui y nomme une release que le binaire n'est pas est pire que pas de numéro, parce qu'on le croit. | |
| 97 | + | |
| 98 | +Le numéro est donc pris au build. L'éditeur de liens estampille `git describe --tags --dirty` dans `internal/version` depuis le Makefile et depuis l'installeur, ce qui fait que `make install` produit un éditeur qui nomme le commit dont il vient. Quand rien ne l'a estampillé, le binaire interroge `runtime/debug.ReadBuildInfo()`, qui couvre le seul chemin impossible à estampiller : `go install rickub.com/turbo-editors/turbo-python@v0.2.0`, où aucun Makefile n'intervient et où l'outil Go connaît la version du module. Ce n'est que si les deux se taisent qu'il annonce `unknown` — délibérément pas un numéro, puisque l'échec contre lequel tout ceci est conçu est justement une version vraisemblable que personne n'a posée. | |
| 99 | + | |
| 100 | +Deux limites du système de build expliquent le reste de la conception. **Il ne lit pas les tags git**, donc un `go build .` nu ne pourra jamais annoncer `0.1.0-14-g88a4c38`, si astucieux que soit le code ; il annonce `devel` plus le commit, et la documentation le dit plutôt que de laisser croire que tous les builds se valent. Et ce qu'il annonce *effectivement* pour un tel build est une **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — affichée comme `devel` à la place, parce que son `0.1.1` est un correctif qui n'existe pas et serait lu comme tel. | |
| 101 | + | |
| 102 | +`vcs.time` est délibérément inutilisé. C'est l'horodatage du commit, et tout binaire est lié après le commit dont il provient : l'étiqueter « Built » serait faux sur chacun d'eux. Une date de build ne s'affiche que si un build en a réellement estampillé une, la même règle que suit la boîte About de bout en bout : **un fait que personne n'a enregistré n'a pas de ligne**, plutôt qu'une ligne vide qui se lit comme un échec à la remplir. | |
| 103 | + | |
| 104 | +Rejeté : une cible `make release` qui tague, construit et pousse. Publier tient en trois commandes git, et les emballer masque laquelle a échoué ; l'estampillage de la version était la partie qu'on ne pouvait pas faire à la main de façon fiable, et c'est celle qui a été automatisée. | |
| 105 | + | |
| 106 | +## Liens avec le reste | |
| 107 | + | |
| 108 | +- Ce que sont les paquets et comment ils s'articulent : [Architecture](architecture.md) | |
| 109 | +- Comment fonctionnent la coloration et la complétion : [Coloration et complétion](colouring-and-completion.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,109 @@ | |||
| 1 | +# Décisions de conception — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Les choix qui ont façonné Turbo Python, quelles étaient les alternatives, et pourquoi elles ont été écartées. C'est la page à lire avant de modifier quelque chose qui paraît arbitraire. | ||
| 6 | + | ||
| 7 | +## Deux dépendances, pas une de plus | ||
| 8 | + | ||
| 9 | +Turbo Python dépend de `tcell/v2` et de `BurntSushi/toml`. Tout le reste est la bibliothèque standard — y compris le tokeniseur, le client JSON-RPC, le cadrage LSP et la gestion des fichiers. | ||
| 10 | + | ||
| 11 | +**Ce qui a été écarté.** `go.lsp.dev/jsonrpc2` aurait économisé peut-être trois cents lignes de `internal/lsp`. `rivo/tview` en aurait économisé bien davantage dans `internal/ui`. Une bibliothèque de coloration syntaxique aurait apporté cinquante langages au lieu d'un. | ||
| 12 | + | ||
| 13 | +**Pourquoi.** Un éditeur est un programme qu'on garde des années et qu'on modifie souvent. Chaque dépendance en est un morceau qu'on ne peut pas modifier, pas tester entièrement, et qu'il faut suivre. Le protocole est assez simple pour être écrit, et l'avoir écrit a placé toute la conversation à un endroit qu'un lecteur peut suivre. Trois cents lignes qu'on comprend valent mieux que trois cents qu'on hérite. | ||
| 14 | + | ||
| 15 | +L'exception confirme la règle : `tcell` n'est pas une commodité, c'est la base de compatibilité des terminaux, et la réimplémenter ne serait ni un petit travail ni un travail honnête. | ||
| 16 | + | ||
| 17 | +## Le framework de widgets est écrit à la main | ||
| 18 | + | ||
| 19 | +`tview` a des widgets. `bubbletea` a une architecture. Aucun des deux n'a ce qu'avait Turbo Vision : des fenêtres déplaçables qui se recouvrent avec des ombres, une barre de menus à lettres d'accès et des dialogues modaux, le tout dessiné en caractères semi-graphiques sur seize couleurs. | ||
| 20 | + | ||
| 21 | +L'architecture à la Elm de `bubbletea` redessine toute la vue à chaque message. Ce modèle est excellent pour un formulaire et malcommode pour un éditeur plein écran où les fenêtres s'empilent et où le curseur doit se trouver dans une cellule précise. | ||
| 22 | + | ||
| 23 | +Écrire le framework a coûté environ mille cinq cents lignes. En échange, l'éditeur ressemble à Turbo C plutôt qu'à une interface moderne portant un fond bleu, et chaque décision d'affichage se trouve à un fichier de distance. | ||
| 24 | + | ||
| 25 | +## Les rectangles sont en coordonnées écran absolues | ||
| 26 | + | ||
| 27 | +Le `Bounds()` de chaque widget indique où il se trouve réellement sur le terminal, pas où il se trouve par rapport à son parent. Tester si un clic l'atteint est alors un simple test de rectangle, et aucun événement n'a jamais besoin d'être traduit en descendant. | ||
| 28 | + | ||
| 29 | +**Le coût** est que les conteneurs placent leurs enfants dans l'espace de l'écran. **L'alternative** — des coordonnées relatives avec une traduction à chaque saut — déplace le calcul de la mise en page vers la gestion des événements, où il est fait bien plus souvent et où il est bien plus facile de se tromper. Le découpage se compose quand même correctement, puisqu'un peintre intersecte le découpage de son parent : un enfant dont le calcul est faux ne dessine rien plutôt que de dessiner par-dessus ses voisins. | ||
| 30 | + | ||
| 31 | +## Toute modification passe par une seule fonction | ||
| 32 | + | ||
| 33 | +`buffer.ReplaceRange` est le seul endroit où le texte est modifié. Insertion, retour arrière, suppression, indentation, collage et annulation y convergent tous, et c'est le seul endroit où sont maintenus l'historique d'annulation, le drapeau « modifié », le compteur de révision et le curseur. | ||
| 34 | + | ||
| 35 | +L'alternative — chaque opération tenant sa propre comptabilité — est la façon dont naissent les bugs d'annulation. Il y a exactement une chose à réussir, et elle est testée directement. | ||
| 36 | + | ||
| 37 | +## Les fenêtres suivent le terminal, elles ne s'y mettent pas à l'échelle | ||
| 38 | + | ||
| 39 | +Une fenêtre a un **mode de croissance**, qui nomme les bords du bureau qu'elle suit. Une fenêtre de document suit les bords droit et bas : son coin supérieur gauche reste où il est, et son coin opposé se déplace exactement autant que celui du terminal. Une fenêtre qui remplissait le terminal le remplit donc toujours, et une fenêtre que vous aviez décalée garde son décalage. | ||
| 40 | + | ||
| 41 | +**L'alternative était la mise à l'échelle proportionnelle** — multiplier le rectangle de chaque fenêtre par le rapport des tailles. Elle a été écartée parce qu'elle déplace des fenêtres que l'utilisateur a placées exprès, et parce que les arrondis la rendent destructive : réduisez puis agrandissez, et plus rien n'est où il était. Turbo Vision utilisait des modes de croissance, et c'est toujours la bonne réponse. | ||
| 42 | + | ||
| 43 | +Quel que soit son mode, une fenêtre est ensuite bornée à la taille du bureau. Une fenêtre plus grande que le bureau qui la contient a des parties que personne ne peut atteindre. | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +## Les cases d'une fenêtre disent ce qu'elles vont faire, pas ce que la fenêtre est | ||
| 47 | + | ||
| 48 | +Le cadre porte deux cases : `[x]` à gauche ferme la fenêtre, `[■]` à droite lui donne tout le bureau. | ||
| 49 | + | ||
| 50 | +La case de fermeture était `[■]` — celle de Turbo Vision — et il fallait qu'elle bouge. Deux cases sur un même cadre doivent se distinguer d'un coup d'œil, et un bloc plein se lit bien plus volontiers « remplir l'écran » que « fermer ». `[x]` veut dire fermer depuis trente ans ; le bloc est allé au travail auquel il ressemble. | ||
| 51 | + | ||
| 52 | +La case d'agrandissement **change avec l'état de la fenêtre** : `[■]` tant qu'il reste de la place, `[▬]` une fois que la fenêtre remplit le bureau. L'autre solution était un symbole fixe, et elle rend le bouton ambigu précisément au moment où l'on en a besoin : on voit bien que la fenêtre est grande, mais pas si l'actionner va l'agrandir encore ou la remettre en place. Un contrôle qui montre son *état* laisse déduire l'action ; un contrôle qui montre son *action*, non. | ||
| 53 | + | ||
| 54 | +Une fenêtre qui n'a nulle part où s'agrandir n'affiche **aucune case**, plutôt qu'une case sans effet. Seul le bureau sait quelle surface une fenêtre remplirait : une fenêtre qui n'est sur aucun bureau n'a rien à proposer. | ||
| 55 | + | ||
| 56 | +**Window ▸ Maximise est le même bascule**, pas une action à sens unique. Un menu et un bouton en désaccord sur le sens d'« agrandir » seraient un bug qu'on signale, pas une subtilité qu'on apprécie. | ||
| 57 | + | ||
| 58 | +## L'annulation fusionne les séries de frappe | ||
| 59 | + | ||
| 60 | +Taper `func` puis Ctrl-Z retire les quatre lettres. Une série de retours arrière aussi. Déplacer le curseur clôt la série, et la frappe ne fusionne jamais avec l'effacement. | ||
| 61 | + | ||
| 62 | +L'annulation caractère par caractère est ce que donne une implémentation naïve, et c'est ce que faisait Turbo C lui-même. C'est aussi ce dont plus personne ne veut. | ||
| 63 | + | ||
| 64 | +## Les thèmes sont en TOML, avec deux formes d'héritage | ||
| 65 | + | ||
| 66 | +**Entre fichiers**, `inherits` prend les styles résolus du parent comme point de départ. Un thème à vous peut donc tenir en cinq lignes. | ||
| 67 | + | ||
| 68 | +**Entre clés**, le long des points : `syntax.keyword` retombe sur `syntax`, et `syntax` sur `default`. Cela se produit deux fois — une fois à l'analyse, pour qu'une entrée ne définissant que `fg` hérite de son `bg`, et une fois à la lecture, pour qu'un thème qui ne mentionne jamais `syntax.keyword` colore quand même les mots-clés. | ||
| 69 | + | ||
| 70 | +C'est cette seconde forme qui fait qu'un thème partiel est un thème utilisable, et c'est pourquoi il n'existe pas de thème laissant la moitié de l'écran non peinte. | ||
| 71 | + | ||
| 72 | +**Pourquoi TOML plutôt que JSON.** Les commentaires. Un thème est un fichier que l'on modifie à la main et que l'on annote. | ||
| 73 | + | ||
| 74 | +**Une couleur inconnue est une erreur**, pas un repli silencieux sur la couleur par défaut du terminal. Une faute de frappe qui repeint discrètement la moitié de l'écran est bien plus difficile à trouver qu'une qui le dit au chargement. | ||
| 75 | + | ||
| 76 | +## Le serveur de langage est optionnel par construction | ||
| 77 | + | ||
| 78 | +`app.Language` enveloppe toute la conversation avec pylsp, et lorsqu'il n'y a pas de serveur, chaque méthode ne fait rien plutôt que d'échouer. Rien d'autre dans l'éditeur ne se demande si un serveur de langage existe. | ||
| 79 | + | ||
| 80 | +L'alternative — vérifier `nil` à chacun des vingt points d'appel — offre vingt occasions d'oublier. Ici, oublier est impossible : il n'y a rien à vérifier. | ||
| 81 | + | ||
| 82 | +C'est pourquoi `pylsp` n'est ni embarqué, ni téléchargé, ni requis. Il est cherché dans le `PATH` et dans `GOPATH/bin`, et son absence est signalée sur la barre d'état avec l'unique commande qui la corrige. | ||
| 83 | + | ||
| 84 | +## L'enregistrement est atomique, et fidèle à l'octet près | ||
| 85 | + | ||
| 86 | +Un enregistrement écrit dans un fichier temporaire du même répertoire puis le renomme sur la cible, en conservant les permissions d'origine. Un enregistrement interrompu ne peut pas laisser un fichier source à moitié écrit. | ||
| 87 | + | ||
| 88 | +Par ailleurs, les fins de ligne avec lesquelles un fichier a été lu et son saut de ligne final — ou son absence — sont mémorisés : ouvrir puis enregistrer un fichier non modifié le reproduit octet pour octet. Un éditeur qui normalise silencieusement les fins de ligne transforme une modification d'une ligne en un diff du fichier entier. | ||
| 89 | + | ||
| 90 | +## Le presse-papier est celui de l'éditeur | ||
| 91 | + | ||
| 92 | +Un programme en terminal ne peut pas lire le presse-papier du système de façon portable. Plutôt que de faire semblant, Turbo Python partage un presse-papier entre ses propres fenêtres, ce que faisait Turbo C. | ||
| 93 | + | ||
| 94 | +## La version est une propriété du build, pas des sources | ||
| 95 | + | ||
| 96 | +La version était autrefois `const Version = "0.1.0"` dans le source de l'éditeur. Elle était juste le jour où elle a été écrite et fausse pendant les quatorze commits suivants, parce que rien dans le fait de valider, taguer ou installer ne touche à une constante Go. Une boîte About, c'est ce que l'on regarde au moment de signaler un bug ; un numéro qui y nomme une release que le binaire n'est pas est pire que pas de numéro, parce qu'on le croit. | ||
| 97 | + | ||
| 98 | +Le numéro est donc pris au build. L'éditeur de liens estampille `git describe --tags --dirty` dans `internal/version` depuis le Makefile et depuis l'installeur, ce qui fait que `make install` produit un éditeur qui nomme le commit dont il vient. Quand rien ne l'a estampillé, le binaire interroge `runtime/debug.ReadBuildInfo()`, qui couvre le seul chemin impossible à estampiller : `go install rickub.com/turbo-editors/turbo-python@v0.2.0`, où aucun Makefile n'intervient et où l'outil Go connaît la version du module. Ce n'est que si les deux se taisent qu'il annonce `unknown` — délibérément pas un numéro, puisque l'échec contre lequel tout ceci est conçu est justement une version vraisemblable que personne n'a posée. | ||
| 99 | + | ||
| 100 | +Deux limites du système de build expliquent le reste de la conception. **Il ne lit pas les tags git**, donc un `go build .` nu ne pourra jamais annoncer `0.1.0-14-g88a4c38`, si astucieux que soit le code ; il annonce `devel` plus le commit, et la documentation le dit plutôt que de laisser croire que tous les builds se valent. Et ce qu'il annonce *effectivement* pour un tel build est une **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — affichée comme `devel` à la place, parce que son `0.1.1` est un correctif qui n'existe pas et serait lu comme tel. | ||
| 101 | + | ||
| 102 | +`vcs.time` est délibérément inutilisé. C'est l'horodatage du commit, et tout binaire est lié après le commit dont il provient : l'étiqueter « Built » serait faux sur chacun d'eux. Une date de build ne s'affiche que si un build en a réellement estampillé une, la même règle que suit la boîte About de bout en bout : **un fait que personne n'a enregistré n'a pas de ligne**, plutôt qu'une ligne vide qui se lit comme un échec à la remplir. | ||
| 103 | + | ||
| 104 | +Rejeté : une cible `make release` qui tague, construit et pousse. Publier tient en trois commandes git, et les emballer masque laquelle a échoué ; l'estampillage de la version était la partie qu'on ne pouvait pas faire à la main de façon fiable, et c'est celle qui a été automatisée. | ||
| 105 | + | ||
| 106 | +## Liens avec le reste | ||
| 107 | + | ||
| 108 | +- Ce que sont les paquets et comment ils s'articulent : [Architecture](architecture.md) | ||
| 109 | +- Comment fonctionnent la coloration et la complétion : [Coloration et complétion](colouring-and-completion.md) | ||
added
docs/fr/explanation/project-settings.md +68 -0 | new file mode 100644 | ||
| @@ -0,0 +1,68 @@ | ||
| 1 | +# Réglages de projet — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Un projet peut garder un `.turbo-python/settings.toml` à côté de son code, disant quel thème utiliser et s'il faut enregistrer les fichiers automatiquement. Cette page traite des décisions contenues dans cette phrase : pourquoi le fichier n'est cherché qu'à un seul endroit, pourquoi le créer est une entrée de menu plutôt que quelque chose qui arrive tout seul, et pourquoi la sauvegarde automatique fonctionne comme elle le fait. | |
| 6 | + | |
| 7 | +## Pourquoi le dossier n'est pas cherché vers le haut | |
| 8 | + | |
| 9 | +`pyproject.toml` est trouvé en remontant depuis le fichier ouvert jusqu'à en croiser un, et le serveur de langage fait exactement cela. Le fichier de réglages, délibérément, non. | |
| 10 | + | |
| 11 | +La remontée est juste pour `pyproject.toml` parce qu'un module a une frontière réelle : le fichier est au-dessus de vous ou il n'y est pas, et être dans un module est un fait à propos du code. « Le projet » n'est pas un fait à propos du code. C'est l'endroit où vous avez décidé de travailler, et la même arborescence est plusieurs projets selon ce que vous y faites — le `services/api` d'un monorepo est un projet quand vous travaillez sur l'API, et une partie d'un plus grand le reste du temps. | |
| 12 | + | |
| 13 | +Une remontée ferait aussi agir le réglage à distance. Vous ouvrez un fichier, et les couleurs de l'éditeur changent à cause d'un fichier trois dossiers plus haut dont vous ignoriez l'existence. Toute explication de ce comportement commence par « eh bien, il cherche vers le haut », alors que la règle qu'on préfère pouvoir énoncer est celle qui est maintenant vraie : **le projet est le dossier depuis lequel vous avez lancé l'éditeur.** | |
| 14 | + | |
| 15 | +Le coût est réel et mérite d'être nommé. Lancez l'éditeur depuis `internal/app` et le thème du projet ne s'applique pas. La réponse est de lancer depuis la racine du projet, là où vous feriez `go build` et `git` de toute façon. | |
| 16 | + | |
| 17 | +## Pourquoi créer le fichier est une entrée de menu | |
| 18 | + | |
| 19 | +L'autre solution était tentante : à la première fois qu'on choisit un thème, écrire `.turbo-python/settings.toml` pour que le choix persiste. Tout éditeur qui stocke un état d'espace de travail fait quelque chose d'approchant. | |
| 20 | + | |
| 21 | +Elle a été écartée parce qu'elle dépose un dossier dans le dépôt de quelqu'un comme effet de bord d'un essai de couleur. L'utilisateur est à un `git status` d'une modification qu'il n'a pas faite, dans un projet qui n'est peut-être pas le sien, éventuellement en pleine revue. Un thème choisi pour être regardé dix secondes ne doit rien laisser derrière lui. | |
| 22 | + | |
| 23 | +Le fichier n'est donc créé que par **Options ▸ Create project settings**, et son existence signifie quelque chose : ce projet a des réglages, exprès. C'est aussi ce qui rend la règle d'écriture simple à énoncer — **le thème est écrit dans le fichier quand le fichier existe, et pas autrement** — sans nulle part une case « voulez-vous vous en souvenir ? ». | |
| 24 | + | |
| 25 | +## Pourquoi le thème est réécrit sur place plutôt que réencodé | |
| 26 | + | |
| 27 | +Une fois le fichier créé, choisir un thème le réécrit. Sérialiser la structure `Settings` vers du TOML ferait quatre lignes et supprimerait tous les commentaires du fichier. | |
| 28 | + | |
| 29 | +Cela compte plus ici qu'ailleurs, parce que ce fichier est *fait* pour être édité à la main. C'est la raison d'être de la coloration TOML dans l'éditeur ; le fichier créé est surtout des commentaires expliquant les clés ; une équipe y ajoutera ses propres commentaires disant pourquoi elle a choisi ce qu'elle a choisi. Tout perdre à la première tentative d'un autre thème serait une suppression silencieuse et surprenante de ce que quelqu'un a écrit. | |
| 30 | + | |
| 31 | +La réécriture trouve donc la ligne `theme` dans la table `[editor]` et change la valeur entre le `=` et un éventuel commentaire de fin de ligne. Tout le reste du fichier revient octet pour octet. Cela fait une quarantaine de lignes au lieu de quatre, et c'est la différence entre un fichier où l'on peut mettre des choses et un fichier qui les mange. | |
| 32 | + | |
| 33 | +## Pourquoi la sauvegarde automatique attend une pause | |
| 34 | + | |
| 35 | +Trois déclencheurs ont été envisagés. | |
| 36 | + | |
| 37 | +**À intervalle fixe** est le plus simple et il est faux : il écrit au milieu d'une modification. La moitié d'un identifiant renommé atteint le disque, un observateur de fichiers reconstruit, et une suite de tests échoue sur du code qui n'a jamais été l'intention de personne. | |
| 38 | + | |
| 39 | +**À la sortie de la fenêtre** n'écrit jamais pendant qu'on travaille, ce qui semble prudent et signifie que ce qui est sur le disque peut avoir une heure de retard sur ce qui est à l'écran — précisément quand cela compte, puisque la raison de vouloir l'autosave est en général un outil qui surveille le fichier. | |
| 40 | + | |
| 41 | +**Après une pause dans la frappe** est ce sur quoi les autres éditeurs et celui-ci se sont arrêtés. Deux secondes, c'est assez long pour qu'une pause de réflexion ne soit pas une écriture, assez court pour qu'une reconstruction suive de près une modification. Une série de frappes fait une écriture, pas une par touche. | |
| 42 | + | |
| 43 | +Il y a une seule échéance pour tout l'éditeur plutôt qu'une par fenêtre, parce que « vous avez cessé de taper » est un seul événement. Une échéance par fenêtre enregistrerait le fichier que vous avez quitté à un moment différent de celui que vous avez sous les yeux, ce que personne ne pourrait observer et qui fait davantage d'état à maintenir juste. | |
| 44 | + | |
| 45 | +## Pourquoi l'échéance est vérifiée, le minuteur ne faisant que pousser | |
| 46 | + | |
| 47 | +C'est le même piège que l'annonce au serveur de langage et que les redessins de terminal ont rencontré, et il vaut d'être énoncé une fois de plus parce qu'il reviendra. | |
| 48 | + | |
| 49 | +L'éditeur est bloqué dans `PollEvent`. Pour remarquer une échéance alors que rien ne se passe, il faut le réveiller, et le seul moyen de le réveiller depuis un minuteur est `PostEvent` — qui **jette** les événements quand sa file est pleine. | |
| 50 | + | |
| 51 | +Le minuteur n'est donc pas ce qui décide. L'échéance est un état, vérifié en tête de chaque tour de boucle, exactement comme `announceOpenDocuments` vérifie si le serveur de langage est prêt. Le seul rôle du minuteur est de garantir qu'un tour ait lieu. Une poussée perdue coûte une sauvegarde en retard jusqu'à la frappe ou au clic suivant ; un design où le minuteur enregistrerait lui-même la perdrait tout court. | |
| 52 | + | |
| 53 | +## Pourquoi une sauvegarde automatique en échec n'ouvre pas de dialogue | |
| 54 | + | |
| 55 | +Une sauvegarde que personne n'a demandée ne doit pas interrompre par une fenêtre modale, et une modale qui revient toutes les deux secondes parce qu'un fichier est en lecture seule est pire que le problème qu'elle signale. Cela va donc dans la barre d'état, et l'échéance est effacée *avant* la tentative d'écriture : un fichier qui ne peut pas être écrit est essayé une fois par modification, et non indéfiniment. | |
| 56 | + | |
| 57 | +## Pourquoi la coloration TOML réutilise les classes de Go | |
| 58 | + | |
| 59 | +Ajouter `syntax.tomlkey` et compagnie aurait signifié que tous les thèmes — y compris ceux écrits par les utilisateurs — auraient silencieusement échoué à colorer le TOML jusqu'à leur mise à jour. | |
| 60 | + | |
| 61 | +Les classes déjà présentes conviennent : un en-tête de table nomme une structure, il se lit donc comme un type ; une clé nomme une chose, elle se lit donc comme un identifiant ; `true` et `false` sont des constantes parce que c'est ce qu'elles sont. Le résultat est que tout thème qui a jamais fonctionné colore le TOML correctement, sans modification et sans nouvelle clé. Le scanner est écrit à la main pour la même raison que l'émulateur de terminal — le TOML est un langage petit et entièrement spécifié, et c'est un fichier contre une troisième dépendance. | |
| 62 | + | |
| 63 | +## Liens avec le reste | |
| 64 | + | |
| 65 | +- Les clés exactes et leurs valeurs par défaut : [Référence des réglages de projet](../reference/project-settings.md) | |
| 66 | +- En mettre en place : [Donner ses propres réglages à un projet](../how-to/configure-a-project.md) | |
| 67 | +- L'autre fichier TOML que lit l'éditeur : [Format des fichiers de thème](../reference/themes.md) | |
| 68 | +- Où `settings` se situe parmi les paquets : [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | +# Réglages de projet — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Un projet peut garder un `.turbo-python/settings.toml` à côté de son code, disant quel thème utiliser et s'il faut enregistrer les fichiers automatiquement. Cette page traite des décisions contenues dans cette phrase : pourquoi le fichier n'est cherché qu'à un seul endroit, pourquoi le créer est une entrée de menu plutôt que quelque chose qui arrive tout seul, et pourquoi la sauvegarde automatique fonctionne comme elle le fait. | ||
| 6 | + | ||
| 7 | +## Pourquoi le dossier n'est pas cherché vers le haut | ||
| 8 | + | ||
| 9 | +`pyproject.toml` est trouvé en remontant depuis le fichier ouvert jusqu'à en croiser un, et le serveur de langage fait exactement cela. Le fichier de réglages, délibérément, non. | ||
| 10 | + | ||
| 11 | +La remontée est juste pour `pyproject.toml` parce qu'un module a une frontière réelle : le fichier est au-dessus de vous ou il n'y est pas, et être dans un module est un fait à propos du code. « Le projet » n'est pas un fait à propos du code. C'est l'endroit où vous avez décidé de travailler, et la même arborescence est plusieurs projets selon ce que vous y faites — le `services/api` d'un monorepo est un projet quand vous travaillez sur l'API, et une partie d'un plus grand le reste du temps. | ||
| 12 | + | ||
| 13 | +Une remontée ferait aussi agir le réglage à distance. Vous ouvrez un fichier, et les couleurs de l'éditeur changent à cause d'un fichier trois dossiers plus haut dont vous ignoriez l'existence. Toute explication de ce comportement commence par « eh bien, il cherche vers le haut », alors que la règle qu'on préfère pouvoir énoncer est celle qui est maintenant vraie : **le projet est le dossier depuis lequel vous avez lancé l'éditeur.** | ||
| 14 | + | ||
| 15 | +Le coût est réel et mérite d'être nommé. Lancez l'éditeur depuis `internal/app` et le thème du projet ne s'applique pas. La réponse est de lancer depuis la racine du projet, là où vous feriez `go build` et `git` de toute façon. | ||
| 16 | + | ||
| 17 | +## Pourquoi créer le fichier est une entrée de menu | ||
| 18 | + | ||
| 19 | +L'autre solution était tentante : à la première fois qu'on choisit un thème, écrire `.turbo-python/settings.toml` pour que le choix persiste. Tout éditeur qui stocke un état d'espace de travail fait quelque chose d'approchant. | ||
| 20 | + | ||
| 21 | +Elle a été écartée parce qu'elle dépose un dossier dans le dépôt de quelqu'un comme effet de bord d'un essai de couleur. L'utilisateur est à un `git status` d'une modification qu'il n'a pas faite, dans un projet qui n'est peut-être pas le sien, éventuellement en pleine revue. Un thème choisi pour être regardé dix secondes ne doit rien laisser derrière lui. | ||
| 22 | + | ||
| 23 | +Le fichier n'est donc créé que par **Options ▸ Create project settings**, et son existence signifie quelque chose : ce projet a des réglages, exprès. C'est aussi ce qui rend la règle d'écriture simple à énoncer — **le thème est écrit dans le fichier quand le fichier existe, et pas autrement** — sans nulle part une case « voulez-vous vous en souvenir ? ». | ||
| 24 | + | ||
| 25 | +## Pourquoi le thème est réécrit sur place plutôt que réencodé | ||
| 26 | + | ||
| 27 | +Une fois le fichier créé, choisir un thème le réécrit. Sérialiser la structure `Settings` vers du TOML ferait quatre lignes et supprimerait tous les commentaires du fichier. | ||
| 28 | + | ||
| 29 | +Cela compte plus ici qu'ailleurs, parce que ce fichier est *fait* pour être édité à la main. C'est la raison d'être de la coloration TOML dans l'éditeur ; le fichier créé est surtout des commentaires expliquant les clés ; une équipe y ajoutera ses propres commentaires disant pourquoi elle a choisi ce qu'elle a choisi. Tout perdre à la première tentative d'un autre thème serait une suppression silencieuse et surprenante de ce que quelqu'un a écrit. | ||
| 30 | + | ||
| 31 | +La réécriture trouve donc la ligne `theme` dans la table `[editor]` et change la valeur entre le `=` et un éventuel commentaire de fin de ligne. Tout le reste du fichier revient octet pour octet. Cela fait une quarantaine de lignes au lieu de quatre, et c'est la différence entre un fichier où l'on peut mettre des choses et un fichier qui les mange. | ||
| 32 | + | ||
| 33 | +## Pourquoi la sauvegarde automatique attend une pause | ||
| 34 | + | ||
| 35 | +Trois déclencheurs ont été envisagés. | ||
| 36 | + | ||
| 37 | +**À intervalle fixe** est le plus simple et il est faux : il écrit au milieu d'une modification. La moitié d'un identifiant renommé atteint le disque, un observateur de fichiers reconstruit, et une suite de tests échoue sur du code qui n'a jamais été l'intention de personne. | ||
| 38 | + | ||
| 39 | +**À la sortie de la fenêtre** n'écrit jamais pendant qu'on travaille, ce qui semble prudent et signifie que ce qui est sur le disque peut avoir une heure de retard sur ce qui est à l'écran — précisément quand cela compte, puisque la raison de vouloir l'autosave est en général un outil qui surveille le fichier. | ||
| 40 | + | ||
| 41 | +**Après une pause dans la frappe** est ce sur quoi les autres éditeurs et celui-ci se sont arrêtés. Deux secondes, c'est assez long pour qu'une pause de réflexion ne soit pas une écriture, assez court pour qu'une reconstruction suive de près une modification. Une série de frappes fait une écriture, pas une par touche. | ||
| 42 | + | ||
| 43 | +Il y a une seule échéance pour tout l'éditeur plutôt qu'une par fenêtre, parce que « vous avez cessé de taper » est un seul événement. Une échéance par fenêtre enregistrerait le fichier que vous avez quitté à un moment différent de celui que vous avez sous les yeux, ce que personne ne pourrait observer et qui fait davantage d'état à maintenir juste. | ||
| 44 | + | ||
| 45 | +## Pourquoi l'échéance est vérifiée, le minuteur ne faisant que pousser | ||
| 46 | + | ||
| 47 | +C'est le même piège que l'annonce au serveur de langage et que les redessins de terminal ont rencontré, et il vaut d'être énoncé une fois de plus parce qu'il reviendra. | ||
| 48 | + | ||
| 49 | +L'éditeur est bloqué dans `PollEvent`. Pour remarquer une échéance alors que rien ne se passe, il faut le réveiller, et le seul moyen de le réveiller depuis un minuteur est `PostEvent` — qui **jette** les événements quand sa file est pleine. | ||
| 50 | + | ||
| 51 | +Le minuteur n'est donc pas ce qui décide. L'échéance est un état, vérifié en tête de chaque tour de boucle, exactement comme `announceOpenDocuments` vérifie si le serveur de langage est prêt. Le seul rôle du minuteur est de garantir qu'un tour ait lieu. Une poussée perdue coûte une sauvegarde en retard jusqu'à la frappe ou au clic suivant ; un design où le minuteur enregistrerait lui-même la perdrait tout court. | ||
| 52 | + | ||
| 53 | +## Pourquoi une sauvegarde automatique en échec n'ouvre pas de dialogue | ||
| 54 | + | ||
| 55 | +Une sauvegarde que personne n'a demandée ne doit pas interrompre par une fenêtre modale, et une modale qui revient toutes les deux secondes parce qu'un fichier est en lecture seule est pire que le problème qu'elle signale. Cela va donc dans la barre d'état, et l'échéance est effacée *avant* la tentative d'écriture : un fichier qui ne peut pas être écrit est essayé une fois par modification, et non indéfiniment. | ||
| 56 | + | ||
| 57 | +## Pourquoi la coloration TOML réutilise les classes de Go | ||
| 58 | + | ||
| 59 | +Ajouter `syntax.tomlkey` et compagnie aurait signifié que tous les thèmes — y compris ceux écrits par les utilisateurs — auraient silencieusement échoué à colorer le TOML jusqu'à leur mise à jour. | ||
| 60 | + | ||
| 61 | +Les classes déjà présentes conviennent : un en-tête de table nomme une structure, il se lit donc comme un type ; une clé nomme une chose, elle se lit donc comme un identifiant ; `true` et `false` sont des constantes parce que c'est ce qu'elles sont. Le résultat est que tout thème qui a jamais fonctionné colore le TOML correctement, sans modification et sans nouvelle clé. Le scanner est écrit à la main pour la même raison que l'émulateur de terminal — le TOML est un langage petit et entièrement spécifié, et c'est un fichier contre une troisième dépendance. | ||
| 62 | + | ||
| 63 | +## Liens avec le reste | ||
| 64 | + | ||
| 65 | +- Les clés exactes et leurs valeurs par défaut : [Référence des réglages de projet](../reference/project-settings.md) | ||
| 66 | +- En mettre en place : [Donner ses propres réglages à un projet](../how-to/configure-a-project.md) | ||
| 67 | +- L'autre fichier TOML que lit l'éditeur : [Format des fichiers de thème](../reference/themes.md) | ||
| 68 | +- Où `settings` se situe parmi les paquets : [Architecture](architecture.md) | ||
added
docs/fr/explanation/project-tree.md +58 -0 | new file mode 100644 | ||
| @@ -0,0 +1,58 @@ | ||
| 1 | +# Arbre du projet — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +`F9` ouvre une fenêtre listant les fichiers du projet, et `Entrée` sur l'un d'eux l'ouvre. Cette page traite des trois décisions contenues là-dedans : où l'arbre s'enracine, pourquoi c'est une fenêtre plutôt qu'un panneau sur le côté, et pourquoi il ne remarque pas tout seul l'apparition de fichiers. | |
| 6 | + | |
| 7 | +## Pourquoi la racine est le répertoire de travail | |
| 8 | + | |
| 9 | +L'éditeur contient déjà deux réponses différentes à « qu'est-ce que le projet ». | |
| 10 | + | |
| 11 | +Le serveur de langage remonte depuis le fichier ouvert jusqu'à trouver un `pyproject.toml`, parce qu'un module a une frontière réelle — en être à l'intérieur est un fait à propos du code, et pylsp a besoin de ce dossier précis pour travailler. Le fichier de réglages, lui, ne remonte pas du tout : `.turbo-python/settings.toml` est cherché dans le répertoire de travail et nulle part ailleurs. | |
| 12 | + | |
| 13 | +L'arbre suit le fichier de réglages, et il vaut la peine de dire pourquoi l'*autre* règle était tentante. Remonter jusqu'au `pyproject.toml` ferait qu'ouvrir un fichier de n'importe où dans un projet montrerait tout le projet, ce que fait habituellement un explorateur. Mais cela signifie aussi que la racine de l'arbre dépend d'un fichier trois dossiers plus loin auquel vous n'avez peut-être pas pensé, et cela cesse d'être prévisible dès qu'un dépôt contient plus d'un module — un monorepo vous montrerait le module auquel appartient le fichier que vous avez ouvert par hasard. | |
| 14 | + | |
| 15 | +La règle retenue est celle qui tient en une phrase et qui est vraie partout dans l'éditeur : **le projet est le dossier depuis lequel vous avez lancé l'éditeur.** Elle coûte quelque chose, et ce coût est nommé dans le [guide](../how-to/browse-a-project.md) : lancez depuis un sous-dossier et vous obtenez l'arbre de ce sous-dossier. La réponse est de lancer depuis la racine du projet, là où vous feriez `go build` et `git` de toute façon. | |
| 16 | + | |
| 17 | +## Pourquoi `.git` est masqué et rien d'autre | |
| 18 | + | |
| 19 | +Le dialogue Open masque toute entrée commençant par un point. Recopier cela ici était la chose évidente, et aurait été faux. | |
| 20 | + | |
| 21 | +`.turbo-python/settings.toml` est un fichier que cet éditeur demande aux gens d'éditer — c'est la raison d'être de la coloration TOML. `.gitignore` et `.qlty/qlty.toml` sont eux aussi des fichiers du projet. Un arbre qui les cacherait rendrait la configuration de l'éditeur inaccessible depuis l'explorateur de fichiers de l'éditeur, ce qui est un endroit curieux où aboutir. | |
| 22 | + | |
| 23 | +`.git` diffère par nature et non par orthographe : rien à l'intérieur n'est fait pour être ouvert à la main, et il contient assez d'objets pour enterrer tout le reste dans la liste. Un seul nom, masqué pour une raison énonçable. Respecter aussi `.gitignore` a été envisagé et écarté pour l'instant : cela masquerait `bin/` et `release/`, ce qui serait réellement plus agréable, et cela coûte un moteur de motifs gitignore — négations, `**`, ancrage — qui est une fonctionnalité à part entière plutôt qu'un détail d'arbre. | |
| 24 | + | |
| 25 | +## Pourquoi une fenêtre, pas un panneau | |
| 26 | + | |
| 27 | +Tous les autres éditeurs mettent leur arbre de fichiers dans une bande fixe à gauche. C'était l'alternative, et elle a été écartée à cause de ce qu'elle aurait coûté au reste de l'éditeur. | |
| 28 | + | |
| 29 | +Un panneau ancré signifie que le bureau n'est plus un simple rectangle où vivent les fenêtres. `Desktop` aurait besoin d'une notion de bords réservés ; `Window.fitInto` et les modes de croissance devraient les respecter ; agrandir voudrait dire « tout le bureau sauf le panneau » ; la mise en mosaïque et en cascade devraient en tenir compte. C'est une modification des fondations de toute l'interface, pour un seul widget. | |
| 30 | + | |
| 31 | +En fenêtre ordinaire, l'arbre obtient tout gratuitement et se comporte comme le reste : `F6` l'atteint, `Alt-2` le remonte, `[x]` le ferme, `[■]` lui donne tout le bureau, **Window ▸ Tile** le met à côté de votre fichier. Rien dans `ui` n'a eu à changer. Si un panneau ancré est voulu plus tard, c'est une fonctionnalité de `ui` à concevoir pour elle-même, plutôt qu'à faire passer en douce avec un explorateur de fichiers. | |
| 32 | + | |
| 33 | +## Pourquoi il n'y en a qu'un | |
| 34 | + | |
| 35 | +Deux arbres sur le même projet seraient deux vues d'une même chose sans rien pour les distinguer, et le projet ne peut pas changer pendant que l'éditeur tourne — la racine est fixée au démarrage. `F9` sur un arbre ouvert le remonte donc au lieu d'en créer un autre, exactement comme ouvrir un fichier déjà ouvert remonte sa fenêtre. | |
| 36 | + | |
| 37 | +## Pourquoi il ne surveille pas le disque | |
| 38 | + | |
| 39 | +Un arbre qui remarquerait `go build` produisant `bin/` serait meilleur. Le faire correctement signifie surveiller le système de fichiers, et en Go cela signifie `fsnotify` — une troisième dépendance, contre un projet qui s'en tient à deux depuis le début et qui traite l'ajout d'une dépendance comme une décision à défendre. | |
| 40 | + | |
| 41 | +Ce n'est pas non plus une petite dépendance en comportement : surveillances récursives, descripteurs épuisés sur les grosses arborescences, et une sémantique différente sur chaque plateforme — pour une fonctionnalité dont le mode d'échec est une ligne périmée dans une liste. | |
| 42 | + | |
| 43 | +L'arbre relit donc à la demande, et l'éditeur choisit les moments dont il peut être sûr. Enregistrer un fichier en est un : c'est l'éditeur qui l'a fait, il le sait donc. `F5` et `Ctrl-R` sont l'autre, parce qu'une compilation dans une fenêtre terminal est quelque chose que seul l'utilisateur sait terminée. Le rafraîchissement conserve la forme de l'arbre et ne relit que les dossiers réellement ouverts : il coûte ce qui est à l'écran, pas un parcours du projet. | |
| 44 | + | |
| 45 | +## Pourquoi l'arbre a ses propres clés de thème | |
| 46 | + | |
| 47 | +L'économie évidente était de le dessiner avec les clés `list.*` — un arbre est une liste, après tout, et cela n'aurait ajouté aucune clé que les thèmes utilisateur puissent manquer. | |
| 48 | + | |
| 49 | +Cela ne marche pas, et la raison mérite d'être consignée. `list.selected` est colorée pour ressortir sur un **dialogue**. Dans `turbo-classic` c'est blanc sur navy, et `window.body` est silver sur **navy** — un arbre dans une fenêtre aurait surligné sa ligne sélectionnée exactement dans la couleur de fond sur laquelle elle repose. La sélection aurait été invisible dans le thème que l'éditeur livre par défaut. | |
| 50 | + | |
| 51 | +D'où `tree.text`, `tree.directory`, `tree.selected` et `tree.unfocused`, et un test qui tient chaque thème livré à un contraste minimal entre la première et la troisième, de la même façon que les couleurs du curseur sont vérifiées. Un thème utilisateur qui n'en définit aucune retombe le long des points sur `default` : un arbre lisible, sans la distinction fichier/dossier, plutôt que rien du tout. | |
| 52 | + | |
| 53 | +## Liens avec le reste | |
| 54 | + | |
| 55 | +- Toutes les touches et toutes les règles, exactement : [Référence de l'arbre du projet](../reference/project-tree.md) | |
| 56 | +- L'utiliser : [Parcourir un projet et ouvrir des fichiers depuis un arbre](../how-to/browse-a-project.md) | |
| 57 | +- L'autre endroit où « le projet » est défini de la même façon : [Réglages de projet](project-settings.md) | |
| 58 | +- Où `filetree` se situe parmi les paquets : [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | +# Arbre du projet — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +`F9` ouvre une fenêtre listant les fichiers du projet, et `Entrée` sur l'un d'eux l'ouvre. Cette page traite des trois décisions contenues là-dedans : où l'arbre s'enracine, pourquoi c'est une fenêtre plutôt qu'un panneau sur le côté, et pourquoi il ne remarque pas tout seul l'apparition de fichiers. | ||
| 6 | + | ||
| 7 | +## Pourquoi la racine est le répertoire de travail | ||
| 8 | + | ||
| 9 | +L'éditeur contient déjà deux réponses différentes à « qu'est-ce que le projet ». | ||
| 10 | + | ||
| 11 | +Le serveur de langage remonte depuis le fichier ouvert jusqu'à trouver un `pyproject.toml`, parce qu'un module a une frontière réelle — en être à l'intérieur est un fait à propos du code, et pylsp a besoin de ce dossier précis pour travailler. Le fichier de réglages, lui, ne remonte pas du tout : `.turbo-python/settings.toml` est cherché dans le répertoire de travail et nulle part ailleurs. | ||
| 12 | + | ||
| 13 | +L'arbre suit le fichier de réglages, et il vaut la peine de dire pourquoi l'*autre* règle était tentante. Remonter jusqu'au `pyproject.toml` ferait qu'ouvrir un fichier de n'importe où dans un projet montrerait tout le projet, ce que fait habituellement un explorateur. Mais cela signifie aussi que la racine de l'arbre dépend d'un fichier trois dossiers plus loin auquel vous n'avez peut-être pas pensé, et cela cesse d'être prévisible dès qu'un dépôt contient plus d'un module — un monorepo vous montrerait le module auquel appartient le fichier que vous avez ouvert par hasard. | ||
| 14 | + | ||
| 15 | +La règle retenue est celle qui tient en une phrase et qui est vraie partout dans l'éditeur : **le projet est le dossier depuis lequel vous avez lancé l'éditeur.** Elle coûte quelque chose, et ce coût est nommé dans le [guide](../how-to/browse-a-project.md) : lancez depuis un sous-dossier et vous obtenez l'arbre de ce sous-dossier. La réponse est de lancer depuis la racine du projet, là où vous feriez `go build` et `git` de toute façon. | ||
| 16 | + | ||
| 17 | +## Pourquoi `.git` est masqué et rien d'autre | ||
| 18 | + | ||
| 19 | +Le dialogue Open masque toute entrée commençant par un point. Recopier cela ici était la chose évidente, et aurait été faux. | ||
| 20 | + | ||
| 21 | +`.turbo-python/settings.toml` est un fichier que cet éditeur demande aux gens d'éditer — c'est la raison d'être de la coloration TOML. `.gitignore` et `.qlty/qlty.toml` sont eux aussi des fichiers du projet. Un arbre qui les cacherait rendrait la configuration de l'éditeur inaccessible depuis l'explorateur de fichiers de l'éditeur, ce qui est un endroit curieux où aboutir. | ||
| 22 | + | ||
| 23 | +`.git` diffère par nature et non par orthographe : rien à l'intérieur n'est fait pour être ouvert à la main, et il contient assez d'objets pour enterrer tout le reste dans la liste. Un seul nom, masqué pour une raison énonçable. Respecter aussi `.gitignore` a été envisagé et écarté pour l'instant : cela masquerait `bin/` et `release/`, ce qui serait réellement plus agréable, et cela coûte un moteur de motifs gitignore — négations, `**`, ancrage — qui est une fonctionnalité à part entière plutôt qu'un détail d'arbre. | ||
| 24 | + | ||
| 25 | +## Pourquoi une fenêtre, pas un panneau | ||
| 26 | + | ||
| 27 | +Tous les autres éditeurs mettent leur arbre de fichiers dans une bande fixe à gauche. C'était l'alternative, et elle a été écartée à cause de ce qu'elle aurait coûté au reste de l'éditeur. | ||
| 28 | + | ||
| 29 | +Un panneau ancré signifie que le bureau n'est plus un simple rectangle où vivent les fenêtres. `Desktop` aurait besoin d'une notion de bords réservés ; `Window.fitInto` et les modes de croissance devraient les respecter ; agrandir voudrait dire « tout le bureau sauf le panneau » ; la mise en mosaïque et en cascade devraient en tenir compte. C'est une modification des fondations de toute l'interface, pour un seul widget. | ||
| 30 | + | ||
| 31 | +En fenêtre ordinaire, l'arbre obtient tout gratuitement et se comporte comme le reste : `F6` l'atteint, `Alt-2` le remonte, `[x]` le ferme, `[■]` lui donne tout le bureau, **Window ▸ Tile** le met à côté de votre fichier. Rien dans `ui` n'a eu à changer. Si un panneau ancré est voulu plus tard, c'est une fonctionnalité de `ui` à concevoir pour elle-même, plutôt qu'à faire passer en douce avec un explorateur de fichiers. | ||
| 32 | + | ||
| 33 | +## Pourquoi il n'y en a qu'un | ||
| 34 | + | ||
| 35 | +Deux arbres sur le même projet seraient deux vues d'une même chose sans rien pour les distinguer, et le projet ne peut pas changer pendant que l'éditeur tourne — la racine est fixée au démarrage. `F9` sur un arbre ouvert le remonte donc au lieu d'en créer un autre, exactement comme ouvrir un fichier déjà ouvert remonte sa fenêtre. | ||
| 36 | + | ||
| 37 | +## Pourquoi il ne surveille pas le disque | ||
| 38 | + | ||
| 39 | +Un arbre qui remarquerait `go build` produisant `bin/` serait meilleur. Le faire correctement signifie surveiller le système de fichiers, et en Go cela signifie `fsnotify` — une troisième dépendance, contre un projet qui s'en tient à deux depuis le début et qui traite l'ajout d'une dépendance comme une décision à défendre. | ||
| 40 | + | ||
| 41 | +Ce n'est pas non plus une petite dépendance en comportement : surveillances récursives, descripteurs épuisés sur les grosses arborescences, et une sémantique différente sur chaque plateforme — pour une fonctionnalité dont le mode d'échec est une ligne périmée dans une liste. | ||
| 42 | + | ||
| 43 | +L'arbre relit donc à la demande, et l'éditeur choisit les moments dont il peut être sûr. Enregistrer un fichier en est un : c'est l'éditeur qui l'a fait, il le sait donc. `F5` et `Ctrl-R` sont l'autre, parce qu'une compilation dans une fenêtre terminal est quelque chose que seul l'utilisateur sait terminée. Le rafraîchissement conserve la forme de l'arbre et ne relit que les dossiers réellement ouverts : il coûte ce qui est à l'écran, pas un parcours du projet. | ||
| 44 | + | ||
| 45 | +## Pourquoi l'arbre a ses propres clés de thème | ||
| 46 | + | ||
| 47 | +L'économie évidente était de le dessiner avec les clés `list.*` — un arbre est une liste, après tout, et cela n'aurait ajouté aucune clé que les thèmes utilisateur puissent manquer. | ||
| 48 | + | ||
| 49 | +Cela ne marche pas, et la raison mérite d'être consignée. `list.selected` est colorée pour ressortir sur un **dialogue**. Dans `turbo-classic` c'est blanc sur navy, et `window.body` est silver sur **navy** — un arbre dans une fenêtre aurait surligné sa ligne sélectionnée exactement dans la couleur de fond sur laquelle elle repose. La sélection aurait été invisible dans le thème que l'éditeur livre par défaut. | ||
| 50 | + | ||
| 51 | +D'où `tree.text`, `tree.directory`, `tree.selected` et `tree.unfocused`, et un test qui tient chaque thème livré à un contraste minimal entre la première et la troisième, de la même façon que les couleurs du curseur sont vérifiées. Un thème utilisateur qui n'en définit aucune retombe le long des points sur `default` : un arbre lisible, sans la distinction fichier/dossier, plutôt que rien du tout. | ||
| 52 | + | ||
| 53 | +## Liens avec le reste | ||
| 54 | + | ||
| 55 | +- Toutes les touches et toutes les règles, exactement : [Référence de l'arbre du projet](../reference/project-tree.md) | ||
| 56 | +- L'utiliser : [Parcourir un projet et ouvrir des fichiers depuis un arbre](../how-to/browse-a-project.md) | ||
| 57 | +- L'autre endroit où « le projet » est défini de la même façon : [Réglages de projet](project-settings.md) | ||
| 58 | +- Où `filetree` se situe parmi les paquets : [Architecture](architecture.md) | ||
added
docs/fr/explanation/python-tools.md +117 -0 | new file mode 100644 | ||
| @@ -0,0 +1,117 @@ | ||
| 1 | +# Outils Python — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Un menu **Python** dont les commandes viennent d'un fichier TOML, chacune lancée dans une fenêtre terminal, et les fichiers ouverts relus ensuite. Cette page explique pourquoi chacun de ces trois points est ce qu'il est. | |
| 6 | + | |
| 7 | +## Pourquoi la sortie a trois destinations, et une popup par défaut | |
| 8 | + | |
| 9 | +La première version mettait chaque commande dans une fenêtre terminal, et c'était le mauvais défaut pour cinq des six. | |
| 10 | + | |
| 11 | +Un terminal est la bonne réponse quand le programme est *interactif ou long* : `uv run` sur quelque chose qui lit l'entrée standard doit pouvoir recevoir une réponse, et une compilation qui s'avère durer une minute doit pouvoir être interrompue par `Ctrl-C`. Ni l'un ni l'autre n'est vrai de `uv run ruff check .`, qui affiche quatre lignes et s'arrête. Lui donner une fenêtre entière — qu'il faut ensuite fermer, sur un bureau où les fenêtres se recouvrent et sont numérotées — est plus de cérémonie que le résultat n'en mérite. | |
| 12 | + | |
| 13 | +Une popup est la bonne réponse pour une commande qu'on lance, qu'on lit et qu'on referme. Elle est modale, ce qui est un coût réel et nommé dans le [guide](../how-to/run-uv-commands.md) : un `go build` qu'on n'attendait pas lent immobilise l'éditeur jusqu'à sa fin ou jusqu'à `Échap`. Ce coût a été accepté exprès, parce que l'alternative — un dialogue surgissant trois secondes plus tard — avale ce qu'on était en train de taper à cet instant. | |
| 14 | + | |
| 15 | +La popup s'ouvre donc **immédiatement et se remplit**. On voit la progression, rien ne surprend, et `Échap` la ferme et arrête la commande — le seul moyen d'interrompre quelque chose dont la sortie n'est pas dans un terminal. | |
| 16 | + | |
| 17 | +Une fenêtre d'édition est la bonne réponse pour une sortie qu'on va éplucher : un long `go test -v`, un rapport de couverture. C'est un buffer ordinaire, donc `Ctrl-F` y cherche et `Save as` le conserve. Elle est remplie à la fin de la commande plutôt qu'au fil de l'eau, parce qu'un buffer qui grandit sous le curseur pendant qu'on y cherche est l'inverse de ce que ce mode vise. | |
| 18 | + | |
| 19 | +Aucune des trois ne convient à tout, et c'est pourquoi `output` est dans le fichier et non dans le code. `Run` en est l'exemple travaillé : c'est la seule commande du fichier de départ qui dit `terminal`, et le commentaire à côté dit pourquoi. | |
| 20 | + | |
| 21 | +## Pourquoi la fenêtre terminal reste | |
| 22 | + | |
| 23 | +L'éditeur en avait déjà une — un vrai pseudo-terminal avec émulateur VT, construit pour les fenêtres `F8` — donc `output = "terminal"` coûte un champ dans ses options et offre gratuitement les couleurs, la pagination, `Ctrl-C`, l'entrée clavier et l'historique, parce que ce sont les mêmes mécanismes que ceux de tous les autres terminaux. | |
| 24 | + | |
| 25 | +La fenêtre reste après la fin de la commande, et c'est le but : la sortie est ce qu'on a demandé, et une fenêtre qui disparaîtrait avec elle serait inutile. | |
| 26 | + | |
| 27 | +Cela a demandé un correctif à part. Une vue terminal consommait toute touche qu'on lui donnait et l'écrivait au shell ; une fois le shell parti, l'écriture échouait en silence et la touche était consommée quand même — `Ctrl-W` ne pouvait donc jamais fermer une fenêtre terminée, et la souris était la seule issue. Une vue terminée ne prend plus que les touches de défilement et laisse passer le reste vers l'éditeur. | |
| 28 | + | |
| 29 | +## Pourquoi le code de sortie est toujours dans le titre | |
| 30 | + | |
| 31 | +`uv sync` qui réussit n'affiche rien du tout. Une popup au corps vide et au titre neutre est indistinguable d'une popup dont la commande n'a pas démarré, et le lecteur en est réduit à deviner la seule chose qu'il voulait savoir. | |
| 32 | + | |
| 33 | +Le titre porte donc le verdict — `— ok` ou `— exit 1` — et un corps vide affiche `(no output)` une fois la commande terminée. Pendant qu'elle tourne, le corps reste vide : « (no output) » est un verdict, et une commande en cours n'y est pas parvenue. | |
| 34 | + | |
| 35 | +## Pourquoi les commandes sont dans un fichier | |
| 36 | + | |
| 37 | +Six commandes codées en dur auraient répondu à la demande. Elles auraient aussi été fausses en une semaine. | |
| 38 | + | |
| 39 | +Toutes les commandes du fichier de départ passent par `uv`, qui crée l'environnement, résout les dépendances et lance les outils dedans — aucune n'exige donc qu'un environnement ait été activé au préalable. C'est un défaut défendable, ce n'est la réponse universelle de personne. Un projet sous Poetry veut `poetry run`. Un projet sous pip avec un `.venv` fait à la main veut la commande nue, l'environnement déjà sur le PATH. Un projet qui a standardisé sur `black` et `flake8` veut ceux-là plutôt que `ruff`. `uv run pytest` suppose pytest ; un projet sous `unittest` veut `python -m unittest`. Un projet avec un `Makefile` veut `make check`. Rien de cela n'est connaissable d'ici, et tout cela fait une ligne dans un fichier. | |
| 40 | + | |
| 41 | +Les six sont donc des **défauts, pas du code** : c'est le contenu du fichier de départ qu'écrit **Python ▸ Create tools file**, et en changer une consiste à éditer un fichier plutôt qu'à recompiler un éditeur. Le fichier est relu à chaque ouverture du menu, pour la même raison que le menu Snippets : une modification doit prendre effet aussitôt, et le fichier est souvent ouvert dans la fenêtre derrière le menu. | |
| 42 | + | |
| 43 | +Les commandes passent par `sh -c` — `cmd.exe /S /C` sous Windows — plutôt que d'être découpées en argv ici. Le fichier est celui de l'utilisateur, donc les tubes, les globs et `&&` sont des fonctionnalités plutôt que des dangers, et une entrée peut être `uv run ruff format . && uv run ruff check . && uv run pytest`. Découper un argv supposerait d'inventer des règles de citation pour une chaîne écrite à la main. | |
| 44 | + | |
| 45 | +## Pourquoi il n'y a pas de fichier d'outils utilisateur | |
| 46 | + | |
| 47 | +Les snippets sont lus depuis deux fichiers — le vôtre et celui du projet — parce que vos snippets sont vos habitudes et doivent vous suivre. | |
| 48 | + | |
| 49 | +Les outils ne sont pas ainsi. Ils appartiennent à la chaîne d'outils propre à un projet : un fichier d'outils global proposerait `uv run pytest` dans un dépôt qui n'a jamais entendu parler d'uv, et un projet épinglé sur Poetry hériterait des habitudes de quelqu'un d'autre dans son menu. Le fichier est par projet, et c'est toute la règle. | |
| 50 | + | |
| 51 | +## Pourquoi un outil peut nommer son propre menu | |
| 52 | + | |
| 53 | +Un menu nommé **Python** contenant `docker compose up` ment sur ce qu'il est. Le premier fichier d'outils que l'on écrit déborde de Python, parce que les commandes d'un projet ne parlent pas toutes du langage dans lequel il est écrit : conteneurs, bases de données, déploiements, une cible de `Makefile` ajoutée en 2019. | |
| 54 | + | |
| 55 | +Deux formes ont été envisagées. Un **second menu fixe** nommé Tools — tout ce qui est Python dans Python, le reste dans Tools — c'est une clé de plus dans le format et aucun problème de nommage, mais cela ne fait que déplacer le mensonge : un menu Tools contenant `docker compose up`, `psql` et un script de déploiement est tout aussi indifférencié, et dès qu'il y a dix entrées personne n'en retrouve une. Et un **second fichier**, `menus.toml`, garde le fichier d'outils simple au prix de deux fichiers qui doivent s'accorder sur les outils qui existent. | |
| 56 | + | |
| 57 | +Le menu est donc un **nom libre porté par l'outil**, dans l'unique fichier : `menu = "Docker"`. Un nom que rien d'autre n'emploie crée le menu ; omettre la clé signifie Python. Il n'y a pas de liste de noms autorisés, parce qu'une liste serait la liste des projets de quelqu'un d'autre. | |
| 58 | + | |
| 59 | +Python reste fixe sur la barre plutôt que de devenir un nom parmi d'autres venu du fichier. **Python ▸ Create tools file** doit être atteignable dans un projet qui n'a aucun fichier d'outils — c'est précisément le projet qui en a besoin — et un menu qui n'existe qu'une fois le fichier créé ne peut pas proposer de créer le fichier. | |
| 60 | + | |
| 61 | +## Pourquoi la touche d'accès n'appartient pas au fichier | |
| 62 | + | |
| 63 | +L'auteur d'un fichier d'outils ne peut pas savoir quelles lettres sont libres. Il voit `File`, `Edit`, `Search`, `Run`, `Options`, `Window`, `Snippets`, `Python` et `Help` sur la barre, mais seulement en comptant les soulignements, et un projet partagé à plusieurs dépendrait alors du fait que personne n'ajoute un menu qui entre en collision. | |
| 64 | + | |
| 65 | +Les collisions sont ici **silencieuses**, et c'est ce qui vaut qu'on se prémunisse contre elles. La barre répond au premier menu dont la touche correspond ; un second menu revendiquant la même lettre n'est pas une erreur et se dessine normalement — il ne s'ouvre simplement jamais. Le piège s'est déjà refermé une fois dans cet éditeur : `Snippets` et `Search` voulaient tous deux le `S`, `Snippets` était celui qu'on ne pouvait pas ouvrir, et tous les tests passaient. Le correctif d'alors fut de déplacer Snippets sur `N` à la main. Laisser un fichier nommer des menus en ferait un danger permanent plutôt qu'une erreur isolée, donc l'attribution revient à l'éditeur : la première lettre du nom que rien d'autre ne revendique. | |
| 66 | + | |
| 67 | +Les tildes écrits dans le nom sont honorés **quand la lettre est libre**, et écartés sans bruit sinon. Refuser le fichier était l'alternative, et elle est pire : la collision dépend des menus qui existent, donc un fichier d'outils qui marchait cesserait de marcher le jour où une version de l'éditeur ajoute un menu. Entre un menu sur une lettre que vous n'avez pas demandée et un menu que vous ne pouvez pas ouvrir, la première est la moindre perte. | |
| 68 | + | |
| 69 | +Quand toutes les lettres d'un nom sont prises, le menu n'a pas de touche d'accès du tout. `F10`, les flèches et la souris l'atteignent encore, et l'alternative — aller chercher une lettre qui n'est pas dans le nom — mettrait un soulignement sous rien. | |
| 70 | + | |
| 71 | +## Pourquoi la barre est reconstruite depuis un stat | |
| 72 | + | |
| 73 | +`Menu.OnOpen` remplit les entrées d'un menu juste avant qu'il ne se déroule, et c'est ainsi que les menus Python et Snippets suivent leurs fichiers sans redémarrage. Cela ne suffit pas ici : l'*ensemble* des menus appartient à la barre et non à un menu, et ajouter `menu = "Docker"` au fichier doit poser Docker sur la barre. | |
| 74 | + | |
| 75 | +Lire et analyser le fichier à chaque tour de la boucle d'événements y parviendrait, et ferait aussi ce travail pour rien à chaque frappe dans un fichier que personne n'a modifié. La barre porte donc la taille et la date de modification du fichier d'outils dont elle est issue, et un `stat` par tour décide s'il faut reconstruire. Modifier le fichier dans la fenêtre devant soi, l'enregistrer et voir la barre changer, c'est le cas visé. | |
| 76 | + | |
| 77 | +## Pourquoi les fichiers ouverts sont relus, et seulement certains | |
| 78 | + | |
| 79 | +`Format` réécrit les fichiers sur le disque — y compris celui qu'on regarde. Sans rien de plus, l'éditeur resterait assis sur une copie périmée, et le `F2` suivant réécrirait votre version non formatée par-dessus le travail de `ruff format`. Ce n'est pas une aspérité : c'est la fonctionnalité qui se défait toute seule, en silence. | |
| 80 | + | |
| 81 | +À la fin d'une commande, l'éditeur relit donc chaque fichier ouvert. La partie intéressante est ceux qu'il refuse de toucher. | |
| 82 | + | |
| 83 | +**Un fichier ayant des modifications non enregistrées est laissé tel quel**, et la barre d'état dit combien ont été ignorés. Le recharger jetterait un travail que l'utilisateur n'a pas enregistré, ce qu'aucune commodité ne justifie. Et le conflit est réel : le formateur et la modification non enregistrée ne sont pas d'accord sur ce que le fichier doit dire, et l'éditeur n'est pas en position de trancher. Le nommer et s'arrêter est l'issue honnête — l'utilisateur peut enregistrer et relancer, ou continuer à éditer et formater plus tard. | |
| 84 | + | |
| 85 | +Deux décisions plus petites à l'intérieur : | |
| 86 | + | |
| 87 | +- **Le curseur reste où il était**, borné à ce que le fichier contient désormais. Un formateur déplace les lignes ; remettre le curseur en haut ferait perdre sa place au lecteur pour rien. | |
| 88 | +- **L'historique d'annulation est jeté.** Annuler au-delà d'un rechargement restaurerait un texte que le fichier n'a plus, ce qui est pire que de ne pas pouvoir annuler. | |
| 89 | + | |
| 90 | +## Pourquoi le rechargement a lieu sur la boucle d'événements | |
| 91 | + | |
| 92 | +La fin de la commande est remarquée par la goroutine qui lit le terminal, laquelle ne peut toucher ni un buffer ni le bureau. Elle positionne donc un drapeau, et le rechargement se fait en tête du tour suivant de la boucle. | |
| 93 | + | |
| 94 | +C'est la quatrième chose construite ainsi dans cet éditeur — l'annonce au serveur de langage, les redessins de terminal, l'échéance d'autosave, et maintenant ceci. La règle qu'elles partagent mérite d'être énoncée une fois de plus : **le réveil peut être perdu, l'état ne doit pas l'être.** `PostEvent` jette ce qui ne tient pas dans sa file, donc tout ce qui dépend de l'arrivée d'un message est un bug qui attend un moment de charge. Un drapeau que la boucle vérifie elle-même ne peut pas disparaître. | |
| 95 | + | |
| 96 | +## Pourquoi une commande peut demander une valeur, et pourquoi en doubles accolades | |
| 97 | + | |
| 98 | +`uv venv` a besoin d'un répertoire. `uv run` a besoin d'un script. `uv add` a besoin d'un nom de paquet, et `pytest -k` d'un motif. Aucun de ces éléments ne peut vivre dans le fichier d'outils sous forme de chaîne figée, parce que la réponse change à chaque fois — et un outil qui ne peut pas demander est un outil qu'il faut éditer avant chaque usage, ce qui n'est pas un outil. | |
| 99 | + | |
| 100 | +Un `{{libellé}}` dans une commande est donc une valeur que l'éditeur demande d'abord, dans une boîte portant le nom de l'outil. | |
| 101 | + | |
| 102 | +**Une seule accolade était l'écriture évidente, et elle est fausse.** `awk '{print $1}'` et `find . -exec rm {} +` sont des choses ordinaires à mettre dans un fichier d'outils, et lire la première comme un libellé transforme une commande qui marche en une boîte demandant « print $1 ». Les doubles accolades n'entrent en collision presque avec rien, et la seule construction avec laquelle elles le font — un bloc imbriqué en awk — est assez rare pour être signalée plutôt que contournée par la conception. | |
| 103 | + | |
| 104 | +**La valeur est protégée par défaut**, parce que l'inverse échoue en silence. Un chemin contenant une espace, substitué tel quel, devient deux arguments et la commande parle d'un fichier qui n'existe pas. La protection fait marcher ce cas et rend l'autre — « ajoute ces trois options à la fin » — impossible ; c'est pourquoi un `...` dans les accolades demande la valeur telle quelle. Deux comportements, tous deux documentés, plutôt qu'un seul faux une fois sur deux. | |
| 105 | + | |
| 106 | +**Rien n'est retenu sur le disque.** La boîte repart de ce qui avait été tapé, pour la session. L'écrire dans le répertoire propre au projet a été envisagé puis rejeté : ce répertoire contient ce que le projet a décidé, et un filtre tapé en poursuivant un test n'en fait pas partie. Ce serait aussi la première chose qui y changerait sans que personne ne modifie un fichier. | |
| 107 | + | |
| 108 | +**Un fichier illisible est refusé à la lecture**, pas au moment où l'outil est choisi. Un `{{` non fermé atteignant le shell donne une commande qui échoue avec des accolades dedans, ce qui ne nomme ni l'outil ni le fichier ; refuser au chargement nomme les deux. C'est la règle que suit déjà une valeur d'`output` inconnue. | |
| 109 | + | |
| 110 | +**La boîte est refusée quand elle ne tient pas.** Un outil demandant plus de valeurs que le terminal n'a de lignes donnerait une boîte dont le bouton OK est sous le bas de l'écran — à laquelle on ne peut répondre que par Échap, qui annule. Dire « celui-ci demande douze valeurs et neuf tiennent » n'est pire que rien que si l'on préfère l'apprendre en essayant. | |
| 111 | + | |
| 112 | +## Liens avec le reste | |
| 113 | + | |
| 114 | +- Toutes les clés du fichier et toutes les règles : [Référence des outils go](../reference/python-tools.md) | |
| 115 | +- L'utiliser : [Lancer les commandes uv depuis l'éditeur](../how-to/run-uv-commands.md) | |
| 116 | +- Les fenêtres qu'emploie `output = "terminal"`, et pourquoi ce sont de vrais terminaux : [Fenêtres terminal](terminal-windows.md) | |
| 117 | +- L'autre menu construit depuis un fichier : [Snippets](snippets.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,117 @@ | |||
| 1 | +# Outils Python — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Un menu **Python** dont les commandes viennent d'un fichier TOML, chacune lancée dans une fenêtre terminal, et les fichiers ouverts relus ensuite. Cette page explique pourquoi chacun de ces trois points est ce qu'il est. | ||
| 6 | + | ||
| 7 | +## Pourquoi la sortie a trois destinations, et une popup par défaut | ||
| 8 | + | ||
| 9 | +La première version mettait chaque commande dans une fenêtre terminal, et c'était le mauvais défaut pour cinq des six. | ||
| 10 | + | ||
| 11 | +Un terminal est la bonne réponse quand le programme est *interactif ou long* : `uv run` sur quelque chose qui lit l'entrée standard doit pouvoir recevoir une réponse, et une compilation qui s'avère durer une minute doit pouvoir être interrompue par `Ctrl-C`. Ni l'un ni l'autre n'est vrai de `uv run ruff check .`, qui affiche quatre lignes et s'arrête. Lui donner une fenêtre entière — qu'il faut ensuite fermer, sur un bureau où les fenêtres se recouvrent et sont numérotées — est plus de cérémonie que le résultat n'en mérite. | ||
| 12 | + | ||
| 13 | +Une popup est la bonne réponse pour une commande qu'on lance, qu'on lit et qu'on referme. Elle est modale, ce qui est un coût réel et nommé dans le [guide](../how-to/run-uv-commands.md) : un `go build` qu'on n'attendait pas lent immobilise l'éditeur jusqu'à sa fin ou jusqu'à `Échap`. Ce coût a été accepté exprès, parce que l'alternative — un dialogue surgissant trois secondes plus tard — avale ce qu'on était en train de taper à cet instant. | ||
| 14 | + | ||
| 15 | +La popup s'ouvre donc **immédiatement et se remplit**. On voit la progression, rien ne surprend, et `Échap` la ferme et arrête la commande — le seul moyen d'interrompre quelque chose dont la sortie n'est pas dans un terminal. | ||
| 16 | + | ||
| 17 | +Une fenêtre d'édition est la bonne réponse pour une sortie qu'on va éplucher : un long `go test -v`, un rapport de couverture. C'est un buffer ordinaire, donc `Ctrl-F` y cherche et `Save as` le conserve. Elle est remplie à la fin de la commande plutôt qu'au fil de l'eau, parce qu'un buffer qui grandit sous le curseur pendant qu'on y cherche est l'inverse de ce que ce mode vise. | ||
| 18 | + | ||
| 19 | +Aucune des trois ne convient à tout, et c'est pourquoi `output` est dans le fichier et non dans le code. `Run` en est l'exemple travaillé : c'est la seule commande du fichier de départ qui dit `terminal`, et le commentaire à côté dit pourquoi. | ||
| 20 | + | ||
| 21 | +## Pourquoi la fenêtre terminal reste | ||
| 22 | + | ||
| 23 | +L'éditeur en avait déjà une — un vrai pseudo-terminal avec émulateur VT, construit pour les fenêtres `F8` — donc `output = "terminal"` coûte un champ dans ses options et offre gratuitement les couleurs, la pagination, `Ctrl-C`, l'entrée clavier et l'historique, parce que ce sont les mêmes mécanismes que ceux de tous les autres terminaux. | ||
| 24 | + | ||
| 25 | +La fenêtre reste après la fin de la commande, et c'est le but : la sortie est ce qu'on a demandé, et une fenêtre qui disparaîtrait avec elle serait inutile. | ||
| 26 | + | ||
| 27 | +Cela a demandé un correctif à part. Une vue terminal consommait toute touche qu'on lui donnait et l'écrivait au shell ; une fois le shell parti, l'écriture échouait en silence et la touche était consommée quand même — `Ctrl-W` ne pouvait donc jamais fermer une fenêtre terminée, et la souris était la seule issue. Une vue terminée ne prend plus que les touches de défilement et laisse passer le reste vers l'éditeur. | ||
| 28 | + | ||
| 29 | +## Pourquoi le code de sortie est toujours dans le titre | ||
| 30 | + | ||
| 31 | +`uv sync` qui réussit n'affiche rien du tout. Une popup au corps vide et au titre neutre est indistinguable d'une popup dont la commande n'a pas démarré, et le lecteur en est réduit à deviner la seule chose qu'il voulait savoir. | ||
| 32 | + | ||
| 33 | +Le titre porte donc le verdict — `— ok` ou `— exit 1` — et un corps vide affiche `(no output)` une fois la commande terminée. Pendant qu'elle tourne, le corps reste vide : « (no output) » est un verdict, et une commande en cours n'y est pas parvenue. | ||
| 34 | + | ||
| 35 | +## Pourquoi les commandes sont dans un fichier | ||
| 36 | + | ||
| 37 | +Six commandes codées en dur auraient répondu à la demande. Elles auraient aussi été fausses en une semaine. | ||
| 38 | + | ||
| 39 | +Toutes les commandes du fichier de départ passent par `uv`, qui crée l'environnement, résout les dépendances et lance les outils dedans — aucune n'exige donc qu'un environnement ait été activé au préalable. C'est un défaut défendable, ce n'est la réponse universelle de personne. Un projet sous Poetry veut `poetry run`. Un projet sous pip avec un `.venv` fait à la main veut la commande nue, l'environnement déjà sur le PATH. Un projet qui a standardisé sur `black` et `flake8` veut ceux-là plutôt que `ruff`. `uv run pytest` suppose pytest ; un projet sous `unittest` veut `python -m unittest`. Un projet avec un `Makefile` veut `make check`. Rien de cela n'est connaissable d'ici, et tout cela fait une ligne dans un fichier. | ||
| 40 | + | ||
| 41 | +Les six sont donc des **défauts, pas du code** : c'est le contenu du fichier de départ qu'écrit **Python ▸ Create tools file**, et en changer une consiste à éditer un fichier plutôt qu'à recompiler un éditeur. Le fichier est relu à chaque ouverture du menu, pour la même raison que le menu Snippets : une modification doit prendre effet aussitôt, et le fichier est souvent ouvert dans la fenêtre derrière le menu. | ||
| 42 | + | ||
| 43 | +Les commandes passent par `sh -c` — `cmd.exe /S /C` sous Windows — plutôt que d'être découpées en argv ici. Le fichier est celui de l'utilisateur, donc les tubes, les globs et `&&` sont des fonctionnalités plutôt que des dangers, et une entrée peut être `uv run ruff format . && uv run ruff check . && uv run pytest`. Découper un argv supposerait d'inventer des règles de citation pour une chaîne écrite à la main. | ||
| 44 | + | ||
| 45 | +## Pourquoi il n'y a pas de fichier d'outils utilisateur | ||
| 46 | + | ||
| 47 | +Les snippets sont lus depuis deux fichiers — le vôtre et celui du projet — parce que vos snippets sont vos habitudes et doivent vous suivre. | ||
| 48 | + | ||
| 49 | +Les outils ne sont pas ainsi. Ils appartiennent à la chaîne d'outils propre à un projet : un fichier d'outils global proposerait `uv run pytest` dans un dépôt qui n'a jamais entendu parler d'uv, et un projet épinglé sur Poetry hériterait des habitudes de quelqu'un d'autre dans son menu. Le fichier est par projet, et c'est toute la règle. | ||
| 50 | + | ||
| 51 | +## Pourquoi un outil peut nommer son propre menu | ||
| 52 | + | ||
| 53 | +Un menu nommé **Python** contenant `docker compose up` ment sur ce qu'il est. Le premier fichier d'outils que l'on écrit déborde de Python, parce que les commandes d'un projet ne parlent pas toutes du langage dans lequel il est écrit : conteneurs, bases de données, déploiements, une cible de `Makefile` ajoutée en 2019. | ||
| 54 | + | ||
| 55 | +Deux formes ont été envisagées. Un **second menu fixe** nommé Tools — tout ce qui est Python dans Python, le reste dans Tools — c'est une clé de plus dans le format et aucun problème de nommage, mais cela ne fait que déplacer le mensonge : un menu Tools contenant `docker compose up`, `psql` et un script de déploiement est tout aussi indifférencié, et dès qu'il y a dix entrées personne n'en retrouve une. Et un **second fichier**, `menus.toml`, garde le fichier d'outils simple au prix de deux fichiers qui doivent s'accorder sur les outils qui existent. | ||
| 56 | + | ||
| 57 | +Le menu est donc un **nom libre porté par l'outil**, dans l'unique fichier : `menu = "Docker"`. Un nom que rien d'autre n'emploie crée le menu ; omettre la clé signifie Python. Il n'y a pas de liste de noms autorisés, parce qu'une liste serait la liste des projets de quelqu'un d'autre. | ||
| 58 | + | ||
| 59 | +Python reste fixe sur la barre plutôt que de devenir un nom parmi d'autres venu du fichier. **Python ▸ Create tools file** doit être atteignable dans un projet qui n'a aucun fichier d'outils — c'est précisément le projet qui en a besoin — et un menu qui n'existe qu'une fois le fichier créé ne peut pas proposer de créer le fichier. | ||
| 60 | + | ||
| 61 | +## Pourquoi la touche d'accès n'appartient pas au fichier | ||
| 62 | + | ||
| 63 | +L'auteur d'un fichier d'outils ne peut pas savoir quelles lettres sont libres. Il voit `File`, `Edit`, `Search`, `Run`, `Options`, `Window`, `Snippets`, `Python` et `Help` sur la barre, mais seulement en comptant les soulignements, et un projet partagé à plusieurs dépendrait alors du fait que personne n'ajoute un menu qui entre en collision. | ||
| 64 | + | ||
| 65 | +Les collisions sont ici **silencieuses**, et c'est ce qui vaut qu'on se prémunisse contre elles. La barre répond au premier menu dont la touche correspond ; un second menu revendiquant la même lettre n'est pas une erreur et se dessine normalement — il ne s'ouvre simplement jamais. Le piège s'est déjà refermé une fois dans cet éditeur : `Snippets` et `Search` voulaient tous deux le `S`, `Snippets` était celui qu'on ne pouvait pas ouvrir, et tous les tests passaient. Le correctif d'alors fut de déplacer Snippets sur `N` à la main. Laisser un fichier nommer des menus en ferait un danger permanent plutôt qu'une erreur isolée, donc l'attribution revient à l'éditeur : la première lettre du nom que rien d'autre ne revendique. | ||
| 66 | + | ||
| 67 | +Les tildes écrits dans le nom sont honorés **quand la lettre est libre**, et écartés sans bruit sinon. Refuser le fichier était l'alternative, et elle est pire : la collision dépend des menus qui existent, donc un fichier d'outils qui marchait cesserait de marcher le jour où une version de l'éditeur ajoute un menu. Entre un menu sur une lettre que vous n'avez pas demandée et un menu que vous ne pouvez pas ouvrir, la première est la moindre perte. | ||
| 68 | + | ||
| 69 | +Quand toutes les lettres d'un nom sont prises, le menu n'a pas de touche d'accès du tout. `F10`, les flèches et la souris l'atteignent encore, et l'alternative — aller chercher une lettre qui n'est pas dans le nom — mettrait un soulignement sous rien. | ||
| 70 | + | ||
| 71 | +## Pourquoi la barre est reconstruite depuis un stat | ||
| 72 | + | ||
| 73 | +`Menu.OnOpen` remplit les entrées d'un menu juste avant qu'il ne se déroule, et c'est ainsi que les menus Python et Snippets suivent leurs fichiers sans redémarrage. Cela ne suffit pas ici : l'*ensemble* des menus appartient à la barre et non à un menu, et ajouter `menu = "Docker"` au fichier doit poser Docker sur la barre. | ||
| 74 | + | ||
| 75 | +Lire et analyser le fichier à chaque tour de la boucle d'événements y parviendrait, et ferait aussi ce travail pour rien à chaque frappe dans un fichier que personne n'a modifié. La barre porte donc la taille et la date de modification du fichier d'outils dont elle est issue, et un `stat` par tour décide s'il faut reconstruire. Modifier le fichier dans la fenêtre devant soi, l'enregistrer et voir la barre changer, c'est le cas visé. | ||
| 76 | + | ||
| 77 | +## Pourquoi les fichiers ouverts sont relus, et seulement certains | ||
| 78 | + | ||
| 79 | +`Format` réécrit les fichiers sur le disque — y compris celui qu'on regarde. Sans rien de plus, l'éditeur resterait assis sur une copie périmée, et le `F2` suivant réécrirait votre version non formatée par-dessus le travail de `ruff format`. Ce n'est pas une aspérité : c'est la fonctionnalité qui se défait toute seule, en silence. | ||
| 80 | + | ||
| 81 | +À la fin d'une commande, l'éditeur relit donc chaque fichier ouvert. La partie intéressante est ceux qu'il refuse de toucher. | ||
| 82 | + | ||
| 83 | +**Un fichier ayant des modifications non enregistrées est laissé tel quel**, et la barre d'état dit combien ont été ignorés. Le recharger jetterait un travail que l'utilisateur n'a pas enregistré, ce qu'aucune commodité ne justifie. Et le conflit est réel : le formateur et la modification non enregistrée ne sont pas d'accord sur ce que le fichier doit dire, et l'éditeur n'est pas en position de trancher. Le nommer et s'arrêter est l'issue honnête — l'utilisateur peut enregistrer et relancer, ou continuer à éditer et formater plus tard. | ||
| 84 | + | ||
| 85 | +Deux décisions plus petites à l'intérieur : | ||
| 86 | + | ||
| 87 | +- **Le curseur reste où il était**, borné à ce que le fichier contient désormais. Un formateur déplace les lignes ; remettre le curseur en haut ferait perdre sa place au lecteur pour rien. | ||
| 88 | +- **L'historique d'annulation est jeté.** Annuler au-delà d'un rechargement restaurerait un texte que le fichier n'a plus, ce qui est pire que de ne pas pouvoir annuler. | ||
| 89 | + | ||
| 90 | +## Pourquoi le rechargement a lieu sur la boucle d'événements | ||
| 91 | + | ||
| 92 | +La fin de la commande est remarquée par la goroutine qui lit le terminal, laquelle ne peut toucher ni un buffer ni le bureau. Elle positionne donc un drapeau, et le rechargement se fait en tête du tour suivant de la boucle. | ||
| 93 | + | ||
| 94 | +C'est la quatrième chose construite ainsi dans cet éditeur — l'annonce au serveur de langage, les redessins de terminal, l'échéance d'autosave, et maintenant ceci. La règle qu'elles partagent mérite d'être énoncée une fois de plus : **le réveil peut être perdu, l'état ne doit pas l'être.** `PostEvent` jette ce qui ne tient pas dans sa file, donc tout ce qui dépend de l'arrivée d'un message est un bug qui attend un moment de charge. Un drapeau que la boucle vérifie elle-même ne peut pas disparaître. | ||
| 95 | + | ||
| 96 | +## Pourquoi une commande peut demander une valeur, et pourquoi en doubles accolades | ||
| 97 | + | ||
| 98 | +`uv venv` a besoin d'un répertoire. `uv run` a besoin d'un script. `uv add` a besoin d'un nom de paquet, et `pytest -k` d'un motif. Aucun de ces éléments ne peut vivre dans le fichier d'outils sous forme de chaîne figée, parce que la réponse change à chaque fois — et un outil qui ne peut pas demander est un outil qu'il faut éditer avant chaque usage, ce qui n'est pas un outil. | ||
| 99 | + | ||
| 100 | +Un `{{libellé}}` dans une commande est donc une valeur que l'éditeur demande d'abord, dans une boîte portant le nom de l'outil. | ||
| 101 | + | ||
| 102 | +**Une seule accolade était l'écriture évidente, et elle est fausse.** `awk '{print $1}'` et `find . -exec rm {} +` sont des choses ordinaires à mettre dans un fichier d'outils, et lire la première comme un libellé transforme une commande qui marche en une boîte demandant « print $1 ». Les doubles accolades n'entrent en collision presque avec rien, et la seule construction avec laquelle elles le font — un bloc imbriqué en awk — est assez rare pour être signalée plutôt que contournée par la conception. | ||
| 103 | + | ||
| 104 | +**La valeur est protégée par défaut**, parce que l'inverse échoue en silence. Un chemin contenant une espace, substitué tel quel, devient deux arguments et la commande parle d'un fichier qui n'existe pas. La protection fait marcher ce cas et rend l'autre — « ajoute ces trois options à la fin » — impossible ; c'est pourquoi un `...` dans les accolades demande la valeur telle quelle. Deux comportements, tous deux documentés, plutôt qu'un seul faux une fois sur deux. | ||
| 105 | + | ||
| 106 | +**Rien n'est retenu sur le disque.** La boîte repart de ce qui avait été tapé, pour la session. L'écrire dans le répertoire propre au projet a été envisagé puis rejeté : ce répertoire contient ce que le projet a décidé, et un filtre tapé en poursuivant un test n'en fait pas partie. Ce serait aussi la première chose qui y changerait sans que personne ne modifie un fichier. | ||
| 107 | + | ||
| 108 | +**Un fichier illisible est refusé à la lecture**, pas au moment où l'outil est choisi. Un `{{` non fermé atteignant le shell donne une commande qui échoue avec des accolades dedans, ce qui ne nomme ni l'outil ni le fichier ; refuser au chargement nomme les deux. C'est la règle que suit déjà une valeur d'`output` inconnue. | ||
| 109 | + | ||
| 110 | +**La boîte est refusée quand elle ne tient pas.** Un outil demandant plus de valeurs que le terminal n'a de lignes donnerait une boîte dont le bouton OK est sous le bas de l'écran — à laquelle on ne peut répondre que par Échap, qui annule. Dire « celui-ci demande douze valeurs et neuf tiennent » n'est pire que rien que si l'on préfère l'apprendre en essayant. | ||
| 111 | + | ||
| 112 | +## Liens avec le reste | ||
| 113 | + | ||
| 114 | +- Toutes les clés du fichier et toutes les règles : [Référence des outils go](../reference/python-tools.md) | ||
| 115 | +- L'utiliser : [Lancer les commandes uv depuis l'éditeur](../how-to/run-uv-commands.md) | ||
| 116 | +- Les fenêtres qu'emploie `output = "terminal"`, et pourquoi ce sont de vrais terminaux : [Fenêtres terminal](terminal-windows.md) | ||
| 117 | +- L'autre menu construit depuis un fichier : [Snippets](snippets.md) | ||
added
docs/fr/explanation/snippets.md +62 -0 | new file mode 100644 | ||
| @@ -0,0 +1,62 @@ | ||
| 1 | +# Snippets — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Un menu **Snippets** dont le contenu vient d'un fichier TOML, et un snippet choisi déposé dans le fichier que vous éditez. Cette page traite des trois décisions qui lui donnent sa forme : pourquoi le menu est reconstruit à chaque ouverture, pourquoi l'éditeur a gagné de vrais sous-menus pour lui, et pourquoi l'insertion réindente. | |
| 6 | + | |
| 7 | +## Pourquoi le menu est construit au moment où il s'ouvre | |
| 8 | + | |
| 9 | +Tous les autres menus de l'éditeur sont décidés une fois, dans `New()`. Celui-ci ne peut pas l'être, et pour deux raisons indépendantes. | |
| 10 | + | |
| 11 | +La première est le fichier. Les snippets vivent dans du TOML, et tout l'intérêt est que vous l'éditiez — souvent dans cet éditeur, dans la fenêtre que l'entrée **Create snippets file** vient d'ouvrir pour vous. Un menu construit au démarrage montrerait l'état du fichier au lancement, et il faudrait redémarrer pour voir un snippet qu'on vient d'écrire. C'est le genre de friction qui fait qu'une fonctionnalité n'est pas utilisée du tout. | |
| 12 | + | |
| 13 | +La seconde est la fenêtre au premier plan. Le menu est filtré par ce que vous éditez, donc il change quand vous appuyez sur `F6`. Il n'existe aucun instant du démarrage où la réponse existe. | |
| 14 | + | |
| 15 | +`ui.Menu` a donc gagné un champ `OnOpen` : une fonction que la barre appelle juste avant de dérouler un menu, laissant son propriétaire regarnir `Items` d'abord. C'est le même mécanisme de communication ascendante que partout ailleurs dans ce code — un champ fonction, pas une interface — et il s'exécute exactement au moment où le contenu va être vu, pas plus souvent. | |
| 16 | + | |
| 17 | +## Pourquoi l'éditeur a gagné des sous-menus | |
| 18 | + | |
| 19 | +`ui.MenuItem` ne savait pas imbriquer, et l'ajouter a été la plus grosse pièce de ce travail : un second panneau à placer et à dessiner, des flèches qui signifient « plus profond » et « ressortir », le pointeur qui ouvre une branche au survol et la referme en la quittant, et une fermeture qui range les deux panneaux d'un coup. | |
| 20 | + | |
| 21 | +L'alternative était un seul panneau plat avec les groupes en intitulés grisés entre des filets. Cela fonctionne, ne demande rien de neuf, et s'effondre sur le cas même pour lequel la fonctionnalité existe : un projet de trente snippets donne un menu plus haut que le terminal. Un regroupement qui étiquette sans replier ne résout pas le problème qu'il semble résoudre. | |
| 22 | + | |
| 23 | +C'est délibérément **un seul niveau**. Le format est des groupes contenant des snippets — exactement un niveau — et une profondeur générale supposerait de remplacer les deux indices de la barre par un chemin, dans le widget dont dépendent déjà tous les dialogues et tous les tests de menu. C'est du travail spéculatif sur la partie la plus porteuse de l'interface. | |
| 24 | + | |
| 25 | +Deux détails du sous-menu méritent d'être nommés, parce qu'ils ont été choisis et non subis : | |
| 26 | + | |
| 27 | +- **Droite et gauche sont asymétriques avec Échap.** Droite ouvre une branche, ou passe au menu suivant quand l'entrée n'en a pas : elle signifie donc toujours « plus profond », où que l'on soit. Gauche *ressort* d'un sous-menu vers son parent, tandis qu'Échap referme tout le menu — parce qu'annuler doit vouloir dire annuler, de n'importe où. | |
| 28 | +- **Le panneau bascule à gauche, et sa largeur est aussi bornée.** Un sous-menu qui dépasserait le bord droit est dessiné de l'autre côté de son parent. Basculer ne suffit pas : un panneau plus large que le terminal ne peut pas être rendu visible en le déplaçant, donc la largeur est bornée aussi et les intitulés longs sont coupés par le peintre. Un cadre sans bord droit paraît cassé d'une façon dont un intitulé tronqué ne l'est pas. | |
| 29 | + | |
| 30 | +## Pourquoi l'insertion réindente | |
| 31 | + | |
| 32 | +Un snippet est du texte, et l'implémentation évidente est de l'insérer. C'est juste pour une seule ligne et faux pour tout le reste, c'est-à-dire pour l'essentiel de ce que les gens gardent en snippets. | |
| 33 | + | |
| 34 | +Déposé tel quel, un corps multi-ligne repart en colonne zéro. Inséré dans une méthode, dans une boucle, dans un bloc `with` — là où l'on insère justement un `try`/`except` — le résultat est un texte dont aucun formateur, aucun lecteur et, en Python, aucun *analyseur* ne se satisfait. Dans un langage où l'indentation **est** la structure des blocs, un snippet en colonne zéro ne fait pas que paraître faux : il referme tous les blocs au-dessus de lui. La première chose qu'on fait est de le réindenter à la main, et une fonctionnalité dont la sortie doit être corrigée chaque fois ne fait gagner de temps à personne. | |
| 35 | + | |
| 36 | +Les lignes après la première reçoivent donc l'indentation de la ligne où était le curseur. Cela recopie ce que le fichier emploie déjà — tabulations ou espaces, en telle quantité — plutôt que d'imposer un choix, ce qui compte dans un projet à l'histoire mêlée. | |
| 37 | + | |
| 38 | +Deux décisions plus petites à l'intérieur : | |
| 39 | + | |
| 40 | +- **Une ligne vide du corps reste vide.** La compléter jusqu'à l'indentation y mettrait des espaces en fin de ligne, que tout formateur supprime ensuite — du bruit dans le diff de l'enregistrement suivant. | |
| 41 | +- **C'est une seule annulation.** Un snippet est une seule action pour qui l'a choisi, donc `Ctrl-Z` doit tout reprendre. Cela découle de faire toute l'insertion en un seul `ReplaceRange`, la règle que le buffer impose déjà à toute autre modification. | |
| 42 | + | |
| 43 | +Les emplacements et les tabulations successives — `${1:nom}` et le passage de l'un à l'autre — ont été envisagés et laissés de côté. C'est une seconde fonctionnalité, avec son propre état à maintenir à travers les modifications, alors que ce qui était demandé est du texte réutilisable. | |
| 44 | + | |
| 45 | +## Pourquoi deux fichiers, et pourquoi le projet gagne | |
| 46 | + | |
| 47 | +Vos snippets vous appartiennent et doivent vous suivre d'un projet à l'autre ; ceux d'un projet lui appartiennent et doivent arriver avec un clone. Ni l'un ni l'autre n'est la réponse complète, donc les deux sont lus. | |
| 48 | + | |
| 49 | +Quand un nom entre en conflit dans le même groupe, celui du projet remplace le vôtre. C'est le plus spécifique des deux énoncés, et c'est celui dont une équipe a convenu — la même raison qui fait qu'un drapeau `-theme` l'emporte sur le réglage d'un projet, tandis que le réglage d'un projet l'emporte sur le défaut intégré. | |
| 50 | + | |
| 51 | +## Pourquoi un fichier illisible est bruyant | |
| 52 | + | |
| 53 | +Une faute de frappe dans le TOML pourrait faire disparaître tous les snippets en silence et laisser un menu ne contenant que **Create snippets file** — ce qui ressemble exactement à un projet sans snippets, et vous envoie créer un fichier que vous avez déjà. | |
| 54 | + | |
| 55 | +Le menu affiche donc un `Cannot read snippets` grisé là où les groupes seraient. Il ne peut pas être choisi, il est là où vous regardiez, et l'entrée de création reste en dessous : il y a une issue dans les deux cas. | |
| 56 | + | |
| 57 | +## Liens avec le reste | |
| 58 | + | |
| 59 | +- Toutes les clés et toutes les règles : [Référence des snippets](../reference/snippets.md) | |
| 60 | +- Les mettre en place : [Insérer des snippets depuis un menu](../how-to/use-snippets.md) | |
| 61 | +- L'autre fichier du même dossier : [Réglages de projet](project-settings.md) | |
| 62 | +- Les noms de langages qu'emploie `languages` : [Langages colorés](../reference/languages.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | +# Snippets — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Un menu **Snippets** dont le contenu vient d'un fichier TOML, et un snippet choisi déposé dans le fichier que vous éditez. Cette page traite des trois décisions qui lui donnent sa forme : pourquoi le menu est reconstruit à chaque ouverture, pourquoi l'éditeur a gagné de vrais sous-menus pour lui, et pourquoi l'insertion réindente. | ||
| 6 | + | ||
| 7 | +## Pourquoi le menu est construit au moment où il s'ouvre | ||
| 8 | + | ||
| 9 | +Tous les autres menus de l'éditeur sont décidés une fois, dans `New()`. Celui-ci ne peut pas l'être, et pour deux raisons indépendantes. | ||
| 10 | + | ||
| 11 | +La première est le fichier. Les snippets vivent dans du TOML, et tout l'intérêt est que vous l'éditiez — souvent dans cet éditeur, dans la fenêtre que l'entrée **Create snippets file** vient d'ouvrir pour vous. Un menu construit au démarrage montrerait l'état du fichier au lancement, et il faudrait redémarrer pour voir un snippet qu'on vient d'écrire. C'est le genre de friction qui fait qu'une fonctionnalité n'est pas utilisée du tout. | ||
| 12 | + | ||
| 13 | +La seconde est la fenêtre au premier plan. Le menu est filtré par ce que vous éditez, donc il change quand vous appuyez sur `F6`. Il n'existe aucun instant du démarrage où la réponse existe. | ||
| 14 | + | ||
| 15 | +`ui.Menu` a donc gagné un champ `OnOpen` : une fonction que la barre appelle juste avant de dérouler un menu, laissant son propriétaire regarnir `Items` d'abord. C'est le même mécanisme de communication ascendante que partout ailleurs dans ce code — un champ fonction, pas une interface — et il s'exécute exactement au moment où le contenu va être vu, pas plus souvent. | ||
| 16 | + | ||
| 17 | +## Pourquoi l'éditeur a gagné des sous-menus | ||
| 18 | + | ||
| 19 | +`ui.MenuItem` ne savait pas imbriquer, et l'ajouter a été la plus grosse pièce de ce travail : un second panneau à placer et à dessiner, des flèches qui signifient « plus profond » et « ressortir », le pointeur qui ouvre une branche au survol et la referme en la quittant, et une fermeture qui range les deux panneaux d'un coup. | ||
| 20 | + | ||
| 21 | +L'alternative était un seul panneau plat avec les groupes en intitulés grisés entre des filets. Cela fonctionne, ne demande rien de neuf, et s'effondre sur le cas même pour lequel la fonctionnalité existe : un projet de trente snippets donne un menu plus haut que le terminal. Un regroupement qui étiquette sans replier ne résout pas le problème qu'il semble résoudre. | ||
| 22 | + | ||
| 23 | +C'est délibérément **un seul niveau**. Le format est des groupes contenant des snippets — exactement un niveau — et une profondeur générale supposerait de remplacer les deux indices de la barre par un chemin, dans le widget dont dépendent déjà tous les dialogues et tous les tests de menu. C'est du travail spéculatif sur la partie la plus porteuse de l'interface. | ||
| 24 | + | ||
| 25 | +Deux détails du sous-menu méritent d'être nommés, parce qu'ils ont été choisis et non subis : | ||
| 26 | + | ||
| 27 | +- **Droite et gauche sont asymétriques avec Échap.** Droite ouvre une branche, ou passe au menu suivant quand l'entrée n'en a pas : elle signifie donc toujours « plus profond », où que l'on soit. Gauche *ressort* d'un sous-menu vers son parent, tandis qu'Échap referme tout le menu — parce qu'annuler doit vouloir dire annuler, de n'importe où. | ||
| 28 | +- **Le panneau bascule à gauche, et sa largeur est aussi bornée.** Un sous-menu qui dépasserait le bord droit est dessiné de l'autre côté de son parent. Basculer ne suffit pas : un panneau plus large que le terminal ne peut pas être rendu visible en le déplaçant, donc la largeur est bornée aussi et les intitulés longs sont coupés par le peintre. Un cadre sans bord droit paraît cassé d'une façon dont un intitulé tronqué ne l'est pas. | ||
| 29 | + | ||
| 30 | +## Pourquoi l'insertion réindente | ||
| 31 | + | ||
| 32 | +Un snippet est du texte, et l'implémentation évidente est de l'insérer. C'est juste pour une seule ligne et faux pour tout le reste, c'est-à-dire pour l'essentiel de ce que les gens gardent en snippets. | ||
| 33 | + | ||
| 34 | +Déposé tel quel, un corps multi-ligne repart en colonne zéro. Inséré dans une méthode, dans une boucle, dans un bloc `with` — là où l'on insère justement un `try`/`except` — le résultat est un texte dont aucun formateur, aucun lecteur et, en Python, aucun *analyseur* ne se satisfait. Dans un langage où l'indentation **est** la structure des blocs, un snippet en colonne zéro ne fait pas que paraître faux : il referme tous les blocs au-dessus de lui. La première chose qu'on fait est de le réindenter à la main, et une fonctionnalité dont la sortie doit être corrigée chaque fois ne fait gagner de temps à personne. | ||
| 35 | + | ||
| 36 | +Les lignes après la première reçoivent donc l'indentation de la ligne où était le curseur. Cela recopie ce que le fichier emploie déjà — tabulations ou espaces, en telle quantité — plutôt que d'imposer un choix, ce qui compte dans un projet à l'histoire mêlée. | ||
| 37 | + | ||
| 38 | +Deux décisions plus petites à l'intérieur : | ||
| 39 | + | ||
| 40 | +- **Une ligne vide du corps reste vide.** La compléter jusqu'à l'indentation y mettrait des espaces en fin de ligne, que tout formateur supprime ensuite — du bruit dans le diff de l'enregistrement suivant. | ||
| 41 | +- **C'est une seule annulation.** Un snippet est une seule action pour qui l'a choisi, donc `Ctrl-Z` doit tout reprendre. Cela découle de faire toute l'insertion en un seul `ReplaceRange`, la règle que le buffer impose déjà à toute autre modification. | ||
| 42 | + | ||
| 43 | +Les emplacements et les tabulations successives — `${1:nom}` et le passage de l'un à l'autre — ont été envisagés et laissés de côté. C'est une seconde fonctionnalité, avec son propre état à maintenir à travers les modifications, alors que ce qui était demandé est du texte réutilisable. | ||
| 44 | + | ||
| 45 | +## Pourquoi deux fichiers, et pourquoi le projet gagne | ||
| 46 | + | ||
| 47 | +Vos snippets vous appartiennent et doivent vous suivre d'un projet à l'autre ; ceux d'un projet lui appartiennent et doivent arriver avec un clone. Ni l'un ni l'autre n'est la réponse complète, donc les deux sont lus. | ||
| 48 | + | ||
| 49 | +Quand un nom entre en conflit dans le même groupe, celui du projet remplace le vôtre. C'est le plus spécifique des deux énoncés, et c'est celui dont une équipe a convenu — la même raison qui fait qu'un drapeau `-theme` l'emporte sur le réglage d'un projet, tandis que le réglage d'un projet l'emporte sur le défaut intégré. | ||
| 50 | + | ||
| 51 | +## Pourquoi un fichier illisible est bruyant | ||
| 52 | + | ||
| 53 | +Une faute de frappe dans le TOML pourrait faire disparaître tous les snippets en silence et laisser un menu ne contenant que **Create snippets file** — ce qui ressemble exactement à un projet sans snippets, et vous envoie créer un fichier que vous avez déjà. | ||
| 54 | + | ||
| 55 | +Le menu affiche donc un `Cannot read snippets` grisé là où les groupes seraient. Il ne peut pas être choisi, il est là où vous regardiez, et l'entrée de création reste en dessous : il y a une issue dans les deux cas. | ||
| 56 | + | ||
| 57 | +## Liens avec le reste | ||
| 58 | + | ||
| 59 | +- Toutes les clés et toutes les règles : [Référence des snippets](../reference/snippets.md) | ||
| 60 | +- Les mettre en place : [Insérer des snippets depuis un menu](../how-to/use-snippets.md) | ||
| 61 | +- L'autre fichier du même dossier : [Réglages de projet](project-settings.md) | ||
| 62 | +- Les noms de langages qu'emploie `languages` : [Langages colorés](../reference/languages.md) | ||
added
docs/fr/explanation/terminal-windows.md +72 -0 | new file mode 100644 | ||
| @@ -0,0 +1,72 @@ | ||
| 1 | +# Fenêtres terminal — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +`F8` ouvre une fenêtre contenant un shell. Cette phrase masque l'essentiel du travail : pour mettre un shell dans une fenêtre, un éditeur doit devenir un émulateur de terminal. Cette page raconte ce que cela a impliqué, et quelles solutions moins coûteuses ont été écartées en chemin. | |
| 6 | + | |
| 7 | +## Pourquoi un vrai pseudo-terminal | |
| 8 | + | |
| 9 | +La version bon marché évidente consiste à lancer une commande avec `exec.Command`, à capturer sa sortie et à l'afficher dans un panneau en lecture seule. Beaucoup d'éditeurs livrent exactement cela, et cela échoue précisément sur ce pour quoi on veut un terminal. | |
| 10 | + | |
| 11 | +Un programme se comporte différemment quand sa sortie est un tube plutôt qu'un terminal. `uv run pytest` abandonne ses couleurs. `git log` ne pagine pas. `ls` affiche un nom par ligne. Rien d'interactif ne fonctionne : ni `vim`, ni `ssh`, ni `git rebase -i`, ni la réponse à une invite, ni `Ctrl-C` — sans terminal de contrôle, il n'y a aucun signal à envoyer. | |
| 12 | + | |
| 13 | +Le shell reçoit donc un vrai pseudo-terminal : `/dev/ptmx` sur les deux plateformes supportées, le fils dans une session à lui avec l'esclave comme terminal de contrôle, et `TIOCSWINSZ` à chaque redimensionnement de la fenêtre. Cela offre gratuitement le contrôle de tâches, `isatty`, `SIGWINCH` et la couleur, parce que ce sont les mêmes mécanismes que ceux de tous les autres terminaux. | |
| 14 | + | |
| 15 | +Le prix à payer est que l'éditeur doit ensuite relire ce qu'un terminal est censé comprendre — c'est-à-dire l'émulateur. | |
| 16 | + | |
| 17 | +## Pourquoi écrire l'émulateur plutôt que d'en emprunter un | |
| 18 | + | |
| 19 | +Go dispose de bibliothèques d'émulation de terminal. En prendre une aurait signifié une troisième dépendance, dans un projet qui en a exactement deux et qui affiche une réticence assumée à en ajouter une troisième. | |
| 20 | + | |
| 21 | +Ce que l'on met en balance n'est pas « émulateur » contre « pas d'émulateur », mais *quelle quantité* d'émulateur. Ce dont ont besoin un shell, `uv run pytest`, `git`, `less`, `htop` et `vim` forme une liste bien délimitée : déplacement du curseur, la famille effacement / insertion-suppression, une région de défilement, SGR dans ses trois profondeurs de couleur, l'écran alternatif, le retour à la ligne automatique, la visibilité du curseur et les touches curseur application. Cela représente environ six cents lignes, c'est écrit noir sur blanc dans ECMA-48, et cela se teste en écrivant des octets en entrée et en lisant une grille en sortie — sans shell, sans temporisation, sans écran. | |
| 22 | + | |
| 23 | +À comparer avec ce qu'apporte une bibliothèque généraliste : jeux de caractères, protocoles de rapport souris, sixel, collage entre crochets, rapports d'état DEC. Tout cela est réel, rien n'est nécessaire ici, et tout cela constitue de la surface à maintenir. | |
| 24 | + | |
| 25 | +L'émulateur est donc écrit à la main et volontairement partiel, et la [référence](../reference/terminal.md) dit exactement où il s'arrête. Un programme qui demande quelque chose d'absent obtient le silence plutôt que de la corruption, ce qui est le bon mode d'échec : `htop` s'affiche, la sortie `sixel` n'apparaît simplement pas. | |
| 26 | + | |
| 27 | +## À qui revient la touche | |
| 28 | + | |
| 29 | +C'est la décision qui pèse le plus sur la sensation d'usage de l'éditeur, et la première version s'était trompée. | |
| 30 | + | |
| 31 | +Les raccourcis globaux de l'éditeur sont examinés avant que la fenêtre du premier plan ne voie quoi que ce soit. C'est juste pour un éditeur, et faux dès l'instant où cette fenêtre est un shell, parce que les deux revendiquent les mêmes touches. `Ctrl-W` ferme une fenêtre dans Turbo C et supprime un mot dans tous les shells. `Ctrl-F` est Rechercher ici et avancer-d'un-caractère dans readline. `Ctrl-C` est copier, et aussi le seul moyen d'arrêter une commande emballée. | |
| 32 | + | |
| 33 | +La règle retenue inverse l'ordre habituel, mais uniquement pour les touches réellement disputées : | |
| 34 | + | |
| 35 | +**Un terminal ayant le focus reçoit tout, sauf les touches de fonction, `Alt-X` et `Alt-0`…`Alt-9`.** | |
| 36 | + | |
| 37 | +Ces exceptions ne sont pas un compromis entre les deux revendications — ce sont la *sortie*. Un programme plein écran comme `vim` recouvre la fenêtre et s'empare de la souris ; sans touche réservée, il n'y aurait aucun moyen d'atteindre la barre de menus, de changer de fenêtre ou de quitter l'éditeur sans d'abord quitter le programme. Les touches de fonction sont la réservation naturelle parce que c'est vers elles qu'un utilisateur de terminal se tourne le moins, et `Alt-X` parce que quitter un éditeur ne devrait jamais faire de doute. | |
| 38 | + | |
| 39 | +Ce que cela coûte est réel et mérite d'être nommé : `Alt-B` et `Alt-F` atteignent le shell, donc le déplacement par mot de readline fonctionne, mais un programme dans une fenêtre terminal ne verra jamais `F1`…`F12`. Le menu par touches de fonction de `htop` est inaccessible. C'est l'arbitrage, et il a été rendu en faveur du fait de toujours pouvoir sortir. | |
| 40 | + | |
| 41 | +## Pourquoi fermer un terminal ne demande rien | |
| 42 | + | |
| 43 | +Fermer un fichier modifié demande s'il faut l'enregistrer. Fermer un terminal ne demande rien du tout, et cette asymétrie est délibérée. | |
| 44 | + | |
| 45 | +Une fenêtre au travail non enregistré contient quelque chose qui serait *perdu*. Un terminal contient un processus en cours, et fermer la fenêtre est la façon ordinaire de dire qu'on en a fini — comme on ferme l'onglet d'un émulateur de terminal. Demander « êtes-vous sûr ? » à chaque fois désapprendrait la réponse à quiconque, ce qui est le problème général des confirmations qui se déclenchent sur le cas courant. | |
| 46 | + | |
| 47 | +Quitter l'éditeur ferme tous les terminaux pour la même raison, en sens inverse : une fenêtre est la seule prise sur ces shells, donc les laisser survivre à l'éditeur abandonnerait des processus que plus rien ne peut atteindre. | |
| 48 | + | |
| 49 | +## Pourquoi les redessins sont cadencés | |
| 50 | + | |
| 51 | +Le shell écrit depuis une goroutine à lui ; l'éditeur dessine depuis la principale. Réveiller la boucle d'événements à chaque bloc de sortie semblait évident et se trompait deux fois. | |
| 52 | + | |
| 53 | +Une compilation écrit bien plus vite qu'un écran ne peut être utilement repeint : la plupart de ces redessins sont donc du gaspillage. Pire, le mécanisme de réveil de la boucle depuis une autre goroutine est le `PostEvent` de tcell, qui **jette** les événements quand sa file est pleine — de sorte que la rafale qui a le plus besoin d'un redessin est justement celle dont le réveil final est perdu, et la fenêtre se fige en pleine compilation sur un texte périmé. Ce bug exact avait déjà été rencontré une fois ailleurs dans cet éditeur, du côté du serveur de langage. | |
| 54 | + | |
| 55 | +La vue positionne donc un drapeau, et une horloge demande un redessin soixante fois par seconde tant que le drapeau est levé. Un réveil perdu ne peut rien bloquer, puisque le tic suivant est à seize millisecondes. | |
| 56 | + | |
| 57 | +## Windows : une pseudo-console, et pourquoi c'est un fichier à part | |
| 58 | + | |
| 59 | +Les pseudo-terminaux sont la seule partie non portable de tout ceci. Linux et macOS passent tous deux par `/dev/ptmx` et ne diffèrent que par l'`ioctl` qui accorde l'esclave. Windows n'a rien de tel : il a des **pseudo-consoles** — ConPTY, depuis Windows 10 version 1809 — un objet détenu par `conhost.exe` et relié à deux tubes de l'éditeur. Ce que le shell affiche arrive sur l'un des tubes sous la forme des mêmes séquences VT qu'un shell Unix écrit dans un pty, ce qui est la raison pour laquelle l'émulateur de ce côté n'a eu besoin d'aucun code Windows ; ce que l'éditeur écrit dans l'autre tube parvient au shell comme des frappes de touches. | |
| 60 | + | |
| 61 | +Trois choses en ont fait un fichier à part plutôt qu'une variante du fichier Unix. Le processus doit être créé à la main, parce que l'attacher à une pseudo-console exige un enregistrement de démarrage étendu que l'`os/exec` de Go ne sait pas porter. Le shell est `%COMSPEC%` — cmd.exe — plutôt que `$SHELL`, et cmd.exe lit sa ligne de commande selon ses propres règles : la ligne qui lance une commande du menu est donc composée pour lui mot pour mot, la commande entre une seule paire de guillemets, au lieu d'être échappée comme tout autre programme l'attend. Et `conhost.exe` garde le tube de sortie ouvert jusqu'à la fermeture de la console, quoi que fasse le shell ; une goroutine attend donc la fin du shell puis ferme la console — c'est ce qui transforme une commande terminée en la fin d'entrée sur laquelle la fenêtre compte pour le dire. Le contrôle de tâches est celui de cmd.exe et non du noyau : `Ctrl-C` interrompt le programme en cours comme il le ferait dans une fenêtre de console. | |
| 62 | + | |
| 63 | +Les fichiers par plateforme restent séparés pour que chaque plateforme ait une implémentation honnête derrière une petite interface, et qu'une plateforme qui n'a ni l'un ni l'autre — les BSD, aujourd'hui — reçoive `ErrUnsupported`, que `F8` le dise clairement, et que rien d'autre dans l'éditeur ne soit affecté. | |
| 64 | + | |
| 65 | +**Le chemin Windows a été compilé et vérifié, pas exécuté.** turbo-core est développé sous Linux et son auteur travaille sous macOS. Les parties pures — le bloc d'environnement, la ligne de commande que veut cmd.exe — sont testées unitairement sur toute plateforme, et les appels à l'API compilent et passent `go vet` sous `GOOS=windows` ; personne n'a encore appuyé sur `F8` sur une machine Windows. [Le guide](../how-to/use-a-terminal.md) dit quoi essayer en premier. | |
| 66 | + | |
| 67 | +## Liens avec le reste | |
| 68 | + | |
| 69 | +- La liste exacte de ce qui est implémenté : [référence des fenêtres terminal](../reference/terminal.md) | |
| 70 | +- En utiliser une : [Lancer des commandes shell sans quitter l'éditeur](../how-to/use-a-terminal.md) | |
| 71 | +- Où `terminal` se situe parmi les paquets, et pourquoi le graphe est orienté : [Architecture](architecture.md) | |
| 72 | +- Le décompte de dépendances que cette page ne cesse d'invoquer : [Décisions de conception](design-decisions.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,72 @@ | |||
| 1 | +# Fenêtres terminal — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +`F8` ouvre une fenêtre contenant un shell. Cette phrase masque l'essentiel du travail : pour mettre un shell dans une fenêtre, un éditeur doit devenir un émulateur de terminal. Cette page raconte ce que cela a impliqué, et quelles solutions moins coûteuses ont été écartées en chemin. | ||
| 6 | + | ||
| 7 | +## Pourquoi un vrai pseudo-terminal | ||
| 8 | + | ||
| 9 | +La version bon marché évidente consiste à lancer une commande avec `exec.Command`, à capturer sa sortie et à l'afficher dans un panneau en lecture seule. Beaucoup d'éditeurs livrent exactement cela, et cela échoue précisément sur ce pour quoi on veut un terminal. | ||
| 10 | + | ||
| 11 | +Un programme se comporte différemment quand sa sortie est un tube plutôt qu'un terminal. `uv run pytest` abandonne ses couleurs. `git log` ne pagine pas. `ls` affiche un nom par ligne. Rien d'interactif ne fonctionne : ni `vim`, ni `ssh`, ni `git rebase -i`, ni la réponse à une invite, ni `Ctrl-C` — sans terminal de contrôle, il n'y a aucun signal à envoyer. | ||
| 12 | + | ||
| 13 | +Le shell reçoit donc un vrai pseudo-terminal : `/dev/ptmx` sur les deux plateformes supportées, le fils dans une session à lui avec l'esclave comme terminal de contrôle, et `TIOCSWINSZ` à chaque redimensionnement de la fenêtre. Cela offre gratuitement le contrôle de tâches, `isatty`, `SIGWINCH` et la couleur, parce que ce sont les mêmes mécanismes que ceux de tous les autres terminaux. | ||
| 14 | + | ||
| 15 | +Le prix à payer est que l'éditeur doit ensuite relire ce qu'un terminal est censé comprendre — c'est-à-dire l'émulateur. | ||
| 16 | + | ||
| 17 | +## Pourquoi écrire l'émulateur plutôt que d'en emprunter un | ||
| 18 | + | ||
| 19 | +Go dispose de bibliothèques d'émulation de terminal. En prendre une aurait signifié une troisième dépendance, dans un projet qui en a exactement deux et qui affiche une réticence assumée à en ajouter une troisième. | ||
| 20 | + | ||
| 21 | +Ce que l'on met en balance n'est pas « émulateur » contre « pas d'émulateur », mais *quelle quantité* d'émulateur. Ce dont ont besoin un shell, `uv run pytest`, `git`, `less`, `htop` et `vim` forme une liste bien délimitée : déplacement du curseur, la famille effacement / insertion-suppression, une région de défilement, SGR dans ses trois profondeurs de couleur, l'écran alternatif, le retour à la ligne automatique, la visibilité du curseur et les touches curseur application. Cela représente environ six cents lignes, c'est écrit noir sur blanc dans ECMA-48, et cela se teste en écrivant des octets en entrée et en lisant une grille en sortie — sans shell, sans temporisation, sans écran. | ||
| 22 | + | ||
| 23 | +À comparer avec ce qu'apporte une bibliothèque généraliste : jeux de caractères, protocoles de rapport souris, sixel, collage entre crochets, rapports d'état DEC. Tout cela est réel, rien n'est nécessaire ici, et tout cela constitue de la surface à maintenir. | ||
| 24 | + | ||
| 25 | +L'émulateur est donc écrit à la main et volontairement partiel, et la [référence](../reference/terminal.md) dit exactement où il s'arrête. Un programme qui demande quelque chose d'absent obtient le silence plutôt que de la corruption, ce qui est le bon mode d'échec : `htop` s'affiche, la sortie `sixel` n'apparaît simplement pas. | ||
| 26 | + | ||
| 27 | +## À qui revient la touche | ||
| 28 | + | ||
| 29 | +C'est la décision qui pèse le plus sur la sensation d'usage de l'éditeur, et la première version s'était trompée. | ||
| 30 | + | ||
| 31 | +Les raccourcis globaux de l'éditeur sont examinés avant que la fenêtre du premier plan ne voie quoi que ce soit. C'est juste pour un éditeur, et faux dès l'instant où cette fenêtre est un shell, parce que les deux revendiquent les mêmes touches. `Ctrl-W` ferme une fenêtre dans Turbo C et supprime un mot dans tous les shells. `Ctrl-F` est Rechercher ici et avancer-d'un-caractère dans readline. `Ctrl-C` est copier, et aussi le seul moyen d'arrêter une commande emballée. | ||
| 32 | + | ||
| 33 | +La règle retenue inverse l'ordre habituel, mais uniquement pour les touches réellement disputées : | ||
| 34 | + | ||
| 35 | +**Un terminal ayant le focus reçoit tout, sauf les touches de fonction, `Alt-X` et `Alt-0`…`Alt-9`.** | ||
| 36 | + | ||
| 37 | +Ces exceptions ne sont pas un compromis entre les deux revendications — ce sont la *sortie*. Un programme plein écran comme `vim` recouvre la fenêtre et s'empare de la souris ; sans touche réservée, il n'y aurait aucun moyen d'atteindre la barre de menus, de changer de fenêtre ou de quitter l'éditeur sans d'abord quitter le programme. Les touches de fonction sont la réservation naturelle parce que c'est vers elles qu'un utilisateur de terminal se tourne le moins, et `Alt-X` parce que quitter un éditeur ne devrait jamais faire de doute. | ||
| 38 | + | ||
| 39 | +Ce que cela coûte est réel et mérite d'être nommé : `Alt-B` et `Alt-F` atteignent le shell, donc le déplacement par mot de readline fonctionne, mais un programme dans une fenêtre terminal ne verra jamais `F1`…`F12`. Le menu par touches de fonction de `htop` est inaccessible. C'est l'arbitrage, et il a été rendu en faveur du fait de toujours pouvoir sortir. | ||
| 40 | + | ||
| 41 | +## Pourquoi fermer un terminal ne demande rien | ||
| 42 | + | ||
| 43 | +Fermer un fichier modifié demande s'il faut l'enregistrer. Fermer un terminal ne demande rien du tout, et cette asymétrie est délibérée. | ||
| 44 | + | ||
| 45 | +Une fenêtre au travail non enregistré contient quelque chose qui serait *perdu*. Un terminal contient un processus en cours, et fermer la fenêtre est la façon ordinaire de dire qu'on en a fini — comme on ferme l'onglet d'un émulateur de terminal. Demander « êtes-vous sûr ? » à chaque fois désapprendrait la réponse à quiconque, ce qui est le problème général des confirmations qui se déclenchent sur le cas courant. | ||
| 46 | + | ||
| 47 | +Quitter l'éditeur ferme tous les terminaux pour la même raison, en sens inverse : une fenêtre est la seule prise sur ces shells, donc les laisser survivre à l'éditeur abandonnerait des processus que plus rien ne peut atteindre. | ||
| 48 | + | ||
| 49 | +## Pourquoi les redessins sont cadencés | ||
| 50 | + | ||
| 51 | +Le shell écrit depuis une goroutine à lui ; l'éditeur dessine depuis la principale. Réveiller la boucle d'événements à chaque bloc de sortie semblait évident et se trompait deux fois. | ||
| 52 | + | ||
| 53 | +Une compilation écrit bien plus vite qu'un écran ne peut être utilement repeint : la plupart de ces redessins sont donc du gaspillage. Pire, le mécanisme de réveil de la boucle depuis une autre goroutine est le `PostEvent` de tcell, qui **jette** les événements quand sa file est pleine — de sorte que la rafale qui a le plus besoin d'un redessin est justement celle dont le réveil final est perdu, et la fenêtre se fige en pleine compilation sur un texte périmé. Ce bug exact avait déjà été rencontré une fois ailleurs dans cet éditeur, du côté du serveur de langage. | ||
| 54 | + | ||
| 55 | +La vue positionne donc un drapeau, et une horloge demande un redessin soixante fois par seconde tant que le drapeau est levé. Un réveil perdu ne peut rien bloquer, puisque le tic suivant est à seize millisecondes. | ||
| 56 | + | ||
| 57 | +## Windows : une pseudo-console, et pourquoi c'est un fichier à part | ||
| 58 | + | ||
| 59 | +Les pseudo-terminaux sont la seule partie non portable de tout ceci. Linux et macOS passent tous deux par `/dev/ptmx` et ne diffèrent que par l'`ioctl` qui accorde l'esclave. Windows n'a rien de tel : il a des **pseudo-consoles** — ConPTY, depuis Windows 10 version 1809 — un objet détenu par `conhost.exe` et relié à deux tubes de l'éditeur. Ce que le shell affiche arrive sur l'un des tubes sous la forme des mêmes séquences VT qu'un shell Unix écrit dans un pty, ce qui est la raison pour laquelle l'émulateur de ce côté n'a eu besoin d'aucun code Windows ; ce que l'éditeur écrit dans l'autre tube parvient au shell comme des frappes de touches. | ||
| 60 | + | ||
| 61 | +Trois choses en ont fait un fichier à part plutôt qu'une variante du fichier Unix. Le processus doit être créé à la main, parce que l'attacher à une pseudo-console exige un enregistrement de démarrage étendu que l'`os/exec` de Go ne sait pas porter. Le shell est `%COMSPEC%` — cmd.exe — plutôt que `$SHELL`, et cmd.exe lit sa ligne de commande selon ses propres règles : la ligne qui lance une commande du menu est donc composée pour lui mot pour mot, la commande entre une seule paire de guillemets, au lieu d'être échappée comme tout autre programme l'attend. Et `conhost.exe` garde le tube de sortie ouvert jusqu'à la fermeture de la console, quoi que fasse le shell ; une goroutine attend donc la fin du shell puis ferme la console — c'est ce qui transforme une commande terminée en la fin d'entrée sur laquelle la fenêtre compte pour le dire. Le contrôle de tâches est celui de cmd.exe et non du noyau : `Ctrl-C` interrompt le programme en cours comme il le ferait dans une fenêtre de console. | ||
| 62 | + | ||
| 63 | +Les fichiers par plateforme restent séparés pour que chaque plateforme ait une implémentation honnête derrière une petite interface, et qu'une plateforme qui n'a ni l'un ni l'autre — les BSD, aujourd'hui — reçoive `ErrUnsupported`, que `F8` le dise clairement, et que rien d'autre dans l'éditeur ne soit affecté. | ||
| 64 | + | ||
| 65 | +**Le chemin Windows a été compilé et vérifié, pas exécuté.** turbo-core est développé sous Linux et son auteur travaille sous macOS. Les parties pures — le bloc d'environnement, la ligne de commande que veut cmd.exe — sont testées unitairement sur toute plateforme, et les appels à l'API compilent et passent `go vet` sous `GOOS=windows` ; personne n'a encore appuyé sur `F8` sur une machine Windows. [Le guide](../how-to/use-a-terminal.md) dit quoi essayer en premier. | ||
| 66 | + | ||
| 67 | +## Liens avec le reste | ||
| 68 | + | ||
| 69 | +- La liste exacte de ce qui est implémenté : [référence des fenêtres terminal](../reference/terminal.md) | ||
| 70 | +- En utiliser une : [Lancer des commandes shell sans quitter l'éditeur](../how-to/use-a-terminal.md) | ||
| 71 | +- Où `terminal` se situe parmi les paquets, et pourquoi le graphe est orienté : [Architecture](architecture.md) | ||
| 72 | +- Le décompte de dépendances que cette page ne cesse d'invoquer : [Décisions de conception](design-decisions.md) | ||
added
docs/fr/how-to/ask-about-code.md +69 -0 | new file mode 100644 | ||
| @@ -0,0 +1,69 @@ | ||
| 1 | +# Comment interroger le code | |
| 2 | + | |
| 3 | +Ce guide montre comment suivre un nom dans un projet : où il est déclaré, ce qui l'implémente, partout où il est utilisé, et ce qui ne va pas avec lui. Il suppose Turbo Python installé et un serveur de langage en marche — la barre d'état affiche `LSP: ready` quand c'est le cas. | |
| 4 | + | |
| 5 | +Pour se déplacer dans un fichier — chercher, aller à une ligne, changer de fenêtre — voir plutôt [Comment se déplacer dans un fichier](navigate-code.md). | |
| 6 | + | |
| 7 | +## Placez le curseur sur un nom | |
| 8 | + | |
| 9 | +N'importe lequel de ses caractères suffit. Chaque question ci-dessous porte sur la **position du curseur**, pas sur une sélection : il n'y a rien à surligner d'abord. | |
| 10 | + | |
| 11 | +## Demandez | |
| 12 | + | |
| 13 | +| Pour trouver | Faites | Raccourci | | |
| 14 | +| --- | --- | --- | | |
| 15 | +| Ce que c'est | **Code ▸ Describe symbol** | `F1` | | |
| 16 | +| Où c'est déclaré | **Code ▸ Go to definition** | `F12` | | |
| 17 | +| Où son *type* est déclaré | **Code ▸ Go to type definition** | | | |
| 18 | +| Ce qui l'implémente | **Code ▸ Find implementations…** | | | |
| 19 | +| Partout où c'est utilisé | **Code ▸ Find references…** | `Shift-F12` | | |
| 20 | + | |
| 21 | +Une seule réponse vous y emmène directement. Plusieurs ouvrent une liste montrant le fichier, sa ligne, et le texte de cette ligne : | |
| 22 | + | |
| 23 | +``` | |
| 24 | +Implementations (2) | |
| 25 | + french.py:4 impl Greeter for French { | |
| 26 | + english.py:4 impl Greeter for English { | |
| 27 | +``` | |
| 28 | + | |
| 29 | +Déplacez-vous aux flèches, `Entrée` pour y aller, `Échap` pour rester. | |
| 30 | + | |
| 31 | +## Quand rien ne revient | |
| 32 | + | |
| 33 | +Trois choses se ressemblent, et la barre d'état les distingue : | |
| 34 | + | |
| 35 | +| Elle affiche | Signification | | |
| 36 | +| --- | --- | | |
| 37 | +| `No references found` | Le serveur a répondu, et il n'y en a pas | | |
| 38 | +| Autre chose, par exemple `Loading…` | Le serveur n'a pas fini d'indexer. Attendez un instant et redemandez. | | |
| 39 | +| `LSP: off` dans la barre d'état | Aucun serveur ne tourne. Voir [Comment activer la complétion](enable-completion.md). | | |
| 40 | + | |
| 41 | +La deuxième mérite d'être connue : un serveur encore en train d'indexer répond rien à toutes les questions, et c'est indiscernable d'une vraie réponse si l'éditeur ne le dit pas. | |
| 42 | + | |
| 43 | +## Chercher par le nom | |
| 44 | + | |
| 45 | +- **Code ▸ Symbol in file…** liste ce que déclare le fichier devant vous, indenté, avec la sorte de chaque symbole — un plan que l'on parcourt. | |
| 46 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) demande un nom et cherche partout. Ce qui compte comme correspondance appartient au serveur ; pylsp est tolérant, quelques lettres suffisent en général. | |
| 47 | + | |
| 48 | +## Voir ce qui ne va pas | |
| 49 | + | |
| 50 | +**Code ▸ Problems…** liste tous les problèmes signalés par le serveur, pour **tous les fichiers qu'il a chargés** — le plus souvent davantage que celui que vous éditez. En choisir un vous mène à la ligne. | |
| 51 | + | |
| 52 | +Les lignes à problème portent une marque dans la gouttière, à côté du numéro de ligne : | |
| 53 | + | |
| 54 | +| Marque | Signification | | |
| 55 | +| --- | --- | | |
| 56 | +| `×` | Une erreur | | |
| 57 | +| `!` | Un avertissement | | |
| 58 | +| `i` | Une information | | |
| 59 | +| `·` | Une suggestion | | |
| 60 | + | |
| 61 | +Une ligne qui a plusieurs problèmes montre le pire d'entre eux. | |
| 62 | + | |
| 63 | +**Les marques ont besoin des numéros de ligne.** Elles occupent la colonne qui sépare les numéros du texte : masquer la gouttière avec **Options ▸ Line numbers** les masque aussi. | |
| 64 | + | |
| 65 | +## Voir aussi | |
| 66 | + | |
| 67 | +- Chaque entrée et sa touche : [Menus](../reference/menus.md) | |
| 68 | +- Faire tourner un serveur : [Comment activer la complétion](enable-completion.md) | |
| 69 | +- Ce que l'éditeur demande, et pourquoi : [Coloration et complétion](../explanation/colouring-and-completion.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,69 @@ | |||
| 1 | +# Comment interroger le code | ||
| 2 | + | ||
| 3 | +Ce guide montre comment suivre un nom dans un projet : où il est déclaré, ce qui l'implémente, partout où il est utilisé, et ce qui ne va pas avec lui. Il suppose Turbo Python installé et un serveur de langage en marche — la barre d'état affiche `LSP: ready` quand c'est le cas. | ||
| 4 | + | ||
| 5 | +Pour se déplacer dans un fichier — chercher, aller à une ligne, changer de fenêtre — voir plutôt [Comment se déplacer dans un fichier](navigate-code.md). | ||
| 6 | + | ||
| 7 | +## Placez le curseur sur un nom | ||
| 8 | + | ||
| 9 | +N'importe lequel de ses caractères suffit. Chaque question ci-dessous porte sur la **position du curseur**, pas sur une sélection : il n'y a rien à surligner d'abord. | ||
| 10 | + | ||
| 11 | +## Demandez | ||
| 12 | + | ||
| 13 | +| Pour trouver | Faites | Raccourci | | ||
| 14 | +| --- | --- | --- | | ||
| 15 | +| Ce que c'est | **Code ▸ Describe symbol** | `F1` | | ||
| 16 | +| Où c'est déclaré | **Code ▸ Go to definition** | `F12` | | ||
| 17 | +| Où son *type* est déclaré | **Code ▸ Go to type definition** | | | ||
| 18 | +| Ce qui l'implémente | **Code ▸ Find implementations…** | | | ||
| 19 | +| Partout où c'est utilisé | **Code ▸ Find references…** | `Shift-F12` | | ||
| 20 | + | ||
| 21 | +Une seule réponse vous y emmène directement. Plusieurs ouvrent une liste montrant le fichier, sa ligne, et le texte de cette ligne : | ||
| 22 | + | ||
| 23 | +``` | ||
| 24 | +Implementations (2) | ||
| 25 | + french.py:4 impl Greeter for French { | ||
| 26 | + english.py:4 impl Greeter for English { | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +Déplacez-vous aux flèches, `Entrée` pour y aller, `Échap` pour rester. | ||
| 30 | + | ||
| 31 | +## Quand rien ne revient | ||
| 32 | + | ||
| 33 | +Trois choses se ressemblent, et la barre d'état les distingue : | ||
| 34 | + | ||
| 35 | +| Elle affiche | Signification | | ||
| 36 | +| --- | --- | | ||
| 37 | +| `No references found` | Le serveur a répondu, et il n'y en a pas | | ||
| 38 | +| Autre chose, par exemple `Loading…` | Le serveur n'a pas fini d'indexer. Attendez un instant et redemandez. | | ||
| 39 | +| `LSP: off` dans la barre d'état | Aucun serveur ne tourne. Voir [Comment activer la complétion](enable-completion.md). | | ||
| 40 | + | ||
| 41 | +La deuxième mérite d'être connue : un serveur encore en train d'indexer répond rien à toutes les questions, et c'est indiscernable d'une vraie réponse si l'éditeur ne le dit pas. | ||
| 42 | + | ||
| 43 | +## Chercher par le nom | ||
| 44 | + | ||
| 45 | +- **Code ▸ Symbol in file…** liste ce que déclare le fichier devant vous, indenté, avec la sorte de chaque symbole — un plan que l'on parcourt. | ||
| 46 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) demande un nom et cherche partout. Ce qui compte comme correspondance appartient au serveur ; pylsp est tolérant, quelques lettres suffisent en général. | ||
| 47 | + | ||
| 48 | +## Voir ce qui ne va pas | ||
| 49 | + | ||
| 50 | +**Code ▸ Problems…** liste tous les problèmes signalés par le serveur, pour **tous les fichiers qu'il a chargés** — le plus souvent davantage que celui que vous éditez. En choisir un vous mène à la ligne. | ||
| 51 | + | ||
| 52 | +Les lignes à problème portent une marque dans la gouttière, à côté du numéro de ligne : | ||
| 53 | + | ||
| 54 | +| Marque | Signification | | ||
| 55 | +| --- | --- | | ||
| 56 | +| `×` | Une erreur | | ||
| 57 | +| `!` | Un avertissement | | ||
| 58 | +| `i` | Une information | | ||
| 59 | +| `·` | Une suggestion | | ||
| 60 | + | ||
| 61 | +Une ligne qui a plusieurs problèmes montre le pire d'entre eux. | ||
| 62 | + | ||
| 63 | +**Les marques ont besoin des numéros de ligne.** Elles occupent la colonne qui sépare les numéros du texte : masquer la gouttière avec **Options ▸ Line numbers** les masque aussi. | ||
| 64 | + | ||
| 65 | +## Voir aussi | ||
| 66 | + | ||
| 67 | +- Chaque entrée et sa touche : [Menus](../reference/menus.md) | ||
| 68 | +- Faire tourner un serveur : [Comment activer la complétion](enable-completion.md) | ||
| 69 | +- Ce que l'éditeur demande, et pourquoi : [Coloration et complétion](../explanation/colouring-and-completion.md) | ||
added
docs/fr/how-to/browse-a-project.md +70 -0 | new file mode 100644 | ||
| @@ -0,0 +1,70 @@ | ||
| 1 | +# Parcourir un projet et ouvrir des fichiers depuis un arbre | |
| 2 | + | |
| 3 | +Ce guide montre comment ouvrir l'arbre du projet, le parcourir et y ouvrir un fichier. Il suppose Turbo Python déjà installé. | |
| 4 | + | |
| 5 | +## Ouvrir l'arbre | |
| 6 | + | |
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis appuyez sur `F9`, ou choisissez **Window ▸ Project tree**. | |
| 8 | + | |
| 9 | +Une fenêtre s'ouvre avec les fichiers du projet, nommée d'après le dossier depuis lequel l'éditeur a été lancé : | |
| 10 | + | |
| 11 | +``` | |
| 12 | +╔═[x]════════════ turbo-python ════════════2═[■]╗ | |
| 13 | +║ ▶ .turbo-python ║ | |
| 14 | +║ ▼ internal ║ | |
| 15 | +║ ▶ app ║ | |
| 16 | +║ ▼ ui ║ | |
| 17 | +║ window.go ║ | |
| 18 | +║ .gitignore ║ | |
| 19 | +║ pyproject.toml ║ | |
| 20 | +║ main.py ║ | |
| 21 | +╚══════════════════════════════════════════╝ | |
| 22 | +``` | |
| 23 | + | |
| 24 | +Les dossiers viennent d'abord, puis les fichiers, chaque groupe trié. `.git` est la seule chose masquée — `.turbo-python`, `.gitignore` et les autres sont des fichiers de votre projet, que vous voudrez sans doute ouvrir. | |
| 25 | + | |
| 26 | +Appuyer de nouveau sur `F9` ramène cette fenêtre au premier plan plutôt que d'ouvrir un second arbre. | |
| 27 | + | |
| 28 | +## Le parcourir | |
| 29 | + | |
| 30 | +| Touche | Effet | | |
| 31 | +| --- | --- | | |
| 32 | +| `↑` `↓` | Déplacer la surbrillance | | |
| 33 | +| `→` | Ouvrir un dossier fermé ; sur autre chose, passer à la ligne suivante | | |
| 34 | +| `←` | Fermer un dossier ouvert ; sur autre chose, remonter au dossier qui le contient | | |
| 35 | +| `Entrée` | Ouvrir un fichier, ou ouvrir et fermer un dossier | | |
| 36 | +| `Début` `Fin` | Première / dernière ligne | | |
| 37 | +| `Page↑` `Page↓` | Un écran à la fois | | |
| 38 | + | |
| 39 | +Un dossier est lu la première fois que vous l'ouvrez : un arbre sur un gros projet coûte donc une lecture de dossier, pas un parcours complet. | |
| 40 | + | |
| 41 | +## Ouvrir un fichier | |
| 42 | + | |
| 43 | +Placez la surbrillance dessus et appuyez sur `Entrée`, ou cliquez-le deux fois. | |
| 44 | + | |
| 45 | +Le fichier s'ouvre dans une fenêtre à lui, devant l'arbre. Un fichier déjà ouvert est ramené au premier plan plutôt qu'ouvert deux fois. | |
| 46 | + | |
| 47 | +## Voir un fichier créé après l'ouverture de l'arbre | |
| 48 | + | |
| 49 | +L'arbre ne surveille pas le disque. Appuyez sur **`F5`** ou **`Ctrl-R`** avec l'arbre au premier plan : il relit le projet, en gardant ouvert ce que vous aviez ouvert et la surbrillance sur la même entrée. | |
| 50 | + | |
| 51 | +Enregistrer un fichier rafraîchit l'arbre pour vous : un **File ▸ Save as** sous un nouveau nom y apparaît sans rien demander. Un fichier créé autrement — un `go build` dans une fenêtre terminal, ou un `git checkout` — demande la touche de rafraîchissement. | |
| 52 | + | |
| 53 | +## Travailler avec l'arbre et un fichier côte à côte | |
| 54 | + | |
| 55 | +L'arbre est une fenêtre ordinaire, donc toutes les commandes de fenêtre s'y appliquent : | |
| 56 | + | |
| 57 | +- **Window ▸ Tile** place l'arbre et votre fichier côte à côte. | |
| 58 | +- Tirez son coin inférieur droit pour le rétrécir une fois que vous vous y retrouvez. | |
| 59 | +- `[x]` le ferme ; `F9` le ramène. | |
| 60 | + | |
| 61 | +## Variantes | |
| 62 | + | |
| 63 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** L'arbre y est enraciné et ne montre que cette partie du projet. Lancez plutôt depuis le dossier du projet — la même règle que `.turbo-python/settings.toml`. | |
| 64 | +- **Un dossier apparaît ouvert mais vide.** Il n'a pas pu être lu, le plus souvent un problème de permissions. Le reste de l'arbre n'est pas affecté ; corrigez les permissions et appuyez sur `F5`. | |
| 65 | + | |
| 66 | +## Voir aussi | |
| 67 | + | |
| 68 | +- Toutes les touches et tout ce que l'arbre montre, exactement : [Référence de l'arbre du projet](../reference/project-tree.md) | |
| 69 | +- Pourquoi c'est une fenêtre et non un panneau ancré, et pourquoi il ne surveille pas le disque : [Arbre du projet](../explanation/project-tree.md) | |
| 70 | +- Le colorer : [Format des fichiers de thème](../reference/themes.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,70 @@ | |||
| 1 | +# Parcourir un projet et ouvrir des fichiers depuis un arbre | ||
| 2 | + | ||
| 3 | +Ce guide montre comment ouvrir l'arbre du projet, le parcourir et y ouvrir un fichier. Il suppose Turbo Python déjà installé. | ||
| 4 | + | ||
| 5 | +## Ouvrir l'arbre | ||
| 6 | + | ||
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis appuyez sur `F9`, ou choisissez **Window ▸ Project tree**. | ||
| 8 | + | ||
| 9 | +Une fenêtre s'ouvre avec les fichiers du projet, nommée d'après le dossier depuis lequel l'éditeur a été lancé : | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +╔═[x]════════════ turbo-python ════════════2═[■]╗ | ||
| 13 | +║ ▶ .turbo-python ║ | ||
| 14 | +║ ▼ internal ║ | ||
| 15 | +║ ▶ app ║ | ||
| 16 | +║ ▼ ui ║ | ||
| 17 | +║ window.go ║ | ||
| 18 | +║ .gitignore ║ | ||
| 19 | +║ pyproject.toml ║ | ||
| 20 | +║ main.py ║ | ||
| 21 | +╚══════════════════════════════════════════╝ | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +Les dossiers viennent d'abord, puis les fichiers, chaque groupe trié. `.git` est la seule chose masquée — `.turbo-python`, `.gitignore` et les autres sont des fichiers de votre projet, que vous voudrez sans doute ouvrir. | ||
| 25 | + | ||
| 26 | +Appuyer de nouveau sur `F9` ramène cette fenêtre au premier plan plutôt que d'ouvrir un second arbre. | ||
| 27 | + | ||
| 28 | +## Le parcourir | ||
| 29 | + | ||
| 30 | +| Touche | Effet | | ||
| 31 | +| --- | --- | | ||
| 32 | +| `↑` `↓` | Déplacer la surbrillance | | ||
| 33 | +| `→` | Ouvrir un dossier fermé ; sur autre chose, passer à la ligne suivante | | ||
| 34 | +| `←` | Fermer un dossier ouvert ; sur autre chose, remonter au dossier qui le contient | | ||
| 35 | +| `Entrée` | Ouvrir un fichier, ou ouvrir et fermer un dossier | | ||
| 36 | +| `Début` `Fin` | Première / dernière ligne | | ||
| 37 | +| `Page↑` `Page↓` | Un écran à la fois | | ||
| 38 | + | ||
| 39 | +Un dossier est lu la première fois que vous l'ouvrez : un arbre sur un gros projet coûte donc une lecture de dossier, pas un parcours complet. | ||
| 40 | + | ||
| 41 | +## Ouvrir un fichier | ||
| 42 | + | ||
| 43 | +Placez la surbrillance dessus et appuyez sur `Entrée`, ou cliquez-le deux fois. | ||
| 44 | + | ||
| 45 | +Le fichier s'ouvre dans une fenêtre à lui, devant l'arbre. Un fichier déjà ouvert est ramené au premier plan plutôt qu'ouvert deux fois. | ||
| 46 | + | ||
| 47 | +## Voir un fichier créé après l'ouverture de l'arbre | ||
| 48 | + | ||
| 49 | +L'arbre ne surveille pas le disque. Appuyez sur **`F5`** ou **`Ctrl-R`** avec l'arbre au premier plan : il relit le projet, en gardant ouvert ce que vous aviez ouvert et la surbrillance sur la même entrée. | ||
| 50 | + | ||
| 51 | +Enregistrer un fichier rafraîchit l'arbre pour vous : un **File ▸ Save as** sous un nouveau nom y apparaît sans rien demander. Un fichier créé autrement — un `go build` dans une fenêtre terminal, ou un `git checkout` — demande la touche de rafraîchissement. | ||
| 52 | + | ||
| 53 | +## Travailler avec l'arbre et un fichier côte à côte | ||
| 54 | + | ||
| 55 | +L'arbre est une fenêtre ordinaire, donc toutes les commandes de fenêtre s'y appliquent : | ||
| 56 | + | ||
| 57 | +- **Window ▸ Tile** place l'arbre et votre fichier côte à côte. | ||
| 58 | +- Tirez son coin inférieur droit pour le rétrécir une fois que vous vous y retrouvez. | ||
| 59 | +- `[x]` le ferme ; `F9` le ramène. | ||
| 60 | + | ||
| 61 | +## Variantes | ||
| 62 | + | ||
| 63 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** L'arbre y est enraciné et ne montre que cette partie du projet. Lancez plutôt depuis le dossier du projet — la même règle que `.turbo-python/settings.toml`. | ||
| 64 | +- **Un dossier apparaît ouvert mais vide.** Il n'a pas pu être lu, le plus souvent un problème de permissions. Le reste de l'arbre n'est pas affecté ; corrigez les permissions et appuyez sur `F5`. | ||
| 65 | + | ||
| 66 | +## Voir aussi | ||
| 67 | + | ||
| 68 | +- Toutes les touches et tout ce que l'arbre montre, exactement : [Référence de l'arbre du projet](../reference/project-tree.md) | ||
| 69 | +- Pourquoi c'est une fenêtre et non un panneau ancré, et pourquoi il ne surveille pas le disque : [Arbre du projet](../explanation/project-tree.md) | ||
| 70 | +- Le colorer : [Format des fichiers de thème](../reference/themes.md) | ||
added
docs/fr/how-to/configure-a-project.md +83 -0 | new file mode 100644 | ||
| @@ -0,0 +1,83 @@ | ||
| 1 | +# Donner ses propres réglages à un projet | |
| 2 | + | |
| 3 | +Ce guide montre comment fixer un thème et activer la sauvegarde automatique pour un projet, afin que tous ceux qui l'ouvrent aient le même éditeur. Il suppose Turbo Python déjà installé. | |
| 4 | + | |
| 5 | +## Créer le fichier de réglages | |
| 6 | + | |
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **Options ▸ Create project settings**. | |
| 8 | + | |
| 9 | +Cela écrit `.turbo-python/settings.toml`, rempli avec le thème que vous utilisez à cet instant, et l'ouvre pour édition — coloré, puisque Turbo Python colore le TOML : | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +# turbo-python project settings. | |
| 13 | +# | |
| 14 | +# These apply to everyone who opens this project in turbo-python. Delete this file | |
| 15 | +# and the editor falls back to its own defaults. | |
| 16 | + | |
| 17 | +[editor] | |
| 18 | + | |
| 19 | +# The colour theme to start in. `turbo-python -list-themes` lists them all. | |
| 20 | +# A -theme flag on the command line overrides this. | |
| 21 | +theme = "turbo-classic" | |
| 22 | + | |
| 23 | +# Write modified files by themselves, a short while after you stop typing. | |
| 24 | +# On, because a project that has gone to the trouble of having a settings file | |
| 25 | +# has said what it wants; set it to false and save, and it stops at once. | |
| 26 | +autosave = true | |
| 27 | + | |
| 28 | +# How long that while is. Any Go duration: "500ms", "2s", "1m". | |
| 29 | +autosave_delay = "2s" | |
| 30 | +``` | |
| 31 | + | |
| 32 | +Le fichier est lu au démarrage de l'éditeur, et **de nouveau à chaque fois que vous l'enregistrez** — une modification est donc en vigueur dès que vous appuyez sur `F2`. La barre d'état le confirme : `Applied .turbo-python/settings.toml — autosave on (2s)`. | |
| 33 | + | |
| 34 | +Cela vaut pour les réglages que ce fichier contient, pas pour le thème : **Options ▸ Theme** est la façon vivante de le changer, et y réécrit votre choix pour vous. | |
| 35 | + | |
| 36 | +L'entrée de menu que vous venez d'utiliser est maintenant grisée, et **Options ▸ Project settings…** à côté d'elle ne l'est plus. C'est la règle pour les trois fichiers du projet : vous pouvez créer celui que vous n'avez pas, et ouvrir celui que vous avez. | |
| 37 | + | |
| 38 | +## La sauvegarde automatique | |
| 39 | + | |
| 40 | +Elle est déjà active : le fichier qu'on vient de vous donner dit `autosave = true`. | |
| 41 | + | |
| 42 | +Tout fichier qui a un nom est écrit deux secondes après que vous ayez cessé de taper. La barre d'état affiche `Saved main.py` au moment où cela arrive. Rien n'est écrit tant que vous tapez : chaque frappe repousse l'attente. | |
| 43 | + | |
| 44 | +Deux choses changent en conséquence, toutes deux voulues : | |
| 45 | + | |
| 46 | +- **Fermer une fenêtre ne demande plus** s'il faut enregistrer. Le fichier allait l'être de toute façon. | |
| 47 | +- **Quitter l'éditeur ne demande plus** non plus, pour la même raison. | |
| 48 | + | |
| 49 | +Un fichier qui n'a jamais reçu de nom fait exception : la sauvegarde automatique n'ouvre jamais de dialogue, donc une fenêtre sans titre garde son `*` et la question est toujours posée à la fermeture. | |
| 50 | + | |
| 51 | +Pour la désactiver, mettez `autosave` à `false` et enregistrez ; la barre d'état répond `autosave off`, et cela s'arrête à l'instant. Pour attendre plus ou moins longtemps, changez `autosave_delay` : | |
| 52 | + | |
| 53 | +```toml | |
| 54 | +autosave_delay = "500ms" | |
| 55 | +``` | |
| 56 | + | |
| 57 | +## Fixer le thème | |
| 58 | + | |
| 59 | +Donnez à `theme` un nom parmi ceux de `turbo-python -list-themes`, ou choisissez-en un simplement avec **Options ▸ Theme** : dès lors qu'un fichier de réglages existe, choisir un thème l'y écrit pour vous, en conservant vos commentaires et votre mise en page. | |
| 60 | + | |
| 61 | +## Essayer un autre thème sans toucher au fichier | |
| 62 | + | |
| 63 | +Passez `-theme` sur la ligne de commande. Il l'emporte sur le choix du projet, le temps de cette exécution seulement : | |
| 64 | + | |
| 65 | +```bash | |
| 66 | +turbo-python -theme turbo-dark main.py | |
| 67 | +``` | |
| 68 | + | |
| 69 | +## Modifier le fichier plus tard | |
| 70 | + | |
| 71 | +**Options ▸ Project settings…** le rouvre. L'entrée est grisée dans un projet qui n'en a pas. | |
| 72 | + | |
| 73 | +## Variantes | |
| 74 | + | |
| 75 | +- **Vous lancez l'éditeur depuis un sous-dossier.** Les réglages ne sont pas trouvés : seul `./.turbo-python` est consulté, sans remontée vers la racine du projet. Lancez depuis le dossier du projet, ou passez `-theme` pour cette fois. | |
| 76 | +- **Le fichier contient une erreur.** L'éditeur le signale sur la sortie d'erreur et s'ouvre avec ses valeurs par défaut — vous pouvez donc corriger le fichier dans l'éditeur lui-même. | |
| 77 | +- **Vous partagez le projet.** `.turbo-python/settings.toml` est un fichier ordinaire : versionnez-le pour convenir d'un thème en équipe, ou ajoutez-le à `.gitignore` pour le garder pour vous. | |
| 78 | + | |
| 79 | +## Voir aussi | |
| 80 | + | |
| 81 | +- Chaque clé, avec son type et sa valeur par défaut : [Référence des réglages de projet](../reference/project-settings.md) | |
| 82 | +- Pourquoi le fichier n'est pas cherché dans les dossiers parents, et pourquoi l'autosave attend : [Réglages de projet](../explanation/project-settings.md) | |
| 83 | +- Écrire un thème à fixer : [Écrire son propre thème](write-a-theme.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,83 @@ | |||
| 1 | +# Donner ses propres réglages à un projet | ||
| 2 | + | ||
| 3 | +Ce guide montre comment fixer un thème et activer la sauvegarde automatique pour un projet, afin que tous ceux qui l'ouvrent aient le même éditeur. Il suppose Turbo Python déjà installé. | ||
| 4 | + | ||
| 5 | +## Créer le fichier de réglages | ||
| 6 | + | ||
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **Options ▸ Create project settings**. | ||
| 8 | + | ||
| 9 | +Cela écrit `.turbo-python/settings.toml`, rempli avec le thème que vous utilisez à cet instant, et l'ouvre pour édition — coloré, puisque Turbo Python colore le TOML : | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +# turbo-python project settings. | ||
| 13 | +# | ||
| 14 | +# These apply to everyone who opens this project in turbo-python. Delete this file | ||
| 15 | +# and the editor falls back to its own defaults. | ||
| 16 | + | ||
| 17 | +[editor] | ||
| 18 | + | ||
| 19 | +# The colour theme to start in. `turbo-python -list-themes` lists them all. | ||
| 20 | +# A -theme flag on the command line overrides this. | ||
| 21 | +theme = "turbo-classic" | ||
| 22 | + | ||
| 23 | +# Write modified files by themselves, a short while after you stop typing. | ||
| 24 | +# On, because a project that has gone to the trouble of having a settings file | ||
| 25 | +# has said what it wants; set it to false and save, and it stops at once. | ||
| 26 | +autosave = true | ||
| 27 | + | ||
| 28 | +# How long that while is. Any Go duration: "500ms", "2s", "1m". | ||
| 29 | +autosave_delay = "2s" | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +Le fichier est lu au démarrage de l'éditeur, et **de nouveau à chaque fois que vous l'enregistrez** — une modification est donc en vigueur dès que vous appuyez sur `F2`. La barre d'état le confirme : `Applied .turbo-python/settings.toml — autosave on (2s)`. | ||
| 33 | + | ||
| 34 | +Cela vaut pour les réglages que ce fichier contient, pas pour le thème : **Options ▸ Theme** est la façon vivante de le changer, et y réécrit votre choix pour vous. | ||
| 35 | + | ||
| 36 | +L'entrée de menu que vous venez d'utiliser est maintenant grisée, et **Options ▸ Project settings…** à côté d'elle ne l'est plus. C'est la règle pour les trois fichiers du projet : vous pouvez créer celui que vous n'avez pas, et ouvrir celui que vous avez. | ||
| 37 | + | ||
| 38 | +## La sauvegarde automatique | ||
| 39 | + | ||
| 40 | +Elle est déjà active : le fichier qu'on vient de vous donner dit `autosave = true`. | ||
| 41 | + | ||
| 42 | +Tout fichier qui a un nom est écrit deux secondes après que vous ayez cessé de taper. La barre d'état affiche `Saved main.py` au moment où cela arrive. Rien n'est écrit tant que vous tapez : chaque frappe repousse l'attente. | ||
| 43 | + | ||
| 44 | +Deux choses changent en conséquence, toutes deux voulues : | ||
| 45 | + | ||
| 46 | +- **Fermer une fenêtre ne demande plus** s'il faut enregistrer. Le fichier allait l'être de toute façon. | ||
| 47 | +- **Quitter l'éditeur ne demande plus** non plus, pour la même raison. | ||
| 48 | + | ||
| 49 | +Un fichier qui n'a jamais reçu de nom fait exception : la sauvegarde automatique n'ouvre jamais de dialogue, donc une fenêtre sans titre garde son `*` et la question est toujours posée à la fermeture. | ||
| 50 | + | ||
| 51 | +Pour la désactiver, mettez `autosave` à `false` et enregistrez ; la barre d'état répond `autosave off`, et cela s'arrête à l'instant. Pour attendre plus ou moins longtemps, changez `autosave_delay` : | ||
| 52 | + | ||
| 53 | +```toml | ||
| 54 | +autosave_delay = "500ms" | ||
| 55 | +``` | ||
| 56 | + | ||
| 57 | +## Fixer le thème | ||
| 58 | + | ||
| 59 | +Donnez à `theme` un nom parmi ceux de `turbo-python -list-themes`, ou choisissez-en un simplement avec **Options ▸ Theme** : dès lors qu'un fichier de réglages existe, choisir un thème l'y écrit pour vous, en conservant vos commentaires et votre mise en page. | ||
| 60 | + | ||
| 61 | +## Essayer un autre thème sans toucher au fichier | ||
| 62 | + | ||
| 63 | +Passez `-theme` sur la ligne de commande. Il l'emporte sur le choix du projet, le temps de cette exécution seulement : | ||
| 64 | + | ||
| 65 | +```bash | ||
| 66 | +turbo-python -theme turbo-dark main.py | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +## Modifier le fichier plus tard | ||
| 70 | + | ||
| 71 | +**Options ▸ Project settings…** le rouvre. L'entrée est grisée dans un projet qui n'en a pas. | ||
| 72 | + | ||
| 73 | +## Variantes | ||
| 74 | + | ||
| 75 | +- **Vous lancez l'éditeur depuis un sous-dossier.** Les réglages ne sont pas trouvés : seul `./.turbo-python` est consulté, sans remontée vers la racine du projet. Lancez depuis le dossier du projet, ou passez `-theme` pour cette fois. | ||
| 76 | +- **Le fichier contient une erreur.** L'éditeur le signale sur la sortie d'erreur et s'ouvre avec ses valeurs par défaut — vous pouvez donc corriger le fichier dans l'éditeur lui-même. | ||
| 77 | +- **Vous partagez le projet.** `.turbo-python/settings.toml` est un fichier ordinaire : versionnez-le pour convenir d'un thème en équipe, ou ajoutez-le à `.gitignore` pour le garder pour vous. | ||
| 78 | + | ||
| 79 | +## Voir aussi | ||
| 80 | + | ||
| 81 | +- Chaque clé, avec son type et sa valeur par défaut : [Référence des réglages de projet](../reference/project-settings.md) | ||
| 82 | +- Pourquoi le fichier n'est pas cherché dans les dossiers parents, et pourquoi l'autosave attend : [Réglages de projet](../explanation/project-settings.md) | ||
| 83 | +- Écrire un thème à fixer : [Écrire son propre thème](write-a-theme.md) | ||
added
docs/fr/how-to/enable-completion.md +95 -0 | new file mode 100644 | ||
| @@ -0,0 +1,95 @@ | ||
| 1 | +# Activer la complétion Python | |
| 2 | + | |
| 3 | +Ce guide montre comment faire fonctionner la complétion, les descriptions de symboles et le saut à la définition. Il suppose que Turbo Python est déjà installé et que vous savez ce qu'est un projet Python. | |
| 4 | + | |
| 5 | +La complétion vient de **pylsp**, le serveur de langage officiel de Python. Turbo Python ne l'embarque pas : l'édition et la coloration fonctionnent sans lui, et seule la complétion est perdue. | |
| 6 | + | |
| 7 | +## 1. Installer pylsp | |
| 8 | + | |
| 9 | +```bash | |
| 10 | +pipx component add pylsp | |
| 11 | +``` | |
| 12 | + | |
| 13 | +## 2. S'assurer que Turbo Python le trouve | |
| 14 | + | |
| 15 | +Turbo Python cherche d'abord dans le `PATH`, puis dans `$GOBIN`, puis dans `$GOPATH/bin`. `go install` écrit dans le dernier, qui n'est très souvent pas dans le `PATH` — c'est pourquoi cela marche en général sans rien faire de plus. Pour vérifier : | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +pylsp version | |
| 19 | +``` | |
| 20 | + | |
| 21 | +Si cette commande répond « introuvable » alors que Turbo Python le trouve quand même, c'est normal et sans conséquence. | |
| 22 | + | |
| 23 | +## 3. Ouvrir un fichier à l'intérieur d'un module | |
| 24 | + | |
| 25 | +```bash | |
| 26 | +cd /chemin/vers/votre/module # le répertoire qui contient pyproject.toml | |
| 27 | +turbo-python main.py | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Turbo Python remonte l'arborescence depuis le fichier à la recherche d'un `pyproject.toml` et démarre pylsp dans le répertoire trouvé. **Hors d'un module, pylsp n'a presque rien à dire** — c'est la raison la plus fréquente pour laquelle la complétion semble ne pas fonctionner. | |
| 31 | + | |
| 32 | +## 4. Demander une complétion | |
| 33 | + | |
| 34 | +Placez le curseur après un point et appuyez sur **Ctrl-Espace** : | |
| 35 | + | |
| 36 | +```go | |
| 37 | +fmt. | |
| 38 | +``` | |
| 39 | + | |
| 40 | +Une liste se déroule sous le curseur. Continuez à taper pour la restreindre, **↑ ↓** pour la parcourir, **Entrée** ou **Tab** pour accepter, **Échap** pour l'abandonner. | |
| 41 | + | |
| 42 | +Taper un `.` demande une complétion tout seul : la plupart du temps, vous n'appuyez sur rien. | |
| 43 | + | |
| 44 | +## Savoir ce que fait le serveur | |
| 45 | + | |
| 46 | +L'extrémité droite de la barre d'état indique l'état du serveur de langage : `LSP: starting…`, `LSP: ready`, ou la raison pour laquelle il n'y en a pas. `Run ▸ Language server status` affiche la même chose dans une boîte. | |
| 47 | + | |
| 48 | +## Variantes | |
| 49 | + | |
| 50 | +**Vous ne voulez pas de serveur de langage du tout :** | |
| 51 | + | |
| 52 | +```bash | |
| 53 | +turbo-python -no-lsp main.py | |
| 54 | +``` | |
| 55 | + | |
| 56 | +**La complétion est morte dans une fenêtre née sans nom.** Une fenêtre « Untitled » n'a aucun fichier à annoncer à pylsp tant qu'elle n'est pas enregistrée — appuyez sur **F2** et donnez-lui un nom en `.py`, quelque part sous le projet. Dès cette sauvegarde, la complétion, le survol et les marques d'erreur fonctionnent dans cette fenêtre ; inutile de quitter et relancer l'éditeur. | |
| 57 | + | |
| 58 | +**La complétion est vide dans un fichier qui compile.** pylsp a besoin que le paquet du fichier se construise. Vérifiez d'abord `uv sync` — un paquet qui ne compile pas ne donne souvent rien d'utile. | |
| 59 | + | |
| 60 | +**La première complétion sur un gros module est lente.** pylsp charge le graphe du module. La barre d'état affiche `LSP: starting…` jusqu'à ce qu'il soit prêt ; les requêtes faites avant sont refusées plutôt que mises en file. | |
| 61 | + | |
| 62 | +**Une requête met trop de temps.** Chaque requête abandonne au bout de trois secondes : un serveur bloqué ralentit l'éditeur mais ne le fige jamais. La barre d'état signale l'échec. | |
| 63 | + | |
| 64 | +**La liste est vide dans un fichier qui ne compile pas.** pylsp ne répond *rien du tout* — pas d'erreur, une liste vide — pour un paquet qu'il ne peut pas charger. Une déclaration en double ou un import non résolu suffit. L'éditeur indique désormais quel problème fait obstacle : | |
| 65 | + | |
| 66 | +``` | |
| 67 | +No completions — this file does not compile: main redeclared in this block | |
| 68 | +``` | |
| 69 | + | |
| 70 | +`Run ▸ Language server status` affiche la même chose, avec le chemin du serveur, la racine du projet et l'information de savoir si ce fichier lui a été annoncé. Corrigez d'abord le paquet — `uv sync` est la vérification la plus rapide. | |
| 71 | + | |
| 72 | +**Ctrl-Espace ne fait rien.** tmux, screen et les terminaux intégrés d'IDE interceptent très souvent `Ctrl-Espace` avant l'éditeur. Tapez plutôt un `.`, qui demande une complétion tout seul, ou passez par `Run ▸ Completion`. | |
| 73 | + | |
| 74 | +## Ce que le serveur apporte d'autre | |
| 75 | + | |
| 76 | +La complétion est ce qu'il fait de plus bruyant et le moindre de ce qu'il sait. La même connexion répond à huit autres questions, toutes dans le menu **Code** et toutes à propos du symbole sous le curseur — aucune sélection n'est nécessaire. | |
| 77 | + | |
| 78 | +| Touche | Effet | | |
| 79 | +| --- | --- | | |
| 80 | +| **Ctrl-Espace** | Liste de complétion | | |
| 81 | +| **F1** | Décrire le symbole sous le curseur | | |
| 82 | +| **F12** | Sauter là où il est déclaré | | |
| 83 | +| **Shift-F12** | Lister partout où il est utilisé | | |
| 84 | +| **Ctrl-T** | Trouver un symbole par son nom dans tout le projet | | |
| 85 | + | |
| 86 | +Et, sans touche : *Go to type definition*, *Find implementations…*, *Symbol in file…* et *Problems…*. | |
| 87 | + | |
| 88 | +Les problèmes qu'il trouve arrivent sans qu'on demande. La première erreur du fichier que vous éditez apparaît à droite de la barre d'état, précédée de `⚠` ; chaque ligne à problème reçoit une marque dans la gouttière (`×` pour une erreur, `!` pour un avertissement) ; et **Code ▸ Problems…** les liste tous, pour tous les fichiers que le serveur a chargés. | |
| 89 | + | |
| 90 | +[Comment interroger le code](ask-about-code.md) parcourt l'ensemble. | |
| 91 | + | |
| 92 | +## Voir aussi | |
| 93 | + | |
| 94 | +- Pourquoi le serveur est optionnel : [Coloration et complétion](../explanation/colouring-and-completion.md) | |
| 95 | +- Toutes les touches : [référence du clavier](../reference/keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | +# Activer la complétion Python | ||
| 2 | + | ||
| 3 | +Ce guide montre comment faire fonctionner la complétion, les descriptions de symboles et le saut à la définition. Il suppose que Turbo Python est déjà installé et que vous savez ce qu'est un projet Python. | ||
| 4 | + | ||
| 5 | +La complétion vient de **pylsp**, le serveur de langage officiel de Python. Turbo Python ne l'embarque pas : l'édition et la coloration fonctionnent sans lui, et seule la complétion est perdue. | ||
| 6 | + | ||
| 7 | +## 1. Installer pylsp | ||
| 8 | + | ||
| 9 | +```bash | ||
| 10 | +pipx component add pylsp | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +## 2. S'assurer que Turbo Python le trouve | ||
| 14 | + | ||
| 15 | +Turbo Python cherche d'abord dans le `PATH`, puis dans `$GOBIN`, puis dans `$GOPATH/bin`. `go install` écrit dans le dernier, qui n'est très souvent pas dans le `PATH` — c'est pourquoi cela marche en général sans rien faire de plus. Pour vérifier : | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +pylsp version | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +Si cette commande répond « introuvable » alors que Turbo Python le trouve quand même, c'est normal et sans conséquence. | ||
| 22 | + | ||
| 23 | +## 3. Ouvrir un fichier à l'intérieur d'un module | ||
| 24 | + | ||
| 25 | +```bash | ||
| 26 | +cd /chemin/vers/votre/module # le répertoire qui contient pyproject.toml | ||
| 27 | +turbo-python main.py | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Turbo Python remonte l'arborescence depuis le fichier à la recherche d'un `pyproject.toml` et démarre pylsp dans le répertoire trouvé. **Hors d'un module, pylsp n'a presque rien à dire** — c'est la raison la plus fréquente pour laquelle la complétion semble ne pas fonctionner. | ||
| 31 | + | ||
| 32 | +## 4. Demander une complétion | ||
| 33 | + | ||
| 34 | +Placez le curseur après un point et appuyez sur **Ctrl-Espace** : | ||
| 35 | + | ||
| 36 | +```go | ||
| 37 | +fmt. | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +Une liste se déroule sous le curseur. Continuez à taper pour la restreindre, **↑ ↓** pour la parcourir, **Entrée** ou **Tab** pour accepter, **Échap** pour l'abandonner. | ||
| 41 | + | ||
| 42 | +Taper un `.` demande une complétion tout seul : la plupart du temps, vous n'appuyez sur rien. | ||
| 43 | + | ||
| 44 | +## Savoir ce que fait le serveur | ||
| 45 | + | ||
| 46 | +L'extrémité droite de la barre d'état indique l'état du serveur de langage : `LSP: starting…`, `LSP: ready`, ou la raison pour laquelle il n'y en a pas. `Run ▸ Language server status` affiche la même chose dans une boîte. | ||
| 47 | + | ||
| 48 | +## Variantes | ||
| 49 | + | ||
| 50 | +**Vous ne voulez pas de serveur de langage du tout :** | ||
| 51 | + | ||
| 52 | +```bash | ||
| 53 | +turbo-python -no-lsp main.py | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +**La complétion est morte dans une fenêtre née sans nom.** Une fenêtre « Untitled » n'a aucun fichier à annoncer à pylsp tant qu'elle n'est pas enregistrée — appuyez sur **F2** et donnez-lui un nom en `.py`, quelque part sous le projet. Dès cette sauvegarde, la complétion, le survol et les marques d'erreur fonctionnent dans cette fenêtre ; inutile de quitter et relancer l'éditeur. | ||
| 57 | + | ||
| 58 | +**La complétion est vide dans un fichier qui compile.** pylsp a besoin que le paquet du fichier se construise. Vérifiez d'abord `uv sync` — un paquet qui ne compile pas ne donne souvent rien d'utile. | ||
| 59 | + | ||
| 60 | +**La première complétion sur un gros module est lente.** pylsp charge le graphe du module. La barre d'état affiche `LSP: starting…` jusqu'à ce qu'il soit prêt ; les requêtes faites avant sont refusées plutôt que mises en file. | ||
| 61 | + | ||
| 62 | +**Une requête met trop de temps.** Chaque requête abandonne au bout de trois secondes : un serveur bloqué ralentit l'éditeur mais ne le fige jamais. La barre d'état signale l'échec. | ||
| 63 | + | ||
| 64 | +**La liste est vide dans un fichier qui ne compile pas.** pylsp ne répond *rien du tout* — pas d'erreur, une liste vide — pour un paquet qu'il ne peut pas charger. Une déclaration en double ou un import non résolu suffit. L'éditeur indique désormais quel problème fait obstacle : | ||
| 65 | + | ||
| 66 | +``` | ||
| 67 | +No completions — this file does not compile: main redeclared in this block | ||
| 68 | +``` | ||
| 69 | + | ||
| 70 | +`Run ▸ Language server status` affiche la même chose, avec le chemin du serveur, la racine du projet et l'information de savoir si ce fichier lui a été annoncé. Corrigez d'abord le paquet — `uv sync` est la vérification la plus rapide. | ||
| 71 | + | ||
| 72 | +**Ctrl-Espace ne fait rien.** tmux, screen et les terminaux intégrés d'IDE interceptent très souvent `Ctrl-Espace` avant l'éditeur. Tapez plutôt un `.`, qui demande une complétion tout seul, ou passez par `Run ▸ Completion`. | ||
| 73 | + | ||
| 74 | +## Ce que le serveur apporte d'autre | ||
| 75 | + | ||
| 76 | +La complétion est ce qu'il fait de plus bruyant et le moindre de ce qu'il sait. La même connexion répond à huit autres questions, toutes dans le menu **Code** et toutes à propos du symbole sous le curseur — aucune sélection n'est nécessaire. | ||
| 77 | + | ||
| 78 | +| Touche | Effet | | ||
| 79 | +| --- | --- | | ||
| 80 | +| **Ctrl-Espace** | Liste de complétion | | ||
| 81 | +| **F1** | Décrire le symbole sous le curseur | | ||
| 82 | +| **F12** | Sauter là où il est déclaré | | ||
| 83 | +| **Shift-F12** | Lister partout où il est utilisé | | ||
| 84 | +| **Ctrl-T** | Trouver un symbole par son nom dans tout le projet | | ||
| 85 | + | ||
| 86 | +Et, sans touche : *Go to type definition*, *Find implementations…*, *Symbol in file…* et *Problems…*. | ||
| 87 | + | ||
| 88 | +Les problèmes qu'il trouve arrivent sans qu'on demande. La première erreur du fichier que vous éditez apparaît à droite de la barre d'état, précédée de `⚠` ; chaque ligne à problème reçoit une marque dans la gouttière (`×` pour une erreur, `!` pour un avertissement) ; et **Code ▸ Problems…** les liste tous, pour tous les fichiers que le serveur a chargés. | ||
| 89 | + | ||
| 90 | +[Comment interroger le code](ask-about-code.md) parcourt l'ensemble. | ||
| 91 | + | ||
| 92 | +## Voir aussi | ||
| 93 | + | ||
| 94 | +- Pourquoi le serveur est optionnel : [Coloration et complétion](../explanation/colouring-and-completion.md) | ||
| 95 | +- Toutes les touches : [référence du clavier](../reference/keyboard.md) | ||
added
docs/fr/how-to/install.md +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 1 | +# Installer et compiler Turbo Python | |
| 2 | + | |
| 3 | +Ce guide montre comment obtenir un binaire `turbo-python` fonctionnel. Il suppose que vous avez Go 1.26 ou plus récent et que vous savez utiliser un terminal. | |
| 4 | + | |
| 5 | +## La voie rapide, depuis un clone | |
| 6 | + | |
| 7 | +```bash | |
| 8 | +git clone ssh://git@rickub.com/turbo-editors/turbo-python.git | |
| 9 | +cd turbo-python | |
| 10 | +make install | |
| 11 | +``` | |
| 12 | + | |
| 13 | +Cela compile l'éditeur, le place là où votre shell cherche ses commandes, et vous dit ce qu'il a trouvé : la version de Go, où le binaire a été posé, si ce répertoire est dans votre `PATH`, et si `pylsp` est installé. La compilation passe d'abord par un fichier temporaire : un échec ne remplace jamais une installation qui marchait. | |
| 14 | + | |
| 15 | +Ensuite, depuis n'importe quel projet Python : | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +turbo-python main.py | |
| 19 | +``` | |
| 20 | + | |
| 21 | +### Options | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +scripts/install.sh --prefix ~/bin # installer ailleurs | |
| 25 | +scripts/install.sh --with-pylsp # installer aussi le serveur de langage | |
| 26 | +scripts/install.sh --uninstall # le retirer (make uninstall) | |
| 27 | +scripts/install.sh --help | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Sans `--prefix`, l'éditeur va là où `go install` le mettrait : `$GOBIN`, ou `$GOPATH/bin` si `GOBIN` n'est pas défini — le plus souvent `~/go/bin`. | |
| 31 | + | |
| 32 | +## Seulement compiler, sans installer | |
| 33 | + | |
| 34 | +```bash | |
| 35 | +make build | |
| 36 | +./bin/turbo-python main.py | |
| 37 | +``` | |
| 38 | + | |
| 39 | +## Depuis le proxy de modules, sans clone | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +go install rickub.com/turbo-editors/turbo-python@latest | |
| 43 | +``` | |
| 44 | + | |
| 45 | +Si la commande est ensuite « introuvable », c'est que le répertoire d'installation n'est pas dans votre `PATH` : | |
| 46 | + | |
| 47 | +```bash | |
| 48 | +export PATH="$PATH:$(go env GOPATH)/bin" | |
| 49 | +``` | |
| 50 | + | |
| 51 | +## Vérifier que ça marche | |
| 52 | + | |
| 53 | +```bash | |
| 54 | +turbo-python -version | |
| 55 | +turbo-python -list-themes | |
| 56 | +``` | |
| 57 | + | |
| 58 | +La première nomme le commit dont le binaire a été construit, ce qu'il faut citer dans un rapport de bug ; [le numéro de version](../reference/versioning.md) explique ce que signifie chaque forme. La seconde affiche les thèmes compilés dans le binaire et vous indique où placer les vôtres. | |
| 59 | + | |
| 60 | +## Variantes | |
| 61 | + | |
| 62 | +- **Vous voulez juste l'essayer une fois** : `go run rickub.com/turbo-editors/turbo-python@latest main.py` | |
| 63 | +- **Vous voulez le binaire à un endroit précis** : `go build -o /usr/local/bin/turbo-python .` | |
| 64 | +- **Votre terminal ne gère pas les couleurs 24 bits** : utilisez `turbo-python -theme turbo-classic`, construit uniquement sur les seize couleurs ANSI. `turbo-dark` et `borland-light` utilisent des couleurs 24 bits. | |
| 65 | + | |
| 66 | +## Quand quelque chose ne va pas | |
| 67 | + | |
| 68 | +**`the installed binary does not run`.** L'installeur affiche juste au-dessus ce que le système a répondu — lisez-le d'abord, c'est lui qui nomme le vrai problème. | |
| 69 | + | |
| 70 | +L'installeur **remplace** le binaire au lieu d'écrire par-dessus celui qui est là : une réinstallation donne donc au fichier une identité neuve. Cela compte sous macOS, qui met en cache la signature de code d'un binaire **par inode** : écrire de nouveaux octets dans l'ancien inode laisse une signature en cache qui décrit autre chose, et le noyau refuse alors d'exécuter un binaire qui s'est pourtant compilé et installé sans erreur. Si une ancienne copie a été installée par un outil qui employait `cp`, la supprimer d'abord efface cet état : | |
| 71 | + | |
| 72 | +```bash | |
| 73 | +scripts/install.sh --uninstall | |
| 74 | +scripts/install.sh | |
| 75 | +``` | |
| 76 | + | |
| 77 | +**`Go x.y or later is needed`.** La version vient de `pyproject.toml` : elle ne peut donc pas diverger de ce dont le code a réellement besoin. Mettez Go à jour, ou compilez depuis une étiquette correspondant à la chaîne d'outils dont vous disposez. | |
| 78 | + | |
| 79 | +**`build failed; nothing was installed`.** Votre installation existante est intacte — la compilation passe d'abord par un fichier temporaire. La sortie du compilateur est affichée au-dessus du message. | |
| 80 | + | |
| 81 | +## Exigences côté terminal | |
| 82 | + | |
| 83 | +Turbo Python a besoin d'un terminal qui rapporte sa taille et gère la souris — tous les terminaux courants le font. Il lit `TERM` via tcell ; si l'affichage est incorrect, vérifiez que `TERM` correspond bien à votre terminal (`xterm-256color` est une valeur sûre). | |
| 84 | + | |
| 85 | +## Voir aussi | |
| 86 | + | |
| 87 | +- Toutes les options : [référence de la ligne de commande](../reference/cli.md) | |
| 88 | +- Faire marcher la complétion : [Activer la complétion Python](enable-completion.md) | |
| 89 | +- Une première session guidée : [Votre premier fichier dans Turbo Python](../tutorials/getting-started.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# Installer et compiler Turbo Python | ||
| 2 | + | ||
| 3 | +Ce guide montre comment obtenir un binaire `turbo-python` fonctionnel. Il suppose que vous avez Go 1.26 ou plus récent et que vous savez utiliser un terminal. | ||
| 4 | + | ||
| 5 | +## La voie rapide, depuis un clone | ||
| 6 | + | ||
| 7 | +```bash | ||
| 8 | +git clone ssh://git@rickub.com/turbo-editors/turbo-python.git | ||
| 9 | +cd turbo-python | ||
| 10 | +make install | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +Cela compile l'éditeur, le place là où votre shell cherche ses commandes, et vous dit ce qu'il a trouvé : la version de Go, où le binaire a été posé, si ce répertoire est dans votre `PATH`, et si `pylsp` est installé. La compilation passe d'abord par un fichier temporaire : un échec ne remplace jamais une installation qui marchait. | ||
| 14 | + | ||
| 15 | +Ensuite, depuis n'importe quel projet Python : | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +turbo-python main.py | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +### Options | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +scripts/install.sh --prefix ~/bin # installer ailleurs | ||
| 25 | +scripts/install.sh --with-pylsp # installer aussi le serveur de langage | ||
| 26 | +scripts/install.sh --uninstall # le retirer (make uninstall) | ||
| 27 | +scripts/install.sh --help | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Sans `--prefix`, l'éditeur va là où `go install` le mettrait : `$GOBIN`, ou `$GOPATH/bin` si `GOBIN` n'est pas défini — le plus souvent `~/go/bin`. | ||
| 31 | + | ||
| 32 | +## Seulement compiler, sans installer | ||
| 33 | + | ||
| 34 | +```bash | ||
| 35 | +make build | ||
| 36 | +./bin/turbo-python main.py | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +## Depuis le proxy de modules, sans clone | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +go install rickub.com/turbo-editors/turbo-python@latest | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +Si la commande est ensuite « introuvable », c'est que le répertoire d'installation n'est pas dans votre `PATH` : | ||
| 46 | + | ||
| 47 | +```bash | ||
| 48 | +export PATH="$PATH:$(go env GOPATH)/bin" | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +## Vérifier que ça marche | ||
| 52 | + | ||
| 53 | +```bash | ||
| 54 | +turbo-python -version | ||
| 55 | +turbo-python -list-themes | ||
| 56 | +``` | ||
| 57 | + | ||
| 58 | +La première nomme le commit dont le binaire a été construit, ce qu'il faut citer dans un rapport de bug ; [le numéro de version](../reference/versioning.md) explique ce que signifie chaque forme. La seconde affiche les thèmes compilés dans le binaire et vous indique où placer les vôtres. | ||
| 59 | + | ||
| 60 | +## Variantes | ||
| 61 | + | ||
| 62 | +- **Vous voulez juste l'essayer une fois** : `go run rickub.com/turbo-editors/turbo-python@latest main.py` | ||
| 63 | +- **Vous voulez le binaire à un endroit précis** : `go build -o /usr/local/bin/turbo-python .` | ||
| 64 | +- **Votre terminal ne gère pas les couleurs 24 bits** : utilisez `turbo-python -theme turbo-classic`, construit uniquement sur les seize couleurs ANSI. `turbo-dark` et `borland-light` utilisent des couleurs 24 bits. | ||
| 65 | + | ||
| 66 | +## Quand quelque chose ne va pas | ||
| 67 | + | ||
| 68 | +**`the installed binary does not run`.** L'installeur affiche juste au-dessus ce que le système a répondu — lisez-le d'abord, c'est lui qui nomme le vrai problème. | ||
| 69 | + | ||
| 70 | +L'installeur **remplace** le binaire au lieu d'écrire par-dessus celui qui est là : une réinstallation donne donc au fichier une identité neuve. Cela compte sous macOS, qui met en cache la signature de code d'un binaire **par inode** : écrire de nouveaux octets dans l'ancien inode laisse une signature en cache qui décrit autre chose, et le noyau refuse alors d'exécuter un binaire qui s'est pourtant compilé et installé sans erreur. Si une ancienne copie a été installée par un outil qui employait `cp`, la supprimer d'abord efface cet état : | ||
| 71 | + | ||
| 72 | +```bash | ||
| 73 | +scripts/install.sh --uninstall | ||
| 74 | +scripts/install.sh | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +**`Go x.y or later is needed`.** La version vient de `pyproject.toml` : elle ne peut donc pas diverger de ce dont le code a réellement besoin. Mettez Go à jour, ou compilez depuis une étiquette correspondant à la chaîne d'outils dont vous disposez. | ||
| 78 | + | ||
| 79 | +**`build failed; nothing was installed`.** Votre installation existante est intacte — la compilation passe d'abord par un fichier temporaire. La sortie du compilateur est affichée au-dessus du message. | ||
| 80 | + | ||
| 81 | +## Exigences côté terminal | ||
| 82 | + | ||
| 83 | +Turbo Python a besoin d'un terminal qui rapporte sa taille et gère la souris — tous les terminaux courants le font. Il lit `TERM` via tcell ; si l'affichage est incorrect, vérifiez que `TERM` correspond bien à votre terminal (`xterm-256color` est une valeur sûre). | ||
| 84 | + | ||
| 85 | +## Voir aussi | ||
| 86 | + | ||
| 87 | +- Toutes les options : [référence de la ligne de commande](../reference/cli.md) | ||
| 88 | +- Faire marcher la complétion : [Activer la complétion Python](enable-completion.md) | ||
| 89 | +- Une première session guidée : [Votre premier fichier dans Turbo Python](../tutorials/getting-started.md) | ||
added
docs/fr/how-to/make-a-release.md +103 -0 | new file mode 100644 | ||
| @@ -0,0 +1,103 @@ | ||
| 1 | +# Comment faire une release | |
| 2 | + | |
| 3 | +Ce guide montre comment publier une version pour que l'éditeur annonce correctement la sienne. Il suppose que vous pouvez pousser sur le dépôt. | |
| 4 | + | |
| 5 | +## Vérifier ce que vous vous apprêtez à publier | |
| 6 | + | |
| 7 | +```sh | |
| 8 | +make version | |
| 9 | +``` | |
| 10 | + | |
| 11 | +``` | |
| 12 | +v0.1.0-14-g88a4c38 (88a4c38) | |
| 13 | +``` | |
| 14 | + | |
| 15 | +Quatorze commits après `v0.1.0`. Un `-dirty` à la fin signifie que vous avez des modifications non validées — validez-les ou mettez-les de côté d'abord, sinon la release portera ce suffixe pour toujours. | |
| 16 | + | |
| 17 | +## Poser le tag | |
| 18 | + | |
| 19 | +```sh | |
| 20 | +git tag -a v0.2.0 -m "v0.2.0" | |
| 21 | +git push origin v0.2.0 | |
| 22 | +``` | |
| 23 | + | |
| 24 | +Le tag est l'origine du numéro : il doit exister avant de construire quoi que ce soit destiné à être distribué. Annoté (`-a`) plutôt que léger, parce que `git describe` préfère les tags annotés. | |
| 25 | + | |
| 26 | +## Construire le binaire de release | |
| 27 | + | |
| 28 | +```sh | |
| 29 | +make build | |
| 30 | +./bin/turbo-python -version | |
| 31 | +``` | |
| 32 | + | |
| 33 | +``` | |
| 34 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | |
| 35 | +``` | |
| 36 | + | |
| 37 | +Pas de suffixe `-14-g…` : vous êtes exactement sur le tag. C'est ce qui vous dit que le tag a bien été pris. | |
| 38 | + | |
| 39 | +## Vérifier la boîte About | |
| 40 | + | |
| 41 | +Lancez l'éditeur et faites `Alt-H`, puis `A`. | |
| 42 | + | |
| 43 | +``` | |
| 44 | +Turbo Python 0.2.0 | |
| 45 | + | |
| 46 | +A Turbo C-style editor for Python, | |
| 47 | +written in Go. | |
| 48 | + | |
| 49 | +Commit: 88a4c38 | |
| 50 | +Built: 2026-08-31 18:04 UTC | |
| 51 | +Theme: Turbo Classic | |
| 52 | +``` | |
| 53 | + | |
| 54 | +## Ou utiliser les scripts et laisser le workflow publier | |
| 55 | + | |
| 56 | +C'est ainsi qu'une release est réellement faite. Mettez la version et sa description d'une ligne dans `release.env` — il est ignoré par git, donc la CI ne le voit jamais : | |
| 57 | + | |
| 58 | +```sh | |
| 59 | +TAG="v1.0.0" | |
| 60 | +ABOUT="Turbo Python" | |
| 61 | +``` | |
| 62 | + | |
| 63 | +Puis lancez un seul script : | |
| 64 | + | |
| 65 | +```sh | |
| 66 | +./01-release.tag.sh | |
| 67 | +``` | |
| 68 | + | |
| 69 | +Il lance `make check`, refuse un tag déjà pris en local ou sur `origin`, refuse un `go.mod` portant une directive `replace`, valide ce qui reste à valider, pousse la branche, et seulement ensuite pose le tag et le pousse. Cet ordre compte : un tag poussé avant la branche pointe sur un commit que le distant n'a jamais vu, et un tag créé avant un push refusé reste là pour que quelqu'un le trouve. | |
| 70 | + | |
| 71 | +C'est la dernière chose que vous lancez à la main. Le push du tag déclenche `.github/workflows/release.yml` ; suivez-le dans l'onglet Actions du dépôt. Il lance la suite de tests, compile les binaires avec `./02-build-releases.sh` — le même script que vous pouvez lancer sur votre machine — et crée la page de release avec : le message du tag, la ligne `go install`, les liens vers la documentation **à ce tag**, un binaire par plateforme, le `SHA256SUMS` et le README qui décrit les téléchargements. | |
| 72 | + | |
| 73 | +Le job publie avec son propre `GITHUB_TOKEN`, la seule authentification que l'API de release de Rickub accepte — un jeton personnel est refusé. Il n'y a rien à configurer et aucun secret à garder, ce qui explique la disparition des anciens `02-release.publish.sh` et `04-release.upload-binaries.sh`. | |
| 74 | + | |
| 75 | +`02-build-releases.sh` compile chaque plateforme et **estampille `TAG` lui-même**, en surchargeant la version du Makefile : `make ldflags VERSION=v1.0.0`. La release *est* `v1.0.0`, donc c'est ce que disent ses binaires — quoi qu'aurait répondu `git describe`, et que le tag existe déjà ou non. Il lance ensuite le binaire préparé pour cette machine et vérifie qu'il annonce bien la version : c'est la seule preuve que ce qui est distribué la porte. | |
| 76 | + | |
| 77 | +Vous pouvez voir ce que le workflow publiera sans rien publier, ou construire les binaires à la main : | |
| 78 | + | |
| 79 | +```sh | |
| 80 | +./02-build-releases.sh v1.0.0 # écrit release/v1.0.0/, ne pousse rien | |
| 81 | +``` | |
| 82 | + | |
| 83 | +Sans argument il lit `TAG` dans `release.env` ; le workflow n'a pas de `release.env`, il passe donc le tag qui l'a déclenché. | |
| 84 | + | |
| 85 | +La suite de tests comprend des tests qui exécutent `01-release.tag.sh` contre un clone jetable. Ils se sautent eux-mêmes quand `TURBO_PYTHON_RELEASING` est défini, ce que le script exporte avant d'appeler `make check` — retirer cette ligne fait récurser une release jusqu'à épuisement. Le workflow pose la même variable pour sa propre étape `go test`. | |
| 86 | + | |
| 87 | +## Variantes | |
| 88 | + | |
| 89 | +- **Vous installez au lieu de distribuer un binaire.** `make install` et `scripts/install.sh` estampillent de la même façon, donc un éditeur installé nomme le commit dont il vient. Il n'y a rien de plus à faire. | |
| 90 | +- **Quelqu'un installe avec `go install`.** `go install rickub.com/turbo-editors/turbo-python@v0.2.0` annonce `0.2.0` d'après la version du module, sans commit ni date de build. C'est le propre enregistrement de l'outil Go ; rien à estampiller. | |
| 91 | +- **Vous avez tagué le mauvais commit.** Si le tag n'a pas été poussé, supprimez-le (`git tag -d v1.0.0`), taguez le bon, et reconstruisez. Une fois sur `origin`, ne le déplacez pas : le proxy de modules a mis en cache `go install …@v1.0.0` et la page de release porte déjà des binaires avec ce numéro — c'est pour cela que `01-release.tag.sh` refuse un tag qui existe. Incrémentez `TAG` et refaites une release. | |
| 92 | +- **About affiche `devel`.** Le binaire a été construit par un `go build .` nu plutôt que par `make`. Il n'a rien d'anormal ; simplement aucun tag ne lui a été estampillé, parce que le système de build de Go ne lit pas les tags git. Utilisez `make build`. | |
| 93 | +- **About affiche `unknown`.** Rien n'a nommé le build — un `uv run`, ou une construction depuis un dossier sans historique git. Utilisez `make build` depuis le dépôt cloné. | |
| 94 | +- **Vous n'avez pas git du tout**, ayant téléchargé une archive des sources. `make build` fonctionne quand même et le binaire annonce `unknown`. Passez la version vous-même si vous en avez besoin : | |
| 95 | + ```sh | |
| 96 | + go build -ldflags "-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0'" -o bin/turbo-python . | |
| 97 | + ``` | |
| 98 | + | |
| 99 | +## Voir aussi | |
| 100 | + | |
| 101 | +- Toutes les sources du numéro, et ce qu'annonce chaque build : [Le numéro de version](../reference/versioning.md) | |
| 102 | +- Pourquoi il n'y a pas de constante de version dans les sources : [Décisions de conception](../explanation/design-decisions.md#la-version-est-une-propriété-du-build-pas-des-sources) | |
| 103 | +- Installer dans votre PATH : [Comment installer et construire Turbo Python](install.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,103 @@ | |||
| 1 | +# Comment faire une release | ||
| 2 | + | ||
| 3 | +Ce guide montre comment publier une version pour que l'éditeur annonce correctement la sienne. Il suppose que vous pouvez pousser sur le dépôt. | ||
| 4 | + | ||
| 5 | +## Vérifier ce que vous vous apprêtez à publier | ||
| 6 | + | ||
| 7 | +```sh | ||
| 8 | +make version | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +``` | ||
| 12 | +v0.1.0-14-g88a4c38 (88a4c38) | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +Quatorze commits après `v0.1.0`. Un `-dirty` à la fin signifie que vous avez des modifications non validées — validez-les ou mettez-les de côté d'abord, sinon la release portera ce suffixe pour toujours. | ||
| 16 | + | ||
| 17 | +## Poser le tag | ||
| 18 | + | ||
| 19 | +```sh | ||
| 20 | +git tag -a v0.2.0 -m "v0.2.0" | ||
| 21 | +git push origin v0.2.0 | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +Le tag est l'origine du numéro : il doit exister avant de construire quoi que ce soit destiné à être distribué. Annoté (`-a`) plutôt que léger, parce que `git describe` préfère les tags annotés. | ||
| 25 | + | ||
| 26 | +## Construire le binaire de release | ||
| 27 | + | ||
| 28 | +```sh | ||
| 29 | +make build | ||
| 30 | +./bin/turbo-python -version | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +``` | ||
| 34 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | ||
| 35 | +``` | ||
| 36 | + | ||
| 37 | +Pas de suffixe `-14-g…` : vous êtes exactement sur le tag. C'est ce qui vous dit que le tag a bien été pris. | ||
| 38 | + | ||
| 39 | +## Vérifier la boîte About | ||
| 40 | + | ||
| 41 | +Lancez l'éditeur et faites `Alt-H`, puis `A`. | ||
| 42 | + | ||
| 43 | +``` | ||
| 44 | +Turbo Python 0.2.0 | ||
| 45 | + | ||
| 46 | +A Turbo C-style editor for Python, | ||
| 47 | +written in Go. | ||
| 48 | + | ||
| 49 | +Commit: 88a4c38 | ||
| 50 | +Built: 2026-08-31 18:04 UTC | ||
| 51 | +Theme: Turbo Classic | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +## Ou utiliser les scripts et laisser le workflow publier | ||
| 55 | + | ||
| 56 | +C'est ainsi qu'une release est réellement faite. Mettez la version et sa description d'une ligne dans `release.env` — il est ignoré par git, donc la CI ne le voit jamais : | ||
| 57 | + | ||
| 58 | +```sh | ||
| 59 | +TAG="v1.0.0" | ||
| 60 | +ABOUT="Turbo Python" | ||
| 61 | +``` | ||
| 62 | + | ||
| 63 | +Puis lancez un seul script : | ||
| 64 | + | ||
| 65 | +```sh | ||
| 66 | +./01-release.tag.sh | ||
| 67 | +``` | ||
| 68 | + | ||
| 69 | +Il lance `make check`, refuse un tag déjà pris en local ou sur `origin`, refuse un `go.mod` portant une directive `replace`, valide ce qui reste à valider, pousse la branche, et seulement ensuite pose le tag et le pousse. Cet ordre compte : un tag poussé avant la branche pointe sur un commit que le distant n'a jamais vu, et un tag créé avant un push refusé reste là pour que quelqu'un le trouve. | ||
| 70 | + | ||
| 71 | +C'est la dernière chose que vous lancez à la main. Le push du tag déclenche `.github/workflows/release.yml` ; suivez-le dans l'onglet Actions du dépôt. Il lance la suite de tests, compile les binaires avec `./02-build-releases.sh` — le même script que vous pouvez lancer sur votre machine — et crée la page de release avec : le message du tag, la ligne `go install`, les liens vers la documentation **à ce tag**, un binaire par plateforme, le `SHA256SUMS` et le README qui décrit les téléchargements. | ||
| 72 | + | ||
| 73 | +Le job publie avec son propre `GITHUB_TOKEN`, la seule authentification que l'API de release de Rickub accepte — un jeton personnel est refusé. Il n'y a rien à configurer et aucun secret à garder, ce qui explique la disparition des anciens `02-release.publish.sh` et `04-release.upload-binaries.sh`. | ||
| 74 | + | ||
| 75 | +`02-build-releases.sh` compile chaque plateforme et **estampille `TAG` lui-même**, en surchargeant la version du Makefile : `make ldflags VERSION=v1.0.0`. La release *est* `v1.0.0`, donc c'est ce que disent ses binaires — quoi qu'aurait répondu `git describe`, et que le tag existe déjà ou non. Il lance ensuite le binaire préparé pour cette machine et vérifie qu'il annonce bien la version : c'est la seule preuve que ce qui est distribué la porte. | ||
| 76 | + | ||
| 77 | +Vous pouvez voir ce que le workflow publiera sans rien publier, ou construire les binaires à la main : | ||
| 78 | + | ||
| 79 | +```sh | ||
| 80 | +./02-build-releases.sh v1.0.0 # écrit release/v1.0.0/, ne pousse rien | ||
| 81 | +``` | ||
| 82 | + | ||
| 83 | +Sans argument il lit `TAG` dans `release.env` ; le workflow n'a pas de `release.env`, il passe donc le tag qui l'a déclenché. | ||
| 84 | + | ||
| 85 | +La suite de tests comprend des tests qui exécutent `01-release.tag.sh` contre un clone jetable. Ils se sautent eux-mêmes quand `TURBO_PYTHON_RELEASING` est défini, ce que le script exporte avant d'appeler `make check` — retirer cette ligne fait récurser une release jusqu'à épuisement. Le workflow pose la même variable pour sa propre étape `go test`. | ||
| 86 | + | ||
| 87 | +## Variantes | ||
| 88 | + | ||
| 89 | +- **Vous installez au lieu de distribuer un binaire.** `make install` et `scripts/install.sh` estampillent de la même façon, donc un éditeur installé nomme le commit dont il vient. Il n'y a rien de plus à faire. | ||
| 90 | +- **Quelqu'un installe avec `go install`.** `go install rickub.com/turbo-editors/turbo-python@v0.2.0` annonce `0.2.0` d'après la version du module, sans commit ni date de build. C'est le propre enregistrement de l'outil Go ; rien à estampiller. | ||
| 91 | +- **Vous avez tagué le mauvais commit.** Si le tag n'a pas été poussé, supprimez-le (`git tag -d v1.0.0`), taguez le bon, et reconstruisez. Une fois sur `origin`, ne le déplacez pas : le proxy de modules a mis en cache `go install …@v1.0.0` et la page de release porte déjà des binaires avec ce numéro — c'est pour cela que `01-release.tag.sh` refuse un tag qui existe. Incrémentez `TAG` et refaites une release. | ||
| 92 | +- **About affiche `devel`.** Le binaire a été construit par un `go build .` nu plutôt que par `make`. Il n'a rien d'anormal ; simplement aucun tag ne lui a été estampillé, parce que le système de build de Go ne lit pas les tags git. Utilisez `make build`. | ||
| 93 | +- **About affiche `unknown`.** Rien n'a nommé le build — un `uv run`, ou une construction depuis un dossier sans historique git. Utilisez `make build` depuis le dépôt cloné. | ||
| 94 | +- **Vous n'avez pas git du tout**, ayant téléchargé une archive des sources. `make build` fonctionne quand même et le binaire annonce `unknown`. Passez la version vous-même si vous en avez besoin : | ||
| 95 | + ```sh | ||
| 96 | + go build -ldflags "-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0'" -o bin/turbo-python . | ||
| 97 | + ``` | ||
| 98 | + | ||
| 99 | +## Voir aussi | ||
| 100 | + | ||
| 101 | +- Toutes les sources du numéro, et ce qu'annonce chaque build : [Le numéro de version](../reference/versioning.md) | ||
| 102 | +- Pourquoi il n'y a pas de constante de version dans les sources : [Décisions de conception](../explanation/design-decisions.md#la-version-est-une-propriété-du-build-pas-des-sources) | ||
| 103 | +- Installer dans votre PATH : [Comment installer et construire Turbo Python](install.md) | ||
added
docs/fr/how-to/run-the-tests.md +95 -0 | new file mode 100644 | ||
| @@ -0,0 +1,95 @@ | ||
| 1 | +# Lancer les tests | |
| 2 | + | |
| 3 | +Ce guide montre comment exécuter et lire la suite de tests de Turbo Python. Il suppose que vous avez un clone du dépôt et Go 1.26 ou plus récent. | |
| 4 | + | |
| 5 | +## Toute la suite | |
| 6 | + | |
| 7 | +```bash | |
| 8 | +make test | |
| 9 | +``` | |
| 10 | + | |
| 11 | +C'est la commande unique documentée. Elle exécute `uv run pytest` sur tous les paquets. | |
| 12 | + | |
| 13 | +## Variantes | |
| 14 | + | |
| 15 | +**Voir chaque test par son nom :** | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +make test-verbose | |
| 19 | +``` | |
| 20 | + | |
| 21 | +**Mesurer la couverture par paquet :** | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +make cover | |
| 25 | +``` | |
| 26 | + | |
| 27 | +**Un seul paquet :** | |
| 28 | + | |
| 29 | +```bash | |
| 30 | +go test ./internal/buffer/ | |
| 31 | +``` | |
| 32 | + | |
| 33 | +**Sans lancer de serveur de langage.** Un test de `internal/lsp` démarre un vrai `pylsp` s'il en trouve un. Pour le sauter : | |
| 34 | + | |
| 35 | +```bash | |
| 36 | +go test -short ./... | |
| 37 | +``` | |
| 38 | + | |
| 39 | +**Avec le détecteur de compétition.** Le client LSP est concurrent : cela vaut la peine avant d'y toucher. | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +go test -race ./internal/lsp/ | |
| 43 | +``` | |
| 44 | + | |
| 45 | +**Tout ce qu'un commit devrait passer :** | |
| 46 | + | |
| 47 | +```bash | |
| 48 | +make check | |
| 49 | +``` | |
| 50 | + | |
| 51 | +Cela enchaîne `go fmt`, `go vet` et les tests, dans cet ordre. | |
| 52 | + | |
| 53 | +## Ce que la suite couvre | |
| 54 | + | |
| 55 | +Aucun test n'a besoin d'un vrai terminal. Les widgets et l'éditeur sont dessinés sur le `SimulationScreen` de tcell — un vrai `Screen` qui dessine en mémoire — si bien que les assertions portent sur l'image qu'un terminal afficherait réellement. Le client LSP est testé contre un serveur de langage tournant dans le même processus, à travers un tube en mémoire. | |
| 56 | + | |
| 57 | +La seule exception est `TestAgainstRealGopls`, qui démarre le vrai serveur. Il **se saute lui-même** quand `pylsp` n'est pas installé : un clone sans serveur de langage a donc quand même une suite verte. | |
| 58 | + | |
| 59 | +## Tester sur un turbo-core non publié | |
| 60 | + | |
| 61 | +L'essentiel de Turbo Python est turbo-core, et ce dépôt en dépend par version, depuis le proxy de modules : | |
| 62 | + | |
| 63 | +``` | |
| 64 | +require rickub.com/turbo-editors/turbo-core v0.2.0 | |
| 65 | +``` | |
| 66 | + | |
| 67 | +Une modification faite dans une copie de turbo-core placée à côté de celle-ci est donc invisible ici tant qu'elle n'est pas publiée. Pour la tester avant, créez un espace de travail : | |
| 68 | + | |
| 69 | +```bash | |
| 70 | +go work init . ../turbo-core | |
| 71 | +make test | |
| 72 | +``` | |
| 73 | + | |
| 74 | +Chaque import de la bibliothèque pointe désormais sur cette copie. Ni `go.mod` ni `go.sum` ne changent : il n'y a donc rien à défaire. Vérifiez que c'est bien pris en compte — c'est l'erreur contre laquelle il faut se prémunir, car sinon tout compile et tout passe quand même : | |
| 75 | + | |
| 76 | +```bash | |
| 77 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app | |
| 78 | +``` | |
| 79 | + | |
| 80 | +La réponse doit être votre copie de travail, pas un chemin sous `pkg/mod`. Une fois terminé, `rm go.work go.work.sum` ; le fichier est ignoré par git, il ne peut donc pas être commité par accident. | |
| 81 | + | |
| 82 | +## Qualité du code | |
| 83 | + | |
| 84 | +La suite de tests n'est pas toute la porte de qualité. Celle-ci se mesure à part : | |
| 85 | + | |
| 86 | +```bash | |
| 87 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | |
| 88 | +``` | |
| 89 | + | |
| 90 | +Elle écrit un rapport sous `.quality/` et sort en erreur si la porte échoue. | |
| 91 | + | |
| 92 | +## Voir aussi | |
| 93 | + | |
| 94 | +- Pourquoi les tests ont cette forme : [Architecture](../explanation/architecture.md) | |
| 95 | +- Toutes les cibles make : [référence de la ligne de commande](../reference/cli.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | +# Lancer les tests | ||
| 2 | + | ||
| 3 | +Ce guide montre comment exécuter et lire la suite de tests de Turbo Python. Il suppose que vous avez un clone du dépôt et Go 1.26 ou plus récent. | ||
| 4 | + | ||
| 5 | +## Toute la suite | ||
| 6 | + | ||
| 7 | +```bash | ||
| 8 | +make test | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +C'est la commande unique documentée. Elle exécute `uv run pytest` sur tous les paquets. | ||
| 12 | + | ||
| 13 | +## Variantes | ||
| 14 | + | ||
| 15 | +**Voir chaque test par son nom :** | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +make test-verbose | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +**Mesurer la couverture par paquet :** | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +make cover | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +**Un seul paquet :** | ||
| 28 | + | ||
| 29 | +```bash | ||
| 30 | +go test ./internal/buffer/ | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +**Sans lancer de serveur de langage.** Un test de `internal/lsp` démarre un vrai `pylsp` s'il en trouve un. Pour le sauter : | ||
| 34 | + | ||
| 35 | +```bash | ||
| 36 | +go test -short ./... | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +**Avec le détecteur de compétition.** Le client LSP est concurrent : cela vaut la peine avant d'y toucher. | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +go test -race ./internal/lsp/ | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +**Tout ce qu'un commit devrait passer :** | ||
| 46 | + | ||
| 47 | +```bash | ||
| 48 | +make check | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +Cela enchaîne `go fmt`, `go vet` et les tests, dans cet ordre. | ||
| 52 | + | ||
| 53 | +## Ce que la suite couvre | ||
| 54 | + | ||
| 55 | +Aucun test n'a besoin d'un vrai terminal. Les widgets et l'éditeur sont dessinés sur le `SimulationScreen` de tcell — un vrai `Screen` qui dessine en mémoire — si bien que les assertions portent sur l'image qu'un terminal afficherait réellement. Le client LSP est testé contre un serveur de langage tournant dans le même processus, à travers un tube en mémoire. | ||
| 56 | + | ||
| 57 | +La seule exception est `TestAgainstRealGopls`, qui démarre le vrai serveur. Il **se saute lui-même** quand `pylsp` n'est pas installé : un clone sans serveur de langage a donc quand même une suite verte. | ||
| 58 | + | ||
| 59 | +## Tester sur un turbo-core non publié | ||
| 60 | + | ||
| 61 | +L'essentiel de Turbo Python est turbo-core, et ce dépôt en dépend par version, depuis le proxy de modules : | ||
| 62 | + | ||
| 63 | +``` | ||
| 64 | +require rickub.com/turbo-editors/turbo-core v0.2.0 | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +Une modification faite dans une copie de turbo-core placée à côté de celle-ci est donc invisible ici tant qu'elle n'est pas publiée. Pour la tester avant, créez un espace de travail : | ||
| 68 | + | ||
| 69 | +```bash | ||
| 70 | +go work init . ../turbo-core | ||
| 71 | +make test | ||
| 72 | +``` | ||
| 73 | + | ||
| 74 | +Chaque import de la bibliothèque pointe désormais sur cette copie. Ni `go.mod` ni `go.sum` ne changent : il n'y a donc rien à défaire. Vérifiez que c'est bien pris en compte — c'est l'erreur contre laquelle il faut se prémunir, car sinon tout compile et tout passe quand même : | ||
| 75 | + | ||
| 76 | +```bash | ||
| 77 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +La réponse doit être votre copie de travail, pas un chemin sous `pkg/mod`. Une fois terminé, `rm go.work go.work.sum` ; le fichier est ignoré par git, il ne peut donc pas être commité par accident. | ||
| 81 | + | ||
| 82 | +## Qualité du code | ||
| 83 | + | ||
| 84 | +La suite de tests n'est pas toute la porte de qualité. Celle-ci se mesure à part : | ||
| 85 | + | ||
| 86 | +```bash | ||
| 87 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | ||
| 88 | +``` | ||
| 89 | + | ||
| 90 | +Elle écrit un rapport sous `.quality/` et sort en erreur si la porte échoue. | ||
| 91 | + | ||
| 92 | +## Voir aussi | ||
| 93 | + | ||
| 94 | +- Pourquoi les tests ont cette forme : [Architecture](../explanation/architecture.md) | ||
| 95 | +- Toutes les cibles make : [référence de la ligne de commande](../reference/cli.md) | ||
added
docs/fr/how-to/run-uv-commands.md +214 -0 | new file mode 100644 | ||
| @@ -0,0 +1,214 @@ | ||
| 1 | +# Lancer les commandes uv depuis l'éditeur | |
| 2 | + | |
| 3 | +Ce guide montre comment formater, vérifier, compiler, tester et exécuter votre projet sans quitter Turbo Python. Il suppose l'éditeur installé et un projet Python sous la main. | |
| 4 | + | |
| 5 | +## Obtenir un fichier de départ | |
| 6 | + | |
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **Python ▸ Create tools file** (`Alt-P`, puis `C`). | |
| 8 | + | |
| 9 | +Cela écrit `.turbo-python/tools.toml` avec les cinq commandes qu'un projet Python passe avant de commiter, et l'ouvre : | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[tool]] | |
| 13 | +name = "~F~ormat" | |
| 14 | +command = "uv run ruff format ." | |
| 15 | +output = "popup" | |
| 16 | + | |
| 17 | +[[tool]] | |
| 18 | +name = "~T~est" | |
| 19 | +command = "uv run pytest" | |
| 20 | +output = "popup" | |
| 21 | + | |
| 22 | +[[tool]] | |
| 23 | +name = "~R~un" | |
| 24 | +command = "uv run" | |
| 25 | +# Un terminal, pas une popup : un programme qui lit le clavier doit pouvoir | |
| 26 | +# recevoir une réponse, et un programme long doit pouvoir être interrompu. | |
| 27 | +output = "terminal" | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Chaque `[[tool]]` devient une ligne du menu **Python**, dans l'ordre du fichier — sauf s'il nomme un `menu` à lui, ce que couvre la section suivante mais une. Le fichier est relu à **chaque ouverture du menu** : une modification prend effet immédiatement. | |
| 31 | + | |
| 32 | +## En lancer une | |
| 33 | + | |
| 34 | +`Alt-P`, puis la lettre entre les tildes — `F` pour formater, `T` pour tester. | |
| 35 | + | |
| 36 | +Une **popup** s'ouvre aussitôt et se remplit à mesure. Son titre porte la commande et, une fois terminée, son issue : | |
| 37 | + | |
| 38 | +``` | |
| 39 | +┌──────────── uv run ruff check . — exit 1 ────────────┐ | |
| 40 | +│ main.py:6:2: unreachable code │ | |
| 41 | +│ │ | |
| 42 | +│ [ Close ] │ | |
| 43 | +└───────────────────────────────────────────────┘ | |
| 44 | +``` | |
| 45 | + | |
| 46 | +| Touche | Effet | | |
| 47 | +| --- | --- | | |
| 48 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Parcourir la sortie | | |
| 49 | +| `Échap` | Fermer — et **arrêter la commande** si elle tourne encore | | |
| 50 | +| `Entrée` | Fermer | | |
| 51 | + | |
| 52 | +Une commande qui a réussi sans rien dire affiche `(no output)` plutôt qu'une boîte vide : on la distingue ainsi d'une commande qui n'a pas démarré. | |
| 53 | + | |
| 54 | +La popup suit la sortie tant que vous n'avez pas remonté ; ensuite elle vous laisse où vous êtes. | |
| 55 | + | |
| 56 | +## Choisir où va la sortie | |
| 57 | + | |
| 58 | +Posez `output` sur un outil : | |
| 59 | + | |
| 60 | +| `output` | Ce que vous obtenez | | |
| 61 | +| --- | --- | | |
| 62 | +| `popup` | Un dialogue qui se remplit pendant l'exécution. Le défaut. | | |
| 63 | +| `terminal` | Une fenêtre terminal : couleurs, `Ctrl-C`, et le clavier atteint le programme | | |
| 64 | +| `editor` | Une fenêtre d'édition une fois terminé, à fouiller avec `Ctrl-F` | | |
| 65 | + | |
| 66 | +`Run` est en `terminal` dans le fichier de départ, et c'est l'exemple même de pourquoi la clé existe : une popup ne peut pas répondre à un programme qui lit le clavier, ni être interrompue par `Ctrl-C`. | |
| 67 | + | |
| 68 | +Prenez `editor` quand la sortie est quelque chose à éplucher — un long `go test -v`, ou un rapport de couverture à parcourir. | |
| 69 | + | |
| 70 | +## Une commande longue immobilise l'éditeur | |
| 71 | + | |
| 72 | +Une popup est modale : pendant que `go build` tourne, vous ne pouvez taper nulle part ailleurs. `Échap` la ferme et arrête la commande. | |
| 73 | + | |
| 74 | +Si cela gêne pour une commande précise, donnez-lui `output = "terminal"` — la fenêtre est ordinaire et vous continuez à travailler à côté. C'est précisément l'intérêt d'avoir rendu la clé configurable. | |
| 75 | + | |
| 76 | +## Ce qui arrive à vos fichiers ouverts | |
| 77 | + | |
| 78 | +`Format` réécrit les fichiers sur le disque — y compris celui que vous regardez. À la fin d'une commande, l'éditeur **relit tout fichier ouvert n'ayant aucune modification non enregistrée** : la version formatée apparaît sans que vous ayez rien à faire. La barre d'état dit combien. | |
| 79 | + | |
| 80 | +Un fichier ayant des modifications non enregistrées est **laissé tel quel**, et la barre d'état le dit aussi : | |
| 81 | + | |
| 82 | +``` | |
| 83 | +Reloaded 2 files; 1 file with unsaved changes left alone | |
| 84 | +``` | |
| 85 | + | |
| 86 | +C'est délibéré : votre modification et le formateur sont réellement en désaccord, et l'éditeur n'est pas celui qui doit trancher. Enregistrez d'abord (`F2`) puis relancez la commande, ou continuez à éditer et formatez plus tard. | |
| 87 | + | |
| 88 | +## Ajouter vos propres commandes | |
| 89 | + | |
| 90 | +Éditez `.turbo-python/tools.toml`. Une commande passe par `sh -c`, donc une seule entrée peut être toute une séquence : | |
| 91 | + | |
| 92 | +```toml | |
| 93 | +[[tool]] | |
| 94 | +name = "~C~heck" | |
| 95 | +command = "uv run ruff format . && uv run ruff check . && uv run pytest" | |
| 96 | +output = "popup" | |
| 97 | + | |
| 98 | +[[tool]] | |
| 99 | +name = "~M~ettre à jour" | |
| 100 | +command = "uv lock --upgrade" | |
| 101 | +output = "popup" | |
| 102 | + | |
| 103 | +[[tool]] | |
| 104 | +name = "Cover~a~ge" | |
| 105 | +command = "uv run pytest --cov --cov-report=term-missing" | |
| 106 | +output = "editor" | |
| 107 | +``` | |
| 108 | + | |
| 109 | +Donnez à chacune une touche d'accès avec des tildes, et gardez-les distinctes — le menu répond à la première correspondance trouvée. | |
| 110 | + | |
| 111 | +## Mettre un outil dans un menu à lui | |
| 112 | + | |
| 113 | +Un outil qui n'a rien à voir avec Python n'a rien à faire dans le menu Python. Donnez-lui un `menu` : | |
| 114 | + | |
| 115 | +```toml | |
| 116 | +[[tool]] | |
| 117 | +name = "~E~cho" | |
| 118 | +command = "echo TADA" | |
| 119 | +output = "terminal" | |
| 120 | +menu = "Tools" | |
| 121 | + | |
| 122 | +[[tool]] | |
| 123 | +name = "~U~p" | |
| 124 | +command = "docker compose up -d" | |
| 125 | +menu = "Docker" | |
| 126 | + | |
| 127 | +[[tool]] | |
| 128 | +name = "~D~own" | |
| 129 | +command = "docker compose down" | |
| 130 | +menu = "Docker" | |
| 131 | +``` | |
| 132 | + | |
| 133 | +Vous obtenez un menu **Tools** et un menu **Docker** sur la barre, entre Python et Help, dans l'ordre où les noms apparaissent pour la première fois dans le fichier. Docker contient ses deux outils. Rien à redémarrer : enregistrez le fichier et la barre suit. | |
| 134 | + | |
| 135 | +Le nom vous appartient — il n'y a pas de liste où piocher. Omettez `menu` et l'outil reste dans Python, où sont les cinq commandes de départ. | |
| 136 | + | |
| 137 | +### La touche d'accès est choisie pour vous | |
| 138 | + | |
| 139 | +Vous ne pouvez pas savoir, en écrivant le fichier, quelles lettres les menus de l'éditeur occupent déjà. Il s'en charge : la première lettre du nom que rien d'autre ne revendique reçoit les tildes. | |
| 140 | + | |
| 141 | +`Tools` obtient `Alt-T`, parce que `T` est libre. Un menu nommé `Format` obtiendrait `Alt-A`, parce que `F` est à File, `o` à Options et `r` à Run. | |
| 142 | + | |
| 143 | +Écrivez les tildes vous-même — `menu = "Doc~k~er"` — et une lettre libre est conservée. Une lettre prise ne l'est pas : la barre répond au *premier* menu correspondant à une touche, donc honorer votre choix rendrait l'un des deux menus inatteignable. Elle en choisit une autre, sans rien dire. | |
| 144 | + | |
| 145 | +## Variantes | |
| 146 | + | |
| 147 | +- **Vous préférez `black` et `flake8` à `ruff`.** Changez les commandes `Format` et `Lint`. `ruff` est le défaut parce qu'il fait les deux métiers à lui seul et qu'`uv run` va le chercher tout seul ; tout autre choix tient également en une ligne. | |
| 148 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** Les commandes s'y exécutent, donc `ruff check .` ne couvre que ce sous-arbre — et `uv` y cherche aussi le `pyproject.toml`. Lancez depuis la racine du projet. | |
| 149 | +- **Le fichier contient une erreur.** Le menu affiche un `Cannot read tools` grisé à la place des commandes, et **Create tools file** reste là. | |
| 150 | +- **Une commande n'est pas installée.** La popup affiche `command not found` et `— exit 127`, ce qu'un shell aurait dit. | |
| 151 | +- **Vous voulez un menu portant le nom d'un menu existant.** `menu = "File"` vous donne un second menu File, plus loin sur la barre, avec une autre touche d'accès. Rien ne l'empêche ; rien ne le recommande non plus. | |
| 152 | +- **Votre menu n'a pas de touche d'accès.** Toutes les lettres de son nom étaient déjà prises. `F10` et les flèches y accèdent, la souris aussi. Renommez-le avec une lettre libre. | |
| 153 | +- **Vous avez mal orthographié la valeur d'`output`.** Tout le fichier est refusé et le menu affiche `Cannot read tools`, en nommant l'outil et en listant les valeurs possibles. Un repli silencieux aurait envoyé la sortie ailleurs que là où vous l'aviez demandée. | |
| 154 | + | |
| 155 | +## Demander une valeur au lancement | |
| 156 | + | |
| 157 | +Certaines commandes ont besoin de quelque chose de saisi à chaque fois : un chemin de module, un nom de projet, un test à filtrer. Mettez un `{{libellé}}` à l'endroit où la valeur va : | |
| 158 | + | |
| 159 | +```toml | |
| 160 | +[[tool]] | |
| 161 | +name = "~I~nit module" | |
| 162 | +command = "uv init --app {{nom du projet}}" | |
| 163 | +output = "popup" | |
| 164 | +``` | |
| 165 | + | |
| 166 | +Choisir cette entrée ouvre une boîte intitulée **Init module** avec un champ, libellé `module path`. Tapez la valeur et appuyez sur Entrée ; la commande se lance avec. Échap, et rien ne se lance. | |
| 167 | + | |
| 168 | +La valeur est protégée, si bien qu'un chemin contenant une espace reste un seul argument. | |
| 169 | + | |
| 170 | +### Plusieurs valeurs à la fois | |
| 171 | + | |
| 172 | +Un champ chacune, dans l'ordre où elles apparaissent : | |
| 173 | + | |
| 174 | +```toml | |
| 175 | +[[tool]] | |
| 176 | +name = "~C~opy" | |
| 177 | +command = "cp {{from}} {{to}}" | |
| 178 | +``` | |
| 179 | + | |
| 180 | +**Tab** passe d'un champ à l'autre, **Entrée** lance. | |
| 181 | + | |
| 182 | +### Un champ valant plusieurs arguments | |
| 183 | + | |
| 184 | +La protection est le mauvais choix quand on veut dire « ajoute ces options à la fin ». Ajoutez `...` à l'intérieur des accolades et la valeur passe telle quelle : | |
| 185 | + | |
| 186 | +```toml | |
| 187 | +[[tool]] | |
| 188 | +name = "Test ~o~ne" | |
| 189 | +command = "uv run pytest {{extra flags...}}" | |
| 190 | +``` | |
| 191 | + | |
| 192 | +Tapez `--release parse` et le tout atteint la commande sous forme d'arguments séparés. | |
| 193 | + | |
| 194 | +### La même valeur deux fois | |
| 195 | + | |
| 196 | +Écrivez le libellé deux fois ; on ne vous le demande qu'une : | |
| 197 | + | |
| 198 | +```toml | |
| 199 | +[[tool]] | |
| 200 | +name = "~N~ew directory" | |
| 201 | +command = "mkdir {{name}} && cd {{name}}" | |
| 202 | +``` | |
| 203 | + | |
| 204 | +### Variantes | |
| 205 | + | |
| 206 | +- **La valeur est souvent la même.** Lancez-le une fois et la boîte retient ce que vous avez tapé, pour le reste de la session. Rien n'est écrit sur le disque. | |
| 207 | +- **Votre commande contient déjà des accolades.** `awk '{print $1}'` et `find . -exec rm {} +` sont laissés tranquilles : seules les doubles accolades demandent quelque chose. | |
| 208 | +- **La commande demande plus de valeurs que l'écran n'en contient.** L'éditeur le dit plutôt que d'ouvrir une boîte dont le bouton OK est sous le bas du terminal. Agrandissez le terminal, ou coupez la commande en deux outils. | |
| 209 | + | |
| 210 | +## Voir aussi | |
| 211 | + | |
| 212 | +- Toutes les clés du fichier et toutes les règles : [Référence des outils go](../reference/python-tools.md) | |
| 213 | +- Pourquoi chaque commande a sa fenêtre terminal, et pourquoi un fichier non modifié se recharge : [Outils Python](../explanation/python-tools.md) | |
| 214 | +- Les fenêtres dans lesquelles les commandes tournent : [Fenêtres terminal](../reference/terminal.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,214 @@ | |||
| 1 | +# Lancer les commandes uv depuis l'éditeur | ||
| 2 | + | ||
| 3 | +Ce guide montre comment formater, vérifier, compiler, tester et exécuter votre projet sans quitter Turbo Python. Il suppose l'éditeur installé et un projet Python sous la main. | ||
| 4 | + | ||
| 5 | +## Obtenir un fichier de départ | ||
| 6 | + | ||
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **Python ▸ Create tools file** (`Alt-P`, puis `C`). | ||
| 8 | + | ||
| 9 | +Cela écrit `.turbo-python/tools.toml` avec les cinq commandes qu'un projet Python passe avant de commiter, et l'ouvre : | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[tool]] | ||
| 13 | +name = "~F~ormat" | ||
| 14 | +command = "uv run ruff format ." | ||
| 15 | +output = "popup" | ||
| 16 | + | ||
| 17 | +[[tool]] | ||
| 18 | +name = "~T~est" | ||
| 19 | +command = "uv run pytest" | ||
| 20 | +output = "popup" | ||
| 21 | + | ||
| 22 | +[[tool]] | ||
| 23 | +name = "~R~un" | ||
| 24 | +command = "uv run" | ||
| 25 | +# Un terminal, pas une popup : un programme qui lit le clavier doit pouvoir | ||
| 26 | +# recevoir une réponse, et un programme long doit pouvoir être interrompu. | ||
| 27 | +output = "terminal" | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Chaque `[[tool]]` devient une ligne du menu **Python**, dans l'ordre du fichier — sauf s'il nomme un `menu` à lui, ce que couvre la section suivante mais une. Le fichier est relu à **chaque ouverture du menu** : une modification prend effet immédiatement. | ||
| 31 | + | ||
| 32 | +## En lancer une | ||
| 33 | + | ||
| 34 | +`Alt-P`, puis la lettre entre les tildes — `F` pour formater, `T` pour tester. | ||
| 35 | + | ||
| 36 | +Une **popup** s'ouvre aussitôt et se remplit à mesure. Son titre porte la commande et, une fois terminée, son issue : | ||
| 37 | + | ||
| 38 | +``` | ||
| 39 | +┌──────────── uv run ruff check . — exit 1 ────────────┐ | ||
| 40 | +│ main.py:6:2: unreachable code │ | ||
| 41 | +│ │ | ||
| 42 | +│ [ Close ] │ | ||
| 43 | +└───────────────────────────────────────────────┘ | ||
| 44 | +``` | ||
| 45 | + | ||
| 46 | +| Touche | Effet | | ||
| 47 | +| --- | --- | | ||
| 48 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Parcourir la sortie | | ||
| 49 | +| `Échap` | Fermer — et **arrêter la commande** si elle tourne encore | | ||
| 50 | +| `Entrée` | Fermer | | ||
| 51 | + | ||
| 52 | +Une commande qui a réussi sans rien dire affiche `(no output)` plutôt qu'une boîte vide : on la distingue ainsi d'une commande qui n'a pas démarré. | ||
| 53 | + | ||
| 54 | +La popup suit la sortie tant que vous n'avez pas remonté ; ensuite elle vous laisse où vous êtes. | ||
| 55 | + | ||
| 56 | +## Choisir où va la sortie | ||
| 57 | + | ||
| 58 | +Posez `output` sur un outil : | ||
| 59 | + | ||
| 60 | +| `output` | Ce que vous obtenez | | ||
| 61 | +| --- | --- | | ||
| 62 | +| `popup` | Un dialogue qui se remplit pendant l'exécution. Le défaut. | | ||
| 63 | +| `terminal` | Une fenêtre terminal : couleurs, `Ctrl-C`, et le clavier atteint le programme | | ||
| 64 | +| `editor` | Une fenêtre d'édition une fois terminé, à fouiller avec `Ctrl-F` | | ||
| 65 | + | ||
| 66 | +`Run` est en `terminal` dans le fichier de départ, et c'est l'exemple même de pourquoi la clé existe : une popup ne peut pas répondre à un programme qui lit le clavier, ni être interrompue par `Ctrl-C`. | ||
| 67 | + | ||
| 68 | +Prenez `editor` quand la sortie est quelque chose à éplucher — un long `go test -v`, ou un rapport de couverture à parcourir. | ||
| 69 | + | ||
| 70 | +## Une commande longue immobilise l'éditeur | ||
| 71 | + | ||
| 72 | +Une popup est modale : pendant que `go build` tourne, vous ne pouvez taper nulle part ailleurs. `Échap` la ferme et arrête la commande. | ||
| 73 | + | ||
| 74 | +Si cela gêne pour une commande précise, donnez-lui `output = "terminal"` — la fenêtre est ordinaire et vous continuez à travailler à côté. C'est précisément l'intérêt d'avoir rendu la clé configurable. | ||
| 75 | + | ||
| 76 | +## Ce qui arrive à vos fichiers ouverts | ||
| 77 | + | ||
| 78 | +`Format` réécrit les fichiers sur le disque — y compris celui que vous regardez. À la fin d'une commande, l'éditeur **relit tout fichier ouvert n'ayant aucune modification non enregistrée** : la version formatée apparaît sans que vous ayez rien à faire. La barre d'état dit combien. | ||
| 79 | + | ||
| 80 | +Un fichier ayant des modifications non enregistrées est **laissé tel quel**, et la barre d'état le dit aussi : | ||
| 81 | + | ||
| 82 | +``` | ||
| 83 | +Reloaded 2 files; 1 file with unsaved changes left alone | ||
| 84 | +``` | ||
| 85 | + | ||
| 86 | +C'est délibéré : votre modification et le formateur sont réellement en désaccord, et l'éditeur n'est pas celui qui doit trancher. Enregistrez d'abord (`F2`) puis relancez la commande, ou continuez à éditer et formatez plus tard. | ||
| 87 | + | ||
| 88 | +## Ajouter vos propres commandes | ||
| 89 | + | ||
| 90 | +Éditez `.turbo-python/tools.toml`. Une commande passe par `sh -c`, donc une seule entrée peut être toute une séquence : | ||
| 91 | + | ||
| 92 | +```toml | ||
| 93 | +[[tool]] | ||
| 94 | +name = "~C~heck" | ||
| 95 | +command = "uv run ruff format . && uv run ruff check . && uv run pytest" | ||
| 96 | +output = "popup" | ||
| 97 | + | ||
| 98 | +[[tool]] | ||
| 99 | +name = "~M~ettre à jour" | ||
| 100 | +command = "uv lock --upgrade" | ||
| 101 | +output = "popup" | ||
| 102 | + | ||
| 103 | +[[tool]] | ||
| 104 | +name = "Cover~a~ge" | ||
| 105 | +command = "uv run pytest --cov --cov-report=term-missing" | ||
| 106 | +output = "editor" | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +Donnez à chacune une touche d'accès avec des tildes, et gardez-les distinctes — le menu répond à la première correspondance trouvée. | ||
| 110 | + | ||
| 111 | +## Mettre un outil dans un menu à lui | ||
| 112 | + | ||
| 113 | +Un outil qui n'a rien à voir avec Python n'a rien à faire dans le menu Python. Donnez-lui un `menu` : | ||
| 114 | + | ||
| 115 | +```toml | ||
| 116 | +[[tool]] | ||
| 117 | +name = "~E~cho" | ||
| 118 | +command = "echo TADA" | ||
| 119 | +output = "terminal" | ||
| 120 | +menu = "Tools" | ||
| 121 | + | ||
| 122 | +[[tool]] | ||
| 123 | +name = "~U~p" | ||
| 124 | +command = "docker compose up -d" | ||
| 125 | +menu = "Docker" | ||
| 126 | + | ||
| 127 | +[[tool]] | ||
| 128 | +name = "~D~own" | ||
| 129 | +command = "docker compose down" | ||
| 130 | +menu = "Docker" | ||
| 131 | +``` | ||
| 132 | + | ||
| 133 | +Vous obtenez un menu **Tools** et un menu **Docker** sur la barre, entre Python et Help, dans l'ordre où les noms apparaissent pour la première fois dans le fichier. Docker contient ses deux outils. Rien à redémarrer : enregistrez le fichier et la barre suit. | ||
| 134 | + | ||
| 135 | +Le nom vous appartient — il n'y a pas de liste où piocher. Omettez `menu` et l'outil reste dans Python, où sont les cinq commandes de départ. | ||
| 136 | + | ||
| 137 | +### La touche d'accès est choisie pour vous | ||
| 138 | + | ||
| 139 | +Vous ne pouvez pas savoir, en écrivant le fichier, quelles lettres les menus de l'éditeur occupent déjà. Il s'en charge : la première lettre du nom que rien d'autre ne revendique reçoit les tildes. | ||
| 140 | + | ||
| 141 | +`Tools` obtient `Alt-T`, parce que `T` est libre. Un menu nommé `Format` obtiendrait `Alt-A`, parce que `F` est à File, `o` à Options et `r` à Run. | ||
| 142 | + | ||
| 143 | +Écrivez les tildes vous-même — `menu = "Doc~k~er"` — et une lettre libre est conservée. Une lettre prise ne l'est pas : la barre répond au *premier* menu correspondant à une touche, donc honorer votre choix rendrait l'un des deux menus inatteignable. Elle en choisit une autre, sans rien dire. | ||
| 144 | + | ||
| 145 | +## Variantes | ||
| 146 | + | ||
| 147 | +- **Vous préférez `black` et `flake8` à `ruff`.** Changez les commandes `Format` et `Lint`. `ruff` est le défaut parce qu'il fait les deux métiers à lui seul et qu'`uv run` va le chercher tout seul ; tout autre choix tient également en une ligne. | ||
| 148 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** Les commandes s'y exécutent, donc `ruff check .` ne couvre que ce sous-arbre — et `uv` y cherche aussi le `pyproject.toml`. Lancez depuis la racine du projet. | ||
| 149 | +- **Le fichier contient une erreur.** Le menu affiche un `Cannot read tools` grisé à la place des commandes, et **Create tools file** reste là. | ||
| 150 | +- **Une commande n'est pas installée.** La popup affiche `command not found` et `— exit 127`, ce qu'un shell aurait dit. | ||
| 151 | +- **Vous voulez un menu portant le nom d'un menu existant.** `menu = "File"` vous donne un second menu File, plus loin sur la barre, avec une autre touche d'accès. Rien ne l'empêche ; rien ne le recommande non plus. | ||
| 152 | +- **Votre menu n'a pas de touche d'accès.** Toutes les lettres de son nom étaient déjà prises. `F10` et les flèches y accèdent, la souris aussi. Renommez-le avec une lettre libre. | ||
| 153 | +- **Vous avez mal orthographié la valeur d'`output`.** Tout le fichier est refusé et le menu affiche `Cannot read tools`, en nommant l'outil et en listant les valeurs possibles. Un repli silencieux aurait envoyé la sortie ailleurs que là où vous l'aviez demandée. | ||
| 154 | + | ||
| 155 | +## Demander une valeur au lancement | ||
| 156 | + | ||
| 157 | +Certaines commandes ont besoin de quelque chose de saisi à chaque fois : un chemin de module, un nom de projet, un test à filtrer. Mettez un `{{libellé}}` à l'endroit où la valeur va : | ||
| 158 | + | ||
| 159 | +```toml | ||
| 160 | +[[tool]] | ||
| 161 | +name = "~I~nit module" | ||
| 162 | +command = "uv init --app {{nom du projet}}" | ||
| 163 | +output = "popup" | ||
| 164 | +``` | ||
| 165 | + | ||
| 166 | +Choisir cette entrée ouvre une boîte intitulée **Init module** avec un champ, libellé `module path`. Tapez la valeur et appuyez sur Entrée ; la commande se lance avec. Échap, et rien ne se lance. | ||
| 167 | + | ||
| 168 | +La valeur est protégée, si bien qu'un chemin contenant une espace reste un seul argument. | ||
| 169 | + | ||
| 170 | +### Plusieurs valeurs à la fois | ||
| 171 | + | ||
| 172 | +Un champ chacune, dans l'ordre où elles apparaissent : | ||
| 173 | + | ||
| 174 | +```toml | ||
| 175 | +[[tool]] | ||
| 176 | +name = "~C~opy" | ||
| 177 | +command = "cp {{from}} {{to}}" | ||
| 178 | +``` | ||
| 179 | + | ||
| 180 | +**Tab** passe d'un champ à l'autre, **Entrée** lance. | ||
| 181 | + | ||
| 182 | +### Un champ valant plusieurs arguments | ||
| 183 | + | ||
| 184 | +La protection est le mauvais choix quand on veut dire « ajoute ces options à la fin ». Ajoutez `...` à l'intérieur des accolades et la valeur passe telle quelle : | ||
| 185 | + | ||
| 186 | +```toml | ||
| 187 | +[[tool]] | ||
| 188 | +name = "Test ~o~ne" | ||
| 189 | +command = "uv run pytest {{extra flags...}}" | ||
| 190 | +``` | ||
| 191 | + | ||
| 192 | +Tapez `--release parse` et le tout atteint la commande sous forme d'arguments séparés. | ||
| 193 | + | ||
| 194 | +### La même valeur deux fois | ||
| 195 | + | ||
| 196 | +Écrivez le libellé deux fois ; on ne vous le demande qu'une : | ||
| 197 | + | ||
| 198 | +```toml | ||
| 199 | +[[tool]] | ||
| 200 | +name = "~N~ew directory" | ||
| 201 | +command = "mkdir {{name}} && cd {{name}}" | ||
| 202 | +``` | ||
| 203 | + | ||
| 204 | +### Variantes | ||
| 205 | + | ||
| 206 | +- **La valeur est souvent la même.** Lancez-le une fois et la boîte retient ce que vous avez tapé, pour le reste de la session. Rien n'est écrit sur le disque. | ||
| 207 | +- **Votre commande contient déjà des accolades.** `awk '{print $1}'` et `find . -exec rm {} +` sont laissés tranquilles : seules les doubles accolades demandent quelque chose. | ||
| 208 | +- **La commande demande plus de valeurs que l'écran n'en contient.** L'éditeur le dit plutôt que d'ouvrir une boîte dont le bouton OK est sous le bas du terminal. Agrandissez le terminal, ou coupez la commande en deux outils. | ||
| 209 | + | ||
| 210 | +## Voir aussi | ||
| 211 | + | ||
| 212 | +- Toutes les clés du fichier et toutes les règles : [Référence des outils go](../reference/python-tools.md) | ||
| 213 | +- Pourquoi chaque commande a sa fenêtre terminal, et pourquoi un fichier non modifié se recharge : [Outils Python](../explanation/python-tools.md) | ||
| 214 | +- Les fenêtres dans lesquelles les commandes tournent : [Fenêtres terminal](../reference/terminal.md) | ||
added
docs/fr/how-to/talk-to-an-agent.md +177 -0 | new file mode 100644 | ||
| @@ -0,0 +1,177 @@ | ||
| 1 | +# Dialoguer avec un agent de code depuis l'éditeur | |
| 2 | + | |
| 3 | +Ce guide montre comment pointer Turbo Python vers un agent qui parle l'[Agent Client Protocol](https://agentclientprotocol.com), ouvrir une fenêtre dessus, et tenir une conversation sur le code en cours d'édition. Il suppose que Turbo Python est déjà lancé dans un projet. | |
| 4 | + | |
| 5 | +Turbo Python est un **client** ACP. Il lance l'agent comme processus fils et lui parle en JSON-RPC sur son entrée et sa sortie standard — le même montage que Zed, donc un agent qui fonctionne là-bas fonctionne ici. | |
| 6 | + | |
| 7 | +## Déclarer un agent à l'éditeur | |
| 8 | + | |
| 9 | +Les agents sont listés dans `acp.toml`. Choisissez **Agent ▸ Create agents file** et l'éditeur écrit un fichier de départ dans `.turbo-python/acp.toml`, puis l'ouvre. | |
| 10 | + | |
| 11 | +Un agent, c'est un bloc `[[agent]]` : | |
| 12 | + | |
| 13 | +```toml | |
| 14 | +[[agent]] | |
| 15 | +name = "Bob (llama.cpp)" | |
| 16 | +command = "docker" | |
| 17 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | |
| 18 | +env = { TELEMETRY_ENABLED = "false" } | |
| 19 | +``` | |
| 20 | + | |
| 21 | +`name` est ce qu'affiche le menu Agent et le nom de la fenêtre. `command` et `args` disent comment démarrer l'agent. C'est tout — le fichier est relu à chaque ouverture de fenêtre, donc on ne redémarre jamais l'éditeur pour essayer une modification. | |
| 22 | + | |
| 23 | +Listez-en autant que vous voulez. Chacun devient une ligne du menu, et chaque fenêtre ouverte depuis cette ligne est un processus distinct avec sa propre conversation. | |
| 24 | + | |
| 25 | +## Placer la configuration de l'agent à côté | |
| 26 | + | |
| 27 | +La plupart des agents ont leur propre fichier de configuration, et `.turbo-python/` est un endroit raisonnable pour le garder afin qu'il voyage avec le projet. Pour `docker agent`, l'enregistrer sous `.turbo-python/agent.yaml` correspond aux `args` ci-dessus : | |
| 28 | + | |
| 29 | +```yaml | |
| 30 | +providers: | |
| 31 | + llamacpp: | |
| 32 | + api_type: openai_chatcompletions | |
| 33 | + base_url: http://localhost:8080/v1 | |
| 34 | + | |
| 35 | +models: | |
| 36 | + mellum2: | |
| 37 | + provider: llamacpp | |
| 38 | + model: JetBrains/Mellum2-12B-A2.5B-Instruct-GGUF-Q4_K_M:Q4_K_M | |
| 39 | + temperature: 0.7 | |
| 40 | + provider_opts: | |
| 41 | + context_size: 262144 | |
| 42 | + | |
| 43 | +agents: | |
| 44 | + root: | |
| 45 | + model: mellum2 | |
| 46 | + description: A helpful AI assistant running on a local llama.cpp server | |
| 47 | + instruction: | | |
| 48 | + You name is Bob 🤓, you are a knowledgeable code assistant. | |
| 49 | + Be helpful, accurate, and concise in your responses. | |
| 50 | + You have access to the local filesystem and shell: use these tools | |
| 51 | + toolsets: | |
| 52 | + - type: filesystem | |
| 53 | + - type: shell | |
| 54 | +``` | |
| 55 | + | |
| 56 | +## Ouvrir une fenêtre dessus | |
| 57 | + | |
| 58 | +Appuyez sur `Alt-A`, ou choisissez **Agent** dans la barre de menus, puis l'agent par son nom. | |
| 59 | + | |
| 60 | +Une fenêtre s'ouvre, coupée en deux : la conversation en haut, une zone de saisie en bas. L'agent est démarré à l'ouverture de la fenêtre et arrêté à sa fermeture. | |
| 61 | + | |
| 62 | +``` | |
| 63 | +┌ Bob (llama.cpp) ───────────────────────────────[■]┐ | |
| 64 | +│ ‣ Vous │ | |
| 65 | +│ Que fait buildMenus ? │ | |
| 66 | +│ │ | |
| 67 | +│ ‣ Shell ls -1 internal/ ✓ fini │ | |
| 68 | +│ golang │ | |
| 69 | +│ │ | |
| 70 | +│ ‣ Bob │ | |
| 71 | +│ Elle assemble la barre de menus. Sa forme : │ | |
| 72 | +│ │ | |
| 73 | +│ ```python │ | |
| 74 | +│ func (a *App) buildMenus() *ui.MenuBar { │ | |
| 75 | +│ return ui.NewMenuBar(a.allMenus()...) │ | |
| 76 | +│ } │ | |
| 77 | +│ ``` │ | |
| 78 | +├───────────────────────────────────────────────────┤ | |
| 79 | +│ > _ │ | |
| 80 | +└───────────────────────────────────────────────────┘ | |
| 81 | +``` | |
| 82 | + | |
| 83 | +Le code que l'agent envoie dans un bloc délimité est coloré par les mêmes analyseurs que l'éditeur utilise pour les fichiers : une réponse en Python est colorée comme du Python, une réponse en shell comme du shell. Un bloc annonçant un langage que l'éditeur ne colore pas est laissé brut plutôt que deviné. | |
| 84 | + | |
| 85 | +## Tenir la conversation | |
| 86 | + | |
| 87 | +| Touche | Effet | | |
| 88 | +| --- | --- | | |
| 89 | +| `Entrée` | Envoyer ce qui est saisi | | |
| 90 | +| `Alt-Entrée` | Passer à la ligne au lieu d'envoyer | | |
| 91 | +| `Tab` | Passer de la conversation à la zone de saisie, et retour | | |
| 92 | +| `PgUp` `PgDn` | Faire défiler la conversation d'un écran | | |
| 93 | +| `Échap` | Arrêter le tour en cours | | |
| 94 | +| `Ctrl-W` | Fermer la fenêtre, et arrêter l'agent avec elle | | |
| 95 | + | |
| 96 | +Pendant que l'agent répond, sa réponse s'affiche au fil de l'écriture plutôt que d'un bloc, et la règle entre les deux zones fait tourner un indicateur à côté du mot *thinking*. `Échap` l'interrompt — l'agent reçoit l'ordre de s'arrêter, et ce qu'il avait déjà dit reste dans la fenêtre. | |
| 97 | + | |
| 98 | +## Utiliser les commandes propres à l'agent | |
| 99 | + | |
| 100 | +Certains agents répondent à des commandes — `/compact`, `/web`, `/plan` — et disent à l'éditeur lesquelles. Tapez `/` comme premier caractère de la zone de saisie et la liste s'ouvre par-dessus la conversation : chaque commande, ce qu'elle fait, et entre chevrons ce qu'elle attend après son nom. | |
| 101 | + | |
| 102 | +Continuez à taper pour la réduire, `↑` `↓` pour vous déplacer, puis `Tab` pour compléter. Une commande qui attend quelque chose est complétée avec une espace après elle, prête à recevoir la suite ; appuyez sur `Entrée` quand la ligne dit ce que vous voulez. Si rien n'apparaît quand vous tapez `/`, l'agent n'a annoncé aucune commande — **Agent ▸ Agent status** le dit — et `/` n'est qu'un caractère. | |
| 103 | + | |
| 104 | +## Désigner un fichier à l'agent | |
| 105 | + | |
| 106 | +Tapez `@` n'importe où dans la zone de saisie et les fichiers du projet apparaissent. Tapez quelques lettres du nom du fichier pour réduire la liste, `Tab` pour prendre celui en surbrillance : | |
| 107 | + | |
| 108 | +``` | |
| 109 | +> explique ce que fait @internal/scanner.go | |
| 110 | +``` | |
| 111 | + | |
| 112 | +Quand vous appuyez sur `Entrée`, l'agent reçoit le **fichier**, et pas seulement son nom : son texte quand l'agent accepte le contexte incorporé, un lien vers lui sinon. Si le fichier est ouvert dans l'éditeur avec des modifications non enregistrées, c'est votre version non enregistrée qui part. La ligne reste dans la conversation telle que vous l'avez tapée. | |
| 113 | + | |
| 114 | +Plusieurs fichiers dans une invite, c'est plusieurs `@`. Un mot qui commence par `@` mais n'est pas un fichier — une adresse électronique — est laissé en texte. | |
| 115 | + | |
| 116 | +## Récupérer un morceau de la conversation | |
| 117 | + | |
| 118 | +Appuyez sur `Tab` pour placer le curseur dans la conversation. La règle change et annonce ce que font désormais les touches. | |
| 119 | + | |
| 120 | +| Touche | Effet | | |
| 121 | +| --- | --- | | |
| 122 | +| `↑` `↓` `PgUp` `PgDn` | Déplacer le curseur dans ce qui a été dit | | |
| 123 | +| `Shift-↑` `Shift-↓` | Sélectionner des lignes entières | | |
| 124 | +| Glisser à la souris | Pareil, à la main | | |
| 125 | +| `Ctrl-C` | Copier | | |
| 126 | +| `Échap` | Abandonner la sélection | | |
| 127 | +| `Tab` | Revenir à la zone de saisie | | |
| 128 | + | |
| 129 | +**Sans rien de sélectionné, `Ctrl-C` copie le bloc sur lequel est le curseur** — un bloc de code délimité, un paragraphe, la sortie d'un outil — sans le libellé de l'interlocuteur au-dessus ni la phrase qui suit. C'est presque toujours ce que vous vouliez, et cela évite de le sélectionner à la main. | |
| 130 | + | |
| 131 | +Ce qui est copié va dans **deux** presse-papiers : celui de l'éditeur, pour que `Shift-Ins` le colle dans un fichier ouvert ici, et celui du système, pour que `Ctrl-V` le colle n'importe où ailleurs. L'indentation d'affichage de la conversation est retirée, donc le code collé arrive collé à la marge. | |
| 132 | + | |
| 133 | +La moitié « système » passe par votre terminal (une séquence d'échappement nommée OSC 52). La plupart des terminaux la gèrent ; quelques-uns la refusent par sécurité, et certains demandent de l'activer. Si `Ctrl-V` ailleurs ne donne rien, c'est là qu'il faut regarder — le presse-papiers de l'éditeur contient le texte dans tous les cas. | |
| 134 | + | |
| 135 | +## Répondre quand l'agent demande la permission | |
| 136 | + | |
| 137 | +Un agent doté d'un outil shell ou d'un outil de fichiers demande avant de s'en servir. Une boîte de dialogue nomme l'outil et la commande exacte, et propose les choix que l'agent lui-même a proposés — d'ordinaire *Autoriser*, *Autoriser et retenir mon choix*, et *Passer*. | |
| 138 | + | |
| 139 | +``` | |
| 140 | +┌────────── Bob (llama.cpp) veut lancer ──────────┐ | |
| 141 | +│ │ | |
| 142 | +│ Shell │ | |
| 143 | +│ ls -1 │ | |
| 144 | +│ │ | |
| 145 | +│ [ Autoriser ] [ Toujours ] [ Passer ] │ | |
| 146 | +└─────────────────────────────────────────────────┘ | |
| 147 | +``` | |
| 148 | + | |
| 149 | +*Toujours* est retenu par l'agent, pas par l'éditeur : ce que cela couvre et combien de temps cela dure sont l'affaire de l'agent. Échap équivaut à *Passer*. | |
| 150 | + | |
| 151 | +Rien ne s'exécute avant votre réponse. Un agent en attente d'une boîte de permission est simplement bloqué, et c'est bien le but. | |
| 152 | + | |
| 153 | +## Laisser l'agent voir ce qui n'est pas encore enregistré | |
| 154 | + | |
| 155 | +L'éditeur offre à l'agent son propre système de fichiers : quand l'agent lit un fichier que vous avez ouvert avec des modifications non enregistrées, il reçoit **le texte du tampon**, pas le texte plus ancien du disque. C'est généralement ce qu'on veut — vous posez une question sur la modification que vous venez de faire. | |
| 156 | + | |
| 157 | +Quand l'agent écrit un fichier, la modification arrive dans le tampon et la fenêtre est marquée modifiée : vous pouvez la lire, l'annuler avec `Ctrl-Z`, ou l'enregistrer avec `F2`. Un fichier que vous n'avez pas ouvert est lu et écrit directement sur le disque. | |
| 158 | + | |
| 159 | +## Faire tourner plusieurs agents à la fois | |
| 160 | + | |
| 161 | +Chaque fenêtre est son propre processus et sa propre conversation. Ouvrir deux fois le même agent donne deux sessions indépendantes, et ouvrir deux agents différents permet de mettre côte à côte un modèle local rapide et un modèle lent et soigneux — **Window ▸ Tile** les dispose. | |
| 162 | + | |
| 163 | +Quitter l'éditeur arrête tous les agents. | |
| 164 | + | |
| 165 | +## Variantes | |
| 166 | + | |
| 167 | +- **Vous voulez que l'agent tourne ailleurs qu'à la racine du projet.** Ajoutez `cwd = "backend"` à son bloc. Le chemin est relatif au projet, et c'est à la fois l'endroit où le processus démarre et le dossier de travail annoncé à l'agent. | |
| 168 | +- **L'agent a besoin d'un identifiant.** Mettez-le dans `env`, ou comptez sur sa présence dans l'environnement depuis lequel vous lancez l'éditeur — l'agent en hérite. | |
| 169 | +- **Les commandes de l'agent n'apparaissent pas quand vous tapez `/`.** Ouvrez **Agent ▸ Agent status** avec la fenêtre devant. S'il ne liste aucune commande, l'agent n'en a annoncé aucune — ou les a annoncées dans une forme que cet éditeur n'a pas su lire, auquel cas la boîte nomme la mise à jour et l'erreur de décodage. Pour voir exactement ce qui est passé sur le fil, lancez l'éditeur avec `TURBO_ACP_TRACE=/tmp/acp.log` et lisez le fichier : `->` est ce que l'éditeur a envoyé, `<-` ce que l'agent a répondu. | |
| 170 | +- **L'agent ne démarre pas.** **Agent ▸ Agent status** liste ce qui a été lu dans `acp.toml`, la ligne de commande obtenue pour chaque agent, et l'erreur de tout ce qui n'a pas démarré. Ce que l'agent écrit sur sa sortie d'erreur y figure aussi, et c'est là qu'un point d'accès de modèle mal configuré se signale. | |
| 171 | +- **Vous gardez le même agent dans tous les projets.** Mettez le bloc `[[agent]]` dans `~/.config/turbo-python/acp.toml`. Le fichier du projet est lu ensuite, et un agent du même `name` y remplace le vôtre. | |
| 172 | + | |
| 173 | +## Voir aussi | |
| 174 | + | |
| 175 | +- Chaque clé du fichier, et la part exacte du protocole implémentée : [référence Agents et ACP](../reference/acp.md) | |
| 176 | +- Pourquoi un agent est une fenêtre et non un panneau, et pourquoi les permissions sont modales : [Fenêtres agent](../explanation/agent-windows.md) | |
| 177 | +- Le protocole lui-même : [agentclientprotocol.com](https://agentclientprotocol.com) | |
| new file mode 100644 | |||
| @@ -0,0 +1,177 @@ | |||
| 1 | +# Dialoguer avec un agent de code depuis l'éditeur | ||
| 2 | + | ||
| 3 | +Ce guide montre comment pointer Turbo Python vers un agent qui parle l'[Agent Client Protocol](https://agentclientprotocol.com), ouvrir une fenêtre dessus, et tenir une conversation sur le code en cours d'édition. Il suppose que Turbo Python est déjà lancé dans un projet. | ||
| 4 | + | ||
| 5 | +Turbo Python est un **client** ACP. Il lance l'agent comme processus fils et lui parle en JSON-RPC sur son entrée et sa sortie standard — le même montage que Zed, donc un agent qui fonctionne là-bas fonctionne ici. | ||
| 6 | + | ||
| 7 | +## Déclarer un agent à l'éditeur | ||
| 8 | + | ||
| 9 | +Les agents sont listés dans `acp.toml`. Choisissez **Agent ▸ Create agents file** et l'éditeur écrit un fichier de départ dans `.turbo-python/acp.toml`, puis l'ouvre. | ||
| 10 | + | ||
| 11 | +Un agent, c'est un bloc `[[agent]]` : | ||
| 12 | + | ||
| 13 | +```toml | ||
| 14 | +[[agent]] | ||
| 15 | +name = "Bob (llama.cpp)" | ||
| 16 | +command = "docker" | ||
| 17 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | ||
| 18 | +env = { TELEMETRY_ENABLED = "false" } | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +`name` est ce qu'affiche le menu Agent et le nom de la fenêtre. `command` et `args` disent comment démarrer l'agent. C'est tout — le fichier est relu à chaque ouverture de fenêtre, donc on ne redémarre jamais l'éditeur pour essayer une modification. | ||
| 22 | + | ||
| 23 | +Listez-en autant que vous voulez. Chacun devient une ligne du menu, et chaque fenêtre ouverte depuis cette ligne est un processus distinct avec sa propre conversation. | ||
| 24 | + | ||
| 25 | +## Placer la configuration de l'agent à côté | ||
| 26 | + | ||
| 27 | +La plupart des agents ont leur propre fichier de configuration, et `.turbo-python/` est un endroit raisonnable pour le garder afin qu'il voyage avec le projet. Pour `docker agent`, l'enregistrer sous `.turbo-python/agent.yaml` correspond aux `args` ci-dessus : | ||
| 28 | + | ||
| 29 | +```yaml | ||
| 30 | +providers: | ||
| 31 | + llamacpp: | ||
| 32 | + api_type: openai_chatcompletions | ||
| 33 | + base_url: http://localhost:8080/v1 | ||
| 34 | + | ||
| 35 | +models: | ||
| 36 | + mellum2: | ||
| 37 | + provider: llamacpp | ||
| 38 | + model: JetBrains/Mellum2-12B-A2.5B-Instruct-GGUF-Q4_K_M:Q4_K_M | ||
| 39 | + temperature: 0.7 | ||
| 40 | + provider_opts: | ||
| 41 | + context_size: 262144 | ||
| 42 | + | ||
| 43 | +agents: | ||
| 44 | + root: | ||
| 45 | + model: mellum2 | ||
| 46 | + description: A helpful AI assistant running on a local llama.cpp server | ||
| 47 | + instruction: | | ||
| 48 | + You name is Bob 🤓, you are a knowledgeable code assistant. | ||
| 49 | + Be helpful, accurate, and concise in your responses. | ||
| 50 | + You have access to the local filesystem and shell: use these tools | ||
| 51 | + toolsets: | ||
| 52 | + - type: filesystem | ||
| 53 | + - type: shell | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +## Ouvrir une fenêtre dessus | ||
| 57 | + | ||
| 58 | +Appuyez sur `Alt-A`, ou choisissez **Agent** dans la barre de menus, puis l'agent par son nom. | ||
| 59 | + | ||
| 60 | +Une fenêtre s'ouvre, coupée en deux : la conversation en haut, une zone de saisie en bas. L'agent est démarré à l'ouverture de la fenêtre et arrêté à sa fermeture. | ||
| 61 | + | ||
| 62 | +``` | ||
| 63 | +┌ Bob (llama.cpp) ───────────────────────────────[■]┐ | ||
| 64 | +│ ‣ Vous │ | ||
| 65 | +│ Que fait buildMenus ? │ | ||
| 66 | +│ │ | ||
| 67 | +│ ‣ Shell ls -1 internal/ ✓ fini │ | ||
| 68 | +│ golang │ | ||
| 69 | +│ │ | ||
| 70 | +│ ‣ Bob │ | ||
| 71 | +│ Elle assemble la barre de menus. Sa forme : │ | ||
| 72 | +│ │ | ||
| 73 | +│ ```python │ | ||
| 74 | +│ func (a *App) buildMenus() *ui.MenuBar { │ | ||
| 75 | +│ return ui.NewMenuBar(a.allMenus()...) │ | ||
| 76 | +│ } │ | ||
| 77 | +│ ``` │ | ||
| 78 | +├───────────────────────────────────────────────────┤ | ||
| 79 | +│ > _ │ | ||
| 80 | +└───────────────────────────────────────────────────┘ | ||
| 81 | +``` | ||
| 82 | + | ||
| 83 | +Le code que l'agent envoie dans un bloc délimité est coloré par les mêmes analyseurs que l'éditeur utilise pour les fichiers : une réponse en Python est colorée comme du Python, une réponse en shell comme du shell. Un bloc annonçant un langage que l'éditeur ne colore pas est laissé brut plutôt que deviné. | ||
| 84 | + | ||
| 85 | +## Tenir la conversation | ||
| 86 | + | ||
| 87 | +| Touche | Effet | | ||
| 88 | +| --- | --- | | ||
| 89 | +| `Entrée` | Envoyer ce qui est saisi | | ||
| 90 | +| `Alt-Entrée` | Passer à la ligne au lieu d'envoyer | | ||
| 91 | +| `Tab` | Passer de la conversation à la zone de saisie, et retour | | ||
| 92 | +| `PgUp` `PgDn` | Faire défiler la conversation d'un écran | | ||
| 93 | +| `Échap` | Arrêter le tour en cours | | ||
| 94 | +| `Ctrl-W` | Fermer la fenêtre, et arrêter l'agent avec elle | | ||
| 95 | + | ||
| 96 | +Pendant que l'agent répond, sa réponse s'affiche au fil de l'écriture plutôt que d'un bloc, et la règle entre les deux zones fait tourner un indicateur à côté du mot *thinking*. `Échap` l'interrompt — l'agent reçoit l'ordre de s'arrêter, et ce qu'il avait déjà dit reste dans la fenêtre. | ||
| 97 | + | ||
| 98 | +## Utiliser les commandes propres à l'agent | ||
| 99 | + | ||
| 100 | +Certains agents répondent à des commandes — `/compact`, `/web`, `/plan` — et disent à l'éditeur lesquelles. Tapez `/` comme premier caractère de la zone de saisie et la liste s'ouvre par-dessus la conversation : chaque commande, ce qu'elle fait, et entre chevrons ce qu'elle attend après son nom. | ||
| 101 | + | ||
| 102 | +Continuez à taper pour la réduire, `↑` `↓` pour vous déplacer, puis `Tab` pour compléter. Une commande qui attend quelque chose est complétée avec une espace après elle, prête à recevoir la suite ; appuyez sur `Entrée` quand la ligne dit ce que vous voulez. Si rien n'apparaît quand vous tapez `/`, l'agent n'a annoncé aucune commande — **Agent ▸ Agent status** le dit — et `/` n'est qu'un caractère. | ||
| 103 | + | ||
| 104 | +## Désigner un fichier à l'agent | ||
| 105 | + | ||
| 106 | +Tapez `@` n'importe où dans la zone de saisie et les fichiers du projet apparaissent. Tapez quelques lettres du nom du fichier pour réduire la liste, `Tab` pour prendre celui en surbrillance : | ||
| 107 | + | ||
| 108 | +``` | ||
| 109 | +> explique ce que fait @internal/scanner.go | ||
| 110 | +``` | ||
| 111 | + | ||
| 112 | +Quand vous appuyez sur `Entrée`, l'agent reçoit le **fichier**, et pas seulement son nom : son texte quand l'agent accepte le contexte incorporé, un lien vers lui sinon. Si le fichier est ouvert dans l'éditeur avec des modifications non enregistrées, c'est votre version non enregistrée qui part. La ligne reste dans la conversation telle que vous l'avez tapée. | ||
| 113 | + | ||
| 114 | +Plusieurs fichiers dans une invite, c'est plusieurs `@`. Un mot qui commence par `@` mais n'est pas un fichier — une adresse électronique — est laissé en texte. | ||
| 115 | + | ||
| 116 | +## Récupérer un morceau de la conversation | ||
| 117 | + | ||
| 118 | +Appuyez sur `Tab` pour placer le curseur dans la conversation. La règle change et annonce ce que font désormais les touches. | ||
| 119 | + | ||
| 120 | +| Touche | Effet | | ||
| 121 | +| --- | --- | | ||
| 122 | +| `↑` `↓` `PgUp` `PgDn` | Déplacer le curseur dans ce qui a été dit | | ||
| 123 | +| `Shift-↑` `Shift-↓` | Sélectionner des lignes entières | | ||
| 124 | +| Glisser à la souris | Pareil, à la main | | ||
| 125 | +| `Ctrl-C` | Copier | | ||
| 126 | +| `Échap` | Abandonner la sélection | | ||
| 127 | +| `Tab` | Revenir à la zone de saisie | | ||
| 128 | + | ||
| 129 | +**Sans rien de sélectionné, `Ctrl-C` copie le bloc sur lequel est le curseur** — un bloc de code délimité, un paragraphe, la sortie d'un outil — sans le libellé de l'interlocuteur au-dessus ni la phrase qui suit. C'est presque toujours ce que vous vouliez, et cela évite de le sélectionner à la main. | ||
| 130 | + | ||
| 131 | +Ce qui est copié va dans **deux** presse-papiers : celui de l'éditeur, pour que `Shift-Ins` le colle dans un fichier ouvert ici, et celui du système, pour que `Ctrl-V` le colle n'importe où ailleurs. L'indentation d'affichage de la conversation est retirée, donc le code collé arrive collé à la marge. | ||
| 132 | + | ||
| 133 | +La moitié « système » passe par votre terminal (une séquence d'échappement nommée OSC 52). La plupart des terminaux la gèrent ; quelques-uns la refusent par sécurité, et certains demandent de l'activer. Si `Ctrl-V` ailleurs ne donne rien, c'est là qu'il faut regarder — le presse-papiers de l'éditeur contient le texte dans tous les cas. | ||
| 134 | + | ||
| 135 | +## Répondre quand l'agent demande la permission | ||
| 136 | + | ||
| 137 | +Un agent doté d'un outil shell ou d'un outil de fichiers demande avant de s'en servir. Une boîte de dialogue nomme l'outil et la commande exacte, et propose les choix que l'agent lui-même a proposés — d'ordinaire *Autoriser*, *Autoriser et retenir mon choix*, et *Passer*. | ||
| 138 | + | ||
| 139 | +``` | ||
| 140 | +┌────────── Bob (llama.cpp) veut lancer ──────────┐ | ||
| 141 | +│ │ | ||
| 142 | +│ Shell │ | ||
| 143 | +│ ls -1 │ | ||
| 144 | +│ │ | ||
| 145 | +│ [ Autoriser ] [ Toujours ] [ Passer ] │ | ||
| 146 | +└─────────────────────────────────────────────────┘ | ||
| 147 | +``` | ||
| 148 | + | ||
| 149 | +*Toujours* est retenu par l'agent, pas par l'éditeur : ce que cela couvre et combien de temps cela dure sont l'affaire de l'agent. Échap équivaut à *Passer*. | ||
| 150 | + | ||
| 151 | +Rien ne s'exécute avant votre réponse. Un agent en attente d'une boîte de permission est simplement bloqué, et c'est bien le but. | ||
| 152 | + | ||
| 153 | +## Laisser l'agent voir ce qui n'est pas encore enregistré | ||
| 154 | + | ||
| 155 | +L'éditeur offre à l'agent son propre système de fichiers : quand l'agent lit un fichier que vous avez ouvert avec des modifications non enregistrées, il reçoit **le texte du tampon**, pas le texte plus ancien du disque. C'est généralement ce qu'on veut — vous posez une question sur la modification que vous venez de faire. | ||
| 156 | + | ||
| 157 | +Quand l'agent écrit un fichier, la modification arrive dans le tampon et la fenêtre est marquée modifiée : vous pouvez la lire, l'annuler avec `Ctrl-Z`, ou l'enregistrer avec `F2`. Un fichier que vous n'avez pas ouvert est lu et écrit directement sur le disque. | ||
| 158 | + | ||
| 159 | +## Faire tourner plusieurs agents à la fois | ||
| 160 | + | ||
| 161 | +Chaque fenêtre est son propre processus et sa propre conversation. Ouvrir deux fois le même agent donne deux sessions indépendantes, et ouvrir deux agents différents permet de mettre côte à côte un modèle local rapide et un modèle lent et soigneux — **Window ▸ Tile** les dispose. | ||
| 162 | + | ||
| 163 | +Quitter l'éditeur arrête tous les agents. | ||
| 164 | + | ||
| 165 | +## Variantes | ||
| 166 | + | ||
| 167 | +- **Vous voulez que l'agent tourne ailleurs qu'à la racine du projet.** Ajoutez `cwd = "backend"` à son bloc. Le chemin est relatif au projet, et c'est à la fois l'endroit où le processus démarre et le dossier de travail annoncé à l'agent. | ||
| 168 | +- **L'agent a besoin d'un identifiant.** Mettez-le dans `env`, ou comptez sur sa présence dans l'environnement depuis lequel vous lancez l'éditeur — l'agent en hérite. | ||
| 169 | +- **Les commandes de l'agent n'apparaissent pas quand vous tapez `/`.** Ouvrez **Agent ▸ Agent status** avec la fenêtre devant. S'il ne liste aucune commande, l'agent n'en a annoncé aucune — ou les a annoncées dans une forme que cet éditeur n'a pas su lire, auquel cas la boîte nomme la mise à jour et l'erreur de décodage. Pour voir exactement ce qui est passé sur le fil, lancez l'éditeur avec `TURBO_ACP_TRACE=/tmp/acp.log` et lisez le fichier : `->` est ce que l'éditeur a envoyé, `<-` ce que l'agent a répondu. | ||
| 170 | +- **L'agent ne démarre pas.** **Agent ▸ Agent status** liste ce qui a été lu dans `acp.toml`, la ligne de commande obtenue pour chaque agent, et l'erreur de tout ce qui n'a pas démarré. Ce que l'agent écrit sur sa sortie d'erreur y figure aussi, et c'est là qu'un point d'accès de modèle mal configuré se signale. | ||
| 171 | +- **Vous gardez le même agent dans tous les projets.** Mettez le bloc `[[agent]]` dans `~/.config/turbo-python/acp.toml`. Le fichier du projet est lu ensuite, et un agent du même `name` y remplace le vôtre. | ||
| 172 | + | ||
| 173 | +## Voir aussi | ||
| 174 | + | ||
| 175 | +- Chaque clé du fichier, et la part exacte du protocole implémentée : [référence Agents et ACP](../reference/acp.md) | ||
| 176 | +- Pourquoi un agent est une fenêtre et non un panneau, et pourquoi les permissions sont modales : [Fenêtres agent](../explanation/agent-windows.md) | ||
| 177 | +- Le protocole lui-même : [agentclientprotocol.com](https://agentclientprotocol.com) | ||
added
docs/fr/how-to/use-a-terminal.md +61 -0 | new file mode 100644 | ||
| @@ -0,0 +1,61 @@ | ||
| 1 | +# Lancer des commandes shell sans quitter l'éditeur | |
| 2 | + | |
| 3 | +Ce guide montre comment ouvrir une fenêtre terminal, y compiler et tester le code en cours d'édition, puis revenir au fichier. Il suppose que Turbo Python est déjà lancé avec un fichier ouvert. | |
| 4 | + | |
| 5 | +## Ouvrir un terminal | |
| 6 | + | |
| 7 | +Appuyez sur `F8`, ou choisissez **Window ▸ New terminal**. | |
| 8 | + | |
| 9 | +Une nouvelle fenêtre s'ouvre avec votre shell, dans le dossier du fichier que vous étiez en train d'éditer. C'est normalement le dossier voulu : `uv sync` et `git diff` portent tous deux sur le paquet que vous avez sous les yeux. | |
| 10 | + | |
| 11 | +La fenêtre porte le nom du shell, et se renomme dès qu'un programme lancé dedans définit un titre — `vim`, `htop` et `ssh` le font tous. | |
| 12 | + | |
| 13 | +## Lancer quelque chose | |
| 14 | + | |
| 15 | +Tapez dedans comme dans n'importe quel terminal. Le shell reçoit presque toutes les touches, y compris celles que l'éditeur utiliserait autrement : `Ctrl-C` interrompt, `Ctrl-W` supprime un mot, `Ctrl-R` cherche dans l'historique. | |
| 16 | + | |
| 17 | +Ce que l'éditeur conserve est court, et voulu — c'est le chemin de sortie : | |
| 18 | + | |
| 19 | +| Touche | Effet, même avec un terminal au premier plan | | |
| 20 | +| --- | --- | | |
| 21 | +| `F8` | Ouvrir un autre terminal | | |
| 22 | +| `F6` | Passer à la fenêtre suivante | | |
| 23 | +| `F10` | Ouvrir la barre de menus | | |
| 24 | +| `F2` `F3` `F4` | Enregistrer, Ouvrir, Nouveau | | |
| 25 | +| `Alt-1` … `Alt-9` | Passer cette fenêtre au premier plan | | |
| 26 | +| `Alt-X` | Quitter l'éditeur | | |
| 27 | + | |
| 28 | +## Relire ce qui a défilé | |
| 29 | + | |
| 30 | +`Shift-PgUp` et `Shift-PgDn` parcourent l'historique un écran à la fois ; la molette déplace de trois lignes. Deux mille lignes sont conservées. | |
| 31 | + | |
| 32 | +Taper quoi que ce soit ramène directement à l'écran vivant : jamais besoin de redescendre avant de lancer la commande suivante. | |
| 33 | + | |
| 34 | +## Travailler avec le fichier et le shell côte à côte | |
| 35 | + | |
| 36 | +Un terminal est une fenêtre ordinaire, donc toutes les commandes de fenêtre s'y appliquent : | |
| 37 | + | |
| 38 | +- **Window ▸ Tile** place le fichier et le terminal côte à côte. | |
| 39 | +- **Window ▸ Maximise**, ou la case `[■]` à droite de sa barre de titre, donne tout le bureau au terminal pendant une compilation. La case affiche alors `[▬]`, et l'actionner remet la fenêtre en place. | |
| 40 | +- Tirez son coin inférieur droit pour le redimensionner — le shell est prévenu de sa nouvelle taille, donc `less` et `vim` se réajustent. | |
| 41 | + | |
| 42 | +## Le fermer | |
| 43 | + | |
| 44 | +`Ctrl-W` appartient au shell, pas à l'éditeur : fermer un terminal se fait donc autrement. | |
| 45 | + | |
| 46 | +- **File ▸ Close**, ou | |
| 47 | +- cliquez sur la case `[x]` dans son coin supérieur gauche. | |
| 48 | + | |
| 49 | +L'un comme l'autre terminent le shell qui y tourne. Rien n'est demandé au préalable : un terminal contient un processus en cours, pas un travail non enregistré, et fermer la fenêtre est la façon de dire que vous en avez fini. Quitter l'éditeur ferme tous les terminaux d'un coup. | |
| 50 | + | |
| 51 | +## Variantes | |
| 52 | + | |
| 53 | +- **Vous voulez un autre shell.** Le shell est pris dans `$SHELL`, avec `/bin/sh` par défaut ; sous Windows dans `%COMSPEC%`, avec `cmd.exe` par défaut. Lancez l'éditeur avec `SHELL=/bin/zsh turbo-python` pour le changer le temps d'une session. | |
| 54 | +- **Aucun fichier n'est ouvert.** Le terminal démarre dans le dossier depuis lequel l'éditeur a été lancé. | |
| 55 | +- **Vous êtes sous Windows.** Les fenêtres terminal tournent dans une pseudo-console (ConPTY), ce qui demande Windows 10 version 1809 ou plus récent, et le shell est `%COMSPEC%` — cmd.exe. Ce chemin a été compilé et vérifié mais pas encore exécuté par les auteurs, qui travaillent sous Linux et macOS. La première fois, essayez les cinq choses qu'il doit réussir — `F8`, tapez `dir`, redimensionnez la fenêtre, lancez une commande du menu qui dit `output = "terminal"`, et interrompez une commande longue avec `Ctrl-C` — et signalez ce qui ne s'est pas comporté comme attendu. | |
| 56 | + | |
| 57 | +## Voir aussi | |
| 58 | + | |
| 59 | +- Tout ce que le terminal implémente, exactement : [référence des fenêtres terminal](../reference/terminal.md) | |
| 60 | +- Pourquoi il lance un vrai shell plutôt que de capturer la sortie d'une commande : [Fenêtres terminal](../explanation/terminal-windows.md) | |
| 61 | +- Les couleurs qu'il utilise : [Format des fichiers de thème](../reference/themes.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | +# Lancer des commandes shell sans quitter l'éditeur | ||
| 2 | + | ||
| 3 | +Ce guide montre comment ouvrir une fenêtre terminal, y compiler et tester le code en cours d'édition, puis revenir au fichier. Il suppose que Turbo Python est déjà lancé avec un fichier ouvert. | ||
| 4 | + | ||
| 5 | +## Ouvrir un terminal | ||
| 6 | + | ||
| 7 | +Appuyez sur `F8`, ou choisissez **Window ▸ New terminal**. | ||
| 8 | + | ||
| 9 | +Une nouvelle fenêtre s'ouvre avec votre shell, dans le dossier du fichier que vous étiez en train d'éditer. C'est normalement le dossier voulu : `uv sync` et `git diff` portent tous deux sur le paquet que vous avez sous les yeux. | ||
| 10 | + | ||
| 11 | +La fenêtre porte le nom du shell, et se renomme dès qu'un programme lancé dedans définit un titre — `vim`, `htop` et `ssh` le font tous. | ||
| 12 | + | ||
| 13 | +## Lancer quelque chose | ||
| 14 | + | ||
| 15 | +Tapez dedans comme dans n'importe quel terminal. Le shell reçoit presque toutes les touches, y compris celles que l'éditeur utiliserait autrement : `Ctrl-C` interrompt, `Ctrl-W` supprime un mot, `Ctrl-R` cherche dans l'historique. | ||
| 16 | + | ||
| 17 | +Ce que l'éditeur conserve est court, et voulu — c'est le chemin de sortie : | ||
| 18 | + | ||
| 19 | +| Touche | Effet, même avec un terminal au premier plan | | ||
| 20 | +| --- | --- | | ||
| 21 | +| `F8` | Ouvrir un autre terminal | | ||
| 22 | +| `F6` | Passer à la fenêtre suivante | | ||
| 23 | +| `F10` | Ouvrir la barre de menus | | ||
| 24 | +| `F2` `F3` `F4` | Enregistrer, Ouvrir, Nouveau | | ||
| 25 | +| `Alt-1` … `Alt-9` | Passer cette fenêtre au premier plan | | ||
| 26 | +| `Alt-X` | Quitter l'éditeur | | ||
| 27 | + | ||
| 28 | +## Relire ce qui a défilé | ||
| 29 | + | ||
| 30 | +`Shift-PgUp` et `Shift-PgDn` parcourent l'historique un écran à la fois ; la molette déplace de trois lignes. Deux mille lignes sont conservées. | ||
| 31 | + | ||
| 32 | +Taper quoi que ce soit ramène directement à l'écran vivant : jamais besoin de redescendre avant de lancer la commande suivante. | ||
| 33 | + | ||
| 34 | +## Travailler avec le fichier et le shell côte à côte | ||
| 35 | + | ||
| 36 | +Un terminal est une fenêtre ordinaire, donc toutes les commandes de fenêtre s'y appliquent : | ||
| 37 | + | ||
| 38 | +- **Window ▸ Tile** place le fichier et le terminal côte à côte. | ||
| 39 | +- **Window ▸ Maximise**, ou la case `[■]` à droite de sa barre de titre, donne tout le bureau au terminal pendant une compilation. La case affiche alors `[▬]`, et l'actionner remet la fenêtre en place. | ||
| 40 | +- Tirez son coin inférieur droit pour le redimensionner — le shell est prévenu de sa nouvelle taille, donc `less` et `vim` se réajustent. | ||
| 41 | + | ||
| 42 | +## Le fermer | ||
| 43 | + | ||
| 44 | +`Ctrl-W` appartient au shell, pas à l'éditeur : fermer un terminal se fait donc autrement. | ||
| 45 | + | ||
| 46 | +- **File ▸ Close**, ou | ||
| 47 | +- cliquez sur la case `[x]` dans son coin supérieur gauche. | ||
| 48 | + | ||
| 49 | +L'un comme l'autre terminent le shell qui y tourne. Rien n'est demandé au préalable : un terminal contient un processus en cours, pas un travail non enregistré, et fermer la fenêtre est la façon de dire que vous en avez fini. Quitter l'éditeur ferme tous les terminaux d'un coup. | ||
| 50 | + | ||
| 51 | +## Variantes | ||
| 52 | + | ||
| 53 | +- **Vous voulez un autre shell.** Le shell est pris dans `$SHELL`, avec `/bin/sh` par défaut ; sous Windows dans `%COMSPEC%`, avec `cmd.exe` par défaut. Lancez l'éditeur avec `SHELL=/bin/zsh turbo-python` pour le changer le temps d'une session. | ||
| 54 | +- **Aucun fichier n'est ouvert.** Le terminal démarre dans le dossier depuis lequel l'éditeur a été lancé. | ||
| 55 | +- **Vous êtes sous Windows.** Les fenêtres terminal tournent dans une pseudo-console (ConPTY), ce qui demande Windows 10 version 1809 ou plus récent, et le shell est `%COMSPEC%` — cmd.exe. Ce chemin a été compilé et vérifié mais pas encore exécuté par les auteurs, qui travaillent sous Linux et macOS. La première fois, essayez les cinq choses qu'il doit réussir — `F8`, tapez `dir`, redimensionnez la fenêtre, lancez une commande du menu qui dit `output = "terminal"`, et interrompez une commande longue avec `Ctrl-C` — et signalez ce qui ne s'est pas comporté comme attendu. | ||
| 56 | + | ||
| 57 | +## Voir aussi | ||
| 58 | + | ||
| 59 | +- Tout ce que le terminal implémente, exactement : [référence des fenêtres terminal](../reference/terminal.md) | ||
| 60 | +- Pourquoi il lance un vrai shell plutôt que de capturer la sortie d'une commande : [Fenêtres terminal](../explanation/terminal-windows.md) | ||
| 61 | +- Les couleurs qu'il utilise : [Format des fichiers de thème](../reference/themes.md) | ||
added
docs/fr/how-to/use-snippets.md +93 -0 | new file mode 100644 | ||
| @@ -0,0 +1,93 @@ | ||
| 1 | +# Insérer des snippets depuis un menu | |
| 2 | + | |
| 3 | +Ce guide montre comment mettre en place des morceaux de texte réutilisables et les insérer dans un fichier à l'endroit du curseur. Il suppose Turbo Python déjà installé. | |
| 4 | + | |
| 5 | +## Obtenir un fichier de départ | |
| 6 | + | |
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **Snippets ▸ Create snippets file** (`Alt-N`, puis `C`). | |
| 8 | + | |
| 9 | +Cela écrit `.turbo-python/snippets.toml`, rempli de quelques exemples travaillés, et l'ouvre — coloré, puisque Turbo Python colore le TOML : | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[snippet]] | |
| 13 | +name = "if err != nil" | |
| 14 | +group = "Python" | |
| 15 | +languages = ["python"] | |
| 16 | +body = """ | |
| 17 | +if err != nil { | |
| 18 | + return err | |
| 19 | +}""" | |
| 20 | + | |
| 21 | +[[snippet]] | |
| 22 | +name = "TODO" | |
| 23 | +body = "TODO: " | |
| 24 | +``` | |
| 25 | + | |
| 26 | +Chaque `[[snippet]]` devient une ligne du menu. Le fichier est relu **chaque fois que le menu s'ouvre** : une modification prend effet immédiatement, sans redémarrage. | |
| 27 | + | |
| 28 | +## En insérer un | |
| 29 | + | |
| 30 | +Ouvrez **Snippets** (`Alt-N`). Les snippets partageant un `group` apparaissent ensemble dans un sous-menu de ce nom ; celui qui n'a pas de groupe va dans **General**. | |
| 31 | + | |
| 32 | +| Touche | Effet | | |
| 33 | +| --- | --- | | |
| 34 | +| `Alt-N`, ou `F10` puis `→` jusqu'à Snippets | Ouvrir le menu | | |
| 35 | +| `↑` `↓` | Parcourir les groupes | | |
| 36 | +| `→`, ou `Entrée` | Ouvrir le groupe surligné | | |
| 37 | +| `↑` `↓` puis `Entrée` | Insérer le snippet surligné | | |
| 38 | +| `←` | Ressortir d'un groupe | | |
| 39 | +| `Échap` | Refermer tout le menu | | |
| 40 | + | |
| 41 | +Le snippet arrive au curseur. **Les lignes suivant la première sont indentées sur la ligne où vous l'avez inséré**, de sorte qu'un snippet multi-ligne déposé dans un bloc imbriqué atterrit là où vous l'auriez tapé : | |
| 42 | + | |
| 43 | +``` | |
| 44 | +func f() { | |
| 45 | + | ← curseur ici | |
| 46 | +} | |
| 47 | +``` | |
| 48 | + | |
| 49 | +devient | |
| 50 | + | |
| 51 | +``` | |
| 52 | +func f() { | |
| 53 | + if err != nil { | |
| 54 | + return err | |
| 55 | + } | |
| 56 | +} | |
| 57 | +``` | |
| 58 | + | |
| 59 | +C'est une seule opération d'annulation : `Ctrl-Z` retire tout le snippet. | |
| 60 | + | |
| 61 | +## Garder ses snippets d'un projet à l'autre | |
| 62 | + | |
| 63 | +Mettez-les dans `~/.config/turbo-python/snippets.toml` — le même dossier que vos thèmes. Ceux-là apparaissent dans tous les projets, et le fichier d'un projet s'y **ajoute** plutôt que de les remplacer. | |
| 64 | + | |
| 65 | +Quand un projet et vous employez le même `name` dans le même `group`, **celui du projet gagne** : c'est le plus spécifique des deux énoncés. | |
| 66 | + | |
| 67 | +## N'afficher un snippet que là où il a un sens | |
| 68 | + | |
| 69 | +Ajoutez `languages`, avec les noms que l'éditeur emploie — `python`, `toml`, `markdown`, `javascript`, `html`, `bash` : | |
| 70 | + | |
| 71 | +```toml | |
| 72 | +[[snippet]] | |
| 73 | +name = "strict mode" | |
| 74 | +group = "Shell" | |
| 75 | +languages = ["bash"] | |
| 76 | +body = "set -euo pipefail" | |
| 77 | +``` | |
| 78 | + | |
| 79 | +Ce snippet n'apparaît alors que si un script shell est au premier plan. Omettez `languages` et le snippet est proposé partout, ce que vous voulez pour un en-tête de licence ou un `TODO`. | |
| 80 | + | |
| 81 | +Un groupe que le filtrage laisse vide n'apparaît pas du tout. | |
| 82 | + | |
| 83 | +## Variantes | |
| 84 | + | |
| 85 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** Le fichier du projet n'est pas trouvé : seul `./.turbo-python` est consulté, la même règle que `settings.toml`. Vos propres snippets apparaissent quand même. | |
| 86 | +- **Le fichier contient une erreur.** Le menu affiche un `Cannot read snippets` grisé à la place des groupes, et **Create snippets file** est toujours là. Ouvrez le fichier et corrigez-le. | |
| 87 | +- **Vous voulez des tabulations dans un corps.** Écrivez `\t`, comme le fichier de départ — le TOML le transforme en tabulation à la lecture. | |
| 88 | + | |
| 89 | +## Voir aussi | |
| 90 | + | |
| 91 | +- Toutes les clés du fichier et toutes les règles : [Référence des snippets](../reference/snippets.md) | |
| 92 | +- Pourquoi le menu est reconstruit à chaque ouverture, et pourquoi l'insertion réindente : [Snippets](../explanation/snippets.md) | |
| 93 | +- L'autre fichier de `.turbo-python` : [Réglages de projet](../reference/project-settings.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,93 @@ | |||
| 1 | +# Insérer des snippets depuis un menu | ||
| 2 | + | ||
| 3 | +Ce guide montre comment mettre en place des morceaux de texte réutilisables et les insérer dans un fichier à l'endroit du curseur. Il suppose Turbo Python déjà installé. | ||
| 4 | + | ||
| 5 | +## Obtenir un fichier de départ | ||
| 6 | + | ||
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **Snippets ▸ Create snippets file** (`Alt-N`, puis `C`). | ||
| 8 | + | ||
| 9 | +Cela écrit `.turbo-python/snippets.toml`, rempli de quelques exemples travaillés, et l'ouvre — coloré, puisque Turbo Python colore le TOML : | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[snippet]] | ||
| 13 | +name = "if err != nil" | ||
| 14 | +group = "Python" | ||
| 15 | +languages = ["python"] | ||
| 16 | +body = """ | ||
| 17 | +if err != nil { | ||
| 18 | + return err | ||
| 19 | +}""" | ||
| 20 | + | ||
| 21 | +[[snippet]] | ||
| 22 | +name = "TODO" | ||
| 23 | +body = "TODO: " | ||
| 24 | +``` | ||
| 25 | + | ||
| 26 | +Chaque `[[snippet]]` devient une ligne du menu. Le fichier est relu **chaque fois que le menu s'ouvre** : une modification prend effet immédiatement, sans redémarrage. | ||
| 27 | + | ||
| 28 | +## En insérer un | ||
| 29 | + | ||
| 30 | +Ouvrez **Snippets** (`Alt-N`). Les snippets partageant un `group` apparaissent ensemble dans un sous-menu de ce nom ; celui qui n'a pas de groupe va dans **General**. | ||
| 31 | + | ||
| 32 | +| Touche | Effet | | ||
| 33 | +| --- | --- | | ||
| 34 | +| `Alt-N`, ou `F10` puis `→` jusqu'à Snippets | Ouvrir le menu | | ||
| 35 | +| `↑` `↓` | Parcourir les groupes | | ||
| 36 | +| `→`, ou `Entrée` | Ouvrir le groupe surligné | | ||
| 37 | +| `↑` `↓` puis `Entrée` | Insérer le snippet surligné | | ||
| 38 | +| `←` | Ressortir d'un groupe | | ||
| 39 | +| `Échap` | Refermer tout le menu | | ||
| 40 | + | ||
| 41 | +Le snippet arrive au curseur. **Les lignes suivant la première sont indentées sur la ligne où vous l'avez inséré**, de sorte qu'un snippet multi-ligne déposé dans un bloc imbriqué atterrit là où vous l'auriez tapé : | ||
| 42 | + | ||
| 43 | +``` | ||
| 44 | +func f() { | ||
| 45 | + | ← curseur ici | ||
| 46 | +} | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +devient | ||
| 50 | + | ||
| 51 | +``` | ||
| 52 | +func f() { | ||
| 53 | + if err != nil { | ||
| 54 | + return err | ||
| 55 | + } | ||
| 56 | +} | ||
| 57 | +``` | ||
| 58 | + | ||
| 59 | +C'est une seule opération d'annulation : `Ctrl-Z` retire tout le snippet. | ||
| 60 | + | ||
| 61 | +## Garder ses snippets d'un projet à l'autre | ||
| 62 | + | ||
| 63 | +Mettez-les dans `~/.config/turbo-python/snippets.toml` — le même dossier que vos thèmes. Ceux-là apparaissent dans tous les projets, et le fichier d'un projet s'y **ajoute** plutôt que de les remplacer. | ||
| 64 | + | ||
| 65 | +Quand un projet et vous employez le même `name` dans le même `group`, **celui du projet gagne** : c'est le plus spécifique des deux énoncés. | ||
| 66 | + | ||
| 67 | +## N'afficher un snippet que là où il a un sens | ||
| 68 | + | ||
| 69 | +Ajoutez `languages`, avec les noms que l'éditeur emploie — `python`, `toml`, `markdown`, `javascript`, `html`, `bash` : | ||
| 70 | + | ||
| 71 | +```toml | ||
| 72 | +[[snippet]] | ||
| 73 | +name = "strict mode" | ||
| 74 | +group = "Shell" | ||
| 75 | +languages = ["bash"] | ||
| 76 | +body = "set -euo pipefail" | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +Ce snippet n'apparaît alors que si un script shell est au premier plan. Omettez `languages` et le snippet est proposé partout, ce que vous voulez pour un en-tête de licence ou un `TODO`. | ||
| 80 | + | ||
| 81 | +Un groupe que le filtrage laisse vide n'apparaît pas du tout. | ||
| 82 | + | ||
| 83 | +## Variantes | ||
| 84 | + | ||
| 85 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** Le fichier du projet n'est pas trouvé : seul `./.turbo-python` est consulté, la même règle que `settings.toml`. Vos propres snippets apparaissent quand même. | ||
| 86 | +- **Le fichier contient une erreur.** Le menu affiche un `Cannot read snippets` grisé à la place des groupes, et **Create snippets file** est toujours là. Ouvrez le fichier et corrigez-le. | ||
| 87 | +- **Vous voulez des tabulations dans un corps.** Écrivez `\t`, comme le fichier de départ — le TOML le transforme en tabulation à la lecture. | ||
| 88 | + | ||
| 89 | +## Voir aussi | ||
| 90 | + | ||
| 91 | +- Toutes les clés du fichier et toutes les règles : [Référence des snippets](../reference/snippets.md) | ||
| 92 | +- Pourquoi le menu est reconstruit à chaque ouverture, et pourquoi l'insertion réindente : [Snippets](../explanation/snippets.md) | ||
| 93 | +- L'autre fichier de `.turbo-python` : [Réglages de projet](../reference/project-settings.md) | ||
added
docs/fr/how-to/write-a-theme.md +152 -0 | new file mode 100644 | ||
| @@ -0,0 +1,152 @@ | ||
| 1 | +# Écrire son propre thème | |
| 2 | + | |
| 3 | +Ce guide montre comment ajouter un thème de couleurs à vous. Il suppose que vous savez où se trouve votre répertoire de configuration et que vous savez éditer un fichier TOML. | |
| 4 | + | |
| 5 | +## 1. Trouver où vont les thèmes | |
| 6 | + | |
| 7 | +```bash | |
| 8 | +turbo-python -list-themes | |
| 9 | +``` | |
| 10 | + | |
| 11 | +La dernière ligne indique le répertoire — `~/.config/turbo-python/themes` sous Linux, `~/Library/Application Support/turbo-python/themes` sous macOS. Créez-le : | |
| 12 | + | |
| 13 | +```bash | |
| 14 | +mkdir -p ~/.config/turbo-python/themes | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## 2. Partir d'un thème existant | |
| 18 | + | |
| 19 | +Le plus rapide est d'hériter d'un thème qui fonctionne déjà et de ne redéfinir que ce que vous voulez : | |
| 20 | + | |
| 21 | +```toml | |
| 22 | +# ~/.config/turbo-python/themes/mine.toml | |
| 23 | +name = "Le mien" | |
| 24 | +description = "Turbo Classic, mais avec des commentaires lisibles." | |
| 25 | +inherits = "turbo-classic" | |
| 26 | + | |
| 27 | +[colors] | |
| 28 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | |
| 29 | +"syntax.string" = { fg = "#87d7af" } | |
| 30 | +``` | |
| 31 | + | |
| 32 | +Tout ce que vous ne définissez pas est repris de `turbo-classic`. | |
| 33 | + | |
| 34 | +**Héritez d'un thème dont le fond ressemble au vôtre.** Les couleurs que vous omettez ont été choisies contre le fond du thème dont vous héritez : un thème sombre bâti sur `turbo-classic` affichera, ici et là, une couleur pensée pour le marine Borland. Pour un thème sombre, héritez de `turbo-dark`, `cappuccino`, `catppuccin-frappe`, `cobalt`, `darcula` ou `monochrome-dark` ; pour un thème clair, de `borland-light`, `catppuccin-latte`, `intellij-light` ou `monochrome-light`. C'est aussi pourquoi les onze thèmes livrés dans le binaire énoncent chacun leur palette en entier au lieu d'en hériter l'essentiel — un test les y oblige, parce qu'un thème livré engage le projet. | |
| 35 | + | |
| 36 | +## 3. L'utiliser | |
| 37 | + | |
| 38 | +```bash | |
| 39 | +turbo-python -theme mine main.py | |
| 40 | +``` | |
| 41 | + | |
| 42 | +Ou depuis l'éditeur : `Options ▸ Theme…`, qui liste tous les thèmes trouvés. | |
| 43 | + | |
| 44 | +## 4. Itérer | |
| 45 | + | |
| 46 | +Modifiez le fichier, puis relancez l'éditeur. Il n'y a pas de rechargement à chaud. | |
| 47 | + | |
| 48 | +Si le thème ne se charge pas, Turbo Python retombe sur le thème par défaut plutôt que de refuser de démarrer. Pour savoir *pourquoi* : | |
| 49 | + | |
| 50 | +```bash | |
| 51 | +turbo-python -list-themes | |
| 52 | +``` | |
| 53 | + | |
| 54 | +Un thème cassé apparaît dans la liste avec l'erreur d'analyse à côté — un nom de couleur inconnu est une erreur, pas un repli silencieux : une faute de frappe est signalée au lieu de repeindre discrètement la moitié de l'écran. | |
| 55 | + | |
| 56 | +## 5. Vérifier qu'il reste lisible | |
| 57 | + | |
| 58 | +Le projet soumet chaque thème qu'il livre à cinq règles mesurées, et elles valent pour le vôtre. `make test` les exécute. | |
| 59 | + | |
| 60 | +| Règle | Pourquoi | | |
| 61 | +| --- | --- | | |
| 62 | +| Le curseur est à au moins 64 de la ligne qu'il occupe, dans son canal le plus fort | Le terminal dessine son curseur par-dessus la cellule ; un curseur qui se fond est introuvable | | |
| 63 | +| Le curseur n'est jamais une simple inversion de cette ligne | Un terminal qui dessine son curseur en inversant la cellule le rendrait invisible | | |
| 64 | +| La ligne courante est à au moins 16 de la page | `turbo-dark` a un jour utilisé dix, ce qui n'est pas un surlignage | | |
| 65 | +| Le texte destiné à la lecture est à au moins 64 de son fond | Le mobilier — bureau, ombre, gouttière d'ascenseur, entrée grisée — en est exempt : il est fait pour s'effacer | | |
| 66 | +| Les commentaires se lisent à 4,5:1 ou mieux sur leur fond, en luminance relative WCAG | Un commentaire est de la prose, lue mot à mot. `turbo-classic` les dessinait en `#808080` sur son bleu marine : 128 valeurs de canal d'écart, donc la règle ci-dessus laissait passer, et 4,05:1 à la lecture, sous le plancher du W3C pour du texte courant. Les commentaires étaient la couleur la plus terne dans six des onze thèmes livrés. | | |
| 67 | + | |
| 68 | + | |
| 69 | +La règle de contraste s'applique aux six thèmes que ce projet écrit lui-même. Les deux thèmes Catppuccin en sont exemptés, et l'exemption est écrite là où elle est faite : leurs couleurs sont la palette publiée de quelqu'un d'autre, copiée fidèlement, et Catppuccin place les commentaires à 2,87:1 en Frappé et 2,83:1 en Latte. Un thème nommé Catppuccin qui n'aurait pas exactement ces valeurs serait un autre thème portant un nom d'emprunt : le correctif, si quelqu'un en veut un, est en amont. | |
| 70 | + | |
| 71 | +Elle s'applique aux commentaires et à rien d'autre. `syntax.punctuation` est plus discret encore dans plusieurs thèmes et le reste : la ponctuation se reconnaît à sa forme, elle ne se lit pas. | |
| 72 | + | |
| 73 | +Une sixième règle attrape l'erreur qu'aucune mesure ne voit : **deux classes syntaxiques que le lecteur rencontre côte à côte ne doivent pas être dessinées à l'identique**. `turbo-classic` a un jour peint `syntax.link` du même vert que `syntax.string` : un lien Markdown et un extrait de code inline devenaient la même chose à l'écran — chaque couleur lisible, chaque clé définie, et les deux simplement égales. Les deux monochromes satisfont cette règle sans aucune teinte, en jouant du gras, de l'italique et du souligné. | |
| 74 | + | |
| 75 | +## Variantes | |
| 76 | + | |
| 77 | +**Remplacer un thème livré plutôt que d'en ajouter un.** Donnez à votre fichier le même nom — `turbo-classic.toml` — et c'est le vôtre qui gagne. Le thème embarqué n'est pas remplacé : supprimer votre fichier le fait revenir. | |
| 78 | + | |
| 79 | +**Partir de zéro.** N'écrivez pas `inherits`. Définissez au moins `default` ; toute clé non définie retombe le long des points jusqu'à lui, si bien qu'un thème d'une seule ligne reste un thème utilisable. | |
| 80 | + | |
| 81 | +**Ne colorer que la syntaxe.** Une seule clé suffit : | |
| 82 | + | |
| 83 | +```toml | |
| 84 | +[colors] | |
| 85 | +syntax = { fg = "silver" } | |
| 86 | +``` | |
| 87 | + | |
| 88 | +`syntax.keyword`, `syntax.string` et les autres y retombent toutes. | |
| 89 | + | |
| 90 | +**Garder les couleurs du terminal.** Utilisez `default` comme valeur : | |
| 91 | + | |
| 92 | +```toml | |
| 93 | +[colors] | |
| 94 | +"editor.text" = { fg = "default", bg = "default" } | |
| 95 | +``` | |
| 96 | + | |
| 97 | +**L'essayer depuis un clone sans l'installer.** Pointez l'éditeur sur n'importe quel répertoire : | |
| 98 | + | |
| 99 | +```bash | |
| 100 | +TURBO_PYTHON_THEME_DIR=./mes-themes turbo-python -theme mine main.py | |
| 101 | +``` | |
| 102 | + | |
| 103 | +**Le curseur est peu visible.** `editor.cursor` fait deux choses : son **fond** est envoyé au terminal comme couleur de son propre curseur, et il peint aussi la cellule en dessous, en secours pour les terminaux qui ignorent la première. Mettez-la sur quelque chose de criard : | |
| 104 | + | |
| 105 | +```toml | |
| 106 | +[colors] | |
| 107 | +"editor.cursor" = { fg = "#000000", bg = "#ff8700" } | |
| 108 | +``` | |
| 109 | + | |
| 110 | +Deux choses font une mauvaise couleur de curseur, et la suite de tests les refuse toutes les deux : une simple inversion de la ligne — que les terminaux dessinant leur curseur par inversion ramènent à l'invisibilité — et tout écart de moins de 64 valeurs de canal avec la ligne sur laquelle il se trouve. | |
| 111 | + | |
| 112 | +**La ligne du curseur est difficile à repérer.** C'est `editor.currentline`, une autre clé. Elle doit s'écarter de `editor.text` d'au moins 16 valeurs de canal pour être un surlignage. | |
| 113 | + | |
| 114 | +**Le Markdown et le HTML rendent fade.** Cinq clés appartiennent aux langages de balisage et n'ont pas d'équivalent en Python : un thème écrit avant leur existence ne les définit pas. | |
| 115 | + | |
| 116 | +```toml | |
| 117 | +[colors] | |
| 118 | +"syntax.heading" = { fg = "white", bold = true } | |
| 119 | +"syntax.tag" = { fg = "aqua" } | |
| 120 | +"syntax.attribute" = { fg = "yellow" } | |
| 121 | +"syntax.emphasis" = { fg = "fuchsia", bold = true } | |
| 122 | +"syntax.link" = { fg = "aqua", underline = true } | |
| 123 | +``` | |
| 124 | + | |
| 125 | +Donnez à `syntax.link` une couleur différente de `syntax.string` : un lien et un `code` en ligne se côtoient dans presque toute prose, et partager une couleur en fait une bouillie. Le `turbo-classic` livré avait exactement ce défaut jusqu'à ce qu'on le regarde sur un vrai terminal. | |
| 126 | + | |
| 127 | +**L'arbre du projet est plat.** Il a quatre clés à lui, dont aucune ne se rabat sur `list` : | |
| 128 | + | |
| 129 | +```toml | |
| 130 | +[colors] | |
| 131 | +"tree.text" = { fg = "silver", bg = "navy" } | |
| 132 | +"tree.directory" = { fg = "white", bg = "navy", bold = true } | |
| 133 | +"tree.selected" = { fg = "black", bg = "aqua" } | |
| 134 | +"tree.unfocused" = { fg = "black", bg = "gray" } | |
| 135 | +``` | |
| 136 | + | |
| 137 | +Donnez à `tree.text` le même fond que `window.body`, pour que l'arbre fasse partie de sa fenêtre, et rendez `tree.selected` nettement différent — la suite de tests tient chaque thème livré à au moins 64 valeurs de canal entre les deux, parce qu'un surlignage de la couleur de la page n'est pas un surlignage. | |
| 138 | + | |
| 139 | +**Les fenêtres terminal rendent mal.** Elles ont deux clés à elles, et aucune ne se rabat sur `editor` : | |
| 140 | + | |
| 141 | +```toml | |
| 142 | +[colors] | |
| 143 | +"terminal.text" = { fg = "silver", bg = "black" } | |
| 144 | +"terminal.cursor" = { fg = "black", bg = "aqua" } | |
| 145 | +``` | |
| 146 | + | |
| 147 | +`terminal.text` est ce que reçoit la sortie d'un shell lorsqu'elle ne nomme aucune couleur — donnez-lui quelque chose de proche d'un vrai terminal plutôt que du fond de votre éditeur, sans quoi `less` et `htop` détonneront. Un programme qui nomme ses couleurs les conserve dans les deux cas. | |
| 148 | + | |
| 149 | +## Voir aussi | |
| 150 | + | |
| 151 | +- Toutes les clés définissables et tous les noms de couleurs : [référence du format de thème](../reference/themes.md) | |
| 152 | +- Pourquoi du TOML avec deux formes d'héritage : [Décisions de conception](../explanation/design-decisions.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,152 @@ | |||
| 1 | +# Écrire son propre thème | ||
| 2 | + | ||
| 3 | +Ce guide montre comment ajouter un thème de couleurs à vous. Il suppose que vous savez où se trouve votre répertoire de configuration et que vous savez éditer un fichier TOML. | ||
| 4 | + | ||
| 5 | +## 1. Trouver où vont les thèmes | ||
| 6 | + | ||
| 7 | +```bash | ||
| 8 | +turbo-python -list-themes | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +La dernière ligne indique le répertoire — `~/.config/turbo-python/themes` sous Linux, `~/Library/Application Support/turbo-python/themes` sous macOS. Créez-le : | ||
| 12 | + | ||
| 13 | +```bash | ||
| 14 | +mkdir -p ~/.config/turbo-python/themes | ||
| 15 | +``` | ||
| 16 | + | ||
| 17 | +## 2. Partir d'un thème existant | ||
| 18 | + | ||
| 19 | +Le plus rapide est d'hériter d'un thème qui fonctionne déjà et de ne redéfinir que ce que vous voulez : | ||
| 20 | + | ||
| 21 | +```toml | ||
| 22 | +# ~/.config/turbo-python/themes/mine.toml | ||
| 23 | +name = "Le mien" | ||
| 24 | +description = "Turbo Classic, mais avec des commentaires lisibles." | ||
| 25 | +inherits = "turbo-classic" | ||
| 26 | + | ||
| 27 | +[colors] | ||
| 28 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | ||
| 29 | +"syntax.string" = { fg = "#87d7af" } | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +Tout ce que vous ne définissez pas est repris de `turbo-classic`. | ||
| 33 | + | ||
| 34 | +**Héritez d'un thème dont le fond ressemble au vôtre.** Les couleurs que vous omettez ont été choisies contre le fond du thème dont vous héritez : un thème sombre bâti sur `turbo-classic` affichera, ici et là, une couleur pensée pour le marine Borland. Pour un thème sombre, héritez de `turbo-dark`, `cappuccino`, `catppuccin-frappe`, `cobalt`, `darcula` ou `monochrome-dark` ; pour un thème clair, de `borland-light`, `catppuccin-latte`, `intellij-light` ou `monochrome-light`. C'est aussi pourquoi les onze thèmes livrés dans le binaire énoncent chacun leur palette en entier au lieu d'en hériter l'essentiel — un test les y oblige, parce qu'un thème livré engage le projet. | ||
| 35 | + | ||
| 36 | +## 3. L'utiliser | ||
| 37 | + | ||
| 38 | +```bash | ||
| 39 | +turbo-python -theme mine main.py | ||
| 40 | +``` | ||
| 41 | + | ||
| 42 | +Ou depuis l'éditeur : `Options ▸ Theme…`, qui liste tous les thèmes trouvés. | ||
| 43 | + | ||
| 44 | +## 4. Itérer | ||
| 45 | + | ||
| 46 | +Modifiez le fichier, puis relancez l'éditeur. Il n'y a pas de rechargement à chaud. | ||
| 47 | + | ||
| 48 | +Si le thème ne se charge pas, Turbo Python retombe sur le thème par défaut plutôt que de refuser de démarrer. Pour savoir *pourquoi* : | ||
| 49 | + | ||
| 50 | +```bash | ||
| 51 | +turbo-python -list-themes | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +Un thème cassé apparaît dans la liste avec l'erreur d'analyse à côté — un nom de couleur inconnu est une erreur, pas un repli silencieux : une faute de frappe est signalée au lieu de repeindre discrètement la moitié de l'écran. | ||
| 55 | + | ||
| 56 | +## 5. Vérifier qu'il reste lisible | ||
| 57 | + | ||
| 58 | +Le projet soumet chaque thème qu'il livre à cinq règles mesurées, et elles valent pour le vôtre. `make test` les exécute. | ||
| 59 | + | ||
| 60 | +| Règle | Pourquoi | | ||
| 61 | +| --- | --- | | ||
| 62 | +| Le curseur est à au moins 64 de la ligne qu'il occupe, dans son canal le plus fort | Le terminal dessine son curseur par-dessus la cellule ; un curseur qui se fond est introuvable | | ||
| 63 | +| Le curseur n'est jamais une simple inversion de cette ligne | Un terminal qui dessine son curseur en inversant la cellule le rendrait invisible | | ||
| 64 | +| La ligne courante est à au moins 16 de la page | `turbo-dark` a un jour utilisé dix, ce qui n'est pas un surlignage | | ||
| 65 | +| Le texte destiné à la lecture est à au moins 64 de son fond | Le mobilier — bureau, ombre, gouttière d'ascenseur, entrée grisée — en est exempt : il est fait pour s'effacer | | ||
| 66 | +| Les commentaires se lisent à 4,5:1 ou mieux sur leur fond, en luminance relative WCAG | Un commentaire est de la prose, lue mot à mot. `turbo-classic` les dessinait en `#808080` sur son bleu marine : 128 valeurs de canal d'écart, donc la règle ci-dessus laissait passer, et 4,05:1 à la lecture, sous le plancher du W3C pour du texte courant. Les commentaires étaient la couleur la plus terne dans six des onze thèmes livrés. | | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +La règle de contraste s'applique aux six thèmes que ce projet écrit lui-même. Les deux thèmes Catppuccin en sont exemptés, et l'exemption est écrite là où elle est faite : leurs couleurs sont la palette publiée de quelqu'un d'autre, copiée fidèlement, et Catppuccin place les commentaires à 2,87:1 en Frappé et 2,83:1 en Latte. Un thème nommé Catppuccin qui n'aurait pas exactement ces valeurs serait un autre thème portant un nom d'emprunt : le correctif, si quelqu'un en veut un, est en amont. | ||
| 70 | + | ||
| 71 | +Elle s'applique aux commentaires et à rien d'autre. `syntax.punctuation` est plus discret encore dans plusieurs thèmes et le reste : la ponctuation se reconnaît à sa forme, elle ne se lit pas. | ||
| 72 | + | ||
| 73 | +Une sixième règle attrape l'erreur qu'aucune mesure ne voit : **deux classes syntaxiques que le lecteur rencontre côte à côte ne doivent pas être dessinées à l'identique**. `turbo-classic` a un jour peint `syntax.link` du même vert que `syntax.string` : un lien Markdown et un extrait de code inline devenaient la même chose à l'écran — chaque couleur lisible, chaque clé définie, et les deux simplement égales. Les deux monochromes satisfont cette règle sans aucune teinte, en jouant du gras, de l'italique et du souligné. | ||
| 74 | + | ||
| 75 | +## Variantes | ||
| 76 | + | ||
| 77 | +**Remplacer un thème livré plutôt que d'en ajouter un.** Donnez à votre fichier le même nom — `turbo-classic.toml` — et c'est le vôtre qui gagne. Le thème embarqué n'est pas remplacé : supprimer votre fichier le fait revenir. | ||
| 78 | + | ||
| 79 | +**Partir de zéro.** N'écrivez pas `inherits`. Définissez au moins `default` ; toute clé non définie retombe le long des points jusqu'à lui, si bien qu'un thème d'une seule ligne reste un thème utilisable. | ||
| 80 | + | ||
| 81 | +**Ne colorer que la syntaxe.** Une seule clé suffit : | ||
| 82 | + | ||
| 83 | +```toml | ||
| 84 | +[colors] | ||
| 85 | +syntax = { fg = "silver" } | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +`syntax.keyword`, `syntax.string` et les autres y retombent toutes. | ||
| 89 | + | ||
| 90 | +**Garder les couleurs du terminal.** Utilisez `default` comme valeur : | ||
| 91 | + | ||
| 92 | +```toml | ||
| 93 | +[colors] | ||
| 94 | +"editor.text" = { fg = "default", bg = "default" } | ||
| 95 | +``` | ||
| 96 | + | ||
| 97 | +**L'essayer depuis un clone sans l'installer.** Pointez l'éditeur sur n'importe quel répertoire : | ||
| 98 | + | ||
| 99 | +```bash | ||
| 100 | +TURBO_PYTHON_THEME_DIR=./mes-themes turbo-python -theme mine main.py | ||
| 101 | +``` | ||
| 102 | + | ||
| 103 | +**Le curseur est peu visible.** `editor.cursor` fait deux choses : son **fond** est envoyé au terminal comme couleur de son propre curseur, et il peint aussi la cellule en dessous, en secours pour les terminaux qui ignorent la première. Mettez-la sur quelque chose de criard : | ||
| 104 | + | ||
| 105 | +```toml | ||
| 106 | +[colors] | ||
| 107 | +"editor.cursor" = { fg = "#000000", bg = "#ff8700" } | ||
| 108 | +``` | ||
| 109 | + | ||
| 110 | +Deux choses font une mauvaise couleur de curseur, et la suite de tests les refuse toutes les deux : une simple inversion de la ligne — que les terminaux dessinant leur curseur par inversion ramènent à l'invisibilité — et tout écart de moins de 64 valeurs de canal avec la ligne sur laquelle il se trouve. | ||
| 111 | + | ||
| 112 | +**La ligne du curseur est difficile à repérer.** C'est `editor.currentline`, une autre clé. Elle doit s'écarter de `editor.text` d'au moins 16 valeurs de canal pour être un surlignage. | ||
| 113 | + | ||
| 114 | +**Le Markdown et le HTML rendent fade.** Cinq clés appartiennent aux langages de balisage et n'ont pas d'équivalent en Python : un thème écrit avant leur existence ne les définit pas. | ||
| 115 | + | ||
| 116 | +```toml | ||
| 117 | +[colors] | ||
| 118 | +"syntax.heading" = { fg = "white", bold = true } | ||
| 119 | +"syntax.tag" = { fg = "aqua" } | ||
| 120 | +"syntax.attribute" = { fg = "yellow" } | ||
| 121 | +"syntax.emphasis" = { fg = "fuchsia", bold = true } | ||
| 122 | +"syntax.link" = { fg = "aqua", underline = true } | ||
| 123 | +``` | ||
| 124 | + | ||
| 125 | +Donnez à `syntax.link` une couleur différente de `syntax.string` : un lien et un `code` en ligne se côtoient dans presque toute prose, et partager une couleur en fait une bouillie. Le `turbo-classic` livré avait exactement ce défaut jusqu'à ce qu'on le regarde sur un vrai terminal. | ||
| 126 | + | ||
| 127 | +**L'arbre du projet est plat.** Il a quatre clés à lui, dont aucune ne se rabat sur `list` : | ||
| 128 | + | ||
| 129 | +```toml | ||
| 130 | +[colors] | ||
| 131 | +"tree.text" = { fg = "silver", bg = "navy" } | ||
| 132 | +"tree.directory" = { fg = "white", bg = "navy", bold = true } | ||
| 133 | +"tree.selected" = { fg = "black", bg = "aqua" } | ||
| 134 | +"tree.unfocused" = { fg = "black", bg = "gray" } | ||
| 135 | +``` | ||
| 136 | + | ||
| 137 | +Donnez à `tree.text` le même fond que `window.body`, pour que l'arbre fasse partie de sa fenêtre, et rendez `tree.selected` nettement différent — la suite de tests tient chaque thème livré à au moins 64 valeurs de canal entre les deux, parce qu'un surlignage de la couleur de la page n'est pas un surlignage. | ||
| 138 | + | ||
| 139 | +**Les fenêtres terminal rendent mal.** Elles ont deux clés à elles, et aucune ne se rabat sur `editor` : | ||
| 140 | + | ||
| 141 | +```toml | ||
| 142 | +[colors] | ||
| 143 | +"terminal.text" = { fg = "silver", bg = "black" } | ||
| 144 | +"terminal.cursor" = { fg = "black", bg = "aqua" } | ||
| 145 | +``` | ||
| 146 | + | ||
| 147 | +`terminal.text` est ce que reçoit la sortie d'un shell lorsqu'elle ne nomme aucune couleur — donnez-lui quelque chose de proche d'un vrai terminal plutôt que du fond de votre éditeur, sans quoi `less` et `htop` détonneront. Un programme qui nomme ses couleurs les conserve dans les deux cas. | ||
| 148 | + | ||
| 149 | +## Voir aussi | ||
| 150 | + | ||
| 151 | +- Toutes les clés définissables et tous les noms de couleurs : [référence du format de thème](../reference/themes.md) | ||
| 152 | +- Pourquoi du TOML avec deux formes d'héritage : [Décisions de conception](../explanation/design-decisions.md) | ||
added
docs/fr/reference/acp.md +239 -0 | new file mode 100644 | ||
| @@ -0,0 +1,239 @@ | ||
| 1 | +# Agents et ACP | |
| 2 | + | |
| 3 | +Turbo Python est un client de l'[Agent Client Protocol](https://agentclientprotocol.com). Il lance chaque agent comme processus fils et échange avec lui des messages JSON-RPC 2.0 sur son entrée et sa sortie standard, à raison d'un message par ligne. | |
| 4 | + | |
| 5 | +## Où se trouve le fichier | |
| 6 | + | |
| 7 | +| Chemin | Lu | Rôle | | |
| 8 | +| --- | --- | --- | | |
| 9 | +| `~/.config/turbo-python/acp.toml` | en premier | Les agents que vous voulez dans tous les projets | | |
| 10 | +| `<projet>/.turbo-python/acp.toml` | en second | Les agents propres à ce projet | | |
| 11 | + | |
| 12 | +Les deux sont facultatifs. Quand un `name` d'agent apparaît dans les deux, celui du projet remplace celui de l'utilisateur, étant l'énoncé le plus spécifique — la règle que suivent déjà les [snippets](snippets.md). Un fichier absent n'est pas une erreur ; un fichier présent mais illisible en est une, signalée sous **Agent ▸ Agent status** plutôt que de laisser silencieusement le menu vide. | |
| 13 | + | |
| 14 | +`TURBO_PYTHON_DIR` remplace le dossier où le fichier utilisateur est cherché. Le fichier du projet est toujours `.turbo-python/acp.toml` sous le dossier depuis lequel l'éditeur a été lancé — il n'y a pas de remontée dans l'arborescence, pour la même raison que les [réglages de projet](project-settings.md) ne remontent pas. | |
| 15 | + | |
| 16 | +## Format du fichier | |
| 17 | + | |
| 18 | +Un bloc `[[agent]]` par agent, dans l'ordre souhaité dans le menu. | |
| 19 | + | |
| 20 | +```toml | |
| 21 | +[[agent]] | |
| 22 | +name = "Bob (llama.cpp)" | |
| 23 | +command = "docker" | |
| 24 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | |
| 25 | +env = { TELEMETRY_ENABLED = "false" } | |
| 26 | +cwd = "." | |
| 27 | +``` | |
| 28 | + | |
| 29 | +| Clé | Type | Requise | Signification | | |
| 30 | +| --- | --- | --- | --- | | |
| 31 | +| `name` | chaîne | **oui** | Ce qu'affiche le menu Agent et le titre de la fenêtre. Doit être unique dans l'ensemble fusionné. | | |
| 32 | +| `command` | chaîne | **oui** | L'exécutable à lancer. Cherché dans `PATH` sauf s'il contient un séparateur. | | |
| 33 | +| `args` | liste de chaînes | non | Ses arguments, passés tels quels — pas de shell, donc ni guillemets, ni jokers, ni `&&`. | | |
| 34 | +| `env` | table de chaînes | non | Variables d'environnement ajoutées à celles de l'éditeur. Un nom donné ici l'emporte. | | |
| 35 | +| `cwd` | chaîne | non | Où le processus démarre, et le `cwd` annoncé à l'agent. Relatif à la racine du projet. Par défaut, la racine du projet. | | |
| 36 | + | |
| 37 | +`env` peut aussi s'écrire en sous-table, ce qui est la même chose : | |
| 38 | + | |
| 39 | +```toml | |
| 40 | +[[agent]] | |
| 41 | +name = "Bob (llama.cpp)" | |
| 42 | +command = "docker" | |
| 43 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | |
| 44 | + | |
| 45 | +[agent.env] | |
| 46 | +TELEMETRY_ENABLED = "false" | |
| 47 | +``` | |
| 48 | + | |
| 49 | +### Ce qui est refusé | |
| 50 | + | |
| 51 | +Le fichier est refusé dans son ensemble, plutôt que chargé à moitié, dès que l'un de ces cas se présente. Un menu à moitié chargé proposant trois de vos cinq agents est pire qu'une erreur qui dit pourquoi. | |
| 52 | + | |
| 53 | +| Problème | Message | | |
| 54 | +| --- | --- | | |
| 55 | +| un agent sans `name` | `reading …/acp.toml: agent 1 has no name` | | |
| 56 | +| un agent sans `command` | `reading …/acp.toml: agent "Bob" has no command` | | |
| 57 | +| deux agents portant le même `name` | `reading …/acp.toml: two agents are called "Bob"` | | |
| 58 | +| une clé que le format ne définit pas | `reading …/acp.toml: agent.comand is not a key this file has` | | |
| 59 | + | |
| 60 | +Le dernier cas est voulu : une clé mal orthographiée silencieusement ignorée ressemblerait exactement à une clé sans effet. | |
| 61 | + | |
| 62 | +## Le menu Agent | |
| 63 | + | |
| 64 | +`Alt-A` l'ouvre. Il est sur la barre qu'un agent soit configuré ou non, parce que c'est de là que **Create agents file** doit être atteignable. | |
| 65 | + | |
| 66 | +| Entrée | Active quand | Effet | | |
| 67 | +| --- | --- | --- | | |
| 68 | +| *une entrée par agent, par son nom* | toujours | Démarrer cet agent et ouvrir une fenêtre dessus | | |
| 69 | +| **Create agents file** | pas d'`acp.toml` dans le projet | Écrire le fichier de départ et l'ouvrir | | |
| 70 | +| **Cancel turn** | un tour est en cours dans la fenêtre de devant | `session/cancel` | | |
| 71 | +| **Agent status** | toujours | Ce qui a été chargé, la ligne de commande de chacun, et ce qui a échoué | | |
| 72 | + | |
| 73 | +## Touches dans une fenêtre agent | |
| 74 | + | |
| 75 | +Une fenêtre agent est une fenêtre ordinaire : `F6`, `Alt-1`…`Alt-9`, Tile, Maximise, `[x]` et `[■]` y fonctionnent tous. À l'intérieur : | |
| 76 | + | |
| 77 | +| Touche | Effet | | |
| 78 | +| --- | --- | | |
| 79 | +| `Entrée` | Envoyer la zone de saisie comme invite | | |
| 80 | +| `Alt-Entrée` | Insérer un saut de ligne dans la zone de saisie | | |
| 81 | +| `Tab` | Déplacer le focus entre la conversation et la zone de saisie | | |
| 82 | +| `Ctrl-C`, `Ctrl-Ins` | Copier la sélection, ou le bloc sur lequel est le curseur | | |
| 83 | +| `Échap` | Abandonner la sélection ; s'il n'y en a pas, annuler le tour en cours | | |
| 84 | +| `Ctrl-W` | Fermer la fenêtre et arrêter l'agent | | |
| 85 | + | |
| 86 | +Avec la **zone de saisie** au premier plan : | |
| 87 | + | |
| 88 | +| Touche | Effet | | |
| 89 | +| --- | --- | | |
| 90 | +| `↑` `↓` `←` `→` `Début` `Fin` | Déplacer le curseur dans ce que vous tapez | | |
| 91 | +| `Retour arrière` `Suppr` | L'éditer ; le retour arrière en début de ligne la joint à celle du dessus | | |
| 92 | +| `/` en premier caractère | Ouvrir la liste des commandes de l'agent — voir [Commandes et mentions](#commandes-et-mentions) | | |
| 93 | +| `@` | Ouvrir la liste des fichiers du projet, réduite par ce que vous tapez ensuite | | |
| 94 | +| `↑` `↓` `PgUp` `PgDn`, liste ouverte | Se déplacer dans la liste | | |
| 95 | +| `Tab`, liste ouverte | Prendre l'entrée en surbrillance | | |
| 96 | +| `Entrée`, liste ouverte | Prendre l'entrée en surbrillance ; sur un mot déjà complet, envoyer | | |
| 97 | +| `Échap`, liste ouverte | Fermer la liste jusqu'à ce que le texte change | | |
| 98 | + | |
| 99 | +Avec la **conversation** au premier plan : | |
| 100 | + | |
| 101 | +| Touche | Effet | | |
| 102 | +| --- | --- | | |
| 103 | +| `↑` `↓` | Déplacer le curseur d'une ligne | | |
| 104 | +| `PgUp` `PgDn` | Le déplacer d'un écran | | |
| 105 | +| `Début` `Fin` | Le début de la conversation, et la fin | | |
| 106 | +| `Shift-` l'une d'elles | Étendre la sélection à la place | | |
| 107 | +| Glisser avec le bouton 1 | Sélectionner à la main | | |
| 108 | +| Molette | Défiler de trois lignes sans bouger le curseur | | |
| 109 | + | |
| 110 | +Contrairement à une fenêtre terminal, une fenêtre agent ne **prend pas** les raccourcis de l'éditeur : il n'y a pas de shell qui ait besoin de `Ctrl-F`, donc cette touche garde son sens habituel. `Ctrl-C` fait exception, et seulement parce que rien d'autre n'en veut dans une fenêtre agent. | |
| 111 | + | |
| 112 | +## Commandes et mentions | |
| 113 | + | |
| 114 | +Deux caractères ouvrent une liste par-dessus le bas de la conversation pendant que vous tapez. Ce sont les deux mêmes que Zed, si bien que la documentation d'un agent — « tapez `/web` pour chercher » — reste vraie ici. | |
| 115 | + | |
| 116 | +### `/` — les commandes de l'agent | |
| 117 | + | |
| 118 | +Un agent peut annoncer des commandes par `available_commands_update`, au début de la session ou à tout moment pendant celle-ci. Taper `/` comme **premier caractère** de la zone de saisie les liste : le nom, la description donnée par l'agent et, entre chevrons, ce qu'il attend après le nom quand il attend quelque chose. Continuez à taper pour réduire la liste ; la correspondance porte sur le début du nom et ignore la casse. | |
| 119 | + | |
| 120 | +`Tab` complète la commande en surbrillance. Une commande qui prend une entrée est complétée avec une espace à la fin, pour que la suite de votre frappe soit son argument ; une qui n'en prend pas est complétée au nom seul. `Entrée` complète aussi, sauf sur un mot qui se lit déjà exactement comme une commande, où elle envoie. | |
| 121 | + | |
| 122 | +Sur le fil, une commande est du **texte** : `/web agent client protocol` part comme un seul bloc texte, et l'agent la reconnaît à son premier mot. C'est tout le protocole des commandes, et c'est pourquoi un `/` ailleurs qu'au début de la zone n'est qu'un caractère. | |
| 123 | + | |
| 124 | +Sans commande annoncée, `/` est un caractère et `Tab` garde son sens habituel. **Agent ▸ Agent status** liste les commandes avec leur description. | |
| 125 | + | |
| 126 | +### `@` — un fichier du projet | |
| 127 | + | |
| 128 | +Taper `@` n'importe où dans la zone liste les fichiers du projet, relatifs à sa racine, avec des barres obliques. Ce que vous tapez après le `@` réduit la liste : les fichiers dont le nom propre commence par cela viennent d'abord, puis ceux dont le chemin le contient seulement. `Tab` ou `Entrée` complète celui en surbrillance et ajoute une espace. | |
| 129 | + | |
| 130 | +À l'envoi de l'invite, chaque `@nom` qui désigne un fichier connu de la liste devient un bloc de contenu **à la place du nom** : | |
| 131 | + | |
| 132 | +| L'agent a déclaré | Le bloc envoyé | | |
| 133 | +| --- | --- | | |
| 134 | +| `promptCapabilities.embeddedContext: true` | `resource` — l'`uri` du fichier, son `mimeType` et son `text` entier, lu comme `fs/read_text_file` le lit : depuis le tampon ouvert quand le fichier est ouvert et modifié | | |
| 135 | +| autre chose, ou le fichier n'a pas pu être lu | `resource_link` — l'`uri`, le `name` et le `mimeType`, pour que l'agent aille le chercher lui-même | | |
| 136 | + | |
| 137 | +Les mots de part et d'autre partent en blocs texte, si bien que `explique @docs/README.md s'il te plaît` fait trois blocs : `explique `, le fichier, ` s'il te plaît`. La conversation garde la ligne telle que vous l'avez tapée. | |
| 138 | + | |
| 139 | +Un mot qui commence par `@` et ne désigne aucun fichier reste du texte — une adresse électronique dans une invite n'est pas un fichier — et `@main.go` ne désigne pas `main.gopher` : le nom doit terminer le mot. | |
| 140 | + | |
| 141 | +La liste est le projet parcouru depuis sa racine, `.git` exclu, au plus 5 000 fichiers, et au plus 200 d'entre eux affichés à la fois. Au-delà de l'une ou l'autre limite, tapez une lettre de plus. Le parcours est refait à chaque ouverture de la liste par `@`, si bien qu'un fichier que l'agent vient de créer y figure. | |
| 142 | + | |
| 143 | +## La copie | |
| 144 | + | |
| 145 | +La sélection porte sur des **lignes entières**. Rien ne s'édite dans une conversation, donc une demi-ligne n'est jamais ce qu'on veut dire, et des lignes entières préservent l'indentation d'un bloc de code copié. | |
| 146 | + | |
| 147 | +Sans rien de sélectionné, la copie prend la **région sur laquelle est le curseur** : un bloc de code délimité, un passage de prose, la sortie d'un appel d'outil. Le libellé d'un interlocuteur et l'en-tête d'un appel d'outil sont du mobilier et forment des régions à part : ni l'un ni l'autre n'est jamais copié avec ce qu'il surmonte. | |
| 148 | + | |
| 149 | +L'indentation d'affichage de la conversation est retirée, donc le code collé arrive collé à la marge. | |
| 150 | + | |
| 151 | +Le texte part à deux endroits à la fois : | |
| 152 | + | |
| 153 | +| Presse-papiers | Comment | Collé avec | | |
| 154 | +| --- | --- | --- | | |
| 155 | +| Celui de l'éditeur | directement | `Shift-Ins`, dans un fichier ouvert ici | | |
| 156 | +| Celui du système | OSC 52, à travers le terminal | `Ctrl-V`, n'importe où ailleurs | | |
| 157 | + | |
| 158 | +Rien ne vérifie que le terminal a accepté le second : il n'y a pas de réponse à vérifier, et un terminal peut refuser OSC 52 par sécurité ou demander qu'on l'active. Le presse-papiers de l'éditeur contient le texte dans tous les cas, et la barre d'état dit combien de lignes ont été copiées. | |
| 159 | + | |
| 160 | +## Quelle part du protocole est implémentée | |
| 161 | + | |
| 162 | +Version de protocole **1**. Turbo Python annonce sa version dans `initialize` et accepte la version que l'agent répond, pourvu qu'il la connaisse. | |
| 163 | + | |
| 164 | +### Ce que l'éditeur appelle sur l'agent | |
| 165 | + | |
| 166 | +| Méthode | Implémentée | Remarques | | |
| 167 | +| --- | --- | --- | | |
| 168 | +| `initialize` | oui | Annonce la capacité `fs` ci-dessous ; `terminal` n'est pas annoncée | | |
| 169 | +| `session/new` | oui | `cwd` vient de la clé `cwd` de l'agent ; `mcpServers` est toujours vide — les serveurs MCP sont l'affaire de l'agent | | |
| 170 | +| `session/prompt` | oui | Des blocs texte, et un bloc `resource` ou `resource_link` par fichier désigné par `@` — voir [Commandes et mentions](#commandes-et-mentions) | | |
| 171 | +| `session/cancel` | oui | `Échap`, et **Agent ▸ Cancel turn** | | |
| 172 | +| `session/load` | **non** | Les conversations ne survivent pas à la fermeture de la fenêtre | | |
| 173 | +| `authenticate` | **non** | Un agent qui liste des `authMethods` est signalé comme exigeant une connexion que l'éditeur ne sait pas faire | | |
| 174 | + | |
| 175 | +### Ce que l'agent peut appeler sur l'éditeur | |
| 176 | + | |
| 177 | +| Méthode | Implémentée | Remarques | | |
| 178 | +| --- | --- | --- | | |
| 179 | +| `session/update` | oui | Voir la table ci-dessous | | |
| 180 | +| `session/request_permission` | oui | Une boîte modale portant les options de l'agent lui-même | | |
| 181 | +| `fs/read_text_file` | oui | Depuis le tampon quand le fichier est ouvert et modifié, sinon depuis le disque | | |
| 182 | +| `fs/write_text_file` | oui | Dans le tampon quand le fichier est ouvert, sinon sur le disque | | |
| 183 | +| `terminal/*` | **non** | Non annoncée, donc un agent conforme ne la demandera pas | | |
| 184 | + | |
| 185 | +### Mises à jour de session | |
| 186 | + | |
| 187 | +| `sessionUpdate` | Affiché comme | | |
| 188 | +| --- | --- | | |
| 189 | +| `agent_message_chunk` | La réponse de l'agent, ajoutée au fil de son arrivée | | |
| 190 | +| `agent_thought_chunk` | La même chose, dans la couleur des commentaires, sous une étiquette *réflexion* | | |
| 191 | +| `user_message_chunk` | Votre propre message, tel que l'agent le renvoie | | |
| 192 | +| `tool_call` | Une ligne nommant l'outil et son titre, avec son état | | |
| 193 | +| `tool_call_update` | Repliée sur la ligne dont le `toolCallId` correspond, avec sa sortie | | |
| 194 | +| `plan` | Les entrées en liste, chacune avec son état | | |
| 195 | +| `available_commands_update` | La liste que `/` ouvre dans la zone de saisie ; aussi listée, avec les descriptions, par **Agent ▸ Agent status** | | |
| 196 | +| `usage_update` | Le compte de jetons dans la barre d'état quand la fenêtre est devant | | |
| 197 | +| tout le reste | Ignoré, et compté ; le compte figure dans **Agent status** | | |
| 198 | + | |
| 199 | +Pendant qu'un tour est en cours, la règle entre les deux zones fait tourner un indicateur. Il est dessiné à partir de l'horloge et non d'un compteur, donc deux fenêtres qui réfléchissent en même temps tournent en phase et rien n'a besoin d'être remis à zéro au début d'un tour. Le *titre* de la fenêtre, lui, n'est délibérément pas animé : c'est aussi ce qu'affichent la liste des fenêtres et le menu `Alt`-chiffre, et un nom qui change huit fois par seconde les fait scintiller tous les deux. | |
| 200 | + | |
| 201 | +Une mise à jour inconnue est ignorée plutôt que refusée : le protocole grandit, et un éditeur qui cesserait de parler à un agent parce que celui-ci a appris un nouveau type de message aurait tort plus souvent que raison. | |
| 202 | + | |
| 203 | +## Coloration | |
| 204 | + | |
| 205 | +La conversation est dessinée avec des clés que tous les thèmes définissent déjà, donc aucun n'a eu besoin d'être touché : | |
| 206 | + | |
| 207 | +| Élément | Classe | | |
| 208 | +| --- | --- | | |
| 209 | +| Le nom d'un interlocuteur | `syntax.keyword` | | |
| 210 | +| Une réflexion | `syntax.comment` | | |
| 211 | +| Un appel d'outil et son état | `syntax.type` | | |
| 212 | +| Un appel d'outil en échec, et les avis de l'éditeur | `diagnostic.error` | | |
| 213 | +| Une ligne sélectionnée, et la barre du curseur | `editor.selection` | | |
| 214 | +| Le code dans un bloc délimité | l'analyseur du langage annoncé | | |
| 215 | +| Tout le reste | le texte ordinaire de la fenêtre | | |
| 216 | + | |
| 217 | +Un bloc délimité annonçant un langage que l'éditeur colore — `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash` — est coloré par cet analyseur. Un bloc annonçant autre chose, ou rien, est laissé brut. | |
| 218 | + | |
| 219 | +## Tracer la conversation avec un agent | |
| 220 | + | |
| 221 | +| Variable | Effet | | |
| 222 | +| --- | --- | | |
| 223 | +| `TURBO_ACP_TRACE=<fichier>` | Ajouter à ce fichier chaque message vers et depuis chaque agent, un par ligne, horodaté et marqué `->` (envoyé) ou `<-` (reçu) | | |
| 224 | + | |
| 225 | +C'est pour la seule question à laquelle l'écran ne peut pas répondre — *qu'a réellement envoyé l'agent ?* Une mise à jour que cet éditeur ne sait pas décoder est comptée dans **Agent ▸ Agent status**, qui nomme aussi la dernière et son erreur ; la trace montre le message lui-même. Un fichier qui ne peut pas être ouvert veut dire pas de trace, et rien d'autre : la trace n'a jamais le droit de casser l'éditeur. | |
| 226 | + | |
| 227 | +## Limites | |
| 228 | + | |
| 229 | +- **Une session par fenêtre.** Fermer la fenêtre termine la session ; il n'y a pas de reprise. | |
| 230 | +- **Texte et fichiers seulement.** L'éditeur envoie du texte, et les fichiers que vous désignez par `@` ; ni images ni audio, quoi que disent les `promptCapabilities` de l'agent. | |
| 231 | +- **Pas d'authentification.** Un agent exigeant une connexion doit être connecté par sa propre CLI avant que l'éditeur ne le lance. | |
| 232 | +- **`args` n'est pas une commande shell.** `command = "sh"`, `args = ["-c", "…"]` est la façon délibérée d'en obtenir une. | |
| 233 | +- **Une entrée est plafonnée** à un mégaoctet de texte. Un agent qui déverse tout un journal de compilation ne peut pas rendre la fenêtre inutilisable ; ce qui a été perdu est signalé dans l'entrée elle-même. | |
| 234 | + | |
| 235 | +## Voir aussi | |
| 236 | + | |
| 237 | +- La tâche : [Dialoguer avec un agent de code depuis l'éditeur](../how-to/talk-to-an-agent.md) | |
| 238 | +- Le raisonnement : [Fenêtres agent](../explanation/agent-windows.md) | |
| 239 | +- Le protocole : [agentclientprotocol.com](https://agentclientprotocol.com) | |
| new file mode 100644 | |||
| @@ -0,0 +1,239 @@ | |||
| 1 | +# Agents et ACP | ||
| 2 | + | ||
| 3 | +Turbo Python est un client de l'[Agent Client Protocol](https://agentclientprotocol.com). Il lance chaque agent comme processus fils et échange avec lui des messages JSON-RPC 2.0 sur son entrée et sa sortie standard, à raison d'un message par ligne. | ||
| 4 | + | ||
| 5 | +## Où se trouve le fichier | ||
| 6 | + | ||
| 7 | +| Chemin | Lu | Rôle | | ||
| 8 | +| --- | --- | --- | | ||
| 9 | +| `~/.config/turbo-python/acp.toml` | en premier | Les agents que vous voulez dans tous les projets | | ||
| 10 | +| `<projet>/.turbo-python/acp.toml` | en second | Les agents propres à ce projet | | ||
| 11 | + | ||
| 12 | +Les deux sont facultatifs. Quand un `name` d'agent apparaît dans les deux, celui du projet remplace celui de l'utilisateur, étant l'énoncé le plus spécifique — la règle que suivent déjà les [snippets](snippets.md). Un fichier absent n'est pas une erreur ; un fichier présent mais illisible en est une, signalée sous **Agent ▸ Agent status** plutôt que de laisser silencieusement le menu vide. | ||
| 13 | + | ||
| 14 | +`TURBO_PYTHON_DIR` remplace le dossier où le fichier utilisateur est cherché. Le fichier du projet est toujours `.turbo-python/acp.toml` sous le dossier depuis lequel l'éditeur a été lancé — il n'y a pas de remontée dans l'arborescence, pour la même raison que les [réglages de projet](project-settings.md) ne remontent pas. | ||
| 15 | + | ||
| 16 | +## Format du fichier | ||
| 17 | + | ||
| 18 | +Un bloc `[[agent]]` par agent, dans l'ordre souhaité dans le menu. | ||
| 19 | + | ||
| 20 | +```toml | ||
| 21 | +[[agent]] | ||
| 22 | +name = "Bob (llama.cpp)" | ||
| 23 | +command = "docker" | ||
| 24 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | ||
| 25 | +env = { TELEMETRY_ENABLED = "false" } | ||
| 26 | +cwd = "." | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +| Clé | Type | Requise | Signification | | ||
| 30 | +| --- | --- | --- | --- | | ||
| 31 | +| `name` | chaîne | **oui** | Ce qu'affiche le menu Agent et le titre de la fenêtre. Doit être unique dans l'ensemble fusionné. | | ||
| 32 | +| `command` | chaîne | **oui** | L'exécutable à lancer. Cherché dans `PATH` sauf s'il contient un séparateur. | | ||
| 33 | +| `args` | liste de chaînes | non | Ses arguments, passés tels quels — pas de shell, donc ni guillemets, ni jokers, ni `&&`. | | ||
| 34 | +| `env` | table de chaînes | non | Variables d'environnement ajoutées à celles de l'éditeur. Un nom donné ici l'emporte. | | ||
| 35 | +| `cwd` | chaîne | non | Où le processus démarre, et le `cwd` annoncé à l'agent. Relatif à la racine du projet. Par défaut, la racine du projet. | | ||
| 36 | + | ||
| 37 | +`env` peut aussi s'écrire en sous-table, ce qui est la même chose : | ||
| 38 | + | ||
| 39 | +```toml | ||
| 40 | +[[agent]] | ||
| 41 | +name = "Bob (llama.cpp)" | ||
| 42 | +command = "docker" | ||
| 43 | +args = ["agent", "serve", "acp", ".turbo-python/agent.yaml"] | ||
| 44 | + | ||
| 45 | +[agent.env] | ||
| 46 | +TELEMETRY_ENABLED = "false" | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +### Ce qui est refusé | ||
| 50 | + | ||
| 51 | +Le fichier est refusé dans son ensemble, plutôt que chargé à moitié, dès que l'un de ces cas se présente. Un menu à moitié chargé proposant trois de vos cinq agents est pire qu'une erreur qui dit pourquoi. | ||
| 52 | + | ||
| 53 | +| Problème | Message | | ||
| 54 | +| --- | --- | | ||
| 55 | +| un agent sans `name` | `reading …/acp.toml: agent 1 has no name` | | ||
| 56 | +| un agent sans `command` | `reading …/acp.toml: agent "Bob" has no command` | | ||
| 57 | +| deux agents portant le même `name` | `reading …/acp.toml: two agents are called "Bob"` | | ||
| 58 | +| une clé que le format ne définit pas | `reading …/acp.toml: agent.comand is not a key this file has` | | ||
| 59 | + | ||
| 60 | +Le dernier cas est voulu : une clé mal orthographiée silencieusement ignorée ressemblerait exactement à une clé sans effet. | ||
| 61 | + | ||
| 62 | +## Le menu Agent | ||
| 63 | + | ||
| 64 | +`Alt-A` l'ouvre. Il est sur la barre qu'un agent soit configuré ou non, parce que c'est de là que **Create agents file** doit être atteignable. | ||
| 65 | + | ||
| 66 | +| Entrée | Active quand | Effet | | ||
| 67 | +| --- | --- | --- | | ||
| 68 | +| *une entrée par agent, par son nom* | toujours | Démarrer cet agent et ouvrir une fenêtre dessus | | ||
| 69 | +| **Create agents file** | pas d'`acp.toml` dans le projet | Écrire le fichier de départ et l'ouvrir | | ||
| 70 | +| **Cancel turn** | un tour est en cours dans la fenêtre de devant | `session/cancel` | | ||
| 71 | +| **Agent status** | toujours | Ce qui a été chargé, la ligne de commande de chacun, et ce qui a échoué | | ||
| 72 | + | ||
| 73 | +## Touches dans une fenêtre agent | ||
| 74 | + | ||
| 75 | +Une fenêtre agent est une fenêtre ordinaire : `F6`, `Alt-1`…`Alt-9`, Tile, Maximise, `[x]` et `[■]` y fonctionnent tous. À l'intérieur : | ||
| 76 | + | ||
| 77 | +| Touche | Effet | | ||
| 78 | +| --- | --- | | ||
| 79 | +| `Entrée` | Envoyer la zone de saisie comme invite | | ||
| 80 | +| `Alt-Entrée` | Insérer un saut de ligne dans la zone de saisie | | ||
| 81 | +| `Tab` | Déplacer le focus entre la conversation et la zone de saisie | | ||
| 82 | +| `Ctrl-C`, `Ctrl-Ins` | Copier la sélection, ou le bloc sur lequel est le curseur | | ||
| 83 | +| `Échap` | Abandonner la sélection ; s'il n'y en a pas, annuler le tour en cours | | ||
| 84 | +| `Ctrl-W` | Fermer la fenêtre et arrêter l'agent | | ||
| 85 | + | ||
| 86 | +Avec la **zone de saisie** au premier plan : | ||
| 87 | + | ||
| 88 | +| Touche | Effet | | ||
| 89 | +| --- | --- | | ||
| 90 | +| `↑` `↓` `←` `→` `Début` `Fin` | Déplacer le curseur dans ce que vous tapez | | ||
| 91 | +| `Retour arrière` `Suppr` | L'éditer ; le retour arrière en début de ligne la joint à celle du dessus | | ||
| 92 | +| `/` en premier caractère | Ouvrir la liste des commandes de l'agent — voir [Commandes et mentions](#commandes-et-mentions) | | ||
| 93 | +| `@` | Ouvrir la liste des fichiers du projet, réduite par ce que vous tapez ensuite | | ||
| 94 | +| `↑` `↓` `PgUp` `PgDn`, liste ouverte | Se déplacer dans la liste | | ||
| 95 | +| `Tab`, liste ouverte | Prendre l'entrée en surbrillance | | ||
| 96 | +| `Entrée`, liste ouverte | Prendre l'entrée en surbrillance ; sur un mot déjà complet, envoyer | | ||
| 97 | +| `Échap`, liste ouverte | Fermer la liste jusqu'à ce que le texte change | | ||
| 98 | + | ||
| 99 | +Avec la **conversation** au premier plan : | ||
| 100 | + | ||
| 101 | +| Touche | Effet | | ||
| 102 | +| --- | --- | | ||
| 103 | +| `↑` `↓` | Déplacer le curseur d'une ligne | | ||
| 104 | +| `PgUp` `PgDn` | Le déplacer d'un écran | | ||
| 105 | +| `Début` `Fin` | Le début de la conversation, et la fin | | ||
| 106 | +| `Shift-` l'une d'elles | Étendre la sélection à la place | | ||
| 107 | +| Glisser avec le bouton 1 | Sélectionner à la main | | ||
| 108 | +| Molette | Défiler de trois lignes sans bouger le curseur | | ||
| 109 | + | ||
| 110 | +Contrairement à une fenêtre terminal, une fenêtre agent ne **prend pas** les raccourcis de l'éditeur : il n'y a pas de shell qui ait besoin de `Ctrl-F`, donc cette touche garde son sens habituel. `Ctrl-C` fait exception, et seulement parce que rien d'autre n'en veut dans une fenêtre agent. | ||
| 111 | + | ||
| 112 | +## Commandes et mentions | ||
| 113 | + | ||
| 114 | +Deux caractères ouvrent une liste par-dessus le bas de la conversation pendant que vous tapez. Ce sont les deux mêmes que Zed, si bien que la documentation d'un agent — « tapez `/web` pour chercher » — reste vraie ici. | ||
| 115 | + | ||
| 116 | +### `/` — les commandes de l'agent | ||
| 117 | + | ||
| 118 | +Un agent peut annoncer des commandes par `available_commands_update`, au début de la session ou à tout moment pendant celle-ci. Taper `/` comme **premier caractère** de la zone de saisie les liste : le nom, la description donnée par l'agent et, entre chevrons, ce qu'il attend après le nom quand il attend quelque chose. Continuez à taper pour réduire la liste ; la correspondance porte sur le début du nom et ignore la casse. | ||
| 119 | + | ||
| 120 | +`Tab` complète la commande en surbrillance. Une commande qui prend une entrée est complétée avec une espace à la fin, pour que la suite de votre frappe soit son argument ; une qui n'en prend pas est complétée au nom seul. `Entrée` complète aussi, sauf sur un mot qui se lit déjà exactement comme une commande, où elle envoie. | ||
| 121 | + | ||
| 122 | +Sur le fil, une commande est du **texte** : `/web agent client protocol` part comme un seul bloc texte, et l'agent la reconnaît à son premier mot. C'est tout le protocole des commandes, et c'est pourquoi un `/` ailleurs qu'au début de la zone n'est qu'un caractère. | ||
| 123 | + | ||
| 124 | +Sans commande annoncée, `/` est un caractère et `Tab` garde son sens habituel. **Agent ▸ Agent status** liste les commandes avec leur description. | ||
| 125 | + | ||
| 126 | +### `@` — un fichier du projet | ||
| 127 | + | ||
| 128 | +Taper `@` n'importe où dans la zone liste les fichiers du projet, relatifs à sa racine, avec des barres obliques. Ce que vous tapez après le `@` réduit la liste : les fichiers dont le nom propre commence par cela viennent d'abord, puis ceux dont le chemin le contient seulement. `Tab` ou `Entrée` complète celui en surbrillance et ajoute une espace. | ||
| 129 | + | ||
| 130 | +À l'envoi de l'invite, chaque `@nom` qui désigne un fichier connu de la liste devient un bloc de contenu **à la place du nom** : | ||
| 131 | + | ||
| 132 | +| L'agent a déclaré | Le bloc envoyé | | ||
| 133 | +| --- | --- | | ||
| 134 | +| `promptCapabilities.embeddedContext: true` | `resource` — l'`uri` du fichier, son `mimeType` et son `text` entier, lu comme `fs/read_text_file` le lit : depuis le tampon ouvert quand le fichier est ouvert et modifié | | ||
| 135 | +| autre chose, ou le fichier n'a pas pu être lu | `resource_link` — l'`uri`, le `name` et le `mimeType`, pour que l'agent aille le chercher lui-même | | ||
| 136 | + | ||
| 137 | +Les mots de part et d'autre partent en blocs texte, si bien que `explique @docs/README.md s'il te plaît` fait trois blocs : `explique `, le fichier, ` s'il te plaît`. La conversation garde la ligne telle que vous l'avez tapée. | ||
| 138 | + | ||
| 139 | +Un mot qui commence par `@` et ne désigne aucun fichier reste du texte — une adresse électronique dans une invite n'est pas un fichier — et `@main.go` ne désigne pas `main.gopher` : le nom doit terminer le mot. | ||
| 140 | + | ||
| 141 | +La liste est le projet parcouru depuis sa racine, `.git` exclu, au plus 5 000 fichiers, et au plus 200 d'entre eux affichés à la fois. Au-delà de l'une ou l'autre limite, tapez une lettre de plus. Le parcours est refait à chaque ouverture de la liste par `@`, si bien qu'un fichier que l'agent vient de créer y figure. | ||
| 142 | + | ||
| 143 | +## La copie | ||
| 144 | + | ||
| 145 | +La sélection porte sur des **lignes entières**. Rien ne s'édite dans une conversation, donc une demi-ligne n'est jamais ce qu'on veut dire, et des lignes entières préservent l'indentation d'un bloc de code copié. | ||
| 146 | + | ||
| 147 | +Sans rien de sélectionné, la copie prend la **région sur laquelle est le curseur** : un bloc de code délimité, un passage de prose, la sortie d'un appel d'outil. Le libellé d'un interlocuteur et l'en-tête d'un appel d'outil sont du mobilier et forment des régions à part : ni l'un ni l'autre n'est jamais copié avec ce qu'il surmonte. | ||
| 148 | + | ||
| 149 | +L'indentation d'affichage de la conversation est retirée, donc le code collé arrive collé à la marge. | ||
| 150 | + | ||
| 151 | +Le texte part à deux endroits à la fois : | ||
| 152 | + | ||
| 153 | +| Presse-papiers | Comment | Collé avec | | ||
| 154 | +| --- | --- | --- | | ||
| 155 | +| Celui de l'éditeur | directement | `Shift-Ins`, dans un fichier ouvert ici | | ||
| 156 | +| Celui du système | OSC 52, à travers le terminal | `Ctrl-V`, n'importe où ailleurs | | ||
| 157 | + | ||
| 158 | +Rien ne vérifie que le terminal a accepté le second : il n'y a pas de réponse à vérifier, et un terminal peut refuser OSC 52 par sécurité ou demander qu'on l'active. Le presse-papiers de l'éditeur contient le texte dans tous les cas, et la barre d'état dit combien de lignes ont été copiées. | ||
| 159 | + | ||
| 160 | +## Quelle part du protocole est implémentée | ||
| 161 | + | ||
| 162 | +Version de protocole **1**. Turbo Python annonce sa version dans `initialize` et accepte la version que l'agent répond, pourvu qu'il la connaisse. | ||
| 163 | + | ||
| 164 | +### Ce que l'éditeur appelle sur l'agent | ||
| 165 | + | ||
| 166 | +| Méthode | Implémentée | Remarques | | ||
| 167 | +| --- | --- | --- | | ||
| 168 | +| `initialize` | oui | Annonce la capacité `fs` ci-dessous ; `terminal` n'est pas annoncée | | ||
| 169 | +| `session/new` | oui | `cwd` vient de la clé `cwd` de l'agent ; `mcpServers` est toujours vide — les serveurs MCP sont l'affaire de l'agent | | ||
| 170 | +| `session/prompt` | oui | Des blocs texte, et un bloc `resource` ou `resource_link` par fichier désigné par `@` — voir [Commandes et mentions](#commandes-et-mentions) | | ||
| 171 | +| `session/cancel` | oui | `Échap`, et **Agent ▸ Cancel turn** | | ||
| 172 | +| `session/load` | **non** | Les conversations ne survivent pas à la fermeture de la fenêtre | | ||
| 173 | +| `authenticate` | **non** | Un agent qui liste des `authMethods` est signalé comme exigeant une connexion que l'éditeur ne sait pas faire | | ||
| 174 | + | ||
| 175 | +### Ce que l'agent peut appeler sur l'éditeur | ||
| 176 | + | ||
| 177 | +| Méthode | Implémentée | Remarques | | ||
| 178 | +| --- | --- | --- | | ||
| 179 | +| `session/update` | oui | Voir la table ci-dessous | | ||
| 180 | +| `session/request_permission` | oui | Une boîte modale portant les options de l'agent lui-même | | ||
| 181 | +| `fs/read_text_file` | oui | Depuis le tampon quand le fichier est ouvert et modifié, sinon depuis le disque | | ||
| 182 | +| `fs/write_text_file` | oui | Dans le tampon quand le fichier est ouvert, sinon sur le disque | | ||
| 183 | +| `terminal/*` | **non** | Non annoncée, donc un agent conforme ne la demandera pas | | ||
| 184 | + | ||
| 185 | +### Mises à jour de session | ||
| 186 | + | ||
| 187 | +| `sessionUpdate` | Affiché comme | | ||
| 188 | +| --- | --- | | ||
| 189 | +| `agent_message_chunk` | La réponse de l'agent, ajoutée au fil de son arrivée | | ||
| 190 | +| `agent_thought_chunk` | La même chose, dans la couleur des commentaires, sous une étiquette *réflexion* | | ||
| 191 | +| `user_message_chunk` | Votre propre message, tel que l'agent le renvoie | | ||
| 192 | +| `tool_call` | Une ligne nommant l'outil et son titre, avec son état | | ||
| 193 | +| `tool_call_update` | Repliée sur la ligne dont le `toolCallId` correspond, avec sa sortie | | ||
| 194 | +| `plan` | Les entrées en liste, chacune avec son état | | ||
| 195 | +| `available_commands_update` | La liste que `/` ouvre dans la zone de saisie ; aussi listée, avec les descriptions, par **Agent ▸ Agent status** | | ||
| 196 | +| `usage_update` | Le compte de jetons dans la barre d'état quand la fenêtre est devant | | ||
| 197 | +| tout le reste | Ignoré, et compté ; le compte figure dans **Agent status** | | ||
| 198 | + | ||
| 199 | +Pendant qu'un tour est en cours, la règle entre les deux zones fait tourner un indicateur. Il est dessiné à partir de l'horloge et non d'un compteur, donc deux fenêtres qui réfléchissent en même temps tournent en phase et rien n'a besoin d'être remis à zéro au début d'un tour. Le *titre* de la fenêtre, lui, n'est délibérément pas animé : c'est aussi ce qu'affichent la liste des fenêtres et le menu `Alt`-chiffre, et un nom qui change huit fois par seconde les fait scintiller tous les deux. | ||
| 200 | + | ||
| 201 | +Une mise à jour inconnue est ignorée plutôt que refusée : le protocole grandit, et un éditeur qui cesserait de parler à un agent parce que celui-ci a appris un nouveau type de message aurait tort plus souvent que raison. | ||
| 202 | + | ||
| 203 | +## Coloration | ||
| 204 | + | ||
| 205 | +La conversation est dessinée avec des clés que tous les thèmes définissent déjà, donc aucun n'a eu besoin d'être touché : | ||
| 206 | + | ||
| 207 | +| Élément | Classe | | ||
| 208 | +| --- | --- | | ||
| 209 | +| Le nom d'un interlocuteur | `syntax.keyword` | | ||
| 210 | +| Une réflexion | `syntax.comment` | | ||
| 211 | +| Un appel d'outil et son état | `syntax.type` | | ||
| 212 | +| Un appel d'outil en échec, et les avis de l'éditeur | `diagnostic.error` | | ||
| 213 | +| Une ligne sélectionnée, et la barre du curseur | `editor.selection` | | ||
| 214 | +| Le code dans un bloc délimité | l'analyseur du langage annoncé | | ||
| 215 | +| Tout le reste | le texte ordinaire de la fenêtre | | ||
| 216 | + | ||
| 217 | +Un bloc délimité annonçant un langage que l'éditeur colore — `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash` — est coloré par cet analyseur. Un bloc annonçant autre chose, ou rien, est laissé brut. | ||
| 218 | + | ||
| 219 | +## Tracer la conversation avec un agent | ||
| 220 | + | ||
| 221 | +| Variable | Effet | | ||
| 222 | +| --- | --- | | ||
| 223 | +| `TURBO_ACP_TRACE=<fichier>` | Ajouter à ce fichier chaque message vers et depuis chaque agent, un par ligne, horodaté et marqué `->` (envoyé) ou `<-` (reçu) | | ||
| 224 | + | ||
| 225 | +C'est pour la seule question à laquelle l'écran ne peut pas répondre — *qu'a réellement envoyé l'agent ?* Une mise à jour que cet éditeur ne sait pas décoder est comptée dans **Agent ▸ Agent status**, qui nomme aussi la dernière et son erreur ; la trace montre le message lui-même. Un fichier qui ne peut pas être ouvert veut dire pas de trace, et rien d'autre : la trace n'a jamais le droit de casser l'éditeur. | ||
| 226 | + | ||
| 227 | +## Limites | ||
| 228 | + | ||
| 229 | +- **Une session par fenêtre.** Fermer la fenêtre termine la session ; il n'y a pas de reprise. | ||
| 230 | +- **Texte et fichiers seulement.** L'éditeur envoie du texte, et les fichiers que vous désignez par `@` ; ni images ni audio, quoi que disent les `promptCapabilities` de l'agent. | ||
| 231 | +- **Pas d'authentification.** Un agent exigeant une connexion doit être connecté par sa propre CLI avant que l'éditeur ne le lance. | ||
| 232 | +- **`args` n'est pas une commande shell.** `command = "sh"`, `args = ["-c", "…"]` est la façon délibérée d'en obtenir une. | ||
| 233 | +- **Une entrée est plafonnée** à un mégaoctet de texte. Un agent qui déverse tout un journal de compilation ne peut pas rendre la fenêtre inutilisable ; ce qui a été perdu est signalé dans l'entrée elle-même. | ||
| 234 | + | ||
| 235 | +## Voir aussi | ||
| 236 | + | ||
| 237 | +- La tâche : [Dialoguer avec un agent de code depuis l'éditeur](../how-to/talk-to-an-agent.md) | ||
| 238 | +- Le raisonnement : [Fenêtres agent](../explanation/agent-windows.md) | ||
| 239 | +- Le protocole : [agentclientprotocol.com](https://agentclientprotocol.com) | ||
added
docs/fr/reference/cli.md +100 -0 | new file mode 100644 | ||
| @@ -0,0 +1,100 @@ | ||
| 1 | +# Référence : ligne de commande | |
| 2 | + | |
| 3 | +> Description neutre de la commande `turbo-python`, de ses options et de l'environnement qu'elle lit. | |
| 4 | + | |
| 5 | +## Synopsis | |
| 6 | + | |
| 7 | +``` | |
| 8 | +turbo-python [options] [fichier...] | |
| 9 | +``` | |
| 10 | + | |
| 11 | +Chaque `fichier` est ouvert dans sa propre fenêtre. Un fichier qui n'existe pas encore est ouvert comme un tampon vide associé à ce chemin. Sans aucun fichier, une seule fenêtre vide sans titre est ouverte. | |
| 12 | + | |
| 13 | +## Options | |
| 14 | + | |
| 15 | +| Option | Type | Défaut | Description | | |
| 16 | +| --- | --- | --- | --- | | |
| 17 | +| `-theme <nom>` | chaîne | celui du projet, sinon `turbo-classic` | Thème de démarrage, l'emportant sur celui du projet. Un nom inconnu retombe sur le thème par défaut sans erreur. | | |
| 18 | +| `-list-themes` | booléen | `false` | Affiche chaque thème chargeable avec sa description, puis le répertoire de thèmes utilisateur, et quitte. | | |
| 19 | +| `-no-lsp` | booléen | `false` | Ne démarre pas de serveur de langage. La coloration et l'édition sont inchangées. | | |
| 20 | +| `-version` | booléen | `false` | Affiche `Turbo Python <version>` sur une ligne, avec le commit et la date de build quand le build les a enregistrés, puis quitte. Voir [le numéro de version](versioning.md). | | |
| 21 | +| `-h`, `-help` | booléen | `false` | Affiche la liste des options et quitte. | | |
| 22 | + | |
| 23 | +## Environnement | |
| 24 | + | |
| 25 | +| Variable | Lue par | Effet | | |
| 26 | +| --- | --- | --- | | |
| 27 | +| `TURBO_PYTHON_THEME_DIR` | chargement des thèmes | Répertoire des thèmes utilisateur, à la place du répertoire de configuration de la plateforme. | | |
| 28 | +| `TERM` | tcell | Description de terminal à utiliser. | | |
| 29 | +| `GOBIN`, `GOPATH`, `HOME` | recherche de pylsp | Consultées, dans cet ordre, quand `pylsp` n'est pas dans le `PATH`. | | |
| 30 | + | |
| 31 | +## Fichiers | |
| 32 | + | |
| 33 | +| Chemin | Rôle | | |
| 34 | +| --- | --- | | |
| 35 | +| `$TURBO_PYTHON_THEME_DIR/*.toml` | Thèmes utilisateur, quand la variable est définie. | | |
| 36 | +| `./.turbo-python/settings.toml` | Les réglages de ce projet, lus une fois au démarrage. Voir [réglages de projet](project-settings.md). | | |
| 37 | +| `~/.config/turbo-python/themes/*.toml` | Thèmes utilisateur sous Linux (`os.UserConfigDir`). | | |
| 38 | +| `~/Library/Application Support/turbo-python/themes/*.toml` | Thèmes utilisateur sous macOS. | | |
| 39 | +| `<module>/pyproject.toml` | Trouvé en remontant depuis le premier fichier ; son répertoire devient la racine du serveur de langage. | | |
| 40 | + | |
| 41 | +## Code de sortie | |
| 42 | + | |
| 43 | +| Code | Signification | | |
| 44 | +| --- | --- | | |
| 45 | +| `0` | L'éditeur s'est terminé normalement, ou une option d'information a été utilisée. | | |
| 46 | +| `1` | Le terminal n'a pas pu être ouvert ou initialisé. La raison est écrite sur la sortie d'erreur. | | |
| 47 | + | |
| 48 | +## Cibles make | |
| 49 | + | |
| 50 | +À exécuter depuis un clone. | |
| 51 | + | |
| 52 | +| Cible | Ce qu'elle lance | | |
| 53 | +| --- | --- | | |
| 54 | +| `make help` | Liste les cibles. C'est la cible par défaut. | | |
| 55 | +| `make test` | `uv run pytest` | | |
| 56 | +| `make test-verbose` | `go test -v ./...` | | |
| 57 | +| `make cover` | `go test -cover ./...` | | |
| 58 | +| `make build` | `go build -o bin/turbo-python .` | | |
| 59 | +| `make install` | `scripts/install.sh` — compile et installe dans le PATH | | |
| 60 | +| `make uninstall` | `scripts/install.sh --uninstall` | | |
| 61 | +| `make run FILE=x.go` | `make build`, puis `./bin/turbo-python x.go` | | |
| 62 | +| `make fmt` | `go fmt ./...` | | |
| 63 | +| `make vet` | `uv run ruff check .` | | |
| 64 | +| `make check` | `fmt`, puis `vet`, puis `test` | | |
| 65 | +| `make clean` | Supprime `bin/` | | |
| 66 | + | |
| 67 | +## Exemples | |
| 68 | + | |
| 69 | +```bash | |
| 70 | +turbo-python # une fenêtre vide | |
| 71 | +turbo-python main.py pyproject.toml # deux fenêtres | |
| 72 | +turbo-python -theme turbo-dark main.py # un autre thème | |
| 73 | +turbo-python -no-lsp main.py # sans serveur de langage | |
| 74 | +turbo-python -list-themes # quels thèmes existent | |
| 75 | +``` | |
| 76 | + | |
| 77 | +## Installateur | |
| 78 | + | |
| 79 | +`scripts/install.sh`, également accessible via `make install`. | |
| 80 | + | |
| 81 | +| Option | Description | | |
| 82 | +| --- | --- | | |
| 83 | +| `-p`, `--prefix RÉP` | Installer dans `RÉP` au lieu de `$GOBIN` ou `$GOPATH/bin`. | | |
| 84 | +| `--with-pylsp` | Installer aussi `pylsp`, s'il n'est pas déjà présent. | | |
| 85 | +| `--uninstall` | Retirer un `turbo-python` installé, puis s'arrêter. | | |
| 86 | +| `-h`, `--help` | Afficher les options, puis s'arrêter. | | |
| 87 | + | |
| 88 | +| Code de sortie | Signification | | |
| 89 | +| --- | --- | | |
| 90 | +| `0` | Installé, retiré, ou aide affichée. | | |
| 91 | +| `1` | Go absent ou trop ancien, échec de compilation, ou destination non accessible en écriture. Rien n'est installé et une installation existante reste intacte. | | |
| 92 | + | |
| 93 | +## Erreurs | |
| 94 | + | |
| 95 | +| Message | Cause | | |
| 96 | +| --- | --- | | |
| 97 | +| `turbo-python: opening the terminal: …` | tcell n'a pas pu ouvrir le terminal ; en général `TERM` est absent ou inconnu. | | |
| 98 | +| `turbo-python: initialising the terminal: …` | Le terminal a été ouvert mais n'a pas pu être mis en mode brut. | | |
| 99 | +| `Cannot open` (dans une boîte) | Le chemin est un répertoire, ou n'est pas lisible. | | |
| 100 | +| `Cannot save` (dans une boîte) | Le répertoire n'existe pas, ou n'est pas accessible en écriture. | | |
| new file mode 100644 | |||
| @@ -0,0 +1,100 @@ | |||
| 1 | +# Référence : ligne de commande | ||
| 2 | + | ||
| 3 | +> Description neutre de la commande `turbo-python`, de ses options et de l'environnement qu'elle lit. | ||
| 4 | + | ||
| 5 | +## Synopsis | ||
| 6 | + | ||
| 7 | +``` | ||
| 8 | +turbo-python [options] [fichier...] | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +Chaque `fichier` est ouvert dans sa propre fenêtre. Un fichier qui n'existe pas encore est ouvert comme un tampon vide associé à ce chemin. Sans aucun fichier, une seule fenêtre vide sans titre est ouverte. | ||
| 12 | + | ||
| 13 | +## Options | ||
| 14 | + | ||
| 15 | +| Option | Type | Défaut | Description | | ||
| 16 | +| --- | --- | --- | --- | | ||
| 17 | +| `-theme <nom>` | chaîne | celui du projet, sinon `turbo-classic` | Thème de démarrage, l'emportant sur celui du projet. Un nom inconnu retombe sur le thème par défaut sans erreur. | | ||
| 18 | +| `-list-themes` | booléen | `false` | Affiche chaque thème chargeable avec sa description, puis le répertoire de thèmes utilisateur, et quitte. | | ||
| 19 | +| `-no-lsp` | booléen | `false` | Ne démarre pas de serveur de langage. La coloration et l'édition sont inchangées. | | ||
| 20 | +| `-version` | booléen | `false` | Affiche `Turbo Python <version>` sur une ligne, avec le commit et la date de build quand le build les a enregistrés, puis quitte. Voir [le numéro de version](versioning.md). | | ||
| 21 | +| `-h`, `-help` | booléen | `false` | Affiche la liste des options et quitte. | | ||
| 22 | + | ||
| 23 | +## Environnement | ||
| 24 | + | ||
| 25 | +| Variable | Lue par | Effet | | ||
| 26 | +| --- | --- | --- | | ||
| 27 | +| `TURBO_PYTHON_THEME_DIR` | chargement des thèmes | Répertoire des thèmes utilisateur, à la place du répertoire de configuration de la plateforme. | | ||
| 28 | +| `TERM` | tcell | Description de terminal à utiliser. | | ||
| 29 | +| `GOBIN`, `GOPATH`, `HOME` | recherche de pylsp | Consultées, dans cet ordre, quand `pylsp` n'est pas dans le `PATH`. | | ||
| 30 | + | ||
| 31 | +## Fichiers | ||
| 32 | + | ||
| 33 | +| Chemin | Rôle | | ||
| 34 | +| --- | --- | | ||
| 35 | +| `$TURBO_PYTHON_THEME_DIR/*.toml` | Thèmes utilisateur, quand la variable est définie. | | ||
| 36 | +| `./.turbo-python/settings.toml` | Les réglages de ce projet, lus une fois au démarrage. Voir [réglages de projet](project-settings.md). | | ||
| 37 | +| `~/.config/turbo-python/themes/*.toml` | Thèmes utilisateur sous Linux (`os.UserConfigDir`). | | ||
| 38 | +| `~/Library/Application Support/turbo-python/themes/*.toml` | Thèmes utilisateur sous macOS. | | ||
| 39 | +| `<module>/pyproject.toml` | Trouvé en remontant depuis le premier fichier ; son répertoire devient la racine du serveur de langage. | | ||
| 40 | + | ||
| 41 | +## Code de sortie | ||
| 42 | + | ||
| 43 | +| Code | Signification | | ||
| 44 | +| --- | --- | | ||
| 45 | +| `0` | L'éditeur s'est terminé normalement, ou une option d'information a été utilisée. | | ||
| 46 | +| `1` | Le terminal n'a pas pu être ouvert ou initialisé. La raison est écrite sur la sortie d'erreur. | | ||
| 47 | + | ||
| 48 | +## Cibles make | ||
| 49 | + | ||
| 50 | +À exécuter depuis un clone. | ||
| 51 | + | ||
| 52 | +| Cible | Ce qu'elle lance | | ||
| 53 | +| --- | --- | | ||
| 54 | +| `make help` | Liste les cibles. C'est la cible par défaut. | | ||
| 55 | +| `make test` | `uv run pytest` | | ||
| 56 | +| `make test-verbose` | `go test -v ./...` | | ||
| 57 | +| `make cover` | `go test -cover ./...` | | ||
| 58 | +| `make build` | `go build -o bin/turbo-python .` | | ||
| 59 | +| `make install` | `scripts/install.sh` — compile et installe dans le PATH | | ||
| 60 | +| `make uninstall` | `scripts/install.sh --uninstall` | | ||
| 61 | +| `make run FILE=x.go` | `make build`, puis `./bin/turbo-python x.go` | | ||
| 62 | +| `make fmt` | `go fmt ./...` | | ||
| 63 | +| `make vet` | `uv run ruff check .` | | ||
| 64 | +| `make check` | `fmt`, puis `vet`, puis `test` | | ||
| 65 | +| `make clean` | Supprime `bin/` | | ||
| 66 | + | ||
| 67 | +## Exemples | ||
| 68 | + | ||
| 69 | +```bash | ||
| 70 | +turbo-python # une fenêtre vide | ||
| 71 | +turbo-python main.py pyproject.toml # deux fenêtres | ||
| 72 | +turbo-python -theme turbo-dark main.py # un autre thème | ||
| 73 | +turbo-python -no-lsp main.py # sans serveur de langage | ||
| 74 | +turbo-python -list-themes # quels thèmes existent | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +## Installateur | ||
| 78 | + | ||
| 79 | +`scripts/install.sh`, également accessible via `make install`. | ||
| 80 | + | ||
| 81 | +| Option | Description | | ||
| 82 | +| --- | --- | | ||
| 83 | +| `-p`, `--prefix RÉP` | Installer dans `RÉP` au lieu de `$GOBIN` ou `$GOPATH/bin`. | | ||
| 84 | +| `--with-pylsp` | Installer aussi `pylsp`, s'il n'est pas déjà présent. | | ||
| 85 | +| `--uninstall` | Retirer un `turbo-python` installé, puis s'arrêter. | | ||
| 86 | +| `-h`, `--help` | Afficher les options, puis s'arrêter. | | ||
| 87 | + | ||
| 88 | +| Code de sortie | Signification | | ||
| 89 | +| --- | --- | | ||
| 90 | +| `0` | Installé, retiré, ou aide affichée. | | ||
| 91 | +| `1` | Go absent ou trop ancien, échec de compilation, ou destination non accessible en écriture. Rien n'est installé et une installation existante reste intacte. | | ||
| 92 | + | ||
| 93 | +## Erreurs | ||
| 94 | + | ||
| 95 | +| Message | Cause | | ||
| 96 | +| --- | --- | | ||
| 97 | +| `turbo-python: opening the terminal: …` | tcell n'a pas pu ouvrir le terminal ; en général `TERM` est absent ou inconnu. | | ||
| 98 | +| `turbo-python: initialising the terminal: …` | Le terminal a été ouvert mais n'a pas pu être mis en mode brut. | | ||
| 99 | +| `Cannot open` (dans une boîte) | Le chemin est un répertoire, ou n'est pas lisible. | | ||
| 100 | +| `Cannot save` (dans une boîte) | Le répertoire n'existe pas, ou n'est pas accessible en écriture. | | ||
added
docs/fr/reference/keyboard.md +177 -0 | new file mode 100644 | ||
| @@ -0,0 +1,177 @@ | ||
| 1 | +# Référence : clavier | |
| 2 | + | |
| 3 | +> Liste complète des touches auxquelles Turbo Python répond, regroupées par élément qui a le focus. | |
| 4 | + | |
| 5 | +Lorsque deux écritures existent, les deux fonctionnent : celle de Turbo C et la moderne. | |
| 6 | + | |
| 7 | +## Global | |
| 8 | + | |
| 9 | +Traitées où que soit le focus, sauf si un dialogue ou la liste de complétion est ouvert. | |
| 10 | + | |
| 11 | +| Touche | Action | | |
| 12 | +| --- | --- | | |
| 13 | +| `F1` | Décrire le symbole sous le curseur ; sans fichier ouvert, afficher l'aide clavier | | |
| 14 | +| `F2` | Enregistrer | | |
| 15 | +| `F3` | Ouvrir | | |
| 16 | +| `F4` | Nouveau | | |
| 17 | +| `F6` | Fenêtre suivante | | |
| 18 | +| `F7` | Occurrence suivante | | |
| 19 | +| `Maj-F7` | Occurrence précédente | | |
| 20 | +| `F8` | Ouvrir une fenêtre terminal | | |
| 21 | +| `F9` | Ouvrir l'arbre du projet | | |
| 22 | +| `F10` | Ouvrir la barre de menus | | |
| 23 | +| `F12` | Aller à la définition | | |
| 24 | +| `Shift-F12` | Trouver les références | | |
| 25 | +| `Ctrl-T` | Trouver un symbole dans tout le projet | | |
| 26 | +| `Ctrl-F` | Chercher | | |
| 27 | +| `Ctrl-G` | Aller à la ligne | | |
| 28 | +| `Ctrl-W` | Fermer la fenêtre courante | | |
| 29 | +| `Alt-X` | Quitter | | |
| 30 | +| `Alt-1` … `Alt-9` | Passer la fenêtre 1…9 au premier plan | | |
| 31 | +| `Alt-0` | Lister les fenêtres ouvertes | | |
| 32 | +| `Alt-N` | Ouvrir le menu Snippets | | |
| 33 | +| `Alt-P` | Ouvrir le menu Python | | |
| 34 | +| `Alt-<lettre>` | Ouvrir le menu dont le titre porte cette lettre | | |
| 35 | + | |
| 36 | +Un menu ajouté par le fichier d'outils du projet reçoit sa lettre par attribution et non par choix, donc ce n'est jamais une de celles ci-dessus. Les règles sont dans [Outils Python](python-tools.md#touches-daccès). | |
| 37 | + | |
| 38 | +## Édition | |
| 39 | + | |
| 40 | +Traitées par la fenêtre qui a le focus. | |
| 41 | + | |
| 42 | +### Déplacement | |
| 43 | + | |
| 44 | +| Touche | Action | | |
| 45 | +| --- | --- | | |
| 46 | +| `←` `→` `↑` `↓` | Un caractère ou une ligne | | |
| 47 | +| `Ctrl-←` `Ctrl-→` | Début du mot précédent / suivant | | |
| 48 | +| `Origine` `Fin` | Début / fin de la ligne | | |
| 49 | +| `Ctrl-Origine` `Ctrl-Fin` | Début / fin du fichier | | |
| 50 | +| `Page↑` `Page↓` | Un écran | | |
| 51 | +| `Maj` + l'une des précédentes | Le même déplacement, en étendant la sélection | | |
| 52 | + | |
| 53 | +### Modification du texte | |
| 54 | + | |
| 55 | +| Touche | Action | | |
| 56 | +| --- | --- | | |
| 57 | +| tout caractère imprimable | L'insérer, en remplaçant la sélection | | |
| 58 | +| `Entrée` | Couper la ligne, en recopiant l'indentation de la ligne courante | | |
| 59 | +| `Retour arrière` | Supprimer la sélection, ou le caractère avant le curseur | | |
| 60 | +| `Suppr` | Supprimer la sélection, ou le caractère sous le curseur | | |
| 61 | +| `Tab` | Insérer une tabulation ; avec une sélection, indenter chaque ligne concernée | | |
| 62 | +| `Maj-Tab` | Retirer un niveau d'indentation de chaque ligne concernée | | |
| 63 | + | |
| 64 | +### Presse-papier et historique | |
| 65 | + | |
| 66 | +| Touche | Aussi | Action | | |
| 67 | +| --- | --- | --- | | |
| 68 | +| `Ctrl-C` | `Ctrl-Inser` | Copier la sélection | | |
| 69 | +| `Ctrl-X` | `Maj-Suppr` | Couper la sélection | | |
| 70 | +| `Ctrl-V` | `Maj-Inser` | Coller | | |
| 71 | +| `Ctrl-A` | | Tout sélectionner | | |
| 72 | +| `Ctrl-Z` | | Annuler | | |
| 73 | +| `Ctrl-R` | | Rétablir | | |
| 74 | +| `Ctrl-N` | | Insérer une ligne vide au-dessus du curseur | | |
| 75 | +| `Ctrl-Y` | | Supprimer la ligne où est le curseur | | |
| 76 | + | |
| 77 | +Une série de caractères tapés, ou une série de retours arrière, forme **une seule** étape d'annulation. Déplacer le curseur clôt la série. | |
| 78 | + | |
| 79 | +### Serveur de langage | |
| 80 | + | |
| 81 | +| Touche | Action | | |
| 82 | +| --- | --- | | |
| 83 | +| `Ctrl-Espace` | Demander une liste de complétion | | |
| 84 | +| `.` | Demander une liste de complétion, en effet de bord de la frappe | | |
| 85 | +| `F1` | Décrire le symbole sous le curseur | | |
| 86 | +| `F12` | Aller à la déclaration | | |
| 87 | + | |
| 88 | +## Barre de menus | |
| 89 | + | |
| 90 | +Une fois un menu ouvert. | |
| 91 | + | |
| 92 | +| Touche | Action | | |
| 93 | +| --- | --- | | |
| 94 | +| `←` `→` | Menu précédent / suivant | | |
| 95 | +| `↑` `↓` | Entrée précédente / suivante, en sautant les séparateurs et les entrées grisées | | |
| 96 | +| `Entrée` | Exécuter l'entrée surlignée | | |
| 97 | +| `<lettre>` | Exécuter l'entrée dont l'intitulé porte cette lettre | | |
| 98 | +| `Échap` | Fermer le menu | | |
| 99 | + | |
| 100 | +Toute autre touche est absorbée : une frappe égarée n'atteint jamais le fichier derrière. | |
| 101 | + | |
| 102 | +## Dialogues | |
| 103 | + | |
| 104 | +| Touche | Action | | |
| 105 | +| --- | --- | | |
| 106 | +| `Tab` / `Maj-Tab` | Contrôle suivant / précédent | | |
| 107 | +| `↑` `↓` | Parcourir la liste qui a le focus ; si le contrôle n'en a pas l'usage, contrôle suivant / précédent | | |
| 108 | +| `Entrée` | Actionner le bouton par défaut, d'où que soit le focus | | |
| 109 | +| `Échap` | Annuler | | |
| 110 | +| `Alt-<lettre>` | Actionner le bouton dont l'intitulé porte cette lettre | | |
| 111 | +| `Ctrl-U` | Vider le champ de saisie qui a le focus | | |
| 112 | + | |
| 113 | +Un dialogue est modal : toute touche dont il n'a pas l'usage est absorbée plutôt que transmise à l'éditeur derrière. | |
| 114 | + | |
| 115 | +### La boîte Open et Save As | |
| 116 | + | |
| 117 | +| | | | |
| 118 | +| --- | --- | | |
| 119 | +| Focus à l'ouverture | Le champ **Name**, pour pouvoir taper un nom directement. La première `↓` déplace donc le focus vers la liste ; la seconde déplace la surbrillance. | | |
| 120 | +| Déplacer la surbrillance | Place le nom de cette entrée dans le champ **Name** : le champ dit toujours ce sur quoi **OK** va agir. Surligner `../` le vide. | | |
| 121 | +| `Entrée` sur la liste | Ouvre le fichier surligné, ou entre dans le dossier surligné | | |
| 122 | +| **OK** | Agit sur le champ **Name** ; si le champ est vide, agit sur ce que la liste a surligné | | |
| 123 | +| Un nom qui est un dossier | Y entre au lieu de fermer le dialogue | | |
| 124 | +| Double clic | Équivaut à `Entrée` sur cette entrée | | |
| 125 | + | |
| 126 | +Les fichiers cachés ne sont pas listés. Les dossiers précèdent les fichiers, chaque groupe trié, avec `../` en premier. | |
| 127 | + | |
| 128 | +## Liste de complétion | |
| 129 | + | |
| 130 | +| Touche | Action | | |
| 131 | +| --- | --- | | |
| 132 | +| `↑` `↓` | Suggestion précédente / suivante | | |
| 133 | +| `Page↑` `Page↓` | Huit à la fois | | |
| 134 | +| `Entrée`, `Tab` | Accepter la suggestion surlignée | | |
| 135 | +| `Échap` | Abandonner la liste | | |
| 136 | +| tout caractère imprimable | Transmis à l'éditeur ; la liste se réduit à ce qui correspond encore | | |
| 137 | + | |
| 138 | +## Fenêtres terminal | |
| 139 | + | |
| 140 | +Une fenêtre terminal au premier plan reçoit **toutes les touches sauf** les touches de fonction, `Alt-X` et `Alt-0`…`Alt-9`, qui restent à l'éditeur pour qu'il y ait toujours une sortie hors d'un programme plein écran. `Ctrl-C`, `Ctrl-W`, `Ctrl-F` et `Alt-<lettre>` atteignent donc le shell plutôt que l'éditeur. | |
| 141 | + | |
| 142 | +| Touche | Action | | |
| 143 | +| --- | --- | | |
| 144 | +| `Maj-Page↑` `Maj-Page↓` | Reculer / avancer d'un écran dans l'historique | | |
| 145 | +| toute autre touche non réservée ci-dessus | Envoyée au shell, ramenant la vue à l'écran vivant | | |
| 146 | + | |
| 147 | +Les octets exacts envoyés par chaque touche sont dans [Fenêtres terminal](terminal.md). | |
| 148 | + | |
| 149 | +## Arbre du projet | |
| 150 | + | |
| 151 | +Traitées quand la fenêtre de l'arbre a le focus. Les règles complètes sont dans [Arbre du projet](project-tree.md). | |
| 152 | + | |
| 153 | +| Touche | Action | | |
| 154 | +| --- | --- | | |
| 155 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Déplacer la surbrillance | | |
| 156 | +| `→` | Déplier un dossier fermé, sinon aller à la ligne suivante | | |
| 157 | +| `←` | Replier un dossier ouvert, sinon remonter à son dossier | | |
| 158 | +| `Entrée` | Ouvrir un fichier ; déplier ou replier un dossier | | |
| 159 | +| `F5`, `Ctrl-R` | Relire le projet | | |
| 160 | + | |
| 161 | +## Souris | |
| 162 | + | |
| 163 | +| Action | Effet | | |
| 164 | +| --- | --- | | |
| 165 | +| Clic dans le texte | Placer le curseur | | |
| 166 | +| Glisser dans le texte | Sélectionner | | |
| 167 | +| Molette | Défiler de trois lignes | | |
| 168 | +| Clic sur un titre de menu | Ouvrir ou fermer ce menu | | |
| 169 | +| Clic sur un indice de la barre d'état | L'exécuter | | |
| 170 | +| Clic sur une fenêtre | La passer au premier plan | | |
| 171 | +| Glisser une barre de titre | Déplacer la fenêtre | | |
| 172 | +| Glisser le coin inférieur droit | Redimensionner la fenêtre | | |
| 173 | +| Clic sur `[x]` | Fermer la fenêtre | | |
| 174 | +| Clic sur `[■]` | Donner tout le bureau à la fenêtre | | |
| 175 | +| Clic sur `[▬]` | Remettre une fenêtre agrandie à sa taille précédente | | |
| 176 | +| Molette sur un terminal | Défiler de trois lignes dans son historique | | |
| 177 | +| Clic sur une ligne d'arbre | La surligner ; un second clic l'ouvre | | |
| new file mode 100644 | |||
| @@ -0,0 +1,177 @@ | |||
| 1 | +# Référence : clavier | ||
| 2 | + | ||
| 3 | +> Liste complète des touches auxquelles Turbo Python répond, regroupées par élément qui a le focus. | ||
| 4 | + | ||
| 5 | +Lorsque deux écritures existent, les deux fonctionnent : celle de Turbo C et la moderne. | ||
| 6 | + | ||
| 7 | +## Global | ||
| 8 | + | ||
| 9 | +Traitées où que soit le focus, sauf si un dialogue ou la liste de complétion est ouvert. | ||
| 10 | + | ||
| 11 | +| Touche | Action | | ||
| 12 | +| --- | --- | | ||
| 13 | +| `F1` | Décrire le symbole sous le curseur ; sans fichier ouvert, afficher l'aide clavier | | ||
| 14 | +| `F2` | Enregistrer | | ||
| 15 | +| `F3` | Ouvrir | | ||
| 16 | +| `F4` | Nouveau | | ||
| 17 | +| `F6` | Fenêtre suivante | | ||
| 18 | +| `F7` | Occurrence suivante | | ||
| 19 | +| `Maj-F7` | Occurrence précédente | | ||
| 20 | +| `F8` | Ouvrir une fenêtre terminal | | ||
| 21 | +| `F9` | Ouvrir l'arbre du projet | | ||
| 22 | +| `F10` | Ouvrir la barre de menus | | ||
| 23 | +| `F12` | Aller à la définition | | ||
| 24 | +| `Shift-F12` | Trouver les références | | ||
| 25 | +| `Ctrl-T` | Trouver un symbole dans tout le projet | | ||
| 26 | +| `Ctrl-F` | Chercher | | ||
| 27 | +| `Ctrl-G` | Aller à la ligne | | ||
| 28 | +| `Ctrl-W` | Fermer la fenêtre courante | | ||
| 29 | +| `Alt-X` | Quitter | | ||
| 30 | +| `Alt-1` … `Alt-9` | Passer la fenêtre 1…9 au premier plan | | ||
| 31 | +| `Alt-0` | Lister les fenêtres ouvertes | | ||
| 32 | +| `Alt-N` | Ouvrir le menu Snippets | | ||
| 33 | +| `Alt-P` | Ouvrir le menu Python | | ||
| 34 | +| `Alt-<lettre>` | Ouvrir le menu dont le titre porte cette lettre | | ||
| 35 | + | ||
| 36 | +Un menu ajouté par le fichier d'outils du projet reçoit sa lettre par attribution et non par choix, donc ce n'est jamais une de celles ci-dessus. Les règles sont dans [Outils Python](python-tools.md#touches-daccès). | ||
| 37 | + | ||
| 38 | +## Édition | ||
| 39 | + | ||
| 40 | +Traitées par la fenêtre qui a le focus. | ||
| 41 | + | ||
| 42 | +### Déplacement | ||
| 43 | + | ||
| 44 | +| Touche | Action | | ||
| 45 | +| --- | --- | | ||
| 46 | +| `←` `→` `↑` `↓` | Un caractère ou une ligne | | ||
| 47 | +| `Ctrl-←` `Ctrl-→` | Début du mot précédent / suivant | | ||
| 48 | +| `Origine` `Fin` | Début / fin de la ligne | | ||
| 49 | +| `Ctrl-Origine` `Ctrl-Fin` | Début / fin du fichier | | ||
| 50 | +| `Page↑` `Page↓` | Un écran | | ||
| 51 | +| `Maj` + l'une des précédentes | Le même déplacement, en étendant la sélection | | ||
| 52 | + | ||
| 53 | +### Modification du texte | ||
| 54 | + | ||
| 55 | +| Touche | Action | | ||
| 56 | +| --- | --- | | ||
| 57 | +| tout caractère imprimable | L'insérer, en remplaçant la sélection | | ||
| 58 | +| `Entrée` | Couper la ligne, en recopiant l'indentation de la ligne courante | | ||
| 59 | +| `Retour arrière` | Supprimer la sélection, ou le caractère avant le curseur | | ||
| 60 | +| `Suppr` | Supprimer la sélection, ou le caractère sous le curseur | | ||
| 61 | +| `Tab` | Insérer une tabulation ; avec une sélection, indenter chaque ligne concernée | | ||
| 62 | +| `Maj-Tab` | Retirer un niveau d'indentation de chaque ligne concernée | | ||
| 63 | + | ||
| 64 | +### Presse-papier et historique | ||
| 65 | + | ||
| 66 | +| Touche | Aussi | Action | | ||
| 67 | +| --- | --- | --- | | ||
| 68 | +| `Ctrl-C` | `Ctrl-Inser` | Copier la sélection | | ||
| 69 | +| `Ctrl-X` | `Maj-Suppr` | Couper la sélection | | ||
| 70 | +| `Ctrl-V` | `Maj-Inser` | Coller | | ||
| 71 | +| `Ctrl-A` | | Tout sélectionner | | ||
| 72 | +| `Ctrl-Z` | | Annuler | | ||
| 73 | +| `Ctrl-R` | | Rétablir | | ||
| 74 | +| `Ctrl-N` | | Insérer une ligne vide au-dessus du curseur | | ||
| 75 | +| `Ctrl-Y` | | Supprimer la ligne où est le curseur | | ||
| 76 | + | ||
| 77 | +Une série de caractères tapés, ou une série de retours arrière, forme **une seule** étape d'annulation. Déplacer le curseur clôt la série. | ||
| 78 | + | ||
| 79 | +### Serveur de langage | ||
| 80 | + | ||
| 81 | +| Touche | Action | | ||
| 82 | +| --- | --- | | ||
| 83 | +| `Ctrl-Espace` | Demander une liste de complétion | | ||
| 84 | +| `.` | Demander une liste de complétion, en effet de bord de la frappe | | ||
| 85 | +| `F1` | Décrire le symbole sous le curseur | | ||
| 86 | +| `F12` | Aller à la déclaration | | ||
| 87 | + | ||
| 88 | +## Barre de menus | ||
| 89 | + | ||
| 90 | +Une fois un menu ouvert. | ||
| 91 | + | ||
| 92 | +| Touche | Action | | ||
| 93 | +| --- | --- | | ||
| 94 | +| `←` `→` | Menu précédent / suivant | | ||
| 95 | +| `↑` `↓` | Entrée précédente / suivante, en sautant les séparateurs et les entrées grisées | | ||
| 96 | +| `Entrée` | Exécuter l'entrée surlignée | | ||
| 97 | +| `<lettre>` | Exécuter l'entrée dont l'intitulé porte cette lettre | | ||
| 98 | +| `Échap` | Fermer le menu | | ||
| 99 | + | ||
| 100 | +Toute autre touche est absorbée : une frappe égarée n'atteint jamais le fichier derrière. | ||
| 101 | + | ||
| 102 | +## Dialogues | ||
| 103 | + | ||
| 104 | +| Touche | Action | | ||
| 105 | +| --- | --- | | ||
| 106 | +| `Tab` / `Maj-Tab` | Contrôle suivant / précédent | | ||
| 107 | +| `↑` `↓` | Parcourir la liste qui a le focus ; si le contrôle n'en a pas l'usage, contrôle suivant / précédent | | ||
| 108 | +| `Entrée` | Actionner le bouton par défaut, d'où que soit le focus | | ||
| 109 | +| `Échap` | Annuler | | ||
| 110 | +| `Alt-<lettre>` | Actionner le bouton dont l'intitulé porte cette lettre | | ||
| 111 | +| `Ctrl-U` | Vider le champ de saisie qui a le focus | | ||
| 112 | + | ||
| 113 | +Un dialogue est modal : toute touche dont il n'a pas l'usage est absorbée plutôt que transmise à l'éditeur derrière. | ||
| 114 | + | ||
| 115 | +### La boîte Open et Save As | ||
| 116 | + | ||
| 117 | +| | | | ||
| 118 | +| --- | --- | | ||
| 119 | +| Focus à l'ouverture | Le champ **Name**, pour pouvoir taper un nom directement. La première `↓` déplace donc le focus vers la liste ; la seconde déplace la surbrillance. | | ||
| 120 | +| Déplacer la surbrillance | Place le nom de cette entrée dans le champ **Name** : le champ dit toujours ce sur quoi **OK** va agir. Surligner `../` le vide. | | ||
| 121 | +| `Entrée` sur la liste | Ouvre le fichier surligné, ou entre dans le dossier surligné | | ||
| 122 | +| **OK** | Agit sur le champ **Name** ; si le champ est vide, agit sur ce que la liste a surligné | | ||
| 123 | +| Un nom qui est un dossier | Y entre au lieu de fermer le dialogue | | ||
| 124 | +| Double clic | Équivaut à `Entrée` sur cette entrée | | ||
| 125 | + | ||
| 126 | +Les fichiers cachés ne sont pas listés. Les dossiers précèdent les fichiers, chaque groupe trié, avec `../` en premier. | ||
| 127 | + | ||
| 128 | +## Liste de complétion | ||
| 129 | + | ||
| 130 | +| Touche | Action | | ||
| 131 | +| --- | --- | | ||
| 132 | +| `↑` `↓` | Suggestion précédente / suivante | | ||
| 133 | +| `Page↑` `Page↓` | Huit à la fois | | ||
| 134 | +| `Entrée`, `Tab` | Accepter la suggestion surlignée | | ||
| 135 | +| `Échap` | Abandonner la liste | | ||
| 136 | +| tout caractère imprimable | Transmis à l'éditeur ; la liste se réduit à ce qui correspond encore | | ||
| 137 | + | ||
| 138 | +## Fenêtres terminal | ||
| 139 | + | ||
| 140 | +Une fenêtre terminal au premier plan reçoit **toutes les touches sauf** les touches de fonction, `Alt-X` et `Alt-0`…`Alt-9`, qui restent à l'éditeur pour qu'il y ait toujours une sortie hors d'un programme plein écran. `Ctrl-C`, `Ctrl-W`, `Ctrl-F` et `Alt-<lettre>` atteignent donc le shell plutôt que l'éditeur. | ||
| 141 | + | ||
| 142 | +| Touche | Action | | ||
| 143 | +| --- | --- | | ||
| 144 | +| `Maj-Page↑` `Maj-Page↓` | Reculer / avancer d'un écran dans l'historique | | ||
| 145 | +| toute autre touche non réservée ci-dessus | Envoyée au shell, ramenant la vue à l'écran vivant | | ||
| 146 | + | ||
| 147 | +Les octets exacts envoyés par chaque touche sont dans [Fenêtres terminal](terminal.md). | ||
| 148 | + | ||
| 149 | +## Arbre du projet | ||
| 150 | + | ||
| 151 | +Traitées quand la fenêtre de l'arbre a le focus. Les règles complètes sont dans [Arbre du projet](project-tree.md). | ||
| 152 | + | ||
| 153 | +| Touche | Action | | ||
| 154 | +| --- | --- | | ||
| 155 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Déplacer la surbrillance | | ||
| 156 | +| `→` | Déplier un dossier fermé, sinon aller à la ligne suivante | | ||
| 157 | +| `←` | Replier un dossier ouvert, sinon remonter à son dossier | | ||
| 158 | +| `Entrée` | Ouvrir un fichier ; déplier ou replier un dossier | | ||
| 159 | +| `F5`, `Ctrl-R` | Relire le projet | | ||
| 160 | + | ||
| 161 | +## Souris | ||
| 162 | + | ||
| 163 | +| Action | Effet | | ||
| 164 | +| --- | --- | | ||
| 165 | +| Clic dans le texte | Placer le curseur | | ||
| 166 | +| Glisser dans le texte | Sélectionner | | ||
| 167 | +| Molette | Défiler de trois lignes | | ||
| 168 | +| Clic sur un titre de menu | Ouvrir ou fermer ce menu | | ||
| 169 | +| Clic sur un indice de la barre d'état | L'exécuter | | ||
| 170 | +| Clic sur une fenêtre | La passer au premier plan | | ||
| 171 | +| Glisser une barre de titre | Déplacer la fenêtre | | ||
| 172 | +| Glisser le coin inférieur droit | Redimensionner la fenêtre | | ||
| 173 | +| Clic sur `[x]` | Fermer la fenêtre | | ||
| 174 | +| Clic sur `[■]` | Donner tout le bureau à la fenêtre | | ||
| 175 | +| Clic sur `[▬]` | Remettre une fenêtre agrandie à sa taille précédente | | ||
| 176 | +| Molette sur un terminal | Défiler de trois lignes dans son historique | | ||
| 177 | +| Clic sur une ligne d'arbre | La surligner ; un second clic l'ouvre | | ||
added
docs/fr/reference/languages.md +289 -0 | new file mode 100644 | ||
| @@ -0,0 +1,289 @@ | ||
| 1 | +# Référence : langages colorés | |
| 2 | + | |
| 3 | +> Description neutre des fichiers que Turbo Python colore, de la façon dont il décide, et de ce que reconnaît chaque scanner. | |
| 4 | + | |
| 5 | +## Reconnaissance | |
| 6 | + | |
| 7 | +L'**extension** d'un fichier décide dès qu'elle fait partie de celles-ci : | |
| 8 | + | |
| 9 | +| Extension | Langage | | |
| 10 | +| --- | --- | | |
| 11 | +| `.py`, `.pyi`, `.pyw` | Python | | |
| 12 | +| `.toml` | TOML | | |
| 13 | +| `.yaml`, `.yml` | YAML | | |
| 14 | +| `.md`, `.markdown` | Markdown | | |
| 15 | +| `.js`, `.mjs`, `.cjs` | JavaScript | | |
| 16 | +| `.html`, `.htm` | HTML | | |
| 17 | +| `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, `.plist`, `.csproj`, `.pom` | XML | | |
| 18 | +| `.sh`, `.bash`, `.zsh` | Shell | | |
| 19 | +| `.dockerfile`, `.containerfile` | Dockerfile | | |
| 20 | + | |
| 21 | +Les extensions sont comparées sans tenir compte de la casse, et seule la dernière compte : `main.py.backup` n'est pas du Python. | |
| 22 | + | |
| 23 | +Un fichier dont l'extension ne décide de rien est ensuite cherché par son **nom**. Seuls les fichiers sans extension exploitable en ont besoin : | |
| 24 | + | |
| 25 | +| Nom | Langage | | |
| 26 | +| --- | --- | | |
| 27 | +| `Dockerfile`, `Containerfile` | Dockerfile | | |
| 28 | + | |
| 29 | +Un nom correspond sur sa totalité ou sur la partie précédant le premier point, sans tenir compte de la casse — ainsi `Dockerfile`, `dockerfile` et `Dockerfile.dev` sont tous reconnus, tandis que `Dockerfile.md` est du Markdown, puisque l'extension est consultée en premier. | |
| 30 | + | |
| 31 | +Un fichier qu'aucun des deux tableaux ne revendique est lu par sa **première ligne**. Un shebang nommant `python` ou `python3` en fait du Python ; un shebang nommant un shell — `sh`, `bash`, `zsh`, `dash` ou `ksh` — en fait un script shell. L'interpréteur est reconnu comme élément de chemin ou comme argument d'`env`. C'est ce qui colore un script dans un répertoire `bin`, un hook git, ou `configure`. | |
| 32 | + | |
| 33 | +| Première ligne | Résultat | | |
| 34 | +| --- | --- | | |
| 35 | +| `#!/bin/sh` | Shell | | |
| 36 | +| `#!/usr/bin/env bash` | Shell | | |
| 37 | +| `#!/usr/bin/env -S bash -e` | Shell | | |
| 38 | +| `#!/usr/bin/env python3` | Python | | |
| 39 | +| `#!/usr/bin/python` | Python | | |
| 40 | +| `#!/usr/bin/env node` | Non coloré | | |
| 41 | +| Tout ce qui ne commence pas par `#!` | Non coloré | | |
| 42 | + | |
| 43 | +L'ordre est fixe — extension, puis nom, puis première ligne — et le premier qui décide l'emporte : un fichier `.md` commençant par un shebang Python reste du Markdown. | |
| 44 | + | |
| 45 | +Tout le reste est affiché en texte brut. Ce n'est pas une erreur — ouvrir un PNG dans l'éditeur n'est pas une faute, c'est simplement non coloré. | |
| 46 | + | |
| 47 | +## Classes | |
| 48 | + | |
| 49 | +Tous les scanners produisent le même vocabulaire de classes, et chacune correspond à une clé de thème. | |
| 50 | + | |
| 51 | +| Classe | Clé de thème | Produite par | | |
| 52 | +| --- | --- | --- | | |
| 53 | +| `identifier` | `syntax.identifier` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 54 | +| `keyword` | `syntax.keyword` | Python, JavaScript, shell, HTML (doctype), XML, Dockerfile | | |
| 55 | +| `type` | `syntax.type` | Python, TOML (en-têtes de table), YAML (étiquettes) | | |
| 56 | +| `builtin` | `syntax.builtin` | Python, JavaScript, shell (builtins et expansions), YAML (ancres et alias), Dockerfile (variables) | | |
| 57 | +| `constant` | `syntax.constant` | Python, TOML, JavaScript, shell, YAML, HTML et XML (entités) | | |
| 58 | +| `function` | `syntax.function` | Python, JavaScript, shell (la commande) | | |
| 59 | +| `string` | `syntax.string` | tous | | |
| 60 | +| `char` | `syntax.char` | rien ici ; la classe existe pour les langages qui ont un type caractère, et Python n'en a pas | | |
| 61 | +| `number` | `syntax.number` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 62 | +| `comment` | `syntax.comment` | Python, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | |
| 63 | +| `operator` | `syntax.operator` | Python, TOML, JavaScript, shell, HTML, YAML (en-têtes de scalaire de bloc), XML, Dockerfile | | |
| 64 | +| `punctuation` | `syntax.punctuation` | Python, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | |
| 65 | +| `heading` | `syntax.heading` | Markdown | | |
| 66 | +| `tag` | `syntax.tag` | HTML, XML | | |
| 67 | +| `attribute` | `syntax.attribute` | Python (décorateurs), HTML, XML, Dockerfile (options) | | |
| 68 | +| `emphasis` | `syntax.emphasis` | Markdown | | |
| 69 | +| `link` | `syntax.link` | Markdown | | |
| 70 | + | |
| 71 | +## Python | |
| 72 | + | |
| 73 | +Écrit à la main, dans `internal/pythonlang`. **Seule une chaîne franchit un saut de ligne**, et de deux manières : une chaîne à triple guillemet court jusqu'aux trois guillemets correspondants, et une chaîne à guillemet simple ne continue que si la ligne se termine par une contre-oblique. Le guillemet qui l'a ouverte est reporté, car un littéral ouvert par trois guillemets doubles et un littéral ouvert par trois apostrophes sont deux chaînes différentes. | |
| 74 | + | |
| 75 | +| Reconnu | Comme | | |
| 76 | +| --- | --- | | |
| 77 | +| `and`, `as`, `assert`, `async`, `await`, `break`, `class`, `continue`, `def`, `del`, `elif`, `else`, `except`, `finally`, `for`, `from`, `global`, `if`, `import`, `in`, `is`, `lambda`, `nonlocal`, `not`, `or`, `pass`, `raise`, `return`, `try`, `while`, `with`, `yield` | mot-clé | | |
| 78 | +| `match` et `case`, lorsqu'ils ouvrent la ligne et que celle-ci se termine par `:` | mot-clé | | |
| 79 | +| `True`, `False`, `None`, `NotImplemented`, `Ellipsis`, `__debug__` | constante | | |
| 80 | +| `bool`, `bytearray`, `bytes`, `complex`, `dict`, `float`, `frozenset`, `int`, `list`, `memoryview`, `object`, `range`, `set`, `slice`, `str`, `tuple`, `type` | type | | |
| 81 | +| tout autre nom commençant par une majuscule — `ValueError`, `Measurement` | type | | |
| 82 | +| un nom écrit entièrement en majuscules — `MAX_SIZE`, `PI`, `HTTP_PORT` | constante | | |
| 83 | +| `__init__`, `__repr__`, `__name__` et tous les autres noms en double soulignement | primitive | | |
| 84 | +| `print`, `len`, `open`, `sorted`, `isinstance`, … ainsi que `self` et `cls` | primitive | | |
| 85 | +| tout autre nom immédiatement suivi de `(` | fonction | | |
| 86 | +| `"…"` et `'…'`, avec n'importe quel préfixe : `r`, `b`, `u`, `f`, `rb`, `br`, `fr`, `rf`, dans les deux casses | chaîne | | |
| 87 | +| `"""…"""` et `'''…'''`, sur autant de lignes qu'il faut | chaîne | | |
| 88 | +| une chaîne à guillemet simple dont la ligne finit par une contre-oblique, sur la ligne suivante | chaîne | | |
| 89 | +| `42`, `1_000`, `0xFF`, `0o17`, `0b1010`, `.5`, `1.`, `1.5e-3`, `1E+7`, `3j` | nombre | | |
| 90 | +| `#` jusqu'à la fin de la ligne, shebang compris | commentaire | | |
| 91 | +| `@property`, `@app.route`, `@pytest.mark.parametrize` — le nom seulement | attribut | | |
| 92 | +| `:=` | opérateur | | |
| 93 | +| `:` partout ailleurs — un bloc, une tranche, un dictionnaire, une annotation | ponctuation | | |
| 94 | +| `@` ailleurs qu'en début de ligne | opérateur | | |
| 95 | +| une `\` en fin de ligne | ponctuation | | |
| 96 | +| suites de `+-*/%=<>!&\|^~?` | opérateur | | |
| 97 | +| `()[]{},;.` | ponctuation | | |
| 98 | + | |
| 99 | +**`match` et `case` ne sont des mots-clés que là où une instruction `match` les place.** Ils ne sont réservés dans aucun contexte — `match = re.match(motif, texte)` est du Python ordinaire — c'est donc la forme de l'instruction qui décide : le mot ouvre la ligne, et la ligne se termine par le deux-points qui ouvre son bloc. Les deux conditions doivent tenir. | |
| 100 | + | |
| 101 | +**Un nom écrit entièrement en majuscules est une constante, et tout autre nom capitalisé est un type.** La PEP 8 sépare assez nettement les deux conventions pour qu'on puisse les lire : `MAX_SIZE` est une constante et `Measurement` une classe. Turbo Rust n'a que la seconde règle et documente `SCREAMING_SNAKE_CASE` comme une réponse fausse connue ; ici, cette réponse mérite d'être supprimée plutôt qu'héritée. | |
| 102 | + | |
| 103 | +**Un nom capitalisé est un type même lorsqu'il est appelé.** `ValueError("non")` et `parse("non")` ont exactement la même forme, parce qu'une classe s'appelle comme une fonction — la parenthèse ne peut donc pas les distinguer, et c'est la convention qui doit le faire. C'est la seule règle que Turbo Python et Turbo Rust ordonnent différemment. | |
| 104 | + | |
| 105 | +**`self` et `cls` sont colorés comme des primitives bien que le langage ne les nomme pas.** C'est une convention : une méthode peut appeler son premier paramètre comme elle veut. Mais tout lecteur de Python lit `self` comme appartenant au langage, de la même façon qu'un lecteur de Rust lit `Some`, et tous les autres coloriseurs font pareil. Le prix à payer : un paramètre honnêtement nommé `self` dans une fonction ordinaire est coloré lui aussi. | |
| 106 | + | |
| 107 | +**Un décorateur s'arrête à ses arguments.** `@pytest.mark.parametrize("n", [1, 2])` colore le nom pointé comme un attribut et le reste comme du Python ordinaire, si bien que la chaîne et la liste qu'il contient gardent leurs propres couleurs. | |
| 108 | + | |
| 109 | +**Une contre-oblique soustrait le caractère qui la suit, y compris dans une chaîne brute.** `r"\""` est une chaîne complète : dans une chaîne brute la contre-oblique reste dans la valeur, mais elle empêche toujours le guillemet suivant de terminer le littéral. La règle de terminaison est donc la même pour les deux, et c'est pourquoi le caractère « brut » n'est pas reporté d'une ligne à l'autre. | |
| 110 | + | |
| 111 | +**Une chaîne qui atteint la fin d'une ligne sans l'une des deux raisons de continuer s'arrête là.** Elle est colorée jusqu'au bout de cette ligne et la ligne suivante redevient du code — parce qu'une chaîne à guillemet simple sans guillemet fermant est du code en cours de frappe, et que la reporter peindrait tout le reste du fichier. | |
| 112 | + | |
| 113 | +**Non reconnu**, chaque fois pour une raison énoncée : | |
| 114 | + | |
| 115 | +| Non reconnu | Parce que | | |
| 116 | +| --- | --- | | |
| 117 | +| L'`{expression}` à l'intérieur d'une f-string | Depuis Python 3.12 elle peut contenir n'importe quoi — guillemets imbriqués, commentaires, une autre f-string. Une seule plage de chaîne est la réponse honnête ; la colorer à moitié terminerait `f"{n:{width}}"` sur l'accolade intérieure | | |
| 118 | +| `match` ou `case` sur une ligne portant un commentaire de fin | Le deux-points est cherché en remontant depuis la fin de la ligne, et un commentaire le masque : `match value: # aiguillage` colore donc `match` comme un nom. C'est le bon sens de l'erreur | | |
| 119 | +| Une docstring comme autre chose qu'une chaîne | C'en *est* une — `help()` la relit comme telle — et la colorer en commentaire serait faux dès qu'on en affecte une à un nom | | |
| 120 | +| Une classe dont le nom est tout en majuscules | `HTTP` est coloré comme une constante. C'est le prix de `MAX_SIZE` correctement coloré, et l'arbitrage suit le cas le plus fréquent | | |
| 121 | +| `type` comme mot-clé souple de `type Alias = int` | C'est aussi un type primitif, et le lire comme le type est juste dans ses deux emplois | | |
| 122 | +| Si un nom est lié dans cette portée | Rien ici ne lit plus d'une ligne à la fois ; c'est la question du serveur de langage, et [F1 y répond](../how-to/ask-about-code.md) | | |
| 123 | + | |
| 124 | +## TOML | |
| 125 | + | |
| 126 | +| Reconnu | Comme | | |
| 127 | +| --- | --- | | |
| 128 | +| `# commentaire` | comment | | |
| 129 | +| `[table]`, `[[array]]` | le nom en type, les crochets en punctuation | | |
| 130 | +| `clé =` | identifier, puis operator | | |
| 131 | +| `"basique"`, `'littérale'`, `"""multi-ligne"""`, `'''multi-ligne'''` | string | | |
| 132 | +| `true`, `false` | constant | | |
| 133 | +| nombres, dates, heures, `inf`, `nan` | number | | |
| 134 | + | |
| 135 | +## YAML | |
| 136 | + | |
| 137 | +Un fichier compose, un manifeste Kubernetes et un workflow d'intégration continue sont tous cela : il n'y a pas de dialecte séparé, parce qu'un dialecte serait le schéma de quelqu'un d'autre à maintenir en phase. | |
| 138 | + | |
| 139 | +| Reconnu | Comme | | |
| 140 | +| --- | --- | | |
| 141 | +| `# commentaire` | commentaire | | |
| 142 | +| `clé:` suivie d'une espace ou de la fin de ligne | la clé en identifiant, le deux-points en ponctuation | | |
| 143 | +| `"entre guillemets": 1`, `'apostrophes': 1` | la clé citée en identifiant | | |
| 144 | +| `- ` ouvrant une entrée de séquence | ponctuation | | |
| 145 | +| `"…"`, `'…'` | chaîne | | |
| 146 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constante, quelle que soit la casse | | |
| 147 | +| nombres, dates et heures écrits sans guillemets | nombre | | |
| 148 | +| `&ancre`, `*alias` | builtin | | |
| 149 | +| `!!str`, `!Custom` | type | | |
| 150 | +| `---`, `...` | toute la ligne en ponctuation | | |
| 151 | +| `{`, `}`, `[`, `]`, `,` | ponctuation | | |
| 152 | +| `\|`, `>`, avec leurs indicateurs de coupe et d'indentation | l'en-tête en opérateur, le corps en chaîne | | |
| 153 | + | |
| 154 | +**Un deux-points n'est un séparateur que si une espace ou la fin de ligne le suit.** `image: nginx:1.27` est une clé et une seule valeur, et `url: http://example.com/x` une clé et une seule URL — colorer les deux-points intérieurs en séparateurs mettrait chaque étiquette d'image et chaque URL en trois couleurs. | |
| 155 | + | |
| 156 | +**L'étendue d'un scalaire de bloc est décidée par l'indentation**, pas par un délimiteur. La première ligne de contenu après `|` ou `>` fixe l'indentation du bloc ; toute ligne indentée au moins autant lui appartient, et la première qui ne l'est pas y met fin. **Une ligne vide à l'intérieur d'un bloc y reste** : un scalaire littéral conserve ses lignes vides, et terminer le bloc au premier saut de paragraphe couperait en deux un script shell dans un fichier d'intégration continue. | |
| 157 | + | |
| 158 | +**Un `#` a besoin d'une espace devant lui pour ouvrir un commentaire**, si bien que `colour: ff#00aa` est un seul scalaire. | |
| 159 | + | |
| 160 | +| Non reconnu | Parce que | | |
| 161 | +| --- | --- | | |
| 162 | +| Le schéma d'un fichier compose, d'un manifeste ou d'un workflow | Colorer `services:` autrement qu'une clé quelconque revient à transporter le schéma de quelqu'un d'autre, qui se périme le jour où il ajoute une clé | | |
| 163 | +| Les flux multi-documents comme documents distincts | `---` est coloré, mais rien n'est réinitialisé à cet endroit ; rien dans la coloration ne dépend des frontières de documents | | |
| 164 | +| Si un mot nu est une chaîne ou un nombre pour un analyseur | `1.2.3` est une version pour un lecteur et une chaîne pour YAML ; l'analyseur colore ce à quoi cela ressemble | | |
| 165 | + | |
| 166 | +## Markdown | |
| 167 | + | |
| 168 | +| Reconnu | Comme | | |
| 169 | +| --- | --- | | |
| 170 | +| `# Titre` … `###### Titre` | toute la ligne en heading | | |
| 171 | +| `**gras**`, `__gras__`, `*italique*`, `_italique_` | emphasis | | |
| 172 | +| `` `code` `` | string | | |
| 173 | +| `[texte](cible)`, `` | l'ensemble en link | | |
| 174 | +| `- `, `* `, `+ `, `1. `, `1) ` | le marqueur en punctuation | | |
| 175 | +| `>` | punctuation | | |
| 176 | +| `---`, `***`, `___` | punctuation | | |
| 177 | +| clôtures ` ``` ` et `~~~` | tout le bloc, lignes d'ouverture et de fermeture comprises, en string | | |
| 178 | + | |
| 179 | +Un bloc clôturé est **d'une seule couleur quel que soit le langage annoncé** : ```` ```python ```` ne colore pas son contenu en Python. La suite de marqueurs qui ouvre un bloc doit être fermée par le même caractère : une clôture en accents graves ne se ferme pas par des tildes. Une clôture non fermée colore jusqu'à la fin du fichier. | |
| 180 | + | |
| 181 | +La suite de marqueurs qui ouvre une emphase doit être fermée par une suite de même longueur, de sorte que `**gras**` fasse un seul span et non deux italiques. | |
| 182 | + | |
| 183 | +## JavaScript | |
| 184 | + | |
| 185 | +| Reconnu | Comme | | |
| 186 | +| --- | --- | | |
| 187 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | |
| 188 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | |
| 189 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | |
| 190 | +| un nom immédiatement suivi de `(` | function | | |
| 191 | +| `"…"`, `'…'` | string | | |
| 192 | +| `` `…` ``, interpolations comprises, sur plusieurs lignes | string | | |
| 193 | +| `//` jusqu'à la fin de la ligne, `/* … */` sur plusieurs lignes | comment | | |
| 194 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | |
| 195 | +| suites de `+-*/%=<>!&|^~?:` | operator | | |
| 196 | +| `()[]{},;.` | punctuation | | |
| 197 | + | |
| 198 | +**Les littéraux d'expression régulière ne sont pas reconnus.** Distinguer `/x/g` d'une division exige de savoir si le token précédent pouvait terminer une expression ; une mauvaise supposition colore le reste de la ligne comme une chaîne, ce qui est pire que de laisser une regex à la couleur d'un opérateur. | |
| 199 | + | |
| 200 | +Les globales sont reconnues par leur nom : un fichier qui masque `Math` la voit quand même colorée comme un builtin — la même règle que les types primitifs de Python. | |
| 201 | + | |
| 202 | +## HTML | |
| 203 | + | |
| 204 | +| Reconnu | Comme | | |
| 205 | +| --- | --- | | |
| 206 | +| `<balise`, `</balise`, `>`, `/>` | tag | | |
| 207 | +| noms d'attributs, dont `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | |
| 208 | +| `=` | operator | | |
| 209 | +| `"…"`, `'…'` | string | | |
| 210 | +| `<!-- … -->`, sur plusieurs lignes | comment | | |
| 211 | +| `&`, `©` | constant | | |
| 212 | +| `<!DOCTYPE …>` et les autres déclarations | keyword | | |
| 213 | + | |
| 214 | +Le texte entre balises n'est pas coloré. Une esperluette isolée sans `;` dans les 32 caractères qui suivent est laissée telle quelle, parce que c'est du texte légal. | |
| 215 | + | |
| 216 | +**Le contenu de `<script>` et de `<style>` n'est pas coloré** en JavaScript ni en CSS. | |
| 217 | + | |
| 218 | +## XML | |
| 219 | + | |
| 220 | +Son propre analyseur plutôt que celui du HTML, pour une raison qui compte : CDATA. Tout l'intérêt de `<![CDATA[ … ]]>` est que son contenu n'est *pas* du balisage, et colorer les balises qu'il contient comme des balises est exactement l'inverse. | |
| 221 | + | |
| 222 | +| Reconnu | Comme | | |
| 223 | +| --- | --- | | |
| 224 | +| `<?xml version="1.0"?>` et les autres instructions de traitement | la cible et `?>` en mot-clé, les paires entre les deux en attributs et chaînes | | |
| 225 | +| `<!DOCTYPE …>` et les autres formes `<!` | mot-clé | | |
| 226 | +| `<!-- … -->`, sur plusieurs lignes | commentaire | | |
| 227 | +| `<![CDATA[ … ]]>`, sur plusieurs lignes | chaîne | | |
| 228 | +| `<balise`, `</balise`, `>`, `/>` | balise | | |
| 229 | +| `<ns:balise>`, `xsi:type` | le préfixe et le nom local en **un seul** segment | | |
| 230 | +| les noms d'attributs | attribut | | |
| 231 | +| `=` | opérateur | | |
| 232 | +| `"…"`, `'…'` | chaîne | | |
| 233 | +| `&`, `©` | constante | | |
| 234 | + | |
| 235 | +**Un commentaire et une section CDATA se ferment sur des délimiteurs différents**, et sont transportés séparément : un `-->` à l'intérieur d'une section CDATA n'y met pas fin. | |
| 236 | + | |
| 237 | +**Une esperluette isolée sans point-virgule dans les 32 caractères suivants est laissée telle quelle**, parce que c'est du texte légal dans bien des documents et qu'avaler le reste de la ligne serait la plus grosse erreur. | |
| 238 | + | |
| 239 | +Le texte entre balises n'est pas coloré. | |
| 240 | + | |
| 241 | +## Shell | |
| 242 | + | |
| 243 | +S'applique indifféremment à `sh`, `bash` et `zsh` : les mots-clés reconnus sont ceux qu'ils partagent. | |
| 244 | + | |
| 245 | +| Reconnu | Comme | | |
| 246 | +| --- | --- | | |
| 247 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | |
| 248 | +| `true`, `false` | constant | | |
| 249 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | |
| 250 | +| `$NOM`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | |
| 251 | +| le **premier mot nu d'une ligne** | function | | |
| 252 | +| tout mot nu suivant, et `NOM` dans `NOM=valeur` | identifier | | |
| 253 | +| `'…'`, sans échappement ni expansion à l'intérieur | string | | |
| 254 | +| `"…"`, avec les expansions colorées comme telles | string | | |
| 255 | +| `#` jusqu'à la fin de la ligne | comment | | |
| 256 | + | |
| 257 | +`$(a $(b) c)` fait un seul span : l'imbrication est comptée. Une option comme `-euo` est un seul mot, et non un moins suivi d'un mot. | |
| 258 | + | |
| 259 | +**Les heredocs ne sont pas reconnus.** `<<EOF` et le texte qui suit sont colorés comme du shell ordinaire. | |
| 260 | + | |
| 261 | +## Dockerfile | |
| 262 | + | |
| 263 | +| Reconnu | Comme | | |
| 264 | +| --- | --- | | |
| 265 | +| `FROM`, `RUN`, `COPY`, `ADD`, `ARG`, `ENV`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `LABEL`, `USER`, `VOLUME`, `WORKDIR`, `HEALTHCHECK`, `ONBUILD`, `SHELL`, `STOPSIGNAL`, `MAINTAINER` | mot-clé, quelle que soit la casse | | |
| 266 | +| `AS`, `NONE` | mot-clé | | |
| 267 | +| `# commentaire`, y compris les directives `# syntax=` et `# escape=` | commentaire | | |
| 268 | +| `--from=builder`, `--chown=me:me` | le nom de l'option en attribut | | |
| 269 | +| `$NOM`, `${NOM}`, `${NOM:-defaut}` | builtin, en un seul segment jusqu'à l'accolade fermante | | |
| 270 | +| `"…"`, `'…'` | chaîne | | |
| 271 | +| un `\` final | opérateur | | |
| 272 | +| les nombres | nombre | | |
| 273 | +| chemins et références d'images — `/usr/local/bin`, `golang:1.26-alpine` | identifiant, en **un seul** segment | | |
| 274 | + | |
| 275 | +**Seul le premier mot d'une ligne peut être une instruction**, et un mot qui n'en est pas une est un argument — ce qui garde le premier mot d'une ligne de continuation hors de la couleur des mots-clés. | |
| 276 | + | |
| 277 | +**Rien ne traverse un saut de ligne.** Un `\` joint deux lignes pour Docker, mais chaque moitié se lit encore comme une commande et est colorée pour elle-même. | |
| 278 | + | |
| 279 | +| Non reconnu | Parce que | | |
| 280 | +| --- | --- | | |
| 281 | +| Le shell à l'intérieur d'un `RUN` | Il faudrait passer l'analyseur shell sur une partie de ligne et en remonter les colonnes, et un `RUN` peut contenir n'importe quel langage | | |
| 282 | +| Les heredocs dans un `RUN` | La même raison que pour l'analyseur shell | | |
| 283 | +| Quelle étape nomme un `--from` | Rien ici ne lit le reste du fichier | | |
| 284 | + | |
| 285 | +## Voir aussi | |
| 286 | + | |
| 287 | +- [Format des fichiers de thème](themes.md) — toutes les clés vers lesquelles ces classes se résolvent | |
| 288 | +- [Coloration et complétion](../explanation/colouring-and-completion.md) — pourquoi les scanners sont écrits ainsi | |
| 289 | +- [Écrire son propre thème](../how-to/write-a-theme.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,289 @@ | |||
| 1 | +# Référence : langages colorés | ||
| 2 | + | ||
| 3 | +> Description neutre des fichiers que Turbo Python colore, de la façon dont il décide, et de ce que reconnaît chaque scanner. | ||
| 4 | + | ||
| 5 | +## Reconnaissance | ||
| 6 | + | ||
| 7 | +L'**extension** d'un fichier décide dès qu'elle fait partie de celles-ci : | ||
| 8 | + | ||
| 9 | +| Extension | Langage | | ||
| 10 | +| --- | --- | | ||
| 11 | +| `.py`, `.pyi`, `.pyw` | Python | | ||
| 12 | +| `.toml` | TOML | | ||
| 13 | +| `.yaml`, `.yml` | YAML | | ||
| 14 | +| `.md`, `.markdown` | Markdown | | ||
| 15 | +| `.js`, `.mjs`, `.cjs` | JavaScript | | ||
| 16 | +| `.html`, `.htm` | HTML | | ||
| 17 | +| `.xml`, `.xsd`, `.xsl`, `.xslt`, `.svg`, `.plist`, `.csproj`, `.pom` | XML | | ||
| 18 | +| `.sh`, `.bash`, `.zsh` | Shell | | ||
| 19 | +| `.dockerfile`, `.containerfile` | Dockerfile | | ||
| 20 | + | ||
| 21 | +Les extensions sont comparées sans tenir compte de la casse, et seule la dernière compte : `main.py.backup` n'est pas du Python. | ||
| 22 | + | ||
| 23 | +Un fichier dont l'extension ne décide de rien est ensuite cherché par son **nom**. Seuls les fichiers sans extension exploitable en ont besoin : | ||
| 24 | + | ||
| 25 | +| Nom | Langage | | ||
| 26 | +| --- | --- | | ||
| 27 | +| `Dockerfile`, `Containerfile` | Dockerfile | | ||
| 28 | + | ||
| 29 | +Un nom correspond sur sa totalité ou sur la partie précédant le premier point, sans tenir compte de la casse — ainsi `Dockerfile`, `dockerfile` et `Dockerfile.dev` sont tous reconnus, tandis que `Dockerfile.md` est du Markdown, puisque l'extension est consultée en premier. | ||
| 30 | + | ||
| 31 | +Un fichier qu'aucun des deux tableaux ne revendique est lu par sa **première ligne**. Un shebang nommant `python` ou `python3` en fait du Python ; un shebang nommant un shell — `sh`, `bash`, `zsh`, `dash` ou `ksh` — en fait un script shell. L'interpréteur est reconnu comme élément de chemin ou comme argument d'`env`. C'est ce qui colore un script dans un répertoire `bin`, un hook git, ou `configure`. | ||
| 32 | + | ||
| 33 | +| Première ligne | Résultat | | ||
| 34 | +| --- | --- | | ||
| 35 | +| `#!/bin/sh` | Shell | | ||
| 36 | +| `#!/usr/bin/env bash` | Shell | | ||
| 37 | +| `#!/usr/bin/env -S bash -e` | Shell | | ||
| 38 | +| `#!/usr/bin/env python3` | Python | | ||
| 39 | +| `#!/usr/bin/python` | Python | | ||
| 40 | +| `#!/usr/bin/env node` | Non coloré | | ||
| 41 | +| Tout ce qui ne commence pas par `#!` | Non coloré | | ||
| 42 | + | ||
| 43 | +L'ordre est fixe — extension, puis nom, puis première ligne — et le premier qui décide l'emporte : un fichier `.md` commençant par un shebang Python reste du Markdown. | ||
| 44 | + | ||
| 45 | +Tout le reste est affiché en texte brut. Ce n'est pas une erreur — ouvrir un PNG dans l'éditeur n'est pas une faute, c'est simplement non coloré. | ||
| 46 | + | ||
| 47 | +## Classes | ||
| 48 | + | ||
| 49 | +Tous les scanners produisent le même vocabulaire de classes, et chacune correspond à une clé de thème. | ||
| 50 | + | ||
| 51 | +| Classe | Clé de thème | Produite par | | ||
| 52 | +| --- | --- | --- | | ||
| 53 | +| `identifier` | `syntax.identifier` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 54 | +| `keyword` | `syntax.keyword` | Python, JavaScript, shell, HTML (doctype), XML, Dockerfile | | ||
| 55 | +| `type` | `syntax.type` | Python, TOML (en-têtes de table), YAML (étiquettes) | | ||
| 56 | +| `builtin` | `syntax.builtin` | Python, JavaScript, shell (builtins et expansions), YAML (ancres et alias), Dockerfile (variables) | | ||
| 57 | +| `constant` | `syntax.constant` | Python, TOML, JavaScript, shell, YAML, HTML et XML (entités) | | ||
| 58 | +| `function` | `syntax.function` | Python, JavaScript, shell (la commande) | | ||
| 59 | +| `string` | `syntax.string` | tous | | ||
| 60 | +| `char` | `syntax.char` | rien ici ; la classe existe pour les langages qui ont un type caractère, et Python n'en a pas | | ||
| 61 | +| `number` | `syntax.number` | Python, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 62 | +| `comment` | `syntax.comment` | Python, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | ||
| 63 | +| `operator` | `syntax.operator` | Python, TOML, JavaScript, shell, HTML, YAML (en-têtes de scalaire de bloc), XML, Dockerfile | | ||
| 64 | +| `punctuation` | `syntax.punctuation` | Python, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | ||
| 65 | +| `heading` | `syntax.heading` | Markdown | | ||
| 66 | +| `tag` | `syntax.tag` | HTML, XML | | ||
| 67 | +| `attribute` | `syntax.attribute` | Python (décorateurs), HTML, XML, Dockerfile (options) | | ||
| 68 | +| `emphasis` | `syntax.emphasis` | Markdown | | ||
| 69 | +| `link` | `syntax.link` | Markdown | | ||
| 70 | + | ||
| 71 | +## Python | ||
| 72 | + | ||
| 73 | +Écrit à la main, dans `internal/pythonlang`. **Seule une chaîne franchit un saut de ligne**, et de deux manières : une chaîne à triple guillemet court jusqu'aux trois guillemets correspondants, et une chaîne à guillemet simple ne continue que si la ligne se termine par une contre-oblique. Le guillemet qui l'a ouverte est reporté, car un littéral ouvert par trois guillemets doubles et un littéral ouvert par trois apostrophes sont deux chaînes différentes. | ||
| 74 | + | ||
| 75 | +| Reconnu | Comme | | ||
| 76 | +| --- | --- | | ||
| 77 | +| `and`, `as`, `assert`, `async`, `await`, `break`, `class`, `continue`, `def`, `del`, `elif`, `else`, `except`, `finally`, `for`, `from`, `global`, `if`, `import`, `in`, `is`, `lambda`, `nonlocal`, `not`, `or`, `pass`, `raise`, `return`, `try`, `while`, `with`, `yield` | mot-clé | | ||
| 78 | +| `match` et `case`, lorsqu'ils ouvrent la ligne et que celle-ci se termine par `:` | mot-clé | | ||
| 79 | +| `True`, `False`, `None`, `NotImplemented`, `Ellipsis`, `__debug__` | constante | | ||
| 80 | +| `bool`, `bytearray`, `bytes`, `complex`, `dict`, `float`, `frozenset`, `int`, `list`, `memoryview`, `object`, `range`, `set`, `slice`, `str`, `tuple`, `type` | type | | ||
| 81 | +| tout autre nom commençant par une majuscule — `ValueError`, `Measurement` | type | | ||
| 82 | +| un nom écrit entièrement en majuscules — `MAX_SIZE`, `PI`, `HTTP_PORT` | constante | | ||
| 83 | +| `__init__`, `__repr__`, `__name__` et tous les autres noms en double soulignement | primitive | | ||
| 84 | +| `print`, `len`, `open`, `sorted`, `isinstance`, … ainsi que `self` et `cls` | primitive | | ||
| 85 | +| tout autre nom immédiatement suivi de `(` | fonction | | ||
| 86 | +| `"…"` et `'…'`, avec n'importe quel préfixe : `r`, `b`, `u`, `f`, `rb`, `br`, `fr`, `rf`, dans les deux casses | chaîne | | ||
| 87 | +| `"""…"""` et `'''…'''`, sur autant de lignes qu'il faut | chaîne | | ||
| 88 | +| une chaîne à guillemet simple dont la ligne finit par une contre-oblique, sur la ligne suivante | chaîne | | ||
| 89 | +| `42`, `1_000`, `0xFF`, `0o17`, `0b1010`, `.5`, `1.`, `1.5e-3`, `1E+7`, `3j` | nombre | | ||
| 90 | +| `#` jusqu'à la fin de la ligne, shebang compris | commentaire | | ||
| 91 | +| `@property`, `@app.route`, `@pytest.mark.parametrize` — le nom seulement | attribut | | ||
| 92 | +| `:=` | opérateur | | ||
| 93 | +| `:` partout ailleurs — un bloc, une tranche, un dictionnaire, une annotation | ponctuation | | ||
| 94 | +| `@` ailleurs qu'en début de ligne | opérateur | | ||
| 95 | +| une `\` en fin de ligne | ponctuation | | ||
| 96 | +| suites de `+-*/%=<>!&\|^~?` | opérateur | | ||
| 97 | +| `()[]{},;.` | ponctuation | | ||
| 98 | + | ||
| 99 | +**`match` et `case` ne sont des mots-clés que là où une instruction `match` les place.** Ils ne sont réservés dans aucun contexte — `match = re.match(motif, texte)` est du Python ordinaire — c'est donc la forme de l'instruction qui décide : le mot ouvre la ligne, et la ligne se termine par le deux-points qui ouvre son bloc. Les deux conditions doivent tenir. | ||
| 100 | + | ||
| 101 | +**Un nom écrit entièrement en majuscules est une constante, et tout autre nom capitalisé est un type.** La PEP 8 sépare assez nettement les deux conventions pour qu'on puisse les lire : `MAX_SIZE` est une constante et `Measurement` une classe. Turbo Rust n'a que la seconde règle et documente `SCREAMING_SNAKE_CASE` comme une réponse fausse connue ; ici, cette réponse mérite d'être supprimée plutôt qu'héritée. | ||
| 102 | + | ||
| 103 | +**Un nom capitalisé est un type même lorsqu'il est appelé.** `ValueError("non")` et `parse("non")` ont exactement la même forme, parce qu'une classe s'appelle comme une fonction — la parenthèse ne peut donc pas les distinguer, et c'est la convention qui doit le faire. C'est la seule règle que Turbo Python et Turbo Rust ordonnent différemment. | ||
| 104 | + | ||
| 105 | +**`self` et `cls` sont colorés comme des primitives bien que le langage ne les nomme pas.** C'est une convention : une méthode peut appeler son premier paramètre comme elle veut. Mais tout lecteur de Python lit `self` comme appartenant au langage, de la même façon qu'un lecteur de Rust lit `Some`, et tous les autres coloriseurs font pareil. Le prix à payer : un paramètre honnêtement nommé `self` dans une fonction ordinaire est coloré lui aussi. | ||
| 106 | + | ||
| 107 | +**Un décorateur s'arrête à ses arguments.** `@pytest.mark.parametrize("n", [1, 2])` colore le nom pointé comme un attribut et le reste comme du Python ordinaire, si bien que la chaîne et la liste qu'il contient gardent leurs propres couleurs. | ||
| 108 | + | ||
| 109 | +**Une contre-oblique soustrait le caractère qui la suit, y compris dans une chaîne brute.** `r"\""` est une chaîne complète : dans une chaîne brute la contre-oblique reste dans la valeur, mais elle empêche toujours le guillemet suivant de terminer le littéral. La règle de terminaison est donc la même pour les deux, et c'est pourquoi le caractère « brut » n'est pas reporté d'une ligne à l'autre. | ||
| 110 | + | ||
| 111 | +**Une chaîne qui atteint la fin d'une ligne sans l'une des deux raisons de continuer s'arrête là.** Elle est colorée jusqu'au bout de cette ligne et la ligne suivante redevient du code — parce qu'une chaîne à guillemet simple sans guillemet fermant est du code en cours de frappe, et que la reporter peindrait tout le reste du fichier. | ||
| 112 | + | ||
| 113 | +**Non reconnu**, chaque fois pour une raison énoncée : | ||
| 114 | + | ||
| 115 | +| Non reconnu | Parce que | | ||
| 116 | +| --- | --- | | ||
| 117 | +| L'`{expression}` à l'intérieur d'une f-string | Depuis Python 3.12 elle peut contenir n'importe quoi — guillemets imbriqués, commentaires, une autre f-string. Une seule plage de chaîne est la réponse honnête ; la colorer à moitié terminerait `f"{n:{width}}"` sur l'accolade intérieure | | ||
| 118 | +| `match` ou `case` sur une ligne portant un commentaire de fin | Le deux-points est cherché en remontant depuis la fin de la ligne, et un commentaire le masque : `match value: # aiguillage` colore donc `match` comme un nom. C'est le bon sens de l'erreur | | ||
| 119 | +| Une docstring comme autre chose qu'une chaîne | C'en *est* une — `help()` la relit comme telle — et la colorer en commentaire serait faux dès qu'on en affecte une à un nom | | ||
| 120 | +| Une classe dont le nom est tout en majuscules | `HTTP` est coloré comme une constante. C'est le prix de `MAX_SIZE` correctement coloré, et l'arbitrage suit le cas le plus fréquent | | ||
| 121 | +| `type` comme mot-clé souple de `type Alias = int` | C'est aussi un type primitif, et le lire comme le type est juste dans ses deux emplois | | ||
| 122 | +| Si un nom est lié dans cette portée | Rien ici ne lit plus d'une ligne à la fois ; c'est la question du serveur de langage, et [F1 y répond](../how-to/ask-about-code.md) | | ||
| 123 | + | ||
| 124 | +## TOML | ||
| 125 | + | ||
| 126 | +| Reconnu | Comme | | ||
| 127 | +| --- | --- | | ||
| 128 | +| `# commentaire` | comment | | ||
| 129 | +| `[table]`, `[[array]]` | le nom en type, les crochets en punctuation | | ||
| 130 | +| `clé =` | identifier, puis operator | | ||
| 131 | +| `"basique"`, `'littérale'`, `"""multi-ligne"""`, `'''multi-ligne'''` | string | | ||
| 132 | +| `true`, `false` | constant | | ||
| 133 | +| nombres, dates, heures, `inf`, `nan` | number | | ||
| 134 | + | ||
| 135 | +## YAML | ||
| 136 | + | ||
| 137 | +Un fichier compose, un manifeste Kubernetes et un workflow d'intégration continue sont tous cela : il n'y a pas de dialecte séparé, parce qu'un dialecte serait le schéma de quelqu'un d'autre à maintenir en phase. | ||
| 138 | + | ||
| 139 | +| Reconnu | Comme | | ||
| 140 | +| --- | --- | | ||
| 141 | +| `# commentaire` | commentaire | | ||
| 142 | +| `clé:` suivie d'une espace ou de la fin de ligne | la clé en identifiant, le deux-points en ponctuation | | ||
| 143 | +| `"entre guillemets": 1`, `'apostrophes': 1` | la clé citée en identifiant | | ||
| 144 | +| `- ` ouvrant une entrée de séquence | ponctuation | | ||
| 145 | +| `"…"`, `'…'` | chaîne | | ||
| 146 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constante, quelle que soit la casse | | ||
| 147 | +| nombres, dates et heures écrits sans guillemets | nombre | | ||
| 148 | +| `&ancre`, `*alias` | builtin | | ||
| 149 | +| `!!str`, `!Custom` | type | | ||
| 150 | +| `---`, `...` | toute la ligne en ponctuation | | ||
| 151 | +| `{`, `}`, `[`, `]`, `,` | ponctuation | | ||
| 152 | +| `\|`, `>`, avec leurs indicateurs de coupe et d'indentation | l'en-tête en opérateur, le corps en chaîne | | ||
| 153 | + | ||
| 154 | +**Un deux-points n'est un séparateur que si une espace ou la fin de ligne le suit.** `image: nginx:1.27` est une clé et une seule valeur, et `url: http://example.com/x` une clé et une seule URL — colorer les deux-points intérieurs en séparateurs mettrait chaque étiquette d'image et chaque URL en trois couleurs. | ||
| 155 | + | ||
| 156 | +**L'étendue d'un scalaire de bloc est décidée par l'indentation**, pas par un délimiteur. La première ligne de contenu après `|` ou `>` fixe l'indentation du bloc ; toute ligne indentée au moins autant lui appartient, et la première qui ne l'est pas y met fin. **Une ligne vide à l'intérieur d'un bloc y reste** : un scalaire littéral conserve ses lignes vides, et terminer le bloc au premier saut de paragraphe couperait en deux un script shell dans un fichier d'intégration continue. | ||
| 157 | + | ||
| 158 | +**Un `#` a besoin d'une espace devant lui pour ouvrir un commentaire**, si bien que `colour: ff#00aa` est un seul scalaire. | ||
| 159 | + | ||
| 160 | +| Non reconnu | Parce que | | ||
| 161 | +| --- | --- | | ||
| 162 | +| Le schéma d'un fichier compose, d'un manifeste ou d'un workflow | Colorer `services:` autrement qu'une clé quelconque revient à transporter le schéma de quelqu'un d'autre, qui se périme le jour où il ajoute une clé | | ||
| 163 | +| Les flux multi-documents comme documents distincts | `---` est coloré, mais rien n'est réinitialisé à cet endroit ; rien dans la coloration ne dépend des frontières de documents | | ||
| 164 | +| Si un mot nu est une chaîne ou un nombre pour un analyseur | `1.2.3` est une version pour un lecteur et une chaîne pour YAML ; l'analyseur colore ce à quoi cela ressemble | | ||
| 165 | + | ||
| 166 | +## Markdown | ||
| 167 | + | ||
| 168 | +| Reconnu | Comme | | ||
| 169 | +| --- | --- | | ||
| 170 | +| `# Titre` … `###### Titre` | toute la ligne en heading | | ||
| 171 | +| `**gras**`, `__gras__`, `*italique*`, `_italique_` | emphasis | | ||
| 172 | +| `` `code` `` | string | | ||
| 173 | +| `[texte](cible)`, `` | l'ensemble en link | | ||
| 174 | +| `- `, `* `, `+ `, `1. `, `1) ` | le marqueur en punctuation | | ||
| 175 | +| `>` | punctuation | | ||
| 176 | +| `---`, `***`, `___` | punctuation | | ||
| 177 | +| clôtures ` ``` ` et `~~~` | tout le bloc, lignes d'ouverture et de fermeture comprises, en string | | ||
| 178 | + | ||
| 179 | +Un bloc clôturé est **d'une seule couleur quel que soit le langage annoncé** : ```` ```python ```` ne colore pas son contenu en Python. La suite de marqueurs qui ouvre un bloc doit être fermée par le même caractère : une clôture en accents graves ne se ferme pas par des tildes. Une clôture non fermée colore jusqu'à la fin du fichier. | ||
| 180 | + | ||
| 181 | +La suite de marqueurs qui ouvre une emphase doit être fermée par une suite de même longueur, de sorte que `**gras**` fasse un seul span et non deux italiques. | ||
| 182 | + | ||
| 183 | +## JavaScript | ||
| 184 | + | ||
| 185 | +| Reconnu | Comme | | ||
| 186 | +| --- | --- | | ||
| 187 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | ||
| 188 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | ||
| 189 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | ||
| 190 | +| un nom immédiatement suivi de `(` | function | | ||
| 191 | +| `"…"`, `'…'` | string | | ||
| 192 | +| `` `…` ``, interpolations comprises, sur plusieurs lignes | string | | ||
| 193 | +| `//` jusqu'à la fin de la ligne, `/* … */` sur plusieurs lignes | comment | | ||
| 194 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | ||
| 195 | +| suites de `+-*/%=<>!&|^~?:` | operator | | ||
| 196 | +| `()[]{},;.` | punctuation | | ||
| 197 | + | ||
| 198 | +**Les littéraux d'expression régulière ne sont pas reconnus.** Distinguer `/x/g` d'une division exige de savoir si le token précédent pouvait terminer une expression ; une mauvaise supposition colore le reste de la ligne comme une chaîne, ce qui est pire que de laisser une regex à la couleur d'un opérateur. | ||
| 199 | + | ||
| 200 | +Les globales sont reconnues par leur nom : un fichier qui masque `Math` la voit quand même colorée comme un builtin — la même règle que les types primitifs de Python. | ||
| 201 | + | ||
| 202 | +## HTML | ||
| 203 | + | ||
| 204 | +| Reconnu | Comme | | ||
| 205 | +| --- | --- | | ||
| 206 | +| `<balise`, `</balise`, `>`, `/>` | tag | | ||
| 207 | +| noms d'attributs, dont `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | ||
| 208 | +| `=` | operator | | ||
| 209 | +| `"…"`, `'…'` | string | | ||
| 210 | +| `<!-- … -->`, sur plusieurs lignes | comment | | ||
| 211 | +| `&`, `©` | constant | | ||
| 212 | +| `<!DOCTYPE …>` et les autres déclarations | keyword | | ||
| 213 | + | ||
| 214 | +Le texte entre balises n'est pas coloré. Une esperluette isolée sans `;` dans les 32 caractères qui suivent est laissée telle quelle, parce que c'est du texte légal. | ||
| 215 | + | ||
| 216 | +**Le contenu de `<script>` et de `<style>` n'est pas coloré** en JavaScript ni en CSS. | ||
| 217 | + | ||
| 218 | +## XML | ||
| 219 | + | ||
| 220 | +Son propre analyseur plutôt que celui du HTML, pour une raison qui compte : CDATA. Tout l'intérêt de `<![CDATA[ … ]]>` est que son contenu n'est *pas* du balisage, et colorer les balises qu'il contient comme des balises est exactement l'inverse. | ||
| 221 | + | ||
| 222 | +| Reconnu | Comme | | ||
| 223 | +| --- | --- | | ||
| 224 | +| `<?xml version="1.0"?>` et les autres instructions de traitement | la cible et `?>` en mot-clé, les paires entre les deux en attributs et chaînes | | ||
| 225 | +| `<!DOCTYPE …>` et les autres formes `<!` | mot-clé | | ||
| 226 | +| `<!-- … -->`, sur plusieurs lignes | commentaire | | ||
| 227 | +| `<![CDATA[ … ]]>`, sur plusieurs lignes | chaîne | | ||
| 228 | +| `<balise`, `</balise`, `>`, `/>` | balise | | ||
| 229 | +| `<ns:balise>`, `xsi:type` | le préfixe et le nom local en **un seul** segment | | ||
| 230 | +| les noms d'attributs | attribut | | ||
| 231 | +| `=` | opérateur | | ||
| 232 | +| `"…"`, `'…'` | chaîne | | ||
| 233 | +| `&`, `©` | constante | | ||
| 234 | + | ||
| 235 | +**Un commentaire et une section CDATA se ferment sur des délimiteurs différents**, et sont transportés séparément : un `-->` à l'intérieur d'une section CDATA n'y met pas fin. | ||
| 236 | + | ||
| 237 | +**Une esperluette isolée sans point-virgule dans les 32 caractères suivants est laissée telle quelle**, parce que c'est du texte légal dans bien des documents et qu'avaler le reste de la ligne serait la plus grosse erreur. | ||
| 238 | + | ||
| 239 | +Le texte entre balises n'est pas coloré. | ||
| 240 | + | ||
| 241 | +## Shell | ||
| 242 | + | ||
| 243 | +S'applique indifféremment à `sh`, `bash` et `zsh` : les mots-clés reconnus sont ceux qu'ils partagent. | ||
| 244 | + | ||
| 245 | +| Reconnu | Comme | | ||
| 246 | +| --- | --- | | ||
| 247 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | ||
| 248 | +| `true`, `false` | constant | | ||
| 249 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | ||
| 250 | +| `$NOM`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | ||
| 251 | +| le **premier mot nu d'une ligne** | function | | ||
| 252 | +| tout mot nu suivant, et `NOM` dans `NOM=valeur` | identifier | | ||
| 253 | +| `'…'`, sans échappement ni expansion à l'intérieur | string | | ||
| 254 | +| `"…"`, avec les expansions colorées comme telles | string | | ||
| 255 | +| `#` jusqu'à la fin de la ligne | comment | | ||
| 256 | + | ||
| 257 | +`$(a $(b) c)` fait un seul span : l'imbrication est comptée. Une option comme `-euo` est un seul mot, et non un moins suivi d'un mot. | ||
| 258 | + | ||
| 259 | +**Les heredocs ne sont pas reconnus.** `<<EOF` et le texte qui suit sont colorés comme du shell ordinaire. | ||
| 260 | + | ||
| 261 | +## Dockerfile | ||
| 262 | + | ||
| 263 | +| Reconnu | Comme | | ||
| 264 | +| --- | --- | | ||
| 265 | +| `FROM`, `RUN`, `COPY`, `ADD`, `ARG`, `ENV`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `LABEL`, `USER`, `VOLUME`, `WORKDIR`, `HEALTHCHECK`, `ONBUILD`, `SHELL`, `STOPSIGNAL`, `MAINTAINER` | mot-clé, quelle que soit la casse | | ||
| 266 | +| `AS`, `NONE` | mot-clé | | ||
| 267 | +| `# commentaire`, y compris les directives `# syntax=` et `# escape=` | commentaire | | ||
| 268 | +| `--from=builder`, `--chown=me:me` | le nom de l'option en attribut | | ||
| 269 | +| `$NOM`, `${NOM}`, `${NOM:-defaut}` | builtin, en un seul segment jusqu'à l'accolade fermante | | ||
| 270 | +| `"…"`, `'…'` | chaîne | | ||
| 271 | +| un `\` final | opérateur | | ||
| 272 | +| les nombres | nombre | | ||
| 273 | +| chemins et références d'images — `/usr/local/bin`, `golang:1.26-alpine` | identifiant, en **un seul** segment | | ||
| 274 | + | ||
| 275 | +**Seul le premier mot d'une ligne peut être une instruction**, et un mot qui n'en est pas une est un argument — ce qui garde le premier mot d'une ligne de continuation hors de la couleur des mots-clés. | ||
| 276 | + | ||
| 277 | +**Rien ne traverse un saut de ligne.** Un `\` joint deux lignes pour Docker, mais chaque moitié se lit encore comme une commande et est colorée pour elle-même. | ||
| 278 | + | ||
| 279 | +| Non reconnu | Parce que | | ||
| 280 | +| --- | --- | | ||
| 281 | +| Le shell à l'intérieur d'un `RUN` | Il faudrait passer l'analyseur shell sur une partie de ligne et en remonter les colonnes, et un `RUN` peut contenir n'importe quel langage | | ||
| 282 | +| Les heredocs dans un `RUN` | La même raison que pour l'analyseur shell | | ||
| 283 | +| Quelle étape nomme un `--from` | Rien ici ne lit le reste du fichier | | ||
| 284 | + | ||
| 285 | +## Voir aussi | ||
| 286 | + | ||
| 287 | +- [Format des fichiers de thème](themes.md) — toutes les clés vers lesquelles ces classes se résolvent | ||
| 288 | +- [Coloration et complétion](../explanation/colouring-and-completion.md) — pourquoi les scanners sont écrits ainsi | ||
| 289 | +- [Écrire son propre thème](../how-to/write-a-theme.md) | ||
added
docs/fr/reference/project-settings.md +111 -0 | new file mode 100644 | ||
| @@ -0,0 +1,111 @@ | ||
| 1 | +# Référence : réglages de projet | |
| 2 | + | |
| 3 | +> Description neutre de `.turbo-python/settings.toml` : où il est cherché, ce qu'il peut contenir, et ce qui y écrit. | |
| 4 | + | |
| 5 | +## Emplacement | |
| 6 | + | |
| 7 | +| Propriété | Valeur | | |
| 8 | +| --- | --- | | |
| 9 | +| Dossier | `.turbo-python` dans le répertoire de travail de l'éditeur | | |
| 10 | +| Fichier | `.turbo-python/settings.toml` | | |
| 11 | +| Recherche | Le répertoire de travail seulement. Les dossiers parents ne sont **pas** parcourus. | | |
| 12 | +| Lecture | Au démarrage de l'éditeur, puis à chaque enregistrement du fichier depuis l'éditeur | | |
| 13 | +| Obligatoire | Non. Un projet qui n'en a pas obtient les valeurs par défaut ci-dessous. | | |
| 14 | + | |
| 15 | +## Clés | |
| 16 | + | |
| 17 | +Chaque clé est facultative, et chaque clé se trouve dans la table `[editor]`. Une clé absente garde sa valeur par défaut ; une clé présente l'emporte, y compris avec une valeur égale à la valeur par défaut. | |
| 18 | + | |
| 19 | +| Clé | Type | Défaut | Description | | |
| 20 | +| --- | --- | --- | --- | | |
| 21 | +| `theme` | chaîne | le défaut de l'éditeur (`turbo-classic`) | Nom du thème de couleurs de démarrage, tel que listé par `turbo-python -list-themes` | | |
| 22 | +| `autosave` | booléen | `false` | Si les fichiers modifiés sont écrits sans qu'on le demande. Le fichier qu'écrit **Create project settings** le met à `true` ; la valeur par défaut ici est celle qui s'applique à un projet sans fichier de réglages du tout. | | |
| 23 | +| `autosave_delay` | chaîne | `"2s"` | Combien de temps attendre après la dernière frappe. Une durée Go : `"500ms"`, `"2s"`, `"1m"`. Consultée seulement quand `autosave` vaut true. | | |
| 24 | + | |
| 25 | +### Exemple | |
| 26 | + | |
| 27 | +```toml | |
| 28 | +[editor] | |
| 29 | +theme = "turbo-dark" | |
| 30 | +autosave = true | |
| 31 | +autosave_delay = "500ms" | |
| 32 | +``` | |
| 33 | + | |
| 34 | +## Priorité du thème | |
| 35 | + | |
| 36 | +De la plus forte à la plus faible : | |
| 37 | + | |
| 38 | +| Source | L'emporte sur | | |
| 39 | +| --- | --- | | |
| 40 | +| `-theme` sur la ligne de commande | tout | | |
| 41 | +| `theme` dans le fichier de réglages | le défaut intégré | | |
| 42 | +| Le défaut intégré `turbo-classic` | — | | |
| 43 | + | |
| 44 | +Un nom de thème inconnu, à n'importe quel niveau, retombe sur le défaut intégré plutôt que d'échouer. | |
| 45 | + | |
| 46 | +## Quand un changement prend effet | |
| 47 | + | |
| 48 | +Le fichier est lu au démarrage, et **de nouveau à chaque enregistrement depuis l'éditeur** — un changement fait dans l'éditeur est donc en vigueur dès que vous appuyez sur `F2`, sans redémarrage. | |
| 49 | + | |
| 50 | +| Clé | Ré-appliquée à l'enregistrement | Pourquoi | | |
| 51 | +| --- | --- | --- | | |
| 52 | +| `autosave` | oui | | | |
| 53 | +| `autosave_delay` | oui | | | |
| 54 | +| `theme` | **non** | Options ▸ Theme est la façon vivante de le changer, et y réécrit déjà le choix. Une option `-theme` donnée en ligne de commande est l'affirmation la plus explicite pour cette session, et l'enregistrement d'un fichier ne la contredit pas. | | |
| 55 | + | |
| 56 | +| Résultat | Barre d'état | | |
| 57 | +| --- | --- | | |
| 58 | +| Lu et appliqué | `Applied .turbo-python/settings.toml — autosave on (2s)` | | |
| 59 | +| Lu et appliqué, autosave désactivée | `Applied .turbo-python/settings.toml — autosave off` | | |
| 60 | +| Enregistré, mais plus du TOML valide | `Saved, but not applied: …` — les valeurs précédentes restent en vigueur | | |
| 61 | + | |
| 62 | +Enregistrer est enregistrer, quel qu'en soit l'auteur : la sauvegarde automatique qui écrit le fichier de réglages les ré-applique exactement comme `F2`. Une modification faite **hors** de l'éditeur n'est pas remarquée ; rien ne surveille le fichier. | |
| 63 | + | |
| 64 | +## Sauvegarde automatique | |
| 65 | + | |
| 66 | +| Comportement | Détail | | |
| 67 | +| --- | --- | | |
| 68 | +| Déclencheur | Le délai écoulé sans modification dans aucune fenêtre | | |
| 69 | +| Portée | Tout fichier ouvert qui a un nom, pas seulement celui au premier plan | | |
| 70 | +| Échéance | Une seule pour tout l'éditeur, relancée par toute modification dans n'importe quelle fenêtre | | |
| 71 | +| Fichiers sans nom | Jamais enregistrés ; jamais l'objet d'une question | | |
| 72 | +| Signalement | `Saved <nom>` dans la barre d'état | | |
| 73 | +| Échec | Signalé dans la barre d'état, jamais dans un dialogue, et non réessayé avant la modification suivante | | |
| 74 | +| Fermeture d'une fenêtre | Enregistre au lieu de demander, si le fichier a un nom | | |
| 75 | +| Sortie de l'éditeur | Enregistre au lieu de demander, si le fichier a un nom | | |
| 76 | + | |
| 77 | +## Écritures | |
| 78 | + | |
| 79 | +Le fichier de réglages est écrit par exactement deux actions. Rien d'autre dans l'éditeur n'y écrit, et rien ne le crée tout seul. | |
| 80 | + | |
| 81 | +| Action | Effet | | |
| 82 | +| --- | --- | | |
| 83 | +| **Options ▸ Create project settings** | Crée `.turbo-python/settings.toml` avec le thème en cours, `autosave = true` et des commentaires explicatifs. Grisée dès que le projet en a un, elle ne peut donc pas être choisie deux fois. | | |
| 84 | +| **Options ▸ Theme** | Réécrit la valeur de `theme` **uniquement si le fichier existe déjà**. Commentaires, lignes vides, ordre des clés et commentaire de fin de la ligne du thème sont conservés. | | |
| 85 | + | |
| 86 | +Les deux écrivent via un fichier temporaire du même dossier, renommé en place : une écriture interrompue laisse le fichier précédent intact. | |
| 87 | + | |
| 88 | +## Entrées de menu | |
| 89 | + | |
| 90 | +| Entrée | Menu | Fichier requis | Effet | | |
| 91 | +| --- | --- | --- | --- | | |
| 92 | +| Create project settings | Options | refuse le fichier | Comme ci-dessus, puis ouvre le fichier. Grisée dès que le projet en a un. | | |
| 93 | +| Project settings… | Options | exige le fichier | Ouvre `.turbo-python/settings.toml`. Grisée tant que le projet n'en a pas. | | |
| 94 | + | |
| 95 | +## Erreurs | |
| 96 | + | |
| 97 | +| Message | Cause | | |
| 98 | +| --- | --- | | |
| 99 | +| `turbo-python: reading …/settings.toml: …` sur la sortie d'erreur | Le fichier est là mais n'est pas du TOML valide. L'éditeur s'ouvre avec ses valeurs par défaut. | | |
| 100 | +| `reading …: autosave_delay "x" is not a duration such as "2s"` | `autosave_delay` n'est pas une durée Go | | |
| 101 | +| `reading …: autosave_delay must be positive, not "0s"` | `autosave_delay` est nul ou négatif | | |
| 102 | +| `Already there: .turbo-python/settings.toml` dans la barre d'état | Créer dans un projet qui en a déjà un. Inatteignable depuis le menu, qui grise l'entrée ; reste possible pour un appelant qui n'est pas un menu. | | |
| 103 | +| `Saved, but not applied: …` dans la barre d'état | Le fichier de réglages a été écrit mais ne s'analyse plus. Les valeurs précédentes restent en vigueur. | | |
| 104 | +| `This project has no .turbo-python/settings.toml yet.` | **Project settings…** dans un projet qui n'en a pas | | |
| 105 | +| `Theme set for this session only: …` | Le thème a changé mais le fichier de réglages n'a pas pu être écrit | | |
| 106 | + | |
| 107 | +## Voir aussi | |
| 108 | + | |
| 109 | +- [Donner ses propres réglages à un projet](../how-to/configure-a-project.md) | |
| 110 | +- [Réglages de projet](../explanation/project-settings.md) | |
| 111 | +- [Format des fichiers de thème](themes.md) — un autre fichier, dans le même langage | |
| new file mode 100644 | |||
| @@ -0,0 +1,111 @@ | |||
| 1 | +# Référence : réglages de projet | ||
| 2 | + | ||
| 3 | +> Description neutre de `.turbo-python/settings.toml` : où il est cherché, ce qu'il peut contenir, et ce qui y écrit. | ||
| 4 | + | ||
| 5 | +## Emplacement | ||
| 6 | + | ||
| 7 | +| Propriété | Valeur | | ||
| 8 | +| --- | --- | | ||
| 9 | +| Dossier | `.turbo-python` dans le répertoire de travail de l'éditeur | | ||
| 10 | +| Fichier | `.turbo-python/settings.toml` | | ||
| 11 | +| Recherche | Le répertoire de travail seulement. Les dossiers parents ne sont **pas** parcourus. | | ||
| 12 | +| Lecture | Au démarrage de l'éditeur, puis à chaque enregistrement du fichier depuis l'éditeur | | ||
| 13 | +| Obligatoire | Non. Un projet qui n'en a pas obtient les valeurs par défaut ci-dessous. | | ||
| 14 | + | ||
| 15 | +## Clés | ||
| 16 | + | ||
| 17 | +Chaque clé est facultative, et chaque clé se trouve dans la table `[editor]`. Une clé absente garde sa valeur par défaut ; une clé présente l'emporte, y compris avec une valeur égale à la valeur par défaut. | ||
| 18 | + | ||
| 19 | +| Clé | Type | Défaut | Description | | ||
| 20 | +| --- | --- | --- | --- | | ||
| 21 | +| `theme` | chaîne | le défaut de l'éditeur (`turbo-classic`) | Nom du thème de couleurs de démarrage, tel que listé par `turbo-python -list-themes` | | ||
| 22 | +| `autosave` | booléen | `false` | Si les fichiers modifiés sont écrits sans qu'on le demande. Le fichier qu'écrit **Create project settings** le met à `true` ; la valeur par défaut ici est celle qui s'applique à un projet sans fichier de réglages du tout. | | ||
| 23 | +| `autosave_delay` | chaîne | `"2s"` | Combien de temps attendre après la dernière frappe. Une durée Go : `"500ms"`, `"2s"`, `"1m"`. Consultée seulement quand `autosave` vaut true. | | ||
| 24 | + | ||
| 25 | +### Exemple | ||
| 26 | + | ||
| 27 | +```toml | ||
| 28 | +[editor] | ||
| 29 | +theme = "turbo-dark" | ||
| 30 | +autosave = true | ||
| 31 | +autosave_delay = "500ms" | ||
| 32 | +``` | ||
| 33 | + | ||
| 34 | +## Priorité du thème | ||
| 35 | + | ||
| 36 | +De la plus forte à la plus faible : | ||
| 37 | + | ||
| 38 | +| Source | L'emporte sur | | ||
| 39 | +| --- | --- | | ||
| 40 | +| `-theme` sur la ligne de commande | tout | | ||
| 41 | +| `theme` dans le fichier de réglages | le défaut intégré | | ||
| 42 | +| Le défaut intégré `turbo-classic` | — | | ||
| 43 | + | ||
| 44 | +Un nom de thème inconnu, à n'importe quel niveau, retombe sur le défaut intégré plutôt que d'échouer. | ||
| 45 | + | ||
| 46 | +## Quand un changement prend effet | ||
| 47 | + | ||
| 48 | +Le fichier est lu au démarrage, et **de nouveau à chaque enregistrement depuis l'éditeur** — un changement fait dans l'éditeur est donc en vigueur dès que vous appuyez sur `F2`, sans redémarrage. | ||
| 49 | + | ||
| 50 | +| Clé | Ré-appliquée à l'enregistrement | Pourquoi | | ||
| 51 | +| --- | --- | --- | | ||
| 52 | +| `autosave` | oui | | | ||
| 53 | +| `autosave_delay` | oui | | | ||
| 54 | +| `theme` | **non** | Options ▸ Theme est la façon vivante de le changer, et y réécrit déjà le choix. Une option `-theme` donnée en ligne de commande est l'affirmation la plus explicite pour cette session, et l'enregistrement d'un fichier ne la contredit pas. | | ||
| 55 | + | ||
| 56 | +| Résultat | Barre d'état | | ||
| 57 | +| --- | --- | | ||
| 58 | +| Lu et appliqué | `Applied .turbo-python/settings.toml — autosave on (2s)` | | ||
| 59 | +| Lu et appliqué, autosave désactivée | `Applied .turbo-python/settings.toml — autosave off` | | ||
| 60 | +| Enregistré, mais plus du TOML valide | `Saved, but not applied: …` — les valeurs précédentes restent en vigueur | | ||
| 61 | + | ||
| 62 | +Enregistrer est enregistrer, quel qu'en soit l'auteur : la sauvegarde automatique qui écrit le fichier de réglages les ré-applique exactement comme `F2`. Une modification faite **hors** de l'éditeur n'est pas remarquée ; rien ne surveille le fichier. | ||
| 63 | + | ||
| 64 | +## Sauvegarde automatique | ||
| 65 | + | ||
| 66 | +| Comportement | Détail | | ||
| 67 | +| --- | --- | | ||
| 68 | +| Déclencheur | Le délai écoulé sans modification dans aucune fenêtre | | ||
| 69 | +| Portée | Tout fichier ouvert qui a un nom, pas seulement celui au premier plan | | ||
| 70 | +| Échéance | Une seule pour tout l'éditeur, relancée par toute modification dans n'importe quelle fenêtre | | ||
| 71 | +| Fichiers sans nom | Jamais enregistrés ; jamais l'objet d'une question | | ||
| 72 | +| Signalement | `Saved <nom>` dans la barre d'état | | ||
| 73 | +| Échec | Signalé dans la barre d'état, jamais dans un dialogue, et non réessayé avant la modification suivante | | ||
| 74 | +| Fermeture d'une fenêtre | Enregistre au lieu de demander, si le fichier a un nom | | ||
| 75 | +| Sortie de l'éditeur | Enregistre au lieu de demander, si le fichier a un nom | | ||
| 76 | + | ||
| 77 | +## Écritures | ||
| 78 | + | ||
| 79 | +Le fichier de réglages est écrit par exactement deux actions. Rien d'autre dans l'éditeur n'y écrit, et rien ne le crée tout seul. | ||
| 80 | + | ||
| 81 | +| Action | Effet | | ||
| 82 | +| --- | --- | | ||
| 83 | +| **Options ▸ Create project settings** | Crée `.turbo-python/settings.toml` avec le thème en cours, `autosave = true` et des commentaires explicatifs. Grisée dès que le projet en a un, elle ne peut donc pas être choisie deux fois. | | ||
| 84 | +| **Options ▸ Theme** | Réécrit la valeur de `theme` **uniquement si le fichier existe déjà**. Commentaires, lignes vides, ordre des clés et commentaire de fin de la ligne du thème sont conservés. | | ||
| 85 | + | ||
| 86 | +Les deux écrivent via un fichier temporaire du même dossier, renommé en place : une écriture interrompue laisse le fichier précédent intact. | ||
| 87 | + | ||
| 88 | +## Entrées de menu | ||
| 89 | + | ||
| 90 | +| Entrée | Menu | Fichier requis | Effet | | ||
| 91 | +| --- | --- | --- | --- | | ||
| 92 | +| Create project settings | Options | refuse le fichier | Comme ci-dessus, puis ouvre le fichier. Grisée dès que le projet en a un. | | ||
| 93 | +| Project settings… | Options | exige le fichier | Ouvre `.turbo-python/settings.toml`. Grisée tant que le projet n'en a pas. | | ||
| 94 | + | ||
| 95 | +## Erreurs | ||
| 96 | + | ||
| 97 | +| Message | Cause | | ||
| 98 | +| --- | --- | | ||
| 99 | +| `turbo-python: reading …/settings.toml: …` sur la sortie d'erreur | Le fichier est là mais n'est pas du TOML valide. L'éditeur s'ouvre avec ses valeurs par défaut. | | ||
| 100 | +| `reading …: autosave_delay "x" is not a duration such as "2s"` | `autosave_delay` n'est pas une durée Go | | ||
| 101 | +| `reading …: autosave_delay must be positive, not "0s"` | `autosave_delay` est nul ou négatif | | ||
| 102 | +| `Already there: .turbo-python/settings.toml` dans la barre d'état | Créer dans un projet qui en a déjà un. Inatteignable depuis le menu, qui grise l'entrée ; reste possible pour un appelant qui n'est pas un menu. | | ||
| 103 | +| `Saved, but not applied: …` dans la barre d'état | Le fichier de réglages a été écrit mais ne s'analyse plus. Les valeurs précédentes restent en vigueur. | | ||
| 104 | +| `This project has no .turbo-python/settings.toml yet.` | **Project settings…** dans un projet qui n'en a pas | | ||
| 105 | +| `Theme set for this session only: …` | Le thème a changé mais le fichier de réglages n'a pas pu être écrit | | ||
| 106 | + | ||
| 107 | +## Voir aussi | ||
| 108 | + | ||
| 109 | +- [Donner ses propres réglages à un projet](../how-to/configure-a-project.md) | ||
| 110 | +- [Réglages de projet](../explanation/project-settings.md) | ||
| 111 | +- [Format des fichiers de thème](themes.md) — un autre fichier, dans le même langage | ||
added
docs/fr/reference/project-tree.md +102 -0 | new file mode 100644 | ||
| @@ -0,0 +1,102 @@ | ||
| 1 | +# Référence : arbre du projet | |
| 2 | + | |
| 3 | +> Description neutre de la fenêtre d'arbre du projet : ce qu'elle montre, ce qu'elle cache, et les touches auxquelles elle répond. | |
| 4 | + | |
| 5 | +## Ouverture | |
| 6 | + | |
| 7 | +| Chemin | Condition | | |
| 8 | +| --- | --- | | |
| 9 | +| `F9` | Toujours | | |
| 10 | +| **Window ▸ Project tree** | Toujours | | |
| 11 | + | |
| 12 | +Aucun des deux n'exige qu'un fichier soit ouvert. Les deux ramènent l'arbre existant au premier plan quand il y en a déjà un : il y a au plus une fenêtre d'arbre. | |
| 13 | + | |
| 14 | +## Racine | |
| 15 | + | |
| 16 | +| Propriété | Valeur | | |
| 17 | +| --- | --- | | |
| 18 | +| Enracinée à | Le dossier depuis lequel l'éditeur a été lancé (`os.Getwd()`) | | |
| 19 | +| Recherche | Ce dossier seulement. Les dossiers parents ne sont **pas** parcourus, la même règle que `.turbo-python/settings.toml`. | | |
| 20 | +| Titre de la fenêtre | Le nom de base de ce dossier | | |
| 21 | +| Ligne de la racine | Non affichée ; la première ligne est la première entrée du projet | | |
| 22 | + | |
| 23 | +## Ce qui est listé | |
| 24 | + | |
| 25 | +| Règle | Détail | | |
| 26 | +| --- | --- | | |
| 27 | +| Ordre | Les dossiers d'abord, puis les fichiers ; chaque groupe trié par nom | | |
| 28 | +| Masqué | `.git` seulement | | |
| 29 | +| Affiché | Toute autre entrée, y compris celles commençant par un point — `.turbo-python`, `.gitignore`, `.qlty` | | |
| 30 | +| Lecture | Un dossier est lu la première fois qu'il est déplié, pas avant | | |
| 31 | +| Dossier illisible | Apparaît déplié et vide ; le reste de l'arbre n'est pas affecté | | |
| 32 | + | |
| 33 | +## Marqueurs | |
| 34 | + | |
| 35 | +| Marqueur | Signification | | |
| 36 | +| --- | --- | | |
| 37 | +| `▶ ` | Un dossier fermé | | |
| 38 | +| `▼ ` | Un dossier ouvert | | |
| 39 | +| (deux espaces) | Un fichier — indenté de la largeur d'un marqueur, pour que les noms s'alignent | | |
| 40 | + | |
| 41 | +Chaque niveau de profondeur ajoute deux espaces d'indentation. | |
| 42 | + | |
| 43 | +## Touches | |
| 44 | + | |
| 45 | +Traitées quand la fenêtre de l'arbre a le focus. | |
| 46 | + | |
| 47 | +| Touche | Action | | |
| 48 | +| --- | --- | | |
| 49 | +| `↑` `↓` | Ligne précédente / suivante | | |
| 50 | +| `Page↑` `Page↓` | Un écran à la fois | | |
| 51 | +| `Début` `Fin` | Première / dernière ligne | | |
| 52 | +| `→` | Déplier un dossier fermé ; sinon aller à la ligne suivante | | |
| 53 | +| `←` | Replier un dossier ouvert ; sinon remonter au dossier qui contient cette ligne | | |
| 54 | +| `Entrée` | Ouvrir un fichier ; déplier ou replier un dossier | | |
| 55 | +| `F5`, `Ctrl-R` | Relire le projet | | |
| 56 | + | |
| 57 | +Les raccourcis de l'éditeur s'appliquent comme d'habitude : `F6` passe à la fenêtre suivante, `Ctrl-W` ferme l'arbre, `Alt-X` quitte. | |
| 58 | + | |
| 59 | +## Souris | |
| 60 | + | |
| 61 | +| Action | Effet | | |
| 62 | +| --- | --- | | |
| 63 | +| Clic sur une ligne | Y déplacer la surbrillance | | |
| 64 | +| Clic sur la ligne surlignée | Agir dessus, comme `Entrée` | | |
| 65 | +| Molette haut / bas | Déplacer la surbrillance de trois lignes | | |
| 66 | + | |
| 67 | +## Rafraîchissement | |
| 68 | + | |
| 69 | +| Déclencheur | Effet | | |
| 70 | +| --- | --- | | |
| 71 | +| `F5` ou `Ctrl-R` | Relit tous les dossiers qui ont été ouverts | | |
| 72 | +| Enregistrer un fichier | La même chose, automatiquement | | |
| 73 | +| Déplier un dossier | Lit ce dossier, s'il n'a pas encore été lu | | |
| 74 | + | |
| 75 | +Le rafraîchissement conserve la forme de l'arbre : un dossier ouvert le reste, un dossier supprimé emporte sa branche, et les dossiers que personne n'a ouverts restent non lus. La surbrillance reste sur la même entrée, ou sur la ligne restante la plus proche si cette entrée a disparu. | |
| 76 | + | |
| 77 | +L'arbre ne surveille **pas** le système de fichiers. Un fichier créé par une fenêtre terminal, ou par un `git checkout`, n'apparaît qu'après un rafraîchissement. | |
| 78 | + | |
| 79 | +## Couleurs | |
| 80 | + | |
| 81 | +| Clé de thème | Ce qu'elle colore | | |
| 82 | +| --- | --- | | |
| 83 | +| `tree.text` | Le nom d'un fichier dans l'arbre, et le fond de l'arbre | | |
| 84 | +| `tree.directory` | Le nom d'un dossier | | |
| 85 | +| `tree.selected` | La ligne surlignée, quand l'arbre a le focus | | |
| 86 | +| `tree.unfocused` | La ligne surlignée, quand il ne l'a pas | | |
| 87 | + | |
| 88 | +Elles ne se rabattent pas sur les clés `list.*` : le rabattement suit les points et s'arrête à `default`. Voir [Format des fichiers de thème](themes.md). | |
| 89 | + | |
| 90 | +## Erreurs | |
| 91 | + | |
| 92 | +| Message | Cause | | |
| 93 | +| --- | --- | | |
| 94 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | |
| 95 | +| `reading …: …` | Le dossier du projet n'a pas pu être lu | | |
| 96 | +| `… is not a directory` | La racine désigne un fichier | | |
| 97 | + | |
| 98 | +## Voir aussi | |
| 99 | + | |
| 100 | +- [Parcourir un projet et ouvrir des fichiers depuis un arbre](../how-to/browse-a-project.md) | |
| 101 | +- [Arbre du projet](../explanation/project-tree.md) | |
| 102 | +- [Clavier](keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,102 @@ | |||
| 1 | +# Référence : arbre du projet | ||
| 2 | + | ||
| 3 | +> Description neutre de la fenêtre d'arbre du projet : ce qu'elle montre, ce qu'elle cache, et les touches auxquelles elle répond. | ||
| 4 | + | ||
| 5 | +## Ouverture | ||
| 6 | + | ||
| 7 | +| Chemin | Condition | | ||
| 8 | +| --- | --- | | ||
| 9 | +| `F9` | Toujours | | ||
| 10 | +| **Window ▸ Project tree** | Toujours | | ||
| 11 | + | ||
| 12 | +Aucun des deux n'exige qu'un fichier soit ouvert. Les deux ramènent l'arbre existant au premier plan quand il y en a déjà un : il y a au plus une fenêtre d'arbre. | ||
| 13 | + | ||
| 14 | +## Racine | ||
| 15 | + | ||
| 16 | +| Propriété | Valeur | | ||
| 17 | +| --- | --- | | ||
| 18 | +| Enracinée à | Le dossier depuis lequel l'éditeur a été lancé (`os.Getwd()`) | | ||
| 19 | +| Recherche | Ce dossier seulement. Les dossiers parents ne sont **pas** parcourus, la même règle que `.turbo-python/settings.toml`. | | ||
| 20 | +| Titre de la fenêtre | Le nom de base de ce dossier | | ||
| 21 | +| Ligne de la racine | Non affichée ; la première ligne est la première entrée du projet | | ||
| 22 | + | ||
| 23 | +## Ce qui est listé | ||
| 24 | + | ||
| 25 | +| Règle | Détail | | ||
| 26 | +| --- | --- | | ||
| 27 | +| Ordre | Les dossiers d'abord, puis les fichiers ; chaque groupe trié par nom | | ||
| 28 | +| Masqué | `.git` seulement | | ||
| 29 | +| Affiché | Toute autre entrée, y compris celles commençant par un point — `.turbo-python`, `.gitignore`, `.qlty` | | ||
| 30 | +| Lecture | Un dossier est lu la première fois qu'il est déplié, pas avant | | ||
| 31 | +| Dossier illisible | Apparaît déplié et vide ; le reste de l'arbre n'est pas affecté | | ||
| 32 | + | ||
| 33 | +## Marqueurs | ||
| 34 | + | ||
| 35 | +| Marqueur | Signification | | ||
| 36 | +| --- | --- | | ||
| 37 | +| `▶ ` | Un dossier fermé | | ||
| 38 | +| `▼ ` | Un dossier ouvert | | ||
| 39 | +| (deux espaces) | Un fichier — indenté de la largeur d'un marqueur, pour que les noms s'alignent | | ||
| 40 | + | ||
| 41 | +Chaque niveau de profondeur ajoute deux espaces d'indentation. | ||
| 42 | + | ||
| 43 | +## Touches | ||
| 44 | + | ||
| 45 | +Traitées quand la fenêtre de l'arbre a le focus. | ||
| 46 | + | ||
| 47 | +| Touche | Action | | ||
| 48 | +| --- | --- | | ||
| 49 | +| `↑` `↓` | Ligne précédente / suivante | | ||
| 50 | +| `Page↑` `Page↓` | Un écran à la fois | | ||
| 51 | +| `Début` `Fin` | Première / dernière ligne | | ||
| 52 | +| `→` | Déplier un dossier fermé ; sinon aller à la ligne suivante | | ||
| 53 | +| `←` | Replier un dossier ouvert ; sinon remonter au dossier qui contient cette ligne | | ||
| 54 | +| `Entrée` | Ouvrir un fichier ; déplier ou replier un dossier | | ||
| 55 | +| `F5`, `Ctrl-R` | Relire le projet | | ||
| 56 | + | ||
| 57 | +Les raccourcis de l'éditeur s'appliquent comme d'habitude : `F6` passe à la fenêtre suivante, `Ctrl-W` ferme l'arbre, `Alt-X` quitte. | ||
| 58 | + | ||
| 59 | +## Souris | ||
| 60 | + | ||
| 61 | +| Action | Effet | | ||
| 62 | +| --- | --- | | ||
| 63 | +| Clic sur une ligne | Y déplacer la surbrillance | | ||
| 64 | +| Clic sur la ligne surlignée | Agir dessus, comme `Entrée` | | ||
| 65 | +| Molette haut / bas | Déplacer la surbrillance de trois lignes | | ||
| 66 | + | ||
| 67 | +## Rafraîchissement | ||
| 68 | + | ||
| 69 | +| Déclencheur | Effet | | ||
| 70 | +| --- | --- | | ||
| 71 | +| `F5` ou `Ctrl-R` | Relit tous les dossiers qui ont été ouverts | | ||
| 72 | +| Enregistrer un fichier | La même chose, automatiquement | | ||
| 73 | +| Déplier un dossier | Lit ce dossier, s'il n'a pas encore été lu | | ||
| 74 | + | ||
| 75 | +Le rafraîchissement conserve la forme de l'arbre : un dossier ouvert le reste, un dossier supprimé emporte sa branche, et les dossiers que personne n'a ouverts restent non lus. La surbrillance reste sur la même entrée, ou sur la ligne restante la plus proche si cette entrée a disparu. | ||
| 76 | + | ||
| 77 | +L'arbre ne surveille **pas** le système de fichiers. Un fichier créé par une fenêtre terminal, ou par un `git checkout`, n'apparaît qu'après un rafraîchissement. | ||
| 78 | + | ||
| 79 | +## Couleurs | ||
| 80 | + | ||
| 81 | +| Clé de thème | Ce qu'elle colore | | ||
| 82 | +| --- | --- | | ||
| 83 | +| `tree.text` | Le nom d'un fichier dans l'arbre, et le fond de l'arbre | | ||
| 84 | +| `tree.directory` | Le nom d'un dossier | | ||
| 85 | +| `tree.selected` | La ligne surlignée, quand l'arbre a le focus | | ||
| 86 | +| `tree.unfocused` | La ligne surlignée, quand il ne l'a pas | | ||
| 87 | + | ||
| 88 | +Elles ne se rabattent pas sur les clés `list.*` : le rabattement suit les points et s'arrête à `default`. Voir [Format des fichiers de thème](themes.md). | ||
| 89 | + | ||
| 90 | +## Erreurs | ||
| 91 | + | ||
| 92 | +| Message | Cause | | ||
| 93 | +| --- | --- | | ||
| 94 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | ||
| 95 | +| `reading …: …` | Le dossier du projet n'a pas pu être lu | | ||
| 96 | +| `… is not a directory` | La racine désigne un fichier | | ||
| 97 | + | ||
| 98 | +## Voir aussi | ||
| 99 | + | ||
| 100 | +- [Parcourir un projet et ouvrir des fichiers depuis un arbre](../how-to/browse-a-project.md) | ||
| 101 | +- [Arbre du projet](../explanation/project-tree.md) | ||
| 102 | +- [Clavier](keyboard.md) | ||
added
docs/fr/reference/python-tools.md +236 -0 | new file mode 100644 | ||
| @@ -0,0 +1,236 @@ | ||
| 1 | +# Référence : outils go | |
| 2 | + | |
| 3 | +> Description neutre de `.turbo-python/tools.toml`, du menu Python, et de ce que lancer une commande fait. | |
| 4 | + | |
| 5 | +## Fichier | |
| 6 | + | |
| 7 | +| Propriété | Valeur | | |
| 8 | +| --- | --- | | |
| 9 | +| Chemin | `./.turbo-python/tools.toml` | | |
| 10 | +| Recherche | Le répertoire de travail seulement. Les dossiers parents ne sont **pas** parcourus. | | |
| 11 | +| Lecture | À chaque ouverture d'un de ses menus, pour les entrées | | |
| 12 | +| Relecture | Dès que la taille ou la date de modification du fichier change, pour l'**ensemble** des menus | | |
| 13 | +| Fichier absent | Pas une erreur | | |
| 14 | +| Fichier illisible | Une erreur, signalée dans le menu | | |
| 15 | +| Fichier utilisateur | **Aucun.** Contrairement aux snippets, il n'y a pas de `~/.config/turbo-python/tools.toml`. | | |
| 16 | + | |
| 17 | +## Format du fichier | |
| 18 | + | |
| 19 | +Une table `[[tool]]` par commande. | |
| 20 | + | |
| 21 | +| Clé | Type | Obligatoire | Description | | |
| 22 | +| --- | --- | --- | --- | | |
| 23 | +| `name` | chaîne | oui | Ce que le menu affiche. Peut porter une touche d'accès écrite avec des tildes, comme `"~T~est"`. | | |
| 24 | +| `command` | chaîne | oui | La commande shell à exécuter | | |
| 25 | +| `output` | chaîne | non | Où va sa sortie : `popup`, `terminal` ou `editor`. Absent signifie `popup`. | | |
| 26 | +| `menu` | chaîne | non | Dans quel menu il apparaît. Absent signifie `Python`. N'importe quel nom ; le menu est créé pour vous. Peut porter une touche d'accès écrite avec des tildes. | | |
| 27 | + | |
| 28 | +`menu` n'est pas vérifié contre une liste, parce qu'il n'y en a pas : un nom qu'aucun autre outil n'emploie crée simplement un menu. Un outil sans `name`, sans `command`, ou dont l'`output` nomme quelque chose qui n'existe pas rend tout le fichier erroné. Un `output` inconnu est **refusé et non corrigé** : `"termnial"` aurait sinon l'air d'avoir fonctionné tout en envoyant la sortie ailleurs. | |
| 29 | + | |
| 30 | +### Exemple | |
| 31 | + | |
| 32 | +```toml | |
| 33 | +[[tool]] | |
| 34 | +name = "~T~est" | |
| 35 | +command = "uv run pytest" | |
| 36 | +output = "popup" | |
| 37 | + | |
| 38 | +[[tool]] | |
| 39 | +name = "~E~cho" | |
| 40 | +command = "echo TADA" | |
| 41 | +output = "terminal" | |
| 42 | +menu = "Tools" | |
| 43 | +``` | |
| 44 | + | |
| 45 | +## Le fichier de départ | |
| 46 | + | |
| 47 | +**Python ▸ Create tools file** écrit ces cinq, dans cet ordre : | |
| 48 | + | |
| 49 | +| Nom | Commande | Sortie | | |
| 50 | +| --- | --- | --- | | |
| 51 | +| Format | `uv run ruff format .` | `popup` | | |
| 52 | +| Lint | `uv run ruff check .` | `popup` | | |
| 53 | +| Build | `uv sync` | `popup` | | |
| 54 | +| Test | `uv run pytest` | `popup` | | |
| 55 | +| Run | `uv run` | `terminal` | | |
| 56 | + | |
| 57 | +Aucun ne nomme de `menu`, donc les cinq sont dans le menu Python. Chacun nomme son `output`, y compris les quatre qui nomment le défaut : la clé est la partie intéressante du format, et un fichier où elle n'apparaît qu'une fois est un fichier où personne ne remarque qu'elle existe. | |
| 58 | + | |
| 59 | +L'entrée est grisée dès que le projet a un fichier d'outils : elle ne peut donc pas en écraser un. Le fichier est écrit via un fichier temporaire du même dossier, renommé en place. | |
| 60 | + | |
| 61 | +## Le menu Python | |
| 62 | + | |
| 63 | +Toujours sur la barre, qu'un fichier d'outils existe ou non. Sa touche d'accès est `Alt-P`. | |
| 64 | + | |
| 65 | +| Entrée | Condition | | |
| 66 | +| --- | --- | | |
| 67 | +| Une ligne par outil sans `menu`, dans l'ordre du fichier | Le fichier en contient au moins un | | |
| 68 | +| `Cannot read tools`, grisé | Le fichier est présent mais illisible | | |
| 69 | +| `Create tools file` | Le projet n'a pas de fichier d'outils | | |
| 70 | +| `Open tools file` | Le projet en a un | | |
| 71 | + | |
| 72 | +## Les menus qu'un outil réclame | |
| 73 | + | |
| 74 | +Un `menu` nommant autre chose que `Go` place sur la barre un menu de ce nom. | |
| 75 | + | |
| 76 | +| Propriété | Valeur | | |
| 77 | +| --- | --- | | |
| 78 | +| Position | Entre Go et Help | | |
| 79 | +| Ordre | L'ordre où chaque nom apparaît pour la première fois dans le fichier | | |
| 80 | +| Entrées | Une ligne par outil nommant ce menu, dans l'ordre du fichier. Rien d'autre — `Create tools file` et `Open tools file` restent dans Python. | | |
| 81 | +| Fichier illisible | Aucun menu ; c'est le menu Python qui porte l'erreur | | |
| 82 | +| Pendant que l'éditeur tourne | Ajoutés, retirés et renommés au fil des modifications du fichier, sans redémarrage | | |
| 83 | + | |
| 84 | +### Touches d'accès | |
| 85 | + | |
| 86 | +Attribuées automatiquement, parce qu'un nom venu d'un fichier ne peut pas être confronté à l'avance aux menus fixes. | |
| 87 | + | |
| 88 | +| Cas | Résultat | | |
| 89 | +| --- | --- | | |
| 90 | +| Aucun tilde dans le nom | La première lettre qu'aucun autre menu ne revendique est marquée. `Format` devient `For~m~at` : `F` est à File, `o` à Options, `r` à Run. | | |
| 91 | +| Des tildes nommant une lettre libre | Conservés tels quels. `Doc~k~er` répond à `Alt-K`. | | |
| 92 | +| Des tildes nommant une lettre prise | Abandonnés, et une lettre libre choisie à la place. `~F~oo` devient `F~o~o`. | | |
| 93 | +| Toutes les lettres prises | Pas de touche d'accès. `F10` et la souris l'ouvrent quand même. | | |
| 94 | + | |
| 95 | +Les lettres que les menus de l'éditeur occupent sont `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` et `H`. | |
| 96 | + | |
| 97 | +## Lancer une commande | |
| 98 | + | |
| 99 | +Commun à toutes les sorties : | |
| 100 | + | |
| 101 | +| Propriété | Valeur | | |
| 102 | +| --- | --- | | |
| 103 | +| Shell | `/bin/sh -c "<commande>"` sous Linux et macOS ; `cmd.exe /S /C "<commande>"` — le shell que nomme `%COMSPEC%` — sous Windows | | |
| 104 | +| Répertoire | Celui depuis lequel l'éditeur a été lancé | | |
| 105 | +| Erreur standard | Mêlée à la sortie standard, dans l'ordre où la commande les a écrites | | |
| 106 | + | |
| 107 | +Passer par un shell signifie que les tubes, les globs, `&&` et `;` fonctionnent : un outil peut être une séquence. Sous Windows le shell est cmd.exe, qui connaît `&&`, `|` et `>` mais ne développe pas les globs, et où `;` n'est pas un séparateur. | |
| 108 | + | |
| 109 | +### `output = "popup"` | |
| 110 | + | |
| 111 | +| Propriété | Valeur | | |
| 112 | +| --- | --- | | |
| 113 | +| Ouverture | Immédiate, avant la fin de la commande | | |
| 114 | +| Modale | Oui : rien d'autre dans l'éditeur n'est utilisable tant qu'elle est là | | |
| 115 | +| Remplissage | À mesure que la sortie arrive, en la suivant tant qu'on n'a pas remonté | | |
| 116 | +| Titre pendant | `<commande> — running` | | |
| 117 | +| Titre à la fin | `<commande> — ok`, ou `<commande> — exit <n>` | | |
| 118 | +| Sortie vide, terminée | Affiche `(no output)` | | |
| 119 | +| Sortie vide, en cours | N'affiche rien | | |
| 120 | +| Plafond de sortie | 10000 lignes ; au-delà les plus anciennes partent et une ligne `… n earlier lines dropped …` le dit | | |
| 121 | + | |
| 122 | +| Touche | Effet | | |
| 123 | +| --- | --- | | |
| 124 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Parcourir la sortie | | |
| 125 | +| Molette | Idem | | |
| 126 | +| `Échap`, `Entrée`, **Close** | Fermer, en **arrêtant la commande** si elle tourne encore | | |
| 127 | + | |
| 128 | +Fermer arrête la commande parce qu'il n'y a pas d'autre moyen d'interrompre celle dont la sortie n'est pas dans un terminal. | |
| 129 | + | |
| 130 | +### `output = "terminal"` | |
| 131 | + | |
| 132 | +| Propriété | Valeur | | |
| 133 | +| --- | --- | | |
| 134 | +| Fenêtre | Une fenêtre terminal à elle, titrée avec la commande | | |
| 135 | +| Environnement | Celui de l'éditeur, avec `TERM` à `xterm-256color` | | |
| 136 | +| Après la sortie | La fenêtre reste, montrant sa sortie | | |
| 137 | +| Modale | Non : l'éditeur continue à côté | | |
| 138 | + | |
| 139 | +Comme c'est un vrai terminal, les couleurs, la pagination, `Ctrl-C` et la lecture au clavier fonctionnent. Voir [Fenêtres terminal](terminal.md). | |
| 140 | + | |
| 141 | +Touches dans une fenêtre **terminée** : | |
| 142 | + | |
| 143 | +| Touche | Effet | | |
| 144 | +| --- | --- | | |
| 145 | +| `Maj-Page↑`, `Maj-Page↓` | Relire la sortie | | |
| 146 | +| `Ctrl-W` | Fermer la fenêtre | | |
| 147 | +| Tout le reste | Atteint l'éditeur, pas le shell mort | | |
| 148 | + | |
| 149 | +### `output = "editor"` | |
| 150 | + | |
| 151 | +| Propriété | Valeur | | |
| 152 | +| --- | --- | | |
| 153 | +| Affiche | Une popup pendant l'exécution, comme ci-dessus | | |
| 154 | +| À la fermeture de la popup | Une fenêtre d'édition contenant la sortie, titrée avec la commande | | |
| 155 | +| Remplie | Une fois, à la fin de la commande — pas au fil de l'eau | | |
| 156 | +| La fenêtre | Une fenêtre d'édition ordinaire sans nom de fichier : cherchable avec `Ctrl-F`, et `Save as` la conserve | | |
| 157 | + | |
| 158 | +## Rechargement après une commande | |
| 159 | + | |
| 160 | +À la fin d'une commande, chaque fichier ouvert est examiné. | |
| 161 | + | |
| 162 | +| Le fichier | Ce qui se passe | | |
| 163 | +| --- | --- | | |
| 164 | +| Non modifié, et changé sur le disque | Relu ; son langage est redécidé et son titre rafraîchi | | |
| 165 | +| Non modifié, et inchangé sur le disque | Laissé tel quel, non compté | | |
| 166 | +| A des modifications non enregistrées | Laissé tel quel et compté comme ignoré | | |
| 167 | +| N'a jamais reçu de nom | Laissé tel quel | | |
| 168 | +| A disparu du disque | Laissé tel quel | | |
| 169 | + | |
| 170 | +Le curseur reste où il était, borné à ce que le fichier contient désormais. L'historique d'annulation est jeté, parce qu'annuler au-delà d'un rechargement restaurerait un texte que le fichier n'a plus. | |
| 171 | + | |
| 172 | +L'arbre du projet est rafraîchi au même moment. | |
| 173 | + | |
| 174 | +| Barre d'état | Quand | | |
| 175 | +| --- | --- | | |
| 176 | +| `Running <commande>` | La fenêtre s'ouvre | | |
| 177 | +| `Reloaded 2 files` | Deux fichiers relus, aucun ignoré | | |
| 178 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Certains ont été ignorés | | |
| 179 | +| `Command finished; 1 file with unsaved changes left alone` | Rien relu, quelque chose ignoré | | |
| 180 | + | |
| 181 | +## Erreurs | |
| 182 | + | |
| 183 | +| Message | Cause | | |
| 184 | +| --- | --- | | |
| 185 | +| `Cannot read tools` dans le menu | Le fichier est présent mais n'est pas du TOML valide, ou contient un outil sans nom ou sans commande | | |
| 186 | +| `Already there: .turbo-python/tools.toml` | Créer dans un projet qui en a déjà un. Inatteignable depuis le menu, qui grise l'entrée ; reste possible pour un appelant qui n'est pas un menu. | | |
| 187 | +| `This project has no .turbo-python/tools.toml yet.` | Ouvrir dans un projet qui n'en a pas, de même | | |
| 188 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | |
| 189 | +| `Terminal windows are not supported on this platform yet` | Lancer une commande dans un terminal exige un pseudo-terminal, que Linux, macOS et Windows possèdent ; voir [Fenêtres terminal](terminal.md) | | |
| 190 | + | |
| 191 | +## Demander une valeur | |
| 192 | + | |
| 193 | +Un `{{libellé}}` n'importe où dans une commande est une valeur que l'éditeur demande avant de lancer, dans une boîte portant le nom de l'outil. Le texte entre les accolades est ce que la boîte demande. | |
| 194 | + | |
| 195 | +| Écrit | Demandé | Substitué | | |
| 196 | +| --- | --- | --- | | |
| 197 | +| `{{chemin du module}}` | `chemin du module` | protégé pour le shell | | |
| 198 | +| `{{options...}}` | `options` | tel quel | | |
| 199 | + | |
| 200 | +Une valeur est **protégée pour le shell** par défaut, si bien qu'un chemin contenant une espace reste un seul argument. Un `...` final à l'intérieur des accolades la demande telle quelle, ce qui permet à un seul champ de valoir plusieurs arguments. | |
| 201 | + | |
| 202 | +```toml | |
| 203 | +[[tool]] | |
| 204 | +name = "~I~nit module" | |
| 205 | +command = "go mod init {{chemin du module}}" | |
| 206 | +output = "popup" | |
| 207 | +``` | |
| 208 | + | |
| 209 | +| Règle | Comportement | | |
| 210 | +| --- | --- | | |
| 211 | +| Plusieurs libellés | Une boîte, un champ chacun, dans l'ordre où ils apparaissent | | |
| 212 | +| Le même libellé deux fois | Un seul champ ; chaque occurrence reçoit ce qui y est tapé | | |
| 213 | +| Un libellé écrit des deux façons | Demandé une fois ; chaque occurrence honore ses propres accolades | | |
| 214 | +| Échap, ou Annuler | La commande n'est pas lancée | | |
| 215 | +| Un champ laissé vide | Substitué par du vide — la commande dira elle-même ce qui lui manque | | |
| 216 | +| Relancer l'outil | La boîte repart de ce qui avait été tapé, pour cette session seulement | | |
| 217 | +| Plus de champs que l'écran n'en contient | Refusé, avec un message disant combien tiennent | | |
| 218 | + | |
| 219 | +**Deux accolades, pas une.** `awk '{print $1}'` et `find . -exec rm {} +` sont des commandes ordinaires, et une syntaxe à une accolade lirait la première comme une demande de valeur nommée `print $1`. | |
| 220 | + | |
| 221 | +Rien n'est écrit sur le disque. Une valeur que quelqu'un a tapée cet après-midi n'est pas une décision du projet, elle n'a donc rien à faire dans le répertoire du projet. | |
| 222 | + | |
| 223 | +### Erreurs | |
| 224 | + | |
| 225 | +| Erreur | Cause | | |
| 226 | +| --- | --- | | |
| 227 | +| `tool "X": "{{module" is never closed` | Une ouverture `{{` sans `}}` après elle | | |
| 228 | +| `tool "X": {{}} asks for a value but does not say what it is` | Un libellé vide, ou réduit à `...` | | |
| 229 | + | |
| 230 | +Les deux sont refusées à la lecture du fichier : un libellé à moitié tapé n'atteint donc jamais le shell avec ses accolades. | |
| 231 | + | |
| 232 | +## Voir aussi | |
| 233 | + | |
| 234 | +- [Lancer les commandes uv depuis l'éditeur](../how-to/run-uv-commands.md) | |
| 235 | +- [Outils Python](../explanation/python-tools.md) | |
| 236 | +- [Fenêtres terminal](terminal.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,236 @@ | |||
| 1 | +# Référence : outils go | ||
| 2 | + | ||
| 3 | +> Description neutre de `.turbo-python/tools.toml`, du menu Python, et de ce que lancer une commande fait. | ||
| 4 | + | ||
| 5 | +## Fichier | ||
| 6 | + | ||
| 7 | +| Propriété | Valeur | | ||
| 8 | +| --- | --- | | ||
| 9 | +| Chemin | `./.turbo-python/tools.toml` | | ||
| 10 | +| Recherche | Le répertoire de travail seulement. Les dossiers parents ne sont **pas** parcourus. | | ||
| 11 | +| Lecture | À chaque ouverture d'un de ses menus, pour les entrées | | ||
| 12 | +| Relecture | Dès que la taille ou la date de modification du fichier change, pour l'**ensemble** des menus | | ||
| 13 | +| Fichier absent | Pas une erreur | | ||
| 14 | +| Fichier illisible | Une erreur, signalée dans le menu | | ||
| 15 | +| Fichier utilisateur | **Aucun.** Contrairement aux snippets, il n'y a pas de `~/.config/turbo-python/tools.toml`. | | ||
| 16 | + | ||
| 17 | +## Format du fichier | ||
| 18 | + | ||
| 19 | +Une table `[[tool]]` par commande. | ||
| 20 | + | ||
| 21 | +| Clé | Type | Obligatoire | Description | | ||
| 22 | +| --- | --- | --- | --- | | ||
| 23 | +| `name` | chaîne | oui | Ce que le menu affiche. Peut porter une touche d'accès écrite avec des tildes, comme `"~T~est"`. | | ||
| 24 | +| `command` | chaîne | oui | La commande shell à exécuter | | ||
| 25 | +| `output` | chaîne | non | Où va sa sortie : `popup`, `terminal` ou `editor`. Absent signifie `popup`. | | ||
| 26 | +| `menu` | chaîne | non | Dans quel menu il apparaît. Absent signifie `Python`. N'importe quel nom ; le menu est créé pour vous. Peut porter une touche d'accès écrite avec des tildes. | | ||
| 27 | + | ||
| 28 | +`menu` n'est pas vérifié contre une liste, parce qu'il n'y en a pas : un nom qu'aucun autre outil n'emploie crée simplement un menu. Un outil sans `name`, sans `command`, ou dont l'`output` nomme quelque chose qui n'existe pas rend tout le fichier erroné. Un `output` inconnu est **refusé et non corrigé** : `"termnial"` aurait sinon l'air d'avoir fonctionné tout en envoyant la sortie ailleurs. | ||
| 29 | + | ||
| 30 | +### Exemple | ||
| 31 | + | ||
| 32 | +```toml | ||
| 33 | +[[tool]] | ||
| 34 | +name = "~T~est" | ||
| 35 | +command = "uv run pytest" | ||
| 36 | +output = "popup" | ||
| 37 | + | ||
| 38 | +[[tool]] | ||
| 39 | +name = "~E~cho" | ||
| 40 | +command = "echo TADA" | ||
| 41 | +output = "terminal" | ||
| 42 | +menu = "Tools" | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +## Le fichier de départ | ||
| 46 | + | ||
| 47 | +**Python ▸ Create tools file** écrit ces cinq, dans cet ordre : | ||
| 48 | + | ||
| 49 | +| Nom | Commande | Sortie | | ||
| 50 | +| --- | --- | --- | | ||
| 51 | +| Format | `uv run ruff format .` | `popup` | | ||
| 52 | +| Lint | `uv run ruff check .` | `popup` | | ||
| 53 | +| Build | `uv sync` | `popup` | | ||
| 54 | +| Test | `uv run pytest` | `popup` | | ||
| 55 | +| Run | `uv run` | `terminal` | | ||
| 56 | + | ||
| 57 | +Aucun ne nomme de `menu`, donc les cinq sont dans le menu Python. Chacun nomme son `output`, y compris les quatre qui nomment le défaut : la clé est la partie intéressante du format, et un fichier où elle n'apparaît qu'une fois est un fichier où personne ne remarque qu'elle existe. | ||
| 58 | + | ||
| 59 | +L'entrée est grisée dès que le projet a un fichier d'outils : elle ne peut donc pas en écraser un. Le fichier est écrit via un fichier temporaire du même dossier, renommé en place. | ||
| 60 | + | ||
| 61 | +## Le menu Python | ||
| 62 | + | ||
| 63 | +Toujours sur la barre, qu'un fichier d'outils existe ou non. Sa touche d'accès est `Alt-P`. | ||
| 64 | + | ||
| 65 | +| Entrée | Condition | | ||
| 66 | +| --- | --- | | ||
| 67 | +| Une ligne par outil sans `menu`, dans l'ordre du fichier | Le fichier en contient au moins un | | ||
| 68 | +| `Cannot read tools`, grisé | Le fichier est présent mais illisible | | ||
| 69 | +| `Create tools file` | Le projet n'a pas de fichier d'outils | | ||
| 70 | +| `Open tools file` | Le projet en a un | | ||
| 71 | + | ||
| 72 | +## Les menus qu'un outil réclame | ||
| 73 | + | ||
| 74 | +Un `menu` nommant autre chose que `Go` place sur la barre un menu de ce nom. | ||
| 75 | + | ||
| 76 | +| Propriété | Valeur | | ||
| 77 | +| --- | --- | | ||
| 78 | +| Position | Entre Go et Help | | ||
| 79 | +| Ordre | L'ordre où chaque nom apparaît pour la première fois dans le fichier | | ||
| 80 | +| Entrées | Une ligne par outil nommant ce menu, dans l'ordre du fichier. Rien d'autre — `Create tools file` et `Open tools file` restent dans Python. | | ||
| 81 | +| Fichier illisible | Aucun menu ; c'est le menu Python qui porte l'erreur | | ||
| 82 | +| Pendant que l'éditeur tourne | Ajoutés, retirés et renommés au fil des modifications du fichier, sans redémarrage | | ||
| 83 | + | ||
| 84 | +### Touches d'accès | ||
| 85 | + | ||
| 86 | +Attribuées automatiquement, parce qu'un nom venu d'un fichier ne peut pas être confronté à l'avance aux menus fixes. | ||
| 87 | + | ||
| 88 | +| Cas | Résultat | | ||
| 89 | +| --- | --- | | ||
| 90 | +| Aucun tilde dans le nom | La première lettre qu'aucun autre menu ne revendique est marquée. `Format` devient `For~m~at` : `F` est à File, `o` à Options, `r` à Run. | | ||
| 91 | +| Des tildes nommant une lettre libre | Conservés tels quels. `Doc~k~er` répond à `Alt-K`. | | ||
| 92 | +| Des tildes nommant une lettre prise | Abandonnés, et une lettre libre choisie à la place. `~F~oo` devient `F~o~o`. | | ||
| 93 | +| Toutes les lettres prises | Pas de touche d'accès. `F10` et la souris l'ouvrent quand même. | | ||
| 94 | + | ||
| 95 | +Les lettres que les menus de l'éditeur occupent sont `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` et `H`. | ||
| 96 | + | ||
| 97 | +## Lancer une commande | ||
| 98 | + | ||
| 99 | +Commun à toutes les sorties : | ||
| 100 | + | ||
| 101 | +| Propriété | Valeur | | ||
| 102 | +| --- | --- | | ||
| 103 | +| Shell | `/bin/sh -c "<commande>"` sous Linux et macOS ; `cmd.exe /S /C "<commande>"` — le shell que nomme `%COMSPEC%` — sous Windows | | ||
| 104 | +| Répertoire | Celui depuis lequel l'éditeur a été lancé | | ||
| 105 | +| Erreur standard | Mêlée à la sortie standard, dans l'ordre où la commande les a écrites | | ||
| 106 | + | ||
| 107 | +Passer par un shell signifie que les tubes, les globs, `&&` et `;` fonctionnent : un outil peut être une séquence. Sous Windows le shell est cmd.exe, qui connaît `&&`, `|` et `>` mais ne développe pas les globs, et où `;` n'est pas un séparateur. | ||
| 108 | + | ||
| 109 | +### `output = "popup"` | ||
| 110 | + | ||
| 111 | +| Propriété | Valeur | | ||
| 112 | +| --- | --- | | ||
| 113 | +| Ouverture | Immédiate, avant la fin de la commande | | ||
| 114 | +| Modale | Oui : rien d'autre dans l'éditeur n'est utilisable tant qu'elle est là | | ||
| 115 | +| Remplissage | À mesure que la sortie arrive, en la suivant tant qu'on n'a pas remonté | | ||
| 116 | +| Titre pendant | `<commande> — running` | | ||
| 117 | +| Titre à la fin | `<commande> — ok`, ou `<commande> — exit <n>` | | ||
| 118 | +| Sortie vide, terminée | Affiche `(no output)` | | ||
| 119 | +| Sortie vide, en cours | N'affiche rien | | ||
| 120 | +| Plafond de sortie | 10000 lignes ; au-delà les plus anciennes partent et une ligne `… n earlier lines dropped …` le dit | | ||
| 121 | + | ||
| 122 | +| Touche | Effet | | ||
| 123 | +| --- | --- | | ||
| 124 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Parcourir la sortie | | ||
| 125 | +| Molette | Idem | | ||
| 126 | +| `Échap`, `Entrée`, **Close** | Fermer, en **arrêtant la commande** si elle tourne encore | | ||
| 127 | + | ||
| 128 | +Fermer arrête la commande parce qu'il n'y a pas d'autre moyen d'interrompre celle dont la sortie n'est pas dans un terminal. | ||
| 129 | + | ||
| 130 | +### `output = "terminal"` | ||
| 131 | + | ||
| 132 | +| Propriété | Valeur | | ||
| 133 | +| --- | --- | | ||
| 134 | +| Fenêtre | Une fenêtre terminal à elle, titrée avec la commande | | ||
| 135 | +| Environnement | Celui de l'éditeur, avec `TERM` à `xterm-256color` | | ||
| 136 | +| Après la sortie | La fenêtre reste, montrant sa sortie | | ||
| 137 | +| Modale | Non : l'éditeur continue à côté | | ||
| 138 | + | ||
| 139 | +Comme c'est un vrai terminal, les couleurs, la pagination, `Ctrl-C` et la lecture au clavier fonctionnent. Voir [Fenêtres terminal](terminal.md). | ||
| 140 | + | ||
| 141 | +Touches dans une fenêtre **terminée** : | ||
| 142 | + | ||
| 143 | +| Touche | Effet | | ||
| 144 | +| --- | --- | | ||
| 145 | +| `Maj-Page↑`, `Maj-Page↓` | Relire la sortie | | ||
| 146 | +| `Ctrl-W` | Fermer la fenêtre | | ||
| 147 | +| Tout le reste | Atteint l'éditeur, pas le shell mort | | ||
| 148 | + | ||
| 149 | +### `output = "editor"` | ||
| 150 | + | ||
| 151 | +| Propriété | Valeur | | ||
| 152 | +| --- | --- | | ||
| 153 | +| Affiche | Une popup pendant l'exécution, comme ci-dessus | | ||
| 154 | +| À la fermeture de la popup | Une fenêtre d'édition contenant la sortie, titrée avec la commande | | ||
| 155 | +| Remplie | Une fois, à la fin de la commande — pas au fil de l'eau | | ||
| 156 | +| La fenêtre | Une fenêtre d'édition ordinaire sans nom de fichier : cherchable avec `Ctrl-F`, et `Save as` la conserve | | ||
| 157 | + | ||
| 158 | +## Rechargement après une commande | ||
| 159 | + | ||
| 160 | +À la fin d'une commande, chaque fichier ouvert est examiné. | ||
| 161 | + | ||
| 162 | +| Le fichier | Ce qui se passe | | ||
| 163 | +| --- | --- | | ||
| 164 | +| Non modifié, et changé sur le disque | Relu ; son langage est redécidé et son titre rafraîchi | | ||
| 165 | +| Non modifié, et inchangé sur le disque | Laissé tel quel, non compté | | ||
| 166 | +| A des modifications non enregistrées | Laissé tel quel et compté comme ignoré | | ||
| 167 | +| N'a jamais reçu de nom | Laissé tel quel | | ||
| 168 | +| A disparu du disque | Laissé tel quel | | ||
| 169 | + | ||
| 170 | +Le curseur reste où il était, borné à ce que le fichier contient désormais. L'historique d'annulation est jeté, parce qu'annuler au-delà d'un rechargement restaurerait un texte que le fichier n'a plus. | ||
| 171 | + | ||
| 172 | +L'arbre du projet est rafraîchi au même moment. | ||
| 173 | + | ||
| 174 | +| Barre d'état | Quand | | ||
| 175 | +| --- | --- | | ||
| 176 | +| `Running <commande>` | La fenêtre s'ouvre | | ||
| 177 | +| `Reloaded 2 files` | Deux fichiers relus, aucun ignoré | | ||
| 178 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Certains ont été ignorés | | ||
| 179 | +| `Command finished; 1 file with unsaved changes left alone` | Rien relu, quelque chose ignoré | | ||
| 180 | + | ||
| 181 | +## Erreurs | ||
| 182 | + | ||
| 183 | +| Message | Cause | | ||
| 184 | +| --- | --- | | ||
| 185 | +| `Cannot read tools` dans le menu | Le fichier est présent mais n'est pas du TOML valide, ou contient un outil sans nom ou sans commande | | ||
| 186 | +| `Already there: .turbo-python/tools.toml` | Créer dans un projet qui en a déjà un. Inatteignable depuis le menu, qui grise l'entrée ; reste possible pour un appelant qui n'est pas un menu. | | ||
| 187 | +| `This project has no .turbo-python/tools.toml yet.` | Ouvrir dans un projet qui n'en a pas, de même | | ||
| 188 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | ||
| 189 | +| `Terminal windows are not supported on this platform yet` | Lancer une commande dans un terminal exige un pseudo-terminal, que Linux, macOS et Windows possèdent ; voir [Fenêtres terminal](terminal.md) | | ||
| 190 | + | ||
| 191 | +## Demander une valeur | ||
| 192 | + | ||
| 193 | +Un `{{libellé}}` n'importe où dans une commande est une valeur que l'éditeur demande avant de lancer, dans une boîte portant le nom de l'outil. Le texte entre les accolades est ce que la boîte demande. | ||
| 194 | + | ||
| 195 | +| Écrit | Demandé | Substitué | | ||
| 196 | +| --- | --- | --- | | ||
| 197 | +| `{{chemin du module}}` | `chemin du module` | protégé pour le shell | | ||
| 198 | +| `{{options...}}` | `options` | tel quel | | ||
| 199 | + | ||
| 200 | +Une valeur est **protégée pour le shell** par défaut, si bien qu'un chemin contenant une espace reste un seul argument. Un `...` final à l'intérieur des accolades la demande telle quelle, ce qui permet à un seul champ de valoir plusieurs arguments. | ||
| 201 | + | ||
| 202 | +```toml | ||
| 203 | +[[tool]] | ||
| 204 | +name = "~I~nit module" | ||
| 205 | +command = "go mod init {{chemin du module}}" | ||
| 206 | +output = "popup" | ||
| 207 | +``` | ||
| 208 | + | ||
| 209 | +| Règle | Comportement | | ||
| 210 | +| --- | --- | | ||
| 211 | +| Plusieurs libellés | Une boîte, un champ chacun, dans l'ordre où ils apparaissent | | ||
| 212 | +| Le même libellé deux fois | Un seul champ ; chaque occurrence reçoit ce qui y est tapé | | ||
| 213 | +| Un libellé écrit des deux façons | Demandé une fois ; chaque occurrence honore ses propres accolades | | ||
| 214 | +| Échap, ou Annuler | La commande n'est pas lancée | | ||
| 215 | +| Un champ laissé vide | Substitué par du vide — la commande dira elle-même ce qui lui manque | | ||
| 216 | +| Relancer l'outil | La boîte repart de ce qui avait été tapé, pour cette session seulement | | ||
| 217 | +| Plus de champs que l'écran n'en contient | Refusé, avec un message disant combien tiennent | | ||
| 218 | + | ||
| 219 | +**Deux accolades, pas une.** `awk '{print $1}'` et `find . -exec rm {} +` sont des commandes ordinaires, et une syntaxe à une accolade lirait la première comme une demande de valeur nommée `print $1`. | ||
| 220 | + | ||
| 221 | +Rien n'est écrit sur le disque. Une valeur que quelqu'un a tapée cet après-midi n'est pas une décision du projet, elle n'a donc rien à faire dans le répertoire du projet. | ||
| 222 | + | ||
| 223 | +### Erreurs | ||
| 224 | + | ||
| 225 | +| Erreur | Cause | | ||
| 226 | +| --- | --- | | ||
| 227 | +| `tool "X": "{{module" is never closed` | Une ouverture `{{` sans `}}` après elle | | ||
| 228 | +| `tool "X": {{}} asks for a value but does not say what it is` | Un libellé vide, ou réduit à `...` | | ||
| 229 | + | ||
| 230 | +Les deux sont refusées à la lecture du fichier : un libellé à moitié tapé n'atteint donc jamais le shell avec ses accolades. | ||
| 231 | + | ||
| 232 | +## Voir aussi | ||
| 233 | + | ||
| 234 | +- [Lancer les commandes uv depuis l'éditeur](../how-to/run-uv-commands.md) | ||
| 235 | +- [Outils Python](../explanation/python-tools.md) | ||
| 236 | +- [Fenêtres terminal](terminal.md) | ||
added
docs/fr/reference/snippets.md +114 -0 | new file mode 100644 | ||
| @@ -0,0 +1,114 @@ | ||
| 1 | +# Référence : snippets | |
| 2 | + | |
| 3 | +> Description neutre des fichiers de snippets, du menu Snippets, et de la façon dont un snippet est inséré. | |
| 4 | + | |
| 5 | +## Fichiers | |
| 6 | + | |
| 7 | +Les deux sont lus, et les deux sont facultatifs. | |
| 8 | + | |
| 9 | +| Fichier | Contient | | |
| 10 | +| --- | --- | | |
| 11 | +| `./.turbo-python/snippets.toml` | Les snippets du projet | | |
| 12 | +| `$TURBO_PYTHON_SNIPPET_DIR/snippets.toml`, sinon `<config utilisateur>/turbo-python/snippets.toml` | Les vôtres, partagés entre projets | | |
| 13 | + | |
| 14 | +`<config utilisateur>` est `os.UserConfigDir()` : `~/.config` sous Linux, `~/Library/Application Support` sous macOS. | |
| 15 | + | |
| 16 | +| Propriété | Valeur | | |
| 17 | +| --- | --- | | |
| 18 | +| Recherche du projet | Le répertoire de travail seulement. Les dossiers parents ne sont **pas** parcourus. | | |
| 19 | +| Lecture | À chaque ouverture du menu Snippets | | |
| 20 | +| Ordre | Les vôtres d'abord, puis ceux du projet | | |
| 21 | +| Conflit de nom | Même `group` **et** même `name` → celui du projet remplace le vôtre | | |
| 22 | +| Fichier absent | Pas une erreur | | |
| 23 | +| Fichier illisible | Une erreur, signalée dans le menu | | |
| 24 | + | |
| 25 | +## Format du fichier | |
| 26 | + | |
| 27 | +Une table `[[snippet]]` par snippet. | |
| 28 | + | |
| 29 | +| Clé | Type | Obligatoire | Description | | |
| 30 | +| --- | --- | --- | --- | | |
| 31 | +| `name` | chaîne | oui | Ce que le menu affiche | | |
| 32 | +| `body` | chaîne | oui | Le texte inséré au curseur | | |
| 33 | +| `group` | chaîne | non | Le sous-menu où il va ; absent signifie `General` | | |
| 34 | +| `languages` | tableau de chaînes | non | Restreint le snippet à ces langages ; absent signifie tous les fichiers | | |
| 35 | + | |
| 36 | +`languages` emploie les noms de langages de l'éditeur : `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash`. Voir [Langages colorés](languages.md). | |
| 37 | + | |
| 38 | +Un snippet sans `name` ou sans `body` rend tout le fichier erroné — il n'aurait pu être affiché, ou n'aurait rien à insérer. | |
| 39 | + | |
| 40 | +### Exemple | |
| 41 | + | |
| 42 | +```toml | |
| 43 | +[[snippet]] | |
| 44 | +name = "if err != nil" | |
| 45 | +group = "Python" | |
| 46 | +languages = ["python"] | |
| 47 | +body = """ | |
| 48 | +if err != nil { | |
| 49 | + return err | |
| 50 | +}""" | |
| 51 | +``` | |
| 52 | + | |
| 53 | +Les chaînes `"""` du TOML suppriment le saut de ligne qui suit immédiatement les guillemets d'ouverture, et interprètent `\t` comme une tabulation. | |
| 54 | + | |
| 55 | +## Le menu | |
| 56 | + | |
| 57 | +| Entrée | Condition | | |
| 58 | +| --- | --- | | |
| 59 | +| Un sous-menu par groupe, dans l'ordre d'apparition des groupes dans les fichiers | Un groupe ayant au moins un snippet applicable à la fenêtre au premier plan | | |
| 60 | +| `Cannot read snippets`, grisé | Un fichier est présent mais illisible | | |
| 61 | +| `Create snippets file` | Le projet n'a pas de fichier d'extraits | | |
| 62 | +| `Open snippets file` | Le projet en a un | | |
| 63 | + | |
| 64 | +La touche d'accès du menu est `Alt-N`, pas `Alt-S` : Search répond déjà au S. | |
| 65 | + | |
| 66 | +Les groupes, et les snippets à l'intérieur, sortent dans l'ordre de lecture : le menu correspond aux fichiers. | |
| 67 | + | |
| 68 | +Une entrée de snippet est grisée quand aucun fichier n'est ouvert pour l'y insérer — un terminal ou l'arbre du projet au premier plan compte comme aucun fichier. | |
| 69 | + | |
| 70 | +### Filtrage | |
| 71 | + | |
| 72 | +| Fenêtre au premier plan | Snippets proposés | | |
| 73 | +| --- | --- | | |
| 74 | +| Un fichier d'un langage reconnu | Ceux qui nomment ce langage, plus ceux qui n'en nomment aucun | | |
| 75 | +| Un fichier d'aucun langage reconnu | Ceux qui n'en nomment aucun | | |
| 76 | +| Un terminal, l'arbre du projet, ou rien | Ceux qui n'en nomment aucun | | |
| 77 | + | |
| 78 | +## Insertion | |
| 79 | + | |
| 80 | +| Comportement | Détail | | |
| 81 | +| --- | --- | | |
| 82 | +| Position | Au curseur | | |
| 83 | +| Première ligne | Insérée là où est le curseur | | |
| 84 | +| Lignes suivantes | Préfixées par l'indentation de la ligne où était le curseur | | |
| 85 | +| Lignes vides du corps | Laissées vides, non complétées d'espaces | | |
| 86 | +| Annulation | Une seule opération pour tout le snippet | | |
| 87 | +| Curseur ensuite | À la fin du texte inséré | | |
| 88 | +| Signalement | `Snippet inserted` dans la barre d'état | | |
| 89 | + | |
| 90 | +L'indentation copiée est le **préfixe d'espaces de la ligne courante**, tabulations ou espaces telles quelles : un snippet suit donc ce que le fichier emploie déjà. | |
| 91 | + | |
| 92 | +## Entrées de menu | |
| 93 | + | |
| 94 | +| Entrée | Menu | Effet | | |
| 95 | +| --- | --- | --- | | |
| 96 | +| Create snippets file | Snippets | Écrit `.turbo-python/snippets.toml` avec des exemples travaillés, puis l'ouvre. Grisée dès que le projet en a un. | | |
| 97 | +| Open snippets file | Snippets | Ouvre `.turbo-python/snippets.toml`. Grisée tant que le projet n'en a pas. Toujours le fichier du projet, jamais le vôtre — c'est celui qu'écrit l'entrée au-dessus. | | |
| 98 | + | |
| 99 | +Le fichier est écrit via un fichier temporaire du même dossier, renommé en place : une écriture interrompue laisse le fichier précédent intact. | |
| 100 | + | |
| 101 | +## Erreurs | |
| 102 | + | |
| 103 | +| Message | Cause | | |
| 104 | +| --- | --- | | |
| 105 | +| `Cannot read snippets` dans le menu | Un fichier de snippets est présent mais n'est pas du TOML valide, ou contient un snippet sans nom ou sans corps | | |
| 106 | +| `Already there: .turbo-python/snippets.toml` | Créer dans un projet qui en a déjà un. Inatteignable depuis le menu, qui grise l'entrée ; reste possible pour un appelant qui n'est pas un menu. | | |
| 107 | +| `This project has no .turbo-python/snippets.toml yet.` | Ouvrir dans un projet qui n'en a pas, de même | | |
| 108 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | |
| 109 | + | |
| 110 | +## Voir aussi | |
| 111 | + | |
| 112 | +- [Insérer des snippets depuis un menu](../how-to/use-snippets.md) | |
| 113 | +- [Snippets](../explanation/snippets.md) | |
| 114 | +- [Clavier](keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,114 @@ | |||
| 1 | +# Référence : snippets | ||
| 2 | + | ||
| 3 | +> Description neutre des fichiers de snippets, du menu Snippets, et de la façon dont un snippet est inséré. | ||
| 4 | + | ||
| 5 | +## Fichiers | ||
| 6 | + | ||
| 7 | +Les deux sont lus, et les deux sont facultatifs. | ||
| 8 | + | ||
| 9 | +| Fichier | Contient | | ||
| 10 | +| --- | --- | | ||
| 11 | +| `./.turbo-python/snippets.toml` | Les snippets du projet | | ||
| 12 | +| `$TURBO_PYTHON_SNIPPET_DIR/snippets.toml`, sinon `<config utilisateur>/turbo-python/snippets.toml` | Les vôtres, partagés entre projets | | ||
| 13 | + | ||
| 14 | +`<config utilisateur>` est `os.UserConfigDir()` : `~/.config` sous Linux, `~/Library/Application Support` sous macOS. | ||
| 15 | + | ||
| 16 | +| Propriété | Valeur | | ||
| 17 | +| --- | --- | | ||
| 18 | +| Recherche du projet | Le répertoire de travail seulement. Les dossiers parents ne sont **pas** parcourus. | | ||
| 19 | +| Lecture | À chaque ouverture du menu Snippets | | ||
| 20 | +| Ordre | Les vôtres d'abord, puis ceux du projet | | ||
| 21 | +| Conflit de nom | Même `group` **et** même `name` → celui du projet remplace le vôtre | | ||
| 22 | +| Fichier absent | Pas une erreur | | ||
| 23 | +| Fichier illisible | Une erreur, signalée dans le menu | | ||
| 24 | + | ||
| 25 | +## Format du fichier | ||
| 26 | + | ||
| 27 | +Une table `[[snippet]]` par snippet. | ||
| 28 | + | ||
| 29 | +| Clé | Type | Obligatoire | Description | | ||
| 30 | +| --- | --- | --- | --- | | ||
| 31 | +| `name` | chaîne | oui | Ce que le menu affiche | | ||
| 32 | +| `body` | chaîne | oui | Le texte inséré au curseur | | ||
| 33 | +| `group` | chaîne | non | Le sous-menu où il va ; absent signifie `General` | | ||
| 34 | +| `languages` | tableau de chaînes | non | Restreint le snippet à ces langages ; absent signifie tous les fichiers | | ||
| 35 | + | ||
| 36 | +`languages` emploie les noms de langages de l'éditeur : `python`, `toml`, `yaml`, `markdown`, `javascript`, `html`, `xml`, `dockerfile`, `bash`. Voir [Langages colorés](languages.md). | ||
| 37 | + | ||
| 38 | +Un snippet sans `name` ou sans `body` rend tout le fichier erroné — il n'aurait pu être affiché, ou n'aurait rien à insérer. | ||
| 39 | + | ||
| 40 | +### Exemple | ||
| 41 | + | ||
| 42 | +```toml | ||
| 43 | +[[snippet]] | ||
| 44 | +name = "if err != nil" | ||
| 45 | +group = "Python" | ||
| 46 | +languages = ["python"] | ||
| 47 | +body = """ | ||
| 48 | +if err != nil { | ||
| 49 | + return err | ||
| 50 | +}""" | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +Les chaînes `"""` du TOML suppriment le saut de ligne qui suit immédiatement les guillemets d'ouverture, et interprètent `\t` comme une tabulation. | ||
| 54 | + | ||
| 55 | +## Le menu | ||
| 56 | + | ||
| 57 | +| Entrée | Condition | | ||
| 58 | +| --- | --- | | ||
| 59 | +| Un sous-menu par groupe, dans l'ordre d'apparition des groupes dans les fichiers | Un groupe ayant au moins un snippet applicable à la fenêtre au premier plan | | ||
| 60 | +| `Cannot read snippets`, grisé | Un fichier est présent mais illisible | | ||
| 61 | +| `Create snippets file` | Le projet n'a pas de fichier d'extraits | | ||
| 62 | +| `Open snippets file` | Le projet en a un | | ||
| 63 | + | ||
| 64 | +La touche d'accès du menu est `Alt-N`, pas `Alt-S` : Search répond déjà au S. | ||
| 65 | + | ||
| 66 | +Les groupes, et les snippets à l'intérieur, sortent dans l'ordre de lecture : le menu correspond aux fichiers. | ||
| 67 | + | ||
| 68 | +Une entrée de snippet est grisée quand aucun fichier n'est ouvert pour l'y insérer — un terminal ou l'arbre du projet au premier plan compte comme aucun fichier. | ||
| 69 | + | ||
| 70 | +### Filtrage | ||
| 71 | + | ||
| 72 | +| Fenêtre au premier plan | Snippets proposés | | ||
| 73 | +| --- | --- | | ||
| 74 | +| Un fichier d'un langage reconnu | Ceux qui nomment ce langage, plus ceux qui n'en nomment aucun | | ||
| 75 | +| Un fichier d'aucun langage reconnu | Ceux qui n'en nomment aucun | | ||
| 76 | +| Un terminal, l'arbre du projet, ou rien | Ceux qui n'en nomment aucun | | ||
| 77 | + | ||
| 78 | +## Insertion | ||
| 79 | + | ||
| 80 | +| Comportement | Détail | | ||
| 81 | +| --- | --- | | ||
| 82 | +| Position | Au curseur | | ||
| 83 | +| Première ligne | Insérée là où est le curseur | | ||
| 84 | +| Lignes suivantes | Préfixées par l'indentation de la ligne où était le curseur | | ||
| 85 | +| Lignes vides du corps | Laissées vides, non complétées d'espaces | | ||
| 86 | +| Annulation | Une seule opération pour tout le snippet | | ||
| 87 | +| Curseur ensuite | À la fin du texte inséré | | ||
| 88 | +| Signalement | `Snippet inserted` dans la barre d'état | | ||
| 89 | + | ||
| 90 | +L'indentation copiée est le **préfixe d'espaces de la ligne courante**, tabulations ou espaces telles quelles : un snippet suit donc ce que le fichier emploie déjà. | ||
| 91 | + | ||
| 92 | +## Entrées de menu | ||
| 93 | + | ||
| 94 | +| Entrée | Menu | Effet | | ||
| 95 | +| --- | --- | --- | | ||
| 96 | +| Create snippets file | Snippets | Écrit `.turbo-python/snippets.toml` avec des exemples travaillés, puis l'ouvre. Grisée dès que le projet en a un. | | ||
| 97 | +| Open snippets file | Snippets | Ouvre `.turbo-python/snippets.toml`. Grisée tant que le projet n'en a pas. Toujours le fichier du projet, jamais le vôtre — c'est celui qu'écrit l'entrée au-dessus. | | ||
| 98 | + | ||
| 99 | +Le fichier est écrit via un fichier temporaire du même dossier, renommé en place : une écriture interrompue laisse le fichier précédent intact. | ||
| 100 | + | ||
| 101 | +## Erreurs | ||
| 102 | + | ||
| 103 | +| Message | Cause | | ||
| 104 | +| --- | --- | | ||
| 105 | +| `Cannot read snippets` dans le menu | Un fichier de snippets est présent mais n'est pas du TOML valide, ou contient un snippet sans nom ou sans corps | | ||
| 106 | +| `Already there: .turbo-python/snippets.toml` | Créer dans un projet qui en a déjà un. Inatteignable depuis le menu, qui grise l'entrée ; reste possible pour un appelant qui n'est pas un menu. | | ||
| 107 | +| `This project has no .turbo-python/snippets.toml yet.` | Ouvrir dans un projet qui n'en a pas, de même | | ||
| 108 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | ||
| 109 | + | ||
| 110 | +## Voir aussi | ||
| 111 | + | ||
| 112 | +- [Insérer des snippets depuis un menu](../how-to/use-snippets.md) | ||
| 113 | +- [Snippets](../explanation/snippets.md) | ||
| 114 | +- [Clavier](keyboard.md) | ||
added
docs/fr/reference/terminal.md +228 -0 | new file mode 100644 | ||
| @@ -0,0 +1,228 @@ | ||
| 1 | +# Référence : fenêtres terminal | |
| 2 | + | |
| 3 | +> Description neutre des fenêtres terminal ouvertes par Turbo Python, des touches auxquelles elles répondent et des séquences d'échappement que l'émulateur implémente. | |
| 4 | + | |
| 5 | +## Ouverture | |
| 6 | + | |
| 7 | +| Chemin | Condition | | |
| 8 | +| --- | --- | | |
| 9 | +| `F8` | Toujours | | |
| 10 | +| **Window ▸ New terminal** | Toujours | | |
| 11 | + | |
| 12 | +Aucun des deux n'exige qu'un fichier soit ouvert. | |
| 13 | + | |
| 14 | +## Le shell | |
| 15 | + | |
| 16 | +| Propriété | Valeur | | |
| 17 | +| --- | --- | | |
| 18 | +| Programme | `$SHELL`, ou `/bin/sh` si la variable est absente ou vide ; sous Windows `%COMSPEC%`, ou `cmd.exe` | | |
| 19 | +| Répertoire de travail | Le dossier du fichier de la fenêtre au premier plan ; le répertoire de travail de l'éditeur si aucun fichier n'est ouvert | | |
| 20 | +| `TERM` | `xterm-256color`, toujours — remplaçant toute valeur héritée | | |
| 21 | +| Environnement | Celui de l'éditeur, avec `TERM` remplacé | | |
| 22 | +| Terminal de contrôle | Oui : sous Linux et macOS le shell tourne dans sa propre session avec le pseudo-terminal comme terminal de contrôle ; sous Windows il est attaché à une pseudo-console. Dans les deux cas le contrôle de tâches et `Ctrl-C` fonctionnent | | |
| 23 | +| Taille initiale | Celle de la fenêtre, mise à jour à chaque redimensionnement | | |
| 24 | + | |
| 25 | +## Plateformes supportées | |
| 26 | + | |
| 27 | +| Plateforme | Comportement | | |
| 28 | +| --- | --- | | |
| 29 | +| Linux | Supportée (`/dev/ptmx`) | | |
| 30 | +| macOS | Supportée (`/dev/ptmx`) | | |
| 31 | +| Windows | Supportée (pseudo-console, ConPTY) : Windows 10 version 1809 ou plus récent. Compilé et vérifié ; **pas encore exécuté par les auteurs** sur une machine Windows | | |
| 32 | +| Autres | `F8` ouvre un message indiquant que les fenêtres terminal ne sont pas encore supportées ; rien d'autre ne change | | |
| 33 | + | |
| 34 | +## Touches | |
| 35 | + | |
| 36 | +### Après la fin du programme | |
| 37 | + | |
| 38 | +Une fenêtre dont la commande est terminée garde sa sortie mais cesse de se comporter comme un terminal : seules `Maj-Page↑` et `Maj-Page↓` sont encore prises, et toute autre touche atteint l'éditeur — c'est ce qui permet à `Ctrl-W` de la fermer. | |
| 39 | + | |
| 40 | +### Envoyées au shell | |
| 41 | + | |
| 42 | +Toute touche non listée ci-dessous sous « conservées par l'éditeur », encodée comme un terminal l'attend. | |
| 43 | + | |
| 44 | +| Touche | Octets envoyés | | |
| 45 | +| --- | --- | | |
| 46 | +| caractère imprimable | son encodage UTF-8 | | |
| 47 | +| `Alt-<touche>` | `ESC` suivi des octets de cette touche | | |
| 48 | +| `Ctrl-A` … `Ctrl-Z` | `0x01` … `0x1a` | | |
| 49 | +| `Enter` | `\r` | | |
| 50 | +| `Tab` | `\t` | | |
| 51 | +| `Shift-Tab` | `ESC [ Z` | | |
| 52 | +| `Backspace` | `0x7f` | | |
| 53 | +| `Escape` | `0x1b` | | |
| 54 | +| `↑` `↓` `→` `←` | `ESC [ A B C D`, ou `ESC O A B C D` en mode curseur application | | |
| 55 | +| `Home` `End` | `ESC [ H`, `ESC [ F`, ou les formes `ESC O` en mode curseur application | | |
| 56 | +| `Insert` `Delete` | `ESC [ 2~`, `ESC [ 3~` | | |
| 57 | +| `PgUp` `PgDn` | `ESC [ 5~`, `ESC [ 6~` | | |
| 58 | +| `F1` … `F4` | `ESC O P Q R S` | | |
| 59 | +| `F5` … `F12` | `ESC [ 15~ 17~ 18~ 19~ 20~ 21~ 23~ 24~` | | |
| 60 | + | |
| 61 | +Une touche sans signification pour un terminal n'envoie rien. | |
| 62 | + | |
| 63 | +### Conservées par l'éditeur | |
| 64 | + | |
| 65 | +| Touche | Action | | |
| 66 | +| --- | --- | | |
| 67 | +| `F1` … `F12` | Leur action habituelle dans l'éditeur | | |
| 68 | +| `Alt-X` | Quitter | | |
| 69 | +| `Alt-0` … `Alt-9` | Lister les fenêtres / passer la fenêtre 1…9 au premier plan | | |
| 70 | + | |
| 71 | +Les touches de fonction n'atteignent donc jamais un programme lancé dans une fenêtre terminal. | |
| 72 | + | |
| 73 | +### Traitées par la fenêtre terminal elle-même | |
| 74 | + | |
| 75 | +| Touche | Action | | |
| 76 | +| --- | --- | | |
| 77 | +| `Shift-PgUp` | Reculer d'un écran dans l'historique | | |
| 78 | +| `Shift-PgDn` | Avancer d'un écran | | |
| 79 | + | |
| 80 | +Toute touche envoyée au shell ramène également la vue à l'écran vivant. | |
| 81 | + | |
| 82 | +## Souris | |
| 83 | + | |
| 84 | +| Action | Effet | | |
| 85 | +| --- | --- | | |
| 86 | +| Molette haut / bas | Défiler de trois lignes dans l'historique | | |
| 87 | +| Clic | Passe la fenêtre au premier plan ; n'est pas transmis au programme | | |
| 88 | + | |
| 89 | +Le rapport souris n'est pas implémenté : un programme n'est jamais informé des clics. | |
| 90 | + | |
| 91 | +## Historique | |
| 92 | + | |
| 93 | +| Propriété | Valeur | | |
| 94 | +| --- | --- | | |
| 95 | +| Lignes conservées | 2000 | | |
| 96 | +| Ce qui est conservé | Uniquement les lignes sorties par le haut de l'écran principal | | |
| 97 | +| Écran alternatif | Non conservé — un programme plein écran ne laisse aucun historique | | |
| 98 | + | |
| 99 | +## Émulation | |
| 100 | + | |
| 101 | +`TERM` vaut `xterm-256color`. Voici ce qui en est implémenté. | |
| 102 | + | |
| 103 | +### Caractères de contrôle | |
| 104 | + | |
| 105 | +| Octet | Effet | | |
| 106 | +| --- | --- | | |
| 107 | +| `0x07` BEL | Noté ; l'éditeur ne l'émet pas | | |
| 108 | +| `0x08` BS | Curseur d'une colonne à gauche | | |
| 109 | +| `0x09` HT | Jusqu'à la tabulation suivante, toutes les 8 colonnes | | |
| 110 | +| `0x0a` `0x0b` `0x0c` | Saut de ligne | | |
| 111 | +| `0x0d` CR | Colonne 1 | | |
| 112 | + | |
| 113 | +### Séquences d'échappement | |
| 114 | + | |
| 115 | +| Séquence | Nom | Effet | | |
| 116 | +| --- | --- | --- | | |
| 117 | +| `ESC D` | IND | Saut de ligne | | |
| 118 | +| `ESC E` | NEL | Retour chariot et saut de ligne | | |
| 119 | +| `ESC M` | RI | Saut de ligne inverse, en conservant la colonne | | |
| 120 | +| `ESC 7` | DECSC | Sauvegarder le curseur et le style | | |
| 121 | +| `ESC 8` | DECRC | Les restaurer | | |
| 122 | +| `ESC c` | RIS | Réinitialisation complète | | |
| 123 | + | |
| 124 | +### Séquences CSI | |
| 125 | + | |
| 126 | +| Séquence | Nom | Effet | | |
| 127 | +| --- | --- | --- | | |
| 128 | +| `CSI n A B C D` | CUU CUD CUF CUB | Déplacer de n cellules haut, bas, droite, gauche | | |
| 129 | +| `CSI n E F` | CNL CPL | n lignes plus bas / plus haut, colonne 1 | | |
| 130 | +| `CSI n G` | CHA | Aller à la colonne n | | |
| 131 | +| `CSI l ; c H`, `CSI l ; c f` | CUP HVP | Aller à la ligne l, colonne c | | |
| 132 | +| `CSI n d` | VPA | Aller à la ligne n | | |
| 133 | +| `CSI n J` | ED | Effacer l'écran : 0 jusqu'à la fin, 1 jusqu'au début, 2 ou 3 tout | | |
| 134 | +| `CSI n K` | EL | Effacer la ligne : 0 jusqu'à la fin, 1 jusqu'au début, 2 tout | | |
| 135 | +| `CSI n L` | IL | Insérer n lignes vides au curseur | | |
| 136 | +| `CSI n M` | DL | Supprimer n lignes au curseur | | |
| 137 | +| `CSI n @` | ICH | Insérer n cellules vides | | |
| 138 | +| `CSI n P` | DCH | Supprimer n cellules | | |
| 139 | +| `CSI n X` | ECH | Effacer n cellules sur place | | |
| 140 | +| `CSI n S` | SU | Faire défiler la région de n lignes vers le haut | | |
| 141 | +| `CSI n T` | SD | Faire défiler la région de n lignes vers le bas | | |
| 142 | +| `CSI h ; b r` | DECSTBM | Définir la région de défilement aux lignes h…b | | |
| 143 | +| `CSI s`, `CSI u` | SCP RCP | Sauvegarder / restaurer le curseur | | |
| 144 | +| `CSI … m` | SGR | Couleurs et attributs, ci-dessous | | |
| 145 | + | |
| 146 | +`IL` et `DL` ne font rien lorsque le curseur est hors de la région de défilement. | |
| 147 | + | |
| 148 | +### Modes privés | |
| 149 | + | |
| 150 | +Activés par `CSI ? n h`, désactivés par `CSI ? n l`. | |
| 151 | + | |
| 152 | +| n | Nom | Effet | | |
| 153 | +| --- | --- | --- | | |
| 154 | +| 1 | DECCKM | Touches curseur application : les flèches envoient `ESC O x` | | |
| 155 | +| 7 | DECAWM | Retour à la ligne automatique à la marge droite | | |
| 156 | +| 25 | DECTCEM | Afficher le curseur | | |
| 157 | +| 47, 1047 | | Écran alternatif | | |
| 158 | +| 1048 | | Sauvegarder / restaurer le curseur | | |
| 159 | +| 1049 | | Sauvegarder le curseur, puis l'écran alternatif | | |
| 160 | + | |
| 161 | +Tout autre mode est analysé et ignoré. | |
| 162 | + | |
| 163 | +### SGR | |
| 164 | + | |
| 165 | +| Code | Effet | | |
| 166 | +| --- | --- | | |
| 167 | +| 0 | Réinitialisation | | |
| 168 | +| 1, 22 | Gras activé / désactivé | | |
| 169 | +| 2, 22 | Atténué activé / désactivé | | |
| 170 | +| 3, 23 | Italique activé / désactivé | | |
| 171 | +| 4, 24 | Souligné activé / désactivé | | |
| 172 | +| 5, 6, 25 | Clignotement activé / désactivé | | |
| 173 | +| 7, 27 | Vidéo inverse activée / désactivée | | |
| 174 | +| 9, 29 | Barré activé / désactivé | | |
| 175 | +| 30–37, 40–47 | Les huit couleurs normales, premier plan / fond | | |
| 176 | +| 90–97, 100–107 | Les huit couleurs vives, premier plan / fond | | |
| 177 | +| 38;5;n, 48;5;n | Couleur n de la palette de 256 | | |
| 178 | +| 38;2;r;g;b, 48;2;r;g;b | Couleur 24 bits | | |
| 179 | +| 39, 49 | Retour à la couleur du thème | | |
| 180 | + | |
| 181 | +Les seize couleurs nommées sont celles de tcell, c'est-à-dire la palette configurée dans le terminal de l'utilisateur, et non des valeurs hexadécimales figées. Une couleur étendue à court de paramètres laisse le style inchangé. Tout autre code est ignoré. | |
| 182 | + | |
| 183 | +### OSC | |
| 184 | + | |
| 185 | +| Séquence | Effet | | |
| 186 | +| --- | --- | | |
| 187 | +| `OSC 0 ; texte BEL`, `OSC 2 ; texte BEL` | Définir le titre de la fenêtre | | |
| 188 | +| `OSC … ST` | Le terminateur `ESC \` est accepté à la place de BEL | | |
| 189 | + | |
| 190 | +Le titre est plafonné à 4096 octets. Les autres commandes OSC sont analysées et ignorées. | |
| 191 | + | |
| 192 | +### Consommées et ignorées | |
| 193 | + | |
| 194 | +Analysées correctement, donc jamais affichées comme des caractères parasites, mais sans effet : | |
| 195 | + | |
| 196 | +| Séquence | Nom | | |
| 197 | +| --- | --- | | |
| 198 | +| `ESC P …`, `ESC X …`, `ESC ^ …`, `ESC _ …` | DCS, SOS, PM, APC — lues jusqu'à leur terminateur de chaîne | | |
| 199 | +| `ESC (`, `ESC )`, `ESC *`, `ESC +`, `ESC %`, `ESC #`, `ESC <espace>` | Sélecteurs de jeu de caractères et de taille de ligne — l'émulateur travaille en UTF-8 de toute façon | | |
| 200 | +| `CSI ? n h`, `CSI ? n l` pour tout autre n | Modes privés non listés ci-dessus | | |
| 201 | +| Tout autre octet final CSI, code SGR ou commande OSC | | | |
| 202 | + | |
| 203 | +### Non implémenté | |
| 204 | + | |
| 205 | +Le rapport souris, le collage entre crochets, les bascules shift-in / shift-out, les lignes double largeur, sixel et les autres protocoles graphiques, ainsi que les rapports d'état et d'attributs DEC. Un programme qui en demande un n'obtient aucune réponse : celui qui en attend une attendra indéfiniment. | |
| 206 | + | |
| 207 | +## Couleurs | |
| 208 | + | |
| 209 | +| Clé de thème | Ce qu'elle colore | | |
| 210 | +| --- | --- | | |
| 211 | +| `terminal.text` | Toute cellule dont le programme n'a pas choisi la couleur | | |
| 212 | +| `terminal.cursor` | La cellule sous le curseur, quand la fenêtre a le focus | | |
| 213 | + | |
| 214 | +Voir [Format des fichiers de thème](themes.md). | |
| 215 | + | |
| 216 | +## Erreurs | |
| 217 | + | |
| 218 | +| Message | Cause | | |
| 219 | +| --- | --- | | |
| 220 | +| Terminal windows are not supported on this platform yet | La compilation n'a pas de support des pseudo-terminaux : toute plateforme autre que Linux, macOS et Windows | | |
| 221 | +| `openpt: …`, `grantpt: …`, `ptsname: …` | Le système d'exploitation a refusé d'ouvrir un pseudo-terminal | | |
| 222 | +| `fork/exec …: no such file or directory` | `$SHELL` désigne un programme inexistant | | |
| 223 | + | |
| 224 | +## Voir aussi | |
| 225 | + | |
| 226 | +- [Lancer des commandes shell sans quitter l'éditeur](../how-to/use-a-terminal.md) | |
| 227 | +- [Fenêtres terminal](../explanation/terminal-windows.md) | |
| 228 | +- [Clavier](keyboard.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,228 @@ | |||
| 1 | +# Référence : fenêtres terminal | ||
| 2 | + | ||
| 3 | +> Description neutre des fenêtres terminal ouvertes par Turbo Python, des touches auxquelles elles répondent et des séquences d'échappement que l'émulateur implémente. | ||
| 4 | + | ||
| 5 | +## Ouverture | ||
| 6 | + | ||
| 7 | +| Chemin | Condition | | ||
| 8 | +| --- | --- | | ||
| 9 | +| `F8` | Toujours | | ||
| 10 | +| **Window ▸ New terminal** | Toujours | | ||
| 11 | + | ||
| 12 | +Aucun des deux n'exige qu'un fichier soit ouvert. | ||
| 13 | + | ||
| 14 | +## Le shell | ||
| 15 | + | ||
| 16 | +| Propriété | Valeur | | ||
| 17 | +| --- | --- | | ||
| 18 | +| Programme | `$SHELL`, ou `/bin/sh` si la variable est absente ou vide ; sous Windows `%COMSPEC%`, ou `cmd.exe` | | ||
| 19 | +| Répertoire de travail | Le dossier du fichier de la fenêtre au premier plan ; le répertoire de travail de l'éditeur si aucun fichier n'est ouvert | | ||
| 20 | +| `TERM` | `xterm-256color`, toujours — remplaçant toute valeur héritée | | ||
| 21 | +| Environnement | Celui de l'éditeur, avec `TERM` remplacé | | ||
| 22 | +| Terminal de contrôle | Oui : sous Linux et macOS le shell tourne dans sa propre session avec le pseudo-terminal comme terminal de contrôle ; sous Windows il est attaché à une pseudo-console. Dans les deux cas le contrôle de tâches et `Ctrl-C` fonctionnent | | ||
| 23 | +| Taille initiale | Celle de la fenêtre, mise à jour à chaque redimensionnement | | ||
| 24 | + | ||
| 25 | +## Plateformes supportées | ||
| 26 | + | ||
| 27 | +| Plateforme | Comportement | | ||
| 28 | +| --- | --- | | ||
| 29 | +| Linux | Supportée (`/dev/ptmx`) | | ||
| 30 | +| macOS | Supportée (`/dev/ptmx`) | | ||
| 31 | +| Windows | Supportée (pseudo-console, ConPTY) : Windows 10 version 1809 ou plus récent. Compilé et vérifié ; **pas encore exécuté par les auteurs** sur une machine Windows | | ||
| 32 | +| Autres | `F8` ouvre un message indiquant que les fenêtres terminal ne sont pas encore supportées ; rien d'autre ne change | | ||
| 33 | + | ||
| 34 | +## Touches | ||
| 35 | + | ||
| 36 | +### Après la fin du programme | ||
| 37 | + | ||
| 38 | +Une fenêtre dont la commande est terminée garde sa sortie mais cesse de se comporter comme un terminal : seules `Maj-Page↑` et `Maj-Page↓` sont encore prises, et toute autre touche atteint l'éditeur — c'est ce qui permet à `Ctrl-W` de la fermer. | ||
| 39 | + | ||
| 40 | +### Envoyées au shell | ||
| 41 | + | ||
| 42 | +Toute touche non listée ci-dessous sous « conservées par l'éditeur », encodée comme un terminal l'attend. | ||
| 43 | + | ||
| 44 | +| Touche | Octets envoyés | | ||
| 45 | +| --- | --- | | ||
| 46 | +| caractère imprimable | son encodage UTF-8 | | ||
| 47 | +| `Alt-<touche>` | `ESC` suivi des octets de cette touche | | ||
| 48 | +| `Ctrl-A` … `Ctrl-Z` | `0x01` … `0x1a` | | ||
| 49 | +| `Enter` | `\r` | | ||
| 50 | +| `Tab` | `\t` | | ||
| 51 | +| `Shift-Tab` | `ESC [ Z` | | ||
| 52 | +| `Backspace` | `0x7f` | | ||
| 53 | +| `Escape` | `0x1b` | | ||
| 54 | +| `↑` `↓` `→` `←` | `ESC [ A B C D`, ou `ESC O A B C D` en mode curseur application | | ||
| 55 | +| `Home` `End` | `ESC [ H`, `ESC [ F`, ou les formes `ESC O` en mode curseur application | | ||
| 56 | +| `Insert` `Delete` | `ESC [ 2~`, `ESC [ 3~` | | ||
| 57 | +| `PgUp` `PgDn` | `ESC [ 5~`, `ESC [ 6~` | | ||
| 58 | +| `F1` … `F4` | `ESC O P Q R S` | | ||
| 59 | +| `F5` … `F12` | `ESC [ 15~ 17~ 18~ 19~ 20~ 21~ 23~ 24~` | | ||
| 60 | + | ||
| 61 | +Une touche sans signification pour un terminal n'envoie rien. | ||
| 62 | + | ||
| 63 | +### Conservées par l'éditeur | ||
| 64 | + | ||
| 65 | +| Touche | Action | | ||
| 66 | +| --- | --- | | ||
| 67 | +| `F1` … `F12` | Leur action habituelle dans l'éditeur | | ||
| 68 | +| `Alt-X` | Quitter | | ||
| 69 | +| `Alt-0` … `Alt-9` | Lister les fenêtres / passer la fenêtre 1…9 au premier plan | | ||
| 70 | + | ||
| 71 | +Les touches de fonction n'atteignent donc jamais un programme lancé dans une fenêtre terminal. | ||
| 72 | + | ||
| 73 | +### Traitées par la fenêtre terminal elle-même | ||
| 74 | + | ||
| 75 | +| Touche | Action | | ||
| 76 | +| --- | --- | | ||
| 77 | +| `Shift-PgUp` | Reculer d'un écran dans l'historique | | ||
| 78 | +| `Shift-PgDn` | Avancer d'un écran | | ||
| 79 | + | ||
| 80 | +Toute touche envoyée au shell ramène également la vue à l'écran vivant. | ||
| 81 | + | ||
| 82 | +## Souris | ||
| 83 | + | ||
| 84 | +| Action | Effet | | ||
| 85 | +| --- | --- | | ||
| 86 | +| Molette haut / bas | Défiler de trois lignes dans l'historique | | ||
| 87 | +| Clic | Passe la fenêtre au premier plan ; n'est pas transmis au programme | | ||
| 88 | + | ||
| 89 | +Le rapport souris n'est pas implémenté : un programme n'est jamais informé des clics. | ||
| 90 | + | ||
| 91 | +## Historique | ||
| 92 | + | ||
| 93 | +| Propriété | Valeur | | ||
| 94 | +| --- | --- | | ||
| 95 | +| Lignes conservées | 2000 | | ||
| 96 | +| Ce qui est conservé | Uniquement les lignes sorties par le haut de l'écran principal | | ||
| 97 | +| Écran alternatif | Non conservé — un programme plein écran ne laisse aucun historique | | ||
| 98 | + | ||
| 99 | +## Émulation | ||
| 100 | + | ||
| 101 | +`TERM` vaut `xterm-256color`. Voici ce qui en est implémenté. | ||
| 102 | + | ||
| 103 | +### Caractères de contrôle | ||
| 104 | + | ||
| 105 | +| Octet | Effet | | ||
| 106 | +| --- | --- | | ||
| 107 | +| `0x07` BEL | Noté ; l'éditeur ne l'émet pas | | ||
| 108 | +| `0x08` BS | Curseur d'une colonne à gauche | | ||
| 109 | +| `0x09` HT | Jusqu'à la tabulation suivante, toutes les 8 colonnes | | ||
| 110 | +| `0x0a` `0x0b` `0x0c` | Saut de ligne | | ||
| 111 | +| `0x0d` CR | Colonne 1 | | ||
| 112 | + | ||
| 113 | +### Séquences d'échappement | ||
| 114 | + | ||
| 115 | +| Séquence | Nom | Effet | | ||
| 116 | +| --- | --- | --- | | ||
| 117 | +| `ESC D` | IND | Saut de ligne | | ||
| 118 | +| `ESC E` | NEL | Retour chariot et saut de ligne | | ||
| 119 | +| `ESC M` | RI | Saut de ligne inverse, en conservant la colonne | | ||
| 120 | +| `ESC 7` | DECSC | Sauvegarder le curseur et le style | | ||
| 121 | +| `ESC 8` | DECRC | Les restaurer | | ||
| 122 | +| `ESC c` | RIS | Réinitialisation complète | | ||
| 123 | + | ||
| 124 | +### Séquences CSI | ||
| 125 | + | ||
| 126 | +| Séquence | Nom | Effet | | ||
| 127 | +| --- | --- | --- | | ||
| 128 | +| `CSI n A B C D` | CUU CUD CUF CUB | Déplacer de n cellules haut, bas, droite, gauche | | ||
| 129 | +| `CSI n E F` | CNL CPL | n lignes plus bas / plus haut, colonne 1 | | ||
| 130 | +| `CSI n G` | CHA | Aller à la colonne n | | ||
| 131 | +| `CSI l ; c H`, `CSI l ; c f` | CUP HVP | Aller à la ligne l, colonne c | | ||
| 132 | +| `CSI n d` | VPA | Aller à la ligne n | | ||
| 133 | +| `CSI n J` | ED | Effacer l'écran : 0 jusqu'à la fin, 1 jusqu'au début, 2 ou 3 tout | | ||
| 134 | +| `CSI n K` | EL | Effacer la ligne : 0 jusqu'à la fin, 1 jusqu'au début, 2 tout | | ||
| 135 | +| `CSI n L` | IL | Insérer n lignes vides au curseur | | ||
| 136 | +| `CSI n M` | DL | Supprimer n lignes au curseur | | ||
| 137 | +| `CSI n @` | ICH | Insérer n cellules vides | | ||
| 138 | +| `CSI n P` | DCH | Supprimer n cellules | | ||
| 139 | +| `CSI n X` | ECH | Effacer n cellules sur place | | ||
| 140 | +| `CSI n S` | SU | Faire défiler la région de n lignes vers le haut | | ||
| 141 | +| `CSI n T` | SD | Faire défiler la région de n lignes vers le bas | | ||
| 142 | +| `CSI h ; b r` | DECSTBM | Définir la région de défilement aux lignes h…b | | ||
| 143 | +| `CSI s`, `CSI u` | SCP RCP | Sauvegarder / restaurer le curseur | | ||
| 144 | +| `CSI … m` | SGR | Couleurs et attributs, ci-dessous | | ||
| 145 | + | ||
| 146 | +`IL` et `DL` ne font rien lorsque le curseur est hors de la région de défilement. | ||
| 147 | + | ||
| 148 | +### Modes privés | ||
| 149 | + | ||
| 150 | +Activés par `CSI ? n h`, désactivés par `CSI ? n l`. | ||
| 151 | + | ||
| 152 | +| n | Nom | Effet | | ||
| 153 | +| --- | --- | --- | | ||
| 154 | +| 1 | DECCKM | Touches curseur application : les flèches envoient `ESC O x` | | ||
| 155 | +| 7 | DECAWM | Retour à la ligne automatique à la marge droite | | ||
| 156 | +| 25 | DECTCEM | Afficher le curseur | | ||
| 157 | +| 47, 1047 | | Écran alternatif | | ||
| 158 | +| 1048 | | Sauvegarder / restaurer le curseur | | ||
| 159 | +| 1049 | | Sauvegarder le curseur, puis l'écran alternatif | | ||
| 160 | + | ||
| 161 | +Tout autre mode est analysé et ignoré. | ||
| 162 | + | ||
| 163 | +### SGR | ||
| 164 | + | ||
| 165 | +| Code | Effet | | ||
| 166 | +| --- | --- | | ||
| 167 | +| 0 | Réinitialisation | | ||
| 168 | +| 1, 22 | Gras activé / désactivé | | ||
| 169 | +| 2, 22 | Atténué activé / désactivé | | ||
| 170 | +| 3, 23 | Italique activé / désactivé | | ||
| 171 | +| 4, 24 | Souligné activé / désactivé | | ||
| 172 | +| 5, 6, 25 | Clignotement activé / désactivé | | ||
| 173 | +| 7, 27 | Vidéo inverse activée / désactivée | | ||
| 174 | +| 9, 29 | Barré activé / désactivé | | ||
| 175 | +| 30–37, 40–47 | Les huit couleurs normales, premier plan / fond | | ||
| 176 | +| 90–97, 100–107 | Les huit couleurs vives, premier plan / fond | | ||
| 177 | +| 38;5;n, 48;5;n | Couleur n de la palette de 256 | | ||
| 178 | +| 38;2;r;g;b, 48;2;r;g;b | Couleur 24 bits | | ||
| 179 | +| 39, 49 | Retour à la couleur du thème | | ||
| 180 | + | ||
| 181 | +Les seize couleurs nommées sont celles de tcell, c'est-à-dire la palette configurée dans le terminal de l'utilisateur, et non des valeurs hexadécimales figées. Une couleur étendue à court de paramètres laisse le style inchangé. Tout autre code est ignoré. | ||
| 182 | + | ||
| 183 | +### OSC | ||
| 184 | + | ||
| 185 | +| Séquence | Effet | | ||
| 186 | +| --- | --- | | ||
| 187 | +| `OSC 0 ; texte BEL`, `OSC 2 ; texte BEL` | Définir le titre de la fenêtre | | ||
| 188 | +| `OSC … ST` | Le terminateur `ESC \` est accepté à la place de BEL | | ||
| 189 | + | ||
| 190 | +Le titre est plafonné à 4096 octets. Les autres commandes OSC sont analysées et ignorées. | ||
| 191 | + | ||
| 192 | +### Consommées et ignorées | ||
| 193 | + | ||
| 194 | +Analysées correctement, donc jamais affichées comme des caractères parasites, mais sans effet : | ||
| 195 | + | ||
| 196 | +| Séquence | Nom | | ||
| 197 | +| --- | --- | | ||
| 198 | +| `ESC P …`, `ESC X …`, `ESC ^ …`, `ESC _ …` | DCS, SOS, PM, APC — lues jusqu'à leur terminateur de chaîne | | ||
| 199 | +| `ESC (`, `ESC )`, `ESC *`, `ESC +`, `ESC %`, `ESC #`, `ESC <espace>` | Sélecteurs de jeu de caractères et de taille de ligne — l'émulateur travaille en UTF-8 de toute façon | | ||
| 200 | +| `CSI ? n h`, `CSI ? n l` pour tout autre n | Modes privés non listés ci-dessus | | ||
| 201 | +| Tout autre octet final CSI, code SGR ou commande OSC | | | ||
| 202 | + | ||
| 203 | +### Non implémenté | ||
| 204 | + | ||
| 205 | +Le rapport souris, le collage entre crochets, les bascules shift-in / shift-out, les lignes double largeur, sixel et les autres protocoles graphiques, ainsi que les rapports d'état et d'attributs DEC. Un programme qui en demande un n'obtient aucune réponse : celui qui en attend une attendra indéfiniment. | ||
| 206 | + | ||
| 207 | +## Couleurs | ||
| 208 | + | ||
| 209 | +| Clé de thème | Ce qu'elle colore | | ||
| 210 | +| --- | --- | | ||
| 211 | +| `terminal.text` | Toute cellule dont le programme n'a pas choisi la couleur | | ||
| 212 | +| `terminal.cursor` | La cellule sous le curseur, quand la fenêtre a le focus | | ||
| 213 | + | ||
| 214 | +Voir [Format des fichiers de thème](themes.md). | ||
| 215 | + | ||
| 216 | +## Erreurs | ||
| 217 | + | ||
| 218 | +| Message | Cause | | ||
| 219 | +| --- | --- | | ||
| 220 | +| Terminal windows are not supported on this platform yet | La compilation n'a pas de support des pseudo-terminaux : toute plateforme autre que Linux, macOS et Windows | | ||
| 221 | +| `openpt: …`, `grantpt: …`, `ptsname: …` | Le système d'exploitation a refusé d'ouvrir un pseudo-terminal | | ||
| 222 | +| `fork/exec …: no such file or directory` | `$SHELL` désigne un programme inexistant | | ||
| 223 | + | ||
| 224 | +## Voir aussi | ||
| 225 | + | ||
| 226 | +- [Lancer des commandes shell sans quitter l'éditeur](../how-to/use-a-terminal.md) | ||
| 227 | +- [Fenêtres terminal](../explanation/terminal-windows.md) | ||
| 228 | +- [Clavier](keyboard.md) | ||
added
docs/fr/reference/themes.md +236 -0 | new file mode 100644 | ||
| @@ -0,0 +1,236 @@ | ||
| 1 | +# Référence : format des fichiers de thème | |
| 2 | + | |
| 3 | +> Description neutre et exhaustive d'un fichier de thème Turbo Python. | |
| 4 | + | |
| 5 | +Un thème est un fichier TOML. Les thèmes sont lus d'abord dans le répertoire utilisateur, puis parmi ceux embarqués dans le binaire ; un fichier utilisateur l'emporte sur un thème embarqué du même nom. | |
| 6 | + | |
| 7 | +## Emplacements | |
| 8 | + | |
| 9 | +| Emplacement | Remarques | | |
| 10 | +| --- | --- | | |
| 11 | +| `$TURBO_PYTHON_THEME_DIR` | Utilisé quand la variable est définie et non vide. | | |
| 12 | +| `~/.config/turbo-python/themes` | Linux (`os.UserConfigDir`). | | |
| 13 | +| `~/Library/Application Support/turbo-python/themes` | macOS. | | |
| 14 | +| embarqués | `turbo-classic`, `turbo-dark`, `borland-light`, `cappuccino`, `catppuccin-frappe`, `catppuccin-latte`, `cobalt`, `darcula`, `intellij-light`, `monochrome-dark`, `monochrome-light`. | | |
| 15 | + | |
| 16 | +Le **nom** d'un thème pour `-theme` et pour `Options ▸ Theme…` est son nom de fichier sans `.toml`. Il ne peut contenir ni `/`, ni `\`, ni `..`. | |
| 17 | + | |
| 18 | +## Les thèmes livrés | |
| 19 | + | |
| 20 | +| Nom | Fond | Pour | | |
| 21 | +| --- | --- | --- | | |
| 22 | +| `turbo-classic` | Marine Borland | Le défaut : la palette de Turbo C | | |
| 23 | +| `turbo-dark` | Gris sombre neutre | Les terminaux modernes en couleurs vraies | | |
| 24 | +| `borland-light` | Blanc papier | Les pièces claires et la vidéoprojection | | |
| 25 | +| `cappuccino` | Brun expresso | La mise en page Turbo, en chaud : du lait dans le texte, du caramel là où Turbo Dark met du bleu | | |
| 26 | +| `catppuccin-frappe` | Ardoise chaude | La palette Catppuccin Frappé, inchangée : des accents pastel sur un fond doucement sombre | | |
| 27 | +| `catppuccin-latte` | Papier chaud | La palette Catppuccin Latte, inchangée : le même mappage avec la saturation qu'exige un fond clair | | |
| 28 | +| `cobalt` | Marine profond | La palette Cobalt, accents laissés aussi francs qu'on les connaît | | |
| 29 | +| `darcula` | Anthracite | D'après le Darcula de JetBrains : mots-clés orange, chaînes vertes, et la ponctuation orange qui le rend reconnaissable | | |
| 30 | +| `intellij-light` | Blanc | D'après l'IntelliJ Light de JetBrains : mots-clés bleus gras, chaînes vertes grasses | | |
| 31 | +| `monochrome-dark` | Noir et gris | Aucune teinte — le code se distingue par la luminosité, le gras, l'italique et le souligné | | |
| 32 | +| `monochrome-light` | Papier et gris | Le même, dans l'autre sens : sur papier, c'est le gris le plus foncé qui parle le plus fort | | |
| 33 | + | |
| 34 | +Chacun **énonce sa palette entière** au lieu d'en hériter l'essentiel. Un thème que vous écrivez, lui, peut hériter ; voir [en écrire un](../how-to/write-a-theme.md). | |
| 35 | + | |
| 36 | +## Un nom auquel un thème répondait autrefois | |
| 37 | + | |
| 38 | +`monochrome` se charge toujours. C'est le nom sous lequel ce thème était livré avant que `monochrome-light` ne le rejoigne et que la paire ne soit renommée : un fichier de réglages ou un `-theme` disant `monochrome` obtient `monochrome-dark`. | |
| 39 | + | |
| 40 | +| Nom retiré | Charge | | |
| 41 | +| --- | --- | | |
| 42 | +| `monochrome` | `monochrome-dark` | | |
| 43 | + | |
| 44 | +Un nom retiré n'est **pas** listé par `-theme` ni par **Options ▸ Theme…** : chaque thème n'apparaît donc qu'une fois, sous le nom qu'il porte aujourd'hui. Un thème à vous nommé `monochrome.toml` l'emporte quand même sur lui, exactement comme pour n'importe quel autre nom. | |
| 45 | + | |
| 46 | +## Champs de premier niveau | |
| 47 | + | |
| 48 | +| Champ | Type | Défaut | Description | | |
| 49 | +| --- | --- | --- | --- | | |
| 50 | +| `name` | chaîne | le nom du fichier | Nom affiché, dans le sélecteur de thème et la boîte À propos. | | |
| 51 | +| `description` | chaîne | `""` | Une ligne, affichée par `-list-themes`. | | |
| 52 | +| `inherits` | chaîne | aucun | Nom d'un thème dont partir. Ses styles résolus servent de base ; ce fichier redéfinit ce qu'il nomme. Les chaînes sont plafonnées à 16 sauts. | | |
| 53 | +| `colors` | table | `{}` | Les styles. Les clés sont celles listées plus bas. | | |
| 54 | + | |
| 55 | +## Champs d'une entrée | |
| 56 | + | |
| 57 | +Chaque valeur sous `[colors]` est une table en ligne : | |
| 58 | + | |
| 59 | +| Champ | Type | Défaut | Description | | |
| 60 | +| --- | --- | --- | --- | | |
| 61 | +| `fg` | chaîne | hérité | Couleur de premier plan. | | |
| 62 | +| `bg` | chaîne | hérité | Couleur de fond. | | |
| 63 | +| `bold` | booléen | `false` | Activer le gras. | | |
| 64 | +| `underline` | booléen | `false` | Activer le souligné. | | |
| 65 | +| `italic` | booléen | `false` | Activer l'italique. | | |
| 66 | +| `reverse` | booléen | `false` | Échanger premier plan et fond. | | |
| 67 | +| `dim` | booléen | `false` | Activer l'atténuation. | | |
| 68 | +| `blink` | booléen | `false` | Activer le clignotement. | | |
| 69 | + | |
| 70 | +Les attributs ne sont jamais qu'**activés** ; il n'existe pas de moyen de désactiver un attribut hérité autrement qu'en n'en héritant pas. | |
| 71 | + | |
| 72 | +## Valeurs de couleur | |
| 73 | + | |
| 74 | +| Forme | Exemple | Remarques | | |
| 75 | +| --- | --- | --- | | |
| 76 | +| Nom ANSI | `navy`, `aqua`, `silver`, `fuchsia` | Les seize noms, plus la liste W3C complète. | | |
| 77 | +| Littéral hexadécimal | `#5fafd7` | 24 bits ; tcell l'approxime sur les terminaux sans couleurs vraies. | | |
| 78 | +| `default` | `default` | Ce que le terminal utilise lui-même. | | |
| 79 | +| `-` | `-` | Identique à `default`. | | |
| 80 | +| `""` | `""` | Identique à `default`. | | |
| 81 | + | |
| 82 | +Les seize noms ANSI : `black` `maroon` `green` `olive` `navy` `purple` `teal` `silver` `gray` `red` `lime` `yellow` `blue` `fuchsia` `aqua` `white`. | |
| 83 | + | |
| 84 | +Une couleur non reconnue est une **erreur de chargement**, pas un repli silencieux. | |
| 85 | + | |
| 86 | +## Clés de style | |
| 87 | + | |
| 88 | +Les clés non définies retombent le long des points, et finalement sur `default`. | |
| 89 | + | |
| 90 | +### Base | |
| 91 | + | |
| 92 | +| Clé | Ce qu'elle colore | | |
| 93 | +| --- | --- | | |
| 94 | +| `default` | Le dernier recours de toute recherche | | |
| 95 | +| `desktop` | Le fond texturé derrière les fenêtres | | |
| 96 | +| `shadow` | Les cellules qu'une fenêtre assombrit derrière elle | | |
| 97 | + | |
| 98 | +### Barre de menus | |
| 99 | + | |
| 100 | +| Clé | Ce qu'elle colore | | |
| 101 | +| --- | --- | | |
| 102 | +| `menu.bar` | La rangée de titres | | |
| 103 | +| `menu.item` | Une entrée déroulante | | |
| 104 | +| `menu.selected` | L'entrée surlignée | | |
| 105 | +| `menu.shortcut` | La lettre d'accès d'un intitulé | | |
| 106 | +| `menu.disabled` | Une entrée non choisissable | | |
| 107 | + | |
| 108 | +### Fenêtres | |
| 109 | + | |
| 110 | +| Clé | Ce qu'elle colore | | |
| 111 | +| --- | --- | | |
| 112 | +| `window.frame.active` | Le cadre de la fenêtre active | | |
| 113 | +| `window.frame.inactive` | Tous les autres cadres | | |
| 114 | +| `window.title.active` | Le titre de la fenêtre active | | |
| 115 | +| `window.title.inactive` | Tous les autres titres | | |
| 116 | +| `window.body` | L'intérieur, avant que son contenu ne se dessine | | |
| 117 | + | |
| 118 | +### Barres | |
| 119 | + | |
| 120 | +| Clé | Ce qu'elle colore | | |
| 121 | +| --- | --- | | |
| 122 | +| `statusbar` | La barre elle-même | | |
| 123 | +| `statusbar.key` | La partie `Fn` d'un indice | | |
| 124 | +| `statusbar.hint` | Le texte aligné à droite | | |
| 125 | +| `scrollbar` | La glissière d'une barre de défilement | | |
| 126 | +| `scrollbar.thumb` | Son curseur et ses flèches | | |
| 127 | + | |
| 128 | +### Dialogues et contrôles | |
| 129 | + | |
| 130 | +| Clé | Ce qu'elle colore | | |
| 131 | +| --- | --- | | |
| 132 | +| `dialog.frame` | Le cadre d'un dialogue | | |
| 133 | +| `dialog.body` | Son intérieur | | |
| 134 | +| `dialog.title` | Son titre | | |
| 135 | +| `dialog.label` | Une ligne de texte statique | | |
| 136 | +| `button` | Un bouton | | |
| 137 | +| `button.focused` | Le bouton qui a le focus | | |
| 138 | +| `button.shortcut` | La lettre d'accès d'un bouton | | |
| 139 | +| `input` | Un champ de saisie | | |
| 140 | +| `input.focused` | Le champ qui a le focus | | |
| 141 | +| `input.selection` | Le texte sélectionné dans un champ | | |
| 142 | +| `list` | Une liste | | |
| 143 | +| `list.selected` | Sa ligne surlignée, quand elle a le focus | | |
| 144 | +| `list.unfocused` | Sa ligne surlignée, sinon | | |
| 145 | +| `checkbox` | Une case à cocher | | |
| 146 | +| `checkbox.focused` | La case qui a le focus | | |
| 147 | + | |
| 148 | +### Éditeur | |
| 149 | + | |
| 150 | +| Clé | Ce qu'elle colore | | |
| 151 | +| --- | --- | | |
| 152 | +| `editor.text` | Le texte qu'aucune autre règle ne revendique | | |
| 153 | +| `editor.selection` | Le texte sélectionné | | |
| 154 | +| `editor.linenumber` | La gouttière des numéros de ligne | | |
| 155 | +| `editor.currentline` | La ligne où se trouve le curseur | | |
| 156 | +| `editor.cursor` | Le curseur. Son **fond** est aussi envoyé au terminal comme couleur de curseur, et son premier plan peint le caractère en dessous. | | |
| 157 | + | |
| 158 | +### Terminal | |
| 159 | + | |
| 160 | +| Clé | Ce qu'elle colore | | |
| 161 | +| --- | --- | | |
| 162 | +| `terminal.text` | Toute cellule d'une fenêtre terminal dont le programme qui y tourne n'a pas choisi la couleur | | |
| 163 | +| `terminal.cursor` | La cellule sous le curseur d'un terminal, quand cette fenêtre a le focus | | |
| 164 | + | |
| 165 | +Un programme qui nomme ses propres couleurs les conserve : ces deux clés ne remplissent que ce qu'il a laissé indéfini. Voir [Fenêtres terminal](terminal.md). | |
| 166 | + | |
| 167 | +### Arbre du projet | |
| 168 | + | |
| 169 | +| Clé | Ce qu'elle colore | | |
| 170 | +| --- | --- | | |
| 171 | +| `tree.text` | Le nom d'un fichier dans l'arbre, et le fond de l'arbre | | |
| 172 | +| `tree.directory` | Le nom d'un dossier | | |
| 173 | +| `tree.selected` | La ligne surlignée, quand l'arbre a le focus | | |
| 174 | +| `tree.unfocused` | La ligne surlignée, quand il ne l'a pas | | |
| 175 | + | |
| 176 | +Elles sont distinctes des clés `list.*` à dessein : la liste d'un dialogue est colorée pour ressortir sur un dialogue, et la réutiliser surlignerait une ligne d'arbre dans la couleur même qu'a déjà le corps d'une fenêtre. Voir [Arbre du projet](project-tree.md). | |
| 177 | + | |
| 178 | +### Syntaxe | |
| 179 | + | |
| 180 | +| Clé | Ce qu'elle colore | | |
| 181 | +| --- | --- | | |
| 182 | +| `syntax.identifier` | Un nom ordinaire | | |
| 183 | +| `syntax.keyword` | `func`, `if`, `package`, … | | |
| 184 | +| `syntax.type` | `int`, `string`, et un nom après `type` | | |
| 185 | +| `syntax.builtin` | `len`, `append`, `make`, … | | |
| 186 | +| `syntax.constant` | `true`, `false`, `nil`, `iota` | | |
| 187 | +| `syntax.function` | Un nom avant `(`, ou après `func` | | |
| 188 | +| `syntax.string` | Un littéral chaîne | | |
| 189 | +| `syntax.char` | Un littéral rune | | |
| 190 | +| `syntax.number` | Un littéral entier, flottant ou imaginaire | | |
| 191 | +| `syntax.comment` | `//` et `/* */` | | |
| 192 | +| `syntax.operator` | `+`, `:=`, `<-`, … | | |
| 193 | +| `syntax.punctuation` | Parenthèses, virgules, points, points-virgules | | |
| 194 | +| `syntax.heading` | Un titre Markdown, toute la ligne | | |
| 195 | +| `syntax.tag` | Un nom d'élément HTML et ses chevrons | | |
| 196 | +| `syntax.attribute` | Le nom d'un attribut HTML | | |
| 197 | +| `syntax.emphasis` | Le gras et l'italique Markdown | | |
| 198 | +| `syntax.link` | Un lien ou une image Markdown | | |
| 199 | + | |
| 200 | +Quel langage produit quelle classe est indiqué dans [Langages colorés](languages.md). | |
| 201 | + | |
| 202 | +### Complétion et diagnostics | |
| 203 | + | |
| 204 | +| Clé | Ce qu'elle colore | | |
| 205 | +| --- | --- | | |
| 206 | +| `completion.frame` | Le cadre de la liste | | |
| 207 | +| `completion.item` | Une suggestion | | |
| 208 | +| `completion.selected` | La suggestion surlignée | | |
| 209 | +| `completion.detail` | L'étiquette de nature à côté d'une suggestion | | |
| 210 | +| `diagnostic.error` | Une erreur du serveur de langage | | |
| 211 | +| `diagnostic.warning` | Un avertissement | | |
| 212 | +| `diagnostic.info` | Une note | | |
| 213 | + | |
| 214 | +## Exemple | |
| 215 | + | |
| 216 | +```toml | |
| 217 | +name = "Le mien" | |
| 218 | +description = "Turbo Classic, avec des commentaires lisibles." | |
| 219 | +inherits = "turbo-classic" | |
| 220 | + | |
| 221 | +[colors] | |
| 222 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | |
| 223 | +"syntax.string" = { fg = "#87d7af" } | |
| 224 | +"editor.currentline" = { bg = "#00005f" } | |
| 225 | +``` | |
| 226 | + | |
| 227 | +## Erreurs | |
| 228 | + | |
| 229 | +| Message | Cause | | |
| 230 | +| --- | --- | | |
| 231 | +| `theme: not found: "x"` | Aucun `x.toml` dans le répertoire utilisateur ni parmi les thèmes embarqués. | | |
| 232 | +| `theme: not found: "…" is not a plain theme name` | Le nom contient `/`, `\` ou `..`. | | |
| 233 | +| `invalid TOML: …` | Le fichier n'est pas du TOML valide. | | |
| 234 | +| `colors."k": fg: unknown colour "…"` | Le nom de couleur n'est pas reconnu. | | |
| 235 | +| `inherits: chain deeper than 16, probably a loop` | Deux thèmes héritent l'un de l'autre, directement ou par l'intermédiaire d'autres. | | |
| 236 | +| `inherits "x": theme: not found` | Le parent nommé n'existe pas. | | |
| new file mode 100644 | |||
| @@ -0,0 +1,236 @@ | |||
| 1 | +# Référence : format des fichiers de thème | ||
| 2 | + | ||
| 3 | +> Description neutre et exhaustive d'un fichier de thème Turbo Python. | ||
| 4 | + | ||
| 5 | +Un thème est un fichier TOML. Les thèmes sont lus d'abord dans le répertoire utilisateur, puis parmi ceux embarqués dans le binaire ; un fichier utilisateur l'emporte sur un thème embarqué du même nom. | ||
| 6 | + | ||
| 7 | +## Emplacements | ||
| 8 | + | ||
| 9 | +| Emplacement | Remarques | | ||
| 10 | +| --- | --- | | ||
| 11 | +| `$TURBO_PYTHON_THEME_DIR` | Utilisé quand la variable est définie et non vide. | | ||
| 12 | +| `~/.config/turbo-python/themes` | Linux (`os.UserConfigDir`). | | ||
| 13 | +| `~/Library/Application Support/turbo-python/themes` | macOS. | | ||
| 14 | +| embarqués | `turbo-classic`, `turbo-dark`, `borland-light`, `cappuccino`, `catppuccin-frappe`, `catppuccin-latte`, `cobalt`, `darcula`, `intellij-light`, `monochrome-dark`, `monochrome-light`. | | ||
| 15 | + | ||
| 16 | +Le **nom** d'un thème pour `-theme` et pour `Options ▸ Theme…` est son nom de fichier sans `.toml`. Il ne peut contenir ni `/`, ni `\`, ni `..`. | ||
| 17 | + | ||
| 18 | +## Les thèmes livrés | ||
| 19 | + | ||
| 20 | +| Nom | Fond | Pour | | ||
| 21 | +| --- | --- | --- | | ||
| 22 | +| `turbo-classic` | Marine Borland | Le défaut : la palette de Turbo C | | ||
| 23 | +| `turbo-dark` | Gris sombre neutre | Les terminaux modernes en couleurs vraies | | ||
| 24 | +| `borland-light` | Blanc papier | Les pièces claires et la vidéoprojection | | ||
| 25 | +| `cappuccino` | Brun expresso | La mise en page Turbo, en chaud : du lait dans le texte, du caramel là où Turbo Dark met du bleu | | ||
| 26 | +| `catppuccin-frappe` | Ardoise chaude | La palette Catppuccin Frappé, inchangée : des accents pastel sur un fond doucement sombre | | ||
| 27 | +| `catppuccin-latte` | Papier chaud | La palette Catppuccin Latte, inchangée : le même mappage avec la saturation qu'exige un fond clair | | ||
| 28 | +| `cobalt` | Marine profond | La palette Cobalt, accents laissés aussi francs qu'on les connaît | | ||
| 29 | +| `darcula` | Anthracite | D'après le Darcula de JetBrains : mots-clés orange, chaînes vertes, et la ponctuation orange qui le rend reconnaissable | | ||
| 30 | +| `intellij-light` | Blanc | D'après l'IntelliJ Light de JetBrains : mots-clés bleus gras, chaînes vertes grasses | | ||
| 31 | +| `monochrome-dark` | Noir et gris | Aucune teinte — le code se distingue par la luminosité, le gras, l'italique et le souligné | | ||
| 32 | +| `monochrome-light` | Papier et gris | Le même, dans l'autre sens : sur papier, c'est le gris le plus foncé qui parle le plus fort | | ||
| 33 | + | ||
| 34 | +Chacun **énonce sa palette entière** au lieu d'en hériter l'essentiel. Un thème que vous écrivez, lui, peut hériter ; voir [en écrire un](../how-to/write-a-theme.md). | ||
| 35 | + | ||
| 36 | +## Un nom auquel un thème répondait autrefois | ||
| 37 | + | ||
| 38 | +`monochrome` se charge toujours. C'est le nom sous lequel ce thème était livré avant que `monochrome-light` ne le rejoigne et que la paire ne soit renommée : un fichier de réglages ou un `-theme` disant `monochrome` obtient `monochrome-dark`. | ||
| 39 | + | ||
| 40 | +| Nom retiré | Charge | | ||
| 41 | +| --- | --- | | ||
| 42 | +| `monochrome` | `monochrome-dark` | | ||
| 43 | + | ||
| 44 | +Un nom retiré n'est **pas** listé par `-theme` ni par **Options ▸ Theme…** : chaque thème n'apparaît donc qu'une fois, sous le nom qu'il porte aujourd'hui. Un thème à vous nommé `monochrome.toml` l'emporte quand même sur lui, exactement comme pour n'importe quel autre nom. | ||
| 45 | + | ||
| 46 | +## Champs de premier niveau | ||
| 47 | + | ||
| 48 | +| Champ | Type | Défaut | Description | | ||
| 49 | +| --- | --- | --- | --- | | ||
| 50 | +| `name` | chaîne | le nom du fichier | Nom affiché, dans le sélecteur de thème et la boîte À propos. | | ||
| 51 | +| `description` | chaîne | `""` | Une ligne, affichée par `-list-themes`. | | ||
| 52 | +| `inherits` | chaîne | aucun | Nom d'un thème dont partir. Ses styles résolus servent de base ; ce fichier redéfinit ce qu'il nomme. Les chaînes sont plafonnées à 16 sauts. | | ||
| 53 | +| `colors` | table | `{}` | Les styles. Les clés sont celles listées plus bas. | | ||
| 54 | + | ||
| 55 | +## Champs d'une entrée | ||
| 56 | + | ||
| 57 | +Chaque valeur sous `[colors]` est une table en ligne : | ||
| 58 | + | ||
| 59 | +| Champ | Type | Défaut | Description | | ||
| 60 | +| --- | --- | --- | --- | | ||
| 61 | +| `fg` | chaîne | hérité | Couleur de premier plan. | | ||
| 62 | +| `bg` | chaîne | hérité | Couleur de fond. | | ||
| 63 | +| `bold` | booléen | `false` | Activer le gras. | | ||
| 64 | +| `underline` | booléen | `false` | Activer le souligné. | | ||
| 65 | +| `italic` | booléen | `false` | Activer l'italique. | | ||
| 66 | +| `reverse` | booléen | `false` | Échanger premier plan et fond. | | ||
| 67 | +| `dim` | booléen | `false` | Activer l'atténuation. | | ||
| 68 | +| `blink` | booléen | `false` | Activer le clignotement. | | ||
| 69 | + | ||
| 70 | +Les attributs ne sont jamais qu'**activés** ; il n'existe pas de moyen de désactiver un attribut hérité autrement qu'en n'en héritant pas. | ||
| 71 | + | ||
| 72 | +## Valeurs de couleur | ||
| 73 | + | ||
| 74 | +| Forme | Exemple | Remarques | | ||
| 75 | +| --- | --- | --- | | ||
| 76 | +| Nom ANSI | `navy`, `aqua`, `silver`, `fuchsia` | Les seize noms, plus la liste W3C complète. | | ||
| 77 | +| Littéral hexadécimal | `#5fafd7` | 24 bits ; tcell l'approxime sur les terminaux sans couleurs vraies. | | ||
| 78 | +| `default` | `default` | Ce que le terminal utilise lui-même. | | ||
| 79 | +| `-` | `-` | Identique à `default`. | | ||
| 80 | +| `""` | `""` | Identique à `default`. | | ||
| 81 | + | ||
| 82 | +Les seize noms ANSI : `black` `maroon` `green` `olive` `navy` `purple` `teal` `silver` `gray` `red` `lime` `yellow` `blue` `fuchsia` `aqua` `white`. | ||
| 83 | + | ||
| 84 | +Une couleur non reconnue est une **erreur de chargement**, pas un repli silencieux. | ||
| 85 | + | ||
| 86 | +## Clés de style | ||
| 87 | + | ||
| 88 | +Les clés non définies retombent le long des points, et finalement sur `default`. | ||
| 89 | + | ||
| 90 | +### Base | ||
| 91 | + | ||
| 92 | +| Clé | Ce qu'elle colore | | ||
| 93 | +| --- | --- | | ||
| 94 | +| `default` | Le dernier recours de toute recherche | | ||
| 95 | +| `desktop` | Le fond texturé derrière les fenêtres | | ||
| 96 | +| `shadow` | Les cellules qu'une fenêtre assombrit derrière elle | | ||
| 97 | + | ||
| 98 | +### Barre de menus | ||
| 99 | + | ||
| 100 | +| Clé | Ce qu'elle colore | | ||
| 101 | +| --- | --- | | ||
| 102 | +| `menu.bar` | La rangée de titres | | ||
| 103 | +| `menu.item` | Une entrée déroulante | | ||
| 104 | +| `menu.selected` | L'entrée surlignée | | ||
| 105 | +| `menu.shortcut` | La lettre d'accès d'un intitulé | | ||
| 106 | +| `menu.disabled` | Une entrée non choisissable | | ||
| 107 | + | ||
| 108 | +### Fenêtres | ||
| 109 | + | ||
| 110 | +| Clé | Ce qu'elle colore | | ||
| 111 | +| --- | --- | | ||
| 112 | +| `window.frame.active` | Le cadre de la fenêtre active | | ||
| 113 | +| `window.frame.inactive` | Tous les autres cadres | | ||
| 114 | +| `window.title.active` | Le titre de la fenêtre active | | ||
| 115 | +| `window.title.inactive` | Tous les autres titres | | ||
| 116 | +| `window.body` | L'intérieur, avant que son contenu ne se dessine | | ||
| 117 | + | ||
| 118 | +### Barres | ||
| 119 | + | ||
| 120 | +| Clé | Ce qu'elle colore | | ||
| 121 | +| --- | --- | | ||
| 122 | +| `statusbar` | La barre elle-même | | ||
| 123 | +| `statusbar.key` | La partie `Fn` d'un indice | | ||
| 124 | +| `statusbar.hint` | Le texte aligné à droite | | ||
| 125 | +| `scrollbar` | La glissière d'une barre de défilement | | ||
| 126 | +| `scrollbar.thumb` | Son curseur et ses flèches | | ||
| 127 | + | ||
| 128 | +### Dialogues et contrôles | ||
| 129 | + | ||
| 130 | +| Clé | Ce qu'elle colore | | ||
| 131 | +| --- | --- | | ||
| 132 | +| `dialog.frame` | Le cadre d'un dialogue | | ||
| 133 | +| `dialog.body` | Son intérieur | | ||
| 134 | +| `dialog.title` | Son titre | | ||
| 135 | +| `dialog.label` | Une ligne de texte statique | | ||
| 136 | +| `button` | Un bouton | | ||
| 137 | +| `button.focused` | Le bouton qui a le focus | | ||
| 138 | +| `button.shortcut` | La lettre d'accès d'un bouton | | ||
| 139 | +| `input` | Un champ de saisie | | ||
| 140 | +| `input.focused` | Le champ qui a le focus | | ||
| 141 | +| `input.selection` | Le texte sélectionné dans un champ | | ||
| 142 | +| `list` | Une liste | | ||
| 143 | +| `list.selected` | Sa ligne surlignée, quand elle a le focus | | ||
| 144 | +| `list.unfocused` | Sa ligne surlignée, sinon | | ||
| 145 | +| `checkbox` | Une case à cocher | | ||
| 146 | +| `checkbox.focused` | La case qui a le focus | | ||
| 147 | + | ||
| 148 | +### Éditeur | ||
| 149 | + | ||
| 150 | +| Clé | Ce qu'elle colore | | ||
| 151 | +| --- | --- | | ||
| 152 | +| `editor.text` | Le texte qu'aucune autre règle ne revendique | | ||
| 153 | +| `editor.selection` | Le texte sélectionné | | ||
| 154 | +| `editor.linenumber` | La gouttière des numéros de ligne | | ||
| 155 | +| `editor.currentline` | La ligne où se trouve le curseur | | ||
| 156 | +| `editor.cursor` | Le curseur. Son **fond** est aussi envoyé au terminal comme couleur de curseur, et son premier plan peint le caractère en dessous. | | ||
| 157 | + | ||
| 158 | +### Terminal | ||
| 159 | + | ||
| 160 | +| Clé | Ce qu'elle colore | | ||
| 161 | +| --- | --- | | ||
| 162 | +| `terminal.text` | Toute cellule d'une fenêtre terminal dont le programme qui y tourne n'a pas choisi la couleur | | ||
| 163 | +| `terminal.cursor` | La cellule sous le curseur d'un terminal, quand cette fenêtre a le focus | | ||
| 164 | + | ||
| 165 | +Un programme qui nomme ses propres couleurs les conserve : ces deux clés ne remplissent que ce qu'il a laissé indéfini. Voir [Fenêtres terminal](terminal.md). | ||
| 166 | + | ||
| 167 | +### Arbre du projet | ||
| 168 | + | ||
| 169 | +| Clé | Ce qu'elle colore | | ||
| 170 | +| --- | --- | | ||
| 171 | +| `tree.text` | Le nom d'un fichier dans l'arbre, et le fond de l'arbre | | ||
| 172 | +| `tree.directory` | Le nom d'un dossier | | ||
| 173 | +| `tree.selected` | La ligne surlignée, quand l'arbre a le focus | | ||
| 174 | +| `tree.unfocused` | La ligne surlignée, quand il ne l'a pas | | ||
| 175 | + | ||
| 176 | +Elles sont distinctes des clés `list.*` à dessein : la liste d'un dialogue est colorée pour ressortir sur un dialogue, et la réutiliser surlignerait une ligne d'arbre dans la couleur même qu'a déjà le corps d'une fenêtre. Voir [Arbre du projet](project-tree.md). | ||
| 177 | + | ||
| 178 | +### Syntaxe | ||
| 179 | + | ||
| 180 | +| Clé | Ce qu'elle colore | | ||
| 181 | +| --- | --- | | ||
| 182 | +| `syntax.identifier` | Un nom ordinaire | | ||
| 183 | +| `syntax.keyword` | `func`, `if`, `package`, … | | ||
| 184 | +| `syntax.type` | `int`, `string`, et un nom après `type` | | ||
| 185 | +| `syntax.builtin` | `len`, `append`, `make`, … | | ||
| 186 | +| `syntax.constant` | `true`, `false`, `nil`, `iota` | | ||
| 187 | +| `syntax.function` | Un nom avant `(`, ou après `func` | | ||
| 188 | +| `syntax.string` | Un littéral chaîne | | ||
| 189 | +| `syntax.char` | Un littéral rune | | ||
| 190 | +| `syntax.number` | Un littéral entier, flottant ou imaginaire | | ||
| 191 | +| `syntax.comment` | `//` et `/* */` | | ||
| 192 | +| `syntax.operator` | `+`, `:=`, `<-`, … | | ||
| 193 | +| `syntax.punctuation` | Parenthèses, virgules, points, points-virgules | | ||
| 194 | +| `syntax.heading` | Un titre Markdown, toute la ligne | | ||
| 195 | +| `syntax.tag` | Un nom d'élément HTML et ses chevrons | | ||
| 196 | +| `syntax.attribute` | Le nom d'un attribut HTML | | ||
| 197 | +| `syntax.emphasis` | Le gras et l'italique Markdown | | ||
| 198 | +| `syntax.link` | Un lien ou une image Markdown | | ||
| 199 | + | ||
| 200 | +Quel langage produit quelle classe est indiqué dans [Langages colorés](languages.md). | ||
| 201 | + | ||
| 202 | +### Complétion et diagnostics | ||
| 203 | + | ||
| 204 | +| Clé | Ce qu'elle colore | | ||
| 205 | +| --- | --- | | ||
| 206 | +| `completion.frame` | Le cadre de la liste | | ||
| 207 | +| `completion.item` | Une suggestion | | ||
| 208 | +| `completion.selected` | La suggestion surlignée | | ||
| 209 | +| `completion.detail` | L'étiquette de nature à côté d'une suggestion | | ||
| 210 | +| `diagnostic.error` | Une erreur du serveur de langage | | ||
| 211 | +| `diagnostic.warning` | Un avertissement | | ||
| 212 | +| `diagnostic.info` | Une note | | ||
| 213 | + | ||
| 214 | +## Exemple | ||
| 215 | + | ||
| 216 | +```toml | ||
| 217 | +name = "Le mien" | ||
| 218 | +description = "Turbo Classic, avec des commentaires lisibles." | ||
| 219 | +inherits = "turbo-classic" | ||
| 220 | + | ||
| 221 | +[colors] | ||
| 222 | +"syntax.comment" = { fg = "#8a8a8a", italic = true } | ||
| 223 | +"syntax.string" = { fg = "#87d7af" } | ||
| 224 | +"editor.currentline" = { bg = "#00005f" } | ||
| 225 | +``` | ||
| 226 | + | ||
| 227 | +## Erreurs | ||
| 228 | + | ||
| 229 | +| Message | Cause | | ||
| 230 | +| --- | --- | | ||
| 231 | +| `theme: not found: "x"` | Aucun `x.toml` dans le répertoire utilisateur ni parmi les thèmes embarqués. | | ||
| 232 | +| `theme: not found: "…" is not a plain theme name` | Le nom contient `/`, `\` ou `..`. | | ||
| 233 | +| `invalid TOML: …` | Le fichier n'est pas du TOML valide. | | ||
| 234 | +| `colors."k": fg: unknown colour "…"` | Le nom de couleur n'est pas reconnu. | | ||
| 235 | +| `inherits: chain deeper than 16, probably a loop` | Deux thèmes héritent l'un de l'autre, directement ou par l'intermédiaire d'autres. | | ||
| 236 | +| `inherits "x": theme: not found` | Le parent nommé n'existe pas. | | ||
added
docs/fr/reference/versioning.md +150 -0 | new file mode 100644 | ||
| @@ -0,0 +1,150 @@ | ||
| 1 | +# Référence : le numéro de version | |
| 2 | + | |
| 3 | +> Description neutre de l'origine de la version que Turbo Python annonce, et de ce que produit chaque façon de le construire. | |
| 4 | + | |
| 5 | +## D'où vient le numéro | |
| 6 | + | |
| 7 | +Trois sources, consultées dans cet ordre. La première qui répond l'emporte. | |
| 8 | + | |
| 9 | +| Ordre | Source | Renseignée par | | |
| 10 | +| --- | --- | --- | | |
| 11 | +| 1 | Estampilles de l'éditeur de liens | `make build`, `make install`, `scripts/install.sh` | | |
| 12 | +| 2 | Informations de build de Go | L'outil Go, automatiquement | | |
| 13 | +| 3 | `unknown` | Rien — la valeur annoncée quand aucune source n'a pu nommer le build | | |
| 14 | + | |
| 15 | +Il n'y a **aucune constante de version dans les sources**. Un numéro écrit dans un fichier `.go` doit être modifié dans le cadre d'une release, et devient faux dès que quelqu'un l'oublie. | |
| 16 | + | |
| 17 | +## Estampilles de l'éditeur de liens | |
| 18 | + | |
| 19 | +Trois variables de paquet dans `internal/version`, renseignées par `-ldflags -X`. | |
| 20 | + | |
| 21 | +| Variable | Remplie depuis | Exemple | | |
| 22 | +| --- | --- | --- | | |
| 23 | +| `stamp` | `git describe --tags --dirty` | `v0.1.0-14-g88a4c38` | | |
| 24 | +| `commit` | `git rev-parse --short HEAD` | `88a4c38` | | |
| 25 | +| `built` | `date -u +%Y-%m-%dT%H:%M:%SZ` | `2026-08-31T18:04:05Z` | | |
| 26 | + | |
| 27 | +```sh | |
| 28 | +go build -ldflags "\ | |
| 29 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' \ | |
| 30 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.commit=88a4c38' \ | |
| 31 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.built=2026-08-31T18:04:05Z'" . | |
| 32 | +``` | |
| 33 | + | |
| 34 | +Un `v` initial est retiré à l'affichage : le tag est `v0.2.0`, la boîte About affiche `0.2.0`. | |
| 35 | + | |
| 36 | +## Informations de build de Go | |
| 37 | + | |
| 38 | +Lues via `runtime/debug.ReadBuildInfo()` quand rien n'a été estampillé. | |
| 39 | + | |
| 40 | +| Champ lu | Sert à | | |
| 41 | +| --- | --- | | |
| 42 | +| `Main.Version` | Le numéro, sauf s'il est vide, `(devel)`, ou une pseudo-version | | |
| 43 | +| `vcs.revision` | Le commit, abrégé à sept caractères | | |
| 44 | +| `vcs.modified` | L'ajout ou non du suffixe `-dirty` | | |
| 45 | + | |
| 46 | +`vcs.time` n'est **pas** utilisé. Il enregistre la date du commit, pas celle de l'édition de liens ; l'annoncer comme date de build serait faux sur tout binaire construit après son propre commit. | |
| 47 | + | |
| 48 | +Une **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — est la façon dont l'outil Go nomme un commit qu'aucun tag ne nomme. Elle est rapportée comme `devel`, et non affichée telle quelle : son `0.1.1` est un correctif qui n'existe pas. | |
| 49 | + | |
| 50 | +## Ce qu'annonce chaque build | |
| 51 | + | |
| 52 | +| Construit par | Numéro | Commit | Date | | |
| 53 | +| --- | --- | --- | --- | | |
| 54 | +| `make build`, `make install`, `scripts/install.sh` | `0.1.0-14-g88a4c38` | oui | oui | | |
| 55 | +| Les mêmes, sur un commit tagué | `0.2.0` | oui | oui | | |
| 56 | +| Les mêmes, avec des modifications non validées | `0.1.0-14-g88a4c38-dirty` | oui | oui | | |
| 57 | +| `go install rickub.com/turbo-editors/turbo-python@v0.2.0` | `0.2.0` | non | non | | |
| 58 | +| `go build .` dans un dépôt cloné | `devel` | oui | non | | |
| 59 | +| `go build .` dans un dépôt cloné avec des modifications | `devel-dirty` | oui | non | | |
| 60 | +| `uv run` | `unknown` | non | non | | |
| 61 | +| Un dossier sans git, et sans estampille | `unknown` | non | non | | |
| 62 | + | |
| 63 | +Seules les lignes estampillées peuvent annoncer un tag : le système de build de Go ne lit pas les tags git. | |
| 64 | + | |
| 65 | +## Vérifié au moment du build | |
| 66 | + | |
| 67 | +Une estampille d'édition de liens est une chaîne de caractères, et une mauvaise n'est pas une erreur. Un `-X` qui nomme un symbole inexistant s'édite sans se plaindre et n'estampille rien ; le binaire retombe alors sur les informations de build de Go et annonce une version que le build n'a jamais voulue — souvent `devel`, sur un binaire attaché à une release. Rien d'autre que l'exécution du binaire ne le détecte : chaque build qui en produit un l'exécute donc. | |
| 68 | + | |
| 69 | +C'est `scripts/check-version.sh` qui s'en charge. | |
| 70 | + | |
| 71 | +| Appelé par | Sur | Un échec fait échouer | | |
| 72 | +| --- | --- | --- | | |
| 73 | +| `make build` | `bin/turbo-python`, avec `$(VERSION)` et `$(COMMIT)` | le build | | |
| 74 | +| `scripts/install.sh` | le binaire en attente, **avant** son installation | l'installation, en laissant intact celui qui est déjà là | | |
| 75 | +| `03-build-releases.sh` | le seul artefact en attente que cette machine sait exécuter, avec le tag | la construction de la release | | |
| 76 | + | |
| 77 | +```sh | |
| 78 | +scripts/check-version.sh bin/turbo-python v0.2.0 88a4c38 # un build estampillé | |
| 79 | +scripts/check-version.sh bin/turbo-python # rien à attendre | |
| 80 | +``` | |
| 81 | + | |
| 82 | +| Arguments | Réussit si | | |
| 83 | +| --- | --- | | |
| 84 | +| binaire, version, commit | le numéro annoncé est **égal** à la version privée de son `v` initial, et le commit apparaît dans la sortie | | |
| 85 | +| binaire, version | le numéro lui est égal | | |
| 86 | +| binaire | le numéro est autre chose qu'`unknown` | | |
| 87 | + | |
| 88 | +La comparaison de version est une égalité, pas une recherche. `0.2.0` est une sous-chaîne de `10.2.0`, et d'une empreinte de commit qui le contiendrait par hasard ; une estampille presque juste est précisément ce que cette vérification existe pour attraper. | |
| 89 | + | |
| 90 | +| Code de sortie | Signification | | |
| 91 | +| --- | --- | | |
| 92 | +| `0` | Le binaire annonce ce que le build voulait. La ligne qu'il a affichée est réémise. | | |
| 93 | +| `1` | Il ne s'exécute pas, n'est pas là, ou annonce autre chose. | | |
| 94 | +| `2` | Aucun binaire n'a été nommé. | | |
| 95 | + | |
| 96 | +## Où il s'affiche | |
| 97 | + | |
| 98 | +### `-version` | |
| 99 | + | |
| 100 | +Une ligne, portant chaque élément connu. | |
| 101 | + | |
| 102 | +``` | |
| 103 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | |
| 104 | +Turbo Python 0.2.0 (88a4c38) | |
| 105 | +Turbo Python 0.2.0 | |
| 106 | +``` | |
| 107 | + | |
| 108 | +### Help ▸ About | |
| 109 | + | |
| 110 | +Une ligne par fait connu. Un fait que le build n'a pas enregistré n'a **pas de ligne**, plutôt qu'une ligne vide. | |
| 111 | + | |
| 112 | +``` | |
| 113 | +Turbo Python 0.2.0 | |
| 114 | + | |
| 115 | +A Turbo C-style editor for Python, | |
| 116 | +written in Go. | |
| 117 | + | |
| 118 | +Commit: 88a4c38 | |
| 119 | +Built: 2026-08-31 18:04 UTC | |
| 120 | +Theme: Turbo Classic | |
| 121 | +``` | |
| 122 | + | |
| 123 | +`Built` est rendu en UTC sous la forme `AAAA-MM-JJ HH:MM UTC`. Une estampille qui n'est pas un RFC 3339 valide est affichée exactement telle qu'elle a été donnée, plutôt que supprimée. | |
| 124 | + | |
| 125 | +### `make version` | |
| 126 | + | |
| 127 | +Affiche ce que ce dépôt estampillerait, sans construire. | |
| 128 | + | |
| 129 | +``` | |
| 130 | +$ make version | |
| 131 | +v0.1.0-14-g88a4c38 (88a4c38) | |
| 132 | +``` | |
| 133 | + | |
| 134 | +### `make ldflags` | |
| 135 | + | |
| 136 | +Affiche les options d'édition de liens qu'utilise un build estampillé, pour qu'un script puisse les réutiliser au lieu de répéter les chemins `-X`. | |
| 137 | + | |
| 138 | +``` | |
| 139 | +$ make ldflags | |
| 140 | +-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' -X '….commit=7f8b36a' -X '….built=2026-08-31T19:02:03Z' | |
| 141 | +``` | |
| 142 | + | |
| 143 | +`03-build-releases.sh` les lit pour ses compilations croisées, en surchargeant la version par le tag qu'il publie — `make ldflags VERSION=v0.2.0` — pour que les binaires disent ce que dit la release plutôt que ce que dit `git describe`. Un binaire compilé sans elles annonce `devel`, quoi que dise la release à laquelle il est attaché. | |
| 144 | + | |
| 145 | +## Voir aussi | |
| 146 | + | |
| 147 | +- Faire une release pour que le numéro soit juste : [Comment faire une release](../how-to/make-a-release.md) | |
| 148 | +- Ce à quoi `-version` ne sert **pas** : il est écrit pour un humain. Un script qui a besoin du numéro doit comparer avec `grep -F`, ou interroger git, plutôt que d'en extraire un champ. | |
| 149 | +- Pourquoi il n'y a pas de constante de version : [Décisions de conception](../explanation/design-decisions.md#la-version-est-une-propriété-du-build-pas-des-sources) | |
| 150 | +- L'option `-version` parmi les autres : [Ligne de commande](cli.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,150 @@ | |||
| 1 | +# Référence : le numéro de version | ||
| 2 | + | ||
| 3 | +> Description neutre de l'origine de la version que Turbo Python annonce, et de ce que produit chaque façon de le construire. | ||
| 4 | + | ||
| 5 | +## D'où vient le numéro | ||
| 6 | + | ||
| 7 | +Trois sources, consultées dans cet ordre. La première qui répond l'emporte. | ||
| 8 | + | ||
| 9 | +| Ordre | Source | Renseignée par | | ||
| 10 | +| --- | --- | --- | | ||
| 11 | +| 1 | Estampilles de l'éditeur de liens | `make build`, `make install`, `scripts/install.sh` | | ||
| 12 | +| 2 | Informations de build de Go | L'outil Go, automatiquement | | ||
| 13 | +| 3 | `unknown` | Rien — la valeur annoncée quand aucune source n'a pu nommer le build | | ||
| 14 | + | ||
| 15 | +Il n'y a **aucune constante de version dans les sources**. Un numéro écrit dans un fichier `.go` doit être modifié dans le cadre d'une release, et devient faux dès que quelqu'un l'oublie. | ||
| 16 | + | ||
| 17 | +## Estampilles de l'éditeur de liens | ||
| 18 | + | ||
| 19 | +Trois variables de paquet dans `internal/version`, renseignées par `-ldflags -X`. | ||
| 20 | + | ||
| 21 | +| Variable | Remplie depuis | Exemple | | ||
| 22 | +| --- | --- | --- | | ||
| 23 | +| `stamp` | `git describe --tags --dirty` | `v0.1.0-14-g88a4c38` | | ||
| 24 | +| `commit` | `git rev-parse --short HEAD` | `88a4c38` | | ||
| 25 | +| `built` | `date -u +%Y-%m-%dT%H:%M:%SZ` | `2026-08-31T18:04:05Z` | | ||
| 26 | + | ||
| 27 | +```sh | ||
| 28 | +go build -ldflags "\ | ||
| 29 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' \ | ||
| 30 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.commit=88a4c38' \ | ||
| 31 | + -X 'rickub.com/turbo-editors/turbo-python/internal/version.built=2026-08-31T18:04:05Z'" . | ||
| 32 | +``` | ||
| 33 | + | ||
| 34 | +Un `v` initial est retiré à l'affichage : le tag est `v0.2.0`, la boîte About affiche `0.2.0`. | ||
| 35 | + | ||
| 36 | +## Informations de build de Go | ||
| 37 | + | ||
| 38 | +Lues via `runtime/debug.ReadBuildInfo()` quand rien n'a été estampillé. | ||
| 39 | + | ||
| 40 | +| Champ lu | Sert à | | ||
| 41 | +| --- | --- | | ||
| 42 | +| `Main.Version` | Le numéro, sauf s'il est vide, `(devel)`, ou une pseudo-version | | ||
| 43 | +| `vcs.revision` | Le commit, abrégé à sept caractères | | ||
| 44 | +| `vcs.modified` | L'ajout ou non du suffixe `-dirty` | | ||
| 45 | + | ||
| 46 | +`vcs.time` n'est **pas** utilisé. Il enregistre la date du commit, pas celle de l'édition de liens ; l'annoncer comme date de build serait faux sur tout binaire construit après son propre commit. | ||
| 47 | + | ||
| 48 | +Une **pseudo-version** — `v0.1.1-0.20260831165958-88a4c3859bf3` — est la façon dont l'outil Go nomme un commit qu'aucun tag ne nomme. Elle est rapportée comme `devel`, et non affichée telle quelle : son `0.1.1` est un correctif qui n'existe pas. | ||
| 49 | + | ||
| 50 | +## Ce qu'annonce chaque build | ||
| 51 | + | ||
| 52 | +| Construit par | Numéro | Commit | Date | | ||
| 53 | +| --- | --- | --- | --- | | ||
| 54 | +| `make build`, `make install`, `scripts/install.sh` | `0.1.0-14-g88a4c38` | oui | oui | | ||
| 55 | +| Les mêmes, sur un commit tagué | `0.2.0` | oui | oui | | ||
| 56 | +| Les mêmes, avec des modifications non validées | `0.1.0-14-g88a4c38-dirty` | oui | oui | | ||
| 57 | +| `go install rickub.com/turbo-editors/turbo-python@v0.2.0` | `0.2.0` | non | non | | ||
| 58 | +| `go build .` dans un dépôt cloné | `devel` | oui | non | | ||
| 59 | +| `go build .` dans un dépôt cloné avec des modifications | `devel-dirty` | oui | non | | ||
| 60 | +| `uv run` | `unknown` | non | non | | ||
| 61 | +| Un dossier sans git, et sans estampille | `unknown` | non | non | | ||
| 62 | + | ||
| 63 | +Seules les lignes estampillées peuvent annoncer un tag : le système de build de Go ne lit pas les tags git. | ||
| 64 | + | ||
| 65 | +## Vérifié au moment du build | ||
| 66 | + | ||
| 67 | +Une estampille d'édition de liens est une chaîne de caractères, et une mauvaise n'est pas une erreur. Un `-X` qui nomme un symbole inexistant s'édite sans se plaindre et n'estampille rien ; le binaire retombe alors sur les informations de build de Go et annonce une version que le build n'a jamais voulue — souvent `devel`, sur un binaire attaché à une release. Rien d'autre que l'exécution du binaire ne le détecte : chaque build qui en produit un l'exécute donc. | ||
| 68 | + | ||
| 69 | +C'est `scripts/check-version.sh` qui s'en charge. | ||
| 70 | + | ||
| 71 | +| Appelé par | Sur | Un échec fait échouer | | ||
| 72 | +| --- | --- | --- | | ||
| 73 | +| `make build` | `bin/turbo-python`, avec `$(VERSION)` et `$(COMMIT)` | le build | | ||
| 74 | +| `scripts/install.sh` | le binaire en attente, **avant** son installation | l'installation, en laissant intact celui qui est déjà là | | ||
| 75 | +| `03-build-releases.sh` | le seul artefact en attente que cette machine sait exécuter, avec le tag | la construction de la release | | ||
| 76 | + | ||
| 77 | +```sh | ||
| 78 | +scripts/check-version.sh bin/turbo-python v0.2.0 88a4c38 # un build estampillé | ||
| 79 | +scripts/check-version.sh bin/turbo-python # rien à attendre | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +| Arguments | Réussit si | | ||
| 83 | +| --- | --- | | ||
| 84 | +| binaire, version, commit | le numéro annoncé est **égal** à la version privée de son `v` initial, et le commit apparaît dans la sortie | | ||
| 85 | +| binaire, version | le numéro lui est égal | | ||
| 86 | +| binaire | le numéro est autre chose qu'`unknown` | | ||
| 87 | + | ||
| 88 | +La comparaison de version est une égalité, pas une recherche. `0.2.0` est une sous-chaîne de `10.2.0`, et d'une empreinte de commit qui le contiendrait par hasard ; une estampille presque juste est précisément ce que cette vérification existe pour attraper. | ||
| 89 | + | ||
| 90 | +| Code de sortie | Signification | | ||
| 91 | +| --- | --- | | ||
| 92 | +| `0` | Le binaire annonce ce que le build voulait. La ligne qu'il a affichée est réémise. | | ||
| 93 | +| `1` | Il ne s'exécute pas, n'est pas là, ou annonce autre chose. | | ||
| 94 | +| `2` | Aucun binaire n'a été nommé. | | ||
| 95 | + | ||
| 96 | +## Où il s'affiche | ||
| 97 | + | ||
| 98 | +### `-version` | ||
| 99 | + | ||
| 100 | +Une ligne, portant chaque élément connu. | ||
| 101 | + | ||
| 102 | +``` | ||
| 103 | +Turbo Python 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | ||
| 104 | +Turbo Python 0.2.0 (88a4c38) | ||
| 105 | +Turbo Python 0.2.0 | ||
| 106 | +``` | ||
| 107 | + | ||
| 108 | +### Help ▸ About | ||
| 109 | + | ||
| 110 | +Une ligne par fait connu. Un fait que le build n'a pas enregistré n'a **pas de ligne**, plutôt qu'une ligne vide. | ||
| 111 | + | ||
| 112 | +``` | ||
| 113 | +Turbo Python 0.2.0 | ||
| 114 | + | ||
| 115 | +A Turbo C-style editor for Python, | ||
| 116 | +written in Go. | ||
| 117 | + | ||
| 118 | +Commit: 88a4c38 | ||
| 119 | +Built: 2026-08-31 18:04 UTC | ||
| 120 | +Theme: Turbo Classic | ||
| 121 | +``` | ||
| 122 | + | ||
| 123 | +`Built` est rendu en UTC sous la forme `AAAA-MM-JJ HH:MM UTC`. Une estampille qui n'est pas un RFC 3339 valide est affichée exactement telle qu'elle a été donnée, plutôt que supprimée. | ||
| 124 | + | ||
| 125 | +### `make version` | ||
| 126 | + | ||
| 127 | +Affiche ce que ce dépôt estampillerait, sans construire. | ||
| 128 | + | ||
| 129 | +``` | ||
| 130 | +$ make version | ||
| 131 | +v0.1.0-14-g88a4c38 (88a4c38) | ||
| 132 | +``` | ||
| 133 | + | ||
| 134 | +### `make ldflags` | ||
| 135 | + | ||
| 136 | +Affiche les options d'édition de liens qu'utilise un build estampillé, pour qu'un script puisse les réutiliser au lieu de répéter les chemins `-X`. | ||
| 137 | + | ||
| 138 | +``` | ||
| 139 | +$ make ldflags | ||
| 140 | +-X 'rickub.com/turbo-editors/turbo-python/internal/version.stamp=v0.2.0' -X '….commit=7f8b36a' -X '….built=2026-08-31T19:02:03Z' | ||
| 141 | +``` | ||
| 142 | + | ||
| 143 | +`03-build-releases.sh` les lit pour ses compilations croisées, en surchargeant la version par le tag qu'il publie — `make ldflags VERSION=v0.2.0` — pour que les binaires disent ce que dit la release plutôt que ce que dit `git describe`. Un binaire compilé sans elles annonce `devel`, quoi que dise la release à laquelle il est attaché. | ||
| 144 | + | ||
| 145 | +## Voir aussi | ||
| 146 | + | ||
| 147 | +- Faire une release pour que le numéro soit juste : [Comment faire une release](../how-to/make-a-release.md) | ||
| 148 | +- Ce à quoi `-version` ne sert **pas** : il est écrit pour un humain. Un script qui a besoin du numéro doit comparer avec `grep -F`, ou interroger git, plutôt que d'en extraire un champ. | ||
| 149 | +- Pourquoi il n'y a pas de constante de version : [Décisions de conception](../explanation/design-decisions.md#la-version-est-une-propriété-du-build-pas-des-sources) | ||
| 150 | +- L'option `-version` parmi les autres : [Ligne de commande](cli.md) | ||
added
docs/fr/tutorials/getting-started.md +216 -0 | new file mode 100644 | ||
| @@ -0,0 +1,216 @@ | ||
| 1 | +# Tutoriel : votre premier fichier dans Turbo Python | |
| 2 | + | |
| 3 | +À la fin de ce tutoriel, vous aurez compilé l'éditeur, écrit un petit programme Python dedans, vu les mots-clés changer de couleur à la frappe, enregistré le fichier et exécuté le résultat. Comptez une dizaine de minutes. | |
| 4 | + | |
| 5 | +Aucune connaissance préalable de Turbo Python n'est nécessaire. Il vous faut Go 1.26 ou plus récent pour compiler l'éditeur, et [uv](https://docs.astral.sh/uv/) pour créer et lancer le projet Python. | |
| 6 | + | |
| 7 | +## Prérequis | |
| 8 | + | |
| 9 | +Vérifiez que Go est là — l'éditeur est écrit en Go, même si c'est un éditeur pour Python : | |
| 10 | + | |
| 11 | +```bash | |
| 12 | +go version | |
| 13 | +``` | |
| 14 | + | |
| 15 | +Vous devriez voir quelque chose comme : | |
| 16 | + | |
| 17 | +``` | |
| 18 | +go version go1.26.5 linux/arm64 | |
| 19 | +``` | |
| 20 | + | |
| 21 | +Si la commande échoue, installez d'abord Go : https://go.dev/dl/ | |
| 22 | + | |
| 23 | +Vérifiez qu'uv est là aussi : | |
| 24 | + | |
| 25 | +```bash | |
| 26 | +uv --version | |
| 27 | +``` | |
| 28 | + | |
| 29 | +Vous devriez voir quelque chose comme : | |
| 30 | + | |
| 31 | +``` | |
| 32 | +uv 0.9.26 | |
| 33 | +``` | |
| 34 | + | |
| 35 | +Si la commande échoue, installez d'abord uv : https://docs.astral.sh/uv/getting-started/installation/ | |
| 36 | + | |
| 37 | +## Étape 1 — Compiler l'éditeur | |
| 38 | + | |
| 39 | +Depuis le dossier du projet, tapez : | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +make build | |
| 43 | +``` | |
| 44 | + | |
| 45 | +Vous devriez voir une ligne `go build`, puis une ligne qui nomme la version que le binaire annonce. Cette dernière ligne est une vérification, pas une décoration : elle exécute le binaire qui vient d'être lié et refuse une compilation dont l'estampille de version ne lui est jamais parvenue. | |
| 46 | + | |
| 47 | +Nous avons maintenant un exécutable dans `bin/turbo-python`. Retenez où il est, pour pouvoir le lancer de n'importe où : | |
| 48 | + | |
| 49 | +```bash | |
| 50 | +export TURBO="$PWD/bin/turbo-python" | |
| 51 | +``` | |
| 52 | + | |
| 53 | +## Étape 2 — Se faire un endroit où travailler | |
| 54 | + | |
| 55 | +Turbo Python est à son meilleur à l'intérieur d'un projet, alors créons-en un : | |
| 56 | + | |
| 57 | +```bash | |
| 58 | +cd /tmp && uv init hello && cd hello | |
| 59 | +``` | |
| 60 | + | |
| 61 | +Vous devriez voir : | |
| 62 | + | |
| 63 | +``` | |
| 64 | +Initialized project `hello` at `/tmp/hello` | |
| 65 | +``` | |
| 66 | + | |
| 67 | +`uv init` écrit un `pyproject.toml`, un `README.md`, un `.python-version` et un `main.py` contenant un hello-world. C'est `pyproject.toml` que Turbo Python cherche pour trouver la racine d'un projet, et c'est là que `pylsp` sera lancé. Nous allons remplacer le contenu de `main.py` par le nôtre. | |
| 68 | + | |
| 69 | +## Étape 3 — Ouvrir l'éditeur | |
| 70 | + | |
| 71 | +Lancez Turbo Python sur le fichier qu'uv a écrit : | |
| 72 | + | |
| 73 | +```bash | |
| 74 | +$TURBO main.py | |
| 75 | +``` | |
| 76 | + | |
| 77 | +L'écran se remplit d'un bureau bleu. Vous devriez voir : | |
| 78 | + | |
| 79 | +- une **barre de menus** en haut : `File Edit Search Run Code Options Window Snippets Python Help` | |
| 80 | +- une **fenêtre** encadrée d'un double trait, intitulée `main.py` | |
| 81 | +- une **barre d'état** en bas : `F1 Describe F2 Save F3 Open …` | |
| 82 | + | |
| 83 | +Le curseur clignote en ligne 1, colonne 1 — la barre d'état affiche `1:1` à droite. | |
| 84 | + | |
| 85 | +À côté, la barre d'état dit l'une de deux choses. `LSP: ready` signifie que le serveur de langage a été trouvé et démarré. `LSP: no pylsp — pipx install "python-lsp-server[all]"` signifie qu'il ne l'a pas été, et nomme l'unique commande qui l'installe. Dans les deux cas la suite de ce tutoriel fonctionne ; le [guide de la complétion](../how-to/enable-completion.md) est là pour transformer le second message en premier. | |
| 86 | + | |
| 87 | +Nous sommes dans l'éditeur. | |
| 88 | + | |
| 89 | +## Étape 4 — Vider le fichier et taper un programme Python | |
| 90 | + | |
| 91 | +Appuyez sur **Ctrl-A** pour tout sélectionner, puis sur **Suppr** pour effacer. La fenêtre est vide et son titre indique `main.py *` — l'étoile signale des modifications non enregistrées. | |
| 92 | + | |
| 93 | +Tapez cette ligne, puis **Entrée** : | |
| 94 | + | |
| 95 | +```python | |
| 96 | +def greet(name): | |
| 97 | +``` | |
| 98 | + | |
| 99 | +Regardez les couleurs pendant que vous tapez. `def` passe en **blanc gras** dès que le mot se termine : c'est un mot-clé. `greet` passe en **jaune gras** dès que vous tapez la `(` qui suit, parce que c'est ce qui en fait une fonction. `name` reste en **jaune** simple : c'est un identifiant ordinaire. | |
| 100 | + | |
| 101 | +(Ce sont les couleurs de Turbo Classic, celles avec lesquelles l'éditeur démarre. L'étape 8 en change.) | |
| 102 | + | |
| 103 | +Tapez maintenant quatre espaces vous-même, puis la ligne suivante : | |
| 104 | + | |
| 105 | +```python | |
| 106 | + message = f"Hello from {name}!" | |
| 107 | +``` | |
| 108 | + | |
| 109 | +**Entrée recopie l'indentation de la ligne courante ; elle n'ajoute pas de niveau après un deux-points.** Les blocs de Python sont faits d'indentation, et l'éditeur ne cherche pas à deviner où un nouveau bloc commence — les quatre espaces sont donc à taper une fois, et toutes les lignes suivantes les gardent gratuitement. | |
| 110 | + | |
| 111 | +`f"Hello from {name}!"` passe en **vert**, en entier, `{name}` compris. C'est une seule chaîne : ce qui est entre les accolades est du Python, mais ce n'est pas coloré comme du Python, parce que décider où une expression s'arrête à l'intérieur d'un littéral demande un analyseur syntaxique et qu'ici il n'y a qu'un scanner. Ce compromis est écrit noir sur blanc dans [Coloration et complétion](../explanation/colouring-and-completion.md). | |
| 112 | + | |
| 113 | +Appuyez sur **Entrée** — le curseur se pose sous le `m`, déjà indenté — et tapez : | |
| 114 | + | |
| 115 | +```python | |
| 116 | + print(message) | |
| 117 | +``` | |
| 118 | + | |
| 119 | +`print` passe en **cyan gras** : c'est l'une des primitives que le langage fournit, et non un nom venu de votre code. | |
| 120 | + | |
| 121 | +Appuyez sur **Entrée**, puis sur **Maj-Tab** pour reprendre l'indentation, et tapez la dernière ligne : | |
| 122 | + | |
| 123 | +```python | |
| 124 | +greet("Turbo Python") | |
| 125 | +``` | |
| 126 | + | |
| 127 | +Nous venons d'écrire un programme Python complet, coloré par l'éditeur au fil de la frappe. | |
| 128 | + | |
| 129 | +Si la barre d'état affichait `LSP: ready` tout à l'heure, regardez le bord gauche de la dernière ligne : il y a un `!` dans la gouttière. Le serveur de langage a un avis sur notre fichier, et **Code ▸ Problems…** dit lequel — `warning main.py:4 E305 expected 2 blank lines after class or function definition`. C'est une règle de style et non une erreur, et la laisser ne coûte rien ; ce qui compte est que la marque et le message soient là, et qu'ils arrivent sans que personne ne les demande. | |
| 130 | + | |
| 131 | +## Étape 5 — Enregistrer | |
| 132 | + | |
| 133 | +Appuyez sur **F2**. | |
| 134 | + | |
| 135 | +L'étoile disparaît du titre, et la barre d'état affiche, un instant : | |
| 136 | + | |
| 137 | +``` | |
| 138 | +Saved main.py | |
| 139 | +``` | |
| 140 | + | |
| 141 | +Elle revient ensuite aux rappels de touches — le message est une confirmation, pas un état. L'état, c'est le titre sans son étoile. | |
| 142 | + | |
| 143 | +## Étape 6 — Regarder le fichier de l'extérieur | |
| 144 | + | |
| 145 | +Quittez l'éditeur avec **Alt-X**. Le terminal revient tel qu'il était. | |
| 146 | + | |
| 147 | +Vérifiez ce que nous avons écrit : | |
| 148 | + | |
| 149 | +```bash | |
| 150 | +cat main.py | |
| 151 | +``` | |
| 152 | + | |
| 153 | +Vous devriez voir : | |
| 154 | + | |
| 155 | +```python | |
| 156 | +def greet(name): | |
| 157 | + message = f"Hello from {name}!" | |
| 158 | + print(message) | |
| 159 | +greet("Turbo Python") | |
| 160 | +``` | |
| 161 | + | |
| 162 | +## Étape 7 — L'exécuter | |
| 163 | + | |
| 164 | +```bash | |
| 165 | +uv run main.py | |
| 166 | +``` | |
| 167 | + | |
| 168 | +Le premier lancement fabrique l'environnement, vous verrez donc une ligne ou deux d'uv avant la sortie : | |
| 169 | + | |
| 170 | +``` | |
| 171 | +Using CPython 3.14.4 interpreter at: /usr/bin/python3.14 | |
| 172 | +Creating virtual environment at: .venv | |
| 173 | +Hello from Turbo Python! | |
| 174 | +``` | |
| 175 | + | |
| 176 | +C'est un programme Python qui marche, écrit entièrement dans l'éditeur. | |
| 177 | + | |
| 178 | +## Étape 8 — Changer de thème | |
| 179 | + | |
| 180 | +Rouvrez le fichier : | |
| 181 | + | |
| 182 | +```bash | |
| 183 | +$TURBO main.py | |
| 184 | +``` | |
| 185 | + | |
| 186 | +Appuyez sur **F10**. Le menu `File` s'ouvre. Appuyez cinq fois sur **→** : le menu longe la barre jusqu'à `Options`, dont la première entrée, `Theme…`, est surlignée. Appuyez sur **Entrée**. | |
| 187 | + | |
| 188 | +Une liste de onze apparaît, par ordre alphabétique, le thème courant déjà surligné : | |
| 189 | + | |
| 190 | +``` | |
| 191 | +borland-light | |
| 192 | +cappuccino | |
| 193 | +catppuccin-frappe | |
| 194 | +catppuccin-latte | |
| 195 | +cobalt | |
| 196 | +darcula | |
| 197 | +intellij-light | |
| 198 | +monochrome-dark | |
| 199 | +monochrome-light | |
| 200 | +turbo-classic | |
| 201 | +turbo-dark | |
| 202 | +``` | |
| 203 | + | |
| 204 | +`turbo-classic` est la ligne surlignée, parce que c'est le thème dans lequel vous êtes. Appuyez une fois sur **↓** pour aller à `turbo-dark`, puis sur **Entrée**. | |
| 205 | + | |
| 206 | +Tout l'éditeur se repeint en gris sombre, et la barre d'état affiche `Theme: Turbo Dark`. | |
| 207 | + | |
| 208 | +Appuyez sur **Alt-X** pour sortir. | |
| 209 | + | |
| 210 | +## Et maintenant ? | |
| 211 | + | |
| 212 | +Vous avez compilé l'éditeur, écrit un programme Python dedans, l'avez enregistré, exécuté, et vous avez changé son apparence. | |
| 213 | + | |
| 214 | +- Pour faire des choses précises — activer la complétion, écrire votre propre thème, chercher dans un fichier → voir les [guides pratiques](../how-to/) | |
| 215 | +- Pour retrouver une touche ou une entrée de menu → voir la [référence](../reference/) | |
| 216 | +- Pour comprendre comment la coloration et la complétion fonctionnent vraiment → voir les [explications](../explanation/) | |
| new file mode 100644 | |||
| @@ -0,0 +1,216 @@ | |||
| 1 | +# Tutoriel : votre premier fichier dans Turbo Python | ||
| 2 | + | ||
| 3 | +À la fin de ce tutoriel, vous aurez compilé l'éditeur, écrit un petit programme Python dedans, vu les mots-clés changer de couleur à la frappe, enregistré le fichier et exécuté le résultat. Comptez une dizaine de minutes. | ||
| 4 | + | ||
| 5 | +Aucune connaissance préalable de Turbo Python n'est nécessaire. Il vous faut Go 1.26 ou plus récent pour compiler l'éditeur, et [uv](https://docs.astral.sh/uv/) pour créer et lancer le projet Python. | ||
| 6 | + | ||
| 7 | +## Prérequis | ||
| 8 | + | ||
| 9 | +Vérifiez que Go est là — l'éditeur est écrit en Go, même si c'est un éditeur pour Python : | ||
| 10 | + | ||
| 11 | +```bash | ||
| 12 | +go version | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +Vous devriez voir quelque chose comme : | ||
| 16 | + | ||
| 17 | +``` | ||
| 18 | +go version go1.26.5 linux/arm64 | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +Si la commande échoue, installez d'abord Go : https://go.dev/dl/ | ||
| 22 | + | ||
| 23 | +Vérifiez qu'uv est là aussi : | ||
| 24 | + | ||
| 25 | +```bash | ||
| 26 | +uv --version | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +Vous devriez voir quelque chose comme : | ||
| 30 | + | ||
| 31 | +``` | ||
| 32 | +uv 0.9.26 | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +Si la commande échoue, installez d'abord uv : https://docs.astral.sh/uv/getting-started/installation/ | ||
| 36 | + | ||
| 37 | +## Étape 1 — Compiler l'éditeur | ||
| 38 | + | ||
| 39 | +Depuis le dossier du projet, tapez : | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +make build | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +Vous devriez voir une ligne `go build`, puis une ligne qui nomme la version que le binaire annonce. Cette dernière ligne est une vérification, pas une décoration : elle exécute le binaire qui vient d'être lié et refuse une compilation dont l'estampille de version ne lui est jamais parvenue. | ||
| 46 | + | ||
| 47 | +Nous avons maintenant un exécutable dans `bin/turbo-python`. Retenez où il est, pour pouvoir le lancer de n'importe où : | ||
| 48 | + | ||
| 49 | +```bash | ||
| 50 | +export TURBO="$PWD/bin/turbo-python" | ||
| 51 | +``` | ||
| 52 | + | ||
| 53 | +## Étape 2 — Se faire un endroit où travailler | ||
| 54 | + | ||
| 55 | +Turbo Python est à son meilleur à l'intérieur d'un projet, alors créons-en un : | ||
| 56 | + | ||
| 57 | +```bash | ||
| 58 | +cd /tmp && uv init hello && cd hello | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +Vous devriez voir : | ||
| 62 | + | ||
| 63 | +``` | ||
| 64 | +Initialized project `hello` at `/tmp/hello` | ||
| 65 | +``` | ||
| 66 | + | ||
| 67 | +`uv init` écrit un `pyproject.toml`, un `README.md`, un `.python-version` et un `main.py` contenant un hello-world. C'est `pyproject.toml` que Turbo Python cherche pour trouver la racine d'un projet, et c'est là que `pylsp` sera lancé. Nous allons remplacer le contenu de `main.py` par le nôtre. | ||
| 68 | + | ||
| 69 | +## Étape 3 — Ouvrir l'éditeur | ||
| 70 | + | ||
| 71 | +Lancez Turbo Python sur le fichier qu'uv a écrit : | ||
| 72 | + | ||
| 73 | +```bash | ||
| 74 | +$TURBO main.py | ||
| 75 | +``` | ||
| 76 | + | ||
| 77 | +L'écran se remplit d'un bureau bleu. Vous devriez voir : | ||
| 78 | + | ||
| 79 | +- une **barre de menus** en haut : `File Edit Search Run Code Options Window Snippets Python Help` | ||
| 80 | +- une **fenêtre** encadrée d'un double trait, intitulée `main.py` | ||
| 81 | +- une **barre d'état** en bas : `F1 Describe F2 Save F3 Open …` | ||
| 82 | + | ||
| 83 | +Le curseur clignote en ligne 1, colonne 1 — la barre d'état affiche `1:1` à droite. | ||
| 84 | + | ||
| 85 | +À côté, la barre d'état dit l'une de deux choses. `LSP: ready` signifie que le serveur de langage a été trouvé et démarré. `LSP: no pylsp — pipx install "python-lsp-server[all]"` signifie qu'il ne l'a pas été, et nomme l'unique commande qui l'installe. Dans les deux cas la suite de ce tutoriel fonctionne ; le [guide de la complétion](../how-to/enable-completion.md) est là pour transformer le second message en premier. | ||
| 86 | + | ||
| 87 | +Nous sommes dans l'éditeur. | ||
| 88 | + | ||
| 89 | +## Étape 4 — Vider le fichier et taper un programme Python | ||
| 90 | + | ||
| 91 | +Appuyez sur **Ctrl-A** pour tout sélectionner, puis sur **Suppr** pour effacer. La fenêtre est vide et son titre indique `main.py *` — l'étoile signale des modifications non enregistrées. | ||
| 92 | + | ||
| 93 | +Tapez cette ligne, puis **Entrée** : | ||
| 94 | + | ||
| 95 | +```python | ||
| 96 | +def greet(name): | ||
| 97 | +``` | ||
| 98 | + | ||
| 99 | +Regardez les couleurs pendant que vous tapez. `def` passe en **blanc gras** dès que le mot se termine : c'est un mot-clé. `greet` passe en **jaune gras** dès que vous tapez la `(` qui suit, parce que c'est ce qui en fait une fonction. `name` reste en **jaune** simple : c'est un identifiant ordinaire. | ||
| 100 | + | ||
| 101 | +(Ce sont les couleurs de Turbo Classic, celles avec lesquelles l'éditeur démarre. L'étape 8 en change.) | ||
| 102 | + | ||
| 103 | +Tapez maintenant quatre espaces vous-même, puis la ligne suivante : | ||
| 104 | + | ||
| 105 | +```python | ||
| 106 | + message = f"Hello from {name}!" | ||
| 107 | +``` | ||
| 108 | + | ||
| 109 | +**Entrée recopie l'indentation de la ligne courante ; elle n'ajoute pas de niveau après un deux-points.** Les blocs de Python sont faits d'indentation, et l'éditeur ne cherche pas à deviner où un nouveau bloc commence — les quatre espaces sont donc à taper une fois, et toutes les lignes suivantes les gardent gratuitement. | ||
| 110 | + | ||
| 111 | +`f"Hello from {name}!"` passe en **vert**, en entier, `{name}` compris. C'est une seule chaîne : ce qui est entre les accolades est du Python, mais ce n'est pas coloré comme du Python, parce que décider où une expression s'arrête à l'intérieur d'un littéral demande un analyseur syntaxique et qu'ici il n'y a qu'un scanner. Ce compromis est écrit noir sur blanc dans [Coloration et complétion](../explanation/colouring-and-completion.md). | ||
| 112 | + | ||
| 113 | +Appuyez sur **Entrée** — le curseur se pose sous le `m`, déjà indenté — et tapez : | ||
| 114 | + | ||
| 115 | +```python | ||
| 116 | + print(message) | ||
| 117 | +``` | ||
| 118 | + | ||
| 119 | +`print` passe en **cyan gras** : c'est l'une des primitives que le langage fournit, et non un nom venu de votre code. | ||
| 120 | + | ||
| 121 | +Appuyez sur **Entrée**, puis sur **Maj-Tab** pour reprendre l'indentation, et tapez la dernière ligne : | ||
| 122 | + | ||
| 123 | +```python | ||
| 124 | +greet("Turbo Python") | ||
| 125 | +``` | ||
| 126 | + | ||
| 127 | +Nous venons d'écrire un programme Python complet, coloré par l'éditeur au fil de la frappe. | ||
| 128 | + | ||
| 129 | +Si la barre d'état affichait `LSP: ready` tout à l'heure, regardez le bord gauche de la dernière ligne : il y a un `!` dans la gouttière. Le serveur de langage a un avis sur notre fichier, et **Code ▸ Problems…** dit lequel — `warning main.py:4 E305 expected 2 blank lines after class or function definition`. C'est une règle de style et non une erreur, et la laisser ne coûte rien ; ce qui compte est que la marque et le message soient là, et qu'ils arrivent sans que personne ne les demande. | ||
| 130 | + | ||
| 131 | +## Étape 5 — Enregistrer | ||
| 132 | + | ||
| 133 | +Appuyez sur **F2**. | ||
| 134 | + | ||
| 135 | +L'étoile disparaît du titre, et la barre d'état affiche, un instant : | ||
| 136 | + | ||
| 137 | +``` | ||
| 138 | +Saved main.py | ||
| 139 | +``` | ||
| 140 | + | ||
| 141 | +Elle revient ensuite aux rappels de touches — le message est une confirmation, pas un état. L'état, c'est le titre sans son étoile. | ||
| 142 | + | ||
| 143 | +## Étape 6 — Regarder le fichier de l'extérieur | ||
| 144 | + | ||
| 145 | +Quittez l'éditeur avec **Alt-X**. Le terminal revient tel qu'il était. | ||
| 146 | + | ||
| 147 | +Vérifiez ce que nous avons écrit : | ||
| 148 | + | ||
| 149 | +```bash | ||
| 150 | +cat main.py | ||
| 151 | +``` | ||
| 152 | + | ||
| 153 | +Vous devriez voir : | ||
| 154 | + | ||
| 155 | +```python | ||
| 156 | +def greet(name): | ||
| 157 | + message = f"Hello from {name}!" | ||
| 158 | + print(message) | ||
| 159 | +greet("Turbo Python") | ||
| 160 | +``` | ||
| 161 | + | ||
| 162 | +## Étape 7 — L'exécuter | ||
| 163 | + | ||
| 164 | +```bash | ||
| 165 | +uv run main.py | ||
| 166 | +``` | ||
| 167 | + | ||
| 168 | +Le premier lancement fabrique l'environnement, vous verrez donc une ligne ou deux d'uv avant la sortie : | ||
| 169 | + | ||
| 170 | +``` | ||
| 171 | +Using CPython 3.14.4 interpreter at: /usr/bin/python3.14 | ||
| 172 | +Creating virtual environment at: .venv | ||
| 173 | +Hello from Turbo Python! | ||
| 174 | +``` | ||
| 175 | + | ||
| 176 | +C'est un programme Python qui marche, écrit entièrement dans l'éditeur. | ||
| 177 | + | ||
| 178 | +## Étape 8 — Changer de thème | ||
| 179 | + | ||
| 180 | +Rouvrez le fichier : | ||
| 181 | + | ||
| 182 | +```bash | ||
| 183 | +$TURBO main.py | ||
| 184 | +``` | ||
| 185 | + | ||
| 186 | +Appuyez sur **F10**. Le menu `File` s'ouvre. Appuyez cinq fois sur **→** : le menu longe la barre jusqu'à `Options`, dont la première entrée, `Theme…`, est surlignée. Appuyez sur **Entrée**. | ||
| 187 | + | ||
| 188 | +Une liste de onze apparaît, par ordre alphabétique, le thème courant déjà surligné : | ||
| 189 | + | ||
| 190 | +``` | ||
| 191 | +borland-light | ||
| 192 | +cappuccino | ||
| 193 | +catppuccin-frappe | ||
| 194 | +catppuccin-latte | ||
| 195 | +cobalt | ||
| 196 | +darcula | ||
| 197 | +intellij-light | ||
| 198 | +monochrome-dark | ||
| 199 | +monochrome-light | ||
| 200 | +turbo-classic | ||
| 201 | +turbo-dark | ||
| 202 | +``` | ||
| 203 | + | ||
| 204 | +`turbo-classic` est la ligne surlignée, parce que c'est le thème dans lequel vous êtes. Appuyez une fois sur **↓** pour aller à `turbo-dark`, puis sur **Entrée**. | ||
| 205 | + | ||
| 206 | +Tout l'éditeur se repeint en gris sombre, et la barre d'état affiche `Theme: Turbo Dark`. | ||
| 207 | + | ||
| 208 | +Appuyez sur **Alt-X** pour sortir. | ||
| 209 | + | ||
| 210 | +## Et maintenant ? | ||
| 211 | + | ||
| 212 | +Vous avez compilé l'éditeur, écrit un programme Python dedans, l'avez enregistré, exécuté, et vous avez changé son apparence. | ||
| 213 | + | ||
| 214 | +- Pour faire des choses précises — activer la complétion, écrire votre propre thème, chercher dans un fichier → voir les [guides pratiques](../how-to/) | ||
| 215 | +- Pour retrouver une touche ou une entrée de menu → voir la [référence](../reference/) | ||
| 216 | +- Pour comprendre comment la coloration et la complétion fonctionnent vraiment → voir les [explications](../explanation/) | ||
added
git.sh +136 -0 | new file mode 100755 | ||
| @@ -0,0 +1,136 @@ | ||
| 1 | +#!/bin/bash | |
| 2 | +message="" | |
| 3 | +case $1 in | |
| 4 | + | |
| 5 | + # 🎨: art | |
| 6 | + art) | |
| 7 | + message="Improve structure / format of the code" | |
| 8 | + emoji="🎨" | |
| 9 | + ;; | |
| 10 | + | |
| 11 | + # 🐛: bug | |
| 12 | + bug|fix) | |
| 13 | + message="Fix a bug" | |
| 14 | + emoji="🐛" | |
| 15 | + ;; | |
| 16 | + | |
| 17 | + # 🤓: geek | |
| 18 | + human|human-fixed) | |
| 19 | + message="Human Fixed" | |
| 20 | + emoji="🤓" | |
| 21 | + ;; | |
| 22 | + | |
| 23 | + # 🤖: robot | |
| 24 | + ai|ai-generated) | |
| 25 | + message="AI generated" | |
| 26 | + emoji="🤖" | |
| 27 | + ;; | |
| 28 | + | |
| 29 | + # ✨: sparkles | |
| 30 | + sparkles|feature) | |
| 31 | + message="Introduce new feature(s)" | |
| 32 | + emoji="✨" | |
| 33 | + ;; | |
| 34 | + | |
| 35 | + # 🧩: jigsaw | |
| 36 | + jigsaw|example|examples|demo|demos) | |
| 37 | + message="Introduce new example(s)" | |
| 38 | + emoji="🧩" | |
| 39 | + ;; | |
| 40 | + | |
| 41 | + | |
| 42 | + # 📝: memo | |
| 43 | + memo|doc|documentation) | |
| 44 | + message="Add or update documentation" | |
| 45 | + emoji="📝" | |
| 46 | + ;; | |
| 47 | + | |
| 48 | + # 🌸: cherry_blossom | |
| 49 | + gardening|garden|clean|cleaning) | |
| 50 | + message="Gardening" | |
| 51 | + emoji="🌸" | |
| 52 | + ;; | |
| 53 | + | |
| 54 | + # 🚀: rocket | |
| 55 | + rocket|deploy) | |
| 56 | + message="Deploy stuff" | |
| 57 | + emoji="🚀" | |
| 58 | + ;; | |
| 59 | + | |
| 60 | + # 🎉: tada | |
| 61 | + tada|first) | |
| 62 | + message="Begin a project" | |
| 63 | + emoji="🎉" | |
| 64 | + ;; | |
| 65 | + | |
| 66 | + # 🚧: construction | |
| 67 | + construction|wip) | |
| 68 | + message="Work in progress" | |
| 69 | + emoji="🚧" | |
| 70 | + ;; | |
| 71 | + | |
| 72 | + # 📦️: package | |
| 73 | + package|build) | |
| 74 | + message="Add or update compiled files or packages" | |
| 75 | + emoji="📦️" | |
| 76 | + ;; | |
| 77 | + | |
| 78 | + # 📦️: package | |
| 79 | + release) | |
| 80 | + message="Create a release" | |
| 81 | + emoji="📦️" | |
| 82 | + ;; | |
| 83 | + | |
| 84 | + # 👽️: alien | |
| 85 | + alien|api) | |
| 86 | + message="Update code due to external API changes" | |
| 87 | + emoji="👽️" | |
| 88 | + ;; | |
| 89 | + | |
| 90 | + # 🐳: whale | |
| 91 | + docker|container) | |
| 92 | + message="Docker" | |
| 93 | + emoji="🐳" | |
| 94 | + ;; | |
| 95 | + | |
| 96 | + # 🍊: tangerine | |
| 97 | + gitpod|gitpodify) | |
| 98 | + message="Gitpodify" | |
| 99 | + emoji="🍊" | |
| 100 | + ;; | |
| 101 | + | |
| 102 | + # 🧪: test tube | |
| 103 | + alembic|experiments|experiment|xp) | |
| 104 | + message="Perform experiments" | |
| 105 | + emoji="🧪" | |
| 106 | + ;; | |
| 107 | + | |
| 108 | + # ✅: check mark | |
| 109 | + test|tests|testing) | |
| 110 | + message="Add or update tests" | |
| 111 | + emoji="✅" | |
| 112 | + ;; | |
| 113 | + | |
| 114 | + # 💾: floppy-disk | |
| 115 | + save) | |
| 116 | + message="Saved" | |
| 117 | + emoji="💾" | |
| 118 | + ;; | |
| 119 | + | |
| 120 | + *) | |
| 121 | + message="Updated" | |
| 122 | + emoji="🛟" | |
| 123 | + ;; | |
| 124 | + | |
| 125 | +esac | |
| 126 | + | |
| 127 | +find . -name '.DS_Store' -type f -delete | |
| 128 | + | |
| 129 | +if [ -z "$2" ] | |
| 130 | +then | |
| 131 | + # empty | |
| 132 | + git add .; git commit -m "$emoji $message."; git push | |
| 133 | +else | |
| 134 | + # not empty | |
| 135 | + git add .; git commit -m "$emoji $message: $2"; git push | |
| 136 | +fi | |
| new file mode 100755 | |||
| @@ -0,0 +1,136 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +message="" | ||
| 3 | +case $1 in | ||
| 4 | + | ||
| 5 | + # 🎨: art | ||
| 6 | + art) | ||
| 7 | + message="Improve structure / format of the code" | ||
| 8 | + emoji="🎨" | ||
| 9 | + ;; | ||
| 10 | + | ||
| 11 | + # 🐛: bug | ||
| 12 | + bug|fix) | ||
| 13 | + message="Fix a bug" | ||
| 14 | + emoji="🐛" | ||
| 15 | + ;; | ||
| 16 | + | ||
| 17 | + # 🤓: geek | ||
| 18 | + human|human-fixed) | ||
| 19 | + message="Human Fixed" | ||
| 20 | + emoji="🤓" | ||
| 21 | + ;; | ||
| 22 | + | ||
| 23 | + # 🤖: robot | ||
| 24 | + ai|ai-generated) | ||
| 25 | + message="AI generated" | ||
| 26 | + emoji="🤖" | ||
| 27 | + ;; | ||
| 28 | + | ||
| 29 | + # ✨: sparkles | ||
| 30 | + sparkles|feature) | ||
| 31 | + message="Introduce new feature(s)" | ||
| 32 | + emoji="✨" | ||
| 33 | + ;; | ||
| 34 | + | ||
| 35 | + # 🧩: jigsaw | ||
| 36 | + jigsaw|example|examples|demo|demos) | ||
| 37 | + message="Introduce new example(s)" | ||
| 38 | + emoji="🧩" | ||
| 39 | + ;; | ||
| 40 | + | ||
| 41 | + | ||
| 42 | + # 📝: memo | ||
| 43 | + memo|doc|documentation) | ||
| 44 | + message="Add or update documentation" | ||
| 45 | + emoji="📝" | ||
| 46 | + ;; | ||
| 47 | + | ||
| 48 | + # 🌸: cherry_blossom | ||
| 49 | + gardening|garden|clean|cleaning) | ||
| 50 | + message="Gardening" | ||
| 51 | + emoji="🌸" | ||
| 52 | + ;; | ||
| 53 | + | ||
| 54 | + # 🚀: rocket | ||
| 55 | + rocket|deploy) | ||
| 56 | + message="Deploy stuff" | ||
| 57 | + emoji="🚀" | ||
| 58 | + ;; | ||
| 59 | + | ||
| 60 | + # 🎉: tada | ||
| 61 | + tada|first) | ||
| 62 | + message="Begin a project" | ||
| 63 | + emoji="🎉" | ||
| 64 | + ;; | ||
| 65 | + | ||
| 66 | + # 🚧: construction | ||
| 67 | + construction|wip) | ||
| 68 | + message="Work in progress" | ||
| 69 | + emoji="🚧" | ||
| 70 | + ;; | ||
| 71 | + | ||
| 72 | + # 📦️: package | ||
| 73 | + package|build) | ||
| 74 | + message="Add or update compiled files or packages" | ||
| 75 | + emoji="📦️" | ||
| 76 | + ;; | ||
| 77 | + | ||
| 78 | + # 📦️: package | ||
| 79 | + release) | ||
| 80 | + message="Create a release" | ||
| 81 | + emoji="📦️" | ||
| 82 | + ;; | ||
| 83 | + | ||
| 84 | + # 👽️: alien | ||
| 85 | + alien|api) | ||
| 86 | + message="Update code due to external API changes" | ||
| 87 | + emoji="👽️" | ||
| 88 | + ;; | ||
| 89 | + | ||
| 90 | + # 🐳: whale | ||
| 91 | + docker|container) | ||
| 92 | + message="Docker" | ||
| 93 | + emoji="🐳" | ||
| 94 | + ;; | ||
| 95 | + | ||
| 96 | + # 🍊: tangerine | ||
| 97 | + gitpod|gitpodify) | ||
| 98 | + message="Gitpodify" | ||
| 99 | + emoji="🍊" | ||
| 100 | + ;; | ||
| 101 | + | ||
| 102 | + # 🧪: test tube | ||
| 103 | + alembic|experiments|experiment|xp) | ||
| 104 | + message="Perform experiments" | ||
| 105 | + emoji="🧪" | ||
| 106 | + ;; | ||
| 107 | + | ||
| 108 | + # ✅: check mark | ||
| 109 | + test|tests|testing) | ||
| 110 | + message="Add or update tests" | ||
| 111 | + emoji="✅" | ||
| 112 | + ;; | ||
| 113 | + | ||
| 114 | + # 💾: floppy-disk | ||
| 115 | + save) | ||
| 116 | + message="Saved" | ||
| 117 | + emoji="💾" | ||
| 118 | + ;; | ||
| 119 | + | ||
| 120 | + *) | ||
| 121 | + message="Updated" | ||
| 122 | + emoji="🛟" | ||
| 123 | + ;; | ||
| 124 | + | ||
| 125 | +esac | ||
| 126 | + | ||
| 127 | +find . -name '.DS_Store' -type f -delete | ||
| 128 | + | ||
| 129 | +if [ -z "$2" ] | ||
| 130 | +then | ||
| 131 | + # empty | ||
| 132 | + git add .; git commit -m "$emoji $message."; git push | ||
| 133 | +else | ||
| 134 | + # not empty | ||
| 135 | + git add .; git commit -m "$emoji $message: $2"; git push | ||
| 136 | +fi | ||
added
go.mod +23 -0 | new file mode 100644 | ||
| @@ -0,0 +1,23 @@ | ||
| 1 | +module rickub.com/turbo-editors/turbo-python | |
| 2 | + | |
| 3 | +go 1.26.1 | |
| 4 | + | |
| 5 | +require ( | |
| 6 | + github.com/gdamore/tcell/v2 v2.13.10 | |
| 7 | + rickub.com/turbo-editors/turbo-core v1.0.0 | |
| 8 | +) | |
| 9 | + | |
| 10 | +require ( | |
| 11 | + github.com/BurntSushi/toml v1.6.0 // indirect | |
| 12 | + github.com/gdamore/encoding v1.0.1 // indirect | |
| 13 | + github.com/lucasb-eyer/go-colorful v1.3.0 // indirect | |
| 14 | + github.com/rivo/uniseg v0.4.7 // indirect | |
| 15 | + golang.org/x/sys v0.38.0 // indirect | |
| 16 | + golang.org/x/term v0.37.0 // indirect | |
| 17 | + golang.org/x/text v0.31.0 // indirect | |
| 18 | +) | |
| 19 | + | |
| 20 | +// turbo-core is developed alongside the editors that use it. Point this at the | |
| 21 | +// checkout beside this one so the whole family builds from a clean clone of the | |
| 22 | +// three repositories; drop it once the version above is tagged and published. | |
| 23 | +// replace rickub.com/turbo-editors/turbo-core => ../turbo-core | |
| new file mode 100644 | |||
| @@ -0,0 +1,23 @@ | |||
| 1 | +module rickub.com/turbo-editors/turbo-python | ||
| 2 | + | ||
| 3 | +go 1.26.1 | ||
| 4 | + | ||
| 5 | +require ( | ||
| 6 | + github.com/gdamore/tcell/v2 v2.13.10 | ||
| 7 | + rickub.com/turbo-editors/turbo-core v1.0.0 | ||
| 8 | +) | ||
| 9 | + | ||
| 10 | +require ( | ||
| 11 | + github.com/BurntSushi/toml v1.6.0 // indirect | ||
| 12 | + github.com/gdamore/encoding v1.0.1 // indirect | ||
| 13 | + github.com/lucasb-eyer/go-colorful v1.3.0 // indirect | ||
| 14 | + github.com/rivo/uniseg v0.4.7 // indirect | ||
| 15 | + golang.org/x/sys v0.38.0 // indirect | ||
| 16 | + golang.org/x/term v0.37.0 // indirect | ||
| 17 | + golang.org/x/text v0.31.0 // indirect | ||
| 18 | +) | ||
| 19 | + | ||
| 20 | +// turbo-core is developed alongside the editors that use it. Point this at the | ||
| 21 | +// checkout beside this one so the whole family builds from a clean clone of the | ||
| 22 | +// three repositories; drop it once the version above is tagged and published. | ||
| 23 | +// replace rickub.com/turbo-editors/turbo-core => ../turbo-core | ||
added
go.sum +49 -0 | new file mode 100644 | ||
| @@ -0,0 +1,49 @@ | ||
| 1 | +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= | |
| 2 | +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= | |
| 3 | +github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= | |
| 4 | +github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= | |
| 5 | +github.com/gdamore/tcell/v2 v2.13.10 h1:Afs3JKt83HnhuUKdZ3MnxUgOqQRWftj5JyDqv1LLynA= | |
| 6 | +github.com/gdamore/tcell/v2 v2.13.10/go.mod h1:+Wfe208WDdB7INEtCsNrAN6O2m+wsTPk1RAovjaILlo= | |
| 7 | +github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= | |
| 8 | +github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= | |
| 9 | +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= | |
| 10 | +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= | |
| 11 | +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= | |
| 12 | +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= | |
| 13 | +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= | |
| 14 | +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= | |
| 15 | +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= | |
| 16 | +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= | |
| 17 | +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= | |
| 18 | +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= | |
| 19 | +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= | |
| 20 | +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | |
| 21 | +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | |
| 22 | +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | |
| 23 | +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | |
| 24 | +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | |
| 25 | +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | |
| 26 | +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | |
| 27 | +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | |
| 28 | +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | |
| 29 | +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= | |
| 30 | +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= | |
| 31 | +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= | |
| 32 | +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= | |
| 33 | +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= | |
| 34 | +golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= | |
| 35 | +golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= | |
| 36 | +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= | |
| 37 | +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= | |
| 38 | +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= | |
| 39 | +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= | |
| 40 | +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= | |
| 41 | +golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= | |
| 42 | +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= | |
| 43 | +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= | |
| 44 | +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= | |
| 45 | +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= | |
| 46 | +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= | |
| 47 | +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= | |
| 48 | +rickub.com/turbo-editors/turbo-core v1.0.0 h1:+tzwwONYXO46o+JpWHFR8PsGHTPLKtgd5NLZx9g3cdY= | |
| 49 | +rickub.com/turbo-editors/turbo-core v1.0.0/go.mod h1:rmfIY5gsFEo3sC5IIJFapwsGvdKG6NjrD7ACmnNTKq8= | |
| new file mode 100644 | |||
| @@ -0,0 +1,49 @@ | |||
| 1 | +github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk= | ||
| 2 | +github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= | ||
| 3 | +github.com/gdamore/encoding v1.0.1 h1:YzKZckdBL6jVt2Gc+5p82qhrGiqMdG/eNs6Wy0u3Uhw= | ||
| 4 | +github.com/gdamore/encoding v1.0.1/go.mod h1:0Z0cMFinngz9kS1QfMjCP8TY7em3bZYeeklsSDPivEo= | ||
| 5 | +github.com/gdamore/tcell/v2 v2.13.10 h1:Afs3JKt83HnhuUKdZ3MnxUgOqQRWftj5JyDqv1LLynA= | ||
| 6 | +github.com/gdamore/tcell/v2 v2.13.10/go.mod h1:+Wfe208WDdB7INEtCsNrAN6O2m+wsTPk1RAovjaILlo= | ||
| 7 | +github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag= | ||
| 8 | +github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= | ||
| 9 | +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= | ||
| 10 | +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= | ||
| 11 | +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= | ||
| 12 | +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= | ||
| 13 | +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= | ||
| 14 | +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= | ||
| 15 | +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= | ||
| 16 | +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= | ||
| 17 | +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= | ||
| 18 | +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= | ||
| 19 | +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= | ||
| 20 | +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | ||
| 21 | +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | ||
| 22 | +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= | ||
| 23 | +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= | ||
| 24 | +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= | ||
| 25 | +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
| 26 | +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
| 27 | +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
| 28 | +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= | ||
| 29 | +golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc= | ||
| 30 | +golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= | ||
| 31 | +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= | ||
| 32 | +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= | ||
| 33 | +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= | ||
| 34 | +golang.org/x/term v0.37.0 h1:8EGAD0qCmHYZg6J17DvsMy9/wJ7/D/4pV/wfnld5lTU= | ||
| 35 | +golang.org/x/term v0.37.0/go.mod h1:5pB4lxRNYYVZuTLmy8oR2BH8dflOR+IbTYFD8fi3254= | ||
| 36 | +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= | ||
| 37 | +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= | ||
| 38 | +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= | ||
| 39 | +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= | ||
| 40 | +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= | ||
| 41 | +golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= | ||
| 42 | +golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= | ||
| 43 | +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= | ||
| 44 | +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= | ||
| 45 | +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= | ||
| 46 | +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= | ||
| 47 | +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= | ||
| 48 | +rickub.com/turbo-editors/turbo-core v1.0.0 h1:+tzwwONYXO46o+JpWHFR8PsGHTPLKtgd5NLZx9g3cdY= | ||
| 49 | +rickub.com/turbo-editors/turbo-core v1.0.0/go.mod h1:rmfIY5gsFEo3sC5IIJFapwsGvdKG6NjrD7ACmnNTKq8= | ||
added
install_test.go +380 -0 | new file mode 100644 | ||
| @@ -0,0 +1,380 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "os" | |
| 5 | + "os/exec" | |
| 6 | + "path/filepath" | |
| 7 | + "runtime" | |
| 8 | + "strings" | |
| 9 | + "syscall" | |
| 10 | + "testing" | |
| 11 | +) | |
| 12 | + | |
| 13 | +// runInstaller runs scripts/install.sh with the given arguments and returns | |
| 14 | +// everything it printed, failing the test if it did not exit cleanly. | |
| 15 | +func runInstaller(t *testing.T, args ...string) string { | |
| 16 | + t.Helper() | |
| 17 | + | |
| 18 | + output, err := exec.Command("bash", append([]string{"scripts/install.sh"}, args...)...).CombinedOutput() | |
| 19 | + if err != nil { | |
| 20 | + t.Fatalf("scripts/install.sh %v failed: %v\n%s", args, err, output) | |
| 21 | + } | |
| 22 | + return string(output) | |
| 23 | +} | |
| 24 | + | |
| 25 | +// skipUnlessShellIsAvailable skips a test where the installer cannot run. | |
| 26 | +func skipUnlessShellIsAvailable(t *testing.T) { | |
| 27 | + t.Helper() | |
| 28 | + | |
| 29 | + if testing.Short() { | |
| 30 | + t.Skip("-short: the installer compiles the whole editor") | |
| 31 | + } | |
| 32 | + if runtime.GOOS == "windows" { | |
| 33 | + t.Skip("the installer is a shell script") | |
| 34 | + } | |
| 35 | + if _, err := exec.LookPath("bash"); err != nil { | |
| 36 | + t.Skip("bash is not available") | |
| 37 | + } | |
| 38 | +} | |
| 39 | + | |
| 40 | +func TestTheInstallerBuildsAWorkingBinary(t *testing.T) { | |
| 41 | + skipUnlessShellIsAvailable(t) | |
| 42 | + prefix := t.TempDir() | |
| 43 | + | |
| 44 | + output := runInstaller(t, "--prefix", prefix) | |
| 45 | + | |
| 46 | + binary := filepath.Join(prefix, "turbo-python") | |
| 47 | + info, err := os.Stat(binary) | |
| 48 | + if err != nil { | |
| 49 | + t.Fatalf("nothing was installed at %s: %v\n%s", binary, err, output) | |
| 50 | + } | |
| 51 | + if info.Mode().Perm()&0o111 == 0 { | |
| 52 | + t.Errorf("the installed file has permissions %o, want it executable", info.Mode().Perm()) | |
| 53 | + } | |
| 54 | + | |
| 55 | + version, err := exec.Command(binary, "-version").Output() | |
| 56 | + if err != nil { | |
| 57 | + t.Fatalf("the installed binary does not run: %v", err) | |
| 58 | + } | |
| 59 | + if !strings.Contains(string(version), "Turbo Python") { | |
| 60 | + t.Errorf("-version printed %q", version) | |
| 61 | + } | |
| 62 | +} | |
| 63 | + | |
| 64 | +func TestTheInstallerSaysWhereItPutThings(t *testing.T) { | |
| 65 | + skipUnlessShellIsAvailable(t) | |
| 66 | + prefix := t.TempDir() | |
| 67 | + | |
| 68 | + output := runInstaller(t, "--prefix", prefix) | |
| 69 | + | |
| 70 | + for _, want := range []string{"Turbo Python", prefix, "PATH", "pylsp"} { | |
| 71 | + if !strings.Contains(output, want) { | |
| 72 | + t.Errorf("the installer never mentions %q:\n%s", want, output) | |
| 73 | + } | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 77 | +func TestTheInstallerWarnsWhenThePrefixIsNotOnPath(t *testing.T) { | |
| 78 | + skipUnlessShellIsAvailable(t) | |
| 79 | + prefix := t.TempDir() // a fresh temporary directory is never on PATH | |
| 80 | + | |
| 81 | + output := runInstaller(t, "--prefix", prefix) | |
| 82 | + | |
| 83 | + if !strings.Contains(output, "not on your PATH") { | |
| 84 | + t.Errorf("the installer did not warn about the PATH:\n%s", output) | |
| 85 | + } | |
| 86 | + if !strings.Contains(output, "export PATH=") { | |
| 87 | + t.Errorf("the installer warned without saying how to fix it:\n%s", output) | |
| 88 | + } | |
| 89 | +} | |
| 90 | + | |
| 91 | +func TestTheInstallerRemovesWhatItInstalled(t *testing.T) { | |
| 92 | + skipUnlessShellIsAvailable(t) | |
| 93 | + prefix := t.TempDir() | |
| 94 | + runInstaller(t, "--prefix", prefix) | |
| 95 | + | |
| 96 | + runInstaller(t, "--prefix", prefix, "--uninstall") | |
| 97 | + | |
| 98 | + if _, err := os.Stat(filepath.Join(prefix, "turbo-python")); !os.IsNotExist(err) { | |
| 99 | + t.Error("the binary is still there after --uninstall") | |
| 100 | + } | |
| 101 | +} | |
| 102 | + | |
| 103 | +func TestUninstallingNothingIsNotAFailure(t *testing.T) { | |
| 104 | + skipUnlessShellIsAvailable(t) | |
| 105 | + | |
| 106 | + output := runInstaller(t, "--prefix", t.TempDir(), "--uninstall") | |
| 107 | + | |
| 108 | + if !strings.Contains(output, "nothing installed") { | |
| 109 | + t.Errorf("the installer did not say there was nothing to remove:\n%s", output) | |
| 110 | + } | |
| 111 | +} | |
| 112 | + | |
| 113 | +func TestTheInstallerExplainsItself(t *testing.T) { | |
| 114 | + skipUnlessShellIsAvailable(t) | |
| 115 | + | |
| 116 | + output := runInstaller(t, "--help") | |
| 117 | + | |
| 118 | + for _, want := range []string{"--prefix", "--with-server", "--uninstall"} { | |
| 119 | + if !strings.Contains(output, want) { | |
| 120 | + t.Errorf("--help does not document %q:\n%s", want, output) | |
| 121 | + } | |
| 122 | + } | |
| 123 | +} | |
| 124 | + | |
| 125 | +func TestTheInstallerRefusesAnUnknownOption(t *testing.T) { | |
| 126 | + skipUnlessShellIsAvailable(t) | |
| 127 | + | |
| 128 | + output, err := exec.Command("bash", "scripts/install.sh", "--nonsense").CombinedOutput() | |
| 129 | + | |
| 130 | + if err == nil { | |
| 131 | + t.Fatal("the installer accepted an option it does not have") | |
| 132 | + } | |
| 133 | + if !strings.Contains(string(output), "unknown option") { | |
| 134 | + t.Errorf("the installer did not say what was wrong:\n%s", output) | |
| 135 | + } | |
| 136 | +} | |
| 137 | + | |
| 138 | +func TestTheInstallerNeedsADirectoryAfterPrefix(t *testing.T) { | |
| 139 | + skipUnlessShellIsAvailable(t) | |
| 140 | + | |
| 141 | + output, err := exec.Command("bash", "scripts/install.sh", "--prefix").CombinedOutput() | |
| 142 | + | |
| 143 | + if err == nil { | |
| 144 | + t.Fatal("--prefix was accepted with nothing after it") | |
| 145 | + } | |
| 146 | + if !strings.Contains(string(output), "needs a directory") { | |
| 147 | + t.Errorf("the installer did not say what was wrong:\n%s", output) | |
| 148 | + } | |
| 149 | +} | |
| 150 | + | |
| 151 | +func TestTheInstallerRunsFromAnyDirectory(t *testing.T) { | |
| 152 | + skipUnlessShellIsAvailable(t) | |
| 153 | + repo, err := filepath.Abs(".") | |
| 154 | + if err != nil { | |
| 155 | + t.Fatalf("Abs() error = %v", err) | |
| 156 | + } | |
| 157 | + prefix := t.TempDir() | |
| 158 | + | |
| 159 | + // It is invoked by absolute path from somewhere else entirely, as it would | |
| 160 | + // be from a shell alias or another script. | |
| 161 | + command := exec.Command("bash", filepath.Join(repo, "scripts", "install.sh"), "--prefix", prefix) | |
| 162 | + command.Dir = t.TempDir() | |
| 163 | + if output, err := command.CombinedOutput(); err != nil { | |
| 164 | + t.Fatalf("the installer failed when run from elsewhere: %v\n%s", err, output) | |
| 165 | + } | |
| 166 | + | |
| 167 | + if _, err := os.Stat(filepath.Join(prefix, "turbo-python")); err != nil { | |
| 168 | + t.Errorf("nothing was installed: %v", err) | |
| 169 | + } | |
| 170 | +} | |
| 171 | + | |
| 172 | +func TestAFailedBuildLeavesTheInstalledBinaryAlone(t *testing.T) { | |
| 173 | + skipUnlessShellIsAvailable(t) | |
| 174 | + prefix := t.TempDir() | |
| 175 | + runInstaller(t, "--prefix", prefix) | |
| 176 | + | |
| 177 | + binary := filepath.Join(prefix, "turbo-python") | |
| 178 | + before, err := os.Stat(binary) | |
| 179 | + if err != nil { | |
| 180 | + t.Fatalf("the first install produced nothing: %v", err) | |
| 181 | + } | |
| 182 | + | |
| 183 | + // A stray file in package main is exactly what a user's own scratch file | |
| 184 | + // does to this repository, and it must not cost them their installation. | |
| 185 | + stray := filepath.Join("scripts", "..", "zz_broken_on_purpose.go") | |
| 186 | + if err := os.WriteFile(stray, []byte("package main\n\nfunc main() {}\n"), 0o644); err != nil { | |
| 187 | + t.Fatalf("writing the stray file: %v", err) | |
| 188 | + } | |
| 189 | + t.Cleanup(func() { os.Remove(stray) }) | |
| 190 | + | |
| 191 | + output, err := exec.Command("bash", "scripts/install.sh", "--prefix", prefix).CombinedOutput() | |
| 192 | + | |
| 193 | + if err == nil { | |
| 194 | + t.Fatal("the installer reported success on a build that cannot succeed") | |
| 195 | + } | |
| 196 | + if !strings.Contains(string(output), "nothing was installed") { | |
| 197 | + t.Errorf("the installer did not say the installation was untouched:\n%s", output) | |
| 198 | + } | |
| 199 | + after, err := os.Stat(binary) | |
| 200 | + if err != nil { | |
| 201 | + t.Fatalf("the failed build removed the installed binary: %v", err) | |
| 202 | + } | |
| 203 | + if !after.ModTime().Equal(before.ModTime()) { | |
| 204 | + t.Error("the failed build replaced the installed binary") | |
| 205 | + } | |
| 206 | +} | |
| 207 | + | |
| 208 | +func TestReinstallingReplacesTheFileRatherThanOverwritingIt(t *testing.T) { | |
| 209 | + // macOS caches a binary's code signature against its inode. Writing new | |
| 210 | + // bytes into the same inode — which is what cp does — leaves the cached | |
| 211 | + // signature describing something else, and the kernel then refuses to | |
| 212 | + // execute it: builds fine, installs fine, "does not run". Replacing the | |
| 213 | + // directory entry with a fresh inode is what avoids that, and it makes the | |
| 214 | + // install atomic besides. | |
| 215 | + skipUnlessShellIsAvailable(t) | |
| 216 | + prefix := t.TempDir() | |
| 217 | + binary := filepath.Join(prefix, "turbo-python") | |
| 218 | + | |
| 219 | + runInstaller(t, "--prefix", prefix) | |
| 220 | + first := inodeOf(t, binary) | |
| 221 | + | |
| 222 | + runInstaller(t, "--prefix", prefix) | |
| 223 | + second := inodeOf(t, binary) | |
| 224 | + | |
| 225 | + if first == second { | |
| 226 | + t.Errorf("the reinstall wrote into the same inode (%d); it must replace the file", first) | |
| 227 | + } | |
| 228 | +} | |
| 229 | + | |
| 230 | +func TestReinstallingLeavesAWorkingBinary(t *testing.T) { | |
| 231 | + skipUnlessShellIsAvailable(t) | |
| 232 | + prefix := t.TempDir() | |
| 233 | + binary := filepath.Join(prefix, "turbo-python") | |
| 234 | + | |
| 235 | + runInstaller(t, "--prefix", prefix) | |
| 236 | + runInstaller(t, "--prefix", prefix) | |
| 237 | + | |
| 238 | + if _, err := exec.Command(binary, "-version").Output(); err != nil { | |
| 239 | + t.Fatalf("the reinstalled binary does not run: %v", err) | |
| 240 | + } | |
| 241 | +} | |
| 242 | + | |
| 243 | +func TestABinaryThatWillNotRunIsReportedWithItsOwnError(t *testing.T) { | |
| 244 | + // "the installed binary does not run" on its own tells whoever hit it | |
| 245 | + // nothing they can act on. Whatever the system said has to come through. | |
| 246 | + skipUnlessShellIsAvailable(t) | |
| 247 | + | |
| 248 | + if !strings.Contains(readInstaller(t), "$verify") { | |
| 249 | + t.Error("the installer discards what the binary said when it will not run") | |
| 250 | + } | |
| 251 | +} | |
| 252 | + | |
| 253 | +// readInstaller returns the installer's source. | |
| 254 | +func readInstaller(t *testing.T) string { | |
| 255 | + t.Helper() | |
| 256 | + | |
| 257 | + data, err := os.ReadFile("scripts/install.sh") | |
| 258 | + if err != nil { | |
| 259 | + t.Fatalf("reading the installer: %v", err) | |
| 260 | + } | |
| 261 | + return string(data) | |
| 262 | +} | |
| 263 | + | |
| 264 | +// inodeOf returns a file's inode number. | |
| 265 | +func inodeOf(t *testing.T, path string) uint64 { | |
| 266 | + t.Helper() | |
| 267 | + | |
| 268 | + info, err := os.Stat(path) | |
| 269 | + if err != nil { | |
| 270 | + t.Fatalf("stat %s: %v", path, err) | |
| 271 | + } | |
| 272 | + stat, ok := info.Sys().(*syscall.Stat_t) | |
| 273 | + if !ok { | |
| 274 | + t.Skip("inode numbers are not available on this platform") | |
| 275 | + } | |
| 276 | + return uint64(stat.Ino) | |
| 277 | +} | |
| 278 | + | |
| 279 | +func TestTheInstalledBinaryReportsTheCommitItWasBuiltFrom(t *testing.T) { | |
| 280 | + // The point of stamping: an installed editor must name the commit it came | |
| 281 | + // from, not a constant somebody forgot to bump before releasing. | |
| 282 | + skipUnlessShellIsAvailable(t) | |
| 283 | + prefix := t.TempDir() | |
| 284 | + | |
| 285 | + runInstaller(t, "--prefix", prefix) | |
| 286 | + | |
| 287 | + reported, err := exec.Command(filepath.Join(prefix, "turbo-python"), "-version").Output() | |
| 288 | + if err != nil { | |
| 289 | + t.Fatalf("the installed binary does not run: %v", err) | |
| 290 | + } | |
| 291 | + | |
| 292 | + commit, err := exec.Command("git", "rev-parse", "--short", "HEAD").Output() | |
| 293 | + if err != nil { | |
| 294 | + t.Skip("not a git checkout, so there is no commit to stamp") | |
| 295 | + } | |
| 296 | + if want := strings.TrimSpace(string(commit)); !strings.Contains(string(reported), want) { | |
| 297 | + t.Errorf("-version printed %q, which never mentions the commit %s", reported, want) | |
| 298 | + } | |
| 299 | +} | |
| 300 | + | |
| 301 | +func TestTheInstalledBinaryDoesNotReportAnUnknownVersion(t *testing.T) { | |
| 302 | + // "unknown" is what the binary says when *no* source could name it, and | |
| 303 | + // seeing it here would mean the installer's ldflags never reached the | |
| 304 | + // linker. "devel" is a different thing: it is what a correct build of a | |
| 305 | + // checkout with no tags reports, so a checkout that has never been tagged | |
| 306 | + // must not fail this. | |
| 307 | + // | |
| 308 | + // What proves the stamp arrived either way is the commit, which only the | |
| 309 | + // linker can have supplied. | |
| 310 | + skipUnlessShellIsAvailable(t) | |
| 311 | + | |
| 312 | + // Outside a git checkout the installer has nothing to stamp *with*, and | |
| 313 | + // "unknown" is then the correct answer rather than a failure — so the | |
| 314 | + // premise is checked before anything is asserted on. | |
| 315 | + commit, err := exec.Command("git", "rev-parse", "--short", "HEAD").Output() | |
| 316 | + if err != nil { | |
| 317 | + t.Skip("not a git checkout, so there is nothing for the installer to stamp") | |
| 318 | + } | |
| 319 | + prefix := t.TempDir() | |
| 320 | + | |
| 321 | + runInstaller(t, "--prefix", prefix) | |
| 322 | + | |
| 323 | + reported, err := exec.Command(filepath.Join(prefix, "turbo-python"), "-version").Output() | |
| 324 | + if err != nil { | |
| 325 | + t.Fatalf("the installed binary does not run: %v", err) | |
| 326 | + } | |
| 327 | + if strings.Contains(string(reported), "unknown") { | |
| 328 | + t.Errorf("-version printed %q, so nothing reached the linker at all", reported) | |
| 329 | + } | |
| 330 | + if want := strings.TrimSpace(string(commit)); !strings.Contains(string(reported), want) { | |
| 331 | + t.Errorf("-version printed %q, want it to carry the commit %q", reported, want) | |
| 332 | + } | |
| 333 | +} | |
| 334 | + | |
| 335 | +func TestTheInstallerStampsThroughTheLinker(t *testing.T) { | |
| 336 | + // A build outside a git checkout has nothing to describe, and must still | |
| 337 | + // build rather than passing a half-built -X flag to the linker. | |
| 338 | + script := readInstaller(t) | |
| 339 | + | |
| 340 | + for _, want := range []string{"turbo-core/version", "-ldflags", "describe --tags --dirty"} { | |
| 341 | + if !strings.Contains(script, want) { | |
| 342 | + t.Errorf("the installer never mentions %q", want) | |
| 343 | + } | |
| 344 | + } | |
| 345 | + if !strings.Contains(script, `ldflags=""`) { | |
| 346 | + t.Error("the installer has no path for a checkout git cannot describe") | |
| 347 | + } | |
| 348 | +} | |
| 349 | + | |
| 350 | +// A pylsp with no linters publishes an empty problem list for a file that does | |
| 351 | +// not parse, and a blank gutter for that reason looks exactly like a blank | |
| 352 | +// gutter because the code is fine. The installer has to say so, which means | |
| 353 | +// this check has to exist and has to be reached. | |
| 354 | +func TestTheInstallerChecksThatTheServerCanProduceDiagnostics(t *testing.T) { | |
| 355 | + source, err := os.ReadFile("scripts/install.sh") | |
| 356 | + if err != nil { | |
| 357 | + t.Fatalf("reading the installer: %v", err) | |
| 358 | + } | |
| 359 | + script := string(source) | |
| 360 | + | |
| 361 | + for _, want := range []string{"server_has_linters", "import pyflakes", "no error marks"} { | |
| 362 | + if !strings.Contains(script, want) { | |
| 363 | + t.Errorf("the installer never mentions %q", want) | |
| 364 | + } | |
| 365 | + } | |
| 366 | +} | |
| 367 | + | |
| 368 | +// Finding the file is not the same as its running, and this family has been | |
| 369 | +// caught by that twice — rustup's shim for Turbo Rust, and a stale tool | |
| 370 | +// directory here. | |
| 371 | +func TestTheInstallerRunsTheServerRatherThanStattingIt(t *testing.T) { | |
| 372 | + source, err := os.ReadFile("scripts/install.sh") | |
| 373 | + if err != nil { | |
| 374 | + t.Fatalf("reading the installer: %v", err) | |
| 375 | + } | |
| 376 | + | |
| 377 | + if !strings.Contains(string(source), `"$candidate" --version`) { | |
| 378 | + t.Error("find_server never runs the candidate; an unusable shim would be reported as installed") | |
| 379 | + } | |
| 380 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,380 @@ | |||
| 1 | +package main | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "os" | ||
| 5 | + "os/exec" | ||
| 6 | + "path/filepath" | ||
| 7 | + "runtime" | ||
| 8 | + "strings" | ||
| 9 | + "syscall" | ||
| 10 | + "testing" | ||
| 11 | +) | ||
| 12 | + | ||
| 13 | +// runInstaller runs scripts/install.sh with the given arguments and returns | ||
| 14 | +// everything it printed, failing the test if it did not exit cleanly. | ||
| 15 | +func runInstaller(t *testing.T, args ...string) string { | ||
| 16 | + t.Helper() | ||
| 17 | + | ||
| 18 | + output, err := exec.Command("bash", append([]string{"scripts/install.sh"}, args...)...).CombinedOutput() | ||
| 19 | + if err != nil { | ||
| 20 | + t.Fatalf("scripts/install.sh %v failed: %v\n%s", args, err, output) | ||
| 21 | + } | ||
| 22 | + return string(output) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +// skipUnlessShellIsAvailable skips a test where the installer cannot run. | ||
| 26 | +func skipUnlessShellIsAvailable(t *testing.T) { | ||
| 27 | + t.Helper() | ||
| 28 | + | ||
| 29 | + if testing.Short() { | ||
| 30 | + t.Skip("-short: the installer compiles the whole editor") | ||
| 31 | + } | ||
| 32 | + if runtime.GOOS == "windows" { | ||
| 33 | + t.Skip("the installer is a shell script") | ||
| 34 | + } | ||
| 35 | + if _, err := exec.LookPath("bash"); err != nil { | ||
| 36 | + t.Skip("bash is not available") | ||
| 37 | + } | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +func TestTheInstallerBuildsAWorkingBinary(t *testing.T) { | ||
| 41 | + skipUnlessShellIsAvailable(t) | ||
| 42 | + prefix := t.TempDir() | ||
| 43 | + | ||
| 44 | + output := runInstaller(t, "--prefix", prefix) | ||
| 45 | + | ||
| 46 | + binary := filepath.Join(prefix, "turbo-python") | ||
| 47 | + info, err := os.Stat(binary) | ||
| 48 | + if err != nil { | ||
| 49 | + t.Fatalf("nothing was installed at %s: %v\n%s", binary, err, output) | ||
| 50 | + } | ||
| 51 | + if info.Mode().Perm()&0o111 == 0 { | ||
| 52 | + t.Errorf("the installed file has permissions %o, want it executable", info.Mode().Perm()) | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + version, err := exec.Command(binary, "-version").Output() | ||
| 56 | + if err != nil { | ||
| 57 | + t.Fatalf("the installed binary does not run: %v", err) | ||
| 58 | + } | ||
| 59 | + if !strings.Contains(string(version), "Turbo Python") { | ||
| 60 | + t.Errorf("-version printed %q", version) | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +func TestTheInstallerSaysWhereItPutThings(t *testing.T) { | ||
| 65 | + skipUnlessShellIsAvailable(t) | ||
| 66 | + prefix := t.TempDir() | ||
| 67 | + | ||
| 68 | + output := runInstaller(t, "--prefix", prefix) | ||
| 69 | + | ||
| 70 | + for _, want := range []string{"Turbo Python", prefix, "PATH", "pylsp"} { | ||
| 71 | + if !strings.Contains(output, want) { | ||
| 72 | + t.Errorf("the installer never mentions %q:\n%s", want, output) | ||
| 73 | + } | ||
| 74 | + } | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +func TestTheInstallerWarnsWhenThePrefixIsNotOnPath(t *testing.T) { | ||
| 78 | + skipUnlessShellIsAvailable(t) | ||
| 79 | + prefix := t.TempDir() // a fresh temporary directory is never on PATH | ||
| 80 | + | ||
| 81 | + output := runInstaller(t, "--prefix", prefix) | ||
| 82 | + | ||
| 83 | + if !strings.Contains(output, "not on your PATH") { | ||
| 84 | + t.Errorf("the installer did not warn about the PATH:\n%s", output) | ||
| 85 | + } | ||
| 86 | + if !strings.Contains(output, "export PATH=") { | ||
| 87 | + t.Errorf("the installer warned without saying how to fix it:\n%s", output) | ||
| 88 | + } | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +func TestTheInstallerRemovesWhatItInstalled(t *testing.T) { | ||
| 92 | + skipUnlessShellIsAvailable(t) | ||
| 93 | + prefix := t.TempDir() | ||
| 94 | + runInstaller(t, "--prefix", prefix) | ||
| 95 | + | ||
| 96 | + runInstaller(t, "--prefix", prefix, "--uninstall") | ||
| 97 | + | ||
| 98 | + if _, err := os.Stat(filepath.Join(prefix, "turbo-python")); !os.IsNotExist(err) { | ||
| 99 | + t.Error("the binary is still there after --uninstall") | ||
| 100 | + } | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +func TestUninstallingNothingIsNotAFailure(t *testing.T) { | ||
| 104 | + skipUnlessShellIsAvailable(t) | ||
| 105 | + | ||
| 106 | + output := runInstaller(t, "--prefix", t.TempDir(), "--uninstall") | ||
| 107 | + | ||
| 108 | + if !strings.Contains(output, "nothing installed") { | ||
| 109 | + t.Errorf("the installer did not say there was nothing to remove:\n%s", output) | ||
| 110 | + } | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +func TestTheInstallerExplainsItself(t *testing.T) { | ||
| 114 | + skipUnlessShellIsAvailable(t) | ||
| 115 | + | ||
| 116 | + output := runInstaller(t, "--help") | ||
| 117 | + | ||
| 118 | + for _, want := range []string{"--prefix", "--with-server", "--uninstall"} { | ||
| 119 | + if !strings.Contains(output, want) { | ||
| 120 | + t.Errorf("--help does not document %q:\n%s", want, output) | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +func TestTheInstallerRefusesAnUnknownOption(t *testing.T) { | ||
| 126 | + skipUnlessShellIsAvailable(t) | ||
| 127 | + | ||
| 128 | + output, err := exec.Command("bash", "scripts/install.sh", "--nonsense").CombinedOutput() | ||
| 129 | + | ||
| 130 | + if err == nil { | ||
| 131 | + t.Fatal("the installer accepted an option it does not have") | ||
| 132 | + } | ||
| 133 | + if !strings.Contains(string(output), "unknown option") { | ||
| 134 | + t.Errorf("the installer did not say what was wrong:\n%s", output) | ||
| 135 | + } | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +func TestTheInstallerNeedsADirectoryAfterPrefix(t *testing.T) { | ||
| 139 | + skipUnlessShellIsAvailable(t) | ||
| 140 | + | ||
| 141 | + output, err := exec.Command("bash", "scripts/install.sh", "--prefix").CombinedOutput() | ||
| 142 | + | ||
| 143 | + if err == nil { | ||
| 144 | + t.Fatal("--prefix was accepted with nothing after it") | ||
| 145 | + } | ||
| 146 | + if !strings.Contains(string(output), "needs a directory") { | ||
| 147 | + t.Errorf("the installer did not say what was wrong:\n%s", output) | ||
| 148 | + } | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +func TestTheInstallerRunsFromAnyDirectory(t *testing.T) { | ||
| 152 | + skipUnlessShellIsAvailable(t) | ||
| 153 | + repo, err := filepath.Abs(".") | ||
| 154 | + if err != nil { | ||
| 155 | + t.Fatalf("Abs() error = %v", err) | ||
| 156 | + } | ||
| 157 | + prefix := t.TempDir() | ||
| 158 | + | ||
| 159 | + // It is invoked by absolute path from somewhere else entirely, as it would | ||
| 160 | + // be from a shell alias or another script. | ||
| 161 | + command := exec.Command("bash", filepath.Join(repo, "scripts", "install.sh"), "--prefix", prefix) | ||
| 162 | + command.Dir = t.TempDir() | ||
| 163 | + if output, err := command.CombinedOutput(); err != nil { | ||
| 164 | + t.Fatalf("the installer failed when run from elsewhere: %v\n%s", err, output) | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + if _, err := os.Stat(filepath.Join(prefix, "turbo-python")); err != nil { | ||
| 168 | + t.Errorf("nothing was installed: %v", err) | ||
| 169 | + } | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +func TestAFailedBuildLeavesTheInstalledBinaryAlone(t *testing.T) { | ||
| 173 | + skipUnlessShellIsAvailable(t) | ||
| 174 | + prefix := t.TempDir() | ||
| 175 | + runInstaller(t, "--prefix", prefix) | ||
| 176 | + | ||
| 177 | + binary := filepath.Join(prefix, "turbo-python") | ||
| 178 | + before, err := os.Stat(binary) | ||
| 179 | + if err != nil { | ||
| 180 | + t.Fatalf("the first install produced nothing: %v", err) | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + // A stray file in package main is exactly what a user's own scratch file | ||
| 184 | + // does to this repository, and it must not cost them their installation. | ||
| 185 | + stray := filepath.Join("scripts", "..", "zz_broken_on_purpose.go") | ||
| 186 | + if err := os.WriteFile(stray, []byte("package main\n\nfunc main() {}\n"), 0o644); err != nil { | ||
| 187 | + t.Fatalf("writing the stray file: %v", err) | ||
| 188 | + } | ||
| 189 | + t.Cleanup(func() { os.Remove(stray) }) | ||
| 190 | + | ||
| 191 | + output, err := exec.Command("bash", "scripts/install.sh", "--prefix", prefix).CombinedOutput() | ||
| 192 | + | ||
| 193 | + if err == nil { | ||
| 194 | + t.Fatal("the installer reported success on a build that cannot succeed") | ||
| 195 | + } | ||
| 196 | + if !strings.Contains(string(output), "nothing was installed") { | ||
| 197 | + t.Errorf("the installer did not say the installation was untouched:\n%s", output) | ||
| 198 | + } | ||
| 199 | + after, err := os.Stat(binary) | ||
| 200 | + if err != nil { | ||
| 201 | + t.Fatalf("the failed build removed the installed binary: %v", err) | ||
| 202 | + } | ||
| 203 | + if !after.ModTime().Equal(before.ModTime()) { | ||
| 204 | + t.Error("the failed build replaced the installed binary") | ||
| 205 | + } | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +func TestReinstallingReplacesTheFileRatherThanOverwritingIt(t *testing.T) { | ||
| 209 | + // macOS caches a binary's code signature against its inode. Writing new | ||
| 210 | + // bytes into the same inode — which is what cp does — leaves the cached | ||
| 211 | + // signature describing something else, and the kernel then refuses to | ||
| 212 | + // execute it: builds fine, installs fine, "does not run". Replacing the | ||
| 213 | + // directory entry with a fresh inode is what avoids that, and it makes the | ||
| 214 | + // install atomic besides. | ||
| 215 | + skipUnlessShellIsAvailable(t) | ||
| 216 | + prefix := t.TempDir() | ||
| 217 | + binary := filepath.Join(prefix, "turbo-python") | ||
| 218 | + | ||
| 219 | + runInstaller(t, "--prefix", prefix) | ||
| 220 | + first := inodeOf(t, binary) | ||
| 221 | + | ||
| 222 | + runInstaller(t, "--prefix", prefix) | ||
| 223 | + second := inodeOf(t, binary) | ||
| 224 | + | ||
| 225 | + if first == second { | ||
| 226 | + t.Errorf("the reinstall wrote into the same inode (%d); it must replace the file", first) | ||
| 227 | + } | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +func TestReinstallingLeavesAWorkingBinary(t *testing.T) { | ||
| 231 | + skipUnlessShellIsAvailable(t) | ||
| 232 | + prefix := t.TempDir() | ||
| 233 | + binary := filepath.Join(prefix, "turbo-python") | ||
| 234 | + | ||
| 235 | + runInstaller(t, "--prefix", prefix) | ||
| 236 | + runInstaller(t, "--prefix", prefix) | ||
| 237 | + | ||
| 238 | + if _, err := exec.Command(binary, "-version").Output(); err != nil { | ||
| 239 | + t.Fatalf("the reinstalled binary does not run: %v", err) | ||
| 240 | + } | ||
| 241 | +} | ||
| 242 | + | ||
| 243 | +func TestABinaryThatWillNotRunIsReportedWithItsOwnError(t *testing.T) { | ||
| 244 | + // "the installed binary does not run" on its own tells whoever hit it | ||
| 245 | + // nothing they can act on. Whatever the system said has to come through. | ||
| 246 | + skipUnlessShellIsAvailable(t) | ||
| 247 | + | ||
| 248 | + if !strings.Contains(readInstaller(t), "$verify") { | ||
| 249 | + t.Error("the installer discards what the binary said when it will not run") | ||
| 250 | + } | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +// readInstaller returns the installer's source. | ||
| 254 | +func readInstaller(t *testing.T) string { | ||
| 255 | + t.Helper() | ||
| 256 | + | ||
| 257 | + data, err := os.ReadFile("scripts/install.sh") | ||
| 258 | + if err != nil { | ||
| 259 | + t.Fatalf("reading the installer: %v", err) | ||
| 260 | + } | ||
| 261 | + return string(data) | ||
| 262 | +} | ||
| 263 | + | ||
| 264 | +// inodeOf returns a file's inode number. | ||
| 265 | +func inodeOf(t *testing.T, path string) uint64 { | ||
| 266 | + t.Helper() | ||
| 267 | + | ||
| 268 | + info, err := os.Stat(path) | ||
| 269 | + if err != nil { | ||
| 270 | + t.Fatalf("stat %s: %v", path, err) | ||
| 271 | + } | ||
| 272 | + stat, ok := info.Sys().(*syscall.Stat_t) | ||
| 273 | + if !ok { | ||
| 274 | + t.Skip("inode numbers are not available on this platform") | ||
| 275 | + } | ||
| 276 | + return uint64(stat.Ino) | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +func TestTheInstalledBinaryReportsTheCommitItWasBuiltFrom(t *testing.T) { | ||
| 280 | + // The point of stamping: an installed editor must name the commit it came | ||
| 281 | + // from, not a constant somebody forgot to bump before releasing. | ||
| 282 | + skipUnlessShellIsAvailable(t) | ||
| 283 | + prefix := t.TempDir() | ||
| 284 | + | ||
| 285 | + runInstaller(t, "--prefix", prefix) | ||
| 286 | + | ||
| 287 | + reported, err := exec.Command(filepath.Join(prefix, "turbo-python"), "-version").Output() | ||
| 288 | + if err != nil { | ||
| 289 | + t.Fatalf("the installed binary does not run: %v", err) | ||
| 290 | + } | ||
| 291 | + | ||
| 292 | + commit, err := exec.Command("git", "rev-parse", "--short", "HEAD").Output() | ||
| 293 | + if err != nil { | ||
| 294 | + t.Skip("not a git checkout, so there is no commit to stamp") | ||
| 295 | + } | ||
| 296 | + if want := strings.TrimSpace(string(commit)); !strings.Contains(string(reported), want) { | ||
| 297 | + t.Errorf("-version printed %q, which never mentions the commit %s", reported, want) | ||
| 298 | + } | ||
| 299 | +} | ||
| 300 | + | ||
| 301 | +func TestTheInstalledBinaryDoesNotReportAnUnknownVersion(t *testing.T) { | ||
| 302 | + // "unknown" is what the binary says when *no* source could name it, and | ||
| 303 | + // seeing it here would mean the installer's ldflags never reached the | ||
| 304 | + // linker. "devel" is a different thing: it is what a correct build of a | ||
| 305 | + // checkout with no tags reports, so a checkout that has never been tagged | ||
| 306 | + // must not fail this. | ||
| 307 | + // | ||
| 308 | + // What proves the stamp arrived either way is the commit, which only the | ||
| 309 | + // linker can have supplied. | ||
| 310 | + skipUnlessShellIsAvailable(t) | ||
| 311 | + | ||
| 312 | + // Outside a git checkout the installer has nothing to stamp *with*, and | ||
| 313 | + // "unknown" is then the correct answer rather than a failure — so the | ||
| 314 | + // premise is checked before anything is asserted on. | ||
| 315 | + commit, err := exec.Command("git", "rev-parse", "--short", "HEAD").Output() | ||
| 316 | + if err != nil { | ||
| 317 | + t.Skip("not a git checkout, so there is nothing for the installer to stamp") | ||
| 318 | + } | ||
| 319 | + prefix := t.TempDir() | ||
| 320 | + | ||
| 321 | + runInstaller(t, "--prefix", prefix) | ||
| 322 | + | ||
| 323 | + reported, err := exec.Command(filepath.Join(prefix, "turbo-python"), "-version").Output() | ||
| 324 | + if err != nil { | ||
| 325 | + t.Fatalf("the installed binary does not run: %v", err) | ||
| 326 | + } | ||
| 327 | + if strings.Contains(string(reported), "unknown") { | ||
| 328 | + t.Errorf("-version printed %q, so nothing reached the linker at all", reported) | ||
| 329 | + } | ||
| 330 | + if want := strings.TrimSpace(string(commit)); !strings.Contains(string(reported), want) { | ||
| 331 | + t.Errorf("-version printed %q, want it to carry the commit %q", reported, want) | ||
| 332 | + } | ||
| 333 | +} | ||
| 334 | + | ||
| 335 | +func TestTheInstallerStampsThroughTheLinker(t *testing.T) { | ||
| 336 | + // A build outside a git checkout has nothing to describe, and must still | ||
| 337 | + // build rather than passing a half-built -X flag to the linker. | ||
| 338 | + script := readInstaller(t) | ||
| 339 | + | ||
| 340 | + for _, want := range []string{"turbo-core/version", "-ldflags", "describe --tags --dirty"} { | ||
| 341 | + if !strings.Contains(script, want) { | ||
| 342 | + t.Errorf("the installer never mentions %q", want) | ||
| 343 | + } | ||
| 344 | + } | ||
| 345 | + if !strings.Contains(script, `ldflags=""`) { | ||
| 346 | + t.Error("the installer has no path for a checkout git cannot describe") | ||
| 347 | + } | ||
| 348 | +} | ||
| 349 | + | ||
| 350 | +// A pylsp with no linters publishes an empty problem list for a file that does | ||
| 351 | +// not parse, and a blank gutter for that reason looks exactly like a blank | ||
| 352 | +// gutter because the code is fine. The installer has to say so, which means | ||
| 353 | +// this check has to exist and has to be reached. | ||
| 354 | +func TestTheInstallerChecksThatTheServerCanProduceDiagnostics(t *testing.T) { | ||
| 355 | + source, err := os.ReadFile("scripts/install.sh") | ||
| 356 | + if err != nil { | ||
| 357 | + t.Fatalf("reading the installer: %v", err) | ||
| 358 | + } | ||
| 359 | + script := string(source) | ||
| 360 | + | ||
| 361 | + for _, want := range []string{"server_has_linters", "import pyflakes", "no error marks"} { | ||
| 362 | + if !strings.Contains(script, want) { | ||
| 363 | + t.Errorf("the installer never mentions %q", want) | ||
| 364 | + } | ||
| 365 | + } | ||
| 366 | +} | ||
| 367 | + | ||
| 368 | +// Finding the file is not the same as its running, and this family has been | ||
| 369 | +// caught by that twice — rustup's shim for Turbo Rust, and a stale tool | ||
| 370 | +// directory here. | ||
| 371 | +func TestTheInstallerRunsTheServerRatherThanStattingIt(t *testing.T) { | ||
| 372 | + source, err := os.ReadFile("scripts/install.sh") | ||
| 373 | + if err != nil { | ||
| 374 | + t.Fatalf("reading the installer: %v", err) | ||
| 375 | + } | ||
| 376 | + | ||
| 377 | + if !strings.Contains(string(source), `"$candidate" --version`) { | ||
| 378 | + t.Error("find_server never runs the candidate; an unusable shim would be reported as installed") | ||
| 379 | + } | ||
| 380 | +} | ||
added
internal/pythonlang/acp.toml.tmpl +80 -0 | new file mode 100644 | ||
| @@ -0,0 +1,80 @@ | ||
| 1 | +# turbo-python agents. | |
| 2 | +# | |
| 3 | +# Each [[agent]] becomes one line of the Agent menu (Alt-A). Choosing it starts | |
| 4 | +# that program and opens a window on the conversation; closing the window stops | |
| 5 | +# it again. Open the same agent twice and you get two independent conversations. | |
| 6 | +# | |
| 7 | +# The editor is a client for the Agent Client Protocol — https://agentclientprotocol.com — | |
| 8 | +# so it holds no API key and knows no model. All of that is your agent's own | |
| 9 | +# configuration, in a file this editor does not read. | |
| 10 | +# | |
| 11 | +# name what the menu shows, and what the window is called. Required, and | |
| 12 | +# unique: a project's agent of the same name replaces one of yours. | |
| 13 | +# command the program to run. Required. Looked up on PATH. | |
| 14 | +# args its arguments, passed as given. There is no shell here, so no | |
| 15 | +# quoting, no globs and no && — use command = "sh", args = ["-c", …] | |
| 16 | +# when you really want one. | |
| 17 | +# env extra environment variables. The agent also inherits the ones the | |
| 18 | +# editor was started with, so a credential already exported reaches | |
| 19 | +# it without being written down here. | |
| 20 | +# cwd where to run it, relative to the project. Left out, it is the | |
| 21 | +# project itself. | |
| 22 | +# | |
| 23 | +# A key this file does not define is refused rather than ignored: a misspelt | |
| 24 | +# `comand` would otherwise look exactly like one that had no effect. | |
| 25 | +# | |
| 26 | +# The same file may also live in %[2]s, where it applies to every project you open. | |
| 27 | +# This one is read afterwards and wins where a name appears in both. | |
| 28 | + | |
| 29 | +# Docker's agent runtime, talking to a model server of your choosing. | |
| 30 | +# `docker agent serve acp <file>` speaks the protocol on its standard input and | |
| 31 | +# output, which is exactly what the editor wants. | |
| 32 | +# | |
| 33 | +# The YAML beside this file is the agent's own: which provider, which model, | |
| 34 | +# which tools. Write it yourself, or run `docker agent new` to start one. | |
| 35 | + | |
| 36 | +[[agent]] | |
| 37 | +name = "Local agent" | |
| 38 | +command = "docker" | |
| 39 | +args = ["agent", "serve", "acp", "%[1]s/agent.yaml"] | |
| 40 | +env = { TELEMETRY_ENABLED = "false" } | |
| 41 | + | |
| 42 | +# A second agent is one more block. Two windows side by side — Window ▸ Tile — | |
| 43 | +# is how a fast local model and a slow careful one get compared. | |
| 44 | +# | |
| 45 | +# [[agent]] | |
| 46 | +# name = "Reviewer" | |
| 47 | +# command = "my-agent" | |
| 48 | +# args = ["--acp", "--profile", "review"] | |
| 49 | +# cwd = "." | |
| 50 | + | |
| 51 | +# Once a window is open: | |
| 52 | +# | |
| 53 | +# Enter send what you have typed | |
| 54 | +# Alt-Enter a new line instead of sending | |
| 55 | +# Tab move between the conversation and the box | |
| 56 | +# / at the start of the box, list the agent's own commands | |
| 57 | +# @ list the project's files; the one you pick goes to the agent | |
| 58 | +# PgUp PgDn read back through the conversation | |
| 59 | +# Esc stop the turn in progress | |
| 60 | +# Ctrl-W close the window, and stop the agent with it | |
| 61 | +# | |
| 62 | +# And in the conversation, with Tab pressed: | |
| 63 | +# | |
| 64 | +# ↑ ↓ move the cursor through what was said | |
| 65 | +# Shift-↑ ↓ select whole lines | |
| 66 | +# Ctrl-C copy — the selection, or the block the cursor is on | |
| 67 | +# | |
| 68 | +# What is copied goes to this editor's clipboard *and*, through the terminal, to | |
| 69 | +# the system's — so Shift-Ins pastes it into a file here, and Ctrl-V pastes it | |
| 70 | +# anywhere else. | |
| 71 | +# | |
| 72 | +# Code the agent sends inside a ```python fence is coloured by the same scanner | |
| 73 | +# this editor colours .py files with. A fence naming a language it does not | |
| 74 | +# know is left plain rather than guessed at. | |
| 75 | +# | |
| 76 | +# An agent with a shell or a filesystem tool asks before it uses one, and the | |
| 77 | +# box that appears carries the agent's own choices. Nothing runs until you | |
| 78 | +# answer. When it reads a file you have open and have not saved, it is given | |
| 79 | +# what you can see rather than what is on disk; when it writes one, the change | |
| 80 | +# lands in the buffer for you to undo with Ctrl-Z or keep with F2. | |
| new file mode 100644 | |||
| @@ -0,0 +1,80 @@ | |||
| 1 | +# turbo-python agents. | ||
| 2 | +# | ||
| 3 | +# Each [[agent]] becomes one line of the Agent menu (Alt-A). Choosing it starts | ||
| 4 | +# that program and opens a window on the conversation; closing the window stops | ||
| 5 | +# it again. Open the same agent twice and you get two independent conversations. | ||
| 6 | +# | ||
| 7 | +# The editor is a client for the Agent Client Protocol — https://agentclientprotocol.com — | ||
| 8 | +# so it holds no API key and knows no model. All of that is your agent's own | ||
| 9 | +# configuration, in a file this editor does not read. | ||
| 10 | +# | ||
| 11 | +# name what the menu shows, and what the window is called. Required, and | ||
| 12 | +# unique: a project's agent of the same name replaces one of yours. | ||
| 13 | +# command the program to run. Required. Looked up on PATH. | ||
| 14 | +# args its arguments, passed as given. There is no shell here, so no | ||
| 15 | +# quoting, no globs and no && — use command = "sh", args = ["-c", …] | ||
| 16 | +# when you really want one. | ||
| 17 | +# env extra environment variables. The agent also inherits the ones the | ||
| 18 | +# editor was started with, so a credential already exported reaches | ||
| 19 | +# it without being written down here. | ||
| 20 | +# cwd where to run it, relative to the project. Left out, it is the | ||
| 21 | +# project itself. | ||
| 22 | +# | ||
| 23 | +# A key this file does not define is refused rather than ignored: a misspelt | ||
| 24 | +# `comand` would otherwise look exactly like one that had no effect. | ||
| 25 | +# | ||
| 26 | +# The same file may also live in %[2]s, where it applies to every project you open. | ||
| 27 | +# This one is read afterwards and wins where a name appears in both. | ||
| 28 | + | ||
| 29 | +# Docker's agent runtime, talking to a model server of your choosing. | ||
| 30 | +# `docker agent serve acp <file>` speaks the protocol on its standard input and | ||
| 31 | +# output, which is exactly what the editor wants. | ||
| 32 | +# | ||
| 33 | +# The YAML beside this file is the agent's own: which provider, which model, | ||
| 34 | +# which tools. Write it yourself, or run `docker agent new` to start one. | ||
| 35 | + | ||
| 36 | +[[agent]] | ||
| 37 | +name = "Local agent" | ||
| 38 | +command = "docker" | ||
| 39 | +args = ["agent", "serve", "acp", "%[1]s/agent.yaml"] | ||
| 40 | +env = { TELEMETRY_ENABLED = "false" } | ||
| 41 | + | ||
| 42 | +# A second agent is one more block. Two windows side by side — Window ▸ Tile — | ||
| 43 | +# is how a fast local model and a slow careful one get compared. | ||
| 44 | +# | ||
| 45 | +# [[agent]] | ||
| 46 | +# name = "Reviewer" | ||
| 47 | +# command = "my-agent" | ||
| 48 | +# args = ["--acp", "--profile", "review"] | ||
| 49 | +# cwd = "." | ||
| 50 | + | ||
| 51 | +# Once a window is open: | ||
| 52 | +# | ||
| 53 | +# Enter send what you have typed | ||
| 54 | +# Alt-Enter a new line instead of sending | ||
| 55 | +# Tab move between the conversation and the box | ||
| 56 | +# / at the start of the box, list the agent's own commands | ||
| 57 | +# @ list the project's files; the one you pick goes to the agent | ||
| 58 | +# PgUp PgDn read back through the conversation | ||
| 59 | +# Esc stop the turn in progress | ||
| 60 | +# Ctrl-W close the window, and stop the agent with it | ||
| 61 | +# | ||
| 62 | +# And in the conversation, with Tab pressed: | ||
| 63 | +# | ||
| 64 | +# ↑ ↓ move the cursor through what was said | ||
| 65 | +# Shift-↑ ↓ select whole lines | ||
| 66 | +# Ctrl-C copy — the selection, or the block the cursor is on | ||
| 67 | +# | ||
| 68 | +# What is copied goes to this editor's clipboard *and*, through the terminal, to | ||
| 69 | +# the system's — so Shift-Ins pastes it into a file here, and Ctrl-V pastes it | ||
| 70 | +# anywhere else. | ||
| 71 | +# | ||
| 72 | +# Code the agent sends inside a ```python fence is coloured by the same scanner | ||
| 73 | +# this editor colours .py files with. A fence naming a language it does not | ||
| 74 | +# know is left plain rather than guessed at. | ||
| 75 | +# | ||
| 76 | +# An agent with a shell or a filesystem tool asks before it uses one, and the | ||
| 77 | +# box that appears carries the agent's own choices. Nothing runs until you | ||
| 78 | +# answer. When it reads a file you have open and have not saved, it is given | ||
| 79 | +# what you can see rather than what is on disk; when it writes one, the change | ||
| 80 | +# lands in the buffer for you to undo with Ctrl-Z or keep with F2. | ||
added
internal/pythonlang/acp_test.go +128 -0 | new file mode 100644 | ||
| @@ -0,0 +1,128 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "errors" | |
| 5 | + "os" | |
| 6 | + "strings" | |
| 7 | + "testing" | |
| 8 | + | |
| 9 | + "rickub.com/turbo-editors/turbo-core/acp" | |
| 10 | +) | |
| 11 | + | |
| 12 | +// The agents file Turbo Python writes. What the *feature* does is turbo-core's to | |
| 13 | +// test; what is checked here is the one part that belongs to this editor — | |
| 14 | +// that the starter file is filled in correctly, loads back as the agent it | |
| 15 | +// describes, and says enough for somebody to point it at their own. | |
| 16 | + | |
| 17 | +// readAgentsFile returns the agents file a project was given. | |
| 18 | +func readAgentsFile(t *testing.T, dir string) string { | |
| 19 | + t.Helper() | |
| 20 | + | |
| 21 | + data, err := os.ReadFile(acp.ProjectPath(Profile(), dir)) | |
| 22 | + if err != nil { | |
| 23 | + t.Fatalf("reading the agents file: %v", err) | |
| 24 | + } | |
| 25 | + return string(data) | |
| 26 | +} | |
| 27 | + | |
| 28 | +// createAgents writes the starter agents file into a fresh project. | |
| 29 | +func createAgents(t *testing.T) string { | |
| 30 | + t.Helper() | |
| 31 | + | |
| 32 | + dir := t.TempDir() | |
| 33 | + if _, err := acp.Create(Profile(), dir); err != nil { | |
| 34 | + t.Fatalf("acp.Create() error = %v", err) | |
| 35 | + } | |
| 36 | + return dir | |
| 37 | +} | |
| 38 | + | |
| 39 | +func TestTheCreatedAgentsFileFillsBothOfItsBlanks(t *testing.T) { | |
| 40 | + // Two different values — the project directory the example agent points | |
| 41 | + // into, and the user's own file that a comment names. Go writes | |
| 42 | + // %!s(MISSING) into the output rather than failing, so a miscounted verb | |
| 43 | + // produces a starter file that is written, opened, and wrong. | |
| 44 | + contents := readAgentsFile(t, createAgents(t)) | |
| 45 | + | |
| 46 | + if strings.Contains(contents, "%!") { | |
| 47 | + t.Errorf("the created file has an unfilled verb in it:\n%s", contents) | |
| 48 | + } | |
| 49 | + if want := Profile().ProjectDir() + "/agent.yaml"; !strings.Contains(contents, want) { | |
| 50 | + t.Errorf("the example agent does not point at %q:\n%s", want, contents) | |
| 51 | + } | |
| 52 | + if want := acp.UserPath(Profile()); want != "" && !strings.Contains(contents, want) { | |
| 53 | + t.Errorf("the created file never names the user's own file %q:\n%s", want, contents) | |
| 54 | + } | |
| 55 | +} | |
| 56 | + | |
| 57 | +func TestTheCreatedAgentsFileLoadsBackAsOneAgent(t *testing.T) { | |
| 58 | + // The file is mostly comments, and a comment carrying an [[agent]] example | |
| 59 | + // that the loader read as real would put an agent nobody configured into | |
| 60 | + // the menu. | |
| 61 | + dir := createAgents(t) | |
| 62 | + | |
| 63 | + list, err := acp.Load(Profile(), dir) | |
| 64 | + if err != nil { | |
| 65 | + t.Fatalf("acp.Load() error = %v", err) | |
| 66 | + } | |
| 67 | + if list.Len() != 1 { | |
| 68 | + t.Fatalf("the created file holds %d agents, want 1: %v", list.Len(), list.Agents()) | |
| 69 | + } | |
| 70 | + | |
| 71 | + agent := list.Agents()[0] | |
| 72 | + if agent.Command != "docker" { | |
| 73 | + t.Errorf("the example agent runs %q, want docker", agent.Command) | |
| 74 | + } | |
| 75 | + if want := "agent serve acp"; !strings.Contains(agent.CommandLine(), want) { | |
| 76 | + t.Errorf("the example command line is %q, want %q in it", agent.CommandLine(), want) | |
| 77 | + } | |
| 78 | +} | |
| 79 | + | |
| 80 | +func TestTheCreatedAgentsFileExplainsItself(t *testing.T) { | |
| 81 | + // The keys, the window's keyboard and how to copy out of it are all | |
| 82 | + // invisible otherwise: this is the only document the editor hands a user. | |
| 83 | + contents := readAgentsFile(t, createAgents(t)) | |
| 84 | + | |
| 85 | + for _, want := range []string{ | |
| 86 | + "[[agent]]", "name", "command", "args", "env", "cwd", | |
| 87 | + "agentclientprotocol.com", | |
| 88 | + "Alt-Enter", "Ctrl-W", "Esc", "Ctrl-C", | |
| 89 | + } { | |
| 90 | + if !strings.Contains(contents, want) { | |
| 91 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | |
| 92 | + } | |
| 93 | + } | |
| 94 | +} | |
| 95 | + | |
| 96 | +func TestTheCreatedAgentsFileNamesThisEditorsOwnLanguage(t *testing.T) { | |
| 97 | + // The comment about coloured code blocks is the one line of this file that | |
| 98 | + // is about Turbo Python rather than about the protocol, and a copy left naming | |
| 99 | + // another editor's language would be the obvious way to get it wrong. | |
| 100 | + contents := readAgentsFile(t, createAgents(t)) | |
| 101 | + | |
| 102 | + if want := "```python"; !strings.Contains(contents, want) { | |
| 103 | + t.Errorf("the created file never mentions a %q fence:\n%s", want, contents) | |
| 104 | + } | |
| 105 | + if want := ".py files"; !strings.Contains(contents, want) { | |
| 106 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | |
| 107 | + } | |
| 108 | +} | |
| 109 | + | |
| 110 | +func TestCreatingAgentsTwiceLeavesTheFirstAlone(t *testing.T) { | |
| 111 | + dir := createAgents(t) | |
| 112 | + path := acp.ProjectPath(Profile(), dir) | |
| 113 | + | |
| 114 | + if err := os.WriteFile(path, []byte("# mine\n"), 0o644); err != nil { | |
| 115 | + t.Fatalf("writing over it: %v", err) | |
| 116 | + } | |
| 117 | + if _, err := acp.Create(Profile(), dir); !errors.Is(err, acp.ErrExists) { | |
| 118 | + t.Errorf("acp.Create() error = %v, want ErrExists", err) | |
| 119 | + } | |
| 120 | + | |
| 121 | + data, err := os.ReadFile(path) | |
| 122 | + if err != nil { | |
| 123 | + t.Fatalf("reading it back: %v", err) | |
| 124 | + } | |
| 125 | + if string(data) != "# mine\n" { | |
| 126 | + t.Errorf("the file was overwritten: %q", data) | |
| 127 | + } | |
| 128 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,128 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "errors" | ||
| 5 | + "os" | ||
| 6 | + "strings" | ||
| 7 | + "testing" | ||
| 8 | + | ||
| 9 | + "rickub.com/turbo-editors/turbo-core/acp" | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | +// The agents file Turbo Python writes. What the *feature* does is turbo-core's to | ||
| 13 | +// test; what is checked here is the one part that belongs to this editor — | ||
| 14 | +// that the starter file is filled in correctly, loads back as the agent it | ||
| 15 | +// describes, and says enough for somebody to point it at their own. | ||
| 16 | + | ||
| 17 | +// readAgentsFile returns the agents file a project was given. | ||
| 18 | +func readAgentsFile(t *testing.T, dir string) string { | ||
| 19 | + t.Helper() | ||
| 20 | + | ||
| 21 | + data, err := os.ReadFile(acp.ProjectPath(Profile(), dir)) | ||
| 22 | + if err != nil { | ||
| 23 | + t.Fatalf("reading the agents file: %v", err) | ||
| 24 | + } | ||
| 25 | + return string(data) | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +// createAgents writes the starter agents file into a fresh project. | ||
| 29 | +func createAgents(t *testing.T) string { | ||
| 30 | + t.Helper() | ||
| 31 | + | ||
| 32 | + dir := t.TempDir() | ||
| 33 | + if _, err := acp.Create(Profile(), dir); err != nil { | ||
| 34 | + t.Fatalf("acp.Create() error = %v", err) | ||
| 35 | + } | ||
| 36 | + return dir | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +func TestTheCreatedAgentsFileFillsBothOfItsBlanks(t *testing.T) { | ||
| 40 | + // Two different values — the project directory the example agent points | ||
| 41 | + // into, and the user's own file that a comment names. Go writes | ||
| 42 | + // %!s(MISSING) into the output rather than failing, so a miscounted verb | ||
| 43 | + // produces a starter file that is written, opened, and wrong. | ||
| 44 | + contents := readAgentsFile(t, createAgents(t)) | ||
| 45 | + | ||
| 46 | + if strings.Contains(contents, "%!") { | ||
| 47 | + t.Errorf("the created file has an unfilled verb in it:\n%s", contents) | ||
| 48 | + } | ||
| 49 | + if want := Profile().ProjectDir() + "/agent.yaml"; !strings.Contains(contents, want) { | ||
| 50 | + t.Errorf("the example agent does not point at %q:\n%s", want, contents) | ||
| 51 | + } | ||
| 52 | + if want := acp.UserPath(Profile()); want != "" && !strings.Contains(contents, want) { | ||
| 53 | + t.Errorf("the created file never names the user's own file %q:\n%s", want, contents) | ||
| 54 | + } | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +func TestTheCreatedAgentsFileLoadsBackAsOneAgent(t *testing.T) { | ||
| 58 | + // The file is mostly comments, and a comment carrying an [[agent]] example | ||
| 59 | + // that the loader read as real would put an agent nobody configured into | ||
| 60 | + // the menu. | ||
| 61 | + dir := createAgents(t) | ||
| 62 | + | ||
| 63 | + list, err := acp.Load(Profile(), dir) | ||
| 64 | + if err != nil { | ||
| 65 | + t.Fatalf("acp.Load() error = %v", err) | ||
| 66 | + } | ||
| 67 | + if list.Len() != 1 { | ||
| 68 | + t.Fatalf("the created file holds %d agents, want 1: %v", list.Len(), list.Agents()) | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + agent := list.Agents()[0] | ||
| 72 | + if agent.Command != "docker" { | ||
| 73 | + t.Errorf("the example agent runs %q, want docker", agent.Command) | ||
| 74 | + } | ||
| 75 | + if want := "agent serve acp"; !strings.Contains(agent.CommandLine(), want) { | ||
| 76 | + t.Errorf("the example command line is %q, want %q in it", agent.CommandLine(), want) | ||
| 77 | + } | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +func TestTheCreatedAgentsFileExplainsItself(t *testing.T) { | ||
| 81 | + // The keys, the window's keyboard and how to copy out of it are all | ||
| 82 | + // invisible otherwise: this is the only document the editor hands a user. | ||
| 83 | + contents := readAgentsFile(t, createAgents(t)) | ||
| 84 | + | ||
| 85 | + for _, want := range []string{ | ||
| 86 | + "[[agent]]", "name", "command", "args", "env", "cwd", | ||
| 87 | + "agentclientprotocol.com", | ||
| 88 | + "Alt-Enter", "Ctrl-W", "Esc", "Ctrl-C", | ||
| 89 | + } { | ||
| 90 | + if !strings.Contains(contents, want) { | ||
| 91 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | ||
| 92 | + } | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +func TestTheCreatedAgentsFileNamesThisEditorsOwnLanguage(t *testing.T) { | ||
| 97 | + // The comment about coloured code blocks is the one line of this file that | ||
| 98 | + // is about Turbo Python rather than about the protocol, and a copy left naming | ||
| 99 | + // another editor's language would be the obvious way to get it wrong. | ||
| 100 | + contents := readAgentsFile(t, createAgents(t)) | ||
| 101 | + | ||
| 102 | + if want := "```python"; !strings.Contains(contents, want) { | ||
| 103 | + t.Errorf("the created file never mentions a %q fence:\n%s", want, contents) | ||
| 104 | + } | ||
| 105 | + if want := ".py files"; !strings.Contains(contents, want) { | ||
| 106 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +func TestCreatingAgentsTwiceLeavesTheFirstAlone(t *testing.T) { | ||
| 111 | + dir := createAgents(t) | ||
| 112 | + path := acp.ProjectPath(Profile(), dir) | ||
| 113 | + | ||
| 114 | + if err := os.WriteFile(path, []byte("# mine\n"), 0o644); err != nil { | ||
| 115 | + t.Fatalf("writing over it: %v", err) | ||
| 116 | + } | ||
| 117 | + if _, err := acp.Create(Profile(), dir); !errors.Is(err, acp.ErrExists) { | ||
| 118 | + t.Errorf("acp.Create() error = %v, want ErrExists", err) | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + data, err := os.ReadFile(path) | ||
| 122 | + if err != nil { | ||
| 123 | + t.Fatalf("reading it back: %v", err) | ||
| 124 | + } | ||
| 125 | + if string(data) != "# mine\n" { | ||
| 126 | + t.Errorf("the file was overwritten: %q", data) | ||
| 127 | + } | ||
| 128 | +} | ||
added
internal/pythonlang/editor_test.go +463 -0 | new file mode 100644 | ||
| @@ -0,0 +1,463 @@ | ||
| 1 | +package pythonlang_test | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "context" | |
| 5 | + "errors" | |
| 6 | + "os" | |
| 7 | + "os/exec" | |
| 8 | + "path/filepath" | |
| 9 | + "strings" | |
| 10 | + "testing" | |
| 11 | + "time" | |
| 12 | + | |
| 13 | + "github.com/gdamore/tcell/v2" | |
| 14 | + | |
| 15 | + "rickub.com/turbo-editors/turbo-core/app" | |
| 16 | + "rickub.com/turbo-editors/turbo-core/buffer" | |
| 17 | + "rickub.com/turbo-editors/turbo-core/lsp" | |
| 18 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 19 | + "rickub.com/turbo-editors/turbo-core/ui" | |
| 20 | + | |
| 21 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | |
| 22 | +) | |
| 23 | + | |
| 24 | +// --- the editor, assembled -------------------------------------------------- | |
| 25 | + | |
| 26 | +func TestTheEditorCallsItselfTurboPython(t *testing.T) { | |
| 27 | + editor := newTestEditor(t) | |
| 28 | + | |
| 29 | + if got := editor.Profile().Name; got != pythonlang.Name { | |
| 30 | + t.Errorf("Profile().Name = %q, want %q", got, pythonlang.Name) | |
| 31 | + } | |
| 32 | + if got := editor.Profile().ProjectDir(); got != ".turbo-python" { | |
| 33 | + t.Errorf("ProjectDir() = %q, want %q", got, ".turbo-python") | |
| 34 | + } | |
| 35 | +} | |
| 36 | + | |
| 37 | +func TestTheEditorColoursPythonSourceItOpens(t *testing.T) { | |
| 38 | + // The whole path in one test: Register taught the library about Python, the | |
| 39 | + // profile named the editor, and a .py file opened through the public API | |
| 40 | + // comes out coloured. | |
| 41 | + root := t.TempDir() | |
| 42 | + path := filepath.Join(root, "main.py") | |
| 43 | + writeFile(t, path, "def main() -> None:\n pass\n") | |
| 44 | + | |
| 45 | + editor := newTestEditor(t) | |
| 46 | + editor.Open(path) | |
| 47 | + | |
| 48 | + if got := editor.ActiveView().Language(); got != pythonlang.Language { | |
| 49 | + t.Fatalf("the view colours the file as %q, want %q", got, pythonlang.Language) | |
| 50 | + } | |
| 51 | + if spans := syntax.Highlight(pythonlang.Language, "def main():"); len(spans[0]) == 0 { | |
| 52 | + t.Error("the registered Python scanner colours nothing") | |
| 53 | + } | |
| 54 | +} | |
| 55 | + | |
| 56 | +// A Python script in a bin directory has no extension at all, and its first | |
| 57 | +// line is the only thing that says what it is. That is what Shebangs is for. | |
| 58 | +func TestAScriptWithNoExtensionIsRecognisedByItsShebang(t *testing.T) { | |
| 59 | + root := t.TempDir() | |
| 60 | + path := filepath.Join(root, "deploy") | |
| 61 | + writeFile(t, path, "#!/usr/bin/env python3\nimport sys\n") | |
| 62 | + | |
| 63 | + editor := newTestEditor(t) | |
| 64 | + editor.Open(path) | |
| 65 | + | |
| 66 | + if got := editor.ActiveView().Language(); got != pythonlang.Language { | |
| 67 | + t.Errorf("a file starting with a python shebang is coloured as %q, want %q", got, pythonlang.Language) | |
| 68 | + } | |
| 69 | +} | |
| 70 | + | |
| 71 | +func TestTheEditorDoesNotColourRust(t *testing.T) { | |
| 72 | + // "Python instead of Rust" is the whole point of this editor being a | |
| 73 | + // separate one: a .rs file opens as plain text here. | |
| 74 | + root := t.TempDir() | |
| 75 | + path := filepath.Join(root, "main.rs") | |
| 76 | + writeFile(t, path, "fn main() {}\n") | |
| 77 | + | |
| 78 | + editor := newTestEditor(t) | |
| 79 | + editor.Open(path) | |
| 80 | + | |
| 81 | + if got := editor.ActiveView().Language(); got != syntax.LanguageNone { | |
| 82 | + t.Errorf("a .rs file is coloured as %q; Turbo Python registers Python, not Rust", got) | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +func TestTheToolchainMenuIsCalledPythonAndNoTwoMenusShareAHotKey(t *testing.T) { | |
| 87 | + // The bar answers the first menu whose hot key matches, so a clash makes | |
| 88 | + // one of the two unreachable from the keyboard — silently, and with every | |
| 89 | + // other test still passing. Python takes P because none of the fixed menus | |
| 90 | + // does, which is exactly the sort of thing only this test notices. | |
| 91 | + editor := newTestEditor(t) | |
| 92 | + | |
| 93 | + seen := map[rune]string{} | |
| 94 | + found := false | |
| 95 | + for _, menu := range editor.MenuBar().Menus() { | |
| 96 | + label, hot, _ := ui.SplitHotKey(menu.Label) | |
| 97 | + if label == "Python" { | |
| 98 | + found = true | |
| 99 | + } | |
| 100 | + if hot == 0 { | |
| 101 | + t.Errorf("the %q menu has no hot key", label) | |
| 102 | + continue | |
| 103 | + } | |
| 104 | + if other, clash := seen[hot]; clash { | |
| 105 | + t.Errorf("%q and %q both answer to Alt-%c", other, label, hot) | |
| 106 | + } | |
| 107 | + seen[hot] = label | |
| 108 | + } | |
| 109 | + if !found { | |
| 110 | + t.Error("there is no Python menu on the bar") | |
| 111 | + } | |
| 112 | +} | |
| 113 | + | |
| 114 | +// --- driven against a real python-lsp-server -------------------------------- | |
| 115 | + | |
| 116 | +// TestCompletionEndToEndWithRealPylsp drives the exact sequence the command | |
| 117 | +// does at start-up: open the files first, start the language server second, | |
| 118 | +// then ask for a completion. | |
| 119 | +// | |
| 120 | +// That order is the whole point, and it is the one Turbo Go got wrong once: an | |
| 121 | +// editor that announces its open documents to a server which does not exist yet | |
| 122 | +// and never mentions them again gets answers about a file the server has never | |
| 123 | +// heard of — which looks, from the outside, exactly like completion not | |
| 124 | +// working. | |
| 125 | +// | |
| 126 | +// It skips itself when pylsp is not installed, and under -short. | |
| 127 | +func TestCompletionEndToEndWithRealPylsp(t *testing.T) { | |
| 128 | + root, editor := startRealServer(t) | |
| 129 | + | |
| 130 | + // The file on disk stops short of the dot. The text the completion is about | |
| 131 | + // gets *typed* below, so the answer can only come from what the editor told | |
| 132 | + // the server — which is the whole point of this test. A fixture already | |
| 133 | + // containing "json." would be answered from disk, and would pass whether or | |
| 134 | + // not the editor said anything at all. | |
| 135 | + path := filepath.Join(root, "main.py") | |
| 136 | + | |
| 137 | + view := editor.ActiveView() | |
| 138 | + view.Buffer().SetCursor(buffer.Position{Line: completionLine, Col: 4}) | |
| 139 | + typeText(editor, "json.") | |
| 140 | + | |
| 141 | + // Typing the dot asks for a completion by itself, but a server that is | |
| 142 | + // still indexing answers nothing at all. Asking again until it answers is | |
| 143 | + // what a person does too. | |
| 144 | + if !waitForCompletion(t, editor) { | |
| 145 | + t.Fatalf("no completion list opened for %s; the status bar says %q", path, editor.StatusBar().Message()) | |
| 146 | + } | |
| 147 | + if !completionOffers(editor, "loads") { | |
| 148 | + t.Errorf("the list does not offer json.loads; it has %d entries", editor.Completion().Count()) | |
| 149 | + } | |
| 150 | +} | |
| 151 | + | |
| 152 | +// Several answers, not one. An earlier version of the library took the first | |
| 153 | +// location and threw the rest away, so a name used in three places sent you to | |
| 154 | +// whichever one the server happened to list first. | |
| 155 | +func TestReferencesAcrossAFileWithRealPylsp(t *testing.T) { | |
| 156 | + root, editor := startRealServer(t) | |
| 157 | + path := filepath.Join(root, "main.py") | |
| 158 | + | |
| 159 | + locations := waitForLocations(t, func(ctx context.Context) ([]lsp.Location, error) { | |
| 160 | + return editor.Language().References(ctx, path, helperLine, helperColumn, helperLineText) | |
| 161 | + }) | |
| 162 | + | |
| 163 | + if len(locations) < 3 { | |
| 164 | + t.Errorf("helper has %d references, want at least 3 — its declaration and its two call sites: %v", | |
| 165 | + len(locations), locations) | |
| 166 | + } | |
| 167 | +} | |
| 168 | + | |
| 169 | +func TestTheSymbolsOfAFileWithRealPylsp(t *testing.T) { | |
| 170 | + root, editor := startRealServer(t) | |
| 171 | + path := filepath.Join(root, "main.py") | |
| 172 | + | |
| 173 | + var symbols []lsp.Symbol | |
| 174 | + waitUntil(t, 30*time.Second, func() bool { | |
| 175 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | |
| 176 | + defer cancel() | |
| 177 | + found, err := editor.Language().DocumentSymbols(ctx, path) | |
| 178 | + if err != nil { | |
| 179 | + return false | |
| 180 | + } | |
| 181 | + symbols = found | |
| 182 | + return len(symbols) > 0 | |
| 183 | + }) | |
| 184 | + | |
| 185 | + names := map[string]bool{} | |
| 186 | + for _, symbol := range symbols { | |
| 187 | + names[symbol.Name] = true | |
| 188 | + } | |
| 189 | + for _, want := range []string{"helper", "first", "second"} { | |
| 190 | + if !names[want] { | |
| 191 | + t.Errorf("the file's symbols do not include %q: %v", want, names) | |
| 192 | + } | |
| 193 | + } | |
| 194 | +} | |
| 195 | + | |
| 196 | +// Diagnostics are the one thing a language server sends without being asked, | |
| 197 | +// and the only feature whose failure looks exactly like success: an editor with | |
| 198 | +// no error to show and one that cannot find the error are the same blank | |
| 199 | +// gutter. So this opens a file that does not parse and waits for the mark. | |
| 200 | +func TestDiagnosticsForAFileThatDoesNotParseWithRealPylsp(t *testing.T) { | |
| 201 | + root, editor := startRealServer(t) | |
| 202 | + | |
| 203 | + broken := filepath.Join(root, "broken.py") | |
| 204 | + writeFile(t, broken, "def f(:\n return 1\n") | |
| 205 | + editor.Open(broken) | |
| 206 | + editor.Tick() | |
| 207 | + | |
| 208 | + waitUntil(t, 30*time.Second, func() bool { | |
| 209 | + editor.Tick() | |
| 210 | + return len(editor.Language().Diagnostics(broken)) > 0 | |
| 211 | + }) | |
| 212 | + | |
| 213 | + problems := editor.Language().Diagnostics(broken) | |
| 214 | + if len(problems) == 0 { | |
| 215 | + t.Fatalf("no diagnostic ever arrived for %s; the status bar says %q", broken, editor.StatusBar().Message()) | |
| 216 | + } | |
| 217 | + if _, ok := editor.Language().FirstError(broken); !ok { | |
| 218 | + t.Errorf("the diagnostics hold no error, only %v", problems) | |
| 219 | + } | |
| 220 | +} | |
| 221 | + | |
| 222 | +// python-lsp-server advertises neither implementationProvider nor | |
| 223 | +// workspaceSymbolProvider, so two of the nine questions turbo-core asks come | |
| 224 | +// back empty. That is documented in how-to/enable-completion.md, and this test | |
| 225 | +// is what keeps the documentation honest: if a future pylsp answers either of | |
| 226 | +// them, this fails and the page gets revisited. | |
| 227 | +func TestPylspAnswersNeitherImplementationsNorProjectWideSymbols(t *testing.T) { | |
| 228 | + root, editor := startRealServer(t) | |
| 229 | + path := filepath.Join(root, "main.py") | |
| 230 | + | |
| 231 | + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) | |
| 232 | + defer cancel() | |
| 233 | + | |
| 234 | + if found, err := editor.Language().Implementation(ctx, path, helperLine, helperColumn, helperLineText); err == nil && len(found) > 0 { | |
| 235 | + t.Errorf("pylsp now answers implementations (%v); how-to/enable-completion.md says it does not", found) | |
| 236 | + } | |
| 237 | + if found, err := editor.Language().WorkspaceSymbols(ctx, "helper"); err == nil && len(found) > 0 { | |
| 238 | + t.Errorf("pylsp now answers project-wide symbols (%v); how-to/enable-completion.md says it does not", found) | |
| 239 | + } | |
| 240 | +} | |
| 241 | + | |
| 242 | +// --- the fixtures and the waiting ------------------------------------------- | |
| 243 | + | |
| 244 | +// realProject is the file every language-server test works against. Line | |
| 245 | +// numbers are counted from zero and are named by the two constants below, so | |
| 246 | +// inserting a line here moves them and the constants have to move too. | |
| 247 | +// | |
| 248 | +// 0 import json | |
| 249 | +// 1 | |
| 250 | +// 2 | |
| 251 | +// 3 def load(text: str) -> object: | |
| 252 | +// 4 ← four spaces, and where the completion is typed | |
| 253 | +// 5 return json.loads(text) | |
| 254 | +// 6 | |
| 255 | +// 7 | |
| 256 | +// 8 def helper() -> int: | |
| 257 | +// 9 return 1 | |
| 258 | +// 10 | |
| 259 | +// 11 | |
| 260 | +// 12 def first() -> int: | |
| 261 | +// 13 return helper() | |
| 262 | +// … | |
| 263 | +// | |
| 264 | +// The line the completion is typed on is deliberately blank on disk but | |
| 265 | +// indented, so that the cursor can sit where a statement would. | |
| 266 | +const realProject = "import json\n" + | |
| 267 | + "\n" + | |
| 268 | + "\n" + | |
| 269 | + "def load(text: str) -> object:\n" + | |
| 270 | + " \n" + | |
| 271 | + " return json.loads(text)\n" + | |
| 272 | + "\n" + | |
| 273 | + "\n" + | |
| 274 | + "def helper() -> int:\n" + | |
| 275 | + " return 1\n" + | |
| 276 | + "\n" + | |
| 277 | + "\n" + | |
| 278 | + "def first() -> int:\n" + | |
| 279 | + " return helper()\n" + | |
| 280 | + "\n" + | |
| 281 | + "\n" + | |
| 282 | + "def second() -> int:\n" + | |
| 283 | + " return helper() + 1\n" | |
| 284 | + | |
| 285 | +// Where the fixture's interesting lines are, counted from zero. | |
| 286 | +const ( | |
| 287 | + completionLine = 4 | |
| 288 | + helperLine = 8 | |
| 289 | + helperColumn = 4 | |
| 290 | + helperLineText = "def helper() -> int:" | |
| 291 | +) | |
| 292 | + | |
| 293 | +// startRealServer writes a project, opens its file, starts pylsp and waits for | |
| 294 | +// it, in the order the command does. It skips the test when pylsp is missing. | |
| 295 | +func startRealServer(t *testing.T) (root string, editor *app.App) { | |
| 296 | + t.Helper() | |
| 297 | + if testing.Short() { | |
| 298 | + t.Skip("-short: not starting a language server") | |
| 299 | + } | |
| 300 | + | |
| 301 | + server, err := lsp.FindServer(pythonlang.Profile().Server) | |
| 302 | + if errors.Is(err, lsp.ErrServerNotFound) { | |
| 303 | + t.Skipf("%s is not installed; %s", pythonlang.ServerCommand, pythonlang.InstallHint) | |
| 304 | + } | |
| 305 | + // Finding it is not the same as being able to run it: a shim left behind by | |
| 306 | + // a tool manager whose environment has since been removed is on PATH and | |
| 307 | + // fails only when started. | |
| 308 | + if !serverRuns(server) { | |
| 309 | + t.Skipf("%s at %s cannot run; %s", pythonlang.ServerCommand, server, pythonlang.InstallHint) | |
| 310 | + } | |
| 311 | + | |
| 312 | + root = t.TempDir() | |
| 313 | + writeFile(t, filepath.Join(root, "pyproject.toml"), | |
| 314 | + "[project]\nname = \"example\"\nversion = \"0.1.0\"\n") | |
| 315 | + writeFile(t, filepath.Join(root, "main.py"), realProject) | |
| 316 | + | |
| 317 | + editor = newTestEditor(t) | |
| 318 | + | |
| 319 | + // 1. Open the file, exactly as main does — before there is any server. | |
| 320 | + editor.Open(filepath.Join(root, "main.py")) | |
| 321 | + | |
| 322 | + // 2. Start the language server, exactly as main does — afterwards. | |
| 323 | + ctx, cancel := context.WithCancel(t.Context()) | |
| 324 | + t.Cleanup(cancel) | |
| 325 | + editor.StartLanguageServer(ctx, root) | |
| 326 | + t.Cleanup(func() { editor.Language().Stop(context.Background()) }) | |
| 327 | + | |
| 328 | + waitUntilReady(t, editor) | |
| 329 | + | |
| 330 | + // 3. Let the event loop notice the server is ready, as Run does on every | |
| 331 | + // turn. This is what announces the file that was already open. | |
| 332 | + editor.Tick() | |
| 333 | + return root, editor | |
| 334 | +} | |
| 335 | + | |
| 336 | +// newTestEditor returns Turbo Python drawing on a simulated terminal, set up | |
| 337 | +// the way the command sets it up. | |
| 338 | +func newTestEditor(t *testing.T) *app.App { | |
| 339 | + t.Helper() | |
| 340 | + | |
| 341 | + pythonlang.Register() | |
| 342 | + screen := tcell.NewSimulationScreen("UTF-8") | |
| 343 | + if err := screen.Init(); err != nil { | |
| 344 | + t.Fatalf("initialising the simulation screen: %v", err) | |
| 345 | + } | |
| 346 | + t.Cleanup(screen.Fini) | |
| 347 | + screen.SetSize(80, 24) | |
| 348 | + | |
| 349 | + // Never read the themes or snippets of whoever is running the tests. | |
| 350 | + p := pythonlang.Profile() | |
| 351 | + t.Setenv(p.ThemeDirEnvVar(), t.TempDir()) | |
| 352 | + t.Setenv(p.SnippetDirEnvVar(), t.TempDir()) | |
| 353 | + | |
| 354 | + editor := app.New(screen, "turbo-classic", p) | |
| 355 | + editor.Render() | |
| 356 | + return editor | |
| 357 | +} | |
| 358 | + | |
| 359 | +// typeText sends a run of printable characters through the whole routing chain. | |
| 360 | +func typeText(editor *app.App, text string) { | |
| 361 | + for _, r := range text { | |
| 362 | + editor.Handle(tcell.NewEventKey(tcell.KeyRune, r, tcell.ModNone)) | |
| 363 | + } | |
| 364 | +} | |
| 365 | + | |
| 366 | +// completionOffers reports whether the open popup holds an entry starting with | |
| 367 | +// a label. | |
| 368 | +func completionOffers(editor *app.App, label string) bool { | |
| 369 | + for _, item := range editor.Completion().Matches() { | |
| 370 | + if strings.HasPrefix(item.Label, label) { | |
| 371 | + return true | |
| 372 | + } | |
| 373 | + } | |
| 374 | + return false | |
| 375 | +} | |
| 376 | + | |
| 377 | +// waitUntilReady blocks until the language server has finished starting. | |
| 378 | +func waitUntilReady(t *testing.T, editor *app.App) { | |
| 379 | + t.Helper() | |
| 380 | + | |
| 381 | + deadline := time.After(lsp.InitializeTimeout) | |
| 382 | + for !editor.Language().Ready() { | |
| 383 | + select { | |
| 384 | + case <-deadline: | |
| 385 | + t.Fatalf("the language server never became ready: %s", editor.Language().Status()) | |
| 386 | + case <-time.After(10 * time.Millisecond): | |
| 387 | + } | |
| 388 | + } | |
| 389 | +} | |
| 390 | + | |
| 391 | +// waitUntil polls a condition until it holds or the time runs out, and fails | |
| 392 | +// the test if it never does. | |
| 393 | +func waitUntil(t *testing.T, within time.Duration, done func() bool) { | |
| 394 | + t.Helper() | |
| 395 | + | |
| 396 | + deadline := time.Now().Add(within) | |
| 397 | + for time.Now().Before(deadline) { | |
| 398 | + if done() { | |
| 399 | + return | |
| 400 | + } | |
| 401 | + time.Sleep(200 * time.Millisecond) | |
| 402 | + } | |
| 403 | + t.Errorf("the server never answered within %s", within) | |
| 404 | +} | |
| 405 | + | |
| 406 | +// waitForLocations asks a location question until it is answered, because a | |
| 407 | +// server that is still indexing answers an empty list rather than an error. | |
| 408 | +func waitForLocations(t *testing.T, ask func(context.Context) ([]lsp.Location, error)) []lsp.Location { | |
| 409 | + t.Helper() | |
| 410 | + | |
| 411 | + var found []lsp.Location | |
| 412 | + waitUntil(t, 30*time.Second, func() bool { | |
| 413 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | |
| 414 | + defer cancel() | |
| 415 | + | |
| 416 | + locations, err := ask(ctx) | |
| 417 | + if err != nil { | |
| 418 | + return false | |
| 419 | + } | |
| 420 | + found = locations | |
| 421 | + return len(found) > 0 | |
| 422 | + }) | |
| 423 | + return found | |
| 424 | +} | |
| 425 | + | |
| 426 | +// waitForCompletion asks for a completion until one arrives, or gives up. | |
| 427 | +// | |
| 428 | +// A server loads the workspace after it has finished initialising, and answers | |
| 429 | +// an empty list until that is done. There is no notification this client reads | |
| 430 | +// that says when — so it asks again, which is what the editor's user would do. | |
| 431 | +func waitForCompletion(t *testing.T, editor *app.App) bool { | |
| 432 | + t.Helper() | |
| 433 | + | |
| 434 | + deadline := time.Now().Add(60 * time.Second) | |
| 435 | + for time.Now().Before(deadline) { | |
| 436 | + if editor.Completion().Visible() { | |
| 437 | + return true | |
| 438 | + } | |
| 439 | + editor.RequestCompletion() | |
| 440 | + if editor.Completion().Visible() { | |
| 441 | + return true | |
| 442 | + } | |
| 443 | + time.Sleep(500 * time.Millisecond) | |
| 444 | + } | |
| 445 | + return false | |
| 446 | +} | |
| 447 | + | |
| 448 | +// serverRuns reports whether the language server at path actually starts. | |
| 449 | +func serverRuns(path string) bool { | |
| 450 | + err := exec.Command(path, "--version").Run() | |
| 451 | + return err == nil | |
| 452 | +} | |
| 453 | + | |
| 454 | +// writeFile creates a file, making its directory first. | |
| 455 | +func writeFile(t *testing.T, path, content string) { | |
| 456 | + t.Helper() | |
| 457 | + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { | |
| 458 | + t.Fatalf("creating %s: %v", filepath.Dir(path), err) | |
| 459 | + } | |
| 460 | + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { | |
| 461 | + t.Fatalf("writing %s: %v", path, err) | |
| 462 | + } | |
| 463 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,463 @@ | |||
| 1 | +package pythonlang_test | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "context" | ||
| 5 | + "errors" | ||
| 6 | + "os" | ||
| 7 | + "os/exec" | ||
| 8 | + "path/filepath" | ||
| 9 | + "strings" | ||
| 10 | + "testing" | ||
| 11 | + "time" | ||
| 12 | + | ||
| 13 | + "github.com/gdamore/tcell/v2" | ||
| 14 | + | ||
| 15 | + "rickub.com/turbo-editors/turbo-core/app" | ||
| 16 | + "rickub.com/turbo-editors/turbo-core/buffer" | ||
| 17 | + "rickub.com/turbo-editors/turbo-core/lsp" | ||
| 18 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 19 | + "rickub.com/turbo-editors/turbo-core/ui" | ||
| 20 | + | ||
| 21 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +// --- the editor, assembled -------------------------------------------------- | ||
| 25 | + | ||
| 26 | +func TestTheEditorCallsItselfTurboPython(t *testing.T) { | ||
| 27 | + editor := newTestEditor(t) | ||
| 28 | + | ||
| 29 | + if got := editor.Profile().Name; got != pythonlang.Name { | ||
| 30 | + t.Errorf("Profile().Name = %q, want %q", got, pythonlang.Name) | ||
| 31 | + } | ||
| 32 | + if got := editor.Profile().ProjectDir(); got != ".turbo-python" { | ||
| 33 | + t.Errorf("ProjectDir() = %q, want %q", got, ".turbo-python") | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +func TestTheEditorColoursPythonSourceItOpens(t *testing.T) { | ||
| 38 | + // The whole path in one test: Register taught the library about Python, the | ||
| 39 | + // profile named the editor, and a .py file opened through the public API | ||
| 40 | + // comes out coloured. | ||
| 41 | + root := t.TempDir() | ||
| 42 | + path := filepath.Join(root, "main.py") | ||
| 43 | + writeFile(t, path, "def main() -> None:\n pass\n") | ||
| 44 | + | ||
| 45 | + editor := newTestEditor(t) | ||
| 46 | + editor.Open(path) | ||
| 47 | + | ||
| 48 | + if got := editor.ActiveView().Language(); got != pythonlang.Language { | ||
| 49 | + t.Fatalf("the view colours the file as %q, want %q", got, pythonlang.Language) | ||
| 50 | + } | ||
| 51 | + if spans := syntax.Highlight(pythonlang.Language, "def main():"); len(spans[0]) == 0 { | ||
| 52 | + t.Error("the registered Python scanner colours nothing") | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +// A Python script in a bin directory has no extension at all, and its first | ||
| 57 | +// line is the only thing that says what it is. That is what Shebangs is for. | ||
| 58 | +func TestAScriptWithNoExtensionIsRecognisedByItsShebang(t *testing.T) { | ||
| 59 | + root := t.TempDir() | ||
| 60 | + path := filepath.Join(root, "deploy") | ||
| 61 | + writeFile(t, path, "#!/usr/bin/env python3\nimport sys\n") | ||
| 62 | + | ||
| 63 | + editor := newTestEditor(t) | ||
| 64 | + editor.Open(path) | ||
| 65 | + | ||
| 66 | + if got := editor.ActiveView().Language(); got != pythonlang.Language { | ||
| 67 | + t.Errorf("a file starting with a python shebang is coloured as %q, want %q", got, pythonlang.Language) | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +func TestTheEditorDoesNotColourRust(t *testing.T) { | ||
| 72 | + // "Python instead of Rust" is the whole point of this editor being a | ||
| 73 | + // separate one: a .rs file opens as plain text here. | ||
| 74 | + root := t.TempDir() | ||
| 75 | + path := filepath.Join(root, "main.rs") | ||
| 76 | + writeFile(t, path, "fn main() {}\n") | ||
| 77 | + | ||
| 78 | + editor := newTestEditor(t) | ||
| 79 | + editor.Open(path) | ||
| 80 | + | ||
| 81 | + if got := editor.ActiveView().Language(); got != syntax.LanguageNone { | ||
| 82 | + t.Errorf("a .rs file is coloured as %q; Turbo Python registers Python, not Rust", got) | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +func TestTheToolchainMenuIsCalledPythonAndNoTwoMenusShareAHotKey(t *testing.T) { | ||
| 87 | + // The bar answers the first menu whose hot key matches, so a clash makes | ||
| 88 | + // one of the two unreachable from the keyboard — silently, and with every | ||
| 89 | + // other test still passing. Python takes P because none of the fixed menus | ||
| 90 | + // does, which is exactly the sort of thing only this test notices. | ||
| 91 | + editor := newTestEditor(t) | ||
| 92 | + | ||
| 93 | + seen := map[rune]string{} | ||
| 94 | + found := false | ||
| 95 | + for _, menu := range editor.MenuBar().Menus() { | ||
| 96 | + label, hot, _ := ui.SplitHotKey(menu.Label) | ||
| 97 | + if label == "Python" { | ||
| 98 | + found = true | ||
| 99 | + } | ||
| 100 | + if hot == 0 { | ||
| 101 | + t.Errorf("the %q menu has no hot key", label) | ||
| 102 | + continue | ||
| 103 | + } | ||
| 104 | + if other, clash := seen[hot]; clash { | ||
| 105 | + t.Errorf("%q and %q both answer to Alt-%c", other, label, hot) | ||
| 106 | + } | ||
| 107 | + seen[hot] = label | ||
| 108 | + } | ||
| 109 | + if !found { | ||
| 110 | + t.Error("there is no Python menu on the bar") | ||
| 111 | + } | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +// --- driven against a real python-lsp-server -------------------------------- | ||
| 115 | + | ||
| 116 | +// TestCompletionEndToEndWithRealPylsp drives the exact sequence the command | ||
| 117 | +// does at start-up: open the files first, start the language server second, | ||
| 118 | +// then ask for a completion. | ||
| 119 | +// | ||
| 120 | +// That order is the whole point, and it is the one Turbo Go got wrong once: an | ||
| 121 | +// editor that announces its open documents to a server which does not exist yet | ||
| 122 | +// and never mentions them again gets answers about a file the server has never | ||
| 123 | +// heard of — which looks, from the outside, exactly like completion not | ||
| 124 | +// working. | ||
| 125 | +// | ||
| 126 | +// It skips itself when pylsp is not installed, and under -short. | ||
| 127 | +func TestCompletionEndToEndWithRealPylsp(t *testing.T) { | ||
| 128 | + root, editor := startRealServer(t) | ||
| 129 | + | ||
| 130 | + // The file on disk stops short of the dot. The text the completion is about | ||
| 131 | + // gets *typed* below, so the answer can only come from what the editor told | ||
| 132 | + // the server — which is the whole point of this test. A fixture already | ||
| 133 | + // containing "json." would be answered from disk, and would pass whether or | ||
| 134 | + // not the editor said anything at all. | ||
| 135 | + path := filepath.Join(root, "main.py") | ||
| 136 | + | ||
| 137 | + view := editor.ActiveView() | ||
| 138 | + view.Buffer().SetCursor(buffer.Position{Line: completionLine, Col: 4}) | ||
| 139 | + typeText(editor, "json.") | ||
| 140 | + | ||
| 141 | + // Typing the dot asks for a completion by itself, but a server that is | ||
| 142 | + // still indexing answers nothing at all. Asking again until it answers is | ||
| 143 | + // what a person does too. | ||
| 144 | + if !waitForCompletion(t, editor) { | ||
| 145 | + t.Fatalf("no completion list opened for %s; the status bar says %q", path, editor.StatusBar().Message()) | ||
| 146 | + } | ||
| 147 | + if !completionOffers(editor, "loads") { | ||
| 148 | + t.Errorf("the list does not offer json.loads; it has %d entries", editor.Completion().Count()) | ||
| 149 | + } | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +// Several answers, not one. An earlier version of the library took the first | ||
| 153 | +// location and threw the rest away, so a name used in three places sent you to | ||
| 154 | +// whichever one the server happened to list first. | ||
| 155 | +func TestReferencesAcrossAFileWithRealPylsp(t *testing.T) { | ||
| 156 | + root, editor := startRealServer(t) | ||
| 157 | + path := filepath.Join(root, "main.py") | ||
| 158 | + | ||
| 159 | + locations := waitForLocations(t, func(ctx context.Context) ([]lsp.Location, error) { | ||
| 160 | + return editor.Language().References(ctx, path, helperLine, helperColumn, helperLineText) | ||
| 161 | + }) | ||
| 162 | + | ||
| 163 | + if len(locations) < 3 { | ||
| 164 | + t.Errorf("helper has %d references, want at least 3 — its declaration and its two call sites: %v", | ||
| 165 | + len(locations), locations) | ||
| 166 | + } | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +func TestTheSymbolsOfAFileWithRealPylsp(t *testing.T) { | ||
| 170 | + root, editor := startRealServer(t) | ||
| 171 | + path := filepath.Join(root, "main.py") | ||
| 172 | + | ||
| 173 | + var symbols []lsp.Symbol | ||
| 174 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 175 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | ||
| 176 | + defer cancel() | ||
| 177 | + found, err := editor.Language().DocumentSymbols(ctx, path) | ||
| 178 | + if err != nil { | ||
| 179 | + return false | ||
| 180 | + } | ||
| 181 | + symbols = found | ||
| 182 | + return len(symbols) > 0 | ||
| 183 | + }) | ||
| 184 | + | ||
| 185 | + names := map[string]bool{} | ||
| 186 | + for _, symbol := range symbols { | ||
| 187 | + names[symbol.Name] = true | ||
| 188 | + } | ||
| 189 | + for _, want := range []string{"helper", "first", "second"} { | ||
| 190 | + if !names[want] { | ||
| 191 | + t.Errorf("the file's symbols do not include %q: %v", want, names) | ||
| 192 | + } | ||
| 193 | + } | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +// Diagnostics are the one thing a language server sends without being asked, | ||
| 197 | +// and the only feature whose failure looks exactly like success: an editor with | ||
| 198 | +// no error to show and one that cannot find the error are the same blank | ||
| 199 | +// gutter. So this opens a file that does not parse and waits for the mark. | ||
| 200 | +func TestDiagnosticsForAFileThatDoesNotParseWithRealPylsp(t *testing.T) { | ||
| 201 | + root, editor := startRealServer(t) | ||
| 202 | + | ||
| 203 | + broken := filepath.Join(root, "broken.py") | ||
| 204 | + writeFile(t, broken, "def f(:\n return 1\n") | ||
| 205 | + editor.Open(broken) | ||
| 206 | + editor.Tick() | ||
| 207 | + | ||
| 208 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 209 | + editor.Tick() | ||
| 210 | + return len(editor.Language().Diagnostics(broken)) > 0 | ||
| 211 | + }) | ||
| 212 | + | ||
| 213 | + problems := editor.Language().Diagnostics(broken) | ||
| 214 | + if len(problems) == 0 { | ||
| 215 | + t.Fatalf("no diagnostic ever arrived for %s; the status bar says %q", broken, editor.StatusBar().Message()) | ||
| 216 | + } | ||
| 217 | + if _, ok := editor.Language().FirstError(broken); !ok { | ||
| 218 | + t.Errorf("the diagnostics hold no error, only %v", problems) | ||
| 219 | + } | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +// python-lsp-server advertises neither implementationProvider nor | ||
| 223 | +// workspaceSymbolProvider, so two of the nine questions turbo-core asks come | ||
| 224 | +// back empty. That is documented in how-to/enable-completion.md, and this test | ||
| 225 | +// is what keeps the documentation honest: if a future pylsp answers either of | ||
| 226 | +// them, this fails and the page gets revisited. | ||
| 227 | +func TestPylspAnswersNeitherImplementationsNorProjectWideSymbols(t *testing.T) { | ||
| 228 | + root, editor := startRealServer(t) | ||
| 229 | + path := filepath.Join(root, "main.py") | ||
| 230 | + | ||
| 231 | + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) | ||
| 232 | + defer cancel() | ||
| 233 | + | ||
| 234 | + if found, err := editor.Language().Implementation(ctx, path, helperLine, helperColumn, helperLineText); err == nil && len(found) > 0 { | ||
| 235 | + t.Errorf("pylsp now answers implementations (%v); how-to/enable-completion.md says it does not", found) | ||
| 236 | + } | ||
| 237 | + if found, err := editor.Language().WorkspaceSymbols(ctx, "helper"); err == nil && len(found) > 0 { | ||
| 238 | + t.Errorf("pylsp now answers project-wide symbols (%v); how-to/enable-completion.md says it does not", found) | ||
| 239 | + } | ||
| 240 | +} | ||
| 241 | + | ||
| 242 | +// --- the fixtures and the waiting ------------------------------------------- | ||
| 243 | + | ||
| 244 | +// realProject is the file every language-server test works against. Line | ||
| 245 | +// numbers are counted from zero and are named by the two constants below, so | ||
| 246 | +// inserting a line here moves them and the constants have to move too. | ||
| 247 | +// | ||
| 248 | +// 0 import json | ||
| 249 | +// 1 | ||
| 250 | +// 2 | ||
| 251 | +// 3 def load(text: str) -> object: | ||
| 252 | +// 4 ← four spaces, and where the completion is typed | ||
| 253 | +// 5 return json.loads(text) | ||
| 254 | +// 6 | ||
| 255 | +// 7 | ||
| 256 | +// 8 def helper() -> int: | ||
| 257 | +// 9 return 1 | ||
| 258 | +// 10 | ||
| 259 | +// 11 | ||
| 260 | +// 12 def first() -> int: | ||
| 261 | +// 13 return helper() | ||
| 262 | +// … | ||
| 263 | +// | ||
| 264 | +// The line the completion is typed on is deliberately blank on disk but | ||
| 265 | +// indented, so that the cursor can sit where a statement would. | ||
| 266 | +const realProject = "import json\n" + | ||
| 267 | + "\n" + | ||
| 268 | + "\n" + | ||
| 269 | + "def load(text: str) -> object:\n" + | ||
| 270 | + " \n" + | ||
| 271 | + " return json.loads(text)\n" + | ||
| 272 | + "\n" + | ||
| 273 | + "\n" + | ||
| 274 | + "def helper() -> int:\n" + | ||
| 275 | + " return 1\n" + | ||
| 276 | + "\n" + | ||
| 277 | + "\n" + | ||
| 278 | + "def first() -> int:\n" + | ||
| 279 | + " return helper()\n" + | ||
| 280 | + "\n" + | ||
| 281 | + "\n" + | ||
| 282 | + "def second() -> int:\n" + | ||
| 283 | + " return helper() + 1\n" | ||
| 284 | + | ||
| 285 | +// Where the fixture's interesting lines are, counted from zero. | ||
| 286 | +const ( | ||
| 287 | + completionLine = 4 | ||
| 288 | + helperLine = 8 | ||
| 289 | + helperColumn = 4 | ||
| 290 | + helperLineText = "def helper() -> int:" | ||
| 291 | +) | ||
| 292 | + | ||
| 293 | +// startRealServer writes a project, opens its file, starts pylsp and waits for | ||
| 294 | +// it, in the order the command does. It skips the test when pylsp is missing. | ||
| 295 | +func startRealServer(t *testing.T) (root string, editor *app.App) { | ||
| 296 | + t.Helper() | ||
| 297 | + if testing.Short() { | ||
| 298 | + t.Skip("-short: not starting a language server") | ||
| 299 | + } | ||
| 300 | + | ||
| 301 | + server, err := lsp.FindServer(pythonlang.Profile().Server) | ||
| 302 | + if errors.Is(err, lsp.ErrServerNotFound) { | ||
| 303 | + t.Skipf("%s is not installed; %s", pythonlang.ServerCommand, pythonlang.InstallHint) | ||
| 304 | + } | ||
| 305 | + // Finding it is not the same as being able to run it: a shim left behind by | ||
| 306 | + // a tool manager whose environment has since been removed is on PATH and | ||
| 307 | + // fails only when started. | ||
| 308 | + if !serverRuns(server) { | ||
| 309 | + t.Skipf("%s at %s cannot run; %s", pythonlang.ServerCommand, server, pythonlang.InstallHint) | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + root = t.TempDir() | ||
| 313 | + writeFile(t, filepath.Join(root, "pyproject.toml"), | ||
| 314 | + "[project]\nname = \"example\"\nversion = \"0.1.0\"\n") | ||
| 315 | + writeFile(t, filepath.Join(root, "main.py"), realProject) | ||
| 316 | + | ||
| 317 | + editor = newTestEditor(t) | ||
| 318 | + | ||
| 319 | + // 1. Open the file, exactly as main does — before there is any server. | ||
| 320 | + editor.Open(filepath.Join(root, "main.py")) | ||
| 321 | + | ||
| 322 | + // 2. Start the language server, exactly as main does — afterwards. | ||
| 323 | + ctx, cancel := context.WithCancel(t.Context()) | ||
| 324 | + t.Cleanup(cancel) | ||
| 325 | + editor.StartLanguageServer(ctx, root) | ||
| 326 | + t.Cleanup(func() { editor.Language().Stop(context.Background()) }) | ||
| 327 | + | ||
| 328 | + waitUntilReady(t, editor) | ||
| 329 | + | ||
| 330 | + // 3. Let the event loop notice the server is ready, as Run does on every | ||
| 331 | + // turn. This is what announces the file that was already open. | ||
| 332 | + editor.Tick() | ||
| 333 | + return root, editor | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +// newTestEditor returns Turbo Python drawing on a simulated terminal, set up | ||
| 337 | +// the way the command sets it up. | ||
| 338 | +func newTestEditor(t *testing.T) *app.App { | ||
| 339 | + t.Helper() | ||
| 340 | + | ||
| 341 | + pythonlang.Register() | ||
| 342 | + screen := tcell.NewSimulationScreen("UTF-8") | ||
| 343 | + if err := screen.Init(); err != nil { | ||
| 344 | + t.Fatalf("initialising the simulation screen: %v", err) | ||
| 345 | + } | ||
| 346 | + t.Cleanup(screen.Fini) | ||
| 347 | + screen.SetSize(80, 24) | ||
| 348 | + | ||
| 349 | + // Never read the themes or snippets of whoever is running the tests. | ||
| 350 | + p := pythonlang.Profile() | ||
| 351 | + t.Setenv(p.ThemeDirEnvVar(), t.TempDir()) | ||
| 352 | + t.Setenv(p.SnippetDirEnvVar(), t.TempDir()) | ||
| 353 | + | ||
| 354 | + editor := app.New(screen, "turbo-classic", p) | ||
| 355 | + editor.Render() | ||
| 356 | + return editor | ||
| 357 | +} | ||
| 358 | + | ||
| 359 | +// typeText sends a run of printable characters through the whole routing chain. | ||
| 360 | +func typeText(editor *app.App, text string) { | ||
| 361 | + for _, r := range text { | ||
| 362 | + editor.Handle(tcell.NewEventKey(tcell.KeyRune, r, tcell.ModNone)) | ||
| 363 | + } | ||
| 364 | +} | ||
| 365 | + | ||
| 366 | +// completionOffers reports whether the open popup holds an entry starting with | ||
| 367 | +// a label. | ||
| 368 | +func completionOffers(editor *app.App, label string) bool { | ||
| 369 | + for _, item := range editor.Completion().Matches() { | ||
| 370 | + if strings.HasPrefix(item.Label, label) { | ||
| 371 | + return true | ||
| 372 | + } | ||
| 373 | + } | ||
| 374 | + return false | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +// waitUntilReady blocks until the language server has finished starting. | ||
| 378 | +func waitUntilReady(t *testing.T, editor *app.App) { | ||
| 379 | + t.Helper() | ||
| 380 | + | ||
| 381 | + deadline := time.After(lsp.InitializeTimeout) | ||
| 382 | + for !editor.Language().Ready() { | ||
| 383 | + select { | ||
| 384 | + case <-deadline: | ||
| 385 | + t.Fatalf("the language server never became ready: %s", editor.Language().Status()) | ||
| 386 | + case <-time.After(10 * time.Millisecond): | ||
| 387 | + } | ||
| 388 | + } | ||
| 389 | +} | ||
| 390 | + | ||
| 391 | +// waitUntil polls a condition until it holds or the time runs out, and fails | ||
| 392 | +// the test if it never does. | ||
| 393 | +func waitUntil(t *testing.T, within time.Duration, done func() bool) { | ||
| 394 | + t.Helper() | ||
| 395 | + | ||
| 396 | + deadline := time.Now().Add(within) | ||
| 397 | + for time.Now().Before(deadline) { | ||
| 398 | + if done() { | ||
| 399 | + return | ||
| 400 | + } | ||
| 401 | + time.Sleep(200 * time.Millisecond) | ||
| 402 | + } | ||
| 403 | + t.Errorf("the server never answered within %s", within) | ||
| 404 | +} | ||
| 405 | + | ||
| 406 | +// waitForLocations asks a location question until it is answered, because a | ||
| 407 | +// server that is still indexing answers an empty list rather than an error. | ||
| 408 | +func waitForLocations(t *testing.T, ask func(context.Context) ([]lsp.Location, error)) []lsp.Location { | ||
| 409 | + t.Helper() | ||
| 410 | + | ||
| 411 | + var found []lsp.Location | ||
| 412 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 413 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | ||
| 414 | + defer cancel() | ||
| 415 | + | ||
| 416 | + locations, err := ask(ctx) | ||
| 417 | + if err != nil { | ||
| 418 | + return false | ||
| 419 | + } | ||
| 420 | + found = locations | ||
| 421 | + return len(found) > 0 | ||
| 422 | + }) | ||
| 423 | + return found | ||
| 424 | +} | ||
| 425 | + | ||
| 426 | +// waitForCompletion asks for a completion until one arrives, or gives up. | ||
| 427 | +// | ||
| 428 | +// A server loads the workspace after it has finished initialising, and answers | ||
| 429 | +// an empty list until that is done. There is no notification this client reads | ||
| 430 | +// that says when — so it asks again, which is what the editor's user would do. | ||
| 431 | +func waitForCompletion(t *testing.T, editor *app.App) bool { | ||
| 432 | + t.Helper() | ||
| 433 | + | ||
| 434 | + deadline := time.Now().Add(60 * time.Second) | ||
| 435 | + for time.Now().Before(deadline) { | ||
| 436 | + if editor.Completion().Visible() { | ||
| 437 | + return true | ||
| 438 | + } | ||
| 439 | + editor.RequestCompletion() | ||
| 440 | + if editor.Completion().Visible() { | ||
| 441 | + return true | ||
| 442 | + } | ||
| 443 | + time.Sleep(500 * time.Millisecond) | ||
| 444 | + } | ||
| 445 | + return false | ||
| 446 | +} | ||
| 447 | + | ||
| 448 | +// serverRuns reports whether the language server at path actually starts. | ||
| 449 | +func serverRuns(path string) bool { | ||
| 450 | + err := exec.Command(path, "--version").Run() | ||
| 451 | + return err == nil | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +// writeFile creates a file, making its directory first. | ||
| 455 | +func writeFile(t *testing.T, path, content string) { | ||
| 456 | + t.Helper() | ||
| 457 | + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { | ||
| 458 | + t.Fatalf("creating %s: %v", filepath.Dir(path), err) | ||
| 459 | + } | ||
| 460 | + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { | ||
| 461 | + t.Fatalf("writing %s: %v", path, err) | ||
| 462 | + } | ||
| 463 | +} | ||
added
internal/pythonlang/literals.go +129 -0 | new file mode 100644 | ||
| @@ -0,0 +1,129 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +// The strings of Python: eight prefixes, two quotes, and each of those in a | |
| 4 | +// single and a triple form — sixteen spellings of one construct, plus the two | |
| 5 | +// different ways one of them reaches the next line. | |
| 6 | + | |
| 7 | +import ( | |
| 8 | + "strings" | |
| 9 | + | |
| 10 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 11 | +) | |
| 12 | + | |
| 13 | +// maxStringPrefix is how many letters may come before the quote: rb, fr and | |
| 14 | +// their case variants are two, and nothing in the language is three. | |
| 15 | +const maxStringPrefix = 2 | |
| 16 | + | |
| 17 | +// isStringStart reports whether a string literal opens at the scanner's | |
| 18 | +// position, prefix included. | |
| 19 | +func isStringStart(s *syntax.LineScanner) bool { | |
| 20 | + _, opens := stringPrefixLength(s) | |
| 21 | + return opens | |
| 22 | +} | |
| 23 | + | |
| 24 | +// stringPrefixLength returns how many prefix letters come before the quote, and | |
| 25 | +// whether a string opens here at all. | |
| 26 | +// | |
| 27 | +// It accepts any one or two of f, r, b and u in any order and in any case, | |
| 28 | +// which is a little more generous than the language: `bu"…"` is not a Python | |
| 29 | +// string and is coloured as one. Being generous is the right way to be wrong | |
| 30 | +// here — the alternative is a table of the twenty-four accepted spellings, and | |
| 31 | +// a half-typed prefix under the cursor colouring as an identifier and a string | |
| 32 | +// that are not there. | |
| 33 | +func stringPrefixLength(s *syntax.LineScanner) (int, bool) { | |
| 34 | + for length := 0; length <= maxStringPrefix; length++ { | |
| 35 | + switch r := s.Peek(length); { | |
| 36 | + case r == '"' || r == '\'': | |
| 37 | + return length, true | |
| 38 | + case !isStringPrefixRune(r): | |
| 39 | + return 0, false | |
| 40 | + } | |
| 41 | + } | |
| 42 | + return 0, false | |
| 43 | +} | |
| 44 | + | |
| 45 | +// isStringPrefixRune reports whether a rune may appear in a string's prefix. | |
| 46 | +func isStringPrefixRune(r rune) bool { | |
| 47 | + switch r { | |
| 48 | + case 'f', 'F', 'r', 'R', 'b', 'B', 'u', 'U': | |
| 49 | + return true | |
| 50 | + } | |
| 51 | + return false | |
| 52 | +} | |
| 53 | + | |
| 54 | +// takeString colours a string from its prefix, remembering what would close it. | |
| 55 | +// | |
| 56 | +// An f-string's {expression} is *not* scanned as code. Since Python 3.12 it may | |
| 57 | +// hold anything, nested quotes and comments included, so colouring it properly | |
| 58 | +// means running the whole scanner inside itself; colouring it half-properly | |
| 59 | +// means a brace in a format spec — "{n:{width}}" — ending the string early. One | |
| 60 | +// flat run is the honest answer, and it is the one this scanner gives. | |
| 61 | +func takeString(s *syntax.LineScanner, open *carry) { | |
| 62 | + start := s.Pos() | |
| 63 | + | |
| 64 | + prefix, _ := stringPrefixLength(s) | |
| 65 | + s.Advance(prefix) | |
| 66 | + | |
| 67 | + quote := s.Peek(0) | |
| 68 | + triple := s.Peek(1) == quote && s.Peek(2) == quote | |
| 69 | + if triple { | |
| 70 | + s.Advance(3) | |
| 71 | + } else { | |
| 72 | + s.Advance(1) | |
| 73 | + } | |
| 74 | + open.open, open.quote, open.triple = true, quote, triple | |
| 75 | + | |
| 76 | + consumeString(s, open) | |
| 77 | + s.Emit(start, s.Pos(), syntax.ClassString) | |
| 78 | +} | |
| 79 | + | |
| 80 | +// continueString colours the rest of a string opened on an earlier line, and | |
| 81 | +// reports whether the line has code after it. | |
| 82 | +func continueString(s *syntax.LineScanner, open *carry) bool { | |
| 83 | + consumeString(s, open) | |
| 84 | + s.Emit(0, s.Pos(), syntax.ClassString) | |
| 85 | + return !open.open && !s.AtEnd() | |
| 86 | +} | |
| 87 | + | |
| 88 | +// consumeString runs to whatever closes the string, or to the end of the line, | |
| 89 | +// and decides there whether the string carries on to the next one. | |
| 90 | +// | |
| 91 | +// A backslash takes the rune after it out of consideration, in a raw string as | |
| 92 | +// much as in an ordinary one — that is what makes r"\"" one string rather than | |
| 93 | +// two. A backslash that is itself the last rune on the line escapes the newline | |
| 94 | +// instead, which is the only way a single-quoted string reaches the next line. | |
| 95 | +func consumeString(s *syntax.LineScanner, open *carry) { | |
| 96 | + closer := stringCloser(*open) | |
| 97 | + continued := false | |
| 98 | + | |
| 99 | + for !s.AtEnd() { | |
| 100 | + switch { | |
| 101 | + case s.Peek(0) == '\\': | |
| 102 | + continued = s.Pos()+2 > s.Len() | |
| 103 | + s.Advance(2) | |
| 104 | + case s.HasPrefix(0, closer): | |
| 105 | + s.Advance(len([]rune(closer))) | |
| 106 | + open.open = false | |
| 107 | + return | |
| 108 | + default: | |
| 109 | + continued = false | |
| 110 | + s.Advance(1) | |
| 111 | + } | |
| 112 | + } | |
| 113 | + | |
| 114 | + // The line ended with the string still open. A triple-quoted one is meant | |
| 115 | + // to do that; a single-quoted one only does it when the newline was | |
| 116 | + // escaped. Anything else is source in the middle of being typed, and is | |
| 117 | + // left behind rather than carried into the rest of the file. | |
| 118 | + if !open.triple && !continued { | |
| 119 | + open.open = false | |
| 120 | + } | |
| 121 | +} | |
| 122 | + | |
| 123 | +// stringCloser returns the text that ends the string being scanned. | |
| 124 | +func stringCloser(open carry) string { | |
| 125 | + if open.triple { | |
| 126 | + return strings.Repeat(string(open.quote), 3) | |
| 127 | + } | |
| 128 | + return string(open.quote) | |
| 129 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,129 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +// The strings of Python: eight prefixes, two quotes, and each of those in a | ||
| 4 | +// single and a triple form — sixteen spellings of one construct, plus the two | ||
| 5 | +// different ways one of them reaches the next line. | ||
| 6 | + | ||
| 7 | +import ( | ||
| 8 | + "strings" | ||
| 9 | + | ||
| 10 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 11 | +) | ||
| 12 | + | ||
| 13 | +// maxStringPrefix is how many letters may come before the quote: rb, fr and | ||
| 14 | +// their case variants are two, and nothing in the language is three. | ||
| 15 | +const maxStringPrefix = 2 | ||
| 16 | + | ||
| 17 | +// isStringStart reports whether a string literal opens at the scanner's | ||
| 18 | +// position, prefix included. | ||
| 19 | +func isStringStart(s *syntax.LineScanner) bool { | ||
| 20 | + _, opens := stringPrefixLength(s) | ||
| 21 | + return opens | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +// stringPrefixLength returns how many prefix letters come before the quote, and | ||
| 25 | +// whether a string opens here at all. | ||
| 26 | +// | ||
| 27 | +// It accepts any one or two of f, r, b and u in any order and in any case, | ||
| 28 | +// which is a little more generous than the language: `bu"…"` is not a Python | ||
| 29 | +// string and is coloured as one. Being generous is the right way to be wrong | ||
| 30 | +// here — the alternative is a table of the twenty-four accepted spellings, and | ||
| 31 | +// a half-typed prefix under the cursor colouring as an identifier and a string | ||
| 32 | +// that are not there. | ||
| 33 | +func stringPrefixLength(s *syntax.LineScanner) (int, bool) { | ||
| 34 | + for length := 0; length <= maxStringPrefix; length++ { | ||
| 35 | + switch r := s.Peek(length); { | ||
| 36 | + case r == '"' || r == '\'': | ||
| 37 | + return length, true | ||
| 38 | + case !isStringPrefixRune(r): | ||
| 39 | + return 0, false | ||
| 40 | + } | ||
| 41 | + } | ||
| 42 | + return 0, false | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +// isStringPrefixRune reports whether a rune may appear in a string's prefix. | ||
| 46 | +func isStringPrefixRune(r rune) bool { | ||
| 47 | + switch r { | ||
| 48 | + case 'f', 'F', 'r', 'R', 'b', 'B', 'u', 'U': | ||
| 49 | + return true | ||
| 50 | + } | ||
| 51 | + return false | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +// takeString colours a string from its prefix, remembering what would close it. | ||
| 55 | +// | ||
| 56 | +// An f-string's {expression} is *not* scanned as code. Since Python 3.12 it may | ||
| 57 | +// hold anything, nested quotes and comments included, so colouring it properly | ||
| 58 | +// means running the whole scanner inside itself; colouring it half-properly | ||
| 59 | +// means a brace in a format spec — "{n:{width}}" — ending the string early. One | ||
| 60 | +// flat run is the honest answer, and it is the one this scanner gives. | ||
| 61 | +func takeString(s *syntax.LineScanner, open *carry) { | ||
| 62 | + start := s.Pos() | ||
| 63 | + | ||
| 64 | + prefix, _ := stringPrefixLength(s) | ||
| 65 | + s.Advance(prefix) | ||
| 66 | + | ||
| 67 | + quote := s.Peek(0) | ||
| 68 | + triple := s.Peek(1) == quote && s.Peek(2) == quote | ||
| 69 | + if triple { | ||
| 70 | + s.Advance(3) | ||
| 71 | + } else { | ||
| 72 | + s.Advance(1) | ||
| 73 | + } | ||
| 74 | + open.open, open.quote, open.triple = true, quote, triple | ||
| 75 | + | ||
| 76 | + consumeString(s, open) | ||
| 77 | + s.Emit(start, s.Pos(), syntax.ClassString) | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +// continueString colours the rest of a string opened on an earlier line, and | ||
| 81 | +// reports whether the line has code after it. | ||
| 82 | +func continueString(s *syntax.LineScanner, open *carry) bool { | ||
| 83 | + consumeString(s, open) | ||
| 84 | + s.Emit(0, s.Pos(), syntax.ClassString) | ||
| 85 | + return !open.open && !s.AtEnd() | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +// consumeString runs to whatever closes the string, or to the end of the line, | ||
| 89 | +// and decides there whether the string carries on to the next one. | ||
| 90 | +// | ||
| 91 | +// A backslash takes the rune after it out of consideration, in a raw string as | ||
| 92 | +// much as in an ordinary one — that is what makes r"\"" one string rather than | ||
| 93 | +// two. A backslash that is itself the last rune on the line escapes the newline | ||
| 94 | +// instead, which is the only way a single-quoted string reaches the next line. | ||
| 95 | +func consumeString(s *syntax.LineScanner, open *carry) { | ||
| 96 | + closer := stringCloser(*open) | ||
| 97 | + continued := false | ||
| 98 | + | ||
| 99 | + for !s.AtEnd() { | ||
| 100 | + switch { | ||
| 101 | + case s.Peek(0) == '\\': | ||
| 102 | + continued = s.Pos()+2 > s.Len() | ||
| 103 | + s.Advance(2) | ||
| 104 | + case s.HasPrefix(0, closer): | ||
| 105 | + s.Advance(len([]rune(closer))) | ||
| 106 | + open.open = false | ||
| 107 | + return | ||
| 108 | + default: | ||
| 109 | + continued = false | ||
| 110 | + s.Advance(1) | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + // The line ended with the string still open. A triple-quoted one is meant | ||
| 115 | + // to do that; a single-quoted one only does it when the newline was | ||
| 116 | + // escaped. Anything else is source in the middle of being typed, and is | ||
| 117 | + // left behind rather than carried into the rest of the file. | ||
| 118 | + if !open.triple && !continued { | ||
| 119 | + open.open = false | ||
| 120 | + } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +// stringCloser returns the text that ends the string being scanned. | ||
| 124 | +func stringCloser(open carry) string { | ||
| 125 | + if open.triple { | ||
| 126 | + return strings.Repeat(string(open.quote), 3) | ||
| 127 | + } | ||
| 128 | + return string(open.quote) | ||
| 129 | +} | ||
added
internal/pythonlang/profile_test.go +178 -0 | new file mode 100644 | ||
| @@ -0,0 +1,178 @@ | ||
| 1 | +package pythonlang_test | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "os" | |
| 5 | + "path/filepath" | |
| 6 | + "runtime" | |
| 7 | + "slices" | |
| 8 | + "testing" | |
| 9 | + | |
| 10 | + "rickub.com/turbo-editors/turbo-core/ui" | |
| 11 | + | |
| 12 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// The slug is load-bearing: four different names are derived from it, and | |
| 16 | +// changing it renames a directory in everybody's projects. | |
| 17 | +func TestTheSlugNamesTheProjectDirectoryAndEveryEnvironmentVariable(t *testing.T) { | |
| 18 | + p := pythonlang.Profile() | |
| 19 | + | |
| 20 | + for _, c := range []struct { | |
| 21 | + what string | |
| 22 | + got string | |
| 23 | + want string | |
| 24 | + }{ | |
| 25 | + {"ProjectDir", p.ProjectDir(), ".turbo-python"}, | |
| 26 | + {"DirEnvVar", p.DirEnvVar(), "TURBO_PYTHON_DIR"}, | |
| 27 | + {"ThemeDirEnvVar", p.ThemeDirEnvVar(), "TURBO_PYTHON_THEME_DIR"}, | |
| 28 | + {"SnippetDirEnvVar", p.SnippetDirEnvVar(), "TURBO_PYTHON_SNIPPET_DIR"}, | |
| 29 | + } { | |
| 30 | + if c.got != c.want { | |
| 31 | + t.Errorf("%s() = %q, want %q", c.what, c.got, c.want) | |
| 32 | + } | |
| 33 | + } | |
| 34 | +} | |
| 35 | + | |
| 36 | +func TestTheUserDirectoryFollowsItsEnvironmentVariable(t *testing.T) { | |
| 37 | + p := pythonlang.Profile() | |
| 38 | + dir := t.TempDir() | |
| 39 | + t.Setenv(p.DirEnvVar(), dir) | |
| 40 | + | |
| 41 | + if got := p.UserDir(); got != dir { | |
| 42 | + t.Errorf("UserDir() = %q, want %q", got, dir) | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +// The theme directory's variable names the directory itself, not the one above | |
| 47 | +// it — the one asymmetry in the derived paths, and the one worth a test. | |
| 48 | +func TestTheThemeDirectoryFollowsItsOwnVariable(t *testing.T) { | |
| 49 | + p := pythonlang.Profile() | |
| 50 | + dir := t.TempDir() | |
| 51 | + t.Setenv(p.ThemeDirEnvVar(), dir) | |
| 52 | + | |
| 53 | + if got := p.ThemeDir(); got != dir { | |
| 54 | + t.Errorf("ThemeDir() = %q, want %q", got, dir) | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 58 | +// P is free because the fixed menus take F, E, S, R, C, O, W, N and H. That the | |
| 59 | +// bar agrees is TestTheToolchainMenuIsCalledPython's job, against the real menu | |
| 60 | +// bar; this one holds the label itself to what was decided. | |
| 61 | +// | |
| 62 | +// The key comes back in lower case: a hot key is matched against what the | |
| 63 | +// terminal delivers, and Alt-P and Alt-Shift-P are the same menu. | |
| 64 | +func TestTheToolchainMenuIsPythonOnP(t *testing.T) { | |
| 65 | + label, hot, _ := ui.SplitHotKey(pythonlang.Profile().ToolsMenu) | |
| 66 | + | |
| 67 | + if label != "Python" { | |
| 68 | + t.Errorf("the toolchain menu is labelled %q, want %q", label, "Python") | |
| 69 | + } | |
| 70 | + if hot != 'p' { | |
| 71 | + t.Errorf("its hot key is %q, want %q", hot, 'p') | |
| 72 | + } | |
| 73 | +} | |
| 74 | + | |
| 75 | +func TestTheProjectRootIsLookedForInThreeMarkersInOrder(t *testing.T) { | |
| 76 | + want := []string{"pyproject.toml", "setup.py", "setup.cfg"} | |
| 77 | + | |
| 78 | + if got := pythonlang.Profile().RootMarkers; !slices.Equal(got, want) { | |
| 79 | + t.Errorf("RootMarkers = %q, want %q", got, want) | |
| 80 | + } | |
| 81 | +} | |
| 82 | + | |
| 83 | +func TestTheServerIsPylspWithNoArguments(t *testing.T) { | |
| 84 | + server := pythonlang.Profile().Server | |
| 85 | + | |
| 86 | + if server.Command != "pylsp" { | |
| 87 | + t.Errorf("Server.Command = %q, want %q", server.Command, "pylsp") | |
| 88 | + } | |
| 89 | + if len(server.Args) != 0 { | |
| 90 | + t.Errorf("Server.Args = %q, want none", server.Args) | |
| 91 | + } | |
| 92 | + if server.InstallHint == "" { | |
| 93 | + t.Error("Server.InstallHint is empty; a missing server would be reported with no way out") | |
| 94 | + } | |
| 95 | +} | |
| 96 | + | |
| 97 | +// An active environment is the most specific answer there is, so it goes first: | |
| 98 | +// a server installed into this project's environment must win over one the user | |
| 99 | +// installed years ago. | |
| 100 | +func TestAnActiveVirtualEnvironmentIsTheFirstPlaceLookedAfterPath(t *testing.T) { | |
| 101 | + env := t.TempDir() | |
| 102 | + t.Setenv("VIRTUAL_ENV", env) | |
| 103 | + | |
| 104 | + dirs := pythonlang.ServerDirs() | |
| 105 | + | |
| 106 | + if len(dirs) == 0 || dirs[0] != filepath.Join(env, "bin") { | |
| 107 | + t.Errorf("ServerDirs() = %q, want %q first", dirs, filepath.Join(env, "bin")) | |
| 108 | + } | |
| 109 | +} | |
| 110 | + | |
| 111 | +func TestNoActiveEnvironmentContributesNothing(t *testing.T) { | |
| 112 | + t.Setenv("VIRTUAL_ENV", "") | |
| 113 | + | |
| 114 | + if got := pythonlang.VirtualEnvBinDir(); got != "" { | |
| 115 | + t.Errorf("VirtualEnvBinDir() = %q with VIRTUAL_ENV unset, want empty", got) | |
| 116 | + } | |
| 117 | +} | |
| 118 | + | |
| 119 | +func TestPyenvIsLookedForUnderItsOwnRootWhenOneIsSet(t *testing.T) { | |
| 120 | + root := t.TempDir() | |
| 121 | + t.Setenv("PYENV_ROOT", root) | |
| 122 | + | |
| 123 | + if got, want := pythonlang.PyenvShimDir(), filepath.Join(root, "shims"); got != want { | |
| 124 | + t.Errorf("PyenvShimDir() = %q, want %q", got, want) | |
| 125 | + } | |
| 126 | +} | |
| 127 | + | |
| 128 | +func TestPyenvFallsBackToTheHomeDirectory(t *testing.T) { | |
| 129 | + home := useTemporaryHome(t) | |
| 130 | + t.Setenv("PYENV_ROOT", "") | |
| 131 | + | |
| 132 | + if got, want := pythonlang.PyenvShimDir(), filepath.Join(home, ".pyenv", "shims"); got != want { | |
| 133 | + t.Errorf("PyenvShimDir() = %q, want %q", got, want) | |
| 134 | + } | |
| 135 | +} | |
| 136 | + | |
| 137 | +// The macOS user-scripts directory carries a version number nobody can predict, | |
| 138 | +// so it is read off the disk. A machine with no such directory — every Linux | |
| 139 | +// one — must contribute nothing rather than a path that cannot exist. | |
| 140 | +func TestTheMacOSUserScriptDirectoriesAreReadRatherThanGuessed(t *testing.T) { | |
| 141 | + home := useTemporaryHome(t) | |
| 142 | + | |
| 143 | + if got := pythonlang.FrameworkScriptDirs(); len(got) != 0 { | |
| 144 | + t.Fatalf("FrameworkScriptDirs() = %q with no Library/Python, want none", got) | |
| 145 | + } | |
| 146 | + | |
| 147 | + makeDir(t, filepath.Join(home, "Library", "Python", "3.9", "bin")) | |
| 148 | + makeDir(t, filepath.Join(home, "Library", "Python", "3.13", "bin")) | |
| 149 | + | |
| 150 | + want := []string{ | |
| 151 | + filepath.Join(home, "Library", "Python", "3.13", "bin"), | |
| 152 | + filepath.Join(home, "Library", "Python", "3.9", "bin"), | |
| 153 | + } | |
| 154 | + if got := pythonlang.FrameworkScriptDirs(); !slices.Equal(got, want) { | |
| 155 | + t.Errorf("FrameworkScriptDirs() = %q, want %q", got, want) | |
| 156 | + } | |
| 157 | +} | |
| 158 | + | |
| 159 | +// useTemporaryHome points the home directory at an empty one, so that the tests | |
| 160 | +// never read the directories of whoever is running them. | |
| 161 | +func useTemporaryHome(t *testing.T) string { | |
| 162 | + t.Helper() | |
| 163 | + if runtime.GOOS == "windows" { | |
| 164 | + t.Skip("the home directory is not read from HOME on Windows") | |
| 165 | + } | |
| 166 | + | |
| 167 | + home := t.TempDir() | |
| 168 | + t.Setenv("HOME", home) | |
| 169 | + return home | |
| 170 | +} | |
| 171 | + | |
| 172 | +// makeDir creates a directory and every parent it needs. | |
| 173 | +func makeDir(t *testing.T, path string) { | |
| 174 | + t.Helper() | |
| 175 | + if err := os.MkdirAll(path, 0o755); err != nil { | |
| 176 | + t.Fatalf("creating %s: %v", path, err) | |
| 177 | + } | |
| 178 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,178 @@ | |||
| 1 | +package pythonlang_test | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "os" | ||
| 5 | + "path/filepath" | ||
| 6 | + "runtime" | ||
| 7 | + "slices" | ||
| 8 | + "testing" | ||
| 9 | + | ||
| 10 | + "rickub.com/turbo-editors/turbo-core/ui" | ||
| 11 | + | ||
| 12 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// The slug is load-bearing: four different names are derived from it, and | ||
| 16 | +// changing it renames a directory in everybody's projects. | ||
| 17 | +func TestTheSlugNamesTheProjectDirectoryAndEveryEnvironmentVariable(t *testing.T) { | ||
| 18 | + p := pythonlang.Profile() | ||
| 19 | + | ||
| 20 | + for _, c := range []struct { | ||
| 21 | + what string | ||
| 22 | + got string | ||
| 23 | + want string | ||
| 24 | + }{ | ||
| 25 | + {"ProjectDir", p.ProjectDir(), ".turbo-python"}, | ||
| 26 | + {"DirEnvVar", p.DirEnvVar(), "TURBO_PYTHON_DIR"}, | ||
| 27 | + {"ThemeDirEnvVar", p.ThemeDirEnvVar(), "TURBO_PYTHON_THEME_DIR"}, | ||
| 28 | + {"SnippetDirEnvVar", p.SnippetDirEnvVar(), "TURBO_PYTHON_SNIPPET_DIR"}, | ||
| 29 | + } { | ||
| 30 | + if c.got != c.want { | ||
| 31 | + t.Errorf("%s() = %q, want %q", c.what, c.got, c.want) | ||
| 32 | + } | ||
| 33 | + } | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +func TestTheUserDirectoryFollowsItsEnvironmentVariable(t *testing.T) { | ||
| 37 | + p := pythonlang.Profile() | ||
| 38 | + dir := t.TempDir() | ||
| 39 | + t.Setenv(p.DirEnvVar(), dir) | ||
| 40 | + | ||
| 41 | + if got := p.UserDir(); got != dir { | ||
| 42 | + t.Errorf("UserDir() = %q, want %q", got, dir) | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +// The theme directory's variable names the directory itself, not the one above | ||
| 47 | +// it — the one asymmetry in the derived paths, and the one worth a test. | ||
| 48 | +func TestTheThemeDirectoryFollowsItsOwnVariable(t *testing.T) { | ||
| 49 | + p := pythonlang.Profile() | ||
| 50 | + dir := t.TempDir() | ||
| 51 | + t.Setenv(p.ThemeDirEnvVar(), dir) | ||
| 52 | + | ||
| 53 | + if got := p.ThemeDir(); got != dir { | ||
| 54 | + t.Errorf("ThemeDir() = %q, want %q", got, dir) | ||
| 55 | + } | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +// P is free because the fixed menus take F, E, S, R, C, O, W, N and H. That the | ||
| 59 | +// bar agrees is TestTheToolchainMenuIsCalledPython's job, against the real menu | ||
| 60 | +// bar; this one holds the label itself to what was decided. | ||
| 61 | +// | ||
| 62 | +// The key comes back in lower case: a hot key is matched against what the | ||
| 63 | +// terminal delivers, and Alt-P and Alt-Shift-P are the same menu. | ||
| 64 | +func TestTheToolchainMenuIsPythonOnP(t *testing.T) { | ||
| 65 | + label, hot, _ := ui.SplitHotKey(pythonlang.Profile().ToolsMenu) | ||
| 66 | + | ||
| 67 | + if label != "Python" { | ||
| 68 | + t.Errorf("the toolchain menu is labelled %q, want %q", label, "Python") | ||
| 69 | + } | ||
| 70 | + if hot != 'p' { | ||
| 71 | + t.Errorf("its hot key is %q, want %q", hot, 'p') | ||
| 72 | + } | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +func TestTheProjectRootIsLookedForInThreeMarkersInOrder(t *testing.T) { | ||
| 76 | + want := []string{"pyproject.toml", "setup.py", "setup.cfg"} | ||
| 77 | + | ||
| 78 | + if got := pythonlang.Profile().RootMarkers; !slices.Equal(got, want) { | ||
| 79 | + t.Errorf("RootMarkers = %q, want %q", got, want) | ||
| 80 | + } | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +func TestTheServerIsPylspWithNoArguments(t *testing.T) { | ||
| 84 | + server := pythonlang.Profile().Server | ||
| 85 | + | ||
| 86 | + if server.Command != "pylsp" { | ||
| 87 | + t.Errorf("Server.Command = %q, want %q", server.Command, "pylsp") | ||
| 88 | + } | ||
| 89 | + if len(server.Args) != 0 { | ||
| 90 | + t.Errorf("Server.Args = %q, want none", server.Args) | ||
| 91 | + } | ||
| 92 | + if server.InstallHint == "" { | ||
| 93 | + t.Error("Server.InstallHint is empty; a missing server would be reported with no way out") | ||
| 94 | + } | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +// An active environment is the most specific answer there is, so it goes first: | ||
| 98 | +// a server installed into this project's environment must win over one the user | ||
| 99 | +// installed years ago. | ||
| 100 | +func TestAnActiveVirtualEnvironmentIsTheFirstPlaceLookedAfterPath(t *testing.T) { | ||
| 101 | + env := t.TempDir() | ||
| 102 | + t.Setenv("VIRTUAL_ENV", env) | ||
| 103 | + | ||
| 104 | + dirs := pythonlang.ServerDirs() | ||
| 105 | + | ||
| 106 | + if len(dirs) == 0 || dirs[0] != filepath.Join(env, "bin") { | ||
| 107 | + t.Errorf("ServerDirs() = %q, want %q first", dirs, filepath.Join(env, "bin")) | ||
| 108 | + } | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +func TestNoActiveEnvironmentContributesNothing(t *testing.T) { | ||
| 112 | + t.Setenv("VIRTUAL_ENV", "") | ||
| 113 | + | ||
| 114 | + if got := pythonlang.VirtualEnvBinDir(); got != "" { | ||
| 115 | + t.Errorf("VirtualEnvBinDir() = %q with VIRTUAL_ENV unset, want empty", got) | ||
| 116 | + } | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +func TestPyenvIsLookedForUnderItsOwnRootWhenOneIsSet(t *testing.T) { | ||
| 120 | + root := t.TempDir() | ||
| 121 | + t.Setenv("PYENV_ROOT", root) | ||
| 122 | + | ||
| 123 | + if got, want := pythonlang.PyenvShimDir(), filepath.Join(root, "shims"); got != want { | ||
| 124 | + t.Errorf("PyenvShimDir() = %q, want %q", got, want) | ||
| 125 | + } | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +func TestPyenvFallsBackToTheHomeDirectory(t *testing.T) { | ||
| 129 | + home := useTemporaryHome(t) | ||
| 130 | + t.Setenv("PYENV_ROOT", "") | ||
| 131 | + | ||
| 132 | + if got, want := pythonlang.PyenvShimDir(), filepath.Join(home, ".pyenv", "shims"); got != want { | ||
| 133 | + t.Errorf("PyenvShimDir() = %q, want %q", got, want) | ||
| 134 | + } | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +// The macOS user-scripts directory carries a version number nobody can predict, | ||
| 138 | +// so it is read off the disk. A machine with no such directory — every Linux | ||
| 139 | +// one — must contribute nothing rather than a path that cannot exist. | ||
| 140 | +func TestTheMacOSUserScriptDirectoriesAreReadRatherThanGuessed(t *testing.T) { | ||
| 141 | + home := useTemporaryHome(t) | ||
| 142 | + | ||
| 143 | + if got := pythonlang.FrameworkScriptDirs(); len(got) != 0 { | ||
| 144 | + t.Fatalf("FrameworkScriptDirs() = %q with no Library/Python, want none", got) | ||
| 145 | + } | ||
| 146 | + | ||
| 147 | + makeDir(t, filepath.Join(home, "Library", "Python", "3.9", "bin")) | ||
| 148 | + makeDir(t, filepath.Join(home, "Library", "Python", "3.13", "bin")) | ||
| 149 | + | ||
| 150 | + want := []string{ | ||
| 151 | + filepath.Join(home, "Library", "Python", "3.13", "bin"), | ||
| 152 | + filepath.Join(home, "Library", "Python", "3.9", "bin"), | ||
| 153 | + } | ||
| 154 | + if got := pythonlang.FrameworkScriptDirs(); !slices.Equal(got, want) { | ||
| 155 | + t.Errorf("FrameworkScriptDirs() = %q, want %q", got, want) | ||
| 156 | + } | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +// useTemporaryHome points the home directory at an empty one, so that the tests | ||
| 160 | +// never read the directories of whoever is running them. | ||
| 161 | +func useTemporaryHome(t *testing.T) string { | ||
| 162 | + t.Helper() | ||
| 163 | + if runtime.GOOS == "windows" { | ||
| 164 | + t.Skip("the home directory is not read from HOME on Windows") | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + home := t.TempDir() | ||
| 168 | + t.Setenv("HOME", home) | ||
| 169 | + return home | ||
| 170 | +} | ||
| 171 | + | ||
| 172 | +// makeDir creates a directory and every parent it needs. | ||
| 173 | +func makeDir(t *testing.T, path string) { | ||
| 174 | + t.Helper() | ||
| 175 | + if err := os.MkdirAll(path, 0o755); err != nil { | ||
| 176 | + t.Fatalf("creating %s: %v", path, err) | ||
| 177 | + } | ||
| 178 | +} | ||
added
internal/pythonlang/pythonlang.go +204 -0 | new file mode 100644 | ||
| @@ -0,0 +1,204 @@ | ||
| 1 | +// Package pythonlang is everything about Turbo Python that is about *Python*: | |
| 2 | +// how the editor names itself, which language server it talks to, what a | |
| 3 | +// project's starter files say, and how Python source is coloured. | |
| 4 | +// | |
| 5 | +// Everything else the editor does lives in turbo-core, which knows nothing | |
| 6 | +// about Python. This package is the whole of the difference between Turbo | |
| 7 | +// Python and Turbo Rust, which is what makes a fourth editor a matter of | |
| 8 | +// writing one of these rather than forking anything. | |
| 9 | +// | |
| 10 | +// pythonlang.Register() // teach the library to colour Python | |
| 11 | +// editor := app.New(screen, name, pythonlang.Profile()) | |
| 12 | +package pythonlang | |
| 13 | + | |
| 14 | +import ( | |
| 15 | + "os" | |
| 16 | + "path/filepath" | |
| 17 | + | |
| 18 | + "rickub.com/turbo-editors/turbo-core/profile" | |
| 19 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 20 | +) | |
| 21 | + | |
| 22 | +// Name and Slug are what the editor calls itself. The slug is also its binary, | |
| 23 | +// its project directory (as .turbo-python) and the stem of its environment | |
| 24 | +// variables (as TURBO_PYTHON_…), so it is not free to change. | |
| 25 | +const ( | |
| 26 | + Name = "Turbo Python" | |
| 27 | + Slug = "turbo-python" | |
| 28 | +) | |
| 29 | + | |
| 30 | +// Language is the name Python is known by: the value LanguageOf returns for a | |
| 31 | +// .py file, and what a snippets file writes in its languages key. | |
| 32 | +const Language syntax.Language = "python" | |
| 33 | + | |
| 34 | +// ServerCommand is the language server Turbo Python talks to, and InstallHint | |
| 35 | +// the single command that installs it. | |
| 36 | +// | |
| 37 | +// python-lsp-server answers seven of the nine questions turbo-core asks — | |
| 38 | +// completion, hover, definition, type definition, references and the file's | |
| 39 | +// symbols — and publishes diagnostics unasked. It advertises neither | |
| 40 | +// implementations nor a project-wide symbol search, so those two items report | |
| 41 | +// nothing found; that is documented rather than worked around. | |
| 42 | +// | |
| 43 | +// **The [all] is not optional.** Installed bare, pylsp starts, completes and | |
| 44 | +// jumps, and publishes an *empty* list of diagnostics for a file that does not | |
| 45 | +// parse — because the linters that produce them are extras, and without them | |
| 46 | +// the server has nothing to say. An editor whose gutter stays blank because | |
| 47 | +// the server has no linter looks exactly like one whose gutter is blank | |
| 48 | +// because the code is fine, which is why the hint installs them. | |
| 49 | +// | |
| 50 | +// pipx is named rather than pip because the server is a tool rather than a | |
| 51 | +// dependency of the project being edited, and installing it into that | |
| 52 | +// project's environment is how it ends up missing from the next one. | |
| 53 | +const ( | |
| 54 | + ServerCommand = "pylsp" | |
| 55 | + InstallHint = `pipx install "python-lsp-server[all]"` | |
| 56 | +) | |
| 57 | + | |
| 58 | +// Profile returns the editor Turbo Python is. | |
| 59 | +// | |
| 60 | +// It is a function rather than a variable because Server.Dirs is worked out | |
| 61 | +// from the environment, and a variable would freeze whatever VIRTUAL_ENV said | |
| 62 | +// when the package was linked — which for a Python tool is the one value most | |
| 63 | +// likely to change between two runs in the same shell. | |
| 64 | +func Profile() profile.Profile { | |
| 65 | + return profile.Profile{ | |
| 66 | + Name: Name, | |
| 67 | + Slug: Slug, | |
| 68 | + Language: "Python", | |
| 69 | + // P is free: the fixed menus take F, E, S, R, C, O, W, N and H, so the | |
| 70 | + // hot key lands on the first letter of the word, which is the reading | |
| 71 | + // that costs nobody a second glance. The menu is named after the | |
| 72 | + // language and not after uv, because it holds whatever the project put | |
| 73 | + // in its tools file — and the first tools file anybody writes outgrows | |
| 74 | + // the language's own toolchain. | |
| 75 | + ToolsMenu: "~P~ython", | |
| 76 | + // pyproject.toml first because it is where a modern project declares | |
| 77 | + // itself, then the two forms a setuptools project used before it | |
| 78 | + // existed. The nearest one going up is the directory the server is | |
| 79 | + // started in. | |
| 80 | + RootMarkers: []string{"pyproject.toml", "setup.py", "setup.cfg"}, | |
| 81 | + Server: profile.Server{ | |
| 82 | + Command: ServerCommand, | |
| 83 | + // pylsp takes no subcommand, unlike gopls. | |
| 84 | + Args: nil, | |
| 85 | + InstallHint: InstallHint, | |
| 86 | + Dirs: ServerDirs(), | |
| 87 | + }, | |
| 88 | + Templates: profile.Templates{ | |
| 89 | + Settings: settingsTemplate, | |
| 90 | + Snippets: snippetsTemplate, | |
| 91 | + Tools: toolsTemplate, | |
| 92 | + Agents: agentsTemplate, | |
| 93 | + }, | |
| 94 | + } | |
| 95 | +} | |
| 96 | + | |
| 97 | +// Register teaches turbo-core to colour Python. | |
| 98 | +// | |
| 99 | +// It is called explicitly at start-up rather than from an init function so that | |
| 100 | +// "which languages does this editor know?" is answered by reading main, not by | |
| 101 | +// working out which packages were imported. | |
| 102 | +func Register() { | |
| 103 | + syntax.Register(syntax.Definition{ | |
| 104 | + Language: Language, | |
| 105 | + // .pyw is Windows' "run me without a console window"; .pyi is a stub | |
| 106 | + // file, which is Python and nothing else. | |
| 107 | + Extensions: []string{".py", ".pyi", ".pyw"}, | |
| 108 | + // A Python script with no extension at all is an ordinary thing to | |
| 109 | + // find in a bin directory, and its first line says what it is. | |
| 110 | + Shebangs: []string{"python", "python3"}, | |
| 111 | + Highlight: Highlight, | |
| 112 | + }) | |
| 113 | +} | |
| 114 | + | |
| 115 | +// ServerDirs returns the directories pylsp is looked for in after PATH, most | |
| 116 | +// specific first. | |
| 117 | +// | |
| 118 | +// "Completion silently does nothing" is what a user sees when the editor cannot | |
| 119 | +// find a server they believe they installed, and Python has more places to | |
| 120 | +// install one than most languages: an environment belonging to this project, a | |
| 121 | +// tool directory belonging to this user, a pyenv shim, and — on macOS — a | |
| 122 | +// per-version directory under the user's Library that is on nobody's PATH by | |
| 123 | +// default. | |
| 124 | +// | |
| 125 | +// Empty entries are skipped by the library, so a machine with no pyenv and no | |
| 126 | +// active environment simply contributes nothing here. | |
| 127 | +func ServerDirs() []string { | |
| 128 | + dirs := []string{VirtualEnvBinDir(), UserBinDir(), PyenvShimDir()} | |
| 129 | + return append(dirs, FrameworkScriptDirs()...) | |
| 130 | +} | |
| 131 | + | |
| 132 | +// VirtualEnvBinDir returns the bin directory of the virtual environment that is | |
| 133 | +// active right now, or "" when none is. | |
| 134 | +// | |
| 135 | +// It comes first because a server installed into the project's own environment | |
| 136 | +// is the most specific answer available, and because it is the one that stops | |
| 137 | +// being true when the user deactivates. | |
| 138 | +func VirtualEnvBinDir() string { | |
| 139 | + env := os.Getenv("VIRTUAL_ENV") | |
| 140 | + if env == "" { | |
| 141 | + return "" | |
| 142 | + } | |
| 143 | + return filepath.Join(env, "bin") | |
| 144 | +} | |
| 145 | + | |
| 146 | +// UserBinDir returns ~/.local/bin, where pipx, `uv tool install` and `pip | |
| 147 | +// install --user` on Linux all put an executable. | |
| 148 | +// | |
| 149 | +// It is the directory the install hint's command writes into, so it is the one | |
| 150 | +// that matters most to somebody who followed the hint and found nothing. | |
| 151 | +func UserBinDir() string { | |
| 152 | + home, err := os.UserHomeDir() | |
| 153 | + if err != nil { | |
| 154 | + return "" | |
| 155 | + } | |
| 156 | + return filepath.Join(home, ".local", "bin") | |
| 157 | +} | |
| 158 | + | |
| 159 | +// PyenvShimDir returns pyenv's shim directory: PYENV_ROOT/shims when PYENV_ROOT | |
| 160 | +// is set, and ~/.pyenv/shims otherwise. | |
| 161 | +// | |
| 162 | +// pyenv works by putting shims on PATH, so this only matters on a machine where | |
| 163 | +// its shell hook was never installed — which is exactly the machine where the | |
| 164 | +// user cannot work out why nothing is found. | |
| 165 | +func PyenvShimDir() string { | |
| 166 | + if root := os.Getenv("PYENV_ROOT"); root != "" { | |
| 167 | + return filepath.Join(root, "shims") | |
| 168 | + } | |
| 169 | + home, err := os.UserHomeDir() | |
| 170 | + if err != nil { | |
| 171 | + return "" | |
| 172 | + } | |
| 173 | + return filepath.Join(home, ".pyenv", "shims") | |
| 174 | +} | |
| 175 | + | |
| 176 | +// FrameworkScriptDirs returns every ~/Library/Python/<version>/bin that exists, | |
| 177 | +// in the order the directory lists them — by name, which is not version order. | |
| 178 | +// | |
| 179 | +// That is where `pip install --user` puts an executable on macOS, and it is on | |
| 180 | +// nobody's PATH by default — so a Mac user who installed the server the obvious | |
| 181 | +// way has it in a directory the shell has never heard of. The version is part | |
| 182 | +// of the path and cannot be predicted, so the directory is read rather than | |
| 183 | +// guessed; on a system with no such directory this returns nothing, which is | |
| 184 | +// what happens on Linux. | |
| 185 | +func FrameworkScriptDirs() []string { | |
| 186 | + home, err := os.UserHomeDir() | |
| 187 | + if err != nil { | |
| 188 | + return nil | |
| 189 | + } | |
| 190 | + | |
| 191 | + versions, err := os.ReadDir(filepath.Join(home, "Library", "Python")) | |
| 192 | + if err != nil { | |
| 193 | + return nil | |
| 194 | + } | |
| 195 | + | |
| 196 | + var dirs []string | |
| 197 | + for _, version := range versions { | |
| 198 | + if !version.IsDir() { | |
| 199 | + continue | |
| 200 | + } | |
| 201 | + dirs = append(dirs, filepath.Join(home, "Library", "Python", version.Name(), "bin")) | |
| 202 | + } | |
| 203 | + return dirs | |
| 204 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,204 @@ | |||
| 1 | +// Package pythonlang is everything about Turbo Python that is about *Python*: | ||
| 2 | +// how the editor names itself, which language server it talks to, what a | ||
| 3 | +// project's starter files say, and how Python source is coloured. | ||
| 4 | +// | ||
| 5 | +// Everything else the editor does lives in turbo-core, which knows nothing | ||
| 6 | +// about Python. This package is the whole of the difference between Turbo | ||
| 7 | +// Python and Turbo Rust, which is what makes a fourth editor a matter of | ||
| 8 | +// writing one of these rather than forking anything. | ||
| 9 | +// | ||
| 10 | +// pythonlang.Register() // teach the library to colour Python | ||
| 11 | +// editor := app.New(screen, name, pythonlang.Profile()) | ||
| 12 | +package pythonlang | ||
| 13 | + | ||
| 14 | +import ( | ||
| 15 | + "os" | ||
| 16 | + "path/filepath" | ||
| 17 | + | ||
| 18 | + "rickub.com/turbo-editors/turbo-core/profile" | ||
| 19 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 20 | +) | ||
| 21 | + | ||
| 22 | +// Name and Slug are what the editor calls itself. The slug is also its binary, | ||
| 23 | +// its project directory (as .turbo-python) and the stem of its environment | ||
| 24 | +// variables (as TURBO_PYTHON_…), so it is not free to change. | ||
| 25 | +const ( | ||
| 26 | + Name = "Turbo Python" | ||
| 27 | + Slug = "turbo-python" | ||
| 28 | +) | ||
| 29 | + | ||
| 30 | +// Language is the name Python is known by: the value LanguageOf returns for a | ||
| 31 | +// .py file, and what a snippets file writes in its languages key. | ||
| 32 | +const Language syntax.Language = "python" | ||
| 33 | + | ||
| 34 | +// ServerCommand is the language server Turbo Python talks to, and InstallHint | ||
| 35 | +// the single command that installs it. | ||
| 36 | +// | ||
| 37 | +// python-lsp-server answers seven of the nine questions turbo-core asks — | ||
| 38 | +// completion, hover, definition, type definition, references and the file's | ||
| 39 | +// symbols — and publishes diagnostics unasked. It advertises neither | ||
| 40 | +// implementations nor a project-wide symbol search, so those two items report | ||
| 41 | +// nothing found; that is documented rather than worked around. | ||
| 42 | +// | ||
| 43 | +// **The [all] is not optional.** Installed bare, pylsp starts, completes and | ||
| 44 | +// jumps, and publishes an *empty* list of diagnostics for a file that does not | ||
| 45 | +// parse — because the linters that produce them are extras, and without them | ||
| 46 | +// the server has nothing to say. An editor whose gutter stays blank because | ||
| 47 | +// the server has no linter looks exactly like one whose gutter is blank | ||
| 48 | +// because the code is fine, which is why the hint installs them. | ||
| 49 | +// | ||
| 50 | +// pipx is named rather than pip because the server is a tool rather than a | ||
| 51 | +// dependency of the project being edited, and installing it into that | ||
| 52 | +// project's environment is how it ends up missing from the next one. | ||
| 53 | +const ( | ||
| 54 | + ServerCommand = "pylsp" | ||
| 55 | + InstallHint = `pipx install "python-lsp-server[all]"` | ||
| 56 | +) | ||
| 57 | + | ||
| 58 | +// Profile returns the editor Turbo Python is. | ||
| 59 | +// | ||
| 60 | +// It is a function rather than a variable because Server.Dirs is worked out | ||
| 61 | +// from the environment, and a variable would freeze whatever VIRTUAL_ENV said | ||
| 62 | +// when the package was linked — which for a Python tool is the one value most | ||
| 63 | +// likely to change between two runs in the same shell. | ||
| 64 | +func Profile() profile.Profile { | ||
| 65 | + return profile.Profile{ | ||
| 66 | + Name: Name, | ||
| 67 | + Slug: Slug, | ||
| 68 | + Language: "Python", | ||
| 69 | + // P is free: the fixed menus take F, E, S, R, C, O, W, N and H, so the | ||
| 70 | + // hot key lands on the first letter of the word, which is the reading | ||
| 71 | + // that costs nobody a second glance. The menu is named after the | ||
| 72 | + // language and not after uv, because it holds whatever the project put | ||
| 73 | + // in its tools file — and the first tools file anybody writes outgrows | ||
| 74 | + // the language's own toolchain. | ||
| 75 | + ToolsMenu: "~P~ython", | ||
| 76 | + // pyproject.toml first because it is where a modern project declares | ||
| 77 | + // itself, then the two forms a setuptools project used before it | ||
| 78 | + // existed. The nearest one going up is the directory the server is | ||
| 79 | + // started in. | ||
| 80 | + RootMarkers: []string{"pyproject.toml", "setup.py", "setup.cfg"}, | ||
| 81 | + Server: profile.Server{ | ||
| 82 | + Command: ServerCommand, | ||
| 83 | + // pylsp takes no subcommand, unlike gopls. | ||
| 84 | + Args: nil, | ||
| 85 | + InstallHint: InstallHint, | ||
| 86 | + Dirs: ServerDirs(), | ||
| 87 | + }, | ||
| 88 | + Templates: profile.Templates{ | ||
| 89 | + Settings: settingsTemplate, | ||
| 90 | + Snippets: snippetsTemplate, | ||
| 91 | + Tools: toolsTemplate, | ||
| 92 | + Agents: agentsTemplate, | ||
| 93 | + }, | ||
| 94 | + } | ||
| 95 | +} | ||
| 96 | + | ||
| 97 | +// Register teaches turbo-core to colour Python. | ||
| 98 | +// | ||
| 99 | +// It is called explicitly at start-up rather than from an init function so that | ||
| 100 | +// "which languages does this editor know?" is answered by reading main, not by | ||
| 101 | +// working out which packages were imported. | ||
| 102 | +func Register() { | ||
| 103 | + syntax.Register(syntax.Definition{ | ||
| 104 | + Language: Language, | ||
| 105 | + // .pyw is Windows' "run me without a console window"; .pyi is a stub | ||
| 106 | + // file, which is Python and nothing else. | ||
| 107 | + Extensions: []string{".py", ".pyi", ".pyw"}, | ||
| 108 | + // A Python script with no extension at all is an ordinary thing to | ||
| 109 | + // find in a bin directory, and its first line says what it is. | ||
| 110 | + Shebangs: []string{"python", "python3"}, | ||
| 111 | + Highlight: Highlight, | ||
| 112 | + }) | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +// ServerDirs returns the directories pylsp is looked for in after PATH, most | ||
| 116 | +// specific first. | ||
| 117 | +// | ||
| 118 | +// "Completion silently does nothing" is what a user sees when the editor cannot | ||
| 119 | +// find a server they believe they installed, and Python has more places to | ||
| 120 | +// install one than most languages: an environment belonging to this project, a | ||
| 121 | +// tool directory belonging to this user, a pyenv shim, and — on macOS — a | ||
| 122 | +// per-version directory under the user's Library that is on nobody's PATH by | ||
| 123 | +// default. | ||
| 124 | +// | ||
| 125 | +// Empty entries are skipped by the library, so a machine with no pyenv and no | ||
| 126 | +// active environment simply contributes nothing here. | ||
| 127 | +func ServerDirs() []string { | ||
| 128 | + dirs := []string{VirtualEnvBinDir(), UserBinDir(), PyenvShimDir()} | ||
| 129 | + return append(dirs, FrameworkScriptDirs()...) | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +// VirtualEnvBinDir returns the bin directory of the virtual environment that is | ||
| 133 | +// active right now, or "" when none is. | ||
| 134 | +// | ||
| 135 | +// It comes first because a server installed into the project's own environment | ||
| 136 | +// is the most specific answer available, and because it is the one that stops | ||
| 137 | +// being true when the user deactivates. | ||
| 138 | +func VirtualEnvBinDir() string { | ||
| 139 | + env := os.Getenv("VIRTUAL_ENV") | ||
| 140 | + if env == "" { | ||
| 141 | + return "" | ||
| 142 | + } | ||
| 143 | + return filepath.Join(env, "bin") | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +// UserBinDir returns ~/.local/bin, where pipx, `uv tool install` and `pip | ||
| 147 | +// install --user` on Linux all put an executable. | ||
| 148 | +// | ||
| 149 | +// It is the directory the install hint's command writes into, so it is the one | ||
| 150 | +// that matters most to somebody who followed the hint and found nothing. | ||
| 151 | +func UserBinDir() string { | ||
| 152 | + home, err := os.UserHomeDir() | ||
| 153 | + if err != nil { | ||
| 154 | + return "" | ||
| 155 | + } | ||
| 156 | + return filepath.Join(home, ".local", "bin") | ||
| 157 | +} | ||
| 158 | + | ||
| 159 | +// PyenvShimDir returns pyenv's shim directory: PYENV_ROOT/shims when PYENV_ROOT | ||
| 160 | +// is set, and ~/.pyenv/shims otherwise. | ||
| 161 | +// | ||
| 162 | +// pyenv works by putting shims on PATH, so this only matters on a machine where | ||
| 163 | +// its shell hook was never installed — which is exactly the machine where the | ||
| 164 | +// user cannot work out why nothing is found. | ||
| 165 | +func PyenvShimDir() string { | ||
| 166 | + if root := os.Getenv("PYENV_ROOT"); root != "" { | ||
| 167 | + return filepath.Join(root, "shims") | ||
| 168 | + } | ||
| 169 | + home, err := os.UserHomeDir() | ||
| 170 | + if err != nil { | ||
| 171 | + return "" | ||
| 172 | + } | ||
| 173 | + return filepath.Join(home, ".pyenv", "shims") | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +// FrameworkScriptDirs returns every ~/Library/Python/<version>/bin that exists, | ||
| 177 | +// in the order the directory lists them — by name, which is not version order. | ||
| 178 | +// | ||
| 179 | +// That is where `pip install --user` puts an executable on macOS, and it is on | ||
| 180 | +// nobody's PATH by default — so a Mac user who installed the server the obvious | ||
| 181 | +// way has it in a directory the shell has never heard of. The version is part | ||
| 182 | +// of the path and cannot be predicted, so the directory is read rather than | ||
| 183 | +// guessed; on a system with no such directory this returns nothing, which is | ||
| 184 | +// what happens on Linux. | ||
| 185 | +func FrameworkScriptDirs() []string { | ||
| 186 | + home, err := os.UserHomeDir() | ||
| 187 | + if err != nil { | ||
| 188 | + return nil | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + versions, err := os.ReadDir(filepath.Join(home, "Library", "Python")) | ||
| 192 | + if err != nil { | ||
| 193 | + return nil | ||
| 194 | + } | ||
| 195 | + | ||
| 196 | + var dirs []string | ||
| 197 | + for _, version := range versions { | ||
| 198 | + if !version.IsDir() { | ||
| 199 | + continue | ||
| 200 | + } | ||
| 201 | + dirs = append(dirs, filepath.Join(home, "Library", "Python", version.Name(), "bin")) | ||
| 202 | + } | ||
| 203 | + return dirs | ||
| 204 | +} | ||
added
internal/pythonlang/reference_test.go +90 -0 | new file mode 100644 | ||
| @@ -0,0 +1,90 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + "testing" | |
| 6 | + | |
| 7 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 8 | +) | |
| 9 | + | |
| 10 | +// TestTheLanguagesReferenceIsTrue holds docs/*/reference/languages.md to the | |
| 11 | +// scanner. Every row of its Python table that no other test here covers is | |
| 12 | +// checked, so a reference claim and the code cannot drift apart quietly. | |
| 13 | +// | |
| 14 | +// The last three cases document *limitations* rather than features — an | |
| 15 | +// all-capital class name read as a constant, `type` read as the builtin rather | |
| 16 | +// than as a soft keyword, an f-string's braces left inside the string. The | |
| 17 | +// reference says each of those in so many words, and these rows are what stops | |
| 18 | +// somebody "fixing" one without also fixing the sentence. | |
| 19 | +func TestTheLanguagesReferenceIsTrue(t *testing.T) { | |
| 20 | + tests := []struct { | |
| 21 | + src string | |
| 22 | + word string | |
| 23 | + want syntax.Class | |
| 24 | + }{ | |
| 25 | + {"assert x is not None", "assert", syntax.ClassKeyword}, | |
| 26 | + {"nonlocal counter", "nonlocal", syntax.ClassKeyword}, | |
| 27 | + {"async def f() -> None:\n pass\n", "async", syntax.ClassKeyword}, | |
| 28 | + {"x = NotImplemented", "NotImplemented", syntax.ClassConstant}, | |
| 29 | + {"x = Ellipsis", "Ellipsis", syntax.ClassConstant}, | |
| 30 | + {"if __debug__:\n pass\n", "__debug__", syntax.ClassConstant}, | |
| 31 | + {"x: frozenset = frozenset()", "frozenset", syntax.ClassType}, | |
| 32 | + {"x: memoryview = m", "memoryview", syntax.ClassType}, | |
| 33 | + {"x = isinstance(v, int)", "isinstance", syntax.ClassBuiltin}, | |
| 34 | + {"x = sorted(v)", "sorted", syntax.ClassBuiltin}, | |
| 35 | + {"def f(cls) -> None:\n pass\n", "cls", syntax.ClassBuiltin}, | |
| 36 | + {"x = obj.__name__", "__name__", syntax.ClassBuiltin}, | |
| 37 | + {`x = rb"raw bytes"`, `rb"raw bytes"`, syntax.ClassString}, | |
| 38 | + {`x = BR"raw bytes"`, `BR"raw bytes"`, syntax.ClassString}, | |
| 39 | + {`x = u"text"`, `u"text"`, syntax.ClassString}, | |
| 40 | + {"x = 0o17", "0o17", syntax.ClassNumber}, | |
| 41 | + {"x = 0b1010", "0b1010", syntax.ClassNumber}, | |
| 42 | + {"x = 3j", "3j", syntax.ClassNumber}, | |
| 43 | + {"x = 1E+7", "1E+7", syntax.ClassNumber}, | |
| 44 | + {"#!/usr/bin/env python3", "#!/usr/bin/env python3", syntax.ClassComment}, | |
| 45 | + {"@property\ndef x(self):\n pass\n", "@property", syntax.ClassAttribute}, | |
| 46 | + {"if (n := f()) > 1:\n pass\n", ":=", syntax.ClassOperator}, | |
| 47 | + {"d = {1: 2}", ":", syntax.ClassPunctuation}, | |
| 48 | + {"x = a @ b", "@", syntax.ClassOperator}, | |
| 49 | + {"x = 1 + \\", "\\", syntax.ClassPunctuation}, | |
| 50 | + {"x = [1, 2]", "[", syntax.ClassPunctuation}, | |
| 51 | + | |
| 52 | + // The documented limitations. | |
| 53 | + {"HTTP = 1", "HTTP", syntax.ClassConstant}, | |
| 54 | + {"type Alias = int", "type", syntax.ClassType}, | |
| 55 | + {"match value: # dispatch\n", "match", syntax.ClassIdentifier}, | |
| 56 | + } | |
| 57 | + | |
| 58 | + for _, test := range tests { | |
| 59 | + t.Run(test.word, func(t *testing.T) { | |
| 60 | + index := strings.Index(test.src, test.word) | |
| 61 | + if index < 0 { | |
| 62 | + t.Fatalf("%q not in %q", test.word, test.src) | |
| 63 | + } | |
| 64 | + got, ok := classAt(Highlight(test.src), 0, index) | |
| 65 | + if !ok || got != test.want { | |
| 66 | + t.Errorf("%q in %q is %v (covered %v), want %v", test.word, test.src, got, ok, test.want) | |
| 67 | + } | |
| 68 | + }) | |
| 69 | + } | |
| 70 | +} | |
| 71 | + | |
| 72 | +// The reference's Python table says the class `char` is produced by nothing | |
| 73 | +// here, because Python has no character type. That is a claim about every span | |
| 74 | +// the scanner can ever emit, so it is checked over a file that uses every | |
| 75 | +// construct the table names. | |
| 76 | +func TestTheScannerNeverProducesACharacterClass(t *testing.T) { | |
| 77 | + const src = "#!/usr/bin/env python3\n" + | |
| 78 | + "x = 'single'\n" + | |
| 79 | + "y = \"double\"\n" + | |
| 80 | + "z = b'bytes'\n" + | |
| 81 | + "w = '''triple'''\n" | |
| 82 | + | |
| 83 | + for line, spans := range Highlight(src) { | |
| 84 | + for _, span := range spans { | |
| 85 | + if span.Class == syntax.ClassChar { | |
| 86 | + t.Errorf("line %d holds a char span at %d; Python has no character literal", line, span.Start) | |
| 87 | + } | |
| 88 | + } | |
| 89 | + } | |
| 90 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,90 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + "testing" | ||
| 6 | + | ||
| 7 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 8 | +) | ||
| 9 | + | ||
| 10 | +// TestTheLanguagesReferenceIsTrue holds docs/*/reference/languages.md to the | ||
| 11 | +// scanner. Every row of its Python table that no other test here covers is | ||
| 12 | +// checked, so a reference claim and the code cannot drift apart quietly. | ||
| 13 | +// | ||
| 14 | +// The last three cases document *limitations* rather than features — an | ||
| 15 | +// all-capital class name read as a constant, `type` read as the builtin rather | ||
| 16 | +// than as a soft keyword, an f-string's braces left inside the string. The | ||
| 17 | +// reference says each of those in so many words, and these rows are what stops | ||
| 18 | +// somebody "fixing" one without also fixing the sentence. | ||
| 19 | +func TestTheLanguagesReferenceIsTrue(t *testing.T) { | ||
| 20 | + tests := []struct { | ||
| 21 | + src string | ||
| 22 | + word string | ||
| 23 | + want syntax.Class | ||
| 24 | + }{ | ||
| 25 | + {"assert x is not None", "assert", syntax.ClassKeyword}, | ||
| 26 | + {"nonlocal counter", "nonlocal", syntax.ClassKeyword}, | ||
| 27 | + {"async def f() -> None:\n pass\n", "async", syntax.ClassKeyword}, | ||
| 28 | + {"x = NotImplemented", "NotImplemented", syntax.ClassConstant}, | ||
| 29 | + {"x = Ellipsis", "Ellipsis", syntax.ClassConstant}, | ||
| 30 | + {"if __debug__:\n pass\n", "__debug__", syntax.ClassConstant}, | ||
| 31 | + {"x: frozenset = frozenset()", "frozenset", syntax.ClassType}, | ||
| 32 | + {"x: memoryview = m", "memoryview", syntax.ClassType}, | ||
| 33 | + {"x = isinstance(v, int)", "isinstance", syntax.ClassBuiltin}, | ||
| 34 | + {"x = sorted(v)", "sorted", syntax.ClassBuiltin}, | ||
| 35 | + {"def f(cls) -> None:\n pass\n", "cls", syntax.ClassBuiltin}, | ||
| 36 | + {"x = obj.__name__", "__name__", syntax.ClassBuiltin}, | ||
| 37 | + {`x = rb"raw bytes"`, `rb"raw bytes"`, syntax.ClassString}, | ||
| 38 | + {`x = BR"raw bytes"`, `BR"raw bytes"`, syntax.ClassString}, | ||
| 39 | + {`x = u"text"`, `u"text"`, syntax.ClassString}, | ||
| 40 | + {"x = 0o17", "0o17", syntax.ClassNumber}, | ||
| 41 | + {"x = 0b1010", "0b1010", syntax.ClassNumber}, | ||
| 42 | + {"x = 3j", "3j", syntax.ClassNumber}, | ||
| 43 | + {"x = 1E+7", "1E+7", syntax.ClassNumber}, | ||
| 44 | + {"#!/usr/bin/env python3", "#!/usr/bin/env python3", syntax.ClassComment}, | ||
| 45 | + {"@property\ndef x(self):\n pass\n", "@property", syntax.ClassAttribute}, | ||
| 46 | + {"if (n := f()) > 1:\n pass\n", ":=", syntax.ClassOperator}, | ||
| 47 | + {"d = {1: 2}", ":", syntax.ClassPunctuation}, | ||
| 48 | + {"x = a @ b", "@", syntax.ClassOperator}, | ||
| 49 | + {"x = 1 + \\", "\\", syntax.ClassPunctuation}, | ||
| 50 | + {"x = [1, 2]", "[", syntax.ClassPunctuation}, | ||
| 51 | + | ||
| 52 | + // The documented limitations. | ||
| 53 | + {"HTTP = 1", "HTTP", syntax.ClassConstant}, | ||
| 54 | + {"type Alias = int", "type", syntax.ClassType}, | ||
| 55 | + {"match value: # dispatch\n", "match", syntax.ClassIdentifier}, | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + for _, test := range tests { | ||
| 59 | + t.Run(test.word, func(t *testing.T) { | ||
| 60 | + index := strings.Index(test.src, test.word) | ||
| 61 | + if index < 0 { | ||
| 62 | + t.Fatalf("%q not in %q", test.word, test.src) | ||
| 63 | + } | ||
| 64 | + got, ok := classAt(Highlight(test.src), 0, index) | ||
| 65 | + if !ok || got != test.want { | ||
| 66 | + t.Errorf("%q in %q is %v (covered %v), want %v", test.word, test.src, got, ok, test.want) | ||
| 67 | + } | ||
| 68 | + }) | ||
| 69 | + } | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +// The reference's Python table says the class `char` is produced by nothing | ||
| 73 | +// here, because Python has no character type. That is a claim about every span | ||
| 74 | +// the scanner can ever emit, so it is checked over a file that uses every | ||
| 75 | +// construct the table names. | ||
| 76 | +func TestTheScannerNeverProducesACharacterClass(t *testing.T) { | ||
| 77 | + const src = "#!/usr/bin/env python3\n" + | ||
| 78 | + "x = 'single'\n" + | ||
| 79 | + "y = \"double\"\n" + | ||
| 80 | + "z = b'bytes'\n" + | ||
| 81 | + "w = '''triple'''\n" | ||
| 82 | + | ||
| 83 | + for line, spans := range Highlight(src) { | ||
| 84 | + for _, span := range spans { | ||
| 85 | + if span.Class == syntax.ClassChar { | ||
| 86 | + t.Errorf("line %d holds a char span at %d; Python has no character literal", line, span.Start) | ||
| 87 | + } | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | +} | ||
added
internal/pythonlang/scan.go +182 -0 | new file mode 100644 | ||
| @@ -0,0 +1,182 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +import "rickub.com/turbo-editors/turbo-core/syntax" | |
| 4 | + | |
| 5 | +// carry is what a line of Python leaves open for the next one. | |
| 6 | +// | |
| 7 | +// Only one construct in Python crosses a line break, and it does so in two | |
| 8 | +// ways. A triple-quoted string runs until the matching three quotes, however | |
| 9 | +// many lines away that is. A single-quoted one runs on only when the line ends | |
| 10 | +// with a backslash, which escapes the newline — anything else that reaches the | |
| 11 | +// end of a line with a quote still open is broken source, and is coloured to | |
| 12 | +// the end of that line and dropped rather than painting the rest of the file. | |
| 13 | +// | |
| 14 | +// Which quote opened it has to be remembered rather than guessed: a literal | |
| 15 | +// opened with three double quotes and one opened with three apostrophes are | |
| 16 | +// different strings, and the closer of one appearing inside the other closes | |
| 17 | +// nothing. (Spelling those triples out in words is deliberate — gofmt rewrites | |
| 18 | +// a bare run of apostrophes in a doc comment into a typographic quote.) | |
| 19 | +// | |
| 20 | +// Rawness is deliberately *not* carried. `r"\""` is a complete string: in a raw | |
| 21 | +// string the backslash stays in the value, but it still stops the quote after | |
| 22 | +// it from ending the literal. Termination is therefore the same rule for both, | |
| 23 | +// and a flag saying otherwise would be a flag nothing reads. | |
| 24 | +type carry struct { | |
| 25 | + // open says a string ran past the end of a line. | |
| 26 | + open bool | |
| 27 | + // quote is the rune that opened it, ' or ". | |
| 28 | + quote rune | |
| 29 | + // triple says it was opened with three of them. | |
| 30 | + triple bool | |
| 31 | +} | |
| 32 | + | |
| 33 | +// Highlight colours Python source. | |
| 34 | +// | |
| 35 | +// It is written against syntax.LineScanner, a line at a time, with the one | |
| 36 | +// multi-line construct above threaded through carry. Python has no tokeniser in | |
| 37 | +// the Go standard library the way Go does, so this is a scanner in the same | |
| 38 | +// style as the ones turbo-core ships for TOML, Markdown and shell. | |
| 39 | +// | |
| 40 | +// It is deliberately tolerant of broken input: source under the cursor is | |
| 41 | +// invalid most of the time it is being typed, and a highlighter that gives up | |
| 42 | +// is a highlighter that flickers off. | |
| 43 | +func Highlight(src string) [][]syntax.Span { | |
| 44 | + return syntax.ScanLines(src, scanLine) | |
| 45 | +} | |
| 46 | + | |
| 47 | +// scanLine colours one line and returns what it leaves open. | |
| 48 | +func scanLine(line []rune, open carry) ([]syntax.Span, carry) { | |
| 49 | + s := syntax.NewLineScanner(line) | |
| 50 | + | |
| 51 | + // Whatever ran past the end of the previous line is finished first: until | |
| 52 | + // it closes, nothing on this line is code. | |
| 53 | + if open.open && !continueString(s, &open) { | |
| 54 | + return s.Spans(), open | |
| 55 | + } | |
| 56 | + | |
| 57 | + for !s.AtEnd() { | |
| 58 | + scanToken(s, &open) | |
| 59 | + } | |
| 60 | + return s.Spans(), open | |
| 61 | +} | |
| 62 | + | |
| 63 | +// scanToken colours whatever starts at the scanner's position. | |
| 64 | +func scanToken(s *syntax.LineScanner, open *carry) { | |
| 65 | + r := s.Peek(0) | |
| 66 | + | |
| 67 | + switch { | |
| 68 | + case r == ' ' || r == '\t': | |
| 69 | + s.SkipSpaces() | |
| 70 | + case r == '#': | |
| 71 | + // Python has no block comment. A run of # lines is a run of comments, | |
| 72 | + // and a """docstring""" is a string, which is what the language calls | |
| 73 | + // it and what `help()` reads back. | |
| 74 | + s.TakeRest(syntax.ClassComment) | |
| 75 | + case isStringStart(s): | |
| 76 | + // Before words, because f, r, b and u are letters: without this, | |
| 77 | + // f"{name}" would be an identifier followed by a string. | |
| 78 | + takeString(s, open) | |
| 79 | + case isDecoratorStart(s): | |
| 80 | + takeDecorator(s) | |
| 81 | + case syntax.IsDigit(r) || r == '.' && syntax.IsDigit(s.Peek(1)): | |
| 82 | + // .5 is a float, so a dot with a digit after it starts a number. A dot | |
| 83 | + // with anything else after it is an attribute access. | |
| 84 | + takeNumber(s) | |
| 85 | + case syntax.IsLetter(r) || r == '_': | |
| 86 | + takeWord(s) | |
| 87 | + case r == ':' && s.Peek(1) != '=': | |
| 88 | + // A colon opens a block, separates a dict's key from its value, cuts a | |
| 89 | + // slice and introduces an annotation: structure in every case, so it | |
| 90 | + // goes with the brackets and the commas rather than with the | |
| 91 | + // arithmetic. ":" is an operator rune, so this has to come first — and | |
| 92 | + // it has to let ":=" through, which really is an operator. | |
| 93 | + s.Take(1, syntax.ClassPunctuation) | |
| 94 | + case r == '@': | |
| 95 | + // Not a decorator, or the case above would have taken it: this is the | |
| 96 | + // matrix-multiplication operator. | |
| 97 | + s.Take(1, syntax.ClassOperator) | |
| 98 | + case r == '\\': | |
| 99 | + // A backslash at the end of a line joins it to the next one. It is | |
| 100 | + // structure rather than computation, and colouring it says that the | |
| 101 | + // line does not end where it looks like it ends. | |
| 102 | + s.Take(1, syntax.ClassPunctuation) | |
| 103 | + case syntax.IsOperatorRune(r): | |
| 104 | + s.TakeWhile(syntax.ClassOperator, syntax.IsOperatorRune) | |
| 105 | + case syntax.IsPunctuationRune(r): | |
| 106 | + s.Take(1, syntax.ClassPunctuation) | |
| 107 | + default: | |
| 108 | + // A rune nothing here claims — a currency sign in a comment-free line, | |
| 109 | + // an accented letter in an identifier — is stepped over uncoloured | |
| 110 | + // rather than guessed at. | |
| 111 | + s.Advance(1) | |
| 112 | + } | |
| 113 | +} | |
| 114 | + | |
| 115 | +// --- decorators ------------------------------------------------------------- | |
| 116 | + | |
| 117 | +// isDecoratorStart reports whether a decorator opens at the scanner's position. | |
| 118 | +// | |
| 119 | +// The same rune is Python's matrix-multiplication operator, and the two are | |
| 120 | +// told apart by where they are: a decorator is the first thing on its line. | |
| 121 | +func isDecoratorStart(s *syntax.LineScanner) bool { | |
| 122 | + if s.Peek(0) != '@' || !atLineStart(s) { | |
| 123 | + return false | |
| 124 | + } | |
| 125 | + next := s.Peek(1) | |
| 126 | + return syntax.IsLetter(next) || next == '_' | |
| 127 | +} | |
| 128 | + | |
| 129 | +// takeDecorator colours @property and the dotted name of @app.route. | |
| 130 | +// | |
| 131 | +// It stops at the opening parenthesis rather than swallowing to the end of the | |
| 132 | +// line: the arguments of @pytest.mark.parametrize("n", [1, 2]) are ordinary | |
| 133 | +// Python, and colouring them as part of the decorator would hide a string and a | |
| 134 | +// list inside one flat run. | |
| 135 | +func takeDecorator(s *syntax.LineScanner) { | |
| 136 | + start := s.Pos() | |
| 137 | + s.Advance(1) // the @ | |
| 138 | + | |
| 139 | + for !s.AtEnd() && (syntax.IsWordRune(s.Peek(0)) || s.Peek(0) == '.') { | |
| 140 | + s.Advance(1) | |
| 141 | + } | |
| 142 | + s.Emit(start, s.Pos(), syntax.ClassAttribute) | |
| 143 | +} | |
| 144 | + | |
| 145 | +// --- where we are on the line ----------------------------------------------- | |
| 146 | + | |
| 147 | +// atLineStart reports whether nothing but indentation comes before the | |
| 148 | +// scanner's position. | |
| 149 | +// | |
| 150 | +// Two decisions need it: a decorator is the first thing on its line, and so is | |
| 151 | +// the soft keyword that opens a match statement. | |
| 152 | +func atLineStart(s *syntax.LineScanner) bool { | |
| 153 | + for at := -1; s.Pos()+at >= 0; at-- { | |
| 154 | + if r := s.Peek(at); r != ' ' && r != '\t' { | |
| 155 | + return false | |
| 156 | + } | |
| 157 | + } | |
| 158 | + return true | |
| 159 | +} | |
| 160 | + | |
| 161 | +// lineEndsWithColon reports whether the last thing on the line is the colon | |
| 162 | +// that opens a block. | |
| 163 | +// | |
| 164 | +// It reads backwards from the end of the line, which is what makes it cheap | |
| 165 | +// enough to ask about every word — and also what gives it its one boundary: a | |
| 166 | +// trailing comment hides the colon from it, so `match x: # dispatch` colours | |
| 167 | +// match as an identifier. That is the safe direction to be wrong in, and it is | |
| 168 | +// documented rather than fixed, because telling a real trailing comment from a | |
| 169 | +// # inside a string means scanning the line forwards, which is the work this | |
| 170 | +// question is meant to avoid. | |
| 171 | +func lineEndsWithColon(s *syntax.LineScanner) bool { | |
| 172 | + for at := s.Len() - s.Pos() - 1; at >= -s.Pos(); at-- { | |
| 173 | + switch r := s.Peek(at); r { | |
| 174 | + case ' ', '\t': | |
| 175 | + case ':': | |
| 176 | + return true | |
| 177 | + default: | |
| 178 | + return false | |
| 179 | + } | |
| 180 | + } | |
| 181 | + return false | |
| 182 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,182 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +import "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 4 | + | ||
| 5 | +// carry is what a line of Python leaves open for the next one. | ||
| 6 | +// | ||
| 7 | +// Only one construct in Python crosses a line break, and it does so in two | ||
| 8 | +// ways. A triple-quoted string runs until the matching three quotes, however | ||
| 9 | +// many lines away that is. A single-quoted one runs on only when the line ends | ||
| 10 | +// with a backslash, which escapes the newline — anything else that reaches the | ||
| 11 | +// end of a line with a quote still open is broken source, and is coloured to | ||
| 12 | +// the end of that line and dropped rather than painting the rest of the file. | ||
| 13 | +// | ||
| 14 | +// Which quote opened it has to be remembered rather than guessed: a literal | ||
| 15 | +// opened with three double quotes and one opened with three apostrophes are | ||
| 16 | +// different strings, and the closer of one appearing inside the other closes | ||
| 17 | +// nothing. (Spelling those triples out in words is deliberate — gofmt rewrites | ||
| 18 | +// a bare run of apostrophes in a doc comment into a typographic quote.) | ||
| 19 | +// | ||
| 20 | +// Rawness is deliberately *not* carried. `r"\""` is a complete string: in a raw | ||
| 21 | +// string the backslash stays in the value, but it still stops the quote after | ||
| 22 | +// it from ending the literal. Termination is therefore the same rule for both, | ||
| 23 | +// and a flag saying otherwise would be a flag nothing reads. | ||
| 24 | +type carry struct { | ||
| 25 | + // open says a string ran past the end of a line. | ||
| 26 | + open bool | ||
| 27 | + // quote is the rune that opened it, ' or ". | ||
| 28 | + quote rune | ||
| 29 | + // triple says it was opened with three of them. | ||
| 30 | + triple bool | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +// Highlight colours Python source. | ||
| 34 | +// | ||
| 35 | +// It is written against syntax.LineScanner, a line at a time, with the one | ||
| 36 | +// multi-line construct above threaded through carry. Python has no tokeniser in | ||
| 37 | +// the Go standard library the way Go does, so this is a scanner in the same | ||
| 38 | +// style as the ones turbo-core ships for TOML, Markdown and shell. | ||
| 39 | +// | ||
| 40 | +// It is deliberately tolerant of broken input: source under the cursor is | ||
| 41 | +// invalid most of the time it is being typed, and a highlighter that gives up | ||
| 42 | +// is a highlighter that flickers off. | ||
| 43 | +func Highlight(src string) [][]syntax.Span { | ||
| 44 | + return syntax.ScanLines(src, scanLine) | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +// scanLine colours one line and returns what it leaves open. | ||
| 48 | +func scanLine(line []rune, open carry) ([]syntax.Span, carry) { | ||
| 49 | + s := syntax.NewLineScanner(line) | ||
| 50 | + | ||
| 51 | + // Whatever ran past the end of the previous line is finished first: until | ||
| 52 | + // it closes, nothing on this line is code. | ||
| 53 | + if open.open && !continueString(s, &open) { | ||
| 54 | + return s.Spans(), open | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + for !s.AtEnd() { | ||
| 58 | + scanToken(s, &open) | ||
| 59 | + } | ||
| 60 | + return s.Spans(), open | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +// scanToken colours whatever starts at the scanner's position. | ||
| 64 | +func scanToken(s *syntax.LineScanner, open *carry) { | ||
| 65 | + r := s.Peek(0) | ||
| 66 | + | ||
| 67 | + switch { | ||
| 68 | + case r == ' ' || r == '\t': | ||
| 69 | + s.SkipSpaces() | ||
| 70 | + case r == '#': | ||
| 71 | + // Python has no block comment. A run of # lines is a run of comments, | ||
| 72 | + // and a """docstring""" is a string, which is what the language calls | ||
| 73 | + // it and what `help()` reads back. | ||
| 74 | + s.TakeRest(syntax.ClassComment) | ||
| 75 | + case isStringStart(s): | ||
| 76 | + // Before words, because f, r, b and u are letters: without this, | ||
| 77 | + // f"{name}" would be an identifier followed by a string. | ||
| 78 | + takeString(s, open) | ||
| 79 | + case isDecoratorStart(s): | ||
| 80 | + takeDecorator(s) | ||
| 81 | + case syntax.IsDigit(r) || r == '.' && syntax.IsDigit(s.Peek(1)): | ||
| 82 | + // .5 is a float, so a dot with a digit after it starts a number. A dot | ||
| 83 | + // with anything else after it is an attribute access. | ||
| 84 | + takeNumber(s) | ||
| 85 | + case syntax.IsLetter(r) || r == '_': | ||
| 86 | + takeWord(s) | ||
| 87 | + case r == ':' && s.Peek(1) != '=': | ||
| 88 | + // A colon opens a block, separates a dict's key from its value, cuts a | ||
| 89 | + // slice and introduces an annotation: structure in every case, so it | ||
| 90 | + // goes with the brackets and the commas rather than with the | ||
| 91 | + // arithmetic. ":" is an operator rune, so this has to come first — and | ||
| 92 | + // it has to let ":=" through, which really is an operator. | ||
| 93 | + s.Take(1, syntax.ClassPunctuation) | ||
| 94 | + case r == '@': | ||
| 95 | + // Not a decorator, or the case above would have taken it: this is the | ||
| 96 | + // matrix-multiplication operator. | ||
| 97 | + s.Take(1, syntax.ClassOperator) | ||
| 98 | + case r == '\\': | ||
| 99 | + // A backslash at the end of a line joins it to the next one. It is | ||
| 100 | + // structure rather than computation, and colouring it says that the | ||
| 101 | + // line does not end where it looks like it ends. | ||
| 102 | + s.Take(1, syntax.ClassPunctuation) | ||
| 103 | + case syntax.IsOperatorRune(r): | ||
| 104 | + s.TakeWhile(syntax.ClassOperator, syntax.IsOperatorRune) | ||
| 105 | + case syntax.IsPunctuationRune(r): | ||
| 106 | + s.Take(1, syntax.ClassPunctuation) | ||
| 107 | + default: | ||
| 108 | + // A rune nothing here claims — a currency sign in a comment-free line, | ||
| 109 | + // an accented letter in an identifier — is stepped over uncoloured | ||
| 110 | + // rather than guessed at. | ||
| 111 | + s.Advance(1) | ||
| 112 | + } | ||
| 113 | +} | ||
| 114 | + | ||
| 115 | +// --- decorators ------------------------------------------------------------- | ||
| 116 | + | ||
| 117 | +// isDecoratorStart reports whether a decorator opens at the scanner's position. | ||
| 118 | +// | ||
| 119 | +// The same rune is Python's matrix-multiplication operator, and the two are | ||
| 120 | +// told apart by where they are: a decorator is the first thing on its line. | ||
| 121 | +func isDecoratorStart(s *syntax.LineScanner) bool { | ||
| 122 | + if s.Peek(0) != '@' || !atLineStart(s) { | ||
| 123 | + return false | ||
| 124 | + } | ||
| 125 | + next := s.Peek(1) | ||
| 126 | + return syntax.IsLetter(next) || next == '_' | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +// takeDecorator colours @property and the dotted name of @app.route. | ||
| 130 | +// | ||
| 131 | +// It stops at the opening parenthesis rather than swallowing to the end of the | ||
| 132 | +// line: the arguments of @pytest.mark.parametrize("n", [1, 2]) are ordinary | ||
| 133 | +// Python, and colouring them as part of the decorator would hide a string and a | ||
| 134 | +// list inside one flat run. | ||
| 135 | +func takeDecorator(s *syntax.LineScanner) { | ||
| 136 | + start := s.Pos() | ||
| 137 | + s.Advance(1) // the @ | ||
| 138 | + | ||
| 139 | + for !s.AtEnd() && (syntax.IsWordRune(s.Peek(0)) || s.Peek(0) == '.') { | ||
| 140 | + s.Advance(1) | ||
| 141 | + } | ||
| 142 | + s.Emit(start, s.Pos(), syntax.ClassAttribute) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +// --- where we are on the line ----------------------------------------------- | ||
| 146 | + | ||
| 147 | +// atLineStart reports whether nothing but indentation comes before the | ||
| 148 | +// scanner's position. | ||
| 149 | +// | ||
| 150 | +// Two decisions need it: a decorator is the first thing on its line, and so is | ||
| 151 | +// the soft keyword that opens a match statement. | ||
| 152 | +func atLineStart(s *syntax.LineScanner) bool { | ||
| 153 | + for at := -1; s.Pos()+at >= 0; at-- { | ||
| 154 | + if r := s.Peek(at); r != ' ' && r != '\t' { | ||
| 155 | + return false | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | + return true | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +// lineEndsWithColon reports whether the last thing on the line is the colon | ||
| 162 | +// that opens a block. | ||
| 163 | +// | ||
| 164 | +// It reads backwards from the end of the line, which is what makes it cheap | ||
| 165 | +// enough to ask about every word — and also what gives it its one boundary: a | ||
| 166 | +// trailing comment hides the colon from it, so `match x: # dispatch` colours | ||
| 167 | +// match as an identifier. That is the safe direction to be wrong in, and it is | ||
| 168 | +// documented rather than fixed, because telling a real trailing comment from a | ||
| 169 | +// # inside a string means scanning the line forwards, which is the work this | ||
| 170 | +// question is meant to avoid. | ||
| 171 | +func lineEndsWithColon(s *syntax.LineScanner) bool { | ||
| 172 | + for at := s.Len() - s.Pos() - 1; at >= -s.Pos(); at-- { | ||
| 173 | + switch r := s.Peek(at); r { | ||
| 174 | + case ' ', '\t': | ||
| 175 | + case ':': | ||
| 176 | + return true | ||
| 177 | + default: | ||
| 178 | + return false | ||
| 179 | + } | ||
| 180 | + } | ||
| 181 | + return false | ||
| 182 | +} | ||
added
internal/pythonlang/scan_test.go +627 -0 | new file mode 100644 | ||
| @@ -0,0 +1,627 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + "testing" | |
| 6 | + | |
| 7 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 8 | +) | |
| 9 | + | |
| 10 | +// classAt returns the class covering a rune column on a line, and whether any | |
| 11 | +// span covers it at all. It is how nearly every test below asks its question. | |
| 12 | +func classAt(spans [][]syntax.Span, line, col int) (syntax.Class, bool) { | |
| 13 | + if line < 0 || line >= len(spans) { | |
| 14 | + return 0, false | |
| 15 | + } | |
| 16 | + for _, s := range spans[line] { | |
| 17 | + if col >= s.Start && col < s.End { | |
| 18 | + return s.Class, true | |
| 19 | + } | |
| 20 | + } | |
| 21 | + return 0, false | |
| 22 | +} | |
| 23 | + | |
| 24 | +// classOfFirst returns the class of the first occurrence of word in src. | |
| 25 | +func classOfFirst(t *testing.T, src, word string) syntax.Class { | |
| 26 | + t.Helper() | |
| 27 | + | |
| 28 | + index := strings.Index(src, word) | |
| 29 | + if index < 0 { | |
| 30 | + t.Fatalf("%q does not appear in the source", word) | |
| 31 | + } | |
| 32 | + line := strings.Count(src[:index], "\n") | |
| 33 | + col := index - (strings.LastIndex(src[:index], "\n") + 1) | |
| 34 | + | |
| 35 | + class, ok := classAt(Highlight(src), line, col) | |
| 36 | + if !ok { | |
| 37 | + t.Fatalf("no span covers %q at line %d column %d", word, line, col) | |
| 38 | + } | |
| 39 | + return class | |
| 40 | +} | |
| 41 | + | |
| 42 | +// spanOfFirst returns the span covering the first occurrence of word, so that a | |
| 43 | +// test can check where a construct *ends* and not only what colour it is. | |
| 44 | +func spanOfFirst(t *testing.T, src, word string) syntax.Span { | |
| 45 | + t.Helper() | |
| 46 | + | |
| 47 | + index := strings.Index(src, word) | |
| 48 | + if index < 0 { | |
| 49 | + t.Fatalf("%q does not appear in the source", word) | |
| 50 | + } | |
| 51 | + line := strings.Count(src[:index], "\n") | |
| 52 | + col := index - (strings.LastIndex(src[:index], "\n") + 1) | |
| 53 | + | |
| 54 | + for _, s := range Highlight(src)[line] { | |
| 55 | + if col >= s.Start && col < s.End { | |
| 56 | + return s | |
| 57 | + } | |
| 58 | + } | |
| 59 | + t.Fatalf("no span covers %q at line %d column %d", word, line, col) | |
| 60 | + return syntax.Span{} | |
| 61 | +} | |
| 62 | + | |
| 63 | +// --- the three invariants the editor relies on ------------------------------ | |
| 64 | + | |
| 65 | +func TestHighlightReturnsOneEntryPerLine(t *testing.T) { | |
| 66 | + // The editor indexes the result by line number without checking, so a short | |
| 67 | + // result is an index out of range in the middle of a redraw. | |
| 68 | + tests := []struct { | |
| 69 | + name string | |
| 70 | + src string | |
| 71 | + want int | |
| 72 | + }{ | |
| 73 | + {"empty", "", 1}, | |
| 74 | + {"one line without a terminator", "x = 1", 1}, | |
| 75 | + {"one line with a terminator", "x = 1\n", 2}, | |
| 76 | + {"three lines", "a\nb\nc", 3}, | |
| 77 | + {"an unterminated triple quote", `x = """a` + "\nb\nc", 3}, | |
| 78 | + } | |
| 79 | + | |
| 80 | + for _, tc := range tests { | |
| 81 | + t.Run(tc.name, func(t *testing.T) { | |
| 82 | + if got := len(Highlight(tc.src)); got != tc.want { | |
| 83 | + t.Errorf("Highlight(%q) returned %d lines, want %d", tc.src, got, tc.want) | |
| 84 | + } | |
| 85 | + }) | |
| 86 | + } | |
| 87 | +} | |
| 88 | + | |
| 89 | +func TestSpansAreInOrderAndDoNotOverlap(t *testing.T) { | |
| 90 | + // They are drawn in order, so two out of order paint over each other and | |
| 91 | + // nothing fails. This has happened in this family, in a scanner that | |
| 92 | + // emitted a quote after the name it belonged to. | |
| 93 | + const src = `#!/usr/bin/env python3 | |
| 94 | +"""A module docstring | |
| 95 | +spanning two lines.""" | |
| 96 | + | |
| 97 | +import re | |
| 98 | +from dataclasses import dataclass | |
| 99 | + | |
| 100 | +MAX_SIZE = 1_000 | |
| 101 | +PATTERN = re.compile(r"\d+(\.\d+)?") | |
| 102 | + | |
| 103 | + | |
| 104 | +@dataclass(frozen=True) | |
| 105 | +class Measurement: | |
| 106 | + """One reading.""" | |
| 107 | + | |
| 108 | + name: str | |
| 109 | + value: float = 0.5 | |
| 110 | + | |
| 111 | + def scaled(self, factor: float = 1.5e-3) -> float: | |
| 112 | + return self.value * factor | |
| 113 | + | |
| 114 | + | |
| 115 | +def main() -> None: | |
| 116 | + for line in open("input.txt"): | |
| 117 | + match line.strip(): | |
| 118 | + case "": | |
| 119 | + continue | |
| 120 | + case other: | |
| 121 | + print(f"{other!r} -> {len(other)}", end="") | |
| 122 | + | |
| 123 | + | |
| 124 | +if __name__ == "__main__": | |
| 125 | + main() | |
| 126 | +` | |
| 127 | + | |
| 128 | + for line, spans := range Highlight(src) { | |
| 129 | + previous := syntax.Span{End: -1} | |
| 130 | + for _, span := range spans { | |
| 131 | + switch { | |
| 132 | + case span.Start < previous.End: | |
| 133 | + t.Errorf("line %d: %v starts at %d, inside %v which ends at %d", | |
| 134 | + line, span.Class, span.Start, previous.Class, previous.End) | |
| 135 | + case span.Start >= span.End: | |
| 136 | + t.Errorf("line %d: %v is empty at %d", line, span.Class, span.Start) | |
| 137 | + } | |
| 138 | + previous = span | |
| 139 | + } | |
| 140 | + } | |
| 141 | +} | |
| 142 | + | |
| 143 | +func TestBrokenSourceStillColours(t *testing.T) { | |
| 144 | + // Source under the cursor is invalid most of the time it is being typed. A | |
| 145 | + // scanner that gives up is a scanner that flickers off. | |
| 146 | + broken := []string{ | |
| 147 | + `x = "unterminated`, | |
| 148 | + `x = '''unterminated`, | |
| 149 | + "def f(", | |
| 150 | + "class", | |
| 151 | + "@", | |
| 152 | + "f'{", | |
| 153 | + "x = 0x", | |
| 154 | + " )))", | |
| 155 | + "\\", | |
| 156 | + "x = 1.2.3.4", | |
| 157 | + } | |
| 158 | + | |
| 159 | + for _, src := range broken { | |
| 160 | + t.Run(src, func(t *testing.T) { | |
| 161 | + spans := Highlight(src) | |
| 162 | + if len(spans) != 1 { | |
| 163 | + t.Fatalf("Highlight(%q) returned %d lines, want 1", src, len(spans)) | |
| 164 | + } | |
| 165 | + for _, span := range spans[0] { | |
| 166 | + if span.Start < 0 || span.End > len([]rune(src)) { | |
| 167 | + t.Errorf("%v runs from %d to %d, outside a line of %d runes", | |
| 168 | + span.Class, span.Start, span.End, len([]rune(src))) | |
| 169 | + } | |
| 170 | + } | |
| 171 | + }) | |
| 172 | + } | |
| 173 | +} | |
| 174 | + | |
| 175 | +// --- one test per construct ------------------------------------------------- | |
| 176 | + | |
| 177 | +func TestEachTokenClass(t *testing.T) { | |
| 178 | + const src = `# a comment | |
| 179 | +import os | |
| 180 | +from typing import Iterator | |
| 181 | + | |
| 182 | + | |
| 183 | +class Shape: | |
| 184 | + def __init__(self, x: int = 0) -> None: | |
| 185 | + self.x = x | |
| 186 | + name = "world" | |
| 187 | + ratio = 1.5 | |
| 188 | + count = 42 | |
| 189 | + missing = None | |
| 190 | + ok = True | |
| 191 | + print(len(name)) | |
| 192 | +` | |
| 193 | + | |
| 194 | + tests := []struct { | |
| 195 | + word string | |
| 196 | + want syntax.Class | |
| 197 | + }{ | |
| 198 | + {"# a comment", syntax.ClassComment}, | |
| 199 | + {"import", syntax.ClassKeyword}, | |
| 200 | + {"from", syntax.ClassKeyword}, | |
| 201 | + {"class", syntax.ClassKeyword}, | |
| 202 | + {"def", syntax.ClassKeyword}, | |
| 203 | + {"Shape", syntax.ClassType}, | |
| 204 | + {"int", syntax.ClassType}, | |
| 205 | + {"__init__", syntax.ClassBuiltin}, | |
| 206 | + {"self", syntax.ClassBuiltin}, | |
| 207 | + {`"world"`, syntax.ClassString}, | |
| 208 | + {"1.5", syntax.ClassNumber}, | |
| 209 | + {"42", syntax.ClassNumber}, | |
| 210 | + {"None", syntax.ClassConstant}, | |
| 211 | + {"True", syntax.ClassConstant}, | |
| 212 | + {"print", syntax.ClassBuiltin}, | |
| 213 | + {"len", syntax.ClassBuiltin}, | |
| 214 | + {":", syntax.ClassPunctuation}, | |
| 215 | + {"=", syntax.ClassOperator}, | |
| 216 | + } | |
| 217 | + | |
| 218 | + for _, test := range tests { | |
| 219 | + t.Run(test.word, func(t *testing.T) { | |
| 220 | + if got := classOfFirst(t, src, test.word); got != test.want { | |
| 221 | + t.Errorf("%q is %v, want %v", test.word, got, test.want) | |
| 222 | + } | |
| 223 | + }) | |
| 224 | + } | |
| 225 | +} | |
| 226 | + | |
| 227 | +func TestACallIsAFunction(t *testing.T) { | |
| 228 | + if got := classOfFirst(t, "n = compute(3)", "compute"); got != syntax.ClassFunction { | |
| 229 | + t.Errorf("compute is %v, want function", got) | |
| 230 | + } | |
| 231 | +} | |
| 232 | + | |
| 233 | +func TestADeclaredFunctionNameIsAFunction(t *testing.T) { | |
| 234 | + if got := classOfFirst(t, "def parse(text):\n pass\n", "parse"); got != syntax.ClassFunction { | |
| 235 | + t.Errorf("parse is %v, want function", got) | |
| 236 | + } | |
| 237 | +} | |
| 238 | + | |
| 239 | +// A class is called exactly the way a function is, so the parenthesis cannot | |
| 240 | +// tell them apart and the naming convention has to. | |
| 241 | +func TestACapitalisedNameIsATypeEvenWhenItIsCalled(t *testing.T) { | |
| 242 | + tests := []struct{ src, word string }{ | |
| 243 | + {`raise ValueError("nope")`, "ValueError"}, | |
| 244 | + {`thing = Measurement(1)`, "Measurement"}, | |
| 245 | + {`class Measurement:`, "Measurement"}, | |
| 246 | + {`def f() -> Measurement:`, "Measurement"}, | |
| 247 | + } | |
| 248 | + | |
| 249 | + for _, tc := range tests { | |
| 250 | + t.Run(tc.src, func(t *testing.T) { | |
| 251 | + if got := classOfFirst(t, tc.src, tc.word); got != syntax.ClassType { | |
| 252 | + t.Errorf("%q in %q is %v, want type", tc.word, tc.src, got) | |
| 253 | + } | |
| 254 | + }) | |
| 255 | + } | |
| 256 | +} | |
| 257 | + | |
| 258 | +func TestAWordInCapitalsIsAConstant(t *testing.T) { | |
| 259 | + for _, word := range []string{"MAX_SIZE", "PI", "HTTP_PORT", "_PRIVATE", "V2"} { | |
| 260 | + t.Run(word, func(t *testing.T) { | |
| 261 | + src := word + " = 1" | |
| 262 | + if got := classOfFirst(t, src, word); got != syntax.ClassConstant { | |
| 263 | + t.Errorf("%s is %v, want constant", word, got) | |
| 264 | + } | |
| 265 | + }) | |
| 266 | + } | |
| 267 | +} | |
| 268 | + | |
| 269 | +func TestASingleCapitalIsATypeNotAConstant(t *testing.T) { | |
| 270 | + // The constant rule wants at least two runes, so that a one-letter type | |
| 271 | + // variable — T, the name every generic in the standard library uses — is | |
| 272 | + // not read as a constant. | |
| 273 | + if got := classOfFirst(t, `T = TypeVar("T")`, "T"); got != syntax.ClassType { | |
| 274 | + t.Errorf("T is %v, want type", got) | |
| 275 | + } | |
| 276 | +} | |
| 277 | + | |
| 278 | +func TestNumbersInEveryBaseAndShape(t *testing.T) { | |
| 279 | + numbers := []string{ | |
| 280 | + "42", "1_000", "0xFF", "0o17", "0b1010", "1.5", ".5", "1.", "1e10", | |
| 281 | + "1.5e-3", "1E+7", "3j", "0x_FF_FF", | |
| 282 | + } | |
| 283 | + | |
| 284 | + for _, number := range numbers { | |
| 285 | + t.Run(number, func(t *testing.T) { | |
| 286 | + src := "x = " + number + "\n" | |
| 287 | + span := spanOfFirst(t, src, number) | |
| 288 | + if span.Class != syntax.ClassNumber { | |
| 289 | + t.Errorf("%s is %v, want number", number, span.Class) | |
| 290 | + } | |
| 291 | + if got := span.End - span.Start; got != len([]rune(number)) { | |
| 292 | + t.Errorf("%s is coloured over %d runes, want %d", number, got, len([]rune(number))) | |
| 293 | + } | |
| 294 | + }) | |
| 295 | + } | |
| 296 | +} | |
| 297 | + | |
| 298 | +// 0xE-1 is a hexadecimal literal minus one. The E is a digit here, not the e of | |
| 299 | +// an exponent, so the sign after it is an operator and not part of the number. | |
| 300 | +func TestAHexadecimalLiteralDoesNotSwallowTheSignAfterIt(t *testing.T) { | |
| 301 | + span := spanOfFirst(t, "x = 0xE-1", "0xE") | |
| 302 | + | |
| 303 | + if span.End != len("x = 0xE") { | |
| 304 | + t.Errorf("0xE is coloured to column %d, want %d — the minus was taken as an exponent's sign", | |
| 305 | + span.End, len("x = 0xE")) | |
| 306 | + } | |
| 307 | +} | |
| 308 | + | |
| 309 | +// A float has at most one dot. Without that limit, `1.2.3` is one long number | |
| 310 | +// and the version string somebody is halfway through typing paints the line. | |
| 311 | +func TestANumberStopsAtItsSecondDot(t *testing.T) { | |
| 312 | + span := spanOfFirst(t, "x = 1.2.3", "1.2") | |
| 313 | + | |
| 314 | + if span.End != len("x = 1.2") { | |
| 315 | + t.Errorf("1.2 is coloured to column %d, want %d — the second dot was swallowed", | |
| 316 | + span.End, len("x = 1.2")) | |
| 317 | + } | |
| 318 | +} | |
| 319 | + | |
| 320 | +func TestADottedAttributeIsNotANumber(t *testing.T) { | |
| 321 | + if got := classOfFirst(t, "value = thing.count", "count"); got != syntax.ClassIdentifier { | |
| 322 | + t.Errorf("count after a dot is %v, want identifier", got) | |
| 323 | + } | |
| 324 | +} | |
| 325 | + | |
| 326 | +// --- strings ---------------------------------------------------------------- | |
| 327 | + | |
| 328 | +func TestEveryStringPrefixOpensAString(t *testing.T) { | |
| 329 | + prefixes := []string{"", "r", "R", "b", "B", "u", "U", "f", "F", "rb", "br", "fr", "rf", "Rb", "BR"} | |
| 330 | + | |
| 331 | + for _, prefix := range prefixes { | |
| 332 | + t.Run("prefix "+prefix, func(t *testing.T) { | |
| 333 | + literal := prefix + `"hello"` | |
| 334 | + src := "x = " + literal | |
| 335 | + span := spanOfFirst(t, src, literal) | |
| 336 | + if span.Class != syntax.ClassString { | |
| 337 | + t.Errorf("%s is %v, want string", literal, span.Class) | |
| 338 | + } | |
| 339 | + if got := span.End - span.Start; got != len([]rune(literal)) { | |
| 340 | + t.Errorf("%s is coloured over %d runes, want %d — the prefix was left out", | |
| 341 | + literal, got, len([]rune(literal))) | |
| 342 | + } | |
| 343 | + }) | |
| 344 | + } | |
| 345 | +} | |
| 346 | + | |
| 347 | +func TestAnIdentifierEndingInAPrefixLetterIsNotAString(t *testing.T) { | |
| 348 | + // foo"bar" must be an identifier and a string, not one run: the prefix | |
| 349 | + // letters are only a prefix when nothing but them comes before the quote. | |
| 350 | + if got := classOfFirst(t, `foo"bar"`, "foo"); got != syntax.ClassIdentifier { | |
| 351 | + t.Errorf("foo before a quote is %v, want identifier", got) | |
| 352 | + } | |
| 353 | +} | |
| 354 | + | |
| 355 | +func TestATripleQuotedStringCrossesLines(t *testing.T) { | |
| 356 | + const src = "text = \"\"\"one\ntwo\nthree\"\"\"\nx = 1\n" | |
| 357 | + spans := Highlight(src) | |
| 358 | + | |
| 359 | + // Column 8 on the opening line is inside the literal; the continued lines | |
| 360 | + // are short, so they are asked about at their first column. | |
| 361 | + for _, at := range []struct{ line, col int }{{0, 8}, {1, 0}, {2, 0}} { | |
| 362 | + if class, ok := classAt(spans, at.line, at.col); !ok || class != syntax.ClassString { | |
| 363 | + t.Errorf("line %d column %d is %v (covered: %t), want string", at.line, at.col, class, ok) | |
| 364 | + } | |
| 365 | + } | |
| 366 | + if class, _ := classAt(spans, 3, 0); class != syntax.ClassIdentifier { | |
| 367 | + t.Errorf("the line after the string is %v, want identifier — the string did not close", class) | |
| 368 | + } | |
| 369 | +} | |
| 370 | + | |
| 371 | +// A lone quote inside a triple-quoted string closes nothing: it takes three. | |
| 372 | +// Without this the closer is the same rune the opener started with, and every | |
| 373 | +// docstring that quotes anything ends in the middle of itself. | |
| 374 | +func TestALoneQuoteInsideATripleQuotedStringClosesNothing(t *testing.T) { | |
| 375 | + const src = "text = \"\"\"say \"hi\" now\"\"\"\nx = 1\n" | |
| 376 | + | |
| 377 | + for _, inside := range []string{"hi", "now"} { | |
| 378 | + if got := classOfFirst(t, src, inside); got != syntax.ClassString { | |
| 379 | + t.Errorf("%q inside the docstring is %v, want string — one quote ended it", inside, got) | |
| 380 | + } | |
| 381 | + } | |
| 382 | + if class, _ := classAt(Highlight(src), 1, 0); class != syntax.ClassIdentifier { | |
| 383 | + t.Errorf("the line after it is %v, want identifier", class) | |
| 384 | + } | |
| 385 | +} | |
| 386 | + | |
| 387 | +// The same thing across a line break, which is where a docstring actually | |
| 388 | +// lives: the carried closer has to be three quotes, not one. | |
| 389 | +func TestACarriedTripleQuotedStringNeedsThreeQuotesToClose(t *testing.T) { | |
| 390 | + const src = "text = \"\"\"first \"quoted\"\nsecond \"also\"\nthird\"\"\"\nx = 1\n" | |
| 391 | + spans := Highlight(src) | |
| 392 | + | |
| 393 | + for line := range 3 { | |
| 394 | + if class, ok := classAt(spans, line, 7); !ok || class != syntax.ClassString { | |
| 395 | + t.Errorf("line %d is %v (covered: %t), want string — a lone quote closed it", line, class, ok) | |
| 396 | + } | |
| 397 | + } | |
| 398 | + if class, _ := classAt(spans, 3, 0); class != syntax.ClassIdentifier { | |
| 399 | + t.Errorf("the line after it is %v, want identifier — the string never closed", class) | |
| 400 | + } | |
| 401 | +} | |
| 402 | + | |
| 403 | +func TestOneKindOfTripleQuoteDoesNotCloseTheOther(t *testing.T) { | |
| 404 | + const src = "text = '''one \"\"\" two'''\nx = 1\n" | |
| 405 | + | |
| 406 | + if got := classOfFirst(t, src, `"""`); got != syntax.ClassString { | |
| 407 | + t.Errorf(`the """ inside a ''' string is %v, want string`, got) | |
| 408 | + } | |
| 409 | + if class, _ := classAt(Highlight(src), 1, 0); class != syntax.ClassIdentifier { | |
| 410 | + t.Errorf("the next line is %v, want identifier — the ''' never closed", class) | |
| 411 | + } | |
| 412 | +} | |
| 413 | + | |
| 414 | +// A single-quoted string is not allowed to cross a line break, so one that | |
| 415 | +// reaches the end of a line without a backslash is coloured to there and | |
| 416 | +// dropped. Carrying it would paint the rest of the file as a string. | |
| 417 | +func TestAnUnterminatedSingleQuotedStringDoesNotCrossTheLineBreak(t *testing.T) { | |
| 418 | + const src = "x = \"unterminated\ny = 1\n" | |
| 419 | + | |
| 420 | + if class, _ := classAt(Highlight(src), 1, 0); class != syntax.ClassIdentifier { | |
| 421 | + t.Errorf("the line after an unterminated string is %v, want identifier", class) | |
| 422 | + } | |
| 423 | +} | |
| 424 | + | |
| 425 | +// …but a backslash at the end of the line escapes the newline, and then it | |
| 426 | +// really does carry on. That is the one case where carrying is right. | |
| 427 | +func TestABackslashAtTheEndOfALineContinuesASingleQuotedString(t *testing.T) { | |
| 428 | + const src = "x = \"one\\\ntwo\"\ny = 1\n" | |
| 429 | + | |
| 430 | + if class, ok := classAt(Highlight(src), 1, 0); !ok || class != syntax.ClassString { | |
| 431 | + t.Errorf("the continued line is %v (covered: %t), want string", class, ok) | |
| 432 | + } | |
| 433 | + if class, _ := classAt(Highlight(src), 2, 0); class != syntax.ClassIdentifier { | |
| 434 | + t.Errorf("the line after the close is %v, want identifier", class) | |
| 435 | + } | |
| 436 | +} | |
| 437 | + | |
| 438 | +// In a raw string the backslash is kept in the value, but it still stops the | |
| 439 | +// quote after it from ending the literal — which is why rawness is not carried. | |
| 440 | +func TestABackslashEscapesTheQuoteInARawStringToo(t *testing.T) { | |
| 441 | + const src = `p = r"\"" + "after"` | |
| 442 | + | |
| 443 | + if got := classOfFirst(t, src, `"after"`); got != syntax.ClassString { | |
| 444 | + t.Errorf(`"after" is %v, want string — r"\"" ended one quote too early`, got) | |
| 445 | + } | |
| 446 | +} | |
| 447 | + | |
| 448 | +func TestAHashInsideAStringIsNotAComment(t *testing.T) { | |
| 449 | + if got := classOfFirst(t, `url = "http://x/#anchor"`, "#anchor"); got != syntax.ClassString { | |
| 450 | + t.Errorf("the # inside a string is %v, want string", got) | |
| 451 | + } | |
| 452 | +} | |
| 453 | + | |
| 454 | +// --- decorators ------------------------------------------------------------- | |
| 455 | + | |
| 456 | +func TestADecoratorIsAnAttribute(t *testing.T) { | |
| 457 | + for _, src := range []string{"@property\n", " @property\n", "@app.route\n"} { | |
| 458 | + t.Run(src, func(t *testing.T) { | |
| 459 | + if got := classOfFirst(t, src, "@"); got != syntax.ClassAttribute { | |
| 460 | + t.Errorf("the decorator in %q is %v, want attribute", src, got) | |
| 461 | + } | |
| 462 | + }) | |
| 463 | + } | |
| 464 | +} | |
| 465 | + | |
| 466 | +func TestADecoratorStopsAtItsArguments(t *testing.T) { | |
| 467 | + const src = `@pytest.mark.parametrize("n", [1, 2])` | |
| 468 | + | |
| 469 | + if span := spanOfFirst(t, src, "@"); span.End != len("@pytest.mark.parametrize") { | |
| 470 | + t.Errorf("the decorator is coloured to column %d, want %d", span.End, len("@pytest.mark.parametrize")) | |
| 471 | + } | |
| 472 | + if got := classOfFirst(t, src, `"n"`); got != syntax.ClassString { | |
| 473 | + t.Errorf(`the "n" argument is %v, want string`, got) | |
| 474 | + } | |
| 475 | +} | |
| 476 | + | |
| 477 | +// The same rune is the matrix-multiplication operator, and only its position | |
| 478 | +// tells the two apart. | |
| 479 | +func TestAnAtSignInTheMiddleOfALineIsAnOperator(t *testing.T) { | |
| 480 | + // With a space after it, the rune that follows already settles it. Without | |
| 481 | + // one — `a @b` is ordinary Python — position is the only thing that does, | |
| 482 | + // which is what this second case is for. | |
| 483 | + for _, src := range []string{"product = a @ b", "product = a @b"} { | |
| 484 | + t.Run(src, func(t *testing.T) { | |
| 485 | + if got := classOfFirst(t, src, "@"); got != syntax.ClassOperator { | |
| 486 | + t.Errorf("the @ in %q is %v, want operator", src, got) | |
| 487 | + } | |
| 488 | + }) | |
| 489 | + } | |
| 490 | +} | |
| 491 | + | |
| 492 | +// --- the soft keywords ------------------------------------------------------ | |
| 493 | + | |
| 494 | +func TestMatchAndCaseAreKeywordsWhenTheyOpenABlock(t *testing.T) { | |
| 495 | + const src = "match command.split():\n case [\"go\", direction]:\n pass\n" | |
| 496 | + | |
| 497 | + if got := classOfFirst(t, src, "match"); got != syntax.ClassKeyword { | |
| 498 | + t.Errorf("match opening a statement is %v, want keyword", got) | |
| 499 | + } | |
| 500 | + if got := classOfFirst(t, src, "case"); got != syntax.ClassKeyword { | |
| 501 | + t.Errorf("case opening a block is %v, want keyword", got) | |
| 502 | + } | |
| 503 | +} | |
| 504 | + | |
| 505 | +func TestMatchIsAnOrdinaryNameEverywhereElse(t *testing.T) { | |
| 506 | + tests := []struct { | |
| 507 | + name string | |
| 508 | + src string | |
| 509 | + want syntax.Class | |
| 510 | + }{ | |
| 511 | + {"assigned", "match = re.match(pattern, text)", syntax.ClassIdentifier}, | |
| 512 | + {"called", "if match(pattern):\n pass\n", syntax.ClassFunction}, | |
| 513 | + {"an argument", "use(match)", syntax.ClassIdentifier}, | |
| 514 | + {"annotated", "match: str = compute()", syntax.ClassIdentifier}, | |
| 515 | + } | |
| 516 | + | |
| 517 | + for _, tc := range tests { | |
| 518 | + t.Run(tc.name, func(t *testing.T) { | |
| 519 | + if got := classOfFirst(t, tc.src, "match"); got != tc.want { | |
| 520 | + t.Errorf("match in %q is %v, want %v", tc.src, got, tc.want) | |
| 521 | + } | |
| 522 | + }) | |
| 523 | + } | |
| 524 | +} | |
| 525 | + | |
| 526 | +// The boundary of the soft-keyword rule, tested rather than left to be | |
| 527 | +// discovered: a trailing comment hides the colon, and match reads as a name. | |
| 528 | +// It is the safe direction to be wrong in, and reference/languages.md says so. | |
| 529 | +func TestATrailingCommentHidesTheColonFromTheSoftKeywordRule(t *testing.T) { | |
| 530 | + if got := classOfFirst(t, "match value: # dispatch\n", "match"); got != syntax.ClassIdentifier { | |
| 531 | + t.Errorf("match before a trailing comment is %v; the documented limitation says identifier", got) | |
| 532 | + } | |
| 533 | +} | |
| 534 | + | |
| 535 | +// --- what the scanner deliberately does not do ------------------------------ | |
| 536 | + | |
| 537 | +// An f-string's {expression} is one flat run of string, on purpose: since | |
| 538 | +// Python 3.12 it may contain anything at all, and colouring it half-properly | |
| 539 | +// breaks a format spec like "{n:{width}}". | |
| 540 | +func TestAnFStringIsNotScannedAsCodeInside(t *testing.T) { | |
| 541 | + const src = `print(f"{count:{width}} items")` | |
| 542 | + | |
| 543 | + for _, inside := range []string{"count", "width", "items"} { | |
| 544 | + if got := classOfFirst(t, src, inside); got != syntax.ClassString { | |
| 545 | + t.Errorf("%q inside an f-string is %v; the whole literal is meant to be one string", inside, got) | |
| 546 | + } | |
| 547 | + } | |
| 548 | +} | |
| 549 | + | |
| 550 | +// A docstring is a string, which is what the language calls it and what help() | |
| 551 | +// reads back. Colouring it as a comment would be a different claim, and wrong | |
| 552 | +// the moment one is assigned to a name. | |
| 553 | +func TestADocstringIsAStringAndNotAComment(t *testing.T) { | |
| 554 | + const src = "def f():\n \"\"\"What it does.\"\"\"\n" | |
| 555 | + | |
| 556 | + if got := classOfFirst(t, src, `"""What it does."""`); got != syntax.ClassString { | |
| 557 | + t.Errorf("a docstring is %v, want string", got) | |
| 558 | + } | |
| 559 | +} | |
| 560 | + | |
| 561 | +// type is a builtin type as well as a soft keyword, and reads correctly as the | |
| 562 | +// type in both jobs — so it is deliberately not in isSoftKeyword. | |
| 563 | +func TestTypeIsTheBuiltinTypeInBothOfItsJobs(t *testing.T) { | |
| 564 | + for _, src := range []string{"type(value)", "type Alias = int"} { | |
| 565 | + if got := classOfFirst(t, src, "type"); got != syntax.ClassType { | |
| 566 | + t.Errorf("type in %q is %v, want type", src, got) | |
| 567 | + } | |
| 568 | + } | |
| 569 | +} | |
| 570 | + | |
| 571 | +// The walrus is an operator; every other colon is structure. | |
| 572 | +func TestTheWalrusIsAnOperatorAndAPlainColonIsNot(t *testing.T) { | |
| 573 | + if got := classOfFirst(t, "if (n := len(text)) > 3:\n pass\n", ":="); got != syntax.ClassOperator { | |
| 574 | + t.Errorf(":= is %v, want operator", got) | |
| 575 | + } | |
| 576 | + if got := classOfFirst(t, `d = {"a": 1}`, ":"); got != syntax.ClassPunctuation { | |
| 577 | + t.Errorf("a dict colon is %v, want punctuation", got) | |
| 578 | + } | |
| 579 | + if got := classOfFirst(t, "items[1:2]", ":"); got != syntax.ClassPunctuation { | |
| 580 | + t.Errorf("a slice colon is %v, want punctuation", got) | |
| 581 | + } | |
| 582 | +} | |
| 583 | + | |
| 584 | +// --- the whole thing over a real file --------------------------------------- | |
| 585 | + | |
| 586 | +func TestASweepOverRepresentativeSourceLeavesNothingUncoloured(t *testing.T) { | |
| 587 | + // Not every rune is coloured — whitespace is not, and neither is a rune the | |
| 588 | + // scanner steps over — but a *word* left with no span at all means the | |
| 589 | + // dispatcher fell through, which is a defect and not a decision. | |
| 590 | + const src = `from __future__ import annotations | |
| 591 | + | |
| 592 | +import asyncio | |
| 593 | +from typing import Any | |
| 594 | + | |
| 595 | + | |
| 596 | +async def gather(*tasks: Any, timeout: float = 1.0) -> list[Any]: | |
| 597 | + async with asyncio.timeout(timeout): | |
| 598 | + return await asyncio.gather(*tasks) | |
| 599 | + | |
| 600 | + | |
| 601 | +class Registry(dict[str, int]): | |
| 602 | + __slots__ = () | |
| 603 | + | |
| 604 | + def add(self, key: str, /, *, count: int = 1) -> None: | |
| 605 | + self[key] = self.get(key, 0) + count | |
| 606 | + | |
| 607 | + def __repr__(self) -> str: | |
| 608 | + return f"Registry({dict(self)!r})" | |
| 609 | + | |
| 610 | + | |
| 611 | +lambda_ = lambda x: x if x else -x | |
| 612 | +numbers = [n**2 for n in range(10) if n % 2 == 0] | |
| 613 | +mapping = {k: v for k, v in zip("abc", [1, 2, 3])} | |
| 614 | +` | |
| 615 | + | |
| 616 | + spans := Highlight(src) | |
| 617 | + for line, text := range strings.Split(src, "\n") { | |
| 618 | + for col, r := range []rune(text) { | |
| 619 | + if !syntax.IsLetter(r) && !syntax.IsDigit(r) { | |
| 620 | + continue | |
| 621 | + } | |
| 622 | + if _, ok := classAt(spans, line, col); !ok { | |
| 623 | + t.Errorf("line %d column %d (%q) is covered by no span: %q", line, col, r, text) | |
| 624 | + } | |
| 625 | + } | |
| 626 | + } | |
| 627 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,627 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + "testing" | ||
| 6 | + | ||
| 7 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 8 | +) | ||
| 9 | + | ||
| 10 | +// classAt returns the class covering a rune column on a line, and whether any | ||
| 11 | +// span covers it at all. It is how nearly every test below asks its question. | ||
| 12 | +func classAt(spans [][]syntax.Span, line, col int) (syntax.Class, bool) { | ||
| 13 | + if line < 0 || line >= len(spans) { | ||
| 14 | + return 0, false | ||
| 15 | + } | ||
| 16 | + for _, s := range spans[line] { | ||
| 17 | + if col >= s.Start && col < s.End { | ||
| 18 | + return s.Class, true | ||
| 19 | + } | ||
| 20 | + } | ||
| 21 | + return 0, false | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +// classOfFirst returns the class of the first occurrence of word in src. | ||
| 25 | +func classOfFirst(t *testing.T, src, word string) syntax.Class { | ||
| 26 | + t.Helper() | ||
| 27 | + | ||
| 28 | + index := strings.Index(src, word) | ||
| 29 | + if index < 0 { | ||
| 30 | + t.Fatalf("%q does not appear in the source", word) | ||
| 31 | + } | ||
| 32 | + line := strings.Count(src[:index], "\n") | ||
| 33 | + col := index - (strings.LastIndex(src[:index], "\n") + 1) | ||
| 34 | + | ||
| 35 | + class, ok := classAt(Highlight(src), line, col) | ||
| 36 | + if !ok { | ||
| 37 | + t.Fatalf("no span covers %q at line %d column %d", word, line, col) | ||
| 38 | + } | ||
| 39 | + return class | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +// spanOfFirst returns the span covering the first occurrence of word, so that a | ||
| 43 | +// test can check where a construct *ends* and not only what colour it is. | ||
| 44 | +func spanOfFirst(t *testing.T, src, word string) syntax.Span { | ||
| 45 | + t.Helper() | ||
| 46 | + | ||
| 47 | + index := strings.Index(src, word) | ||
| 48 | + if index < 0 { | ||
| 49 | + t.Fatalf("%q does not appear in the source", word) | ||
| 50 | + } | ||
| 51 | + line := strings.Count(src[:index], "\n") | ||
| 52 | + col := index - (strings.LastIndex(src[:index], "\n") + 1) | ||
| 53 | + | ||
| 54 | + for _, s := range Highlight(src)[line] { | ||
| 55 | + if col >= s.Start && col < s.End { | ||
| 56 | + return s | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + t.Fatalf("no span covers %q at line %d column %d", word, line, col) | ||
| 60 | + return syntax.Span{} | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +// --- the three invariants the editor relies on ------------------------------ | ||
| 64 | + | ||
| 65 | +func TestHighlightReturnsOneEntryPerLine(t *testing.T) { | ||
| 66 | + // The editor indexes the result by line number without checking, so a short | ||
| 67 | + // result is an index out of range in the middle of a redraw. | ||
| 68 | + tests := []struct { | ||
| 69 | + name string | ||
| 70 | + src string | ||
| 71 | + want int | ||
| 72 | + }{ | ||
| 73 | + {"empty", "", 1}, | ||
| 74 | + {"one line without a terminator", "x = 1", 1}, | ||
| 75 | + {"one line with a terminator", "x = 1\n", 2}, | ||
| 76 | + {"three lines", "a\nb\nc", 3}, | ||
| 77 | + {"an unterminated triple quote", `x = """a` + "\nb\nc", 3}, | ||
| 78 | + } | ||
| 79 | + | ||
| 80 | + for _, tc := range tests { | ||
| 81 | + t.Run(tc.name, func(t *testing.T) { | ||
| 82 | + if got := len(Highlight(tc.src)); got != tc.want { | ||
| 83 | + t.Errorf("Highlight(%q) returned %d lines, want %d", tc.src, got, tc.want) | ||
| 84 | + } | ||
| 85 | + }) | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +func TestSpansAreInOrderAndDoNotOverlap(t *testing.T) { | ||
| 90 | + // They are drawn in order, so two out of order paint over each other and | ||
| 91 | + // nothing fails. This has happened in this family, in a scanner that | ||
| 92 | + // emitted a quote after the name it belonged to. | ||
| 93 | + const src = `#!/usr/bin/env python3 | ||
| 94 | +"""A module docstring | ||
| 95 | +spanning two lines.""" | ||
| 96 | + | ||
| 97 | +import re | ||
| 98 | +from dataclasses import dataclass | ||
| 99 | + | ||
| 100 | +MAX_SIZE = 1_000 | ||
| 101 | +PATTERN = re.compile(r"\d+(\.\d+)?") | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +@dataclass(frozen=True) | ||
| 105 | +class Measurement: | ||
| 106 | + """One reading.""" | ||
| 107 | + | ||
| 108 | + name: str | ||
| 109 | + value: float = 0.5 | ||
| 110 | + | ||
| 111 | + def scaled(self, factor: float = 1.5e-3) -> float: | ||
| 112 | + return self.value * factor | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +def main() -> None: | ||
| 116 | + for line in open("input.txt"): | ||
| 117 | + match line.strip(): | ||
| 118 | + case "": | ||
| 119 | + continue | ||
| 120 | + case other: | ||
| 121 | + print(f"{other!r} -> {len(other)}", end="") | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +if __name__ == "__main__": | ||
| 125 | + main() | ||
| 126 | +` | ||
| 127 | + | ||
| 128 | + for line, spans := range Highlight(src) { | ||
| 129 | + previous := syntax.Span{End: -1} | ||
| 130 | + for _, span := range spans { | ||
| 131 | + switch { | ||
| 132 | + case span.Start < previous.End: | ||
| 133 | + t.Errorf("line %d: %v starts at %d, inside %v which ends at %d", | ||
| 134 | + line, span.Class, span.Start, previous.Class, previous.End) | ||
| 135 | + case span.Start >= span.End: | ||
| 136 | + t.Errorf("line %d: %v is empty at %d", line, span.Class, span.Start) | ||
| 137 | + } | ||
| 138 | + previous = span | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +func TestBrokenSourceStillColours(t *testing.T) { | ||
| 144 | + // Source under the cursor is invalid most of the time it is being typed. A | ||
| 145 | + // scanner that gives up is a scanner that flickers off. | ||
| 146 | + broken := []string{ | ||
| 147 | + `x = "unterminated`, | ||
| 148 | + `x = '''unterminated`, | ||
| 149 | + "def f(", | ||
| 150 | + "class", | ||
| 151 | + "@", | ||
| 152 | + "f'{", | ||
| 153 | + "x = 0x", | ||
| 154 | + " )))", | ||
| 155 | + "\\", | ||
| 156 | + "x = 1.2.3.4", | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + for _, src := range broken { | ||
| 160 | + t.Run(src, func(t *testing.T) { | ||
| 161 | + spans := Highlight(src) | ||
| 162 | + if len(spans) != 1 { | ||
| 163 | + t.Fatalf("Highlight(%q) returned %d lines, want 1", src, len(spans)) | ||
| 164 | + } | ||
| 165 | + for _, span := range spans[0] { | ||
| 166 | + if span.Start < 0 || span.End > len([]rune(src)) { | ||
| 167 | + t.Errorf("%v runs from %d to %d, outside a line of %d runes", | ||
| 168 | + span.Class, span.Start, span.End, len([]rune(src))) | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | + }) | ||
| 172 | + } | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +// --- one test per construct ------------------------------------------------- | ||
| 176 | + | ||
| 177 | +func TestEachTokenClass(t *testing.T) { | ||
| 178 | + const src = `# a comment | ||
| 179 | +import os | ||
| 180 | +from typing import Iterator | ||
| 181 | + | ||
| 182 | + | ||
| 183 | +class Shape: | ||
| 184 | + def __init__(self, x: int = 0) -> None: | ||
| 185 | + self.x = x | ||
| 186 | + name = "world" | ||
| 187 | + ratio = 1.5 | ||
| 188 | + count = 42 | ||
| 189 | + missing = None | ||
| 190 | + ok = True | ||
| 191 | + print(len(name)) | ||
| 192 | +` | ||
| 193 | + | ||
| 194 | + tests := []struct { | ||
| 195 | + word string | ||
| 196 | + want syntax.Class | ||
| 197 | + }{ | ||
| 198 | + {"# a comment", syntax.ClassComment}, | ||
| 199 | + {"import", syntax.ClassKeyword}, | ||
| 200 | + {"from", syntax.ClassKeyword}, | ||
| 201 | + {"class", syntax.ClassKeyword}, | ||
| 202 | + {"def", syntax.ClassKeyword}, | ||
| 203 | + {"Shape", syntax.ClassType}, | ||
| 204 | + {"int", syntax.ClassType}, | ||
| 205 | + {"__init__", syntax.ClassBuiltin}, | ||
| 206 | + {"self", syntax.ClassBuiltin}, | ||
| 207 | + {`"world"`, syntax.ClassString}, | ||
| 208 | + {"1.5", syntax.ClassNumber}, | ||
| 209 | + {"42", syntax.ClassNumber}, | ||
| 210 | + {"None", syntax.ClassConstant}, | ||
| 211 | + {"True", syntax.ClassConstant}, | ||
| 212 | + {"print", syntax.ClassBuiltin}, | ||
| 213 | + {"len", syntax.ClassBuiltin}, | ||
| 214 | + {":", syntax.ClassPunctuation}, | ||
| 215 | + {"=", syntax.ClassOperator}, | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + for _, test := range tests { | ||
| 219 | + t.Run(test.word, func(t *testing.T) { | ||
| 220 | + if got := classOfFirst(t, src, test.word); got != test.want { | ||
| 221 | + t.Errorf("%q is %v, want %v", test.word, got, test.want) | ||
| 222 | + } | ||
| 223 | + }) | ||
| 224 | + } | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +func TestACallIsAFunction(t *testing.T) { | ||
| 228 | + if got := classOfFirst(t, "n = compute(3)", "compute"); got != syntax.ClassFunction { | ||
| 229 | + t.Errorf("compute is %v, want function", got) | ||
| 230 | + } | ||
| 231 | +} | ||
| 232 | + | ||
| 233 | +func TestADeclaredFunctionNameIsAFunction(t *testing.T) { | ||
| 234 | + if got := classOfFirst(t, "def parse(text):\n pass\n", "parse"); got != syntax.ClassFunction { | ||
| 235 | + t.Errorf("parse is %v, want function", got) | ||
| 236 | + } | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +// A class is called exactly the way a function is, so the parenthesis cannot | ||
| 240 | +// tell them apart and the naming convention has to. | ||
| 241 | +func TestACapitalisedNameIsATypeEvenWhenItIsCalled(t *testing.T) { | ||
| 242 | + tests := []struct{ src, word string }{ | ||
| 243 | + {`raise ValueError("nope")`, "ValueError"}, | ||
| 244 | + {`thing = Measurement(1)`, "Measurement"}, | ||
| 245 | + {`class Measurement:`, "Measurement"}, | ||
| 246 | + {`def f() -> Measurement:`, "Measurement"}, | ||
| 247 | + } | ||
| 248 | + | ||
| 249 | + for _, tc := range tests { | ||
| 250 | + t.Run(tc.src, func(t *testing.T) { | ||
| 251 | + if got := classOfFirst(t, tc.src, tc.word); got != syntax.ClassType { | ||
| 252 | + t.Errorf("%q in %q is %v, want type", tc.word, tc.src, got) | ||
| 253 | + } | ||
| 254 | + }) | ||
| 255 | + } | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +func TestAWordInCapitalsIsAConstant(t *testing.T) { | ||
| 259 | + for _, word := range []string{"MAX_SIZE", "PI", "HTTP_PORT", "_PRIVATE", "V2"} { | ||
| 260 | + t.Run(word, func(t *testing.T) { | ||
| 261 | + src := word + " = 1" | ||
| 262 | + if got := classOfFirst(t, src, word); got != syntax.ClassConstant { | ||
| 263 | + t.Errorf("%s is %v, want constant", word, got) | ||
| 264 | + } | ||
| 265 | + }) | ||
| 266 | + } | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +func TestASingleCapitalIsATypeNotAConstant(t *testing.T) { | ||
| 270 | + // The constant rule wants at least two runes, so that a one-letter type | ||
| 271 | + // variable — T, the name every generic in the standard library uses — is | ||
| 272 | + // not read as a constant. | ||
| 273 | + if got := classOfFirst(t, `T = TypeVar("T")`, "T"); got != syntax.ClassType { | ||
| 274 | + t.Errorf("T is %v, want type", got) | ||
| 275 | + } | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +func TestNumbersInEveryBaseAndShape(t *testing.T) { | ||
| 279 | + numbers := []string{ | ||
| 280 | + "42", "1_000", "0xFF", "0o17", "0b1010", "1.5", ".5", "1.", "1e10", | ||
| 281 | + "1.5e-3", "1E+7", "3j", "0x_FF_FF", | ||
| 282 | + } | ||
| 283 | + | ||
| 284 | + for _, number := range numbers { | ||
| 285 | + t.Run(number, func(t *testing.T) { | ||
| 286 | + src := "x = " + number + "\n" | ||
| 287 | + span := spanOfFirst(t, src, number) | ||
| 288 | + if span.Class != syntax.ClassNumber { | ||
| 289 | + t.Errorf("%s is %v, want number", number, span.Class) | ||
| 290 | + } | ||
| 291 | + if got := span.End - span.Start; got != len([]rune(number)) { | ||
| 292 | + t.Errorf("%s is coloured over %d runes, want %d", number, got, len([]rune(number))) | ||
| 293 | + } | ||
| 294 | + }) | ||
| 295 | + } | ||
| 296 | +} | ||
| 297 | + | ||
| 298 | +// 0xE-1 is a hexadecimal literal minus one. The E is a digit here, not the e of | ||
| 299 | +// an exponent, so the sign after it is an operator and not part of the number. | ||
| 300 | +func TestAHexadecimalLiteralDoesNotSwallowTheSignAfterIt(t *testing.T) { | ||
| 301 | + span := spanOfFirst(t, "x = 0xE-1", "0xE") | ||
| 302 | + | ||
| 303 | + if span.End != len("x = 0xE") { | ||
| 304 | + t.Errorf("0xE is coloured to column %d, want %d — the minus was taken as an exponent's sign", | ||
| 305 | + span.End, len("x = 0xE")) | ||
| 306 | + } | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +// A float has at most one dot. Without that limit, `1.2.3` is one long number | ||
| 310 | +// and the version string somebody is halfway through typing paints the line. | ||
| 311 | +func TestANumberStopsAtItsSecondDot(t *testing.T) { | ||
| 312 | + span := spanOfFirst(t, "x = 1.2.3", "1.2") | ||
| 313 | + | ||
| 314 | + if span.End != len("x = 1.2") { | ||
| 315 | + t.Errorf("1.2 is coloured to column %d, want %d — the second dot was swallowed", | ||
| 316 | + span.End, len("x = 1.2")) | ||
| 317 | + } | ||
| 318 | +} | ||
| 319 | + | ||
| 320 | +func TestADottedAttributeIsNotANumber(t *testing.T) { | ||
| 321 | + if got := classOfFirst(t, "value = thing.count", "count"); got != syntax.ClassIdentifier { | ||
| 322 | + t.Errorf("count after a dot is %v, want identifier", got) | ||
| 323 | + } | ||
| 324 | +} | ||
| 325 | + | ||
| 326 | +// --- strings ---------------------------------------------------------------- | ||
| 327 | + | ||
| 328 | +func TestEveryStringPrefixOpensAString(t *testing.T) { | ||
| 329 | + prefixes := []string{"", "r", "R", "b", "B", "u", "U", "f", "F", "rb", "br", "fr", "rf", "Rb", "BR"} | ||
| 330 | + | ||
| 331 | + for _, prefix := range prefixes { | ||
| 332 | + t.Run("prefix "+prefix, func(t *testing.T) { | ||
| 333 | + literal := prefix + `"hello"` | ||
| 334 | + src := "x = " + literal | ||
| 335 | + span := spanOfFirst(t, src, literal) | ||
| 336 | + if span.Class != syntax.ClassString { | ||
| 337 | + t.Errorf("%s is %v, want string", literal, span.Class) | ||
| 338 | + } | ||
| 339 | + if got := span.End - span.Start; got != len([]rune(literal)) { | ||
| 340 | + t.Errorf("%s is coloured over %d runes, want %d — the prefix was left out", | ||
| 341 | + literal, got, len([]rune(literal))) | ||
| 342 | + } | ||
| 343 | + }) | ||
| 344 | + } | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +func TestAnIdentifierEndingInAPrefixLetterIsNotAString(t *testing.T) { | ||
| 348 | + // foo"bar" must be an identifier and a string, not one run: the prefix | ||
| 349 | + // letters are only a prefix when nothing but them comes before the quote. | ||
| 350 | + if got := classOfFirst(t, `foo"bar"`, "foo"); got != syntax.ClassIdentifier { | ||
| 351 | + t.Errorf("foo before a quote is %v, want identifier", got) | ||
| 352 | + } | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +func TestATripleQuotedStringCrossesLines(t *testing.T) { | ||
| 356 | + const src = "text = \"\"\"one\ntwo\nthree\"\"\"\nx = 1\n" | ||
| 357 | + spans := Highlight(src) | ||
| 358 | + | ||
| 359 | + // Column 8 on the opening line is inside the literal; the continued lines | ||
| 360 | + // are short, so they are asked about at their first column. | ||
| 361 | + for _, at := range []struct{ line, col int }{{0, 8}, {1, 0}, {2, 0}} { | ||
| 362 | + if class, ok := classAt(spans, at.line, at.col); !ok || class != syntax.ClassString { | ||
| 363 | + t.Errorf("line %d column %d is %v (covered: %t), want string", at.line, at.col, class, ok) | ||
| 364 | + } | ||
| 365 | + } | ||
| 366 | + if class, _ := classAt(spans, 3, 0); class != syntax.ClassIdentifier { | ||
| 367 | + t.Errorf("the line after the string is %v, want identifier — the string did not close", class) | ||
| 368 | + } | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +// A lone quote inside a triple-quoted string closes nothing: it takes three. | ||
| 372 | +// Without this the closer is the same rune the opener started with, and every | ||
| 373 | +// docstring that quotes anything ends in the middle of itself. | ||
| 374 | +func TestALoneQuoteInsideATripleQuotedStringClosesNothing(t *testing.T) { | ||
| 375 | + const src = "text = \"\"\"say \"hi\" now\"\"\"\nx = 1\n" | ||
| 376 | + | ||
| 377 | + for _, inside := range []string{"hi", "now"} { | ||
| 378 | + if got := classOfFirst(t, src, inside); got != syntax.ClassString { | ||
| 379 | + t.Errorf("%q inside the docstring is %v, want string — one quote ended it", inside, got) | ||
| 380 | + } | ||
| 381 | + } | ||
| 382 | + if class, _ := classAt(Highlight(src), 1, 0); class != syntax.ClassIdentifier { | ||
| 383 | + t.Errorf("the line after it is %v, want identifier", class) | ||
| 384 | + } | ||
| 385 | +} | ||
| 386 | + | ||
| 387 | +// The same thing across a line break, which is where a docstring actually | ||
| 388 | +// lives: the carried closer has to be three quotes, not one. | ||
| 389 | +func TestACarriedTripleQuotedStringNeedsThreeQuotesToClose(t *testing.T) { | ||
| 390 | + const src = "text = \"\"\"first \"quoted\"\nsecond \"also\"\nthird\"\"\"\nx = 1\n" | ||
| 391 | + spans := Highlight(src) | ||
| 392 | + | ||
| 393 | + for line := range 3 { | ||
| 394 | + if class, ok := classAt(spans, line, 7); !ok || class != syntax.ClassString { | ||
| 395 | + t.Errorf("line %d is %v (covered: %t), want string — a lone quote closed it", line, class, ok) | ||
| 396 | + } | ||
| 397 | + } | ||
| 398 | + if class, _ := classAt(spans, 3, 0); class != syntax.ClassIdentifier { | ||
| 399 | + t.Errorf("the line after it is %v, want identifier — the string never closed", class) | ||
| 400 | + } | ||
| 401 | +} | ||
| 402 | + | ||
| 403 | +func TestOneKindOfTripleQuoteDoesNotCloseTheOther(t *testing.T) { | ||
| 404 | + const src = "text = '''one \"\"\" two'''\nx = 1\n" | ||
| 405 | + | ||
| 406 | + if got := classOfFirst(t, src, `"""`); got != syntax.ClassString { | ||
| 407 | + t.Errorf(`the """ inside a ''' string is %v, want string`, got) | ||
| 408 | + } | ||
| 409 | + if class, _ := classAt(Highlight(src), 1, 0); class != syntax.ClassIdentifier { | ||
| 410 | + t.Errorf("the next line is %v, want identifier — the ''' never closed", class) | ||
| 411 | + } | ||
| 412 | +} | ||
| 413 | + | ||
| 414 | +// A single-quoted string is not allowed to cross a line break, so one that | ||
| 415 | +// reaches the end of a line without a backslash is coloured to there and | ||
| 416 | +// dropped. Carrying it would paint the rest of the file as a string. | ||
| 417 | +func TestAnUnterminatedSingleQuotedStringDoesNotCrossTheLineBreak(t *testing.T) { | ||
| 418 | + const src = "x = \"unterminated\ny = 1\n" | ||
| 419 | + | ||
| 420 | + if class, _ := classAt(Highlight(src), 1, 0); class != syntax.ClassIdentifier { | ||
| 421 | + t.Errorf("the line after an unterminated string is %v, want identifier", class) | ||
| 422 | + } | ||
| 423 | +} | ||
| 424 | + | ||
| 425 | +// …but a backslash at the end of the line escapes the newline, and then it | ||
| 426 | +// really does carry on. That is the one case where carrying is right. | ||
| 427 | +func TestABackslashAtTheEndOfALineContinuesASingleQuotedString(t *testing.T) { | ||
| 428 | + const src = "x = \"one\\\ntwo\"\ny = 1\n" | ||
| 429 | + | ||
| 430 | + if class, ok := classAt(Highlight(src), 1, 0); !ok || class != syntax.ClassString { | ||
| 431 | + t.Errorf("the continued line is %v (covered: %t), want string", class, ok) | ||
| 432 | + } | ||
| 433 | + if class, _ := classAt(Highlight(src), 2, 0); class != syntax.ClassIdentifier { | ||
| 434 | + t.Errorf("the line after the close is %v, want identifier", class) | ||
| 435 | + } | ||
| 436 | +} | ||
| 437 | + | ||
| 438 | +// In a raw string the backslash is kept in the value, but it still stops the | ||
| 439 | +// quote after it from ending the literal — which is why rawness is not carried. | ||
| 440 | +func TestABackslashEscapesTheQuoteInARawStringToo(t *testing.T) { | ||
| 441 | + const src = `p = r"\"" + "after"` | ||
| 442 | + | ||
| 443 | + if got := classOfFirst(t, src, `"after"`); got != syntax.ClassString { | ||
| 444 | + t.Errorf(`"after" is %v, want string — r"\"" ended one quote too early`, got) | ||
| 445 | + } | ||
| 446 | +} | ||
| 447 | + | ||
| 448 | +func TestAHashInsideAStringIsNotAComment(t *testing.T) { | ||
| 449 | + if got := classOfFirst(t, `url = "http://x/#anchor"`, "#anchor"); got != syntax.ClassString { | ||
| 450 | + t.Errorf("the # inside a string is %v, want string", got) | ||
| 451 | + } | ||
| 452 | +} | ||
| 453 | + | ||
| 454 | +// --- decorators ------------------------------------------------------------- | ||
| 455 | + | ||
| 456 | +func TestADecoratorIsAnAttribute(t *testing.T) { | ||
| 457 | + for _, src := range []string{"@property\n", " @property\n", "@app.route\n"} { | ||
| 458 | + t.Run(src, func(t *testing.T) { | ||
| 459 | + if got := classOfFirst(t, src, "@"); got != syntax.ClassAttribute { | ||
| 460 | + t.Errorf("the decorator in %q is %v, want attribute", src, got) | ||
| 461 | + } | ||
| 462 | + }) | ||
| 463 | + } | ||
| 464 | +} | ||
| 465 | + | ||
| 466 | +func TestADecoratorStopsAtItsArguments(t *testing.T) { | ||
| 467 | + const src = `@pytest.mark.parametrize("n", [1, 2])` | ||
| 468 | + | ||
| 469 | + if span := spanOfFirst(t, src, "@"); span.End != len("@pytest.mark.parametrize") { | ||
| 470 | + t.Errorf("the decorator is coloured to column %d, want %d", span.End, len("@pytest.mark.parametrize")) | ||
| 471 | + } | ||
| 472 | + if got := classOfFirst(t, src, `"n"`); got != syntax.ClassString { | ||
| 473 | + t.Errorf(`the "n" argument is %v, want string`, got) | ||
| 474 | + } | ||
| 475 | +} | ||
| 476 | + | ||
| 477 | +// The same rune is the matrix-multiplication operator, and only its position | ||
| 478 | +// tells the two apart. | ||
| 479 | +func TestAnAtSignInTheMiddleOfALineIsAnOperator(t *testing.T) { | ||
| 480 | + // With a space after it, the rune that follows already settles it. Without | ||
| 481 | + // one — `a @b` is ordinary Python — position is the only thing that does, | ||
| 482 | + // which is what this second case is for. | ||
| 483 | + for _, src := range []string{"product = a @ b", "product = a @b"} { | ||
| 484 | + t.Run(src, func(t *testing.T) { | ||
| 485 | + if got := classOfFirst(t, src, "@"); got != syntax.ClassOperator { | ||
| 486 | + t.Errorf("the @ in %q is %v, want operator", src, got) | ||
| 487 | + } | ||
| 488 | + }) | ||
| 489 | + } | ||
| 490 | +} | ||
| 491 | + | ||
| 492 | +// --- the soft keywords ------------------------------------------------------ | ||
| 493 | + | ||
| 494 | +func TestMatchAndCaseAreKeywordsWhenTheyOpenABlock(t *testing.T) { | ||
| 495 | + const src = "match command.split():\n case [\"go\", direction]:\n pass\n" | ||
| 496 | + | ||
| 497 | + if got := classOfFirst(t, src, "match"); got != syntax.ClassKeyword { | ||
| 498 | + t.Errorf("match opening a statement is %v, want keyword", got) | ||
| 499 | + } | ||
| 500 | + if got := classOfFirst(t, src, "case"); got != syntax.ClassKeyword { | ||
| 501 | + t.Errorf("case opening a block is %v, want keyword", got) | ||
| 502 | + } | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +func TestMatchIsAnOrdinaryNameEverywhereElse(t *testing.T) { | ||
| 506 | + tests := []struct { | ||
| 507 | + name string | ||
| 508 | + src string | ||
| 509 | + want syntax.Class | ||
| 510 | + }{ | ||
| 511 | + {"assigned", "match = re.match(pattern, text)", syntax.ClassIdentifier}, | ||
| 512 | + {"called", "if match(pattern):\n pass\n", syntax.ClassFunction}, | ||
| 513 | + {"an argument", "use(match)", syntax.ClassIdentifier}, | ||
| 514 | + {"annotated", "match: str = compute()", syntax.ClassIdentifier}, | ||
| 515 | + } | ||
| 516 | + | ||
| 517 | + for _, tc := range tests { | ||
| 518 | + t.Run(tc.name, func(t *testing.T) { | ||
| 519 | + if got := classOfFirst(t, tc.src, "match"); got != tc.want { | ||
| 520 | + t.Errorf("match in %q is %v, want %v", tc.src, got, tc.want) | ||
| 521 | + } | ||
| 522 | + }) | ||
| 523 | + } | ||
| 524 | +} | ||
| 525 | + | ||
| 526 | +// The boundary of the soft-keyword rule, tested rather than left to be | ||
| 527 | +// discovered: a trailing comment hides the colon, and match reads as a name. | ||
| 528 | +// It is the safe direction to be wrong in, and reference/languages.md says so. | ||
| 529 | +func TestATrailingCommentHidesTheColonFromTheSoftKeywordRule(t *testing.T) { | ||
| 530 | + if got := classOfFirst(t, "match value: # dispatch\n", "match"); got != syntax.ClassIdentifier { | ||
| 531 | + t.Errorf("match before a trailing comment is %v; the documented limitation says identifier", got) | ||
| 532 | + } | ||
| 533 | +} | ||
| 534 | + | ||
| 535 | +// --- what the scanner deliberately does not do ------------------------------ | ||
| 536 | + | ||
| 537 | +// An f-string's {expression} is one flat run of string, on purpose: since | ||
| 538 | +// Python 3.12 it may contain anything at all, and colouring it half-properly | ||
| 539 | +// breaks a format spec like "{n:{width}}". | ||
| 540 | +func TestAnFStringIsNotScannedAsCodeInside(t *testing.T) { | ||
| 541 | + const src = `print(f"{count:{width}} items")` | ||
| 542 | + | ||
| 543 | + for _, inside := range []string{"count", "width", "items"} { | ||
| 544 | + if got := classOfFirst(t, src, inside); got != syntax.ClassString { | ||
| 545 | + t.Errorf("%q inside an f-string is %v; the whole literal is meant to be one string", inside, got) | ||
| 546 | + } | ||
| 547 | + } | ||
| 548 | +} | ||
| 549 | + | ||
| 550 | +// A docstring is a string, which is what the language calls it and what help() | ||
| 551 | +// reads back. Colouring it as a comment would be a different claim, and wrong | ||
| 552 | +// the moment one is assigned to a name. | ||
| 553 | +func TestADocstringIsAStringAndNotAComment(t *testing.T) { | ||
| 554 | + const src = "def f():\n \"\"\"What it does.\"\"\"\n" | ||
| 555 | + | ||
| 556 | + if got := classOfFirst(t, src, `"""What it does."""`); got != syntax.ClassString { | ||
| 557 | + t.Errorf("a docstring is %v, want string", got) | ||
| 558 | + } | ||
| 559 | +} | ||
| 560 | + | ||
| 561 | +// type is a builtin type as well as a soft keyword, and reads correctly as the | ||
| 562 | +// type in both jobs — so it is deliberately not in isSoftKeyword. | ||
| 563 | +func TestTypeIsTheBuiltinTypeInBothOfItsJobs(t *testing.T) { | ||
| 564 | + for _, src := range []string{"type(value)", "type Alias = int"} { | ||
| 565 | + if got := classOfFirst(t, src, "type"); got != syntax.ClassType { | ||
| 566 | + t.Errorf("type in %q is %v, want type", src, got) | ||
| 567 | + } | ||
| 568 | + } | ||
| 569 | +} | ||
| 570 | + | ||
| 571 | +// The walrus is an operator; every other colon is structure. | ||
| 572 | +func TestTheWalrusIsAnOperatorAndAPlainColonIsNot(t *testing.T) { | ||
| 573 | + if got := classOfFirst(t, "if (n := len(text)) > 3:\n pass\n", ":="); got != syntax.ClassOperator { | ||
| 574 | + t.Errorf(":= is %v, want operator", got) | ||
| 575 | + } | ||
| 576 | + if got := classOfFirst(t, `d = {"a": 1}`, ":"); got != syntax.ClassPunctuation { | ||
| 577 | + t.Errorf("a dict colon is %v, want punctuation", got) | ||
| 578 | + } | ||
| 579 | + if got := classOfFirst(t, "items[1:2]", ":"); got != syntax.ClassPunctuation { | ||
| 580 | + t.Errorf("a slice colon is %v, want punctuation", got) | ||
| 581 | + } | ||
| 582 | +} | ||
| 583 | + | ||
| 584 | +// --- the whole thing over a real file --------------------------------------- | ||
| 585 | + | ||
| 586 | +func TestASweepOverRepresentativeSourceLeavesNothingUncoloured(t *testing.T) { | ||
| 587 | + // Not every rune is coloured — whitespace is not, and neither is a rune the | ||
| 588 | + // scanner steps over — but a *word* left with no span at all means the | ||
| 589 | + // dispatcher fell through, which is a defect and not a decision. | ||
| 590 | + const src = `from __future__ import annotations | ||
| 591 | + | ||
| 592 | +import asyncio | ||
| 593 | +from typing import Any | ||
| 594 | + | ||
| 595 | + | ||
| 596 | +async def gather(*tasks: Any, timeout: float = 1.0) -> list[Any]: | ||
| 597 | + async with asyncio.timeout(timeout): | ||
| 598 | + return await asyncio.gather(*tasks) | ||
| 599 | + | ||
| 600 | + | ||
| 601 | +class Registry(dict[str, int]): | ||
| 602 | + __slots__ = () | ||
| 603 | + | ||
| 604 | + def add(self, key: str, /, *, count: int = 1) -> None: | ||
| 605 | + self[key] = self.get(key, 0) + count | ||
| 606 | + | ||
| 607 | + def __repr__(self) -> str: | ||
| 608 | + return f"Registry({dict(self)!r})" | ||
| 609 | + | ||
| 610 | + | ||
| 611 | +lambda_ = lambda x: x if x else -x | ||
| 612 | +numbers = [n**2 for n in range(10) if n % 2 == 0] | ||
| 613 | +mapping = {k: v for k, v in zip("abc", [1, 2, 3])} | ||
| 614 | +` | ||
| 615 | + | ||
| 616 | + spans := Highlight(src) | ||
| 617 | + for line, text := range strings.Split(src, "\n") { | ||
| 618 | + for col, r := range []rune(text) { | ||
| 619 | + if !syntax.IsLetter(r) && !syntax.IsDigit(r) { | ||
| 620 | + continue | ||
| 621 | + } | ||
| 622 | + if _, ok := classAt(spans, line, col); !ok { | ||
| 623 | + t.Errorf("line %d column %d (%q) is covered by no span: %q", line, col, r, text) | ||
| 624 | + } | ||
| 625 | + } | ||
| 626 | + } | ||
| 627 | +} | ||
added
internal/pythonlang/settings.toml.tmpl +18 -0 | new file mode 100644 | ||
| @@ -0,0 +1,18 @@ | ||
| 1 | +# turbo-python project settings. | |
| 2 | +# | |
| 3 | +# These apply to everyone who opens this project in turbo-python. Delete this | |
| 4 | +# file and the editor falls back to its own defaults. | |
| 5 | + | |
| 6 | +[editor] | |
| 7 | + | |
| 8 | +# The colour theme to start in. `turbo-python -list-themes` lists them all. | |
| 9 | +# A -theme flag on the command line overrides this. | |
| 10 | +theme = %q | |
| 11 | + | |
| 12 | +# Write modified files by themselves, a short while after you stop typing. | |
| 13 | +# On, because a project that has gone to the trouble of having a settings file | |
| 14 | +# has said what it wants; set it to false and save, and it stops at once. | |
| 15 | +autosave = true | |
| 16 | + | |
| 17 | +# How long that while is. Any Go duration: "500ms", "2s", "1m". | |
| 18 | +autosave_delay = %q | |
| new file mode 100644 | |||
| @@ -0,0 +1,18 @@ | |||
| 1 | +# turbo-python project settings. | ||
| 2 | +# | ||
| 3 | +# These apply to everyone who opens this project in turbo-python. Delete this | ||
| 4 | +# file and the editor falls back to its own defaults. | ||
| 5 | + | ||
| 6 | +[editor] | ||
| 7 | + | ||
| 8 | +# The colour theme to start in. `turbo-python -list-themes` lists them all. | ||
| 9 | +# A -theme flag on the command line overrides this. | ||
| 10 | +theme = %q | ||
| 11 | + | ||
| 12 | +# Write modified files by themselves, a short while after you stop typing. | ||
| 13 | +# On, because a project that has gone to the trouble of having a settings file | ||
| 14 | +# has said what it wants; set it to false and save, and it stops at once. | ||
| 15 | +autosave = true | ||
| 16 | + | ||
| 17 | +# How long that while is. Any Go duration: "500ms", "2s", "1m". | ||
| 18 | +autosave_delay = %q | ||
added
internal/pythonlang/snippets.toml.tmpl +88 -0 | new file mode 100644 | ||
| @@ -0,0 +1,88 @@ | ||
| 1 | +# turbo-python snippets. | |
| 2 | +# | |
| 3 | +# Each [[snippet]] becomes one line of the Snippets menu. Snippets sharing a | |
| 4 | +# group appear together in a submenu of that name; one with no group goes into | |
| 5 | +# %s. A snippet is inserted at the cursor, and every line after the | |
| 6 | +# first is indented to match the line you inserted it on. | |
| 7 | +# | |
| 8 | +# languages restricts a snippet to files of those kinds, by the names the | |
| 9 | +# editor uses: python, toml, yaml, markdown, javascript, html, xml, dockerfile, | |
| 10 | +# bash. Leave it out and the snippet is offered everywhere. | |
| 11 | +# | |
| 12 | +# Bodies are indented with four spaces, never a tab: that is what PEP 8 asks | |
| 13 | +# for, and a tab inserted into a file indented with spaces is an indentation | |
| 14 | +# error rather than a formatting quibble. | |
| 15 | +# | |
| 16 | +# Your own snippets, shared across every project, go in: | |
| 17 | +# %s | |
| 18 | + | |
| 19 | +[[snippet]] | |
| 20 | +name = "main guard" | |
| 21 | +group = "Python" | |
| 22 | +languages = ["python"] | |
| 23 | +body = """ | |
| 24 | +def main() -> None: | |
| 25 | + ... | |
| 26 | + | |
| 27 | + | |
| 28 | +if __name__ == "__main__": | |
| 29 | + main()""" | |
| 30 | + | |
| 31 | +[[snippet]] | |
| 32 | +name = "class" | |
| 33 | +group = "Python" | |
| 34 | +languages = ["python"] | |
| 35 | +body = """ | |
| 36 | +class Thing: | |
| 37 | + def __init__(self, name: str) -> None: | |
| 38 | + self.name = name""" | |
| 39 | + | |
| 40 | +[[snippet]] | |
| 41 | +name = "match" | |
| 42 | +group = "Python" | |
| 43 | +languages = ["python"] | |
| 44 | +body = """ | |
| 45 | +match value: | |
| 46 | + case 0: | |
| 47 | + ... | |
| 48 | + case _: | |
| 49 | + ...""" | |
| 50 | + | |
| 51 | +[[snippet]] | |
| 52 | +name = "try / except" | |
| 53 | +group = "Python" | |
| 54 | +languages = ["python"] | |
| 55 | +body = """ | |
| 56 | +try: | |
| 57 | + ... | |
| 58 | +except ValueError as error: | |
| 59 | + raise SystemExit(error) from error""" | |
| 60 | + | |
| 61 | +[[snippet]] | |
| 62 | +name = "dataclass" | |
| 63 | +group = "Python" | |
| 64 | +languages = ["python"] | |
| 65 | +body = """ | |
| 66 | +@dataclass(frozen=True) | |
| 67 | +class Thing: | |
| 68 | + name: str | |
| 69 | + count: int = 0""" | |
| 70 | + | |
| 71 | +[[snippet]] | |
| 72 | +name = "test" | |
| 73 | +group = "Python" | |
| 74 | +languages = ["python"] | |
| 75 | +body = """ | |
| 76 | +def test_it_works() -> None: | |
| 77 | + assert 1 + 1 == 2""" | |
| 78 | + | |
| 79 | +[[snippet]] | |
| 80 | +group = "General" | |
| 81 | +name = "Hello" | |
| 82 | +body = "Hello!!!" | |
| 83 | + | |
| 84 | +[[snippet]] | |
| 85 | +group = "Markdown" | |
| 86 | +name = "Image" | |
| 87 | +languages = ["markdown"] | |
| 88 | +body = "" | |
| new file mode 100644 | |||
| @@ -0,0 +1,88 @@ | |||
| 1 | +# turbo-python snippets. | ||
| 2 | +# | ||
| 3 | +# Each [[snippet]] becomes one line of the Snippets menu. Snippets sharing a | ||
| 4 | +# group appear together in a submenu of that name; one with no group goes into | ||
| 5 | +# %s. A snippet is inserted at the cursor, and every line after the | ||
| 6 | +# first is indented to match the line you inserted it on. | ||
| 7 | +# | ||
| 8 | +# languages restricts a snippet to files of those kinds, by the names the | ||
| 9 | +# editor uses: python, toml, yaml, markdown, javascript, html, xml, dockerfile, | ||
| 10 | +# bash. Leave it out and the snippet is offered everywhere. | ||
| 11 | +# | ||
| 12 | +# Bodies are indented with four spaces, never a tab: that is what PEP 8 asks | ||
| 13 | +# for, and a tab inserted into a file indented with spaces is an indentation | ||
| 14 | +# error rather than a formatting quibble. | ||
| 15 | +# | ||
| 16 | +# Your own snippets, shared across every project, go in: | ||
| 17 | +# %s | ||
| 18 | + | ||
| 19 | +[[snippet]] | ||
| 20 | +name = "main guard" | ||
| 21 | +group = "Python" | ||
| 22 | +languages = ["python"] | ||
| 23 | +body = """ | ||
| 24 | +def main() -> None: | ||
| 25 | + ... | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +if __name__ == "__main__": | ||
| 29 | + main()""" | ||
| 30 | + | ||
| 31 | +[[snippet]] | ||
| 32 | +name = "class" | ||
| 33 | +group = "Python" | ||
| 34 | +languages = ["python"] | ||
| 35 | +body = """ | ||
| 36 | +class Thing: | ||
| 37 | + def __init__(self, name: str) -> None: | ||
| 38 | + self.name = name""" | ||
| 39 | + | ||
| 40 | +[[snippet]] | ||
| 41 | +name = "match" | ||
| 42 | +group = "Python" | ||
| 43 | +languages = ["python"] | ||
| 44 | +body = """ | ||
| 45 | +match value: | ||
| 46 | + case 0: | ||
| 47 | + ... | ||
| 48 | + case _: | ||
| 49 | + ...""" | ||
| 50 | + | ||
| 51 | +[[snippet]] | ||
| 52 | +name = "try / except" | ||
| 53 | +group = "Python" | ||
| 54 | +languages = ["python"] | ||
| 55 | +body = """ | ||
| 56 | +try: | ||
| 57 | + ... | ||
| 58 | +except ValueError as error: | ||
| 59 | + raise SystemExit(error) from error""" | ||
| 60 | + | ||
| 61 | +[[snippet]] | ||
| 62 | +name = "dataclass" | ||
| 63 | +group = "Python" | ||
| 64 | +languages = ["python"] | ||
| 65 | +body = """ | ||
| 66 | +@dataclass(frozen=True) | ||
| 67 | +class Thing: | ||
| 68 | + name: str | ||
| 69 | + count: int = 0""" | ||
| 70 | + | ||
| 71 | +[[snippet]] | ||
| 72 | +name = "test" | ||
| 73 | +group = "Python" | ||
| 74 | +languages = ["python"] | ||
| 75 | +body = """ | ||
| 76 | +def test_it_works() -> None: | ||
| 77 | + assert 1 + 1 == 2""" | ||
| 78 | + | ||
| 79 | +[[snippet]] | ||
| 80 | +group = "General" | ||
| 81 | +name = "Hello" | ||
| 82 | +body = "Hello!!!" | ||
| 83 | + | ||
| 84 | +[[snippet]] | ||
| 85 | +group = "Markdown" | ||
| 86 | +name = "Image" | ||
| 87 | +languages = ["markdown"] | ||
| 88 | +body = "" | ||
added
internal/pythonlang/templates.go +64 -0 | new file mode 100644 | ||
| @@ -0,0 +1,64 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +import _ "embed" | |
| 4 | + | |
| 5 | +// The starter files Turbo Python writes into a project's .turbo-python | |
| 6 | +// directory. | |
| 7 | +// | |
| 8 | +// They live in four files beside this one and are embedded into the binary at | |
| 9 | +// compile time. Written out as text rather than encoded from structs because | |
| 10 | +// they are meant to be read and edited by a person: the comments in them say | |
| 11 | +// what each key is for, which is the whole reason the editor offers to create | |
| 12 | +// them at all rather than only to read them. | |
| 13 | +// | |
| 14 | +// Their contents are the one part of these four files that is about Python | |
| 15 | +// rather than about editing, which is why they live here and not in turbo-core. | |
| 16 | +// | |
| 17 | +// **The .tmpl suffix is not decoration.** Each file is formatted with | |
| 18 | +// fmt.Sprintf before it is written, and settings.toml.tmpl holds `theme = %q` | |
| 19 | +// — which is not valid TOML. Naming it settings.toml would be a claim it | |
| 20 | +// cannot meet: a TOML linter would reject it, and Turbo Python itself would | |
| 21 | +// colour it as TOML and draw it as broken. The blanks each one takes are | |
| 22 | +// documented on profile.Templates, and templates_test.go holds them to it. | |
| 23 | + | |
| 24 | +// settingsTemplate is the settings file a project gets when it asks for one. | |
| 25 | +// | |
| 26 | +// autosave is on: a project that has gone to the trouble of creating a | |
| 27 | +// settings file has said what it wants, and the file is the visible, editable | |
| 28 | +// place to say otherwise. settings.Default() — what applies with no file at | |
| 29 | +// all — stays off. | |
| 30 | +// | |
| 31 | +//go:embed settings.toml.tmpl | |
| 32 | +var settingsTemplate string | |
| 33 | + | |
| 34 | +// snippetsTemplate is the snippets file a project gets when it asks for one. | |
| 35 | +// | |
| 36 | +// It lists every language name the editor knows in its `languages` comment, | |
| 37 | +// because that comment is where a user finds out what they may write there. A | |
| 38 | +// test iterates syntax.Registered() rather than a hardcoded list, so the | |
| 39 | +// comment cannot fall behind the registry. | |
| 40 | +// | |
| 41 | +//go:embed snippets.toml.tmpl | |
| 42 | +var snippetsTemplate string | |
| 43 | + | |
| 44 | +// toolsTemplate is the tools file a project gets when it asks for one. | |
| 45 | +// | |
| 46 | +// Six commands, and the two features that are invisible otherwise: a | |
| 47 | +// {{placeholder}} that asks for a value before the command runs, and the | |
| 48 | +// `menu` key that puts a tool in a menu of its own. | |
| 49 | +// | |
| 50 | +// The first of the six creates the virtual environment, because in Python that | |
| 51 | +// is the step that has to happen before any of the others can, and the one a | |
| 52 | +// newcomer to a project most often has not done yet. | |
| 53 | +// | |
| 54 | +//go:embed tools.toml.tmpl | |
| 55 | +var toolsTemplate string | |
| 56 | + | |
| 57 | +// agentsTemplate is the agents file a project gets when it asks for one. | |
| 58 | +// | |
| 59 | +// It takes two blanks, in this order: the editor's own project directory — | |
| 60 | +// which the example agent's arguments point into — and the path to the user's | |
| 61 | +// own agents file, which a comment names. | |
| 62 | +// | |
| 63 | +//go:embed acp.toml.tmpl | |
| 64 | +var agentsTemplate string | |
| new file mode 100644 | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +import _ "embed" | ||
| 4 | + | ||
| 5 | +// The starter files Turbo Python writes into a project's .turbo-python | ||
| 6 | +// directory. | ||
| 7 | +// | ||
| 8 | +// They live in four files beside this one and are embedded into the binary at | ||
| 9 | +// compile time. Written out as text rather than encoded from structs because | ||
| 10 | +// they are meant to be read and edited by a person: the comments in them say | ||
| 11 | +// what each key is for, which is the whole reason the editor offers to create | ||
| 12 | +// them at all rather than only to read them. | ||
| 13 | +// | ||
| 14 | +// Their contents are the one part of these four files that is about Python | ||
| 15 | +// rather than about editing, which is why they live here and not in turbo-core. | ||
| 16 | +// | ||
| 17 | +// **The .tmpl suffix is not decoration.** Each file is formatted with | ||
| 18 | +// fmt.Sprintf before it is written, and settings.toml.tmpl holds `theme = %q` | ||
| 19 | +// — which is not valid TOML. Naming it settings.toml would be a claim it | ||
| 20 | +// cannot meet: a TOML linter would reject it, and Turbo Python itself would | ||
| 21 | +// colour it as TOML and draw it as broken. The blanks each one takes are | ||
| 22 | +// documented on profile.Templates, and templates_test.go holds them to it. | ||
| 23 | + | ||
| 24 | +// settingsTemplate is the settings file a project gets when it asks for one. | ||
| 25 | +// | ||
| 26 | +// autosave is on: a project that has gone to the trouble of creating a | ||
| 27 | +// settings file has said what it wants, and the file is the visible, editable | ||
| 28 | +// place to say otherwise. settings.Default() — what applies with no file at | ||
| 29 | +// all — stays off. | ||
| 30 | +// | ||
| 31 | +//go:embed settings.toml.tmpl | ||
| 32 | +var settingsTemplate string | ||
| 33 | + | ||
| 34 | +// snippetsTemplate is the snippets file a project gets when it asks for one. | ||
| 35 | +// | ||
| 36 | +// It lists every language name the editor knows in its `languages` comment, | ||
| 37 | +// because that comment is where a user finds out what they may write there. A | ||
| 38 | +// test iterates syntax.Registered() rather than a hardcoded list, so the | ||
| 39 | +// comment cannot fall behind the registry. | ||
| 40 | +// | ||
| 41 | +//go:embed snippets.toml.tmpl | ||
| 42 | +var snippetsTemplate string | ||
| 43 | + | ||
| 44 | +// toolsTemplate is the tools file a project gets when it asks for one. | ||
| 45 | +// | ||
| 46 | +// Six commands, and the two features that are invisible otherwise: a | ||
| 47 | +// {{placeholder}} that asks for a value before the command runs, and the | ||
| 48 | +// `menu` key that puts a tool in a menu of its own. | ||
| 49 | +// | ||
| 50 | +// The first of the six creates the virtual environment, because in Python that | ||
| 51 | +// is the step that has to happen before any of the others can, and the one a | ||
| 52 | +// newcomer to a project most often has not done yet. | ||
| 53 | +// | ||
| 54 | +//go:embed tools.toml.tmpl | ||
| 55 | +var toolsTemplate string | ||
| 56 | + | ||
| 57 | +// agentsTemplate is the agents file a project gets when it asks for one. | ||
| 58 | +// | ||
| 59 | +// It takes two blanks, in this order: the editor's own project directory — | ||
| 60 | +// which the example agent's arguments point into — and the path to the user's | ||
| 61 | +// own agents file, which a comment names. | ||
| 62 | +// | ||
| 63 | +//go:embed acp.toml.tmpl | ||
| 64 | +var agentsTemplate string | ||
added
internal/pythonlang/templates_test.go +483 -0 | new file mode 100644 | ||
| @@ -0,0 +1,483 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "fmt" | |
| 5 | + "os" | |
| 6 | + "strings" | |
| 7 | + "testing" | |
| 8 | + | |
| 9 | + "rickub.com/turbo-editors/turbo-core/settings" | |
| 10 | + "rickub.com/turbo-editors/turbo-core/snippets" | |
| 11 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 12 | + "rickub.com/turbo-editors/turbo-core/tools" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// The starter files Turbo Python writes are the one part of a project's | |
| 16 | +// .turbo-python directory that is about Python, so this is where what is *in* | |
| 17 | +// them is checked. That the file written is the profile's template at all is | |
| 18 | +// turbo-core's test. | |
| 19 | + | |
| 20 | +// noUserSnippets points the user's own snippets at an empty directory, so a | |
| 21 | +// test never reads whoever is running it. | |
| 22 | +func noUserSnippets(t *testing.T) { | |
| 23 | + t.Helper() | |
| 24 | + t.Setenv(Profile().SnippetDirEnvVar(), t.TempDir()) | |
| 25 | +} | |
| 26 | + | |
| 27 | +// createTools writes a project's tools file and returns the project directory. | |
| 28 | +func createTools(t *testing.T) string { | |
| 29 | + t.Helper() | |
| 30 | + | |
| 31 | + dir := t.TempDir() | |
| 32 | + if _, err := tools.Create(Profile(), dir); err != nil { | |
| 33 | + t.Fatalf("tools.Create() error = %v", err) | |
| 34 | + } | |
| 35 | + return dir | |
| 36 | +} | |
| 37 | + | |
| 38 | +// createSnippets writes a project's snippets file and returns the directory. | |
| 39 | +func createSnippets(t *testing.T) string { | |
| 40 | + t.Helper() | |
| 41 | + noUserSnippets(t) | |
| 42 | + | |
| 43 | + dir := t.TempDir() | |
| 44 | + if _, err := snippets.Create(Profile(), dir); err != nil { | |
| 45 | + t.Fatalf("snippets.Create() error = %v", err) | |
| 46 | + } | |
| 47 | + return dir | |
| 48 | +} | |
| 49 | + | |
| 50 | +// createSettings writes a project's settings file and returns the directory. | |
| 51 | +func createSettings(t *testing.T) string { | |
| 52 | + t.Helper() | |
| 53 | + | |
| 54 | + dir := t.TempDir() | |
| 55 | + if _, err := settings.Create(Profile(), dir, "turbo-classic"); err != nil { | |
| 56 | + t.Fatalf("settings.Create() error = %v", err) | |
| 57 | + } | |
| 58 | + return dir | |
| 59 | +} | |
| 60 | + | |
| 61 | +// loadTools reads a project's tools, failing the test if it cannot. | |
| 62 | +func loadTools(t *testing.T, dir string) tools.List { | |
| 63 | + t.Helper() | |
| 64 | + | |
| 65 | + list, err := tools.Load(Profile(), dir) | |
| 66 | + if err != nil { | |
| 67 | + t.Fatalf("tools.Load(%q) error = %v", dir, err) | |
| 68 | + } | |
| 69 | + return list | |
| 70 | +} | |
| 71 | + | |
| 72 | +// loadSnippets reads a project's snippets, failing the test if it cannot. | |
| 73 | +func loadSnippets(t *testing.T, dir string) snippets.List { | |
| 74 | + t.Helper() | |
| 75 | + | |
| 76 | + list, err := snippets.Load(Profile(), dir) | |
| 77 | + if err != nil { | |
| 78 | + t.Fatalf("snippets.Load(%q) error = %v", dir, err) | |
| 79 | + } | |
| 80 | + return list | |
| 81 | +} | |
| 82 | + | |
| 83 | +// readFile returns a file's contents. | |
| 84 | +func readFile(t *testing.T, path string) string { | |
| 85 | + t.Helper() | |
| 86 | + | |
| 87 | + data, err := os.ReadFile(path) | |
| 88 | + if err != nil { | |
| 89 | + t.Fatalf("reading %s: %v", path, err) | |
| 90 | + } | |
| 91 | + return string(data) | |
| 92 | +} | |
| 93 | + | |
| 94 | +// plain strips the tilde hot-key markers from a label. | |
| 95 | +func plain(label string) string { return strings.ReplaceAll(label, "~", "") } | |
| 96 | + | |
| 97 | +// hotKey returns the character between the tildes, or 0 when there is none. | |
| 98 | +func hotKey(label string) rune { | |
| 99 | + first := strings.IndexByte(label, '~') | |
| 100 | + if first < 0 || first+1 >= len(label) { | |
| 101 | + return 0 | |
| 102 | + } | |
| 103 | + return rune(label[first+1]) | |
| 104 | +} | |
| 105 | + | |
| 106 | +// --- the tools file --------------------------------------------------------- | |
| 107 | + | |
| 108 | +func TestTheCreatedToolsFileHoldsTheSixCommandsAProjectRuns(t *testing.T) { | |
| 109 | + // These are what a Python project runs on itself, and they are the reason | |
| 110 | + // the file exists at all. Everything goes through uv, so none of them needs | |
| 111 | + // an environment to have been activated first. | |
| 112 | + byName := map[string]string{} | |
| 113 | + for _, tool := range loadTools(t, createTools(t)).In("Python") { | |
| 114 | + byName[plain(tool.Name)] = tool.Command | |
| 115 | + } | |
| 116 | + | |
| 117 | + want := map[string]string{ | |
| 118 | + "Environment": "uv venv {{directory, usually .venv}}", | |
| 119 | + "Sync": "uv sync", | |
| 120 | + "Format": "uv run ruff format .", | |
| 121 | + "Lint": "uv run ruff check .", | |
| 122 | + "Test": "uv run pytest", | |
| 123 | + "Run": "uv run {{script}}", | |
| 124 | + } | |
| 125 | + for name, command := range want { | |
| 126 | + if got := byName[name]; got != command { | |
| 127 | + t.Errorf("%s runs %q, want %q", name, got, command) | |
| 128 | + } | |
| 129 | + } | |
| 130 | + if len(byName) != len(want) { | |
| 131 | + t.Errorf("the Python menu holds %d tools, want %d: %v", len(byName), len(want), byName) | |
| 132 | + } | |
| 133 | +} | |
| 134 | + | |
| 135 | +// Creating the environment is the step in Python that has to happen before any | |
| 136 | +// of the others can, and the one a newcomer to a project most often has not | |
| 137 | +// done — so it is the first item in the menu rather than the last. | |
| 138 | +func TestCreatingTheEnvironmentIsTheFirstToolInTheMenu(t *testing.T) { | |
| 139 | + python := loadTools(t, createTools(t)).In("Python") | |
| 140 | + | |
| 141 | + if len(python) == 0 { | |
| 142 | + t.Fatal("the Python menu is empty") | |
| 143 | + } | |
| 144 | + if got := plain(python[0].Name); got != "Environment" { | |
| 145 | + t.Errorf("the first tool in the menu is %q, want %q", got, "Environment") | |
| 146 | + } | |
| 147 | +} | |
| 148 | + | |
| 149 | +// The directory is asked for rather than fixed: .venv is the usual answer and | |
| 150 | +// not the only one, and a tool that asks is also the file's live demonstration | |
| 151 | +// that asking is possible. | |
| 152 | +func TestTheEnvironmentToolAsksWhereToPutIt(t *testing.T) { | |
| 153 | + for _, tool := range loadTools(t, createTools(t)).Tools() { | |
| 154 | + if plain(tool.Name) != "Environment" { | |
| 155 | + continue | |
| 156 | + } | |
| 157 | + | |
| 158 | + asked := tool.Placeholders() | |
| 159 | + if len(asked) != 1 { | |
| 160 | + t.Fatalf("Environment asks for %d values, want 1: %v", len(asked), asked) | |
| 161 | + } | |
| 162 | + if !strings.Contains(asked[0].Label, ".venv") { | |
| 163 | + t.Errorf("it asks for %q, which never mentions .venv", asked[0].Label) | |
| 164 | + } | |
| 165 | + if asked[0].Raw { | |
| 166 | + t.Errorf("it asks for %q unquoted; a directory with a space in it would become two arguments", asked[0].Label) | |
| 167 | + } | |
| 168 | + return | |
| 169 | + } | |
| 170 | + t.Fatal("there is no Environment tool") | |
| 171 | +} | |
| 172 | + | |
| 173 | +func TestOnlyTheTwoToolsThatNeedAValueAskForOne(t *testing.T) { | |
| 174 | + // Every other command is complete as it stands, and a box in front of a | |
| 175 | + // command that has nothing to ask is a keystroke for nothing. | |
| 176 | + asking := map[string]bool{"Environment": true, "Run": true} | |
| 177 | + | |
| 178 | + for _, tool := range loadTools(t, createTools(t)).Tools() { | |
| 179 | + name := plain(tool.Name) | |
| 180 | + if got := len(tool.Placeholders()) > 0; got != asking[name] { | |
| 181 | + t.Errorf("%s asks for a value: %t, want %t (%q)", name, got, asking[name], tool.Command) | |
| 182 | + } | |
| 183 | + } | |
| 184 | +} | |
| 185 | + | |
| 186 | +func TestTheCreatedToolsCarryHotKeysUniqueWithinTheirMenu(t *testing.T) { | |
| 187 | + // Six items in a menu are worth reaching with one keystroke each. Two menus | |
| 188 | + // may each have an E, which is why the check is per menu. | |
| 189 | + list := loadTools(t, createTools(t)) | |
| 190 | + | |
| 191 | + for _, menu := range list.MenuNames() { | |
| 192 | + seen := map[rune]string{} | |
| 193 | + for _, tool := range list.In(menu) { | |
| 194 | + key := hotKey(tool.Name) | |
| 195 | + if key == 0 { | |
| 196 | + t.Errorf("%q in the %s menu has no hot key", tool.Name, menu) | |
| 197 | + continue | |
| 198 | + } | |
| 199 | + if other, clash := seen[key]; clash { | |
| 200 | + t.Errorf("%q and %q in the %s menu both answer to %c", other, tool.Name, menu, key) | |
| 201 | + } | |
| 202 | + seen[key] = tool.Name | |
| 203 | + } | |
| 204 | + } | |
| 205 | +} | |
| 206 | + | |
| 207 | +func TestTheCreatedToolsFileNamesAnOutputForEveryTool(t *testing.T) { | |
| 208 | + // The key is the interesting part of the format, and a file where it only | |
| 209 | + // appears once is a file where nobody notices it exists. | |
| 210 | + for _, tool := range loadTools(t, createTools(t)).Tools() { | |
| 211 | + if tool.Output == "" { | |
| 212 | + t.Errorf("%q leaves its output to the default rather than saying it", tool.Name) | |
| 213 | + } | |
| 214 | + } | |
| 215 | +} | |
| 216 | + | |
| 217 | +func TestRunIsTheOneToolchainCommandInATerminal(t *testing.T) { | |
| 218 | + // A Python script usually reads the keyboard, runs long, or both, and a | |
| 219 | + // popup can answer neither. The Echo example is in a terminal too, but it | |
| 220 | + // is in a menu of its own and is there to demonstrate the menu key. | |
| 221 | + for _, tool := range loadTools(t, createTools(t)).In("Python") { | |
| 222 | + want := tools.OutputPopup | |
| 223 | + if plain(tool.Name) == "Run" { | |
| 224 | + want = tools.OutputTerminal | |
| 225 | + } | |
| 226 | + if got := tool.Where(); got != want { | |
| 227 | + t.Errorf("%s goes to %q, want %q", plain(tool.Name), got, want) | |
| 228 | + } | |
| 229 | + } | |
| 230 | +} | |
| 231 | + | |
| 232 | +func TestTheCreatedToolsFileExplainsItself(t *testing.T) { | |
| 233 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | |
| 234 | + | |
| 235 | + for _, want := range []string{"[[tool]]", "sh -c", "hot key", "popup", "terminal", "editor"} { | |
| 236 | + if !strings.Contains(contents, want) { | |
| 237 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | |
| 238 | + } | |
| 239 | + } | |
| 240 | +} | |
| 241 | + | |
| 242 | +func TestTheCreatedToolsFileNamesThePythonMenuAndNoOtherEditorsMenu(t *testing.T) { | |
| 243 | + // The comments explain which menu a tool lands in by naming it. Naming the | |
| 244 | + // menu of the editor this one was adapted from is the copy-and-paste | |
| 245 | + // mistake this catches, and it is invisible to every other test. | |
| 246 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | |
| 247 | + | |
| 248 | + if !strings.Contains(contents, "Python menu") { | |
| 249 | + t.Errorf("the created file never names the Python menu:\n%s", contents) | |
| 250 | + } | |
| 251 | + for _, other := range []string{"Go menu", "Rust menu", "turbo-go", "turbo-rust", "cargo"} { | |
| 252 | + if strings.Contains(contents, other) { | |
| 253 | + t.Errorf("the created file still talks about %q:\n%s", other, contents) | |
| 254 | + } | |
| 255 | + } | |
| 256 | +} | |
| 257 | + | |
| 258 | +func TestTheCreatedToolsFileShowsHowToUseAnotherMenu(t *testing.T) { | |
| 259 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | |
| 260 | + | |
| 261 | + for _, want := range []string{"menu says which menu", `menu = "Tools"`} { | |
| 262 | + if !strings.Contains(contents, want) { | |
| 263 | + t.Errorf("the created file never shows %q:\n%s", want, contents) | |
| 264 | + } | |
| 265 | + } | |
| 266 | +} | |
| 267 | + | |
| 268 | +func TestTheCreatedToolsFileExplainsHowToAskForAValue(t *testing.T) { | |
| 269 | + // A parameterised tool is only discoverable if the file people get says the | |
| 270 | + // syntax exists. The double-brace warning is here too, because somebody | |
| 271 | + // reading this file may well have an awk one-liner in mind. | |
| 272 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | |
| 273 | + | |
| 274 | + for _, want := range []string{ | |
| 275 | + "{{label}}", | |
| 276 | + "uv add {{package}}", | |
| 277 | + "{{extra flags...}}", | |
| 278 | + "Double braces, not single", | |
| 279 | + } { | |
| 280 | + if !strings.Contains(contents, want) { | |
| 281 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | |
| 282 | + } | |
| 283 | + } | |
| 284 | +} | |
| 285 | + | |
| 286 | +// --- the snippets file ------------------------------------------------------ | |
| 287 | + | |
| 288 | +func TestTheCreatedSnippetsFileHoldsUsablePythonSnippets(t *testing.T) { | |
| 289 | + groups := loadSnippets(t, createSnippets(t)).Groups(string(Language)) | |
| 290 | + | |
| 291 | + if len(groups) == 0 { | |
| 292 | + t.Fatal("the created file offers nothing at all in a Python file") | |
| 293 | + } | |
| 294 | + for _, group := range groups { | |
| 295 | + for _, snippet := range group.Snippets { | |
| 296 | + if snippet.Name == "" || snippet.Body == "" { | |
| 297 | + t.Errorf("the created file holds an unusable snippet %+v", snippet) | |
| 298 | + } | |
| 299 | + } | |
| 300 | + } | |
| 301 | +} | |
| 302 | + | |
| 303 | +func TestTheCreatedSnippetsIndentWithFourSpacesTheWayPEP8Does(t *testing.T) { | |
| 304 | + // A tab inserted into a file indented with spaces is an indentation error | |
| 305 | + // in Python, not a formatting quibble: the file stops running. | |
| 306 | + for _, group := range loadSnippets(t, createSnippets(t)).Groups(string(Language)) { | |
| 307 | + for _, snippet := range group.Snippets { | |
| 308 | + if strings.Contains(snippet.Body, "\t") { | |
| 309 | + t.Errorf("%q indents with a tab:\n%q", snippet.Name, snippet.Body) | |
| 310 | + } | |
| 311 | + for _, line := range strings.Split(snippet.Body, "\n") { | |
| 312 | + indent := len(line) - len(strings.TrimLeft(line, " ")) | |
| 313 | + if indent%4 != 0 { | |
| 314 | + t.Errorf("%q has a line indented by %d spaces:\n%q", snippet.Name, indent, line) | |
| 315 | + } | |
| 316 | + } | |
| 317 | + } | |
| 318 | + } | |
| 319 | +} | |
| 320 | + | |
| 321 | +// Every snippet must be Python that runs, not Python that looks right — the | |
| 322 | +// scanner is the nearest thing to a parser this repository has, and a snippet | |
| 323 | +// whose whole body comes out as one colour is a snippet with an unclosed | |
| 324 | +// string in it. | |
| 325 | +func TestEverySnippetBodyColoursAsMoreThanOneThing(t *testing.T) { | |
| 326 | + for _, group := range loadSnippets(t, createSnippets(t)).Groups(string(Language)) { | |
| 327 | + for _, snippet := range group.Snippets { | |
| 328 | + classes := map[syntax.Class]bool{} | |
| 329 | + for _, line := range Highlight(snippet.Body) { | |
| 330 | + for _, span := range line { | |
| 331 | + classes[span.Class] = true | |
| 332 | + } | |
| 333 | + } | |
| 334 | + if len(classes) < 2 { | |
| 335 | + t.Errorf("%q colours as %d classes:\n%s", snippet.Name, len(classes), snippet.Body) | |
| 336 | + } | |
| 337 | + } | |
| 338 | + } | |
| 339 | +} | |
| 340 | + | |
| 341 | +func TestTheCreatedSnippetsFileExplainsItself(t *testing.T) { | |
| 342 | + contents := readFile(t, snippets.ProjectPath(Profile(), createSnippets(t))) | |
| 343 | + | |
| 344 | + for _, want := range []string{"[[snippet]]", "languages", "group", "General", snippets.UserPath(Profile())} { | |
| 345 | + if !strings.Contains(contents, want) { | |
| 346 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | |
| 347 | + } | |
| 348 | + } | |
| 349 | +} | |
| 350 | + | |
| 351 | +func TestTheCreatedSnippetsFileListsEveryLanguageTheEditorKnows(t *testing.T) { | |
| 352 | + // The comment is where a user finds out what they may write in a languages | |
| 353 | + // key. One that omits a language the editor colours sends them looking for | |
| 354 | + // a feature that is already there. Iterating the registry rather than a | |
| 355 | + // list is what stops the comment falling behind it, as turbo-rust's did | |
| 356 | + // when turbo-core learnt YAML, XML and Dockerfiles. | |
| 357 | + Register() | |
| 358 | + contents := readFile(t, snippets.ProjectPath(Profile(), createSnippets(t))) | |
| 359 | + | |
| 360 | + for _, language := range syntax.Registered() { | |
| 361 | + if !strings.Contains(contents, string(language)) { | |
| 362 | + t.Errorf("the created file never mentions the %q language:\n%s", language, contents) | |
| 363 | + } | |
| 364 | + } | |
| 365 | +} | |
| 366 | + | |
| 367 | +// --- the settings file ------------------------------------------------------ | |
| 368 | + | |
| 369 | +func TestTheCreatedSettingsFileExplainsItself(t *testing.T) { | |
| 370 | + contents := readFile(t, settings.Path(Profile(), createSettings(t))) | |
| 371 | + | |
| 372 | + for _, want := range []string{"theme", "autosave", "autosave_delay", "-list-themes"} { | |
| 373 | + if !strings.Contains(contents, want) { | |
| 374 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | |
| 375 | + } | |
| 376 | + } | |
| 377 | +} | |
| 378 | + | |
| 379 | +func TestTheCreatedSettingsFileTurnsAutosaveOn(t *testing.T) { | |
| 380 | + // A project that has gone to the trouble of creating a settings file has | |
| 381 | + // said what it wants. The file is the visible, editable place to say | |
| 382 | + // otherwise, which is why this default lives here and not in the library. | |
| 383 | + project := createSettings(t) | |
| 384 | + | |
| 385 | + loaded, err := settings.Load(Profile(), project) | |
| 386 | + if err != nil { | |
| 387 | + t.Fatalf("settings.Load() error = %v", err) | |
| 388 | + } | |
| 389 | + if !loaded.Autosave { | |
| 390 | + t.Errorf("the created settings file leaves autosave off:\n%s", readFile(t, settings.Path(Profile(), project))) | |
| 391 | + } | |
| 392 | + if loaded.AutosaveDelay != settings.DefaultAutosaveDelay { | |
| 393 | + t.Errorf("AutosaveDelay = %v, want the library default %v", loaded.AutosaveDelay, settings.DefaultAutosaveDelay) | |
| 394 | + } | |
| 395 | +} | |
| 396 | + | |
| 397 | +func TestAProjectWithNoSettingsFileStillDoesNotAutosave(t *testing.T) { | |
| 398 | + // The other half of the decision. Turning autosave on for a project that | |
| 399 | + // never opted in would mean the editor writing to disk in any directory it | |
| 400 | + // is started in, which is a different and much larger claim. | |
| 401 | + if settings.Default().Autosave { | |
| 402 | + t.Error("settings.Default() autosaves; a project with no settings file never opted in") | |
| 403 | + } | |
| 404 | +} | |
| 405 | + | |
| 406 | +// --- the contract the three templates are held to --------------------------- | |
| 407 | + | |
| 408 | +// The three embedded templates and the blanks profile.Templates says each one | |
| 409 | +// takes. Kept together so that adding a verb to a .tmpl file without saying so | |
| 410 | +// here fails, which is the guard the constants used to get for free by sitting | |
| 411 | +// next to the contract. | |
| 412 | +var embeddedTemplates = []struct { | |
| 413 | + name string | |
| 414 | + body string | |
| 415 | + verb string | |
| 416 | + blanks int | |
| 417 | + filledBy []any | |
| 418 | +}{ | |
| 419 | + {"settings.toml.tmpl", settingsTemplate, "%q", 2, []any{"turbo-classic", "2s"}}, | |
| 420 | + {"snippets.toml.tmpl", snippetsTemplate, "%s", 2, []any{"General", "/tmp/snippets.toml"}}, | |
| 421 | + {"tools.toml.tmpl", toolsTemplate, "%", 0, nil}, | |
| 422 | +} | |
| 423 | + | |
| 424 | +func TestEveryTemplateIsEmbeddedAndNotEmpty(t *testing.T) { | |
| 425 | + // go:embed fails to compile when a file is missing, but an empty file | |
| 426 | + // compiles happily and writes an empty starter file into somebody's | |
| 427 | + // project. | |
| 428 | + for _, template := range embeddedTemplates { | |
| 429 | + if len(template.body) == 0 { | |
| 430 | + t.Errorf("%s embedded as nothing", template.name) | |
| 431 | + } | |
| 432 | + } | |
| 433 | +} | |
| 434 | + | |
| 435 | +func TestEveryTemplateTakesTheBlanksItsContractPromises(t *testing.T) { | |
| 436 | + // profile.Templates documents the count and the verb of each. The templates | |
| 437 | + // live in files of their own, so nothing but this notices a verb added, | |
| 438 | + // removed, or changed. | |
| 439 | + for _, template := range embeddedTemplates { | |
| 440 | + if got := strings.Count(template.body, template.verb); got != template.blanks { | |
| 441 | + t.Errorf("%s holds %d %q, want %d", template.name, got, template.verb, template.blanks) | |
| 442 | + } | |
| 443 | + } | |
| 444 | +} | |
| 445 | + | |
| 446 | +func TestFillingATemplateLeavesNoFormattingMarker(t *testing.T) { | |
| 447 | + // Go writes %!q(MISSING) or %!(EXTRA …) into the output rather than | |
| 448 | + // failing, so a template with the wrong number of blanks produces a file | |
| 449 | + // that is written, opened, and wrong. | |
| 450 | + for _, template := range embeddedTemplates { | |
| 451 | + filled := template.body | |
| 452 | + if template.filledBy != nil { | |
| 453 | + filled = fmt.Sprintf(template.body, template.filledBy...) | |
| 454 | + } | |
| 455 | + if strings.Contains(filled, "%!") { | |
| 456 | + t.Errorf("%s filled to:\n%s", template.name, filled) | |
| 457 | + } | |
| 458 | + } | |
| 459 | +} | |
| 460 | + | |
| 461 | +func TestEveryTemplateNamesThisEditorAndNotTheOnesItWasAdaptedFrom(t *testing.T) { | |
| 462 | + // The three templates started as Turbo Rust's. A leftover "turbo-rust" in a | |
| 463 | + // file written into somebody's Python project is the whole class of mistake | |
| 464 | + // this catches. | |
| 465 | + templates := map[string]string{ | |
| 466 | + "settings": settingsTemplate, | |
| 467 | + "snippets": snippetsTemplate, | |
| 468 | + "tools": toolsTemplate, | |
| 469 | + } | |
| 470 | + | |
| 471 | + for name, template := range templates { | |
| 472 | + t.Run(name, func(t *testing.T) { | |
| 473 | + for _, other := range []string{"turbo-go", "turbo-rust", "cargo", "gopls", "rust-analyzer"} { | |
| 474 | + if strings.Contains(template, other) { | |
| 475 | + t.Errorf("the %s template still says %q:\n%s", name, other, template) | |
| 476 | + } | |
| 477 | + } | |
| 478 | + if !strings.Contains(template, Slug) { | |
| 479 | + t.Errorf("the %s template never names %s:\n%s", name, Slug, template) | |
| 480 | + } | |
| 481 | + }) | |
| 482 | + } | |
| 483 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,483 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "fmt" | ||
| 5 | + "os" | ||
| 6 | + "strings" | ||
| 7 | + "testing" | ||
| 8 | + | ||
| 9 | + "rickub.com/turbo-editors/turbo-core/settings" | ||
| 10 | + "rickub.com/turbo-editors/turbo-core/snippets" | ||
| 11 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 12 | + "rickub.com/turbo-editors/turbo-core/tools" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// The starter files Turbo Python writes are the one part of a project's | ||
| 16 | +// .turbo-python directory that is about Python, so this is where what is *in* | ||
| 17 | +// them is checked. That the file written is the profile's template at all is | ||
| 18 | +// turbo-core's test. | ||
| 19 | + | ||
| 20 | +// noUserSnippets points the user's own snippets at an empty directory, so a | ||
| 21 | +// test never reads whoever is running it. | ||
| 22 | +func noUserSnippets(t *testing.T) { | ||
| 23 | + t.Helper() | ||
| 24 | + t.Setenv(Profile().SnippetDirEnvVar(), t.TempDir()) | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +// createTools writes a project's tools file and returns the project directory. | ||
| 28 | +func createTools(t *testing.T) string { | ||
| 29 | + t.Helper() | ||
| 30 | + | ||
| 31 | + dir := t.TempDir() | ||
| 32 | + if _, err := tools.Create(Profile(), dir); err != nil { | ||
| 33 | + t.Fatalf("tools.Create() error = %v", err) | ||
| 34 | + } | ||
| 35 | + return dir | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +// createSnippets writes a project's snippets file and returns the directory. | ||
| 39 | +func createSnippets(t *testing.T) string { | ||
| 40 | + t.Helper() | ||
| 41 | + noUserSnippets(t) | ||
| 42 | + | ||
| 43 | + dir := t.TempDir() | ||
| 44 | + if _, err := snippets.Create(Profile(), dir); err != nil { | ||
| 45 | + t.Fatalf("snippets.Create() error = %v", err) | ||
| 46 | + } | ||
| 47 | + return dir | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +// createSettings writes a project's settings file and returns the directory. | ||
| 51 | +func createSettings(t *testing.T) string { | ||
| 52 | + t.Helper() | ||
| 53 | + | ||
| 54 | + dir := t.TempDir() | ||
| 55 | + if _, err := settings.Create(Profile(), dir, "turbo-classic"); err != nil { | ||
| 56 | + t.Fatalf("settings.Create() error = %v", err) | ||
| 57 | + } | ||
| 58 | + return dir | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +// loadTools reads a project's tools, failing the test if it cannot. | ||
| 62 | +func loadTools(t *testing.T, dir string) tools.List { | ||
| 63 | + t.Helper() | ||
| 64 | + | ||
| 65 | + list, err := tools.Load(Profile(), dir) | ||
| 66 | + if err != nil { | ||
| 67 | + t.Fatalf("tools.Load(%q) error = %v", dir, err) | ||
| 68 | + } | ||
| 69 | + return list | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +// loadSnippets reads a project's snippets, failing the test if it cannot. | ||
| 73 | +func loadSnippets(t *testing.T, dir string) snippets.List { | ||
| 74 | + t.Helper() | ||
| 75 | + | ||
| 76 | + list, err := snippets.Load(Profile(), dir) | ||
| 77 | + if err != nil { | ||
| 78 | + t.Fatalf("snippets.Load(%q) error = %v", dir, err) | ||
| 79 | + } | ||
| 80 | + return list | ||
| 81 | +} | ||
| 82 | + | ||
| 83 | +// readFile returns a file's contents. | ||
| 84 | +func readFile(t *testing.T, path string) string { | ||
| 85 | + t.Helper() | ||
| 86 | + | ||
| 87 | + data, err := os.ReadFile(path) | ||
| 88 | + if err != nil { | ||
| 89 | + t.Fatalf("reading %s: %v", path, err) | ||
| 90 | + } | ||
| 91 | + return string(data) | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +// plain strips the tilde hot-key markers from a label. | ||
| 95 | +func plain(label string) string { return strings.ReplaceAll(label, "~", "") } | ||
| 96 | + | ||
| 97 | +// hotKey returns the character between the tildes, or 0 when there is none. | ||
| 98 | +func hotKey(label string) rune { | ||
| 99 | + first := strings.IndexByte(label, '~') | ||
| 100 | + if first < 0 || first+1 >= len(label) { | ||
| 101 | + return 0 | ||
| 102 | + } | ||
| 103 | + return rune(label[first+1]) | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +// --- the tools file --------------------------------------------------------- | ||
| 107 | + | ||
| 108 | +func TestTheCreatedToolsFileHoldsTheSixCommandsAProjectRuns(t *testing.T) { | ||
| 109 | + // These are what a Python project runs on itself, and they are the reason | ||
| 110 | + // the file exists at all. Everything goes through uv, so none of them needs | ||
| 111 | + // an environment to have been activated first. | ||
| 112 | + byName := map[string]string{} | ||
| 113 | + for _, tool := range loadTools(t, createTools(t)).In("Python") { | ||
| 114 | + byName[plain(tool.Name)] = tool.Command | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + want := map[string]string{ | ||
| 118 | + "Environment": "uv venv {{directory, usually .venv}}", | ||
| 119 | + "Sync": "uv sync", | ||
| 120 | + "Format": "uv run ruff format .", | ||
| 121 | + "Lint": "uv run ruff check .", | ||
| 122 | + "Test": "uv run pytest", | ||
| 123 | + "Run": "uv run {{script}}", | ||
| 124 | + } | ||
| 125 | + for name, command := range want { | ||
| 126 | + if got := byName[name]; got != command { | ||
| 127 | + t.Errorf("%s runs %q, want %q", name, got, command) | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + if len(byName) != len(want) { | ||
| 131 | + t.Errorf("the Python menu holds %d tools, want %d: %v", len(byName), len(want), byName) | ||
| 132 | + } | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +// Creating the environment is the step in Python that has to happen before any | ||
| 136 | +// of the others can, and the one a newcomer to a project most often has not | ||
| 137 | +// done — so it is the first item in the menu rather than the last. | ||
| 138 | +func TestCreatingTheEnvironmentIsTheFirstToolInTheMenu(t *testing.T) { | ||
| 139 | + python := loadTools(t, createTools(t)).In("Python") | ||
| 140 | + | ||
| 141 | + if len(python) == 0 { | ||
| 142 | + t.Fatal("the Python menu is empty") | ||
| 143 | + } | ||
| 144 | + if got := plain(python[0].Name); got != "Environment" { | ||
| 145 | + t.Errorf("the first tool in the menu is %q, want %q", got, "Environment") | ||
| 146 | + } | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +// The directory is asked for rather than fixed: .venv is the usual answer and | ||
| 150 | +// not the only one, and a tool that asks is also the file's live demonstration | ||
| 151 | +// that asking is possible. | ||
| 152 | +func TestTheEnvironmentToolAsksWhereToPutIt(t *testing.T) { | ||
| 153 | + for _, tool := range loadTools(t, createTools(t)).Tools() { | ||
| 154 | + if plain(tool.Name) != "Environment" { | ||
| 155 | + continue | ||
| 156 | + } | ||
| 157 | + | ||
| 158 | + asked := tool.Placeholders() | ||
| 159 | + if len(asked) != 1 { | ||
| 160 | + t.Fatalf("Environment asks for %d values, want 1: %v", len(asked), asked) | ||
| 161 | + } | ||
| 162 | + if !strings.Contains(asked[0].Label, ".venv") { | ||
| 163 | + t.Errorf("it asks for %q, which never mentions .venv", asked[0].Label) | ||
| 164 | + } | ||
| 165 | + if asked[0].Raw { | ||
| 166 | + t.Errorf("it asks for %q unquoted; a directory with a space in it would become two arguments", asked[0].Label) | ||
| 167 | + } | ||
| 168 | + return | ||
| 169 | + } | ||
| 170 | + t.Fatal("there is no Environment tool") | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +func TestOnlyTheTwoToolsThatNeedAValueAskForOne(t *testing.T) { | ||
| 174 | + // Every other command is complete as it stands, and a box in front of a | ||
| 175 | + // command that has nothing to ask is a keystroke for nothing. | ||
| 176 | + asking := map[string]bool{"Environment": true, "Run": true} | ||
| 177 | + | ||
| 178 | + for _, tool := range loadTools(t, createTools(t)).Tools() { | ||
| 179 | + name := plain(tool.Name) | ||
| 180 | + if got := len(tool.Placeholders()) > 0; got != asking[name] { | ||
| 181 | + t.Errorf("%s asks for a value: %t, want %t (%q)", name, got, asking[name], tool.Command) | ||
| 182 | + } | ||
| 183 | + } | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +func TestTheCreatedToolsCarryHotKeysUniqueWithinTheirMenu(t *testing.T) { | ||
| 187 | + // Six items in a menu are worth reaching with one keystroke each. Two menus | ||
| 188 | + // may each have an E, which is why the check is per menu. | ||
| 189 | + list := loadTools(t, createTools(t)) | ||
| 190 | + | ||
| 191 | + for _, menu := range list.MenuNames() { | ||
| 192 | + seen := map[rune]string{} | ||
| 193 | + for _, tool := range list.In(menu) { | ||
| 194 | + key := hotKey(tool.Name) | ||
| 195 | + if key == 0 { | ||
| 196 | + t.Errorf("%q in the %s menu has no hot key", tool.Name, menu) | ||
| 197 | + continue | ||
| 198 | + } | ||
| 199 | + if other, clash := seen[key]; clash { | ||
| 200 | + t.Errorf("%q and %q in the %s menu both answer to %c", other, tool.Name, menu, key) | ||
| 201 | + } | ||
| 202 | + seen[key] = tool.Name | ||
| 203 | + } | ||
| 204 | + } | ||
| 205 | +} | ||
| 206 | + | ||
| 207 | +func TestTheCreatedToolsFileNamesAnOutputForEveryTool(t *testing.T) { | ||
| 208 | + // The key is the interesting part of the format, and a file where it only | ||
| 209 | + // appears once is a file where nobody notices it exists. | ||
| 210 | + for _, tool := range loadTools(t, createTools(t)).Tools() { | ||
| 211 | + if tool.Output == "" { | ||
| 212 | + t.Errorf("%q leaves its output to the default rather than saying it", tool.Name) | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +func TestRunIsTheOneToolchainCommandInATerminal(t *testing.T) { | ||
| 218 | + // A Python script usually reads the keyboard, runs long, or both, and a | ||
| 219 | + // popup can answer neither. The Echo example is in a terminal too, but it | ||
| 220 | + // is in a menu of its own and is there to demonstrate the menu key. | ||
| 221 | + for _, tool := range loadTools(t, createTools(t)).In("Python") { | ||
| 222 | + want := tools.OutputPopup | ||
| 223 | + if plain(tool.Name) == "Run" { | ||
| 224 | + want = tools.OutputTerminal | ||
| 225 | + } | ||
| 226 | + if got := tool.Where(); got != want { | ||
| 227 | + t.Errorf("%s goes to %q, want %q", plain(tool.Name), got, want) | ||
| 228 | + } | ||
| 229 | + } | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +func TestTheCreatedToolsFileExplainsItself(t *testing.T) { | ||
| 233 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | ||
| 234 | + | ||
| 235 | + for _, want := range []string{"[[tool]]", "sh -c", "hot key", "popup", "terminal", "editor"} { | ||
| 236 | + if !strings.Contains(contents, want) { | ||
| 237 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | ||
| 238 | + } | ||
| 239 | + } | ||
| 240 | +} | ||
| 241 | + | ||
| 242 | +func TestTheCreatedToolsFileNamesThePythonMenuAndNoOtherEditorsMenu(t *testing.T) { | ||
| 243 | + // The comments explain which menu a tool lands in by naming it. Naming the | ||
| 244 | + // menu of the editor this one was adapted from is the copy-and-paste | ||
| 245 | + // mistake this catches, and it is invisible to every other test. | ||
| 246 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | ||
| 247 | + | ||
| 248 | + if !strings.Contains(contents, "Python menu") { | ||
| 249 | + t.Errorf("the created file never names the Python menu:\n%s", contents) | ||
| 250 | + } | ||
| 251 | + for _, other := range []string{"Go menu", "Rust menu", "turbo-go", "turbo-rust", "cargo"} { | ||
| 252 | + if strings.Contains(contents, other) { | ||
| 253 | + t.Errorf("the created file still talks about %q:\n%s", other, contents) | ||
| 254 | + } | ||
| 255 | + } | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +func TestTheCreatedToolsFileShowsHowToUseAnotherMenu(t *testing.T) { | ||
| 259 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | ||
| 260 | + | ||
| 261 | + for _, want := range []string{"menu says which menu", `menu = "Tools"`} { | ||
| 262 | + if !strings.Contains(contents, want) { | ||
| 263 | + t.Errorf("the created file never shows %q:\n%s", want, contents) | ||
| 264 | + } | ||
| 265 | + } | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +func TestTheCreatedToolsFileExplainsHowToAskForAValue(t *testing.T) { | ||
| 269 | + // A parameterised tool is only discoverable if the file people get says the | ||
| 270 | + // syntax exists. The double-brace warning is here too, because somebody | ||
| 271 | + // reading this file may well have an awk one-liner in mind. | ||
| 272 | + contents := readFile(t, tools.Path(Profile(), createTools(t))) | ||
| 273 | + | ||
| 274 | + for _, want := range []string{ | ||
| 275 | + "{{label}}", | ||
| 276 | + "uv add {{package}}", | ||
| 277 | + "{{extra flags...}}", | ||
| 278 | + "Double braces, not single", | ||
| 279 | + } { | ||
| 280 | + if !strings.Contains(contents, want) { | ||
| 281 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | ||
| 282 | + } | ||
| 283 | + } | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +// --- the snippets file ------------------------------------------------------ | ||
| 287 | + | ||
| 288 | +func TestTheCreatedSnippetsFileHoldsUsablePythonSnippets(t *testing.T) { | ||
| 289 | + groups := loadSnippets(t, createSnippets(t)).Groups(string(Language)) | ||
| 290 | + | ||
| 291 | + if len(groups) == 0 { | ||
| 292 | + t.Fatal("the created file offers nothing at all in a Python file") | ||
| 293 | + } | ||
| 294 | + for _, group := range groups { | ||
| 295 | + for _, snippet := range group.Snippets { | ||
| 296 | + if snippet.Name == "" || snippet.Body == "" { | ||
| 297 | + t.Errorf("the created file holds an unusable snippet %+v", snippet) | ||
| 298 | + } | ||
| 299 | + } | ||
| 300 | + } | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +func TestTheCreatedSnippetsIndentWithFourSpacesTheWayPEP8Does(t *testing.T) { | ||
| 304 | + // A tab inserted into a file indented with spaces is an indentation error | ||
| 305 | + // in Python, not a formatting quibble: the file stops running. | ||
| 306 | + for _, group := range loadSnippets(t, createSnippets(t)).Groups(string(Language)) { | ||
| 307 | + for _, snippet := range group.Snippets { | ||
| 308 | + if strings.Contains(snippet.Body, "\t") { | ||
| 309 | + t.Errorf("%q indents with a tab:\n%q", snippet.Name, snippet.Body) | ||
| 310 | + } | ||
| 311 | + for _, line := range strings.Split(snippet.Body, "\n") { | ||
| 312 | + indent := len(line) - len(strings.TrimLeft(line, " ")) | ||
| 313 | + if indent%4 != 0 { | ||
| 314 | + t.Errorf("%q has a line indented by %d spaces:\n%q", snippet.Name, indent, line) | ||
| 315 | + } | ||
| 316 | + } | ||
| 317 | + } | ||
| 318 | + } | ||
| 319 | +} | ||
| 320 | + | ||
| 321 | +// Every snippet must be Python that runs, not Python that looks right — the | ||
| 322 | +// scanner is the nearest thing to a parser this repository has, and a snippet | ||
| 323 | +// whose whole body comes out as one colour is a snippet with an unclosed | ||
| 324 | +// string in it. | ||
| 325 | +func TestEverySnippetBodyColoursAsMoreThanOneThing(t *testing.T) { | ||
| 326 | + for _, group := range loadSnippets(t, createSnippets(t)).Groups(string(Language)) { | ||
| 327 | + for _, snippet := range group.Snippets { | ||
| 328 | + classes := map[syntax.Class]bool{} | ||
| 329 | + for _, line := range Highlight(snippet.Body) { | ||
| 330 | + for _, span := range line { | ||
| 331 | + classes[span.Class] = true | ||
| 332 | + } | ||
| 333 | + } | ||
| 334 | + if len(classes) < 2 { | ||
| 335 | + t.Errorf("%q colours as %d classes:\n%s", snippet.Name, len(classes), snippet.Body) | ||
| 336 | + } | ||
| 337 | + } | ||
| 338 | + } | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +func TestTheCreatedSnippetsFileExplainsItself(t *testing.T) { | ||
| 342 | + contents := readFile(t, snippets.ProjectPath(Profile(), createSnippets(t))) | ||
| 343 | + | ||
| 344 | + for _, want := range []string{"[[snippet]]", "languages", "group", "General", snippets.UserPath(Profile())} { | ||
| 345 | + if !strings.Contains(contents, want) { | ||
| 346 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | ||
| 347 | + } | ||
| 348 | + } | ||
| 349 | +} | ||
| 350 | + | ||
| 351 | +func TestTheCreatedSnippetsFileListsEveryLanguageTheEditorKnows(t *testing.T) { | ||
| 352 | + // The comment is where a user finds out what they may write in a languages | ||
| 353 | + // key. One that omits a language the editor colours sends them looking for | ||
| 354 | + // a feature that is already there. Iterating the registry rather than a | ||
| 355 | + // list is what stops the comment falling behind it, as turbo-rust's did | ||
| 356 | + // when turbo-core learnt YAML, XML and Dockerfiles. | ||
| 357 | + Register() | ||
| 358 | + contents := readFile(t, snippets.ProjectPath(Profile(), createSnippets(t))) | ||
| 359 | + | ||
| 360 | + for _, language := range syntax.Registered() { | ||
| 361 | + if !strings.Contains(contents, string(language)) { | ||
| 362 | + t.Errorf("the created file never mentions the %q language:\n%s", language, contents) | ||
| 363 | + } | ||
| 364 | + } | ||
| 365 | +} | ||
| 366 | + | ||
| 367 | +// --- the settings file ------------------------------------------------------ | ||
| 368 | + | ||
| 369 | +func TestTheCreatedSettingsFileExplainsItself(t *testing.T) { | ||
| 370 | + contents := readFile(t, settings.Path(Profile(), createSettings(t))) | ||
| 371 | + | ||
| 372 | + for _, want := range []string{"theme", "autosave", "autosave_delay", "-list-themes"} { | ||
| 373 | + if !strings.Contains(contents, want) { | ||
| 374 | + t.Errorf("the created file never mentions %q:\n%s", want, contents) | ||
| 375 | + } | ||
| 376 | + } | ||
| 377 | +} | ||
| 378 | + | ||
| 379 | +func TestTheCreatedSettingsFileTurnsAutosaveOn(t *testing.T) { | ||
| 380 | + // A project that has gone to the trouble of creating a settings file has | ||
| 381 | + // said what it wants. The file is the visible, editable place to say | ||
| 382 | + // otherwise, which is why this default lives here and not in the library. | ||
| 383 | + project := createSettings(t) | ||
| 384 | + | ||
| 385 | + loaded, err := settings.Load(Profile(), project) | ||
| 386 | + if err != nil { | ||
| 387 | + t.Fatalf("settings.Load() error = %v", err) | ||
| 388 | + } | ||
| 389 | + if !loaded.Autosave { | ||
| 390 | + t.Errorf("the created settings file leaves autosave off:\n%s", readFile(t, settings.Path(Profile(), project))) | ||
| 391 | + } | ||
| 392 | + if loaded.AutosaveDelay != settings.DefaultAutosaveDelay { | ||
| 393 | + t.Errorf("AutosaveDelay = %v, want the library default %v", loaded.AutosaveDelay, settings.DefaultAutosaveDelay) | ||
| 394 | + } | ||
| 395 | +} | ||
| 396 | + | ||
| 397 | +func TestAProjectWithNoSettingsFileStillDoesNotAutosave(t *testing.T) { | ||
| 398 | + // The other half of the decision. Turning autosave on for a project that | ||
| 399 | + // never opted in would mean the editor writing to disk in any directory it | ||
| 400 | + // is started in, which is a different and much larger claim. | ||
| 401 | + if settings.Default().Autosave { | ||
| 402 | + t.Error("settings.Default() autosaves; a project with no settings file never opted in") | ||
| 403 | + } | ||
| 404 | +} | ||
| 405 | + | ||
| 406 | +// --- the contract the three templates are held to --------------------------- | ||
| 407 | + | ||
| 408 | +// The three embedded templates and the blanks profile.Templates says each one | ||
| 409 | +// takes. Kept together so that adding a verb to a .tmpl file without saying so | ||
| 410 | +// here fails, which is the guard the constants used to get for free by sitting | ||
| 411 | +// next to the contract. | ||
| 412 | +var embeddedTemplates = []struct { | ||
| 413 | + name string | ||
| 414 | + body string | ||
| 415 | + verb string | ||
| 416 | + blanks int | ||
| 417 | + filledBy []any | ||
| 418 | +}{ | ||
| 419 | + {"settings.toml.tmpl", settingsTemplate, "%q", 2, []any{"turbo-classic", "2s"}}, | ||
| 420 | + {"snippets.toml.tmpl", snippetsTemplate, "%s", 2, []any{"General", "/tmp/snippets.toml"}}, | ||
| 421 | + {"tools.toml.tmpl", toolsTemplate, "%", 0, nil}, | ||
| 422 | +} | ||
| 423 | + | ||
| 424 | +func TestEveryTemplateIsEmbeddedAndNotEmpty(t *testing.T) { | ||
| 425 | + // go:embed fails to compile when a file is missing, but an empty file | ||
| 426 | + // compiles happily and writes an empty starter file into somebody's | ||
| 427 | + // project. | ||
| 428 | + for _, template := range embeddedTemplates { | ||
| 429 | + if len(template.body) == 0 { | ||
| 430 | + t.Errorf("%s embedded as nothing", template.name) | ||
| 431 | + } | ||
| 432 | + } | ||
| 433 | +} | ||
| 434 | + | ||
| 435 | +func TestEveryTemplateTakesTheBlanksItsContractPromises(t *testing.T) { | ||
| 436 | + // profile.Templates documents the count and the verb of each. The templates | ||
| 437 | + // live in files of their own, so nothing but this notices a verb added, | ||
| 438 | + // removed, or changed. | ||
| 439 | + for _, template := range embeddedTemplates { | ||
| 440 | + if got := strings.Count(template.body, template.verb); got != template.blanks { | ||
| 441 | + t.Errorf("%s holds %d %q, want %d", template.name, got, template.verb, template.blanks) | ||
| 442 | + } | ||
| 443 | + } | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +func TestFillingATemplateLeavesNoFormattingMarker(t *testing.T) { | ||
| 447 | + // Go writes %!q(MISSING) or %!(EXTRA …) into the output rather than | ||
| 448 | + // failing, so a template with the wrong number of blanks produces a file | ||
| 449 | + // that is written, opened, and wrong. | ||
| 450 | + for _, template := range embeddedTemplates { | ||
| 451 | + filled := template.body | ||
| 452 | + if template.filledBy != nil { | ||
| 453 | + filled = fmt.Sprintf(template.body, template.filledBy...) | ||
| 454 | + } | ||
| 455 | + if strings.Contains(filled, "%!") { | ||
| 456 | + t.Errorf("%s filled to:\n%s", template.name, filled) | ||
| 457 | + } | ||
| 458 | + } | ||
| 459 | +} | ||
| 460 | + | ||
| 461 | +func TestEveryTemplateNamesThisEditorAndNotTheOnesItWasAdaptedFrom(t *testing.T) { | ||
| 462 | + // The three templates started as Turbo Rust's. A leftover "turbo-rust" in a | ||
| 463 | + // file written into somebody's Python project is the whole class of mistake | ||
| 464 | + // this catches. | ||
| 465 | + templates := map[string]string{ | ||
| 466 | + "settings": settingsTemplate, | ||
| 467 | + "snippets": snippetsTemplate, | ||
| 468 | + "tools": toolsTemplate, | ||
| 469 | + } | ||
| 470 | + | ||
| 471 | + for name, template := range templates { | ||
| 472 | + t.Run(name, func(t *testing.T) { | ||
| 473 | + for _, other := range []string{"turbo-go", "turbo-rust", "cargo", "gopls", "rust-analyzer"} { | ||
| 474 | + if strings.Contains(template, other) { | ||
| 475 | + t.Errorf("the %s template still says %q:\n%s", name, other, template) | ||
| 476 | + } | ||
| 477 | + } | ||
| 478 | + if !strings.Contains(template, Slug) { | ||
| 479 | + t.Errorf("the %s template never names %s:\n%s", name, Slug, template) | ||
| 480 | + } | ||
| 481 | + }) | ||
| 482 | + } | ||
| 483 | +} | ||
added
internal/pythonlang/tools.toml.tmpl +95 -0 | new file mode 100644 | ||
| @@ -0,0 +1,95 @@ | ||
| 1 | +# turbo-python tools. | |
| 2 | +# | |
| 3 | +# Each [[tool]] becomes one line of the Python menu, in the order they appear | |
| 4 | +# here. name is what the menu shows; a letter between tildes is its hot key, and | |
| 5 | +# no two tools should claim the same one. | |
| 6 | +# | |
| 7 | +# command goes to "sh -c", so pipes, globs and && work: one entry can be a | |
| 8 | +# whole sequence. | |
| 9 | +# | |
| 10 | +# menu says which menu it appears in. Leave it out and the tool goes into the | |
| 11 | +# Python menu; name anything else and that menu is created for you, in the order | |
| 12 | +# the names first appear here. A tool that has nothing to do with Python belongs | |
| 13 | +# in one of your own: | |
| 14 | +# | |
| 15 | +# [[tool]] | |
| 16 | +# name = "~E~cho" | |
| 17 | +# command = "echo TADA" | |
| 18 | +# menu = "Tools" | |
| 19 | +# | |
| 20 | +# A {{label}} in a command is a value the editor asks for before running it, in | |
| 21 | +# a box titled after the tool. The text between the braces is what it asks for: | |
| 22 | +# | |
| 23 | +# [[tool]] | |
| 24 | +# name = "~A~dd a dependency" | |
| 25 | +# command = "uv add {{package}}" | |
| 26 | +# | |
| 27 | +# The value is quoted, so a path with a space in it stays one argument. Add ... | |
| 28 | +# inside the braces when you mean several arguments rather than one value: | |
| 29 | +# | |
| 30 | +# [[tool]] | |
| 31 | +# name = "Test ~o~ne" | |
| 32 | +# command = "uv run pytest {{extra flags...}}" | |
| 33 | +# | |
| 34 | +# Double braces, not single. Single ones appear in real commands — awk '{print | |
| 35 | +# $1}' and find . -exec rm {} + are both ordinary things to put here — and | |
| 36 | +# neither is asking you for anything. | |
| 37 | +# | |
| 38 | +# output says where what the command prints goes: | |
| 39 | +# popup a dialog that fills in as it runs, and says the exit code (default) | |
| 40 | +# terminal a terminal window, for anything that reads the keyboard or runs long | |
| 41 | +# editor an editing window once it has finished, to search with Ctrl-F | |
| 42 | +# | |
| 43 | +# Commands run in the directory the editor was started in, which is why they | |
| 44 | +# see the whole project when you start from its root. | |
| 45 | +# | |
| 46 | +# Everything below goes through uv, which creates the environment, resolves the | |
| 47 | +# dependencies, and runs the tools inside it — so no command here needs an | |
| 48 | +# environment to have been activated first. Replace `uv run x` with `x` if you | |
| 49 | +# would rather activate one yourself. | |
| 50 | + | |
| 51 | +[[tool]] | |
| 52 | +name = "~E~nvironment" | |
| 53 | +# The one command that has to come first in a new project: it creates the | |
| 54 | +# virtual environment everything else runs inside. The name is asked for rather | |
| 55 | +# than fixed, because .venv is only the usual answer and not the only one. | |
| 56 | +command = "uv venv {{directory, usually .venv}}" | |
| 57 | +output = "popup" | |
| 58 | + | |
| 59 | +[[tool]] | |
| 60 | +name = "~S~ync" | |
| 61 | +command = "uv sync" | |
| 62 | +output = "popup" | |
| 63 | + | |
| 64 | +[[tool]] | |
| 65 | +name = "~F~ormat" | |
| 66 | +command = "uv run ruff format ." | |
| 67 | +output = "popup" | |
| 68 | + | |
| 69 | +[[tool]] | |
| 70 | +name = "~L~int" | |
| 71 | +command = "uv run ruff check ." | |
| 72 | +output = "popup" | |
| 73 | + | |
| 74 | +[[tool]] | |
| 75 | +name = "~T~est" | |
| 76 | +command = "uv run pytest" | |
| 77 | +output = "popup" | |
| 78 | + | |
| 79 | +[[tool]] | |
| 80 | +name = "~R~un" | |
| 81 | +command = "uv run {{script}}" | |
| 82 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | |
| 83 | +# be answered, and one that runs long has to be able to be interrupted. Python | |
| 84 | +# scripts are usually both. | |
| 85 | +output = "terminal" | |
| 86 | + | |
| 87 | +# A tool naming a `menu` gets a menu of its own on the bar. Nothing above does, | |
| 88 | +# so every tool above is in the Python menu. This one is in a menu called Tools, | |
| 89 | +# which appears between Python and Help — that is the whole mechanism. | |
| 90 | + | |
| 91 | +[[tool]] | |
| 92 | +name = "~E~cho" | |
| 93 | +command = "echo 🎉 tada!" | |
| 94 | +menu = "Tools" | |
| 95 | +output = "terminal" | |
| new file mode 100644 | |||
| @@ -0,0 +1,95 @@ | |||
| 1 | +# turbo-python tools. | ||
| 2 | +# | ||
| 3 | +# Each [[tool]] becomes one line of the Python menu, in the order they appear | ||
| 4 | +# here. name is what the menu shows; a letter between tildes is its hot key, and | ||
| 5 | +# no two tools should claim the same one. | ||
| 6 | +# | ||
| 7 | +# command goes to "sh -c", so pipes, globs and && work: one entry can be a | ||
| 8 | +# whole sequence. | ||
| 9 | +# | ||
| 10 | +# menu says which menu it appears in. Leave it out and the tool goes into the | ||
| 11 | +# Python menu; name anything else and that menu is created for you, in the order | ||
| 12 | +# the names first appear here. A tool that has nothing to do with Python belongs | ||
| 13 | +# in one of your own: | ||
| 14 | +# | ||
| 15 | +# [[tool]] | ||
| 16 | +# name = "~E~cho" | ||
| 17 | +# command = "echo TADA" | ||
| 18 | +# menu = "Tools" | ||
| 19 | +# | ||
| 20 | +# A {{label}} in a command is a value the editor asks for before running it, in | ||
| 21 | +# a box titled after the tool. The text between the braces is what it asks for: | ||
| 22 | +# | ||
| 23 | +# [[tool]] | ||
| 24 | +# name = "~A~dd a dependency" | ||
| 25 | +# command = "uv add {{package}}" | ||
| 26 | +# | ||
| 27 | +# The value is quoted, so a path with a space in it stays one argument. Add ... | ||
| 28 | +# inside the braces when you mean several arguments rather than one value: | ||
| 29 | +# | ||
| 30 | +# [[tool]] | ||
| 31 | +# name = "Test ~o~ne" | ||
| 32 | +# command = "uv run pytest {{extra flags...}}" | ||
| 33 | +# | ||
| 34 | +# Double braces, not single. Single ones appear in real commands — awk '{print | ||
| 35 | +# $1}' and find . -exec rm {} + are both ordinary things to put here — and | ||
| 36 | +# neither is asking you for anything. | ||
| 37 | +# | ||
| 38 | +# output says where what the command prints goes: | ||
| 39 | +# popup a dialog that fills in as it runs, and says the exit code (default) | ||
| 40 | +# terminal a terminal window, for anything that reads the keyboard or runs long | ||
| 41 | +# editor an editing window once it has finished, to search with Ctrl-F | ||
| 42 | +# | ||
| 43 | +# Commands run in the directory the editor was started in, which is why they | ||
| 44 | +# see the whole project when you start from its root. | ||
| 45 | +# | ||
| 46 | +# Everything below goes through uv, which creates the environment, resolves the | ||
| 47 | +# dependencies, and runs the tools inside it — so no command here needs an | ||
| 48 | +# environment to have been activated first. Replace `uv run x` with `x` if you | ||
| 49 | +# would rather activate one yourself. | ||
| 50 | + | ||
| 51 | +[[tool]] | ||
| 52 | +name = "~E~nvironment" | ||
| 53 | +# The one command that has to come first in a new project: it creates the | ||
| 54 | +# virtual environment everything else runs inside. The name is asked for rather | ||
| 55 | +# than fixed, because .venv is only the usual answer and not the only one. | ||
| 56 | +command = "uv venv {{directory, usually .venv}}" | ||
| 57 | +output = "popup" | ||
| 58 | + | ||
| 59 | +[[tool]] | ||
| 60 | +name = "~S~ync" | ||
| 61 | +command = "uv sync" | ||
| 62 | +output = "popup" | ||
| 63 | + | ||
| 64 | +[[tool]] | ||
| 65 | +name = "~F~ormat" | ||
| 66 | +command = "uv run ruff format ." | ||
| 67 | +output = "popup" | ||
| 68 | + | ||
| 69 | +[[tool]] | ||
| 70 | +name = "~L~int" | ||
| 71 | +command = "uv run ruff check ." | ||
| 72 | +output = "popup" | ||
| 73 | + | ||
| 74 | +[[tool]] | ||
| 75 | +name = "~T~est" | ||
| 76 | +command = "uv run pytest" | ||
| 77 | +output = "popup" | ||
| 78 | + | ||
| 79 | +[[tool]] | ||
| 80 | +name = "~R~un" | ||
| 81 | +command = "uv run {{script}}" | ||
| 82 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | ||
| 83 | +# be answered, and one that runs long has to be able to be interrupted. Python | ||
| 84 | +# scripts are usually both. | ||
| 85 | +output = "terminal" | ||
| 86 | + | ||
| 87 | +# A tool naming a `menu` gets a menu of its own on the bar. Nothing above does, | ||
| 88 | +# so every tool above is in the Python menu. This one is in a menu called Tools, | ||
| 89 | +# which appears between Python and Help — that is the whole mechanism. | ||
| 90 | + | ||
| 91 | +[[tool]] | ||
| 92 | +name = "~E~cho" | ||
| 93 | +command = "echo 🎉 tada!" | ||
| 94 | +menu = "Tools" | ||
| 95 | +output = "terminal" | ||
added
internal/pythonlang/words.go +263 -0 | new file mode 100644 | ||
| @@ -0,0 +1,263 @@ | ||
| 1 | +package pythonlang | |
| 2 | + | |
| 3 | +// Numbers and words: what a run of letters or digits turns out to be. | |
| 4 | + | |
| 5 | +import ( | |
| 6 | + "strings" | |
| 7 | + | |
| 8 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// --- numbers ---------------------------------------------------------------- | |
| 12 | + | |
| 13 | +// takeNumber colours a numeric literal, base prefix, underscores, exponent and | |
| 14 | +// imaginary suffix included: 1_000, 0xFF, 0b1010, .5, 1.5e-3, 3j. | |
| 15 | +func takeNumber(s *syntax.LineScanner) { | |
| 16 | + start := s.Pos() | |
| 17 | + // A float may have exactly one dot, and 1. is as valid as 1.0 — so the dot | |
| 18 | + // is counted rather than required to have a digit after it. A second one is | |
| 19 | + // where the number stops, which is what keeps `1..2` from being one token. | |
| 20 | + seenDot := s.Peek(0) == '.' | |
| 21 | + // 0xE-1 is a hexadecimal literal minus one, not an exponent: the sign rule | |
| 22 | + // below has to know that the E it just saw was a digit. | |
| 23 | + hex := s.Peek(0) == '0' && (s.Peek(1) == 'x' || s.Peek(1) == 'X') | |
| 24 | + s.Advance(1) | |
| 25 | + | |
| 26 | + for !s.AtEnd() { | |
| 27 | + r := s.Peek(0) | |
| 28 | + switch { | |
| 29 | + case syntax.IsWordRune(r): | |
| 30 | + s.Advance(1) | |
| 31 | + case r == '.' && !seenDot: | |
| 32 | + seenDot = true | |
| 33 | + s.Advance(1) | |
| 34 | + case (r == '+' || r == '-') && !hex && isExponent(s.Peek(-1)): | |
| 35 | + s.Advance(1) | |
| 36 | + default: | |
| 37 | + s.Emit(start, s.Pos(), syntax.ClassNumber) | |
| 38 | + return | |
| 39 | + } | |
| 40 | + } | |
| 41 | + s.Emit(start, s.Pos(), syntax.ClassNumber) | |
| 42 | +} | |
| 43 | + | |
| 44 | +// isExponent reports whether a rune is the e of an exponent, which is what | |
| 45 | +// makes the sign after it part of the number rather than an operator. | |
| 46 | +func isExponent(r rune) bool { return r == 'e' || r == 'E' } | |
| 47 | + | |
| 48 | +// --- words ------------------------------------------------------------------ | |
| 49 | + | |
| 50 | +// takeWord colours an identifier, deciding what kind of thing it is from the | |
| 51 | +// word itself, from the rune after it, and — for the two soft keywords — from | |
| 52 | +// where it sits on the line. | |
| 53 | +func takeWord(s *syntax.LineScanner) { | |
| 54 | + start := s.Pos() | |
| 55 | + // Asked before the word is consumed, because afterwards the scanner is no | |
| 56 | + // longer at its first rune. | |
| 57 | + first := atLineStart(s) | |
| 58 | + | |
| 59 | + for !s.AtEnd() && syntax.IsWordRune(s.Peek(0)) { | |
| 60 | + s.Advance(1) | |
| 61 | + } | |
| 62 | + word := wordAt(s, start) | |
| 63 | + | |
| 64 | + class := classOfWord(word, s.Peek(0)) | |
| 65 | + if isSoftKeyword(word) && first && lineEndsWithColon(s) { | |
| 66 | + class = syntax.ClassKeyword | |
| 67 | + } | |
| 68 | + s.Emit(start, s.Pos(), class) | |
| 69 | +} | |
| 70 | + | |
| 71 | +// wordAt returns the word running from start to the scanner's position. | |
| 72 | +func wordAt(s *syntax.LineScanner, start int) string { | |
| 73 | + var b strings.Builder | |
| 74 | + for at := start; at < s.Pos(); at++ { | |
| 75 | + b.WriteRune(s.Peek(at - s.Pos())) | |
| 76 | + } | |
| 77 | + return b.String() | |
| 78 | +} | |
| 79 | + | |
| 80 | +// isSoftKeyword reports whether a word is one of the two Python added without | |
| 81 | +// reserving. | |
| 82 | +// | |
| 83 | +// `match` and `case` open a match statement, and are ordinary names everywhere | |
| 84 | +// else — `match = re.match(pattern, text)` is the line that made this a rule | |
| 85 | +// rather than a table entry. What tells them apart is the shape of a | |
| 86 | +// statement: it starts the line, and the line ends with the colon that opens | |
| 87 | +// its block. Both conditions are checked, and `type` is deliberately not here: | |
| 88 | +// it is a builtin as well as a soft keyword, and reading as a builtin is right | |
| 89 | +// in both of its jobs. | |
| 90 | +func isSoftKeyword(word string) bool { return word == "match" || word == "case" } | |
| 91 | + | |
| 92 | +// classOfWord decides what a word is, given the rune that follows it. | |
| 93 | +// | |
| 94 | +// The order is the design. A word the language names is what the language says | |
| 95 | +// it is, whatever follows it. Then the naming conventions, which in Python are | |
| 96 | +// strong enough to answer a question that the syntax cannot: a class is called | |
| 97 | +// exactly the way a function is, so `ValueError("nope")` and `parse("nope")` | |
| 98 | +// are the same shape, and only CapWords tells them apart. Only after that does | |
| 99 | +// a parenthesis make a name a function. | |
| 100 | +// | |
| 101 | +// This is the one place Turbo Python and Turbo Rust order the same three rules | |
| 102 | +// differently, and the reason is Rust's `Some(x)`: there, a parenthesis after a | |
| 103 | +// capitalised name is usually a constructor the language names, so it is | |
| 104 | +// answered from the table before the convention is consulted. | |
| 105 | +func classOfWord(word string, next rune) syntax.Class { | |
| 106 | + if class, known := knownWords[word]; known { | |
| 107 | + return class | |
| 108 | + } | |
| 109 | + for _, convention := range conventions { | |
| 110 | + if convention.spelt(word) { | |
| 111 | + return convention.class | |
| 112 | + } | |
| 113 | + } | |
| 114 | + if next == '(' { | |
| 115 | + return syntax.ClassFunction | |
| 116 | + } | |
| 117 | + return syntax.ClassIdentifier | |
| 118 | +} | |
| 119 | + | |
| 120 | +// conventions are the ways Python spells what a name is, consulted in order for | |
| 121 | +// a word the language does not name itself. | |
| 122 | +// | |
| 123 | +// A list rather than a chain of ifs because the order *is* the rule, and a list | |
| 124 | +// is where a reader looks for one: a dunder is the language's whatever else it | |
| 125 | +// looks like, and a name in capitals is a constant before it is a type. | |
| 126 | +var conventions = []struct { | |
| 127 | + spelt func(string) bool | |
| 128 | + class syntax.Class | |
| 129 | +}{ | |
| 130 | + {isDunder, syntax.ClassBuiltin}, | |
| 131 | + {isScreamingCase, syntax.ClassConstant}, | |
| 132 | + {startsUpperCase, syntax.ClassType}, | |
| 133 | +} | |
| 134 | + | |
| 135 | +// isDunder reports whether a word is one of the names the language reserves to | |
| 136 | +// itself by spelling: __init__, __name__, __repr__. | |
| 137 | +// | |
| 138 | +// They are the language's own hooks rather than anybody's identifiers, and a | |
| 139 | +// reader looking for where a class begins finds __init__ faster when it is not | |
| 140 | +// the same colour as the method below it. | |
| 141 | +func isDunder(word string) bool { | |
| 142 | + return len(word) > 4 && strings.HasPrefix(word, "__") && strings.HasSuffix(word, "__") | |
| 143 | +} | |
| 144 | + | |
| 145 | +// isScreamingCase reports whether a word is written the way PEP 8 writes a | |
| 146 | +// constant: MAX_SIZE, HTTP_PORT, PI. | |
| 147 | +// | |
| 148 | +// Turbo Rust has no rule like this one and documents SCREAMING_SNAKE_CASE as a | |
| 149 | +// known wrong answer — it colours such a word as a type. Python's convention is | |
| 150 | +// separated from its class convention by more than Rust's is, so the wrong | |
| 151 | +// answer is worth removing rather than inheriting. What it costs is a class | |
| 152 | +// named in capitals, which is rare enough to document. | |
| 153 | +func isScreamingCase(word string) bool { | |
| 154 | + if len(word) < 2 { | |
| 155 | + return false | |
| 156 | + } | |
| 157 | + letters := 0 | |
| 158 | + for _, r := range word { | |
| 159 | + switch { | |
| 160 | + case r >= 'A' && r <= 'Z': | |
| 161 | + letters++ | |
| 162 | + case r == '_' || r >= '0' && r <= '9': | |
| 163 | + default: | |
| 164 | + return false | |
| 165 | + } | |
| 166 | + } | |
| 167 | + return letters > 0 | |
| 168 | +} | |
| 169 | + | |
| 170 | +// startsUpperCase reports whether a word begins with an ASCII capital. | |
| 171 | +func startsUpperCase(word string) bool { | |
| 172 | + return word != "" && word[0] >= 'A' && word[0] <= 'Z' | |
| 173 | +} | |
| 174 | + | |
| 175 | +// knownWords is every word the language itself names, and what each one is. | |
| 176 | +// | |
| 177 | +// It is one table rather than four because it answers one question. The four | |
| 178 | +// groups below are kept apart only so that each can carry the reasoning that | |
| 179 | +// belongs to it. | |
| 180 | +// | |
| 181 | +// The exception hierarchy is deliberately absent. ValueError, KeyError and the | |
| 182 | +// seventy others are CapWords, so the convention rule in classOfWord already | |
| 183 | +// colours them as types — and a table naming them would go out of date the next | |
| 184 | +// time Python adds one. | |
| 185 | +var knownWords = merge( | |
| 186 | + classify(syntax.ClassKeyword, keywords), | |
| 187 | + classify(syntax.ClassConstant, constants), | |
| 188 | + classify(syntax.ClassType, builtinTypes), | |
| 189 | + classify(syntax.ClassBuiltin, builtinFunctions), | |
| 190 | +) | |
| 191 | + | |
| 192 | +// keywords are Python's reserved words — the ones that cannot be used as a | |
| 193 | +// name. and, or, not, in and is are here rather than among the operators | |
| 194 | +// because that is what the language calls them, and because a theme that quiets | |
| 195 | +// keywords should quiet them. | |
| 196 | +// | |
| 197 | +// match and case are not here: they are reserved in no context at all, and are | |
| 198 | +// decided by isSoftKeyword. | |
| 199 | +var keywords = words( | |
| 200 | + "and", "as", "assert", "async", "await", "break", "class", "continue", | |
| 201 | + "def", "del", "elif", "else", "except", "finally", "for", "from", "global", | |
| 202 | + "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", | |
| 203 | + "raise", "return", "try", "while", "with", "yield", | |
| 204 | +) | |
| 205 | + | |
| 206 | +// constants are the values the language names, plus the flag it sets for you. | |
| 207 | +var constants = words("True", "False", "None", "NotImplemented", "Ellipsis", "__debug__") | |
| 208 | + | |
| 209 | +// builtinTypes are the types you can call without importing anything. | |
| 210 | +// | |
| 211 | +// self and cls are here as *builtins* rather than as types, in builtinFunctions | |
| 212 | +// below — they name a value, not a type. | |
| 213 | +var builtinTypes = words( | |
| 214 | + "bool", "bytearray", "bytes", "complex", "dict", "float", "frozenset", | |
| 215 | + "int", "list", "memoryview", "object", "range", "set", "slice", "str", | |
| 216 | + "tuple", "type", | |
| 217 | +) | |
| 218 | + | |
| 219 | +// builtinFunctions are the names in the builtins module, plus the two argument | |
| 220 | +// names every Python reader reads as the language's own. | |
| 221 | +// | |
| 222 | +// self and cls are a convention rather than a rule — a method may name its | |
| 223 | +// first parameter anything — but the convention is universal enough that every | |
| 224 | +// other highlighter colours them, and a reader who meets `self` reads it the | |
| 225 | +// way a Rust reader reads `Some`. That parallel is the argument; the caveat is | |
| 226 | +// that a parameter honestly named self in a plain function is coloured too. | |
| 227 | +var builtinFunctions = words( | |
| 228 | + "abs", "aiter", "anext", "all", "any", "ascii", "bin", "breakpoint", | |
| 229 | + "callable", "chr", "classmethod", "compile", "delattr", "dir", "divmod", | |
| 230 | + "enumerate", "eval", "exec", "filter", "format", "getattr", "globals", | |
| 231 | + "hasattr", "hash", "help", "hex", "id", "input", "isinstance", "issubclass", | |
| 232 | + "iter", "len", "locals", "map", "max", "min", "next", "oct", "open", "ord", | |
| 233 | + "pow", "print", "property", "repr", "reversed", "round", "setattr", | |
| 234 | + "sorted", "staticmethod", "sum", "super", "vars", "zip", | |
| 235 | + "self", "cls", | |
| 236 | +) | |
| 237 | + | |
| 238 | +// words gathers a group of them, which reads better at the call sites above | |
| 239 | +// than a slice literal does. | |
| 240 | +func words(list ...string) []string { return list } | |
| 241 | + | |
| 242 | +// classify pairs every word in a group with the class it belongs to. | |
| 243 | +func classify(class syntax.Class, list []string) map[string]syntax.Class { | |
| 244 | + out := make(map[string]syntax.Class, len(list)) | |
| 245 | + for _, word := range list { | |
| 246 | + out[word] = class | |
| 247 | + } | |
| 248 | + return out | |
| 249 | +} | |
| 250 | + | |
| 251 | +// merge folds the groups into one table. An earlier group wins a word a later | |
| 252 | +// one repeats, which is what keeps a keyword a keyword. | |
| 253 | +func merge(groups ...map[string]syntax.Class) map[string]syntax.Class { | |
| 254 | + out := map[string]syntax.Class{} | |
| 255 | + for _, group := range groups { | |
| 256 | + for word, class := range group { | |
| 257 | + if _, taken := out[word]; !taken { | |
| 258 | + out[word] = class | |
| 259 | + } | |
| 260 | + } | |
| 261 | + } | |
| 262 | + return out | |
| 263 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,263 @@ | |||
| 1 | +package pythonlang | ||
| 2 | + | ||
| 3 | +// Numbers and words: what a run of letters or digits turns out to be. | ||
| 4 | + | ||
| 5 | +import ( | ||
| 6 | + "strings" | ||
| 7 | + | ||
| 8 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// --- numbers ---------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +// takeNumber colours a numeric literal, base prefix, underscores, exponent and | ||
| 14 | +// imaginary suffix included: 1_000, 0xFF, 0b1010, .5, 1.5e-3, 3j. | ||
| 15 | +func takeNumber(s *syntax.LineScanner) { | ||
| 16 | + start := s.Pos() | ||
| 17 | + // A float may have exactly one dot, and 1. is as valid as 1.0 — so the dot | ||
| 18 | + // is counted rather than required to have a digit after it. A second one is | ||
| 19 | + // where the number stops, which is what keeps `1..2` from being one token. | ||
| 20 | + seenDot := s.Peek(0) == '.' | ||
| 21 | + // 0xE-1 is a hexadecimal literal minus one, not an exponent: the sign rule | ||
| 22 | + // below has to know that the E it just saw was a digit. | ||
| 23 | + hex := s.Peek(0) == '0' && (s.Peek(1) == 'x' || s.Peek(1) == 'X') | ||
| 24 | + s.Advance(1) | ||
| 25 | + | ||
| 26 | + for !s.AtEnd() { | ||
| 27 | + r := s.Peek(0) | ||
| 28 | + switch { | ||
| 29 | + case syntax.IsWordRune(r): | ||
| 30 | + s.Advance(1) | ||
| 31 | + case r == '.' && !seenDot: | ||
| 32 | + seenDot = true | ||
| 33 | + s.Advance(1) | ||
| 34 | + case (r == '+' || r == '-') && !hex && isExponent(s.Peek(-1)): | ||
| 35 | + s.Advance(1) | ||
| 36 | + default: | ||
| 37 | + s.Emit(start, s.Pos(), syntax.ClassNumber) | ||
| 38 | + return | ||
| 39 | + } | ||
| 40 | + } | ||
| 41 | + s.Emit(start, s.Pos(), syntax.ClassNumber) | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// isExponent reports whether a rune is the e of an exponent, which is what | ||
| 45 | +// makes the sign after it part of the number rather than an operator. | ||
| 46 | +func isExponent(r rune) bool { return r == 'e' || r == 'E' } | ||
| 47 | + | ||
| 48 | +// --- words ------------------------------------------------------------------ | ||
| 49 | + | ||
| 50 | +// takeWord colours an identifier, deciding what kind of thing it is from the | ||
| 51 | +// word itself, from the rune after it, and — for the two soft keywords — from | ||
| 52 | +// where it sits on the line. | ||
| 53 | +func takeWord(s *syntax.LineScanner) { | ||
| 54 | + start := s.Pos() | ||
| 55 | + // Asked before the word is consumed, because afterwards the scanner is no | ||
| 56 | + // longer at its first rune. | ||
| 57 | + first := atLineStart(s) | ||
| 58 | + | ||
| 59 | + for !s.AtEnd() && syntax.IsWordRune(s.Peek(0)) { | ||
| 60 | + s.Advance(1) | ||
| 61 | + } | ||
| 62 | + word := wordAt(s, start) | ||
| 63 | + | ||
| 64 | + class := classOfWord(word, s.Peek(0)) | ||
| 65 | + if isSoftKeyword(word) && first && lineEndsWithColon(s) { | ||
| 66 | + class = syntax.ClassKeyword | ||
| 67 | + } | ||
| 68 | + s.Emit(start, s.Pos(), class) | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +// wordAt returns the word running from start to the scanner's position. | ||
| 72 | +func wordAt(s *syntax.LineScanner, start int) string { | ||
| 73 | + var b strings.Builder | ||
| 74 | + for at := start; at < s.Pos(); at++ { | ||
| 75 | + b.WriteRune(s.Peek(at - s.Pos())) | ||
| 76 | + } | ||
| 77 | + return b.String() | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +// isSoftKeyword reports whether a word is one of the two Python added without | ||
| 81 | +// reserving. | ||
| 82 | +// | ||
| 83 | +// `match` and `case` open a match statement, and are ordinary names everywhere | ||
| 84 | +// else — `match = re.match(pattern, text)` is the line that made this a rule | ||
| 85 | +// rather than a table entry. What tells them apart is the shape of a | ||
| 86 | +// statement: it starts the line, and the line ends with the colon that opens | ||
| 87 | +// its block. Both conditions are checked, and `type` is deliberately not here: | ||
| 88 | +// it is a builtin as well as a soft keyword, and reading as a builtin is right | ||
| 89 | +// in both of its jobs. | ||
| 90 | +func isSoftKeyword(word string) bool { return word == "match" || word == "case" } | ||
| 91 | + | ||
| 92 | +// classOfWord decides what a word is, given the rune that follows it. | ||
| 93 | +// | ||
| 94 | +// The order is the design. A word the language names is what the language says | ||
| 95 | +// it is, whatever follows it. Then the naming conventions, which in Python are | ||
| 96 | +// strong enough to answer a question that the syntax cannot: a class is called | ||
| 97 | +// exactly the way a function is, so `ValueError("nope")` and `parse("nope")` | ||
| 98 | +// are the same shape, and only CapWords tells them apart. Only after that does | ||
| 99 | +// a parenthesis make a name a function. | ||
| 100 | +// | ||
| 101 | +// This is the one place Turbo Python and Turbo Rust order the same three rules | ||
| 102 | +// differently, and the reason is Rust's `Some(x)`: there, a parenthesis after a | ||
| 103 | +// capitalised name is usually a constructor the language names, so it is | ||
| 104 | +// answered from the table before the convention is consulted. | ||
| 105 | +func classOfWord(word string, next rune) syntax.Class { | ||
| 106 | + if class, known := knownWords[word]; known { | ||
| 107 | + return class | ||
| 108 | + } | ||
| 109 | + for _, convention := range conventions { | ||
| 110 | + if convention.spelt(word) { | ||
| 111 | + return convention.class | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + if next == '(' { | ||
| 115 | + return syntax.ClassFunction | ||
| 116 | + } | ||
| 117 | + return syntax.ClassIdentifier | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +// conventions are the ways Python spells what a name is, consulted in order for | ||
| 121 | +// a word the language does not name itself. | ||
| 122 | +// | ||
| 123 | +// A list rather than a chain of ifs because the order *is* the rule, and a list | ||
| 124 | +// is where a reader looks for one: a dunder is the language's whatever else it | ||
| 125 | +// looks like, and a name in capitals is a constant before it is a type. | ||
| 126 | +var conventions = []struct { | ||
| 127 | + spelt func(string) bool | ||
| 128 | + class syntax.Class | ||
| 129 | +}{ | ||
| 130 | + {isDunder, syntax.ClassBuiltin}, | ||
| 131 | + {isScreamingCase, syntax.ClassConstant}, | ||
| 132 | + {startsUpperCase, syntax.ClassType}, | ||
| 133 | +} | ||
| 134 | + | ||
| 135 | +// isDunder reports whether a word is one of the names the language reserves to | ||
| 136 | +// itself by spelling: __init__, __name__, __repr__. | ||
| 137 | +// | ||
| 138 | +// They are the language's own hooks rather than anybody's identifiers, and a | ||
| 139 | +// reader looking for where a class begins finds __init__ faster when it is not | ||
| 140 | +// the same colour as the method below it. | ||
| 141 | +func isDunder(word string) bool { | ||
| 142 | + return len(word) > 4 && strings.HasPrefix(word, "__") && strings.HasSuffix(word, "__") | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +// isScreamingCase reports whether a word is written the way PEP 8 writes a | ||
| 146 | +// constant: MAX_SIZE, HTTP_PORT, PI. | ||
| 147 | +// | ||
| 148 | +// Turbo Rust has no rule like this one and documents SCREAMING_SNAKE_CASE as a | ||
| 149 | +// known wrong answer — it colours such a word as a type. Python's convention is | ||
| 150 | +// separated from its class convention by more than Rust's is, so the wrong | ||
| 151 | +// answer is worth removing rather than inheriting. What it costs is a class | ||
| 152 | +// named in capitals, which is rare enough to document. | ||
| 153 | +func isScreamingCase(word string) bool { | ||
| 154 | + if len(word) < 2 { | ||
| 155 | + return false | ||
| 156 | + } | ||
| 157 | + letters := 0 | ||
| 158 | + for _, r := range word { | ||
| 159 | + switch { | ||
| 160 | + case r >= 'A' && r <= 'Z': | ||
| 161 | + letters++ | ||
| 162 | + case r == '_' || r >= '0' && r <= '9': | ||
| 163 | + default: | ||
| 164 | + return false | ||
| 165 | + } | ||
| 166 | + } | ||
| 167 | + return letters > 0 | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +// startsUpperCase reports whether a word begins with an ASCII capital. | ||
| 171 | +func startsUpperCase(word string) bool { | ||
| 172 | + return word != "" && word[0] >= 'A' && word[0] <= 'Z' | ||
| 173 | +} | ||
| 174 | + | ||
| 175 | +// knownWords is every word the language itself names, and what each one is. | ||
| 176 | +// | ||
| 177 | +// It is one table rather than four because it answers one question. The four | ||
| 178 | +// groups below are kept apart only so that each can carry the reasoning that | ||
| 179 | +// belongs to it. | ||
| 180 | +// | ||
| 181 | +// The exception hierarchy is deliberately absent. ValueError, KeyError and the | ||
| 182 | +// seventy others are CapWords, so the convention rule in classOfWord already | ||
| 183 | +// colours them as types — and a table naming them would go out of date the next | ||
| 184 | +// time Python adds one. | ||
| 185 | +var knownWords = merge( | ||
| 186 | + classify(syntax.ClassKeyword, keywords), | ||
| 187 | + classify(syntax.ClassConstant, constants), | ||
| 188 | + classify(syntax.ClassType, builtinTypes), | ||
| 189 | + classify(syntax.ClassBuiltin, builtinFunctions), | ||
| 190 | +) | ||
| 191 | + | ||
| 192 | +// keywords are Python's reserved words — the ones that cannot be used as a | ||
| 193 | +// name. and, or, not, in and is are here rather than among the operators | ||
| 194 | +// because that is what the language calls them, and because a theme that quiets | ||
| 195 | +// keywords should quiet them. | ||
| 196 | +// | ||
| 197 | +// match and case are not here: they are reserved in no context at all, and are | ||
| 198 | +// decided by isSoftKeyword. | ||
| 199 | +var keywords = words( | ||
| 200 | + "and", "as", "assert", "async", "await", "break", "class", "continue", | ||
| 201 | + "def", "del", "elif", "else", "except", "finally", "for", "from", "global", | ||
| 202 | + "if", "import", "in", "is", "lambda", "nonlocal", "not", "or", "pass", | ||
| 203 | + "raise", "return", "try", "while", "with", "yield", | ||
| 204 | +) | ||
| 205 | + | ||
| 206 | +// constants are the values the language names, plus the flag it sets for you. | ||
| 207 | +var constants = words("True", "False", "None", "NotImplemented", "Ellipsis", "__debug__") | ||
| 208 | + | ||
| 209 | +// builtinTypes are the types you can call without importing anything. | ||
| 210 | +// | ||
| 211 | +// self and cls are here as *builtins* rather than as types, in builtinFunctions | ||
| 212 | +// below — they name a value, not a type. | ||
| 213 | +var builtinTypes = words( | ||
| 214 | + "bool", "bytearray", "bytes", "complex", "dict", "float", "frozenset", | ||
| 215 | + "int", "list", "memoryview", "object", "range", "set", "slice", "str", | ||
| 216 | + "tuple", "type", | ||
| 217 | +) | ||
| 218 | + | ||
| 219 | +// builtinFunctions are the names in the builtins module, plus the two argument | ||
| 220 | +// names every Python reader reads as the language's own. | ||
| 221 | +// | ||
| 222 | +// self and cls are a convention rather than a rule — a method may name its | ||
| 223 | +// first parameter anything — but the convention is universal enough that every | ||
| 224 | +// other highlighter colours them, and a reader who meets `self` reads it the | ||
| 225 | +// way a Rust reader reads `Some`. That parallel is the argument; the caveat is | ||
| 226 | +// that a parameter honestly named self in a plain function is coloured too. | ||
| 227 | +var builtinFunctions = words( | ||
| 228 | + "abs", "aiter", "anext", "all", "any", "ascii", "bin", "breakpoint", | ||
| 229 | + "callable", "chr", "classmethod", "compile", "delattr", "dir", "divmod", | ||
| 230 | + "enumerate", "eval", "exec", "filter", "format", "getattr", "globals", | ||
| 231 | + "hasattr", "hash", "help", "hex", "id", "input", "isinstance", "issubclass", | ||
| 232 | + "iter", "len", "locals", "map", "max", "min", "next", "oct", "open", "ord", | ||
| 233 | + "pow", "print", "property", "repr", "reversed", "round", "setattr", | ||
| 234 | + "sorted", "staticmethod", "sum", "super", "vars", "zip", | ||
| 235 | + "self", "cls", | ||
| 236 | +) | ||
| 237 | + | ||
| 238 | +// words gathers a group of them, which reads better at the call sites above | ||
| 239 | +// than a slice literal does. | ||
| 240 | +func words(list ...string) []string { return list } | ||
| 241 | + | ||
| 242 | +// classify pairs every word in a group with the class it belongs to. | ||
| 243 | +func classify(class syntax.Class, list []string) map[string]syntax.Class { | ||
| 244 | + out := make(map[string]syntax.Class, len(list)) | ||
| 245 | + for _, word := range list { | ||
| 246 | + out[word] = class | ||
| 247 | + } | ||
| 248 | + return out | ||
| 249 | +} | ||
| 250 | + | ||
| 251 | +// merge folds the groups into one table. An earlier group wins a word a later | ||
| 252 | +// one repeats, which is what keeps a keyword a keyword. | ||
| 253 | +func merge(groups ...map[string]syntax.Class) map[string]syntax.Class { | ||
| 254 | + out := map[string]syntax.Class{} | ||
| 255 | + for _, group := range groups { | ||
| 256 | + for word, class := range group { | ||
| 257 | + if _, taken := out[word]; !taken { | ||
| 258 | + out[word] = class | ||
| 259 | + } | ||
| 260 | + } | ||
| 261 | + } | ||
| 262 | + return out | ||
| 263 | +} | ||
added
main.go +204 -0 | new file mode 100644 | ||
| @@ -0,0 +1,204 @@ | ||
| 1 | +// Command turbo-python is a Turbo C-style editor for Python: a full-screen | |
| 2 | +// terminal IDE with menus, movable windows, syntax colouring and completion | |
| 3 | +// from python-lsp-server. | |
| 4 | +// | |
| 5 | +// Almost all of it is turbo-core, the library every Turbo editor is built on. | |
| 6 | +// What is here is the command line, the terminal, and internal/pythonlang — the | |
| 7 | +// profile that says this one is for Python. | |
| 8 | +// | |
| 9 | +// Usage: | |
| 10 | +// | |
| 11 | +// turbo-python [flags] [file...] | |
| 12 | +// | |
| 13 | +// Flags: | |
| 14 | +// | |
| 15 | +// -theme name the colour theme to start with, overriding the project's | |
| 16 | +// -list-themes print the available themes and exit | |
| 17 | +// -no-lsp do not start a language server | |
| 18 | +// -version print the version and exit | |
| 19 | +package main | |
| 20 | + | |
| 21 | +import ( | |
| 22 | + "context" | |
| 23 | + "errors" | |
| 24 | + "flag" | |
| 25 | + "fmt" | |
| 26 | + "os" | |
| 27 | + | |
| 28 | + "github.com/gdamore/tcell/v2" | |
| 29 | + | |
| 30 | + "rickub.com/turbo-editors/turbo-core/app" | |
| 31 | + "rickub.com/turbo-editors/turbo-core/profile" | |
| 32 | + "rickub.com/turbo-editors/turbo-core/settings" | |
| 33 | + "rickub.com/turbo-editors/turbo-core/theme" | |
| 34 | + "rickub.com/turbo-editors/turbo-core/version" | |
| 35 | + | |
| 36 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | |
| 37 | +) | |
| 38 | + | |
| 39 | +func main() { | |
| 40 | + if err := run(); err != nil { | |
| 41 | + fmt.Fprintf(os.Stderr, "%s: %v\n", pythonlang.Slug, err) | |
| 42 | + os.Exit(1) | |
| 43 | + } | |
| 44 | +} | |
| 45 | + | |
| 46 | +// options are what the command line asked for. | |
| 47 | +type options struct { | |
| 48 | + theme string | |
| 49 | + listThemes bool | |
| 50 | + noLSP bool | |
| 51 | + version bool | |
| 52 | + files []string | |
| 53 | +} | |
| 54 | + | |
| 55 | +// parseFlags reads the command line. | |
| 56 | +func parseFlags() options { | |
| 57 | + var opts options | |
| 58 | + | |
| 59 | + // The default is empty rather than the theme's name so that "was -theme | |
| 60 | + // given?" can still be answered afterwards, which is what lets the project | |
| 61 | + // settings fill it in without overriding an explicit choice. | |
| 62 | + flag.StringVar(&opts.theme, "theme", "", "colour theme to start with (default from the project, else "+theme.DefaultName+")") | |
| 63 | + flag.BoolVar(&opts.listThemes, "list-themes", false, "print the available themes and exit") | |
| 64 | + flag.BoolVar(&opts.noLSP, "no-lsp", false, "do not start a language server") | |
| 65 | + flag.BoolVar(&opts.version, "version", false, "print the version and exit") | |
| 66 | + flag.Parse() | |
| 67 | + | |
| 68 | + opts.files = flag.Args() | |
| 69 | + return opts | |
| 70 | +} | |
| 71 | + | |
| 72 | +// run does the work, so that main is nothing but error reporting. | |
| 73 | +func run() error { | |
| 74 | + opts := parseFlags() | |
| 75 | + // Registering here rather than from an init function is what makes "this | |
| 76 | + // editor knows Python" a line somebody can read. | |
| 77 | + pythonlang.Register() | |
| 78 | + p := pythonlang.Profile() | |
| 79 | + | |
| 80 | + switch { | |
| 81 | + case opts.version: | |
| 82 | + fmt.Printf("%s %s\n", p.Name, version.Current()) | |
| 83 | + return nil | |
| 84 | + case opts.listThemes: | |
| 85 | + return listThemes(p) | |
| 86 | + } | |
| 87 | + | |
| 88 | + return edit(opts, p) | |
| 89 | +} | |
| 90 | + | |
| 91 | +// listThemes prints every theme that can be loaded, with its description. | |
| 92 | +func listThemes(p profile.Profile) error { | |
| 93 | + userDir := p.ThemeDir() | |
| 94 | + | |
| 95 | + for _, name := range theme.Available(userDir) { | |
| 96 | + loaded, err := theme.Load(name, userDir) | |
| 97 | + if err != nil { | |
| 98 | + fmt.Printf("%-16s (cannot be loaded: %v)\n", name, err) | |
| 99 | + continue | |
| 100 | + } | |
| 101 | + fmt.Printf("%-16s %s\n", name, loaded.Description()) | |
| 102 | + } | |
| 103 | + | |
| 104 | + if userDir != "" { | |
| 105 | + fmt.Printf("\nYour own themes go in %s\n", userDir) | |
| 106 | + } | |
| 107 | + return nil | |
| 108 | +} | |
| 109 | + | |
| 110 | +// edit opens the terminal and runs the editor until the user leaves. | |
| 111 | +func edit(opts options, p profile.Profile) error { | |
| 112 | + project, projectSettings := loadProjectSettings(p) | |
| 113 | + | |
| 114 | + screen, err := newScreen() | |
| 115 | + if err != nil { | |
| 116 | + return err | |
| 117 | + } | |
| 118 | + // The screen must be given back whatever happens, or a crash leaves the | |
| 119 | + // terminal in raw mode with no cursor. | |
| 120 | + defer screen.Fini() | |
| 121 | + | |
| 122 | + editor := app.New(screen, themeName(opts, projectSettings), p) | |
| 123 | + if settings.Exists(p, project) { | |
| 124 | + editor.UseSettings(projectSettings, settings.Path(p, project)) | |
| 125 | + } | |
| 126 | + openFiles(editor, opts.files) | |
| 127 | + | |
| 128 | + ctx, cancel := context.WithCancel(context.Background()) | |
| 129 | + defer cancel() | |
| 130 | + if !opts.noLSP { | |
| 131 | + editor.StartLanguageServer(ctx, app.ProjectRoot(p, opts.files)) | |
| 132 | + } | |
| 133 | + defer editor.Language().Stop(context.Background()) | |
| 134 | + | |
| 135 | + return editor.Run() | |
| 136 | +} | |
| 137 | + | |
| 138 | +// loadProjectSettings reads .turbo-python/settings.toml from the working | |
| 139 | +// directory, and returns that directory along with what it found. | |
| 140 | +// | |
| 141 | +// The working directory alone is looked in, with no walk up towards the root: | |
| 142 | +// "the project" is where you started the editor, which is a rule you can hold | |
| 143 | +// in your head. A file that is there but unreadable is reported on standard | |
| 144 | +// error and then ignored — a broken settings file must not stop the editor | |
| 145 | +// opening, because the editor is how you would fix it. | |
| 146 | +func loadProjectSettings(p profile.Profile) (string, settings.Settings) { | |
| 147 | + project, err := os.Getwd() | |
| 148 | + if err != nil { | |
| 149 | + project = "." | |
| 150 | + } | |
| 151 | + | |
| 152 | + loaded, err := settings.Load(p, project) | |
| 153 | + switch { | |
| 154 | + case errors.Is(err, settings.ErrNotFound): | |
| 155 | + return project, settings.Default() | |
| 156 | + case err != nil: | |
| 157 | + fmt.Fprintf(os.Stderr, "%s: %v\n", pythonlang.Slug, err) | |
| 158 | + return project, settings.Default() | |
| 159 | + } | |
| 160 | + return project, loaded | |
| 161 | +} | |
| 162 | + | |
| 163 | +// themeName decides which theme to start in. | |
| 164 | +// | |
| 165 | +// A -theme flag wins, because it is the more explicit statement of the two and | |
| 166 | +// is how you try a theme without editing a file everyone shares. The project's | |
| 167 | +// settings come next, and the built-in default last. | |
| 168 | +func themeName(opts options, projectSettings settings.Settings) string { | |
| 169 | + switch { | |
| 170 | + case opts.theme != "": | |
| 171 | + return opts.theme | |
| 172 | + case projectSettings.Theme != "": | |
| 173 | + return projectSettings.Theme | |
| 174 | + default: | |
| 175 | + return theme.DefaultName | |
| 176 | + } | |
| 177 | +} | |
| 178 | + | |
| 179 | +// newScreen opens the terminal and turns on what the editor needs from it. | |
| 180 | +func newScreen() (tcell.Screen, error) { | |
| 181 | + screen, err := tcell.NewScreen() | |
| 182 | + if err != nil { | |
| 183 | + return nil, fmt.Errorf("opening the terminal: %w", err) | |
| 184 | + } | |
| 185 | + if err := screen.Init(); err != nil { | |
| 186 | + return nil, fmt.Errorf("initialising the terminal: %w", err) | |
| 187 | + } | |
| 188 | + | |
| 189 | + screen.EnableMouse() | |
| 190 | + screen.EnablePaste() | |
| 191 | + return screen, nil | |
| 192 | +} | |
| 193 | + | |
| 194 | +// openFiles opens the files named on the command line, or an empty window when | |
| 195 | +// none were. | |
| 196 | +func openFiles(editor *app.App, files []string) { | |
| 197 | + if len(files) == 0 { | |
| 198 | + editor.NewFile() | |
| 199 | + return | |
| 200 | + } | |
| 201 | + for _, file := range files { | |
| 202 | + editor.Open(file) | |
| 203 | + } | |
| 204 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,204 @@ | |||
| 1 | +// Command turbo-python is a Turbo C-style editor for Python: a full-screen | ||
| 2 | +// terminal IDE with menus, movable windows, syntax colouring and completion | ||
| 3 | +// from python-lsp-server. | ||
| 4 | +// | ||
| 5 | +// Almost all of it is turbo-core, the library every Turbo editor is built on. | ||
| 6 | +// What is here is the command line, the terminal, and internal/pythonlang — the | ||
| 7 | +// profile that says this one is for Python. | ||
| 8 | +// | ||
| 9 | +// Usage: | ||
| 10 | +// | ||
| 11 | +// turbo-python [flags] [file...] | ||
| 12 | +// | ||
| 13 | +// Flags: | ||
| 14 | +// | ||
| 15 | +// -theme name the colour theme to start with, overriding the project's | ||
| 16 | +// -list-themes print the available themes and exit | ||
| 17 | +// -no-lsp do not start a language server | ||
| 18 | +// -version print the version and exit | ||
| 19 | +package main | ||
| 20 | + | ||
| 21 | +import ( | ||
| 22 | + "context" | ||
| 23 | + "errors" | ||
| 24 | + "flag" | ||
| 25 | + "fmt" | ||
| 26 | + "os" | ||
| 27 | + | ||
| 28 | + "github.com/gdamore/tcell/v2" | ||
| 29 | + | ||
| 30 | + "rickub.com/turbo-editors/turbo-core/app" | ||
| 31 | + "rickub.com/turbo-editors/turbo-core/profile" | ||
| 32 | + "rickub.com/turbo-editors/turbo-core/settings" | ||
| 33 | + "rickub.com/turbo-editors/turbo-core/theme" | ||
| 34 | + "rickub.com/turbo-editors/turbo-core/version" | ||
| 35 | + | ||
| 36 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | ||
| 37 | +) | ||
| 38 | + | ||
| 39 | +func main() { | ||
| 40 | + if err := run(); err != nil { | ||
| 41 | + fmt.Fprintf(os.Stderr, "%s: %v\n", pythonlang.Slug, err) | ||
| 42 | + os.Exit(1) | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +// options are what the command line asked for. | ||
| 47 | +type options struct { | ||
| 48 | + theme string | ||
| 49 | + listThemes bool | ||
| 50 | + noLSP bool | ||
| 51 | + version bool | ||
| 52 | + files []string | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +// parseFlags reads the command line. | ||
| 56 | +func parseFlags() options { | ||
| 57 | + var opts options | ||
| 58 | + | ||
| 59 | + // The default is empty rather than the theme's name so that "was -theme | ||
| 60 | + // given?" can still be answered afterwards, which is what lets the project | ||
| 61 | + // settings fill it in without overriding an explicit choice. | ||
| 62 | + flag.StringVar(&opts.theme, "theme", "", "colour theme to start with (default from the project, else "+theme.DefaultName+")") | ||
| 63 | + flag.BoolVar(&opts.listThemes, "list-themes", false, "print the available themes and exit") | ||
| 64 | + flag.BoolVar(&opts.noLSP, "no-lsp", false, "do not start a language server") | ||
| 65 | + flag.BoolVar(&opts.version, "version", false, "print the version and exit") | ||
| 66 | + flag.Parse() | ||
| 67 | + | ||
| 68 | + opts.files = flag.Args() | ||
| 69 | + return opts | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +// run does the work, so that main is nothing but error reporting. | ||
| 73 | +func run() error { | ||
| 74 | + opts := parseFlags() | ||
| 75 | + // Registering here rather than from an init function is what makes "this | ||
| 76 | + // editor knows Python" a line somebody can read. | ||
| 77 | + pythonlang.Register() | ||
| 78 | + p := pythonlang.Profile() | ||
| 79 | + | ||
| 80 | + switch { | ||
| 81 | + case opts.version: | ||
| 82 | + fmt.Printf("%s %s\n", p.Name, version.Current()) | ||
| 83 | + return nil | ||
| 84 | + case opts.listThemes: | ||
| 85 | + return listThemes(p) | ||
| 86 | + } | ||
| 87 | + | ||
| 88 | + return edit(opts, p) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +// listThemes prints every theme that can be loaded, with its description. | ||
| 92 | +func listThemes(p profile.Profile) error { | ||
| 93 | + userDir := p.ThemeDir() | ||
| 94 | + | ||
| 95 | + for _, name := range theme.Available(userDir) { | ||
| 96 | + loaded, err := theme.Load(name, userDir) | ||
| 97 | + if err != nil { | ||
| 98 | + fmt.Printf("%-16s (cannot be loaded: %v)\n", name, err) | ||
| 99 | + continue | ||
| 100 | + } | ||
| 101 | + fmt.Printf("%-16s %s\n", name, loaded.Description()) | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + if userDir != "" { | ||
| 105 | + fmt.Printf("\nYour own themes go in %s\n", userDir) | ||
| 106 | + } | ||
| 107 | + return nil | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +// edit opens the terminal and runs the editor until the user leaves. | ||
| 111 | +func edit(opts options, p profile.Profile) error { | ||
| 112 | + project, projectSettings := loadProjectSettings(p) | ||
| 113 | + | ||
| 114 | + screen, err := newScreen() | ||
| 115 | + if err != nil { | ||
| 116 | + return err | ||
| 117 | + } | ||
| 118 | + // The screen must be given back whatever happens, or a crash leaves the | ||
| 119 | + // terminal in raw mode with no cursor. | ||
| 120 | + defer screen.Fini() | ||
| 121 | + | ||
| 122 | + editor := app.New(screen, themeName(opts, projectSettings), p) | ||
| 123 | + if settings.Exists(p, project) { | ||
| 124 | + editor.UseSettings(projectSettings, settings.Path(p, project)) | ||
| 125 | + } | ||
| 126 | + openFiles(editor, opts.files) | ||
| 127 | + | ||
| 128 | + ctx, cancel := context.WithCancel(context.Background()) | ||
| 129 | + defer cancel() | ||
| 130 | + if !opts.noLSP { | ||
| 131 | + editor.StartLanguageServer(ctx, app.ProjectRoot(p, opts.files)) | ||
| 132 | + } | ||
| 133 | + defer editor.Language().Stop(context.Background()) | ||
| 134 | + | ||
| 135 | + return editor.Run() | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +// loadProjectSettings reads .turbo-python/settings.toml from the working | ||
| 139 | +// directory, and returns that directory along with what it found. | ||
| 140 | +// | ||
| 141 | +// The working directory alone is looked in, with no walk up towards the root: | ||
| 142 | +// "the project" is where you started the editor, which is a rule you can hold | ||
| 143 | +// in your head. A file that is there but unreadable is reported on standard | ||
| 144 | +// error and then ignored — a broken settings file must not stop the editor | ||
| 145 | +// opening, because the editor is how you would fix it. | ||
| 146 | +func loadProjectSettings(p profile.Profile) (string, settings.Settings) { | ||
| 147 | + project, err := os.Getwd() | ||
| 148 | + if err != nil { | ||
| 149 | + project = "." | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + loaded, err := settings.Load(p, project) | ||
| 153 | + switch { | ||
| 154 | + case errors.Is(err, settings.ErrNotFound): | ||
| 155 | + return project, settings.Default() | ||
| 156 | + case err != nil: | ||
| 157 | + fmt.Fprintf(os.Stderr, "%s: %v\n", pythonlang.Slug, err) | ||
| 158 | + return project, settings.Default() | ||
| 159 | + } | ||
| 160 | + return project, loaded | ||
| 161 | +} | ||
| 162 | + | ||
| 163 | +// themeName decides which theme to start in. | ||
| 164 | +// | ||
| 165 | +// A -theme flag wins, because it is the more explicit statement of the two and | ||
| 166 | +// is how you try a theme without editing a file everyone shares. The project's | ||
| 167 | +// settings come next, and the built-in default last. | ||
| 168 | +func themeName(opts options, projectSettings settings.Settings) string { | ||
| 169 | + switch { | ||
| 170 | + case opts.theme != "": | ||
| 171 | + return opts.theme | ||
| 172 | + case projectSettings.Theme != "": | ||
| 173 | + return projectSettings.Theme | ||
| 174 | + default: | ||
| 175 | + return theme.DefaultName | ||
| 176 | + } | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +// newScreen opens the terminal and turns on what the editor needs from it. | ||
| 180 | +func newScreen() (tcell.Screen, error) { | ||
| 181 | + screen, err := tcell.NewScreen() | ||
| 182 | + if err != nil { | ||
| 183 | + return nil, fmt.Errorf("opening the terminal: %w", err) | ||
| 184 | + } | ||
| 185 | + if err := screen.Init(); err != nil { | ||
| 186 | + return nil, fmt.Errorf("initialising the terminal: %w", err) | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + screen.EnableMouse() | ||
| 190 | + screen.EnablePaste() | ||
| 191 | + return screen, nil | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +// openFiles opens the files named on the command line, or an empty window when | ||
| 195 | +// none were. | ||
| 196 | +func openFiles(editor *app.App, files []string) { | ||
| 197 | + if len(files) == 0 { | ||
| 198 | + editor.NewFile() | ||
| 199 | + return | ||
| 200 | + } | ||
| 201 | + for _, file := range files { | ||
| 202 | + editor.Open(file) | ||
| 203 | + } | ||
| 204 | +} | ||
added
main_test.go +156 -0 | new file mode 100644 | ||
| @@ -0,0 +1,156 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "os" | |
| 5 | + "path/filepath" | |
| 6 | + "testing" | |
| 7 | + | |
| 8 | + "rickub.com/turbo-editors/turbo-core/app" | |
| 9 | + "rickub.com/turbo-editors/turbo-core/settings" | |
| 10 | + "rickub.com/turbo-editors/turbo-core/theme" | |
| 11 | + | |
| 12 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | |
| 13 | +) | |
| 14 | + | |
| 15 | +// Each of the three markers finds the root on its own, and the walk stops at | |
| 16 | +// the nearest directory holding any of them. pylsp is started there, and it is | |
| 17 | +// what decides the code the server loads. | |
| 18 | +func TestTheProjectRootIsFoundByAnyOfTheThreeMarkers(t *testing.T) { | |
| 19 | + markers := map[string]string{ | |
| 20 | + "pyproject.toml": "[project]\nname = \"x\"\n", | |
| 21 | + "setup.py": "from setuptools import setup\n\nsetup()\n", | |
| 22 | + "setup.cfg": "[metadata]\nname = x\n", | |
| 23 | + } | |
| 24 | + | |
| 25 | + for marker, contents := range markers { | |
| 26 | + t.Run(marker, func(t *testing.T) { | |
| 27 | + root := t.TempDir() | |
| 28 | + writeFile(t, filepath.Join(root, marker), contents) | |
| 29 | + file := filepath.Join(root, "src", "package", "deep.py") | |
| 30 | + writeFile(t, file, "def f() -> None:\n pass\n") | |
| 31 | + | |
| 32 | + if got := app.ProjectRoot(pythonlang.Profile(), []string{file}); got != root { | |
| 33 | + t.Errorf("ProjectRoot() = %q, want the project root %q", got, root) | |
| 34 | + } | |
| 35 | + }) | |
| 36 | + } | |
| 37 | +} | |
| 38 | + | |
| 39 | +// A directory with none of the three is its own root: the walk must not climb | |
| 40 | +// past a project into whatever is above it. | |
| 41 | +func TestAFileInNoProjectIsItsOwnRoot(t *testing.T) { | |
| 42 | + root := t.TempDir() | |
| 43 | + file := filepath.Join(root, "script.py") | |
| 44 | + writeFile(t, file, "print(1)\n") | |
| 45 | + | |
| 46 | + if got := app.ProjectRoot(pythonlang.Profile(), []string{file}); got != root { | |
| 47 | + t.Errorf("ProjectRoot() = %q, want the file's own directory %q", got, root) | |
| 48 | + } | |
| 49 | +} | |
| 50 | + | |
| 51 | +// writeFile creates a file, making its directory first. | |
| 52 | +func writeFile(t *testing.T, path, contents string) { | |
| 53 | + t.Helper() | |
| 54 | + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { | |
| 55 | + t.Fatalf("creating %s: %v", filepath.Dir(path), err) | |
| 56 | + } | |
| 57 | + if err := os.WriteFile(path, []byte(contents), 0o644); err != nil { | |
| 58 | + t.Fatalf("writing %s: %v", path, err) | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +func TestThemeNamePrefersTheFlagOverTheProject(t *testing.T) { | |
| 63 | + got := themeName(options{theme: "borland-light"}, settings.Settings{Theme: "turbo-dark"}) | |
| 64 | + | |
| 65 | + if got != "borland-light" { | |
| 66 | + t.Errorf("themeName() = %q; an explicit -theme must win over the project's", got) | |
| 67 | + } | |
| 68 | +} | |
| 69 | + | |
| 70 | +func TestThemeNameUsesTheProjectWhenNoFlagWasGiven(t *testing.T) { | |
| 71 | + got := themeName(options{}, settings.Settings{Theme: "turbo-dark"}) | |
| 72 | + | |
| 73 | + if got != "turbo-dark" { | |
| 74 | + t.Errorf("themeName() = %q, want the project's theme", got) | |
| 75 | + } | |
| 76 | +} | |
| 77 | + | |
| 78 | +func TestThemeNameFallsBackToTheDefault(t *testing.T) { | |
| 79 | + got := themeName(options{}, settings.Settings{}) | |
| 80 | + | |
| 81 | + if got != theme.DefaultName { | |
| 82 | + t.Errorf("themeName() = %q, want %q", got, theme.DefaultName) | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +func TestLoadProjectSettingsReadsTheWorkingDirectory(t *testing.T) { | |
| 87 | + project := t.TempDir() | |
| 88 | + t.Chdir(project) | |
| 89 | + if err := os.MkdirAll(settings.Dir(pythonlang.Profile(), project), 0o755); err != nil { | |
| 90 | + t.Fatalf("creating the settings directory: %v", err) | |
| 91 | + } | |
| 92 | + contents := "[editor]\ntheme = \"turbo-dark\"\nautosave = true\n" | |
| 93 | + if err := os.WriteFile(settings.Path(pythonlang.Profile(), project), []byte(contents), 0o644); err != nil { | |
| 94 | + t.Fatalf("writing the settings file: %v", err) | |
| 95 | + } | |
| 96 | + | |
| 97 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | |
| 98 | + | |
| 99 | + if loaded.Theme != "turbo-dark" { | |
| 100 | + t.Errorf("Theme = %q, want turbo-dark", loaded.Theme) | |
| 101 | + } | |
| 102 | + if !loaded.Autosave { | |
| 103 | + t.Error("Autosave = false, want the file's true") | |
| 104 | + } | |
| 105 | +} | |
| 106 | + | |
| 107 | +func TestLoadProjectSettingsDoesNotWalkUpToAParent(t *testing.T) { | |
| 108 | + // "The project is where you started the editor" is the rule; a settings | |
| 109 | + // file one directory up belongs to a different project. | |
| 110 | + parent := t.TempDir() | |
| 111 | + if err := os.MkdirAll(settings.Dir(pythonlang.Profile(), parent), 0o755); err != nil { | |
| 112 | + t.Fatalf("creating the settings directory: %v", err) | |
| 113 | + } | |
| 114 | + if err := os.WriteFile(settings.Path(pythonlang.Profile(), parent), []byte("[editor]\ntheme = \"turbo-dark\"\n"), 0o644); err != nil { | |
| 115 | + t.Fatalf("writing the settings file: %v", err) | |
| 116 | + } | |
| 117 | + child := filepath.Join(parent, "src") | |
| 118 | + if err := os.Mkdir(child, 0o755); err != nil { | |
| 119 | + t.Fatalf("creating the child directory: %v", err) | |
| 120 | + } | |
| 121 | + t.Chdir(child) | |
| 122 | + | |
| 123 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | |
| 124 | + | |
| 125 | + if loaded.Theme != "" { | |
| 126 | + t.Errorf("Theme = %q; settings were read from a parent directory", loaded.Theme) | |
| 127 | + } | |
| 128 | +} | |
| 129 | + | |
| 130 | +func TestLoadProjectSettingsCarriesOnWithoutAFile(t *testing.T) { | |
| 131 | + t.Chdir(t.TempDir()) | |
| 132 | + | |
| 133 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | |
| 134 | + | |
| 135 | + if loaded != settings.Default() { | |
| 136 | + t.Errorf("loadProjectSettings(pythonlang.Profile()) = %+v, want the defaults", loaded) | |
| 137 | + } | |
| 138 | +} | |
| 139 | + | |
| 140 | +func TestABrokenSettingsFileDoesNotStopTheEditor(t *testing.T) { | |
| 141 | + // The editor is how you would fix the file, so it has to open. | |
| 142 | + project := t.TempDir() | |
| 143 | + t.Chdir(project) | |
| 144 | + if err := os.MkdirAll(settings.Dir(pythonlang.Profile(), project), 0o755); err != nil { | |
| 145 | + t.Fatalf("creating the settings directory: %v", err) | |
| 146 | + } | |
| 147 | + if err := os.WriteFile(settings.Path(pythonlang.Profile(), project), []byte("[editor\nnot toml"), 0o644); err != nil { | |
| 148 | + t.Fatalf("writing the settings file: %v", err) | |
| 149 | + } | |
| 150 | + | |
| 151 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | |
| 152 | + | |
| 153 | + if loaded != settings.Default() { | |
| 154 | + t.Errorf("loadProjectSettings(pythonlang.Profile()) = %+v, want the defaults", loaded) | |
| 155 | + } | |
| 156 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,156 @@ | |||
| 1 | +package main | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "os" | ||
| 5 | + "path/filepath" | ||
| 6 | + "testing" | ||
| 7 | + | ||
| 8 | + "rickub.com/turbo-editors/turbo-core/app" | ||
| 9 | + "rickub.com/turbo-editors/turbo-core/settings" | ||
| 10 | + "rickub.com/turbo-editors/turbo-core/theme" | ||
| 11 | + | ||
| 12 | + "rickub.com/turbo-editors/turbo-python/internal/pythonlang" | ||
| 13 | +) | ||
| 14 | + | ||
| 15 | +// Each of the three markers finds the root on its own, and the walk stops at | ||
| 16 | +// the nearest directory holding any of them. pylsp is started there, and it is | ||
| 17 | +// what decides the code the server loads. | ||
| 18 | +func TestTheProjectRootIsFoundByAnyOfTheThreeMarkers(t *testing.T) { | ||
| 19 | + markers := map[string]string{ | ||
| 20 | + "pyproject.toml": "[project]\nname = \"x\"\n", | ||
| 21 | + "setup.py": "from setuptools import setup\n\nsetup()\n", | ||
| 22 | + "setup.cfg": "[metadata]\nname = x\n", | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + for marker, contents := range markers { | ||
| 26 | + t.Run(marker, func(t *testing.T) { | ||
| 27 | + root := t.TempDir() | ||
| 28 | + writeFile(t, filepath.Join(root, marker), contents) | ||
| 29 | + file := filepath.Join(root, "src", "package", "deep.py") | ||
| 30 | + writeFile(t, file, "def f() -> None:\n pass\n") | ||
| 31 | + | ||
| 32 | + if got := app.ProjectRoot(pythonlang.Profile(), []string{file}); got != root { | ||
| 33 | + t.Errorf("ProjectRoot() = %q, want the project root %q", got, root) | ||
| 34 | + } | ||
| 35 | + }) | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +// A directory with none of the three is its own root: the walk must not climb | ||
| 40 | +// past a project into whatever is above it. | ||
| 41 | +func TestAFileInNoProjectIsItsOwnRoot(t *testing.T) { | ||
| 42 | + root := t.TempDir() | ||
| 43 | + file := filepath.Join(root, "script.py") | ||
| 44 | + writeFile(t, file, "print(1)\n") | ||
| 45 | + | ||
| 46 | + if got := app.ProjectRoot(pythonlang.Profile(), []string{file}); got != root { | ||
| 47 | + t.Errorf("ProjectRoot() = %q, want the file's own directory %q", got, root) | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +// writeFile creates a file, making its directory first. | ||
| 52 | +func writeFile(t *testing.T, path, contents string) { | ||
| 53 | + t.Helper() | ||
| 54 | + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { | ||
| 55 | + t.Fatalf("creating %s: %v", filepath.Dir(path), err) | ||
| 56 | + } | ||
| 57 | + if err := os.WriteFile(path, []byte(contents), 0o644); err != nil { | ||
| 58 | + t.Fatalf("writing %s: %v", path, err) | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +func TestThemeNamePrefersTheFlagOverTheProject(t *testing.T) { | ||
| 63 | + got := themeName(options{theme: "borland-light"}, settings.Settings{Theme: "turbo-dark"}) | ||
| 64 | + | ||
| 65 | + if got != "borland-light" { | ||
| 66 | + t.Errorf("themeName() = %q; an explicit -theme must win over the project's", got) | ||
| 67 | + } | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +func TestThemeNameUsesTheProjectWhenNoFlagWasGiven(t *testing.T) { | ||
| 71 | + got := themeName(options{}, settings.Settings{Theme: "turbo-dark"}) | ||
| 72 | + | ||
| 73 | + if got != "turbo-dark" { | ||
| 74 | + t.Errorf("themeName() = %q, want the project's theme", got) | ||
| 75 | + } | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +func TestThemeNameFallsBackToTheDefault(t *testing.T) { | ||
| 79 | + got := themeName(options{}, settings.Settings{}) | ||
| 80 | + | ||
| 81 | + if got != theme.DefaultName { | ||
| 82 | + t.Errorf("themeName() = %q, want %q", got, theme.DefaultName) | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +func TestLoadProjectSettingsReadsTheWorkingDirectory(t *testing.T) { | ||
| 87 | + project := t.TempDir() | ||
| 88 | + t.Chdir(project) | ||
| 89 | + if err := os.MkdirAll(settings.Dir(pythonlang.Profile(), project), 0o755); err != nil { | ||
| 90 | + t.Fatalf("creating the settings directory: %v", err) | ||
| 91 | + } | ||
| 92 | + contents := "[editor]\ntheme = \"turbo-dark\"\nautosave = true\n" | ||
| 93 | + if err := os.WriteFile(settings.Path(pythonlang.Profile(), project), []byte(contents), 0o644); err != nil { | ||
| 94 | + t.Fatalf("writing the settings file: %v", err) | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | ||
| 98 | + | ||
| 99 | + if loaded.Theme != "turbo-dark" { | ||
| 100 | + t.Errorf("Theme = %q, want turbo-dark", loaded.Theme) | ||
| 101 | + } | ||
| 102 | + if !loaded.Autosave { | ||
| 103 | + t.Error("Autosave = false, want the file's true") | ||
| 104 | + } | ||
| 105 | +} | ||
| 106 | + | ||
| 107 | +func TestLoadProjectSettingsDoesNotWalkUpToAParent(t *testing.T) { | ||
| 108 | + // "The project is where you started the editor" is the rule; a settings | ||
| 109 | + // file one directory up belongs to a different project. | ||
| 110 | + parent := t.TempDir() | ||
| 111 | + if err := os.MkdirAll(settings.Dir(pythonlang.Profile(), parent), 0o755); err != nil { | ||
| 112 | + t.Fatalf("creating the settings directory: %v", err) | ||
| 113 | + } | ||
| 114 | + if err := os.WriteFile(settings.Path(pythonlang.Profile(), parent), []byte("[editor]\ntheme = \"turbo-dark\"\n"), 0o644); err != nil { | ||
| 115 | + t.Fatalf("writing the settings file: %v", err) | ||
| 116 | + } | ||
| 117 | + child := filepath.Join(parent, "src") | ||
| 118 | + if err := os.Mkdir(child, 0o755); err != nil { | ||
| 119 | + t.Fatalf("creating the child directory: %v", err) | ||
| 120 | + } | ||
| 121 | + t.Chdir(child) | ||
| 122 | + | ||
| 123 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | ||
| 124 | + | ||
| 125 | + if loaded.Theme != "" { | ||
| 126 | + t.Errorf("Theme = %q; settings were read from a parent directory", loaded.Theme) | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +func TestLoadProjectSettingsCarriesOnWithoutAFile(t *testing.T) { | ||
| 131 | + t.Chdir(t.TempDir()) | ||
| 132 | + | ||
| 133 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | ||
| 134 | + | ||
| 135 | + if loaded != settings.Default() { | ||
| 136 | + t.Errorf("loadProjectSettings(pythonlang.Profile()) = %+v, want the defaults", loaded) | ||
| 137 | + } | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +func TestABrokenSettingsFileDoesNotStopTheEditor(t *testing.T) { | ||
| 141 | + // The editor is how you would fix the file, so it has to open. | ||
| 142 | + project := t.TempDir() | ||
| 143 | + t.Chdir(project) | ||
| 144 | + if err := os.MkdirAll(settings.Dir(pythonlang.Profile(), project), 0o755); err != nil { | ||
| 145 | + t.Fatalf("creating the settings directory: %v", err) | ||
| 146 | + } | ||
| 147 | + if err := os.WriteFile(settings.Path(pythonlang.Profile(), project), []byte("[editor\nnot toml"), 0o644); err != nil { | ||
| 148 | + t.Fatalf("writing the settings file: %v", err) | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + _, loaded := loadProjectSettings(pythonlang.Profile()) | ||
| 152 | + | ||
| 153 | + if loaded != settings.Default() { | ||
| 154 | + t.Errorf("loadProjectSettings(pythonlang.Profile()) = %+v, want the defaults", loaded) | ||
| 155 | + } | ||
| 156 | +} | ||
added
new.branch.sh +3 -0 | new file mode 100755 | ||
| @@ -0,0 +1,3 @@ | ||
| 1 | +#!/bin/bash | |
| 2 | +git switch -c "$1" | |
| 3 | +git push -u origin "$1" | |
| new file mode 100755 | |||
| @@ -0,0 +1,3 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +git switch -c "$1" | ||
| 3 | +git push -u origin "$1" | ||
added
new.feature.sh +6 -0 | new file mode 100755 | ||
| @@ -0,0 +1,6 @@ | ||
| 1 | +#!/bin/bash | |
| 2 | +git switch -c feature/"$1" | |
| 3 | +# touch new.feature.txt | |
| 4 | +# git add . | |
| 5 | +# git commit -m "$1" | |
| 6 | +git push -u origin feature/"$1" | |
| new file mode 100755 | |||
| @@ -0,0 +1,6 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +git switch -c feature/"$1" | ||
| 3 | +# touch new.feature.txt | ||
| 4 | +# git add . | ||
| 5 | +# git commit -m "$1" | ||
| 6 | +git push -u origin feature/"$1" | ||
added
new.fix.sh +6 -0 | new file mode 100755 | ||
| @@ -0,0 +1,6 @@ | ||
| 1 | +#!/bin/bash | |
| 2 | +git switch -c fix/"$1" | |
| 3 | +#touch new.fix.txt | |
| 4 | +# git add . | |
| 5 | +# git commit -m "$1" | |
| 6 | +git push -u origin fix/"$1" | |
| new file mode 100755 | |||
| @@ -0,0 +1,6 @@ | |||
| 1 | +#!/bin/bash | ||
| 2 | +git switch -c fix/"$1" | ||
| 3 | +#touch new.fix.txt | ||
| 4 | +# git add . | ||
| 5 | +# git commit -m "$1" | ||
| 6 | +git push -u origin fix/"$1" | ||
added
release_test.go +594 -0 | new file mode 100644 | ||
| @@ -0,0 +1,594 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "os" | |
| 5 | + "os/exec" | |
| 6 | + "path/filepath" | |
| 7 | + "runtime" | |
| 8 | + "strings" | |
| 9 | + "testing" | |
| 10 | +) | |
| 11 | + | |
| 12 | +// readReleaseScript returns the release builder, so its rules can be asserted | |
| 13 | +// without running it: running it cross-compiles five binaries, which is not a | |
| 14 | +// unit test. (Running the tagging script, on the other hand, is done below, | |
| 15 | +// against a throwaway clone.) | |
| 16 | +func readReleaseScript(t *testing.T) string { | |
| 17 | + t.Helper() | |
| 18 | + | |
| 19 | + script, err := os.ReadFile("02-build-releases.sh") | |
| 20 | + if err != nil { | |
| 21 | + t.Fatalf("cannot read the release script: %v", err) | |
| 22 | + } | |
| 23 | + return string(script) | |
| 24 | +} | |
| 25 | + | |
| 26 | +func TestTheReleaseScriptStampsTheBinariesItShips(t *testing.T) { | |
| 27 | + // Without -ldflags on the cross-compile, every downloaded binary reports | |
| 28 | + // "devel" while the release page names a version. The host binary would | |
| 29 | + // still be right, so nothing but this notices. | |
| 30 | + script := readReleaseScript(t) | |
| 31 | + | |
| 32 | + build := commandContaining(t, script, "GOARCH=") | |
| 33 | + if !strings.Contains(build, "-ldflags") { | |
| 34 | + t.Errorf("the cross-compile does not stamp a version:\n%s", build) | |
| 35 | + } | |
| 36 | +} | |
| 37 | + | |
| 38 | +func TestTheReleaseScriptTakesTheStampFromTheMakefile(t *testing.T) { | |
| 39 | + // Repeating the -X paths in the script is how the host binary and the | |
| 40 | + // downloads would come to disagree about which package holds the version. | |
| 41 | + script := readReleaseScript(t) | |
| 42 | + | |
| 43 | + if !strings.Contains(script, "make --no-print-directory ldflags") { | |
| 44 | + t.Error("the script does not read the linker flags from the Makefile") | |
| 45 | + } | |
| 46 | + if strings.Contains(script, "version.stamp=") { | |
| 47 | + t.Error("the script spells out the -X path, which the Makefile already owns") | |
| 48 | + } | |
| 49 | +} | |
| 50 | + | |
| 51 | +func TestTheReleaseScriptStampsTheTagItIsReleasing(t *testing.T) { | |
| 52 | + // The release *is* ${TAG}, so that is what the binaries say. Letting the | |
| 53 | + // Makefile's default stand would stamp `git describe`, which answers a | |
| 54 | + // different question — where HEAD is — and disagrees the moment anyone | |
| 55 | + // commits after tagging. | |
| 56 | + script := readReleaseScript(t) | |
| 57 | + | |
| 58 | + flags := commandContaining(t, script, "ldflags") | |
| 59 | + if !strings.Contains(flags, `VERSION="${TAG}"`) { | |
| 60 | + t.Errorf("the stamp does not come from TAG:\n%s", flags) | |
| 61 | + } | |
| 62 | + if build := commandContaining(t, script, "make build"); !strings.Contains(build, `VERSION="${TAG}"`) { | |
| 63 | + t.Errorf("the host build carries a different version from the assets:\n%s", build) | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +func TestTheReleaseScriptDoesNotParseTheVersionOutOfProse(t *testing.T) { | |
| 68 | + // `-version` is written for a person and has changed shape once already; | |
| 69 | + // awk '{print $NF}' on it read a timestamp and failed a release. | |
| 70 | + script := readReleaseScript(t) | |
| 71 | + | |
| 72 | + if strings.Contains(script, "$NF") { | |
| 73 | + t.Error("the script reads a field out of the -version line, which is prose") | |
| 74 | + } | |
| 75 | +} | |
| 76 | + | |
| 77 | +func TestTheMakefileHandsOutTheFlagsThatStampABuild(t *testing.T) { | |
| 78 | + // The contract the release script depends on: `make ldflags` prints flags | |
| 79 | + // that actually put *the Makefile's own version* into a binary. | |
| 80 | + // | |
| 81 | + // It is checked against `make version` rather than against "not devel", | |
| 82 | + // because a checkout with no tags — a fresh clone, or a repository that has | |
| 83 | + // never had a release — correctly reports devel, and a test that called | |
| 84 | + // that a failure would be testing the tags rather than the flags. | |
| 85 | + version, err := exec.Command("make", "--no-print-directory", "version").Output() | |
| 86 | + if err != nil { | |
| 87 | + t.Fatalf("make version: %v", err) | |
| 88 | + } | |
| 89 | + // internal/version drops the leading v of a tag, so the comparison has to | |
| 90 | + // as well: `make version` says v0.2.1 and the binary says 0.2.1. | |
| 91 | + number := strings.TrimPrefix(strings.Fields(strings.TrimSpace(string(version)))[0], "v") | |
| 92 | + | |
| 93 | + flags, err := exec.Command("make", "--no-print-directory", "ldflags").Output() | |
| 94 | + if err != nil { | |
| 95 | + t.Fatalf("make ldflags: %v", err) | |
| 96 | + } | |
| 97 | + | |
| 98 | + binary := filepath.Join(t.TempDir(), "turbo-python") | |
| 99 | + build := exec.Command("go", "build", "-trimpath", "-ldflags", strings.TrimSpace(string(flags)), "-o", binary, ".") | |
| 100 | + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS="+runtime.GOOS, "GOARCH="+runtime.GOARCH) | |
| 101 | + if out, err := build.CombinedOutput(); err != nil { | |
| 102 | + t.Fatalf("building with those flags failed: %v\n%s", err, out) | |
| 103 | + } | |
| 104 | + | |
| 105 | + reported, err := exec.Command(binary, "-version").Output() | |
| 106 | + if err != nil { | |
| 107 | + t.Fatalf("the stamped binary does not run: %v", err) | |
| 108 | + } | |
| 109 | + if !strings.Contains(string(reported), number) { | |
| 110 | + t.Errorf("-version printed %q, want it to carry the Makefile's version %q", reported, number) | |
| 111 | + } | |
| 112 | + if strings.Contains(string(reported), "unknown") { | |
| 113 | + t.Errorf("-version printed %q, so nothing reached the linker at all", reported) | |
| 114 | + } | |
| 115 | +} | |
| 116 | + | |
| 117 | +func TestMakeLdflagsTakesTheVersionItIsGiven(t *testing.T) { | |
| 118 | + // The release script overrides VERSION with the tag it is releasing, and | |
| 119 | + // everything downstream rests on that override reaching the linker. | |
| 120 | + flags, err := exec.Command("make", "--no-print-directory", "ldflags", "VERSION=v9.9.9").Output() | |
| 121 | + if err != nil { | |
| 122 | + t.Fatalf("make ldflags: %v", err) | |
| 123 | + } | |
| 124 | + | |
| 125 | + binary := filepath.Join(t.TempDir(), "turbo-python") | |
| 126 | + build := exec.Command("go", "build", "-trimpath", "-ldflags", strings.TrimSpace(string(flags)), "-o", binary, ".") | |
| 127 | + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS="+runtime.GOOS, "GOARCH="+runtime.GOARCH) | |
| 128 | + if out, err := build.CombinedOutput(); err != nil { | |
| 129 | + t.Fatalf("building with those flags failed: %v\n%s", err, out) | |
| 130 | + } | |
| 131 | + | |
| 132 | + reported, err := exec.Command(binary, "-version").Output() | |
| 133 | + if err != nil { | |
| 134 | + t.Fatalf("the stamped binary does not run: %v", err) | |
| 135 | + } | |
| 136 | + if !strings.Contains(string(reported), "9.9.9") { | |
| 137 | + t.Errorf("-version printed %q, so VERSION=v9.9.9 never reached the linker", reported) | |
| 138 | + } | |
| 139 | +} | |
| 140 | + | |
| 141 | +// commandContaining returns the first shell command of a script holding a | |
| 142 | +// fragment, with backslash continuations joined: a command's flags are often | |
| 143 | +// on the line after the one that names it, and a test about the command should | |
| 144 | +// not depend on where it happens to wrap. | |
| 145 | +func commandContaining(t *testing.T, script, fragment string) string { | |
| 146 | + t.Helper() | |
| 147 | + | |
| 148 | + joined := strings.ReplaceAll(script, "\\\n", " ") | |
| 149 | + for _, line := range strings.Split(joined, "\n") { | |
| 150 | + if strings.Contains(line, fragment) { | |
| 151 | + return strings.TrimSpace(line) | |
| 152 | + } | |
| 153 | + } | |
| 154 | + t.Fatalf("no command in the script contains %q", fragment) | |
| 155 | + return "" | |
| 156 | +} | |
| 157 | + | |
| 158 | +// readTagScript returns the tagging script, whose failure modes are what the | |
| 159 | +// release builder is left to notice when they are not caught here. | |
| 160 | +func readTagScript(t *testing.T) string { | |
| 161 | + t.Helper() | |
| 162 | + | |
| 163 | + script, err := os.ReadFile("01-release.tag.sh") | |
| 164 | + if err != nil { | |
| 165 | + t.Fatalf("cannot read the tagging script: %v", err) | |
| 166 | + } | |
| 167 | + return string(script) | |
| 168 | +} | |
| 169 | + | |
| 170 | +func TestTheTagScriptStopsOnTheFirstFailure(t *testing.T) { | |
| 171 | + // Without this, `git tag` refusing a tag that already existed was skipped | |
| 172 | + // in silence and the `git push` after it pushed the OLD tag, cutting a | |
| 173 | + // release from a commit nobody meant. | |
| 174 | + if !strings.Contains(readTagScript(t), "set -euo pipefail") { | |
| 175 | + t.Error("the tagging script does not stop on a failing step") | |
| 176 | + } | |
| 177 | +} | |
| 178 | + | |
| 179 | +func TestTheTagScriptRefusesATagThatAlreadyExists(t *testing.T) { | |
| 180 | + script := readTagScript(t) | |
| 181 | + | |
| 182 | + for _, want := range []string{ | |
| 183 | + "git rev-parse -q --verify", // taken locally | |
| 184 | + "git ls-remote --tags origin", // taken on the remote, after a local delete | |
| 185 | + } { | |
| 186 | + if !strings.Contains(script, want) { | |
| 187 | + t.Errorf("the tagging script never checks %q", want) | |
| 188 | + } | |
| 189 | + } | |
| 190 | +} | |
| 191 | + | |
| 192 | +func TestTheTagScriptSurvivesHavingNothingToCommit(t *testing.T) { | |
| 193 | + // Under `set -e` a plain `git commit` with a clean tree ends the release, | |
| 194 | + // which is wrong: the work being already committed is the normal case on a | |
| 195 | + // second run. | |
| 196 | + script := readTagScript(t) | |
| 197 | + | |
| 198 | + if !strings.Contains(script, "git diff --cached --quiet") { | |
| 199 | + t.Error("the tagging script commits without checking there is anything to commit") | |
| 200 | + } | |
| 201 | +} | |
| 202 | + | |
| 203 | +func TestTheTagScriptTagsOnlyAfterThePushSucceeded(t *testing.T) { | |
| 204 | + // A tag left behind pointing at a commit the remote has never seen is the | |
| 205 | + // state that needs a force push to escape. | |
| 206 | + script := readTagScript(t) | |
| 207 | + | |
| 208 | + push := strings.Index(script, `git push origin "$(git rev-parse`) | |
| 209 | + tag := strings.Index(script, `git tag -a "${TAG}"`) | |
| 210 | + if push < 0 || tag < 0 { | |
| 211 | + t.Fatal("the tagging script no longer pushes and tags") | |
| 212 | + } | |
| 213 | + if tag < push { | |
| 214 | + t.Error("the script tags before pushing, so a rejected push leaves a stray tag") | |
| 215 | + } | |
| 216 | +} | |
| 217 | + | |
| 218 | +// skipInsideARelease stops a test that runs the tagging script from running | |
| 219 | +// while the tagging script is running it. | |
| 220 | +// | |
| 221 | +// The script sets this before `make check`, and `make check` runs this suite. | |
| 222 | +// Without the guard the two call each other forever — which is not a test-only | |
| 223 | +// hazard: a real release would recurse in exactly the same way. The Release | |
| 224 | +// workflow sets it too, for the same reason. | |
| 225 | +func skipInsideARelease(t *testing.T) { | |
| 226 | + t.Helper() | |
| 227 | + if os.Getenv("TURBO_PYTHON_RELEASING") != "" { | |
| 228 | + t.Skip("running inside a release; not starting another one") | |
| 229 | + } | |
| 230 | +} | |
| 231 | + | |
| 232 | +func TestTheTagScriptRunsTheSuiteBeforePublishing(t *testing.T) { | |
| 233 | + // A version people will download, and the proxy will cache, is the wrong | |
| 234 | + // place to find out the suite was red. | |
| 235 | + if !strings.Contains(readTagScript(t), "make --no-print-directory check") { | |
| 236 | + t.Error("the tagging script publishes without running make check") | |
| 237 | + } | |
| 238 | +} | |
| 239 | + | |
| 240 | +func TestTheTagScriptRefusesAReplaceDirective(t *testing.T) { | |
| 241 | + // The proxy serves go.mod as written, so `go install …@TAG` on a module | |
| 242 | + // carrying a replace looks for turbo-core in a directory that does not | |
| 243 | + // exist on the installer's machine. | |
| 244 | + if !strings.Contains(readTagScript(t), "replace") { | |
| 245 | + t.Error("the tagging script does not check go.mod for a replace directive") | |
| 246 | + } | |
| 247 | +} | |
| 248 | + | |
| 249 | +func TestThisModuleHasNoReplaceDirective(t *testing.T) { | |
| 250 | + // The check above only helps if it is true today as well. | |
| 251 | + data, err := os.ReadFile("go.mod") | |
| 252 | + if err != nil { | |
| 253 | + t.Fatalf("reading go.mod: %v", err) | |
| 254 | + } | |
| 255 | + for _, line := range strings.Split(string(data), "\n") { | |
| 256 | + if strings.HasPrefix(strings.TrimSpace(line), "replace ") { | |
| 257 | + t.Errorf("go.mod carries %q; a published module must not", line) | |
| 258 | + } | |
| 259 | + } | |
| 260 | +} | |
| 261 | + | |
| 262 | +func TestTheReleaseToolingNeedsNoPersonalToken(t *testing.T) { | |
| 263 | + // The Release workflow publishes with the job's own GITHUB_TOKEN, which is | |
| 264 | + // the only credential Rickub's release API accepts. A script still reading | |
| 265 | + // a token file is a credential that cannot work and has to be kept | |
| 266 | + // somewhere all the same — and a 02 or 04 left in the tree is a second | |
| 267 | + // pipeline somebody will run by mistake. | |
| 268 | + for _, script := range []string{"01-release.tag.sh", "02-build-releases.sh"} { | |
| 269 | + data, err := os.ReadFile(script) | |
| 270 | + if err != nil { | |
| 271 | + t.Fatalf("reading %s: %v", script, err) | |
| 272 | + } | |
| 273 | + for _, secret := range []string{"token.env", "${TOKEN}"} { | |
| 274 | + if strings.Contains(string(data), secret) { | |
| 275 | + t.Errorf("%s still reads %s", script, secret) | |
| 276 | + } | |
| 277 | + } | |
| 278 | + } | |
| 279 | + for _, gone := range []string{"02-release.publish.sh", "04-release.upload-binaries.sh"} { | |
| 280 | + if _, err := os.Stat(gone); err == nil { | |
| 281 | + t.Errorf("%s is still there; the workflow publishes and attaches the binaries now", gone) | |
| 282 | + } | |
| 283 | + } | |
| 284 | +} | |
| 285 | + | |
| 286 | +func TestTheTagScriptTagsAndPushesForReal(t *testing.T) { | |
| 287 | + // The whole flow, in a throwaway clone with its own bare remote, so no tag | |
| 288 | + // is ever created in the real repository. Reading the script is not the | |
| 289 | + // same as running it: every guard above was added because one of them was | |
| 290 | + // wrong once. | |
| 291 | + skipInsideARelease(t) | |
| 292 | + if _, err := exec.LookPath("git"); err != nil { | |
| 293 | + t.Skip("git is not available") | |
| 294 | + } | |
| 295 | + | |
| 296 | + remote, clone := throwawayClone(t) | |
| 297 | + | |
| 298 | + out, err := runAllowingFailure(t, clone, "./01-release.tag.sh") | |
| 299 | + if err != nil { | |
| 300 | + t.Fatalf("the tagging script failed:\n%s", out) | |
| 301 | + } | |
| 302 | + if !strings.Contains(out, "published") { | |
| 303 | + t.Errorf("the script did not report publishing:\n%s", out) | |
| 304 | + } | |
| 305 | + | |
| 306 | + tags, _ := runAllowingFailure(t, remote, "git", "tag") | |
| 307 | + if !strings.Contains(tags, "v0.0.1-test") { | |
| 308 | + t.Errorf("the remote has tags %q, want v0.0.1-test", strings.TrimSpace(tags)) | |
| 309 | + } | |
| 310 | +} | |
| 311 | + | |
| 312 | +func TestTheTagScriptRefusesATagItAlreadyPublished(t *testing.T) { | |
| 313 | + // Moving a published version is not an option: the proxy caches what it | |
| 314 | + // fetched, and the release page already carries binaries with that number. | |
| 315 | + skipInsideARelease(t) | |
| 316 | + if _, err := exec.LookPath("git"); err != nil { | |
| 317 | + t.Skip("git is not available") | |
| 318 | + } | |
| 319 | + | |
| 320 | + _, clone := throwawayClone(t) | |
| 321 | + | |
| 322 | + if out, err := runAllowingFailure(t, clone, "./01-release.tag.sh"); err != nil { | |
| 323 | + t.Fatalf("the first release failed:\n%s", out) | |
| 324 | + } | |
| 325 | + | |
| 326 | + out, err := runAllowingFailure(t, clone, "./01-release.tag.sh") | |
| 327 | + | |
| 328 | + if err == nil { | |
| 329 | + t.Fatalf("the script published the same tag twice:\n%s", out) | |
| 330 | + } | |
| 331 | + if !strings.Contains(out, "already exists") { | |
| 332 | + t.Errorf("the refusal does not say the tag is taken:\n%s", out) | |
| 333 | + } | |
| 334 | +} | |
| 335 | + | |
| 336 | +// throwawayClone sets up a bare remote and a clone of it holding a copy of | |
| 337 | +// this module and a release.env naming a test version, and returns both paths. | |
| 338 | +func throwawayClone(t *testing.T) (remote, clone string) { | |
| 339 | + t.Helper() | |
| 340 | + | |
| 341 | + root := t.TempDir() | |
| 342 | + remote = filepath.Join(root, "remote.git") | |
| 343 | + clone = filepath.Join(root, "clone") | |
| 344 | + | |
| 345 | + runOrFail(t, root, "git", "init", "--bare", "--initial-branch=main", remote) | |
| 346 | + runOrFail(t, root, "git", "clone", remote, clone) | |
| 347 | + copyModuleInto(t, clone) | |
| 348 | + runOrFail(t, clone, "git", "config", "user.email", "test@example.test") | |
| 349 | + runOrFail(t, clone, "git", "config", "user.name", "Release Test") | |
| 350 | + writeTestFile(t, filepath.Join(clone, "release.env"), "TAG=v0.0.1-test\nABOUT=\"a throwaway release\"\n") | |
| 351 | + return remote, clone | |
| 352 | +} | |
| 353 | + | |
| 354 | +// copyModuleInto copies the module's source into a directory, so the script can | |
| 355 | +// be run against a real checkout without touching this one. | |
| 356 | +// | |
| 357 | +// .git is left out because the target has its own; *.env because a test writes | |
| 358 | +// its own release.env — copying this checkout's would release whatever version | |
| 359 | +// happens to be in it; go.work because it would point the copy at a turbo-core | |
| 360 | +// checkout that is not what a release builds against; and the build outputs | |
| 361 | +// (bin, release, kits) and the demo project because they are hundreds of | |
| 362 | +// megabytes the script never reads. | |
| 363 | +// | |
| 364 | +// The copying is done here rather than by shelling out to cp, which on a | |
| 365 | +// network-backed working copy has been seen to write the right number of bytes | |
| 366 | +// and the wrong ones: every file in the copy came out NUL-filled. | |
| 367 | +func copyModuleInto(t *testing.T, target string) { | |
| 368 | + t.Helper() | |
| 369 | + | |
| 370 | + entries, err := os.ReadDir(".") | |
| 371 | + if err != nil { | |
| 372 | + t.Fatalf("reading the module: %v", err) | |
| 373 | + } | |
| 374 | + for _, entry := range entries { | |
| 375 | + if leftOutOfTheCopy(entry.Name()) { | |
| 376 | + continue | |
| 377 | + } | |
| 378 | + copyTree(t, entry.Name(), filepath.Join(target, entry.Name())) | |
| 379 | + } | |
| 380 | +} | |
| 381 | + | |
| 382 | +// leftOutOfTheCopy reports whether a top-level entry stays out of a throwaway | |
| 383 | +// copy of the module. | |
| 384 | +func leftOutOfTheCopy(name string) bool { | |
| 385 | + switch name { | |
| 386 | + case ".git", "bin", "release", "kits", "demo", "demos", "go.work", "go.work.sum": | |
| 387 | + return true | |
| 388 | + } | |
| 389 | + return strings.HasSuffix(name, ".env") | |
| 390 | +} | |
| 391 | + | |
| 392 | +// copyTree copies a file or a directory to a new path. | |
| 393 | +// | |
| 394 | +// Anything that is neither a regular file nor a directory is skipped: the tool | |
| 395 | +// directories beside the source hold symlinks into caches that do not exist in | |
| 396 | +// a temporary copy, and the release scripts have no use for them. | |
| 397 | +func copyTree(t *testing.T, from, to string) { | |
| 398 | + t.Helper() | |
| 399 | + | |
| 400 | + err := filepath.WalkDir(from, func(path string, entry os.DirEntry, err error) error { | |
| 401 | + if err != nil { | |
| 402 | + return err | |
| 403 | + } | |
| 404 | + relative, err := filepath.Rel(from, path) | |
| 405 | + if err != nil { | |
| 406 | + return err | |
| 407 | + } | |
| 408 | + destination := filepath.Join(to, relative) | |
| 409 | + | |
| 410 | + if entry.IsDir() { | |
| 411 | + return os.MkdirAll(destination, 0o755) | |
| 412 | + } | |
| 413 | + if !entry.Type().IsRegular() { | |
| 414 | + return nil | |
| 415 | + } | |
| 416 | + info, err := entry.Info() | |
| 417 | + if err != nil { | |
| 418 | + return err | |
| 419 | + } | |
| 420 | + data, err := os.ReadFile(path) | |
| 421 | + if err != nil { | |
| 422 | + return err | |
| 423 | + } | |
| 424 | + if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil { | |
| 425 | + return err | |
| 426 | + } | |
| 427 | + // The mode carries the execute bit, without which the scripts these | |
| 428 | + // tests exist to run cannot be run. | |
| 429 | + return os.WriteFile(destination, data, info.Mode().Perm()) | |
| 430 | + }) | |
| 431 | + if err != nil { | |
| 432 | + t.Fatalf("copying %s: %v", from, err) | |
| 433 | + } | |
| 434 | +} | |
| 435 | + | |
| 436 | +// runOrFail executes a command in a directory, failing the test if it does not | |
| 437 | +// succeed. | |
| 438 | +func runOrFail(t *testing.T, dir string, name string, args ...string) { | |
| 439 | + t.Helper() | |
| 440 | + | |
| 441 | + if out, err := runAllowingFailure(t, dir, name, args...); err != nil { | |
| 442 | + t.Fatalf("%s %v: %v\n%s", name, args, err, out) | |
| 443 | + } | |
| 444 | +} | |
| 445 | + | |
| 446 | +// runAllowingFailure executes a command and returns its combined output along | |
| 447 | +// with whether it succeeded. | |
| 448 | +// | |
| 449 | +// GOWORK is switched off for the child: a go.work beside this checkout points | |
| 450 | +// at a turbo-core working tree, and a release is built against the published | |
| 451 | +// module, which is what a clean clone would see. | |
| 452 | +func runAllowingFailure(t *testing.T, dir string, name string, args ...string) (string, error) { | |
| 453 | + t.Helper() | |
| 454 | + | |
| 455 | + command := exec.Command(name, args...) | |
| 456 | + command.Dir = dir | |
| 457 | + command.Env = append(os.Environ(), "GOWORK=off") | |
| 458 | + out, err := command.CombinedOutput() | |
| 459 | + return string(out), err | |
| 460 | +} | |
| 461 | + | |
| 462 | +// writeTestFile creates a file, failing the test if it cannot. | |
| 463 | +func writeTestFile(t *testing.T, path, contents string) { | |
| 464 | + t.Helper() | |
| 465 | + | |
| 466 | + if err := os.WriteFile(path, []byte(contents), 0o644); err != nil { | |
| 467 | + t.Fatalf("writing %s: %v", path, err) | |
| 468 | + } | |
| 469 | +} | |
| 470 | + | |
| 471 | +func TestTheBuildScriptTakesTheTagFromTheCommandLine(t *testing.T) { | |
| 472 | + // release.env is git-ignored, so the workflow has none: it passes the tag | |
| 473 | + // it was started by. A script that only reads the file builds nothing in | |
| 474 | + // CI, or builds whatever version the file last named. | |
| 475 | + script := readReleaseScript(t) | |
| 476 | + | |
| 477 | + if !strings.Contains(script, `TAG="${1:-${TAG:-}}"`) { | |
| 478 | + t.Error("the build script does not take the tag from its first argument") | |
| 479 | + } | |
| 480 | + if !strings.Contains(script, `[ -f release.env ]`) { | |
| 481 | + t.Error("the build script requires release.env, which CI does not have") | |
| 482 | + } | |
| 483 | +} | |
| 484 | + | |
| 485 | +func TestTheBuildScriptRefusesATagThatIsNotAVersion(t *testing.T) { | |
| 486 | + // The proxy will not serve a tag it cannot read as a version, so a typo | |
| 487 | + // here builds perfectly and then fails at every `go install`. | |
| 488 | + // | |
| 489 | + // The refusal comes before anything is built or written, so the script | |
| 490 | + // alone is enough: it is run from an empty directory with no release.env. | |
| 491 | + dir := t.TempDir() | |
| 492 | + script, err := os.ReadFile("02-build-releases.sh") | |
| 493 | + if err != nil { | |
| 494 | + t.Fatalf("reading the build script: %v", err) | |
| 495 | + } | |
| 496 | + writeTestFile(t, filepath.Join(dir, "02-build-releases.sh"), string(script)) | |
| 497 | + | |
| 498 | + out, err := runAllowingFailure(t, dir, "bash", "./02-build-releases.sh", "v0.o.0") | |
| 499 | + | |
| 500 | + if err == nil { | |
| 501 | + t.Fatalf("the script accepted a tag that is not a version:\n%s", out) | |
| 502 | + } | |
| 503 | + if !strings.Contains(out, "v1.2.3") { | |
| 504 | + t.Errorf("the refusal does not say what a tag should look like:\n%s", out) | |
| 505 | + } | |
| 506 | +} | |
| 507 | + | |
| 508 | +func TestTheBuildScriptDoesNotHandOffToAnUploadScript(t *testing.T) { | |
| 509 | + // 04 attached the binaries to a release page a personal token had created. | |
| 510 | + // The workflow does both now; a script still pointing at 04 sends the | |
| 511 | + // reader to run something that is not there. | |
| 512 | + if strings.Contains(readReleaseScript(t), "04-release") { | |
| 513 | + t.Error("the build script still hands off to 04-release.upload-binaries.sh") | |
| 514 | + } | |
| 515 | +} | |
| 516 | + | |
| 517 | +// readWorkflow returns the release workflow's text. | |
| 518 | +func readWorkflow(t *testing.T) string { | |
| 519 | + t.Helper() | |
| 520 | + | |
| 521 | + data, err := os.ReadFile(filepath.Join(".github", "workflows", "release.yml")) | |
| 522 | + if err != nil { | |
| 523 | + t.Fatalf("reading the release workflow: %v", err) | |
| 524 | + } | |
| 525 | + return string(data) | |
| 526 | +} | |
| 527 | + | |
| 528 | +func TestTheWorkflowPublishesOnATagPush(t *testing.T) { | |
| 529 | + // The tag push is the trigger: ./01-release.tag.sh ends by pushing one, | |
| 530 | + // and nothing else starts a release. | |
| 531 | + workflow := readWorkflow(t) | |
| 532 | + | |
| 533 | + for _, want := range []string{"push:", "tags:", `- "v*"`} { | |
| 534 | + if !strings.Contains(workflow, want) { | |
| 535 | + t.Errorf("the workflow never declares %q", want) | |
| 536 | + } | |
| 537 | + } | |
| 538 | + // A workflow with the default read-only token cannot create a release, and | |
| 539 | + // fails at its last step after doing all the work. | |
| 540 | + if !strings.Contains(workflow, "contents: write") { | |
| 541 | + t.Error("the workflow does not ask for contents: write") | |
| 542 | + } | |
| 543 | +} | |
| 544 | + | |
| 545 | +func TestTheWorkflowBuildsWithTheSameScriptAPersonRuns(t *testing.T) { | |
| 546 | + // A CI job that builds its own way is a second pipeline nobody tests, and | |
| 547 | + // the local one is then only ever exercised by accident. | |
| 548 | + if !strings.Contains(readWorkflow(t), "./02-build-releases.sh") { | |
| 549 | + t.Error("the workflow does not build the release with ./02-build-releases.sh") | |
| 550 | + } | |
| 551 | +} | |
| 552 | + | |
| 553 | +func TestTheWorkflowAttachesWhatWasBuilt(t *testing.T) { | |
| 554 | + // Publishing a release page with no files attached is a silent half-job: | |
| 555 | + // the page exists and the downloads are not there. | |
| 556 | + workflow := readWorkflow(t) | |
| 557 | + | |
| 558 | + for _, want := range []string{"turbo-python-*", "SHA256SUMS", "fail_on_unmatched_files: true"} { | |
| 559 | + if !strings.Contains(workflow, want) { | |
| 560 | + t.Errorf("the workflow never mentions %q", want) | |
| 561 | + } | |
| 562 | + } | |
| 563 | +} | |
| 564 | + | |
| 565 | +func TestTheWorkflowLinksToTheDocumentationAtThatTag(t *testing.T) { | |
| 566 | + // A release page is not inside the repository tree, so a relative path | |
| 567 | + // from it 404s — and a link to the branch would rot as the branch moves. | |
| 568 | + workflow := readWorkflow(t) | |
| 569 | + | |
| 570 | + if !strings.Contains(workflow, "blob/${GITHUB_REF_NAME}") { | |
| 571 | + t.Error("the release notes do not link into the repository at the released tag") | |
| 572 | + } | |
| 573 | + if !strings.Contains(workflow, "/docs/en/README.md") { | |
| 574 | + t.Error("the release notes do not link to the documentation") | |
| 575 | + } | |
| 576 | +} | |
| 577 | + | |
| 578 | +func TestTheWorkflowNeedsNoPersonalToken(t *testing.T) { | |
| 579 | + // The release API behind Rickub's /gh shim accepts the job's own | |
| 580 | + // GITHUB_TOKEN and refuses a personal one, so a secret referenced here is | |
| 581 | + // a credential that cannot work and still has to be kept somewhere. | |
| 582 | + if strings.Contains(readWorkflow(t), "secrets.") { | |
| 583 | + t.Error("the workflow reads a secret; the job's own token is the only credential the release API takes") | |
| 584 | + } | |
| 585 | +} | |
| 586 | + | |
| 587 | +func TestTheWorkflowDoesNotStartAReleaseInsideItself(t *testing.T) { | |
| 588 | + // The suite it runs includes tests that run ./01-release.tag.sh against a | |
| 589 | + // throwaway clone. Locally the script exports this before calling make; | |
| 590 | + // in CI nothing calls the script, so the job has to set it itself. | |
| 591 | + if !strings.Contains(readWorkflow(t), "TURBO_PYTHON_RELEASING") { | |
| 592 | + t.Error("the workflow runs the suite without TURBO_PYTHON_RELEASING set") | |
| 593 | + } | |
| 594 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,594 @@ | |||
| 1 | +package main | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "os" | ||
| 5 | + "os/exec" | ||
| 6 | + "path/filepath" | ||
| 7 | + "runtime" | ||
| 8 | + "strings" | ||
| 9 | + "testing" | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | +// readReleaseScript returns the release builder, so its rules can be asserted | ||
| 13 | +// without running it: running it cross-compiles five binaries, which is not a | ||
| 14 | +// unit test. (Running the tagging script, on the other hand, is done below, | ||
| 15 | +// against a throwaway clone.) | ||
| 16 | +func readReleaseScript(t *testing.T) string { | ||
| 17 | + t.Helper() | ||
| 18 | + | ||
| 19 | + script, err := os.ReadFile("02-build-releases.sh") | ||
| 20 | + if err != nil { | ||
| 21 | + t.Fatalf("cannot read the release script: %v", err) | ||
| 22 | + } | ||
| 23 | + return string(script) | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +func TestTheReleaseScriptStampsTheBinariesItShips(t *testing.T) { | ||
| 27 | + // Without -ldflags on the cross-compile, every downloaded binary reports | ||
| 28 | + // "devel" while the release page names a version. The host binary would | ||
| 29 | + // still be right, so nothing but this notices. | ||
| 30 | + script := readReleaseScript(t) | ||
| 31 | + | ||
| 32 | + build := commandContaining(t, script, "GOARCH=") | ||
| 33 | + if !strings.Contains(build, "-ldflags") { | ||
| 34 | + t.Errorf("the cross-compile does not stamp a version:\n%s", build) | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +func TestTheReleaseScriptTakesTheStampFromTheMakefile(t *testing.T) { | ||
| 39 | + // Repeating the -X paths in the script is how the host binary and the | ||
| 40 | + // downloads would come to disagree about which package holds the version. | ||
| 41 | + script := readReleaseScript(t) | ||
| 42 | + | ||
| 43 | + if !strings.Contains(script, "make --no-print-directory ldflags") { | ||
| 44 | + t.Error("the script does not read the linker flags from the Makefile") | ||
| 45 | + } | ||
| 46 | + if strings.Contains(script, "version.stamp=") { | ||
| 47 | + t.Error("the script spells out the -X path, which the Makefile already owns") | ||
| 48 | + } | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +func TestTheReleaseScriptStampsTheTagItIsReleasing(t *testing.T) { | ||
| 52 | + // The release *is* ${TAG}, so that is what the binaries say. Letting the | ||
| 53 | + // Makefile's default stand would stamp `git describe`, which answers a | ||
| 54 | + // different question — where HEAD is — and disagrees the moment anyone | ||
| 55 | + // commits after tagging. | ||
| 56 | + script := readReleaseScript(t) | ||
| 57 | + | ||
| 58 | + flags := commandContaining(t, script, "ldflags") | ||
| 59 | + if !strings.Contains(flags, `VERSION="${TAG}"`) { | ||
| 60 | + t.Errorf("the stamp does not come from TAG:\n%s", flags) | ||
| 61 | + } | ||
| 62 | + if build := commandContaining(t, script, "make build"); !strings.Contains(build, `VERSION="${TAG}"`) { | ||
| 63 | + t.Errorf("the host build carries a different version from the assets:\n%s", build) | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +func TestTheReleaseScriptDoesNotParseTheVersionOutOfProse(t *testing.T) { | ||
| 68 | + // `-version` is written for a person and has changed shape once already; | ||
| 69 | + // awk '{print $NF}' on it read a timestamp and failed a release. | ||
| 70 | + script := readReleaseScript(t) | ||
| 71 | + | ||
| 72 | + if strings.Contains(script, "$NF") { | ||
| 73 | + t.Error("the script reads a field out of the -version line, which is prose") | ||
| 74 | + } | ||
| 75 | +} | ||
| 76 | + | ||
| 77 | +func TestTheMakefileHandsOutTheFlagsThatStampABuild(t *testing.T) { | ||
| 78 | + // The contract the release script depends on: `make ldflags` prints flags | ||
| 79 | + // that actually put *the Makefile's own version* into a binary. | ||
| 80 | + // | ||
| 81 | + // It is checked against `make version` rather than against "not devel", | ||
| 82 | + // because a checkout with no tags — a fresh clone, or a repository that has | ||
| 83 | + // never had a release — correctly reports devel, and a test that called | ||
| 84 | + // that a failure would be testing the tags rather than the flags. | ||
| 85 | + version, err := exec.Command("make", "--no-print-directory", "version").Output() | ||
| 86 | + if err != nil { | ||
| 87 | + t.Fatalf("make version: %v", err) | ||
| 88 | + } | ||
| 89 | + // internal/version drops the leading v of a tag, so the comparison has to | ||
| 90 | + // as well: `make version` says v0.2.1 and the binary says 0.2.1. | ||
| 91 | + number := strings.TrimPrefix(strings.Fields(strings.TrimSpace(string(version)))[0], "v") | ||
| 92 | + | ||
| 93 | + flags, err := exec.Command("make", "--no-print-directory", "ldflags").Output() | ||
| 94 | + if err != nil { | ||
| 95 | + t.Fatalf("make ldflags: %v", err) | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + binary := filepath.Join(t.TempDir(), "turbo-python") | ||
| 99 | + build := exec.Command("go", "build", "-trimpath", "-ldflags", strings.TrimSpace(string(flags)), "-o", binary, ".") | ||
| 100 | + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS="+runtime.GOOS, "GOARCH="+runtime.GOARCH) | ||
| 101 | + if out, err := build.CombinedOutput(); err != nil { | ||
| 102 | + t.Fatalf("building with those flags failed: %v\n%s", err, out) | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + reported, err := exec.Command(binary, "-version").Output() | ||
| 106 | + if err != nil { | ||
| 107 | + t.Fatalf("the stamped binary does not run: %v", err) | ||
| 108 | + } | ||
| 109 | + if !strings.Contains(string(reported), number) { | ||
| 110 | + t.Errorf("-version printed %q, want it to carry the Makefile's version %q", reported, number) | ||
| 111 | + } | ||
| 112 | + if strings.Contains(string(reported), "unknown") { | ||
| 113 | + t.Errorf("-version printed %q, so nothing reached the linker at all", reported) | ||
| 114 | + } | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +func TestMakeLdflagsTakesTheVersionItIsGiven(t *testing.T) { | ||
| 118 | + // The release script overrides VERSION with the tag it is releasing, and | ||
| 119 | + // everything downstream rests on that override reaching the linker. | ||
| 120 | + flags, err := exec.Command("make", "--no-print-directory", "ldflags", "VERSION=v9.9.9").Output() | ||
| 121 | + if err != nil { | ||
| 122 | + t.Fatalf("make ldflags: %v", err) | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + binary := filepath.Join(t.TempDir(), "turbo-python") | ||
| 126 | + build := exec.Command("go", "build", "-trimpath", "-ldflags", strings.TrimSpace(string(flags)), "-o", binary, ".") | ||
| 127 | + build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS="+runtime.GOOS, "GOARCH="+runtime.GOARCH) | ||
| 128 | + if out, err := build.CombinedOutput(); err != nil { | ||
| 129 | + t.Fatalf("building with those flags failed: %v\n%s", err, out) | ||
| 130 | + } | ||
| 131 | + | ||
| 132 | + reported, err := exec.Command(binary, "-version").Output() | ||
| 133 | + if err != nil { | ||
| 134 | + t.Fatalf("the stamped binary does not run: %v", err) | ||
| 135 | + } | ||
| 136 | + if !strings.Contains(string(reported), "9.9.9") { | ||
| 137 | + t.Errorf("-version printed %q, so VERSION=v9.9.9 never reached the linker", reported) | ||
| 138 | + } | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +// commandContaining returns the first shell command of a script holding a | ||
| 142 | +// fragment, with backslash continuations joined: a command's flags are often | ||
| 143 | +// on the line after the one that names it, and a test about the command should | ||
| 144 | +// not depend on where it happens to wrap. | ||
| 145 | +func commandContaining(t *testing.T, script, fragment string) string { | ||
| 146 | + t.Helper() | ||
| 147 | + | ||
| 148 | + joined := strings.ReplaceAll(script, "\\\n", " ") | ||
| 149 | + for _, line := range strings.Split(joined, "\n") { | ||
| 150 | + if strings.Contains(line, fragment) { | ||
| 151 | + return strings.TrimSpace(line) | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | + t.Fatalf("no command in the script contains %q", fragment) | ||
| 155 | + return "" | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +// readTagScript returns the tagging script, whose failure modes are what the | ||
| 159 | +// release builder is left to notice when they are not caught here. | ||
| 160 | +func readTagScript(t *testing.T) string { | ||
| 161 | + t.Helper() | ||
| 162 | + | ||
| 163 | + script, err := os.ReadFile("01-release.tag.sh") | ||
| 164 | + if err != nil { | ||
| 165 | + t.Fatalf("cannot read the tagging script: %v", err) | ||
| 166 | + } | ||
| 167 | + return string(script) | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +func TestTheTagScriptStopsOnTheFirstFailure(t *testing.T) { | ||
| 171 | + // Without this, `git tag` refusing a tag that already existed was skipped | ||
| 172 | + // in silence and the `git push` after it pushed the OLD tag, cutting a | ||
| 173 | + // release from a commit nobody meant. | ||
| 174 | + if !strings.Contains(readTagScript(t), "set -euo pipefail") { | ||
| 175 | + t.Error("the tagging script does not stop on a failing step") | ||
| 176 | + } | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +func TestTheTagScriptRefusesATagThatAlreadyExists(t *testing.T) { | ||
| 180 | + script := readTagScript(t) | ||
| 181 | + | ||
| 182 | + for _, want := range []string{ | ||
| 183 | + "git rev-parse -q --verify", // taken locally | ||
| 184 | + "git ls-remote --tags origin", // taken on the remote, after a local delete | ||
| 185 | + } { | ||
| 186 | + if !strings.Contains(script, want) { | ||
| 187 | + t.Errorf("the tagging script never checks %q", want) | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +func TestTheTagScriptSurvivesHavingNothingToCommit(t *testing.T) { | ||
| 193 | + // Under `set -e` a plain `git commit` with a clean tree ends the release, | ||
| 194 | + // which is wrong: the work being already committed is the normal case on a | ||
| 195 | + // second run. | ||
| 196 | + script := readTagScript(t) | ||
| 197 | + | ||
| 198 | + if !strings.Contains(script, "git diff --cached --quiet") { | ||
| 199 | + t.Error("the tagging script commits without checking there is anything to commit") | ||
| 200 | + } | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +func TestTheTagScriptTagsOnlyAfterThePushSucceeded(t *testing.T) { | ||
| 204 | + // A tag left behind pointing at a commit the remote has never seen is the | ||
| 205 | + // state that needs a force push to escape. | ||
| 206 | + script := readTagScript(t) | ||
| 207 | + | ||
| 208 | + push := strings.Index(script, `git push origin "$(git rev-parse`) | ||
| 209 | + tag := strings.Index(script, `git tag -a "${TAG}"`) | ||
| 210 | + if push < 0 || tag < 0 { | ||
| 211 | + t.Fatal("the tagging script no longer pushes and tags") | ||
| 212 | + } | ||
| 213 | + if tag < push { | ||
| 214 | + t.Error("the script tags before pushing, so a rejected push leaves a stray tag") | ||
| 215 | + } | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +// skipInsideARelease stops a test that runs the tagging script from running | ||
| 219 | +// while the tagging script is running it. | ||
| 220 | +// | ||
| 221 | +// The script sets this before `make check`, and `make check` runs this suite. | ||
| 222 | +// Without the guard the two call each other forever — which is not a test-only | ||
| 223 | +// hazard: a real release would recurse in exactly the same way. The Release | ||
| 224 | +// workflow sets it too, for the same reason. | ||
| 225 | +func skipInsideARelease(t *testing.T) { | ||
| 226 | + t.Helper() | ||
| 227 | + if os.Getenv("TURBO_PYTHON_RELEASING") != "" { | ||
| 228 | + t.Skip("running inside a release; not starting another one") | ||
| 229 | + } | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +func TestTheTagScriptRunsTheSuiteBeforePublishing(t *testing.T) { | ||
| 233 | + // A version people will download, and the proxy will cache, is the wrong | ||
| 234 | + // place to find out the suite was red. | ||
| 235 | + if !strings.Contains(readTagScript(t), "make --no-print-directory check") { | ||
| 236 | + t.Error("the tagging script publishes without running make check") | ||
| 237 | + } | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +func TestTheTagScriptRefusesAReplaceDirective(t *testing.T) { | ||
| 241 | + // The proxy serves go.mod as written, so `go install …@TAG` on a module | ||
| 242 | + // carrying a replace looks for turbo-core in a directory that does not | ||
| 243 | + // exist on the installer's machine. | ||
| 244 | + if !strings.Contains(readTagScript(t), "replace") { | ||
| 245 | + t.Error("the tagging script does not check go.mod for a replace directive") | ||
| 246 | + } | ||
| 247 | +} | ||
| 248 | + | ||
| 249 | +func TestThisModuleHasNoReplaceDirective(t *testing.T) { | ||
| 250 | + // The check above only helps if it is true today as well. | ||
| 251 | + data, err := os.ReadFile("go.mod") | ||
| 252 | + if err != nil { | ||
| 253 | + t.Fatalf("reading go.mod: %v", err) | ||
| 254 | + } | ||
| 255 | + for _, line := range strings.Split(string(data), "\n") { | ||
| 256 | + if strings.HasPrefix(strings.TrimSpace(line), "replace ") { | ||
| 257 | + t.Errorf("go.mod carries %q; a published module must not", line) | ||
| 258 | + } | ||
| 259 | + } | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +func TestTheReleaseToolingNeedsNoPersonalToken(t *testing.T) { | ||
| 263 | + // The Release workflow publishes with the job's own GITHUB_TOKEN, which is | ||
| 264 | + // the only credential Rickub's release API accepts. A script still reading | ||
| 265 | + // a token file is a credential that cannot work and has to be kept | ||
| 266 | + // somewhere all the same — and a 02 or 04 left in the tree is a second | ||
| 267 | + // pipeline somebody will run by mistake. | ||
| 268 | + for _, script := range []string{"01-release.tag.sh", "02-build-releases.sh"} { | ||
| 269 | + data, err := os.ReadFile(script) | ||
| 270 | + if err != nil { | ||
| 271 | + t.Fatalf("reading %s: %v", script, err) | ||
| 272 | + } | ||
| 273 | + for _, secret := range []string{"token.env", "${TOKEN}"} { | ||
| 274 | + if strings.Contains(string(data), secret) { | ||
| 275 | + t.Errorf("%s still reads %s", script, secret) | ||
| 276 | + } | ||
| 277 | + } | ||
| 278 | + } | ||
| 279 | + for _, gone := range []string{"02-release.publish.sh", "04-release.upload-binaries.sh"} { | ||
| 280 | + if _, err := os.Stat(gone); err == nil { | ||
| 281 | + t.Errorf("%s is still there; the workflow publishes and attaches the binaries now", gone) | ||
| 282 | + } | ||
| 283 | + } | ||
| 284 | +} | ||
| 285 | + | ||
| 286 | +func TestTheTagScriptTagsAndPushesForReal(t *testing.T) { | ||
| 287 | + // The whole flow, in a throwaway clone with its own bare remote, so no tag | ||
| 288 | + // is ever created in the real repository. Reading the script is not the | ||
| 289 | + // same as running it: every guard above was added because one of them was | ||
| 290 | + // wrong once. | ||
| 291 | + skipInsideARelease(t) | ||
| 292 | + if _, err := exec.LookPath("git"); err != nil { | ||
| 293 | + t.Skip("git is not available") | ||
| 294 | + } | ||
| 295 | + | ||
| 296 | + remote, clone := throwawayClone(t) | ||
| 297 | + | ||
| 298 | + out, err := runAllowingFailure(t, clone, "./01-release.tag.sh") | ||
| 299 | + if err != nil { | ||
| 300 | + t.Fatalf("the tagging script failed:\n%s", out) | ||
| 301 | + } | ||
| 302 | + if !strings.Contains(out, "published") { | ||
| 303 | + t.Errorf("the script did not report publishing:\n%s", out) | ||
| 304 | + } | ||
| 305 | + | ||
| 306 | + tags, _ := runAllowingFailure(t, remote, "git", "tag") | ||
| 307 | + if !strings.Contains(tags, "v0.0.1-test") { | ||
| 308 | + t.Errorf("the remote has tags %q, want v0.0.1-test", strings.TrimSpace(tags)) | ||
| 309 | + } | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +func TestTheTagScriptRefusesATagItAlreadyPublished(t *testing.T) { | ||
| 313 | + // Moving a published version is not an option: the proxy caches what it | ||
| 314 | + // fetched, and the release page already carries binaries with that number. | ||
| 315 | + skipInsideARelease(t) | ||
| 316 | + if _, err := exec.LookPath("git"); err != nil { | ||
| 317 | + t.Skip("git is not available") | ||
| 318 | + } | ||
| 319 | + | ||
| 320 | + _, clone := throwawayClone(t) | ||
| 321 | + | ||
| 322 | + if out, err := runAllowingFailure(t, clone, "./01-release.tag.sh"); err != nil { | ||
| 323 | + t.Fatalf("the first release failed:\n%s", out) | ||
| 324 | + } | ||
| 325 | + | ||
| 326 | + out, err := runAllowingFailure(t, clone, "./01-release.tag.sh") | ||
| 327 | + | ||
| 328 | + if err == nil { | ||
| 329 | + t.Fatalf("the script published the same tag twice:\n%s", out) | ||
| 330 | + } | ||
| 331 | + if !strings.Contains(out, "already exists") { | ||
| 332 | + t.Errorf("the refusal does not say the tag is taken:\n%s", out) | ||
| 333 | + } | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +// throwawayClone sets up a bare remote and a clone of it holding a copy of | ||
| 337 | +// this module and a release.env naming a test version, and returns both paths. | ||
| 338 | +func throwawayClone(t *testing.T) (remote, clone string) { | ||
| 339 | + t.Helper() | ||
| 340 | + | ||
| 341 | + root := t.TempDir() | ||
| 342 | + remote = filepath.Join(root, "remote.git") | ||
| 343 | + clone = filepath.Join(root, "clone") | ||
| 344 | + | ||
| 345 | + runOrFail(t, root, "git", "init", "--bare", "--initial-branch=main", remote) | ||
| 346 | + runOrFail(t, root, "git", "clone", remote, clone) | ||
| 347 | + copyModuleInto(t, clone) | ||
| 348 | + runOrFail(t, clone, "git", "config", "user.email", "test@example.test") | ||
| 349 | + runOrFail(t, clone, "git", "config", "user.name", "Release Test") | ||
| 350 | + writeTestFile(t, filepath.Join(clone, "release.env"), "TAG=v0.0.1-test\nABOUT=\"a throwaway release\"\n") | ||
| 351 | + return remote, clone | ||
| 352 | +} | ||
| 353 | + | ||
| 354 | +// copyModuleInto copies the module's source into a directory, so the script can | ||
| 355 | +// be run against a real checkout without touching this one. | ||
| 356 | +// | ||
| 357 | +// .git is left out because the target has its own; *.env because a test writes | ||
| 358 | +// its own release.env — copying this checkout's would release whatever version | ||
| 359 | +// happens to be in it; go.work because it would point the copy at a turbo-core | ||
| 360 | +// checkout that is not what a release builds against; and the build outputs | ||
| 361 | +// (bin, release, kits) and the demo project because they are hundreds of | ||
| 362 | +// megabytes the script never reads. | ||
| 363 | +// | ||
| 364 | +// The copying is done here rather than by shelling out to cp, which on a | ||
| 365 | +// network-backed working copy has been seen to write the right number of bytes | ||
| 366 | +// and the wrong ones: every file in the copy came out NUL-filled. | ||
| 367 | +func copyModuleInto(t *testing.T, target string) { | ||
| 368 | + t.Helper() | ||
| 369 | + | ||
| 370 | + entries, err := os.ReadDir(".") | ||
| 371 | + if err != nil { | ||
| 372 | + t.Fatalf("reading the module: %v", err) | ||
| 373 | + } | ||
| 374 | + for _, entry := range entries { | ||
| 375 | + if leftOutOfTheCopy(entry.Name()) { | ||
| 376 | + continue | ||
| 377 | + } | ||
| 378 | + copyTree(t, entry.Name(), filepath.Join(target, entry.Name())) | ||
| 379 | + } | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +// leftOutOfTheCopy reports whether a top-level entry stays out of a throwaway | ||
| 383 | +// copy of the module. | ||
| 384 | +func leftOutOfTheCopy(name string) bool { | ||
| 385 | + switch name { | ||
| 386 | + case ".git", "bin", "release", "kits", "demo", "demos", "go.work", "go.work.sum": | ||
| 387 | + return true | ||
| 388 | + } | ||
| 389 | + return strings.HasSuffix(name, ".env") | ||
| 390 | +} | ||
| 391 | + | ||
| 392 | +// copyTree copies a file or a directory to a new path. | ||
| 393 | +// | ||
| 394 | +// Anything that is neither a regular file nor a directory is skipped: the tool | ||
| 395 | +// directories beside the source hold symlinks into caches that do not exist in | ||
| 396 | +// a temporary copy, and the release scripts have no use for them. | ||
| 397 | +func copyTree(t *testing.T, from, to string) { | ||
| 398 | + t.Helper() | ||
| 399 | + | ||
| 400 | + err := filepath.WalkDir(from, func(path string, entry os.DirEntry, err error) error { | ||
| 401 | + if err != nil { | ||
| 402 | + return err | ||
| 403 | + } | ||
| 404 | + relative, err := filepath.Rel(from, path) | ||
| 405 | + if err != nil { | ||
| 406 | + return err | ||
| 407 | + } | ||
| 408 | + destination := filepath.Join(to, relative) | ||
| 409 | + | ||
| 410 | + if entry.IsDir() { | ||
| 411 | + return os.MkdirAll(destination, 0o755) | ||
| 412 | + } | ||
| 413 | + if !entry.Type().IsRegular() { | ||
| 414 | + return nil | ||
| 415 | + } | ||
| 416 | + info, err := entry.Info() | ||
| 417 | + if err != nil { | ||
| 418 | + return err | ||
| 419 | + } | ||
| 420 | + data, err := os.ReadFile(path) | ||
| 421 | + if err != nil { | ||
| 422 | + return err | ||
| 423 | + } | ||
| 424 | + if err := os.MkdirAll(filepath.Dir(destination), 0o755); err != nil { | ||
| 425 | + return err | ||
| 426 | + } | ||
| 427 | + // The mode carries the execute bit, without which the scripts these | ||
| 428 | + // tests exist to run cannot be run. | ||
| 429 | + return os.WriteFile(destination, data, info.Mode().Perm()) | ||
| 430 | + }) | ||
| 431 | + if err != nil { | ||
| 432 | + t.Fatalf("copying %s: %v", from, err) | ||
| 433 | + } | ||
| 434 | +} | ||
| 435 | + | ||
| 436 | +// runOrFail executes a command in a directory, failing the test if it does not | ||
| 437 | +// succeed. | ||
| 438 | +func runOrFail(t *testing.T, dir string, name string, args ...string) { | ||
| 439 | + t.Helper() | ||
| 440 | + | ||
| 441 | + if out, err := runAllowingFailure(t, dir, name, args...); err != nil { | ||
| 442 | + t.Fatalf("%s %v: %v\n%s", name, args, err, out) | ||
| 443 | + } | ||
| 444 | +} | ||
| 445 | + | ||
| 446 | +// runAllowingFailure executes a command and returns its combined output along | ||
| 447 | +// with whether it succeeded. | ||
| 448 | +// | ||
| 449 | +// GOWORK is switched off for the child: a go.work beside this checkout points | ||
| 450 | +// at a turbo-core working tree, and a release is built against the published | ||
| 451 | +// module, which is what a clean clone would see. | ||
| 452 | +func runAllowingFailure(t *testing.T, dir string, name string, args ...string) (string, error) { | ||
| 453 | + t.Helper() | ||
| 454 | + | ||
| 455 | + command := exec.Command(name, args...) | ||
| 456 | + command.Dir = dir | ||
| 457 | + command.Env = append(os.Environ(), "GOWORK=off") | ||
| 458 | + out, err := command.CombinedOutput() | ||
| 459 | + return string(out), err | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +// writeTestFile creates a file, failing the test if it cannot. | ||
| 463 | +func writeTestFile(t *testing.T, path, contents string) { | ||
| 464 | + t.Helper() | ||
| 465 | + | ||
| 466 | + if err := os.WriteFile(path, []byte(contents), 0o644); err != nil { | ||
| 467 | + t.Fatalf("writing %s: %v", path, err) | ||
| 468 | + } | ||
| 469 | +} | ||
| 470 | + | ||
| 471 | +func TestTheBuildScriptTakesTheTagFromTheCommandLine(t *testing.T) { | ||
| 472 | + // release.env is git-ignored, so the workflow has none: it passes the tag | ||
| 473 | + // it was started by. A script that only reads the file builds nothing in | ||
| 474 | + // CI, or builds whatever version the file last named. | ||
| 475 | + script := readReleaseScript(t) | ||
| 476 | + | ||
| 477 | + if !strings.Contains(script, `TAG="${1:-${TAG:-}}"`) { | ||
| 478 | + t.Error("the build script does not take the tag from its first argument") | ||
| 479 | + } | ||
| 480 | + if !strings.Contains(script, `[ -f release.env ]`) { | ||
| 481 | + t.Error("the build script requires release.env, which CI does not have") | ||
| 482 | + } | ||
| 483 | +} | ||
| 484 | + | ||
| 485 | +func TestTheBuildScriptRefusesATagThatIsNotAVersion(t *testing.T) { | ||
| 486 | + // The proxy will not serve a tag it cannot read as a version, so a typo | ||
| 487 | + // here builds perfectly and then fails at every `go install`. | ||
| 488 | + // | ||
| 489 | + // The refusal comes before anything is built or written, so the script | ||
| 490 | + // alone is enough: it is run from an empty directory with no release.env. | ||
| 491 | + dir := t.TempDir() | ||
| 492 | + script, err := os.ReadFile("02-build-releases.sh") | ||
| 493 | + if err != nil { | ||
| 494 | + t.Fatalf("reading the build script: %v", err) | ||
| 495 | + } | ||
| 496 | + writeTestFile(t, filepath.Join(dir, "02-build-releases.sh"), string(script)) | ||
| 497 | + | ||
| 498 | + out, err := runAllowingFailure(t, dir, "bash", "./02-build-releases.sh", "v0.o.0") | ||
| 499 | + | ||
| 500 | + if err == nil { | ||
| 501 | + t.Fatalf("the script accepted a tag that is not a version:\n%s", out) | ||
| 502 | + } | ||
| 503 | + if !strings.Contains(out, "v1.2.3") { | ||
| 504 | + t.Errorf("the refusal does not say what a tag should look like:\n%s", out) | ||
| 505 | + } | ||
| 506 | +} | ||
| 507 | + | ||
| 508 | +func TestTheBuildScriptDoesNotHandOffToAnUploadScript(t *testing.T) { | ||
| 509 | + // 04 attached the binaries to a release page a personal token had created. | ||
| 510 | + // The workflow does both now; a script still pointing at 04 sends the | ||
| 511 | + // reader to run something that is not there. | ||
| 512 | + if strings.Contains(readReleaseScript(t), "04-release") { | ||
| 513 | + t.Error("the build script still hands off to 04-release.upload-binaries.sh") | ||
| 514 | + } | ||
| 515 | +} | ||
| 516 | + | ||
| 517 | +// readWorkflow returns the release workflow's text. | ||
| 518 | +func readWorkflow(t *testing.T) string { | ||
| 519 | + t.Helper() | ||
| 520 | + | ||
| 521 | + data, err := os.ReadFile(filepath.Join(".github", "workflows", "release.yml")) | ||
| 522 | + if err != nil { | ||
| 523 | + t.Fatalf("reading the release workflow: %v", err) | ||
| 524 | + } | ||
| 525 | + return string(data) | ||
| 526 | +} | ||
| 527 | + | ||
| 528 | +func TestTheWorkflowPublishesOnATagPush(t *testing.T) { | ||
| 529 | + // The tag push is the trigger: ./01-release.tag.sh ends by pushing one, | ||
| 530 | + // and nothing else starts a release. | ||
| 531 | + workflow := readWorkflow(t) | ||
| 532 | + | ||
| 533 | + for _, want := range []string{"push:", "tags:", `- "v*"`} { | ||
| 534 | + if !strings.Contains(workflow, want) { | ||
| 535 | + t.Errorf("the workflow never declares %q", want) | ||
| 536 | + } | ||
| 537 | + } | ||
| 538 | + // A workflow with the default read-only token cannot create a release, and | ||
| 539 | + // fails at its last step after doing all the work. | ||
| 540 | + if !strings.Contains(workflow, "contents: write") { | ||
| 541 | + t.Error("the workflow does not ask for contents: write") | ||
| 542 | + } | ||
| 543 | +} | ||
| 544 | + | ||
| 545 | +func TestTheWorkflowBuildsWithTheSameScriptAPersonRuns(t *testing.T) { | ||
| 546 | + // A CI job that builds its own way is a second pipeline nobody tests, and | ||
| 547 | + // the local one is then only ever exercised by accident. | ||
| 548 | + if !strings.Contains(readWorkflow(t), "./02-build-releases.sh") { | ||
| 549 | + t.Error("the workflow does not build the release with ./02-build-releases.sh") | ||
| 550 | + } | ||
| 551 | +} | ||
| 552 | + | ||
| 553 | +func TestTheWorkflowAttachesWhatWasBuilt(t *testing.T) { | ||
| 554 | + // Publishing a release page with no files attached is a silent half-job: | ||
| 555 | + // the page exists and the downloads are not there. | ||
| 556 | + workflow := readWorkflow(t) | ||
| 557 | + | ||
| 558 | + for _, want := range []string{"turbo-python-*", "SHA256SUMS", "fail_on_unmatched_files: true"} { | ||
| 559 | + if !strings.Contains(workflow, want) { | ||
| 560 | + t.Errorf("the workflow never mentions %q", want) | ||
| 561 | + } | ||
| 562 | + } | ||
| 563 | +} | ||
| 564 | + | ||
| 565 | +func TestTheWorkflowLinksToTheDocumentationAtThatTag(t *testing.T) { | ||
| 566 | + // A release page is not inside the repository tree, so a relative path | ||
| 567 | + // from it 404s — and a link to the branch would rot as the branch moves. | ||
| 568 | + workflow := readWorkflow(t) | ||
| 569 | + | ||
| 570 | + if !strings.Contains(workflow, "blob/${GITHUB_REF_NAME}") { | ||
| 571 | + t.Error("the release notes do not link into the repository at the released tag") | ||
| 572 | + } | ||
| 573 | + if !strings.Contains(workflow, "/docs/en/README.md") { | ||
| 574 | + t.Error("the release notes do not link to the documentation") | ||
| 575 | + } | ||
| 576 | +} | ||
| 577 | + | ||
| 578 | +func TestTheWorkflowNeedsNoPersonalToken(t *testing.T) { | ||
| 579 | + // The release API behind Rickub's /gh shim accepts the job's own | ||
| 580 | + // GITHUB_TOKEN and refuses a personal one, so a secret referenced here is | ||
| 581 | + // a credential that cannot work and still has to be kept somewhere. | ||
| 582 | + if strings.Contains(readWorkflow(t), "secrets.") { | ||
| 583 | + t.Error("the workflow reads a secret; the job's own token is the only credential the release API takes") | ||
| 584 | + } | ||
| 585 | +} | ||
| 586 | + | ||
| 587 | +func TestTheWorkflowDoesNotStartAReleaseInsideItself(t *testing.T) { | ||
| 588 | + // The suite it runs includes tests that run ./01-release.tag.sh against a | ||
| 589 | + // throwaway clone. Locally the script exports this before calling make; | ||
| 590 | + // in CI nothing calls the script, so the job has to set it itself. | ||
| 591 | + if !strings.Contains(readWorkflow(t), "TURBO_PYTHON_RELEASING") { | ||
| 592 | + t.Error("the workflow runs the suite without TURBO_PYTHON_RELEASING set") | ||
| 593 | + } | ||
| 594 | +} | ||
added
scripts/check-version.sh +72 -0 | new file mode 100755 | ||
| @@ -0,0 +1,72 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# | |
| 3 | +# Check that a freshly built binary reports the version the build meant to put | |
| 4 | +# into it. | |
| 5 | +# | |
| 6 | +# scripts/check-version.sh bin/turbo-python v0.2.0 88a4c38 | |
| 7 | +# scripts/check-version.sh bin/turbo-python # unstamped build | |
| 8 | +# | |
| 9 | +# Linker flags are a string: a typo in one produces a binary that builds, links | |
| 10 | +# and runs, and quietly reports the wrong version — or "unknown". Nothing but | |
| 11 | +# running the binary catches that, so the build runs it. | |
| 12 | +# | |
| 13 | +# With a version to expect, the reported number must **equal** it. A substring | |
| 14 | +# test is not enough: "0.2.0" is a substring of "10.2.0" and of a commit hash | |
| 15 | +# that happens to contain it, and the case this exists to catch is a stamp that | |
| 16 | +# is nearly right. | |
| 17 | +# | |
| 18 | +# With no version to expect — a build outside a git checkout, where there is | |
| 19 | +# nothing to describe — the only claim left is that some source named it, so | |
| 20 | +# "unknown" is the failure. | |
| 21 | + | |
| 22 | +set -euo pipefail | |
| 23 | + | |
| 24 | +if [ $# -lt 1 ]; then | |
| 25 | + echo "usage: $0 <binary> [expected-version] [expected-commit]" >&2 | |
| 26 | + exit 2 | |
| 27 | +fi | |
| 28 | + | |
| 29 | +readonly BINARY="$1" | |
| 30 | +readonly EXPECTED_VERSION="${2:-}" | |
| 31 | +readonly EXPECTED_COMMIT="${3:-}" | |
| 32 | + | |
| 33 | +if [ ! -x "${BINARY}" ]; then | |
| 34 | + echo "check-version: ${BINARY} is not an executable file" >&2 | |
| 35 | + exit 1 | |
| 36 | +fi | |
| 37 | + | |
| 38 | +if ! reported="$("${BINARY}" -version 2>&1)"; then | |
| 39 | + echo "check-version: ${BINARY} does not run:" >&2 | |
| 40 | + echo "${reported}" >&2 | |
| 41 | + exit 1 | |
| 42 | +fi | |
| 43 | + | |
| 44 | +# The binary prints "<Name> <number>" or "<Name> <number> (<commit>, built …)", | |
| 45 | +# so the number is the last field before the parenthesis, if there is one. The | |
| 46 | +# name is two words in every editor built on turbo-core and one word in some | |
| 47 | +# future one, which is why it is read from the right rather than the left. | |
| 48 | +head="${reported%% (*}" | |
| 49 | +number="${head##* }" | |
| 50 | + | |
| 51 | +if [ -n "${EXPECTED_VERSION}" ]; then | |
| 52 | + # The version package drops the leading v of a tag: the tag is v0.2.0 and | |
| 53 | + # what a person reads is 0.2.0. | |
| 54 | + want="${EXPECTED_VERSION#v}" | |
| 55 | + if [ "${number}" != "${want}" ]; then | |
| 56 | + echo "check-version: the build meant to stamp ${want} and the binary reports ${number}" >&2 | |
| 57 | + echo " ${reported}" >&2 | |
| 58 | + exit 1 | |
| 59 | + fi | |
| 60 | +elif [ "${number}" = "unknown" ]; then | |
| 61 | + echo "check-version: the binary cannot name its own version" >&2 | |
| 62 | + echo " ${reported}" >&2 | |
| 63 | + exit 1 | |
| 64 | +fi | |
| 65 | + | |
| 66 | +if [ -n "${EXPECTED_COMMIT}" ] && [ "${reported}" = "${reported#*"${EXPECTED_COMMIT}"}" ]; then | |
| 67 | + echo "check-version: the build meant to stamp commit ${EXPECTED_COMMIT} and the binary reports:" >&2 | |
| 68 | + echo " ${reported}" >&2 | |
| 69 | + exit 1 | |
| 70 | +fi | |
| 71 | + | |
| 72 | +echo "${reported}" | |
| new file mode 100755 | |||
| @@ -0,0 +1,72 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# | ||
| 3 | +# Check that a freshly built binary reports the version the build meant to put | ||
| 4 | +# into it. | ||
| 5 | +# | ||
| 6 | +# scripts/check-version.sh bin/turbo-python v0.2.0 88a4c38 | ||
| 7 | +# scripts/check-version.sh bin/turbo-python # unstamped build | ||
| 8 | +# | ||
| 9 | +# Linker flags are a string: a typo in one produces a binary that builds, links | ||
| 10 | +# and runs, and quietly reports the wrong version — or "unknown". Nothing but | ||
| 11 | +# running the binary catches that, so the build runs it. | ||
| 12 | +# | ||
| 13 | +# With a version to expect, the reported number must **equal** it. A substring | ||
| 14 | +# test is not enough: "0.2.0" is a substring of "10.2.0" and of a commit hash | ||
| 15 | +# that happens to contain it, and the case this exists to catch is a stamp that | ||
| 16 | +# is nearly right. | ||
| 17 | +# | ||
| 18 | +# With no version to expect — a build outside a git checkout, where there is | ||
| 19 | +# nothing to describe — the only claim left is that some source named it, so | ||
| 20 | +# "unknown" is the failure. | ||
| 21 | + | ||
| 22 | +set -euo pipefail | ||
| 23 | + | ||
| 24 | +if [ $# -lt 1 ]; then | ||
| 25 | + echo "usage: $0 <binary> [expected-version] [expected-commit]" >&2 | ||
| 26 | + exit 2 | ||
| 27 | +fi | ||
| 28 | + | ||
| 29 | +readonly BINARY="$1" | ||
| 30 | +readonly EXPECTED_VERSION="${2:-}" | ||
| 31 | +readonly EXPECTED_COMMIT="${3:-}" | ||
| 32 | + | ||
| 33 | +if [ ! -x "${BINARY}" ]; then | ||
| 34 | + echo "check-version: ${BINARY} is not an executable file" >&2 | ||
| 35 | + exit 1 | ||
| 36 | +fi | ||
| 37 | + | ||
| 38 | +if ! reported="$("${BINARY}" -version 2>&1)"; then | ||
| 39 | + echo "check-version: ${BINARY} does not run:" >&2 | ||
| 40 | + echo "${reported}" >&2 | ||
| 41 | + exit 1 | ||
| 42 | +fi | ||
| 43 | + | ||
| 44 | +# The binary prints "<Name> <number>" or "<Name> <number> (<commit>, built …)", | ||
| 45 | +# so the number is the last field before the parenthesis, if there is one. The | ||
| 46 | +# name is two words in every editor built on turbo-core and one word in some | ||
| 47 | +# future one, which is why it is read from the right rather than the left. | ||
| 48 | +head="${reported%% (*}" | ||
| 49 | +number="${head##* }" | ||
| 50 | + | ||
| 51 | +if [ -n "${EXPECTED_VERSION}" ]; then | ||
| 52 | + # The version package drops the leading v of a tag: the tag is v0.2.0 and | ||
| 53 | + # what a person reads is 0.2.0. | ||
| 54 | + want="${EXPECTED_VERSION#v}" | ||
| 55 | + if [ "${number}" != "${want}" ]; then | ||
| 56 | + echo "check-version: the build meant to stamp ${want} and the binary reports ${number}" >&2 | ||
| 57 | + echo " ${reported}" >&2 | ||
| 58 | + exit 1 | ||
| 59 | + fi | ||
| 60 | +elif [ "${number}" = "unknown" ]; then | ||
| 61 | + echo "check-version: the binary cannot name its own version" >&2 | ||
| 62 | + echo " ${reported}" >&2 | ||
| 63 | + exit 1 | ||
| 64 | +fi | ||
| 65 | + | ||
| 66 | +if [ -n "${EXPECTED_COMMIT}" ] && [ "${reported}" = "${reported#*"${EXPECTED_COMMIT}"}" ]; then | ||
| 67 | + echo "check-version: the build meant to stamp commit ${EXPECTED_COMMIT} and the binary reports:" >&2 | ||
| 68 | + echo " ${reported}" >&2 | ||
| 69 | + exit 1 | ||
| 70 | +fi | ||
| 71 | + | ||
| 72 | +echo "${reported}" | ||
added
scripts/install.sh +327 -0 | new file mode 100755 | ||
| @@ -0,0 +1,327 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# | |
| 3 | +# Build turbo-python and install it where your shell can find it. | |
| 4 | +# | |
| 5 | +# scripts/install.sh # install into GOBIN, or GOPATH/bin | |
| 6 | +# scripts/install.sh --prefix ~/bin # install somewhere else | |
| 7 | +# scripts/install.sh --with-analyzer # install the language server too | |
| 8 | +# scripts/install.sh --uninstall # remove it again | |
| 9 | +# | |
| 10 | +# The build goes to a temporary file first, so a failed build never replaces a | |
| 11 | +# working installation, and the install itself is a rename rather than a write | |
| 12 | +# over the binary that is already there. The version is stamped in by the | |
| 13 | +# linker, so `turbo-python -version` names the commit it was built from. | |
| 14 | + | |
| 15 | +set -euo pipefail | |
| 16 | + | |
| 17 | +readonly BINARY=turbo-python | |
| 18 | + | |
| 19 | +# --- output ----------------------------------------------------------------- | |
| 20 | + | |
| 21 | +if [ -t 1 ]; then | |
| 22 | + readonly BOLD=$'\033[1m' DIM=$'\033[2m' RED=$'\033[31m' GREEN=$'\033[32m' YELLOW=$'\033[33m' RESET=$'\033[0m' | |
| 23 | +else | |
| 24 | + readonly BOLD='' DIM='' RED='' GREEN='' YELLOW='' RESET='' | |
| 25 | +fi | |
| 26 | + | |
| 27 | +info() { printf '%s\n' "$*"; } | |
| 28 | +step() { printf '%s==>%s %s\n' "$BOLD" "$RESET" "$*"; } | |
| 29 | +ok() { printf '%s ✓%s %s\n' "$GREEN" "$RESET" "$*"; } | |
| 30 | +warn() { printf '%s !%s %s\n' "$YELLOW" "$RESET" "$*"; } | |
| 31 | +die() { | |
| 32 | + printf '%s ✗%s %s\n' "$RED" "$RESET" "$*" >&2 | |
| 33 | + exit 1 | |
| 34 | +} | |
| 35 | + | |
| 36 | +usage() { | |
| 37 | + cat <<EOF | |
| 38 | +${BOLD}$BINARY installer${RESET} | |
| 39 | + | |
| 40 | + scripts/install.sh [options] | |
| 41 | + | |
| 42 | +Options: | |
| 43 | + -p, --prefix DIR install into DIR (default: GOBIN, or GOPATH/bin) | |
| 44 | + --with-server also install pylsp, which completion needs | |
| 45 | + --uninstall remove an installed $BINARY and stop | |
| 46 | + -h, --help show this and stop | |
| 47 | +EOF | |
| 48 | +} | |
| 49 | + | |
| 50 | +# --- arguments -------------------------------------------------------------- | |
| 51 | + | |
| 52 | +prefix="" | |
| 53 | +with_server=false | |
| 54 | +uninstall=false | |
| 55 | + | |
| 56 | +while [ $# -gt 0 ]; do | |
| 57 | + case "$1" in | |
| 58 | + -p | --prefix) | |
| 59 | + [ $# -ge 2 ] || die "--prefix needs a directory" | |
| 60 | + prefix="$2" | |
| 61 | + shift 2 | |
| 62 | + ;; | |
| 63 | + --with-server) | |
| 64 | + with_server=true | |
| 65 | + shift | |
| 66 | + ;; | |
| 67 | + --uninstall) | |
| 68 | + uninstall=true | |
| 69 | + shift | |
| 70 | + ;; | |
| 71 | + -h | --help) | |
| 72 | + usage | |
| 73 | + exit 0 | |
| 74 | + ;; | |
| 75 | + *) die "unknown option: $1 (try --help)" ;; | |
| 76 | + esac | |
| 77 | +done | |
| 78 | + | |
| 79 | +# --- where things are ------------------------------------------------------- | |
| 80 | + | |
| 81 | +cd "$(dirname "${BASH_SOURCE[0]}")/.." | |
| 82 | +readonly REPO="$PWD" | |
| 83 | + | |
| 84 | +command -v go >/dev/null 2>&1 || die "go is not installed: https://go.dev/dl/" | |
| 85 | + | |
| 86 | +# default_prefix returns where "go install" would put a binary: GOBIN when it | |
| 87 | +# is set, GOPATH/bin otherwise. That is the directory a Go developer is most | |
| 88 | +# likely to already have on PATH. | |
| 89 | +default_prefix() { | |
| 90 | + local gobin | |
| 91 | + gobin="$(go env GOBIN)" | |
| 92 | + if [ -n "$gobin" ]; then | |
| 93 | + printf '%s\n' "$gobin" | |
| 94 | + else | |
| 95 | + printf '%s/bin\n' "$(go env GOPATH)" | |
| 96 | + fi | |
| 97 | +} | |
| 98 | + | |
| 99 | +[ -n "$prefix" ] || prefix="$(default_prefix)" | |
| 100 | +[ -n "$prefix" ] || die "cannot work out where to install; use --prefix DIR" | |
| 101 | +readonly TARGET="$prefix/$BINARY" | |
| 102 | + | |
| 103 | +# --- uninstall -------------------------------------------------------------- | |
| 104 | + | |
| 105 | +if $uninstall; then | |
| 106 | + step "Removing $TARGET" | |
| 107 | + if [ -e "$TARGET" ]; then | |
| 108 | + rm -f "$TARGET" | |
| 109 | + ok "removed" | |
| 110 | + else | |
| 111 | + warn "nothing installed at $TARGET" | |
| 112 | + fi | |
| 113 | + exit 0 | |
| 114 | +fi | |
| 115 | + | |
| 116 | +# --- toolchain -------------------------------------------------------------- | |
| 117 | + | |
| 118 | +step "Checking the Go toolchain" | |
| 119 | + | |
| 120 | +# The requirement lives in go.mod, so this check cannot drift from the build. | |
| 121 | +required="$(awk '/^go /{print $2; exit}' "$REPO/go.mod")" | |
| 122 | +installed="$(go env GOVERSION)" | |
| 123 | +installed="${installed#go}" | |
| 124 | + | |
| 125 | +if [ "$(printf '%s\n%s\n' "$required" "$installed" | sort -V | head -1)" != "$required" ]; then | |
| 126 | + die "Go $required or later is needed, but $installed is installed" | |
| 127 | +fi | |
| 128 | +ok "go $installed (go.mod asks for $required or later)" | |
| 129 | + | |
| 130 | +# --- build ------------------------------------------------------------------ | |
| 131 | + | |
| 132 | +step "Building $BINARY" | |
| 133 | + | |
| 134 | +readonly STAGING="$(mktemp -d)" | |
| 135 | +trap 'rm -rf "$STAGING"' EXIT | |
| 136 | + | |
| 137 | +# The version the binary reports is stamped in by the linker, so that an | |
| 138 | +# installed editor names the commit it was actually built from rather than a | |
| 139 | +# constant somebody forgot to bump. Outside a git checkout — installed from a | |
| 140 | +# tarball, say — there is nothing to describe and the binary works the version | |
| 141 | +# out from its own build information instead. | |
| 142 | +version_pkg="rickub.com/turbo-editors/turbo-core/version" | |
| 143 | +if describe="$(git -C "$REPO" describe --tags --dirty 2>/dev/null)"; then | |
| 144 | + commit="$(git -C "$REPO" rev-parse --short HEAD 2>/dev/null || true)" | |
| 145 | + built="$(date -u +%Y-%m-%dT%H:%M:%SZ)" | |
| 146 | + ldflags="-X '$version_pkg.stamp=$describe' -X '$version_pkg.commit=$commit' -X '$version_pkg.built=$built'" | |
| 147 | +else | |
| 148 | + ldflags="" | |
| 149 | +fi | |
| 150 | + | |
| 151 | +if ! go build -ldflags "$ldflags" -o "$STAGING/$BINARY" "$REPO" 2>"$STAGING/build.log"; then | |
| 152 | + cat "$STAGING/build.log" >&2 | |
| 153 | + info "" | |
| 154 | + warn "A failure in the repository root is often a stray .go file that has" | |
| 155 | + warn "landed in package main. 'go vet .' names it." | |
| 156 | + die "build failed; nothing was installed" | |
| 157 | +fi | |
| 158 | + | |
| 159 | +# Running the staged binary is the only proof that the flags above reached the | |
| 160 | +# linker rather than merely looking right. It happens before the install, so a | |
| 161 | +# binary that cannot name its own version never replaces a working one. | |
| 162 | +if ! stamped="$("$REPO/scripts/check-version.sh" "$STAGING/$BINARY" "${describe:-}" "${commit:-}" 2>&1)"; then | |
| 163 | + info "$stamped" | |
| 164 | + die "the build did not carry its version; nothing was installed" | |
| 165 | +fi | |
| 166 | +ok "built — $stamped" | |
| 167 | + | |
| 168 | +# --- install ---------------------------------------------------------------- | |
| 169 | + | |
| 170 | +step "Installing into $prefix" | |
| 171 | + | |
| 172 | +mkdir -p "$prefix" || die "cannot create $prefix" | |
| 173 | + | |
| 174 | +# Install by renaming a complete file over the target, never by writing into | |
| 175 | +# the one that is there. | |
| 176 | +# | |
| 177 | +# macOS caches a binary's code signature against its inode. cp writes new bytes | |
| 178 | +# into the existing inode, so the cached signature ends up describing something | |
| 179 | +# else and the kernel refuses to execute the result — a reinstall that builds, | |
| 180 | +# installs, and then will not run. A rename gives the name a fresh inode, so | |
| 181 | +# there is nothing stale to cache. It is atomic besides: no moment at which a | |
| 182 | +# half-written turbo-python is on the PATH. | |
| 183 | +# | |
| 184 | +# The temporary has to sit in $prefix, because a rename only works within one | |
| 185 | +# filesystem and $STAGING is somewhere else entirely. | |
| 186 | +readonly INCOMING="$prefix/.$BINARY.incoming.$$" | |
| 187 | +trap 'rm -rf "$STAGING"; rm -f "$INCOMING"' EXIT | |
| 188 | + | |
| 189 | +cp "$STAGING/$BINARY" "$INCOMING" || die "cannot write into $prefix" | |
| 190 | +chmod 0755 "$INCOMING" | |
| 191 | +mv -f "$INCOMING" "$TARGET" || die "cannot replace $TARGET" | |
| 192 | + | |
| 193 | +# Whatever the system said is the useful part: "does not run" on its own tells | |
| 194 | +# nobody anything they can act on. | |
| 195 | +if ! verify="$("$TARGET" -version 2>&1)"; then | |
| 196 | + info "$verify" | |
| 197 | + die "the installed binary does not run" | |
| 198 | +fi | |
| 199 | +version="$verify" | |
| 200 | +ok "$version → $TARGET" | |
| 201 | + | |
| 202 | +# --- PATH ------------------------------------------------------------------- | |
| 203 | + | |
| 204 | +# on_path reports whether a directory is one the shell searches. | |
| 205 | +on_path() { | |
| 206 | + case ":${PATH:-}:" in | |
| 207 | + *":$1:"*) return 0 ;; | |
| 208 | + *) return 1 ;; | |
| 209 | + esac | |
| 210 | +} | |
| 211 | + | |
| 212 | +# shell_profile guesses the file that sets PATH for the user's shell. | |
| 213 | +shell_profile() { | |
| 214 | + case "${SHELL:-}" in | |
| 215 | + */zsh) printf '~/.zshrc\n' ;; | |
| 216 | + */fish) printf '~/.config/fish/config.fish\n' ;; | |
| 217 | + *) printf '~/.bashrc\n' ;; | |
| 218 | + esac | |
| 219 | +} | |
| 220 | + | |
| 221 | +step "Checking your PATH" | |
| 222 | +if on_path "$prefix"; then | |
| 223 | + ok "$prefix is on your PATH" | |
| 224 | +else | |
| 225 | + warn "$prefix is not on your PATH. Add it:" | |
| 226 | + info "" | |
| 227 | + info " echo 'export PATH=\"\$PATH:$prefix\"' >> $(shell_profile)" | |
| 228 | + info " exec \$SHELL" | |
| 229 | +fi | |
| 230 | + | |
| 231 | +# --- the language server ---------------------------------------------------- | |
| 232 | + | |
| 233 | +# find_server looks where the editor itself looks: PATH, then the active | |
| 234 | +# virtual environment, the user's tool directory, pyenv's shims, and — on macOS | |
| 235 | +# — the per-version script directory that is on nobody's PATH. | |
| 236 | +# | |
| 237 | +# Finding it is not the same as its working: a shim left behind by a tool | |
| 238 | +# manager whose environment has since been removed sits on PATH and fails only | |
| 239 | +# when started. So this asks it for its version rather than trusting the file's | |
| 240 | +# existence, which is the difference between "you have completion" and "you | |
| 241 | +# will find out you have not when you press Ctrl-Space". | |
| 242 | +find_server() { | |
| 243 | + local candidate | |
| 244 | + for candidate in \ | |
| 245 | + "$(command -v pylsp 2>/dev/null || true)" \ | |
| 246 | + "${VIRTUAL_ENV:-/nonexistent}/bin/pylsp" \ | |
| 247 | + "$HOME/.local/bin/pylsp" \ | |
| 248 | + "${PYENV_ROOT:-$HOME/.pyenv}/shims/pylsp" \ | |
| 249 | + "$HOME"/Library/Python/*/bin/pylsp; do | |
| 250 | + [ -n "$candidate" ] && [ -x "$candidate" ] || continue | |
| 251 | + "$candidate" --version >/dev/null 2>&1 || continue | |
| 252 | + printf '%s\n' "$candidate" | |
| 253 | + return 0 | |
| 254 | + done | |
| 255 | + return 1 | |
| 256 | +} | |
| 257 | + | |
| 258 | +# server_has_linters reports whether the server can produce diagnostics at all. | |
| 259 | +# | |
| 260 | +# This is the trap that costs an afternoon. Installed without its extras, pylsp | |
| 261 | +# starts, completes and jumps to definitions — and publishes an *empty* list of | |
| 262 | +# problems for a file that does not even parse, because the linters that find | |
| 263 | +# them are optional dependencies. A blank gutter because the server has no | |
| 264 | +# linter and a blank gutter because the code is fine look identical. | |
| 265 | +# | |
| 266 | +# pylsp is a script whose first line names the interpreter it runs under, and | |
| 267 | +# the linters live in that interpreter's environment. A server this cannot read | |
| 268 | +# a shebang from returns 2, and nothing is claimed either way. | |
| 269 | +server_has_linters() { | |
| 270 | + local interpreter | |
| 271 | + interpreter="$(sed -n '1s/^#!\([^ ]*\).*/\1/p' "$1" 2>/dev/null || true)" | |
| 272 | + [ -n "$interpreter" ] && [ -x "$interpreter" ] || return 2 | |
| 273 | + "$interpreter" -c 'import pyflakes' >/dev/null 2>&1 | |
| 274 | +} | |
| 275 | + | |
| 276 | +# install_server runs the one command the editor's install hint names. | |
| 277 | +install_server() { | |
| 278 | + if command -v pipx >/dev/null 2>&1; then | |
| 279 | + pipx install "python-lsp-server[all]" || die "pipx could not install python-lsp-server" | |
| 280 | + elif command -v uv >/dev/null 2>&1; then | |
| 281 | + uv tool install "python-lsp-server[all]" || die "uv could not install python-lsp-server" | |
| 282 | + else | |
| 283 | + die "neither pipx nor uv is installed; see https://pipx.pypa.io" | |
| 284 | + fi | |
| 285 | +} | |
| 286 | + | |
| 287 | +step "Checking the language server" | |
| 288 | + | |
| 289 | +if $with_server && ! find_server >/dev/null; then | |
| 290 | + info " installing python-lsp-server…" | |
| 291 | + install_server | |
| 292 | +fi | |
| 293 | + | |
| 294 | +if server_path="$(find_server)"; then | |
| 295 | + ok "pylsp at $server_path" | |
| 296 | + | |
| 297 | + server_has_linters "$server_path" | |
| 298 | + case $? in | |
| 299 | + 0) ;; | |
| 300 | + 1) | |
| 301 | + warn "…but it has no linters, so there will be no error marks in the gutter." | |
| 302 | + warn "Completion and Go to definition work; problems will never appear." | |
| 303 | + info "" | |
| 304 | + info " pipx install --force \"python-lsp-server[all]\"" | |
| 305 | + ;; | |
| 306 | + esac | |
| 307 | +else | |
| 308 | + warn "pylsp is not installed, so there will be no completion." | |
| 309 | + warn "Editing, colouring and themes all work without it." | |
| 310 | + info "" | |
| 311 | + info " pipx install \"python-lsp-server[all]\"" | |
| 312 | + info " ${DIM}or re-run this script with --with-server${RESET}" | |
| 313 | +fi | |
| 314 | + | |
| 315 | +# --- what to do next -------------------------------------------------------- | |
| 316 | + | |
| 317 | +info "" | |
| 318 | +step "Ready" | |
| 319 | +info "" | |
| 320 | +info " Open a file ${BOLD}inside a Go module${RESET} — completion needs one:" | |
| 321 | +info "" | |
| 322 | +info " cd /path/to/your/project" | |
| 323 | +info " $BINARY main.go" | |
| 324 | +info "" | |
| 325 | +info " ${DIM}F10 menu · F2 save · Alt-X exit · type a '.' for completion${RESET}" | |
| 326 | +info " ${DIM}themes: $BINARY -list-themes${RESET}" | |
| 327 | +info "" | |
| new file mode 100755 | |||
| @@ -0,0 +1,327 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# | ||
| 3 | +# Build turbo-python and install it where your shell can find it. | ||
| 4 | +# | ||
| 5 | +# scripts/install.sh # install into GOBIN, or GOPATH/bin | ||
| 6 | +# scripts/install.sh --prefix ~/bin # install somewhere else | ||
| 7 | +# scripts/install.sh --with-analyzer # install the language server too | ||
| 8 | +# scripts/install.sh --uninstall # remove it again | ||
| 9 | +# | ||
| 10 | +# The build goes to a temporary file first, so a failed build never replaces a | ||
| 11 | +# working installation, and the install itself is a rename rather than a write | ||
| 12 | +# over the binary that is already there. The version is stamped in by the | ||
| 13 | +# linker, so `turbo-python -version` names the commit it was built from. | ||
| 14 | + | ||
| 15 | +set -euo pipefail | ||
| 16 | + | ||
| 17 | +readonly BINARY=turbo-python | ||
| 18 | + | ||
| 19 | +# --- output ----------------------------------------------------------------- | ||
| 20 | + | ||
| 21 | +if [ -t 1 ]; then | ||
| 22 | + readonly BOLD=$'\033[1m' DIM=$'\033[2m' RED=$'\033[31m' GREEN=$'\033[32m' YELLOW=$'\033[33m' RESET=$'\033[0m' | ||
| 23 | +else | ||
| 24 | + readonly BOLD='' DIM='' RED='' GREEN='' YELLOW='' RESET='' | ||
| 25 | +fi | ||
| 26 | + | ||
| 27 | +info() { printf '%s\n' "$*"; } | ||
| 28 | +step() { printf '%s==>%s %s\n' "$BOLD" "$RESET" "$*"; } | ||
| 29 | +ok() { printf '%s ✓%s %s\n' "$GREEN" "$RESET" "$*"; } | ||
| 30 | +warn() { printf '%s !%s %s\n' "$YELLOW" "$RESET" "$*"; } | ||
| 31 | +die() { | ||
| 32 | + printf '%s ✗%s %s\n' "$RED" "$RESET" "$*" >&2 | ||
| 33 | + exit 1 | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +usage() { | ||
| 37 | + cat <<EOF | ||
| 38 | +${BOLD}$BINARY installer${RESET} | ||
| 39 | + | ||
| 40 | + scripts/install.sh [options] | ||
| 41 | + | ||
| 42 | +Options: | ||
| 43 | + -p, --prefix DIR install into DIR (default: GOBIN, or GOPATH/bin) | ||
| 44 | + --with-server also install pylsp, which completion needs | ||
| 45 | + --uninstall remove an installed $BINARY and stop | ||
| 46 | + -h, --help show this and stop | ||
| 47 | +EOF | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +# --- arguments -------------------------------------------------------------- | ||
| 51 | + | ||
| 52 | +prefix="" | ||
| 53 | +with_server=false | ||
| 54 | +uninstall=false | ||
| 55 | + | ||
| 56 | +while [ $# -gt 0 ]; do | ||
| 57 | + case "$1" in | ||
| 58 | + -p | --prefix) | ||
| 59 | + [ $# -ge 2 ] || die "--prefix needs a directory" | ||
| 60 | + prefix="$2" | ||
| 61 | + shift 2 | ||
| 62 | + ;; | ||
| 63 | + --with-server) | ||
| 64 | + with_server=true | ||
| 65 | + shift | ||
| 66 | + ;; | ||
| 67 | + --uninstall) | ||
| 68 | + uninstall=true | ||
| 69 | + shift | ||
| 70 | + ;; | ||
| 71 | + -h | --help) | ||
| 72 | + usage | ||
| 73 | + exit 0 | ||
| 74 | + ;; | ||
| 75 | + *) die "unknown option: $1 (try --help)" ;; | ||
| 76 | + esac | ||
| 77 | +done | ||
| 78 | + | ||
| 79 | +# --- where things are ------------------------------------------------------- | ||
| 80 | + | ||
| 81 | +cd "$(dirname "${BASH_SOURCE[0]}")/.." | ||
| 82 | +readonly REPO="$PWD" | ||
| 83 | + | ||
| 84 | +command -v go >/dev/null 2>&1 || die "go is not installed: https://go.dev/dl/" | ||
| 85 | + | ||
| 86 | +# default_prefix returns where "go install" would put a binary: GOBIN when it | ||
| 87 | +# is set, GOPATH/bin otherwise. That is the directory a Go developer is most | ||
| 88 | +# likely to already have on PATH. | ||
| 89 | +default_prefix() { | ||
| 90 | + local gobin | ||
| 91 | + gobin="$(go env GOBIN)" | ||
| 92 | + if [ -n "$gobin" ]; then | ||
| 93 | + printf '%s\n' "$gobin" | ||
| 94 | + else | ||
| 95 | + printf '%s/bin\n' "$(go env GOPATH)" | ||
| 96 | + fi | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +[ -n "$prefix" ] || prefix="$(default_prefix)" | ||
| 100 | +[ -n "$prefix" ] || die "cannot work out where to install; use --prefix DIR" | ||
| 101 | +readonly TARGET="$prefix/$BINARY" | ||
| 102 | + | ||
| 103 | +# --- uninstall -------------------------------------------------------------- | ||
| 104 | + | ||
| 105 | +if $uninstall; then | ||
| 106 | + step "Removing $TARGET" | ||
| 107 | + if [ -e "$TARGET" ]; then | ||
| 108 | + rm -f "$TARGET" | ||
| 109 | + ok "removed" | ||
| 110 | + else | ||
| 111 | + warn "nothing installed at $TARGET" | ||
| 112 | + fi | ||
| 113 | + exit 0 | ||
| 114 | +fi | ||
| 115 | + | ||
| 116 | +# --- toolchain -------------------------------------------------------------- | ||
| 117 | + | ||
| 118 | +step "Checking the Go toolchain" | ||
| 119 | + | ||
| 120 | +# The requirement lives in go.mod, so this check cannot drift from the build. | ||
| 121 | +required="$(awk '/^go /{print $2; exit}' "$REPO/go.mod")" | ||
| 122 | +installed="$(go env GOVERSION)" | ||
| 123 | +installed="${installed#go}" | ||
| 124 | + | ||
| 125 | +if [ "$(printf '%s\n%s\n' "$required" "$installed" | sort -V | head -1)" != "$required" ]; then | ||
| 126 | + die "Go $required or later is needed, but $installed is installed" | ||
| 127 | +fi | ||
| 128 | +ok "go $installed (go.mod asks for $required or later)" | ||
| 129 | + | ||
| 130 | +# --- build ------------------------------------------------------------------ | ||
| 131 | + | ||
| 132 | +step "Building $BINARY" | ||
| 133 | + | ||
| 134 | +readonly STAGING="$(mktemp -d)" | ||
| 135 | +trap 'rm -rf "$STAGING"' EXIT | ||
| 136 | + | ||
| 137 | +# The version the binary reports is stamped in by the linker, so that an | ||
| 138 | +# installed editor names the commit it was actually built from rather than a | ||
| 139 | +# constant somebody forgot to bump. Outside a git checkout — installed from a | ||
| 140 | +# tarball, say — there is nothing to describe and the binary works the version | ||
| 141 | +# out from its own build information instead. | ||
| 142 | +version_pkg="rickub.com/turbo-editors/turbo-core/version" | ||
| 143 | +if describe="$(git -C "$REPO" describe --tags --dirty 2>/dev/null)"; then | ||
| 144 | + commit="$(git -C "$REPO" rev-parse --short HEAD 2>/dev/null || true)" | ||
| 145 | + built="$(date -u +%Y-%m-%dT%H:%M:%SZ)" | ||
| 146 | + ldflags="-X '$version_pkg.stamp=$describe' -X '$version_pkg.commit=$commit' -X '$version_pkg.built=$built'" | ||
| 147 | +else | ||
| 148 | + ldflags="" | ||
| 149 | +fi | ||
| 150 | + | ||
| 151 | +if ! go build -ldflags "$ldflags" -o "$STAGING/$BINARY" "$REPO" 2>"$STAGING/build.log"; then | ||
| 152 | + cat "$STAGING/build.log" >&2 | ||
| 153 | + info "" | ||
| 154 | + warn "A failure in the repository root is often a stray .go file that has" | ||
| 155 | + warn "landed in package main. 'go vet .' names it." | ||
| 156 | + die "build failed; nothing was installed" | ||
| 157 | +fi | ||
| 158 | + | ||
| 159 | +# Running the staged binary is the only proof that the flags above reached the | ||
| 160 | +# linker rather than merely looking right. It happens before the install, so a | ||
| 161 | +# binary that cannot name its own version never replaces a working one. | ||
| 162 | +if ! stamped="$("$REPO/scripts/check-version.sh" "$STAGING/$BINARY" "${describe:-}" "${commit:-}" 2>&1)"; then | ||
| 163 | + info "$stamped" | ||
| 164 | + die "the build did not carry its version; nothing was installed" | ||
| 165 | +fi | ||
| 166 | +ok "built — $stamped" | ||
| 167 | + | ||
| 168 | +# --- install ---------------------------------------------------------------- | ||
| 169 | + | ||
| 170 | +step "Installing into $prefix" | ||
| 171 | + | ||
| 172 | +mkdir -p "$prefix" || die "cannot create $prefix" | ||
| 173 | + | ||
| 174 | +# Install by renaming a complete file over the target, never by writing into | ||
| 175 | +# the one that is there. | ||
| 176 | +# | ||
| 177 | +# macOS caches a binary's code signature against its inode. cp writes new bytes | ||
| 178 | +# into the existing inode, so the cached signature ends up describing something | ||
| 179 | +# else and the kernel refuses to execute the result — a reinstall that builds, | ||
| 180 | +# installs, and then will not run. A rename gives the name a fresh inode, so | ||
| 181 | +# there is nothing stale to cache. It is atomic besides: no moment at which a | ||
| 182 | +# half-written turbo-python is on the PATH. | ||
| 183 | +# | ||
| 184 | +# The temporary has to sit in $prefix, because a rename only works within one | ||
| 185 | +# filesystem and $STAGING is somewhere else entirely. | ||
| 186 | +readonly INCOMING="$prefix/.$BINARY.incoming.$$" | ||
| 187 | +trap 'rm -rf "$STAGING"; rm -f "$INCOMING"' EXIT | ||
| 188 | + | ||
| 189 | +cp "$STAGING/$BINARY" "$INCOMING" || die "cannot write into $prefix" | ||
| 190 | +chmod 0755 "$INCOMING" | ||
| 191 | +mv -f "$INCOMING" "$TARGET" || die "cannot replace $TARGET" | ||
| 192 | + | ||
| 193 | +# Whatever the system said is the useful part: "does not run" on its own tells | ||
| 194 | +# nobody anything they can act on. | ||
| 195 | +if ! verify="$("$TARGET" -version 2>&1)"; then | ||
| 196 | + info "$verify" | ||
| 197 | + die "the installed binary does not run" | ||
| 198 | +fi | ||
| 199 | +version="$verify" | ||
| 200 | +ok "$version → $TARGET" | ||
| 201 | + | ||
| 202 | +# --- PATH ------------------------------------------------------------------- | ||
| 203 | + | ||
| 204 | +# on_path reports whether a directory is one the shell searches. | ||
| 205 | +on_path() { | ||
| 206 | + case ":${PATH:-}:" in | ||
| 207 | + *":$1:"*) return 0 ;; | ||
| 208 | + *) return 1 ;; | ||
| 209 | + esac | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +# shell_profile guesses the file that sets PATH for the user's shell. | ||
| 213 | +shell_profile() { | ||
| 214 | + case "${SHELL:-}" in | ||
| 215 | + */zsh) printf '~/.zshrc\n' ;; | ||
| 216 | + */fish) printf '~/.config/fish/config.fish\n' ;; | ||
| 217 | + *) printf '~/.bashrc\n' ;; | ||
| 218 | + esac | ||
| 219 | +} | ||
| 220 | + | ||
| 221 | +step "Checking your PATH" | ||
| 222 | +if on_path "$prefix"; then | ||
| 223 | + ok "$prefix is on your PATH" | ||
| 224 | +else | ||
| 225 | + warn "$prefix is not on your PATH. Add it:" | ||
| 226 | + info "" | ||
| 227 | + info " echo 'export PATH=\"\$PATH:$prefix\"' >> $(shell_profile)" | ||
| 228 | + info " exec \$SHELL" | ||
| 229 | +fi | ||
| 230 | + | ||
| 231 | +# --- the language server ---------------------------------------------------- | ||
| 232 | + | ||
| 233 | +# find_server looks where the editor itself looks: PATH, then the active | ||
| 234 | +# virtual environment, the user's tool directory, pyenv's shims, and — on macOS | ||
| 235 | +# — the per-version script directory that is on nobody's PATH. | ||
| 236 | +# | ||
| 237 | +# Finding it is not the same as its working: a shim left behind by a tool | ||
| 238 | +# manager whose environment has since been removed sits on PATH and fails only | ||
| 239 | +# when started. So this asks it for its version rather than trusting the file's | ||
| 240 | +# existence, which is the difference between "you have completion" and "you | ||
| 241 | +# will find out you have not when you press Ctrl-Space". | ||
| 242 | +find_server() { | ||
| 243 | + local candidate | ||
| 244 | + for candidate in \ | ||
| 245 | + "$(command -v pylsp 2>/dev/null || true)" \ | ||
| 246 | + "${VIRTUAL_ENV:-/nonexistent}/bin/pylsp" \ | ||
| 247 | + "$HOME/.local/bin/pylsp" \ | ||
| 248 | + "${PYENV_ROOT:-$HOME/.pyenv}/shims/pylsp" \ | ||
| 249 | + "$HOME"/Library/Python/*/bin/pylsp; do | ||
| 250 | + [ -n "$candidate" ] && [ -x "$candidate" ] || continue | ||
| 251 | + "$candidate" --version >/dev/null 2>&1 || continue | ||
| 252 | + printf '%s\n' "$candidate" | ||
| 253 | + return 0 | ||
| 254 | + done | ||
| 255 | + return 1 | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +# server_has_linters reports whether the server can produce diagnostics at all. | ||
| 259 | +# | ||
| 260 | +# This is the trap that costs an afternoon. Installed without its extras, pylsp | ||
| 261 | +# starts, completes and jumps to definitions — and publishes an *empty* list of | ||
| 262 | +# problems for a file that does not even parse, because the linters that find | ||
| 263 | +# them are optional dependencies. A blank gutter because the server has no | ||
| 264 | +# linter and a blank gutter because the code is fine look identical. | ||
| 265 | +# | ||
| 266 | +# pylsp is a script whose first line names the interpreter it runs under, and | ||
| 267 | +# the linters live in that interpreter's environment. A server this cannot read | ||
| 268 | +# a shebang from returns 2, and nothing is claimed either way. | ||
| 269 | +server_has_linters() { | ||
| 270 | + local interpreter | ||
| 271 | + interpreter="$(sed -n '1s/^#!\([^ ]*\).*/\1/p' "$1" 2>/dev/null || true)" | ||
| 272 | + [ -n "$interpreter" ] && [ -x "$interpreter" ] || return 2 | ||
| 273 | + "$interpreter" -c 'import pyflakes' >/dev/null 2>&1 | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +# install_server runs the one command the editor's install hint names. | ||
| 277 | +install_server() { | ||
| 278 | + if command -v pipx >/dev/null 2>&1; then | ||
| 279 | + pipx install "python-lsp-server[all]" || die "pipx could not install python-lsp-server" | ||
| 280 | + elif command -v uv >/dev/null 2>&1; then | ||
| 281 | + uv tool install "python-lsp-server[all]" || die "uv could not install python-lsp-server" | ||
| 282 | + else | ||
| 283 | + die "neither pipx nor uv is installed; see https://pipx.pypa.io" | ||
| 284 | + fi | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +step "Checking the language server" | ||
| 288 | + | ||
| 289 | +if $with_server && ! find_server >/dev/null; then | ||
| 290 | + info " installing python-lsp-server…" | ||
| 291 | + install_server | ||
| 292 | +fi | ||
| 293 | + | ||
| 294 | +if server_path="$(find_server)"; then | ||
| 295 | + ok "pylsp at $server_path" | ||
| 296 | + | ||
| 297 | + server_has_linters "$server_path" | ||
| 298 | + case $? in | ||
| 299 | + 0) ;; | ||
| 300 | + 1) | ||
| 301 | + warn "…but it has no linters, so there will be no error marks in the gutter." | ||
| 302 | + warn "Completion and Go to definition work; problems will never appear." | ||
| 303 | + info "" | ||
| 304 | + info " pipx install --force \"python-lsp-server[all]\"" | ||
| 305 | + ;; | ||
| 306 | + esac | ||
| 307 | +else | ||
| 308 | + warn "pylsp is not installed, so there will be no completion." | ||
| 309 | + warn "Editing, colouring and themes all work without it." | ||
| 310 | + info "" | ||
| 311 | + info " pipx install \"python-lsp-server[all]\"" | ||
| 312 | + info " ${DIM}or re-run this script with --with-server${RESET}" | ||
| 313 | +fi | ||
| 314 | + | ||
| 315 | +# --- what to do next -------------------------------------------------------- | ||
| 316 | + | ||
| 317 | +info "" | ||
| 318 | +step "Ready" | ||
| 319 | +info "" | ||
| 320 | +info " Open a file ${BOLD}inside a Go module${RESET} — completion needs one:" | ||
| 321 | +info "" | ||
| 322 | +info " cd /path/to/your/project" | ||
| 323 | +info " $BINARY main.go" | ||
| 324 | +info "" | ||
| 325 | +info " ${DIM}F10 menu · F2 save · Alt-X exit · type a '.' for completion${RESET}" | ||
| 326 | +info " ${DIM}themes: $BINARY -list-themes${RESET}" | ||
| 327 | +info "" | ||
added
version_check_test.go +174 -0 | new file mode 100644 | ||
| @@ -0,0 +1,174 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "os" | |
| 5 | + "os/exec" | |
| 6 | + "path/filepath" | |
| 7 | + "strings" | |
| 8 | + "testing" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// Linker flags are a string, and a wrong one is not an error: `-X` naming a | |
| 12 | +// symbol that does not exist links happily and stamps nothing, so the binary | |
| 13 | +// falls back to whatever the Go build system knows and reports a version the | |
| 14 | +// build never meant. Nothing but running the binary catches that, which is why | |
| 15 | +// `make build` runs it and why these tests do too. | |
| 16 | + | |
| 17 | +// buildStampedWith compiles the editor with the flags `make ldflags` produces | |
| 18 | +// for a version, and returns the path to the binary. | |
| 19 | +func buildStampedWith(t *testing.T, version string) string { | |
| 20 | + t.Helper() | |
| 21 | + | |
| 22 | + flags, err := exec.Command("make", "--no-print-directory", "ldflags", "VERSION="+version).Output() | |
| 23 | + if err != nil { | |
| 24 | + t.Fatalf("make ldflags VERSION=%s: %v", version, err) | |
| 25 | + } | |
| 26 | + | |
| 27 | + binary := filepath.Join(t.TempDir(), "turbo-python") | |
| 28 | + build := exec.Command("go", "build", "-ldflags", strings.TrimSpace(string(flags)), "-o", binary, ".") | |
| 29 | + if out, err := build.CombinedOutput(); err != nil { | |
| 30 | + t.Fatalf("building with those flags failed: %v\n%s", err, out) | |
| 31 | + } | |
| 32 | + return binary | |
| 33 | +} | |
| 34 | + | |
| 35 | +// checkVersion runs the build's version check and returns what it said and | |
| 36 | +// whether it was satisfied. | |
| 37 | +func checkVersion(t *testing.T, args ...string) (string, bool) { | |
| 38 | + t.Helper() | |
| 39 | + | |
| 40 | + out, err := exec.Command("./scripts/check-version.sh", args...).CombinedOutput() | |
| 41 | + return string(out), err == nil | |
| 42 | +} | |
| 43 | + | |
| 44 | +func TestTheVersionCheckAcceptsTheVersionTheBuildStamped(t *testing.T) { | |
| 45 | + binary := buildStampedWith(t, "v9.9.9") | |
| 46 | + | |
| 47 | + out, ok := checkVersion(t, binary, "v9.9.9") | |
| 48 | + if !ok { | |
| 49 | + t.Fatalf("the check refused a correctly stamped binary:\n%s", out) | |
| 50 | + } | |
| 51 | + if !strings.Contains(out, "9.9.9") { | |
| 52 | + t.Errorf("the check reported %q, want it to name the version", out) | |
| 53 | + } | |
| 54 | +} | |
| 55 | + | |
| 56 | +func TestTheVersionCheckRefusesAVersionThatMerelyContainsTheRightOne(t *testing.T) { | |
| 57 | + // The reason this is an equality test and not a grep: "0.2.0" is a | |
| 58 | + // substring of "10.2.0", so a substring check passes a release that ships | |
| 59 | + // a binary naming an entirely different version. | |
| 60 | + binary := buildStampedWith(t, "v10.2.0") | |
| 61 | + | |
| 62 | + out, ok := checkVersion(t, binary, "v0.2.0") | |
| 63 | + if ok { | |
| 64 | + t.Fatalf("the check accepted 10.2.0 as 0.2.0:\n%s", out) | |
| 65 | + } | |
| 66 | + if !strings.Contains(out, "10.2.0") { | |
| 67 | + t.Errorf("the failure does not say what the binary actually reports:\n%s", out) | |
| 68 | + } | |
| 69 | +} | |
| 70 | + | |
| 71 | +func TestTheVersionCheckRefusesAStampThatNeverReachedTheLinker(t *testing.T) { | |
| 72 | + // The failure this exists for. `-X` naming a symbol that is not there is | |
| 73 | + // not an error: the binary links, runs, and reports the wrong thing. | |
| 74 | + binary := filepath.Join(t.TempDir(), "turbo-python") | |
| 75 | + build := exec.Command("go", "build", | |
| 76 | + "-ldflags", "-X 'rickub.com/turbo-editors/turbo-core/version.stampX=v9.9.9'", | |
| 77 | + "-o", binary, ".") | |
| 78 | + if out, err := build.CombinedOutput(); err != nil { | |
| 79 | + t.Fatalf("the build with a misspelt -X failed, so there is nothing to catch: %v\n%s", err, out) | |
| 80 | + } | |
| 81 | + | |
| 82 | + out, ok := checkVersion(t, binary, "v9.9.9") | |
| 83 | + if ok { | |
| 84 | + t.Fatalf("the check accepted a binary nothing was stamped into:\n%s", out) | |
| 85 | + } | |
| 86 | +} | |
| 87 | + | |
| 88 | +func TestTheVersionCheckRefusesABinaryThatDoesNotRun(t *testing.T) { | |
| 89 | + binary := filepath.Join(t.TempDir(), "turbo-python") | |
| 90 | + if err := os.WriteFile(binary, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { | |
| 91 | + t.Fatalf("cannot write the stand-in: %v", err) | |
| 92 | + } | |
| 93 | + | |
| 94 | + if out, ok := checkVersion(t, binary, "v9.9.9"); ok { | |
| 95 | + t.Fatalf("the check accepted a binary that does not run:\n%s", out) | |
| 96 | + } | |
| 97 | +} | |
| 98 | + | |
| 99 | +func TestTheVersionCheckNeedsSomethingToCheck(t *testing.T) { | |
| 100 | + if out, ok := checkVersion(t); ok { | |
| 101 | + t.Fatalf("the check accepted no arguments at all:\n%s", out) | |
| 102 | + } | |
| 103 | + if out, ok := checkVersion(t, filepath.Join(t.TempDir(), "not-there")); ok { | |
| 104 | + t.Fatalf("the check accepted a path with no binary at it:\n%s", out) | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 108 | +func TestAnUnstampedBuildIsAcceptedButAnUnnameableOneIsNot(t *testing.T) { | |
| 109 | + // Installing from a tarball has no git checkout to describe, so there is no | |
| 110 | + // version to expect. The claim left is that *some* source named it. | |
| 111 | + binary := filepath.Join(t.TempDir(), "turbo-python") | |
| 112 | + build := exec.Command("go", "build", "-o", binary, ".") | |
| 113 | + if out, err := build.CombinedOutput(); err != nil { | |
| 114 | + t.Fatalf("an unstamped build failed: %v\n%s", err, out) | |
| 115 | + } | |
| 116 | + | |
| 117 | + out, ok := checkVersion(t, binary) | |
| 118 | + if !ok { | |
| 119 | + t.Fatalf("the check refused an unstamped build, which is a legitimate one:\n%s", out) | |
| 120 | + } | |
| 121 | + if strings.Contains(out, "unknown") { | |
| 122 | + t.Errorf("the binary cannot name its version and the check passed anyway:\n%s", out) | |
| 123 | + } | |
| 124 | +} | |
| 125 | + | |
| 126 | +func TestTheBuildTargetChecksWhatItStamped(t *testing.T) { | |
| 127 | + // The wiring, not the script: a check nothing calls protects nothing. | |
| 128 | + makefile, err := os.ReadFile("Makefile") | |
| 129 | + if err != nil { | |
| 130 | + t.Fatalf("cannot read the Makefile: %v", err) | |
| 131 | + } | |
| 132 | + recipe := buildRecipe(t, string(makefile)) | |
| 133 | + | |
| 134 | + if !strings.Contains(recipe, "check-version.sh") { | |
| 135 | + t.Errorf("the build target never checks the version it stamped:\n%s", recipe) | |
| 136 | + } | |
| 137 | +} | |
| 138 | + | |
| 139 | +func TestTheInstallerChecksWhatItStampedBeforeItInstalls(t *testing.T) { | |
| 140 | + // Before, not after: a binary that cannot name its own version must never | |
| 141 | + // replace one that can. | |
| 142 | + script, err := os.ReadFile("scripts/install.sh") | |
| 143 | + if err != nil { | |
| 144 | + t.Fatalf("cannot read the installer: %v", err) | |
| 145 | + } | |
| 146 | + text := string(script) | |
| 147 | + | |
| 148 | + check := strings.Index(text, "check-version.sh") | |
| 149 | + install := strings.Index(text, "mv -f") | |
| 150 | + switch { | |
| 151 | + case check < 0: | |
| 152 | + t.Fatal("the installer never checks the version it stamped") | |
| 153 | + case install < 0: | |
| 154 | + t.Fatal("the installer no longer installs by rename; this test is out of date") | |
| 155 | + case check > install: | |
| 156 | + t.Error("the installer checks the version after installing, so a bad build replaces a good one") | |
| 157 | + } | |
| 158 | +} | |
| 159 | + | |
| 160 | +// buildRecipe returns the lines of the Makefile's build target. | |
| 161 | +func buildRecipe(t *testing.T, makefile string) string { | |
| 162 | + t.Helper() | |
| 163 | + | |
| 164 | + start := strings.Index(makefile, "\nbuild:") | |
| 165 | + if start < 0 { | |
| 166 | + t.Fatal("the Makefile has no build target") | |
| 167 | + } | |
| 168 | + rest := makefile[start+1:] | |
| 169 | + end := strings.Index(rest, "\n\n") | |
| 170 | + if end < 0 { | |
| 171 | + end = len(rest) | |
| 172 | + } | |
| 173 | + return rest[:end] | |
| 174 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,174 @@ | |||
| 1 | +package main | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "os" | ||
| 5 | + "os/exec" | ||
| 6 | + "path/filepath" | ||
| 7 | + "strings" | ||
| 8 | + "testing" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// Linker flags are a string, and a wrong one is not an error: `-X` naming a | ||
| 12 | +// symbol that does not exist links happily and stamps nothing, so the binary | ||
| 13 | +// falls back to whatever the Go build system knows and reports a version the | ||
| 14 | +// build never meant. Nothing but running the binary catches that, which is why | ||
| 15 | +// `make build` runs it and why these tests do too. | ||
| 16 | + | ||
| 17 | +// buildStampedWith compiles the editor with the flags `make ldflags` produces | ||
| 18 | +// for a version, and returns the path to the binary. | ||
| 19 | +func buildStampedWith(t *testing.T, version string) string { | ||
| 20 | + t.Helper() | ||
| 21 | + | ||
| 22 | + flags, err := exec.Command("make", "--no-print-directory", "ldflags", "VERSION="+version).Output() | ||
| 23 | + if err != nil { | ||
| 24 | + t.Fatalf("make ldflags VERSION=%s: %v", version, err) | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + binary := filepath.Join(t.TempDir(), "turbo-python") | ||
| 28 | + build := exec.Command("go", "build", "-ldflags", strings.TrimSpace(string(flags)), "-o", binary, ".") | ||
| 29 | + if out, err := build.CombinedOutput(); err != nil { | ||
| 30 | + t.Fatalf("building with those flags failed: %v\n%s", err, out) | ||
| 31 | + } | ||
| 32 | + return binary | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +// checkVersion runs the build's version check and returns what it said and | ||
| 36 | +// whether it was satisfied. | ||
| 37 | +func checkVersion(t *testing.T, args ...string) (string, bool) { | ||
| 38 | + t.Helper() | ||
| 39 | + | ||
| 40 | + out, err := exec.Command("./scripts/check-version.sh", args...).CombinedOutput() | ||
| 41 | + return string(out), err == nil | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +func TestTheVersionCheckAcceptsTheVersionTheBuildStamped(t *testing.T) { | ||
| 45 | + binary := buildStampedWith(t, "v9.9.9") | ||
| 46 | + | ||
| 47 | + out, ok := checkVersion(t, binary, "v9.9.9") | ||
| 48 | + if !ok { | ||
| 49 | + t.Fatalf("the check refused a correctly stamped binary:\n%s", out) | ||
| 50 | + } | ||
| 51 | + if !strings.Contains(out, "9.9.9") { | ||
| 52 | + t.Errorf("the check reported %q, want it to name the version", out) | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +func TestTheVersionCheckRefusesAVersionThatMerelyContainsTheRightOne(t *testing.T) { | ||
| 57 | + // The reason this is an equality test and not a grep: "0.2.0" is a | ||
| 58 | + // substring of "10.2.0", so a substring check passes a release that ships | ||
| 59 | + // a binary naming an entirely different version. | ||
| 60 | + binary := buildStampedWith(t, "v10.2.0") | ||
| 61 | + | ||
| 62 | + out, ok := checkVersion(t, binary, "v0.2.0") | ||
| 63 | + if ok { | ||
| 64 | + t.Fatalf("the check accepted 10.2.0 as 0.2.0:\n%s", out) | ||
| 65 | + } | ||
| 66 | + if !strings.Contains(out, "10.2.0") { | ||
| 67 | + t.Errorf("the failure does not say what the binary actually reports:\n%s", out) | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +func TestTheVersionCheckRefusesAStampThatNeverReachedTheLinker(t *testing.T) { | ||
| 72 | + // The failure this exists for. `-X` naming a symbol that is not there is | ||
| 73 | + // not an error: the binary links, runs, and reports the wrong thing. | ||
| 74 | + binary := filepath.Join(t.TempDir(), "turbo-python") | ||
| 75 | + build := exec.Command("go", "build", | ||
| 76 | + "-ldflags", "-X 'rickub.com/turbo-editors/turbo-core/version.stampX=v9.9.9'", | ||
| 77 | + "-o", binary, ".") | ||
| 78 | + if out, err := build.CombinedOutput(); err != nil { | ||
| 79 | + t.Fatalf("the build with a misspelt -X failed, so there is nothing to catch: %v\n%s", err, out) | ||
| 80 | + } | ||
| 81 | + | ||
| 82 | + out, ok := checkVersion(t, binary, "v9.9.9") | ||
| 83 | + if ok { | ||
| 84 | + t.Fatalf("the check accepted a binary nothing was stamped into:\n%s", out) | ||
| 85 | + } | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +func TestTheVersionCheckRefusesABinaryThatDoesNotRun(t *testing.T) { | ||
| 89 | + binary := filepath.Join(t.TempDir(), "turbo-python") | ||
| 90 | + if err := os.WriteFile(binary, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { | ||
| 91 | + t.Fatalf("cannot write the stand-in: %v", err) | ||
| 92 | + } | ||
| 93 | + | ||
| 94 | + if out, ok := checkVersion(t, binary, "v9.9.9"); ok { | ||
| 95 | + t.Fatalf("the check accepted a binary that does not run:\n%s", out) | ||
| 96 | + } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +func TestTheVersionCheckNeedsSomethingToCheck(t *testing.T) { | ||
| 100 | + if out, ok := checkVersion(t); ok { | ||
| 101 | + t.Fatalf("the check accepted no arguments at all:\n%s", out) | ||
| 102 | + } | ||
| 103 | + if out, ok := checkVersion(t, filepath.Join(t.TempDir(), "not-there")); ok { | ||
| 104 | + t.Fatalf("the check accepted a path with no binary at it:\n%s", out) | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +func TestAnUnstampedBuildIsAcceptedButAnUnnameableOneIsNot(t *testing.T) { | ||
| 109 | + // Installing from a tarball has no git checkout to describe, so there is no | ||
| 110 | + // version to expect. The claim left is that *some* source named it. | ||
| 111 | + binary := filepath.Join(t.TempDir(), "turbo-python") | ||
| 112 | + build := exec.Command("go", "build", "-o", binary, ".") | ||
| 113 | + if out, err := build.CombinedOutput(); err != nil { | ||
| 114 | + t.Fatalf("an unstamped build failed: %v\n%s", err, out) | ||
| 115 | + } | ||
| 116 | + | ||
| 117 | + out, ok := checkVersion(t, binary) | ||
| 118 | + if !ok { | ||
| 119 | + t.Fatalf("the check refused an unstamped build, which is a legitimate one:\n%s", out) | ||
| 120 | + } | ||
| 121 | + if strings.Contains(out, "unknown") { | ||
| 122 | + t.Errorf("the binary cannot name its version and the check passed anyway:\n%s", out) | ||
| 123 | + } | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +func TestTheBuildTargetChecksWhatItStamped(t *testing.T) { | ||
| 127 | + // The wiring, not the script: a check nothing calls protects nothing. | ||
| 128 | + makefile, err := os.ReadFile("Makefile") | ||
| 129 | + if err != nil { | ||
| 130 | + t.Fatalf("cannot read the Makefile: %v", err) | ||
| 131 | + } | ||
| 132 | + recipe := buildRecipe(t, string(makefile)) | ||
| 133 | + | ||
| 134 | + if !strings.Contains(recipe, "check-version.sh") { | ||
| 135 | + t.Errorf("the build target never checks the version it stamped:\n%s", recipe) | ||
| 136 | + } | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +func TestTheInstallerChecksWhatItStampedBeforeItInstalls(t *testing.T) { | ||
| 140 | + // Before, not after: a binary that cannot name its own version must never | ||
| 141 | + // replace one that can. | ||
| 142 | + script, err := os.ReadFile("scripts/install.sh") | ||
| 143 | + if err != nil { | ||
| 144 | + t.Fatalf("cannot read the installer: %v", err) | ||
| 145 | + } | ||
| 146 | + text := string(script) | ||
| 147 | + | ||
| 148 | + check := strings.Index(text, "check-version.sh") | ||
| 149 | + install := strings.Index(text, "mv -f") | ||
| 150 | + switch { | ||
| 151 | + case check < 0: | ||
| 152 | + t.Fatal("the installer never checks the version it stamped") | ||
| 153 | + case install < 0: | ||
| 154 | + t.Fatal("the installer no longer installs by rename; this test is out of date") | ||
| 155 | + case check > install: | ||
| 156 | + t.Error("the installer checks the version after installing, so a bad build replaces a good one") | ||
| 157 | + } | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +// buildRecipe returns the lines of the Makefile's build target. | ||
| 161 | +func buildRecipe(t *testing.T, makefile string) string { | ||
| 162 | + t.Helper() | ||
| 163 | + | ||
| 164 | + start := strings.Index(makefile, "\nbuild:") | ||
| 165 | + if start < 0 { | ||
| 166 | + t.Fatal("the Makefile has no build target") | ||
| 167 | + } | ||
| 168 | + rest := makefile[start+1:] | ||
| 169 | + end := strings.Index(rest, "\n\n") | ||
| 170 | + if end < 0 { | ||
| 171 | + end = len(rest) | ||
| 172 | + } | ||
| 173 | + return rest[:end] | ||
| 174 | +} | ||