Skip to content

Commit

Permalink
Merge pull request #153 from non/topic/cn-cp-history-nav
Browse files Browse the repository at this point in the history
Add support for C-p/C-n for prev/next in history.
  • Loading branch information
lihaoyi committed Aug 12, 2015
2 parents 128c504 + bb9f061 commit 7a5198b
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions terminal/src/main/scala/ammonite/terminal/ReadlineFilters.scala
Original file line number Diff line number Diff line change
Expand Up @@ -85,23 +85,38 @@ object ReadlineFilters {
def lastRow(cursor: Int, buffer: Vector[Char], width: Int) = {
(buffer.length - cursor) < width && (buffer.lastIndexOf('\n') < cursor || buffer.lastIndexOf('\n') == -1)
}

case class HistoryFilter(history: () => Seq[String]) extends TermCore.DelegateFilter{
var index = -1
var currentHistory = Vector[Char]()

def swapInHistory(b: Vector[Char], newIndex: Int, rest: LazyList[Int], c: Int) = {
def swapInHistory(b: Vector[Char], newIndex: Int, rest: LazyList[Int]): TermState = {
if (index == -1 && newIndex != -1) currentHistory = b

index = newIndex
val h = if (index == -1) currentHistory else history()(index).toVector
TS(rest, h, h.length)
}

if (index == -1) TS(rest, currentHistory, c)
else TS(rest, history()(index).toVector, c)
def constrainIndex(n: Int): Int = {
val max = history().length - 1
if (n < -1) -1 else if (max < n) max else n
}

def previousHistory(b: Vector[Char], rest: LazyList[Int], c: Int): TermState =
swapInHistory(b, constrainIndex(index + 1), rest)

def nextHistory(b: Vector[Char], rest: LazyList[Int], c: Int): TermState =
swapInHistory(b, constrainIndex(index - 1), rest)

def filter = {
case TermInfo(TS(p"\u001b[A$rest", b, c), w) if firstRow(c, b, w) =>
swapInHistory(b, (index + 1) min (history().length - 1), rest, 99999)
previousHistory(b, rest, c)
case TermInfo(TS(p"\u0010$rest", b, c), w) if lastRow(c, b, w) =>
previousHistory(b, rest, c)
case TermInfo(TS(p"\u001b[B$rest", b, c), w) if lastRow(c, b, w) =>
swapInHistory(b, (index - 1) max -1, rest, 0)
nextHistory(b, rest, c)
case TermInfo(TS(p"\u000e$rest", b, c), w) if firstRow(c, b, w) =>
nextHistory(b, rest, c)
}
}
}

0 comments on commit 7a5198b

Please sign in to comment.