Is there a way to include math formulae in Scaladoc?

后端 未结 4 1043
南方客
南方客 2021-01-01 23:03

I would like to enter math formulae in Scaladoc documentation of mathematical Scala code. In Java, I found a library called LatexTaglet that can do exactly this for Javadoc,

4条回答
  •  醉梦人生
    2021-01-01 23:45

    To follow on @mergeconflict answer, here is how I did it

    As there is no proper solution, what I did is to implement a crawler that parse all generated html files, and replace any found "import tag" (see code below), by the import of the MathJax script:

    lazy val mathFormulaInDoc  = taskKey[Unit]("add MathJax script import in doc html to display nice latex formula")
    
    mathFormulaInDoc := {
      val apiDir = (doc in Compile).value
      val docDir = apiDir    // /"some"/"subfolder"  // in my case, only api/some/solder is parsed
      // will replace this "importTag" by "scriptLine
      val importTag  = "##import MathJax"
      val scriptLine = ""
      // find all html file and apply patch
      if(docDir.isDirectory)
        listHtmlFile(docDir).foreach { f =>
          val content = Source.fromFile(f).getLines().mkString("\n")
            if(content.contains(importTag)) {
              val writer = new PrintWriter(f)
              writer.write(content.replace(importTag, scriptLine))
              writer.close()
            }
        }
    }
    
    // attach this task to doc task
    mathFormulaInDoc <<= mathFormulaInDoc triggeredBy (doc in Compile)
    
    // function that find html files recursively
    def listHtmlFile(dir: java.io.File): List[java.io.File] = {
      dir.listFiles.toList.flatMap { f =>
        if(f.getName.endsWith(".html")) List(f)
        else if(f.isDirectory)          listHtmlFile(f)
        else                            List[File]()
      }
    }
    

    As you could see, this crawler task is attached to the doc task, to it is done automatically by sbt doc.

    Here is an example of doc that will be rendered with formula

    /**
     * Compute the energy using formula:
     *
     * ##import MathJax
     *
     * $$e = m\times c^2$$
     */
    def energy(m: Double, c: Double) = m*c*c 
    

    Now, it would be possible to improve this code. For example:

    • add the script import in the html head section
    • avoid reading the whole files (maybe add a rule that the import tag should be in the first few lines
    • add the script to the sbt package, and add it to the target/api folder using some suitable task

提交回复
热议问题