diff --git a/extras/clink/CHANGES b/extras/clink/CHANGES index af8b6b1f1bc64ee7cdea2901c44a673abf7466ad..9d91db95a49c54fa434879b6b5831f2289ecb7b9 100644 --- a/extras/clink/CHANGES +++ b/extras/clink/CHANGES @@ -1,32 +1,697 @@ +# Changes -### Changes +## Releases from [chrisant996/clink](https://github.com/chrisant996/clink) fork -##### v0.4.9 +### v1.2.9 + +- Added detection for possible antivirus interference when injecting Clink. +- Ignore duplicate scripts paths when loading scripts. +- Fixed [#118](https://github.com/chrisant996/clink/issues/118); inputrc is not read from state directory (regression introduced in v1.0.0). + +### v1.2.8 + +- Fixed `...\` or `.../` to change directories (path separator after several dots). +- Fixed `/dirname/` to change directories (forward slashes when a directory is the only thing in the input line). +- Fixed [#114](https://github.com/chrisant996/clink/issues/114); "Clink already loaded in process" error when autorun is installed for both Current User and All Users. +- Fixed [#113](https://github.com/chrisant996/clink/issues/113); forward slash translation didn't work with the `cd` command. + +### v1.2.7 + +- Fixed [#113](https://github.com/chrisant996/clink/issues/113); `clink.slash_translation()` had been removed (regression introduced in v1.0.0). + - The new `match.translate_slashes` setting controls the default behavior for slash translation for completion matches. + - The new `clink.translateslashes()` API can override slash translation for completion matches (and `clink.slash_translation()` is supported for backward compatibility). + +### v1.2.6 + +- Fixed tilde expansion for directory by itself; now `~\` can change the working directory to the `~` directory. +- Fixed pagination when displaying completions that take more than 1 line to display. +- Fixed inserting directory match completions when a Lua script didn't include a trailing path separator in the directory match. +- Fixed [#111](https://github.com/chrisant996/clink/issues/111); `..` completion is different from bash (regression introduced in v1.0.0). + +### v1.2.5 + +- Added `os.expandenv()` function to expand environment variables in a string. +- Added `console.cellcount()` function to count the cells a string will use when displayed. +- Added `console.plaintext()` function to remove ANSI escape codes from a string. +- Clink now sets `%=clink.bin%` that points to the Clink binaries directory. This can be particularly useful for a portable installation of Clink so that scripts can find the Clink binaries directory and construct relative paths to other nearby files. +- Clean up column alignment in `--help` texts. +- Fixed `history.sticky_search` with anchored history search. +- Fixed `clink inject --profile` to use correct log file name while initially injecting. +- Fixed Clink autorun to be more compatible with Cmder ([Cmder #2536](https://github.com/cmderdev/cmder/issues/2536)). + +### v1.2.4 + +- Added support for Shift+Arrows to select text and typing to replace selected text. +- Added optional argument to `word_classifications:classifyword()` and `word_classifications:applycolor()` to allow only applying color where another color hasn't yet been applied. +- Fixed first Up after reusing a history line so that it gets the reused history line, rather than getting the previous history line. +- Fixed `add-history` command to not add blank lines to history. +- Fixed `rl.setmatches()` (regression introduced in v1.1.26). +- Fixed input coloring for `clink set` and any color setting name (regression introduced in v1.2). +- Fixed potential crash with `clink history --session`. +- Fixed Ctrl+D when `cmd.ctrld_exits` is disabled; it didn't exit, but it did still discard the input line and start a new prompt. +- Fixed [#107](https://github.com/chrisant996/clink/issues/107); autorun reports inject failures (regression introduced in v1.2.3). +- Fixed [#106](https://github.com/chrisant996/clink/issues/106); history missing `--bare` option (regression introduced in v1.2.3). + +### v1.2.3 + +- Added `history.sticky_search` setting: when enabled, reusing a history line does not add the reused line to the end of the history, and it leaves the history search position on the reused line so next/prev history can continue from there (e.g. replaying commands via Up several times then Enter, Down, Enter, etc). +- Added failure reporting and logging when `clink inject` fails. +- Added `--unique` flag for use with `clink history compact --unique` to remove duplicate entries from the history list. +- The `clink-popup-complete` command now matches wildcards. +- Restored the Ctrl+Alt+U key binding from v0.4.9 (moves the current working directory up one level). +- Fixed searching for inputrc files to also search in the profile directory (regression introduced in v1.0.0). +- Fixed incremental search in the History popup list to search in reverse order (bottom to top). +- Fixed `clink-popup-history` to set the history search position like other history search commands do, so that it plays well with the `history.sticky_search` setting. + +### v1.2.2 + +- Added `%CLINK_HISTORY_LABEL%` environment variable to use a different master history file (fixes [#99](https://github.com/chrisant996/clink/issues/99)). + +### v1.2.1 + +- Added Troubleshooting Tips section in the documentation. +- Added backward compatibility for `clink set` with v0.4.9. Old setting names and values are not documented, but are automatically mapped to the appropriate new setting(s). This was done so that suggestions in old web sites and posts can usually continue to work, to reduce confusion and support burden. +- Fixed [#97](https://github.com/chrisant996/clink/issues/97); VS2017 error C2039: 'min': is not a member of 'std'. +- Fixed [#96](https://github.com/chrisant996/clink/issues/96); wrong setting string (the name of a setting was accidentally truncated). +- Fixed some slightly inaccurate/incomplete migration from old settings to new settings. + +### v1.2 + +- First official release from [chrisant996/clink](https://github.com/chrisant996/clink) fork. + +### v1.1.49 + +- Added `clink.classifier()` to enable coloring the input line independently from argmatchers. +- Added `word_classifications:applycolor()` to apply SGR escape codes anywhere in the input line. +- Removed `word_classifications:iswordclassified()`. +- Fixed the Product Version string in the binary file version resources. + +### v1.1.48 + +- Added `clink.getansihost()` function to get Clink's best guess who will process ANSI escape codes (can be useful for avoiding 256 bit and 24 bit color codes, for example). +- Added detection for being hosted in ConsoleZ. +- Fixed [#20](https://github.com/chrisant996/clink/issues/20); `set /p VAR=""` shows the normal command prompt text instead of empty prompt text. + +### v1.1.47 + +- Added default key binding for Ctrl+Space to invoke `old-menu-complete`, which is the most similar to CMD's standard Tab behavior. +- Fixed `search-ignore-case` config variable to be on by default. + +### v1.1.46 + +- Added `rl.setvariable()` to temporarily override the value of a Readline config variable. +- The completion commands now also expand tilde by itself (`~`), in addition to tilde followed by a path separator (`~\etc`). +- Fixed [#94](https://github.com/chrisant996/clink/issues/94); setting `history.save` to False also disables interactive history in subsequent sessions. + +### v1.1.45 + +- Fixed [#93](https://github.com/chrisant996/clink/issues/93); stdout is sometimes broken by Cmder init.bat. + +### v1.1.44 + +- Added `clink.getsession()`. +- Added `%CLINK_NOAUTORUN%` which overrides automatic inject when Clink is installed for autorun. +- Fixed [#92](https://github.com/chrisant996/clink/issues/92); `clink-popup-history` and similar commands not working with ConEmu and Cmder (regression introduced in v1.1.25). + +### v1.1.43 + +- Added `clink history --diag` flag that prints diagnostic information while performing history operations. +- Minor optimization in `clink history` when printing the full list of history items. +- Fixed `clink history compact` so it actually performs compaction. + +### v1.1.42 + +- Added `clink history --bare` flag to omit history item numbers. +- Added several Lua functions: + - `io.popenrw()` is like `io.popen()`, but returns both a read file handle and a write file handle (see documentation for important usage warning). + - `os.createtmpfile()` creates a unique named temporary file, with control over the prefix and suffix and path. + - `os.getfullpathname()` to get the full path name for a file. + - `os.getlongpathname()` to get the long path name for a file. + - `os.getshortpathname()` to get the 8.3 short path name (if available) for a file. +- Improved argument validation for Clink's Lua APIs. This could expose bugs in existing scripts, so there is also a `lua.strict` setting that can be disabled to revert back to loose argument validation. +- Updated documentation. +- Fixed `clink history compact` so that it forces compaction as intended. +- Fixed completion for `clink set` so that filename completion works in string settings. +- Fixed backwards return value from `rl.invokecommand()`. +- Fixed console input/output modes across `luafunc:` key bindings, in case the Lua functions spawn a process that alters the console mode without restoring it. + +### v1.1.41 + +- Added `terminal.adjust_cursor_style` setting as a workaround to avoid interfering with the Windows 10 Cursor Shape console setting. There are several trade-offs, though. +- Added `rl_buffer:refreshline()` function to redraw the input line, e.g. in case something has written over it. +- Added `os.getpid()` function to get the process ID, intended mainly to help salt unique resource names. +- Added `clink.onfiltermatches()` so scripts can register a callback function to run after Clink generates matches and before it displays them. + +### v1.1.40 + +- Added a group of `clink-complete-numbers` commands that do completion for numbers from the console screen, bound to Ctrl+Alt+N by default. +- Added `rl.getlastcommand()` function that returns the name of the last command invoked by key bindings. +- Fixed sort order in Alt+H for the newly supported key bindings (that were added in v1.1.39). +- Fixed Ctrl+Space (regression introduced in v1.1.39). +- Fixed various Ctrl+Shift+whatever combinations (regression introduced in v1.1.39). +- Fixed `rl.setmatches()` when the input line is not empty and `clink.colorize_input` is enabled. + +### v1.1.39 + +- Added support for many more key bindings, such as Ctrl+Shift+Letter keys. +- Added `terminal.differentiate_keys` setting that when enabled allows binding Ctrl + H or I or M or [ separately from Backspace, Tab, Return, or Escape. +- Removed `terminal.modify_other_keys` setting and made it always enabled. +- Changed `terminal.use_altgr_substitute` to be disabled by default so that Ctrl+Alt key bindings can work by default on keyboards with AltGr. +- Changed output from `clink echo` so it's directly usable in the inputrc files. +- Fixed `terminal.use_altgr_substitute` to only affect AltGr substitute key combinations (it had always broken the RightAlt key in general on other keyboard layouts). +- Fixed a benign issue with the console input mode in `clink echo`. + +### v1.1.38 + +- Fixed [#84](https://github.com/chrisant996/clink/issues/84); added `terminal.use_altgr_substitute` setting. +- Fixed [#80](https://github.com/chrisant996/clink/issues/80); clink.log is not deleted when Cmder injects Clink. + +### v1.1.37 + +- Fixed copy to clipboard (it never cleared the clipboard!). +- Fixed [#82](https://github.com/chrisant996/clink/issues/82); added two new `clink.paste_crlf` modes: `ampersand` replaces newlines with ampersands, and `crlf` pastes newlines as-is and executes any commands ending in a newline. +- Fixed [#69](https://github.com/chrisant996/clink/issues/69); space in the prompt disappears after enter echo: added support for CJK codepages. + +### v1.1.36 + +- Fixed [#79](https://github.com/chrisant996/clink/issues/79); Issue with United States - international keyboard layout (regression introduced in v1.1.0). +- Fixed [#78](https://github.com/chrisant996/clink/issues/78); crash when history file contains a line longer than 8192 characters (regression introduced in v1.1.2-alpha). + +### v1.1.35 + +- Fixed when the `mark-directories` inputrc variable is `off` (regression introduced in v1.1.1-alpha). +- Fixed Lua reading from stdin, especially in the Lua debugger (regression introduced in v1.1.25). +- Fixed exponential cost performance bug in Readline when removing duplicate matches. + +### v1.1.34 + +- Fixed copying to clipboard (CF_UNICODETEXT was put on the clipboard correctly, but CF_TEXT was empty and should have been omitted to let Windows automatically convert it from the Unicode text). + +### v1.1.33 + +- Make the "replacing arglink" warning message a little more informative, and write a lua traceback to the Clink log file. +- Fixed [#77](https://github.com/chrisant996/clink/issues/77); with ConsoleZ scrolling does not always work. +- Fixed [#76](https://github.com/chrisant996/clink/issues/76); cannot `cd` up multiple directories normally. + +### v1.1.32 + +- Added support for non-standard escape codes to set the window title or print environment variables. Depending on the `terminal.emulation` setting, the behavior is slightly different. When `emulate` Clink processes the escape codes. When `native` with ConEmu (and Clink) the escape codes are passed to ConEmu, except that Clink processes the environment variable codes in prompt strings. When `native` with other terminals, Clink preprocesses the title and environment variable escape codes in prompt strings, but passes the escape codes to the terminal outside of prompt strings. +- Fixed [#67](https://github.com/chrisant996/clink/issues/67); AutoRun interferes with Cmder. + +### v1.1.31 + +- Fixed [#74](https://github.com/chrisant996/clink/issues/74); clink gets confused by non-standard ConEmu escape codes. +- Fixed [#73](https://github.com/chrisant996/clink/issues/73); `exec.space_prefix` and other settings defined in Lua scripts don't take effect until second input line (regression introduced in v1.1.4). + +### v1.1.30 + +- Fixed history compacting on x86 (regression introduced in v1.1.2-alpha). + +### v1.1.29 + +- Added `clink installscripts` and `clink uninstallscripts` to make it easy for package managers like Scoop to install/uninstall script packages for use with Clink. The installed script paths are stored in the registry for the current user. +- Fixed `bold` vs `bright` colors to more accurately follow generally accepted ANSI escape code conventions: + - Renamed `dim` to `nobold` for clarity (though `dim` is still recognized for backward compatibility). + - `bold` adds intensity to a non-intense color (e.g. `cyan` which is 36). + - `nobold` removes intensity added by `bold` (e.g. `1;36` becomes `36`), but does not remove intensity from an explicit intense color (such as `bright cyan` which is `96`). +- Fixed support for `--file=` flags in argmatchers. +- Fixed match display filtering on the first try for a word (regression introduced in v1.1.19). +- Fixed the `clink --profile` flag (regression introduced in v1.1.10). +- Fixed `clink info` to accurately report the script dirs (it didn't account for the `clink.path` setting correctly). + +### v1.1.28 + +- Renamed the `log.rl_terminal` setting to `debug.log_terminal`; it has already been repeatedly very useful in multiple was since it was added, so it stays. +- Fixed [#70](https://github.com/chrisant996/clink/issues/70); ctrl+c not working (regression introduced in v1.1.25). + +### v1.1.27 + +- Added `color.argmatcher` setting which, when set, is used to color a command name if it has an associated argmatcher (this supersedes `color.cmd`, `color.doskey`, and `color.input`). By default it's not set. +- Added `log.rl_terminal` setting which logs all terminal input and output for Readline (this setting may be renamed or removed in the future). + +### v1.1.26 + +- Added `rl.invokecommand()` which can invoke a Readline command from inside a "luafunc:" key binding. +- Added `rl.setmatches()` which can override match completions from inside a "luafunc:" key binding. +- Worked around UTF8 key binding problem with Readline which had been causing some meta key bindings (M-x, M-C-x, etc) to sometimes produce garbled key bindings and garbled entries in `clink-show-help` (Alt+H). +- Fixed crash if "luafunc:" key binding macro refers to a symbol that doesn't exist. + +### v1.1.25 + +- Added `clink-find-conhost` command that, when in a default (conhost) console window, is equivalent to picking "Find..." from the system menu. +- Added `clink-mark-conhost` command that, when in a default (conhost) console window, is equivalent to picking "Mark" from the system menu. +- `clink-copy-word` now copies the current word by default, but copies the nth word if a numeric argument is entered (see "Readline Arguments" in the Readline manual). +- Fixed match display filtering to not exceed the screen width (regression introduced in v1.1.12). +- Fixed multi-key sequences; in some cases it could get confused about whether an input key is part of a multi-key binding sequence (regression introduced in v1.1.1-alpha). +- Fixed stray input processing by conhost (holding Ctrl+A or Ctrl+F or etc could accidentally trigger conhost's shortcut keys). +- Fixed popup window location and size when using Windows Terminal. +- Fixed input coloring after `operate-and-get-next`; also fixes brief flicker of incorrect coloring whenever the input line is modified. + +### v1.1.24 + +- `auto` for `terminal.emulation` now uses native VT support on Windows 10 build 15063 and higher, unless the HKCU\Console\ForceV2 regkey is 0. +- Special quote handling now enables `"dir\"fi` to complete to `"dir\file"`. CMD simply strips quotes during completion, and now Clink behaves similarly. +- Breaking Change: `line:getword()` and `line:getendword()` now strip quotes from the word. This should generally automagically make existing match generators work even with embedded quotes, but there's a chance that some match generator might need to be updated. This seems like a reasonable compromise, given the general benefit purchased by this breaking change. +- `os:globdirs()` and `os:globfile()` strip quotes from the globpattern in order to behave more like CMD. Embedded quotes are nonsensical and the intended interpretation is clear, so the APIs now help out with that. +- Fixed [#66](https://github.com/chrisant996/clink/issues/66); crash when injecting into 32 bit cmd (regression introduced in v1.1.21). +- Fixed [#64](https://github.com/chrisant996/clink/issues/64); wrong cursor position when PROMPT contains BEL character. +- Fixed [#62](https://github.com/chrisant996/clink/issues/62); argmatchers should color `-x:"foo"` as a flag if `-x:` is a flag. +- Fixed [#61](https://github.com/chrisant996/clink/issues/61); argmatchers should not handle completion for text immediately following `-flag:`. Instead it always uses file completion. A custom generator can be used to override that behavior. +- Fixed [#60](https://github.com/chrisant996/clink/issues/60); completion fails with multiple slashes. +- Fixed completion in some circumstances. Readline and Clink didn't always agree on where the word breaks were; now Clink always tells Readline where the word breaks are (so that completion, input colorization, and lua scripts can all work properly and consistently). +- Fixed 256 color ANSI codes. + +### v1.1.23 + +- Fixed [#57](https://github.com/chrisant996/clink/issues/57); slashes not normalized in some cases. +- Fixed [#45](https://github.com/chrisant996/clink/issues/45); interaction between `history.dupe_mode`=`erase_prev` and `history.shared`=`false`. +- Fixed `menu-complete-wraparound` when off and there's only 1 match. + +### v1.1.22 + +- Added `menu-complete-wraparound` (on by default) that controls whether completion commands wrap around when cycling past an end (affects popup windows as well). +- Fixed match completion getting stuck (regression introduced in v1.1.19). +- Fixed active mark region so it gets deactivated appropriately (it wasn't hooked up fully for Readline's callback mode, which is the mode Clink uses). +- Fixed `clink-show-help` (Alt+H) so it's able to list `C-@` bindings. +- Fixed inconsistent mark color. + +### v1.1.21 + +- Added `clink.oninject()` so scripts can register a callback function to run when Clink is injected into CMD. +- Added `console.linehascolor()` function that returns whether the specified line contains any of the specified colors. +- Added `console.findprevline()` and `console.findnextline()` functions that can search backwards or forwards for text and/or colors in the screen buffer. Regular expressions may be used. +- Fixed doskey alias parsing for match generators and input line coloring (Clink had been using slightly different parsing rules than CMD does). +- Fixed the "-- More --" prompt while listing key bindings; Esc didn't quit, and unexpected keys weren't ignored. + +### v1.1.20 + +- Now you can bind Lua functions to keys via "luafunc:" macros! Added new `rl_buffer` type that gets passed to the Lua function. +- Added a group of `console` Lua APIs intended mainly for use by Lua function key bindings (e.g. `console.scroll()`). +- Added `string.equalsi()` function that performs a case insensitive UTF8 comparison of two strings. +- Added `string.matchlen()` function that compares two UTF8 strings and returns how many characters match at the beginning, or -1 if the entire strings match. It respects the `match.ignore_case` and `match.ignore_accents` settings. +- Added `path.toparent()` function that adjust the input string by moving up one directory level. +- Added `clink.onendedit()` so scripts can register a callback function to run when editing finishes (e.g. Enter is pressed). If desired, the function can even change the input text. This is very powerful, and should be used carefully. +- Changed `os.getbatterystatus()` to return a table with the battery status details, rather than four separate return values. +- Fixed the `doskey.enhanced` setting to not expand doskey aliases when preceded by a space. However, a doskey alias after a `&` or `|` command separator needs to be preceded by two spaces to avoid expanding it. That's so `alias & alias` expands both, and ` alias & alias` expands neither; while the rules are more complicated to explain, they make more sense visually. +- Fixed environment variable completion (regression introduced in v1.1.19). +- Fixed Cmder startup (regression introduced in v1.1.17). Cmder expects to be able to replace Clink v0.4.9's clink.lua file, but there is no such thing anymore in newer versions of Clink. To be properly backwardly compatible with Clink v0.4.9 requires loading clink.lua (if it exists) from the first script directory listed by `clink info`, and ignoring clink.lua files in all other script directories. + +### v1.1.19 + +- Improved responsiveness while typing: matches are collected only on demand, instead of always while typing. This makes it possible to always support match completion for UNC paths. +- Fixed [#50](https://github.com/chrisant996/clink/issues/50); Alt+H could warn about likely mistakes in key bindings. + +### v1.1.18 + +- The input text now has context sensitive coloring based on the argmatchers. It's on by default and can be turned off with `clink set clink.colorize_input false`. +- Updated the Readline library to 8.1. +- Terminal emulation now supports the audible bell character. +- Fixed [#48](https://github.com/chrisant996/clink/issues/48); `menu-complete` gets stuck. +- Fixed [#47](https://github.com/chrisant996/clink/issues/47); Alt+D erases history instead of word. +- Fixed [#46](https://github.com/chrisant996/clink/issues/46); typing `..` in subdirectory of root doesn't work. +- Fixed restoring color after pager when showing help. +- Fixed `clink set` match completions for color settings. + +### v1.1.17 + +- Added `os.getbatterystatus()` function that gets battery status information much faster than launching `wmic`. +- Fixed [#44](https://github.com/chrisant996/clink/issues/44); Path completion doesn't work with `cd /d`. +- Fixed loading scripts to ignore loading clink.lua, so that loading scripts behaves like Clink v0.4.9. + +### v1.1.16 + +- Added `match.ignore_accent` setting (enabled by default) that ignores Latin alphabet diacriticals when completing matches (e.g. `ä` matches `a`, `ı` matches `i`, `ł` matches `l`, etc). +- Fixed [#42](https://github.com/chrisant996/clink/issues/42); history lines are split on special characters. +- Fixed [#41](https://github.com/chrisant996/clink/issues/41); Enable custom doskey handling of `..` and `-`. +- Fixed Readline bug inserting dir matches; `\win_ foo` (cursor at `_`) would become `\Windows\\_ foo`. +- Fixed the `quoted-insert` command to insert just `\x1b` when ESC is pressed. + +### v1.1.15 + +- Migrating settings now immediately writes a new settings file, instead of waiting until a setting is changed. +- Added support to detect when running in Windows Terminal and use native terminal support (which enables things like Xterm 256 and 24-bit color support). +- Added terminal emulation support for Xterm 256 and 24-bit color escape codes. Clink maps the specified color to the most similar color in the active 16 color palette (using the CIELAB color space). To get full support for 24-bit color, it's necessary to use ConEmu or Windows Terminal or a similar console host, or to set `terminal.emulation` to `native` (which isn't supported on some older Windows OS versions). +- Allow doskey macros named `..` or `-`, and also now doskey macros that resolve to `..` or `-` or a directory name will work (just like if the macro text had been typed at the Clink prompt). +- Fixed compatibility problem with various scripts getting the %HOME% environment variable. Now if it isn't set, then Clink synthesizes %HOME% from %HOMEDRIVE% and %HOMEPATH% or from %USERPROFILE%. +- Fixed saving color settings to behave like other settings: only write a setting's value to the setting file if it differs from the default value. +- Fixed the `clink.print()` Lua function so it also works during loading scripts and during prompt filtering. +- Fixed the Readline input text display getting garbled if the filtered prompt includes Xterm's OSC window title code (`\x1b]0;text\x07`). Clink doesn't support that escape code, but at no longer garbles the input text if that escape code is present. + +### v1.1.14 + +- Migrate settings and history from an old version of Clink, if present. This only happens if the new-version Clink settings or history files don't exist. (Deleting an existing new-version Clink settings or history file will cause migration to happen again.) +- Added `color.prompt` setting for backward compatibility with Clink v0.4.x. + +### v1.1.13 + +- Fixed `clink.arg.register_parser` backward compatibility. + +### v1.1.12 + +- Added `clink.ondisplaymatches()` as a replacement for the deprecated `clink.match_display_filter`. The new API is able to support popup list windows as well. +- Speculative possible fix for [#35](https://github.com/chrisant996/clink/issues/35) Crash when clink on clink.bat. +- Fixed [#33](https://github.com/chrisant996/clink/issues/33); Tab autocomplete, auto-quoting paths doesn't seem to work as in Clink 0.4.9. + +### v1.1.11 + +- Changed to load Lua scripts only once per session, unless forced to reload them. This enables backward compatibility for things like [z.lua](https://github.com/skywind3000/z.lua) which has certain features that rely on Clink only loading scripts once per session. +- Added `clink.onbeginedit()` so scripts can register a callback function to run each time the edit prompt is activated. +- Added `lua.reload_scripts` setting to optionally force reloading Lua scripts each time the edit prompt is activated. +- Added `color.message` setting for the Readline message area color (e.g. the search prompt message or digit argument prompt message, etc). +- Fixed stray sticky `=` appended to completions after typing `set ` and then typing a different command. + +### v1.1.10 + +- Fixed [#32](https://github.com/chrisant996/clink/issues/32); hooking `ReadConsoleW` on Windows 7. + +### v1.1.9 + +- Added backward compatibility for `clink.match_display_filter`. The clink-completions/git.lua script uses it a lot, and that should all be working now. +- `settings.add` adds a color setting when the type is string and the name starts with "color.". +- `settings.get` now has an extra parameter to request the user friendly color name when getting a color setting. +- Added `clink.version_encoded` variable with the Clink version number as _MMmmmpppp_ (e.g. v1.1.9 is `10010009`) to make it easy for scripts to check for feature availability. +- The `clink info` command now shows Lua script paths as well. +- Fixed backward compatibility for loading scripts from the profile directory (if `clink.path` isn't set, then load scripts from the DLL directory and the profile directory). +- Fixed some `color.input` bleed through to other things (introduced in v1.1.5). +- Fixed scroll commands (regression introduced by input line color in v1.1.5). +- Fixed horizontally sorted match display and re-enabled the performance fix from v1.1.4. +- Fixed wildcard evaluation with non-file and non-directory matches (e.g. a branch name `origin/master` accidentally didn't match `or` or `*ma` because of the `/`). +- Fixed sort order of `foo\` vs `foo.bar\` when displaying matches or using the `menu-complete` family of commands. +- Fixed potentially-missing trailing path separator when `menu-complete` completes a directory match (regression introduced by wildcard matching in v1.1.5). +- Other obscure minor fixes. + +### v1.1.8 + +- Fixed file match completions when an argmatcher only generates flag matches. +- Fixed automatic inferring whether Readline should use filename completion and/or display rules (regression introduced by backward compatibility in v1.1.3-alpha). +- Fixed backward compatibility for `clink.find_files()` and `clink.find_dirs()` (regression introduced by performance improvement in v1.1.7). + - Ignore extra arguments after the first one (the performance improvement in v1.1.7 revealed that some scripts call `clink.find_files()` with extra invalid arguments; e.g. clink-completions/modules/matchers.lua). + - Don't append a trailing path separator on directory names returned by these functions (the new `os.globfiles()` and `os.globdirs()` functions do, but the old `clink.find_files()` and `clink.find_dirs()` functions should not). +- Fixed backward compatibility for coloring matches (regression introduced by backward compatibility changes in v1.1.4). + +### v1.1.7 + +- Performance improvement when displaying matches: When enumerating files and dirs, the `os.globfiles` and `os.globdirs` functions have all the info about each file. Now they can return that info in a table. This frees the match display function from needing to do any further file system IO. The performance boost is noticeable. +- Rewrote the color settings: the .fg and .bg sub-settings are gone, and the main setting now uses a more natural syntax (e.g. `clink set color.input bright yellow` or `clink set color.modmark bright cyan on blue`). +- Added "cmd" match type for shell (CMD.EXE) command completions. +- Added VT emulation for the reverse video SGR parameters. +- Fixed tab completion for clink set setting, and also handle the new color setting syntax. +- Fixed confusing behavior if multiple scripts try to add settings with the same name (now the first one succeeds and the rest report errors). + +### v1.1.6 + +- Hooked up tilde completion in the `cd`, `md`, and `rd` command argmatchers. +- Hooked up tilde completion with the `exec.enable` setting ("~\pro" matches "C:\Users\myusername\program.exe"). +- When `terminal.emulation` is `auto`, now it also detects ANSI{32|64}.DLL just like Clink 0.4.8 did. + +### v1.1.5 + +- The `menu-complete` family of commands now support matching `?` and `*` wildcards when the `match.wild` setting is enabled. +- Added `colour.input` and `colour.modmark` settings for coloring Readline's input line. +- Added `clink.upper()` Lua function, and both `clink.lower()` and `clink.upper()` are properly UTF8 aware now. +- Added `clink-copy-word` command that copies the word at the cursor to the clipboard. +- Added `clink.promptfilter` setting to control whether to filter the prompt with Lua scripts. +- Renamed `terminal.emulate` setting to `terminal.emulation`. +- Improved executable file extension logic to consistently use %PATHEXT% (and efficiently). +- Improved file extension logic (e.g. "file.foo bar" has no extension because of the space). +- Updated arg matcher for `clink` itself (was missing some flags). +- Changed `colour.hidden` setting to not be set by default. +- Fixed [#28](https://github.com/chrisant996/clink/issues/28); Tab completion for "~" does not work. +- Fixed [#25](https://github.com/chrisant996/clink/issues/25); Unicode surrogate pairs (and emoji) input isn't working -- Microsoft Terminal renders the text correctly, but ConEmu and the default conhost still don't (and that isn't a Clink issue). +- Fixed screen size bug in Readline on Windows. +- Fixed the backwards values in the `terminal.emulation` setting. +- Fixed `....` so it works properly again. +- Fixed case sensitive sorting of matches. +- Fixed script error when %PATHEXT% is empty. +- Fixed the `exec.cwd` Clink setting to default to true, so that the default behavior is consistent with how v0.4.x behaved. +- Fixed the `cd`, `md`, `rd`, etc argmatchers to only match one argument to be consistent with the actual command syntax. + +### v1.1.4 + +- Automatically detect when running inside ConEmu and disable Clink's Virtual Terminal emulation. +- Added `search-ignore-case` inputrc variable that makes the history search commands case insensitive. +- Suppress adding a space after completing a flag match that ends with `:` or `=` (e.g. `msbuild -maxCpuCount:`). +- Report any errors while loading Lua scripts. +- Report an error if a Lua script tries to add a flag string that begins with a letter. +- Fixed slow printing of possible matches. Readline is inefficient about emitting output, so Clink supplies a custom implementation. +- Fixed some bugs in auto detection of flag prefix characters. +- Fixed backward compatibility for flags, and for args when merging two parsers by calling `clink.arg.register_parser('foo')` multiple times for the same command string. +- Fixed truncated message when the last line of a prompt exceeds 128 characters. +- Fixed abort (Ctrl+G or Esc) in non-incremental history search mode. +- Fixed saved values for settings added by Lua scripts; now the saved value is available to the script immediately on adding the setting, and saved values are retained even if the setting isn't always added by the script. +- Fixed (and documented) shorthand form for defining an argmatcher. +- Fixed length of colored match prefix after a path separator. +- Fixed normalizing a slash by itself (`command /` mustn't become `command \` since that can interfere with completing flags). +- Fixed the `completion-auto-query-items` inputrc variable. +- Fixed the key binding list to correctly respect `completion-display-width`. +- _No visible effect yet: internal change that parses the input line to identify colors to use for each word (command, argument, flag, etc), but the colors aren't yet applied to the input line._ + +### v1.1.3-alpha + +- Fixed argmatcher lookup to be more strict, like in Clink 0.4.9 (match exact names, or name plus an extension from %PATHEXT%). +- Backward compatibility: + - Most things should work now. + - Dropping the new Clink on top of the vendor\clink directory in Cmder seems to work -- _but make a backup before you try this at home!_ +- API changes: + - Added `log.info()` function. + - Added Clink version numbers in `clink.version_major`, etc. + - Added `_argmatcher:getwordbreakinfo()` callback; removed `_argmatcher:setprefixincluded()` (it was a mess, and it was new to v1.x, so there's no compatibility concern with removing it). + - Deprecated `_argmatcher:setflagprefix()`; now it happens automagically when using `_argmatcher:addflags()`. + - Introduced several deprecated functions to support backward compatibility. +- Improvements to Lua debugger: + - Added `lua.traceback_on_error`, `lua.break_on_error`, and `lua.break_on_traceback` settings to make debugging script errors easier. + - Made `pause()` consistent about pausing in the caller (rather than sometimes inside the pause command itself). + - The debugger automatically shows the stack trace when entering debug mode, and on every pause. + - Show 3 lines of source context by default. + - The help list is sorted now. + - Fixed the `set` command in the debugger to behave as documented. + +### v1.1.2-alpha + +- Documentation is mostly updated; just the argmatcher Lua API and Clink command line options are left to be documented. +- Added `history.max_lines` setting that controls how many lines of command history to save (1 to 50000, default is 2500). +- Added `readline.hide_stderr` setting that can suppress stderr output from the Readline library. +- For backward compatibility with 0.4.8, `clink_inputrc` files are loaded as well. +- Lua script API changes: + - `addmatch()` in Lua scripts takes an optional match type argument. + - Removed `displayable`, `aux`, and `suffix` fields in matches. + - Revert the change to disallow mixing file/directory/symlink with other match types (it broke the tests and certain completion scenarios). +- Fixed issues: + - [#18](https://github.com/chrisant996/clink/issues/18) alt+digit then alt+ctrl+y isn't working. + - [#17](https://github.com/chrisant996/clink/issues/17) arrow keys don't exit `reverse-search-history` like in bash. + - [#16](https://github.com/chrisant996/clink/issues/16) problems with $T in doskey macros. + - [#13](https://github.com/chrisant996/clink/issues/13) `clink history delete ` returns a CRT error. +- Other fixes: + - There should be no more problems running on Windows Insider builds because Clink now uses [Detours](https://github.com/microsoft/detours) for hooking APIs. + - Fixed crash in `insert-completions` due to heap failure (introduced by the performance changes for displaying matches). + - Fixed `clink` and `history` built-in aliases (solve glitchy path problem). + - Fixed scrolling to top of screen buffer. + - Fixed env var and `set` completions. + - Fixed `tilde-expand` for quoted text. + - Fixed Esc in Readline's digit argument input mode (it doesn't try to cancel the mode, because that's not how Readline is documented to work). + - Fixed exit code from some `clink` command line options. +- Set locale to UTF8 much earlier to avoid quirky behavior early in script processing. + +### v1.1.1-alpha + +- Exclusively use Readline's completion implementation. This (with fixes and enhancements in Readline itself) makes the completion experience much nicer and more sophisticated, and removes a lot of code that was added in v1.0.0a0. +- Exclusively use Readline's key binding implementation. This makes it possible to have a single consistent way to set key bindings (inputrc) and for `clink-show-help` to list all key bindings, and removes a lot of code that was added in v1.0.0a0. +- Converted all of Clink's internal key behaviors to be implemented as commands that can be bound in the inputrc file. +- Rewrote and refactored the pagination routine to be used in multiple places. +- Fixed prompt filtering to correctly use the specified priority order. +- Readline library: + - Updated the Readline library from v6.2 to v8.0. This picked up lots of bug fixes and new capabilities (for example colored completions). + - Changed Readline to support backslash as a path separator. + - The pager prompt in Readline is optionally colored, controlled by the `colour.interact` Clink setting. + - Added `completion-auto-query-items` config variable (on by default) which asks whether to list possible matches when the number of lines listed will fill one screen page. + - Added `history-point-at-end-of-anchored-search` config variable in inputrc to make the cursor point behave like 4Dos/4NT/TakeCommand when searching forward and backward through command history. + - Fixed prev history at top of history. + - Fixed to get the current values of environment variables when needed, rather than always getting the value from whenever Clink was started. + - Fixed coloring directory completions. + - Fixed `menu-complete` for `\dir` and `.` and `..`. + - Fixed slow performance when displaying matches. Readline was calling stat() at least once per match (!!). A new match type field enables faster performance, coloring readonly and hidden file matches, applying filename completion rules only to filenames (vs branch names or other text strings), correct match de-duplication, and more. The Lua match APIs can supply the new match type. + - Fixed inserting a completion to happen as a single undo group. + - Fixed tilde to map to `%USERPROFILE%` instead of `%APPDATA%` on Windows. +- Typing a directory by itself uses `cd /d` to change to the directory: + - Typing a directory with a trailing path separator changes to the directory. + - Typing `..\` changes to the parent directory. + - Typing `...` or `....` etc moves up an extra parent directory level for each extra dot (2 dots move up one parent, 3 dots moves up two parents, etc). A trailing path separator is optional when there are more than 2 dots. + - Typing `-` or `cd -` or `chdir -` changes to the previous directory. +- Commands that are new, enhanced, or fixed: + - Added `add-history` and `remove-history` commands (similar to 4Dos/4NT/TakeCommand). + - Got the `menu-complete`, `menu-complete-backward`, and `old-menu-complete` commands working (they never worked properly before in Clink). + - Also added a corresponding `old-menu-complete-backward` command for reverse order. + - All of the `*-menu-complete-*` commands support wildcards (`*` and `?`). + - Added `clink-show-help` command (Alt+H). The help now lists _**all**_ key bindings, and it shows user-friendly key names (like `A-Up` or `C-x,C-r` or `C-S-PgUp` or `A-C-S-F3`). + - Added `clink-popup-completions` command that shows a popup window listing possible completions. Enter inserts the highlighted completion. + - Added `clink-popup-directories` command that shows a popup window listing recent directories. Enter changes to the highlighted directory, or Shift+Enter inserts the highlighted directory in the editing line (or Ctrl+Enter). + - Added `clink-popup-history` command that shows a popup window listing command history. Enter executes the highlighted command, or Shift+Enter jumps to the highlighted command in the history (or Ctrl+Enter). + - Added `clink-scroll-lineup`, `clink-scroll-linedown`, `clink-scroll-page-up`, `clink-scroll-page-down`, `clink-scroll-top`, and `clink-scroll-bottom` commands that do what it looks like they'd do and are bound to the keys it looks like they'd be. + - Added `clink-expand-doskey` command (Ctrl+Alt+f) that expands the current line according to the current doskey aliases. + - Added `clink-expand-env-var` command (Ctrl+Alt+e) that expands the environment variable at the cursor point. + - Added `clink-exit` command (Alt+F4) that exits CMD. +- Fixed keyboard input issues: + - Esc is a bindable key now (`\e[27;27~`). + - Added more bindable key combinations (run `clink echo` then press keys to see the key sequence to use in the inputrc file). + - Ctrl+@ (NUL) didn't work. + - Ins toggles insert/overwrite mode. + - Unbound keys are ignored now, instead of inserting gibberish characters (part of the terminal internal key sequence). + - Fixed input handling so the `quoted-insert` command can work properly. + - Fixed Esc while searching. + - Fixed vi mode (was working in v0.4.9, but not in v1.0.x). +- Fixed command history issues: + - The `dont_add_to_history_cmds` Clink setting is a space-delimited list of commands to not add to history. + - Fixed bleeding between history banks. + - Fixed uninitialized variable that made history updates intermittently do nothing or corrupt the other history bank. + - Fixed output from `clink history` to convert to UTF16 when writing to the console (but write UTF8 when output is redirected). +- Fixed terminal output issues: + - Added `terminal.emulate` Clink setting that controls whether Clink does VT emulation or passes all ANSI escape codes directly to the console host. For example, this lets the prompt and completion coloring take advantage of more sophisticated ANSI escape codes such as XTerm 256 color and 16 bit color support. + - Added back support for the `prefer-visible-bell` config variable. + - Fixed underline support. + - Fixed handling for UTF8 output from Readline. + - Fixed invisible cursor point in Lua debugger. +- Completions: + - Added `match.sort_dirs` Clink setting that specifies where to sort directories in the list of possible completions: before files, mixed in with files, or after files. + - Don't attempt completing incomplete UNC paths: at least the `\\server\share\` path components are required (for anything shorter the OS APIs are guaranteed to fail, but will fail slowly). + - Fixed sorting to use Unicode aware locale based sorting (like Windows does) instead of dumb UTF8 byte comparisons. + - Fixed arbitrary limit on completions (had been limited to 64KB worth of completions). + - Fixed quoting spaces in completions. + - Fixed to use the same list as CMD for characters that require quoting. + - Fixed normalizing UNC paths. + - Fixed volume relative completions (e.g. `x:foo`). + - Disallow mixing file/directory/symlink with other match types. This was to avoid a confusing/malfunctioning case in match display and prefix highlighting. +- Fixed UTF8 encoding in various Lua functions. +- Fixed printing stderr output from Readline, Lua, and Clink. +- Fixed crashes and other failures when starting Clink in 32 bit CMD. +- Fixed some memory leaks that accumulated with each new line of input. +- Fixed prompt filtering API to be backward compatible with v0.4.9 scripts. +- Fixed Lua errors from `clink set` (it neglected to fully initialize Clink's Lua integration before loading Lua scripts). +- Fixed UTF8 conversion bug that could truncate a string without fully converting it. +- Fixed serious rampant memory corruption bug in v1.0.x (not present in v0.4.9), which had been causing intermittent malfunctions and data corruption and crashes. +- Fixed multi-line doskey macros to show the prompt in between lines, like CMD does. +- Removed the 4096 byte limit on input. +- Renamed the Clink DLL back to what it was in v0.4.x, to fix compile time problems. +- Other fixed issues: + - [mridgers #544](https://github.com/mridgers/clink/issues/544) Clink v1.0.0.a1 doesn't support cyrillic characters keyboard input on Windows 10 with console V2. + - [mridgers #543](https://github.com/mridgers/clink/issues/543) Not compatible with Windows Insider Build 20150. + - [mridgers #537](https://github.com/mridgers/clink/issues/537) Clink breaks the CMDS tool. + - [mridgers #520](https://github.com/mridgers/clink/issues/520) Clink 1.0.0.a1 - `clink set history_io 1` Error. + - [mridgers #519](https://github.com/mridgers/clink/issues/519) Clink v1.0.0.a1 - `-s|--scripts [path]` command line arg removed? + - [mridgers #516](https://github.com/mridgers/clink/issues/516) Doskey $T not handled properly. + - [mridgers #512](https://github.com/mridgers/clink/issues/512) Command history missing in .history. + - [mridgers #503](https://github.com/mridgers/clink/issues/503) Keyboard shortcut for scrolling. + - [mridgers #501](https://github.com/mridgers/clink/issues/501) Ctrl+Backspace works now. + - [mridgers #487](https://github.com/mridgers/clink/issues/487) Clink breaks ConEmu-specific Escape codes. + - [mridgers #480](https://github.com/mridgers/clink/issues/480) History never saved. + - [mridgers #465](https://github.com/mridgers/clink/issues/465) Using LuaJIT (FFI). + - [mridgers #456](https://github.com/mridgers/clink/issues/456) Clear-screen not working properly when PROMPT is two lines long. + - [mridgers #453](https://github.com/mridgers/clink/issues/453) Wrong cursor position when a line contains non-printable characters. + - [mridgers #442](https://github.com/mridgers/clink/issues/442) Unable to paste more than 1024 characters using Ctrl+V. + - [mridgers #422](https://github.com/mridgers/clink/issues/422) Problem with filename modifiers. + - [mridgers #420](https://github.com/mridgers/clink/issues/420) Use NtSuspendProcess instead of CreateToolhelp32Snapshot to freeze the threads. + - [mridgers #372](https://github.com/mridgers/clink/issues/372) Provide a way to select a previous directory. + - [mridgers #365](https://github.com/mridgers/clink/issues/365) history-search behavior. + - [mridgers #342](https://github.com/mridgers/clink/issues/342) Clink_inputrc not being processed if it the clink_inputrc is a link (created via mklink). +- Fixed many other bugs. + +## Releases from [mridgers/clink](https://github.com/mridgers/clink) original repo + +### v1.0.0a1 _(alpha test release)_ + +- Improve terminal integration with the Readline library. +- Internal improvements to the built-in ecma48 terminal emulator. +- Fixed use after free in Doskey emulation. +- Fixed dash-dash flag completion. +- Search ancestors for a compatible target process (for when cmd.exe starts another process that subsequently starts clink; especially useful during development). +- Use clink/terminal's wcwidth() implementation. +- screen_buffer::set_cursor() should be relative to the visible area. +- Try to adjust the cursor position better when resizing the terminal. +- Some internal Lua functions needed the unquoted clink exe path. +- The origin path now affects the hash in the dll cache, to guard against directory moves. +- More code reorganization. + +### v1.0.0a0 _(alpha test release)_ + +- Extensive code reorganization, refactoring, and rewriting -- multiple times -- almost everything was touched. +- OS integration: + - Fixed Doskey macros on Win8, and on Win10. + - Fixed `clink_x??.exe` startup stall on Windows 10. + - Removed XP support. It doesn't load DLLs like Clink uses them. + - Removed Powershell support. +- Readline integration: + - Search for multiple places for [.|_]inputrc (fixes [mridgers #258](https://github.com/mridgers/clink/issues/258)). + - Disabled Readline's completion code, and only use the clink alternative code. + - Removed redundant slash translation and shims to make it happen. + - Removed control of Readline's suffix appending and disabled it. +- `clink` commands and flags: + - Changed `--cfgdir` to `--profile`, it's no longer required, and added help about it. + - Added a `--version` option to print Clink's version. + - Added `clink info` to print information about Clink. + - Added `clink echo` command to echo input key sequences to stdout. + - Added `clink history` command (fixes [mridgers #172](https://github.com/mridgers/clink/issues/172)). + - Added `history` as an alias for `clink history`. + - Added internal `--list` flag to `clink set` for match generation. + - Removed `--scripts` argument (fixes [mridgers #206](https://github.com/mridgers/clink/issues/206)). + - Updated `clink autorun` command's help text. +- Lua scripts: + - Prefer `userprofile` over other standard environment variables for where to look for lua scripts. + - New API for argument style completion scripts. + - Refactored prompt filtering, and introduced new prompt filtering API. + - Refactored generating matches, and introduced new match generator API. + - Removed built in completions scripts for git, go, hg, and p4. There's better ones. + - Renamed many of clink's Lua functions. + - Moved functions from `clink` to `os` in Lua. + - Removed `clink.is_match()` in Lua; don't presume anything on anyone's behalf about matches. + - Added some current dir functions in Lua. + - Added some env/dir functions in Lua. + - Exposed path manipulation functions to Lua. + - Embed the core Lua scripts instead of loading them from files. +- Terminal IO: + - Added a module for scrolling the screen. + - Rewrote the terminal emulation module, and all Readline IO goes through it. + - Use VT220-style control codes for special keys. + - If Alt is pressed send ESC in the input stream rather than setting meta bit. + - Replaced wcwidth() with a more complete and correct version. +- Settings: + - Added `clink_path` setting for where to look for lua scripts. + - Added `match.ignore_case` setting. + - Added `files.unc_paths` setting for optional matching from UNC paths. + - Added a setting to skip adding lines that start with `history`. + - Removed `esc_clears_line` setting. + - Pasting CRLFs doesn't really make sense. + - Don't write out settings that are set to default. +- Make sure Ctrl-C doesn't modify history. +- Make a cached copy of Clink's DLL when injecting so as to not lock the master. +- Guard against Readline's writes to stderr. +- Remove `clink_inputrc_base` file and embed its content (fixes [mridgers #257](https://github.com/mridgers/clink/issues/257)). +- Include more metadata in the Clink's executables. + +### v0.4.9 - Fixed broken Doskey on Win10 (#438, #451) -##### v0.4.8 +### v0.4.8 -- Environment variable 'clink_profile' overrides Clink's profile path (#390). +- Environment variable `clink_profile` overrides Clink's profile path (#390). - Load a clink_inputrc file from Clink's profile directory (fixes #406). - Bug fixes; - Redraw issues when prompts end in OSC ANSI codes (#387, #384). - - Fixed 'clink autorun --help' crash. + - Fixed `clink autorun --help` crash. -##### v0.4.7 +### v0.4.7 - Bug fixes; - Sometimes autorun tries to run clink.exe (#374). - Autorun would cause cmd.exe to return an error if it wasn't interactive (#373). -##### v0.4.6 +### v0.4.6 - HOME is only set if it is currently unset. - Readline can be initialised with .inputrc and _inputrc files too (#258). - Bug fixes; - Executable completion; - Paths from PATH were checked twice. - - Incorrect results were returned for words ending in '.' or '-'. + - Incorrect results were returned for words ending in `.` or `-`. - Directories . and .. were incorrectly displayed. - Fixed a crash if .bat script's stdout is redirected (#366). - Occasional crash when injecting Clink (#351). @@ -35,26 +700,26 @@ - Double display of multi-line prompts when resizing the terminal (#352). - Very rare wrap artefacts when making the terminal window larger. - Doskey emulation (#344). - - Improved 'clink autorun' help (#348). + - Improved `clink autorun` help (#348). - Fixed launching Clink when clink.bat is renamed (#357). -##### v0.4.5 +### v0.4.5 -- Improved 'clink autorun'. It now defaults to the Current User registry hive. -- 'clink set' gives more details for enumeration-type settings. +- Improved `clink autorun`. It now defaults to the Current User registry hive. +- `clink set` gives more details for enumeration-type settings. - Tab completion for p4vc. -- New settings 'history_expand_mode' to control history expansion in quotes (#317). +- New settings `history_expand_mode` to control history expansion in quotes (#317). - Bug fixes; - Use full width of the terminal (#337). - Fixed MinGW compile error (#335). - Autorun now defaults to the current user's hive (#332). - Creating clink.html no longer needs Pandoc, plus it looks a bit better (#331). - Added settings to control history expansion (#326). - - Correct fallback when 'use_altgr_substitute' is off (#325). + - Correct fallback when `use_altgr_substitute` is off (#325). - Load history prior to saving it on shutdown (#318). - Added Shift-Tab documentation and menu completion example (#190). - Added shim for backwards menu completion (#190). - - Input handling now outputs '\e`Z' for Shift-Tab (#190). + - Input handling now outputs \e`Z for Shift-Tab (#190). - Updated Readme with current Premake info (#310). - Guard against there being no buffer to read from (#304). - Fixed artefacts when resizing conhost's buffer (#139). @@ -63,36 +728,36 @@ - Fixed leaking exception filters. - Clearing the screen doesn't leave artefacts behind. -##### v0.4.4 +### v0.4.4 - Completing .. behaves more like Bash (#277). -- Escape from yes/no question when Ctrl+C is pressed. +- Escape from yes/no question when Ctrl+C is pressed. - Valid XP executables (#278, #289). - Fixed n-th argument yank not working as expected (#254). - Fixed prompt colours sometimes not working (#279, #286). -- Fixed '!0' causing Clink to crash. +- Fixed `!0` causing Clink to crash. - Save/restore cursor position in case Readline moves it. -##### v0.4.3 +### v0.4.3 -- Localised Y/N when auto-answering 'terminate?' prompt. -- $* would early out if there was no arguments. +- Localised Y/N when auto-answering "terminate?" prompt. +- `$*` would early out if there was no arguments. - Disable ANSI code support if third party provides it. - Installer can now set %CLINK_DIR% to install location. -- Improved output from 'clink set'. +- Improved output from `clink set`. - Support for Windows 10 Technical Preview. -- Ctrl-L now scrolls last line to the top of the window rather than clearing. +- Ctrl-L now scrolls last line to the top of the window rather than clearing. - New option to control how newline characters are pasted to the line. - New options to control history; - - 'history_file_lines' - maximum lines saved to disk. - - 'history_ignore_space' - ignore lines prefixed with whitespace. - - 'history_dupe_mode' - how duplicate entries are handled. - - 'history_io' - load/save history from disk every line. + - `history_file_lines` - maximum lines saved to disk. + - `history_ignore_space` - ignore lines prefixed with whitespace. + - `history_dupe_mode` - how duplicate entries are handled. + - `history_io` - load/save history from disk every line. - Fixed nonfunctional numpad keys. - Fixed missing WINCH signals if other processes resize the buffer. -- Support Alt codes sent from Conhost. +- Support Alt codes sent from Conhost. -##### v0.4.2 +### v0.4.2 - Prompt colouring no longer requires third party ANSI code utility. - Override settings with environment variables prefixed with 'clink'. @@ -100,44 +765,44 @@ - Updated Go completions (by matrixik). - Arguments to clink.arg.new_parser() now initialise parser's flags/args (from vladimir-kotikov). - New clink.arg.add_flags() and clink.arg.add_arguments() functions. -- Removed footer and Alt-H tip for more succinct stdout output. +- Removed footer and Alt-H tip for more succinct stdout output. - Bug fixes; - Windows XP works again. - Fixed race condition in lua_execute(). -##### v0.4.1 +### v0.4.1 - Bug fixes; - Various Unicode fixes causing corrupt environment variables. - Fixed thread resume/suspend causing rare system-wide deadlock. - Fixed incorrect translation of suffixed slash when completing flags. -- Add --nolog argument to disable file logging. Fix #187 Fix #154 +- Add `--nolog` argument to disable file logging. Fix #187 Fix #154 - Added missing escape sequences from doskey emulation. - Reinstated unix-kill-line key binding. -- Mapped PgUp/Down to search history using line typed so far. +- Mapped PgUp/Down to search history using line typed so far. - Added documentation covering escape codes for special keys. -- Added support for Windows' AltGr substitute Ctrl-Alt. +- Added support for Windows' AltGr substitute Ctrl-Alt. - Support for Readline's 'menu' style completion (see docs). -##### v0.4 +### v0.4 - New features; - - Better 'clink.arg' API. Easier, more intuitive, and more powerful. + - Better `clink.arg` API. Easier, more intuitive, and more powerful. - Whitespace prefix skips exec matching. - - Added a 'set' verb to easily change settings from the command line. + - Added a `set` verb to easily change settings from the command line. - Basic support for a shells other than cmd.exe. - Completion for Go (contributed by Dobroslaw Zybort). - - Setting 'exec_match_style' to -1 disables it entirely. + - Setting `exec_match_style` to -1 disables it entirely. - Make history persistence optional. - Alias/doskey completion. - Very basic support for Powershell. - View cmd.exe's autorun entry without needing admin rights. - New key bindings; - - Ctrl-Alt-C : Copy command line to the clipboard. - - Ctrl-Alt-E : Expand environment variable under cursor. - - Ctrl-Alt-U : 'up directory' (formerly Shift-Up). - - Ctrl-U : Adds '..\' to the command line. - - Alt-H : Shows active keymap's key bindings. + - Ctrl-Alt-C : Copy command line to the clipboard. + - Ctrl-Alt-E : Expand environment variable under cursor. + - Ctrl-Alt-U : "up directory" (formerly Shift-Up). + - Ctrl-U : Adds `..\` to the command line. + - Alt-H : Shows active keymap's key bindings. - New Lua functions; - clink.execute(). - clink.get_host_process(). @@ -146,18 +811,18 @@ - clink.get_console_aliases(). - Lots of bug fixes, including; - Better command extraction. - - Fixed cmd.exe command paging and Ctrl-C/Ctrl-Break handling. + - Fixed cmd.exe command paging and Ctrl-C/Ctrl-Break handling. - Multiple locale fixes. - - Use localised text for 'Terminate batch job?' prompt. + - Use localised text for "Terminate batch job?" prompt. -##### v0.3 +### v0.3 -- Automatic answering of cmd.exe's 'Terminate batch script?' prompt. +- Automatic answering of cmd.exe's "Terminate batch script?" prompt. - Coloured prompts (requires ANSICON or ConEmu). -- Added Shift-Up keyboard shortcut to automatically execute 'cd ..' -- Mapped Ctrl-Z to undo, Microsoft style. +- Added Shift-Up keyboard shortcut to automatically execute `cd ..` +- Mapped Ctrl-Z to undo, Microsoft style. - Improved integration of Readline; - - New input handling code (Ctrl-Alt combos now work). + - New input handling code (Ctrl-Alt combos now work). - An implementation of the Termcap library. - Fully functional Vi-mode support. - Support for resizable consoles. @@ -175,31 +840,31 @@ - clink.get_cwd(). - Functions to query Clink's settings. - New command line options; - - '--profile ' to override default profile directory. - - '--nohostcheck' disables verification that host is cmd.exe. - - '--pid' specifies the process to inject into. + - --profile dir to override default profile directory. + - `--nohostcheck` disables verification that host is cmd.exe. + - `--pid` specifies the process to inject into. - Update Mercurial completion (issue 73). - Start menu shortcut starts in USERPROFILE, like cmd.exe - Zip distribution is now portable. -##### v0.2.1 +### v0.2.1 - The .history file now merges multiple sessions together. - Fixed missing y/n, pause, and other prompts. - Fixed segfault in loader executable. - Better ConEmu compatibility. -##### v0.2 +### v0.2 -- Basic argument completion for 'git', 'hg', 'svn', and 'p4'. -- Traditional Bash clear screen ('Ctrl-L') and exit shortcuts ('Ctrl-D'). -- Scrollable command window using 'PgUp'/'PgDown' keys. +- Basic argument completion for `git`, `hg`, `svn`, and `p4`. +- Traditional Bash clear screen (Ctrl-L) and exit shortcuts (Ctrl-D). +- Scrollable command window using PgUp/PgDown keys. - Doskey support. - Automatic quoting of file names with spaces. - Scriptable custom prompts. - New argument framework to ease writing context-sensitive match generators. - History and log file is now saved per-user rather than globally. -- Improved Clink's command line interface ('clink --help'). +- Improved Clink's command line interface (`clink --help`). - More reliable handling of cmd.exe's autorun entry. - General improvements to executable and directory-command completion. - Symbolic link support. @@ -208,12 +873,16 @@ - Improved hooking so Clink can be shared with other thirdparty utilities that also hook cmd.exe (ConEmu, ANSICon, etc.). -##### v0.1.1 +### v0.1.1 -- Fixed AltGr+ on international keyboards. -- Fixed broken completion when directories have a '-' in their name (Mark Hammond) +- Fixed AltGr+<key> on international keyboards. +- Fixed broken completion when directories have a `-` in their name (Mark Hammond) - The check for single match scenarios now correctly handles case-insensitivity. -##### v0.1 +### v0.1 - Initial release. + + + diff --git a/extras/clink/clink.bat b/extras/clink/clink.bat index 0c73ec282696a3e820e6b2311e01f451d69f4cfd..76d589ff836f6f935d3fdfdf02132d5480ee4551 100644 --- a/extras/clink/clink.bat +++ b/extras/clink/clink.bat @@ -1,24 +1,9 @@ :: Copyright (c) 2012 Martin Ridgers -:: -:: 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. +:: License: http://opensource.org/licenses/MIT @echo off +set clink_profile_arg= +set clink_quiet_arg= :: Mimic cmd.exe's behaviour when starting from the start menu. if /i "%1"=="startmenu" ( @@ -33,6 +18,12 @@ if /i "%1"=="--profile" ( shift /1 ) +:: Check for the --quiet option. +if /i "%1"=="--quiet" ( + set clink_quiet_arg= --quiet + shift /1 +) + :: If the .bat is run without any arguments, then start a cmd.exe instance. if "%1"=="" ( call :launch @@ -52,9 +43,10 @@ if /i "%processor_architecture%"=="x86" ( :end set clink_profile_arg= +set clink_quiet_arg= goto :eof :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :launch -start "Clink" cmd.exe /s /k ""%~dpnx0" inject %clink_profile_arg%" +start "Clink" cmd.exe /s /k ""%~dpnx0" inject %clink_profile_arg%%clink_quiet_arg%" exit /b 0 diff --git a/extras/clink/clink.html b/extras/clink/clink.html index 80cfe4b24e18708e68af24ba66dc00c4809212f3..d2067d5e04fbc563106745551a0de089bda70082 100644 --- a/extras/clink/clink.html +++ b/extras/clink/clink.html @@ -3,26 +3,139 @@ +Clink v1.2.9 - -
-
- -### What is Clink? - -Clink combines the native Windows shell cmd.exe with the powerful command line editing features of the GNU Readline library, which provides rich completion, history, and line-editing capabilities. Readline is best known for its use in the famous Unix shell Bash, the standard shell for Mac OS X and many Linux distributions. - -### Features - -- The same line editing as Bash (from GNU's Readline library). -- History persistence between sessions. -- Context sensitive completion; - - Executables (and aliases). - - Directory commands. - - Environment variables - - Thirdparty tools; Git, Mercurial, SVN, Go, and P4. -- New keyboard shortcuts; - - Paste from clipboard (**Ctrl-V**). - - Incremental history search (**Ctrl-R/Ctrl-S**). - - Powerful completion (**TAB**). - - Undo (**Ctrl-Z**). - - Automatic "cd .." (**Ctrl-Alt-U**). - - Environment variable expansion (**Ctrl-Alt-E**). - - (press **Alt-H** for many more...) -- Scriptable completion with Lua. -- Coloured and scriptable prompt. -- Auto-answering of the "Terminate batch job?" prompt. - -By default Clink binds **Alt-H** to display the current key bindings. More features can also be found in GNU's [Readline](http://tinyurl.com/oum26rp) and [History](http://tinyurl.com/p92oq5d) libraries' manuals. - -### Usage - -There are three ways to use Clink the first of which is to add Clink to cmd.exe's autorun registry entry. This can be selected when installing Clink using the installer and Clink also provides the ability to manage this autorun entry from the command line. Running **clink autorun --help** has more information. - -The second alternative is to manually run Clink using the command **clink inject** from within a command prompt session to run Clink in that session. - -The last option is to use the Clink shortcut that the installer adds to Windows' start menu. This is in essence a shortcut to the command **cmd.exe /k clink inject**. - -### How Clink Works - -When running Clink via the methods above, Clink checks the parent process is supported and injects a DLL into it. The DLL then hooks the WriteConsole() and ReadConsole() Windows functions. The former is so that Clink can capture the current prompt, and the latter hook allows Clink to provide it's own Readline-powered command line editing. - -### Configuring Clink - -The easiest way to configure Clink is to use Clink's **set** command line option. This can list, query, and set Clink's settings. Run **clink set --help** from a Clink-installed cmd.exe process to learn more both about how to use it and to get descriptions for Clink's various options. - -Settings that are loaded when Clink starts can be overridden by setting environment variables matching the setting name and prefixed with "clink.". For example, the command **set clink.prompt_colour=10** will turn the prompt green regardless of what is in the settings file. Overrides are not saved to disk. - -The following table describes the available settings; - -Name | Description -:--: | ----------- -**ansi_code_support** | When printing the prompt, Clink has basic built-in support for SGR ANSI escape codes to control the text colours. This is automatically disabled if a third party tool is detected that also provides this facility. It can also be disabled by setting this to 0. -**ctrld_exits** | Ctrl-D exits the process when it is pressed on an empty line. -**esc_clears_line** | Clink clears the current line when Esc is pressed (unless Readline's Vi mode is enabled). -**exec_match_style** | Changes how Clink will match executables when there is no path separator on the line. 0 = PATH only, 1 = PATH and CWD, 2 = PATH, CWD, and directories. In all cases both executables and directories are matched when there is a path separator present. -**history_dupe_mode** | If a line is a duplicate of an existing history entry Clink will erase the duplicate when this is set 2. A value of 1 will not add duplicates to the history and a value of 0 will always add lines. -**history_expand_mode** | The '!' character in an entered line can be interpreted to introduce words from the history. This can be enabled and disable by setting this value to 1 or 0. Values or 2, 3 or 4 will skip any ! character quoted in single, double, or both quotes respectively. -**history_file_lines** | When set to a positive integer this is the number of lines of history that will persist when Clink saves the command history to disk. Use 0 for infinite lines and <0 to disable history persistence. -**history_ignore_space** | Ignore lines that begin with whitespace when adding lines in to the history. -**history_io** | Use this setting to control when the history is written to disk and when it is read back. A value of 1 will read the history before editing of a new line commences, 2 will write the history, and 3 will do both. The default (0) is to write the history when the process exits.", -**match_colour** | Colour to use when displaying matches. A value less than 0 will be the opposite brightness of the default colour. -**prompt_colour** | Surrounds the prompt in ANSI escape codes to set the prompt's colour (0..15). Disabled when the value is less than 0. -**space_prefix_match_files** | If the line begins with whitespace then Clink bypasses executable matching and will match all files and directories instead. -**terminate_autoanswer** | Automatically answers cmd.exe's **Terminate batch job (Y/N)?** prompts. 0 = disabled, 1 = answer Y, 2 = answer N. -**use_altgr_substitute** | Windows provides Ctrl-Alt as a substitute for AltGr, historically to support keyboards with no AltGr key. This may collide with some of Readline's bindings. - -#### File Locations - -Settings and history are persisted to disk from session to session. The location of these files depends on which distribution of Clink was used. If you installed Clink using the .exe installer then Clink uses the current user's non-roaming application data directory. This user directory is usually found in one of the following locations; - -- c:\Documents and Settings\\<username>\Local Settings\Application Data *(XP)* -- c:\Users\\<username>\AppData\Local *(Vista onwards)* - -The .zip distribution of Clink creates and uses a directory called **profile** which is located in the same directory where Clink's core files are found. - -All of the above locations can be overridden using the **--profile <path>** command line option which is specified when injecting Clink into cmd.exe using **clink inject**. - -### Configuring Readline - -Readline itself can also be configured to add custom keybindings and macros by creating a Readline init file. There is excellent documentation for all the options available to configure Readline in Readline's [manual](http://tinyurl.com/oum26rp). - -Clink will search in the directory as specified by the HOME environment variable for one or all of the following files; `clink_inputrc`, `_inputrc`, and `.inputrc`. If HOME is unset then Clink will use either of the standard Windows environment variables `%homedrive%\%homepath%` or `%userprofile%`. - -Other software that also uses Readline will also look for the `.inputrc` file (and possibly the `_inputrc` file too). To set macros and keybindings intended only for Clink one can use the Readline init file conditional construct like this; `$if cmd.exe [...] $endif`. - -Editing the `clink_inputrc_base` is discouraged as this will change from version to version and may not be present in the future. - -### Extending Clink - -The Readline library allows clients to offer an alternative path for creating completion matches. Clink uses this to hook Lua into the completion process making it possible to script the generation of matches with Lua scripts. The following sections describe this in more detail and shows some examples. - -#### The Location of Lua Scripts - -Clink looks for Lua scripts in the folders as described in the **Configuring Clink** section. By default **Ctrl-Q** is mapped to reload all Lua scripts which can be useful when developing and iterating on your own scripts. - -#### Match Generators - -These are Lua functions that are registered with Clink and are called as part of Readline's completion process. Match generator functions take the following form; - -``` -function my_match_generator(text, first, last) - -- Use text/rl_state.line_buffer to create matches, - -- Submit matches to Clink using clink.add_match() - -- Return true/false. + + + +
+
+
+ +
+
+
+

What is Clink?

+

Clink combines the native Windows shell cmd.exe with the powerful command line editing features of the GNU Readline library, which provides rich completion, history, and line-editing capabilities. Readline is best known for its use in the well-known Unix shell Bash, the standard shell for Mac OS X and many Linux distributions.

+

Features

+
    +
  • The same line editing as Bash (from the GNU Readline library version 8.1).
  • +
  • History persistence between sessions.
  • +
  • Context sensitive completion;
      +
    • Executables (and aliases).
    • +
    • Directory commands.
    • +
    • Environment variables.
    • +
    +
  • +
  • Context sensitive colored input text.
  • +
  • New keyboard shortcuts;
      +
    • Paste from clipboard (Ctrl+V).
    • +
    • Incremental history search (Ctrl+R and Ctrl+S).
    • +
    • Powerful completion (Tab).
    • +
    • Undo (Ctrl+Z).
    • +
    • Automatic cd .. (Ctrl+Alt+U).
    • +
    • Environment variable expansion (Ctrl+Alt+E).
    • +
    • Doskey alias expansion (Ctrl+Alt+F).
    • +
    • Scroll the screen buffer (Alt+Up, etc).
    • +
    • Shift+Arrow keys to select text, typing replaces selected text, etc.
    • +
    • (press Alt+H for many more...)
    • +
    +
  • +
  • Directory shortcuts;
      +
    • Typing a directory name followed by a path separator is a shortcut for cd /d to that directory.
    • +
    • Typing .. or ... is a shortcut for cd .. or cd ..\.. (each additional . adds another \..).
    • +
    • Typing - or cd - changes to the previous current working directory.
    • +
    +
  • +
  • Scriptable completion with Lua.
  • +
  • Scriptable key bindings with Lua.
  • +
  • Colored and scriptable prompt.
  • +
  • Auto-answering of the "Terminate batch job?" prompt.
  • +
+

By default Clink binds Alt+H to display the current key bindings. More features can also be found in GNU's Readline and History libraries' manuals.

+
+

+Want some quick but powerful tips to get started? +

+

+ + + + + + + + + +
Ctrl+OThis is operate-and-get-next, which accepts the current input line and gets the next history line. You can search history for a command, then press Ctrl+O to run that command and queue up the next command after it. Repeat it to conveniently rerun a series of commands from the history.
Alt+.This is yank-last-arg, which inserts the last argument from the previous line. You can use it repeatedly to cycle backwards through the history, inserting the last argument from each line. Learn more by reading up on the "yank" features in the Readline manual.
Ctrl+RThis is reverse-search-history, which incrementally searches the history. Press it, then type, and it does a reverse incremental search while you type. Press Ctrl+R again (and again, etc) to search for other matches of the search text. Learn more by reading up on the "search" and "history" features in the Readline manual.
Ctrl+Alt+DThis is remove-history, which deletes the currently selected history line after using any of the history search or navigation commands.
Ctrl+Alt+KThis is add-history, which adds the current line to the history without executing it, and then clears the input line.
Ctrl+Alt+NThis is clink-menu-complete-numbers, which grabs numbers with 3 or more digits from the current console screen and cycles through inserting them as completions (binary, octal, decimal, hexadecimal). Super handy for quickly inserting a commit hash that was printed as output from a preceding command.
Alt+0 to Alt+9These are digit-argument, which let you enter a numeric value used by many commands. For example Ctrl+Alt+W copies the current word to the clipboard, but if you first type Alt+2 followed by Ctrl+Alt+W then it copies the 3rd word to the clipboard (the first word is 0, the second is 1, etc). Learn more by reading up on "Readline Arguments" in the Readline manual.
Alt+HThis is clink-show-help, which lists the key bindings and commands. Learn more by visiting Key Bindings.
+

+
+ +

Usage

+

There are several ways to start Clink.

+
    +
  1. If you installed the auto-run, just start cmd.exe. Run clink autorun --help for more info.
  2. +
  3. To manually start, run the Clink shortcut from the Start menu (or the clink.bat located in the install directory).
  4. +
  5. To establish Clink to an existing cmd.exe process, use <install_dir>\clink.exe inject.
  6. +
+

Upgrading from Clink v0.4.9

+

The new Clink tries to be as backward compatible with Clink v0.4.9 as possible. However, in some cases upgrading may require a little bit of configuration work.

+
    +
  • Some key binding sequences have changed; see Key Bindings for more information.
  • +
  • Match coloring is now done by Readline and is configured differently; see Completion Colors for more information.
  • +
  • Settings and history should migrate automatically if the new clink_settings and clink_history files don't exist (deleting them will cause migration to happen again). To find the directory that contains these files, run clink info and look for the "state" line.
  • +
  • Script compatibility should be very good, but some scripts may still encounter problems. If you do encounter a compatibility problem you can look for an updated version of the script, update the script yourself, or visit the repo and open an issue describing details about the compatibility problem.
  • +
  • Some settings have changed slightly, and there are many new settings. See Configuring Clink for more information.
  • +
+

How Clink Works

+

When running Clink via the methods above, Clink checks the parent process is supported and injects a DLL into it. The DLL then hooks the WriteConsole() and ReadConsole() Windows functions. The former is so that Clink can capture the current prompt, and the latter hook allows Clink to provide its own Readline-powered command line editing.

+ + +

Privacy

+

Clink does not collect user data. Clink writes diagnostic information to its local log file, and does not transmit the log file off the local computer. For the location of the log file, refer to File Locations or run clink info.

+ + +

Configuring Clink

+

The easiest way to configure Clink is to use Clink's set command line option. This can list, query, and set Clink's settings. Run clink set --help from a Clink-installed cmd.exe process to learn more both about how to use it and to get descriptions for Clink's various options.

+

The following table describes the available Clink settings:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDefaultDescription
clink.colorize_inputTrueEnables context sensitive coloring for the input text (see Coloring The Input Text).
clink.paste_crlfcrlfWhat to do with CR and LF characters on paste. Setting this to delete deletes them, space replaces them with spaces, ampersand replaces them with ampersands, and crlf pastes them as-is (executing commands that end with a newline).
clink.pathA list of paths to load Lua scripts. Multiple paths can be delimited semicolons.
clink.promptfilterTrueEnable prompt filtering by Lua scripts.
cmd.auto_answeroffAutomatically answers cmd.exe's "Terminate batch job (Y/N)?" prompts. off = disabled, answer_yes = answer Y, answer_no = answer N.
cmd.ctrld_exitsTrueCtrl+D exits the process when it is pressed on an empty line.
color.argThe color for arguments in the input line when clink.colorize_input is enabled.
color.argmatcherThe color for the command name in the input line when clink.colorize_input is enabled, if the command name has an argmatcher available.
color.cmdboldUsed when Clink displays shell (CMD.EXE) command completions, and in the input line when clink.colorize_input is enabled.
color.doskeybright cyanUsed when Clink displays doskey alias completions, and in the input line when clink.colorize_input is enabled.
color.filteredboldThe default color for filtered completions (see Filtering the Match Display).
color.flagdefaultThe color for flags in the input line when clink.colorize_input is enabled.
color.hiddenUsed when Clink displays file completions with the "hidden" attribute.
color.horizscrollUsed when Clink displays the < or > horizontal scroll indicators when Readline's horizontal-scroll-mode variable is set.
color.inputUsed when Clink displays the input line text. Note that when clink.colorize_input is disabled, the entire input line is displayed using color.input.
color.interactboldUsed when Clink displays text or prompts such as a pager's --More?-- prompt.
color.messagedefaultThe color for the message area (e.g. the search prompt message, digit argument prompt message, etc).
color.modmarkUsed when Clink displays the * mark on modified history lines when Readline's mark-modified-lines variable and Clink's color.input setting are both set. Falls back to color.input if not set.
color.promptWhen set, this is used as the default color for the prompt. But it's overridden by any colors set by Customising The Prompt.
color.readonlyUsed when Clink displays file completions with the "readonly" attribute.
color.selectionThe color for selected text in the input line. If no color is set, then reverse video is used.
color.unexpecteddefaultThe color for unexpected arguments in the input line when clink.colorize_input is enabled.
debug.log_terminalFalseLogs all terminal input and output to the clink.log file. This is intended for diagnostic purposes only, and can make the log file grow significantly.
doskey.enhancedTrueEnhanced Doskey adds the expansion of macros that follow | and & command separators and respects quotes around words when parsing $1..$9 tags. Note that these features do not apply to Doskey use in Batch files.
exec.cwdTrueWhen matching executables as the first word (exec.enable), include executables in the current directory. (This is implicit if the word being completed is a relative path).
exec.dirsTrueWhen matching executables as the first word (exec.enable), also include directories relative to the current working directory as matches.
exec.enableTrueMatch executables when completing the first word of a line.
exec.pathTrueWhen matching executables as the first word (exec.enable), include executables found in the directories specified in the %PATH% environment variable.
exec.space_prefixTrueIf the line begins with whitespace then Clink bypasses executable matching (exec.path) and will do normal files matching instead.
files.hiddenTrueIncludes or excludes files with the "hidden" attribute set when generating file lists.
files.systemFalseIncludes or excludes files with the "system" attribute set when generating file lists.
history.dont_add_to_history_cmdsexit historyList of commands that aren't automatically added to the history. Commands are separated by spaces, commas, or semicolons. Default is exit history, to exclude both of those commands.
history.dupe_modeerase_prevIf a line is a duplicate of an existing history entry Clink will erase the duplicate when this is set to 'erase_prev'. Setting it to 'ignore' will not add duplicates to the history, and setting it to 'add' will always add lines (except when overridden by history.sticky_search).
history.expand_modenot_quotedThe ! character in an entered line can be interpreted to introduce words from the history. This can be enabled and disable by setting this value to on or off. Values of not_squoted, not_dquoted, or not_quoted will skip any ! character quoted in single, double, or both quotes respectively.
history.ignore_spaceTrueIgnore lines that begin with whitespace when adding lines in to the history.
history.max_lines2500The number of history lines to save if history.save is enabled (1 to 50000).
history.saveTrueSaves history between sessions. When disabled, history is neither read from nor written to a master history list; history for each session exists only in memory until the session ends.
history.sharedFalseWhen history is shared, all instances of Clink update the master history list after each command and reload the master history list on each prompt. When history is not shared, each instance updates the master history list on exit.
history.sticky_searchFalseWhen enabled, reusing a history line does not add the reused line to the end of the history, and it leaves the history search position on the reused line so next/prev history can continue from there (e.g. replaying commands via Up several times then Enter, Down, Enter, etc).
lua.break_on_errorFalseBreaks into Lua debugger on Lua errors.
lua.break_on_tracebackFalseBreaks into Lua debugger on traceback().
lua.debugFalseLoads a simple embedded command line debugger when enabled. Breakpoints can be added by calling pause().
lua.pathValue to append to package.path. Used to search for Lua scripts specified in require() statements.
lua.reload_scriptsFalseWhen false, Lua scripts are loaded once and are only reloaded if forced (see The Location of Lua Scripts for details). When true, Lua scripts are loaded each time the edit prompt is activated.
lua.strictTrueWhen enabled, argument errors cause Lua scripts to fail. This may expose bugs in some older scripts, causing them to fail where they used to succeed. In that case you can try turning this off, but please alert the script owner about the issue so they can fix the script.
lua.traceback_on_errorFalsePrints stack trace on Lua errors.
match.ignore_accentTrueControls accent sensitivity when completing matches. For example, ä and a are considered equivalent with this enabled.
match.ignore_caserelaxedControls case sensitivity when completing matches. off = case sensitive, on = case insensitive, relaxed = case insensitive plus - and _ are considered equal.
match.sort_dirswithHow to sort matching directory names. before = before files, with = with files, after = after files.
match.translate_slashessystemFile and directory completions can be translated to use consistent slashes. The default is system to use the appropriate path separator for the OS host (backslashes on Windows). Use slash to use forward slashes, or backslash to use backslashes. Use off to turn off translating slashes from custom match generators.
match.wildTrueMatches ? and * wildcards when using any of the menu-complete commands or the clink-popup-complete command. Turn this off to behave how bash does, and not match wildcards.
readline.hide_stderrFalseSuppresses stderr from the Readline library. Enable this if Readline error messages are getting in the way.
terminal.adjust_cursor_styleTrueWhen enabled, Clink adjusts the cursor shape and visibility to show Insert Mode, produce the visible bell effect, avoid disorienting cursor flicker, and to support ANSI escape codes that adjust the cursor shape and visibility. But it interferes with the Windows 10 Cursor Shape console setting. You can make the Cursor Shape setting work by disabling this Clink setting (and the features this provides).
terminal.differentiate_keysFalseWhen enabled, pressing Ctrl + H or I or M or [ generate special key sequences to enable binding them separately from Backspace or Tab or Enter or Esc.
terminal.emulationautoClink can either emulate a virtual terminal and handle ANSI escape codes itself, or let the console host natively handle ANSI escape codes. native = pass output directly to the console host process, emulate = clink handles ANSI escape codes itself, auto = emulate except when running in ConEmu, Windows Terminal, or Windows 10 new console.
terminal.use_altgr_substituteFalseSupport Windows' Ctrl-Alt substitute for AltGr. Turning this off may resolve collisions with Readline's key bindings.
+

+ +

+

Compatibility Notes:

+
+
+ + +

Color Settings

+

Friendly Color Names

+

The Clink color settings use the following syntax:

+

[attributes] [foreground_color] [on [background_color]]

+

Optional attributes (can be abbreviated to 3 letters):

+
    +
  • bold or nobold adds or removes boldface (usually represented by forcing the color to use high intensity if it doesn't already).
  • +
  • underline or nounderline adds or removes an underline.
  • +
+

Optional colors for foreground_color and background_color (can be abbreviated to 3 letters):

+
    +
  • default or normal uses the default color as defined by the current color theme in the console window.
  • +
  • black, red, green, yellow, blue, cyan, magenta, white are the basic colors names.
  • +
  • bright can be combined with any of the other color names to make them bright (high intensity).
  • +
+

Examples (specific results may depend on the console host program):

+
    +
  • bri yel for bright yellow foreground on default background color.
  • +
  • bold for bright default foreground on default background color.
  • +
  • underline bright black on white for dark gray (bright black) foreground on light gray (white) background.
  • +
  • default on blue for default foreground color on blue background.
  • +
+

Alternative SGR Syntax

+

It's also possible to set any ANSI SGR escape code using sgr SGR_parameters (for example sgr 7 is the code for reverse video, which swaps the foreground and background colors).

+

Be careful, since some escape code sequences might behave strangely.

+ + +

File Locations

+

Settings and history are persisted to disk from session to session. The location of these files depends on which distribution of Clink was used. If you installed Clink using the .exe installer then Clink uses the current user's non-roaming application data directory. This user directory is usually found in one of the following locations;

+
    +
  • Windows XP: c:\Documents and Settings\<username>\Local Settings\Application Data\clink
  • +
  • Windows Vista onwards: c:\Users\<username>\AppData\Local\clink
  • +
+

All of the above locations can be overridden using the --profile path command line option which is specified when injecting Clink into cmd.exe using clink inject. Or with the %CLINK_PROFILE% environment variable if it is already present when Clink is injected (this envvar takes precedence over any other mechanism of specifying a profile directory, if more than one was used).

+

You can use clink info to find the directories and configuration files for the current Clink session.

+

Command Line Options

+

+

clink
+
+Shows command line usage help.
+

+ +

+

clink inject
+
+Injects Clink into a CMD.EXE process.
+See clink inject --help for more information.
+

+ +

+

clink autorun
+
+Manages Clink's entry in CMD.EXE's autorun section, which can automatically inject Clink when starting CMD.EXE.
+When Clink is installed for autorun, the automatic inject can be overridden by setting the CLINK_NOAUTORUN environment variable (to any value).
+See clink autorun --help for more information.
+

+ +

+

clink set
+
+clink set by itself lists all settings and their values.
+clink set setting_name describes the setting shows its current value.
+clink set setting_name clear resets the setting to its default value.
+clink set setting_name value sets the setting to the specified value.
+

+ +

+

clink installscripts
+
+Adds a path to search for Lua scripts.
+The path is stored in the registry and applies to all installations of Clink, regardless where their config paths are, etc. This is intended to make it easy for package managers like Scoop to be able to install (and uninstall) scripts for use with Clink.
+See clink installscripts --help for more information.
+

+ +

+

clink uninstallscripts
+
+Removes a path added by `clink installscripts`.
+See clink uninstallscripts --help for more information.
+

+ +

+

clink history
+
+Lists the command history.
+See clink history --help for more information.
+Also, Clink automatically defines history as an alias for clink history.
+

+ +

+

clink info
+
+Prints information about Clink, including the version and various configuration directories and files.
+Or clink --version shows just the version number.
+

+ +

+

clink echo
+
+Echos key sequences to use in the .inputrc files for binding keys to Clink commands. Each key pressed prints the associated key sequence on a separate line, until Ctrl+C is pressed.
+

+ +

Portable Configuration

+

Sometimes it's useful to run Clink from a flash drive or from a network share, especially if you want to use Clink on someone else's computer.

+

Here's how you can set up a portable configuration for Clink:

+
    +
  1. Put your Lua scripts and other tools in the same directory as the Clink executable files. For example fzf.exe, z.cmd, oh-my-posh.exe, or etc can all go in the same directory on a flash drive or network share.
  2. +
  3. Make a batch file such as portable.bat that injects Clink using a specific profile directory.
      +
    • On a flash drive, you can have a portable profile in a subdirectory under the Clink directory.
    • +
    • On a network share, you'll want to copy some initial settings into a local profile directory (a profile directory on a network share will be slow).
    • +
    +
  4. +
  5. In any cmd.exe window on any computer, you can then run the portable.bat script to inject Clink and have all your favorite settings and key bindings work.
  6. +
+

Here are some sample scripts:

+

portable.bat (on a flash drive)

+

This sample script assumes the portable.bat script is in the Clink directory, and it uses a clink_portable profile directory under the Clink directory.

+
@echo off
+rem -- Do any other desired configuration here, such as loading a doskey macro file.
+call "%~dp0clink.bat" inject --profile "%~dp0clink_portable" %1 %2 %3 %4 %5 %6 %7 %8 %9
+
+

portable.bat (on a network share)

+

This sample script assumes the portable.bat script is in the Clink directory, and that there is a file portable_clink_settings with the settings you want to copy to the local profile directory.

+
@echo off
+if not exist "%TEMP%\clink_portable" md "%TEMP%\clink_portable" >nul
+if not exist "%TEMP%\clink_portable\clink_settings" copy "%~dp0portable_clink_settings" "%TEMP%\clink_portable\clink_settings" >nul
+rem -- Do any other desired configuration here, such as loading a doskey macro file.
+call "%~dp0clink.bat" inject --profile "%TEMP%\clink_portable" %1 %2 %3 %4 %5 %6 %7 %8 %9
+
+
+ +

Configuring Readline

+

Readline itself can also be configured to add custom keybindings and macros by creating a Readline init file. There is excellent documentation for all the options available to configure Readline in Readline's manual.

+

Clink searches in the directories referenced by the following environment variables and loads any .inputrc or _inputrc files present, in the order listed here:

+
    +
  • %CLINK_INPUTRC%
  • +
  • The Clink profile directory (see the "state" line from clink info).
  • +
  • %USERPROFILE%
  • +
  • %LOCALAPPDATA%
  • +
  • %APPDATA%
  • +
  • %HOME%
  • +
+

Configuration in files loaded earlier can be overridden by files loaded later.

+

Other software that also uses Readline will also look for the .inputrc file (and possibly the _inputrc file too). To set macros and keybindings intended only for Clink one can use the Readline init file conditional construct like this; $if clink [...] $endif.

+

You can use clink info to find the directories and configuration files for the current Clink session.

+
+

Compatibility Notes:

+
    +
  • The clink_inputrc_base file from v0.4.8 is no longer used.
  • +
  • For backward compatibility, clink_inputrc is also loaded from the above locations, but it has been deprecated and may be removed in the future.
  • +
+
+

Basic Format

+

The quick version is that mostly you'll use these kinds of lines:

+
    +
  • keyname: command
  • +
  • keyname: "literal text"
  • +
  • keyname: "luafunc:lua_function_name"
  • +
  • set varname value
  • +
+

If a Readline macro begins with "luafunc:" then Clink interprets it as a Lua key binding and will invoke the named Lua function. Function names can include periods (such as foo.bar) but cannot include any other punctuation. See Lua Key Bindings for more information.

+

Refer to the Readline manual for a more thorough explanation of the .inputrc file format, list of available commands, and list of configuration variables and their values.

+

See Key Bindings for more information about binding keys in Clink.

+

New Configuration Variables

+

Clink adds some new configuration variables to Readline, beyond what's described in the Readline manual:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDefaultDescription
completion-auto-query-itemsonAutomatically prompts before displaying completions if they need more than half a screen page.
history-point-at-end-of-anchored-searchoffPuts the cursor at the end of the line when using history-search-forward or history-search-backward.
menu-complete-wraparoundonThe menu-complete family of commands wraps around when reaching the end of the possible completions.
search-ignore-caseonControls whether the history search commands ignore case.
+

New Commands

+

Clink adds some new commands to Readline, beyond what's described in the Readline manual:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameDescription
add-historyAdds the current line to the history without executing it, and clears the editing line.
clink-complete-numbersLike complete, but for numbers from the console screen (3 digits or more, up to hexadecimal).
clink-copy-cwdCopy the current working directory to the clipboard.
clink-copy-lineCopy the current line to the clipboard.
clink-copy-wordCopy the word at the cursor to the clipboard, or copies the nth word if a numeric argument is provided via the digit-argument keys.
clink-ctrl-cDiscards the current line and starts a new one (like Ctrl+C in CMD.EXE).
clink-exitReplaces the current line with exit and executes it (exits the shell instance).
clink-expand-doskey-aliasExpand the doskey alias (if any) at the beginning of the line.
clink-expand-env-varsExpand the environment variable (e.g. %FOOBAR%) at the cursor.
clink-find-conhostActivates the "Find" dialog when running in a standard console window (hosted by the OS conhost). This is equivalent to picking "Find..." from the console window's system menu.
clink-insert-dot-dotInserts ..\ at the cursor.
clink-mark-conhostActivates the "Mark" mode when running in a standard console window (hosted by the OS conhost). This is equivalent to picking "Mark" from the console window's system menu.
clink-menu-complete-numbersLike menu-complete, but for numbers from the console screen (3 digits or more, up to hexadecimal).
clink-menu-complete-numbers-backwardLike menu-complete-backward, but for numbers from the console screen (3 digits or more, up to hexadecimal).
clink-old-menu-complete-numbersLike old-menu-complete, but for numbers from the console screen (3 digits or more, up to hexadecimal).
clink-old-menu-complete-numbers-backwardLike old-menu-complete-backward, but for numbers from the console screen (3 digits or more, up to hexadecimal).
clink-pastePaste the clipboard at the cursor.
clink-popup-completeShow a popup window that lists the available completions.
clink-popup-complete-numbersLike clink-popup-complete, but for numbers from the console screen (3 digits or more, up to hexadecimal).
clink-popup-directoriesShow a popup window of recent current working directories. In the popup, use Enter to cd /d to the highlighted directory. See below more about the popup window.
clink-popup-historyShow a popup window that lists the command history (if any text precedes the cursor then it uses an anchored search to filter the list). In the popup, use Enter to execute the highlighted command. See below for more about the popup window.
clink-reloadReloads the .inputrc file and the Lua scripts.
clink-reset-lineClears the current line.
clink-scroll-bottomScroll the console window to the bottom (the current input line).
clink-scroll-line-downScroll the console window down one line.
clink-scroll-line-upScroll the console window up one line.
clink-scroll-page-downScroll the console window down one page.
clink-scroll-page-upScroll the console window up one page.
clink-scroll-topScroll the console window to the top.
clink-show-helpLists the currently active key bindings using friendly key names.
clink-show-help-rawLists the currently active key bindings using raw key sequences.
clink-up-directoryChanges to the parent directory.
cua-backward-charExtends the selection and moves back a character.
cua-backward-wordExtends the selection and moves back a word.
cua-beg-of-lineExtends the selection and moves to the start of the current line.
cua-copyCopies the selection to the clipboard.
cua-cutCuts the selection to the clipboard.
cua-end-of-lineExtends the selection and moves to the end of the line.
cua-forward-charExtends the selection and moves forward a character.
cua-forward-wordExtends the selection and moves forward a word.
old-menu-complete-backwardLike old-menu-complete, but in reverse.
remove-historyWhile searching history, removes the current line from the history.
+ + +

Completion Colors

+

When colored-completion-prefix is configured to on, then the "so" color from %LS_COLORS% is used to color the common prefix when displaying possible completions. The default for "so" is magenta, but for example set LS_COLORS=so=90 sets the color to bright black (which shows up as a dark gray).

+

When colored-stats is configured to on, then the color definitions from %LS_COLORS% (using ANSI escape codes) are used to color file completions according to their file type or extension. Each definition is a either a two character type id or a file extension, followed by an equals sign and then the SGR parameters for an ANSI escape code. Multiple definitions are separated by colons. Also, since %LS_COLORS% doesn't cover readonly files, hidden files, doskey aliases, or shell commands the color.readonly, color.hidden, color.doskey, and color.cmd Clink settings exist to cover those.

+

Here is an example where %LS_COLORS% defines colors for various types.

+
    +
  • so= defines the color for the common prefix for possible completions.
  • +
  • fi= defines the color for normal files.
  • +
  • di= defines the color for directories.
  • +
  • ex= defines the color for executable files.
  • +
+
set LS_COLORS=so=90:fi=97:di=93:ex=92:*.pdf=30;105:*.md=4
+
+

Let's break that down:

+
    +
  • so=90 uses bright black (dark gray) for the common prefix for possible completions.
  • +
  • fi=97 uses bright white for files.
  • +
  • di=93 uses bright yellow for directories.
  • +
  • ex=92 uses bright green for executable files.
  • +
  • *.pdf=30;105 uses black on bright magenta for .pdf files.
  • +
  • *.md=4 uses underline for .md files.
  • +
+ +

The clink-popup-complete, clink-popup-directories, and clink-popup-history commands show a popup window that lists the available completions, directory history, or command history. Here's how it works:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
KeyDescription
EscapeCancels the popup.
EnterInserts the highlighted completion, changes to the highlighted directory, or executes the highlighted command.
Shift+EnterInserts the highlighted completion, inserts the highlighted directory, or jumps to the highlighted command history entry without executing it.
Ctrl+EnterSame as Shift+Enter.
TypingTyping does an incremental search.
F3Go to the next match.
Ctrl+LGo to the next match.
Shift+F3Go to the previous match.
Ctrl+Shift+LGo to the previous match.
+

Extending Clink

+

The Readline library allows clients to offer an alternative path for creating completion matches. Clink uses this to hook Lua into the completion process making it possible to script the generation of matches with Lua scripts. The following sections describe this in more detail and show some examples.

+ + +

The Location of Lua Scripts

+

Clink loads all Lua scripts it finds in these directories:

+
    +
  1. All directories listed in the clink.path setting, separated by semicolons.
  2. +
  3. If clink.path is not set, then the DLL directory and the profile directory are used (see File Locations for info about the profile directory).
  4. +
  5. All directories listed in the %CLINK_PATH% environment variable, separated by semicolons.
  6. +
  7. All directories registered by the clink installscripts command.
  8. +
+

Lua scripts are loaded once and are only reloaded if forced because the scripts locations change, the clink-reload command is invoked (Ctrl+X,Ctrl+R), or the lua.reload_scripts setting changes (or is True).

+

Run clink info to see the script paths for the current session.

+ + +

Match Generators

+

These are Lua functions that are called as part of Readline's completion process.

+

First create a match generator object:

+
local my_generator = clink.generator(priority)
+
+

The priority argument is a number that influences when the generator gets called, with lower numbers going before higher numbers.

+

The :generate() Function

+

Next define a match generator function on the object, taking the following form:

+
function my_generator:generate(line_state, match_builder)
+    -- Use the line_state object to examine the current line and create matches.
+    -- Submit matches to Clink using the match_builder object.
+    -- Return true or false.
+end
+
+

line_state is a line object that has information about the current line.

+

match_builder is a builder object to which matches can be added.

+

If no further match generators need to be called then the function should return true. Returning false or nil continues letting other match generators get called.

+

Here is an example script that supplies git branch names as matches for git checkout. It's based on git_branch_autocomplete.lua from collink.clink-git-extensions. The version here is updated for the new Clink Lua API, and for illustration purposes it's been simplified to not support git aliases.

+
local git_branch_autocomplete = clink.generator(1)
+
+local function string.starts(str, start)
+    return string.sub(str, 1, string.len(start)) == start
 end
-```
-
-**Text** is the word that is being completed, **first** and **last** and the indices into the complete line buffer for **text** (the full line buffer can be accessed using the variable **rl_state.line_buffer**). If no further match generators need to be called then the function should return true.
-
-Registering the match generation function is done as follows;
-
-```
-clink.register_match_generator(my_match_generator, sort_id)
-```
 
-The **sort_id** argument is used to sort the match generators such that generators with a lower sort ids are called first.
+local function is_checkout_ac(text)
+    if string.starts(text, "git checkout") then
+        return true
+    end
+    return false
+end
 
-Here is an simple example script that checks if **text** begins with a **%** character and then uses the remained of **text** to match the names of environment variables.
+local function get_branches()
+    -- Run git command to get branches.
+    local handle = io.popen("git branch -a 2>&1")
+    local result = handle:read("*a")
+    handle:close()
+    -- Parse the branches from the output.
+    local branches = {}
+    if string.starts(result, "fatal") == false then
+        for branch in string.gmatch(result, "  %S+") do
+            branch = string.gsub(branch, "  ", "")
+            if branch ~= "HEAD" then
+                table.insert(branches, branch)
+            end
+        end
+    end
+    return branches
+end
 
-```
-function env_vars_match_generator(text, first, last)
-    if not text:find("^%%") then
+function git_branch_autocomplete:generate(line_state, match_builder)
+    -- Check if it's a checkout command.
+    if not is_checkout_ac(line_state:getline()) then
+        return false
+    end
+    -- Get branches and add them (does nothing if not in a git repo).
+    local matchCount = 0
+    for _, branch in ipairs(get_branches()) do
+        match_builder:addmatch(branch)
+        matchCount = matchCount + 1
+    end
+    -- If we found branches, then stop other match generators.
+    return matchCount > 0
+end
+
+

The :getwordbreakinfo() Function

+

A generator can influence word breaking for the end word by defining a :getwordbreakinfo() function. The function takes a line_state line object that has information about the current line. If it returns nil or 0, the end word is truncated to 0 length. This is the normal behavior, which allows Clink to collect and cache all matches and then filter them based on typing. Or it can return two numbers: word break length and an optional end word length. The end word is split at the word break length: one word contains the first word break length characters from the end word (if 0 length then it's discarded), and the next word contains the rest of the end word truncated to the optional word length (0 if omitted).

+

For example, when the environment variable match generator sees the end word is abc%USER it returns 3,1 so that the last two words become "abc" and "%" so that its generator knows it can do environment variable matching. But when it sees abc%FOO%def it returns 8,0 so that the last two words become "abc%FOO%" and "" so that its generator won't do environment variable matching, and also so other generators can produce matches for what follows, since "%FOO%" is an already-completed environment variable and therefore should behave like a word break. In other words, it breaks the end word differently depending on whether the number of percent signs is odd or even, to account for environent variable syntax rules.

+

And when an argmatcher sees the end word begins with a flag character it returns 0,1 so the end word contains only the flag character in order to switch from argument matching to flag matching.

+
+

Note: The :getwordbreakinfo() function is called very often, so it needs to be very fast or it can cause responsiveness problems while typing.

+
+
local envvar_generator = clink.generator(10)
+
+function envvar_generator:generate(line_state, match_builder)
+    -- Does the word end with a percent sign?
+    local word = line_state:getendword()
+    if word:sub(-1) ~= "%" then
         return false
     end
 
-    text = clink.lower(text:sub(2))
-    local text_len = #text
-    for _, name in ipairs(clink.get_env_var_names()) do
-        if clink.lower(name:sub(1, text_len)) == text then
-            clink.add_match('%'..name..'%')
-        end
+    -- Add env vars as matches.
+    for _, i in ipairs(os.getenvnames()) do
+        match_builder:addmatch("%"..i.."%", "word")
     end
 
+    match_builder:setsuppressappend()   -- Don't append a space character.
+    match_builder:setsuppressquoting()  -- Don't quote envvars.
     return true
 end
 
-clink.register_match_generator(env_vars_match_generator, 10)
-```
-
-#### Argument Completion
-
-Clink provides a framework for writing complex argument match generators in Lua.  It works by creating a parser object that describes a command's arguments and flags and then registering the parser with Clink. When Clink detects the command is being entered on the current command line being edited, it uses the parser to generate matches.
-
-Here is an example of a simple parser for the command **foobar**;
-
-```
-my_parser = clink.arg.new_parser()
-my_parser:set_flags("-foo", "-bar")
-my_parser:set_arguments(
-    { "hello", "hi" },
-    { "world", "wombles" }
-)
-
-clink.arg.register_parser("foobar", my_parser)
-```
-
-This parser describes a command that has two positional arguments each with two potential options. It also has two flags which the parser considers to be position independent meaning that provided the word being completed starts with a certain prefix the parser with attempt to match the from the set of flags.
-
-On the command line completion would look something like this;
-
-```
-C:\>foobar hello -foo wo
-world   wombles
-C:\>foobar hello -foo wo_
-```
-
-As an alternative to calling **clink.arg.set_arguments()** and **clink.arg.set_flags()** you can instead provide the parser's flags and positional arguments as arguments to **clink.arg.new_parser()** as follows;
-
-```
-some_parser = clink.arg.new_parser(
-    { "arg1-1", "arg1-2" },
-    { "arg2-1", "arg2-2" },
-    "-flag1", "-flag2"
-)
-```
-
-##### More Advanced Stuff
-
-###### Linking Parsers
-
-There are often situations where the parsing of a command's arguments is dependent on the previous words (**git merge ...** compared to **git log ...** for example). For these scenarios Clink allows you to link parsers to arguments' words using Lua's concatenation operator. Parsers can also be concatenated with flags too.
-
-```
-a_parser = clink.arg.new_parser():set_arguments({"foo", "bar" })
-b_parser = clink.arg.new_parser():set_arguments({ "abc", "123" })
-c_parser = clink.arg.new_parser()
-c_parser:set_arguments(
-    { "foobar" .. b_parser },
-    { c_parser }
-)
-```
-
-With syntax from preceding section this converts into:
+function envvar_generator:getwordbreakinfo(line_state)
+    local word = line_state:getendword()
+    local in_out = false
+    local index = nil
+
+    -- Paired percent signs denote already-completed environment variables.
+    -- So use envvar completion for abc%foo%def%USER but not for abc%foo%USER.
+    for i = 1, #word do
+        if word:sub(i, i) == "%" then
+            in_out = not in_out
+            if in_out then
+                index = i - 1
+            else
+                index = i
+            end
+        end
+    end
 
-```
-parser = clink.arg.new_parser
-a_parser = parser({"foo", "bar" })
-c_parser = parser(
-    { "foobar" .. parser({ "abc", "123" }) },
-    { c_parser }
+    -- If there were any percent signs, return word break info to influence the
+    -- match generators.
+    if index then
+        return index, (in_out and 1) or 0
+    end
+end
+
+ + +

Argument Completion

+

Clink provides a framework for writing complex argument match generators in Lua. It works by creating a parser object that describes a command's arguments and flags and then registering the parser with Clink. When Clink detects the command is being entered on the current command line being edited, it uses the parser to generate matches.

+

Here is an example of a simple parser for the command foobar;

+
clink.argmatcher("foobar")
+:addflags("-foo", "-bar")
+:addarg(
+    { "hello", "hi" },      -- Completions for arg #1
+    { "world", "wombles" }  -- Completions for arg #2
 )
-```
-
-As the example above shows, it is also possible to use a parser without concatenating it to a word. When Clink follows a link to a parser it is permanent and it will not return to the previous parser.
-
-###### Functions As Argument Options
-
-Argument options are not limited solely to strings. Clink also accepts functions too so more context aware argument options can be used.
-
-```
-function rainbow_function(word)
-    return { "red", "white", "blue" }
+
+

This parser describes a command that has two positional arguments each with two potential options. It also has two flags which the parser considers to be position independent meaning that provided the word being completed starts with a certain prefix the parser with attempt to match the from the set of flags.

+

On the command line completion would look something like this:

+
C:>foobar hello -foo wo
+wombles  wonder   world
+C:>foobar hello -foo wo_
+
+ +

When displaying possible completions, flag matches are only shown if the flag character has been input (so command and Alt+= would list only non-flag matches, or command - and Alt+= would list only flag matches).

+

More Advanced Stuff

+

Linking Parsers

+

There are often situations where the parsing of a command's arguments is dependent on the previous words (git merge ... compared to git log ... for example). For these scenarios Clink allows you to link parsers to arguments' words using Lua's concatenation operator. Parsers can also be concatenated with flags too.

+
a_parser = clink.argmatcher():addarg({ "foo", "bar" })
+b_parser = clink.argmatcher():addarg({ "abc", "123" })
+c_parser = clink.argmatcher()
+c_parser:addarg({ "foobar" .. a_parser })   -- Arg #1 is "foobar", which has args "foo" or "bar".
+c_parser:addarg({ b_parser })               -- Arg #2 is "abc" or "123".
+
+

As the example above shows, it is also possible to use a parser without concatenating it to a word. When Clink follows a link to a parser it is permanent and it will not return to the previous parser.

+

Functions As Argument Options

+

Argument options are not limited solely to strings. Clink also accepts functions too so more context aware argument options can be used.

+
function rainbow_function(word)
+    return { "red", "white", "blue" }
 end
 
-the_parser = clink.arg.new_parser()
-the_parser:set_arguments(
-    { "zippy", "bungle", "george" },
-    { rainbow_function, "yellow", "green" }
+the_parser = clink.argmatcher()
+the_parser:addarg({ "zippy", "bungle", "george" })
+the_parser:addarg({ rainbow_function, "yellow", "green" })
+
+

The functions take a single argument which is a word from the command line being edited (or partial word if it is the one under the cursor). Functions should return a table of potential matches.

+

Some built-in matcher functions are available:

+ + + + + + + + + + + + + + + +
FunctionDescription
clink.dirmatchesGenerates directory matches.
clink.filematchesGenerates file matches.
+

Shorthand

+

It is also possible to omit the addarg and addflags function calls and use a more declarative shorthand form:

+
-- Shorthand form; requires tables.
+clink.argmatcher()
+    { "one", "won" }                -- Arg #1
+    { "two", "too" }                -- Arg #2
+    { "-a", "-b", "/?", "/h" }      -- Flags
+
+-- Normal form:
+clink.argmatcher()
+:addarg(
+    { "one", "won" }                -- Arg #1
+    { "two", "too" }                -- Arg #2
 )
-```
-
-The functions take a single argument which is a word from the command line being edited (or partial word if it is the one under the cursor). Functions should return a table of potential matches (or an empty table if it calls clink.add_match() directly itself).
-
-#### Filtering The Match Display
-
-In some instances it may be preferable to display potential matches in an alternative form than the generated matches passed to and used internally by Readline. This happens for example with Readline's standard file name matches, where the matches are the whole word being completed but only the last part of the path is shown (e.g. the match **foo/bar** is displayed as **bar**).
-
-To facilitate custom match generators that may wish to do this there is the **clink.match_display_filter** variable. This can be set to a function that will then be called before matches are to be displayed.
-
-```
-function my_display_filter(matches)
-    new_matches = {}
-
-    for _, m in ipairs(matches) do
-        local _, _, n = m:find("\\([^\\]+)$")
-        table.insert(new_matches, n)
+:addflags("-a", "-b", "/?", "/h")   -- Flags
+
+

With the shorthand form flags are implied rather than declared. When a shorthand table's first value is a string starting with - or / then the table is interpreted as flags. Note that it's still possible with shorthand form to mix flag prefixes, and even add additional flag prefixes, such as { '-a', '/b', '=c' }.

+
+ +

Filtering Match Completions

+

A match generator or luafunc: key binding can use clink.onfiltermatches() to register a function that will be called after matches are generated but before they are displayed or inserted.

+

The function receives a table argument containing the matches to be displayed, a string argument indicating the completion type, and a boolean argument indicating whether filename completion is desired. The table argument has a match string field and a type string field; these are the same as in builder:addmatch().

+

The possible completion types are:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeDescriptionExample
"?"List the possible completions.possible-completions or popup-complete
"*"Insert all of the possible completions.insert-completions
"\t"Do standard completion.complete
"!"Do standard completion, and list all possible completions if there is more than one.complete (when the show-all-if-ambiguous config variable is set)
"@"Do standard completion, and list all possible completions if there is more than one and partial completion is not possible.complete (when the show-all-if-unmodified config variable is set)
"%"Do menu completion (cycle through possible completions).menu-complete or old-menu-complete
+

The return value is a table with the input matches filtered as desired. The match filter function can remove matches, but cannot add matches (use a match generator instead). If only one match remains after filtering, then many commands will insert the match without displaying it. This makes it possible to spawn a process (such as fzf) to perform enhanced completion by interactively filtering the matches and keeping only one selected match.

+
settings.add("fzf.height", "40%", "Height to use for the --height flag")
+settings.add("fzf.exe_location", "", "Location of fzf.exe if not on the PATH")
+
+-- Build a command line to launch fzf.
+local function get_fzf()
+    local height = settings.get("fzf.height")
+    local command = settings.get("fzf.exe_location")
+    if not command or command == "" then
+        command = "fzf.exe"
+    else
+        command = os.getshortname(command)
     end
-
-    return new_matches
+    if height and height ~= "" then
+        command = command..' --height '..height
+    end
+    return command
 end
 
-function my_match_generator(text, first, last)
-    ...
+local fzf_complete_intercept = false
 
-    clink.match_display_filter = my_display_filter
-    return true
+-- Sample key binding in .inputrc:
+--      M-C-x: "luafunc:fzf_complete"
+function fzf_complete(rl_buffer)
+    fzf_complete_intercept = true
+    rl.invokecommand("complete")
+    if fzf_complete_intercept then
+        rl_buffer:ding()
+    end
+    fzf_complete_intercept = false
+    rl_buffer:refreshline()
 end
-```
-
-The function's single argument **matches** is a table containing what Clink is going to display. The return value is a table with the input matches filtered as required by the match generator. The value of **clink.match_display_filter** is reset every time match generation is invoked.
-
-#### Customising The Prompt
 
-Before Clink displays the prompt it filters the prompt through Lua so that the prompt can be customised. This happens each and every time that the prompt is shown which allows for context sensitive customisations (such as showing the current branch of a git repository for example).
-
-Writing a prompt filter is straight forward and best illustrated with an example that displays the current git branch when the current directory is a git repository.
-
-```
-function git_prompt_filter()
-    for line in io.popen("git branch 2>nul"):lines() do
-        local m = line:match("%* (.+)$")
-        if m then
-            clink.prompt.value = "["..m.."] "..clink.prompt.value
+local function filter_matches(matches, completion_type, filename_completion_desired)
+    if not fzf_complete_intercept then
+        return
+    end
+    -- Start fzf.
+    local r,w = io.popenrw(get_fzf()..' --layout=reverse-list')
+    if not r or not w then
+        return
+    end
+    -- Write matches to the write pipe.
+    for _,m in ipairs(matches) do
+        w:write(m.match.."\n")
+    end
+    w:close()
+    -- Read filtered matches.
+    local ret = {}
+    while (true) do
+        local line = r:read('*line')
+        if not line then
             break
         end
+        for _,m in ipairs(matches) do
+            if m.match == line then
+                table.insert(ret, m)
+            end
+        end
     end
+    r:close()
+    -- Yay, successful; clear it to not ding.
+    fzf_complete_intercept = false
+    return ret
+end
 
+local interceptor = clink.generator(0)
+function interceptor:generate(line_state, match_builder)
+    -- Only intercept when the specific command was used.
+    if fzf_complete_intercept then
+        clink.onfiltermatches(filter_matches)
+    end
     return false
 end
+
+ + +

Filtering The Match Display

+

In some instances it may be preferable to display potential matches in an alternative form than the generated matches passed to and used internally by Readline. For example, it might be desirable to display a * next to some matches, or to show additional information about each match. Filtering the match display only affects what is displayed; it doesn't affect completing matches.

+

A match generator can use clink.ondisplaymatches() to register a function that will be called before matches are displayed (this is reset every time match generation is invoked).

+

The function receives a table argument containing the matches to be displayed, and a boolean argument indicating whether they'll be displayed in a popup window. The table argument has a match string field and a type string field; these are the same as in builder:addmatch(). The return value is a table with the input matches filtered as required by the match generator. The returned table can also optionally include a display string field and a description string field. When present, display will be displayed as the match instead of the match field, and description will be displayed next to the match. Putting the description in a separate field enables Clink to align the descriptions in a column.

+
local function my_filter(matches, popup)
+    local new_matches = {}
+    for _,m in ipairs(matches) do
+        if m.match:find("[0-9]") then
+            -- Ignore matches with one or more digits.
+        else
+            -- Keep the match, and also add * prefix to directory matches.
+            if m.type:find("^dir") then
+                m.display = "*"..m.match
+            end
+            table.insert(new_matches, m)
+        end
+    end
+    return new_matches
+end
 
-clink.prompt.register_filter(git_prompt_filter, 50)
-```
-
-The filter function takes no arguments instead receiving and modifying the prompt through the **clink.prompt.value** variable. It returns true if the prompt filtering is finished, and false if it should continue on to the next registered filter.
-
-A filter function is registered into the filter chain by passing the function to **clink.prompt.register_filter()** along with a sort id which dictates the order in which filters are called. Lower sort ids are called first.
+function my_match_generator:generate(line_state, match_builder)
+    ...
+    clink.ondisplaymatches(my_filter)
+end
+
+

+ +

+

Compatibility Note: When a match display filter has been set, it changes how match generation behaves.

+
    +
  • When a match display filter is set, then match generation is also re-run whenever matches are displayed.
  • +
  • Normally match generation only happens at the start of a new word. The full set of potential matches is remembered and dynamically filtered based on further typing.
  • +
  • So if a match generator made contextual decisions during match generation (other than filtering) then it could potentially behave differently in Clink v1.x than it did in v0.x.
  • +
+
+ + +

Coloring The Input Text

+

When the clink.colorize_input setting is enabled, argmatcher automatically apply colors to the input text by parsing it.

+

It's possible for an argmatcher to provide a function to override how its arguments are colored. This function is called once for each of the argmatcher's arguments.

+

It's also possible to register a classifier function for the whole input line. This function is very similar to a match generator; classifier functions are called in priority order, and a classifier can choose to stop the classification process.

+

Setting a classifier function in an argmatcher

+

In cases where an argmatcher isn't able to color the input text in the desired manner, it's possible to supply a classifier function that overrides how the argmatcher colors the input text. An argmatcher's classifier function is called once for each word the argmatcher parses, but it can classify any words (not just the word it was called for). Each argmatcher can have its own classifier function, so when there are linked argmatchers more than one function may be invoked.

+

Words are colored by classifying the words, and each classification has an associated color. See word_classifications:classifyword() for the available classification codes.

+

The clink set command has different syntax depending on the setting type, so the argmatcher for clink needs help in order to get everything right. A custom generator function parses the input text to provide appropriate matches, and a custom classifier function applies appropriate coloring.

+
-- In this example, the argmatcher matches a directory as the first argument and
+-- a file as the second argument.  It uses a word classifier function to classify
+-- directories (words that end with a path separator) as "unexpected" in the
+-- second argument position.
+
+local function classify_handler(arg_index, word, word_index, line_state, classifications)
+    -- `arg_index` is the argument position in the argmatcher.
+    -- In this example only position 2 needs special treatent.
+    if arg_index ~= 2 then
+        return
+    end
 
-### Miscellaneous
+    -- `arg_index` is the argument position in the argmatcher.
+    -- `word_index` is the word position in the `line_state`.
+    -- Ex1: in `samp dir file` for the word `dir` the argument index is 1 and
+    -- the word index is 2.
+    -- Ex2: in `samp --help dir file` for the word `dir` the argument index is
+    -- still 1, but the word index is 3.
+
+    -- `word` is the word the classifier function was called for and `word_index`
+    -- is its position in the line.  Because `line_state` is also provided, the
+    -- function can examine any words in the input line.
+    if word:sub(-1) == "\\" then
+        -- The word appears to be a directory, but this example expects only
+        -- files in argument position 2.  Here the word gets classified as "n"
+        -- (unexpected) so it gets colored differently.
+        classifications:classifyword(word_index, "n")
+    end
+end
 
-#### Binding special keys
+local matcher = clink.argmatcher("samp")
+:addflags("--help")
+:addarg({ clink.dirmatches })
+:addarg({ clink.filematches })
+:setclassifier(classify_handler)
+
+

Setting a classifier function for the whole input line

+

In some cases it may be desireable to use a custom classifier to apply coloring in an input line.

+

First create a classifier object:

+
local my_classifier = clink.classifier(priority)
+
+

The priority argument is a number that influences when the classifier gets called, with lower numbers going before higher numbers.

+

Next define a classify function on the object, taking the following form:

+
function my_classifier:classify(commands)
+    -- commands is a table of { line_state, classifications } objects, one per
+    -- command in the input line.  For example, "echo hello & echo world" is two
+    -- commands:  "echo hello" and "echo world".
+end
+
+

commands is a table of tables, with the following scheme: +{ {line_state:line, classifications:word_classifications}, ... }.

+

If no further classifiers need to be called then the function should return true. Returning false or nil continues letting other classifiers get called.

+
-- In this example, a custom classifier applies colors to command separators and
+-- redirection symbols in the input line.
+local cmdsep_classifier = clink.classifier(50)
+function cmdsep_classifier:classify(commands)
+    -- The `classifications:classifyword()` method can only affect the words for
+    -- the corresponding command.  However, this example doesn't need to parse
+    -- words within commands, it just wants to parse the whole line.  And since
+    -- each command's `classifications:applycolor()` method can apply color
+    -- anywhere in the entire input line, this example can simply use the first
+    -- command's `classifications` object.
+    if commands[1] then
+        local line_state = commands[1].line_state
+        local classifications = commands[1].classifications
+        local line = line_state:getline()
+        local quote = false
+        local i = 1
+        while (i <= #line) do
+            local c = line:sub(i,i)
+            if c == '^' then
+                i = i + 1
+            elseif c == '"' then
+                quote = not quote
+            elseif quote then
+            elseif c == '&' or c == '|' then
+                classifications:applycolor(i, 1, "95")
+            elseif c == '>' or c == '<' then
+                classifications:applycolor(i, 1, "35")
+                if line:sub(i,i+1) == '>&' then
+                    i = i + 1
+                    classifications:applycolor(i, 1, "35")
+                end
+            end
+            i = i + 1
+        end
+    end
+end
+
+ + +

Customising The Prompt

+

Before Clink displays the prompt it filters the prompt through Lua so that the prompt can be customised. This happens each and every time that the prompt is shown which allows for context sensitive customisations (such as showing the current branch of a git repository).

+

Writing a prompt filter is straightforward:

+
    +
  1. Create a new prompt filter by calling clink.promptfilter() along with a priority id which dictates the order in which filters are called. Lower priority ids are called first.
  2. +
  3. Define a filter() function on the returned prompt filter.
  4. +
+

The filter function takes a string argument that contains the filtered prompt so far. If the filter function returns nil, it has no effect. If the filter function returns a string, that string is used as the new filtered prompt (and may be further modified by other prompt filters with higher priority ids). If the filter function returns a string and a boolean, then if the boolean is false the prompt filtering is done and no further filter functions are called.

+
local p = clink.promptfilter(30)
+function p:filter(prompt)
+    return "new prefix "..prompt.." new suffix" -- Add ,false to stop filtering.
+end
+
+

The following example illustrates setting the prompt, modifying the prompt, using ANSI escape code for colors, running a git command to find the current branch, and stopping any further processing.

+
local green  = "\x1b[92m"
+local yellow = "\x1b[93m"
+local cyan   = "\x1b[36m"
+local normal = "\x1b[m"
+
+-- A prompt filter that discards any prompt so far and sets the
+-- prompt to the current working directory.  An ANSI escape code
+-- colors it yellow.
+local cwd_prompt = clink.promptfilter(30)
+function cwd_prompt:filter(prompt)
+    return yellow..os.getcwd()..normal
+end
 
-Due to differences between Windows and Linux, escape codes for keys like PageUp/Down and the arrow keys are different in Clink. Escape codes take the format **\\e`?** where '?' is one of the characters from the following table;
+-- A prompt filter that inserts the date at the beginning of the
+-- the prompt.  An ANSI escape code colors the date green.
+local date_prompt = clink.promptfilter(40)
+function date_prompt:filter(prompt)
+    return green..os.date("%a %H:%M")..normal.." "..prompt
+end
 
-Key      | Normal | Shift | Ctrl  | Ctrl-Shift
-:-:      | :-:    | :-:   | :-:   | :-:
-Home     | G      | a     | w     | !
-Up       | H      | b     | T     | "
-PageUp   | I      | c     | U     | #
-Left     | K      | d     | s     | $
-Right    | M      | e     | t     | %
-End      | O      | f     | u     | &
-Down     | P      | g     | V     | '
-PageDown | Q      | h     | v     | (
-Insert   | R      | i     | W     | )
-Delete   | S      | j     | X     | \*
-Tab      | (n/a)  | Z     | (n/a) | (n/a)
+-- A prompt filter that may stop further prompt filtering.
+-- This is a silly example, but on Wednesdays, it stops the
+-- filtering, which in this example prevents git branch
+-- detection and the line feed and angle bracket.
+local wednesday_silliness = clink.promptfilter(45)
+function wednesday_silliness:filter(prompt)
+    if os.date("%a") == "Wed" then
+        -- The ,false stops any further filtering.
+        return prompt.." HAPPY HUMP DAY! ", false
+    end
+end
 
-Here is an example line from a clink_inputrc file that binds Shift-End to the Readline function **transpose-word** function;
+-- A prompt filter that appends the current git branch.
+local git_branch_prompt = clink.promptfilter(50)
+function git_branch_prompt:filter(prompt)
+    for line in io.popen("git branch 2>nul"):lines() do
+        local branch = line:match("%* (.+)$")
+        if branch then
+            return prompt.." "..cyan.."["..branch.."]"..normal
+        end
+    end
+end
 
-```
-"\e`f": transpose-word
-```
+-- A prompt filter that adds a line feed and angle bracket.
+local bracket_prompt = clink.promptfilter(150)
+function bracket_prompt:filter(prompt)
+    return prompt.."\n> "
+end
+
+

The resulting prompt will look like this:

+
Wed 12:54 c:\dir [master]
+> _
+
+ +

...except on Wednesdays, when it will look like this:

+
Wed 12:54 c:\dir HAPPY HUMP DAY! _
+
+ +

+ + + +

ANSI escape codes in the prompt string

+

Readline needs to be told which characters in the prompt are unprintable or invisible. To help with that, Clink automatically detects most standard ANSI escape codes (and most of ConEmu's non-standard escape codes) and the BEL character (^G, audible bell) and surrounds them with \001 (^A) and \002 (^B) characters. For any other unprintable characters, the \001 and \002 characters need to be added manually. Otherwise Readline misinterprets the length of the prompt and can display the prompt and input line incorrectly in some cases (especially if the input line wraps onto a second line).

+

Miscellaneous

+
+ +

Key bindings

+

Key bindings are defined in .inputrc files. See the Configuring Readline section for more information.

+

Here is the quick version:

+
    +
  • A key binding is name: function or name: "literal text".
  • +
  • Key names are like this:
      +
    • C-a and "\C-a" are both Ctrl+a.
    • +
    • M-a and "\M-a" are both Alt+a.
    • +
    • M-C-a and "\M-\C-a" are both Alt+Ctrl+a.
    • +
    • hello is just h; the ello is a syntax error and is silently discarded by Readline.
    • +
    • "hello" is the series of keys h,e,l,l,o.
    • +
    • Special keys like Up are represented by VT220 escape codes such as"\e[A" (see table below for more info).
    • +
    +
  • +
  • Key bindings can be either functions or macros (literal text):
      +
    • blah-blah binds to a function named "blah-blah".
    • +
    • "blah-blah" inserts the literal text "blah-blah".
    • +
    +
  • +
+

You can use clink info to find the directories and configuration files for the current Clink session.

+

Here is an example .inputrc file with the key bindings that I use myself:

+
$if clink           # begin clink-only section
+
+# The following key bindings are for emacs mode.
+set keymap emacs
+
+# Completion key bindings.
+"\t":               old-menu-complete               # Tab
+"\e[Z":             old-menu-complete-backward      # Shift+Tab
+"\e[27;5;9~":       clink-popup-complete            # Ctrl+Tab (ConEmu needs additional configuration to allow Ctrl+Tab)
+"\x1b[27;5;32~":    complete                        # Ctrl+Space
+
+# Some key bindings I got used to from 4Dos/4NT/Take Command.
+C-b:                                                # Ctrl+B (cleared because I redefined Ctrl+F)
+C-d:                remove-history                  # Ctrl+D (replaces `delete-char`)
+C-f:                clink-expand-doskey-alias       # Ctrl+F (replaces `forward-char`)
+C-k:                add-history                     # Ctrl+K (replaces `kill-line`)
+"\e[A":             history-search-backward         # Up (replaces `previous-history`)
+"\e[B":             history-search-forward          # Down (replaces `next-history`)
+"\e[5~":            clink-popup-history             # PgUp (replaces `history-search-backward`)
+"\e[6~":                                            # PgDn (cleared because I redefined PgUp)
+"\e[1;5F":          end-of-line                     # Ctrl+End (replaces `kill-line`)
+"\e[1;5H":          beginning-of-line               # Ctrl+Home (replaces `backward-kill-line`)
+
+# Some key bindings handy in default (conhost) console windows.
+M-b:                                                # Alt+B (cleared because I redefined Alt+F)
+M-f:                clink-find-conhost              # Alt+F for "Find..." from the console's system menu
+M-m:                clink-mark-conhost              # Alt+M for "Mark" from the console's system menu
+
+# Some key bindings for interrogating the Readline configuration.
+"\C-x\C-f":         dump-functions                  # Ctrl+X, Ctrl+F
+"\C-x\C-m":         dump-macros                     # Ctrl+X, Ctrl+M
+"\C-x\C-v":         dump-variables                  # Ctrl+X, Ctrl+V
+
+# Misc other key bindings.
+"\e[5;6~":          clink-popup-directories         # Ctrl+Shift+PgUp
+C-_:                kill-line                       # Ctrl+- (replaces `undo`)
+
+$endif              # end clink-only section
+
+ +

The clink-show-help command is bound to Alt+H and lists all currently active key bindings. The list displays "friendly" key names, and these names are generally not suitable for use in .inputrc files. For example "Up" is the friendly name for "\e[A", and "A-C-F2" is the friendly name for "\e\e[1;5Q". To see key sequence strings suitable for use in .inputrc files use clink echo or Alt+Shift+H.

+
+

Note: Third party console hosts such as ConEmu may have their own key bindings that supersede Clink. They usually have documentation for how to change or disable their key bindings to allow console programs to handle the keys instead.

+
+ +

Clink provides an easy way to find the key sequence for any key combination that Clink supports. Run clink echo and then press key combinations; the associated key binding sequence is printed to the console output and can be used for a key binding in the inputrc file.

+

A chord can be formed by concatenating multiple key binding sequences. For example, "\C-X" and "\e[H" can be concatenated to form "\C-X\e[H" representing the chord Ctrl+X,Home.

+

Binding special keys

+

Here is a table of the key binding sequences for the special keys. Clink primarily uses VT220 emulation for keyboard input, but also uses some Xterm extended key sequences.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NormalShiftCtrlCtrl+ShiftAltAlt+ShiftAlt+CtrlAlt+Ctrl+Shift
Up\e[A\e[1;2A\e[1;5A\e[1;6A\e[1;3A\e[1;4A\e[1;7A\e[1;8A
Down\e[B\e[1;2B\e[1;5B\e[1;6B\e[1;3B\e[1;4B\e[1;7B\e[1;8B
Left\e[D\e[1;2D\e[1;5D\e[1;6D\e[1;3D\e[1;4D\e[1;7D\e[1;8D
Right\e[C\e[1;2C\e[1;5C\e[1;6C\e[1;3C\e[1;4C\e[1;7C\e[1;8C
Insert\e[2~\e[2;2~\e[2;5~\e[2;6~\e[2;3~\e[2;4~\e[2;7~\e[2;8~
Delete\e[3~\e[3;2~\e[3;5~\e[3;6~\e[3;3~\e[3;4~\e[3;7~\e[3;8~
Home\e[H\e[1;2H\e[1;5H\e[1;6H\e[1;3H\e[1;4H\e[1;7H\e[1;8H
End\e[F\e[1;2F\e[1;5F\e[1;6F\e[1;3F\e[1;4F\e[1;7F\e[1;8F
PgUp\e[5~\e[5;2~\e[5;5~\e[5;6~\e[5;3~\e[5;4~\e[5;7~\e[5;8~
PgDn\e[6~\e[6;2~\e[6;5~\e[6;6~\e[6;3~\e[6;4~\e[6;7~\e[6;8~
Tab\t\e[Z\e[27;5;9~\e[27;6;9~----
SpaceSpace-\e[27;5;32~\e[27;6;32~--\e[27;7;32~\e[27;8;32~
Backspace^h\e[27;2;8~Rubout\e[27;6;8~\e^h\e[27;4;8~\eRubout\e[27;8;8~
Escape\e[27;27~-------
F1\eOP\e[1;2P\e[1;5P\e[1;6P\e\eOP\e\e[1;2P\e\e[1;5P\e\e[1;6P
F2\eOQ\e[1;2Q\e[1;5Q\e[1;6Q\e\eOQ\e\e[1;2Q\e\e[1;5Q\e\e[1;6Q
F3\eOR\e[1;2R\e[1;5R\e[1;6R\e\eOR\e\e[1;2R\e\e[1;5R\e\e[1;6R
F4\eOS\e[1;2S\e[1;5S\e[1;6S\e\eOS\e\e[1;2S\e\e[1;5S\e\e[1;6S
F5\e[15~\e[15;2~\e[15;5~\e[15;6~\e\e[15~\e\e[15;2~\e\e[15;5~\e\e[15;6~
F6\e[17~\e[17;2~\e[17;5~\e[17;6~\e\e[17~\e\e[17;2~\e\e[17;5~\e\e[17;6~
F7\e[18~\e[18;2~\e[18;5~\e[18;6~\e\e[18~\e\e[18;2~\e\e[18;5~\e\e[18;6~
F8\e[19~\e[19;2~\e[19;5~\e[19;6~\e\e[19~\e\e[19;2~\e\e[19;5~\e\e[19;6~
F9\e[20~\e[20;2~\e[20;5~\e[20;6~\e\e[20~\e\e[20;2~\e\e[20;5~\e\e[20;6~
F10\e[21~\e[21;2~\e[21;5~\e[21;6~\e\e[21~\e\e[21;2~\e\e[21;5~\e\e[21;6~
F11\e[23~\e[23;2~\e[23;5~\e[23;6~\e\e[23~\e\e[23;2~\e\e[23;5~\e\e[23;6~
F12\e[24~\e[24;2~\e[24;5~\e[24;6~\e\e[24~\e\e[24;2~\e\e[24;5~\e\e[24;6~
+

When the terminal.differentiate_keys setting is enabled then the following key bindings are also available:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CtrlCtrl+ShiftAltAlt+ShiftAlt+CtrlAlt+Ctrl+Shift
H\e[27;5;72~\e[27;6;72~\eh\eH\e[27;7;72~\e[27;8;72~
I\e[27;5;73~\e[27;6;73~\ei\eI\e[27;7;73~\e[27;8;73~
M\e[27;5;77~\e[27;6;77~\em\eM\e[27;7;77~\e[27;8;77~
[\e[27;5;219~\e[27;6;219~\e[27;3;219~\e[27;4;219~\e[27;7;219~\e[27;8;219~
+ + +

Lua Key Bindings

+

You can bind a key to a Lua function by binding it to a macro that begins with "luafunc:". Clink will invoke the named Lua function when the key binding is input. Function names can include periods (such as foo.bar) but cannot include any other punctuation.

+

The Lua function receives a rl_buffer argument that gives it access to the input buffer.

+

Lua functions can print output, but should first call rl_buffer:beginoutput so that the output doesn't overwrite the displayed input line.

+

Example of a Lua function key binding in a .inputrc file:

+
M-C-y:      "luafunc:insert_date"
+M-C-z:      "luafunc:print_date"
+
+ +

Example functions to go with that:

+
function insert_date(rl_buffer)
+    rl_buffer:insert(os.date("%x %X"))
+end
 
-#### Readline's menu-complete
+function print_date(rl_buffer)
+    rl_buffer:beginoutput()
+    print(os.date("%A %B %d, %Y   %I:%M %p"))
+end
+
+

Saved Command History

+

Clink has a list of commands from the current session, and it can be saved and loaded across sessions.

+

A line won't be added to history if either of the following are true:

+
    +
  • The first word in the line matches one of the words in the history.dont_add_to_history_cmds setting.
  • +
  • The line begins with a space character.
  • +
+

To prevent doskey alias expansion while still adding the line to history, you can start the line with a semicolon.

+ + + + + + + + + + + + + + + + + + + +
LineDescription
somecmdExpands doskey alias and adds to history.
 somecmdDoesn't expand doskey alias and doesn't add to history.
;somecmdDoesn't expand doskey alias but does add to history.
+

The master history file

+

When the history.saved setting is enabled, then the command history is loaded and saved as follows (or when the setting is disabled, then it isn't saved between sessions).

+

Every time a new input line starts, Clink reloads the master history list and prunes it not to exceed the history.max_lines setting.

+

For performance reasons, deleting a history line marks the line as deleted without rewriting the history file. When the number of deleted lines gets too large (exceeding the max lines or 200, whichever is larger) then the history file is compacted: the file is rewritten with the deleted lines removed.

+

You can force the history file to be compacted regardless of the number of deleted lines by running history compact.

+

Shared command history

+

When the history.shared setting is enabled, then all instances of Clink update the master history file and reload it every time a new input line starts. This gives the effect that all instances of Clink share the same history -- a command entered in one instance will appear in other instances' history the next time they start an input line.

+

When the setting is disabled, then each instance of Clink loads the master file but doesn't append its own history back to the master file until after it exits, giving the effect that once an instance starts its history is isolated from other instances' history.

+

Multiple master history files

+

Normally Clink saves a single saved master history list. All instances of Clink load and save the same master history list.

+

It's also possible to make one or more instances of Clink use a different saved master history list by setting the %CLINK_HISTORY_LABEL% environment variable. This can be up to 32 alphanumeric characters, and is appended to the master history file name. Changing the %CLINK_HISTORY_LABEL% environment variable takes effect at the next input line.

+

Sample Scripts

+

Here are a few samples of what can be done with Clink.

+ +

The clink-completions collection of scripts has a bunch of argument matchers and completion generators for things like git, mercurial, npm, and more.

+

cmder-powerline-prompt

+

The cmder-powerline-prompt collection of scripts provides a Powerline-like prompt for Clink. It's extensible so you can add your own segments, and some configuration of built-in segments is also available.

+

oh-my-posh

+

The oh-my-posh program can generate fancy prompts. Refer to its documentation for how to configure it.

+

Integrating oh-my-posh with Clink is easy: just save the following text to an oh-my-posh.lua file in your Clink scripts directory (run clink info to find that), and make sure the oh-my-posh.exe program is in a directory listed in the %PATH% environment variable. (Or edit the script below to provide a fully qualified path to the oh-my-posh.exe program.)

+
-- oh-my-posh.lua
+local ohmyposh_prompt = clink.promptfilter(1)
+function ohmyposh_prompt:filter(prompt)
+    prompt = io.popen("oh-my-posh.exe"):read("*a")
+    return prompt, false
+end
+
+

z.lua

+

The z.lua tool is a faster way to navigate directories, and it integrates with Clink.

+

Troubleshooting Tips

+

If something seems to malfunction, here are some things to try that often help track down what's going wrong:

+
    +
  • Check if anti-malware software blocked Clink from injecting. Consider adding an exclusion for Clink.
  • +
  • Check clink info. E.g. does the state dir look right, do the script paths look right, do the inputrc files look right?
  • +
  • Check clink set. E.g. do the settings look right?
  • +
  • Check the clink.log file for clues (its location is reported by clink info).
  • +
+

When reporting an issue, please include the following which answer a bunch of commonly relevant questions and saves time:

+
    +
  • Please describe what was expected to happen.
  • +
  • Please describe what actually happened.
  • +
  • Please include the output from clink info and clink set.
  • +
  • Please include the clink.log file (the location is reported by clink info).
  • +
+
+

Lua API Reference

+ This section describes the Clink Lua API extensions. + Also see Lua Documentation for more information about the Lua programming language. +
+
_argmatcher
( choices...:string|table ) : self

This adds argument matches. Arguments can be a string, a string linked to another parser by the concatenation operator, a table of arguments, or a function that returns a table of arguments. See Argument Completion for more information.

local my_parser = clink.argmatcher("git")
+:addarg("add", "status", "commit", "checkout")

+
( flags...:string ) : self

This adds flag matches. Flags are separate from arguments: When listing possible completions for an empty word, only arguments are listed. But when the word being completed starts with the first character of any of the flags, then only flags are listed. See Argument Completion for more information.

local my_parser = clink.argmatcher("git")
+:addarg({ "add", "status", "commit", "checkout" })
+:addflags("-a", "-g", "-p", "--help")

+
( [index:integer] ) : self

This makes the parser loop back to argument position index when it runs out of positional sets of arguments (if index is omitted it loops back to argument position 1).

clink.argmatcher("xyzzy")
+:addarg("zero", "cero")     -- first arg can be zero or cero
+:addarg("one", "uno")       -- second arg can be one or uno
+:addarg("two", "dos")       -- third arg can be two or dos
+:loop(2)    -- fourth arg loops back to position 2, for one or uno, and so on

+

This makes the parser prevent invoking match generators. You can use it to "dead end" a parser and suggest no completions.


+
( func:function ) : self

This registers a function that gets called for each word the argmatcher handles, to classify the word as part of coloring the input text. See Coloring The Input Text for more information.


+
( [prefixes...:string] ) : self

Deprecated; don't use this. See _argmatcher:addflags for more information.

This overrides the default flag prefix (-). The flag prefixes are used to switch between matching arguments versus matching flags. When listing possible completions for an empty word (e.g. command _ where the cursor is at the _), only arguments are listed. And only flags are listed when the word starts with one of the flag prefixes. Each flag prefix must be a single character, but there can be multiple prefixes.

This is no longer needed because :addflags() does it automatically.

local my_parser = clink.argmatcher()
+:setflagprefix("-", "/", "+")
+:addflags("--help", "/?", "+mode")

+
builder
( match:string|table, [type:string] ) : boolean

Adds a match. If match is a string, it's added as a match and type is the optional match type.

Or match can be a table with the following scheme: { match:string, [type:string] }. If a table element is missing the type field, then the type argument is used for that element.

If the type argument is omitted, "none" is assumed.

The match type can affect how the match is inserted, displayed, and colored:

TypeDescription
"word"Shows the whole word even if it contains slashes.
"arg"Avoids appending a space if the match ends with a colon or equal sign.
"command"Displays the match using color.cmd.
"alias"Displays the match using color.doskey.
"file"Shows only the last path component, with appropriate file coloring.
"dir"Shows only the last path component and adds a trailing path separator, with appropriate directory coloring.
"link"Shows only the last path component, with appropriate symlink coloring. Not supported yet.
"none"For backward compatibility the match is treated like "file", unless it ends with a path separator in which case it's treated like "dir".

ModifierDescription
"hidden"This can be combined with "file" or "dir" to use color.hidden (e.g. "file,hidden").
"readonly"This can be combined with "file" or "dir" to use color.readonly (e.g. "file,readonly").

See Completion Colors and Color Settings for more information about colors.

builder:addmatch("hello") -- type is "none"
+builder:addmatch("some_word", "word")
+builder:addmatch("/flag", "arg")
+builder:addmatch("abbrev", "alias")
+builder:addmatch({ match="foo.cpp", type="file" })
+builder:addmatch({ match="bar", type="dir" })
+builder:addmatch({ match=".git", type="dir hidden" })

+
( matches:table, [type:string] ) : integer, boolean

This is the equivalent of calling builder:addmatch() in a for-loop. Returns the number of matches added and a boolean indicating if all matches were added successfully.

matches can be a table of match strings, or a table of tables describing the matches.
type is used as the type when a match doesn't explicitly include a type, and is "none" if omitted.

builder:addmatches({"abc", "def"}) -- Adds two matches of type "none"
+builder:addmatches({"abc", "def"}, "file") -- Adds two matches of type "file"
+builder:addmatches({
+  -- Same table scheme per entry here as in builder:addmatch()
+  { match="remote/origin/master", type="word" },
+  { match="remote/origin/topic", type="word" }
+})

+
( [append:string] ) : nil

Sets character to append after matches. For example the set match generator uses this to append "=" when completing matches, so that completing set USER becomes set USERDOMAIN= (rather than set USERDOMAIN ).


+
( [state:boolean] ) : nil

Sets whether to suppress appending anything after the match except a possible closing quote. For example the env var match generator uses this.


+
( [state:integer] ) : nil

Sets whether to suppress quoting for the matches. Set to 0 for normal quoting, or 1 to suppress quoting, or 2 to suppress end quotes. For example the env var match generator sets this to 1 to overcome the quoting that would normally happen for "%" characters in filenames.


+
clink
( match:string ) : nil

Deprecated; don't use this. See builder:addmatch for more information.

This is a shim that lets clink.register_match_generator continue to work for now, despite being obsolete.


+
( [priority:integer], commands...:string ) : _argmatcher

Creates and returns a new argument matcher parser object. Use :addarg() and etc to add arguments, flags, other parsers, and more. See Argument Completion for more information.

If one command is provided and an argument matcher parser object is already associated with the command, this returns the existing parser rather than creating a new parser. Using :addarg() starts at arg position 1, making it possible to merge new args and etc into the existing parser.


+
( [priority:integer] ) : table

Creates and returns a new word classifier object. Define on the object a classify() function which gets called in increasing priority order (low values to high values) when classifying words for coloring the input. See Coloring The Input Text for more information.


+
( word:string ) : table

You can use this function in an argmatcher to supply directory matches. This automatically handles Readline tilde completion.

-- Make "cd" generate directory matches (no files).
+clink.argmatcher("cd")
+:addflags("/d")
+:addarg({ clink.dirmatches })

+
( word:string ) : table

You can use this function in an argmatcher to supply file matches. This automatically handles Readline tilde completion.

Argmatchers default to matching files, so it's unusual to need this function. However, some exceptions are when a flag needs to accept file matches but other flags and arguments don't, or when matches need to include more than files.

-- Make "foo --file" generate file matches, but other flags and args don't.
+-- And the third argument can be a file or $stdin or $stdout.
+clink.argmatcher("foo")
+:addflags(
+  "--help",
+  "--file"..clink.argmatcher():addarg({ clink.filematches })
+)
+:addarg({ "one", "won" })
+:addarg({ "two", "too" })
+:addarg({ clink.filematches, "$stdin", "$stdout" })

+
( [priority:integer] ) : table

Creates and returns a new match generator object. Define on the object a generate() function which gets called in increasing priority order (low values to high values) when generating matches for completion. See Match Generators for more information.


+
() : string

Returns a string indicating who Clink thinks will currently handle ANSI escape codes. This can change based on the terminal.emulation setting. This always returns "unknown" until the first edit prompt (see clink.onbeginedit()).

This can be useful in choosing what kind of ANSI escape codes to use, but it is a best guess and is not necessarily 100% reliable.

ReturnDescription
"unknown"Clink doesn't know.
"clink"Clink is emulating ANSI support. 256 color and 24 bit color escape codes are mapped to the nearest of the 16 basic colors.
"conemu"Clink thinks ANSI escape codes will be handled by ConEmu.
"ansicon"Clink thinks ANSI escape codes will be handled by ANSICON.
"winterminal"Clink thinks ANSI escape codes will be handled by Windows Terminal.
"winconsole"Clink thinks ANSI escape codes will be handled by the default console support in Windows, but Clink detected a terminal replacement that won't support 256 color or 24 bit color.
"winconsolev2"Clink thinks ANSI escape codes will be handled by the default console support in Windows, or it might be handled by a terminal replacement that Clink wasn't able to detect.


+
() : string

Returns the current Clink session id.

This is needed when using io.popen() (or similar functions) to invoke clink history or clink info while Clink is installed for autorun. The popen API spawns a new CMD.exe, which gets a new Clink instance injected, so the history or info command will use the new session unless explicitly directed to use the calling session.

local c = os.getalias("clink")
+local r = io.popen(c.." --session "..clink.getsession().." history")

+
( needle:string, candidate:string ) : boolean

Deprecated; don't use this. See clink.generator for more information.

This returns true if needle is a prefix of candidate with a case insensitive comparison.

Normally in Clink v1.x and higher the needle will be an empty string because the generators are no longer responsible for filtering matches. The match pipeline itself handles that internally now.


+
( text:string ) : string

This API correctly converts UTF8 strings to lowercase, with international linguistic awareness.

clink.lower("Hello World") -- returns "hello world"

+
function variable

Deprecated; don't use this. See clink.ondisplaymatches for more information.

A match generator can set this varible to a filter function that is called before displaying matches. It is reset every time match generation is invoked. The filter function receives table argument containing the matches that are going to be displayed, and it returns a table filtered as required by the match generator.

See Filtering the Match Display for more information.


+
function variable

Deprecated; don't use this. See builder:addmatch for more information.

This is no longer used.

clink.match_display_filter = function(matches)
+  -- Transform matches.
+  return matches
+end

+
( [files:boolean] ) : nil

Deprecated; don't use this. See builder:addmatch for more information.

This is no longer needed, because now it's inferred from the match type when adding matches.


+
( func:function ) : nil

Registers func to be called when Clink's edit prompt is activated. The function receives no arguments and has no return values.


+
( func:function ) : nil

Registers func to be called when Clink is about to display matches. See Filtering the Match Display for more information.

local function my_filter(matches, popup)
+  local new_matches = {}
+  for _,m in ipairs(matches) do
+    if m.match:find("[0-9]") then
+      -- Ignore matches with one or more digits.
+    else
+      -- Keep the match, and also add * prefix to directory matches.
+      if m.type:find("^dir") then
+        m.display = "*"..m.match
+      end
+      table.insert(new_matches, m)
+    end
+  end
+  return new_matches
+end
 
-Clink supports Readline's menu-complete command (which is similar to vanilla cmd.exe completion that cycles through matches rather than displaying available ones). To use this menu-style completion Clink provides the alternative command **clink-menu-completion-shim**. Using this ensures that appropriate path separator translation takes place.
+function my_match_generator:generate(line_state, match_builder)
+  ...
+  clink.ondisplaymatches(my_filter)
+end

+
( func:function ) : nil

Registers func to be called when Clink's edit prompt ends. The function receives a string argument containing the input text from the edit prompt. The function returns up to two values. If the first is not nil then it's a string that replaces the edit prompt text. If the second is not nil and is false then it stops further onendedit handlers from running.

Note: Be very careful if you replace the text; this has the potential to interfere with or even ruin the user's ability to enter command lines for CMD to process.


+
( func:function ) : nil

Registers func to be called after Clink generates matches for completion. See Filtering Match Completions for more information.


+
( func:function ) : nil

Registers func to be called when Clink is injected into a CMD process. The function is called only once per session.


+
( [priority:integer] ) : table

Creates and returns a new promptfilter object that is applied in increasing priority order (low values to high values). Define on the object a filter() function that takes a string argument which contains the filtered prompt so far. The function can return nil to have no effect, or can return a new prompt string. It can optionally stop further prompt filtering by also returning false. See Customising The Prompt for more information.

local foo_prompt = clink.promptfilter(80)
+function foo_prompt:filter(prompt)
+  -- Insert the date at the beginning of the prompt.
+  return os.date("%a %H:%M").." "..prompt
+end

+
( func:function, priority:integer ) : nil

Deprecated; don't use this. See clink.generator for more information.

Registers a generator function for producing matches. This behaves similarly to v0.4.8, but not identically. The Clink schema has changed significantly enough that there is no direct 1:1 translation; generators are called at a different time than before and have access to more information than before.

-- Deprecated form:
+local function match_generator_func(text, first, last)
+  -- `text` is the word text.
+  -- `first` is the index of the beginning of the end word.
+  -- `last` is the index of the end of the end word.
+  -- `clink.add_match()` is used to add matches.
+  -- return true if handled, or false to let another generator try.
+end
+clink.register_match_generator(match_generator_func, 10)
+
+-- Replace with new form:
+local g = clink.generator(10)
+function g:generate(line_state, match_builder)
+  -- `line_state` is a line object.
+  -- `match_builder:addmatch()` is used to add matches.
+  -- return true if handled, or false to let another generator try.
+end

+
( type:integer ) : nil

Deprecated; don't use this. See clink.translateslashes for more information.

Controls how Clink will translate the path separating slashes for the current path being completed. Values for type are;
-1 - no translation
0 - to backslashes
1 - to forward slashes


+
( [mode:integer] ) : integer

This overrides how Clink translates slashes in completion matches, which is normally determined by the match.translate_slashes setting.

This is reset every time match generation is invoked, so use a generator to set this.

The mode specifies how to translate slashes when generators add matches:
ModeDescription
0No translation.
1Translate using the system path separator (backslash on Windows).
2Translate to slashes (/).
3Translate to backslashes (\).

If mode is omitted, then the function returns the current slash translation mode without changing it.

Note: Clink always generates file matches using the system path separator (backslash on Windows), regardless what path separator may have been typed as input. Setting this to 0 does not disable normalizing typed input paths when invoking completion; it only disables translating slashes in custom generators.

-- This example affects all match generators, by using priority -1 to
+-- run first and returning false to let generators continue.
+-- To instead affect only one generator, call clink.translateslashes()
+-- in its :generate() function and return true.
+local force_slashes = clink.generator(-1)
+function force_slashes:generate()
+  clink.translateslashes(2)    -- Convert to slashes.
+  return false                 -- Allow generators to continue.
+end

+
( text:string ) : string

This API correctly converts UTF8 strings to uppercase, with international linguistic awareness.

clink.upper("Hello World") -- returns "HELLO WORLD"

+
string variable

The commit part of the Clink version number. For v1.2.3.a0f14d the commit part is a0f14d.


+
integer variable

The Clink version number encoded as a single integer following the format Mmmmpppp where M is the major part, m is the minor part, and p is the patch part of the version number.

For example, Clink v95.6.723 would be 950060723.

This format makes it easy to test for feature availability by encoding version numbers from the release notes.


+
integer variable

The major part of the Clink version number. For v1.2.3.a0f14d the major version is 1.


+
integer variable

The minor part of the Clink version number. For v1.2.3.a0f14d the minor version is 2.


+
integer variable

The patch part of the Clink version number. For v1.2.3.a0f14d the patch version is 3.


+
clink.arg
( ... ) : table

Deprecated; don't use this. See clink.argmatcher for more information.

Creates a new parser and adds ... to it.

-- Deprecated form:
+local parser = clink.arg.new_parser(
+  { "abc", "def" },       -- arg position 1
+  { "ghi", "jkl" },       -- arg position 2
+  "--flag1", "--flag2"    -- flags
+)
 
-#### Powershell
+-- Replace with form:
+local parser = clink.argmatcher()
+:addarg("abc", "def")               -- arg position 1
+:addarg("ghi", "jkl")               -- arg position 2
+:addflags("--flag1", "--flag2")     -- flags

+
( cmd:string, parser:table ) : table

Deprecated; don't use this. See clink.argmatcher for more information.

Adds parser to the first argmatcher for cmd. This behaves similarly to v0.4.8, but not identically. The Clink schema has changed significantly enough that there is no direct 1:1 translation. Calling clink.arg.register_parser repeatedly with the same command to merge parsers is not supported anymore.

-- Deprecated form:
+local parser1 = clink.arg.new_parser("abc", "def")
+local parser2 = clink.arg.new_parser("ghi", "jkl")
+clink.arg.register_parser("foo", parser1)
+clink.arg.register_parser("foo", parser2)
+
+-- Replace with new form:
+clink.argmatcher("foo"):addarg(parser1, parser2)
+
+-- Warning:  Note that the following are NOT the same as above!
+-- This replaces parser1 with parser2:
+clink.argmatcher("foo"):addarg(parser1)
+clink.argmatcher("foo"):addarg(parser2)
+-- This uses only parser2 if/when parser1 finishes parsing args:
+clink.argmatcher("foo"):addarg(parser1):addarg(parser2)

+
clink.prompt
( filter_func:function, [priority:integer] ) : table

Deprecated; don't use this. See clink.promptfilter for more information.

Registers a prompt filter function. The capabilities are the same as before but the syntax is changed.

-- Deprecated form:
+function foo_prompt()
+  clink.prompt.value = "FOO "..clink.prompt.value.." >>"
+  --return true  -- Returning true stops further filtering.
+end
+clink.prompt.register_filter(foo_prompt, 10)
+
+-- Replace with new form:
+local foo_prompt = clink.promptfilter(10)
+function foo_prompt:filter(prompt)
+  return "FOO "..prompt.." >>" --,false  -- Adding ,false stops further filtering.
+end

+
console
( text:string ) : integer

Returns the count of visible character cells that would be consumed if the text string were output to the console, accounting for any ANSI escape codes that may be present in the text.

Note: backspace characters and line endings are counted as visible character cells and will skew the resulting count.


+
( starting_line:integer, [text:string], [mode:string], [attr:integer], [attrs:table of integers], [mask:string] ) : integer

Searches downwards (forwards) for a line containing the specified text and/or attributes, starting at line starting_line. The matching line number is returned, or 0 if no matching line is found.

This behaves the same as console.findprevline() except that it searches in the opposite direction.


+
( starting_line:integer, [text:string], [mode:string], [attr:integer], [attrs:table of integers], [mask:string] ) : integer

Searches upwards (backwards) for a line containing the specified text and/or attributes, starting at line starting_line. The matching line number is returned, or 0 if no matching line is found, or -1 if an invalid regular expression is provided.

You can search for text, attributes, or both. Include the text argument to search for text, and include either the attr or attrs argument to search for attributes. If both text and attribute(s) are passed, then the attribute(s) must be found within the found text. If only attribute(s) are passed, then they must be found anywhere in the line. See console.linehascolor() for more information about the color codes.

The mode argument selects how the search behaves. To use a regular expression, pass "regex". To use a case insensitive search, pass "icase". These can be combined by separating them with a comma. The regular expression syntax is the ECMAScript syntax described here.

Any trailing whitespace is ignored when searching. This especially affects the $ (end of line) regex operator.

mask is optional and can be "fore" or "back" to only match foreground or background colors, respectively.

Note: Although most of the arguments are optional, the order of provided arguments is important.

The following example provides a pair of find_prev_colored_line and find_next_colored_line functions. The functions can be bound to keys via the luafunc: macro syntax in a .inputrc file. They scroll the screen buffer to the previous or next line that contains "warn" or "error" colored red or yellow.

local was_top
+local found_index
+
+local function reset_found()
+  was_top = nil
+  found_index = nil
+end
 
-Clink has basic support for Powershell. In order to show completion correctly Clink needs to parse Powershell's prompt to extract the current directory. If the prompt has been customized Clink is unlikely to work as expected.
+-- Register for the onbeginedit event, to reset the found
+-- line number each time a new editing prompt begins.
+clink.onbeginedit(reset_found)
+
+-- Searches upwards for a line containing "warn" or "error"
+-- colored red or yellow.
+function find_prev_colored_line(rl_buffer)
+  local height = console.getheight()
+  local cur_top = console.gettop()
+  local offset = math.modf((height - 1) / 2) -- For vertically centering the found line.
+
+  local start
+  if found_index == nil or cur_top ~= was_top then
+    start = cur_top
+    was_top = start
+  else
+    start = found_index
+  end
+
+  -- Only search if there's still room to scroll up.
+  if start - offset > 1 then
+    local match = console.findprevline(start - 1, "warn|error", "regex", {4,12,14}, "fore")
+    if match ~= nil and match > 0 then
+      found_index = match
+    end
+  end
+
+  if found_index ~= nil then
+    console.scroll("absolute", found_index - offset)
+    was_top = console.gettop()
+  else
+    rl_buffer:ding()
+  end
+end
 
+-- Searches downwards for a line containing "warn" or "error"
+-- colored red or yellow.
+function find_next_colored_line(rl_buffer)
+  if found_index == nil then
+    rl_buffer:ding()
+    return
+  end
+
+  local height = console.getheight()
+  local cur_top = console.gettop()
+  local offset = math.modf((height - 1) / 2)
+
+  local start
+  if cur_top ~= was_top then
+      start = cur_top + height - 1
+      was_top = cur_top
+  else
+      start = found_index
+  end
+
+  -- Only search if there's still room to scroll down.
+  local bottom = console.getnumlines()
+  if start - offset + height - 1 < bottom then
+    local match = console.findnextline(start + 1, "warn|error", "regex", {4,12,14}, "fore")
+    if match ~= nil and match > 0 then
+      found_index = match
+    end
+  end
+
+  if found_index ~= nil then
+    console.scroll("absolute", found_index - offset)
+    was_top = console.gettop()
+  else
+    rl_buffer:ding()
+  end
+end

+
() : integer

Returns the number of visible lines of the console screen buffer.


+
( line:integer ) : string

Returns the text from line number line, from 1 to console.getnumlines().

Any trailing whitespace is stripped before returning the text.


+
() : integer

Returns the total number of lines in the console screen buffer.


+
() : string

Returns the console title text.


+
() : integer

Returns the current top line (scroll position) in the console screen buffer.


+
() : integer

Returns the width of the console screen buffer in characters.


+
( line:integer ) : boolean

Returns whether line number line uses only the default text color.


+
( line:integer, [attr:integer], [attrs:table of integers], [mask:string] ) : boolean

Returns whether line number line contains the DOS color code attr, or any of the DOS color codes in attrs (either an integer or a table of integers must be provided, but not both). mask is optional and can be "fore" or "back" to only match foreground or background colors, respectively.

The low 4 bits of the color code are the foreground color, and the high 4 bits of the color code are the background color. This refers to the default 16 color palette used by console windows. When 256 color or 24-bit color ANSI escape codes have been used, the closest of the 16 colors is used.

To build a color code, add the corresponding Foreground color and the Background color values from this table:

ForegroundBackgroundColor
00
 
Black
116
 
Dark Blue
232
 
Dark Green
348
 
Dark Cyan
464
 
Dark Red
580
 
Dark Magenta
696
 
Dark Yellow
7112
 
Gray
8128
 
Dark Gray
9144
 
Bright Blue
10160
 
Bright Green
11176
 
Bright Cyan
12192
 
Bright Red
13208
 
Bright Magenta
14224
 
Bright Yellow
15240
 
White


+
( text:string ) : string, integer

Returns the input text with ANSI escape codes removed, and the count of visible character cells that would be consumed if the text were output to the console.

Note: backspace characters and line endings are counted as visible character cells and will skew the resulting count.


+
( candidate_pattern:string, accept_pattern:string ) : table

Uses the provided Lua string patterns to collect text from the current console screen and returns a table of matching text snippets. The snippets are ordered by distance from the input line.

For example candidate_pattern could specify a pattern that identifies words, and accept_pattern could specify a pattern that matches words composed of hexadecimal digits.

local matches = console.screengrab(
+        "[^%w]*(%w%w[%w]+)",   -- Words with 3 or more letters are candidates.
+        "^%x+$")               -- A candidate containing only hexadecimal digits is a match.

+
( mode:string, amount:integer ) : integer

Scrolls the console screen buffer and returns the number of lines scrolled up (negative) or down (positive).

The mode specifies how to scroll:
ModeDescription
"line"Scrolls by amount lines; negative is up and positive is down.
"page"Scrolls by amount pages; negative is up and positive is down.
"end"Scrolls to the top if amount is negative, or to the bottom if positive.
"absolute"Scrolls to line amount, from 1 to console.getnumlines().


+
( title:string ) : nil

Sets the console title text.


+
io
( command:string, [mode:string] ) : file, file

Runs command and returns two file handles: a file handle for reading output from the command, and a file handle for writing input to the command.

mode can be "t" for text mode (the default if omitted) or "b" for binary mode.

If the function fails it returns nil, an error message, and an error number.

Warning This can result in deadlocks unless the command fully reads all of its input before writing any output. This is because Lua uses blocking IO to read and write file handles. If the write buffer fills (or the read buffer is empty) then the write (or read) will block and can only become unblocked if the command correspondingly reads (or writes). But the other command can easily experience the same blocking IO problem on its end, resulting in a deadlock: process 1 is blocked from writing more until process 2 reads, but process 2 can't read because it is blocked from writing until process 1 reads.

local r,w = io.popenrw("fzf.exe --height 40%")
+
+w:write("hello\n")
+w:write("world\n")
+w:close()
+
+while (true) do
+  local line = r:read("*line")
+  if not line then
+    break
+  end
+  print(line)
+end
+r:close()

+
line
() : integer

Returns the offset to the start of the delimited command in the line that's being effectively edited. Note that this may not be the offset of the first command of the line unquoted as whitespace isn't considered for words.

-- Given the following line; abc& 123
+-- where commands are separated by & symbols.
+line:getcommandoffset() == 4

+
() : integer

Returns the position of the cursor.


+
() : string

Returns the last word of the line. This is the word that matches are being generated for.

Note: The returned word omits any quotes. This helps generators naturally complete "foo\"ba to "foo\bar". The raw word including quotes can be obtained using the offset and length fields from line:getwordinfo() to extract a substring from the line returned by line:getline().

line:getword(line:getwordcount()) == line:getendword()

+
() : string

Returns the current line in its entirety.


+
( index:integer ) : string

Returns the word of the line at index.

Note: The returned word omits any quotes. This helps generators naturally complete "foo\"ba to "foo\bar". The raw word including quotes can be obtained using the offset and length fields from line:getwordinfo() to extract a substring from the line returned by line:getline().


+
() : integer

Returns the number of words in the current line.


+
( index:integer ) : table

Returns a table of information about the Nth word in the line.

Note: The length refers to the substring in the line; it omits leading and trailing quotes, but includes embedded quotes. line:getword() conveniently strips embedded quotes to help generators naturally complete "foo\"ba to "foo\bar".

The table returned has the following scheme:

{
+  offset,  -- [integer] offset where the word starts in the line:getline() string.
+  length,  -- [integer] length of the word (includes embedded quotes).
+  quoted,  -- [boolean] indicates whether the word is quoted.
+  delim,   -- [string] the delimiter character, or an empty string.
+  alias,   -- [boolean | nil] true if the word is a doskey alias, otherwise nil.
+}

+
log
( message:string ) : nil

Writes info message to the Clink log file. Use this sparingly, or it could cause performance problems or disk space problems.


+
os
( path:string ) : boolean

Changes the current directory to path and returns whether it was successful.


+
( src:string, dest:string ) : boolean

Copies the src file to the dest file.


+
( [prefix:string], [ext:string], [path:string], [mode:string] ) : file, string

Creates a uniquely named file, intended for use as a temporary file. The name pattern is "location \ prefix _ processId _ uniqueNum extension".

prefix optionally specifies a prefix for the file name and defaults to "tmp".

ext optionally specifies a suffix for the file name and defaults to "" (if ext starts with a period "." then it is a filename extension).

path optionally specifies a path location in which to create the file. The default is the system TEMP directory.

mode optionally specifies "t" for text mode (line endings are translated) or "b" for binary mode (untranslated IO). The default is "t".

When successful, the function returns a file handle and the file name.

Note: Be sure to delete the file when finished, or it will be leaked.

If the function is unable to create a file it returns nil, an error message, and an error number. For example if the directory is inaccessible, or if there are already too many files, or invalid file name characters are used, or etc.


+
( value:string ) : string

Returns value with any %name% environment variables expanded. Names are case insensitive. Special CMD syntax is not supported (e.g. %name:str1=str2% or %name:~offset,length%).

Note: os.getenv("HOME") receives special treatment: if %HOME% is not set then it is synthesized from %HOMEDRIVE% and %HOMEPATH%, or from %USERPROFILE%.


+
( name:string ) : string | nil

Returns command string for doskey alias name, or nil if the named alias does not exist.


+
() : table

Returns doskey aliases in a table with the following scheme: { {name:string, command:string}, ... }.


+

Returns a table containing the battery status for the device, or nil if an error occurs. The returned table has the following scheme:

{
+  level,         -- [integer] the battery life from 0 to 100, or -1 if an
+                 --            error occurred or there is no battery.
+  acpower,       -- [boolean] whether the device is connected to AC power.
+  charging,      -- [boolean] whether the battery is charging.
+  batterysaver,  -- [boolean] whether Battery Saver mode is active.
+}

+
() : string

Returns the current directory.


+
( name:string ) : string | nil

Returns the value of the named environment variable, or nil if it doesn't exist.

Note: os.getenv("HOME") receives special treatment: if %HOME% is not set then it is synthesized from %HOMEDRIVE% and %HOMEPATH%, or from %USERPROFILE%.


+
() : table

Returns all environment variables in a table with the following scheme: { {name:string, value:string}, ... }.


+
( path:string ) : string

Returns the full path name for path.


+
() : string

Returns the fully qualified file name of the host process. Currently only CMD.EXE can host Clink.


+
( path:string ) : string

Returns the long path name for path.


+
() : integer

Returns the CMD.EXE process ID. This is mainly intended to help with salting unique resource names (for example named pipes).


+
() : table

Returns dimensions of the terminal's buffer and visible window. The returned table has the following scheme:

{
+  bufwidth,     -- [integer] width of the screen buffer
+  bufheight,    -- [integer] height of the screen buffer
+  winwidth,     -- [integer] width of the visible window
+  winheight,    -- [integer] height of the visible window
+}

+
( path:string ) : string

Returns the 8.3 short path name for path. This may return the input path if an 8.3 short path name is not available.


+
( globpattern:string, [extrainfo:boolean] ) : table

Collects directories matching globpattern and returns them in a table of strings.

When extrainfo is true, then the returned table has the following scheme: { {name:string, type:string}, ... }.

The type string can be "file" or "dir", and may also contain ",hidden" and ",readonly" depending on the attributes (making it usable as a match type for builder:addmatch()).

Note: any quotation marks (") in globpattern are stripped.


+
( globpattern:string, [extrainfo:boolean] ) : table

Collects files and/or directories matching globpattern and returns them in a table of strings.

When extrainfo is true, then the returned table has the following scheme: { {name:string, type:string}, ... }.

The type string can be "file" or "dir", and may also contain ",hidden" and ",readonly" depending on the attributes (making it usable as a match type for builder:addmatch()).

Note: any quotation marks (") in globpattern are stripped.


+
( path:string ) : boolean

Returns whether path is a directory.


+
( path:string ) : boolean

Returns whether path is a file.


+
( path:string ) : boolean

Returns whether path has the hidden attribute set.


+
( path:string ) : boolean

Creates the directory path and returns whether it was successful.


+
( src:string, dest:string ) : boolean

Moves the src file to the dest file.


+
( path:string ) : boolean

Removes the directory path and returns whether it was successful.


+
( name:string, value:string ) : boolean

Sets the name environment variable to value and returns whether it was successful.


+
( path:string ) : boolean

Deletes the file path and returns whether it was successful.


+
path
( path:string ) : string

path.getbasename("/foo/bar.ext")    -- returns "bar"
+path.getbasename("")                -- returns ""
+path.getbasename(nil)               -- returns nil

+
( path:string ) : nil or string

This is similar to path.toparent() but can behave differently when the input path ends with a path separator. This is the recommended API for parsing a path into its component pieces, but is not recommended for walking up through parent directories.

path.getdirectory("foo")                -- returns nil
+path.getdirectory("\foo")               -- returns "\"
+path.getdirectory("c:foo")              -- returns "c:"
+path.getdirectory([[c:\]])              -- returns "c:\"
+path.getdirectory("c:\foo")             -- returns "c:\"
+path.getdirectory("c:\foo\bar")         -- returns "c:\foo"
+path.getdirectory("\\foo\bar")          -- returns "\\foo\bar"
+path.getdirectory("\\foo\bar\dir")      -- returns "\\foo\bar"
+path.getdirectory("")                   -- returns nil
+path.getdirectory(nil)                  -- returns nil
+
+-- These split the path components differently than path.toparent().
+path.getdirectory([[c:\foo\bar\]])      -- returns "c:\foo\bar"
+path.getdirectory([[\\foo\bar\dir\]])   -- returns "\\foo\bar\dir"

+
( path:string ) : nil or string

path.getdrive("e:/foo/bar")     -- returns "e:"
+path.getdrive("foo/bar")        -- returns nil
+path.getdrive("")               -- returns nil
+path.getdrive(nil)              -- returns nil

+
( path:string ) : string

path.getextension("bar.ext")    -- returns ".ext"
+path.getextension("bar")        -- returns ""
+path.getextension("")           -- returns ""
+path.getextension(nil)          -- returns nil

+
( path:string ) : string

path.getname("/foo/bar.ext")    -- returns "bar.ext"
+path.getname("")                -- returns ""
+path.getname(nil)               -- returns nil

+
( path:string ) : boolean

Examines the extension of the path name. Returns true if the extension is listed in %PATHEXT%. This caches the extensions in a map so that it's more efficient than getting and parsing %PATHEXT% each time.

path.isexecext("program.exe")   -- returns true
+path.isexecext("file.doc")      -- returns false
+path.isexecext("")              -- returns false
+path.isexecext(nil)             -- returns nil

+
( left:string, right:string ) : string

path.join("/foo", "bar")    -- returns "/foo\bar"
+path.join("", "bar")        -- returns "bar"
+path.join("/foo", "")       -- returns "/foo"
+path.join(nil, "bar")       -- returns nil
+path.join("/foo", nil)      -- returns nil

+
( path:string, [separator:string] ) : string

Cleans path by normalising separators and removing "." and ".." elements. If separator is provided it is used to delimit path elements, otherwise a system-specific delimiter is used.

path.normalise("a////b/\\/c/")  -- returns "a\b\c\"
+path.normalise("")              -- returns ""
+path.normalise(nil)             -- returns nil

+
( path:string ) : parent:string, child:string

Splits the last path component from path, if possible. Returns the result and the component that was split, if any.

This is similar to path.getdirectory() but can behave differently when the input path ends with a path separator. This is the recommended API for walking up through parent directories.

local parent,child
+parent,child = path.toparent("foo")             -- returns "", "foo"
+parent,child = path.toparent("\foo")            -- returns "\", "foo"
+parent,child = path.toparent("c:foo")           -- returns "c:", "foo"
+parent,child = path.toparent([[c:\]])           -- returns "c:\", ""
+parent,child = path.toparent("c:\foo")          -- returns "c:\", "foo"
+parent,child = path.toparent("c:\foo\bar")      -- returns "c:\foo", "bar"
+parent,child = path.toparent("\\foo\bar")       -- returns "\\foo\bar", ""
+parent,child = path.toparent("\\foo\bar\dir")   -- returns "\\foo\bar", "dir"
+parent,child = path.toparent("")                -- returns "", ""
+parent,child = path.toparent(nil)               -- returns nil
+
+-- These split the path components differently than path.getdirectory().
+parent,child = path.toparent([[c:\foo\bar\]])   -- returns "c:\foo", "bar"
+parent,child = path.toparent([[\\foo\bar\dir\]])-- returns "\\foo\bar", "dir"

+
rl
( path:string, [force:boolean] ) : string

Undoes Readline tilde expansion. See rl.expandtilde for more information.

rl.collapsetilde("C:\Users\yourusername\Documents")
+ 
+-- The return value depends on the expand-tilde configuration variable:
+-- When "on", the function returns "C:\Users\yourusername\Documents".
+-- When "off", the function returns "~\Documents".
+ 
+-- Or when force is true, the function returns "~\Documents".

+
( path:string ) : string, boolean

Performs Readline tilde expansion.

When generating filename matches for a word, use the rl.expandtilde and rl.collapsetilde helper functions to perform tilde completion expansion according to Readline's configuration.

Use rl.expandtilde to do tilde expansion before collecting file matches (e.g. via os.globfiles). If it indicates that it expanded the string, then use rl.collapsetilde to put back the tilde before returning a match.

local result, expanded = rl.expandtilde("~\Documents")
+-- result is "C:\Users\yourusername\Documents"
+-- expanded is true
+ 
+-- This dir_matches function demonstrates efficient use of rl.expandtilde()
+-- and rl.collapsetilde() to generate directory matches from the file system.
+function dir_matches(match_word, word_index, line_state)
+  -- Expand tilde before scanning file system.
+  local word = line_state:getword(word_index)
+  local expanded
+  word, expanded = rl.expandtilde(word)
+ 
+  -- Get the directory from 'word', and collapse tilde before generating
+  -- matches.  Notice that collapsetilde() only needs to be called once!
+  local root = path.getdirectory(word) or ""
+  if expanded then
+    root = rl.collapsetilde(root)
+  end
+ 
+  local matches = {}
+  for _, d in ipairs(os.globdirs(word.."*", true)) do
+    -- Join the filename with the input directory (might have a tilde).
+    local dir = path.join(root, d.name)
+    table.insert(matches, { match = dir, type = d.type })
+  end
+  return matches
+end

+
() : string, function

Returns two values:

  • The name of the last Readline command invoked by a key binding.
  • The name of the last Lua function invoked by a key binding.

If the last key binding invoked a Lua function, then the first return value is an empty string unless the Lua function used rl.invokecommand() to also internally invoke a Readline command. If the last key binding did not invoke a Lua function, then the second return value is an empty string.

local last_rl_func, last_lua_func = rl.getlastcommand()

+
( name:string ) : string | nil

Returns the value of the named Readline configuration variable as a string, or nil if the variable name is not recognized.


+
( command:string, [count:integer] ) : boolean | nil

Invokes a Readline command named command. May only be used within a luafunc: key binding.

count is optional and defaults to 1 if omitted.

Returns true if the named command succeeds, false if the named command fails, or nil if the named command doesn't exist.

Warning: Invoking more than one Readline command in a luafunc: key binding could have unexpected results, depending on which commands are invoked.


+
( name:string ) : boolean | nil

Returns a boolean value indicating whether the named Readline configuration variable is set to true (on), or nil if the variable name is not recognized.


+
( matches:table, [type:string] ) : integer, boolean

Provides an alternative set of matches for the current word. This discards any matches that may have already been collected and uses matches for subsequent Readline completion commands until any action that normally resets the matches (such as moving the cursor or editing the input line).

May only be used within a luafunc: key binding.

The syntax is the same as for builder:addmatches() with one addition: You can add a "nosort" key to the matches table to disable sorting the matches.

local matches = {}
matches["nosort"] = true
rl.setmatches(matches)

This function can be used by a luafunc: key binding to provide matches based on some special criteria. For example, a key binding could collect numbers from the current screen buffer (such as issue numbers, commit hashes, line numbers, etc) and provide them to Readline as matches, making it convenient to grab a number from the screen and insert it as a command line argument.

Match display filtering is also possible by using clink.ondisplaymatches() after setting the matches.

Example .inputrc key binding:

M-n:            "luafunc:completenumbers"       # Alt+N

Example Lua function:

function completenumbers()
+  local _,last_luafunc = rl.getlastcommand()
+  if last_luafunc ~= "completenumbers" then
+    -- Collect numbers from the screen (minimum of three digits).
+    -- The numbers can be any base up to hexadecimal (decimal, octal, etc).
+    local matches = console.screengrab("[^%w]*(%w%w[%w]+)", "^%x+$")
+    -- They're already sorted by distance from the input line.
+    matches["nosort"] = true
+    rl.setmatches(matches)
+  end
+
+  rl.invokecommand("old-menu-complete")
+end

+
( name:string, value:string ) : boolean

Temporarily overrides the named Readline configuration variable to the specified value. The return value reports whether it was successful, or is nil if the variable name is not recognized.

Note: This does not write the value into a config file. Instead it updates the variable in memory, temporarily overriding whatever is present in any config files. When config files are reloaded, they may replace the value again.


+
rl_buffer

Advances the output cursor to the next line after the Readline input buffer so that subsequent output doesn't overwrite the input buffer display.


+

Starts a new undo group. This is useful for grouping together multiple editing actions into a single undo operation.


+
() : nil

Dings the bell. If the bell-style Readline variable is visible then it flashes the cursor instead.


+

Ends an undo group. This is useful for grouping together multiple editing actions into a single undo operation.

Note: all undo groups are automatically ended when a key binding finishes execution, so this function is only needed if a key binding needs to create more than one undo group.


+
() : string

Returns the current input line.


+
() : integer

Returns the cursor position in the input line.


+
() : integer

Returns the length of the input line.


+
( text:string ) : nil

Inserts text at the cursor position in the input line.


+

Redraws the input line.


+
( from:integer, to:integer ) : nil

Removes text from the input line starting at cursor position from through to.

Note: the input line is UTF8, and removing only part of a multi-byte Unicode character may have undesirable results.


+
( cursor:integer ) : integer

Sets the cursor position in the input line and returns the previous cursor position. cursor can be from 1 to rl_buffer:getlength().

Note: the input line is UTF8, and setting the cursor position inside a multi-byte Unicode character may have undesirable results.


+
settings
( name:string, default:..., [short_desc:string], [long_desc:string] ) : boolean

Adds a setting to the list of Clink settings and includes it in clink set. The new setting is named name and has a default value default when the setting isn't explicitly set.

The type of default determines what kind of setting is added: boolean, integer, and string values add the corresponding setting type. Or if the type is table then an enum setting is added: the table defines the accepted values, and the first value is the default value. Or if it's a string type and the name starts with "color." then a color setting is added.

name can't be more than 32 characters.
short_desc is an optional quick summary description and can't be more than 48 characters.
long_desc is an optional long description.

settings.add("myscript.myabc", true, "Boolean setting")
+settings.add("myscript.mydef", 100, "Number setting")
+settings.add("myscript.myghi", "abc", "String setting")
+settings.add("myscript.myjkl", {"x","y","z"}, "Enum setting")
+settings.add("color.mymno", "bright magenta", "Color setting")

+
( name:string, [descriptive:boolean] ) : boolean or string or integer

Returns the current value of the name Clink setting.

If it's a color setting and the optional descriptive parameter is true then the user friendly color name is returned.


+
( name:string, value:string ) : boolean

Sets the name Clink setting to value and returns whether it was successful.


+
string
( a:string, b:string ) : boolean

Performs a case insensitive comparison of the strings with international linguistic awareness. This is more efficient than converting both strings to lowercase and comparing the results.


+
( text:string, [delims:string], [quote_pair:string] ) : table

Splits text delimited by delims (or by spaces if not provided) and returns a table containing the substrings.

The optional quote_pair can provide a beginning quote character and an ending quote character. If only one character is provided it is used as both a beginning and ending quote character.


+
( text:string ) : integer

Returns a hash of the input text.


+
( a:string, b:string ) : integer

Returns how many characters match at the beginning of the strings, or -1 if the entire strings match. This respects the match.ignore_case and match.ignore_accents Clink settings.

string.matchlen("abx", "a")         -- returns 1
+string.matchlen("abx", "aby")       -- returns 2
+string.matchlen("abx", "abx")       -- returns -1

+
word_classifications
( start:integer, length:integer, color:string, [overwrite:boolean] ) : nil

Applies an ANSI SGR escape code to some characters in the input line.

start is where to begin applying the SGR code.

length is the number of characters to affect.

color is the SGR parameters sequence to apply (for example "7" is the code for reverse video, which swaps the foreground and background colors).

By default the color is applied to the characters even if some of them are already colored. But if overwrite is false each character is only colored if it hasn't been yet.

See Coloring The Input Text for more information.


+
( word_index:integer, word_class:string, [overwrite:boolean] ) : nil

This classifies the indicated word so that it can be colored appropriately.

The word_class is one of the following codes:

CodeClassificationClink Color Setting
"a"Argument; used for words that match a list of preset argument matches.color.arg or color.input
"c"Shell command; used for CMD command names.color.cmd
"d"Doskey alias.color.doskey
"f"Flag; used for flags that match a list of preset flag matches.color.flag
"o"Other; used for file names and words that don't fit any of the other classifications.color.input
"n"None; used for words that aren't recognized as part of the expected input syntax.color.unexpected
"m"Prefix that can be combined with another code (for the first word) to indicate the command has an argmatcher (e.g. "mc" or "md").color.argmatcher or the other code's color

By default the classification is applied to the word even if the word has already been classified. But if overwrite is false the word is only classified if it hasn't been yet.

See Coloring The Input Text for more information.


+
[other]
table variable

Deprecated; don't use this. See line for more information.

This is an obsolete global variable that was set while running match generators. It has been superseded by the line type parameter passed into match generator functions when using the new clink.generator API.


+
+
+
+

Changes

+ +

v1.2.9

+
    +
  • Added detection for possible antivirus interference when injecting Clink.
  • +
  • Ignore duplicate scripts paths when loading scripts.
  • +
  • Fixed #118; inputrc is not read from state directory (regression introduced in v1.0.0).
  • +
+

v1.2.8

+
    +
  • Fixed ...\ or .../ to change directories (path separator after several dots).
  • +
  • Fixed /dirname/ to change directories (forward slashes when a directory is the only thing in the input line).
  • +
  • Fixed #114; "Clink already loaded in process" error when autorun is installed for both Current User and All Users.
  • +
  • Fixed #113; forward slash translation didn't work with the cd command.
  • +
+

v1.2.7

+
    +
  • Fixed #113; clink.slash_translation() had been removed (regression introduced in v1.0.0).
      +
    • The new match.translate_slashes setting controls the default behavior for slash translation for completion matches.
    • +
    • The new clink.translateslashes() API can override slash translation for completion matches (and clink.slash_translation() is supported for backward compatibility).
    • +
    +
  • +
+

v1.2.6

+
    +
  • Fixed tilde expansion for directory by itself; now ~\ can change the working directory to the ~ directory.
  • +
  • Fixed pagination when displaying completions that take more than 1 line to display.
  • +
  • Fixed inserting directory match completions when a Lua script didn't include a trailing path separator in the directory match.
  • +
  • Fixed #111; .. completion is different from bash (regression introduced in v1.0.0).
  • +
+

v1.2.5

+
    +
  • Added os.expandenv() function to expand environment variables in a string.
  • +
  • Added console.cellcount() function to count the cells a string will use when displayed.
  • +
  • Added console.plaintext() function to remove ANSI escape codes from a string.
  • +
  • Clink now sets %=clink.bin% that points to the Clink binaries directory. This can be particularly useful for a portable installation of Clink so that scripts can find the Clink binaries directory and construct relative paths to other nearby files.
  • +
  • Clean up column alignment in --help texts.
  • +
  • Fixed history.sticky_search with anchored history search.
  • +
  • Fixed clink inject --profile to use correct log file name while initially injecting.
  • +
  • Fixed Clink autorun to be more compatible with Cmder (Cmder #2536).
  • +
+

v1.2.4

+
    +
  • Added support for Shift+Arrows to select text and typing to replace selected text.
  • +
  • Added optional argument to word_classifications:classifyword() and word_classifications:applycolor() to allow only applying color where another color hasn't yet been applied.
  • +
  • Fixed first Up after reusing a history line so that it gets the reused history line, rather than getting the previous history line.
  • +
  • Fixed add-history command to not add blank lines to history.
  • +
  • Fixed rl.setmatches() (regression introduced in v1.1.26).
  • +
  • Fixed input coloring for clink set and any color setting name (regression introduced in v1.2).
  • +
  • Fixed potential crash with clink history --session.
  • +
  • Fixed Ctrl+D when cmd.ctrld_exits is disabled; it didn't exit, but it did still discard the input line and start a new prompt.
  • +
  • Fixed #107; autorun reports inject failures (regression introduced in v1.2.3).
  • +
  • Fixed #106; history missing --bare option (regression introduced in v1.2.3).
  • +
+

v1.2.3

+
    +
  • Added history.sticky_search setting: when enabled, reusing a history line does not add the reused line to the end of the history, and it leaves the history search position on the reused line so next/prev history can continue from there (e.g. replaying commands via Up several times then Enter, Down, Enter, etc).
  • +
  • Added failure reporting and logging when clink inject fails.
  • +
  • Added --unique flag for use with clink history compact --unique to remove duplicate entries from the history list.
  • +
  • The clink-popup-complete command now matches wildcards.
  • +
  • Restored the Ctrl+Alt+U key binding from v0.4.9 (moves the current working directory up one level).
  • +
  • Fixed searching for inputrc files to also search in the profile directory (regression introduced in v1.0.0).
  • +
  • Fixed incremental search in the History popup list to search in reverse order (bottom to top).
  • +
  • Fixed clink-popup-history to set the history search position like other history search commands do, so that it plays well with the history.sticky_search setting.
  • +
+

v1.2.2

+
    +
  • Added %CLINK_HISTORY_LABEL% environment variable to use a different master history file (fixes #99).
  • +
+

v1.2.1

+
    +
  • Added Troubleshooting Tips section in the documentation.
  • +
  • Added backward compatibility for clink set with v0.4.9. Old setting names and values are not documented, but are automatically mapped to the appropriate new setting(s). This was done so that suggestions in old web sites and posts can usually continue to work, to reduce confusion and support burden.
  • +
  • Fixed #97; VS2017 error C2039: 'min': is not a member of 'std'.
  • +
  • Fixed #96; wrong setting string (the name of a setting was accidentally truncated).
  • +
  • Fixed some slightly inaccurate/incomplete migration from old settings to new settings.
  • +
+

v1.2

+ +

v1.1.49

+
    +
  • Added clink.classifier() to enable coloring the input line independently from argmatchers.
  • +
  • Added word_classifications:applycolor() to apply SGR escape codes anywhere in the input line.
  • +
  • Removed word_classifications:iswordclassified().
  • +
  • Fixed the Product Version string in the binary file version resources.
  • +
+

v1.1.48

+
    +
  • Added clink.getansihost() function to get Clink's best guess who will process ANSI escape codes (can be useful for avoiding 256 bit and 24 bit color codes, for example).
  • +
  • Added detection for being hosted in ConsoleZ.
  • +
  • Fixed #20; set /p VAR="" shows the normal command prompt text instead of empty prompt text.
  • +
+

v1.1.47

+
    +
  • Added default key binding for Ctrl+Space to invoke old-menu-complete, which is the most similar to CMD's standard Tab behavior.
  • +
  • Fixed search-ignore-case config variable to be on by default.
  • +
+

v1.1.46

+
    +
  • Added rl.setvariable() to temporarily override the value of a Readline config variable.
  • +
  • The completion commands now also expand tilde by itself (~), in addition to tilde followed by a path separator (~\etc).
  • +
  • Fixed #94; setting history.save to False also disables interactive history in subsequent sessions.
  • +
+

v1.1.45

+
    +
  • Fixed #93; stdout is sometimes broken by Cmder init.bat.
  • +
+

v1.1.44

+
    +
  • Added clink.getsession().
  • +
  • Added %CLINK_NOAUTORUN% which overrides automatic inject when Clink is installed for autorun.
  • +
  • Fixed #92; clink-popup-history and similar commands not working with ConEmu and Cmder (regression introduced in v1.1.25).
  • +
+

v1.1.43

+
    +
  • Added clink history --diag flag that prints diagnostic information while performing history operations.
  • +
  • Minor optimization in clink history when printing the full list of history items.
  • +
  • Fixed clink history compact so it actually performs compaction.
  • +
+

v1.1.42

+
    +
  • Added clink history --bare flag to omit history item numbers.
  • +
  • Added several Lua functions:
      +
    • io.popenrw() is like io.popen(), but returns both a read file handle and a write file handle (see documentation for important usage warning).
    • +
    • os.createtmpfile() creates a unique named temporary file, with control over the prefix and suffix and path.
    • +
    • os.getfullpathname() to get the full path name for a file.
    • +
    • os.getlongpathname() to get the long path name for a file.
    • +
    • os.getshortpathname() to get the 8.3 short path name (if available) for a file.
    • +
    +
  • +
  • Improved argument validation for Clink's Lua APIs. This could expose bugs in existing scripts, so there is also a lua.strict setting that can be disabled to revert back to loose argument validation.
  • +
  • Updated documentation.
  • +
  • Fixed clink history compact so that it forces compaction as intended.
  • +
  • Fixed completion for clink set so that filename completion works in string settings.
  • +
  • Fixed backwards return value from rl.invokecommand().
  • +
  • Fixed console input/output modes across luafunc: key bindings, in case the Lua functions spawn a process that alters the console mode without restoring it.
  • +
+

v1.1.41

+
    +
  • Added terminal.adjust_cursor_style setting as a workaround to avoid interfering with the Windows 10 Cursor Shape console setting. There are several trade-offs, though.
  • +
  • Added rl_buffer:refreshline() function to redraw the input line, e.g. in case something has written over it.
  • +
  • Added os.getpid() function to get the process ID, intended mainly to help salt unique resource names.
  • +
  • Added clink.onfiltermatches() so scripts can register a callback function to run after Clink generates matches and before it displays them.
  • +
+

v1.1.40

+
    +
  • Added a group of clink-complete-numbers commands that do completion for numbers from the console screen, bound to Ctrl+Alt+N by default.
  • +
  • Added rl.getlastcommand() function that returns the name of the last command invoked by key bindings.
  • +
  • Fixed sort order in Alt+H for the newly supported key bindings (that were added in v1.1.39).
  • +
  • Fixed Ctrl+Space (regression introduced in v1.1.39).
  • +
  • Fixed various Ctrl+Shift+whatever combinations (regression introduced in v1.1.39).
  • +
  • Fixed rl.setmatches() when the input line is not empty and clink.colorize_input is enabled.
  • +
+

v1.1.39

+
    +
  • Added support for many more key bindings, such as Ctrl+Shift+Letter keys.
  • +
  • Added terminal.differentiate_keys setting that when enabled allows binding Ctrl + H or I or M or [ separately from Backspace, Tab, Return, or Escape.
  • +
  • Removed terminal.modify_other_keys setting and made it always enabled.
  • +
  • Changed terminal.use_altgr_substitute to be disabled by default so that Ctrl+Alt key bindings can work by default on keyboards with AltGr.
  • +
  • Changed output from clink echo so it's directly usable in the inputrc files.
  • +
  • Fixed terminal.use_altgr_substitute to only affect AltGr substitute key combinations (it had always broken the RightAlt key in general on other keyboard layouts).
  • +
  • Fixed a benign issue with the console input mode in clink echo.
  • +
+

v1.1.38

+
    +
  • Fixed #84; added terminal.use_altgr_substitute setting.
  • +
  • Fixed #80; clink.log is not deleted when Cmder injects Clink.
  • +
+

v1.1.37

+
    +
  • Fixed copy to clipboard (it never cleared the clipboard!).
  • +
  • Fixed #82; added two new clink.paste_crlf modes: ampersand replaces newlines with ampersands, and crlf pastes newlines as-is and executes any commands ending in a newline.
  • +
  • Fixed #69; space in the prompt disappears after enter echo: added support for CJK codepages.
  • +
+

v1.1.36

+
    +
  • Fixed #79; Issue with United States - international keyboard layout (regression introduced in v1.1.0).
  • +
  • Fixed #78; crash when history file contains a line longer than 8192 characters (regression introduced in v1.1.2-alpha).
  • +
+

v1.1.35

+
    +
  • Fixed when the mark-directories inputrc variable is off (regression introduced in v1.1.1-alpha).
  • +
  • Fixed Lua reading from stdin, especially in the Lua debugger (regression introduced in v1.1.25).
  • +
  • Fixed exponential cost performance bug in Readline when removing duplicate matches.
  • +
+

v1.1.34

+
    +
  • Fixed copying to clipboard (CF_UNICODETEXT was put on the clipboard correctly, but CF_TEXT was empty and should have been omitted to let Windows automatically convert it from the Unicode text).
  • +
+

v1.1.33

+
    +
  • Make the "replacing arglink" warning message a little more informative, and write a lua traceback to the Clink log file.
  • +
  • Fixed #77; with ConsoleZ scrolling does not always work.
  • +
  • Fixed #76; cannot cd up multiple directories normally.
  • +
+

v1.1.32

+
    +
  • Added support for non-standard escape codes to set the window title or print environment variables. Depending on the terminal.emulation setting, the behavior is slightly different. When emulate Clink processes the escape codes. When native with ConEmu (and Clink) the escape codes are passed to ConEmu, except that Clink processes the environment variable codes in prompt strings. When native with other terminals, Clink preprocesses the title and environment variable escape codes in prompt strings, but passes the escape codes to the terminal outside of prompt strings.
  • +
  • Fixed #67; AutoRun interferes with Cmder.
  • +
+

v1.1.31

+
    +
  • Fixed #74; clink gets confused by non-standard ConEmu escape codes.
  • +
  • Fixed #73; exec.space_prefix and other settings defined in Lua scripts don't take effect until second input line (regression introduced in v1.1.4).
  • +
+

v1.1.30

+
    +
  • Fixed history compacting on x86 (regression introduced in v1.1.2-alpha).
  • +
+

v1.1.29

+
    +
  • Added clink installscripts and clink uninstallscripts to make it easy for package managers like Scoop to install/uninstall script packages for use with Clink. The installed script paths are stored in the registry for the current user.
  • +
  • Fixed bold vs bright colors to more accurately follow generally accepted ANSI escape code conventions:
      +
    • Renamed dim to nobold for clarity (though dim is still recognized for backward compatibility).
    • +
    • bold adds intensity to a non-intense color (e.g. cyan which is 36).
    • +
    • nobold removes intensity added by bold (e.g. 1;36 becomes 36), but does not remove intensity from an explicit intense color (such as bright cyan which is 96).
    • +
    +
  • +
  • Fixed support for --file= flags in argmatchers.
  • +
  • Fixed match display filtering on the first try for a word (regression introduced in v1.1.19).
  • +
  • Fixed the clink --profile flag (regression introduced in v1.1.10).
  • +
  • Fixed clink info to accurately report the script dirs (it didn't account for the clink.path setting correctly).
  • +
+

v1.1.28

+
    +
  • Renamed the log.rl_terminal setting to debug.log_terminal; it has already been repeatedly very useful in multiple was since it was added, so it stays.
  • +
  • Fixed #70; ctrl+c not working (regression introduced in v1.1.25).
  • +
+

v1.1.27

+
    +
  • Added color.argmatcher setting which, when set, is used to color a command name if it has an associated argmatcher (this supersedes color.cmd, color.doskey, and color.input). By default it's not set.
  • +
  • Added log.rl_terminal setting which logs all terminal input and output for Readline (this setting may be renamed or removed in the future).
  • +
+

v1.1.26

+
    +
  • Added rl.invokecommand() which can invoke a Readline command from inside a "luafunc:" key binding.
  • +
  • Added rl.setmatches() which can override match completions from inside a "luafunc:" key binding.
  • +
  • Worked around UTF8 key binding problem with Readline which had been causing some meta key bindings (M-x, M-C-x, etc) to sometimes produce garbled key bindings and garbled entries in clink-show-help (Alt+H).
  • +
  • Fixed crash if "luafunc:" key binding macro refers to a symbol that doesn't exist.
  • +
+

v1.1.25

+
    +
  • Added clink-find-conhost command that, when in a default (conhost) console window, is equivalent to picking "Find..." from the system menu.
  • +
  • Added clink-mark-conhost command that, when in a default (conhost) console window, is equivalent to picking "Mark" from the system menu.
  • +
  • clink-copy-word now copies the current word by default, but copies the nth word if a numeric argument is entered (see "Readline Arguments" in the Readline manual).
  • +
  • Fixed match display filtering to not exceed the screen width (regression introduced in v1.1.12).
  • +
  • Fixed multi-key sequences; in some cases it could get confused about whether an input key is part of a multi-key binding sequence (regression introduced in v1.1.1-alpha).
  • +
  • Fixed stray input processing by conhost (holding Ctrl+A or Ctrl+F or etc could accidentally trigger conhost's shortcut keys).
  • +
  • Fixed popup window location and size when using Windows Terminal.
  • +
  • Fixed input coloring after operate-and-get-next; also fixes brief flicker of incorrect coloring whenever the input line is modified.
  • +
+

v1.1.24

+
    +
  • auto for terminal.emulation now uses native VT support on Windows 10 build 15063 and higher, unless the HKCU\Console\ForceV2 regkey is 0.
  • +
  • Special quote handling now enables "dir\"fi to complete to "dir\file". CMD simply strips quotes during completion, and now Clink behaves similarly.
  • +
  • Breaking Change: line:getword() and line:getendword() now strip quotes from the word. This should generally automagically make existing match generators work even with embedded quotes, but there's a chance that some match generator might need to be updated. This seems like a reasonable compromise, given the general benefit purchased by this breaking change.
  • +
  • os:globdirs() and os:globfile() strip quotes from the globpattern in order to behave more like CMD. Embedded quotes are nonsensical and the intended interpretation is clear, so the APIs now help out with that.
  • +
  • Fixed #66; crash when injecting into 32 bit cmd (regression introduced in v1.1.21).
  • +
  • Fixed #64; wrong cursor position when PROMPT contains BEL character.
  • +
  • Fixed #62; argmatchers should color -x:"foo" as a flag if -x: is a flag.
  • +
  • Fixed #61; argmatchers should not handle completion for text immediately following -flag:. Instead it always uses file completion. A custom generator can be used to override that behavior.
  • +
  • Fixed #60; completion fails with multiple slashes.
  • +
  • Fixed completion in some circumstances. Readline and Clink didn't always agree on where the word breaks were; now Clink always tells Readline where the word breaks are (so that completion, input colorization, and lua scripts can all work properly and consistently).
  • +
  • Fixed 256 color ANSI codes.
  • +
+

v1.1.23

+
    +
  • Fixed #57; slashes not normalized in some cases.
  • +
  • Fixed #45; interaction between history.dupe_mode=erase_prev and history.shared=false.
  • +
  • Fixed menu-complete-wraparound when off and there's only 1 match.
  • +
+

v1.1.22

+
    +
  • Added menu-complete-wraparound (on by default) that controls whether completion commands wrap around when cycling past an end (affects popup windows as well).
  • +
  • Fixed match completion getting stuck (regression introduced in v1.1.19).
  • +
  • Fixed active mark region so it gets deactivated appropriately (it wasn't hooked up fully for Readline's callback mode, which is the mode Clink uses).
  • +
  • Fixed clink-show-help (Alt+H) so it's able to list C-@ bindings.
  • +
  • Fixed inconsistent mark color.
  • +
+

v1.1.21

+
    +
  • Added clink.oninject() so scripts can register a callback function to run when Clink is injected into CMD.
  • +
  • Added console.linehascolor() function that returns whether the specified line contains any of the specified colors.
  • +
  • Added console.findprevline() and console.findnextline() functions that can search backwards or forwards for text and/or colors in the screen buffer. Regular expressions may be used.
  • +
  • Fixed doskey alias parsing for match generators and input line coloring (Clink had been using slightly different parsing rules than CMD does).
  • +
  • Fixed the "-- More --" prompt while listing key bindings; Esc didn't quit, and unexpected keys weren't ignored.
  • +
+

v1.1.20

+
    +
  • Now you can bind Lua functions to keys via "luafunc:" macros! Added new rl_buffer type that gets passed to the Lua function.
  • +
  • Added a group of console Lua APIs intended mainly for use by Lua function key bindings (e.g. console.scroll()).
  • +
  • Added string.equalsi() function that performs a case insensitive UTF8 comparison of two strings.
  • +
  • Added string.matchlen() function that compares two UTF8 strings and returns how many characters match at the beginning, or -1 if the entire strings match. It respects the match.ignore_case and match.ignore_accents settings.
  • +
  • Added path.toparent() function that adjust the input string by moving up one directory level.
  • +
  • Added clink.onendedit() so scripts can register a callback function to run when editing finishes (e.g. Enter is pressed). If desired, the function can even change the input text. This is very powerful, and should be used carefully.
  • +
  • Changed os.getbatterystatus() to return a table with the battery status details, rather than four separate return values.
  • +
  • Fixed the doskey.enhanced setting to not expand doskey aliases when preceded by a space. However, a doskey alias after a & or | command separator needs to be preceded by two spaces to avoid expanding it. That's so alias & alias expands both, and alias & alias expands neither; while the rules are more complicated to explain, they make more sense visually.
  • +
  • Fixed environment variable completion (regression introduced in v1.1.19).
  • +
  • Fixed Cmder startup (regression introduced in v1.1.17). Cmder expects to be able to replace Clink v0.4.9's clink.lua file, but there is no such thing anymore in newer versions of Clink. To be properly backwardly compatible with Clink v0.4.9 requires loading clink.lua (if it exists) from the first script directory listed by clink info, and ignoring clink.lua files in all other script directories.
  • +
+

v1.1.19

+
    +
  • Improved responsiveness while typing: matches are collected only on demand, instead of always while typing. This makes it possible to always support match completion for UNC paths.
  • +
  • Fixed #50; Alt+H could warn about likely mistakes in key bindings.
  • +
+

v1.1.18

+
    +
  • The input text now has context sensitive coloring based on the argmatchers. It's on by default and can be turned off with clink set clink.colorize_input false.
  • +
  • Updated the Readline library to 8.1.
  • +
  • Terminal emulation now supports the audible bell character.
  • +
  • Fixed #48; menu-complete gets stuck.
  • +
  • Fixed #47; Alt+D erases history instead of word.
  • +
  • Fixed #46; typing .. in subdirectory of root doesn't work.
  • +
  • Fixed restoring color after pager when showing help.
  • +
  • Fixed clink set match completions for color settings.
  • +
+

v1.1.17

+
    +
  • Added os.getbatterystatus() function that gets battery status information much faster than launching wmic.
  • +
  • Fixed #44; Path completion doesn't work with cd /d.
  • +
  • Fixed loading scripts to ignore loading clink.lua, so that loading scripts behaves like Clink v0.4.9.
  • +
+

v1.1.16

+
    +
  • Added match.ignore_accent setting (enabled by default) that ignores Latin alphabet diacriticals when completing matches (e.g. ä matches a, ı matches i, ł matches l, etc).
  • +
  • Fixed #42; history lines are split on special characters.
  • +
  • Fixed #41; Enable custom doskey handling of .. and -.
  • +
  • Fixed Readline bug inserting dir matches; \win_ foo (cursor at _) would become \Windows\\_ foo.
  • +
  • Fixed the quoted-insert command to insert just \x1b when ESC is pressed.
  • +
+

v1.1.15

+
    +
  • Migrating settings now immediately writes a new settings file, instead of waiting until a setting is changed.
  • +
  • Added support to detect when running in Windows Terminal and use native terminal support (which enables things like Xterm 256 and 24-bit color support).
  • +
  • Added terminal emulation support for Xterm 256 and 24-bit color escape codes. Clink maps the specified color to the most similar color in the active 16 color palette (using the CIELAB color space). To get full support for 24-bit color, it's necessary to use ConEmu or Windows Terminal or a similar console host, or to set terminal.emulation to native (which isn't supported on some older Windows OS versions).
  • +
  • Allow doskey macros named .. or -, and also now doskey macros that resolve to .. or - or a directory name will work (just like if the macro text had been typed at the Clink prompt).
  • +
  • Fixed compatibility problem with various scripts getting the %HOME% environment variable. Now if it isn't set, then Clink synthesizes %HOME% from %HOMEDRIVE% and %HOMEPATH% or from %USERPROFILE%.
  • +
  • Fixed saving color settings to behave like other settings: only write a setting's value to the setting file if it differs from the default value.
  • +
  • Fixed the clink.print() Lua function so it also works during loading scripts and during prompt filtering.
  • +
  • Fixed the Readline input text display getting garbled if the filtered prompt includes Xterm's OSC window title code (\x1b]0;text\x07). Clink doesn't support that escape code, but at no longer garbles the input text if that escape code is present.
  • +
+

v1.1.14

+
    +
  • Migrate settings and history from an old version of Clink, if present. This only happens if the new-version Clink settings or history files don't exist. (Deleting an existing new-version Clink settings or history file will cause migration to happen again.)
  • +
  • Added color.prompt setting for backward compatibility with Clink v0.4.x.
  • +
+

v1.1.13

+
    +
  • Fixed clink.arg.register_parser backward compatibility.
  • +
+

v1.1.12

+
    +
  • Added clink.ondisplaymatches() as a replacement for the deprecated clink.match_display_filter. The new API is able to support popup list windows as well.
  • +
  • Speculative possible fix for #35 Crash when clink on clink.bat.
  • +
  • Fixed #33; Tab autocomplete, auto-quoting paths doesn't seem to work as in Clink 0.4.9.
  • +
+

v1.1.11

+
    +
  • Changed to load Lua scripts only once per session, unless forced to reload them. This enables backward compatibility for things like z.lua which has certain features that rely on Clink only loading scripts once per session.
  • +
  • Added clink.onbeginedit() so scripts can register a callback function to run each time the edit prompt is activated.
  • +
  • Added lua.reload_scripts setting to optionally force reloading Lua scripts each time the edit prompt is activated.
  • +
  • Added color.message setting for the Readline message area color (e.g. the search prompt message or digit argument prompt message, etc).
  • +
  • Fixed stray sticky = appended to completions after typing set and then typing a different command.
  • +
+

v1.1.10

+
    +
  • Fixed #32; hooking ReadConsoleW on Windows 7.
  • +
+

v1.1.9

+
    +
  • Added backward compatibility for clink.match_display_filter. The clink-completions/git.lua script uses it a lot, and that should all be working now.
  • +
  • settings.add adds a color setting when the type is string and the name starts with "color.".
  • +
  • settings.get now has an extra parameter to request the user friendly color name when getting a color setting.
  • +
  • Added clink.version_encoded variable with the Clink version number as MMmmmpppp (e.g. v1.1.9 is 10010009) to make it easy for scripts to check for feature availability.
  • +
  • The clink info command now shows Lua script paths as well.
  • +
  • Fixed backward compatibility for loading scripts from the profile directory (if clink.path isn't set, then load scripts from the DLL directory and the profile directory).
  • +
  • Fixed some color.input bleed through to other things (introduced in v1.1.5).
  • +
  • Fixed scroll commands (regression introduced by input line color in v1.1.5).
  • +
  • Fixed horizontally sorted match display and re-enabled the performance fix from v1.1.4.
  • +
  • Fixed wildcard evaluation with non-file and non-directory matches (e.g. a branch name origin/master accidentally didn't match or or *ma because of the /).
  • +
  • Fixed sort order of foo\ vs foo.bar\ when displaying matches or using the menu-complete family of commands.
  • +
  • Fixed potentially-missing trailing path separator when menu-complete completes a directory match (regression introduced by wildcard matching in v1.1.5).
  • +
  • Other obscure minor fixes.
  • +
+

v1.1.8

+
    +
  • Fixed file match completions when an argmatcher only generates flag matches.
  • +
  • Fixed automatic inferring whether Readline should use filename completion and/or display rules (regression introduced by backward compatibility in v1.1.3-alpha).
  • +
  • Fixed backward compatibility for clink.find_files() and clink.find_dirs() (regression introduced by performance improvement in v1.1.7).
      +
    • Ignore extra arguments after the first one (the performance improvement in v1.1.7 revealed that some scripts call clink.find_files() with extra invalid arguments; e.g. clink-completions/modules/matchers.lua).
    • +
    • Don't append a trailing path separator on directory names returned by these functions (the new os.globfiles() and os.globdirs() functions do, but the old clink.find_files() and clink.find_dirs() functions should not).
    • +
    +
  • +
  • Fixed backward compatibility for coloring matches (regression introduced by backward compatibility changes in v1.1.4).
  • +
+

v1.1.7

+
    +
  • Performance improvement when displaying matches: When enumerating files and dirs, the os.globfiles and os.globdirs functions have all the info about each file. Now they can return that info in a table. This frees the match display function from needing to do any further file system IO. The performance boost is noticeable.
  • +
  • Rewrote the color settings: the .fg and .bg sub-settings are gone, and the main setting now uses a more natural syntax (e.g. clink set color.input bright yellow or clink set color.modmark bright cyan on blue).
  • +
  • Added "cmd" match type for shell (CMD.EXE) command completions.
  • +
  • Added VT emulation for the reverse video SGR parameters.
  • +
  • Fixed tab completion for clink set setting, and also handle the new color setting syntax.
  • +
  • Fixed confusing behavior if multiple scripts try to add settings with the same name (now the first one succeeds and the rest report errors).
  • +
+

v1.1.6

+
    +
  • Hooked up tilde completion in the cd, md, and rd command argmatchers.
  • +
  • Hooked up tilde completion with the exec.enable setting ("~\pro" matches "C:\Users\myusername\program.exe").
  • +
  • When terminal.emulation is auto, now it also detects ANSI{32|64}.DLL just like Clink 0.4.8 did.
  • +
+

v1.1.5

+
    +
  • The menu-complete family of commands now support matching ? and * wildcards when the match.wild setting is enabled.
  • +
  • Added colour.input and colour.modmark settings for coloring Readline's input line.
  • +
  • Added clink.upper() Lua function, and both clink.lower() and clink.upper() are properly UTF8 aware now.
  • +
  • Added clink-copy-word command that copies the word at the cursor to the clipboard.
  • +
  • Added clink.promptfilter setting to control whether to filter the prompt with Lua scripts.
  • +
  • Renamed terminal.emulate setting to terminal.emulation.
  • +
  • Improved executable file extension logic to consistently use %PATHEXT% (and efficiently).
  • +
  • Improved file extension logic (e.g. "file.foo bar" has no extension because of the space).
  • +
  • Updated arg matcher for clink itself (was missing some flags).
  • +
  • Changed colour.hidden setting to not be set by default.
  • +
  • Fixed #28; Tab completion for "~" does not work.
  • +
  • Fixed #25; Unicode surrogate pairs (and emoji) input isn't working -- Microsoft Terminal renders the text correctly, but ConEmu and the default conhost still don't (and that isn't a Clink issue).
  • +
  • Fixed screen size bug in Readline on Windows.
  • +
  • Fixed the backwards values in the terminal.emulation setting.
  • +
  • Fixed .... so it works properly again.
  • +
  • Fixed case sensitive sorting of matches.
  • +
  • Fixed script error when %PATHEXT% is empty.
  • +
  • Fixed the exec.cwd Clink setting to default to true, so that the default behavior is consistent with how v0.4.x behaved.
  • +
  • Fixed the cd, md, rd, etc argmatchers to only match one argument to be consistent with the actual command syntax.
  • +
+

v1.1.4

+
    +
  • Automatically detect when running inside ConEmu and disable Clink's Virtual Terminal emulation.
  • +
  • Added search-ignore-case inputrc variable that makes the history search commands case insensitive.
  • +
  • Suppress adding a space after completing a flag match that ends with : or = (e.g. msbuild -maxCpuCount:).
  • +
  • Report any errors while loading Lua scripts.
  • +
  • Report an error if a Lua script tries to add a flag string that begins with a letter.
  • +
  • Fixed slow printing of possible matches. Readline is inefficient about emitting output, so Clink supplies a custom implementation.
  • +
  • Fixed some bugs in auto detection of flag prefix characters.
  • +
  • Fixed backward compatibility for flags, and for args when merging two parsers by calling clink.arg.register_parser('foo') multiple times for the same command string.
  • +
  • Fixed truncated message when the last line of a prompt exceeds 128 characters.
  • +
  • Fixed abort (Ctrl+G or Esc) in non-incremental history search mode.
  • +
  • Fixed saved values for settings added by Lua scripts; now the saved value is available to the script immediately on adding the setting, and saved values are retained even if the setting isn't always added by the script.
  • +
  • Fixed (and documented) shorthand form for defining an argmatcher.
  • +
  • Fixed length of colored match prefix after a path separator.
  • +
  • Fixed normalizing a slash by itself (command / mustn't become command \ since that can interfere with completing flags).
  • +
  • Fixed the completion-auto-query-items inputrc variable.
  • +
  • Fixed the key binding list to correctly respect completion-display-width.
  • +
  • No visible effect yet: internal change that parses the input line to identify colors to use for each word (command, argument, flag, etc), but the colors aren't yet applied to the input line.
  • +
+

v1.1.3-alpha

+
    +
  • Fixed argmatcher lookup to be more strict, like in Clink 0.4.9 (match exact names, or name plus an extension from %PATHEXT%).
  • +
  • Backward compatibility:
      +
    • Most things should work now.
    • +
    • Dropping the new Clink on top of the vendor\clink directory in Cmder seems to work -- but make a backup before you try this at home!
    • +
    +
  • +
  • API changes:
      +
    • Added log.info() function.
    • +
    • Added Clink version numbers in clink.version_major, etc.
    • +
    • Added _argmatcher:getwordbreakinfo() callback; removed _argmatcher:setprefixincluded() (it was a mess, and it was new to v1.x, so there's no compatibility concern with removing it).
    • +
    • Deprecated _argmatcher:setflagprefix(); now it happens automagically when using _argmatcher:addflags().
    • +
    • Introduced several deprecated functions to support backward compatibility.
    • +
    +
  • +
  • Improvements to Lua debugger:
      +
    • Added lua.traceback_on_error, lua.break_on_error, and lua.break_on_traceback settings to make debugging script errors easier.
    • +
    • Made pause() consistent about pausing in the caller (rather than sometimes inside the pause command itself).
    • +
    • The debugger automatically shows the stack trace when entering debug mode, and on every pause.
    • +
    • Show 3 lines of source context by default.
    • +
    • The help list is sorted now.
    • +
    • Fixed the set command in the debugger to behave as documented.
    • +
    +
  • +
+

v1.1.2-alpha

+
    +
  • Documentation is mostly updated; just the argmatcher Lua API and Clink command line options are left to be documented.
  • +
  • Added history.max_lines setting that controls how many lines of command history to save (1 to 50000, default is 2500).
  • +
  • Added readline.hide_stderr setting that can suppress stderr output from the Readline library.
  • +
  • For backward compatibility with 0.4.8, clink_inputrc files are loaded as well.
  • +
  • Lua script API changes:
      +
    • addmatch() in Lua scripts takes an optional match type argument.
    • +
    • Removed displayable, aux, and suffix fields in matches.
    • +
    • Revert the change to disallow mixing file/directory/symlink with other match types (it broke the tests and certain completion scenarios).
    • +
    +
  • +
  • Fixed issues:
      +
    • #18 alt+digit then alt+ctrl+y isn't working.
    • +
    • #17 arrow keys don't exit reverse-search-history like in bash.
    • +
    • #16 problems with $T in doskey macros.
    • +
    • #13 clink history delete <n> returns a CRT error.
    • +
    +
  • +
  • Other fixes:
      +
    • There should be no more problems running on Windows Insider builds because Clink now uses Detours for hooking APIs.
    • +
    • Fixed crash in insert-completions due to heap failure (introduced by the performance changes for displaying matches).
    • +
    • Fixed clink and history built-in aliases (solve glitchy path problem).
    • +
    • Fixed scrolling to top of screen buffer.
    • +
    • Fixed env var and set completions.
    • +
    • Fixed tilde-expand for quoted text.
    • +
    • Fixed Esc in Readline's digit argument input mode (it doesn't try to cancel the mode, because that's not how Readline is documented to work).
    • +
    • Fixed exit code from some clink command line options.
    • +
    +
  • +
  • Set locale to UTF8 much earlier to avoid quirky behavior early in script processing.
  • +
+

v1.1.1-alpha

+
    +
  • Exclusively use Readline's completion implementation. This (with fixes and enhancements in Readline itself) makes the completion experience much nicer and more sophisticated, and removes a lot of code that was added in v1.0.0a0.
  • +
  • Exclusively use Readline's key binding implementation. This makes it possible to have a single consistent way to set key bindings (inputrc) and for clink-show-help to list all key bindings, and removes a lot of code that was added in v1.0.0a0.
  • +
  • Converted all of Clink's internal key behaviors to be implemented as commands that can be bound in the inputrc file.
  • +
  • Rewrote and refactored the pagination routine to be used in multiple places.
  • +
  • Fixed prompt filtering to correctly use the specified priority order.
  • +
  • Readline library:
      +
    • Updated the Readline library from v6.2 to v8.0. This picked up lots of bug fixes and new capabilities (for example colored completions).
    • +
    • Changed Readline to support backslash as a path separator.
    • +
    • The pager prompt in Readline is optionally colored, controlled by the colour.interact Clink setting.
    • +
    • Added completion-auto-query-items config variable (on by default) which asks whether to list possible matches when the number of lines listed will fill one screen page.
    • +
    • Added history-point-at-end-of-anchored-search config variable in inputrc to make the cursor point behave like 4Dos/4NT/TakeCommand when searching forward and backward through command history.
    • +
    • Fixed prev history at top of history.
    • +
    • Fixed to get the current values of environment variables when needed, rather than always getting the value from whenever Clink was started.
    • +
    • Fixed coloring directory completions.
    • +
    • Fixed menu-complete for \dir and . and ...
    • +
    • Fixed slow performance when displaying matches. Readline was calling stat() at least once per match (!!). A new match type field enables faster performance, coloring readonly and hidden file matches, applying filename completion rules only to filenames (vs branch names or other text strings), correct match de-duplication, and more. The Lua match APIs can supply the new match type.
    • +
    • Fixed inserting a completion to happen as a single undo group.
    • +
    • Fixed tilde to map to %USERPROFILE% instead of %APPDATA% on Windows.
    • +
    +
  • +
  • Typing a directory by itself uses cd /d to change to the directory:
      +
    • Typing a directory with a trailing path separator changes to the directory.
    • +
    • Typing ..\ changes to the parent directory.
    • +
    • Typing ... or .... etc moves up an extra parent directory level for each extra dot (2 dots move up one parent, 3 dots moves up two parents, etc). A trailing path separator is optional when there are more than 2 dots.
    • +
    • Typing - or cd - or chdir - changes to the previous directory.
    • +
    +
  • +
  • Commands that are new, enhanced, or fixed:
      +
    • Added add-history and remove-history commands (similar to 4Dos/4NT/TakeCommand).
    • +
    • Got the menu-complete, menu-complete-backward, and old-menu-complete commands working (they never worked properly before in Clink).
        +
      • Also added a corresponding old-menu-complete-backward command for reverse order.
      • +
      • All of the *-menu-complete-* commands support wildcards (* and ?).
      • +
      +
    • +
    • Added clink-show-help command (Alt+H). The help now lists all key bindings, and it shows user-friendly key names (like A-Up or C-x,C-r or C-S-PgUp or A-C-S-F3).
    • +
    • Added clink-popup-completions command that shows a popup window listing possible completions. Enter inserts the highlighted completion.
    • +
    • Added clink-popup-directories command that shows a popup window listing recent directories. Enter changes to the highlighted directory, or Shift+Enter inserts the highlighted directory in the editing line (or Ctrl+Enter).
    • +
    • Added clink-popup-history command that shows a popup window listing command history. Enter executes the highlighted command, or Shift+Enter jumps to the highlighted command in the history (or Ctrl+Enter).
    • +
    • Added clink-scroll-lineup, clink-scroll-linedown, clink-scroll-page-up, clink-scroll-page-down, clink-scroll-top, and clink-scroll-bottom commands that do what it looks like they'd do and are bound to the keys it looks like they'd be.
    • +
    • Added clink-expand-doskey command (Ctrl+Alt+f) that expands the current line according to the current doskey aliases.
    • +
    • Added clink-expand-env-var command (Ctrl+Alt+e) that expands the environment variable at the cursor point.
    • +
    • Added clink-exit command (Alt+F4) that exits CMD.
    • +
    +
  • +
  • Fixed keyboard input issues:
      +
    • Esc is a bindable key now (\e[27;27~).
    • +
    • Added more bindable key combinations (run clink echo then press keys to see the key sequence to use in the inputrc file).
    • +
    • Ctrl+@ (NUL) didn't work.
    • +
    • Ins toggles insert/overwrite mode.
    • +
    • Unbound keys are ignored now, instead of inserting gibberish characters (part of the terminal internal key sequence).
    • +
    • Fixed input handling so the quoted-insert command can work properly.
    • +
    • Fixed Esc while searching.
    • +
    • Fixed vi mode (was working in v0.4.9, but not in v1.0.x).
    • +
    +
  • +
  • Fixed command history issues:
      +
    • The dont_add_to_history_cmds Clink setting is a space-delimited list of commands to not add to history.
    • +
    • Fixed bleeding between history banks.
    • +
    • Fixed uninitialized variable that made history updates intermittently do nothing or corrupt the other history bank.
    • +
    • Fixed output from clink history to convert to UTF16 when writing to the console (but write UTF8 when output is redirected).
    • +
    +
  • +
  • Fixed terminal output issues:
      +
    • Added terminal.emulate Clink setting that controls whether Clink does VT emulation or passes all ANSI escape codes directly to the console host. For example, this lets the prompt and completion coloring take advantage of more sophisticated ANSI escape codes such as XTerm 256 color and 16 bit color support.
    • +
    • Added back support for the prefer-visible-bell config variable.
    • +
    • Fixed underline support.
    • +
    • Fixed handling for UTF8 output from Readline.
    • +
    • Fixed invisible cursor point in Lua debugger.
    • +
    +
  • +
  • Completions:
      +
    • Added match.sort_dirs Clink setting that specifies where to sort directories in the list of possible completions: before files, mixed in with files, or after files.
    • +
    • Don't attempt completing incomplete UNC paths: at least the \\server\share\ path components are required (for anything shorter the OS APIs are guaranteed to fail, but will fail slowly).
    • +
    • Fixed sorting to use Unicode aware locale based sorting (like Windows does) instead of dumb UTF8 byte comparisons.
    • +
    • Fixed arbitrary limit on completions (had been limited to 64KB worth of completions).
    • +
    • Fixed quoting spaces in completions.
    • +
    • Fixed to use the same list as CMD for characters that require quoting.
    • +
    • Fixed normalizing UNC paths.
    • +
    • Fixed volume relative completions (e.g. x:foo).
    • +
    • Disallow mixing file/directory/symlink with other match types. This was to avoid a confusing/malfunctioning case in match display and prefix highlighting.
    • +
    +
  • +
  • Fixed UTF8 encoding in various Lua functions.
  • +
  • Fixed printing stderr output from Readline, Lua, and Clink.
  • +
  • Fixed crashes and other failures when starting Clink in 32 bit CMD.
  • +
  • Fixed some memory leaks that accumulated with each new line of input.
  • +
  • Fixed prompt filtering API to be backward compatible with v0.4.9 scripts.
  • +
  • Fixed Lua errors from clink set (it neglected to fully initialize Clink's Lua integration before loading Lua scripts).
  • +
  • Fixed UTF8 conversion bug that could truncate a string without fully converting it.
  • +
  • Fixed serious rampant memory corruption bug in v1.0.x (not present in v0.4.9), which had been causing intermittent malfunctions and data corruption and crashes.
  • +
  • Fixed multi-line doskey macros to show the prompt in between lines, like CMD does.
  • +
  • Removed the 4096 byte limit on input.
  • +
  • Renamed the Clink DLL back to what it was in v0.4.x, to fix compile time problems.
  • +
  • Other fixed issues: +
  • +
  • Fixed many other bugs.
  • +
+ +

v1.0.0a1 (alpha test release)

+
    +
  • Improve terminal integration with the Readline library.
  • +
  • Internal improvements to the built-in ecma48 terminal emulator.
  • +
  • Fixed use after free in Doskey emulation.
  • +
  • Fixed dash-dash flag completion.
  • +
  • Search ancestors for a compatible target process (for when cmd.exe starts another process that subsequently starts clink; especially useful during development).
  • +
  • Use clink/terminal's wcwidth() implementation.
  • +
  • screen_buffer::set_cursor() should be relative to the visible area.
  • +
  • Try to adjust the cursor position better when resizing the terminal.
  • +
  • Some internal Lua functions needed the unquoted clink exe path.
  • +
  • The origin path now affects the hash in the dll cache, to guard against directory moves.
  • +
  • More code reorganization.
  • +
+

v1.0.0a0 (alpha test release)

+
    +
  • Extensive code reorganization, refactoring, and rewriting -- multiple times -- almost everything was touched.
  • +
  • OS integration:
      +
    • Fixed Doskey macros on Win8, and on Win10.
    • +
    • Fixed clink_x??.exe startup stall on Windows 10.
    • +
    • Removed XP support. It doesn't load DLLs like Clink uses them.
    • +
    • Removed Powershell support.
    • +
    +
  • +
  • Readline integration:
      +
    • Search for multiple places for [.|_]inputrc (fixes mridgers #258).
    • +
    • Disabled Readline's completion code, and only use the clink alternative code.
    • +
    • Removed redundant slash translation and shims to make it happen.
    • +
    • Removed control of Readline's suffix appending and disabled it.
    • +
    +
  • +
  • clink commands and flags:
      +
    • Changed --cfgdir to --profile, it's no longer required, and added help about it.
    • +
    • Added a --version option to print Clink's version.
    • +
    • Added clink info to print information about Clink.
    • +
    • Added clink echo command to echo input key sequences to stdout.
    • +
    • Added clink history command (fixes mridgers #172).
    • +
    • Added history as an alias for clink history.
    • +
    • Added internal --list flag to clink set for match generation.
    • +
    • Removed --scripts argument (fixes mridgers #206).
    • +
    • Updated clink autorun command's help text.
    • +
    +
  • +
  • Lua scripts:
      +
    • Prefer userprofile over other standard environment variables for where to look for lua scripts.
    • +
    • New API for argument style completion scripts.
    • +
    • Refactored prompt filtering, and introduced new prompt filtering API.
    • +
    • Refactored generating matches, and introduced new match generator API.
    • +
    • Removed built in completions scripts for git, go, hg, and p4. There's better ones.
    • +
    • Renamed many of clink's Lua functions.
    • +
    • Moved functions from clink to os in Lua.
    • +
    • Removed clink.is_match() in Lua; don't presume anything on anyone's behalf about matches.
    • +
    • Added some current dir functions in Lua.
    • +
    • Added some env/dir functions in Lua.
    • +
    • Exposed path manipulation functions to Lua.
    • +
    • Embed the core Lua scripts instead of loading them from files.
    • +
    +
  • +
  • Terminal IO:
      +
    • Added a module for scrolling the screen.
    • +
    • Rewrote the terminal emulation module, and all Readline IO goes through it.
    • +
    • Use VT220-style control codes for special keys.
    • +
    • If Alt is pressed send ESC in the input stream rather than setting meta bit.
    • +
    • Replaced wcwidth() with a more complete and correct version.
    • +
    +
  • +
  • Settings:
      +
    • Added clink_path setting for where to look for lua scripts.
    • +
    • Added match.ignore_case setting.
    • +
    • Added files.unc_paths setting for optional matching from UNC paths.
    • +
    • Added a setting to skip adding lines that start with history.
    • +
    • Removed esc_clears_line setting.
    • +
    • Pasting CRLFs doesn't really make sense.
    • +
    • Don't write out settings that are set to default.
    • +
    +
  • +
  • Make sure Ctrl-C doesn't modify history.
  • +
  • Make a cached copy of Clink's DLL when injecting so as to not lock the master.
  • +
  • Guard against Readline's writes to stderr.
  • +
  • Remove clink_inputrc_base file and embed its content (fixes mridgers #257).
  • +
  • Include more metadata in the Clink's executables.
  • +
+

v0.4.9

+
    +
  • Fixed broken Doskey on Win10 (#438, #451)
  • +
+

v0.4.8

+
    +
  • Environment variable clink_profile overrides Clink's profile path (#390).
  • +
  • Load a clink_inputrc file from Clink's profile directory (fixes #406).
  • +
  • Bug fixes;
      +
    • Redraw issues when prompts end in OSC ANSI codes (#387, #384).
    • +
    • Fixed clink autorun --help crash.
    • +
    +
  • +
+

v0.4.7

+
    +
  • Bug fixes;
      +
    • Sometimes autorun tries to run clink.exe (#374).
    • +
    • Autorun would cause cmd.exe to return an error if it wasn't interactive (#373).
    • +
    +
  • +
+

v0.4.6

+
    +
  • HOME is only set if it is currently unset.
  • +
  • Readline can be initialised with .inputrc and _inputrc files too (#258).
  • +
  • Bug fixes;
      +
    • Executable completion;
        +
      • Paths from PATH were checked twice.
      • +
      • Incorrect results were returned for words ending in . or -.
      • +
      • Directories . and .. were incorrectly displayed.
      • +
      +
    • +
    • Fixed a crash if .bat script's stdout is redirected (#366).
    • +
    • Occasional crash when injecting Clink (#351).
    • +
    • Display errors;
        +
      • When editing near the window's right-hand edge (#347).
      • +
      • Double display of multi-line prompts when resizing the terminal (#352).
      • +
      • Very rare wrap artefacts when making the terminal window larger.
      • +
      +
    • +
    • Doskey emulation (#344).
    • +
    • Improved clink autorun help (#348).
    • +
    • Fixed launching Clink when clink.bat is renamed (#357).
    • +
    +
  • +
+

v0.4.5

+
    +
  • Improved clink autorun. It now defaults to the Current User registry hive.
  • +
  • clink set gives more details for enumeration-type settings.
  • +
  • Tab completion for p4vc.
  • +
  • New settings history_expand_mode to control history expansion in quotes (#317).
  • +
  • Bug fixes;
      +
    • Use full width of the terminal (#337).
    • +
    • Fixed MinGW compile error (#335).
    • +
    • Autorun now defaults to the current user's hive (#332).
    • +
    • Creating clink.html no longer needs Pandoc, plus it looks a bit better (#331).
    • +
    • Added settings to control history expansion (#326).
    • +
    • Correct fallback when use_altgr_substitute is off (#325).
    • +
    • Load history prior to saving it on shutdown (#318).
    • +
    • Added Shift-Tab documentation and menu completion example (#190).
    • +
    • Added shim for backwards menu completion (#190).
    • +
    • Input handling now outputs \e`Z for Shift-Tab (#190).
    • +
    • Updated Readme with current Premake info (#310).
    • +
    • Guard against there being no buffer to read from (#304).
    • +
    • Fixed artefacts when resizing conhost's buffer (#139).
    • +
    • Clear remaining characters if scroll window was too small (#301)
    • +
    • Escape % characters when expanding aliases (#280).
    • +
    • Fixed leaking exception filters.
    • +
    • Clearing the screen doesn't leave artefacts behind.
    • +
    +
  • +
+

v0.4.4

+
    +
  • Completing .. behaves more like Bash (#277).
  • +
  • Escape from yes/no question when Ctrl+C is pressed.
  • +
  • Valid XP executables (#278, #289).
  • +
  • Fixed n-th argument yank not working as expected (#254).
  • +
  • Fixed prompt colours sometimes not working (#279, #286).
  • +
  • Fixed !0 causing Clink to crash.
  • +
  • Save/restore cursor position in case Readline moves it.
  • +
+

v0.4.3

+
    +
  • Localised Y/N when auto-answering "terminate?" prompt.
  • +
  • $* would early out if there was no arguments.
  • +
  • Disable ANSI code support if third party provides it.
  • +
  • Installer can now set %CLINK_DIR% to install location.
  • +
  • Improved output from clink set.
  • +
  • Support for Windows 10 Technical Preview.
  • +
  • Ctrl-L now scrolls last line to the top of the window rather than clearing.
  • +
  • New option to control how newline characters are pasted to the line.
  • +
  • New options to control history;
      +
    • history_file_lines - maximum lines saved to disk.
    • +
    • history_ignore_space - ignore lines prefixed with whitespace.
    • +
    • history_dupe_mode - how duplicate entries are handled.
    • +
    • history_io - load/save history from disk every line.
    • +
    +
  • +
  • Fixed nonfunctional numpad keys.
  • +
  • Fixed missing WINCH signals if other processes resize the buffer.
  • +
  • Support Alt codes sent from Conhost.
  • +
+

v0.4.2

+
    +
  • Prompt colouring no longer requires third party ANSI code utility.
  • +
  • Override settings with environment variables prefixed with 'clink'.
  • +
  • Ctrl-PgUp goes up a directory.
  • +
  • Updated Go completions (by matrixik).
  • +
  • Arguments to clink.arg.new_parser() now initialise parser's flags/args (from vladimir-kotikov).
  • +
  • New clink.arg.add_flags() and clink.arg.add_arguments() functions.
  • +
  • Removed footer and Alt-H tip for more succinct stdout output.
  • +
  • Bug fixes;
      +
    • Windows XP works again.
    • +
    • Fixed race condition in lua_execute().
    • +
    +
  • +
+

v0.4.1

+
    +
  • Bug fixes;
      +
    • Various Unicode fixes causing corrupt environment variables.
    • +
    • Fixed thread resume/suspend causing rare system-wide deadlock.
    • +
    • Fixed incorrect translation of suffixed slash when completing flags.
    • +
    +
  • +
  • Add --nolog argument to disable file logging. Fix #187 Fix #154
  • +
  • Added missing escape sequences from doskey emulation.
  • +
  • Reinstated unix-kill-line key binding.
  • +
  • Mapped PgUp/Down to search history using line typed so far.
  • +
  • Added documentation covering escape codes for special keys.
  • +
  • Added support for Windows' AltGr substitute Ctrl-Alt.
  • +
  • Support for Readline's 'menu' style completion (see docs).
  • +
+

v0.4

+
    +
  • New features;
      +
    • Better clink.arg API. Easier, more intuitive, and more powerful.
    • +
    • Whitespace prefix skips exec matching.
    • +
    • Added a set verb to easily change settings from the command line.
    • +
    • Basic support for a shells other than cmd.exe.
    • +
    • Completion for Go (contributed by Dobroslaw Zybort).
    • +
    • Setting exec_match_style to -1 disables it entirely.
    • +
    • Make history persistence optional.
    • +
    • Alias/doskey completion.
    • +
    • Very basic support for Powershell.
    • +
    • View cmd.exe's autorun entry without needing admin rights.
    • +
    +
  • +
  • New key bindings;
      +
    • Ctrl-Alt-C : Copy command line to the clipboard.
    • +
    • Ctrl-Alt-E : Expand environment variable under cursor.
    • +
    • Ctrl-Alt-U : "up directory" (formerly Shift-Up).
    • +
    • Ctrl-U : Adds ..\ to the command line.
    • +
    • Alt-H : Shows active keymap's key bindings.
    • +
    +
  • +
  • New Lua functions;
      +
    • clink.execute().
    • +
    • clink.get_host_process().
    • +
    • clink.match_files().
    • +
    • clink.match_words().
    • +
    • clink.get_console_aliases().
    • +
    +
  • +
  • Lots of bug fixes, including;
      +
    • Better command extraction.
    • +
    • Fixed cmd.exe command paging and Ctrl-C/Ctrl-Break handling.
    • +
    • Multiple locale fixes.
    • +
    • Use localised text for "Terminate batch job?" prompt.
    • +
    +
  • +
+

v0.3

+
    +
  • Automatic answering of cmd.exe's "Terminate batch script?" prompt.
  • +
  • Coloured prompts (requires ANSICON or ConEmu).
  • +
  • Added Shift-Up keyboard shortcut to automatically execute cd ..
  • +
  • Mapped Ctrl-Z to undo, Microsoft style.
  • +
  • Improved integration of Readline;
      +
    • New input handling code (Ctrl-Alt combos now work).
    • +
    • An implementation of the Termcap library.
    • +
    • Fully functional Vi-mode support.
    • +
    • Support for resizable consoles.
    • +
    • Line wrapping now works correctly (issue 50).
    • +
    +
  • +
  • Adjustable executable match style (issue 65).
  • +
  • Improved environment variable completion.
  • +
  • Added settings file to customise Clink.
  • +
  • New Lua features and functions;
      +
    • Matches can now be filtered in Lua before they are display.
    • +
    • clink.quote_split().
    • +
    • clink.arg.node_merge().
    • +
    • clink.get_screen_info() (issue 71).
    • +
    • clink.split() (for splitting strings).
    • +
    • clink.chdir().
    • +
    • clink.get_cwd().
    • +
    • Functions to query Clink's settings.
    • +
    +
  • +
  • New command line options;
      +
    • --profile dir to override default profile directory.
    • +
    • --nohostcheck disables verification that host is cmd.exe.
    • +
    • --pid specifies the process to inject into.
    • +
    +
  • +
  • Update Mercurial completion (issue 73).
  • +
  • Start menu shortcut starts in USERPROFILE, like cmd.exe
  • +
  • Zip distribution is now portable.
  • +
+

v0.2.1

+
    +
  • The .history file now merges multiple sessions together.
  • +
  • Fixed missing y/n, pause, and other prompts.
  • +
  • Fixed segfault in loader executable.
  • +
  • Better ConEmu compatibility.
  • +
+

v0.2

+
    +
  • Basic argument completion for git, hg, svn, and p4.
  • +
  • Traditional Bash clear screen (Ctrl-L) and exit shortcuts (Ctrl-D).
  • +
  • Scrollable command window using PgUp/PgDown keys.
  • +
  • Doskey support.
  • +
  • Automatic quoting of file names with spaces.
  • +
  • Scriptable custom prompts.
  • +
  • New argument framework to ease writing context-sensitive match generators.
  • +
  • History and log file is now saved per-user rather than globally.
  • +
  • Improved Clink's command line interface (clink --help).
  • +
  • More reliable handling of cmd.exe's autorun entry.
  • +
  • General improvements to executable and directory-command completion.
  • +
  • Symbolic link support.
  • +
  • Documentation.
  • +
  • Windows 8 support.
  • +
  • Improved hooking so Clink can be shared with other thirdparty utilities that +also hook cmd.exe (ConEmu, ANSICon, etc.).
  • +
+

v0.1.1

+
    +
  • Fixed AltGr+<key> on international keyboards.
  • +
  • Fixed broken completion when directories have a - in their name (Mark Hammond)
  • +
  • The check for single match scenarios now correctly handles case-insensitivity.
  • +
+

v0.1

+
    +
  • Initial release.
  • +
- - -### The Clink Lua API - -#### Matches - -##### clink.add_match(text) - -Outputs **text** as a match for the active completion. - -##### clink.compute_lcd(text, matches) - -Returns the least-common-denominator of **matches**. It is assumed that **text** was the input to generate **matches**. As such it is expected that each match starts with **text**. - -##### clink.get_match(index) - -Returns a match by **index** from the matches output by clink.add_match(). - -##### clink.is_match(needle, candidate) - -Given a **needle** (such as the section of the current line buffer being completed), this function returns true or false if **candidate** begins with **needle**. Readline's -/_ case-mapping is respected if it is enabled. - -##### clink.is_single_match(matches) - -Checks each match in the table **matches** and checks to see if they are all duplicates of each other. - -##### clink.match_count() - -Returns the number of matches output by calls to clink.add_match(). - -##### clink.match_display_filter - -This variable can be set to a function so that matches can be filtered before they are displayed. See **Display Filtering** section for more info. - -##### clink.matches_are_files() - -Tells Readline that the matches we are passing back to it are files. This will cause Readline to append the path separator character to the line if there's only one match, and mark directories when displaying multiple matches. - -##### clink.register_match_generator(generator, sort_id) - -Registers a match **generator** function that is called to generate matches when the complete keys is press (TAB by default). - -The generator function takes the form **generator_function(text, first, last)** where **text** is the portion of the line buffer that is to be completed, **first** and **last** are the start and end indices into the line buffer for **text**. - -##### clink.set_match(index, value) - -Explicitly sets match at **index** to **value**. - -#### Argument Framework - -##### parser:add_arguments(table1, table2, ...) - -Adds more positional arguments to the parser. See **parser:set_arguments()**. - -##### parser:add_flags(flag1, flag2, ...) - -Adds more flags to the parser. See **parser:set_flags()**. -##### parser:be_precise() - -Ordinarily Clink only loosely matches word as it traverses a parser. Calling this will make Clink only accept an exact matching word to consider moving onto the next one. - -##### parser:disable_file_matching() - -If this is called then Clink will not default to matching the file system if parsing comes to an end or can not be completed. - -##### parser:dump() - -Prints the parser to stdout. - -##### parser:go(parts) - -This runs the parser for the table of words **parts**. It returns a table of argument options. It is this method that Clink uses internally. - -##### parser:is_flag(word) - -Returns true of **word** is a valid flag. - -##### parser:loop(index) - -By default parsers do not loop and parsing comes to an end when there are no more arguments to traverse through. If loop() is called Clink will loop back to argument at **index** rather than terminating the parse. - -##### parser:set_arguments(table1, table2, ...) - -This method sets the parser's positional arguments. Each of the variable number of arguments to the method is a table of potential options for the argument at that position. Note that calling this method replaces any existing positional arguments the parser may already have. Use **parser:add_arguments()** to append more positional arguments. - -##### parser:set_flags(flag1, flag2, ...) - -Sets the parser's flags (which can be thought of as position independent arguments). Each argument is a string and must start with the expected flag prefix ("-" by default). Be aware that calling **set_flags()** will replace the parser's existing flags. To add more use **parser:add_flags()**. - -#### Prompt Filtering - -##### clink.prompt.register_filter(filter, sort_id) - -Used to register a **filter** function to pre-process the prompt before use by Readline. Filters are called by **sort_id** where lower sort ids get called first. Filter functions will receive no arguments and return true if filtering is finished. Getting and setting the prompt value is done through the **clink.prompt.value** variable. - -##### clink.prompt.value - -User-provided prompt filter functions can get and set the prompt value using this variable. - -#### Miscellaneous - -##### clink.chdir(path) - -Changes the current working directory to **path**. Clink caches and restores the working directory between calls to the match generation so that it does not interfere with the processes normal operation. - -##### clink.find_dirs(mask, case_map) - -Returns a table (array) of directories that match the supplied **mask**. If **case_map** is **true** then Clink will adjust the last part of the mask's path so that returned matches respect Readline's case-mapping feature (if it is enabled). For example; **.\foo_foo\bar_bar*** becomes **.\foo_foo\bar?bar***. - -There is no support for recursively traversing the path in **mask**. - -##### clink.find_files(mask, case_map) - -Returns a table (array) of files that match the supplied **mask**. See **find_dirs** for details on the **case_map** argument. - -There is no support for recursively traversing the path in **mask**. - -##### clink.get_cwd() - -Returns the current working directory. - -##### clink.get_console_aliases() - -Returns a table of all the registered console aliases. Windows' console alias API is exposed via **doskey** or progromatically via the AddConsoleAlias() function. - -##### clink.get_env(env_var_name) - -Returns the value of the environment variable **env_var_name**. This is preferable to the built-in Lua function os.getenv() as the latter uses a cached version of the current process' environment which can result in incorrect results. - -##### clink.get_env_var_names() - -Returns a table of the names of the current process' environment variables. - -##### clink.get_host_process() - -Returns the name of the host process (the rl_readline_name variable). - -##### clink.get_screen_info() - -Returns a table describing the current console buffer's state with the following -contents; - -``` -{ - -- Dimensions of the console's buffer. - buffer_width - buffer_height - - -- Dimensions of the visible area of the console buffer. - window_width - window_height -} -``` - -##### clink.get_setting_str(name) - -Retrieves the Clink setting **name**, returning it as a string. See **Settings** for more information on the available settings. - -##### clink.get_setting_int(name) - -As **clink.get_setting_str** but returning a number instead. - -##### clink.is_dir(path) - -Returns true if **path** resolves to a directory. - -##### clink.is_rl_variable_true(readline_var_name) - -Returns the boolean value of a Readline variable. These can be set with the clink_inputrc file, more details of which can be found in the [Readline manual](http://tinyurl.com/oum26rp). - -##### clink.lower(text) - -Same as os.lower() but respects Readline's case-mapping feature which will consider - and _ as case insensitive. - -Care should be taken when using this to generate masks for file/dir find operations due to the -/_ giving different results (unless of course Readline's extended case-mapping is disabled). - -##### clink.match_files(pattern, full_path, find_func) - -Globs files using **pattern** and adds results as matches. If **full_path** is **true** then the path from **pattern** is prefixed to the results (otherwise only the file names are included). The last argument **find_func** is the function to use to do the globbing. If it's unspecified (or nil) Clink falls back to **clink.find_files**. - -##### clink.match_words(text, words) - -Calls clink.is_match() on each word in the table **words** and adds matches to Clink that match the needle **text**. - -##### clink.quote_split(str, ql, qr) - -This function takes the string **str** which is quoted by **ql** (the opening quote character) and **qr** (the closing character) and splits it into parts as per the quotes. A table of these parts is returned. - -``` -clink.quote_split("pre(middle)post", "(", ")") = { - "pre", "middle", "post" -} -``` - -##### clink.slash_translation(type) - -Controls how Clink will translate the path separating slashes for the current path being completed. Values for **type** are; - -- -1 - no translation -- 0 - to backslashes -- 1 - to forward slashes. - - -##### clink.split(str, sep) - -Splits the string **str** into pieces separated by **sep**, returning a table of the pieces. - -##### clink.suppress_char_append() - -This stops Readline from adding a trailing character when completion is finished (usually when a single match is returned). The suffixing of a character is enabled before completion functions are called so a call to this will only apply for the current completion. - -By default Readline appends a space character (' ') when the is only a single match unless it is completing files where it will use the path separator instead. - -##### clink.suppress_quoting() - -Suppress the prefixing and suffixing of quotes even if there is a character in the current word being completed that would ordinarily need surrounding in quotes. - -#### Readline Constants - -Clink exposes a small amount of state from Readline in the global **rl_state** table. Readline's nomenclature is maintained (minus the *rl* prefix) so Readline's manual can also be used as reference. This table should be considered read-only - changes to the table's members are not fed back to Readline. - -##### rl_state.line_buffer - -This variable contains the current state of the whole line being edited. - -##### rl_state.point - -The current cursor position within the line buffer. - - - - - -### Changes - -##### v0.4.9 - -- Fixed broken Doskey on Win10 (#438, #451) - -##### v0.4.8 - -- Environment variable 'clink_profile' overrides Clink's profile path (#390). -- Load a clink_inputrc file from Clink's profile directory (fixes #406). -- Bug fixes; - - Redraw issues when prompts end in OSC ANSI codes (#387, #384). - - Fixed 'clink autorun --help' crash. - -##### v0.4.7 - -- Bug fixes; - - Sometimes autorun tries to run clink.exe (#374). - - Autorun would cause cmd.exe to return an error if it wasn't interactive (#373). - -##### v0.4.6 - -- HOME is only set if it is currently unset. -- Readline can be initialised with .inputrc and _inputrc files too (#258). -- Bug fixes; - - Executable completion; - - Paths from PATH were checked twice. - - Incorrect results were returned for words ending in '.' or '-'. - - Directories . and .. were incorrectly displayed. - - Fixed a crash if .bat script's stdout is redirected (#366). - - Occasional crash when injecting Clink (#351). - - Display errors; - - When editing near the window's right-hand edge (#347). - - Double display of multi-line prompts when resizing the terminal (#352). - - Very rare wrap artefacts when making the terminal window larger. - - Doskey emulation (#344). - - Improved 'clink autorun' help (#348). - - Fixed launching Clink when clink.bat is renamed (#357). - -##### v0.4.5 - -- Improved 'clink autorun'. It now defaults to the Current User registry hive. -- 'clink set' gives more details for enumeration-type settings. -- Tab completion for p4vc. -- New settings 'history_expand_mode' to control history expansion in quotes (#317). -- Bug fixes; - - Use full width of the terminal (#337). - - Fixed MinGW compile error (#335). - - Autorun now defaults to the current user's hive (#332). - - Creating clink.html no longer needs Pandoc, plus it looks a bit better (#331). - - Added settings to control history expansion (#326). - - Correct fallback when 'use_altgr_substitute' is off (#325). - - Load history prior to saving it on shutdown (#318). - - Added Shift-Tab documentation and menu completion example (#190). - - Added shim for backwards menu completion (#190). - - Input handling now outputs '\e`Z' for Shift-Tab (#190). - - Updated Readme with current Premake info (#310). - - Guard against there being no buffer to read from (#304). - - Fixed artefacts when resizing conhost's buffer (#139). - - Clear remaining characters if scroll window was too small (#301) - - Escape % characters when expanding aliases (#280). - - Fixed leaking exception filters. - - Clearing the screen doesn't leave artefacts behind. - -##### v0.4.4 - -- Completing .. behaves more like Bash (#277). -- Escape from yes/no question when Ctrl+C is pressed. -- Valid XP executables (#278, #289). -- Fixed n-th argument yank not working as expected (#254). -- Fixed prompt colours sometimes not working (#279, #286). -- Fixed '!0' causing Clink to crash. -- Save/restore cursor position in case Readline moves it. - -##### v0.4.3 - -- Localised Y/N when auto-answering 'terminate?' prompt. -- $* would early out if there was no arguments. -- Disable ANSI code support if third party provides it. -- Installer can now set %CLINK_DIR% to install location. -- Improved output from 'clink set'. -- Support for Windows 10 Technical Preview. -- Ctrl-L now scrolls last line to the top of the window rather than clearing. -- New option to control how newline characters are pasted to the line. -- New options to control history; - - 'history_file_lines' - maximum lines saved to disk. - - 'history_ignore_space' - ignore lines prefixed with whitespace. - - 'history_dupe_mode' - how duplicate entries are handled. - - 'history_io' - load/save history from disk every line. -- Fixed nonfunctional numpad keys. -- Fixed missing WINCH signals if other processes resize the buffer. -- Support Alt codes sent from Conhost. - -##### v0.4.2 - -- Prompt colouring no longer requires third party ANSI code utility. -- Override settings with environment variables prefixed with 'clink'. -- Ctrl-PgUp goes up a directory. -- Updated Go completions (by matrixik). -- Arguments to clink.arg.new_parser() now initialise parser's flags/args (from vladimir-kotikov). -- New clink.arg.add_flags() and clink.arg.add_arguments() functions. -- Removed footer and Alt-H tip for more succinct stdout output. -- Bug fixes; - - Windows XP works again. - - Fixed race condition in lua_execute(). - -##### v0.4.1 - -- Bug fixes; - - Various Unicode fixes causing corrupt environment variables. - - Fixed thread resume/suspend causing rare system-wide deadlock. - - Fixed incorrect translation of suffixed slash when completing flags. -- Add --nolog argument to disable file logging. Fix #187 Fix #154 -- Added missing escape sequences from doskey emulation. -- Reinstated unix-kill-line key binding. -- Mapped PgUp/Down to search history using line typed so far. -- Added documentation covering escape codes for special keys. -- Added support for Windows' AltGr substitute Ctrl-Alt. -- Support for Readline's 'menu' style completion (see docs). - -##### v0.4 - -- New features; - - Better 'clink.arg' API. Easier, more intuitive, and more powerful. - - Whitespace prefix skips exec matching. - - Added a 'set' verb to easily change settings from the command line. - - Basic support for a shells other than cmd.exe. - - Completion for Go (contributed by Dobroslaw Zybort). - - Setting 'exec_match_style' to -1 disables it entirely. - - Make history persistence optional. - - Alias/doskey completion. - - Very basic support for Powershell. - - View cmd.exe's autorun entry without needing admin rights. -- New key bindings; - - Ctrl-Alt-C : Copy command line to the clipboard. - - Ctrl-Alt-E : Expand environment variable under cursor. - - Ctrl-Alt-U : 'up directory' (formerly Shift-Up). - - Ctrl-U : Adds '..\' to the command line. - - Alt-H : Shows active keymap's key bindings. -- New Lua functions; - - clink.execute(). - - clink.get_host_process(). - - clink.match_files(). - - clink.match_words(). - - clink.get_console_aliases(). -- Lots of bug fixes, including; - - Better command extraction. - - Fixed cmd.exe command paging and Ctrl-C/Ctrl-Break handling. - - Multiple locale fixes. - - Use localised text for 'Terminate batch job?' prompt. - -##### v0.3 - -- Automatic answering of cmd.exe's 'Terminate batch script?' prompt. -- Coloured prompts (requires ANSICON or ConEmu). -- Added Shift-Up keyboard shortcut to automatically execute 'cd ..' -- Mapped Ctrl-Z to undo, Microsoft style. -- Improved integration of Readline; - - New input handling code (Ctrl-Alt combos now work). - - An implementation of the Termcap library. - - Fully functional Vi-mode support. - - Support for resizable consoles. - - Line wrapping now works correctly (issue 50). -- Adjustable executable match style (issue 65). -- Improved environment variable completion. -- Added settings file to customise Clink. -- New Lua features and functions; - - Matches can now be filtered in Lua before they are display. - - clink.quote_split(). - - clink.arg.node_merge(). - - clink.get_screen_info() (issue 71). - - clink.split() (for splitting strings). - - clink.chdir(). - - clink.get_cwd(). - - Functions to query Clink's settings. -- New command line options; - - '--profile ' to override default profile directory. - - '--nohostcheck' disables verification that host is cmd.exe. - - '--pid' specifies the process to inject into. -- Update Mercurial completion (issue 73). -- Start menu shortcut starts in USERPROFILE, like cmd.exe -- Zip distribution is now portable. - -##### v0.2.1 - -- The .history file now merges multiple sessions together. -- Fixed missing y/n, pause, and other prompts. -- Fixed segfault in loader executable. -- Better ConEmu compatibility. - -##### v0.2 - -- Basic argument completion for 'git', 'hg', 'svn', and 'p4'. -- Traditional Bash clear screen ('Ctrl-L') and exit shortcuts ('Ctrl-D'). -- Scrollable command window using 'PgUp'/'PgDown' keys. -- Doskey support. -- Automatic quoting of file names with spaces. -- Scriptable custom prompts. -- New argument framework to ease writing context-sensitive match generators. -- History and log file is now saved per-user rather than globally. -- Improved Clink's command line interface ('clink --help'). -- More reliable handling of cmd.exe's autorun entry. -- General improvements to executable and directory-command completion. -- Symbolic link support. -- Documentation. -- Windows 8 support. -- Improved hooking so Clink can be shared with other thirdparty utilities that - also hook cmd.exe (ConEmu, ANSICon, etc.). - -##### v0.1.1 - -- Fixed AltGr+ on international keyboards. -- Fixed broken completion when directories have a '-' in their name (Mark Hammond) -- The check for single match scenarios now correctly handles case-insensitivity. - -##### v0.1 - -- Initial release. - +
+
+

License

+

Clink is distributed under the terms of the GNU General Public License, version 3.

+

Credits

+ +

Clink was originally built by Martin Ridgers (https://github.com/mridgers/clink).
+Copyright (c) 2012-2018 by Martin Ridgers.

+

Clink has been forked and renovated by Christopher Antos (https://github.com/chrisant996/clink).
+Portions Copyright (c) 2020-2021 by Christopher Antos.

+

Libraries

+

GNU Readline library version 8.1 (https://tiswww.case.edu/php/chet/readline/rltop.html).
+GNU Readline is distributed under the terms of the GNU General Public License, version 3.

+

Lua 5.2 (https://www.lua.org).

+

getopt library.
+Copyright (c) 1997 Gregory Pietsch, placed in the public domain.

+

Detours library version 4.0.1 (https://github.com/microsoft/detours).
+Copyright (c) Microsoft Corporation. All rights reserved.
+Licensed under the MIT license.

+

Clink documentation embeds the highlight.js library (https://highlightjs.org).
+Highlight.js is released under the BSD License.

+
+
diff --git a/extras/clink/clink.lua b/extras/clink/clink.lua index c59f06c04a4616644b1b11c5a8202e2beb561e6f..d25fd02b76b3a97d9f2bb6add1be166a1b701d3a 100644 --- a/extras/clink/clink.lua +++ b/extras/clink/clink.lua @@ -1,3420 +1,5 @@ +-- This file is intentionally blank. -- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -clink.matches = {} -clink.generators = {} - -clink.prompt = {} -clink.prompt.filters = {} - --------------------------------------------------------------------------------- -function clink.compute_lcd(text, list) - local list_n = #list - if list_n < 2 then - return - end - - -- Find min and max limits - local max = 100000 - for i = 1, #list, 1 do - local j = #(list[i]) - if max > j then - max = j - end - end - - -- For each character in the search range... - local mid = #text - local lcd = "" - for i = 1, max, 1 do - local same = true - local l = list[1]:sub(i, i) - local m = l:lower() - - -- Compare character at the index with each other character in the - -- other matches. - for j = 2, list_n, 1 do - local n = list[j]:sub(i, i):lower() - if m ~= n then - same = false - break - end - end - - -- If all characters match then use first match's character. - if same then - lcd = lcd..l - else - -- Otherwise use what the user's typed or if we're past that then - -- bail out. - if i <= mid then - lcd = lcd..text:sub(i, i) - else - break - end - end - end - - return lcd -end - --------------------------------------------------------------------------------- -function clink.is_single_match(matches) - if #matches <= 1 then - return true - end - - local first = matches[1]:lower() - for i = 2, #matches, 1 do - if first ~= matches[i]:lower() then - return false - end - end - - return true -end - --------------------------------------------------------------------------------- -function clink.is_point_in_quote(str, i) - if i > #str then - i = #str - end - - local c = 1 - local q = string.byte("\"") - for j = 1, i do - if string.byte(str, j) == q then - c = c * -1 - end - end - - if c < 0 then - return true - end - - return false -end - --------------------------------------------------------------------------------- -function clink.adjust_for_separator(buffer, point, first, last) - local seps = nil - if clink.get_host_process() == "cmd.exe" then - seps = "|&" - end - - if seps then - -- Find any valid command separators and if found, manipulate the - -- completion state a little bit. - local leading = buffer:sub(1, first - 1) - - -- regex is: - local regex = "["..seps.."]([^"..seps.."]*)$" - local sep_found, _, post_sep = leading:find(regex) - - if sep_found and not clink.is_point_in_quote(leading, sep_found) then - local delta = #leading - #post_sep - buffer = buffer:sub(delta + 1) - first = first - delta - last = last - delta - point = point - delta - - if first < 1 then - first = 1 - end - end - end - - return buffer, point, first, last -end - --------------------------------------------------------------------------------- -function clink.generate_matches(text, first, last) - local line_buffer - local point - - line_buffer, point, first, last = clink.adjust_for_separator( - rl_state.line_buffer, - rl_state.point, - first, - last - ) - - rl_state.line_buffer = line_buffer - rl_state.point = point - - clink.matches = {} - clink.match_display_filter = nil - - for _, generator in ipairs(clink.generators) do - if generator.f(text, first, last) == true then - if #clink.matches > 1 then - -- Catch instances where there's many entries of a single match - if clink.is_single_match(clink.matches) then - clink.matches = { clink.matches[1] } - return true; - end - - -- First entry in the match list should be the user's input, - -- modified here to be the lowest common denominator. - local lcd = clink.compute_lcd(text, clink.matches) - table.insert(clink.matches, 1, lcd) - end - - return true - end - end - - return false -end - --------------------------------------------------------------------------------- -function clink.add_match(match) - if type(match) == "table" then - for _, i in ipairs(match) do - table.insert(clink.matches, i) - end - - return - end - - table.insert(clink.matches, match) -end - --------------------------------------------------------------------------------- -function clink.register_match_generator(func, priority) - if priority == nil then - priority = 999 - end - - table.insert(clink.generators, {f=func, p=priority}) - table.sort(clink.generators, function(a, b) return a["p"] < b["p"] end) -end - --------------------------------------------------------------------------------- -function clink.is_match(needle, candidate) - if needle == nil then - error("Nil needle value when calling clink.is_match()", 2) - end - - if clink.lower(candidate:sub(1, #needle)) == clink.lower(needle) then - return true - end - return false -end - --------------------------------------------------------------------------------- -function clink.match_count() - return #clink.matches -end - --------------------------------------------------------------------------------- -function clink.set_match(i, value) - clink.matches[i] = value -end - --------------------------------------------------------------------------------- -function clink.get_match(i) - return clink.matches[i] -end - --------------------------------------------------------------------------------- -function clink.match_words(text, words) - local count = clink.match_count() - - for _, i in ipairs(words) do - if clink.is_match(text, i) then - clink.add_match(i) - end - end - - return clink.match_count() - count -end - --------------------------------------------------------------------------------- -function clink.match_files(pattern, full_path, find_func) - -- Fill out default values - if type(find_func) ~= "function" then - find_func = clink.find_files - end - - if full_path == nil then - full_path = true - end - - if pattern == nil then - pattern = "*" - end - - -- Glob files. - pattern = pattern:gsub("/", "\\") - local glob = find_func(pattern, true) - - -- Get glob's base. - local base = "" - local i = pattern:find("[\\:][^\\:]*$") - if i and full_path then - base = pattern:sub(1, i) - end - - -- Match them. - local count = clink.match_count() - - for _, i in ipairs(glob) do - local full = base..i - clink.add_match(full) - end - - return clink.match_count() - count -end - --------------------------------------------------------------------------------- -function clink.split(str, sep) - local i = 1 - local ret = {} - for _, j in function() return str:find(sep, i, true) end do - table.insert(ret, str:sub(i, j - 1)) - i = j + 1 - end - table.insert(ret, str:sub(i, j)) - - return ret -end - --------------------------------------------------------------------------------- -function clink.quote_split(str, ql, qr) - if not qr then - qr = ql - end - - -- First parse in "pre[ql]quote_string[qr]" chunks - local insert = table.insert - local i = 1 - local needle = "%b"..ql..qr - local parts = {} - for l, r, quote in function() return str:find(needle, i) end do - -- "pre" - if l > 1 then - insert(parts, str:sub(i, l - 1)) - end - - -- "quote_string" - insert(parts, str:sub(l, r)) - i = r + 1 - end - - -- Second parse what remains as "pre[ql]being_quoted" - local l = str:find(ql, i, true) - if l then - -- "pre" - if l > 1 then - insert(parts, str:sub(i, l - 1)) - end - - -- "being_quoted" - insert(parts, str:sub(l)) - elseif i <= #str then - -- Finally add whatever remains... - insert(parts, str:sub(i)) - end - - return parts -end - --------------------------------------------------------------------------------- -function clink.prompt.register_filter(filter, priority) - if priority == nil then - priority = 999 - end - - table.insert(clink.prompt.filters, {f=filter, p=priority}) - table.sort(clink.prompt.filters, function(a, b) return a["p"] < b["p"] end) -end - --------------------------------------------------------------------------------- -function clink.filter_prompt(prompt) - local function add_ansi_codes(p) - local c = tonumber(clink.get_setting_int("prompt_colour")) - if c < 0 then - return p - end - - c = c % 16 - - --[[ - <4 >=4 %2 - 0 0 0 Black 4 1 -3 Blue 0 - 1 4 3 Red 5 5 0 Magenta 1 - 2 2 0 Green 6 3 -3 Cyan 0 - 3 6 3 Yellow 7 7 0 Gray 1 - --]] - - -- Convert from cmd.exe colour indices to ANSI ones. - local colour_id = c % 8 - if (colour_id % 2) == 1 then - if colour_id < 4 then - c = c + 3 - end - elseif colour_id >= 4 then - c = c - 3 - end - - -- Clamp - if c > 15 then - c = 15 - end - - -- Build ANSI code - local code = "\x1b[0;" - if c > 7 then - c = c - 8 - code = code.."1;" - end - code = code..(c + 30).."m" - - return code..p.."\x1b[0m" - end - - clink.prompt.value = prompt - - for _, filter in ipairs(clink.prompt.filters) do - if filter.f() == true then - return add_ansi_codes(clink.prompt.value) - end - end - - return add_ansi_codes(clink.prompt.value) -end - --- vim: expandtab --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -clink.arg = {} - --------------------------------------------------------------------------------- -local parsers = {} -local is_parser -local is_sub_parser -local new_sub_parser -local parser_go_impl -local merge_parsers - -local parser_meta_table = {} -local sub_parser_meta_table = {} - --------------------------------------------------------------------------------- -function parser_meta_table.__concat(lhs, rhs) - if not is_parser(rhs) then - error("Right-handside must be parser.", 2) - end - - local t = type(lhs) - if t == "table" then - local ret = {} - for _, i in ipairs(lhs) do - table.insert(ret, i .. rhs) - end - - return ret - elseif t ~= "string" then - error("Left-handside must be a string or a table.", 2) - end - - return new_sub_parser(lhs, rhs) -end - --------------------------------------------------------------------------------- -local function unfold_table(source, target) - for _, i in ipairs(source) do - if type(i) == "table" and getmetatable(i) == nil then - unfold_table(i, target) - else - table.insert(target, i) - end - end -end - --------------------------------------------------------------------------------- -local function parser_is_flag(parser, part) - if part == nil then - return false - end - - local prefix = part:sub(1, 1) - return prefix == "-" or prefix == "/" -end - --------------------------------------------------------------------------------- -local function parser_add_arguments(parser, ...) - for _, i in ipairs({...}) do - -- Check all arguments are tables. - if type(i) ~= "table" then - error("All arguments to add_arguments() must be tables.", 2) - end - - -- Only parsers are allowed to be specified without being wrapped in a - -- containing table. - if getmetatable(i) ~= nil then - if is_parser(i) then - table.insert(parser.arguments, i) - else - error("Tables can't have meta-tables.", 2) - end - else - -- Expand out nested tables and insert into object's arguments table. - local arguments = {} - unfold_table(i, arguments) - table.insert(parser.arguments, arguments) - end - end - - return parser -end - --------------------------------------------------------------------------------- -local function parser_set_arguments(parser, ...) - parser.arguments = {} - return parser:add_arguments(...) -end - --------------------------------------------------------------------------------- -local function parser_add_flags(parser, ...) - local flags = {} - unfold_table({...}, flags) - - -- Validate the specified flags. - for _, i in ipairs(flags) do - if is_sub_parser(i) then - i = i.key - end - - -- Check all flags are strings. - if type(i) ~= "string" then - error("All parser flags must be strings. Found "..type(i), 2) - end - - -- Check all flags start with a - or a / - if not parser:is_flag(i) then - error("Flags must begin with a '-' or a '/'", 2) - end - end - - -- Append flags to parser's existing table of flags. - for _, i in ipairs(flags) do - table.insert(parser.flags, i) - end - - return parser -end - --------------------------------------------------------------------------------- -local function parser_set_flags(parser, ...) - parser.flags = {} - return parser:add_flags(...) -end - --------------------------------------------------------------------------------- -local function parser_flatten_argument(parser, index, func_thunk) - -- Sanity check the 'index' param to make sure it's valid. - if type(index) == "number" then - if index <= 0 or index > #parser.arguments then - return parser.use_file_matching - end - end - - -- index == nil is a special case that returns the parser's flags - local opts = {} - local arg_opts - if index == nil then - arg_opts = parser.flags - else - arg_opts = parser.arguments[index] - end - - -- Convert each argument option into a string and collect them in a table. - for _, i in ipairs(arg_opts) do - if is_sub_parser(i) then - table.insert(opts, i.key) - else - local t = type(i) - if t == "function" then - local results = func_thunk(i) - local t = type(results) - if not results then - return parser.use_file_matching - elseif t == "boolean" then - return (results and parser.use_file_matching) - elseif t == "table" then - for _, j in ipairs(results) do - table.insert(opts, j) - end - end - elseif t == "string" or t == "number" then - table.insert(opts, tostring(i)) - end - end - end - - return opts -end - --------------------------------------------------------------------------------- -local function parser_go_args(parser, state) - local exhausted_args = false - local exhausted_parts = false - - local part = state.parts[state.part_index] - local arg_index = state.arg_index - local arg_opts = parser.arguments[arg_index] - local arg_count = #parser.arguments - - -- Is the next argument a parser? Parse control directly on to it. - if is_parser(arg_opts) then - state.arg_index = 1 - return parser_go_impl(arg_opts, state) - end - - -- Advance parts state. - state.part_index = state.part_index + 1 - if state.part_index > #state.parts then - exhausted_parts = true - end - - -- Advance argument state. - state.arg_index = arg_index + 1 - if arg_index > arg_count then - exhausted_args = true - end - - -- We've exhausted all available arguments. We either loop or we're done. - if parser.loop_point > 0 and state.arg_index > arg_count then - state.arg_index = parser.loop_point - if state.arg_index > arg_count then - state.arg_index = arg_count - end - end - - -- Is there some state to process? - if not exhausted_parts and not exhausted_args then - local exact = false - for _, arg_opt in ipairs(arg_opts) do - -- Is the argument a key to a sub-parser? If so then hand control - -- off to it. - if is_sub_parser(arg_opt) then - if arg_opt.key == part then - state.arg_index = 1 - return parser_go_impl(arg_opt.parser, state) - end - end - - -- Check so see if the part has an exact match in the argument. Note - -- that only string-type options are considered. - if type(arg_opt) == "string" then - exact = exact or arg_opt == part - else - exact = true - end - end - - -- If the parser's required to be precise then check here. - if parser.precise and not exact then - exhausted_args = true - else - return nil - end - end - - -- If we've no more arguments to traverse but there's still parts remaining - -- then we start skipping arguments but keep going so that flags still get - -- parsed (as flags have no position). - if exhausted_args then - state.part_index = state.part_index - 1 - - if not exhausted_parts then - if state.depth <= 1 then - state.skip_args = true - return - end - - return parser.use_file_matching - end - end - - -- Now we've an index into the parser's arguments that matches the line - -- state. Flatten it. - local func_thunk = function(func) - return func(part) - end - - return parser:flatten_argument(arg_index, func_thunk) -end - --------------------------------------------------------------------------------- -local function parser_go_flags(parser, state) - local part = state.parts[state.part_index] - - -- Advance parts state. - state.part_index = state.part_index + 1 - if state.part_index > #state.parts then - return parser:flatten_argument() - end - - for _, arg_opt in ipairs(parser.flags) do - if is_sub_parser(arg_opt) then - if arg_opt.key == part then - local arg_index_cache = state.arg_index - local skip_args_cache = state.skip_args - - state.arg_index = 1 - state.skip_args = false - state.depth = state.depth + 1 - - local ret = parser_go_impl(arg_opt.parser, state) - if type(ret) == "table" then - return ret - end - - state.depth = state.depth - 1 - state.skip_args = skip_args_cache - state.arg_index = arg_index_cache - end - end - end -end - --------------------------------------------------------------------------------- -function parser_go_impl(parser, state) - local has_flags = #parser.flags > 0 - - while state.part_index <= #state.parts do - local part = state.parts[state.part_index] - local dispatch_func - - if has_flags and parser:is_flag(part) then - dispatch_func = parser_go_flags - elseif not state.skip_args then - dispatch_func = parser_go_args - end - - if dispatch_func ~= nil then - local ret = dispatch_func(parser, state) - if ret ~= nil then - return ret - end - else - state.part_index = state.part_index + 1 - end - end - - return parser.use_file_matching -end - --------------------------------------------------------------------------------- -local function parser_go(parser, parts) - -- Validate 'parts'. - if type(parts) ~= "table" then - error("'Parts' param must be a table of strings ("..type(parts)..").", 2) - else - if #parts == 0 then - part = { "" } - end - - for i, j in ipairs(parts) do - local t = type(parts[i]) - if t ~= "string" then - error("'Parts' table can only contain strings; "..j.."="..t, 2) - end - end - end - - local state = { - arg_index = 1, - part_index = 1, - parts = parts, - skip_args = false, - depth = 1, - } - - return parser_go_impl(parser, state) -end - --------------------------------------------------------------------------------- -local function parser_dump(parser, depth) - if depth == nil then - depth = 0 - end - - function prt(depth, index, text) - local indent = string.sub(" ", 1, depth) - text = tostring(text) - print(indent..depth.."."..index.." - "..text) - end - - -- Print arguments - local i = 0 - for _, arg_opts in ipairs(parser.arguments) do - for _, arg_opt in ipairs(arg_opts) do - if is_sub_parser(arg_opt) then - prt(depth, i, arg_opt.key) - arg_opt.parser:dump(depth + 1) - else - prt(depth, i, arg_opt) - end - end - - i = i + 1 - end - - -- Print flags - for _, flag in ipairs(parser.flags) do - prt(depth, "F", flag) - end -end - --------------------------------------------------------------------------------- -function parser_be_precise(parser) - parser.precise = true - return parser -end - --------------------------------------------------------------------------------- -function is_parser(p) - return type(p) == "table" and getmetatable(p) == parser_meta_table -end - --------------------------------------------------------------------------------- -function is_sub_parser(sp) - return type(sp) == "table" and getmetatable(sp) == sub_parser_meta_table -end - --------------------------------------------------------------------------------- -local function get_sub_parser(argument, str) - for _, arg in ipairs(argument) do - if is_sub_parser(arg) then - if arg.key == str then - return arg.parser - end - end - end -end - --------------------------------------------------------------------------------- -function new_sub_parser(key, parser) - local sub_parser = {} - sub_parser.key = key - sub_parser.parser = parser - - setmetatable(sub_parser, sub_parser_meta_table) - return sub_parser -end - --------------------------------------------------------------------------------- -local function parser_disable_file_matching(parser) - parser.use_file_matching = false - return parser -end - --------------------------------------------------------------------------------- -local function parser_loop(parser, loop_point) - if loop_point == nil or type(loop_point) ~= "number" or loop_point < 1 then - loop_point = 1 - end - - parser.loop_point = loop_point - return parser -end - --------------------------------------------------------------------------------- -local function parser_initialise(parser, ...) - for _, word in ipairs({...}) do - local t = type(word) - if t == "string" then - parser:add_flags(word) - elseif t == "table" then - if is_sub_parser(word) and parser_is_flag(nil, word.key) then - parser:add_flags(word) - else - parser:add_arguments(word) - end - else - error("Additional arguments to new_parser() must be tables or strings", 2) - end - end -end - --------------------------------------------------------------------------------- -function clink.arg.new_parser(...) - local parser = {} - - -- Methods - parser.set_flags = parser_set_flags - parser.add_flags = parser_add_flags - parser.set_arguments = parser_set_arguments - parser.add_arguments = parser_add_arguments - parser.dump = parser_dump - parser.go = parser_go - parser.flatten_argument = parser_flatten_argument - parser.be_precise = parser_be_precise - parser.disable_file_matching = parser_disable_file_matching - parser.loop = parser_loop - parser.is_flag = parser_is_flag - - -- Members. - parser.flags = {} - parser.arguments = {} - parser.precise = false - parser.use_file_matching = true - parser.loop_point = 0 - - setmetatable(parser, parser_meta_table) - - -- If any arguments are provided treat them as parser's arguments or flags - if ... then - success, msg = pcall(parser_initialise, parser, ...) - if not success then - error(msg, 2) - end - end - - return parser -end - --------------------------------------------------------------------------------- -function merge_parsers(lhs, rhs) - -- Merging parsers is not a trivial matter and this implementation is far - -- from correct. It is however sufficient for the majority of cases. - - -- Merge flags. - for _, rflag in ipairs(rhs.flags) do - table.insert(lhs.flags, rflag) - end - - -- Remove (and save value of) the first argument in RHS. - local rhs_arg_1 = table.remove(rhs.arguments, 1) - if rhs_arg_1 == nil then - return - end - - -- Get reference to the LHS's first argument table (creating it if needed). - local lhs_arg_1 = lhs.arguments[1] - if lhs_arg_1 == nil then - lhs_arg_1 = {} - table.insert(lhs.arguments, lhs_arg_1) - end - - -- Link RHS to LHS through sub-parsers. - for _, rarg in ipairs(rhs_arg_1) do - local child - - -- Split sub parser - if is_sub_parser(rarg) then - child = rarg.parser - rarg = rarg.key - else - child = rhs - end - - -- If LHS's first argument has rarg in it which links to a sub-parser - -- then we need to recursively merge them. - local lhs_sub_parser = get_sub_parser(lhs_arg_1, rarg) - if lhs_sub_parser then - merge_parsers(lhs_sub_parser, child) - else - local to_add = rarg - if type(rarg) ~= "function" then - to_add = rarg .. child - end - - table.insert(lhs_arg_1, to_add) - end - end -end - --------------------------------------------------------------------------------- -function clink.arg.register_parser(cmd, parser) - if not is_parser(parser) then - local p = clink.arg.new_parser() - p:set_arguments({ parser }) - parser = p - end - - cmd = cmd:lower() - local prev = parsers[cmd] - if prev ~= nil then - merge_parsers(prev, parser) - else - parsers[cmd] = parser - end -end - --------------------------------------------------------------------------------- -local function argument_match_generator(text, first, last) - local leading = rl_state.line_buffer:sub(1, first - 1):lower() - - -- Extract the command. - local cmd_l, cmd_r - if leading:find("^%s*\"") then - -- Command appears to be surround by quotes. - cmd_l, cmd_r = leading:find("%b\"\"") - if cmd_l and cmd_r then - cmd_l = cmd_l + 1 - cmd_r = cmd_r - 1 - end - else - -- No quotes so the first, longest, non-whitespace word is extracted. - cmd_l, cmd_r = leading:find("[^%s]+") - end - - if not cmd_l or not cmd_r then - return false - end - - local regex = "[\\/:]*([^\\/:.]+)(%.*[%l]*)%s*$" - local _, _, cmd, ext = leading:sub(cmd_l, cmd_r):lower():find(regex) - - -- Check to make sure the extension extracted is in pathext. - if ext and ext ~= "" then - if not clink.get_env("pathext"):lower():match(ext.."[;$]", 1, true) then - return false - end - end - - -- Find a registered parser. - local parser = parsers[cmd] - if parser == nil then - return false - end - - -- Split the command line into parts. - local str = rl_state.line_buffer:sub(cmd_r + 2, last) - local parts = {} - for _, sub_str in ipairs(clink.quote_split(str, "\"")) do - -- Quoted strings still have their quotes. Look for those type of - -- strings, strip the quotes and add it completely. - if sub_str:sub(1, 1) == "\"" then - local l, r = sub_str:find("\"[^\"]+") - if l then - local part = sub_str:sub(l + 1, r) - table.insert(parts, part) - end - else - -- Extract non-whitespace parts. - for _, r, part in function () return sub_str:find("^%s*([^%s]+)") end do - table.insert(parts, part) - sub_str = sub_str:sub(r + 1) - end - end - end - - -- If 'text' is empty then add it as a part as it would have been skipped - -- by the split loop above. - if text == "" then - table.insert(parts, text) - end - - -- Extend rl_state with match generation state; text, first, and last. - rl_state.text = text - rl_state.first = first - rl_state.last = last - - -- Call the parser. - local needle = parts[#parts] - local ret = parser:go(parts) - if type(ret) ~= "table" then - return not ret - end - - -- Iterate through the matches the parser returned and collect matches. - for _, match in ipairs(ret) do - if clink.is_match(needle, match) then - clink.add_match(match) - end - end - - return true -end - --------------------------------------------------------------------------------- -clink.register_match_generator(argument_match_generator, 25) - --- vim: expandtab - ---{{{ history - ---15/03/06 DCN Created based on RemDebug ---28/04/06 DCN Update for Lua 5.1 ---01/06/06 DCN Fix command argument parsing --- Add step/over N facility --- Add trace lines facility ---05/06/06 DCN Add trace call/return facility ---06/06/06 DCN Make it behave when stepping through the creation of a coroutine ---06/06/06 DCN Integrate the simple debugger into the main one ---07/06/06 DCN Provide facility to step into coroutines ---13/06/06 DCN Fix bug that caused the function environment to get corrupted with the global one ---14/06/06 DCN Allow 'sloppy' file names when setting breakpoints ---04/08/06 DCN Allow for no space after command name ---11/08/06 DCN Use io.write not print ---30/08/06 DCN Allow access to array elements in 'dump' ---10/10/06 DCN Default to breakfile for all commands that require a filename and give '-' ---06/12/06 DCN Allow for punctuation characters in DUMP variable names ---03/01/07 DCN Add pause on/off facility ---19/06/07 DCN Allow for duff commands being typed in the debugger (thanks to Michael.Bringmann@lsi.com) --- Allow for case sensitive file systems (thanks to Michael.Bringmann@lsi.com) ---04/08/09 DCN Add optional line count param to pause ---05/08/09 DCN Reset the debug hook in Pause() even if we think we're started ---30/09/09 DCN Re-jig to not use co-routines (makes debugging co-routines awkward) ---01/10/09 DCN Add ability to break on reaching any line in a file ---24/07/13 TWW Added code for emulating setfenv/getfenv in Lua 5.2 as per --- http://lua-users.org/lists/lua-l/2010-06/msg00313.html ---25/07/13 TWW Copied Alex Parrill's fix for errors when tracing back across a C frame --- (https://github.com/ColonelThirtyTwo/clidebugger, 26/01/12) ---25/07/13 DCN Allow for windows and unix file name conventions in has_breakpoint ---26/07/13 DCN Allow for \ being interpreted as an escape inside a [] pattern in 5.2 - ---}}} ---{{{ description - ---A simple command line debug system for Lua written by Dave Nichols of ---Match-IT Limited. Its public domain software. Do with it as you wish. - ---This debugger was inspired by: --- RemDebug 1.0 Beta --- Copyright Kepler Project 2005 (http://www.keplerproject.org/remdebug) - ---Usage: --- require('debugger') --load the debug library --- pause(message) --start/resume a debug session - ---An assert() failure will also invoke the debugger. - ---}}} - -local IsWindows = string.find(string.lower(os.getenv('OS') or ''),'^windows') - -local coro_debugger -local events = { BREAK = 1, WATCH = 2, STEP = 3, SET = 4 } -local breakpoints = {} -local watches = {} -local step_into = false -local step_over = false -local step_lines = 0 -local step_level = {main=0} -local stack_level = {main=0} -local trace_level = {main=0} -local trace_calls = false -local trace_returns = false -local trace_lines = false -local ret_file, ret_line, ret_name -local current_thread = 'main' -local started = false -local pause_off = false -local _g = _G -local cocreate, cowrap = coroutine.create, coroutine.wrap -local pausemsg = 'pause' - -local aliases = { - p = "over", - t = "step", - q = "exit", - g = "run", - dv = "dump", - dt = "locs", - k = "trace", - bp = "setb", - bc = "delb", - bl = "listb", - pt = "out", -} - ---{{{ make Lua 5.2 compatible - -if not setfenv then -- Lua 5.2 - --[[ - As far as I can see, the only missing detail of these functions (except - for occasional bugs) to achieve 100% compatibility is the case of - 'getfenv' over a function that does not have an _ENV variable (that is, - it uses no globals). - - We could use a weak table to keep the environments of these functions - when set by setfenv, but that still misses the case of a function - without _ENV that was not subjected to setfenv. - - -- Roberto - ]]-- - - setfenv = setfenv or function(f, t) - f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func) - local name - local up = 0 - repeat - up = up + 1 - name = debug.getupvalue(f, up) - until name == '_ENV' or name == nil - if name then - debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue - debug.setupvalue(f, up, t) - end - end - - getfenv = getfenv or function(f) - f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func) - local name, val - local up = 0 - repeat - up = up + 1 - name, val = debug.getupvalue(f, up) - until name == '_ENV' or name == nil - return val - end - - unpack = table.unpack - -end - ---}}} - ---{{{ local hints -- command help ---The format in here is name=summary|description -local hints = { - -pause = [[ -pause(msg[,lines][,force]) -- start/resume a debugger session| - -This can only be used in your code or from the console as a means to -start/resume a debug session. -If msg is given that is shown when the session starts/resumes. Useful to -give a context if you've instrumented your code with pause() statements. - -If lines is given, the script pauses after that many lines, else it pauses -immediately. - -If force is true, the pause function is honoured even if poff has been used. -This is useful when in an interactive console session to regain debugger -control. -]], - -poff = [[ -poff -- turn off pause() command| - -This causes all pause() commands to be ignored. This is useful if you have -instrumented your code in a busy loop and want to continue normal execution -with no further interruption. -]], - -pon = [[ -pon -- turn on pause() command| - -This re-instates honouring the pause() commands you may have instrumented -your code with. -]], - -setb = [[ -setb [line file] -- set a breakpoint to line/file|, line 0 means 'any' - -If file is omitted or is "-" the breakpoint is set at the file for the -currently set level (see "set"). Execution pauses when this line is about -to be executed and the debugger session is re-activated. - -The file can be given as the fully qualified name, partially qualified or -just the file name. E.g. if file is set as "myfile.lua", then whenever -execution reaches any file that ends with "myfile.lua" it will pause. If -no extension is given, any extension will do. - -If the line is given as 0, then reaching any line in the file will do. -]], - -delb = [[ -delb [line file] -- removes a breakpoint| - -If file is omitted or is "-" the breakpoint is removed for the file of the -currently set level (see "set"). -]], - -delallb = [[ -delallb -- removes all breakpoints| -]], - -setw = [[ -setw -- adds a new watch expression| - -The expression is evaluated before each line is executed. If the expression -yields true then execution is paused and the debugger session re-activated. -The expression is executed in the context of the line about to be executed. -]], - -delw = [[ -delw -- removes the watch expression at index| - -The index is that returned when the watch expression was set by setw. -]], - -delallw = [[ -delallw -- removes all watch expressions| -]], - -run = [[ -run -- run until next breakpoint or watch expression| -]], - -step = [[ -step [N] -- run next N lines, stepping into function calls| - -If N is omitted, use 1. -]], - -over = [[ -over [N] -- run next N lines, stepping over function calls| - -If N is omitted, use 1. -]], - -out = [[ -out [N] -- run lines until stepped out of N functions| - -If N is omitted, use 1. -If you are inside a function, using "out 1" will run until you return -from that function to the caller. -]], - -gotoo = [[ -gotoo [line file] -- step to line in file| - -This is equivalent to 'setb line file', followed by 'run', followed -by 'delb line file'. -]], - -listb = [[ -listb -- lists breakpoints| -]], - -listw = [[ -listw -- lists watch expressions| -]], - -set = [[ -set [level] -- set context to stack level, omitted=show| - -If level is omitted it just prints the current level set. -This sets the current context to the level given. This affects the -context used for several other functions (e.g. vars). The possible -levels are those shown by trace. -]], - -vars = [[ -vars [depth] -- list context locals to depth, omitted=1| - -If depth is omitted then uses 1. -Use a depth of 0 for the maximum. -Lists all non-nil local variables and all non-nil upvalues in the -currently set context. For variables that are tables, lists all fields -to the given depth. -]], - -fenv = [[ -fenv [depth] -- list context function env to depth, omitted=1| - -If depth is omitted then uses 1. -Use a depth of 0 for the maximum. -Lists all function environment variables in the currently set context. -For variables that are tables, lists all fields to the given depth. -]], - -glob = [[ -glob [depth] -- list globals to depth, omitted=1| - -If depth is omitted then uses 1. -Use a depth of 0 for the maximum. -Lists all global variables. -For variables that are tables, lists all fields to the given depth. -]], - -ups = [[ -ups -- list all the upvalue names| - -These names will also be in the "vars" list unless their value is nil. -This provides a means to identify which vars are upvalues and which are -locals. If a name is both an upvalue and a local, the local value takes -precedance. -]], - -locs = [[ -locs -- list all the locals names| - -These names will also be in the "vars" list unless their value is nil. -This provides a means to identify which vars are upvalues and which are -locals. If a name is both an upvalue and a local, the local value takes -precedance. -]], - -dump = [[ -dump [depth] -- dump all fields of variable to depth| - -If depth is omitted then uses 1. -Use a depth of 0 for the maximum. -Prints the value of in the currently set context level. If -is a table, lists all fields to the given depth. can be just a -name, or name.field or name.# to any depth, e.g. t.1.f accesses field -'f' in array element 1 in table 't'. - -Can also be called from a script as dump(var,depth). -]], - -tron = [[ -tron [crl] -- turn trace on for (c)alls, (r)etuns, (l)lines| - -If no parameter is given then tracing is turned off. -When tracing is turned on a line is printed to the console for each -debug 'event' selected. c=function calls, r=function returns, l=lines. -]], - -trace = [[ -trace -- dumps a stack trace| - -Format is [level] = file,line,name -The level is a candidate for use by the 'set' command. -]], - -info = [[ -info -- dumps the complete debug info captured| - -Only useful as a diagnostic aid for the debugger itself. This information -can be HUGE as it dumps all variables to the maximum depth, so be careful. -]], - -show = [[ -show line file X Y -- show X lines before and Y after line in file| - -If line is omitted or is '-' then the current set context line is used. -If file is omitted or is '-' then the current set context file is used. -If file is not fully qualified and cannot be opened as specified, then -a search for the file in the package[path] is performed using the usual -"require" searching rules. If no file extension is given, .lua is used. -Prints the lines from the source file around the given line. -]], - -exit = [[ -exit -- exits debugger, re-start it using pause()| -]], - -help = [[ -help [command] -- show this list or help for command| -]], - -[""] = [[ - -- execute a statement in the current context| - -The statement can be anything that is legal in the context, including -assignments. Such assignments affect the context and will be in force -immediately. Any results returned are printed. Use '=' as a short-hand -for 'return', e.g. "=func(arg)" will call 'func' with 'arg' and print -the results, and "=var" will just print the value of 'var'. -]], - -what = [[ -what -- show where is defined (if known)| -]], - -} ---}}} - ---{{{ local function getinfo(level,field) - ---like debug.getinfo but copes with no activation record at the given level ---and knows how to get 'field'. 'field' can be the name of any of the ---activation record fields or any of the 'what' names or nil for everything. ---only valid when using the stack level to get info, not a function name. - -local function getinfo(level,field) - level = level + 1 --to get to the same relative level as the caller - if not field then return debug.getinfo(level) end - local what - if field == 'name' or field == 'namewhat' then - what = 'n' - elseif field == 'what' or field == 'source' or field == 'linedefined' or field == 'lastlinedefined' or field == 'short_src' then - what = 'S' - elseif field == 'currentline' then - what = 'l' - elseif field == 'nups' then - what = 'u' - elseif field == 'func' then - what = 'f' - else - return debug.getinfo(level,field) - end - local ar = debug.getinfo(level,what) - if ar then return ar[field] else return nil end -end - ---}}} ---{{{ local function indented( level, ... ) - -local function indented( level, ... ) - io.write( string.rep(' ',level), table.concat({...}), '\n' ) -end - ---}}} ---{{{ local function dumpval( level, name, value, limit ) - -local dumpvisited - -local function dumpval( level, name, value, limit ) - local index - if type(name) == 'number' then - index = string.format('[%d] = ',name) - elseif type(name) == 'string' - and (name == '__VARSLEVEL__' or name == '__ENVIRONMENT__' or name == '__GLOBALS__' or name == '__UPVALUES__' or name == '__LOCALS__') then - --ignore these, they are debugger generated - return - elseif type(name) == 'string' and string.find(name,'^[_%a][_.%w]*$') then - index = name ..' = ' - else - index = string.format('[%q] = ',tostring(name)) - end - if type(value) == 'table' then - if dumpvisited[value] then - indented( level, index, string.format('ref%q;',dumpvisited[value]) ) - else - dumpvisited[value] = tostring(value) - if (limit or 0) > 0 and level+1 >= limit then - indented( level, index, dumpvisited[value] ) - else - indented( level, index, '{ -- ', dumpvisited[value] ) - for n,v in pairs(value) do - dumpval( level+1, n, v, limit ) - end - indented( level, '};' ) - end - end - else - if type(value) == 'string' then - if string.len(value) > 40 then - indented( level, index, '[[', value, ']];' ) - else - indented( level, index, string.format('%q',value), ';' ) - end - else - indented( level, index, tostring(value), ';' ) - end - end -end - ---}}} ---{{{ local function dumpvar( value, limit, name ) - -local function dumpvar( value, limit, name ) - dumpvisited = {} - dumpval( 0, name or tostring(value), value, limit ) -end - ---}}} ---{{{ local function show(file,line,before,after) - ---show +/-N lines of a file around line M - -local function show(file,line,before,after) - - line = tonumber(line or 1) - before = tonumber(before or 10) - after = tonumber(after or before) - - if not string.find(file,'%.') then file = file..'.lua' end - - local f = io.open(file,'r') - if not f then - --{{{ try to find the file in the path - - -- - -- looks for a file in the package path - -- - local path = package.path or LUA_PATH or '' - for c in string.gmatch (path, "[^;]+") do - local c = string.gsub (c, "%?%.lua", file) - f = io.open (c,'r') - if f then - break - end - end - - --}}} - if not f then - io.write('Cannot find '..file..'\n') - return - end - end - - local i = 0 - for l in f:lines() do - i = i + 1 - if i >= (line-before) then - if i > (line+after) then break end - if i == line then - io.write(i..'***\t'..l..'\n') - else - io.write(i..'\t'..l..'\n') - end - end - end - - f:close() - -end - ---}}} ---{{{ local function tracestack(l) - -local function gi( i ) - return function() i=i+1 return debug.getinfo(i),i end -end - -local function gl( level, j ) - return function() j=j+1 return debug.getlocal( level, j ) end -end - -local function gu( func, k ) - return function() k=k+1 return debug.getupvalue( func, k ) end -end - -local traceinfo - -local function tracestack(l) - local l = l + 1 --NB: +1 to get level relative to caller - traceinfo = {} - traceinfo.pausemsg = pausemsg - for ar,i in gi(l) do - table.insert( traceinfo, ar ) - if ar.what ~= 'C' then - local names = {} - local values = {} - for n,v in gl(i,0) do - if string.sub(n,1,1) ~= '(' then --ignore internal control variables - table.insert( names, n ) - table.insert( values, v ) - end - end - if #names > 0 then - ar.lnames = names - ar.lvalues = values - end - end - if ar.func then - local names = {} - local values = {} - for n,v in gu(ar.func,0) do - if string.sub(n,1,1) ~= '(' then --ignore internal control variables - table.insert( names, n ) - table.insert( values, v ) - end - end - if #names > 0 then - ar.unames = names - ar.uvalues = values - end - end - end -end - ---}}} ---{{{ local function trace() - -local function trace(set) - local mark - for level,ar in ipairs(traceinfo) do - if level == set then - mark = '***' - else - mark = '' - end - io.write('['..level..']'..mark..'\t'..(ar.name or ar.what)..' in '..ar.short_src..':'..ar.currentline..'\n') - end -end - ---}}} ---{{{ local function info() - -local function info() dumpvar( traceinfo, 0, 'traceinfo' ) end - ---}}} - ---{{{ local function set_breakpoint(file, line, once) - -local function set_breakpoint(file, line, once) - if not breakpoints[line] then - breakpoints[line] = {} - end - if once then - breakpoints[line][file] = 1 - else - breakpoints[line][file] = true - end -end - ---}}} ---{{{ local function remove_breakpoint(file, line) - -local function remove_breakpoint(file, line) - if breakpoints[line] then - breakpoints[line][file] = nil - end -end - ---}}} ---{{{ local function has_breakpoint(file, line) - ---allow for 'sloppy' file names ---search for file and all variations walking up its directory hierachy ---ditto for the file with no extension ---a breakpoint can be permenant or once only, if once only its removed ---after detection here, these are used for temporary breakpoints in the ---debugger loop when executing the 'gotoo' command ---a breakpoint on line 0 of a file means any line in that file - -local function has_breakpoint(file, line) - local isLine = breakpoints[line] - local isZero = breakpoints[0] - if not isLine and not isZero then return false end - local noext = string.gsub(file,"(%..-)$",'',1) - if noext == file then noext = nil end - while file do - if isLine and isLine[file] then - if isLine[file] == 1 then isLine[file] = nil end - return true - end - if isZero and isZero[file] then - if isZero[file] == 1 then isZero[file] = nil end - return true - end - if IsWindows then - file = string.match(file,"[:/\\](.+)$") - else - file = string.match(file,"[:/](.+)$") - end - end - while noext do - if isLine and isLine[noext] then - if isLine[noext] == 1 then isLine[noext] = nil end - return true - end - if isZero and isZero[noext] then - if isZero[noext] == 1 then isZero[noext] = nil end - return true - end - if IsWindows then - noext = string.match(noext,"[:/\\](.+)$") - else - noext = string.match(noext,"[:/](.+)$") - end - end - return false -end - ---}}} ---{{{ local function capture_vars(ref,level,line) - -local function capture_vars(ref,level,line) - --get vars, file and line for the given level relative to debug_hook offset by ref - - local lvl = ref + level --NB: This includes an offset of +1 for the call to here - - --{{{ capture variables - - local ar = debug.getinfo(lvl, "f") - if not ar then return {},'?',0 end - - local vars = {__UPVALUES__={}, __LOCALS__={}} - local i - - local func = ar.func - if func then - i = 1 - while true do - local name, value = debug.getupvalue(func, i) - if not name then break end - if string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables - vars[name] = value - vars.__UPVALUES__[i] = name - end - i = i + 1 - end - vars.__ENVIRONMENT__ = getfenv(func) - end - - vars.__GLOBALS__ = getfenv(0) - - i = 1 - while true do - local name, value = debug.getlocal(lvl, i) - if not name then break end - if string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables - vars[name] = value - vars.__LOCALS__[i] = name - end - i = i + 1 - end - - vars.__VARSLEVEL__ = level - - if func then - --NB: Do not do this until finished filling the vars table - setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) - end - - --NB: Do not read or write the vars table anymore else the metatable functions will get invoked! - - --}}} - - local file = getinfo(lvl, "source") - if string.find(file, "@") == 1 then - file = string.sub(file, 2) - end - if IsWindows then file = string.lower(file) end - - if not line then - line = getinfo(lvl, "currentline") - end - - return vars,file,line - -end - ---}}} ---{{{ local function restore_vars(ref,vars) - -local function restore_vars(ref,vars) - - if type(vars) ~= 'table' then return end - - local level = vars.__VARSLEVEL__ --NB: This level is relative to debug_hook offset by ref - if not level then return end - - level = level + ref --NB: This includes an offset of +1 for the call to here - - local i - local written_vars = {} - - i = 1 - while true do - local name, value = debug.getlocal(level, i) - if not name then break end - if vars[name] and string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables - debug.setlocal(level, i, vars[name]) - written_vars[name] = true - end - i = i + 1 - end - - local ar = debug.getinfo(level, "f") - if not ar then return end - - local func = ar.func - if func then - - i = 1 - while true do - local name, value = debug.getupvalue(func, i) - if not name then break end - if vars[name] and string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables - if not written_vars[name] then - debug.setupvalue(func, i, vars[name]) - end - written_vars[name] = true - end - i = i + 1 - end - - end - -end - ---}}} ---{{{ local function trace_event(event, line, level) - -local function print_trace(level,depth,event,file,line,name) - - --NB: level here is relative to the caller of trace_event, so offset by 2 to get to there - level = level + 2 - - local file = file or getinfo(level,'short_src') - local line = line or getinfo(level,'currentline') - local name = name or getinfo(level,'name') - - local prefix = '' - if current_thread ~= 'main' then prefix = '['..tostring(current_thread)..'] ' end - - io.write(prefix.. - string.format('%08.2f:%02i.',os.clock(),depth).. - string.rep('.',depth%32).. - (file or '')..' ('..(line or '')..') '.. - (name or '').. - ' ('..event..')\n') - -end - -local function trace_event(event, line, level) - - if event == 'return' and trace_returns then - --note the line info for later - ret_file = getinfo(level+1,'short_src') - ret_line = getinfo(level+1,'currentline') - ret_name = getinfo(level+1,'name') - end - - if event ~= 'line' then return end - - local slevel = stack_level[current_thread] - local tlevel = trace_level[current_thread] - - if trace_calls and slevel > tlevel then - --we are now in the function called, so look back 1 level further to find the calling file and line - print_trace(level+1,slevel-1,'c',nil,nil,getinfo(level+1,'name')) - end - - if trace_returns and slevel < tlevel then - print_trace(level,slevel,'r',ret_file,ret_line,ret_name) - end - - if trace_lines then - print_trace(level,slevel,'l') - end - - trace_level[current_thread] = stack_level[current_thread] - -end - ---}}} ---{{{ local function report(ev, vars, file, line, idx_watch) - -local function report(ev, vars, file, line, idx_watch) - function show_source() - show(traceinfo[1].short_src, traceinfo[1].currentline, 2, 2) - end - - local vars = vars or {} - local file = file or '?' - local line = line or 0 - local prefix = '' - if current_thread ~= 'main' then prefix = '['..tostring(current_thread)..'] ' end - if ev == events.STEP then - io.write(prefix.."Paused at file "..file.." line "..line..' ('..stack_level[current_thread]..')\n') - show_source() - elseif ev == events.BREAK then - io.write(prefix.."Paused at file "..file.." line "..line..' ('..stack_level[current_thread]..') (breakpoint)\n') - show_source() - elseif ev == events.WATCH then - io.write(prefix.."Paused at file "..file.." line "..line..' ('..stack_level[current_thread]..')'.." (watch expression "..idx_watch.. ": ["..watches[idx_watch].exp.."])\n") - show_source() - elseif ev == events.SET then - --do nothing - else - io.write(prefix.."Error in application: "..file.." line "..line.."\n") - end - if ev ~= events.SET then - if pausemsg and pausemsg ~= '' then io.write('Message: '..pausemsg..'\n') end - pausemsg = '' - end - return vars, file, line -end - ---}}} - ---{{{ local function debugger_loop(ev, vars, file, line, idx_watch) - -local last_line = "" - -local function debugger_loop(ev, vars, file, line, idx_watch) - - local eval_env = vars or {} - local breakfile = file or '?' - local breakline = line or 0 - - local command, args - - --{{{ local function getargs(spec) - - --get command arguments according to the given spec from the args string - --the spec has a single character for each argument, arguments are separated - --by white space, the spec characters can be one of: - -- F for a filename (defaults to breakfile if - given in args) - -- L for a line number (defaults to breakline if - given in args) - -- N for a number - -- V for a variable name - -- S for a string - - local function getargs(spec) - local res={} - local char,arg - local ptr=1 - for i=1,string.len(spec) do - char = string.sub(spec,i,i) - if char == 'F' then - _,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr) - if not arg or arg == '' then arg = '-' end - if arg == '-' then arg = breakfile end - elseif char == 'L' then - _,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr) - if not arg or arg == '' then arg = '-' end - if arg == '-' then arg = breakline end - arg = tonumber(arg) or 0 - elseif char == 'N' then - _,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr) - if not arg or arg == '' then arg = '0' end - arg = tonumber(arg) or 0 - elseif char == 'V' then - _,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr) - if not arg or arg == '' then arg = '' end - elseif char == 'S' then - _,ptr,arg = string.find(args..' ',"%s*([%w%p]*)%s*",ptr) - if not arg or arg == '' then arg = '' end - else - arg = '' - end - table.insert(res,arg or '') - end - return unpack(res) - end - - --}}} - - while true do - io.write("[DEBUG]> ") - local line = io.read("*line") - if line == nil then io.write('\n'); line = 'exit' end - - if line == "" then - line = last_line - else - last_line = line - end - io.write("'" .. last_line .. "'\n") - - if string.find(line, "^[a-z]+") then - command = string.sub(line, string.find(line, "^[a-z]+")) - args = string.gsub(line,"^[a-z]+%s*",'',1) --strip command off line - else - command = '' - end - - command = aliases[command] or command - - if command == "setb" then - --{{{ set breakpoint - - local line, filename = getargs('LF') - if filename ~= '' and line ~= '' then - set_breakpoint(filename,line) - io.write("Breakpoint set in file "..filename..' line '..line..'\n') - else - io.write("Bad request\n") - end - - --}}} - - elseif command == "delb" then - --{{{ delete breakpoint - - local line, filename = getargs('LF') - if filename ~= '' and line ~= '' then - remove_breakpoint(filename, line) - io.write("Breakpoint deleted from file "..filename..' line '..line.."\n") - else - io.write("Bad request\n") - end - - --}}} - - elseif command == "delallb" then - --{{{ delete all breakpoints - breakpoints = {} - io.write('All breakpoints deleted\n') - --}}} - - elseif command == "listb" then - --{{{ list breakpoints - for i, v in pairs(breakpoints) do - for ii, vv in pairs(v) do - io.write("Break at: "..i..' in '..ii..'\n') - end - end - --}}} - - elseif command == "setw" then - --{{{ set watch expression - - if args and args ~= '' then - local func = loadstring("return(" .. args .. ")") - local newidx = #watches + 1 - watches[newidx] = {func = func, exp = args} - io.write("Set watch exp no. " .. newidx..'\n') - else - io.write("Bad request\n") - end - - --}}} - - elseif command == "delw" then - --{{{ delete watch expression - - local index = tonumber(args) - if index then - watches[index] = nil - io.write("Watch expression deleted\n") - else - io.write("Bad request\n") - end - - --}}} - - elseif command == "delallw" then - --{{{ delete all watch expressions - watches = {} - io.write('All watch expressions deleted\n') - --}}} - - elseif command == "listw" then - --{{{ list watch expressions - for i, v in pairs(watches) do - io.write("Watch exp. " .. i .. ": " .. v.exp..'\n') - end - --}}} - - elseif command == "run" then - --{{{ run until breakpoint - step_into = false - step_over = false - return 'cont' - --}}} - - elseif command == "step" then - --{{{ step N lines (into functions) - local N = tonumber(args) or 1 - step_over = false - step_into = true - step_lines = tonumber(N or 1) - return 'cont' - --}}} - - elseif command == "over" then - --{{{ step N lines (over functions) - local N = tonumber(args) or 1 - step_into = false - step_over = true - step_lines = tonumber(N or 1) - step_level[current_thread] = stack_level[current_thread] - return 'cont' - --}}} - - elseif command == "out" then - --{{{ step N lines (out of functions) - local N = tonumber(args) or 1 - step_into = false - step_over = true - step_lines = 1 - step_level[current_thread] = stack_level[current_thread] - tonumber(N or 1) - return 'cont' - --}}} - - elseif command == "gotoo" then - --{{{ step until reach line - local line, filename = getargs('LF') - if line ~= '' then - step_over = false - step_into = false - if has_breakpoint(filename,line) then - return 'cont' - else - set_breakpoint(filename,line,true) - return 'cont' - end - else - io.write("Bad request\n") - end - --}}} - - elseif command == "set" then - --{{{ set/show context level - local level = args - if level and level == '' then level = nil end - if level then return level end - --}}} - - elseif command == "vars" then - --{{{ list context variables - local depth = args - if depth and depth == '' then depth = nil end - depth = tonumber(depth) or 1 - dumpvar(eval_env, depth+1, 'variables') - --}}} - - elseif command == "glob" then - --{{{ list global variables - local depth = args - if depth and depth == '' then depth = nil end - depth = tonumber(depth) or 1 - dumpvar(eval_env.__GLOBALS__,depth+1,'globals') - --}}} - - elseif command == "fenv" then - --{{{ list function environment variables - local depth = args - if depth and depth == '' then depth = nil end - depth = tonumber(depth) or 1 - dumpvar(eval_env.__ENVIRONMENT__,depth+1,'environment') - --}}} - - elseif command == "ups" then - --{{{ list upvalue names - dumpvar(eval_env.__UPVALUES__,2,'upvalues') - --}}} - - elseif command == "locs" then - --{{{ list locals names - dumpvar(eval_env.__LOCALS__,2,'upvalues') - --}}} - - elseif command == "what" then - --{{{ show where a function is defined - if args and args ~= '' then - local v = eval_env - local n = nil - for w in string.gmatch(args,"[%w_]+") do - v = v[w] - if n then n = n..'.'..w else n = w end - if not v then break end - end - if type(v) == 'function' then - local def = debug.getinfo(v,'S') - if def then - io.write(def.what..' in '..def.short_src..' '..def.linedefined..'..'..def.lastlinedefined..'\n') - else - io.write('Cannot get info for '..v..'\n') - end - else - io.write(v..' is not a function\n') - end - else - io.write("Bad request\n") - end - --}}} - - elseif command == "dump" then - --{{{ dump a variable - local name, depth = getargs('VN') - if name ~= '' then - if depth == '' or depth == 0 then depth = nil end - depth = tonumber(depth or 1) - local v = eval_env - local n = nil - for w in string.gmatch(name,"[^%.]+") do --get everything between dots - if tonumber(w) then - v = v[tonumber(w)] - else - v = v[w] - end - if n then n = n..'.'..w else n = w end - if not v then break end - end - dumpvar(v,depth+1,n) - else - io.write("Bad request\n") - end - --}}} - - elseif command == "show" then - --{{{ show file around a line or the current breakpoint - - local line, file, before, after = getargs('LFNN') - if before == 0 then before = 10 end - if after == 0 then after = before end - - if file ~= '' and file ~= "=stdin" then - show(file,line,before,after) - else - io.write('Nothing to show\n') - end - - --}}} - - elseif command == "poff" then - --{{{ turn pause command off - pause_off = true - --}}} - - elseif command == "pon" then - --{{{ turn pause command on - pause_off = false - --}}} - - elseif command == "tron" then - --{{{ turn tracing on/off - local option = getargs('S') - trace_calls = false - trace_returns = false - trace_lines = false - if string.find(option,'c') then trace_calls = true end - if string.find(option,'r') then trace_returns = true end - if string.find(option,'l') then trace_lines = true end - --}}} - - elseif command == "trace" then - --{{{ dump a stack trace - trace(eval_env.__VARSLEVEL__) - --}}} - - elseif command == "info" then - --{{{ dump all debug info captured - info() - --}}} - - elseif command == "pause" then - --{{{ not allowed in here - io.write('pause() should only be used in the script you are debugging\n') - --}}} - - elseif command == "help" then - --{{{ help - local command = getargs('S') - if command ~= '' and hints[command] then - io.write(hints[command]..'\n') - else - for _,v in pairs(hints) do - local _,_,h = string.find(v,"(.+)|") - io.write(h..'\n') - end - end - --}}} - - elseif command == "exit" then - --{{{ exit debugger - return 'stop' - --}}} - - elseif line ~= '' then - --{{{ just execute whatever it is in the current context - - --map line starting with "=..." to "return ..." - if string.sub(line,1,1) == '=' then line = string.gsub(line,'=','return ',1) end - - local ok, func = pcall(loadstring,line) - if func == nil then --Michael.Bringmann@lsi.com - io.write("Compile error: "..line..'\n') - elseif not ok then - io.write("Compile error: "..func..'\n') - else - setfenv(func, eval_env) - local res = {pcall(func)} - if res[1] then - if res[2] then - table.remove(res,1) - for _,v in ipairs(res) do - io.write(tostring(v)) - io.write('\t') - end - io.write('\n') - end - --update in the context - return 0 - else - io.write("Run error: "..res[2]..'\n') - end - end - - --}}} - end - end - -end - ---}}} ---{{{ local function debug_hook(event, line, level, thread) - -local function debug_hook(event, line, level, thread) - if not started then debug.sethook(); coro_debugger = nil; return end - current_thread = thread or 'main' - local level = level or 2 - trace_event(event,line,level) - if event == "call" then - stack_level[current_thread] = stack_level[current_thread] + 1 - elseif event == "return" then - stack_level[current_thread] = stack_level[current_thread] - 1 - if stack_level[current_thread] < 0 then stack_level[current_thread] = 0 end - else - local vars,file,line = capture_vars(level,1,line) - local stop, ev, idx = false, events.STEP, 0 - while true do - for index, value in pairs(watches) do - setfenv(value.func, vars) - local status, res = pcall(value.func) - if status and res then - ev, idx = events.WATCH, index - stop = true - break - end - end - if stop then break end - if (step_into) - or (step_over and (stack_level[current_thread] <= step_level[current_thread] or stack_level[current_thread] == 0)) then - step_lines = step_lines - 1 - if step_lines < 1 then - ev, idx = events.STEP, 0 - break - end - end - if has_breakpoint(file, line) then - ev, idx = events.BREAK, 0 - break - end - return - end - tracestack(level) - if not coro_debugger then - io.write("\nLua Debugger\n") - vars, file, line = report(ev, vars, file, line, idx) - io.write("Type 'help' for commands\n") - coro_debugger = true - else - vars, file, line = report(ev, vars, file, line, idx) - end - local last_next = 1 - local next = 'ask' - local silent = false - while true do - if next == 'ask' then - next = debugger_loop(ev, vars, file, line, idx) - elseif next == 'cont' then - return - elseif next == 'stop' then - started = false - debug.sethook() - coro_debugger = nil - return - elseif tonumber(next) then --get vars for given level or last level - next = tonumber(next) - if next == 0 then silent = true; next = last_next else silent = false end - last_next = next - restore_vars(level,vars) - vars, file, line = capture_vars(level,next) - if not silent then - if vars and vars.__VARSLEVEL__ then - io.write('Level: '..vars.__VARSLEVEL__..'\n') - else - io.write('No level set\n') - end - end - ev = events.SET - next = 'ask' - else - io.write('Unknown command from debugger_loop: '..tostring(next)..'\n') - io.write('Stopping debugger\n') - next = 'stop' - end - end - end -end - ---}}} - ---{{{ coroutine.create - ---This function overrides the built-in for the purposes of propagating ---the debug hook settings from the creator into the created coroutine. - -_G.coroutine.create = function(f) - local thread - local hook, mask, count = debug.gethook() - if hook then - local function thread_hook(event,line) - hook(event,line,3,thread) - end - thread = cocreate(function(...) - stack_level[thread] = 0 - trace_level[thread] = 0 - step_level [thread] = 0 - debug.sethook(thread_hook,mask,count) - return f(...) - end) - return thread - else - return cocreate(f) - end -end - ---}}} ---{{{ coroutine.wrap - ---This function overrides the built-in for the purposes of propagating ---the debug hook settings from the creator into the created coroutine. - -_G.coroutine.wrap = function(f) - local thread - local hook, mask, count = debug.gethook() - if hook then - local function thread_hook(event,line) - hook(event,line,3,thread) - end - thread = cowrap(function(...) - stack_level[thread] = 0 - trace_level[thread] = 0 - step_level [thread] = 0 - debug.sethook(thread_hook,mask,count) - return f(...) - end) - return thread - else - return cowrap(f) - end -end - ---}}} - ---{{{ function pause(x,l,f) - --- --- Starts/resumes a debug session --- - -function pause(x,l,f) - if not f and pause_off then return end --being told to ignore pauses - pausemsg = x or 'pause' - local lines - local src = getinfo(2,'short_src') - if l then - lines = l --being told when to stop - elseif src == "stdin" then - lines = 1 --if in a console session, stop now - else - lines = 2 --if in a script, stop when get out of pause() - end - if started then - --we'll stop now 'cos the existing debug hook will grab us - step_lines = lines - step_into = true - debug.sethook(debug_hook, "crl") --reset it in case some external agent fiddled with it - else - --set to stop when get out of pause() - trace_level[current_thread] = 0 - step_level [current_thread] = 0 - stack_level[current_thread] = 1 - step_lines = lines - step_into = true - started = true - debug.sethook(debug_hook, "crl") --NB: this will cause an immediate entry to the debugger_loop - end -end - ---}}} ---{{{ function dump(v,depth) - ---shows the value of the given variable, only really useful ---when the variable is a table ---see dump debug command hints for full semantics - -function dump(v,depth) - dumpvar(v,(depth or 1)+1,tostring(v)) -end - ---}}} ---{{{ function debug.traceback(x) - -local _traceback = debug.traceback --note original function - ---override standard function -debug.traceback = function(x) - local assertmsg = _traceback(x) --do original function - pause(x) --let user have a look at stuff - return assertmsg --carry on -end - -_TRACEBACK = debug.traceback --Lua 5.0 function - ---}}} - --------------------------------------------------------------------------------- --- dir.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -function dir_match_generator_impl(text) - -- Strip off any path components that may be on text. - local prefix = "" - local i = text:find("[\\/:][^\\/:]*$") - if i then - prefix = text:sub(1, i) - end - - local include_dots = text:find("%.+$") ~= nil - - local matches = {} - local mask = text.."*" - - -- Find matches. - for _, dir in ipairs(clink.find_dirs(mask, true)) do - local file = prefix..dir - - if include_dots or (dir ~= "." and dir ~= "..") then - if clink.is_match(text, file) then - table.insert(matches, prefix..dir) - end - end - end - - return matches -end - --------------------------------------------------------------------------------- -local function dir_match_generator(word) - local matches = dir_match_generator_impl(word) - - -- If there was no matches but text is a dir then use it as the single match. - -- Otherwise tell readline that matches are files and it will do magic. - if #matches == 0 then - if clink.is_dir(rl_state.text) then - table.insert(matches, rl_state.text) - end - else - clink.matches_are_files() - end - - return matches -end - --------------------------------------------------------------------------------- -clink.arg.register_parser("cd", dir_match_generator) -clink.arg.register_parser("chdir", dir_match_generator) -clink.arg.register_parser("pushd", dir_match_generator) -clink.arg.register_parser("rd", dir_match_generator) -clink.arg.register_parser("rmdir", dir_match_generator) -clink.arg.register_parser("md", dir_match_generator) -clink.arg.register_parser("mkdir", dir_match_generator) - --- vim: expandtab - --------------------------------------------------------------------------------- --- env.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local special_env_vars = { - "cd", "date", "time", "random", "errorlevel", - "cmdextversion", "cmdcmdline", "highestnumanodenumber" -} - --------------------------------------------------------------------------------- -local function env_vars_display_filter(matches) - local to_display = {} - for _, m in ipairs(matches) do - local _, _, out = m:find("(%%[^%%]+%%)$") - table.insert(to_display, out) - end - - return to_display -end - --------------------------------------------------------------------------------- -local function env_vars_find_matches(candidates, prefix, part) - local part_len = #part - for _, name in ipairs(candidates) do - if clink.lower(name:sub(1, part_len)) == part then - clink.add_match(prefix..'%'..name:lower()..'%') - end - end -end - --------------------------------------------------------------------------------- -local function env_vars_match_generator(text, first, last) - local all = rl_state.line_buffer:sub(1, last) - - -- Skip pairs of %s - local i = 1 - for _, r in function () return all:find("%b%%", i) end do - i = r + 2 - end - - -- Find a solitary % - local i = all:find("%%", i) - if not i then - return false - end - - if i < first then - return false - end - - local part = clink.lower(all:sub(i + 1)) - local part_len = #part - - i = i - first - local prefix = text:sub(1, i) - - env_vars_find_matches(clink.get_env_var_names(), prefix, part) - env_vars_find_matches(special_env_vars, prefix, part) - - if clink.match_count() >= 1 then - clink.match_display_filter = env_vars_display_filter - - clink.suppress_char_append() - clink.suppress_quoting() - - return true - end - - return false -end - --------------------------------------------------------------------------------- -if clink.get_host_process() == "cmd.exe" then - clink.register_match_generator(env_vars_match_generator, 10) -end - --- vim: expandtab - --------------------------------------------------------------------------------- --- exec.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local dos_commands = { - "assoc", "break", "call", "cd", "chcp", "chdir", "cls", "color", "copy", - "date", "del", "dir", "diskcomp", "diskcopy", "echo", "endlocal", "erase", - "exit", "for", "format", "ftype", "goto", "graftabl", "if", "md", "mkdir", - "mklink", "more", "move", "path", "pause", "popd", "prompt", "pushd", "rd", - "rem", "ren", "rename", "rmdir", "set", "setlocal", "shift", "start", - "time", "title", "tree", "type", "ver", "verify", "vol" -} - --------------------------------------------------------------------------------- -local function get_environment_paths() - local paths = clink.split(clink.get_env("PATH"), ";") - - -- We're expecting absolute paths and as ';' is a valid path character - -- there maybe unneccessary splits. Here we resolve them. - local paths_merged = { paths[1] } - for i = 2, #paths, 1 do - if not paths[i]:find("^[a-zA-Z]:") then - local t = paths_merged[#paths_merged]; - paths_merged[#paths_merged] = t..paths[i] - else - table.insert(paths_merged, paths[i]) - end - end - - -- Append slashes. - for i = 1, #paths_merged, 1 do - paths_merged[i] = paths_merged[i].."/" - end - - return paths_merged -end - --------------------------------------------------------------------------------- -local function exec_find_dirs(pattern, case_map) - local ret = {} - - for _, dir in ipairs(clink.find_dirs(pattern, case_map)) do - if dir ~= "." and dir ~= ".." then - table.insert(ret, dir) - end - end - - return ret -end - --------------------------------------------------------------------------------- -local function exec_match_generator(text, first, last) - -- If match style setting is < 0 then consider executable matching disabled. - local match_style = clink.get_setting_int("exec_match_style") - if match_style < 0 then - return false - end - - -- We're only interested in exec completion if this is the first word of the - -- line, or the first word after a command separator. - if clink.get_setting_int("space_prefix_match_files") > 0 then - if first > 1 then - return false - end - else - local leading = rl_state.line_buffer:sub(1, first - 1) - local is_first = leading:find("^%s*\"*$") - if not is_first then - return false - end - end - - -- Split text into directory and name - local text_dir = "" - local text_name = text - local i = text:find("[\\/:][^\\/:]*$") - if i then - text_dir = text:sub(1, i) - text_name = text:sub(i + 1) - end - - local paths - if not text:find("[\\/:]") then - -- If the terminal is cmd.exe check it's commands for matches. - if clink.get_host_process() == "cmd.exe" then - clink.match_words(text, dos_commands) - end - - -- Add console aliases as matches. - local aliases = clink.get_console_aliases() - clink.match_words(text, aliases) - - paths = get_environment_paths(); - else - paths = {} - - -- 'text' is an absolute or relative path. If we're doing Bash-style - -- matching should now consider directories. - if match_style < 1 then - match_style = 2 - else - match_style = 1 - end - end - - -- Should we also consider the path referenced by 'text'? - if match_style >= 1 then - table.insert(paths, text_dir) - end - - -- Search 'paths' for files ending in 'suffices' and look for matches - local suffices = clink.split(clink.get_env("pathext"), ";") - for _, suffix in ipairs(suffices) do - for _, path in ipairs(paths) do - local files = clink.find_files(path.."*"..suffix, false) - for _, file in ipairs(files) do - if clink.is_match(text_name, file) then - clink.add_match(text_dir..file) - end - end - end - end - - -- Lastly we may wish to consider directories too. - if clink.match_count() == 0 or match_style >= 2 then - clink.match_files(text.."*", true, exec_find_dirs) - end - - clink.matches_are_files() - return true -end - --------------------------------------------------------------------------------- -clink.register_match_generator(exec_match_generator, 50) - --- vim: expandtab - --------------------------------------------------------------------------------- --- git.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local git_argument_tree = { - -- Porcelain and ancillary commands from git's man page. - "add", "am", "archive", "bisect", "branch", "bundle", "checkout", - "cherry-pick", "citool", "clean", "clone", "commit", "describe", "diff", - "fetch", "format-patch", "gc", "grep", "gui", "init", "log", "merge", "mv", - "notes", "pull", "push", "rebase", "reset", "revert", "rm", "shortlog", - "show", "stash", "status", "submodule", "tag", "config", "fast-export", - "fast-import", "filter-branch", "lost-found", "mergetool", "pack-refs", - "prune", "reflog", "relink", "remote", "repack", "replace", "repo-config", - "annotate", "blame", "cherry", "count-objects", "difftool", "fsck", - "get-tar-commit-id", "help", "instaweb", "merge-tree", "rerere", - "rev-parse", "show-branch", "verify-tag", "whatchanged" -} - -clink.arg.register_parser("git", git_argument_tree) - --- vim: expandtab - --------------------------------------------------------------------------------- --- go.lua --- - --- --- Copyright (c) 2013 Dobroslaw Zybort --- --- 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. --- - --------------------------------------------------------------------------------- -local function flags(...) - local p = clink.arg.new_parser() - p:set_flags(...) - return p -end - --------------------------------------------------------------------------------- -local go_tool_parser = clink.arg.new_parser() -go_tool_parser:set_flags("-n") -go_tool_parser:set_arguments({ - "8a", "8c", "8g", "8l", "addr2line", "cgo", "dist", "nm", "objdump", - "pack", - "cover" .. flags("-func", "-html", "-mode", "-o", "-var"), - "fix" .. flags("-diff", "-force", "-r"), - "prof" .. flags("-p", "-t", "-d", "-P", "-h", "-f", "-l", "-r", "-s", - "-hs"), - "pprof" .. flags(-- Options: - "--cum", "--base", "--interactive", "--seconds", - "--add_lib", "--lib_prefix", - -- Reporting Granularity: - "--addresses", "--lines", "--functions", "--files", - -- Output type: - "--text", "--callgrind", "--gv", "--web", "--list", - "--disasm", "--symbols", "--dot", "--ps", "--pdf", - "--svg", "--gif", "--raw", - -- Heap-Profile Options: - "--inuse_space", "--inuse_objects", "--alloc_space", - "--alloc_objects", "--show_bytes", "--drop_negative", - -- Contention-profile options: - "--total_delay", "--contentions", "--mean_delay", - -- Call-graph Options: - "--nodecount", "--nodefraction", "--edgefraction", - "--focus", "--ignore", "--scale", "--heapcheck", - -- Miscellaneous: - "--tools", "--test", "--help", "--version"), - "vet" .. flags("-all", "-asmdecl", "-assign", "-atomic", "-buildtags", - "-composites", "-compositewhitelist", "-copylocks", - "-methods", "-nilfunc", "-printf", "-printfuncs", - "-rangeloops", "-shadow", "-shadowstrict", "-structtags", - "-test", "-unreachable", "-v"), - "yacc" .. flags("-l", "-o", "-p", "-v"), -}) - --------------------------------------------------------------------------------- -local go_parser = clink.arg.new_parser() -go_parser:set_arguments({ - "env", - "fix", - "version", - "build" .. flags("-o", "-a", "-n", "-p", "-installsuffix", "-v", "-x", - "-work", "-gcflags", "-ccflags", "-ldflags", - "-gccgoflags", "-tags", "-compiler", "-race"), - "clean" .. flags("-i", "-n", "-r", "-x"), - "fmt" .. flags("-n", "-x"), - "get" .. flags("-d", "-fix", "-t", "-u", - -- Build flags - "-a", "-n", "-p", "-installsuffix", "-v", "-x", - "-work", "-gcflags", "-ccflags", "-ldflags", - "-gccgoflags", "-tags", "-compiler", "-race"), - "install" .. flags(-- All `go build` flags - "-o", "-a", "-n", "-p", "-installsuffix", "-v", "-x", - "-work", "-gcflags", "-ccflags", "-ldflags", - "-gccgoflags", "-tags", "-compiler", "-race"), - "list" .. flags("-e", "-race", "-f", "-json", "-tags"), - "run" .. flags("-exec", - -- Build flags - "-a", "-n", "-p", "-installsuffix", "-v", "-x", - "-work", "-gcflags", "-ccflags", "-ldflags", - "-gccgoflags", "-tags", "-compiler", "-race"), - "test" .. flags(-- Local. - "-c", "-file", "-i", "-cover", "-coverpkg", - -- Build flags - "-a", "-n", "-p", "-x", "-work", "-ccflags", - "-gcflags", "-exec", "-ldflags", "-gccgoflags", - "-tags", "-compiler", "-race", "-installsuffix", - -- Passed to 6.out - "-bench", "-benchmem", "-benchtime", "-covermode", - "-coverprofile", "-cpu", "-cpuprofile", "-memprofile", - "-memprofilerate", "-blockprofile", - "-blockprofilerate", "-outputdir", "-parallel", "-run", - "-short", "-timeout", "-v"), - "tool" .. go_tool_parser, - "vet" .. flags("-n", "-x"), -}) - --------------------------------------------------------------------------------- -local go_help_parser = clink.arg.new_parser() -go_help_parser:set_arguments({ - "help" .. clink.arg.new_parser():set_arguments({ - go_parser:flatten_argument(1) - }) -}) - --------------------------------------------------------------------------------- -local godoc_parser = clink.arg.new_parser() -godoc_parser:set_flags( - "-zip", "-write_index", "-analysis", "-http", "-server", "-html","-src", - "-url", "-q", "-v", "-goroot", "-tabwidth", "-timestamps", "-templates", - "-play", "-ex", "-links", "-index", "-index_files", "-maxresults", - "-index_throttle", "-notes", "-httptest.serve" -) - --------------------------------------------------------------------------------- -local gofmt_parser = clink.arg.new_parser() -gofmt_parser:set_flags( - "-cpuprofile", "-d", "-e", "-l", "-r", "-s", "-w" -) - --------------------------------------------------------------------------------- -clink.arg.register_parser("go", go_parser) -clink.arg.register_parser("go", go_help_parser) -clink.arg.register_parser("godoc", godoc_parser) -clink.arg.register_parser("gofmt", gofmt_parser) - --------------------------------------------------------------------------------- --- hg.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local hg_tree = { - "add", "addremove", "annotate", "archive", "backout", "bisect", "bookmarks", - "branch", "branches", "bundle", "cat", "clone", "commit", "copy", "diff", - "export", "forget", "grep", "heads", "help", "identify", "import", - "incoming", "init", "locate", "log", "manifest", "merge", "outgoing", - "parents", "paths", "pull", "push", "recover", "remove", "rename", "resolve", - "revert", "rollback", "root", "serve", "showconfig", "status", "summary", - "tag", "tags", "tip", "unbundle", "update", "verify", "version", "graft", - "phases" -} - -clink.arg.register_parser("hg", hg_tree) - --- vim: expandtab - --------------------------------------------------------------------------------- --- p4.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local p4_tree = { - "add", "annotate", "attribute", "branch", "branches", "browse", "change", - "changes", "changelist", "changelists", "client", "clients", "copy", - "counter", "counters", "cstat", "delete", "depot", "depots", "describe", - "diff", "diff2", "dirs", "edit", "filelog", "files", "fix", "fixes", - "flush", "fstat", "grep", "group", "groups", "have", "help", "info", - "integrate", "integrated", "interchanges", "istat", "job", "jobs", "label", - "labels", "labelsync", "legal", "list", "lock", "logger", "login", - "logout", "merge", "move", "opened", "passwd", "populate", "print", - "protect", "protects", "reconcile", "rename", "reopen", "resolve", - "resolved", "revert", "review", "reviews", "set", "shelve", "status", - "sizes", "stream", "streams", "submit", "sync", "tag", "tickets", "unlock", - "unshelve", "update", "user", "users", "where", "workspace", "workspaces" -} - -clink.arg.register_parser("p4", p4_tree) - --------------------------------------------------------------------------------- -local p4vc_tree = { - "help", "branchmappings", "branches", "diff", "groups", "branch", "change", - "client", "workspace", "depot", "group", "job", "label", "user", "jobs", - "labels", "pendingchanges", "resolve", "revisiongraph", "revgraph", - "streamgraph", "streams", "submit", "submittedchanges", "timelapse", - "timelapseview", "tlv", "users", "workspaces", "clients", "shutdown" -} - -clink.arg.register_parser("p4vc", p4vc_tree) - --- vim: expandtab - --------------------------------------------------------------------------------- --- powershell.lua --- - --- --- Copyright (c) 2013 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local function powershell_prompt_filter() - local l, r, path = clink.prompt.value:find("([a-zA-Z]:\\.*)> $") - if path ~= nil then - clink.chdir(path) - end -end - --------------------------------------------------------------------------------- -if clink.get_host_process() == "powershell.exe" then - clink.prompt.register_filter(powershell_prompt_filter, -493) -end - --------------------------------------------------------------------------------- --- self.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local null_parser = clink.arg.new_parser() -null_parser:disable_file_matching() - -local inject_parser = clink.arg.new_parser() -inject_parser:set_flags( - "--help", - "--nohostcheck", - "--pid", - "--profile", - "--quiet", - "--scripts" -) - -local autorun_dashdash_parser = clink.arg.new_parser() -autorun_dashdash_parser:set_arguments({ "--" .. inject_parser }) - -local autorun_parser = clink.arg.new_parser() -autorun_parser:set_flags("--allusers", "--help") -autorun_parser:set_arguments( - { - "install" .. autorun_dashdash_parser, - "uninstall" .. null_parser, - "show" .. null_parser, - "set" - } -) - -local set_parser = clink.arg.new_parser() -set_parser:disable_file_matching() -set_parser:set_flags("--help") -set_parser:set_arguments( - { - "ansi_code_support", - "ctrld_exits", - "esc_clears_line", - "exec_match_style", - "history_dupe_mode", - "history_expand_mode", - "history_file_lines", - "history_ignore_space", - "history_io", - "match_colour", - "prompt_colour", - "space_prefix_match_files", - "strip_crlf_on_paste", - "terminate_autoanswer", - "use_altgr_substitute", - } -) - -local self_parser = clink.arg.new_parser() -self_parser:set_arguments( - { - "inject" .. inject_parser, - "autorun" .. autorun_parser, - "set" .. set_parser, - } -) - -clink.arg.register_parser("clink", self_parser) -clink.arg.register_parser("clink_x86", self_parser) -clink.arg.register_parser("clink_x64", self_parser) - --- vim: expandtab - --------------------------------------------------------------------------------- --- set.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local function set_match_generator(word) - -- Skip this generator if first is in the rvalue. - local leading = rl_state.line_buffer:sub(1, rl_state.first - 1) - if leading:find("=") then - return false - end - - -- Enumerate environment variables and check for potential matches. - local matches = {} - for _, name in ipairs(clink.get_env_var_names()) do - if clink.is_match(word, name) then - table.insert(matches, name:lower()) - end - end - - clink.suppress_char_append() - return matches -end - --------------------------------------------------------------------------------- -clink.arg.register_parser("set", set_match_generator) - --- vim: expandtab - --------------------------------------------------------------------------------- --- svn.lua --- - --- --- Copyright (c) 2012 Martin Ridgers --- --- 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. --- - --------------------------------------------------------------------------------- -local svn_tree = { - "add", "blame", "praise", "annotate", "ann", "cat", "changelist", "cl", - "checkout", "co", "cleanup", "commit", "ci", "copy", "cp", "delete", "del", - "remove", "rm", "diff", "di", "export", "help", "h", "import", "info", - "list", "ls", "lock", "log", "merge", "mergeinfo", "mkdir", "move", "mv", - "rename", "ren", "propdel", "pdel", "pd", "propedit", "pedit", "pe", - "propget", "pget", "pg", "proplist", "plist", "pl", "propset", "pset", "ps", - "resolve", "resolved", "revert", "status", "stat", "st", "switch", "sw", - "unlock", "update", "up" -} - -clink.arg.register_parser("svn", svn_tree) - --- vim: expandtab +-- The old clink.lua file is no longer used, and this blank file ensures if a +-- new clink version is copied over an old clink version, it won't accidentally +-- use an obsolete leftover clink.lua file. diff --git a/extras/clink/clink_dll_x64.dll b/extras/clink/clink_dll_x64.dll index 452e505c4be1e465a2b3c4a530e18b0edcdf6166..1bc038044f227a769d0505fffd37b6fdbfe68d21 100644 Binary files a/extras/clink/clink_dll_x64.dll and b/extras/clink/clink_dll_x64.dll differ diff --git a/extras/clink/clink_dll_x86.dll b/extras/clink/clink_dll_x86.dll index 1d1298ef86cabc4d6af441a93dc744ed0cd6b177..e45a74ff2f0f7bbcaecb069d2a8459d1921370c1 100644 Binary files a/extras/clink/clink_dll_x86.dll and b/extras/clink/clink_dll_x86.dll differ diff --git a/extras/clink/clink_x64.exe b/extras/clink/clink_x64.exe index 1d58e943430cd08908d136bcfc84a44d03fa1ce2..35f132ef30d5606ea4ead482eb6842fc25d28a02 100644 Binary files a/extras/clink/clink_x64.exe and b/extras/clink/clink_x64.exe differ diff --git a/extras/clink/clink_x86.exe b/extras/clink/clink_x86.exe index 549736011d7b8d82a636965b5a6ed19b94fbd05b..4a5c247953e0b68834d7ec6d39931f8d060c6bef 100644 Binary files a/extras/clink/clink_x86.exe and b/extras/clink/clink_x86.exe differ diff --git a/extras/clink/profile/.history b/extras/clink/profile/.history deleted file mode 100644 index 164bd9dca8bfde3ddbdef595a15ea20494cbf358..0000000000000000000000000000000000000000 --- a/extras/clink/profile/.history +++ /dev/null @@ -1 +0,0 @@ -Ls diff --git a/extras/clink/profile/settings b/extras/clink/profile/settings deleted file mode 100644 index 12681f68af4ea457315995e560ccf1fec32666b4..0000000000000000000000000000000000000000 --- a/extras/clink/profile/settings +++ /dev/null @@ -1,116 +0,0 @@ -# name: Pressing Ctrl-D exits session -# type: bool -# Ctrl-D exits cmd.exe when it is pressed on an empty line. -ctrld_exits = 1 - -# name: Toggle if pressing Esc clears line -# type: bool -# Clink clears the current line when Esc is pressed (unless Readline's Vi mode -# is enabled). -esc_clears_line = 1 - -# name: Match display colour -# type: int -# Colour to use when displaying matches. A value less than 0 will be the -# opposite brightness of the default colour. -match_colour = -1 - -# name: Executable match style -# type: enum -# 0 = PATH only -# 1 = PATH and CWD -# 2 = PATH, CWD, and directories -# Changes how Clink will match executables when there is no path separator on -# the line. 0 = PATH only, 1 = PATH and CWD, 2 = PATH, CWD, and directories. In -# all cases both executables and directories are matched when there is a path -# separator present. A value of -1 will disable executable matching completely. -exec_match_style = 2 - -# name: Whitespace prefix matches files -# type: bool -# If the line begins with whitespace then Clink bypasses executable matching and -# will match all files and directories instead. -space_prefix_match_files = 1 - -# name: Colour of the prompt -# type: int -# Surrounds the prompt in ANSI escape codes to set the prompt's colour. Disabled -# when the value is less than 0. -prompt_colour = -1 - -# name: Auto-answer terminate prompt -# type: enum -# 0 = Disabled -# 1 = Answer 'Y' -# 2 = Answer 'N' -# Automatically answers cmd.exe's 'Terminate batch job (Y/N)?' prompts. 0 = -# disabled, 1 = answer 'Y', 2 = answer 'N'. -terminate_autoanswer = 0 - -# name: Lines of history saved to disk -# type: int -# When set to a positive integer this is the number of lines of history that -# will persist when Clink saves the command history to disk. Use 0 for infinite -# lines and <0 to disable history persistence. -history_file_lines = 10000 - -# name: Skip adding lines prefixed with whitespace -# type: bool -# Ignore lines that begin with whitespace when adding lines in to the history. -history_ignore_space = 0 - -# name: Controls how duplicate entries are handled -# type: enum -# 0 = Always add -# 1 = Ignore -# 2 = Erase previous -# If a line is a duplicate of an existing history entry Clink will erase the -# duplicate when this is set 2. A value of 1 will not add duplicates to the -# history and a value of 0 will always add lines. Note that history is not -# deduplicated when reading/writing to disk. -history_dupe_mode = 2 - -# name: Read/write history file each line edited -# type: bool -# When non-zero the history will be read from disk before editing a new line and -# written to disk afterwards. -history_io = 0 - -# name: Sets how command history expansion is applied -# type: enum -# 0 = Off -# 1 = On -# 2 = Not in single quotes -# 3 = Not in double quote -# 4 = Not in any quotes -# The '!' character in an entered line can be interpreted to introduce words -# from the history. This can be enabled and disable by setting this value to 1 -# or 0. Values or 2, 3 or 4 will skip any ! character quoted in single, double, -# or both quotes respectively. -history_expand_mode = 4 - -# name: Support Windows' Ctrl-Alt substitute for AltGr -# type: bool -# Windows provides Ctrl-Alt as a substitute for AltGr, historically to support -# keyboards with no AltGr key. This may collide with some of Readline's -# bindings. -use_altgr_substitute = 1 - -# name: Strips CR and LF chars on paste -# type: enum -# 0 = Paste unchanged -# 1 = Strip -# 2 = As space -# Setting this to a value >0 will make Clink strip CR and LF characters from -# text pasted into the current line. Set this to 1 to strip all newline -# characters and 2 to replace them with a space. -strip_crlf_on_paste = 2 - -# name: Enables basic ANSI escape code support -# type: bool -# When printing the prompt, Clink has basic built-in support for SGR ANSI escape -# codes to control the text colours. This is automatically disabled if a third -# party tool is detected that also provides this facility. It can also be -# disabled by setting this to 0. -ansi_code_support = 1 - diff --git a/terminus-local/src/shells/windowsStock.ts b/terminus-local/src/shells/windowsStock.ts index 475e2b33280369d23d55123cec43f99a2f4ff42b..c12e636bbcbd325ee1a3970ba5e1d5f42d0be94b 100644 --- a/terminus-local/src/shells/windowsStock.ts +++ b/terminus-local/src/shells/windowsStock.ts @@ -18,23 +18,34 @@ export class WindowsStockShellsProvider extends ShellProvider { if (this.hostApp.platform !== Platform.Windows) { return [] } + + let clinkPath = path.join( + path.dirname(this.electron.app.getPath('exe')), + 'resources', + 'extras', + 'clink', + `clink_${process.arch}.exe`, + ) + + if (process.env.TERMINUS_DEV) { + clinkPath = path.join( + path.dirname(this.electron.app.getPath('exe')), + '..', '..', '..', + 'extras', + 'clink', + `clink_${process.arch}.exe`, + ) + } return [ { id: 'clink', name: 'CMD (clink)', command: 'cmd.exe', - args: [ - '/k', - path.join( - path.dirname(this.electron.app.getPath('exe')), - 'resources', - 'extras', - 'clink', - `clink_${process.arch}.exe`, - ), - 'inject', - ], - env: {}, + args: ['/k', clinkPath, 'inject'], + env: { + // Tell clink not to emulate ANSI handling + WT_SESSION: '0', + }, icon: require('../icons/clink.svg'), }, {