Compare commits

..

1 Commits

Author SHA1 Message Date
sammyette 53634bac0c
Merge eded38c7b5 into 9d5f5abef4 2023-12-25 19:01:02 -05:00
79 changed files with 1202 additions and 3647 deletions

View File

@ -36,7 +36,7 @@ jobs:
fetch-depth: 0
- name: Download Task
run: 'sh -c "$(curl --location https://taskfile.dev/install.sh)" -- -d'
- uses: wangyoucao577/go-release-action@v1
- uses: wangyoucao577/go-release-action@v1.25
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
goos: ${{ matrix.goos }}

View File

@ -1,31 +1,17 @@
# 🎀 Changelog
## Unreleased
## Added
- Page Up/Down keybinds for Greenhouse will now scroll up and down the size of the region (a page)
## Changed
- Remove usage of `hilbish.goro` in Greenhouse.
## [2.2.1] - 2023-12-26
## Fixed
- Removed a left over debug print
- Recover panic in `hilbish.goro`
## [2.2.0] - 2023-12-25
### Added
- [Native Modules](https://rosettea.github.io/Hilbish/docs/api/hilbish/hilbish.module/)
- Made a few additions to the sink type:
- `read()` method for retrieving input (so now the `in` sink of commanders is useful)
- `flush()` and `autoFlush()` related to flushing outputs
- `pipe` property to check if a sink with input is a pipe (like stdin)
- Add fuzzy search to history search (enable via `hilbish.opts.fuzzy = true`)
- Show indexes on cdr list and use ~ for home directory.
- Show indexes on cdr list
- Fix doc command not displaying correct subdocs when using shorthand api doc access (`doc api hilbish.jobs` as an example)
- `hilbish.messages` interface (details in [#219])
- `hilbish.notification` signal when a message/notification is sent
- `notifyJobFinish` opt to send a notification when background jobs are
- `hilbish.goVersion` for the version of Go used to compile Hilbish.
completed.
- Allow numbered arg substitutions in aliases.
- Example: `hilbish.alias('hello', 'echo %1 says hello')` allows the user to run `hello hilbish`
@ -34,23 +20,8 @@ completed.
- Greenhouse is a pager library and program. Basic usage is `greenhouse <file>`
- Using this also brings enhancements to the `doc` command like easy
navigation of neighboring doc files.
Ctrl-N can be used for the table of contents, which views adjacent documentation.
### Changed
- Documentation for EVERYTHING has been improved, with more
information added, code example, parameter details, etc.
You can see the improvements!
- Documentation has gotten an uplift in the `doc` command.
This includes:
- Proper highlighting of code
- Paging (via Greenhouse)
- Highlighting more markdown things
### Fixed
- Fix panic when runner doesn't return a table
- Fix edge case of crash on empty alias resolve
- File completion on Windows
- Job management commands work now
- Fix infinite loop when navigating history without any history. [#252](https://github.com/Rosettea/Hilbish/issues/252)
- Return the prefix when calling `hilbish.completions.call`. [#219](https://github.com/Rosettea/Hilbish/issues/219)
- Replaced `sed` in-place editing with `grep` and `mv` for compatibility with BSD utils
@ -700,11 +671,6 @@ This input for example will prompt for more input to complete:
First "stable" release of Hilbish.
[2.2.2]: https://github.com/Rosettea/Hilbish/compare/v2.2.1...v2.2.2
[2.2.1]: https://github.com/Rosettea/Hilbish/compare/v2.2.0...v2.2.1
[2.2.0]: https://github.com/Rosettea/Hilbish/compare/v2.1.0...v2.2.0
[2.1.2]: https://github.com/Rosettea/Hilbish/compare/v2.1.1...v2.1.2
[2.1.1]: https://github.com/Rosettea/Hilbish/compare/v2.1.0...v2.1.1
[2.1.0]: https://github.com/Rosettea/Hilbish/compare/v2.0.1...v2.1.0
[2.0.1]: https://github.com/Rosettea/Hilbish/compare/v2.0.0...v2.0.1
[2.0.0]: https://github.com/Rosettea/Hilbish/compare/v1.2.0...v2.0.0

View File

@ -111,23 +111,15 @@ func (a *aliasModule) Loader(rtm *rt.Runtime) *rt.Table {
// #interface aliases
// add(alias, cmd)
// This is an alias (ha) for the [hilbish.alias](../#alias) function.
// This is an alias (ha) for the `hilbish.alias` function.
// --- @param alias string
// --- @param cmd string
func _hlalias() {}
// #interface aliases
// list() -> table[string, string]
// list() -> table<string, string>
// Get a table of all aliases, with string keys as the alias and the value as the command.
// #returns table[string, string]
/*
#example
hilbish.aliases.add('hi', 'echo hi')
local aliases = hilbish.aliases.list()
-- -> {hi = 'echo hi'}
#example
*/
// --- @returns table<string, string>
func (a *aliasModule) luaList(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
aliasesList := rt.NewTable()
for k, v := range a.All() {
@ -140,7 +132,7 @@ func (a *aliasModule) luaList(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface aliases
// delete(name)
// Removes an alias.
// #param name string
// --- @param name string
func (a *aliasModule) luaDelete(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -155,10 +147,10 @@ func (a *aliasModule) luaDelete(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// #interface aliases
// resolve(alias) -> string?
// Resolves an alias to its original command. Will thrown an error if the alias doesn't exist.
// #param alias string
// #returns string
// resolve(alias) -> command (string)
// Tries to resolve an alias to its command.
// --- @param alias string
// --- @returns string
func (a *aliasModule) luaResolve(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err

219
api.go
View File

@ -9,7 +9,7 @@
// #field interactive Is Hilbish in an interactive shell?
// #field login Is Hilbish the login shell?
// #field vimMode Current Vim input mode of Hilbish (will be nil if not in Vim input mode)
// #field exitCode Exit code of the last executed command
// #field exitCode xit code of the last executed command
package main
import (
@ -192,10 +192,12 @@ func unsetVimMode() {
}
// run(cmd, returnOut) -> exitCode (number), stdout (string), stderr (string)
// Runs `cmd` in Hilbish's shell script interpreter.
// #param cmd string
// #param returnOut boolean If this is true, the function will return the standard output and error of the command instead of printing it.
// #returns number, string, string
// Runs `cmd` in Hilbish's sh interpreter.
// If returnOut is true, the outputs of `cmd` will be returned as the 2nd and
// 3rd values instead of being outputted to the terminal.
// --- @param cmd string
// --- @param returnOut boolean
// --- @returns number, string, string
func hlrun(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -237,8 +239,8 @@ func hlrun(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// cwd() -> string
// Returns the current directory of the shell.
// #returns string
// Returns the current directory of the shell
// --- @returns string
func hlcwd(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
cwd, _ := os.Getwd()
@ -249,9 +251,9 @@ func hlcwd(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// read(prompt) -> input (string)
// Read input from the user, using Hilbish's line editor/input reader.
// This is a separate instance from the one Hilbish actually uses.
// Returns `input`, will be nil if Ctrl-D is pressed, or an error occurs.
// #param prompt? string Text to print before input, can be empty.
// #returns string|nil
// Returns `input`, will be nil if ctrl + d is pressed, or an error occurs (which shouldn't happen)
// --- @param prompt? string
// --- @returns string|nil
func hlread(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
luaprompt := c.Arg(0)
if typ := luaprompt.Type(); typ != rt.StringType && typ != rt.NilType {
@ -279,21 +281,14 @@ func hlread(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
/*
prompt(str, typ)
Changes the shell prompt to the provided string.
Changes the shell prompt to `str`
There are a few verbs that can be used in the prompt text.
These will be formatted and replaced with the appropriate values.
`%d` - Current working directory
`%u` - Name of current user
`%h` - Hostname of device
#param str string
#param typ? string Type of prompt, being left or right. Left by default.
#example
-- the default hilbish prompt without color
hilbish.prompt '%u %d '
-- or something of old:
hilbish.prompt '%u@%h :%d $'
-- prompt: user@hostname: ~/directory $
#example
--- @param str string
--- @param typ? string Type of prompt, being left or right. Left by default.
*/
func hlprompt(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
err := c.Check1Arg()
@ -327,28 +322,8 @@ func hlprompt(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// multiprompt(str)
// Changes the text prompt when Hilbish asks for more input.
// This will show up when text is incomplete, like a missing quote
// #param str string
/*
#example
--[[
imagine this is your text input:
user ~ echo "hey
but there's a missing quote! hilbish will now prompt you so the terminal
will look like:
user ~ echo "hey
--> ...!"
so then you get
user ~ echo "hey
--> ...!"
hey ...!
]]--
hilbish.multiprompt '-->'
#example
*/
// Changes the continued line prompt to `str`
// --- @param str string
func hlmultiprompt(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -363,19 +338,9 @@ func hlmultiprompt(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// alias(cmd, orig)
// Sets an alias, with a name of `cmd` to another command.
// #param cmd string Name of the alias
// #param orig string Command that will be aliased
/*
#example
-- With this, "ga file" will turn into "git add file"
hilbish.alias('ga', 'git add')
-- Numbered substitutions are supported here!
hilbish.alias('dircount', 'ls %1 | wc -l')
-- "dircount ~" would count how many files are in ~ (home directory).
#example
*/
// Sets an alias of `cmd` to `orig`
// --- @param cmd string
// --- @param orig string
func hlalias(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(2); err != nil {
return nil, err
@ -395,20 +360,8 @@ func hlalias(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// appendPath(dir)
// Appends the provided dir to the command path (`$PATH`)
// #param dir string|table Directory (or directories) to append to path
/*
#example
hilbish.appendPath '~/go/bin'
-- Will add ~/go/bin to the command path.
-- Or do multiple:
hilbish.appendPath {
'~/go/bin',
'~/.local/bin'
}
#example
*/
// Appends `dir` to $PATH
// --- @param dir string|table
func hlappendPath(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -442,9 +395,8 @@ func appendPath(dir string) {
}
// exec(cmd)
// Replaces the currently running Hilbish instance with the supplied command.
// This can be used to do an in-place restart.
// #param cmd string
// Replaces running hilbish with `cmd`
// --- @param cmd string
func hlexec(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -478,11 +430,8 @@ func hlexec(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// goro(fn)
// Puts `fn` in a Goroutine.
// This can be used to run any function in another thread at the same time as other Lua code.
// **NOTE: THIS FUNCTION MAY CRASH HILBISH IF OUTSIDE VARIABLES ARE ACCESSED.**
// **This is a limitation of the Lua runtime.**
// #param fn function
// Puts `fn` in a goroutine
// --- @param fn function
func hlgoro(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -494,12 +443,6 @@ func hlgoro(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// call fn
go func() {
defer func() {
if r := recover(); r != nil {
// do something here?
}
}()
_, err := rt.Call1(l.MainThread(), rt.FunctionValue(fn), c.Etc()...)
if err != nil {
fmt.Fprintln(os.Stderr, "Error in goro function:\n\n", err)
@ -510,11 +453,11 @@ func hlgoro(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// timeout(cb, time) -> @Timer
// Executed the `cb` function after a period of `time`.
// This creates a Timer that starts ticking immediately.
// #param cb function
// #param time number Time to run in milliseconds.
// #returns Timer
// Runs the `cb` function after `time` in milliseconds.
// This creates a timer that starts immediately.
// --- @param cb function
// --- @param time number
// --- @returns Timer
func hltimeout(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(2); err != nil {
return nil, err
@ -536,11 +479,11 @@ func hltimeout(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// interval(cb, time) -> @Timer
// Runs the `cb` function every specified amount of `time`.
// This creates a timer that ticking immediately.
// #param cb function
// #param time number Time in milliseconds.
// #return Timer
// Runs the `cb` function every `time` milliseconds.
// This creates a timer that starts immediately.
// --- @param cb function
// --- @param time number
// --- @return Timer
func hlinterval(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(2); err != nil {
return nil, err
@ -562,40 +505,13 @@ func hlinterval(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// complete(scope, cb)
// Registers a completion handler for the specified scope.
// A `scope` is expected to be `command.<cmd>`,
// Registers a completion handler for `scope`.
// A `scope` is currently only expected to be `command.<cmd>`,
// replacing <cmd> with the name of the command (for example `command.git`).
// The documentation for completions, under Features/Completions or `doc completions`
// provides more details.
// #param scope string
// #param cb function
/*
#example
-- This is a very simple example. Read the full doc for completions for details.
hilbish.complete('command.sudo', function(query, ctx, fields)
if #fields == 0 then
-- complete for commands
local comps, pfx = hilbish.completion.bins(query, ctx, fields)
local compGroup = {
items = comps, -- our list of items to complete
type = 'grid' -- what our completions will look like.
}
return {compGroup}, pfx
end
-- otherwise just be boring and return files
local comps, pfx = hilbish.completion.files(query, ctx, fields)
local compGroup = {
items = comps,
type = 'grid'
}
return {compGroup}, pfx
end)
#example
*/
// `cb` must be a function that returns a table of "completion groups."
// Check `doc completions` for more information.
// --- @param scope string
// --- @param cb function
func hlcomplete(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
scope, cb, err := util.HandleStrCallback(t, c)
if err != nil {
@ -607,8 +523,8 @@ func hlcomplete(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// prependPath(dir)
// Prepends `dir` to $PATH.
// #param dir string
// Prepends `dir` to $PATH
// --- @param dir string
func hlprependPath(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -631,8 +547,8 @@ func hlprependPath(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// which(name) -> string
// Checks if `name` is a valid command.
// Will return the path of the binary, or a basename if it's a commander.
// #param name string
// #returns string
// --- @param name string
// --- @returns string
func hlwhich(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -662,10 +578,8 @@ func hlwhich(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// inputMode(mode)
// Sets the input mode for Hilbish's line reader.
// `emacs` is the default. Setting it to `vim` changes behavior of input to be
// Vim-like with modes and Vim keybinds.
// #param mode string Can be set to either `emacs` or `vim`
// Sets the input mode for Hilbish's line reader. Accepts either emacs or vim
// --- @param mode string
func hlinputMode(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -690,14 +604,12 @@ func hlinputMode(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// runnerMode(mode)
// Sets the execution/runner mode for interactive Hilbish.
// This determines whether Hilbish wll try to run input as Lua
// and/or sh or only do one of either.
// Sets the execution/runner mode for interactive Hilbish. This determines whether
// Hilbish wll try to run input as Lua and/or sh or only do one of either.
// Accepted values for mode are hybrid (the default), hybridRev (sh first then Lua),
// sh, and lua. It also accepts a function, to which if it is passed one
// will call it to execute user input instead.
// Read [about runner mode](../features/runner-mode) for more information.
// #param mode string|function
// --- @param mode string|function
func hlrunnerMode(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -723,33 +635,26 @@ func hlrunnerMode(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// line and cursor position. It is expected to return a string which is used
// as the text for the hint. This is by default a shim. To set hints,
// override this function with your custom handler.
// #param line string
// #param pos number Position of cursor in line. Usually equals string.len(line)
/*
#example
-- this will display "hi" after the cursor in a dimmed color.
function hilbish.hinter(line, pos)
return 'hi'
end
#example
*/
// --- @param line string
// --- @param pos number
func hlhinter(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.Next(), nil
}
// highlighter(line)
// Line highlighter handler.
// This is mainly for syntax highlighting, but in reality could set the input
// of the prompt to *display* anything. The callback is passed the current line
// and is expected to return a line that will be used as the input display.
// Line highlighter handler. This is mainly for syntax highlighting, but in
// reality could set the input of the prompt to *display* anything. The
// callback is passed the current line and is expected to return a line that
// will be used as the input display.
// Note that to set a highlighter, one has to override this function.
// #example
// --This code will highlight all double quoted strings in green.
// Example:
// ```
// function hilbish.highlighter(line)
// return line:gsub('"%w+"', function(c) return lunacolors.green(c) end)
// end
// #example
// #param line string
// ```
// This code will highlight all double quoted strings in green.
// --- @param line string
func hlhighlighter(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.Next(), nil
}

View File

@ -11,8 +11,6 @@ import (
"strings"
"os"
"sync"
md "github.com/atsushinee/go-markdown-generator/doc"
)
var header = `---
@ -45,12 +43,6 @@ type module struct {
HasTypes bool
}
type param struct{
Name string
Type string
Doc []string
}
type docPiece struct {
Doc []string
FuncSig string
@ -63,14 +55,11 @@ type docPiece struct {
IsType bool
Fields []docPiece
Properties []docPiece
Params []param
Tags map[string][]tag
}
type tag struct {
id string
fields []string
startIdx int
}
var docs = make(map[string]module)
@ -91,7 +80,7 @@ func getTagsAndDocs(docs string) (map[string][]tag, []string) {
parts := []string{}
tags := make(map[string][]tag)
for idx, part := range pts {
for _, part := range pts {
if strings.HasPrefix(part, "#") {
tagParts := strings.Split(strings.TrimPrefix(part, "#"), " ")
if tags[tagParts[0]] == nil {
@ -100,21 +89,12 @@ func getTagsAndDocs(docs string) (map[string][]tag, []string) {
id = tagParts[1]
}
tags[tagParts[0]] = []tag{
{id: id, startIdx: idx},
{id: id},
}
if len(tagParts) >= 2 {
tags[tagParts[0]][0].fields = tagParts[2:]
}
} else {
if tagParts[0] == "example" {
exampleIdx := tags["example"][0].startIdx
exampleCode := pts[exampleIdx+1:idx]
tags["example"][0].fields = exampleCode
parts = strings.Split(strings.Replace(strings.Join(parts, "\n"), strings.TrimPrefix(strings.Join(exampleCode, "\n"), "#example\n"), "", -1), "\n")
continue
}
fleds := []string{}
if len(tagParts) >= 2 {
fleds = tagParts[2:]
@ -199,7 +179,6 @@ func setupDocType(mod string, typ *doc.Type) *docPiece {
ParentModule: parentMod,
Fields: fields,
Properties: properties,
Tags: tags,
}
typeTable[strings.ToLower(typeName)] = []string{parentMod, interfaces}
@ -236,17 +215,6 @@ start:
fields := docPieceTag("field", tags)
properties := docPieceTag("property", tags)
var params []param
if paramsRaw := tags["param"]; paramsRaw != nil {
params = make([]param, len(paramsRaw))
for i, p := range paramsRaw {
params[i] = param{
Name: p.id,
Type: p.fields[0],
Doc: p.fields[1:],
}
}
}
for _, d := range doc {
if strings.HasPrefix(d, "---") {
@ -284,8 +252,6 @@ start:
ParentModule: parentMod,
Fields: fields,
Properties: properties,
Params: params,
Tags: tags,
}
if strings.HasSuffix(dps.GoFuncName, strings.ToLower("loader")) {
dps.Doc = parts
@ -446,14 +412,13 @@ func main() {
defer wg.Done()
modOrIface := "Module"
if modu.ParentModule != "" {
modOrIface = "Module"
modOrIface = "Interface"
}
lastHeader := ""
f, _ := os.Create(docPath)
f.WriteString(fmt.Sprintf(header, modOrIface, modname, modu.ShortDescription))
typeTag, _ := regexp.Compile(`\B@\w+`)
modDescription := typeTag.ReplaceAllStringFunc(strings.Replace(strings.Replace(modu.Description, "<", `\<`, -1), "{{\\<", "{{<", -1), func(typ string) string {
modDescription := typeTag.ReplaceAllStringFunc(strings.Replace(modu.Description, "<", `\<`, -1), func(typ string) string {
typName := typ[1:]
typLookup := typeTable[strings.ToLower(typName)]
ifaces := typLookup[0] + "." + typLookup[1] + "/"
@ -464,77 +429,32 @@ func main() {
return fmt.Sprintf(`<a href="%s" style="text-decoration: none;">%s</a>`, linkedTyp, typName)
})
f.WriteString(fmt.Sprintf("## Introduction\n%s\n\n", modDescription))
if len(modu.Docs) != 0 {
funcCount := 0
for _, dps := range modu.Docs {
if dps.IsMember {
continue
}
funcCount++
}
f.WriteString("## Functions\n")
lastHeader = "functions"
mdTable := md.NewTable(funcCount, 2)
mdTable.SetTitle(0, "")
mdTable.SetTitle(1, "")
diff := 0
for i, dps := range modu.Docs {
if dps.IsMember {
diff++
continue
}
mdTable.SetContent(i - diff, 0, fmt.Sprintf(`<a href="#%s">%s</a>`, dps.FuncName, dps.FuncSig))
mdTable.SetContent(i - diff, 1, dps.Doc[0])
}
f.WriteString(mdTable.String())
if len(modu.Fields) != 0 {
f.WriteString("## Interface fields\n")
for _, dps := range modu.Fields {
f.WriteString(fmt.Sprintf("- `%s`: ", dps.FuncName))
f.WriteString(strings.Join(dps.Doc, " "))
f.WriteString("\n")
}
if len(modu.Fields) != 0 {
f.WriteString("## Static module fields\n")
mdTable := md.NewTable(len(modu.Fields), 2)
mdTable.SetTitle(0, "")
mdTable.SetTitle(1, "")
for i, dps := range modu.Fields {
mdTable.SetContent(i, 0, dps.FuncName)
mdTable.SetContent(i, 1, strings.Join(dps.Doc, " "))
}
f.WriteString(mdTable.String())
f.WriteString("\n")
}
if len(modu.Properties) != 0 {
f.WriteString("## Object properties\n")
mdTable := md.NewTable(len(modu.Fields), 2)
mdTable.SetTitle(0, "")
mdTable.SetTitle(1, "")
for i, dps := range modu.Properties {
mdTable.SetContent(i, 0, dps.FuncName)
mdTable.SetContent(i, 1, strings.Join(dps.Doc, " "))
for _, dps := range modu.Properties {
f.WriteString(fmt.Sprintf("- `%s`: ", dps.FuncName))
f.WriteString(strings.Join(dps.Doc, " "))
f.WriteString("\n")
}
f.WriteString(mdTable.String())
f.WriteString("\n")
}
if len(modu.Docs) != 0 {
if lastHeader != "functions" {
f.WriteString("## Functions\n")
}
for _, dps := range modu.Docs {
if dps.IsMember {
continue
}
f.WriteString(fmt.Sprintf("<hr>\n<div id='%s'>", dps.FuncName))
htmlSig := typeTag.ReplaceAllStringFunc(strings.Replace(modname + "." + dps.FuncSig, "<", `\<`, -1), func(typ string) string {
htmlSig := typeTag.ReplaceAllStringFunc(strings.Replace(dps.FuncSig, "<", `\<`, -1), func(typ string) string {
typName := typ[1:]
typLookup := typeTable[strings.ToLower(typName)]
ifaces := typLookup[0] + "." + typLookup[1] + "/"
@ -542,55 +462,21 @@ func main() {
ifaces = ""
}
linkedTyp := fmt.Sprintf("/Hilbish/docs/api/%s/%s#%s", typLookup[0], ifaces, strings.ToLower(typName))
return fmt.Sprintf(`<a href="%s" style="text-decoration: none;" id="lol">%s</a>`, linkedTyp, typName)
return fmt.Sprintf(`<a href="%s" style="text-decoration: none;">%s</a>`, linkedTyp, typName)
})
f.WriteString(fmt.Sprintf(`
<h4 class='heading'>
%s
<a href="#%s" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
`, htmlSig, dps.FuncName))
f.WriteString(fmt.Sprintf("### %s\n", htmlSig))
for _, doc := range dps.Doc {
if !strings.HasPrefix(doc, "---") && doc != "" {
if !strings.HasPrefix(doc, "---") {
f.WriteString(doc + "\n")
}
}
f.WriteString("\n#### Parameters\n")
if len(dps.Params) == 0 {
f.WriteString("This function has no parameters. \n")
}
for _, p := range dps.Params {
isVariadic := false
typ := p.Type
if strings.HasPrefix(p.Type, "...") {
isVariadic = true
typ = p.Type[3:]
}
f.WriteString(fmt.Sprintf("`%s` **`%s`**", typ, p.Name))
if isVariadic {
f.WriteString(" (This type is variadic. You can pass an infinite amount of parameters with this type.)")
}
f.WriteString("\n")
f.WriteString(strings.Join(p.Doc, " "))
f.WriteString("\n\n")
}
if codeExample := dps.Tags["example"]; codeExample != nil {
f.WriteString("#### Example\n")
f.WriteString(fmt.Sprintf("```lua\n%s\n```\n", strings.Join(codeExample[0].fields, "\n")))
}
f.WriteString("</div>")
f.WriteString("\n\n")
}
}
if len(modu.Types) != 0 {
f.WriteString("## Types\n")
for _, dps := range modu.Types {
f.WriteString("<hr>\n\n")
f.WriteString(fmt.Sprintf("## %s\n", dps.FuncName))
for _, doc := range dps.Doc {
if !strings.HasPrefix(doc, "---") {
@ -598,19 +484,13 @@ func main() {
}
}
if len(dps.Properties) != 0 {
f.WriteString("## Object properties\n")
mdTable := md.NewTable(len(dps.Properties), 2)
mdTable.SetTitle(0, "")
mdTable.SetTitle(1, "")
for i, d := range dps.Properties {
mdTable.SetContent(i, 0, d.FuncName)
mdTable.SetContent(i, 1, strings.Join(d.Doc, " "))
}
f.WriteString(mdTable.String())
f.WriteString("### Properties\n")
for _, dps := range dps.Properties {
f.WriteString(fmt.Sprintf("- `%s`: ", dps.FuncName))
f.WriteString(strings.Join(dps.Doc, " "))
f.WriteString("\n")
}
}
f.WriteString("\n")
f.WriteString("### Methods\n")
for _, dps := range modu.Docs {

View File

@ -1,146 +0,0 @@
local fs = require 'fs'
local emmyPattern = '^%-%-%- (.+)'
local modpattern = '^%-+ @module (%w+)'
local pieces = {}
local files = fs.readdir 'nature'
for _, fname in ipairs(files) do
local isScript = fname:match'%.lua$'
if not isScript then goto continue end
local f = io.open(string.format('nature/%s', fname))
local header = f:read '*l'
local mod = header:match(modpattern)
if not mod then goto continue end
print(fname, mod)
pieces[mod] = {}
local docPiece = {}
local lines = {}
local lineno = 0
for line in f:lines() do
lineno = lineno + 1
lines[lineno] = line
if line == header then goto continue2 end
if not line:match(emmyPattern) then
if line:match '^function' then
local pattern = (string.format('^function %s%%.', mod) .. '(%w+)')
local funcName = line:match(pattern)
if not funcName then goto continue2 end
local dps = {
description = {},
params = {}
}
local offset = 1
while true do
local prev = lines[lineno - offset]
local docline = prev:match '^%-+ (.+)'
if docline then
local emmy = docline:match '@(%w+)'
local cut = 0
if emmy then cut = emmy:len() + 3 end
local emmythings = string.split(docline:sub(cut), ' ')
if emmy then
if emmy == 'param' then
table.insert(dps.params, 1, {
name = emmythings[1],
type = emmythings[2]
})
end
else
table.insert(dps.description, 1, docline)
end
offset = offset + 1
else
break
end
end
pieces[mod][funcName] = dps
end
docPiece = {}
goto continue2
end
table.insert(docPiece, line)
::continue2::
end
::continue::
end
local header = [[---
title: %s %s
description: %s
layout: doc
menu:
docs:
parent: "Nature"
---
]]
for iface, dps in pairs(pieces) do
local mod = iface:match '(%w+)%.' or 'nature'
local path = string.format('docs/%s/%s.md', mod, iface)
fs.mkdir(fs.dir(path), true)
local f <close> = io.open(path, 'w')
f:write(string.format(header, 'Module', iface, 'No description.'))
print(f)
print(mod, path)
for func, docs in pairs(dps) do
f:write(string.format('<hr>\n<div id=\'%s\'>', func))
local sig = string.format('%s.%s(', iface, func)
for idx, param in ipairs(docs.params) do
sig = sig .. ((param.name:gsub('%?$', '')))
if idx ~= #docs.params then sig = sig .. ', ' end
end
sig = sig .. ')'
f:write(string.format([[
<h4 class='heading'>
%s
<a href="#%s" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
]], sig, func))
f:write(table.concat(docs.description, '\n') .. '\n')
f:write '#### Parameters\n'
if #docs.params == 0 then
f:write 'This function has no parameters. \n'
end
for _, param in ipairs(docs.params) do
f:write(string.format('`%s` **`%s`**\n', param.name:gsub('%?$', ''), param.type))
end
--[[
local params = table.filter(docs, function(t)
return t:match '^%-%-%- @param'
end)
for i, str in ipairs(params) do
if i ~= 1 then
f:write ', '
end
f:write(str:match '^%-%-%- @param ([%w]+) ')
end
f:write(')\n')
for _, str in ipairs(docs) do
if not str:match '^%-%-%- @' then
f:write(str:match '^%-%-%- (.+)' .. '\n')
end
end
]]--
f:write('</div>')
f:write('\n\n')
end
end

View File

@ -193,10 +193,10 @@ func escapeFilename(fname string) string {
// The completions interface deals with tab completions.
func completionLoader(rtm *rt.Runtime) *rt.Table {
exports := map[string]util.LuaExport{
"bins": {hcmpBins, 3, false},
"call": {hcmpCall, 4, false},
"files": {hcmpFiles, 3, false},
"handler": {hcmpHandler, 2, false},
"files": {luaFileComplete, 3, false},
"bins": {luaBinaryComplete, 3, false},
"call": {callLuaCompleter, 4, false},
"handler": {completionHandler, 2, false},
}
mod := rt.NewTable()
@ -206,57 +206,26 @@ func completionLoader(rtm *rt.Runtime) *rt.Table {
}
// #interface completion
// bins(query, ctx, fields) -> entries (table), prefix (string)
// Return binaries/executables based on the provided parameters.
// This function is meant to be used as a helper in a command completion handler.
// #param query string
// #param ctx string
// #param fields table
/*
#example
-- an extremely simple completer for sudo.
hilbish.complete('command.sudo', function(query, ctx, fields)
table.remove(fields, 1)
if #fields[1] then
-- return commands because sudo runs a command as root..!
local entries, pfx = hilbish.completion.bins(query, ctx, fields)
return {
type = 'grid',
items = entries
}, pfx
end
-- ... else suggest files or anything else ..
end)
#example
*/
func hcmpBins(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
query, ctx, fds, err := getCompleteParams(t, c)
if err != nil {
return nil, err
}
completions, pfx := binaryComplete(query, ctx, fds)
luaComps := rt.NewTable()
for i, comp := range completions {
luaComps.Set(rt.IntValue(int64(i + 1)), rt.StringValue(comp))
}
return c.PushingNext(t.Runtime, rt.TableValue(luaComps), rt.StringValue(pfx)), nil
// handler(line, pos)
// The handler function is the callback for tab completion in Hilbish.
// You can check the completions doc for more info.
// --- @param line string
// --- @param pos string
func completionHandler(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.Next(), nil
}
// #interface completion
// call(name, query, ctx, fields) -> completionGroups (table), prefix (string)
// Calls a completer function. This is mainly used to call a command completer, which will have a `name`
// in the form of `command.name`, example: `command.git`.
// You can check the Completions doc or `doc completions` for info on the `completionGroups` return value.
// #param name string
// #param query string
// #param ctx string
// #param fields table
func hcmpCall(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// Calls a completer function. This is mainly used to call
// a command completer, which will have a `name` in the form
// of `command.name`, example: `command.git`.
// You can check `doc completions` for info on the `completionGroups` return value.
// --- @param name string
// --- @param query string
// --- @param ctx string
// --- @param fields table
func callLuaCompleter(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(4); err != nil {
return nil, err
}
@ -298,12 +267,11 @@ func hcmpCall(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface completion
// files(query, ctx, fields) -> entries (table), prefix (string)
// Returns file matches based on the provided parameters.
// This function is meant to be used as a helper in a command completion handler.
// #param query string
// #param ctx string
// #param fields table
func hcmpFiles(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// Returns file completion candidates based on the provided query.
// --- @param query string
// --- @param ctx string
// --- @param fields table
func luaFileComplete(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
query, ctx, fds, err := getCompleteParams(t, c)
if err != nil {
return nil, err
@ -320,30 +288,26 @@ func hcmpFiles(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// #interface completion
// handler(line, pos)
// This function contains the general completion handler for Hilbish. This function handles
// completion of everything, which includes calling other command handlers, binaries, and files.
// This function can be overriden to supply a custom handler. Note that alias resolution is required to be done in this function.
// #param line string The current Hilbish command line
// #param pos number Numerical position of the cursor
/*
#example
-- stripped down version of the default implementation
function hilbish.completion.handler(line, pos)
local query = fields[#fields]
if #fields == 1 then
-- call bins handler here
else
-- call command completer or files completer here
end
end
#example
*/
func hcmpHandler(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.Next(), nil
// bins(query, ctx, fields) -> entries (table), prefix (string)
// Returns binary/executale completion candidates based on the provided query.
// --- @param query string
// --- @param ctx string
// --- @param fields table
func luaBinaryComplete(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
query, ctx, fds, err := getCompleteParams(t, c)
if err != nil {
return nil, err
}
completions, pfx := binaryComplete(query, ctx, fds)
luaComps := rt.NewTable()
for i, comp := range completions {
luaComps.Set(rt.IntValue(int64(i + 1)), rt.StringValue(comp))
}
return c.PushingNext(t.Runtime, rt.TableValue(luaComps), rt.StringValue(pfx)), nil
}
func getCompleteParams(t *rt.Thread, c *rt.GoCont) (string, string, []string, error) {
if err := c.CheckNArgs(3); err != nil {

View File

@ -1,7 +1,7 @@
---
title: API
layout: doc
weight: -100
weight: -50
menu: docs
---

View File

@ -8,160 +8,27 @@ menu:
---
## Introduction
Bait is the event emitter for Hilbish. Much like Node.js and
its `events` system, many actions in Hilbish emit events.
Unlike Node.js, Hilbish events are global. So make sure to
pick a unique name!
Usage of the Bait module consists of userstanding
event-driven architecture, but it's pretty simple:
If you want to act on a certain event, you can `catch` it.
You can act on events via callback functions.
Examples of this are in the Hilbish default config!
Consider this part of it:
```lua
bait.catch('command.exit', function(code)
running = false
doPrompt(code ~= 0)
doNotifyPrompt()
end)
```
What this does is, whenever the `command.exit` event is thrown,
this function will set the user prompt.
Bait is the event emitter for Hilbish. Why name it bait? Why not.
It throws hooks that you can catch. This is what you will use if
you want to listen in on hooks to know when certain things have
happened, like when you've changed directory, a command has failed,
etc. To find all available hooks thrown by Hilbish, see doc hooks.
## Functions
|||
|----|----|
|<a href="#catch">catch(name, cb)</a>|Catches an event. This function can be used to act on events.|
|<a href="#catchOnce">catchOnce(name, cb)</a>|Catches an event, but only once. This will remove the hook immediately after it runs for the first time.|
|<a href="#hooks">hooks(name) -> table</a>|Returns a table of functions that are hooked on an event with the corresponding `name`.|
|<a href="#release">release(name, catcher)</a>|Removes the `catcher` for the event with `name`.|
|<a href="#throw">throw(name, ...args)</a>|Throws a hook with `name` with the provided `args`.|
### catch(name, cb)
Catches a hook with `name`. Runs the `cb` when it is thrown
<hr>
<div id='catch'>
<h4 class='heading'>
bait.catch(name, cb)
<a href="#catch" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### catchOnce(name, cb)
Same as catch, but only runs the `cb` once and then removes the hook
Catches an event. This function can be used to act on events.
#### Parameters
`string` **`name`**
The name of the hook.
`function` **`cb`**
The function that will be called when the hook is thrown.
#### Example
```lua
bait.catch('hilbish.exit', function()
print 'Goodbye Hilbish!'
end)
```
</div>
<hr>
<div id='catchOnce'>
<h4 class='heading'>
bait.catchOnce(name, cb)
<a href="#catchOnce" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Catches an event, but only once. This will remove the hook immediately after it runs for the first time.
#### Parameters
`string` **`name`**
The name of the event
`function` **`cb`**
The function that will be called when the event is thrown.
</div>
<hr>
<div id='hooks'>
<h4 class='heading'>
bait.hooks(name) -> table
<a href="#hooks" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Returns a table of functions that are hooked on an event with the corresponding `name`.
#### Parameters
`string` **`name`**
The name of the hook
</div>
<hr>
<div id='release'>
<h4 class='heading'>
bait.release(name, catcher)
<a href="#release" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### hooks(name) -> table
Returns a table with hooks (callback functions) on the event with `name`.
### release(name, catcher)
Removes the `catcher` for the event with `name`.
For this to work, `catcher` has to be the same function used to catch
an event, like one saved to a variable.
#### Parameters
`string` **`name`**
Name of the event the hook is on
`function` **`catcher`**
Hook function to remove
#### Example
```lua
local hookCallback = function() print 'hi' end
bait.catch('event', hookCallback)
-- a little while later....
bait.release('event', hookCallback)
-- and now hookCallback will no longer be ran for the event.
```
</div>
<hr>
<div id='throw'>
<h4 class='heading'>
bait.throw(name, ...args)
<a href="#throw" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Throws a hook with `name` with the provided `args`.
#### Parameters
`string` **`name`**
The name of the hook.
`any` **`args`** (This type is variadic. You can pass an infinite amount of parameters with this type.)
The arguments to pass to the hook.
#### Example
```lua
bait.throw('greeting', 'world')
-- This can then be listened to via
bait.catch('gretting', function(greetTo)
print('Hello ' .. greetTo)
end)
```
</div>
### throw(name, ...args)
Throws a hook with `name` with the provided `args`

View File

@ -9,10 +9,11 @@ menu:
## Introduction
Commander is the library which handles Hilbish commands. This makes
the user able to add Lua-written commands to their shell without making
a separate script in a bin folder. Instead, you may simply use the Commander
library in your Hilbish config.
Commander is a library for writing custom commands in Lua.
In order to make it easier to write commands for Hilbish,
not require separate scripts and to be able to use in a config,
the Commander library exists. This is like a very simple wrapper
that works with Hilbish for writing commands. Example:
```lua
local commander = require 'commander'
@ -27,67 +28,19 @@ that will print `Hello world!` to output. One question you may
have is: What is the `sinks` parameter?
The `sinks` parameter is a table with 3 keys: `in`, `out`,
and `err`. All of them are a <a href="/Hilbish/docs/api/hilbish/#sink" style="text-decoration: none;">Sink</a>.
and `err`. The values of these is a <a href="/Hilbish/docs/api/hilbish/#sink" style="text-decoration: none;">Sink</a>.
- `in` is the standard input.
You may use the read functions on this sink to get input from the user.
- `out` is standard output.
This is usually where command output should go.
- `err` is standard error.
This sink is for writing errors, as the name would suggest.
- `in` is the standard input. You can read from this sink
to get user input. (**This is currently unimplemented.**)
- `out` is standard output. This is usually where text meant for
output should go.
- `err` is standard error. This sink is for writing errors, as the
name would suggest.
## Functions
|||
|----|----|
|<a href="#deregister">deregister(name)</a>|Removes the named command. Note that this will only remove Commander-registered commands.|
|<a href="#register">register(name, cb)</a>|Adds a new command with the given `name`. When Hilbish has to run a command with a name,|
### deregister(name)
Deregisters any command registered with `name`
<hr>
<div id='deregister'>
<h4 class='heading'>
commander.deregister(name)
<a href="#deregister" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Removes the named command. Note that this will only remove Commander-registered commands.
#### Parameters
`string` **`name`**
Name of the command to remove.
</div>
<hr>
<div id='register'>
<h4 class='heading'>
commander.register(name, cb)
<a href="#register" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Adds a new command with the given `name`. When Hilbish has to run a command with a name,
it will run the function providing the arguments and sinks.
#### Parameters
`string` **`name`**
Name of the command
`function` **`cb`**
Callback to handle command invocation
#### Example
```lua
-- When you run the command `hello` in the shell, it will print `Hello world`.
-- If you run it with, for example, `hello Hilbish`, it will print 'Hello Hilbish'
commander.register('hello', function(args, sinks)
local name = 'world'
if #args > 0 then name = args[1] end
sinks.out:writeln('Hello ' .. name)
end)
```
</div>
### register(name, cb)
Register a command with `name` that runs `cb` when ran

View File

@ -8,233 +8,44 @@ menu:
---
## Introduction
The fs module provides filesystem functions to Hilbish. While Lua's standard
library has some I/O functions, they're missing a lot of the basics. The `fs`
library offers more functions and will work on any operating system Hilbish does.
The fs module provides easy and simple access to filesystem functions
and other things, and acts an addition to the Lua standard library's
I/O and filesystem functions.
## Functions
|||
|----|----|
|<a href="#abs">abs(path) -> string</a>|Returns an absolute version of the `path`.|
|<a href="#basename">basename(path) -> string</a>|Returns the "basename," or the last part of the provided `path`. If path is empty,|
|<a href="#cd">cd(dir)</a>|Changes Hilbish's directory to `dir`.|
|<a href="#dir">dir(path) -> string</a>|Returns the directory part of `path`. If a file path like|
|<a href="#glob">glob(pattern) -> matches (table)</a>|Match all files based on the provided `pattern`.|
|<a href="#join">join(...path) -> string</a>|Takes any list of paths and joins them based on the operating system's path separator.|
|<a href="#mkdir">mkdir(name, recursive)</a>|Creates a new directory with the provided `name`.|
|<a href="#readdir">readdir(path) -> table[string]</a>|Returns a list of all files and directories in the provided path.|
|<a href="#stat">stat(path) -> {}</a>|Returns the information about a given `path`.|
### abs(path) -> string
Gives an absolute version of `path`.
## Static module fields
|||
|----|----|
|pathSep|The operating system's path separator.|
### basename(path) -> string
Gives the basename of `path`. For the rules,
see Go's filepath.Base
<hr>
<div id='abs'>
<h4 class='heading'>
fs.abs(path) -> string
<a href="#abs" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### cd(dir)
Changes directory to `dir`
Returns an absolute version of the `path`.
This can be used to resolve short paths like `..` to `/home/user`.
### dir(path) -> string
Returns the directory part of `path`. For the rules, see Go's
filepath.Dir
#### Parameters
`string` **`path`**
### glob(pattern) -> matches (table)
Glob all files and directories that match the pattern.
For the rules, see Go's filepath.Glob
### join(...) -> string
Takes paths and joins them together with the OS's
directory separator (forward or backward slash).
</div>
### mkdir(name, recursive)
Makes a directory called `name`. If `recursive` is true, it will create its parent directories.
<hr>
<div id='basename'>
<h4 class='heading'>
fs.basename(path) -> string
<a href="#basename" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### readdir(dir) -> {}
Returns a table of files in `dir`.
Returns the "basename," or the last part of the provided `path`. If path is empty,
`.` will be returned.
#### Parameters
`string` **`path`**
Path to get the base name of.
</div>
<hr>
<div id='cd'>
<h4 class='heading'>
fs.cd(dir)
<a href="#cd" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Changes Hilbish's directory to `dir`.
#### Parameters
`string` **`dir`**
Path to change directory to.
</div>
<hr>
<div id='dir'>
<h4 class='heading'>
fs.dir(path) -> string
<a href="#dir" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Returns the directory part of `path`. If a file path like
`~/Documents/doc.txt` then this function will return `~/Documents`.
#### Parameters
`string` **`path`**
Path to get the directory for.
</div>
<hr>
<div id='glob'>
<h4 class='heading'>
fs.glob(pattern) -> matches (table)
<a href="#glob" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Match all files based on the provided `pattern`.
For the syntax' refer to Go's filepath.Match function: https://pkg.go.dev/path/filepath#Match
#### Parameters
`string` **`pattern`**
Pattern to compare files with.
#### Example
```lua
--[[
Within a folder that contains the following files:
a.txt
init.lua
code.lua
doc.pdf
]]--
local matches = fs.glob './*.lua'
print(matches)
-- -> {'init.lua', 'code.lua'}
```
</div>
<hr>
<div id='join'>
<h4 class='heading'>
fs.join(...path) -> string
<a href="#join" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Takes any list of paths and joins them based on the operating system's path separator.
#### Parameters
`string` **`path`** (This type is variadic. You can pass an infinite amount of parameters with this type.)
Paths to join together
#### Example
```lua
-- This prints the directory for Hilbish's config!
print(fs.join(hilbish.userDir.config, 'hilbish'))
-- -> '/home/user/.config/hilbish' on Linux
```
</div>
<hr>
<div id='mkdir'>
<h4 class='heading'>
fs.mkdir(name, recursive)
<a href="#mkdir" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Creates a new directory with the provided `name`.
With `recursive`, mkdir will create parent directories.
#### Parameters
`string` **`name`**
Name of the directory
`boolean` **`recursive`**
Whether to create parent directories for the provided name
#### Example
```lua
-- This will create the directory foo, then create the directory bar in the
-- foo directory. If recursive is false in this case, it will fail.
fs.mkdir('./foo/bar', true)
```
</div>
<hr>
<div id='readdir'>
<h4 class='heading'>
fs.readdir(path) -> table[string]
<a href="#readdir" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Returns a list of all files and directories in the provided path.
#### Parameters
`string` **`dir`**
</div>
<hr>
<div id='stat'>
<h4 class='heading'>
fs.stat(path) -> {}
<a href="#stat" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Returns the information about a given `path`.
The returned table contains the following values:
### stat(path) -> {}
Returns a table of info about the `path`.
It contains the following keys:
name (string) - Name of the path
size (number) - Size of the path in bytes
mode (string) - Unix permission mode in an octal format string (with leading 0)
size (number) - Size of the path
mode (string) - Permission mode in an octal format string (with leading 0)
isDir (boolean) - If the path is a directory
#### Parameters
`string` **`path`**
#### Example
```lua
local inspect = require 'inspect'
local stat = fs.stat '~'
print(inspect(stat))
--[[
Would print the following:
{
isDir = true,
mode = "0755",
name = "username",
size = 12288
}
]]--
```
</div>

View File

@ -11,490 +11,108 @@ menu:
The Hilbish module includes the core API, containing
interfaces and functions which directly relate to shell functionality.
## Interface fields
- `ver`: The version of Hilbish
- `goVersion`: The version of Go that Hilbish was compiled with
- `user`: Username of the user
- `host`: Hostname of the machine
- `dataDir`: Directory for Hilbish data files, including the docs and default modules
- `interactive`: Is Hilbish in an interactive shell?
- `login`: Is Hilbish the login shell?
- `vimMode`: Current Vim input mode of Hilbish (will be nil if not in Vim input mode)
- `exitCode`: xit code of the last executed command
## Functions
|||
|----|----|
|<a href="#alias">alias(cmd, orig)</a>|Sets an alias, with a name of `cmd` to another command.|
|<a href="#appendPath">appendPath(dir)</a>|Appends the provided dir to the command path (`$PATH`)|
|<a href="#complete">complete(scope, cb)</a>|Registers a completion handler for the specified scope.|
|<a href="#cwd">cwd() -> string</a>|Returns the current directory of the shell.|
|<a href="#exec">exec(cmd)</a>|Replaces the currently running Hilbish instance with the supplied command.|
|<a href="#goro">goro(fn)</a>|Puts `fn` in a Goroutine.|
|<a href="#highlighter">highlighter(line)</a>|Line highlighter handler.|
|<a href="#hinter">hinter(line, pos)</a>|The command line hint handler. It gets called on every key insert to|
|<a href="#inputMode">inputMode(mode)</a>|Sets the input mode for Hilbish's line reader.|
|<a href="#interval">interval(cb, time) -> @Timer</a>|Runs the `cb` function every specified amount of `time`.|
|<a href="#multiprompt">multiprompt(str)</a>|Changes the text prompt when Hilbish asks for more input.|
|<a href="#prependPath">prependPath(dir)</a>|Prepends `dir` to $PATH.|
|<a href="#prompt">prompt(str, typ)</a>|Changes the shell prompt to the provided string.|
|<a href="#read">read(prompt) -> input (string)</a>|Read input from the user, using Hilbish's line editor/input reader.|
|<a href="#run">run(cmd, returnOut) -> exitCode (number), stdout (string), stderr (string)</a>|Runs `cmd` in Hilbish's shell script interpreter.|
|<a href="#runnerMode">runnerMode(mode)</a>|Sets the execution/runner mode for interactive Hilbish.|
|<a href="#timeout">timeout(cb, time) -> @Timer</a>|Executed the `cb` function after a period of `time`.|
|<a href="#which">which(name) -> string</a>|Checks if `name` is a valid command.|
### alias(cmd, orig)
Sets an alias of `cmd` to `orig`
## Static module fields
|||
|----|----|
|ver|The version of Hilbish|
|goVersion|The version of Go that Hilbish was compiled with|
|user|Username of the user|
|host|Hostname of the machine|
|dataDir|Directory for Hilbish data files, including the docs and default modules|
|interactive|Is Hilbish in an interactive shell?|
|login|Is Hilbish the login shell?|
|vimMode|Current Vim input mode of Hilbish (will be nil if not in Vim input mode)|
|exitCode|Exit code of the last executed command|
### appendPath(dir)
Appends `dir` to $PATH
<hr>
<div id='alias'>
<h4 class='heading'>
hilbish.alias(cmd, orig)
<a href="#alias" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Sets an alias, with a name of `cmd` to another command.
#### Parameters
`string` **`cmd`**
Name of the alias
`string` **`orig`**
Command that will be aliased
#### Example
```lua
-- With this, "ga file" will turn into "git add file"
hilbish.alias('ga', 'git add')
-- Numbered substitutions are supported here!
hilbish.alias('dircount', 'ls %1 | wc -l')
-- "dircount ~" would count how many files are in ~ (home directory).
```
</div>
<hr>
<div id='appendPath'>
<h4 class='heading'>
hilbish.appendPath(dir)
<a href="#appendPath" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Appends the provided dir to the command path (`$PATH`)
#### Parameters
`string|table` **`dir`**
Directory (or directories) to append to path
#### Example
```lua
hilbish.appendPath '~/go/bin'
-- Will add ~/go/bin to the command path.
-- Or do multiple:
hilbish.appendPath {
'~/go/bin',
'~/.local/bin'
}
```
</div>
<hr>
<div id='complete'>
<h4 class='heading'>
hilbish.complete(scope, cb)
<a href="#complete" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Registers a completion handler for the specified scope.
A `scope` is expected to be `command.<cmd>`,
### complete(scope, cb)
Registers a completion handler for `scope`.
A `scope` is currently only expected to be `command.<cmd>`,
replacing <cmd> with the name of the command (for example `command.git`).
The documentation for completions, under Features/Completions or `doc completions`
provides more details.
`cb` must be a function that returns a table of "completion groups."
Check `doc completions` for more information.
#### Parameters
`string` **`scope`**
### cwd() -> string
Returns the current directory of the shell
### exec(cmd)
Replaces running hilbish with `cmd`
`function` **`cb`**
### goro(fn)
Puts `fn` in a goroutine
#### Example
```lua
-- This is a very simple example. Read the full doc for completions for details.
hilbish.complete('command.sudo', function(query, ctx, fields)
if #fields == 0 then
-- complete for commands
local comps, pfx = hilbish.completion.bins(query, ctx, fields)
local compGroup = {
items = comps, -- our list of items to complete
type = 'grid' -- what our completions will look like.
}
return {compGroup}, pfx
end
-- otherwise just be boring and return files
local comps, pfx = hilbish.completion.files(query, ctx, fields)
local compGroup = {
items = comps,
type = 'grid'
}
return {compGroup}, pfx
end)
```
</div>
<hr>
<div id='cwd'>
<h4 class='heading'>
hilbish.cwd() -> string
<a href="#cwd" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Returns the current directory of the shell.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='exec'>
<h4 class='heading'>
hilbish.exec(cmd)
<a href="#exec" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Replaces the currently running Hilbish instance with the supplied command.
This can be used to do an in-place restart.
#### Parameters
`string` **`cmd`**
</div>
<hr>
<div id='goro'>
<h4 class='heading'>
hilbish.goro(fn)
<a href="#goro" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Puts `fn` in a Goroutine.
This can be used to run any function in another thread at the same time as other Lua code.
**NOTE: THIS FUNCTION MAY CRASH HILBISH IF OUTSIDE VARIABLES ARE ACCESSED.**
**This is a limitation of the Lua runtime.**
#### Parameters
`function` **`fn`**
</div>
<hr>
<div id='highlighter'>
<h4 class='heading'>
hilbish.highlighter(line)
<a href="#highlighter" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Line highlighter handler.
This is mainly for syntax highlighting, but in reality could set the input
of the prompt to *display* anything. The callback is passed the current line
and is expected to return a line that will be used as the input display.
### highlighter(line)
Line highlighter handler. This is mainly for syntax highlighting, but in
reality could set the input of the prompt to *display* anything. The
callback is passed the current line and is expected to return a line that
will be used as the input display.
Note that to set a highlighter, one has to override this function.
#### Parameters
`string` **`line`**
#### Example
```lua
--This code will highlight all double quoted strings in green.
Example:
```
function hilbish.highlighter(line)
return line:gsub('"%w+"', function(c) return lunacolors.green(c) end)
end
```
</div>
<hr>
<div id='hinter'>
<h4 class='heading'>
hilbish.hinter(line, pos)
<a href="#hinter" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
This code will highlight all double quoted strings in green.
### hinter(line, pos)
The command line hint handler. It gets called on every key insert to
determine what text to use as an inline hint. It is passed the current
line and cursor position. It is expected to return a string which is used
as the text for the hint. This is by default a shim. To set hints,
override this function with your custom handler.
#### Parameters
`string` **`line`**
### inputMode(mode)
Sets the input mode for Hilbish's line reader. Accepts either emacs or vim
### interval(cb, time) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;">Timer</a>
Runs the `cb` function every `time` milliseconds.
This creates a timer that starts immediately.
`number` **`pos`**
Position of cursor in line. Usually equals string.len(line)
### multiprompt(str)
Changes the continued line prompt to `str`
#### Example
```lua
-- this will display "hi" after the cursor in a dimmed color.
function hilbish.hinter(line, pos)
return 'hi'
end
```
</div>
### prependPath(dir)
Prepends `dir` to $PATH
<hr>
<div id='inputMode'>
<h4 class='heading'>
hilbish.inputMode(mode)
<a href="#inputMode" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Sets the input mode for Hilbish's line reader.
`emacs` is the default. Setting it to `vim` changes behavior of input to be
Vim-like with modes and Vim keybinds.
#### Parameters
`string` **`mode`**
Can be set to either `emacs` or `vim`
</div>
<hr>
<div id='interval'>
<h4 class='heading'>
hilbish.interval(cb, time) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;" id="lol">Timer</a>
<a href="#interval" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Runs the `cb` function every specified amount of `time`.
This creates a timer that ticking immediately.
#### Parameters
`function` **`cb`**
`number` **`time`**
Time in milliseconds.
</div>
<hr>
<div id='multiprompt'>
<h4 class='heading'>
hilbish.multiprompt(str)
<a href="#multiprompt" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Changes the text prompt when Hilbish asks for more input.
This will show up when text is incomplete, like a missing quote
#### Parameters
`string` **`str`**
#### Example
```lua
--[[
imagine this is your text input:
user ~ ∆ echo "hey
but there's a missing quote! hilbish will now prompt you so the terminal
will look like:
user ~ ∆ echo "hey
--> ...!"
so then you get
user ~ ∆ echo "hey
--> ...!"
hey ...!
]]--
hilbish.multiprompt '-->'
```
</div>
<hr>
<div id='prependPath'>
<h4 class='heading'>
hilbish.prependPath(dir)
<a href="#prependPath" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Prepends `dir` to $PATH.
#### Parameters
`string` **`dir`**
</div>
<hr>
<div id='prompt'>
<h4 class='heading'>
hilbish.prompt(str, typ)
<a href="#prompt" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Changes the shell prompt to the provided string.
### prompt(str, typ)
Changes the shell prompt to `str`
There are a few verbs that can be used in the prompt text.
These will be formatted and replaced with the appropriate values.
`%d` - Current working directory
`%u` - Name of current user
`%h` - Hostname of device
#### Parameters
`string` **`str`**
`string` **`typ?`**
Type of prompt, being left or right. Left by default.
#### Example
```lua
-- the default hilbish prompt without color
hilbish.prompt '%u %d ∆'
-- or something of old:
hilbish.prompt '%u@%h :%d $'
-- prompt: user@hostname: ~/directory $
```
</div>
<hr>
<div id='read'>
<h4 class='heading'>
hilbish.read(prompt) -> input (string)
<a href="#read" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### read(prompt) -> input (string)
Read input from the user, using Hilbish's line editor/input reader.
This is a separate instance from the one Hilbish actually uses.
Returns `input`, will be nil if Ctrl-D is pressed, or an error occurs.
Returns `input`, will be nil if ctrl + d is pressed, or an error occurs (which shouldn't happen)
#### Parameters
`string` **`prompt?`**
Text to print before input, can be empty.
### run(cmd, returnOut) -> exitCode (number), stdout (string), stderr (string)
Runs `cmd` in Hilbish's sh interpreter.
If returnOut is true, the outputs of `cmd` will be returned as the 2nd and
3rd values instead of being outputted to the terminal.
</div>
<hr>
<div id='run'>
<h4 class='heading'>
hilbish.run(cmd, returnOut) -> exitCode (number), stdout (string), stderr (string)
<a href="#run" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Runs `cmd` in Hilbish's shell script interpreter.
#### Parameters
`string` **`cmd`**
`boolean` **`returnOut`**
If this is true, the function will return the standard output and error of the command instead of printing it.
</div>
<hr>
<div id='runnerMode'>
<h4 class='heading'>
hilbish.runnerMode(mode)
<a href="#runnerMode" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Sets the execution/runner mode for interactive Hilbish.
This determines whether Hilbish wll try to run input as Lua
and/or sh or only do one of either.
### runnerMode(mode)
Sets the execution/runner mode for interactive Hilbish. This determines whether
Hilbish wll try to run input as Lua and/or sh or only do one of either.
Accepted values for mode are hybrid (the default), hybridRev (sh first then Lua),
sh, and lua. It also accepts a function, to which if it is passed one
will call it to execute user input instead.
Read [about runner mode](../features/runner-mode) for more information.
#### Parameters
`string|function` **`mode`**
</div>
<hr>
<div id='timeout'>
<h4 class='heading'>
hilbish.timeout(cb, time) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;" id="lol">Timer</a>
<a href="#timeout" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Executed the `cb` function after a period of `time`.
This creates a Timer that starts ticking immediately.
#### Parameters
`function` **`cb`**
`number` **`time`**
Time to run in milliseconds.
</div>
<hr>
<div id='which'>
<h4 class='heading'>
hilbish.which(name) -> string
<a href="#which" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### timeout(cb, time) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;">Timer</a>
Runs the `cb` function after `time` in milliseconds.
This creates a timer that starts immediately.
### which(name) -> string
Checks if `name` is a valid command.
Will return the path of the binary, or a basename if it's a commander.
#### Parameters
`string` **`name`**
</div>
## Types
<hr>
## Sink
A sink is a structure that has input and/or output to/from
a desination.

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.aliases
title: Interface hilbish.aliases
description: command aliasing
layout: doc
menu:
@ -11,81 +11,15 @@ menu:
The alias interface deals with all command aliases in Hilbish.
## Functions
|||
|----|----|
|<a href="#aliases.add">add(alias, cmd)</a>|This is an alias (ha) for the [hilbish.alias](../#alias) function.|
|<a href="#aliases.delete">delete(name)</a>|Removes an alias.|
|<a href="#aliases.list">list() -> table[string, string]</a>|Get a table of all aliases, with string keys as the alias and the value as the command.|
|<a href="#aliases.resolve">resolve(alias) -> string?</a>|Resolves an alias to its original command. Will thrown an error if the alias doesn't exist.|
<hr>
<div id='aliases.add'>
<h4 class='heading'>
hilbish.aliases.add(alias, cmd)
<a href="#aliases.add" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
This is an alias (ha) for the [hilbish.alias](../#alias) function.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='aliases.delete'>
<h4 class='heading'>
hilbish.aliases.delete(name)
<a href="#aliases.delete" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### add(alias, cmd)
This is an alias (ha) for the `hilbish.alias` function.
### delete(name)
Removes an alias.
#### Parameters
`string` **`name`**
</div>
<hr>
<div id='aliases.list'>
<h4 class='heading'>
hilbish.aliases.list() -> table[string, string]
<a href="#aliases.list" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### list() -> table\<string, string>
Get a table of all aliases, with string keys as the alias and the value as the command.
#### Parameters
This function has no parameters.
#### Example
```lua
hilbish.aliases.add('hi', 'echo hi')
local aliases = hilbish.aliases.list()
-- -> {hi = 'echo hi'}
```
</div>
<hr>
<div id='aliases.resolve'>
<h4 class='heading'>
hilbish.aliases.resolve(alias) -> string?
<a href="#aliases.resolve" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Resolves an alias to its original command. Will thrown an error if the alias doesn't exist.
#### Parameters
`string` **`alias`**
</div>
### resolve(alias) -> command (string)
Tries to resolve an alias to its command.

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.completion
title: Interface hilbish.completion
description: tab completions
layout: doc
menu:
@ -11,139 +11,19 @@ menu:
The completions interface deals with tab completions.
## Functions
|||
|----|----|
|<a href="#completion.bins">bins(query, ctx, fields) -> entries (table), prefix (string)</a>|Return binaries/executables based on the provided parameters.|
|<a href="#completion.call">call(name, query, ctx, fields) -> completionGroups (table), prefix (string)</a>|Calls a completer function. This is mainly used to call a command completer, which will have a `name`|
|<a href="#completion.files">files(query, ctx, fields) -> entries (table), prefix (string)</a>|Returns file matches based on the provided parameters.|
|<a href="#completion.handler">handler(line, pos)</a>|This function contains the general completion handler for Hilbish. This function handles|
### call(name, query, ctx, fields) -> completionGroups (table), prefix (string)
Calls a completer function. This is mainly used to call
a command completer, which will have a `name` in the form
of `command.name`, example: `command.git`.
You can check `doc completions` for info on the `completionGroups` return value.
<hr>
<div id='completion.bins'>
<h4 class='heading'>
hilbish.completion.bins(query, ctx, fields) -> entries (table), prefix (string)
<a href="#completion.bins" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### handler(line, pos)
The handler function is the callback for tab completion in Hilbish.
You can check the completions doc for more info.
Return binaries/executables based on the provided parameters.
This function is meant to be used as a helper in a command completion handler.
### bins(query, ctx, fields) -> entries (table), prefix (string)
Returns binary/executale completion candidates based on the provided query.
#### Parameters
`string` **`query`**
`string` **`ctx`**
`table` **`fields`**
#### Example
```lua
-- an extremely simple completer for sudo.
hilbish.complete('command.sudo', function(query, ctx, fields)
table.remove(fields, 1)
if #fields[1] then
-- return commands because sudo runs a command as root..!
local entries, pfx = hilbish.completion.bins(query, ctx, fields)
return {
type = 'grid',
items = entries
}, pfx
end
-- ... else suggest files or anything else ..
end)
```
</div>
<hr>
<div id='completion.call'>
<h4 class='heading'>
hilbish.completion.call(name, query, ctx, fields) -> completionGroups (table), prefix (string)
<a href="#completion.call" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Calls a completer function. This is mainly used to call a command completer, which will have a `name`
in the form of `command.name`, example: `command.git`.
You can check the Completions doc or `doc completions` for info on the `completionGroups` return value.
#### Parameters
`string` **`name`**
`string` **`query`**
`string` **`ctx`**
`table` **`fields`**
</div>
<hr>
<div id='completion.files'>
<h4 class='heading'>
hilbish.completion.files(query, ctx, fields) -> entries (table), prefix (string)
<a href="#completion.files" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Returns file matches based on the provided parameters.
This function is meant to be used as a helper in a command completion handler.
#### Parameters
`string` **`query`**
`string` **`ctx`**
`table` **`fields`**
</div>
<hr>
<div id='completion.handler'>
<h4 class='heading'>
hilbish.completion.handler(line, pos)
<a href="#completion.handler" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
This function contains the general completion handler for Hilbish. This function handles
completion of everything, which includes calling other command handlers, binaries, and files.
This function can be overriden to supply a custom handler. Note that alias resolution is required to be done in this function.
#### Parameters
`string` **`line`**
The current Hilbish command line
`number` **`pos`**
Numerical position of the cursor
#### Example
```lua
-- stripped down version of the default implementation
function hilbish.completion.handler(line, pos)
local query = fields[#fields]
if #fields == 1 then
-- call bins handler here
else
-- call command completer or files completer here
end
end
```
</div>
### files(query, ctx, fields) -> entries (table), prefix (string)
Returns file completion candidates based on the provided query.

View File

@ -0,0 +1,29 @@
---
title: Interface hilbish.completions
description: tab completions
layout: doc
menu:
docs:
parent: "API"
---
## Introduction
The completions interface deals with tab completions.
## Functions
### call(name, query, ctx, fields) -> completionGroups (table), prefix (string)
Calls a completer function. This is mainly used to call
a command completer, which will have a `name` in the form
of `command.name`, example: `command.git`.
You can check `doc completions` for info on the `completionGroups` return value.
### handler(line, pos)
The handler function is the callback for tab completion in Hilbish.
You can check the completions doc for more info.
### bins(query, ctx, fields) -> entries (table), prefix (string)
Returns binary/executale completion candidates based on the provided query.
### files(query, ctx, fields) -> entries (table), prefix (string)
Returns file completion candidates based on the provided query.

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.editor
title: Interface hilbish.editor
description: interactions for Hilbish's line reader
layout: doc
menu:
@ -12,92 +12,19 @@ The hilbish.editor interface provides functions to
directly interact with the line editor in use.
## Functions
|||
|----|----|
|<a href="#editor.getLine">getLine() -> string</a>|Returns the current input line.|
|<a href="#editor.getVimRegister">getVimRegister(register) -> string</a>|Returns the text that is at the register.|
|<a href="#editor.insert">insert(text)</a>|Inserts text into the Hilbish command line.|
|<a href="#editor.getChar">getChar() -> string</a>|Reads a keystroke from the user. This is in a format of something like Ctrl-L.|
|<a href="#editor.setVimRegister">setVimRegister(register, text)</a>|Sets the vim register at `register` to hold the passed text.|
<hr>
<div id='editor.getLine'>
<h4 class='heading'>
hilbish.editor.getLine() -> string
<a href="#editor.getLine" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### getLine() -> string
Returns the current input line.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='editor.getVimRegister'>
<h4 class='heading'>
hilbish.editor.getVimRegister(register) -> string
<a href="#editor.getVimRegister" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### getVimRegister(register) -> string
Returns the text that is at the register.
#### Parameters
`string` **`register`**
### insert(text)
Inserts text into the line.
### getChar() -> string
Reads a keystroke from the user. This is in a format
of something like Ctrl-L..
</div>
<hr>
<div id='editor.insert'>
<h4 class='heading'>
hilbish.editor.insert(text)
<a href="#editor.insert" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Inserts text into the Hilbish command line.
#### Parameters
`string` **`text`**
</div>
<hr>
<div id='editor.getChar'>
<h4 class='heading'>
hilbish.editor.getChar() -> string
<a href="#editor.getChar" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Reads a keystroke from the user. This is in a format of something like Ctrl-L.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='editor.setVimRegister'>
<h4 class='heading'>
hilbish.editor.setVimRegister(register, text)
<a href="#editor.setVimRegister" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### setVimRegister(register, text)
Sets the vim register at `register` to hold the passed text.
#### Parameters
`string` **`text`**
</div>

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.history
title: Interface hilbish.history
description: command history
layout: doc
menu:
@ -13,90 +13,18 @@ This includes the ability to override functions to change the main
method of saving history.
## Functions
|||
|----|----|
|<a href="#history.add">add(cmd)</a>|Adds a command to the history.|
|<a href="#history.all">all() -> table</a>|Retrieves all history as a table.|
|<a href="#history.clear">clear()</a>|Deletes all commands from the history.|
|<a href="#history.get">get(index)</a>|Retrieves a command from the history based on the `index`.|
|<a href="#history.size">size() -> number</a>|Returns the amount of commands in the history.|
<hr>
<div id='history.add'>
<h4 class='heading'>
hilbish.history.add(cmd)
<a href="#history.add" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### add(cmd)
Adds a command to the history.
#### Parameters
`string` **`cmd`**
</div>
<hr>
<div id='history.all'>
<h4 class='heading'>
hilbish.history.all() -> table
<a href="#history.all" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Retrieves all history as a table.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='history.clear'>
<h4 class='heading'>
hilbish.history.clear()
<a href="#history.clear" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### all() -> table
Retrieves all history.
### clear()
Deletes all commands from the history.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='history.get'>
<h4 class='heading'>
hilbish.history.get(index)
<a href="#history.get" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Retrieves a command from the history based on the `index`.
#### Parameters
`number` **`index`**
</div>
<hr>
<div id='history.size'>
<h4 class='heading'>
hilbish.history.size() -> number
<a href="#history.size" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### get(idx)
Retrieves a command from the history based on the `idx`.
### size() -> number
Returns the amount of commands in the history.
#### Parameters
This function has no parameters.
</div>

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.jobs
title: Interface hilbish.jobs
description: background job management
layout: doc
menu:
@ -15,120 +15,32 @@ Jobs are the name of background tasks/commands. A job can be started via
interactive usage or with the functions defined below for use in external runners.
## Functions
|||
|----|----|
|<a href="#jobs.add">add(cmdstr, args, execPath)</a>|Creates a new job. This function does not run the job. This function is intended to be|
|<a href="#jobs.all">all() -> table[@Job]</a>|Returns a table of all job objects.|
|<a href="#jobs.disown">disown(id)</a>|Disowns a job. This simply deletes it from the list of jobs without stopping it.|
|<a href="#jobs.get">get(id) -> @Job</a>|Get a job object via its ID.|
|<a href="#jobs.last">last() -> @Job</a>|Returns the last added job to the table.|
<hr>
<div id='jobs.add'>
<h4 class='heading'>
hilbish.jobs.add(cmdstr, args, execPath)
<a href="#jobs.add" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Creates a new job. This function does not run the job. This function is intended to be
used by runners, but can also be used to create jobs via Lua. Commanders cannot be ran as jobs.
#### Parameters
`string` **`cmdstr`**
String that a user would write for the job
`table` **`args`**
Arguments for the commands. Has to include the name of the command.
`string` **`execPath`**
Binary to use to run the command. Needs to be an absolute path.
#### Example
```lua
hilbish.jobs.add('go build', {'go', 'build'}, '/usr/bin/go')
```
</div>
<hr>
<div id='jobs.all'>
<h4 class='heading'>
hilbish.jobs.all() -> table[<a href="/Hilbish/docs/api/hilbish/hilbish.jobs/#job" style="text-decoration: none;" id="lol">Job</a>]
<a href="#jobs.all" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### add(cmdstr, args, execPath)
Adds a new job to the job table. Note that this does not immediately run it.
### all() -> table\<<a href="/Hilbish/docs/api/hilbish/hilbish.jobs/#job" style="text-decoration: none;">Job</a>>
Returns a table of all job objects.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='jobs.disown'>
<h4 class='heading'>
hilbish.jobs.disown(id)
<a href="#jobs.disown" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Disowns a job. This simply deletes it from the list of jobs without stopping it.
#### Parameters
`number` **`id`**
</div>
<hr>
<div id='jobs.get'>
<h4 class='heading'>
hilbish.jobs.get(id) -> <a href="/Hilbish/docs/api/hilbish/hilbish.jobs/#job" style="text-decoration: none;" id="lol">Job</a>
<a href="#jobs.get" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### disown(id)
Disowns a job. This deletes it from the job table.
### get(id) -> <a href="/Hilbish/docs/api/hilbish/hilbish.jobs/#job" style="text-decoration: none;">Job</a>
Get a job object via its ID.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='jobs.last'>
<h4 class='heading'>
hilbish.jobs.last() -> <a href="/Hilbish/docs/api/hilbish/hilbish.jobs/#job" style="text-decoration: none;" id="lol">Job</a>
<a href="#jobs.last" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Returns the last added job to the table.
#### Parameters
This function has no parameters.
</div>
### last() -> <a href="/Hilbish/docs/api/hilbish/hilbish.jobs/#job" style="text-decoration: none;">Job</a>
Returns the last added job from the table.
## Types
<hr>
## Job
The Job type describes a Hilbish job.
## Object properties
|||
|----|----|
|cmd|The user entered command string for the job.|
|running|Whether the job is running or not.|
|id|The ID of the job in the job table|
|pid|The Process ID|
|exitCode|The last exit code of the job.|
|stdout|The standard output of the job. This just means the normal logs of the process.|
|stderr|The standard error stream of the process. This (usually) includes error messages of the job.|
### Properties
- `cmd`: The user entered command string for the job.
- `running`: Whether the job is running or not.
- `id`: The ID of the job in the job table
- `pid`: The Process ID
- `exitCode`: The last exit code of the job.
- `stdout`: The standard output of the job. This just means the normal logs of the process.
- `stderr`: The standard error stream of the process. This (usually) includes error messages of the job.
### Methods
#### background()

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.module
title: Interface hilbish.module
description: native module loading
layout: doc
menu:
@ -43,31 +43,11 @@ func Loader(rtm *rt.Runtime) rt.Value {
This can be compiled with `go build -buildmode=plugin plugin.go`.
If you attempt to require and print the result (`print(require 'plugin')`), it will show "hello world!"
## Interface fields
- `paths`: A list of paths to search when loading native modules. This is in the style of Lua search paths and will be used when requiring native modules. Example: `?.so;?/?.so`
## Functions
|||
|----|----|
|<a href="#module.load">load(path)</a>|Loads a module at the designated `path`.|
## Static module fields
|||
|----|----|
|paths|A list of paths to search when loading native modules. This is in the style of Lua search paths and will be used when requiring native modules. Example: `?.so;?/?.so`|
<hr>
<div id='module.load'>
<h4 class='heading'>
hilbish.module.load(path)
<a href="#module.load" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### load(path)
Loads a module at the designated `path`.
It will throw if any error occurs.
#### Parameters
`string` **`path`**
</div>

View File

@ -1,6 +1,6 @@
---
title: Module hilbish.os
description: operating system info
title: Interface hilbish.os
description: OS Info
layout: doc
menu:
docs:
@ -8,13 +8,12 @@ menu:
---
## Introduction
Provides simple text information properties about the current operating system.
This mainly includes the name and version.
The `os` interface provides simple text information properties about
the current OS on the systen. This mainly includes the name and
version.
## Static module fields
|||
|----|----|
|family|Family name of the current OS|
|name|Pretty name of the current OS|
|version|Version of the current OS|
## Interface fields
- `family`: Family name of the current OS
- `name`: Pretty name of the current OS
- `version`: Version of the current OS

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.runner
title: Interface hilbish.runner
description: interactive command runner customization
layout: doc
menu:
@ -14,101 +14,18 @@ Users can add and change the default runner for interactive input to any
language or script of their choosing. A good example is using it to
write command in Fennel.
Runners are functions that evaluate user input. The default runners in
Hilbish can run shell script and Lua code.
A runner is passed the input and has to return a table with these values.
All are not required, only the useful ones the runner needs to return.
(So if there isn't an error, just omit `err`.)
- `exitCode` (number): A numerical code to indicate the exit result.
- `input` (string): The user input. This will be used to add
to the history.
- `err` (string): A string to indicate an interal error for the runner.
It can be set to a few special values for Hilbish to throw the right hooks and have a better looking message:
`[command]: not-found` will throw a command.not-found hook based on what `[command]` is.
`[command]: not-executable` will throw a command.not-executable hook.
- `continue` (boolean): Whether to prompt the user for more input.
Here is a simple example of a fennel runner. It falls back to
shell script if fennel eval has an error.
```lua
local fennel = require 'fennel'
hilbish.runnerMode(function(input)
local ok = pcall(fennel.eval, input)
if ok then
return {
input = input
}
end
return hilbish.runner.sh(input)
end)
```
## Functions
|||
|----|----|
|<a href="#runner.setMode">setMode(cb)</a>|This is the same as the `hilbish.runnerMode` function.|
|<a href="#runner.lua">lua(cmd)</a>|Evaluates `cmd` as Lua input. This is the same as using `dofile`|
|<a href="#runner.sh">sh(cmd)</a>|Runs a command in Hilbish's shell script interpreter.|
<hr>
<div id='runner.setMode'>
<h4 class='heading'>
hilbish.runner.setMode(cb)
<a href="#runner.setMode" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
This is the same as the `hilbish.runnerMode` function.
It takes a callback, which will be used to execute all interactive input.
### setMode(cb)
This is the same as the `hilbish.runnerMode` function. It takes a callback,
which will be used to execute all interactive input.
In normal cases, neither callbacks should be overrided by the user,
as the higher level functions listed below this will handle it.
#### Parameters
`function` **`cb`**
</div>
<hr>
<div id='runner.lua'>
<h4 class='heading'>
hilbish.runner.lua(cmd)
<a href="#runner.lua" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### lua(cmd)
Evaluates `cmd` as Lua input. This is the same as using `dofile`
or `load`, but is appropriated for the runner interface.
#### Parameters
`string` **`cmd`**
</div>
<hr>
<div id='runner.sh'>
<h4 class='heading'>
hilbish.runner.sh(cmd)
<a href="#runner.sh" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### sh(cmd)
Runs a command in Hilbish's shell script interpreter.
This is the equivalent of using `source`.
#### Parameters
`string` **`cmd`**
</div>

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.timers
title: Interface hilbish.timers
description: timeout and interval API
layout: doc
menu:
@ -14,10 +14,14 @@ a few seconds, you don't have to rely on timing tricks, as Hilbish has a
timer API to set intervals and timeouts.
These are the simple functions `hilbish.interval` and `hilbish.timeout` (doc
accessible with `doc hilbish`, or `Module hilbish` on the Website).
accessible with `doc hilbish`). But if you want slightly more control over
them, there is the `hilbish.timers` interface. It allows you to get
a timer via ID and control them.
All functions documented with the `Timer` type refer to a Timer object.
An example of usage:
```lua
```
local t = hilbish.timers.create(hilbish.timers.TIMEOUT, 5000, function()
print 'hello!'
end)
@ -26,70 +30,25 @@ t:start()
print(t.running) // true
```
## Interface fields
- `INTERVAL`: Constant for an interval timer type
- `TIMEOUT`: Constant for a timeout timer type
## Functions
|||
|----|----|
|<a href="#timers.create">create(type, time, callback) -> @Timer</a>|Creates a timer that runs based on the specified `time`.|
|<a href="#timers.get">get(id) -> @Timer</a>|Retrieves a timer via its ID.|
## Static module fields
|||
|----|----|
|INTERVAL|Constant for an interval timer type|
|TIMEOUT|Constant for a timeout timer type|
<hr>
<div id='timers.create'>
<h4 class='heading'>
hilbish.timers.create(type, time, callback) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;" id="lol">Timer</a>
<a href="#timers.create" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Creates a timer that runs based on the specified `time`.
#### Parameters
`number` **`type`**
What kind of timer to create, can either be `hilbish.timers.INTERVAL` or `hilbish.timers.TIMEOUT`
`number` **`time`**
The amount of time the function should run in milliseconds.
`function` **`callback`**
The function to run for the timer.
</div>
<hr>
<div id='timers.get'>
<h4 class='heading'>
hilbish.timers.get(id) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;" id="lol">Timer</a>
<a href="#timers.get" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### create(type, time, callback) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;">Timer</a>
Creates a timer that runs based on the specified `time` in milliseconds.
The `type` can either be `hilbish.timers.INTERVAL` or `hilbish.timers.TIMEOUT`
### get(id) -> <a href="/Hilbish/docs/api/hilbish/hilbish.timers/#timer" style="text-decoration: none;">Timer</a>
Retrieves a timer via its ID.
#### Parameters
`number` **`id`**
</div>
## Types
<hr>
## Timer
The Job type describes a Hilbish timer.
## Object properties
|||
|----|----|
|type|What type of timer it is|
|running|If the timer is running|
|duration|The duration in milliseconds that the timer will run|
### Properties
- `type`: What type of timer it is
- `running`: If the timer is running
- `duration`: The duration in milliseconds that the timer will run
### Methods
#### start()

View File

@ -1,5 +1,5 @@
---
title: Module hilbish.userDir
title: Interface hilbish.userDir
description: user-related directories
layout: doc
menu:
@ -12,9 +12,7 @@ This interface just contains properties to know about certain user directories.
It is equivalent to XDG on Linux and gets the user's preferred directories
for configs and data.
## Static module fields
|||
|----|----|
|config|The user's config directory|
|data|The user's directory for program data|
## Interface fields
- `config`: The user's config directory
- `data`: The user's directory for program data

View File

@ -11,71 +11,16 @@ menu:
The terminal library is a simple and lower level library for certain terminal interactions.
## Functions
|||
|----|----|
|<a href="#restoreState">restoreState()</a>|Restores the last saved state of the terminal|
|<a href="#saveState">saveState()</a>|Saves the current state of the terminal.|
|<a href="#setRaw">setRaw()</a>|Puts the terminal into raw mode.|
|<a href="#size">size()</a>|Gets the dimensions of the terminal. Returns a table with `width` and `height`|
<hr>
<div id='restoreState'>
<h4 class='heading'>
terminal.restoreState()
<a href="#restoreState" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### restoreState()
Restores the last saved state of the terminal
#### Parameters
This function has no parameters.
</div>
### saveState()
Saves the current state of the terminal
<hr>
<div id='saveState'>
<h4 class='heading'>
terminal.saveState()
<a href="#saveState" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Saves the current state of the terminal.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='setRaw'>
<h4 class='heading'>
terminal.setRaw()
<a href="#setRaw" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Puts the terminal into raw mode.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='size'>
<h4 class='heading'>
terminal.size()
<a href="#size" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
### setRaw()
Puts the terminal in raw mode
### size()
Gets the dimensions of the terminal. Returns a table with `width` and `height`
NOTE: The size refers to the amount of columns and rows of text that can fit in the terminal.
#### Parameters
This function has no parameters.
</div>
Note: this is not the size in relation to the dimensions of the display

View File

@ -1,78 +1,56 @@
---
title: Completions
description: Tab completion for commands.
layout: doc
menu:
docs:
parent: "Features"
---
Hilbish has a pretty good completion system. It has a nice looking
menu, with 2 types of menus: grid (like file completions) or
list.
Completions for commands can be created with the [`hilbish.complete`](../api/hilbish#complete)
function. See the link for how to use it.
To create completions for a command is simple.
The callback will be passed 3 parameters:
- `query` (string): The text that the user is currently trying to complete.
This should be used to match entries.
- `ctx` (string): Contains the entire line. Use this if
more text is needed to be parsed for context.
- `fields` (string): The `ctx` split up by spaces.
In most cases, the completer just uses `fields` to check the amount
and `query` on what to match entries on.
In order to return your results, it has to go within a "completion group."
Then you return a table of completion groups and a prefix. The prefix will
usually just be the `query`.
Hilbish allows one to mix completion menus of different types, so
a grid menu and a list menu can be used and complete and display at the same time.
A completion group is a table with these keys:
- `type` (string): type of completion menu, either `grid` or `list`.
- `items` (table): a list of items.
The requirements of the `items` table is different based on the
`type`. If it is a `grid`, it can simply be a table of strings.
Otherwise if it is a `list` then each entry can
either be a string or a table.
Example:
```lua
local cg = {
items = {
'list item 1',
['--command-flag-here'] = {'this does a thing', '--the-flag-alias'}
},
type = 'list'
}
local cg2 = {
items = {'just', 'a bunch', 'of items', 'here', 'hehe'},
type = 'grid'
}
return {cg, cg2}, prefix
```
Which looks like this:
{{< video src="https://safe.saya.moe/t4CiLK6dgPbD.mp4" >}}
# Completion Handler
Like most parts of Hilbish, it's made to be extensible and
customizable. The default handler for completions in general can
be overwritten to provide more advanced completions if needed.
This usually doesn't need to be done though, unless you know
what you're doing.
The default completion handler provides 3 things:
# Completion Handler
By default, it provides 3 things: for the first argument,
binaries (with a plain name requested to complete, those in
$PATH), files, or command completions. It will try to run a handler
for the command or fallback to file completions.
$PATH), files, or command completions. With the default
completion handler, it will try to run a handler for the
command or fallback to file completions.
To overwrite it, just assign a function to `hilbish.completion.handler` like so:
```lua
-- line is the entire line as a string
-- pos is the position of the cursor.
To overwrite it, just assign a function to
`hilbish.completion.handler` like so:
function hilbish.completion.handler(line, pos)
-- do things
end
```
It is passed 2 arguments, the entire line, and the current
cursor position. The functions in the completion interface
take 3 arguments: query, ctx, and fields.
- The `query`, which what the user is currently trying to complete
- `ctx`, being just the entire line
- `fields` being a table of arguments. It's just `ctx` split up,
delimited by spaces.
It's expected to return 2 things: a table of completion groups, and
a prefix. A completion group is defined as a table with 2 keys:
`items` and `type`.
- The `items` field is just a table of items to use for completions.
- The `type` is for the completion menu type, being either `grid` or
`list`.
The prefix is what all the completions start with. It should be empty
if the user doesn't have a query. If the beginning of the completion
item does not match the prefix, it will be replaced and fixed
properly in the line. It is case sensitive.
If you want to overwrite the functionality of the general completion
handler, or make your command completion have files as well
(and filter them), then there is the `files` function, which is
mentioned below.
# Completion Interface
## Functions
- `files(query, ctx, fields)` -> table, prefix: get file completions,
based on the user's query.
- `bins(query, ctx, fields)` -> table, prefix: get binary/executable
completions, based on user query.
- `call(scope, query, ctx, fields)` -> table, prefix: call a completion
handler with `scope`, usually being in the form of `command.<name>`

View File

@ -1,78 +0,0 @@
---
title: Options
description: Simple customizable options.
layout: doc
menu:
docs:
parent: "Features"
---
Opts are simple toggle or value options a user can set in Hilbish.
As toggles, there are things like `autocd` or history saving. As values,
there is the `motd` which the user can either change to a custom string or disable.
Opts are accessed from the `hilbish.opts` table. Here they can either
be read or modified
### `autocd`
#### Value: `boolean`
#### Default: `false`
The autocd opt makes it so that lone directories attempted to be executed are
instead set as the shell's directory.
Example:
```
~/Directory
∆ ~
~
∆ Downloads
~/Downloads
∆ ../Documents
~/Documents
```
<hr>
### `history`
#### Value: `boolean`
#### Default: `true`
Sets whether command history will be saved or not.
<hr>
### `greeting`
#### Value: `boolean` or `string`
The greeting is the message that Hilbish shows on startup
(the one which says Welcome to Hilbish).
This can be set to either true/false to enable/disable or a custom greeting string.
<hr>
### `motd`
#### Value: `boolean`
#### Default: `true`
The message of the day shows the current major.minor version and
includes a small range of things added in the current release.
This can be set to `false` to disable the message.
<hr>
### `fuzzy`
#### Value: `boolean`
#### Default: `false`
Toggles the functionality of fuzzy history searching, usable
via the menu in Ctrl-R. Fuzzy searching is an approximate searching
method, which means results that match *closest* will be shown instead
of an exact match.
<hr>
### `notifyJobFinish`
#### Value: `boolean`
#### Default: `true`
If this is enabled, when a background job is finished,
a [notification](../notifications) will be sent.

View File

@ -1,11 +1,13 @@
---
title: Signals
description:
layout: doc
weight: -50
menu:
docs
---
Here is a list of bait hooks that are thrown by Hilbish. If a hook is related
to a command, it will have the `command` scope, as example.
Signals are global events emitted with the [Bait](../api/bait) module.
For more detail on how to use these signals, you may check the Bait page.
Here is the format for a doc for a hook:
+ <hook name> -> <args> > <description>
`<args>` just means the arguments of the hook. If a hook doc has the format
of `arg...`, it means the hook can take/recieve any number of `arg`.
+ error -> eventName, handler, err > Emitted when there is an error in
an event handler. The `eventName` is the name of the event the handler
is for, the `handler` is the callback function, and `err` is the error
message.

View File

@ -1,67 +1,12 @@
---
title: Command
description:
layout: doc
menu:
docs:
parent: "Signals"
---
+ `command.preexec` -> input, cmdStr > Thrown before a command
is executed. The `input` is the user written command, while `cmdStr`
is what will be executed (`input` will have aliases while `cmdStr`
will have alias resolved input).
## command.preexec
Thrown right before a command is executed.
+ `command.exit` -> code, cmdStr > Thrown when a command exits.
`code` is the exit code of the command, and `cmdStr` is the command that was run.
#### Variables
`string` **`input`**
The raw string that the user typed. This will include the text
without changes applied to it (argument substitution, alias expansion,
etc.)
+ `command.not-found` -> cmdStr > Thrown when a command is not found.
`string` **`cmdStr`**
The command that will be directly executed by the current runner.
<hr>
## command.exit
Thrown after the user's ran command is finished.
#### Variables
`number` **`code`**
The exit code of what was executed.
`string` **`cmdStr`**
The command or code that was executed
<hr>
## command.not-found
Thrown if the command attempted to execute was not found.
This can be used to customize the text printed when a command is not found.
Example:
```lua
local bait = require 'bait'
-- Remove any present handlers on `command.not-found`
local notFoundHooks = bait.hooks 'command.not-found'
for _, hook in ipairs(notFoundHooks) do
bait.release('command.not-found', hook)
end
-- then assign custom
bait.catch('command.not-found', function(cmd)
print(string.format('The command "%s" was not found.', cmd))
end)
```
#### Variables
`string` **`cmdStr`**
The name of the command.
<hr>
## command.not-executable
Thrown when the user attempts to run a file that is not executable
(like a text file, or Unix binary without +x permission).
#### Variables
`string` **`cmdStr`**
The name of the command.
+ `command.not-executable` -> cmdStr > Thrown when Hilbish attempts to run a file
that is not executable.

View File

@ -1,47 +1,12 @@
---
title: Hilbish
description:
layout: doc
menu:
docs:
parent: "Signals"
---
+ `hilbish.exit` > Sent when Hilbish is about to exit.
## hilbish.exit
Sent when Hilbish is going to exit.
#### Variables
This signal returns no variables.
<hr>
## hilbish.vimMode
Sent when the Vim mode of Hilbish is changed (like from insert to normal mode).
This can be used to change the prompt and notify based on Vim mode.
#### Variables
`string` **`modeName`**
The mode that has been set.
Can be these values: `insert`, `normal`, `delete` or `replace`
<hr>
## hilbish.cancel
Sent when the user cancels their command input with Ctrl-C
#### Variables
This signal returns no variables.
<hr>
## hilbish.notification
Thrown when a [notification](../../features/notifications) is sent.
#### Variables
`table` **`notification`**
The notification. The properties are defined in the link above.
<hr>
+ `hilbish.vimMode` -> modeName > Sent when Hilbish's Vim mode is changed (example insert to normal mode),
`modeName` is the name of the mode changed to (can be `insert`, `normal`, `delete` or `replace`).
+ `hilbish.vimAction` -> actionName, args > Sent when the user does a "vim action," being something
like yanking or pasting text. See `doc vim-mode actions` for more info.
+ `hilbish.cancel` > Sent when the user cancels their input with Ctrl-C.
+ `hilbish.notification` -> message > Sent when a message is
sent.

View File

@ -1,40 +1,7 @@
---
title: Signal
description:
layout: doc
menu:
docs:
parent: "Signals"
---
+ `signal.sigint` > Sent when Hilbish receives SIGINT (on Ctrl-C).
## signal.sigint
Thrown when Hilbish receive the SIGINT signal,
aka when Ctrl-C is pressed.
+ `signal.resize` > Sent when the terminal is resized.
#### Variables
This signal returns no variables.
<hr>
## signal.resize
Thrown when the terminal is resized.
#### Variables
This signal returns no variables.
<hr>
## signal.sigusr1
Thrown when SIGUSR1 is sent to Hilbish.
#### Variables
This signal returns no variables.
<hr>
## signal.sigusr2
Thrown when SIGUSR2 is sent to Hilbish.
#### Variables
This signal returns no variables.
+ `signal.sigusr1`
+ `signal.sigusr2`

View File

@ -1,5 +1,3 @@
(This has mainly been replaced by [hilbish.jobs](../api/hilbish.jobs)).
Hilbish has pretty standard job control. It's missing one or two things,
but works well. One thing which is different from other shells
(besides Hilbish) itself is the API for jobs, and of course it's in Lua.

View File

@ -1,10 +1,3 @@
---
title: Lunacolors
layout: doc
weight: -60
menu: docs
---
Lunacolors is an ANSI color/styling library for Lua. It is included
by default in standard Hilbish distributions to provide easy styling
for things like prompts and text.

View File

@ -1,17 +1,10 @@
---
title: Nature
layout: doc
weight: -90
menu: docs
---
A bit after creation, we have the outside nature. Little plants, seeds,
growing to their final phase: a full plant. A lot of Hilbish itself is
written in Go, but there are parts made in Lua, being most builtins
(`doc`, `cd`, cdr), completions, and other things.
Hilbish's Lua core module is called `nature`.
It runs after Hilbish's Go core does.
Hilbish's Lua core module is called `nature`. It's handled after everything
on the Go side initializes, which is what that first sentence was from.
# Nature Modules
Currently, `nature` provides 1 intended public module: `nature.dirs`.

View File

@ -1,79 +0,0 @@
---
title: Module dirs
description: No description.
layout: doc
menu:
docs:
parent: "Nature"
---
<hr>
<div id='setOld'>
<h4 class='heading'>
dirs.setOld(d)
<a href="#setOld" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Sets the old directory string.
#### Parameters
`d` **`string`**
</div>
<hr>
<div id='push'>
<h4 class='heading'>
dirs.push()
<a href="#push" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Add `d` to the recent directories list.
#### Parameters
This function has no parameters.
</div>
<hr>
<div id='peak'>
<h4 class='heading'>
dirs.peak(num)
<a href="#peak" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Look at `num` amount of recent directories, starting from the latest.
#### Parameters
`num` **`number`**
</div>
<hr>
<div id='pop'>
<h4 class='heading'>
dirs.pop(num)
<a href="#pop" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Remove the specified amount of dirs from the recent directories list.
#### Parameters
`num` **`number`**
</div>
<hr>
<div id='recent'>
<h4 class='heading'>
dirs.recent(idx)
<a href="#recent" class='heading-link'>
<i class="fas fa-paperclip"></i>
</a>
</h4>
Get entry from recent directories list based on index.
#### Parameters
`idx` **`number`**
</div>

View File

@ -1,24 +1,7 @@
---
title: Runner Mode
description: Customize the interactive script/command runner.
layout: doc
menu:
docs:
parent: "Features"
---
Hilbish allows you to change how interactive text can be interpreted.
This is mainly due to the fact that the default method Hilbish uses
is that it runs Lua first and then falls back to shell script.
In some cases, someone might want to switch to just shell script to avoid
it while interactive but still have a Lua config, or go full Lua to use
Hilbish as a REPL. This also allows users to add alternative languages like
Fennel as the interactive script runner.
Runner mode can also be used to handle specific kinds of input before
evaluating like normal, which is how [Link.hsh](https://github.com/TorchedSammy/Link.hsh)
handles links.
Hilbish is *unique,* when interactive it first attempts to run input as
Lua and then tries shell script. But if you're normal, you wouldn't
really be using Hilbish anyway but you'd also not want this
(or maybe want Lua only in some cases.)
The "runner mode" of Hilbish is customizable via `hilbish.runnerMode`,
which determines how Hilbish will run user input. By default, this is
@ -28,23 +11,28 @@ set it to `hybridRev` and for isolated modes there is `sh` and `lua`
respectively.
You can also set it to a function, which will be called everytime Hilbish
needs to run interactive input. For more detail, see the [API documentation](../../api/hilbish/hilbish.runner)
needs to run interactive input. For example, you can set this to a simple
function to compile and evaluate Fennel, and now you can run Fennel.
You can even mix it with sh to make a hybrid mode with Lua replaced by
Fennel.
An example:
hilbish.runnerMode(function(input)
local ok = pcall(fennel.eval, input)
if ok then
return input, 0, nil
end
return hilbish.runner.sh(input)
end)
The `hilbish.runner` interface is an alternative to using `hilbish.runnerMode`
and also provides the shell script and Lua runner functions that Hilbish itself uses.
A runner function is expected to return a table with the following values:
- `exitCode` (number): Exit code of the command
- `input` (string): The text input of the user. This is used by Hilbish to append extra input, in case
more is requested.
- `err` (string): A string that represents an error from the runner.
This should only be set when, for example, there is a syntax error.
It can be set to a few special values for Hilbish to throw the right
hooks and have a better looking message.
- `<command>: not-found` will throw a `command.not-found` hook
based on what `<command>` is.
- `<command>: not-executable` will throw a `command.not-executable` hook.
- `continue` (boolean): Whether Hilbish should prompt the user for no input
and also provides the sh and Lua runner functions that Hilbish itself uses.
A runner function is expected to return 3 values: the input, exit code, and an error.
The input return is there incase you need to prompt for more input.
If you don't, just return the input passed to the runner function.
The exit code has to be a number, it will be 0 otherwise and the error can be
`nil` to indicate no error.
## Functions
These are the "low level" functions for the `hilbish.runner` interface.
@ -53,6 +41,21 @@ These are the "low level" functions for the `hilbish.runner` interface.
+ sh(input) -> table > Runs `input` in Hilbish's sh interpreter
+ lua(input) -> table > Evals `input` as Lua code
The table value that runners return can have at least 4 values:
+ input (string): The full input text.
+ exitCode (number): Exit code (usually from a command)
+ continue (boolean): Whether to prompt the user for more input
(in the case of incomplete syntax)
+ err (string): A string that represents an error from the runner.
This should only be set when, for example, there is a syntax error.
It can be set to a few special values for Hilbish to throw the right
hooks and have a better looking message.
+ `<command>: not-found` will throw a `command.not-found` hook
based on what `<command>` is.
+ `<command>: not-executable` will throw a `command.not-executable` hook.
The others here are defined in Lua and have EmmyLua documentation.
These functions should be preferred over the previous ones.
+ setCurrent(mode) > The same as `setMode`, but works with runners managed
via the functions below.

View File

@ -1,10 +1,3 @@
---
title: Vim Mode
layout: doc
weight: -90
menu: docs
---
Hilbish has a Vim binding input mode accessible for use.
It can be enabled with the `hilbish.inputMode` function (check `doc hilbish`).

View File

@ -1,12 +1,3 @@
---
title: Actions
layout: doc
weight: -80
menu:
docs:
parent: "Vim Mode"
---
Vim actions are essentially just when a user uses a Vim keybind.
Things like yanking and pasting are Vim actions.
This is not an "offical Vim thing," just a Hilbish thing.

View File

@ -27,8 +27,7 @@ func editorLoader(rtm *rt.Runtime) *rt.Table {
// #interface editor
// insert(text)
// Inserts text into the Hilbish command line.
// #param text string
// Inserts text into the line.
func editorInsert(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -47,8 +46,8 @@ func editorInsert(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface editor
// setVimRegister(register, text)
// Sets the vim register at `register` to hold the passed text.
// #aram register string
// #param text string
// --- @param register string
// --- @param text string
func editorSetRegister(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -72,7 +71,7 @@ func editorSetRegister(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface editor
// getVimRegister(register) -> string
// Returns the text that is at the register.
// #param register string
// --- @param register string
func editorGetRegister(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -91,7 +90,6 @@ func editorGetRegister(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface editor
// getLine() -> string
// Returns the current input line.
// #returns string
func editorGetLine(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
buf := lr.rl.GetLine()
@ -100,7 +98,8 @@ func editorGetLine(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface editor
// getChar() -> string
// Reads a keystroke from the user. This is in a format of something like Ctrl-L.
// Reads a keystroke from the user. This is in a format
// of something like Ctrl-L..
func editorReadChar(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
buf := lr.rl.ReadChar()

View File

@ -2,27 +2,31 @@
local bait = {}
--- Catches an event. This function can be used to act on events.
---
---
--- Catches a hook with `name`. Runs the `cb` when it is thrown
--- @param name string
--- @param cb function
function bait.catch(name, cb) end
--- Catches an event, but only once. This will remove the hook immediately after it runs for the first time.
--- Same as catch, but only runs the `cb` once and then removes the hook
--- @param name string
--- @param cb function
function bait.catchOnce(name, cb) end
--- Returns a table of functions that are hooked on an event with the corresponding `name`.
--- Returns a table with hooks (callback functions) on the event with `name`.
--- @param name string
--- @returns table<function>
function bait.hooks(name) end
--- Removes the `catcher` for the event with `name`.
--- For this to work, `catcher` has to be the same function used to catch
--- an event, like one saved to a variable.
---
---
--- @param name string
--- @param catcher function
function bait.release(name, catcher) end
--- Throws a hook with `name` with the provided `args`.
---
---
--- Throws a hook with `name` with the provided `args`
--- @param name string
--- @vararg any
function bait.throw(name, ...args) end
return bait

View File

@ -2,13 +2,13 @@
local commander = {}
--- Removes the named command. Note that this will only remove Commander-registered commands.
--- Deregisters any command registered with `name`
--- @param name string
function commander.deregister(name) end
--- Adds a new command with the given `name`. When Hilbish has to run a command with a name,
--- it will run the function providing the arguments and sinks.
---
---
--- Register a command with `name` that runs `cb` when ran
--- @param name string
--- @param cb function
function commander.register(name, cb) end
return commander

View File

@ -2,49 +2,56 @@
local fs = {}
--- Returns an absolute version of the `path`.
--- This can be used to resolve short paths like `..` to `/home/user`.
--- Gives an absolute version of `path`.
--- @param path string
--- @returns string
function fs.abs(path) end
--- Returns the "basename," or the last part of the provided `path`. If path is empty,
--- `.` will be returned.
--- Gives the basename of `path`. For the rules,
--- see Go's filepath.Base
--- @returns string
function fs.basename(path) end
--- Changes Hilbish's directory to `dir`.
--- Changes directory to `dir`
--- @param dir string
function fs.cd(dir) end
--- Returns the directory part of `path`. If a file path like
--- `~/Documents/doc.txt` then this function will return `~/Documents`.
--- Returns the directory part of `path`. For the rules, see Go's
--- filepath.Dir
--- @param path string
--- @returns string
function fs.dir(path) end
--- Match all files based on the provided `pattern`.
--- For the syntax' refer to Go's filepath.Match function: https://pkg.go.dev/path/filepath#Match
---
---
--- Glob all files and directories that match the pattern.
--- For the rules, see Go's filepath.Glob
--- @param pattern string
--- @returns table
function fs.glob(pattern) end
--- Takes any list of paths and joins them based on the operating system's path separator.
---
---
function fs.join(...path) end
--- Takes paths and joins them together with the OS's
--- directory separator (forward or backward slash).
--- @vararg string
--- @returns string
function fs.join(...) end
--- Creates a new directory with the provided `name`.
--- With `recursive`, mkdir will create parent directories.
---
---
--- Makes a directory called `name`. If `recursive` is true, it will create its parent directories.
--- @param name string
--- @param recursive boolean
function fs.mkdir(name, recursive) end
--- Returns a list of all files and directories in the provided path.
function fs.readdir(path) end
--- Returns a table of files in `dir`.
--- @param dir string
--- @return table
function fs.readdir(dir) end
--- Returns the information about a given `path`.
--- The returned table contains the following values:
--- Returns a table of info about the `path`.
--- It contains the following keys:
--- name (string) - Name of the path
--- size (number) - Size of the path in bytes
--- mode (string) - Unix permission mode in an octal format string (with leading 0)
--- size (number) - Size of the path
--- mode (string) - Permission mode in an octal format string (with leading 0)
--- isDir (boolean) - If the path is a directory
---
---
--- @param path string
--- @returns table
function fs.stat(path) end
return fs

View File

@ -2,92 +2,96 @@
local hilbish = {}
--- This is an alias (ha) for the [hilbish.alias](../#alias) function.
--- This is an alias (ha) for the `hilbish.alias` function.
--- @param alias string
--- @param cmd string
function hilbish.aliases.add(alias, cmd) end
--- This is the same as the `hilbish.runnerMode` function.
--- It takes a callback, which will be used to execute all interactive input.
--- This is the same as the `hilbish.runnerMode` function. It takes a callback,
--- which will be used to execute all interactive input.
--- In normal cases, neither callbacks should be overrided by the user,
--- as the higher level functions listed below this will handle it.
--- @param cb function
function hilbish.runner.setMode(cb) end
--- Calls a completer function. This is mainly used to call
--- a command completer, which will have a `name` in the form
--- of `command.name`, example: `command.git`.
--- You can check `doc completions` for info on the `completionGroups` return value.
--- @param name string
--- @param query string
--- @param ctx string
--- @param fields table
function hilbish.completion.call(name, query, ctx, fields) end
--- The handler function is the callback for tab completion in Hilbish.
--- You can check the completions doc for more info.
--- @param line string
--- @param pos string
function hilbish.completion.handler(line, pos) end
--- Returns the current input line.
function hilbish.editor.getLine() end
--- Returns the text that is at the register.
--- @param register string
function hilbish.editor.getVimRegister(register) end
--- Inserts text into the Hilbish command line.
--- Inserts text into the line.
function hilbish.editor.insert(text) end
--- Reads a keystroke from the user. This is in a format of something like Ctrl-L.
--- Reads a keystroke from the user. This is in a format
--- of something like Ctrl-L..
function hilbish.editor.getChar() end
--- Sets the vim register at `register` to hold the passed text.
--- @param register string
--- @param text string
function hilbish.editor.setVimRegister(register, text) end
--- Return binaries/executables based on the provided parameters.
--- This function is meant to be used as a helper in a command completion handler.
---
---
function hilbish.completion.bins(query, ctx, fields) end
--- Calls a completer function. This is mainly used to call a command completer, which will have a `name`
--- in the form of `command.name`, example: `command.git`.
--- You can check the Completions doc or `doc completions` for info on the `completionGroups` return value.
function hilbish.completion.call(name, query, ctx, fields) end
--- Returns file matches based on the provided parameters.
--- This function is meant to be used as a helper in a command completion handler.
function hilbish.completion.files(query, ctx, fields) end
--- This function contains the general completion handler for Hilbish. This function handles
--- completion of everything, which includes calling other command handlers, binaries, and files.
--- This function can be overriden to supply a custom handler. Note that alias resolution is required to be done in this function.
---
---
function hilbish.completion.handler(line, pos) end
--- Sets an alias, with a name of `cmd` to another command.
---
---
--- Sets an alias of `cmd` to `orig`
--- @param cmd string
--- @param orig string
function hilbish.alias(cmd, orig) end
--- Appends the provided dir to the command path (`$PATH`)
---
---
--- Appends `dir` to $PATH
--- @param dir string|table
function hilbish.appendPath(dir) end
--- Registers a completion handler for the specified scope.
--- A `scope` is expected to be `command.<cmd>`,
--- Registers a completion handler for `scope`.
--- A `scope` is currently only expected to be `command.<cmd>`,
--- replacing <cmd> with the name of the command (for example `command.git`).
--- The documentation for completions, under Features/Completions or `doc completions`
--- provides more details.
---
---
--- `cb` must be a function that returns a table of "completion groups."
--- Check `doc completions` for more information.
--- @param scope string
--- @param cb function
function hilbish.complete(scope, cb) end
--- Returns the current directory of the shell.
--- Returns the current directory of the shell
--- @returns string
function hilbish.cwd() end
--- Replaces the currently running Hilbish instance with the supplied command.
--- This can be used to do an in-place restart.
--- Replaces running hilbish with `cmd`
--- @param cmd string
function hilbish.exec(cmd) end
--- Puts `fn` in a Goroutine.
--- This can be used to run any function in another thread at the same time as other Lua code.
--- **NOTE: THIS FUNCTION MAY CRASH HILBISH IF OUTSIDE VARIABLES ARE ACCESSED.**
--- **This is a limitation of the Lua runtime.**
--- Puts `fn` in a goroutine
--- @param fn function
function hilbish.goro(fn) end
--- Line highlighter handler.
--- This is mainly for syntax highlighting, but in reality could set the input
--- of the prompt to *display* anything. The callback is passed the current line
--- and is expected to return a line that will be used as the input display.
--- Line highlighter handler. This is mainly for syntax highlighting, but in
--- reality could set the input of the prompt to *display* anything. The
--- callback is passed the current line and is expected to return a line that
--- will be used as the input display.
--- Note that to set a highlighter, one has to override this function.
---
--- Example:
--- ```
--- function hilbish.highlighter(line)
--- return line:gsub('"%w+"', function(c) return lunacolors.green(c) end)
--- end
--- ```
--- This code will highlight all double quoted strings in green.
--- @param line string
function hilbish.highlighter(line) end
--- The command line hint handler. It gets called on every key insert to
@ -95,71 +99,97 @@ function hilbish.highlighter(line) end
--- line and cursor position. It is expected to return a string which is used
--- as the text for the hint. This is by default a shim. To set hints,
--- override this function with your custom handler.
---
---
--- @param line string
--- @param pos number
function hilbish.hinter(line, pos) end
--- Sets the input mode for Hilbish's line reader.
--- `emacs` is the default. Setting it to `vim` changes behavior of input to be
--- Vim-like with modes and Vim keybinds.
--- Sets the input mode for Hilbish's line reader. Accepts either emacs or vim
--- @param mode string
function hilbish.inputMode(mode) end
--- Runs the `cb` function every specified amount of `time`.
--- This creates a timer that ticking immediately.
--- Runs the `cb` function every `time` milliseconds.
--- This creates a timer that starts immediately.
--- @param cb function
--- @param time number
--- @return Timer
function hilbish.interval(cb, time) end
--- Changes the text prompt when Hilbish asks for more input.
--- This will show up when text is incomplete, like a missing quote
---
---
--- Changes the continued line prompt to `str`
--- @param str string
function hilbish.multiprompt(str) end
--- Prepends `dir` to $PATH.
--- Prepends `dir` to $PATH
--- @param dir string
function hilbish.prependPath(dir) end
--- Changes the shell prompt to the provided string.
--- Changes the shell prompt to `str`
--- There are a few verbs that can be used in the prompt text.
--- These will be formatted and replaced with the appropriate values.
--- `%d` - Current working directory
--- `%u` - Name of current user
--- `%h` - Hostname of device
---
--- @param str string
--- @param typ? string Type of prompt, being left or right. Left by default.
function hilbish.prompt(str, typ) end
--- Read input from the user, using Hilbish's line editor/input reader.
--- This is a separate instance from the one Hilbish actually uses.
--- Returns `input`, will be nil if Ctrl-D is pressed, or an error occurs.
--- Returns `input`, will be nil if ctrl + d is pressed, or an error occurs (which shouldn't happen)
--- @param prompt? string
--- @returns string|nil
function hilbish.read(prompt) end
--- Runs `cmd` in Hilbish's shell script interpreter.
--- Runs `cmd` in Hilbish's sh interpreter.
--- If returnOut is true, the outputs of `cmd` will be returned as the 2nd and
--- 3rd values instead of being outputted to the terminal.
--- @param cmd string
--- @param returnOut boolean
--- @returns number, string, string
function hilbish.run(cmd, returnOut) end
--- Sets the execution/runner mode for interactive Hilbish.
--- This determines whether Hilbish wll try to run input as Lua
--- and/or sh or only do one of either.
--- Sets the execution/runner mode for interactive Hilbish. This determines whether
--- Hilbish wll try to run input as Lua and/or sh or only do one of either.
--- Accepted values for mode are hybrid (the default), hybridRev (sh first then Lua),
--- sh, and lua. It also accepts a function, to which if it is passed one
--- will call it to execute user input instead.
--- Read [about runner mode](../features/runner-mode) for more information.
--- @param mode string|function
function hilbish.runnerMode(mode) end
--- Executed the `cb` function after a period of `time`.
--- This creates a Timer that starts ticking immediately.
--- Runs the `cb` function after `time` in milliseconds.
--- This creates a timer that starts immediately.
--- @param cb function
--- @param time number
--- @returns Timer
function hilbish.timeout(cb, time) end
--- Checks if `name` is a valid command.
--- Will return the path of the binary, or a basename if it's a commander.
--- @param name string
--- @returns string
function hilbish.which(name) end
--- Puts a job in the background. This acts the same as initially running a job.
function hilbish.jobs:background() end
--- Returns binary/executale completion candidates based on the provided query.
--- @param query string
--- @param ctx string
--- @param fields table
function hilbish.completion.bins(query, ctx, fields) end
--- Returns file completion candidates based on the provided query.
--- @param query string
--- @param ctx string
--- @param fields table
function hilbish.completion.files(query, ctx, fields) end
--- Puts a job in the foreground. This will cause it to run like it was
--- executed normally and wait for it to complete.
function hilbish.jobs:foreground() end
--- Evaluates `cmd` as Lua input. This is the same as using `dofile`
--- or `load`, but is appropriated for the runner interface.
--- @param cmd string
function hilbish.runner.lua(cmd) end
--- Sets/toggles the option of automatically flushing output.
@ -196,6 +226,7 @@ function hilbish.module.load(path) end
--- Runs a command in Hilbish's shell script interpreter.
--- This is the equivalent of using `source`.
--- @param cmd string
function hilbish.runner.sh(cmd) end
--- Starts a timer.
@ -205,26 +236,30 @@ function hilbish.timers:start() end
function hilbish.timers:stop() end
--- Removes an alias.
--- @param name string
function hilbish.aliases.delete(name) end
--- Get a table of all aliases, with string keys as the alias and the value as the command.
---
---
--- @returns table<string, string>
function hilbish.aliases.list() end
--- Resolves an alias to its original command. Will thrown an error if the alias doesn't exist.
--- Tries to resolve an alias to its command.
--- @param alias string
--- @returns string
function hilbish.aliases.resolve(alias) end
--- Creates a new job. This function does not run the job. This function is intended to be
--- used by runners, but can also be used to create jobs via Lua. Commanders cannot be ran as jobs.
---
---
--- Adds a new job to the job table. Note that this does not immediately run it.
--- @param cmdstr string
--- @param args table
--- @param execPath string
function hilbish.jobs.add(cmdstr, args, execPath) end
--- Returns a table of all job objects.
--- @returns table<Job>
function hilbish.jobs.all() end
--- Disowns a job. This simply deletes it from the list of jobs without stopping it.
--- Disowns a job. This deletes it from the job table.
--- @param id number
function hilbish.jobs.disown(id) end
--- Get a job object via its ID.
@ -232,28 +267,39 @@ function hilbish.jobs.disown(id) end
--- @returns Job
function hilbish.jobs.get(id) end
--- Returns the last added job to the table.
--- Returns the last added job from the table.
--- @returns Job
function hilbish.jobs.last() end
--- Adds a command to the history.
--- @param cmd string
function hilbish.history.add(cmd) end
--- Retrieves all history as a table.
--- Retrieves all history.
--- @returns table
function hilbish.history.all() end
--- Deletes all commands from the history.
function hilbish.history.clear() end
--- Retrieves a command from the history based on the `index`.
function hilbish.history.get(index) end
--- Retrieves a command from the history based on the `idx`.
--- @param idx number
function hilbish.history.get(idx) end
--- Returns the amount of commands in the history.
--- @returns number
function hilbish.history.size() end
--- Creates a timer that runs based on the specified `time`.
--- Creates a timer that runs based on the specified `time` in milliseconds.
--- The `type` can either be `hilbish.timers.INTERVAL` or `hilbish.timers.TIMEOUT`
--- @param type number
--- @param time number
--- @param callback function
function hilbish.timers.create(type, time, callback) end
--- Retrieves a timer via its ID.
--- @param id number
--- @returns Timer
function hilbish.timers.get(id) end
return hilbish

View File

@ -5,14 +5,14 @@ local terminal = {}
--- Restores the last saved state of the terminal
function terminal.restoreState() end
--- Saves the current state of the terminal.
--- Saves the current state of the terminal
function terminal.saveState() end
--- Puts the terminal into raw mode.
--- Puts the terminal in raw mode
function terminal.setRaw() end
--- Gets the dimensions of the terminal. Returns a table with `width` and `height`
--- NOTE: The size refers to the amount of columns and rows of text that can fit in the terminal.
--- Note: this is not the size in relation to the dimensions of the display
function terminal.size() end
return terminal

1
go.mod
View File

@ -4,7 +4,6 @@ go 1.17
require (
github.com/arnodel/golua v0.0.0-20220221163911-dfcf252b6f86
github.com/atsushinee/go-markdown-generator v0.0.0-20191121114853-83f9e1f68504
github.com/blackfireio/osinfo v1.0.3
github.com/maxlandon/readline v0.1.0-beta.0.20211027085530-2b76cabb8036
github.com/pborman/getopt v1.1.0

2
go.sum
View File

@ -8,8 +8,6 @@ github.com/arnodel/edit v0.0.0-20220202110212-dfc8d7a13890/go.mod h1:AcpttpuZBaL
github.com/arnodel/strftime v0.1.6 h1:0hc0pUvk8KhEMXE+htyaOUV42zNcf/csIbjzEFCJqsw=
github.com/arnodel/strftime v0.1.6/go.mod h1:5NbK5XqYK8QpRZpqKNt4OlxLtIB8cotkLk4KTKzJfWs=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/atsushinee/go-markdown-generator v0.0.0-20191121114853-83f9e1f68504 h1:R1/AOzdMbopSliUTTEHvHbyNmnZ3YxY5GvdhTkpPsSY=
github.com/atsushinee/go-markdown-generator v0.0.0-20191121114853-83f9e1f68504/go.mod h1:kHBCvAXJIatTX1pw6tLiOspjGc3MhUDRlog9yrCUS+k=
github.com/blackfireio/osinfo v1.0.3 h1:Yk2t2GTPjBcESv6nDSWZKO87bGMQgO+Hi9OoXPpxX8c=
github.com/blackfireio/osinfo v1.0.3/go.mod h1:Pd987poVNmd5Wsx6PRPw4+w7kLlf9iJxoRKPtPAjOrA=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=

View File

@ -1,28 +1,9 @@
// the event emitter
/*
Bait is the event emitter for Hilbish. Much like Node.js and
its `events` system, many actions in Hilbish emit events.
Unlike Node.js, Hilbish events are global. So make sure to
pick a unique name!
Usage of the Bait module consists of userstanding
event-driven architecture, but it's pretty simple:
If you want to act on a certain event, you can `catch` it.
You can act on events via callback functions.
Examples of this are in the Hilbish default config!
Consider this part of it:
```lua
bait.catch('command.exit', function(code)
running = false
doPrompt(code ~= 0)
doNotifyPrompt()
end)
```
What this does is, whenever the `command.exit` event is thrown,
this function will set the user prompt.
*/
// Bait is the event emitter for Hilbish. Why name it bait? Why not.
// It throws hooks that you can catch. This is what you will use if
// you want to listen in on hooks to know when certain things have
// happened, like when you've changed directory, a command has failed,
// etc. To find all available hooks thrown by Hilbish, see doc hooks.
package bait
import (
@ -247,17 +228,31 @@ func handleHook(t *rt.Thread, c *rt.GoCont, name string, catcher *rt.Closure, ar
}
}
// throw(name, ...args)
// Throws a hook with `name` with the provided `args`
// --- @param name string
// --- @vararg any
func (b *Bait) bthrow(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
name, err := c.StringArg(0)
if err != nil {
return nil, err
}
ifaceSlice := make([]interface{}, len(c.Etc()))
for i, v := range c.Etc() {
ifaceSlice[i] = v
}
b.Emit(name, ifaceSlice...)
return c.Next(), nil
}
// catch(name, cb)
// Catches an event. This function can be used to act on events.
// #param name string The name of the hook.
// #param cb function The function that will be called when the hook is thrown.
/*
#example
bait.catch('hilbish.exit', function()
print 'Goodbye Hilbish!'
end)
#example
*/
// Catches a hook with `name`. Runs the `cb` when it is thrown
// --- @param name string
// --- @param cb function
func (b *Bait) bcatch(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
name, catcher, err := util.HandleStrCallback(t, c)
if err != nil {
@ -270,9 +265,9 @@ func (b *Bait) bcatch(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// catchOnce(name, cb)
// Catches an event, but only once. This will remove the hook immediately after it runs for the first time.
// #param name string The name of the event
// #param cb function The function that will be called when the event is thrown.
// Same as catch, but only runs the `cb` once and then removes the hook
// --- @param name string
// --- @param cb function
func (b *Bait) bcatchOnce(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
name, catcher, err := util.HandleStrCallback(t, c)
if err != nil {
@ -284,10 +279,27 @@ func (b *Bait) bcatchOnce(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.Next(), nil
}
// release(name, catcher)
// Removes the `catcher` for the event with `name`.
// For this to work, `catcher` has to be the same function used to catch
// an event, like one saved to a variable.
// --- @param name string
// --- @param catcher function
func (b *Bait) brelease(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
name, catcher, err := util.HandleStrCallback(t, c)
if err != nil {
return nil, err
}
b.OffLua(name, catcher)
return c.Next(), nil
}
// hooks(name) -> table
// Returns a table of functions that are hooked on an event with the corresponding `name`.
// #param name string The name of the hook
// #returns table<function>
// Returns a table with hooks (callback functions) on the event with `name`.
// --- @param name string
// --- @returns table<function>
func (b *Bait) bhooks(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -315,62 +327,3 @@ func (b *Bait) bhooks(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.PushingNext1(t.Runtime, rt.TableValue(luaHandlers)), nil
}
// release(name, catcher)
// Removes the `catcher` for the event with `name`.
// For this to work, `catcher` has to be the same function used to catch
// an event, like one saved to a variable.
// #param name string Name of the event the hook is on
// #param catcher function Hook function to remove
/*
#example
local hookCallback = function() print 'hi' end
bait.catch('event', hookCallback)
-- a little while later....
bait.release('event', hookCallback)
-- and now hookCallback will no longer be ran for the event.
#example
*/
func (b *Bait) brelease(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
name, catcher, err := util.HandleStrCallback(t, c)
if err != nil {
return nil, err
}
b.OffLua(name, catcher)
return c.Next(), nil
}
// throw(name, ...args)
// #param name string The name of the hook.
// #param args ...any The arguments to pass to the hook.
// Throws a hook with `name` with the provided `args`.
/*
#example
bait.throw('greeting', 'world')
-- This can then be listened to via
bait.catch('gretting', function(greetTo)
print('Hello ' .. greetTo)
end)
#example
*/
func (b *Bait) bthrow(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
name, err := c.StringArg(0)
if err != nil {
return nil, err
}
ifaceSlice := make([]interface{}, len(c.Etc()))
for i, v := range c.Etc() {
ifaceSlice[i] = v
}
b.Emit(name, ifaceSlice...)
return c.Next(), nil
}

View File

@ -1,9 +1,10 @@
// library for custom commands
/*
Commander is the library which handles Hilbish commands. This makes
the user able to add Lua-written commands to their shell without making
a separate script in a bin folder. Instead, you may simply use the Commander
library in your Hilbish config.
Commander is a library for writing custom commands in Lua.
In order to make it easier to write commands for Hilbish,
not require separate scripts and to be able to use in a config,
the Commander library exists. This is like a very simple wrapper
that works with Hilbish for writing commands. Example:
```lua
local commander = require 'commander'
@ -18,14 +19,14 @@ that will print `Hello world!` to output. One question you may
have is: What is the `sinks` parameter?
The `sinks` parameter is a table with 3 keys: `in`, `out`,
and `err`. All of them are a @Sink.
and `err`. The values of these is a @Sink.
- `in` is the standard input.
You may use the read functions on this sink to get input from the user.
- `out` is standard output.
This is usually where command output should go.
- `err` is standard error.
This sink is for writing errors, as the name would suggest.
- `in` is the standard input. You can read from this sink
to get user input. (**This is currently unimplemented.**)
- `out` is standard output. This is usually where text meant for
output should go.
- `err` is standard error. This sink is for writing errors, as the
name would suggest.
*/
package commander
@ -66,22 +67,9 @@ func (c *Commander) loaderFunc(rtm *rt.Runtime) (rt.Value, func()) {
}
// register(name, cb)
// Adds a new command with the given `name`. When Hilbish has to run a command with a name,
// it will run the function providing the arguments and sinks.
// #param name string Name of the command
// #param cb function Callback to handle command invocation
/*
#example
-- When you run the command `hello` in the shell, it will print `Hello world`.
-- If you run it with, for example, `hello Hilbish`, it will print 'Hello Hilbish'
commander.register('hello', function(args, sinks)
local name = 'world'
if #args > 0 then name = args[1] end
sinks.out:writeln('Hello ' .. name)
end)
#example
*/
// Register a command with `name` that runs `cb` when ran
// --- @param name string
// --- @param cb function
func (c *Commander) cregister(t *rt.Thread, ct *rt.GoCont) (rt.Cont, error) {
cmdName, cmd, err := util.HandleStrCallback(t, ct)
if err != nil {
@ -94,8 +82,8 @@ func (c *Commander) cregister(t *rt.Thread, ct *rt.GoCont) (rt.Cont, error) {
}
// deregister(name)
// Removes the named command. Note that this will only remove Commander-registered commands.
// #param name string Name of the command to remove.
// Deregisters any command registered with `name`
// --- @param name string
func (c *Commander) cderegister(t *rt.Thread, ct *rt.GoCont) (rt.Cont, error) {
if err := ct.Check1Arg(); err != nil {
return nil, err

View File

@ -1,10 +1,7 @@
// filesystem interaction and functionality library
/*
The fs module provides filesystem functions to Hilbish. While Lua's standard
library has some I/O functions, they're missing a lot of the basics. The `fs`
library offers more functions and will work on any operating system Hilbish does.
#field pathSep The operating system's path separator.
*/
// The fs module provides easy and simple access to filesystem functions
// and other things, and acts an addition to the Lua standard library's
// I/O and filesystem functions.
package fs
import (
@ -45,46 +42,9 @@ func loaderFunc(rtm *rt.Runtime) (rt.Value, func()) {
return rt.TableValue(mod), nil
}
// abs(path) -> string
// Returns an absolute version of the `path`.
// This can be used to resolve short paths like `..` to `/home/user`.
// #param path string
// #returns string
func fabs(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
path, err := c.StringArg(0)
if err != nil {
return nil, err
}
path = util.ExpandHome(path)
abspath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
return c.PushingNext1(t.Runtime, rt.StringValue(abspath)), nil
}
// basename(path) -> string
// Returns the "basename," or the last part of the provided `path`. If path is empty,
// `.` will be returned.
// #param path string Path to get the base name of.
// #returns string
func fbasename(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
path, err := c.StringArg(0)
if err != nil {
return nil, err
}
return c.PushingNext(t.Runtime, rt.StringValue(filepath.Base(path))), nil
}
// cd(dir)
// Changes Hilbish's directory to `dir`.
// #param dir string Path to change directory to.
// Changes directory to `dir`
// --- @param dir string
func fcd(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -103,103 +63,10 @@ func fcd(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.Next(), err
}
// dir(path) -> string
// Returns the directory part of `path`. If a file path like
// `~/Documents/doc.txt` then this function will return `~/Documents`.
// #param path string Path to get the directory for.
// #returns string
func fdir(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
path, err := c.StringArg(0)
if err != nil {
return nil, err
}
return c.PushingNext(t.Runtime, rt.StringValue(filepath.Dir(path))), nil
}
// glob(pattern) -> matches (table)
// Match all files based on the provided `pattern`.
// For the syntax' refer to Go's filepath.Match function: https://pkg.go.dev/path/filepath#Match
// #param pattern string Pattern to compare files with.
// #returns table A list of file names/paths that match.
/*
#example
--[[
Within a folder that contains the following files:
a.txt
init.lua
code.lua
doc.pdf
]]--
local matches = fs.glob './*.lua'
print(matches)
-- -> {'init.lua', 'code.lua'}
#example
*/
func fglob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
pattern, err := c.StringArg(0)
if err != nil {
return nil, err
}
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
luaMatches := rt.NewTable()
for i, match := range matches {
luaMatches.Set(rt.IntValue(int64(i + 1)), rt.StringValue(match))
}
return c.PushingNext(t.Runtime, rt.TableValue(luaMatches)), nil
}
// join(...path) -> string
// Takes any list of paths and joins them based on the operating system's path separator.
// #param path ...string Paths to join together
// #returns string The joined path.
/*
#example
-- This prints the directory for Hilbish's config!
print(fs.join(hilbish.userDir.config, 'hilbish'))
-- -> '/home/user/.config/hilbish' on Linux
#example
*/
func fjoin(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
strs := make([]string, len(c.Etc()))
for i, v := range c.Etc() {
if v.Type() != rt.StringType {
// +2; go indexes of 0 and first arg from above
return nil, fmt.Errorf("bad argument #%d to run (expected string, got %s)", i + 1, v.TypeName())
}
strs[i] = v.AsString()
}
res := filepath.Join(strs...)
return c.PushingNext(t.Runtime, rt.StringValue(res)), nil
}
// mkdir(name, recursive)
// Creates a new directory with the provided `name`.
// With `recursive`, mkdir will create parent directories.
// #param name string Name of the directory
// #param recursive boolean Whether to create parent directories for the provided name
/*
#example
-- This will create the directory foo, then create the directory bar in the
-- foo directory. If recursive is false in this case, it will fail.
fs.mkdir('./foo/bar', true)
#example
*/
// Makes a directory called `name`. If `recursive` is true, it will create its parent directories.
// --- @param name string
// --- @param recursive boolean
func fmkdir(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(2); err != nil {
return nil, err
@ -226,58 +93,15 @@ func fmkdir(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.Next(), err
}
// readdir(path) -> table[string]
// Returns a list of all files and directories in the provided path.
// #param dir string
// #returns table
func freaddir(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
dir, err := c.StringArg(0)
if err != nil {
return nil, err
}
dir = util.ExpandHome(dir)
names := rt.NewTable()
dirEntries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for i, entry := range dirEntries {
names.Set(rt.IntValue(int64(i + 1)), rt.StringValue(entry.Name()))
}
return c.PushingNext1(t.Runtime, rt.TableValue(names)), nil
}
// stat(path) -> {}
// Returns the information about a given `path`.
// The returned table contains the following values:
// Returns a table of info about the `path`.
// It contains the following keys:
// name (string) - Name of the path
// size (number) - Size of the path in bytes
// mode (string) - Unix permission mode in an octal format string (with leading 0)
// size (number) - Size of the path
// mode (string) - Permission mode in an octal format string (with leading 0)
// isDir (boolean) - If the path is a directory
// #param path string
// #returns table
/*
#example
local inspect = require 'inspect'
local stat = fs.stat '~'
print(inspect(stat))
--[[
Would print the following:
{
isDir = true,
mode = "0755",
name = "username",
size = 12288
}
]]--
#example
*/
// --- @param path string
// --- @returns table
func fstat(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -301,3 +125,128 @@ func fstat(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.PushingNext1(t.Runtime, rt.TableValue(statTbl)), nil
}
// readdir(dir) -> {}
// Returns a table of files in `dir`.
// --- @param dir string
// --- @return table
func freaddir(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
dir, err := c.StringArg(0)
if err != nil {
return nil, err
}
dir = util.ExpandHome(dir)
names := rt.NewTable()
dirEntries, err := os.ReadDir(dir)
if err != nil {
return nil, err
}
for i, entry := range dirEntries {
names.Set(rt.IntValue(int64(i + 1)), rt.StringValue(entry.Name()))
}
return c.PushingNext1(t.Runtime, rt.TableValue(names)), nil
}
// abs(path) -> string
// Gives an absolute version of `path`.
// --- @param path string
// --- @returns string
func fabs(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
path, err := c.StringArg(0)
if err != nil {
return nil, err
}
path = util.ExpandHome(path)
abspath, err := filepath.Abs(path)
if err != nil {
return nil, err
}
return c.PushingNext1(t.Runtime, rt.StringValue(abspath)), nil
}
// basename(path) -> string
// Gives the basename of `path`. For the rules,
// see Go's filepath.Base
// --- @returns string
func fbasename(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
path, err := c.StringArg(0)
if err != nil {
return nil, err
}
return c.PushingNext(t.Runtime, rt.StringValue(filepath.Base(path))), nil
}
// dir(path) -> string
// Returns the directory part of `path`. For the rules, see Go's
// filepath.Dir
// --- @param path string
// --- @returns string
func fdir(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
path, err := c.StringArg(0)
if err != nil {
return nil, err
}
return c.PushingNext(t.Runtime, rt.StringValue(filepath.Dir(path))), nil
}
// glob(pattern) -> matches (table)
// Glob all files and directories that match the pattern.
// For the rules, see Go's filepath.Glob
// --- @param pattern string
// --- @returns table
func fglob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
}
pattern, err := c.StringArg(0)
if err != nil {
return nil, err
}
matches, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
luaMatches := rt.NewTable()
for i, match := range matches {
luaMatches.Set(rt.IntValue(int64(i + 1)), rt.StringValue(match))
}
return c.PushingNext(t.Runtime, rt.TableValue(luaMatches)), nil
}
// join(...) -> string
// Takes paths and joins them together with the OS's
// directory separator (forward or backward slash).
// --- @vararg string
// --- @returns string
func fjoin(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
strs := make([]string, len(c.Etc()))
for i, v := range c.Etc() {
if v.Type() != rt.StringType {
// +2; go indexes of 0 and first arg from above
return nil, fmt.Errorf("bad argument #%d to run (expected string, got %s)", i + 1, v.TypeName())
}
strs[i] = v.AsString()
}
res := filepath.Join(strs...)
return c.PushingNext(t.Runtime, rt.StringValue(res)), nil
}

View File

@ -34,7 +34,7 @@ func loaderFunc(rtm *rt.Runtime) (rt.Value, func()) {
// size()
// Gets the dimensions of the terminal. Returns a table with `width` and `height`
// NOTE: The size refers to the amount of columns and rows of text that can fit in the terminal.
// Note: this is not the size in relation to the dimensions of the display
func termsize(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
w, h, err := term.GetSize(int(os.Stdin.Fd()))
if err != nil {
@ -49,7 +49,7 @@ func termsize(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// saveState()
// Saves the current state of the terminal.
// Saves the current state of the terminal
func termsaveState(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
state, err := term.GetState(int(os.Stdin.Fd()))
if err != nil {
@ -72,7 +72,7 @@ func termrestoreState(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// setRaw()
// Puts the terminal into raw mode.
// Puts the terminal in raw mode
func termsetRaw(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
_, err := term.MakeRaw(int(os.Stdin.Fd()))
if err != nil {

26
job.go
View File

@ -414,16 +414,10 @@ func (j *jobHandler) luaGetJob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface jobs
// add(cmdstr, args, execPath)
// Creates a new job. This function does not run the job. This function is intended to be
// used by runners, but can also be used to create jobs via Lua. Commanders cannot be ran as jobs.
// #param cmdstr string String that a user would write for the job
// #param args table Arguments for the commands. Has to include the name of the command.
// #param execPath string Binary to use to run the command. Needs to be an absolute path.
/*
#example
hilbish.jobs.add('go build', {'go', 'build'}, '/usr/bin/go')
#example
*/
// Adds a new job to the job table. Note that this does not immediately run it.
// --- @param cmdstr string
// --- @param args table
// --- @param execPath string
func (j *jobHandler) luaAddJob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(3); err != nil {
return nil, err
@ -454,9 +448,9 @@ func (j *jobHandler) luaAddJob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
}
// #interface jobs
// all() -> table[@Job]
// all() -> table<@Job>
// Returns a table of all job objects.
// #returns table[Job]
// --- @returns table<Job>
func (j *jobHandler) luaAllJobs(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
j.mu.RLock()
defer j.mu.RUnlock()
@ -471,8 +465,8 @@ func (j *jobHandler) luaAllJobs(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface jobs
// disown(id)
// Disowns a job. This simply deletes it from the list of jobs without stopping it.
// #param id number
// Disowns a job. This deletes it from the job table.
// --- @param id number
func (j *jobHandler) luaDisownJob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -492,8 +486,8 @@ func (j *jobHandler) luaDisownJob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface jobs
// last() -> @Job
// Returns the last added job to the table.
// #returns Job
// Returns the last added job from the table.
// --- @returns Job
func (j *jobHandler) luaLastJob(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
j.mu.RLock()
defer j.mu.RUnlock()

View File

@ -61,7 +61,6 @@ func moduleLoader(rtm *rt.Runtime) *rt.Table {
// load(path)
// Loads a module at the designated `path`.
// It will throw if any error occurs.
// #param path string
func moduleLoad(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(1); err != nil {
return nil, err

View File

@ -4,39 +4,6 @@ local fs = require 'fs'
local lunacolors = require 'lunacolors'
local Greenhouse = require 'nature.greenhouse'
local Page = require 'nature.greenhouse.page'
local docfuncs = require 'nature.doc'
local function strip(text, ...)
for _, pat in ipairs {...} do
text = text:gsub(pat, '\n')
end
return text
end
local function transformHTMLandMD(text)
return strip(text, '|||', '|%-%-%-%-|%-%-%-%-|')
:gsub('|(.-)|(.-)|', function(entry1, entry2)
return string.format('%s - %s', entry1, entry2)
end)
:gsub('<hr>', '{separator}')
:gsub('<.->', '')
--:gsub('^\n\n', '\n')
:gsub('\n%s+\n', '\n\n')
--:gsub(' \n', '\n\n')
:gsub('{{< (%w+) `(.-)` >}}', function(shortcode, text)
return docfuncs.renderInfoBlock(shortcode, text)
end)
:gsub('```(%w+)\n(.-)```', function(lang, text)
return docfuncs.renderCodeBlock(text)
end)
:gsub('```\n(.-)\n```', function(text)
return docfuncs.renderCodeBlock(text)
end)
:gsub('`[^\n].-`', lunacolors.cyan)
:gsub('#+ (.-\n)', function(heading) return lunacolors.blue(lunacolors.bold('' .. heading)) end)
:gsub('%*%*(.-)%*%*', lunacolors.bold)
end
commander.register('doc', function(args, sinks)
local moddocPath = hilbish.dataDir .. '/docs/'
@ -61,13 +28,10 @@ Available sections: ]] .. table.concat(modules, ', ')
local vals = {}
local docs = d
local valsStr = docs:match '^%-%-%-\n.-\n%-%-%-'
local valsStr = docs:match '%-%-%-\n([^%-%-%-]+)\n'
print(valsStr)
if valsStr then
docs = docs:sub(valsStr:len() + 2, #docs)
local pre = docs:sub(1, 1)
if pre == '\n' then
docs = docs:sub(2)
end
docs = docs:sub(valsStr:len() + 10, #docs)
-- parse vals
local lines = string.split(valsStr, '\n')
@ -125,7 +89,7 @@ Available sections: ]] .. table.concat(modules, ', ')
local size = terminal.size()
self.region = {
width = size.width,
height = size.height - 1
height = size.height - 3
}
end
gh:resize()
@ -137,13 +101,11 @@ Available sections: ]] .. table.concat(modules, ', ')
offset = self.specialOffset
workingPage = self.specialPage
end
local size = terminal.size()
self.sink:write(ansikit.getCSI(size.height - 1 .. ';1', 'H'))
self.sink:write(ansikit.getCSI(0, 'J'))
self.sink:write(ansikit.getCSI(self.region.height + 2 .. ';1', 'H'))
if not self.isSpecial then
if args[1] == 'api' then
self.sink:writeln(workingPage.title)
self.sink:writeln(lunacolors.reset(string.format('%s', workingPage.title)))
self.sink:write(lunacolors.format(string.format('{grayBg} ↳ {white}{italic}%s {reset}', workingPage.description or 'No description.')))
else
self.sink:write(lunacolors.reset(string.format('Viewing doc page %s', moddocPath)))
@ -152,19 +114,21 @@ Available sections: ]] .. table.concat(modules, ', ')
end
local backtickOccurence = 0
local function formatDocText(d)
return transformHTMLandMD(d)
--[[
return lunacolors.format(d:gsub('`(.-)`', function(t)
return docfuncs.renderCodeBlock(t)
return lunacolors.format(d:gsub('`', function()
backtickOccurence = backtickOccurence + 1
if backtickOccurence % 2 == 0 then
return '{reset}'
else
return '{underline}{green}'
end
end):gsub('\n#+.-\n', function(t)
local signature = t:gsub('<.->(.-)</.->', '{underline}%1'):gsub('\\', '<')
return '{bold}{yellow}' .. signature .. '{reset}'
end))
]]--
end
local doc, vals = handleYamlInfo(#args == 0 and doc or formatDocText(f:read '*a'))
local doc, vals = handleYamlInfo(#args == 0 and doc or formatDocText(f:read '*a':gsub('-([%d]+)', '%1')))
if #moddocs ~= 0 and f then
doc = doc .. '\nSubdocs: ' .. table.concat(subdocs, ', ') .. '\n\n'
end
@ -182,8 +146,8 @@ Available sections: ]] .. table.concat(modules, ', ')
end
local f = io.open(moddocPath .. sdFile, 'rb')
local doc, vals = handleYamlInfo(formatDocText(f:read '*a'))
local page = Page(vals.title or sdName, doc)
local doc, vals = handleYamlInfo(f:read '*a':gsub('-([%d]+)', '%1'))
local page = Page(vals.title, formatDocText(doc))
page.description = vals.description
gh:addPage(page)
end

View File

@ -1,4 +1,3 @@
-- @module dirs
local fs = require 'fs'
local dirs = {}
@ -12,8 +11,8 @@ dirs.recentDirs = {}
dirs.recentSize = 10
--- Get (and remove) a `num` of entries from recent directories.
-- @param num number
-- @param remove boolean Whether to remove items
--- @param num number
--- @param remove boolean Whether to remove items
function dirRecents(num, remove)
num = num or 1
local entries = {}
@ -35,12 +34,12 @@ function dirRecents(num, remove)
end
--- Look at `num` amount of recent directories, starting from the latest.
-- @param num? number
--- @param num? number
function dirs.peak(num)
return dirRecents(num)
end
--- Add `d` to the recent directories list.
--- Add `d` to the recent directories.
function dirs.push(d)
dirs.recentDirs[dirs.recentSize + 1] = nil
if dirs.recentDirs[#dirs.recentDirs - 1] ~= d then
@ -51,20 +50,20 @@ function dirs.push(d)
end
end
--- Remove the specified amount of dirs from the recent directories list.
-- @param num number
--- Remove `num` amount of dirs from the recent directories.
--- @param num number
function dirs.pop(num)
return dirRecents(num, true)
end
--- Get entry from recent directories list based on index.
-- @param idx number
--- Get entry from recent directories.
--- @param idx number
function dirs.recent(idx)
return dirs.recentDirs[idx]
end
--- Sets the old directory string.
-- @param d string
--- Sets the old directory.
--- @param d string
function dirs.setOld(d)
ok, d = pcall(fs.abs, d)
assert(ok, 'could not turn "' .. d .. '"into an absolute path')

View File

@ -1,47 +0,0 @@
local lunacolors = require 'lunacolors'
local M = {}
function M.highlight(text)
return text:gsub('\'.-\'', lunacolors.yellow)
--:gsub('%-%- .-', lunacolors.black)
end
function M.renderCodeBlock(text)
local longest = 0
local lines = string.split(text:gsub('\t', ' '), '\n')
for i, line in ipairs(lines) do
local len = line:len()
if len > longest then longest = len end
end
for i, line in ipairs(lines) do
lines[i] = ' ' .. M.highlight(line:sub(0, longest))
.. string.rep(' ', longest - line:len()) .. ' '
end
return '\n' .. lunacolors.format('{greyBg}' .. table.concat(lines, '\n')) .. '\n'
end
function M.renderInfoBlock(type, text)
local longest = 0
local lines = string.split(text:gsub('\t', ' '), '\n')
for i, line in ipairs(lines) do
local len = line:len()
if len > longest then longest = len end
end
for i, line in ipairs(lines) do
lines[i] = ' ' .. M.highlight(line:sub(0, longest))
.. string.rep(' ', longest - line:len()) .. ' '
end
local heading
if type == 'warning' then
heading = lunacolors.yellowBg(lunacolors.black(' ⚠ Warning '))
end
return '\n' .. heading .. '\n' .. lunacolors.format('{greyBg}' .. table.concat(lines, '\n')) .. '\n'
end
return M

View File

@ -18,20 +18,12 @@ function Greenhouse:new(sink)
self.contents = nil -- or can be a table
self.start = 1 -- where to start drawing from (should replace with self.region.y)
self.offset = 1 -- vertical text offset
self.horizOffset = 1
self.sink = sink
self.pages = {}
self.curPage = 1
self.step = {
horizontal = 5,
vertical = 1
}
self.separator = ''
self.keybinds = {
['Up'] = function(self) self:scroll 'up' end,
['Down'] = function(self) self:scroll 'down' end,
['Left'] = function(self) self:scroll 'left' end,
['Right'] = function(self) self:scroll 'right' end,
['Ctrl-Left'] = self.previous,
['Ctrl-Right'] = self.next,
['Ctrl-N'] = function(self) self:toc(true) end,
@ -40,9 +32,7 @@ function Greenhouse:new(sink)
self:jump(self.specialPageIdx)
self:special(false)
end
end,
['Page-Down'] = function(self) self:scroll('down', {page = true}) end,
['Page-Up'] = function(self) self:scroll('up', {page = true}) end
end
}
self.isSpecial = false
self.specialPage = nil
@ -61,7 +51,7 @@ function Greenhouse:updateCurrentPage(text)
page:setText(text)
end
function Greenhouse:sub(str, offset, limit)
local function sub(str, limit)
local overhead = 0
local function addOverhead(s)
overhead = overhead + string.len(s)
@ -73,8 +63,7 @@ function Greenhouse:sub(str, offset, limit)
:gsub('\x1b%[%d+;%d+%w', addOverhead)
:gsub('\x1b%[%d+%w', addOverhead)
return s:sub(offset, utf8.offset(str, limit + overhead) or limit + overhead)
--return s:sub(offset, limit + overhead)
return s:sub(0, limit + overhead)
end
function Greenhouse:draw()
@ -93,26 +82,21 @@ function Greenhouse:draw()
self.sink:write(ansikit.getCSI(self.start .. ';1', 'H'))
self.sink:write(ansikit.getCSI(2, 'J'))
local writer = self.sink.writeln
for i = offset, offset + self.region.height - 1 do
if i > #lines then break end
local writer = self.sink.writeln
if i == offset + self.region.height - 1 then writer = self.sink.write end
self.sink:write(ansikit.getCSI(self.start + i - offset .. ';1', 'H'))
local line = lines[i]:gsub('{separator}', function() return self.separator:rep(self.region.width - 1) end)
writer(self.sink, self:sub(line:gsub('\t', ' '), self.horizOffset, self.region.width))
writer(self.sink, sub(lines[i]:gsub('\t', ' '), self.region.width))
end
writer(self.sink, '\27[0m')
self:render()
end
function Greenhouse:render()
end
function Greenhouse:scroll(direction, opts)
opts = opts or {}
function Greenhouse:scroll(direction)
if self.isSpecial then
if direction == 'down' then
self:next(true)
@ -125,28 +109,13 @@ function Greenhouse:scroll(direction, opts)
local lines = self.pages[self.curPage].lines
local oldOffset = self.offset
local oldHorizOffset = self.horizOffset
local amount = self.step.vertical
if opts.page then
amount = self.region.height
end
if direction == 'down' then
self.offset = math.min(self.offset + amount, math.max(1, #lines - self.region.height))
self.offset = math.min(self.offset + 1, math.max(1, #lines - self.region.height))
elseif direction == 'up' then
self.offset = math.max(self.offset - amount, 1)
self.offset = math.max(self.offset - 1, 1)
end
--[[
if direction == 'left' then
self.horizOffset = math.max(self.horizOffset - self.step.horizontal, 1)
elseif direction == 'right' then
self.horizOffset = self.horizOffset + self.step.horizontal
end
]]--
if self.offset ~= oldOffset then self:draw() end
if self.horizOffset ~= oldHorizOffset then self:draw() end
end
function Greenhouse:update()
@ -293,11 +262,9 @@ function Greenhouse:initUi()
ansikit.clear(true)
self:draw()
hilbish.goro(function()
while not done do
local c = read()
self:keybind('Ctrl-Q', function()
done = true
end)
self:keybind('Ctrl-D', function()
done = true
end)
@ -307,8 +274,44 @@ function Greenhouse:initUi()
else
self:input(c)
end
--[[
if c == 27 then
local c1 = read()
if c1 == 91 then
local c2 = read()
if c2 == 66 then -- arrow down
self:scroll 'down'
elseif c2 == 65 then -- arrow up
self:scroll 'up'
end
if c2 == 49 then
local c3 = read()
if c3 == 59 then
local c4 = read()
if c4 == 53 then
local c5 = read()
if c5 == 67 then
self:next()
elseif c5 == 68 then
self:previous()
end
end
end
end
end
goto continue
end
]]--
::continue::
end
end)
while not done do
--
end
ansikit.showCursor()
ansikit.screenMain()
end

View File

@ -1,11 +0,0 @@
local lunacolors = require 'lunacolors'
bait.catch('hilbish.init', function()
if os.date '%m' == '12' and hilbish.interactive and hilbish.opts.crimmas then
local crimmas = math.random(1, 31)
if crimmas >= 25 and crimmas <= 29 then
print(lunacolors.format '🎄 {green}Merry {red}Christmas{reset} from your {green}favourite{reset} shell {red}(right?){reset} 🌺')
end
end
end)

View File

@ -27,8 +27,7 @@ The nice lil shell for {blue}Lua{reset} fanatics!
]], hilbish.user),
motd = true,
fuzzy = false,
notifyJobFinish = true,
crimmas = true
notifyJobFinish = true
}
for optsName, default in pairs(defaultOpts) do

View File

@ -2,8 +2,8 @@ local bait = require 'bait'
local lunacolors = require 'lunacolors'
hilbish.motd = [[
Finally at {red}v2.2!{reset} So much {green}documentation improvements{reset}
and 1 single fix for Windows! {blue}.. and a feature they can't use.{reset}
1000 commits on the Hilbish repository brings us to {cyan}Version 2.1!{reset}
Docs, docs, docs... At least builtins work with pipes now.
]]
bait.catch('hilbish.init', function()

7
os.go
View File

@ -8,9 +8,10 @@ import (
)
// #interface os
// operating system info
// Provides simple text information properties about the current operating system.
// This mainly includes the name and version.
// OS Info
// The `os` interface provides simple text information properties about
// the current OS on the systen. This mainly includes the name and
// version.
// #field family Family name of the current OS
// #field name Pretty name of the current OS
// #field version Version of the current OS

View File

@ -60,8 +60,6 @@ var (
seqAltF = string([]byte{27, 102})
seqAltR = string([]byte{27, 114}) // Used for alternative history
seqAltBackspace = string([]byte{27, 127})
seqPageUp = string([]byte{27, 91, 53, 126})
seqPageDown = string([]byte{27, 91, 54, 126})
)
const (
@ -187,8 +185,6 @@ func (rl *Instance) ReadChar() string {
case seqHome, seqHomeSc: return "Home"
case seqEnd, seqEndSc: return "End"
case seqDelete, seqDelete2: return "Delete"
case seqPageUp: return "Page-Up"
case seqPageDown: return "Page-Down"
}
}

14
rl.go
View File

@ -267,7 +267,7 @@ func (lr *lineReader) Loader(rtm *rt.Runtime) *rt.Table {
// #interface history
// add(cmd)
// Adds a command to the history.
// #param cmd string
// --- @param cmd string
func (lr *lineReader) luaAddHistory(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -284,15 +284,15 @@ func (lr *lineReader) luaAddHistory(t *rt.Thread, c *rt.GoCont) (rt.Cont, error)
// #interface history
// size() -> number
// Returns the amount of commands in the history.
// #eturns number
// --- @returns number
func (lr *lineReader) luaSize(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
return c.PushingNext1(t.Runtime, rt.IntValue(int64(lr.fileHist.Len()))), nil
}
// #interface history
// get(index)
// Retrieves a command from the history based on the `index`.
// #param index number
// get(idx)
// Retrieves a command from the history based on the `idx`.
// --- @param idx number
func (lr *lineReader) luaGetHistory(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -309,8 +309,8 @@ func (lr *lineReader) luaGetHistory(t *rt.Thread, c *rt.GoCont) (rt.Cont, error)
// #interface history
// all() -> table
// Retrieves all history as a table.
// #returns table
// Retrieves all history.
// --- @returns table
func (lr *lineReader) luaAllHistory(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
tbl := rt.NewTable()
size := lr.fileHist.Len()

View File

@ -8,47 +8,11 @@ import (
// #interface runner
// interactive command runner customization
/* The runner interface contains functions that allow the user to change
how Hilbish interprets interactive input.
Users can add and change the default runner for interactive input to any
language or script of their choosing. A good example is using it to
write command in Fennel.
Runners are functions that evaluate user input. The default runners in
Hilbish can run shell script and Lua code.
A runner is passed the input and has to return a table with these values.
All are not required, only the useful ones the runner needs to return.
(So if there isn't an error, just omit `err`.)
- `exitCode` (number): A numerical code to indicate the exit result.
- `input` (string): The user input. This will be used to add
to the history.
- `err` (string): A string to indicate an interal error for the runner.
It can be set to a few special values for Hilbish to throw the right hooks and have a better looking message:
`[command]: not-found` will throw a command.not-found hook based on what `[command]` is.
`[command]: not-executable` will throw a command.not-executable hook.
- `continue` (boolean): Whether to prompt the user for more input.
Here is a simple example of a fennel runner. It falls back to
shell script if fennel eval has an error.
```lua
local fennel = require 'fennel'
hilbish.runnerMode(function(input)
local ok = pcall(fennel.eval, input)
if ok then
return {
input = input
}
end
return hilbish.runner.sh(input)
end)
```
*/
// The runner interface contains functions that allow the user to change
// how Hilbish interprets interactive input.
// Users can add and change the default runner for interactive input to any
// language or script of their choosing. A good example is using it to
// write command in Fennel.
func runnerModeLoader(rtm *rt.Runtime) *rt.Table {
exports := map[string]util.LuaExport{
"sh": {shRunner, 1, false},
@ -64,18 +28,18 @@ func runnerModeLoader(rtm *rt.Runtime) *rt.Table {
// #interface runner
// setMode(cb)
// This is the same as the `hilbish.runnerMode` function.
// It takes a callback, which will be used to execute all interactive input.
// This is the same as the `hilbish.runnerMode` function. It takes a callback,
// which will be used to execute all interactive input.
// In normal cases, neither callbacks should be overrided by the user,
// as the higher level functions listed below this will handle it.
// #param cb function
// --- @param cb function
func _runnerMode() {}
// #interface runner
// sh(cmd)
// Runs a command in Hilbish's shell script interpreter.
// This is the equivalent of using `source`.
// #param cmd string
// --- @param cmd string
func shRunner(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -103,7 +67,7 @@ func shRunner(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// lua(cmd)
// Evaluates `cmd` as Lua input. This is the same as using `dofile`
// or `load`, but is appropriated for the runner interface.
// #param cmd string
// --- @param cmd string
func luaRunner(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err

View File

@ -63,10 +63,11 @@ func (th *timersModule) get(id int) *timer {
// #interface timers
// create(type, time, callback) -> @Timer
// Creates a timer that runs based on the specified `time`.
// #param type number What kind of timer to create, can either be `hilbish.timers.INTERVAL` or `hilbish.timers.TIMEOUT`
// #param time number The amount of time the function should run in milliseconds.
// #param callback function The function to run for the timer.
// Creates a timer that runs based on the specified `time` in milliseconds.
// The `type` can either be `hilbish.timers.INTERVAL` or `hilbish.timers.TIMEOUT`
// --- @param type number
// --- @param time number
// --- @param callback function
func (th *timersModule) luaCreate(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.CheckNArgs(3); err != nil {
return nil, err
@ -92,8 +93,8 @@ func (th *timersModule) luaCreate(t *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
// #interface timers
// get(id) -> @Timer
// Retrieves a timer via its ID.
// #param id number
// #returns Timer
// --- @param id number
// --- @returns Timer
func (th *timersModule) luaGet(thr *rt.Thread, c *rt.GoCont) (rt.Cont, error) {
if err := c.Check1Arg(); err != nil {
return nil, err
@ -121,10 +122,15 @@ a few seconds, you don't have to rely on timing tricks, as Hilbish has a
timer API to set intervals and timeouts.
These are the simple functions `hilbish.interval` and `hilbish.timeout` (doc
accessible with `doc hilbish`, or `Module hilbish` on the Website).
accessible with `doc hilbish`). But if you want slightly more control over
them, there is the `hilbish.timers` interface. It allows you to get
a timer via ID and control them.
## Timer Object
All functions documented with the `Timer` type refer to a Timer object.
An example of usage:
```lua
```
local t = hilbish.timers.create(hilbish.timers.TIMEOUT, 5000, function()
print 'hello!'
end)

View File

@ -11,7 +11,7 @@ var (
// Version info
var (
ver = "v2.2.1"
ver = "v2.2.0"
releaseName = "Poppy"
gitCommit string

View File

@ -1,5 +1,5 @@
languageCode = 'en-us'
baseURL = 'https://rosettea.github.io/Hilbish/'
languageCode = 'en-us'
title = 'Hilbish'
theme = 'hsh'
enableGitInfo = true
@ -29,14 +29,6 @@ enableGitInfo = true
[markup.goldmark.renderer]
unsafe = true
[markup.highlight]
lineNos = true
lineNumbersInTable = false
noClasses = false
codeFences = true
guessSyntax = true
tabWidth = 4
[author]
[author.sammyette]
name = 'sammyette'

View File

@ -19,50 +19,109 @@ description: 'Something Unique. Hilbish is the new interactive shell for Lua fan
<div class="row row-cols-1 row-cols-md-2 g-4">
<div class="col">
<div class="card">
<div class="card border-light mb-3">
<div class="row g-0">
<div class="col-md-4">
<a href="https://safe.kashima.moe/6njmopm47u1x.png">
<img src="https://safe.kashima.moe/6njmopm47u1x.png" class="img-fluid rounded-start">
</a>
</div>
<div class="col-md-8">
<h5 class="card-header">Simple and Easy Scripting</h5>
<div class="card-body">
<h5 class="card-title">Simple and Easy Scripting</h5>
<p class="card-text">Hilbish is configured and scripted in the
Lua programming language. This removes all the old, ugly things
about Shell script and introduces everything good about Lua,
including other languages (Fennel, Lua derivatives).</p>
<p class="card-text">
Hilbish is configured and scripted in the Lua programming language.
This removes all the old, ugly things about Shell script and introduces
everything good about Lua, including other languages (Moonscript & Fennel).
</p>
</div>
</div>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card border-light mb-3">
<div class="row g-0">
<div class="col-md-4">
<a href="https://safe.kashima.moe/jkndbi636lzj.png">
<img src="https://safe.kashima.moe/jkndbi636lzj.png" class="img-fluid rounded-start">
</a>
</div>
<div class="col-md-8">
<h5 class="card-header">History and Completion Menus</h5>
<div class="card-body">
<h5 class="card-title">History and Completion Menus</h5>
<p class="card-text">Hilbish provides the user with proper menus
for completions and history usage. Want to see your previous commands?
Hit Ctrl-R.</p>
<p class="card-text">
Hilbish provides the user with proper menus for completions,
history searching. Want to see your previous commands? Hit Ctrl-R.
</p>
</div>
</div>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card border-light mb-3">
<div class="row g-0">
<div class="col-md-4">
<a href="https://safe.kashima.moe/6yfeooamzro4.png">
<img src="https://safe.kashima.moe/6yfeooamzro4.png" class="img-fluid rounded-start">
</a>
</div>
<div class="col-md-8">
<h5 class="card-header">Tons of Features, and More to Come</h5>
<div class="card-body">
<h5 class="card-title">Tons of Features, and More to Come</h5>
<p class="card-text">Hilbish offers a bunch of features to make your
interactive shell experience rich. Things like syntax highlighting
and hinting available via the Lua API.</p>
<p class="card-text">
Hilbish offers a bunch of features to make your interactive
shell experience rich. Things like syntax highlighting and hinting
available via the Lua API.
</p>
<p class="card-small text-muted">* Command hints shown in photo are not default.</p>
</div>
</div>
</div>
</div>
</div>
<!-- uncomment, replace top when editor interface can be replaced (and replace the images) -->
<!--
<div class="col">
<div class="card">
<div class="card border-light mb-3">
<div class="row g-0">
<div class="col-md-4">
<a href="https://safe.kashima.moe/6yfeooamzro4.png">
<img src="https://safe.kashima.moe/6yfeooamzro4.png" class="img-fluid rounded-start">
</a>
</div>
<div class="col-md-8">
<h5 class="card-header">Highly Extensible</h5>
<div class="card-body">
<h5 class="card-title">Customizable and Extensible via an accessible Lua API</h5>
<p class="card-text">Want to change the language used for interactive input?
Or maybe monitor and notify for the output of background jobs?
Have a real-time updating prompt? All this can be done in Hilbish!</p>
<p class="card-text">
Hilbish can be turned into an all new shell if wanted. One of our
main goals is that most (if not all) interfaces can be replaced.
</p>
</div>
</div>
</div>
</div>
</div>
-->
</div>
<hr>
<h1 class="fw-light">Screenshots</h1>
<div class="row row-cols-1 row-cols-md-2 g-4">
<div class="col">
<img src="/Hilbish/pillprompt.png">
</div>
<div class="col">
<img src="/Hilbish/default.png">
</div>
<div class="col">
<img src="/Hilbish/tab.png">
</div>
</div>
<br>
<h1 class="fw-light">Why not just Lua?</h1>
<p>
Hilbish is your interactive shell as well as a just a Lua interpreter

View File

@ -1,81 +0,0 @@
---
title: "v2.2 Release"
date: 2023-12-25T23:56:36-04:00
draft: false
---
> The release with full changelogs and prebuilt binaries can be
seen at the [v2.2.0](https://github.com/Rosettea/Hilbish/releases/tag/v2.2.0)
tag.
Welcome to a very long awaited release of Hilbish, and on Christmas. Just think
of it as a long preparing, late Christmas gift. :)
This release does not contain a whole lot of changes, but it is a new
release with enhancements and bug fixes!
# Documentation
As is a trend, the documentation has been improved by ONE HUNDRED TIMES.
Okay, not quite, but they've definitely been given an uplift.
Everything has been rewritten, new documentation has been added to both
the website and the local docs accessible with the `doc` command.
Both the website and local docs are now in sync with each other.
This means that the `doc` command has also been improved to consolidate
the documentation changes. It looks a lot better, has pagination, etc!
Speaking of pagination...
# Features
## Greenhouse
The first new added feature is the Greenhouse pager! It is a library and
command accessible via `greenhouse`. It will have better integration with
Hilbish things, like notifications and can be used as a base for displaying
multi-line text output instead of paging to less. The usage of Greenhouse is
more efficient and better in Hibish!
## Notifications
Wait... notifications? Yes! All new in the 2.2 release is a generic notification
interface for things in Hilbish to alert the user of things going on. Stuff like
background jobs finishing, simple alarms, *actual messages*, whatever you like.
## Fuzzy Searching
Users can now use fuzzy search for command history and completion search.
Enable it with `hilbish.opts.fuzzy = true`!
### Smaller Enhancements
Did you know of the `cdr` command? I personally don't use it, but I've made
it look slightly better for ease of use. That simple change is adding the indexes
next to the directory so you'll know to type `cdr 2`.
Users can now add aliases with numbered substitutions. In shell script,
some people have to make functions for certain things that are actually
just aliases. A simple example: `nix run nixpkgs#package` cannot be aliased
because if it was aliased to something like `run` normally there would be a space after.
Simple fix:
```lua
hilbish.alias('run', 'nix run nixpkgs#%1')
```
Rejoice!
# Bug Fixes
There are a small amount of bug fixes but they're still fixes!
In some cases Hilbish will panic if:
- Alias resolution results in something empty
- A user does not return a table in a runner functions
These are both fixed.
An infinite loop has been patched out if someone navigates without
having any prior history. Imagine pressing the up key on a fresh Hilbish
install and you shell no longer working... that's gone now.
Something else that's gone... is still Windows support, but I added a fix
which will make file completion work now. Job management commands work as
well now too due to an oversight when changing up the job functions.
# Towards v2.3
For the next release, I'm hoping that it won't take as long to deliver on
what is realistically a small amount of changes. So v2.3 will be coming
in a short time with some good changes, promise! See you in the
next blog post.

View File

@ -1 +0,0 @@
../../docs

View File

@ -0,0 +1 @@
../../../docs/api/

View File

@ -15,12 +15,11 @@ It compiles for Windows (CI ensures it does), but otherwise it is not
directly supported. If you'd like to improve this situation,
checkout [the discussion](https://github.com/Rosettea/Hilbish/discussions/165).
# Where is the API documentation?
The builtin `doc` command supplies all documentation of Hilbish provided
APIs. You can also check the sidebar.
# Why?
Hilbish emerged from the desire of a Lua configured shell.
It was the initial reason that it was created, but now it's more:
to be hyper extensible, simpler and more user friendly.
# Does it have "autocompletion" or "tab completion"
Of course! This is a modern shell. Hilbish provides a way for users
to write tab completion for any command and/or the whole shell.
Inline hinting and syntax highlighting are also available.

View File

@ -0,0 +1,21 @@
---
title: Runner Mode
description: Customize the interactive script/command runner.
layout: doc
menu:
docs:
parent: "Features"
---
Hilbish allows you to change how interactive text can be interpreted.
This is mainly due to the fact that the default method Hilbish uses
is that it runs Lua first and then falls back to shell script.
In some cases, someone might want to switch to just shell script to avoid
it while interactive but still have a Lua config, or go full Lua to use
Hilbish as a REPL. This also allows users to add alternative languages like
Fennel as the interactive script runner.
Runner mode can also be used to handle specific kinds of input before
evaluating like normal, which is how [Link.hsh](https://github.com/TorchedSammy/Link.hsh)
handles links.

Binary file not shown.

View File

@ -1,89 +0,0 @@
.chroma {
display: inline-block;
padding: 0.5em;
}
/* Background */ .bg { background-color: #F7F7F7; }
/* PreWrapper */ .chroma { background-color: #F7F7F7; }
/* Other */ .chroma .x { }
/* Error */ .chroma .err { color: #a61717; background-color: #e3d2d2 }
/* CodeLine */ .chroma .cl { }
/* LineTableTD */ .chroma .lntd { vertical-align: top; padding: 0; margin: 0; border: 0; }
/* LineTable */ .chroma .lntable { border-spacing: 0; padding: 0; margin: 0; border: 0; }
/* LineHighlight */ .chroma .hl { background-color: #F7F7F7 }
/* LineNumbersTable */ .chroma .lnt { white-space: pre; user-select: none; margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f }
/* LineNumbers */ .chroma .ln { white-space: pre; user-select: none; margin-right: 0.4em; padding: 0 0.4em 0 0.4em;color: #7f7f7f }
/* Line */ .chroma .line { display: flex; }
/* Keyword */ .chroma .k { color: #008800; font-weight: bold }
/* KeywordConstant */ .chroma .kc { color: #008800; font-weight: bold }
/* KeywordDeclaration */ .chroma .kd { color: #008800; font-weight: bold }
/* KeywordNamespace */ .chroma .kn { color: #008800; font-weight: bold }
/* KeywordPseudo */ .chroma .kp { color: #008800 }
/* KeywordReserved */ .chroma .kr { color: #008800; font-weight: bold }
/* KeywordType */ .chroma .kt { color: #888888; font-weight: bold }
/* Name */ .chroma .n { }
/* NameAttribute */ .chroma .na { color: #336699 }
/* NameBuiltin */ .chroma .nb { color: #003388 }
/* NameBuiltinPseudo */ .chroma .bp { }
/* NameClass */ .chroma .nc { color: #bb0066; font-weight: bold }
/* NameConstant */ .chroma .no { color: #003366; font-weight: bold }
/* NameDecorator */ .chroma .nd { color: #555555 }
/* NameEntity */ .chroma .ni { }
/* NameException */ .chroma .ne { color: #bb0066; font-weight: bold }
/* NameFunction */ .chroma .nf { color: #0066bb; font-weight: bold }
/* NameFunctionMagic */ .chroma .fm { }
/* NameLabel */ .chroma .nl { color: #336699; font-style: italic }
/* NameNamespace */ .chroma .nn { color: #bb0066; font-weight: bold }
/* NameOther */ .chroma .nx { }
/* NameProperty */ .chroma .py { color: #336699; font-weight: bold }
/* NameTag */ .chroma .nt { color: #bb0066; font-weight: bold }
/* NameVariable */ .chroma .nv { color: #336699 }
/* NameVariableClass */ .chroma .vc { color: #336699 }
/* NameVariableGlobal */ .chroma .vg { color: #dd7700 }
/* NameVariableInstance */ .chroma .vi { color: #3333bb }
/* NameVariableMagic */ .chroma .vm { }
/* Literal */ .chroma .l { }
/* LiteralDate */ .chroma .ld { }
/* LiteralString */ .chroma .s { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringAffix */ .chroma .sa { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringBacktick */ .chroma .sb { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringChar */ .chroma .sc { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringDelimiter */ .chroma .dl { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringDoc */ .chroma .sd { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringDouble */ .chroma .s2 { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringEscape */ .chroma .se { color: #0044dd; background-color: #fff0f0 }
/* LiteralStringHeredoc */ .chroma .sh { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringInterpol */ .chroma .si { color: #3333bb; background-color: #fff0f0 }
/* LiteralStringOther */ .chroma .sx { color: #22bb22; background-color: #f0fff0 }
/* LiteralStringRegex */ .chroma .sr { color: #008800; background-color: #fff0ff }
/* LiteralStringSingle */ .chroma .s1 { color: #dd2200; background-color: #fff0f0 }
/* LiteralStringSymbol */ .chroma .ss { color: #aa6600; background-color: #fff0f0 }
/* LiteralNumber */ .chroma .m { color: #0000dd; font-weight: bold }
/* LiteralNumberBin */ .chroma .mb { color: #0000dd; font-weight: bold }
/* LiteralNumberFloat */ .chroma .mf { color: #0000dd; font-weight: bold }
/* LiteralNumberHex */ .chroma .mh { color: #0000dd; font-weight: bold }
/* LiteralNumberInteger */ .chroma .mi { color: #0000dd; font-weight: bold }
/* LiteralNumberIntegerLong */ .chroma .il { color: #0000dd; font-weight: bold }
/* LiteralNumberOct */ .chroma .mo { color: #0000dd; font-weight: bold }
/* Operator */ .chroma .o { }
/* OperatorWord */ .chroma .ow { color: #008800 }
/* Punctuation */ .chroma .p { }
/* Comment */ .chroma .c { color: #888888 }
/* CommentHashbang */ .chroma .ch { color: #888888 }
/* CommentMultiline */ .chroma .cm { color: #888888 }
/* CommentSingle */ .chroma .c1 { color: #888888 }
/* CommentSpecial */ .chroma .cs { color: #cc0000; background-color: #fff0f0; font-weight: bold }
/* CommentPreproc */ .chroma .cp { color: #cc0000; font-weight: bold }
/* CommentPreprocFile */ .chroma .cpf { color: #cc0000; font-weight: bold }
/* Generic */ .chroma .g { }
/* GenericDeleted */ .chroma .gd { color: #000000; background-color: #ffdddd }
/* GenericEmph */ .chroma .ge { font-style: italic }
/* GenericError */ .chroma .gr { color: #aa0000 }
/* GenericHeading */ .chroma .gh { color: #333333 }
/* GenericInserted */ .chroma .gi { color: #000000; background-color: #ddffdd }
/* GenericOutput */ .chroma .go { color: #888888 }
/* GenericPrompt */ .chroma .gp { color: #555555 }
/* GenericStrong */ .chroma .gs { font-weight: bold }
/* GenericSubheading */ .chroma .gu { color: #666666 }
/* GenericTraceback */ .chroma .gt { color: #aa0000 }
/* GenericUnderline */ .chroma .gl { text-decoration: underline }
/* TextWhitespace */ .chroma .w { color: #bbbbbb }

View File

@ -23,10 +23,7 @@
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
{{ $syntax := resources.Get "css/syntax.css" | resources.Minify | resources.Fingerprint }}
<link rel="stylesheet" href="{{ $syntax.RelPermalink }}" integrity="{{ $syntax.Data.Integrity }}">
</link>
<style>
.heading > .heading-link {
opacity: 0
@ -37,42 +34,5 @@
opacity: 1;
transition: all .1s ease-in;
}
@keyframes highlight {
0% {
background: none
}
50% {
background: #fff2cf;
}
100% {
background: none;
}
}
div:target {
animation: highlight 1.2s;
animation-timing-function: cubic-bezier(1,-0.02,.45,.89);
}
table {
border-width: 1px;
border-style: solid;
border-color: #565c64;;
border-collapse: collapse;
margin-bottom: 12px;
}
table td {
padding: 5px;
}
table tr {
border-width: 1px;
}
thead {
display: none;
}
</style>
</head>

View File

@ -1,5 +0,0 @@
<video src="{{ .Get "src" }}" style="height: auto; max-width: 100%;" controls>
There's a video missing here...
Well here is the URL: {{ .Get "src" }}
</video>