Premier commit déjà bien avancé

This commit is contained in:
2025-11-10 18:33:24 +01:00
commit db4f0508cb
652 changed files with 440521 additions and 0 deletions

569
API.md Normal file
View File

@ -0,0 +1,569 @@
# Project Notes REST API Documentation
Version: **v1**
Base URL: `http://localhost:8080/api/v1`
## Table des matières
- [Vue d'ensemble](#vue-densemble)
- [Authentification](#authentification)
- [Formats de données](#formats-de-données)
- [Endpoints](#endpoints)
- [Lister les notes](#lister-les-notes)
- [Récupérer une note](#récupérer-une-note)
- [Créer/Mettre à jour une note](#créermettre-à-jour-une-note)
- [Supprimer une note](#supprimer-une-note)
- [Codes de statut HTTP](#codes-de-statut-http)
- [Exemples d'utilisation](#exemples-dutilisation)
---
## Vue d'ensemble
L'API REST de Project Notes permet de gérer vos notes Markdown via HTTP. Elle supporte :
- **Listage** : Récupérer la liste de toutes les notes avec métadonnées
- **Lecture** : Télécharger une note en JSON ou Markdown brut
- **Écriture** : Créer ou mettre à jour une note
- **Suppression** : Supprimer une note définitivement
### Caractéristiques
-**Versionnée** : `/api/v1` pour assurer la compatibilité future
-**Content Negotiation** : Support JSON et Markdown selon le header `Accept`
-**Idempotence** : PUT crée ou met à jour (idempotent)
-**Automatisation** : Front matter géré automatiquement
-**Ré-indexation** : Recherche mise à jour automatiquement après chaque modification
-**Support sous-dossiers** : Organisation hiérarchique native
---
## Authentification
**Version actuelle : Aucune authentification requise**
⚠️ **IMPORTANT** : L'API n'a pas d'authentification. Si vous exposez le serveur publiquement :
1. Utilisez un reverse proxy (nginx, Caddy) avec authentification
2. Implémentez Basic Auth ou API Key
3. Utilisez un VPN ou tunnel SSH
---
## Formats de données
### Note complète (NoteResponse)
```json
{
"path": "projet/backend.md",
"title": "Backend API",
"content": "---\ntitle: Backend API\n...\n---\n\n# Content",
"body": "\n# Content",
"frontMatter": {
"title": "Backend API",
"date": "10-11-2025",
"last_modified": "10-11-2025:14:30",
"tags": ["projet", "backend"]
},
"lastModified": "10-11-2025:14:30",
"size": 1024
}
```
### Métadonnées de note (NoteMetadata)
```json
{
"path": "projet/backend.md",
"title": "Backend API",
"tags": ["projet", "backend"],
"lastModified": "10-11-2025:14:30",
"date": "10-11-2025",
"size": 1024
}
```
### Requête de création/modification (NoteRequest)
Deux options :
**Option 1 : Content complet** (recommandé pour migration)
```json
{
"content": "---\ntitle: Ma note\ntags: [test]\n---\n\n# Contenu"
}
```
**Option 2 : Body + FrontMatter séparés** (recommandé pour création)
```json
{
"body": "\n# Mon contenu\n\nTexte ici...",
"frontMatter": {
"title": "Ma note",
"tags": ["test", "exemple"]
}
}
```
### Erreur (ErrorResponse)
```json
{
"error": "Bad Request",
"message": "Invalid path",
"code": 400
}
```
---
## Endpoints
### Lister les notes
Récupère la liste de toutes les notes avec leurs métadonnées.
**Endpoint** : `GET /api/v1/notes`
**Paramètres** : Aucun
**Réponse** : `200 OK`
```json
{
"notes": [
{
"path": "projet/backend.md",
"title": "Backend API",
"tags": ["projet", "backend"],
"lastModified": "10-11-2025:14:30",
"date": "10-11-2025",
"size": 1024
},
{
"path": "daily/2025-11-10.md",
"title": "Notes du 10 novembre",
"tags": ["daily"],
"lastModified": "10-11-2025:09:15",
"date": "10-11-2025",
"size": 2048
}
],
"total": 2
}
```
**Exemple curl** :
```bash
curl http://localhost:8080/api/v1/notes
```
---
### Récupérer une note
Télécharge une note spécifique. Le format dépend du header `Accept`.
**Endpoint** : `GET /api/v1/notes/{path}`
**Paramètres** :
- `{path}` : Chemin relatif de la note (ex: `projet/backend.md`)
**Headers** :
- `Accept: application/json` (défaut) : Retourne JSON avec métadonnées
- `Accept: text/markdown` : Retourne Markdown brut
- `Accept: text/plain` : Retourne Markdown brut
**Réponse JSON** : `200 OK`
```json
{
"path": "projet/backend.md",
"title": "Backend API",
"content": "---\ntitle: Backend API\ndate: 10-11-2025\nlast_modified: 10-11-2025:14:30\ntags:\n - projet\n - backend\n---\n\n# Backend API\n\nContenu de la note...",
"body": "\n# Backend API\n\nContenu de la note...",
"frontMatter": {
"title": "Backend API",
"date": "10-11-2025",
"last_modified": "10-11-2025:14:30",
"tags": ["projet", "backend"]
},
"lastModified": "10-11-2025:14:30",
"size": 1024
}
```
**Réponse Markdown** : `200 OK`
```markdown
---
title: Backend API
date: 10-11-2025
last_modified: 10-11-2025:14:30
tags:
- projet
- backend
---
# Backend API
Contenu de la note...
```
**Erreurs** :
- `404 Not Found` : Note inexistante
**Exemples curl** :
```bash
# Récupérer en JSON
curl http://localhost:8080/api/v1/notes/projet/backend.md \
-H "Accept: application/json"
# Récupérer en Markdown brut
curl http://localhost:8080/api/v1/notes/projet/backend.md \
-H "Accept: text/markdown"
# Sauvegarder dans un fichier
curl http://localhost:8080/api/v1/notes/projet/backend.md \
-H "Accept: text/markdown" \
-o backend.md
```
---
### Créer/Mettre à jour une note
Crée une nouvelle note ou met à jour une note existante (idempotent).
**Endpoint** : `PUT /api/v1/notes/{path}`
**Paramètres** :
- `{path}` : Chemin relatif de la note (ex: `projet/nouvelle-note.md`)
**Headers** :
- `Content-Type: application/json` : Envoyer du JSON
- `Content-Type: text/markdown` : Envoyer du Markdown brut
**Body JSON** :
```json
{
"body": "\n# Ma nouvelle note\n\nContenu ici...",
"frontMatter": {
"title": "Ma nouvelle note",
"tags": ["test", "exemple"]
}
}
```
Ou avec `content` complet :
```json
{
"content": "---\ntitle: Ma note\ntags: [test]\n---\n\n# Contenu"
}
```
**Body Markdown brut** :
```markdown
# Ma nouvelle note
Contenu ici...
```
**Réponse** : `201 Created` (nouvelle note) ou `200 OK` (mise à jour)
```json
{
"path": "projet/nouvelle-note.md",
"title": "Ma nouvelle note",
"content": "---\ntitle: Ma nouvelle note\n...",
"body": "\n# Ma nouvelle note\n\nContenu ici...",
"frontMatter": {
"title": "Ma nouvelle note",
"date": "10-11-2025",
"last_modified": "10-11-2025:14:35",
"tags": ["test", "exemple"]
},
"lastModified": "10-11-2025:14:35",
"size": 256
}
```
**Comportement** :
- ✅ Crée automatiquement les dossiers parents
- ✅ Génère le front matter si absent
- ✅ Met à jour `last_modified` automatiquement
- ✅ Préserve `date` pour notes existantes
- ✅ Ré-indexe automatiquement pour la recherche
**Erreurs** :
- `400 Bad Request` : Chemin invalide ou JSON malformé
- `415 Unsupported Media Type` : Content-Type non supporté
- `500 Internal Server Error` : Erreur d'écriture
**Exemples curl** :
```bash
# Créer avec JSON
curl -X PUT http://localhost:8080/api/v1/notes/projet/test.md \
-H "Content-Type: application/json" \
-d '{
"body": "\n# Test\n\nCeci est un test.",
"frontMatter": {
"title": "Note de test",
"tags": ["test"]
}
}'
# Créer avec Markdown brut
curl -X PUT http://localhost:8080/api/v1/notes/projet/simple.md \
-H "Content-Type: text/markdown" \
-d "# Simple note
Contenu simple sans front matter."
# Upload depuis un fichier
curl -X PUT http://localhost:8080/api/v1/notes/projet/from-file.md \
-H "Content-Type: text/markdown" \
--data-binary @local-file.md
```
---
### Supprimer une note
Supprime définitivement une note.
**Endpoint** : `DELETE /api/v1/notes/{path}`
**Paramètres** :
- `{path}` : Chemin relatif de la note (ex: `projet/old-note.md`)
**Réponse** : `200 OK`
```json
{
"message": "Note deleted successfully",
"path": "projet/old-note.md"
}
```
**Erreurs** :
- `404 Not Found` : Note inexistante
- `500 Internal Server Error` : Erreur de suppression
**Exemple curl** :
```bash
curl -X DELETE http://localhost:8080/api/v1/notes/projet/old-note.md
```
---
## Codes de statut HTTP
| Code | Signification | Description |
|------|---------------|-------------|
| `200` | OK | Requête réussie |
| `201` | Created | Note créée avec succès |
| `400` | Bad Request | Requête invalide (chemin, JSON, etc.) |
| `404` | Not Found | Note inexistante |
| `405` | Method Not Allowed | Méthode HTTP non supportée |
| `415` | Unsupported Media Type | Content-Type non supporté |
| `500` | Internal Server Error | Erreur serveur |
---
## Exemples d'utilisation
### Synchronisation de notes
**Télécharger toutes les notes** :
```bash
#!/bin/bash
# Télécharger toutes les notes localement
mkdir -p notes-backup
# Récupérer la liste
curl -s http://localhost:8080/api/v1/notes | jq -r '.notes[].path' | while read path; do
# Créer les dossiers parents
mkdir -p "notes-backup/$(dirname "$path")"
# Télécharger la note
curl -s http://localhost:8080/api/v1/notes/"$path" \
-H "Accept: text/markdown" \
-o "notes-backup/$path"
echo "✓ Downloaded: $path"
done
echo "Backup terminé!"
```
**Uploader un dossier de notes** :
```bash
#!/bin/bash
# Uploader toutes les notes .md d'un dossier
find ./my-notes -name "*.md" | while read file; do
# Calculer le chemin relatif
relpath="${file#./my-notes/}"
# Upload
curl -X PUT http://localhost:8080/api/v1/notes/"$relpath" \
-H "Content-Type: text/markdown" \
--data-binary @"$file"
echo "✓ Uploaded: $relpath"
done
echo "Upload terminé!"
```
### Recherche et filtrage
**Lister toutes les notes avec un tag spécifique** :
```bash
curl -s http://localhost:8080/api/v1/notes | \
jq '.notes[] | select(.tags | contains(["projet"])) | .path'
```
**Compter les notes par dossier** :
```bash
curl -s http://localhost:8080/api/v1/notes | \
jq -r '.notes[].path' | \
xargs -n1 dirname | \
sort | uniq -c
```
### Création automatique de notes
**Note quotidienne** :
```bash
#!/bin/bash
# Créer une note quotidienne
TODAY=$(date +%Y-%m-%d)
TITLE="Notes du $(date +%d/%m/%Y)"
curl -X PUT http://localhost:8080/api/v1/notes/daily/${TODAY}.md \
-H "Content-Type: application/json" \
-d "{
\"body\": \"\\n# ${TITLE}\\n\\n## Tasks\\n- [ ] TODO\\n\\n## Notes\\n\",
\"frontMatter\": {
\"title\": \"${TITLE}\",
\"tags\": [\"daily\"]
}
}"
echo "Note quotidienne créée: daily/${TODAY}.md"
```
### Intégration avec d'autres outils
**Exporter en HTML avec Pandoc** :
```bash
curl -s http://localhost:8080/api/v1/notes/projet/doc.md \
-H "Accept: text/markdown" | \
pandoc -f markdown -t html -o doc.html
echo "Exporté en HTML: doc.html"
```
**Recherche full-text avec jq** :
```bash
# Chercher "API" dans tous les titres
curl -s http://localhost:8080/api/v1/notes | \
jq '.notes[] | select(.title | contains("API"))'
```
### Script de maintenance
**Vérifier les notes sans tags** :
```bash
curl -s http://localhost:8080/api/v1/notes | \
jq -r '.notes[] | select(.tags | length == 0) | .path'
```
**Statistiques** :
```bash
#!/bin/bash
# Afficher des statistiques sur les notes
STATS=$(curl -s http://localhost:8080/api/v1/notes)
TOTAL=$(echo "$STATS" | jq '.total')
TOTAL_SIZE=$(echo "$STATS" | jq '[.notes[].size] | add')
AVG_SIZE=$(echo "$STATS" | jq '[.notes[].size] | add / length | floor')
echo "📊 Statistiques des notes"
echo "========================"
echo "Total de notes: $TOTAL"
echo "Taille totale: $(numfmt --to=iec-i --suffix=B $TOTAL_SIZE)"
echo "Taille moyenne: $(numfmt --to=iec-i --suffix=B $AVG_SIZE)"
echo ""
echo "Top 5 tags:"
echo "$STATS" | jq -r '.notes[].tags[]' | sort | uniq -c | sort -rn | head -5
```
---
## Bonnes pratiques
### Sécurité
1. **Ne pas exposer publiquement sans authentification**
2. **Utiliser HTTPS en production**
3. **Valider les chemins côté client** (éviter `../` malveillants)
4. **Limiter la taille des uploads** (si nécessaire, ajouter un middleware)
### Performance
1. **Pagination** : L'API liste ne pagine pas actuellement (toutes les notes en une requête). Pour beaucoup de notes (>1000), envisager d'ajouter `?limit=` et `?offset=`
2. **Cache** : Utiliser un proxy cache (Varnish, nginx) pour GET
3. **Compression** : Activer gzip sur le reverse proxy
### Workflow recommandé
1. **Backup régulier** : Script cron qui télécharge toutes les notes
2. **Versioning Git** : Synchroniser le dossier de notes avec Git
3. **CI/CD** : Valider le format Markdown avec des linters
4. **Monitoring** : Logger les accès API pour audit
---
## Support et contribution
- **Issues** : Rapporter les bugs sur GitHub
- **Documentation** : Ce fichier (`API.md`)
- **Code source** : `internal/api/rest_handler.go`
---
## Changelog
### v1 (2025-11-10)
- ✨ Première version de l'API REST
- ✅ Endpoints: LIST, GET, PUT, DELETE
- ✅ Content negotiation JSON/Markdown
- ✅ Support sous-dossiers
- ✅ Gestion automatique du front matter
- ✅ Ré-indexation automatique
---
**Note** : Cette API coexiste avec l'interface web HTML. Les deux peuvent être utilisées simultanément sans conflit.

421
CLAUDE.md Normal file
View File

@ -0,0 +1,421 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
A lightweight web-based Markdown note-taking application with a Go backend and modern JavaScript frontend. Notes are stored as plain Markdown files with YAML front matter containing metadata (title, date, last_modified, tags). The system provides a sophisticated CodeMirror 6 editor with live preview, rich search capabilities, hierarchical organization, and automatic front matter management.
**Recent Modernization**: The project has been migrated from a simple textarea editor to CodeMirror 6, with a Vite build system for frontend modules. The backend remains unchanged, maintaining the same Go architecture with htmx for dynamic interactions.
## Architecture
### Backend (Go)
Three main packages under `internal/`:
- **indexer**: Maintains an in-memory index mapping tags to note files. Parses YAML front matter from `.md` files to build the index. Thread-safe with RWMutex.
- **watcher**: Uses `fsnotify` to monitor filesystem changes and trigger re-indexing with 200ms debounce. Recursively watches all subdirectories.
- **api**: HTTP handlers that serve templates and handle CRUD operations on notes. Updates front matter automatically on save.
The server (`cmd/server/main.go`) coordinates these components:
1. Loads initial index from notes directory
2. Starts filesystem watcher for automatic re-indexing
3. Pre-parses HTML templates from `templates/`
4. Serves routes: `/` (main page), `/api/search`, `/api/notes/*`, `/api/tree`, `/api/folders/create`, `/api/files/move`
5. Handles static files from `static/` directory
### Frontend
The frontend uses a modern build system with Vite and CodeMirror 6:
#### Architecture
- **Build System**: Vite compiles frontend modules from `frontend/src/` to `static/dist/`
- **Editor**: CodeMirror 6 with Markdown language support, One Dark theme, and syntax highlighting
- **Templates**: `index.html`, `editor.html`, `file-tree.html`, `search-results.html`, `new-note-prompt.html`
- **HTMX Integration**: Server returns HTML fragments that htmx swaps into the DOM
- **Out-of-band swaps**: Update the file tree after saves/deletes without full page reload
#### Frontend Source Structure
```
frontend/src/
├── main.js # Entry point - imports all modules
├── editor.js # CodeMirror 6 editor implementation with slash commands
├── file-tree.js # Drag-and-drop file organization
└── ui.js # Sidebar toggle functionality
```
#### CodeMirror 6 Editor Features
- **Syntax Highlighting**: Full Markdown language support (`@codemirror/lang-markdown`)
- **Theme**: One Dark theme (`@codemirror/theme-one-dark`) - VS Code-inspired dark theme
- **Live Preview**: Debounced updates (150ms) synchronized with editor scroll position
- **Auto-Save**: Triggers after 2 seconds of inactivity
- **Keyboard Shortcuts**:
- `Ctrl/Cmd+S` for manual save
- `Tab` for proper indentation
- Full keyboard navigation
- **View Modes**: Toggle between split view, editor-only, and preview-only
- **Slash Commands**: Type `/` to open command palette for quick Markdown insertion
- **Front Matter Handling**: Automatically strips YAML front matter in preview
#### File Tree Features
- **Folder Management**: Expand/collapse folders with visual indicators (📁/📂)
- **Drag & Drop**: Move files between folders with visual feedback
- **Folder Creation**: Modal-based creation supporting nested paths
- **Safe Validation**: Prevents dangerous path operations
#### Rendering Pipeline
- **marked.js**: Markdown to HTML conversion
- **DOMPurify**: HTML sanitization to prevent XSS attacks
- **Highlight.js**: Syntax highlighting for code blocks in preview
- **Custom Theme**: Material Darker theme in `static/theme.css` with CSS custom properties
### Note Format
Notes have YAML front matter with these fields:
```yaml
---
title: "Note Title"
date: "08-11-2025"
last_modified: "08-11-2025:13:02"
tags: [tag1, tag2]
---
```
The `indexer` package handles both single-value and array-format tags via custom `UnmarshalYAML`.
## Development Commands
### Building the Frontend
**IMPORTANT**: The frontend must be built before running the application. The compiled JavaScript is required.
```bash
cd frontend
npm install # Install dependencies (first time only)
npm run build # Compile frontend modules to static/dist/
```
Output files (loaded by templates):
- `static/dist/project-notes-frontend.es.js` (ES module)
- `static/dist/project-notes-frontend.umd.js` (UMD format)
Frontend dependencies (from `frontend/package.json`):
- `@codemirror/basic-setup` - Base editor functionality
- `@codemirror/lang-markdown` - Markdown language support
- `@codemirror/state` - Editor state management
- `@codemirror/view` - Editor view layer
- `@codemirror/theme-one-dark` - Dark theme
- `vite` - Build tool
### Running the Server
```bash
go run ./cmd/server
```
Server starts on `http://localhost:8080`. Use flags to customize:
- `-addr :PORT` - Change server address (default: `:8080`)
- `-notes-dir PATH` - Change notes directory (default: `./notes`)
### Testing
Run all tests:
```bash
go test ./...
```
Run specific package tests:
```bash
go test ./internal/indexer
go test ./internal/api
```
Run tests with verbose output:
```bash
go test -v ./...
```
### Building the Server Binary
```bash
go build ./cmd/server
```
### Backend Dependencies
Update Go dependencies:
```bash
go mod tidy
```
Key backend dependencies:
- `github.com/fsnotify/fsnotify` - Filesystem watcher
- `gopkg.in/yaml.v3` - YAML parsing for front matter
### Vite Build System
The frontend uses Vite (`frontend/vite.config.js`) for bundling JavaScript modules:
**Configuration**:
- **Entry Point**: `frontend/src/main.js` (imports editor.js, file-tree.js, ui.js)
- **Output Directory**: `static/dist/` (served by Go server)
- **Library Mode**: Builds as a library with both ES and UMD formats
- **Single Bundle**: No code splitting - all dependencies bundled together
- **Aliases**: Path aliases for `@codemirror/state` and `@codemirror/view` to ensure consistent versions
**Build Process**:
1. Vite reads all source files from `frontend/src/`
2. Resolves npm dependencies (@codemirror packages)
3. Bundles everything into two formats:
- ES module (`project-notes-frontend.es.js`) - 1.0 MB
- UMD (`project-notes-frontend.umd.js`) - 679 KB
4. Outputs to `static/dist/` where Go server can serve them
5. Templates load the ES module version via `<script type="module">`
**Development Workflow**:
```bash
cd frontend
npm run build # Build for production
npm run build -- --watch # Watch mode for development
```
The Go server does not need to be restarted after frontend builds - simply refresh the browser.
## Key Implementation Details
### Front Matter Management
The system automatically manages front matter when saving notes:
- `title`: Auto-generated from filename if missing (converts hyphens to spaces, title-cases)
- `date`: Set to creation date for new files, preserved for existing files
- `last_modified`: Always updated to current timestamp on save (format: `DD-MM-YYYY:HH:MM`)
- `tags`: Preserved from user input; defaults to `["default"]` for new notes
Front matter extraction happens in two places:
- `indexer.ExtractFrontMatterAndBody()` - For file paths
- `indexer.ExtractFrontMatterAndBodyFromReader()` - For `io.Reader` (used when parsing form content)
### Indexing and Search
The indexer maintains two data structures:
- `tags map[string][]string` - Maps tags to file paths for tag-based lookup
- `docs map[string]*Document` - Stores full document metadata for rich search
Re-indexing happens:
- On server startup
- When files are created/modified/deleted (via watcher with 200ms debounce)
- After POST/DELETE/MOVE operations (background goroutine)
Rich search supports multiple query formats:
- General terms: Search across title, tags, path, and body (AND logic)
- `tag:value` - Filter by specific tag (case-insensitive)
- `title:value` - Filter by title content
- `path:value` - Filter by file path
- Quoted phrases: `"exact phrase"` preserves spaces
- Results are scored and ranked by relevance (title matches score highest)
### Security Considerations
File path validation in `handler.go`:
- `filepath.Clean()` to normalize paths
- Reject paths starting with `..` or absolute paths (directory traversal prevention)
- Enforce `.md` extension for notes
- Use `filepath.Join()` to construct safe paths within notes directory
- DOMPurify sanitizes Markdown-rendered HTML to prevent XSS attacks
### Template System
Templates are pre-parsed at startup. The API handler returns HTML fragments that htmx inserts into the page. Out-of-band swaps update the file tree sidebar without full page reload.
### Concurrency
- Indexer uses `sync.RWMutex` for thread-safe access (read locks for searches, write locks for re-indexing)
- Re-indexing after saves/deletes/moves happens in background goroutines to avoid blocking HTTP responses
- Watcher runs in separate goroutine with proper context cancellation
- Server shutdown uses 5-second graceful shutdown timeout with context
### File Organization
The application supports hierarchical note organization:
- Notes can be organized in subdirectories within the `notes/` directory
- The file tree displays folders and files in a hierarchical view
- Folders are displayed before files, both sorted alphabetically (case-insensitive)
- API endpoints for folder creation (`/api/folders/create`) and file moving (`/api/files/move`)
- Watcher recursively monitors all subdirectories for changes
### CodeMirror 6 Editor Implementation
The editor is implemented in `frontend/src/editor.js` with two main classes:
#### MarkdownEditor Class
Manages the CodeMirror 6 instance and its interactions:
**Initialization**:
```javascript
EditorState.create({
doc: content,
extensions: [
basicSetup, // Line numbers, search, fold gutter
markdown(), // Markdown syntax support
oneDark, // One Dark theme
keymap.of([indentWithTab]),
EditorView.updateListener.of(...), // Preview & auto-save
keymap.of([{ key: "Mod-s", run: saveFunction }])
]
});
```
**Key Features**:
- **Live Preview**: Updates preview pane with 150ms debounce on editor changes
- **Auto-Save**: Triggers form submission after 2 seconds of inactivity
- **Scroll Sync**: Bidirectional scroll synchronization between editor and preview (50ms debounce)
- **Front Matter Stripping**: Removes YAML front matter from preview rendering
- **View Modes**: Three modes (split/editor-only/preview-only) saved to localStorage
- **Height Management**: Dynamic height calculation (`window.innerHeight - 180px`) with resize handling
- **Cleanup**: Proper destruction of editor instances to prevent memory leaks
**Integration**:
- Replaces the hidden textarea element
- HTMX events trigger editor initialization (`htmx:afterSwap`)
- Form submission uses `requestSubmit()` to trigger HTMX POST
#### SlashCommands Class
Provides command palette for quick Markdown insertion:
**Trigger**: Type `/` at the beginning of a line to open the palette
**Implementation**:
- Monitors editor state changes for `/` character
- Filters commands in real-time as user types
- Positions palette dynamically using CodeMirror's `coordsAtPos()`
- Keyboard navigation with arrow keys, Enter/Tab to select
- Inserts Markdown text using CodeMirror transactions
- 13 built-in commands with text templates
**UI/UX**:
- Styled palette with gradient selection indicator
- Smooth animations and transitions
- Accessible keyboard navigation
- Auto-closes on selection or Escape key
### Slash Commands
The editor includes a slash command system integrated with CodeMirror 6:
- Type `/` at the start of a line to trigger the command palette
- Available commands (13 total):
- **Headings**: h1, h2, h3 - Insert Markdown headers
- **Formatting**: bold, italic, code - Text formatting
- **Blocks**: codeblock, quote, hr, table - Block-level elements
- **Lists**: list - Unordered list
- **Dynamic**: date - Insert current date in French format (DD/MM/YYYY)
- **Links**: link - Insert link template `[text](url)`
- Navigate with Arrow Up/Down, select with Enter/Tab, cancel with Escape
- Commands are filtered in real-time as you type after the `/`
- The palette is positioned dynamically near the cursor using CodeMirror coordinates
- Implementation in `frontend/src/editor.js` with the `SlashCommands` class
- Styled command palette with gradient selection indicator
## Frontend Libraries
The application uses a mix of npm packages (for the editor) and CDN-loaded libraries (for utilities):
### NPM Packages (Built with Vite)
Managed in `frontend/package.json`:
- **@codemirror/basic-setup (^0.20.0)**: Base editor functionality (line numbers, search, etc.)
- **@codemirror/lang-markdown (^6.5.0)**: Markdown language support and syntax highlighting
- **@codemirror/state (^6.5.2)**: Editor state management
- **@codemirror/view (^6.38.6)**: Editor view layer and rendering
- **@codemirror/theme-one-dark (^6.1.3)**: Dark theme for CodeMirror
- **vite (^5.0.0)**: Build tool for bundling frontend modules
### CDN Libraries
Loaded in `templates/index.html`:
- **htmx (1.9.10)**: AJAX interactions and dynamic content loading
- **marked.js**: Markdown to HTML conversion for preview
- **DOMPurify**: HTML sanitization to prevent XSS attacks
- **Highlight.js (11.9.0)**: Syntax highlighting for code blocks in preview with Atom One Dark theme
### Styling
- **Material Darker Theme**: Custom dark theme in `static/theme.css`
- **Color System**: CSS custom properties for consistent theming
- Background colors: `--bg-primary`, `--bg-secondary`, `--bg-tertiary`, `--bg-elevated`
- Text colors: `--text-primary`, `--text-secondary`, `--text-muted`
- Accent colors: `--accent-blue`, `--accent-violet`
- **No CSS Framework**: All styles hand-crafted with CSS Grid and Flexbox
- **Responsive Design**: Adaptive layout for different screen sizes
- **Custom Scrollbars**: Styled scrollbars matching the dark theme
### Build Output
The Vite build process produces:
- `static/dist/project-notes-frontend.es.js` - ES module format (1.0 MB, includes all CodeMirror 6 dependencies)
- `static/dist/project-notes-frontend.umd.js` - UMD format (679 KB, legacy compatibility)
## Project Structure
```
project-notes/
├── cmd/
│ └── server/
│ └── main.go # Server entry point
├── internal/
│ ├── api/
│ │ └── handler.go # HTTP handlers for CRUD operations
│ ├── indexer/
│ │ └── indexer.go # Note indexing and search
│ └── watcher/
│ └── watcher.go # Filesystem watcher with fsnotify
├── frontend/ # Frontend build system (NEW)
│ ├── src/
│ │ ├── main.js # Entry point
│ │ ├── editor.js # CodeMirror 6 implementation (26 KB)
│ │ ├── file-tree.js # Drag-and-drop file management (11 KB)
│ │ └── ui.js # Sidebar toggle (720 B)
│ ├── package.json # NPM dependencies
│ ├── package-lock.json
│ └── vite.config.js # Vite build configuration
├── static/
│ ├── dist/ # Compiled frontend (generated)
│ │ ├── project-notes-frontend.es.js
│ │ └── project-notes-frontend.umd.js
│ └── theme.css # Material Darker theme
├── templates/
│ ├── index.html # Main page layout
│ ├── editor.html # Editor component
│ ├── file-tree.html # File tree sidebar
│ ├── search-results.html # Search results
│ └── new-note-prompt.html # New note modal
├── notes/ # Note storage directory
│ └── *.md # Markdown files with YAML front matter
├── go.mod # Go dependencies
├── go.sum
└── CLAUDE.md # This file
```
### Key Files to Edit
**Backend Development**:
- `cmd/server/main.go` - Server initialization and routing
- `internal/api/handler.go` - API endpoints and request handling
- `internal/indexer/indexer.go` - Search and indexing logic
- `internal/watcher/watcher.go` - Filesystem monitoring
**Frontend Development**:
- `frontend/src/editor.js` - CodeMirror editor, preview, slash commands
- `frontend/src/file-tree.js` - File tree interactions and drag-and-drop
- `frontend/src/ui.js` - UI utilities (sidebar toggle)
- `static/theme.css` - Styling and theming
- `templates/*.html` - HTML templates (Go template syntax)
**Configuration**:
- `frontend/vite.config.js` - Frontend build configuration
- `frontend/package.json` - NPM dependencies and scripts
- `go.mod` - Go dependencies
### Important Notes
1. **Frontend builds are required**: The application will not work without compiled JavaScript in `static/dist/`
2. **No hot reload for frontend**: Changes to `frontend/src/` require running `npm run build` and refreshing the browser
3. **Backend changes**: Require restarting the Go server (`go run ./cmd/server`)
4. **Template changes**: Require restarting the Go server (templates are pre-parsed at startup)
5. **CSS changes**: Only require browser refresh (loaded via `<link>` tag)
6. **Note changes**: Automatically detected by filesystem watcher, trigger re-indexing

124
GEMINI.md Normal file
View File

@ -0,0 +1,124 @@
# Project Notes
A lightweight, web-based Markdown note-taking application with a Go backend and a minimalist frontend built with htmx. It allows users to create, edit, delete, and search Markdown notes, with automatic front matter management and a live Markdown preview.
## Features
* **File-based Notes:** All notes are stored as plain Markdown files (`.md`) on the filesystem.
* **Tag Indexing:** Notes are indexed by tags specified in their YAML front matter, enabling quick search.
* **Live Markdown Preview:** A side-by-side editor and live preview pane for a better writing experience.
* **Automatic Front Matter:** Automatically generates and updates `title`, `date` (creation), `last_modified`, and `tags` in YAML front matter.
* **Slash Commands:** Insert common Markdown elements and dynamic content (like current date) using `/` commands in the editor.
* **Dynamic File Tree:** An automatically updating file tree in the sidebar to navigate notes.
* **Lightweight Frontend:** Built with htmx for dynamic interactions, minimizing JavaScript complexity.
* **Hierarchical Organization:** Organize notes in folders with drag-and-drop file management.
* **Rich Search:** Search by keywords, tags (`tag:projet`), title (`title:meeting`), or path (`path:backend`).
* **Go Backend:** A fast and efficient Go server handles file operations, indexing, and serving the frontend.
## Technologies Used
* **Backend:** Go
* `net/http`: Standard library for the web server.
* `github.com/fsnotify/fsnotify`: For watching file system changes and re-indexing.
* `gopkg.in/yaml.v3`: For parsing and marshaling YAML front matter.
* **Frontend:** HTML, CSS, JavaScript
* [htmx](https://htmx.org/): For dynamic UI interactions without writing much JavaScript.
* [marked.js](https://marked.js.org/): For client-side Markdown parsing in the preview.
* [DOMPurify](https://dompurpurify.com/): For sanitizing HTML output from Markdown to prevent XSS vulnerabilities.
* [Highlight.js](https://highlightjs.org/): For syntax highlighting in code blocks.
* Custom CSS theme with dark mode inspired by VS Code and GitHub Dark.
### Frontend Build Process
The frontend assets (JavaScript, CSS) are built and optimized using [Vite](https://vitejs.dev/). When changes are made to the frontend source code (e.g., in `frontend/src/`), the `npm run build` command must be executed from the `frontend/` directory. This command compiles, bundles, and minifies the source files into static assets (located in `static/dist/`) that the Go backend serves to the browser. This step is crucial to ensure that the latest frontend changes are reflected in the application.
## Getting Started
### Prerequisites
* [Go](https://go.dev/doc/install) (version 1.22 or higher recommended)
### Installation
1. **Clone the repository:**
```bash
git clone https://github.com/mathieu/project-notes.git
cd project-notes
```
2. **Download Go modules:**
```bash
go mod tidy
```
### Running the Application
To start the Go backend server:
```bash
go run ./cmd/server
```
The application will be accessible in your web browser at `http://localhost:8080`.
## Usage
### Creating a New Note
1. Click the "✨ Nouvelle note" button in the header.
2. Enter a filename (e.g., `my-new-note.md`) in the modal dialog.
3. Click "Créer / Ouvrir" - if the note exists, it will be opened; otherwise, a new note will be created.
4. An editor will appear with pre-filled YAML front matter (title, creation date, last modified date, and a "default" tag).
### Editing a Note
1. Click on a note in the "Notes" file tree in the sidebar.
2. The note's content will load into the editor.
3. Make your changes in the left pane (textarea). The right pane will show a live preview.
4. Click the "Enregistrer" button or use **Ctrl/Cmd+S** to save your changes. The `last_modified` date in the front matter will be updated automatically.
### Searching Notes
The search supports multiple query formats:
1. **General search:** Type keywords to search across title, tags, path, and content.
2. **Tag filter:** Use `tag:projet` to filter by specific tags.
3. **Title filter:** Use `title:meeting` to search within note titles.
4. **Path filter:** Use `path:backend` to search by file path.
5. **Quoted phrases:** Use `"exact phrase"` to search for exact matches.
Results are scored and ranked by relevance (title matches score highest).
### Using Slash Commands
1. While editing a note, type `/` at the start of a line in the textarea.
2. A command palette will appear with available commands.
3. Type to filter commands (e.g., `/h1`, `/date`, `/table`).
4. Use `ArrowUp`/`ArrowDown` to navigate and `Enter` or `Tab` to select a command.
5. The corresponding Markdown snippet will be inserted at your cursor position.
**Available commands:** h1, h2, h3, list, date, link, bold, italic, code, codeblock, quote, hr, table
### Organizing Notes in Folders
1. Click the "📁 Nouveau dossier" button in the sidebar.
2. Enter a folder path (e.g., `projets` or `projets/backend`).
3. The folder will be created and appear in the file tree.
4. Drag and drop notes between folders to reorganize them.
### Deleting a Note
1. Load the note you wish to delete into the editor.
2. Click the "Supprimer" button.
3. Confirm the deletion when prompted. The note will be removed from the filesystem and the file tree will update automatically.
## Server Configuration
The server accepts the following command-line flags:
- `-addr :PORT` - Change server address (default: `:8080`)
- `-notes-dir PATH` - Change notes directory (default: `./notes`)
Example:
```bash
go run ./cmd/server -addr :3000 -notes-dir ~/my-notes
```

93
PROJET.md Normal file
View File

@ -0,0 +1,93 @@
# Plan de Développement : Éditeur Markdown HTTP(S)
Ce document détaille le plan de développement pour un éditeur Markdown web, avec un backend en Go et un frontend JavaScript simple, intégrant des fonctionnalités WYSIWYG, des commandes slash et une recherche par tags sans base de données.
## 1. Objectifs Principaux
* **Éditeur Markdown :** Rapide, simple, avec une notion de WYSIWYG.
* **Commandes Slash (`/`) :** Permettre l'utilisation de raccourcis Markdown ou d'autres actions (ex: ajouter la date, des liens).
* **Stockage des Notes :** Fichiers Markdown purs (`.md`).
* **Recherche par Tags :** Possibilité de rechercher des notes par tags, sans utiliser de base de données.
* **Architecture :** Application web HTTP(S) avec backend Go et frontend JavaScript.
## 2. Architecture et Technologies Choisies
### Backend (Go)
* **Langage :** Go
* **Serveur Web :** `net/http` (bibliothèque standard de Go)
* **Rôles :**
* Servir les fichiers statiques du frontend (HTML, CSS, JavaScript).
* **Scanner les fichiers `.md` au démarrage pour construire et maintenir un index des tags en mémoire.**
* **Exposer une API (ex: `GET /api/search`) pour permettre la recherche dans cet index.**
* (À terme) Gérer la lecture/écriture des fichiers Markdown.
### Frontend (JavaScript)
* **Langage :** JavaScript (ES6+ "vanilla")
* **Structure :** HTML5, CSS3
* **Éditeur Markdown :** [Milkdown](https://milkdown.dev/)
* **Pourquoi Milkdown ?** Éditeur "headless" basé sur Prosemirror et Remark, léger, extensible, supporte nativement les commandes slash (`/`) et offre une expérience WYSIWYG moderne.
* **Style (CSS) :** [Pico.css](https://picocss.com/)
* **Pourquoi Pico.css ?** Micro-framework CSS minimaliste qui fournit un style propre et moderne aux éléments HTML de base sans configuration complexe.
## 3. Détail du Plan par Phase
### Phase 1 : Mise en place du Backend Go
1. Créer la structure de projet Go.
2. Mettre en place un serveur HTTP simple utilisant `net/http`.
3. Configurer le serveur pour servir les fichiers statiques depuis un répertoire `public/` (qui contiendra le frontend).
4. **Implémenter la logique de scan des fichiers `.md` :**
* Au démarrage du serveur, parcourir un répertoire désigné (ex: `notes/`).
* Pour chaque fichier `.md`, lire le "Front Matter" YAML en début de fichier.
* Extraire les `tags` et autres métadonnées.
* Construire un index en mémoire (ex: `map[string][]string` où la clé est le tag et la valeur est une liste de chemins de fichiers).
5. **Créer une API de recherche :**
* Définir une route `GET /api/search?tag=votre_tag`.
* Cette route interrogera l'index en mémoire et renverra la liste des fichiers correspondants (ex: leurs noms ou chemins relatifs).
### Phase 2 : Développement du Frontend
1. Créer le répertoire `public/` pour les fichiers frontend.
2. Créer le fichier `public/index.html` avec la structure de base.
3. Inclure Pico.css via CDN pour le style général.
4. Inclure Milkdown et ses dépendances (via CDN ou modules ES) dans `index.html`.
5. Créer un fichier `public/app.js` pour la logique JavaScript.
6. Dans `app.js`, initialiser l'éditeur Milkdown dans un élément `div` de `index.html`.
7. **Ajouter les éléments d'interface pour la recherche :**
* Un champ de saisie pour les tags.
* Un bouton de recherche ou une recherche dynamique.
* Une zone pour afficher les résultats de la recherche (liste de liens vers les notes).
### Phase 3 : Implémentation des Fonctionnalités Clés
1. **Configuration des Commandes Slash (`/`) dans Milkdown :**
* Utiliser le plugin "slash" de Milkdown.
* Définir des commandes de base (ex: `/h1` pour titre 1, `/list` pour liste).
* **Implémenter des commandes personnalisées :**
* `/date` : Insère la date actuelle.
* `/lien` : Insère un modèle de lien Markdown (ex: `[texte du lien](url)`).
2. **Intégration de la Recherche :**
* Lorsque l'utilisateur saisit un tag et lance la recherche dans le frontend, `app.js` effectue une requête `fetch` vers `GET /api/search?tag=...`.
* Afficher les résultats de l'API dans la zone dédiée du frontend.
* Permettre de cliquer sur un résultat pour charger le contenu du fichier Markdown correspondant dans l'éditeur (nécessitera une nouvelle API backend pour `GET /api/notes/{filename}`).
3. **Gestion des Fichiers Markdown :**
* (Backend) Créer une API `GET /api/notes/{filename}` pour lire et renvoyer le contenu d'un fichier Markdown spécifique.
* (Backend) Créer une API `POST /api/notes/{filename}` pour sauvegarder le contenu de l'éditeur dans un fichier Markdown.
## 4. Approche de Stockage des Tags (Sans BDD)
* **Format :** YAML Front Matter en haut de chaque fichier `.md`.
* **Exemple :**
```yaml
---
title: Mon Titre
tags: [tag1, tag2, autre-tag]
date: 2025-11-08
---
```
* **Indexation :** Le backend Go lit ce bloc au démarrage et construit un index en mémoire pour des recherches rapides.
* **Mise à jour de l'index :** Pour une solution plus robuste, un "watcher" de fichiers (`fsnotify`) pourra être ajouté pour mettre à jour l'index dynamiquement lors des modifications de fichiers.
Ce plan fournit une feuille de route claire pour le développement de votre éditeur Markdown.

125
README.md Normal file
View File

@ -0,0 +1,125 @@
# Project Notes
A lightweight, web-based Markdown note-taking application with a Go backend and a minimalist frontend built with htmx. It allows users to create, edit, delete, and search Markdown notes, with automatic front matter management and a live Markdown preview.
## Features
* **File-based Notes:** All notes are stored as plain Markdown files (`.md`) on the filesystem.
* **Tag Indexing:** Notes are indexed by tags specified in their YAML front matter, enabling quick search.
* **Live Markdown Preview:** A side-by-side editor and live preview pane for a better writing experience.
* **Automatic Front Matter:** Automatically generates and updates `title`, `date` (creation), `last_modified`, and `tags` in YAML front matter.
* **Slash Commands:** Insert common Markdown elements and dynamic content (like current date) using `/` commands in the editor.
* **Dynamic File Tree:** An automatically updating file tree in the sidebar to navigate notes.
* **Lightweight Frontend:** Built with htmx for dynamic interactions, minimizing JavaScript complexity.
* **Hierarchical Organization:** Organize notes in folders with drag-and-drop file management.
* **Rich Search:** Search by keywords, tags (`tag:projet`), title (`title:meeting`), or path (`path:backend`).
* **Go Backend:** A fast and efficient Go server handles file operations, indexing, and serving the frontend.
## Technologies Used
* **Backend:** Go
* `net/http`: Standard library for the web server.
* `github.com/fsnotify/fsnotify`: For watching file system changes and re-indexing.
* `gopkg.in/yaml.v3`: For parsing and marshaling YAML front matter.
* **Frontend:** HTML, CSS, JavaScript
* [htmx](https://htmx.org/): For dynamic UI interactions without writing much JavaScript.
* [CodeMirror 6](https://codemirror.net/6/): For the robust Markdown editor.
* [marked.js](https://marked.js.org/): For client-side Markdown parsing in the preview.
* [DOMPurify](https://dompurpurify.com/): For sanitizing HTML output from Markdown to prevent XSS vulnerabilities.
* [Highlight.js](https://highlightjs.org/): For syntax highlighting in code blocks.
* Custom CSS theme with dark mode inspired by VS Code and GitHub Dark.
## Getting Started
### Prerequisites
* [Go](https://go.dev/doc/install) (version 1.22 or higher recommended)
### Installation
1. **Clone the repository:**
```bash
git clone https://github.com/mathieu/project-notes.git
cd project-notes
```
2. **Download Go modules:**
```bash
go mod tidy
```
### Frontend Build Process
The frontend assets (JavaScript, CSS) are built and optimized using [Vite](https://vitejs.dev/). When changes are made to the frontend source code (e.g., in `frontend/src/`), the `npm run build` command must be executed from the `frontend/` directory. This command compiles, bundles, and minifies the source files into static assets (located in `static/dist/`) that the Go backend serves to the browser. This step is crucial to ensure that the latest frontend changes are reflected in the application.
### Running the Application
To start the Go backend server:
```bash
go run ./cmd/server
```
The application will be accessible in your web browser at `http://localhost:8080`.
## Usage
### Creating a New Note
1. Click the "✨ Nouvelle note" button in the header.
2. Enter a filename (e.g., `my-new-note.md`) in the modal dialog.
3. Click "Créer / Ouvrir" - if the note exists, it will be opened; otherwise, a new note will be created.
4. An editor will appear with pre-filled YAML front matter (title, creation date, last modified date, and a "default" tag).
### Editing a Note
1. Click on a note in the "Notes" file tree in the sidebar.
2. The note's content will load into the editor.
3. Make your changes in the left pane (textarea). The right pane will show a live preview.
4. Click the "Enregistrer" button or use **Ctrl/Cmd+S** to save your changes. The `last_modified` date in the front matter will be updated automatically.
### Searching Notes
The search supports multiple query formats:
1. **General search:** Type keywords to search across title, tags, path, and content.
2. **Tag filter:** Use `tag:projet` to filter by specific tags.
3. **Title filter:** Use `title:meeting` to search within note titles.
4. **Path filter:** Use `path:backend` to search by file path.
5. **Quoted phrases:** Use `"exact phrase"` to search for exact matches.
Results are scored and ranked by relevance (title matches score highest).
### Using Slash Commands
1. While editing a note, type `/` at the start of a line in the textarea.
2. A command palette will appear with available commands.
3. Type to filter commands (e.g., `/h1`, `/date`, `/table`).
4. Use `ArrowUp`/`ArrowDown` to navigate and `Enter` or `Tab` to select a command.
5. The corresponding Markdown snippet will be inserted at your cursor position.
**Available commands:** h1, h2, h3, list, date, link, bold, italic, code, codeblock, quote, hr, table
### Organizing Notes in Folders
1. Click the "📁 Nouveau dossier" button in the sidebar.
2. Enter a folder path (e.g., `projets` or `projets/backend`).
3. The folder will be created and appear in the file tree.
4. Drag and drop notes between folders to reorganize them.
### Deleting a Note
1. Load the note you wish to delete into the editor.
2. Click the "Supprimer" button.
3. Confirm the deletion when prompted. The note will be removed from the filesystem and the file tree will update automatically.
## Server Configuration
The server accepts the following command-line flags:
- `-addr :PORT` - Change server address (default: `:8080`)
- `-notes-dir PATH` - Change notes directory (default: `./notes`)
Example:
```bash
go run ./cmd/server -addr :3000 -notes-dir ~/my-notes
```

112
cmd/server/main.go Normal file
View File

@ -0,0 +1,112 @@
package main
import (
"context"
"errors"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/mathieu/project-notes/internal/api"
"github.com/mathieu/project-notes/internal/indexer"
"github.com/mathieu/project-notes/internal/watcher"
)
func main() {
addr := flag.String("addr", ":8080", "Adresse d ecoute HTTP")
notesDir := flag.String("notes-dir", "./notes", "Repertoire contenant les notes Markdown")
flag.Parse()
logger := log.New(os.Stdout, "[server] ", log.LstdFlags)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
if err := ensureDir(*notesDir); err != nil {
logger.Fatalf("repertoire notes invalide: %v", err)
}
idx := indexer.New()
if err := idx.Load(*notesDir); err != nil {
logger.Fatalf("echec de l indexation initiale: %v", err)
}
w, err := watcher.Start(ctx, *notesDir, idx, logger)
if err != nil {
logger.Fatalf("echec du watcher: %v", err)
}
defer w.Close()
// Pre-parse templates
templates, err := template.ParseGlob("templates/*.html")
if err != nil {
logger.Fatalf("echec de l analyse des templates: %v", err)
}
mux := http.NewServeMux()
// Servir les fichiers statiques
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
if err := templates.ExecuteTemplate(w, "index.html", nil); err != nil {
logger.Printf("erreur d execution du template index: %v", err)
http.Error(w, "erreur interne", http.StatusInternalServerError)
}
})
apiHandler := api.NewHandler(*notesDir, idx, templates, logger)
mux.Handle("/api/search", apiHandler)
mux.Handle("/api/folders/create", apiHandler)
mux.Handle("/api/files/move", apiHandler)
mux.Handle("/api/home", apiHandler)
mux.Handle("/api/notes/", apiHandler)
mux.Handle("/api/tree", apiHandler)
srv := &http.Server{
Addr: *addr,
Handler: mux,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
logger.Printf("demarrage du serveur sur %s", *addr)
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
logger.Printf("erreur durant l arret du serveur: %v", err)
}
}()
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Fatalf("arret inattendu du serveur: %v", err)
}
}
func ensureDir(path string) error {
info, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("le chemin %s n existe pas", path)
}
return err
}
if !info.IsDir() {
return fmt.Errorf("%s n est pas un repertoire", path)
}
return nil
}

1
frontend/node_modules/.bin/esbuild generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esbuild/bin/esbuild

1
frontend/node_modules/.bin/nanoid generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nanoid/bin/nanoid.cjs

1
frontend/node_modules/.bin/rollup generated vendored Symbolic link
View File

@ -0,0 +1 @@
../rollup/dist/bin/rollup

1
frontend/node_modules/.bin/vite generated vendored Symbolic link
View File

@ -0,0 +1 @@
../vite/bin/vite.js

742
frontend/node_modules/.package-lock.json generated vendored Normal file
View File

@ -0,0 +1,742 @@
{
"name": "frontend",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"node_modules/@codemirror/autocomplete": {
"version": "6.19.1",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.19.1.tgz",
"integrity": "sha512-q6NenYkEy2fn9+JyjIxMWcNjzTL/IhwqfzOut1/G3PrIFkrbl4AL7Wkse5tLrQUUyqGoAKU5+Pi5jnnXxH5HGw==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
}
},
"node_modules/@codemirror/basic-setup": {
"version": "0.20.0",
"resolved": "https://registry.npmjs.org/@codemirror/basic-setup/-/basic-setup-0.20.0.tgz",
"integrity": "sha512-W/ERKMLErWkrVLyP5I8Yh8PXl4r+WFNkdYVSzkXYPQv2RMPSkWpr2BgggiSJ8AHF/q3GuApncDD8I4BZz65fyg==",
"deprecated": "In version 6.0, this package has been renamed to just 'codemirror'",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^0.20.0",
"@codemirror/commands": "^0.20.0",
"@codemirror/language": "^0.20.0",
"@codemirror/lint": "^0.20.0",
"@codemirror/search": "^0.20.0",
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0"
}
},
"node_modules/@codemirror/basic-setup/node_modules/@codemirror/autocomplete": {
"version": "0.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-0.20.3.tgz",
"integrity": "sha512-lYB+NPGP+LEzAudkWhLfMxhTrxtLILGl938w+RcFrGdrIc54A+UgmCoz+McE3IYRFp4xyQcL4uFJwo+93YdgHw==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^0.20.0",
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0",
"@lezer/common": "^0.16.0"
}
},
"node_modules/@codemirror/basic-setup/node_modules/@codemirror/language": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-0.20.2.tgz",
"integrity": "sha512-WB3Bnuusw0xhVvhBocieYKwJm04SOk5bPoOEYksVHKHcGHFOaYaw+eZVxR4gIqMMcGzOIUil0FsCmFk8yrhHpw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0",
"@lezer/common": "^0.16.0",
"@lezer/highlight": "^0.16.0",
"@lezer/lr": "^0.16.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/basic-setup/node_modules/@codemirror/lint": {
"version": "0.20.3",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-0.20.3.tgz",
"integrity": "sha512-06xUScbbspZ8mKoODQCEx6hz1bjaq9m8W8DxdycWARMiiX1wMtfCh/MoHpaL7ws/KUMwlsFFfp2qhm32oaCvVA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.2",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/basic-setup/node_modules/@codemirror/state": {
"version": "0.20.1",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-0.20.1.tgz",
"integrity": "sha512-ms0tlV5A02OK0pFvTtSUGMLkoarzh1F8mr6jy1cD7ucSC2X/VLHtQCxfhdSEGqTYlQF2hoZtmLv+amqhdgbwjQ==",
"license": "MIT"
},
"node_modules/@codemirror/basic-setup/node_modules/@codemirror/view": {
"version": "0.20.7",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-0.20.7.tgz",
"integrity": "sha512-pqEPCb9QFTOtHgAH5XU/oVy9UR/Anj6r+tG5CRmkNVcqSKEPmBU05WtN/jxJCFZBXf6HumzWC9ydE4qstO3TxQ==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"style-mod": "^4.0.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@codemirror/basic-setup/node_modules/@lezer/common": {
"version": "0.16.1",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-0.16.1.tgz",
"integrity": "sha512-qPmG7YTZ6lATyTOAWf8vXE+iRrt1NJd4cm2nJHK+v7X9TsOF6+HtuU/ctaZy2RCrluxDb89hI6KWQ5LfQGQWuA==",
"license": "MIT"
},
"node_modules/@codemirror/basic-setup/node_modules/@lezer/highlight": {
"version": "0.16.0",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-0.16.0.tgz",
"integrity": "sha512-iE5f4flHlJ1g1clOStvXNLbORJoiW4Kytso6ubfYzHnaNo/eo5SKhxs4wv/rtvwZQeZrK3we8S9SyA7OGOoRKQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^0.16.0"
}
},
"node_modules/@codemirror/basic-setup/node_modules/@lezer/lr": {
"version": "0.16.3",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-0.16.3.tgz",
"integrity": "sha512-pau7um4eAw94BEuuShUIeQDTf3k4Wt6oIUOYxMmkZgDHdqtIcxWND4LRxi8nI9KuT4I1bXQv67BCapkxt7Ywqw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^0.16.0"
}
},
"node_modules/@codemirror/commands": {
"version": "0.20.0",
"resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-0.20.0.tgz",
"integrity": "sha512-v9L5NNVA+A9R6zaFvaTbxs30kc69F6BkOoiEbeFw4m4I0exmDEKBILN6mK+GksJtvTzGBxvhAPlVFTdQW8GB7Q==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^0.20.0",
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0",
"@lezer/common": "^0.16.0"
}
},
"node_modules/@codemirror/commands/node_modules/@codemirror/language": {
"version": "0.20.2",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-0.20.2.tgz",
"integrity": "sha512-WB3Bnuusw0xhVvhBocieYKwJm04SOk5bPoOEYksVHKHcGHFOaYaw+eZVxR4gIqMMcGzOIUil0FsCmFk8yrhHpw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0",
"@lezer/common": "^0.16.0",
"@lezer/highlight": "^0.16.0",
"@lezer/lr": "^0.16.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/commands/node_modules/@codemirror/state": {
"version": "0.20.1",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-0.20.1.tgz",
"integrity": "sha512-ms0tlV5A02OK0pFvTtSUGMLkoarzh1F8mr6jy1cD7ucSC2X/VLHtQCxfhdSEGqTYlQF2hoZtmLv+amqhdgbwjQ==",
"license": "MIT"
},
"node_modules/@codemirror/commands/node_modules/@codemirror/view": {
"version": "0.20.7",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-0.20.7.tgz",
"integrity": "sha512-pqEPCb9QFTOtHgAH5XU/oVy9UR/Anj6r+tG5CRmkNVcqSKEPmBU05WtN/jxJCFZBXf6HumzWC9ydE4qstO3TxQ==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"style-mod": "^4.0.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@codemirror/commands/node_modules/@lezer/common": {
"version": "0.16.1",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-0.16.1.tgz",
"integrity": "sha512-qPmG7YTZ6lATyTOAWf8vXE+iRrt1NJd4cm2nJHK+v7X9TsOF6+HtuU/ctaZy2RCrluxDb89hI6KWQ5LfQGQWuA==",
"license": "MIT"
},
"node_modules/@codemirror/commands/node_modules/@lezer/highlight": {
"version": "0.16.0",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-0.16.0.tgz",
"integrity": "sha512-iE5f4flHlJ1g1clOStvXNLbORJoiW4Kytso6ubfYzHnaNo/eo5SKhxs4wv/rtvwZQeZrK3we8S9SyA7OGOoRKQ==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^0.16.0"
}
},
"node_modules/@codemirror/commands/node_modules/@lezer/lr": {
"version": "0.16.3",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-0.16.3.tgz",
"integrity": "sha512-pau7um4eAw94BEuuShUIeQDTf3k4Wt6oIUOYxMmkZgDHdqtIcxWND4LRxi8nI9KuT4I1bXQv67BCapkxt7Ywqw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^0.16.0"
}
},
"node_modules/@codemirror/lang-css": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/@codemirror/lang-css/-/lang-css-6.3.1.tgz",
"integrity": "sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@lezer/common": "^1.0.2",
"@lezer/css": "^1.1.7"
}
},
"node_modules/@codemirror/lang-html": {
"version": "6.4.11",
"resolved": "https://registry.npmjs.org/@codemirror/lang-html/-/lang-html-6.4.11.tgz",
"integrity": "sha512-9NsXp7Nwp891pQchI7gPdTwBuSuT3K65NGTHWHNJ55HjYcHLllr0rbIZNdOzas9ztc1EUVBlHou85FFZS4BNnw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/lang-css": "^6.0.0",
"@codemirror/lang-javascript": "^6.0.0",
"@codemirror/language": "^6.4.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/css": "^1.1.0",
"@lezer/html": "^1.3.12"
}
},
"node_modules/@codemirror/lang-javascript": {
"version": "6.2.4",
"resolved": "https://registry.npmjs.org/@codemirror/lang-javascript/-/lang-javascript-6.2.4.tgz",
"integrity": "sha512-0WVmhp1QOqZ4Rt6GlVGwKJN3KW7Xh4H2q8ZZNGZaP6lRdxXJzmjm4FqvmOojVj6khWJHIb9sp7U/72W7xQgqAA==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.0.0",
"@codemirror/language": "^6.6.0",
"@codemirror/lint": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0",
"@lezer/javascript": "^1.0.0"
}
},
"node_modules/@codemirror/lang-markdown": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/@codemirror/lang-markdown/-/lang-markdown-6.5.0.tgz",
"integrity": "sha512-0K40bZ35jpHya6FriukbgaleaqzBLZfOh7HuzqbMxBXkbYMJDxfF39c23xOgxFezR+3G+tR2/Mup+Xk865OMvw==",
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^6.7.1",
"@codemirror/lang-html": "^6.0.0",
"@codemirror/language": "^6.3.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/common": "^1.2.1",
"@lezer/markdown": "^1.0.0"
}
},
"node_modules/@codemirror/language": {
"version": "6.11.3",
"resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.11.3.tgz",
"integrity": "sha512-9HBM2XnwDj7fnu0551HkGdrUrrqmYq/WC5iv6nbY2WdicXdGbhR/gfbZOH73Aqj4351alY1+aoG9rCNfiwS1RA==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.23.0",
"@lezer/common": "^1.1.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0",
"style-mod": "^4.0.0"
}
},
"node_modules/@codemirror/lint": {
"version": "6.9.2",
"resolved": "https://registry.npmjs.org/@codemirror/lint/-/lint-6.9.2.tgz",
"integrity": "sha512-sv3DylBiIyi+xKwRCJAAsBZZZWo82shJ/RTMymLabAdtbkV5cSKwWDeCgtUq3v8flTaXS2y1kKkICuRYtUswyQ==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.35.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/search": {
"version": "0.20.1",
"resolved": "https://registry.npmjs.org/@codemirror/search/-/search-0.20.1.tgz",
"integrity": "sha512-ROe6gRboQU5E4z6GAkNa2kxhXqsGNbeLEisbvzbOeB7nuDYXUZ70vGIgmqPu0tB+1M3F9yWk6W8k2vrFpJaD4Q==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0",
"crelt": "^1.0.5"
}
},
"node_modules/@codemirror/search/node_modules/@codemirror/state": {
"version": "0.20.1",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-0.20.1.tgz",
"integrity": "sha512-ms0tlV5A02OK0pFvTtSUGMLkoarzh1F8mr6jy1cD7ucSC2X/VLHtQCxfhdSEGqTYlQF2hoZtmLv+amqhdgbwjQ==",
"license": "MIT"
},
"node_modules/@codemirror/search/node_modules/@codemirror/view": {
"version": "0.20.7",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-0.20.7.tgz",
"integrity": "sha512-pqEPCb9QFTOtHgAH5XU/oVy9UR/Anj6r+tG5CRmkNVcqSKEPmBU05WtN/jxJCFZBXf6HumzWC9ydE4qstO3TxQ==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"style-mod": "^4.0.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@codemirror/state": {
"version": "6.5.2",
"resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.5.2.tgz",
"integrity": "sha512-FVqsPqtPWKVVL3dPSxy8wEF/ymIEuVzF1PK3VbUgrxXpJUSHQWWZz4JMToquRxnkw+36LTamCZG2iua2Ptq0fA==",
"license": "MIT",
"dependencies": {
"@marijn/find-cluster-break": "^1.0.0"
}
},
"node_modules/@codemirror/theme-one-dark": {
"version": "6.1.3",
"resolved": "https://registry.npmjs.org/@codemirror/theme-one-dark/-/theme-one-dark-6.1.3.tgz",
"integrity": "sha512-NzBdIvEJmx6fjeremiGp3t/okrLPYT0d9orIc7AFun8oZcRk58aejkqhv6spnz4MLAevrKNPMQYXEWMg4s+sKA==",
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.0.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@codemirror/view": {
"version": "6.38.6",
"resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.38.6.tgz",
"integrity": "sha512-qiS0z1bKs5WOvHIAC0Cybmv4AJSkAXgX5aD6Mqd2epSLlVJsQl8NG23jCVouIgkh4All/mrbdsf2UOLFnJw0tw==",
"license": "MIT",
"dependencies": {
"@codemirror/state": "^6.5.0",
"crelt": "^1.0.6",
"style-mod": "^4.1.0",
"w3c-keyname": "^2.2.4"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@lezer/common": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.3.0.tgz",
"integrity": "sha512-L9X8uHCYU310o99L3/MpJKYxPzXPOS7S0NmBaM7UO/x2Kb2WbmMLSkfvdr1KxRIFYOpbY0Jhn7CfLSUDzL8arQ==",
"license": "MIT"
},
"node_modules/@lezer/css": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@lezer/css/-/css-1.3.0.tgz",
"integrity": "sha512-pBL7hup88KbI7hXnZV3PQsn43DHy6TWyzuyk2AO9UyoXcDltvIdqWKE1dLL/45JVZ+YZkHe1WVHqO6wugZZWcw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/highlight": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz",
"integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.3.0"
}
},
"node_modules/@lezer/html": {
"version": "1.3.12",
"resolved": "https://registry.npmjs.org/@lezer/html/-/html-1.3.12.tgz",
"integrity": "sha512-RJ7eRWdaJe3bsiiLLHjCFT1JMk8m1YP9kaUbvu2rMLEoOnke9mcTVDyfOslsln0LtujdWespjJ39w6zo+RsQYw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.0.0",
"@lezer/lr": "^1.0.0"
}
},
"node_modules/@lezer/javascript": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/@lezer/javascript/-/javascript-1.5.4.tgz",
"integrity": "sha512-vvYx3MhWqeZtGPwDStM2dwgljd5smolYD2lR2UyFcHfxbBQebqx8yjmFmxtJ/E6nN6u1D9srOiVWm3Rb4tmcUA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.2.0",
"@lezer/highlight": "^1.1.3",
"@lezer/lr": "^1.3.0"
}
},
"node_modules/@lezer/lr": {
"version": "1.4.3",
"resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.3.tgz",
"integrity": "sha512-yenN5SqAxAPv/qMnpWW0AT7l+SxVrgG+u0tNsRQWqbrz66HIl8DnEbBObvy21J5K7+I1v7gsAnlE2VQ5yYVSeA==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0"
}
},
"node_modules/@lezer/markdown": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@lezer/markdown/-/markdown-1.6.0.tgz",
"integrity": "sha512-AXb98u3M6BEzTnreBnGtQaF7xFTiMA92Dsy5tqEjpacbjRxDSFdN4bKJo9uvU4cEEOS7D2B9MT7kvDgOEIzJSw==",
"license": "MIT",
"dependencies": {
"@lezer/common": "^1.0.0",
"@lezer/highlight": "^1.0.0"
}
},
"node_modules/@marijn/find-cluster-break": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz",
"integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==",
"license": "MIT"
},
"node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.53.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.53.1.tgz",
"integrity": "sha512-E/n8x2MSjAQgjj9IixO4UeEUeqXLtiA7pyoXCFYLuXpBA/t2hnbIdxHfA7kK9BFsYAoNU4st1rHYdldl8dTqGA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@rollup/rollup-linux-x64-musl": {
"version": "4.53.1",
"resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.53.1.tgz",
"integrity": "sha512-IhJ087PbLOQXCN6Ui/3FUkI9pWNZe/Z7rEIVOzMsOs1/HSAECCvSZ7PkIbkNqL/AZn6WbZvnoVZw/qwqYMo4/w==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
]
},
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
"integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==",
"dev": true,
"license": "MIT"
},
"node_modules/crelt": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz",
"integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==",
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.25.12",
"@esbuild/android-arm": "0.25.12",
"@esbuild/android-arm64": "0.25.12",
"@esbuild/android-x64": "0.25.12",
"@esbuild/darwin-arm64": "0.25.12",
"@esbuild/darwin-x64": "0.25.12",
"@esbuild/freebsd-arm64": "0.25.12",
"@esbuild/freebsd-x64": "0.25.12",
"@esbuild/linux-arm": "0.25.12",
"@esbuild/linux-arm64": "0.25.12",
"@esbuild/linux-ia32": "0.25.12",
"@esbuild/linux-loong64": "0.25.12",
"@esbuild/linux-mips64el": "0.25.12",
"@esbuild/linux-ppc64": "0.25.12",
"@esbuild/linux-riscv64": "0.25.12",
"@esbuild/linux-s390x": "0.25.12",
"@esbuild/linux-x64": "0.25.12",
"@esbuild/netbsd-arm64": "0.25.12",
"@esbuild/netbsd-x64": "0.25.12",
"@esbuild/openbsd-arm64": "0.25.12",
"@esbuild/openbsd-x64": "0.25.12",
"@esbuild/openharmony-arm64": "0.25.12",
"@esbuild/sunos-x64": "0.25.12",
"@esbuild/win32-arm64": "0.25.12",
"@esbuild/win32-ia32": "0.25.12",
"@esbuild/win32-x64": "0.25.12"
}
},
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
"integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12.0.0"
},
"peerDependencies": {
"picomatch": "^3 || ^4"
},
"peerDependenciesMeta": {
"picomatch": {
"optional": true
}
}
},
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
"integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"dev": true,
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/postcss": {
"version": "8.5.6",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz",
"integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==",
"dev": true,
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.11",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/rollup": {
"version": "4.53.1",
"resolved": "https://registry.npmjs.org/rollup/-/rollup-4.53.1.tgz",
"integrity": "sha512-n2I0V0lN3E9cxxMqBCT3opWOiQBzRN7UG60z/WDKqdX2zHUS/39lezBcsckZFsV6fUTSnfqI7kHf60jDAPGKug==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "1.0.8"
},
"bin": {
"rollup": "dist/bin/rollup"
},
"engines": {
"node": ">=18.0.0",
"npm": ">=8.0.0"
},
"optionalDependencies": {
"@rollup/rollup-android-arm-eabi": "4.53.1",
"@rollup/rollup-android-arm64": "4.53.1",
"@rollup/rollup-darwin-arm64": "4.53.1",
"@rollup/rollup-darwin-x64": "4.53.1",
"@rollup/rollup-freebsd-arm64": "4.53.1",
"@rollup/rollup-freebsd-x64": "4.53.1",
"@rollup/rollup-linux-arm-gnueabihf": "4.53.1",
"@rollup/rollup-linux-arm-musleabihf": "4.53.1",
"@rollup/rollup-linux-arm64-gnu": "4.53.1",
"@rollup/rollup-linux-arm64-musl": "4.53.1",
"@rollup/rollup-linux-loong64-gnu": "4.53.1",
"@rollup/rollup-linux-ppc64-gnu": "4.53.1",
"@rollup/rollup-linux-riscv64-gnu": "4.53.1",
"@rollup/rollup-linux-riscv64-musl": "4.53.1",
"@rollup/rollup-linux-s390x-gnu": "4.53.1",
"@rollup/rollup-linux-x64-gnu": "4.53.1",
"@rollup/rollup-linux-x64-musl": "4.53.1",
"@rollup/rollup-openharmony-arm64": "4.53.1",
"@rollup/rollup-win32-arm64-msvc": "4.53.1",
"@rollup/rollup-win32-ia32-msvc": "4.53.1",
"@rollup/rollup-win32-x64-gnu": "4.53.1",
"@rollup/rollup-win32-x64-msvc": "4.53.1",
"fsevents": "~2.3.2"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/style-mod": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz",
"integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==",
"license": "MIT"
},
"node_modules/tinyglobby": {
"version": "0.2.15",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz",
"integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"fdir": "^6.5.0",
"picomatch": "^4.0.3"
},
"engines": {
"node": ">=12.0.0"
},
"funding": {
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/vite": {
"version": "7.2.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.2.2.tgz",
"integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.5.0",
"picomatch": "^4.0.3",
"postcss": "^8.5.6",
"rollup": "^4.43.0",
"tinyglobby": "^0.2.15"
},
"bin": {
"vite": "bin/vite.js"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"funding": {
"url": "https://github.com/vitejs/vite?sponsor=1"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
},
"peerDependencies": {
"@types/node": "^20.19.0 || >=22.12.0",
"jiti": ">=1.21.0",
"less": "^4.0.0",
"lightningcss": "^1.21.0",
"sass": "^1.70.0",
"sass-embedded": "^1.70.0",
"stylus": ">=0.54.8",
"sugarss": "^5.0.0",
"terser": "^5.16.0",
"tsx": "^4.8.1",
"yaml": "^2.4.2"
},
"peerDependenciesMeta": {
"@types/node": {
"optional": true
},
"jiti": {
"optional": true
},
"less": {
"optional": true
},
"lightningcss": {
"optional": true
},
"sass": {
"optional": true
},
"sass-embedded": {
"optional": true
},
"stylus": {
"optional": true
},
"sugarss": {
"optional": true
},
"terser": {
"optional": true
},
"tsx": {
"optional": true
},
"yaml": {
"optional": true
}
}
},
"node_modules/w3c-keyname": {
"version": "2.2.8",
"resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz",
"integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==",
"license": "MIT"
}
}
}

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: dev
owner: codemirror
event_type: push

View File

@ -0,0 +1,628 @@
## 6.19.1 (2025-10-23)
### Bug fixes
Make sure a completion's info panel is associated with that completion in the accessibility tree.
## 6.19.0 (2025-09-26)
### New features
Completion sections may now set their rank to `dynamic` to indicate their order should be determined by the matching score of their best-matching option.
## 6.18.7 (2025-09-02)
### Bug fixes
Add a binding for Alt-i to trigger `startCompletion`, following VS Code's current default bindings.
Improve handling of nested fields in snippets.
## 6.18.6 (2025-02-12)
### Bug fixes
Fix an issue where the closing character for double-angle quotation marks and full-width brackets was computed incorrectly.
## 6.18.5 (2025-02-11)
### Bug fixes
Fix an issue where clicking on the scrollbar for the completion list could move focus out of the editor.
## 6.18.4 (2024-12-17)
### Bug fixes
Align the behavior of snippet completions with text completions in that they overwrite the selected text.
## 6.18.3 (2024-11-13)
### Bug fixes
Backspacing to the start of the completed range will no longer close the completion tooltip when it was triggered implicitly by typing the character before that range.
## 6.18.2 (2024-10-30)
### Bug fixes
Don't immediately show synchronously updated completions when there are some sources that still need to return.
## 6.18.1 (2024-09-14)
### Bug fixes
Fix an issue where `insertCompletionText` would get confused about the length of the inserted text when it contained CRLF line breaks, and create an invalid selection.
Add Alt-Backtick as additional binding on macOS, where IME can take over Ctrl-Space.
## 6.18.0 (2024-08-05)
### Bug fixes
Style the info element so that newlines are preserved, to make it easier to display multi-line info from a string source.
### New features
When registering an `abort` handler for a completion query, you can now use the `onDocChange` option to indicate that your query should be aborted as soon as the document changes while it is running.
## 6.17.0 (2024-07-03)
### Bug fixes
Fix an issue where completions weren't properly reset when starting a new completion through `activateOnCompletion`.
### New features
`CompletionContext` objects now have a `view` property that holds the editor view when the query context has a view available.
## 6.16.3 (2024-06-19)
### Bug fixes
Avoid adding an `aria-autocomplete` attribute to the editor when there are no active sources active.
## 6.16.2 (2024-05-31)
### Bug fixes
Allow backslash-escaped closing braces inside snippet field names/content.
## 6.16.1 (2024-05-29)
### Bug fixes
Fix a bug where multiple backslashes before a brace in a snippet were all removed.
## 6.16.0 (2024-04-12)
### New features
The new `activateOnCompletion` option allows autocompletion to be configured to chain completion activation for some types of completions.
## 6.15.0 (2024-03-13)
### New features
The new `filterStrict` option can be used to turn off fuzzy matching of completions.
## 6.14.0 (2024-03-10)
### New features
Completion results can now define a `map` method that can be used to adjust position-dependent information for document changes.
## 6.13.0 (2024-02-29)
### New features
Completions may now provide 'commit characters' that, when typed, commit the completion before inserting the character.
## 6.12.0 (2024-01-12)
### Bug fixes
Make sure snippet completions also set `userEvent` to `input.complete`.
Fix a crash when the editor lost focus during an update and autocompletion was active.
Fix a crash when using a snippet that has only one field, but multiple instances of that field.
### New features
The new `activateOnTypingDelay` option allows control over the debounce time before the completions are queried when the user types.
## 6.11.1 (2023-11-27)
### Bug fixes
Fix a bug that caused typing over closed brackets after pressing enter to still not work in many situations.
## 6.11.0 (2023-11-09)
### Bug fixes
Fix an issue that would prevent typing over closed brackets after starting a new line with enter.
### New features
Additional elements rendered in completion options with `addToOptions` are now given access to the editor view.
## 6.10.2 (2023-10-13)
### Bug fixes
Fix a bug that caused `updateSyncTime` to always delay the initial population of the tooltip.
## 6.10.1 (2023-10-11)
### Bug fixes
Fix a bug where picking a selection with the mouse could use the wrong completion if the completion list was updated after being opened.
## 6.10.0 (2023-10-11)
### New features
The new autocompletion configuration option `updateSyncTime` allows control over how long fast sources are held back waiting for slower completion sources.
## 6.9.2 (2023-10-06)
### Bug fixes
Fix a bug in `completeAnyWord` that could cause it to generate invalid regular expressions and crash.
## 6.9.1 (2023-09-14)
### Bug fixes
Make sure the cursor is scrolled into view after inserting completion text.
Make sure scrolling completions into view doesn't get confused when the tooltip is scaled.
## 6.9.0 (2023-07-18)
### New features
Completions may now provide a `displayLabel` property that overrides the way they are displayed in the completion list.
## 6.8.1 (2023-06-23)
### Bug fixes
`acceptCompletion` now returns false (allowing other handlers to take effect) when the completion popup is open but disabled.
## 6.8.0 (2023-06-12)
### New features
The result of `Completion.info` may now include a `destroy` method that will be called when the tooltip is removed.
## 6.7.1 (2023-05-13)
### Bug fixes
Fix a bug that cause incorrect ordering of completions when some results covered input text and others didn't.
## 6.7.0 (2023-05-11)
### New features
The new `hasNextSnippetField` and `hasPrevSnippetField` functions can be used to figure out if the snippet-field-motion commands apply to a given state.
## 6.6.1 (2023-05-03)
### Bug fixes
Fix a bug that made the editor use the completion's original position, rather than its current position, when changes happened in the document while a result was active.
## 6.6.0 (2023-04-27)
### Bug fixes
Fix a bug in `insertCompletionText` that caused it to replace the wrong range when a result set's `to` fell after the cursor.
### New features
Functions returned by `snippet` can now be called without a completion object.
## 6.5.1 (2023-04-13)
### Bug fixes
Keep completions open when interaction with an info tooltip moves focus out of the editor.
## 6.5.0 (2023-04-13)
### Bug fixes
When `closeBrackets` skips a bracket, it now generates a change that overwrites the bracket.
Replace the entire selected range when picking a completion with a non-cursor selection active.
### New features
Completions can now provide a `section` field that is used to group them into sections.
The new `positionInfo` option can be used to provide custom logic for positioning the info tooltips.
## 6.4.2 (2023-02-17)
### Bug fixes
Fix a bug where the apply method created by `snippet` didn't add a `pickedCompletion` annotation to the transactions it created.
## 6.4.1 (2023-02-14)
### Bug fixes
Don't consider node names in trees that aren't the same language as the one at the completion position in `ifIn` and `ifNotIn`.
Make sure completions that exactly match the input get a higher score than those that don't (so that even if the latter has a score boost, it ends up lower in the list).
## 6.4.0 (2022-12-14)
### Bug fixes
Fix an issue where the extension would sometimes try to draw a disabled dialog at an outdated position, leading to plugin crashes.
### New features
A `tooltipClass` option to autocompletion can now be used to add additional CSS classes to the completion tooltip.
## 6.3.4 (2022-11-24)
### Bug fixes
Fix an issue where completion lists could end up being higher than the tooltip they were in.
## 6.3.3 (2022-11-18)
### Bug fixes
Set an explicit `box-sizing` style on completion icons so CSS resets don't mess them up.
Allow closing braces in templates to be escaped with a backslash.
## 6.3.2 (2022-11-15)
### Bug fixes
Fix a regression that could cause the completion dialog to stick around when it should be hidden.
## 6.3.1 (2022-11-14)
### Bug fixes
Fix a regression where transactions for picking a completion (without custom `apply` method) no longer had the `pickedCompletion` annotation.
Reduce flickering for completion sources without `validFor` info by temporarily showing a disabled tooltip while the completion updates.
Make sure completion info tooltips are kept within the space provided by the `tooltipSpace` option.
## 6.3.0 (2022-09-22)
### New features
Close bracket configuration now supports a `stringPrefixes` property that can be used to allow autoclosing of prefixed strings.
## 6.2.0 (2022-09-13)
### New features
Autocompletion now takes an `interactionDelay` option that can be used to control the delay between the time where completion opens and the time where commands like `acceptCompletion` affect it.
## 6.1.1 (2022-09-08)
### Bug fixes
Fix a bug that prevented transactions produced by `deleteBracketPair` from being marked as deletion user events.
Improve positioning of completion info tooltips so they are less likely to stick out of the screen on small displays.
## 6.1.0 (2022-07-19)
### New features
You can now provide a `compareCompletions` option to autocompletion to influence the way completions with the same match score are sorted.
The `selectOnOpen` option to autocompletion can be used to require explicitly selecting a completion option before `acceptCompletion` does anything.
## 6.0.4 (2022-07-07)
### Bug fixes
Remove a leftover `console.log` in bracket closing code.
## 6.0.3 (2022-07-04)
### Bug fixes
Fix a bug that caused `closeBrackets` to not close quotes when at the end of a syntactic construct that starts with a similar quote.
## 6.0.2 (2022-06-15)
### Bug fixes
Declare package dependencies as peer dependencies as an attempt to avoid duplicated package issues.
## 6.0.1 (2022-06-09)
### Bug fixes
Support escaping `${` or `#{` in snippets.
## 6.0.0 (2022-06-08)
### Bug fixes
Scroll the cursor into view when inserting a snippet.
## 0.20.3 (2022-05-30)
### Bug fixes
Add an aria-label to the completion listbox.
Fix a regression that caused transactions generated for completion to not have a `userEvent` annotation.
## 0.20.2 (2022-05-24)
### New features
The package now exports an `insertCompletionText` helper that implements the default behavior for applying a completion.
## 0.20.1 (2022-05-16)
### New features
The new `closeOnBlur` option determines whether the completion tooltip is closed when the editor loses focus.
`CompletionResult` objects with `filter: false` may now have a `getMatch` property that determines the matched range in the options.
## 0.20.0 (2022-04-20)
### Breaking changes
`CompletionResult.span` has been renamed to `validFor`, and may now hold a function as well as a regular expression.
### Bug fixes
Remove code that dropped any options beyond the 300th one when matching and sorting option lists.
Completion will now apply to all cursors when there are multiple cursors.
### New features
`CompletionResult.update` can now be used to implement quick autocompletion updates in a synchronous way.
The @codemirror/closebrackets package was merged into this one.
## 0.19.15 (2022-03-23)
### New features
The `selectedCompletionIndex` function tells you the position of the currently selected completion.
The new `setSelectionCompletion` function creates a state effect that moves the selected completion to a given index.
A completion's `info` method may now return null to indicate that no further info is available.
## 0.19.14 (2022-03-10)
### Bug fixes
Make the ARIA attributes added to the editor during autocompletion spec-compliant.
## 0.19.13 (2022-02-18)
### Bug fixes
Fix an issue where the completion tooltip stayed open if it was explicitly opened and the user backspaced past its start.
Stop snippet filling when a change happens across one of the snippet fields' boundaries.
## 0.19.12 (2022-01-11)
### Bug fixes
Fix completion navigation with PageUp/Down when the completion tooltip isn't part of the view DOM.
## 0.19.11 (2022-01-11)
### Bug fixes
Fix a bug that caused page up/down to only move the selection by two options in the completion tooltip.
## 0.19.10 (2022-01-05)
### Bug fixes
Make sure the info tooltip is hidden when the selected option is scrolled out of view.
Fix a bug in the completion ranking that would sometimes give options that match the input by word start chars higher scores than appropriate.
Options are now sorted (ascending) by length when their match score is otherwise identical.
## 0.19.9 (2021-11-26)
### Bug fixes
Fix an issue where info tooltips would be visible in an inappropriate position when there was no room to place them properly.
## 0.19.8 (2021-11-17)
### Bug fixes
Give the completion tooltip a minimal width, and show ellipsis when completions overflow the tooltip width.
### New features
`autocompletion` now accepts an `aboveCursor` option to make the completion tooltip show up above the cursor.
## 0.19.7 (2021-11-16)
### Bug fixes
Make option deduplication less aggressive, so that options with different `type` or `apply` fields don't get merged.
## 0.19.6 (2021-11-12)
### Bug fixes
Fix an issue where parsing a snippet with a field that was labeled only by a number crashed.
## 0.19.5 (2021-11-09)
### Bug fixes
Make sure info tooltips don't stick out of the bottom of the page.
### New features
The package exports a new function `selectedCompletion`, which can be used to find out which completion is currently selected.
Transactions created by picking a completion now have an annotation (`pickedCompletion`) holding the original completion.
## 0.19.4 (2021-10-24)
### Bug fixes
Don't rely on the platform's highlight colors for the active completion, since those are inconsistent and may not be appropriate for the theme.
Fix incorrect match underline for some kinds of matched completions.
## 0.19.3 (2021-08-31)
### Bug fixes
Improve the sorting of completions by using `localeCompare`.
Fix reading of autocompletions in NVDA screen reader.
### New features
The new `icons` option can be used to turn off icons in the completion list.
The `optionClass` option can now be used to add CSS classes to the options in the completion list.
It is now possible to inject additional content into rendered completion options with the `addToOptions` configuration option.
## 0.19.2 (2021-08-25)
### Bug fixes
Fix an issue where `completeAnyWord` would return results when there was no query and `explicit` was false.
## 0.19.1 (2021-08-11)
### Bug fixes
Fix incorrect versions for @lezer dependencies.
## 0.19.0 (2021-08-11)
### Breaking changes
Update dependencies to 0.19.0
## 0.18.8 (2021-06-30)
### New features
Add an `ifIn` helper function that constrains a completion source to only fire when in a given syntax node. Add support for unfiltered completions
A completion result can now set a `filter: false` property to disable filtering and sorting of completions, when it already did so itself.
## 0.18.7 (2021-06-14)
### Bug fixes
Don't treat continued completions when typing after an explicit completion as explicit.
## 0.18.6 (2021-06-03)
### Bug fixes
Adding or reconfiguring completion sources will now cause them to be activated right away if a completion was active.
### New features
You can now specify multiple types in `Completion.type` by separating them by spaces. Small doc comment tweak for Completion.type
## 0.18.5 (2021-04-23)
### Bug fixes
Fix a regression where snippet field selection didn't work with @codemirror/state 0.18.6.
Fix a bug where snippet fields with different position numbers were inappropriately merged.
## 0.18.4 (2021-04-20)
### Bug fixes
Fix a crash in Safari when moving the selection during composition.
## 0.18.3 (2021-03-15)
### Bug fixes
Adjust to updated @codemirror/tooltip interface.
## 0.18.2 (2021-03-14)
### Bug fixes
Fix unintended ES2020 output (the package contains ES6 code again).
## 0.18.1 (2021-03-11)
### Bug fixes
Stop active completion when all sources resolve without producing any matches.
### New features
`Completion.info` may now return a promise.
## 0.18.0 (2021-03-03)
### Bug fixes
Only preserve selected option across updates when it isn't the first option.
## 0.17.4 (2021-01-18)
### Bug fixes
Fix a styling issue where the selection had become invisible inside snippet fields (when using `drawSelection`).
### New features
Snippet fields can now be selected with the pointing device (so that they are usable on touch devices).
## 0.17.3 (2021-01-18)
### Bug fixes
Fix a bug where uppercase completions would be incorrectly matched against the typed input.
## 0.17.2 (2021-01-12)
### Bug fixes
Don't bind Cmd-Space on macOS, since that already has a system default binding. Use Ctrl-Space for autocompletion.
## 0.17.1 (2021-01-06)
### New features
The package now also exports a CommonJS module.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

21
frontend/node_modules/@codemirror/autocomplete/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijn@haverbeke.berlin> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,43 @@
# @codemirror/autocomplete [![NPM version](https://img.shields.io/npm/v/@codemirror/autocomplete.svg)](https://www.npmjs.org/package/@codemirror/autocomplete)
[ [**WEBSITE**](https://codemirror.net/) | [**DOCS**](https://codemirror.net/docs/ref/#autocomplete) | [**ISSUES**](https://github.com/codemirror/dev/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/autocomplete/blob/main/CHANGELOG.md) ]
This package implements autocompletion for the
[CodeMirror](https://codemirror.net/) code editor.
The [project page](https://codemirror.net/) has more information, a
number of [examples](https://codemirror.net/examples/) and the
[documentation](https://codemirror.net/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/autocomplete/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.
## Usage
```javascript
import {EditorView} from "@codemirror/view"
import {autocompletion} from "@codemirror/autocomplete"
import {jsonLanguage} from "@codemirror/lang-json"
const view = new EditorView({
parent: document.body,
extensions: [
jsonLanguage,
autocompletion(),
jsonLanguage.data.of({
autocomplete: ["id", "name", "address"]
})
]
})
```
This configuration will just complete the given words anywhere in JSON
context. Most language modules come with more refined autocompletion
built-in, but you can also write your own custom autocompletion
[sources](https://codemirror.net/docs/ref/#autocomplete.CompletionSource)
and associate them with your language this way.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,643 @@
import * as _codemirror_state from '@codemirror/state';
import { EditorState, ChangeDesc, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
import { EditorView, Rect, KeyBinding, Command } from '@codemirror/view';
import * as _lezer_common from '@lezer/common';
/**
Objects type used to represent individual completions.
*/
interface Completion {
/**
The label to show in the completion picker. This is what input
is matched against to determine whether a completion matches (and
how well it matches).
*/
label: string;
/**
An optional override for the completion's visible label. When
using this, matched characters will only be highlighted if you
provide a [`getMatch`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.getMatch)
function.
*/
displayLabel?: string;
/**
An optional short piece of information to show (with a different
style) after the label.
*/
detail?: string;
/**
Additional info to show when the completion is selected. Can be
a plain string or a function that'll render the DOM structure to
show when invoked.
*/
info?: string | ((completion: Completion) => CompletionInfo | Promise<CompletionInfo>);
/**
How to apply the completion. The default is to replace it with
its [label](https://codemirror.net/6/docs/ref/#autocomplete.Completion.label). When this holds a
string, the completion range is replaced by that string. When it
is a function, that function is called to perform the
completion. If it fires a transaction, it is responsible for
adding the [`pickedCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.pickedCompletion)
annotation to it.
*/
apply?: string | ((view: EditorView, completion: Completion, from: number, to: number) => void);
/**
The type of the completion. This is used to pick an icon to show
for the completion. Icons are styled with a CSS class created by
appending the type name to `"cm-completionIcon-"`. You can
define or restyle icons by defining these selectors. The base
library defines simple icons for `class`, `constant`, `enum`,
`function`, `interface`, `keyword`, `method`, `namespace`,
`property`, `text`, `type`, and `variable`.
Multiple types can be provided by separating them with spaces.
*/
type?: string;
/**
When this option is selected, and one of these characters is
typed, insert the completion before typing the character.
*/
commitCharacters?: readonly string[];
/**
When given, should be a number from -99 to 99 that adjusts how
this completion is ranked compared to other completions that
match the input as well as this one. A negative number moves it
down the list, a positive number moves it up.
*/
boost?: number;
/**
Can be used to divide the completion list into sections.
Completions in a given section (matched by name) will be grouped
together, with a heading above them. Options without section
will appear above all sections. A string value is equivalent to
a `{name}` object.
*/
section?: string | CompletionSection;
}
/**
The type returned from
[`Completion.info`](https://codemirror.net/6/docs/ref/#autocomplete.Completion.info). May be a DOM
node, null to indicate there is no info, or an object with an
optional `destroy` method that cleans up the node.
*/
type CompletionInfo = Node | null | {
dom: Node;
destroy?(): void;
};
/**
Object used to describe a completion
[section](https://codemirror.net/6/docs/ref/#autocomplete.Completion.section). It is recommended to
create a shared object used by all the completions in a given
section.
*/
interface CompletionSection {
/**
The name of the section. If no `render` method is present, this
will be displayed above the options.
*/
name: string;
/**
An optional function that renders the section header. Since the
headers are shown inside a list, you should make sure the
resulting element has a `display: list-item` style.
*/
header?: (section: CompletionSection) => HTMLElement;
/**
By default, sections are ordered alphabetically by name. To
specify an explicit order, `rank` can be used. Sections with a
lower rank will be shown above sections with a higher rank.
When set to `"dynamic"`, the section's position compared to
other dynamic sections depends on the matching score of the
best-matching option in the sections.
*/
rank?: number | "dynamic";
}
/**
An instance of this is passed to completion source functions.
*/
declare class CompletionContext {
/**
The editor state that the completion happens in.
*/
readonly state: EditorState;
/**
The position at which the completion is happening.
*/
readonly pos: number;
/**
Indicates whether completion was activated explicitly, or
implicitly by typing. The usual way to respond to this is to
only return completions when either there is part of a
completable entity before the cursor, or `explicit` is true.
*/
readonly explicit: boolean;
/**
The editor view. May be undefined if the context was created
in a situation where there is no such view available, such as
in synchronous updates via
[`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
or when called by test code.
*/
readonly view?: EditorView | undefined;
/**
Create a new completion context. (Mostly useful for testing
completion sources—in the editor, the extension will create
these for you.)
*/
constructor(
/**
The editor state that the completion happens in.
*/
state: EditorState,
/**
The position at which the completion is happening.
*/
pos: number,
/**
Indicates whether completion was activated explicitly, or
implicitly by typing. The usual way to respond to this is to
only return completions when either there is part of a
completable entity before the cursor, or `explicit` is true.
*/
explicit: boolean,
/**
The editor view. May be undefined if the context was created
in a situation where there is no such view available, such as
in synchronous updates via
[`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
or when called by test code.
*/
view?: EditorView | undefined);
/**
Get the extent, content, and (if there is a token) type of the
token before `this.pos`.
*/
tokenBefore(types: readonly string[]): {
from: number;
to: number;
text: string;
type: _lezer_common.NodeType;
} | null;
/**
Get the match of the given expression directly before the
cursor.
*/
matchBefore(expr: RegExp): {
from: number;
to: number;
text: string;
} | null;
/**
Yields true when the query has been aborted. Can be useful in
asynchronous queries to avoid doing work that will be ignored.
*/
get aborted(): boolean;
/**
Allows you to register abort handlers, which will be called when
the query is
[aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
By default, running queries will not be aborted for regular
typing or backspacing, on the assumption that they are likely to
return a result with a
[`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
allows the result to be used after all. Passing `onDocChange:
true` will cause this query to be aborted for any document
change.
*/
addEventListener(type: "abort", listener: () => void, options?: {
onDocChange: boolean;
}): void;
}
/**
Given a a fixed array of options, return an autocompleter that
completes them.
*/
declare function completeFromList(list: readonly (string | Completion)[]): CompletionSource;
/**
Wrap the given completion source so that it will only fire when the
cursor is in a syntax node with one of the given names.
*/
declare function ifIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
/**
Wrap the given completion source so that it will not fire when the
cursor is in a syntax node with one of the given names.
*/
declare function ifNotIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
/**
The function signature for a completion source. Such a function
may return its [result](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult)
synchronously or as a promise. Returning null indicates no
completions are available.
*/
type CompletionSource = (context: CompletionContext) => CompletionResult | null | Promise<CompletionResult | null>;
/**
Interface for objects returned by completion sources.
*/
interface CompletionResult {
/**
The start of the range that is being completed.
*/
from: number;
/**
The end of the range that is being completed. Defaults to the
main cursor position.
*/
to?: number;
/**
The completions returned. These don't have to be compared with
the input by the source—the autocompletion system will do its
own matching (against the text between `from` and `to`) and
sorting.
*/
options: readonly Completion[];
/**
When given, further typing or deletion that causes the part of
the document between ([mapped](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) `from`
and `to` to match this regular expression or predicate function
will not query the completion source again, but continue with
this list of options. This can help a lot with responsiveness,
since it allows the completion list to be updated synchronously.
*/
validFor?: RegExp | ((text: string, from: number, to: number, state: EditorState) => boolean);
/**
By default, the library filters and scores completions. Set
`filter` to `false` to disable this, and cause your completions
to all be included, in the order they were given. When there are
other sources, unfiltered completions appear at the top of the
list of completions. `validFor` must not be given when `filter`
is `false`, because it only works when filtering.
*/
filter?: boolean;
/**
When [`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) is set to
`false` or a completion has a
[`displayLabel`](https://codemirror.net/6/docs/ref/#autocomplete.Completion.displayLabel), this
may be provided to compute the ranges on the label that match
the input. Should return an array of numbers where each pair of
adjacent numbers provide the start and end of a range. The
second argument, the match found by the library, is only passed
when `filter` isn't `false`.
*/
getMatch?: (completion: Completion, matched?: readonly number[]) => readonly number[];
/**
Synchronously update the completion result after typing or
deletion. If given, this should not do any expensive work, since
it will be called during editor state updates. The function
should make sure (similar to
[`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor)) that the
completion still applies in the new state.
*/
update?: (current: CompletionResult, from: number, to: number, context: CompletionContext) => CompletionResult | null;
/**
When results contain position-dependent information in, for
example, `apply` methods, you can provide this method to update
the result for transactions that happen after the query. It is
not necessary to update `from` and `to`—those are tracked
automatically.
*/
map?: (current: CompletionResult, changes: ChangeDesc) => CompletionResult | null;
/**
Set a default set of [commit
characters](https://codemirror.net/6/docs/ref/#autocomplete.Completion.commitCharacters) for all
options in this result.
*/
commitCharacters?: readonly string[];
}
/**
This annotation is added to transactions that are produced by
picking a completion.
*/
declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
/**
Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
interface CompletionConfig {
/**
When enabled (defaults to true), autocompletion will start
whenever the user types something that can be completed.
*/
activateOnTyping?: boolean;
/**
When given, if a completion that matches the predicate is
picked, reactivate completion again as if it was typed normally.
*/
activateOnCompletion?: (completion: Completion) => boolean;
/**
The amount of time to wait for further typing before querying
completion sources via
[`activateOnTyping`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.activateOnTyping).
Defaults to 100, which should be fine unless your completion
source is very slow and/or doesn't use `validFor`.
*/
activateOnTypingDelay?: number;
/**
By default, when completion opens, the first option is selected
and can be confirmed with
[`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion). When this
is set to false, the completion widget starts with no completion
selected, and the user has to explicitly move to a completion
before you can confirm one.
*/
selectOnOpen?: boolean;
/**
Override the completion sources used. By default, they will be
taken from the `"autocomplete"` [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) (which should hold
[completion sources](https://codemirror.net/6/docs/ref/#autocomplete.CompletionSource) or arrays
of [completions](https://codemirror.net/6/docs/ref/#autocomplete.Completion)).
*/
override?: readonly CompletionSource[] | null;
/**
Determines whether the completion tooltip is closed when the
editor loses focus. Defaults to true.
*/
closeOnBlur?: boolean;
/**
The maximum number of options to render to the DOM.
*/
maxRenderedOptions?: number;
/**
Set this to false to disable the [default completion
keymap](https://codemirror.net/6/docs/ref/#autocomplete.completionKeymap). (This requires you to
add bindings to control completion yourself. The bindings should
probably have a higher precedence than other bindings for the
same keys.)
*/
defaultKeymap?: boolean;
/**
By default, completions are shown below the cursor when there is
space. Setting this to true will make the extension put the
completions above the cursor when possible.
*/
aboveCursor?: boolean;
/**
When given, this may return an additional CSS class to add to
the completion dialog element.
*/
tooltipClass?: (state: EditorState) => string;
/**
This can be used to add additional CSS classes to completion
options.
*/
optionClass?: (completion: Completion) => string;
/**
By default, the library will render icons based on the
completion's [type](https://codemirror.net/6/docs/ref/#autocomplete.Completion.type) in front of
each option. Set this to false to turn that off.
*/
icons?: boolean;
/**
This option can be used to inject additional content into
options. The `render` function will be called for each visible
completion, and should produce a DOM node to show. `position`
determines where in the DOM the result appears, relative to
other added widgets and the standard content. The default icons
have position 20, the label position 50, and the detail position
80.
*/
addToOptions?: {
render: (completion: Completion, state: EditorState, view: EditorView) => Node | null;
position: number;
}[];
/**
By default, [info](https://codemirror.net/6/docs/ref/#autocomplete.Completion.info) tooltips are
placed to the side of the selected completion. This option can
be used to override that. It will be given rectangles for the
list of completions, the selected option, the info element, and
the availble [tooltip
space](https://codemirror.net/6/docs/ref/#view.tooltips^config.tooltipSpace), and should return
style and/or class strings for the info element.
*/
positionInfo?: (view: EditorView, list: Rect, option: Rect, info: Rect, space: Rect) => {
style?: string;
class?: string;
};
/**
The comparison function to use when sorting completions with the same
match score. Defaults to using
[`localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare).
*/
compareCompletions?: (a: Completion, b: Completion) => number;
/**
When set to true (the default is false), turn off fuzzy matching
of completions and only show those that start with the text the
user typed. Only takes effect for results where
[`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) isn't false.
*/
filterStrict?: boolean;
/**
By default, commands relating to an open completion only take
effect 75 milliseconds after the completion opened, so that key
presses made before the user is aware of the tooltip don't go to
the tooltip. This option can be used to configure that delay.
*/
interactionDelay?: number;
/**
When there are multiple asynchronous completion sources, this
controls how long the extension waits for a slow source before
displaying results from faster sources. Defaults to 100
milliseconds.
*/
updateSyncTime?: number;
}
/**
Convert a snippet template to a function that can
[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
using syntax like this:
"for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
Each `${}` placeholder (you may also use `#{}`) indicates a field
that the user can fill in. Its name, if any, will be the default
content for the field.
When the snippet is activated by calling the returned function,
the code is inserted at the given position. Newlines in the
template are indented by the indentation of the start line, plus
one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
the newline.
On activation, (all instances of) the first field are selected.
The user can move between fields with Tab and Shift-Tab as long as
the fields are active. Moving to the last field or moving the
cursor out of the current field deactivates the fields.
The order of fields defaults to textual order, but you can add
numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
a custom order.
To include a literal `{` or `}` in your template, put a backslash
in front of it. This will be removed and the brace will not be
interpreted as indicating a placeholder.
*/
declare function snippet(template: string): (editor: {
state: EditorState;
dispatch: (tr: Transaction) => void;
}, completion: Completion | null, from: number, to: number) => void;
/**
A command that clears the active snippet, if any.
*/
declare const clearSnippet: StateCommand;
/**
Move to the next snippet field, if available.
*/
declare const nextSnippetField: StateCommand;
/**
Move to the previous snippet field, if available.
*/
declare const prevSnippetField: StateCommand;
/**
Check if there is an active snippet with a next field for
`nextSnippetField` to move to.
*/
declare function hasNextSnippetField(state: EditorState): boolean;
/**
Returns true if there is an active snippet and a previous field
for `prevSnippetField` to move to.
*/
declare function hasPrevSnippetField(state: EditorState): boolean;
/**
A facet that can be used to configure the key bindings used by
snippets. The default binds Tab to
[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
*/
declare const snippetKeymap: Facet<readonly KeyBinding[], readonly KeyBinding[]>;
/**
Create a completion from a snippet. Returns an object with the
properties from `completion`, plus an `apply` function that
applies the snippet.
*/
declare function snippetCompletion(template: string, completion: Completion): Completion;
/**
Returns a command that moves the completion selection forward or
backward by the given amount.
*/
declare function moveCompletionSelection(forward: boolean, by?: "option" | "page"): Command;
/**
Accept the current completion.
*/
declare const acceptCompletion: Command;
/**
Explicitly start autocompletion.
*/
declare const startCompletion: Command;
/**
Close the currently active completion.
*/
declare const closeCompletion: Command;
/**
A completion source that will scan the document for words (using a
[character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and
return those as completions.
*/
declare const completeAnyWord: CompletionSource;
/**
Configures bracket closing behavior for a syntax (via
[language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt)) using the `"closeBrackets"`
identifier.
*/
interface CloseBracketConfig {
/**
The opening brackets to close. Defaults to `["(", "[", "{", "'",
'"']`. Brackets may be single characters or a triple of quotes
(as in `"'''"`).
*/
brackets?: string[];
/**
Characters in front of which newly opened brackets are
automatically closed. Closing always happens in front of
whitespace. Defaults to `")]}:;>"`.
*/
before?: string;
/**
When determining whether a given node may be a string, recognize
these prefixes before the opening quote.
*/
stringPrefixes?: string[];
}
/**
Extension to enable bracket-closing behavior. When a closeable
bracket is typed, its closing bracket is immediately inserted
after the cursor. When closing a bracket directly in front of a
closing bracket inserted by the extension, the cursor moves over
that bracket.
*/
declare function closeBrackets(): Extension;
/**
Command that implements deleting a pair of matching brackets when
the cursor is between them.
*/
declare const deleteBracketPair: StateCommand;
/**
Close-brackets related key bindings. Binds Backspace to
[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
*/
declare const closeBracketsKeymap: readonly KeyBinding[];
/**
Implements the extension's behavior on text insertion. If the
given string counts as a bracket in the language around the
selection, and replacing the selection with it requires custom
behavior (inserting a closing version or skipping past a
previously-closed bracket), this function returns a transaction
representing that custom behavior. (You only need this if you want
to programmatically insert brackets—the
[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
take care of running this for user input.)
*/
declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
/**
Returns an extension that enables autocompletion.
*/
declare function autocompletion(config?: CompletionConfig): Extension;
/**
Basic keybindings for autocompletion.
- Ctrl-Space (and Alt-\` or Alt-i on macOS): [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
- Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
- ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
- ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
- PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
- PageUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false, "page")`
- Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
*/
declare const completionKeymap: readonly KeyBinding[];
/**
Get the current completion status. When completions are available,
this will return `"active"`. When completions are pending (in the
process of being queried), this returns `"pending"`. Otherwise, it
returns `null`.
*/
declare function completionStatus(state: EditorState): null | "active" | "pending";
/**
Returns the available completions as an array.
*/
declare function currentCompletions(state: EditorState): readonly Completion[];
/**
Return the currently selected completion, if any.
*/
declare function selectedCompletion(state: EditorState): Completion | null;
/**
Returns the currently selected position in the active completion
list, or null if no completions are active.
*/
declare function selectedCompletionIndex(state: EditorState): number | null;
/**
Create an effect that can be attached to a transaction to change
the currently selected completion.
*/
declare function setSelectedCompletion(index: number): StateEffect<unknown>;
export { type CloseBracketConfig, type Completion, CompletionContext, type CompletionInfo, type CompletionResult, type CompletionSection, type CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };

View File

@ -0,0 +1,643 @@
import * as _codemirror_state from '@codemirror/state';
import { EditorState, ChangeDesc, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
import { EditorView, Rect, KeyBinding, Command } from '@codemirror/view';
import * as _lezer_common from '@lezer/common';
/**
Objects type used to represent individual completions.
*/
interface Completion {
/**
The label to show in the completion picker. This is what input
is matched against to determine whether a completion matches (and
how well it matches).
*/
label: string;
/**
An optional override for the completion's visible label. When
using this, matched characters will only be highlighted if you
provide a [`getMatch`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.getMatch)
function.
*/
displayLabel?: string;
/**
An optional short piece of information to show (with a different
style) after the label.
*/
detail?: string;
/**
Additional info to show when the completion is selected. Can be
a plain string or a function that'll render the DOM structure to
show when invoked.
*/
info?: string | ((completion: Completion) => CompletionInfo | Promise<CompletionInfo>);
/**
How to apply the completion. The default is to replace it with
its [label](https://codemirror.net/6/docs/ref/#autocomplete.Completion.label). When this holds a
string, the completion range is replaced by that string. When it
is a function, that function is called to perform the
completion. If it fires a transaction, it is responsible for
adding the [`pickedCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.pickedCompletion)
annotation to it.
*/
apply?: string | ((view: EditorView, completion: Completion, from: number, to: number) => void);
/**
The type of the completion. This is used to pick an icon to show
for the completion. Icons are styled with a CSS class created by
appending the type name to `"cm-completionIcon-"`. You can
define or restyle icons by defining these selectors. The base
library defines simple icons for `class`, `constant`, `enum`,
`function`, `interface`, `keyword`, `method`, `namespace`,
`property`, `text`, `type`, and `variable`.
Multiple types can be provided by separating them with spaces.
*/
type?: string;
/**
When this option is selected, and one of these characters is
typed, insert the completion before typing the character.
*/
commitCharacters?: readonly string[];
/**
When given, should be a number from -99 to 99 that adjusts how
this completion is ranked compared to other completions that
match the input as well as this one. A negative number moves it
down the list, a positive number moves it up.
*/
boost?: number;
/**
Can be used to divide the completion list into sections.
Completions in a given section (matched by name) will be grouped
together, with a heading above them. Options without section
will appear above all sections. A string value is equivalent to
a `{name}` object.
*/
section?: string | CompletionSection;
}
/**
The type returned from
[`Completion.info`](https://codemirror.net/6/docs/ref/#autocomplete.Completion.info). May be a DOM
node, null to indicate there is no info, or an object with an
optional `destroy` method that cleans up the node.
*/
type CompletionInfo = Node | null | {
dom: Node;
destroy?(): void;
};
/**
Object used to describe a completion
[section](https://codemirror.net/6/docs/ref/#autocomplete.Completion.section). It is recommended to
create a shared object used by all the completions in a given
section.
*/
interface CompletionSection {
/**
The name of the section. If no `render` method is present, this
will be displayed above the options.
*/
name: string;
/**
An optional function that renders the section header. Since the
headers are shown inside a list, you should make sure the
resulting element has a `display: list-item` style.
*/
header?: (section: CompletionSection) => HTMLElement;
/**
By default, sections are ordered alphabetically by name. To
specify an explicit order, `rank` can be used. Sections with a
lower rank will be shown above sections with a higher rank.
When set to `"dynamic"`, the section's position compared to
other dynamic sections depends on the matching score of the
best-matching option in the sections.
*/
rank?: number | "dynamic";
}
/**
An instance of this is passed to completion source functions.
*/
declare class CompletionContext {
/**
The editor state that the completion happens in.
*/
readonly state: EditorState;
/**
The position at which the completion is happening.
*/
readonly pos: number;
/**
Indicates whether completion was activated explicitly, or
implicitly by typing. The usual way to respond to this is to
only return completions when either there is part of a
completable entity before the cursor, or `explicit` is true.
*/
readonly explicit: boolean;
/**
The editor view. May be undefined if the context was created
in a situation where there is no such view available, such as
in synchronous updates via
[`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
or when called by test code.
*/
readonly view?: EditorView | undefined;
/**
Create a new completion context. (Mostly useful for testing
completion sources—in the editor, the extension will create
these for you.)
*/
constructor(
/**
The editor state that the completion happens in.
*/
state: EditorState,
/**
The position at which the completion is happening.
*/
pos: number,
/**
Indicates whether completion was activated explicitly, or
implicitly by typing. The usual way to respond to this is to
only return completions when either there is part of a
completable entity before the cursor, or `explicit` is true.
*/
explicit: boolean,
/**
The editor view. May be undefined if the context was created
in a situation where there is no such view available, such as
in synchronous updates via
[`CompletionResult.update`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.update)
or when called by test code.
*/
view?: EditorView | undefined);
/**
Get the extent, content, and (if there is a token) type of the
token before `this.pos`.
*/
tokenBefore(types: readonly string[]): {
from: number;
to: number;
text: string;
type: _lezer_common.NodeType;
} | null;
/**
Get the match of the given expression directly before the
cursor.
*/
matchBefore(expr: RegExp): {
from: number;
to: number;
text: string;
} | null;
/**
Yields true when the query has been aborted. Can be useful in
asynchronous queries to avoid doing work that will be ignored.
*/
get aborted(): boolean;
/**
Allows you to register abort handlers, which will be called when
the query is
[aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
By default, running queries will not be aborted for regular
typing or backspacing, on the assumption that they are likely to
return a result with a
[`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor) field that
allows the result to be used after all. Passing `onDocChange:
true` will cause this query to be aborted for any document
change.
*/
addEventListener(type: "abort", listener: () => void, options?: {
onDocChange: boolean;
}): void;
}
/**
Given a a fixed array of options, return an autocompleter that
completes them.
*/
declare function completeFromList(list: readonly (string | Completion)[]): CompletionSource;
/**
Wrap the given completion source so that it will only fire when the
cursor is in a syntax node with one of the given names.
*/
declare function ifIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
/**
Wrap the given completion source so that it will not fire when the
cursor is in a syntax node with one of the given names.
*/
declare function ifNotIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
/**
The function signature for a completion source. Such a function
may return its [result](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult)
synchronously or as a promise. Returning null indicates no
completions are available.
*/
type CompletionSource = (context: CompletionContext) => CompletionResult | null | Promise<CompletionResult | null>;
/**
Interface for objects returned by completion sources.
*/
interface CompletionResult {
/**
The start of the range that is being completed.
*/
from: number;
/**
The end of the range that is being completed. Defaults to the
main cursor position.
*/
to?: number;
/**
The completions returned. These don't have to be compared with
the input by the source—the autocompletion system will do its
own matching (against the text between `from` and `to`) and
sorting.
*/
options: readonly Completion[];
/**
When given, further typing or deletion that causes the part of
the document between ([mapped](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) `from`
and `to` to match this regular expression or predicate function
will not query the completion source again, but continue with
this list of options. This can help a lot with responsiveness,
since it allows the completion list to be updated synchronously.
*/
validFor?: RegExp | ((text: string, from: number, to: number, state: EditorState) => boolean);
/**
By default, the library filters and scores completions. Set
`filter` to `false` to disable this, and cause your completions
to all be included, in the order they were given. When there are
other sources, unfiltered completions appear at the top of the
list of completions. `validFor` must not be given when `filter`
is `false`, because it only works when filtering.
*/
filter?: boolean;
/**
When [`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) is set to
`false` or a completion has a
[`displayLabel`](https://codemirror.net/6/docs/ref/#autocomplete.Completion.displayLabel), this
may be provided to compute the ranges on the label that match
the input. Should return an array of numbers where each pair of
adjacent numbers provide the start and end of a range. The
second argument, the match found by the library, is only passed
when `filter` isn't `false`.
*/
getMatch?: (completion: Completion, matched?: readonly number[]) => readonly number[];
/**
Synchronously update the completion result after typing or
deletion. If given, this should not do any expensive work, since
it will be called during editor state updates. The function
should make sure (similar to
[`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor)) that the
completion still applies in the new state.
*/
update?: (current: CompletionResult, from: number, to: number, context: CompletionContext) => CompletionResult | null;
/**
When results contain position-dependent information in, for
example, `apply` methods, you can provide this method to update
the result for transactions that happen after the query. It is
not necessary to update `from` and `to`—those are tracked
automatically.
*/
map?: (current: CompletionResult, changes: ChangeDesc) => CompletionResult | null;
/**
Set a default set of [commit
characters](https://codemirror.net/6/docs/ref/#autocomplete.Completion.commitCharacters) for all
options in this result.
*/
commitCharacters?: readonly string[];
}
/**
This annotation is added to transactions that are produced by
picking a completion.
*/
declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
/**
Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
interface CompletionConfig {
/**
When enabled (defaults to true), autocompletion will start
whenever the user types something that can be completed.
*/
activateOnTyping?: boolean;
/**
When given, if a completion that matches the predicate is
picked, reactivate completion again as if it was typed normally.
*/
activateOnCompletion?: (completion: Completion) => boolean;
/**
The amount of time to wait for further typing before querying
completion sources via
[`activateOnTyping`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.activateOnTyping).
Defaults to 100, which should be fine unless your completion
source is very slow and/or doesn't use `validFor`.
*/
activateOnTypingDelay?: number;
/**
By default, when completion opens, the first option is selected
and can be confirmed with
[`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion). When this
is set to false, the completion widget starts with no completion
selected, and the user has to explicitly move to a completion
before you can confirm one.
*/
selectOnOpen?: boolean;
/**
Override the completion sources used. By default, they will be
taken from the `"autocomplete"` [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) (which should hold
[completion sources](https://codemirror.net/6/docs/ref/#autocomplete.CompletionSource) or arrays
of [completions](https://codemirror.net/6/docs/ref/#autocomplete.Completion)).
*/
override?: readonly CompletionSource[] | null;
/**
Determines whether the completion tooltip is closed when the
editor loses focus. Defaults to true.
*/
closeOnBlur?: boolean;
/**
The maximum number of options to render to the DOM.
*/
maxRenderedOptions?: number;
/**
Set this to false to disable the [default completion
keymap](https://codemirror.net/6/docs/ref/#autocomplete.completionKeymap). (This requires you to
add bindings to control completion yourself. The bindings should
probably have a higher precedence than other bindings for the
same keys.)
*/
defaultKeymap?: boolean;
/**
By default, completions are shown below the cursor when there is
space. Setting this to true will make the extension put the
completions above the cursor when possible.
*/
aboveCursor?: boolean;
/**
When given, this may return an additional CSS class to add to
the completion dialog element.
*/
tooltipClass?: (state: EditorState) => string;
/**
This can be used to add additional CSS classes to completion
options.
*/
optionClass?: (completion: Completion) => string;
/**
By default, the library will render icons based on the
completion's [type](https://codemirror.net/6/docs/ref/#autocomplete.Completion.type) in front of
each option. Set this to false to turn that off.
*/
icons?: boolean;
/**
This option can be used to inject additional content into
options. The `render` function will be called for each visible
completion, and should produce a DOM node to show. `position`
determines where in the DOM the result appears, relative to
other added widgets and the standard content. The default icons
have position 20, the label position 50, and the detail position
80.
*/
addToOptions?: {
render: (completion: Completion, state: EditorState, view: EditorView) => Node | null;
position: number;
}[];
/**
By default, [info](https://codemirror.net/6/docs/ref/#autocomplete.Completion.info) tooltips are
placed to the side of the selected completion. This option can
be used to override that. It will be given rectangles for the
list of completions, the selected option, the info element, and
the availble [tooltip
space](https://codemirror.net/6/docs/ref/#view.tooltips^config.tooltipSpace), and should return
style and/or class strings for the info element.
*/
positionInfo?: (view: EditorView, list: Rect, option: Rect, info: Rect, space: Rect) => {
style?: string;
class?: string;
};
/**
The comparison function to use when sorting completions with the same
match score. Defaults to using
[`localeCompare`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare).
*/
compareCompletions?: (a: Completion, b: Completion) => number;
/**
When set to true (the default is false), turn off fuzzy matching
of completions and only show those that start with the text the
user typed. Only takes effect for results where
[`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) isn't false.
*/
filterStrict?: boolean;
/**
By default, commands relating to an open completion only take
effect 75 milliseconds after the completion opened, so that key
presses made before the user is aware of the tooltip don't go to
the tooltip. This option can be used to configure that delay.
*/
interactionDelay?: number;
/**
When there are multiple asynchronous completion sources, this
controls how long the extension waits for a slow source before
displaying results from faster sources. Defaults to 100
milliseconds.
*/
updateSyncTime?: number;
}
/**
Convert a snippet template to a function that can
[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
using syntax like this:
"for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
Each `${}` placeholder (you may also use `#{}`) indicates a field
that the user can fill in. Its name, if any, will be the default
content for the field.
When the snippet is activated by calling the returned function,
the code is inserted at the given position. Newlines in the
template are indented by the indentation of the start line, plus
one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
the newline.
On activation, (all instances of) the first field are selected.
The user can move between fields with Tab and Shift-Tab as long as
the fields are active. Moving to the last field or moving the
cursor out of the current field deactivates the fields.
The order of fields defaults to textual order, but you can add
numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
a custom order.
To include a literal `{` or `}` in your template, put a backslash
in front of it. This will be removed and the brace will not be
interpreted as indicating a placeholder.
*/
declare function snippet(template: string): (editor: {
state: EditorState;
dispatch: (tr: Transaction) => void;
}, completion: Completion | null, from: number, to: number) => void;
/**
A command that clears the active snippet, if any.
*/
declare const clearSnippet: StateCommand;
/**
Move to the next snippet field, if available.
*/
declare const nextSnippetField: StateCommand;
/**
Move to the previous snippet field, if available.
*/
declare const prevSnippetField: StateCommand;
/**
Check if there is an active snippet with a next field for
`nextSnippetField` to move to.
*/
declare function hasNextSnippetField(state: EditorState): boolean;
/**
Returns true if there is an active snippet and a previous field
for `prevSnippetField` to move to.
*/
declare function hasPrevSnippetField(state: EditorState): boolean;
/**
A facet that can be used to configure the key bindings used by
snippets. The default binds Tab to
[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
*/
declare const snippetKeymap: Facet<readonly KeyBinding[], readonly KeyBinding[]>;
/**
Create a completion from a snippet. Returns an object with the
properties from `completion`, plus an `apply` function that
applies the snippet.
*/
declare function snippetCompletion(template: string, completion: Completion): Completion;
/**
Returns a command that moves the completion selection forward or
backward by the given amount.
*/
declare function moveCompletionSelection(forward: boolean, by?: "option" | "page"): Command;
/**
Accept the current completion.
*/
declare const acceptCompletion: Command;
/**
Explicitly start autocompletion.
*/
declare const startCompletion: Command;
/**
Close the currently active completion.
*/
declare const closeCompletion: Command;
/**
A completion source that will scan the document for words (using a
[character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and
return those as completions.
*/
declare const completeAnyWord: CompletionSource;
/**
Configures bracket closing behavior for a syntax (via
[language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt)) using the `"closeBrackets"`
identifier.
*/
interface CloseBracketConfig {
/**
The opening brackets to close. Defaults to `["(", "[", "{", "'",
'"']`. Brackets may be single characters or a triple of quotes
(as in `"'''"`).
*/
brackets?: string[];
/**
Characters in front of which newly opened brackets are
automatically closed. Closing always happens in front of
whitespace. Defaults to `")]}:;>"`.
*/
before?: string;
/**
When determining whether a given node may be a string, recognize
these prefixes before the opening quote.
*/
stringPrefixes?: string[];
}
/**
Extension to enable bracket-closing behavior. When a closeable
bracket is typed, its closing bracket is immediately inserted
after the cursor. When closing a bracket directly in front of a
closing bracket inserted by the extension, the cursor moves over
that bracket.
*/
declare function closeBrackets(): Extension;
/**
Command that implements deleting a pair of matching brackets when
the cursor is between them.
*/
declare const deleteBracketPair: StateCommand;
/**
Close-brackets related key bindings. Binds Backspace to
[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
*/
declare const closeBracketsKeymap: readonly KeyBinding[];
/**
Implements the extension's behavior on text insertion. If the
given string counts as a bracket in the language around the
selection, and replacing the selection with it requires custom
behavior (inserting a closing version or skipping past a
previously-closed bracket), this function returns a transaction
representing that custom behavior. (You only need this if you want
to programmatically insert brackets—the
[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
take care of running this for user input.)
*/
declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
/**
Returns an extension that enables autocompletion.
*/
declare function autocompletion(config?: CompletionConfig): Extension;
/**
Basic keybindings for autocompletion.
- Ctrl-Space (and Alt-\` or Alt-i on macOS): [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
- Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
- ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
- ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
- PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
- PageUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false, "page")`
- Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
*/
declare const completionKeymap: readonly KeyBinding[];
/**
Get the current completion status. When completions are available,
this will return `"active"`. When completions are pending (in the
process of being queried), this returns `"pending"`. Otherwise, it
returns `null`.
*/
declare function completionStatus(state: EditorState): null | "active" | "pending";
/**
Returns the available completions as an array.
*/
declare function currentCompletions(state: EditorState): readonly Completion[];
/**
Return the currently selected completion, if any.
*/
declare function selectedCompletion(state: EditorState): Completion | null;
/**
Returns the currently selected position in the active completion
list, or null if no completions are active.
*/
declare function selectedCompletionIndex(state: EditorState): number | null;
/**
Create an effect that can be attached to a transaction to change
the currently selected completion.
*/
declare function setSelectedCompletion(index: number): StateEffect<unknown>;
export { type CloseBracketConfig, type Completion, CompletionContext, type CompletionInfo, type CompletionResult, type CompletionSection, type CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, hasNextSnippetField, hasPrevSnippetField, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
{
"name": "@codemirror/autocomplete",
"version": "6.19.1",
"description": "Autocompletion for the CodeMirror code editor",
"scripts": {
"test": "cm-runtests",
"prepare": "cm-buildhelper src/index.ts"
},
"keywords": [
"editor",
"code"
],
"author": {
"name": "Marijn Haverbeke",
"email": "marijn@haverbeke.berlin",
"url": "http://marijnhaverbeke.nl"
},
"type": "module",
"main": "dist/index.cjs",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"types": "dist/index.d.ts",
"module": "dist/index.js",
"sideEffects": false,
"license": "MIT",
"dependencies": {
"@codemirror/language": "^6.0.0",
"@codemirror/state": "^6.0.0",
"@codemirror/view": "^6.17.0",
"@lezer/common": "^1.0.0"
},
"devDependencies": {
"@codemirror/buildhelper": "^1.0.0"
},
"repository": {
"type": "git",
"url": "https://github.com/codemirror/autocomplete.git"
}
}

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: codemirror.next
owner: codemirror
event_type: push

View File

@ -0,0 +1,58 @@
## 0.20.0 (2022-04-20)
### Breaking changes
Update dependencies to 0.20.0
## 0.19.3 (2022-03-30)
### New features
Add the extension that shows a crosshair cursor when Alt is held down to the basic setup.
## 0.19.1 (2021-12-13)
### New features
The basic setup now includes the `dropCursor` extension.
## 0.19.0 (2021-08-11)
### Breaking changes
Update dependencies to 0.19.0
## 0.18.2 (2021-05-25)
### Bug fixes
Fix too-low dependency on @codemirror/gutter that could cause broken upgrades.
## 0.18.1 (2021-05-15)
### New features
The basic setup now includes `highlightActiveLineGutter` from @codemirror/gutter.
## 0.18.0 (2021-03-03)
### Breaking changes
Update dependencies to 0.18.
## 0.17.1 (2021-01-06)
### Bug fixes
Putting a theme after the basic setup no longer causes the default highlighter to be used with the theme's editor styling.
### New features
The package now also exports a CommonJS module.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

21
frontend/node_modules/@codemirror/basic-setup/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,18 @@
# @codemirror/basic-setup [![NPM version](https://img.shields.io/npm/v/@codemirror/basic-setup.svg)](https://www.npmjs.org/package/@codemirror/basic-setup)
[ [**WEBSITE**](https://codemirror.net/6/) | [**DOCS**](https://codemirror.net/6/docs/ref/#basic-setup) | [**ISSUES**](https://github.com/codemirror/codemirror.next/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/basic-setup/blob/main/CHANGELOG.md) ]
This package implements an example configuration for the
[CodeMirror](https://codemirror.net/6/) code editor.
The [project page](https://codemirror.net/6/) has more information, a
number of [examples](https://codemirror.net/6/examples/) and the
[documentation](https://codemirror.net/6/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/basic-setup/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.

View File

@ -0,0 +1,87 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var view = require('@codemirror/view');
var state = require('@codemirror/state');
var language = require('@codemirror/language');
var commands = require('@codemirror/commands');
var search = require('@codemirror/search');
var autocomplete = require('@codemirror/autocomplete');
var lint = require('@codemirror/lint');
/**
This is an extension value that just pulls together a number of
extensions that you might want in a basic editor. It is meant as a
convenient helper to quickly set up CodeMirror without installing
and importing a lot of separate packages.
Specifically, it includes...
- [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap)
- [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers)
- [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars)
- [the undo history](https://codemirror.net/6/docs/ref/#commands.history)
- [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter)
- [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection)
- [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor)
- [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
- [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput)
- [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback)
- [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching)
- [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets)
- [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion)
- [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor)
- [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine)
- [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter)
- [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches)
- [search](https://codemirror.net/6/docs/ref/#search.searchKeymap)
- [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap)
(You'll probably want to add some language package to your setup
too.)
This package does not allow customization. The idea is that, once
you decide you want to configure your editor more precisely, you
take this package's source (which is just a bunch of imports and
an array literal), copy it into your own code, and adjust it as
desired.
*/
const basicSetup = [
view.lineNumbers(),
view.highlightActiveLineGutter(),
view.highlightSpecialChars(),
commands.history(),
language.foldGutter(),
view.drawSelection(),
view.dropCursor(),
state.EditorState.allowMultipleSelections.of(true),
language.indentOnInput(),
language.syntaxHighlighting(language.defaultHighlightStyle, { fallback: true }),
language.bracketMatching(),
autocomplete.closeBrackets(),
autocomplete.autocompletion(),
view.rectangularSelection(),
view.crosshairCursor(),
view.highlightActiveLine(),
search.highlightSelectionMatches(),
view.keymap.of([
...autocomplete.closeBracketsKeymap,
...commands.defaultKeymap,
...search.searchKeymap,
...commands.historyKeymap,
...language.foldKeymap,
...autocomplete.completionKeymap,
...lint.lintKeymap
])
];
Object.defineProperty(exports, 'EditorView', {
enumerable: true,
get: function () { return view.EditorView; }
});
Object.defineProperty(exports, 'EditorState', {
enumerable: true,
get: function () { return state.EditorState; }
});
exports.basicSetup = basicSetup;

View File

@ -0,0 +1,44 @@
import { Extension } from '@codemirror/state';
export { EditorState } from '@codemirror/state';
export { EditorView } from '@codemirror/view';
/**
This is an extension value that just pulls together a number of
extensions that you might want in a basic editor. It is meant as a
convenient helper to quickly set up CodeMirror without installing
and importing a lot of separate packages.
Specifically, it includes...
- [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap)
- [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers)
- [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars)
- [the undo history](https://codemirror.net/6/docs/ref/#commands.history)
- [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter)
- [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection)
- [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor)
- [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
- [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput)
- [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback)
- [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching)
- [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets)
- [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion)
- [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor)
- [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine)
- [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter)
- [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches)
- [search](https://codemirror.net/6/docs/ref/#search.searchKeymap)
- [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap)
(You'll probably want to add some language package to your setup
too.)
This package does not allow customization. The idea is that, once
you decide you want to configure your editor more precisely, you
take this package's source (which is just a bunch of imports and
an array literal), copy it into your own code, and adjust it as
desired.
*/
declare const basicSetup: Extension;
export { basicSetup };

View File

@ -0,0 +1,77 @@
import { lineNumbers, highlightActiveLineGutter, highlightSpecialChars, drawSelection, dropCursor, rectangularSelection, crosshairCursor, highlightActiveLine, keymap } from '@codemirror/view';
export { EditorView } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
export { EditorState } from '@codemirror/state';
import { foldGutter, indentOnInput, syntaxHighlighting, defaultHighlightStyle, bracketMatching, foldKeymap } from '@codemirror/language';
import { history, defaultKeymap, historyKeymap } from '@codemirror/commands';
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search';
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
import { lintKeymap } from '@codemirror/lint';
/**
This is an extension value that just pulls together a number of
extensions that you might want in a basic editor. It is meant as a
convenient helper to quickly set up CodeMirror without installing
and importing a lot of separate packages.
Specifically, it includes...
- [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap)
- [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers)
- [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars)
- [the undo history](https://codemirror.net/6/docs/ref/#commands.history)
- [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter)
- [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection)
- [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor)
- [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
- [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput)
- [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback)
- [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching)
- [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets)
- [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion)
- [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor)
- [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine)
- [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter)
- [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches)
- [search](https://codemirror.net/6/docs/ref/#search.searchKeymap)
- [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap)
(You'll probably want to add some language package to your setup
too.)
This package does not allow customization. The idea is that, once
you decide you want to configure your editor more precisely, you
take this package's source (which is just a bunch of imports and
an array literal), copy it into your own code, and adjust it as
desired.
*/
const basicSetup = [
/*@__PURE__*/lineNumbers(),
/*@__PURE__*/highlightActiveLineGutter(),
/*@__PURE__*/highlightSpecialChars(),
/*@__PURE__*/history(),
/*@__PURE__*/foldGutter(),
/*@__PURE__*/drawSelection(),
/*@__PURE__*/dropCursor(),
/*@__PURE__*/EditorState.allowMultipleSelections.of(true),
/*@__PURE__*/indentOnInput(),
/*@__PURE__*/syntaxHighlighting(defaultHighlightStyle, { fallback: true }),
/*@__PURE__*/bracketMatching(),
/*@__PURE__*/closeBrackets(),
/*@__PURE__*/autocompletion(),
/*@__PURE__*/rectangularSelection(),
/*@__PURE__*/crosshairCursor(),
/*@__PURE__*/highlightActiveLine(),
/*@__PURE__*/highlightSelectionMatches(),
/*@__PURE__*/keymap.of([
...closeBracketsKeymap,
...defaultKeymap,
...searchKeymap,
...historyKeymap,
...foldKeymap,
...completionKeymap,
...lintKeymap
])
];
export { basicSetup };

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: codemirror.next
owner: codemirror
event_type: push

View File

@ -0,0 +1,268 @@
## 0.20.3 (2022-05-30)
### Bug fixes
Add an aria-label to the completion listbox.
Fix a regression that caused transactions generated for completion to not have a `userEvent` annotation.
## 0.20.2 (2022-05-24)
### New features
The package now exports an `insertCompletionText` helper that implements the default behavior for applying a completion.
## 0.20.1 (2022-05-16)
### New features
The new `closeOnBlur` option determines whether the completion tooltip is closed when the editor loses focus.
`CompletionResult` objects with `filter: false` may now have a `getMatch` property that determines the matched range in the options.
## 0.20.0 (2022-04-20)
### Breaking changes
`CompletionResult.span` has been renamed to `validFor`, and may now hold a function as well as a regular expression.
### Bug fixes
Remove code that dropped any options beyond the 300th one when matching and sorting option lists.
Completion will now apply to all cursors when there are multiple cursors.
### New features
`CompletionResult.update` can now be used to implement quick autocompletion updates in a synchronous way.
The @codemirror/closebrackets package was merged into this one.
## 0.19.15 (2022-03-23)
### New features
The `selectedCompletionIndex` function tells you the position of the currently selected completion.
The new `setSelectionCompletion` function creates a state effect that moves the selected completion to a given index.
A completion's `info` method may now return null to indicate that no further info is available.
## 0.19.14 (2022-03-10)
### Bug fixes
Make the ARIA attributes added to the editor during autocompletion spec-compliant.
## 0.19.13 (2022-02-18)
### Bug fixes
Fix an issue where the completion tooltip stayed open if it was explicitly opened and the user backspaced past its start.
Stop snippet filling when a change happens across one of the snippet fields' boundaries.
## 0.19.12 (2022-01-11)
### Bug fixes
Fix completion navigation with PageUp/Down when the completion tooltip isn't part of the view DOM.
## 0.19.11 (2022-01-11)
### Bug fixes
Fix a bug that caused page up/down to only move the selection by two options in the completion tooltip.
## 0.19.10 (2022-01-05)
### Bug fixes
Make sure the info tooltip is hidden when the selected option is scrolled out of view.
Fix a bug in the completion ranking that would sometimes give options that match the input by word start chars higher scores than appropriate.
Options are now sorted (ascending) by length when their match score is otherwise identical.
## 0.19.9 (2021-11-26)
### Bug fixes
Fix an issue where info tooltips would be visible in an inappropriate position when there was no room to place them properly.
## 0.19.8 (2021-11-17)
### Bug fixes
Give the completion tooltip a minimal width, and show ellipsis when completions overflow the tooltip width.
### New features
`autocompletion` now accepts an `aboveCursor` option to make the completion tooltip show up above the cursor.
## 0.19.7 (2021-11-16)
### Bug fixes
Make option deduplication less aggressive, so that options with different `type` or `apply` fields don't get merged.
## 0.19.6 (2021-11-12)
### Bug fixes
Fix an issue where parsing a snippet with a field that was labeled only by a number crashed.
## 0.19.5 (2021-11-09)
### Bug fixes
Make sure info tooltips don't stick out of the bottom of the page.
### New features
The package exports a new function `selectedCompletion`, which can be used to find out which completion is currently selected.
Transactions created by picking a completion now have an annotation (`pickedCompletion`) holding the original completion.
## 0.19.4 (2021-10-24)
### Bug fixes
Don't rely on the platform's highlight colors for the active completion, since those are inconsistent and may not be appropriate for the theme.
Fix incorrect match underline for some kinds of matched completions.
## 0.19.3 (2021-08-31)
### Bug fixes
Improve the sorting of completions by using `localeCompare`.
Fix reading of autocompletions in NVDA screen reader.
### New features
The new `icons` option can be used to turn off icons in the completion list.
The `optionClass` option can now be used to add CSS classes to the options in the completion list.
It is now possible to inject additional content into rendered completion options with the `addToOptions` configuration option.
## 0.19.2 (2021-08-25)
### Bug fixes
Fix an issue where `completeAnyWord` would return results when there was no query and `explicit` was false.
## 0.19.1 (2021-08-11)
### Bug fixes
Fix incorrect versions for @lezer dependencies.
## 0.19.0 (2021-08-11)
### Breaking changes
Update dependencies to 0.19.0
## 0.18.8 (2021-06-30)
### New features
Add an `ifIn` helper function that constrains a completion source to only fire when in a given syntax node. Add support for unfiltered completions
A completion result can now set a `filter: false` property to disable filtering and sorting of completions, when it already did so itself.
## 0.18.7 (2021-06-14)
### Bug fixes
Don't treat continued completions when typing after an explicit completion as explicit.
## 0.18.6 (2021-06-03)
### Bug fixes
Adding or reconfiguring completion sources will now cause them to be activated right away if a completion was active.
### New features
You can now specify multiple types in `Completion.type` by separating them by spaces. Small doc comment tweak for Completion.type
## 0.18.5 (2021-04-23)
### Bug fixes
Fix a regression where snippet field selection didn't work with @codemirror/state 0.18.6.
Fix a bug where snippet fields with different position numbers were inappropriately merged.
## 0.18.4 (2021-04-20)
### Bug fixes
Fix a crash in Safari when moving the selection during composition.
## 0.18.3 (2021-03-15)
### Bug fixes
Adjust to updated @codemirror/tooltip interface.
## 0.18.2 (2021-03-14)
### Bug fixes
Fix unintended ES2020 output (the package contains ES6 code again).
## 0.18.1 (2021-03-11)
### Bug fixes
Stop active completion when all sources resolve without producing any matches.
### New features
`Completion.info` may now return a promise.
## 0.18.0 (2021-03-03)
### Bug fixes
Only preserve selected option across updates when it isn't the first option.
## 0.17.4 (2021-01-18)
### Bug fixes
Fix a styling issue where the selection had become invisible inside snippet fields (when using `drawSelection`).
### New features
Snippet fields can now be selected with the pointing device (so that they are usable on touch devices).
## 0.17.3 (2021-01-18)
### Bug fixes
Fix a bug where uppercase completions would be incorrectly matched against the typed input.
## 0.17.2 (2021-01-12)
### Bug fixes
Don't bind Cmd-Space on macOS, since that already has a system default binding. Use Ctrl-Space for autocompletion.
## 0.17.1 (2021-01-06)
### New features
The package now also exports a CommonJS module.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,18 @@
# @codemirror/autocomplete [![NPM version](https://img.shields.io/npm/v/@codemirror/autocomplete.svg)](https://www.npmjs.org/package/@codemirror/autocomplete)
[ [**WEBSITE**](https://codemirror.net/6/) | [**DOCS**](https://codemirror.net/6/docs/ref/#autocomplete) | [**ISSUES**](https://github.com/codemirror/codemirror.next/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/autocomplete/blob/main/CHANGELOG.md) ]
This package implements autocompletion for the
[CodeMirror](https://codemirror.net/6/) code editor.
The [project page](https://codemirror.net/6/) has more information, a
number of [examples](https://codemirror.net/6/examples/) and the
[documentation](https://codemirror.net/6/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/autocomplete/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,454 @@
import * as _codemirror_state from '@codemirror/state';
import { EditorState, TransactionSpec, Transaction, StateCommand, Facet, Extension, StateEffect } from '@codemirror/state';
import { EditorView, KeyBinding, Command } from '@codemirror/view';
import * as _lezer_common from '@lezer/common';
interface CompletionConfig {
/**
When enabled (defaults to true), autocompletion will start
whenever the user types something that can be completed.
*/
activateOnTyping?: boolean;
/**
Override the completion sources used. By default, they will be
taken from the `"autocomplete"` [language
data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt) (which should hold
[completion sources](https://codemirror.net/6/docs/ref/#autocomplete.CompletionSource) or arrays
of [completions](https://codemirror.net/6/docs/ref/#autocomplete.Completion)).
*/
override?: readonly CompletionSource[] | null;
/**
Determines whether the completion tooltip is closed when the
editor loses focus. Defaults to true.
*/
closeOnBlur?: boolean;
/**
The maximum number of options to render to the DOM.
*/
maxRenderedOptions?: number;
/**
Set this to false to disable the [default completion
keymap](https://codemirror.net/6/docs/ref/#autocomplete.completionKeymap). (This requires you to
add bindings to control completion yourself. The bindings should
probably have a higher precedence than other bindings for the
same keys.)
*/
defaultKeymap?: boolean;
/**
By default, completions are shown below the cursor when there is
space. Setting this to true will make the extension put the
completions above the cursor when possible.
*/
aboveCursor?: boolean;
/**
This can be used to add additional CSS classes to completion
options.
*/
optionClass?: (completion: Completion) => string;
/**
By default, the library will render icons based on the
completion's [type](https://codemirror.net/6/docs/ref/#autocomplete.Completion.type) in front of
each option. Set this to false to turn that off.
*/
icons?: boolean;
/**
This option can be used to inject additional content into
options. The `render` function will be called for each visible
completion, and should produce a DOM node to show. `position`
determines where in the DOM the result appears, relative to
other added widgets and the standard content. The default icons
have position 20, the label position 50, and the detail position 70.
*/
addToOptions?: {
render: (completion: Completion, state: EditorState) => Node | null;
position: number;
}[];
}
/**
Objects type used to represent individual completions.
*/
interface Completion {
/**
The label to show in the completion picker. This is what input
is matched agains to determine whether a completion matches (and
how well it matches).
*/
label: string;
/**
An optional short piece of information to show (with a different
style) after the label.
*/
detail?: string;
/**
Additional info to show when the completion is selected. Can be
a plain string or a function that'll render the DOM structure to
show when invoked.
*/
info?: string | ((completion: Completion) => (Node | null | Promise<Node | null>));
/**
How to apply the completion. The default is to replace it with
its [label](https://codemirror.net/6/docs/ref/#autocomplete.Completion.label). When this holds a
string, the completion range is replaced by that string. When it
is a function, that function is called to perform the
completion. If it fires a transaction, it is responsible for
adding the [`pickedCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.pickedCompletion)
annotation to it.
*/
apply?: string | ((view: EditorView, completion: Completion, from: number, to: number) => void);
/**
The type of the completion. This is used to pick an icon to show
for the completion. Icons are styled with a CSS class created by
appending the type name to `"cm-completionIcon-"`. You can
define or restyle icons by defining these selectors. The base
library defines simple icons for `class`, `constant`, `enum`,
`function`, `interface`, `keyword`, `method`, `namespace`,
`property`, `text`, `type`, and `variable`.
Multiple types can be provided by separating them with spaces.
*/
type?: string;
/**
When given, should be a number from -99 to 99 that adjusts how
this completion is ranked compared to other completions that
match the input as well as this one. A negative number moves it
down the list, a positive number moves it up.
*/
boost?: number;
}
/**
An instance of this is passed to completion source functions.
*/
declare class CompletionContext {
/**
The editor state that the completion happens in.
*/
readonly state: EditorState;
/**
The position at which the completion is happening.
*/
readonly pos: number;
/**
Indicates whether completion was activated explicitly, or
implicitly by typing. The usual way to respond to this is to
only return completions when either there is part of a
completable entity before the cursor, or `explicit` is true.
*/
readonly explicit: boolean;
/**
Create a new completion context. (Mostly useful for testing
completion sources—in the editor, the extension will create
these for you.)
*/
constructor(
/**
The editor state that the completion happens in.
*/
state: EditorState,
/**
The position at which the completion is happening.
*/
pos: number,
/**
Indicates whether completion was activated explicitly, or
implicitly by typing. The usual way to respond to this is to
only return completions when either there is part of a
completable entity before the cursor, or `explicit` is true.
*/
explicit: boolean);
/**
Get the extent, content, and (if there is a token) type of the
token before `this.pos`.
*/
tokenBefore(types: readonly string[]): {
from: number;
to: number;
text: string;
type: _lezer_common.NodeType;
} | null;
/**
Get the match of the given expression directly before the
cursor.
*/
matchBefore(expr: RegExp): {
from: number;
to: number;
text: string;
} | null;
/**
Yields true when the query has been aborted. Can be useful in
asynchronous queries to avoid doing work that will be ignored.
*/
get aborted(): boolean;
/**
Allows you to register abort handlers, which will be called when
the query is
[aborted](https://codemirror.net/6/docs/ref/#autocomplete.CompletionContext.aborted).
*/
addEventListener(type: "abort", listener: () => void): void;
}
/**
Given a a fixed array of options, return an autocompleter that
completes them.
*/
declare function completeFromList(list: readonly (string | Completion)[]): CompletionSource;
/**
Wrap the given completion source so that it will only fire when the
cursor is in a syntax node with one of the given names.
*/
declare function ifIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
/**
Wrap the given completion source so that it will not fire when the
cursor is in a syntax node with one of the given names.
*/
declare function ifNotIn(nodes: readonly string[], source: CompletionSource): CompletionSource;
/**
The function signature for a completion source. Such a function
may return its [result](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult)
synchronously or as a promise. Returning null indicates no
completions are available.
*/
declare type CompletionSource = (context: CompletionContext) => CompletionResult | null | Promise<CompletionResult | null>;
/**
Interface for objects returned by completion sources.
*/
interface CompletionResult {
/**
The start of the range that is being completed.
*/
from: number;
/**
The end of the range that is being completed. Defaults to the
main cursor position.
*/
to?: number;
/**
The completions returned. These don't have to be compared with
the input by the source—the autocompletion system will do its
own matching (against the text between `from` and `to`) and
sorting.
*/
options: readonly Completion[];
/**
When given, further typing or deletion that causes the part of
the document between ([mapped](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) `from`
and `to` to match this regular expression or predicate function
will not query the completion source again, but continue with
this list of options. This can help a lot with responsiveness,
since it allows the completion list to be updated synchronously.
*/
validFor?: RegExp | ((text: string, from: number, to: number, state: EditorState) => boolean);
/**
By default, the library filters and scores completions. Set
`filter` to `false` to disable this, and cause your completions
to all be included, in the order they were given. When there are
other sources, unfiltered completions appear at the top of the
list of completions. `validFor` must not be given when `filter`
is `false`, because it only works when filtering.
*/
filter?: boolean;
/**
When [`filter`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.filter) is set to
`false`, this may be provided to compute the ranges on the label
that match the input. Should return an array of numbers where
each pair of adjacent numbers provide the start and end of a
range.
*/
getMatch?: (completion: Completion) => readonly number[];
/**
Synchronously update the completion result after typing or
deletion. If given, this should not do any expensive work, since
it will be called during editor state updates. The function
should make sure (similar to
[`validFor`](https://codemirror.net/6/docs/ref/#autocomplete.CompletionResult.validFor)) that the
completion still applies in the new state.
*/
update?: (current: CompletionResult, from: number, to: number, context: CompletionContext) => CompletionResult | null;
}
/**
This annotation is added to transactions that are produced by
picking a completion.
*/
declare const pickedCompletion: _codemirror_state.AnnotationType<Completion>;
/**
Helper function that returns a transaction spec which inserts a
completion's text in the main selection range, and any other
selection range that has the same text in front of it.
*/
declare function insertCompletionText(state: EditorState, text: string, from: number, to: number): TransactionSpec;
/**
Convert a snippet template to a function that can
[apply](https://codemirror.net/6/docs/ref/#autocomplete.Completion.apply) it. Snippets are written
using syntax like this:
"for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"
Each `${}` placeholder (you may also use `#{}`) indicates a field
that the user can fill in. Its name, if any, will be the default
content for the field.
When the snippet is activated by calling the returned function,
the code is inserted at the given position. Newlines in the
template are indented by the indentation of the start line, plus
one [indent unit](https://codemirror.net/6/docs/ref/#language.indentUnit) per tab character after
the newline.
On activation, (all instances of) the first field are selected.
The user can move between fields with Tab and Shift-Tab as long as
the fields are active. Moving to the last field or moving the
cursor out of the current field deactivates the fields.
The order of fields defaults to textual order, but you can add
numbers to placeholders (`${1}` or `${1:defaultText}`) to provide
a custom order.
*/
declare function snippet(template: string): (editor: {
state: EditorState;
dispatch: (tr: Transaction) => void;
}, _completion: Completion, from: number, to: number) => void;
/**
A command that clears the active snippet, if any.
*/
declare const clearSnippet: StateCommand;
/**
Move to the next snippet field, if available.
*/
declare const nextSnippetField: StateCommand;
/**
Move to the previous snippet field, if available.
*/
declare const prevSnippetField: StateCommand;
/**
A facet that can be used to configure the key bindings used by
snippets. The default binds Tab to
[`nextSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.nextSnippetField), Shift-Tab to
[`prevSnippetField`](https://codemirror.net/6/docs/ref/#autocomplete.prevSnippetField), and Escape
to [`clearSnippet`](https://codemirror.net/6/docs/ref/#autocomplete.clearSnippet).
*/
declare const snippetKeymap: Facet<readonly KeyBinding[], readonly KeyBinding[]>;
/**
Create a completion from a snippet. Returns an object with the
properties from `completion`, plus an `apply` function that
applies the snippet.
*/
declare function snippetCompletion(template: string, completion: Completion): Completion;
/**
Returns a command that moves the completion selection forward or
backward by the given amount.
*/
declare function moveCompletionSelection(forward: boolean, by?: "option" | "page"): Command;
/**
Accept the current completion.
*/
declare const acceptCompletion: Command;
/**
Explicitly start autocompletion.
*/
declare const startCompletion: Command;
/**
Close the currently active completion.
*/
declare const closeCompletion: Command;
/**
A completion source that will scan the document for words (using a
[character categorizer](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer)), and
return those as completions.
*/
declare const completeAnyWord: CompletionSource;
/**
Configures bracket closing behavior for a syntax (via
[language data](https://codemirror.net/6/docs/ref/#state.EditorState.languageDataAt)) using the `"closeBrackets"`
identifier.
*/
interface CloseBracketConfig {
/**
The opening brackets to close. Defaults to `["(", "[", "{", "'",
'"']`. Brackets may be single characters or a triple of quotes
(as in `"''''"`).
*/
brackets?: string[];
/**
Characters in front of which newly opened brackets are
automatically closed. Closing always happens in front of
whitespace. Defaults to `")]}:;>"`.
*/
before?: string;
}
/**
Extension to enable bracket-closing behavior. When a closeable
bracket is typed, its closing bracket is immediately inserted
after the cursor. When closing a bracket directly in front of a
closing bracket inserted by the extension, the cursor moves over
that bracket.
*/
declare function closeBrackets(): Extension;
/**
Command that implements deleting a pair of matching brackets when
the cursor is between them.
*/
declare const deleteBracketPair: StateCommand;
/**
Close-brackets related key bindings. Binds Backspace to
[`deleteBracketPair`](https://codemirror.net/6/docs/ref/#autocomplete.deleteBracketPair).
*/
declare const closeBracketsKeymap: readonly KeyBinding[];
/**
Implements the extension's behavior on text insertion. If the
given string counts as a bracket in the language around the
selection, and replacing the selection with it requires custom
behavior (inserting a closing version or skipping past a
previously-closed bracket), this function returns a transaction
representing that custom behavior. (You only need this if you want
to programmatically insert brackets—the
[`closeBrackets`](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets) extension will
take care of running this for user input.)
*/
declare function insertBracket(state: EditorState, bracket: string): Transaction | null;
/**
Returns an extension that enables autocompletion.
*/
declare function autocompletion(config?: CompletionConfig): Extension;
/**
Basic keybindings for autocompletion.
- Ctrl-Space: [`startCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.startCompletion)
- Escape: [`closeCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.closeCompletion)
- ArrowDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true)`
- ArrowUp: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(false)`
- PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
- PageDown: [`moveCompletionSelection`](https://codemirror.net/6/docs/ref/#autocomplete.moveCompletionSelection)`(true, "page")`
- Enter: [`acceptCompletion`](https://codemirror.net/6/docs/ref/#autocomplete.acceptCompletion)
*/
declare const completionKeymap: readonly KeyBinding[];
/**
Get the current completion status. When completions are available,
this will return `"active"`. When completions are pending (in the
process of being queried), this returns `"pending"`. Otherwise, it
returns `null`.
*/
declare function completionStatus(state: EditorState): null | "active" | "pending";
/**
Returns the available completions as an array.
*/
declare function currentCompletions(state: EditorState): readonly Completion[];
/**
Return the currently selected completion, if any.
*/
declare function selectedCompletion(state: EditorState): Completion | null;
/**
Returns the currently selected position in the active completion
list, or null if no completions are active.
*/
declare function selectedCompletionIndex(state: EditorState): number | null;
/**
Create an effect that can be attached to a transaction to change
the currently selected completion.
*/
declare function setSelectedCompletion(index: number): StateEffect<unknown>;
export { CloseBracketConfig, Completion, CompletionContext, CompletionResult, CompletionSource, acceptCompletion, autocompletion, clearSnippet, closeBrackets, closeBracketsKeymap, closeCompletion, completeAnyWord, completeFromList, completionKeymap, completionStatus, currentCompletions, deleteBracketPair, ifIn, ifNotIn, insertBracket, insertCompletionText, moveCompletionSelection, nextSnippetField, pickedCompletion, prevSnippetField, selectedCompletion, selectedCompletionIndex, setSelectedCompletion, snippet, snippetCompletion, snippetKeymap, startCompletion };

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,41 @@
{
"name": "@codemirror/autocomplete",
"version": "0.20.3",
"description": "Autocompletion for the CodeMirror code editor",
"scripts": {
"test": "cm-runtests",
"prepare": "cm-buildhelper src/index.ts"
},
"keywords": [
"editor",
"code"
],
"author": {
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"url": "http://marijnhaverbeke.nl"
},
"type": "module",
"main": "dist/index.cjs",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"types": "dist/index.d.ts",
"module": "dist/index.js",
"sideEffects": false,
"license": "MIT",
"dependencies": {
"@codemirror/language": "^0.20.0",
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0",
"@lezer/common": "^0.16.0"
},
"devDependencies": {
"@codemirror/buildhelper": "^0.1.5"
},
"repository": {
"type": "git",
"url": "https://github.com/codemirror/autocomplete.git"
}
}

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: codemirror.next
owner: codemirror
event_type: push

View File

@ -0,0 +1,188 @@
## 0.20.2 (2022-05-20)
### Bug fixes
List style-mod as a dependency.
## 0.20.1 (2022-05-18)
### Bug fixes
Make sure `all` styles in the CSS generated for a `HighlightStyle` have a lower precedence than the other rules defined for the style. Use a shorthand property
## 0.20.0 (2022-04-20)
### Breaking changes
`HighlightStyle.get` is now called `highlightingFor`.
`HighlightStyles` no longer function as extensions (to improve tree shaking), and must be wrapped with `syntaxHighlighting` to add to an editor configuration.
`Language` objects no longer have a `topNode` property.
### New features
`HighlightStyle` and `defaultHighlightStyle` from the now-removed @codemirror/highlight package now live in this package.
The new `forceParsing` function can be used to run the parser forward on an editor view.
The exports that used to live in @codemirror/matchbrackets are now exported from this package.
The @codemirror/fold package has been merged into this one.
The exports from the old @codemirror/stream-parser package now live in this package.
## 0.19.10 (2022-03-31)
### Bug fixes
Autocompletion may now also trigger automatic indentation on input.
## 0.19.9 (2022-03-30)
### Bug fixes
Make sure nodes that end at the end of a partial parse aren't treated as valid fold targets.
Fix an issue where the parser sometimes wouldn't reuse parsing work done in the background on transactions.
## 0.19.8 (2022-03-03)
### Bug fixes
Fix an issue that could cause indentation logic to use the wrong line content when indenting multiple lines at once.
## 0.19.7 (2021-12-02)
### Bug fixes
Fix an issue where the parse worker could incorrectly stop working when the parse tree has skipped gaps in it.
## 0.19.6 (2021-11-26)
### Bug fixes
Fixes an issue where the background parse work would be scheduled too aggressively, degrading responsiveness on a newly-created editor with a large document.
Improve initial highlight for mixed-language editors and limit the amount of parsing done on state creation for faster startup.
## 0.19.5 (2021-11-17)
### New features
The new function `syntaxTreeAvailable` can be used to check if a fully-parsed syntax tree is available up to a given document position.
The module now exports `syntaxParserRunning`, which tells you whether the background parser is still planning to do more work for a given editor view.
## 0.19.4 (2021-11-13)
### New features
`LanguageDescription.of` now takes an optional already-loaded extension.
## 0.19.3 (2021-09-13)
### Bug fixes
Fix an issue where a parse that skipped content with `skipUntilInView` would in some cases not be restarted when the range came into view.
## 0.19.2 (2021-08-11)
### Bug fixes
Fix a bug that caused `indentOnInput` to fire for the wrong kinds of transactions.
Fix a bug that could cause `indentOnInput` to apply its changes incorrectly.
## 0.19.1 (2021-08-11)
### Bug fixes
Fix incorrect versions for @lezer dependencies.
## 0.19.0 (2021-08-11)
### Breaking changes
CodeMirror now uses lezer 0.15, which means different package names (scoped with @lezer) and some breaking changes in the library.
`EditorParseContext` is now called `ParseContext`. It is no longer passed to parsers, but must be retrieved with `ParseContext.get`.
`IndentContext.lineIndent` now takes a position, not a `Line` object, as argument.
`LezerLanguage` was renamed to `LRLanguage` (because all languages must emit Lezer-style trees, the name was misleading).
`Language.parseString` no longer exists. You can just call `.parser.parse(...)` instead.
### New features
New `IndentContext.lineAt` method to access lines in a way that is aware of simulated line breaks.
`IndentContext` now provides a `simulatedBreak` property through which client code can query whether the context has a simulated line break.
## 0.18.2 (2021-06-01)
### Bug fixes
Fix an issue where asynchronous re-parsing (with dynamically loaded languages) sometimes failed to fully happen.
## 0.18.1 (2021-03-31)
### Breaking changes
`EditorParseContext.getSkippingParser` now replaces `EditorParseContext.skippingParser` and allows you to provide a promise that'll cause parsing to start again. (The old property remains available until the next major release.)
### Bug fixes
Fix an issue where nested parsers could see past the end of the nested region.
## 0.18.0 (2021-03-03)
### Breaking changes
Update dependencies to 0.18.
### Breaking changes
The `Language` constructor takes an additional argument that provides the top node type.
### New features
`Language` instances now have a `topNode` property giving their top node type.
`TreeIndentContext` now has a `continue` method that allows an indenter to defer to the indentation of the parent nodes.
## 0.17.5 (2021-02-19)
### New features
This package now exports a `foldInside` helper function, a fold function that should work for most delimited node types.
## 0.17.4 (2021-01-15)
## 0.17.3 (2021-01-15)
### Bug fixes
Parse scheduling has been improved to reduce the likelyhood of the user looking at unparsed code in big documents.
Prevent parser from running too far past the current viewport in huge documents.
## 0.17.2 (2021-01-06)
### New features
The package now also exports a CommonJS module.
## 0.17.1 (2020-12-30)
### Bug fixes
Fix a bug where changing the editor configuration wouldn't update the language parser used.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,18 @@
# @codemirror/language [![NPM version](https://img.shields.io/npm/v/@codemirror/language.svg)](https://www.npmjs.org/package/@codemirror/language)
[ [**WEBSITE**](https://codemirror.net/6/) | [**DOCS**](https://codemirror.net/6/docs/ref/#language) | [**ISSUES**](https://github.com/codemirror/codemirror.next/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/language/blob/main/CHANGELOG.md) ]
This package implements the language support infrastructure for the
[CodeMirror](https://codemirror.net/6/) code editor.
The [project page](https://codemirror.net/6/) has more information, a
number of [examples](https://codemirror.net/6/examples/) and the
[documentation](https://codemirror.net/6/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/language/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,44 @@
{
"name": "@codemirror/language",
"version": "0.20.2",
"description": "Language support infrastructure for the CodeMirror code editor",
"scripts": {
"test": "cm-runtests",
"prepare": "cm-buildhelper src/index.ts"
},
"keywords": [
"editor",
"code"
],
"author": {
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"url": "http://marijnhaverbeke.nl"
},
"type": "module",
"main": "dist/index.cjs",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"types": "dist/index.d.ts",
"module": "dist/index.js",
"sideEffects": false,
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0",
"@lezer/common": "^0.16.0",
"@lezer/highlight": "^0.16.0",
"@lezer/lr": "^0.16.0",
"style-mod": "^4.0.0"
},
"devDependencies": {
"@codemirror/buildhelper": "^0.1.5",
"@lezer/javascript": "^0.16.0"
},
"repository": {
"type": "git",
"url": "https://github.com/codemirror/language.git"
}
}

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: codemirror.next
owner: codemirror
event_type: push

View File

@ -0,0 +1,144 @@
## 0.20.3 (2022-05-25)
### New features
Diagnostic objects may now have a `renderMessage` method to render their message to the DOM.
## 0.20.2 (2022-05-02)
### New features
The package now exports the `LintSource` function type.
The new `markerFilter` and `tooltipFilter` options to `linter` and `lintGutter` allow more control over which diagnostics are visible and which have tooltips.
## 0.20.1 (2022-04-22)
### Bug fixes
Hide lint tooltips when the document is changed.
## 0.20.0 (2022-04-20)
### Breaking changes
Update dependencies to 0.20.0
## 0.19.6 (2022-03-04)
### Bug fixes
Fix a bug where hovering over the icons in the lint gutter would sometimes fail to show a tooltip or show the tooltip for another line.
## 0.19.5 (2022-02-25)
### Bug fixes
Make sure the lint gutter tooltips are positioned under their icon, even when the line is wrapped.
## 0.19.4 (2022-02-25)
### Bug fixes
Fix an issue where an outdated marker could stick around on the lint gutter after all diagnostics were removed.
### New features
Add a `hoverTime` option to the lint gutter. Change default hover time to 300
## 0.19.3 (2021-11-09)
### New features
Export a function `lintGutter` which returns an extension that installs a gutter marking lines with diagnostics.
The package now exports the effect used to update the diagnostics (`setDiagnosticsEffect`).
## 0.19.2 (2021-09-29)
### Bug fixes
Fix a bug where reconfiguring the lint source didn't restart linting.
## 0.19.1 (2021-09-17)
### Bug fixes
Prevent decorations that cover just a line break from being invisible by showing a widget instead of range for them.
### New features
The `diagnosticCount` method can now be used to determine whether there are active diagnostics.
## 0.19.0 (2021-08-11)
### Breaking changes
Update dependencies to 0.19.0
## 0.18.6 (2021-08-08)
### Bug fixes
Fix a crash in the key handler of the lint panel when no diagnostics are available.
## 0.18.5 (2021-08-07)
### Bug fixes
Fix an issue that caused `openLintPanel` to not actually open the panel when ran before the editor had any lint state loaded.
### New features
The package now exports a `forceLinting` function that forces pending lint queries to run immediately.
## 0.18.4 (2021-06-07)
### Bug fixes
Multiple `linter` extensions can now be added to an editor without disrupting each other.
Fix poor layout on lint tooltips due to changes in @codemirror/tooltip.
## 0.18.3 (2021-05-10)
### Bug fixes
Fix a regression where using `setDiagnostics` when linting hadn't been abled yet ignored the first set of diagnostics.
## 0.18.2 (2021-04-16)
### Bug fixes
Newlines in line messages are now shown as line breaks to the user.
### New features
You can now pass a delay option to `linter` to configure how long it waits before calling the linter.
## 0.18.1 (2021-03-15)
### Bug fixes
Adjust to current @codemirror/panel and @codemirror/tooltip interfaces.
## 0.18.0 (2021-03-03)
### Bug fixes
Make sure action access keys are discoverable for screen reader users.
Selection in the lint panel should now be properly visible to screen readers.
## 0.17.1 (2021-01-06)
### New features
The package now also exports a CommonJS module.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,18 @@
# @codemirror/lint [![NPM version](https://img.shields.io/npm/v/@codemirror/lint.svg)](https://www.npmjs.org/package/@codemirror/lint)
[ [**WEBSITE**](https://codemirror.net/6/) | [**DOCS**](https://codemirror.net/6/docs/ref/#lint) | [**ISSUES**](https://github.com/codemirror/codemirror.next/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/lint/blob/main/CHANGELOG.md) ]
This package implements linting support for the
[CodeMirror](https://codemirror.net/6/) code editor.
The [project page](https://codemirror.net/6/) has more information, a
number of [examples](https://codemirror.net/6/examples/) and the
[documentation](https://codemirror.net/6/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/lint/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.

View File

@ -0,0 +1,749 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var view = require('@codemirror/view');
var state = require('@codemirror/state');
var elt = require('crelt');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var elt__default = /*#__PURE__*/_interopDefaultLegacy(elt);
class SelectedDiagnostic {
constructor(from, to, diagnostic) {
this.from = from;
this.to = to;
this.diagnostic = diagnostic;
}
}
class LintState {
constructor(diagnostics, panel, selected) {
this.diagnostics = diagnostics;
this.panel = panel;
this.selected = selected;
}
static init(diagnostics, panel, state) {
// Filter the list of diagnostics for which to create markers
let markedDiagnostics = diagnostics;
let diagnosticFilter = state.facet(lintConfig).markerFilter;
if (diagnosticFilter)
markedDiagnostics = diagnosticFilter(markedDiagnostics);
let ranges = view.Decoration.set(markedDiagnostics.map((d) => {
// For zero-length ranges or ranges covering only a line break, create a widget
return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from)
? view.Decoration.widget({
widget: new DiagnosticWidget(d),
diagnostic: d
}).range(d.from)
: view.Decoration.mark({
attributes: { class: "cm-lintRange cm-lintRange-" + d.severity },
diagnostic: d
}).range(d.from, d.to);
}), true);
return new LintState(ranges, panel, findDiagnostic(ranges));
}
}
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
let found = null;
diagnostics.between(after, 1e9, (from, to, { spec }) => {
if (diagnostic && spec.diagnostic != diagnostic)
return;
found = new SelectedDiagnostic(from, to, spec.diagnostic);
return false;
});
return found;
}
function hideTooltip(tr, tooltip) {
return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(tooltip.pos));
}
function maybeEnableLint(state$1, effects) {
return state$1.field(lintState, false) ? effects : effects.concat(state.StateEffect.appendConfig.of([
lintState,
view.EditorView.decorations.compute([lintState], state => {
let { selected, panel } = state.field(lintState);
return !selected || !panel || selected.from == selected.to ? view.Decoration.none : view.Decoration.set([
activeMark.range(selected.from, selected.to)
]);
}),
view.hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
baseTheme
]));
}
/**
Returns a transaction spec which updates the current set of
diagnostics, and enables the lint extension if if wasn't already
active.
*/
function setDiagnostics(state, diagnostics) {
return {
effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)])
};
}
/**
The state effect that updates the set of active diagnostics. Can
be useful when writing an extension that needs to track these.
*/
const setDiagnosticsEffect = state.StateEffect.define();
const togglePanel = state.StateEffect.define();
const movePanelSelection = state.StateEffect.define();
const lintState = state.StateField.define({
create() {
return new LintState(view.Decoration.none, null, null);
},
update(value, tr) {
if (tr.docChanged) {
let mapped = value.diagnostics.map(tr.changes), selected = null;
if (value.selected) {
let selPos = tr.changes.mapPos(value.selected.from, 1);
selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
}
value = new LintState(mapped, value.panel, selected);
}
for (let effect of tr.effects) {
if (effect.is(setDiagnosticsEffect)) {
value = LintState.init(effect.value, value.panel, tr.state);
}
else if (effect.is(togglePanel)) {
value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected);
}
else if (effect.is(movePanelSelection)) {
value = new LintState(value.diagnostics, value.panel, effect.value);
}
}
return value;
},
provide: f => [view.showPanel.from(f, val => val.panel),
view.EditorView.decorations.from(f, s => s.diagnostics)]
});
/**
Returns the number of active lint diagnostics in the given state.
*/
function diagnosticCount(state) {
let lint = state.field(lintState, false);
return lint ? lint.diagnostics.size : 0;
}
const activeMark = view.Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
function lintTooltip(view, pos, side) {
let { diagnostics } = view.state.field(lintState);
let found = [], stackStart = 2e8, stackEnd = 0;
diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
if (pos >= from && pos <= to &&
(from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) {
found.push(spec.diagnostic);
stackStart = Math.min(from, stackStart);
stackEnd = Math.max(to, stackEnd);
}
});
let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
if (diagnosticFilter)
found = diagnosticFilter(found);
if (!found.length)
return null;
return {
pos: stackStart,
end: stackEnd,
above: view.state.doc.lineAt(stackStart).to < stackEnd,
create() {
return { dom: diagnosticsTooltip(view, found) };
}
};
}
function diagnosticsTooltip(view, diagnostics) {
return elt__default["default"]("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false)));
}
/**
Command to open and focus the lint panel.
*/
const openLintPanel = (view$1) => {
let field = view$1.state.field(lintState, false);
if (!field || !field.panel)
view$1.dispatch({ effects: maybeEnableLint(view$1.state, [togglePanel.of(true)]) });
let panel = view.getPanel(view$1, LintPanel.open);
if (panel)
panel.dom.querySelector(".cm-panel-lint ul").focus();
return true;
};
/**
Command to close the lint panel, when open.
*/
const closeLintPanel = (view) => {
let field = view.state.field(lintState, false);
if (!field || !field.panel)
return false;
view.dispatch({ effects: togglePanel.of(false) });
return true;
};
/**
Move the selection to the next diagnostic.
*/
const nextDiagnostic = (view) => {
let field = view.state.field(lintState, false);
if (!field)
return false;
let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1);
if (!next.value) {
next = field.diagnostics.iter(0);
if (!next.value || next.from == sel.from && next.to == sel.to)
return false;
}
view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
return true;
};
/**
A set of default key bindings for the lint functionality.
- Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel)
- F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic)
*/
const lintKeymap = [
{ key: "Mod-Shift-m", run: openLintPanel },
{ key: "F8", run: nextDiagnostic }
];
const lintPlugin = view.ViewPlugin.fromClass(class {
constructor(view) {
this.view = view;
this.timeout = -1;
this.set = true;
let { delay } = view.state.facet(lintConfig);
this.lintTime = Date.now() + delay;
this.run = this.run.bind(this);
this.timeout = setTimeout(this.run, delay);
}
run() {
let now = Date.now();
if (now < this.lintTime - 10) {
setTimeout(this.run, this.lintTime - now);
}
else {
this.set = false;
let { state } = this.view, { sources } = state.facet(lintConfig);
Promise.all(sources.map(source => Promise.resolve(source(this.view)))).then(annotations => {
let all = annotations.reduce((a, b) => a.concat(b));
if (this.view.state.doc == state.doc)
this.view.dispatch(setDiagnostics(this.view.state, all));
}, error => { view.logException(this.view.state, error); });
}
}
update(update) {
let config = update.state.facet(lintConfig);
if (update.docChanged || config != update.startState.facet(lintConfig)) {
this.lintTime = Date.now() + config.delay;
if (!this.set) {
this.set = true;
this.timeout = setTimeout(this.run, config.delay);
}
}
}
force() {
if (this.set) {
this.lintTime = Date.now();
this.run();
}
}
destroy() {
clearTimeout(this.timeout);
}
});
const lintConfig = state.Facet.define({
combine(input) {
return Object.assign({ sources: input.map(i => i.source) }, state.combineConfig(input.map(i => i.config), {
delay: 750,
markerFilter: null,
tooltipFilter: null
}));
},
enables: lintPlugin
});
/**
Given a diagnostic source, this function returns an extension that
enables linting with that source. It will be called whenever the
editor is idle (after its content changed).
*/
function linter(source, config = {}) {
return lintConfig.of({ source, config });
}
/**
Forces any linters [configured](https://codemirror.net/6/docs/ref/#lint.linter) to run when the
editor is idle to run right away.
*/
function forceLinting(view) {
let plugin = view.plugin(lintPlugin);
if (plugin)
plugin.force();
}
function assignKeys(actions) {
let assigned = [];
if (actions)
actions: for (let { name } of actions) {
for (let i = 0; i < name.length; i++) {
let ch = name[i];
if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) {
assigned.push(ch);
continue actions;
}
}
assigned.push("");
}
return assigned;
}
function renderDiagnostic(view, diagnostic, inPanel) {
var _a;
let keys = inPanel ? assignKeys(diagnostic.actions) : [];
return elt__default["default"]("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, elt__default["default"]("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage() : diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => {
let click = (e) => {
e.preventDefault();
let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
if (found)
action.apply(view, found.from, found.to);
};
let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1;
let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex),
elt__default["default"]("u", name.slice(keyIndex, keyIndex + 1)),
name.slice(keyIndex + 1)];
return elt__default["default"]("button", {
type: "button",
class: "cm-diagnosticAction",
onclick: click,
onmousedown: click,
"aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.`
}, nameElt);
}), diagnostic.source && elt__default["default"]("div", { class: "cm-diagnosticSource" }, diagnostic.source));
}
class DiagnosticWidget extends view.WidgetType {
constructor(diagnostic) {
super();
this.diagnostic = diagnostic;
}
eq(other) { return other.diagnostic == this.diagnostic; }
toDOM() {
return elt__default["default"]("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity });
}
}
class PanelItem {
constructor(view, diagnostic) {
this.diagnostic = diagnostic;
this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16);
this.dom = renderDiagnostic(view, diagnostic, true);
this.dom.id = this.id;
this.dom.setAttribute("role", "option");
}
}
class LintPanel {
constructor(view) {
this.view = view;
this.items = [];
let onkeydown = (event) => {
if (event.keyCode == 27) { // Escape
closeLintPanel(this.view);
this.view.focus();
}
else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp
this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
}
else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown
this.moveSelection((this.selectedIndex + 1) % this.items.length);
}
else if (event.keyCode == 36) { // Home
this.moveSelection(0);
}
else if (event.keyCode == 35) { // End
this.moveSelection(this.items.length - 1);
}
else if (event.keyCode == 13) { // Enter
this.view.focus();
}
else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z
let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions);
for (let i = 0; i < keys.length; i++)
if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) {
let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
if (found)
diagnostic.actions[i].apply(view, found.from, found.to);
}
}
else {
return;
}
event.preventDefault();
};
let onclick = (event) => {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].dom.contains(event.target))
this.moveSelection(i);
}
};
this.list = elt__default["default"]("ul", {
tabIndex: 0,
role: "listbox",
"aria-label": this.view.state.phrase("Diagnostics"),
onkeydown,
onclick
});
this.dom = elt__default["default"]("div", { class: "cm-panel-lint" }, this.list, elt__default["default"]("button", {
type: "button",
name: "close",
"aria-label": this.view.state.phrase("close"),
onclick: () => closeLintPanel(this.view)
}, "×"));
this.update();
}
get selectedIndex() {
let selected = this.view.state.field(lintState).selected;
if (!selected)
return -1;
for (let i = 0; i < this.items.length; i++)
if (this.items[i].diagnostic == selected.diagnostic)
return i;
return -1;
}
update() {
let { diagnostics, selected } = this.view.state.field(lintState);
let i = 0, needsSync = false, newSelectedItem = null;
diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
let found = -1, item;
for (let j = i; j < this.items.length; j++)
if (this.items[j].diagnostic == spec.diagnostic) {
found = j;
break;
}
if (found < 0) {
item = new PanelItem(this.view, spec.diagnostic);
this.items.splice(i, 0, item);
needsSync = true;
}
else {
item = this.items[found];
if (found > i) {
this.items.splice(i, found - i);
needsSync = true;
}
}
if (selected && item.diagnostic == selected.diagnostic) {
if (!item.dom.hasAttribute("aria-selected")) {
item.dom.setAttribute("aria-selected", "true");
newSelectedItem = item;
}
}
else if (item.dom.hasAttribute("aria-selected")) {
item.dom.removeAttribute("aria-selected");
}
i++;
});
while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
needsSync = true;
this.items.pop();
}
if (this.items.length == 0) {
this.items.push(new PanelItem(this.view, {
from: -1, to: -1,
severity: "info",
message: this.view.state.phrase("No diagnostics")
}));
needsSync = true;
}
if (newSelectedItem) {
this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
this.view.requestMeasure({
key: this,
read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
write: ({ sel, panel }) => {
if (sel.top < panel.top)
this.list.scrollTop -= panel.top - sel.top;
else if (sel.bottom > panel.bottom)
this.list.scrollTop += sel.bottom - panel.bottom;
}
});
}
else if (this.selectedIndex < 0) {
this.list.removeAttribute("aria-activedescendant");
}
if (needsSync)
this.sync();
}
sync() {
let domPos = this.list.firstChild;
function rm() {
let prev = domPos;
domPos = prev.nextSibling;
prev.remove();
}
for (let item of this.items) {
if (item.dom.parentNode == this.list) {
while (domPos != item.dom)
rm();
domPos = item.dom.nextSibling;
}
else {
this.list.insertBefore(item.dom, domPos);
}
}
while (domPos)
rm();
}
moveSelection(selectedIndex) {
if (this.selectedIndex < 0)
return;
let field = this.view.state.field(lintState);
let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
if (!selection)
return;
this.view.dispatch({
selection: { anchor: selection.from, head: selection.to },
scrollIntoView: true,
effects: movePanelSelection.of(selection)
});
}
static open(view) { return new LintPanel(view); }
}
function svg(content, attrs = `viewBox="0 0 40 40"`) {
return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;
}
function underline(color) {
return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
}
const baseTheme = view.EditorView.baseTheme({
".cm-diagnostic": {
padding: "3px 6px 3px 8px",
marginLeft: "-1px",
display: "block",
whiteSpace: "pre-wrap"
},
".cm-diagnostic-error": { borderLeft: "5px solid #d11" },
".cm-diagnostic-warning": { borderLeft: "5px solid orange" },
".cm-diagnostic-info": { borderLeft: "5px solid #999" },
".cm-diagnosticAction": {
font: "inherit",
border: "none",
padding: "2px 4px",
backgroundColor: "#444",
color: "white",
borderRadius: "3px",
marginLeft: "8px"
},
".cm-diagnosticSource": {
fontSize: "70%",
opacity: .7
},
".cm-lintRange": {
backgroundPosition: "left bottom",
backgroundRepeat: "repeat-x",
paddingBottom: "0.7px",
},
".cm-lintRange-error": { backgroundImage: underline("#d11") },
".cm-lintRange-warning": { backgroundImage: underline("orange") },
".cm-lintRange-info": { backgroundImage: underline("#999") },
".cm-lintRange-active": { backgroundColor: "#ffdd9980" },
".cm-tooltip-lint": {
padding: 0,
margin: 0
},
".cm-lintPoint": {
position: "relative",
"&:after": {
content: '""',
position: "absolute",
bottom: 0,
left: "-2px",
borderLeft: "3px solid transparent",
borderRight: "3px solid transparent",
borderBottom: "4px solid #d11"
}
},
".cm-lintPoint-warning": {
"&:after": { borderBottomColor: "orange" }
},
".cm-lintPoint-info": {
"&:after": { borderBottomColor: "#999" }
},
".cm-panel.cm-panel-lint": {
position: "relative",
"& ul": {
maxHeight: "100px",
overflowY: "auto",
"& [aria-selected]": {
backgroundColor: "#ddd",
"& u": { textDecoration: "underline" }
},
"&:focus [aria-selected]": {
background_fallback: "#bdf",
backgroundColor: "Highlight",
color_fallback: "white",
color: "HighlightText"
},
"& u": { textDecoration: "none" },
padding: 0,
margin: 0
},
"& [name=close]": {
position: "absolute",
top: "0",
right: "2px",
background: "inherit",
border: "none",
font: "inherit",
padding: 0,
margin: 0
}
}
});
class LintGutterMarker extends view.GutterMarker {
constructor(diagnostics) {
super();
this.diagnostics = diagnostics;
this.severity = diagnostics.reduce((max, d) => {
let s = d.severity;
return s == "error" || s == "warning" && max == "info" ? s : max;
}, "info");
}
toDOM(view) {
let elt = document.createElement("div");
elt.className = "cm-lint-marker cm-lint-marker-" + this.severity;
let diagnostics = this.diagnostics;
let diagnosticsFilter = view.state.facet(lintGutterConfig).tooltipFilter;
if (diagnosticsFilter)
diagnostics = diagnosticsFilter(diagnostics);
if (diagnostics.length)
elt.onmouseover = () => gutterMarkerMouseOver(view, elt, diagnostics);
return elt;
}
}
function trackHoverOn(view, marker) {
let mousemove = (event) => {
let rect = marker.getBoundingClientRect();
if (event.clientX > rect.left - 10 /* Margin */ && event.clientX < rect.right + 10 /* Margin */ &&
event.clientY > rect.top - 10 /* Margin */ && event.clientY < rect.bottom + 10 /* Margin */)
return;
for (let target = event.target; target; target = target.parentNode) {
if (target.nodeType == 1 && target.classList.contains("cm-tooltip-lint"))
return;
}
window.removeEventListener("mousemove", mousemove);
if (view.state.field(lintGutterTooltip))
view.dispatch({ effects: setLintGutterTooltip.of(null) });
};
window.addEventListener("mousemove", mousemove);
}
function gutterMarkerMouseOver(view, marker, diagnostics) {
function hovered() {
let line = view.elementAtHeight(marker.getBoundingClientRect().top + 5 - view.documentTop);
const linePos = view.coordsAtPos(line.from);
if (linePos) {
view.dispatch({ effects: setLintGutterTooltip.of({
pos: line.from,
above: false,
create() {
return {
dom: diagnosticsTooltip(view, diagnostics),
getCoords: () => marker.getBoundingClientRect()
};
}
}) });
}
marker.onmouseout = marker.onmousemove = null;
trackHoverOn(view, marker);
}
let { hoverTime } = view.state.facet(lintGutterConfig);
let hoverTimeout = setTimeout(hovered, hoverTime);
marker.onmouseout = () => {
clearTimeout(hoverTimeout);
marker.onmouseout = marker.onmousemove = null;
};
marker.onmousemove = () => {
clearTimeout(hoverTimeout);
hoverTimeout = setTimeout(hovered, hoverTime);
};
}
function markersForDiagnostics(doc, diagnostics) {
let byLine = Object.create(null);
for (let diagnostic of diagnostics) {
let line = doc.lineAt(diagnostic.from);
(byLine[line.from] || (byLine[line.from] = [])).push(diagnostic);
}
let markers = [];
for (let line in byLine) {
markers.push(new LintGutterMarker(byLine[line]).range(+line));
}
return state.RangeSet.of(markers, true);
}
const lintGutterExtension = view.gutter({
class: "cm-gutter-lint",
markers: view => view.state.field(lintGutterMarkers),
});
const lintGutterMarkers = state.StateField.define({
create() {
return state.RangeSet.empty;
},
update(markers, tr) {
markers = markers.map(tr.changes);
let diagnosticFilter = tr.state.facet(lintGutterConfig).markerFilter;
for (let effect of tr.effects) {
if (effect.is(setDiagnosticsEffect)) {
let diagnostics = effect.value;
if (diagnosticFilter)
diagnostics = diagnosticFilter(diagnostics || []);
markers = markersForDiagnostics(tr.state.doc, diagnostics.slice(0));
}
}
return markers;
}
});
const setLintGutterTooltip = state.StateEffect.define();
const lintGutterTooltip = state.StateField.define({
create() { return null; },
update(tooltip, tr) {
if (tooltip && tr.docChanged)
tooltip = hideTooltip(tr, tooltip) ? null : Object.assign(Object.assign({}, tooltip), { pos: tr.changes.mapPos(tooltip.pos) });
return tr.effects.reduce((t, e) => e.is(setLintGutterTooltip) ? e.value : t, tooltip);
},
provide: field => view.showTooltip.from(field)
});
const lintGutterTheme = view.EditorView.baseTheme({
".cm-gutter-lint": {
width: "1.4em",
"& .cm-gutterElement": {
padding: ".2em"
}
},
".cm-lint-marker": {
width: "1em",
height: "1em"
},
".cm-lint-marker-info": {
content: svg(`<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>`)
},
".cm-lint-marker-warning": {
content: svg(`<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`),
},
".cm-lint-marker-error:before": {
content: svg(`<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`)
},
});
const lintGutterConfig = state.Facet.define({
combine(configs) {
return state.combineConfig(configs, {
hoverTime: 300 /* Time */,
markerFilter: null,
tooltipFilter: null
});
}
});
/**
Returns an extension that installs a gutter showing markers for
each line that has diagnostics, which can be hovered over to see
the diagnostics.
*/
function lintGutter(config = {}) {
return [lintGutterConfig.of(config), lintGutterMarkers, lintGutterExtension, lintGutterTheme, lintGutterTooltip];
}
exports.closeLintPanel = closeLintPanel;
exports.diagnosticCount = diagnosticCount;
exports.forceLinting = forceLinting;
exports.lintGutter = lintGutter;
exports.lintKeymap = lintKeymap;
exports.linter = linter;
exports.nextDiagnostic = nextDiagnostic;
exports.openLintPanel = openLintPanel;
exports.setDiagnostics = setDiagnostics;
exports.setDiagnosticsEffect = setDiagnosticsEffect;

View File

@ -0,0 +1,149 @@
import * as _codemirror_state from '@codemirror/state';
import { EditorState, TransactionSpec, Extension } from '@codemirror/state';
import { EditorView, Command, KeyBinding } from '@codemirror/view';
/**
Describes a problem or hint for a piece of code.
*/
interface Diagnostic {
/**
The start position of the relevant text.
*/
from: number;
/**
The end position. May be equal to `from`, though actually
covering text is preferable.
*/
to: number;
/**
The severity of the problem. This will influence how it is
displayed.
*/
severity: "info" | "warning" | "error";
/**
An optional source string indicating where the diagnostic is
coming from. You can put the name of your linter here, if
applicable.
*/
source?: string;
/**
The message associated with this diagnostic.
*/
message: string;
/**
An optional custom rendering function that displays the message
as a DOM node.
*/
renderMessage?: () => Node;
/**
An optional array of actions that can be taken on this
diagnostic.
*/
actions?: readonly Action[];
}
/**
An action associated with a diagnostic.
*/
interface Action {
/**
The label to show to the user. Should be relatively short.
*/
name: string;
/**
The function to call when the user activates this action. Is
given the diagnostic's _current_ position, which may have
changed since the creation of the diagnostic, due to editing.
*/
apply: (view: EditorView, from: number, to: number) => void;
}
declare type DiagnosticFilter = (diagnostics: readonly Diagnostic[]) => Diagnostic[];
interface LintConfig {
/**
Time to wait (in milliseconds) after a change before running
the linter. Defaults to 750ms.
*/
delay?: number;
/**
Optional filter to determine which diagnostics produce markers
in the content.
*/
markerFilter?: null | DiagnosticFilter;
/**
Filter applied to a set of diagnostics shown in a tooltip. No
tooltip will appear if the empty set is returned.
*/
tooltipFilter?: null | DiagnosticFilter;
}
interface LintGutterConfig {
/**
The delay before showing a tooltip when hovering over a lint gutter marker.
*/
hoverTime?: number;
/**
Optional filter determining which diagnostics show a marker in
the gutter.
*/
markerFilter?: null | DiagnosticFilter;
/**
Optional filter for diagnostics displayed in a tooltip, which
can also be used to prevent a tooltip appearing.
*/
tooltipFilter?: null | DiagnosticFilter;
}
/**
Returns a transaction spec which updates the current set of
diagnostics, and enables the lint extension if if wasn't already
active.
*/
declare function setDiagnostics(state: EditorState, diagnostics: readonly Diagnostic[]): TransactionSpec;
/**
The state effect that updates the set of active diagnostics. Can
be useful when writing an extension that needs to track these.
*/
declare const setDiagnosticsEffect: _codemirror_state.StateEffectType<readonly Diagnostic[]>;
/**
Returns the number of active lint diagnostics in the given state.
*/
declare function diagnosticCount(state: EditorState): number;
/**
Command to open and focus the lint panel.
*/
declare const openLintPanel: Command;
/**
Command to close the lint panel, when open.
*/
declare const closeLintPanel: Command;
/**
Move the selection to the next diagnostic.
*/
declare const nextDiagnostic: Command;
/**
A set of default key bindings for the lint functionality.
- Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel)
- F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic)
*/
declare const lintKeymap: readonly KeyBinding[];
/**
The type of a function that produces diagnostics.
*/
declare type LintSource = (view: EditorView) => readonly Diagnostic[] | Promise<readonly Diagnostic[]>;
/**
Given a diagnostic source, this function returns an extension that
enables linting with that source. It will be called whenever the
editor is idle (after its content changed).
*/
declare function linter(source: LintSource, config?: LintConfig): Extension;
/**
Forces any linters [configured](https://codemirror.net/6/docs/ref/#lint.linter) to run when the
editor is idle to run right away.
*/
declare function forceLinting(view: EditorView): void;
/**
Returns an extension that installs a gutter showing markers for
each line that has diagnostics, which can be hovered over to see
the diagnostics.
*/
declare function lintGutter(config?: LintGutterConfig): Extension;
export { Action, Diagnostic, LintSource, closeLintPanel, diagnosticCount, forceLinting, lintGutter, lintKeymap, linter, nextDiagnostic, openLintPanel, setDiagnostics, setDiagnosticsEffect };

View File

@ -0,0 +1,732 @@
import { Decoration, showPanel, EditorView, ViewPlugin, hoverTooltip, logException, gutter, showTooltip, getPanel, WidgetType, GutterMarker } from '@codemirror/view';
import { StateEffect, StateField, Facet, combineConfig, RangeSet } from '@codemirror/state';
import elt from 'crelt';
class SelectedDiagnostic {
constructor(from, to, diagnostic) {
this.from = from;
this.to = to;
this.diagnostic = diagnostic;
}
}
class LintState {
constructor(diagnostics, panel, selected) {
this.diagnostics = diagnostics;
this.panel = panel;
this.selected = selected;
}
static init(diagnostics, panel, state) {
// Filter the list of diagnostics for which to create markers
let markedDiagnostics = diagnostics;
let diagnosticFilter = state.facet(lintConfig).markerFilter;
if (diagnosticFilter)
markedDiagnostics = diagnosticFilter(markedDiagnostics);
let ranges = Decoration.set(markedDiagnostics.map((d) => {
// For zero-length ranges or ranges covering only a line break, create a widget
return d.from == d.to || (d.from == d.to - 1 && state.doc.lineAt(d.from).to == d.from)
? Decoration.widget({
widget: new DiagnosticWidget(d),
diagnostic: d
}).range(d.from)
: Decoration.mark({
attributes: { class: "cm-lintRange cm-lintRange-" + d.severity },
diagnostic: d
}).range(d.from, d.to);
}), true);
return new LintState(ranges, panel, findDiagnostic(ranges));
}
}
function findDiagnostic(diagnostics, diagnostic = null, after = 0) {
let found = null;
diagnostics.between(after, 1e9, (from, to, { spec }) => {
if (diagnostic && spec.diagnostic != diagnostic)
return;
found = new SelectedDiagnostic(from, to, spec.diagnostic);
return false;
});
return found;
}
function hideTooltip(tr, tooltip) {
return !!(tr.effects.some(e => e.is(setDiagnosticsEffect)) || tr.changes.touchesRange(tooltip.pos));
}
function maybeEnableLint(state, effects) {
return state.field(lintState, false) ? effects : effects.concat(StateEffect.appendConfig.of([
lintState,
EditorView.decorations.compute([lintState], state => {
let { selected, panel } = state.field(lintState);
return !selected || !panel || selected.from == selected.to ? Decoration.none : Decoration.set([
activeMark.range(selected.from, selected.to)
]);
}),
hoverTooltip(lintTooltip, { hideOn: hideTooltip }),
baseTheme
]));
}
/**
Returns a transaction spec which updates the current set of
diagnostics, and enables the lint extension if if wasn't already
active.
*/
function setDiagnostics(state, diagnostics) {
return {
effects: maybeEnableLint(state, [setDiagnosticsEffect.of(diagnostics)])
};
}
/**
The state effect that updates the set of active diagnostics. Can
be useful when writing an extension that needs to track these.
*/
const setDiagnosticsEffect = /*@__PURE__*/StateEffect.define();
const togglePanel = /*@__PURE__*/StateEffect.define();
const movePanelSelection = /*@__PURE__*/StateEffect.define();
const lintState = /*@__PURE__*/StateField.define({
create() {
return new LintState(Decoration.none, null, null);
},
update(value, tr) {
if (tr.docChanged) {
let mapped = value.diagnostics.map(tr.changes), selected = null;
if (value.selected) {
let selPos = tr.changes.mapPos(value.selected.from, 1);
selected = findDiagnostic(mapped, value.selected.diagnostic, selPos) || findDiagnostic(mapped, null, selPos);
}
value = new LintState(mapped, value.panel, selected);
}
for (let effect of tr.effects) {
if (effect.is(setDiagnosticsEffect)) {
value = LintState.init(effect.value, value.panel, tr.state);
}
else if (effect.is(togglePanel)) {
value = new LintState(value.diagnostics, effect.value ? LintPanel.open : null, value.selected);
}
else if (effect.is(movePanelSelection)) {
value = new LintState(value.diagnostics, value.panel, effect.value);
}
}
return value;
},
provide: f => [showPanel.from(f, val => val.panel),
EditorView.decorations.from(f, s => s.diagnostics)]
});
/**
Returns the number of active lint diagnostics in the given state.
*/
function diagnosticCount(state) {
let lint = state.field(lintState, false);
return lint ? lint.diagnostics.size : 0;
}
const activeMark = /*@__PURE__*/Decoration.mark({ class: "cm-lintRange cm-lintRange-active" });
function lintTooltip(view, pos, side) {
let { diagnostics } = view.state.field(lintState);
let found = [], stackStart = 2e8, stackEnd = 0;
diagnostics.between(pos - (side < 0 ? 1 : 0), pos + (side > 0 ? 1 : 0), (from, to, { spec }) => {
if (pos >= from && pos <= to &&
(from == to || ((pos > from || side > 0) && (pos < to || side < 0)))) {
found.push(spec.diagnostic);
stackStart = Math.min(from, stackStart);
stackEnd = Math.max(to, stackEnd);
}
});
let diagnosticFilter = view.state.facet(lintConfig).tooltipFilter;
if (diagnosticFilter)
found = diagnosticFilter(found);
if (!found.length)
return null;
return {
pos: stackStart,
end: stackEnd,
above: view.state.doc.lineAt(stackStart).to < stackEnd,
create() {
return { dom: diagnosticsTooltip(view, found) };
}
};
}
function diagnosticsTooltip(view, diagnostics) {
return elt("ul", { class: "cm-tooltip-lint" }, diagnostics.map(d => renderDiagnostic(view, d, false)));
}
/**
Command to open and focus the lint panel.
*/
const openLintPanel = (view) => {
let field = view.state.field(lintState, false);
if (!field || !field.panel)
view.dispatch({ effects: maybeEnableLint(view.state, [togglePanel.of(true)]) });
let panel = getPanel(view, LintPanel.open);
if (panel)
panel.dom.querySelector(".cm-panel-lint ul").focus();
return true;
};
/**
Command to close the lint panel, when open.
*/
const closeLintPanel = (view) => {
let field = view.state.field(lintState, false);
if (!field || !field.panel)
return false;
view.dispatch({ effects: togglePanel.of(false) });
return true;
};
/**
Move the selection to the next diagnostic.
*/
const nextDiagnostic = (view) => {
let field = view.state.field(lintState, false);
if (!field)
return false;
let sel = view.state.selection.main, next = field.diagnostics.iter(sel.to + 1);
if (!next.value) {
next = field.diagnostics.iter(0);
if (!next.value || next.from == sel.from && next.to == sel.to)
return false;
}
view.dispatch({ selection: { anchor: next.from, head: next.to }, scrollIntoView: true });
return true;
};
/**
A set of default key bindings for the lint functionality.
- Ctrl-Shift-m (Cmd-Shift-m on macOS): [`openLintPanel`](https://codemirror.net/6/docs/ref/#lint.openLintPanel)
- F8: [`nextDiagnostic`](https://codemirror.net/6/docs/ref/#lint.nextDiagnostic)
*/
const lintKeymap = [
{ key: "Mod-Shift-m", run: openLintPanel },
{ key: "F8", run: nextDiagnostic }
];
const lintPlugin = /*@__PURE__*/ViewPlugin.fromClass(class {
constructor(view) {
this.view = view;
this.timeout = -1;
this.set = true;
let { delay } = view.state.facet(lintConfig);
this.lintTime = Date.now() + delay;
this.run = this.run.bind(this);
this.timeout = setTimeout(this.run, delay);
}
run() {
let now = Date.now();
if (now < this.lintTime - 10) {
setTimeout(this.run, this.lintTime - now);
}
else {
this.set = false;
let { state } = this.view, { sources } = state.facet(lintConfig);
Promise.all(sources.map(source => Promise.resolve(source(this.view)))).then(annotations => {
let all = annotations.reduce((a, b) => a.concat(b));
if (this.view.state.doc == state.doc)
this.view.dispatch(setDiagnostics(this.view.state, all));
}, error => { logException(this.view.state, error); });
}
}
update(update) {
let config = update.state.facet(lintConfig);
if (update.docChanged || config != update.startState.facet(lintConfig)) {
this.lintTime = Date.now() + config.delay;
if (!this.set) {
this.set = true;
this.timeout = setTimeout(this.run, config.delay);
}
}
}
force() {
if (this.set) {
this.lintTime = Date.now();
this.run();
}
}
destroy() {
clearTimeout(this.timeout);
}
});
const lintConfig = /*@__PURE__*/Facet.define({
combine(input) {
return Object.assign({ sources: input.map(i => i.source) }, combineConfig(input.map(i => i.config), {
delay: 750,
markerFilter: null,
tooltipFilter: null
}));
},
enables: lintPlugin
});
/**
Given a diagnostic source, this function returns an extension that
enables linting with that source. It will be called whenever the
editor is idle (after its content changed).
*/
function linter(source, config = {}) {
return lintConfig.of({ source, config });
}
/**
Forces any linters [configured](https://codemirror.net/6/docs/ref/#lint.linter) to run when the
editor is idle to run right away.
*/
function forceLinting(view) {
let plugin = view.plugin(lintPlugin);
if (plugin)
plugin.force();
}
function assignKeys(actions) {
let assigned = [];
if (actions)
actions: for (let { name } of actions) {
for (let i = 0; i < name.length; i++) {
let ch = name[i];
if (/[a-zA-Z]/.test(ch) && !assigned.some(c => c.toLowerCase() == ch.toLowerCase())) {
assigned.push(ch);
continue actions;
}
}
assigned.push("");
}
return assigned;
}
function renderDiagnostic(view, diagnostic, inPanel) {
var _a;
let keys = inPanel ? assignKeys(diagnostic.actions) : [];
return elt("li", { class: "cm-diagnostic cm-diagnostic-" + diagnostic.severity }, elt("span", { class: "cm-diagnosticText" }, diagnostic.renderMessage ? diagnostic.renderMessage() : diagnostic.message), (_a = diagnostic.actions) === null || _a === void 0 ? void 0 : _a.map((action, i) => {
let click = (e) => {
e.preventDefault();
let found = findDiagnostic(view.state.field(lintState).diagnostics, diagnostic);
if (found)
action.apply(view, found.from, found.to);
};
let { name } = action, keyIndex = keys[i] ? name.indexOf(keys[i]) : -1;
let nameElt = keyIndex < 0 ? name : [name.slice(0, keyIndex),
elt("u", name.slice(keyIndex, keyIndex + 1)),
name.slice(keyIndex + 1)];
return elt("button", {
type: "button",
class: "cm-diagnosticAction",
onclick: click,
onmousedown: click,
"aria-label": ` Action: ${name}${keyIndex < 0 ? "" : ` (access key "${keys[i]})"`}.`
}, nameElt);
}), diagnostic.source && elt("div", { class: "cm-diagnosticSource" }, diagnostic.source));
}
class DiagnosticWidget extends WidgetType {
constructor(diagnostic) {
super();
this.diagnostic = diagnostic;
}
eq(other) { return other.diagnostic == this.diagnostic; }
toDOM() {
return elt("span", { class: "cm-lintPoint cm-lintPoint-" + this.diagnostic.severity });
}
}
class PanelItem {
constructor(view, diagnostic) {
this.diagnostic = diagnostic;
this.id = "item_" + Math.floor(Math.random() * 0xffffffff).toString(16);
this.dom = renderDiagnostic(view, diagnostic, true);
this.dom.id = this.id;
this.dom.setAttribute("role", "option");
}
}
class LintPanel {
constructor(view) {
this.view = view;
this.items = [];
let onkeydown = (event) => {
if (event.keyCode == 27) { // Escape
closeLintPanel(this.view);
this.view.focus();
}
else if (event.keyCode == 38 || event.keyCode == 33) { // ArrowUp, PageUp
this.moveSelection((this.selectedIndex - 1 + this.items.length) % this.items.length);
}
else if (event.keyCode == 40 || event.keyCode == 34) { // ArrowDown, PageDown
this.moveSelection((this.selectedIndex + 1) % this.items.length);
}
else if (event.keyCode == 36) { // Home
this.moveSelection(0);
}
else if (event.keyCode == 35) { // End
this.moveSelection(this.items.length - 1);
}
else if (event.keyCode == 13) { // Enter
this.view.focus();
}
else if (event.keyCode >= 65 && event.keyCode <= 90 && this.selectedIndex >= 0) { // A-Z
let { diagnostic } = this.items[this.selectedIndex], keys = assignKeys(diagnostic.actions);
for (let i = 0; i < keys.length; i++)
if (keys[i].toUpperCase().charCodeAt(0) == event.keyCode) {
let found = findDiagnostic(this.view.state.field(lintState).diagnostics, diagnostic);
if (found)
diagnostic.actions[i].apply(view, found.from, found.to);
}
}
else {
return;
}
event.preventDefault();
};
let onclick = (event) => {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].dom.contains(event.target))
this.moveSelection(i);
}
};
this.list = elt("ul", {
tabIndex: 0,
role: "listbox",
"aria-label": this.view.state.phrase("Diagnostics"),
onkeydown,
onclick
});
this.dom = elt("div", { class: "cm-panel-lint" }, this.list, elt("button", {
type: "button",
name: "close",
"aria-label": this.view.state.phrase("close"),
onclick: () => closeLintPanel(this.view)
}, "×"));
this.update();
}
get selectedIndex() {
let selected = this.view.state.field(lintState).selected;
if (!selected)
return -1;
for (let i = 0; i < this.items.length; i++)
if (this.items[i].diagnostic == selected.diagnostic)
return i;
return -1;
}
update() {
let { diagnostics, selected } = this.view.state.field(lintState);
let i = 0, needsSync = false, newSelectedItem = null;
diagnostics.between(0, this.view.state.doc.length, (_start, _end, { spec }) => {
let found = -1, item;
for (let j = i; j < this.items.length; j++)
if (this.items[j].diagnostic == spec.diagnostic) {
found = j;
break;
}
if (found < 0) {
item = new PanelItem(this.view, spec.diagnostic);
this.items.splice(i, 0, item);
needsSync = true;
}
else {
item = this.items[found];
if (found > i) {
this.items.splice(i, found - i);
needsSync = true;
}
}
if (selected && item.diagnostic == selected.diagnostic) {
if (!item.dom.hasAttribute("aria-selected")) {
item.dom.setAttribute("aria-selected", "true");
newSelectedItem = item;
}
}
else if (item.dom.hasAttribute("aria-selected")) {
item.dom.removeAttribute("aria-selected");
}
i++;
});
while (i < this.items.length && !(this.items.length == 1 && this.items[0].diagnostic.from < 0)) {
needsSync = true;
this.items.pop();
}
if (this.items.length == 0) {
this.items.push(new PanelItem(this.view, {
from: -1, to: -1,
severity: "info",
message: this.view.state.phrase("No diagnostics")
}));
needsSync = true;
}
if (newSelectedItem) {
this.list.setAttribute("aria-activedescendant", newSelectedItem.id);
this.view.requestMeasure({
key: this,
read: () => ({ sel: newSelectedItem.dom.getBoundingClientRect(), panel: this.list.getBoundingClientRect() }),
write: ({ sel, panel }) => {
if (sel.top < panel.top)
this.list.scrollTop -= panel.top - sel.top;
else if (sel.bottom > panel.bottom)
this.list.scrollTop += sel.bottom - panel.bottom;
}
});
}
else if (this.selectedIndex < 0) {
this.list.removeAttribute("aria-activedescendant");
}
if (needsSync)
this.sync();
}
sync() {
let domPos = this.list.firstChild;
function rm() {
let prev = domPos;
domPos = prev.nextSibling;
prev.remove();
}
for (let item of this.items) {
if (item.dom.parentNode == this.list) {
while (domPos != item.dom)
rm();
domPos = item.dom.nextSibling;
}
else {
this.list.insertBefore(item.dom, domPos);
}
}
while (domPos)
rm();
}
moveSelection(selectedIndex) {
if (this.selectedIndex < 0)
return;
let field = this.view.state.field(lintState);
let selection = findDiagnostic(field.diagnostics, this.items[selectedIndex].diagnostic);
if (!selection)
return;
this.view.dispatch({
selection: { anchor: selection.from, head: selection.to },
scrollIntoView: true,
effects: movePanelSelection.of(selection)
});
}
static open(view) { return new LintPanel(view); }
}
function svg(content, attrs = `viewBox="0 0 40 40"`) {
return `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${attrs}>${encodeURIComponent(content)}</svg>')`;
}
function underline(color) {
return svg(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${color}" fill="none" stroke-width=".7"/>`, `width="6" height="3"`);
}
const baseTheme = /*@__PURE__*/EditorView.baseTheme({
".cm-diagnostic": {
padding: "3px 6px 3px 8px",
marginLeft: "-1px",
display: "block",
whiteSpace: "pre-wrap"
},
".cm-diagnostic-error": { borderLeft: "5px solid #d11" },
".cm-diagnostic-warning": { borderLeft: "5px solid orange" },
".cm-diagnostic-info": { borderLeft: "5px solid #999" },
".cm-diagnosticAction": {
font: "inherit",
border: "none",
padding: "2px 4px",
backgroundColor: "#444",
color: "white",
borderRadius: "3px",
marginLeft: "8px"
},
".cm-diagnosticSource": {
fontSize: "70%",
opacity: .7
},
".cm-lintRange": {
backgroundPosition: "left bottom",
backgroundRepeat: "repeat-x",
paddingBottom: "0.7px",
},
".cm-lintRange-error": { backgroundImage: /*@__PURE__*/underline("#d11") },
".cm-lintRange-warning": { backgroundImage: /*@__PURE__*/underline("orange") },
".cm-lintRange-info": { backgroundImage: /*@__PURE__*/underline("#999") },
".cm-lintRange-active": { backgroundColor: "#ffdd9980" },
".cm-tooltip-lint": {
padding: 0,
margin: 0
},
".cm-lintPoint": {
position: "relative",
"&:after": {
content: '""',
position: "absolute",
bottom: 0,
left: "-2px",
borderLeft: "3px solid transparent",
borderRight: "3px solid transparent",
borderBottom: "4px solid #d11"
}
},
".cm-lintPoint-warning": {
"&:after": { borderBottomColor: "orange" }
},
".cm-lintPoint-info": {
"&:after": { borderBottomColor: "#999" }
},
".cm-panel.cm-panel-lint": {
position: "relative",
"& ul": {
maxHeight: "100px",
overflowY: "auto",
"& [aria-selected]": {
backgroundColor: "#ddd",
"& u": { textDecoration: "underline" }
},
"&:focus [aria-selected]": {
background_fallback: "#bdf",
backgroundColor: "Highlight",
color_fallback: "white",
color: "HighlightText"
},
"& u": { textDecoration: "none" },
padding: 0,
margin: 0
},
"& [name=close]": {
position: "absolute",
top: "0",
right: "2px",
background: "inherit",
border: "none",
font: "inherit",
padding: 0,
margin: 0
}
}
});
class LintGutterMarker extends GutterMarker {
constructor(diagnostics) {
super();
this.diagnostics = diagnostics;
this.severity = diagnostics.reduce((max, d) => {
let s = d.severity;
return s == "error" || s == "warning" && max == "info" ? s : max;
}, "info");
}
toDOM(view) {
let elt = document.createElement("div");
elt.className = "cm-lint-marker cm-lint-marker-" + this.severity;
let diagnostics = this.diagnostics;
let diagnosticsFilter = view.state.facet(lintGutterConfig).tooltipFilter;
if (diagnosticsFilter)
diagnostics = diagnosticsFilter(diagnostics);
if (diagnostics.length)
elt.onmouseover = () => gutterMarkerMouseOver(view, elt, diagnostics);
return elt;
}
}
function trackHoverOn(view, marker) {
let mousemove = (event) => {
let rect = marker.getBoundingClientRect();
if (event.clientX > rect.left - 10 /* Margin */ && event.clientX < rect.right + 10 /* Margin */ &&
event.clientY > rect.top - 10 /* Margin */ && event.clientY < rect.bottom + 10 /* Margin */)
return;
for (let target = event.target; target; target = target.parentNode) {
if (target.nodeType == 1 && target.classList.contains("cm-tooltip-lint"))
return;
}
window.removeEventListener("mousemove", mousemove);
if (view.state.field(lintGutterTooltip))
view.dispatch({ effects: setLintGutterTooltip.of(null) });
};
window.addEventListener("mousemove", mousemove);
}
function gutterMarkerMouseOver(view, marker, diagnostics) {
function hovered() {
let line = view.elementAtHeight(marker.getBoundingClientRect().top + 5 - view.documentTop);
const linePos = view.coordsAtPos(line.from);
if (linePos) {
view.dispatch({ effects: setLintGutterTooltip.of({
pos: line.from,
above: false,
create() {
return {
dom: diagnosticsTooltip(view, diagnostics),
getCoords: () => marker.getBoundingClientRect()
};
}
}) });
}
marker.onmouseout = marker.onmousemove = null;
trackHoverOn(view, marker);
}
let { hoverTime } = view.state.facet(lintGutterConfig);
let hoverTimeout = setTimeout(hovered, hoverTime);
marker.onmouseout = () => {
clearTimeout(hoverTimeout);
marker.onmouseout = marker.onmousemove = null;
};
marker.onmousemove = () => {
clearTimeout(hoverTimeout);
hoverTimeout = setTimeout(hovered, hoverTime);
};
}
function markersForDiagnostics(doc, diagnostics) {
let byLine = Object.create(null);
for (let diagnostic of diagnostics) {
let line = doc.lineAt(diagnostic.from);
(byLine[line.from] || (byLine[line.from] = [])).push(diagnostic);
}
let markers = [];
for (let line in byLine) {
markers.push(new LintGutterMarker(byLine[line]).range(+line));
}
return RangeSet.of(markers, true);
}
const lintGutterExtension = /*@__PURE__*/gutter({
class: "cm-gutter-lint",
markers: view => view.state.field(lintGutterMarkers),
});
const lintGutterMarkers = /*@__PURE__*/StateField.define({
create() {
return RangeSet.empty;
},
update(markers, tr) {
markers = markers.map(tr.changes);
let diagnosticFilter = tr.state.facet(lintGutterConfig).markerFilter;
for (let effect of tr.effects) {
if (effect.is(setDiagnosticsEffect)) {
let diagnostics = effect.value;
if (diagnosticFilter)
diagnostics = diagnosticFilter(diagnostics || []);
markers = markersForDiagnostics(tr.state.doc, diagnostics.slice(0));
}
}
return markers;
}
});
const setLintGutterTooltip = /*@__PURE__*/StateEffect.define();
const lintGutterTooltip = /*@__PURE__*/StateField.define({
create() { return null; },
update(tooltip, tr) {
if (tooltip && tr.docChanged)
tooltip = hideTooltip(tr, tooltip) ? null : Object.assign(Object.assign({}, tooltip), { pos: tr.changes.mapPos(tooltip.pos) });
return tr.effects.reduce((t, e) => e.is(setLintGutterTooltip) ? e.value : t, tooltip);
},
provide: field => showTooltip.from(field)
});
const lintGutterTheme = /*@__PURE__*/EditorView.baseTheme({
".cm-gutter-lint": {
width: "1.4em",
"& .cm-gutterElement": {
padding: ".2em"
}
},
".cm-lint-marker": {
width: "1em",
height: "1em"
},
".cm-lint-marker-info": {
content: /*@__PURE__*/svg(`<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>`)
},
".cm-lint-marker-warning": {
content: /*@__PURE__*/svg(`<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>`),
},
".cm-lint-marker-error:before": {
content: /*@__PURE__*/svg(`<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>`)
},
});
const lintGutterConfig = /*@__PURE__*/Facet.define({
combine(configs) {
return combineConfig(configs, {
hoverTime: 300 /* Time */,
markerFilter: null,
tooltipFilter: null
});
}
});
/**
Returns an extension that installs a gutter showing markers for
each line that has diagnostics, which can be hovered over to see
the diagnostics.
*/
function lintGutter(config = {}) {
return [lintGutterConfig.of(config), lintGutterMarkers, lintGutterExtension, lintGutterTheme, lintGutterTooltip];
}
export { closeLintPanel, diagnosticCount, forceLinting, lintGutter, lintKeymap, linter, nextDiagnostic, openLintPanel, setDiagnostics, setDiagnosticsEffect };

View File

@ -0,0 +1,40 @@
{
"name": "@codemirror/lint",
"version": "0.20.3",
"description": "Linting support for the CodeMirror code editor",
"scripts": {
"test": "cm-runtests",
"prepare": "cm-buildhelper src/lint.ts"
},
"keywords": [
"editor",
"code"
],
"author": {
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"url": "http://marijnhaverbeke.nl"
},
"type": "module",
"main": "dist/index.cjs",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"types": "dist/index.d.ts",
"module": "dist/index.js",
"sideEffects": false,
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.2",
"crelt": "^1.0.5"
},
"devDependencies": {
"@codemirror/buildhelper": "^0.1.0"
},
"repository": {
"type": "git",
"url": "https://github.com/codemirror/lint.git"
}
}

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: codemirror.next
owner: codemirror
event_type: push

View File

@ -0,0 +1,164 @@
## 0.20.1 (2022-06-02)
### New features
`EditorView.phrase` now accepts additional arguments, which it will interpolate into the phrase in the place of `$` markers.
## 0.20.0 (2022-04-20)
### Breaking changes
The deprecated precedence names `fallback`, `extend`, and `override` were removed from the library.
### Bug fixes
Fix a bug where, if an extension value occurs multiple times, its lowest, rather than highest precedence is used.
Fix an issue where facets with computed inputs would unneccesarily have their outputs recreated on state reconfiguration.
Fix a bug in the order in which new values for state fields and facets were computed, which could cause dynamic facets to hold the wrong value in some situations.
### New features
The exports from @codemirror/rangeset now live in this package.
The exports from @codemirror/text now live in this package.
## 0.19.9 (2022-02-16)
### Bug fixes
Mapping a non-empty selection range now always puts any newly inserted text on the sides of the range outside of the mapped version.
## 0.19.8 (2022-02-15)
### Bug fixes
Fix a bug where facet values with computed inputs could incorrectly retain their old value on reconfiguration.
## 0.19.7 (2022-02-11)
### Bug fixes
Avoid recomputing facets on state reconfiguration if that facet's inputs stayed precisely the same.
Selection ranges created with `EditorSelection.range` will now have an assoc pointing at their anchor, when non-empty.
## 0.19.6 (2021-11-19)
### Bug fixes
Fix a bug that caused facet compare functions to be called with an invalid value in some situations.
Fix a bug that caused dynamic facet values to be incorrectly kept unchanged when reconfiguration changed one of their dependencies.
## 0.19.5 (2021-11-10)
### Bug fixes
Fix a bug that would cause dynamic facet values influenced by a state reconfiguration to not properly recompute.
## 0.19.4 (2021-11-05)
### Bug fixes
When reconfiguring a state, effects from the reconfiguring transaction can now be seen by newly added state fields.
## 0.19.3 (2021-11-03)
### New features
The precedence levels (under `Prec`) now have more generic names, because their 'meaningful' names were entirely inappropriate in many situations.
## 0.19.2 (2021-09-13)
### New features
The editor state now has a `readOnly` property with a matching facet to control its value.
## 0.19.1 (2021-08-15)
### Bug fixes
Fix a bug where `wordAt` never returned a useful result.
## 0.19.0 (2021-08-11)
### Breaking changes
User event strings now work differently—the events emitted by the core packages follow a different system, and hierarchical event tags can be created by separating the words with dots.
### New features
`languageDataAt` now takes an optional `side` argument to specificy which side of the position you're interested in.
It is now possible to add a user event annotation with a direct `userEvent` property on a transaction spec.
Transactions now have an `isUserEvent` method that can be used to check if it is (a subtype of) some user event type.
## 0.18.7 (2021-05-04)
### Bug fixes
Fix an issue where state fields might be initialized with a state that they aren't actually part of during reconfiguration.
## 0.18.6 (2021-04-12)
### New features
The new `EditorState.wordAt` method finds the word at a given position.
## 0.18.5 (2021-04-08)
### Bug fixes
Fix an issue in the compiled output that would break the code when minified with terser.
## 0.18.4 (2021-04-06)
### New features
The new `Transaction.remote` annotation can be used to mark and recognize transactions created by other actors.
## 0.18.3 (2021-03-23)
### New features
The `ChangeDesc` class now has `toJSON` and `fromJSON` methods.
## 0.18.2 (2021-03-14)
### Bug fixes
Fix unintended ES2020 output (the package contains ES6 code again).
## 0.18.1 (2021-03-10)
### New features
The new `Compartment.get` method can be used to get the content of a compartment in a given state.
## 0.18.0 (2021-03-03)
### Breaking changes
`tagExtension` and the `reconfigure` transaction spec property have been replaced with the concept of configuration compartments and reconfiguration effects (see `Compartment`, `StateEffect.reconfigure`, and `StateEffect.appendConfig`).
## 0.17.2 (2021-02-19)
### New features
`EditorSelection.map` and `SelectionRange.map` now take an optional second argument to indicate which direction to map to.
## 0.17.1 (2021-01-06)
### New features
The package now also exports a CommonJS module.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,18 @@
# @codemirror/state [![NPM version](https://img.shields.io/npm/v/@codemirror/state.svg)](https://www.npmjs.org/package/@codemirror/state)
[ [**WEBSITE**](https://codemirror.net/6/) | [**DOCS**](https://codemirror.net/6/docs/ref/#state) | [**ISSUES**](https://github.com/codemirror/codemirror.next/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/state/blob/main/CHANGELOG.md) ]
This package implements the editor state data structures for the
[CodeMirror](https://codemirror.net/6/) code editor.
The [project page](https://codemirror.net/6/) has more information, a
number of [examples](https://codemirror.net/6/examples/) and the
[documentation](https://codemirror.net/6/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/state/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
{
"name": "@codemirror/state",
"version": "0.20.1",
"description": "Editor state data structures for the CodeMirror code editor",
"scripts": {
"test": "cm-runtests",
"prepare": "cm-buildhelper src/index.ts"
},
"keywords": [
"editor",
"code"
],
"author": {
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"url": "http://marijnhaverbeke.nl"
},
"type": "module",
"main": "dist/index.cjs",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"types": "dist/index.d.ts",
"module": "dist/index.js",
"sideEffects": false,
"license": "MIT",
"devDependencies": {
"@codemirror/buildhelper": "^0.1.5"
},
"repository": {
"type": "git",
"url": "https://github.com/codemirror/state.git"
}
}

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: codemirror.next
owner: codemirror
event_type: push

View File

@ -0,0 +1,865 @@
## 0.20.7 (2022-05-30)
### Bug fixes
Fix an issue on Chrome Android where the DOM could fail to display the actual document after backspace.
Avoid an issue on Chrome Android where DOM changes were sometimes inappropriately replace by a backspace key effect due to spurious beforeinput events.
Fix a problem where the content element's width didn't cover the width of the actual content.
Work around a bug in Chrome 102 which caused wheel scrolling of the editor to be interrupted every few lines.
## 0.20.6 (2022-05-20)
### Bug fixes
Make sure the editor re-measures itself when its attributes are updated.
## 0.20.5 (2022-05-18)
### Bug fixes
Fix an issue where gutter elements without any markers in them would not get the `cm-gutterElement` class assigned.
Fix an issue where DOM event handlers registered by plugins were retained indefinitely, even after the editor was reconfigured.
## 0.20.4 (2022-05-03)
### Bug fixes
Prevent Mac-style behavior of inserting a period when the user inserts two spaces.
Fix an issue where the editor would sometimes not restore the DOM selection when refocused with a selection identical to the one it held when it lost focus.
## 0.20.3 (2022-04-27)
### Bug fixes
Fix a bug where the input handling could crash on repeated (or held) backspace presses on Chrome Android.
## 0.20.2 (2022-04-22)
### New features
The new `hideOn` option to `hoverTooltip` allows more fine-grained control over when the tooltip should hide.
## 0.20.1 (2022-04-20)
### Bug fixes
Remove debug statements that accidentally made it into 0.20.0.
Fix a regression in `moveVertically`.
## 0.20.0 (2022-04-20)
### Breaking changes
The deprecated interfaces `blockAtHeight`, `visualLineAtHeight`, `viewportLines`, `visualLineAt`, `scrollPosIntoView`, `scrollTo`, and `centerOn` were removed from the library.
All decorations are now provided through `EditorView.decorations`, and are part of a single precedence ordering. Decoration sources that need access to the view are provided as functions.
Atomic ranges are now specified through a facet (`EditorView.atomicRanges`).
Scroll margins are now specified through a facet (`EditorView.scrollMargins`).
Plugin fields no longer exist in the library (and are replaced by facets holding function values).
This package no longer re-exports the Range type from @codemirror/state.
### Bug fixes
Fix a bug where zero-length block widgets could cause `viewportLineBlocks` to contain overlapping ranges.
### New features
The new `perLineTextDirection` facet configures whether the editor reads text direction per line, or uses a single direction for the entire editor. `EditorView.textDirectionAt` returns the direction around a given position.
`rectangularSelection` and `crosshairCursor` from @codemirror/rectangular-selection were merged into this package.
This package now exports the tooltip functionality that used to live in @codemirror/tooltip.
The exports from the old @codemirror/panel package are now available from this package.
The exports from the old @codemirror/gutter package are now available from this package.
## 0.19.48 (2022-03-30)
### Bug fixes
Fix an issue where DOM syncing could crash when a DOM node was moved from a parent to a child node (via widgets reusing existing nodes).
To avoid interfering with things like a vim mode too much, the editor will now only activate the tab-to-move-focus escape hatch after an escape press that wasn't handled by an event handler.
Make sure the view measures itself before the page is printed.
Tweak types of view plugin defining functions to avoid TypeScript errors when the plugin value doesn't have any of the interface's properties.
## 0.19.47 (2022-03-08)
### Bug fixes
Fix an issue where block widgets at the start of the viewport could break height computations.
## 0.19.46 (2022-03-03)
### Bug fixes
Fix a bug where block widgets on the edges of viewports could cause the positioning of content to misalign with the gutter and height computations.
Improve cursor height next to widgets.
Fix a bug where mapping positions to screen coordinates could return incorred coordinates during composition.
## 0.19.45 (2022-02-23)
### Bug fixes
Fix an issue where the library failed to call `WidgetType.destroy` on the old widget when replacing a widget with a different widget of the same type.
Fix an issue where the editor would compute DOM positions inside composition contexts incorrectly in some cases, causing the selection to be put in the wrong place and needlessly interrupting compositions.
Fix leaking of resize event handlers.
## 0.19.44 (2022-02-17)
### Bug fixes
Fix a crash that occasionally occurred when drag-selecting in a way that scrolled the editor.
### New features
The new `EditorView.compositionStarted` property indicates whether a composition is starting.
## 0.19.43 (2022-02-16)
### Bug fixes
Fix several issues where editing or composition went wrong due to our zero-width space kludge characters ending up in unexpected places.
Make sure the editor re-measures its dimensions whenever its theme changes.
Fix an issue where some keys on Android phones could leave the editor DOM unsynced with the actual document.
## 0.19.42 (2022-02-05)
### Bug fixes
Fix a regression in cursor position determination after making an edit next to a widget.
## 0.19.41 (2022-02-04)
### Bug fixes
Fix an issue where the editor's view of its content height could go out of sync with the DOM when a line-wrapping editor had its width changed, causing wrapping to change.
Fix a bug that caused the editor to draw way too much content when scrolling to a position in an editor (much) taller than the window.
Report an error when a replace decoration from a plugin crosses a line break, rather than silently ignoring it.
Fix an issue where reading DOM changes was broken when `lineSeparator` contained more than one character.
Make ordering of replace and mark decorations with the same extent and inclusivness more predictable by giving replace decorations precedence.
Fix a bug where, on Chrome, replacement across line boundaries and next to widgets could cause bogus zero-width characters to appear in the content.
## 0.19.40 (2022-01-19)
### Bug fixes
Make composition input properly appear at secondary cursors (except when those are in the DOM node with the composition, in which case the browser won't allow us to intervene without aborting the composition).
Fix a bug that cause the editor to get confused about which content was visible after scrolling something into view.
Fix a bug where the dummy elements rendered around widgets could end up in a separate set of wrapping marks, and thus become visible.
`EditorView.moveVertically` now preserves the `assoc` property of the input range.
Get rid of gaps between selection elements drawn by `drawSelection`.
Fix an issue where replacing text next to a widget might leak bogus zero-width spaces into the document.
Avoid browser selection mishandling when a focused view has `setState` called by eagerly refocusing it.
## 0.19.39 (2022-01-06)
### Bug fixes
Make sure the editor signals a `geometryChanged` update when its width changes.
### New features
`EditorView.darkTheme` can now be queried to figure out whether the editor is using a dark theme.
## 0.19.38 (2022-01-05)
### Bug fixes
Fix a bug that caused line decorations with a `class` property to suppress all other line decorations for that line.
Fix a bug that caused scroll effects to be corrupted when further updates came in before they were applied.
Fix an issue where, depending on which way a floating point rounding error fell, `posAtCoords` (and thus vertical cursor motion) for positions outside of the vertical range of the document might or might not return the start/end of the document.
## 0.19.37 (2021-12-22)
### Bug fixes
Fix regression where plugin replacing decorations that span to the end of the line are ignored.
## 0.19.36 (2021-12-22)
### Bug fixes
Fix a crash in `posAtCoords` when the position lies in a block widget that is rendered but scrolled out of view.
Adding block decorations from a plugin now raises an error. Replacing decorations that cross lines are ignored, when provided by a plugin.
Fix inverted interpretation of the `precise` argument to `posAtCoords`.
## 0.19.35 (2021-12-20)
### Bug fixes
The editor will now handle double-taps as if they are double-clicks, rather than letting the browser's native behavior happen (because the latter often does the wrong thing).
Fix an issue where backspacing out a selection on Chrome Android would sometimes only delete the last character due to event order issues.
`posAtCoords`, without second argument, will no longer return null for positions below or above the document.
## 0.19.34 (2021-12-17)
### Bug fixes
Fix a bug where content line elements would in some cases lose their `cm-line` class.
## 0.19.33 (2021-12-16)
### Breaking changes
`EditorView.scrollTo` and `EditorView.centerOn` are deprecated in favor of `EditorView.scrollIntoView`, and will be removed in the next breaking release.
### Bug fixes
Fix an issue that could cause the editor to unnecessarily interfere with composition (especially visible on macOS Chrome).
A composition started with multiple lines selected will no longer be interruptd by the editor.
### New features
The new `EditorView.scrollIntoView` function allows you to do more fine-grained scrolling.
## 0.19.32 (2021-12-15)
### Bug fixes
Fix a bug where CodeMirror's own event handers would run even after a user-supplied handler called `preventDefault` on an event.
Properly draw selections when negative text-indent is used for soft wrapping.
Fix an issue where `viewportLineBlocks` could hold inaccurate height information when the vertical scaling changed.
Fixes drop cursor positioning when the document is scrolled. Force a content measure when the editor comes into view
Fix a bug that could cause the editor to not measure its layout the first time it came into view.
## 0.19.31 (2021-12-13)
### New features
The package now exports a `dropCursor` extension that draws a cursor at the current drop position when dragging content over the editor.
## 0.19.30 (2021-12-13)
### Bug fixes
Refine Android key event handling to work properly in a GBoard corner case where pressing Enter fires a bunch of spurious deleteContentBackward events.
Fix a crash in `drawSelection` for some kinds of selections.
Prevent a possibility where some content updates causes duplicate text to remain in DOM.
### New features
Support a `maxLength` option to `MatchDecorator` that allows user code to control how far it scans into hidden parts of viewport lines.
## 0.19.29 (2021-12-09)
### Bug fixes
Fix a bug that could cause out-of-view editors to get a nonsensical viewport and fail to scroll into view when asked to.
Fix a bug where would return 0 when clicking below the content if the last line was replaced with a block widget decoration.
Fix an issue where clicking at the position of the previous cursor in a blurred editor would cause the selection to reset to the start of the document.
Fix an issue where composition could be interrupted if the browser created a new node inside a mark decoration node.
## 0.19.28 (2021-12-08)
### Bug fixes
Fix an issue where pressing Enter on Chrome Android during composition did not fire key handlers for Enter.
Avoid a Chrome bug where the virtual keyboard closes when pressing backspace after a widget.
Fix an issue where the editor could show a horizontal scroll bar even after all lines that caused it had been deleted or changed.
## 0.19.27 (2021-12-06)
### Bug fixes
Fix a bug that could cause `EditorView.plugin` to inappropriately return `null` during plugin initialization.
Fix a bug where a block widget without `estimatedHeight` at the end of the document could fail to be drawn
## 0.19.26 (2021-12-03)
### New features
Widgets can now define a `destroy` method that is called when they are removed from the view.
## 0.19.25 (2021-12-02)
### Bug fixes
Widgets around replaced ranges are now visible when their side does not point towards the replaced range.
A replaced line with a line decoration no longer creates an extra empty line block in the editor.
The `scrollPastEnd` extension will now over-reserve space at the bottom of the editor on startup, to prevent restored scroll positions from being clipped.
### New features
`EditorView.editorAttributes` and `contentAttributes` may now hold functions that produce the attributes.
## 0.19.24 (2021-12-01)
### Bug fixes
Fix a bug where `lineBlockAt`, for queries inside the viewport, would always return the first line in the viewport.
## 0.19.23 (2021-11-30)
### Bug fixes
Fix an issue where after some kinds of changes, `EditorView.viewportLineBlocks` held an out-of-date set of blocks.
### New features
Export `EditorView.documentPadding`, with information about the vertical padding of the document.
## 0.19.22 (2021-11-30)
### Bug fixes
Fix an issue where editors with large vertical padding (for example via `scrollPastEnd`) could sometimes lose their scroll position on Chrome.
Avoid some unnecessary DOM measuring work by more carefully checking whether it is needed.
### New features
The new `elementAtHeight`, `lineBlockAtHeight`, and `lineBlockAt` methods provide a simpler and more efficient replacement for the (now deprecated) `blockAtHeight`, `visualLineAtHeight`, and `visualLineAt` methods.
The editor view now exports a `documentTop` getter that gives you the vertical position of the top of the document. All height info is queried and reported relative to this top.
The editor view's new `viewportLineBlocks` property provides an array of in-viewport line blocks, and replaces the (now deprecated) `viewportLines` method.
## 0.19.21 (2021-11-26)
### Bug fixes
Fix a problem where the DOM update would unnecessarily trigger browser relayouts.
## 0.19.20 (2021-11-19)
### Bug fixes
Run a measure cycle when the editor's size spontaneously changes.
## 0.19.19 (2021-11-17)
### Bug fixes
Fix a bug that caused the precedence of `editorAttributes` and `contentAttributes` to be inverted, making lower-precedence extensions override higher-precedence ones.
## 0.19.18 (2021-11-16)
### Bug fixes
Fix an issue where the editor wasn't aware it was line-wrapping with its own `lineWrapping` extension enabled.
## 0.19.17 (2021-11-16)
### Bug fixes
Avoid an issue where stretches of whitespace on line wrap points could cause the cursor to be placed outside of the content.
## 0.19.16 (2021-11-11)
### Breaking changes
Block replacement decorations now default to inclusive, because non-inclusive block decorations are rarely what you need.
### Bug fixes
Fix an issue that caused block widgets to always have a large side value, making it impossible to show them between to replacement decorations.
Fix a crash that could happen after some types of viewport changes, due to a bug in the block widget view data structure.
## 0.19.15 (2021-11-09)
### Bug fixes
Fix a bug where the editor would think it was invisible when the document body was given screen height and scroll behavior.
Fix selection reading inside a shadow root on iOS.
## 0.19.14 (2021-11-07)
### Bug fixes
Fix an issue where typing into a read-only editor would move the selection.
Fix slowness when backspace is held down on iOS.
## 0.19.13 (2021-11-06)
### Bug fixes
Fix a bug where backspace, enter, and delete would get applied twice on iOS.
## 0.19.12 (2021-11-04)
### Bug fixes
Make sure the workaround for the lost virtual keyboard on Chrome Android also works on slower phones. Slight style change in beforeinput handler
Avoid failure cases in viewport-based rendering of very long lines.
## 0.19.11 (2021-11-03)
### Breaking changes
`EditorView.scrollPosIntoView` has been deprecated. Use the `EditorView.scrollTo` effect instead.
### New features
The new `EditorView.centerOn` effect can be used to scroll a given range to the center of the view.
## 0.19.10 (2021-11-02)
### Bug fixes
Don't crash when `IntersectionObserver` fires its callback without any records. Try to handle some backspace issues on Chrome Android
Using backspace near uneditable widgets on Chrome Android should now be more reliable.
Work around a number of browser bugs by always rendering zero-width spaces around in-content widgets, so that browsers will treat the positions near them as valid cursor positions and not try to run composition across widget boundaries.
Work around bogus composition changes created by Chrome Android after handled backspace presses.
Work around an issue where tapping on an uneditable node in the editor would sometimes fail to show the virtual keyboard on Chrome Android.
Prevent translation services from translating the editor content. Show direction override characters as special chars by default
`specialChars` will now, by default, replace direction override chars, to mitigate https://trojansource.codes/ attacks.
### New features
The editor view will, if `parent` is given but `root` is not, derive the root from the parent element.
Line decorations now accept a `class` property to directly add DOM classes to the line.
## 0.19.9 (2021-10-01)
### Bug fixes
Fix an issue where some kinds of reflows in the surrounding document could move unrendered parts of the editor into view without the editor noticing and updating its viewport.
Fix an occasional crash in the selection drawing extension.
## 0.19.8 (2021-09-26)
### Bug fixes
Fix a bug that could, on DOM changes near block widgets, insert superfluous line breaks.
Make interacting with a destroyed editor view do nothing, rather than crash, to avoid tripping people up with pending timeouts and such.
Make sure `ViewUpdate.viewportChanged` is true whenever `visibleRanges` changes, so that plugins acting only on visible ranges can use it to check when to update.
Fix line-wise cut on empty lines.
## 0.19.7 (2021-09-13)
### Bug fixes
The view is now aware of the new `EditorState.readOnly` property, and suppresses events that modify the document when it is true.
## 0.19.6 (2021-09-10)
### Bug fixes
Remove a `console.log` that slipped into the previous release.
## 0.19.5 (2021-09-09)
### New features
The new `EditorView.scrollTo` effect can be used to scroll a given range into view.
## 0.19.4 (2021-09-01)
### Bug fixes
Fix an issue where lines containing just a widget decoration wrapped in a mark decoration could be displayed with 0 height.
## 0.19.3 (2021-08-25)
### Bug fixes
Fix a view corruption that could happen in situations involving overlapping mark decorations.
## 0.19.2 (2021-08-23)
### New features
The package now exports a `scrollPastEnd` function, which returns an extension that adds space below the document to allow the last line to be scrolled to the top of the editor.
## 0.19.1 (2021-08-11)
### Breaking changes
The view now emits new-style user event annotations for the transactions it generates.
### Bug fixes
Fix a bug where `coordsAtPos` would allow the passed `side` argument to override widget sides, producing incorrect cursor positions.
Fix a bug that could cause content lines to be misaligned in certain situations involving widgets at the end of lines.
Fix an issue where, if the browser decided to modify DOM attributes in the content in response to some editing action, the view failed to reset those again.
## 0.18.19 (2021-07-12)
### Bug fixes
Fix a regression where `EditorView.editable.of(false)` didn't disable editing on Webkit-based browsers.
## 0.18.18 (2021-07-06)
### Bug fixes
Fix a bug that caused `EditorView.moveVertically` to only move by one line, even when given a custom distance, in some cases.
Hide Safari's native bold/italic/underline controls for the content.
Fix a CSS problem that prevented Safari from breaking words longer than the line in line-wrapping mode.
Avoid a problem where composition would be inappropriately abored on Safari.
Fix drag-selection that scrolls the content by dragging past the visible viewport.
### New features
`posAtCoords` now has an imprecise mode where it'll return an approximate position even for parts of the document that aren't currently rendered.
## 0.18.17 (2021-06-14)
### Bug fixes
Make `drawSelection` behave properly when lines are split by block widgets.
Make sure drawn selections that span a single line break don't leave a gap between the lines.
## 0.18.16 (2021-06-03)
### Bug fixes
Fix a crash that could occur when the document changed during mouse selection.
Fix a bug where composition inside styled content would sometimes be inappropriately aborted by editor DOM updates.
### New features
`MouseSelectionStyle.update` may now return true to indicate it should be queried for a new selection after the update.
## 0.18.15 (2021-06-01)
### Bug fixes
Fix a bug that would, in very specific circumstances, cause `posAtCoords` to go into an infinite loop in Safari.
Fix a bug where some types of IME input on Mobile Safari would drop text.
## 0.18.14 (2021-05-28)
### Bug fixes
Fix an issue where the DOM selection was sometimes not properly updated when next to a widget.
Invert the order in which overlapping decorations are drawn so that higher-precedence decorations are nested inside lower-precedence ones (and thus override their styling).
Fix a but in `posAtCoords` where it would in some situations return -1 instead of `null`.
### New features
A new plugin field, `PluginField.atomicRanges`, can be used to cause cursor motion to skip past some ranges of the document.
## 0.18.13 (2021-05-20)
### Bug fixes
Fix a bug that would cause the content DOM update to crash in specific circumstances.
Work around an issue where, after some types of changes, Mobile Safari would ignore Enter presses.
Make iOS enter and backspace handling more robust, so that platform bugs are less likely to break those keys in the editor.
Fix a regression where Esc + Tab no longer allowed the user to exit the editor.
### New features
You can now drop text files into the editor.
## 0.18.12 (2021-05-10)
### Bug fixes
Work around a Mobile Safari bug where, after backspacing out the last character on a line, Enter didn't work anymore.
Work around a problem in Mobile Safari where you couldn't tap to put the cursor at the end of a line that ended in a widget.
## 0.18.11 (2021-04-30)
### Bug fixes
Add an attribute to prevent the Grammarly browser extension from messing with the editor content.
Fix more issues around selection handling a Shadow DOM in Safari.
## 0.18.10 (2021-04-27)
### Bug fixes
Fix a bug where some types of updates wouldn't properly cause marks around the changes to be joined in the DOM.
Fix an issue where the content and gutters in a fixed-height editor could be smaller than the editor height.
Fix a crash on Safari when initializing an editor in an unfocused window.
Fix a bug where the editor would incorrectly conclude it was out of view in some types of absolutely positioned parent elements.
## 0.18.9 (2021-04-23)
### Bug fixes
Fix a crash that occurred when determining DOM coordinates in some specific situations.
Fix a crash when a DOM change that ended at a zero-width view element (widget) removed that element from the DOM.
Disable autocorrect and autocapitalize by default, since in most code-editor contexts they get in the way. You can use `EditorView.contentAttributes` to override this.
Fix a bug that interfered with native touch selection handling on Android.
Fix an unnecessary DOM update after composition that would disrupt touch selection on Android.
Add a workaround for Safari's broken selection reporting when the editor is in a shadow DOM tree.
Fix select-all from the context menu on Safari.
## 0.18.8 (2021-04-19)
### Bug fixes
Handle selection replacements where the inserted text matches the start/end of the replaced text better.
Fix an issue where the editor would miss scroll events when it was placed in a DOM component slot.
## 0.18.7 (2021-04-13)
### Bug fixes
Fix a crash when drag-selecting out of the editor with editable turned off.
Backspace and delete now largely work in an editor without a keymap.
Pressing backspace on iOS should now properly update the virtual keyboard's capitalize and autocorrect state.
Prevent random line-wrapping in (non-wrapping) editors on Mobile Safari.
## 0.18.6 (2021-04-08)
### Bug fixes
Fix an issue in the compiled output that would break the code when minified with terser.
## 0.18.5 (2021-04-07)
### Bug fixes
Improve handling of bidi text with brackets (conforming to Unicode 13's bidi algorithm).
Fix the position where `drawSelection` displays the cursor on bidi boundaries.
## 0.18.4 (2021-04-07)
### Bug fixes
Fix an issue where the default focus ring gets obscured by the gutters and active line.
Fix an issue where the editor believed Chrome Android didn't support the CSS `tab-size` style.
Don't style active lines when there are non-empty selection ranges, so that the active line background doesn't obscure the selection.
Make iOS autocapitalize update properly when you press Enter.
## 0.18.3 (2021-03-19)
### Breaking changes
The outer DOM element now has class `cm-editor` instead of `cm-wrap` (`cm-wrap` will be present as well until 0.19).
### Bug fixes
Improve behavior of `posAtCoords` when the position is near text but not in any character's actual box.
## 0.18.2 (2021-03-19)
### Bug fixes
Triple-clicking now selects the line break after the clicked line (if any).
Fix an issue where the `drawSelection` plugin would fail to draw the top line of the selection when it started in an empty line.
Fix an issue where, at the end of a specific type of composition on iOS, the editor read the DOM before the browser was done updating it.
## 0.18.1 (2021-03-05)
### Bug fixes
Fix an issue where, on iOS, some types of IME would cause the composed content to be deleted when confirming a composition.
## 0.18.0 (2021-03-03)
### Breaking changes
The `themeClass` function and ``-style selectors in themes are no longer supported (prefixing with `cm-` should be done manually now).
Themes must now use `&` (instead of an extra `$`) to target the editor wrapper element.
The editor no longer adds `cm-light` or `cm-dark` classes. Targeting light or dark configurations in base themes should now be done by using a `&light` or `&dark` top-level selector.
## 0.17.13 (2021-03-03)
### Bug fixes
Work around a Firefox bug where it won't draw the cursor when it is between uneditable elements.
Fix a bug that broke built-in mouse event handling.
## 0.17.12 (2021-03-02)
### Bug fixes
Avoid interfering with touch events, to allow native selection behavior.
Fix a bug that broke sub-selectors with multiple `&` placeholders in themes.
## 0.17.11 (2021-02-25)
### Bug fixes
Fix vertical cursor motion on Safari with a larger line-height.
Fix incorrect selection drawing (with `drawSelection`) when the selection spans to just after a soft wrap point.
Fix an issue where compositions on Safari were inappropriately aborted in some circumstances.
The view will now redraw when the `EditorView.phrases` facet changes, to make sure translated text is properly updated.
## 0.17.10 (2021-02-22)
### Bug fixes
Long words without spaces, when line-wrapping is enabled, are now properly broken.
Fix the horizontal position of selections drawn by `drawSelection` in right-to-left editors with a scrollbar.
## 0.17.9 (2021-02-18)
### Bug fixes
Fix an issue where pasting linewise at the start of a line left the cursor before the inserted content.
## 0.17.8 (2021-02-16)
### Bug fixes
Fix a problem where the DOM selection and the editor state could get out of sync in non-editable mode.
Fix a crash when the editor was hidden on Safari, due to `getClientRects` returning an empty list.
Prevent Firefox from making the scrollable element keyboard-focusable.
## 0.17.7 (2021-01-25)
### New features
Add an `EditorView.announce` state effect that can be used to conveniently provide screen reader announcements.
## 0.17.6 (2021-01-22)
### Bug fixes
Avoid creating very high scroll containers for large documents so that we don't overflow the DOM's fixed-precision numbers.
## 0.17.5 (2021-01-15)
### Bug fixes
Fix a bug that would create space-filling placeholders with incorrect height when document is very large.
## 0.17.4 (2021-01-14)
### Bug fixes
The `drawSelection` extension will now reuse cursor DOM nodes when the number of cursors stays the same, allowing some degree of cursor transition animation.
Makes highlighted special characters styleable (``) and fix their default look in dark themes to have appropriate contrast.
### New features
Adds a new `MatchDecorator` helper class which can be used to easily maintain decorations on content that matches a regular expression.
## 0.17.3 (2021-01-06)
### New features
The package now also exports a CommonJS module.
## 0.17.2 (2021-01-04)
### Bug fixes
Work around Chrome problem where the native shift-enter behavior inserts two line breaks.
Make bracket closing and bracket pair removing more reliable on Android.
Fix bad cursor position and superfluous change transactions after pressing enter when in a composition on Android.
Fix issue where the wrong character was deleted when backspacing out a character before an identical copy of that character on Android.
## 0.17.1 (2020-12-30)
### Bug fixes
Fix a bug that prevented `ViewUpdate.focusChanged` from ever being true.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,18 @@
# @codemirror/view [![NPM version](https://img.shields.io/npm/v/@codemirror/view.svg)](https://www.npmjs.org/package/@codemirror/view)
[ [**WEBSITE**](https://codemirror.net/6/) | [**DOCS**](https://codemirror.net/6/docs/ref/#view) | [**ISSUES**](https://github.com/codemirror/codemirror.next/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/view/blob/main/CHANGELOG.md) ]
This package implements the DOM view component for the
[CodeMirror](https://codemirror.net/6/) code editor.
The [project page](https://codemirror.net/6/) has more information, a
number of [examples](https://codemirror.net/6/examples/) and the
[documentation](https://codemirror.net/6/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/view/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,40 @@
{
"name": "@codemirror/view",
"version": "0.20.7",
"description": "DOM view component for the CodeMirror code editor",
"scripts": {
"test": "cm-runtests",
"prepare": "cm-buildhelper src/index.ts"
},
"keywords": [
"editor",
"code"
],
"author": {
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"url": "http://marijnhaverbeke.nl"
},
"type": "module",
"main": "dist/index.cjs",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"types": "dist/index.d.ts",
"module": "dist/index.js",
"sideEffects": false,
"license": "MIT",
"dependencies": {
"@codemirror/state": "^0.20.0",
"style-mod": "^4.0.0",
"w3c-keyname": "^2.2.4"
},
"devDependencies": {
"@codemirror/buildhelper": "^0.1.6"
},
"repository": {
"type": "git",
"url": "https://github.com/codemirror/view.git"
}
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,14 @@
# @lezer/common
[ [**WEBSITE**](http://lezer.codemirror.net) | [**ISSUES**](https://github.com/lezer-parser/lezer/issues) | [**FORUM**](https://discuss.codemirror.net/c/lezer) | [**CHANGELOG**](https://github.com/lezer-parser/common/blob/master/CHANGELOG.md) ]
[Lezer](https://lezer.codemirror.net/) is an incremental parser system
intended for use in an editor or similar system.
@lezer/common provides the syntax tree data structure and parser
abstractions for Lezer parsers.
Its programming interface is documented on [the
website](https://lezer.codemirror.net/docs/ref/#common).
This code is licensed under an MIT license.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
export { DefaultBufferLength, NodeProp, MountedTree, NodePropSource, NodeType, NodeSet, Tree, TreeBuffer, SyntaxNode, SyntaxNodeRef, TreeCursor, BufferCursor, NodeWeakMap, IterMode } from "./tree";
export { ChangedRange, TreeFragment, PartialParse, Parser, Input, ParseWrapper } from "./parse";
export { NestedParse, parseMixed } from "./mix";

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,13 @@
import { SyntaxNodeRef } from "./tree";
import { Input, Parser, ParseWrapper } from "./parse";
export interface NestedParse {
parser: Parser;
overlay?: readonly {
from: number;
to: number;
}[] | ((node: SyntaxNodeRef) => {
from: number;
to: number;
} | boolean);
}
export declare function parseMixed(nest: (node: SyntaxNodeRef, input: Input) => NestedParse | null): ParseWrapper;

View File

@ -0,0 +1,48 @@
import { Tree } from "./tree";
export interface ChangedRange {
fromA: number;
toA: number;
fromB: number;
toB: number;
}
export declare class TreeFragment {
readonly from: number;
readonly to: number;
readonly tree: Tree;
readonly offset: number;
constructor(from: number, to: number, tree: Tree, offset: number, openStart?: boolean, openEnd?: boolean);
get openStart(): boolean;
get openEnd(): boolean;
static addTree(tree: Tree, fragments?: readonly TreeFragment[], partial?: boolean): TreeFragment[];
static applyChanges(fragments: readonly TreeFragment[], changes: readonly ChangedRange[], minGap?: number): readonly TreeFragment[];
}
export interface PartialParse {
advance(): Tree | null;
readonly parsedPos: number;
stopAt(pos: number): void;
readonly stoppedAt: number | null;
}
export declare abstract class Parser {
abstract createParse(input: Input, fragments: readonly TreeFragment[], ranges: readonly {
from: number;
to: number;
}[]): PartialParse;
startParse(input: Input | string, fragments?: readonly TreeFragment[], ranges?: readonly {
from: number;
to: number;
}[]): PartialParse;
parse(input: Input | string, fragments?: readonly TreeFragment[], ranges?: readonly {
from: number;
to: number;
}[]): Tree;
}
export interface Input {
readonly length: number;
chunk(from: number): string;
readonly lineChunks: boolean;
read(from: number, to: number): string;
}
export declare type ParseWrapper = (inner: PartialParse, input: Input, fragments: readonly TreeFragment[], ranges: readonly {
from: number;
to: number;
}[]) => PartialParse;

View File

@ -0,0 +1,262 @@
import { Parser } from "./parse";
export declare const DefaultBufferLength = 1024;
export declare class Range {
readonly from: number;
readonly to: number;
constructor(from: number, to: number);
}
export declare class NodeProp<T> {
perNode: boolean;
deserialize: (str: string) => T;
constructor(config?: {
deserialize?: (str: string) => T;
perNode?: boolean;
});
add(match: {
[selector: string]: T;
} | ((type: NodeType) => T | undefined)): NodePropSource;
static closedBy: NodeProp<readonly string[]>;
static openedBy: NodeProp<readonly string[]>;
static group: NodeProp<readonly string[]>;
static contextHash: NodeProp<number>;
static lookAhead: NodeProp<number>;
static mounted: NodeProp<MountedTree>;
}
export declare class MountedTree {
readonly tree: Tree;
readonly overlay: readonly {
from: number;
to: number;
}[] | null;
readonly parser: Parser;
constructor(tree: Tree, overlay: readonly {
from: number;
to: number;
}[] | null, parser: Parser);
}
export declare type NodePropSource = (type: NodeType) => null | [NodeProp<any>, any];
export declare class NodeType {
readonly name: string;
readonly id: number;
static define(spec: {
id: number;
name?: string;
props?: readonly ([NodeProp<any>, any] | NodePropSource)[];
top?: boolean;
error?: boolean;
skipped?: boolean;
}): NodeType;
prop<T>(prop: NodeProp<T>): T | undefined;
get isTop(): boolean;
get isSkipped(): boolean;
get isError(): boolean;
get isAnonymous(): boolean;
is(name: string | number): boolean;
static none: NodeType;
static match<T>(map: {
[selector: string]: T;
}): (node: NodeType) => T | undefined;
}
export declare class NodeSet {
readonly types: readonly NodeType[];
constructor(types: readonly NodeType[]);
extend(...props: NodePropSource[]): NodeSet;
}
export declare enum IterMode {
ExcludeBuffers = 1,
IncludeAnonymous = 2,
IgnoreMounts = 4,
IgnoreOverlays = 8
}
export declare class Tree {
readonly type: NodeType;
readonly children: readonly (Tree | TreeBuffer)[];
readonly positions: readonly number[];
readonly length: number;
constructor(type: NodeType, children: readonly (Tree | TreeBuffer)[], positions: readonly number[], length: number, props?: readonly [NodeProp<any> | number, any][]);
static empty: Tree;
cursor(mode?: IterMode): TreeCursor;
cursorAt(pos: number, side?: -1 | 0 | 1, mode?: IterMode): TreeCursor;
get topNode(): SyntaxNode;
resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode;
resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode;
iterate(spec: {
enter(node: SyntaxNodeRef): boolean | void;
leave?(node: SyntaxNodeRef): void;
from?: number;
to?: number;
mode?: IterMode;
}): void;
prop<T>(prop: NodeProp<T>): T | undefined;
get propValues(): readonly [NodeProp<any> | number, any][];
balance(config?: {
makeTree?: (children: readonly (Tree | TreeBuffer)[], positions: readonly number[], length: number) => Tree;
}): Tree;
static build(data: BuildData): Tree;
}
declare type BuildData = {
buffer: BufferCursor | readonly number[];
nodeSet: NodeSet;
topID: number;
start?: number;
bufferStart?: number;
length?: number;
maxBufferLength?: number;
reused?: readonly Tree[];
minRepeatType?: number;
};
export interface BufferCursor {
pos: number;
id: number;
start: number;
end: number;
size: number;
next(): void;
fork(): BufferCursor;
}
export declare class TreeBuffer {
readonly buffer: Uint16Array;
readonly length: number;
readonly set: NodeSet;
constructor(buffer: Uint16Array, length: number, set: NodeSet);
}
export interface SyntaxNodeRef {
readonly from: number;
readonly to: number;
readonly type: NodeType;
readonly name: string;
readonly tree: Tree | null;
readonly node: SyntaxNode;
matchContext(context: readonly string[]): boolean;
}
export interface SyntaxNode extends SyntaxNodeRef {
parent: SyntaxNode | null;
firstChild: SyntaxNode | null;
lastChild: SyntaxNode | null;
childAfter(pos: number): SyntaxNode | null;
childBefore(pos: number): SyntaxNode | null;
enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): SyntaxNode | null;
nextSibling: SyntaxNode | null;
prevSibling: SyntaxNode | null;
cursor(mode?: IterMode): TreeCursor;
resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode;
resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode;
enterUnfinishedNodesBefore(pos: number): SyntaxNode;
toTree(): Tree;
getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode | null;
getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[];
matchContext(context: readonly string[]): boolean;
}
declare const enum Side {
Before = -2,
AtOrBefore = -1,
Around = 0,
AtOrAfter = 1,
After = 2,
DontCare = 4
}
export declare class TreeNode implements SyntaxNode {
readonly _tree: Tree;
readonly from: number;
readonly index: number;
readonly _parent: TreeNode | null;
constructor(_tree: Tree, from: number, index: number, _parent: TreeNode | null);
get type(): NodeType;
get name(): string;
get to(): number;
nextChild(i: number, dir: 1 | -1, pos: number, side: Side, mode?: IterMode): TreeNode | BufferNode | null;
get firstChild(): TreeNode | BufferNode;
get lastChild(): TreeNode | BufferNode;
childAfter(pos: number): TreeNode | BufferNode;
childBefore(pos: number): TreeNode | BufferNode;
enter(pos: number, side: -1 | 0 | 1, mode?: number): TreeNode | BufferNode;
nextSignificantParent(): TreeNode;
get parent(): TreeNode | null;
get nextSibling(): SyntaxNode | null;
get prevSibling(): SyntaxNode | null;
cursor(mode?: IterMode): TreeCursor;
get tree(): Tree;
toTree(): Tree;
resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode;
resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode;
enterUnfinishedNodesBefore(pos: number): SyntaxNode;
getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode;
getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[];
get node(): this;
matchContext(context: readonly string[]): boolean;
}
declare class BufferContext {
readonly parent: TreeNode;
readonly buffer: TreeBuffer;
readonly index: number;
readonly start: number;
constructor(parent: TreeNode, buffer: TreeBuffer, index: number, start: number);
}
declare class BufferNode implements SyntaxNode {
readonly context: BufferContext;
readonly _parent: BufferNode | null;
readonly index: number;
type: NodeType;
get name(): string;
get from(): number;
get to(): number;
constructor(context: BufferContext, _parent: BufferNode | null, index: number);
child(dir: 1 | -1, pos: number, side: Side): BufferNode | null;
get firstChild(): BufferNode;
get lastChild(): BufferNode;
childAfter(pos: number): BufferNode;
childBefore(pos: number): BufferNode;
enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): BufferNode;
get parent(): SyntaxNode | null;
externalSibling(dir: 1 | -1): TreeNode | BufferNode;
get nextSibling(): SyntaxNode | null;
get prevSibling(): SyntaxNode | null;
cursor(mode?: IterMode): TreeCursor;
get tree(): any;
toTree(): Tree;
resolve(pos: number, side?: -1 | 0 | 1): SyntaxNode;
resolveInner(pos: number, side?: -1 | 0 | 1): SyntaxNode;
enterUnfinishedNodesBefore(pos: number): SyntaxNode;
getChild(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode;
getChildren(type: string | number, before?: string | number | null, after?: string | number | null): SyntaxNode[];
get node(): this;
matchContext(context: readonly string[]): boolean;
}
export declare class TreeCursor implements SyntaxNodeRef {
type: NodeType;
get name(): string;
from: number;
to: number;
private stack;
private bufferNode;
private yieldNode;
private yieldBuf;
private yield;
firstChild(): boolean;
lastChild(): boolean;
childAfter(pos: number): boolean;
childBefore(pos: number): boolean;
enter(pos: number, side: -1 | 0 | 1, mode?: IterMode): boolean;
parent(): boolean;
nextSibling(): boolean;
prevSibling(): boolean;
private atLastNode;
private move;
next(enter?: boolean): boolean;
prev(enter?: boolean): boolean;
moveTo(pos: number, side?: -1 | 0 | 1): this;
get node(): SyntaxNode;
get tree(): Tree | null;
iterate(enter: (node: SyntaxNodeRef) => boolean | void, leave?: (node: SyntaxNodeRef) => void): void;
matchContext(context: readonly string[]): boolean;
}
export declare class NodeWeakMap<T> {
private map;
private setBuffer;
private getBuffer;
set(node: SyntaxNode, value: T): void;
get(node: SyntaxNode): T | undefined;
cursorSet(cursor: TreeCursor, value: T): void;
cursorGet(cursor: TreeCursor): T | undefined;
}
export {};

View File

@ -0,0 +1,36 @@
{
"name": "@lezer/common",
"version": "0.16.1",
"description": "Syntax tree data structure and parser interfaces for the lezer parser",
"main": "dist/index.cjs",
"type": "module",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"module": "dist/index.js",
"types": "dist/index.d.ts",
"author": "Marijn Haverbeke <marijnh@gmail.com>",
"license": "MIT",
"devDependencies": {
"ist": "^1.1.1",
"rollup": "^2.52.2",
"@rollup/plugin-commonjs": "^15.1.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"rollup-plugin-typescript2": "^0.30.0",
"typescript": "^4.3.4",
"@types/mocha": "^5.2.6",
"ts-node": "^10.0.0",
"mocha": "^9.0.1"
},
"files": ["dist"],
"repository": {
"type" : "git",
"url" : "https://github.com/lezer-parser/common.git"
},
"scripts": {
"watch": "rollup -w -c rollup.config.js",
"prepare": "rollup -c rollup.config.js",
"test": "mocha"
}
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,14 @@
# @lezer/highlight
[ [**WEBSITE**](http://lezer.codemirror.net) | [**ISSUES**](https://github.com/lezer-parser/lezer/issues) | [**FORUM**](https://discuss.codemirror.net/c/lezer) | [**CHANGELOG**](https://github.com/lezer-parser/highlight/blob/master/CHANGELOG.md) ]
[Lezer](https://lezer.codemirror.net/) is an incremental parser system
intended for use in an editor or similar system.
@lezer/highlight provides a syntax highlighting framework for Lezer
parse trees.
Its programming interface is documented on [the
website](https://lezer.codemirror.net/docs/ref/#highlight).
This code is licensed under an MIT license.

View File

@ -0,0 +1,109 @@
import { Tree, NodeType } from "@lezer/common";
export declare class Tag {
readonly set: Tag[];
static define(parent?: Tag): Tag;
static defineModifier(): (tag: Tag) => Tag;
}
export declare function styleTags(spec: {
[selector: string]: Tag | readonly Tag[];
}): import("@lezer/common").NodePropSource;
export interface Highlighter {
style(tags: readonly Tag[]): string | null;
scope?(node: NodeType): boolean;
}
export declare function tagHighlighter(tags: readonly {
tag: Tag | readonly Tag[];
class: string;
}[], options?: {
scope?: (node: NodeType) => boolean;
all?: string;
}): Highlighter;
export declare function highlightTags(highlighters: readonly Highlighter[], tags: readonly Tag[]): string | null;
export declare function highlightTree(tree: Tree, highlighter: Highlighter | readonly Highlighter[], putStyle: (from: number, to: number, classes: string) => void, from?: number, to?: number): void;
export declare const tags: {
comment: Tag;
lineComment: Tag;
blockComment: Tag;
docComment: Tag;
name: Tag;
variableName: Tag;
typeName: Tag;
tagName: Tag;
propertyName: Tag;
attributeName: Tag;
className: Tag;
labelName: Tag;
namespace: Tag;
macroName: Tag;
literal: Tag;
string: Tag;
docString: Tag;
character: Tag;
attributeValue: Tag;
number: Tag;
integer: Tag;
float: Tag;
bool: Tag;
regexp: Tag;
escape: Tag;
color: Tag;
url: Tag;
keyword: Tag;
self: Tag;
null: Tag;
atom: Tag;
unit: Tag;
modifier: Tag;
operatorKeyword: Tag;
controlKeyword: Tag;
definitionKeyword: Tag;
moduleKeyword: Tag;
operator: Tag;
derefOperator: Tag;
arithmeticOperator: Tag;
logicOperator: Tag;
bitwiseOperator: Tag;
compareOperator: Tag;
updateOperator: Tag;
definitionOperator: Tag;
typeOperator: Tag;
controlOperator: Tag;
punctuation: Tag;
separator: Tag;
bracket: Tag;
angleBracket: Tag;
squareBracket: Tag;
paren: Tag;
brace: Tag;
content: Tag;
heading: Tag;
heading1: Tag;
heading2: Tag;
heading3: Tag;
heading4: Tag;
heading5: Tag;
heading6: Tag;
contentSeparator: Tag;
list: Tag;
quote: Tag;
emphasis: Tag;
strong: Tag;
link: Tag;
monospace: Tag;
strikethrough: Tag;
inserted: Tag;
deleted: Tag;
changed: Tag;
invalid: Tag;
meta: Tag;
documentMeta: Tag;
annotation: Tag;
processingInstruction: Tag;
definition: (tag: Tag) => Tag;
constant: (tag: Tag) => Tag;
function: (tag: Tag) => Tag;
standard: (tag: Tag) => Tag;
local: (tag: Tag) => Tag;
special: (tag: Tag) => Tag;
};
export declare const classHighlighter: Highlighter;

View File

@ -0,0 +1,658 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var common = require('@lezer/common');
let nextTagID = 0;
/// Highlighting tags are markers that denote a highlighting category.
/// They are [associated](#highlight.styleTags) with parts of a syntax
/// tree by a language mode, and then mapped to an actual CSS style by
/// a [highlighter](#highlight.Highlighter).
///
/// Because syntax tree node types and highlight styles have to be
/// able to talk the same language, CodeMirror uses a mostly _closed_
/// [vocabulary](#highlight.tags) of syntax tags (as opposed to
/// traditional open string-based systems, which make it hard for
/// highlighting themes to cover all the tokens produced by the
/// various languages).
///
/// It _is_ possible to [define](#highlight.Tag^define) your own
/// highlighting tags for system-internal use (where you control both
/// the language package and the highlighter), but such tags will not
/// be picked up by regular highlighters (though you can derive them
/// from standard tags to allow highlighters to fall back to those).
class Tag {
/// @internal
constructor(
/// The set of this tag and all its parent tags, starting with
/// this one itself and sorted in order of decreasing specificity.
set,
/// The base unmodified tag that this one is based on, if it's
/// modified @internal
base,
/// The modifiers applied to this.base @internal
modified) {
this.set = set;
this.base = base;
this.modified = modified;
/// @internal
this.id = nextTagID++;
}
/// Define a new tag. If `parent` is given, the tag is treated as a
/// sub-tag of that parent, and
/// [highlighters](#highlight.tagHighlighter) that don't mention
/// this tag will try to fall back to the parent tag (or grandparent
/// tag, etc).
static define(parent) {
if (parent === null || parent === void 0 ? void 0 : parent.base)
throw new Error("Can not derive from a modified tag");
let tag = new Tag([], null, []);
tag.set.push(tag);
if (parent)
for (let t of parent.set)
tag.set.push(t);
return tag;
}
/// Define a tag _modifier_, which is a function that, given a tag,
/// will return a tag that is a subtag of the original. Applying the
/// same modifier to a twice tag will return the same value (`m1(t1)
/// == m1(t1)`) and applying multiple modifiers will, regardless or
/// order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
///
/// When multiple modifiers are applied to a given base tag, each
/// smaller set of modifiers is registered as a parent, so that for
/// example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
/// `m1(m3(t1)`, and so on.
static defineModifier() {
let mod = new Modifier;
return (tag) => {
if (tag.modified.indexOf(mod) > -1)
return tag;
return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
};
}
}
let nextModifierID = 0;
class Modifier {
constructor() {
this.instances = [];
this.id = nextModifierID++;
}
static get(base, mods) {
if (!mods.length)
return base;
let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));
if (exists)
return exists;
let set = [], tag = new Tag(set, base, mods);
for (let m of mods)
m.instances.push(tag);
let configs = permute(mods);
for (let parent of base.set)
for (let config of configs)
set.push(Modifier.get(parent, config));
return tag;
}
}
function sameArray(a, b) {
return a.length == b.length && a.every((x, i) => x == b[i]);
}
function permute(array) {
let result = [array];
for (let i = 0; i < array.length; i++) {
for (let a of permute(array.slice(0, i).concat(array.slice(i + 1))))
result.push(a);
}
return result;
}
/// This function is used to add a set of tags to a language syntax
/// via [`NodeSet.extend`](#common.NodeSet.extend) or
/// [`LRParser.configure`](#lr.LRParser.configure).
///
/// The argument object maps node selectors to [highlighting
/// tags](#highlight.Tag) or arrays of tags.
///
/// Node selectors may hold one or more (space-separated) node paths.
/// Such a path can be a [node name](#common.NodeType.name), or
/// multiple node names (or `*` wildcards) separated by slash
/// characters, as in `"Block/Declaration/VariableName"`. Such a path
/// matches the final node but only if its direct parent nodes are the
/// other nodes mentioned. A `*` in such a path matches any parent,
/// but only a single level—wildcards that match multiple parents
/// aren't supported, both for efficiency reasons and because Lezer
/// trees make it rather hard to reason about what they would match.)
///
/// A path can be ended with `/...` to indicate that the tag assigned
/// to the node should also apply to all child nodes, even if they
/// match their own style (by default, only the innermost style is
/// used).
///
/// When a path ends in `!`, as in `Attribute!`, no further matching
/// happens for the node's child nodes, and the entire node gets the
/// given style.
///
/// In this notation, node names that contain `/`, `!`, `*`, or `...`
/// must be quoted as JSON strings.
///
/// For example:
///
/// ```javascript
/// parser.withProps(
/// styleTags({
/// // Style Number and BigNumber nodes
/// "Number BigNumber": tags.number,
/// // Style Escape nodes whose parent is String
/// "String/Escape": tags.escape,
/// // Style anything inside Attributes nodes
/// "Attributes!": tags.meta,
/// // Add a style to all content inside Italic nodes
/// "Italic/...": tags.emphasis,
/// // Style InvalidString nodes as both `string` and `invalid`
/// "InvalidString": [tags.string, tags.invalid],
/// // Style the node named "/" as punctuation
/// '"/"': tags.punctuation
/// })
/// )
/// ```
function styleTags(spec) {
let byName = Object.create(null);
for (let prop in spec) {
let tags = spec[prop];
if (!Array.isArray(tags))
tags = [tags];
for (let part of prop.split(" "))
if (part) {
let pieces = [], mode = 2 /* Normal */, rest = part;
for (let pos = 0;;) {
if (rest == "..." && pos > 0 && pos + 3 == part.length) {
mode = 1 /* Inherit */;
break;
}
let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
if (!m)
throw new RangeError("Invalid path: " + part);
pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
pos += m[0].length;
if (pos == part.length)
break;
let next = part[pos++];
if (pos == part.length && next == "!") {
mode = 0 /* Opaque */;
break;
}
if (next != "/")
throw new RangeError("Invalid path: " + part);
rest = part.slice(pos);
}
let last = pieces.length - 1, inner = pieces[last];
if (!inner)
throw new RangeError("Invalid path: " + part);
let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
byName[inner] = rule.sort(byName[inner]);
}
}
return ruleNodeProp.add(byName);
}
const ruleNodeProp = new common.NodeProp();
class Rule {
constructor(tags, mode, context, next) {
this.tags = tags;
this.mode = mode;
this.context = context;
this.next = next;
}
sort(other) {
if (!other || other.depth < this.depth) {
this.next = other;
return this;
}
other.next = this.sort(other.next);
return other;
}
get depth() { return this.context ? this.context.length : 0; }
}
/// Define a [highlighter](#highlight.Highlighter) from an array of
/// tag/class pairs. Classes associated with more specific tags will
/// take precedence.
function tagHighlighter(tags, options) {
let map = Object.create(null);
for (let style of tags) {
if (!Array.isArray(style.tag))
map[style.tag.id] = style.class;
else
for (let tag of style.tag)
map[tag.id] = style.class;
}
let { scope, all = null } = options || {};
return {
style: (tags) => {
let cls = all;
for (let tag of tags) {
for (let sub of tag.set) {
let tagClass = map[sub.id];
if (tagClass) {
cls = cls ? cls + " " + tagClass : tagClass;
break;
}
}
}
return cls;
},
scope: scope
};
}
function highlightTags(highlighters, tags) {
let result = null;
for (let highlighter of highlighters) {
let value = highlighter.style(tags);
if (value)
result = result ? result + " " + value : value;
}
return result;
}
/// Highlight the given [tree](#common.Tree) with the given
/// [highlighter](#highlight.Highlighter).
function highlightTree(tree, highlighter,
/// Assign styling to a region of the text. Will be called, in order
/// of position, for any ranges where more than zero classes apply.
/// `classes` is a space separated string of CSS classes.
putStyle,
/// The start of the range to highlight.
from = 0,
/// The end of the range.
to = tree.length) {
let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
builder.flush(to);
}
class HighlightBuilder {
constructor(at, highlighters, span) {
this.at = at;
this.highlighters = highlighters;
this.span = span;
this.class = "";
}
startSpan(at, cls) {
if (cls != this.class) {
this.flush(at);
if (at > this.at)
this.at = at;
this.class = cls;
}
}
flush(to) {
if (to > this.at && this.class)
this.span(this.at, to, this.class);
}
highlightRange(cursor, from, to, inheritedClass, highlighters) {
let { type, from: start, to: end } = cursor;
if (start >= to || end <= from)
return;
if (type.isTop)
highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
let cls = inheritedClass;
let rule = type.prop(ruleNodeProp), opaque = false;
while (rule) {
if (!rule.context || cursor.matchContext(rule.context)) {
let tagCls = highlightTags(highlighters, rule.tags);
if (tagCls) {
if (cls)
cls += " ";
cls += tagCls;
if (rule.mode == 1 /* Inherit */)
inheritedClass += (inheritedClass ? " " : "") + tagCls;
else if (rule.mode == 0 /* Opaque */)
opaque = true;
}
break;
}
rule = rule.next;
}
this.startSpan(cursor.from, cls);
if (opaque)
return;
let mounted = cursor.tree && cursor.tree.prop(common.NodeProp.mounted);
if (mounted && mounted.overlay) {
let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
let hasChild = cursor.firstChild();
for (let i = 0, pos = start;; i++) {
let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
let nextPos = next ? next.from + start : end;
let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
if (rangeFrom < rangeTo && hasChild) {
while (cursor.from < rangeTo) {
this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
this.startSpan(Math.min(to, cursor.to), cls);
if (cursor.to >= nextPos || !cursor.nextSibling())
break;
}
}
if (!next || nextPos > to)
break;
pos = next.to + start;
if (pos > from) {
this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters);
this.startSpan(pos, cls);
}
}
if (hasChild)
cursor.parent();
}
else if (cursor.firstChild()) {
do {
if (cursor.to <= from)
continue;
if (cursor.from >= to)
break;
this.highlightRange(cursor, from, to, inheritedClass, highlighters);
this.startSpan(Math.min(to, cursor.to), cls);
} while (cursor.nextSibling());
cursor.parent();
}
}
}
const t = Tag.define;
const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
/// The default set of highlighting [tags](#highlight.Tag).
///
/// This collection is heavily biased towards programming languages,
/// and necessarily incomplete. A full ontology of syntactic
/// constructs would fill a stack of books, and be impractical to
/// write themes for. So try to make do with this set. If all else
/// fails, [open an
/// issue](https://github.com/codemirror/codemirror.next) to propose a
/// new tag, or [define](#highlight.Tag^define) a local custom tag for
/// your use case.
///
/// Note that it is not obligatory to always attach the most specific
/// tag possible to an element—if your grammar can't easily
/// distinguish a certain type of element (such as a local variable),
/// it is okay to style it as its more general variant (a variable).
///
/// For tags that extend some parent tag, the documentation links to
/// the parent.
const tags = {
/// A comment.
comment,
/// A line [comment](#highlight.tags.comment).
lineComment: t(comment),
/// A block [comment](#highlight.tags.comment).
blockComment: t(comment),
/// A documentation [comment](#highlight.tags.comment).
docComment: t(comment),
/// Any kind of identifier.
name,
/// The [name](#highlight.tags.name) of a variable.
variableName: t(name),
/// A type [name](#highlight.tags.name).
typeName: typeName,
/// A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
tagName: t(typeName),
/// A property or field [name](#highlight.tags.name).
propertyName: propertyName,
/// An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
attributeName: t(propertyName),
/// The [name](#highlight.tags.name) of a class.
className: t(name),
/// A label [name](#highlight.tags.name).
labelName: t(name),
/// A namespace [name](#highlight.tags.name).
namespace: t(name),
/// The [name](#highlight.tags.name) of a macro.
macroName: t(name),
/// A literal value.
literal,
/// A string [literal](#highlight.tags.literal).
string,
/// A documentation [string](#highlight.tags.string).
docString: t(string),
/// A character literal (subtag of [string](#highlight.tags.string)).
character: t(string),
/// An attribute value (subtag of [string](#highlight.tags.string)).
attributeValue: t(string),
/// A number [literal](#highlight.tags.literal).
number,
/// An integer [number](#highlight.tags.number) literal.
integer: t(number),
/// A floating-point [number](#highlight.tags.number) literal.
float: t(number),
/// A boolean [literal](#highlight.tags.literal).
bool: t(literal),
/// Regular expression [literal](#highlight.tags.literal).
regexp: t(literal),
/// An escape [literal](#highlight.tags.literal), for example a
/// backslash escape in a string.
escape: t(literal),
/// A color [literal](#highlight.tags.literal).
color: t(literal),
/// A URL [literal](#highlight.tags.literal).
url: t(literal),
/// A language keyword.
keyword,
/// The [keyword](#highlight.tags.keyword) for the self or this
/// object.
self: t(keyword),
/// The [keyword](#highlight.tags.keyword) for null.
null: t(keyword),
/// A [keyword](#highlight.tags.keyword) denoting some atomic value.
atom: t(keyword),
/// A [keyword](#highlight.tags.keyword) that represents a unit.
unit: t(keyword),
/// A modifier [keyword](#highlight.tags.keyword).
modifier: t(keyword),
/// A [keyword](#highlight.tags.keyword) that acts as an operator.
operatorKeyword: t(keyword),
/// A control-flow related [keyword](#highlight.tags.keyword).
controlKeyword: t(keyword),
/// A [keyword](#highlight.tags.keyword) that defines something.
definitionKeyword: t(keyword),
/// A [keyword](#highlight.tags.keyword) related to defining or
/// interfacing with modules.
moduleKeyword: t(keyword),
/// An operator.
operator,
/// An [operator](#highlight.tags.operator) that defines something.
derefOperator: t(operator),
/// Arithmetic-related [operator](#highlight.tags.operator).
arithmeticOperator: t(operator),
/// Logical [operator](#highlight.tags.operator).
logicOperator: t(operator),
/// Bit [operator](#highlight.tags.operator).
bitwiseOperator: t(operator),
/// Comparison [operator](#highlight.tags.operator).
compareOperator: t(operator),
/// [Operator](#highlight.tags.operator) that updates its operand.
updateOperator: t(operator),
/// [Operator](#highlight.tags.operator) that defines something.
definitionOperator: t(operator),
/// Type-related [operator](#highlight.tags.operator).
typeOperator: t(operator),
/// Control-flow [operator](#highlight.tags.operator).
controlOperator: t(operator),
/// Program or markup punctuation.
punctuation,
/// [Punctuation](#highlight.tags.punctuation) that separates
/// things.
separator: t(punctuation),
/// Bracket-style [punctuation](#highlight.tags.punctuation).
bracket,
/// Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
/// tokens).
angleBracket: t(bracket),
/// Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
/// tokens).
squareBracket: t(bracket),
/// Parentheses (usually `(` and `)` tokens). Subtag of
/// [bracket](#highlight.tags.bracket).
paren: t(bracket),
/// Braces (usually `{` and `}` tokens). Subtag of
/// [bracket](#highlight.tags.bracket).
brace: t(bracket),
/// Content, for example plain text in XML or markup documents.
content,
/// [Content](#highlight.tags.content) that represents a heading.
heading,
/// A level 1 [heading](#highlight.tags.heading).
heading1: t(heading),
/// A level 2 [heading](#highlight.tags.heading).
heading2: t(heading),
/// A level 3 [heading](#highlight.tags.heading).
heading3: t(heading),
/// A level 4 [heading](#highlight.tags.heading).
heading4: t(heading),
/// A level 5 [heading](#highlight.tags.heading).
heading5: t(heading),
/// A level 6 [heading](#highlight.tags.heading).
heading6: t(heading),
/// A prose separator (such as a horizontal rule).
contentSeparator: t(content),
/// [Content](#highlight.tags.content) that represents a list.
list: t(content),
/// [Content](#highlight.tags.content) that represents a quote.
quote: t(content),
/// [Content](#highlight.tags.content) that is emphasized.
emphasis: t(content),
/// [Content](#highlight.tags.content) that is styled strong.
strong: t(content),
/// [Content](#highlight.tags.content) that is part of a link.
link: t(content),
/// [Content](#highlight.tags.content) that is styled as code or
/// monospace.
monospace: t(content),
/// [Content](#highlight.tags.content) that has a strike-through
/// style.
strikethrough: t(content),
/// Inserted text in a change-tracking format.
inserted: t(),
/// Deleted text.
deleted: t(),
/// Changed text.
changed: t(),
/// An invalid or unsyntactic element.
invalid: t(),
/// Metadata or meta-instruction.
meta,
/// [Metadata](#highlight.tags.meta) that applies to the entire
/// document.
documentMeta: t(meta),
/// [Metadata](#highlight.tags.meta) that annotates or adds
/// attributes to a given syntactic element.
annotation: t(meta),
/// Processing instruction or preprocessor directive. Subtag of
/// [meta](#highlight.tags.meta).
processingInstruction: t(meta),
/// [Modifier](#highlight.Tag^defineModifier) that indicates that a
/// given element is being defined. Expected to be used with the
/// various [name](#highlight.tags.name) tags.
definition: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) that indicates that
/// something is constant. Mostly expected to be used with
/// [variable names](#highlight.tags.variableName).
constant: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) used to indicate that
/// a [variable](#highlight.tags.variableName) or [property
/// name](#highlight.tags.propertyName) is being called or defined
/// as a function.
function: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) that can be applied to
/// [names](#highlight.tags.name) to indicate that they belong to
/// the language's standard environment.
standard: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) that indicates a given
/// [names](#highlight.tags.name) is local to some scope.
local: Tag.defineModifier(),
/// A generic variant [modifier](#highlight.Tag^defineModifier) that
/// can be used to tag language-specific alternative variants of
/// some common tag. It is recommended for themes to define special
/// forms of at least the [string](#highlight.tags.string) and
/// [variable name](#highlight.tags.variableName) tags, since those
/// come up a lot.
special: Tag.defineModifier()
};
/// This is a highlighter that adds stable, predictable classes to
/// tokens, for styling with external CSS.
///
/// The following tags are mapped to their name prefixed with `"tok-"`
/// (for example `"tok-comment"`):
///
/// * [`link`](#highlight.tags.link)
/// * [`heading`](#highlight.tags.heading)
/// * [`emphasis`](#highlight.tags.emphasis)
/// * [`strong`](#highlight.tags.strong)
/// * [`keyword`](#highlight.tags.keyword)
/// * [`atom`](#highlight.tags.atom) [`bool`](#highlight.tags.bool)
/// * [`url`](#highlight.tags.url)
/// * [`labelName`](#highlight.tags.labelName)
/// * [`inserted`](#highlight.tags.inserted)
/// * [`deleted`](#highlight.tags.deleted)
/// * [`literal`](#highlight.tags.literal)
/// * [`string`](#highlight.tags.string)
/// * [`number`](#highlight.tags.number)
/// * [`variableName`](#highlight.tags.variableName)
/// * [`typeName`](#highlight.tags.typeName)
/// * [`namespace`](#highlight.tags.namespace)
/// * [`className`](#highlight.tags.className)
/// * [`macroName`](#highlight.tags.macroName)
/// * [`propertyName`](#highlight.tags.propertyName)
/// * [`operator`](#highlight.tags.operator)
/// * [`comment`](#highlight.tags.comment)
/// * [`meta`](#highlight.tags.meta)
/// * [`punctuation`](#highlight.tags.punctuation)
/// * [`invalid`](#highlight.tags.invalid)
///
/// In addition, these mappings are provided:
///
/// * [`regexp`](#highlight.tags.regexp),
/// [`escape`](#highlight.tags.escape), and
/// [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
/// are mapped to `"tok-string2"`
/// * [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
/// to `"tok-variableName2"`
/// * [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
/// to `"tok-variableName tok-local"`
/// * [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
/// to `"tok-variableName tok-definition"`
/// * [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
/// to `"tok-propertyName tok-definition"`
const classHighlighter = tagHighlighter([
{ tag: tags.link, class: "tok-link" },
{ tag: tags.heading, class: "tok-heading" },
{ tag: tags.emphasis, class: "tok-emphasis" },
{ tag: tags.strong, class: "tok-strong" },
{ tag: tags.keyword, class: "tok-keyword" },
{ tag: tags.atom, class: "tok-atom" },
{ tag: tags.bool, class: "tok-bool" },
{ tag: tags.url, class: "tok-url" },
{ tag: tags.labelName, class: "tok-labelName" },
{ tag: tags.inserted, class: "tok-inserted" },
{ tag: tags.deleted, class: "tok-deleted" },
{ tag: tags.literal, class: "tok-literal" },
{ tag: tags.string, class: "tok-string" },
{ tag: tags.number, class: "tok-number" },
{ tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
{ tag: tags.variableName, class: "tok-variableName" },
{ tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
{ tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
{ tag: tags.special(tags.variableName), class: "tok-variableName2" },
{ tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
{ tag: tags.typeName, class: "tok-typeName" },
{ tag: tags.namespace, class: "tok-namespace" },
{ tag: tags.className, class: "tok-className" },
{ tag: tags.macroName, class: "tok-macroName" },
{ tag: tags.propertyName, class: "tok-propertyName" },
{ tag: tags.operator, class: "tok-operator" },
{ tag: tags.comment, class: "tok-comment" },
{ tag: tags.meta, class: "tok-meta" },
{ tag: tags.invalid, class: "tok-invalid" },
{ tag: tags.punctuation, class: "tok-punctuation" }
]);
exports.Tag = Tag;
exports.classHighlighter = classHighlighter;
exports.highlightTags = highlightTags;
exports.highlightTree = highlightTree;
exports.styleTags = styleTags;
exports.tagHighlighter = tagHighlighter;
exports.tags = tags;

View File

@ -0,0 +1,648 @@
import { NodeProp } from '@lezer/common';
let nextTagID = 0;
/// Highlighting tags are markers that denote a highlighting category.
/// They are [associated](#highlight.styleTags) with parts of a syntax
/// tree by a language mode, and then mapped to an actual CSS style by
/// a [highlighter](#highlight.Highlighter).
///
/// Because syntax tree node types and highlight styles have to be
/// able to talk the same language, CodeMirror uses a mostly _closed_
/// [vocabulary](#highlight.tags) of syntax tags (as opposed to
/// traditional open string-based systems, which make it hard for
/// highlighting themes to cover all the tokens produced by the
/// various languages).
///
/// It _is_ possible to [define](#highlight.Tag^define) your own
/// highlighting tags for system-internal use (where you control both
/// the language package and the highlighter), but such tags will not
/// be picked up by regular highlighters (though you can derive them
/// from standard tags to allow highlighters to fall back to those).
class Tag {
/// @internal
constructor(
/// The set of this tag and all its parent tags, starting with
/// this one itself and sorted in order of decreasing specificity.
set,
/// The base unmodified tag that this one is based on, if it's
/// modified @internal
base,
/// The modifiers applied to this.base @internal
modified) {
this.set = set;
this.base = base;
this.modified = modified;
/// @internal
this.id = nextTagID++;
}
/// Define a new tag. If `parent` is given, the tag is treated as a
/// sub-tag of that parent, and
/// [highlighters](#highlight.tagHighlighter) that don't mention
/// this tag will try to fall back to the parent tag (or grandparent
/// tag, etc).
static define(parent) {
if (parent === null || parent === void 0 ? void 0 : parent.base)
throw new Error("Can not derive from a modified tag");
let tag = new Tag([], null, []);
tag.set.push(tag);
if (parent)
for (let t of parent.set)
tag.set.push(t);
return tag;
}
/// Define a tag _modifier_, which is a function that, given a tag,
/// will return a tag that is a subtag of the original. Applying the
/// same modifier to a twice tag will return the same value (`m1(t1)
/// == m1(t1)`) and applying multiple modifiers will, regardless or
/// order, produce the same tag (`m1(m2(t1)) == m2(m1(t1))`).
///
/// When multiple modifiers are applied to a given base tag, each
/// smaller set of modifiers is registered as a parent, so that for
/// example `m1(m2(m3(t1)))` is a subtype of `m1(m2(t1))`,
/// `m1(m3(t1)`, and so on.
static defineModifier() {
let mod = new Modifier;
return (tag) => {
if (tag.modified.indexOf(mod) > -1)
return tag;
return Modifier.get(tag.base || tag, tag.modified.concat(mod).sort((a, b) => a.id - b.id));
};
}
}
let nextModifierID = 0;
class Modifier {
constructor() {
this.instances = [];
this.id = nextModifierID++;
}
static get(base, mods) {
if (!mods.length)
return base;
let exists = mods[0].instances.find(t => t.base == base && sameArray(mods, t.modified));
if (exists)
return exists;
let set = [], tag = new Tag(set, base, mods);
for (let m of mods)
m.instances.push(tag);
let configs = permute(mods);
for (let parent of base.set)
for (let config of configs)
set.push(Modifier.get(parent, config));
return tag;
}
}
function sameArray(a, b) {
return a.length == b.length && a.every((x, i) => x == b[i]);
}
function permute(array) {
let result = [array];
for (let i = 0; i < array.length; i++) {
for (let a of permute(array.slice(0, i).concat(array.slice(i + 1))))
result.push(a);
}
return result;
}
/// This function is used to add a set of tags to a language syntax
/// via [`NodeSet.extend`](#common.NodeSet.extend) or
/// [`LRParser.configure`](#lr.LRParser.configure).
///
/// The argument object maps node selectors to [highlighting
/// tags](#highlight.Tag) or arrays of tags.
///
/// Node selectors may hold one or more (space-separated) node paths.
/// Such a path can be a [node name](#common.NodeType.name), or
/// multiple node names (or `*` wildcards) separated by slash
/// characters, as in `"Block/Declaration/VariableName"`. Such a path
/// matches the final node but only if its direct parent nodes are the
/// other nodes mentioned. A `*` in such a path matches any parent,
/// but only a single level—wildcards that match multiple parents
/// aren't supported, both for efficiency reasons and because Lezer
/// trees make it rather hard to reason about what they would match.)
///
/// A path can be ended with `/...` to indicate that the tag assigned
/// to the node should also apply to all child nodes, even if they
/// match their own style (by default, only the innermost style is
/// used).
///
/// When a path ends in `!`, as in `Attribute!`, no further matching
/// happens for the node's child nodes, and the entire node gets the
/// given style.
///
/// In this notation, node names that contain `/`, `!`, `*`, or `...`
/// must be quoted as JSON strings.
///
/// For example:
///
/// ```javascript
/// parser.withProps(
/// styleTags({
/// // Style Number and BigNumber nodes
/// "Number BigNumber": tags.number,
/// // Style Escape nodes whose parent is String
/// "String/Escape": tags.escape,
/// // Style anything inside Attributes nodes
/// "Attributes!": tags.meta,
/// // Add a style to all content inside Italic nodes
/// "Italic/...": tags.emphasis,
/// // Style InvalidString nodes as both `string` and `invalid`
/// "InvalidString": [tags.string, tags.invalid],
/// // Style the node named "/" as punctuation
/// '"/"': tags.punctuation
/// })
/// )
/// ```
function styleTags(spec) {
let byName = Object.create(null);
for (let prop in spec) {
let tags = spec[prop];
if (!Array.isArray(tags))
tags = [tags];
for (let part of prop.split(" "))
if (part) {
let pieces = [], mode = 2 /* Normal */, rest = part;
for (let pos = 0;;) {
if (rest == "..." && pos > 0 && pos + 3 == part.length) {
mode = 1 /* Inherit */;
break;
}
let m = /^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(rest);
if (!m)
throw new RangeError("Invalid path: " + part);
pieces.push(m[0] == "*" ? "" : m[0][0] == '"' ? JSON.parse(m[0]) : m[0]);
pos += m[0].length;
if (pos == part.length)
break;
let next = part[pos++];
if (pos == part.length && next == "!") {
mode = 0 /* Opaque */;
break;
}
if (next != "/")
throw new RangeError("Invalid path: " + part);
rest = part.slice(pos);
}
let last = pieces.length - 1, inner = pieces[last];
if (!inner)
throw new RangeError("Invalid path: " + part);
let rule = new Rule(tags, mode, last > 0 ? pieces.slice(0, last) : null);
byName[inner] = rule.sort(byName[inner]);
}
}
return ruleNodeProp.add(byName);
}
const ruleNodeProp = new NodeProp();
class Rule {
constructor(tags, mode, context, next) {
this.tags = tags;
this.mode = mode;
this.context = context;
this.next = next;
}
sort(other) {
if (!other || other.depth < this.depth) {
this.next = other;
return this;
}
other.next = this.sort(other.next);
return other;
}
get depth() { return this.context ? this.context.length : 0; }
}
/// Define a [highlighter](#highlight.Highlighter) from an array of
/// tag/class pairs. Classes associated with more specific tags will
/// take precedence.
function tagHighlighter(tags, options) {
let map = Object.create(null);
for (let style of tags) {
if (!Array.isArray(style.tag))
map[style.tag.id] = style.class;
else
for (let tag of style.tag)
map[tag.id] = style.class;
}
let { scope, all = null } = options || {};
return {
style: (tags) => {
let cls = all;
for (let tag of tags) {
for (let sub of tag.set) {
let tagClass = map[sub.id];
if (tagClass) {
cls = cls ? cls + " " + tagClass : tagClass;
break;
}
}
}
return cls;
},
scope: scope
};
}
function highlightTags(highlighters, tags) {
let result = null;
for (let highlighter of highlighters) {
let value = highlighter.style(tags);
if (value)
result = result ? result + " " + value : value;
}
return result;
}
/// Highlight the given [tree](#common.Tree) with the given
/// [highlighter](#highlight.Highlighter).
function highlightTree(tree, highlighter,
/// Assign styling to a region of the text. Will be called, in order
/// of position, for any ranges where more than zero classes apply.
/// `classes` is a space separated string of CSS classes.
putStyle,
/// The start of the range to highlight.
from = 0,
/// The end of the range.
to = tree.length) {
let builder = new HighlightBuilder(from, Array.isArray(highlighter) ? highlighter : [highlighter], putStyle);
builder.highlightRange(tree.cursor(), from, to, "", builder.highlighters);
builder.flush(to);
}
class HighlightBuilder {
constructor(at, highlighters, span) {
this.at = at;
this.highlighters = highlighters;
this.span = span;
this.class = "";
}
startSpan(at, cls) {
if (cls != this.class) {
this.flush(at);
if (at > this.at)
this.at = at;
this.class = cls;
}
}
flush(to) {
if (to > this.at && this.class)
this.span(this.at, to, this.class);
}
highlightRange(cursor, from, to, inheritedClass, highlighters) {
let { type, from: start, to: end } = cursor;
if (start >= to || end <= from)
return;
if (type.isTop)
highlighters = this.highlighters.filter(h => !h.scope || h.scope(type));
let cls = inheritedClass;
let rule = type.prop(ruleNodeProp), opaque = false;
while (rule) {
if (!rule.context || cursor.matchContext(rule.context)) {
let tagCls = highlightTags(highlighters, rule.tags);
if (tagCls) {
if (cls)
cls += " ";
cls += tagCls;
if (rule.mode == 1 /* Inherit */)
inheritedClass += (inheritedClass ? " " : "") + tagCls;
else if (rule.mode == 0 /* Opaque */)
opaque = true;
}
break;
}
rule = rule.next;
}
this.startSpan(cursor.from, cls);
if (opaque)
return;
let mounted = cursor.tree && cursor.tree.prop(NodeProp.mounted);
if (mounted && mounted.overlay) {
let inner = cursor.node.enter(mounted.overlay[0].from + start, 1);
let innerHighlighters = this.highlighters.filter(h => !h.scope || h.scope(mounted.tree.type));
let hasChild = cursor.firstChild();
for (let i = 0, pos = start;; i++) {
let next = i < mounted.overlay.length ? mounted.overlay[i] : null;
let nextPos = next ? next.from + start : end;
let rangeFrom = Math.max(from, pos), rangeTo = Math.min(to, nextPos);
if (rangeFrom < rangeTo && hasChild) {
while (cursor.from < rangeTo) {
this.highlightRange(cursor, rangeFrom, rangeTo, inheritedClass, highlighters);
this.startSpan(Math.min(to, cursor.to), cls);
if (cursor.to >= nextPos || !cursor.nextSibling())
break;
}
}
if (!next || nextPos > to)
break;
pos = next.to + start;
if (pos > from) {
this.highlightRange(inner.cursor(), Math.max(from, next.from + start), Math.min(to, pos), inheritedClass, innerHighlighters);
this.startSpan(pos, cls);
}
}
if (hasChild)
cursor.parent();
}
else if (cursor.firstChild()) {
do {
if (cursor.to <= from)
continue;
if (cursor.from >= to)
break;
this.highlightRange(cursor, from, to, inheritedClass, highlighters);
this.startSpan(Math.min(to, cursor.to), cls);
} while (cursor.nextSibling());
cursor.parent();
}
}
}
const t = Tag.define;
const comment = t(), name = t(), typeName = t(name), propertyName = t(name), literal = t(), string = t(literal), number = t(literal), content = t(), heading = t(content), keyword = t(), operator = t(), punctuation = t(), bracket = t(punctuation), meta = t();
/// The default set of highlighting [tags](#highlight.Tag).
///
/// This collection is heavily biased towards programming languages,
/// and necessarily incomplete. A full ontology of syntactic
/// constructs would fill a stack of books, and be impractical to
/// write themes for. So try to make do with this set. If all else
/// fails, [open an
/// issue](https://github.com/codemirror/codemirror.next) to propose a
/// new tag, or [define](#highlight.Tag^define) a local custom tag for
/// your use case.
///
/// Note that it is not obligatory to always attach the most specific
/// tag possible to an element—if your grammar can't easily
/// distinguish a certain type of element (such as a local variable),
/// it is okay to style it as its more general variant (a variable).
///
/// For tags that extend some parent tag, the documentation links to
/// the parent.
const tags = {
/// A comment.
comment,
/// A line [comment](#highlight.tags.comment).
lineComment: t(comment),
/// A block [comment](#highlight.tags.comment).
blockComment: t(comment),
/// A documentation [comment](#highlight.tags.comment).
docComment: t(comment),
/// Any kind of identifier.
name,
/// The [name](#highlight.tags.name) of a variable.
variableName: t(name),
/// A type [name](#highlight.tags.name).
typeName: typeName,
/// A tag name (subtag of [`typeName`](#highlight.tags.typeName)).
tagName: t(typeName),
/// A property or field [name](#highlight.tags.name).
propertyName: propertyName,
/// An attribute name (subtag of [`propertyName`](#highlight.tags.propertyName)).
attributeName: t(propertyName),
/// The [name](#highlight.tags.name) of a class.
className: t(name),
/// A label [name](#highlight.tags.name).
labelName: t(name),
/// A namespace [name](#highlight.tags.name).
namespace: t(name),
/// The [name](#highlight.tags.name) of a macro.
macroName: t(name),
/// A literal value.
literal,
/// A string [literal](#highlight.tags.literal).
string,
/// A documentation [string](#highlight.tags.string).
docString: t(string),
/// A character literal (subtag of [string](#highlight.tags.string)).
character: t(string),
/// An attribute value (subtag of [string](#highlight.tags.string)).
attributeValue: t(string),
/// A number [literal](#highlight.tags.literal).
number,
/// An integer [number](#highlight.tags.number) literal.
integer: t(number),
/// A floating-point [number](#highlight.tags.number) literal.
float: t(number),
/// A boolean [literal](#highlight.tags.literal).
bool: t(literal),
/// Regular expression [literal](#highlight.tags.literal).
regexp: t(literal),
/// An escape [literal](#highlight.tags.literal), for example a
/// backslash escape in a string.
escape: t(literal),
/// A color [literal](#highlight.tags.literal).
color: t(literal),
/// A URL [literal](#highlight.tags.literal).
url: t(literal),
/// A language keyword.
keyword,
/// The [keyword](#highlight.tags.keyword) for the self or this
/// object.
self: t(keyword),
/// The [keyword](#highlight.tags.keyword) for null.
null: t(keyword),
/// A [keyword](#highlight.tags.keyword) denoting some atomic value.
atom: t(keyword),
/// A [keyword](#highlight.tags.keyword) that represents a unit.
unit: t(keyword),
/// A modifier [keyword](#highlight.tags.keyword).
modifier: t(keyword),
/// A [keyword](#highlight.tags.keyword) that acts as an operator.
operatorKeyword: t(keyword),
/// A control-flow related [keyword](#highlight.tags.keyword).
controlKeyword: t(keyword),
/// A [keyword](#highlight.tags.keyword) that defines something.
definitionKeyword: t(keyword),
/// A [keyword](#highlight.tags.keyword) related to defining or
/// interfacing with modules.
moduleKeyword: t(keyword),
/// An operator.
operator,
/// An [operator](#highlight.tags.operator) that defines something.
derefOperator: t(operator),
/// Arithmetic-related [operator](#highlight.tags.operator).
arithmeticOperator: t(operator),
/// Logical [operator](#highlight.tags.operator).
logicOperator: t(operator),
/// Bit [operator](#highlight.tags.operator).
bitwiseOperator: t(operator),
/// Comparison [operator](#highlight.tags.operator).
compareOperator: t(operator),
/// [Operator](#highlight.tags.operator) that updates its operand.
updateOperator: t(operator),
/// [Operator](#highlight.tags.operator) that defines something.
definitionOperator: t(operator),
/// Type-related [operator](#highlight.tags.operator).
typeOperator: t(operator),
/// Control-flow [operator](#highlight.tags.operator).
controlOperator: t(operator),
/// Program or markup punctuation.
punctuation,
/// [Punctuation](#highlight.tags.punctuation) that separates
/// things.
separator: t(punctuation),
/// Bracket-style [punctuation](#highlight.tags.punctuation).
bracket,
/// Angle [brackets](#highlight.tags.bracket) (usually `<` and `>`
/// tokens).
angleBracket: t(bracket),
/// Square [brackets](#highlight.tags.bracket) (usually `[` and `]`
/// tokens).
squareBracket: t(bracket),
/// Parentheses (usually `(` and `)` tokens). Subtag of
/// [bracket](#highlight.tags.bracket).
paren: t(bracket),
/// Braces (usually `{` and `}` tokens). Subtag of
/// [bracket](#highlight.tags.bracket).
brace: t(bracket),
/// Content, for example plain text in XML or markup documents.
content,
/// [Content](#highlight.tags.content) that represents a heading.
heading,
/// A level 1 [heading](#highlight.tags.heading).
heading1: t(heading),
/// A level 2 [heading](#highlight.tags.heading).
heading2: t(heading),
/// A level 3 [heading](#highlight.tags.heading).
heading3: t(heading),
/// A level 4 [heading](#highlight.tags.heading).
heading4: t(heading),
/// A level 5 [heading](#highlight.tags.heading).
heading5: t(heading),
/// A level 6 [heading](#highlight.tags.heading).
heading6: t(heading),
/// A prose separator (such as a horizontal rule).
contentSeparator: t(content),
/// [Content](#highlight.tags.content) that represents a list.
list: t(content),
/// [Content](#highlight.tags.content) that represents a quote.
quote: t(content),
/// [Content](#highlight.tags.content) that is emphasized.
emphasis: t(content),
/// [Content](#highlight.tags.content) that is styled strong.
strong: t(content),
/// [Content](#highlight.tags.content) that is part of a link.
link: t(content),
/// [Content](#highlight.tags.content) that is styled as code or
/// monospace.
monospace: t(content),
/// [Content](#highlight.tags.content) that has a strike-through
/// style.
strikethrough: t(content),
/// Inserted text in a change-tracking format.
inserted: t(),
/// Deleted text.
deleted: t(),
/// Changed text.
changed: t(),
/// An invalid or unsyntactic element.
invalid: t(),
/// Metadata or meta-instruction.
meta,
/// [Metadata](#highlight.tags.meta) that applies to the entire
/// document.
documentMeta: t(meta),
/// [Metadata](#highlight.tags.meta) that annotates or adds
/// attributes to a given syntactic element.
annotation: t(meta),
/// Processing instruction or preprocessor directive. Subtag of
/// [meta](#highlight.tags.meta).
processingInstruction: t(meta),
/// [Modifier](#highlight.Tag^defineModifier) that indicates that a
/// given element is being defined. Expected to be used with the
/// various [name](#highlight.tags.name) tags.
definition: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) that indicates that
/// something is constant. Mostly expected to be used with
/// [variable names](#highlight.tags.variableName).
constant: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) used to indicate that
/// a [variable](#highlight.tags.variableName) or [property
/// name](#highlight.tags.propertyName) is being called or defined
/// as a function.
function: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) that can be applied to
/// [names](#highlight.tags.name) to indicate that they belong to
/// the language's standard environment.
standard: Tag.defineModifier(),
/// [Modifier](#highlight.Tag^defineModifier) that indicates a given
/// [names](#highlight.tags.name) is local to some scope.
local: Tag.defineModifier(),
/// A generic variant [modifier](#highlight.Tag^defineModifier) that
/// can be used to tag language-specific alternative variants of
/// some common tag. It is recommended for themes to define special
/// forms of at least the [string](#highlight.tags.string) and
/// [variable name](#highlight.tags.variableName) tags, since those
/// come up a lot.
special: Tag.defineModifier()
};
/// This is a highlighter that adds stable, predictable classes to
/// tokens, for styling with external CSS.
///
/// The following tags are mapped to their name prefixed with `"tok-"`
/// (for example `"tok-comment"`):
///
/// * [`link`](#highlight.tags.link)
/// * [`heading`](#highlight.tags.heading)
/// * [`emphasis`](#highlight.tags.emphasis)
/// * [`strong`](#highlight.tags.strong)
/// * [`keyword`](#highlight.tags.keyword)
/// * [`atom`](#highlight.tags.atom) [`bool`](#highlight.tags.bool)
/// * [`url`](#highlight.tags.url)
/// * [`labelName`](#highlight.tags.labelName)
/// * [`inserted`](#highlight.tags.inserted)
/// * [`deleted`](#highlight.tags.deleted)
/// * [`literal`](#highlight.tags.literal)
/// * [`string`](#highlight.tags.string)
/// * [`number`](#highlight.tags.number)
/// * [`variableName`](#highlight.tags.variableName)
/// * [`typeName`](#highlight.tags.typeName)
/// * [`namespace`](#highlight.tags.namespace)
/// * [`className`](#highlight.tags.className)
/// * [`macroName`](#highlight.tags.macroName)
/// * [`propertyName`](#highlight.tags.propertyName)
/// * [`operator`](#highlight.tags.operator)
/// * [`comment`](#highlight.tags.comment)
/// * [`meta`](#highlight.tags.meta)
/// * [`punctuation`](#highlight.tags.punctuation)
/// * [`invalid`](#highlight.tags.invalid)
///
/// In addition, these mappings are provided:
///
/// * [`regexp`](#highlight.tags.regexp),
/// [`escape`](#highlight.tags.escape), and
/// [`special`](#highlight.tags.special)[`(string)`](#highlight.tags.string)
/// are mapped to `"tok-string2"`
/// * [`special`](#highlight.tags.special)[`(variableName)`](#highlight.tags.variableName)
/// to `"tok-variableName2"`
/// * [`local`](#highlight.tags.local)[`(variableName)`](#highlight.tags.variableName)
/// to `"tok-variableName tok-local"`
/// * [`definition`](#highlight.tags.definition)[`(variableName)`](#highlight.tags.variableName)
/// to `"tok-variableName tok-definition"`
/// * [`definition`](#highlight.tags.definition)[`(propertyName)`](#highlight.tags.propertyName)
/// to `"tok-propertyName tok-definition"`
const classHighlighter = tagHighlighter([
{ tag: tags.link, class: "tok-link" },
{ tag: tags.heading, class: "tok-heading" },
{ tag: tags.emphasis, class: "tok-emphasis" },
{ tag: tags.strong, class: "tok-strong" },
{ tag: tags.keyword, class: "tok-keyword" },
{ tag: tags.atom, class: "tok-atom" },
{ tag: tags.bool, class: "tok-bool" },
{ tag: tags.url, class: "tok-url" },
{ tag: tags.labelName, class: "tok-labelName" },
{ tag: tags.inserted, class: "tok-inserted" },
{ tag: tags.deleted, class: "tok-deleted" },
{ tag: tags.literal, class: "tok-literal" },
{ tag: tags.string, class: "tok-string" },
{ tag: tags.number, class: "tok-number" },
{ tag: [tags.regexp, tags.escape, tags.special(tags.string)], class: "tok-string2" },
{ tag: tags.variableName, class: "tok-variableName" },
{ tag: tags.local(tags.variableName), class: "tok-variableName tok-local" },
{ tag: tags.definition(tags.variableName), class: "tok-variableName tok-definition" },
{ tag: tags.special(tags.variableName), class: "tok-variableName2" },
{ tag: tags.definition(tags.propertyName), class: "tok-propertyName tok-definition" },
{ tag: tags.typeName, class: "tok-typeName" },
{ tag: tags.namespace, class: "tok-namespace" },
{ tag: tags.className, class: "tok-className" },
{ tag: tags.macroName, class: "tok-macroName" },
{ tag: tags.propertyName, class: "tok-propertyName" },
{ tag: tags.operator, class: "tok-operator" },
{ tag: tags.comment, class: "tok-comment" },
{ tag: tags.meta, class: "tok-meta" },
{ tag: tags.invalid, class: "tok-invalid" },
{ tag: tags.punctuation, class: "tok-punctuation" }
]);
export { Tag, classHighlighter, highlightTags, highlightTree, styleTags, tagHighlighter, tags };

View File

@ -0,0 +1,34 @@
{
"name": "@lezer/highlight",
"version": "0.16.0",
"description": "Highlighting system for Lezer parse trees",
"main": "dist/index.cjs",
"type": "module",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"module": "dist/index.js",
"types": "dist/highlight.d.ts",
"author": "Marijn Haverbeke <marijnh@gmail.com>",
"license": "MIT",
"devDependencies": {
"rollup": "^2.52.2",
"@rollup/plugin-commonjs": "^15.1.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"rollup-plugin-typescript2": "^0.30.0",
"typescript": "^4.3.4"
},
"dependencies": {
"@lezer/common": "^0.16.0"
},
"files": ["dist"],
"repository": {
"type" : "git",
"url" : "https://github.com/lezer-parser/highlight.git"
},
"scripts": {
"watch": "rollup -w -c rollup.config.js",
"prepare": "rollup -c rollup.config.js"
}
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@ -0,0 +1,25 @@
# @lezer/lr
[ [**WEBSITE**](http://lezer.codemirror.net) | [**ISSUES**](https://github.com/lezer-parser/lezer/issues) | [**FORUM**](https://discuss.codemirror.net/c/lezer) | [**CHANGELOG**](https://github.com/lezer-parser/lr/blob/master/CHANGELOG.md) ]
Lezer ("reader" in Dutch, pronounced pretty much as laser) is an
incremental GLR parser intended for use in an editor or similar
system, which needs to keep a representation of the program current
during changes and in the face of syntax errors.
It prioritizes speed and compactness (both of parser table files and
of syntax tree) over having a highly usable parse tree—trees nodes are
just blobs with a start, end, tag, and set of child nodes, with no
further labeling of child nodes or extra metadata.
This package contains the run-time LR parser library. It consumes
parsers generated by
[@lezer/generator](https://github.com/lezer-parser/generator).
The parser programming interface is documented on [the
website](https://lezer.codemirror.net/docs/ref/#lr).
The code is licensed under an MIT license.
This project was hugely inspired by
[tree-sitter](http://tree-sitter.github.io/tree-sitter/).

View File

@ -0,0 +1,45 @@
export declare const enum Action {
ReduceFlag = 65536,
ValueMask = 65535,
ReduceDepthShift = 19,
RepeatFlag = 131072,
GotoFlag = 131072,
StayFlag = 262144
}
export declare const enum StateFlag {
Skipped = 1,
Accepting = 2
}
export declare const enum Specialize {
Specialize = 0,
Extend = 1
}
export declare const enum Term {
Err = 0
}
export declare const enum Seq {
End = 65535,
Done = 0,
Next = 1,
Other = 2
}
export declare const enum ParseState {
Flags = 0,
Actions = 1,
Skip = 2,
TokenizerMask = 3,
DefaultReduce = 4,
ForcedReduce = 5,
Size = 6
}
export declare const enum Encode {
BigValCode = 126,
BigVal = 65535,
Start = 32,
Gap1 = 34,
Gap2 = 92,
Base = 46
}
export declare const enum File {
Version = 14
}

View File

@ -0,0 +1,5 @@
export declare function decodeArray<T extends {
[i: number]: number;
} = Uint16Array>(input: string | T, Type?: {
new (n: number): T;
}): T;

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,3 @@
export { LRParser, ParserConfig, ContextTracker } from "./parse";
export { InputStream, ExternalTokenizer } from "./token";
export { Stack } from "./stack";

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,102 @@
import { Tree, TreeFragment, NodeSet, NodeType, NodePropSource, Input, PartialParse, Parser, ParseWrapper } from "@lezer/common";
import { Stack } from "./stack";
import { Tokenizer, ExternalTokenizer, CachedToken, InputStream } from "./token";
declare class FragmentCursor {
readonly fragments: readonly TreeFragment[];
readonly nodeSet: NodeSet;
i: number;
fragment: TreeFragment | null;
safeFrom: number;
safeTo: number;
trees: Tree[];
start: number[];
index: number[];
nextStart: number;
constructor(fragments: readonly TreeFragment[], nodeSet: NodeSet);
nextFragment(): void;
nodeAt(pos: number): Tree | null;
}
declare class TokenCache {
readonly stream: InputStream;
tokens: CachedToken[];
mainToken: CachedToken | null;
actions: number[];
constructor(parser: LRParser, stream: InputStream);
getActions(stack: Stack): number[];
getMainToken(stack: Stack): CachedToken;
updateCachedToken(token: CachedToken, tokenizer: Tokenizer, stack: Stack): void;
putAction(action: number, token: number, end: number, index: number): number;
addActions(stack: Stack, token: number, end: number, index: number): number;
}
export declare class Parse implements PartialParse {
readonly parser: LRParser;
readonly input: Input;
readonly ranges: readonly {
from: number;
to: number;
}[];
stacks: Stack[];
recovering: number;
fragments: FragmentCursor | null;
nextStackID: number;
minStackPos: number;
reused: Tree[];
stream: InputStream;
tokens: TokenCache;
topTerm: number;
stoppedAt: null | number;
constructor(parser: LRParser, input: Input, fragments: readonly TreeFragment[], ranges: readonly {
from: number;
to: number;
}[]);
get parsedPos(): number;
advance(): Tree;
stopAt(pos: number): void;
private advanceStack;
private advanceFully;
private runRecovery;
stackToTree(stack: Stack): Tree;
private stackID;
}
export declare class Dialect {
readonly source: string | undefined;
readonly flags: readonly boolean[];
readonly disabled: null | Uint8Array;
constructor(source: string | undefined, flags: readonly boolean[], disabled: null | Uint8Array);
allows(term: number): boolean;
}
export declare class ContextTracker<T> {
constructor(spec: {
start: T;
shift?(context: T, term: number, stack: Stack, input: InputStream): T;
reduce?(context: T, term: number, stack: Stack, input: InputStream): T;
reuse?(context: T, node: Tree, stack: Stack, input: InputStream): T;
hash?(context: T): number;
strict?: boolean;
});
}
export interface ParserConfig {
props?: readonly NodePropSource[];
top?: string;
dialect?: string;
tokenizers?: {
from: ExternalTokenizer;
to: ExternalTokenizer;
}[];
contextTracker?: ContextTracker<any>;
strict?: boolean;
wrap?: ParseWrapper;
bufferLength?: number;
}
export declare class LRParser extends Parser {
readonly nodeSet: NodeSet;
createParse(input: Input, fragments: readonly TreeFragment[], ranges: readonly {
from: number;
to: number;
}[]): PartialParse;
configure(config: ParserConfig): LRParser;
hasWrappers(): boolean;
getName(term: number): string;
get topNode(): NodeType;
}
export {};

View File

@ -0,0 +1,34 @@
import { BufferCursor } from "@lezer/common";
export declare class Stack {
pos: number;
get context(): any;
canShift(term: number): boolean;
get parser(): import("./parse").LRParser;
dialectEnabled(dialectID: number): boolean;
private shiftContext;
private reduceContext;
private updateContext;
}
export declare const enum Recover {
Insert = 200,
Delete = 190,
Reduce = 100,
MaxNext = 4,
MaxInsertStackDepth = 300,
DampenInsertStackDepth = 120
}
export declare class StackBufferCursor implements BufferCursor {
stack: Stack;
pos: number;
index: number;
buffer: number[];
constructor(stack: Stack, pos: number, index: number);
static create(stack: Stack, pos?: number): StackBufferCursor;
maybeNext(): void;
get id(): number;
get start(): number;
get end(): number;
get size(): number;
next(): void;
fork(): StackBufferCursor;
}

View File

@ -0,0 +1,36 @@
import { Stack } from "./stack";
export declare class CachedToken {
start: number;
value: number;
end: number;
extended: number;
lookAhead: number;
mask: number;
context: number;
}
export declare class InputStream {
private chunk2;
private chunk2Pos;
next: number;
pos: number;
private rangeIndex;
private range;
resolveOffset(offset: number, assoc: -1 | 1): number;
peek(offset: number): any;
acceptToken(token: number, endOffset?: number): void;
private getChunk;
private readNext;
advance(n?: number): number;
private setDone;
}
export interface Tokenizer {
}
interface ExternalOptions {
contextual?: boolean;
fallback?: boolean;
extend?: boolean;
}
export declare class ExternalTokenizer implements Tokenizer {
constructor(token: (input: InputStream, stack: Stack) => void, options?: ExternalOptions);
}
export {};

View File

@ -0,0 +1,35 @@
{
"name": "@lezer/lr",
"version": "0.16.3",
"description": "Incremental parser",
"main": "dist/index.cjs",
"type": "module",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"module": "dist/index.js",
"types": "dist/index.d.ts",
"author": "Marijn Haverbeke <marijnh@gmail.com>",
"license": "MIT",
"repository": {
"type" : "git",
"url" : "https://github.com/lezer-parser/lr.git"
},
"devDependencies": {
"rollup": "^2.52.2",
"@rollup/plugin-commonjs": "^15.1.0",
"@rollup/plugin-node-resolve": "^9.0.0",
"rollup-plugin-typescript2": "^0.30.0",
"typescript": "^4.3.4"
},
"dependencies": {
"@lezer/common": "^0.16.0"
},
"files": ["dist"],
"scripts": {
"test": "echo 'Tests are in @lezer/generator'",
"watch": "rollup -w -c rollup.config.js",
"prepare": "rollup -c rollup.config.js"
}
}

View File

@ -0,0 +1,44 @@
{
"name": "@codemirror/basic-setup",
"version": "0.20.0",
"description": "Example configuration for the CodeMirror code editor",
"scripts": {
"test": "cm-runtests",
"prepare": "cm-buildhelper src/basic-setup.ts"
},
"keywords": [
"editor",
"code"
],
"author": {
"name": "Marijn Haverbeke",
"email": "marijnh@gmail.com",
"url": "http://marijnhaverbeke.nl"
},
"type": "module",
"main": "dist/index.cjs",
"exports": {
"import": "./dist/index.js",
"require": "./dist/index.cjs"
},
"types": "dist/index.d.ts",
"module": "dist/index.js",
"sideEffects": false,
"license": "MIT",
"dependencies": {
"@codemirror/autocomplete": "^0.20.0",
"@codemirror/commands": "^0.20.0",
"@codemirror/language": "^0.20.0",
"@codemirror/lint": "^0.20.0",
"@codemirror/search": "^0.20.0",
"@codemirror/state": "^0.20.0",
"@codemirror/view": "^0.20.0"
},
"devDependencies": {
"@codemirror/buildhelper": "^0.1.5"
},
"repository": {
"type": "git",
"url": "https://github.com/codemirror/basic-setup.git"
}
}

View File

@ -0,0 +1,16 @@
name: Trigger CI
on: push
jobs:
build:
name: Dispatch to main repo
runs-on: ubuntu-latest
steps:
- name: Emit repository_dispatch
uses: mvasigh/dispatch-action@main
with:
# You should create a personal access token and store it in your repository
token: ${{ secrets.DISPATCH_AUTH }}
repo: codemirror.next
owner: codemirror
event_type: push

168
frontend/node_modules/@codemirror/commands/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,168 @@
## 0.20.0 (2022-04-20)
### Breaking changes
There is no longer a separate `commentKeymap`. Those bindings are now part of `defaultKeymap`.
### Bug fixes
Make `cursorPageUp` and `cursorPageDown` move by window height when the editor is higher than the window.
Make sure the default behavior of Home/End is prevented, since it could produce unexpected results on macOS.
### New features
The exports from @codemirror/comment are now available in this package.
The exports from the @codemirror/history package are now available from this package.
## 0.19.8 (2022-01-26)
### Bug fixes
`deleteCharBackward` now removes extending characters one at a time, rather than deleting the entire glyph at once.
Alt-v is no longer bound in `emacsStyleKeymap` and macOS's `standardKeymap`, because macOS doesn't bind it by default and it conflicts with some keyboard layouts.
## 0.19.7 (2022-01-11)
### Bug fixes
Don't bind Alt-\< and Alt-> on macOS by default, since those interfere with some keyboard layouts. Make cursorPageUp/Down scroll the view to keep the cursor in place
`cursorPageUp` and `cursorPageDown` now scroll the view by the amount that the cursor moved.
## 0.19.6 (2021-12-10)
### Bug fixes
The standard keymap no longer overrides Shift-Delete, in order to allow the native behavior of that key to happen on platforms that support it.
## 0.19.5 (2021-09-21)
### New features
Adds an `insertBlankLine` command which creates an empty line below the selection, and binds it to Mod-Enter in the default keymap.
## 0.19.4 (2021-09-13)
### Bug fixes
Make commands that affect the editor's content check `state.readOnly` and return false when that is true.
## 0.19.3 (2021-09-09)
### Bug fixes
Make by-line cursor motion commands move the cursor to the start/end of the document when they hit the first/last line.
Fix a bug where `deleteCharForward`/`Backward` behaved incorrectly when deleting directly before or after an atomic range.
## 0.19.2 (2021-08-24)
### New features
New commands `cursorSubwordForward`, `cursorSubwordBackward`, `selectSubwordForward`, and `selectSubwordBackward` which implement motion by camel case subword.
## 0.19.1 (2021-08-11)
### Bug fixes
Fix incorrect versions for @lezer dependencies.
## 0.19.0 (2021-08-11)
### Breaking changes
Change default binding for backspace to `deleteCharBackward`, drop `deleteCodePointBackward`/`Forward` from the library.
`defaultTabBinding` was removed.
### Bug fixes
Drop Alt-d, Alt-f, and Alt-b bindings from `emacsStyleKeymap` (and thus from the default macOS bindings).
`deleteCharBackward` and `deleteCharForward` now take atomic ranges into account.
### New features
Attach more granular user event strings to transactions.
The module exports a new binding `indentWithTab` that binds tab and shift-tab to `indentMore` and `indentLess`.
## 0.18.3 (2021-06-11)
### Bug fixes
`moveLineDown` will no longer incorrectly grow the selection.
Line-based commands will no longer include lines where a range selection ends right at the start of the line.
## 0.18.2 (2021-05-06)
### Bug fixes
Use Ctrl-l, not Alt-l, to bind `selectLine` on macOS, to avoid conflicting with special-character-insertion bindings.
Make the macOS Command-ArrowLeft/Right commands behave more like their native versions.
## 0.18.1 (2021-04-08)
### Bug fixes
Also bind Shift-Backspace and Shift-Delete in the default keymap (to do the same thing as the Shift-less binding).
### New features
Adds a `deleteToLineStart` command.
Adds bindings for Cmd-Delete and Cmd-Backspace on macOS.
## 0.18.0 (2021-03-03)
### Breaking changes
Update dependencies to 0.18.
## 0.17.5 (2021-02-25)
### Bug fixes
Use Alt-l for the default `selectLine` binding, because Mod-l already has an important meaning in the browser.
Make `deleteGroupBackward`/`deleteGroupForward` delete groups of whitespace when bigger than a single space.
Don't change lines that have the end of a range selection directly at their start in `indentLess`, `indentMore`, and `indentSelection`.
## 0.17.4 (2021-02-18)
### Bug fixes
Fix a bug where `deleteToLineEnd` would delete the rest of the document when at the end of a line.
## 0.17.3 (2021-02-16)
### Bug fixes
Fix an issue where `insertNewlineAndIndent` behaved strangely with the cursor between brackets that sat on different lines.
## 0.17.2 (2021-01-22)
### New features
The new `insertTab` command inserts a tab when nothing is selected, and defers to `indentMore` otherwise.
The package now exports a `defaultTabBinding` object that provides a recommended binding for tab (if you must bind tab).
## 0.17.1 (2021-01-06)
### New features
The package now also exports a CommonJS module.
## 0.17.0 (2020-12-29)
### Breaking changes
First numbered release.

21
frontend/node_modules/@codemirror/commands/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (C) 2018-2021 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

18
frontend/node_modules/@codemirror/commands/README.md generated vendored Normal file
View File

@ -0,0 +1,18 @@
# @codemirror/commands [![NPM version](https://img.shields.io/npm/v/@codemirror/commands.svg)](https://www.npmjs.org/package/@codemirror/commands)
[ [**WEBSITE**](https://codemirror.net/6/) | [**DOCS**](https://codemirror.net/6/docs/ref/#commands) | [**ISSUES**](https://github.com/codemirror/codemirror.next/issues) | [**FORUM**](https://discuss.codemirror.net/c/next/) | [**CHANGELOG**](https://github.com/codemirror/commands/blob/main/CHANGELOG.md) ]
This package implements a collection of editing commands for the
[CodeMirror](https://codemirror.net/6/) code editor.
The [project page](https://codemirror.net/6/) has more information, a
number of [examples](https://codemirror.net/6/examples/) and the
[documentation](https://codemirror.net/6/docs/).
This code is released under an
[MIT license](https://github.com/codemirror/commands/tree/main/LICENSE).
We aim to be an inclusive, welcoming community. To make that explicit,
we have a [code of
conduct](http://contributor-covenant.org/version/1/1/0/) that applies
to communication around the project.

1629
frontend/node_modules/@codemirror/commands/dist/index.cjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More