Skip to content

Commit bad1ef1

Browse files
committed
Also allow output in History.At - and protect from panic in History methods
1 parent a5f4981 commit bad1ef1

File tree

1 file changed

+17
-5
lines changed

1 file changed

+17
-5
lines changed

terminal.go

+17-5
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,20 @@ func visualLength(runes []rune) int {
468468
return length
469469
}
470470

471+
// histroryAt unlocks the terminal and relocks it while calling History.At.
472+
func (t *Terminal) historyAt(idx int) (string, bool) {
473+
t.lock.Unlock()
474+
defer t.lock.Lock()
475+
return t.History.At(idx)
476+
}
477+
478+
// historyAdd unlocks the terminal and relocks it while calling History.Add.
479+
func (t *Terminal) historyAdd(entry string) {
480+
t.lock.Unlock() // Unlock to avoid deadlock if History methods use the output writer.
481+
defer t.lock.Lock() // panic in Add protection.
482+
t.History.Add(entry)
483+
}
484+
471485
// handleKey processes the given key and, optionally, returns a line of text
472486
// that the user has entered.
473487
func (t *Terminal) handleKey(key rune) (line string, ok bool) {
@@ -515,7 +529,7 @@ func (t *Terminal) handleKey(key rune) (line string, ok bool) {
515529
t.pos = len(t.line)
516530
t.moveCursorToPos(t.pos)
517531
case keyUp:
518-
entry, ok := t.History.At(t.historyIndex + 1)
532+
entry, ok := t.historyAt(t.historyIndex + 1)
519533
if !ok {
520534
return "", false
521535
}
@@ -534,7 +548,7 @@ func (t *Terminal) handleKey(key rune) (line string, ok bool) {
534548
t.setLine(runes, len(runes))
535549
t.historyIndex--
536550
default:
537-
entry, ok := t.History.At(t.historyIndex - 1)
551+
entry, ok := t.historyAt(t.historyIndex - 1)
538552
if ok {
539553
t.historyIndex--
540554
runes := []rune(entry)
@@ -799,9 +813,7 @@ func (t *Terminal) readLine() (line string, err error) {
799813
if lineOk {
800814
if t.echo {
801815
t.historyIndex = -1
802-
t.lock.Unlock()
803-
t.History.Add(line) // so this can output without deadlock.
804-
t.lock.Lock()
816+
t.historyAdd(line) // so this can output without deadlock.
805817
}
806818
if lineIsPasted {
807819
err = ErrPasteIndicator

0 commit comments

Comments
 (0)