📦 Turbo MoonBit
cc1f595 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_MOONBIT_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 MoonBit <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 MoonBit ${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-moonbit-${version}-<platform>" | |
| 100 | + echo "./turbo-moonbit-${version}-<platform> main.mbt" | |
| 101 | + echo '```' | |
| 102 | + echo | |
| 103 | + echo "On macOS, an unsigned download is quarantined until you say otherwise: \`xattr -d com.apple.quarantine turbo-moonbit-${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-moonbit-${{ 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-moonbit-* | |
| 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_MOONBIT_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 MoonBit <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 MoonBit ${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-moonbit-${version}-<platform>" | ||
| 100 | + echo "./turbo-moonbit-${version}-<platform> main.mbt" | ||
| 101 | + echo '```' | ||
| 102 | + echo | ||
| 103 | + echo "On macOS, an unsigned download is quarantined until you say otherwise: \`xattr -d com.apple.quarantine turbo-moonbit-${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-moonbit-${{ 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-moonbit-* | ||
| 135 | + release/${{ github.ref_name }}/SHA256SUMS | ||
| 136 | + release/${{ github.ref_name }}/README.md | ||
| 137 | + fail_on_unmatched_files: true | ||
added
.gitignore +14 -0 | new file mode 100644 | ||
| @@ -0,0 +1,14 @@ | ||
| 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 | |
| 11 | + | |
| 12 | +# The demo projects build into these. moon always excludes a package-root | |
| 13 | +# _build/ from what it packages, and there is no reason to commit one either. | |
| 14 | +demos/**/_build/ | |
| new file mode 100644 | |||
| @@ -0,0 +1,14 @@ | |||
| 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 | ||
| 11 | + | ||
| 12 | +# The demo projects build into these. moon always excludes a package-root | ||
| 13 | +# _build/ from what it packages, and there is no reason to commit one either. | ||
| 14 | +demos/**/_build/ | ||
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-09-first-editor.md +42 -0 | new file mode 100644 | ||
| @@ -0,0 +1,42 @@ | ||
| 1 | +# Handoff — 2026-09-09 — Turbo MoonBit, first build | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +The editor is complete and green. `make check` passes, the quality gate passes, the documentation is written in both languages, and the binary has been driven through a pty. Nothing is in flight. | |
| 6 | + | |
| 7 | +The working tree is **uncommitted**. Everything described here exists on disk on `main`, at `a1558e2` (the initial commit), and has not been staged. That was deliberate — no commit was asked for. | |
| 8 | + | |
| 9 | +## Added after the first pass | |
| 10 | + | |
| 11 | +`demos/` — three MoonBit projects (`hello`, `shapes`, `syntax-tour`) with a README. All three `moon check` clean, are unchanged by `moon fmt`, and run; `shapes` has five tests. **Building them is what found three things the Go suite could not**: `derive(Show)` and the functional `loop` form are both deprecated (the starter snippets file used both — fixed), and `typealias` is not accepted at top level by this compiler although the grammar lists it as a keyword. | |
| 12 | + | |
| 13 | +Opening `syntax-tour/tour.mbt` in a pty also found a scanner boundary the docs had described too loosely: a string nested inside an interpolation ends the outer literal. The reference and the explanation now state it exactly, a test pins it, and the demo keeps the offending line with a comment. | |
| 14 | + | |
| 15 | +## What was touched outside this repository | |
| 16 | + | |
| 17 | +Two sibling repositories were edited, and both need their own commit: | |
| 18 | + | |
| 19 | +- **turbo-core** — `README.md`, `docs/{en,fr}/README.md`, `docs/{en,fr}/how-to/test-without-publishing.md`, `profile/profile.go`'s package comment, and `.memory/summary.md`: all now count four editors. Its `.go` strings were swept for hardcoded language names and **no code change was needed**, which is the strongest evidence yet that the seam holds. | |
| 20 | +- **turbo-python** — a real defect, found because this editor was adapted from it. Its docs claimed the Python menu answers to `Alt-T`; it answers to `Alt-P`. `Alt-T` is Turbo Rust's, inherited through a mechanical substitution that only looked at identifiers. Fixed in eight places across both languages, along with "all three editors" → four in its architecture explanation. **That repository's `.memory/` has not been updated**, and should get a history entry saying so. | |
| 21 | + | |
| 22 | +## Next steps | |
| 23 | + | |
| 24 | +1. **Commit.** This repository, turbo-core and turbo-python each want one. | |
| 25 | +2. **Tag a release.** `release.env` currently says `TAG="v0.1.1"`, copied from turbo-python; the first tag here should be `v0.1.0`. `01-release.tag.sh` runs `make check` and refuses a live `replace`, so it should go through as it stands. | |
| 26 | +3. **Read the two boundaries in `summary.md`** before promising anything about diagnostics or about labels in `turbo-classic`. | |
| 27 | + | |
| 28 | +## Open questions / blockers | |
| 29 | + | |
| 30 | +- **Should turbo-core send `workspace/didChangeWatchedFiles`?** It is the fix for "moon-lsp never diagnoses a file created after it started", it would help every editor in the family, and it is a library change with its own `/methodical-dev` cycle. Not started. | |
| 31 | +- **Should `turbo-classic` give `syntax.attribute` its own colour?** It is currently the same yellow as `syntax.identifier`, so a MoonBit label or attribute is invisible as such in that one theme — and Turbo Rust's `#[derive]` has the same problem. Also turbo-core's decision. | |
| 32 | +- **Nothing here has run on macOS or Windows.** The user's machine is macOS; the binary built in this sandbox is an ELF they cannot run. | |
| 33 | + | |
| 34 | +## Watch out for | |
| 35 | + | |
| 36 | +- **Do not use a shell `cp file /tmp/x; …; cp /tmp/x file` round trip to back a file up before mutating it.** Doing that during mutation testing silently left three source files NUL-padded, and the symptom was `unexpected NUL in input` from the compiler rather than anything pointing at the backup. Mutate in-process instead: read the file into a Python string, write the mutation, write the original string back. `/tmp/falsify*.py` do it that way and are safe to re-run. | |
| 37 | +- **`gofmt` rewrites a bare run of three apostrophes in a doc comment into typographic quotes.** `templates.go` says "three apostrophes" in words for that reason; do not helpfully replace it with the characters. | |
| 38 | +- **`moon-lsp` with no argument prints its usage and exits.** The `--stdio` in `ServerArgs()` is load-bearing, and dropping it looks like a server that died at start-up. | |
| 39 | +- **A fixture project for the language-server tests must compile.** `brokenProject` exists as a *second* fixture rather than as an extra file in the first, because a package holding an error makes every other answer from the server worthless — the completion test would then be measuring a broken build. | |
| 40 | +- **The `-short` flag skips every moon-lsp test.** A green `go test -short ./...` proves nothing about the server. | |
| 41 | +- **The demos are not checked by anything automatic.** They were built, run and formatted by hand. A future MoonBit release could deprecate something in them and nothing would say so — re-run `moon check` in each before a release, or wire it into `make check` if the toolchain can be assumed present. | |
| 42 | +- **`docs/*/reference/languages.md` is read by a test.** `TestEveryKeywordTheReferenceListsIsAKeyword` parses the keyword row out of the English page, so reformatting that table breaks the test rather than the docs. | |
| new file mode 100644 | |||
| @@ -0,0 +1,42 @@ | |||
| 1 | +# Handoff — 2026-09-09 — Turbo MoonBit, first build | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +The editor is complete and green. `make check` passes, the quality gate passes, the documentation is written in both languages, and the binary has been driven through a pty. Nothing is in flight. | ||
| 6 | + | ||
| 7 | +The working tree is **uncommitted**. Everything described here exists on disk on `main`, at `a1558e2` (the initial commit), and has not been staged. That was deliberate — no commit was asked for. | ||
| 8 | + | ||
| 9 | +## Added after the first pass | ||
| 10 | + | ||
| 11 | +`demos/` — three MoonBit projects (`hello`, `shapes`, `syntax-tour`) with a README. All three `moon check` clean, are unchanged by `moon fmt`, and run; `shapes` has five tests. **Building them is what found three things the Go suite could not**: `derive(Show)` and the functional `loop` form are both deprecated (the starter snippets file used both — fixed), and `typealias` is not accepted at top level by this compiler although the grammar lists it as a keyword. | ||
| 12 | + | ||
| 13 | +Opening `syntax-tour/tour.mbt` in a pty also found a scanner boundary the docs had described too loosely: a string nested inside an interpolation ends the outer literal. The reference and the explanation now state it exactly, a test pins it, and the demo keeps the offending line with a comment. | ||
| 14 | + | ||
| 15 | +## What was touched outside this repository | ||
| 16 | + | ||
| 17 | +Two sibling repositories were edited, and both need their own commit: | ||
| 18 | + | ||
| 19 | +- **turbo-core** — `README.md`, `docs/{en,fr}/README.md`, `docs/{en,fr}/how-to/test-without-publishing.md`, `profile/profile.go`'s package comment, and `.memory/summary.md`: all now count four editors. Its `.go` strings were swept for hardcoded language names and **no code change was needed**, which is the strongest evidence yet that the seam holds. | ||
| 20 | +- **turbo-python** — a real defect, found because this editor was adapted from it. Its docs claimed the Python menu answers to `Alt-T`; it answers to `Alt-P`. `Alt-T` is Turbo Rust's, inherited through a mechanical substitution that only looked at identifiers. Fixed in eight places across both languages, along with "all three editors" → four in its architecture explanation. **That repository's `.memory/` has not been updated**, and should get a history entry saying so. | ||
| 21 | + | ||
| 22 | +## Next steps | ||
| 23 | + | ||
| 24 | +1. **Commit.** This repository, turbo-core and turbo-python each want one. | ||
| 25 | +2. **Tag a release.** `release.env` currently says `TAG="v0.1.1"`, copied from turbo-python; the first tag here should be `v0.1.0`. `01-release.tag.sh` runs `make check` and refuses a live `replace`, so it should go through as it stands. | ||
| 26 | +3. **Read the two boundaries in `summary.md`** before promising anything about diagnostics or about labels in `turbo-classic`. | ||
| 27 | + | ||
| 28 | +## Open questions / blockers | ||
| 29 | + | ||
| 30 | +- **Should turbo-core send `workspace/didChangeWatchedFiles`?** It is the fix for "moon-lsp never diagnoses a file created after it started", it would help every editor in the family, and it is a library change with its own `/methodical-dev` cycle. Not started. | ||
| 31 | +- **Should `turbo-classic` give `syntax.attribute` its own colour?** It is currently the same yellow as `syntax.identifier`, so a MoonBit label or attribute is invisible as such in that one theme — and Turbo Rust's `#[derive]` has the same problem. Also turbo-core's decision. | ||
| 32 | +- **Nothing here has run on macOS or Windows.** The user's machine is macOS; the binary built in this sandbox is an ELF they cannot run. | ||
| 33 | + | ||
| 34 | +## Watch out for | ||
| 35 | + | ||
| 36 | +- **Do not use a shell `cp file /tmp/x; …; cp /tmp/x file` round trip to back a file up before mutating it.** Doing that during mutation testing silently left three source files NUL-padded, and the symptom was `unexpected NUL in input` from the compiler rather than anything pointing at the backup. Mutate in-process instead: read the file into a Python string, write the mutation, write the original string back. `/tmp/falsify*.py` do it that way and are safe to re-run. | ||
| 37 | +- **`gofmt` rewrites a bare run of three apostrophes in a doc comment into typographic quotes.** `templates.go` says "three apostrophes" in words for that reason; do not helpfully replace it with the characters. | ||
| 38 | +- **`moon-lsp` with no argument prints its usage and exits.** The `--stdio` in `ServerArgs()` is load-bearing, and dropping it looks like a server that died at start-up. | ||
| 39 | +- **A fixture project for the language-server tests must compile.** `brokenProject` exists as a *second* fixture rather than as an extra file in the first, because a package holding an error makes every other answer from the server worthless — the completion test would then be measuring a broken build. | ||
| 40 | +- **The `-short` flag skips every moon-lsp test.** A green `go test -short ./...` proves nothing about the server. | ||
| 41 | +- **The demos are not checked by anything automatic.** They were built, run and formatted by hand. A future MoonBit release could deprecate something in them and nothing would say so — re-run `moon check` in each before a release, or wire it into `make check` if the toolchain can be assumed present. | ||
| 42 | +- **`docs/*/reference/languages.md` is read by a test.** `TestEveryKeywordTheReferenceListsIsAKeyword` parses the keyword row out of the English page, so reformatting that table breaks the test rather than the docs. | ||
added
.memory/handoffs/2026-09-14-family-count.md +5 -0 | new file mode 100644 | ||
| @@ -0,0 +1,5 @@ | ||
| 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`. | |
| 4 | + | |
| 5 | +The working tree also carries the user's own change to `demos/hello/.turbo-moonbit/settings.toml` (theme switched to `monochrome-light`), which predates this session and was not touched. Two unrelated changes in one tree — commit them apart or together, but know they are two. | |
| new file mode 100644 | |||
| @@ -0,0 +1,5 @@ | |||
| 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`. | ||
| 4 | + | ||
| 5 | +The working tree also carries the user's own change to `demos/hello/.turbo-moonbit/settings.toml` (theme switched to `monochrome-light`), which predates this session and was not touched. Two unrelated changes in one tree — commit them apart or together, but know they are two. | ||
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 | +`demos/hello/.turbo-moonbit/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 | +`demos/hello/.turbo-moonbit/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 ```moonbit 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 ```moonbit 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 +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +# Handoff — 2026-09-19 — Rickub migration and the Release workflow | |
| 2 | + | |
| 3 | +## State | |
| 4 | + | |
| 5 | +- Module `rickub.com/turbo-editors/turbo-moonbit`, 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-moonbit.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 MoonBit"`) 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-moonbit-<tag>` artifact (14 days). | |
| 14 | +4. `turbo-moonbit.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. | |
| 22 | + | |
| 23 | +## Later the same day — blocked on turbo-core v1.0.1 | |
| 24 | + | |
| 25 | +`make check` fails on macOS against turbo-core v1.0.0 (see `history.md`: symlinked temp dirs and moon-lsp). Wait for turbo-core v1.0.1, re-pin (`go get rickub.com/turbo-editors/turbo-core@v1.0.1 && go mod tidy && GOWORK=off make check`), then release. The MoonBit toolchain 2026-09-15 is installed in the sandbox (`~/.moon/bin`), so the real-server tests run here now. | |
| 26 | + | |
| 27 | +## Blocked on turbo-core v1.0.2 now | |
| 28 | + | |
| 29 | +v1.0.1 fixed the symlink failures; the next `make check` on the Mac hit the "never diagnosed after start" pin, which is a turbo-core limit fixed in v1.0.2 (see `history.md`). Re-pin to v1.0.2, `GOWORK=off make check`, release. | |
| new file mode 100644 | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | +# Handoff — 2026-09-19 — Rickub migration and the Release workflow | ||
| 2 | + | ||
| 3 | +## State | ||
| 4 | + | ||
| 5 | +- Module `rickub.com/turbo-editors/turbo-moonbit`, 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-moonbit.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 MoonBit"`) 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-moonbit-<tag>` artifact (14 days). | ||
| 14 | +4. `turbo-moonbit.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. | ||
| 22 | + | ||
| 23 | +## Later the same day — blocked on turbo-core v1.0.1 | ||
| 24 | + | ||
| 25 | +`make check` fails on macOS against turbo-core v1.0.0 (see `history.md`: symlinked temp dirs and moon-lsp). Wait for turbo-core v1.0.1, re-pin (`go get rickub.com/turbo-editors/turbo-core@v1.0.1 && go mod tidy && GOWORK=off make check`), then release. The MoonBit toolchain 2026-09-15 is installed in the sandbox (`~/.moon/bin`), so the real-server tests run here now. | ||
| 26 | + | ||
| 27 | +## Blocked on turbo-core v1.0.2 now | ||
| 28 | + | ||
| 29 | +v1.0.1 fixed the symlink failures; the next `make check` on the Mac hit the "never diagnosed after start" pin, which is a turbo-core limit fixed in v1.0.2 (see `history.md`). Re-pin to v1.0.2, `GOWORK=off make check`, release. | ||
added
.memory/history.md +115 -0 | new file mode 100644 | ||
| @@ -0,0 +1,115 @@ | ||
| 1 | +# History | |
| 2 | + | |
| 3 | +One dated entry per session, appended. Never rewritten. | |
| 4 | + | |
| 5 | +## 2026-09-09 — Turbo MoonBit built, from an empty repository to a passing gate | |
| 6 | + | |
| 7 | +- **Goal**: a Turbo editor for MoonBit — `/turbo-new-editor` for the language, in this directory, with the MoonBit toolchain's installation documented. | |
| 8 | +- **Changes**: `go.mod` (turbo-core v0.4.2, no active `replace`), `main.go`, `internal/moonbitlang/` (profile, three-file scanner, three starter templates), `Makefile`, `scripts/`, the four release scripts, `docs/{en,fr}/` at 34 pages each, `docs/diagrams/packages.drawio`, `README.md`, and eight test files. | |
| 9 | +- **Decisions**: | |
| 10 | + - **The scanner carries no state.** Established from MoonBit's published lexical grammar rather than assumed: no block comment, no literal that may cross a line, multi-line strings as runs of self-contained `#|`/`$|` lines, attributes explicitly one line. Every other editor in this family threads a carry; this one does not, and a stray quote therefore cannot paint the rest of the file. Rejected: copying Turbo Python's carry structure and leaving the fields unused. | |
| 11 | + - **No table of built-in types.** MoonBit's `uident` rule is lexical, so one line colours `Int`, `StringBuilder` and a type written this morning. Accepted cost: an enum constructor of your own reads as a type. Rejected: a table of the standard library's types, which goes stale the day the library grows. | |
| 12 | + - **The prelude was read out of `moonbitlang/core/prelude`'s generated `.mbti`.** That is how `print` stayed out — MoonBit has never had it, and the compiler said so when the tutorial's first draft used it. | |
| 13 | + - **The toolchain menu is `~M~oonBit`**, put to the user. M is free; both the O and the N of "MoonBit" are taken by Options and Snippets. | |
| 14 | + - **`moon-lsp --stdio`**, with the whole-toolchain installer as the install hint, because moon-lsp does not exist as a separate package. | |
| 15 | + - **Root markers stop at `moon.mod` / `moon.mod.json`**, put to the user. `moon.work` was rejected although `moon` itself looks for it: it only sits above a module, so naming it would make a rare case look like part of the rule. | |
| 16 | + - **Snippet bodies are TOML literal strings**, because MoonBit's `\{…}` is not a valid TOML escape and a basic-string body would make the file the editor had just written unreadable. | |
| 17 | +- **Tests**: 374 tests and subtests. Scanner invariants (one entry per line, spans ordered and non-overlapping, broken input, nothing carried), one case per construct and one per documented refusal, the template contract, the editor assembled on a `SimulationScreen`, the drawio held to `go list`, the languages reference held to the scanner with its keyword row read out of the page, and seven tests driving a real `moon-lsp`. `make check`. | |
| 18 | +- **Falsification**: 50 mutations run across four suites; all caught. Two weak tests were found and strengthened — one that passed with the language list missing from the snippets comment (the file's own slug satisfied the `Contains` check), and one that missed a literal running past its closing quote. | |
| 19 | +- **Quality**: PASS on the first run and again at the end — 0 errors, 0 warnings, 0 smells, total complexity 87, worst file 40 against a limit of 60. | |
| 20 | +- **Docs**: 34 pages × EN + FR. `reference/languages.md`, `explanation/colouring-and-completion.md`, both tools pages, `how-to/enable-completion.md` and the tutorial were written rather than adapted. A new `how-to/install-the-moonbit-toolchain.md` in both languages covers the installer, `MOON_HOME`, upgrading, what each binary is for, and how to check the editor found it. | |
| 21 | +- **Verified in a pty**: the menu bar, `Alt-M`, the create/open pair swapping, every colour claim in the tutorial read back as SGR codes, the About box, `moon fmt` run from the menu, and a file that does not compile showing `×` in the gutter and its message on the status bar. The tutorial's arrow counts were read off the wire rather than counted. | |
| 22 | +- **Two boundaries found and written down rather than worked around**: moon-lsp never diagnoses a `.mbt` file created after it started (turbo-core sends no `didChangeWatchedFiles`; confirmed at the raw protocol level and pinned by a test), and `turbo-classic` draws `syntax.attribute` and `syntax.identifier` identically, so a MoonBit label is invisible as such in that one theme. | |
| 23 | +- **Family**: turbo-core's README, both doc READMEs, `profile/profile.go`, both workspace how-tos and its `.memory/summary.md` now count four editors; its `.go` strings were swept for hardcoded language names and every hit was innocent, so **no library change was needed**. A pre-existing defect was fixed in turbo-python at the same time: its docs claimed `Alt-T` for a menu whose key is `Alt-P`, inherited from Turbo Rust's `Rus~t~` through a mechanical substitution, in eight places across both languages. | |
| 24 | + | |
| 25 | +## 2026-09-09 (later) — three demo projects, and what building them found | |
| 26 | + | |
| 27 | +- **Goal**: `demos/` with two or three MoonBit projects to open in the editor. | |
| 28 | +- **Changes**: `demos/README.md` and three projects — `hello` (struct, enum, match, labelled argument, interpolation), `shapes` (library plus `cmd/main`, traits, generics, `suberror`, five tests), `syntax-tour` (every construct the scanner recognises, in one compiling file). `.gitignore` gained `demos/**/_build/`. The root README, both doc indexes and both `how-to/install.md` link to them. | |
| 29 | +- **What building them found**, none of which the Go tests could have: | |
| 30 | + - **`derive(Show)` is deprecated**; `derive(Debug)`, or a hand-written `impl Show … with fn output`, is what the toolchain points at. The starter snippets file used it. Fixed there, in the README banner, and in the demo. | |
| 31 | + - **The functional `loop (a, b) { (x, y) => … }` form is deprecated**, replaced by `for i = a, j = b { … break … continue … }`. The starter snippets file's `loop` snippet used it. Fixed. | |
| 32 | + - **`typealias` is not accepted at top level** by this compiler, although the published grammar lists it as a keyword. Left in the scanner's keyword table — it is a keyword to the lexer, which is what the scanner models — and simply not used in the demos. | |
| 33 | + - **`print` does not exist** — only `println`. The compiler caught this three separate times while the demos were written, which is the best evidence yet that leaving it out of the builtins table was right. | |
| 34 | + - **`pub struct` is read-only outside its package**; `pub(all)` is what lets another package construct one. | |
| 35 | +- **A scanner boundary was found and made precise.** Opening `tour.mbt` in a pty showed a string nested inside an interpolation being split: `"answer: \{if true { "yes" } else { "no" }}"` colours `yes` and `no` as identifiers. The reference and the explanation had said "one flat run is the honest answer", which is true of the ordinary case and not of this one. Both pages now state the boundary exactly in both languages, `TestAStringInsideAnInterpolationEndsTheOuterLiteral` pins it, and the demo keeps the line with a comment rather than avoiding it. | |
| 36 | +- **Tests**: one added. `make check` passes, and all three demos pass `moon check` with no warnings, are unchanged by `moon fmt`, and run; `shapes` passes its own 5 tests. | |
| 37 | +- **Quality**: PASS, run #4 — 0 errors, 0 warnings, 0 smells, complexity unchanged at 87. qlty does not analyse `.mbt`, so the demos neither help nor hurt the numbers. | |
| 38 | + | |
| 39 | +## 2026-09-09 (later) — the theme list gained three entries | |
| 40 | + | |
| 41 | +- **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. | |
| 42 | +- **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. | |
| 43 | +- **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. | |
| 44 | +- **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. | |
| 45 | + | |
| 46 | +## 2026-09-14 — the family count moved from four to five | |
| 47 | + | |
| 48 | +- **Asked**: nothing of this repository. Turbo Golo was built beside it — adapted from this editor's pages — and `docs/{en,fr}/explanation/architecture.md` said the library's packages are used unchanged by "all four editors". | |
| 49 | +- **Changes**: that one sentence, in both languages — four → five. No code touched; no tests run. | |
| 50 | +- **Also in the working tree, not mine**: `demos/hello/.turbo-moonbit/settings.toml` has the user's own uncommitted change (theme `catppuccin-frappe` → `monochrome-light`). Left alone. | |
| 51 | + | |
| 52 | +## 2026-09-15 — ACP agent windows, ported from turbo-go | |
| 53 | + | |
| 54 | +- **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. | |
| 55 | +- **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. | |
| 56 | +- **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. | |
| 57 | +- **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. | |
| 58 | +- **Quality**: PASS 0/0/0. | |
| 59 | +- **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. | |
| 60 | +- Not committed. | |
| 61 | + | |
| 62 | +## 2026-09-15 (night) — slash commands and `@` mentions, documented | |
| 63 | + | |
| 64 | +- **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. | |
| 65 | +- **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. | |
| 66 | +- **Tests**: `go test ./...` green (the template change is a comment; the tests that read the created file still pass). | |
| 67 | +- **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. | |
| 68 | +- Not committed. | |
| 69 | + | |
| 70 | +## 2026-09-16 — the trace variable and a troubleshooting bullet, documented | |
| 71 | + | |
| 72 | +- 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. | |
| 73 | +- **Later on 2026-09-16**: `demos/hello/.turbo-moonbit/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. | |
| 74 | + | |
| 75 | +## 2026-09-16 — family count: a sixth editor, Turbo JS | |
| 76 | + | |
| 77 | +- **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. | |
| 78 | +- **Changes**: `docs/en/explanation/architecture.md`, `docs/fr/explanation/architecture.md` — "five editors" → six. Nothing else touched; history left as it was. | |
| 79 | +- **Tests**: none affected — documentation only. | |
| 80 | + | |
| 81 | +## 2026-09-17 — documentation: terminal windows and tools on Windows | |
| 82 | + | |
| 83 | +- **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. | |
| 84 | +- **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/moonbit-tools.md` (shell row, cmd.exe's globs and `;`, error row), `docs/*/explanation/moonbit-tools.md` (`cmd.exe /S /C`). Applied by one script across the six editors, one anchor per file. | |
| 85 | +- **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. | |
| 86 | +- **Tests**: none affected — documentation only. | |
| 87 | + | |
| 88 | +## 2026-09-18 — the "Untitled window has no LSP" fix: docs variant added, fix is turbo-core's | |
| 89 | + | |
| 90 | +- **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. | |
| 91 | +- **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. | |
| 92 | +- **Quality**: gate not re-run — a Markdown-only change; the gate measures the Go code. | |
| 93 | +- **Docs ahead of the binary**: the behaviour arrives only when turbo-core is tagged and this editor re-pinned. Not committed. | |
| 94 | + | |
| 95 | +## 2026-09-19 — moved to Rickub: turbo-core v1.0.0 re-pinned, releases published by a workflow | |
| 96 | + | |
| 97 | +- **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. | |
| 98 | +- **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. | |
| 99 | +- **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 MoonBit"`). 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.mbt`) 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. | |
| 100 | +- **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`. | |
| 101 | +- **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. | |
| 102 | + | |
| 103 | +## 2026-09-19 (later) — first run on macOS: two real-server tests failed, the defect was turbo-core's | |
| 104 | + | |
| 105 | +- **Origin**: the user's `./01-release.tag.sh` stopped in `make check`: `TestCompletionEndToEndWithRealMoonLSP` ("No completions here") and `TestDiagnosticsForAFileThatDoesNotCompileWithRealMoonLSP` (nothing in 30 s); the four other `…WithRealMoonLSP` tests passed. First time this suite ran on macOS. | |
| 106 | +- **Cause**: macOS temp dirs are `/var/folders/…`, a link to `/private/var/…`; moon-lsp canonicalises paths, so the file the editor announced belonged to no package (no type-level completion) and its diagnostics came back under `/private/var/…`, which turbo-core keyed by `filepath.Abs` could not match. Reproduced on Linux with `TMPDIR` under a symlink and with an LSP probe; the toolchain and the fixture (`moon.mod` / `moon.pkg`) are fine — `moon 0.1.20260915` accepts them, and warns that the JSON manifests are deprecated. | |
| 107 | +- **Fix**: in turbo-core (`lsp.CanonicalPath`, used by `PathToURI` and `pathKey`), to be released as **v1.0.1**. Nothing changed in this repository's code or tests: through `go.work` against the fixed local core, all six real-server tests pass under a symlinked `TMPDIR`, and the whole suite passes. | |
| 108 | +- **Next**: once turbo-core v1.0.1 is tagged — `go get rickub.com/turbo-editors/turbo-core@v1.0.1 && go mod tidy && GOWORK=off make check`, then `./01-release.tag.sh`. | |
| 109 | + | |
| 110 | +## 2026-09-19 (later still) — the "never diagnosed after start" pin went red on macOS; the fix is turbo-core v1.0.2 | |
| 111 | + | |
| 112 | +- **Origin**: re-pinned to turbo-core v1.0.1, `./01-release.tag.sh` failed in `make check` on `TestAFileCreatedAfterTheServerStartedIsNotDiagnosed`: moon-lsp on the user's Mac diagnoses a file created after it started. On Linux (moon 0.1.20260915) it does not — unless `workspace/didChangeWatchedFiles` names the file, which turbo-core never sent. The documentation the test cited had already moved on (`enable-completion.md`, 2026-09-18) and `languages.md` no longer says anything about it. | |
| 113 | +- **Changes here**: the pin replaced by `TestAFileCreatedInTheEditorIsDiagnosedFromItsFirstSaveWithRealMoonLSP` — `editor.Open` on a file not yet on disk, type the broken fixture, `SetAutosave(true, 10 ms)`, wait for the diagnostic; the one exported way to write a buffer without a dialog. `typeText` sends `KeyEnter` for `\n` (it dropped newlines: traced through a tee wrapper around `moon-lsp`, the saved file was one `///|` line). `os` imported. | |
| 114 | +- **Fix**: turbo-core v1.0.2 (`lsp.Client.FileCreated`, sent by `announceSaved` when the save created the file). Verified through `go.work` against the local core: the new test passes under `/tmp` and under a symlinked `TMPDIR`; **against the published v1.0.1 it fails** — the falsification. | |
| 115 | +- **Next**: when turbo-core v1.0.2 is tagged — `go get rickub.com/turbo-editors/turbo-core@v1.0.2 && go mod tidy && GOWORK=off make check`, then `./01-release.tag.sh`. | |
| new file mode 100644 | |||
| @@ -0,0 +1,115 @@ | |||
| 1 | +# History | ||
| 2 | + | ||
| 3 | +One dated entry per session, appended. Never rewritten. | ||
| 4 | + | ||
| 5 | +## 2026-09-09 — Turbo MoonBit built, from an empty repository to a passing gate | ||
| 6 | + | ||
| 7 | +- **Goal**: a Turbo editor for MoonBit — `/turbo-new-editor` for the language, in this directory, with the MoonBit toolchain's installation documented. | ||
| 8 | +- **Changes**: `go.mod` (turbo-core v0.4.2, no active `replace`), `main.go`, `internal/moonbitlang/` (profile, three-file scanner, three starter templates), `Makefile`, `scripts/`, the four release scripts, `docs/{en,fr}/` at 34 pages each, `docs/diagrams/packages.drawio`, `README.md`, and eight test files. | ||
| 9 | +- **Decisions**: | ||
| 10 | + - **The scanner carries no state.** Established from MoonBit's published lexical grammar rather than assumed: no block comment, no literal that may cross a line, multi-line strings as runs of self-contained `#|`/`$|` lines, attributes explicitly one line. Every other editor in this family threads a carry; this one does not, and a stray quote therefore cannot paint the rest of the file. Rejected: copying Turbo Python's carry structure and leaving the fields unused. | ||
| 11 | + - **No table of built-in types.** MoonBit's `uident` rule is lexical, so one line colours `Int`, `StringBuilder` and a type written this morning. Accepted cost: an enum constructor of your own reads as a type. Rejected: a table of the standard library's types, which goes stale the day the library grows. | ||
| 12 | + - **The prelude was read out of `moonbitlang/core/prelude`'s generated `.mbti`.** That is how `print` stayed out — MoonBit has never had it, and the compiler said so when the tutorial's first draft used it. | ||
| 13 | + - **The toolchain menu is `~M~oonBit`**, put to the user. M is free; both the O and the N of "MoonBit" are taken by Options and Snippets. | ||
| 14 | + - **`moon-lsp --stdio`**, with the whole-toolchain installer as the install hint, because moon-lsp does not exist as a separate package. | ||
| 15 | + - **Root markers stop at `moon.mod` / `moon.mod.json`**, put to the user. `moon.work` was rejected although `moon` itself looks for it: it only sits above a module, so naming it would make a rare case look like part of the rule. | ||
| 16 | + - **Snippet bodies are TOML literal strings**, because MoonBit's `\{…}` is not a valid TOML escape and a basic-string body would make the file the editor had just written unreadable. | ||
| 17 | +- **Tests**: 374 tests and subtests. Scanner invariants (one entry per line, spans ordered and non-overlapping, broken input, nothing carried), one case per construct and one per documented refusal, the template contract, the editor assembled on a `SimulationScreen`, the drawio held to `go list`, the languages reference held to the scanner with its keyword row read out of the page, and seven tests driving a real `moon-lsp`. `make check`. | ||
| 18 | +- **Falsification**: 50 mutations run across four suites; all caught. Two weak tests were found and strengthened — one that passed with the language list missing from the snippets comment (the file's own slug satisfied the `Contains` check), and one that missed a literal running past its closing quote. | ||
| 19 | +- **Quality**: PASS on the first run and again at the end — 0 errors, 0 warnings, 0 smells, total complexity 87, worst file 40 against a limit of 60. | ||
| 20 | +- **Docs**: 34 pages × EN + FR. `reference/languages.md`, `explanation/colouring-and-completion.md`, both tools pages, `how-to/enable-completion.md` and the tutorial were written rather than adapted. A new `how-to/install-the-moonbit-toolchain.md` in both languages covers the installer, `MOON_HOME`, upgrading, what each binary is for, and how to check the editor found it. | ||
| 21 | +- **Verified in a pty**: the menu bar, `Alt-M`, the create/open pair swapping, every colour claim in the tutorial read back as SGR codes, the About box, `moon fmt` run from the menu, and a file that does not compile showing `×` in the gutter and its message on the status bar. The tutorial's arrow counts were read off the wire rather than counted. | ||
| 22 | +- **Two boundaries found and written down rather than worked around**: moon-lsp never diagnoses a `.mbt` file created after it started (turbo-core sends no `didChangeWatchedFiles`; confirmed at the raw protocol level and pinned by a test), and `turbo-classic` draws `syntax.attribute` and `syntax.identifier` identically, so a MoonBit label is invisible as such in that one theme. | ||
| 23 | +- **Family**: turbo-core's README, both doc READMEs, `profile/profile.go`, both workspace how-tos and its `.memory/summary.md` now count four editors; its `.go` strings were swept for hardcoded language names and every hit was innocent, so **no library change was needed**. A pre-existing defect was fixed in turbo-python at the same time: its docs claimed `Alt-T` for a menu whose key is `Alt-P`, inherited from Turbo Rust's `Rus~t~` through a mechanical substitution, in eight places across both languages. | ||
| 24 | + | ||
| 25 | +## 2026-09-09 (later) — three demo projects, and what building them found | ||
| 26 | + | ||
| 27 | +- **Goal**: `demos/` with two or three MoonBit projects to open in the editor. | ||
| 28 | +- **Changes**: `demos/README.md` and three projects — `hello` (struct, enum, match, labelled argument, interpolation), `shapes` (library plus `cmd/main`, traits, generics, `suberror`, five tests), `syntax-tour` (every construct the scanner recognises, in one compiling file). `.gitignore` gained `demos/**/_build/`. The root README, both doc indexes and both `how-to/install.md` link to them. | ||
| 29 | +- **What building them found**, none of which the Go tests could have: | ||
| 30 | + - **`derive(Show)` is deprecated**; `derive(Debug)`, or a hand-written `impl Show … with fn output`, is what the toolchain points at. The starter snippets file used it. Fixed there, in the README banner, and in the demo. | ||
| 31 | + - **The functional `loop (a, b) { (x, y) => … }` form is deprecated**, replaced by `for i = a, j = b { … break … continue … }`. The starter snippets file's `loop` snippet used it. Fixed. | ||
| 32 | + - **`typealias` is not accepted at top level** by this compiler, although the published grammar lists it as a keyword. Left in the scanner's keyword table — it is a keyword to the lexer, which is what the scanner models — and simply not used in the demos. | ||
| 33 | + - **`print` does not exist** — only `println`. The compiler caught this three separate times while the demos were written, which is the best evidence yet that leaving it out of the builtins table was right. | ||
| 34 | + - **`pub struct` is read-only outside its package**; `pub(all)` is what lets another package construct one. | ||
| 35 | +- **A scanner boundary was found and made precise.** Opening `tour.mbt` in a pty showed a string nested inside an interpolation being split: `"answer: \{if true { "yes" } else { "no" }}"` colours `yes` and `no` as identifiers. The reference and the explanation had said "one flat run is the honest answer", which is true of the ordinary case and not of this one. Both pages now state the boundary exactly in both languages, `TestAStringInsideAnInterpolationEndsTheOuterLiteral` pins it, and the demo keeps the line with a comment rather than avoiding it. | ||
| 36 | +- **Tests**: one added. `make check` passes, and all three demos pass `moon check` with no warnings, are unchanged by `moon fmt`, and run; `shapes` passes its own 5 tests. | ||
| 37 | +- **Quality**: PASS, run #4 — 0 errors, 0 warnings, 0 smells, complexity unchanged at 87. qlty does not analyse `.mbt`, so the demos neither help nor hurt the numbers. | ||
| 38 | + | ||
| 39 | +## 2026-09-09 (later) — the theme list gained three entries | ||
| 40 | + | ||
| 41 | +- **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. | ||
| 42 | +- **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. | ||
| 43 | +- **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. | ||
| 44 | +- **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. | ||
| 45 | + | ||
| 46 | +## 2026-09-14 — the family count moved from four to five | ||
| 47 | + | ||
| 48 | +- **Asked**: nothing of this repository. Turbo Golo was built beside it — adapted from this editor's pages — and `docs/{en,fr}/explanation/architecture.md` said the library's packages are used unchanged by "all four editors". | ||
| 49 | +- **Changes**: that one sentence, in both languages — four → five. No code touched; no tests run. | ||
| 50 | +- **Also in the working tree, not mine**: `demos/hello/.turbo-moonbit/settings.toml` has the user's own uncommitted change (theme `catppuccin-frappe` → `monochrome-light`). Left alone. | ||
| 51 | + | ||
| 52 | +## 2026-09-15 — ACP agent windows, ported from turbo-go | ||
| 53 | + | ||
| 54 | +- **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. | ||
| 55 | +- **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. | ||
| 56 | +- **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. | ||
| 57 | +- **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. | ||
| 58 | +- **Quality**: PASS 0/0/0. | ||
| 59 | +- **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. | ||
| 60 | +- Not committed. | ||
| 61 | + | ||
| 62 | +## 2026-09-15 (night) — slash commands and `@` mentions, documented | ||
| 63 | + | ||
| 64 | +- **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. | ||
| 65 | +- **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. | ||
| 66 | +- **Tests**: `go test ./...` green (the template change is a comment; the tests that read the created file still pass). | ||
| 67 | +- **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. | ||
| 68 | +- Not committed. | ||
| 69 | + | ||
| 70 | +## 2026-09-16 — the trace variable and a troubleshooting bullet, documented | ||
| 71 | + | ||
| 72 | +- 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. | ||
| 73 | +- **Later on 2026-09-16**: `demos/hello/.turbo-moonbit/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. | ||
| 74 | + | ||
| 75 | +## 2026-09-16 — family count: a sixth editor, Turbo JS | ||
| 76 | + | ||
| 77 | +- **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. | ||
| 78 | +- **Changes**: `docs/en/explanation/architecture.md`, `docs/fr/explanation/architecture.md` — "five editors" → six. Nothing else touched; history left as it was. | ||
| 79 | +- **Tests**: none affected — documentation only. | ||
| 80 | + | ||
| 81 | +## 2026-09-17 — documentation: terminal windows and tools on Windows | ||
| 82 | + | ||
| 83 | +- **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. | ||
| 84 | +- **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/moonbit-tools.md` (shell row, cmd.exe's globs and `;`, error row), `docs/*/explanation/moonbit-tools.md` (`cmd.exe /S /C`). Applied by one script across the six editors, one anchor per file. | ||
| 85 | +- **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. | ||
| 86 | +- **Tests**: none affected — documentation only. | ||
| 87 | + | ||
| 88 | +## 2026-09-18 — the "Untitled window has no LSP" fix: docs variant added, fix is turbo-core's | ||
| 89 | + | ||
| 90 | +- **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. | ||
| 91 | +- **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. | ||
| 92 | +- **Quality**: gate not re-run — a Markdown-only change; the gate measures the Go code. | ||
| 93 | +- **Docs ahead of the binary**: the behaviour arrives only when turbo-core is tagged and this editor re-pinned. Not committed. | ||
| 94 | + | ||
| 95 | +## 2026-09-19 — moved to Rickub: turbo-core v1.0.0 re-pinned, releases published by a workflow | ||
| 96 | + | ||
| 97 | +- **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. | ||
| 98 | +- **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. | ||
| 99 | +- **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 MoonBit"`). 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.mbt`) 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. | ||
| 100 | +- **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`. | ||
| 101 | +- **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. | ||
| 102 | + | ||
| 103 | +## 2026-09-19 (later) — first run on macOS: two real-server tests failed, the defect was turbo-core's | ||
| 104 | + | ||
| 105 | +- **Origin**: the user's `./01-release.tag.sh` stopped in `make check`: `TestCompletionEndToEndWithRealMoonLSP` ("No completions here") and `TestDiagnosticsForAFileThatDoesNotCompileWithRealMoonLSP` (nothing in 30 s); the four other `…WithRealMoonLSP` tests passed. First time this suite ran on macOS. | ||
| 106 | +- **Cause**: macOS temp dirs are `/var/folders/…`, a link to `/private/var/…`; moon-lsp canonicalises paths, so the file the editor announced belonged to no package (no type-level completion) and its diagnostics came back under `/private/var/…`, which turbo-core keyed by `filepath.Abs` could not match. Reproduced on Linux with `TMPDIR` under a symlink and with an LSP probe; the toolchain and the fixture (`moon.mod` / `moon.pkg`) are fine — `moon 0.1.20260915` accepts them, and warns that the JSON manifests are deprecated. | ||
| 107 | +- **Fix**: in turbo-core (`lsp.CanonicalPath`, used by `PathToURI` and `pathKey`), to be released as **v1.0.1**. Nothing changed in this repository's code or tests: through `go.work` against the fixed local core, all six real-server tests pass under a symlinked `TMPDIR`, and the whole suite passes. | ||
| 108 | +- **Next**: once turbo-core v1.0.1 is tagged — `go get rickub.com/turbo-editors/turbo-core@v1.0.1 && go mod tidy && GOWORK=off make check`, then `./01-release.tag.sh`. | ||
| 109 | + | ||
| 110 | +## 2026-09-19 (later still) — the "never diagnosed after start" pin went red on macOS; the fix is turbo-core v1.0.2 | ||
| 111 | + | ||
| 112 | +- **Origin**: re-pinned to turbo-core v1.0.1, `./01-release.tag.sh` failed in `make check` on `TestAFileCreatedAfterTheServerStartedIsNotDiagnosed`: moon-lsp on the user's Mac diagnoses a file created after it started. On Linux (moon 0.1.20260915) it does not — unless `workspace/didChangeWatchedFiles` names the file, which turbo-core never sent. The documentation the test cited had already moved on (`enable-completion.md`, 2026-09-18) and `languages.md` no longer says anything about it. | ||
| 113 | +- **Changes here**: the pin replaced by `TestAFileCreatedInTheEditorIsDiagnosedFromItsFirstSaveWithRealMoonLSP` — `editor.Open` on a file not yet on disk, type the broken fixture, `SetAutosave(true, 10 ms)`, wait for the diagnostic; the one exported way to write a buffer without a dialog. `typeText` sends `KeyEnter` for `\n` (it dropped newlines: traced through a tee wrapper around `moon-lsp`, the saved file was one `///|` line). `os` imported. | ||
| 114 | +- **Fix**: turbo-core v1.0.2 (`lsp.Client.FileCreated`, sent by `announceSaved` when the save created the file). Verified through `go.work` against the local core: the new test passes under `/tmp` and under a symlinked `TMPDIR`; **against the published v1.0.1 it fails** — the falsification. | ||
| 115 | +- **Next**: when turbo-core v1.0.2 is tagged — `go get rickub.com/turbo-editors/turbo-core@v1.0.2 && go mod tidy && GOWORK=off make check`, then `./01-release.tag.sh`. | ||
added
.memory/summary.md +111 -0 | new file mode 100644 | ||
| @@ -0,0 +1,111 @@ | ||
| 1 | +# turbo-moonbit — 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 MoonBit, written in Go, built on **[turbo-core](https://rickub.com/turbo-editors/turbo-core)** — the library Turbo Go, Turbo Rust and Turbo Python already share. This repository holds the command, the profile that says the editor is for MoonBit, and the MoonBit scanner. Everything else — the event loop, the windows, the dialogs, the themes, the LSP client, the terminal emulator, the project tree, the snippets and tools machinery — is the library's, and none of it is copied here. | |
| 8 | + | |
| 9 | +Module `rickub.com/turbo-editors/turbo-moonbit`, `require`ing turbo-core **v0.4.2** from the module proxy with **no active `replace`**. The commented-out `replace` at the bottom of `go.mod` documents the escape hatch without being one; `01-release.tag.sh` refuses to tag a release whose `go.mod` carries a live one. | |
| 10 | + | |
| 11 | +## Layout | |
| 12 | + | |
| 13 | +| | | | |
| 14 | +| --- | --- | | |
| 15 | +| `main.go` | flags, the terminal, `moonbitlang.Register()`, the profile, the loop | | |
| 16 | +| `internal/moonbitlang/moonbitlang.go` | `Name`, `Slug`, `Language`, `Profile()`, `Register()`, the server directories | | |
| 17 | +| `internal/moonbitlang/scan.go` | the dispatcher, comments, attributes, multi-line string lines, package names, what follows a dot | | |
| 18 | +| `internal/moonbitlang/literals.go` | the five quoted forms — `"…"`, `b"…"`, `re"…"`, `'c'`, `b'c'` | | |
| 19 | +| `internal/moonbitlang/words.go` | numbers, keywords, labels, the identifier-case rule | | |
| 20 | +| `internal/moonbitlang/*.toml.tmpl` | the three starter files, embedded by `templates.go` | | |
| 21 | +| `diagram_test.go` | holds `docs/diagrams/packages.drawio` to `go list` | | |
| 22 | +| `internal/moonbitlang/reference_test.go` | holds `docs/*/reference/languages.md` to the scanner, keyword row included | | |
| 23 | +| `docs/{en,fr}/` | 34 pages each (README included), Diátaxis | | |
| 24 | +| `demos/` | three MoonBit projects to open in the editor: `hello`, `shapes`, `syntax-tour` | | |
| 25 | + | |
| 26 | +## How to build, test and measure | |
| 27 | + | |
| 28 | +```bash | |
| 29 | +make check # fmt, vet, then the whole suite — what a commit should pass | |
| 30 | +make build # into bin/turbo-moonbit, then check the binary reports its version | |
| 31 | +make install # build, install onto PATH, report what it found | |
| 32 | +go test ./... # the moon-lsp tests skip themselves without the toolchain | |
| 33 | +``` | |
| 34 | + | |
| 35 | +Quality gate, separate from the tests: | |
| 36 | + | |
| 37 | +```bash | |
| 38 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | |
| 39 | +``` | |
| 40 | + | |
| 41 | +To build against a turbo-core you have changed but not released: | |
| 42 | + | |
| 43 | +```bash | |
| 44 | +go work init . ../turbo-core | |
| 45 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app # must NOT be under pkg/mod | |
| 46 | +``` | |
| 47 | + | |
| 48 | +`go.work` and `go.work.sum` are gitignored. **Everything still builds and still passes** while testing the published library instead of your changes, so run that second line. | |
| 49 | + | |
| 50 | +## Decisions in force | |
| 51 | + | |
| 52 | +- **The scanner carries no state at all**, and it is the only one in this family that does not. MoonBit has no block comment, no literal that may reach the next line (a newline before a closing quote is an *unterminated literal* error), a multi-line string is a run of self-contained `#|` / `$|` lines, and an attribute is explicitly one line. The `carry` type is empty and named rather than `struct{}` inline, so the reasoning has somewhere to live and a future construct that crosses lines has somewhere to go. | |
| 53 | +- **The scanner was written against the published lexical grammar**, not against examples. `docs.moonbitlang.com/en/latest/language/lexical-conventions.html` gives every literal production, the keyword list, and the sentence that decides `1..=2`. Where the scanner departs from it, the departure is named in `reference/languages.md`. | |
| 54 | +- **There is no table of built-in types, and there does not need to be.** A `uident` "begins with an ASCII uppercase letter" is a *lexical* rule, so every capitalised name is a type by the same line of code. The cost is that an enum constructor of your own is coloured as a type; nothing in the syntax separates `Circle(1.0)` from a type applied to arguments. | |
| 55 | +- **The prelude table was read out of `moonbitlang/core/prelude`'s generated `.mbti`**, not remembered. That is how `print` stayed out of it: MoonBit has `println` and has never had `print`, and the compiler confirmed it during the tutorial's first draft. | |
| 56 | +- **A number's dot is only part of it when a second dot does not follow.** Without that, `1..=2` reads as the double `1.` and `.=2`, and every range in every file is miscoloured. Suffixes are upper case or they are not suffixes. | |
| 57 | +- **A name after a dot is looked up without the keyword table**, because dot-identifiers "use the identifier case rules without consulting the keyword table, so `.if` is valid". | |
| 58 | +- **A labelled argument's `name~` is `ClassAttribute`, tilde included.** The tilde appears in no MoonBit operator, so it can only be a label — except after a capital or a keyword, which the grammar excludes. | |
| 59 | +- **An attribute takes the whole line**, because the grammar hands it everything through the next newline. | |
| 60 | +- **`package` is coloured as a keyword in `.mbt` too**, although it is only reserved there. It is a real keyword in the `.mbti` files this editor also colours, and in a `.mbt` the colour says what the compiler is about to. | |
| 61 | +- **The toolchain menu is `~M~oonBit`, not `moon`.** M is free — the fixed menus take F, E, S, R, C, O, W, N and H, which rules out both the O and the N of MoonBit. Named after the language because the menu holds whatever the project put in its tools file. | |
| 62 | +- **The language server is `moon-lsp --stdio`**, and the install hint installs the whole toolchain: `curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash`. The `--stdio` is not optional — with no argument moon-lsp prints its usage and exits, which the editor would see as a server that died at once. | |
| 63 | +- **moon-lsp answers seven of turbo-core's nine questions.** It advertises neither `typeDefinition` nor `implementation`, so those two items report nothing found. It *does* answer `workspace/symbol`, which Turbo Python's server does not. A test asserts both halves. | |
| 64 | +- **Two directories are searched for the server besides `PATH`**: `$MOON_HOME/bin` and `~/.moon/bin`. The MoonBit installer's last act is to append its bin directory to one shell profile, which does nothing for an editor started from a shell that was already open. | |
| 65 | +- **Root markers, in order: `moon.mod`, `moon.mod.json`.** `moon.work` is deliberately absent although `moon` itself looks for it: a workspace manifest only ever sits *above* a `moon.mod`, so naming it would make a rare case look like part of the rule. | |
| 66 | +- **`Profile()` is a function, not a variable**, because `Server.Dirs` reads the environment and a variable would freeze whatever `MOON_HOME` said at link time. | |
| 67 | +- **Snippet bodies are TOML *literal* multi-line strings** — three apostrophes, not three double quotes. MoonBit interpolates with `\{…}`, and a backslash before a brace is not one of TOML's escapes, so a body in basic strings would not parse and the file the editor had just offered to create would be refused when read back. | |
| 68 | +- **Snippet bodies are indented two spaces**, which is what `moon fmt` writes. A snippet that disagrees with the formatter turns one insertion into a whole-file diff. | |
| 69 | +- **Nine tools in the starter file**, `moon check` first because it answers "is this sound?" without producing anything. Three ask for a value and one names a menu of its own — both features are invisible otherwise. | |
| 70 | +- **`autosave = true` in the starter settings file, `false` in `settings.Default()`.** Two statements in two places on purpose. | |
| 71 | +- **The starter templates are embedded files, not Go constants**, with the `.tmpl` suffix because `settings.toml.tmpl` holds `theme = %q`, which is not valid TOML. | |
| 72 | +- **The three demo projects must build, run and survive `moon fmt` unchanged.** They are the only MoonBit in this repository that a compiler ever sees, and they are what caught three things the scanner alone could not: `derive(Show)` is deprecated in favour of `derive(Debug)`, the functional `loop (a, b) { … }` form is deprecated in favour of `for i = a, j = b { … }`, and `typealias` is not accepted at top level by this compiler although it is in the grammar's keyword list. The first two were in the starter snippets file and are now fixed. | |
| 73 | +- **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 MoonBit's contribution to the feature. The example agent is `docker agent serve acp .turbo-moonbit/agent.yaml`; the only other thing about this editor in it is the sentence saying a ```moonbit 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`. | |
| 74 | +- **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. | |
| 75 | + | |
| 76 | +## State as of 2026-09-09 | |
| 77 | + | |
| 78 | +- **Complete and green.** `make check` passes; `gofmt -l` and `go vet` are clean. 374 tests and subtests. | |
| 79 | +- **Quality gate: PASS**, twice. 0 errors, 0 warnings, 0 smells; total complexity 87, worst file 40 against a limit of 60. | |
| 80 | +- **Documentation**: 34 files × EN + FR, a `README.md` at the root, and `docs/diagrams/packages.drawio` checked against `go list` by `diagram_test.go`. | |
| 81 | +- **Every test was falsified.** 21 mutations of the scanner and profile, 16 of the templates, 5 of the language-server tests, 8 of the diagram/installer/Makefile checks — all caught. Two genuinely weak tests were found this way and strengthened: one that would have passed with the language list missing from the snippets comment, and one that missed a literal running past its closing quote. | |
| 82 | +- **Verified in a real pty**, not only by tests: the bar reading ` File Edit Search Run Code Options Window Snippets MoonBit Help`; `Alt-M` opening the MoonBit menu with `Create tools file` available (`30;42`) and `Open tools file` greyed (`90;47`), then the two swapping once the file exists; keywords `97;44;1`, types `96;44`, functions `93;44;1`, builtins `96;44;1`, strings `92;44`, numbers `95;44`, comments `38;2;143;143;143`; a string span covering its `\{…}` interpolations whole; the About box reading **"A Turbo C-style editor for MoonBit, / written in Go."**; `moon fmt` run from the menu adding a trailing comma and the editor reloading the file; and — the one that matters — **a file that does not compile, opened by a relative path, showing `×` in the gutter (`91;44;1`) and `⚠ The value identifier undefined_name is unbound.` on the status bar**. | |
| 83 | +- **The arrow counts in the tutorial were read off a pty**, not counted by hand: five `→` from File reaches Options, eight reaches MoonBit. | |
| 84 | +- **The server is found outside `PATH`** — `scripts/install.sh` located it at `~/.moon/bin/moon-lsp` and the profile searches the same places. | |
| 85 | +- **The editor is registered in the family.** turbo-core's `README.md`, both doc `README`s, `profile/profile.go`'s package comment, both workspace how-tos and `.memory/summary.md` now count four editors. turbo-core's `.go` strings were swept for hardcoded language names; **every hit was a false positive, a doc-comment example of the seam, or the true statement that these editors are written in Go.** No library change was needed. | |
| 86 | + | |
| 87 | +## Known boundaries | |
| 88 | + | |
| 89 | +- **A `.mbt` created in the editor is diagnosed from its first save — with turbo-core ≥ v1.0.2.** moon-lsp lists a package's files from the directory, so a document it was told is open but never told *exists* was never diagnosed; turbo-core now sends `workspace/didChangeWatchedFiles` when a save creates the file. Until 2026-09-19 this was pinned as a limit (`TestAFileCreatedAfterTheServerStartedIsNotDiagnosed`); that test went red on macOS, where moon-lsp notices new files by itself, and is now `TestAFileCreatedInTheEditorIsDiagnosedFromItsFirstSaveWithRealMoonLSP` — which fails against turbo-core v1.0.1 and passes from v1.0.2. `enable-completion.md` had promised this since 2026-09-18. The test helper `typeText` now sends Enter for a newline; typed as a rune, `\n` was dropped and a four-line fixture became one `///|` comment line. | |
| 90 | +- **In `turbo-classic` alone, `syntax.attribute` and `syntax.identifier` are both plain yellow**, so a MoonBit attribute or label is not told apart from an ordinary name in that one theme. The other seven distinguish them. It is a turbo-core theme matter that hits Turbo Rust's `#[derive]` equally, so it was not fixed from here. | |
| 91 | +- **A non-ASCII identifier is left uncoloured.** MoonBit allows CJK and other Unicode ranges in a name; turbo-core's rune predicates are ASCII. | |
| 92 | +- **A string nested inside an interpolation ends the outer literal.** `"a \{b} c"` is one span, but `"a \{f("x")} c"` scans as string, then `x` as an identifier, then string, because the first unescaped quote is taken as the closer. The grammar says nested literals do not count, so a correct implementation needs the parser. The spans stay ordered and non-overlapping, so nothing downstream misbehaves. Pinned by `TestAStringInsideAnInterpolationEndsTheOuterLiteral`, and `demos/syntax-tour/tour.mbt` carries a labelled line that shows it. | |
| 93 | + | |
| 94 | +## Not yet established | |
| 95 | + | |
| 96 | +- **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-moonbit`, pressed `Alt-A` and talked to an agent from it. | |
| 97 | + | |
| 98 | + | |
| 99 | +- **Run on macOS once (2026-09-19), by the user's `make check`, and it found a turbo-core defect**: symlinked temp dirs (`/var` → `/private/var`) made moon-lsp treat the fixture as a file of no package. Fixed in turbo-core v1.0.1; this editor must re-pin before releasing. Never run on Windows. | |
| 100 | +- **No CI.** There is no pipeline configuration in the repository. | |
| 101 | +- **Never released.** No tag exists; `01`–`04` have only ever been read here, never run. | |
| 102 | +- **Performance on a large file is unmeasured.** The scanner is a line at a time and carries nothing, but nothing has been timed. | |
| 103 | +- **`.mbtx` scripts are claimed but untested against a real one.** The extension is registered and coloured; no `.mbtx` file has been opened in the editor. | |
| 104 | +- **Nothing checks the demos automatically.** They were built, run and formatted by hand; no test or CI step re-runs `moon check` over them, so a future MoonBit release could deprecate something in them without anything noticing. | |
| 105 | +- **`moon.work` workspaces are untested.** The root markers deliberately stop at the module, and no multi-module project has been opened. | |
| 106 | + | |
| 107 | +## State as of 2026-09-19 — moved to Rickub, released by a workflow | |
| 108 | + | |
| 109 | +- **Module path `rickub.com/turbo-editors/turbo-moonbit`**, 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-moonbit.git` and **no commit yet**; `01-release.tag.sh` makes the first one. | |
| 110 | +- **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_MOONBIT_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_MOONBIT_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-moonbit-*`, `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-moonbit.token.env` is read by nothing. | |
| 111 | +- **`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_MOONBIT_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,111 @@ | |||
| 1 | +# turbo-moonbit — 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 MoonBit, written in Go, built on **[turbo-core](https://rickub.com/turbo-editors/turbo-core)** — the library Turbo Go, Turbo Rust and Turbo Python already share. This repository holds the command, the profile that says the editor is for MoonBit, and the MoonBit scanner. Everything else — the event loop, the windows, the dialogs, the themes, the LSP client, the terminal emulator, the project tree, the snippets and tools machinery — is the library's, and none of it is copied here. | ||
| 8 | + | ||
| 9 | +Module `rickub.com/turbo-editors/turbo-moonbit`, `require`ing turbo-core **v0.4.2** from the module proxy with **no active `replace`**. The commented-out `replace` at the bottom of `go.mod` documents the escape hatch without being one; `01-release.tag.sh` refuses to tag a release whose `go.mod` carries a live one. | ||
| 10 | + | ||
| 11 | +## Layout | ||
| 12 | + | ||
| 13 | +| | | | ||
| 14 | +| --- | --- | | ||
| 15 | +| `main.go` | flags, the terminal, `moonbitlang.Register()`, the profile, the loop | | ||
| 16 | +| `internal/moonbitlang/moonbitlang.go` | `Name`, `Slug`, `Language`, `Profile()`, `Register()`, the server directories | | ||
| 17 | +| `internal/moonbitlang/scan.go` | the dispatcher, comments, attributes, multi-line string lines, package names, what follows a dot | | ||
| 18 | +| `internal/moonbitlang/literals.go` | the five quoted forms — `"…"`, `b"…"`, `re"…"`, `'c'`, `b'c'` | | ||
| 19 | +| `internal/moonbitlang/words.go` | numbers, keywords, labels, the identifier-case rule | | ||
| 20 | +| `internal/moonbitlang/*.toml.tmpl` | the three starter files, embedded by `templates.go` | | ||
| 21 | +| `diagram_test.go` | holds `docs/diagrams/packages.drawio` to `go list` | | ||
| 22 | +| `internal/moonbitlang/reference_test.go` | holds `docs/*/reference/languages.md` to the scanner, keyword row included | | ||
| 23 | +| `docs/{en,fr}/` | 34 pages each (README included), Diátaxis | | ||
| 24 | +| `demos/` | three MoonBit projects to open in the editor: `hello`, `shapes`, `syntax-tour` | | ||
| 25 | + | ||
| 26 | +## How to build, test and measure | ||
| 27 | + | ||
| 28 | +```bash | ||
| 29 | +make check # fmt, vet, then the whole suite — what a commit should pass | ||
| 30 | +make build # into bin/turbo-moonbit, then check the binary reports its version | ||
| 31 | +make install # build, install onto PATH, report what it found | ||
| 32 | +go test ./... # the moon-lsp tests skip themselves without the toolchain | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +Quality gate, separate from the tests: | ||
| 36 | + | ||
| 37 | +```bash | ||
| 38 | +python3 ~/.claude/skills/quality/scripts/quality_report.py --workspace . | ||
| 39 | +``` | ||
| 40 | + | ||
| 41 | +To build against a turbo-core you have changed but not released: | ||
| 42 | + | ||
| 43 | +```bash | ||
| 44 | +go work init . ../turbo-core | ||
| 45 | +go list -f '{{.Dir}}' rickub.com/turbo-editors/turbo-core/app # must NOT be under pkg/mod | ||
| 46 | +``` | ||
| 47 | + | ||
| 48 | +`go.work` and `go.work.sum` are gitignored. **Everything still builds and still passes** while testing the published library instead of your changes, so run that second line. | ||
| 49 | + | ||
| 50 | +## Decisions in force | ||
| 51 | + | ||
| 52 | +- **The scanner carries no state at all**, and it is the only one in this family that does not. MoonBit has no block comment, no literal that may reach the next line (a newline before a closing quote is an *unterminated literal* error), a multi-line string is a run of self-contained `#|` / `$|` lines, and an attribute is explicitly one line. The `carry` type is empty and named rather than `struct{}` inline, so the reasoning has somewhere to live and a future construct that crosses lines has somewhere to go. | ||
| 53 | +- **The scanner was written against the published lexical grammar**, not against examples. `docs.moonbitlang.com/en/latest/language/lexical-conventions.html` gives every literal production, the keyword list, and the sentence that decides `1..=2`. Where the scanner departs from it, the departure is named in `reference/languages.md`. | ||
| 54 | +- **There is no table of built-in types, and there does not need to be.** A `uident` "begins with an ASCII uppercase letter" is a *lexical* rule, so every capitalised name is a type by the same line of code. The cost is that an enum constructor of your own is coloured as a type; nothing in the syntax separates `Circle(1.0)` from a type applied to arguments. | ||
| 55 | +- **The prelude table was read out of `moonbitlang/core/prelude`'s generated `.mbti`**, not remembered. That is how `print` stayed out of it: MoonBit has `println` and has never had `print`, and the compiler confirmed it during the tutorial's first draft. | ||
| 56 | +- **A number's dot is only part of it when a second dot does not follow.** Without that, `1..=2` reads as the double `1.` and `.=2`, and every range in every file is miscoloured. Suffixes are upper case or they are not suffixes. | ||
| 57 | +- **A name after a dot is looked up without the keyword table**, because dot-identifiers "use the identifier case rules without consulting the keyword table, so `.if` is valid". | ||
| 58 | +- **A labelled argument's `name~` is `ClassAttribute`, tilde included.** The tilde appears in no MoonBit operator, so it can only be a label — except after a capital or a keyword, which the grammar excludes. | ||
| 59 | +- **An attribute takes the whole line**, because the grammar hands it everything through the next newline. | ||
| 60 | +- **`package` is coloured as a keyword in `.mbt` too**, although it is only reserved there. It is a real keyword in the `.mbti` files this editor also colours, and in a `.mbt` the colour says what the compiler is about to. | ||
| 61 | +- **The toolchain menu is `~M~oonBit`, not `moon`.** M is free — the fixed menus take F, E, S, R, C, O, W, N and H, which rules out both the O and the N of MoonBit. Named after the language because the menu holds whatever the project put in its tools file. | ||
| 62 | +- **The language server is `moon-lsp --stdio`**, and the install hint installs the whole toolchain: `curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash`. The `--stdio` is not optional — with no argument moon-lsp prints its usage and exits, which the editor would see as a server that died at once. | ||
| 63 | +- **moon-lsp answers seven of turbo-core's nine questions.** It advertises neither `typeDefinition` nor `implementation`, so those two items report nothing found. It *does* answer `workspace/symbol`, which Turbo Python's server does not. A test asserts both halves. | ||
| 64 | +- **Two directories are searched for the server besides `PATH`**: `$MOON_HOME/bin` and `~/.moon/bin`. The MoonBit installer's last act is to append its bin directory to one shell profile, which does nothing for an editor started from a shell that was already open. | ||
| 65 | +- **Root markers, in order: `moon.mod`, `moon.mod.json`.** `moon.work` is deliberately absent although `moon` itself looks for it: a workspace manifest only ever sits *above* a `moon.mod`, so naming it would make a rare case look like part of the rule. | ||
| 66 | +- **`Profile()` is a function, not a variable**, because `Server.Dirs` reads the environment and a variable would freeze whatever `MOON_HOME` said at link time. | ||
| 67 | +- **Snippet bodies are TOML *literal* multi-line strings** — three apostrophes, not three double quotes. MoonBit interpolates with `\{…}`, and a backslash before a brace is not one of TOML's escapes, so a body in basic strings would not parse and the file the editor had just offered to create would be refused when read back. | ||
| 68 | +- **Snippet bodies are indented two spaces**, which is what `moon fmt` writes. A snippet that disagrees with the formatter turns one insertion into a whole-file diff. | ||
| 69 | +- **Nine tools in the starter file**, `moon check` first because it answers "is this sound?" without producing anything. Three ask for a value and one names a menu of its own — both features are invisible otherwise. | ||
| 70 | +- **`autosave = true` in the starter settings file, `false` in `settings.Default()`.** Two statements in two places on purpose. | ||
| 71 | +- **The starter templates are embedded files, not Go constants**, with the `.tmpl` suffix because `settings.toml.tmpl` holds `theme = %q`, which is not valid TOML. | ||
| 72 | +- **The three demo projects must build, run and survive `moon fmt` unchanged.** They are the only MoonBit in this repository that a compiler ever sees, and they are what caught three things the scanner alone could not: `derive(Show)` is deprecated in favour of `derive(Debug)`, the functional `loop (a, b) { … }` form is deprecated in favour of `for i = a, j = b { … }`, and `typealias` is not accepted at top level by this compiler although it is in the grammar's keyword list. The first two were in the starter snippets file and are now fixed. | ||
| 73 | +- **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 MoonBit's contribution to the feature. The example agent is `docker agent serve acp .turbo-moonbit/agent.yaml`; the only other thing about this editor in it is the sentence saying a ```moonbit 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`. | ||
| 74 | +- **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. | ||
| 75 | + | ||
| 76 | +## State as of 2026-09-09 | ||
| 77 | + | ||
| 78 | +- **Complete and green.** `make check` passes; `gofmt -l` and `go vet` are clean. 374 tests and subtests. | ||
| 79 | +- **Quality gate: PASS**, twice. 0 errors, 0 warnings, 0 smells; total complexity 87, worst file 40 against a limit of 60. | ||
| 80 | +- **Documentation**: 34 files × EN + FR, a `README.md` at the root, and `docs/diagrams/packages.drawio` checked against `go list` by `diagram_test.go`. | ||
| 81 | +- **Every test was falsified.** 21 mutations of the scanner and profile, 16 of the templates, 5 of the language-server tests, 8 of the diagram/installer/Makefile checks — all caught. Two genuinely weak tests were found this way and strengthened: one that would have passed with the language list missing from the snippets comment, and one that missed a literal running past its closing quote. | ||
| 82 | +- **Verified in a real pty**, not only by tests: the bar reading ` File Edit Search Run Code Options Window Snippets MoonBit Help`; `Alt-M` opening the MoonBit menu with `Create tools file` available (`30;42`) and `Open tools file` greyed (`90;47`), then the two swapping once the file exists; keywords `97;44;1`, types `96;44`, functions `93;44;1`, builtins `96;44;1`, strings `92;44`, numbers `95;44`, comments `38;2;143;143;143`; a string span covering its `\{…}` interpolations whole; the About box reading **"A Turbo C-style editor for MoonBit, / written in Go."**; `moon fmt` run from the menu adding a trailing comma and the editor reloading the file; and — the one that matters — **a file that does not compile, opened by a relative path, showing `×` in the gutter (`91;44;1`) and `⚠ The value identifier undefined_name is unbound.` on the status bar**. | ||
| 83 | +- **The arrow counts in the tutorial were read off a pty**, not counted by hand: five `→` from File reaches Options, eight reaches MoonBit. | ||
| 84 | +- **The server is found outside `PATH`** — `scripts/install.sh` located it at `~/.moon/bin/moon-lsp` and the profile searches the same places. | ||
| 85 | +- **The editor is registered in the family.** turbo-core's `README.md`, both doc `README`s, `profile/profile.go`'s package comment, both workspace how-tos and `.memory/summary.md` now count four editors. turbo-core's `.go` strings were swept for hardcoded language names; **every hit was a false positive, a doc-comment example of the seam, or the true statement that these editors are written in Go.** No library change was needed. | ||
| 86 | + | ||
| 87 | +## Known boundaries | ||
| 88 | + | ||
| 89 | +- **A `.mbt` created in the editor is diagnosed from its first save — with turbo-core ≥ v1.0.2.** moon-lsp lists a package's files from the directory, so a document it was told is open but never told *exists* was never diagnosed; turbo-core now sends `workspace/didChangeWatchedFiles` when a save creates the file. Until 2026-09-19 this was pinned as a limit (`TestAFileCreatedAfterTheServerStartedIsNotDiagnosed`); that test went red on macOS, where moon-lsp notices new files by itself, and is now `TestAFileCreatedInTheEditorIsDiagnosedFromItsFirstSaveWithRealMoonLSP` — which fails against turbo-core v1.0.1 and passes from v1.0.2. `enable-completion.md` had promised this since 2026-09-18. The test helper `typeText` now sends Enter for a newline; typed as a rune, `\n` was dropped and a four-line fixture became one `///|` comment line. | ||
| 90 | +- **In `turbo-classic` alone, `syntax.attribute` and `syntax.identifier` are both plain yellow**, so a MoonBit attribute or label is not told apart from an ordinary name in that one theme. The other seven distinguish them. It is a turbo-core theme matter that hits Turbo Rust's `#[derive]` equally, so it was not fixed from here. | ||
| 91 | +- **A non-ASCII identifier is left uncoloured.** MoonBit allows CJK and other Unicode ranges in a name; turbo-core's rune predicates are ASCII. | ||
| 92 | +- **A string nested inside an interpolation ends the outer literal.** `"a \{b} c"` is one span, but `"a \{f("x")} c"` scans as string, then `x` as an identifier, then string, because the first unescaped quote is taken as the closer. The grammar says nested literals do not count, so a correct implementation needs the parser. The spans stay ordered and non-overlapping, so nothing downstream misbehaves. Pinned by `TestAStringInsideAnInterpolationEndsTheOuterLiteral`, and `demos/syntax-tour/tour.mbt` carries a labelled line that shows it. | ||
| 93 | + | ||
| 94 | +## Not yet established | ||
| 95 | + | ||
| 96 | +- **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-moonbit`, pressed `Alt-A` and talked to an agent from it. | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +- **Run on macOS once (2026-09-19), by the user's `make check`, and it found a turbo-core defect**: symlinked temp dirs (`/var` → `/private/var`) made moon-lsp treat the fixture as a file of no package. Fixed in turbo-core v1.0.1; this editor must re-pin before releasing. Never run on Windows. | ||
| 100 | +- **No CI.** There is no pipeline configuration in the repository. | ||
| 101 | +- **Never released.** No tag exists; `01`–`04` have only ever been read here, never run. | ||
| 102 | +- **Performance on a large file is unmeasured.** The scanner is a line at a time and carries nothing, but nothing has been timed. | ||
| 103 | +- **`.mbtx` scripts are claimed but untested against a real one.** The extension is registered and coloured; no `.mbtx` file has been opened in the editor. | ||
| 104 | +- **Nothing checks the demos automatically.** They were built, run and formatted by hand; no test or CI step re-runs `moon check` over them, so a future MoonBit release could deprecate something in them without anything noticing. | ||
| 105 | +- **`moon.work` workspaces are untested.** The root markers deliberately stop at the module, and no multi-module project has been opened. | ||
| 106 | + | ||
| 107 | +## State as of 2026-09-19 — moved to Rickub, released by a workflow | ||
| 108 | + | ||
| 109 | +- **Module path `rickub.com/turbo-editors/turbo-moonbit`**, 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-moonbit.git` and **no commit yet**; `01-release.tag.sh` makes the first one. | ||
| 110 | +- **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_MOONBIT_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_MOONBIT_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-moonbit-*`, `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-moonbit.token.env` is read by nothing. | ||
| 111 | +- **`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_MOONBIT_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 +5 -0 | new file mode 100644 | ||
| @@ -0,0 +1,5 @@ | ||
| 1 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 1, "smells": 0, "timestamp": "2026-09-09T06:21:17Z"} | |
| 2 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 2, "smells": 0, "timestamp": "2026-09-09T06:36:30Z"} | |
| 3 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 3, "smells": 0, "timestamp": "2026-09-09T06:41:29Z"} | |
| 4 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 4, "smells": 0, "timestamp": "2026-09-09T11:50:28Z"} | |
| 5 | +{"branch": "feature/acp", "breaches": [], "commit": "3b4d297", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1143, "loc": 541}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 5, "smells": 0, "timestamp": "2026-09-15T16:54:08Z"} | |
| new file mode 100644 | |||
| @@ -0,0 +1,5 @@ | |||
| 1 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 1, "smells": 0, "timestamp": "2026-09-09T06:21:17Z"} | ||
| 2 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 2, "smells": 0, "timestamp": "2026-09-09T06:36:30Z"} | ||
| 3 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 3, "smells": 0, "timestamp": "2026-09-09T06:41:29Z"} | ||
| 4 | +{"branch": "main", "breaches": [], "commit": "a1558e2", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1133, "loc": 539}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 4, "smells": 0, "timestamp": "2026-09-09T11:50:28Z"} | ||
| 5 | +{"branch": "feature/acp", "breaches": [], "commit": "3b4d297", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 2, "complex": 87, "cyclo": 181, "fields": 7, "funcs": 52, "lcom": 0, "lines": 1143, "loc": 541}, "qlty_version": "qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23)", "run": 5, "smells": 0, "timestamp": "2026-09-15T16:54:08Z"} | ||
added
.quality/report-20260909T062117Z.md +54 -0 | new file mode 100644 | ||
| @@ -0,0 +1,54 @@ | ||
| 1 | +# Quality report — 2026-09-09T06:21:17Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `a1558e2` on `main` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #1 (first recorded run) | |
| 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: —) | |
| 23 | + | |
| 24 | +_none_ | |
| 25 | + | |
| 26 | +## Metrics (`qlty metrics`) | |
| 27 | + | |
| 28 | +| metric | total | vs previous | | |
| 29 | +|---|---|---| | |
| 30 | +| funcs | 52 | — | | |
| 31 | +| classes | 2 | — | | |
| 32 | +| fields | 7 | — | | |
| 33 | +| cyclo | 181 | — | | |
| 34 | +| complex | 87 | — | | |
| 35 | +| lcom | 0 | — | | |
| 36 | +| lines | 1133 | — | | |
| 37 | +| loc | 539 | — | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | |
| 44 | +| main.go | 16 | 32 | 132 | | |
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | |
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | |
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | |
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,54 @@ | |||
| 1 | +# Quality report — 2026-09-09T06:21:17Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `a1558e2` on `main` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #1 (first recorded run) | ||
| 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: —) | ||
| 23 | + | ||
| 24 | +_none_ | ||
| 25 | + | ||
| 26 | +## Metrics (`qlty metrics`) | ||
| 27 | + | ||
| 28 | +| metric | total | vs previous | | ||
| 29 | +|---|---|---| | ||
| 30 | +| funcs | 52 | — | | ||
| 31 | +| classes | 2 | — | | ||
| 32 | +| fields | 7 | — | | ||
| 33 | +| cyclo | 181 | — | | ||
| 34 | +| complex | 87 | — | | ||
| 35 | +| lcom | 0 | — | | ||
| 36 | +| lines | 1133 | — | | ||
| 37 | +| loc | 539 | — | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | ||
| 44 | +| main.go | 16 | 32 | 132 | | ||
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | ||
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | ||
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | ||
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | ||
added
.quality/report-20260909T063630Z.md +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +# Quality report — 2026-09-09T06:36:30Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `a1558e2` on `main` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #2 (previous: 2026-09-09T06:21:17Z) | |
| 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 | 52 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 7 | ±0 | | |
| 33 | +| cyclo | 181 | ±0 | | |
| 34 | +| complex | 87 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1133 | ±0 | | |
| 37 | +| loc | 539 | ±0 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | |
| 44 | +| main.go | 16 | 32 | 132 | | |
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | |
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | |
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | |
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | |
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +# Quality report — 2026-09-09T06:36:30Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `a1558e2` on `main` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #2 (previous: 2026-09-09T06:21:17Z) | ||
| 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 | 52 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 7 | ±0 | | ||
| 33 | +| cyclo | 181 | ±0 | | ||
| 34 | +| complex | 87 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1133 | ±0 | | ||
| 37 | +| loc | 539 | ±0 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | ||
| 44 | +| main.go | 16 | 32 | 132 | | ||
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | ||
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | ||
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | ||
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | ||
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | ||
added
.quality/report-20260909T064129Z.md +56 -0 | new file mode 100644 | ||
| @@ -0,0 +1,56 @@ | ||
| 1 | +# Quality report — 2026-09-09T06:41:29Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `a1558e2` on `main` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #3 (previous: 2026-09-09T06:36:30Z) | |
| 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 | 52 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 7 | ±0 | | |
| 33 | +| cyclo | 181 | ±0 | | |
| 34 | +| complex | 87 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1133 | ±0 | | |
| 37 | +| loc | 539 | ±0 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | |
| 44 | +| main.go | 16 | 32 | 132 | | |
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | |
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | |
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | |
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | |
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | |
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,56 @@ | |||
| 1 | +# Quality report — 2026-09-09T06:41:29Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `a1558e2` on `main` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #3 (previous: 2026-09-09T06:36:30Z) | ||
| 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 | 52 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 7 | ±0 | | ||
| 33 | +| cyclo | 181 | ±0 | | ||
| 34 | +| complex | 87 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1133 | ±0 | | ||
| 37 | +| loc | 539 | ±0 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | ||
| 44 | +| main.go | 16 | 32 | 132 | | ||
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | ||
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | ||
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | ||
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | ||
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | ||
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | ||
added
.quality/report-20260909T115028Z.md +57 -0 | new file mode 100644 | ||
| @@ -0,0 +1,57 @@ | ||
| 1 | +# Quality report — 2026-09-09T11:50:28Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `a1558e2` on `main` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #4 (previous: 2026-09-09T06:41:29Z) | |
| 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 | 52 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 7 | ±0 | | |
| 33 | +| cyclo | 181 | ±0 | | |
| 34 | +| complex | 87 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1133 | ±0 | | |
| 37 | +| loc | 539 | ±0 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | |
| 44 | +| main.go | 16 | 32 | 132 | | |
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | |
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | |
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | |
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | |
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | |
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | |
| 57 | +| 4 | 2026-09-09T11:50:28Z | 0 | 0 | 0 | 87 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,57 @@ | |||
| 1 | +# Quality report — 2026-09-09T11:50:28Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `a1558e2` on `main` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #4 (previous: 2026-09-09T06:41:29Z) | ||
| 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 | 52 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 7 | ±0 | | ||
| 33 | +| cyclo | 181 | ±0 | | ||
| 34 | +| complex | 87 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1133 | ±0 | | ||
| 37 | +| loc | 539 | ±0 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | ||
| 44 | +| main.go | 16 | 32 | 132 | | ||
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | ||
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | ||
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 65 | | ||
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 5 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | ||
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | ||
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | ||
| 57 | +| 4 | 2026-09-09T11:50:28Z | 0 | 0 | 0 | 87 | PASS | | ||
added
.quality/report-20260915T165408Z.md +58 -0 | new file mode 100644 | ||
| @@ -0,0 +1,58 @@ | ||
| 1 | +# Quality report — 2026-09-15T16:54:08Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `3b4d297` on `feature/acp` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #5 (previous: 2026-09-09T11:50:28Z) | |
| 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 | 52 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 7 | ±0 | | |
| 33 | +| cyclo | 181 | ±0 | | |
| 34 | +| complex | 87 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1143 | +10 | | |
| 37 | +| loc | 541 | +2 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | |
| 44 | +| main.go | 16 | 32 | 132 | | |
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | |
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | |
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 66 | | |
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 6 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | |
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | |
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | |
| 57 | +| 4 | 2026-09-09T11:50:28Z | 0 | 0 | 0 | 87 | PASS | | |
| 58 | +| 5 | 2026-09-15T16:54:08Z | 0 | 0 | 0 | 87 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | +# Quality report — 2026-09-15T16:54:08Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `3b4d297` on `feature/acp` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #5 (previous: 2026-09-09T11:50:28Z) | ||
| 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 | 52 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 7 | ±0 | | ||
| 33 | +| cyclo | 181 | ±0 | | ||
| 34 | +| complex | 87 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1143 | +10 | | ||
| 37 | +| loc | 541 | +2 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | ||
| 44 | +| main.go | 16 | 32 | 132 | | ||
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | ||
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | ||
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 66 | | ||
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 6 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | ||
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | ||
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | ||
| 57 | +| 4 | 2026-09-09T11:50:28Z | 0 | 0 | 0 | 87 | PASS | | ||
| 58 | +| 5 | 2026-09-15T16:54:08Z | 0 | 0 | 0 | 87 | PASS | | ||
added
.quality/report-latest.md +58 -0 | new file mode 100644 | ||
| @@ -0,0 +1,58 @@ | ||
| 1 | +# Quality report — 2026-09-15T16:54:08Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `3b4d297` on `feature/acp` | |
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | |
| 6 | +- **Run**: #5 (previous: 2026-09-09T11:50:28Z) | |
| 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 | 52 | ±0 | | |
| 31 | +| classes | 2 | ±0 | | |
| 32 | +| fields | 7 | ±0 | | |
| 33 | +| cyclo | 181 | ±0 | | |
| 34 | +| complex | 87 | ±0 | | |
| 35 | +| lcom | 0 | ±0 | | |
| 36 | +| lines | 1143 | +10 | | |
| 37 | +| loc | 541 | +2 | | |
| 38 | + | |
| 39 | +### Most complex files | |
| 40 | + | |
| 41 | +| file | complex | cyclo | loc | | |
| 42 | +|---|---|---|---| | |
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | |
| 44 | +| main.go | 16 | 32 | 132 | | |
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | |
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | |
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 66 | | |
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 6 | | |
| 49 | + | |
| 50 | +## Trend | |
| 51 | + | |
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 53 | +|---|---|---|---|---|---|---| | |
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | |
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | |
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | |
| 57 | +| 4 | 2026-09-09T11:50:28Z | 0 | 0 | 0 | 87 | PASS | | |
| 58 | +| 5 | 2026-09-15T16:54:08Z | 0 | 0 | 0 | 87 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,58 @@ | |||
| 1 | +# Quality report — 2026-09-15T16:54:08Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `3b4d297` on `feature/acp` | ||
| 5 | +- **qlty**: qlty 0.639.0 linux-arm64 (d9801f1 2026-07-23) | ||
| 6 | +- **Run**: #5 (previous: 2026-09-09T11:50:28Z) | ||
| 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 | 52 | ±0 | | ||
| 31 | +| classes | 2 | ±0 | | ||
| 32 | +| fields | 7 | ±0 | | ||
| 33 | +| cyclo | 181 | ±0 | | ||
| 34 | +| complex | 87 | ±0 | | ||
| 35 | +| lcom | 0 | ±0 | | ||
| 36 | +| lines | 1143 | +10 | | ||
| 37 | +| loc | 541 | +2 | | ||
| 38 | + | ||
| 39 | +### Most complex files | ||
| 40 | + | ||
| 41 | +| file | complex | cyclo | loc | | ||
| 42 | +|---|---|---|---| | ||
| 43 | +| internal/moonbitlang/words.go | 40 | 76 | 180 | | ||
| 44 | +| main.go | 16 | 32 | 132 | | ||
| 45 | +| internal/moonbitlang/scan.go | 15 | 49 | 95 | | ||
| 46 | +| internal/moonbitlang/literals.go | 13 | 16 | 62 | | ||
| 47 | +| internal/moonbitlang/moonbitlang.go | 3 | 7 | 66 | | ||
| 48 | +| internal/moonbitlang/templates.go | 0 | 1 | 6 | | ||
| 49 | + | ||
| 50 | +## Trend | ||
| 51 | + | ||
| 52 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 53 | +|---|---|---|---|---|---|---| | ||
| 54 | +| 1 | 2026-09-09T06:21:17Z | 0 | 0 | 0 | 87 | PASS | | ||
| 55 | +| 2 | 2026-09-09T06:36:30Z | 0 | 0 | 0 | 87 | PASS | | ||
| 56 | +| 3 | 2026-09-09T06:41:29Z | 0 | 0 | 0 | 87 | PASS | | ||
| 57 | +| 4 | 2026-09-09T11:50:28Z | 0 | 0 | 0 | 87 | PASS | | ||
| 58 | +| 5 | 2026-09-15T16:54:08Z | 0 | 0 | 0 | 87 | PASS | | ||
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 +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 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 | + "workbench.colorCustomizations": { | |
| 64 | + "activityBar.activeBackground": "#ffffff", | |
| 65 | + "activityBar.background": "#ffffff", | |
| 66 | + "activityBar.foreground": "#15202b", | |
| 67 | + "activityBar.inactiveForeground": "#15202b99", | |
| 68 | + "activityBarBadge.background": "#90a5de", | |
| 69 | + "activityBarBadge.foreground": "#15202b", | |
| 70 | + "commandCenter.border": "#15202b99", | |
| 71 | + "sash.hoverBorder": "#ffffff", | |
| 72 | + "statusBar.background": "#b8a8e8", | |
| 73 | + "statusBar.foreground": "#15202b", | |
| 74 | + "statusBarItem.hoverBackground": "#a4f5b0", | |
| 75 | + "statusBarItem.remoteBackground": "#9c8cf2", | |
| 76 | + "statusBarItem.remoteForeground": "#15202b", | |
| 77 | + "titleBar.activeBackground": "#90a5de", | |
| 78 | + "titleBar.activeForeground": "#15202b", | |
| 79 | + "titleBar.inactiveBackground": "#90a5de", | |
| 80 | + "titleBar.inactiveForeground": "#15202b99", | |
| 81 | + "activityBarTop.activeBackground": "#ffffff", | |
| 82 | + "activityBarTop.background": "#ffffff", | |
| 83 | + "activityBarTop.foreground": "#15202b", | |
| 84 | + "activityBarTop.inactiveForeground": "#15202b99", | |
| 85 | + "commandCenter.foreground": "#15202b", | |
| 86 | + "statusBar.debuggingBackground": "#90a5de", | |
| 87 | + "statusBar.debuggingForeground": "#15202b" | |
| 88 | + } | |
| 89 | +} | |
| \ No newline at end of file | ||
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 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 | + "workbench.colorCustomizations": { | ||
| 64 | + "activityBar.activeBackground": "#ffffff", | ||
| 65 | + "activityBar.background": "#ffffff", | ||
| 66 | + "activityBar.foreground": "#15202b", | ||
| 67 | + "activityBar.inactiveForeground": "#15202b99", | ||
| 68 | + "activityBarBadge.background": "#90a5de", | ||
| 69 | + "activityBarBadge.foreground": "#15202b", | ||
| 70 | + "commandCenter.border": "#15202b99", | ||
| 71 | + "sash.hoverBorder": "#ffffff", | ||
| 72 | + "statusBar.background": "#b8a8e8", | ||
| 73 | + "statusBar.foreground": "#15202b", | ||
| 74 | + "statusBarItem.hoverBackground": "#a4f5b0", | ||
| 75 | + "statusBarItem.remoteBackground": "#9c8cf2", | ||
| 76 | + "statusBarItem.remoteForeground": "#15202b", | ||
| 77 | + "titleBar.activeBackground": "#90a5de", | ||
| 78 | + "titleBar.activeForeground": "#15202b", | ||
| 79 | + "titleBar.inactiveBackground": "#90a5de", | ||
| 80 | + "titleBar.inactiveForeground": "#15202b99", | ||
| 81 | + "activityBarTop.activeBackground": "#ffffff", | ||
| 82 | + "activityBarTop.background": "#ffffff", | ||
| 83 | + "activityBarTop.foreground": "#15202b", | ||
| 84 | + "activityBarTop.inactiveForeground": "#15202b99", | ||
| 85 | + "commandCenter.foreground": "#15202b", | ||
| 86 | + "statusBar.debuggingBackground": "#90a5de", | ||
| 87 | + "statusBar.debuggingForeground": "#15202b" | ||
| 88 | + } | ||
| 89 | +} | ||
| \ 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-moonbit 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 MoonBit"' | |
| 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-moonbit ${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_MOONBIT_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-moonbit ${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-moonbit 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 MoonBit"' | ||
| 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-moonbit ${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_MOONBIT_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-moonbit ${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-moonbit-<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 MoonBit ${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 MoonBit ${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-moonbit" | |
| 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-moonbit-${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-moonbit-"${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 MoonBit ${TAG} | |
| 176 | + | |
| 177 | +${ABOUT} | |
| 178 | + | |
| 179 | +Built with $(go env GOVERSION). No runtime dependencies; \`moon-lsp\` is optional and | |
| 180 | +only completion and error marks need it. | |
| 181 | + | |
| 182 | +$(downloadTable) | |
| 183 | + | |
| 184 | +## Running it | |
| 185 | + | |
| 186 | + chmod +x turbo-moonbit-${VERSION}-<platform> | |
| 187 | + ./turbo-moonbit-${VERSION}-<platform> main.mbt | |
| 188 | + | |
| 189 | +On macOS, an unsigned download is quarantined until you say otherwise: | |
| 190 | + | |
| 191 | + xattr -d com.apple.quarantine turbo-moonbit-${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-moonbit-<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 MoonBit ${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 MoonBit ${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-moonbit" | ||
| 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-moonbit-${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-moonbit-"${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 MoonBit ${TAG} | ||
| 176 | + | ||
| 177 | +${ABOUT} | ||
| 178 | + | ||
| 179 | +Built with $(go env GOVERSION). No runtime dependencies; \`moon-lsp\` is optional and | ||
| 180 | +only completion and error marks need it. | ||
| 181 | + | ||
| 182 | +$(downloadTable) | ||
| 183 | + | ||
| 184 | +## Running it | ||
| 185 | + | ||
| 186 | + chmod +x turbo-moonbit-${VERSION}-<platform> | ||
| 187 | + ./turbo-moonbit-${VERSION}-<platform> main.mbt | ||
| 188 | + | ||
| 189 | +On macOS, an unsigned download is quarantined until you say otherwise: | ||
| 190 | + | ||
| 191 | + xattr -d com.apple.quarantine turbo-moonbit-${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-moonbit | |
| 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-moonbit, 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-moonbit where your shell can find it | |
| 49 | +install: | |
| 50 | + @scripts/install.sh | |
| 51 | + | |
| 52 | +## uninstall: remove an installed turbo-moonbit | |
| 53 | +uninstall: | |
| 54 | + @scripts/install.sh --uninstall | |
| 55 | + | |
| 56 | +## run: build and start the editor (make run FILE=main.mbt) | |
| 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-moonbit | ||
| 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-moonbit, 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-moonbit where your shell can find it | ||
| 49 | +install: | ||
| 50 | + @scripts/install.sh | ||
| 51 | + | ||
| 52 | +## uninstall: remove an installed turbo-moonbit | ||
| 53 | +uninstall: | ||
| 54 | + @scripts/install.sh --uninstall | ||
| 55 | + | ||
| 56 | +## run: build and start the editor (make run FILE=main.mbt) | ||
| 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 +117 -0 | new file mode 100644 | ||
| @@ -0,0 +1,117 @@ | ||
| 1 | +# turbo-moonbit | |
| 2 | + | |
| 3 | +A Turbo C-style editor for MoonBit, 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 MoonBit, and the MoonBit scanner — about eleven hundred lines, comments and all. 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 MoonBit editor needs: syntax colouring written against the language's published lexical grammar, loadable colour themes, completion and diagnostics from `moon-lsp`, shell windows, per-project settings, a project tree, snippets, and the `moon` toolchain a menu away. | |
| 8 | + | |
| 9 | +``` | |
| 10 | + File Edit Search Run Code Options Window Snippets MoonBit Help | |
| 11 | +╔═[x]═════════════════════════════ main.mbt ════════════════════════════════1═[■]╗ | |
| 12 | +║ 1 ///| ▲║ | |
| 13 | +║ 2 struct Greeting { ▓║ | |
| 14 | +║ 3 name : String ░║ | |
| 15 | +║ 4 times : Int ░║ | |
| 16 | +║ 5 } derive(Debug) ░║ | |
| 17 | +║ 6 ░║ | |
| 18 | +║ 7 ///| ░║ | |
| 19 | +║ 8 fn greet(g : Greeting) -> Unit { ░║ | |
| 20 | +║ 9 for i in 0..<g.times { println("Hello, \{g.name}! (\{i + 1})") } ▼║ | |
| 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 `moon-lsp` is installed. Then, from any MoonBit project: | |
| 33 | + | |
| 34 | +```bash | |
| 35 | +turbo-moonbit cmd/main/main.mbt | |
| 36 | +``` | |
| 37 | + | |
| 38 | +To build without installing, `make build` leaves the binary in `bin/turbo-moonbit`. From the module proxy instead of a checkout: `go install rickub.com/turbo-editors/turbo-moonbit@latest`. | |
| 39 | + | |
| 40 | +For completion and diagnostics, install the MoonBit toolchain as well — the editor works without it, and says so on the status bar: | |
| 41 | + | |
| 42 | +```bash | |
| 43 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | |
| 44 | +``` | |
| 45 | + | |
| 46 | +That one command installs `moon`, `moonc` and `moon-lsp` together. `moon-lsp` alone is not enough: it works a project out by running `moon`, so a machine with the server but not the build system gets a server that starts and then knows nothing about any file. [The install guide](docs/en/how-to/install-the-moonbit-toolchain.md) covers `MOON_HOME`, upgrading, and how to check the editor really found it. | |
| 47 | + | |
| 48 | +The [tutorial](docs/en/tutorials/getting-started.md) walks through a first session in about ten minutes, and [`demos/`](demos/) holds three MoonBit projects to open in it — a small one, one with a library and tests, and a tour of every construct the scanner colours. | |
| 49 | + | |
| 50 | +## Features | |
| 51 | + | |
| 52 | +- **Every build knows what it is** — `turbo-moonbit -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** — MoonBit by a hand-written scanner written against the language's published lexical grammar: every literal form including `b"…"`, `re"…"` and the `#|` / `$|` multi-line lines, every numeric suffix, attributes as whole lines, labelled arguments, package qualifiers, and the rule that makes `1..=2` an integer and a range rather than a double. Plus TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell scripts from turbo-core | |
| 55 | +- **Nothing carried between lines** — MoonBit has no block comment and no literal that may reach the next line, so an unterminated string cannot paint the rest of the file. It is the only editor in this family whose scanner needs no state at all | |
| 56 | +- **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 | |
| 57 | +- **Per-project settings** in `.turbo-moonbit/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 | |
| 58 | +- **Completion, hover, go-to-definition, references, symbols and diagnostics** from `moon-lsp`, entirely optional. The server is looked for in `$MOON_HOME/bin` and `~/.moon/bin` as well as on `PATH`, so an editor started from a shell that never read the installer's profile still finds it | |
| 59 | +- **Terminal windows** — `F8` opens a real shell in a window, with its own VT/ANSI emulator, scrollback and job control (Linux, macOS and Windows) | |
| 60 | +- **Project tree** — `F9` shows the project's files in a window; walk it with the arrows and press Enter to open one | |
| 61 | +- **Snippets** — a `Snippets` menu built from `.turbo-moonbit/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, and indented two spaces because that is what `moon fmt` writes | |
| 62 | +- **The MoonBit toolchain a menu away** — `Alt-M` runs `moon check`, `moon fmt`, `moon build`, `moon test`, `moon run`, `moon add`, `moon info` and `moon clean` from `.turbo-moonbit/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 | |
| 63 | +- **Editing** with word movement, block indent, a shared clipboard, and undo that merges a run of typing into one step | |
| 64 | +- **Faithful files** — line endings and the trailing newline are preserved, and saving is atomic | |
| 65 | +- **Automatic saving**, off by default, writing a short while after you stop typing | |
| 66 | + | |
| 67 | +## Commands | |
| 68 | + | |
| 69 | +| Command | What it does | | |
| 70 | +| --- | --- | | |
| 71 | +| `make install` | Build and install onto your `PATH` | | |
| 72 | +| `make build` | Compile into `bin/turbo-moonbit` | | |
| 73 | +| `make test` | Run the whole test suite | | |
| 74 | +| `make check` | `fmt`, `vet`, then the tests — what a commit should pass | | |
| 75 | +| `make run FILE=x.mbt` | Build and start the editor on a file | | |
| 76 | +| `make help` | List every target | | |
| 77 | + | |
| 78 | +```bash | |
| 79 | +turbo-moonbit [-theme name] [-no-lsp] [file...] | |
| 80 | +turbo-moonbit -list-themes | |
| 81 | +``` | |
| 82 | + | |
| 83 | +## Documentation | |
| 84 | + | |
| 85 | +Full documentation in **[English](docs/en/)** and **[French](docs/fr/)**, organised by the [Diátaxis](https://diataxis.fr) method: | |
| 86 | + | |
| 87 | +| | | | |
| 88 | +| --- | --- | | |
| 89 | +| **Tutorial** | [Your first MoonBit program in Turbo MoonBit](docs/en/tutorials/getting-started.md) | | |
| 90 | +| **How-to** | [install the editor](docs/en/how-to/install.md) · [install the MoonBit toolchain](docs/en/how-to/install-the-moonbit-toolchain.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 moon commands](docs/en/how-to/run-moon-commands.md) · [make a release](docs/en/how-to/make-a-release.md) | | |
| 91 | +| **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) · [MoonBit tools](docs/en/reference/moonbit-tools.md) · [the version number](docs/en/reference/versioning.md) | | |
| 92 | +| **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) · [MoonBit tools](docs/en/explanation/moonbit-tools.md) | | |
| 93 | + | |
| 94 | +The library's packages each carry their own `README.md` beside the code, in [turbo-core](https://rickub.com/turbo-editors/turbo-core). | |
| 95 | + | |
| 96 | +## Where the code is | |
| 97 | + | |
| 98 | +| | | | |
| 99 | +| --- | --- | | |
| 100 | +| `main.go` | flags, the terminal, the wiring | | |
| 101 | +| `internal/moonbitlang` | the profile, the MoonBit scanner, the three starter files | | |
| 102 | +| `demos/` | three MoonBit projects to open in the editor; each builds and runs | | |
| 103 | +| everything else | [turbo-core](https://rickub.com/turbo-editors/turbo-core) | | |
| 104 | + | |
| 105 | +The dependency graph is drawn in [`docs/diagrams/packages.drawio`](docs/diagrams/packages.drawio), checked against `go list` by `diagram_test.go`. | |
| 106 | + | |
| 107 | +## Design in one line | |
| 108 | + | |
| 109 | +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. | |
| 110 | + | |
| 111 | +## Requirements | |
| 112 | + | |
| 113 | +Go 1.26 or later to build it — the editor is written in Go even though it is an editor for MoonBit. A terminal with mouse reporting, which is all of them. The MoonBit toolchain is optional, and is what completion and the error marks need. | |
| 114 | + | |
| 115 | +## Licence | |
| 116 | + | |
| 117 | +See [LICENSE](LICENSE). | |
| new file mode 100644 | |||
| @@ -0,0 +1,117 @@ | |||
| 1 | +# turbo-moonbit | ||
| 2 | + | ||
| 3 | +A Turbo C-style editor for MoonBit, 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 MoonBit, and the MoonBit scanner — about eleven hundred lines, comments and all. 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 MoonBit editor needs: syntax colouring written against the language's published lexical grammar, loadable colour themes, completion and diagnostics from `moon-lsp`, shell windows, per-project settings, a project tree, snippets, and the `moon` toolchain a menu away. | ||
| 8 | + | ||
| 9 | +``` | ||
| 10 | + File Edit Search Run Code Options Window Snippets MoonBit Help | ||
| 11 | +╔═[x]═════════════════════════════ main.mbt ════════════════════════════════1═[■]╗ | ||
| 12 | +║ 1 ///| ▲║ | ||
| 13 | +║ 2 struct Greeting { ▓║ | ||
| 14 | +║ 3 name : String ░║ | ||
| 15 | +║ 4 times : Int ░║ | ||
| 16 | +║ 5 } derive(Debug) ░║ | ||
| 17 | +║ 6 ░║ | ||
| 18 | +║ 7 ///| ░║ | ||
| 19 | +║ 8 fn greet(g : Greeting) -> Unit { ░║ | ||
| 20 | +║ 9 for i in 0..<g.times { println("Hello, \{g.name}! (\{i + 1})") } ▼║ | ||
| 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 `moon-lsp` is installed. Then, from any MoonBit project: | ||
| 33 | + | ||
| 34 | +```bash | ||
| 35 | +turbo-moonbit cmd/main/main.mbt | ||
| 36 | +``` | ||
| 37 | + | ||
| 38 | +To build without installing, `make build` leaves the binary in `bin/turbo-moonbit`. From the module proxy instead of a checkout: `go install rickub.com/turbo-editors/turbo-moonbit@latest`. | ||
| 39 | + | ||
| 40 | +For completion and diagnostics, install the MoonBit toolchain as well — the editor works without it, and says so on the status bar: | ||
| 41 | + | ||
| 42 | +```bash | ||
| 43 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | ||
| 44 | +``` | ||
| 45 | + | ||
| 46 | +That one command installs `moon`, `moonc` and `moon-lsp` together. `moon-lsp` alone is not enough: it works a project out by running `moon`, so a machine with the server but not the build system gets a server that starts and then knows nothing about any file. [The install guide](docs/en/how-to/install-the-moonbit-toolchain.md) covers `MOON_HOME`, upgrading, and how to check the editor really found it. | ||
| 47 | + | ||
| 48 | +The [tutorial](docs/en/tutorials/getting-started.md) walks through a first session in about ten minutes, and [`demos/`](demos/) holds three MoonBit projects to open in it — a small one, one with a library and tests, and a tour of every construct the scanner colours. | ||
| 49 | + | ||
| 50 | +## Features | ||
| 51 | + | ||
| 52 | +- **Every build knows what it is** — `turbo-moonbit -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** — MoonBit by a hand-written scanner written against the language's published lexical grammar: every literal form including `b"…"`, `re"…"` and the `#|` / `$|` multi-line lines, every numeric suffix, attributes as whole lines, labelled arguments, package qualifiers, and the rule that makes `1..=2` an integer and a range rather than a double. Plus TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell scripts from turbo-core | ||
| 55 | +- **Nothing carried between lines** — MoonBit has no block comment and no literal that may reach the next line, so an unterminated string cannot paint the rest of the file. It is the only editor in this family whose scanner needs no state at all | ||
| 56 | +- **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 | ||
| 57 | +- **Per-project settings** in `.turbo-moonbit/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 | ||
| 58 | +- **Completion, hover, go-to-definition, references, symbols and diagnostics** from `moon-lsp`, entirely optional. The server is looked for in `$MOON_HOME/bin` and `~/.moon/bin` as well as on `PATH`, so an editor started from a shell that never read the installer's profile still finds it | ||
| 59 | +- **Terminal windows** — `F8` opens a real shell in a window, with its own VT/ANSI emulator, scrollback and job control (Linux, macOS and Windows) | ||
| 60 | +- **Project tree** — `F9` shows the project's files in a window; walk it with the arrows and press Enter to open one | ||
| 61 | +- **Snippets** — a `Snippets` menu built from `.turbo-moonbit/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, and indented two spaces because that is what `moon fmt` writes | ||
| 62 | +- **The MoonBit toolchain a menu away** — `Alt-M` runs `moon check`, `moon fmt`, `moon build`, `moon test`, `moon run`, `moon add`, `moon info` and `moon clean` from `.turbo-moonbit/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 | ||
| 63 | +- **Editing** with word movement, block indent, a shared clipboard, and undo that merges a run of typing into one step | ||
| 64 | +- **Faithful files** — line endings and the trailing newline are preserved, and saving is atomic | ||
| 65 | +- **Automatic saving**, off by default, writing a short while after you stop typing | ||
| 66 | + | ||
| 67 | +## Commands | ||
| 68 | + | ||
| 69 | +| Command | What it does | | ||
| 70 | +| --- | --- | | ||
| 71 | +| `make install` | Build and install onto your `PATH` | | ||
| 72 | +| `make build` | Compile into `bin/turbo-moonbit` | | ||
| 73 | +| `make test` | Run the whole test suite | | ||
| 74 | +| `make check` | `fmt`, `vet`, then the tests — what a commit should pass | | ||
| 75 | +| `make run FILE=x.mbt` | Build and start the editor on a file | | ||
| 76 | +| `make help` | List every target | | ||
| 77 | + | ||
| 78 | +```bash | ||
| 79 | +turbo-moonbit [-theme name] [-no-lsp] [file...] | ||
| 80 | +turbo-moonbit -list-themes | ||
| 81 | +``` | ||
| 82 | + | ||
| 83 | +## Documentation | ||
| 84 | + | ||
| 85 | +Full documentation in **[English](docs/en/)** and **[French](docs/fr/)**, organised by the [Diátaxis](https://diataxis.fr) method: | ||
| 86 | + | ||
| 87 | +| | | | ||
| 88 | +| --- | --- | | ||
| 89 | +| **Tutorial** | [Your first MoonBit program in Turbo MoonBit](docs/en/tutorials/getting-started.md) | | ||
| 90 | +| **How-to** | [install the editor](docs/en/how-to/install.md) · [install the MoonBit toolchain](docs/en/how-to/install-the-moonbit-toolchain.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 moon commands](docs/en/how-to/run-moon-commands.md) · [make a release](docs/en/how-to/make-a-release.md) | | ||
| 91 | +| **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) · [MoonBit tools](docs/en/reference/moonbit-tools.md) · [the version number](docs/en/reference/versioning.md) | | ||
| 92 | +| **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) · [MoonBit tools](docs/en/explanation/moonbit-tools.md) | | ||
| 93 | + | ||
| 94 | +The library's packages each carry their own `README.md` beside the code, in [turbo-core](https://rickub.com/turbo-editors/turbo-core). | ||
| 95 | + | ||
| 96 | +## Where the code is | ||
| 97 | + | ||
| 98 | +| | | | ||
| 99 | +| --- | --- | | ||
| 100 | +| `main.go` | flags, the terminal, the wiring | | ||
| 101 | +| `internal/moonbitlang` | the profile, the MoonBit scanner, the three starter files | | ||
| 102 | +| `demos/` | three MoonBit projects to open in the editor; each builds and runs | | ||
| 103 | +| everything else | [turbo-core](https://rickub.com/turbo-editors/turbo-core) | | ||
| 104 | + | ||
| 105 | +The dependency graph is drawn in [`docs/diagrams/packages.drawio`](docs/diagrams/packages.drawio), checked against `go list` by `diagram_test.go`. | ||
| 106 | + | ||
| 107 | +## Design in one line | ||
| 108 | + | ||
| 109 | +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. | ||
| 110 | + | ||
| 111 | +## Requirements | ||
| 112 | + | ||
| 113 | +Go 1.26 or later to build it — the editor is written in Go even though it is an editor for MoonBit. A terminal with mouse reporting, which is all of them. The MoonBit toolchain is optional, and is what completion and the error marks need. | ||
| 114 | + | ||
| 115 | +## Licence | ||
| 116 | + | ||
| 117 | +See [LICENSE](LICENSE). | ||
added
UPDATE.md +4 -0 | new file mode 100644 | ||
| @@ -0,0 +1,4 @@ | ||
| 1 | +```bash | |
| 2 | +go get rickub.com/turbo-editors/turbo-core@v1.0.2 && go mod tidy && GOWORK=off make check | |
| 3 | +./01-release.tag.sh | |
| 4 | +``` | |
| \ No newline at end of file | ||
| new file mode 100644 | |||
| @@ -0,0 +1,4 @@ | |||
| 1 | +```bash | ||
| 2 | +go get rickub.com/turbo-editors/turbo-core@v1.0.2 && go mod tidy && GOWORK=off make check | ||
| 3 | +./01-release.tag.sh | ||
| 4 | +``` | ||
| \ No newline at end of file | \ No newline at end of file | ||
added
demos/README.md +65 -0 | new file mode 100644 | ||
| @@ -0,0 +1,65 @@ | ||
| 1 | +# Demo projects | |
| 2 | + | |
| 3 | +Three small MoonBit projects to open in Turbo MoonBit. They exist to be *edited*, not just read: each one is a real `moon` module, so opening any file in it starts `moon-lsp` in that directory and the MoonBit menu's commands work on it. | |
| 4 | + | |
| 5 | +**All three compile with no errors and no warnings**, pass `moon fmt` without being rewritten, and were run before being committed. That is the whole point — a colouring demo that does not build is a screenshot. | |
| 6 | + | |
| 7 | +| Project | What it is for | | |
| 8 | +| --- | --- | | |
| 9 | +| [`hello/`](hello/) | The smallest thing that is still interesting: a struct, an enum, a match, a labelled argument, string interpolation | | |
| 10 | +| [`shapes/`](shapes/) | A library plus a program: traits, generics, a custom error, and five tests to run from the **Test** menu item | | |
| 11 | +| [`syntax-tour/`](syntax-tour/) | Every construct the scanner recognises, in one file that compiles. Open it to see what each colour means | | |
| 12 | + | |
| 13 | +## Trying one | |
| 14 | + | |
| 15 | +```bash | |
| 16 | +cd demos/hello | |
| 17 | +turbo-moonbit main.mbt | |
| 18 | +``` | |
| 19 | + | |
| 20 | +The status bar should read `LSP: ready` at the right-hand end — `moon.mod` is beside the file, so the server starts here. Then: | |
| 21 | + | |
| 22 | +- `Alt-M` opens the **MoonBit** menu. The first time, it offers only **Create tools file**; choose it, and the nine commands appear. | |
| 23 | +- **Run** asks which package to run. In `hello` and `syntax-tour` the answer is `.`; in `shapes` it is `cmd/main`. | |
| 24 | +- **Test** works in `shapes`, which is the one with tests. | |
| 25 | + | |
| 26 | +From a shell instead: | |
| 27 | + | |
| 28 | +```bash | |
| 29 | +moon check # type-check, no output files | |
| 30 | +moon fmt # format in place | |
| 31 | +moon run . # or `moon run cmd/main` in shapes | |
| 32 | +moon test # shapes only | |
| 33 | +``` | |
| 34 | + | |
| 35 | +## hello | |
| 36 | + | |
| 37 | +A greeting printed a few times, in three tones. It is deliberately short enough to read in one screen. | |
| 38 | + | |
| 39 | +What it shows: `struct` with `derive(Eq)`, an `enum` and a `match` over it, a hand-written `impl Show … with fn output` (which is what `derive(Show)` was deprecated in favour of), a labelled argument with a default — `tone~ : Tone = Plain`, passed as `greet(g, tone=Loud)` — and `\{…}` interpolation. | |
| 40 | + | |
| 41 | +## shapes | |
| 42 | + | |
| 43 | +A library package at the root and a program under `cmd/main` that imports it. This is the layout `moon new` produces, and the one most real projects have. | |
| 44 | + | |
| 45 | +What it shows: `pub(open) trait Area`, two implementations, generic functions bounded by a trait — `pub fn[T : Area] total(…)` — a `pub suberror` and `raise`, `guard … else { raise … }`, `try`/`catch`/`noraise`, `Option` with `Some`/`None`, and package qualifiers (`@shapes.Circle`) everywhere, because the program is in a different package from the library. | |
| 46 | + | |
| 47 | +`pub(all)` rather than `pub` on the two structs is not decoration: `pub` alone makes a type read-only from outside its package, so `cmd/main` could not construct one. | |
| 48 | + | |
| 49 | +## syntax-tour | |
| 50 | + | |
| 51 | +One file, `tour.mbt`, holding every construct the MoonBit scanner recognises — and one it gets wrong on purpose. | |
| 52 | + | |
| 53 | +What it shows: all five quoted forms (`"…"`, `b"…"`, `re"…"`, `'c'`, `b'c'`), both multi-line string prefixes (`#|` literal, `$|` interpolating), every numeric form and suffix the grammar allows, `1..=5` and `0..<3` (which is where a scanner that swallowed any dot after a number would go wrong), traits and `extend`, `suberror` and error handling, a `for` loop carrying accumulators with `break` and `continue`, tuples and `.0`, the pipe operator, and both kinds of attribute — a built-in `#deprecated("…")` and a user-defined `#custom.note(…)`, each taking its whole line. | |
| 54 | + | |
| 55 | +**One line is coloured wrongly, and is kept and labelled rather than avoided:** | |
| 56 | + | |
| 57 | +```moonbit | |
| 58 | +let nested = "answer: \{if true { "yes" } else { "no" }}" | |
| 59 | +``` | |
| 60 | + | |
| 61 | +A string nested inside an interpolation ends the outer literal as far as the scanner is concerned, so `yes` and `no` come out as identifiers. Finding the real end needs the parser rather than the scanner. [`reference/languages.md`](../docs/en/reference/languages.md) says so, and a test pins it, so it is a known boundary rather than a surprise. | |
| 62 | + | |
| 63 | +## A note on `_build/` | |
| 64 | + | |
| 65 | +`moon` writes its output into a `_build/` directory beside each `moon.mod`. Those are gitignored. `moon clean` removes them. | |
| new file mode 100644 | |||
| @@ -0,0 +1,65 @@ | |||
| 1 | +# Demo projects | ||
| 2 | + | ||
| 3 | +Three small MoonBit projects to open in Turbo MoonBit. They exist to be *edited*, not just read: each one is a real `moon` module, so opening any file in it starts `moon-lsp` in that directory and the MoonBit menu's commands work on it. | ||
| 4 | + | ||
| 5 | +**All three compile with no errors and no warnings**, pass `moon fmt` without being rewritten, and were run before being committed. That is the whole point — a colouring demo that does not build is a screenshot. | ||
| 6 | + | ||
| 7 | +| Project | What it is for | | ||
| 8 | +| --- | --- | | ||
| 9 | +| [`hello/`](hello/) | The smallest thing that is still interesting: a struct, an enum, a match, a labelled argument, string interpolation | | ||
| 10 | +| [`shapes/`](shapes/) | A library plus a program: traits, generics, a custom error, and five tests to run from the **Test** menu item | | ||
| 11 | +| [`syntax-tour/`](syntax-tour/) | Every construct the scanner recognises, in one file that compiles. Open it to see what each colour means | | ||
| 12 | + | ||
| 13 | +## Trying one | ||
| 14 | + | ||
| 15 | +```bash | ||
| 16 | +cd demos/hello | ||
| 17 | +turbo-moonbit main.mbt | ||
| 18 | +``` | ||
| 19 | + | ||
| 20 | +The status bar should read `LSP: ready` at the right-hand end — `moon.mod` is beside the file, so the server starts here. Then: | ||
| 21 | + | ||
| 22 | +- `Alt-M` opens the **MoonBit** menu. The first time, it offers only **Create tools file**; choose it, and the nine commands appear. | ||
| 23 | +- **Run** asks which package to run. In `hello` and `syntax-tour` the answer is `.`; in `shapes` it is `cmd/main`. | ||
| 24 | +- **Test** works in `shapes`, which is the one with tests. | ||
| 25 | + | ||
| 26 | +From a shell instead: | ||
| 27 | + | ||
| 28 | +```bash | ||
| 29 | +moon check # type-check, no output files | ||
| 30 | +moon fmt # format in place | ||
| 31 | +moon run . # or `moon run cmd/main` in shapes | ||
| 32 | +moon test # shapes only | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +## hello | ||
| 36 | + | ||
| 37 | +A greeting printed a few times, in three tones. It is deliberately short enough to read in one screen. | ||
| 38 | + | ||
| 39 | +What it shows: `struct` with `derive(Eq)`, an `enum` and a `match` over it, a hand-written `impl Show … with fn output` (which is what `derive(Show)` was deprecated in favour of), a labelled argument with a default — `tone~ : Tone = Plain`, passed as `greet(g, tone=Loud)` — and `\{…}` interpolation. | ||
| 40 | + | ||
| 41 | +## shapes | ||
| 42 | + | ||
| 43 | +A library package at the root and a program under `cmd/main` that imports it. This is the layout `moon new` produces, and the one most real projects have. | ||
| 44 | + | ||
| 45 | +What it shows: `pub(open) trait Area`, two implementations, generic functions bounded by a trait — `pub fn[T : Area] total(…)` — a `pub suberror` and `raise`, `guard … else { raise … }`, `try`/`catch`/`noraise`, `Option` with `Some`/`None`, and package qualifiers (`@shapes.Circle`) everywhere, because the program is in a different package from the library. | ||
| 46 | + | ||
| 47 | +`pub(all)` rather than `pub` on the two structs is not decoration: `pub` alone makes a type read-only from outside its package, so `cmd/main` could not construct one. | ||
| 48 | + | ||
| 49 | +## syntax-tour | ||
| 50 | + | ||
| 51 | +One file, `tour.mbt`, holding every construct the MoonBit scanner recognises — and one it gets wrong on purpose. | ||
| 52 | + | ||
| 53 | +What it shows: all five quoted forms (`"…"`, `b"…"`, `re"…"`, `'c'`, `b'c'`), both multi-line string prefixes (`#|` literal, `$|` interpolating), every numeric form and suffix the grammar allows, `1..=5` and `0..<3` (which is where a scanner that swallowed any dot after a number would go wrong), traits and `extend`, `suberror` and error handling, a `for` loop carrying accumulators with `break` and `continue`, tuples and `.0`, the pipe operator, and both kinds of attribute — a built-in `#deprecated("…")` and a user-defined `#custom.note(…)`, each taking its whole line. | ||
| 54 | + | ||
| 55 | +**One line is coloured wrongly, and is kept and labelled rather than avoided:** | ||
| 56 | + | ||
| 57 | +```moonbit | ||
| 58 | +let nested = "answer: \{if true { "yes" } else { "no" }}" | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +A string nested inside an interpolation ends the outer literal as far as the scanner is concerned, so `yes` and `no` come out as identifiers. Finding the real end needs the parser rather than the scanner. [`reference/languages.md`](../docs/en/reference/languages.md) says so, and a test pins it, so it is a known boundary rather than a surprise. | ||
| 62 | + | ||
| 63 | +## A note on `_build/` | ||
| 64 | + | ||
| 65 | +`moon` writes its output into a `_build/` directory beside each `moon.mod`. Those are gitignored. `moon clean` removes them. | ||
added
demos/hello/.turbo-moonbit/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-moonbit/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-moonbit/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
demos/hello/.turbo-moonbit/agent.yaml +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +# /Users/k33g/CodeBerg/turbo-editors/turbo-moonbit/hello/.turbo-moonbit/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-moonbit/hello/.turbo-moonbit/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
demos/hello/.turbo-moonbit/settings.toml +18 -0 | new file mode 100644 | ||
| @@ -0,0 +1,18 @@ | ||
| 1 | +# turbo-moonbit project settings. | |
| 2 | +# | |
| 3 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -list-themes` lists them all. | |
| 9 | +# A -theme flag on the command line overrides this. | |
| 10 | +theme = "monochrome-light" | |
| 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 = "2s" | |
| new file mode 100644 | |||
| @@ -0,0 +1,18 @@ | |||
| 1 | +# turbo-moonbit project settings. | ||
| 2 | +# | ||
| 3 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -list-themes` lists them all. | ||
| 9 | +# A -theme flag on the command line overrides this. | ||
| 10 | +theme = "monochrome-light" | ||
| 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 = "2s" | ||
added
demos/hello/.turbo-moonbit/snippets.toml +106 -0 | new file mode 100644 | ||
| @@ -0,0 +1,106 @@ | ||
| 1 | +# turbo-moonbit 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 | +# General. 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: bash, dockerfile, html, javascript, markdown, moonbit, toml, | |
| 10 | +# xml, yaml. Leave it out and the snippet is offered everywhere. | |
| 11 | +# | |
| 12 | +# Bodies are indented with two spaces, which is what `moon fmt` writes. Running | |
| 13 | +# the formatter over a file indented any other way rewrites the whole file, so | |
| 14 | +# a snippet that disagrees with it turns one insertion into a large diff. | |
| 15 | +# | |
| 16 | +# Every MoonBit body below is written in single quotes — '''…''' rather than | |
| 17 | +# """…""" — because MoonBit interpolates with \{…}, and a backslash before a | |
| 18 | +# brace is not a valid escape in a TOML basic string. In a literal string a | |
| 19 | +# backslash is just a backslash, which is exactly what a MoonBit snippet needs. | |
| 20 | +# | |
| 21 | +# Your own snippets, shared across every project, go in: | |
| 22 | +# /Users/k33g/Library/Application Support/turbo-moonbit/snippets.toml | |
| 23 | + | |
| 24 | +[[snippet]] | |
| 25 | +name = "main" | |
| 26 | +group = "MoonBit" | |
| 27 | +languages = ["moonbit"] | |
| 28 | +body = ''' | |
| 29 | +fn main { | |
| 30 | + println("Hello, MoonBit!") | |
| 31 | +}''' | |
| 32 | + | |
| 33 | +[[snippet]] | |
| 34 | +name = "test" | |
| 35 | +group = "MoonBit" | |
| 36 | +languages = ["moonbit"] | |
| 37 | +body = ''' | |
| 38 | +test "it works" { | |
| 39 | + assert_eq(1 + 1, 2) | |
| 40 | +}''' | |
| 41 | + | |
| 42 | +[[snippet]] | |
| 43 | +name = "struct" | |
| 44 | +group = "MoonBit" | |
| 45 | +languages = ["moonbit"] | |
| 46 | +body = ''' | |
| 47 | +struct Point { | |
| 48 | + x : Int | |
| 49 | + y : Int | |
| 50 | +} derive(Eq)''' | |
| 51 | + | |
| 52 | +[[snippet]] | |
| 53 | +name = "enum" | |
| 54 | +group = "MoonBit" | |
| 55 | +languages = ["moonbit"] | |
| 56 | +body = ''' | |
| 57 | +enum Shape { | |
| 58 | + Circle(Double) | |
| 59 | + Rect(Double, Double) | |
| 60 | +} derive(Show)''' | |
| 61 | + | |
| 62 | +[[snippet]] | |
| 63 | +name = "match" | |
| 64 | +group = "MoonBit" | |
| 65 | +languages = ["moonbit"] | |
| 66 | +body = ''' | |
| 67 | +match value { | |
| 68 | + Some(x) => "got \{x}" | |
| 69 | + None => "nothing" | |
| 70 | +}''' | |
| 71 | + | |
| 72 | +[[snippet]] | |
| 73 | +name = "trait impl" | |
| 74 | +group = "MoonBit" | |
| 75 | +languages = ["moonbit"] | |
| 76 | +body = ''' | |
| 77 | +impl Show for Point with fn output(self, logger) { | |
| 78 | + logger.write_string("Point(\{self.x}, \{self.y})") | |
| 79 | +}''' | |
| 80 | + | |
| 81 | +[[snippet]] | |
| 82 | +name = "loop" | |
| 83 | +group = "MoonBit" | |
| 84 | +languages = ["moonbit"] | |
| 85 | +body = ''' | |
| 86 | +loop (0, 0) { | |
| 87 | + (i, acc) => if i > n { break acc } else { continue (i + 1, acc + i) } | |
| 88 | +}''' | |
| 89 | + | |
| 90 | +[[snippet]] | |
| 91 | +name = "guard" | |
| 92 | +group = "MoonBit" | |
| 93 | +languages = ["moonbit"] | |
| 94 | +body = ''' | |
| 95 | +guard xs.length() > 0 else { fail("empty") }''' | |
| 96 | + | |
| 97 | +[[snippet]] | |
| 98 | +group = "General" | |
| 99 | +name = "Hello" | |
| 100 | +body = "Hello!!!" | |
| 101 | + | |
| 102 | +[[snippet]] | |
| 103 | +group = "Markdown" | |
| 104 | +name = "Image" | |
| 105 | +languages = ["markdown"] | |
| 106 | +body = "" | |
| new file mode 100644 | |||
| @@ -0,0 +1,106 @@ | |||
| 1 | +# turbo-moonbit 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 | +# General. 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: bash, dockerfile, html, javascript, markdown, moonbit, toml, | ||
| 10 | +# xml, yaml. Leave it out and the snippet is offered everywhere. | ||
| 11 | +# | ||
| 12 | +# Bodies are indented with two spaces, which is what `moon fmt` writes. Running | ||
| 13 | +# the formatter over a file indented any other way rewrites the whole file, so | ||
| 14 | +# a snippet that disagrees with it turns one insertion into a large diff. | ||
| 15 | +# | ||
| 16 | +# Every MoonBit body below is written in single quotes — '''…''' rather than | ||
| 17 | +# """…""" — because MoonBit interpolates with \{…}, and a backslash before a | ||
| 18 | +# brace is not a valid escape in a TOML basic string. In a literal string a | ||
| 19 | +# backslash is just a backslash, which is exactly what a MoonBit snippet needs. | ||
| 20 | +# | ||
| 21 | +# Your own snippets, shared across every project, go in: | ||
| 22 | +# /Users/k33g/Library/Application Support/turbo-moonbit/snippets.toml | ||
| 23 | + | ||
| 24 | +[[snippet]] | ||
| 25 | +name = "main" | ||
| 26 | +group = "MoonBit" | ||
| 27 | +languages = ["moonbit"] | ||
| 28 | +body = ''' | ||
| 29 | +fn main { | ||
| 30 | + println("Hello, MoonBit!") | ||
| 31 | +}''' | ||
| 32 | + | ||
| 33 | +[[snippet]] | ||
| 34 | +name = "test" | ||
| 35 | +group = "MoonBit" | ||
| 36 | +languages = ["moonbit"] | ||
| 37 | +body = ''' | ||
| 38 | +test "it works" { | ||
| 39 | + assert_eq(1 + 1, 2) | ||
| 40 | +}''' | ||
| 41 | + | ||
| 42 | +[[snippet]] | ||
| 43 | +name = "struct" | ||
| 44 | +group = "MoonBit" | ||
| 45 | +languages = ["moonbit"] | ||
| 46 | +body = ''' | ||
| 47 | +struct Point { | ||
| 48 | + x : Int | ||
| 49 | + y : Int | ||
| 50 | +} derive(Eq)''' | ||
| 51 | + | ||
| 52 | +[[snippet]] | ||
| 53 | +name = "enum" | ||
| 54 | +group = "MoonBit" | ||
| 55 | +languages = ["moonbit"] | ||
| 56 | +body = ''' | ||
| 57 | +enum Shape { | ||
| 58 | + Circle(Double) | ||
| 59 | + Rect(Double, Double) | ||
| 60 | +} derive(Show)''' | ||
| 61 | + | ||
| 62 | +[[snippet]] | ||
| 63 | +name = "match" | ||
| 64 | +group = "MoonBit" | ||
| 65 | +languages = ["moonbit"] | ||
| 66 | +body = ''' | ||
| 67 | +match value { | ||
| 68 | + Some(x) => "got \{x}" | ||
| 69 | + None => "nothing" | ||
| 70 | +}''' | ||
| 71 | + | ||
| 72 | +[[snippet]] | ||
| 73 | +name = "trait impl" | ||
| 74 | +group = "MoonBit" | ||
| 75 | +languages = ["moonbit"] | ||
| 76 | +body = ''' | ||
| 77 | +impl Show for Point with fn output(self, logger) { | ||
| 78 | + logger.write_string("Point(\{self.x}, \{self.y})") | ||
| 79 | +}''' | ||
| 80 | + | ||
| 81 | +[[snippet]] | ||
| 82 | +name = "loop" | ||
| 83 | +group = "MoonBit" | ||
| 84 | +languages = ["moonbit"] | ||
| 85 | +body = ''' | ||
| 86 | +loop (0, 0) { | ||
| 87 | + (i, acc) => if i > n { break acc } else { continue (i + 1, acc + i) } | ||
| 88 | +}''' | ||
| 89 | + | ||
| 90 | +[[snippet]] | ||
| 91 | +name = "guard" | ||
| 92 | +group = "MoonBit" | ||
| 93 | +languages = ["moonbit"] | ||
| 94 | +body = ''' | ||
| 95 | +guard xs.length() > 0 else { fail("empty") }''' | ||
| 96 | + | ||
| 97 | +[[snippet]] | ||
| 98 | +group = "General" | ||
| 99 | +name = "Hello" | ||
| 100 | +body = "Hello!!!" | ||
| 101 | + | ||
| 102 | +[[snippet]] | ||
| 103 | +group = "Markdown" | ||
| 104 | +name = "Image" | ||
| 105 | +languages = ["markdown"] | ||
| 106 | +body = "" | ||
added
demos/hello/.turbo-moonbit/tools.toml +104 -0 | new file mode 100644 | ||
| @@ -0,0 +1,104 @@ | ||
| 1 | +# turbo-moonbit tools. | |
| 2 | +# | |
| 3 | +# Each [[tool]] becomes one line of the MoonBit 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 | +# MoonBit menu; name anything else and that menu is created for you, in the | |
| 12 | +# order the names first appear here. A tool that has nothing to do with MoonBit | |
| 13 | +# belongs 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 = "moon add {{module}}" | |
| 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 = "moon test {{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. moon itself looks upwards | |
| 45 | +# for moon.mod, so most of these also work from a package inside the project. | |
| 46 | + | |
| 47 | +[[tool]] | |
| 48 | +name = "~C~heck" | |
| 49 | +# The fastest thing that tells you whether the project is sound: it type-checks | |
| 50 | +# without emitting object files, which is why it comes first rather than build. | |
| 51 | +command = "moon check" | |
| 52 | +output = "popup" | |
| 53 | + | |
| 54 | +[[tool]] | |
| 55 | +name = "~F~ormat" | |
| 56 | +command = "moon fmt" | |
| 57 | +output = "popup" | |
| 58 | + | |
| 59 | +[[tool]] | |
| 60 | +name = "~B~uild" | |
| 61 | +# MoonBit compiles to several backends, and which one a project wants is not | |
| 62 | +# something a starter file can know. The value is asked for rather than fixed: | |
| 63 | +# wasm, wasm-gc, js, native, llvm, or all. | |
| 64 | +command = "moon build --target {{backend: wasm-gc, js, native, llvm or all...}}" | |
| 65 | +output = "popup" | |
| 66 | + | |
| 67 | +[[tool]] | |
| 68 | +name = "~T~est" | |
| 69 | +command = "moon test" | |
| 70 | +output = "popup" | |
| 71 | + | |
| 72 | +[[tool]] | |
| 73 | +name = "~R~un" | |
| 74 | +command = "moon run {{package, e.g. cmd/main}}" | |
| 75 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | |
| 76 | +# be answered, and one that runs long has to be able to be interrupted. | |
| 77 | +output = "terminal" | |
| 78 | + | |
| 79 | +[[tool]] | |
| 80 | +name = "~A~dd a dependency" | |
| 81 | +command = "moon add {{module, e.g. moonbitlang/x}}" | |
| 82 | +output = "popup" | |
| 83 | + | |
| 84 | +[[tool]] | |
| 85 | +name = "~I~nterfaces" | |
| 86 | +# Regenerates the .mbti files that record each package's public surface. Worth | |
| 87 | +# a menu entry because a diff in one is how a review sees that an API changed. | |
| 88 | +command = "moon info" | |
| 89 | +output = "popup" | |
| 90 | + | |
| 91 | +[[tool]] | |
| 92 | +name = "C~l~ean" | |
| 93 | +command = "moon clean" | |
| 94 | +output = "popup" | |
| 95 | + | |
| 96 | +# A tool naming a `menu` gets a menu of its own on the bar. Nothing above does, | |
| 97 | +# so every tool above is in the MoonBit menu. This one is in a menu called | |
| 98 | +# Tools, which appears between MoonBit and Help — that is the whole mechanism. | |
| 99 | + | |
| 100 | +[[tool]] | |
| 101 | +name = "~E~cho" | |
| 102 | +command = "echo 🎉 tada!" | |
| 103 | +menu = "Tools" | |
| 104 | +output = "terminal" | |
| new file mode 100644 | |||
| @@ -0,0 +1,104 @@ | |||
| 1 | +# turbo-moonbit tools. | ||
| 2 | +# | ||
| 3 | +# Each [[tool]] becomes one line of the MoonBit 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 | +# MoonBit menu; name anything else and that menu is created for you, in the | ||
| 12 | +# order the names first appear here. A tool that has nothing to do with MoonBit | ||
| 13 | +# belongs 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 = "moon add {{module}}" | ||
| 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 = "moon test {{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. moon itself looks upwards | ||
| 45 | +# for moon.mod, so most of these also work from a package inside the project. | ||
| 46 | + | ||
| 47 | +[[tool]] | ||
| 48 | +name = "~C~heck" | ||
| 49 | +# The fastest thing that tells you whether the project is sound: it type-checks | ||
| 50 | +# without emitting object files, which is why it comes first rather than build. | ||
| 51 | +command = "moon check" | ||
| 52 | +output = "popup" | ||
| 53 | + | ||
| 54 | +[[tool]] | ||
| 55 | +name = "~F~ormat" | ||
| 56 | +command = "moon fmt" | ||
| 57 | +output = "popup" | ||
| 58 | + | ||
| 59 | +[[tool]] | ||
| 60 | +name = "~B~uild" | ||
| 61 | +# MoonBit compiles to several backends, and which one a project wants is not | ||
| 62 | +# something a starter file can know. The value is asked for rather than fixed: | ||
| 63 | +# wasm, wasm-gc, js, native, llvm, or all. | ||
| 64 | +command = "moon build --target {{backend: wasm-gc, js, native, llvm or all...}}" | ||
| 65 | +output = "popup" | ||
| 66 | + | ||
| 67 | +[[tool]] | ||
| 68 | +name = "~T~est" | ||
| 69 | +command = "moon test" | ||
| 70 | +output = "popup" | ||
| 71 | + | ||
| 72 | +[[tool]] | ||
| 73 | +name = "~R~un" | ||
| 74 | +command = "moon run {{package, e.g. cmd/main}}" | ||
| 75 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | ||
| 76 | +# be answered, and one that runs long has to be able to be interrupted. | ||
| 77 | +output = "terminal" | ||
| 78 | + | ||
| 79 | +[[tool]] | ||
| 80 | +name = "~A~dd a dependency" | ||
| 81 | +command = "moon add {{module, e.g. moonbitlang/x}}" | ||
| 82 | +output = "popup" | ||
| 83 | + | ||
| 84 | +[[tool]] | ||
| 85 | +name = "~I~nterfaces" | ||
| 86 | +# Regenerates the .mbti files that record each package's public surface. Worth | ||
| 87 | +# a menu entry because a diff in one is how a review sees that an API changed. | ||
| 88 | +command = "moon info" | ||
| 89 | +output = "popup" | ||
| 90 | + | ||
| 91 | +[[tool]] | ||
| 92 | +name = "C~l~ean" | ||
| 93 | +command = "moon clean" | ||
| 94 | +output = "popup" | ||
| 95 | + | ||
| 96 | +# A tool naming a `menu` gets a menu of its own on the bar. Nothing above does, | ||
| 97 | +# so every tool above is in the MoonBit menu. This one is in a menu called | ||
| 98 | +# Tools, which appears between MoonBit and Help — that is the whole mechanism. | ||
| 99 | + | ||
| 100 | +[[tool]] | ||
| 101 | +name = "~E~cho" | ||
| 102 | +command = "echo 🎉 tada!" | ||
| 103 | +menu = "Tools" | ||
| 104 | +output = "terminal" | ||
added
demos/hello/main.mbt +52 -0 | new file mode 100644 | ||
| @@ -0,0 +1,52 @@ | ||
| 1 | +///| | |
| 2 | +/// A greeting to print, and how many times to print it. | |
| 3 | +struct Greeting { | |
| 4 | + name : String | |
| 5 | + times : Int | |
| 6 | +} derive(Eq) | |
| 7 | + | |
| 8 | +///| | |
| 9 | +/// Show is written out by hand rather than derived: `derive(Show)` is | |
| 10 | +/// deprecated, and this is the form the toolchain points at instead. | |
| 11 | +impl Show for Greeting with fn output(self, logger) { | |
| 12 | + logger.write_string("\{self.name} × \{self.times}") | |
| 13 | +} | |
| 14 | + | |
| 15 | +///| | |
| 16 | +/// The tone a greeting is delivered in. | |
| 17 | +enum Tone { | |
| 18 | + Plain | |
| 19 | + Loud | |
| 20 | + Question | |
| 21 | +} derive(Debug) | |
| 22 | + | |
| 23 | +///| | |
| 24 | +/// punctuate returns the mark a tone ends on. | |
| 25 | +fn punctuate(tone : Tone) -> String { | |
| 26 | + match tone { | |
| 27 | + Plain => "." | |
| 28 | + Loud => "!" | |
| 29 | + Question => "?" | |
| 30 | + } | |
| 31 | +} | |
| 32 | + | |
| 33 | +///| | |
| 34 | +/// greet prints one greeting, once per `times`. | |
| 35 | +/// | |
| 36 | +/// `tone` is a labelled argument with a default, so a call site may leave it | |
| 37 | +/// out — and when it does not, it reads as `greet(g, tone=Loud)`. | |
| 38 | +fn greet(g : Greeting, tone? : Tone = Plain) -> Unit { | |
| 39 | + for i in 0..<g.times { | |
| 40 | + println("Hello, \{g.name}\{punctuate(tone)} (\{i + 1} of \{g.times})") | |
| 41 | + } | |
| 42 | +} | |
| 43 | + | |
| 44 | +///| | |
| 45 | +fn main { | |
| 46 | + let g = { name: "MoonBit", times: 2, } | |
| 47 | + for tone in [Plain, Loud, Question] { | |
| 48 | + greet(g, tone~) | |
| 49 | + } | |
| 50 | + println("") | |
| 51 | + println("the greeting itself: \{g}") | |
| 52 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,52 @@ | |||
| 1 | +///| | ||
| 2 | +/// A greeting to print, and how many times to print it. | ||
| 3 | +struct Greeting { | ||
| 4 | + name : String | ||
| 5 | + times : Int | ||
| 6 | +} derive(Eq) | ||
| 7 | + | ||
| 8 | +///| | ||
| 9 | +/// Show is written out by hand rather than derived: `derive(Show)` is | ||
| 10 | +/// deprecated, and this is the form the toolchain points at instead. | ||
| 11 | +impl Show for Greeting with fn output(self, logger) { | ||
| 12 | + logger.write_string("\{self.name} × \{self.times}") | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +///| | ||
| 16 | +/// The tone a greeting is delivered in. | ||
| 17 | +enum Tone { | ||
| 18 | + Plain | ||
| 19 | + Loud | ||
| 20 | + Question | ||
| 21 | +} derive(Debug) | ||
| 22 | + | ||
| 23 | +///| | ||
| 24 | +/// punctuate returns the mark a tone ends on. | ||
| 25 | +fn punctuate(tone : Tone) -> String { | ||
| 26 | + match tone { | ||
| 27 | + Plain => "." | ||
| 28 | + Loud => "!" | ||
| 29 | + Question => "?" | ||
| 30 | + } | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +///| | ||
| 34 | +/// greet prints one greeting, once per `times`. | ||
| 35 | +/// | ||
| 36 | +/// `tone` is a labelled argument with a default, so a call site may leave it | ||
| 37 | +/// out — and when it does not, it reads as `greet(g, tone=Loud)`. | ||
| 38 | +fn greet(g : Greeting, tone? : Tone = Plain) -> Unit { | ||
| 39 | + for i in 0..<g.times { | ||
| 40 | + println("Hello, \{g.name}\{punctuate(tone)} (\{i + 1} of \{g.times})") | ||
| 41 | + } | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +///| | ||
| 45 | +fn main { | ||
| 46 | + let g = { name: "MoonBit", times: 2, } | ||
| 47 | + for tone in [Plain, Loud, Question] { | ||
| 48 | + greet(g, tone~) | ||
| 49 | + } | ||
| 50 | + println("") | ||
| 51 | + println("the greeting itself: \{g}") | ||
| 52 | +} | ||
added
demos/hello/moon.mod +8 -0 | new file mode 100644 | ||
| @@ -0,0 +1,8 @@ | ||
| 1 | +// The module file. Turbo MoonBit walks up from the file you opened looking for | |
| 2 | +// one of these, and starts moon-lsp in the directory that holds it. | |
| 3 | + | |
| 4 | +name = "demo/hello" | |
| 5 | + | |
| 6 | +version = "0.1.0" | |
| 7 | + | |
| 8 | +license = "MIT" | |
| new file mode 100644 | |||
| @@ -0,0 +1,8 @@ | |||
| 1 | +// The module file. Turbo MoonBit walks up from the file you opened looking for | ||
| 2 | +// one of these, and starts moon-lsp in the directory that holds it. | ||
| 3 | + | ||
| 4 | +name = "demo/hello" | ||
| 5 | + | ||
| 6 | +version = "0.1.0" | ||
| 7 | + | ||
| 8 | +license = "MIT" | ||
added
demos/hello/moon.pkg +2 -0 | new file mode 100644 | ||
| @@ -0,0 +1,2 @@ | ||
| 1 | +// A package that builds a program rather than a library. | |
| 2 | +pkgtype(kind: "executable") | |
| new file mode 100644 | |||
| @@ -0,0 +1,2 @@ | |||
| 1 | +// A package that builds a program rather than a library. | ||
| 2 | +pkgtype(kind: "executable") | ||
added
demos/shapes/cmd/main/main.mbt +37 -0 | new file mode 100644 | ||
| @@ -0,0 +1,37 @@ | ||
| 1 | +///| | |
| 2 | +/// Measures a handful of shapes and prints what it found. | |
| 3 | +/// | |
| 4 | +/// Run it from the project root with `moon run cmd/main`, or from the | |
| 5 | +/// editor's MoonBit menu with **Run** and `cmd/main`. | |
| 6 | +fn main { | |
| 7 | + let circles = [ | |
| 8 | + @shapes.Circle::{ radius: 1.0, }, | |
| 9 | + @shapes.Circle::{ radius: 2.5, }, | |
| 10 | + @shapes.Circle::{ radius: 0.5, }, | |
| 11 | + ] | |
| 12 | + let rects = [ | |
| 13 | + @shapes.Rect::{ width: 3.0, height: 4.0, }, | |
| 14 | + @shapes.Rect::{ width: 1.5, height: 1.5, }, | |
| 15 | + ] | |
| 16 | + report("circles", circles) | |
| 17 | + report("rectangles", rects) | |
| 18 | + report("nothing at all", ([] : Array[@shapes.Circle])) | |
| 19 | +} | |
| 20 | + | |
| 21 | +///| | |
| 22 | +/// report prints the total and the largest of a list, and says so plainly when | |
| 23 | +/// the list is empty rather than letting the error escape. | |
| 24 | +fn[T : @shapes.Area + Show] report(what : String, shapes : Array[T]) -> Unit { | |
| 25 | + println("── \{what} ──") | |
| 26 | + try { | |
| 27 | + let sum = @shapes.total(shapes) | |
| 28 | + println(" total area: \{sum}") | |
| 29 | + } catch { | |
| 30 | + @shapes.NoShapes => println(" no shapes were given") | |
| 31 | + } | |
| 32 | + match @shapes.largest(shapes) { | |
| 33 | + Some(shape) => println(" largest: \{shape}") | |
| 34 | + None => println(" largest: none") | |
| 35 | + } | |
| 36 | + println("") | |
| 37 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,37 @@ | |||
| 1 | +///| | ||
| 2 | +/// Measures a handful of shapes and prints what it found. | ||
| 3 | +/// | ||
| 4 | +/// Run it from the project root with `moon run cmd/main`, or from the | ||
| 5 | +/// editor's MoonBit menu with **Run** and `cmd/main`. | ||
| 6 | +fn main { | ||
| 7 | + let circles = [ | ||
| 8 | + @shapes.Circle::{ radius: 1.0, }, | ||
| 9 | + @shapes.Circle::{ radius: 2.5, }, | ||
| 10 | + @shapes.Circle::{ radius: 0.5, }, | ||
| 11 | + ] | ||
| 12 | + let rects = [ | ||
| 13 | + @shapes.Rect::{ width: 3.0, height: 4.0, }, | ||
| 14 | + @shapes.Rect::{ width: 1.5, height: 1.5, }, | ||
| 15 | + ] | ||
| 16 | + report("circles", circles) | ||
| 17 | + report("rectangles", rects) | ||
| 18 | + report("nothing at all", ([] : Array[@shapes.Circle])) | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +///| | ||
| 22 | +/// report prints the total and the largest of a list, and says so plainly when | ||
| 23 | +/// the list is empty rather than letting the error escape. | ||
| 24 | +fn[T : @shapes.Area + Show] report(what : String, shapes : Array[T]) -> Unit { | ||
| 25 | + println("── \{what} ──") | ||
| 26 | + try { | ||
| 27 | + let sum = @shapes.total(shapes) | ||
| 28 | + println(" total area: \{sum}") | ||
| 29 | + } catch { | ||
| 30 | + @shapes.NoShapes => println(" no shapes were given") | ||
| 31 | + } | ||
| 32 | + match @shapes.largest(shapes) { | ||
| 33 | + Some(shape) => println(" largest: \{shape}") | ||
| 34 | + None => println(" largest: none") | ||
| 35 | + } | ||
| 36 | + println("") | ||
| 37 | +} | ||
added
demos/shapes/cmd/main/moon.pkg +5 -0 | new file mode 100644 | ||
| @@ -0,0 +1,5 @@ | ||
| 1 | +import { | |
| 2 | + "demo/shapes", | |
| 3 | +} | |
| 4 | + | |
| 5 | +pkgtype(kind: "executable") | |
| new file mode 100644 | |||
| @@ -0,0 +1,5 @@ | |||
| 1 | +import { | ||
| 2 | + "demo/shapes", | ||
| 3 | +} | ||
| 4 | + | ||
| 5 | +pkgtype(kind: "executable") | ||
added
demos/shapes/moon.mod +8 -0 | new file mode 100644 | ||
| @@ -0,0 +1,8 @@ | ||
| 1 | +// A library package at the root, and a program under cmd/main that uses it. | |
| 2 | +// Open any file in here and moon-lsp is started in this directory. | |
| 3 | + | |
| 4 | +name = "demo/shapes" | |
| 5 | + | |
| 6 | +version = "0.1.0" | |
| 7 | + | |
| 8 | +license = "MIT" | |
| new file mode 100644 | |||
| @@ -0,0 +1,8 @@ | |||
| 1 | +// A library package at the root, and a program under cmd/main that uses it. | ||
| 2 | +// Open any file in here and moon-lsp is started in this directory. | ||
| 3 | + | ||
| 4 | +name = "demo/shapes" | ||
| 5 | + | ||
| 6 | +version = "0.1.0" | ||
| 7 | + | ||
| 8 | +license = "MIT" | ||
added
demos/shapes/moon.pkg +1 -0 | new file mode 100644 | ||
| @@ -0,0 +1 @@ | ||
| 1 | + | |
| new file mode 100644 | |||
| @@ -0,0 +1 @@ | |||
| 1 | + | ||
added
demos/shapes/shapes.mbt +69 -0 | new file mode 100644 | ||
| @@ -0,0 +1,69 @@ | ||
| 1 | +///| | |
| 2 | +/// A shape that knows its own area. | |
| 3 | +pub(open) trait Area { | |
| 4 | + fn area(Self) -> Double | |
| 5 | +} | |
| 6 | + | |
| 7 | +///| | |
| 8 | +/// A circle, by its radius. | |
| 9 | +pub(all) struct Circle { | |
| 10 | + radius : Double | |
| 11 | +} derive(Eq, Debug) | |
| 12 | + | |
| 13 | +///| | |
| 14 | +/// A rectangle, by its two sides. | |
| 15 | +pub(all) struct Rect { | |
| 16 | + width : Double | |
| 17 | + height : Double | |
| 18 | +} derive(Eq, Debug) | |
| 19 | + | |
| 20 | +///| | |
| 21 | +pub impl Area for Circle with fn area(self) { | |
| 22 | + 3.141_592_653_589_793 * self.radius * self.radius | |
| 23 | +} | |
| 24 | + | |
| 25 | +///| | |
| 26 | +pub impl Area for Rect with fn area(self) { | |
| 27 | + self.width * self.height | |
| 28 | +} | |
| 29 | + | |
| 30 | +///| | |
| 31 | +pub impl Show for Circle with fn output(self, logger) { | |
| 32 | + logger.write_string("Circle(r=\{self.radius})") | |
| 33 | +} | |
| 34 | + | |
| 35 | +///| | |
| 36 | +pub impl Show for Rect with fn output(self, logger) { | |
| 37 | + logger.write_string("Rect(\{self.width}×\{self.height})") | |
| 38 | +} | |
| 39 | + | |
| 40 | +///| | |
| 41 | +/// Raised when a measurement is asked of nothing at all. | |
| 42 | +pub suberror NoShapes | |
| 43 | + | |
| 44 | +///| | |
| 45 | +/// total adds up the areas of every shape given. | |
| 46 | +/// | |
| 47 | +/// It is generic over anything that implements `Area`, so one function serves | |
| 48 | +/// circles, rectangles and whatever else somebody adds later. | |
| 49 | +pub fn[T : Area] total(shapes : Array[T]) -> Double raise NoShapes { | |
| 50 | + guard shapes.length() > 0 else { raise NoShapes } | |
| 51 | + let mut sum = 0.0 | |
| 52 | + for shape in shapes { | |
| 53 | + sum = sum + shape.area() | |
| 54 | + } | |
| 55 | + sum | |
| 56 | +} | |
| 57 | + | |
| 58 | +///| | |
| 59 | +/// largest returns the shape with the greatest area, or None for an empty list. | |
| 60 | +pub fn[T : Area] largest(shapes : Array[T]) -> T? { | |
| 61 | + let mut best : T? = None | |
| 62 | + for shape in shapes { | |
| 63 | + match best { | |
| 64 | + None => best = Some(shape) | |
| 65 | + Some(current) => if shape.area() > current.area() { best = Some(shape) } | |
| 66 | + } | |
| 67 | + } | |
| 68 | + best | |
| 69 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,69 @@ | |||
| 1 | +///| | ||
| 2 | +/// A shape that knows its own area. | ||
| 3 | +pub(open) trait Area { | ||
| 4 | + fn area(Self) -> Double | ||
| 5 | +} | ||
| 6 | + | ||
| 7 | +///| | ||
| 8 | +/// A circle, by its radius. | ||
| 9 | +pub(all) struct Circle { | ||
| 10 | + radius : Double | ||
| 11 | +} derive(Eq, Debug) | ||
| 12 | + | ||
| 13 | +///| | ||
| 14 | +/// A rectangle, by its two sides. | ||
| 15 | +pub(all) struct Rect { | ||
| 16 | + width : Double | ||
| 17 | + height : Double | ||
| 18 | +} derive(Eq, Debug) | ||
| 19 | + | ||
| 20 | +///| | ||
| 21 | +pub impl Area for Circle with fn area(self) { | ||
| 22 | + 3.141_592_653_589_793 * self.radius * self.radius | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +///| | ||
| 26 | +pub impl Area for Rect with fn area(self) { | ||
| 27 | + self.width * self.height | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +///| | ||
| 31 | +pub impl Show for Circle with fn output(self, logger) { | ||
| 32 | + logger.write_string("Circle(r=\{self.radius})") | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +///| | ||
| 36 | +pub impl Show for Rect with fn output(self, logger) { | ||
| 37 | + logger.write_string("Rect(\{self.width}×\{self.height})") | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +///| | ||
| 41 | +/// Raised when a measurement is asked of nothing at all. | ||
| 42 | +pub suberror NoShapes | ||
| 43 | + | ||
| 44 | +///| | ||
| 45 | +/// total adds up the areas of every shape given. | ||
| 46 | +/// | ||
| 47 | +/// It is generic over anything that implements `Area`, so one function serves | ||
| 48 | +/// circles, rectangles and whatever else somebody adds later. | ||
| 49 | +pub fn[T : Area] total(shapes : Array[T]) -> Double raise NoShapes { | ||
| 50 | + guard shapes.length() > 0 else { raise NoShapes } | ||
| 51 | + let mut sum = 0.0 | ||
| 52 | + for shape in shapes { | ||
| 53 | + sum = sum + shape.area() | ||
| 54 | + } | ||
| 55 | + sum | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +///| | ||
| 59 | +/// largest returns the shape with the greatest area, or None for an empty list. | ||
| 60 | +pub fn[T : Area] largest(shapes : Array[T]) -> T? { | ||
| 61 | + let mut best : T? = None | ||
| 62 | + for shape in shapes { | ||
| 63 | + match best { | ||
| 64 | + None => best = Some(shape) | ||
| 65 | + Some(current) => if shape.area() > current.area() { best = Some(shape) } | ||
| 66 | + } | ||
| 67 | + } | ||
| 68 | + best | ||
| 69 | +} | ||
added
demos/shapes/shapes_test.mbt +50 -0 | new file mode 100644 | ||
| @@ -0,0 +1,50 @@ | ||
| 1 | +// Blackbox tests: they see the package's public surface only, exactly as | |
| 2 | +// another package would. Run them with `moon test`, or from the editor's | |
| 3 | +// MoonBit menu with **Test**. | |
| 4 | + | |
| 5 | +///| | |
| 6 | +test "a circle knows its area" { | |
| 7 | + let c = @shapes.Circle::{ radius: 2.0, } | |
| 8 | + assert_true((c.area() - 12.566370614359172).abs() < 1.0e-9) | |
| 9 | +} | |
| 10 | + | |
| 11 | +///| | |
| 12 | +test "a rectangle knows its area" { | |
| 13 | + assert_eq(@shapes.Rect::{ width: 3.0, height: 4.0, }.area(), 12.0) | |
| 14 | +} | |
| 15 | + | |
| 16 | +///| | |
| 17 | +test "total adds every shape up" { | |
| 18 | + let rects = [ | |
| 19 | + @shapes.Rect::{ width: 2.0, height: 2.0, }, | |
| 20 | + @shapes.Rect::{ width: 1.0, height: 5.0, }, | |
| 21 | + ] | |
| 22 | + assert_eq(@shapes.total(rects), 9.0) | |
| 23 | +} | |
| 24 | + | |
| 25 | +///| | |
| 26 | +/// `catch` names the error; `noraise` is the branch taken when nothing was | |
| 27 | +/// raised at all, which is what makes this a real assertion rather than a | |
| 28 | +/// test that passes either way. | |
| 29 | +test "total refuses an empty list" { | |
| 30 | + let empty : Array[@shapes.Rect] = [] | |
| 31 | + try ignore(@shapes.total(empty)) catch { | |
| 32 | + @shapes.NoShapes => () | |
| 33 | + } noraise { | |
| 34 | + _ => fail("an empty list should have raised NoShapes") | |
| 35 | + } | |
| 36 | +} | |
| 37 | + | |
| 38 | +///| | |
| 39 | +test "largest picks the biggest, and None when there is nothing" { | |
| 40 | + let rects = [ | |
| 41 | + @shapes.Rect::{ width: 1.0, height: 1.0, }, | |
| 42 | + @shapes.Rect::{ width: 9.0, height: 9.0, }, | |
| 43 | + ] | |
| 44 | + assert_eq( | |
| 45 | + @shapes.largest(rects), | |
| 46 | + Some(@shapes.Rect::{ width: 9.0, height: 9.0, }), | |
| 47 | + ) | |
| 48 | + let empty : Array[@shapes.Rect] = [] | |
| 49 | + assert_eq(@shapes.largest(empty), None) | |
| 50 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,50 @@ | |||
| 1 | +// Blackbox tests: they see the package's public surface only, exactly as | ||
| 2 | +// another package would. Run them with `moon test`, or from the editor's | ||
| 3 | +// MoonBit menu with **Test**. | ||
| 4 | + | ||
| 5 | +///| | ||
| 6 | +test "a circle knows its area" { | ||
| 7 | + let c = @shapes.Circle::{ radius: 2.0, } | ||
| 8 | + assert_true((c.area() - 12.566370614359172).abs() < 1.0e-9) | ||
| 9 | +} | ||
| 10 | + | ||
| 11 | +///| | ||
| 12 | +test "a rectangle knows its area" { | ||
| 13 | + assert_eq(@shapes.Rect::{ width: 3.0, height: 4.0, }.area(), 12.0) | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +///| | ||
| 17 | +test "total adds every shape up" { | ||
| 18 | + let rects = [ | ||
| 19 | + @shapes.Rect::{ width: 2.0, height: 2.0, }, | ||
| 20 | + @shapes.Rect::{ width: 1.0, height: 5.0, }, | ||
| 21 | + ] | ||
| 22 | + assert_eq(@shapes.total(rects), 9.0) | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +///| | ||
| 26 | +/// `catch` names the error; `noraise` is the branch taken when nothing was | ||
| 27 | +/// raised at all, which is what makes this a real assertion rather than a | ||
| 28 | +/// test that passes either way. | ||
| 29 | +test "total refuses an empty list" { | ||
| 30 | + let empty : Array[@shapes.Rect] = [] | ||
| 31 | + try ignore(@shapes.total(empty)) catch { | ||
| 32 | + @shapes.NoShapes => () | ||
| 33 | + } noraise { | ||
| 34 | + _ => fail("an empty list should have raised NoShapes") | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +///| | ||
| 39 | +test "largest picks the biggest, and None when there is nothing" { | ||
| 40 | + let rects = [ | ||
| 41 | + @shapes.Rect::{ width: 1.0, height: 1.0, }, | ||
| 42 | + @shapes.Rect::{ width: 9.0, height: 9.0, }, | ||
| 43 | + ] | ||
| 44 | + assert_eq( | ||
| 45 | + @shapes.largest(rects), | ||
| 46 | + Some(@shapes.Rect::{ width: 9.0, height: 9.0, }), | ||
| 47 | + ) | ||
| 48 | + let empty : Array[@shapes.Rect] = [] | ||
| 49 | + assert_eq(@shapes.largest(empty), None) | ||
| 50 | +} | ||
added
demos/syntax-tour/moon.mod +8 -0 | new file mode 100644 | ||
| @@ -0,0 +1,8 @@ | ||
| 1 | +// Every construct the Turbo MoonBit scanner recognises, in one file that | |
| 2 | +// really compiles. Open tour.mbt and read the colours. | |
| 3 | + | |
| 4 | +name = "demo/syntax-tour" | |
| 5 | + | |
| 6 | +version = "0.1.0" | |
| 7 | + | |
| 8 | +license = "MIT" | |
| new file mode 100644 | |||
| @@ -0,0 +1,8 @@ | |||
| 1 | +// Every construct the Turbo MoonBit scanner recognises, in one file that | ||
| 2 | +// really compiles. Open tour.mbt and read the colours. | ||
| 3 | + | ||
| 4 | +name = "demo/syntax-tour" | ||
| 5 | + | ||
| 6 | +version = "0.1.0" | ||
| 7 | + | ||
| 8 | +license = "MIT" | ||
added
demos/syntax-tour/moon.pkg +1 -0 | new file mode 100644 | ||
| @@ -0,0 +1 @@ | ||
| 1 | +pkgtype(kind: "executable") | |
| new file mode 100644 | |||
| @@ -0,0 +1 @@ | |||
| 1 | +pkgtype(kind: "executable") | ||
added
demos/syntax-tour/tour.mbt +255 -0 | new file mode 100644 | ||
| @@ -0,0 +1,255 @@ | ||
| 1 | +// An ordinary line comment. | |
| 2 | + | |
| 3 | +///| | |
| 4 | +/// A doc comment. `///|` above is the separator MoonBit's own formatter puts | |
| 5 | +/// between top-level items — it is a comment too, and coloured as one. | |
| 6 | +/// | |
| 7 | +/// Everything below compiles. `moon check` reports no warnings and no errors, | |
| 8 | +/// which is the point: a colouring demo that does not build is a screenshot. | |
| 9 | + | |
| 10 | +// ── literals ──────────────────────────────────────────────────────────────── | |
| 11 | + | |
| 12 | +///| | |
| 13 | +fn literals() -> Unit { | |
| 14 | + // Strings, and the four other quoted forms. | |
| 15 | + let plain = "an ordinary string" | |
| 16 | + let escaped = "a quote \" and a backslash \\ and a newline \n" | |
| 17 | + let unicode = "\u{1F31C} é" | |
| 18 | + let bytes = b"\xDE\xAD\xBE\xEF" | |
| 19 | + let ch = 'x' | |
| 20 | + let escaped_char = '\n' | |
| 21 | + let byte_char = b'A' | |
| 22 | + | |
| 23 | + // Interpolation is one string span, brace to brace: the expression inside is | |
| 24 | + // deliberately not coloured as code. | |
| 25 | + let name = "MoonBit" | |
| 26 | + let interpolated = "hello \{name}, and \{1 + 2}" | |
| 27 | + | |
| 28 | + // The one line in this file the editor colours *wrongly*, kept on purpose. | |
| 29 | + // A string nested inside an interpolation ends the outer literal as far as | |
| 30 | + // the scanner is concerned, so `yes` and `no` below come out as identifiers | |
| 31 | + // rather than as part of the string. The compiler disagrees, and is right; | |
| 32 | + // finding the real end needs the parser. See reference/languages.md. | |
| 33 | + let nested = "answer: \{if true { "yes" } else { "no" }}" | |
| 34 | + | |
| 35 | + // A multi-line string is a run of lines, each complete in itself. #| is | |
| 36 | + // literal; $| interpolates. | |
| 37 | + let raw = | |
| 38 | + #| {"note": "braces and \backslashes are literal here"} | |
| 39 | + #| second line | |
| 40 | + let woven = | |
| 41 | + $| the name again: \{name} | |
| 42 | + $| and arithmetic: \{6 * 7} | |
| 43 | + | |
| 44 | + println(plain) | |
| 45 | + println(escaped) | |
| 46 | + println(unicode) | |
| 47 | + println("bytes: \{bytes.length()} of them") | |
| 48 | + println("chars: \{ch} \{escaped_char.to_int()} \{byte_char.to_int()}") | |
| 49 | + println(interpolated) | |
| 50 | + println(nested) | |
| 51 | + println(raw) | |
| 52 | + println(woven) | |
| 53 | +} | |
| 54 | + | |
| 55 | +// ── numbers ───────────────────────────────────────────────────────────────── | |
| 56 | + | |
| 57 | +///| | |
| 58 | +/// Every numeric form the grammar allows, including the suffixes — which are | |
| 59 | +/// upper case or they are not suffixes at all. | |
| 60 | +fn numbers() -> Unit { | |
| 61 | + let decimal = 1_000_000 | |
| 62 | + let hexadecimal = 0xFF_FF | |
| 63 | + let octal = 0o17 | |
| 64 | + let binary = 0b1010_1010 | |
| 65 | + let double = 1.5 | |
| 66 | + let trailing_point = 1.0 | |
| 67 | + let exponent = 1.5e-3 | |
| 68 | + let hex_float = 0x1.8p3 | |
| 69 | + let unsigned : UInt = 42U | |
| 70 | + let long : Int64 = 42L | |
| 71 | + let unsigned_long : UInt64 = 42UL | |
| 72 | + let big : BigInt = 42N | |
| 73 | + let single : Float = 1.0F | |
| 74 | + | |
| 75 | + // An integer ends before `..`, so this is 1, then ..=, then 5 — not the | |
| 76 | + // double `1.` followed by `.=5`. | |
| 77 | + let mut sum = 0 | |
| 78 | + for i in 1..<=5 { | |
| 79 | + sum = sum + i | |
| 80 | + } | |
| 81 | + for i in 0..<3 { | |
| 82 | + sum = sum - i | |
| 83 | + } | |
| 84 | + | |
| 85 | + println("\{decimal} \{hexadecimal} \{octal} \{binary}") | |
| 86 | + println("\{double} \{trailing_point} \{exponent} \{hex_float}") | |
| 87 | + println("\{unsigned} \{long} \{unsigned_long} \{big} \{single}") | |
| 88 | + println("range sum: \{sum}") | |
| 89 | +} | |
| 90 | + | |
| 91 | +// ── types, traits, and the case rule ──────────────────────────────────────── | |
| 92 | + | |
| 93 | +///| | |
| 94 | +/// A capitalised name can only be a type, a trait or a constructor — that is a | |
| 95 | +/// lexical rule in MoonBit, not a convention, so the scanner needs no table of | |
| 96 | +/// built-in type names. | |
| 97 | +pub(all) struct Point { | |
| 98 | + x : Int | |
| 99 | + y : Int | |
| 100 | +} derive(Eq, Debug) | |
| 101 | + | |
| 102 | +///| | |
| 103 | +pub(all) enum Shape { | |
| 104 | + Dot | |
| 105 | + Line(Point, Point) | |
| 106 | + Poly(Array[Point]) | |
| 107 | +} derive(Debug) | |
| 108 | + | |
| 109 | +///| | |
| 110 | +pub(open) trait Describe { | |
| 111 | + fn describe(Self) -> String | |
| 112 | +} | |
| 113 | + | |
| 114 | +///| | |
| 115 | +pub impl Describe for Point with fn describe(self) { | |
| 116 | + "Point(\{self.x}, \{self.y})" | |
| 117 | +} | |
| 118 | + | |
| 119 | +///| | |
| 120 | +pub impl Show for Point with fn output(self, logger) { | |
| 121 | + logger.write_string(self.describe()) | |
| 122 | +} | |
| 123 | + | |
| 124 | +///| | |
| 125 | +/// `extend` promotes a trait's method onto the type, so `p.describe()` works | |
| 126 | +/// as well as `Describe::describe(p)`. | |
| 127 | +extend Point with Describe::{describe} | |
| 128 | + | |
| 129 | +///| | |
| 130 | +/// A labelled argument with a default: the call site may leave it out. | |
| 131 | +fn walk(path : Array[Point], closed? : Bool = false) -> Int { | |
| 132 | + let steps = path.length() | |
| 133 | + if closed { | |
| 134 | + steps | |
| 135 | + } else { | |
| 136 | + steps - 1 | |
| 137 | + } | |
| 138 | +} | |
| 139 | + | |
| 140 | +// ── control flow ──────────────────────────────────────────────────────────── | |
| 141 | + | |
| 142 | +///| | |
| 143 | +/// Raised when a shape has no points to speak of. | |
| 144 | +pub suberror Empty | |
| 145 | + | |
| 146 | +///| | |
| 147 | +fn corners(shape : Shape) -> Int raise Empty { | |
| 148 | + match shape { | |
| 149 | + Dot => 1 | |
| 150 | + Line(_, _) => 2 | |
| 151 | + Poly(points) => { | |
| 152 | + guard points.length() > 0 else { raise Empty } | |
| 153 | + points.length() | |
| 154 | + } | |
| 155 | + } | |
| 156 | +} | |
| 157 | + | |
| 158 | +///| | |
| 159 | +fn control() -> Unit { | |
| 160 | + let square : Array[Point] = [ | |
| 161 | + { x: 0, y: 0, }, | |
| 162 | + { x: 1, y: 0, }, | |
| 163 | + { x: 1, y: 1, }, | |
| 164 | + { x: 0, y: 1, }, | |
| 165 | + ] | |
| 166 | + println("open path steps: \{walk(square)}") | |
| 167 | + println("closed path steps: \{walk(square, closed=true)}") | |
| 168 | + | |
| 169 | + for shape in [Dot, Line({ x: 0, y: 0, }, { x: 1, y: 1, }), Poly(square)] { | |
| 170 | + debug(shape) | |
| 171 | + println(" … has \{corners(shape)} corner(s)") catch { | |
| 172 | + Empty => println(" … has no corners") | |
| 173 | + } | |
| 174 | + } | |
| 175 | + | |
| 176 | + // A `for` loop carrying accumulators, with `break` to return a value and | |
| 177 | + // `continue` to go round again. (The older `loop (a, b) { … }` form is | |
| 178 | + // deprecated; this is what replaced it.) | |
| 179 | + let counted = for i = 0, acc = 0 { | |
| 180 | + if i >= 10 { | |
| 181 | + break acc | |
| 182 | + } else if i % 2 == 0 { | |
| 183 | + continue i + 1, acc + i | |
| 184 | + } else { | |
| 185 | + continue i + 1, acc | |
| 186 | + } | |
| 187 | + } | |
| 188 | + println("even numbers below ten add to \{counted}") | |
| 189 | + | |
| 190 | + // while, with a mutable binding. | |
| 191 | + let mut countdown = 3 | |
| 192 | + while countdown > 0 { | |
| 193 | + countdown = countdown - 1 | |
| 194 | + } | |
| 195 | + println("countdown reached \{countdown}") | |
| 196 | + | |
| 197 | + // Option and Result, and the four constructors the language's readers know. | |
| 198 | + let found : Int? = Some(7) | |
| 199 | + let missing : Int? = None | |
| 200 | + let good : Result[Int, String] = Ok(1) | |
| 201 | + let bad : Result[Int, String] = Err("nope") | |
| 202 | + // Option and Result are printed with `debug`: interpolating them would go | |
| 203 | + // through Show, which the toolchain now steers away from for debugging. | |
| 204 | + debug(found) | |
| 205 | + debug(missing) | |
| 206 | + debug(good) | |
| 207 | + debug(bad) | |
| 208 | + println("truth values: \{true} \{false}") | |
| 209 | + | |
| 210 | + // A tuple, and its accessor. | |
| 211 | + let pair = (1, "one") | |
| 212 | + println("pair.0 = \{pair.0}, pair.1 = \{pair.1}") | |
| 213 | + | |
| 214 | + // The pipe operator. | |
| 215 | + let piped = [3, 1, 2] |> sorted | |
| 216 | + println("piped:") | |
| 217 | + debug(piped) | |
| 218 | +} | |
| 219 | + | |
| 220 | +///| | |
| 221 | +fn sorted(xs : Array[Int]) -> Array[Int] { | |
| 222 | + let copy = xs.copy() | |
| 223 | + copy.sort() | |
| 224 | + copy | |
| 225 | +} | |
| 226 | + | |
| 227 | +// ── attributes ────────────────────────────────────────────────────────────── | |
| 228 | + | |
| 229 | +///| | |
| 230 | +/// An attribute takes the whole line: after the dotted name, everything up to | |
| 231 | +/// the newline is its raw payload. | |
| 232 | +#deprecated("kept only so the colouring has something to show") | |
| 233 | +pub fn old_name() -> Int { | |
| 234 | + 1 | |
| 235 | +} | |
| 236 | + | |
| 237 | +///| | |
| 238 | +/// A user-defined attribute has a namespace and is ignored by the compiler. | |
| 239 | +#custom.note(kind="demo", enabled=true) | |
| 240 | +fn annotated() -> Int { | |
| 241 | + 2 | |
| 242 | +} | |
| 243 | + | |
| 244 | +// ── the entry point ───────────────────────────────────────────────────────── | |
| 245 | + | |
| 246 | +///| | |
| 247 | +fn main { | |
| 248 | + literals() | |
| 249 | + println("") | |
| 250 | + numbers() | |
| 251 | + println("") | |
| 252 | + control() | |
| 253 | + println("") | |
| 254 | + println("annotated() = \{annotated()}") | |
| 255 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,255 @@ | |||
| 1 | +// An ordinary line comment. | ||
| 2 | + | ||
| 3 | +///| | ||
| 4 | +/// A doc comment. `///|` above is the separator MoonBit's own formatter puts | ||
| 5 | +/// between top-level items — it is a comment too, and coloured as one. | ||
| 6 | +/// | ||
| 7 | +/// Everything below compiles. `moon check` reports no warnings and no errors, | ||
| 8 | +/// which is the point: a colouring demo that does not build is a screenshot. | ||
| 9 | + | ||
| 10 | +// ── literals ──────────────────────────────────────────────────────────────── | ||
| 11 | + | ||
| 12 | +///| | ||
| 13 | +fn literals() -> Unit { | ||
| 14 | + // Strings, and the four other quoted forms. | ||
| 15 | + let plain = "an ordinary string" | ||
| 16 | + let escaped = "a quote \" and a backslash \\ and a newline \n" | ||
| 17 | + let unicode = "\u{1F31C} é" | ||
| 18 | + let bytes = b"\xDE\xAD\xBE\xEF" | ||
| 19 | + let ch = 'x' | ||
| 20 | + let escaped_char = '\n' | ||
| 21 | + let byte_char = b'A' | ||
| 22 | + | ||
| 23 | + // Interpolation is one string span, brace to brace: the expression inside is | ||
| 24 | + // deliberately not coloured as code. | ||
| 25 | + let name = "MoonBit" | ||
| 26 | + let interpolated = "hello \{name}, and \{1 + 2}" | ||
| 27 | + | ||
| 28 | + // The one line in this file the editor colours *wrongly*, kept on purpose. | ||
| 29 | + // A string nested inside an interpolation ends the outer literal as far as | ||
| 30 | + // the scanner is concerned, so `yes` and `no` below come out as identifiers | ||
| 31 | + // rather than as part of the string. The compiler disagrees, and is right; | ||
| 32 | + // finding the real end needs the parser. See reference/languages.md. | ||
| 33 | + let nested = "answer: \{if true { "yes" } else { "no" }}" | ||
| 34 | + | ||
| 35 | + // A multi-line string is a run of lines, each complete in itself. #| is | ||
| 36 | + // literal; $| interpolates. | ||
| 37 | + let raw = | ||
| 38 | + #| {"note": "braces and \backslashes are literal here"} | ||
| 39 | + #| second line | ||
| 40 | + let woven = | ||
| 41 | + $| the name again: \{name} | ||
| 42 | + $| and arithmetic: \{6 * 7} | ||
| 43 | + | ||
| 44 | + println(plain) | ||
| 45 | + println(escaped) | ||
| 46 | + println(unicode) | ||
| 47 | + println("bytes: \{bytes.length()} of them") | ||
| 48 | + println("chars: \{ch} \{escaped_char.to_int()} \{byte_char.to_int()}") | ||
| 49 | + println(interpolated) | ||
| 50 | + println(nested) | ||
| 51 | + println(raw) | ||
| 52 | + println(woven) | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +// ── numbers ───────────────────────────────────────────────────────────────── | ||
| 56 | + | ||
| 57 | +///| | ||
| 58 | +/// Every numeric form the grammar allows, including the suffixes — which are | ||
| 59 | +/// upper case or they are not suffixes at all. | ||
| 60 | +fn numbers() -> Unit { | ||
| 61 | + let decimal = 1_000_000 | ||
| 62 | + let hexadecimal = 0xFF_FF | ||
| 63 | + let octal = 0o17 | ||
| 64 | + let binary = 0b1010_1010 | ||
| 65 | + let double = 1.5 | ||
| 66 | + let trailing_point = 1.0 | ||
| 67 | + let exponent = 1.5e-3 | ||
| 68 | + let hex_float = 0x1.8p3 | ||
| 69 | + let unsigned : UInt = 42U | ||
| 70 | + let long : Int64 = 42L | ||
| 71 | + let unsigned_long : UInt64 = 42UL | ||
| 72 | + let big : BigInt = 42N | ||
| 73 | + let single : Float = 1.0F | ||
| 74 | + | ||
| 75 | + // An integer ends before `..`, so this is 1, then ..=, then 5 — not the | ||
| 76 | + // double `1.` followed by `.=5`. | ||
| 77 | + let mut sum = 0 | ||
| 78 | + for i in 1..<=5 { | ||
| 79 | + sum = sum + i | ||
| 80 | + } | ||
| 81 | + for i in 0..<3 { | ||
| 82 | + sum = sum - i | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + println("\{decimal} \{hexadecimal} \{octal} \{binary}") | ||
| 86 | + println("\{double} \{trailing_point} \{exponent} \{hex_float}") | ||
| 87 | + println("\{unsigned} \{long} \{unsigned_long} \{big} \{single}") | ||
| 88 | + println("range sum: \{sum}") | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +// ── types, traits, and the case rule ──────────────────────────────────────── | ||
| 92 | + | ||
| 93 | +///| | ||
| 94 | +/// A capitalised name can only be a type, a trait or a constructor — that is a | ||
| 95 | +/// lexical rule in MoonBit, not a convention, so the scanner needs no table of | ||
| 96 | +/// built-in type names. | ||
| 97 | +pub(all) struct Point { | ||
| 98 | + x : Int | ||
| 99 | + y : Int | ||
| 100 | +} derive(Eq, Debug) | ||
| 101 | + | ||
| 102 | +///| | ||
| 103 | +pub(all) enum Shape { | ||
| 104 | + Dot | ||
| 105 | + Line(Point, Point) | ||
| 106 | + Poly(Array[Point]) | ||
| 107 | +} derive(Debug) | ||
| 108 | + | ||
| 109 | +///| | ||
| 110 | +pub(open) trait Describe { | ||
| 111 | + fn describe(Self) -> String | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +///| | ||
| 115 | +pub impl Describe for Point with fn describe(self) { | ||
| 116 | + "Point(\{self.x}, \{self.y})" | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +///| | ||
| 120 | +pub impl Show for Point with fn output(self, logger) { | ||
| 121 | + logger.write_string(self.describe()) | ||
| 122 | +} | ||
| 123 | + | ||
| 124 | +///| | ||
| 125 | +/// `extend` promotes a trait's method onto the type, so `p.describe()` works | ||
| 126 | +/// as well as `Describe::describe(p)`. | ||
| 127 | +extend Point with Describe::{describe} | ||
| 128 | + | ||
| 129 | +///| | ||
| 130 | +/// A labelled argument with a default: the call site may leave it out. | ||
| 131 | +fn walk(path : Array[Point], closed? : Bool = false) -> Int { | ||
| 132 | + let steps = path.length() | ||
| 133 | + if closed { | ||
| 134 | + steps | ||
| 135 | + } else { | ||
| 136 | + steps - 1 | ||
| 137 | + } | ||
| 138 | +} | ||
| 139 | + | ||
| 140 | +// ── control flow ──────────────────────────────────────────────────────────── | ||
| 141 | + | ||
| 142 | +///| | ||
| 143 | +/// Raised when a shape has no points to speak of. | ||
| 144 | +pub suberror Empty | ||
| 145 | + | ||
| 146 | +///| | ||
| 147 | +fn corners(shape : Shape) -> Int raise Empty { | ||
| 148 | + match shape { | ||
| 149 | + Dot => 1 | ||
| 150 | + Line(_, _) => 2 | ||
| 151 | + Poly(points) => { | ||
| 152 | + guard points.length() > 0 else { raise Empty } | ||
| 153 | + points.length() | ||
| 154 | + } | ||
| 155 | + } | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +///| | ||
| 159 | +fn control() -> Unit { | ||
| 160 | + let square : Array[Point] = [ | ||
| 161 | + { x: 0, y: 0, }, | ||
| 162 | + { x: 1, y: 0, }, | ||
| 163 | + { x: 1, y: 1, }, | ||
| 164 | + { x: 0, y: 1, }, | ||
| 165 | + ] | ||
| 166 | + println("open path steps: \{walk(square)}") | ||
| 167 | + println("closed path steps: \{walk(square, closed=true)}") | ||
| 168 | + | ||
| 169 | + for shape in [Dot, Line({ x: 0, y: 0, }, { x: 1, y: 1, }), Poly(square)] { | ||
| 170 | + debug(shape) | ||
| 171 | + println(" … has \{corners(shape)} corner(s)") catch { | ||
| 172 | + Empty => println(" … has no corners") | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | + | ||
| 176 | + // A `for` loop carrying accumulators, with `break` to return a value and | ||
| 177 | + // `continue` to go round again. (The older `loop (a, b) { … }` form is | ||
| 178 | + // deprecated; this is what replaced it.) | ||
| 179 | + let counted = for i = 0, acc = 0 { | ||
| 180 | + if i >= 10 { | ||
| 181 | + break acc | ||
| 182 | + } else if i % 2 == 0 { | ||
| 183 | + continue i + 1, acc + i | ||
| 184 | + } else { | ||
| 185 | + continue i + 1, acc | ||
| 186 | + } | ||
| 187 | + } | ||
| 188 | + println("even numbers below ten add to \{counted}") | ||
| 189 | + | ||
| 190 | + // while, with a mutable binding. | ||
| 191 | + let mut countdown = 3 | ||
| 192 | + while countdown > 0 { | ||
| 193 | + countdown = countdown - 1 | ||
| 194 | + } | ||
| 195 | + println("countdown reached \{countdown}") | ||
| 196 | + | ||
| 197 | + // Option and Result, and the four constructors the language's readers know. | ||
| 198 | + let found : Int? = Some(7) | ||
| 199 | + let missing : Int? = None | ||
| 200 | + let good : Result[Int, String] = Ok(1) | ||
| 201 | + let bad : Result[Int, String] = Err("nope") | ||
| 202 | + // Option and Result are printed with `debug`: interpolating them would go | ||
| 203 | + // through Show, which the toolchain now steers away from for debugging. | ||
| 204 | + debug(found) | ||
| 205 | + debug(missing) | ||
| 206 | + debug(good) | ||
| 207 | + debug(bad) | ||
| 208 | + println("truth values: \{true} \{false}") | ||
| 209 | + | ||
| 210 | + // A tuple, and its accessor. | ||
| 211 | + let pair = (1, "one") | ||
| 212 | + println("pair.0 = \{pair.0}, pair.1 = \{pair.1}") | ||
| 213 | + | ||
| 214 | + // The pipe operator. | ||
| 215 | + let piped = [3, 1, 2] |> sorted | ||
| 216 | + println("piped:") | ||
| 217 | + debug(piped) | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +///| | ||
| 221 | +fn sorted(xs : Array[Int]) -> Array[Int] { | ||
| 222 | + let copy = xs.copy() | ||
| 223 | + copy.sort() | ||
| 224 | + copy | ||
| 225 | +} | ||
| 226 | + | ||
| 227 | +// ── attributes ────────────────────────────────────────────────────────────── | ||
| 228 | + | ||
| 229 | +///| | ||
| 230 | +/// An attribute takes the whole line: after the dotted name, everything up to | ||
| 231 | +/// the newline is its raw payload. | ||
| 232 | +#deprecated("kept only so the colouring has something to show") | ||
| 233 | +pub fn old_name() -> Int { | ||
| 234 | + 1 | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +///| | ||
| 238 | +/// A user-defined attribute has a namespace and is ignored by the compiler. | ||
| 239 | +#custom.note(kind="demo", enabled=true) | ||
| 240 | +fn annotated() -> Int { | ||
| 241 | + 2 | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +// ── the entry point ───────────────────────────────────────────────────────── | ||
| 245 | + | ||
| 246 | +///| | ||
| 247 | +fn main { | ||
| 248 | + literals() | ||
| 249 | + println("") | ||
| 250 | + numbers() | ||
| 251 | + println("") | ||
| 252 | + control() | ||
| 253 | + println("") | ||
| 254 | + println("annotated() = \{annotated()}") | ||
| 255 | +} | ||
added
diagram_test.go +202 -0 | new file mode 100644 | ||
| @@ -0,0 +1,202 @@ | ||
| 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. This diagram began as Turbo Python's, which is | |
| 22 | +// exactly the provenance the four checks below exist to catch. | |
| 23 | + | |
| 24 | +// diagramFile is the drawio the documentation links to. | |
| 25 | +const diagramFile = "docs/diagrams/packages.drawio" | |
| 26 | + | |
| 27 | +// mxFile is as much of drawio's format as these tests need: every cell, with | |
| 28 | +// its label, and — for an arrow — the two cells it joins. | |
| 29 | +type mxFile struct { | |
| 30 | + Host string `xml:"host,attr"` | |
| 31 | + Cells []mxCell `xml:"diagram>mxGraphModel>root>mxCell"` | |
| 32 | +} | |
| 33 | + | |
| 34 | +type mxCell struct { | |
| 35 | + ID string `xml:"id,attr"` | |
| 36 | + Value string `xml:"value,attr"` | |
| 37 | + Edge string `xml:"edge,attr"` | |
| 38 | + Source string `xml:"source,attr"` | |
| 39 | + Target string `xml:"target,attr"` | |
| 40 | +} | |
| 41 | + | |
| 42 | +// boldLabel is the package name inside a box: drawio stores the label as | |
| 43 | +// escaped HTML, and the name is the part in bold. | |
| 44 | +var boldLabel = regexp.MustCompile(`(?s)<b>(.*?)</b>`) | |
| 45 | + | |
| 46 | +// readDiagram parses the diagram, failing the test rather than returning an | |
| 47 | +// error — a diagram that will not parse is not a case any caller can handle. | |
| 48 | +func readDiagram(t *testing.T) mxFile { | |
| 49 | + t.Helper() | |
| 50 | + | |
| 51 | + raw, err := os.ReadFile(diagramFile) | |
| 52 | + if err != nil { | |
| 53 | + t.Fatalf("reading %s: %v", diagramFile, err) | |
| 54 | + } | |
| 55 | + | |
| 56 | + var file mxFile | |
| 57 | + if err := xml.Unmarshal(raw, &file); err != nil { | |
| 58 | + t.Fatalf("parsing %s: %v", diagramFile, err) | |
| 59 | + } | |
| 60 | + return file | |
| 61 | +} | |
| 62 | + | |
| 63 | +// boxes maps each box's package name to the id the arrows use for it. | |
| 64 | +func boxes(t *testing.T, file mxFile) map[string]string { | |
| 65 | + t.Helper() | |
| 66 | + | |
| 67 | + found := map[string]string{} | |
| 68 | + for _, cell := range file.Cells { | |
| 69 | + if cell.Edge == "1" || cell.Value == "" { | |
| 70 | + continue | |
| 71 | + } | |
| 72 | + label := html.UnescapeString(cell.Value) | |
| 73 | + // A box's package name is the part in bold, where there is one; the | |
| 74 | + // third-party box carries its name plain, with nothing to tell apart | |
| 75 | + // from it. | |
| 76 | + if match := boldLabel.FindStringSubmatch(label); match != nil { | |
| 77 | + label = match[1] | |
| 78 | + } | |
| 79 | + found[label] = cell.ID | |
| 80 | + } | |
| 81 | + return found | |
| 82 | +} | |
| 83 | + | |
| 84 | +// imports asks the toolchain what a package imports, shortened to the names the | |
| 85 | +// diagram uses: the last element for a turbo-core package, the module-relative | |
| 86 | +// path for one of ours, and "tcell/v2" for the one third-party dependency. | |
| 87 | +func imports(t *testing.T, pkg string) []string { | |
| 88 | + t.Helper() | |
| 89 | + | |
| 90 | + out, err := exec.Command("go", "list", "-f", `{{join .Imports "\n"}}`, pkg).Output() | |
| 91 | + if err != nil { | |
| 92 | + t.Fatalf("go list %s: %v", pkg, err) | |
| 93 | + } | |
| 94 | + | |
| 95 | + var names []string | |
| 96 | + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { | |
| 97 | + switch { | |
| 98 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-core/"): | |
| 99 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-core/")) | |
| 100 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-moonbit/"): | |
| 101 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-moonbit/")) | |
| 102 | + case strings.HasPrefix(line, "github.com/gdamore/tcell/"): | |
| 103 | + names = append(names, "tcell/v2") | |
| 104 | + } | |
| 105 | + } | |
| 106 | + sort.Strings(names) | |
| 107 | + return names | |
| 108 | +} | |
| 109 | + | |
| 110 | +// The boxes are exactly the packages the two packages of this module import, | |
| 111 | +// plus the two packages themselves. A box for a package nothing imports is as | |
| 112 | +// wrong as a missing one: both tell a reader something untrue about the code. | |
| 113 | +func TestTheDiagramDrawsExactlyThePackagesThisModuleImports(t *testing.T) { | |
| 114 | + drawn := boxes(t, readDiagram(t)) | |
| 115 | + | |
| 116 | + want := map[string]bool{"main": true, "internal/moonbitlang": true} | |
| 117 | + for _, pkg := range append(imports(t, "."), imports(t, "./internal/moonbitlang")...) { | |
| 118 | + want[pkg] = true | |
| 119 | + } | |
| 120 | + | |
| 121 | + for name := range want { | |
| 122 | + if _, ok := drawn[name]; !ok { | |
| 123 | + t.Errorf("%s draws no box for %q", diagramFile, name) | |
| 124 | + } | |
| 125 | + } | |
| 126 | + for name := range drawn { | |
| 127 | + if !want[name] { | |
| 128 | + t.Errorf("%s draws a box for %q, which nothing in this module imports", diagramFile, name) | |
| 129 | + } | |
| 130 | + } | |
| 131 | +} | |
| 132 | + | |
| 133 | +// Every arrow leaving one of our two boxes is an import that exists. This is | |
| 134 | +// the half that caught the copied diagram: an arrow drawn out of a box labelled | |
| 135 | +// internal/rustlang cannot be checked at all until the box is named right. | |
| 136 | +func TestEveryArrowOutOfOurPackagesIsARealImport(t *testing.T) { | |
| 137 | + file := readDiagram(t) | |
| 138 | + drawn := boxes(t, file) | |
| 139 | + | |
| 140 | + byID := map[string]string{} | |
| 141 | + for name, id := range drawn { | |
| 142 | + byID[id] = name | |
| 143 | + } | |
| 144 | + | |
| 145 | + ours := map[string]string{"main": ".", "internal/moonbitlang": "./internal/moonbitlang"} | |
| 146 | + for _, cell := range file.Cells { | |
| 147 | + if cell.Edge != "1" { | |
| 148 | + continue | |
| 149 | + } | |
| 150 | + from, ok := byID[cell.Source] | |
| 151 | + if !ok { | |
| 152 | + t.Errorf("%s draws an arrow out of unknown cell %q", diagramFile, cell.Source) | |
| 153 | + continue | |
| 154 | + } | |
| 155 | + pkg, ok := ours[from] | |
| 156 | + if !ok { | |
| 157 | + continue | |
| 158 | + } | |
| 159 | + | |
| 160 | + to := byID[cell.Target] | |
| 161 | + if to == "internal/moonbitlang" && from == "main" { | |
| 162 | + continue // main imports it under its full path, already shortened | |
| 163 | + } | |
| 164 | + if !slicesContain(imports(t, pkg), to) { | |
| 165 | + t.Errorf("%s draws %s → %s, but %s imports no such package", diagramFile, from, to, from) | |
| 166 | + } | |
| 167 | + } | |
| 168 | +} | |
| 169 | + | |
| 170 | +// The file's host attribute names the project it was drawn for. It is the one | |
| 171 | +// field a reader never sees and a copy always keeps. | |
| 172 | +func TestTheDiagramSaysWhichProjectItWasDrawnFor(t *testing.T) { | |
| 173 | + if host := readDiagram(t).Host; host != "turbo-moonbit" { | |
| 174 | + t.Errorf("%s was drawn for %q, not turbo-moonbit", diagramFile, host) | |
| 175 | + } | |
| 176 | +} | |
| 177 | + | |
| 178 | +// No label anywhere in the diagram names another editor in the family, or the | |
| 179 | +// language it edits. The copied diagram said "the Rust scanner" in prose that | |
| 180 | +// no identifier check would have looked at. | |
| 181 | +func TestNoLabelInTheDiagramNamesAnotherEditorsLanguage(t *testing.T) { | |
| 182 | + for _, cell := range readDiagram(t).Cells { | |
| 183 | + label := html.UnescapeString(cell.Value) | |
| 184 | + for _, other := range []string{"pythonlang", "rustlang", "golang", "Python", "Rust", "Go ", "turbo-python", "turbo-rust", "turbo-go"} { | |
| 185 | + if strings.Contains(label, other) { | |
| 186 | + t.Errorf("%s labels a cell %q, which names %q", diagramFile, label, other) | |
| 187 | + } | |
| 188 | + } | |
| 189 | + } | |
| 190 | +} | |
| 191 | + | |
| 192 | +// slicesContain says whether a sorted list holds a value. It is here rather | |
| 193 | +// than from the standard library's slices package so the test reads the same | |
| 194 | +// way in a checkout of any Go version this module supports. | |
| 195 | +func slicesContain(list []string, want string) bool { | |
| 196 | + for _, got := range list { | |
| 197 | + if got == want { | |
| 198 | + return true | |
| 199 | + } | |
| 200 | + } | |
| 201 | + return false | |
| 202 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,202 @@ | |||
| 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. This diagram began as Turbo Python's, which is | ||
| 22 | +// exactly the provenance the four checks below exist to catch. | ||
| 23 | + | ||
| 24 | +// diagramFile is the drawio the documentation links to. | ||
| 25 | +const diagramFile = "docs/diagrams/packages.drawio" | ||
| 26 | + | ||
| 27 | +// mxFile is as much of drawio's format as these tests need: every cell, with | ||
| 28 | +// its label, and — for an arrow — the two cells it joins. | ||
| 29 | +type mxFile struct { | ||
| 30 | + Host string `xml:"host,attr"` | ||
| 31 | + Cells []mxCell `xml:"diagram>mxGraphModel>root>mxCell"` | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +type mxCell struct { | ||
| 35 | + ID string `xml:"id,attr"` | ||
| 36 | + Value string `xml:"value,attr"` | ||
| 37 | + Edge string `xml:"edge,attr"` | ||
| 38 | + Source string `xml:"source,attr"` | ||
| 39 | + Target string `xml:"target,attr"` | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +// boldLabel is the package name inside a box: drawio stores the label as | ||
| 43 | +// escaped HTML, and the name is the part in bold. | ||
| 44 | +var boldLabel = regexp.MustCompile(`(?s)<b>(.*?)</b>`) | ||
| 45 | + | ||
| 46 | +// readDiagram parses the diagram, failing the test rather than returning an | ||
| 47 | +// error — a diagram that will not parse is not a case any caller can handle. | ||
| 48 | +func readDiagram(t *testing.T) mxFile { | ||
| 49 | + t.Helper() | ||
| 50 | + | ||
| 51 | + raw, err := os.ReadFile(diagramFile) | ||
| 52 | + if err != nil { | ||
| 53 | + t.Fatalf("reading %s: %v", diagramFile, err) | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + var file mxFile | ||
| 57 | + if err := xml.Unmarshal(raw, &file); err != nil { | ||
| 58 | + t.Fatalf("parsing %s: %v", diagramFile, err) | ||
| 59 | + } | ||
| 60 | + return file | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +// boxes maps each box's package name to the id the arrows use for it. | ||
| 64 | +func boxes(t *testing.T, file mxFile) map[string]string { | ||
| 65 | + t.Helper() | ||
| 66 | + | ||
| 67 | + found := map[string]string{} | ||
| 68 | + for _, cell := range file.Cells { | ||
| 69 | + if cell.Edge == "1" || cell.Value == "" { | ||
| 70 | + continue | ||
| 71 | + } | ||
| 72 | + label := html.UnescapeString(cell.Value) | ||
| 73 | + // A box's package name is the part in bold, where there is one; the | ||
| 74 | + // third-party box carries its name plain, with nothing to tell apart | ||
| 75 | + // from it. | ||
| 76 | + if match := boldLabel.FindStringSubmatch(label); match != nil { | ||
| 77 | + label = match[1] | ||
| 78 | + } | ||
| 79 | + found[label] = cell.ID | ||
| 80 | + } | ||
| 81 | + return found | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +// imports asks the toolchain what a package imports, shortened to the names the | ||
| 85 | +// diagram uses: the last element for a turbo-core package, the module-relative | ||
| 86 | +// path for one of ours, and "tcell/v2" for the one third-party dependency. | ||
| 87 | +func imports(t *testing.T, pkg string) []string { | ||
| 88 | + t.Helper() | ||
| 89 | + | ||
| 90 | + out, err := exec.Command("go", "list", "-f", `{{join .Imports "\n"}}`, pkg).Output() | ||
| 91 | + if err != nil { | ||
| 92 | + t.Fatalf("go list %s: %v", pkg, err) | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + var names []string | ||
| 96 | + for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { | ||
| 97 | + switch { | ||
| 98 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-core/"): | ||
| 99 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-core/")) | ||
| 100 | + case strings.HasPrefix(line, "rickub.com/turbo-editors/turbo-moonbit/"): | ||
| 101 | + names = append(names, strings.TrimPrefix(line, "rickub.com/turbo-editors/turbo-moonbit/")) | ||
| 102 | + case strings.HasPrefix(line, "github.com/gdamore/tcell/"): | ||
| 103 | + names = append(names, "tcell/v2") | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | + sort.Strings(names) | ||
| 107 | + return names | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +// The boxes are exactly the packages the two packages of this module import, | ||
| 111 | +// plus the two packages themselves. A box for a package nothing imports is as | ||
| 112 | +// wrong as a missing one: both tell a reader something untrue about the code. | ||
| 113 | +func TestTheDiagramDrawsExactlyThePackagesThisModuleImports(t *testing.T) { | ||
| 114 | + drawn := boxes(t, readDiagram(t)) | ||
| 115 | + | ||
| 116 | + want := map[string]bool{"main": true, "internal/moonbitlang": true} | ||
| 117 | + for _, pkg := range append(imports(t, "."), imports(t, "./internal/moonbitlang")...) { | ||
| 118 | + want[pkg] = true | ||
| 119 | + } | ||
| 120 | + | ||
| 121 | + for name := range want { | ||
| 122 | + if _, ok := drawn[name]; !ok { | ||
| 123 | + t.Errorf("%s draws no box for %q", diagramFile, name) | ||
| 124 | + } | ||
| 125 | + } | ||
| 126 | + for name := range drawn { | ||
| 127 | + if !want[name] { | ||
| 128 | + t.Errorf("%s draws a box for %q, which nothing in this module imports", diagramFile, name) | ||
| 129 | + } | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +// Every arrow leaving one of our two boxes is an import that exists. This is | ||
| 134 | +// the half that caught the copied diagram: an arrow drawn out of a box labelled | ||
| 135 | +// internal/rustlang cannot be checked at all until the box is named right. | ||
| 136 | +func TestEveryArrowOutOfOurPackagesIsARealImport(t *testing.T) { | ||
| 137 | + file := readDiagram(t) | ||
| 138 | + drawn := boxes(t, file) | ||
| 139 | + | ||
| 140 | + byID := map[string]string{} | ||
| 141 | + for name, id := range drawn { | ||
| 142 | + byID[id] = name | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + ours := map[string]string{"main": ".", "internal/moonbitlang": "./internal/moonbitlang"} | ||
| 146 | + for _, cell := range file.Cells { | ||
| 147 | + if cell.Edge != "1" { | ||
| 148 | + continue | ||
| 149 | + } | ||
| 150 | + from, ok := byID[cell.Source] | ||
| 151 | + if !ok { | ||
| 152 | + t.Errorf("%s draws an arrow out of unknown cell %q", diagramFile, cell.Source) | ||
| 153 | + continue | ||
| 154 | + } | ||
| 155 | + pkg, ok := ours[from] | ||
| 156 | + if !ok { | ||
| 157 | + continue | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + to := byID[cell.Target] | ||
| 161 | + if to == "internal/moonbitlang" && from == "main" { | ||
| 162 | + continue // main imports it under its full path, already shortened | ||
| 163 | + } | ||
| 164 | + if !slicesContain(imports(t, pkg), to) { | ||
| 165 | + t.Errorf("%s draws %s → %s, but %s imports no such package", diagramFile, from, to, from) | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +// The file's host attribute names the project it was drawn for. It is the one | ||
| 171 | +// field a reader never sees and a copy always keeps. | ||
| 172 | +func TestTheDiagramSaysWhichProjectItWasDrawnFor(t *testing.T) { | ||
| 173 | + if host := readDiagram(t).Host; host != "turbo-moonbit" { | ||
| 174 | + t.Errorf("%s was drawn for %q, not turbo-moonbit", diagramFile, host) | ||
| 175 | + } | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +// No label anywhere in the diagram names another editor in the family, or the | ||
| 179 | +// language it edits. The copied diagram said "the Rust scanner" in prose that | ||
| 180 | +// no identifier check would have looked at. | ||
| 181 | +func TestNoLabelInTheDiagramNamesAnotherEditorsLanguage(t *testing.T) { | ||
| 182 | + for _, cell := range readDiagram(t).Cells { | ||
| 183 | + label := html.UnescapeString(cell.Value) | ||
| 184 | + for _, other := range []string{"pythonlang", "rustlang", "golang", "Python", "Rust", "Go ", "turbo-python", "turbo-rust", "turbo-go"} { | ||
| 185 | + if strings.Contains(label, other) { | ||
| 186 | + t.Errorf("%s labels a cell %q, which names %q", diagramFile, label, other) | ||
| 187 | + } | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | +} | ||
| 191 | + | ||
| 192 | +// slicesContain says whether a sorted list holds a value. It is here rather | ||
| 193 | +// than from the standard library's slices package so the test reads the same | ||
| 194 | +// way in a checkout of any Go version this module supports. | ||
| 195 | +func slicesContain(list []string, want string) bool { | ||
| 196 | + for _, got := range list { | ||
| 197 | + if got == want { | ||
| 198 | + return true | ||
| 199 | + } | ||
| 200 | + } | ||
| 201 | + return false | ||
| 202 | +} | ||
added
docs/README.md +10 -0 | new file mode 100644 | ||
| @@ -0,0 +1,10 @@ | ||
| 1 | +# Turbo MoonBit — 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 MoonBit — 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-moonbit" 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/moonbitlang</b><br/><font style='font-size:10px'>the profile and the MoonBit 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-moonbit" 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/moonbitlang</b><br/><font style='font-size:10px'>the profile and the MoonBit 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 +61 -0 | new file mode 100644 | ||
| @@ -0,0 +1,61 @@ | ||
| 1 | +# Turbo MoonBit — documentation | |
| 2 | + | |
| 3 | +Turbo MoonBit is a Turbo C-style editor for MoonBit: a full-screen terminal IDE with menus, movable windows, syntax colouring for nine languages, themes, completion from `moon-lsp`, shell windows, per-project settings, a project tree, snippets, and the MoonBit 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 MoonBit program in Turbo MoonBit](tutorials/getting-started.md) — install it, write a program, format it, run it, break it and see the editor say where. | |
| 17 | +- [Demo projects](../../demos/) — three MoonBit projects to open in the editor once you have it: a small one, one with a library and tests, and a tour of every construct the scanner colours. | |
| 18 | + | |
| 19 | +## How-to guides — recipes for a task | |
| 20 | + | |
| 21 | +- [How to install and build Turbo MoonBit](how-to/install.md) | |
| 22 | +- [How to install the MoonBit toolchain](how-to/install-the-moonbit-toolchain.md) | |
| 23 | +- [How to run the tests](how-to/run-the-tests.md) | |
| 24 | +- [How to enable MoonBit completion](how-to/enable-completion.md) | |
| 25 | +- [How to write your own theme](how-to/write-a-theme.md) | |
| 26 | +- [How to move around a file](how-to/navigate-code.md) | |
| 27 | +- [How to ask what the code means](how-to/ask-about-code.md) | |
| 28 | +- [How to run shell commands without leaving the editor](how-to/use-a-terminal.md) | |
| 29 | +- [How to give a project its own settings](how-to/configure-a-project.md) | |
| 30 | +- [How to browse a project and open files from a tree](how-to/browse-a-project.md) | |
| 31 | +- [How to insert snippets from a menu](how-to/use-snippets.md) | |
| 32 | +- [How to run moon commands from the editor](how-to/run-moon-commands.md) | |
| 33 | +- [How to make a release](how-to/make-a-release.md) | |
| 34 | +- [How to talk to a coding agent from the editor](how-to/talk-to-an-agent.md) | |
| 35 | + | |
| 36 | +## Reference — the exact details | |
| 37 | + | |
| 38 | +- [Command line](reference/cli.md) | |
| 39 | +- [Keyboard](reference/keyboard.md) | |
| 40 | +- [Menus](reference/menus.md) | |
| 41 | +- [Theme file format](reference/themes.md) | |
| 42 | +- [Terminal windows](reference/terminal.md) | |
| 43 | +- [Project settings](reference/project-settings.md) | |
| 44 | +- [Project tree](reference/project-tree.md) | |
| 45 | +- [Languages coloured](reference/languages.md) | |
| 46 | +- [Snippets](reference/snippets.md) | |
| 47 | +- [MoonBit tools](reference/moonbit-tools.md) | |
| 48 | +- [The version number](reference/versioning.md) | |
| 49 | +- [Agents and ACP](reference/acp.md) | |
| 50 | + | |
| 51 | +## Explanation — understanding | |
| 52 | + | |
| 53 | +- [Architecture](explanation/architecture.md) | |
| 54 | +- [Design decisions](explanation/design-decisions.md) | |
| 55 | +- [Colouring and completion](explanation/colouring-and-completion.md) | |
| 56 | +- [Terminal windows](explanation/terminal-windows.md) | |
| 57 | +- [Project settings](explanation/project-settings.md) | |
| 58 | +- [Project tree](explanation/project-tree.md) | |
| 59 | +- [Snippets](explanation/snippets.md) | |
| 60 | +- [MoonBit tools](explanation/moonbit-tools.md) | |
| 61 | +- [Agent windows](explanation/agent-windows.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | +# Turbo MoonBit — documentation | ||
| 2 | + | ||
| 3 | +Turbo MoonBit is a Turbo C-style editor for MoonBit: a full-screen terminal IDE with menus, movable windows, syntax colouring for nine languages, themes, completion from `moon-lsp`, shell windows, per-project settings, a project tree, snippets, and the MoonBit 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 MoonBit program in Turbo MoonBit](tutorials/getting-started.md) — install it, write a program, format it, run it, break it and see the editor say where. | ||
| 17 | +- [Demo projects](../../demos/) — three MoonBit projects to open in the editor once you have it: a small one, one with a library and tests, and a tour of every construct the scanner colours. | ||
| 18 | + | ||
| 19 | +## How-to guides — recipes for a task | ||
| 20 | + | ||
| 21 | +- [How to install and build Turbo MoonBit](how-to/install.md) | ||
| 22 | +- [How to install the MoonBit toolchain](how-to/install-the-moonbit-toolchain.md) | ||
| 23 | +- [How to run the tests](how-to/run-the-tests.md) | ||
| 24 | +- [How to enable MoonBit completion](how-to/enable-completion.md) | ||
| 25 | +- [How to write your own theme](how-to/write-a-theme.md) | ||
| 26 | +- [How to move around a file](how-to/navigate-code.md) | ||
| 27 | +- [How to ask what the code means](how-to/ask-about-code.md) | ||
| 28 | +- [How to run shell commands without leaving the editor](how-to/use-a-terminal.md) | ||
| 29 | +- [How to give a project its own settings](how-to/configure-a-project.md) | ||
| 30 | +- [How to browse a project and open files from a tree](how-to/browse-a-project.md) | ||
| 31 | +- [How to insert snippets from a menu](how-to/use-snippets.md) | ||
| 32 | +- [How to run moon commands from the editor](how-to/run-moon-commands.md) | ||
| 33 | +- [How to make a release](how-to/make-a-release.md) | ||
| 34 | +- [How to talk to a coding agent from the editor](how-to/talk-to-an-agent.md) | ||
| 35 | + | ||
| 36 | +## Reference — the exact details | ||
| 37 | + | ||
| 38 | +- [Command line](reference/cli.md) | ||
| 39 | +- [Keyboard](reference/keyboard.md) | ||
| 40 | +- [Menus](reference/menus.md) | ||
| 41 | +- [Theme file format](reference/themes.md) | ||
| 42 | +- [Terminal windows](reference/terminal.md) | ||
| 43 | +- [Project settings](reference/project-settings.md) | ||
| 44 | +- [Project tree](reference/project-tree.md) | ||
| 45 | +- [Languages coloured](reference/languages.md) | ||
| 46 | +- [Snippets](reference/snippets.md) | ||
| 47 | +- [MoonBit tools](reference/moonbit-tools.md) | ||
| 48 | +- [The version number](reference/versioning.md) | ||
| 49 | +- [Agents and ACP](reference/acp.md) | ||
| 50 | + | ||
| 51 | +## Explanation — understanding | ||
| 52 | + | ||
| 53 | +- [Architecture](explanation/architecture.md) | ||
| 54 | +- [Design decisions](explanation/design-decisions.md) | ||
| 55 | +- [Colouring and completion](explanation/colouring-and-completion.md) | ||
| 56 | +- [Terminal windows](explanation/terminal-windows.md) | ||
| 57 | +- [Project settings](explanation/project-settings.md) | ||
| 58 | +- [Project tree](explanation/project-tree.md) | ||
| 59 | +- [Snippets](explanation/snippets.md) | ||
| 60 | +- [MoonBit tools](explanation/moonbit-tools.md) | ||
| 61 | +- [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 MoonBit 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 MoonBit contributes is the starter `acp.toml` it offers to write — the one part of this that is about MoonBit projects. Turbo Rust and Turbo Python 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 `moon 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 `moon-lsp`. | |
| 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 MoonBit 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 MoonBit contributes is the starter `acp.toml` it offers to write — the one part of this that is about MoonBit projects. Turbo Rust and Turbo Python 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 `moon 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 `moon-lsp`. | ||
| 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 MoonBit 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/moonbitlang the whole of what makes this Turbo MoonBit | |
| 14 | + moonbitlang.go the profile: name, menu, server, root markers, where moon-lsp 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 eleven hundred lines counting the comments, of which seven hundred are the scanner — five hundred and forty lines of code by qlty's count. 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 `moonbitlang.Register()`, which teaches the library to colour `.mbt` files. | |
| 30 | +3. Builds `moonbitlang.Profile()` — the value that says this editor is Turbo MoonBit. | |
| 31 | +4. Reads `.turbo-moonbit/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 moon-lsp 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 MoonBit. | |
| 36 | + | |
| 37 | +## The profile is the seam | |
| 38 | + | |
| 39 | +```go | |
| 40 | +profile.Profile{ | |
| 41 | + Name: "Turbo MoonBit", | |
| 42 | + Slug: "turbo-moonbit", | |
| 43 | + Language: "MoonBit", | |
| 44 | + ToolsMenu: "~P~ython", | |
| 45 | + RootMarkers: []string{"moon.mod", "moon.mod.json"}, | |
| 46 | + Server: profile.Server{Command: "moon-lsp", …}, | |
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | |
| 48 | +} | |
| 49 | +``` | |
| 50 | + | |
| 51 | +Everything that would otherwise be a hardcoded `"turbo-moonbit"`, `"moon-lsp"` or `"moon.mod"` 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-moonbit`, the project directory is `.turbo-moonbit`, the user's own configuration lives in `~/.config/turbo-moonbit`, and the environment variables that override it are `TURBO_MOONBIT_THEME_DIR` and `TURBO_MOONBIT_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 | +MoonBit 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 `.mbt` 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 MoonBit 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 `moon`: 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 **moon** holding `docker compose up` is a lie about what the menu is, in exactly the way the library's own documentation warns about. `MoonBit` is the language, and the language is what this editor is for. | |
| 68 | + | |
| 69 | +## Why the tests drive the real editor | |
| 70 | + | |
| 71 | +`internal/moonbitlang/editor_test.go` builds a whole Turbo MoonBit on a simulated terminal — `app.New(screen, "turbo-classic", moonbitlang.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 `.mbt` file comes out coloured. A bug where `main` forgot to register MoonBit would pass every test in turbo-core. | |
| 74 | + | |
| 75 | +The same file drives a **real moon-lsp** 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 moon-lsp *cannot* do: it advertises neither `typeDefinition` nor `implementation`, the documentation says so, and the test fails if a future moon-lsp 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 MoonBit 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: [MoonBit tools](moonbit-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 MoonBit 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/moonbitlang the whole of what makes this Turbo MoonBit | ||
| 14 | + moonbitlang.go the profile: name, menu, server, root markers, where moon-lsp 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 eleven hundred lines counting the comments, of which seven hundred are the scanner — five hundred and forty lines of code by qlty's count. 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 `moonbitlang.Register()`, which teaches the library to colour `.mbt` files. | ||
| 30 | +3. Builds `moonbitlang.Profile()` — the value that says this editor is Turbo MoonBit. | ||
| 31 | +4. Reads `.turbo-moonbit/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 moon-lsp 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 MoonBit. | ||
| 36 | + | ||
| 37 | +## The profile is the seam | ||
| 38 | + | ||
| 39 | +```go | ||
| 40 | +profile.Profile{ | ||
| 41 | + Name: "Turbo MoonBit", | ||
| 42 | + Slug: "turbo-moonbit", | ||
| 43 | + Language: "MoonBit", | ||
| 44 | + ToolsMenu: "~P~ython", | ||
| 45 | + RootMarkers: []string{"moon.mod", "moon.mod.json"}, | ||
| 46 | + Server: profile.Server{Command: "moon-lsp", …}, | ||
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | ||
| 48 | +} | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +Everything that would otherwise be a hardcoded `"turbo-moonbit"`, `"moon-lsp"` or `"moon.mod"` 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-moonbit`, the project directory is `.turbo-moonbit`, the user's own configuration lives in `~/.config/turbo-moonbit`, and the environment variables that override it are `TURBO_MOONBIT_THEME_DIR` and `TURBO_MOONBIT_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 | +MoonBit 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 `.mbt` 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 MoonBit 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 `moon`: 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 **moon** holding `docker compose up` is a lie about what the menu is, in exactly the way the library's own documentation warns about. `MoonBit` is the language, and the language is what this editor is for. | ||
| 68 | + | ||
| 69 | +## Why the tests drive the real editor | ||
| 70 | + | ||
| 71 | +`internal/moonbitlang/editor_test.go` builds a whole Turbo MoonBit on a simulated terminal — `app.New(screen, "turbo-classic", moonbitlang.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 `.mbt` file comes out coloured. A bug where `main` forgot to register MoonBit would pass every test in turbo-core. | ||
| 74 | + | ||
| 75 | +The same file drives a **real moon-lsp** 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 moon-lsp *cannot* do: it advertises neither `typeDefinition` nor `implementation`, the documentation says so, and the test fails if a future moon-lsp 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 MoonBit 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: [MoonBit tools](moonbit-tools.md) | ||
| 97 | +- The decisions that outlived the refactoring: [Design decisions](design-decisions.md) | ||
added
docs/en/explanation/colouring-and-completion.md +116 -0 | new file mode 100644 | ||
| @@ -0,0 +1,116 @@ | ||
| 1 | +# Colouring and completion — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +The two features that make Turbo MoonBit an editor *for MoonBit* rather than a text editor that happens to open `.mbt` 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 moon-lsp, and Turbo MoonBit 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 MoonBit 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 MoonBit is scanned by hand | |
| 16 | + | |
| 17 | +MoonBit has no lexer available as a Go package. Turbo Go can go through `go/scanner` — the standard library analysing its own language, so the editor and the compiler agree about what a token is with nothing to keep in step. Turbo MoonBit has no such thing, and the three ways round it were weighed. | |
| 18 | + | |
| 19 | +**Running a real MoonBit lexer** would mean starting `moonc` and asking it for tokens: a process per keystroke, and a dependency on a toolchain the editor should not need in order to colour a file. | |
| 20 | + | |
| 21 | +**Embedding a grammar** — tree-sitter or the like — would mean a native library, a build step, and a binary that no longer compiles everywhere. turbo-core holds itself to two and a half direct dependencies; this is not where the third gets added. | |
| 22 | + | |
| 23 | +**Writing a scanner by hand** costs one more file and gives something that runs on every keystroke without allocating anything surprising, never breaks on invalid text, and reads like ordinary Go. | |
| 24 | + | |
| 25 | +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. | |
| 26 | + | |
| 27 | +The published grammar made that affordable. MoonBit's documentation carries a complete lexical specification — the productions for every literal, the keyword list, the rule that an integer ends before `..` — so this scanner was written against a specification rather than against a pile of examples, and the places where it deliberately departs from that specification are named below. | |
| 28 | + | |
| 29 | +## Nothing crosses a line break | |
| 30 | + | |
| 31 | +Every other editor in this family threads real state through its scanner. Turbo Go and Turbo Rust carry a block-comment depth; Turbo Rust also carries a raw string's delimiter; Turbo Python carries which of the two quotes opened a triple-quoted literal. Turbo MoonBit carries nothing at all, and that is a fact about the language rather than a shortcut: | |
| 32 | + | |
| 33 | +- **There is no block comment.** The grammar says so in as many words: "MoonBit has no block-comment form." `//` runs to the end of the line, `///` is a doc comment that does the same. | |
| 34 | +- **No literal may reach the next line.** For strings, bytes, regexes, characters and byte characters alike, "a newline before the closing quote reports an unterminated string literal". A line that ends inside a literal is broken source, not a construct. | |
| 35 | +- **A multi-line string is not one literal spanning lines.** It is a run of lines each prefixed `#|` or `$|`, each a complete token, which the compiler joins with a newline afterwards. | |
| 36 | +- **An attribute is explicitly one line**: "everything through the next newline is the raw payload". | |
| 37 | + | |
| 38 | +So the carry type is empty, and it is a named type rather than `struct{}` written inline, so that the reasoning has somewhere to live. If MoonBit ever grows a construct that crosses a line break, that type is what gains a field. | |
| 39 | + | |
| 40 | +What this buys is worth stating plainly: **a stray quote cannot paint the rest of the file.** In every other editor here, an unterminated string is a case the scanner has to decide to *drop*, and getting that decision wrong turns one keystroke into a screenful of green. Here there is no decision to get wrong. | |
| 41 | + | |
| 42 | +## Where the scanner leans on the language, not on convention | |
| 43 | + | |
| 44 | +This is the part that makes MoonBit's scanner shorter than its siblings', and the reason is one lexical rule. | |
| 45 | + | |
| 46 | +**A capitalised name is a type, and that is the language's rule rather than a habit.** The grammar defines `uident` as beginning "with an ASCII uppercase letter", and only a type, a trait or an enum constructor may be spelt that way. Turbo Python has to consult PEP 8 to tell `ValueError("nope")` from `parse("nope")`; Turbo Rust has to keep a table of the constructors the language names, because `Some(x)` looks like a call. Here the case *is* the answer, so there is no table of built-in types in this repository at all — `Int`, `StringBuilder` and a type somebody wrote this morning are coloured by the same line of code. | |
| 47 | + | |
| 48 | +**What that costs is one thing, and it is unavoidable.** An enum constructor of your own — `Circle(1.0)` — is coloured as a type, because nothing in the syntax separates it from a type applied to arguments. Inventing a separation would mean being wrong in both directions instead of one. | |
| 49 | + | |
| 50 | +**The prelude is a table, and it was read rather than remembered.** `println`, `abort`, `fail`, `ignore`, `inspect` and the rest come out of `moonbitlang/core/prelude`'s generated interface file. That matters more than it sounds: a table written from habit would have held `print`, and MoonBit has never had `print`. The prelude's deprecated names — `dump`, `not`, `tap` — are deliberately absent, because colouring them as builtins would present four things the language is retiring as its own. | |
| 51 | + | |
| 52 | +## The one place the grammar has to be followed exactly | |
| 53 | + | |
| 54 | +`1..=2` is an integer and a range operator. A scanner that swallowed any dot after a number would read the double `1.` and leave `.=2` behind, and every range in every file would be miscoloured. | |
| 55 | + | |
| 56 | +The grammar settles it in a sentence — "before `..`, an integer ends first, so `1..=2` begins with `1` and `..=`" — and the scanner follows it exactly: a dot joins a number only when a second one does not follow. The same discipline governs the suffixes. `42UL` is one number and `42u` is `42` followed by the name `u`, because the grammar says the suffixes are upper case, and colouring `42u` as a literal would be inventing something the compiler is about to reject. | |
| 57 | + | |
| 58 | +A dot has two other jobs, and both had to be written out rather than folded into punctuation. `pair.0` is a tuple accessor. `xs.length()` is a method — and the name after the dot is looked up *without* the keyword table, because MoonBit's dot-identifiers "use the identifier case rules without consulting the keyword table, so `.if` is valid". A record with a field called `type` is ordinary MoonBit, and a scanner that coloured that field as a keyword would be making a claim the language contradicts. | |
| 59 | + | |
| 60 | +## What the scanner refuses to guess | |
| 61 | + | |
| 62 | +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: | |
| 63 | + | |
| 64 | +| Not recognised | Because | | |
| 65 | +| --- | --- | | |
| 66 | +| The expression inside `\{…}` | The grammar matches it to "the matching `}`", with braces inside nested literals not counting — finding the end needs the parser. A brace counter that got it wrong would end the string early, and a literal that swallows the rest of the line is the loudest way a highlighter can break. One flat run of string is the honest answer for the ordinary case, and it is the one Turbo Python gives an f-string for the same reason. Its limit is a *string* nested inside the interpolation — see below | | |
| 67 | +| A reserved word as a keyword | `move`, `ref`, `static`, `unsafe`, `await` and forty others are *reserved* rather than keywords: the lexer treats them as identifiers and warns. Colouring them would tell a reader they cannot write `let ref = 1` when they can | | |
| 68 | +| An identifier holding non-ASCII letters | MoonBit allows CJK and several other Unicode ranges in a name. The rune predicates this scanner is built on are ASCII, so such a name is stepped over uncoloured rather than guessed at — a boundary worth knowing rather than a defect to hide | | |
| 69 | +| `moon.mod`, `moon.pkg` and `moon.work` | They are MoonBit's own configuration DSL rather than MoonBit. Colouring them with the MoonBit scanner would be wrong about `import { … }` and about every bare key, and writing a second scanner for a format that is still changing is work with a short shelf life | | |
| 70 | +| The contents of a `.mbt.md` fence | It is a Markdown document, and Markdown colours it. A fenced block is one colour whatever language it announces — that is turbo-core's rule, and it applies to `mbt` exactly as it applies to `bash` | | |
| 71 | + | |
| 72 | +**The one place that answer is visibly wrong is a string inside an interpolation.** `"a \{f("x")} c"` is one literal to the compiler and three spans to the scanner — string, then `x` as an identifier, then string — because the first unescaped quote is taken as the closer. It is the price of not parsing, it is bounded (the spans stay in order and never overlap, so nothing downstream misbehaves), and `demos/syntax-tour/tour.mbt` has a line that shows it rather than avoiding it. | |
| 73 | + | |
| 74 | +**`package` is the one deliberate over-reach**, and it is worth naming as such. In a `.mbt` file it is only a reserved word; in the `.mbti` interface files this editor also colours, it is a real keyword. One scanner serves both, and colouring it as a keyword says in a `.mbt` file exactly what the compiler is about to: this word is not yours to use. | |
| 75 | + | |
| 76 | +## The other eight languages come free | |
| 77 | + | |
| 78 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell are coloured by turbo-core, not here. A MoonBit project has a `moon.mod`, a `README.md`, some scripts, a CI workflow in YAML and often a Dockerfile, and an editor that coloured only the `.mbt` files would make you leave it for the rest. | |
| 79 | + | |
| 80 | +That they are shared rather than copied is the point of the library: they were written once, for Turbo Go, and Turbo MoonBit got them by importing a package. | |
| 81 | + | |
| 82 | +## Completion, and why it can fail silently | |
| 83 | + | |
| 84 | +Turbo MoonBit knows nothing about MoonBit's type system and does not try to. It asks moon-lsp over the Language Server Protocol and draws the answer. | |
| 85 | + | |
| 86 | +Three things about that are worth knowing, because all three look like "completion is broken": | |
| 87 | + | |
| 88 | +**moon-lsp 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. | |
| 89 | + | |
| 90 | +**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 `moon.mod`, `moon.mod.json` or `moon.mod.json` rather than using the working directory, and it is the single most confusing way completion can fail. | |
| 91 | + | |
| 92 | +**A server installed without its extras answers questions but never volunteers a problem.** moon-lsp'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. | |
| 93 | + | |
| 94 | +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. | |
| 95 | + | |
| 96 | +## Nine questions, one connection — and the two moon-lsp does not answer | |
| 97 | + | |
| 98 | +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. | |
| 99 | + | |
| 100 | +**Something to read.** `hover` — what is this? — drawn in a box. | |
| 101 | + | |
| 102 | +**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. | |
| 103 | + | |
| 104 | +**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. | |
| 105 | + | |
| 106 | +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. | |
| 107 | + | |
| 108 | +**Two of the nine come back empty with moon-lsp, and that is the server's boundary rather than the editor's.** moon-lsp advertises neither `typeDefinition` nor `implementation`, so **Code ▸ Type definition** and **Code ▸ Find implementations** report nothing found. Everything else works, including the project-wide symbol search that Turbo Python's server does not answer. 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. | |
| 109 | + | |
| 110 | +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. | |
| 111 | + | |
| 112 | +## How it relates to the rest | |
| 113 | + | |
| 114 | +- Exactly what is recognised: [Languages coloured](../reference/languages.md) | |
| 115 | +- Getting completion working: [How to enable MoonBit completion](../how-to/enable-completion.md) | |
| 116 | +- Where the scanner lives and why: [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,116 @@ | |||
| 1 | +# Colouring and completion — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +The two features that make Turbo MoonBit an editor *for MoonBit* rather than a text editor that happens to open `.mbt` 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 moon-lsp, and Turbo MoonBit 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 MoonBit 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 MoonBit is scanned by hand | ||
| 16 | + | ||
| 17 | +MoonBit has no lexer available as a Go package. Turbo Go can go through `go/scanner` — the standard library analysing its own language, so the editor and the compiler agree about what a token is with nothing to keep in step. Turbo MoonBit has no such thing, and the three ways round it were weighed. | ||
| 18 | + | ||
| 19 | +**Running a real MoonBit lexer** would mean starting `moonc` and asking it for tokens: a process per keystroke, and a dependency on a toolchain the editor should not need in order to colour a file. | ||
| 20 | + | ||
| 21 | +**Embedding a grammar** — tree-sitter or the like — would mean a native library, a build step, and a binary that no longer compiles everywhere. turbo-core holds itself to two and a half direct dependencies; this is not where the third gets added. | ||
| 22 | + | ||
| 23 | +**Writing a scanner by hand** costs one more file and gives something that runs on every keystroke without allocating anything surprising, never breaks on invalid text, and reads like ordinary Go. | ||
| 24 | + | ||
| 25 | +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. | ||
| 26 | + | ||
| 27 | +The published grammar made that affordable. MoonBit's documentation carries a complete lexical specification — the productions for every literal, the keyword list, the rule that an integer ends before `..` — so this scanner was written against a specification rather than against a pile of examples, and the places where it deliberately departs from that specification are named below. | ||
| 28 | + | ||
| 29 | +## Nothing crosses a line break | ||
| 30 | + | ||
| 31 | +Every other editor in this family threads real state through its scanner. Turbo Go and Turbo Rust carry a block-comment depth; Turbo Rust also carries a raw string's delimiter; Turbo Python carries which of the two quotes opened a triple-quoted literal. Turbo MoonBit carries nothing at all, and that is a fact about the language rather than a shortcut: | ||
| 32 | + | ||
| 33 | +- **There is no block comment.** The grammar says so in as many words: "MoonBit has no block-comment form." `//` runs to the end of the line, `///` is a doc comment that does the same. | ||
| 34 | +- **No literal may reach the next line.** For strings, bytes, regexes, characters and byte characters alike, "a newline before the closing quote reports an unterminated string literal". A line that ends inside a literal is broken source, not a construct. | ||
| 35 | +- **A multi-line string is not one literal spanning lines.** It is a run of lines each prefixed `#|` or `$|`, each a complete token, which the compiler joins with a newline afterwards. | ||
| 36 | +- **An attribute is explicitly one line**: "everything through the next newline is the raw payload". | ||
| 37 | + | ||
| 38 | +So the carry type is empty, and it is a named type rather than `struct{}` written inline, so that the reasoning has somewhere to live. If MoonBit ever grows a construct that crosses a line break, that type is what gains a field. | ||
| 39 | + | ||
| 40 | +What this buys is worth stating plainly: **a stray quote cannot paint the rest of the file.** In every other editor here, an unterminated string is a case the scanner has to decide to *drop*, and getting that decision wrong turns one keystroke into a screenful of green. Here there is no decision to get wrong. | ||
| 41 | + | ||
| 42 | +## Where the scanner leans on the language, not on convention | ||
| 43 | + | ||
| 44 | +This is the part that makes MoonBit's scanner shorter than its siblings', and the reason is one lexical rule. | ||
| 45 | + | ||
| 46 | +**A capitalised name is a type, and that is the language's rule rather than a habit.** The grammar defines `uident` as beginning "with an ASCII uppercase letter", and only a type, a trait or an enum constructor may be spelt that way. Turbo Python has to consult PEP 8 to tell `ValueError("nope")` from `parse("nope")`; Turbo Rust has to keep a table of the constructors the language names, because `Some(x)` looks like a call. Here the case *is* the answer, so there is no table of built-in types in this repository at all — `Int`, `StringBuilder` and a type somebody wrote this morning are coloured by the same line of code. | ||
| 47 | + | ||
| 48 | +**What that costs is one thing, and it is unavoidable.** An enum constructor of your own — `Circle(1.0)` — is coloured as a type, because nothing in the syntax separates it from a type applied to arguments. Inventing a separation would mean being wrong in both directions instead of one. | ||
| 49 | + | ||
| 50 | +**The prelude is a table, and it was read rather than remembered.** `println`, `abort`, `fail`, `ignore`, `inspect` and the rest come out of `moonbitlang/core/prelude`'s generated interface file. That matters more than it sounds: a table written from habit would have held `print`, and MoonBit has never had `print`. The prelude's deprecated names — `dump`, `not`, `tap` — are deliberately absent, because colouring them as builtins would present four things the language is retiring as its own. | ||
| 51 | + | ||
| 52 | +## The one place the grammar has to be followed exactly | ||
| 53 | + | ||
| 54 | +`1..=2` is an integer and a range operator. A scanner that swallowed any dot after a number would read the double `1.` and leave `.=2` behind, and every range in every file would be miscoloured. | ||
| 55 | + | ||
| 56 | +The grammar settles it in a sentence — "before `..`, an integer ends first, so `1..=2` begins with `1` and `..=`" — and the scanner follows it exactly: a dot joins a number only when a second one does not follow. The same discipline governs the suffixes. `42UL` is one number and `42u` is `42` followed by the name `u`, because the grammar says the suffixes are upper case, and colouring `42u` as a literal would be inventing something the compiler is about to reject. | ||
| 57 | + | ||
| 58 | +A dot has two other jobs, and both had to be written out rather than folded into punctuation. `pair.0` is a tuple accessor. `xs.length()` is a method — and the name after the dot is looked up *without* the keyword table, because MoonBit's dot-identifiers "use the identifier case rules without consulting the keyword table, so `.if` is valid". A record with a field called `type` is ordinary MoonBit, and a scanner that coloured that field as a keyword would be making a claim the language contradicts. | ||
| 59 | + | ||
| 60 | +## What the scanner refuses to guess | ||
| 61 | + | ||
| 62 | +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: | ||
| 63 | + | ||
| 64 | +| Not recognised | Because | | ||
| 65 | +| --- | --- | | ||
| 66 | +| The expression inside `\{…}` | The grammar matches it to "the matching `}`", with braces inside nested literals not counting — finding the end needs the parser. A brace counter that got it wrong would end the string early, and a literal that swallows the rest of the line is the loudest way a highlighter can break. One flat run of string is the honest answer for the ordinary case, and it is the one Turbo Python gives an f-string for the same reason. Its limit is a *string* nested inside the interpolation — see below | | ||
| 67 | +| A reserved word as a keyword | `move`, `ref`, `static`, `unsafe`, `await` and forty others are *reserved* rather than keywords: the lexer treats them as identifiers and warns. Colouring them would tell a reader they cannot write `let ref = 1` when they can | | ||
| 68 | +| An identifier holding non-ASCII letters | MoonBit allows CJK and several other Unicode ranges in a name. The rune predicates this scanner is built on are ASCII, so such a name is stepped over uncoloured rather than guessed at — a boundary worth knowing rather than a defect to hide | | ||
| 69 | +| `moon.mod`, `moon.pkg` and `moon.work` | They are MoonBit's own configuration DSL rather than MoonBit. Colouring them with the MoonBit scanner would be wrong about `import { … }` and about every bare key, and writing a second scanner for a format that is still changing is work with a short shelf life | | ||
| 70 | +| The contents of a `.mbt.md` fence | It is a Markdown document, and Markdown colours it. A fenced block is one colour whatever language it announces — that is turbo-core's rule, and it applies to `mbt` exactly as it applies to `bash` | | ||
| 71 | + | ||
| 72 | +**The one place that answer is visibly wrong is a string inside an interpolation.** `"a \{f("x")} c"` is one literal to the compiler and three spans to the scanner — string, then `x` as an identifier, then string — because the first unescaped quote is taken as the closer. It is the price of not parsing, it is bounded (the spans stay in order and never overlap, so nothing downstream misbehaves), and `demos/syntax-tour/tour.mbt` has a line that shows it rather than avoiding it. | ||
| 73 | + | ||
| 74 | +**`package` is the one deliberate over-reach**, and it is worth naming as such. In a `.mbt` file it is only a reserved word; in the `.mbti` interface files this editor also colours, it is a real keyword. One scanner serves both, and colouring it as a keyword says in a `.mbt` file exactly what the compiler is about to: this word is not yours to use. | ||
| 75 | + | ||
| 76 | +## The other eight languages come free | ||
| 77 | + | ||
| 78 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfiles and shell are coloured by turbo-core, not here. A MoonBit project has a `moon.mod`, a `README.md`, some scripts, a CI workflow in YAML and often a Dockerfile, and an editor that coloured only the `.mbt` files would make you leave it for the rest. | ||
| 79 | + | ||
| 80 | +That they are shared rather than copied is the point of the library: they were written once, for Turbo Go, and Turbo MoonBit got them by importing a package. | ||
| 81 | + | ||
| 82 | +## Completion, and why it can fail silently | ||
| 83 | + | ||
| 84 | +Turbo MoonBit knows nothing about MoonBit's type system and does not try to. It asks moon-lsp over the Language Server Protocol and draws the answer. | ||
| 85 | + | ||
| 86 | +Three things about that are worth knowing, because all three look like "completion is broken": | ||
| 87 | + | ||
| 88 | +**moon-lsp 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. | ||
| 89 | + | ||
| 90 | +**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 `moon.mod`, `moon.mod.json` or `moon.mod.json` rather than using the working directory, and it is the single most confusing way completion can fail. | ||
| 91 | + | ||
| 92 | +**A server installed without its extras answers questions but never volunteers a problem.** moon-lsp'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. | ||
| 93 | + | ||
| 94 | +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. | ||
| 95 | + | ||
| 96 | +## Nine questions, one connection — and the two moon-lsp does not answer | ||
| 97 | + | ||
| 98 | +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. | ||
| 99 | + | ||
| 100 | +**Something to read.** `hover` — what is this? — drawn in a box. | ||
| 101 | + | ||
| 102 | +**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. | ||
| 103 | + | ||
| 104 | +**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. | ||
| 105 | + | ||
| 106 | +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. | ||
| 107 | + | ||
| 108 | +**Two of the nine come back empty with moon-lsp, and that is the server's boundary rather than the editor's.** moon-lsp advertises neither `typeDefinition` nor `implementation`, so **Code ▸ Type definition** and **Code ▸ Find implementations** report nothing found. Everything else works, including the project-wide symbol search that Turbo Python's server does not answer. 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. | ||
| 109 | + | ||
| 110 | +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. | ||
| 111 | + | ||
| 112 | +## How it relates to the rest | ||
| 113 | + | ||
| 114 | +- Exactly what is recognised: [Languages coloured](../reference/languages.md) | ||
| 115 | +- Getting completion working: [How to enable MoonBit completion](../how-to/enable-completion.md) | ||
| 116 | +- 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 MoonBit, 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 MoonBit 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 moon-lsp 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 `moon-lsp` 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 MoonBit 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-moonbit@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 MoonBit, 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 MoonBit 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 moon-lsp 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 `moon-lsp` 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 MoonBit 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-moonbit@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/moonbit-tools.md +119 -0 | new file mode 100644 | ||
| @@ -0,0 +1,119 @@ | ||
| 1 | +# MoonBit tools — explanation | |
| 2 | + | |
| 3 | +## What is this about? | |
| 4 | + | |
| 5 | +A **MoonBit** 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*: `moon run cmd/main` on a program that reads the keyboard has to be answerable, and a `moon build --target all` that turns out to compile five backends has to be interruptible with `Ctrl-C`. Neither is true of `moon check`, which prints a few 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-moon-commands.md): a `moon build` 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 `moon test`, or `moon 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 | +`moon fmt` 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 `moon`, the build system that ships with the language — so none of them needs anything set up beyond the toolchain itself. That is a defensible default and it is nobody's universal answer. A project that builds for one backend wants `moon build --target js` without being asked. One inside a `moon.work` workspace wants `moon check --target all` from the workspace root. One with a `Makefile` wants `make check`. One that runs its tests under a coverage report wants `moon coverage analyze`. 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 **MoonBit ▸ 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 `moon fmt && moon check && moon test`. 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 `moon test` in a repository that has never heard of MoonBit, and a project that builds only for `wasm-gc` would get somebody else's backend 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 **MoonBit** holding `docker compose up` is a lie about what the menu is. The first tools file anybody writes outgrows MoonBit, 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 MoonBit in MoonBit, 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 MoonBit. There is no list of allowed names, because a list would be a list of somebody else's projects. | |
| 58 | + | |
| 59 | +MoonBit itself stays fixed on the bar rather than becoming just another name from the file. **MoonBit ▸ 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`, `MoonBit` 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 MoonBit 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 `moon fmt`'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 | +`moon build` needs a backend. `moon run` needs a package. `moon add` needs a module name. 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 | +There are three of them in the starter file, and the first is the one worth explaining. **`moon build --target` asks which backend to compile for**, because MoonBit compiles to `wasm`, `wasm-gc`, `js`, `native`, `llvm` or all of them, and which one a project wants is not something a starter file can know. Writing one in would be a guess that is wrong for most projects and silently right for none. | |
| 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: [MoonBit tools reference](../reference/moonbit-tools.md) | |
| 117 | +- Using it: [How to run moon commands from the editor](../how-to/run-moon-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 | +# MoonBit tools — explanation | ||
| 2 | + | ||
| 3 | +## What is this about? | ||
| 4 | + | ||
| 5 | +A **MoonBit** 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*: `moon run cmd/main` on a program that reads the keyboard has to be answerable, and a `moon build --target all` that turns out to compile five backends has to be interruptible with `Ctrl-C`. Neither is true of `moon check`, which prints a few 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-moon-commands.md): a `moon build` 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 `moon test`, or `moon 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 | +`moon fmt` 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 `moon`, the build system that ships with the language — so none of them needs anything set up beyond the toolchain itself. That is a defensible default and it is nobody's universal answer. A project that builds for one backend wants `moon build --target js` without being asked. One inside a `moon.work` workspace wants `moon check --target all` from the workspace root. One with a `Makefile` wants `make check`. One that runs its tests under a coverage report wants `moon coverage analyze`. 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 **MoonBit ▸ 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 `moon fmt && moon check && moon test`. 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 `moon test` in a repository that has never heard of MoonBit, and a project that builds only for `wasm-gc` would get somebody else's backend 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 **MoonBit** holding `docker compose up` is a lie about what the menu is. The first tools file anybody writes outgrows MoonBit, 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 MoonBit in MoonBit, 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 MoonBit. There is no list of allowed names, because a list would be a list of somebody else's projects. | ||
| 58 | + | ||
| 59 | +MoonBit itself stays fixed on the bar rather than becoming just another name from the file. **MoonBit ▸ 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`, `MoonBit` 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 MoonBit 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 `moon fmt`'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 | +`moon build` needs a backend. `moon run` needs a package. `moon add` needs a module name. 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 | +There are three of them in the starter file, and the first is the one worth explaining. **`moon build --target` asks which backend to compile for**, because MoonBit compiles to `wasm`, `wasm-gc`, `js`, `native`, `llvm` or all of them, and which one a project wants is not something a starter file can know. Writing one in would be a guess that is wrong for most projects and silently right for none. | ||
| 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: [MoonBit tools reference](../reference/moonbit-tools.md) | ||
| 117 | +- Using it: [How to run moon commands from the editor](../how-to/run-moon-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/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-moonbit/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 | +`moon.mod` 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 `moon.mod` 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-moonbit/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-moonbit/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 | +`moon.mod` 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 `moon.mod` 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-moonbit/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 `moon.mod`, because a module has a real boundary — being inside one is a fact about the code, and moon-lsp needs that exact directory to work in. The project settings file does not walk at all: `.turbo-moonbit/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 `moon.mod` 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-moonbit/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 `moon.mod`, because a module has a real boundary — being inside one is a fact about the code, and moon-lsp needs that exact directory to work in. The project settings file does not walk at all: `.turbo-moonbit/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 `moon.mod` 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-moonbit/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/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 MoonBit, 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 MoonBit, 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. `moon test` 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, `moon test`, `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. `moon test` 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, `moon test`, `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 +72 -0 | new file mode 100644 | ||
| @@ -0,0 +1,72 @@ | ||
| 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 MoonBit 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 | +**Two of these five report nothing with moon-lsp.** The server advertises neither `typeDefinition` nor `implementation`, so **Go to type definition** and **Find implementations** answer nothing found however good the code is. The other three, and the two symbol searches below, all work. See [colouring and completion](../explanation/colouring-and-completion.md) for why this is written down rather than hidden behind a greyed-out menu item. | |
| 22 | + | |
| 23 | +One answer takes you straight there. Several open a list showing each file, its line, and the text of that line: | |
| 24 | + | |
| 25 | +``` | |
| 26 | +References (3) | |
| 27 | + main.mbt:1 fn helper() -> Int { | |
| 28 | + main.mbt:7 helper() | |
| 29 | + main.mbt:12 helper() + 1 | |
| 30 | +``` | |
| 31 | + | |
| 32 | +Move with the arrow keys, `Enter` to go, `Esc` to stay where you are. | |
| 33 | + | |
| 34 | +## When nothing comes back | |
| 35 | + | |
| 36 | +Three different things look alike, and the status bar tells them apart: | |
| 37 | + | |
| 38 | +| It says | Meaning | | |
| 39 | +| --- | --- | | |
| 40 | +| `No references found` | The server answered, and there are none | | |
| 41 | +| Anything else, such as `Loading…` | The server has not finished indexing. Wait a moment and ask again. | | |
| 42 | +| `LSP: off` on the status bar | No server is running. See [How to enable completion](enable-completion.md). | | |
| 43 | + | |
| 44 | +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. | |
| 45 | + | |
| 46 | +## Find something by name instead | |
| 47 | + | |
| 48 | +- **Code ▸ Symbol in file…** lists what the file in front declares, indented, with each symbol's kind — an outline you can walk. | |
| 49 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) asks for a name and searches everywhere. What counts as a match is the server's decision; moon-lsp matches loosely, so a few letters usually do. | |
| 50 | + | |
| 51 | +## See what is wrong | |
| 52 | + | |
| 53 | +**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. | |
| 54 | + | |
| 55 | +Lines with a problem carry a mark in the gutter, beside the line number: | |
| 56 | + | |
| 57 | +| Mark | Meaning | | |
| 58 | +| --- | --- | | |
| 59 | +| `×` | An error | | |
| 60 | +| `!` | A warning | | |
| 61 | +| `i` | Information | | |
| 62 | +| `·` | A hint | | |
| 63 | + | |
| 64 | +A line with more than one problem shows the worst of them. | |
| 65 | + | |
| 66 | +**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. | |
| 67 | + | |
| 68 | +## See also | |
| 69 | + | |
| 70 | +- Every item and its key: [Menus](../reference/menus.md) | |
| 71 | +- Getting a server running: [How to enable completion](enable-completion.md) | |
| 72 | +- What the editor asks, and why: [Colouring and completion](../explanation/colouring-and-completion.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,72 @@ | |||
| 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 MoonBit 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 | +**Two of these five report nothing with moon-lsp.** The server advertises neither `typeDefinition` nor `implementation`, so **Go to type definition** and **Find implementations** answer nothing found however good the code is. The other three, and the two symbol searches below, all work. See [colouring and completion](../explanation/colouring-and-completion.md) for why this is written down rather than hidden behind a greyed-out menu item. | ||
| 22 | + | ||
| 23 | +One answer takes you straight there. Several open a list showing each file, its line, and the text of that line: | ||
| 24 | + | ||
| 25 | +``` | ||
| 26 | +References (3) | ||
| 27 | + main.mbt:1 fn helper() -> Int { | ||
| 28 | + main.mbt:7 helper() | ||
| 29 | + main.mbt:12 helper() + 1 | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +Move with the arrow keys, `Enter` to go, `Esc` to stay where you are. | ||
| 33 | + | ||
| 34 | +## When nothing comes back | ||
| 35 | + | ||
| 36 | +Three different things look alike, and the status bar tells them apart: | ||
| 37 | + | ||
| 38 | +| It says | Meaning | | ||
| 39 | +| --- | --- | | ||
| 40 | +| `No references found` | The server answered, and there are none | | ||
| 41 | +| Anything else, such as `Loading…` | The server has not finished indexing. Wait a moment and ask again. | | ||
| 42 | +| `LSP: off` on the status bar | No server is running. See [How to enable completion](enable-completion.md). | | ||
| 43 | + | ||
| 44 | +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. | ||
| 45 | + | ||
| 46 | +## Find something by name instead | ||
| 47 | + | ||
| 48 | +- **Code ▸ Symbol in file…** lists what the file in front declares, indented, with each symbol's kind — an outline you can walk. | ||
| 49 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) asks for a name and searches everywhere. What counts as a match is the server's decision; moon-lsp matches loosely, so a few letters usually do. | ||
| 50 | + | ||
| 51 | +## See what is wrong | ||
| 52 | + | ||
| 53 | +**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. | ||
| 54 | + | ||
| 55 | +Lines with a problem carry a mark in the gutter, beside the line number: | ||
| 56 | + | ||
| 57 | +| Mark | Meaning | | ||
| 58 | +| --- | --- | | ||
| 59 | +| `×` | An error | | ||
| 60 | +| `!` | A warning | | ||
| 61 | +| `i` | Information | | ||
| 62 | +| `·` | A hint | | ||
| 63 | + | ||
| 64 | +A line with more than one problem shows the worst of them. | ||
| 65 | + | ||
| 66 | +**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. | ||
| 67 | + | ||
| 68 | +## See also | ||
| 69 | + | ||
| 70 | +- Every item and its key: [Menus](../reference/menus.md) | ||
| 71 | +- Getting a server running: [How to enable completion](enable-completion.md) | ||
| 72 | +- 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 MoonBit 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-moonbit ════════════2═[■]╗ | |
| 13 | +║ ▶ .turbo-moonbit ║ | |
| 14 | +║ ▼ internal ║ | |
| 15 | +║ ▶ app ║ | |
| 16 | +║ ▼ ui ║ | |
| 17 | +║ window.go ║ | |
| 18 | +║ .gitignore ║ | |
| 19 | +║ moon.mod ║ | |
| 20 | +║ main.mbt ║ | |
| 21 | +╚══════════════════════════════════════════╝ | |
| 22 | +``` | |
| 23 | + | |
| 24 | +Directories come first, then files, each group sorted. `.git` is the only thing hidden — `.turbo-moonbit`, `.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-moonbit/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 MoonBit 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-moonbit ════════════2═[■]╗ | ||
| 13 | +║ ▶ .turbo-moonbit ║ | ||
| 14 | +║ ▼ internal ║ | ||
| 15 | +║ ▶ app ║ | ||
| 16 | +║ ▼ ui ║ | ||
| 17 | +║ window.go ║ | ||
| 18 | +║ .gitignore ║ | ||
| 19 | +║ moon.mod ║ | ||
| 20 | +║ main.mbt ║ | ||
| 21 | +╚══════════════════════════════════════════╝ | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +Directories come first, then files, each group sorted. `.git` is the only thing hidden — `.turbo-moonbit`, `.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-moonbit/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 MoonBit 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-moonbit/settings.toml`, filled in with the theme you are using right now, and opens it for editing — coloured, because Turbo MoonBit colours TOML: | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +# turbo-moonbit project settings. | |
| 13 | +# | |
| 14 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -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-moonbit/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.mbt` 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-moonbit -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-moonbit -theme turbo-dark main.mbt | |
| 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-moonbit` 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-moonbit/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 MoonBit 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-moonbit/settings.toml`, filled in with the theme you are using right now, and opens it for editing — coloured, because Turbo MoonBit colours TOML: | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +# turbo-moonbit project settings. | ||
| 13 | +# | ||
| 14 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -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-moonbit/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.mbt` 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-moonbit -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-moonbit -theme turbo-dark main.mbt | ||
| 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-moonbit` 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-moonbit/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 MoonBit completion | |
| 2 | + | |
| 3 | +This guide shows how to get completion, hovers and go-to-definition working. It assumes Turbo MoonBit is already installed and that you know what a MoonBit project is. | |
| 4 | + | |
| 5 | +Completion comes from **moon-lsp**, the official MoonBit language server. Turbo MoonBit does not bundle it: editing and colouring work without it, and only completion is lost. | |
| 6 | + | |
| 7 | +## 1. Install moon-lsp | |
| 8 | + | |
| 9 | +```bash | |
| 10 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | |
| 11 | +``` | |
| 12 | + | |
| 13 | +## 2. Make sure Turbo MoonBit can find it | |
| 14 | + | |
| 15 | +Turbo MoonBit 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 | +moon-lsp version | |
| 19 | +``` | |
| 20 | + | |
| 21 | +If that says "command not found" but Turbo MoonBit 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 moon.mod | |
| 27 | +turbo-moonbit main.mbt | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Turbo MoonBit walks up from the file looking for `moon.mod` and starts moon-lsp in the directory it finds. **Outside a module, moon-lsp 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-moonbit -no-lsp main.mbt | |
| 54 | +``` | |
| 55 | + | |
| 56 | +**Completion is dead in a window that started without a name.** An Untitled window has no file to announce to moon-lsp until it is saved — press **F2** and give it a name ending in `.mbt`, somewhere under the module. 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.** moon-lsp needs the file's package to build. Run `moon check` first — a package that does not compile often yields nothing useful. | |
| 59 | + | |
| 60 | +**The first completion after opening a large module is slow.** moon-lsp 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.** moon-lsp 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 — `moon check` 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 MoonBit completion | ||
| 2 | + | ||
| 3 | +This guide shows how to get completion, hovers and go-to-definition working. It assumes Turbo MoonBit is already installed and that you know what a MoonBit project is. | ||
| 4 | + | ||
| 5 | +Completion comes from **moon-lsp**, the official MoonBit language server. Turbo MoonBit does not bundle it: editing and colouring work without it, and only completion is lost. | ||
| 6 | + | ||
| 7 | +## 1. Install moon-lsp | ||
| 8 | + | ||
| 9 | +```bash | ||
| 10 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +## 2. Make sure Turbo MoonBit can find it | ||
| 14 | + | ||
| 15 | +Turbo MoonBit 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 | +moon-lsp version | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +If that says "command not found" but Turbo MoonBit 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 moon.mod | ||
| 27 | +turbo-moonbit main.mbt | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Turbo MoonBit walks up from the file looking for `moon.mod` and starts moon-lsp in the directory it finds. **Outside a module, moon-lsp 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-moonbit -no-lsp main.mbt | ||
| 54 | +``` | ||
| 55 | + | ||
| 56 | +**Completion is dead in a window that started without a name.** An Untitled window has no file to announce to moon-lsp until it is saved — press **F2** and give it a name ending in `.mbt`, somewhere under the module. 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.** moon-lsp needs the file's package to build. Run `moon check` first — a package that does not compile often yields nothing useful. | ||
| 59 | + | ||
| 60 | +**The first completion after opening a large module is slow.** moon-lsp 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.** moon-lsp 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 — `moon check` 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-the-moonbit-toolchain.md +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 1 | +# How to install the MoonBit toolchain | |
| 2 | + | |
| 3 | +This guide shows how to get `moon`, `moonc` and `moon-lsp` onto a machine, and how to check that Turbo MoonBit can find them. It assumes you already have Turbo MoonBit, or are about to — see [how to install the editor](install.md) for that. | |
| 4 | + | |
| 5 | +**The editor works without any of this.** Editing, colouring, themes, snippets and terminal windows all run with no toolchain at all. What needs it is completion, the error marks in the gutter, and every command in the MoonBit menu. | |
| 6 | + | |
| 7 | +## Install it | |
| 8 | + | |
| 9 | +One command installs the whole toolchain — the compiler, the build system and the language server together: | |
| 10 | + | |
| 11 | +```bash | |
| 12 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | |
| 13 | +``` | |
| 14 | + | |
| 15 | +It downloads into `~/.moon`, takes a few hundred megabytes with the standard library bundled, and finishes with: | |
| 16 | + | |
| 17 | +``` | |
| 18 | +moonbit was installed successfully to ~/.moon | |
| 19 | +Added "~/.moon/bin" to $PATH in "~/.bashrc" | |
| 20 | +``` | |
| 21 | + | |
| 22 | +That last line is the one to read twice. The installer edits **one** shell profile; a shell that was already open, and any program started from a desktop launcher, has not read it. | |
| 23 | + | |
| 24 | +```bash | |
| 25 | +source ~/.bashrc | |
| 26 | +``` | |
| 27 | + | |
| 28 | +On Windows, run the PowerShell installer from https://www.moonbitlang.com/download instead. Everything below applies unchanged once it has finished. | |
| 29 | + | |
| 30 | +## Check it | |
| 31 | + | |
| 32 | +```bash | |
| 33 | +moon version --all | |
| 34 | +``` | |
| 35 | + | |
| 36 | +You should see three lines and a path for each: | |
| 37 | + | |
| 38 | +``` | |
| 39 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | |
| 40 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | |
| 41 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | |
| 42 | +``` | |
| 43 | + | |
| 44 | +The language server is a fourth binary in the same directory, and it is worth asking separately, because it is the one the editor needs: | |
| 45 | + | |
| 46 | +```bash | |
| 47 | +moon-lsp --version | |
| 48 | +``` | |
| 49 | + | |
| 50 | +``` | |
| 51 | +v0.10.12+1634b282e (2026-09-07) | |
| 52 | +``` | |
| 53 | + | |
| 54 | +## Check that the editor finds it | |
| 55 | + | |
| 56 | +Open any file in a MoonBit project and read the right-hand end of the status bar: | |
| 57 | + | |
| 58 | +``` | |
| 59 | + F1 Describe F2 Save F3 Open F6 Window F10 Menu 1:1 LSP: ready | |
| 60 | +``` | |
| 61 | + | |
| 62 | +`LSP: ready` means the server started. `LSP: no moon-lsp — curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash` means it was not found, and the message is the command to run. | |
| 63 | + | |
| 64 | +**Turbo MoonBit looks in three places, in order**: your `PATH`, then `$MOON_HOME/bin` if `MOON_HOME` is set, then `~/.moon/bin`. So the editor finds a toolchain installed the usual way even from a shell that never read the profile the installer edited — which is the case that otherwise looks like the server being broken. | |
| 65 | + | |
| 66 | +## Variants | |
| 67 | + | |
| 68 | +- **You install toolchains somewhere else.** Set `MOON_HOME` before running the installer; it honours it, and so does the editor. | |
| 69 | +- **You already have `moon` but no completion.** Check `moon-lsp --version` specifically. A toolchain unpacked by hand, or a partial upgrade, can leave `moon` working and `moon-lsp` missing. | |
| 70 | +- **You want to upgrade.** `moon upgrade` replaces the toolchain in place; `moon upgrade --dev` takes the development build. Both leave `MOON_HOME` and your `PATH` alone. | |
| 71 | +- **You are installing for CI, or into an image.** The installer is an ordinary shell script and takes no flags worth setting; pinning a version means fetching a release from https://www.moonbitlang.com/download rather than using it. | |
| 72 | +- **You want to be sure the editor is not simply finding it on `PATH`.** Start it with a stripped environment — `env PATH=/usr/bin:/bin turbo-moonbit main.mbt` — and the status bar should still say `LSP: ready`, from `~/.moon/bin`. | |
| 73 | + | |
| 74 | +## What each binary is for | |
| 75 | + | |
| 76 | +| Binary | What the editor uses it for | | |
| 77 | +| --- | --- | | |
| 78 | +| `moon-lsp` | Completion, hover, definitions, references, symbols and the error marks in the gutter | | |
| 79 | +| `moon` | Every command in the MoonBit menu — and `moon-lsp` runs it too, to work out what a project holds | | |
| 80 | +| `moonc` | The compiler, invoked by `moon` | | |
| 81 | +| `moonrun` | Runs the WebAssembly output, invoked by `moon run` | | |
| 82 | + | |
| 83 | +`moon-lsp` on its own is not enough: it works a project out by running `moon`, so a machine with the server but not the build system gets a server that starts, is found, and then knows nothing about any file. `scripts/install.sh` checks for exactly that and says so. | |
| 84 | + | |
| 85 | +## See also | |
| 86 | + | |
| 87 | +- [How to enable completion](enable-completion.md) — what to do when the server is installed and still says nothing | |
| 88 | +- [How to run moon commands from the editor](run-moon-commands.md) — the MoonBit menu | |
| 89 | +- [Colouring and completion](../explanation/colouring-and-completion.md) — why the editor needs a server at all | |
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# How to install the MoonBit toolchain | ||
| 2 | + | ||
| 3 | +This guide shows how to get `moon`, `moonc` and `moon-lsp` onto a machine, and how to check that Turbo MoonBit can find them. It assumes you already have Turbo MoonBit, or are about to — see [how to install the editor](install.md) for that. | ||
| 4 | + | ||
| 5 | +**The editor works without any of this.** Editing, colouring, themes, snippets and terminal windows all run with no toolchain at all. What needs it is completion, the error marks in the gutter, and every command in the MoonBit menu. | ||
| 6 | + | ||
| 7 | +## Install it | ||
| 8 | + | ||
| 9 | +One command installs the whole toolchain — the compiler, the build system and the language server together: | ||
| 10 | + | ||
| 11 | +```bash | ||
| 12 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +It downloads into `~/.moon`, takes a few hundred megabytes with the standard library bundled, and finishes with: | ||
| 16 | + | ||
| 17 | +``` | ||
| 18 | +moonbit was installed successfully to ~/.moon | ||
| 19 | +Added "~/.moon/bin" to $PATH in "~/.bashrc" | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +That last line is the one to read twice. The installer edits **one** shell profile; a shell that was already open, and any program started from a desktop launcher, has not read it. | ||
| 23 | + | ||
| 24 | +```bash | ||
| 25 | +source ~/.bashrc | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +On Windows, run the PowerShell installer from https://www.moonbitlang.com/download instead. Everything below applies unchanged once it has finished. | ||
| 29 | + | ||
| 30 | +## Check it | ||
| 31 | + | ||
| 32 | +```bash | ||
| 33 | +moon version --all | ||
| 34 | +``` | ||
| 35 | + | ||
| 36 | +You should see three lines and a path for each: | ||
| 37 | + | ||
| 38 | +``` | ||
| 39 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | ||
| 40 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | ||
| 41 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +The language server is a fourth binary in the same directory, and it is worth asking separately, because it is the one the editor needs: | ||
| 45 | + | ||
| 46 | +```bash | ||
| 47 | +moon-lsp --version | ||
| 48 | +``` | ||
| 49 | + | ||
| 50 | +``` | ||
| 51 | +v0.10.12+1634b282e (2026-09-07) | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +## Check that the editor finds it | ||
| 55 | + | ||
| 56 | +Open any file in a MoonBit project and read the right-hand end of the status bar: | ||
| 57 | + | ||
| 58 | +``` | ||
| 59 | + F1 Describe F2 Save F3 Open F6 Window F10 Menu 1:1 LSP: ready | ||
| 60 | +``` | ||
| 61 | + | ||
| 62 | +`LSP: ready` means the server started. `LSP: no moon-lsp — curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash` means it was not found, and the message is the command to run. | ||
| 63 | + | ||
| 64 | +**Turbo MoonBit looks in three places, in order**: your `PATH`, then `$MOON_HOME/bin` if `MOON_HOME` is set, then `~/.moon/bin`. So the editor finds a toolchain installed the usual way even from a shell that never read the profile the installer edited — which is the case that otherwise looks like the server being broken. | ||
| 65 | + | ||
| 66 | +## Variants | ||
| 67 | + | ||
| 68 | +- **You install toolchains somewhere else.** Set `MOON_HOME` before running the installer; it honours it, and so does the editor. | ||
| 69 | +- **You already have `moon` but no completion.** Check `moon-lsp --version` specifically. A toolchain unpacked by hand, or a partial upgrade, can leave `moon` working and `moon-lsp` missing. | ||
| 70 | +- **You want to upgrade.** `moon upgrade` replaces the toolchain in place; `moon upgrade --dev` takes the development build. Both leave `MOON_HOME` and your `PATH` alone. | ||
| 71 | +- **You are installing for CI, or into an image.** The installer is an ordinary shell script and takes no flags worth setting; pinning a version means fetching a release from https://www.moonbitlang.com/download rather than using it. | ||
| 72 | +- **You want to be sure the editor is not simply finding it on `PATH`.** Start it with a stripped environment — `env PATH=/usr/bin:/bin turbo-moonbit main.mbt` — and the status bar should still say `LSP: ready`, from `~/.moon/bin`. | ||
| 73 | + | ||
| 74 | +## What each binary is for | ||
| 75 | + | ||
| 76 | +| Binary | What the editor uses it for | | ||
| 77 | +| --- | --- | | ||
| 78 | +| `moon-lsp` | Completion, hover, definitions, references, symbols and the error marks in the gutter | | ||
| 79 | +| `moon` | Every command in the MoonBit menu — and `moon-lsp` runs it too, to work out what a project holds | | ||
| 80 | +| `moonc` | The compiler, invoked by `moon` | | ||
| 81 | +| `moonrun` | Runs the WebAssembly output, invoked by `moon run` | | ||
| 82 | + | ||
| 83 | +`moon-lsp` on its own is not enough: it works a project out by running `moon`, so a machine with the server but not the build system gets a server that starts, is found, and then knows nothing about any file. `scripts/install.sh` checks for exactly that and says so. | ||
| 84 | + | ||
| 85 | +## See also | ||
| 86 | + | ||
| 87 | +- [How to enable completion](enable-completion.md) — what to do when the server is installed and still says nothing | ||
| 88 | +- [How to run moon commands from the editor](run-moon-commands.md) — the MoonBit menu | ||
| 89 | +- [Colouring and completion](../explanation/colouring-and-completion.md) — why the editor needs a server at all | ||
added
docs/en/how-to/install.md +90 -0 | new file mode 100644 | ||
| @@ -0,0 +1,90 @@ | ||
| 1 | +# How to install and build Turbo MoonBit | |
| 2 | + | |
| 3 | +This guide shows how to get a working `turbo-moonbit` 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-moonbit.git | |
| 9 | +cd turbo-moonbit | |
| 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 `moon-lsp` is installed. The build goes to a temporary file first, so a failed build never replaces a working installation. | |
| 14 | + | |
| 15 | +Then, from any MoonBit project: | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +turbo-moonbit main.mbt | |
| 19 | +``` | |
| 20 | + | |
| 21 | +### Options | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +scripts/install.sh --prefix ~/bin # install somewhere of your choosing | |
| 25 | +scripts/install.sh --with-moon-lsp # 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-moonbit main.mbt | |
| 37 | +``` | |
| 38 | + | |
| 39 | +## From the module proxy, without a checkout | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +go install rickub.com/turbo-editors/turbo-moonbit@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-moonbit -version | |
| 55 | +turbo-moonbit -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-moonbit@latest src/main.mbt` | |
| 63 | +- **You want the binary somewhere specific**: `go build -o /usr/local/bin/turbo-moonbit .` | |
| 64 | +- **Your terminal has no true colour**: use `turbo-moonbit -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 MoonBit. 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 MoonBit 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 MoonBit completion](enable-completion.md) | |
| 89 | +- A guided first session: [Your first MoonBit program in Turbo MoonBit](../tutorials/getting-started.md) | |
| 90 | +- Projects to try it on: [the demos](../../../demos/) | |
| new file mode 100644 | |||
| @@ -0,0 +1,90 @@ | |||
| 1 | +# How to install and build Turbo MoonBit | ||
| 2 | + | ||
| 3 | +This guide shows how to get a working `turbo-moonbit` 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-moonbit.git | ||
| 9 | +cd turbo-moonbit | ||
| 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 `moon-lsp` is installed. The build goes to a temporary file first, so a failed build never replaces a working installation. | ||
| 14 | + | ||
| 15 | +Then, from any MoonBit project: | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +turbo-moonbit main.mbt | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +### Options | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +scripts/install.sh --prefix ~/bin # install somewhere of your choosing | ||
| 25 | +scripts/install.sh --with-moon-lsp # 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-moonbit main.mbt | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +## From the module proxy, without a checkout | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +go install rickub.com/turbo-editors/turbo-moonbit@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-moonbit -version | ||
| 55 | +turbo-moonbit -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-moonbit@latest src/main.mbt` | ||
| 63 | +- **You want the binary somewhere specific**: `go build -o /usr/local/bin/turbo-moonbit .` | ||
| 64 | +- **Your terminal has no true colour**: use `turbo-moonbit -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 MoonBit. 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 MoonBit 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 MoonBit completion](enable-completion.md) | ||
| 89 | +- A guided first session: [Your first MoonBit program in Turbo MoonBit](../tutorials/getting-started.md) | ||
| 90 | +- Projects to try it on: [the demos](../../../demos/) | ||
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-moonbit -version | |
| 31 | +``` | |
| 32 | + | |
| 33 | +``` | |
| 34 | +Turbo MoonBit 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 MoonBit 0.2.0 | |
| 45 | + | |
| 46 | +A Turbo C-style editor for MoonBit, | |
| 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 MoonBit" | |
| 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_MOONBIT_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-moonbit@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 `moon 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-moonbit/internal/version.stamp=v0.2.0'" -o bin/turbo-moonbit . | |
| 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 MoonBit](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-moonbit -version | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +``` | ||
| 34 | +Turbo MoonBit 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 MoonBit 0.2.0 | ||
| 45 | + | ||
| 46 | +A Turbo C-style editor for MoonBit, | ||
| 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 MoonBit" | ||
| 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_MOONBIT_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-moonbit@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 `moon 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-moonbit/internal/version.stamp=v0.2.0'" -o bin/turbo-moonbit . | ||
| 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 MoonBit](install.md) | ||
added
docs/en/how-to/run-moon-commands.md +214 -0 | new file mode 100644 | ||
| @@ -0,0 +1,214 @@ | ||
| 1 | +# How to run moon commands from the editor | |
| 2 | + | |
| 3 | +This guide shows how to format, lint, build, test and run your project without leaving Turbo MoonBit. It assumes the editor is installed and you have a MoonBit project. | |
| 4 | + | |
| 5 | +## Get a starter file | |
| 6 | + | |
| 7 | +Start the editor **from the project's own directory**, then choose **MoonBit ▸ Create tools file** (`Alt-M`, then `C`). | |
| 8 | + | |
| 9 | +That writes `.turbo-moonbit/tools.toml` with the five commands a MoonBit project runs before it commits, and opens it: | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[tool]] | |
| 13 | +name = "~F~ormat" | |
| 14 | +command = "moon fmt" | |
| 15 | +output = "popup" | |
| 16 | + | |
| 17 | +[[tool]] | |
| 18 | +name = "~T~est" | |
| 19 | +command = "moon test" | |
| 20 | +output = "popup" | |
| 21 | + | |
| 22 | +[[tool]] | |
| 23 | +name = "~R~un" | |
| 24 | +command = "moon 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 **MoonBit** 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-M`, 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 | +┌──────────── moon check — exit 1 ────────────┐ | |
| 40 | +│ main.mbt: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-moonbit/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 = "moon fmt && moon check && moon test" | |
| 96 | +output = "popup" | |
| 97 | + | |
| 98 | +[[tool]] | |
| 99 | +name = "~U~pgrade" | |
| 100 | +command = "moon update" | |
| 101 | +output = "popup" | |
| 102 | + | |
| 103 | +[[tool]] | |
| 104 | +name = "Cover~a~ge" | |
| 105 | +command = "moon coverage analyze" | |
| 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 MoonBit does not belong in the MoonBit 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 MoonBit 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 MoonBit, which is where eight of the nine 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 build for one backend and never the others.** Replace `moon build --target {{…}}` with `moon build --target js`, and the box stops appearing. The placeholder is there because a starter file cannot know which of `wasm`, `wasm-gc`, `js`, `native` and `llvm` a project wants. | |
| 148 | +- **You started the editor from a subdirectory.** Commands run there. `moon` looks upwards for `moon.mod`, so most of them still work — but in a `moon.work` workspace the commands that take `--target all` want the workspace root, so start from there. | |
| 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 = "moon new {{project path}}" | |
| 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 = "moon test {{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: [MoonBit tools reference](../reference/moonbit-tools.md) | |
| 213 | +- Why each command gets a terminal window, and why an unmodified file reloads: [MoonBit tools](../explanation/moonbit-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 moon commands from the editor | ||
| 2 | + | ||
| 3 | +This guide shows how to format, lint, build, test and run your project without leaving Turbo MoonBit. It assumes the editor is installed and you have a MoonBit project. | ||
| 4 | + | ||
| 5 | +## Get a starter file | ||
| 6 | + | ||
| 7 | +Start the editor **from the project's own directory**, then choose **MoonBit ▸ Create tools file** (`Alt-M`, then `C`). | ||
| 8 | + | ||
| 9 | +That writes `.turbo-moonbit/tools.toml` with the five commands a MoonBit project runs before it commits, and opens it: | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[tool]] | ||
| 13 | +name = "~F~ormat" | ||
| 14 | +command = "moon fmt" | ||
| 15 | +output = "popup" | ||
| 16 | + | ||
| 17 | +[[tool]] | ||
| 18 | +name = "~T~est" | ||
| 19 | +command = "moon test" | ||
| 20 | +output = "popup" | ||
| 21 | + | ||
| 22 | +[[tool]] | ||
| 23 | +name = "~R~un" | ||
| 24 | +command = "moon 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 **MoonBit** 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-M`, 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 | +┌──────────── moon check — exit 1 ────────────┐ | ||
| 40 | +│ main.mbt: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-moonbit/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 = "moon fmt && moon check && moon test" | ||
| 96 | +output = "popup" | ||
| 97 | + | ||
| 98 | +[[tool]] | ||
| 99 | +name = "~U~pgrade" | ||
| 100 | +command = "moon update" | ||
| 101 | +output = "popup" | ||
| 102 | + | ||
| 103 | +[[tool]] | ||
| 104 | +name = "Cover~a~ge" | ||
| 105 | +command = "moon coverage analyze" | ||
| 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 MoonBit does not belong in the MoonBit 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 MoonBit 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 MoonBit, which is where eight of the nine 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 build for one backend and never the others.** Replace `moon build --target {{…}}` with `moon build --target js`, and the box stops appearing. The placeholder is there because a starter file cannot know which of `wasm`, `wasm-gc`, `js`, `native` and `llvm` a project wants. | ||
| 148 | +- **You started the editor from a subdirectory.** Commands run there. `moon` looks upwards for `moon.mod`, so most of them still work — but in a `moon.work` workspace the commands that take `--target all` want the workspace root, so start from there. | ||
| 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 = "moon new {{project path}}" | ||
| 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 = "moon test {{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: [MoonBit tools reference](../reference/moonbit-tools.md) | ||
| 213 | +- Why each command gets a terminal window, and why an unmodified file reloads: [MoonBit tools](../explanation/moonbit-tools.md) | ||
| 214 | +- The windows the commands run in: [Terminal windows](../reference/terminal.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 MoonBit'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 `go test ./...` 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 `moon-lsp` 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 `moon-lsp` 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 MoonBit 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 MoonBit'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 `go test ./...` 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 `moon-lsp` 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 `moon-lsp` 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 MoonBit 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/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 MoonBit 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 MoonBit running in a project. | |
| 4 | + | |
| 5 | +Turbo MoonBit 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-moonbit/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-moonbit/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-moonbit/` is a reasonable place to keep it so that it travels with the project. For `docker agent`, saving this as `.turbo-moonbit/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 | +│ ```moonbit │ | |
| 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 MoonBit answer is coloured as MoonBit 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-moonbit/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 MoonBit 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 MoonBit running in a project. | ||
| 4 | + | ||
| 5 | +Turbo MoonBit 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-moonbit/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-moonbit/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-moonbit/` is a reasonable place to keep it so that it travels with the project. For `docker agent`, saving this as `.turbo-moonbit/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 | +│ ```moonbit │ | ||
| 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 MoonBit answer is coloured as MoonBit 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-moonbit/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 MoonBit 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: `moon install` 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-moonbit` 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 MoonBit 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: `moon install` 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-moonbit` 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 MoonBit 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-moonbit/snippets.toml`, filled in with a few worked examples, and opens it — coloured, because Turbo MoonBit colours TOML: | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[snippet]] | |
| 13 | +name = "if err != nil" | |
| 14 | +group = "MoonBit" | |
| 15 | +languages = ["moonbit"] | |
| 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-moonbit/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 — `moonbit`, `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-moonbit` 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-moonbit`: [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 MoonBit 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-moonbit/snippets.toml`, filled in with a few worked examples, and opens it — coloured, because Turbo MoonBit colours TOML: | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[snippet]] | ||
| 13 | +name = "if err != nil" | ||
| 14 | +group = "MoonBit" | ||
| 15 | +languages = ["moonbit"] | ||
| 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-moonbit/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 — `moonbit`, `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-moonbit` 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-moonbit`: [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-moonbit -list-themes | |
| 9 | +``` | |
| 10 | + | |
| 11 | +The last line tells you the directory — `~/.config/turbo-moonbit/themes` on Linux, `~/Library/Application Support/turbo-moonbit/themes` on macOS. Create it: | |
| 12 | + | |
| 13 | +```bash | |
| 14 | +mkdir -p ~/.config/turbo-moonbit/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-moonbit/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-moonbit -theme mine main.mbt | |
| 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 MoonBit falls back to the default rather than refusing to start. To see *why* it failed: | |
| 49 | + | |
| 50 | +```bash | |
| 51 | +turbo-moonbit -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_MOONBIT_THEME_DIR=./my-themes turbo-moonbit -theme mine main.mbt | |
| 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 MoonBit, 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-moonbit -list-themes | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +The last line tells you the directory — `~/.config/turbo-moonbit/themes` on Linux, `~/Library/Application Support/turbo-moonbit/themes` on macOS. Create it: | ||
| 12 | + | ||
| 13 | +```bash | ||
| 14 | +mkdir -p ~/.config/turbo-moonbit/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-moonbit/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-moonbit -theme mine main.mbt | ||
| 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 MoonBit falls back to the default rather than refusing to start. To see *why* it failed: | ||
| 49 | + | ||
| 50 | +```bash | ||
| 51 | +turbo-moonbit -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_MOONBIT_THEME_DIR=./my-themes turbo-moonbit -theme mine main.mbt | ||
| 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 MoonBit, 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 MoonBit 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-moonbit/acp.toml` | first | Agents you want in every project | | |
| 10 | +| `<project>/.turbo-moonbit/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_MOONBIT_DIR` overrides the directory the user-level file is looked for in. The project file is always `.turbo-moonbit/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-moonbit/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-moonbit/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 MoonBit 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 — `moonbit`, `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 MoonBit 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-moonbit/acp.toml` | first | Agents you want in every project | | ||
| 10 | +| `<project>/.turbo-moonbit/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_MOONBIT_DIR` overrides the directory the user-level file is looked for in. The project file is always `.turbo-moonbit/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-moonbit/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-moonbit/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 MoonBit 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 — `moonbit`, `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-moonbit` command, its flags, and the environment it reads. | |
| 4 | + | |
| 5 | +## Synopsis | |
| 6 | + | |
| 7 | +``` | |
| 8 | +turbo-moonbit [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 MoonBit <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_MOONBIT_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` | moon-lsp lookup | Searched, in that order, when `moon-lsp` is not on `PATH`. | | |
| 30 | + | |
| 31 | +## Files | |
| 32 | + | |
| 33 | +| Path | Purpose | | |
| 34 | +| --- | --- | | |
| 35 | +| `$TURBO_MOONBIT_THEME_DIR/*.toml` | User themes, when the variable is set. | | |
| 36 | +| `./.turbo-moonbit/settings.toml` | This project's settings, read once at start-up. See [project settings](project-settings.md). | | |
| 37 | +| `~/.config/turbo-moonbit/themes/*.toml` | User themes on Linux (`os.UserConfigDir`). | | |
| 38 | +| `~/Library/Application Support/turbo-moonbit/themes/*.toml` | User themes on macOS. | | |
| 39 | +| `<module>/moon.mod`, `<module>/moon.mod.json` | Located by walking up from the first file; the nearest directory holding either 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` | `go test ./...` | | |
| 56 | +| `make test-verbose` | `go test -v ./...` | | |
| 57 | +| `make cover` | `go test -cover ./...` | | |
| 58 | +| `make build` | `go build -o bin/turbo-moonbit .` | | |
| 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-moonbit x.go` | | |
| 62 | +| `make fmt` | `go fmt ./...` | | |
| 63 | +| `make vet` | `go vet ./...` | | |
| 64 | +| `make check` | `fmt`, then `vet`, then `test` | | |
| 65 | +| `make clean` | Remove `bin/` | | |
| 66 | + | |
| 67 | +## Examples | |
| 68 | + | |
| 69 | +```bash | |
| 70 | +turbo-moonbit # one empty window | |
| 71 | +turbo-moonbit main.mbt moon.mod # two windows | |
| 72 | +turbo-moonbit -theme turbo-dark main.mbt # a different theme | |
| 73 | +turbo-moonbit -no-lsp main.mbt # no language server | |
| 74 | +turbo-moonbit -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-moon-lsp` | Install `moon-lsp` as well, if it is not already there. | | |
| 85 | +| `--uninstall` | Remove an installed `turbo-moonbit` 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-moonbit: opening the terminal: …` | tcell could not open the terminal; usually `TERM` is unset or unknown. | | |
| 98 | +| `turbo-moonbit: 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-moonbit` command, its flags, and the environment it reads. | ||
| 4 | + | ||
| 5 | +## Synopsis | ||
| 6 | + | ||
| 7 | +``` | ||
| 8 | +turbo-moonbit [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 MoonBit <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_MOONBIT_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` | moon-lsp lookup | Searched, in that order, when `moon-lsp` is not on `PATH`. | | ||
| 30 | + | ||
| 31 | +## Files | ||
| 32 | + | ||
| 33 | +| Path | Purpose | | ||
| 34 | +| --- | --- | | ||
| 35 | +| `$TURBO_MOONBIT_THEME_DIR/*.toml` | User themes, when the variable is set. | | ||
| 36 | +| `./.turbo-moonbit/settings.toml` | This project's settings, read once at start-up. See [project settings](project-settings.md). | | ||
| 37 | +| `~/.config/turbo-moonbit/themes/*.toml` | User themes on Linux (`os.UserConfigDir`). | | ||
| 38 | +| `~/Library/Application Support/turbo-moonbit/themes/*.toml` | User themes on macOS. | | ||
| 39 | +| `<module>/moon.mod`, `<module>/moon.mod.json` | Located by walking up from the first file; the nearest directory holding either 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` | `go test ./...` | | ||
| 56 | +| `make test-verbose` | `go test -v ./...` | | ||
| 57 | +| `make cover` | `go test -cover ./...` | | ||
| 58 | +| `make build` | `go build -o bin/turbo-moonbit .` | | ||
| 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-moonbit x.go` | | ||
| 62 | +| `make fmt` | `go fmt ./...` | | ||
| 63 | +| `make vet` | `go vet ./...` | | ||
| 64 | +| `make check` | `fmt`, then `vet`, then `test` | | ||
| 65 | +| `make clean` | Remove `bin/` | | ||
| 66 | + | ||
| 67 | +## Examples | ||
| 68 | + | ||
| 69 | +```bash | ||
| 70 | +turbo-moonbit # one empty window | ||
| 71 | +turbo-moonbit main.mbt moon.mod # two windows | ||
| 72 | +turbo-moonbit -theme turbo-dark main.mbt # a different theme | ||
| 73 | +turbo-moonbit -no-lsp main.mbt # no language server | ||
| 74 | +turbo-moonbit -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-moon-lsp` | Install `moon-lsp` as well, if it is not already there. | | ||
| 85 | +| `--uninstall` | Remove an installed `turbo-moonbit` 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-moonbit: opening the terminal: …` | tcell could not open the terminal; usually `TERM` is unset or unknown. | | ||
| 98 | +| `turbo-moonbit: 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 MoonBit 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-M` | Open the MoonBit 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 [MoonBit tools](moonbit-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 MoonBit 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-M` | Open the MoonBit 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 [MoonBit tools](moonbit-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 +296 -0 | new file mode 100644 | ||
| @@ -0,0 +1,296 @@ | ||
| 1 | +# Reference: languages coloured | |
| 2 | + | |
| 3 | +> Neutral description of which files Turbo MoonBit 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 | +| `.mbt`, `.mbti`, `.mbtx` | MoonBit | | |
| 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: `README.mbt.md` is Markdown, and `main.mbt.backup` is not MoonBit. | |
| 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 | +`moon.mod`, `moon.pkg` and `moon.work` are **not** in that table. They are MoonBit's own configuration DSL rather than MoonBit, and their legacy JSON forms — `moon.mod.json`, `moon.pkg.json` — are not JSON that this editor colours either. All five open in plain text. | |
| 32 | + | |
| 33 | +A file that neither table claims is read by its **first line**. A shebang naming a shell — `sh`, `bash`, `zsh`, `dash` or `ksh` — makes it a shell script, and 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`. | |
| 34 | + | |
| 35 | +**No shebang makes a file MoonBit.** The language has no interpreter line: a file opening with `#!` would lex as an attribute named `!` and fail. A file with no extension is not MoonBit, and claiming otherwise would take a shell script away from the scanner that can actually colour it. | |
| 36 | + | |
| 37 | +| First line | Result | | |
| 38 | +| --- | --- | | |
| 39 | +| `#!/bin/sh` | Shell | | |
| 40 | +| `#!/usr/bin/env bash` | Shell | | |
| 41 | +| `#!/usr/bin/env -S bash -e` | Shell | | |
| 42 | +| `#!/usr/bin/env moon` | Not coloured | | |
| 43 | +| `#!/usr/bin/env node` | Not coloured | | |
| 44 | +| Anything not starting `#!` | Not coloured | | |
| 45 | + | |
| 46 | +The order is fixed — extension, then name, then first line — and the first to decide wins. | |
| 47 | + | |
| 48 | +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. | |
| 49 | + | |
| 50 | +## Classes | |
| 51 | + | |
| 52 | +Every scanner produces the same vocabulary of classes, and each maps to one theme key. | |
| 53 | + | |
| 54 | +| Class | Theme key | Produced by | | |
| 55 | +| --- | --- | --- | | |
| 56 | +| `identifier` | `syntax.identifier` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 57 | +| `keyword` | `syntax.keyword` | MoonBit, JavaScript, shell, HTML (doctype), XML, Dockerfile | | |
| 58 | +| `type` | `syntax.type` | MoonBit (every capitalised name, and package qualifiers), TOML (table headers), YAML (tags) | | |
| 59 | +| `builtin` | `syntax.builtin` | MoonBit (the prelude), JavaScript, shell (builtins and expansions), YAML (anchors and aliases), Dockerfile (variables) | | |
| 60 | +| `constant` | `syntax.constant` | MoonBit, TOML, JavaScript, shell, YAML, HTML and XML (entities) | | |
| 61 | +| `function` | `syntax.function` | MoonBit, JavaScript, shell (the command) | | |
| 62 | +| `string` | `syntax.string` | all | | |
| 63 | +| `char` | `syntax.char` | MoonBit (`'c'` and `b'c'`) | | |
| 64 | +| `number` | `syntax.number` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 65 | +| `comment` | `syntax.comment` | MoonBit, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | |
| 66 | +| `operator` | `syntax.operator` | MoonBit, TOML, JavaScript, shell, HTML, YAML (block scalar headers), XML, Dockerfile | | |
| 67 | +| `punctuation` | `syntax.punctuation` | MoonBit, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | |
| 68 | +| `heading` | `syntax.heading` | Markdown | | |
| 69 | +| `tag` | `syntax.tag` | HTML, XML | | |
| 70 | +| `attribute` | `syntax.attribute` | MoonBit (attributes and labelled arguments), HTML, XML, Dockerfile (flags) | | |
| 71 | +| `emphasis` | `syntax.emphasis` | Markdown | | |
| 72 | +| `link` | `syntax.link` | Markdown | | |
| 73 | + | |
| 74 | +In `turbo-classic` alone, `syntax.attribute` and `syntax.identifier` are both plain yellow, so a MoonBit attribute or label is not told apart from an ordinary name in that one theme. The other seven give them different colours. See [how to write your own theme](../how-to/write-a-theme.md) if you want to change it. | |
| 75 | + | |
| 76 | +## MoonBit | |
| 77 | + | |
| 78 | +Hand-written, in `internal/moonbitlang`. **Nothing crosses a line break**, and that is a property of the language rather than a simplification: MoonBit has no block comment, a newline before a closing quote is an *unterminated literal* error, a multi-line string is a run of self-contained `#|` or `$|` lines, and an attribute is explicitly one line. So a stray quote colours to the end of its line and the next line is code again. | |
| 79 | + | |
| 80 | +| Recognised | As | | |
| 81 | +| --- | --- | | |
| 82 | +| `and`, `as`, `async`, `break`, `catch`, `const`, `continue`, `declare`, `defer`, `derive`, `else`, `enum`, `enumview`, `extend`, `extenum`, `extern`, `fn`, `for`, `guard`, `if`, `impl`, `import`, `in`, `is`, `let`, `letrec`, `lexscan`, `loop`, `match`, `mut`, `nobreak`, `nocancel`, `noraise`, `package`, `priv`, `proof_assert`, `proof_let`, `pub`, `raise`, `readonly`, `return`, `struct`, `suberror`, `test`, `throw`, `trait`, `try`, `type`, `using`, `where`, `while`, `with` | keyword | | |
| 83 | +| `try!` and `guard!`, mark included | keyword | | |
| 84 | +| `true`, `false`, `None`, `Some`, `Ok`, `Err` | constant | | |
| 85 | +| any name starting with an ASCII capital — `Int`, `StringBuilder`, `Shape`, `Circle` | type | | |
| 86 | +| `println`, `abort`, `panic`, `fail`, `ignore`, `inspect`, `debug`, `repr`, `hash`, `compare`, `null`, `assert_eq`, `assert_not_eq`, `assert_true`, `assert_false`, `debug_assert`, `debug_inspect`, `json_inspect`, `physical_equal` | builtin | | |
| 87 | +| any other lower-case name immediately before `(` | function | | |
| 88 | +| `"…"`, `b"…"`, `re"…"` | string | | |
| 89 | +| `'c'`, `b'c'` | char | | |
| 90 | +| `#\|` and `$\|` | the two-rune prefix as punctuation, the rest of the line as string | | |
| 91 | +| `42`, `1_000`, `0xFF_FF`, `0o17`, `0b1010`, `1.5`, `1.`, `1.5e-3`, `0x1.8p3F`, `42U`, `42L`, `42UL`, `42N`, `1.0F` | number | | |
| 92 | +| `//` and `///` to the end of the line | comment | | |
| 93 | +| `#deprecated("…")`, `#external`, `#custom.attribute(key="v")` — the whole line | attribute | | |
| 94 | +| `name~` in a labelled argument, tilde included | attribute | | |
| 95 | +| `@json`, `@moonbitlang/core/builtin`, `@my-pkg` — the `@` included, as one span | type | | |
| 96 | +| `.0` in a tuple accessor | the dot as punctuation, the digits as number | | |
| 97 | +| `..`, `..=`, `..<`, `...` | operator | | |
| 98 | +| runs of `+-*/%=<>!&\|^~?:` | operator | | |
| 99 | +| `()[]{},;.` | punctuation | | |
| 100 | + | |
| 101 | +**Nothing here is a table of built-in types, and nothing needs to be.** MoonBit's identifier case is a *lexical* rule rather than a convention: the grammar says a `uident` "begins with an ASCII uppercase letter", and only a type, a trait or an enum constructor may be spelt that way. `Int`, `StringBuilder` and a type somebody wrote this morning are all coloured by the same line. Every other scanner in this family needs a table here; this one does not. | |
| 102 | + | |
| 103 | +**An integer ends before `..`.** The grammar is explicit — "before `..`, an integer ends first, so `1..=2` begins with `1` and `..=`" — so a dot is only part of a number when a second one does not follow it. Without that rule `1..=2` reads as the double `1.` and then `.=2`, and every range in the file is miscoloured. | |
| 104 | + | |
| 105 | +**A number's suffix is upper case or it is not a suffix.** `42UL` is one number; `42u` is the number `42` followed by the name `u`, which is what the compiler sees too. | |
| 106 | + | |
| 107 | +**An attribute takes the whole line.** The grammar hands it everything after the dotted name: "everything through the next newline is the raw payload". Colouring less than the line would be inventing a structure the lexer does not have. | |
| 108 | + | |
| 109 | +**`#|` and `#deprecated` are told apart by the rune after the `#`.** An attribute's name must start with a letter or an underscore; a multi-line string line has a bar there. | |
| 110 | + | |
| 111 | +**A doc comment is coloured like any other comment.** `///`, `///|` and `//` all reach `syntax.comment`, because turbo-core's set of classes is closed on purpose — that is what lets one theme colour every language an editor will ever learn. | |
| 112 | + | |
| 113 | +**A name after a dot is never a keyword.** MoonBit's dot-identifiers "use the identifier case rules without consulting the keyword table, so `.if` is valid" — a record with a field called `type` is ordinary MoonBit. | |
| 114 | + | |
| 115 | +**`package` is coloured as a keyword in a `.mbt` file too**, although it is only a *reserved* word there. It is a real keyword in the `.mbti` interface files this editor also colours, and in a `.mbt` file the colour says exactly what the compiler is about to: this word is not yours to use. The rest of the reserved list — `move`, `ref`, `static`, `unsafe`, `await` and the forty others — is deliberately left alone, because those really are names you may use. | |
| 116 | + | |
| 117 | +**A tilde against the end of a lower-case name is a label**, and against anything else it is not: the grammar says "ASCII-uppercase identifiers and keywords cannot form labels", so `Foo~` is a type and a tilde. | |
| 118 | + | |
| 119 | +**Not recognised**, each for a stated reason: | |
| 120 | + | |
| 121 | +| Not recognised | Because | | |
| 122 | +| --- | --- | | |
| 123 | +| The expression inside `\{…}` | The grammar matches it to "the matching `}`", with braces inside nested literals not counting — finding the end needs the parser. `"a \{b} c"` is therefore one string span, brace to brace. **A string nested inside an interpolation is where that stops**: the scanner takes the first unescaped quote as the closer, so `"a \{f("x")} c"` scans as string, then `x` as an identifier, then string. The spans stay in order and never overlap; the cost is a wrong colour inside a nested literal, which is rarer than the brace-counting bugs the alternative would cause | | |
| 124 | +| An enum constructor of your own, as anything but a type | Nothing in the syntax separates `Circle(1.0)` from a type applied to arguments; inventing a separation means being wrong in both directions instead of one | | |
| 125 | +| `.5` as a number | MoonBit requires a digit before the point, so a leading dot is a tuple accessor or a dot-identifier and never a literal | | |
| 126 | +| A reserved word as a keyword | `move`, `ref` and the rest are identifiers the compiler merely warns about, and colouring them would tell a reader they cannot write `let ref = 1` when they can | | |
| 127 | +| An identifier holding non-ASCII letters | MoonBit allows CJK and several other ranges in a name; the rune predicates this scanner is built on are ASCII, so such a name is stepped over uncoloured rather than guessed at | | |
| 128 | +| `.mbt.md` as MoonBit | It is a Markdown document with MoonBit in its fences. Its extension is `.md`, and Markdown is what colours it | | |
| 129 | +| 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) | | |
| 130 | + | |
| 131 | +## TOML | |
| 132 | + | |
| 133 | +| Recognised | As | | |
| 134 | +| --- | --- | | |
| 135 | +| `# comment` | comment | | |
| 136 | +| `[table]`, `[[array]]` | the name as a type, the brackets as punctuation | | |
| 137 | +| `key =` | identifier, then operator | | |
| 138 | +| `"basic"`, `'literal'`, `"""multi-line"""`, `'''multi-line'''` | string | | |
| 139 | +| `true`, `false` | constant | | |
| 140 | +| numbers, dates, times, `inf`, `nan` | number | | |
| 141 | + | |
| 142 | +## YAML | |
| 143 | + | |
| 144 | +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. | |
| 145 | + | |
| 146 | +| Recognised | As | | |
| 147 | +| --- | --- | | |
| 148 | +| `# comment` | comment | | |
| 149 | +| `key:` before a space or the end of the line | the key as an identifier, the colon as punctuation | | |
| 150 | +| `"quoted": 1`, `'quoted': 1` | the quoted key as an identifier | | |
| 151 | +| `- ` opening a sequence entry | punctuation | | |
| 152 | +| `"…"`, `'…'` | string | | |
| 153 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constant, whatever their case | | |
| 154 | +| numbers, dates and times written without quotes | number | | |
| 155 | +| `&anchor`, `*alias` | builtin | | |
| 156 | +| `!!str`, `!Custom` | type | | |
| 157 | +| `---`, `...` | the whole line as punctuation | | |
| 158 | +| `{`, `}`, `[`, `]`, `,` | punctuation | | |
| 159 | +| `\|`, `>`, with their chomping and indentation indicators | the header as an operator, the body as a string | | |
| 160 | + | |
| 161 | +**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. | |
| 162 | + | |
| 163 | +**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. | |
| 164 | + | |
| 165 | +**A `#` needs a space before it to start a comment**, so `colour: ff#00aa` is one scalar. | |
| 166 | + | |
| 167 | +| Not recognised | Because | | |
| 168 | +| --- | --- | | |
| 169 | +| 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 | | |
| 170 | +| Multi-document streams as separate documents | `---` is coloured, but nothing is reset at it; nothing in the colouring depends on document boundaries | | |
| 171 | +| 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 | | |
| 172 | + | |
| 173 | +## Markdown | |
| 174 | + | |
| 175 | +| Recognised | As | | |
| 176 | +| --- | --- | | |
| 177 | +| `# Heading` … `###### Heading` | the whole line as a heading | | |
| 178 | +| `**bold**`, `__bold__`, `*italic*`, `_italic_` | emphasis | | |
| 179 | +| `` `code` `` | string | | |
| 180 | +| `[text](target)`, `` | the whole thing as a link | | |
| 181 | +| `- `, `* `, `+ `, `1. `, `1) ` | the marker as punctuation | | |
| 182 | +| `>` | punctuation | | |
| 183 | +| `---`, `***`, `___` | punctuation | | |
| 184 | +| ` ``` ` and `~~~` fences | the whole block, opening and closing lines included, as a string | | |
| 185 | + | |
| 186 | +A fenced block is **one colour whatever language it announces**: ```` ```moonbit ```` does not colour its contents as MoonBit. 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. | |
| 187 | + | |
| 188 | +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. | |
| 189 | + | |
| 190 | +## JavaScript | |
| 191 | + | |
| 192 | +| Recognised | As | | |
| 193 | +| --- | --- | | |
| 194 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | |
| 195 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | |
| 196 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | |
| 197 | +| a name immediately before `(` | function | | |
| 198 | +| `"…"`, `'…'` | string | | |
| 199 | +| `` `…` ``, interpolations included, across lines | string | | |
| 200 | +| `//` to end of line, `/* … */` across lines | comment | | |
| 201 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | |
| 202 | +| runs of `+-*/%=<>!&|^~?:` | operator | | |
| 203 | +| `()[]{},;.` | punctuation | | |
| 204 | + | |
| 205 | +**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. | |
| 206 | + | |
| 207 | +Globals are recognised by name, so a file that shadows `Math` still has it coloured as a builtin — the same rule MoonBit's builtins follow here. | |
| 208 | + | |
| 209 | +## HTML | |
| 210 | + | |
| 211 | +| Recognised | As | | |
| 212 | +| --- | --- | | |
| 213 | +| `<tag`, `</tag`, `>`, `/>` | tag | | |
| 214 | +| attribute names, including `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | |
| 215 | +| `=` | operator | | |
| 216 | +| `"…"`, `'…'` | string | | |
| 217 | +| `<!-- … -->`, across lines | comment | | |
| 218 | +| `&`, `©` | constant | | |
| 219 | +| `<!DOCTYPE …>` and other declarations | keyword | | |
| 220 | + | |
| 221 | +Text between tags is not coloured. A bare `&` with no `;` within 32 characters is left alone, because it is legal text. | |
| 222 | + | |
| 223 | +**The contents of `<script>` and `<style>` are not coloured** as JavaScript and CSS. | |
| 224 | + | |
| 225 | +## XML | |
| 226 | + | |
| 227 | +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. | |
| 228 | + | |
| 229 | +| Recognised | As | | |
| 230 | +| --- | --- | | |
| 231 | +| `<?xml version="1.0"?>` and other processing instructions | the target and `?>` as keyword, the pairs between as attributes and strings | | |
| 232 | +| `<!DOCTYPE …>` and the other `<!` forms | keyword | | |
| 233 | +| `<!-- … -->`, across lines | comment | | |
| 234 | +| `<![CDATA[ … ]]>`, across lines | string | | |
| 235 | +| `<tag`, `</tag`, `>`, `/>` | tag | | |
| 236 | +| `<ns:tag>`, `xsi:type` | the prefix and the local name as **one** span | | |
| 237 | +| attribute names | attribute | | |
| 238 | +| `=` | operator | | |
| 239 | +| `"…"`, `'…'` | string | | |
| 240 | +| `&`, `©` | constant | | |
| 241 | + | |
| 242 | +**A comment and a CDATA section close on different delimiters**, and are carried separately: a `-->` inside a CDATA section does not end it. | |
| 243 | + | |
| 244 | +**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. | |
| 245 | + | |
| 246 | +Text between tags is not coloured. | |
| 247 | + | |
| 248 | +## Shell | |
| 249 | + | |
| 250 | +Applies to `sh`, `bash` and `zsh` alike: the keywords recognised are the ones they share. | |
| 251 | + | |
| 252 | +| Recognised | As | | |
| 253 | +| --- | --- | | |
| 254 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | |
| 255 | +| `true`, `false` | constant | | |
| 256 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | |
| 257 | +| `$NAME`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | |
| 258 | +| the **first bare word on a line** | function | | |
| 259 | +| every later bare word, and `NAME` in `NAME=value` | identifier | | |
| 260 | +| `'…'`, with nothing escaped or expanded inside | string | | |
| 261 | +| `"…"`, with the expansions inside it coloured as expansions | string | | |
| 262 | +| `#` to end of line | comment | | |
| 263 | + | |
| 264 | +`$(a $(b) c)` is one span: nesting is counted. An option such as `-euo` is one word, not a minus and a word. | |
| 265 | + | |
| 266 | +**Heredocs are not recognised.** `<<EOF` and the text after it are coloured as ordinary shell. | |
| 267 | + | |
| 268 | +## Dockerfile | |
| 269 | + | |
| 270 | +| Recognised | As | | |
| 271 | +| --- | --- | | |
| 272 | +| `FROM`, `RUN`, `COPY`, `ADD`, `ARG`, `ENV`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `LABEL`, `USER`, `VOLUME`, `WORKDIR`, `HEALTHCHECK`, `ONBUILD`, `SHELL`, `STOPSIGNAL`, `MAINTAINER` | keyword, in any case | | |
| 273 | +| `AS`, `NONE` | keyword | | |
| 274 | +| `# comment`, including the `# syntax=` and `# escape=` directives | comment | | |
| 275 | +| `--from=builder`, `--chown=me:me` | the flag name as an attribute | | |
| 276 | +| `$NAME`, `${NAME}`, `${NAME:-default}` | builtin, as one span to the closing brace | | |
| 277 | +| `"…"`, `'…'` | string | | |
| 278 | +| a trailing `\` | operator | | |
| 279 | +| numbers | number | | |
| 280 | +| paths and image references — `/usr/local/bin`, `golang:1.26-alpine` | identifier, as **one** span | | |
| 281 | + | |
| 282 | +**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. | |
| 283 | + | |
| 284 | +**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. | |
| 285 | + | |
| 286 | +| Not recognised | Because | | |
| 287 | +| --- | --- | | |
| 288 | +| 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 | | |
| 289 | +| Heredocs in a `RUN` | The same reason the shell scanner does not recognise them | | |
| 290 | +| Which stage a `--from` names | Nothing here reads the rest of the file | | |
| 291 | + | |
| 292 | +## See also | |
| 293 | + | |
| 294 | +- [Theme file format](themes.md) — every key these classes resolve to | |
| 295 | +- [Colouring and completion](../explanation/colouring-and-completion.md) — why the scanners are written this way | |
| 296 | +- [How to write your own theme](../how-to/write-a-theme.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,296 @@ | |||
| 1 | +# Reference: languages coloured | ||
| 2 | + | ||
| 3 | +> Neutral description of which files Turbo MoonBit 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 | +| `.mbt`, `.mbti`, `.mbtx` | MoonBit | | ||
| 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: `README.mbt.md` is Markdown, and `main.mbt.backup` is not MoonBit. | ||
| 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 | +`moon.mod`, `moon.pkg` and `moon.work` are **not** in that table. They are MoonBit's own configuration DSL rather than MoonBit, and their legacy JSON forms — `moon.mod.json`, `moon.pkg.json` — are not JSON that this editor colours either. All five open in plain text. | ||
| 32 | + | ||
| 33 | +A file that neither table claims is read by its **first line**. A shebang naming a shell — `sh`, `bash`, `zsh`, `dash` or `ksh` — makes it a shell script, and 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`. | ||
| 34 | + | ||
| 35 | +**No shebang makes a file MoonBit.** The language has no interpreter line: a file opening with `#!` would lex as an attribute named `!` and fail. A file with no extension is not MoonBit, and claiming otherwise would take a shell script away from the scanner that can actually colour it. | ||
| 36 | + | ||
| 37 | +| First line | Result | | ||
| 38 | +| --- | --- | | ||
| 39 | +| `#!/bin/sh` | Shell | | ||
| 40 | +| `#!/usr/bin/env bash` | Shell | | ||
| 41 | +| `#!/usr/bin/env -S bash -e` | Shell | | ||
| 42 | +| `#!/usr/bin/env moon` | Not coloured | | ||
| 43 | +| `#!/usr/bin/env node` | Not coloured | | ||
| 44 | +| Anything not starting `#!` | Not coloured | | ||
| 45 | + | ||
| 46 | +The order is fixed — extension, then name, then first line — and the first to decide wins. | ||
| 47 | + | ||
| 48 | +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. | ||
| 49 | + | ||
| 50 | +## Classes | ||
| 51 | + | ||
| 52 | +Every scanner produces the same vocabulary of classes, and each maps to one theme key. | ||
| 53 | + | ||
| 54 | +| Class | Theme key | Produced by | | ||
| 55 | +| --- | --- | --- | | ||
| 56 | +| `identifier` | `syntax.identifier` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 57 | +| `keyword` | `syntax.keyword` | MoonBit, JavaScript, shell, HTML (doctype), XML, Dockerfile | | ||
| 58 | +| `type` | `syntax.type` | MoonBit (every capitalised name, and package qualifiers), TOML (table headers), YAML (tags) | | ||
| 59 | +| `builtin` | `syntax.builtin` | MoonBit (the prelude), JavaScript, shell (builtins and expansions), YAML (anchors and aliases), Dockerfile (variables) | | ||
| 60 | +| `constant` | `syntax.constant` | MoonBit, TOML, JavaScript, shell, YAML, HTML and XML (entities) | | ||
| 61 | +| `function` | `syntax.function` | MoonBit, JavaScript, shell (the command) | | ||
| 62 | +| `string` | `syntax.string` | all | | ||
| 63 | +| `char` | `syntax.char` | MoonBit (`'c'` and `b'c'`) | | ||
| 64 | +| `number` | `syntax.number` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 65 | +| `comment` | `syntax.comment` | MoonBit, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | ||
| 66 | +| `operator` | `syntax.operator` | MoonBit, TOML, JavaScript, shell, HTML, YAML (block scalar headers), XML, Dockerfile | | ||
| 67 | +| `punctuation` | `syntax.punctuation` | MoonBit, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | ||
| 68 | +| `heading` | `syntax.heading` | Markdown | | ||
| 69 | +| `tag` | `syntax.tag` | HTML, XML | | ||
| 70 | +| `attribute` | `syntax.attribute` | MoonBit (attributes and labelled arguments), HTML, XML, Dockerfile (flags) | | ||
| 71 | +| `emphasis` | `syntax.emphasis` | Markdown | | ||
| 72 | +| `link` | `syntax.link` | Markdown | | ||
| 73 | + | ||
| 74 | +In `turbo-classic` alone, `syntax.attribute` and `syntax.identifier` are both plain yellow, so a MoonBit attribute or label is not told apart from an ordinary name in that one theme. The other seven give them different colours. See [how to write your own theme](../how-to/write-a-theme.md) if you want to change it. | ||
| 75 | + | ||
| 76 | +## MoonBit | ||
| 77 | + | ||
| 78 | +Hand-written, in `internal/moonbitlang`. **Nothing crosses a line break**, and that is a property of the language rather than a simplification: MoonBit has no block comment, a newline before a closing quote is an *unterminated literal* error, a multi-line string is a run of self-contained `#|` or `$|` lines, and an attribute is explicitly one line. So a stray quote colours to the end of its line and the next line is code again. | ||
| 79 | + | ||
| 80 | +| Recognised | As | | ||
| 81 | +| --- | --- | | ||
| 82 | +| `and`, `as`, `async`, `break`, `catch`, `const`, `continue`, `declare`, `defer`, `derive`, `else`, `enum`, `enumview`, `extend`, `extenum`, `extern`, `fn`, `for`, `guard`, `if`, `impl`, `import`, `in`, `is`, `let`, `letrec`, `lexscan`, `loop`, `match`, `mut`, `nobreak`, `nocancel`, `noraise`, `package`, `priv`, `proof_assert`, `proof_let`, `pub`, `raise`, `readonly`, `return`, `struct`, `suberror`, `test`, `throw`, `trait`, `try`, `type`, `using`, `where`, `while`, `with` | keyword | | ||
| 83 | +| `try!` and `guard!`, mark included | keyword | | ||
| 84 | +| `true`, `false`, `None`, `Some`, `Ok`, `Err` | constant | | ||
| 85 | +| any name starting with an ASCII capital — `Int`, `StringBuilder`, `Shape`, `Circle` | type | | ||
| 86 | +| `println`, `abort`, `panic`, `fail`, `ignore`, `inspect`, `debug`, `repr`, `hash`, `compare`, `null`, `assert_eq`, `assert_not_eq`, `assert_true`, `assert_false`, `debug_assert`, `debug_inspect`, `json_inspect`, `physical_equal` | builtin | | ||
| 87 | +| any other lower-case name immediately before `(` | function | | ||
| 88 | +| `"…"`, `b"…"`, `re"…"` | string | | ||
| 89 | +| `'c'`, `b'c'` | char | | ||
| 90 | +| `#\|` and `$\|` | the two-rune prefix as punctuation, the rest of the line as string | | ||
| 91 | +| `42`, `1_000`, `0xFF_FF`, `0o17`, `0b1010`, `1.5`, `1.`, `1.5e-3`, `0x1.8p3F`, `42U`, `42L`, `42UL`, `42N`, `1.0F` | number | | ||
| 92 | +| `//` and `///` to the end of the line | comment | | ||
| 93 | +| `#deprecated("…")`, `#external`, `#custom.attribute(key="v")` — the whole line | attribute | | ||
| 94 | +| `name~` in a labelled argument, tilde included | attribute | | ||
| 95 | +| `@json`, `@moonbitlang/core/builtin`, `@my-pkg` — the `@` included, as one span | type | | ||
| 96 | +| `.0` in a tuple accessor | the dot as punctuation, the digits as number | | ||
| 97 | +| `..`, `..=`, `..<`, `...` | operator | | ||
| 98 | +| runs of `+-*/%=<>!&\|^~?:` | operator | | ||
| 99 | +| `()[]{},;.` | punctuation | | ||
| 100 | + | ||
| 101 | +**Nothing here is a table of built-in types, and nothing needs to be.** MoonBit's identifier case is a *lexical* rule rather than a convention: the grammar says a `uident` "begins with an ASCII uppercase letter", and only a type, a trait or an enum constructor may be spelt that way. `Int`, `StringBuilder` and a type somebody wrote this morning are all coloured by the same line. Every other scanner in this family needs a table here; this one does not. | ||
| 102 | + | ||
| 103 | +**An integer ends before `..`.** The grammar is explicit — "before `..`, an integer ends first, so `1..=2` begins with `1` and `..=`" — so a dot is only part of a number when a second one does not follow it. Without that rule `1..=2` reads as the double `1.` and then `.=2`, and every range in the file is miscoloured. | ||
| 104 | + | ||
| 105 | +**A number's suffix is upper case or it is not a suffix.** `42UL` is one number; `42u` is the number `42` followed by the name `u`, which is what the compiler sees too. | ||
| 106 | + | ||
| 107 | +**An attribute takes the whole line.** The grammar hands it everything after the dotted name: "everything through the next newline is the raw payload". Colouring less than the line would be inventing a structure the lexer does not have. | ||
| 108 | + | ||
| 109 | +**`#|` and `#deprecated` are told apart by the rune after the `#`.** An attribute's name must start with a letter or an underscore; a multi-line string line has a bar there. | ||
| 110 | + | ||
| 111 | +**A doc comment is coloured like any other comment.** `///`, `///|` and `//` all reach `syntax.comment`, because turbo-core's set of classes is closed on purpose — that is what lets one theme colour every language an editor will ever learn. | ||
| 112 | + | ||
| 113 | +**A name after a dot is never a keyword.** MoonBit's dot-identifiers "use the identifier case rules without consulting the keyword table, so `.if` is valid" — a record with a field called `type` is ordinary MoonBit. | ||
| 114 | + | ||
| 115 | +**`package` is coloured as a keyword in a `.mbt` file too**, although it is only a *reserved* word there. It is a real keyword in the `.mbti` interface files this editor also colours, and in a `.mbt` file the colour says exactly what the compiler is about to: this word is not yours to use. The rest of the reserved list — `move`, `ref`, `static`, `unsafe`, `await` and the forty others — is deliberately left alone, because those really are names you may use. | ||
| 116 | + | ||
| 117 | +**A tilde against the end of a lower-case name is a label**, and against anything else it is not: the grammar says "ASCII-uppercase identifiers and keywords cannot form labels", so `Foo~` is a type and a tilde. | ||
| 118 | + | ||
| 119 | +**Not recognised**, each for a stated reason: | ||
| 120 | + | ||
| 121 | +| Not recognised | Because | | ||
| 122 | +| --- | --- | | ||
| 123 | +| The expression inside `\{…}` | The grammar matches it to "the matching `}`", with braces inside nested literals not counting — finding the end needs the parser. `"a \{b} c"` is therefore one string span, brace to brace. **A string nested inside an interpolation is where that stops**: the scanner takes the first unescaped quote as the closer, so `"a \{f("x")} c"` scans as string, then `x` as an identifier, then string. The spans stay in order and never overlap; the cost is a wrong colour inside a nested literal, which is rarer than the brace-counting bugs the alternative would cause | | ||
| 124 | +| An enum constructor of your own, as anything but a type | Nothing in the syntax separates `Circle(1.0)` from a type applied to arguments; inventing a separation means being wrong in both directions instead of one | | ||
| 125 | +| `.5` as a number | MoonBit requires a digit before the point, so a leading dot is a tuple accessor or a dot-identifier and never a literal | | ||
| 126 | +| A reserved word as a keyword | `move`, `ref` and the rest are identifiers the compiler merely warns about, and colouring them would tell a reader they cannot write `let ref = 1` when they can | | ||
| 127 | +| An identifier holding non-ASCII letters | MoonBit allows CJK and several other ranges in a name; the rune predicates this scanner is built on are ASCII, so such a name is stepped over uncoloured rather than guessed at | | ||
| 128 | +| `.mbt.md` as MoonBit | It is a Markdown document with MoonBit in its fences. Its extension is `.md`, and Markdown is what colours it | | ||
| 129 | +| 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) | | ||
| 130 | + | ||
| 131 | +## TOML | ||
| 132 | + | ||
| 133 | +| Recognised | As | | ||
| 134 | +| --- | --- | | ||
| 135 | +| `# comment` | comment | | ||
| 136 | +| `[table]`, `[[array]]` | the name as a type, the brackets as punctuation | | ||
| 137 | +| `key =` | identifier, then operator | | ||
| 138 | +| `"basic"`, `'literal'`, `"""multi-line"""`, `'''multi-line'''` | string | | ||
| 139 | +| `true`, `false` | constant | | ||
| 140 | +| numbers, dates, times, `inf`, `nan` | number | | ||
| 141 | + | ||
| 142 | +## YAML | ||
| 143 | + | ||
| 144 | +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. | ||
| 145 | + | ||
| 146 | +| Recognised | As | | ||
| 147 | +| --- | --- | | ||
| 148 | +| `# comment` | comment | | ||
| 149 | +| `key:` before a space or the end of the line | the key as an identifier, the colon as punctuation | | ||
| 150 | +| `"quoted": 1`, `'quoted': 1` | the quoted key as an identifier | | ||
| 151 | +| `- ` opening a sequence entry | punctuation | | ||
| 152 | +| `"…"`, `'…'` | string | | ||
| 153 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constant, whatever their case | | ||
| 154 | +| numbers, dates and times written without quotes | number | | ||
| 155 | +| `&anchor`, `*alias` | builtin | | ||
| 156 | +| `!!str`, `!Custom` | type | | ||
| 157 | +| `---`, `...` | the whole line as punctuation | | ||
| 158 | +| `{`, `}`, `[`, `]`, `,` | punctuation | | ||
| 159 | +| `\|`, `>`, with their chomping and indentation indicators | the header as an operator, the body as a string | | ||
| 160 | + | ||
| 161 | +**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. | ||
| 162 | + | ||
| 163 | +**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. | ||
| 164 | + | ||
| 165 | +**A `#` needs a space before it to start a comment**, so `colour: ff#00aa` is one scalar. | ||
| 166 | + | ||
| 167 | +| Not recognised | Because | | ||
| 168 | +| --- | --- | | ||
| 169 | +| 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 | | ||
| 170 | +| Multi-document streams as separate documents | `---` is coloured, but nothing is reset at it; nothing in the colouring depends on document boundaries | | ||
| 171 | +| 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 | | ||
| 172 | + | ||
| 173 | +## Markdown | ||
| 174 | + | ||
| 175 | +| Recognised | As | | ||
| 176 | +| --- | --- | | ||
| 177 | +| `# Heading` … `###### Heading` | the whole line as a heading | | ||
| 178 | +| `**bold**`, `__bold__`, `*italic*`, `_italic_` | emphasis | | ||
| 179 | +| `` `code` `` | string | | ||
| 180 | +| `[text](target)`, `` | the whole thing as a link | | ||
| 181 | +| `- `, `* `, `+ `, `1. `, `1) ` | the marker as punctuation | | ||
| 182 | +| `>` | punctuation | | ||
| 183 | +| `---`, `***`, `___` | punctuation | | ||
| 184 | +| ` ``` ` and `~~~` fences | the whole block, opening and closing lines included, as a string | | ||
| 185 | + | ||
| 186 | +A fenced block is **one colour whatever language it announces**: ```` ```moonbit ```` does not colour its contents as MoonBit. 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. | ||
| 187 | + | ||
| 188 | +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. | ||
| 189 | + | ||
| 190 | +## JavaScript | ||
| 191 | + | ||
| 192 | +| Recognised | As | | ||
| 193 | +| --- | --- | | ||
| 194 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | ||
| 195 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | ||
| 196 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | ||
| 197 | +| a name immediately before `(` | function | | ||
| 198 | +| `"…"`, `'…'` | string | | ||
| 199 | +| `` `…` ``, interpolations included, across lines | string | | ||
| 200 | +| `//` to end of line, `/* … */` across lines | comment | | ||
| 201 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | ||
| 202 | +| runs of `+-*/%=<>!&|^~?:` | operator | | ||
| 203 | +| `()[]{},;.` | punctuation | | ||
| 204 | + | ||
| 205 | +**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. | ||
| 206 | + | ||
| 207 | +Globals are recognised by name, so a file that shadows `Math` still has it coloured as a builtin — the same rule MoonBit's builtins follow here. | ||
| 208 | + | ||
| 209 | +## HTML | ||
| 210 | + | ||
| 211 | +| Recognised | As | | ||
| 212 | +| --- | --- | | ||
| 213 | +| `<tag`, `</tag`, `>`, `/>` | tag | | ||
| 214 | +| attribute names, including `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | ||
| 215 | +| `=` | operator | | ||
| 216 | +| `"…"`, `'…'` | string | | ||
| 217 | +| `<!-- … -->`, across lines | comment | | ||
| 218 | +| `&`, `©` | constant | | ||
| 219 | +| `<!DOCTYPE …>` and other declarations | keyword | | ||
| 220 | + | ||
| 221 | +Text between tags is not coloured. A bare `&` with no `;` within 32 characters is left alone, because it is legal text. | ||
| 222 | + | ||
| 223 | +**The contents of `<script>` and `<style>` are not coloured** as JavaScript and CSS. | ||
| 224 | + | ||
| 225 | +## XML | ||
| 226 | + | ||
| 227 | +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. | ||
| 228 | + | ||
| 229 | +| Recognised | As | | ||
| 230 | +| --- | --- | | ||
| 231 | +| `<?xml version="1.0"?>` and other processing instructions | the target and `?>` as keyword, the pairs between as attributes and strings | | ||
| 232 | +| `<!DOCTYPE …>` and the other `<!` forms | keyword | | ||
| 233 | +| `<!-- … -->`, across lines | comment | | ||
| 234 | +| `<![CDATA[ … ]]>`, across lines | string | | ||
| 235 | +| `<tag`, `</tag`, `>`, `/>` | tag | | ||
| 236 | +| `<ns:tag>`, `xsi:type` | the prefix and the local name as **one** span | | ||
| 237 | +| attribute names | attribute | | ||
| 238 | +| `=` | operator | | ||
| 239 | +| `"…"`, `'…'` | string | | ||
| 240 | +| `&`, `©` | constant | | ||
| 241 | + | ||
| 242 | +**A comment and a CDATA section close on different delimiters**, and are carried separately: a `-->` inside a CDATA section does not end it. | ||
| 243 | + | ||
| 244 | +**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. | ||
| 245 | + | ||
| 246 | +Text between tags is not coloured. | ||
| 247 | + | ||
| 248 | +## Shell | ||
| 249 | + | ||
| 250 | +Applies to `sh`, `bash` and `zsh` alike: the keywords recognised are the ones they share. | ||
| 251 | + | ||
| 252 | +| Recognised | As | | ||
| 253 | +| --- | --- | | ||
| 254 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | ||
| 255 | +| `true`, `false` | constant | | ||
| 256 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | ||
| 257 | +| `$NAME`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | ||
| 258 | +| the **first bare word on a line** | function | | ||
| 259 | +| every later bare word, and `NAME` in `NAME=value` | identifier | | ||
| 260 | +| `'…'`, with nothing escaped or expanded inside | string | | ||
| 261 | +| `"…"`, with the expansions inside it coloured as expansions | string | | ||
| 262 | +| `#` to end of line | comment | | ||
| 263 | + | ||
| 264 | +`$(a $(b) c)` is one span: nesting is counted. An option such as `-euo` is one word, not a minus and a word. | ||
| 265 | + | ||
| 266 | +**Heredocs are not recognised.** `<<EOF` and the text after it are coloured as ordinary shell. | ||
| 267 | + | ||
| 268 | +## Dockerfile | ||
| 269 | + | ||
| 270 | +| Recognised | As | | ||
| 271 | +| --- | --- | | ||
| 272 | +| `FROM`, `RUN`, `COPY`, `ADD`, `ARG`, `ENV`, `CMD`, `ENTRYPOINT`, `EXPOSE`, `LABEL`, `USER`, `VOLUME`, `WORKDIR`, `HEALTHCHECK`, `ONBUILD`, `SHELL`, `STOPSIGNAL`, `MAINTAINER` | keyword, in any case | | ||
| 273 | +| `AS`, `NONE` | keyword | | ||
| 274 | +| `# comment`, including the `# syntax=` and `# escape=` directives | comment | | ||
| 275 | +| `--from=builder`, `--chown=me:me` | the flag name as an attribute | | ||
| 276 | +| `$NAME`, `${NAME}`, `${NAME:-default}` | builtin, as one span to the closing brace | | ||
| 277 | +| `"…"`, `'…'` | string | | ||
| 278 | +| a trailing `\` | operator | | ||
| 279 | +| numbers | number | | ||
| 280 | +| paths and image references — `/usr/local/bin`, `golang:1.26-alpine` | identifier, as **one** span | | ||
| 281 | + | ||
| 282 | +**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. | ||
| 283 | + | ||
| 284 | +**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. | ||
| 285 | + | ||
| 286 | +| Not recognised | Because | | ||
| 287 | +| --- | --- | | ||
| 288 | +| 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 | | ||
| 289 | +| Heredocs in a `RUN` | The same reason the shell scanner does not recognise them | | ||
| 290 | +| Which stage a `--from` names | Nothing here reads the rest of the file | | ||
| 291 | + | ||
| 292 | +## See also | ||
| 293 | + | ||
| 294 | +- [Theme file format](themes.md) — every key these classes resolve to | ||
| 295 | +- [Colouring and completion](../explanation/colouring-and-completion.md) — why the scanners are written this way | ||
| 296 | +- [How to write your own theme](../how-to/write-a-theme.md) | ||
added
docs/en/reference/moonbit-tools.md +242 -0 | new file mode 100644 | ||
| @@ -0,0 +1,242 @@ | ||
| 1 | +# Reference: MoonBit tools | |
| 2 | + | |
| 3 | +> Neutral description of `.turbo-moonbit/tools.toml`, the MoonBit menu, and what running a command does. | |
| 4 | + | |
| 5 | +## File | |
| 6 | + | |
| 7 | +| Property | Value | | |
| 8 | +| --- | --- | | |
| 9 | +| Path | `./.turbo-moonbit/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-moonbit/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 `MoonBit`. 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 = "moon test" | |
| 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 | +**MoonBit ▸ Create tools file** writes these nine, in this order: | |
| 48 | + | |
| 49 | +| Name | Command | Output | Menu | | |
| 50 | +| --- | --- | --- | --- | | |
| 51 | +| `~C~heck` | `moon check` | `popup` | MoonBit | | |
| 52 | +| `~F~ormat` | `moon fmt` | `popup` | MoonBit | | |
| 53 | +| `~B~uild` | `moon build --target {{backend: wasm-gc, js, native, llvm or all...}}` | `popup` | MoonBit | | |
| 54 | +| `~T~est` | `moon test` | `popup` | MoonBit | | |
| 55 | +| `~R~un` | `moon run {{package, e.g. cmd/main}}` | `terminal` | MoonBit | | |
| 56 | +| `~A~dd a dependency` | `moon add {{module, e.g. moonbitlang/x}}` | `popup` | MoonBit | | |
| 57 | +| `~I~nterfaces` | `moon info` | `popup` | MoonBit | | |
| 58 | +| `C~l~ean` | `moon clean` | `popup` | MoonBit | | |
| 59 | +| `~E~cho` | `echo 🎉 tada!` | `terminal` | Tools | | |
| 60 | + | |
| 61 | +`Check` comes before `Build` because it is the command that answers "is this sound?" without producing anything. Three of them ask for a value before they run, and one names a `menu` of its own — those two features are invisible unless the starter file shows them. | |
| 62 | + | |
| 63 | +Every tool names its `output`, including the ones 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. | |
| 64 | + | |
| 65 | +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. | |
| 66 | + | |
| 67 | +## The MoonBit menu | |
| 68 | + | |
| 69 | +Always on the bar, whether or not a tools file exists. Its hot key is `Alt-M`. | |
| 70 | + | |
| 71 | +| Item | Condition | | |
| 72 | +| --- | --- | | |
| 73 | +| One line per tool with no `menu`, in file order | The file holds at least one | | |
| 74 | +| `Cannot read tools`, greyed out | The file is present but unreadable | | |
| 75 | +| `Create tools file` | The project has no tools file | | |
| 76 | +| `Open tools file` | The project has one | | |
| 77 | + | |
| 78 | +## Menus a tool asks for | |
| 79 | + | |
| 80 | +A `menu` naming anything other than `MoonBit` puts a menu of that name on the bar. | |
| 81 | + | |
| 82 | +| Property | Value | | |
| 83 | +| --- | --- | | |
| 84 | +| Position | Between MoonBit and Help | | |
| 85 | +| Order | The order each name first appears in the file | | |
| 86 | +| Items | One line per tool naming that menu, in file order. Nothing else — `Create tools file` and `Open tools file` stay in MoonBit. | | |
| 87 | +| Unreadable file | No menus at all; the MoonBit menu carries the error | | |
| 88 | +| While the editor runs | Added, removed and renamed as the file changes, without restarting | | |
| 89 | + | |
| 90 | +### Hot keys | |
| 91 | + | |
| 92 | +Assigned automatically, because a name from a file cannot be checked against the fixed menus in advance. | |
| 93 | + | |
| 94 | +| Case | Result | | |
| 95 | +| --- | --- | | |
| 96 | +| 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. | | |
| 97 | +| Tildes naming a free letter | Kept as written. `Doc~k~er` answers to `Alt-K`. | | |
| 98 | +| Tildes naming a taken letter | Dropped, and a free letter chosen instead. `~F~oo` becomes `F~o~o`. | | |
| 99 | +| Every letter taken | No hot key. `F10` and the mouse still open it. | | |
| 100 | + | |
| 101 | +The letters the editor's own menus hold are `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` and `H`. | |
| 102 | + | |
| 103 | +## Running a command | |
| 104 | + | |
| 105 | +Common to every output: | |
| 106 | + | |
| 107 | +| Property | Value | | |
| 108 | +| --- | --- | | |
| 109 | +| Shell | `/bin/sh -c "<command>"` on Linux and macOS; `cmd.exe /S /C "<command>"` — the shell `%COMSPEC%` names — on Windows | | |
| 110 | +| Directory | The directory the editor was started in | | |
| 111 | +| Standard error | Merged into standard output, in the order the command wrote them | | |
| 112 | + | |
| 113 | +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. | |
| 114 | + | |
| 115 | +### `output = "popup"` | |
| 116 | + | |
| 117 | +| Property | Value | | |
| 118 | +| --- | --- | | |
| 119 | +| Opens | Immediately, before the command has finished | | |
| 120 | +| Modal | Yes: nothing else in the editor can be used while it is up | | |
| 121 | +| Fills in | As output arrives, following it until you scroll back | | |
| 122 | +| Title while running | `<command> — running` | | |
| 123 | +| Title when finished | `<command> — ok`, or `<command> — exit <n>` | | |
| 124 | +| Empty output, finished | Shows `(no output)` | | |
| 125 | +| Empty output, running | Shows nothing | | |
| 126 | +| Output cap | 10000 lines; past it the oldest go and a `… n earlier lines dropped …` line says so | | |
| 127 | + | |
| 128 | +| Key | Effect | | |
| 129 | +| --- | --- | | |
| 130 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Read through the output | | |
| 131 | +| Wheel | The same | | |
| 132 | +| `Escape`, `Enter`, **Close** | Close it, **stopping the command** if it is still running | | |
| 133 | + | |
| 134 | +Closing stops the command because there is no other way to interrupt one whose output is not in a terminal. | |
| 135 | + | |
| 136 | +### `output = "terminal"` | |
| 137 | + | |
| 138 | +| Property | Value | | |
| 139 | +| --- | --- | | |
| 140 | +| Window | A terminal window of its own, titled with the command | | |
| 141 | +| Environment | The editor's own, with `TERM` set to `xterm-256color` | | |
| 142 | +| After it exits | The window stays, showing its output | | |
| 143 | +| Modal | No: the editor carries on beside it | | |
| 144 | + | |
| 145 | +Because it is a real terminal, colours, paging, `Ctrl-C` and reading from the keyboard all work. See [Terminal windows](terminal.md). | |
| 146 | + | |
| 147 | +Keys in a **finished** terminal window: | |
| 148 | + | |
| 149 | +| Key | Effect | | |
| 150 | +| --- | --- | | |
| 151 | +| `Shift-PgUp`, `Shift-PgDn` | Read back through the output | | |
| 152 | +| `Ctrl-W` | Close the window | | |
| 153 | +| Anything else | Reaches the editor, not the dead shell | | |
| 154 | + | |
| 155 | +### `output = "editor"` | |
| 156 | + | |
| 157 | +| Property | Value | | |
| 158 | +| --- | --- | | |
| 159 | +| Shows | A popup while it runs, as above | | |
| 160 | +| On closing the popup | An editing window holding the output, titled with the command | | |
| 161 | +| Filled | Once, when the command has finished — not as it goes | | |
| 162 | +| The window | An ordinary editing window with no file name: searchable with `Ctrl-F`, and `Save as` keeps it | | |
| 163 | + | |
| 164 | +## Reloading after a command | |
| 165 | + | |
| 166 | +When a command finishes, every open file is considered. | |
| 167 | + | |
| 168 | +| The file | What happens | | |
| 169 | +| --- | --- | | |
| 170 | +| Unmodified, and changed on disk | Re-read; its syntax is re-decided and its title refreshed | | |
| 171 | +| Unmodified, and unchanged on disk | Left alone, not counted | | |
| 172 | +| Has unsaved changes | Left alone and counted as skipped | | |
| 173 | +| Has never been named | Left alone | | |
| 174 | +| Has gone from disk | Left alone | | |
| 175 | + | |
| 176 | +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. | |
| 177 | + | |
| 178 | +The project tree is refreshed at the same moment. | |
| 179 | + | |
| 180 | +| Status bar | When | | |
| 181 | +| --- | --- | | |
| 182 | +| `Running <command>` | The window opens | | |
| 183 | +| `Reloaded 2 files` | Two files were re-read, none skipped | | |
| 184 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Some were skipped | | |
| 185 | +| `Command finished; 1 file with unsaved changes left alone` | Nothing was re-read, something was skipped | | |
| 186 | + | |
| 187 | +## Errors | |
| 188 | + | |
| 189 | +| Message | Cause | | |
| 190 | +| --- | --- | | |
| 191 | +| `Cannot read tools` in the menu | The file is present but not valid TOML, or holds a tool with no name or no command | | |
| 192 | +| `Already there: .turbo-moonbit/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. | | |
| 193 | +| `This project has no .turbo-moonbit/tools.toml yet.` | Opening in a project that has none, likewise | | |
| 194 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | |
| 195 | +| `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) | | |
| 196 | + | |
| 197 | +## Asking for a value | |
| 198 | + | |
| 199 | +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. | |
| 200 | + | |
| 201 | +| Written | Asked for | Substituted | | |
| 202 | +| --- | --- | --- | | |
| 203 | +| `{{module path}}` | `module path` | shell-quoted | | |
| 204 | +| `{{extra flags...}}` | `extra flags` | verbatim | | |
| 205 | + | |
| 206 | +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. | |
| 207 | + | |
| 208 | +```toml | |
| 209 | +[[tool]] | |
| 210 | +name = "~I~nit module" | |
| 211 | +command = "go mod init {{module path}}" | |
| 212 | +output = "popup" | |
| 213 | +``` | |
| 214 | + | |
| 215 | +| Rule | Behaviour | | |
| 216 | +| --- | --- | | |
| 217 | +| Several placeholders | One box, one field each, in the order they appear in the command | | |
| 218 | +| The same label twice | One field; every occurrence gets what is typed into it | | |
| 219 | +| A label written both ways | Asked for once; each occurrence honours its own braces | | |
| 220 | +| Escape, or Cancel | The command does not run | | |
| 221 | +| A field left empty | Substituted as empty — the command reports its own complaint | | |
| 222 | +| Running the tool again | The box starts from what was typed last time, for this session only | | |
| 223 | +| More fields than fit on screen | Refused, with a message saying how many fit | | |
| 224 | + | |
| 225 | +**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`. | |
| 226 | + | |
| 227 | +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. | |
| 228 | + | |
| 229 | +### Errors | |
| 230 | + | |
| 231 | +| Error | Cause | | |
| 232 | +| --- | --- | | |
| 233 | +| `tool "X": "{{module" is never closed` | An opening `{{` with no `}}` after it | | |
| 234 | +| `tool "X": {{}} asks for a value but does not say what it is` | A placeholder with no label, or one that is only `...` | | |
| 235 | + | |
| 236 | +Both are refused when the file is read, so a half-typed placeholder never reaches the shell with its braces still in it. | |
| 237 | + | |
| 238 | +## See also | |
| 239 | + | |
| 240 | +- [How to run moon commands from the editor](../how-to/run-moon-commands.md) | |
| 241 | +- [MoonBit tools](../explanation/moonbit-tools.md) | |
| 242 | +- [Terminal windows](terminal.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,242 @@ | |||
| 1 | +# Reference: MoonBit tools | ||
| 2 | + | ||
| 3 | +> Neutral description of `.turbo-moonbit/tools.toml`, the MoonBit menu, and what running a command does. | ||
| 4 | + | ||
| 5 | +## File | ||
| 6 | + | ||
| 7 | +| Property | Value | | ||
| 8 | +| --- | --- | | ||
| 9 | +| Path | `./.turbo-moonbit/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-moonbit/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 `MoonBit`. 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 = "moon test" | ||
| 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 | +**MoonBit ▸ Create tools file** writes these nine, in this order: | ||
| 48 | + | ||
| 49 | +| Name | Command | Output | Menu | | ||
| 50 | +| --- | --- | --- | --- | | ||
| 51 | +| `~C~heck` | `moon check` | `popup` | MoonBit | | ||
| 52 | +| `~F~ormat` | `moon fmt` | `popup` | MoonBit | | ||
| 53 | +| `~B~uild` | `moon build --target {{backend: wasm-gc, js, native, llvm or all...}}` | `popup` | MoonBit | | ||
| 54 | +| `~T~est` | `moon test` | `popup` | MoonBit | | ||
| 55 | +| `~R~un` | `moon run {{package, e.g. cmd/main}}` | `terminal` | MoonBit | | ||
| 56 | +| `~A~dd a dependency` | `moon add {{module, e.g. moonbitlang/x}}` | `popup` | MoonBit | | ||
| 57 | +| `~I~nterfaces` | `moon info` | `popup` | MoonBit | | ||
| 58 | +| `C~l~ean` | `moon clean` | `popup` | MoonBit | | ||
| 59 | +| `~E~cho` | `echo 🎉 tada!` | `terminal` | Tools | | ||
| 60 | + | ||
| 61 | +`Check` comes before `Build` because it is the command that answers "is this sound?" without producing anything. Three of them ask for a value before they run, and one names a `menu` of its own — those two features are invisible unless the starter file shows them. | ||
| 62 | + | ||
| 63 | +Every tool names its `output`, including the ones 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. | ||
| 64 | + | ||
| 65 | +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. | ||
| 66 | + | ||
| 67 | +## The MoonBit menu | ||
| 68 | + | ||
| 69 | +Always on the bar, whether or not a tools file exists. Its hot key is `Alt-M`. | ||
| 70 | + | ||
| 71 | +| Item | Condition | | ||
| 72 | +| --- | --- | | ||
| 73 | +| One line per tool with no `menu`, in file order | The file holds at least one | | ||
| 74 | +| `Cannot read tools`, greyed out | The file is present but unreadable | | ||
| 75 | +| `Create tools file` | The project has no tools file | | ||
| 76 | +| `Open tools file` | The project has one | | ||
| 77 | + | ||
| 78 | +## Menus a tool asks for | ||
| 79 | + | ||
| 80 | +A `menu` naming anything other than `MoonBit` puts a menu of that name on the bar. | ||
| 81 | + | ||
| 82 | +| Property | Value | | ||
| 83 | +| --- | --- | | ||
| 84 | +| Position | Between MoonBit and Help | | ||
| 85 | +| Order | The order each name first appears in the file | | ||
| 86 | +| Items | One line per tool naming that menu, in file order. Nothing else — `Create tools file` and `Open tools file` stay in MoonBit. | | ||
| 87 | +| Unreadable file | No menus at all; the MoonBit menu carries the error | | ||
| 88 | +| While the editor runs | Added, removed and renamed as the file changes, without restarting | | ||
| 89 | + | ||
| 90 | +### Hot keys | ||
| 91 | + | ||
| 92 | +Assigned automatically, because a name from a file cannot be checked against the fixed menus in advance. | ||
| 93 | + | ||
| 94 | +| Case | Result | | ||
| 95 | +| --- | --- | | ||
| 96 | +| 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. | | ||
| 97 | +| Tildes naming a free letter | Kept as written. `Doc~k~er` answers to `Alt-K`. | | ||
| 98 | +| Tildes naming a taken letter | Dropped, and a free letter chosen instead. `~F~oo` becomes `F~o~o`. | | ||
| 99 | +| Every letter taken | No hot key. `F10` and the mouse still open it. | | ||
| 100 | + | ||
| 101 | +The letters the editor's own menus hold are `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` and `H`. | ||
| 102 | + | ||
| 103 | +## Running a command | ||
| 104 | + | ||
| 105 | +Common to every output: | ||
| 106 | + | ||
| 107 | +| Property | Value | | ||
| 108 | +| --- | --- | | ||
| 109 | +| Shell | `/bin/sh -c "<command>"` on Linux and macOS; `cmd.exe /S /C "<command>"` — the shell `%COMSPEC%` names — on Windows | | ||
| 110 | +| Directory | The directory the editor was started in | | ||
| 111 | +| Standard error | Merged into standard output, in the order the command wrote them | | ||
| 112 | + | ||
| 113 | +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. | ||
| 114 | + | ||
| 115 | +### `output = "popup"` | ||
| 116 | + | ||
| 117 | +| Property | Value | | ||
| 118 | +| --- | --- | | ||
| 119 | +| Opens | Immediately, before the command has finished | | ||
| 120 | +| Modal | Yes: nothing else in the editor can be used while it is up | | ||
| 121 | +| Fills in | As output arrives, following it until you scroll back | | ||
| 122 | +| Title while running | `<command> — running` | | ||
| 123 | +| Title when finished | `<command> — ok`, or `<command> — exit <n>` | | ||
| 124 | +| Empty output, finished | Shows `(no output)` | | ||
| 125 | +| Empty output, running | Shows nothing | | ||
| 126 | +| Output cap | 10000 lines; past it the oldest go and a `… n earlier lines dropped …` line says so | | ||
| 127 | + | ||
| 128 | +| Key | Effect | | ||
| 129 | +| --- | --- | | ||
| 130 | +| `↑` `↓` `PgUp` `PgDn` `Home` `End` | Read through the output | | ||
| 131 | +| Wheel | The same | | ||
| 132 | +| `Escape`, `Enter`, **Close** | Close it, **stopping the command** if it is still running | | ||
| 133 | + | ||
| 134 | +Closing stops the command because there is no other way to interrupt one whose output is not in a terminal. | ||
| 135 | + | ||
| 136 | +### `output = "terminal"` | ||
| 137 | + | ||
| 138 | +| Property | Value | | ||
| 139 | +| --- | --- | | ||
| 140 | +| Window | A terminal window of its own, titled with the command | | ||
| 141 | +| Environment | The editor's own, with `TERM` set to `xterm-256color` | | ||
| 142 | +| After it exits | The window stays, showing its output | | ||
| 143 | +| Modal | No: the editor carries on beside it | | ||
| 144 | + | ||
| 145 | +Because it is a real terminal, colours, paging, `Ctrl-C` and reading from the keyboard all work. See [Terminal windows](terminal.md). | ||
| 146 | + | ||
| 147 | +Keys in a **finished** terminal window: | ||
| 148 | + | ||
| 149 | +| Key | Effect | | ||
| 150 | +| --- | --- | | ||
| 151 | +| `Shift-PgUp`, `Shift-PgDn` | Read back through the output | | ||
| 152 | +| `Ctrl-W` | Close the window | | ||
| 153 | +| Anything else | Reaches the editor, not the dead shell | | ||
| 154 | + | ||
| 155 | +### `output = "editor"` | ||
| 156 | + | ||
| 157 | +| Property | Value | | ||
| 158 | +| --- | --- | | ||
| 159 | +| Shows | A popup while it runs, as above | | ||
| 160 | +| On closing the popup | An editing window holding the output, titled with the command | | ||
| 161 | +| Filled | Once, when the command has finished — not as it goes | | ||
| 162 | +| The window | An ordinary editing window with no file name: searchable with `Ctrl-F`, and `Save as` keeps it | | ||
| 163 | + | ||
| 164 | +## Reloading after a command | ||
| 165 | + | ||
| 166 | +When a command finishes, every open file is considered. | ||
| 167 | + | ||
| 168 | +| The file | What happens | | ||
| 169 | +| --- | --- | | ||
| 170 | +| Unmodified, and changed on disk | Re-read; its syntax is re-decided and its title refreshed | | ||
| 171 | +| Unmodified, and unchanged on disk | Left alone, not counted | | ||
| 172 | +| Has unsaved changes | Left alone and counted as skipped | | ||
| 173 | +| Has never been named | Left alone | | ||
| 174 | +| Has gone from disk | Left alone | | ||
| 175 | + | ||
| 176 | +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. | ||
| 177 | + | ||
| 178 | +The project tree is refreshed at the same moment. | ||
| 179 | + | ||
| 180 | +| Status bar | When | | ||
| 181 | +| --- | --- | | ||
| 182 | +| `Running <command>` | The window opens | | ||
| 183 | +| `Reloaded 2 files` | Two files were re-read, none skipped | | ||
| 184 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Some were skipped | | ||
| 185 | +| `Command finished; 1 file with unsaved changes left alone` | Nothing was re-read, something was skipped | | ||
| 186 | + | ||
| 187 | +## Errors | ||
| 188 | + | ||
| 189 | +| Message | Cause | | ||
| 190 | +| --- | --- | | ||
| 191 | +| `Cannot read tools` in the menu | The file is present but not valid TOML, or holds a tool with no name or no command | | ||
| 192 | +| `Already there: .turbo-moonbit/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. | | ||
| 193 | +| `This project has no .turbo-moonbit/tools.toml yet.` | Opening in a project that has none, likewise | | ||
| 194 | +| `Cannot tell which directory this is: …` | The working directory could not be read | | ||
| 195 | +| `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) | | ||
| 196 | + | ||
| 197 | +## Asking for a value | ||
| 198 | + | ||
| 199 | +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. | ||
| 200 | + | ||
| 201 | +| Written | Asked for | Substituted | | ||
| 202 | +| --- | --- | --- | | ||
| 203 | +| `{{module path}}` | `module path` | shell-quoted | | ||
| 204 | +| `{{extra flags...}}` | `extra flags` | verbatim | | ||
| 205 | + | ||
| 206 | +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. | ||
| 207 | + | ||
| 208 | +```toml | ||
| 209 | +[[tool]] | ||
| 210 | +name = "~I~nit module" | ||
| 211 | +command = "go mod init {{module path}}" | ||
| 212 | +output = "popup" | ||
| 213 | +``` | ||
| 214 | + | ||
| 215 | +| Rule | Behaviour | | ||
| 216 | +| --- | --- | | ||
| 217 | +| Several placeholders | One box, one field each, in the order they appear in the command | | ||
| 218 | +| The same label twice | One field; every occurrence gets what is typed into it | | ||
| 219 | +| A label written both ways | Asked for once; each occurrence honours its own braces | | ||
| 220 | +| Escape, or Cancel | The command does not run | | ||
| 221 | +| A field left empty | Substituted as empty — the command reports its own complaint | | ||
| 222 | +| Running the tool again | The box starts from what was typed last time, for this session only | | ||
| 223 | +| More fields than fit on screen | Refused, with a message saying how many fit | | ||
| 224 | + | ||
| 225 | +**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`. | ||
| 226 | + | ||
| 227 | +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. | ||
| 228 | + | ||
| 229 | +### Errors | ||
| 230 | + | ||
| 231 | +| Error | Cause | | ||
| 232 | +| --- | --- | | ||
| 233 | +| `tool "X": "{{module" is never closed` | An opening `{{` with no `}}` after it | | ||
| 234 | +| `tool "X": {{}} asks for a value but does not say what it is` | A placeholder with no label, or one that is only `...` | | ||
| 235 | + | ||
| 236 | +Both are refused when the file is read, so a half-typed placeholder never reaches the shell with its braces still in it. | ||
| 237 | + | ||
| 238 | +## See also | ||
| 239 | + | ||
| 240 | +- [How to run moon commands from the editor](../how-to/run-moon-commands.md) | ||
| 241 | +- [MoonBit tools](../explanation/moonbit-tools.md) | ||
| 242 | +- [Terminal windows](terminal.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-moonbit/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-moonbit` in the editor's working directory | | |
| 10 | +| File | `.turbo-moonbit/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-moonbit -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-moonbit/settings.toml — autosave on (2s)` | | |
| 59 | +| Read and applied, autosave off | `Applied .turbo-moonbit/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-moonbit/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-moonbit/settings.toml`. Greyed out until the project has one. | | |
| 94 | + | |
| 95 | +## Errors | |
| 96 | + | |
| 97 | +| Message | Cause | | |
| 98 | +| --- | --- | | |
| 99 | +| `turbo-moonbit: 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-moonbit/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-moonbit/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-moonbit/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-moonbit` in the editor's working directory | | ||
| 10 | +| File | `.turbo-moonbit/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-moonbit -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-moonbit/settings.toml — autosave on (2s)` | | ||
| 59 | +| Read and applied, autosave off | `Applied .turbo-moonbit/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-moonbit/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-moonbit/settings.toml`. Greyed out until the project has one. | | ||
| 94 | + | ||
| 95 | +## Errors | ||
| 96 | + | ||
| 97 | +| Message | Cause | | ||
| 98 | +| --- | --- | | ||
| 99 | +| `turbo-moonbit: 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-moonbit/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-moonbit/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-moonbit/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-moonbit`, `.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-moonbit/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-moonbit`, `.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/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-moonbit/snippets.toml` | The project's snippets | | |
| 12 | +| `$TURBO_MOONBIT_SNIPPET_DIR/snippets.toml`, else `<user config>/turbo-moonbit/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: `moonbit`, `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 = "MoonBit" | |
| 46 | +languages = ["moonbit"] | |
| 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-moonbit/snippets.toml` with worked examples, then opens it. Greyed out once the project has one. | | |
| 97 | +| Open snippets file | Snippets | Opens `.turbo-moonbit/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-moonbit/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-moonbit/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-moonbit/snippets.toml` | The project's snippets | | ||
| 12 | +| `$TURBO_MOONBIT_SNIPPET_DIR/snippets.toml`, else `<user config>/turbo-moonbit/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: `moonbit`, `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 = "MoonBit" | ||
| 46 | +languages = ["moonbit"] | ||
| 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-moonbit/snippets.toml` with worked examples, then opens it. Greyed out once the project has one. | | ||
| 97 | +| Open snippets file | Snippets | Opens `.turbo-moonbit/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-moonbit/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-moonbit/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 MoonBit 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 MoonBit 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 MoonBit 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_MOONBIT_THEME_DIR` | Used when the variable is set and non-empty. | | |
| 12 | +| `~/.config/turbo-moonbit/themes` | Linux (`os.UserConfigDir`). | | |
| 13 | +| `~/Library/Application Support/turbo-moonbit/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 MoonBit 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_MOONBIT_THEME_DIR` | Used when the variable is set and non-empty. | | ||
| 12 | +| `~/.config/turbo-moonbit/themes` | Linux (`os.UserConfigDir`). | | ||
| 13 | +| `~/Library/Application Support/turbo-moonbit/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 MoonBit 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-moonbit/internal/version.stamp=v0.2.0' \ | |
| 30 | + -X 'rickub.com/turbo-editors/turbo-moonbit/internal/version.commit=88a4c38' \ | |
| 31 | + -X 'rickub.com/turbo-editors/turbo-moonbit/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-moonbit@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 | +| `moon 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-moonbit`, 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-moonbit v0.2.0 88a4c38 # a stamped build | |
| 79 | +scripts/check-version.sh bin/turbo-moonbit # 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 MoonBit 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | |
| 104 | +Turbo MoonBit 0.2.0 (88a4c38) | |
| 105 | +Turbo MoonBit 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 MoonBit 0.2.0 | |
| 114 | + | |
| 115 | +A Turbo C-style editor for MoonBit, | |
| 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-moonbit/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 MoonBit 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-moonbit/internal/version.stamp=v0.2.0' \ | ||
| 30 | + -X 'rickub.com/turbo-editors/turbo-moonbit/internal/version.commit=88a4c38' \ | ||
| 31 | + -X 'rickub.com/turbo-editors/turbo-moonbit/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-moonbit@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 | +| `moon 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-moonbit`, 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-moonbit v0.2.0 88a4c38 # a stamped build | ||
| 79 | +scripts/check-version.sh bin/turbo-moonbit # 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 MoonBit 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | ||
| 104 | +Turbo MoonBit 0.2.0 (88a4c38) | ||
| 105 | +Turbo MoonBit 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 MoonBit 0.2.0 | ||
| 114 | + | ||
| 115 | +A Turbo C-style editor for MoonBit, | ||
| 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-moonbit/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 +217 -0 | new file mode 100644 | ||
| @@ -0,0 +1,217 @@ | ||
| 1 | +# Tutorial: your first MoonBit program in Turbo MoonBit | |
| 2 | + | |
| 3 | +By the end of this tutorial you will have written, formatted, run and broken a small MoonBit program without leaving the editor — and seen the editor tell you where the mistake was. | |
| 4 | + | |
| 5 | +No prior knowledge of Turbo MoonBit is needed. You need Go 1.26 or later to build the editor, and the MoonBit toolchain to build the program. | |
| 6 | + | |
| 7 | +## Prerequisites | |
| 8 | + | |
| 9 | +Check Go: | |
| 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 | +Check the MoonBit toolchain: | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +moon version --all | |
| 25 | +``` | |
| 26 | + | |
| 27 | +You should see three lines, each ending in a path: | |
| 28 | + | |
| 29 | +``` | |
| 30 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | |
| 31 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | |
| 32 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | |
| 33 | +``` | |
| 34 | + | |
| 35 | +If that command is not found, install the toolchain first — [one command does it](../how-to/install-the-moonbit-toolchain.md). | |
| 36 | + | |
| 37 | +## Step 1 — Install the editor | |
| 38 | + | |
| 39 | +```bash | |
| 40 | +git clone https://rickub.com/turbo-editors/turbo-moonbit.git | |
| 41 | +cd turbo-moonbit | |
| 42 | +make install | |
| 43 | +``` | |
| 44 | + | |
| 45 | +The installer builds, installs, and then checks what it installed. The last lines are: | |
| 46 | + | |
| 47 | +``` | |
| 48 | +==> Checking the language server | |
| 49 | + ✓ moon-lsp at ~/.moon/bin/moon-lsp | |
| 50 | + | |
| 51 | +==> Ready | |
| 52 | +``` | |
| 53 | + | |
| 54 | +We now have a `turbo-moonbit` command. | |
| 55 | + | |
| 56 | +## Step 2 — Make a project | |
| 57 | + | |
| 58 | +```bash | |
| 59 | +cd /tmp | |
| 60 | +moon new hello | |
| 61 | +cd hello | |
| 62 | +``` | |
| 63 | + | |
| 64 | +``` | |
| 65 | +Created username/hello at hello | |
| 66 | +``` | |
| 67 | + | |
| 68 | +`moon new` writes a `moon.mod`, a `moon.pkg`, a library file, some test files, and a `cmd/main/main.mbt` with a hello-world in it. **`moon.mod` is what Turbo MoonBit looks for** to find the root of a project, and it is the directory `moon-lsp` will be started in. | |
| 69 | + | |
| 70 | +## Step 3 — Open the file | |
| 71 | + | |
| 72 | +```bash | |
| 73 | +turbo-moonbit cmd/main/main.mbt | |
| 74 | +``` | |
| 75 | + | |
| 76 | +The screen fills. Along the top: | |
| 77 | + | |
| 78 | +``` | |
| 79 | + File Edit Search Run Code Options Window Snippets MoonBit Help | |
| 80 | +``` | |
| 81 | + | |
| 82 | +Ten menus, and the ninth is named after the language. Along the bottom, at the right-hand end, you should see: | |
| 83 | + | |
| 84 | +``` | |
| 85 | +1:1 LSP: ready | |
| 86 | +``` | |
| 87 | + | |
| 88 | +`LSP: ready` means `moon-lsp` started in this directory. We will use it in Step 8. | |
| 89 | + | |
| 90 | +## Step 4 — Write the program | |
| 91 | + | |
| 92 | +Select everything with `Ctrl-A` and press `Delete`, then type this in. Type it exactly; we will look at the colours next. | |
| 93 | + | |
| 94 | +```moonbit | |
| 95 | +///| | |
| 96 | +struct Greeting { | |
| 97 | + name : String | |
| 98 | + times : Int | |
| 99 | +} | |
| 100 | + | |
| 101 | +///| | |
| 102 | +fn greet(g : Greeting) -> Unit { | |
| 103 | + for i in 0..<g.times { | |
| 104 | + println("Hello, \{g.name}! (\{i + 1})") | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 108 | +///| | |
| 109 | +fn main { | |
| 110 | + greet({ name: "MoonBit", times: 3 }) | |
| 111 | +} | |
| 112 | +``` | |
| 113 | + | |
| 114 | +Press `F2` to save. The star beside `main.mbt` in the window's title goes away. | |
| 115 | + | |
| 116 | +## Step 5 — Read the colours | |
| 117 | + | |
| 118 | +Look at what you have typed. In the default `turbo-classic` theme: | |
| 119 | + | |
| 120 | +| What | Colour | | |
| 121 | +| --- | --- | | |
| 122 | +| `struct`, `fn`, `for`, `in` | bright white, bold — keywords | | |
| 123 | +| `Greeting`, `String`, `Int`, `Unit` | bright cyan — types | | |
| 124 | +| `greet`, where it is declared and where it is called | bright yellow, bold — functions | | |
| 125 | +| `println` | bright cyan, bold — a name the language provides | | |
| 126 | +| `name`, `times`, `g`, `i` | bright yellow — ordinary names | | |
| 127 | +| `"Hello, \{g.name}! (\{i + 1})"` | green, **all of it** — one string | | |
| 128 | +| `0`, `1`, `3` | magenta — numbers | | |
| 129 | +| `///\|` | grey — a comment | | |
| 130 | + | |
| 131 | +Two of those rows are worth a second look. | |
| 132 | + | |
| 133 | +**`Greeting` is cyan and `greet` is yellow**, and nothing in the editor was told which of them is a type. MoonBit's own rule decides it: a name beginning with a capital can only be a type, a trait or a constructor. | |
| 134 | + | |
| 135 | +**The string is green from the first quote to the last**, interpolations included. The `\{g.name}` inside it is not coloured as code — [and that is on purpose](../explanation/colouring-and-completion.md). | |
| 136 | + | |
| 137 | +## Step 6 — Give the project its tools | |
| 138 | + | |
| 139 | +Press `F10` to open the menu bar, then `→` **eight times** to reach **MoonBit** — past Edit, Search, Run, Code, Options, Window and Snippets. Faster: press `Alt-M`. | |
| 140 | + | |
| 141 | +The menu holds two items, and only one of them is available: | |
| 142 | + | |
| 143 | +``` | |
| 144 | +┌───────────────────┐ | |
| 145 | +│ Create tools file │ | |
| 146 | +│ Open tools file │ ← greyed out; there is no file to open yet | |
| 147 | +└───────────────────┘ | |
| 148 | +``` | |
| 149 | + | |
| 150 | +Choose **Create tools file**. | |
| 151 | + | |
| 152 | +A second window opens on the file that was just written, `.turbo-moonbit/tools.toml`. Read it if you like — it explains every key it uses — then press `Ctrl-W` to close it. | |
| 153 | + | |
| 154 | +Open the MoonBit menu again. It now holds nine commands, and the two items have swapped: `Create tools file` is greyed out, and `Open tools file` is the one you can choose. | |
| 155 | + | |
| 156 | +## Step 7 — Format it, and run it | |
| 157 | + | |
| 158 | +Press `Alt-M` and choose **Format**. | |
| 159 | + | |
| 160 | +A dialog opens, fills in, and says `— exit 0`. Press `Escape`. | |
| 161 | + | |
| 162 | +Look at the last line of your `main` function. It has changed: | |
| 163 | + | |
| 164 | +```moonbit | |
| 165 | + greet({ name: "MoonBit", times: 3, }) | |
| 166 | +``` | |
| 167 | + | |
| 168 | +`moon fmt` added a trailing comma, and the editor reloaded the file it had just been told had changed underneath it. | |
| 169 | + | |
| 170 | +Now `Alt-M`, then **Run**. A box asks for a value before the command runs: | |
| 171 | + | |
| 172 | +``` | |
| 173 | +┌──────────────── Run ────────────────┐ | |
| 174 | +│ package, e.g. cmd/main │ | |
| 175 | +│ [ ] │ | |
| 176 | +└─────────────────────────────────────┘ | |
| 177 | +``` | |
| 178 | + | |
| 179 | +Type `cmd/main` and press `Enter`. A terminal window opens and the program runs in it: | |
| 180 | + | |
| 181 | +``` | |
| 182 | +Hello, MoonBit! (1) | |
| 183 | +Hello, MoonBit! (2) | |
| 184 | +Hello, MoonBit! (3) | |
| 185 | +``` | |
| 186 | + | |
| 187 | +A terminal rather than a dialog, because a program that reads the keyboard has to be answerable. The program has finished, so the window has stopped behaving like a terminal and every key reaches the editor again: press `Ctrl-W` to close it. | |
| 188 | + | |
| 189 | +## Step 8 — Break it, and see where | |
| 190 | + | |
| 191 | +Go to the `println` line and change `g.name` to `g.nam`. Press `F2` to save. | |
| 192 | + | |
| 193 | +Within a second or two, two things happen. A red `×` appears in the gutter, just left of that line's number. And the status bar reads: | |
| 194 | + | |
| 195 | +``` | |
| 196 | +⚠ The value identifier nam is unbound. | |
| 197 | +``` | |
| 198 | + | |
| 199 | +Nothing asked for that. `moon-lsp` publishes it by itself whenever it re-reads the file. | |
| 200 | + | |
| 201 | +Put the `e` back and save again; both the mark and the message go away. | |
| 202 | + | |
| 203 | +## Step 9 — Change the theme | |
| 204 | + | |
| 205 | +`F10`, then `→` **five times** to reach **Options** — past Edit, Search, Run and Code. Choose **Theme…**. | |
| 206 | + | |
| 207 | +A list opens on the theme you are in. Press `↓` to `cobalt` and `Enter`. The whole screen changes, keeping the same shape. | |
| 208 | + | |
| 209 | +Press `Alt-X` to leave. The editor asks about unsaved files first, if there are any. | |
| 210 | + | |
| 211 | +## What now? | |
| 212 | + | |
| 213 | +You have made a MoonBit project, written a program in the editor, formatted it, run it, broken it, and seen the editor say where. To go further: | |
| 214 | + | |
| 215 | +- To do specific things → the [how-to guides](../how-to/) | |
| 216 | +- To see exactly what is coloured and how → [languages coloured](../reference/languages.md) | |
| 217 | +- To understand why the editor is built this way → the [explanation](../explanation/) | |
| new file mode 100644 | |||
| @@ -0,0 +1,217 @@ | |||
| 1 | +# Tutorial: your first MoonBit program in Turbo MoonBit | ||
| 2 | + | ||
| 3 | +By the end of this tutorial you will have written, formatted, run and broken a small MoonBit program without leaving the editor — and seen the editor tell you where the mistake was. | ||
| 4 | + | ||
| 5 | +No prior knowledge of Turbo MoonBit is needed. You need Go 1.26 or later to build the editor, and the MoonBit toolchain to build the program. | ||
| 6 | + | ||
| 7 | +## Prerequisites | ||
| 8 | + | ||
| 9 | +Check Go: | ||
| 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 | +Check the MoonBit toolchain: | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +moon version --all | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +You should see three lines, each ending in a path: | ||
| 28 | + | ||
| 29 | +``` | ||
| 30 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | ||
| 31 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | ||
| 32 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +If that command is not found, install the toolchain first — [one command does it](../how-to/install-the-moonbit-toolchain.md). | ||
| 36 | + | ||
| 37 | +## Step 1 — Install the editor | ||
| 38 | + | ||
| 39 | +```bash | ||
| 40 | +git clone https://rickub.com/turbo-editors/turbo-moonbit.git | ||
| 41 | +cd turbo-moonbit | ||
| 42 | +make install | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +The installer builds, installs, and then checks what it installed. The last lines are: | ||
| 46 | + | ||
| 47 | +``` | ||
| 48 | +==> Checking the language server | ||
| 49 | + ✓ moon-lsp at ~/.moon/bin/moon-lsp | ||
| 50 | + | ||
| 51 | +==> Ready | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +We now have a `turbo-moonbit` command. | ||
| 55 | + | ||
| 56 | +## Step 2 — Make a project | ||
| 57 | + | ||
| 58 | +```bash | ||
| 59 | +cd /tmp | ||
| 60 | +moon new hello | ||
| 61 | +cd hello | ||
| 62 | +``` | ||
| 63 | + | ||
| 64 | +``` | ||
| 65 | +Created username/hello at hello | ||
| 66 | +``` | ||
| 67 | + | ||
| 68 | +`moon new` writes a `moon.mod`, a `moon.pkg`, a library file, some test files, and a `cmd/main/main.mbt` with a hello-world in it. **`moon.mod` is what Turbo MoonBit looks for** to find the root of a project, and it is the directory `moon-lsp` will be started in. | ||
| 69 | + | ||
| 70 | +## Step 3 — Open the file | ||
| 71 | + | ||
| 72 | +```bash | ||
| 73 | +turbo-moonbit cmd/main/main.mbt | ||
| 74 | +``` | ||
| 75 | + | ||
| 76 | +The screen fills. Along the top: | ||
| 77 | + | ||
| 78 | +``` | ||
| 79 | + File Edit Search Run Code Options Window Snippets MoonBit Help | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +Ten menus, and the ninth is named after the language. Along the bottom, at the right-hand end, you should see: | ||
| 83 | + | ||
| 84 | +``` | ||
| 85 | +1:1 LSP: ready | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +`LSP: ready` means `moon-lsp` started in this directory. We will use it in Step 8. | ||
| 89 | + | ||
| 90 | +## Step 4 — Write the program | ||
| 91 | + | ||
| 92 | +Select everything with `Ctrl-A` and press `Delete`, then type this in. Type it exactly; we will look at the colours next. | ||
| 93 | + | ||
| 94 | +```moonbit | ||
| 95 | +///| | ||
| 96 | +struct Greeting { | ||
| 97 | + name : String | ||
| 98 | + times : Int | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +///| | ||
| 102 | +fn greet(g : Greeting) -> Unit { | ||
| 103 | + for i in 0..<g.times { | ||
| 104 | + println("Hello, \{g.name}! (\{i + 1})") | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +///| | ||
| 109 | +fn main { | ||
| 110 | + greet({ name: "MoonBit", times: 3 }) | ||
| 111 | +} | ||
| 112 | +``` | ||
| 113 | + | ||
| 114 | +Press `F2` to save. The star beside `main.mbt` in the window's title goes away. | ||
| 115 | + | ||
| 116 | +## Step 5 — Read the colours | ||
| 117 | + | ||
| 118 | +Look at what you have typed. In the default `turbo-classic` theme: | ||
| 119 | + | ||
| 120 | +| What | Colour | | ||
| 121 | +| --- | --- | | ||
| 122 | +| `struct`, `fn`, `for`, `in` | bright white, bold — keywords | | ||
| 123 | +| `Greeting`, `String`, `Int`, `Unit` | bright cyan — types | | ||
| 124 | +| `greet`, where it is declared and where it is called | bright yellow, bold — functions | | ||
| 125 | +| `println` | bright cyan, bold — a name the language provides | | ||
| 126 | +| `name`, `times`, `g`, `i` | bright yellow — ordinary names | | ||
| 127 | +| `"Hello, \{g.name}! (\{i + 1})"` | green, **all of it** — one string | | ||
| 128 | +| `0`, `1`, `3` | magenta — numbers | | ||
| 129 | +| `///\|` | grey — a comment | | ||
| 130 | + | ||
| 131 | +Two of those rows are worth a second look. | ||
| 132 | + | ||
| 133 | +**`Greeting` is cyan and `greet` is yellow**, and nothing in the editor was told which of them is a type. MoonBit's own rule decides it: a name beginning with a capital can only be a type, a trait or a constructor. | ||
| 134 | + | ||
| 135 | +**The string is green from the first quote to the last**, interpolations included. The `\{g.name}` inside it is not coloured as code — [and that is on purpose](../explanation/colouring-and-completion.md). | ||
| 136 | + | ||
| 137 | +## Step 6 — Give the project its tools | ||
| 138 | + | ||
| 139 | +Press `F10` to open the menu bar, then `→` **eight times** to reach **MoonBit** — past Edit, Search, Run, Code, Options, Window and Snippets. Faster: press `Alt-M`. | ||
| 140 | + | ||
| 141 | +The menu holds two items, and only one of them is available: | ||
| 142 | + | ||
| 143 | +``` | ||
| 144 | +┌───────────────────┐ | ||
| 145 | +│ Create tools file │ | ||
| 146 | +│ Open tools file │ ← greyed out; there is no file to open yet | ||
| 147 | +└───────────────────┘ | ||
| 148 | +``` | ||
| 149 | + | ||
| 150 | +Choose **Create tools file**. | ||
| 151 | + | ||
| 152 | +A second window opens on the file that was just written, `.turbo-moonbit/tools.toml`. Read it if you like — it explains every key it uses — then press `Ctrl-W` to close it. | ||
| 153 | + | ||
| 154 | +Open the MoonBit menu again. It now holds nine commands, and the two items have swapped: `Create tools file` is greyed out, and `Open tools file` is the one you can choose. | ||
| 155 | + | ||
| 156 | +## Step 7 — Format it, and run it | ||
| 157 | + | ||
| 158 | +Press `Alt-M` and choose **Format**. | ||
| 159 | + | ||
| 160 | +A dialog opens, fills in, and says `— exit 0`. Press `Escape`. | ||
| 161 | + | ||
| 162 | +Look at the last line of your `main` function. It has changed: | ||
| 163 | + | ||
| 164 | +```moonbit | ||
| 165 | + greet({ name: "MoonBit", times: 3, }) | ||
| 166 | +``` | ||
| 167 | + | ||
| 168 | +`moon fmt` added a trailing comma, and the editor reloaded the file it had just been told had changed underneath it. | ||
| 169 | + | ||
| 170 | +Now `Alt-M`, then **Run**. A box asks for a value before the command runs: | ||
| 171 | + | ||
| 172 | +``` | ||
| 173 | +┌──────────────── Run ────────────────┐ | ||
| 174 | +│ package, e.g. cmd/main │ | ||
| 175 | +│ [ ] │ | ||
| 176 | +└─────────────────────────────────────┘ | ||
| 177 | +``` | ||
| 178 | + | ||
| 179 | +Type `cmd/main` and press `Enter`. A terminal window opens and the program runs in it: | ||
| 180 | + | ||
| 181 | +``` | ||
| 182 | +Hello, MoonBit! (1) | ||
| 183 | +Hello, MoonBit! (2) | ||
| 184 | +Hello, MoonBit! (3) | ||
| 185 | +``` | ||
| 186 | + | ||
| 187 | +A terminal rather than a dialog, because a program that reads the keyboard has to be answerable. The program has finished, so the window has stopped behaving like a terminal and every key reaches the editor again: press `Ctrl-W` to close it. | ||
| 188 | + | ||
| 189 | +## Step 8 — Break it, and see where | ||
| 190 | + | ||
| 191 | +Go to the `println` line and change `g.name` to `g.nam`. Press `F2` to save. | ||
| 192 | + | ||
| 193 | +Within a second or two, two things happen. A red `×` appears in the gutter, just left of that line's number. And the status bar reads: | ||
| 194 | + | ||
| 195 | +``` | ||
| 196 | +⚠ The value identifier nam is unbound. | ||
| 197 | +``` | ||
| 198 | + | ||
| 199 | +Nothing asked for that. `moon-lsp` publishes it by itself whenever it re-reads the file. | ||
| 200 | + | ||
| 201 | +Put the `e` back and save again; both the mark and the message go away. | ||
| 202 | + | ||
| 203 | +## Step 9 — Change the theme | ||
| 204 | + | ||
| 205 | +`F10`, then `→` **five times** to reach **Options** — past Edit, Search, Run and Code. Choose **Theme…**. | ||
| 206 | + | ||
| 207 | +A list opens on the theme you are in. Press `↓` to `cobalt` and `Enter`. The whole screen changes, keeping the same shape. | ||
| 208 | + | ||
| 209 | +Press `Alt-X` to leave. The editor asks about unsaved files first, if there are any. | ||
| 210 | + | ||
| 211 | +## What now? | ||
| 212 | + | ||
| 213 | +You have made a MoonBit project, written a program in the editor, formatted it, run it, broken it, and seen the editor say where. To go further: | ||
| 214 | + | ||
| 215 | +- To do specific things → the [how-to guides](../how-to/) | ||
| 216 | +- To see exactly what is coloured and how → [languages coloured](../reference/languages.md) | ||
| 217 | +- To understand why the editor is built this way → the [explanation](../explanation/) | ||
added
docs/fr/README.md +63 -0 | new file mode 100644 | ||
| @@ -0,0 +1,63 @@ | ||
| 1 | +# Turbo MoonBit — documentation | |
| 2 | + | |
| 3 | +Turbo MoonBit est un éditeur pour MoonBit 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 `moon-lsp`, fenêtres shell, réglages par projet, arbre du projet, snippets, et la chaîne d'outils MoonBit à 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 programme MoonBit dans Turbo MoonBit](tutorials/getting-started.md) — l'installer, écrire un programme, le formater, l'exécuter, le casser et voir l'éditeur dire où. | |
| 19 | +- [Projets de démonstration](../../demos/) — trois projets MoonBit à ouvrir dans l'éditeur une fois qu'il est là : un petit, un avec bibliothèque et tests, et un tour de toutes les constructions que le scanner colore. | |
| 20 | + | |
| 21 | +## Guides pratiques — des recettes pour une tâche | |
| 22 | + | |
| 23 | +- [Installer et compiler Turbo MoonBit](how-to/install.md) | |
| 24 | +- [Installer la chaîne d'outils MoonBit](how-to/install-the-moonbit-toolchain.md) | |
| 25 | +- [Lancer les tests](how-to/run-the-tests.md) | |
| 26 | +- [Activer la complétion MoonBit](how-to/enable-completion.md) | |
| 27 | +- [Écrire son propre thème](how-to/write-a-theme.md) | |
| 28 | +- [Se déplacer dans un fichier](how-to/navigate-code.md) | |
| 29 | +- [Interroger le code](how-to/ask-about-code.md) | |
| 30 | +- [Lancer des commandes shell sans quitter l'éditeur](how-to/use-a-terminal.md) | |
| 31 | +- [Donner ses propres réglages à un projet](how-to/configure-a-project.md) | |
| 32 | +- [Parcourir un projet et ouvrir des fichiers depuis un arbre](how-to/browse-a-project.md) | |
| 33 | +- [Insérer des snippets depuis un menu](how-to/use-snippets.md) | |
| 34 | +- [Lancer les commandes moon depuis l'éditeur](how-to/run-moon-commands.md) | |
| 35 | +- [Faire une release](how-to/make-a-release.md) | |
| 36 | +- [Dialoguer avec un agent de code depuis l'éditeur](how-to/talk-to-an-agent.md) | |
| 37 | + | |
| 38 | +## Référence — les détails exacts | |
| 39 | + | |
| 40 | +- [Ligne de commande](reference/cli.md) | |
| 41 | +- [Clavier](reference/keyboard.md) | |
| 42 | +- [Menus](reference/menus.md) | |
| 43 | +- [Format des fichiers de thème](reference/themes.md) | |
| 44 | +- [Fenêtres terminal](reference/terminal.md) | |
| 45 | +- [Réglages de projet](reference/project-settings.md) | |
| 46 | +- [Arbre du projet](reference/project-tree.md) | |
| 47 | +- [Langages colorés](reference/languages.md) | |
| 48 | +- [Snippets](reference/snippets.md) | |
| 49 | +- [Outils MoonBit](reference/moonbit-tools.md) | |
| 50 | +- [Le numéro de version](reference/versioning.md) | |
| 51 | +- [Agents et ACP](reference/acp.md) | |
| 52 | + | |
| 53 | +## Explications — comprendre | |
| 54 | + | |
| 55 | +- [Architecture](explanation/architecture.md) | |
| 56 | +- [Décisions de conception](explanation/design-decisions.md) | |
| 57 | +- [Coloration et complétion](explanation/colouring-and-completion.md) | |
| 58 | +- [Fenêtres terminal](explanation/terminal-windows.md) | |
| 59 | +- [Réglages de projet](explanation/project-settings.md) | |
| 60 | +- [Arbre du projet](explanation/project-tree.md) | |
| 61 | +- [Snippets](explanation/snippets.md) | |
| 62 | +- [Outils MoonBit](explanation/moonbit-tools.md) | |
| 63 | +- [Fenêtres agent](explanation/agent-windows.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,63 @@ | |||
| 1 | +# Turbo MoonBit — documentation | ||
| 2 | + | ||
| 3 | +Turbo MoonBit est un éditeur pour MoonBit 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 `moon-lsp`, fenêtres shell, réglages par projet, arbre du projet, snippets, et la chaîne d'outils MoonBit à 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 programme MoonBit dans Turbo MoonBit](tutorials/getting-started.md) — l'installer, écrire un programme, le formater, l'exécuter, le casser et voir l'éditeur dire où. | ||
| 19 | +- [Projets de démonstration](../../demos/) — trois projets MoonBit à ouvrir dans l'éditeur une fois qu'il est là : un petit, un avec bibliothèque et tests, et un tour de toutes les constructions que le scanner colore. | ||
| 20 | + | ||
| 21 | +## Guides pratiques — des recettes pour une tâche | ||
| 22 | + | ||
| 23 | +- [Installer et compiler Turbo MoonBit](how-to/install.md) | ||
| 24 | +- [Installer la chaîne d'outils MoonBit](how-to/install-the-moonbit-toolchain.md) | ||
| 25 | +- [Lancer les tests](how-to/run-the-tests.md) | ||
| 26 | +- [Activer la complétion MoonBit](how-to/enable-completion.md) | ||
| 27 | +- [Écrire son propre thème](how-to/write-a-theme.md) | ||
| 28 | +- [Se déplacer dans un fichier](how-to/navigate-code.md) | ||
| 29 | +- [Interroger le code](how-to/ask-about-code.md) | ||
| 30 | +- [Lancer des commandes shell sans quitter l'éditeur](how-to/use-a-terminal.md) | ||
| 31 | +- [Donner ses propres réglages à un projet](how-to/configure-a-project.md) | ||
| 32 | +- [Parcourir un projet et ouvrir des fichiers depuis un arbre](how-to/browse-a-project.md) | ||
| 33 | +- [Insérer des snippets depuis un menu](how-to/use-snippets.md) | ||
| 34 | +- [Lancer les commandes moon depuis l'éditeur](how-to/run-moon-commands.md) | ||
| 35 | +- [Faire une release](how-to/make-a-release.md) | ||
| 36 | +- [Dialoguer avec un agent de code depuis l'éditeur](how-to/talk-to-an-agent.md) | ||
| 37 | + | ||
| 38 | +## Référence — les détails exacts | ||
| 39 | + | ||
| 40 | +- [Ligne de commande](reference/cli.md) | ||
| 41 | +- [Clavier](reference/keyboard.md) | ||
| 42 | +- [Menus](reference/menus.md) | ||
| 43 | +- [Format des fichiers de thème](reference/themes.md) | ||
| 44 | +- [Fenêtres terminal](reference/terminal.md) | ||
| 45 | +- [Réglages de projet](reference/project-settings.md) | ||
| 46 | +- [Arbre du projet](reference/project-tree.md) | ||
| 47 | +- [Langages colorés](reference/languages.md) | ||
| 48 | +- [Snippets](reference/snippets.md) | ||
| 49 | +- [Outils MoonBit](reference/moonbit-tools.md) | ||
| 50 | +- [Le numéro de version](reference/versioning.md) | ||
| 51 | +- [Agents et ACP](reference/acp.md) | ||
| 52 | + | ||
| 53 | +## Explications — comprendre | ||
| 54 | + | ||
| 55 | +- [Architecture](explanation/architecture.md) | ||
| 56 | +- [Décisions de conception](explanation/design-decisions.md) | ||
| 57 | +- [Coloration et complétion](explanation/colouring-and-completion.md) | ||
| 58 | +- [Fenêtres terminal](explanation/terminal-windows.md) | ||
| 59 | +- [Réglages de projet](explanation/project-settings.md) | ||
| 60 | +- [Arbre du projet](explanation/project-tree.md) | ||
| 61 | +- [Snippets](explanation/snippets.md) | ||
| 62 | +- [Outils MoonBit](explanation/moonbit-tools.md) | ||
| 63 | +- [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 MoonBit 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 MoonBit apporte, c'est l'`acp.toml` de départ qu'il propose d'écrire — la seule part de tout ceci qui parle de projets MoonBit. Turbo Rust et Turbo Python 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 `moon 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 à `moon-lsp`. | |
| 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 MoonBit 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 MoonBit apporte, c'est l'`acp.toml` de départ qu'il propose d'écrire — la seule part de tout ceci qui parle de projets MoonBit. Turbo Rust et Turbo Python 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 `moon 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 à `moon-lsp`. | ||
| 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 MoonBit 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/moonbitlang la totalité de ce qui fait Turbo MoonBit | |
| 14 | + moonbitlang.go le profil : nom, menu, serveur, marqueurs de racine, où moon-lsp 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 onze cents lignes commentaires compris, dont sept cents pour l'analyseur — cinq cent quarante lignes de code au décompte de qlty. 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 `moonbitlang.Register()`, qui apprend à la bibliothèque à colorer les fichiers `.mbt`. | |
| 30 | +3. Construit `moonbitlang.Profile()` — la valeur qui dit que cet éditeur est Turbo MoonBit. | |
| 31 | +4. Lit `.turbo-moonbit/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 moon-lsp à 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 MoonBit. | |
| 36 | + | |
| 37 | +## Le profil est la couture | |
| 38 | + | |
| 39 | +```go | |
| 40 | +profile.Profile{ | |
| 41 | + Name: "Turbo MoonBit", | |
| 42 | + Slug: "turbo-moonbit", | |
| 43 | + Language: "MoonBit", | |
| 44 | + ToolsMenu: "~P~ython", | |
| 45 | + RootMarkers: []string{"moon.mod", "moon.mod.json"}, | |
| 46 | + Server: profile.Server{Command: "moon-lsp", …}, | |
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | |
| 48 | +} | |
| 49 | +``` | |
| 50 | + | |
| 51 | +Tout ce qui serait sinon un `"turbo-moonbit"`, un `"moon-lsp"` ou un `"moon.mod"` 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-moonbit`, le répertoire de projet est `.turbo-moonbit`, la configuration de l'utilisateur vit dans `~/.config/turbo-moonbit`, et les variables d'environnement qui la remplacent sont `TURBO_MOONBIT_THEME_DIR` et `TURBO_MOONBIT_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 | +MoonBit 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 `.mbt` 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 MoonBit 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 `moon` : 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é **moon** 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. `MoonBit` 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/moonbitlang/editor_test.go` construit un Turbo MoonBit entier sur un terminal simulé — `app.New(screen, "turbo-classic", moonbitlang.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 `.mbt` ressort coloré. Un bug où `main` aurait oublié d'enregistrer MoonBit passerait tous les tests de turbo-core. | |
| 74 | + | |
| 75 | +Le même fichier pilote un **vrai moon-lsp** 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 moon-lsp *ne peut pas* faire : il n'annonce ni `typeDefinition` ni `implementation`, la documentation le dit, et le test échoue si un futur moon-lsp 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 MoonBit 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 MoonBit](moonbit-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 MoonBit 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/moonbitlang la totalité de ce qui fait Turbo MoonBit | ||
| 14 | + moonbitlang.go le profil : nom, menu, serveur, marqueurs de racine, où moon-lsp 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 onze cents lignes commentaires compris, dont sept cents pour l'analyseur — cinq cent quarante lignes de code au décompte de qlty. 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 `moonbitlang.Register()`, qui apprend à la bibliothèque à colorer les fichiers `.mbt`. | ||
| 30 | +3. Construit `moonbitlang.Profile()` — la valeur qui dit que cet éditeur est Turbo MoonBit. | ||
| 31 | +4. Lit `.turbo-moonbit/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 moon-lsp à 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 MoonBit. | ||
| 36 | + | ||
| 37 | +## Le profil est la couture | ||
| 38 | + | ||
| 39 | +```go | ||
| 40 | +profile.Profile{ | ||
| 41 | + Name: "Turbo MoonBit", | ||
| 42 | + Slug: "turbo-moonbit", | ||
| 43 | + Language: "MoonBit", | ||
| 44 | + ToolsMenu: "~P~ython", | ||
| 45 | + RootMarkers: []string{"moon.mod", "moon.mod.json"}, | ||
| 46 | + Server: profile.Server{Command: "moon-lsp", …}, | ||
| 47 | + Templates: profile.Templates{Settings: …, Snippets: …, Tools: …}, | ||
| 48 | +} | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +Tout ce qui serait sinon un `"turbo-moonbit"`, un `"moon-lsp"` ou un `"moon.mod"` 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-moonbit`, le répertoire de projet est `.turbo-moonbit`, la configuration de l'utilisateur vit dans `~/.config/turbo-moonbit`, et les variables d'environnement qui la remplacent sont `TURBO_MOONBIT_THEME_DIR` et `TURBO_MOONBIT_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 | +MoonBit 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 `.mbt` 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 MoonBit 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 `moon` : 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é **moon** 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. `MoonBit` 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/moonbitlang/editor_test.go` construit un Turbo MoonBit entier sur un terminal simulé — `app.New(screen, "turbo-classic", moonbitlang.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 `.mbt` ressort coloré. Un bug où `main` aurait oublié d'enregistrer MoonBit passerait tous les tests de turbo-core. | ||
| 74 | + | ||
| 75 | +Le même fichier pilote un **vrai moon-lsp** 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 moon-lsp *ne peut pas* faire : il n'annonce ni `typeDefinition` ni `implementation`, la documentation le dit, et le test échoue si un futur moon-lsp 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 MoonBit 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 MoonBit](moonbit-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 +114 -0 | new file mode 100644 | ||
| @@ -0,0 +1,114 @@ | ||
| 1 | +# Coloration et complétion — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Les deux fonctions qui font de Turbo MoonBit un éditeur *pour MoonBit* plutôt qu'un éditeur de texte qui ouvre des fichiers `.mbt` : 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 moon-lsp, et Turbo MoonBit 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 MoonBit 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 MoonBit est analysé à la main | |
| 16 | + | |
| 17 | +MoonBit n'a pas de lexeur disponible sous forme de paquet Go. Turbo Go peut passer par `go/scanner`, la bibliothèque standard analysant son propre langage ; Turbo MoonBit n'a rien de tel, et les trois voies possibles ont été pesées. | |
| 18 | + | |
| 19 | +**Faire tourner un vrai lexeur MoonBit** voudrait dire lancer `moonc` et lui demander des jetons — un processus par frappe, et une dépendance sur une chaîne d'outils que l'éditeur ne devrait pas exiger pour colorer un fichier. | |
| 20 | + | |
| 21 | +**Embarquer une grammaire** — tree-sitter ou équivalent — voudrait dire une bibliothèque native, une étape de compilation et un binaire qui ne se compile plus partout. Turbo Core tient à deux dépendances directes et demi ; ce n'est pas ici qu'on ajoute la troisième. | |
| 22 | + | |
| 23 | +**Écrire un scanner à la main** demande un fichier de plus et donne quelque chose qui tourne à chaque frappe sans rien allouer d'inattendu, ne casse jamais sur du texte invalide et se lit comme du Go ordinaire. | |
| 24 | + | |
| 25 | +Le scanner, donc. Quelque six cents lignes, un fichier chacun pour l'aiguillage, les littéraux et les mots — et aucune tentative de moteur généraliste. Pas de langage de motifs, pas de format de grammaire, pas de table d'expressions régulières : du Go ordinaire qu'un lecteur peut suivre, la règle même que suivent les huit scanners de turbo-core. | |
| 26 | + | |
| 27 | +## Rien ne franchit une fin de ligne | |
| 28 | + | |
| 29 | +Tous les autres éditeurs de cette famille font passer un état réel à travers leur scanner. Turbo Go et Turbo Rust portent une profondeur de commentaire de bloc ; Turbo Rust porte en plus le délimiteur d'une chaîne brute ; Turbo Python porte lequel des deux guillemets a ouvert un littéral triple. Turbo MoonBit ne porte rien du tout, et c'est un fait sur le langage plutôt qu'un raccourci : | |
| 30 | + | |
| 31 | +- **Il n'y a pas de commentaire de bloc.** La grammaire le dit en toutes lettres : « MoonBit n'a pas de forme de commentaire de bloc. » `//` va jusqu'à la fin de la ligne, `///` est un commentaire de documentation qui fait de même. | |
| 32 | +- **Aucun littéral ne peut atteindre la ligne suivante.** Pour les chaînes, les octets, les expressions régulières, les caractères et les octets-caractères, « un saut de ligne avant le guillemet fermant signale un littéral de chaîne non terminé ». Une ligne qui se termine à l'intérieur d'un littéral est du source cassé, pas une construction. | |
| 33 | +- **Une chaîne multiligne n'est pas un littéral qui s'étend sur plusieurs lignes.** C'est une suite de lignes préfixées `#|` ou `$|`, chacune un jeton complet, que le compilateur joint ensuite par un saut de ligne. | |
| 34 | +- **Un attribut tient explicitement sur une ligne** : « tout ce qui va jusqu'au saut de ligne suivant est la charge utile brute ». | |
| 35 | + | |
| 36 | +Le type de report est donc vide, et c'est un type nommé plutôt qu'un `struct{}` écrit sur place, pour que le raisonnement ait un endroit où vivre. Si MoonBit acquiert un jour une construction qui franchit les lignes, c'est ce type qui gagnera un champ. | |
| 37 | + | |
| 38 | +Ce que cela achète mérite d'être dit clairement : **un guillemet égaré ne peut pas peindre le reste du fichier.** Dans tous les autres éditeurs d'ici, une chaîne non terminée est un cas que le scanner doit décider d'*abandonner*, et se tromper sur cette décision transforme une frappe en un écran entier de vert. Ici, il n'y a pas de décision à rater. | |
| 39 | + | |
| 40 | +## Là où le scanner s'appuie sur le langage, et non sur une convention | |
| 41 | + | |
| 42 | +C'est ce qui rend le scanner de MoonBit plus court que celui de ses frères, et la raison tient en une règle lexicale. | |
| 43 | + | |
| 44 | +**Un nom capitalisé est un type, et c'est la règle du langage plutôt qu'une habitude.** La grammaire définit `uident` comme commençant « par une majuscule ASCII », et seuls un type, un trait ou un constructeur d'énumération peuvent s'écrire ainsi. Turbo Python doit consulter la PEP 8 pour distinguer `ValueError("non")` de `parse("non")` ; Turbo Rust doit tenir une table des constructeurs que le langage nomme, parce que `Some(x)` ressemble à un appel. Ici, la casse *est* la réponse : il n'y a donc aucune table des types intégrés dans ce dépôt — `Int`, `StringBuilder` et un type écrit ce matin sont colorés par la même ligne de code. | |
| 45 | + | |
| 46 | +**Ce que cela coûte est unique, et inévitable.** Un constructeur d'énumération à vous — `Circle(1.0)` — est coloré en type, parce que rien dans la syntaxe ne le sépare d'un type appliqué à des arguments. Inventer une séparation reviendrait à se tromper dans les deux sens au lieu d'un. | |
| 47 | + | |
| 48 | +**Le prélude, lui, est une table, et elle a été lue plutôt que retenue.** `println`, `abort`, `fail`, `ignore`, `inspect` et les autres proviennent du fichier d'interface généré de `moonbitlang/core/prelude`. Cela compte plus qu'il n'y paraît : une table écrite d'habitude aurait contenu `print`, et MoonBit n'a jamais eu de `print`. Les noms dépréciés du prélude — `dump`, `not`, `tap` — sont délibérément absents, parce que les colorer en primitives présenterait comme siennes quatre choses que le langage cherche à retirer. | |
| 49 | + | |
| 50 | +## Le seul endroit où la grammaire doit être suivie à la lettre | |
| 51 | + | |
| 52 | +`1..=2`, c'est un entier et un opérateur d'intervalle. Un scanner qui avalerait n'importe quel point après un nombre lirait le double `1.` et laisserait `.=2` derrière lui, et tous les intervalles de tous les fichiers seraient mal colorés. | |
| 53 | + | |
| 54 | +La grammaire tranche en une phrase — « avant `..`, l'entier se termine d'abord, donc `1..=2` commence par `1` puis `..=` » — et le scanner la suit exactement : un point ne rejoint un nombre que si un second ne le suit pas. La même discipline gouverne les suffixes. `42UL` est un seul nombre et `42u` est `42` suivi du nom `u`, parce que la grammaire dit que les suffixes sont en majuscules, et colorer `42u` en littéral inventerait quelque chose que le compilateur s'apprête à rejeter. | |
| 55 | + | |
| 56 | +Un point a deux autres métiers, et tous deux ont dû être écrits explicitement plutôt que rangés dans la ponctuation. `pair.0` est un accès de tuple. `xs.length()` est une méthode — et le nom qui suit le point est cherché *sans* la table des mots-clés, parce que les identifiants pointés de MoonBit « suivent les règles de casse des identifiants sans consulter la table des mots-clés, si bien que `.if` est valide ». Un enregistrement avec un champ nommé `type` est du MoonBit ordinaire, et un scanner qui colorerait ce champ en mot-clé affirmerait quelque chose que le langage contredit. | |
| 57 | + | |
| 58 | +## Ce que le scanner refuse de deviner | |
| 59 | + | |
| 60 | +Là où une construction ne peut pas être reconnue depuis ce que contient une seule ligne, elle est laissée tranquille plutôt qu'approximée. Un coloriseur qui se trompe est pire qu'un coloriseur discret : | |
| 61 | + | |
| 62 | +| Non reconnu | Parce que | | |
| 63 | +| --- | --- | | |
| 64 | +| L'expression à l'intérieur de `\{…}` | La grammaire la fait aller jusqu'à « l'accolade correspondante », celles des littéraux imbriqués ne comptant pas : trouver la fin demande l'analyseur syntaxique. Un compteur d'accolades qui se tromperait terminerait la chaîne trop tôt, et un littéral qui avale le reste de la ligne est la façon la plus bruyante dont un coloriseur puisse casser. Une seule étendue plate est la réponse honnête pour le cas ordinaire, et c'est celle que Turbo Python donne à une f-string pour la même raison. Sa limite est une *chaîne* imbriquée dans l'interpolation — voir plus bas | | |
| 65 | +| Un mot réservé comme mot-clé | `move`, `ref`, `static`, `unsafe`, `await` et quarante autres sont *réservés* plutôt que mots-clés : le lexeur les traite comme des identifiants et se contente d'avertir. Les colorer dirait au lecteur qu'il ne peut pas écrire `let ref = 1` alors qu'il le peut | | |
| 66 | +| Un identifiant contenant des lettres non ASCII | MoonBit accepte le CJK et plusieurs autres plages Unicode dans un nom. Les prédicats de caractères sur lesquels ce scanner est bâti sont ASCII : un tel nom est franchi sans couleur plutôt que deviné — une frontière qu'il vaut mieux connaître qu'un défaut à cacher | | |
| 67 | +| `moon.mod`, `moon.pkg` et `moon.work` | Ce sont les fichiers du DSL de configuration de MoonBit plutôt que du MoonBit. Les colorer avec le scanner MoonBit serait faux sur `import { … }` et sur chaque clé nue, et écrire un second scanner pour un format qui bouge encore est un travail à courte durée de vie | | |
| 68 | +| Le contenu d'un bloc de `.mbt.md` | C'est un document Markdown, et c'est Markdown qui le colore. Un bloc délimité est d'une seule couleur quel que soit le langage qu'il annonce — c'est la règle de turbo-core, et elle s'applique à `mbt` exactement comme à `bash` | | |
| 69 | + | |
| 70 | +**Le seul endroit où cette réponse est visiblement fausse est une chaîne à l'intérieur d'une interpolation.** `"a \{f("x")} c"` est un seul littéral pour le compilateur et trois étendues pour le scanner — chaîne, puis `x` en identifiant, puis chaîne — parce que le premier guillemet non échappé est pris pour le fermant. C'est le prix du refus d'analyser, c'est borné (les étendues restent ordonnées et ne se chevauchent jamais, donc rien en aval ne se dérègle), et `demos/syntax-tour/tour.mbt` contient une ligne qui le montre plutôt que de l'éviter. | |
| 71 | + | |
| 72 | +**`package` est le seul débordement délibéré**, et il mérite d'être nommé comme tel. Dans un fichier `.mbt` ce n'est qu'un mot réservé ; dans les fichiers d'interface `.mbti` que cet éditeur colore aussi, c'est un vrai mot-clé. Un seul scanner sert les deux, et le colorer en mot-clé dit dans un `.mbt` exactement ce que le compilateur s'apprête à dire : ce mot ne vous appartient pas. | |
| 73 | + | |
| 74 | +## Les huit autres langages viennent gratuitement | |
| 75 | + | |
| 76 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfile et shell sont colorés par turbo-core, pas ici. Un projet MoonBit a un `moon.mod`, un `README.md`, quelques scripts, un workflow CI en YAML et souvent un Dockerfile, et un éditeur qui ne colorerait que les fichiers `.mbt` obligerait à le quitter pour tout le reste. | |
| 77 | + | |
| 78 | +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 MoonBit les a obtenus en important un paquet. | |
| 79 | + | |
| 80 | +## La complétion, et pourquoi elle peut échouer en silence | |
| 81 | + | |
| 82 | +Turbo MoonBit ne sait rien du système de types de MoonBit et n'essaie pas d'en savoir. Il interroge moon-lsp par le Language Server Protocol et dessine la réponse. | |
| 83 | + | |
| 84 | +Trois choses méritent d'être connues, car toutes trois ressemblent à « la complétion est cassée » : | |
| 85 | + | |
| 86 | +**moon-lsp 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. | |
| 87 | + | |
| 88 | +**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 `moon.mod`, `moon.mod.json` ou `moon.mod.json` 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. | |
| 89 | + | |
| 90 | +**Un serveur installé sans ses extras répond aux questions mais ne signale jamais un problème de lui-même.** Les linters de moon-lsp 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. | |
| 91 | + | |
| 92 | +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. | |
| 93 | + | |
| 94 | +## Neuf questions, une connexion — et les deux auxquelles moon-lsp ne répond pas | |
| 95 | + | |
| 96 | +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. | |
| 97 | + | |
| 98 | +**Quelque chose à lire.** `hover` — qu'est-ce que c'est ? — dessiné dans une boîte. | |
| 99 | + | |
| 100 | +**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. | |
| 101 | + | |
| 102 | +**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. | |
| 103 | + | |
| 104 | +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. | |
| 105 | + | |
| 106 | +**Deux des neuf reviennent vides avec moon-lsp, et c'est la limite du serveur plutôt que celle de l'éditeur.** moon-lsp n'annonce ni `typeDefinition` ni `implementation` : **Code ▸ Type definition** et **Code ▸ Find implementations** ne signalent donc rien. Tout le reste fonctionne, y compris la recherche de symboles à l'échelle du projet, à laquelle le serveur de Turbo Python ne répond pas. C'est écrit plutôt que caché parce que l'alternative — griser deux entrées de menu selon ce qu'un serveur a dit au démarrage — donne au menu une forme différente selon les machines, et un utilisateur qui a lu cette page en sait plus qu'un utilisateur tombé sur une entrée grisée. | |
| 107 | + | |
| 108 | +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. | |
| 109 | + | |
| 110 | +## Rapport avec le reste | |
| 111 | + | |
| 112 | +- Ce qui est reconnu exactement : [Langages colorés](../reference/languages.md) | |
| 113 | +- Faire marcher la complétion : [Comment activer la complétion MoonBit](../how-to/enable-completion.md) | |
| 114 | +- Où vit le scanner et pourquoi : [Architecture](architecture.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,114 @@ | |||
| 1 | +# Coloration et complétion — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Les deux fonctions qui font de Turbo MoonBit un éditeur *pour MoonBit* plutôt qu'un éditeur de texte qui ouvre des fichiers `.mbt` : 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 moon-lsp, et Turbo MoonBit 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 MoonBit 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 MoonBit est analysé à la main | ||
| 16 | + | ||
| 17 | +MoonBit n'a pas de lexeur disponible sous forme de paquet Go. Turbo Go peut passer par `go/scanner`, la bibliothèque standard analysant son propre langage ; Turbo MoonBit n'a rien de tel, et les trois voies possibles ont été pesées. | ||
| 18 | + | ||
| 19 | +**Faire tourner un vrai lexeur MoonBit** voudrait dire lancer `moonc` et lui demander des jetons — un processus par frappe, et une dépendance sur une chaîne d'outils que l'éditeur ne devrait pas exiger pour colorer un fichier. | ||
| 20 | + | ||
| 21 | +**Embarquer une grammaire** — tree-sitter ou équivalent — voudrait dire une bibliothèque native, une étape de compilation et un binaire qui ne se compile plus partout. Turbo Core tient à deux dépendances directes et demi ; ce n'est pas ici qu'on ajoute la troisième. | ||
| 22 | + | ||
| 23 | +**Écrire un scanner à la main** demande un fichier de plus et donne quelque chose qui tourne à chaque frappe sans rien allouer d'inattendu, ne casse jamais sur du texte invalide et se lit comme du Go ordinaire. | ||
| 24 | + | ||
| 25 | +Le scanner, donc. Quelque six cents lignes, un fichier chacun pour l'aiguillage, les littéraux et les mots — et aucune tentative de moteur généraliste. Pas de langage de motifs, pas de format de grammaire, pas de table d'expressions régulières : du Go ordinaire qu'un lecteur peut suivre, la règle même que suivent les huit scanners de turbo-core. | ||
| 26 | + | ||
| 27 | +## Rien ne franchit une fin de ligne | ||
| 28 | + | ||
| 29 | +Tous les autres éditeurs de cette famille font passer un état réel à travers leur scanner. Turbo Go et Turbo Rust portent une profondeur de commentaire de bloc ; Turbo Rust porte en plus le délimiteur d'une chaîne brute ; Turbo Python porte lequel des deux guillemets a ouvert un littéral triple. Turbo MoonBit ne porte rien du tout, et c'est un fait sur le langage plutôt qu'un raccourci : | ||
| 30 | + | ||
| 31 | +- **Il n'y a pas de commentaire de bloc.** La grammaire le dit en toutes lettres : « MoonBit n'a pas de forme de commentaire de bloc. » `//` va jusqu'à la fin de la ligne, `///` est un commentaire de documentation qui fait de même. | ||
| 32 | +- **Aucun littéral ne peut atteindre la ligne suivante.** Pour les chaînes, les octets, les expressions régulières, les caractères et les octets-caractères, « un saut de ligne avant le guillemet fermant signale un littéral de chaîne non terminé ». Une ligne qui se termine à l'intérieur d'un littéral est du source cassé, pas une construction. | ||
| 33 | +- **Une chaîne multiligne n'est pas un littéral qui s'étend sur plusieurs lignes.** C'est une suite de lignes préfixées `#|` ou `$|`, chacune un jeton complet, que le compilateur joint ensuite par un saut de ligne. | ||
| 34 | +- **Un attribut tient explicitement sur une ligne** : « tout ce qui va jusqu'au saut de ligne suivant est la charge utile brute ». | ||
| 35 | + | ||
| 36 | +Le type de report est donc vide, et c'est un type nommé plutôt qu'un `struct{}` écrit sur place, pour que le raisonnement ait un endroit où vivre. Si MoonBit acquiert un jour une construction qui franchit les lignes, c'est ce type qui gagnera un champ. | ||
| 37 | + | ||
| 38 | +Ce que cela achète mérite d'être dit clairement : **un guillemet égaré ne peut pas peindre le reste du fichier.** Dans tous les autres éditeurs d'ici, une chaîne non terminée est un cas que le scanner doit décider d'*abandonner*, et se tromper sur cette décision transforme une frappe en un écran entier de vert. Ici, il n'y a pas de décision à rater. | ||
| 39 | + | ||
| 40 | +## Là où le scanner s'appuie sur le langage, et non sur une convention | ||
| 41 | + | ||
| 42 | +C'est ce qui rend le scanner de MoonBit plus court que celui de ses frères, et la raison tient en une règle lexicale. | ||
| 43 | + | ||
| 44 | +**Un nom capitalisé est un type, et c'est la règle du langage plutôt qu'une habitude.** La grammaire définit `uident` comme commençant « par une majuscule ASCII », et seuls un type, un trait ou un constructeur d'énumération peuvent s'écrire ainsi. Turbo Python doit consulter la PEP 8 pour distinguer `ValueError("non")` de `parse("non")` ; Turbo Rust doit tenir une table des constructeurs que le langage nomme, parce que `Some(x)` ressemble à un appel. Ici, la casse *est* la réponse : il n'y a donc aucune table des types intégrés dans ce dépôt — `Int`, `StringBuilder` et un type écrit ce matin sont colorés par la même ligne de code. | ||
| 45 | + | ||
| 46 | +**Ce que cela coûte est unique, et inévitable.** Un constructeur d'énumération à vous — `Circle(1.0)` — est coloré en type, parce que rien dans la syntaxe ne le sépare d'un type appliqué à des arguments. Inventer une séparation reviendrait à se tromper dans les deux sens au lieu d'un. | ||
| 47 | + | ||
| 48 | +**Le prélude, lui, est une table, et elle a été lue plutôt que retenue.** `println`, `abort`, `fail`, `ignore`, `inspect` et les autres proviennent du fichier d'interface généré de `moonbitlang/core/prelude`. Cela compte plus qu'il n'y paraît : une table écrite d'habitude aurait contenu `print`, et MoonBit n'a jamais eu de `print`. Les noms dépréciés du prélude — `dump`, `not`, `tap` — sont délibérément absents, parce que les colorer en primitives présenterait comme siennes quatre choses que le langage cherche à retirer. | ||
| 49 | + | ||
| 50 | +## Le seul endroit où la grammaire doit être suivie à la lettre | ||
| 51 | + | ||
| 52 | +`1..=2`, c'est un entier et un opérateur d'intervalle. Un scanner qui avalerait n'importe quel point après un nombre lirait le double `1.` et laisserait `.=2` derrière lui, et tous les intervalles de tous les fichiers seraient mal colorés. | ||
| 53 | + | ||
| 54 | +La grammaire tranche en une phrase — « avant `..`, l'entier se termine d'abord, donc `1..=2` commence par `1` puis `..=` » — et le scanner la suit exactement : un point ne rejoint un nombre que si un second ne le suit pas. La même discipline gouverne les suffixes. `42UL` est un seul nombre et `42u` est `42` suivi du nom `u`, parce que la grammaire dit que les suffixes sont en majuscules, et colorer `42u` en littéral inventerait quelque chose que le compilateur s'apprête à rejeter. | ||
| 55 | + | ||
| 56 | +Un point a deux autres métiers, et tous deux ont dû être écrits explicitement plutôt que rangés dans la ponctuation. `pair.0` est un accès de tuple. `xs.length()` est une méthode — et le nom qui suit le point est cherché *sans* la table des mots-clés, parce que les identifiants pointés de MoonBit « suivent les règles de casse des identifiants sans consulter la table des mots-clés, si bien que `.if` est valide ». Un enregistrement avec un champ nommé `type` est du MoonBit ordinaire, et un scanner qui colorerait ce champ en mot-clé affirmerait quelque chose que le langage contredit. | ||
| 57 | + | ||
| 58 | +## Ce que le scanner refuse de deviner | ||
| 59 | + | ||
| 60 | +Là où une construction ne peut pas être reconnue depuis ce que contient une seule ligne, elle est laissée tranquille plutôt qu'approximée. Un coloriseur qui se trompe est pire qu'un coloriseur discret : | ||
| 61 | + | ||
| 62 | +| Non reconnu | Parce que | | ||
| 63 | +| --- | --- | | ||
| 64 | +| L'expression à l'intérieur de `\{…}` | La grammaire la fait aller jusqu'à « l'accolade correspondante », celles des littéraux imbriqués ne comptant pas : trouver la fin demande l'analyseur syntaxique. Un compteur d'accolades qui se tromperait terminerait la chaîne trop tôt, et un littéral qui avale le reste de la ligne est la façon la plus bruyante dont un coloriseur puisse casser. Une seule étendue plate est la réponse honnête pour le cas ordinaire, et c'est celle que Turbo Python donne à une f-string pour la même raison. Sa limite est une *chaîne* imbriquée dans l'interpolation — voir plus bas | | ||
| 65 | +| Un mot réservé comme mot-clé | `move`, `ref`, `static`, `unsafe`, `await` et quarante autres sont *réservés* plutôt que mots-clés : le lexeur les traite comme des identifiants et se contente d'avertir. Les colorer dirait au lecteur qu'il ne peut pas écrire `let ref = 1` alors qu'il le peut | | ||
| 66 | +| Un identifiant contenant des lettres non ASCII | MoonBit accepte le CJK et plusieurs autres plages Unicode dans un nom. Les prédicats de caractères sur lesquels ce scanner est bâti sont ASCII : un tel nom est franchi sans couleur plutôt que deviné — une frontière qu'il vaut mieux connaître qu'un défaut à cacher | | ||
| 67 | +| `moon.mod`, `moon.pkg` et `moon.work` | Ce sont les fichiers du DSL de configuration de MoonBit plutôt que du MoonBit. Les colorer avec le scanner MoonBit serait faux sur `import { … }` et sur chaque clé nue, et écrire un second scanner pour un format qui bouge encore est un travail à courte durée de vie | | ||
| 68 | +| Le contenu d'un bloc de `.mbt.md` | C'est un document Markdown, et c'est Markdown qui le colore. Un bloc délimité est d'une seule couleur quel que soit le langage qu'il annonce — c'est la règle de turbo-core, et elle s'applique à `mbt` exactement comme à `bash` | | ||
| 69 | + | ||
| 70 | +**Le seul endroit où cette réponse est visiblement fausse est une chaîne à l'intérieur d'une interpolation.** `"a \{f("x")} c"` est un seul littéral pour le compilateur et trois étendues pour le scanner — chaîne, puis `x` en identifiant, puis chaîne — parce que le premier guillemet non échappé est pris pour le fermant. C'est le prix du refus d'analyser, c'est borné (les étendues restent ordonnées et ne se chevauchent jamais, donc rien en aval ne se dérègle), et `demos/syntax-tour/tour.mbt` contient une ligne qui le montre plutôt que de l'éviter. | ||
| 71 | + | ||
| 72 | +**`package` est le seul débordement délibéré**, et il mérite d'être nommé comme tel. Dans un fichier `.mbt` ce n'est qu'un mot réservé ; dans les fichiers d'interface `.mbti` que cet éditeur colore aussi, c'est un vrai mot-clé. Un seul scanner sert les deux, et le colorer en mot-clé dit dans un `.mbt` exactement ce que le compilateur s'apprête à dire : ce mot ne vous appartient pas. | ||
| 73 | + | ||
| 74 | +## Les huit autres langages viennent gratuitement | ||
| 75 | + | ||
| 76 | +TOML, YAML, Markdown, JavaScript, HTML, XML, Dockerfile et shell sont colorés par turbo-core, pas ici. Un projet MoonBit a un `moon.mod`, un `README.md`, quelques scripts, un workflow CI en YAML et souvent un Dockerfile, et un éditeur qui ne colorerait que les fichiers `.mbt` obligerait à le quitter pour tout le reste. | ||
| 77 | + | ||
| 78 | +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 MoonBit les a obtenus en important un paquet. | ||
| 79 | + | ||
| 80 | +## La complétion, et pourquoi elle peut échouer en silence | ||
| 81 | + | ||
| 82 | +Turbo MoonBit ne sait rien du système de types de MoonBit et n'essaie pas d'en savoir. Il interroge moon-lsp par le Language Server Protocol et dessine la réponse. | ||
| 83 | + | ||
| 84 | +Trois choses méritent d'être connues, car toutes trois ressemblent à « la complétion est cassée » : | ||
| 85 | + | ||
| 86 | +**moon-lsp 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. | ||
| 87 | + | ||
| 88 | +**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 `moon.mod`, `moon.mod.json` ou `moon.mod.json` 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. | ||
| 89 | + | ||
| 90 | +**Un serveur installé sans ses extras répond aux questions mais ne signale jamais un problème de lui-même.** Les linters de moon-lsp 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. | ||
| 91 | + | ||
| 92 | +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. | ||
| 93 | + | ||
| 94 | +## Neuf questions, une connexion — et les deux auxquelles moon-lsp ne répond pas | ||
| 95 | + | ||
| 96 | +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. | ||
| 97 | + | ||
| 98 | +**Quelque chose à lire.** `hover` — qu'est-ce que c'est ? — dessiné dans une boîte. | ||
| 99 | + | ||
| 100 | +**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. | ||
| 101 | + | ||
| 102 | +**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. | ||
| 103 | + | ||
| 104 | +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. | ||
| 105 | + | ||
| 106 | +**Deux des neuf reviennent vides avec moon-lsp, et c'est la limite du serveur plutôt que celle de l'éditeur.** moon-lsp n'annonce ni `typeDefinition` ni `implementation` : **Code ▸ Type definition** et **Code ▸ Find implementations** ne signalent donc rien. Tout le reste fonctionne, y compris la recherche de symboles à l'échelle du projet, à laquelle le serveur de Turbo Python ne répond pas. C'est écrit plutôt que caché parce que l'alternative — griser deux entrées de menu selon ce qu'un serveur a dit au démarrage — donne au menu une forme différente selon les machines, et un utilisateur qui a lu cette page en sait plus qu'un utilisateur tombé sur une entrée grisée. | ||
| 107 | + | ||
| 108 | +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. | ||
| 109 | + | ||
| 110 | +## Rapport avec le reste | ||
| 111 | + | ||
| 112 | +- Ce qui est reconnu exactement : [Langages colorés](../reference/languages.md) | ||
| 113 | +- Faire marcher la complétion : [Comment activer la complétion MoonBit](../how-to/enable-completion.md) | ||
| 114 | +- 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 MoonBit, 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 MoonBit 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 moon-lsp, 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 `moon-lsp` 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 MoonBit 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-moonbit@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 MoonBit, 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 MoonBit 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 moon-lsp, 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 `moon-lsp` 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 MoonBit 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-moonbit@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/moonbit-tools.md +117 -0 | new file mode 100644 | ||
| @@ -0,0 +1,117 @@ | ||
| 1 | +# Outils MoonBit — explication | |
| 2 | + | |
| 3 | +## De quoi s'agit-il ? | |
| 4 | + | |
| 5 | +Un menu **MoonBit** 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* : `moon 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 `moon 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-moon-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 | +`moon install` 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 `moon`, le système de construction livré avec le langage — aucune n'exige donc quoi que ce soit au-delà de la chaîne d'outils elle-même. C'est un défaut défendable, ce n'est la réponse universelle de personne. Un projet qui ne compile que pour un backend veut `moon build --target js` sans qu'on le lui demande. Un projet dans un espace de travail `moon.work` veut `moon check --target all` depuis la racine de cet espace. Un projet avec un `Makefile` veut `make check`. Un projet qui mesure sa couverture veut `moon coverage analyze`. 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 **MoonBit ▸ 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 `moon fmt && moon check && moon test`. 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 `moon test` dans un dépôt qui n'a jamais entendu parler de MoonBit, et un projet qui ne compile que pour `wasm-gc` hériterait du backend 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é **MoonBit** contenant `docker compose up` ment sur ce qu'il est. Le premier fichier d'outils que l'on écrit déborde de MoonBit, 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 MoonBit dans MoonBit, 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 MoonBit. 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 | +MoonBit reste fixe sur la barre plutôt que de devenir un nom parmi d'autres venu du fichier. **MoonBit ▸ 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`, `MoonBit` 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 MoonBit 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 `moon fmt`. 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 | +`moon build` a besoin d'un backend. `moon run` a besoin d'un paquet. `moon add` a besoin d'un nom de module. 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/moonbit-tools.md) | |
| 115 | +- L'utiliser : [Lancer les commandes moon depuis l'éditeur](../how-to/run-moon-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 MoonBit — explication | ||
| 2 | + | ||
| 3 | +## De quoi s'agit-il ? | ||
| 4 | + | ||
| 5 | +Un menu **MoonBit** 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* : `moon 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 `moon 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-moon-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 | +`moon install` 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 `moon`, le système de construction livré avec le langage — aucune n'exige donc quoi que ce soit au-delà de la chaîne d'outils elle-même. C'est un défaut défendable, ce n'est la réponse universelle de personne. Un projet qui ne compile que pour un backend veut `moon build --target js` sans qu'on le lui demande. Un projet dans un espace de travail `moon.work` veut `moon check --target all` depuis la racine de cet espace. Un projet avec un `Makefile` veut `make check`. Un projet qui mesure sa couverture veut `moon coverage analyze`. 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 **MoonBit ▸ 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 `moon fmt && moon check && moon test`. 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 `moon test` dans un dépôt qui n'a jamais entendu parler de MoonBit, et un projet qui ne compile que pour `wasm-gc` hériterait du backend 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é **MoonBit** contenant `docker compose up` ment sur ce qu'il est. Le premier fichier d'outils que l'on écrit déborde de MoonBit, 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 MoonBit dans MoonBit, 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 MoonBit. 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 | +MoonBit reste fixe sur la barre plutôt que de devenir un nom parmi d'autres venu du fichier. **MoonBit ▸ 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`, `MoonBit` 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 MoonBit 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 `moon fmt`. 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 | +`moon build` a besoin d'un backend. `moon run` a besoin d'un paquet. `moon add` a besoin d'un nom de module. 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/moonbit-tools.md) | ||
| 115 | +- L'utiliser : [Lancer les commandes moon depuis l'éditeur](../how-to/run-moon-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/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-moonbit/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 | +`moon.mod` 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 `moon.mod` 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-moonbit/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-moonbit/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 | +`moon.mod` 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 `moon.mod` 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-moonbit/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 `moon.mod`, parce qu'un module a une frontière réelle — en être à l'intérieur est un fait à propos du code, et moon-lsp a besoin de ce dossier précis pour travailler. Le fichier de réglages, lui, ne remonte pas du tout : `.turbo-moonbit/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 `moon.mod` 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-moonbit/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 `moon.mod`, parce qu'un module a une frontière réelle — en être à l'intérieur est un fait à propos du code, et moon-lsp a besoin de ce dossier précis pour travailler. Le fichier de réglages, lui, ne remonte pas du tout : `.turbo-moonbit/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 `moon.mod` 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-moonbit/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/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 MoonBit, 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 MoonBit, 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. `moon test` 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, `moon test`, `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. `moon test` 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, `moon test`, `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 +72 -0 | new file mode 100644 | ||
| @@ -0,0 +1,72 @@ | ||
| 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 MoonBit 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 | +**Deux de ces cinq entrées ne signalent rien avec moon-lsp.** Le serveur n'annonce ni `typeDefinition` ni `implementation` : **Go to type definition** et **Find implementations** répondent donc qu'il n'y a rien, quelle que soit la qualité du code. Les trois autres, et les deux recherches de symboles ci-dessous, fonctionnent. Voir [coloration et complétion](../explanation/colouring-and-completion.md) pour savoir pourquoi c'est écrit plutôt que caché derrière une entrée de menu grisée. | |
| 22 | + | |
| 23 | +Une seule réponse vous y emmène directement. Plusieurs ouvrent une liste montrant le fichier, sa ligne, et le texte de cette ligne : | |
| 24 | + | |
| 25 | +``` | |
| 26 | +References (3) | |
| 27 | + main.mbt:1 fn helper() -> Int { | |
| 28 | + main.mbt:7 helper() | |
| 29 | + main.mbt:12 helper() + 1 | |
| 30 | +``` | |
| 31 | + | |
| 32 | +Déplacez-vous aux flèches, `Entrée` pour y aller, `Échap` pour rester. | |
| 33 | + | |
| 34 | +## Quand rien ne revient | |
| 35 | + | |
| 36 | +Trois choses se ressemblent, et la barre d'état les distingue : | |
| 37 | + | |
| 38 | +| Elle affiche | Signification | | |
| 39 | +| --- | --- | | |
| 40 | +| `No references found` | Le serveur a répondu, et il n'y en a pas | | |
| 41 | +| Autre chose, par exemple `Loading…` | Le serveur n'a pas fini d'indexer. Attendez un instant et redemandez. | | |
| 42 | +| `LSP: off` dans la barre d'état | Aucun serveur ne tourne. Voir [Comment activer la complétion](enable-completion.md). | | |
| 43 | + | |
| 44 | +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. | |
| 45 | + | |
| 46 | +## Chercher par le nom | |
| 47 | + | |
| 48 | +- **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. | |
| 49 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) demande un nom et cherche partout. Ce qui compte comme correspondance appartient au serveur ; moon-lsp est tolérant, quelques lettres suffisent en général. | |
| 50 | + | |
| 51 | +## Voir ce qui ne va pas | |
| 52 | + | |
| 53 | +**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. | |
| 54 | + | |
| 55 | +Les lignes à problème portent une marque dans la gouttière, à côté du numéro de ligne : | |
| 56 | + | |
| 57 | +| Marque | Signification | | |
| 58 | +| --- | --- | | |
| 59 | +| `×` | Une erreur | | |
| 60 | +| `!` | Un avertissement | | |
| 61 | +| `i` | Une information | | |
| 62 | +| `·` | Une suggestion | | |
| 63 | + | |
| 64 | +Une ligne qui a plusieurs problèmes montre le pire d'entre eux. | |
| 65 | + | |
| 66 | +**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. | |
| 67 | + | |
| 68 | +## Voir aussi | |
| 69 | + | |
| 70 | +- Chaque entrée et sa touche : [Menus](../reference/menus.md) | |
| 71 | +- Faire tourner un serveur : [Comment activer la complétion](enable-completion.md) | |
| 72 | +- Ce que l'éditeur demande, et pourquoi : [Coloration et complétion](../explanation/colouring-and-completion.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,72 @@ | |||
| 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 MoonBit 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 | +**Deux de ces cinq entrées ne signalent rien avec moon-lsp.** Le serveur n'annonce ni `typeDefinition` ni `implementation` : **Go to type definition** et **Find implementations** répondent donc qu'il n'y a rien, quelle que soit la qualité du code. Les trois autres, et les deux recherches de symboles ci-dessous, fonctionnent. Voir [coloration et complétion](../explanation/colouring-and-completion.md) pour savoir pourquoi c'est écrit plutôt que caché derrière une entrée de menu grisée. | ||
| 22 | + | ||
| 23 | +Une seule réponse vous y emmène directement. Plusieurs ouvrent une liste montrant le fichier, sa ligne, et le texte de cette ligne : | ||
| 24 | + | ||
| 25 | +``` | ||
| 26 | +References (3) | ||
| 27 | + main.mbt:1 fn helper() -> Int { | ||
| 28 | + main.mbt:7 helper() | ||
| 29 | + main.mbt:12 helper() + 1 | ||
| 30 | +``` | ||
| 31 | + | ||
| 32 | +Déplacez-vous aux flèches, `Entrée` pour y aller, `Échap` pour rester. | ||
| 33 | + | ||
| 34 | +## Quand rien ne revient | ||
| 35 | + | ||
| 36 | +Trois choses se ressemblent, et la barre d'état les distingue : | ||
| 37 | + | ||
| 38 | +| Elle affiche | Signification | | ||
| 39 | +| --- | --- | | ||
| 40 | +| `No references found` | Le serveur a répondu, et il n'y en a pas | | ||
| 41 | +| Autre chose, par exemple `Loading…` | Le serveur n'a pas fini d'indexer. Attendez un instant et redemandez. | | ||
| 42 | +| `LSP: off` dans la barre d'état | Aucun serveur ne tourne. Voir [Comment activer la complétion](enable-completion.md). | | ||
| 43 | + | ||
| 44 | +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. | ||
| 45 | + | ||
| 46 | +## Chercher par le nom | ||
| 47 | + | ||
| 48 | +- **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. | ||
| 49 | +- **Code ▸ Symbol in project…** (`Ctrl-T`) demande un nom et cherche partout. Ce qui compte comme correspondance appartient au serveur ; moon-lsp est tolérant, quelques lettres suffisent en général. | ||
| 50 | + | ||
| 51 | +## Voir ce qui ne va pas | ||
| 52 | + | ||
| 53 | +**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. | ||
| 54 | + | ||
| 55 | +Les lignes à problème portent une marque dans la gouttière, à côté du numéro de ligne : | ||
| 56 | + | ||
| 57 | +| Marque | Signification | | ||
| 58 | +| --- | --- | | ||
| 59 | +| `×` | Une erreur | | ||
| 60 | +| `!` | Un avertissement | | ||
| 61 | +| `i` | Une information | | ||
| 62 | +| `·` | Une suggestion | | ||
| 63 | + | ||
| 64 | +Une ligne qui a plusieurs problèmes montre le pire d'entre eux. | ||
| 65 | + | ||
| 66 | +**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. | ||
| 67 | + | ||
| 68 | +## Voir aussi | ||
| 69 | + | ||
| 70 | +- Chaque entrée et sa touche : [Menus](../reference/menus.md) | ||
| 71 | +- Faire tourner un serveur : [Comment activer la complétion](enable-completion.md) | ||
| 72 | +- 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 MoonBit 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-moonbit ════════════2═[■]╗ | |
| 13 | +║ ▶ .turbo-moonbit ║ | |
| 14 | +║ ▼ internal ║ | |
| 15 | +║ ▶ app ║ | |
| 16 | +║ ▼ ui ║ | |
| 17 | +║ window.go ║ | |
| 18 | +║ .gitignore ║ | |
| 19 | +║ moon.mod ║ | |
| 20 | +║ main.mbt ║ | |
| 21 | +╚══════════════════════════════════════════╝ | |
| 22 | +``` | |
| 23 | + | |
| 24 | +Les dossiers viennent d'abord, puis les fichiers, chaque groupe trié. `.git` est la seule chose masquée — `.turbo-moonbit`, `.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-moonbit/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 MoonBit 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-moonbit ════════════2═[■]╗ | ||
| 13 | +║ ▶ .turbo-moonbit ║ | ||
| 14 | +║ ▼ internal ║ | ||
| 15 | +║ ▶ app ║ | ||
| 16 | +║ ▼ ui ║ | ||
| 17 | +║ window.go ║ | ||
| 18 | +║ .gitignore ║ | ||
| 19 | +║ moon.mod ║ | ||
| 20 | +║ main.mbt ║ | ||
| 21 | +╚══════════════════════════════════════════╝ | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +Les dossiers viennent d'abord, puis les fichiers, chaque groupe trié. `.git` est la seule chose masquée — `.turbo-moonbit`, `.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-moonbit/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 MoonBit 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-moonbit/settings.toml`, rempli avec le thème que vous utilisez à cet instant, et l'ouvre pour édition — coloré, puisque Turbo MoonBit colore le TOML : | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +# turbo-moonbit project settings. | |
| 13 | +# | |
| 14 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -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-moonbit/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.mbt` 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-moonbit -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-moonbit -theme turbo-dark main.mbt | |
| 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-moonbit` 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-moonbit/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 MoonBit 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-moonbit/settings.toml`, rempli avec le thème que vous utilisez à cet instant, et l'ouvre pour édition — coloré, puisque Turbo MoonBit colore le TOML : | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +# turbo-moonbit project settings. | ||
| 13 | +# | ||
| 14 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -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-moonbit/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.mbt` 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-moonbit -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-moonbit -theme turbo-dark main.mbt | ||
| 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-moonbit` 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-moonbit/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 MoonBit | |
| 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 MoonBit est déjà installé et que vous savez ce qu'est un projet MoonBit. | |
| 4 | + | |
| 5 | +La complétion vient de **moon-lsp**, le serveur de langage officiel de MoonBit. Turbo MoonBit ne l'embarque pas : l'édition et la coloration fonctionnent sans lui, et seule la complétion est perdue. | |
| 6 | + | |
| 7 | +## 1. Installer moon-lsp | |
| 8 | + | |
| 9 | +```bash | |
| 10 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | |
| 11 | +``` | |
| 12 | + | |
| 13 | +## 2. S'assurer que Turbo MoonBit le trouve | |
| 14 | + | |
| 15 | +Turbo MoonBit 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 | +moon-lsp version | |
| 19 | +``` | |
| 20 | + | |
| 21 | +Si cette commande répond « introuvable » alors que Turbo MoonBit 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 moon.mod | |
| 27 | +turbo-moonbit main.mbt | |
| 28 | +``` | |
| 29 | + | |
| 30 | +Turbo MoonBit remonte l'arborescence depuis le fichier à la recherche d'un `moon.mod` et démarre moon-lsp dans le répertoire trouvé. **Hors d'un module, moon-lsp 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-moonbit -no-lsp main.mbt | |
| 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 à moon-lsp tant qu'elle n'est pas enregistrée — appuyez sur **F2** et donnez-lui un nom en `.mbt`, quelque part sous le module. 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.** moon-lsp a besoin que le paquet du fichier se construise. Lancez d'abord `moon check` — 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.** moon-lsp 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.** moon-lsp 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 — `moon install` 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 MoonBit | ||
| 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 MoonBit est déjà installé et que vous savez ce qu'est un projet MoonBit. | ||
| 4 | + | ||
| 5 | +La complétion vient de **moon-lsp**, le serveur de langage officiel de MoonBit. Turbo MoonBit ne l'embarque pas : l'édition et la coloration fonctionnent sans lui, et seule la complétion est perdue. | ||
| 6 | + | ||
| 7 | +## 1. Installer moon-lsp | ||
| 8 | + | ||
| 9 | +```bash | ||
| 10 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | ||
| 11 | +``` | ||
| 12 | + | ||
| 13 | +## 2. S'assurer que Turbo MoonBit le trouve | ||
| 14 | + | ||
| 15 | +Turbo MoonBit 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 | +moon-lsp version | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +Si cette commande répond « introuvable » alors que Turbo MoonBit 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 moon.mod | ||
| 27 | +turbo-moonbit main.mbt | ||
| 28 | +``` | ||
| 29 | + | ||
| 30 | +Turbo MoonBit remonte l'arborescence depuis le fichier à la recherche d'un `moon.mod` et démarre moon-lsp dans le répertoire trouvé. **Hors d'un module, moon-lsp 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-moonbit -no-lsp main.mbt | ||
| 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 à moon-lsp tant qu'elle n'est pas enregistrée — appuyez sur **F2** et donnez-lui un nom en `.mbt`, quelque part sous le module. 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.** moon-lsp a besoin que le paquet du fichier se construise. Lancez d'abord `moon check` — 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.** moon-lsp 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.** moon-lsp 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 — `moon install` 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-the-moonbit-toolchain.md +89 -0 | new file mode 100644 | ||
| @@ -0,0 +1,89 @@ | ||
| 1 | +# Installer la chaîne d'outils MoonBit | |
| 2 | + | |
| 3 | +Ce guide montre comment obtenir `moon`, `moonc` et `moon-lsp` sur une machine, et comment vérifier que Turbo MoonBit les trouve. Il suppose que vous avez déjà Turbo MoonBit, ou que vous êtes sur le point de l'avoir — voir [installer l'éditeur](install.md) pour cela. | |
| 4 | + | |
| 5 | +**L'éditeur fonctionne sans rien de tout ceci.** L'édition, la coloration, les thèmes, les snippets et les fenêtres de terminal tournent sans aucune chaîne d'outils. Ce qui en a besoin, c'est la complétion, les marques d'erreur dans la gouttière, et toutes les commandes du menu MoonBit. | |
| 6 | + | |
| 7 | +## L'installer | |
| 8 | + | |
| 9 | +Une seule commande installe toute la chaîne — le compilateur, le système de construction et le serveur de langage ensemble : | |
| 10 | + | |
| 11 | +```bash | |
| 12 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | |
| 13 | +``` | |
| 14 | + | |
| 15 | +Elle télécharge dans `~/.moon`, occupe quelques centaines de mégaoctets avec la bibliothèque standard compilée, et se termine par : | |
| 16 | + | |
| 17 | +``` | |
| 18 | +moonbit was installed successfully to ~/.moon | |
| 19 | +Added "~/.moon/bin" to $PATH in "~/.bashrc" | |
| 20 | +``` | |
| 21 | + | |
| 22 | +C'est cette dernière ligne qu'il faut lire deux fois. L'installeur modifie **un seul** profil de shell ; un shell déjà ouvert, et tout programme lancé depuis un lanceur de bureau, ne l'a pas lu. | |
| 23 | + | |
| 24 | +```bash | |
| 25 | +source ~/.bashrc | |
| 26 | +``` | |
| 27 | + | |
| 28 | +Sous Windows, lancez plutôt l'installeur PowerShell depuis https://www.moonbitlang.com/download. Tout ce qui suit s'applique tel quel une fois qu'il a terminé. | |
| 29 | + | |
| 30 | +## Le vérifier | |
| 31 | + | |
| 32 | +```bash | |
| 33 | +moon version --all | |
| 34 | +``` | |
| 35 | + | |
| 36 | +Vous devriez voir trois lignes, chacune avec son chemin : | |
| 37 | + | |
| 38 | +``` | |
| 39 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | |
| 40 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | |
| 41 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | |
| 42 | +``` | |
| 43 | + | |
| 44 | +Le serveur de langage est un quatrième binaire dans le même dossier, et il vaut la peine d'être interrogé séparément, parce que c'est celui dont l'éditeur a besoin : | |
| 45 | + | |
| 46 | +```bash | |
| 47 | +moon-lsp --version | |
| 48 | +``` | |
| 49 | + | |
| 50 | +``` | |
| 51 | +v0.10.12+1634b282e (2026-09-07) | |
| 52 | +``` | |
| 53 | + | |
| 54 | +## Vérifier que l'éditeur le trouve | |
| 55 | + | |
| 56 | +Ouvrez n'importe quel fichier d'un projet MoonBit et lisez l'extrémité droite de la barre d'état : | |
| 57 | + | |
| 58 | +``` | |
| 59 | + F1 Describe F2 Save F3 Open F6 Window F10 Menu 1:1 LSP: ready | |
| 60 | +``` | |
| 61 | + | |
| 62 | +`LSP: ready` signifie que le serveur a démarré. `LSP: no moon-lsp — curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash` signifie qu'il n'a pas été trouvé, et le message est la commande à lancer. | |
| 63 | + | |
| 64 | +**Turbo MoonBit cherche à trois endroits, dans cet ordre** : votre `PATH`, puis `$MOON_HOME/bin` si `MOON_HOME` est défini, puis `~/.moon/bin`. L'éditeur trouve donc une chaîne d'outils installée normalement même depuis un shell qui n'a jamais lu le profil que l'installeur a modifié — c'est précisément le cas qui, autrement, ressemble à un serveur en panne. | |
| 65 | + | |
| 66 | +## Variantes | |
| 67 | + | |
| 68 | +- **Vous installez vos chaînes d'outils ailleurs.** Définissez `MOON_HOME` avant de lancer l'installeur ; il en tient compte, et l'éditeur aussi. | |
| 69 | +- **Vous avez déjà `moon` mais pas de complétion.** Vérifiez `moon-lsp --version` spécifiquement. Une chaîne dépaquetée à la main, ou une mise à jour partielle, peut laisser `moon` en état de marche et `moon-lsp` absent. | |
| 70 | +- **Vous voulez mettre à jour.** `moon upgrade` remplace la chaîne sur place ; `moon upgrade --dev` prend la version de développement. Ni l'un ni l'autre ne touche à `MOON_HOME` ni à votre `PATH`. | |
| 71 | +- **Vous installez pour de l'intégration continue, ou dans une image.** L'installeur est un script shell ordinaire et n'a pas d'option qui vaille la peine ; épingler une version veut dire récupérer une release depuis https://www.moonbitlang.com/download plutôt que de l'utiliser. | |
| 72 | +- **Vous voulez être sûr que l'éditeur ne le trouve pas simplement via le `PATH`.** Lancez-le avec un environnement réduit — `env PATH=/usr/bin:/bin turbo-moonbit main.mbt` — et la barre d'état devrait toujours dire `LSP: ready`, depuis `~/.moon/bin`. | |
| 73 | + | |
| 74 | +## À quoi sert chaque binaire | |
| 75 | + | |
| 76 | +| Binaire | Ce que l'éditeur en fait | | |
| 77 | +| --- | --- | | |
| 78 | +| `moon-lsp` | Complétion, survol, définitions, références, symboles et marques d'erreur dans la gouttière | | |
| 79 | +| `moon` | Toutes les commandes du menu MoonBit — et `moon-lsp` le lance aussi, pour savoir ce que contient un projet | | |
| 80 | +| `moonc` | Le compilateur, appelé par `moon` | | |
| 81 | +| `moonrun` | Exécute la sortie WebAssembly, appelé par `moon run` | | |
| 82 | + | |
| 83 | +`moon-lsp` seul ne suffit pas : il détermine le projet en lançant `moon`, si bien qu'une machine ayant le serveur mais pas le système de construction obtient un serveur qui démarre, qui est trouvé, et qui ne sait ensuite rien d'aucun fichier. `scripts/install.sh` vérifie exactement cela et le dit. | |
| 84 | + | |
| 85 | +## Voir aussi | |
| 86 | + | |
| 87 | +- [Activer la complétion](enable-completion.md) — que faire quand le serveur est installé et ne dit toujours rien | |
| 88 | +- [Lancer les commandes moon depuis l'éditeur](run-moon-commands.md) — le menu MoonBit | |
| 89 | +- [Coloration et complétion](../explanation/colouring-and-completion.md) — pourquoi l'éditeur a besoin d'un serveur | |
| new file mode 100644 | |||
| @@ -0,0 +1,89 @@ | |||
| 1 | +# Installer la chaîne d'outils MoonBit | ||
| 2 | + | ||
| 3 | +Ce guide montre comment obtenir `moon`, `moonc` et `moon-lsp` sur une machine, et comment vérifier que Turbo MoonBit les trouve. Il suppose que vous avez déjà Turbo MoonBit, ou que vous êtes sur le point de l'avoir — voir [installer l'éditeur](install.md) pour cela. | ||
| 4 | + | ||
| 5 | +**L'éditeur fonctionne sans rien de tout ceci.** L'édition, la coloration, les thèmes, les snippets et les fenêtres de terminal tournent sans aucune chaîne d'outils. Ce qui en a besoin, c'est la complétion, les marques d'erreur dans la gouttière, et toutes les commandes du menu MoonBit. | ||
| 6 | + | ||
| 7 | +## L'installer | ||
| 8 | + | ||
| 9 | +Une seule commande installe toute la chaîne — le compilateur, le système de construction et le serveur de langage ensemble : | ||
| 10 | + | ||
| 11 | +```bash | ||
| 12 | +curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +Elle télécharge dans `~/.moon`, occupe quelques centaines de mégaoctets avec la bibliothèque standard compilée, et se termine par : | ||
| 16 | + | ||
| 17 | +``` | ||
| 18 | +moonbit was installed successfully to ~/.moon | ||
| 19 | +Added "~/.moon/bin" to $PATH in "~/.bashrc" | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +C'est cette dernière ligne qu'il faut lire deux fois. L'installeur modifie **un seul** profil de shell ; un shell déjà ouvert, et tout programme lancé depuis un lanceur de bureau, ne l'a pas lu. | ||
| 23 | + | ||
| 24 | +```bash | ||
| 25 | +source ~/.bashrc | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +Sous Windows, lancez plutôt l'installeur PowerShell depuis https://www.moonbitlang.com/download. Tout ce qui suit s'applique tel quel une fois qu'il a terminé. | ||
| 29 | + | ||
| 30 | +## Le vérifier | ||
| 31 | + | ||
| 32 | +```bash | ||
| 33 | +moon version --all | ||
| 34 | +``` | ||
| 35 | + | ||
| 36 | +Vous devriez voir trois lignes, chacune avec son chemin : | ||
| 37 | + | ||
| 38 | +``` | ||
| 39 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | ||
| 40 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | ||
| 41 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +Le serveur de langage est un quatrième binaire dans le même dossier, et il vaut la peine d'être interrogé séparément, parce que c'est celui dont l'éditeur a besoin : | ||
| 45 | + | ||
| 46 | +```bash | ||
| 47 | +moon-lsp --version | ||
| 48 | +``` | ||
| 49 | + | ||
| 50 | +``` | ||
| 51 | +v0.10.12+1634b282e (2026-09-07) | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +## Vérifier que l'éditeur le trouve | ||
| 55 | + | ||
| 56 | +Ouvrez n'importe quel fichier d'un projet MoonBit et lisez l'extrémité droite de la barre d'état : | ||
| 57 | + | ||
| 58 | +``` | ||
| 59 | + F1 Describe F2 Save F3 Open F6 Window F10 Menu 1:1 LSP: ready | ||
| 60 | +``` | ||
| 61 | + | ||
| 62 | +`LSP: ready` signifie que le serveur a démarré. `LSP: no moon-lsp — curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash` signifie qu'il n'a pas été trouvé, et le message est la commande à lancer. | ||
| 63 | + | ||
| 64 | +**Turbo MoonBit cherche à trois endroits, dans cet ordre** : votre `PATH`, puis `$MOON_HOME/bin` si `MOON_HOME` est défini, puis `~/.moon/bin`. L'éditeur trouve donc une chaîne d'outils installée normalement même depuis un shell qui n'a jamais lu le profil que l'installeur a modifié — c'est précisément le cas qui, autrement, ressemble à un serveur en panne. | ||
| 65 | + | ||
| 66 | +## Variantes | ||
| 67 | + | ||
| 68 | +- **Vous installez vos chaînes d'outils ailleurs.** Définissez `MOON_HOME` avant de lancer l'installeur ; il en tient compte, et l'éditeur aussi. | ||
| 69 | +- **Vous avez déjà `moon` mais pas de complétion.** Vérifiez `moon-lsp --version` spécifiquement. Une chaîne dépaquetée à la main, ou une mise à jour partielle, peut laisser `moon` en état de marche et `moon-lsp` absent. | ||
| 70 | +- **Vous voulez mettre à jour.** `moon upgrade` remplace la chaîne sur place ; `moon upgrade --dev` prend la version de développement. Ni l'un ni l'autre ne touche à `MOON_HOME` ni à votre `PATH`. | ||
| 71 | +- **Vous installez pour de l'intégration continue, ou dans une image.** L'installeur est un script shell ordinaire et n'a pas d'option qui vaille la peine ; épingler une version veut dire récupérer une release depuis https://www.moonbitlang.com/download plutôt que de l'utiliser. | ||
| 72 | +- **Vous voulez être sûr que l'éditeur ne le trouve pas simplement via le `PATH`.** Lancez-le avec un environnement réduit — `env PATH=/usr/bin:/bin turbo-moonbit main.mbt` — et la barre d'état devrait toujours dire `LSP: ready`, depuis `~/.moon/bin`. | ||
| 73 | + | ||
| 74 | +## À quoi sert chaque binaire | ||
| 75 | + | ||
| 76 | +| Binaire | Ce que l'éditeur en fait | | ||
| 77 | +| --- | --- | | ||
| 78 | +| `moon-lsp` | Complétion, survol, définitions, références, symboles et marques d'erreur dans la gouttière | | ||
| 79 | +| `moon` | Toutes les commandes du menu MoonBit — et `moon-lsp` le lance aussi, pour savoir ce que contient un projet | | ||
| 80 | +| `moonc` | Le compilateur, appelé par `moon` | | ||
| 81 | +| `moonrun` | Exécute la sortie WebAssembly, appelé par `moon run` | | ||
| 82 | + | ||
| 83 | +`moon-lsp` seul ne suffit pas : il détermine le projet en lançant `moon`, si bien qu'une machine ayant le serveur mais pas le système de construction obtient un serveur qui démarre, qui est trouvé, et qui ne sait ensuite rien d'aucun fichier. `scripts/install.sh` vérifie exactement cela et le dit. | ||
| 84 | + | ||
| 85 | +## Voir aussi | ||
| 86 | + | ||
| 87 | +- [Activer la complétion](enable-completion.md) — que faire quand le serveur est installé et ne dit toujours rien | ||
| 88 | +- [Lancer les commandes moon depuis l'éditeur](run-moon-commands.md) — le menu MoonBit | ||
| 89 | +- [Coloration et complétion](../explanation/colouring-and-completion.md) — pourquoi l'éditeur a besoin d'un serveur | ||
added
docs/fr/how-to/install.md +90 -0 | new file mode 100644 | ||
| @@ -0,0 +1,90 @@ | ||
| 1 | +# Installer et compiler Turbo MoonBit | |
| 2 | + | |
| 3 | +Ce guide montre comment obtenir un binaire `turbo-moonbit` 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-moonbit.git | |
| 9 | +cd turbo-moonbit | |
| 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 `moon-lsp` 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 MoonBit : | |
| 16 | + | |
| 17 | +```bash | |
| 18 | +turbo-moonbit main.mbt | |
| 19 | +``` | |
| 20 | + | |
| 21 | +### Options | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +scripts/install.sh --prefix ~/bin # installer ailleurs | |
| 25 | +scripts/install.sh --with-moon-lsp # 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-moonbit main.mbt | |
| 37 | +``` | |
| 38 | + | |
| 39 | +## Depuis le proxy de modules, sans clone | |
| 40 | + | |
| 41 | +```bash | |
| 42 | +go install rickub.com/turbo-editors/turbo-moonbit@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-moonbit -version | |
| 55 | +turbo-moonbit -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-moonbit@latest main.mbt` | |
| 63 | +- **Vous voulez le binaire à un endroit précis** : `go build -o /usr/local/bin/turbo-moonbit .` | |
| 64 | +- **Votre terminal ne gère pas les couleurs 24 bits** : utilisez `turbo-moonbit -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 `moon.mod` : 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 MoonBit 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 MoonBit](enable-completion.md) | |
| 89 | +- Une première session guidée : [Votre premier programme MoonBit dans Turbo MoonBit](../tutorials/getting-started.md) | |
| 90 | +- Des projets pour l'essayer : [les démos](../../../demos/) | |
| new file mode 100644 | |||
| @@ -0,0 +1,90 @@ | |||
| 1 | +# Installer et compiler Turbo MoonBit | ||
| 2 | + | ||
| 3 | +Ce guide montre comment obtenir un binaire `turbo-moonbit` 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-moonbit.git | ||
| 9 | +cd turbo-moonbit | ||
| 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 `moon-lsp` 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 MoonBit : | ||
| 16 | + | ||
| 17 | +```bash | ||
| 18 | +turbo-moonbit main.mbt | ||
| 19 | +``` | ||
| 20 | + | ||
| 21 | +### Options | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +scripts/install.sh --prefix ~/bin # installer ailleurs | ||
| 25 | +scripts/install.sh --with-moon-lsp # 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-moonbit main.mbt | ||
| 37 | +``` | ||
| 38 | + | ||
| 39 | +## Depuis le proxy de modules, sans clone | ||
| 40 | + | ||
| 41 | +```bash | ||
| 42 | +go install rickub.com/turbo-editors/turbo-moonbit@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-moonbit -version | ||
| 55 | +turbo-moonbit -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-moonbit@latest main.mbt` | ||
| 63 | +- **Vous voulez le binaire à un endroit précis** : `go build -o /usr/local/bin/turbo-moonbit .` | ||
| 64 | +- **Votre terminal ne gère pas les couleurs 24 bits** : utilisez `turbo-moonbit -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 `moon.mod` : 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 MoonBit 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 MoonBit](enable-completion.md) | ||
| 89 | +- Une première session guidée : [Votre premier programme MoonBit dans Turbo MoonBit](../tutorials/getting-started.md) | ||
| 90 | +- Des projets pour l'essayer : [les démos](../../../demos/) | ||
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-moonbit -version | |
| 31 | +``` | |
| 32 | + | |
| 33 | +``` | |
| 34 | +Turbo MoonBit 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 MoonBit 0.2.0 | |
| 45 | + | |
| 46 | +A Turbo C-style editor for MoonBit, | |
| 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 MoonBit" | |
| 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_MOONBIT_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-moonbit@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 `moon 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-moonbit/internal/version.stamp=v0.2.0'" -o bin/turbo-moonbit . | |
| 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 MoonBit](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-moonbit -version | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +``` | ||
| 34 | +Turbo MoonBit 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 MoonBit 0.2.0 | ||
| 45 | + | ||
| 46 | +A Turbo C-style editor for MoonBit, | ||
| 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 MoonBit" | ||
| 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_MOONBIT_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-moonbit@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 `moon 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-moonbit/internal/version.stamp=v0.2.0'" -o bin/turbo-moonbit . | ||
| 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 MoonBit](install.md) | ||
added
docs/fr/how-to/run-moon-commands.md +214 -0 | new file mode 100644 | ||
| @@ -0,0 +1,214 @@ | ||
| 1 | +# Lancer les commandes moon depuis l'éditeur | |
| 2 | + | |
| 3 | +Ce guide montre comment formater, vérifier, compiler, tester et exécuter votre projet sans quitter Turbo MoonBit. Il suppose l'éditeur installé et un projet MoonBit sous la main. | |
| 4 | + | |
| 5 | +## Obtenir un fichier de départ | |
| 6 | + | |
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **MoonBit ▸ Create tools file** (`Alt-M`, puis `C`). | |
| 8 | + | |
| 9 | +Cela écrit `.turbo-moonbit/tools.toml` avec les cinq commandes qu'un projet MoonBit passe avant de commiter, et l'ouvre : | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[tool]] | |
| 13 | +name = "~F~ormat" | |
| 14 | +command = "moon fmt" | |
| 15 | +output = "popup" | |
| 16 | + | |
| 17 | +[[tool]] | |
| 18 | +name = "~T~est" | |
| 19 | +command = "moon test" | |
| 20 | +output = "popup" | |
| 21 | + | |
| 22 | +[[tool]] | |
| 23 | +name = "~R~un" | |
| 24 | +command = "moon 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 **MoonBit**, 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-M`, 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 | +┌──────────── moon check — exit 1 ────────────┐ | |
| 40 | +│ main.mbt: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-moonbit/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 = "moon fmt && moon check && moon test" | |
| 96 | +output = "popup" | |
| 97 | + | |
| 98 | +[[tool]] | |
| 99 | +name = "~M~ettre à jour" | |
| 100 | +command = "moon update" | |
| 101 | +output = "popup" | |
| 102 | + | |
| 103 | +[[tool]] | |
| 104 | +name = "Cover~a~ge" | |
| 105 | +command = "moon test --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 MoonBit n'a rien à faire dans le menu MoonBit. 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 MoonBit 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 MoonBit, 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 ne compilez que pour un seul backend.** Remplacez `moon build --target {{…}}` par `moon build --target js`, et la boîte cesse d'apparaître. Le paramètre est là parce qu'un fichier de départ ne peut pas savoir lequel de `wasm`, `wasm-gc`, `js`, `native` et `llvm` un projet veut. | |
| 148 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** Les commandes s'y exécutent. `moon` cherche `moon.mod` en remontant, donc la plupart fonctionnent quand même — mais dans un espace de travail `moon.work`, les commandes en `--target all` veulent la racine de l'espace de travail : lancez depuis là. | |
| 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 = "moon new {{chemin 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 = "moon test {{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/moonbit-tools.md) | |
| 213 | +- Pourquoi chaque commande a sa fenêtre terminal, et pourquoi un fichier non modifié se recharge : [Outils MoonBit](../explanation/moonbit-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 moon depuis l'éditeur | ||
| 2 | + | ||
| 3 | +Ce guide montre comment formater, vérifier, compiler, tester et exécuter votre projet sans quitter Turbo MoonBit. Il suppose l'éditeur installé et un projet MoonBit sous la main. | ||
| 4 | + | ||
| 5 | +## Obtenir un fichier de départ | ||
| 6 | + | ||
| 7 | +Lancez l'éditeur **depuis le dossier du projet**, puis choisissez **MoonBit ▸ Create tools file** (`Alt-M`, puis `C`). | ||
| 8 | + | ||
| 9 | +Cela écrit `.turbo-moonbit/tools.toml` avec les cinq commandes qu'un projet MoonBit passe avant de commiter, et l'ouvre : | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[tool]] | ||
| 13 | +name = "~F~ormat" | ||
| 14 | +command = "moon fmt" | ||
| 15 | +output = "popup" | ||
| 16 | + | ||
| 17 | +[[tool]] | ||
| 18 | +name = "~T~est" | ||
| 19 | +command = "moon test" | ||
| 20 | +output = "popup" | ||
| 21 | + | ||
| 22 | +[[tool]] | ||
| 23 | +name = "~R~un" | ||
| 24 | +command = "moon 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 **MoonBit**, 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-M`, 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 | +┌──────────── moon check — exit 1 ────────────┐ | ||
| 40 | +│ main.mbt: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-moonbit/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 = "moon fmt && moon check && moon test" | ||
| 96 | +output = "popup" | ||
| 97 | + | ||
| 98 | +[[tool]] | ||
| 99 | +name = "~M~ettre à jour" | ||
| 100 | +command = "moon update" | ||
| 101 | +output = "popup" | ||
| 102 | + | ||
| 103 | +[[tool]] | ||
| 104 | +name = "Cover~a~ge" | ||
| 105 | +command = "moon test --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 MoonBit n'a rien à faire dans le menu MoonBit. 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 MoonBit 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 MoonBit, 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 ne compilez que pour un seul backend.** Remplacez `moon build --target {{…}}` par `moon build --target js`, et la boîte cesse d'apparaître. Le paramètre est là parce qu'un fichier de départ ne peut pas savoir lequel de `wasm`, `wasm-gc`, `js`, `native` et `llvm` un projet veut. | ||
| 148 | +- **Vous avez lancé l'éditeur depuis un sous-dossier.** Les commandes s'y exécutent. `moon` cherche `moon.mod` en remontant, donc la plupart fonctionnent quand même — mais dans un espace de travail `moon.work`, les commandes en `--target all` veulent la racine de l'espace de travail : lancez depuis là. | ||
| 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 = "moon new {{chemin 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 = "moon test {{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/moonbit-tools.md) | ||
| 213 | +- Pourquoi chaque commande a sa fenêtre terminal, et pourquoi un fichier non modifié se recharge : [Outils MoonBit](../explanation/moonbit-tools.md) | ||
| 214 | +- Les fenêtres dans lesquelles les commandes tournent : [Fenêtres terminal](../reference/terminal.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 MoonBit. 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 `moon test` 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 `moon-lsp` 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 `moon-lsp` 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 MoonBit 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 MoonBit. 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 `moon test` 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 `moon-lsp` 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 `moon-lsp` 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 MoonBit 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/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 MoonBit 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 MoonBit est déjà lancé dans un projet. | |
| 4 | + | |
| 5 | +Turbo MoonBit 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-moonbit/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-moonbit/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-moonbit/` est un endroit raisonnable pour le garder afin qu'il voyage avec le projet. Pour `docker agent`, l'enregistrer sous `.turbo-moonbit/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 | +│ ```moonbit │ | |
| 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 MoonBit est colorée comme du MoonBit, 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-moonbit/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 MoonBit 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 MoonBit est déjà lancé dans un projet. | ||
| 4 | + | ||
| 5 | +Turbo MoonBit 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-moonbit/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-moonbit/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-moonbit/` est un endroit raisonnable pour le garder afin qu'il voyage avec le projet. Pour `docker agent`, l'enregistrer sous `.turbo-moonbit/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 | +│ ```moonbit │ | ||
| 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 MoonBit est colorée comme du MoonBit, 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-moonbit/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 MoonBit 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 : `moon install` 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-moonbit` 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 MoonBit 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 : `moon install` 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-moonbit` 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 MoonBit 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-moonbit/snippets.toml`, rempli de quelques exemples travaillés, et l'ouvre — coloré, puisque Turbo MoonBit colore le TOML : | |
| 10 | + | |
| 11 | +```toml | |
| 12 | +[[snippet]] | |
| 13 | +name = "if err != nil" | |
| 14 | +group = "MoonBit" | |
| 15 | +languages = ["moonbit"] | |
| 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-moonbit/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 — `moonbit`, `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-moonbit` 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-moonbit` : [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 MoonBit 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-moonbit/snippets.toml`, rempli de quelques exemples travaillés, et l'ouvre — coloré, puisque Turbo MoonBit colore le TOML : | ||
| 10 | + | ||
| 11 | +```toml | ||
| 12 | +[[snippet]] | ||
| 13 | +name = "if err != nil" | ||
| 14 | +group = "MoonBit" | ||
| 15 | +languages = ["moonbit"] | ||
| 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-moonbit/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 — `moonbit`, `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-moonbit` 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-moonbit` : [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-moonbit -list-themes | |
| 9 | +``` | |
| 10 | + | |
| 11 | +La dernière ligne indique le répertoire — `~/.config/turbo-moonbit/themes` sous Linux, `~/Library/Application Support/turbo-moonbit/themes` sous macOS. Créez-le : | |
| 12 | + | |
| 13 | +```bash | |
| 14 | +mkdir -p ~/.config/turbo-moonbit/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-moonbit/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-moonbit -theme mine main.mbt | |
| 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 MoonBit retombe sur le thème par défaut plutôt que de refuser de démarrer. Pour savoir *pourquoi* : | |
| 49 | + | |
| 50 | +```bash | |
| 51 | +turbo-moonbit -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_MOONBIT_THEME_DIR=./mes-themes turbo-moonbit -theme mine main.mbt | |
| 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 MoonBit : 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-moonbit -list-themes | ||
| 9 | +``` | ||
| 10 | + | ||
| 11 | +La dernière ligne indique le répertoire — `~/.config/turbo-moonbit/themes` sous Linux, `~/Library/Application Support/turbo-moonbit/themes` sous macOS. Créez-le : | ||
| 12 | + | ||
| 13 | +```bash | ||
| 14 | +mkdir -p ~/.config/turbo-moonbit/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-moonbit/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-moonbit -theme mine main.mbt | ||
| 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 MoonBit retombe sur le thème par défaut plutôt que de refuser de démarrer. Pour savoir *pourquoi* : | ||
| 49 | + | ||
| 50 | +```bash | ||
| 51 | +turbo-moonbit -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_MOONBIT_THEME_DIR=./mes-themes turbo-moonbit -theme mine main.mbt | ||
| 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 MoonBit : 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 MoonBit 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-moonbit/acp.toml` | en premier | Les agents que vous voulez dans tous les projets | | |
| 10 | +| `<projet>/.turbo-moonbit/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_MOONBIT_DIR` remplace le dossier où le fichier utilisateur est cherché. Le fichier du projet est toujours `.turbo-moonbit/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-moonbit/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-moonbit/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 MoonBit 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 — `moonbit`, `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 MoonBit 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-moonbit/acp.toml` | en premier | Les agents que vous voulez dans tous les projets | | ||
| 10 | +| `<projet>/.turbo-moonbit/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_MOONBIT_DIR` remplace le dossier où le fichier utilisateur est cherché. Le fichier du projet est toujours `.turbo-moonbit/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-moonbit/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-moonbit/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 MoonBit 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 — `moonbit`, `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-moonbit`, de ses options et de l'environnement qu'elle lit. | |
| 4 | + | |
| 5 | +## Synopsis | |
| 6 | + | |
| 7 | +``` | |
| 8 | +turbo-moonbit [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 MoonBit <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_MOONBIT_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 moon-lsp | Consultées, dans cet ordre, quand `moon-lsp` n'est pas dans le `PATH`. | | |
| 30 | + | |
| 31 | +## Fichiers | |
| 32 | + | |
| 33 | +| Chemin | Rôle | | |
| 34 | +| --- | --- | | |
| 35 | +| `$TURBO_MOONBIT_THEME_DIR/*.toml` | Thèmes utilisateur, quand la variable est définie. | | |
| 36 | +| `./.turbo-moonbit/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-moonbit/themes/*.toml` | Thèmes utilisateur sous Linux (`os.UserConfigDir`). | | |
| 38 | +| `~/Library/Application Support/turbo-moonbit/themes/*.toml` | Thèmes utilisateur sous macOS. | | |
| 39 | +| `<module>/moon.mod` | 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` | `go test ./...` | | |
| 56 | +| `make test-verbose` | `go test -v ./...` | | |
| 57 | +| `make cover` | `go test -cover ./...` | | |
| 58 | +| `make build` | `go build -o bin/turbo-moonbit .` | | |
| 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-moonbit x.go` | | |
| 62 | +| `make fmt` | `go fmt ./...` | | |
| 63 | +| `make vet` | `go vet ./...` | | |
| 64 | +| `make check` | `fmt`, puis `vet`, puis `test` | | |
| 65 | +| `make clean` | Supprime `bin/` | | |
| 66 | + | |
| 67 | +## Exemples | |
| 68 | + | |
| 69 | +```bash | |
| 70 | +turbo-moonbit # une fenêtre vide | |
| 71 | +turbo-moonbit main.mbt moon.mod # deux fenêtres | |
| 72 | +turbo-moonbit -theme turbo-dark main.mbt # un autre thème | |
| 73 | +turbo-moonbit -no-lsp main.mbt # sans serveur de langage | |
| 74 | +turbo-moonbit -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-moon-lsp` | Installer aussi `moon-lsp`, s'il n'est pas déjà présent. | | |
| 85 | +| `--uninstall` | Retirer un `turbo-moonbit` 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-moonbit: opening the terminal: …` | tcell n'a pas pu ouvrir le terminal ; en général `TERM` est absent ou inconnu. | | |
| 98 | +| `turbo-moonbit: 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-moonbit`, de ses options et de l'environnement qu'elle lit. | ||
| 4 | + | ||
| 5 | +## Synopsis | ||
| 6 | + | ||
| 7 | +``` | ||
| 8 | +turbo-moonbit [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 MoonBit <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_MOONBIT_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 moon-lsp | Consultées, dans cet ordre, quand `moon-lsp` n'est pas dans le `PATH`. | | ||
| 30 | + | ||
| 31 | +## Fichiers | ||
| 32 | + | ||
| 33 | +| Chemin | Rôle | | ||
| 34 | +| --- | --- | | ||
| 35 | +| `$TURBO_MOONBIT_THEME_DIR/*.toml` | Thèmes utilisateur, quand la variable est définie. | | ||
| 36 | +| `./.turbo-moonbit/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-moonbit/themes/*.toml` | Thèmes utilisateur sous Linux (`os.UserConfigDir`). | | ||
| 38 | +| `~/Library/Application Support/turbo-moonbit/themes/*.toml` | Thèmes utilisateur sous macOS. | | ||
| 39 | +| `<module>/moon.mod` | 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` | `go test ./...` | | ||
| 56 | +| `make test-verbose` | `go test -v ./...` | | ||
| 57 | +| `make cover` | `go test -cover ./...` | | ||
| 58 | +| `make build` | `go build -o bin/turbo-moonbit .` | | ||
| 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-moonbit x.go` | | ||
| 62 | +| `make fmt` | `go fmt ./...` | | ||
| 63 | +| `make vet` | `go vet ./...` | | ||
| 64 | +| `make check` | `fmt`, puis `vet`, puis `test` | | ||
| 65 | +| `make clean` | Supprime `bin/` | | ||
| 66 | + | ||
| 67 | +## Exemples | ||
| 68 | + | ||
| 69 | +```bash | ||
| 70 | +turbo-moonbit # une fenêtre vide | ||
| 71 | +turbo-moonbit main.mbt moon.mod # deux fenêtres | ||
| 72 | +turbo-moonbit -theme turbo-dark main.mbt # un autre thème | ||
| 73 | +turbo-moonbit -no-lsp main.mbt # sans serveur de langage | ||
| 74 | +turbo-moonbit -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-moon-lsp` | Installer aussi `moon-lsp`, s'il n'est pas déjà présent. | | ||
| 85 | +| `--uninstall` | Retirer un `turbo-moonbit` 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-moonbit: opening the terminal: …` | tcell n'a pas pu ouvrir le terminal ; en général `TERM` est absent ou inconnu. | | ||
| 98 | +| `turbo-moonbit: 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 MoonBit 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-M` | Ouvrir le menu MoonBit | | |
| 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 MoonBit](moonbit-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 MoonBit 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-M` | Ouvrir le menu MoonBit | | ||
| 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 MoonBit](moonbit-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 +296 -0 | new file mode 100644 | ||
| @@ -0,0 +1,296 @@ | ||
| 1 | +# Référence : langages colorés | |
| 2 | + | |
| 3 | +> Description neutre des fichiers que Turbo MoonBit 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 | +| `.mbt`, `.mbti`, `.mbtx` | MoonBit | | |
| 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 : `README.mbt.md` est du Markdown, et `main.mbt.backup` n'est pas du MoonBit. | |
| 22 | + | |
| 23 | +Un fichier dont l'extension ne décide de rien est ensuite cherché par son **nom**. Seuls les fichiers dépourvus d'extension utile en ont besoin : | |
| 24 | + | |
| 25 | +| Nom | Langage | | |
| 26 | +| --- | --- | | |
| 27 | +| `Dockerfile`, `Containerfile` | Dockerfile | | |
| 28 | + | |
| 29 | +Un nom correspond soit en entier, soit sur la partie qui précède le premier point, sans tenir compte de la casse — `Dockerfile`, `dockerfile` et `Dockerfile.dev` sont donc tous reconnus, tandis que `Dockerfile.md` est du Markdown, puisque l'extension est consultée d'abord. | |
| 30 | + | |
| 31 | +`moon.mod`, `moon.pkg` et `moon.work` ne sont **pas** dans cette table. Ce sont les fichiers du DSL de configuration de MoonBit plutôt que du MoonBit, et leurs anciennes formes JSON — `moon.mod.json`, `moon.pkg.json` — ne sont pas non plus du JSON que cet éditeur colore. Les cinq s'ouvrent en texte brut. | |
| 32 | + | |
| 33 | +Un fichier qu'aucune des deux tables ne réclame est lu par sa **première ligne**. Un shebang nommant un shell — `sh`, `bash`, `zsh`, `dash` ou `ksh` — en fait un script shell, et l'interpréteur est reconnu comme élément de chemin ou comme argument de `env`. C'est ce qui colore un script dans un répertoire `bin`, un hook git ou un `configure`. | |
| 34 | + | |
| 35 | +**Aucun shebang ne fait d'un fichier du MoonBit.** Le langage n'a pas de ligne d'interpréteur : un fichier commençant par `#!` serait lu comme un attribut nommé `!` et échouerait. Un fichier sans extension n'est pas du MoonBit, et prétendre le contraire retirerait un script shell au scanner qui sait réellement le colorer. | |
| 36 | + | |
| 37 | +| Première ligne | Résultat | | |
| 38 | +| --- | --- | | |
| 39 | +| `#!/bin/sh` | Shell | | |
| 40 | +| `#!/usr/bin/env bash` | Shell | | |
| 41 | +| `#!/usr/bin/env -S bash -e` | Shell | | |
| 42 | +| `#!/usr/bin/env moon` | Non coloré | | |
| 43 | +| `#!/usr/bin/env node` | Non coloré | | |
| 44 | +| Tout ce qui ne commence pas par `#!` | Non coloré | | |
| 45 | + | |
| 46 | +L'ordre est fixe — extension, puis nom, puis première ligne — et le premier qui décide l'emporte. | |
| 47 | + | |
| 48 | +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, ce n'est simplement pas coloré. | |
| 49 | + | |
| 50 | +## Classes | |
| 51 | + | |
| 52 | +Chaque scanner produit le même vocabulaire de classes, et chacune correspond à une clé de thème. | |
| 53 | + | |
| 54 | +| Classe | Clé de thème | Produite par | | |
| 55 | +| --- | --- | --- | | |
| 56 | +| `identifier` | `syntax.identifier` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 57 | +| `keyword` | `syntax.keyword` | MoonBit, JavaScript, shell, HTML (doctype), XML, Dockerfile | | |
| 58 | +| `type` | `syntax.type` | MoonBit (tout nom capitalisé, et les qualificateurs de paquet), TOML (en-têtes de table), YAML (tags) | | |
| 59 | +| `builtin` | `syntax.builtin` | MoonBit (le prélude), JavaScript, shell (primitives et expansions), YAML (ancres et alias), Dockerfile (variables) | | |
| 60 | +| `constant` | `syntax.constant` | MoonBit, TOML, JavaScript, shell, YAML, HTML et XML (entités) | | |
| 61 | +| `function` | `syntax.function` | MoonBit, JavaScript, shell (la commande) | | |
| 62 | +| `string` | `syntax.string` | tous | | |
| 63 | +| `char` | `syntax.char` | MoonBit (`'c'` et `b'c'`) | | |
| 64 | +| `number` | `syntax.number` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | |
| 65 | +| `comment` | `syntax.comment` | MoonBit, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | |
| 66 | +| `operator` | `syntax.operator` | MoonBit, TOML, JavaScript, shell, HTML, YAML (en-têtes de scalaire de bloc), XML, Dockerfile | | |
| 67 | +| `punctuation` | `syntax.punctuation` | MoonBit, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | |
| 68 | +| `heading` | `syntax.heading` | Markdown | | |
| 69 | +| `tag` | `syntax.tag` | HTML, XML | | |
| 70 | +| `attribute` | `syntax.attribute` | MoonBit (attributs et arguments étiquetés), HTML, XML, Dockerfile (options) | | |
| 71 | +| `emphasis` | `syntax.emphasis` | Markdown | | |
| 72 | +| `link` | `syntax.link` | Markdown | | |
| 73 | + | |
| 74 | +Dans le seul thème `turbo-classic`, `syntax.attribute` et `syntax.identifier` sont tous deux en jaune simple : un attribut ou une étiquette MoonBit ne s'y distingue donc pas d'un nom ordinaire. Les sept autres thèmes leur donnent des couleurs différentes. Voir [comment écrire son propre thème](../how-to/write-a-theme.md) pour changer cela. | |
| 75 | + | |
| 76 | +## MoonBit | |
| 77 | + | |
| 78 | +Écrit à la main, dans `internal/moonbitlang`. **Rien ne franchit une fin de ligne**, et c'est une propriété du langage plutôt qu'une simplification : MoonBit n'a pas de commentaire de bloc, un saut de ligne avant le guillemet fermant est une erreur de *littéral non terminé*, une chaîne multiligne est une suite de lignes `#|` ou `$|` complètes chacune en elle-même, et un attribut tient explicitement sur une ligne. Un guillemet égaré colore donc jusqu'à la fin de sa ligne, et la ligne suivante est de nouveau du code. | |
| 79 | + | |
| 80 | +| Reconnu | Comme | | |
| 81 | +| --- | --- | | |
| 82 | +| `and`, `as`, `async`, `break`, `catch`, `const`, `continue`, `declare`, `defer`, `derive`, `else`, `enum`, `enumview`, `extend`, `extenum`, `extern`, `fn`, `for`, `guard`, `if`, `impl`, `import`, `in`, `is`, `let`, `letrec`, `lexscan`, `loop`, `match`, `mut`, `nobreak`, `nocancel`, `noraise`, `package`, `priv`, `proof_assert`, `proof_let`, `pub`, `raise`, `readonly`, `return`, `struct`, `suberror`, `test`, `throw`, `trait`, `try`, `type`, `using`, `where`, `while`, `with` | mot-clé | | |
| 83 | +| `try!` et `guard!`, point d'exclamation compris | mot-clé | | |
| 84 | +| `true`, `false`, `None`, `Some`, `Ok`, `Err` | constante | | |
| 85 | +| tout nom commençant par une majuscule ASCII — `Int`, `StringBuilder`, `Shape`, `Circle` | type | | |
| 86 | +| `println`, `abort`, `panic`, `fail`, `ignore`, `inspect`, `debug`, `repr`, `hash`, `compare`, `null`, `assert_eq`, `assert_not_eq`, `assert_true`, `assert_false`, `debug_assert`, `debug_inspect`, `json_inspect`, `physical_equal` | primitive | | |
| 87 | +| tout autre nom en minuscules immédiatement suivi de `(` | fonction | | |
| 88 | +| `"…"`, `b"…"`, `re"…"` | chaîne | | |
| 89 | +| `'c'`, `b'c'` | caractère | | |
| 90 | +| `#\|` et `$\|` | le préfixe de deux caractères en ponctuation, le reste de la ligne en chaîne | | |
| 91 | +| `42`, `1_000`, `0xFF_FF`, `0o17`, `0b1010`, `1.5`, `1.`, `1.5e-3`, `0x1.8p3F`, `42U`, `42L`, `42UL`, `42N`, `1.0F` | nombre | | |
| 92 | +| `//` et `///` jusqu'à la fin de la ligne | commentaire | | |
| 93 | +| `#deprecated("…")`, `#external`, `#custom.attribute(key="v")` — la ligne entière | attribut | | |
| 94 | +| `name~` dans un argument étiqueté, tilde compris | attribut | | |
| 95 | +| `@json`, `@moonbitlang/core/builtin`, `@my-pkg` — le `@` compris, en une seule étendue | type | | |
| 96 | +| `.0` dans un accès de tuple | le point en ponctuation, les chiffres en nombre | | |
| 97 | +| `..`, `..=`, `..<`, `...` | opérateur | | |
| 98 | +| suites de `+-*/%=<>!&\|^~?:` | opérateur | | |
| 99 | +| `()[]{},;.` | ponctuation | | |
| 100 | + | |
| 101 | +**Il n'y a ici aucune table des types intégrés, et il n'en faut aucune.** La casse des identifiants de MoonBit est une règle *lexicale* et non une convention : la grammaire dit qu'un `uident` « commence par une majuscule ASCII », et seuls un type, un trait ou un constructeur d'énumération peuvent s'écrire ainsi. `Int`, `StringBuilder` et un type écrit ce matin sont tous colorés par la même ligne de code. Tous les autres scanners de cette famille ont besoin d'une table ici ; celui-ci non. | |
| 102 | + | |
| 103 | +**Un entier se termine avant `..`.** La grammaire est explicite — « avant `..`, l'entier se termine d'abord, donc `1..=2` commence par `1` puis `..=` » — un point ne fait donc partie d'un nombre que si un second ne le suit pas. Sans cette règle, `1..=2` se lit comme le double `1.` puis `.=2`, et tous les intervalles du fichier sont mal colorés. | |
| 104 | + | |
| 105 | +**Le suffixe d'un nombre est en majuscules ou ce n'est pas un suffixe.** `42UL` est un seul nombre ; `42u` est le nombre `42` suivi du nom `u`, ce que voit aussi le compilateur. | |
| 106 | + | |
| 107 | +**Un attribut prend la ligne entière.** La grammaire lui donne tout ce qui suit le nom pointé : « tout ce qui va jusqu'au saut de ligne suivant est la charge utile brute ». Colorer moins que la ligne inventerait une structure que le lexeur n'a pas. | |
| 108 | + | |
| 109 | +**`#|` et `#deprecated` se distinguent par le caractère qui suit le `#`.** Le nom d'un attribut doit commencer par une lettre ou un tiret bas ; une ligne de chaîne multiligne a une barre verticale à cette place. | |
| 110 | + | |
| 111 | +**Un commentaire de documentation est coloré comme n'importe quel autre commentaire.** `///`, `///|` et `//` aboutissent tous à `syntax.comment`, parce que l'ensemble des classes de turbo-core est délibérément fermé — c'est ce qui permet à un seul thème de colorer tous les langages qu'un éditeur apprendra jamais. | |
| 112 | + | |
| 113 | +**Un nom après un point n'est jamais un mot-clé.** Les identifiants pointés de MoonBit « suivent les règles de casse des identifiants sans consulter la table des mots-clés, si bien que `.if` est valide » — un enregistrement avec un champ nommé `type` est du MoonBit ordinaire. | |
| 114 | + | |
| 115 | +**`package` est aussi coloré comme mot-clé dans un fichier `.mbt`**, alors qu'il n'y est qu'un mot *réservé*. C'est un vrai mot-clé dans les fichiers d'interface `.mbti` que cet éditeur colore également, et dans un `.mbt` la couleur dit exactement ce que le compilateur s'apprête à dire : ce mot ne vous appartient pas. Le reste de la liste réservée — `move`, `ref`, `static`, `unsafe`, `await` et les quarante autres — est délibérément laissé tranquille, parce que ce sont réellement des noms utilisables. | |
| 116 | + | |
| 117 | +**Un tilde collé à la fin d'un nom en minuscules est une étiquette**, et collé à autre chose il ne l'est pas : la grammaire dit que « les identifiants en majuscules ASCII et les mots-clés ne peuvent pas former d'étiquette », donc `Foo~` est un type suivi d'un tilde. | |
| 118 | + | |
| 119 | +**Non reconnu**, chaque cas pour une raison énoncée : | |
| 120 | + | |
| 121 | +| Non reconnu | Parce que | | |
| 122 | +| --- | --- | | |
| 123 | +| L'expression à l'intérieur de `\{…}` | La grammaire la fait aller jusqu'à « l'accolade correspondante », les accolades des littéraux imbriqués ne comptant pas : trouver la fin demande l'analyseur syntaxique. `"a \{b} c"` est donc une seule étendue de chaîne, d'accolade à accolade. **C'est une chaîne imbriquée dans une interpolation qui arrête cela** : le scanner prend le premier guillemet non échappé pour le fermant, si bien que `"a \{f("x")} c"` se lit comme chaîne, puis `x` en identifiant, puis chaîne. Les étendues restent ordonnées et ne se chevauchent jamais ; le coût est une couleur fausse à l'intérieur d'un littéral imbriqué, plus rare que les bugs de comptage d'accolades qu'entraînerait l'alternative | | |
| 124 | +| Un constructeur d'énumération à vous, autrement que comme un type | Rien dans la syntaxe ne sépare `Circle(1.0)` d'un type appliqué à des arguments ; inventer une séparation reviendrait à se tromper dans les deux sens au lieu d'un | | |
| 125 | +| `.5` comme nombre | MoonBit exige un chiffre avant le point : un point initial est donc un accès de tuple ou un identifiant pointé, jamais un littéral | | |
| 126 | +| Un mot réservé comme mot-clé | `move`, `ref` et les autres sont des identifiants dont le compilateur se contente d'avertir, et les colorer dirait au lecteur qu'il ne peut pas écrire `let ref = 1` alors qu'il le peut | | |
| 127 | +| Un identifiant contenant des lettres non ASCII | MoonBit accepte le CJK et plusieurs autres plages dans un nom ; les prédicats de caractères sur lesquels ce scanner est bâti sont ASCII, un tel nom est donc franchi sans couleur plutôt que deviné | | |
| 128 | +| `.mbt.md` comme du MoonBit | C'est un document Markdown contenant du MoonBit dans ses blocs. Son extension est `.md`, et c'est Markdown qui le colore | | |
| 129 | +| 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) | | |
| 130 | + | |
| 131 | +## TOML | |
| 132 | + | |
| 133 | +| Reconnu | Comme | | |
| 134 | +| --- | --- | | |
| 135 | +| `# commentaire` | comment | | |
| 136 | +| `[table]`, `[[array]]` | le nom en type, les crochets en punctuation | | |
| 137 | +| `clé =` | identifier, puis operator | | |
| 138 | +| `"basique"`, `'littérale'`, `"""multi-ligne"""`, `'''multi-ligne'''` | string | | |
| 139 | +| `true`, `false` | constant | | |
| 140 | +| nombres, dates, heures, `inf`, `nan` | number | | |
| 141 | + | |
| 142 | +## YAML | |
| 143 | + | |
| 144 | +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. | |
| 145 | + | |
| 146 | +| Reconnu | Comme | | |
| 147 | +| --- | --- | | |
| 148 | +| `# commentaire` | commentaire | | |
| 149 | +| `clé:` suivie d'une espace ou de la fin de ligne | la clé en identifiant, le deux-points en ponctuation | | |
| 150 | +| `"entre guillemets": 1`, `'apostrophes': 1` | la clé citée en identifiant | | |
| 151 | +| `- ` ouvrant une entrée de séquence | ponctuation | | |
| 152 | +| `"…"`, `'…'` | chaîne | | |
| 153 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constante, quelle que soit la casse | | |
| 154 | +| nombres, dates et heures écrits sans guillemets | nombre | | |
| 155 | +| `&ancre`, `*alias` | builtin | | |
| 156 | +| `!!str`, `!Custom` | type | | |
| 157 | +| `---`, `...` | toute la ligne en ponctuation | | |
| 158 | +| `{`, `}`, `[`, `]`, `,` | ponctuation | | |
| 159 | +| `\|`, `>`, avec leurs indicateurs de coupe et d'indentation | l'en-tête en opérateur, le corps en chaîne | | |
| 160 | + | |
| 161 | +**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. | |
| 162 | + | |
| 163 | +**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. | |
| 164 | + | |
| 165 | +**Un `#` a besoin d'une espace devant lui pour ouvrir un commentaire**, si bien que `colour: ff#00aa` est un seul scalaire. | |
| 166 | + | |
| 167 | +| Non reconnu | Parce que | | |
| 168 | +| --- | --- | | |
| 169 | +| 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é | | |
| 170 | +| 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 | | |
| 171 | +| 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 | | |
| 172 | + | |
| 173 | +## Markdown | |
| 174 | + | |
| 175 | +| Reconnu | Comme | | |
| 176 | +| --- | --- | | |
| 177 | +| `# Titre` … `###### Titre` | toute la ligne en heading | | |
| 178 | +| `**gras**`, `__gras__`, `*italique*`, `_italique_` | emphasis | | |
| 179 | +| `` `code` `` | string | | |
| 180 | +| `[texte](cible)`, `` | l'ensemble en link | | |
| 181 | +| `- `, `* `, `+ `, `1. `, `1) ` | le marqueur en punctuation | | |
| 182 | +| `>` | punctuation | | |
| 183 | +| `---`, `***`, `___` | punctuation | | |
| 184 | +| clôtures ` ``` ` et `~~~` | tout le bloc, lignes d'ouverture et de fermeture comprises, en string | | |
| 185 | + | |
| 186 | +Un bloc clôturé est **d'une seule couleur quel que soit le langage annoncé** : ```` ```moonbit ```` ne colore pas son contenu en MoonBit. 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. | |
| 187 | + | |
| 188 | +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. | |
| 189 | + | |
| 190 | +## JavaScript | |
| 191 | + | |
| 192 | +| Reconnu | Comme | | |
| 193 | +| --- | --- | | |
| 194 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | |
| 195 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | |
| 196 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | |
| 197 | +| un nom immédiatement suivi de `(` | function | | |
| 198 | +| `"…"`, `'…'` | string | | |
| 199 | +| `` `…` ``, interpolations comprises, sur plusieurs lignes | string | | |
| 200 | +| `//` jusqu'à la fin de la ligne, `/* … */` sur plusieurs lignes | comment | | |
| 201 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | |
| 202 | +| suites de `+-*/%=<>!&|^~?:` | operator | | |
| 203 | +| `()[]{},;.` | punctuation | | |
| 204 | + | |
| 205 | +**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. | |
| 206 | + | |
| 207 | +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 MoonBit. | |
| 208 | + | |
| 209 | +## HTML | |
| 210 | + | |
| 211 | +| Reconnu | Comme | | |
| 212 | +| --- | --- | | |
| 213 | +| `<balise`, `</balise`, `>`, `/>` | tag | | |
| 214 | +| noms d'attributs, dont `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | |
| 215 | +| `=` | operator | | |
| 216 | +| `"…"`, `'…'` | string | | |
| 217 | +| `<!-- … -->`, sur plusieurs lignes | comment | | |
| 218 | +| `&`, `©` | constant | | |
| 219 | +| `<!DOCTYPE …>` et les autres déclarations | keyword | | |
| 220 | + | |
| 221 | +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. | |
| 222 | + | |
| 223 | +**Le contenu de `<script>` et de `<style>` n'est pas coloré** en JavaScript ni en CSS. | |
| 224 | + | |
| 225 | +## XML | |
| 226 | + | |
| 227 | +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. | |
| 228 | + | |
| 229 | +| Reconnu | Comme | | |
| 230 | +| --- | --- | | |
| 231 | +| `<?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 | | |
| 232 | +| `<!DOCTYPE …>` et les autres formes `<!` | mot-clé | | |
| 233 | +| `<!-- … -->`, sur plusieurs lignes | commentaire | | |
| 234 | +| `<![CDATA[ … ]]>`, sur plusieurs lignes | chaîne | | |
| 235 | +| `<balise`, `</balise`, `>`, `/>` | balise | | |
| 236 | +| `<ns:balise>`, `xsi:type` | le préfixe et le nom local en **un seul** segment | | |
| 237 | +| les noms d'attributs | attribut | | |
| 238 | +| `=` | opérateur | | |
| 239 | +| `"…"`, `'…'` | chaîne | | |
| 240 | +| `&`, `©` | constante | | |
| 241 | + | |
| 242 | +**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. | |
| 243 | + | |
| 244 | +**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. | |
| 245 | + | |
| 246 | +Le texte entre balises n'est pas coloré. | |
| 247 | + | |
| 248 | +## Shell | |
| 249 | + | |
| 250 | +S'applique indifféremment à `sh`, `bash` et `zsh` : les mots-clés reconnus sont ceux qu'ils partagent. | |
| 251 | + | |
| 252 | +| Reconnu | Comme | | |
| 253 | +| --- | --- | | |
| 254 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | |
| 255 | +| `true`, `false` | constant | | |
| 256 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | |
| 257 | +| `$NOM`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | |
| 258 | +| le **premier mot nu d'une ligne** | function | | |
| 259 | +| tout mot nu suivant, et `NOM` dans `NOM=valeur` | identifier | | |
| 260 | +| `'…'`, sans échappement ni expansion à l'intérieur | string | | |
| 261 | +| `"…"`, avec les expansions colorées comme telles | string | | |
| 262 | +| `#` jusqu'à la fin de la ligne | comment | | |
| 263 | + | |
| 264 | +`$(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. | |
| 265 | + | |
| 266 | +**Les heredocs ne sont pas reconnus.** `<<EOF` et le texte qui suit sont colorés comme du shell ordinaire. | |
| 267 | + | |
| 268 | +## Dockerfile | |
| 269 | + | |
| 270 | +| Reconnu | Comme | | |
| 271 | +| --- | --- | | |
| 272 | +| `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 | | |
| 273 | +| `AS`, `NONE` | mot-clé | | |
| 274 | +| `# commentaire`, y compris les directives `# syntax=` et `# escape=` | commentaire | | |
| 275 | +| `--from=builder`, `--chown=me:me` | le nom de l'option en attribut | | |
| 276 | +| `$NOM`, `${NOM}`, `${NOM:-defaut}` | builtin, en un seul segment jusqu'à l'accolade fermante | | |
| 277 | +| `"…"`, `'…'` | chaîne | | |
| 278 | +| un `\` final | opérateur | | |
| 279 | +| les nombres | nombre | | |
| 280 | +| chemins et références d'images — `/usr/local/bin`, `golang:1.26-alpine` | identifiant, en **un seul** segment | | |
| 281 | + | |
| 282 | +**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. | |
| 283 | + | |
| 284 | +**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. | |
| 285 | + | |
| 286 | +| Non reconnu | Parce que | | |
| 287 | +| --- | --- | | |
| 288 | +| 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 | | |
| 289 | +| Les heredocs dans un `RUN` | La même raison que pour l'analyseur shell | | |
| 290 | +| Quelle étape nomme un `--from` | Rien ici ne lit le reste du fichier | | |
| 291 | + | |
| 292 | +## Voir aussi | |
| 293 | + | |
| 294 | +- [Format des fichiers de thème](themes.md) — toutes les clés vers lesquelles ces classes se résolvent | |
| 295 | +- [Coloration et complétion](../explanation/colouring-and-completion.md) — pourquoi les scanners sont écrits ainsi | |
| 296 | +- [Écrire son propre thème](../how-to/write-a-theme.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,296 @@ | |||
| 1 | +# Référence : langages colorés | ||
| 2 | + | ||
| 3 | +> Description neutre des fichiers que Turbo MoonBit 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 | +| `.mbt`, `.mbti`, `.mbtx` | MoonBit | | ||
| 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 : `README.mbt.md` est du Markdown, et `main.mbt.backup` n'est pas du MoonBit. | ||
| 22 | + | ||
| 23 | +Un fichier dont l'extension ne décide de rien est ensuite cherché par son **nom**. Seuls les fichiers dépourvus d'extension utile en ont besoin : | ||
| 24 | + | ||
| 25 | +| Nom | Langage | | ||
| 26 | +| --- | --- | | ||
| 27 | +| `Dockerfile`, `Containerfile` | Dockerfile | | ||
| 28 | + | ||
| 29 | +Un nom correspond soit en entier, soit sur la partie qui précède le premier point, sans tenir compte de la casse — `Dockerfile`, `dockerfile` et `Dockerfile.dev` sont donc tous reconnus, tandis que `Dockerfile.md` est du Markdown, puisque l'extension est consultée d'abord. | ||
| 30 | + | ||
| 31 | +`moon.mod`, `moon.pkg` et `moon.work` ne sont **pas** dans cette table. Ce sont les fichiers du DSL de configuration de MoonBit plutôt que du MoonBit, et leurs anciennes formes JSON — `moon.mod.json`, `moon.pkg.json` — ne sont pas non plus du JSON que cet éditeur colore. Les cinq s'ouvrent en texte brut. | ||
| 32 | + | ||
| 33 | +Un fichier qu'aucune des deux tables ne réclame est lu par sa **première ligne**. Un shebang nommant un shell — `sh`, `bash`, `zsh`, `dash` ou `ksh` — en fait un script shell, et l'interpréteur est reconnu comme élément de chemin ou comme argument de `env`. C'est ce qui colore un script dans un répertoire `bin`, un hook git ou un `configure`. | ||
| 34 | + | ||
| 35 | +**Aucun shebang ne fait d'un fichier du MoonBit.** Le langage n'a pas de ligne d'interpréteur : un fichier commençant par `#!` serait lu comme un attribut nommé `!` et échouerait. Un fichier sans extension n'est pas du MoonBit, et prétendre le contraire retirerait un script shell au scanner qui sait réellement le colorer. | ||
| 36 | + | ||
| 37 | +| Première ligne | Résultat | | ||
| 38 | +| --- | --- | | ||
| 39 | +| `#!/bin/sh` | Shell | | ||
| 40 | +| `#!/usr/bin/env bash` | Shell | | ||
| 41 | +| `#!/usr/bin/env -S bash -e` | Shell | | ||
| 42 | +| `#!/usr/bin/env moon` | Non coloré | | ||
| 43 | +| `#!/usr/bin/env node` | Non coloré | | ||
| 44 | +| Tout ce qui ne commence pas par `#!` | Non coloré | | ||
| 45 | + | ||
| 46 | +L'ordre est fixe — extension, puis nom, puis première ligne — et le premier qui décide l'emporte. | ||
| 47 | + | ||
| 48 | +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, ce n'est simplement pas coloré. | ||
| 49 | + | ||
| 50 | +## Classes | ||
| 51 | + | ||
| 52 | +Chaque scanner produit le même vocabulaire de classes, et chacune correspond à une clé de thème. | ||
| 53 | + | ||
| 54 | +| Classe | Clé de thème | Produite par | | ||
| 55 | +| --- | --- | --- | | ||
| 56 | +| `identifier` | `syntax.identifier` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 57 | +| `keyword` | `syntax.keyword` | MoonBit, JavaScript, shell, HTML (doctype), XML, Dockerfile | | ||
| 58 | +| `type` | `syntax.type` | MoonBit (tout nom capitalisé, et les qualificateurs de paquet), TOML (en-têtes de table), YAML (tags) | | ||
| 59 | +| `builtin` | `syntax.builtin` | MoonBit (le prélude), JavaScript, shell (primitives et expansions), YAML (ancres et alias), Dockerfile (variables) | | ||
| 60 | +| `constant` | `syntax.constant` | MoonBit, TOML, JavaScript, shell, YAML, HTML et XML (entités) | | ||
| 61 | +| `function` | `syntax.function` | MoonBit, JavaScript, shell (la commande) | | ||
| 62 | +| `string` | `syntax.string` | tous | | ||
| 63 | +| `char` | `syntax.char` | MoonBit (`'c'` et `b'c'`) | | ||
| 64 | +| `number` | `syntax.number` | MoonBit, TOML, JavaScript, shell, YAML, Dockerfile | | ||
| 65 | +| `comment` | `syntax.comment` | MoonBit, TOML, JavaScript, shell, HTML, YAML, XML, Dockerfile | | ||
| 66 | +| `operator` | `syntax.operator` | MoonBit, TOML, JavaScript, shell, HTML, YAML (en-têtes de scalaire de bloc), XML, Dockerfile | | ||
| 67 | +| `punctuation` | `syntax.punctuation` | MoonBit, TOML, JavaScript, shell, Markdown, YAML, Dockerfile | | ||
| 68 | +| `heading` | `syntax.heading` | Markdown | | ||
| 69 | +| `tag` | `syntax.tag` | HTML, XML | | ||
| 70 | +| `attribute` | `syntax.attribute` | MoonBit (attributs et arguments étiquetés), HTML, XML, Dockerfile (options) | | ||
| 71 | +| `emphasis` | `syntax.emphasis` | Markdown | | ||
| 72 | +| `link` | `syntax.link` | Markdown | | ||
| 73 | + | ||
| 74 | +Dans le seul thème `turbo-classic`, `syntax.attribute` et `syntax.identifier` sont tous deux en jaune simple : un attribut ou une étiquette MoonBit ne s'y distingue donc pas d'un nom ordinaire. Les sept autres thèmes leur donnent des couleurs différentes. Voir [comment écrire son propre thème](../how-to/write-a-theme.md) pour changer cela. | ||
| 75 | + | ||
| 76 | +## MoonBit | ||
| 77 | + | ||
| 78 | +Écrit à la main, dans `internal/moonbitlang`. **Rien ne franchit une fin de ligne**, et c'est une propriété du langage plutôt qu'une simplification : MoonBit n'a pas de commentaire de bloc, un saut de ligne avant le guillemet fermant est une erreur de *littéral non terminé*, une chaîne multiligne est une suite de lignes `#|` ou `$|` complètes chacune en elle-même, et un attribut tient explicitement sur une ligne. Un guillemet égaré colore donc jusqu'à la fin de sa ligne, et la ligne suivante est de nouveau du code. | ||
| 79 | + | ||
| 80 | +| Reconnu | Comme | | ||
| 81 | +| --- | --- | | ||
| 82 | +| `and`, `as`, `async`, `break`, `catch`, `const`, `continue`, `declare`, `defer`, `derive`, `else`, `enum`, `enumview`, `extend`, `extenum`, `extern`, `fn`, `for`, `guard`, `if`, `impl`, `import`, `in`, `is`, `let`, `letrec`, `lexscan`, `loop`, `match`, `mut`, `nobreak`, `nocancel`, `noraise`, `package`, `priv`, `proof_assert`, `proof_let`, `pub`, `raise`, `readonly`, `return`, `struct`, `suberror`, `test`, `throw`, `trait`, `try`, `type`, `using`, `where`, `while`, `with` | mot-clé | | ||
| 83 | +| `try!` et `guard!`, point d'exclamation compris | mot-clé | | ||
| 84 | +| `true`, `false`, `None`, `Some`, `Ok`, `Err` | constante | | ||
| 85 | +| tout nom commençant par une majuscule ASCII — `Int`, `StringBuilder`, `Shape`, `Circle` | type | | ||
| 86 | +| `println`, `abort`, `panic`, `fail`, `ignore`, `inspect`, `debug`, `repr`, `hash`, `compare`, `null`, `assert_eq`, `assert_not_eq`, `assert_true`, `assert_false`, `debug_assert`, `debug_inspect`, `json_inspect`, `physical_equal` | primitive | | ||
| 87 | +| tout autre nom en minuscules immédiatement suivi de `(` | fonction | | ||
| 88 | +| `"…"`, `b"…"`, `re"…"` | chaîne | | ||
| 89 | +| `'c'`, `b'c'` | caractère | | ||
| 90 | +| `#\|` et `$\|` | le préfixe de deux caractères en ponctuation, le reste de la ligne en chaîne | | ||
| 91 | +| `42`, `1_000`, `0xFF_FF`, `0o17`, `0b1010`, `1.5`, `1.`, `1.5e-3`, `0x1.8p3F`, `42U`, `42L`, `42UL`, `42N`, `1.0F` | nombre | | ||
| 92 | +| `//` et `///` jusqu'à la fin de la ligne | commentaire | | ||
| 93 | +| `#deprecated("…")`, `#external`, `#custom.attribute(key="v")` — la ligne entière | attribut | | ||
| 94 | +| `name~` dans un argument étiqueté, tilde compris | attribut | | ||
| 95 | +| `@json`, `@moonbitlang/core/builtin`, `@my-pkg` — le `@` compris, en une seule étendue | type | | ||
| 96 | +| `.0` dans un accès de tuple | le point en ponctuation, les chiffres en nombre | | ||
| 97 | +| `..`, `..=`, `..<`, `...` | opérateur | | ||
| 98 | +| suites de `+-*/%=<>!&\|^~?:` | opérateur | | ||
| 99 | +| `()[]{},;.` | ponctuation | | ||
| 100 | + | ||
| 101 | +**Il n'y a ici aucune table des types intégrés, et il n'en faut aucune.** La casse des identifiants de MoonBit est une règle *lexicale* et non une convention : la grammaire dit qu'un `uident` « commence par une majuscule ASCII », et seuls un type, un trait ou un constructeur d'énumération peuvent s'écrire ainsi. `Int`, `StringBuilder` et un type écrit ce matin sont tous colorés par la même ligne de code. Tous les autres scanners de cette famille ont besoin d'une table ici ; celui-ci non. | ||
| 102 | + | ||
| 103 | +**Un entier se termine avant `..`.** La grammaire est explicite — « avant `..`, l'entier se termine d'abord, donc `1..=2` commence par `1` puis `..=` » — un point ne fait donc partie d'un nombre que si un second ne le suit pas. Sans cette règle, `1..=2` se lit comme le double `1.` puis `.=2`, et tous les intervalles du fichier sont mal colorés. | ||
| 104 | + | ||
| 105 | +**Le suffixe d'un nombre est en majuscules ou ce n'est pas un suffixe.** `42UL` est un seul nombre ; `42u` est le nombre `42` suivi du nom `u`, ce que voit aussi le compilateur. | ||
| 106 | + | ||
| 107 | +**Un attribut prend la ligne entière.** La grammaire lui donne tout ce qui suit le nom pointé : « tout ce qui va jusqu'au saut de ligne suivant est la charge utile brute ». Colorer moins que la ligne inventerait une structure que le lexeur n'a pas. | ||
| 108 | + | ||
| 109 | +**`#|` et `#deprecated` se distinguent par le caractère qui suit le `#`.** Le nom d'un attribut doit commencer par une lettre ou un tiret bas ; une ligne de chaîne multiligne a une barre verticale à cette place. | ||
| 110 | + | ||
| 111 | +**Un commentaire de documentation est coloré comme n'importe quel autre commentaire.** `///`, `///|` et `//` aboutissent tous à `syntax.comment`, parce que l'ensemble des classes de turbo-core est délibérément fermé — c'est ce qui permet à un seul thème de colorer tous les langages qu'un éditeur apprendra jamais. | ||
| 112 | + | ||
| 113 | +**Un nom après un point n'est jamais un mot-clé.** Les identifiants pointés de MoonBit « suivent les règles de casse des identifiants sans consulter la table des mots-clés, si bien que `.if` est valide » — un enregistrement avec un champ nommé `type` est du MoonBit ordinaire. | ||
| 114 | + | ||
| 115 | +**`package` est aussi coloré comme mot-clé dans un fichier `.mbt`**, alors qu'il n'y est qu'un mot *réservé*. C'est un vrai mot-clé dans les fichiers d'interface `.mbti` que cet éditeur colore également, et dans un `.mbt` la couleur dit exactement ce que le compilateur s'apprête à dire : ce mot ne vous appartient pas. Le reste de la liste réservée — `move`, `ref`, `static`, `unsafe`, `await` et les quarante autres — est délibérément laissé tranquille, parce que ce sont réellement des noms utilisables. | ||
| 116 | + | ||
| 117 | +**Un tilde collé à la fin d'un nom en minuscules est une étiquette**, et collé à autre chose il ne l'est pas : la grammaire dit que « les identifiants en majuscules ASCII et les mots-clés ne peuvent pas former d'étiquette », donc `Foo~` est un type suivi d'un tilde. | ||
| 118 | + | ||
| 119 | +**Non reconnu**, chaque cas pour une raison énoncée : | ||
| 120 | + | ||
| 121 | +| Non reconnu | Parce que | | ||
| 122 | +| --- | --- | | ||
| 123 | +| L'expression à l'intérieur de `\{…}` | La grammaire la fait aller jusqu'à « l'accolade correspondante », les accolades des littéraux imbriqués ne comptant pas : trouver la fin demande l'analyseur syntaxique. `"a \{b} c"` est donc une seule étendue de chaîne, d'accolade à accolade. **C'est une chaîne imbriquée dans une interpolation qui arrête cela** : le scanner prend le premier guillemet non échappé pour le fermant, si bien que `"a \{f("x")} c"` se lit comme chaîne, puis `x` en identifiant, puis chaîne. Les étendues restent ordonnées et ne se chevauchent jamais ; le coût est une couleur fausse à l'intérieur d'un littéral imbriqué, plus rare que les bugs de comptage d'accolades qu'entraînerait l'alternative | | ||
| 124 | +| Un constructeur d'énumération à vous, autrement que comme un type | Rien dans la syntaxe ne sépare `Circle(1.0)` d'un type appliqué à des arguments ; inventer une séparation reviendrait à se tromper dans les deux sens au lieu d'un | | ||
| 125 | +| `.5` comme nombre | MoonBit exige un chiffre avant le point : un point initial est donc un accès de tuple ou un identifiant pointé, jamais un littéral | | ||
| 126 | +| Un mot réservé comme mot-clé | `move`, `ref` et les autres sont des identifiants dont le compilateur se contente d'avertir, et les colorer dirait au lecteur qu'il ne peut pas écrire `let ref = 1` alors qu'il le peut | | ||
| 127 | +| Un identifiant contenant des lettres non ASCII | MoonBit accepte le CJK et plusieurs autres plages dans un nom ; les prédicats de caractères sur lesquels ce scanner est bâti sont ASCII, un tel nom est donc franchi sans couleur plutôt que deviné | | ||
| 128 | +| `.mbt.md` comme du MoonBit | C'est un document Markdown contenant du MoonBit dans ses blocs. Son extension est `.md`, et c'est Markdown qui le colore | | ||
| 129 | +| 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) | | ||
| 130 | + | ||
| 131 | +## TOML | ||
| 132 | + | ||
| 133 | +| Reconnu | Comme | | ||
| 134 | +| --- | --- | | ||
| 135 | +| `# commentaire` | comment | | ||
| 136 | +| `[table]`, `[[array]]` | le nom en type, les crochets en punctuation | | ||
| 137 | +| `clé =` | identifier, puis operator | | ||
| 138 | +| `"basique"`, `'littérale'`, `"""multi-ligne"""`, `'''multi-ligne'''` | string | | ||
| 139 | +| `true`, `false` | constant | | ||
| 140 | +| nombres, dates, heures, `inf`, `nan` | number | | ||
| 141 | + | ||
| 142 | +## YAML | ||
| 143 | + | ||
| 144 | +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. | ||
| 145 | + | ||
| 146 | +| Reconnu | Comme | | ||
| 147 | +| --- | --- | | ||
| 148 | +| `# commentaire` | commentaire | | ||
| 149 | +| `clé:` suivie d'une espace ou de la fin de ligne | la clé en identifiant, le deux-points en ponctuation | | ||
| 150 | +| `"entre guillemets": 1`, `'apostrophes': 1` | la clé citée en identifiant | | ||
| 151 | +| `- ` ouvrant une entrée de séquence | ponctuation | | ||
| 152 | +| `"…"`, `'…'` | chaîne | | ||
| 153 | +| `true`, `false`, `yes`, `no`, `on`, `off`, `null` | constante, quelle que soit la casse | | ||
| 154 | +| nombres, dates et heures écrits sans guillemets | nombre | | ||
| 155 | +| `&ancre`, `*alias` | builtin | | ||
| 156 | +| `!!str`, `!Custom` | type | | ||
| 157 | +| `---`, `...` | toute la ligne en ponctuation | | ||
| 158 | +| `{`, `}`, `[`, `]`, `,` | ponctuation | | ||
| 159 | +| `\|`, `>`, avec leurs indicateurs de coupe et d'indentation | l'en-tête en opérateur, le corps en chaîne | | ||
| 160 | + | ||
| 161 | +**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. | ||
| 162 | + | ||
| 163 | +**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. | ||
| 164 | + | ||
| 165 | +**Un `#` a besoin d'une espace devant lui pour ouvrir un commentaire**, si bien que `colour: ff#00aa` est un seul scalaire. | ||
| 166 | + | ||
| 167 | +| Non reconnu | Parce que | | ||
| 168 | +| --- | --- | | ||
| 169 | +| 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é | | ||
| 170 | +| 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 | | ||
| 171 | +| 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 | | ||
| 172 | + | ||
| 173 | +## Markdown | ||
| 174 | + | ||
| 175 | +| Reconnu | Comme | | ||
| 176 | +| --- | --- | | ||
| 177 | +| `# Titre` … `###### Titre` | toute la ligne en heading | | ||
| 178 | +| `**gras**`, `__gras__`, `*italique*`, `_italique_` | emphasis | | ||
| 179 | +| `` `code` `` | string | | ||
| 180 | +| `[texte](cible)`, `` | l'ensemble en link | | ||
| 181 | +| `- `, `* `, `+ `, `1. `, `1) ` | le marqueur en punctuation | | ||
| 182 | +| `>` | punctuation | | ||
| 183 | +| `---`, `***`, `___` | punctuation | | ||
| 184 | +| clôtures ` ``` ` et `~~~` | tout le bloc, lignes d'ouverture et de fermeture comprises, en string | | ||
| 185 | + | ||
| 186 | +Un bloc clôturé est **d'une seule couleur quel que soit le langage annoncé** : ```` ```moonbit ```` ne colore pas son contenu en MoonBit. 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. | ||
| 187 | + | ||
| 188 | +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. | ||
| 189 | + | ||
| 190 | +## JavaScript | ||
| 191 | + | ||
| 192 | +| Reconnu | Comme | | ||
| 193 | +| --- | --- | | ||
| 194 | +| `const`, `let`, `function`, `class`, `async`, `await`, `import`, `export`, … | keyword | | ||
| 195 | +| `true`, `false`, `null`, `undefined`, `NaN`, `Infinity`, `this` | constant | | ||
| 196 | +| `console`, `document`, `window`, `Array`, `Object`, `Promise`, `Math`, `JSON`, … | builtin | | ||
| 197 | +| un nom immédiatement suivi de `(` | function | | ||
| 198 | +| `"…"`, `'…'` | string | | ||
| 199 | +| `` `…` ``, interpolations comprises, sur plusieurs lignes | string | | ||
| 200 | +| `//` jusqu'à la fin de la ligne, `/* … */` sur plusieurs lignes | comment | | ||
| 201 | +| `42`, `3.14`, `0x1f`, `0b1010`, `0o777`, `1_000_000`, `1e6`, `10n` | number | | ||
| 202 | +| suites de `+-*/%=<>!&|^~?:` | operator | | ||
| 203 | +| `()[]{},;.` | punctuation | | ||
| 204 | + | ||
| 205 | +**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. | ||
| 206 | + | ||
| 207 | +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 MoonBit. | ||
| 208 | + | ||
| 209 | +## HTML | ||
| 210 | + | ||
| 211 | +| Reconnu | Comme | | ||
| 212 | +| --- | --- | | ||
| 213 | +| `<balise`, `</balise`, `>`, `/>` | tag | | ||
| 214 | +| noms d'attributs, dont `data-*`, `xlink:href`, `@click`, `v-bind.prop` | attribute | | ||
| 215 | +| `=` | operator | | ||
| 216 | +| `"…"`, `'…'` | string | | ||
| 217 | +| `<!-- … -->`, sur plusieurs lignes | comment | | ||
| 218 | +| `&`, `©` | constant | | ||
| 219 | +| `<!DOCTYPE …>` et les autres déclarations | keyword | | ||
| 220 | + | ||
| 221 | +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. | ||
| 222 | + | ||
| 223 | +**Le contenu de `<script>` et de `<style>` n'est pas coloré** en JavaScript ni en CSS. | ||
| 224 | + | ||
| 225 | +## XML | ||
| 226 | + | ||
| 227 | +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. | ||
| 228 | + | ||
| 229 | +| Reconnu | Comme | | ||
| 230 | +| --- | --- | | ||
| 231 | +| `<?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 | | ||
| 232 | +| `<!DOCTYPE …>` et les autres formes `<!` | mot-clé | | ||
| 233 | +| `<!-- … -->`, sur plusieurs lignes | commentaire | | ||
| 234 | +| `<![CDATA[ … ]]>`, sur plusieurs lignes | chaîne | | ||
| 235 | +| `<balise`, `</balise`, `>`, `/>` | balise | | ||
| 236 | +| `<ns:balise>`, `xsi:type` | le préfixe et le nom local en **un seul** segment | | ||
| 237 | +| les noms d'attributs | attribut | | ||
| 238 | +| `=` | opérateur | | ||
| 239 | +| `"…"`, `'…'` | chaîne | | ||
| 240 | +| `&`, `©` | constante | | ||
| 241 | + | ||
| 242 | +**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. | ||
| 243 | + | ||
| 244 | +**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. | ||
| 245 | + | ||
| 246 | +Le texte entre balises n'est pas coloré. | ||
| 247 | + | ||
| 248 | +## Shell | ||
| 249 | + | ||
| 250 | +S'applique indifféremment à `sh`, `bash` et `zsh` : les mots-clés reconnus sont ceux qu'ils partagent. | ||
| 251 | + | ||
| 252 | +| Reconnu | Comme | | ||
| 253 | +| --- | --- | | ||
| 254 | +| `if`, `then`, `fi`, `for`, `while`, `case`, `esac`, `function`, `return`, … | keyword | | ||
| 255 | +| `true`, `false` | constant | | ||
| 256 | +| `echo`, `printf`, `export`, `local`, `read`, `cd`, `set`, `source`, … | builtin | | ||
| 257 | +| `$NOM`, `${…}`, `$(…)`, `$1`, `$?`, `$@` | builtin | | ||
| 258 | +| le **premier mot nu d'une ligne** | function | | ||
| 259 | +| tout mot nu suivant, et `NOM` dans `NOM=valeur` | identifier | | ||
| 260 | +| `'…'`, sans échappement ni expansion à l'intérieur | string | | ||
| 261 | +| `"…"`, avec les expansions colorées comme telles | string | | ||
| 262 | +| `#` jusqu'à la fin de la ligne | comment | | ||
| 263 | + | ||
| 264 | +`$(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. | ||
| 265 | + | ||
| 266 | +**Les heredocs ne sont pas reconnus.** `<<EOF` et le texte qui suit sont colorés comme du shell ordinaire. | ||
| 267 | + | ||
| 268 | +## Dockerfile | ||
| 269 | + | ||
| 270 | +| Reconnu | Comme | | ||
| 271 | +| --- | --- | | ||
| 272 | +| `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 | | ||
| 273 | +| `AS`, `NONE` | mot-clé | | ||
| 274 | +| `# commentaire`, y compris les directives `# syntax=` et `# escape=` | commentaire | | ||
| 275 | +| `--from=builder`, `--chown=me:me` | le nom de l'option en attribut | | ||
| 276 | +| `$NOM`, `${NOM}`, `${NOM:-defaut}` | builtin, en un seul segment jusqu'à l'accolade fermante | | ||
| 277 | +| `"…"`, `'…'` | chaîne | | ||
| 278 | +| un `\` final | opérateur | | ||
| 279 | +| les nombres | nombre | | ||
| 280 | +| chemins et références d'images — `/usr/local/bin`, `golang:1.26-alpine` | identifiant, en **un seul** segment | | ||
| 281 | + | ||
| 282 | +**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. | ||
| 283 | + | ||
| 284 | +**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. | ||
| 285 | + | ||
| 286 | +| Non reconnu | Parce que | | ||
| 287 | +| --- | --- | | ||
| 288 | +| 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 | | ||
| 289 | +| Les heredocs dans un `RUN` | La même raison que pour l'analyseur shell | | ||
| 290 | +| Quelle étape nomme un `--from` | Rien ici ne lit le reste du fichier | | ||
| 291 | + | ||
| 292 | +## Voir aussi | ||
| 293 | + | ||
| 294 | +- [Format des fichiers de thème](themes.md) — toutes les clés vers lesquelles ces classes se résolvent | ||
| 295 | +- [Coloration et complétion](../explanation/colouring-and-completion.md) — pourquoi les scanners sont écrits ainsi | ||
| 296 | +- [Écrire son propre thème](../how-to/write-a-theme.md) | ||
added
docs/fr/reference/moonbit-tools.md +242 -0 | new file mode 100644 | ||
| @@ -0,0 +1,242 @@ | ||
| 1 | +# Référence : outils go | |
| 2 | + | |
| 3 | +> Description neutre de `.turbo-moonbit/tools.toml`, du menu MoonBit, et de ce que lancer une commande fait. | |
| 4 | + | |
| 5 | +## Fichier | |
| 6 | + | |
| 7 | +| Propriété | Valeur | | |
| 8 | +| --- | --- | | |
| 9 | +| Chemin | `./.turbo-moonbit/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-moonbit/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 `MoonBit`. 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 = "moon test" | |
| 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 | +**MoonBit ▸ Create tools file** écrit ces neuf entrées, dans cet ordre : | |
| 48 | + | |
| 49 | +| Nom | Commande | Sortie | Menu | | |
| 50 | +| --- | --- | --- | --- | | |
| 51 | +| `~C~heck` | `moon check` | `popup` | MoonBit | | |
| 52 | +| `~F~ormat` | `moon fmt` | `popup` | MoonBit | | |
| 53 | +| `~B~uild` | `moon build --target {{backend: wasm-gc, js, native, llvm or all...}}` | `popup` | MoonBit | | |
| 54 | +| `~T~est` | `moon test` | `popup` | MoonBit | | |
| 55 | +| `~R~un` | `moon run {{package, e.g. cmd/main}}` | `terminal` | MoonBit | | |
| 56 | +| `~A~dd a dependency` | `moon add {{module, e.g. moonbitlang/x}}` | `popup` | MoonBit | | |
| 57 | +| `~I~nterfaces` | `moon info` | `popup` | MoonBit | | |
| 58 | +| `C~l~ean` | `moon clean` | `popup` | MoonBit | | |
| 59 | +| `~E~cho` | `echo 🎉 tada!` | `terminal` | Tools | | |
| 60 | + | |
| 61 | +`Check` précède `Build` parce que c'est la commande qui répond « est-ce que ça tient ? » sans rien produire. Trois d'entre elles demandent une valeur avant de s'exécuter, et une nomme son propre `menu` : ces deux fonctionnalités sont invisibles si le fichier de départ ne les montre pas. | |
| 62 | + | |
| 63 | +Chaque outil nomme sa `output`, y compris ceux qui nomment la valeur par 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. | |
| 64 | + | |
| 65 | +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. | |
| 66 | + | |
| 67 | +## Le menu MoonBit | |
| 68 | + | |
| 69 | +Toujours sur la barre, qu'un fichier d'outils existe ou non. Sa touche d'accès est `Alt-M`. | |
| 70 | + | |
| 71 | +| Entrée | Condition | | |
| 72 | +| --- | --- | | |
| 73 | +| Une ligne par outil sans `menu`, dans l'ordre du fichier | Le fichier en contient au moins un | | |
| 74 | +| `Cannot read tools`, grisé | Le fichier est présent mais illisible | | |
| 75 | +| `Create tools file` | Le projet n'a pas de fichier d'outils | | |
| 76 | +| `Open tools file` | Le projet en a un | | |
| 77 | + | |
| 78 | +## Les menus qu'un outil réclame | |
| 79 | + | |
| 80 | +Un `menu` nommant autre chose que `Go` place sur la barre un menu de ce nom. | |
| 81 | + | |
| 82 | +| Propriété | Valeur | | |
| 83 | +| --- | --- | | |
| 84 | +| Position | Entre Go et Help | | |
| 85 | +| Ordre | L'ordre où chaque nom apparaît pour la première fois dans le fichier | | |
| 86 | +| 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 MoonBit. | | |
| 87 | +| Fichier illisible | Aucun menu ; c'est le menu MoonBit qui porte l'erreur | | |
| 88 | +| Pendant que l'éditeur tourne | Ajoutés, retirés et renommés au fil des modifications du fichier, sans redémarrage | | |
| 89 | + | |
| 90 | +### Touches d'accès | |
| 91 | + | |
| 92 | +Attribuées automatiquement, parce qu'un nom venu d'un fichier ne peut pas être confronté à l'avance aux menus fixes. | |
| 93 | + | |
| 94 | +| Cas | Résultat | | |
| 95 | +| --- | --- | | |
| 96 | +| 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. | | |
| 97 | +| Des tildes nommant une lettre libre | Conservés tels quels. `Doc~k~er` répond à `Alt-K`. | | |
| 98 | +| Des tildes nommant une lettre prise | Abandonnés, et une lettre libre choisie à la place. `~F~oo` devient `F~o~o`. | | |
| 99 | +| Toutes les lettres prises | Pas de touche d'accès. `F10` et la souris l'ouvrent quand même. | | |
| 100 | + | |
| 101 | +Les lettres que les menus de l'éditeur occupent sont `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` et `H`. | |
| 102 | + | |
| 103 | +## Lancer une commande | |
| 104 | + | |
| 105 | +Commun à toutes les sorties : | |
| 106 | + | |
| 107 | +| Propriété | Valeur | | |
| 108 | +| --- | --- | | |
| 109 | +| Shell | `/bin/sh -c "<commande>"` sous Linux et macOS ; `cmd.exe /S /C "<commande>"` — le shell que nomme `%COMSPEC%` — sous Windows | | |
| 110 | +| Répertoire | Celui depuis lequel l'éditeur a été lancé | | |
| 111 | +| Erreur standard | Mêlée à la sortie standard, dans l'ordre où la commande les a écrites | | |
| 112 | + | |
| 113 | +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. | |
| 114 | + | |
| 115 | +### `output = "popup"` | |
| 116 | + | |
| 117 | +| Propriété | Valeur | | |
| 118 | +| --- | --- | | |
| 119 | +| Ouverture | Immédiate, avant la fin de la commande | | |
| 120 | +| Modale | Oui : rien d'autre dans l'éditeur n'est utilisable tant qu'elle est là | | |
| 121 | +| Remplissage | À mesure que la sortie arrive, en la suivant tant qu'on n'a pas remonté | | |
| 122 | +| Titre pendant | `<commande> — running` | | |
| 123 | +| Titre à la fin | `<commande> — ok`, ou `<commande> — exit <n>` | | |
| 124 | +| Sortie vide, terminée | Affiche `(no output)` | | |
| 125 | +| Sortie vide, en cours | N'affiche rien | | |
| 126 | +| Plafond de sortie | 10000 lignes ; au-delà les plus anciennes partent et une ligne `… n earlier lines dropped …` le dit | | |
| 127 | + | |
| 128 | +| Touche | Effet | | |
| 129 | +| --- | --- | | |
| 130 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Parcourir la sortie | | |
| 131 | +| Molette | Idem | | |
| 132 | +| `Échap`, `Entrée`, **Close** | Fermer, en **arrêtant la commande** si elle tourne encore | | |
| 133 | + | |
| 134 | +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. | |
| 135 | + | |
| 136 | +### `output = "terminal"` | |
| 137 | + | |
| 138 | +| Propriété | Valeur | | |
| 139 | +| --- | --- | | |
| 140 | +| Fenêtre | Une fenêtre terminal à elle, titrée avec la commande | | |
| 141 | +| Environnement | Celui de l'éditeur, avec `TERM` à `xterm-256color` | | |
| 142 | +| Après la sortie | La fenêtre reste, montrant sa sortie | | |
| 143 | +| Modale | Non : l'éditeur continue à côté | | |
| 144 | + | |
| 145 | +Comme c'est un vrai terminal, les couleurs, la pagination, `Ctrl-C` et la lecture au clavier fonctionnent. Voir [Fenêtres terminal](terminal.md). | |
| 146 | + | |
| 147 | +Touches dans une fenêtre **terminée** : | |
| 148 | + | |
| 149 | +| Touche | Effet | | |
| 150 | +| --- | --- | | |
| 151 | +| `Maj-Page↑`, `Maj-Page↓` | Relire la sortie | | |
| 152 | +| `Ctrl-W` | Fermer la fenêtre | | |
| 153 | +| Tout le reste | Atteint l'éditeur, pas le shell mort | | |
| 154 | + | |
| 155 | +### `output = "editor"` | |
| 156 | + | |
| 157 | +| Propriété | Valeur | | |
| 158 | +| --- | --- | | |
| 159 | +| Affiche | Une popup pendant l'exécution, comme ci-dessus | | |
| 160 | +| À la fermeture de la popup | Une fenêtre d'édition contenant la sortie, titrée avec la commande | | |
| 161 | +| Remplie | Une fois, à la fin de la commande — pas au fil de l'eau | | |
| 162 | +| La fenêtre | Une fenêtre d'édition ordinaire sans nom de fichier : cherchable avec `Ctrl-F`, et `Save as` la conserve | | |
| 163 | + | |
| 164 | +## Rechargement après une commande | |
| 165 | + | |
| 166 | +À la fin d'une commande, chaque fichier ouvert est examiné. | |
| 167 | + | |
| 168 | +| Le fichier | Ce qui se passe | | |
| 169 | +| --- | --- | | |
| 170 | +| Non modifié, et changé sur le disque | Relu ; son langage est redécidé et son titre rafraîchi | | |
| 171 | +| Non modifié, et inchangé sur le disque | Laissé tel quel, non compté | | |
| 172 | +| A des modifications non enregistrées | Laissé tel quel et compté comme ignoré | | |
| 173 | +| N'a jamais reçu de nom | Laissé tel quel | | |
| 174 | +| A disparu du disque | Laissé tel quel | | |
| 175 | + | |
| 176 | +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. | |
| 177 | + | |
| 178 | +L'arbre du projet est rafraîchi au même moment. | |
| 179 | + | |
| 180 | +| Barre d'état | Quand | | |
| 181 | +| --- | --- | | |
| 182 | +| `Running <commande>` | La fenêtre s'ouvre | | |
| 183 | +| `Reloaded 2 files` | Deux fichiers relus, aucun ignoré | | |
| 184 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Certains ont été ignorés | | |
| 185 | +| `Command finished; 1 file with unsaved changes left alone` | Rien relu, quelque chose ignoré | | |
| 186 | + | |
| 187 | +## Erreurs | |
| 188 | + | |
| 189 | +| Message | Cause | | |
| 190 | +| --- | --- | | |
| 191 | +| `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 | | |
| 192 | +| `Already there: .turbo-moonbit/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. | | |
| 193 | +| `This project has no .turbo-moonbit/tools.toml yet.` | Ouvrir dans un projet qui n'en a pas, de même | | |
| 194 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | |
| 195 | +| `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) | | |
| 196 | + | |
| 197 | +## Demander une valeur | |
| 198 | + | |
| 199 | +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. | |
| 200 | + | |
| 201 | +| Écrit | Demandé | Substitué | | |
| 202 | +| --- | --- | --- | | |
| 203 | +| `{{chemin du module}}` | `chemin du module` | protégé pour le shell | | |
| 204 | +| `{{options...}}` | `options` | tel quel | | |
| 205 | + | |
| 206 | +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. | |
| 207 | + | |
| 208 | +```toml | |
| 209 | +[[tool]] | |
| 210 | +name = "~I~nit module" | |
| 211 | +command = "go mod init {{chemin du module}}" | |
| 212 | +output = "popup" | |
| 213 | +``` | |
| 214 | + | |
| 215 | +| Règle | Comportement | | |
| 216 | +| --- | --- | | |
| 217 | +| Plusieurs libellés | Une boîte, un champ chacun, dans l'ordre où ils apparaissent | | |
| 218 | +| Le même libellé deux fois | Un seul champ ; chaque occurrence reçoit ce qui y est tapé | | |
| 219 | +| Un libellé écrit des deux façons | Demandé une fois ; chaque occurrence honore ses propres accolades | | |
| 220 | +| Échap, ou Annuler | La commande n'est pas lancée | | |
| 221 | +| Un champ laissé vide | Substitué par du vide — la commande dira elle-même ce qui lui manque | | |
| 222 | +| Relancer l'outil | La boîte repart de ce qui avait été tapé, pour cette session seulement | | |
| 223 | +| Plus de champs que l'écran n'en contient | Refusé, avec un message disant combien tiennent | | |
| 224 | + | |
| 225 | +**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`. | |
| 226 | + | |
| 227 | +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. | |
| 228 | + | |
| 229 | +### Erreurs | |
| 230 | + | |
| 231 | +| Erreur | Cause | | |
| 232 | +| --- | --- | | |
| 233 | +| `tool "X": "{{module" is never closed` | Une ouverture `{{` sans `}}` après elle | | |
| 234 | +| `tool "X": {{}} asks for a value but does not say what it is` | Un libellé vide, ou réduit à `...` | | |
| 235 | + | |
| 236 | +Les deux sont refusées à la lecture du fichier : un libellé à moitié tapé n'atteint donc jamais le shell avec ses accolades. | |
| 237 | + | |
| 238 | +## Voir aussi | |
| 239 | + | |
| 240 | +- [Lancer les commandes moon depuis l'éditeur](../how-to/run-moon-commands.md) | |
| 241 | +- [Outils MoonBit](../explanation/moonbit-tools.md) | |
| 242 | +- [Fenêtres terminal](terminal.md) | |
| new file mode 100644 | |||
| @@ -0,0 +1,242 @@ | |||
| 1 | +# Référence : outils go | ||
| 2 | + | ||
| 3 | +> Description neutre de `.turbo-moonbit/tools.toml`, du menu MoonBit, et de ce que lancer une commande fait. | ||
| 4 | + | ||
| 5 | +## Fichier | ||
| 6 | + | ||
| 7 | +| Propriété | Valeur | | ||
| 8 | +| --- | --- | | ||
| 9 | +| Chemin | `./.turbo-moonbit/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-moonbit/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 `MoonBit`. 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 = "moon test" | ||
| 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 | +**MoonBit ▸ Create tools file** écrit ces neuf entrées, dans cet ordre : | ||
| 48 | + | ||
| 49 | +| Nom | Commande | Sortie | Menu | | ||
| 50 | +| --- | --- | --- | --- | | ||
| 51 | +| `~C~heck` | `moon check` | `popup` | MoonBit | | ||
| 52 | +| `~F~ormat` | `moon fmt` | `popup` | MoonBit | | ||
| 53 | +| `~B~uild` | `moon build --target {{backend: wasm-gc, js, native, llvm or all...}}` | `popup` | MoonBit | | ||
| 54 | +| `~T~est` | `moon test` | `popup` | MoonBit | | ||
| 55 | +| `~R~un` | `moon run {{package, e.g. cmd/main}}` | `terminal` | MoonBit | | ||
| 56 | +| `~A~dd a dependency` | `moon add {{module, e.g. moonbitlang/x}}` | `popup` | MoonBit | | ||
| 57 | +| `~I~nterfaces` | `moon info` | `popup` | MoonBit | | ||
| 58 | +| `C~l~ean` | `moon clean` | `popup` | MoonBit | | ||
| 59 | +| `~E~cho` | `echo 🎉 tada!` | `terminal` | Tools | | ||
| 60 | + | ||
| 61 | +`Check` précède `Build` parce que c'est la commande qui répond « est-ce que ça tient ? » sans rien produire. Trois d'entre elles demandent une valeur avant de s'exécuter, et une nomme son propre `menu` : ces deux fonctionnalités sont invisibles si le fichier de départ ne les montre pas. | ||
| 62 | + | ||
| 63 | +Chaque outil nomme sa `output`, y compris ceux qui nomment la valeur par 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. | ||
| 64 | + | ||
| 65 | +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. | ||
| 66 | + | ||
| 67 | +## Le menu MoonBit | ||
| 68 | + | ||
| 69 | +Toujours sur la barre, qu'un fichier d'outils existe ou non. Sa touche d'accès est `Alt-M`. | ||
| 70 | + | ||
| 71 | +| Entrée | Condition | | ||
| 72 | +| --- | --- | | ||
| 73 | +| Une ligne par outil sans `menu`, dans l'ordre du fichier | Le fichier en contient au moins un | | ||
| 74 | +| `Cannot read tools`, grisé | Le fichier est présent mais illisible | | ||
| 75 | +| `Create tools file` | Le projet n'a pas de fichier d'outils | | ||
| 76 | +| `Open tools file` | Le projet en a un | | ||
| 77 | + | ||
| 78 | +## Les menus qu'un outil réclame | ||
| 79 | + | ||
| 80 | +Un `menu` nommant autre chose que `Go` place sur la barre un menu de ce nom. | ||
| 81 | + | ||
| 82 | +| Propriété | Valeur | | ||
| 83 | +| --- | --- | | ||
| 84 | +| Position | Entre Go et Help | | ||
| 85 | +| Ordre | L'ordre où chaque nom apparaît pour la première fois dans le fichier | | ||
| 86 | +| 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 MoonBit. | | ||
| 87 | +| Fichier illisible | Aucun menu ; c'est le menu MoonBit qui porte l'erreur | | ||
| 88 | +| Pendant que l'éditeur tourne | Ajoutés, retirés et renommés au fil des modifications du fichier, sans redémarrage | | ||
| 89 | + | ||
| 90 | +### Touches d'accès | ||
| 91 | + | ||
| 92 | +Attribuées automatiquement, parce qu'un nom venu d'un fichier ne peut pas être confronté à l'avance aux menus fixes. | ||
| 93 | + | ||
| 94 | +| Cas | Résultat | | ||
| 95 | +| --- | --- | | ||
| 96 | +| 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. | | ||
| 97 | +| Des tildes nommant une lettre libre | Conservés tels quels. `Doc~k~er` répond à `Alt-K`. | | ||
| 98 | +| Des tildes nommant une lettre prise | Abandonnés, et une lettre libre choisie à la place. `~F~oo` devient `F~o~o`. | | ||
| 99 | +| Toutes les lettres prises | Pas de touche d'accès. `F10` et la souris l'ouvrent quand même. | | ||
| 100 | + | ||
| 101 | +Les lettres que les menus de l'éditeur occupent sont `F`, `E`, `S`, `R`, `O`, `W`, `N` (Snippets), `G` et `H`. | ||
| 102 | + | ||
| 103 | +## Lancer une commande | ||
| 104 | + | ||
| 105 | +Commun à toutes les sorties : | ||
| 106 | + | ||
| 107 | +| Propriété | Valeur | | ||
| 108 | +| --- | --- | | ||
| 109 | +| Shell | `/bin/sh -c "<commande>"` sous Linux et macOS ; `cmd.exe /S /C "<commande>"` — le shell que nomme `%COMSPEC%` — sous Windows | | ||
| 110 | +| Répertoire | Celui depuis lequel l'éditeur a été lancé | | ||
| 111 | +| Erreur standard | Mêlée à la sortie standard, dans l'ordre où la commande les a écrites | | ||
| 112 | + | ||
| 113 | +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. | ||
| 114 | + | ||
| 115 | +### `output = "popup"` | ||
| 116 | + | ||
| 117 | +| Propriété | Valeur | | ||
| 118 | +| --- | --- | | ||
| 119 | +| Ouverture | Immédiate, avant la fin de la commande | | ||
| 120 | +| Modale | Oui : rien d'autre dans l'éditeur n'est utilisable tant qu'elle est là | | ||
| 121 | +| Remplissage | À mesure que la sortie arrive, en la suivant tant qu'on n'a pas remonté | | ||
| 122 | +| Titre pendant | `<commande> — running` | | ||
| 123 | +| Titre à la fin | `<commande> — ok`, ou `<commande> — exit <n>` | | ||
| 124 | +| Sortie vide, terminée | Affiche `(no output)` | | ||
| 125 | +| Sortie vide, en cours | N'affiche rien | | ||
| 126 | +| Plafond de sortie | 10000 lignes ; au-delà les plus anciennes partent et une ligne `… n earlier lines dropped …` le dit | | ||
| 127 | + | ||
| 128 | +| Touche | Effet | | ||
| 129 | +| --- | --- | | ||
| 130 | +| `↑` `↓` `Page↑` `Page↓` `Début` `Fin` | Parcourir la sortie | | ||
| 131 | +| Molette | Idem | | ||
| 132 | +| `Échap`, `Entrée`, **Close** | Fermer, en **arrêtant la commande** si elle tourne encore | | ||
| 133 | + | ||
| 134 | +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. | ||
| 135 | + | ||
| 136 | +### `output = "terminal"` | ||
| 137 | + | ||
| 138 | +| Propriété | Valeur | | ||
| 139 | +| --- | --- | | ||
| 140 | +| Fenêtre | Une fenêtre terminal à elle, titrée avec la commande | | ||
| 141 | +| Environnement | Celui de l'éditeur, avec `TERM` à `xterm-256color` | | ||
| 142 | +| Après la sortie | La fenêtre reste, montrant sa sortie | | ||
| 143 | +| Modale | Non : l'éditeur continue à côté | | ||
| 144 | + | ||
| 145 | +Comme c'est un vrai terminal, les couleurs, la pagination, `Ctrl-C` et la lecture au clavier fonctionnent. Voir [Fenêtres terminal](terminal.md). | ||
| 146 | + | ||
| 147 | +Touches dans une fenêtre **terminée** : | ||
| 148 | + | ||
| 149 | +| Touche | Effet | | ||
| 150 | +| --- | --- | | ||
| 151 | +| `Maj-Page↑`, `Maj-Page↓` | Relire la sortie | | ||
| 152 | +| `Ctrl-W` | Fermer la fenêtre | | ||
| 153 | +| Tout le reste | Atteint l'éditeur, pas le shell mort | | ||
| 154 | + | ||
| 155 | +### `output = "editor"` | ||
| 156 | + | ||
| 157 | +| Propriété | Valeur | | ||
| 158 | +| --- | --- | | ||
| 159 | +| Affiche | Une popup pendant l'exécution, comme ci-dessus | | ||
| 160 | +| À la fermeture de la popup | Une fenêtre d'édition contenant la sortie, titrée avec la commande | | ||
| 161 | +| Remplie | Une fois, à la fin de la commande — pas au fil de l'eau | | ||
| 162 | +| La fenêtre | Une fenêtre d'édition ordinaire sans nom de fichier : cherchable avec `Ctrl-F`, et `Save as` la conserve | | ||
| 163 | + | ||
| 164 | +## Rechargement après une commande | ||
| 165 | + | ||
| 166 | +À la fin d'une commande, chaque fichier ouvert est examiné. | ||
| 167 | + | ||
| 168 | +| Le fichier | Ce qui se passe | | ||
| 169 | +| --- | --- | | ||
| 170 | +| Non modifié, et changé sur le disque | Relu ; son langage est redécidé et son titre rafraîchi | | ||
| 171 | +| Non modifié, et inchangé sur le disque | Laissé tel quel, non compté | | ||
| 172 | +| A des modifications non enregistrées | Laissé tel quel et compté comme ignoré | | ||
| 173 | +| N'a jamais reçu de nom | Laissé tel quel | | ||
| 174 | +| A disparu du disque | Laissé tel quel | | ||
| 175 | + | ||
| 176 | +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. | ||
| 177 | + | ||
| 178 | +L'arbre du projet est rafraîchi au même moment. | ||
| 179 | + | ||
| 180 | +| Barre d'état | Quand | | ||
| 181 | +| --- | --- | | ||
| 182 | +| `Running <commande>` | La fenêtre s'ouvre | | ||
| 183 | +| `Reloaded 2 files` | Deux fichiers relus, aucun ignoré | | ||
| 184 | +| `Reloaded 2 files; 1 file with unsaved changes left alone` | Certains ont été ignorés | | ||
| 185 | +| `Command finished; 1 file with unsaved changes left alone` | Rien relu, quelque chose ignoré | | ||
| 186 | + | ||
| 187 | +## Erreurs | ||
| 188 | + | ||
| 189 | +| Message | Cause | | ||
| 190 | +| --- | --- | | ||
| 191 | +| `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 | | ||
| 192 | +| `Already there: .turbo-moonbit/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. | | ||
| 193 | +| `This project has no .turbo-moonbit/tools.toml yet.` | Ouvrir dans un projet qui n'en a pas, de même | | ||
| 194 | +| `Cannot tell which directory this is: …` | Le répertoire de travail n'a pas pu être lu | | ||
| 195 | +| `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) | | ||
| 196 | + | ||
| 197 | +## Demander une valeur | ||
| 198 | + | ||
| 199 | +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. | ||
| 200 | + | ||
| 201 | +| Écrit | Demandé | Substitué | | ||
| 202 | +| --- | --- | --- | | ||
| 203 | +| `{{chemin du module}}` | `chemin du module` | protégé pour le shell | | ||
| 204 | +| `{{options...}}` | `options` | tel quel | | ||
| 205 | + | ||
| 206 | +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. | ||
| 207 | + | ||
| 208 | +```toml | ||
| 209 | +[[tool]] | ||
| 210 | +name = "~I~nit module" | ||
| 211 | +command = "go mod init {{chemin du module}}" | ||
| 212 | +output = "popup" | ||
| 213 | +``` | ||
| 214 | + | ||
| 215 | +| Règle | Comportement | | ||
| 216 | +| --- | --- | | ||
| 217 | +| Plusieurs libellés | Une boîte, un champ chacun, dans l'ordre où ils apparaissent | | ||
| 218 | +| Le même libellé deux fois | Un seul champ ; chaque occurrence reçoit ce qui y est tapé | | ||
| 219 | +| Un libellé écrit des deux façons | Demandé une fois ; chaque occurrence honore ses propres accolades | | ||
| 220 | +| Échap, ou Annuler | La commande n'est pas lancée | | ||
| 221 | +| Un champ laissé vide | Substitué par du vide — la commande dira elle-même ce qui lui manque | | ||
| 222 | +| Relancer l'outil | La boîte repart de ce qui avait été tapé, pour cette session seulement | | ||
| 223 | +| Plus de champs que l'écran n'en contient | Refusé, avec un message disant combien tiennent | | ||
| 224 | + | ||
| 225 | +**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`. | ||
| 226 | + | ||
| 227 | +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. | ||
| 228 | + | ||
| 229 | +### Erreurs | ||
| 230 | + | ||
| 231 | +| Erreur | Cause | | ||
| 232 | +| --- | --- | | ||
| 233 | +| `tool "X": "{{module" is never closed` | Une ouverture `{{` sans `}}` après elle | | ||
| 234 | +| `tool "X": {{}} asks for a value but does not say what it is` | Un libellé vide, ou réduit à `...` | | ||
| 235 | + | ||
| 236 | +Les deux sont refusées à la lecture du fichier : un libellé à moitié tapé n'atteint donc jamais le shell avec ses accolades. | ||
| 237 | + | ||
| 238 | +## Voir aussi | ||
| 239 | + | ||
| 240 | +- [Lancer les commandes moon depuis l'éditeur](../how-to/run-moon-commands.md) | ||
| 241 | +- [Outils MoonBit](../explanation/moonbit-tools.md) | ||
| 242 | +- [Fenêtres terminal](terminal.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-moonbit/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-moonbit` dans le répertoire de travail de l'éditeur | | |
| 10 | +| Fichier | `.turbo-moonbit/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-moonbit -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-moonbit/settings.toml — autosave on (2s)` | | |
| 59 | +| Lu et appliqué, autosave désactivée | `Applied .turbo-moonbit/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-moonbit/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-moonbit/settings.toml`. Grisée tant que le projet n'en a pas. | | |
| 94 | + | |
| 95 | +## Erreurs | |
| 96 | + | |
| 97 | +| Message | Cause | | |
| 98 | +| --- | --- | | |
| 99 | +| `turbo-moonbit: 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-moonbit/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-moonbit/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-moonbit/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-moonbit` dans le répertoire de travail de l'éditeur | | ||
| 10 | +| Fichier | `.turbo-moonbit/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-moonbit -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-moonbit/settings.toml — autosave on (2s)` | | ||
| 59 | +| Lu et appliqué, autosave désactivée | `Applied .turbo-moonbit/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-moonbit/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-moonbit/settings.toml`. Grisée tant que le projet n'en a pas. | | ||
| 94 | + | ||
| 95 | +## Erreurs | ||
| 96 | + | ||
| 97 | +| Message | Cause | | ||
| 98 | +| --- | --- | | ||
| 99 | +| `turbo-moonbit: 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-moonbit/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-moonbit/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-moonbit/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-moonbit`, `.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-moonbit/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-moonbit`, `.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/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-moonbit/snippets.toml` | Les snippets du projet | | |
| 12 | +| `$TURBO_MOONBIT_SNIPPET_DIR/snippets.toml`, sinon `<config utilisateur>/turbo-moonbit/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 : `moonbit`, `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 = "MoonBit" | |
| 46 | +languages = ["moonbit"] | |
| 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-moonbit/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-moonbit/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-moonbit/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-moonbit/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-moonbit/snippets.toml` | Les snippets du projet | | ||
| 12 | +| `$TURBO_MOONBIT_SNIPPET_DIR/snippets.toml`, sinon `<config utilisateur>/turbo-moonbit/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 : `moonbit`, `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 = "MoonBit" | ||
| 46 | +languages = ["moonbit"] | ||
| 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-moonbit/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-moonbit/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-moonbit/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-moonbit/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 MoonBit, 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 MoonBit, 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 MoonBit. | |
| 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_MOONBIT_THEME_DIR` | Utilisé quand la variable est définie et non vide. | | |
| 12 | +| `~/.config/turbo-moonbit/themes` | Linux (`os.UserConfigDir`). | | |
| 13 | +| `~/Library/Application Support/turbo-moonbit/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 MoonBit. | ||
| 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_MOONBIT_THEME_DIR` | Utilisé quand la variable est définie et non vide. | | ||
| 12 | +| `~/.config/turbo-moonbit/themes` | Linux (`os.UserConfigDir`). | | ||
| 13 | +| `~/Library/Application Support/turbo-moonbit/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 MoonBit 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-moonbit/internal/version.stamp=v0.2.0' \ | |
| 30 | + -X 'rickub.com/turbo-editors/turbo-moonbit/internal/version.commit=88a4c38' \ | |
| 31 | + -X 'rickub.com/turbo-editors/turbo-moonbit/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-moonbit@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 | +| `moon 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-moonbit`, 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-moonbit v0.2.0 88a4c38 # un build estampillé | |
| 79 | +scripts/check-version.sh bin/turbo-moonbit # 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 MoonBit 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | |
| 104 | +Turbo MoonBit 0.2.0 (88a4c38) | |
| 105 | +Turbo MoonBit 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 MoonBit 0.2.0 | |
| 114 | + | |
| 115 | +A Turbo C-style editor for MoonBit, | |
| 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-moonbit/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 MoonBit 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-moonbit/internal/version.stamp=v0.2.0' \ | ||
| 30 | + -X 'rickub.com/turbo-editors/turbo-moonbit/internal/version.commit=88a4c38' \ | ||
| 31 | + -X 'rickub.com/turbo-editors/turbo-moonbit/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-moonbit@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 | +| `moon 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-moonbit`, 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-moonbit v0.2.0 88a4c38 # un build estampillé | ||
| 79 | +scripts/check-version.sh bin/turbo-moonbit # 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 MoonBit 0.2.0 (88a4c38, built 2026-08-31T18:04:05Z) | ||
| 104 | +Turbo MoonBit 0.2.0 (88a4c38) | ||
| 105 | +Turbo MoonBit 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 MoonBit 0.2.0 | ||
| 114 | + | ||
| 115 | +A Turbo C-style editor for MoonBit, | ||
| 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-moonbit/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 +217 -0 | new file mode 100644 | ||
| @@ -0,0 +1,217 @@ | ||
| 1 | +# Tutoriel : votre premier programme MoonBit dans Turbo MoonBit | |
| 2 | + | |
| 3 | +À la fin de ce tutoriel, vous aurez écrit, formaté, lancé et cassé un petit programme MoonBit sans quitter l'éditeur — et vu l'éditeur vous dire où était l'erreur. | |
| 4 | + | |
| 5 | +Aucune connaissance préalable de Turbo MoonBit n'est nécessaire. Il vous faut Go 1.26 ou plus récent pour compiler l'éditeur, et la chaîne d'outils MoonBit pour compiler le programme. | |
| 6 | + | |
| 7 | +## Prérequis | |
| 8 | + | |
| 9 | +Vérifiez Go : | |
| 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 | +Vérifiez la chaîne d'outils MoonBit : | |
| 22 | + | |
| 23 | +```bash | |
| 24 | +moon version --all | |
| 25 | +``` | |
| 26 | + | |
| 27 | +Vous devriez voir trois lignes, chacune se terminant par un chemin : | |
| 28 | + | |
| 29 | +``` | |
| 30 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | |
| 31 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | |
| 32 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | |
| 33 | +``` | |
| 34 | + | |
| 35 | +Si la commande est introuvable, installez d'abord la chaîne d'outils — [une seule commande suffit](../how-to/install-the-moonbit-toolchain.md). | |
| 36 | + | |
| 37 | +## Étape 1 — Installer l'éditeur | |
| 38 | + | |
| 39 | +```bash | |
| 40 | +git clone https://rickub.com/turbo-editors/turbo-moonbit.git | |
| 41 | +cd turbo-moonbit | |
| 42 | +make install | |
| 43 | +``` | |
| 44 | + | |
| 45 | +L'installeur compile, installe, puis vérifie ce qu'il a installé. Les dernières lignes sont : | |
| 46 | + | |
| 47 | +``` | |
| 48 | +==> Checking the language server | |
| 49 | + ✓ moon-lsp at ~/.moon/bin/moon-lsp | |
| 50 | + | |
| 51 | +==> Ready | |
| 52 | +``` | |
| 53 | + | |
| 54 | +Nous avons maintenant une commande `turbo-moonbit`. | |
| 55 | + | |
| 56 | +## Étape 2 — Créer un projet | |
| 57 | + | |
| 58 | +```bash | |
| 59 | +cd /tmp | |
| 60 | +moon new hello | |
| 61 | +cd hello | |
| 62 | +``` | |
| 63 | + | |
| 64 | +``` | |
| 65 | +Created username/hello at hello | |
| 66 | +``` | |
| 67 | + | |
| 68 | +`moon new` écrit un `moon.mod`, un `moon.pkg`, un fichier de bibliothèque, quelques fichiers de test, et un `cmd/main/main.mbt` contenant un hello-world. **C'est `moon.mod` que Turbo MoonBit cherche** pour trouver la racine d'un projet, et c'est le dossier dans lequel `moon-lsp` sera lancé. | |
| 69 | + | |
| 70 | +## Étape 3 — Ouvrir le fichier | |
| 71 | + | |
| 72 | +```bash | |
| 73 | +turbo-moonbit cmd/main/main.mbt | |
| 74 | +``` | |
| 75 | + | |
| 76 | +L'écran se remplit. En haut : | |
| 77 | + | |
| 78 | +``` | |
| 79 | + File Edit Search Run Code Options Window Snippets MoonBit Help | |
| 80 | +``` | |
| 81 | + | |
| 82 | +Dix menus, et le neuvième porte le nom du langage. En bas, à droite, vous devriez voir : | |
| 83 | + | |
| 84 | +``` | |
| 85 | +1:1 LSP: ready | |
| 86 | +``` | |
| 87 | + | |
| 88 | +`LSP: ready` signifie que `moon-lsp` a démarré dans ce dossier. Nous nous en servirons à l'étape 8. | |
| 89 | + | |
| 90 | +## Étape 4 — Écrire le programme | |
| 91 | + | |
| 92 | +Sélectionnez tout avec `Ctrl-A` et appuyez sur `Suppr`, puis tapez ceci. Tapez-le exactement ; nous allons regarder les couleurs juste après. | |
| 93 | + | |
| 94 | +```moonbit | |
| 95 | +///| | |
| 96 | +struct Greeting { | |
| 97 | + name : String | |
| 98 | + times : Int | |
| 99 | +} | |
| 100 | + | |
| 101 | +///| | |
| 102 | +fn greet(g : Greeting) -> Unit { | |
| 103 | + for i in 0..<g.times { | |
| 104 | + println("Hello, \{g.name}! (\{i + 1})") | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 108 | +///| | |
| 109 | +fn main { | |
| 110 | + greet({ name: "MoonBit", times: 3 }) | |
| 111 | +} | |
| 112 | +``` | |
| 113 | + | |
| 114 | +Appuyez sur `F2` pour enregistrer. L'étoile à côté de `main.mbt` dans le titre de la fenêtre disparaît. | |
| 115 | + | |
| 116 | +## Étape 5 — Lire les couleurs | |
| 117 | + | |
| 118 | +Regardez ce que vous venez de taper. Dans le thème par défaut `turbo-classic` : | |
| 119 | + | |
| 120 | +| Quoi | Couleur | | |
| 121 | +| --- | --- | | |
| 122 | +| `struct`, `fn`, `for`, `in` | blanc vif, gras — mots-clés | | |
| 123 | +| `Greeting`, `String`, `Int`, `Unit` | cyan vif — types | | |
| 124 | +| `greet`, là où il est déclaré comme là où il est appelé | jaune vif, gras — fonctions | | |
| 125 | +| `println` | cyan vif, gras — un nom fourni par le langage | | |
| 126 | +| `name`, `times`, `g`, `i` | jaune vif — noms ordinaires | | |
| 127 | +| `"Hello, \{g.name}! (\{i + 1})"` | vert, **en entier** — une seule chaîne | | |
| 128 | +| `0`, `1`, `3` | magenta — nombres | | |
| 129 | +| `///\|` | gris — un commentaire | | |
| 130 | + | |
| 131 | +Deux de ces lignes méritent un second regard. | |
| 132 | + | |
| 133 | +**`Greeting` est cyan et `greet` est jaune**, et personne n'a dit à l'éditeur lequel des deux est un type. C'est la règle propre à MoonBit qui tranche : un nom commençant par une majuscule ne peut être qu'un type, un trait ou un constructeur. | |
| 134 | + | |
| 135 | +**La chaîne est verte du premier guillemet au dernier**, interpolations comprises. Le `\{g.name}` qu'elle contient n'est pas coloré comme du code — [et c'est délibéré](../explanation/colouring-and-completion.md). | |
| 136 | + | |
| 137 | +## Étape 6 — Donner ses outils au projet | |
| 138 | + | |
| 139 | +Appuyez sur `F10` pour ouvrir la barre de menus, puis sur `→` **huit fois** pour atteindre **MoonBit** — après Edit, Search, Run, Code, Options, Window et Snippets. Plus rapide : `Alt-M`. | |
| 140 | + | |
| 141 | +Le menu contient deux entrées, et une seule est disponible : | |
| 142 | + | |
| 143 | +``` | |
| 144 | +┌───────────────────┐ | |
| 145 | +│ Create tools file │ | |
| 146 | +│ Open tools file │ ← grisée ; il n'y a pas encore de fichier à ouvrir | |
| 147 | +└───────────────────┘ | |
| 148 | +``` | |
| 149 | + | |
| 150 | +Choisissez **Create tools file**. | |
| 151 | + | |
| 152 | +Une seconde fenêtre s'ouvre sur le fichier qui vient d'être écrit, `.turbo-moonbit/tools.toml`. Lisez-le si vous voulez — il explique chacune de ses clés — puis fermez-le avec `Ctrl-W`. | |
| 153 | + | |
| 154 | +Rouvrez le menu MoonBit. Il contient maintenant neuf commandes, et les deux entrées ont échangé leurs rôles : `Create tools file` est grisée, et c'est `Open tools file` qui est choisissable. | |
| 155 | + | |
| 156 | +## Étape 7 — Le formater, et le lancer | |
| 157 | + | |
| 158 | +Appuyez sur `Alt-M` et choisissez **Format**. | |
| 159 | + | |
| 160 | +Une boîte de dialogue s'ouvre, se remplit, et affiche `— exit 0`. Appuyez sur `Échap`. | |
| 161 | + | |
| 162 | +Regardez la dernière ligne de votre fonction `main`. Elle a changé : | |
| 163 | + | |
| 164 | +```moonbit | |
| 165 | + greet({ name: "MoonBit", times: 3, }) | |
| 166 | +``` | |
| 167 | + | |
| 168 | +`moon fmt` a ajouté une virgule finale, et l'éditeur a rechargé le fichier dont on venait de lui dire qu'il avait changé sous ses pieds. | |
| 169 | + | |
| 170 | +Maintenant `Alt-M`, puis **Run**. Une boîte demande une valeur avant de lancer la commande : | |
| 171 | + | |
| 172 | +``` | |
| 173 | +┌──────────────── Run ────────────────┐ | |
| 174 | +│ package, e.g. cmd/main │ | |
| 175 | +│ [ ] │ | |
| 176 | +└─────────────────────────────────────┘ | |
| 177 | +``` | |
| 178 | + | |
| 179 | +Tapez `cmd/main` et appuyez sur `Entrée`. Une fenêtre de terminal s'ouvre et le programme s'y exécute : | |
| 180 | + | |
| 181 | +``` | |
| 182 | +Hello, MoonBit! (1) | |
| 183 | +Hello, MoonBit! (2) | |
| 184 | +Hello, MoonBit! (3) | |
| 185 | +``` | |
| 186 | + | |
| 187 | +Un terminal plutôt qu'une boîte de dialogue, parce qu'un programme qui lit le clavier doit pouvoir recevoir une réponse. Le programme est terminé, la fenêtre a donc cessé de se comporter comme un terminal et toutes les touches reviennent à l'éditeur : appuyez sur `Ctrl-W` pour la fermer. | |
| 188 | + | |
| 189 | +## Étape 8 — Le casser, et voir où | |
| 190 | + | |
| 191 | +Allez sur la ligne du `println` et remplacez `g.name` par `g.nam`. Appuyez sur `F2` pour enregistrer. | |
| 192 | + | |
| 193 | +En une seconde ou deux, deux choses se produisent. Un `×` rouge apparaît dans la gouttière, juste à gauche du numéro de cette ligne. Et la barre d'état affiche : | |
| 194 | + | |
| 195 | +``` | |
| 196 | +⚠ The value identifier nam is unbound. | |
| 197 | +``` | |
| 198 | + | |
| 199 | +Personne ne l'a demandé. `moon-lsp` le publie de lui-même chaque fois qu'il relit le fichier. | |
| 200 | + | |
| 201 | +Remettez le `e` et enregistrez de nouveau ; la marque et le message disparaissent tous les deux. | |
| 202 | + | |
| 203 | +## Étape 9 — Changer de thème | |
| 204 | + | |
| 205 | +`F10`, puis `→` **cinq fois** pour atteindre **Options** — après Edit, Search, Run et Code. Choisissez **Theme…**. | |
| 206 | + | |
| 207 | +Une liste s'ouvre sur le thème dans lequel vous êtes. Appuyez sur `↓` jusqu'à `cobalt` puis `Entrée`. Tout l'écran change, en gardant la même forme. | |
| 208 | + | |
| 209 | +Appuyez sur `Alt-X` pour quitter. L'éditeur pose d'abord la question des fichiers non enregistrés, s'il y en a. | |
| 210 | + | |
| 211 | +## Et maintenant ? | |
| 212 | + | |
| 213 | +Vous avez créé un projet MoonBit, écrit un programme dans l'éditeur, formaté, lancé, cassé, et vu l'éditeur dire où. Pour aller plus loin : | |
| 214 | + | |
| 215 | +- Pour faire des choses précises → les [guides pratiques](../how-to/) | |
| 216 | +- Pour savoir exactement ce qui est coloré et comment → [langages colorés](../reference/languages.md) | |
| 217 | +- Pour comprendre pourquoi l'éditeur est bâti ainsi → les [explications](../explanation/) | |
| new file mode 100644 | |||
| @@ -0,0 +1,217 @@ | |||
| 1 | +# Tutoriel : votre premier programme MoonBit dans Turbo MoonBit | ||
| 2 | + | ||
| 3 | +À la fin de ce tutoriel, vous aurez écrit, formaté, lancé et cassé un petit programme MoonBit sans quitter l'éditeur — et vu l'éditeur vous dire où était l'erreur. | ||
| 4 | + | ||
| 5 | +Aucune connaissance préalable de Turbo MoonBit n'est nécessaire. Il vous faut Go 1.26 ou plus récent pour compiler l'éditeur, et la chaîne d'outils MoonBit pour compiler le programme. | ||
| 6 | + | ||
| 7 | +## Prérequis | ||
| 8 | + | ||
| 9 | +Vérifiez Go : | ||
| 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 | +Vérifiez la chaîne d'outils MoonBit : | ||
| 22 | + | ||
| 23 | +```bash | ||
| 24 | +moon version --all | ||
| 25 | +``` | ||
| 26 | + | ||
| 27 | +Vous devriez voir trois lignes, chacune se terminant par un chemin : | ||
| 28 | + | ||
| 29 | +``` | ||
| 30 | +moon 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moon | ||
| 31 | +moonc v0.10.12+1634b282e (2026-09-07) ~/.moon/bin/moonc | ||
| 32 | +moonrun 0.1.20260904 (94521db 2026-09-04) ~/.moon/bin/moonrun | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +Si la commande est introuvable, installez d'abord la chaîne d'outils — [une seule commande suffit](../how-to/install-the-moonbit-toolchain.md). | ||
| 36 | + | ||
| 37 | +## Étape 1 — Installer l'éditeur | ||
| 38 | + | ||
| 39 | +```bash | ||
| 40 | +git clone https://rickub.com/turbo-editors/turbo-moonbit.git | ||
| 41 | +cd turbo-moonbit | ||
| 42 | +make install | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +L'installeur compile, installe, puis vérifie ce qu'il a installé. Les dernières lignes sont : | ||
| 46 | + | ||
| 47 | +``` | ||
| 48 | +==> Checking the language server | ||
| 49 | + ✓ moon-lsp at ~/.moon/bin/moon-lsp | ||
| 50 | + | ||
| 51 | +==> Ready | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +Nous avons maintenant une commande `turbo-moonbit`. | ||
| 55 | + | ||
| 56 | +## Étape 2 — Créer un projet | ||
| 57 | + | ||
| 58 | +```bash | ||
| 59 | +cd /tmp | ||
| 60 | +moon new hello | ||
| 61 | +cd hello | ||
| 62 | +``` | ||
| 63 | + | ||
| 64 | +``` | ||
| 65 | +Created username/hello at hello | ||
| 66 | +``` | ||
| 67 | + | ||
| 68 | +`moon new` écrit un `moon.mod`, un `moon.pkg`, un fichier de bibliothèque, quelques fichiers de test, et un `cmd/main/main.mbt` contenant un hello-world. **C'est `moon.mod` que Turbo MoonBit cherche** pour trouver la racine d'un projet, et c'est le dossier dans lequel `moon-lsp` sera lancé. | ||
| 69 | + | ||
| 70 | +## Étape 3 — Ouvrir le fichier | ||
| 71 | + | ||
| 72 | +```bash | ||
| 73 | +turbo-moonbit cmd/main/main.mbt | ||
| 74 | +``` | ||
| 75 | + | ||
| 76 | +L'écran se remplit. En haut : | ||
| 77 | + | ||
| 78 | +``` | ||
| 79 | + File Edit Search Run Code Options Window Snippets MoonBit Help | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +Dix menus, et le neuvième porte le nom du langage. En bas, à droite, vous devriez voir : | ||
| 83 | + | ||
| 84 | +``` | ||
| 85 | +1:1 LSP: ready | ||
| 86 | +``` | ||
| 87 | + | ||
| 88 | +`LSP: ready` signifie que `moon-lsp` a démarré dans ce dossier. Nous nous en servirons à l'étape 8. | ||
| 89 | + | ||
| 90 | +## Étape 4 — Écrire le programme | ||
| 91 | + | ||
| 92 | +Sélectionnez tout avec `Ctrl-A` et appuyez sur `Suppr`, puis tapez ceci. Tapez-le exactement ; nous allons regarder les couleurs juste après. | ||
| 93 | + | ||
| 94 | +```moonbit | ||
| 95 | +///| | ||
| 96 | +struct Greeting { | ||
| 97 | + name : String | ||
| 98 | + times : Int | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +///| | ||
| 102 | +fn greet(g : Greeting) -> Unit { | ||
| 103 | + for i in 0..<g.times { | ||
| 104 | + println("Hello, \{g.name}! (\{i + 1})") | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +///| | ||
| 109 | +fn main { | ||
| 110 | + greet({ name: "MoonBit", times: 3 }) | ||
| 111 | +} | ||
| 112 | +``` | ||
| 113 | + | ||
| 114 | +Appuyez sur `F2` pour enregistrer. L'étoile à côté de `main.mbt` dans le titre de la fenêtre disparaît. | ||
| 115 | + | ||
| 116 | +## Étape 5 — Lire les couleurs | ||
| 117 | + | ||
| 118 | +Regardez ce que vous venez de taper. Dans le thème par défaut `turbo-classic` : | ||
| 119 | + | ||
| 120 | +| Quoi | Couleur | | ||
| 121 | +| --- | --- | | ||
| 122 | +| `struct`, `fn`, `for`, `in` | blanc vif, gras — mots-clés | | ||
| 123 | +| `Greeting`, `String`, `Int`, `Unit` | cyan vif — types | | ||
| 124 | +| `greet`, là où il est déclaré comme là où il est appelé | jaune vif, gras — fonctions | | ||
| 125 | +| `println` | cyan vif, gras — un nom fourni par le langage | | ||
| 126 | +| `name`, `times`, `g`, `i` | jaune vif — noms ordinaires | | ||
| 127 | +| `"Hello, \{g.name}! (\{i + 1})"` | vert, **en entier** — une seule chaîne | | ||
| 128 | +| `0`, `1`, `3` | magenta — nombres | | ||
| 129 | +| `///\|` | gris — un commentaire | | ||
| 130 | + | ||
| 131 | +Deux de ces lignes méritent un second regard. | ||
| 132 | + | ||
| 133 | +**`Greeting` est cyan et `greet` est jaune**, et personne n'a dit à l'éditeur lequel des deux est un type. C'est la règle propre à MoonBit qui tranche : un nom commençant par une majuscule ne peut être qu'un type, un trait ou un constructeur. | ||
| 134 | + | ||
| 135 | +**La chaîne est verte du premier guillemet au dernier**, interpolations comprises. Le `\{g.name}` qu'elle contient n'est pas coloré comme du code — [et c'est délibéré](../explanation/colouring-and-completion.md). | ||
| 136 | + | ||
| 137 | +## Étape 6 — Donner ses outils au projet | ||
| 138 | + | ||
| 139 | +Appuyez sur `F10` pour ouvrir la barre de menus, puis sur `→` **huit fois** pour atteindre **MoonBit** — après Edit, Search, Run, Code, Options, Window et Snippets. Plus rapide : `Alt-M`. | ||
| 140 | + | ||
| 141 | +Le menu contient deux entrées, et une seule est disponible : | ||
| 142 | + | ||
| 143 | +``` | ||
| 144 | +┌───────────────────┐ | ||
| 145 | +│ Create tools file │ | ||
| 146 | +│ Open tools file │ ← grisée ; il n'y a pas encore de fichier à ouvrir | ||
| 147 | +└───────────────────┘ | ||
| 148 | +``` | ||
| 149 | + | ||
| 150 | +Choisissez **Create tools file**. | ||
| 151 | + | ||
| 152 | +Une seconde fenêtre s'ouvre sur le fichier qui vient d'être écrit, `.turbo-moonbit/tools.toml`. Lisez-le si vous voulez — il explique chacune de ses clés — puis fermez-le avec `Ctrl-W`. | ||
| 153 | + | ||
| 154 | +Rouvrez le menu MoonBit. Il contient maintenant neuf commandes, et les deux entrées ont échangé leurs rôles : `Create tools file` est grisée, et c'est `Open tools file` qui est choisissable. | ||
| 155 | + | ||
| 156 | +## Étape 7 — Le formater, et le lancer | ||
| 157 | + | ||
| 158 | +Appuyez sur `Alt-M` et choisissez **Format**. | ||
| 159 | + | ||
| 160 | +Une boîte de dialogue s'ouvre, se remplit, et affiche `— exit 0`. Appuyez sur `Échap`. | ||
| 161 | + | ||
| 162 | +Regardez la dernière ligne de votre fonction `main`. Elle a changé : | ||
| 163 | + | ||
| 164 | +```moonbit | ||
| 165 | + greet({ name: "MoonBit", times: 3, }) | ||
| 166 | +``` | ||
| 167 | + | ||
| 168 | +`moon fmt` a ajouté une virgule finale, et l'éditeur a rechargé le fichier dont on venait de lui dire qu'il avait changé sous ses pieds. | ||
| 169 | + | ||
| 170 | +Maintenant `Alt-M`, puis **Run**. Une boîte demande une valeur avant de lancer la commande : | ||
| 171 | + | ||
| 172 | +``` | ||
| 173 | +┌──────────────── Run ────────────────┐ | ||
| 174 | +│ package, e.g. cmd/main │ | ||
| 175 | +│ [ ] │ | ||
| 176 | +└─────────────────────────────────────┘ | ||
| 177 | +``` | ||
| 178 | + | ||
| 179 | +Tapez `cmd/main` et appuyez sur `Entrée`. Une fenêtre de terminal s'ouvre et le programme s'y exécute : | ||
| 180 | + | ||
| 181 | +``` | ||
| 182 | +Hello, MoonBit! (1) | ||
| 183 | +Hello, MoonBit! (2) | ||
| 184 | +Hello, MoonBit! (3) | ||
| 185 | +``` | ||
| 186 | + | ||
| 187 | +Un terminal plutôt qu'une boîte de dialogue, parce qu'un programme qui lit le clavier doit pouvoir recevoir une réponse. Le programme est terminé, la fenêtre a donc cessé de se comporter comme un terminal et toutes les touches reviennent à l'éditeur : appuyez sur `Ctrl-W` pour la fermer. | ||
| 188 | + | ||
| 189 | +## Étape 8 — Le casser, et voir où | ||
| 190 | + | ||
| 191 | +Allez sur la ligne du `println` et remplacez `g.name` par `g.nam`. Appuyez sur `F2` pour enregistrer. | ||
| 192 | + | ||
| 193 | +En une seconde ou deux, deux choses se produisent. Un `×` rouge apparaît dans la gouttière, juste à gauche du numéro de cette ligne. Et la barre d'état affiche : | ||
| 194 | + | ||
| 195 | +``` | ||
| 196 | +⚠ The value identifier nam is unbound. | ||
| 197 | +``` | ||
| 198 | + | ||
| 199 | +Personne ne l'a demandé. `moon-lsp` le publie de lui-même chaque fois qu'il relit le fichier. | ||
| 200 | + | ||
| 201 | +Remettez le `e` et enregistrez de nouveau ; la marque et le message disparaissent tous les deux. | ||
| 202 | + | ||
| 203 | +## Étape 9 — Changer de thème | ||
| 204 | + | ||
| 205 | +`F10`, puis `→` **cinq fois** pour atteindre **Options** — après Edit, Search, Run et Code. Choisissez **Theme…**. | ||
| 206 | + | ||
| 207 | +Une liste s'ouvre sur le thème dans lequel vous êtes. Appuyez sur `↓` jusqu'à `cobalt` puis `Entrée`. Tout l'écran change, en gardant la même forme. | ||
| 208 | + | ||
| 209 | +Appuyez sur `Alt-X` pour quitter. L'éditeur pose d'abord la question des fichiers non enregistrés, s'il y en a. | ||
| 210 | + | ||
| 211 | +## Et maintenant ? | ||
| 212 | + | ||
| 213 | +Vous avez créé un projet MoonBit, écrit un programme dans l'éditeur, formaté, lancé, cassé, et vu l'éditeur dire où. Pour aller plus loin : | ||
| 214 | + | ||
| 215 | +- Pour faire des choses précises → les [guides pratiques](../how-to/) | ||
| 216 | +- Pour savoir exactement ce qui est coloré et comment → [langages colorés](../reference/languages.md) | ||
| 217 | +- Pour comprendre pourquoi l'éditeur est bâti ainsi → 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-moonbit | |
| 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.2 | |
| 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-moonbit | ||
| 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.2 | ||
| 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.2 h1:OA/LhR6JkvtUlp6lTgYa0wwaWou3HKXd1Glnoscyffw= | |
| 49 | +rickub.com/turbo-editors/turbo-core v1.0.2/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.2 h1:OA/LhR6JkvtUlp6lTgYa0wwaWou3HKXd1Glnoscyffw= | ||
| 49 | +rickub.com/turbo-editors/turbo-core v1.0.2/go.mod h1:rmfIY5gsFEo3sC5IIJFapwsGvdKG6NjrD7ACmnNTKq8= | ||
added
install_test.go +385 -0 | new file mode 100644 | ||
| @@ -0,0 +1,385 @@ | ||
| 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-moonbit") | |
| 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 MoonBit") { | |
| 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 MoonBit", prefix, "PATH", "moon-lsp"} { | |
| 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-moonbit")); !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-moonbit")); 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-moonbit") | |
| 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-moonbit") | |
| 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-moonbit") | |
| 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-moonbit"), "-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-moonbit"), "-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 | +// moon-lsp answers about a *project*, and it works the project out by running | |
| 351 | +// moon. Installed on its own it would start, be found, and then know nothing | |
| 352 | +// about any file — which looks exactly like a server that is not running. The | |
| 353 | +// installer has to say so, which means this check has to exist and has to be | |
| 354 | +// reached. | |
| 355 | +func TestTheInstallerChecksThatTheServerHasItsToolchain(t *testing.T) { | |
| 356 | + script := readInstaller(t) | |
| 357 | + | |
| 358 | + // Both halves: the check has to be written *and* reached. A function that | |
| 359 | + // is defined and never called is the shape this kind of grep test misses. | |
| 360 | + for _, want := range []string{"server_has_toolchain() {", "if ! server_has_toolchain", "answer nothing"} { | |
| 361 | + if !strings.Contains(script, want) { | |
| 362 | + t.Errorf("the installer never mentions %q", want) | |
| 363 | + } | |
| 364 | + } | |
| 365 | +} | |
| 366 | + | |
| 367 | +// The install hint on the status bar and the command the installer runs must be | |
| 368 | +// the same one. Two spellings of "how do I get this" is how one of them goes | |
| 369 | +// stale without anybody noticing. | |
| 370 | +func TestTheInstallerRunsTheCommandTheEditorRecommends(t *testing.T) { | |
| 371 | + script := readInstaller(t) | |
| 372 | + | |
| 373 | + if !strings.Contains(script, "cli.moonbitlang.com/install/unix.sh") { | |
| 374 | + t.Error("the installer does not name the MoonBit toolchain installer the editor's hint names") | |
| 375 | + } | |
| 376 | +} | |
| 377 | + | |
| 378 | +// Finding the file is not the same as its running, and this family has been | |
| 379 | +// caught by that twice — rustup's shim for Turbo Rust, and a stale tool | |
| 380 | +// directory in Turbo Python. | |
| 381 | +func TestTheInstallerRunsTheServerRatherThanStattingIt(t *testing.T) { | |
| 382 | + if !strings.Contains(readInstaller(t), `"$candidate" --version`) { | |
| 383 | + t.Error("find_server never runs the candidate; an unusable shim would be reported as installed") | |
| 384 | + } | |
| 385 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,385 @@ | |||
| 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-moonbit") | ||
| 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 MoonBit") { | ||
| 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 MoonBit", prefix, "PATH", "moon-lsp"} { | ||
| 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-moonbit")); !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-moonbit")); 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-moonbit") | ||
| 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-moonbit") | ||
| 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-moonbit") | ||
| 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-moonbit"), "-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-moonbit"), "-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 | +// moon-lsp answers about a *project*, and it works the project out by running | ||
| 351 | +// moon. Installed on its own it would start, be found, and then know nothing | ||
| 352 | +// about any file — which looks exactly like a server that is not running. The | ||
| 353 | +// installer has to say so, which means this check has to exist and has to be | ||
| 354 | +// reached. | ||
| 355 | +func TestTheInstallerChecksThatTheServerHasItsToolchain(t *testing.T) { | ||
| 356 | + script := readInstaller(t) | ||
| 357 | + | ||
| 358 | + // Both halves: the check has to be written *and* reached. A function that | ||
| 359 | + // is defined and never called is the shape this kind of grep test misses. | ||
| 360 | + for _, want := range []string{"server_has_toolchain() {", "if ! server_has_toolchain", "answer nothing"} { | ||
| 361 | + if !strings.Contains(script, want) { | ||
| 362 | + t.Errorf("the installer never mentions %q", want) | ||
| 363 | + } | ||
| 364 | + } | ||
| 365 | +} | ||
| 366 | + | ||
| 367 | +// The install hint on the status bar and the command the installer runs must be | ||
| 368 | +// the same one. Two spellings of "how do I get this" is how one of them goes | ||
| 369 | +// stale without anybody noticing. | ||
| 370 | +func TestTheInstallerRunsTheCommandTheEditorRecommends(t *testing.T) { | ||
| 371 | + script := readInstaller(t) | ||
| 372 | + | ||
| 373 | + if !strings.Contains(script, "cli.moonbitlang.com/install/unix.sh") { | ||
| 374 | + t.Error("the installer does not name the MoonBit toolchain installer the editor's hint names") | ||
| 375 | + } | ||
| 376 | +} | ||
| 377 | + | ||
| 378 | +// Finding the file is not the same as its running, and this family has been | ||
| 379 | +// caught by that twice — rustup's shim for Turbo Rust, and a stale tool | ||
| 380 | +// directory in Turbo Python. | ||
| 381 | +func TestTheInstallerRunsTheServerRatherThanStattingIt(t *testing.T) { | ||
| 382 | + if !strings.Contains(readInstaller(t), `"$candidate" --version`) { | ||
| 383 | + t.Error("find_server never runs the candidate; an unusable shim would be reported as installed") | ||
| 384 | + } | ||
| 385 | +} | ||
added
internal/moonbitlang/acp.toml.tmpl +80 -0 | new file mode 100644 | ||
| @@ -0,0 +1,80 @@ | ||
| 1 | +# turbo-moonbit 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 ```moonbit fence is coloured by the same scanner | |
| 73 | +# this editor colours .mbt 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-moonbit 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 ```moonbit fence is coloured by the same scanner | ||
| 73 | +# this editor colours .mbt 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/moonbitlang/acp_test.go +128 -0 | new file mode 100644 | ||
| @@ -0,0 +1,128 @@ | ||
| 1 | +package moonbitlang | |
| 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 MoonBit 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 MoonBit 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 := "```moonbit"; !strings.Contains(contents, want) { | |
| 103 | + t.Errorf("the created file never mentions a %q fence:\n%s", want, contents) | |
| 104 | + } | |
| 105 | + if want := ".mbt 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 moonbitlang | ||
| 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 MoonBit 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 MoonBit 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 := "```moonbit"; !strings.Contains(contents, want) { | ||
| 103 | + t.Errorf("the created file never mentions a %q fence:\n%s", want, contents) | ||
| 104 | + } | ||
| 105 | + if want := ".mbt 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/moonbitlang/editor_test.go +601 -0 | new file mode 100644 | ||
| @@ -0,0 +1,601 @@ | ||
| 1 | +package moonbitlang_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-moonbit/internal/moonbitlang" | |
| 22 | +) | |
| 23 | + | |
| 24 | +// --- the editor, assembled -------------------------------------------------- | |
| 25 | + | |
| 26 | +func TestTheEditorCallsItselfTurboMoonBit(t *testing.T) { | |
| 27 | + editor := newTestEditor(t) | |
| 28 | + | |
| 29 | + if got := editor.Profile().Name; got != moonbitlang.Name { | |
| 30 | + t.Errorf("Profile().Name = %q, want %q", got, moonbitlang.Name) | |
| 31 | + } | |
| 32 | + if got := editor.Profile().ProjectDir(); got != ".turbo-moonbit" { | |
| 33 | + t.Errorf("ProjectDir() = %q, want %q", got, ".turbo-moonbit") | |
| 34 | + } | |
| 35 | +} | |
| 36 | + | |
| 37 | +func TestTheEditorColoursMoonBitSourceItOpens(t *testing.T) { | |
| 38 | + // The whole path in one test: Register taught the library about MoonBit, | |
| 39 | + // the profile named the editor, and a .mbt file opened through the public | |
| 40 | + // API comes out coloured. | |
| 41 | + root := t.TempDir() | |
| 42 | + path := filepath.Join(root, "main.mbt") | |
| 43 | + writeFile(t, path, "fn main {\n println(\"hi\")\n}\n") | |
| 44 | + | |
| 45 | + editor := newTestEditor(t) | |
| 46 | + editor.Open(path) | |
| 47 | + | |
| 48 | + if got := editor.ActiveView().Language(); got != moonbitlang.Language { | |
| 49 | + t.Fatalf("the view colours the file as %q, want %q", got, moonbitlang.Language) | |
| 50 | + } | |
| 51 | + if spans := syntax.Highlight(moonbitlang.Language, "fn main {"); len(spans[0]) == 0 { | |
| 52 | + t.Error("the registered MoonBit scanner colours nothing") | |
| 53 | + } | |
| 54 | +} | |
| 55 | + | |
| 56 | +func TestAnInterfaceFileIsMoonBitToo(t *testing.T) { | |
| 57 | + // A .mbti is generated by `moon info` and read in review. It is MoonBit | |
| 58 | + // and nothing else, so it opens coloured. | |
| 59 | + root := t.TempDir() | |
| 60 | + path := filepath.Join(root, "pkg.generated.mbti") | |
| 61 | + writeFile(t, path, "package \"example/demo\"\n\npub fn helper() -> Int\n") | |
| 62 | + | |
| 63 | + editor := newTestEditor(t) | |
| 64 | + editor.Open(path) | |
| 65 | + | |
| 66 | + if got := editor.ActiveView().Language(); got != moonbitlang.Language { | |
| 67 | + t.Errorf("a .mbti file is coloured as %q, want %q", got, moonbitlang.Language) | |
| 68 | + } | |
| 69 | +} | |
| 70 | + | |
| 71 | +func TestTheEditorDoesNotColourPython(t *testing.T) { | |
| 72 | + // "MoonBit instead of Python" is the whole point of this editor being a | |
| 73 | + // separate one: a .py file opens as plain text here. | |
| 74 | + root := t.TempDir() | |
| 75 | + path := filepath.Join(root, "main.py") | |
| 76 | + writeFile(t, path, "def main() -> None:\n pass\n") | |
| 77 | + | |
| 78 | + editor := newTestEditor(t) | |
| 79 | + editor.Open(path) | |
| 80 | + | |
| 81 | + if got := editor.ActiveView().Language(); got != syntax.LanguageNone { | |
| 82 | + t.Errorf("a .py file is coloured as %q; Turbo MoonBit registers MoonBit, not Python", got) | |
| 83 | + } | |
| 84 | +} | |
| 85 | + | |
| 86 | +func TestAProjectsOwnFilesAreStillColouredByTheLibrary(t *testing.T) { | |
| 87 | + // moon.pkg.json and a README are what a MoonBit project is made of besides | |
| 88 | + // its source, and turbo-core colours both without this editor doing | |
| 89 | + // anything. That the inherited languages survive registration is worth one | |
| 90 | + // test, because syntax.Register writes into package-level state. | |
| 91 | + root := t.TempDir() | |
| 92 | + editor := newTestEditor(t) | |
| 93 | + | |
| 94 | + for name, want := range map[string]syntax.Language{ | |
| 95 | + "README.md": syntax.LanguageMarkdown, | |
| 96 | + "README.mbt.md": syntax.LanguageMarkdown, | |
| 97 | + "ci.yml": syntax.LanguageYAML, | |
| 98 | + } { | |
| 99 | + path := filepath.Join(root, name) | |
| 100 | + writeFile(t, path, "# heading\n") | |
| 101 | + editor.Open(path) | |
| 102 | + | |
| 103 | + if got := editor.ActiveView().Language(); got != want { | |
| 104 | + t.Errorf("%s is coloured as %q, want %q", name, got, want) | |
| 105 | + } | |
| 106 | + } | |
| 107 | +} | |
| 108 | + | |
| 109 | +func TestTheToolchainMenuIsCalledMoonBitAndNoTwoMenusShareAHotKey(t *testing.T) { | |
| 110 | + // The bar answers the first menu whose hot key matches, so a clash makes | |
| 111 | + // one of the two unreachable from the keyboard — silently, and with every | |
| 112 | + // other test still passing. MoonBit takes M because none of the fixed menus | |
| 113 | + // does, which is exactly the sort of thing only this test notices. | |
| 114 | + editor := newTestEditor(t) | |
| 115 | + | |
| 116 | + seen := map[rune]string{} | |
| 117 | + found := false | |
| 118 | + for _, menu := range editor.MenuBar().Menus() { | |
| 119 | + label, hot, _ := ui.SplitHotKey(menu.Label) | |
| 120 | + if label == "MoonBit" { | |
| 121 | + found = true | |
| 122 | + } | |
| 123 | + if hot == 0 { | |
| 124 | + t.Errorf("the %q menu has no hot key", label) | |
| 125 | + continue | |
| 126 | + } | |
| 127 | + if other, clash := seen[hot]; clash { | |
| 128 | + t.Errorf("%q and %q both answer to Alt-%c", other, label, hot) | |
| 129 | + } | |
| 130 | + seen[hot] = label | |
| 131 | + } | |
| 132 | + if !found { | |
| 133 | + t.Error("there is no MoonBit menu on the bar") | |
| 134 | + } | |
| 135 | +} | |
| 136 | + | |
| 137 | +// --- driven against a real moon-lsp ----------------------------------------- | |
| 138 | + | |
| 139 | +// TestCompletionEndToEndWithRealMoonLSP drives the exact sequence the command | |
| 140 | +// does at start-up: open the files first, start the language server second, | |
| 141 | +// then ask for a completion. | |
| 142 | +// | |
| 143 | +// That order is the whole point, and it is the one Turbo Go got wrong once: an | |
| 144 | +// editor that announces its open documents to a server which does not exist yet | |
| 145 | +// and never mentions them again gets answers about a file the server has never | |
| 146 | +// heard of — which looks, from the outside, exactly like completion not | |
| 147 | +// working. | |
| 148 | +// | |
| 149 | +// It skips itself when the MoonBit toolchain is not installed, and under | |
| 150 | +// -short. | |
| 151 | +func TestCompletionEndToEndWithRealMoonLSP(t *testing.T) { | |
| 152 | + root, editor := startRealServer(t) | |
| 153 | + | |
| 154 | + // The line on disk is blank. The text the completion is about gets *typed* | |
| 155 | + // below, so the answer can only come from what the editor told the server — | |
| 156 | + // which is the whole point of this test. A fixture already containing | |
| 157 | + // "text." would be answered from disk, and would pass whether or not the | |
| 158 | + // editor said anything at all. | |
| 159 | + path := filepath.Join(root, "main.mbt") | |
| 160 | + | |
| 161 | + view := editor.ActiveView() | |
| 162 | + view.Buffer().SetCursor(buffer.Position{Line: completionLine, Col: 2}) | |
| 163 | + typeText(editor, "text.") | |
| 164 | + | |
| 165 | + // Typing the dot asks for a completion by itself, but a server that is | |
| 166 | + // still indexing answers nothing at all. Asking again until it answers is | |
| 167 | + // what a person does too. | |
| 168 | + if !waitForCompletion(t, editor) { | |
| 169 | + t.Fatalf("no completion list opened for %s; the status bar says %q", path, editor.StatusBar().Message()) | |
| 170 | + } | |
| 171 | + // length() is a String method, so an answer holding it is an answer about | |
| 172 | + // the *type* of the name that was typed, not a list of every word in the | |
| 173 | + // file. | |
| 174 | + if !completionOffers(editor, "length") { | |
| 175 | + t.Errorf("the list does not offer String's length; it has %d entries", editor.Completion().Count()) | |
| 176 | + } | |
| 177 | +} | |
| 178 | + | |
| 179 | +// Several answers, not one. An earlier version of the library took the first | |
| 180 | +// location and threw the rest away, so a name used in three places sent you to | |
| 181 | +// whichever one the server happened to list first. | |
| 182 | +func TestReferencesAcrossAFileWithRealMoonLSP(t *testing.T) { | |
| 183 | + root, editor := startRealServer(t) | |
| 184 | + path := filepath.Join(root, "main.mbt") | |
| 185 | + | |
| 186 | + locations := waitForLocations(t, func(ctx context.Context) ([]lsp.Location, error) { | |
| 187 | + return editor.Language().References(ctx, path, helperLine, helperColumn, helperLineText) | |
| 188 | + }) | |
| 189 | + | |
| 190 | + if len(locations) < 3 { | |
| 191 | + t.Errorf("helper has %d references, want at least 3 — its declaration and its two call sites: %v", | |
| 192 | + len(locations), locations) | |
| 193 | + } | |
| 194 | +} | |
| 195 | + | |
| 196 | +func TestGoToDefinitionWithRealMoonLSP(t *testing.T) { | |
| 197 | + root, editor := startRealServer(t) | |
| 198 | + path := filepath.Join(root, "main.mbt") | |
| 199 | + | |
| 200 | + locations := waitForLocations(t, func(ctx context.Context) ([]lsp.Location, error) { | |
| 201 | + return editor.Language().Definition(ctx, path, callLine, callColumn, callLineText) | |
| 202 | + }) | |
| 203 | + | |
| 204 | + if len(locations) != 1 { | |
| 205 | + t.Fatalf("the call to helper has %d definitions, want exactly 1: %v", len(locations), locations) | |
| 206 | + } | |
| 207 | + if got := locations[0].Range.Start.Line; got != helperLine { | |
| 208 | + t.Errorf("the definition of helper is on line %d, want %d", got, helperLine) | |
| 209 | + } | |
| 210 | +} | |
| 211 | + | |
| 212 | +func TestTheSymbolsOfAFileWithRealMoonLSP(t *testing.T) { | |
| 213 | + root, editor := startRealServer(t) | |
| 214 | + path := filepath.Join(root, "main.mbt") | |
| 215 | + | |
| 216 | + var symbols []lsp.Symbol | |
| 217 | + waitUntil(t, 30*time.Second, func() bool { | |
| 218 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | |
| 219 | + defer cancel() | |
| 220 | + found, err := editor.Language().DocumentSymbols(ctx, path) | |
| 221 | + if err != nil { | |
| 222 | + return false | |
| 223 | + } | |
| 224 | + symbols = found | |
| 225 | + return len(symbols) > 0 | |
| 226 | + }) | |
| 227 | + | |
| 228 | + names := map[string]bool{} | |
| 229 | + for _, symbol := range symbols { | |
| 230 | + names[symbol.Name] = true | |
| 231 | + } | |
| 232 | + for _, want := range []string{"helper", "first", "second", "main"} { | |
| 233 | + if !names[want] { | |
| 234 | + t.Errorf("the file's symbols do not include %q: %v", want, names) | |
| 235 | + } | |
| 236 | + } | |
| 237 | +} | |
| 238 | + | |
| 239 | +func TestTheProjectsSymbolsWithRealMoonLSP(t *testing.T) { | |
| 240 | + // moon-lsp advertises workspaceSymbolProvider, which pylsp does not — so | |
| 241 | + // Code ▸ Symbol in project and Ctrl-T really answer here. | |
| 242 | + _, editor := startRealServer(t) | |
| 243 | + | |
| 244 | + var symbols []lsp.Symbol | |
| 245 | + waitUntil(t, 30*time.Second, func() bool { | |
| 246 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | |
| 247 | + defer cancel() | |
| 248 | + found, err := editor.Language().WorkspaceSymbols(ctx, "helper") | |
| 249 | + if err != nil { | |
| 250 | + return false | |
| 251 | + } | |
| 252 | + symbols = found | |
| 253 | + return len(symbols) > 0 | |
| 254 | + }) | |
| 255 | + | |
| 256 | + if len(symbols) == 0 { | |
| 257 | + t.Error("moon-lsp answered no project-wide symbols for \"helper\"") | |
| 258 | + } | |
| 259 | +} | |
| 260 | + | |
| 261 | +// Diagnostics are the one thing a language server sends without being asked, | |
| 262 | +// and the only feature whose failure looks exactly like success: an editor with | |
| 263 | +// no error to show and one that cannot find the error are the same blank | |
| 264 | +// gutter. So this opens a file that does not compile and waits for the mark. | |
| 265 | +// | |
| 266 | +// The file is on disk before the server starts, which is what a person actually | |
| 267 | +// does — the code was already broken when they opened it. The other order does | |
| 268 | +// not work, and the test below says so rather than leaving it to be discovered. | |
| 269 | +func TestDiagnosticsForAFileThatDoesNotCompileWithRealMoonLSP(t *testing.T) { | |
| 270 | + root, editor := startRealServerOn(t, brokenProject) | |
| 271 | + path := filepath.Join(root, "main.mbt") | |
| 272 | + | |
| 273 | + waitUntil(t, 30*time.Second, func() bool { | |
| 274 | + editor.Tick() | |
| 275 | + return len(editor.Language().Diagnostics(path)) > 0 | |
| 276 | + }) | |
| 277 | + | |
| 278 | + problems := editor.Language().Diagnostics(path) | |
| 279 | + if len(problems) == 0 { | |
| 280 | + t.Fatalf("no diagnostic ever arrived for %s; the status bar says %q", path, editor.StatusBar().Message()) | |
| 281 | + } | |
| 282 | + if _, ok := editor.Language().FirstError(path); !ok { | |
| 283 | + t.Errorf("the diagnostics hold no error, only %v", problems) | |
| 284 | + } | |
| 285 | +} | |
| 286 | + | |
| 287 | +// A .mbt file that did not exist when moon-lsp first analysed the package is | |
| 288 | +// diagnosed from its first save. It was not, until turbo-core v1.0.2: the | |
| 289 | +// server works out which files a package holds from the directory, and a | |
| 290 | +// document being open and a file existing are two different facts to it — a | |
| 291 | +// file saved for the first time got no diagnostics however loudly the document | |
| 292 | +// had been announced, until the editor also sent | |
| 293 | +// workspace/didChangeWatchedFiles. The test that pinned that limit went red on | |
| 294 | +// macOS on 2026-09-19, where moon-lsp evidently notices new files by itself; | |
| 295 | +// on Linux it does not, and the notification is what makes this pass. | |
| 296 | +// | |
| 297 | +// The scenario is the one a person lives: `turbo-moonbit late.mbt` on a file | |
| 298 | +// that is not there yet, type, and let the save happen — here automatic | |
| 299 | +// saving, the one exported way to write a buffer without a dialog. | |
| 300 | +func TestAFileCreatedInTheEditorIsDiagnosedFromItsFirstSaveWithRealMoonLSP(t *testing.T) { | |
| 301 | + root, editor := startRealServer(t) | |
| 302 | + | |
| 303 | + late := filepath.Join(root, "late.mbt") | |
| 304 | + editor.Open(late) // not on disk: an empty buffer with that name | |
| 305 | + editor.Tick() | |
| 306 | + editor.SetAutosave(true, 10*time.Millisecond) | |
| 307 | + typeText(editor, "///|\nfn oops() -> Int {\n undefined_name()\n}\n") | |
| 308 | + | |
| 309 | + waitUntil(t, 30*time.Second, func() bool { | |
| 310 | + editor.Tick() | |
| 311 | + return len(editor.Language().Diagnostics(late)) > 0 | |
| 312 | + }) | |
| 313 | + | |
| 314 | + if _, err := os.Stat(late); err != nil { | |
| 315 | + t.Fatalf("the file was never written, so this proves nothing about the server: %v", err) | |
| 316 | + } | |
| 317 | + if !editor.Language().Knows(late) { | |
| 318 | + t.Error("the editor never told the server about the new file") | |
| 319 | + } | |
| 320 | + if len(editor.Language().Diagnostics(late)) == 0 { | |
| 321 | + t.Errorf("no diagnostic arrived for a file created after the server started; the status bar says %q", editor.StatusBar().Message()) | |
| 322 | + } | |
| 323 | +} | |
| 324 | + | |
| 325 | +// moon-lsp advertises neither typeDefinitionProvider nor implementationProvider, | |
| 326 | +// so two of the nine questions turbo-core asks come back empty. That is | |
| 327 | +// documented in how-to/enable-completion.md, and this test is what keeps the | |
| 328 | +// documentation honest: if a future moon-lsp answers either of them, this fails | |
| 329 | +// and the page gets revisited. | |
| 330 | +func TestMoonLSPAnswersNeitherTypeDefinitionsNorImplementations(t *testing.T) { | |
| 331 | + root, editor := startRealServer(t) | |
| 332 | + path := filepath.Join(root, "main.mbt") | |
| 333 | + | |
| 334 | + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) | |
| 335 | + defer cancel() | |
| 336 | + | |
| 337 | + if found, err := editor.Language().TypeDefinition(ctx, path, helperLine, helperColumn, helperLineText); err == nil && len(found) > 0 { | |
| 338 | + t.Errorf("moon-lsp now answers type definitions (%v); how-to/enable-completion.md says it does not", found) | |
| 339 | + } | |
| 340 | + if found, err := editor.Language().Implementation(ctx, path, helperLine, helperColumn, helperLineText); err == nil && len(found) > 0 { | |
| 341 | + t.Errorf("moon-lsp now answers implementations (%v); how-to/enable-completion.md says it does not", found) | |
| 342 | + } | |
| 343 | +} | |
| 344 | + | |
| 345 | +// --- the fixtures and the waiting ------------------------------------------- | |
| 346 | + | |
| 347 | +// realProject is the file every language-server test works against. Line | |
| 348 | +// numbers are counted from zero and are named by the constants below, so | |
| 349 | +// inserting a line here moves them and the constants have to move too. | |
| 350 | +// | |
| 351 | +// 0 ///| | |
| 352 | +// 1 fn helper() -> Int { | |
| 353 | +// 2 1 | |
| 354 | +// 3 } | |
| 355 | +// 4 | |
| 356 | +// 5 ///| | |
| 357 | +// 6 fn first() -> Int { | |
| 358 | +// 7 helper() | |
| 359 | +// 8 } | |
| 360 | +// 9 | |
| 361 | +// 10 ///| | |
| 362 | +// 11 fn second() -> Int { | |
| 363 | +// 12 helper() + 1 | |
| 364 | +// 13 } | |
| 365 | +// 14 | |
| 366 | +// 15 ///| | |
| 367 | +// 16 fn main { | |
| 368 | +// 17 let text = "hi" | |
| 369 | +// 18 ← two spaces, and where the completion is typed | |
| 370 | +// 19 println(first() + second() + text.length()) | |
| 371 | +// 20 } | |
| 372 | +// | |
| 373 | +// It compiles with no errors and no warnings under `moon check`, which matters: | |
| 374 | +// a fixture the toolchain complains about would make the diagnostics test pass | |
| 375 | +// for the wrong reason. | |
| 376 | +const realProject = "///|\n" + | |
| 377 | + "fn helper() -> Int {\n" + | |
| 378 | + " 1\n" + | |
| 379 | + "}\n" + | |
| 380 | + "\n" + | |
| 381 | + "///|\n" + | |
| 382 | + "fn first() -> Int {\n" + | |
| 383 | + " helper()\n" + | |
| 384 | + "}\n" + | |
| 385 | + "\n" + | |
| 386 | + "///|\n" + | |
| 387 | + "fn second() -> Int {\n" + | |
| 388 | + " helper() + 1\n" + | |
| 389 | + "}\n" + | |
| 390 | + "\n" + | |
| 391 | + "///|\n" + | |
| 392 | + "fn main {\n" + | |
| 393 | + " let text = \"hi\"\n" + | |
| 394 | + " \n" + | |
| 395 | + " println(first() + second() + text.length())\n" + | |
| 396 | + "}\n" | |
| 397 | + | |
| 398 | +// brokenProject is a project whose one file does not compile. It exists as a | |
| 399 | +// second fixture rather than as a file added to the first, because a package | |
| 400 | +// holding an error is a package whose *other* answers are worth nothing: the | |
| 401 | +// completion test would then be measuring a broken build. | |
| 402 | +const brokenProject = "///|\n" + | |
| 403 | + "fn main {\n" + | |
| 404 | + " undefined_name()\n" + | |
| 405 | + "}\n" | |
| 406 | + | |
| 407 | +// Where the fixture's interesting lines are, counted from zero. | |
| 408 | +const ( | |
| 409 | + completionLine = 18 | |
| 410 | + helperLine = 1 | |
| 411 | + helperColumn = 3 | |
| 412 | + helperLineText = "fn helper() -> Int {" | |
| 413 | + callLine = 7 | |
| 414 | + callColumn = 2 | |
| 415 | + callLineText = " helper()" | |
| 416 | +) | |
| 417 | + | |
| 418 | +// startRealServer writes a project, opens its file, starts moon-lsp and waits | |
| 419 | +// for it, in the order the command does. It skips the test when the MoonBit | |
| 420 | +// toolchain is missing. | |
| 421 | +func startRealServer(t *testing.T) (root string, editor *app.App) { | |
| 422 | + t.Helper() | |
| 423 | + return startRealServerOn(t, realProject) | |
| 424 | +} | |
| 425 | + | |
| 426 | +// startRealServerOn is startRealServer over a chosen main.mbt. | |
| 427 | +func startRealServerOn(t *testing.T, source string) (root string, editor *app.App) { | |
| 428 | + t.Helper() | |
| 429 | + if testing.Short() { | |
| 430 | + t.Skip("-short: not starting a language server") | |
| 431 | + } | |
| 432 | + | |
| 433 | + server, err := lsp.FindServer(moonbitlang.Profile().Server) | |
| 434 | + if errors.Is(err, lsp.ErrServerNotFound) { | |
| 435 | + t.Skipf("%s is not installed; %s", moonbitlang.ServerCommand, moonbitlang.InstallHint) | |
| 436 | + } | |
| 437 | + // Finding it is not the same as being able to run it: a shim left behind by | |
| 438 | + // a tool manager whose environment has since been removed is on PATH and | |
| 439 | + // fails only when started. | |
| 440 | + if !serverRuns(server) { | |
| 441 | + t.Skipf("%s at %s cannot run; %s", moonbitlang.ServerCommand, server, moonbitlang.InstallHint) | |
| 442 | + } | |
| 443 | + | |
| 444 | + root = t.TempDir() | |
| 445 | + writeFile(t, filepath.Join(root, "moon.mod"), "name = \"example/demo\"\nversion = \"0.1.0\"\n") | |
| 446 | + writeFile(t, filepath.Join(root, "moon.pkg"), "pkgtype(kind: \"executable\")\n") | |
| 447 | + writeFile(t, filepath.Join(root, "main.mbt"), source) | |
| 448 | + | |
| 449 | + editor = newTestEditor(t) | |
| 450 | + | |
| 451 | + // 1. Open the file, exactly as main does — before there is any server. | |
| 452 | + editor.Open(filepath.Join(root, "main.mbt")) | |
| 453 | + | |
| 454 | + // 2. Start the language server, exactly as main does — afterwards. | |
| 455 | + ctx, cancel := context.WithCancel(t.Context()) | |
| 456 | + t.Cleanup(cancel) | |
| 457 | + editor.StartLanguageServer(ctx, root) | |
| 458 | + t.Cleanup(func() { editor.Language().Stop(context.Background()) }) | |
| 459 | + | |
| 460 | + waitUntilReady(t, editor) | |
| 461 | + | |
| 462 | + // 3. Let the event loop notice the server is ready, as Run does on every | |
| 463 | + // turn. This is what announces the file that was already open. | |
| 464 | + editor.Tick() | |
| 465 | + return root, editor | |
| 466 | +} | |
| 467 | + | |
| 468 | +// newTestEditor returns Turbo MoonBit drawing on a simulated terminal, set up | |
| 469 | +// the way the command sets it up. | |
| 470 | +func newTestEditor(t *testing.T) *app.App { | |
| 471 | + t.Helper() | |
| 472 | + | |
| 473 | + moonbitlang.Register() | |
| 474 | + screen := tcell.NewSimulationScreen("UTF-8") | |
| 475 | + if err := screen.Init(); err != nil { | |
| 476 | + t.Fatalf("initialising the simulation screen: %v", err) | |
| 477 | + } | |
| 478 | + t.Cleanup(screen.Fini) | |
| 479 | + screen.SetSize(80, 24) | |
| 480 | + | |
| 481 | + // Never read the themes or snippets of whoever is running the tests. | |
| 482 | + p := moonbitlang.Profile() | |
| 483 | + t.Setenv(p.ThemeDirEnvVar(), t.TempDir()) | |
| 484 | + t.Setenv(p.SnippetDirEnvVar(), t.TempDir()) | |
| 485 | + | |
| 486 | + editor := app.New(screen, "turbo-classic", p) | |
| 487 | + editor.Render() | |
| 488 | + return editor | |
| 489 | +} | |
| 490 | + | |
| 491 | +// typeText sends a run of printable characters through the whole routing chain. | |
| 492 | +func typeText(editor *app.App, text string) { | |
| 493 | + for _, r := range text { | |
| 494 | + // A newline is the Enter key, not a rune: typed as a rune it is | |
| 495 | + // dropped, and a fixture meant to span four lines lands on one — | |
| 496 | + // where `///|` turns the whole of it into a doc comment. | |
| 497 | + if r == '\n' { | |
| 498 | + editor.Handle(tcell.NewEventKey(tcell.KeyEnter, 0, tcell.ModNone)) | |
| 499 | + continue | |
| 500 | + } | |
| 501 | + editor.Handle(tcell.NewEventKey(tcell.KeyRune, r, tcell.ModNone)) | |
| 502 | + } | |
| 503 | +} | |
| 504 | + | |
| 505 | +// completionOffers reports whether the open popup holds an entry starting with | |
| 506 | +// a label. | |
| 507 | +func completionOffers(editor *app.App, label string) bool { | |
| 508 | + for _, item := range editor.Completion().Matches() { | |
| 509 | + if strings.HasPrefix(item.Label, label) { | |
| 510 | + return true | |
| 511 | + } | |
| 512 | + } | |
| 513 | + return false | |
| 514 | +} | |
| 515 | + | |
| 516 | +// waitUntilReady blocks until the language server has finished starting. | |
| 517 | +func waitUntilReady(t *testing.T, editor *app.App) { | |
| 518 | + t.Helper() | |
| 519 | + | |
| 520 | + deadline := time.After(lsp.InitializeTimeout) | |
| 521 | + for !editor.Language().Ready() { | |
| 522 | + select { | |
| 523 | + case <-deadline: | |
| 524 | + t.Fatalf("the language server never became ready: %s", editor.Language().Status()) | |
| 525 | + case <-time.After(10 * time.Millisecond): | |
| 526 | + } | |
| 527 | + } | |
| 528 | +} | |
| 529 | + | |
| 530 | +// waitUntil polls a condition until it holds or the time runs out, and fails | |
| 531 | +// the test if it never does. | |
| 532 | +func waitUntil(t *testing.T, within time.Duration, done func() bool) { | |
| 533 | + t.Helper() | |
| 534 | + | |
| 535 | + deadline := time.Now().Add(within) | |
| 536 | + for time.Now().Before(deadline) { | |
| 537 | + if done() { | |
| 538 | + return | |
| 539 | + } | |
| 540 | + time.Sleep(200 * time.Millisecond) | |
| 541 | + } | |
| 542 | + t.Errorf("the server never answered within %s", within) | |
| 543 | +} | |
| 544 | + | |
| 545 | +// waitForLocations asks a location question until it is answered, because a | |
| 546 | +// server that is still indexing answers an empty list rather than an error. | |
| 547 | +func waitForLocations(t *testing.T, ask func(context.Context) ([]lsp.Location, error)) []lsp.Location { | |
| 548 | + t.Helper() | |
| 549 | + | |
| 550 | + var found []lsp.Location | |
| 551 | + waitUntil(t, 30*time.Second, func() bool { | |
| 552 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | |
| 553 | + defer cancel() | |
| 554 | + | |
| 555 | + locations, err := ask(ctx) | |
| 556 | + if err != nil { | |
| 557 | + return false | |
| 558 | + } | |
| 559 | + found = locations | |
| 560 | + return len(found) > 0 | |
| 561 | + }) | |
| 562 | + return found | |
| 563 | +} | |
| 564 | + | |
| 565 | +// waitForCompletion asks for a completion until one arrives, or gives up. | |
| 566 | +// | |
| 567 | +// A server loads the workspace after it has finished initialising, and answers | |
| 568 | +// an empty list until that is done. There is no notification this client reads | |
| 569 | +// that says when — so it asks again, which is what the editor's user would do. | |
| 570 | +func waitForCompletion(t *testing.T, editor *app.App) bool { | |
| 571 | + t.Helper() | |
| 572 | + | |
| 573 | + deadline := time.Now().Add(60 * time.Second) | |
| 574 | + for time.Now().Before(deadline) { | |
| 575 | + if editor.Completion().Visible() { | |
| 576 | + return true | |
| 577 | + } | |
| 578 | + editor.RequestCompletion() | |
| 579 | + if editor.Completion().Visible() { | |
| 580 | + return true | |
| 581 | + } | |
| 582 | + time.Sleep(500 * time.Millisecond) | |
| 583 | + } | |
| 584 | + return false | |
| 585 | +} | |
| 586 | + | |
| 587 | +// serverRuns reports whether the language server at path actually starts. | |
| 588 | +func serverRuns(path string) bool { | |
| 589 | + return exec.Command(path, "--version").Run() == nil | |
| 590 | +} | |
| 591 | + | |
| 592 | +// writeFile creates a file, making its directory first. | |
| 593 | +func writeFile(t *testing.T, path, content string) { | |
| 594 | + t.Helper() | |
| 595 | + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { | |
| 596 | + t.Fatalf("creating %s: %v", filepath.Dir(path), err) | |
| 597 | + } | |
| 598 | + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { | |
| 599 | + t.Fatalf("writing %s: %v", path, err) | |
| 600 | + } | |
| 601 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,601 @@ | |||
| 1 | +package moonbitlang_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-moonbit/internal/moonbitlang" | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +// --- the editor, assembled -------------------------------------------------- | ||
| 25 | + | ||
| 26 | +func TestTheEditorCallsItselfTurboMoonBit(t *testing.T) { | ||
| 27 | + editor := newTestEditor(t) | ||
| 28 | + | ||
| 29 | + if got := editor.Profile().Name; got != moonbitlang.Name { | ||
| 30 | + t.Errorf("Profile().Name = %q, want %q", got, moonbitlang.Name) | ||
| 31 | + } | ||
| 32 | + if got := editor.Profile().ProjectDir(); got != ".turbo-moonbit" { | ||
| 33 | + t.Errorf("ProjectDir() = %q, want %q", got, ".turbo-moonbit") | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +func TestTheEditorColoursMoonBitSourceItOpens(t *testing.T) { | ||
| 38 | + // The whole path in one test: Register taught the library about MoonBit, | ||
| 39 | + // the profile named the editor, and a .mbt file opened through the public | ||
| 40 | + // API comes out coloured. | ||
| 41 | + root := t.TempDir() | ||
| 42 | + path := filepath.Join(root, "main.mbt") | ||
| 43 | + writeFile(t, path, "fn main {\n println(\"hi\")\n}\n") | ||
| 44 | + | ||
| 45 | + editor := newTestEditor(t) | ||
| 46 | + editor.Open(path) | ||
| 47 | + | ||
| 48 | + if got := editor.ActiveView().Language(); got != moonbitlang.Language { | ||
| 49 | + t.Fatalf("the view colours the file as %q, want %q", got, moonbitlang.Language) | ||
| 50 | + } | ||
| 51 | + if spans := syntax.Highlight(moonbitlang.Language, "fn main {"); len(spans[0]) == 0 { | ||
| 52 | + t.Error("the registered MoonBit scanner colours nothing") | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +func TestAnInterfaceFileIsMoonBitToo(t *testing.T) { | ||
| 57 | + // A .mbti is generated by `moon info` and read in review. It is MoonBit | ||
| 58 | + // and nothing else, so it opens coloured. | ||
| 59 | + root := t.TempDir() | ||
| 60 | + path := filepath.Join(root, "pkg.generated.mbti") | ||
| 61 | + writeFile(t, path, "package \"example/demo\"\n\npub fn helper() -> Int\n") | ||
| 62 | + | ||
| 63 | + editor := newTestEditor(t) | ||
| 64 | + editor.Open(path) | ||
| 65 | + | ||
| 66 | + if got := editor.ActiveView().Language(); got != moonbitlang.Language { | ||
| 67 | + t.Errorf("a .mbti file is coloured as %q, want %q", got, moonbitlang.Language) | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +func TestTheEditorDoesNotColourPython(t *testing.T) { | ||
| 72 | + // "MoonBit instead of Python" is the whole point of this editor being a | ||
| 73 | + // separate one: a .py file opens as plain text here. | ||
| 74 | + root := t.TempDir() | ||
| 75 | + path := filepath.Join(root, "main.py") | ||
| 76 | + writeFile(t, path, "def main() -> None:\n pass\n") | ||
| 77 | + | ||
| 78 | + editor := newTestEditor(t) | ||
| 79 | + editor.Open(path) | ||
| 80 | + | ||
| 81 | + if got := editor.ActiveView().Language(); got != syntax.LanguageNone { | ||
| 82 | + t.Errorf("a .py file is coloured as %q; Turbo MoonBit registers MoonBit, not Python", got) | ||
| 83 | + } | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +func TestAProjectsOwnFilesAreStillColouredByTheLibrary(t *testing.T) { | ||
| 87 | + // moon.pkg.json and a README are what a MoonBit project is made of besides | ||
| 88 | + // its source, and turbo-core colours both without this editor doing | ||
| 89 | + // anything. That the inherited languages survive registration is worth one | ||
| 90 | + // test, because syntax.Register writes into package-level state. | ||
| 91 | + root := t.TempDir() | ||
| 92 | + editor := newTestEditor(t) | ||
| 93 | + | ||
| 94 | + for name, want := range map[string]syntax.Language{ | ||
| 95 | + "README.md": syntax.LanguageMarkdown, | ||
| 96 | + "README.mbt.md": syntax.LanguageMarkdown, | ||
| 97 | + "ci.yml": syntax.LanguageYAML, | ||
| 98 | + } { | ||
| 99 | + path := filepath.Join(root, name) | ||
| 100 | + writeFile(t, path, "# heading\n") | ||
| 101 | + editor.Open(path) | ||
| 102 | + | ||
| 103 | + if got := editor.ActiveView().Language(); got != want { | ||
| 104 | + t.Errorf("%s is coloured as %q, want %q", name, got, want) | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | +} | ||
| 108 | + | ||
| 109 | +func TestTheToolchainMenuIsCalledMoonBitAndNoTwoMenusShareAHotKey(t *testing.T) { | ||
| 110 | + // The bar answers the first menu whose hot key matches, so a clash makes | ||
| 111 | + // one of the two unreachable from the keyboard — silently, and with every | ||
| 112 | + // other test still passing. MoonBit takes M because none of the fixed menus | ||
| 113 | + // does, which is exactly the sort of thing only this test notices. | ||
| 114 | + editor := newTestEditor(t) | ||
| 115 | + | ||
| 116 | + seen := map[rune]string{} | ||
| 117 | + found := false | ||
| 118 | + for _, menu := range editor.MenuBar().Menus() { | ||
| 119 | + label, hot, _ := ui.SplitHotKey(menu.Label) | ||
| 120 | + if label == "MoonBit" { | ||
| 121 | + found = true | ||
| 122 | + } | ||
| 123 | + if hot == 0 { | ||
| 124 | + t.Errorf("the %q menu has no hot key", label) | ||
| 125 | + continue | ||
| 126 | + } | ||
| 127 | + if other, clash := seen[hot]; clash { | ||
| 128 | + t.Errorf("%q and %q both answer to Alt-%c", other, label, hot) | ||
| 129 | + } | ||
| 130 | + seen[hot] = label | ||
| 131 | + } | ||
| 132 | + if !found { | ||
| 133 | + t.Error("there is no MoonBit menu on the bar") | ||
| 134 | + } | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +// --- driven against a real moon-lsp ----------------------------------------- | ||
| 138 | + | ||
| 139 | +// TestCompletionEndToEndWithRealMoonLSP drives the exact sequence the command | ||
| 140 | +// does at start-up: open the files first, start the language server second, | ||
| 141 | +// then ask for a completion. | ||
| 142 | +// | ||
| 143 | +// That order is the whole point, and it is the one Turbo Go got wrong once: an | ||
| 144 | +// editor that announces its open documents to a server which does not exist yet | ||
| 145 | +// and never mentions them again gets answers about a file the server has never | ||
| 146 | +// heard of — which looks, from the outside, exactly like completion not | ||
| 147 | +// working. | ||
| 148 | +// | ||
| 149 | +// It skips itself when the MoonBit toolchain is not installed, and under | ||
| 150 | +// -short. | ||
| 151 | +func TestCompletionEndToEndWithRealMoonLSP(t *testing.T) { | ||
| 152 | + root, editor := startRealServer(t) | ||
| 153 | + | ||
| 154 | + // The line on disk is blank. The text the completion is about gets *typed* | ||
| 155 | + // below, so the answer can only come from what the editor told the server — | ||
| 156 | + // which is the whole point of this test. A fixture already containing | ||
| 157 | + // "text." would be answered from disk, and would pass whether or not the | ||
| 158 | + // editor said anything at all. | ||
| 159 | + path := filepath.Join(root, "main.mbt") | ||
| 160 | + | ||
| 161 | + view := editor.ActiveView() | ||
| 162 | + view.Buffer().SetCursor(buffer.Position{Line: completionLine, Col: 2}) | ||
| 163 | + typeText(editor, "text.") | ||
| 164 | + | ||
| 165 | + // Typing the dot asks for a completion by itself, but a server that is | ||
| 166 | + // still indexing answers nothing at all. Asking again until it answers is | ||
| 167 | + // what a person does too. | ||
| 168 | + if !waitForCompletion(t, editor) { | ||
| 169 | + t.Fatalf("no completion list opened for %s; the status bar says %q", path, editor.StatusBar().Message()) | ||
| 170 | + } | ||
| 171 | + // length() is a String method, so an answer holding it is an answer about | ||
| 172 | + // the *type* of the name that was typed, not a list of every word in the | ||
| 173 | + // file. | ||
| 174 | + if !completionOffers(editor, "length") { | ||
| 175 | + t.Errorf("the list does not offer String's length; it has %d entries", editor.Completion().Count()) | ||
| 176 | + } | ||
| 177 | +} | ||
| 178 | + | ||
| 179 | +// Several answers, not one. An earlier version of the library took the first | ||
| 180 | +// location and threw the rest away, so a name used in three places sent you to | ||
| 181 | +// whichever one the server happened to list first. | ||
| 182 | +func TestReferencesAcrossAFileWithRealMoonLSP(t *testing.T) { | ||
| 183 | + root, editor := startRealServer(t) | ||
| 184 | + path := filepath.Join(root, "main.mbt") | ||
| 185 | + | ||
| 186 | + locations := waitForLocations(t, func(ctx context.Context) ([]lsp.Location, error) { | ||
| 187 | + return editor.Language().References(ctx, path, helperLine, helperColumn, helperLineText) | ||
| 188 | + }) | ||
| 189 | + | ||
| 190 | + if len(locations) < 3 { | ||
| 191 | + t.Errorf("helper has %d references, want at least 3 — its declaration and its two call sites: %v", | ||
| 192 | + len(locations), locations) | ||
| 193 | + } | ||
| 194 | +} | ||
| 195 | + | ||
| 196 | +func TestGoToDefinitionWithRealMoonLSP(t *testing.T) { | ||
| 197 | + root, editor := startRealServer(t) | ||
| 198 | + path := filepath.Join(root, "main.mbt") | ||
| 199 | + | ||
| 200 | + locations := waitForLocations(t, func(ctx context.Context) ([]lsp.Location, error) { | ||
| 201 | + return editor.Language().Definition(ctx, path, callLine, callColumn, callLineText) | ||
| 202 | + }) | ||
| 203 | + | ||
| 204 | + if len(locations) != 1 { | ||
| 205 | + t.Fatalf("the call to helper has %d definitions, want exactly 1: %v", len(locations), locations) | ||
| 206 | + } | ||
| 207 | + if got := locations[0].Range.Start.Line; got != helperLine { | ||
| 208 | + t.Errorf("the definition of helper is on line %d, want %d", got, helperLine) | ||
| 209 | + } | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +func TestTheSymbolsOfAFileWithRealMoonLSP(t *testing.T) { | ||
| 213 | + root, editor := startRealServer(t) | ||
| 214 | + path := filepath.Join(root, "main.mbt") | ||
| 215 | + | ||
| 216 | + var symbols []lsp.Symbol | ||
| 217 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 218 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | ||
| 219 | + defer cancel() | ||
| 220 | + found, err := editor.Language().DocumentSymbols(ctx, path) | ||
| 221 | + if err != nil { | ||
| 222 | + return false | ||
| 223 | + } | ||
| 224 | + symbols = found | ||
| 225 | + return len(symbols) > 0 | ||
| 226 | + }) | ||
| 227 | + | ||
| 228 | + names := map[string]bool{} | ||
| 229 | + for _, symbol := range symbols { | ||
| 230 | + names[symbol.Name] = true | ||
| 231 | + } | ||
| 232 | + for _, want := range []string{"helper", "first", "second", "main"} { | ||
| 233 | + if !names[want] { | ||
| 234 | + t.Errorf("the file's symbols do not include %q: %v", want, names) | ||
| 235 | + } | ||
| 236 | + } | ||
| 237 | +} | ||
| 238 | + | ||
| 239 | +func TestTheProjectsSymbolsWithRealMoonLSP(t *testing.T) { | ||
| 240 | + // moon-lsp advertises workspaceSymbolProvider, which pylsp does not — so | ||
| 241 | + // Code ▸ Symbol in project and Ctrl-T really answer here. | ||
| 242 | + _, editor := startRealServer(t) | ||
| 243 | + | ||
| 244 | + var symbols []lsp.Symbol | ||
| 245 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 246 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | ||
| 247 | + defer cancel() | ||
| 248 | + found, err := editor.Language().WorkspaceSymbols(ctx, "helper") | ||
| 249 | + if err != nil { | ||
| 250 | + return false | ||
| 251 | + } | ||
| 252 | + symbols = found | ||
| 253 | + return len(symbols) > 0 | ||
| 254 | + }) | ||
| 255 | + | ||
| 256 | + if len(symbols) == 0 { | ||
| 257 | + t.Error("moon-lsp answered no project-wide symbols for \"helper\"") | ||
| 258 | + } | ||
| 259 | +} | ||
| 260 | + | ||
| 261 | +// Diagnostics are the one thing a language server sends without being asked, | ||
| 262 | +// and the only feature whose failure looks exactly like success: an editor with | ||
| 263 | +// no error to show and one that cannot find the error are the same blank | ||
| 264 | +// gutter. So this opens a file that does not compile and waits for the mark. | ||
| 265 | +// | ||
| 266 | +// The file is on disk before the server starts, which is what a person actually | ||
| 267 | +// does — the code was already broken when they opened it. The other order does | ||
| 268 | +// not work, and the test below says so rather than leaving it to be discovered. | ||
| 269 | +func TestDiagnosticsForAFileThatDoesNotCompileWithRealMoonLSP(t *testing.T) { | ||
| 270 | + root, editor := startRealServerOn(t, brokenProject) | ||
| 271 | + path := filepath.Join(root, "main.mbt") | ||
| 272 | + | ||
| 273 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 274 | + editor.Tick() | ||
| 275 | + return len(editor.Language().Diagnostics(path)) > 0 | ||
| 276 | + }) | ||
| 277 | + | ||
| 278 | + problems := editor.Language().Diagnostics(path) | ||
| 279 | + if len(problems) == 0 { | ||
| 280 | + t.Fatalf("no diagnostic ever arrived for %s; the status bar says %q", path, editor.StatusBar().Message()) | ||
| 281 | + } | ||
| 282 | + if _, ok := editor.Language().FirstError(path); !ok { | ||
| 283 | + t.Errorf("the diagnostics hold no error, only %v", problems) | ||
| 284 | + } | ||
| 285 | +} | ||
| 286 | + | ||
| 287 | +// A .mbt file that did not exist when moon-lsp first analysed the package is | ||
| 288 | +// diagnosed from its first save. It was not, until turbo-core v1.0.2: the | ||
| 289 | +// server works out which files a package holds from the directory, and a | ||
| 290 | +// document being open and a file existing are two different facts to it — a | ||
| 291 | +// file saved for the first time got no diagnostics however loudly the document | ||
| 292 | +// had been announced, until the editor also sent | ||
| 293 | +// workspace/didChangeWatchedFiles. The test that pinned that limit went red on | ||
| 294 | +// macOS on 2026-09-19, where moon-lsp evidently notices new files by itself; | ||
| 295 | +// on Linux it does not, and the notification is what makes this pass. | ||
| 296 | +// | ||
| 297 | +// The scenario is the one a person lives: `turbo-moonbit late.mbt` on a file | ||
| 298 | +// that is not there yet, type, and let the save happen — here automatic | ||
| 299 | +// saving, the one exported way to write a buffer without a dialog. | ||
| 300 | +func TestAFileCreatedInTheEditorIsDiagnosedFromItsFirstSaveWithRealMoonLSP(t *testing.T) { | ||
| 301 | + root, editor := startRealServer(t) | ||
| 302 | + | ||
| 303 | + late := filepath.Join(root, "late.mbt") | ||
| 304 | + editor.Open(late) // not on disk: an empty buffer with that name | ||
| 305 | + editor.Tick() | ||
| 306 | + editor.SetAutosave(true, 10*time.Millisecond) | ||
| 307 | + typeText(editor, "///|\nfn oops() -> Int {\n undefined_name()\n}\n") | ||
| 308 | + | ||
| 309 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 310 | + editor.Tick() | ||
| 311 | + return len(editor.Language().Diagnostics(late)) > 0 | ||
| 312 | + }) | ||
| 313 | + | ||
| 314 | + if _, err := os.Stat(late); err != nil { | ||
| 315 | + t.Fatalf("the file was never written, so this proves nothing about the server: %v", err) | ||
| 316 | + } | ||
| 317 | + if !editor.Language().Knows(late) { | ||
| 318 | + t.Error("the editor never told the server about the new file") | ||
| 319 | + } | ||
| 320 | + if len(editor.Language().Diagnostics(late)) == 0 { | ||
| 321 | + t.Errorf("no diagnostic arrived for a file created after the server started; the status bar says %q", editor.StatusBar().Message()) | ||
| 322 | + } | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +// moon-lsp advertises neither typeDefinitionProvider nor implementationProvider, | ||
| 326 | +// so two of the nine questions turbo-core asks come back empty. That is | ||
| 327 | +// documented in how-to/enable-completion.md, and this test is what keeps the | ||
| 328 | +// documentation honest: if a future moon-lsp answers either of them, this fails | ||
| 329 | +// and the page gets revisited. | ||
| 330 | +func TestMoonLSPAnswersNeitherTypeDefinitionsNorImplementations(t *testing.T) { | ||
| 331 | + root, editor := startRealServer(t) | ||
| 332 | + path := filepath.Join(root, "main.mbt") | ||
| 333 | + | ||
| 334 | + ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) | ||
| 335 | + defer cancel() | ||
| 336 | + | ||
| 337 | + if found, err := editor.Language().TypeDefinition(ctx, path, helperLine, helperColumn, helperLineText); err == nil && len(found) > 0 { | ||
| 338 | + t.Errorf("moon-lsp now answers type definitions (%v); how-to/enable-completion.md says it does not", found) | ||
| 339 | + } | ||
| 340 | + if found, err := editor.Language().Implementation(ctx, path, helperLine, helperColumn, helperLineText); err == nil && len(found) > 0 { | ||
| 341 | + t.Errorf("moon-lsp now answers implementations (%v); how-to/enable-completion.md says it does not", found) | ||
| 342 | + } | ||
| 343 | +} | ||
| 344 | + | ||
| 345 | +// --- the fixtures and the waiting ------------------------------------------- | ||
| 346 | + | ||
| 347 | +// realProject is the file every language-server test works against. Line | ||
| 348 | +// numbers are counted from zero and are named by the constants below, so | ||
| 349 | +// inserting a line here moves them and the constants have to move too. | ||
| 350 | +// | ||
| 351 | +// 0 ///| | ||
| 352 | +// 1 fn helper() -> Int { | ||
| 353 | +// 2 1 | ||
| 354 | +// 3 } | ||
| 355 | +// 4 | ||
| 356 | +// 5 ///| | ||
| 357 | +// 6 fn first() -> Int { | ||
| 358 | +// 7 helper() | ||
| 359 | +// 8 } | ||
| 360 | +// 9 | ||
| 361 | +// 10 ///| | ||
| 362 | +// 11 fn second() -> Int { | ||
| 363 | +// 12 helper() + 1 | ||
| 364 | +// 13 } | ||
| 365 | +// 14 | ||
| 366 | +// 15 ///| | ||
| 367 | +// 16 fn main { | ||
| 368 | +// 17 let text = "hi" | ||
| 369 | +// 18 ← two spaces, and where the completion is typed | ||
| 370 | +// 19 println(first() + second() + text.length()) | ||
| 371 | +// 20 } | ||
| 372 | +// | ||
| 373 | +// It compiles with no errors and no warnings under `moon check`, which matters: | ||
| 374 | +// a fixture the toolchain complains about would make the diagnostics test pass | ||
| 375 | +// for the wrong reason. | ||
| 376 | +const realProject = "///|\n" + | ||
| 377 | + "fn helper() -> Int {\n" + | ||
| 378 | + " 1\n" + | ||
| 379 | + "}\n" + | ||
| 380 | + "\n" + | ||
| 381 | + "///|\n" + | ||
| 382 | + "fn first() -> Int {\n" + | ||
| 383 | + " helper()\n" + | ||
| 384 | + "}\n" + | ||
| 385 | + "\n" + | ||
| 386 | + "///|\n" + | ||
| 387 | + "fn second() -> Int {\n" + | ||
| 388 | + " helper() + 1\n" + | ||
| 389 | + "}\n" + | ||
| 390 | + "\n" + | ||
| 391 | + "///|\n" + | ||
| 392 | + "fn main {\n" + | ||
| 393 | + " let text = \"hi\"\n" + | ||
| 394 | + " \n" + | ||
| 395 | + " println(first() + second() + text.length())\n" + | ||
| 396 | + "}\n" | ||
| 397 | + | ||
| 398 | +// brokenProject is a project whose one file does not compile. It exists as a | ||
| 399 | +// second fixture rather than as a file added to the first, because a package | ||
| 400 | +// holding an error is a package whose *other* answers are worth nothing: the | ||
| 401 | +// completion test would then be measuring a broken build. | ||
| 402 | +const brokenProject = "///|\n" + | ||
| 403 | + "fn main {\n" + | ||
| 404 | + " undefined_name()\n" + | ||
| 405 | + "}\n" | ||
| 406 | + | ||
| 407 | +// Where the fixture's interesting lines are, counted from zero. | ||
| 408 | +const ( | ||
| 409 | + completionLine = 18 | ||
| 410 | + helperLine = 1 | ||
| 411 | + helperColumn = 3 | ||
| 412 | + helperLineText = "fn helper() -> Int {" | ||
| 413 | + callLine = 7 | ||
| 414 | + callColumn = 2 | ||
| 415 | + callLineText = " helper()" | ||
| 416 | +) | ||
| 417 | + | ||
| 418 | +// startRealServer writes a project, opens its file, starts moon-lsp and waits | ||
| 419 | +// for it, in the order the command does. It skips the test when the MoonBit | ||
| 420 | +// toolchain is missing. | ||
| 421 | +func startRealServer(t *testing.T) (root string, editor *app.App) { | ||
| 422 | + t.Helper() | ||
| 423 | + return startRealServerOn(t, realProject) | ||
| 424 | +} | ||
| 425 | + | ||
| 426 | +// startRealServerOn is startRealServer over a chosen main.mbt. | ||
| 427 | +func startRealServerOn(t *testing.T, source string) (root string, editor *app.App) { | ||
| 428 | + t.Helper() | ||
| 429 | + if testing.Short() { | ||
| 430 | + t.Skip("-short: not starting a language server") | ||
| 431 | + } | ||
| 432 | + | ||
| 433 | + server, err := lsp.FindServer(moonbitlang.Profile().Server) | ||
| 434 | + if errors.Is(err, lsp.ErrServerNotFound) { | ||
| 435 | + t.Skipf("%s is not installed; %s", moonbitlang.ServerCommand, moonbitlang.InstallHint) | ||
| 436 | + } | ||
| 437 | + // Finding it is not the same as being able to run it: a shim left behind by | ||
| 438 | + // a tool manager whose environment has since been removed is on PATH and | ||
| 439 | + // fails only when started. | ||
| 440 | + if !serverRuns(server) { | ||
| 441 | + t.Skipf("%s at %s cannot run; %s", moonbitlang.ServerCommand, server, moonbitlang.InstallHint) | ||
| 442 | + } | ||
| 443 | + | ||
| 444 | + root = t.TempDir() | ||
| 445 | + writeFile(t, filepath.Join(root, "moon.mod"), "name = \"example/demo\"\nversion = \"0.1.0\"\n") | ||
| 446 | + writeFile(t, filepath.Join(root, "moon.pkg"), "pkgtype(kind: \"executable\")\n") | ||
| 447 | + writeFile(t, filepath.Join(root, "main.mbt"), source) | ||
| 448 | + | ||
| 449 | + editor = newTestEditor(t) | ||
| 450 | + | ||
| 451 | + // 1. Open the file, exactly as main does — before there is any server. | ||
| 452 | + editor.Open(filepath.Join(root, "main.mbt")) | ||
| 453 | + | ||
| 454 | + // 2. Start the language server, exactly as main does — afterwards. | ||
| 455 | + ctx, cancel := context.WithCancel(t.Context()) | ||
| 456 | + t.Cleanup(cancel) | ||
| 457 | + editor.StartLanguageServer(ctx, root) | ||
| 458 | + t.Cleanup(func() { editor.Language().Stop(context.Background()) }) | ||
| 459 | + | ||
| 460 | + waitUntilReady(t, editor) | ||
| 461 | + | ||
| 462 | + // 3. Let the event loop notice the server is ready, as Run does on every | ||
| 463 | + // turn. This is what announces the file that was already open. | ||
| 464 | + editor.Tick() | ||
| 465 | + return root, editor | ||
| 466 | +} | ||
| 467 | + | ||
| 468 | +// newTestEditor returns Turbo MoonBit drawing on a simulated terminal, set up | ||
| 469 | +// the way the command sets it up. | ||
| 470 | +func newTestEditor(t *testing.T) *app.App { | ||
| 471 | + t.Helper() | ||
| 472 | + | ||
| 473 | + moonbitlang.Register() | ||
| 474 | + screen := tcell.NewSimulationScreen("UTF-8") | ||
| 475 | + if err := screen.Init(); err != nil { | ||
| 476 | + t.Fatalf("initialising the simulation screen: %v", err) | ||
| 477 | + } | ||
| 478 | + t.Cleanup(screen.Fini) | ||
| 479 | + screen.SetSize(80, 24) | ||
| 480 | + | ||
| 481 | + // Never read the themes or snippets of whoever is running the tests. | ||
| 482 | + p := moonbitlang.Profile() | ||
| 483 | + t.Setenv(p.ThemeDirEnvVar(), t.TempDir()) | ||
| 484 | + t.Setenv(p.SnippetDirEnvVar(), t.TempDir()) | ||
| 485 | + | ||
| 486 | + editor := app.New(screen, "turbo-classic", p) | ||
| 487 | + editor.Render() | ||
| 488 | + return editor | ||
| 489 | +} | ||
| 490 | + | ||
| 491 | +// typeText sends a run of printable characters through the whole routing chain. | ||
| 492 | +func typeText(editor *app.App, text string) { | ||
| 493 | + for _, r := range text { | ||
| 494 | + // A newline is the Enter key, not a rune: typed as a rune it is | ||
| 495 | + // dropped, and a fixture meant to span four lines lands on one — | ||
| 496 | + // where `///|` turns the whole of it into a doc comment. | ||
| 497 | + if r == '\n' { | ||
| 498 | + editor.Handle(tcell.NewEventKey(tcell.KeyEnter, 0, tcell.ModNone)) | ||
| 499 | + continue | ||
| 500 | + } | ||
| 501 | + editor.Handle(tcell.NewEventKey(tcell.KeyRune, r, tcell.ModNone)) | ||
| 502 | + } | ||
| 503 | +} | ||
| 504 | + | ||
| 505 | +// completionOffers reports whether the open popup holds an entry starting with | ||
| 506 | +// a label. | ||
| 507 | +func completionOffers(editor *app.App, label string) bool { | ||
| 508 | + for _, item := range editor.Completion().Matches() { | ||
| 509 | + if strings.HasPrefix(item.Label, label) { | ||
| 510 | + return true | ||
| 511 | + } | ||
| 512 | + } | ||
| 513 | + return false | ||
| 514 | +} | ||
| 515 | + | ||
| 516 | +// waitUntilReady blocks until the language server has finished starting. | ||
| 517 | +func waitUntilReady(t *testing.T, editor *app.App) { | ||
| 518 | + t.Helper() | ||
| 519 | + | ||
| 520 | + deadline := time.After(lsp.InitializeTimeout) | ||
| 521 | + for !editor.Language().Ready() { | ||
| 522 | + select { | ||
| 523 | + case <-deadline: | ||
| 524 | + t.Fatalf("the language server never became ready: %s", editor.Language().Status()) | ||
| 525 | + case <-time.After(10 * time.Millisecond): | ||
| 526 | + } | ||
| 527 | + } | ||
| 528 | +} | ||
| 529 | + | ||
| 530 | +// waitUntil polls a condition until it holds or the time runs out, and fails | ||
| 531 | +// the test if it never does. | ||
| 532 | +func waitUntil(t *testing.T, within time.Duration, done func() bool) { | ||
| 533 | + t.Helper() | ||
| 534 | + | ||
| 535 | + deadline := time.Now().Add(within) | ||
| 536 | + for time.Now().Before(deadline) { | ||
| 537 | + if done() { | ||
| 538 | + return | ||
| 539 | + } | ||
| 540 | + time.Sleep(200 * time.Millisecond) | ||
| 541 | + } | ||
| 542 | + t.Errorf("the server never answered within %s", within) | ||
| 543 | +} | ||
| 544 | + | ||
| 545 | +// waitForLocations asks a location question until it is answered, because a | ||
| 546 | +// server that is still indexing answers an empty list rather than an error. | ||
| 547 | +func waitForLocations(t *testing.T, ask func(context.Context) ([]lsp.Location, error)) []lsp.Location { | ||
| 548 | + t.Helper() | ||
| 549 | + | ||
| 550 | + var found []lsp.Location | ||
| 551 | + waitUntil(t, 30*time.Second, func() bool { | ||
| 552 | + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) | ||
| 553 | + defer cancel() | ||
| 554 | + | ||
| 555 | + locations, err := ask(ctx) | ||
| 556 | + if err != nil { | ||
| 557 | + return false | ||
| 558 | + } | ||
| 559 | + found = locations | ||
| 560 | + return len(found) > 0 | ||
| 561 | + }) | ||
| 562 | + return found | ||
| 563 | +} | ||
| 564 | + | ||
| 565 | +// waitForCompletion asks for a completion until one arrives, or gives up. | ||
| 566 | +// | ||
| 567 | +// A server loads the workspace after it has finished initialising, and answers | ||
| 568 | +// an empty list until that is done. There is no notification this client reads | ||
| 569 | +// that says when — so it asks again, which is what the editor's user would do. | ||
| 570 | +func waitForCompletion(t *testing.T, editor *app.App) bool { | ||
| 571 | + t.Helper() | ||
| 572 | + | ||
| 573 | + deadline := time.Now().Add(60 * time.Second) | ||
| 574 | + for time.Now().Before(deadline) { | ||
| 575 | + if editor.Completion().Visible() { | ||
| 576 | + return true | ||
| 577 | + } | ||
| 578 | + editor.RequestCompletion() | ||
| 579 | + if editor.Completion().Visible() { | ||
| 580 | + return true | ||
| 581 | + } | ||
| 582 | + time.Sleep(500 * time.Millisecond) | ||
| 583 | + } | ||
| 584 | + return false | ||
| 585 | +} | ||
| 586 | + | ||
| 587 | +// serverRuns reports whether the language server at path actually starts. | ||
| 588 | +func serverRuns(path string) bool { | ||
| 589 | + return exec.Command(path, "--version").Run() == nil | ||
| 590 | +} | ||
| 591 | + | ||
| 592 | +// writeFile creates a file, making its directory first. | ||
| 593 | +func writeFile(t *testing.T, path, content string) { | ||
| 594 | + t.Helper() | ||
| 595 | + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { | ||
| 596 | + t.Fatalf("creating %s: %v", filepath.Dir(path), err) | ||
| 597 | + } | ||
| 598 | + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { | ||
| 599 | + t.Fatalf("writing %s: %v", path, err) | ||
| 600 | + } | ||
| 601 | +} | ||
added
internal/moonbitlang/literals.go +116 -0 | new file mode 100644 | ||
| @@ -0,0 +1,116 @@ | ||
| 1 | +package moonbitlang | |
| 2 | + | |
| 3 | +// The literals of MoonBit: five quoted forms, and one rule that governs all of | |
| 4 | +// them — none may reach the next line. | |
| 5 | + | |
| 6 | +import "rickub.com/turbo-editors/turbo-core/syntax" | |
| 7 | + | |
| 8 | +// literalPrefixes are the letters that may come before a quote, and what | |
| 9 | +// opening quote each of them expects. | |
| 10 | +// | |
| 11 | +// b takes either quote — b"bytes" and b'x' are both byte literals — while re | |
| 12 | +// takes only the double one. A prefix is only a prefix when the quote touches | |
| 13 | +// it, which is what keeps the variable b in `b + 1` from starting a literal. | |
| 14 | +var literalPrefixes = []struct { | |
| 15 | + prefix string | |
| 16 | + quotes string | |
| 17 | +}{ | |
| 18 | + {"b", `"'`}, | |
| 19 | + {"re", `"`}, | |
| 20 | +} | |
| 21 | + | |
| 22 | +// isLiteralStart reports whether a quoted literal opens at the scanner's | |
| 23 | +// position, prefix included. | |
| 24 | +func isLiteralStart(s *syntax.LineScanner) bool { | |
| 25 | + _, opens := literalPrefixLength(s) | |
| 26 | + return opens | |
| 27 | +} | |
| 28 | + | |
| 29 | +// literalPrefixLength returns how many prefix runes come before the quote, and | |
| 30 | +// whether a literal opens here at all. | |
| 31 | +func literalPrefixLength(s *syntax.LineScanner) (int, bool) { | |
| 32 | + if isQuote(s.Peek(0)) { | |
| 33 | + return 0, true | |
| 34 | + } | |
| 35 | + for _, candidate := range literalPrefixes { | |
| 36 | + length := len(candidate.prefix) | |
| 37 | + if s.HasPrefix(0, candidate.prefix) && containsRune(candidate.quotes, s.Peek(length)) { | |
| 38 | + return length, true | |
| 39 | + } | |
| 40 | + } | |
| 41 | + return 0, false | |
| 42 | +} | |
| 43 | + | |
| 44 | +// isQuote reports whether a rune opens a literal on its own. | |
| 45 | +func isQuote(r rune) bool { return r == '"' || r == '\'' } | |
| 46 | + | |
| 47 | +// containsRune reports whether a set of runes, written as a string, holds one. | |
| 48 | +func containsRune(set string, r rune) bool { | |
| 49 | + for _, member := range set { | |
| 50 | + if member == r { | |
| 51 | + return true | |
| 52 | + } | |
| 53 | + } | |
| 54 | + return false | |
| 55 | +} | |
| 56 | + | |
| 57 | +// takeLiteral colours a quoted literal from its prefix to its closing quote, or | |
| 58 | +// to the end of the line when it has none. | |
| 59 | +// | |
| 60 | +// An unterminated literal is coloured to the end of the line and left there. In | |
| 61 | +// most languages that is a tolerance; in MoonBit it is the rule, because "a | |
| 62 | +// newline before the closing quote reports an unterminated string literal" — so | |
| 63 | +// a line ending inside a literal is broken source, and carrying the colour onto | |
| 64 | +// the next line would paint the rest of the file for one stray quote. | |
| 65 | +// | |
| 66 | +// An interpolated \{expression} is *not* scanned as code. The grammar matches | |
| 67 | +// it to "the matching }", with braces inside nested literals not counting, so | |
| 68 | +// finding where one ends needs the parser rather than the scanner; and a brace | |
| 69 | +// counter that got it wrong would end the string early, which is the loudest | |
| 70 | +// way a highlighter can be broken. One flat run is the honest answer, and it is | |
| 71 | +// the one Turbo Python gives an f-string for the same reason. | |
| 72 | +func takeLiteral(s *syntax.LineScanner) { | |
| 73 | + start := s.Pos() | |
| 74 | + | |
| 75 | + prefix, _ := literalPrefixLength(s) | |
| 76 | + s.Advance(prefix) | |
| 77 | + | |
| 78 | + quote := s.Peek(0) | |
| 79 | + s.Advance(1) | |
| 80 | + consumeLiteral(s, quote) | |
| 81 | + | |
| 82 | + s.Emit(start, s.Pos(), classOfQuote(quote)) | |
| 83 | +} | |
| 84 | + | |
| 85 | +// classOfQuote says which class a literal gets from the quote that opened it. | |
| 86 | +// | |
| 87 | +// The apostrophe forms — 'c' and b'x' — are characters; the double-quoted | |
| 88 | +// forms — "s", b"s" and re"s" — are strings. A regex literal is a string | |
| 89 | +// rather than a class of its own: the closed Class set has no regex, and a | |
| 90 | +// regex is a string with a second reader. | |
| 91 | +func classOfQuote(quote rune) syntax.Class { | |
| 92 | + if quote == '\'' { | |
| 93 | + return syntax.ClassChar | |
| 94 | + } | |
| 95 | + return syntax.ClassString | |
| 96 | +} | |
| 97 | + | |
| 98 | +// consumeLiteral runs to the closing quote, or to the end of the line. | |
| 99 | +// | |
| 100 | +// A backslash takes the rune after it out of consideration. That one rule | |
| 101 | +// covers every escape the language has — \n, \u{1F600}, \xFF and the \{ that | |
| 102 | +// opens an interpolation — because all any of them need from this scanner is | |
| 103 | +// that the rune after the backslash cannot close the literal. | |
| 104 | +func consumeLiteral(s *syntax.LineScanner, quote rune) { | |
| 105 | + for !s.AtEnd() { | |
| 106 | + switch s.Peek(0) { | |
| 107 | + case '\\': | |
| 108 | + s.Advance(2) | |
| 109 | + case quote: | |
| 110 | + s.Advance(1) | |
| 111 | + return | |
| 112 | + default: | |
| 113 | + s.Advance(1) | |
| 114 | + } | |
| 115 | + } | |
| 116 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,116 @@ | |||
| 1 | +package moonbitlang | ||
| 2 | + | ||
| 3 | +// The literals of MoonBit: five quoted forms, and one rule that governs all of | ||
| 4 | +// them — none may reach the next line. | ||
| 5 | + | ||
| 6 | +import "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 7 | + | ||
| 8 | +// literalPrefixes are the letters that may come before a quote, and what | ||
| 9 | +// opening quote each of them expects. | ||
| 10 | +// | ||
| 11 | +// b takes either quote — b"bytes" and b'x' are both byte literals — while re | ||
| 12 | +// takes only the double one. A prefix is only a prefix when the quote touches | ||
| 13 | +// it, which is what keeps the variable b in `b + 1` from starting a literal. | ||
| 14 | +var literalPrefixes = []struct { | ||
| 15 | + prefix string | ||
| 16 | + quotes string | ||
| 17 | +}{ | ||
| 18 | + {"b", `"'`}, | ||
| 19 | + {"re", `"`}, | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +// isLiteralStart reports whether a quoted literal opens at the scanner's | ||
| 23 | +// position, prefix included. | ||
| 24 | +func isLiteralStart(s *syntax.LineScanner) bool { | ||
| 25 | + _, opens := literalPrefixLength(s) | ||
| 26 | + return opens | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +// literalPrefixLength returns how many prefix runes come before the quote, and | ||
| 30 | +// whether a literal opens here at all. | ||
| 31 | +func literalPrefixLength(s *syntax.LineScanner) (int, bool) { | ||
| 32 | + if isQuote(s.Peek(0)) { | ||
| 33 | + return 0, true | ||
| 34 | + } | ||
| 35 | + for _, candidate := range literalPrefixes { | ||
| 36 | + length := len(candidate.prefix) | ||
| 37 | + if s.HasPrefix(0, candidate.prefix) && containsRune(candidate.quotes, s.Peek(length)) { | ||
| 38 | + return length, true | ||
| 39 | + } | ||
| 40 | + } | ||
| 41 | + return 0, false | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +// isQuote reports whether a rune opens a literal on its own. | ||
| 45 | +func isQuote(r rune) bool { return r == '"' || r == '\'' } | ||
| 46 | + | ||
| 47 | +// containsRune reports whether a set of runes, written as a string, holds one. | ||
| 48 | +func containsRune(set string, r rune) bool { | ||
| 49 | + for _, member := range set { | ||
| 50 | + if member == r { | ||
| 51 | + return true | ||
| 52 | + } | ||
| 53 | + } | ||
| 54 | + return false | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +// takeLiteral colours a quoted literal from its prefix to its closing quote, or | ||
| 58 | +// to the end of the line when it has none. | ||
| 59 | +// | ||
| 60 | +// An unterminated literal is coloured to the end of the line and left there. In | ||
| 61 | +// most languages that is a tolerance; in MoonBit it is the rule, because "a | ||
| 62 | +// newline before the closing quote reports an unterminated string literal" — so | ||
| 63 | +// a line ending inside a literal is broken source, and carrying the colour onto | ||
| 64 | +// the next line would paint the rest of the file for one stray quote. | ||
| 65 | +// | ||
| 66 | +// An interpolated \{expression} is *not* scanned as code. The grammar matches | ||
| 67 | +// it to "the matching }", with braces inside nested literals not counting, so | ||
| 68 | +// finding where one ends needs the parser rather than the scanner; and a brace | ||
| 69 | +// counter that got it wrong would end the string early, which is the loudest | ||
| 70 | +// way a highlighter can be broken. One flat run is the honest answer, and it is | ||
| 71 | +// the one Turbo Python gives an f-string for the same reason. | ||
| 72 | +func takeLiteral(s *syntax.LineScanner) { | ||
| 73 | + start := s.Pos() | ||
| 74 | + | ||
| 75 | + prefix, _ := literalPrefixLength(s) | ||
| 76 | + s.Advance(prefix) | ||
| 77 | + | ||
| 78 | + quote := s.Peek(0) | ||
| 79 | + s.Advance(1) | ||
| 80 | + consumeLiteral(s, quote) | ||
| 81 | + | ||
| 82 | + s.Emit(start, s.Pos(), classOfQuote(quote)) | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +// classOfQuote says which class a literal gets from the quote that opened it. | ||
| 86 | +// | ||
| 87 | +// The apostrophe forms — 'c' and b'x' — are characters; the double-quoted | ||
| 88 | +// forms — "s", b"s" and re"s" — are strings. A regex literal is a string | ||
| 89 | +// rather than a class of its own: the closed Class set has no regex, and a | ||
| 90 | +// regex is a string with a second reader. | ||
| 91 | +func classOfQuote(quote rune) syntax.Class { | ||
| 92 | + if quote == '\'' { | ||
| 93 | + return syntax.ClassChar | ||
| 94 | + } | ||
| 95 | + return syntax.ClassString | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +// consumeLiteral runs to the closing quote, or to the end of the line. | ||
| 99 | +// | ||
| 100 | +// A backslash takes the rune after it out of consideration. That one rule | ||
| 101 | +// covers every escape the language has — \n, \u{1F600}, \xFF and the \{ that | ||
| 102 | +// opens an interpolation — because all any of them need from this scanner is | ||
| 103 | +// that the rune after the backslash cannot close the literal. | ||
| 104 | +func consumeLiteral(s *syntax.LineScanner, quote rune) { | ||
| 105 | + for !s.AtEnd() { | ||
| 106 | + switch s.Peek(0) { | ||
| 107 | + case '\\': | ||
| 108 | + s.Advance(2) | ||
| 109 | + case quote: | ||
| 110 | + s.Advance(1) | ||
| 111 | + return | ||
| 112 | + default: | ||
| 113 | + s.Advance(1) | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | +} | ||
added
internal/moonbitlang/moonbitlang.go +179 -0 | new file mode 100644 | ||
| @@ -0,0 +1,179 @@ | ||
| 1 | +// Package moonbitlang is everything about Turbo MoonBit that is about | |
| 2 | +// *MoonBit*: how the editor names itself, which language server it talks to, | |
| 3 | +// what a project's starter files say, and how MoonBit source is coloured. | |
| 4 | +// | |
| 5 | +// Everything else the editor does lives in turbo-core, which knows nothing | |
| 6 | +// about MoonBit. This package is the whole of the difference between Turbo | |
| 7 | +// MoonBit and Turbo Python, which is what makes a fifth editor a matter of | |
| 8 | +// writing one of these rather than forking anything. | |
| 9 | +// | |
| 10 | +// moonbitlang.Register() // teach the library to colour MoonBit | |
| 11 | +// editor := app.New(screen, name, moonbitlang.Profile()) | |
| 12 | +package moonbitlang | |
| 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-moonbit) and the stem of its environment | |
| 24 | +// variables (as TURBO_MOONBIT_…), so it is not free to change. | |
| 25 | +const ( | |
| 26 | + Name = "Turbo MoonBit" | |
| 27 | + Slug = "turbo-moonbit" | |
| 28 | +) | |
| 29 | + | |
| 30 | +// Language is the name MoonBit is known by: the value LanguageOf returns for a | |
| 31 | +// .mbt file, and what a snippets file writes in its languages key. | |
| 32 | +// | |
| 33 | +// It is lower case because every other name in the registry is — "moonbit" | |
| 34 | +// beside "toml" and "dockerfile" — while the language's own spelling, the one | |
| 35 | +// a person reads, is Profile().Language. | |
| 36 | +const Language syntax.Language = "moonbit" | |
| 37 | + | |
| 38 | +// ServerCommand is the language server Turbo MoonBit talks to, and InstallHint | |
| 39 | +// the single command that installs it. | |
| 40 | +// | |
| 41 | +// moon-lsp ships inside the MoonBit toolchain rather than being installed | |
| 42 | +// separately, so the hint installs the whole toolchain: the same one command | |
| 43 | +// puts moon, moonc and moon-lsp in place, and a machine that has moon but not | |
| 44 | +// moon-lsp is not a machine anybody has. | |
| 45 | +// | |
| 46 | +// It answers seven of the nine questions turbo-core asks — completion, hover, | |
| 47 | +// definition, references, the file's symbols and the project's symbols — and | |
| 48 | +// publishes diagnostics unasked. It advertises neither typeDefinition nor | |
| 49 | +// implementation, so those two items report nothing found; that is documented | |
| 50 | +// rather than worked around, and a test asserts it so a future moon-lsp gaining | |
| 51 | +// them is noticed. | |
| 52 | +const ( | |
| 53 | + ServerCommand = "moon-lsp" | |
| 54 | + InstallHint = "curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash" | |
| 55 | +) | |
| 56 | + | |
| 57 | +// ServerArgs is what moon-lsp is started with. | |
| 58 | +// | |
| 59 | +// The --stdio is not optional: moon-lsp with no argument prints its usage and | |
| 60 | +// exits, which the editor would see as a server that died at once. It is a | |
| 61 | +// function rather than a variable so that no caller can append to the package's | |
| 62 | +// own slice. | |
| 63 | +func ServerArgs() []string { return []string{"--stdio"} } | |
| 64 | + | |
| 65 | +// Profile returns the editor Turbo MoonBit is. | |
| 66 | +// | |
| 67 | +// It is a function rather than a variable because Server.Dirs is worked out | |
| 68 | +// from the environment, and a variable would freeze whatever MOON_HOME said | |
| 69 | +// when the package was linked. | |
| 70 | +func Profile() profile.Profile { | |
| 71 | + return profile.Profile{ | |
| 72 | + Name: Name, | |
| 73 | + Slug: Slug, | |
| 74 | + // The language's own spelling, camel case and all. This is what the | |
| 75 | + // About box and the status bar read out, so it is written the way the | |
| 76 | + // people who made it write it. | |
| 77 | + Language: "MoonBit", | |
| 78 | + // M is free: the fixed menus take F, E, S, R, C, O, W, N and H — which | |
| 79 | + // rules out both the O and the N of MoonBit — so the hot key lands on | |
| 80 | + // the first letter of the word, which is the reading that costs nobody | |
| 81 | + // a second glance. The menu is named after the language and not after | |
| 82 | + // moon, because it holds whatever the project put in its tools file, | |
| 83 | + // and the first tools file anybody writes outgrows the language's own | |
| 84 | + // toolchain. | |
| 85 | + ToolsMenu: "~M~oonBit", | |
| 86 | + // moon.mod is what `moon new` writes today; moon.mod.json is the | |
| 87 | + // deprecated JSON form, still found in every project written before | |
| 88 | + // the change and still understood by the toolchain. The nearest one | |
| 89 | + // going up is the directory the server is started in. | |
| 90 | + // | |
| 91 | + // moon.work — the multi-module workspace manifest — is deliberately | |
| 92 | + // absent, although moon itself looks for it. It only ever sits *above* | |
| 93 | + // a moon.mod, so it could only be reached for a file lying loose in a | |
| 94 | + // workspace root, and naming it would make that rare case look like | |
| 95 | + // part of the rule. | |
| 96 | + RootMarkers: []string{"moon.mod", "moon.mod.json"}, | |
| 97 | + Server: profile.Server{ | |
| 98 | + Command: ServerCommand, | |
| 99 | + Args: ServerArgs(), | |
| 100 | + InstallHint: InstallHint, | |
| 101 | + Dirs: ServerDirs(), | |
| 102 | + }, | |
| 103 | + Templates: profile.Templates{ | |
| 104 | + Settings: settingsTemplate, | |
| 105 | + Snippets: snippetsTemplate, | |
| 106 | + Tools: toolsTemplate, | |
| 107 | + Agents: agentsTemplate, | |
| 108 | + }, | |
| 109 | + } | |
| 110 | +} | |
| 111 | + | |
| 112 | +// Register teaches turbo-core to colour MoonBit. | |
| 113 | +// | |
| 114 | +// It is called explicitly at start-up rather than from an init function so that | |
| 115 | +// "which languages does this editor know?" is answered by reading main, not by | |
| 116 | +// working out which packages were imported. | |
| 117 | +// | |
| 118 | +// No shebang is claimed. MoonBit has no interpreter line: a file opening with | |
| 119 | +// #! would lex as an attribute named ! and fail, so a file with no extension is | |
| 120 | +// not MoonBit, and guessing otherwise would take a shell script away from the | |
| 121 | +// scanner that can actually colour it. | |
| 122 | +func Register() { | |
| 123 | + syntax.Register(syntax.Definition{ | |
| 124 | + Language: Language, | |
| 125 | + // .mbt is source; .mbti is a generated interface file, which is | |
| 126 | + // MoonBit and nothing else; .mbtx is a standalone script, which needs | |
| 127 | + // no module or package file at all. | |
| 128 | + // | |
| 129 | + // .mbt.md is deliberately not here, and could not be: it is a Markdown | |
| 130 | + // document with MoonBit in its fences, its extension is .md, and | |
| 131 | + // Markdown is what should colour it. | |
| 132 | + Extensions: []string{".mbt", ".mbti", ".mbtx"}, | |
| 133 | + Highlight: Highlight, | |
| 134 | + }) | |
| 135 | +} | |
| 136 | + | |
| 137 | +// ServerDirs returns the directories moon-lsp is looked for in after PATH. | |
| 138 | +// | |
| 139 | +// "Completion silently does nothing" is what a user sees when the editor cannot | |
| 140 | +// find a server they believe they installed, and the MoonBit installer's own | |
| 141 | +// last act is to append its bin directory to a shell profile — which does | |
| 142 | +// nothing for an editor started from a shell that was already open, or from a | |
| 143 | +// desktop launcher that reads no profile at all. | |
| 144 | +// | |
| 145 | +// Empty entries are skipped by the library, so a machine with MOON_HOME unset | |
| 146 | +// simply contributes the default alone. | |
| 147 | +func ServerDirs() []string { | |
| 148 | + dirs := []string{MoonHomeBinDir(), DefaultMoonBinDir()} | |
| 149 | + if dirs[0] == dirs[1] { | |
| 150 | + return dirs[:1] | |
| 151 | + } | |
| 152 | + return dirs | |
| 153 | +} | |
| 154 | + | |
| 155 | +// MoonHomeBinDir returns $MOON_HOME/bin, or "" when MOON_HOME is not set. | |
| 156 | +// | |
| 157 | +// MOON_HOME is what the installer itself honours when deciding where to put the | |
| 158 | +// toolchain, so a user who set it has the whole toolchain somewhere this is the | |
| 159 | +// only way to find. | |
| 160 | +func MoonHomeBinDir() string { | |
| 161 | + home := os.Getenv("MOON_HOME") | |
| 162 | + if home == "" { | |
| 163 | + return "" | |
| 164 | + } | |
| 165 | + return filepath.Join(home, "bin") | |
| 166 | +} | |
| 167 | + | |
| 168 | +// DefaultMoonBinDir returns ~/.moon/bin, where the installer puts the toolchain | |
| 169 | +// when MOON_HOME says nothing. | |
| 170 | +// | |
| 171 | +// It is the directory the install hint's command writes into, so it is the one | |
| 172 | +// that matters most to somebody who followed the hint and found nothing. | |
| 173 | +func DefaultMoonBinDir() string { | |
| 174 | + home, err := os.UserHomeDir() | |
| 175 | + if err != nil { | |
| 176 | + return "" | |
| 177 | + } | |
| 178 | + return filepath.Join(home, ".moon", "bin") | |
| 179 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,179 @@ | |||
| 1 | +// Package moonbitlang is everything about Turbo MoonBit that is about | ||
| 2 | +// *MoonBit*: how the editor names itself, which language server it talks to, | ||
| 3 | +// what a project's starter files say, and how MoonBit source is coloured. | ||
| 4 | +// | ||
| 5 | +// Everything else the editor does lives in turbo-core, which knows nothing | ||
| 6 | +// about MoonBit. This package is the whole of the difference between Turbo | ||
| 7 | +// MoonBit and Turbo Python, which is what makes a fifth editor a matter of | ||
| 8 | +// writing one of these rather than forking anything. | ||
| 9 | +// | ||
| 10 | +// moonbitlang.Register() // teach the library to colour MoonBit | ||
| 11 | +// editor := app.New(screen, name, moonbitlang.Profile()) | ||
| 12 | +package moonbitlang | ||
| 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-moonbit) and the stem of its environment | ||
| 24 | +// variables (as TURBO_MOONBIT_…), so it is not free to change. | ||
| 25 | +const ( | ||
| 26 | + Name = "Turbo MoonBit" | ||
| 27 | + Slug = "turbo-moonbit" | ||
| 28 | +) | ||
| 29 | + | ||
| 30 | +// Language is the name MoonBit is known by: the value LanguageOf returns for a | ||
| 31 | +// .mbt file, and what a snippets file writes in its languages key. | ||
| 32 | +// | ||
| 33 | +// It is lower case because every other name in the registry is — "moonbit" | ||
| 34 | +// beside "toml" and "dockerfile" — while the language's own spelling, the one | ||
| 35 | +// a person reads, is Profile().Language. | ||
| 36 | +const Language syntax.Language = "moonbit" | ||
| 37 | + | ||
| 38 | +// ServerCommand is the language server Turbo MoonBit talks to, and InstallHint | ||
| 39 | +// the single command that installs it. | ||
| 40 | +// | ||
| 41 | +// moon-lsp ships inside the MoonBit toolchain rather than being installed | ||
| 42 | +// separately, so the hint installs the whole toolchain: the same one command | ||
| 43 | +// puts moon, moonc and moon-lsp in place, and a machine that has moon but not | ||
| 44 | +// moon-lsp is not a machine anybody has. | ||
| 45 | +// | ||
| 46 | +// It answers seven of the nine questions turbo-core asks — completion, hover, | ||
| 47 | +// definition, references, the file's symbols and the project's symbols — and | ||
| 48 | +// publishes diagnostics unasked. It advertises neither typeDefinition nor | ||
| 49 | +// implementation, so those two items report nothing found; that is documented | ||
| 50 | +// rather than worked around, and a test asserts it so a future moon-lsp gaining | ||
| 51 | +// them is noticed. | ||
| 52 | +const ( | ||
| 53 | + ServerCommand = "moon-lsp" | ||
| 54 | + InstallHint = "curl -fsSL https://cli.moonbitlang.com/install/unix.sh | bash" | ||
| 55 | +) | ||
| 56 | + | ||
| 57 | +// ServerArgs is what moon-lsp is started with. | ||
| 58 | +// | ||
| 59 | +// The --stdio is not optional: moon-lsp with no argument prints its usage and | ||
| 60 | +// exits, which the editor would see as a server that died at once. It is a | ||
| 61 | +// function rather than a variable so that no caller can append to the package's | ||
| 62 | +// own slice. | ||
| 63 | +func ServerArgs() []string { return []string{"--stdio"} } | ||
| 64 | + | ||
| 65 | +// Profile returns the editor Turbo MoonBit is. | ||
| 66 | +// | ||
| 67 | +// It is a function rather than a variable because Server.Dirs is worked out | ||
| 68 | +// from the environment, and a variable would freeze whatever MOON_HOME said | ||
| 69 | +// when the package was linked. | ||
| 70 | +func Profile() profile.Profile { | ||
| 71 | + return profile.Profile{ | ||
| 72 | + Name: Name, | ||
| 73 | + Slug: Slug, | ||
| 74 | + // The language's own spelling, camel case and all. This is what the | ||
| 75 | + // About box and the status bar read out, so it is written the way the | ||
| 76 | + // people who made it write it. | ||
| 77 | + Language: "MoonBit", | ||
| 78 | + // M is free: the fixed menus take F, E, S, R, C, O, W, N and H — which | ||
| 79 | + // rules out both the O and the N of MoonBit — so the hot key lands on | ||
| 80 | + // the first letter of the word, which is the reading that costs nobody | ||
| 81 | + // a second glance. The menu is named after the language and not after | ||
| 82 | + // moon, because it holds whatever the project put in its tools file, | ||
| 83 | + // and the first tools file anybody writes outgrows the language's own | ||
| 84 | + // toolchain. | ||
| 85 | + ToolsMenu: "~M~oonBit", | ||
| 86 | + // moon.mod is what `moon new` writes today; moon.mod.json is the | ||
| 87 | + // deprecated JSON form, still found in every project written before | ||
| 88 | + // the change and still understood by the toolchain. The nearest one | ||
| 89 | + // going up is the directory the server is started in. | ||
| 90 | + // | ||
| 91 | + // moon.work — the multi-module workspace manifest — is deliberately | ||
| 92 | + // absent, although moon itself looks for it. It only ever sits *above* | ||
| 93 | + // a moon.mod, so it could only be reached for a file lying loose in a | ||
| 94 | + // workspace root, and naming it would make that rare case look like | ||
| 95 | + // part of the rule. | ||
| 96 | + RootMarkers: []string{"moon.mod", "moon.mod.json"}, | ||
| 97 | + Server: profile.Server{ | ||
| 98 | + Command: ServerCommand, | ||
| 99 | + Args: ServerArgs(), | ||
| 100 | + InstallHint: InstallHint, | ||
| 101 | + Dirs: ServerDirs(), | ||
| 102 | + }, | ||
| 103 | + Templates: profile.Templates{ | ||
| 104 | + Settings: settingsTemplate, | ||
| 105 | + Snippets: snippetsTemplate, | ||
| 106 | + Tools: toolsTemplate, | ||
| 107 | + Agents: agentsTemplate, | ||
| 108 | + }, | ||
| 109 | + } | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +// Register teaches turbo-core to colour MoonBit. | ||
| 113 | +// | ||
| 114 | +// It is called explicitly at start-up rather than from an init function so that | ||
| 115 | +// "which languages does this editor know?" is answered by reading main, not by | ||
| 116 | +// working out which packages were imported. | ||
| 117 | +// | ||
| 118 | +// No shebang is claimed. MoonBit has no interpreter line: a file opening with | ||
| 119 | +// #! would lex as an attribute named ! and fail, so a file with no extension is | ||
| 120 | +// not MoonBit, and guessing otherwise would take a shell script away from the | ||
| 121 | +// scanner that can actually colour it. | ||
| 122 | +func Register() { | ||
| 123 | + syntax.Register(syntax.Definition{ | ||
| 124 | + Language: Language, | ||
| 125 | + // .mbt is source; .mbti is a generated interface file, which is | ||
| 126 | + // MoonBit and nothing else; .mbtx is a standalone script, which needs | ||
| 127 | + // no module or package file at all. | ||
| 128 | + // | ||
| 129 | + // .mbt.md is deliberately not here, and could not be: it is a Markdown | ||
| 130 | + // document with MoonBit in its fences, its extension is .md, and | ||
| 131 | + // Markdown is what should colour it. | ||
| 132 | + Extensions: []string{".mbt", ".mbti", ".mbtx"}, | ||
| 133 | + Highlight: Highlight, | ||
| 134 | + }) | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +// ServerDirs returns the directories moon-lsp is looked for in after PATH. | ||
| 138 | +// | ||
| 139 | +// "Completion silently does nothing" is what a user sees when the editor cannot | ||
| 140 | +// find a server they believe they installed, and the MoonBit installer's own | ||
| 141 | +// last act is to append its bin directory to a shell profile — which does | ||
| 142 | +// nothing for an editor started from a shell that was already open, or from a | ||
| 143 | +// desktop launcher that reads no profile at all. | ||
| 144 | +// | ||
| 145 | +// Empty entries are skipped by the library, so a machine with MOON_HOME unset | ||
| 146 | +// simply contributes the default alone. | ||
| 147 | +func ServerDirs() []string { | ||
| 148 | + dirs := []string{MoonHomeBinDir(), DefaultMoonBinDir()} | ||
| 149 | + if dirs[0] == dirs[1] { | ||
| 150 | + return dirs[:1] | ||
| 151 | + } | ||
| 152 | + return dirs | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +// MoonHomeBinDir returns $MOON_HOME/bin, or "" when MOON_HOME is not set. | ||
| 156 | +// | ||
| 157 | +// MOON_HOME is what the installer itself honours when deciding where to put the | ||
| 158 | +// toolchain, so a user who set it has the whole toolchain somewhere this is the | ||
| 159 | +// only way to find. | ||
| 160 | +func MoonHomeBinDir() string { | ||
| 161 | + home := os.Getenv("MOON_HOME") | ||
| 162 | + if home == "" { | ||
| 163 | + return "" | ||
| 164 | + } | ||
| 165 | + return filepath.Join(home, "bin") | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +// DefaultMoonBinDir returns ~/.moon/bin, where the installer puts the toolchain | ||
| 169 | +// when MOON_HOME says nothing. | ||
| 170 | +// | ||
| 171 | +// It is the directory the install hint's command writes into, so it is the one | ||
| 172 | +// that matters most to somebody who followed the hint and found nothing. | ||
| 173 | +func DefaultMoonBinDir() string { | ||
| 174 | + home, err := os.UserHomeDir() | ||
| 175 | + if err != nil { | ||
| 176 | + return "" | ||
| 177 | + } | ||
| 178 | + return filepath.Join(home, ".moon", "bin") | ||
| 179 | +} | ||
added
internal/moonbitlang/profile_test.go +247 -0 | new file mode 100644 | ||
| @@ -0,0 +1,247 @@ | ||
| 1 | +package moonbitlang_test | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "os" | |
| 5 | + "path/filepath" | |
| 6 | + "slices" | |
| 7 | + "strings" | |
| 8 | + "testing" | |
| 9 | + | |
| 10 | + "rickub.com/turbo-editors/turbo-core/profile" | |
| 11 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 12 | + | |
| 13 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | |
| 14 | +) | |
| 15 | + | |
| 16 | +// fixedMenuHotKeys are the hot keys turbo-core's own menus take. The toolchain | |
| 17 | +// menu may not claim one of them, or one of the two would be unreachable from | |
| 18 | +// the keyboard and nothing would say so. | |
| 19 | +var fixedMenuHotKeys = []rune{'F', 'E', 'S', 'R', 'C', 'O', 'W', 'N', 'H'} | |
| 20 | + | |
| 21 | +func TestProfileNamesTheEditor(t *testing.T) { | |
| 22 | + p := moonbitlang.Profile() | |
| 23 | + | |
| 24 | + if p.Name != "Turbo MoonBit" { | |
| 25 | + t.Errorf("Name = %q, want %q", p.Name, "Turbo MoonBit") | |
| 26 | + } | |
| 27 | + if p.Slug != "turbo-moonbit" { | |
| 28 | + t.Errorf("Slug = %q, want %q", p.Slug, "turbo-moonbit") | |
| 29 | + } | |
| 30 | + // The About box and the status bar read this out, so it is the language's | |
| 31 | + // own spelling rather than the registry's lower-case name. | |
| 32 | + if p.Language != "MoonBit" { | |
| 33 | + t.Errorf("Language = %q, want %q", p.Language, "MoonBit") | |
| 34 | + } | |
| 35 | +} | |
| 36 | + | |
| 37 | +func TestSlugDerivesEveryPath(t *testing.T) { | |
| 38 | + p := moonbitlang.Profile() | |
| 39 | + | |
| 40 | + if got := p.ProjectDir(); got != ".turbo-moonbit" { | |
| 41 | + t.Errorf("ProjectDir() = %q, want %q", got, ".turbo-moonbit") | |
| 42 | + } | |
| 43 | + for name, got := range map[string]string{ | |
| 44 | + "DirEnvVar": p.DirEnvVar(), | |
| 45 | + "ThemeDirEnvVar": p.ThemeDirEnvVar(), | |
| 46 | + "SnippetDirEnvVar": p.SnippetDirEnvVar(), | |
| 47 | + } { | |
| 48 | + if !strings.HasPrefix(got, "TURBO_MOONBIT_") { | |
| 49 | + t.Errorf("%s() = %q, want a TURBO_MOONBIT_ prefix", name, got) | |
| 50 | + } | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +func TestThemeDirFollowsItsEnvironmentVariable(t *testing.T) { | |
| 55 | + p := moonbitlang.Profile() | |
| 56 | + want := t.TempDir() | |
| 57 | + t.Setenv(p.ThemeDirEnvVar(), want) | |
| 58 | + | |
| 59 | + if got := p.ThemeDir(); got != want { | |
| 60 | + t.Errorf("ThemeDir() = %q, want %q", got, want) | |
| 61 | + } | |
| 62 | +} | |
| 63 | + | |
| 64 | +func TestToolsMenuHotKeyClashesWithNoFixedMenu(t *testing.T) { | |
| 65 | + label := moonbitlang.Profile().ToolsMenu | |
| 66 | + | |
| 67 | + hotKey, ok := hotKeyOf(label) | |
| 68 | + if !ok { | |
| 69 | + t.Fatalf("ToolsMenu = %q, which marks no hot key between tildes", label) | |
| 70 | + } | |
| 71 | + if slices.Contains(fixedMenuHotKeys, hotKey) { | |
| 72 | + t.Errorf("ToolsMenu hot key %q is already taken by a fixed menu", hotKey) | |
| 73 | + } | |
| 74 | + if got := strings.ReplaceAll(label, "~", ""); got != "MoonBit" { | |
| 75 | + t.Errorf("ToolsMenu reads %q once the tildes are removed, want %q", got, "MoonBit") | |
| 76 | + } | |
| 77 | +} | |
| 78 | + | |
| 79 | +// hotKeyOf returns the upper-case letter a menu label marks between tildes. | |
| 80 | +func hotKeyOf(label string) (rune, bool) { | |
| 81 | + open := strings.Index(label, "~") | |
| 82 | + if open < 0 { | |
| 83 | + return 0, false | |
| 84 | + } | |
| 85 | + rest := label[open+1:] | |
| 86 | + shut := strings.Index(rest, "~") | |
| 87 | + if shut != 1 { | |
| 88 | + return 0, false | |
| 89 | + } | |
| 90 | + return []rune(strings.ToUpper(rest))[0], true | |
| 91 | +} | |
| 92 | + | |
| 93 | +func TestRootMarkersAreMoonModules(t *testing.T) { | |
| 94 | + want := []string{"moon.mod", "moon.mod.json"} | |
| 95 | + | |
| 96 | + if got := moonbitlang.Profile().RootMarkers; !slices.Equal(got, want) { | |
| 97 | + t.Errorf("RootMarkers = %v, want %v", got, want) | |
| 98 | + } | |
| 99 | +} | |
| 100 | + | |
| 101 | +func TestServerIsMoonLSPOverStdio(t *testing.T) { | |
| 102 | + server := moonbitlang.Profile().Server | |
| 103 | + | |
| 104 | + if server.Command != "moon-lsp" { | |
| 105 | + t.Errorf("Server.Command = %q, want %q", server.Command, "moon-lsp") | |
| 106 | + } | |
| 107 | + // moon-lsp with no argument prints its usage and exits, which the editor | |
| 108 | + // would see as a server that died at once. | |
| 109 | + if !slices.Contains(server.Args, "--stdio") { | |
| 110 | + t.Errorf("Server.Args = %v, want it to contain --stdio", server.Args) | |
| 111 | + } | |
| 112 | + if server.InstallHint == "" { | |
| 113 | + t.Error("Server.InstallHint is empty; a missing server would say nothing useful") | |
| 114 | + } | |
| 115 | + // It is shown on the status bar, so it has to fit on a narrow line. | |
| 116 | + if len(server.InstallHint) > 72 { | |
| 117 | + t.Errorf("InstallHint is %d characters, too long for a status bar", len(server.InstallHint)) | |
| 118 | + } | |
| 119 | +} | |
| 120 | + | |
| 121 | +func TestServerArgsCannotBeAppendedToByACaller(t *testing.T) { | |
| 122 | + first := moonbitlang.ServerArgs() | |
| 123 | + first = append(first, "--nonsense") | |
| 124 | + | |
| 125 | + if second := moonbitlang.ServerArgs(); slices.Contains(second, "--nonsense") { | |
| 126 | + t.Errorf("ServerArgs() = %v after a caller appended to an earlier result", second) | |
| 127 | + } | |
| 128 | +} | |
| 129 | + | |
| 130 | +func TestServerIsLookedForInMoonHome(t *testing.T) { | |
| 131 | + home := t.TempDir() | |
| 132 | + t.Setenv("MOON_HOME", home) | |
| 133 | + | |
| 134 | + dirs := moonbitlang.Profile().Server.Dirs | |
| 135 | + want := filepath.Join(home, "bin") | |
| 136 | + if !slices.Contains(dirs, want) { | |
| 137 | + t.Errorf("Server.Dirs = %v, want it to contain %q", dirs, want) | |
| 138 | + } | |
| 139 | +} | |
| 140 | + | |
| 141 | +func TestServerDirsFallBackToTheDefaultInstallDirectory(t *testing.T) { | |
| 142 | + t.Setenv("MOON_HOME", "") | |
| 143 | + | |
| 144 | + home, err := os.UserHomeDir() | |
| 145 | + if err != nil { | |
| 146 | + t.Skip("no home directory on this machine") | |
| 147 | + } | |
| 148 | + want := filepath.Join(home, ".moon", "bin") | |
| 149 | + | |
| 150 | + if dirs := moonbitlang.ServerDirs(); !slices.Contains(dirs, want) { | |
| 151 | + t.Errorf("ServerDirs() = %v, want it to contain %q", dirs, want) | |
| 152 | + } | |
| 153 | +} | |
| 154 | + | |
| 155 | +func TestServerDirsDoNotRepeatOneDirectory(t *testing.T) { | |
| 156 | + home, err := os.UserHomeDir() | |
| 157 | + if err != nil { | |
| 158 | + t.Skip("no home directory on this machine") | |
| 159 | + } | |
| 160 | + t.Setenv("MOON_HOME", filepath.Join(home, ".moon")) | |
| 161 | + | |
| 162 | + dirs := moonbitlang.ServerDirs() | |
| 163 | + if len(dirs) != 1 { | |
| 164 | + t.Errorf("ServerDirs() = %v with MOON_HOME at the default, want one entry", dirs) | |
| 165 | + } | |
| 166 | +} | |
| 167 | + | |
| 168 | +func TestProfileIsReadAfreshEveryTime(t *testing.T) { | |
| 169 | + // Server.Dirs comes out of the environment, so a package-level variable | |
| 170 | + // would freeze whatever MOON_HOME said when the binary was linked. | |
| 171 | + first := t.TempDir() | |
| 172 | + t.Setenv("MOON_HOME", first) | |
| 173 | + before := moonbitlang.Profile().Server.Dirs | |
| 174 | + | |
| 175 | + second := t.TempDir() | |
| 176 | + t.Setenv("MOON_HOME", second) | |
| 177 | + after := moonbitlang.Profile().Server.Dirs | |
| 178 | + | |
| 179 | + if slices.Equal(before, after) { | |
| 180 | + t.Errorf("Profile().Server.Dirs = %v both times; it did not follow MOON_HOME", after) | |
| 181 | + } | |
| 182 | +} | |
| 183 | + | |
| 184 | +func TestTemplatesAreAllFilledIn(t *testing.T) { | |
| 185 | + templates := moonbitlang.Profile().Templates | |
| 186 | + | |
| 187 | + for name, template := range map[string]string{ | |
| 188 | + "Settings": templates.Settings, | |
| 189 | + "Snippets": templates.Snippets, | |
| 190 | + "Tools": templates.Tools, | |
| 191 | + } { | |
| 192 | + if template == "" { | |
| 193 | + t.Errorf("Templates.%s is empty; the editor would offer to write nothing", name) | |
| 194 | + } | |
| 195 | + } | |
| 196 | +} | |
| 197 | + | |
| 198 | +func TestRegisterTeachesTheLibraryMoonBit(t *testing.T) { | |
| 199 | + moonbitlang.Register() | |
| 200 | + | |
| 201 | + if !slices.Contains(syntax.Registered(), moonbitlang.Language) { | |
| 202 | + t.Fatalf("Registered() = %v, want it to contain %q", syntax.Registered(), moonbitlang.Language) | |
| 203 | + } | |
| 204 | + | |
| 205 | + for _, path := range []string{"main.mbt", "pkg.mbti", "script.mbtx", "DEEP/nested/x.MBT"} { | |
| 206 | + if got := syntax.LanguageOf(path, ""); got != moonbitlang.Language { | |
| 207 | + t.Errorf("LanguageOf(%q) = %q, want %q", path, got, moonbitlang.Language) | |
| 208 | + } | |
| 209 | + } | |
| 210 | +} | |
| 211 | + | |
| 212 | +func TestRegisterLeavesOtherFilesAlone(t *testing.T) { | |
| 213 | + moonbitlang.Register() | |
| 214 | + | |
| 215 | + cases := map[string]syntax.Language{ | |
| 216 | + // A .mbt.md is a Markdown document with MoonBit in its fences. Its | |
| 217 | + // extension is .md, and Markdown is what should colour it. | |
| 218 | + "README.mbt.md": syntax.LanguageMarkdown, | |
| 219 | + "moon.mod.json": syntax.LanguageNone, | |
| 220 | + "Dockerfile": syntax.LanguageDockerfile, | |
| 221 | + "main.py": syntax.LanguageNone, | |
| 222 | + } | |
| 223 | + for path, want := range cases { | |
| 224 | + if got := syntax.LanguageOf(path, ""); got != want { | |
| 225 | + t.Errorf("LanguageOf(%q) = %q, want %q", path, got, want) | |
| 226 | + } | |
| 227 | + } | |
| 228 | +} | |
| 229 | + | |
| 230 | +func TestNoShebangIsClaimed(t *testing.T) { | |
| 231 | + moonbitlang.Register() | |
| 232 | + | |
| 233 | + // MoonBit has no interpreter line: a file opening with #! would lex as an | |
| 234 | + // attribute named ! and fail. Claiming one would take a shell script away | |
| 235 | + // from the scanner that can actually colour it. | |
| 236 | + if got := syntax.LanguageOf("script", "#!/usr/bin/env moon"); got == moonbitlang.Language { | |
| 237 | + t.Errorf("LanguageOf with a moon shebang = %q, want anything but MoonBit", got) | |
| 238 | + } | |
| 239 | +} | |
| 240 | + | |
| 241 | +// A profile is a literal, so this example is the whole of how one is used. | |
| 242 | +func ExampleProfile() { | |
| 243 | + moonbitlang.Register() | |
| 244 | + | |
| 245 | + var p profile.Profile = moonbitlang.Profile() | |
| 246 | + _ = p.ProjectDir() // ".turbo-moonbit" | |
| 247 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,247 @@ | |||
| 1 | +package moonbitlang_test | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "os" | ||
| 5 | + "path/filepath" | ||
| 6 | + "slices" | ||
| 7 | + "strings" | ||
| 8 | + "testing" | ||
| 9 | + | ||
| 10 | + "rickub.com/turbo-editors/turbo-core/profile" | ||
| 11 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 12 | + | ||
| 13 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | ||
| 14 | +) | ||
| 15 | + | ||
| 16 | +// fixedMenuHotKeys are the hot keys turbo-core's own menus take. The toolchain | ||
| 17 | +// menu may not claim one of them, or one of the two would be unreachable from | ||
| 18 | +// the keyboard and nothing would say so. | ||
| 19 | +var fixedMenuHotKeys = []rune{'F', 'E', 'S', 'R', 'C', 'O', 'W', 'N', 'H'} | ||
| 20 | + | ||
| 21 | +func TestProfileNamesTheEditor(t *testing.T) { | ||
| 22 | + p := moonbitlang.Profile() | ||
| 23 | + | ||
| 24 | + if p.Name != "Turbo MoonBit" { | ||
| 25 | + t.Errorf("Name = %q, want %q", p.Name, "Turbo MoonBit") | ||
| 26 | + } | ||
| 27 | + if p.Slug != "turbo-moonbit" { | ||
| 28 | + t.Errorf("Slug = %q, want %q", p.Slug, "turbo-moonbit") | ||
| 29 | + } | ||
| 30 | + // The About box and the status bar read this out, so it is the language's | ||
| 31 | + // own spelling rather than the registry's lower-case name. | ||
| 32 | + if p.Language != "MoonBit" { | ||
| 33 | + t.Errorf("Language = %q, want %q", p.Language, "MoonBit") | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +func TestSlugDerivesEveryPath(t *testing.T) { | ||
| 38 | + p := moonbitlang.Profile() | ||
| 39 | + | ||
| 40 | + if got := p.ProjectDir(); got != ".turbo-moonbit" { | ||
| 41 | + t.Errorf("ProjectDir() = %q, want %q", got, ".turbo-moonbit") | ||
| 42 | + } | ||
| 43 | + for name, got := range map[string]string{ | ||
| 44 | + "DirEnvVar": p.DirEnvVar(), | ||
| 45 | + "ThemeDirEnvVar": p.ThemeDirEnvVar(), | ||
| 46 | + "SnippetDirEnvVar": p.SnippetDirEnvVar(), | ||
| 47 | + } { | ||
| 48 | + if !strings.HasPrefix(got, "TURBO_MOONBIT_") { | ||
| 49 | + t.Errorf("%s() = %q, want a TURBO_MOONBIT_ prefix", name, got) | ||
| 50 | + } | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +func TestThemeDirFollowsItsEnvironmentVariable(t *testing.T) { | ||
| 55 | + p := moonbitlang.Profile() | ||
| 56 | + want := t.TempDir() | ||
| 57 | + t.Setenv(p.ThemeDirEnvVar(), want) | ||
| 58 | + | ||
| 59 | + if got := p.ThemeDir(); got != want { | ||
| 60 | + t.Errorf("ThemeDir() = %q, want %q", got, want) | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +func TestToolsMenuHotKeyClashesWithNoFixedMenu(t *testing.T) { | ||
| 65 | + label := moonbitlang.Profile().ToolsMenu | ||
| 66 | + | ||
| 67 | + hotKey, ok := hotKeyOf(label) | ||
| 68 | + if !ok { | ||
| 69 | + t.Fatalf("ToolsMenu = %q, which marks no hot key between tildes", label) | ||
| 70 | + } | ||
| 71 | + if slices.Contains(fixedMenuHotKeys, hotKey) { | ||
| 72 | + t.Errorf("ToolsMenu hot key %q is already taken by a fixed menu", hotKey) | ||
| 73 | + } | ||
| 74 | + if got := strings.ReplaceAll(label, "~", ""); got != "MoonBit" { | ||
| 75 | + t.Errorf("ToolsMenu reads %q once the tildes are removed, want %q", got, "MoonBit") | ||
| 76 | + } | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +// hotKeyOf returns the upper-case letter a menu label marks between tildes. | ||
| 80 | +func hotKeyOf(label string) (rune, bool) { | ||
| 81 | + open := strings.Index(label, "~") | ||
| 82 | + if open < 0 { | ||
| 83 | + return 0, false | ||
| 84 | + } | ||
| 85 | + rest := label[open+1:] | ||
| 86 | + shut := strings.Index(rest, "~") | ||
| 87 | + if shut != 1 { | ||
| 88 | + return 0, false | ||
| 89 | + } | ||
| 90 | + return []rune(strings.ToUpper(rest))[0], true | ||
| 91 | +} | ||
| 92 | + | ||
| 93 | +func TestRootMarkersAreMoonModules(t *testing.T) { | ||
| 94 | + want := []string{"moon.mod", "moon.mod.json"} | ||
| 95 | + | ||
| 96 | + if got := moonbitlang.Profile().RootMarkers; !slices.Equal(got, want) { | ||
| 97 | + t.Errorf("RootMarkers = %v, want %v", got, want) | ||
| 98 | + } | ||
| 99 | +} | ||
| 100 | + | ||
| 101 | +func TestServerIsMoonLSPOverStdio(t *testing.T) { | ||
| 102 | + server := moonbitlang.Profile().Server | ||
| 103 | + | ||
| 104 | + if server.Command != "moon-lsp" { | ||
| 105 | + t.Errorf("Server.Command = %q, want %q", server.Command, "moon-lsp") | ||
| 106 | + } | ||
| 107 | + // moon-lsp with no argument prints its usage and exits, which the editor | ||
| 108 | + // would see as a server that died at once. | ||
| 109 | + if !slices.Contains(server.Args, "--stdio") { | ||
| 110 | + t.Errorf("Server.Args = %v, want it to contain --stdio", server.Args) | ||
| 111 | + } | ||
| 112 | + if server.InstallHint == "" { | ||
| 113 | + t.Error("Server.InstallHint is empty; a missing server would say nothing useful") | ||
| 114 | + } | ||
| 115 | + // It is shown on the status bar, so it has to fit on a narrow line. | ||
| 116 | + if len(server.InstallHint) > 72 { | ||
| 117 | + t.Errorf("InstallHint is %d characters, too long for a status bar", len(server.InstallHint)) | ||
| 118 | + } | ||
| 119 | +} | ||
| 120 | + | ||
| 121 | +func TestServerArgsCannotBeAppendedToByACaller(t *testing.T) { | ||
| 122 | + first := moonbitlang.ServerArgs() | ||
| 123 | + first = append(first, "--nonsense") | ||
| 124 | + | ||
| 125 | + if second := moonbitlang.ServerArgs(); slices.Contains(second, "--nonsense") { | ||
| 126 | + t.Errorf("ServerArgs() = %v after a caller appended to an earlier result", second) | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +func TestServerIsLookedForInMoonHome(t *testing.T) { | ||
| 131 | + home := t.TempDir() | ||
| 132 | + t.Setenv("MOON_HOME", home) | ||
| 133 | + | ||
| 134 | + dirs := moonbitlang.Profile().Server.Dirs | ||
| 135 | + want := filepath.Join(home, "bin") | ||
| 136 | + if !slices.Contains(dirs, want) { | ||
| 137 | + t.Errorf("Server.Dirs = %v, want it to contain %q", dirs, want) | ||
| 138 | + } | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +func TestServerDirsFallBackToTheDefaultInstallDirectory(t *testing.T) { | ||
| 142 | + t.Setenv("MOON_HOME", "") | ||
| 143 | + | ||
| 144 | + home, err := os.UserHomeDir() | ||
| 145 | + if err != nil { | ||
| 146 | + t.Skip("no home directory on this machine") | ||
| 147 | + } | ||
| 148 | + want := filepath.Join(home, ".moon", "bin") | ||
| 149 | + | ||
| 150 | + if dirs := moonbitlang.ServerDirs(); !slices.Contains(dirs, want) { | ||
| 151 | + t.Errorf("ServerDirs() = %v, want it to contain %q", dirs, want) | ||
| 152 | + } | ||
| 153 | +} | ||
| 154 | + | ||
| 155 | +func TestServerDirsDoNotRepeatOneDirectory(t *testing.T) { | ||
| 156 | + home, err := os.UserHomeDir() | ||
| 157 | + if err != nil { | ||
| 158 | + t.Skip("no home directory on this machine") | ||
| 159 | + } | ||
| 160 | + t.Setenv("MOON_HOME", filepath.Join(home, ".moon")) | ||
| 161 | + | ||
| 162 | + dirs := moonbitlang.ServerDirs() | ||
| 163 | + if len(dirs) != 1 { | ||
| 164 | + t.Errorf("ServerDirs() = %v with MOON_HOME at the default, want one entry", dirs) | ||
| 165 | + } | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +func TestProfileIsReadAfreshEveryTime(t *testing.T) { | ||
| 169 | + // Server.Dirs comes out of the environment, so a package-level variable | ||
| 170 | + // would freeze whatever MOON_HOME said when the binary was linked. | ||
| 171 | + first := t.TempDir() | ||
| 172 | + t.Setenv("MOON_HOME", first) | ||
| 173 | + before := moonbitlang.Profile().Server.Dirs | ||
| 174 | + | ||
| 175 | + second := t.TempDir() | ||
| 176 | + t.Setenv("MOON_HOME", second) | ||
| 177 | + after := moonbitlang.Profile().Server.Dirs | ||
| 178 | + | ||
| 179 | + if slices.Equal(before, after) { | ||
| 180 | + t.Errorf("Profile().Server.Dirs = %v both times; it did not follow MOON_HOME", after) | ||
| 181 | + } | ||
| 182 | +} | ||
| 183 | + | ||
| 184 | +func TestTemplatesAreAllFilledIn(t *testing.T) { | ||
| 185 | + templates := moonbitlang.Profile().Templates | ||
| 186 | + | ||
| 187 | + for name, template := range map[string]string{ | ||
| 188 | + "Settings": templates.Settings, | ||
| 189 | + "Snippets": templates.Snippets, | ||
| 190 | + "Tools": templates.Tools, | ||
| 191 | + } { | ||
| 192 | + if template == "" { | ||
| 193 | + t.Errorf("Templates.%s is empty; the editor would offer to write nothing", name) | ||
| 194 | + } | ||
| 195 | + } | ||
| 196 | +} | ||
| 197 | + | ||
| 198 | +func TestRegisterTeachesTheLibraryMoonBit(t *testing.T) { | ||
| 199 | + moonbitlang.Register() | ||
| 200 | + | ||
| 201 | + if !slices.Contains(syntax.Registered(), moonbitlang.Language) { | ||
| 202 | + t.Fatalf("Registered() = %v, want it to contain %q", syntax.Registered(), moonbitlang.Language) | ||
| 203 | + } | ||
| 204 | + | ||
| 205 | + for _, path := range []string{"main.mbt", "pkg.mbti", "script.mbtx", "DEEP/nested/x.MBT"} { | ||
| 206 | + if got := syntax.LanguageOf(path, ""); got != moonbitlang.Language { | ||
| 207 | + t.Errorf("LanguageOf(%q) = %q, want %q", path, got, moonbitlang.Language) | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | +} | ||
| 211 | + | ||
| 212 | +func TestRegisterLeavesOtherFilesAlone(t *testing.T) { | ||
| 213 | + moonbitlang.Register() | ||
| 214 | + | ||
| 215 | + cases := map[string]syntax.Language{ | ||
| 216 | + // A .mbt.md is a Markdown document with MoonBit in its fences. Its | ||
| 217 | + // extension is .md, and Markdown is what should colour it. | ||
| 218 | + "README.mbt.md": syntax.LanguageMarkdown, | ||
| 219 | + "moon.mod.json": syntax.LanguageNone, | ||
| 220 | + "Dockerfile": syntax.LanguageDockerfile, | ||
| 221 | + "main.py": syntax.LanguageNone, | ||
| 222 | + } | ||
| 223 | + for path, want := range cases { | ||
| 224 | + if got := syntax.LanguageOf(path, ""); got != want { | ||
| 225 | + t.Errorf("LanguageOf(%q) = %q, want %q", path, got, want) | ||
| 226 | + } | ||
| 227 | + } | ||
| 228 | +} | ||
| 229 | + | ||
| 230 | +func TestNoShebangIsClaimed(t *testing.T) { | ||
| 231 | + moonbitlang.Register() | ||
| 232 | + | ||
| 233 | + // MoonBit has no interpreter line: a file opening with #! would lex as an | ||
| 234 | + // attribute named ! and fail. Claiming one would take a shell script away | ||
| 235 | + // from the scanner that can actually colour it. | ||
| 236 | + if got := syntax.LanguageOf("script", "#!/usr/bin/env moon"); got == moonbitlang.Language { | ||
| 237 | + t.Errorf("LanguageOf with a moon shebang = %q, want anything but MoonBit", got) | ||
| 238 | + } | ||
| 239 | +} | ||
| 240 | + | ||
| 241 | +// A profile is a literal, so this example is the whole of how one is used. | ||
| 242 | +func ExampleProfile() { | ||
| 243 | + moonbitlang.Register() | ||
| 244 | + | ||
| 245 | + var p profile.Profile = moonbitlang.Profile() | ||
| 246 | + _ = p.ProjectDir() // ".turbo-moonbit" | ||
| 247 | +} | ||
added
internal/moonbitlang/reference_test.go +208 -0 | new file mode 100644 | ||
| @@ -0,0 +1,208 @@ | ||
| 1 | +package moonbitlang_test | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "os" | |
| 5 | + "strings" | |
| 6 | + "testing" | |
| 7 | + | |
| 8 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 9 | + | |
| 10 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | |
| 11 | +) | |
| 12 | + | |
| 13 | +// TestTheLanguagesReferenceIsTrue holds docs/*/reference/languages.md to the | |
| 14 | +// scanner. Every row of its MoonBit table that no other test here covers is | |
| 15 | +// checked, so a reference claim and the code cannot drift apart quietly. | |
| 16 | +// | |
| 17 | +// The last rows document *limitations* rather than features — an enum | |
| 18 | +// constructor read as a type, a leading dot that is not a number, a reserved | |
| 19 | +// word left as an identifier. The reference says each of those in so many | |
| 20 | +// words, and these rows are what stops somebody "fixing" one without also | |
| 21 | +// fixing the sentence. | |
| 22 | +func TestTheLanguagesReferenceIsTrue(t *testing.T) { | |
| 23 | + tests := []struct { | |
| 24 | + src string | |
| 25 | + word string | |
| 26 | + want syntax.Class | |
| 27 | + }{ | |
| 28 | + // Keywords the reference lists that no other test exercises. | |
| 29 | + {"suberror MyError String", "suberror", syntax.ClassKeyword}, | |
| 30 | + {"defer cleanup()", "defer", syntax.ClassKeyword}, | |
| 31 | + {"letrec f = fn(x) { x }", "letrec", syntax.ClassKeyword}, | |
| 32 | + {"extern \"c\" fn f() -> Unit", "extern", syntax.ClassKeyword}, | |
| 33 | + {"nobreak { x }", "nobreak", syntax.ClassKeyword}, | |
| 34 | + {"using @json", "using", syntax.ClassKeyword}, | |
| 35 | + {"where T : Show", "where", syntax.ClassKeyword}, | |
| 36 | + {"package \"example/demo\"", "package", syntax.ClassKeyword}, | |
| 37 | + {"test \"it works\" { }", "test", syntax.ClassKeyword}, | |
| 38 | + {"trait Shape { }", "trait", syntax.ClassKeyword}, | |
| 39 | + | |
| 40 | + // Constants and the prelude. | |
| 41 | + {"let x = Err(\"no\")", "Err", syntax.ClassConstant}, | |
| 42 | + {"let x = Ok(1)", "Ok", syntax.ClassConstant}, | |
| 43 | + {"abort(\"stop\")", "abort", syntax.ClassBuiltin}, | |
| 44 | + {"panic()", "panic", syntax.ClassBuiltin}, | |
| 45 | + {"inspect(value)", "inspect", syntax.ClassBuiltin}, | |
| 46 | + {"debug_assert(fn() { true })", "debug_assert", syntax.ClassBuiltin}, | |
| 47 | + {"physical_equal(a, b)", "physical_equal", syntax.ClassBuiltin}, | |
| 48 | + {"json_inspect(value)", "json_inspect", syntax.ClassBuiltin}, | |
| 49 | + {"let x = null", "null", syntax.ClassBuiltin}, | |
| 50 | + | |
| 51 | + // Types, by the language's own case rule. | |
| 52 | + {"let b : StringBuilder = StringBuilder::new()", "StringBuilder", syntax.ClassType}, | |
| 53 | + {"let x : FixedArray[Int] = []", "FixedArray", syntax.ClassType}, | |
| 54 | + | |
| 55 | + // Literals. | |
| 56 | + {"let s = b\"\\xFF\"", "b\"\\xFF\"", syntax.ClassString}, | |
| 57 | + {"let r = re\"[a-z]+\"", "re\"[a-z]+\"", syntax.ClassString}, | |
| 58 | + {"let c = 'x'", "'x'", syntax.ClassChar}, | |
| 59 | + {"let c = b'x'", "b'x'", syntax.ClassChar}, | |
| 60 | + {"let c = '\\n'", "'\\n'", syntax.ClassChar}, | |
| 61 | + | |
| 62 | + // Numbers, one per row of the reference's list. | |
| 63 | + {"let n = 0o17", "0o17", syntax.ClassNumber}, | |
| 64 | + {"let n = 0b1010", "0b1010", syntax.ClassNumber}, | |
| 65 | + {"let n = 0xFF_FF", "0xFF_FF", syntax.ClassNumber}, | |
| 66 | + {"let n = 1_000", "1_000", syntax.ClassNumber}, | |
| 67 | + {"let n = 1.", "1.", syntax.ClassNumber}, | |
| 68 | + {"let n = 1.5e-3", "1.5e-3", syntax.ClassNumber}, | |
| 69 | + {"let n = 0x1.8p3F", "0x1.8p3F", syntax.ClassNumber}, | |
| 70 | + {"let n = 42U", "42U", syntax.ClassNumber}, | |
| 71 | + {"let n = 42L", "42L", syntax.ClassNumber}, | |
| 72 | + {"let n = 42UL", "42UL", syntax.ClassNumber}, | |
| 73 | + {"let n = 42N", "42N", syntax.ClassNumber}, | |
| 74 | + {"let n = 1.0F", "1.0F", syntax.ClassNumber}, | |
| 75 | + | |
| 76 | + // Comments, attributes, labels, packages. | |
| 77 | + {"/// Adds two numbers.", "/// Adds two numbers.", syntax.ClassComment}, | |
| 78 | + {"///|", "///|", syntax.ClassComment}, | |
| 79 | + {"#external", "#external", syntax.ClassAttribute}, | |
| 80 | + {"#custom.attribute(key=\"v\")", "#custom.attribute(key=\"v\")", syntax.ClassAttribute}, | |
| 81 | + {"fn greet(name~ : String) -> Unit", "name~", syntax.ClassAttribute}, | |
| 82 | + {"@moonbitlang/core/builtin.foo()", "@moonbitlang/core/builtin", syntax.ClassType}, | |
| 83 | + {"@my-pkg.foo()", "@my-pkg", syntax.ClassType}, | |
| 84 | + | |
| 85 | + // Operators and punctuation. | |
| 86 | + {"for i in 1..<10 { }", "..", syntax.ClassOperator}, | |
| 87 | + {"let x = a |> f", "|>", syntax.ClassOperator}, | |
| 88 | + {"let x = pair.0", ".", syntax.ClassPunctuation}, | |
| 89 | + | |
| 90 | + // The documented limitations. | |
| 91 | + {"Circle(1.0)", "Circle", syntax.ClassType}, | |
| 92 | + {"let n = .5", ".", syntax.ClassPunctuation}, | |
| 93 | + {"let n = 42u", "42", syntax.ClassNumber}, | |
| 94 | + {"let ref = 1", "ref", syntax.ClassIdentifier}, | |
| 95 | + {"let move = 1", "move", syntax.ClassIdentifier}, | |
| 96 | + {"config.if", "if", syntax.ClassIdentifier}, | |
| 97 | + {"let s = \"\\{count + 1}\"", "\"\\{count + 1}\"", syntax.ClassString}, | |
| 98 | + } | |
| 99 | + | |
| 100 | + for _, test := range tests { | |
| 101 | + t.Run(test.word, func(t *testing.T) { | |
| 102 | + index := strings.Index(test.src, test.word) | |
| 103 | + if index < 0 { | |
| 104 | + t.Fatalf("%q not in %q", test.word, test.src) | |
| 105 | + } | |
| 106 | + got, ok := classAt(moonbitlang.Highlight(test.src), 0, index) | |
| 107 | + if !ok || got != test.want { | |
| 108 | + t.Errorf("%q in %q is %v (covered %v), want %v", test.word, test.src, got, ok, test.want) | |
| 109 | + } | |
| 110 | + }) | |
| 111 | + } | |
| 112 | +} | |
| 113 | + | |
| 114 | +// classAt returns the class covering one rune column of one line. | |
| 115 | +func classAt(spans [][]syntax.Span, line, col int) (syntax.Class, bool) { | |
| 116 | + if line < 0 || line >= len(spans) { | |
| 117 | + return 0, false | |
| 118 | + } | |
| 119 | + for _, s := range spans[line] { | |
| 120 | + if col >= s.Start && col < s.End { | |
| 121 | + return s.Class, true | |
| 122 | + } | |
| 123 | + } | |
| 124 | + return 0, false | |
| 125 | +} | |
| 126 | + | |
| 127 | +// The reference's Classes table says MoonBit produces no heading, tag, | |
| 128 | +// emphasis or link. That is a claim about every span the scanner can ever | |
| 129 | +// emit, so it is checked over a file that uses every construct the MoonBit | |
| 130 | +// table names. | |
| 131 | +func TestTheScannerNeverProducesAMarkupClass(t *testing.T) { | |
| 132 | + const src = "///| A doc comment.\n" + | |
| 133 | + "// An ordinary one.\n" + | |
| 134 | + "#deprecated(\"use area\")\n" + | |
| 135 | + "pub fn area(shape~ : Shape, scale~ : Double) -> Double raise {\n" + | |
| 136 | + " let table : Map[String, Int] = { \"a\": 0xFF }\n" + | |
| 137 | + " let text = \"got \\{shape}\"\n" + | |
| 138 | + " let raw =\n" + | |
| 139 | + " #|literal\n" + | |
| 140 | + " $|and \\{interpolated}\n" + | |
| 141 | + " guard scale > 0.0 else { fail(\"scale\") }\n" + | |
| 142 | + " match shape { Circle(r) => 3.14 * r ; _ => 1.0 }\n" + | |
| 143 | + " let range = 1..=2\n" + | |
| 144 | + " let pair = (1, 2).0\n" + | |
| 145 | + " let bytes = b\"\\xFF\"\n" + | |
| 146 | + " let ch = 'x'\n" + | |
| 147 | + " let pattern = re\"[a-z]+\"\n" + | |
| 148 | + " ignore(@json.parse(text))\n" + | |
| 149 | + "}\n" | |
| 150 | + | |
| 151 | + forbidden := map[syntax.Class]bool{ | |
| 152 | + syntax.ClassHeading: true, | |
| 153 | + syntax.ClassTag: true, | |
| 154 | + syntax.ClassEmphasis: true, | |
| 155 | + syntax.ClassLink: true, | |
| 156 | + } | |
| 157 | + for line, spans := range moonbitlang.Highlight(src) { | |
| 158 | + for _, span := range spans { | |
| 159 | + if forbidden[span.Class] { | |
| 160 | + t.Errorf("line %d holds a %s span at %d; the reference says MoonBit produces none", line+1, span.Class, span.Start) | |
| 161 | + } | |
| 162 | + } | |
| 163 | + } | |
| 164 | +} | |
| 165 | + | |
| 166 | +// Every keyword the reference's table lists is one the scanner really treats as | |
| 167 | +// a keyword. The table is read out of the page rather than repeated here, so a | |
| 168 | +// word added to one and not the other is what fails. | |
| 169 | +func TestEveryKeywordTheReferenceListsIsAKeyword(t *testing.T) { | |
| 170 | + const page = "../../docs/en/reference/languages.md" | |
| 171 | + | |
| 172 | + raw, err := os.ReadFile(page) | |
| 173 | + if err != nil { | |
| 174 | + t.Fatalf("reading %s: %v", page, err) | |
| 175 | + } | |
| 176 | + | |
| 177 | + words := keywordRowOf(t, string(raw)) | |
| 178 | + if len(words) < 40 { | |
| 179 | + t.Fatalf("only %d keywords found in %s; the table's shape has changed", len(words), page) | |
| 180 | + } | |
| 181 | + for _, word := range words { | |
| 182 | + src := word + " x" | |
| 183 | + got, ok := classAt(moonbitlang.Highlight(src), 0, 0) | |
| 184 | + if !ok || got != syntax.ClassKeyword { | |
| 185 | + t.Errorf("%s says %q is a keyword; the scanner colours it %v", page, word, got) | |
| 186 | + } | |
| 187 | + } | |
| 188 | +} | |
| 189 | + | |
| 190 | +// keywordRowOf pulls the back-quoted words out of the reference's keyword row. | |
| 191 | +func keywordRowOf(t *testing.T, page string) []string { | |
| 192 | + t.Helper() | |
| 193 | + | |
| 194 | + for _, line := range strings.Split(page, "\n") { | |
| 195 | + if !strings.HasSuffix(line, "| keyword |") || !strings.Contains(line, "`fn`") { | |
| 196 | + continue | |
| 197 | + } | |
| 198 | + var words []string | |
| 199 | + for i, part := range strings.Split(line, "`") { | |
| 200 | + if i%2 == 1 { | |
| 201 | + words = append(words, part) | |
| 202 | + } | |
| 203 | + } | |
| 204 | + return words | |
| 205 | + } | |
| 206 | + t.Fatal("no keyword row found in the reference") | |
| 207 | + return nil | |
| 208 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,208 @@ | |||
| 1 | +package moonbitlang_test | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "os" | ||
| 5 | + "strings" | ||
| 6 | + "testing" | ||
| 7 | + | ||
| 8 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 9 | + | ||
| 10 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | ||
| 11 | +) | ||
| 12 | + | ||
| 13 | +// TestTheLanguagesReferenceIsTrue holds docs/*/reference/languages.md to the | ||
| 14 | +// scanner. Every row of its MoonBit table that no other test here covers is | ||
| 15 | +// checked, so a reference claim and the code cannot drift apart quietly. | ||
| 16 | +// | ||
| 17 | +// The last rows document *limitations* rather than features — an enum | ||
| 18 | +// constructor read as a type, a leading dot that is not a number, a reserved | ||
| 19 | +// word left as an identifier. The reference says each of those in so many | ||
| 20 | +// words, and these rows are what stops somebody "fixing" one without also | ||
| 21 | +// fixing the sentence. | ||
| 22 | +func TestTheLanguagesReferenceIsTrue(t *testing.T) { | ||
| 23 | + tests := []struct { | ||
| 24 | + src string | ||
| 25 | + word string | ||
| 26 | + want syntax.Class | ||
| 27 | + }{ | ||
| 28 | + // Keywords the reference lists that no other test exercises. | ||
| 29 | + {"suberror MyError String", "suberror", syntax.ClassKeyword}, | ||
| 30 | + {"defer cleanup()", "defer", syntax.ClassKeyword}, | ||
| 31 | + {"letrec f = fn(x) { x }", "letrec", syntax.ClassKeyword}, | ||
| 32 | + {"extern \"c\" fn f() -> Unit", "extern", syntax.ClassKeyword}, | ||
| 33 | + {"nobreak { x }", "nobreak", syntax.ClassKeyword}, | ||
| 34 | + {"using @json", "using", syntax.ClassKeyword}, | ||
| 35 | + {"where T : Show", "where", syntax.ClassKeyword}, | ||
| 36 | + {"package \"example/demo\"", "package", syntax.ClassKeyword}, | ||
| 37 | + {"test \"it works\" { }", "test", syntax.ClassKeyword}, | ||
| 38 | + {"trait Shape { }", "trait", syntax.ClassKeyword}, | ||
| 39 | + | ||
| 40 | + // Constants and the prelude. | ||
| 41 | + {"let x = Err(\"no\")", "Err", syntax.ClassConstant}, | ||
| 42 | + {"let x = Ok(1)", "Ok", syntax.ClassConstant}, | ||
| 43 | + {"abort(\"stop\")", "abort", syntax.ClassBuiltin}, | ||
| 44 | + {"panic()", "panic", syntax.ClassBuiltin}, | ||
| 45 | + {"inspect(value)", "inspect", syntax.ClassBuiltin}, | ||
| 46 | + {"debug_assert(fn() { true })", "debug_assert", syntax.ClassBuiltin}, | ||
| 47 | + {"physical_equal(a, b)", "physical_equal", syntax.ClassBuiltin}, | ||
| 48 | + {"json_inspect(value)", "json_inspect", syntax.ClassBuiltin}, | ||
| 49 | + {"let x = null", "null", syntax.ClassBuiltin}, | ||
| 50 | + | ||
| 51 | + // Types, by the language's own case rule. | ||
| 52 | + {"let b : StringBuilder = StringBuilder::new()", "StringBuilder", syntax.ClassType}, | ||
| 53 | + {"let x : FixedArray[Int] = []", "FixedArray", syntax.ClassType}, | ||
| 54 | + | ||
| 55 | + // Literals. | ||
| 56 | + {"let s = b\"\\xFF\"", "b\"\\xFF\"", syntax.ClassString}, | ||
| 57 | + {"let r = re\"[a-z]+\"", "re\"[a-z]+\"", syntax.ClassString}, | ||
| 58 | + {"let c = 'x'", "'x'", syntax.ClassChar}, | ||
| 59 | + {"let c = b'x'", "b'x'", syntax.ClassChar}, | ||
| 60 | + {"let c = '\\n'", "'\\n'", syntax.ClassChar}, | ||
| 61 | + | ||
| 62 | + // Numbers, one per row of the reference's list. | ||
| 63 | + {"let n = 0o17", "0o17", syntax.ClassNumber}, | ||
| 64 | + {"let n = 0b1010", "0b1010", syntax.ClassNumber}, | ||
| 65 | + {"let n = 0xFF_FF", "0xFF_FF", syntax.ClassNumber}, | ||
| 66 | + {"let n = 1_000", "1_000", syntax.ClassNumber}, | ||
| 67 | + {"let n = 1.", "1.", syntax.ClassNumber}, | ||
| 68 | + {"let n = 1.5e-3", "1.5e-3", syntax.ClassNumber}, | ||
| 69 | + {"let n = 0x1.8p3F", "0x1.8p3F", syntax.ClassNumber}, | ||
| 70 | + {"let n = 42U", "42U", syntax.ClassNumber}, | ||
| 71 | + {"let n = 42L", "42L", syntax.ClassNumber}, | ||
| 72 | + {"let n = 42UL", "42UL", syntax.ClassNumber}, | ||
| 73 | + {"let n = 42N", "42N", syntax.ClassNumber}, | ||
| 74 | + {"let n = 1.0F", "1.0F", syntax.ClassNumber}, | ||
| 75 | + | ||
| 76 | + // Comments, attributes, labels, packages. | ||
| 77 | + {"/// Adds two numbers.", "/// Adds two numbers.", syntax.ClassComment}, | ||
| 78 | + {"///|", "///|", syntax.ClassComment}, | ||
| 79 | + {"#external", "#external", syntax.ClassAttribute}, | ||
| 80 | + {"#custom.attribute(key=\"v\")", "#custom.attribute(key=\"v\")", syntax.ClassAttribute}, | ||
| 81 | + {"fn greet(name~ : String) -> Unit", "name~", syntax.ClassAttribute}, | ||
| 82 | + {"@moonbitlang/core/builtin.foo()", "@moonbitlang/core/builtin", syntax.ClassType}, | ||
| 83 | + {"@my-pkg.foo()", "@my-pkg", syntax.ClassType}, | ||
| 84 | + | ||
| 85 | + // Operators and punctuation. | ||
| 86 | + {"for i in 1..<10 { }", "..", syntax.ClassOperator}, | ||
| 87 | + {"let x = a |> f", "|>", syntax.ClassOperator}, | ||
| 88 | + {"let x = pair.0", ".", syntax.ClassPunctuation}, | ||
| 89 | + | ||
| 90 | + // The documented limitations. | ||
| 91 | + {"Circle(1.0)", "Circle", syntax.ClassType}, | ||
| 92 | + {"let n = .5", ".", syntax.ClassPunctuation}, | ||
| 93 | + {"let n = 42u", "42", syntax.ClassNumber}, | ||
| 94 | + {"let ref = 1", "ref", syntax.ClassIdentifier}, | ||
| 95 | + {"let move = 1", "move", syntax.ClassIdentifier}, | ||
| 96 | + {"config.if", "if", syntax.ClassIdentifier}, | ||
| 97 | + {"let s = \"\\{count + 1}\"", "\"\\{count + 1}\"", syntax.ClassString}, | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + for _, test := range tests { | ||
| 101 | + t.Run(test.word, func(t *testing.T) { | ||
| 102 | + index := strings.Index(test.src, test.word) | ||
| 103 | + if index < 0 { | ||
| 104 | + t.Fatalf("%q not in %q", test.word, test.src) | ||
| 105 | + } | ||
| 106 | + got, ok := classAt(moonbitlang.Highlight(test.src), 0, index) | ||
| 107 | + if !ok || got != test.want { | ||
| 108 | + t.Errorf("%q in %q is %v (covered %v), want %v", test.word, test.src, got, ok, test.want) | ||
| 109 | + } | ||
| 110 | + }) | ||
| 111 | + } | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +// classAt returns the class covering one rune column of one line. | ||
| 115 | +func classAt(spans [][]syntax.Span, line, col int) (syntax.Class, bool) { | ||
| 116 | + if line < 0 || line >= len(spans) { | ||
| 117 | + return 0, false | ||
| 118 | + } | ||
| 119 | + for _, s := range spans[line] { | ||
| 120 | + if col >= s.Start && col < s.End { | ||
| 121 | + return s.Class, true | ||
| 122 | + } | ||
| 123 | + } | ||
| 124 | + return 0, false | ||
| 125 | +} | ||
| 126 | + | ||
| 127 | +// The reference's Classes table says MoonBit produces no heading, tag, | ||
| 128 | +// emphasis or link. That is a claim about every span the scanner can ever | ||
| 129 | +// emit, so it is checked over a file that uses every construct the MoonBit | ||
| 130 | +// table names. | ||
| 131 | +func TestTheScannerNeverProducesAMarkupClass(t *testing.T) { | ||
| 132 | + const src = "///| A doc comment.\n" + | ||
| 133 | + "// An ordinary one.\n" + | ||
| 134 | + "#deprecated(\"use area\")\n" + | ||
| 135 | + "pub fn area(shape~ : Shape, scale~ : Double) -> Double raise {\n" + | ||
| 136 | + " let table : Map[String, Int] = { \"a\": 0xFF }\n" + | ||
| 137 | + " let text = \"got \\{shape}\"\n" + | ||
| 138 | + " let raw =\n" + | ||
| 139 | + " #|literal\n" + | ||
| 140 | + " $|and \\{interpolated}\n" + | ||
| 141 | + " guard scale > 0.0 else { fail(\"scale\") }\n" + | ||
| 142 | + " match shape { Circle(r) => 3.14 * r ; _ => 1.0 }\n" + | ||
| 143 | + " let range = 1..=2\n" + | ||
| 144 | + " let pair = (1, 2).0\n" + | ||
| 145 | + " let bytes = b\"\\xFF\"\n" + | ||
| 146 | + " let ch = 'x'\n" + | ||
| 147 | + " let pattern = re\"[a-z]+\"\n" + | ||
| 148 | + " ignore(@json.parse(text))\n" + | ||
| 149 | + "}\n" | ||
| 150 | + | ||
| 151 | + forbidden := map[syntax.Class]bool{ | ||
| 152 | + syntax.ClassHeading: true, | ||
| 153 | + syntax.ClassTag: true, | ||
| 154 | + syntax.ClassEmphasis: true, | ||
| 155 | + syntax.ClassLink: true, | ||
| 156 | + } | ||
| 157 | + for line, spans := range moonbitlang.Highlight(src) { | ||
| 158 | + for _, span := range spans { | ||
| 159 | + if forbidden[span.Class] { | ||
| 160 | + t.Errorf("line %d holds a %s span at %d; the reference says MoonBit produces none", line+1, span.Class, span.Start) | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +// Every keyword the reference's table lists is one the scanner really treats as | ||
| 167 | +// a keyword. The table is read out of the page rather than repeated here, so a | ||
| 168 | +// word added to one and not the other is what fails. | ||
| 169 | +func TestEveryKeywordTheReferenceListsIsAKeyword(t *testing.T) { | ||
| 170 | + const page = "../../docs/en/reference/languages.md" | ||
| 171 | + | ||
| 172 | + raw, err := os.ReadFile(page) | ||
| 173 | + if err != nil { | ||
| 174 | + t.Fatalf("reading %s: %v", page, err) | ||
| 175 | + } | ||
| 176 | + | ||
| 177 | + words := keywordRowOf(t, string(raw)) | ||
| 178 | + if len(words) < 40 { | ||
| 179 | + t.Fatalf("only %d keywords found in %s; the table's shape has changed", len(words), page) | ||
| 180 | + } | ||
| 181 | + for _, word := range words { | ||
| 182 | + src := word + " x" | ||
| 183 | + got, ok := classAt(moonbitlang.Highlight(src), 0, 0) | ||
| 184 | + if !ok || got != syntax.ClassKeyword { | ||
| 185 | + t.Errorf("%s says %q is a keyword; the scanner colours it %v", page, word, got) | ||
| 186 | + } | ||
| 187 | + } | ||
| 188 | +} | ||
| 189 | + | ||
| 190 | +// keywordRowOf pulls the back-quoted words out of the reference's keyword row. | ||
| 191 | +func keywordRowOf(t *testing.T, page string) []string { | ||
| 192 | + t.Helper() | ||
| 193 | + | ||
| 194 | + for _, line := range strings.Split(page, "\n") { | ||
| 195 | + if !strings.HasSuffix(line, "| keyword |") || !strings.Contains(line, "`fn`") { | ||
| 196 | + continue | ||
| 197 | + } | ||
| 198 | + var words []string | ||
| 199 | + for i, part := range strings.Split(line, "`") { | ||
| 200 | + if i%2 == 1 { | ||
| 201 | + words = append(words, part) | ||
| 202 | + } | ||
| 203 | + } | ||
| 204 | + return words | ||
| 205 | + } | ||
| 206 | + t.Fatal("no keyword row found in the reference") | ||
| 207 | + return nil | ||
| 208 | +} | ||
added
internal/moonbitlang/scan.go +217 -0 | new file mode 100644 | ||
| @@ -0,0 +1,217 @@ | ||
| 1 | +package moonbitlang | |
| 2 | + | |
| 3 | +import "rickub.com/turbo-editors/turbo-core/syntax" | |
| 4 | + | |
| 5 | +// carry is what a line of MoonBit leaves open for the next one — and in this | |
| 6 | +// language, nothing does. | |
| 7 | +// | |
| 8 | +// Every other editor in this family threads real state through its scanner: Go | |
| 9 | +// and Rust carry a block-comment depth, Rust carries a raw string's delimiter, | |
| 10 | +// Python carries which quote opened a triple-quoted literal. MoonBit needs | |
| 11 | +// none of it, and that is a property of the language rather than a shortcut: | |
| 12 | +// | |
| 13 | +// - There is no block comment. The grammar says so in as many words: "MoonBit | |
| 14 | +// has no block-comment form." // runs to the end of the line, and /// is a | |
| 15 | +// doc comment that does the same. | |
| 16 | +// - A newline before a closing quote is an *unterminated literal* error, for | |
| 17 | +// strings, bytes, regexes, characters and byte characters alike. No literal | |
| 18 | +// may reach the next line, so none of them can be carried onto it. | |
| 19 | +// - A multi-line string is not one literal spanning lines. It is a run of | |
| 20 | +// lines each prefixed #| or $|, each complete in itself, joined afterwards. | |
| 21 | +// - An attribute is explicitly one line: "everything through the next newline | |
| 22 | +// is the raw payload". | |
| 23 | +// | |
| 24 | +// So the type is empty, and it is a named type rather than struct{} written | |
| 25 | +// inline so that this comment has somewhere to live. If MoonBit ever grows a | |
| 26 | +// construct that crosses a line break, this is the type that gains a field and | |
| 27 | +// scanLine is where it would be threaded. | |
| 28 | +type carry struct{} | |
| 29 | + | |
| 30 | +// Highlight colours MoonBit source. | |
| 31 | +// | |
| 32 | +// It is written against syntax.LineScanner, a line at a time. MoonBit has no | |
| 33 | +// tokeniser in the Go standard library the way Go does, so this is a scanner in | |
| 34 | +// the same style as the ones turbo-core ships for TOML, Markdown and shell. | |
| 35 | +// | |
| 36 | +// It is deliberately tolerant of broken input: source under the cursor is | |
| 37 | +// invalid most of the time it is being typed, and a highlighter that gives up | |
| 38 | +// is a highlighter that flickers off. | |
| 39 | +// | |
| 40 | +// spans := moonbitlang.Highlight("fn main {\n println(\"hi\")\n}\n") | |
| 41 | +// // spans[0][0] covers "fn" with syntax.ClassKeyword | |
| 42 | +func Highlight(src string) [][]syntax.Span { | |
| 43 | + return syntax.ScanLines(src, scanLine) | |
| 44 | +} | |
| 45 | + | |
| 46 | +// scanLine colours one line. The carry is threaded because ScanLines asks for | |
| 47 | +// it, and is returned untouched because nothing in MoonBit crosses a line. | |
| 48 | +func scanLine(line []rune, open carry) ([]syntax.Span, carry) { | |
| 49 | + s := syntax.NewLineScanner(line) | |
| 50 | + for !s.AtEnd() { | |
| 51 | + scanToken(s) | |
| 52 | + } | |
| 53 | + return s.Spans(), open | |
| 54 | +} | |
| 55 | + | |
| 56 | +// scanToken colours whatever starts at the scanner's position. | |
| 57 | +// | |
| 58 | +// The order of the cases is the design, and three of them are load-bearing: | |
| 59 | +// | |
| 60 | +// - "//" is tested before the operators, because / is an operator rune. | |
| 61 | +// - A multi-line string line is tested before an attribute, because both | |
| 62 | +// begin with #, and what tells them apart is the rune after it. | |
| 63 | +// - A literal is tested before a word, because b" and re" begin with letters: | |
| 64 | +// without this, b"bytes" would be an identifier followed by a string. | |
| 65 | +func scanToken(s *syntax.LineScanner) { | |
| 66 | + r := s.Peek(0) | |
| 67 | + | |
| 68 | + switch { | |
| 69 | + case r == ' ' || r == '\t': | |
| 70 | + s.SkipSpaces() | |
| 71 | + case s.HasPrefix(0, "//"): | |
| 72 | + // /// is a doc comment and // is an ordinary one. They are the same | |
| 73 | + // colour because turbo-core's Class set has one comment class, and | |
| 74 | + // that set is closed on purpose — a theme colours every language an | |
| 75 | + // editor will ever learn. | |
| 76 | + s.TakeRest(syntax.ClassComment) | |
| 77 | + case isMultilineStringStart(s): | |
| 78 | + takeMultilineStringLine(s) | |
| 79 | + case isAttributeStart(s): | |
| 80 | + // The grammar hands the whole rest of the line to the attribute: after | |
| 81 | + // the dotted name, "everything through the next newline is the raw | |
| 82 | + // payload". Colouring less than the line would be inventing a | |
| 83 | + // structure the lexer does not have. | |
| 84 | + s.TakeRest(syntax.ClassAttribute) | |
| 85 | + case isPackageStart(s): | |
| 86 | + takePackageName(s) | |
| 87 | + case isLiteralStart(s): | |
| 88 | + takeLiteral(s) | |
| 89 | + case syntax.IsDigit(r): | |
| 90 | + // A leading dot is never a number in MoonBit: the grammar requires a | |
| 91 | + // digit before the point, so .5 is not a literal and .0 is a tuple | |
| 92 | + // accessor. That is why this case asks for a digit and nothing else. | |
| 93 | + takeNumber(s) | |
| 94 | + case r == '.': | |
| 95 | + takeDot(s) | |
| 96 | + case syntax.IsLetter(r) || r == '_': | |
| 97 | + takeWord(s) | |
| 98 | + case syntax.IsOperatorRune(r): | |
| 99 | + s.TakeWhile(syntax.ClassOperator, syntax.IsOperatorRune) | |
| 100 | + case syntax.IsPunctuationRune(r): | |
| 101 | + s.Take(1, syntax.ClassPunctuation) | |
| 102 | + default: | |
| 103 | + // A rune nothing here claims — a CJK letter in an identifier, which | |
| 104 | + // MoonBit allows and turbo-core's ASCII rune predicates do not — is | |
| 105 | + // stepped over uncoloured rather than guessed at. | |
| 106 | + s.Advance(1) | |
| 107 | + } | |
| 108 | +} | |
| 109 | + | |
| 110 | +// --- comments' neighbours: attributes and multi-line strings ---------------- | |
| 111 | + | |
| 112 | +// isAttributeStart reports whether an attribute opens at the scanner's | |
| 113 | +// position. | |
| 114 | +// | |
| 115 | +// An attribute name must begin with a letter or an underscore, which is the | |
| 116 | +// whole of what separates #deprecated from the #| that opens a raw multi-line | |
| 117 | +// string line. | |
| 118 | +func isAttributeStart(s *syntax.LineScanner) bool { | |
| 119 | + if s.Peek(0) != '#' { | |
| 120 | + return false | |
| 121 | + } | |
| 122 | + next := s.Peek(1) | |
| 123 | + return syntax.IsLetter(next) || next == '_' | |
| 124 | +} | |
| 125 | + | |
| 126 | +// isMultilineStringStart reports whether a multi-line string line opens at the | |
| 127 | +// scanner's position. | |
| 128 | +// | |
| 129 | +// #| is a raw line and $| an interpolated one. Neither is a literal that | |
| 130 | +// continues: the lines are separate tokens which the compiler joins with a | |
| 131 | +// newline afterwards, which is exactly why this scanner needs no carry. | |
| 132 | +func isMultilineStringStart(s *syntax.LineScanner) bool { | |
| 133 | + return (s.Peek(0) == '#' || s.Peek(0) == '$') && s.Peek(1) == '|' | |
| 134 | +} | |
| 135 | + | |
| 136 | +// takeMultilineStringLine colours one #| or $| line. | |
| 137 | +// | |
| 138 | +// The two-rune prefix is punctuation rather than string, because it is not part | |
| 139 | +// of the value: it says "this line is text", and the text is what follows it. | |
| 140 | +func takeMultilineStringLine(s *syntax.LineScanner) { | |
| 141 | + s.Take(2, syntax.ClassPunctuation) | |
| 142 | + s.TakeRest(syntax.ClassString) | |
| 143 | +} | |
| 144 | + | |
| 145 | +// --- package names ---------------------------------------------------------- | |
| 146 | + | |
| 147 | +// isPackageStart reports whether a package name opens at the scanner's | |
| 148 | +// position: @ followed by the first rune of a package part. | |
| 149 | +func isPackageStart(s *syntax.LineScanner) bool { | |
| 150 | + if s.Peek(0) != '@' { | |
| 151 | + return false | |
| 152 | + } | |
| 153 | + next := s.Peek(1) | |
| 154 | + return syntax.IsLetter(next) || next == '_' | |
| 155 | +} | |
| 156 | + | |
| 157 | +// takePackageName colours @json, @moonbitlang/core/builtin and the like. | |
| 158 | +// | |
| 159 | +// It is one span including the @, because that is one token: the grammar says | |
| 160 | +// "the leading @, slashes, and parts must be adjacent". ClassType is the | |
| 161 | +// closest of the seventeen classes — a package qualifier names a thing rather | |
| 162 | +// than holding a value, and the reading it has to be saved from is the one | |
| 163 | +// where @json.parse looks like a local variable called json. | |
| 164 | +// | |
| 165 | +// A slash or a hyphen is only taken when a name follows it, so @a/2 stops at | |
| 166 | +// the slash and @a - b stops at the space, rather than swallowing an operator | |
| 167 | +// because it happened to touch a package name. | |
| 168 | +func takePackageName(s *syntax.LineScanner) { | |
| 169 | + start := s.Pos() | |
| 170 | + s.Advance(1) // the @ | |
| 171 | + | |
| 172 | + for !s.AtEnd() { | |
| 173 | + switch r := s.Peek(0); { | |
| 174 | + case syntax.IsWordRune(r): | |
| 175 | + s.Advance(1) | |
| 176 | + case r == '/' && (syntax.IsLetter(s.Peek(1)) || s.Peek(1) == '_'): | |
| 177 | + s.Advance(1) | |
| 178 | + case r == '-' && syntax.IsWordRune(s.Peek(1)): | |
| 179 | + s.Advance(1) | |
| 180 | + default: | |
| 181 | + s.Emit(start, s.Pos(), syntax.ClassType) | |
| 182 | + return | |
| 183 | + } | |
| 184 | + } | |
| 185 | + s.Emit(start, s.Pos(), syntax.ClassType) | |
| 186 | +} | |
| 187 | + | |
| 188 | +// --- what follows a dot ----------------------------------------------------- | |
| 189 | + | |
| 190 | +// takeDot colours a dot and whatever the language says belongs with it. | |
| 191 | +// | |
| 192 | +// Three things begin with one, and telling them apart is what keeps 1..=2 from | |
| 193 | +// being read as the number 1. followed by =2: | |
| 194 | +// | |
| 195 | +// - a run of dots is a range operator — .. ..= ..< ... | |
| 196 | +// - a dot with digits after it is a tuple accessor, pair.0 | |
| 197 | +// - a dot with a name after it is a field or a method, xs.length() | |
| 198 | +// | |
| 199 | +// The third case is the reason this is a function rather than a punctuation | |
| 200 | +// rune. A dot-identifier "uses the identifier case rules without consulting the | |
| 201 | +// keyword table, so .if is valid" — so the name after a dot must not be looked | |
| 202 | +// up among the keywords, and takeMember is the version of takeWord that does | |
| 203 | +// not. | |
| 204 | +func takeDot(s *syntax.LineScanner) { | |
| 205 | + switch next := s.Peek(1); { | |
| 206 | + case next == '.': | |
| 207 | + s.TakeWhile(syntax.ClassOperator, func(r rune) bool { return r == '.' }) | |
| 208 | + case syntax.IsDigit(next): | |
| 209 | + s.Take(1, syntax.ClassPunctuation) | |
| 210 | + s.TakeWhile(syntax.ClassNumber, syntax.IsDigit) | |
| 211 | + case syntax.IsLetter(next) || next == '_': | |
| 212 | + s.Take(1, syntax.ClassPunctuation) | |
| 213 | + takeMember(s) | |
| 214 | + default: | |
| 215 | + s.Take(1, syntax.ClassPunctuation) | |
| 216 | + } | |
| 217 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,217 @@ | |||
| 1 | +package moonbitlang | ||
| 2 | + | ||
| 3 | +import "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 4 | + | ||
| 5 | +// carry is what a line of MoonBit leaves open for the next one — and in this | ||
| 6 | +// language, nothing does. | ||
| 7 | +// | ||
| 8 | +// Every other editor in this family threads real state through its scanner: Go | ||
| 9 | +// and Rust carry a block-comment depth, Rust carries a raw string's delimiter, | ||
| 10 | +// Python carries which quote opened a triple-quoted literal. MoonBit needs | ||
| 11 | +// none of it, and that is a property of the language rather than a shortcut: | ||
| 12 | +// | ||
| 13 | +// - There is no block comment. The grammar says so in as many words: "MoonBit | ||
| 14 | +// has no block-comment form." // runs to the end of the line, and /// is a | ||
| 15 | +// doc comment that does the same. | ||
| 16 | +// - A newline before a closing quote is an *unterminated literal* error, for | ||
| 17 | +// strings, bytes, regexes, characters and byte characters alike. No literal | ||
| 18 | +// may reach the next line, so none of them can be carried onto it. | ||
| 19 | +// - A multi-line string is not one literal spanning lines. It is a run of | ||
| 20 | +// lines each prefixed #| or $|, each complete in itself, joined afterwards. | ||
| 21 | +// - An attribute is explicitly one line: "everything through the next newline | ||
| 22 | +// is the raw payload". | ||
| 23 | +// | ||
| 24 | +// So the type is empty, and it is a named type rather than struct{} written | ||
| 25 | +// inline so that this comment has somewhere to live. If MoonBit ever grows a | ||
| 26 | +// construct that crosses a line break, this is the type that gains a field and | ||
| 27 | +// scanLine is where it would be threaded. | ||
| 28 | +type carry struct{} | ||
| 29 | + | ||
| 30 | +// Highlight colours MoonBit source. | ||
| 31 | +// | ||
| 32 | +// It is written against syntax.LineScanner, a line at a time. MoonBit has no | ||
| 33 | +// tokeniser in the Go standard library the way Go does, so this is a scanner in | ||
| 34 | +// the same style as the ones turbo-core ships for TOML, Markdown and shell. | ||
| 35 | +// | ||
| 36 | +// It is deliberately tolerant of broken input: source under the cursor is | ||
| 37 | +// invalid most of the time it is being typed, and a highlighter that gives up | ||
| 38 | +// is a highlighter that flickers off. | ||
| 39 | +// | ||
| 40 | +// spans := moonbitlang.Highlight("fn main {\n println(\"hi\")\n}\n") | ||
| 41 | +// // spans[0][0] covers "fn" with syntax.ClassKeyword | ||
| 42 | +func Highlight(src string) [][]syntax.Span { | ||
| 43 | + return syntax.ScanLines(src, scanLine) | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +// scanLine colours one line. The carry is threaded because ScanLines asks for | ||
| 47 | +// it, and is returned untouched because nothing in MoonBit crosses a line. | ||
| 48 | +func scanLine(line []rune, open carry) ([]syntax.Span, carry) { | ||
| 49 | + s := syntax.NewLineScanner(line) | ||
| 50 | + for !s.AtEnd() { | ||
| 51 | + scanToken(s) | ||
| 52 | + } | ||
| 53 | + return s.Spans(), open | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +// scanToken colours whatever starts at the scanner's position. | ||
| 57 | +// | ||
| 58 | +// The order of the cases is the design, and three of them are load-bearing: | ||
| 59 | +// | ||
| 60 | +// - "//" is tested before the operators, because / is an operator rune. | ||
| 61 | +// - A multi-line string line is tested before an attribute, because both | ||
| 62 | +// begin with #, and what tells them apart is the rune after it. | ||
| 63 | +// - A literal is tested before a word, because b" and re" begin with letters: | ||
| 64 | +// without this, b"bytes" would be an identifier followed by a string. | ||
| 65 | +func scanToken(s *syntax.LineScanner) { | ||
| 66 | + r := s.Peek(0) | ||
| 67 | + | ||
| 68 | + switch { | ||
| 69 | + case r == ' ' || r == '\t': | ||
| 70 | + s.SkipSpaces() | ||
| 71 | + case s.HasPrefix(0, "//"): | ||
| 72 | + // /// is a doc comment and // is an ordinary one. They are the same | ||
| 73 | + // colour because turbo-core's Class set has one comment class, and | ||
| 74 | + // that set is closed on purpose — a theme colours every language an | ||
| 75 | + // editor will ever learn. | ||
| 76 | + s.TakeRest(syntax.ClassComment) | ||
| 77 | + case isMultilineStringStart(s): | ||
| 78 | + takeMultilineStringLine(s) | ||
| 79 | + case isAttributeStart(s): | ||
| 80 | + // The grammar hands the whole rest of the line to the attribute: after | ||
| 81 | + // the dotted name, "everything through the next newline is the raw | ||
| 82 | + // payload". Colouring less than the line would be inventing a | ||
| 83 | + // structure the lexer does not have. | ||
| 84 | + s.TakeRest(syntax.ClassAttribute) | ||
| 85 | + case isPackageStart(s): | ||
| 86 | + takePackageName(s) | ||
| 87 | + case isLiteralStart(s): | ||
| 88 | + takeLiteral(s) | ||
| 89 | + case syntax.IsDigit(r): | ||
| 90 | + // A leading dot is never a number in MoonBit: the grammar requires a | ||
| 91 | + // digit before the point, so .5 is not a literal and .0 is a tuple | ||
| 92 | + // accessor. That is why this case asks for a digit and nothing else. | ||
| 93 | + takeNumber(s) | ||
| 94 | + case r == '.': | ||
| 95 | + takeDot(s) | ||
| 96 | + case syntax.IsLetter(r) || r == '_': | ||
| 97 | + takeWord(s) | ||
| 98 | + case syntax.IsOperatorRune(r): | ||
| 99 | + s.TakeWhile(syntax.ClassOperator, syntax.IsOperatorRune) | ||
| 100 | + case syntax.IsPunctuationRune(r): | ||
| 101 | + s.Take(1, syntax.ClassPunctuation) | ||
| 102 | + default: | ||
| 103 | + // A rune nothing here claims — a CJK letter in an identifier, which | ||
| 104 | + // MoonBit allows and turbo-core's ASCII rune predicates do not — is | ||
| 105 | + // stepped over uncoloured rather than guessed at. | ||
| 106 | + s.Advance(1) | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +// --- comments' neighbours: attributes and multi-line strings ---------------- | ||
| 111 | + | ||
| 112 | +// isAttributeStart reports whether an attribute opens at the scanner's | ||
| 113 | +// position. | ||
| 114 | +// | ||
| 115 | +// An attribute name must begin with a letter or an underscore, which is the | ||
| 116 | +// whole of what separates #deprecated from the #| that opens a raw multi-line | ||
| 117 | +// string line. | ||
| 118 | +func isAttributeStart(s *syntax.LineScanner) bool { | ||
| 119 | + if s.Peek(0) != '#' { | ||
| 120 | + return false | ||
| 121 | + } | ||
| 122 | + next := s.Peek(1) | ||
| 123 | + return syntax.IsLetter(next) || next == '_' | ||
| 124 | +} | ||
| 125 | + | ||
| 126 | +// isMultilineStringStart reports whether a multi-line string line opens at the | ||
| 127 | +// scanner's position. | ||
| 128 | +// | ||
| 129 | +// #| is a raw line and $| an interpolated one. Neither is a literal that | ||
| 130 | +// continues: the lines are separate tokens which the compiler joins with a | ||
| 131 | +// newline afterwards, which is exactly why this scanner needs no carry. | ||
| 132 | +func isMultilineStringStart(s *syntax.LineScanner) bool { | ||
| 133 | + return (s.Peek(0) == '#' || s.Peek(0) == '$') && s.Peek(1) == '|' | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +// takeMultilineStringLine colours one #| or $| line. | ||
| 137 | +// | ||
| 138 | +// The two-rune prefix is punctuation rather than string, because it is not part | ||
| 139 | +// of the value: it says "this line is text", and the text is what follows it. | ||
| 140 | +func takeMultilineStringLine(s *syntax.LineScanner) { | ||
| 141 | + s.Take(2, syntax.ClassPunctuation) | ||
| 142 | + s.TakeRest(syntax.ClassString) | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +// --- package names ---------------------------------------------------------- | ||
| 146 | + | ||
| 147 | +// isPackageStart reports whether a package name opens at the scanner's | ||
| 148 | +// position: @ followed by the first rune of a package part. | ||
| 149 | +func isPackageStart(s *syntax.LineScanner) bool { | ||
| 150 | + if s.Peek(0) != '@' { | ||
| 151 | + return false | ||
| 152 | + } | ||
| 153 | + next := s.Peek(1) | ||
| 154 | + return syntax.IsLetter(next) || next == '_' | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +// takePackageName colours @json, @moonbitlang/core/builtin and the like. | ||
| 158 | +// | ||
| 159 | +// It is one span including the @, because that is one token: the grammar says | ||
| 160 | +// "the leading @, slashes, and parts must be adjacent". ClassType is the | ||
| 161 | +// closest of the seventeen classes — a package qualifier names a thing rather | ||
| 162 | +// than holding a value, and the reading it has to be saved from is the one | ||
| 163 | +// where @json.parse looks like a local variable called json. | ||
| 164 | +// | ||
| 165 | +// A slash or a hyphen is only taken when a name follows it, so @a/2 stops at | ||
| 166 | +// the slash and @a - b stops at the space, rather than swallowing an operator | ||
| 167 | +// because it happened to touch a package name. | ||
| 168 | +func takePackageName(s *syntax.LineScanner) { | ||
| 169 | + start := s.Pos() | ||
| 170 | + s.Advance(1) // the @ | ||
| 171 | + | ||
| 172 | + for !s.AtEnd() { | ||
| 173 | + switch r := s.Peek(0); { | ||
| 174 | + case syntax.IsWordRune(r): | ||
| 175 | + s.Advance(1) | ||
| 176 | + case r == '/' && (syntax.IsLetter(s.Peek(1)) || s.Peek(1) == '_'): | ||
| 177 | + s.Advance(1) | ||
| 178 | + case r == '-' && syntax.IsWordRune(s.Peek(1)): | ||
| 179 | + s.Advance(1) | ||
| 180 | + default: | ||
| 181 | + s.Emit(start, s.Pos(), syntax.ClassType) | ||
| 182 | + return | ||
| 183 | + } | ||
| 184 | + } | ||
| 185 | + s.Emit(start, s.Pos(), syntax.ClassType) | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +// --- what follows a dot ----------------------------------------------------- | ||
| 189 | + | ||
| 190 | +// takeDot colours a dot and whatever the language says belongs with it. | ||
| 191 | +// | ||
| 192 | +// Three things begin with one, and telling them apart is what keeps 1..=2 from | ||
| 193 | +// being read as the number 1. followed by =2: | ||
| 194 | +// | ||
| 195 | +// - a run of dots is a range operator — .. ..= ..< ... | ||
| 196 | +// - a dot with digits after it is a tuple accessor, pair.0 | ||
| 197 | +// - a dot with a name after it is a field or a method, xs.length() | ||
| 198 | +// | ||
| 199 | +// The third case is the reason this is a function rather than a punctuation | ||
| 200 | +// rune. A dot-identifier "uses the identifier case rules without consulting the | ||
| 201 | +// keyword table, so .if is valid" — so the name after a dot must not be looked | ||
| 202 | +// up among the keywords, and takeMember is the version of takeWord that does | ||
| 203 | +// not. | ||
| 204 | +func takeDot(s *syntax.LineScanner) { | ||
| 205 | + switch next := s.Peek(1); { | ||
| 206 | + case next == '.': | ||
| 207 | + s.TakeWhile(syntax.ClassOperator, func(r rune) bool { return r == '.' }) | ||
| 208 | + case syntax.IsDigit(next): | ||
| 209 | + s.Take(1, syntax.ClassPunctuation) | ||
| 210 | + s.TakeWhile(syntax.ClassNumber, syntax.IsDigit) | ||
| 211 | + case syntax.IsLetter(next) || next == '_': | ||
| 212 | + s.Take(1, syntax.ClassPunctuation) | ||
| 213 | + takeMember(s) | ||
| 214 | + default: | ||
| 215 | + s.Take(1, syntax.ClassPunctuation) | ||
| 216 | + } | ||
| 217 | +} | ||
added
internal/moonbitlang/scan_test.go +468 -0 | new file mode 100644 | ||
| @@ -0,0 +1,468 @@ | ||
| 1 | +package moonbitlang_test | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "strings" | |
| 5 | + "testing" | |
| 6 | + | |
| 7 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 8 | + | |
| 9 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | |
| 10 | +) | |
| 11 | + | |
| 12 | +// coloured is one span with the text it covers, which is what a test wants to | |
| 13 | +// talk about: "the word fn is a keyword", not "columns 0 to 2 are class 1". | |
| 14 | +type coloured struct { | |
| 15 | + text string | |
| 16 | + class syntax.Class | |
| 17 | +} | |
| 18 | + | |
| 19 | +func (c coloured) String() string { return c.text + ":" + c.class.String() } | |
| 20 | + | |
| 21 | +// colouredLine returns every span of one line of source, with its text. | |
| 22 | +func colouredLine(t *testing.T, src string) []coloured { | |
| 23 | + t.Helper() | |
| 24 | + | |
| 25 | + lines := moonbitlang.Highlight(src) | |
| 26 | + if len(lines) != 1 { | |
| 27 | + t.Fatalf("Highlight(%q) returned %d lines, want 1", src, len(lines)) | |
| 28 | + } | |
| 29 | + return withText([]rune(src), lines[0]) | |
| 30 | +} | |
| 31 | + | |
| 32 | +// withText pairs each span with the runes it covers. | |
| 33 | +func withText(line []rune, spans []syntax.Span) []coloured { | |
| 34 | + out := make([]coloured, 0, len(spans)) | |
| 35 | + for _, span := range spans { | |
| 36 | + out = append(out, coloured{string(line[span.Start:span.End]), span.Class}) | |
| 37 | + } | |
| 38 | + return out | |
| 39 | +} | |
| 40 | + | |
| 41 | +// find returns the span covering exactly the given text, if there is one. | |
| 42 | +func find(spans []coloured, text string) (coloured, bool) { | |
| 43 | + for _, span := range spans { | |
| 44 | + if span.text == text { | |
| 45 | + return span, true | |
| 46 | + } | |
| 47 | + } | |
| 48 | + return coloured{}, false | |
| 49 | +} | |
| 50 | + | |
| 51 | +// assertClass fails unless one span covers exactly text and has the wanted | |
| 52 | +// class. Asking for the whole text means a scanner that split a construct in | |
| 53 | +// two is caught, not only one that coloured it wrongly. | |
| 54 | +func assertClass(t *testing.T, src, text string, want syntax.Class) { | |
| 55 | + t.Helper() | |
| 56 | + | |
| 57 | + spans := colouredLine(t, src) | |
| 58 | + got, ok := find(spans, text) | |
| 59 | + if !ok { | |
| 60 | + t.Fatalf("in %q: no single span covers %q; got %v", src, text, spans) | |
| 61 | + } | |
| 62 | + if got.class != want { | |
| 63 | + t.Errorf("in %q: %q is %s, want %s", src, text, got.class, want) | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +// --- the three invariants the editor relies on ------------------------------ | |
| 68 | + | |
| 69 | +// A representative body of MoonBit, used by the invariant tests below. It is | |
| 70 | +// deliberately a mixture: every construct the scanner knows, some broken input, | |
| 71 | +// and the constructs that most easily run into one another. | |
| 72 | +const sample = `///| A doc comment. | |
| 73 | +// An ordinary one. | |
| 74 | +#deprecated("use area instead") | |
| 75 | +pub fn area(shape : Shape, scale~ : Double = 1.0) -> Double raise { | |
| 76 | + let table : Map[String, Int] = { "a": 1, "b": 0xFF } | |
| 77 | + let text = "got \{shape} and \{scale}" | |
| 78 | + let raw = | |
| 79 | + #|literal ${not interpolated} | |
| 80 | + $|and \{interpolated} | |
| 81 | + guard scale > 0.0 else { fail("scale") } | |
| 82 | + match shape { | |
| 83 | + Circle(r) => 3.14159 * r * r | |
| 84 | + Rect(w, h) => w * h | |
| 85 | + } | |
| 86 | + let range = 1..=2 | |
| 87 | + let pair = (1, 2).0 | |
| 88 | + let bytes = b"\xFF\x00" | |
| 89 | + let ch = 'x' | |
| 90 | + let pattern = re"[a-z]+" | |
| 91 | + ignore(@json.parse(text)) | |
| 92 | + let broken = "unterminated | |
| 93 | + let after = 1 | |
| 94 | +}` | |
| 95 | + | |
| 96 | +func TestEveryLineGetsExactlyOneEntry(t *testing.T) { | |
| 97 | + // The editor indexes the result by line number without checking, so a | |
| 98 | + // scanner that returned one entry fewer would draw every line below the | |
| 99 | + // gap in the wrong colours. | |
| 100 | + src := sample + "\n\n\ntrailing\n" | |
| 101 | + want := len(strings.Split(src, "\n")) | |
| 102 | + | |
| 103 | + if got := len(moonbitlang.Highlight(src)); got != want { | |
| 104 | + t.Errorf("Highlight returned %d lines for %d lines of source", got, want) | |
| 105 | + } | |
| 106 | +} | |
| 107 | + | |
| 108 | +func TestSpansAreInOrderAndDoNotOverlap(t *testing.T) { | |
| 109 | + // Spans are drawn in the order they arrive. Two out of order paint over | |
| 110 | + // each other, and nothing fails. | |
| 111 | + for number, spans := range moonbitlang.Highlight(sample) { | |
| 112 | + line := []rune(strings.Split(sample, "\n")[number]) | |
| 113 | + previousEnd := 0 | |
| 114 | + | |
| 115 | + for _, span := range spans { | |
| 116 | + switch { | |
| 117 | + case span.Start < previousEnd: | |
| 118 | + t.Errorf("line %d: span %v starts before the previous one ended at %d", number+1, span, previousEnd) | |
| 119 | + case span.Start >= span.End: | |
| 120 | + t.Errorf("line %d: span %v is empty or inverted", number+1, span) | |
| 121 | + case span.End > len(line): | |
| 122 | + t.Errorf("line %d: span %v runs past the %d runes of the line", number+1, span, len(line)) | |
| 123 | + } | |
| 124 | + previousEnd = span.End | |
| 125 | + } | |
| 126 | + } | |
| 127 | +} | |
| 128 | + | |
| 129 | +func TestBrokenInputStillColours(t *testing.T) { | |
| 130 | + // Source under the cursor is invalid most of the time it is being typed. | |
| 131 | + broken := []string{ | |
| 132 | + `let x = "`, | |
| 133 | + `let x = '`, | |
| 134 | + `let x = b"\`, | |
| 135 | + `fn (`, | |
| 136 | + `#`, | |
| 137 | + `#|`, | |
| 138 | + `$|`, | |
| 139 | + `@`, | |
| 140 | + `@/`, | |
| 141 | + `.`, | |
| 142 | + `..`, | |
| 143 | + `1.`, | |
| 144 | + `0x`, | |
| 145 | + `re"`, | |
| 146 | + `}}}`, | |
| 147 | + `let x = 1e`, | |
| 148 | + `let x = 1e-`, | |
| 149 | + `~`, | |
| 150 | + `let x~`, | |
| 151 | + } | |
| 152 | + for _, src := range broken { | |
| 153 | + spans := moonbitlang.Highlight(src) | |
| 154 | + if len(spans) != 1 { | |
| 155 | + t.Errorf("Highlight(%q) returned %d lines, want 1", src, len(spans)) | |
| 156 | + } | |
| 157 | + } | |
| 158 | +} | |
| 159 | + | |
| 160 | +func TestNothingCarriesOntoTheNextLine(t *testing.T) { | |
| 161 | + // This is the property that makes MoonBit's scanner stateless: no literal | |
| 162 | + // may reach the next line, so a stray quote must not paint the rest of the | |
| 163 | + // file. Every other editor in this family would carry here. | |
| 164 | + // | |
| 165 | + // Today the carry type is empty, so this cannot fail — and that is why it | |
| 166 | + // is written down. It is the guard on the type: a later change that gives | |
| 167 | + // carry a field has to keep every one of these openers from reaching the | |
| 168 | + // line below, and this is where it finds out that it did not. | |
| 169 | + openers := []string{`"`, `'`, `b"`, `b'`, `re"`, `#|`, `$|`, `#deprecated(`, `//`} | |
| 170 | + | |
| 171 | + for _, opener := range openers { | |
| 172 | + src := "let a = " + opener + "\nfn main {\n println(\"hi\")\n}" | |
| 173 | + lines := moonbitlang.Highlight(src) | |
| 174 | + | |
| 175 | + second := withText([]rune("fn main {"), lines[1]) | |
| 176 | + if got, ok := find(second, "fn"); !ok || got.class != syntax.ClassKeyword { | |
| 177 | + t.Errorf("after a line opening with %q, fn on the next line is %v, want a keyword", opener, second) | |
| 178 | + } | |
| 179 | + } | |
| 180 | +} | |
| 181 | + | |
| 182 | +func TestAnEmptyDocumentIsOneEmptyLine(t *testing.T) { | |
| 183 | + if got := moonbitlang.Highlight(""); len(got) != 1 || len(got[0]) != 0 { | |
| 184 | + t.Errorf("Highlight(\"\") = %v, want one line with no spans", got) | |
| 185 | + } | |
| 186 | +} | |
| 187 | + | |
| 188 | +func TestCRLFColoursTheSameAsLF(t *testing.T) { | |
| 189 | + unix := moonbitlang.Highlight("fn main {\n println(\"hi\")\n}") | |
| 190 | + windows := moonbitlang.Highlight("fn main {\r\n println(\"hi\")\r\n}") | |
| 191 | + | |
| 192 | + if len(unix) != len(windows) { | |
| 193 | + t.Fatalf("CRLF gave %d lines, LF gave %d", len(windows), len(unix)) | |
| 194 | + } | |
| 195 | + for i := range unix { | |
| 196 | + if len(unix[i]) != len(windows[i]) { | |
| 197 | + t.Errorf("line %d: CRLF gave %v, LF gave %v", i+1, windows[i], unix[i]) | |
| 198 | + } | |
| 199 | + } | |
| 200 | +} | |
| 201 | + | |
| 202 | +// --- one case per construct ------------------------------------------------- | |
| 203 | + | |
| 204 | +func TestConstructs(t *testing.T) { | |
| 205 | + cases := []struct { | |
| 206 | + name string | |
| 207 | + src string | |
| 208 | + text string | |
| 209 | + class syntax.Class | |
| 210 | + }{ | |
| 211 | + {"line comment", `let x = 1 // why`, `// why`, syntax.ClassComment}, | |
| 212 | + {"doc comment", `/// Adds two numbers.`, `/// Adds two numbers.`, syntax.ClassComment}, | |
| 213 | + {"section marker", `///|`, `///|`, syntax.ClassComment}, | |
| 214 | + {"comment wins over division", `// a / b`, `// a / b`, syntax.ClassComment}, | |
| 215 | + | |
| 216 | + {"attribute", `#deprecated("use area")`, `#deprecated("use area")`, syntax.ClassAttribute}, | |
| 217 | + {"namespaced attribute", `#custom.attribute(key="v")`, `#custom.attribute(key="v")`, syntax.ClassAttribute}, | |
| 218 | + {"bare attribute", `#external`, `#external`, syntax.ClassAttribute}, | |
| 219 | + | |
| 220 | + {"raw multiline prefix", ` #|hello`, `#|`, syntax.ClassPunctuation}, | |
| 221 | + {"raw multiline text", ` #|hello`, `hello`, syntax.ClassString}, | |
| 222 | + {"interpolated multiline prefix", ` $|hi \{name}`, `$|`, syntax.ClassPunctuation}, | |
| 223 | + {"interpolated multiline text", ` $|hi \{name}`, `hi \{name}`, syntax.ClassString}, | |
| 224 | + | |
| 225 | + {"string", `let s = "hi"`, `"hi"`, syntax.ClassString}, | |
| 226 | + {"string stops at its closing quote", `let s = "hi" + name`, `"hi"`, syntax.ClassString}, | |
| 227 | + {"code after a string is still code", `let s = "hi" + name`, `name`, syntax.ClassIdentifier}, | |
| 228 | + {"char stops at its closing quote", `let c = 'x' + 1`, `'x'`, syntax.ClassChar}, | |
| 229 | + {"code after a char is still code", `let c = 'x' + 1`, `1`, syntax.ClassNumber}, | |
| 230 | + {"empty string", `let s = ""`, `""`, syntax.ClassString}, | |
| 231 | + {"string with interpolation", `let s = "a \{b} c"`, `"a \{b} c"`, syntax.ClassString}, | |
| 232 | + {"string with escaped quote", `let s = "a \" b"`, `"a \" b"`, syntax.ClassString}, | |
| 233 | + {"bytes literal", `let b = b"\xFF"`, `b"\xFF"`, syntax.ClassString}, | |
| 234 | + {"regex literal", `let r = re"[a-z]+"`, `re"[a-z]+"`, syntax.ClassString}, | |
| 235 | + {"char literal", `let c = 'x'`, `'x'`, syntax.ClassChar}, | |
| 236 | + {"escaped char literal", `let c = '\n'`, `'\n'`, syntax.ClassChar}, | |
| 237 | + {"byte literal", `let c = b'x'`, `b'x'`, syntax.ClassChar}, | |
| 238 | + | |
| 239 | + {"decimal", `let n = 1_000`, `1_000`, syntax.ClassNumber}, | |
| 240 | + {"hexadecimal", `let n = 0xFF_FF`, `0xFF_FF`, syntax.ClassNumber}, | |
| 241 | + {"octal", `let n = 0o17`, `0o17`, syntax.ClassNumber}, | |
| 242 | + {"binary", `let n = 0b1010`, `0b1010`, syntax.ClassNumber}, | |
| 243 | + {"double", `let n = 1.5`, `1.5`, syntax.ClassNumber}, | |
| 244 | + {"double with a trailing point", `let n = 1.`, `1.`, syntax.ClassNumber}, | |
| 245 | + {"exponent", `let n = 1.5e-3`, `1.5e-3`, syntax.ClassNumber}, | |
| 246 | + {"hex float", `let n = 0x1.8p3F`, `0x1.8p3F`, syntax.ClassNumber}, | |
| 247 | + {"uint suffix", `let n = 42U`, `42U`, syntax.ClassNumber}, | |
| 248 | + {"uint64 suffix", `let n = 42UL`, `42UL`, syntax.ClassNumber}, | |
| 249 | + {"bigint suffix", `let n = 42N`, `42N`, syntax.ClassNumber}, | |
| 250 | + {"float suffix", `let n = 1.0F`, `1.0F`, syntax.ClassNumber}, | |
| 251 | + | |
| 252 | + {"keyword", `pub fn area() -> Int {`, `fn`, syntax.ClassKeyword}, | |
| 253 | + {"visibility keyword", `pub fn area() -> Int {`, `pub`, syntax.ClassKeyword}, | |
| 254 | + {"try with a bang", `try! risky()`, `try!`, syntax.ClassKeyword}, | |
| 255 | + {"guard with a bang", `guard! x`, `guard!`, syntax.ClassKeyword}, | |
| 256 | + {"constant", `let ok = true`, `true`, syntax.ClassConstant}, | |
| 257 | + {"option constructor", `Some(1)`, `Some`, syntax.ClassConstant}, | |
| 258 | + {"result constructor", `Err("no")`, `Err`, syntax.ClassConstant}, | |
| 259 | + {"builtin", `println("hi")`, `println`, syntax.ClassBuiltin}, | |
| 260 | + {"builtin in a test", `assert_eq(1, 1)`, `assert_eq`, syntax.ClassBuiltin}, | |
| 261 | + | |
| 262 | + {"built-in type", `let n : Int = 1`, `Int`, syntax.ClassType}, | |
| 263 | + {"generic type", `let m : Map[String, Int] = {}`, `Map`, syntax.ClassType}, | |
| 264 | + {"a type nobody built in", `let p : Point = origin`, `Point`, syntax.ClassType}, | |
| 265 | + {"a constructor of your own", `Circle(1.0)`, `Circle`, syntax.ClassType}, | |
| 266 | + {"call", `area(shape)`, `area`, syntax.ClassFunction}, | |
| 267 | + {"plain identifier", `let shape = other`, `other`, syntax.ClassIdentifier}, | |
| 268 | + | |
| 269 | + {"package name", `@json.parse(text)`, `@json`, syntax.ClassType}, | |
| 270 | + {"nested package name", `@moonbitlang/core/builtin.foo()`, `@moonbitlang/core/builtin`, syntax.ClassType}, | |
| 271 | + {"hyphenated package name", `@my-pkg.foo()`, `@my-pkg`, syntax.ClassType}, | |
| 272 | + | |
| 273 | + {"label", `fn greet(name~ : String)`, `name~`, syntax.ClassAttribute}, | |
| 274 | + {"optional label", `fn greet(name~ : String = "x")`, `name~`, syntax.ClassAttribute}, | |
| 275 | + | |
| 276 | + {"method call", `xs.length()`, `length`, syntax.ClassFunction}, | |
| 277 | + {"field access", `point.x`, `x`, syntax.ClassIdentifier}, | |
| 278 | + {"tuple accessor dot", `pair.0`, `.`, syntax.ClassPunctuation}, | |
| 279 | + {"tuple accessor index", `pair.0`, `0`, syntax.ClassNumber}, | |
| 280 | + | |
| 281 | + {"range operator", `for i in 1..=10 {`, `..`, syntax.ClassOperator}, | |
| 282 | + {"pipe operator", `x |> f`, `|>`, syntax.ClassOperator}, | |
| 283 | + {"arrow", `Circle(r) => r`, `=>`, syntax.ClassOperator}, | |
| 284 | + {"colon is an operator rune", `Type::method`, `::`, syntax.ClassOperator}, | |
| 285 | + {"brace", `fn main {`, `{`, syntax.ClassPunctuation}, | |
| 286 | + } | |
| 287 | + | |
| 288 | + for _, c := range cases { | |
| 289 | + t.Run(c.name, func(t *testing.T) { | |
| 290 | + assertClass(t, c.src, c.text, c.class) | |
| 291 | + }) | |
| 292 | + } | |
| 293 | +} | |
| 294 | + | |
| 295 | +func TestRangeStopsTheNumberBeforeIt(t *testing.T) { | |
| 296 | + // "Before .., an integer ends first, so 1..=2 begins with 1 and ..=". A | |
| 297 | + // scanner that swallowed any dot would read 1. as a double and miscolour | |
| 298 | + // every range in the file. | |
| 299 | + spans := colouredLine(t, `for i in 1..=10 {`) | |
| 300 | + | |
| 301 | + if got, ok := find(spans, "1"); !ok || got.class != syntax.ClassNumber { | |
| 302 | + t.Errorf("in 1..=10, the 1 is %v, want a number on its own; got %v", got, spans) | |
| 303 | + } | |
| 304 | + if _, ok := find(spans, "1."); ok { | |
| 305 | + t.Errorf("in 1..=10, the scanner read 1. as a double: %v", spans) | |
| 306 | + } | |
| 307 | +} | |
| 308 | + | |
| 309 | +// --- one case per thing the scanner deliberately refuses -------------------- | |
| 310 | + | |
| 311 | +func TestRefusals(t *testing.T) { | |
| 312 | + cases := []struct { | |
| 313 | + name string | |
| 314 | + why string | |
| 315 | + src string | |
| 316 | + text string | |
| 317 | + class syntax.Class | |
| 318 | + }{ | |
| 319 | + { | |
| 320 | + name: "an interpolated expression is not code", | |
| 321 | + why: "finding where one ends needs the parser; a brace counter that got it wrong would end the string early", | |
| 322 | + src: `let s = "\{count + 1}"`, | |
| 323 | + text: `"\{count + 1}"`, | |
| 324 | + class: syntax.ClassString, | |
| 325 | + }, | |
| 326 | + { | |
| 327 | + name: "a lower-case number suffix is not a suffix", | |
| 328 | + why: "the grammar says the suffixes are upper case, so 42u is 42 and then the name u", | |
| 329 | + src: `let n = 42u`, | |
| 330 | + text: `42`, | |
| 331 | + class: syntax.ClassNumber, | |
| 332 | + }, | |
| 333 | + { | |
| 334 | + name: "a leading dot is never a number", | |
| 335 | + why: "MoonBit requires a digit before the point, so .5 is a dot and then a name", | |
| 336 | + src: `let n = .5`, | |
| 337 | + text: `.`, | |
| 338 | + class: syntax.ClassPunctuation, | |
| 339 | + }, | |
| 340 | + { | |
| 341 | + name: "a keyword after a dot is a field name", | |
| 342 | + why: "dot-identifiers use the identifier case rules without consulting the keyword table, so .if is valid", | |
| 343 | + src: `config.if`, | |
| 344 | + text: `if`, | |
| 345 | + class: syntax.ClassIdentifier, | |
| 346 | + }, | |
| 347 | + { | |
| 348 | + name: "a reserved word is not a keyword", | |
| 349 | + why: "move, ref and the rest are identifiers the compiler warns about; colouring them would deny a valid name", | |
| 350 | + src: `let ref = 1`, | |
| 351 | + text: `ref`, | |
| 352 | + class: syntax.ClassIdentifier, | |
| 353 | + }, | |
| 354 | + { | |
| 355 | + name: "an enum constructor of your own is a type", | |
| 356 | + why: "nothing in the syntax separates Circle(1.0) from a type applied to arguments", | |
| 357 | + src: `Circle(1.0)`, | |
| 358 | + text: `Circle`, | |
| 359 | + class: syntax.ClassType, | |
| 360 | + }, | |
| 361 | + { | |
| 362 | + name: "an unterminated literal stops at the line", | |
| 363 | + why: "a newline before the closing quote is an unterminated-literal error, so there is nothing to carry", | |
| 364 | + src: `let s = "oops`, | |
| 365 | + text: `"oops`, | |
| 366 | + class: syntax.ClassString, | |
| 367 | + }, | |
| 368 | + { | |
| 369 | + name: "an upper-case name cannot form a label", | |
| 370 | + why: "the grammar says ASCII-uppercase identifiers and keywords cannot form labels", | |
| 371 | + src: `Foo~`, | |
| 372 | + text: `Foo`, | |
| 373 | + class: syntax.ClassType, | |
| 374 | + }, | |
| 375 | + { | |
| 376 | + name: "a keyword cannot form a label", | |
| 377 | + why: "same rule; let~ is not a labelled argument called let", | |
| 378 | + src: `let~`, | |
| 379 | + text: `let`, | |
| 380 | + class: syntax.ClassKeyword, | |
| 381 | + }, | |
| 382 | + { | |
| 383 | + name: "b is only a prefix when the quote touches it", | |
| 384 | + why: "otherwise the variable b in `b + 1` would open a literal", | |
| 385 | + src: `b + 1`, | |
| 386 | + text: `b`, | |
| 387 | + class: syntax.ClassIdentifier, | |
| 388 | + }, | |
| 389 | + { | |
| 390 | + name: "a package part must follow the slash", | |
| 391 | + why: "@a/2 is a package and then a division, not a package part called 2", | |
| 392 | + src: `@a/2`, | |
| 393 | + text: `@a`, | |
| 394 | + class: syntax.ClassType, | |
| 395 | + }, | |
| 396 | + { | |
| 397 | + name: "a doc comment is coloured like any other comment", | |
| 398 | + why: "turbo-core's Class set is closed and has one comment class, which is what lets one theme colour every language", | |
| 399 | + src: `/// docs`, | |
| 400 | + text: `/// docs`, | |
| 401 | + class: syntax.ClassComment, | |
| 402 | + }, | |
| 403 | + } | |
| 404 | + | |
| 405 | + for _, c := range cases { | |
| 406 | + t.Run(c.name, func(t *testing.T) { | |
| 407 | + assertClass(t, c.src, c.text, c.class) | |
| 408 | + }) | |
| 409 | + } | |
| 410 | +} | |
| 411 | + | |
| 412 | +// A string *nested inside* an interpolation ends the outer literal, because | |
| 413 | +// the scanner takes the first unescaped quote as the closer. The grammar says | |
| 414 | +// otherwise — "braces inside nested literals do not affect matching" — so this | |
| 415 | +// is the precise shape of what the scanner gives up by not parsing, and it is | |
| 416 | +// pinned here rather than described loosely. | |
| 417 | +// | |
| 418 | +// The spans stay in order and never overlap, so nothing downstream breaks; the | |
| 419 | +// cost is that text inside the nested literal may take a different colour. | |
| 420 | +func TestAStringInsideAnInterpolationEndsTheOuterLiteral(t *testing.T) { | |
| 421 | + // The ordinary case is one span, which is what almost every interpolation | |
| 422 | + // in real MoonBit looks like. | |
| 423 | + if spans := colouredLine(t, `let s = "a \{b} c"`); len(spans) != 4 { | |
| 424 | + t.Errorf(`"a \{b} c" gave %v, want the whole literal as one span`, spans) | |
| 425 | + } | |
| 426 | + | |
| 427 | + // With a nested literal it is not one span, and the inside of that literal | |
| 428 | + // is not coloured as a string. | |
| 429 | + spans := colouredLine(t, `let s = "a \{f("x")} c"`) | |
| 430 | + if got, ok := find(spans, "x"); !ok || got.class != syntax.ClassIdentifier { | |
| 431 | + t.Errorf(`"a \{f("x")} c" coloured the nested literal's contents as %v, want the documented identifier`, spans) | |
| 432 | + } | |
| 433 | + | |
| 434 | + // Whatever it does colour, the invariants hold. | |
| 435 | + previousEnd := 0 | |
| 436 | + for _, span := range moonbitlang.Highlight(`let s = "a \{f("x")} c"`)[0] { | |
| 437 | + if span.Start < previousEnd { | |
| 438 | + t.Errorf("spans overlap: %v", spans) | |
| 439 | + } | |
| 440 | + previousEnd = span.End | |
| 441 | + } | |
| 442 | +} | |
| 443 | + | |
| 444 | +func TestANonASCIIIdentifierIsLeftUncoloured(t *testing.T) { | |
| 445 | + // MoonBit allows CJK and other ranges in identifiers; turbo-core's rune | |
| 446 | + // predicates are ASCII. Such a name is stepped over rather than guessed at, | |
| 447 | + // which is a boundary worth knowing rather than a defect to hide. | |
| 448 | + spans := colouredLine(t, `let 名前 = 1`) | |
| 449 | + | |
| 450 | + if _, ok := find(spans, "名前"); ok { | |
| 451 | + t.Errorf("a CJK identifier was coloured: %v", spans) | |
| 452 | + } | |
| 453 | + if got, ok := find(spans, "let"); !ok || got.class != syntax.ClassKeyword { | |
| 454 | + t.Errorf("the rest of the line stopped colouring: %v", spans) | |
| 455 | + } | |
| 456 | +} | |
| 457 | + | |
| 458 | +func TestHighlightIsWhatTheRegistryUses(t *testing.T) { | |
| 459 | + moonbitlang.Register() | |
| 460 | + | |
| 461 | + spans := syntax.Highlight(moonbitlang.Language, "fn main {\n") | |
| 462 | + if len(spans) == 0 || len(spans[0]) == 0 { | |
| 463 | + t.Fatalf("syntax.Highlight gave nothing for MoonBit: %v", spans) | |
| 464 | + } | |
| 465 | + if spans[0][0].Class != syntax.ClassKeyword { | |
| 466 | + t.Errorf("the registered highlighter coloured fn as %s, want a keyword", spans[0][0].Class) | |
| 467 | + } | |
| 468 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,468 @@ | |||
| 1 | +package moonbitlang_test | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "strings" | ||
| 5 | + "testing" | ||
| 6 | + | ||
| 7 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 8 | + | ||
| 9 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | ||
| 10 | +) | ||
| 11 | + | ||
| 12 | +// coloured is one span with the text it covers, which is what a test wants to | ||
| 13 | +// talk about: "the word fn is a keyword", not "columns 0 to 2 are class 1". | ||
| 14 | +type coloured struct { | ||
| 15 | + text string | ||
| 16 | + class syntax.Class | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +func (c coloured) String() string { return c.text + ":" + c.class.String() } | ||
| 20 | + | ||
| 21 | +// colouredLine returns every span of one line of source, with its text. | ||
| 22 | +func colouredLine(t *testing.T, src string) []coloured { | ||
| 23 | + t.Helper() | ||
| 24 | + | ||
| 25 | + lines := moonbitlang.Highlight(src) | ||
| 26 | + if len(lines) != 1 { | ||
| 27 | + t.Fatalf("Highlight(%q) returned %d lines, want 1", src, len(lines)) | ||
| 28 | + } | ||
| 29 | + return withText([]rune(src), lines[0]) | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +// withText pairs each span with the runes it covers. | ||
| 33 | +func withText(line []rune, spans []syntax.Span) []coloured { | ||
| 34 | + out := make([]coloured, 0, len(spans)) | ||
| 35 | + for _, span := range spans { | ||
| 36 | + out = append(out, coloured{string(line[span.Start:span.End]), span.Class}) | ||
| 37 | + } | ||
| 38 | + return out | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +// find returns the span covering exactly the given text, if there is one. | ||
| 42 | +func find(spans []coloured, text string) (coloured, bool) { | ||
| 43 | + for _, span := range spans { | ||
| 44 | + if span.text == text { | ||
| 45 | + return span, true | ||
| 46 | + } | ||
| 47 | + } | ||
| 48 | + return coloured{}, false | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +// assertClass fails unless one span covers exactly text and has the wanted | ||
| 52 | +// class. Asking for the whole text means a scanner that split a construct in | ||
| 53 | +// two is caught, not only one that coloured it wrongly. | ||
| 54 | +func assertClass(t *testing.T, src, text string, want syntax.Class) { | ||
| 55 | + t.Helper() | ||
| 56 | + | ||
| 57 | + spans := colouredLine(t, src) | ||
| 58 | + got, ok := find(spans, text) | ||
| 59 | + if !ok { | ||
| 60 | + t.Fatalf("in %q: no single span covers %q; got %v", src, text, spans) | ||
| 61 | + } | ||
| 62 | + if got.class != want { | ||
| 63 | + t.Errorf("in %q: %q is %s, want %s", src, text, got.class, want) | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +// --- the three invariants the editor relies on ------------------------------ | ||
| 68 | + | ||
| 69 | +// A representative body of MoonBit, used by the invariant tests below. It is | ||
| 70 | +// deliberately a mixture: every construct the scanner knows, some broken input, | ||
| 71 | +// and the constructs that most easily run into one another. | ||
| 72 | +const sample = `///| A doc comment. | ||
| 73 | +// An ordinary one. | ||
| 74 | +#deprecated("use area instead") | ||
| 75 | +pub fn area(shape : Shape, scale~ : Double = 1.0) -> Double raise { | ||
| 76 | + let table : Map[String, Int] = { "a": 1, "b": 0xFF } | ||
| 77 | + let text = "got \{shape} and \{scale}" | ||
| 78 | + let raw = | ||
| 79 | + #|literal ${not interpolated} | ||
| 80 | + $|and \{interpolated} | ||
| 81 | + guard scale > 0.0 else { fail("scale") } | ||
| 82 | + match shape { | ||
| 83 | + Circle(r) => 3.14159 * r * r | ||
| 84 | + Rect(w, h) => w * h | ||
| 85 | + } | ||
| 86 | + let range = 1..=2 | ||
| 87 | + let pair = (1, 2).0 | ||
| 88 | + let bytes = b"\xFF\x00" | ||
| 89 | + let ch = 'x' | ||
| 90 | + let pattern = re"[a-z]+" | ||
| 91 | + ignore(@json.parse(text)) | ||
| 92 | + let broken = "unterminated | ||
| 93 | + let after = 1 | ||
| 94 | +}` | ||
| 95 | + | ||
| 96 | +func TestEveryLineGetsExactlyOneEntry(t *testing.T) { | ||
| 97 | + // The editor indexes the result by line number without checking, so a | ||
| 98 | + // scanner that returned one entry fewer would draw every line below the | ||
| 99 | + // gap in the wrong colours. | ||
| 100 | + src := sample + "\n\n\ntrailing\n" | ||
| 101 | + want := len(strings.Split(src, "\n")) | ||
| 102 | + | ||
| 103 | + if got := len(moonbitlang.Highlight(src)); got != want { | ||
| 104 | + t.Errorf("Highlight returned %d lines for %d lines of source", got, want) | ||
| 105 | + } | ||
| 106 | +} | ||
| 107 | + | ||
| 108 | +func TestSpansAreInOrderAndDoNotOverlap(t *testing.T) { | ||
| 109 | + // Spans are drawn in the order they arrive. Two out of order paint over | ||
| 110 | + // each other, and nothing fails. | ||
| 111 | + for number, spans := range moonbitlang.Highlight(sample) { | ||
| 112 | + line := []rune(strings.Split(sample, "\n")[number]) | ||
| 113 | + previousEnd := 0 | ||
| 114 | + | ||
| 115 | + for _, span := range spans { | ||
| 116 | + switch { | ||
| 117 | + case span.Start < previousEnd: | ||
| 118 | + t.Errorf("line %d: span %v starts before the previous one ended at %d", number+1, span, previousEnd) | ||
| 119 | + case span.Start >= span.End: | ||
| 120 | + t.Errorf("line %d: span %v is empty or inverted", number+1, span) | ||
| 121 | + case span.End > len(line): | ||
| 122 | + t.Errorf("line %d: span %v runs past the %d runes of the line", number+1, span, len(line)) | ||
| 123 | + } | ||
| 124 | + previousEnd = span.End | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +func TestBrokenInputStillColours(t *testing.T) { | ||
| 130 | + // Source under the cursor is invalid most of the time it is being typed. | ||
| 131 | + broken := []string{ | ||
| 132 | + `let x = "`, | ||
| 133 | + `let x = '`, | ||
| 134 | + `let x = b"\`, | ||
| 135 | + `fn (`, | ||
| 136 | + `#`, | ||
| 137 | + `#|`, | ||
| 138 | + `$|`, | ||
| 139 | + `@`, | ||
| 140 | + `@/`, | ||
| 141 | + `.`, | ||
| 142 | + `..`, | ||
| 143 | + `1.`, | ||
| 144 | + `0x`, | ||
| 145 | + `re"`, | ||
| 146 | + `}}}`, | ||
| 147 | + `let x = 1e`, | ||
| 148 | + `let x = 1e-`, | ||
| 149 | + `~`, | ||
| 150 | + `let x~`, | ||
| 151 | + } | ||
| 152 | + for _, src := range broken { | ||
| 153 | + spans := moonbitlang.Highlight(src) | ||
| 154 | + if len(spans) != 1 { | ||
| 155 | + t.Errorf("Highlight(%q) returned %d lines, want 1", src, len(spans)) | ||
| 156 | + } | ||
| 157 | + } | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +func TestNothingCarriesOntoTheNextLine(t *testing.T) { | ||
| 161 | + // This is the property that makes MoonBit's scanner stateless: no literal | ||
| 162 | + // may reach the next line, so a stray quote must not paint the rest of the | ||
| 163 | + // file. Every other editor in this family would carry here. | ||
| 164 | + // | ||
| 165 | + // Today the carry type is empty, so this cannot fail — and that is why it | ||
| 166 | + // is written down. It is the guard on the type: a later change that gives | ||
| 167 | + // carry a field has to keep every one of these openers from reaching the | ||
| 168 | + // line below, and this is where it finds out that it did not. | ||
| 169 | + openers := []string{`"`, `'`, `b"`, `b'`, `re"`, `#|`, `$|`, `#deprecated(`, `//`} | ||
| 170 | + | ||
| 171 | + for _, opener := range openers { | ||
| 172 | + src := "let a = " + opener + "\nfn main {\n println(\"hi\")\n}" | ||
| 173 | + lines := moonbitlang.Highlight(src) | ||
| 174 | + | ||
| 175 | + second := withText([]rune("fn main {"), lines[1]) | ||
| 176 | + if got, ok := find(second, "fn"); !ok || got.class != syntax.ClassKeyword { | ||
| 177 | + t.Errorf("after a line opening with %q, fn on the next line is %v, want a keyword", opener, second) | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | +} | ||
| 181 | + | ||
| 182 | +func TestAnEmptyDocumentIsOneEmptyLine(t *testing.T) { | ||
| 183 | + if got := moonbitlang.Highlight(""); len(got) != 1 || len(got[0]) != 0 { | ||
| 184 | + t.Errorf("Highlight(\"\") = %v, want one line with no spans", got) | ||
| 185 | + } | ||
| 186 | +} | ||
| 187 | + | ||
| 188 | +func TestCRLFColoursTheSameAsLF(t *testing.T) { | ||
| 189 | + unix := moonbitlang.Highlight("fn main {\n println(\"hi\")\n}") | ||
| 190 | + windows := moonbitlang.Highlight("fn main {\r\n println(\"hi\")\r\n}") | ||
| 191 | + | ||
| 192 | + if len(unix) != len(windows) { | ||
| 193 | + t.Fatalf("CRLF gave %d lines, LF gave %d", len(windows), len(unix)) | ||
| 194 | + } | ||
| 195 | + for i := range unix { | ||
| 196 | + if len(unix[i]) != len(windows[i]) { | ||
| 197 | + t.Errorf("line %d: CRLF gave %v, LF gave %v", i+1, windows[i], unix[i]) | ||
| 198 | + } | ||
| 199 | + } | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +// --- one case per construct ------------------------------------------------- | ||
| 203 | + | ||
| 204 | +func TestConstructs(t *testing.T) { | ||
| 205 | + cases := []struct { | ||
| 206 | + name string | ||
| 207 | + src string | ||
| 208 | + text string | ||
| 209 | + class syntax.Class | ||
| 210 | + }{ | ||
| 211 | + {"line comment", `let x = 1 // why`, `// why`, syntax.ClassComment}, | ||
| 212 | + {"doc comment", `/// Adds two numbers.`, `/// Adds two numbers.`, syntax.ClassComment}, | ||
| 213 | + {"section marker", `///|`, `///|`, syntax.ClassComment}, | ||
| 214 | + {"comment wins over division", `// a / b`, `// a / b`, syntax.ClassComment}, | ||
| 215 | + | ||
| 216 | + {"attribute", `#deprecated("use area")`, `#deprecated("use area")`, syntax.ClassAttribute}, | ||
| 217 | + {"namespaced attribute", `#custom.attribute(key="v")`, `#custom.attribute(key="v")`, syntax.ClassAttribute}, | ||
| 218 | + {"bare attribute", `#external`, `#external`, syntax.ClassAttribute}, | ||
| 219 | + | ||
| 220 | + {"raw multiline prefix", ` #|hello`, `#|`, syntax.ClassPunctuation}, | ||
| 221 | + {"raw multiline text", ` #|hello`, `hello`, syntax.ClassString}, | ||
| 222 | + {"interpolated multiline prefix", ` $|hi \{name}`, `$|`, syntax.ClassPunctuation}, | ||
| 223 | + {"interpolated multiline text", ` $|hi \{name}`, `hi \{name}`, syntax.ClassString}, | ||
| 224 | + | ||
| 225 | + {"string", `let s = "hi"`, `"hi"`, syntax.ClassString}, | ||
| 226 | + {"string stops at its closing quote", `let s = "hi" + name`, `"hi"`, syntax.ClassString}, | ||
| 227 | + {"code after a string is still code", `let s = "hi" + name`, `name`, syntax.ClassIdentifier}, | ||
| 228 | + {"char stops at its closing quote", `let c = 'x' + 1`, `'x'`, syntax.ClassChar}, | ||
| 229 | + {"code after a char is still code", `let c = 'x' + 1`, `1`, syntax.ClassNumber}, | ||
| 230 | + {"empty string", `let s = ""`, `""`, syntax.ClassString}, | ||
| 231 | + {"string with interpolation", `let s = "a \{b} c"`, `"a \{b} c"`, syntax.ClassString}, | ||
| 232 | + {"string with escaped quote", `let s = "a \" b"`, `"a \" b"`, syntax.ClassString}, | ||
| 233 | + {"bytes literal", `let b = b"\xFF"`, `b"\xFF"`, syntax.ClassString}, | ||
| 234 | + {"regex literal", `let r = re"[a-z]+"`, `re"[a-z]+"`, syntax.ClassString}, | ||
| 235 | + {"char literal", `let c = 'x'`, `'x'`, syntax.ClassChar}, | ||
| 236 | + {"escaped char literal", `let c = '\n'`, `'\n'`, syntax.ClassChar}, | ||
| 237 | + {"byte literal", `let c = b'x'`, `b'x'`, syntax.ClassChar}, | ||
| 238 | + | ||
| 239 | + {"decimal", `let n = 1_000`, `1_000`, syntax.ClassNumber}, | ||
| 240 | + {"hexadecimal", `let n = 0xFF_FF`, `0xFF_FF`, syntax.ClassNumber}, | ||
| 241 | + {"octal", `let n = 0o17`, `0o17`, syntax.ClassNumber}, | ||
| 242 | + {"binary", `let n = 0b1010`, `0b1010`, syntax.ClassNumber}, | ||
| 243 | + {"double", `let n = 1.5`, `1.5`, syntax.ClassNumber}, | ||
| 244 | + {"double with a trailing point", `let n = 1.`, `1.`, syntax.ClassNumber}, | ||
| 245 | + {"exponent", `let n = 1.5e-3`, `1.5e-3`, syntax.ClassNumber}, | ||
| 246 | + {"hex float", `let n = 0x1.8p3F`, `0x1.8p3F`, syntax.ClassNumber}, | ||
| 247 | + {"uint suffix", `let n = 42U`, `42U`, syntax.ClassNumber}, | ||
| 248 | + {"uint64 suffix", `let n = 42UL`, `42UL`, syntax.ClassNumber}, | ||
| 249 | + {"bigint suffix", `let n = 42N`, `42N`, syntax.ClassNumber}, | ||
| 250 | + {"float suffix", `let n = 1.0F`, `1.0F`, syntax.ClassNumber}, | ||
| 251 | + | ||
| 252 | + {"keyword", `pub fn area() -> Int {`, `fn`, syntax.ClassKeyword}, | ||
| 253 | + {"visibility keyword", `pub fn area() -> Int {`, `pub`, syntax.ClassKeyword}, | ||
| 254 | + {"try with a bang", `try! risky()`, `try!`, syntax.ClassKeyword}, | ||
| 255 | + {"guard with a bang", `guard! x`, `guard!`, syntax.ClassKeyword}, | ||
| 256 | + {"constant", `let ok = true`, `true`, syntax.ClassConstant}, | ||
| 257 | + {"option constructor", `Some(1)`, `Some`, syntax.ClassConstant}, | ||
| 258 | + {"result constructor", `Err("no")`, `Err`, syntax.ClassConstant}, | ||
| 259 | + {"builtin", `println("hi")`, `println`, syntax.ClassBuiltin}, | ||
| 260 | + {"builtin in a test", `assert_eq(1, 1)`, `assert_eq`, syntax.ClassBuiltin}, | ||
| 261 | + | ||
| 262 | + {"built-in type", `let n : Int = 1`, `Int`, syntax.ClassType}, | ||
| 263 | + {"generic type", `let m : Map[String, Int] = {}`, `Map`, syntax.ClassType}, | ||
| 264 | + {"a type nobody built in", `let p : Point = origin`, `Point`, syntax.ClassType}, | ||
| 265 | + {"a constructor of your own", `Circle(1.0)`, `Circle`, syntax.ClassType}, | ||
| 266 | + {"call", `area(shape)`, `area`, syntax.ClassFunction}, | ||
| 267 | + {"plain identifier", `let shape = other`, `other`, syntax.ClassIdentifier}, | ||
| 268 | + | ||
| 269 | + {"package name", `@json.parse(text)`, `@json`, syntax.ClassType}, | ||
| 270 | + {"nested package name", `@moonbitlang/core/builtin.foo()`, `@moonbitlang/core/builtin`, syntax.ClassType}, | ||
| 271 | + {"hyphenated package name", `@my-pkg.foo()`, `@my-pkg`, syntax.ClassType}, | ||
| 272 | + | ||
| 273 | + {"label", `fn greet(name~ : String)`, `name~`, syntax.ClassAttribute}, | ||
| 274 | + {"optional label", `fn greet(name~ : String = "x")`, `name~`, syntax.ClassAttribute}, | ||
| 275 | + | ||
| 276 | + {"method call", `xs.length()`, `length`, syntax.ClassFunction}, | ||
| 277 | + {"field access", `point.x`, `x`, syntax.ClassIdentifier}, | ||
| 278 | + {"tuple accessor dot", `pair.0`, `.`, syntax.ClassPunctuation}, | ||
| 279 | + {"tuple accessor index", `pair.0`, `0`, syntax.ClassNumber}, | ||
| 280 | + | ||
| 281 | + {"range operator", `for i in 1..=10 {`, `..`, syntax.ClassOperator}, | ||
| 282 | + {"pipe operator", `x |> f`, `|>`, syntax.ClassOperator}, | ||
| 283 | + {"arrow", `Circle(r) => r`, `=>`, syntax.ClassOperator}, | ||
| 284 | + {"colon is an operator rune", `Type::method`, `::`, syntax.ClassOperator}, | ||
| 285 | + {"brace", `fn main {`, `{`, syntax.ClassPunctuation}, | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + for _, c := range cases { | ||
| 289 | + t.Run(c.name, func(t *testing.T) { | ||
| 290 | + assertClass(t, c.src, c.text, c.class) | ||
| 291 | + }) | ||
| 292 | + } | ||
| 293 | +} | ||
| 294 | + | ||
| 295 | +func TestRangeStopsTheNumberBeforeIt(t *testing.T) { | ||
| 296 | + // "Before .., an integer ends first, so 1..=2 begins with 1 and ..=". A | ||
| 297 | + // scanner that swallowed any dot would read 1. as a double and miscolour | ||
| 298 | + // every range in the file. | ||
| 299 | + spans := colouredLine(t, `for i in 1..=10 {`) | ||
| 300 | + | ||
| 301 | + if got, ok := find(spans, "1"); !ok || got.class != syntax.ClassNumber { | ||
| 302 | + t.Errorf("in 1..=10, the 1 is %v, want a number on its own; got %v", got, spans) | ||
| 303 | + } | ||
| 304 | + if _, ok := find(spans, "1."); ok { | ||
| 305 | + t.Errorf("in 1..=10, the scanner read 1. as a double: %v", spans) | ||
| 306 | + } | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +// --- one case per thing the scanner deliberately refuses -------------------- | ||
| 310 | + | ||
| 311 | +func TestRefusals(t *testing.T) { | ||
| 312 | + cases := []struct { | ||
| 313 | + name string | ||
| 314 | + why string | ||
| 315 | + src string | ||
| 316 | + text string | ||
| 317 | + class syntax.Class | ||
| 318 | + }{ | ||
| 319 | + { | ||
| 320 | + name: "an interpolated expression is not code", | ||
| 321 | + why: "finding where one ends needs the parser; a brace counter that got it wrong would end the string early", | ||
| 322 | + src: `let s = "\{count + 1}"`, | ||
| 323 | + text: `"\{count + 1}"`, | ||
| 324 | + class: syntax.ClassString, | ||
| 325 | + }, | ||
| 326 | + { | ||
| 327 | + name: "a lower-case number suffix is not a suffix", | ||
| 328 | + why: "the grammar says the suffixes are upper case, so 42u is 42 and then the name u", | ||
| 329 | + src: `let n = 42u`, | ||
| 330 | + text: `42`, | ||
| 331 | + class: syntax.ClassNumber, | ||
| 332 | + }, | ||
| 333 | + { | ||
| 334 | + name: "a leading dot is never a number", | ||
| 335 | + why: "MoonBit requires a digit before the point, so .5 is a dot and then a name", | ||
| 336 | + src: `let n = .5`, | ||
| 337 | + text: `.`, | ||
| 338 | + class: syntax.ClassPunctuation, | ||
| 339 | + }, | ||
| 340 | + { | ||
| 341 | + name: "a keyword after a dot is a field name", | ||
| 342 | + why: "dot-identifiers use the identifier case rules without consulting the keyword table, so .if is valid", | ||
| 343 | + src: `config.if`, | ||
| 344 | + text: `if`, | ||
| 345 | + class: syntax.ClassIdentifier, | ||
| 346 | + }, | ||
| 347 | + { | ||
| 348 | + name: "a reserved word is not a keyword", | ||
| 349 | + why: "move, ref and the rest are identifiers the compiler warns about; colouring them would deny a valid name", | ||
| 350 | + src: `let ref = 1`, | ||
| 351 | + text: `ref`, | ||
| 352 | + class: syntax.ClassIdentifier, | ||
| 353 | + }, | ||
| 354 | + { | ||
| 355 | + name: "an enum constructor of your own is a type", | ||
| 356 | + why: "nothing in the syntax separates Circle(1.0) from a type applied to arguments", | ||
| 357 | + src: `Circle(1.0)`, | ||
| 358 | + text: `Circle`, | ||
| 359 | + class: syntax.ClassType, | ||
| 360 | + }, | ||
| 361 | + { | ||
| 362 | + name: "an unterminated literal stops at the line", | ||
| 363 | + why: "a newline before the closing quote is an unterminated-literal error, so there is nothing to carry", | ||
| 364 | + src: `let s = "oops`, | ||
| 365 | + text: `"oops`, | ||
| 366 | + class: syntax.ClassString, | ||
| 367 | + }, | ||
| 368 | + { | ||
| 369 | + name: "an upper-case name cannot form a label", | ||
| 370 | + why: "the grammar says ASCII-uppercase identifiers and keywords cannot form labels", | ||
| 371 | + src: `Foo~`, | ||
| 372 | + text: `Foo`, | ||
| 373 | + class: syntax.ClassType, | ||
| 374 | + }, | ||
| 375 | + { | ||
| 376 | + name: "a keyword cannot form a label", | ||
| 377 | + why: "same rule; let~ is not a labelled argument called let", | ||
| 378 | + src: `let~`, | ||
| 379 | + text: `let`, | ||
| 380 | + class: syntax.ClassKeyword, | ||
| 381 | + }, | ||
| 382 | + { | ||
| 383 | + name: "b is only a prefix when the quote touches it", | ||
| 384 | + why: "otherwise the variable b in `b + 1` would open a literal", | ||
| 385 | + src: `b + 1`, | ||
| 386 | + text: `b`, | ||
| 387 | + class: syntax.ClassIdentifier, | ||
| 388 | + }, | ||
| 389 | + { | ||
| 390 | + name: "a package part must follow the slash", | ||
| 391 | + why: "@a/2 is a package and then a division, not a package part called 2", | ||
| 392 | + src: `@a/2`, | ||
| 393 | + text: `@a`, | ||
| 394 | + class: syntax.ClassType, | ||
| 395 | + }, | ||
| 396 | + { | ||
| 397 | + name: "a doc comment is coloured like any other comment", | ||
| 398 | + why: "turbo-core's Class set is closed and has one comment class, which is what lets one theme colour every language", | ||
| 399 | + src: `/// docs`, | ||
| 400 | + text: `/// docs`, | ||
| 401 | + class: syntax.ClassComment, | ||
| 402 | + }, | ||
| 403 | + } | ||
| 404 | + | ||
| 405 | + for _, c := range cases { | ||
| 406 | + t.Run(c.name, func(t *testing.T) { | ||
| 407 | + assertClass(t, c.src, c.text, c.class) | ||
| 408 | + }) | ||
| 409 | + } | ||
| 410 | +} | ||
| 411 | + | ||
| 412 | +// A string *nested inside* an interpolation ends the outer literal, because | ||
| 413 | +// the scanner takes the first unescaped quote as the closer. The grammar says | ||
| 414 | +// otherwise — "braces inside nested literals do not affect matching" — so this | ||
| 415 | +// is the precise shape of what the scanner gives up by not parsing, and it is | ||
| 416 | +// pinned here rather than described loosely. | ||
| 417 | +// | ||
| 418 | +// The spans stay in order and never overlap, so nothing downstream breaks; the | ||
| 419 | +// cost is that text inside the nested literal may take a different colour. | ||
| 420 | +func TestAStringInsideAnInterpolationEndsTheOuterLiteral(t *testing.T) { | ||
| 421 | + // The ordinary case is one span, which is what almost every interpolation | ||
| 422 | + // in real MoonBit looks like. | ||
| 423 | + if spans := colouredLine(t, `let s = "a \{b} c"`); len(spans) != 4 { | ||
| 424 | + t.Errorf(`"a \{b} c" gave %v, want the whole literal as one span`, spans) | ||
| 425 | + } | ||
| 426 | + | ||
| 427 | + // With a nested literal it is not one span, and the inside of that literal | ||
| 428 | + // is not coloured as a string. | ||
| 429 | + spans := colouredLine(t, `let s = "a \{f("x")} c"`) | ||
| 430 | + if got, ok := find(spans, "x"); !ok || got.class != syntax.ClassIdentifier { | ||
| 431 | + t.Errorf(`"a \{f("x")} c" coloured the nested literal's contents as %v, want the documented identifier`, spans) | ||
| 432 | + } | ||
| 433 | + | ||
| 434 | + // Whatever it does colour, the invariants hold. | ||
| 435 | + previousEnd := 0 | ||
| 436 | + for _, span := range moonbitlang.Highlight(`let s = "a \{f("x")} c"`)[0] { | ||
| 437 | + if span.Start < previousEnd { | ||
| 438 | + t.Errorf("spans overlap: %v", spans) | ||
| 439 | + } | ||
| 440 | + previousEnd = span.End | ||
| 441 | + } | ||
| 442 | +} | ||
| 443 | + | ||
| 444 | +func TestANonASCIIIdentifierIsLeftUncoloured(t *testing.T) { | ||
| 445 | + // MoonBit allows CJK and other ranges in identifiers; turbo-core's rune | ||
| 446 | + // predicates are ASCII. Such a name is stepped over rather than guessed at, | ||
| 447 | + // which is a boundary worth knowing rather than a defect to hide. | ||
| 448 | + spans := colouredLine(t, `let 名前 = 1`) | ||
| 449 | + | ||
| 450 | + if _, ok := find(spans, "名前"); ok { | ||
| 451 | + t.Errorf("a CJK identifier was coloured: %v", spans) | ||
| 452 | + } | ||
| 453 | + if got, ok := find(spans, "let"); !ok || got.class != syntax.ClassKeyword { | ||
| 454 | + t.Errorf("the rest of the line stopped colouring: %v", spans) | ||
| 455 | + } | ||
| 456 | +} | ||
| 457 | + | ||
| 458 | +func TestHighlightIsWhatTheRegistryUses(t *testing.T) { | ||
| 459 | + moonbitlang.Register() | ||
| 460 | + | ||
| 461 | + spans := syntax.Highlight(moonbitlang.Language, "fn main {\n") | ||
| 462 | + if len(spans) == 0 || len(spans[0]) == 0 { | ||
| 463 | + t.Fatalf("syntax.Highlight gave nothing for MoonBit: %v", spans) | ||
| 464 | + } | ||
| 465 | + if spans[0][0].Class != syntax.ClassKeyword { | ||
| 466 | + t.Errorf("the registered highlighter coloured fn as %s, want a keyword", spans[0][0].Class) | ||
| 467 | + } | ||
| 468 | +} | ||
added
internal/moonbitlang/settings.toml.tmpl +18 -0 | new file mode 100644 | ||
| @@ -0,0 +1,18 @@ | ||
| 1 | +# turbo-moonbit project settings. | |
| 2 | +# | |
| 3 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -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-moonbit project settings. | ||
| 2 | +# | ||
| 3 | +# These apply to everyone who opens this project in turbo-moonbit. 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-moonbit -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/moonbitlang/snippets.toml.tmpl +106 -0 | new file mode 100644 | ||
| @@ -0,0 +1,106 @@ | ||
| 1 | +# turbo-moonbit 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: bash, dockerfile, html, javascript, markdown, moonbit, toml, | |
| 10 | +# xml, yaml. Leave it out and the snippet is offered everywhere. | |
| 11 | +# | |
| 12 | +# Bodies are indented with two spaces, which is what `moon fmt` writes. Running | |
| 13 | +# the formatter over a file indented any other way rewrites the whole file, so | |
| 14 | +# a snippet that disagrees with it turns one insertion into a large diff. | |
| 15 | +# | |
| 16 | +# Every MoonBit body below is written in single quotes — '''…''' rather than | |
| 17 | +# """…""" — because MoonBit interpolates with \{…}, and a backslash before a | |
| 18 | +# brace is not a valid escape in a TOML basic string. In a literal string a | |
| 19 | +# backslash is just a backslash, which is exactly what a MoonBit snippet needs. | |
| 20 | +# | |
| 21 | +# Your own snippets, shared across every project, go in: | |
| 22 | +# %s | |
| 23 | + | |
| 24 | +[[snippet]] | |
| 25 | +name = "main" | |
| 26 | +group = "MoonBit" | |
| 27 | +languages = ["moonbit"] | |
| 28 | +body = ''' | |
| 29 | +fn main { | |
| 30 | + println("Hello, MoonBit!") | |
| 31 | +}''' | |
| 32 | + | |
| 33 | +[[snippet]] | |
| 34 | +name = "test" | |
| 35 | +group = "MoonBit" | |
| 36 | +languages = ["moonbit"] | |
| 37 | +body = ''' | |
| 38 | +test "it works" { | |
| 39 | + assert_eq(1 + 1, 2) | |
| 40 | +}''' | |
| 41 | + | |
| 42 | +[[snippet]] | |
| 43 | +name = "struct" | |
| 44 | +group = "MoonBit" | |
| 45 | +languages = ["moonbit"] | |
| 46 | +body = ''' | |
| 47 | +struct Point { | |
| 48 | + x : Int | |
| 49 | + y : Int | |
| 50 | +} derive(Eq)''' | |
| 51 | + | |
| 52 | +[[snippet]] | |
| 53 | +name = "enum" | |
| 54 | +group = "MoonBit" | |
| 55 | +languages = ["moonbit"] | |
| 56 | +body = ''' | |
| 57 | +enum Shape { | |
| 58 | + Circle(Double) | |
| 59 | + Rect(Double, Double) | |
| 60 | +} derive(Debug)''' | |
| 61 | + | |
| 62 | +[[snippet]] | |
| 63 | +name = "match" | |
| 64 | +group = "MoonBit" | |
| 65 | +languages = ["moonbit"] | |
| 66 | +body = ''' | |
| 67 | +match value { | |
| 68 | + Some(x) => "got \{x}" | |
| 69 | + None => "nothing" | |
| 70 | +}''' | |
| 71 | + | |
| 72 | +[[snippet]] | |
| 73 | +name = "trait impl" | |
| 74 | +group = "MoonBit" | |
| 75 | +languages = ["moonbit"] | |
| 76 | +body = ''' | |
| 77 | +impl Show for Point with fn output(self, logger) { | |
| 78 | + logger.write_string("Point(\{self.x}, \{self.y})") | |
| 79 | +}''' | |
| 80 | + | |
| 81 | +[[snippet]] | |
| 82 | +name = "loop" | |
| 83 | +group = "MoonBit" | |
| 84 | +languages = ["moonbit"] | |
| 85 | +body = ''' | |
| 86 | +for i = 0, acc = 0 { | |
| 87 | + if i > n { break acc } else { continue i + 1, acc + i } | |
| 88 | +}''' | |
| 89 | + | |
| 90 | +[[snippet]] | |
| 91 | +name = "guard" | |
| 92 | +group = "MoonBit" | |
| 93 | +languages = ["moonbit"] | |
| 94 | +body = ''' | |
| 95 | +guard xs.length() > 0 else { fail("empty") }''' | |
| 96 | + | |
| 97 | +[[snippet]] | |
| 98 | +group = "General" | |
| 99 | +name = "Hello" | |
| 100 | +body = "Hello!!!" | |
| 101 | + | |
| 102 | +[[snippet]] | |
| 103 | +group = "Markdown" | |
| 104 | +name = "Image" | |
| 105 | +languages = ["markdown"] | |
| 106 | +body = "" | |
| new file mode 100644 | |||
| @@ -0,0 +1,106 @@ | |||
| 1 | +# turbo-moonbit 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: bash, dockerfile, html, javascript, markdown, moonbit, toml, | ||
| 10 | +# xml, yaml. Leave it out and the snippet is offered everywhere. | ||
| 11 | +# | ||
| 12 | +# Bodies are indented with two spaces, which is what `moon fmt` writes. Running | ||
| 13 | +# the formatter over a file indented any other way rewrites the whole file, so | ||
| 14 | +# a snippet that disagrees with it turns one insertion into a large diff. | ||
| 15 | +# | ||
| 16 | +# Every MoonBit body below is written in single quotes — '''…''' rather than | ||
| 17 | +# """…""" — because MoonBit interpolates with \{…}, and a backslash before a | ||
| 18 | +# brace is not a valid escape in a TOML basic string. In a literal string a | ||
| 19 | +# backslash is just a backslash, which is exactly what a MoonBit snippet needs. | ||
| 20 | +# | ||
| 21 | +# Your own snippets, shared across every project, go in: | ||
| 22 | +# %s | ||
| 23 | + | ||
| 24 | +[[snippet]] | ||
| 25 | +name = "main" | ||
| 26 | +group = "MoonBit" | ||
| 27 | +languages = ["moonbit"] | ||
| 28 | +body = ''' | ||
| 29 | +fn main { | ||
| 30 | + println("Hello, MoonBit!") | ||
| 31 | +}''' | ||
| 32 | + | ||
| 33 | +[[snippet]] | ||
| 34 | +name = "test" | ||
| 35 | +group = "MoonBit" | ||
| 36 | +languages = ["moonbit"] | ||
| 37 | +body = ''' | ||
| 38 | +test "it works" { | ||
| 39 | + assert_eq(1 + 1, 2) | ||
| 40 | +}''' | ||
| 41 | + | ||
| 42 | +[[snippet]] | ||
| 43 | +name = "struct" | ||
| 44 | +group = "MoonBit" | ||
| 45 | +languages = ["moonbit"] | ||
| 46 | +body = ''' | ||
| 47 | +struct Point { | ||
| 48 | + x : Int | ||
| 49 | + y : Int | ||
| 50 | +} derive(Eq)''' | ||
| 51 | + | ||
| 52 | +[[snippet]] | ||
| 53 | +name = "enum" | ||
| 54 | +group = "MoonBit" | ||
| 55 | +languages = ["moonbit"] | ||
| 56 | +body = ''' | ||
| 57 | +enum Shape { | ||
| 58 | + Circle(Double) | ||
| 59 | + Rect(Double, Double) | ||
| 60 | +} derive(Debug)''' | ||
| 61 | + | ||
| 62 | +[[snippet]] | ||
| 63 | +name = "match" | ||
| 64 | +group = "MoonBit" | ||
| 65 | +languages = ["moonbit"] | ||
| 66 | +body = ''' | ||
| 67 | +match value { | ||
| 68 | + Some(x) => "got \{x}" | ||
| 69 | + None => "nothing" | ||
| 70 | +}''' | ||
| 71 | + | ||
| 72 | +[[snippet]] | ||
| 73 | +name = "trait impl" | ||
| 74 | +group = "MoonBit" | ||
| 75 | +languages = ["moonbit"] | ||
| 76 | +body = ''' | ||
| 77 | +impl Show for Point with fn output(self, logger) { | ||
| 78 | + logger.write_string("Point(\{self.x}, \{self.y})") | ||
| 79 | +}''' | ||
| 80 | + | ||
| 81 | +[[snippet]] | ||
| 82 | +name = "loop" | ||
| 83 | +group = "MoonBit" | ||
| 84 | +languages = ["moonbit"] | ||
| 85 | +body = ''' | ||
| 86 | +for i = 0, acc = 0 { | ||
| 87 | + if i > n { break acc } else { continue i + 1, acc + i } | ||
| 88 | +}''' | ||
| 89 | + | ||
| 90 | +[[snippet]] | ||
| 91 | +name = "guard" | ||
| 92 | +group = "MoonBit" | ||
| 93 | +languages = ["moonbit"] | ||
| 94 | +body = ''' | ||
| 95 | +guard xs.length() > 0 else { fail("empty") }''' | ||
| 96 | + | ||
| 97 | +[[snippet]] | ||
| 98 | +group = "General" | ||
| 99 | +name = "Hello" | ||
| 100 | +body = "Hello!!!" | ||
| 101 | + | ||
| 102 | +[[snippet]] | ||
| 103 | +group = "Markdown" | ||
| 104 | +name = "Image" | ||
| 105 | +languages = ["markdown"] | ||
| 106 | +body = "" | ||
added
internal/moonbitlang/templates.go +72 -0 | new file mode 100644 | ||
| @@ -0,0 +1,72 @@ | ||
| 1 | +package moonbitlang | |
| 2 | + | |
| 3 | +import _ "embed" | |
| 4 | + | |
| 5 | +// The starter files Turbo MoonBit writes into a project's .turbo-moonbit | |
| 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 MoonBit | |
| 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 MoonBit 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 | +// Every MoonBit body in it is a TOML *literal* multi-line string — the form | |
| 42 | +// written with three apostrophes rather than three double quotes. (Spelling | |
| 43 | +// that out in words is deliberate: gofmt rewrites a bare run of apostrophes in | |
| 44 | +// a doc comment into typographic quotes.) MoonBit interpolates with \{…}, and | |
| 45 | +// a backslash before a brace is not one of TOML's escape sequences — so a body | |
| 46 | +// written in basic strings would not parse, and the snippets file the editor | |
| 47 | +// had just offered to create would be refused the moment it was read back. | |
| 48 | +// | |
| 49 | +//go:embed snippets.toml.tmpl | |
| 50 | +var snippetsTemplate string | |
| 51 | + | |
| 52 | +// toolsTemplate is the tools file a project gets when it asks for one. | |
| 53 | +// | |
| 54 | +// Eight commands, and the two features that are invisible otherwise: a | |
| 55 | +// {{placeholder}} that asks for a value before the command runs, and the | |
| 56 | +// `menu` key that puts a tool in a menu of its own. | |
| 57 | +// | |
| 58 | +// `moon check` comes first rather than `moon build`, because it is the command | |
| 59 | +// that answers "is this sound?" without producing anything, and it is what the | |
| 60 | +// MoonBit toolchain itself puts in a project's pre-commit hook. | |
| 61 | +// | |
| 62 | +//go:embed tools.toml.tmpl | |
| 63 | +var toolsTemplate string | |
| 64 | + | |
| 65 | +// agentsTemplate is the agents file a project gets when it asks for one. | |
| 66 | +// | |
| 67 | +// It takes two blanks, in this order: the editor's own project directory — | |
| 68 | +// which the example agent's arguments point into — and the path to the user's | |
| 69 | +// own agents file, which a comment names. | |
| 70 | +// | |
| 71 | +//go:embed acp.toml.tmpl | |
| 72 | +var agentsTemplate string | |
| new file mode 100644 | |||
| @@ -0,0 +1,72 @@ | |||
| 1 | +package moonbitlang | ||
| 2 | + | ||
| 3 | +import _ "embed" | ||
| 4 | + | ||
| 5 | +// The starter files Turbo MoonBit writes into a project's .turbo-moonbit | ||
| 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 MoonBit | ||
| 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 MoonBit 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 | +// Every MoonBit body in it is a TOML *literal* multi-line string — the form | ||
| 42 | +// written with three apostrophes rather than three double quotes. (Spelling | ||
| 43 | +// that out in words is deliberate: gofmt rewrites a bare run of apostrophes in | ||
| 44 | +// a doc comment into typographic quotes.) MoonBit interpolates with \{…}, and | ||
| 45 | +// a backslash before a brace is not one of TOML's escape sequences — so a body | ||
| 46 | +// written in basic strings would not parse, and the snippets file the editor | ||
| 47 | +// had just offered to create would be refused the moment it was read back. | ||
| 48 | +// | ||
| 49 | +//go:embed snippets.toml.tmpl | ||
| 50 | +var snippetsTemplate string | ||
| 51 | + | ||
| 52 | +// toolsTemplate is the tools file a project gets when it asks for one. | ||
| 53 | +// | ||
| 54 | +// Eight commands, and the two features that are invisible otherwise: a | ||
| 55 | +// {{placeholder}} that asks for a value before the command runs, and the | ||
| 56 | +// `menu` key that puts a tool in a menu of its own. | ||
| 57 | +// | ||
| 58 | +// `moon check` comes first rather than `moon build`, because it is the command | ||
| 59 | +// that answers "is this sound?" without producing anything, and it is what the | ||
| 60 | +// MoonBit toolchain itself puts in a project's pre-commit hook. | ||
| 61 | +// | ||
| 62 | +//go:embed tools.toml.tmpl | ||
| 63 | +var toolsTemplate string | ||
| 64 | + | ||
| 65 | +// agentsTemplate is the agents file a project gets when it asks for one. | ||
| 66 | +// | ||
| 67 | +// It takes two blanks, in this order: the editor's own project directory — | ||
| 68 | +// which the example agent's arguments point into — and the path to the user's | ||
| 69 | +// own agents file, which a comment names. | ||
| 70 | +// | ||
| 71 | +//go:embed acp.toml.tmpl | ||
| 72 | +var agentsTemplate string | ||
added
internal/moonbitlang/templates_test.go +437 -0 | new file mode 100644 | ||
| @@ -0,0 +1,437 @@ | ||
| 1 | +package moonbitlang | |
| 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 MoonBit writes are the one part of a project's | |
| 16 | +// .turbo-moonbit directory that is about MoonBit, 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 | +// readFile returns a file's contents. | |
| 62 | +func readFile(t *testing.T, path string) string { | |
| 63 | + t.Helper() | |
| 64 | + | |
| 65 | + data, err := os.ReadFile(path) | |
| 66 | + if err != nil { | |
| 67 | + t.Fatalf("reading %s: %v", path, err) | |
| 68 | + } | |
| 69 | + return string(data) | |
| 70 | +} | |
| 71 | + | |
| 72 | +// --- the formatting contract ------------------------------------------------ | |
| 73 | + | |
| 74 | +// profile.Templates documents how many verbs each template takes, and nothing | |
| 75 | +// enforces it. A template with the wrong number produces %!q(MISSING) or | |
| 76 | +// %!(EXTRA …) in a file that is written into somebody's project, opened, and | |
| 77 | +// wrong — Go writes the marker into the output rather than failing. | |
| 78 | + | |
| 79 | +func TestEachTemplateTakesTheVerbsItsContractSays(t *testing.T) { | |
| 80 | + cases := []struct { | |
| 81 | + name string | |
| 82 | + template string | |
| 83 | + verb string | |
| 84 | + want int | |
| 85 | + }{ | |
| 86 | + {"Settings", settingsTemplate, "%q", 2}, | |
| 87 | + {"Snippets", snippetsTemplate, "%s", 2}, | |
| 88 | + {"Tools", toolsTemplate, "%", 0}, | |
| 89 | + } | |
| 90 | + | |
| 91 | + for _, c := range cases { | |
| 92 | + if got := strings.Count(c.template, c.verb); got != c.want { | |
| 93 | + t.Errorf("%s template has %d %q verbs, want %d", c.name, got, c.verb, c.want) | |
| 94 | + } | |
| 95 | + } | |
| 96 | +} | |
| 97 | + | |
| 98 | +func TestFillingATemplateLeavesNoMissingMarker(t *testing.T) { | |
| 99 | + filled := map[string]string{ | |
| 100 | + "settings": fmt.Sprintf(settingsTemplate, "turbo-classic", "500ms"), | |
| 101 | + "snippets": fmt.Sprintf(snippetsTemplate, "Snippets", "/home/someone/.config/turbo-moonbit/snippets.toml"), | |
| 102 | + "tools": toolsTemplate, | |
| 103 | + } | |
| 104 | + | |
| 105 | + for name, text := range filled { | |
| 106 | + if at := strings.Index(text, "%!"); at >= 0 { | |
| 107 | + t.Errorf("the %s template filled in with %q — the wrong number of verbs", name, text[at:min(at+24, len(text))]) | |
| 108 | + } | |
| 109 | + } | |
| 110 | +} | |
| 111 | + | |
| 112 | +// --- what the files say ----------------------------------------------------- | |
| 113 | + | |
| 114 | +func TestNoTemplateNamesTheEditorThisOneWasAdaptedFrom(t *testing.T) { | |
| 115 | + // A leftover turbo-python in a file written into somebody's MoonBit | |
| 116 | + // project is invisible to every other test here. | |
| 117 | + strangers := []string{"turbo-python", "turbo-rust", "turbo-go", "pythonlang", "rustlang", "golang", "pyproject", "Cargo", "cargo", "pytest", "uv run", "clippy"} | |
| 118 | + | |
| 119 | + for name, template := range map[string]string{ | |
| 120 | + "settings": settingsTemplate, | |
| 121 | + "snippets": snippetsTemplate, | |
| 122 | + "tools": toolsTemplate, | |
| 123 | + } { | |
| 124 | + for _, stranger := range strangers { | |
| 125 | + if strings.Contains(template, stranger) { | |
| 126 | + t.Errorf("the %s template still says %q", name, stranger) | |
| 127 | + } | |
| 128 | + } | |
| 129 | + } | |
| 130 | +} | |
| 131 | + | |
| 132 | +func TestTheSettingsFileTurnsAutosaveOn(t *testing.T) { | |
| 133 | + // A project that has gone to the trouble of creating a settings file has | |
| 134 | + // said what it wants. settings.Default() — what applies with no file at | |
| 135 | + // all — stays off, and that is checked below. | |
| 136 | + dir := createSettings(t) | |
| 137 | + | |
| 138 | + loaded, err := settings.Load(Profile(), dir) | |
| 139 | + if err != nil { | |
| 140 | + t.Fatalf("settings.Load() error = %v", err) | |
| 141 | + } | |
| 142 | + if !loaded.Autosave { | |
| 143 | + t.Error("the starter settings file leaves autosave off, want it on") | |
| 144 | + } | |
| 145 | + if settings.Default().Autosave { | |
| 146 | + t.Error("settings.Default() has autosave on; the two statements have drifted together") | |
| 147 | + } | |
| 148 | +} | |
| 149 | + | |
| 150 | +func TestTheSettingsFileNamesTheThemeItWasCreatedWith(t *testing.T) { | |
| 151 | + dir := createSettings(t) | |
| 152 | + | |
| 153 | + loaded, err := settings.Load(Profile(), dir) | |
| 154 | + if err != nil { | |
| 155 | + t.Fatalf("settings.Load() error = %v", err) | |
| 156 | + } | |
| 157 | + if loaded.Theme != "turbo-classic" { | |
| 158 | + t.Errorf("theme = %q, want %q", loaded.Theme, "turbo-classic") | |
| 159 | + } | |
| 160 | +} | |
| 161 | + | |
| 162 | +func TestTheSnippetsCommentNamesEveryLanguageTheEditorKnows(t *testing.T) { | |
| 163 | + // The comment is where a user finds out what they may write in a | |
| 164 | + // `languages` key. It fell behind the registry once already in this family, | |
| 165 | + // when turbo-core learnt YAML, XML and Dockerfiles — so the list is read | |
| 166 | + // from the registry rather than written down here. | |
| 167 | + Register() | |
| 168 | + | |
| 169 | + list := languageListOf(t, snippetsTemplate) | |
| 170 | + for _, language := range syntax.Registered() { | |
| 171 | + if !strings.Contains(list, language.String()) { | |
| 172 | + t.Errorf("the snippets template's languages comment does not name %q; it reads %q", language, list) | |
| 173 | + } | |
| 174 | + } | |
| 175 | +} | |
| 176 | + | |
| 177 | +// languageListOf returns the one sentence of the snippets template that lists | |
| 178 | +// the language names, with its comment marks stripped. | |
| 179 | +// | |
| 180 | +// Only that sentence will do. Every snippet body below it carries a languages | |
| 181 | +// key naming MoonBit, and the file's own first line names turbo-moonbit — so a | |
| 182 | +// check against the whole template, or even against all of its comments, would | |
| 183 | +// pass with the list itself saying nothing at all. | |
| 184 | +func languageListOf(t *testing.T, template string) string { | |
| 185 | + t.Helper() | |
| 186 | + | |
| 187 | + const marker = "editor uses:" | |
| 188 | + at := strings.Index(template, marker) | |
| 189 | + if at < 0 { | |
| 190 | + t.Fatalf("the snippets template no longer introduces its language list with %q", marker) | |
| 191 | + } | |
| 192 | + | |
| 193 | + rest := template[at+len(marker):] | |
| 194 | + end := strings.Index(rest, ".") | |
| 195 | + if end < 0 { | |
| 196 | + t.Fatal("the snippets template's language list does not end in a full stop") | |
| 197 | + } | |
| 198 | + return strings.ReplaceAll(rest[:end], "#", "") | |
| 199 | +} | |
| 200 | + | |
| 201 | +func TestEverySnippetLoadsAndIsForMoonBit(t *testing.T) { | |
| 202 | + Register() | |
| 203 | + dir := createSnippets(t) | |
| 204 | + | |
| 205 | + list, err := snippets.Load(Profile(), dir) | |
| 206 | + if err != nil { | |
| 207 | + t.Fatalf("snippets.Load() error = %v", err) | |
| 208 | + } | |
| 209 | + if list.Len() == 0 { | |
| 210 | + t.Fatal("the starter snippets file holds none") | |
| 211 | + } | |
| 212 | + | |
| 213 | + groups := list.Groups(Language.String()) | |
| 214 | + var found bool | |
| 215 | + for _, group := range groups { | |
| 216 | + if group.Name == "MoonBit" { | |
| 217 | + found = true | |
| 218 | + } | |
| 219 | + } | |
| 220 | + if !found { | |
| 221 | + t.Errorf("no MoonBit group among %v", groups) | |
| 222 | + } | |
| 223 | +} | |
| 224 | + | |
| 225 | +func TestSnippetBodiesAreIndentedTheWayMoonFmtIndents(t *testing.T) { | |
| 226 | + // `moon fmt` writes two spaces. A snippet that disagrees with the | |
| 227 | + // formatter turns one insertion into a whole-file diff the next time | |
| 228 | + // anybody runs it, and never a tab: MoonBit's formatter does not emit one. | |
| 229 | + Register() | |
| 230 | + dir := createSnippets(t) | |
| 231 | + | |
| 232 | + list, err := snippets.Load(Profile(), dir) | |
| 233 | + if err != nil { | |
| 234 | + t.Fatalf("snippets.Load() error = %v", err) | |
| 235 | + } | |
| 236 | + | |
| 237 | + for _, group := range list.Groups(Language.String()) { | |
| 238 | + for _, snippet := range group.Snippets { | |
| 239 | + for _, line := range strings.Split(snippet.Body, "\n") { | |
| 240 | + if strings.Contains(line, "\t") { | |
| 241 | + t.Errorf("snippet %q has a tab in %q", snippet.Name, line) | |
| 242 | + } | |
| 243 | + indent := len(line) - len(strings.TrimLeft(line, " ")) | |
| 244 | + if indent%2 != 0 { | |
| 245 | + t.Errorf("snippet %q indents %q by %d spaces, want a multiple of two", snippet.Name, line, indent) | |
| 246 | + } | |
| 247 | + } | |
| 248 | + } | |
| 249 | + } | |
| 250 | +} | |
| 251 | + | |
| 252 | +func TestTheSnippetsFileIsTOMLWithLiteralBodies(t *testing.T) { | |
| 253 | + // MoonBit interpolates with \{…}. A backslash before a brace is not one of | |
| 254 | + // TOML's escapes, so a body written in basic strings would not parse — and | |
| 255 | + // the file the editor had just offered to create would be refused the | |
| 256 | + // moment it was read back. That it parses at all is what createSnippets | |
| 257 | + // proves; that it really does hold a backslash is what makes the proof | |
| 258 | + // mean something. | |
| 259 | + Register() | |
| 260 | + dir := createSnippets(t) | |
| 261 | + | |
| 262 | + written := readFile(t, snippets.ProjectPath(Profile(), dir)) | |
| 263 | + if !strings.Contains(written, `\{`) { | |
| 264 | + t.Fatal("no snippet in the starter file interpolates, so nothing here tests the literal-string decision") | |
| 265 | + } | |
| 266 | + for _, line := range strings.Split(written, "\n") { | |
| 267 | + if strings.HasPrefix(line, `body = """`) { | |
| 268 | + t.Errorf("a body is opened with a TOML basic multi-line string: %q", line) | |
| 269 | + } | |
| 270 | + } | |
| 271 | +} | |
| 272 | + | |
| 273 | +func TestEveryToolLoadsAndRunsMoon(t *testing.T) { | |
| 274 | + dir := createTools(t) | |
| 275 | + | |
| 276 | + list, err := tools.Load(Profile(), dir) | |
| 277 | + if err != nil { | |
| 278 | + t.Fatalf("tools.Load() error = %v", err) | |
| 279 | + } | |
| 280 | + if list.Len() == 0 { | |
| 281 | + t.Fatal("the starter tools file holds none") | |
| 282 | + } | |
| 283 | + | |
| 284 | + for _, tool := range list.In("MoonBit") { | |
| 285 | + if !strings.HasPrefix(tool.Command, "moon ") { | |
| 286 | + t.Errorf("tool %q in the MoonBit menu runs %q, which is not a moon command", tool.Name, tool.Command) | |
| 287 | + } | |
| 288 | + } | |
| 289 | +} | |
| 290 | + | |
| 291 | +func TestTheToolsFileShowsBothInvisibleFeatures(t *testing.T) { | |
| 292 | + // A {{placeholder}} and the `menu` key are invisible unless the starter | |
| 293 | + // file demonstrates them, and the starter file is where anyone learns they | |
| 294 | + // exist at all. | |
| 295 | + dir := createTools(t) | |
| 296 | + | |
| 297 | + list, err := tools.Load(Profile(), dir) | |
| 298 | + if err != nil { | |
| 299 | + t.Fatalf("tools.Load() error = %v", err) | |
| 300 | + } | |
| 301 | + | |
| 302 | + var asks, elsewhere int | |
| 303 | + for _, tool := range list.Tools() { | |
| 304 | + if len(tool.Placeholders()) > 0 { | |
| 305 | + asks++ | |
| 306 | + } | |
| 307 | + if tool.Menu != list.DefaultMenu() { | |
| 308 | + elsewhere++ | |
| 309 | + } | |
| 310 | + } | |
| 311 | + if asks == 0 { | |
| 312 | + t.Error("no tool asks for a value, so nothing shows the {{placeholder}} form") | |
| 313 | + } | |
| 314 | + if elsewhere == 0 { | |
| 315 | + t.Error("no tool names a menu of its own, so nothing shows the menu key") | |
| 316 | + } | |
| 317 | +} | |
| 318 | + | |
| 319 | +func TestTheDefaultMenuIsTheMoonBitOne(t *testing.T) { | |
| 320 | + dir := createTools(t) | |
| 321 | + | |
| 322 | + list, err := tools.Load(Profile(), dir) | |
| 323 | + if err != nil { | |
| 324 | + t.Fatalf("tools.Load() error = %v", err) | |
| 325 | + } | |
| 326 | + if got := list.DefaultMenu(); got != "MoonBit" { | |
| 327 | + t.Errorf("DefaultMenu() = %q, want %q", got, "MoonBit") | |
| 328 | + } | |
| 329 | +} | |
| 330 | + | |
| 331 | +func TestNoTwoToolsInOneMenuClaimTheSameHotKey(t *testing.T) { | |
| 332 | + dir := createTools(t) | |
| 333 | + | |
| 334 | + list, err := tools.Load(Profile(), dir) | |
| 335 | + if err != nil { | |
| 336 | + t.Fatalf("tools.Load() error = %v", err) | |
| 337 | + } | |
| 338 | + | |
| 339 | + for _, menu := range list.MenuNames() { | |
| 340 | + taken := map[rune]string{} | |
| 341 | + for _, tool := range list.In(menu) { | |
| 342 | + key, ok := hotKey(tool.Name) | |
| 343 | + if !ok { | |
| 344 | + continue | |
| 345 | + } | |
| 346 | + if other, clash := taken[key]; clash { | |
| 347 | + t.Errorf("in the %s menu, %q and %q both claim %q", menu, other, tool.Name, key) | |
| 348 | + } | |
| 349 | + taken[key] = tool.Name | |
| 350 | + } | |
| 351 | + } | |
| 352 | +} | |
| 353 | + | |
| 354 | +// hotKey returns the upper-case letter a tool's name marks between tildes. | |
| 355 | +func hotKey(name string) (rune, bool) { | |
| 356 | + open := strings.Index(name, "~") | |
| 357 | + if open < 0 || len(name) < open+3 || name[open+2] != '~' { | |
| 358 | + return 0, false | |
| 359 | + } | |
| 360 | + return []rune(strings.ToUpper(name[open+1 : open+2]))[0], true | |
| 361 | +} | |
| 362 | + | |
| 363 | +func TestTheRunToolGetsATerminal(t *testing.T) { | |
| 364 | + // A program that reads the keyboard has to be answerable, and one that runs | |
| 365 | + // long has to be interruptible. A popup is neither. | |
| 366 | + dir := createTools(t) | |
| 367 | + | |
| 368 | + list, err := tools.Load(Profile(), dir) | |
| 369 | + if err != nil { | |
| 370 | + t.Fatalf("tools.Load() error = %v", err) | |
| 371 | + } | |
| 372 | + | |
| 373 | + for _, tool := range list.Tools() { | |
| 374 | + if strings.HasPrefix(tool.Command, "moon run") && tool.Output != tools.OutputTerminal { | |
| 375 | + t.Errorf("the run tool sends its output to %q, want a terminal", tool.Output) | |
| 376 | + } | |
| 377 | + } | |
| 378 | +} | |
| 379 | + | |
| 380 | +func TestEveryPlaceholderAsksForSomething(t *testing.T) { | |
| 381 | + // A half-typed {{ is refused when the file is read, which tools.Load | |
| 382 | + // already proves. This checks the other half: that each label says what it | |
| 383 | + // wants, because the label is the whole of what the box shows. | |
| 384 | + dir := createTools(t) | |
| 385 | + | |
| 386 | + list, err := tools.Load(Profile(), dir) | |
| 387 | + if err != nil { | |
| 388 | + t.Fatalf("tools.Load() error = %v", err) | |
| 389 | + } | |
| 390 | + | |
| 391 | + for _, tool := range list.Tools() { | |
| 392 | + for _, placeholder := range tool.Placeholders() { | |
| 393 | + if strings.TrimSpace(placeholder.Label) == "" { | |
| 394 | + t.Errorf("tool %q has a placeholder with no label", tool.Name) | |
| 395 | + } | |
| 396 | + } | |
| 397 | + } | |
| 398 | +} | |
| 399 | + | |
| 400 | +// The tools reference prints the starter file's table. Turbo Python's shipped | |
| 401 | +// five rows for a file that had six, and claimed `Alt-T` for a menu whose key | |
| 402 | +// is `Alt-P` — both inherited from Turbo Rust by a mechanical substitution that | |
| 403 | +// only looked at identifiers. Nothing in either repository could see it. | |
| 404 | +// | |
| 405 | +// So the table is read out of the page and held to the file the editor | |
| 406 | +// actually writes, in both languages. | |
| 407 | +func TestTheToolsReferenceMatchesTheStarterFile(t *testing.T) { | |
| 408 | + dir := createTools(t) | |
| 409 | + | |
| 410 | + list, err := tools.Load(Profile(), dir) | |
| 411 | + if err != nil { | |
| 412 | + t.Fatalf("tools.Load() error = %v", err) | |
| 413 | + } | |
| 414 | + | |
| 415 | + for _, page := range []string{"../../docs/en/reference/moonbit-tools.md", "../../docs/fr/reference/moonbit-tools.md"} { | |
| 416 | + raw, err := os.ReadFile(page) | |
| 417 | + if err != nil { | |
| 418 | + t.Fatalf("reading %s: %v", page, err) | |
| 419 | + } | |
| 420 | + text := string(raw) | |
| 421 | + | |
| 422 | + for _, tool := range list.Tools() { | |
| 423 | + if !strings.Contains(text, "| `"+tool.Name+"` |") { | |
| 424 | + t.Errorf("%s has no row for the tool %q", page, tool.Name) | |
| 425 | + } | |
| 426 | + if !strings.Contains(text, "`"+tool.Command+"`") { | |
| 427 | + t.Errorf("%s does not print the command %q", page, tool.Command) | |
| 428 | + } | |
| 429 | + } | |
| 430 | + if !strings.Contains(text, "`Alt-M`") { | |
| 431 | + t.Errorf("%s never names Alt-M, the key the MoonBit menu really answers to", page) | |
| 432 | + } | |
| 433 | + if strings.Contains(text, "`Alt-T`, then") || strings.Contains(text, "`Alt-T`, puis") { | |
| 434 | + t.Errorf("%s still opens the toolchain menu with Alt-T, which belongs to Turbo Rust", page) | |
| 435 | + } | |
| 436 | + } | |
| 437 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,437 @@ | |||
| 1 | +package moonbitlang | ||
| 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 MoonBit writes are the one part of a project's | ||
| 16 | +// .turbo-moonbit directory that is about MoonBit, 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 | +// readFile returns a file's contents. | ||
| 62 | +func readFile(t *testing.T, path string) string { | ||
| 63 | + t.Helper() | ||
| 64 | + | ||
| 65 | + data, err := os.ReadFile(path) | ||
| 66 | + if err != nil { | ||
| 67 | + t.Fatalf("reading %s: %v", path, err) | ||
| 68 | + } | ||
| 69 | + return string(data) | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +// --- the formatting contract ------------------------------------------------ | ||
| 73 | + | ||
| 74 | +// profile.Templates documents how many verbs each template takes, and nothing | ||
| 75 | +// enforces it. A template with the wrong number produces %!q(MISSING) or | ||
| 76 | +// %!(EXTRA …) in a file that is written into somebody's project, opened, and | ||
| 77 | +// wrong — Go writes the marker into the output rather than failing. | ||
| 78 | + | ||
| 79 | +func TestEachTemplateTakesTheVerbsItsContractSays(t *testing.T) { | ||
| 80 | + cases := []struct { | ||
| 81 | + name string | ||
| 82 | + template string | ||
| 83 | + verb string | ||
| 84 | + want int | ||
| 85 | + }{ | ||
| 86 | + {"Settings", settingsTemplate, "%q", 2}, | ||
| 87 | + {"Snippets", snippetsTemplate, "%s", 2}, | ||
| 88 | + {"Tools", toolsTemplate, "%", 0}, | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + for _, c := range cases { | ||
| 92 | + if got := strings.Count(c.template, c.verb); got != c.want { | ||
| 93 | + t.Errorf("%s template has %d %q verbs, want %d", c.name, got, c.verb, c.want) | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +func TestFillingATemplateLeavesNoMissingMarker(t *testing.T) { | ||
| 99 | + filled := map[string]string{ | ||
| 100 | + "settings": fmt.Sprintf(settingsTemplate, "turbo-classic", "500ms"), | ||
| 101 | + "snippets": fmt.Sprintf(snippetsTemplate, "Snippets", "/home/someone/.config/turbo-moonbit/snippets.toml"), | ||
| 102 | + "tools": toolsTemplate, | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + for name, text := range filled { | ||
| 106 | + if at := strings.Index(text, "%!"); at >= 0 { | ||
| 107 | + t.Errorf("the %s template filled in with %q — the wrong number of verbs", name, text[at:min(at+24, len(text))]) | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +// --- what the files say ----------------------------------------------------- | ||
| 113 | + | ||
| 114 | +func TestNoTemplateNamesTheEditorThisOneWasAdaptedFrom(t *testing.T) { | ||
| 115 | + // A leftover turbo-python in a file written into somebody's MoonBit | ||
| 116 | + // project is invisible to every other test here. | ||
| 117 | + strangers := []string{"turbo-python", "turbo-rust", "turbo-go", "pythonlang", "rustlang", "golang", "pyproject", "Cargo", "cargo", "pytest", "uv run", "clippy"} | ||
| 118 | + | ||
| 119 | + for name, template := range map[string]string{ | ||
| 120 | + "settings": settingsTemplate, | ||
| 121 | + "snippets": snippetsTemplate, | ||
| 122 | + "tools": toolsTemplate, | ||
| 123 | + } { | ||
| 124 | + for _, stranger := range strangers { | ||
| 125 | + if strings.Contains(template, stranger) { | ||
| 126 | + t.Errorf("the %s template still says %q", name, stranger) | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +func TestTheSettingsFileTurnsAutosaveOn(t *testing.T) { | ||
| 133 | + // A project that has gone to the trouble of creating a settings file has | ||
| 134 | + // said what it wants. settings.Default() — what applies with no file at | ||
| 135 | + // all — stays off, and that is checked below. | ||
| 136 | + dir := createSettings(t) | ||
| 137 | + | ||
| 138 | + loaded, err := settings.Load(Profile(), dir) | ||
| 139 | + if err != nil { | ||
| 140 | + t.Fatalf("settings.Load() error = %v", err) | ||
| 141 | + } | ||
| 142 | + if !loaded.Autosave { | ||
| 143 | + t.Error("the starter settings file leaves autosave off, want it on") | ||
| 144 | + } | ||
| 145 | + if settings.Default().Autosave { | ||
| 146 | + t.Error("settings.Default() has autosave on; the two statements have drifted together") | ||
| 147 | + } | ||
| 148 | +} | ||
| 149 | + | ||
| 150 | +func TestTheSettingsFileNamesTheThemeItWasCreatedWith(t *testing.T) { | ||
| 151 | + dir := createSettings(t) | ||
| 152 | + | ||
| 153 | + loaded, err := settings.Load(Profile(), dir) | ||
| 154 | + if err != nil { | ||
| 155 | + t.Fatalf("settings.Load() error = %v", err) | ||
| 156 | + } | ||
| 157 | + if loaded.Theme != "turbo-classic" { | ||
| 158 | + t.Errorf("theme = %q, want %q", loaded.Theme, "turbo-classic") | ||
| 159 | + } | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +func TestTheSnippetsCommentNamesEveryLanguageTheEditorKnows(t *testing.T) { | ||
| 163 | + // The comment is where a user finds out what they may write in a | ||
| 164 | + // `languages` key. It fell behind the registry once already in this family, | ||
| 165 | + // when turbo-core learnt YAML, XML and Dockerfiles — so the list is read | ||
| 166 | + // from the registry rather than written down here. | ||
| 167 | + Register() | ||
| 168 | + | ||
| 169 | + list := languageListOf(t, snippetsTemplate) | ||
| 170 | + for _, language := range syntax.Registered() { | ||
| 171 | + if !strings.Contains(list, language.String()) { | ||
| 172 | + t.Errorf("the snippets template's languages comment does not name %q; it reads %q", language, list) | ||
| 173 | + } | ||
| 174 | + } | ||
| 175 | +} | ||
| 176 | + | ||
| 177 | +// languageListOf returns the one sentence of the snippets template that lists | ||
| 178 | +// the language names, with its comment marks stripped. | ||
| 179 | +// | ||
| 180 | +// Only that sentence will do. Every snippet body below it carries a languages | ||
| 181 | +// key naming MoonBit, and the file's own first line names turbo-moonbit — so a | ||
| 182 | +// check against the whole template, or even against all of its comments, would | ||
| 183 | +// pass with the list itself saying nothing at all. | ||
| 184 | +func languageListOf(t *testing.T, template string) string { | ||
| 185 | + t.Helper() | ||
| 186 | + | ||
| 187 | + const marker = "editor uses:" | ||
| 188 | + at := strings.Index(template, marker) | ||
| 189 | + if at < 0 { | ||
| 190 | + t.Fatalf("the snippets template no longer introduces its language list with %q", marker) | ||
| 191 | + } | ||
| 192 | + | ||
| 193 | + rest := template[at+len(marker):] | ||
| 194 | + end := strings.Index(rest, ".") | ||
| 195 | + if end < 0 { | ||
| 196 | + t.Fatal("the snippets template's language list does not end in a full stop") | ||
| 197 | + } | ||
| 198 | + return strings.ReplaceAll(rest[:end], "#", "") | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +func TestEverySnippetLoadsAndIsForMoonBit(t *testing.T) { | ||
| 202 | + Register() | ||
| 203 | + dir := createSnippets(t) | ||
| 204 | + | ||
| 205 | + list, err := snippets.Load(Profile(), dir) | ||
| 206 | + if err != nil { | ||
| 207 | + t.Fatalf("snippets.Load() error = %v", err) | ||
| 208 | + } | ||
| 209 | + if list.Len() == 0 { | ||
| 210 | + t.Fatal("the starter snippets file holds none") | ||
| 211 | + } | ||
| 212 | + | ||
| 213 | + groups := list.Groups(Language.String()) | ||
| 214 | + var found bool | ||
| 215 | + for _, group := range groups { | ||
| 216 | + if group.Name == "MoonBit" { | ||
| 217 | + found = true | ||
| 218 | + } | ||
| 219 | + } | ||
| 220 | + if !found { | ||
| 221 | + t.Errorf("no MoonBit group among %v", groups) | ||
| 222 | + } | ||
| 223 | +} | ||
| 224 | + | ||
| 225 | +func TestSnippetBodiesAreIndentedTheWayMoonFmtIndents(t *testing.T) { | ||
| 226 | + // `moon fmt` writes two spaces. A snippet that disagrees with the | ||
| 227 | + // formatter turns one insertion into a whole-file diff the next time | ||
| 228 | + // anybody runs it, and never a tab: MoonBit's formatter does not emit one. | ||
| 229 | + Register() | ||
| 230 | + dir := createSnippets(t) | ||
| 231 | + | ||
| 232 | + list, err := snippets.Load(Profile(), dir) | ||
| 233 | + if err != nil { | ||
| 234 | + t.Fatalf("snippets.Load() error = %v", err) | ||
| 235 | + } | ||
| 236 | + | ||
| 237 | + for _, group := range list.Groups(Language.String()) { | ||
| 238 | + for _, snippet := range group.Snippets { | ||
| 239 | + for _, line := range strings.Split(snippet.Body, "\n") { | ||
| 240 | + if strings.Contains(line, "\t") { | ||
| 241 | + t.Errorf("snippet %q has a tab in %q", snippet.Name, line) | ||
| 242 | + } | ||
| 243 | + indent := len(line) - len(strings.TrimLeft(line, " ")) | ||
| 244 | + if indent%2 != 0 { | ||
| 245 | + t.Errorf("snippet %q indents %q by %d spaces, want a multiple of two", snippet.Name, line, indent) | ||
| 246 | + } | ||
| 247 | + } | ||
| 248 | + } | ||
| 249 | + } | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +func TestTheSnippetsFileIsTOMLWithLiteralBodies(t *testing.T) { | ||
| 253 | + // MoonBit interpolates with \{…}. A backslash before a brace is not one of | ||
| 254 | + // TOML's escapes, so a body written in basic strings would not parse — and | ||
| 255 | + // the file the editor had just offered to create would be refused the | ||
| 256 | + // moment it was read back. That it parses at all is what createSnippets | ||
| 257 | + // proves; that it really does hold a backslash is what makes the proof | ||
| 258 | + // mean something. | ||
| 259 | + Register() | ||
| 260 | + dir := createSnippets(t) | ||
| 261 | + | ||
| 262 | + written := readFile(t, snippets.ProjectPath(Profile(), dir)) | ||
| 263 | + if !strings.Contains(written, `\{`) { | ||
| 264 | + t.Fatal("no snippet in the starter file interpolates, so nothing here tests the literal-string decision") | ||
| 265 | + } | ||
| 266 | + for _, line := range strings.Split(written, "\n") { | ||
| 267 | + if strings.HasPrefix(line, `body = """`) { | ||
| 268 | + t.Errorf("a body is opened with a TOML basic multi-line string: %q", line) | ||
| 269 | + } | ||
| 270 | + } | ||
| 271 | +} | ||
| 272 | + | ||
| 273 | +func TestEveryToolLoadsAndRunsMoon(t *testing.T) { | ||
| 274 | + dir := createTools(t) | ||
| 275 | + | ||
| 276 | + list, err := tools.Load(Profile(), dir) | ||
| 277 | + if err != nil { | ||
| 278 | + t.Fatalf("tools.Load() error = %v", err) | ||
| 279 | + } | ||
| 280 | + if list.Len() == 0 { | ||
| 281 | + t.Fatal("the starter tools file holds none") | ||
| 282 | + } | ||
| 283 | + | ||
| 284 | + for _, tool := range list.In("MoonBit") { | ||
| 285 | + if !strings.HasPrefix(tool.Command, "moon ") { | ||
| 286 | + t.Errorf("tool %q in the MoonBit menu runs %q, which is not a moon command", tool.Name, tool.Command) | ||
| 287 | + } | ||
| 288 | + } | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +func TestTheToolsFileShowsBothInvisibleFeatures(t *testing.T) { | ||
| 292 | + // A {{placeholder}} and the `menu` key are invisible unless the starter | ||
| 293 | + // file demonstrates them, and the starter file is where anyone learns they | ||
| 294 | + // exist at all. | ||
| 295 | + dir := createTools(t) | ||
| 296 | + | ||
| 297 | + list, err := tools.Load(Profile(), dir) | ||
| 298 | + if err != nil { | ||
| 299 | + t.Fatalf("tools.Load() error = %v", err) | ||
| 300 | + } | ||
| 301 | + | ||
| 302 | + var asks, elsewhere int | ||
| 303 | + for _, tool := range list.Tools() { | ||
| 304 | + if len(tool.Placeholders()) > 0 { | ||
| 305 | + asks++ | ||
| 306 | + } | ||
| 307 | + if tool.Menu != list.DefaultMenu() { | ||
| 308 | + elsewhere++ | ||
| 309 | + } | ||
| 310 | + } | ||
| 311 | + if asks == 0 { | ||
| 312 | + t.Error("no tool asks for a value, so nothing shows the {{placeholder}} form") | ||
| 313 | + } | ||
| 314 | + if elsewhere == 0 { | ||
| 315 | + t.Error("no tool names a menu of its own, so nothing shows the menu key") | ||
| 316 | + } | ||
| 317 | +} | ||
| 318 | + | ||
| 319 | +func TestTheDefaultMenuIsTheMoonBitOne(t *testing.T) { | ||
| 320 | + dir := createTools(t) | ||
| 321 | + | ||
| 322 | + list, err := tools.Load(Profile(), dir) | ||
| 323 | + if err != nil { | ||
| 324 | + t.Fatalf("tools.Load() error = %v", err) | ||
| 325 | + } | ||
| 326 | + if got := list.DefaultMenu(); got != "MoonBit" { | ||
| 327 | + t.Errorf("DefaultMenu() = %q, want %q", got, "MoonBit") | ||
| 328 | + } | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +func TestNoTwoToolsInOneMenuClaimTheSameHotKey(t *testing.T) { | ||
| 332 | + dir := createTools(t) | ||
| 333 | + | ||
| 334 | + list, err := tools.Load(Profile(), dir) | ||
| 335 | + if err != nil { | ||
| 336 | + t.Fatalf("tools.Load() error = %v", err) | ||
| 337 | + } | ||
| 338 | + | ||
| 339 | + for _, menu := range list.MenuNames() { | ||
| 340 | + taken := map[rune]string{} | ||
| 341 | + for _, tool := range list.In(menu) { | ||
| 342 | + key, ok := hotKey(tool.Name) | ||
| 343 | + if !ok { | ||
| 344 | + continue | ||
| 345 | + } | ||
| 346 | + if other, clash := taken[key]; clash { | ||
| 347 | + t.Errorf("in the %s menu, %q and %q both claim %q", menu, other, tool.Name, key) | ||
| 348 | + } | ||
| 349 | + taken[key] = tool.Name | ||
| 350 | + } | ||
| 351 | + } | ||
| 352 | +} | ||
| 353 | + | ||
| 354 | +// hotKey returns the upper-case letter a tool's name marks between tildes. | ||
| 355 | +func hotKey(name string) (rune, bool) { | ||
| 356 | + open := strings.Index(name, "~") | ||
| 357 | + if open < 0 || len(name) < open+3 || name[open+2] != '~' { | ||
| 358 | + return 0, false | ||
| 359 | + } | ||
| 360 | + return []rune(strings.ToUpper(name[open+1 : open+2]))[0], true | ||
| 361 | +} | ||
| 362 | + | ||
| 363 | +func TestTheRunToolGetsATerminal(t *testing.T) { | ||
| 364 | + // A program that reads the keyboard has to be answerable, and one that runs | ||
| 365 | + // long has to be interruptible. A popup is neither. | ||
| 366 | + dir := createTools(t) | ||
| 367 | + | ||
| 368 | + list, err := tools.Load(Profile(), dir) | ||
| 369 | + if err != nil { | ||
| 370 | + t.Fatalf("tools.Load() error = %v", err) | ||
| 371 | + } | ||
| 372 | + | ||
| 373 | + for _, tool := range list.Tools() { | ||
| 374 | + if strings.HasPrefix(tool.Command, "moon run") && tool.Output != tools.OutputTerminal { | ||
| 375 | + t.Errorf("the run tool sends its output to %q, want a terminal", tool.Output) | ||
| 376 | + } | ||
| 377 | + } | ||
| 378 | +} | ||
| 379 | + | ||
| 380 | +func TestEveryPlaceholderAsksForSomething(t *testing.T) { | ||
| 381 | + // A half-typed {{ is refused when the file is read, which tools.Load | ||
| 382 | + // already proves. This checks the other half: that each label says what it | ||
| 383 | + // wants, because the label is the whole of what the box shows. | ||
| 384 | + dir := createTools(t) | ||
| 385 | + | ||
| 386 | + list, err := tools.Load(Profile(), dir) | ||
| 387 | + if err != nil { | ||
| 388 | + t.Fatalf("tools.Load() error = %v", err) | ||
| 389 | + } | ||
| 390 | + | ||
| 391 | + for _, tool := range list.Tools() { | ||
| 392 | + for _, placeholder := range tool.Placeholders() { | ||
| 393 | + if strings.TrimSpace(placeholder.Label) == "" { | ||
| 394 | + t.Errorf("tool %q has a placeholder with no label", tool.Name) | ||
| 395 | + } | ||
| 396 | + } | ||
| 397 | + } | ||
| 398 | +} | ||
| 399 | + | ||
| 400 | +// The tools reference prints the starter file's table. Turbo Python's shipped | ||
| 401 | +// five rows for a file that had six, and claimed `Alt-T` for a menu whose key | ||
| 402 | +// is `Alt-P` — both inherited from Turbo Rust by a mechanical substitution that | ||
| 403 | +// only looked at identifiers. Nothing in either repository could see it. | ||
| 404 | +// | ||
| 405 | +// So the table is read out of the page and held to the file the editor | ||
| 406 | +// actually writes, in both languages. | ||
| 407 | +func TestTheToolsReferenceMatchesTheStarterFile(t *testing.T) { | ||
| 408 | + dir := createTools(t) | ||
| 409 | + | ||
| 410 | + list, err := tools.Load(Profile(), dir) | ||
| 411 | + if err != nil { | ||
| 412 | + t.Fatalf("tools.Load() error = %v", err) | ||
| 413 | + } | ||
| 414 | + | ||
| 415 | + for _, page := range []string{"../../docs/en/reference/moonbit-tools.md", "../../docs/fr/reference/moonbit-tools.md"} { | ||
| 416 | + raw, err := os.ReadFile(page) | ||
| 417 | + if err != nil { | ||
| 418 | + t.Fatalf("reading %s: %v", page, err) | ||
| 419 | + } | ||
| 420 | + text := string(raw) | ||
| 421 | + | ||
| 422 | + for _, tool := range list.Tools() { | ||
| 423 | + if !strings.Contains(text, "| `"+tool.Name+"` |") { | ||
| 424 | + t.Errorf("%s has no row for the tool %q", page, tool.Name) | ||
| 425 | + } | ||
| 426 | + if !strings.Contains(text, "`"+tool.Command+"`") { | ||
| 427 | + t.Errorf("%s does not print the command %q", page, tool.Command) | ||
| 428 | + } | ||
| 429 | + } | ||
| 430 | + if !strings.Contains(text, "`Alt-M`") { | ||
| 431 | + t.Errorf("%s never names Alt-M, the key the MoonBit menu really answers to", page) | ||
| 432 | + } | ||
| 433 | + if strings.Contains(text, "`Alt-T`, then") || strings.Contains(text, "`Alt-T`, puis") { | ||
| 434 | + t.Errorf("%s still opens the toolchain menu with Alt-T, which belongs to Turbo Rust", page) | ||
| 435 | + } | ||
| 436 | + } | ||
| 437 | +} | ||
added
internal/moonbitlang/tools.toml.tmpl +104 -0 | new file mode 100644 | ||
| @@ -0,0 +1,104 @@ | ||
| 1 | +# turbo-moonbit tools. | |
| 2 | +# | |
| 3 | +# Each [[tool]] becomes one line of the MoonBit 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 | +# MoonBit menu; name anything else and that menu is created for you, in the | |
| 12 | +# order the names first appear here. A tool that has nothing to do with MoonBit | |
| 13 | +# belongs 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 = "moon add {{module}}" | |
| 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 = "moon test {{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. moon itself looks upwards | |
| 45 | +# for moon.mod, so most of these also work from a package inside the project. | |
| 46 | + | |
| 47 | +[[tool]] | |
| 48 | +name = "~C~heck" | |
| 49 | +# The fastest thing that tells you whether the project is sound: it type-checks | |
| 50 | +# without emitting object files, which is why it comes first rather than build. | |
| 51 | +command = "moon check" | |
| 52 | +output = "popup" | |
| 53 | + | |
| 54 | +[[tool]] | |
| 55 | +name = "~F~ormat" | |
| 56 | +command = "moon fmt" | |
| 57 | +output = "popup" | |
| 58 | + | |
| 59 | +[[tool]] | |
| 60 | +name = "~B~uild" | |
| 61 | +# MoonBit compiles to several backends, and which one a project wants is not | |
| 62 | +# something a starter file can know. The value is asked for rather than fixed: | |
| 63 | +# wasm, wasm-gc, js, native, llvm, or all. | |
| 64 | +command = "moon build --target {{backend: wasm-gc, js, native, llvm or all...}}" | |
| 65 | +output = "popup" | |
| 66 | + | |
| 67 | +[[tool]] | |
| 68 | +name = "~T~est" | |
| 69 | +command = "moon test" | |
| 70 | +output = "popup" | |
| 71 | + | |
| 72 | +[[tool]] | |
| 73 | +name = "~R~un" | |
| 74 | +command = "moon run {{package, e.g. cmd/main}}" | |
| 75 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | |
| 76 | +# be answered, and one that runs long has to be able to be interrupted. | |
| 77 | +output = "terminal" | |
| 78 | + | |
| 79 | +[[tool]] | |
| 80 | +name = "~A~dd a dependency" | |
| 81 | +command = "moon add {{module, e.g. moonbitlang/x}}" | |
| 82 | +output = "popup" | |
| 83 | + | |
| 84 | +[[tool]] | |
| 85 | +name = "~I~nterfaces" | |
| 86 | +# Regenerates the .mbti files that record each package's public surface. Worth | |
| 87 | +# a menu entry because a diff in one is how a review sees that an API changed. | |
| 88 | +command = "moon info" | |
| 89 | +output = "popup" | |
| 90 | + | |
| 91 | +[[tool]] | |
| 92 | +name = "C~l~ean" | |
| 93 | +command = "moon clean" | |
| 94 | +output = "popup" | |
| 95 | + | |
| 96 | +# A tool naming a `menu` gets a menu of its own on the bar. Nothing above does, | |
| 97 | +# so every tool above is in the MoonBit menu. This one is in a menu called | |
| 98 | +# Tools, which appears between MoonBit and Help — that is the whole mechanism. | |
| 99 | + | |
| 100 | +[[tool]] | |
| 101 | +name = "~E~cho" | |
| 102 | +command = "echo 🎉 tada!" | |
| 103 | +menu = "Tools" | |
| 104 | +output = "terminal" | |
| new file mode 100644 | |||
| @@ -0,0 +1,104 @@ | |||
| 1 | +# turbo-moonbit tools. | ||
| 2 | +# | ||
| 3 | +# Each [[tool]] becomes one line of the MoonBit 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 | +# MoonBit menu; name anything else and that menu is created for you, in the | ||
| 12 | +# order the names first appear here. A tool that has nothing to do with MoonBit | ||
| 13 | +# belongs 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 = "moon add {{module}}" | ||
| 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 = "moon test {{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. moon itself looks upwards | ||
| 45 | +# for moon.mod, so most of these also work from a package inside the project. | ||
| 46 | + | ||
| 47 | +[[tool]] | ||
| 48 | +name = "~C~heck" | ||
| 49 | +# The fastest thing that tells you whether the project is sound: it type-checks | ||
| 50 | +# without emitting object files, which is why it comes first rather than build. | ||
| 51 | +command = "moon check" | ||
| 52 | +output = "popup" | ||
| 53 | + | ||
| 54 | +[[tool]] | ||
| 55 | +name = "~F~ormat" | ||
| 56 | +command = "moon fmt" | ||
| 57 | +output = "popup" | ||
| 58 | + | ||
| 59 | +[[tool]] | ||
| 60 | +name = "~B~uild" | ||
| 61 | +# MoonBit compiles to several backends, and which one a project wants is not | ||
| 62 | +# something a starter file can know. The value is asked for rather than fixed: | ||
| 63 | +# wasm, wasm-gc, js, native, llvm, or all. | ||
| 64 | +command = "moon build --target {{backend: wasm-gc, js, native, llvm or all...}}" | ||
| 65 | +output = "popup" | ||
| 66 | + | ||
| 67 | +[[tool]] | ||
| 68 | +name = "~T~est" | ||
| 69 | +command = "moon test" | ||
| 70 | +output = "popup" | ||
| 71 | + | ||
| 72 | +[[tool]] | ||
| 73 | +name = "~R~un" | ||
| 74 | +command = "moon run {{package, e.g. cmd/main}}" | ||
| 75 | +# A terminal, not a popup: a program that reads the keyboard has to be able to | ||
| 76 | +# be answered, and one that runs long has to be able to be interrupted. | ||
| 77 | +output = "terminal" | ||
| 78 | + | ||
| 79 | +[[tool]] | ||
| 80 | +name = "~A~dd a dependency" | ||
| 81 | +command = "moon add {{module, e.g. moonbitlang/x}}" | ||
| 82 | +output = "popup" | ||
| 83 | + | ||
| 84 | +[[tool]] | ||
| 85 | +name = "~I~nterfaces" | ||
| 86 | +# Regenerates the .mbti files that record each package's public surface. Worth | ||
| 87 | +# a menu entry because a diff in one is how a review sees that an API changed. | ||
| 88 | +command = "moon info" | ||
| 89 | +output = "popup" | ||
| 90 | + | ||
| 91 | +[[tool]] | ||
| 92 | +name = "C~l~ean" | ||
| 93 | +command = "moon clean" | ||
| 94 | +output = "popup" | ||
| 95 | + | ||
| 96 | +# A tool naming a `menu` gets a menu of its own on the bar. Nothing above does, | ||
| 97 | +# so every tool above is in the MoonBit menu. This one is in a menu called | ||
| 98 | +# Tools, which appears between MoonBit and Help — that is the whole mechanism. | ||
| 99 | + | ||
| 100 | +[[tool]] | ||
| 101 | +name = "~E~cho" | ||
| 102 | +command = "echo 🎉 tada!" | ||
| 103 | +menu = "Tools" | ||
| 104 | +output = "terminal" | ||
added
internal/moonbitlang/words.go +355 -0 | new file mode 100644 | ||
| @@ -0,0 +1,355 @@ | ||
| 1 | +package moonbitlang | |
| 2 | + | |
| 3 | +// Numbers and words: what a run of digits or letters turns out to be. | |
| 4 | + | |
| 5 | +import ( | |
| 6 | + "strings" | |
| 7 | + | |
| 8 | + "rickub.com/turbo-editors/turbo-core/syntax" | |
| 9 | +) | |
| 10 | + | |
| 11 | +// --- numbers ---------------------------------------------------------------- | |
| 12 | + | |
| 13 | +// numberSuffixes are the literal suffixes MoonBit recognises, longest first so | |
| 14 | +// that UL is matched before U. | |
| 15 | +// | |
| 16 | +// They are upper case and nothing else: the grammar spells out "Uppercase | |
| 17 | +// suffixes select UInt (U), Int64 (L), UInt64 (UL), BigInt (N), or Float (F)", | |
| 18 | +// so 123u is the number 123 followed by the identifier u, and colouring it | |
| 19 | +// otherwise would be inventing a literal the compiler will reject. | |
| 20 | +var numberSuffixes = []string{"UL", "U", "L", "N", "F"} | |
| 21 | + | |
| 22 | +// takeNumber colours a numeric literal: 1_000, 0xFF, 0o17, 0b1010, 1.5e-3, | |
| 23 | +// 0x1.8p3F, 42UL. | |
| 24 | +// | |
| 25 | +// It follows the grammar rather than being generous, because one case needs it | |
| 26 | +// to. "Before .., an integer ends first, so 1..=2 begins with 1 and ..=" — a | |
| 27 | +// scanner that swallowed any dot would read 1. as a double and leave .=2 | |
| 28 | +// behind, and a range would be miscoloured everywhere it appeared. | |
| 29 | +// | |
| 30 | +// The whole literal is one span, so every step here advances the scanner | |
| 31 | +// without colouring and the single Emit at the end covers what they consumed. | |
| 32 | +func takeNumber(s *syntax.LineScanner) { | |
| 33 | + start := s.Pos() | |
| 34 | + digit, hexadecimal := takeIntegerPart(s) | |
| 35 | + | |
| 36 | + // A floating-point literal always has a point, and the point is only part | |
| 37 | + // of the number when a second one does not follow it. | |
| 38 | + if s.Peek(0) == '.' && s.Peek(1) != '.' { | |
| 39 | + s.Advance(1) | |
| 40 | + advanceWhile(s, digit) | |
| 41 | + } | |
| 42 | + | |
| 43 | + takeExponent(s, hexadecimal) | |
| 44 | + takeNumberSuffix(s) | |
| 45 | + s.Emit(start, s.Pos(), syntax.ClassNumber) | |
| 46 | +} | |
| 47 | + | |
| 48 | +// takeIntegerPart consumes the digits before any point. It returns the | |
| 49 | +// predicate saying which runes count as digits for the rest of the literal, and | |
| 50 | +// whether the literal is hexadecimal. | |
| 51 | +// | |
| 52 | +// The base prefix decides both. After 0x every hexadecimal digit is a digit, | |
| 53 | +// which is what makes the F of 0x1.F part of the number rather than a Float | |
| 54 | +// suffix — and an exponent is introduced by p rather than by e, because e is | |
| 55 | +// itself a hexadecimal digit. | |
| 56 | +func takeIntegerPart(s *syntax.LineScanner) (digit func(rune) bool, hexadecimal bool) { | |
| 57 | + if s.Peek(0) == '0' { | |
| 58 | + switch s.Peek(1) { | |
| 59 | + case 'x', 'X': | |
| 60 | + return takeBase(s, isHexDigit), true | |
| 61 | + case 'o', 'O': | |
| 62 | + return takeBase(s, isOctalDigit), false | |
| 63 | + case 'b', 'B': | |
| 64 | + return takeBase(s, isBinaryDigit), false | |
| 65 | + } | |
| 66 | + } | |
| 67 | + | |
| 68 | + advanceWhile(s, isDecimalDigit) | |
| 69 | + return isDecimalDigit, false | |
| 70 | +} | |
| 71 | + | |
| 72 | +// takeBase consumes a base prefix and the digits after it, and hands back the | |
| 73 | +// predicate that recognised them. | |
| 74 | +func takeBase(s *syntax.LineScanner, digit func(rune) bool) func(rune) bool { | |
| 75 | + s.Advance(2) // the 0 and its base letter | |
| 76 | + advanceWhile(s, digit) | |
| 77 | + return digit | |
| 78 | +} | |
| 79 | + | |
| 80 | +// takeExponent consumes an exponent when one is there: e or E for a decimal | |
| 81 | +// literal, p or P for a hexadecimal one, each with an optional sign. | |
| 82 | +// | |
| 83 | +// The sign is only taken when a digit follows it, so 1e-x stops at the e and | |
| 84 | +// leaves the - and the x to be coloured as an operator and a name. | |
| 85 | +func takeExponent(s *syntax.LineScanner, hexadecimal bool) { | |
| 86 | + if !isExponentLetter(s.Peek(0), hexadecimal) { | |
| 87 | + return | |
| 88 | + } | |
| 89 | + | |
| 90 | + offset := 1 | |
| 91 | + if s.Peek(offset) == '+' || s.Peek(offset) == '-' { | |
| 92 | + offset++ | |
| 93 | + } | |
| 94 | + if !syntax.IsDigit(s.Peek(offset)) { | |
| 95 | + return | |
| 96 | + } | |
| 97 | + | |
| 98 | + s.Advance(offset) | |
| 99 | + advanceWhile(s, isDecimalDigit) | |
| 100 | +} | |
| 101 | + | |
| 102 | +// takeNumberSuffix consumes UL, U, L, N or F when the literal ends in one. | |
| 103 | +// | |
| 104 | +// A suffix must not be followed by another word rune: 1Length is not the Int64 | |
| 105 | +// 1 followed by ength, it is a number and then a name the compiler will | |
| 106 | +// complain about, and stopping short of it is the reading that says so. | |
| 107 | +func takeNumberSuffix(s *syntax.LineScanner) { | |
| 108 | + for _, suffix := range numberSuffixes { | |
| 109 | + if s.HasPrefix(0, suffix) && !syntax.IsWordRune(s.Peek(len(suffix))) { | |
| 110 | + s.Advance(len(suffix)) | |
| 111 | + return | |
| 112 | + } | |
| 113 | + } | |
| 114 | +} | |
| 115 | + | |
| 116 | +// advanceWhile steps over runes that match, without colouring any of them. It | |
| 117 | +// is what a construct emitted as a single span uses in place of TakeWhile, | |
| 118 | +// which would colour each run it consumed and leave the Emit overlapping it. | |
| 119 | +func advanceWhile(s *syntax.LineScanner, matches func(rune) bool) { | |
| 120 | + for !s.AtEnd() && matches(s.Peek(0)) { | |
| 121 | + s.Advance(1) | |
| 122 | + } | |
| 123 | +} | |
| 124 | + | |
| 125 | +// isExponentLetter reports whether a rune introduces an exponent, which depends | |
| 126 | +// on the base: a hexadecimal literal uses p, because e is one of its digits. | |
| 127 | +func isExponentLetter(r rune, hexadecimal bool) bool { | |
| 128 | + if hexadecimal { | |
| 129 | + return r == 'p' || r == 'P' | |
| 130 | + } | |
| 131 | + return r == 'e' || r == 'E' | |
| 132 | +} | |
| 133 | + | |
| 134 | +// isDecimalDigit reports whether a rune may appear in a decimal literal after | |
| 135 | +// its first digit. An underscore may, and "underscores may repeat or trail". | |
| 136 | +func isDecimalDigit(r rune) bool { return syntax.IsDigit(r) || r == '_' } | |
| 137 | + | |
| 138 | +// isHexDigit reports whether a rune may appear in a hexadecimal literal. | |
| 139 | +func isHexDigit(r rune) bool { | |
| 140 | + return isDecimalDigit(r) || | |
| 141 | + r >= 'a' && r <= 'f' || | |
| 142 | + r >= 'A' && r <= 'F' | |
| 143 | +} | |
| 144 | + | |
| 145 | +// isOctalDigit reports whether a rune may appear in an octal literal. | |
| 146 | +func isOctalDigit(r rune) bool { return r >= '0' && r <= '7' || r == '_' } | |
| 147 | + | |
| 148 | +// isBinaryDigit reports whether a rune may appear in a binary literal. | |
| 149 | +func isBinaryDigit(r rune) bool { return r == '0' || r == '1' || r == '_' } | |
| 150 | + | |
| 151 | +// --- words ------------------------------------------------------------------ | |
| 152 | + | |
| 153 | +// bangKeywords are the two keywords that end in an exclamation mark. | |
| 154 | +// | |
| 155 | +// The grammar lists try! and guard! among the keywords, and ! is an operator | |
| 156 | +// rune — so without this the mark would be coloured as an operator hanging off | |
| 157 | +// the end of a keyword, which is not what the language sees there. | |
| 158 | +var bangKeywords = map[string]bool{"try": true, "guard": true} | |
| 159 | + | |
| 160 | +// takeWord colours an identifier, deciding what kind of thing it is from the | |
| 161 | +// word itself and from the rune that follows it. | |
| 162 | +func takeWord(s *syntax.LineScanner) { | |
| 163 | + start := s.Pos() | |
| 164 | + advanceWhile(s, syntax.IsWordRune) | |
| 165 | + word := wordAt(s, start) | |
| 166 | + | |
| 167 | + if bangKeywords[word] && s.Peek(0) == '!' { | |
| 168 | + s.Advance(1) | |
| 169 | + s.Emit(start, s.Pos(), syntax.ClassKeyword) | |
| 170 | + return | |
| 171 | + } | |
| 172 | + if isLabel(s, word) { | |
| 173 | + s.Advance(1) // the ~ | |
| 174 | + s.Emit(start, s.Pos(), syntax.ClassAttribute) | |
| 175 | + return | |
| 176 | + } | |
| 177 | + | |
| 178 | + s.Emit(start, s.Pos(), classOfWord(word, s.Peek(0))) | |
| 179 | +} | |
| 180 | + | |
| 181 | +// takeMember colours the name after a dot: a field, or a method. | |
| 182 | +// | |
| 183 | +// It is takeWord without the keyword table, because MoonBit's dot-identifiers | |
| 184 | +// "use the identifier case rules without consulting the keyword table, so .if | |
| 185 | +// is valid". A record with a field called `type` is ordinary MoonBit, and | |
| 186 | +// colouring that field as a keyword would be a claim about the language that | |
| 187 | +// the language contradicts. | |
| 188 | +func takeMember(s *syntax.LineScanner) { | |
| 189 | + start := s.Pos() | |
| 190 | + advanceWhile(s, syntax.IsWordRune) | |
| 191 | + s.Emit(start, s.Pos(), classOfMember(wordAt(s, start), s.Peek(0))) | |
| 192 | +} | |
| 193 | + | |
| 194 | +// wordAt returns the word running from start to the scanner's position. | |
| 195 | +func wordAt(s *syntax.LineScanner, start int) string { | |
| 196 | + var b strings.Builder | |
| 197 | + for at := start; at < s.Pos(); at++ { | |
| 198 | + b.WriteRune(s.Peek(at - s.Pos())) | |
| 199 | + } | |
| 200 | + return b.String() | |
| 201 | +} | |
| 202 | + | |
| 203 | +// isLabel reports whether the word just consumed is a labelled argument's name, | |
| 204 | +// which is to say whether a tilde touches it. | |
| 205 | +// | |
| 206 | +// The tilde is MoonBit's alone: it appears in no operator the language has, so | |
| 207 | +// a tilde against the end of a name can only be a label. The two exclusions are | |
| 208 | +// the grammar's own — "ASCII-uppercase identifiers and keywords cannot form | |
| 209 | +// labels" — and they matter, because without the first, Foo~ in a piece of | |
| 210 | +// half-typed code would colour a type as a label. | |
| 211 | +func isLabel(s *syntax.LineScanner, word string) bool { | |
| 212 | + if s.Peek(0) != '~' || word == "" { | |
| 213 | + return false | |
| 214 | + } | |
| 215 | + if startsUpperCase(word) { | |
| 216 | + return false | |
| 217 | + } | |
| 218 | + _, reserved := knownWords[word] | |
| 219 | + return !reserved | |
| 220 | +} | |
| 221 | + | |
| 222 | +// classOfWord decides what a word is, given the rune that follows it. | |
| 223 | +// | |
| 224 | +// The order is the design, and MoonBit lets it be shorter than any other | |
| 225 | +// scanner in this family. A word the language names is what the language says | |
| 226 | +// it is. After that comes the case rule — and in MoonBit that is a *lexical* | |
| 227 | +// rule rather than a convention: a uident "begins with an ASCII uppercase | |
| 228 | +// letter", and only a type, a trait or an enum constructor may be spelt that | |
| 229 | +// way. So there is no table of built-in types here, and there does not need to | |
| 230 | +// be: Int, StringBuilder and a type somebody wrote this morning are all | |
| 231 | +// capitalised, and all coloured by the same line. | |
| 232 | +// | |
| 233 | +// What that costs is that a constructor of your own enum is coloured as a type. | |
| 234 | +// Nothing in the syntax separates Circle(1.0) from a type applied to arguments, | |
| 235 | +// and inventing a separation would mean being wrong in both directions instead | |
| 236 | +// of one. | |
| 237 | +func classOfWord(word string, next rune) syntax.Class { | |
| 238 | + if class, known := knownWords[word]; known { | |
| 239 | + return class | |
| 240 | + } | |
| 241 | + if startsUpperCase(word) { | |
| 242 | + return syntax.ClassType | |
| 243 | + } | |
| 244 | + if next == '(' { | |
| 245 | + return syntax.ClassFunction | |
| 246 | + } | |
| 247 | + return syntax.ClassIdentifier | |
| 248 | +} | |
| 249 | + | |
| 250 | +// classOfMember decides what the name after a dot is. It is classOfWord with | |
| 251 | +// the keyword table left out; see takeMember. | |
| 252 | +func classOfMember(word string, next rune) syntax.Class { | |
| 253 | + if startsUpperCase(word) { | |
| 254 | + return syntax.ClassType | |
| 255 | + } | |
| 256 | + if next == '(' { | |
| 257 | + return syntax.ClassFunction | |
| 258 | + } | |
| 259 | + return syntax.ClassIdentifier | |
| 260 | +} | |
| 261 | + | |
| 262 | +// startsUpperCase reports whether a word begins with an ASCII capital, which is | |
| 263 | +// what makes it a uident. | |
| 264 | +func startsUpperCase(word string) bool { | |
| 265 | + return word != "" && word[0] >= 'A' && word[0] <= 'Z' | |
| 266 | +} | |
| 267 | + | |
| 268 | +// knownWords is every word the language itself names, and what each one is. | |
| 269 | +// | |
| 270 | +// It is one table rather than three because it answers one question. The three | |
| 271 | +// groups below are kept apart only so that each can carry the reasoning that | |
| 272 | +// belongs to it. | |
| 273 | +var knownWords = merge( | |
| 274 | + classify(syntax.ClassKeyword, keywords), | |
| 275 | + classify(syntax.ClassConstant, constants), | |
| 276 | + classify(syntax.ClassBuiltin, builtinValues), | |
| 277 | +) | |
| 278 | + | |
| 279 | +// keywords are the words MoonBit reserves, taken from the grammar's keyword | |
| 280 | +// production. | |
| 281 | +// | |
| 282 | +// true and false are in it there and are not here: they are keywords to the | |
| 283 | +// lexer and values to the reader, and every editor in this family colours them | |
| 284 | +// as constants. try! and guard! are not here either — the mark is glued on by | |
| 285 | +// takeWord, because a table cannot hold a word whose last rune is an operator. | |
| 286 | +// | |
| 287 | +// package is here although in a .mbt file it is only a *reserved* word, which | |
| 288 | +// the lexer treats as an identifier and warns about. It is a real keyword in | |
| 289 | +// the .mbti interface files this editor also colours, and in a .mbt file | |
| 290 | +// colouring it says exactly what the compiler is about to: this word is not | |
| 291 | +// yours to use. | |
| 292 | +// | |
| 293 | +// The rest of the reserved list — move, ref, static, unsafe, await, and the | |
| 294 | +// forty others — is deliberately absent. Those are identifiers that earn a | |
| 295 | +// warning, and a scanner that coloured them as keywords would be telling a | |
| 296 | +// reader they cannot write `let ref = 1` when they can. | |
| 297 | +var keywords = words( | |
| 298 | + "and", "as", "async", "break", "catch", "const", "continue", "declare", | |
| 299 | + "defer", "derive", "else", "enum", "enumview", "extend", "extenum", | |
| 300 | + "extern", "fn", "for", "guard", "if", "impl", "import", "in", "is", "let", | |
| 301 | + "letrec", "lexscan", "loop", "match", "mut", "nobreak", "nocancel", | |
| 302 | + "noraise", "package", "priv", "proof_assert", "proof_let", "pub", "raise", | |
| 303 | + "readonly", "return", "struct", "suberror", "test", "throw", "trait", | |
| 304 | + "try", "type", "using", "where", "while", "with", | |
| 305 | +) | |
| 306 | + | |
| 307 | +// constants are the values a reader meets as the language's own. | |
| 308 | +// | |
| 309 | +// None, Some, Ok and Err belong to Option and Result rather than to the | |
| 310 | +// language, but a reader meets them everywhere and reads them as built in, the | |
| 311 | +// same argument Turbo Rust records for the same four names. | |
| 312 | +var constants = words("true", "false", "None", "Some", "Ok", "Err") | |
| 313 | + | |
| 314 | +// builtinValues are the lower-case names the prelude puts in scope without an | |
| 315 | +// import, read out of moonbitlang/core/prelude rather than remembered. | |
| 316 | +// | |
| 317 | +// The prelude's deprecated names — dump, not, tap, then, to_repr — are left | |
| 318 | +// out on purpose: colouring them as builtins would present as the language's | |
| 319 | +// own four things it is trying to retire. There is no print here for the same | |
| 320 | +// kind of reason, and it is the one worth stating: MoonBit has println and has | |
| 321 | +// never had print, so a table written from habit would have coloured a name | |
| 322 | +// that does not exist. | |
| 323 | +var builtinValues = words( | |
| 324 | + "abort", "assert_eq", "assert_false", "assert_not_eq", "assert_true", | |
| 325 | + "compare", "debug", "debug_assert", "debug_inspect", "fail", "hash", | |
| 326 | + "ignore", "inspect", "json_inspect", "null", "panic", "physical_equal", | |
| 327 | + "println", "repr", | |
| 328 | +) | |
| 329 | + | |
| 330 | +// words gathers a group of them, which reads better at the call sites above | |
| 331 | +// than a slice literal does. | |
| 332 | +func words(list ...string) []string { return list } | |
| 333 | + | |
| 334 | +// classify pairs every word in a group with the class it belongs to. | |
| 335 | +func classify(class syntax.Class, list []string) map[string]syntax.Class { | |
| 336 | + out := make(map[string]syntax.Class, len(list)) | |
| 337 | + for _, word := range list { | |
| 338 | + out[word] = class | |
| 339 | + } | |
| 340 | + return out | |
| 341 | +} | |
| 342 | + | |
| 343 | +// merge folds the groups into one table. An earlier group wins a word a later | |
| 344 | +// one repeats, which is what keeps a keyword a keyword. | |
| 345 | +func merge(groups ...map[string]syntax.Class) map[string]syntax.Class { | |
| 346 | + out := map[string]syntax.Class{} | |
| 347 | + for _, group := range groups { | |
| 348 | + for word, class := range group { | |
| 349 | + if _, taken := out[word]; !taken { | |
| 350 | + out[word] = class | |
| 351 | + } | |
| 352 | + } | |
| 353 | + } | |
| 354 | + return out | |
| 355 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,355 @@ | |||
| 1 | +package moonbitlang | ||
| 2 | + | ||
| 3 | +// Numbers and words: what a run of digits or letters turns out to be. | ||
| 4 | + | ||
| 5 | +import ( | ||
| 6 | + "strings" | ||
| 7 | + | ||
| 8 | + "rickub.com/turbo-editors/turbo-core/syntax" | ||
| 9 | +) | ||
| 10 | + | ||
| 11 | +// --- numbers ---------------------------------------------------------------- | ||
| 12 | + | ||
| 13 | +// numberSuffixes are the literal suffixes MoonBit recognises, longest first so | ||
| 14 | +// that UL is matched before U. | ||
| 15 | +// | ||
| 16 | +// They are upper case and nothing else: the grammar spells out "Uppercase | ||
| 17 | +// suffixes select UInt (U), Int64 (L), UInt64 (UL), BigInt (N), or Float (F)", | ||
| 18 | +// so 123u is the number 123 followed by the identifier u, and colouring it | ||
| 19 | +// otherwise would be inventing a literal the compiler will reject. | ||
| 20 | +var numberSuffixes = []string{"UL", "U", "L", "N", "F"} | ||
| 21 | + | ||
| 22 | +// takeNumber colours a numeric literal: 1_000, 0xFF, 0o17, 0b1010, 1.5e-3, | ||
| 23 | +// 0x1.8p3F, 42UL. | ||
| 24 | +// | ||
| 25 | +// It follows the grammar rather than being generous, because one case needs it | ||
| 26 | +// to. "Before .., an integer ends first, so 1..=2 begins with 1 and ..=" — a | ||
| 27 | +// scanner that swallowed any dot would read 1. as a double and leave .=2 | ||
| 28 | +// behind, and a range would be miscoloured everywhere it appeared. | ||
| 29 | +// | ||
| 30 | +// The whole literal is one span, so every step here advances the scanner | ||
| 31 | +// without colouring and the single Emit at the end covers what they consumed. | ||
| 32 | +func takeNumber(s *syntax.LineScanner) { | ||
| 33 | + start := s.Pos() | ||
| 34 | + digit, hexadecimal := takeIntegerPart(s) | ||
| 35 | + | ||
| 36 | + // A floating-point literal always has a point, and the point is only part | ||
| 37 | + // of the number when a second one does not follow it. | ||
| 38 | + if s.Peek(0) == '.' && s.Peek(1) != '.' { | ||
| 39 | + s.Advance(1) | ||
| 40 | + advanceWhile(s, digit) | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + takeExponent(s, hexadecimal) | ||
| 44 | + takeNumberSuffix(s) | ||
| 45 | + s.Emit(start, s.Pos(), syntax.ClassNumber) | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +// takeIntegerPart consumes the digits before any point. It returns the | ||
| 49 | +// predicate saying which runes count as digits for the rest of the literal, and | ||
| 50 | +// whether the literal is hexadecimal. | ||
| 51 | +// | ||
| 52 | +// The base prefix decides both. After 0x every hexadecimal digit is a digit, | ||
| 53 | +// which is what makes the F of 0x1.F part of the number rather than a Float | ||
| 54 | +// suffix — and an exponent is introduced by p rather than by e, because e is | ||
| 55 | +// itself a hexadecimal digit. | ||
| 56 | +func takeIntegerPart(s *syntax.LineScanner) (digit func(rune) bool, hexadecimal bool) { | ||
| 57 | + if s.Peek(0) == '0' { | ||
| 58 | + switch s.Peek(1) { | ||
| 59 | + case 'x', 'X': | ||
| 60 | + return takeBase(s, isHexDigit), true | ||
| 61 | + case 'o', 'O': | ||
| 62 | + return takeBase(s, isOctalDigit), false | ||
| 63 | + case 'b', 'B': | ||
| 64 | + return takeBase(s, isBinaryDigit), false | ||
| 65 | + } | ||
| 66 | + } | ||
| 67 | + | ||
| 68 | + advanceWhile(s, isDecimalDigit) | ||
| 69 | + return isDecimalDigit, false | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +// takeBase consumes a base prefix and the digits after it, and hands back the | ||
| 73 | +// predicate that recognised them. | ||
| 74 | +func takeBase(s *syntax.LineScanner, digit func(rune) bool) func(rune) bool { | ||
| 75 | + s.Advance(2) // the 0 and its base letter | ||
| 76 | + advanceWhile(s, digit) | ||
| 77 | + return digit | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +// takeExponent consumes an exponent when one is there: e or E for a decimal | ||
| 81 | +// literal, p or P for a hexadecimal one, each with an optional sign. | ||
| 82 | +// | ||
| 83 | +// The sign is only taken when a digit follows it, so 1e-x stops at the e and | ||
| 84 | +// leaves the - and the x to be coloured as an operator and a name. | ||
| 85 | +func takeExponent(s *syntax.LineScanner, hexadecimal bool) { | ||
| 86 | + if !isExponentLetter(s.Peek(0), hexadecimal) { | ||
| 87 | + return | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + offset := 1 | ||
| 91 | + if s.Peek(offset) == '+' || s.Peek(offset) == '-' { | ||
| 92 | + offset++ | ||
| 93 | + } | ||
| 94 | + if !syntax.IsDigit(s.Peek(offset)) { | ||
| 95 | + return | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + s.Advance(offset) | ||
| 99 | + advanceWhile(s, isDecimalDigit) | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +// takeNumberSuffix consumes UL, U, L, N or F when the literal ends in one. | ||
| 103 | +// | ||
| 104 | +// A suffix must not be followed by another word rune: 1Length is not the Int64 | ||
| 105 | +// 1 followed by ength, it is a number and then a name the compiler will | ||
| 106 | +// complain about, and stopping short of it is the reading that says so. | ||
| 107 | +func takeNumberSuffix(s *syntax.LineScanner) { | ||
| 108 | + for _, suffix := range numberSuffixes { | ||
| 109 | + if s.HasPrefix(0, suffix) && !syntax.IsWordRune(s.Peek(len(suffix))) { | ||
| 110 | + s.Advance(len(suffix)) | ||
| 111 | + return | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +// advanceWhile steps over runes that match, without colouring any of them. It | ||
| 117 | +// is what a construct emitted as a single span uses in place of TakeWhile, | ||
| 118 | +// which would colour each run it consumed and leave the Emit overlapping it. | ||
| 119 | +func advanceWhile(s *syntax.LineScanner, matches func(rune) bool) { | ||
| 120 | + for !s.AtEnd() && matches(s.Peek(0)) { | ||
| 121 | + s.Advance(1) | ||
| 122 | + } | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +// isExponentLetter reports whether a rune introduces an exponent, which depends | ||
| 126 | +// on the base: a hexadecimal literal uses p, because e is one of its digits. | ||
| 127 | +func isExponentLetter(r rune, hexadecimal bool) bool { | ||
| 128 | + if hexadecimal { | ||
| 129 | + return r == 'p' || r == 'P' | ||
| 130 | + } | ||
| 131 | + return r == 'e' || r == 'E' | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +// isDecimalDigit reports whether a rune may appear in a decimal literal after | ||
| 135 | +// its first digit. An underscore may, and "underscores may repeat or trail". | ||
| 136 | +func isDecimalDigit(r rune) bool { return syntax.IsDigit(r) || r == '_' } | ||
| 137 | + | ||
| 138 | +// isHexDigit reports whether a rune may appear in a hexadecimal literal. | ||
| 139 | +func isHexDigit(r rune) bool { | ||
| 140 | + return isDecimalDigit(r) || | ||
| 141 | + r >= 'a' && r <= 'f' || | ||
| 142 | + r >= 'A' && r <= 'F' | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +// isOctalDigit reports whether a rune may appear in an octal literal. | ||
| 146 | +func isOctalDigit(r rune) bool { return r >= '0' && r <= '7' || r == '_' } | ||
| 147 | + | ||
| 148 | +// isBinaryDigit reports whether a rune may appear in a binary literal. | ||
| 149 | +func isBinaryDigit(r rune) bool { return r == '0' || r == '1' || r == '_' } | ||
| 150 | + | ||
| 151 | +// --- words ------------------------------------------------------------------ | ||
| 152 | + | ||
| 153 | +// bangKeywords are the two keywords that end in an exclamation mark. | ||
| 154 | +// | ||
| 155 | +// The grammar lists try! and guard! among the keywords, and ! is an operator | ||
| 156 | +// rune — so without this the mark would be coloured as an operator hanging off | ||
| 157 | +// the end of a keyword, which is not what the language sees there. | ||
| 158 | +var bangKeywords = map[string]bool{"try": true, "guard": true} | ||
| 159 | + | ||
| 160 | +// takeWord colours an identifier, deciding what kind of thing it is from the | ||
| 161 | +// word itself and from the rune that follows it. | ||
| 162 | +func takeWord(s *syntax.LineScanner) { | ||
| 163 | + start := s.Pos() | ||
| 164 | + advanceWhile(s, syntax.IsWordRune) | ||
| 165 | + word := wordAt(s, start) | ||
| 166 | + | ||
| 167 | + if bangKeywords[word] && s.Peek(0) == '!' { | ||
| 168 | + s.Advance(1) | ||
| 169 | + s.Emit(start, s.Pos(), syntax.ClassKeyword) | ||
| 170 | + return | ||
| 171 | + } | ||
| 172 | + if isLabel(s, word) { | ||
| 173 | + s.Advance(1) // the ~ | ||
| 174 | + s.Emit(start, s.Pos(), syntax.ClassAttribute) | ||
| 175 | + return | ||
| 176 | + } | ||
| 177 | + | ||
| 178 | + s.Emit(start, s.Pos(), classOfWord(word, s.Peek(0))) | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +// takeMember colours the name after a dot: a field, or a method. | ||
| 182 | +// | ||
| 183 | +// It is takeWord without the keyword table, because MoonBit's dot-identifiers | ||
| 184 | +// "use the identifier case rules without consulting the keyword table, so .if | ||
| 185 | +// is valid". A record with a field called `type` is ordinary MoonBit, and | ||
| 186 | +// colouring that field as a keyword would be a claim about the language that | ||
| 187 | +// the language contradicts. | ||
| 188 | +func takeMember(s *syntax.LineScanner) { | ||
| 189 | + start := s.Pos() | ||
| 190 | + advanceWhile(s, syntax.IsWordRune) | ||
| 191 | + s.Emit(start, s.Pos(), classOfMember(wordAt(s, start), s.Peek(0))) | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +// wordAt returns the word running from start to the scanner's position. | ||
| 195 | +func wordAt(s *syntax.LineScanner, start int) string { | ||
| 196 | + var b strings.Builder | ||
| 197 | + for at := start; at < s.Pos(); at++ { | ||
| 198 | + b.WriteRune(s.Peek(at - s.Pos())) | ||
| 199 | + } | ||
| 200 | + return b.String() | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +// isLabel reports whether the word just consumed is a labelled argument's name, | ||
| 204 | +// which is to say whether a tilde touches it. | ||
| 205 | +// | ||
| 206 | +// The tilde is MoonBit's alone: it appears in no operator the language has, so | ||
| 207 | +// a tilde against the end of a name can only be a label. The two exclusions are | ||
| 208 | +// the grammar's own — "ASCII-uppercase identifiers and keywords cannot form | ||
| 209 | +// labels" — and they matter, because without the first, Foo~ in a piece of | ||
| 210 | +// half-typed code would colour a type as a label. | ||
| 211 | +func isLabel(s *syntax.LineScanner, word string) bool { | ||
| 212 | + if s.Peek(0) != '~' || word == "" { | ||
| 213 | + return false | ||
| 214 | + } | ||
| 215 | + if startsUpperCase(word) { | ||
| 216 | + return false | ||
| 217 | + } | ||
| 218 | + _, reserved := knownWords[word] | ||
| 219 | + return !reserved | ||
| 220 | +} | ||
| 221 | + | ||
| 222 | +// classOfWord decides what a word is, given the rune that follows it. | ||
| 223 | +// | ||
| 224 | +// The order is the design, and MoonBit lets it be shorter than any other | ||
| 225 | +// scanner in this family. A word the language names is what the language says | ||
| 226 | +// it is. After that comes the case rule — and in MoonBit that is a *lexical* | ||
| 227 | +// rule rather than a convention: a uident "begins with an ASCII uppercase | ||
| 228 | +// letter", and only a type, a trait or an enum constructor may be spelt that | ||
| 229 | +// way. So there is no table of built-in types here, and there does not need to | ||
| 230 | +// be: Int, StringBuilder and a type somebody wrote this morning are all | ||
| 231 | +// capitalised, and all coloured by the same line. | ||
| 232 | +// | ||
| 233 | +// What that costs is that a constructor of your own enum is coloured as a type. | ||
| 234 | +// Nothing in the syntax separates Circle(1.0) from a type applied to arguments, | ||
| 235 | +// and inventing a separation would mean being wrong in both directions instead | ||
| 236 | +// of one. | ||
| 237 | +func classOfWord(word string, next rune) syntax.Class { | ||
| 238 | + if class, known := knownWords[word]; known { | ||
| 239 | + return class | ||
| 240 | + } | ||
| 241 | + if startsUpperCase(word) { | ||
| 242 | + return syntax.ClassType | ||
| 243 | + } | ||
| 244 | + if next == '(' { | ||
| 245 | + return syntax.ClassFunction | ||
| 246 | + } | ||
| 247 | + return syntax.ClassIdentifier | ||
| 248 | +} | ||
| 249 | + | ||
| 250 | +// classOfMember decides what the name after a dot is. It is classOfWord with | ||
| 251 | +// the keyword table left out; see takeMember. | ||
| 252 | +func classOfMember(word string, next rune) syntax.Class { | ||
| 253 | + if startsUpperCase(word) { | ||
| 254 | + return syntax.ClassType | ||
| 255 | + } | ||
| 256 | + if next == '(' { | ||
| 257 | + return syntax.ClassFunction | ||
| 258 | + } | ||
| 259 | + return syntax.ClassIdentifier | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +// startsUpperCase reports whether a word begins with an ASCII capital, which is | ||
| 263 | +// what makes it a uident. | ||
| 264 | +func startsUpperCase(word string) bool { | ||
| 265 | + return word != "" && word[0] >= 'A' && word[0] <= 'Z' | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +// knownWords is every word the language itself names, and what each one is. | ||
| 269 | +// | ||
| 270 | +// It is one table rather than three because it answers one question. The three | ||
| 271 | +// groups below are kept apart only so that each can carry the reasoning that | ||
| 272 | +// belongs to it. | ||
| 273 | +var knownWords = merge( | ||
| 274 | + classify(syntax.ClassKeyword, keywords), | ||
| 275 | + classify(syntax.ClassConstant, constants), | ||
| 276 | + classify(syntax.ClassBuiltin, builtinValues), | ||
| 277 | +) | ||
| 278 | + | ||
| 279 | +// keywords are the words MoonBit reserves, taken from the grammar's keyword | ||
| 280 | +// production. | ||
| 281 | +// | ||
| 282 | +// true and false are in it there and are not here: they are keywords to the | ||
| 283 | +// lexer and values to the reader, and every editor in this family colours them | ||
| 284 | +// as constants. try! and guard! are not here either — the mark is glued on by | ||
| 285 | +// takeWord, because a table cannot hold a word whose last rune is an operator. | ||
| 286 | +// | ||
| 287 | +// package is here although in a .mbt file it is only a *reserved* word, which | ||
| 288 | +// the lexer treats as an identifier and warns about. It is a real keyword in | ||
| 289 | +// the .mbti interface files this editor also colours, and in a .mbt file | ||
| 290 | +// colouring it says exactly what the compiler is about to: this word is not | ||
| 291 | +// yours to use. | ||
| 292 | +// | ||
| 293 | +// The rest of the reserved list — move, ref, static, unsafe, await, and the | ||
| 294 | +// forty others — is deliberately absent. Those are identifiers that earn a | ||
| 295 | +// warning, and a scanner that coloured them as keywords would be telling a | ||
| 296 | +// reader they cannot write `let ref = 1` when they can. | ||
| 297 | +var keywords = words( | ||
| 298 | + "and", "as", "async", "break", "catch", "const", "continue", "declare", | ||
| 299 | + "defer", "derive", "else", "enum", "enumview", "extend", "extenum", | ||
| 300 | + "extern", "fn", "for", "guard", "if", "impl", "import", "in", "is", "let", | ||
| 301 | + "letrec", "lexscan", "loop", "match", "mut", "nobreak", "nocancel", | ||
| 302 | + "noraise", "package", "priv", "proof_assert", "proof_let", "pub", "raise", | ||
| 303 | + "readonly", "return", "struct", "suberror", "test", "throw", "trait", | ||
| 304 | + "try", "type", "using", "where", "while", "with", | ||
| 305 | +) | ||
| 306 | + | ||
| 307 | +// constants are the values a reader meets as the language's own. | ||
| 308 | +// | ||
| 309 | +// None, Some, Ok and Err belong to Option and Result rather than to the | ||
| 310 | +// language, but a reader meets them everywhere and reads them as built in, the | ||
| 311 | +// same argument Turbo Rust records for the same four names. | ||
| 312 | +var constants = words("true", "false", "None", "Some", "Ok", "Err") | ||
| 313 | + | ||
| 314 | +// builtinValues are the lower-case names the prelude puts in scope without an | ||
| 315 | +// import, read out of moonbitlang/core/prelude rather than remembered. | ||
| 316 | +// | ||
| 317 | +// The prelude's deprecated names — dump, not, tap, then, to_repr — are left | ||
| 318 | +// out on purpose: colouring them as builtins would present as the language's | ||
| 319 | +// own four things it is trying to retire. There is no print here for the same | ||
| 320 | +// kind of reason, and it is the one worth stating: MoonBit has println and has | ||
| 321 | +// never had print, so a table written from habit would have coloured a name | ||
| 322 | +// that does not exist. | ||
| 323 | +var builtinValues = words( | ||
| 324 | + "abort", "assert_eq", "assert_false", "assert_not_eq", "assert_true", | ||
| 325 | + "compare", "debug", "debug_assert", "debug_inspect", "fail", "hash", | ||
| 326 | + "ignore", "inspect", "json_inspect", "null", "panic", "physical_equal", | ||
| 327 | + "println", "repr", | ||
| 328 | +) | ||
| 329 | + | ||
| 330 | +// words gathers a group of them, which reads better at the call sites above | ||
| 331 | +// than a slice literal does. | ||
| 332 | +func words(list ...string) []string { return list } | ||
| 333 | + | ||
| 334 | +// classify pairs every word in a group with the class it belongs to. | ||
| 335 | +func classify(class syntax.Class, list []string) map[string]syntax.Class { | ||
| 336 | + out := make(map[string]syntax.Class, len(list)) | ||
| 337 | + for _, word := range list { | ||
| 338 | + out[word] = class | ||
| 339 | + } | ||
| 340 | + return out | ||
| 341 | +} | ||
| 342 | + | ||
| 343 | +// merge folds the groups into one table. An earlier group wins a word a later | ||
| 344 | +// one repeats, which is what keeps a keyword a keyword. | ||
| 345 | +func merge(groups ...map[string]syntax.Class) map[string]syntax.Class { | ||
| 346 | + out := map[string]syntax.Class{} | ||
| 347 | + for _, group := range groups { | ||
| 348 | + for word, class := range group { | ||
| 349 | + if _, taken := out[word]; !taken { | ||
| 350 | + out[word] = class | ||
| 351 | + } | ||
| 352 | + } | ||
| 353 | + } | ||
| 354 | + return out | ||
| 355 | +} | ||
added
main.go +204 -0 | new file mode 100644 | ||
| @@ -0,0 +1,204 @@ | ||
| 1 | +// Command turbo-moonbit is a Turbo C-style editor for MoonBit: a full-screen | |
| 2 | +// terminal IDE with menus, movable windows, syntax colouring and completion | |
| 3 | +// from moon-lsp. | |
| 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/moonbitlang — | |
| 7 | +// the profile that says this one is for MoonBit. | |
| 8 | +// | |
| 9 | +// Usage: | |
| 10 | +// | |
| 11 | +// turbo-moonbit [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-moonbit/internal/moonbitlang" | |
| 37 | +) | |
| 38 | + | |
| 39 | +func main() { | |
| 40 | + if err := run(); err != nil { | |
| 41 | + fmt.Fprintf(os.Stderr, "%s: %v\n", moonbitlang.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 MoonBit" a line somebody can read. | |
| 77 | + moonbitlang.Register() | |
| 78 | + p := moonbitlang.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-moonbit/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", moonbitlang.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-moonbit is a Turbo C-style editor for MoonBit: a full-screen | ||
| 2 | +// terminal IDE with menus, movable windows, syntax colouring and completion | ||
| 3 | +// from moon-lsp. | ||
| 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/moonbitlang — | ||
| 7 | +// the profile that says this one is for MoonBit. | ||
| 8 | +// | ||
| 9 | +// Usage: | ||
| 10 | +// | ||
| 11 | +// turbo-moonbit [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-moonbit/internal/moonbitlang" | ||
| 37 | +) | ||
| 38 | + | ||
| 39 | +func main() { | ||
| 40 | + if err := run(); err != nil { | ||
| 41 | + fmt.Fprintf(os.Stderr, "%s: %v\n", moonbitlang.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 MoonBit" a line somebody can read. | ||
| 77 | + moonbitlang.Register() | ||
| 78 | + p := moonbitlang.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-moonbit/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", moonbitlang.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 +157 -0 | new file mode 100644 | ||
| @@ -0,0 +1,157 @@ | ||
| 1 | +package main | |
| 2 | + | |
| 3 | +import ( | |
| 4 | + "flag" | |
| 5 | + "os" | |
| 6 | + "path/filepath" | |
| 7 | + "slices" | |
| 8 | + "testing" | |
| 9 | + | |
| 10 | + "rickub.com/turbo-editors/turbo-core/app" | |
| 11 | + "rickub.com/turbo-editors/turbo-core/settings" | |
| 12 | + | |
| 13 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | |
| 14 | +) | |
| 15 | + | |
| 16 | +// withArgs runs the command line parser against a fixed argument list, and | |
| 17 | +// restores the real one afterwards so tests do not affect each other. | |
| 18 | +func withArgs(t *testing.T, args ...string) options { | |
| 19 | + t.Helper() | |
| 20 | + | |
| 21 | + realArgs, realFlags := os.Args, flag.CommandLine | |
| 22 | + t.Cleanup(func() { os.Args, flag.CommandLine = realArgs, realFlags }) | |
| 23 | + | |
| 24 | + os.Args = append([]string{"turbo-moonbit"}, args...) | |
| 25 | + flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError) | |
| 26 | + return parseFlags() | |
| 27 | +} | |
| 28 | + | |
| 29 | +func TestFilesAreWhatIsLeftAfterTheFlags(t *testing.T) { | |
| 30 | + opts := withArgs(t, "-no-lsp", "main.mbt", "lib/x.mbt") | |
| 31 | + | |
| 32 | + if !opts.noLSP { | |
| 33 | + t.Error("-no-lsp was not read") | |
| 34 | + } | |
| 35 | + if want := []string{"main.mbt", "lib/x.mbt"}; !slices.Equal(opts.files, want) { | |
| 36 | + t.Errorf("files = %v, want %v", opts.files, want) | |
| 37 | + } | |
| 38 | +} | |
| 39 | + | |
| 40 | +func TestTheThemeFlagDefaultsToEmptyRatherThanToAName(t *testing.T) { | |
| 41 | + // Empty is what lets "was -theme given?" still be answered afterwards, and | |
| 42 | + // that is what lets the project's settings fill it in without overriding an | |
| 43 | + // explicit choice. | |
| 44 | + if opts := withArgs(t); opts.theme != "" { | |
| 45 | + t.Errorf("theme = %q with no flag, want the empty string", opts.theme) | |
| 46 | + } | |
| 47 | +} | |
| 48 | + | |
| 49 | +func TestTheThemeFlagBeatsTheProjectSettings(t *testing.T) { | |
| 50 | + project := settings.Default() | |
| 51 | + project.Theme = "cobalt" | |
| 52 | + | |
| 53 | + if got := themeName(options{theme: "monochrome"}, project); got != "monochrome" { | |
| 54 | + t.Errorf("themeName() = %q, want the flag's %q", got, "monochrome") | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 58 | +func TestTheProjectSettingsBeatTheBuiltInDefault(t *testing.T) { | |
| 59 | + project := settings.Default() | |
| 60 | + project.Theme = "cobalt" | |
| 61 | + | |
| 62 | + if got := themeName(options{}, project); got != "cobalt" { | |
| 63 | + t.Errorf("themeName() = %q, want the project's %q", got, "cobalt") | |
| 64 | + } | |
| 65 | +} | |
| 66 | + | |
| 67 | +func TestTheBuiltInDefaultIsUsedWhenNobodySaysOtherwise(t *testing.T) { | |
| 68 | + if got := themeName(options{}, settings.Default()); got == "" { | |
| 69 | + t.Error("themeName() = \"\" with nothing set, want the library's default") | |
| 70 | + } | |
| 71 | +} | |
| 72 | + | |
| 73 | +func TestTheProjectRootIsTheNearestMoonModule(t *testing.T) { | |
| 74 | + // app.ProjectRoot walks up looking for the profile's RootMarkers. This is | |
| 75 | + // what decides the directory moon-lsp is started in, and starting it | |
| 76 | + // anywhere else is how a server answers nothing for a whole session. | |
| 77 | + root := t.TempDir() | |
| 78 | + nested := filepath.Join(root, "cmd", "main") | |
| 79 | + if err := os.MkdirAll(nested, 0o755); err != nil { | |
| 80 | + t.Fatal(err) | |
| 81 | + } | |
| 82 | + if err := os.WriteFile(filepath.Join(root, "moon.mod"), []byte(`name = "u/m"`), 0o644); err != nil { | |
| 83 | + t.Fatal(err) | |
| 84 | + } | |
| 85 | + | |
| 86 | + file := filepath.Join(nested, "main.mbt") | |
| 87 | + if got := app.ProjectRoot(moonbitlang.Profile(), []string{file}); got != root { | |
| 88 | + t.Errorf("ProjectRoot(%q) = %q, want %q", file, got, root) | |
| 89 | + } | |
| 90 | +} | |
| 91 | + | |
| 92 | +func TestTheLegacyJSONModuleFileIsAlsoARoot(t *testing.T) { | |
| 93 | + root := t.TempDir() | |
| 94 | + if err := os.WriteFile(filepath.Join(root, "moon.mod.json"), []byte(`{"name":"u/m"}`), 0o644); err != nil { | |
| 95 | + t.Fatal(err) | |
| 96 | + } | |
| 97 | + | |
| 98 | + file := filepath.Join(root, "main.mbt") | |
| 99 | + if got := app.ProjectRoot(moonbitlang.Profile(), []string{file}); got != root { | |
| 100 | + t.Errorf("ProjectRoot(%q) = %q, want %q", file, got, root) | |
| 101 | + } | |
| 102 | +} | |
| 103 | + | |
| 104 | +func TestTheNearestModuleWinsOverTheOneAboveIt(t *testing.T) { | |
| 105 | + // A workspace holds several modules. The server belongs to the one the | |
| 106 | + // file is in, not to the outermost directory that happens to have a | |
| 107 | + // manifest. | |
| 108 | + outer := t.TempDir() | |
| 109 | + inner := filepath.Join(outer, "member") | |
| 110 | + if err := os.MkdirAll(inner, 0o755); err != nil { | |
| 111 | + t.Fatal(err) | |
| 112 | + } | |
| 113 | + for _, dir := range []string{outer, inner} { | |
| 114 | + if err := os.WriteFile(filepath.Join(dir, "moon.mod"), []byte(`name = "u/m"`), 0o644); err != nil { | |
| 115 | + t.Fatal(err) | |
| 116 | + } | |
| 117 | + } | |
| 118 | + | |
| 119 | + file := filepath.Join(inner, "lib.mbt") | |
| 120 | + if got := app.ProjectRoot(moonbitlang.Profile(), []string{file}); got != inner { | |
| 121 | + t.Errorf("ProjectRoot(%q) = %q, want the nearer %q", file, got, inner) | |
| 122 | + } | |
| 123 | +} | |
| 124 | + | |
| 125 | +func TestLoadingSettingsFromADirectoryWithNoneGivesTheDefaults(t *testing.T) { | |
| 126 | + // A directory somebody merely started the editor in has said nothing, and | |
| 127 | + // the editor must not write to it. The starter file turns autosave on; the | |
| 128 | + // default leaves it off. | |
| 129 | + dir := t.TempDir() | |
| 130 | + t.Chdir(dir) | |
| 131 | + | |
| 132 | + project, loaded := loadProjectSettings(moonbitlang.Profile()) | |
| 133 | + if project == "" { | |
| 134 | + t.Error("loadProjectSettings returned no project directory") | |
| 135 | + } | |
| 136 | + if loaded.Autosave { | |
| 137 | + t.Error("autosave is on with no settings file, want it off") | |
| 138 | + } | |
| 139 | +} | |
| 140 | + | |
| 141 | +func TestABrokenSettingsFileDoesNotStopTheEditorOpening(t *testing.T) { | |
| 142 | + // A broken settings file must not stop the editor opening, because the | |
| 143 | + // editor is how you would fix it. | |
| 144 | + dir := t.TempDir() | |
| 145 | + p := moonbitlang.Profile() | |
| 146 | + if err := os.MkdirAll(filepath.Join(dir, p.ProjectDir()), 0o755); err != nil { | |
| 147 | + t.Fatal(err) | |
| 148 | + } | |
| 149 | + if err := os.WriteFile(settings.Path(p, dir), []byte("this is not ["), 0o644); err != nil { | |
| 150 | + t.Fatal(err) | |
| 151 | + } | |
| 152 | + t.Chdir(dir) | |
| 153 | + | |
| 154 | + if _, loaded := loadProjectSettings(p); loaded != settings.Default() { | |
| 155 | + t.Errorf("loadProjectSettings() = %+v with a broken file, want the defaults", loaded) | |
| 156 | + } | |
| 157 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,157 @@ | |||
| 1 | +package main | ||
| 2 | + | ||
| 3 | +import ( | ||
| 4 | + "flag" | ||
| 5 | + "os" | ||
| 6 | + "path/filepath" | ||
| 7 | + "slices" | ||
| 8 | + "testing" | ||
| 9 | + | ||
| 10 | + "rickub.com/turbo-editors/turbo-core/app" | ||
| 11 | + "rickub.com/turbo-editors/turbo-core/settings" | ||
| 12 | + | ||
| 13 | + "rickub.com/turbo-editors/turbo-moonbit/internal/moonbitlang" | ||
| 14 | +) | ||
| 15 | + | ||
| 16 | +// withArgs runs the command line parser against a fixed argument list, and | ||
| 17 | +// restores the real one afterwards so tests do not affect each other. | ||
| 18 | +func withArgs(t *testing.T, args ...string) options { | ||
| 19 | + t.Helper() | ||
| 20 | + | ||
| 21 | + realArgs, realFlags := os.Args, flag.CommandLine | ||
| 22 | + t.Cleanup(func() { os.Args, flag.CommandLine = realArgs, realFlags }) | ||
| 23 | + | ||
| 24 | + os.Args = append([]string{"turbo-moonbit"}, args...) | ||
| 25 | + flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ContinueOnError) | ||
| 26 | + return parseFlags() | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +func TestFilesAreWhatIsLeftAfterTheFlags(t *testing.T) { | ||
| 30 | + opts := withArgs(t, "-no-lsp", "main.mbt", "lib/x.mbt") | ||
| 31 | + | ||
| 32 | + if !opts.noLSP { | ||
| 33 | + t.Error("-no-lsp was not read") | ||
| 34 | + } | ||
| 35 | + if want := []string{"main.mbt", "lib/x.mbt"}; !slices.Equal(opts.files, want) { | ||
| 36 | + t.Errorf("files = %v, want %v", opts.files, want) | ||
| 37 | + } | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +func TestTheThemeFlagDefaultsToEmptyRatherThanToAName(t *testing.T) { | ||
| 41 | + // Empty is what lets "was -theme given?" still be answered afterwards, and | ||
| 42 | + // that is what lets the project's settings fill it in without overriding an | ||
| 43 | + // explicit choice. | ||
| 44 | + if opts := withArgs(t); opts.theme != "" { | ||
| 45 | + t.Errorf("theme = %q with no flag, want the empty string", opts.theme) | ||
| 46 | + } | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +func TestTheThemeFlagBeatsTheProjectSettings(t *testing.T) { | ||
| 50 | + project := settings.Default() | ||
| 51 | + project.Theme = "cobalt" | ||
| 52 | + | ||
| 53 | + if got := themeName(options{theme: "monochrome"}, project); got != "monochrome" { | ||
| 54 | + t.Errorf("themeName() = %q, want the flag's %q", got, "monochrome") | ||
| 55 | + } | ||
| 56 | +} | ||
| 57 | + | ||
| 58 | +func TestTheProjectSettingsBeatTheBuiltInDefault(t *testing.T) { | ||
| 59 | + project := settings.Default() | ||
| 60 | + project.Theme = "cobalt" | ||
| 61 | + | ||
| 62 | + if got := themeName(options{}, project); got != "cobalt" { | ||
| 63 | + t.Errorf("themeName() = %q, want the project's %q", got, "cobalt") | ||
| 64 | + } | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +func TestTheBuiltInDefaultIsUsedWhenNobodySaysOtherwise(t *testing.T) { | ||
| 68 | + if got := themeName(options{}, settings.Default()); got == "" { | ||
| 69 | + t.Error("themeName() = \"\" with nothing set, want the library's default") | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +func TestTheProjectRootIsTheNearestMoonModule(t *testing.T) { | ||
| 74 | + // app.ProjectRoot walks up looking for the profile's RootMarkers. This is | ||
| 75 | + // what decides the directory moon-lsp is started in, and starting it | ||
| 76 | + // anywhere else is how a server answers nothing for a whole session. | ||
| 77 | + root := t.TempDir() | ||
| 78 | + nested := filepath.Join(root, "cmd", "main") | ||
| 79 | + if err := os.MkdirAll(nested, 0o755); err != nil { | ||
| 80 | + t.Fatal(err) | ||
| 81 | + } | ||
| 82 | + if err := os.WriteFile(filepath.Join(root, "moon.mod"), []byte(`name = "u/m"`), 0o644); err != nil { | ||
| 83 | + t.Fatal(err) | ||
| 84 | + } | ||
| 85 | + | ||
| 86 | + file := filepath.Join(nested, "main.mbt") | ||
| 87 | + if got := app.ProjectRoot(moonbitlang.Profile(), []string{file}); got != root { | ||
| 88 | + t.Errorf("ProjectRoot(%q) = %q, want %q", file, got, root) | ||
| 89 | + } | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +func TestTheLegacyJSONModuleFileIsAlsoARoot(t *testing.T) { | ||
| 93 | + root := t.TempDir() | ||
| 94 | + if err := os.WriteFile(filepath.Join(root, "moon.mod.json"), []byte(`{"name":"u/m"}`), 0o644); err != nil { | ||
| 95 | + t.Fatal(err) | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + file := filepath.Join(root, "main.mbt") | ||
| 99 | + if got := app.ProjectRoot(moonbitlang.Profile(), []string{file}); got != root { | ||
| 100 | + t.Errorf("ProjectRoot(%q) = %q, want %q", file, got, root) | ||
| 101 | + } | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +func TestTheNearestModuleWinsOverTheOneAboveIt(t *testing.T) { | ||
| 105 | + // A workspace holds several modules. The server belongs to the one the | ||
| 106 | + // file is in, not to the outermost directory that happens to have a | ||
| 107 | + // manifest. | ||
| 108 | + outer := t.TempDir() | ||
| 109 | + inner := filepath.Join(outer, "member") | ||
| 110 | + if err := os.MkdirAll(inner, 0o755); err != nil { | ||
| 111 | + t.Fatal(err) | ||
| 112 | + } | ||
| 113 | + for _, dir := range []string{outer, inner} { | ||
| 114 | + if err := os.WriteFile(filepath.Join(dir, "moon.mod"), []byte(`name = "u/m"`), 0o644); err != nil { | ||
| 115 | + t.Fatal(err) | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + file := filepath.Join(inner, "lib.mbt") | ||
| 120 | + if got := app.ProjectRoot(moonbitlang.Profile(), []string{file}); got != inner { | ||
| 121 | + t.Errorf("ProjectRoot(%q) = %q, want the nearer %q", file, got, inner) | ||
| 122 | + } | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +func TestLoadingSettingsFromADirectoryWithNoneGivesTheDefaults(t *testing.T) { | ||
| 126 | + // A directory somebody merely started the editor in has said nothing, and | ||
| 127 | + // the editor must not write to it. The starter file turns autosave on; the | ||
| 128 | + // default leaves it off. | ||
| 129 | + dir := t.TempDir() | ||
| 130 | + t.Chdir(dir) | ||
| 131 | + | ||
| 132 | + project, loaded := loadProjectSettings(moonbitlang.Profile()) | ||
| 133 | + if project == "" { | ||
| 134 | + t.Error("loadProjectSettings returned no project directory") | ||
| 135 | + } | ||
| 136 | + if loaded.Autosave { | ||
| 137 | + t.Error("autosave is on with no settings file, want it off") | ||
| 138 | + } | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +func TestABrokenSettingsFileDoesNotStopTheEditorOpening(t *testing.T) { | ||
| 142 | + // A broken settings file must not stop the editor opening, because the | ||
| 143 | + // editor is how you would fix it. | ||
| 144 | + dir := t.TempDir() | ||
| 145 | + p := moonbitlang.Profile() | ||
| 146 | + if err := os.MkdirAll(filepath.Join(dir, p.ProjectDir()), 0o755); err != nil { | ||
| 147 | + t.Fatal(err) | ||
| 148 | + } | ||
| 149 | + if err := os.WriteFile(settings.Path(p, dir), []byte("this is not ["), 0o644); err != nil { | ||
| 150 | + t.Fatal(err) | ||
| 151 | + } | ||
| 152 | + t.Chdir(dir) | ||
| 153 | + | ||
| 154 | + if _, loaded := loadProjectSettings(p); loaded != settings.Default() { | ||
| 155 | + t.Errorf("loadProjectSettings() = %+v with a broken file, want the defaults", loaded) | ||
| 156 | + } | ||
| 157 | +} | ||
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-moonbit") | |
| 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-moonbit") | |
| 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_MOONBIT_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-moonbit-*", "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_MOONBIT_RELEASING") { | |
| 592 | + t.Error("the workflow runs the suite without TURBO_MOONBIT_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-moonbit") | ||
| 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-moonbit") | ||
| 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_MOONBIT_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-moonbit-*", "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_MOONBIT_RELEASING") { | ||
| 592 | + t.Error("the workflow runs the suite without TURBO_MOONBIT_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-moonbit v0.2.0 88a4c38 | |
| 7 | +# scripts/check-version.sh bin/turbo-moonbit # 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-moonbit v0.2.0 88a4c38 | ||
| 7 | +# scripts/check-version.sh bin/turbo-moonbit # 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 +318 -0 | new file mode 100755 | ||
| @@ -0,0 +1,318 @@ | ||
| 1 | +#!/usr/bin/env bash | |
| 2 | +# | |
| 3 | +# Build turbo-moonbit 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-server # install the MoonBit toolchain 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-moonbit -version` names the commit it was built from. | |
| 14 | + | |
| 15 | +set -euo pipefail | |
| 16 | + | |
| 17 | +readonly BINARY=turbo-moonbit | |
| 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 the MoonBit toolchain, 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-moonbit 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 | +# moon-lsp is not installed on its own. It ships inside the MoonBit toolchain, | |
| 234 | +# alongside moon and moonc, so there is one command for all of it and a machine | |
| 235 | +# with moon but no moon-lsp is not a machine anybody has. | |
| 236 | +readonly SERVER=moon-lsp | |
| 237 | +readonly TOOLCHAIN_INSTALLER=https://cli.moonbitlang.com/install/unix.sh | |
| 238 | + | |
| 239 | +# find_server looks where the editor itself looks: PATH, then $MOON_HOME/bin, | |
| 240 | +# then the ~/.moon/bin the installer writes into when MOON_HOME says nothing. | |
| 241 | +# | |
| 242 | +# Finding it is not the same as its working: a file left behind by a half-undone | |
| 243 | +# installation sits on PATH and fails only when started. So this asks it for its | |
| 244 | +# version rather than trusting the file's existence, which is the difference | |
| 245 | +# between "you have completion" and "you will find out you have not when you | |
| 246 | +# press Ctrl-Space". | |
| 247 | +find_server() { | |
| 248 | + local candidate | |
| 249 | + for candidate in \ | |
| 250 | + "$(command -v "$SERVER" 2>/dev/null || true)" \ | |
| 251 | + "${MOON_HOME:-/nonexistent}/bin/$SERVER" \ | |
| 252 | + "$HOME/.moon/bin/$SERVER"; do | |
| 253 | + [ -n "$candidate" ] && [ -x "$candidate" ] || continue | |
| 254 | + "$candidate" --version >/dev/null 2>&1 || continue | |
| 255 | + printf '%s\n' "$candidate" | |
| 256 | + return 0 | |
| 257 | + done | |
| 258 | + return 1 | |
| 259 | +} | |
| 260 | + | |
| 261 | +# server_has_toolchain reports whether the build system is there beside the | |
| 262 | +# server. | |
| 263 | +# | |
| 264 | +# moon-lsp answers about a *project*, and it works the project out by running | |
| 265 | +# moon: without it the server starts, and then knows nothing about any file in | |
| 266 | +# any package. A server that starts and answers nothing looks exactly like a | |
| 267 | +# server that is not running at all, which is why this is checked separately | |
| 268 | +# rather than assumed from the server being found. | |
| 269 | +server_has_toolchain() { | |
| 270 | + local dir | |
| 271 | + dir="$(dirname "$1")" | |
| 272 | + [ -x "$dir/moon" ] || command -v moon >/dev/null 2>&1 | |
| 273 | +} | |
| 274 | + | |
| 275 | +# install_server runs the one command the editor's install hint names. | |
| 276 | +install_server() { | |
| 277 | + command -v curl >/dev/null 2>&1 || die "curl is needed to install the MoonBit toolchain" | |
| 278 | + curl -fsSL "$TOOLCHAIN_INSTALLER" | bash || | |
| 279 | + die "the MoonBit toolchain installer failed; see https://www.moonbitlang.com/download" | |
| 280 | +} | |
| 281 | + | |
| 282 | +step "Checking the language server" | |
| 283 | + | |
| 284 | +if $with_server && ! find_server >/dev/null; then | |
| 285 | + info " installing the MoonBit toolchain…" | |
| 286 | + install_server | |
| 287 | +fi | |
| 288 | + | |
| 289 | +if server_path="$(find_server)"; then | |
| 290 | + ok "$SERVER at $server_path" | |
| 291 | + | |
| 292 | + if ! server_has_toolchain "$server_path"; then | |
| 293 | + warn "…but moon is not beside it, so the server will answer nothing." | |
| 294 | + warn "moon-lsp works a project out by running moon; without it there is no project." | |
| 295 | + info "" | |
| 296 | + info " curl -fsSL $TOOLCHAIN_INSTALLER | bash" | |
| 297 | + fi | |
| 298 | +else | |
| 299 | + warn "$SERVER is not installed, so there will be no completion." | |
| 300 | + warn "Editing, colouring and themes all work without it." | |
| 301 | + info "" | |
| 302 | + info " curl -fsSL $TOOLCHAIN_INSTALLER | bash" | |
| 303 | + info " ${DIM}or re-run this script with --with-server${RESET}" | |
| 304 | +fi | |
| 305 | + | |
| 306 | +# --- what to do next -------------------------------------------------------- | |
| 307 | + | |
| 308 | +info "" | |
| 309 | +step "Ready" | |
| 310 | +info "" | |
| 311 | +info " Open a file ${BOLD}inside a MoonBit module${RESET} — completion needs one:" | |
| 312 | +info "" | |
| 313 | +info " cd /path/to/your/project" | |
| 314 | +info " $BINARY main.mbt" | |
| 315 | +info "" | |
| 316 | +info " ${DIM}F10 menu · F2 save · Alt-X exit · type a '.' for completion${RESET}" | |
| 317 | +info " ${DIM}themes: $BINARY -list-themes${RESET}" | |
| 318 | +info "" | |
| new file mode 100755 | |||
| @@ -0,0 +1,318 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# | ||
| 3 | +# Build turbo-moonbit 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-server # install the MoonBit toolchain 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-moonbit -version` names the commit it was built from. | ||
| 14 | + | ||
| 15 | +set -euo pipefail | ||
| 16 | + | ||
| 17 | +readonly BINARY=turbo-moonbit | ||
| 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 the MoonBit toolchain, 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-moonbit 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 | +# moon-lsp is not installed on its own. It ships inside the MoonBit toolchain, | ||
| 234 | +# alongside moon and moonc, so there is one command for all of it and a machine | ||
| 235 | +# with moon but no moon-lsp is not a machine anybody has. | ||
| 236 | +readonly SERVER=moon-lsp | ||
| 237 | +readonly TOOLCHAIN_INSTALLER=https://cli.moonbitlang.com/install/unix.sh | ||
| 238 | + | ||
| 239 | +# find_server looks where the editor itself looks: PATH, then $MOON_HOME/bin, | ||
| 240 | +# then the ~/.moon/bin the installer writes into when MOON_HOME says nothing. | ||
| 241 | +# | ||
| 242 | +# Finding it is not the same as its working: a file left behind by a half-undone | ||
| 243 | +# installation sits on PATH and fails only when started. So this asks it for its | ||
| 244 | +# version rather than trusting the file's existence, which is the difference | ||
| 245 | +# between "you have completion" and "you will find out you have not when you | ||
| 246 | +# press Ctrl-Space". | ||
| 247 | +find_server() { | ||
| 248 | + local candidate | ||
| 249 | + for candidate in \ | ||
| 250 | + "$(command -v "$SERVER" 2>/dev/null || true)" \ | ||
| 251 | + "${MOON_HOME:-/nonexistent}/bin/$SERVER" \ | ||
| 252 | + "$HOME/.moon/bin/$SERVER"; do | ||
| 253 | + [ -n "$candidate" ] && [ -x "$candidate" ] || continue | ||
| 254 | + "$candidate" --version >/dev/null 2>&1 || continue | ||
| 255 | + printf '%s\n' "$candidate" | ||
| 256 | + return 0 | ||
| 257 | + done | ||
| 258 | + return 1 | ||
| 259 | +} | ||
| 260 | + | ||
| 261 | +# server_has_toolchain reports whether the build system is there beside the | ||
| 262 | +# server. | ||
| 263 | +# | ||
| 264 | +# moon-lsp answers about a *project*, and it works the project out by running | ||
| 265 | +# moon: without it the server starts, and then knows nothing about any file in | ||
| 266 | +# any package. A server that starts and answers nothing looks exactly like a | ||
| 267 | +# server that is not running at all, which is why this is checked separately | ||
| 268 | +# rather than assumed from the server being found. | ||
| 269 | +server_has_toolchain() { | ||
| 270 | + local dir | ||
| 271 | + dir="$(dirname "$1")" | ||
| 272 | + [ -x "$dir/moon" ] || command -v moon >/dev/null 2>&1 | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +# install_server runs the one command the editor's install hint names. | ||
| 276 | +install_server() { | ||
| 277 | + command -v curl >/dev/null 2>&1 || die "curl is needed to install the MoonBit toolchain" | ||
| 278 | + curl -fsSL "$TOOLCHAIN_INSTALLER" | bash || | ||
| 279 | + die "the MoonBit toolchain installer failed; see https://www.moonbitlang.com/download" | ||
| 280 | +} | ||
| 281 | + | ||
| 282 | +step "Checking the language server" | ||
| 283 | + | ||
| 284 | +if $with_server && ! find_server >/dev/null; then | ||
| 285 | + info " installing the MoonBit toolchain…" | ||
| 286 | + install_server | ||
| 287 | +fi | ||
| 288 | + | ||
| 289 | +if server_path="$(find_server)"; then | ||
| 290 | + ok "$SERVER at $server_path" | ||
| 291 | + | ||
| 292 | + if ! server_has_toolchain "$server_path"; then | ||
| 293 | + warn "…but moon is not beside it, so the server will answer nothing." | ||
| 294 | + warn "moon-lsp works a project out by running moon; without it there is no project." | ||
| 295 | + info "" | ||
| 296 | + info " curl -fsSL $TOOLCHAIN_INSTALLER | bash" | ||
| 297 | + fi | ||
| 298 | +else | ||
| 299 | + warn "$SERVER is not installed, so there will be no completion." | ||
| 300 | + warn "Editing, colouring and themes all work without it." | ||
| 301 | + info "" | ||
| 302 | + info " curl -fsSL $TOOLCHAIN_INSTALLER | bash" | ||
| 303 | + info " ${DIM}or re-run this script with --with-server${RESET}" | ||
| 304 | +fi | ||
| 305 | + | ||
| 306 | +# --- what to do next -------------------------------------------------------- | ||
| 307 | + | ||
| 308 | +info "" | ||
| 309 | +step "Ready" | ||
| 310 | +info "" | ||
| 311 | +info " Open a file ${BOLD}inside a MoonBit module${RESET} — completion needs one:" | ||
| 312 | +info "" | ||
| 313 | +info " cd /path/to/your/project" | ||
| 314 | +info " $BINARY main.mbt" | ||
| 315 | +info "" | ||
| 316 | +info " ${DIM}F10 menu · F2 save · Alt-X exit · type a '.' for completion${RESET}" | ||
| 317 | +info " ${DIM}themes: $BINARY -list-themes${RESET}" | ||
| 318 | +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-moonbit") | |
| 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-moonbit") | |
| 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-moonbit") | |
| 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-moonbit") | |
| 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-moonbit") | ||
| 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-moonbit") | ||
| 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-moonbit") | ||
| 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-moonbit") | ||
| 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 | +} | ||