government / cmd / govlisp / lines.go

@ 2dbe47969d09d4856796bbf662b4e11c74a7f4fe | history


package main

import (
	"bufio"
	"errors"
	"io"
	"os"
	"path/filepath"
	"sort"
	"strings"

	"github.com/ergochat/readline"

	"government/builtin"
	"government/eval"
	"government/sexpr"
)

// newSource picks how the REPL reads: with readline on a terminal, and
// line by line with no prompts otherwise, so piped input gives clean
// output.
func newSource(stdin *os.File, top *eval.TopLevel) (lineSource, error) {
	if !isTerminal(stdin) {
		return newPlainSource(stdin), nil
	}
	history := ""
	if home, err := os.UserHomeDir(); err == nil {
		history = filepath.Join(home, ".govlisp_history")
	}
	return newReadlineSource(&readline.Config{HistoryFile: history}, top)
}

func isTerminal(f *os.File) bool {
	info, err := f.Stat()
	return err == nil && info.Mode()&os.ModeCharDevice != 0
}

// plainSource yields input one line at a time, without the line ending.
// It has no limit on line length, unlike bufio.Scanner's default.
type plainSource struct {
	r *bufio.Reader
}

func newPlainSource(in io.Reader) *plainSource {
	return &plainSource{r: bufio.NewReader(in)}
}

func (s *plainSource) readLine(string) (string, error) {
	line, err := s.r.ReadString('\n')
	if err != nil && line == "" {
		return "", io.EOF
	}
	if n := len(line); n > 0 && line[n-1] == '\n' {
		line = line[:n-1]
		if n := len(line); n > 0 && line[n-1] == '\r' {
			line = line[:n-1]
		}
	}
	return line, nil
}

func (s *plainSource) Close() error { return nil }

// readlineSource reads from a terminal with line editing and history.
// History is kept one line at a time, as typed: joining a multi-line form
// into one entry would change its meaning when a line ends in a comment
// or a string spans lines.
type readlineSource struct {
	rl *readline.Instance
}

func newReadlineSource(cfg *readline.Config, top *eval.TopLevel) (*readlineSource, error) {
	cfg.Prompt = prompt
	cfg.AutoComplete = completer{top}
	cfg.InterruptPrompt = "^C"
	cfg.HistorySearchFold = true
	rl, err := readline.NewFromConfig(cfg)
	if err != nil {
		return nil, err
	}
	return &readlineSource{rl}, nil
}

func (s *readlineSource) readLine(p string) (string, error) {
	s.rl.SetPrompt(p)
	line, err := s.rl.Readline()
	if errors.Is(err, readline.ErrInterrupt) {
		return "", errInterrupt
	}
	return line, err
}

func (s *readlineSource) Close() error { return s.rl.Close() }

// completer completes the name before the cursor from everything in scope:
// the special forms, the builtins and the user's own definitions. With
// nothing to complete, Tab indents, which is what it is for on the
// continuation lines of a long form.
type completer struct {
	top *eval.TopLevel
}

const indent = "  "

func (c completer) Do(line []rune, pos int) ([][]rune, int) {
	start := pos
	for start > 0 && !sexpr.IsDelimiter(line[start-1]) {
		start--
	}
	prefix := string(line[start:pos])
	if prefix == "" {
		return [][]rune{[]rune(indent)}, 0
	}
	var out [][]rune
	for _, name := range c.names() {
		if strings.HasPrefix(name, prefix) && name != prefix {
			out = append(out, []rune(name[len(prefix):]))
		}
	}
	return out, len([]rune(prefix))
}

func (c completer) names() []string {
	seen := map[string]bool{}
	for _, spec := range builtin.All {
		if spec.Kind == builtin.SpecialForm {
			seen[spec.Name] = true
		}
	}
	for _, name := range c.top.Names() {
		seen[string(name)] = true
	}
	names := make([]string, 0, len(seen))
	for name := range seen {
		names = append(names, name)
	}
	sort.Strings(names)
	return names
}