Skip to content

Commit e4cae6f

Browse files
authored
Add AutoHistory(false) option (default remains true) to not automatically add to the History (golang#4)
* Add AutoHistory(false) option (default remains true) to not automatically add to the History and let the caller of ReadLine() decide, for instance to only add validated commands
1 parent 7796a13 commit e4cae6f

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

terminal.go

+17-2
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ type Terminal struct {
9494
// the incomplete, initial line. That value is stored in
9595
// historyPending.
9696
historyPending string
97+
// autoHistory, if true, causes lines to be automatically added to the history.
98+
// If false, call AddToHistory to add lines to the history for instance only adding
99+
// successful commands. Defaults to true. This is controlled through AutoHistory(bool).
100+
autoHistory bool
97101
}
98102

99103
// NewTerminal runs a VT100 terminal on the given ReadWriter. If the ReadWriter is
@@ -110,6 +114,7 @@ func NewTerminal(c io.ReadWriter, prompt string) *Terminal {
110114
echo: true,
111115
historyIndex: -1,
112116
history: NewHistory(defaultNumEntries),
117+
autoHistory: true,
113118
}
114119
}
115120

@@ -772,8 +777,10 @@ func (t *Terminal) readLine() (line string, err error) {
772777
t.outBuf = t.outBuf[:0]
773778
if lineOk {
774779
if t.echo {
775-
t.historyIndex = -1
776-
t.history.Add(line)
780+
t.historyIndex = -1 // Resets the key up behavior/historyPending.
781+
if t.autoHistory {
782+
t.history.Add(line)
783+
}
777784
}
778785
if lineIsPasted {
779786
err = ErrPasteIndicator
@@ -829,6 +836,14 @@ func (t *Terminal) AddToHistory(entry ...string) {
829836
}
830837
}
831838

839+
// AutoHistory sets whether lines are automatically added to the history
840+
// before being returned by ReadLine() or not. Defaults to true.
841+
func (t *Terminal) AutoHistory(onOff bool) {
842+
t.lock.Lock()
843+
t.autoHistory = onOff
844+
t.lock.Unlock()
845+
}
846+
832847
// SetPrompt sets the prompt to be used when reading subsequent lines.
833848
func (t *Terminal) SetPrompt(prompt string) {
834849
t.lock.Lock()

0 commit comments

Comments
 (0)