@leosdc/exploreio 0.0.0-stage → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +85 -2
- package/dist/cli.js +192 -0
- package/dist/cli.js.map +1 -0
- package/dist/editor/vimBuffer.js +351 -0
- package/dist/editor/vimBuffer.js.map +1 -0
- package/dist/editor/vimEngine.js +574 -0
- package/dist/editor/vimEngine.js.map +1 -0
- package/dist/editor/vimView.js +175 -0
- package/dist/editor/vimView.js.map +1 -0
- package/dist/fs/explorer.js +207 -0
- package/dist/fs/explorer.js.map +1 -0
- package/dist/renderers/code.js +311 -0
- package/dist/renderers/code.js.map +1 -0
- package/dist/renderers/html.js +182 -0
- package/dist/renderers/html.js.map +1 -0
- package/dist/renderers/index.js +180 -0
- package/dist/renderers/index.js.map +1 -0
- package/dist/renderers/json.js +127 -0
- package/dist/renderers/json.js.map +1 -0
- package/dist/renderers/markdown.js +252 -0
- package/dist/renderers/markdown.js.map +1 -0
- package/dist/renderers/mermaid.js +67 -0
- package/dist/renderers/mermaid.js.map +1 -0
- package/dist/renderers/mermaidParser.js +526 -0
- package/dist/renderers/mermaidParser.js.map +1 -0
- package/dist/test/exploreio.test.js +202 -0
- package/dist/test/exploreio.test.js.map +1 -0
- package/dist/test/mermaid.test.js +130 -0
- package/dist/test/mermaid.test.js.map +1 -0
- package/dist/test/vim-editor.test.js +154 -0
- package/dist/test/vim-editor.test.js.map +1 -0
- package/dist/themes/palette.js +134 -0
- package/dist/themes/palette.js.map +1 -0
- package/dist/tui/ansi.js +274 -0
- package/dist/tui/ansi.js.map +1 -0
- package/dist/tui/app.js +944 -0
- package/dist/tui/app.js.map +1 -0
- package/dist/tui/clipboard.js +110 -0
- package/dist/tui/clipboard.js.map +1 -0
- package/dist/tui/input.js +123 -0
- package/dist/tui/input.js.map +1 -0
- package/dist/tui/screen.js +80 -0
- package/dist/tui/screen.js.map +1 -0
- package/package.json +54 -4
- package/scripts/postinstall.mjs +28 -0
- package/scripts/setup.mjs +89 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Leonardo da Cruz (@Leosdc)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,86 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ◈ Exploreio — Explorador de Terminal estilo Yazi com Leitor Rico Nativo
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Um gerenciador de arquivos para CLI/terminal inspirado no **Yazi**, projetado para **não apenas navegar pastas**, mas **abrir e renderizar arquivos com qualidade visual diretamente no prompt** — sem depender de `bat`, `glow`, `jq` ou editores externos.
|
|
4
|
+
|
|
5
|
+
## ✨ Destaques
|
|
6
|
+
|
|
7
|
+
- **Layout 3 Painéis estilo Yazi:** `Diretório Pai` | `Diretório Atual` | `Preview Rico ao Vivo` (responsivo para terminais estreitos).
|
|
8
|
+
- **Leitor Fullscreen Nativo no Prompt (`Enter`):**
|
|
9
|
+
- **Markdown (`.md`, `.mdx`):** títulos estilizados, negrito/itálico/tachado, código inline, links, checklists (`☑`/`☐`), callouts GitHub (`[!NOTE]`, `[!TIP]`, `[!WARNING]`), tabelas Unicode alinhadas, **diagramas Mermaid renderizados inline** e blocos de código com syntax highlighting + toggle `Tab` (*Rendered* ↔ *Raw*).
|
|
10
|
+
- **Mermaid (`.mmd`, `.mermaid`):** interpretador e renderizador nativo Unicode/ANSI (zero dependências) para `flowchart`/`graph`, `sequenceDiagram`, `stateDiagram`, `classDiagram` e `erDiagram` com adaptação à largura do terminal, fallback seguro e toggle `Tab` (*Diagram* ↔ *Raw*).
|
|
11
|
+
- **JSON (`.json`):** **Tree View interativa** (recolher/expandir nós com `Enter`/`←`/`→`, `e` expande tudo, `c` recolhe tudo) + modo *Pretty Highlighted* + diagnóstico visual de JSON inválido.
|
|
12
|
+
- **HTML (`.html`, `.htm`):** **Modo Reader** limpo (extrai títulos, parágrafos, listas, links, citações, blocos de código e tabelas ignorando `<script>`/`<style>`) + toggle `Tab` para *Source* colorido.
|
|
13
|
+
- **Código-Fonte:** syntax highlighting multi-linguagem leve (TS/JS, Python, Rust, Go, C/C++/Java/C#, CSS, SQL, YAML, TOML, Shell/PowerShell) com números de linha.
|
|
14
|
+
- **Binários:** detecção de assinatura (PNG, JPEG, PDF, ZIP, WASM, ELF, EXE) + prévia segura em *Hex Dump*.
|
|
15
|
+
- **Modo Direto no Prompt (`--print` / `-p`):** renderize qualquer arquivo diretamente no stdout (`exploreio -p README.md`).
|
|
16
|
+
- **Editor Modal Estilo Vim Nativo (`e`):** edite qualquer arquivo de texto/código diretamente dentro do Exploreio com modos `NORMAL`, `INSERT`, `VISUAL`/`V-LINE`, `COMMAND` (`:w`, `:wq`, `:q!`, `:<linha>`) e `SEARCH` (`/`), undo/redo (`u`/`Ctrl+r`), syntax highlighting e preservação de EOL (`\r\n`/`\n`).
|
|
17
|
+
- **3 Temas Oficiais de Terminal (`t`):** `midnight`, `parchment` (claro) e `nord` com detecção Truecolor / ANSI 256.
|
|
18
|
+
- **Seguro por Padrão:** sanitização anti-ANSI-injection, limite de 2 MB contra OOM e confirmação obrigatória para exclusões.
|
|
19
|
+
|
|
20
|
+
## 🚀 Instalação & Comandos Globais (`exploreio` / `exp`)
|
|
21
|
+
|
|
22
|
+
### Via npm (Recomendado)
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
# Instalação global (ativa os comandos `exploreio` e `exp`)
|
|
26
|
+
npm install -g @leosdc/exploreio
|
|
27
|
+
|
|
28
|
+
# Ou execute sem instalar
|
|
29
|
+
npx @leosdc/exploreio
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Depois disso, basta abrir **qualquer pasta** no Windows Terminal, PowerShell, CMD, macOS ou Linux e rodar:
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
# Abrir TUI estilo Yazi no diretório atual
|
|
36
|
+
exploreio
|
|
37
|
+
|
|
38
|
+
# Abrir um arquivo direto no Leitor Fullscreen
|
|
39
|
+
exploreio README.md
|
|
40
|
+
|
|
41
|
+
# Imprimir renderizado direto no prompt (stdout)
|
|
42
|
+
exploreio -p README.md
|
|
43
|
+
exploreio -p package.json -m tree -t nord
|
|
44
|
+
exploreio -p index.html -m reader -t parchment
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### A partir do código-fonte (Desenvolvimento Local)
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npm install
|
|
51
|
+
npm run setup
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
O assistente `npm run setup` (também acionado automaticamente ao instalar localmente em terminal interativo) pergunta se você deseja ativar os comandos globais **`exploreio`** e **`exp`** via `npm link` e permite escolher seu tema padrão (`midnight`, `parchment` ou `nord`), salvo em `~/.exploreiorc.json`.
|
|
55
|
+
|
|
56
|
+
## ⌨️ Principais Atalhos
|
|
57
|
+
|
|
58
|
+
| Contexto | Tecla | Ação |
|
|
59
|
+
| :--- | :--- | :--- |
|
|
60
|
+
| **Navegador** | `↑`/`↓` ou `j`/`k` | Mover seleção (roda do mouse suportada) |
|
|
61
|
+
| **Navegador** | `Enter` ou `→`/`l` | Entrar na pasta ou **abrir arquivo no Leitor Fullscreen** |
|
|
62
|
+
| **Navegador** | `←`/`h`/`Backspace` | Voltar para o diretório pai |
|
|
63
|
+
| **Navegador** | `/` ou `f` | Filtro fuzzy instantâneo no diretório atual |
|
|
64
|
+
| **Navegador** | `.` | Alternar arquivos ocultos |
|
|
65
|
+
| **Navegador / Leitor** | `y` | Copiar caminho completo selecionado (arquivo ou pasta) |
|
|
66
|
+
| **Navegador** | `a` / `r` / `d` | Criar / Renomear / Excluir (com confirmação) |
|
|
67
|
+
| **Navegador / Leitor** | `e` *(ou `E` no JSON Tree)* | Abrir arquivo no **Editor Modal Estilo Vim Nativo** |
|
|
68
|
+
| **Editor Vim** | `i`/`I`/`a`/`A`/`o`/`O` · `Esc` | Entrar em `INSERT` · voltar para `NORMAL` |
|
|
69
|
+
| **Editor Vim** | `v`/`V` · `dd`/`yy`/`p` · `u`/`Ctrl+r` | Seleção Visual · deletar/copiar/colar · Undo/Redo |
|
|
70
|
+
| **Editor Vim** | `:w` · `:wq` · `:q!` · `:<linha>` | Salvar · salvar e sair · descartar · ir para linha |
|
|
71
|
+
| **Leitor** | `Tab` | Alternar visualização (*Rendered↔Raw*, *Tree↔Pretty*, *Reader↔Source*) |
|
|
72
|
+
| **Leitor (JSON Tree)** | `Enter`/`←`/`→` · `e`/`c` | Abrir/fechar nó selecionado · expandir/recolher tudo |
|
|
73
|
+
| **Leitor** | `/` · `n`/`N` | Buscar texto no arquivo e navegar ocorrências |
|
|
74
|
+
| **Global** | `t` · `?` · `Esc`/`q` | Trocar tema · Ajuda · Voltar/Sair |
|
|
75
|
+
|
|
76
|
+
## 💡 Dica: Usando em Split no Windows Terminal
|
|
77
|
+
|
|
78
|
+
O layout do **Exploreio** se adapta ao vivo à largura do painel (`≥ 96` colunas exibe **3 painéis**; `60–95` colunas exibe **2 painéis**). Para abrir e ajustar painéis lado a lado no **Windows Terminal**:
|
|
79
|
+
|
|
80
|
+
| Atalho | Ação |
|
|
81
|
+
| :--- | :--- |
|
|
82
|
+
| `Alt + Shift + +` | Abrir novo painel vertical lado a lado (split) |
|
|
83
|
+
| `Alt + Shift + -` | Abrir novo painel horizontal |
|
|
84
|
+
| `Alt + Shift + ←`/`→`/`↑`/`↓` | Redimensionar o painel ativo (alterna 2 ↔ 3 painéis ao vivo) |
|
|
85
|
+
| `Alt + ←`/`→`/`↑`/`↓` | Alternar foco entre painéis sem usar o mouse |
|
|
86
|
+
| `Ctrl + Shift + W` | Fechar o painel ativo |
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Exploreio CLI Entrypoint (SPEC-001)
|
|
4
|
+
* Uso:
|
|
5
|
+
* exploreio [diretorio|arquivo] Abre a TUI estilo Yazi (ou direto no Leitor se arquivo)
|
|
6
|
+
* exploreio --print <arquivo> Renderiza o arquivo lindamente direto no prompt/stdout
|
|
7
|
+
* exploreio --mode <rendered|raw|tree|pretty|reader|source>
|
|
8
|
+
* exploreio --theme <midnight|parchment|nord>
|
|
9
|
+
*/
|
|
10
|
+
import fs from 'node:fs/promises';
|
|
11
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { safeReadFilePreview } from './fs/explorer.js';
|
|
16
|
+
import { renderDocument } from './renderers/index.js';
|
|
17
|
+
import { fg, getTheme } from './themes/palette.js';
|
|
18
|
+
import { BOLD, DIM, RESET } from './tui/ansi.js';
|
|
19
|
+
import { ExploreioApp } from './tui/app.js';
|
|
20
|
+
export const VERSION = '0.1.0';
|
|
21
|
+
export function loadSavedDefaultTheme() {
|
|
22
|
+
try {
|
|
23
|
+
const rcPath = path.join(os.homedir(), '.exploreiorc.json');
|
|
24
|
+
if (!existsSync(rcPath))
|
|
25
|
+
return 'midnight';
|
|
26
|
+
const raw = JSON.parse(readFileSync(rcPath, 'utf8'));
|
|
27
|
+
return getTheme(raw.theme).name;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return 'midnight';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const VALID_MODES = new Set(['rendered', 'raw', 'tree', 'pretty', 'reader', 'source', 'code', 'hex']);
|
|
34
|
+
export function parseCliArgs(argv, defaultTheme = loadSavedDefaultTheme()) {
|
|
35
|
+
let target = process.cwd();
|
|
36
|
+
let hasTarget = false;
|
|
37
|
+
let printMode = false;
|
|
38
|
+
let theme = defaultTheme;
|
|
39
|
+
let viewMode;
|
|
40
|
+
let width;
|
|
41
|
+
let showHidden = false;
|
|
42
|
+
let showHelp = false;
|
|
43
|
+
let showVersion = false;
|
|
44
|
+
for (let i = 0; i < argv.length; i++) {
|
|
45
|
+
const arg = argv[i] ?? '';
|
|
46
|
+
if (arg === '-h' || arg === '--help') {
|
|
47
|
+
showHelp = true;
|
|
48
|
+
}
|
|
49
|
+
else if (arg === '-v' || arg === '--version') {
|
|
50
|
+
showVersion = true;
|
|
51
|
+
}
|
|
52
|
+
else if (arg === '-p' || arg === '--print' || arg === '--view') {
|
|
53
|
+
printMode = true;
|
|
54
|
+
}
|
|
55
|
+
else if (arg === '-a' || arg === '--all') {
|
|
56
|
+
showHidden = true;
|
|
57
|
+
}
|
|
58
|
+
else if ((arg === '-t' || arg === '--theme') && argv[i + 1]) {
|
|
59
|
+
theme = getTheme(argv[++i]).name;
|
|
60
|
+
}
|
|
61
|
+
else if ((arg === '-m' || arg === '--mode') && argv[i + 1]) {
|
|
62
|
+
const candidate = (argv[++i] ?? '').toLowerCase();
|
|
63
|
+
if (VALID_MODES.has(candidate))
|
|
64
|
+
viewMode = candidate;
|
|
65
|
+
}
|
|
66
|
+
else if ((arg === '-w' || arg === '--width') && argv[i + 1]) {
|
|
67
|
+
const parsed = Number.parseInt(argv[++i] ?? '', 10);
|
|
68
|
+
if (Number.isFinite(parsed) && parsed >= 30)
|
|
69
|
+
width = parsed;
|
|
70
|
+
}
|
|
71
|
+
else if (!arg.startsWith('-') && !hasTarget) {
|
|
72
|
+
target = arg;
|
|
73
|
+
hasTarget = true;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return { target, printMode, theme, viewMode, width, showHidden, showHelp, showVersion };
|
|
77
|
+
}
|
|
78
|
+
export function getHelpText(theme = getTheme(loadSavedDefaultTheme())) {
|
|
79
|
+
const h = (title) => `${fg(theme.accentAlt)}${BOLD}▌ ${title}${RESET}`;
|
|
80
|
+
const cmd = (text) => `${fg(theme.accent)}${BOLD}${text}${RESET}`;
|
|
81
|
+
const dim = (text) => `${fg(theme.muted)}${DIM}${text}${RESET}`;
|
|
82
|
+
const txt = (text) => `${fg(theme.text)}${text}${RESET}`;
|
|
83
|
+
return [
|
|
84
|
+
`${fg(theme.accent)}${BOLD}╔══════════════════════════════════════════════════════════════════════╗${RESET}`,
|
|
85
|
+
`${fg(theme.accent)}${BOLD}║ ◈ EXPLOREIO v${VERSION} — Explorador de Terminal & Leitor Rico Nativo ║${RESET}`,
|
|
86
|
+
`${fg(theme.accent)}${BOLD}╚══════════════════════════════════════════════════════════════════════╝${RESET}`,
|
|
87
|
+
txt('Navegação 3 colunas estilo Yazi + abertura e leitura rica direto no prompt.'),
|
|
88
|
+
'',
|
|
89
|
+
h('FORMAS DE ABRIR'),
|
|
90
|
+
` ${cmd('exploreio')} ${txt('Abre a TUI de 3 colunas (Pai | Atual | Preview Rico) aqui')}`,
|
|
91
|
+
` ${cmd('exploreio <pasta>')} ${txt('Abre a TUI diretamente em outro diretório')}`,
|
|
92
|
+
` ${cmd('exploreio <arquivo>')} ${txt('Abre o arquivo direto no Leitor Fullscreen interativo')}`,
|
|
93
|
+
` ${cmd('exploreio -p <arquivo>')} ${txt('Imprime formatado direto no prompt (stdout) e sai')}`,
|
|
94
|
+
` ${cmd('exp ...')} ${dim('Atalho curto idêntico a exploreio')}`,
|
|
95
|
+
'',
|
|
96
|
+
h('FORMATOS COM RENDERIZAÇÃO RICA (Tab alterna o modo no Leitor)'),
|
|
97
|
+
` ${cmd('Markdown (.md/.mdx)')} ${txt('Títulos, tabelas Unicode, checklists, callouts e código')} ${dim('[rendered | raw]')}`,
|
|
98
|
+
` ${cmd('JSON (.json/.jsonc)')} ${txt('Árvore interativa recolhível/expansível + diagnóstico')} ${dim('[tree | pretty]')}`,
|
|
99
|
+
` ${cmd('HTML (.html/.htm)')} ${txt('Modo Reader limpo (sem scripts/styles) + fonte colorido')} ${dim('[reader | source]')}`,
|
|
100
|
+
` ${cmd('Código-Fonte')} ${txt('Syntax highlighting (TS/JS/Py/Rust/Go/CSS/SQL/YAML/Sh)')} ${dim('[code]')}`,
|
|
101
|
+
` ${cmd('Binários')} ${txt('Assinatura detectada (PNG/PDF/ZIP/WASM/EXE) + Hex Dump')} ${dim('[hex]')}`,
|
|
102
|
+
'',
|
|
103
|
+
h('OPÇÕES DE LINHA DE COMANDO'),
|
|
104
|
+
` ${cmd('-p, --print, --view')} ${txt('Renderiza o arquivo direto no stdout (estilo glow/bat/jq)')}`,
|
|
105
|
+
` ${cmd('-m, --mode <modo>')} ${txt('rendered | raw | tree | pretty | reader | source')}`,
|
|
106
|
+
` ${cmd('-t, --theme <tema>')} ${txt('midnight (escuro) | parchment (claro) | nord (ártico)')}`,
|
|
107
|
+
` ${cmd('-w, --width <colunas>')} ${txt('Largura máxima de renderização no modo --print')}`,
|
|
108
|
+
` ${cmd('-a, --all')} ${txt('Exibe arquivos ocultos (iniciados por ".") ao abrir')}`,
|
|
109
|
+
` ${cmd('-v, --version')} ${txt('Exibe a versão instalada')}`,
|
|
110
|
+
` ${cmd('-h, --help')} ${txt('Exibe este guia de uso')}`,
|
|
111
|
+
'',
|
|
112
|
+
h('ATALHOS ESSENCIAIS NA TUI'),
|
|
113
|
+
` ${cmd('↑/↓ ou j/k')} Mover (roda do mouse) ${cmd('Enter / →')} Entrar na pasta ou ABRIR no Leitor`,
|
|
114
|
+
` ${cmd('← / Bksp')} Subir diretório ${cmd('Tab')} Alternar modo (Rendered↔Raw / Tree↔Pretty)`,
|
|
115
|
+
` ${cmd('/ ou f')} Filtrar / Buscar (n/N) ${cmd('t')} Trocar tema (Midnight · Parchment · Nord)`,
|
|
116
|
+
` ${cmd('e / c')} Expandir/Recolher JSON ${cmd('a / r / d')} Criar / Renomear / Excluir arquivo`,
|
|
117
|
+
` ${cmd('y')} Copiar caminho (path) ${cmd('.')} Alternar arquivos ocultos`,
|
|
118
|
+
` ${cmd('?')} Ajuda completa ${cmd('Esc / q')} Voltar ou Sair`,
|
|
119
|
+
'',
|
|
120
|
+
h('EXEMPLOS PRÁTICOS'),
|
|
121
|
+
` ${cmd('exploreio')} ${dim('# Navegador 3 colunas na pasta atual')}`,
|
|
122
|
+
` ${cmd('exploreio README.md')} ${dim('# Abre README.md no Leitor Fullscreen')}`,
|
|
123
|
+
` ${cmd('exp -p package.json -m tree -t nord')} ${dim('# Árvore JSON colorida direto no prompt')}`,
|
|
124
|
+
` ${cmd('exp -p index.html -m reader -t parchment')} ${dim('# HTML legível em tema claro no prompt')}`,
|
|
125
|
+
].join('\n');
|
|
126
|
+
}
|
|
127
|
+
export async function runCli(argv = process.argv.slice(2)) {
|
|
128
|
+
const args = parseCliArgs(argv);
|
|
129
|
+
if (args.showHelp) {
|
|
130
|
+
process.stdout.write(`${getHelpText(getTheme(args.theme))}\n`);
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
if (args.showVersion) {
|
|
134
|
+
process.stdout.write(`exploreio v${VERSION}\n`);
|
|
135
|
+
return 0;
|
|
136
|
+
}
|
|
137
|
+
const resolvedTarget = path.resolve(args.target);
|
|
138
|
+
let isFile = false;
|
|
139
|
+
try {
|
|
140
|
+
const stat = await fs.stat(resolvedTarget);
|
|
141
|
+
isFile = stat.isFile();
|
|
142
|
+
}
|
|
143
|
+
catch (err) {
|
|
144
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
145
|
+
process.stderr.write(`Exploreio: caminho não encontrado (${resolvedTarget}) — ${msg}\n`);
|
|
146
|
+
return 1;
|
|
147
|
+
}
|
|
148
|
+
if (args.printMode) {
|
|
149
|
+
if (!isFile) {
|
|
150
|
+
process.stderr.write('Exploreio: o modo --print exige um arquivo (ex.: exploreio -p README.md).\n');
|
|
151
|
+
return 1;
|
|
152
|
+
}
|
|
153
|
+
const preview = await safeReadFilePreview(resolvedTarget);
|
|
154
|
+
const theme = getTheme(args.theme);
|
|
155
|
+
const width = args.width ?? Math.max(50, Math.min(120, process.stdout.columns || 92));
|
|
156
|
+
const doc = renderDocument(preview, { width, theme, preferredMode: args.viewMode });
|
|
157
|
+
process.stdout.write(`${doc.lines.join('\n')}\n`);
|
|
158
|
+
return 0;
|
|
159
|
+
}
|
|
160
|
+
const app = new ExploreioApp({
|
|
161
|
+
startDir: isFile ? path.dirname(resolvedTarget) : resolvedTarget,
|
|
162
|
+
initialFile: isFile ? resolvedTarget : undefined,
|
|
163
|
+
themeName: args.theme,
|
|
164
|
+
showHidden: args.showHidden,
|
|
165
|
+
});
|
|
166
|
+
await app.start(isFile ? resolvedTarget : undefined);
|
|
167
|
+
return 0;
|
|
168
|
+
}
|
|
169
|
+
function isDirectExecution() {
|
|
170
|
+
const invoked = process.argv[1];
|
|
171
|
+
if (!invoked)
|
|
172
|
+
return false;
|
|
173
|
+
try {
|
|
174
|
+
const currentFile = realpathSync(fileURLToPath(import.meta.url));
|
|
175
|
+
const invokedFile = realpathSync(path.resolve(invoked));
|
|
176
|
+
return currentFile.toLowerCase() === invokedFile.toLowerCase();
|
|
177
|
+
}
|
|
178
|
+
catch {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
if (isDirectExecution()) {
|
|
183
|
+
runCli().then((code) => {
|
|
184
|
+
if (code !== 0)
|
|
185
|
+
process.exit(code);
|
|
186
|
+
}).catch((err) => {
|
|
187
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
188
|
+
process.stderr.write(`Exploreio erro fatal: ${msg}\n`);
|
|
189
|
+
process.exit(1);
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AACA;;;;;;;GAOG;AAEH,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACjE,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AACvD,OAAO,EAAE,cAAc,EAAiB,MAAM,sBAAsB,CAAC;AACrE,OAAO,EAAE,EAAE,EAAE,QAAQ,EAAqC,MAAM,qBAAqB,CAAC;AACtF,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5C,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAE/B,MAAM,UAAU,qBAAqB;IACnC,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,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WAAW,GAAG,YAAY,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QACjE,MAAM,WAAW,GAAG,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC;QACxD,OAAO,WAAW,CAAC,WAAW,EAAE,KAAK,WAAW,CAAC,WAAW,EAAE,CAAC;IACjE,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,IAAI,iBAAiB,EAAE,EAAE,CAAC;IACxB,MAAM,EAAE,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE;QACrB,IAAI,IAAI,KAAK,CAAC;YAAE,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,GAAY,EAAE,EAAE;QACxB,MAAM,GAAG,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QAC7D,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,yBAAyB,GAAG,IAAI,CAAC,CAAC;QACvD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC"}
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* VimBuffer — Estrutura de dados do buffer de texto do editor modal (SPEC-002)
|
|
3
|
+
* Gerencia linhas, cursor, seleção visual, histórico Undo/Redo, register, busca e EOL.
|
|
4
|
+
*/
|
|
5
|
+
const WORD_CHAR_RE = /[A-Za-z0-9_À-ÖØ-öø-ÿ]/;
|
|
6
|
+
function isWordChar(ch) {
|
|
7
|
+
return WORD_CHAR_RE.test(ch);
|
|
8
|
+
}
|
|
9
|
+
export function comparePos(a, b) {
|
|
10
|
+
if (a.line !== b.line)
|
|
11
|
+
return a.line - b.line;
|
|
12
|
+
return a.col - b.col;
|
|
13
|
+
}
|
|
14
|
+
export function normalizeRange(a, b) {
|
|
15
|
+
return comparePos(a, b) <= 0
|
|
16
|
+
? { start: { ...a }, end: { ...b } }
|
|
17
|
+
: { start: { ...b }, end: { ...a } };
|
|
18
|
+
}
|
|
19
|
+
export class VimBuffer {
|
|
20
|
+
lines;
|
|
21
|
+
cursor = { line: 0, col: 0 };
|
|
22
|
+
eol;
|
|
23
|
+
dirty = false;
|
|
24
|
+
register = { text: '', linewise: false };
|
|
25
|
+
undoStack = [];
|
|
26
|
+
redoStack = [];
|
|
27
|
+
maxHistory = 200;
|
|
28
|
+
constructor(rawText) {
|
|
29
|
+
this.eol = rawText.includes('\r\n') ? '\r\n' : '\n';
|
|
30
|
+
const normalized = rawText.replace(/\r\n/g, '\n');
|
|
31
|
+
this.lines = normalized.length === 0 ? [''] : normalized.split('\n');
|
|
32
|
+
}
|
|
33
|
+
toText() {
|
|
34
|
+
return this.lines.join(this.eol);
|
|
35
|
+
}
|
|
36
|
+
currentLine() {
|
|
37
|
+
return this.lines[this.cursor.line] ?? '';
|
|
38
|
+
}
|
|
39
|
+
clampCursor(allowLineEnd) {
|
|
40
|
+
this.cursor.line = Math.max(0, Math.min(this.cursor.line, this.lines.length - 1));
|
|
41
|
+
const lineLen = this.lines[this.cursor.line]?.length ?? 0;
|
|
42
|
+
const maxCol = allowLineEnd ? lineLen : Math.max(0, lineLen - 1);
|
|
43
|
+
this.cursor.col = Math.max(0, Math.min(this.cursor.col, maxCol));
|
|
44
|
+
}
|
|
45
|
+
pushUndo() {
|
|
46
|
+
this.undoStack.push({
|
|
47
|
+
lines: [...this.lines],
|
|
48
|
+
cursor: { ...this.cursor },
|
|
49
|
+
});
|
|
50
|
+
if (this.undoStack.length > this.maxHistory) {
|
|
51
|
+
this.undoStack.shift();
|
|
52
|
+
}
|
|
53
|
+
this.redoStack = [];
|
|
54
|
+
}
|
|
55
|
+
undo() {
|
|
56
|
+
const prev = this.undoStack.pop();
|
|
57
|
+
if (!prev)
|
|
58
|
+
return false;
|
|
59
|
+
this.redoStack.push({ lines: [...this.lines], cursor: { ...this.cursor } });
|
|
60
|
+
this.lines = prev.lines;
|
|
61
|
+
this.cursor = prev.cursor;
|
|
62
|
+
this.dirty = true;
|
|
63
|
+
this.clampCursor(false);
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
redo() {
|
|
67
|
+
const next = this.redoStack.pop();
|
|
68
|
+
if (!next)
|
|
69
|
+
return false;
|
|
70
|
+
this.undoStack.push({ lines: [...this.lines], cursor: { ...this.cursor } });
|
|
71
|
+
this.lines = next.lines;
|
|
72
|
+
this.cursor = next.cursor;
|
|
73
|
+
this.dirty = true;
|
|
74
|
+
this.clampCursor(false);
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
insertText(text) {
|
|
78
|
+
const line = this.currentLine();
|
|
79
|
+
const col = Math.min(this.cursor.col, line.length);
|
|
80
|
+
this.lines[this.cursor.line] = `${line.slice(0, col)}${text}${line.slice(col)}`;
|
|
81
|
+
this.cursor.col = col + text.length;
|
|
82
|
+
this.dirty = true;
|
|
83
|
+
}
|
|
84
|
+
insertNewline() {
|
|
85
|
+
const line = this.currentLine();
|
|
86
|
+
const col = Math.min(this.cursor.col, line.length);
|
|
87
|
+
const before = line.slice(0, col);
|
|
88
|
+
const after = line.slice(col);
|
|
89
|
+
const indent = before.match(/^(\s*)/)?.[1] ?? '';
|
|
90
|
+
this.lines[this.cursor.line] = before;
|
|
91
|
+
this.lines.splice(this.cursor.line + 1, 0, `${indent}${after}`);
|
|
92
|
+
this.cursor.line += 1;
|
|
93
|
+
this.cursor.col = indent.length;
|
|
94
|
+
this.dirty = true;
|
|
95
|
+
}
|
|
96
|
+
backspace() {
|
|
97
|
+
if (this.cursor.col > 0) {
|
|
98
|
+
const line = this.currentLine();
|
|
99
|
+
this.lines[this.cursor.line] = `${line.slice(0, this.cursor.col - 1)}${line.slice(this.cursor.col)}`;
|
|
100
|
+
this.cursor.col -= 1;
|
|
101
|
+
this.dirty = true;
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
if (this.cursor.line > 0) {
|
|
105
|
+
const prevLine = this.lines[this.cursor.line - 1] ?? '';
|
|
106
|
+
const currLine = this.currentLine();
|
|
107
|
+
const joinCol = prevLine.length;
|
|
108
|
+
this.lines[this.cursor.line - 1] = `${prevLine}${currLine}`;
|
|
109
|
+
this.lines.splice(this.cursor.line, 1);
|
|
110
|
+
this.cursor.line -= 1;
|
|
111
|
+
this.cursor.col = joinCol;
|
|
112
|
+
this.dirty = true;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
deleteCharAt(allowJoinNext) {
|
|
116
|
+
const line = this.currentLine();
|
|
117
|
+
if (this.cursor.col < line.length) {
|
|
118
|
+
const removed = line[this.cursor.col] ?? '';
|
|
119
|
+
this.lines[this.cursor.line] = `${line.slice(0, this.cursor.col)}${line.slice(this.cursor.col + 1)}`;
|
|
120
|
+
this.register = { text: removed, linewise: false };
|
|
121
|
+
this.dirty = true;
|
|
122
|
+
this.clampCursor(allowJoinNext);
|
|
123
|
+
return true;
|
|
124
|
+
}
|
|
125
|
+
if (allowJoinNext && this.cursor.line < this.lines.length - 1) {
|
|
126
|
+
const nextLine = this.lines[this.cursor.line + 1] ?? '';
|
|
127
|
+
this.lines[this.cursor.line] = `${line}${nextLine}`;
|
|
128
|
+
this.lines.splice(this.cursor.line + 1, 1);
|
|
129
|
+
this.dirty = true;
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
return false;
|
|
133
|
+
}
|
|
134
|
+
replaceCharAt(ch) {
|
|
135
|
+
const line = this.currentLine();
|
|
136
|
+
if (this.cursor.col >= line.length)
|
|
137
|
+
return false;
|
|
138
|
+
this.pushUndo();
|
|
139
|
+
this.lines[this.cursor.line] = `${line.slice(0, this.cursor.col)}${ch}${line.slice(this.cursor.col + 1)}`;
|
|
140
|
+
this.dirty = true;
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
deleteLines(startLine, count) {
|
|
144
|
+
const start = Math.max(0, Math.min(startLine, this.lines.length - 1));
|
|
145
|
+
const safeCount = Math.max(1, Math.min(count, this.lines.length - start));
|
|
146
|
+
this.pushUndo();
|
|
147
|
+
const removed = this.lines.splice(start, safeCount);
|
|
148
|
+
this.register = { text: removed.join('\n'), linewise: true };
|
|
149
|
+
if (this.lines.length === 0) {
|
|
150
|
+
this.lines = [''];
|
|
151
|
+
}
|
|
152
|
+
this.cursor.line = Math.min(start, this.lines.length - 1);
|
|
153
|
+
this.clampCursor(false);
|
|
154
|
+
this.dirty = true;
|
|
155
|
+
return removed.length;
|
|
156
|
+
}
|
|
157
|
+
yankLines(startLine, count) {
|
|
158
|
+
const start = Math.max(0, Math.min(startLine, this.lines.length - 1));
|
|
159
|
+
const safeCount = Math.max(1, Math.min(count, this.lines.length - start));
|
|
160
|
+
const slice = this.lines.slice(start, start + safeCount);
|
|
161
|
+
this.register = { text: slice.join('\n'), linewise: true };
|
|
162
|
+
return slice.length;
|
|
163
|
+
}
|
|
164
|
+
yankCharRange(a, b) {
|
|
165
|
+
const { start, end } = normalizeRange(a, b);
|
|
166
|
+
if (start.line === end.line) {
|
|
167
|
+
const line = this.lines[start.line] ?? '';
|
|
168
|
+
const text = line.slice(start.col, end.col + 1);
|
|
169
|
+
this.register = { text, linewise: false };
|
|
170
|
+
return text;
|
|
171
|
+
}
|
|
172
|
+
const parts = [];
|
|
173
|
+
parts.push((this.lines[start.line] ?? '').slice(start.col));
|
|
174
|
+
for (let l = start.line + 1; l < end.line; l++) {
|
|
175
|
+
parts.push(this.lines[l] ?? '');
|
|
176
|
+
}
|
|
177
|
+
parts.push((this.lines[end.line] ?? '').slice(0, end.col + 1));
|
|
178
|
+
const text = parts.join('\n');
|
|
179
|
+
this.register = { text, linewise: false };
|
|
180
|
+
return text;
|
|
181
|
+
}
|
|
182
|
+
deleteCharRange(a, b) {
|
|
183
|
+
const { start, end } = normalizeRange(a, b);
|
|
184
|
+
this.yankCharRange(start, end);
|
|
185
|
+
this.pushUndo();
|
|
186
|
+
const startLine = this.lines[start.line] ?? '';
|
|
187
|
+
const endLine = this.lines[end.line] ?? '';
|
|
188
|
+
const prefix = startLine.slice(0, start.col);
|
|
189
|
+
const suffix = endLine.slice(end.col + 1);
|
|
190
|
+
this.lines.splice(start.line, end.line - start.line + 1, `${prefix}${suffix}`);
|
|
191
|
+
this.cursor = { line: start.line, col: start.col };
|
|
192
|
+
this.clampCursor(false);
|
|
193
|
+
this.dirty = true;
|
|
194
|
+
}
|
|
195
|
+
paste(before) {
|
|
196
|
+
if (!this.register.text)
|
|
197
|
+
return false;
|
|
198
|
+
this.pushUndo();
|
|
199
|
+
if (this.register.linewise) {
|
|
200
|
+
const toInsert = this.register.text.split('\n');
|
|
201
|
+
const insertAt = before ? this.cursor.line : this.cursor.line + 1;
|
|
202
|
+
this.lines.splice(insertAt, 0, ...toInsert);
|
|
203
|
+
this.cursor.line = insertAt;
|
|
204
|
+
this.cursor.col = this.firstNonWhitespaceCol(insertAt);
|
|
205
|
+
this.dirty = true;
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
const line = this.currentLine();
|
|
209
|
+
const col = before ? this.cursor.col : Math.min(line.length, this.cursor.col + 1);
|
|
210
|
+
const parts = this.register.text.split('\n');
|
|
211
|
+
if (parts.length === 1) {
|
|
212
|
+
const txt = parts[0] ?? '';
|
|
213
|
+
this.lines[this.cursor.line] = `${line.slice(0, col)}${txt}${line.slice(col)}`;
|
|
214
|
+
this.cursor.col = Math.max(0, col + txt.length - 1);
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
const first = parts[0] ?? '';
|
|
218
|
+
const last = parts[parts.length - 1] ?? '';
|
|
219
|
+
const middle = parts.slice(1, -1);
|
|
220
|
+
const newLines = [`${line.slice(0, col)}${first}`, ...middle, `${last}${line.slice(col)}`];
|
|
221
|
+
this.lines.splice(this.cursor.line, 1, ...newLines);
|
|
222
|
+
this.cursor.line += parts.length - 1;
|
|
223
|
+
this.cursor.col = Math.max(0, last.length - 1);
|
|
224
|
+
}
|
|
225
|
+
this.clampCursor(false);
|
|
226
|
+
this.dirty = true;
|
|
227
|
+
return true;
|
|
228
|
+
}
|
|
229
|
+
openLine(above) {
|
|
230
|
+
this.pushUndo();
|
|
231
|
+
const indent = this.currentLine().match(/^(\s*)/)?.[1] ?? '';
|
|
232
|
+
const insertAt = above ? this.cursor.line : this.cursor.line + 1;
|
|
233
|
+
this.lines.splice(insertAt, 0, indent);
|
|
234
|
+
this.cursor = { line: insertAt, col: indent.length };
|
|
235
|
+
this.dirty = true;
|
|
236
|
+
}
|
|
237
|
+
joinNextLine() {
|
|
238
|
+
if (this.cursor.line >= this.lines.length - 1)
|
|
239
|
+
return false;
|
|
240
|
+
this.pushUndo();
|
|
241
|
+
const curr = this.currentLine();
|
|
242
|
+
const next = (this.lines[this.cursor.line + 1] ?? '').trimStart();
|
|
243
|
+
const joinCol = curr.length;
|
|
244
|
+
this.lines[this.cursor.line] = next ? `${curr}${curr.endsWith(' ') || !curr ? '' : ' '}${next}` : curr;
|
|
245
|
+
this.lines.splice(this.cursor.line + 1, 1);
|
|
246
|
+
this.cursor.col = Math.min(joinCol, Math.max(0, (this.lines[this.cursor.line]?.length ?? 1) - 1));
|
|
247
|
+
this.dirty = true;
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
firstNonWhitespaceCol(lineIdx = this.cursor.line) {
|
|
251
|
+
const line = this.lines[lineIdx] ?? '';
|
|
252
|
+
const idx = line.search(/\S/);
|
|
253
|
+
return idx >= 0 ? idx : 0;
|
|
254
|
+
}
|
|
255
|
+
moveWordForward() {
|
|
256
|
+
let { line, col } = this.cursor;
|
|
257
|
+
const curr = this.lines[line] ?? '';
|
|
258
|
+
if (col < curr.length) {
|
|
259
|
+
if (isWordChar(curr[col] ?? '')) {
|
|
260
|
+
while (col < curr.length && isWordChar(curr[col] ?? ''))
|
|
261
|
+
col++;
|
|
262
|
+
}
|
|
263
|
+
else if (!/\s/.test(curr[col] ?? '')) {
|
|
264
|
+
while (col < curr.length && !isWordChar(curr[col] ?? '') && !/\s/.test(curr[col] ?? ''))
|
|
265
|
+
col++;
|
|
266
|
+
}
|
|
267
|
+
while (col < curr.length && /\s/.test(curr[col] ?? ''))
|
|
268
|
+
col++;
|
|
269
|
+
if (col < curr.length) {
|
|
270
|
+
this.cursor = { line, col };
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
if (line < this.lines.length - 1) {
|
|
275
|
+
line += 1;
|
|
276
|
+
this.cursor = { line, col: this.firstNonWhitespaceCol(line) };
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
moveWordBackward() {
|
|
280
|
+
let { line, col } = this.cursor;
|
|
281
|
+
if (col === 0) {
|
|
282
|
+
if (line === 0)
|
|
283
|
+
return;
|
|
284
|
+
line -= 1;
|
|
285
|
+
col = Math.max(0, (this.lines[line]?.length ?? 1) - 1);
|
|
286
|
+
this.cursor = { line, col };
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
const curr = this.lines[line] ?? '';
|
|
290
|
+
col = Math.min(col - 1, curr.length - 1);
|
|
291
|
+
while (col > 0 && /\s/.test(curr[col] ?? ''))
|
|
292
|
+
col--;
|
|
293
|
+
if (isWordChar(curr[col] ?? '')) {
|
|
294
|
+
while (col > 0 && isWordChar(curr[col - 1] ?? ''))
|
|
295
|
+
col--;
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
while (col > 0 && !isWordChar(curr[col - 1] ?? '') && !/\s/.test(curr[col - 1] ?? ''))
|
|
299
|
+
col--;
|
|
300
|
+
}
|
|
301
|
+
this.cursor = { line, col };
|
|
302
|
+
}
|
|
303
|
+
moveWordEnd() {
|
|
304
|
+
let { line, col } = this.cursor;
|
|
305
|
+
let curr = this.lines[line] ?? '';
|
|
306
|
+
if (col + 1 >= curr.length) {
|
|
307
|
+
if (line >= this.lines.length - 1)
|
|
308
|
+
return;
|
|
309
|
+
line += 1;
|
|
310
|
+
curr = this.lines[line] ?? '';
|
|
311
|
+
col = 0;
|
|
312
|
+
}
|
|
313
|
+
else {
|
|
314
|
+
col += 1;
|
|
315
|
+
}
|
|
316
|
+
while (col < curr.length && /\s/.test(curr[col] ?? ''))
|
|
317
|
+
col++;
|
|
318
|
+
if (col < curr.length) {
|
|
319
|
+
if (isWordChar(curr[col] ?? '')) {
|
|
320
|
+
while (col + 1 < curr.length && isWordChar(curr[col + 1] ?? ''))
|
|
321
|
+
col++;
|
|
322
|
+
}
|
|
323
|
+
else {
|
|
324
|
+
while (col + 1 < curr.length && !isWordChar(curr[col + 1] ?? '') && !/\s/.test(curr[col + 1] ?? '')) {
|
|
325
|
+
col++;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
this.cursor = { line, col: Math.min(col, Math.max(0, curr.length - 1)) };
|
|
330
|
+
}
|
|
331
|
+
findAllMatches(query) {
|
|
332
|
+
const clean = query.trim();
|
|
333
|
+
if (!clean)
|
|
334
|
+
return [];
|
|
335
|
+
const lowerQ = clean.toLowerCase();
|
|
336
|
+
const matches = [];
|
|
337
|
+
for (let l = 0; l < this.lines.length; l++) {
|
|
338
|
+
const lowerLine = (this.lines[l] ?? '').toLowerCase();
|
|
339
|
+
let pos = 0;
|
|
340
|
+
while (pos < lowerLine.length) {
|
|
341
|
+
const idx = lowerLine.indexOf(lowerQ, pos);
|
|
342
|
+
if (idx === -1)
|
|
343
|
+
break;
|
|
344
|
+
matches.push({ line: l, col: idx, length: clean.length });
|
|
345
|
+
pos = idx + clean.length;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
return matches;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
//# sourceMappingURL=vimBuffer.js.map
|