All Downloads are FREE. Search and download functionalities are using the official Maven repository.

ammonite.repl.PPrints.scala Maven / Gradle / Ivy

There is a newer version: 2.4.1-8-a6696a8f
Show newest version
package ammonite.repl

import ammonite.ops.{CommandResult, LsSeq}
import ammonite.runtime.History
import ammonite.runtime.tools.GrepResult
import pprint.Renderer

object PPrints{
  val replPPrintHandlers: PartialFunction[Any, pprint.Tree] = {
    case x: ammonite.ops.LsSeq => PPrints.lsSeqRepr(x)
    case x: ammonite.ops.Path => PPrints.pathRepr(x)
    case x: ammonite.ops.RelPath => PPrints.relPathRepr(x)
    case x: ammonite.ops.CommandResult => PPrints.commandResultRepr(x)
    case t: History => pprint.Tree.Lazy(ctx => Iterator(t.mkString("\n")))
    case t: GrepResult => pprint.Tree.Lazy(ctx => Iterator(GrepResult.grepResultRepr(t, ctx)))
    case t: scala.xml.Elem => pprint.Tree.Lazy(_ => Iterator(t.toString))
  }
  def lsSeqRepr(t: LsSeq) = pprint.Tree.Lazy { ctx =>
    val renderer = new Renderer(
      ctx.width, ctx.applyPrefixColor, ctx.literalColor, ctx.indentStep
    )
    val snippets = for (p <- t) yield {
      fansi.Str.join(renderer.rec(relPathRepr(p relativeTo t.base), 0, 0).iter.toStream:_*)
    }
    Iterator("\n") ++ FrontEndUtils.tabulate(snippets, FrontEndUtils.width)
  }


  def reprSection(s: String, cfg: pprint.Tree.Ctx): fansi.Str = {
    val validIdentifier = "([a-zA-Z_][a-zA-Z_0-9]+)".r

    if (validIdentifier.findFirstIn(s) == Some(s)){
      cfg.literalColor(''' + s)
    }else{
      cfg.literalColor(pprint.Util.literalize(s))
    }
  }

  def relPathRepr(p: ammonite.ops.RelPath) = pprint.Tree.Lazy(ctx =>
    Iterator(
      (Seq.fill(p.ups)("up") ++ p.segments.map(reprSection(_, ctx))).mkString("/")
    )
  )

  def pathRepr(p: ammonite.ops.Path) = pprint.Tree.Lazy(ctx =>
    Iterator("root") ++ p.segments.iterator.map("/" + reprSection(_, ctx))
  )

  def commandResultRepr(x: CommandResult) = pprint.Tree.Lazy(ctx =>
    x.chunks.iterator.flatMap { chunk =>
      val (color, s) = chunk match{
        case Left(s) => (ctx.literalColor, s)
        case Right(s) => (fansi.Color.Red, s)
      }
      Iterator("\n", color(new String(s.array)).render)
    }
  )

  implicit val defaultHighlightColor = {
    ammonite.runtime.tools.GrepResult.Color(
      fansi.Color.Blue ++ fansi.Back.Yellow,
      fansi.Color.Yellow
    )
  }
}





© 2015 - 2025 Weber Informatics LLC | Privacy Policy