Skip to content

Instantly share code, notes, and snippets.

@x7c1
Last active October 23, 2015 19:01
Show Gist options
  • Select an option

  • Save x7c1/38ec85c5b254730395ac to your computer and use it in GitHub Desktop.

Select an option

Save x7c1/38ec85c5b254730395ac to your computer and use it in GitHub Desktop.
sbt custom tab-completion, which diminishes candidates if matched.
import sbt.complete.DefaultParsers._
val sample = inputKey[Unit]("sample of tab-completion")
val settings = Seq(
sample := {
val selected = parser.parsed
println("selected numbers")
selected.map(" * " + _).foreach(println)
}
)
lazy val parser: Def.Initialize[State => Parser[Seq[String]]] =
Def.setting { state =>
val items = (1 to 5).map(_.toString)
exclusiveParser(items)
}
def exclusiveParser(items: Seq[String]): Parser[Seq[String]] = {
val base = items match {
case Nil => failure("item not remain")
case _ => items.map(token(_)).reduce(_ | _)
}
val recurse = (Space ~> base) flatMap { item =>
val (consumed, remains) = items.partition(_ == item)
exclusiveParser(remains) map { input => consumed ++ input }
}
recurse ?? Nil
}
> sample
1 2 3 4 5
> sample 1
2 3 4 5
> sample 1 3
2 4 5
> sample 1 3 4
2 5
> sample 1 3 4 2 5
selected numbers
* 1
* 3
* 4
* 2
* 5
> sample foo
[error] Expected whitespace character
[error] Expected '1'
[error] Expected '2'
[error] Expected '3'
[error] Expected '4'
[error] Expected '5'
[error] sample foo
[error] ^
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment