@noldova/terminal 0.0.10 → 0.0.12

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/src/resources.js CHANGED
@@ -11,6 +11,8 @@ import { MarkKind } from "./enums/mark-kind.js";
11
11
  import { SystemRequirement } from "./enums/system-requirement.js";
12
12
  import { PowerShellCmdlet } from "./models/powershell-cmdlet.js";
13
13
  import { PowerShellParameter } from "./models/powershell-parameter.js";
14
+ import { ToolCommand } from "./models/tool-command.js";
15
+ import { ToolWord } from "./models/tool-word.js";
14
16
  export class Resources {
15
17
  static highWatermark = 1_048_576;
16
18
  static lowWatermark = 262_144;
@@ -24,6 +26,7 @@ export class Resources {
24
26
  static promptDrawWaitMilliseconds = 10_000;
25
27
  static foregroundPollMilliseconds = 50;
26
28
  static cursorAnswerMilliseconds = 500;
29
+ static cursorRequestFrameMilliseconds = 100;
27
30
  static maximumKeptRuns = 100;
28
31
  static scrollback = 1_000;
29
32
  static terminalHistoryFlags = "w+";
@@ -76,6 +79,8 @@ export class Resources {
76
79
  static windowsPathListSeparator = ";";
77
80
  static optionsProperty = "Options=";
78
81
  static optionsBound = "1";
82
+ static folderKeysProperty = "FolderKeys=";
83
+ static folderKeysBound = "1";
79
84
  static autocdName = "*/";
80
85
  static suffixAliasNameStart = "*.";
81
86
  static suffixStart = ".";
@@ -87,6 +92,7 @@ export class Resources {
87
92
  static integrationWaitMilliseconds = 10_000;
88
93
  static paneFitWaitMilliseconds = 10_000;
89
94
  static shellStartMilliseconds = 60_000;
95
+ static folderChangeWaitMilliseconds = 30_000;
90
96
  static maximumExitedSessions = 32;
91
97
  static restartReset = "\u001b[?1047l\u001b[!p\u001b[?1000l\u001b[?1002l\u001b[?1003l\u001b[?1006l\u001b[?2004l\r";
92
98
  static lineFeed = "\n";
@@ -174,6 +180,10 @@ export class Resources {
174
180
  static posixEscape = "\\";
175
181
  static powerShellEscape = "`";
176
182
  static singleQuote = "'";
183
+ static posixChangeFolder = "cd -- ";
184
+ static posixQuotedSingleQuote = "'\\''";
185
+ static powerShellChangeFolder = "Set-Location -LiteralPath ";
186
+ static powerShellSingleQuotes = /['\u2018\u2019\u201a\u201b]/gu;
177
187
  static doubleQuote = "\"";
178
188
  static wordBreaks = " \t";
179
189
  static commandBreaks = "|;&";
@@ -296,14 +306,69 @@ export class Resources {
296
306
  static npmCommand = "npm";
297
307
  static npmRunCommands = ["run", "run-script"];
298
308
  static packageFile = "package.json";
309
+ static toolCommands = [
310
+ new ToolCommand("npm", [
311
+ new ToolWord("install", "Install a package and the packages it depends on"), new ToolWord("ci", "Install exactly what package-lock.json locks"),
312
+ new ToolWord("run", "Run a script from package.json"), new ToolWord("test", "Run the test script"), new ToolWord("start", "Run the start script"),
313
+ new ToolWord("stop", "Run the stop script"), new ToolWord("restart", "Run the restart script"), new ToolWord("exec", "Run a command from a package"),
314
+ new ToolWord("uninstall", "Remove a package"), new ToolWord("update", "Update packages to the newest versions their ranges allow"),
315
+ new ToolWord("outdated", "List packages with newer versions"), new ToolWord("ls", "List installed packages"),
316
+ new ToolWord("audit", "Check packages for known vulnerabilities"), new ToolWord("init", "Create a package.json"),
317
+ new ToolWord("pack", "Pack the package into an archive"), new ToolWord("publish", "Publish the package to the registry"),
318
+ new ToolWord("version", "Change the package's version"), new ToolWord("view", "Show a package's registry details"),
319
+ new ToolWord("link", "Link a package folder in place of an installed one"), new ToolWord("prune", "Remove packages nothing depends on"),
320
+ new ToolWord("dedupe", "Reduce duplicate packages"), new ToolWord("rebuild", "Rebuild installed packages"), new ToolWord("cache", "Manage the package cache"),
321
+ new ToolWord("config", "Manage npm's settings"), new ToolWord("explain", "Explain why a package is installed"),
322
+ new ToolWord("search", "Search the registry"), new ToolWord("login", "Sign in to the registry"), new ToolWord("logout", "Sign out of the registry"),
323
+ new ToolWord("whoami", "Show the signed-in user"), new ToolWord("doctor", "Check npm's environment"), new ToolWord("help", "Show npm's help")
324
+ ]),
325
+ new ToolCommand("git", [
326
+ new ToolWord("status", "Show the working tree's state"), new ToolWord("add", "Stage changes for the next commit"),
327
+ new ToolWord("commit", "Record the staged changes"), new ToolWord("push", "Send commits to a remote"), new ToolWord("pull", "Fetch and merge from a remote"),
328
+ new ToolWord("fetch", "Download from a remote without merging"), new ToolWord("checkout", "Switch branches or restore files"),
329
+ new ToolWord("switch", "Switch branches"), new ToolWord("branch", "List, create or delete branches"), new ToolWord("merge", "Join another branch into this one"),
330
+ new ToolWord("rebase", "Reapply commits on top of another base"), new ToolWord("log", "Show the commit history"), new ToolWord("diff", "Show changes"),
331
+ new ToolWord("show", "Show a commit or another object"), new ToolWord("restore", "Restore files in the working tree"),
332
+ new ToolWord("reset", "Move the branch to another commit"), new ToolWord("revert", "Record a commit that undoes another"),
333
+ new ToolWord("stash", "Set changes aside"), new ToolWord("tag", "List, create or delete tags"), new ToolWord("remote", "Manage remotes"),
334
+ new ToolWord("clone", "Copy a repository"), new ToolWord("init", "Create a repository"), new ToolWord("cherry-pick", "Apply another commit's changes"),
335
+ new ToolWord("blame", "Show who changed each line"), new ToolWord("clean", "Remove untracked files"), new ToolWord("rm", "Remove files from the index"),
336
+ new ToolWord("mv", "Move or rename a file"), new ToolWord("grep", "Search tracked files"), new ToolWord("bisect", "Find the commit that brought a bug"),
337
+ new ToolWord("reflog", "Show where references have been"), new ToolWord("worktree", "Manage more working trees"), new ToolWord("config", "Manage git's settings")
338
+ ]),
339
+ new ToolCommand("dotnet", [
340
+ new ToolWord("build", "Build a project"), new ToolWord("run", "Build and run a project"), new ToolWord("test", "Run a project's tests"),
341
+ new ToolWord("new", "Create a project from a template"), new ToolWord("restore", "Restore a project's dependencies"), new ToolWord("publish", "Publish a project for deployment"),
342
+ new ToolWord("pack", "Pack a project into a NuGet package"), new ToolWord("clean", "Remove a project's build output"), new ToolWord("add", "Add a package or reference"),
343
+ new ToolWord("remove", "Remove a package or reference"), new ToolWord("list", "List a project's packages or references"), new ToolWord("sln", "Manage a solution's projects"),
344
+ new ToolWord("format", "Format code to its style settings"), new ToolWord("watch", "Rebuild and rerun on file changes"), new ToolWord("tool", "Manage .NET tools"),
345
+ new ToolWord("workload", "Manage optional workloads"), new ToolWord("nuget", "Run NuGet commands")
346
+ ]),
347
+ new ToolCommand("docker", [
348
+ new ToolWord("run", "Create and start a container"), new ToolWord("ps", "List containers"), new ToolWord("build", "Build an image"),
349
+ new ToolWord("images", "List images"), new ToolWord("pull", "Download an image"), new ToolWord("push", "Upload an image"),
350
+ new ToolWord("exec", "Run a command in a running container"), new ToolWord("logs", "Show a container's logs"), new ToolWord("start", "Start a container"),
351
+ new ToolWord("stop", "Stop a container"), new ToolWord("restart", "Restart a container"), new ToolWord("rm", "Remove a container"),
352
+ new ToolWord("rmi", "Remove an image"), new ToolWord("compose", "Run multi-container applications"), new ToolWord("inspect", "Show an object's details"),
353
+ new ToolWord("cp", "Copy files to or from a container"), new ToolWord("kill", "Kill a running container"), new ToolWord("tag", "Name an image"),
354
+ new ToolWord("network", "Manage networks"), new ToolWord("volume", "Manage volumes"), new ToolWord("system", "Manage Docker itself"),
355
+ new ToolWord("login", "Sign in to a registry"), new ToolWord("logout", "Sign out of a registry")
356
+ ])
357
+ ];
358
+ static nodeScriptExtensions = [".js", ".mjs", ".cjs", ".ts", ".mts", ".cts"];
359
+ static nodeCommand = "node";
360
+ static npxCommand = "npx";
361
+ static packageBinFolder = ["node_modules", ".bin"];
362
+ static packageBinExtension = /\.(?:cmd|ps1)$/iu;
299
363
  static completionCommandMilliseconds = 2_000;
300
364
  static completionReadMilliseconds = 1_000;
301
365
  static runFolderReadMilliseconds = 1_000;
302
366
  static completionConcurrentReads = 2;
303
- static optionsKeys = new Map([
304
- [TerminalShellKind.PowerShell, "\u001b[24~o"],
305
- [TerminalShellKind.Zsh, "\u001b[24;7~"]
306
- ]);
367
+ static powerShellOptionsKeys = "\u001b[24~o";
368
+ static zshOptionsKeys = "\u001b[24;7~";
369
+ static powerShellFolderKeys = "\u001b[24~d";
370
+ static zshFolderKeys = "\u001b[23;7~";
371
+ static folderEncoding = "hex";
307
372
  static optionsMilliseconds = 500;
308
373
  static firstOptionsMilliseconds = 3_500;
309
374
  static powerShellLookupMilliseconds = 10_000;
@@ -313,6 +378,35 @@ export class Resources {
313
378
  static powerShellLookupModulePathReset = "the session's PSModulePath was reset";
314
379
  static powerShellLookupNamesTooLong = "the shell's last list of its names was too long to send";
315
380
  static powerShellLookupNamesUnreported = "the shell has sent no list of its names yet";
381
+ static describeMilliseconds = 10_000;
382
+ static maximumDescribedLength = 200;
383
+ static describedNamePattern = /^[\p{L}\p{N}._+@%:,][\p{L}\p{N}._+@%:,-]*$/u;
384
+ static describedSeparator = "\t";
385
+ static whatisScript = "whatis \"$@\" 2>/dev/null; exit 0";
386
+ static whatisScriptName = "describe";
387
+ static whatisDash = /\s+-\s+/u;
388
+ static whatisEntry = /^\s*([^\s(]+)\s*\(([^)]*)\)/u;
389
+ static whatisEntrySeparator = ",";
390
+ static whatisSections = ["1", "8", "6"];
391
+ static whatisRuns = 4;
392
+ static whatisNamesPerRun = 6;
393
+ static describeRetryMilliseconds = 300_000;
394
+ static zshNoStartupArgument = "-f";
395
+ static bashStartupVariable = "BASH_ENV";
396
+ static formatDescribeFailed(count, message) {
397
+ return `The lookup of ${count} ${count === 1 ? "command's description" : "commands' descriptions"} gave up, so they show none: ${message}`;
398
+ }
399
+ static formatPowerShellDescribeScript(names) {
400
+ return `$ErrorActionPreference = 'SilentlyContinue'
401
+ $names = @(${names.map(t => `'${t}'`).join(", ")})
402
+ for ($index = 0; $index -lt $names.Count; $index++) {
403
+ $command = Get-Command -Name $names[$index] | Select-Object -First 1
404
+ if ($command.CommandType -eq 'Alias') { $command = $command.ResolvedCommand }
405
+ if (-not $command) { continue }
406
+ $text = if ($command.CommandType -eq 'Application') { $command.FileVersionInfo.FileDescription } else { (Get-Help -Name $command.Name).Synopsis }
407
+ if ($text -and -not ([string]$text).Trim().StartsWith($command.Name, [StringComparison]::OrdinalIgnoreCase)) { [string]$index + [char]9 + ([string]$text -replace '[\r\n]+', ' ') }
408
+ }`;
409
+ }
316
410
  static powerShellLookupNamePattern = /^[\p{L}\p{N}._+@%:,-]+$/u;
317
411
  static powerShellImplicitVerb = "Get-";
318
412
  static powerShellBuiltins = [
@@ -322,7 +416,59 @@ export class Resources {
322
416
  "Select-String", "Set-Content", "Set-Location", "Sort-Object", "Split-Path", "Start-Process", "Stop-Process", "Test-Path", "Where-Object",
323
417
  "Write-Host", "Write-Output", "cat", "cd", "cls", "copy", "del", "dir", "echo", "exit", "ls", "md", "move", "pwd", "ren", "rm", "type"
324
418
  ];
325
- static completedShellKinds = [TerminalShellKind.Bash, TerminalShellKind.Zsh, TerminalShellKind.PowerShell];
419
+ static powerShellDescriptions = new Map([
420
+ ["clear-host", "Clear the screen"],
421
+ ["copy-item", "Copy files, folders or other items"],
422
+ ["foreach-object", "Run a script block for each object in the pipeline"],
423
+ ["get-childitem", "List the files and folders in a location"],
424
+ ["get-command", "List the commands PowerShell can run"],
425
+ ["get-content", "Read the content of a file"],
426
+ ["get-date", "Get the current date and time"],
427
+ ["get-help", "Show help about a command or a topic"],
428
+ ["get-item", "Get the file, folder or other item at a path"],
429
+ ["get-location", "Show the current folder"],
430
+ ["get-module", "List the modules loaded or available"],
431
+ ["get-process", "List the running processes"],
432
+ ["import-module", "Load a module into the session"],
433
+ ["invoke-restmethod", "Send a web request and read the response as data"],
434
+ ["invoke-webrequest", "Send a web request and get the response"],
435
+ ["join-path", "Join a path and a child path into one path"],
436
+ ["measure-object", "Count objects or measure their properties"],
437
+ ["move-item", "Move or rename files, folders or other items"],
438
+ ["new-item", "Create a file, folder or other item"],
439
+ ["out-file", "Write the output to a file"],
440
+ ["pop-location", "Go back to the folder last saved by Push-Location"],
441
+ ["push-location", "Save the current folder and go to another"],
442
+ ["remove-item", "Delete files, folders or other items"],
443
+ ["rename-item", "Rename an item"],
444
+ ["resolve-path", "Resolve wildcards in a path to full paths"],
445
+ ["select-object", "Pick properties or objects from the pipeline"],
446
+ ["select-string", "Find text in strings or files"],
447
+ ["set-content", "Write content to a file, replacing what it held"],
448
+ ["set-location", "Change the current folder"],
449
+ ["sort-object", "Sort objects by their property values"],
450
+ ["split-path", "Get part of a path, such as its parent folder or file name"],
451
+ ["start-process", "Start a program or open a file"],
452
+ ["stop-process", "Stop running processes"],
453
+ ["test-path", "Check whether a path exists"],
454
+ ["where-object", "Keep the objects that match a condition"],
455
+ ["write-host", "Write text to the screen"],
456
+ ["write-output", "Send objects down the pipeline"],
457
+ ["cat", "Read the content of a file"],
458
+ ["cd", "Change the current folder"],
459
+ ["cls", "Clear the screen"],
460
+ ["copy", "Copy files, folders or other items"],
461
+ ["del", "Delete files, folders or other items"],
462
+ ["dir", "List the files and folders in a location"],
463
+ ["echo", "Send objects down the pipeline"],
464
+ ["ls", "List the files and folders in a location"],
465
+ ["move", "Move or rename files, folders or other items"],
466
+ ["pwd", "Show the current folder"],
467
+ ["ren", "Rename an item"],
468
+ ["rm", "Delete files, folders or other items"],
469
+ ["type", "Read the content of a file"],
470
+ ["md", "Create a folder"]
471
+ ]);
326
472
  static programFilesVariable = "ProgramFiles";
327
473
  static programFilesX86Variable = "ProgramFiles(x86)";
328
474
  static localAppDataVariable = "LOCALAPPDATA";
@@ -348,6 +494,7 @@ export class Resources {
348
494
  static windowsPowerShellName = "Windows PowerShell";
349
495
  static windowsPowerShellPath = ["System32", "WindowsPowerShell", "v1.0", "powershell.exe"];
350
496
  static cmdId = "cmd";
497
+ static resizeQuietShellIds = [Resources.windowsPowerShellId, Resources.pwshId, Resources.cmdId];
351
498
  static cmdName = "Command Prompt";
352
499
  static cmdPath = ["System32", "cmd.exe"];
353
500
  static gitBashId = "git-bash";
@@ -581,6 +728,8 @@ exit 0
581
728
  static storedLinesFailed = "The terminal's stored lines could not be written.";
582
729
  static storedLinesDamaged = "The terminal's stored lines are damaged.";
583
730
  static carriageReturn = "\r";
731
+ static printedTextBreaks = /(\r|\n)/u;
732
+ static lineEndMarks = ["%", "#"];
584
733
  static decimalRadix = 10;
585
734
  static hexadecimalRadix = 16;
586
735
  static utf8Encoding = "utf8";
@@ -723,6 +872,9 @@ exit 0
723
872
  static formatTerminalHistoryFolder(pid) {
724
873
  return `${Resources.terminalHistoryFolderPrefix}${pid}-`;
725
874
  }
875
+ static formatEnvironmentFolder(pid) {
876
+ return `${Resources.environmentFolderPrefix}${pid}-`;
877
+ }
726
878
  static formatTerminalHistoryNotPrivate(message) {
727
879
  return `A terminal opens without stored lines, whose folder could not be made private: ${message}`;
728
880
  }
@@ -1364,6 +1516,10 @@ Remove-Variable -Name __NoldovaProfile -Scope Global -ErrorAction SilentlyContin
1364
1516
  $Global:__NoldovaOptionsSent = $Global:__NoldovaOptions
1365
1517
  $marks += __NoldovaMark 'P' "${Resources.optionsProperty}$(if ($Global:__NoldovaOptions) { '${Resources.optionsBound}' } else { '0' })"
1366
1518
  }
1519
+ if ($Global:__NoldovaFolderKeys -ne $Global:__NoldovaFolderKeysSent) {
1520
+ $Global:__NoldovaFolderKeysSent = $Global:__NoldovaFolderKeys
1521
+ $marks += __NoldovaMark 'P' "${Resources.folderKeysProperty}$(if ($Global:__NoldovaFolderKeys) { '${Resources.folderKeysBound}' } else { '0' })"
1522
+ }
1367
1523
  $Global:__NoldovaHistoryId = $historyId
1368
1524
  $Global:__NoldovaHasPrompted = $true
1369
1525
  $text = (& $Global:__NoldovaPrompt) -join ''
@@ -1416,15 +1572,59 @@ Remove-Variable -Name __NoldovaProfile -Scope Global -ErrorAction SilentlyContin
1416
1572
  [Console]::Write("$mark$([char] 0x07)")
1417
1573
  }
1418
1574
 
1575
+ # The hidden folder binding reads the folder as UTF-8 in hex digits up to Enter, which nothing shows, moves there and draws the prompt
1576
+ # again, so no command, history entry or echoed line comes of it. Any other key ends it where it is. The keys come from PSReadLine's own
1577
+ # queue, which its reading thread fills, as Console's would race it for them.
1578
+ function Global:__NoldovaChangeFolder {
1579
+ $hex = ''
1580
+ while ($true) {
1581
+ $char = $Global:__NoldovaReadKey.Invoke($null, $null).KeyChar
1582
+ if ([int] $char -in 10, 13) {
1583
+ break
1584
+ }
1585
+ if ("$char" -cnotmatch '^[0-9a-f]$') {
1586
+ return
1587
+ }
1588
+ $hex += $char
1589
+ }
1590
+ try {
1591
+ $bytes = [byte[]] -split ($hex -replace '..', '0x$& ')
1592
+ Set-Location -LiteralPath ([Text.Encoding]::UTF8.GetString($bytes)) -ErrorAction Stop
1593
+ }
1594
+ catch {
1595
+ }
1596
+ # PSReadLine draws the prompt again through Console, in the console's code page, which would turn the folder's name in the prompt and its
1597
+ # mark into a best fit; the shell draws it through the host, in Unicode.
1598
+ $encoding = [Console]::OutputEncoding
1599
+ try {
1600
+ [Console]::OutputEncoding = New-Object Text.UTF8Encoding $false
1601
+ [Microsoft.PowerShell.PSConsoleReadLine]::InvokePrompt()
1602
+ }
1603
+ finally {
1604
+ [Console]::OutputEncoding = $encoding
1605
+ }
1606
+ }
1607
+
1419
1608
  # Only where PSReadLine reads the line, and not where a profile bound F12 or a chord starting with it, which the chord would take over; each
1420
1609
  # prompt reports whether it is in place.
1421
1610
  $Global:__NoldovaOptions = $false
1422
1611
  $Global:__NoldovaOptionsSent = $false
1612
+ $Global:__NoldovaFolderKeys = $false
1613
+ $Global:__NoldovaFolderKeysSent = $false
1614
+ $Global:__NoldovaReadKey = $null
1423
1615
  if (Get-Command -Name Set-PSReadLineKeyHandler -ErrorAction SilentlyContinue) {
1424
1616
  try {
1425
1617
  if (-not (Get-PSReadLineKeyHandler -Bound | Where-Object { $_.Key -eq 'F12' -or $_.Key -like 'F12,*' })) {
1426
1618
  Set-PSReadLineKeyHandler -Chord 'F12,o' -ScriptBlock { __NoldovaOptions } -ErrorAction Stop
1427
1619
  $Global:__NoldovaOptions = $true
1620
+ # The folder binding reads keys through PSReadLine's own reader, which ConstrainedLanguage refuses and a version without it lacks.
1621
+ if ($ExecutionContext.SessionState.LanguageMode -eq 'FullLanguage') {
1622
+ $Global:__NoldovaReadKey = [Microsoft.PowerShell.PSConsoleReadLine].GetMethod('ReadKey', [Reflection.BindingFlags] 'NonPublic, Static', $null, [Type[]] @(), $null)
1623
+ }
1624
+ if ($null -ne $Global:__NoldovaReadKey) {
1625
+ Set-PSReadLineKeyHandler -Chord 'F12,d' -ScriptBlock { __NoldovaChangeFolder } -ErrorAction Stop
1626
+ $Global:__NoldovaFolderKeys = $true
1627
+ }
1428
1628
  }
1429
1629
  }
1430
1630
  catch {
@@ -1581,6 +1781,14 @@ if [[ -n "\${__noldova_nonce_read-}" && -z "\${__noldova_nonce-}" ]]; then
1581
1781
  __noldova_options_sent="$options"
1582
1782
  __noldova_mark P "${Resources.optionsProperty}$options"
1583
1783
  fi
1784
+ builtin local folder_keys=0
1785
+ if [[ -o zle ]] && (( \${+widgets[__noldova_change_folder]} )); then
1786
+ folder_keys=${Resources.folderKeysBound}
1787
+ fi
1788
+ if [[ "$folder_keys" != "\${__noldova_folder_keys_sent-0}" ]]; then
1789
+ __noldova_folder_keys_sent="$folder_keys"
1790
+ __noldova_mark P "${Resources.folderKeysProperty}$folder_keys"
1791
+ fi
1584
1792
  __noldova_escape "$PWD" escaped
1585
1793
  __noldova_mark P "Cwd=$escaped"
1586
1794
  if (( __noldova_in_command )); then
@@ -1669,6 +1877,28 @@ if [[ -n "\${__noldova_nonce_read-}" && -z "\${__noldova_nonce-}" ]]; then
1669
1877
  builtin printf '%s\\007' "$mark"
1670
1878
  }
1671
1879
 
1880
+ # The hidden folder binding reads the folder as UTF-8 in hex digits up to Enter, which nothing shows, moves there, runs the prompt hooks and
1881
+ # draws the prompt again, so no command, history entry or echoed line comes of it. Any other key ends it where it is.
1882
+ __noldova_change_folder() {
1883
+ builtin setopt local_options no_xtrace extended_glob
1884
+ builtin local hex= key folder hook
1885
+ while :; do
1886
+ builtin read -k 1 key || builtin return 0
1887
+ [[ "$key" == $'\\r' || "$key" == $'\\n' ]] && builtin break
1888
+ [[ "$key" == [0-9a-f] ]] || builtin return 0
1889
+ hex+="$key"
1890
+ done
1891
+ builtin printf -v folder '%b' "\${hex//(#m)??/\\\\x$MATCH}"
1892
+ builtin cd -- "$folder" 2>/dev/null
1893
+ if (( \${+functions[precmd]} )); then
1894
+ precmd
1895
+ fi
1896
+ for hook in $precmd_functions; do
1897
+ "$hook"
1898
+ done
1899
+ builtin zle reset-prompt
1900
+ }
1901
+
1672
1902
  # Not where the person's startup files bound Ctrl+Alt+F12 in one of the keymaps, which the binding would take over.
1673
1903
  if [[ -o zle ]]; then
1674
1904
  __noldova_options_free=1
@@ -1684,6 +1914,20 @@ if [[ -n "\${__noldova_nonce_read-}" && -z "\${__noldova_nonce-}" ]]; then
1684
1914
  fi
1685
1915
  builtin unset __noldova_keymap __noldova_options_free
1686
1916
  fi
1917
+ # The folder binding is Ctrl+Alt+F11, on the same terms.
1918
+ if [[ -o zle ]]; then
1919
+ __noldova_folder_free=1
1920
+ for __noldova_keymap in emacs viins vicmd; do
1921
+ [[ "$(builtin bindkey -M "$__noldova_keymap" '\\e[23;7~' 2>/dev/null)" == *' undefined-key' ]] || __noldova_folder_free=0
1922
+ done
1923
+ if (( __noldova_folder_free )); then
1924
+ builtin zle -N __noldova_change_folder
1925
+ for __noldova_keymap in emacs viins vicmd; do
1926
+ builtin bindkey -M "$__noldova_keymap" '\\e[23;7~' __noldova_change_folder
1927
+ done
1928
+ fi
1929
+ builtin unset __noldova_keymap __noldova_folder_free
1930
+ fi
1687
1931
 
1688
1932
  precmd_functions=(__noldova_capture $precmd_functions __noldova_precmd)
1689
1933
  preexec_functions+=(__noldova_preexec)
@@ -1703,7 +1947,8 @@ fi
1703
1947
  static shellWordsPosixQuotedSingleQuote = "'\\''";
1704
1948
  static systemRequirementsWindowsBuild = /^\d+\.\d+\.(\d+)$/u;
1705
1949
  static systemRequirementsGlibcVersion = /^(\d+)\.(\d+)/u;
1706
- static terminalHistoryFolderFolderSuffix = /^(\d{1,10})-.{6}$/u;
1950
+ static leftoverFolderSuffix = /^(\d{1,10})-.{6}$/u;
1951
+ static leftoverFolderSuffixWithoutPid = /^[0-9A-Za-z]{6}$/u;
1707
1952
  static terminalHostUuidSeparator = "-";
1708
1953
  static terminalMirrorLeadingWhiteSpace = /^\s/u;
1709
1954
  static terminalOwnerServiceAgentSessionIdField = "agentSessionId";
@@ -14,6 +14,7 @@ import { RequestClient } from "./models/request-client.js";
14
14
  import { TerminalEvents } from "./models/terminal-events.js";
15
15
  import { Resources } from "./resources.js";
16
16
  import { AgentTerminals } from "./services/agent-terminals.js";
17
+ import { CommandDescriber } from "./services/command-describer.js";
17
18
  import { CommandRunner } from "./services/command-runner.js";
18
19
  import { CompletionSource } from "./services/completion-source.js";
19
20
  import { ContextPtySpawner } from "./services/context-pty-spawner.js";
@@ -49,11 +50,12 @@ export class RuntimePart {
49
50
  const writer = new FileSystemWriter();
50
51
  const runner = new CommandRunner(context);
51
52
  const access = FolderAccess.create(process.platform, runner, process.env);
52
- const environment = ShellEnvironment.create(process.platform, process.env, new EnvironmentTools(new LineProcessStarter(context), runner, reader, writer, access, tmpdir()), context.log, Intl.DateTimeFormat().resolvedOptions().locale, MacEnvironment.hasSystemLocaleAsync);
53
+ const signaller = new ProcessSignaller();
54
+ const environment = ShellEnvironment.create(process.platform, process.env, new EnvironmentTools(new LineProcessStarter(context), runner, reader, writer, access, tmpdir(), signaller, process.pid), context.log, Intl.DateTimeFormat().resolvedOptions().locale, MacEnvironment.hasSystemLocaleAsync);
53
55
  environment.start();
54
56
  try {
55
- const events = new TerminalEvents(context.declareEvent(TerminalNames.outputEvent), context.declareEvent(TerminalNames.exitedEvent), context.declareEvent(TerminalNames.restartedEvent), context.declareEvent(TerminalNames.titleChangedEvent), context.declareEvent(TerminalNames.cwdChangedEvent), context.declareEvent(TerminalNames.detachedEvent), context.declareEvent(TerminalNames.closedEvent), context.declareEvent(TerminalNames.openedEvent), context.declareEvent(TerminalNames.launchCommandEndedEvent), context.declareEvent(TerminalNames.runOpenedEvent), context.declareEvent(TerminalNames.runEndedEvent), context.declareEvent(TerminalNames.renamedEvent), context.declareEvent(TerminalNames.commandAddedEvent), context.declareEvent(TerminalNames.commandStartedEvent), context.declareEvent(TerminalNames.outputStartedEvent), context.declareEvent(TerminalNames.commandEndedEvent), context.declareEvent(TerminalNames.promptStartedEvent), context.declareEvent(TerminalNames.screenChangedEvent));
56
- const host = new TerminalHost(new ContextPtySpawner(context), reader, new ShellIntegration(writer, tmpdir(), context.log, access, context.settings, process.platform), new TerminalHistoryFolder(writer, reader, new ProcessSignaller(), tmpdir(), process.pid, context.log, access), new ShellLocator(process.platform, process.arch, process.env, ShellLocator.readUserShell(), reader, runner, context.log), process.platform, release(), new LatestEnvironment(environment, process.env), homedir(), context.log, events, new SavedTerminals(context.database, context.log), new CompletionSource(reader, runner, process.platform, homedir(), context.log));
57
+ const events = new TerminalEvents(context.declareEvent(TerminalNames.outputEvent), context.declareEvent(TerminalNames.exitedEvent), context.declareEvent(TerminalNames.restartedEvent), context.declareEvent(TerminalNames.titleChangedEvent), context.declareEvent(TerminalNames.cwdChangedEvent), context.declareEvent(TerminalNames.detachedEvent), context.declareEvent(TerminalNames.closedEvent), context.declareEvent(TerminalNames.openedEvent), context.declareEvent(TerminalNames.launchCommandEndedEvent), context.declareEvent(TerminalNames.runOpenedEvent), context.declareEvent(TerminalNames.runEndedEvent), context.declareEvent(TerminalNames.renamedEvent), context.declareEvent(TerminalNames.commandAddedEvent), context.declareEvent(TerminalNames.commandStartedEvent), context.declareEvent(TerminalNames.outputStartedEvent), context.declareEvent(TerminalNames.outputPrintedEvent), context.declareEvent(TerminalNames.commandEndedEvent), context.declareEvent(TerminalNames.promptStartedEvent), context.declareEvent(TerminalNames.screenChangedEvent));
58
+ const host = new TerminalHost(new ContextPtySpawner(context), reader, new ShellIntegration(writer, tmpdir(), context.log, access, context.settings, process.platform), new TerminalHistoryFolder(writer, reader, signaller, tmpdir(), process.pid, context.log, access), new ShellLocator(process.platform, process.arch, process.env, ShellLocator.readUserShell(), reader, runner, context.log), process.platform, release(), new LatestEnvironment(environment, process.env), homedir(), context.log, events, new SavedTerminals(context.database, context.log), new CompletionSource(reader, runner, process.platform, homedir(), context.log), new CommandDescriber(runner, context.log));
57
59
  for (const name of TerminalNames.methods)
58
60
  context.registerMethod(name, { handleAsync: t => host.handleAsync(name, t.payload, RequestClient.fromContext(t)) });
59
61
  context.onClientClosed(t => host.closeConnectionAsync(t.connection, t.window));
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @license
3
+ * Copyright (c) Noldova.
4
+ *
5
+ * This source code is licensed under the license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+ import { TerminalCommandDescription, TerminalCommandDescriptions, TerminalShellKind } from "@noldova/terminal.protocol";
9
+ import { CommandFailedException } from "../exceptions/command-failed.exception.js";
10
+ import { DescribeGroup } from "../models/describe-group.js";
11
+ import { KnownDescription } from "../models/known-description.js";
12
+ import { Resources } from "../resources.js";
13
+ export class CommandDescriber {
14
+ runner;
15
+ log;
16
+ known = new Map();
17
+ constructor(runner, log) {
18
+ this.runner = runner;
19
+ this.log = log;
20
+ }
21
+ async describeAsync(kind, program, names, environment) {
22
+ const asked = [...new Set(names)].filter(t => Resources.describedNamePattern.test(t));
23
+ const isPowerShell = kind === TerminalShellKind.PowerShell;
24
+ if (!isPowerShell && kind !== TerminalShellKind.Bash && kind !== TerminalShellKind.Zsh)
25
+ return new TerminalCommandDescriptions([]);
26
+ const perRun = isPowerShell ? Number.POSITIVE_INFINITY : Resources.whatisNamesPerRun;
27
+ const now = Date.now();
28
+ const groups = [];
29
+ const describe = name => {
30
+ const own = isPowerShell ? Resources.powerShellDescriptions.get(name.toLowerCase()) : undefined;
31
+ if (!Object.isUndefined(own))
32
+ return Promise.resolve(own);
33
+ const key = JSON.stringify([kind, program, isPowerShell ? name.toLowerCase() : name]);
34
+ const known = this.known.get(key);
35
+ if (!Object.isUndefined(known) && known.isFresh(now))
36
+ return known.description;
37
+ let group = groups.at(-1);
38
+ if (Object.isUndefined(group) || group.names.length === perRun) {
39
+ group = new DescribeGroup();
40
+ groups.push(group);
41
+ }
42
+ group.names.push(name);
43
+ const entry = new KnownDescription(group.answer.promise.then(t => {
44
+ if (!Object.isNull(t))
45
+ return t.get(name) ?? null;
46
+ entry.failedAt = Date.now();
47
+ return null;
48
+ }, (error) => {
49
+ this.known.delete(key);
50
+ throw error;
51
+ }));
52
+ this.known.set(key, entry);
53
+ return entry.description;
54
+ };
55
+ const pending = asked.map(async (name) => {
56
+ const description = await describe(name);
57
+ return Object.isNull(description) ? null : new TerminalCommandDescription(name, description);
58
+ });
59
+ const shellEnvironment = Object.fromEntries(Object.entries(environment)
60
+ .filter(([t]) => t !== Resources.bashStartupVariable));
61
+ for (let lane = 0; lane < Resources.whatisRuns; lane++)
62
+ void this.runAsync(groups.filter((_t, i) => i % Resources.whatisRuns === lane), kind, program, shellEnvironment);
63
+ const items = await Promise.all(pending);
64
+ return new TerminalCommandDescriptions(items.flatMap(t => Object.isNull(t) ? [] : [t]));
65
+ }
66
+ async runAsync(groups, kind, program, environment) {
67
+ for (const group of groups) {
68
+ try {
69
+ group.answer.resolve(await this.lookUpAsync(kind, program, group.names, environment));
70
+ }
71
+ catch (error) {
72
+ group.answer.reject(error);
73
+ }
74
+ }
75
+ }
76
+ async lookUpAsync(kind, program, names, environment) {
77
+ try {
78
+ if (kind === TerminalShellKind.PowerShell) {
79
+ const output = await this.runner.runAsync(program, [...Resources.environmentReadArguments,
80
+ Buffer.from(Resources.formatPowerShellDescribeScript(names), Resources.utf16Encoding).toString(Resources.base64Encoding)], Resources.describeMilliseconds, environment);
81
+ return CommandDescriber.readPowerShell(output, names);
82
+ }
83
+ const output = await this.runner.runAsync(program, [...kind === TerminalShellKind.Zsh ? [Resources.zshNoStartupArgument] : [],
84
+ ...Resources.posixOneShotArguments, Resources.whatisScript, Resources.whatisScriptName, ...names], Resources.describeMilliseconds, environment);
85
+ return CommandDescriber.readWhatis(output, names);
86
+ }
87
+ catch (error) {
88
+ if (!(error instanceof CommandFailedException))
89
+ throw error;
90
+ this.log.write(Resources.formatDescribeFailed(names.length, error.message));
91
+ return null;
92
+ }
93
+ }
94
+ static readPowerShell(output, names) {
95
+ const found = new Map();
96
+ for (const line of output.split(Resources.lineBreaks)) {
97
+ const tab = line.indexOf(Resources.describedSeparator);
98
+ const index = Number(line.slice(0, tab));
99
+ const name = names[index];
100
+ const description = tab > 0 ? CommandDescriber.toLine(line.slice(tab + 1)) : null;
101
+ if (!Object.isUndefined(name) && !Object.isNull(description))
102
+ found.set(name, description);
103
+ }
104
+ return found;
105
+ }
106
+ static readWhatis(output, names) {
107
+ const asked = new Set(names);
108
+ const found = new Map();
109
+ const ranks = new Map();
110
+ for (const line of output.split(Resources.lineBreaks)) {
111
+ const dash = Resources.whatisDash.exec(line);
112
+ const description = Object.isNull(dash) ? null : CommandDescriber.toLine(line.slice(dash.index + dash[0].length));
113
+ if (Object.isNull(dash) || Object.isNull(description))
114
+ continue;
115
+ for (const [index, entry] of line.slice(0, dash.index).split(Resources.whatisEntrySeparator).entries()) {
116
+ const page = Resources.whatisEntry.exec(entry);
117
+ const name = page?.[1] ?? "";
118
+ const section = page?.[2] ?? "";
119
+ const rank = Resources.whatisSections.findIndex(t => section.startsWith(t));
120
+ const order = (rank < 0 ? Resources.whatisSections.length : rank) * 2 + (index === 0 ? 0 : 1);
121
+ if (asked.has(name) && order < (ranks.get(name) ?? Number.POSITIVE_INFINITY)) {
122
+ found.set(name, description);
123
+ ranks.set(name, order);
124
+ }
125
+ }
126
+ }
127
+ return found;
128
+ }
129
+ static toLine(text) {
130
+ const line = text.replace(Resources.controlCharacters, " ").replace(Resources.whitespaceRuns, " ").trim();
131
+ return line.length === 0 ? null : [...line].slice(0, Resources.maximumDescribedLength).join("");
132
+ }
133
+ }
@@ -33,6 +33,7 @@ export class CommandTracker {
33
33
  isNamesReset = false;
34
34
  builtins = null;
35
35
  hasOptionsBinding = false;
36
+ hasFolderBinding = false;
36
37
  isLoaded = false;
37
38
  lastCommand = null;
38
39
  prompts = 0;
@@ -128,6 +129,8 @@ export class CommandTracker {
128
129
  this.builtins = null;
129
130
  else if (mark.value?.startsWith(Resources.optionsProperty) === true)
130
131
  this.hasOptionsBinding = mark.value.slice(Resources.optionsProperty.length) === Resources.optionsBound;
132
+ else if (mark.value?.startsWith(Resources.folderKeysProperty) === true)
133
+ this.hasFolderBinding = mark.value.slice(Resources.folderKeysProperty.length) === Resources.folderKeysBound;
131
134
  break;
132
135
  }
133
136
  }