CommandLineUI.lua


NAME

CommandLineUI - Lua module offering a Command-Line User Interface


SYNOPSIS

 local C = require 'CommandLineUI'
 print(C.Version, C.VersionDate)
 -- uses arrow-keys, or hjkl, or mouse ...
 choice  = C.choose("Which item ?", a_list)  -- single choice
 -- multi-line question-texts are fine ...
 choice  = C.choose("Which item ?"..C.help_text('choose'), a_list)
 choices = C.choose("Which items ?", a_list, {multichoice=true})
 if C.confirm("OK to proceed ?") then do_something() end
 answer   = C.ask(question)  -- with History and Tab-completion
 answer   = C.ask(question..C.help_text('ask'))
 password = C.ask_password("Enter password:")
 filename = C.ask_filename("Which file ?") -- synonym for C.ask()
 newtext = C.edit(title, oldtext) -- if title is _not_ a filename
 C.edit(textfile)     -- if textfile _is_ a filename
 C.view(title, text)  -- if title is _not_ a filename
 C.view(textfile)     -- if textfile _is_ a filename
 local P = require 'posix'
 C.edit(C.choose("Edit which file ?", P.glob('*.txt')))


DESCRIPTION

CommandLineUI offers a high-level user interface to give the user of command-line applications a consistent "look and feel". Its metaphor for the computer is as a human-like conversation-partner, and as each question/response is completed it is summarised onto one line, and remains on screen, so that the history of the session gradually accumulates on the screen and is available for review, or for highlight/paste.

This user interface can therefore be intermixed with standard applications which write to STDOUT or STDERR, such as make, pgp, rcs, slrn, mplayer, alpine, wget, luarocks etc.

For the user, choose() uses either the mouse, or arrow keys (or hjkl) and Return; also q to quit, and SpaceBar or Button3 to highlight multiple choices. confirm() expects y, Y, n or N. In general, ctrl-L redraws the (currently active bit of the) screen. edit() and view() use the default EDITOR and PAGER if possible.

It's fast and simple to use. It depends on posix but doesn't use curses (which is a whole-of-screen interface); it uses a small subset of vt100 sequences which are very portable, and also the SET_ANY_EVENT_MOUSE and kmous (terminfo) sequences, which are supported by all xterm, rxvt, konsole, screen, linux, gnome and putty terminals.

It's a slightly leaner descendant of the Perl CPAN module Term::Clui and the Python3 module TermClui.py, which were in turn based on some old Perl4 libraries, ask.pl, choose.pl, confirm.pl, edit.pl, sorry.pl, inform.pl and view.pl, which were in turn based on some even older curses-based programs in C.

It is intended to keep the Perl, Python and Lua version-numbers approximately synchronised.


WINDOW-SIZE

CommandLineUI attempts to handle the WINCH signal. If the window size is changed, then as soon as the user enters the next keystroke (such as ctrl-L) the current question/response will be redisplayed to fit the new size.

The first line of the question, the one which will remain on-screen, is not re-formatted, but is left to be dealt with by the width of the window. Subsequent lines are split into blank-separated words which are filled into the available width; lines beginning with white-space are treated as the beginning of a new indented paragraph, individual words which will not fit onto one line are truncated, and successive blank lines are collapsed into one. If the question will not fit within the available rows, it is truncated.

If the available choice items in a choose() overflow the screen, the user is asked to enter "clue" letters, and as soon as the items matching them will fit onto the screen they are displayed as a choice.

The WINCH signal, unfortunately, is not defined by core POSIX, and so is hardcoded here to 28. The command kill -l should tell you if this number is correct on your system.


FUNCTIONS

ask( question )

Asks the user the question and returns a string answer, with no newline character at the end.

This function uses Gnu Readline to provide filename-completion with the Tab key, and history with the Up and Down arrow keys, just like in the bash shell.

It also displays multi-line questions in the same way as confirm and choose do; if the question is multi-line, the entry-field is at the top to the right of the first line, and the subsequent lines are formatted within the screen width and displayed beneath, as with choose and confirm.

For the user, left and right arrow keys move backward and forward through the string, delete and backspace erase the previous character, ctrl-A moves to the beginning, ctrl-E to the end, and ctrl-D or ctrl-X clear the current string.

ask_password( question )

Does the same as ask, but with no echo, as used for password entry.

ask_filename( question )

In this Lua module, Tab-filename-completion is enabled by default, and this function is just a synonym for ask

choose( question, a_list [, {multichoice=true}] )

Displays the question, and formats the list items onto the lines beneath it.

If the multichoice option is not set, the user can choose an item using arrow keys (or hjkl) and Return, or with the mouse-left-click, or cancel the choice with a "q". choose then returns the chosen string, or nil if the choice was cancelled.

If the multichoice option is set, the user can also mark an item with the SpaceBar, or the mouse-right-click. choose then returns an array of the marked items, (including the item highlit when Return was pressed), or an empty array if the choice was cancelled.

A GDBM database is maintained of the question and its chosen response. The next time the user is offered a choice with the same question, if that response is still in the list it is highlighted as the default; otherwise the first item is highlighted. Different parts of the code, or different applications using CommandLineUI, can therefore share defaults simply by using the same question words, such as "Which printer ?". Multiple choices are not remembered, as the danger exists that the user might fail to notice some of the highlit items (for example, all the items might not fit onto one screen).

The database ~/.clui_dir/choices.gdbm or $CLUI_DIR/choices.gdbm is available to be read or written if lower-level manipulation is needed, and the functions get_default(question) and set_default(question, choice) should be used for this purpose, as they handle DBM's problem with concurrent accesses. The whole default database mechanism can be disabled by CLUI_DIR=OFF if you really want to :-(

If the items won't fit on the screen, the user is asked to enter a substring as a clue. As soon as the matching items will fit, they are displayed to be chosen as normal. If the user pressed q at this choice, they are asked if they wish to change their substring clue; if they reply "n" to this, choose quits and returns undefined.

If the question is multi-line, the first line is put at the top as usual with the choices arranged beneath it; the subsequent lines are formatted within the screen width and displayed at the bottom. After the choice is made, all but the first line is erased, and the first line remains on-screen with the choice appended after it. You should therefore try to arrange multi-line questions so that the first line is the question in short form, and subsequent lines are explanation. The function help_text() exists to provide general User-Interface help.

confirm( question )

Asks the question, and takes y, n, Y or N as a response. If the question is multi-line, after the response, all but the first line is erased, and the first line remains on-screen with Yes or No appended after it; you should therefore try to arrange multi-line questions so that the first line is the question in short form, and subsequent lines are explanatory.

Returns true or false.

edit( title, text ) OR edit( filename )

Uses the environment variable EDITOR ( or vi :-) Uses rcs if the directory RCS/ exists

sorry( message )

Similar to io.stderr:write("Sorry, "..message.."\r\n")

inform( message )

Similar to io.stderr:write(message.."\r\n") except that it doesn't add the newline at the end if there already is one, and it uses /dev/tty rather than STDERR if it can.

view( title, text ) OR view( filename )

If the text is longer than a screenful, uses the environment variable PAGER ( or less ) to display it. If it is one or two lines it just omits the title and displays it. Otherwise it uses a simple built-in routine which expects either q or Return from the user; if the user presses Return the displayed text remains on the screen and the dialogue continues after it, if the user presses q the text is erased.

If there is only one argument and it's a filename, then the user's PAGER displays it, except if it's a .doc file, when either wvText, antiword or catdoc is used to extract its contents first.

help_text( mode )

This returns a short help message for the user. If mode is "ask" then the text describes the keys the user has available when responding to an ask question; If mode contains the string "pass" then the text describes the keys the user has available when responding to an ask_password question; If mode is "multi" then the text describes the keys and mouse actions the user has available when responding to a multiple-choice choose question; otherwise, the text describes the keys and mouse actions the user has available when responding to a single-choice choose.

beep()

Beeps. Usually this has no effect; beeping is considered old-fashioned.

timestamp()

Returns a sortable timestamp string in "YYYYMMDD hhmmss" form.

get_default( question )

Consults the database ~/.clui_dir/choices.gdbm or $CLUI_DIR/choices.gdbm and returns the choice that the user made the last time this question was asked. This is better than opening the database directly as it handles DBM's problem with concurrent accesses.

set_default( question, new_default )

Opens the database ~/.clui_dir/choices.gdbm or $CLUI_DIR/choices.gdbm and sets the default response which will be offered to the user made the next time this question is asked. This is better than opening the database directly as it handles DBM's problem with concurrent accesses.

back_up( nlines )

This moves the cursor back up nlines lines and erases all the text beneath its new position. You don't often need it, but sometimes in an application it can be neat to clear up a few lines.


DEPENDENCIES

Requires the luarock modules luaposix, terminfo, readkey, readline, luabitop, and lgdbm.

See the SEE ALSO section below.


ENVIRONMENT

The environment variable CLUI_DIR can be used (by programmer or user) to override ~/.clui_dir as the directory in which choose() keeps its database of previous choices. The whole default database mechanism can be disabled by CLUI_DIR=OFF if you really want to.

If the variable CLUI_MOUSE is set to OFF then choose() will not interpret mouse-clicks as making a choice. The advantage of this is that the mouse can then be used to highlight and paste text from this window as usual.

If the variables LANG or LC_TYPE contain the string "utf8" then all strings will be displayed assuming they are utf8 strings. (It's a question of calculating the length of the string correctly.)

CommandLineUI.lua also consults the environment variables HOME, EDITOR and PAGER, if they are set.


EXAMPLES

/usr/local/bin/confirm
#! /usr/bin/lua
-- usage: confirm 'start X ?' && startx
--        confirm "OK to delete $file" && rm $file
local C = require 'CommandLineUI'
if C.confirm(arg[1]) then os.exit(0) else os.exit(1) end
/usr/local/bin/audio_stuff
This script is a wrapper for aplaymidi, cdda2wav, cdrecord, lame, timidity etc.

Written as an example for the CommandLineUI module, it integrates various open-source programs for handling Midi, WAV, MP3, CDDA and DVD files into one ArrowKey-and-Return user-interface.

burn files->DataCD    burn WAV->AudioCD     change Directory
connect MIDIports     consult Manual        convert MIDI->MP3
convert MIDI->WAV     copy audio CD         copy video DVD
decode MP3->WAV       encode WAV->MP2       encode WAV->MP3
play MIDI,WAV,MP3     record AudioIn->WAV   record Keyboard->MIDI
rip AudioCD->WAV      rip MP3CD->MP3        run alsamixer


DOWNLOAD

This module is available as a LuaRock in luarocks.org/modules/peterbillam so you should be able to install it with the command:

 $ su
 Password:
 # luarocks install commandlineui

or:

 # luarocks install http://www.pjb.com.au/comp/lua/commandlineui-1.74-0.rockspec

This module requires the lgdbm module, so if the install fails with some message beginning with
  Error: Could not find expected file libgdbm.a, or libgdbm.so,
then consult lgdbm.html for details of how to get round it; after which you should be able to install commandlineui with no problem.

The Perl module is available from CPAN at search.cpan.org/perldoc?Term::Clui


CHANGES

 20150421 1.74 include lua5.3, and move pod and doc back to luarocks.org
 20140718 1.73 insure against nil in line 387
 20140607 1.72 switch pod and doc over to using moonrocks
 20131101 1.71 various undeclared global variables declared as local
 20131031      multichoice choose() consistently returns {} if cancelled
 20131019 1.70 check_size() repositioned after fmt(); new_mid_col defined=0
 20131010      calls to absent warn() eliminated; is_executable() redundant
 20131004 1.69 first working version in Lua


AUTHOR

Peter J Billam   www.pjb.com.au/comp/contact.html


SEE ALSO

 bash
 http://search.cpan.org/perldoc?Term::Clui
 http://cpansearch.perl.org/src/PJB/Term-Clui-1.68/py/TermClui.py
 http://www.pjb.com.au/
 http://www.pjb.com.au/comp/index.html#lua
 http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
 http://search.cpan.org/~pjb
 http://luarocks.org/modules/gvvaughan/luaposix
 http://luaposix.github.io/luaposix/docs/
 http://luarocks.org/modules/peterbillam/terminfo
 http://pjb.com.au/comp/lua/terminfo.html
 http://luarocks.org/modules/peterbillam/readkey
 http://pjb.com.au/comp/lua/readkey.html
 http://luarocks.org/modules/peterbillam/readline
 http://pjb.com.au/comp/lua/readline.html
 http://luarocks.org/modules/luarocks/lgdbm
 http://pjb.com.au/comp/lua/lgdbm.html
 http://luarocks.org/modules/luarocks/luabitop
 http://bitop.luajit.org/api.html
 http://luarocks.org/modules/peterbillam/commandlineui