Skip to content

Commit

Permalink
Merge pull request #399 from refaktor/multiliner
Browse files Browse the repository at this point in the history
Multiliner
  • Loading branch information
refaktor authored Nov 8, 2024
2 parents 4b70de9 + 3569c46 commit ccd8b15
Show file tree
Hide file tree
Showing 5 changed files with 155 additions and 28 deletions.
4 changes: 2 additions & 2 deletions env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func (e RyeCtx) GetState() map[int]Object {

func (e RyeCtx) Print(idxs Idxs) string {
var bu strings.Builder
bu.WriteString("[Context (" + e.Kind.Print(idxs) + "): ")
bu.WriteString("[Context (" + e.Kind.Print(idxs) + ") \"" + e.Doc + "\": ")
for k, v := range e.state {
bu.WriteString(idxs.GetWord(k) + ": " + v.Inspect(idxs) + " ")
}
Expand Down Expand Up @@ -251,7 +251,7 @@ func (e *RyeCtx) Get2(word int) (Object, bool, *RyeCtx) {

func (e *RyeCtx) Set(word int, val Object) Object {
if _, exists := e.state[word]; exists {
return NewError("Can't set already set word, try using modword! FIXME !")
return *NewError("Can't set already set word, try using modword! FIXME !")
} else {
e.state[word] = val
return val
Expand Down
40 changes: 38 additions & 2 deletions evaldo/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -924,13 +924,15 @@ var builtins = map[string]*env.Builtin{
return *sp
case *env.Block:
return *sp
case *env.RyeCtx:
return *sp
case *env.String:
return *sp
case *env.Native:
sp.Value = env.DereferenceAny(sp.Value)
return *sp
default:
return MakeArgError(ps, 1, []env.Type{env.SpreadsheetType}, "thaw")
return MakeArgError(ps, 1, []env.Type{env.SpreadsheetType, env.DictType, env.ListType, env.BlockType, env.StringType, env.NativeType, env.CtxType}, "thaw")
}
},
},
Expand Down Expand Up @@ -3181,6 +3183,10 @@ var builtins = map[string]*env.Builtin{
s1.Parent = ps.Ctx // TODO ... this is temporary so ccp works, but some other method must be figured out as changing the parent is not OK
ps.Ctx = &s1
return s1
case *env.RyeCtx:
s1.Parent = ps.Ctx // TODO ... this is temporary so ccp works, but some other method must be figured out as changing the parent is not OK
ps.Ctx = s1
return s1
default:
return MakeArgError(ps, 1, []env.Type{env.CtxType}, "cc")
}
Expand All @@ -3204,7 +3210,11 @@ var builtins = map[string]*env.Builtin{
switch word := arg0.(type) {
case env.Word:
newctx := env.NewEnv(ps.Ctx)
ps.Ctx.Set(word.Index, *newctx)
ret := ps.Ctx.Set(word.Index, newctx)
s, ok := ret.(env.Error)
if ok {
return s
}
ctx := ps.Ctx
ps.Ctx = newctx // make new context with current par
return *ctx
Expand Down Expand Up @@ -7752,6 +7762,32 @@ var builtins = map[string]*env.Builtin{
},
},

"time?": {
Argsn: 1,
Doc: "Returns Time part of a datetime.",
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {
switch s1 := arg0.(type) {
case env.Time:
return *env.NewString(s1.Value.Format("15:04:05"))
default:
return MakeArgError(ps, 1, []env.Type{env.TimeType}, "hour?")
}
},
},

"date?": {
Argsn: 1,
Doc: "Returns date part of datetime.",
Fn: func(ps *env.ProgramState, arg0 env.Object, arg1 env.Object, arg2 env.Object, arg3 env.Object, arg4 env.Object) env.Object {
switch s1 := arg0.(type) {
case env.Time:
return *env.NewString(s1.Value.Format("2006-01-02"))
default:
return MakeArgError(ps, 1, []env.Type{env.TimeType}, "hour?")
}
},
},

"day?": {
Argsn: 1,
Doc: "Returns current Time.",
Expand Down
4 changes: 3 additions & 1 deletion evaldo/repl.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,8 @@ func (r *Repl) evalLine(es *env.ProgramState, code string) string {
es.LiveObj.PsMutex.Unlock()
}

// if last character is space is turns to multiline more and doesn't eval yet, but we
// want to move this to microliner, so we can edit multiple lines there
multiline := len(code) > 1 && code[len(code)-1:] == " "

comment := regexp.MustCompile(`\s*;`)
Expand Down Expand Up @@ -371,7 +373,7 @@ func DoRyeRepl(es *env.ProgramState, dialect string, showResults bool) { // here
// #TODO don't display more than N words
// #TODO make current word bold

// # TRICK: we don't have the cursor position, but the caller code handles that already so we can suggest in the middle
// # TRICK: we don't have the cursor position, but the caller code handles that already so we can suggest in the middle
suggestions := make([]string, 0)
var wordpart string
spacePos := strings.LastIndex(line, " ")
Expand Down
5 changes: 4 additions & 1 deletion runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -527,7 +527,10 @@ func main_rye_repl(_ io.Reader, _ io.Writer, subc bool, here bool, lang string,
// userHomeDir, _ := os.UserHomeDir()
// profile_path := filepath.Join(userHomeDir, ".rye-profile")

fmt.Println("Welcome to Rye console. Use lc to list current or lcp and lcp\\ \"pri\" to list parent contexts.")
// fmt.Println("Welcome to Rye console. Use lc to list current or lcp and lcp\\ \"pri\" to list parent contexts.")
fmt.Println("Welcome to Rye console. We're still W-I-P. Visit \033[38;5;14mryelang.org\033[0m for more info.")
fmt.Println("- \033[38;5;246mtype in lcp (list context parent) too see functions, or lc to see your context\033[0m")
//fmt.Println("--------------------------------------------------------------------------------")

//if _, err := os.Stat(profile_path); err == nil {
//content, err := os.ReadFile(profile_path)
Expand Down
130 changes: 108 additions & 22 deletions term/microliner.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,9 +269,11 @@ type MLState struct {
lastLineString bool
prevLines int
prevCursorLine int
// killRing *ring.Ring
completer WordCompleter
completer WordCompleter
lines []string // added for the multiline behaviour
currline int // same
// pending []rune
// killRing *ring.Ring
}

// NewLiner initializes a new *State, and sets the terminal into raw mode. To
Expand All @@ -287,15 +289,15 @@ func NewMicroLiner(ch chan KeyEvent, sb func(msg string), el func(line string) s

func (s *MLState) getColumns() bool {
s.columns = GetTerminalColumns()
fmt.Print("*getColumns* : ")
fmt.Println(s.columns)
// fmt.Print("*getColumns* : ")
// fmt.Println(s.columns)
return true
}

func (s *MLState) SetColumns(cols int) bool {
s.columns = cols
fmt.Print("*setColumns* : ")
fmt.Println(s.columns)
// fmt.Print("*setColumns* : ")
// fmt.Println(s.columns)
return true
}

Expand Down Expand Up @@ -581,6 +583,16 @@ func (s *MLState) refreshSingleLine(prompt []rune, buf []rune, pos int) error {
return nil
}

func getLengthOfLastLine(input string) (int, bool) {
if !strings.Contains(input, "\n") {
return len(input), false
}

lines := strings.Split(input, "\n")
lastLine := lines[len(lines)-1]
return len(lastLine) - 3, true // for the prefix because currently string isn't padded on left line TODO unify this
}

// signals end-of-file by pressing Ctrl-D.
func (s *MLState) MicroPrompt(prompt string, text string, pos int, ctx1 context.Context) (string, error) {
// history related
Expand All @@ -601,7 +613,7 @@ startOfHere:
} else {
s.sendBack(" ")
p = []rune(" ")
multiline = false
//// WWW multiline = false
}

// defer s.stopPrompt()
Expand Down Expand Up @@ -637,7 +649,11 @@ startOfHere:
}
historyPos--
line = []rune(historyPrefix[historyPos])
pos = len(line)
pos, multiline = getLengthOfLastLine(string(line)) // TODO
if multiline {
s.lines = strings.Split(string(line), "\n")
s.currline = len(s.lines) - 1
}
s.needRefresh = true
} else {
s.doBeep()
Expand All @@ -657,7 +673,11 @@ startOfHere:
} else {
line = []rune(historyPrefix[historyPos])
}
pos = len(line)
pos, multiline = getLengthOfLastLine(string(line))
if multiline {
s.lines = strings.Split(string(line), "\n")
s.currline = len(s.lines) - 1
}
s.needRefresh = true
} else {
s.doBeep()
Expand Down Expand Up @@ -700,23 +720,25 @@ startOfHere:
///// pLen := countGlyphs(p)
haveNext:
if next.Ctrl {
switch next.Code {
case 13: // Enter Newline
fmt.Println("CLCLCLCLCLC")
}
switch strings.ToLower(next.Key) {
// next line
case "x":
// TEMP copy of code below ... refactor
historyStale = true
s.lastLineString = false
// trace2("NL")
s.sendBack(fmt.Sprintf("%s⏎\n%s", color_emph, reset))
s.sendBack(fmt.Sprintf("%s\n%s", color_emph, reset)) // ⏎
if s.inString {
s.lastLineString = true
}
s.enterLine(string(line) + " ")
// DONT SEND LINE BACK BUT STORE IT
// s.enterLine(string(line) + " ")
s.currline += 1
s.lines = append(s.lines, string(line))
pos = 0
//if xx == "next line" {
multiline = true
//} else {
// s.sendBack("") // WW?
//}
line = make([]rune, 0)
trace(line)
goto startOfHere
Expand Down Expand Up @@ -861,7 +883,25 @@ startOfHere:
}
} else {
switch next.Code {
case 13: // Enter
case 13: // Enter Newline
if s.inString {
// This is copy from ctrl+x code above ... deduplicate and systemize TODO
historyStale = true
s.lastLineString = false
s.sendBack(fmt.Sprintf("%s\n%s", color_emph, reset)) //
if s.inString {
s.lastLineString = true
}
// DONT SEND LINE BACK BUT STORE IT
// s.enterLine(string(line) + " ")
s.lines = append(s.lines, string(line))
pos = 0
multiline = true
s.currline += 1
line = make([]rune, 0)
trace(line)
goto startOfHere
}
if tabCompletionWasActive {
// TODO --- make it into a function - deduplicate
fmt.Println("")
Expand All @@ -872,20 +912,36 @@ startOfHere:
s.lastLineString = false
// trace2("NL")
if len(line) > 0 && unicode.IsSpace(line[len(line)-1]) {
s.sendBack(fmt.Sprintf("%s\n%s", color_emph, reset))
s.sendBack(fmt.Sprintf("%s\n%s", color_emph, reset))
if s.inString {
s.lastLineString = true
}
} else {
s.sendBack("\n")
}
xx := s.enterLine(string(line))
xx := ""
if multiline {
// fmt.Println(s.currline)
// fmt.Println(len(s.lines))
if s.currline > len(s.lines)-1 {
s.lines = append(s.lines, string(line))
} else {
s.lines[s.currline] = string(line)
}
xx = s.enterLine(strings.Join(s.lines, "\n"))
} else {
xx = s.enterLine(string(line))

}
pos = 0
multiline = false
if xx == "next line" {
multiline = true
} else {
s.sendBack("") // WW?
}
s.currline = 0
s.lines = make([]string, 0)
line = make([]rune, 0)
trace(line)
goto startOfHere
Expand Down Expand Up @@ -935,9 +991,39 @@ startOfHere:
s.doBeep()
}
case 38: // Up
histPrev()
if multiline {
if s.currline > 0 { // len(s.lines) {
CurUp(1)
// append the last line -- only when in last line but ok for now
if s.currline > len(s.lines)-1 {
s.lines = append(s.lines, string(line))
} else {
s.lines[s.currline] = string(line)
}
s.currline -= 1 // later increment
line = []rune(s.lines[s.currline]) // + "⏎")
if pos > len(line) {
pos = len(line) - 1
}
}
} else {
histPrev()
}
case 40: // Down
histNext()
if multiline {
if s.currline < len(s.lines)-1 {
CurDown(1)
// append the last line -- only when in last line but ok for now
s.lines[s.currline] = string(line)
s.currline += 1 // later increment
line = []rune(s.lines[s.currline]) // + "⏎...")
if pos > len(line) {
pos = len(line) - 1
}
}
} else {
histNext()
}
case 36: // Home
pos = 0
case 35: // End
Expand Down

0 comments on commit ccd8b15

Please sign in to comment.