Zulip Chat Archive

Stream: lean4

Topic: Syntax.prettyPrint has lots of space


James Gallicchio (Apr 30 2024 at 18:57):

mwe:

import Lean

unsafe def main : IO Unit := do
  let syn : Except _ Lean.Syntax  Lean.withImportModules
    (imports := #[])
    (opts := default)
    (trustLevel := 0)
    <| fun env => EIO.toIO' <|
    Lean.Core.CoreM.run'
      (ctx := {
        fileName := "Example.lean"
        fileMap := default
      })
      (s := {
        env
      })
      (Lean.liftCommandElabM <| do
        `(def hi (x : Int) := sorry))
  match syn with
  | .error exc =>
    IO.println ( exc.toMessageData.toString)
  | .ok syn =>
  IO.println (syn.prettyPrint.pretty)

#eval main
-- def  hi  (  x  :  Int  )  :=  sorry

Is there some way I can prettyprint the syntax without so much extra whitespace?

Eric Wieser (Apr 30 2024 at 20:14):

There's a better function inside the PrettyPrinter namespace

James Gallicchio (Apr 30 2024 at 21:52):

aha, thanks!

updated MWE for my own future reference:

import Lean

unsafe def main : IO Unit := do
  let syn : Except _ Lean.Format  Lean.withImportModules
    (imports := #[])
    (opts := default)
    (trustLevel := 0)
    <| fun env => EIO.toIO' <|
    Lean.Core.CoreM.run'
      (ctx := {
        fileName := "Example.lean"
        fileMap := default
      })
      (s := {
        env
      })
      (do
        let opt  Lean.liftCommandElabM (do
          let int := Lean.mkIdent ``Unit
          `(opaque hi (x : $int) : $int))
        Lean.PrettyPrinter.formatCommand opt
      )
  match syn with
  | .error exc =>
    IO.println ( exc.toMessageData.toString)
  | .ok syn =>
  IO.println (syn.pretty)

#eval main --opaque hi.1 (x.1 : Unit) : Unit

Last updated: May 02 2025 at 03:31 UTC