Skip to content

Instantly share code, notes, and snippets.

@lihaoyi
Last active April 10, 2019 23:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lihaoyi/7e6c429bf0c18465479450c0a351e8f5 to your computer and use it in GitHub Desktop.
Save lihaoyi/7e6c429bf0c18465479450c0a351e8f5 to your computer and use it in GitHub Desktop.
Scala.js pprint debug
def debug[T](value: sourcecode.Text[T], tag: String = "")
(implicit pprinter: pprint.PPrint[T],
path: sourcecode.Enclosing,
line: sourcecode.Line,
cfg: Config = pprint.Config.Colors.PPrintConfig)= {
val titleIter = path.value.split(" |#|\\.").filter(!_.contains("$")).last
val tagIter =
if (tag == "") ""
else " " + pprint.tokenize(tag).mkString
val lineIter = ":" + pprint.tokenize(line.value).mkString
val valName = value.source
val item = pprint.tokenize(value.value).mkString
val wholeStr =
cfg.colors.prefixColor(titleIter + tagIter).render +
lineIter + " " + valName + "\t" + item
val replaced = fansi.Str.ansiRegex.matcher(wholeStr).replaceAll("%c")
val m = fansi.Str.ansiRegex.matcher(wholeStr)
val styleList = mutable.Buffer.empty[js.Any]
while(m.find()){
styleList.append(
wholeStr.substring(m.start(), m.end) match{
case Console.RED => "color: red"
case Console.GREEN => "color: green"
case Console.BLUE => "color: blue"
case Console.YELLOW => "color: orange"// yellow is too bright
case Console.MAGENTA => "color: magenta"
case Console.CYAN => "color: cyan"
case _ => "color: black"
}
)
}
dom.console.log(replaced, styleList:_*)
}

example

Scala.js pprint debug: a short snippet to let you use pprint's pretty colored, formatted pretty-printing in the chrome console, with Scala.js.

Normally PPrint's pprint.log method this only works in the ANSI terminal since it uses ANSI color codes, but with some regexes we can easily transform those ANSI color codes into Chrome's CSS-colored console-logging format.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment