How to embed Markdown in Scala code? - scala

I know that in Scala we have sbt plugins which allow us to execute code embedded in Markdown, plugins like tut and sbt-site. But how can we do the opposite? I would like to embed Markdown in Scala code as part of comments.
E.g.:
// number.sc file
// # Markdown code
// some text
1 + 1
//res0: Int = 2
And the code will than be converted to markdown.
Here is how you add numbers:
```scala
scala> 1 + 1
res0: Int = 2
```
Does someone know if something similar already exists?

Related

How to write Scala documentation with runnable snippets, similar to mdbook?

The Rust tool mdbook generates documentation from Markdown. It lets the reader edit and run Rust snippets directly in the browser by piping them to the Rust Playground. This lets you write readable documentation while letting your reader try out examples without cut-and-paste into a local editor. The Rust documentation uses this.
Is there anything like this for Scala? Scala has a playground (SCastie) so it seems the hard part has been dealt with. Perhaps there is a more general tool like gitbook that can do this by configuring SCastie as a backend?
Mdoc allows creating SCastie snippets out of your code.
From docs:
Before:
```scala mdoc:scastie
val x = 1 + 2
println(x)
```
After:
<script src="https://scastie.scala-lang.org/embedded.js"></script>
<pre class='scastie-snippet-2bc0b4f2-db76-4c68-8e7f-3a472d59c50d'></pre>
<script>window.addEventListener('load', function() {
scastie.Embedded('.scastie-snippet-2bc0b4f2-db76-4c68-8e7f-3a472d59c50d', {
code: `val x = 1 + 2
println(x)`,
theme: 'light',
isWorksheetMode: true,
targetType: 'jvm',
scalaVersion: '2.12.6'
})
})</script>
You can make scalafiddle snippets. See the documentation at https://github.com/scalafiddle/scalafiddle-core/blob/master/integrations/README.md

How to render a scalate template manually?

I want to try Scalate in this way:
Provide a scalate template, say: index.html
Use scala code to render it with some data manually
Any template format is OK(mustache, Scaml, SSP, Jade)
But I sad found nothing to do this even if I have read all the documentation and source code I found.
In order to make this question more clear, so I have such a template user.html:
<%# var user: User %>
<p>Hi ${user.name},</p>
#for (i <- 1 to 3)
<p>${i}</p>
#end
<p>See, I can count!</p>
I want to render it with a user instance User(name="Mike"). How to do it?
Suppose you have the following simple_example.mustache template:
I like {{programming_language}}
The code is {{code_description}}
You can render the template with this code:
import org.fusesource.scalate.TemplateEngine
val sourceDataPath = os.pwd/"simple_example.mustache".toString
val engine = new TemplateEngine
val someAttributes = Map(
"programming_language" -> "Scala",
"code_description" -> "pretty"
)
engine.layout(sourceDataPath, someAttributes)
Here's the result:
I like Scala
The code is pretty
Once you get past the initial learning hump, Scalate is actually pretty nice to work with (the docs don't make the lib easy to use).

How to define custom macros in MathJax

I'm trying to define custom macros used in LaTeX files in MathJax.
Can define simple macros (single parameter) without any issue such as;
\newcommand{\braket}[1]{\langle #1 \rangle}
as
Macros: {
braket: ['{\\langle #1 \\rangle}', 1]
}
But struggle with complicated ones;
\newcommand{\Abs}[2][]{\left\lvert#2\right\rvert_{\text{#1}}}
trying to define it like;
Macros: {
Abs: ['{\\left\\lvert#2\\rvert_{\\text{#1}}}', 2]
}
but no luck.
This is how it is used in LaTeX file
\begin{align}\nonumber
p_e = \Abs{\braket{e|\psi(t)}}^2 = \sin^2\Omega t\, .
\end{align}
Not sure where I did wrong.
I'm not a LaTeX expert, but just a developer trying to display LaTeX files on a web app (for Quantum Physics community), so I would greatly appreciate your help. thanks.
P.S this question was asked and closed on SE they redirected me to SO.
I've updated the codepen from my comment.
Primarliy, you forgot a \\right; I also modified your macro definition so that it has an optional parameter. In other words, something along the lines of:
Macros: {
braket: ['{\\langle #1 \\rangle}', 1],
Abs: ['\\left\\lvert #2 \\right\\rvert_{\\text{#1}}', 2, ""]
}},

How can I serve mostly static pages from a scala Play! application like an "About" page in different languages?

I am building an application using the Play! framework version 2.0.4. Some pages that are legally required such as an imprint mostly contain lots (some 10k each) of static text which I would like to provide in different languages.
In versions 1.x there was an #include directive that allowed to construct the actual resource path using the current Lang.
What is the recommended way of implementing sth similar with Play 2.x?
Thank you & best regards,
Erich
I'm not 100% certain how you implement it as of now, but here's what I've come up with.
You could just write your own include helper. Save the following in a file Helpers.scala in your views folder. Explanations are in the code's comments.
package views.html.helper
object include {
import play.api.templates.Html
import play.api.Play
import play.api.Play.current
import play.api.i18n._
// The default is to look in the public dir, but you can change it if necessary
def apply(filePath: String, rootDir: String = "public")(implicit lang: Lang): Html = {
// Split filePath at name and suffix to insert the language in between them
val (fileName, suffix) = filePath.splitAt(filePath.lastIndexOf("."))
// Retrieve the file with the current language, or as a fallback, without any suffix
val maybeFile =
Play.getExistingFile(rootDir + "/" + fileName + "_" + lang.language + suffix).
orElse(Play.getExistingFile(rootDir + "/" + filePath))
// Read the file's content and wrap it in HTML or return an error message
maybeFile map { file =>
val content = scala.io.Source.fromFile(file).mkString
Html(content)
} getOrElse Html("File Not Found")
}
}
Now in your imprint.scala.html you could call it like this:
#()(implicit lang: Lang)
#import helper._
#include("static/imprint.html")
Way showed by Schleichardt was used in play-authenticate to select mail templates in different languages and now it's changed to work with reflections on the controller, so maybe it can be interesting for you. Anyway it was intendent to keep standard templating possibilities (cause each mail need to be personalized before send)
For static info pages, you can just save the code for each language with suffix ie. impressum_en.html, impressum_de.html in the file system and use simple controller which will find file with proper suffix and return its content exactly as it is... all you need probably to return Ok(fileContent) and set the Content-Type manually to text/html.
Other option is doing the similar thing but storing it in the DB, so you can create simple back-end and edit it with browser.
If you still need to replace some elements, you can do it with some ###MARKER### in the code + simple String operations, or with JavaScript on the client side.
Templates in 2.0 work a bit differently. The Scala based templates are compiled. From one template instead of 'including' another, you can make a call to it. I'm not sure exactly what you mean by the language thing. In 2.0 though, a parameter to the template could be the language.
Example template named 'included' in package whateverpackage.
#(lang: Lang)
...
Example calling a template named 'included':
#import whateverpackage._
#included(Lang("en"))
#()(implicit lang: Lang)
#main(Messages("imprint")) {
#lang match {
case Lang("de", _) => { #germanImprint() #* uses app/views/germanImprint.scala.html file *#}
case _ => { #englishImprint() }
}
}

Can the Eclipse code style formatter align assignment statements?

Eclipse has an option in Indentation: "Alignment of fields in class declarations" that will
align assignments of class members as in:
class Foo {
int x = 3;
String y = "abc"
long z = 2;
}
Is there a setting that will do the same for method level assignments as in:
private void foo() {
int x = 3;
String y = "abc"
long z = 2;
}
I can not find such a setting.
Try creating a new Java Code Style Formatter profile (Window->Prefernces->Java->Code Style->Formatter) or modifying an older one and check Indentation and Braces tabs.
For future visitors.
There is no such option in Eclipse, but, as mentioned here, you can use plugin named OCDFormat that aligns assignments and declarations in a selected piece of code.
Installation: download the latest version of OCDFormat_*.jar from project page on github (click → Raw → Save as) and add it to your Eclipse plugins or dropins directory.
Usage: select a piece of code and press Ctrl+4.
The Eclipse code style formatter cannot align assignment statements.
columns4eclipse is plug-in that allows you to do so. I had made a gif video illustrating its use but my answer got deleted by a moderator (as >10k users will see), so I let you try the plug-in and see by yourself.