Julia: docstrings and LaTeX - julia

Julia has docstrings capabilities, which are documented here https://docs.julialang.org/en/stable/manual/documentation/. I'm under the impression that it has support for LaTeX code, but I'm not sure if the intention is that the LaTeX code should look like code or like an interpretation. In the following, the LaTeX code is garbled somewhat (see rho, for instance) and not interpreted (rho does not look like ρ). Am I doing something wrong?
Is there a way to get LaTeX code look interpreted?
What I mean by interpreted is something like what they do at https://math.stackexchange.com/.
The documentation says that LaTeX code should be wrapped around double back-quotes and that Greek letters should be typed as ρ rather than \rho. But that rather defeats the point of being able to include LaTeX code, doesn't it?
Note: Version 0.5.2 run in Juno/Atom console.
"""
Module blabla
The objective function is:
``\max \mathbb{E}_0 \int_0^{\infty} e^{-\rho t} F(x_t) dt``
"""
module blabla
end
If I then execute the module and query I get this:
With triple quotes, the dollar signs disappear, but the formula is printed on a dark background:
EDIT Follow-up to David P. Sanders' suggestion to use the Documenter.jl package.
using Documenter
doc"""
Module blabla
The objective function is:
$\max \mathbb{E}_0 \int_0^{\infty} e^{-\rho t} F(x_t) dt$
"""
module blabla
end
Gives the following: the LaTeX code appears to print correctly, but it's not interpreted (ρ is displayed as \rho. I followed suggestions in: https://juliadocs.github.io/Documenter.jl/stable/man/latex.html to

Rendering LaTeX code as actual equations has to be supported by whichever software renders your docstrings. So, the short answer to why you're not seeing any rendered equations in Juno is that LaTeX rendering is currently not supported in Juno (as Matt B. pointed out, there's an open issue for that).
The doc"" string literal / string macro is there to get around another issue. Backslashes and dollar signs normally have a special meaning in string literals -- escape sequences and variable interpolation, respectively (e.g. \n gets replaced by a newline character, $(variable) inserts the value of variable into the string). This, of course, clashes with the ordinary LaTeX commands and delimiters (e.g. \frac, $...$). So, to actually have backslashes and dollar signs in a string you need to escape them all with backslashes, e.g.:
julia> "\$\\frac{x}{y}\$" |> print
$\frac{x}{y}$
Not doing that will either give an error:
julia> "$\frac{x}{y}$" |> print
ERROR: syntax: invalid interpolation syntax: "$\"
or invalid characters in the resulting strings:
julia> "``\e^x``" |> print
``^x``
Having to escape everything all the time would, of course, be annoying when writing docstrings. So, to get around this, as David pointed out out, you can use the doc string macro / non-standard string literal. In a doc literal all standard escape sequences are ignored, so an unescaped LaTeX string doesn't cause any issues:
julia> doc"$\frac{x}{y}$" |> print
$$
\frac{x}{y}
$$
Note: doc also parses the Markdown in the string and actually returns a Base.Markdown.MD object, not a string, which is why the printed string is a bit different from the input.
Finally, you can then use these doc-literals as normal docstrings, but you can then freely use LaTeX syntax without having to worry about escaping everything:
doc"""
$\frac{x}{y}$
"""
function foo end
This is also documented in Documenter's manual, although it is not actually specific to Documenter.
Double backticks vs dollar signs. The preferred way to mark LaTeX in Julia docstrings or documentation is by using double backticks or ```math blocks, as documented in the manual. Dollar signs are supported for backwards compatibility.
Note: Documenter's manual and the show methods for Markdown objects in Julia should be updated to reflect this.

You can use
doc"""
...
"""
This is a "non-standard string literal" used by the Documenter.jl package; see https://docs.julialang.org/en/stable/manual/strings/#non-standard-string-literals.

Related

What do these characters mean?(ANSI Code)

It's the code I'm printing with node:
const m = `[38;5;1;48;5;16m TEST`
console.log(m)
output:
It changes the text color.
As you can see `` is a special char I don't understand(It's not being shown by the browser). How does it work?
Is there any alternative for ESC?
As #puucee already mentions they are terminal control characters. I find it surprising that it says ESC[ in the code as that won't be escaped in normal node. I suspect that maybe your IDE is converting the "true" escape character to ESC. Node does not support octal escapes (such as \033), but hexadecimal escapes. That is, you string should usually be like this:
console.log('\x1b[38;5;1;48;5;16m TEST \x1b[0m')
These are terminal control characters. They are often used e.g. for coloring the output. Some are non-printable. Backticks ` in your javascript example are called template literals.

can we use cartouches instead of quotation marks to delineate inner syntax in jEdit Isabelle/HOL sessions

In typing statements of a proof into an Isabelle (2020) theory file, e.g.,
from ‹prime p › have p: "1 < p "
the jEdit interface application pops up a tooltip offering to insert an open cartouche command \<open> when I type a quotation mark. As you can see in the line above, I have been allowing this and it seems to be permitted. The Isabelle documentation seems to view inner syntax as category embedded, which seems to permit delineation with quotation marks or with the cartouche enclosure \<open ... \<close>.
Is there a down side to doing this? The imports statement requires quoting a reference to a theory file "HOL-Computational_Algebra.Primes" with module.theory format and will not accept cartouche there, but in theory statements it certainly appears to be equivalent.
Cartouches vs quotes is currently a matter of style, except for imports, syntax definitions, and for some command arguments (like nitpick[eval=".."]).
Remark that some keyboard layouts make it possible to type them directly (e.g., mac US international).
I believe that Makarius would like to deprecate the quotes eventually. This would allow users to write "a" instead of ''a'' for strings). But don't expect that to happen anytime soon.
So: Write what you like most!

Does R 4.0.0. make it possible to define foo"(...)" operators, similar to the newly introduced r"(...)" syntax?

R 4.0.0 brings in a new syntax for raw strings:
r"(raw string here can contain anything except the closing sequence)"
But this same construct in R 3.x.x produced a syntax error:
Error: unexpected string constant in "r"(asdasd)""
Does it mean that the interpreter was changed in R 4.0.0. ?
And if so - does R 4.0.0. provide a mechanism to define custom functions like foo"()" ?
No, that's not possible at the moment (nor would I anticipate it becoming possible anytime soon).
Here's the NEWS item:
There is a new syntax for specifying raw character constants similar to the one used in C++: r"(...)" with ... any character sequence not containing the sequence )". This makes it easier to write strings that contain backslashes or both single and double quotes. For more details see ?Quotes.
https://cran.r-project.org/doc/manuals/r-devel/NEWS.html
Then from ?Quotes:
Raw character constants are also available using a syntax similar to
the one used in C++: r"(...)" with ... any character
sequence, except that it must not contain the closing sequence
)". The delimiter pairs [] and {} can also be
used, and R can be used in place of r. For additional
flexibility, a number of dashes can be placed between the opening quote
and the opening delimiter, as long as the same number of dashes appear
between the closing delimiter and the closing quote.
https://github.com/wch/r-source/blob/trunk/src/library/base/man/Quotes.Rd
Here's the (git mirror of the SVN patch of the) commit where this functionality was added:
https://github.com/wch/r-source/commit/8b0e58041120ddd56cd3bb0442ebc00a3ab67ebc

How to process latex commands in R?

I work with knitr() and I wish to transform inline Latex commands like "\label" and "\ref", depending on the output target (Latex or HTML).
In order to do that, I need to (programmatically) generate valid R strings that correctly represent the backslash: for example "\label" should become "\\label". The goal would be to replace all backslashes in a text fragment with double-backslashes.
but it seems that I cannot even read these strings, let alone process them: if I define:
okstr <- function(str) "do something"
then when I call
okstr("\label")
I directly get an error "unrecognized escape sequence"
(of course, as \l is faultly)
So my question is : does anybody know a way to read strings (in R), without using the escaping mechanism ?
Yes, I know I could do it manually, but that's the point: I need to do it programmatically.
There are many questions that are close to this one, and I have spent some time browsing, but I have found none that yields a workable solution for this.
Best regards.
Inside R code, you need to adhere to R’s syntactic conventions. And since \ in strings is used as an escape character, it needs to form a valid escape sequence (and \l isn’t a valid escape sequence in R).
There is simply no way around this.
But if you are reading the string from elsewhere, e.g. using readLines, scan or any of the other file reading functions, you are already getting the correct string, and no handling is necessary.
Alternatively, if you absolutely want to write LaTeX-like commands in literal strings inside R, just use a different character for \; for instance, +. Just make sure that your function correctly handles it everywhere, and that you keep a way of getting a literal + back. Here’s a suggestion:
okstr("+label{1 ++ 2}")
The implementation of okstr then needs to replace single + by \, and double ++ by + (making the above result in \label{1 + 2}). But consider in which order this needs to happen, and how you’d like to treat more complex cases; for instance, what should the following yield: okstr("1 +++label")?

julia to regex match lines in a file like grep

I would like to see a code snippet of julia that will read a file and return lines (string type) that match a regular expression.
I welcome multiple techniques, but output should be equivalent to the following:
$> grep -E ^AB[AJ].*TO' 'webster-unabridged-dictionary-1913.txt'
ABACTOR
ABATOR
ABATTOIR
ABJURATORY
I'm using GNU grep 3.1 here, and the first line of each entry in the file is the all caps word on its own.
You could also use the filter function to do this in one line.
filter(line -> ismatch(r"^AB[AJ].*TO",line),readlines(open("webster-unabridged-dictionary-1913.txt")))
filter applies a function returning a Boolean to an array, and only returns those elements of the array which are true. The function in this case is an anonymous function line -> ismatch(r"^AB[AJ].*TO",line)", which basically says to call each element of the array being filtered (each line, in this case) line.
I think this might not be the best solution for very large files as the entire file needs to be loaded into memory before filtering, but for this example it seems to be just as fast as the for loop using eachline. Another difference is that this solution returns the results as an array rather than printing each of them, which depending on what you want to do with the matches might be a good or bad thing.
My favored solution uses a simple loop and is very easy to understand.
julia> open("webster-unabridged-dictionary-1913.txt") do f
for i in eachline(f)
if ismatch(r"^AB[AJ].*TO", i) println(i) end
end
end
ABACTOR
ABATOR
ABATTOIR
ABJURATORY
notes
Lines with tab separations have the tabs preserved (no literal output of '\t')
my source file in this example has the dictionary words in all caps alone on one line above the definition; the complete line is returned.
the file I/O operation is wrapped in a do block syntax structure, which expresses an anonymous function more conveniently than lamba x -> f(x) syntax for multi-line functions. This is particularly expressive with the file open() command, defined with a try-finally-close operation when called with a function as an argument.
Julia docs: Strings/Regular Expressions
regex objects take the form r"<regex_literal_here>"
the regex itself is a string
based on perl PCRE library
matches become regex match objects
example
julia> reg = r"^AB[AJ].*TO";
julia> typeof(reg)
Regex
julia> test = match(reg, "ABJURATORY")
RegexMatch("ABJURATO")
julia> typeof(test)
RegexMatch
Just putting ; in front is Julia's way to using commandline commands so this works in Julia's REPL
;grep -E ^AB[AJ].*TO' 'webster-unabridged-dictionary-1913.txt'

Resources