Roy Ivy III

Idylls, Invention, and Investigation

README.mkd example

Title (Raleway) {.–bordered-b}

Chapter · Intro {.–bordered-b #intro}

This file utilizes markdown syntax (specifically, a compatible intersection of CommonMark and pandoc markdown).

See also https://gist.github.com/dupuy/1855764 for information regarding various Markdown flavors vs reStructured Text.

markdown-render{.bordered-b}^1

For display of local markdown files, markdown-render, a javascript “user script”, is used to dynamically render the markdown into a fully styled page.

markdown-render uses markdown-it (including definition lists, footnote and pandoc attribute plugins) to render the CommonMark formatted source. markdown-it is configured as ‘default’ mode instead of ‘commonmark’ so that the markdown for special typography (eg, em-dashes (—), en-dashes (–), and ellipses (…)) is recognized and rendered. The ‘typographer’ setting is also enabled to produce “smart quotes”.

pandoc

The pandoc executable may be used (along with MiKTeX / XeLaTeX; install via scoop install latex) to render the file into other formats, such as PDF, eg:

{.shell .no-line-numbers .line-wrapping .breaklines #pandoc.exe}
1
pandoc.exe -o "FILE.pdf" "FILE.md" --standalone --latex-engine=xelatex -V documentclass=scrartcl -V geometry:paperwidth=7.5in -V geometry:paperheight=10in -V geometry:top=0.75in -V geometry:left=1in -V fontsize=11pt -V linkcolor="[RGB]{255,127,0}" --highlight-style haddock --smart

Section · Limitations and Annoyances

Firefox reports an error in the Console when running javascript on the plain text file …

The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature.

Unfortunately, neither <meta http-equiv="Content-Type" content="text/plain; charset=utf-8" /> nor <meta charset="utf-8"/> can be used to inform Firefox that the file is in UTF-8 format. If used, either notation causes Firefox to interpret the page as an HTML/XML document, and irretrievably modifies the original plain text content, causing artifacts in the later markdown render.

This means, if the file uses any UTF-8 characters out of the ANSI range that they will not be displayed correctly, unless the file is saved with a UTF BOM. So, if using such characters, the markdown file must be saved with a BOM for correct interpretation and rendering.

NOTE: this has now been remedied by coercing Firefox to re-read the original source and rebuild a page that more closely resembles the (arguably, more correct) page that Chrome constructs from the same source. This should be brought to the attention of Mozilla to fix this (IMO) “bug”.

Section: Code { #code }

Code can be written inline (eg, return ((my $max < 100 ) ? 100 : $max{.perl .language-perl data-theme=”monokai”}), or as a code block using markdown “code fences”.

This “code fence” written in markdown …

1
2
3
4
5
6
7
8
9
~~~~ {.perl .language-perl #listing-1.1 .numberLines startFrom=50}
sub random_int_between {
my ($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}
~~~~

or, equivalently, in HTML …

1
2
3
4
5
6
7
8
<pre id="listing-1.1" class="language-perl perl numberLines" startFrom=50><code class="language-perl">sub random_int_between {
my ($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}
</code></pre>

is rendered as …

.language-perl #listing-1.1 .numberLines startFrom
1
2
3
4
5
6
7
sub random_int_between {
my ($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}

Here listing-1.1 is an HTML identifier (aka, bookmark), perl and numberLines are classes, and startFrom is an attribute with the value 50. Some output formats can use this information to do syntax highlighting. Currently, the only output formats that uses this information are HTML and LaTeX.

If highlighting is supported for your output format and language, then the code block above will appear highlighted. (To see which languages are supported, do pandoc --version.) Otherwise, the code block above will appear as follows:

#listing-2.1 .numberLines startFrom
1
2
3
4
5
6
7
sub random_int_between {
my ($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}

.language-haskell #listing-1.2 .numberLines startFrom
1
2
3
qsort []     = []
qsort (x:xs) = qsort (filter ( < x) xs) ++ [x] ++
qsort (filter (>= x) xs)

Optionally, you may attach attributes, including HTML attributes such as style="background:inherit", to the code block using pandoc-type attribute syntax:

  • install vsftpd

    .language-bash}
    1
    sudo apt-get install vsftpd

Indented code block using a block quote…

{.perl .language-perl #listing-1.3 .numberLines .line-numbers startFrom
1
2
3
4
5
6
7
sub random_int_between {
my ($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}

Otherwise, the code block above will appear as follows:

1
2
3
4
5
6
7
sub random_int_between {
my ($min, $max) = @_;
# Assumes that the two arguments are integers themselves!
return $min if $min == $max;
($min, $max) = ($max, $min) if $min > $max;
return $min + int rand(1 + $max - $min);
}

Indenting a code block using a block quote…

1
2
3
qsort []     = []
qsort (x:xs) = qsort (filter ( < x) xs) ++ [x] ++
qsort (filter (>= x) xs)

Listing-2.2 A haskell code snippet
{ style=”margin:0” }

or, in a table:

 

Listing-2.5 : Python
.no-border style
1
2
3
4
5
6
import time
# Quick, count to ten!
for i in range(10):
# (but not *too* quick)
time.sleep(0.5)
print i

(which makes copying & pasting easier).

NOTE: the ““ causes pandoc to disregard the table as it has no support for colspan, at this time.

You can optionally mark the delimited block for Pandoc to syntax highlight it:

1
2
3
4
5
6
7
# Listing: EX-3.1
import time
# Quick, count to ten!
for i in range(10):
# (but not *too* quick)
time.sleep(0.5)
print i

… now Table-3.2:

Table-3.2 · Python code listing
{.no-border}
1
2
3
4
5
6
7
# Listing: EX-3.2
import time
# Quick, count to ten!
for i in range(10):
# (but not *too* quick)
time.sleep(0.5)
print i

CMD shell · C:\>{.–monospace}
{style=”margin:0;”}

batch
{style=”margin:0; color: black; font-size: 0.8rem;”}

{ data-lang
1
2
3
@setlocal
cd "%TEMP%"
mkdir "t1"

Testing

1
[rectangle setX: 10 y: 10 width: 20 height: 20];
1
$x = 10
1
2
3
// some code
int c = 10;
for ...

next/_config.yml
1
2
# Console reminder if new version released.
reminder: false

C code {.bordered-b}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void wc (FILE *fp)
//void wc (FILE *fp)
{
int c = NUL, lastc, state;
const int INWord = 1;
const int OUTWord = 0;

charCount = wordCount = lineCount = 0;

state = OUTWord;
while (EOF != (lastc = c, c = getc(fp))) {
if ('\n' != c) ++charCount;
else ++lineCount;
if (' ' == c || '\n' == c || '\t' == c) state = OUTWord;
else if (OUTWord == state) {
state = INWord;
++wordCount;
}
}
if (('\n' != lastc) && (charCount>0)) ++lineCount;
}

C# code { .bordered-b }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections;
using System.Collections.Generic;
static class CharStrExtMethods {
public static int[] FindAll(this string matchStr, string searchedStr, int startPos) {
int foundPos = -1; // -1 represents not found.
int count = 0;
List<int> foundItems = new List<int>();
do {
foundPos = searchedStr.IndexOf(matchStr, startPos, StringComparison. Ordinal);
if (foundPos > -1) {
startPos = foundPos + 1;
count++;
foundItems.Add(foundPos);
Console.WriteLine("Found item at position: " + foundPos. ToString());
}
} while (foundPos > -1 && startPos < searchedStr.Length);
return ((int[])foundItems.ToArray());
}
}

Erlang

1
2
3
4
area({square, Side}) ->  Side * Side ;
area({circle, Radius}) -> math:pi() * Radius * Radius;
area({triangle, A, B, C}) -> S = (A + B + C)/2, math:sqrt(S*(S-A)*(S-B)*(S-C));
area(Other) -> {error, invalid_object}.

An h1 header

Paragraphs are separated by a blank line.

2nd paragraph. Italic, bold, monospace. Itemized lists
look like:

  • this one
  • that one
  • the other one

Note that — not considering the asterisk — the actual text
content starts at 4-columns in.

Block quotes are
written like so.

They can span multiple paragraphs,
if you like.

Use 3 dashes for an em-dash. Use 2 dashes for ranges (ex. “it’s all in
chapters 12–14”). Three dots … will be converted to an ellipsis.

An h2 header {.no-break}

Here’s a numbered list:

  1. first item
  2. second item
  3. third item

Note again how the actual text starts at 4 columns in (4 characters
from the left side). Here’s a code sample:

# Let me re-iterate ...
for i in 1 .. 10 { do-something(i) }

As you probably guessed, indented 4 spaces. By the way, instead of
indenting the block, you can use delimited blocks, if you like:

1
2
3
define foobar() {
print "Welcome to flavor country!";
}

(which makes copying & pasting easier). You can optionally mark the
delimited block for Pandoc to syntax highlight it:

1
2
3
4
5
6
import time
# Quick, count to ten!
for i in range(10):
# (but not *too* quick)
time.sleep(0.5)
print i

An h3 header

Now a nested list:

  1. First, get these ingredients:

    • carrots
    • celery
    • lentils
  2. Boil some water.

  3. Dump everything in the pot and follow
    this algorithm:

    find wooden spoon
    uncover pot
    stir
    cover pot
    balance wooden spoon precariously on pot handle
    wait 10 minutes
    goto first step (or shut off burner when done)
    

    Do not bump wooden spoon or it will fall.

Notice again how text always lines up on 4-space indents (including that last line which
continues item 3 above).
Here’s a link to a website.
Here’s a link to a local doc.

Here’s a footnote.[^2]

[^2]: Footnote text goes here.

1
2
my $x = $y;
say "$x";

Tables can look like this:

size material color
9 leather brown
10 hemp canvas natural
11 glass transparent

or, being modified with HTML attributes (eg, styles or classes with associated styles), like this:

size material color
9 leather brown
10 hemp canvas natural
11 glass transparent
[Shoes, their sizes, and what they’re made of]
{.width-100percent}

(The above is the caption for the table.) Here’s a definition list:

apples
: reddish
: Good for making applesauce

oranges
: Citrus!

tomatoes
: There’s no “e” in tomatoe

Again, text is indented 4 spaces. (Alternately, put blank lines in
between each of the above definition list lines to spread things
out more.)

size material color
9 leather brown
10 hemp canvas natural
11 glass transparent
{style=”width:90%; margin-left: auto; margin-right: auto;”}

Section: Math

$$ |x| = \left( y \cdot z \right) $$


Use a <div> followed immediately by the LaTeX disables markdown interpretation and avoids the need to escape backslashes with the markdown (eg, requiring four backslashes for \\; causing double interpretation for pandoc). This method works identically for both pandoc and markdown …

$$ \begin{aligned} e^{\pi i} + 1 &= 0 \\ 2x - 5y &= 8 \\ 3x + 9y &= -12 \end{aligned} $$

$$ \begin{array}{lcr} {First\ number} & x & 8 \\ {Second\ number} & y & 15 \\ {Sum} & x + y & 23 \\ {Difference} & x - y & -7 \\ {Product} & xy & 120 \end{array} $$

$$\begin{aligned} \frac{1}{\Bigl(\sqrt{\phi \sqrt{5}}-\phi\Bigr) e^{\frac25 \pi}} \equiv 1+\frac{e^{-2\pi}} {1+\frac{e^{-4\pi}} {1+\frac{e^{-6\pi}} {1+\frac{e^{-8\pi}} {1+\cdots} } } } \end{aligned}$$

$$ \left[ \begin{array}{c|c} \epsilon' [T|_A]\epsilon & \ast \\ 0 & _{\overline{B}'} [\overline{T}] _{\overline{B}{\overline{B}'}} \end{array} \right] $$

LaTeX tables (ref: https://github.com/mathjax/MathJax-docs/wiki/LaTeX-Tabular-environment[@]):

$$ \begin{array}{|c|c|} X & P(X = i) \\ 1 & 1/6 \\ 2 & 1/6 \\ 3 & 1/6 \\ 4 & 1/6 \\ 5 & 1/6 \\ 6 & 1/6 \end{array} $$

Various versions of MathJax can’t handle single $ signal characters, so, the enclosing token set [${, }$] (eg, ${}$) is used as a hack-ish method of implementing inline LaTeX that works for both pandoc and markdown (with math extensions). As LaTeX ignores surrounding brackets in math equations[^latex-surrounding-brackets], using ${}$ for inline math and $${}$$ for block math is fully compatible between pandoc and MathJax.

[^latex-surrounding-brackets]: LaTeX ignores the surrounding brackets in a math equation; [@{style=”background:none; padding:0”}].

Alternatively, $\phantom{}\phantom{}$ is also cross-compatible and may be used (eg, $\phantom{}\frac{d}{dx}\left(\int_{0}^{x}f(u){\small \Delta}du\right)=f(x)\phantom{}${.stex} => $\phantom{}\frac{d}{dx}\left(\int_{0}^{x}f(u){\small \Delta}du\right)=f(x)\phantom{}$).

It is possible that KaTeX may offer a more compatible solution when/if the no quirks mode issue is resolved.

Other LaTeX formulas: $\phantom{}\frac{d}{dx}\left(\int_{0}^{x}f(u){\small \Delta}du\right)=f(x)\phantom{}$

or (with ${}$): ${\frac{d}{dx}\left(\int_{0}^{x}f(u){\small \Delta}du\right)=f(x)}$

Inline math equations go in like so… $\phantom{}\omega = d\phi / dt\phantom{}$. Display
math should get its own line and be put in in double-dollar-signs:

$$ I = \int \rho R^{2} dV $$

$ x = 10 $

This is some math ($ x = 10 $ , $$ x = 10 $$) as well.

$$
\frac{1}{\displaystyle 1+
\frac{1}{\displaystyle 2+
\frac{1}{\displaystyle 3+x}}} +
\frac{1}{1+\frac{1}{2+\frac{1}{3+x}}}
$$

End of math.

markdown-render

markdown-render is a user javascript, running in-browser, which automatically renders raw local markdown files (eg, “file://PATH/TO/file.mkd”) into HTML.

Setup

  1. Setup the browser userscript manager

  2. Enable TamperMonkey scripting of file URLs

    • Chrome
      1. open “chrome://extensions”
      2. for the TamperMonkey extension, ENABLE the “Allow access to file URLs” option
    • Firefox … not needed
  3. Install the markdown-render userscript

    1. open https://github.com/rivy/js-user.markdown-render/raw/master/markdown-render.user.js
    2. CLICK “Install” in the TamperMonkey installation dialog

Known Limitations

Incorrect interpretation of files with initial HTML tags

  • TLDR; when possible, use YAML front matter prior to, or <!DOCTYPE markdown> as the initial content of, all markdown files.

While most markdown files are correctly interpreted, those with leading HTML tags are problematic. Both Chrome and Firefox will interpret and parse a file as HTML if it contains an initial HTML tag, even if the file extension is not “.htm” or “.html”. This interpretation and parsing of the file happens during loading and results in an irretrievable garbling of file contents and a subsequent inability to correctly render the file.

Firefox can be coerced into re-reading the file as text, but Chrome can not. So, valid markdown files with leading HTML elements will be misinterpreted by Chrome.

A “workaround” is to always use initial content without HTML elements, such as a DOCTYPE declaration (eg, <!DOCTYPE markdown> [uppercase ‘DOCTYPE’ preferred for widest compatibility]). A DOCTYPE declaration works for all browsers and is completely valid markdown. Alternatively, using YAML front matter elements will also prevent the destructive interpretation of the file as purely HTML.

Edge isn’t usable

  • TLDR; use Chrome or Firefox as default handlers for files with markdown file extensions.

MS Edge won’t open and render local files, except for files with specific extensions (eg, “.html”). And there is no current method to enable reading and rendering of new file types / extensions (eg, all the markdown extensions). So, while the script may actually work, it’s impossible to test or use at this moment. If a markdown file is opened, it will be pushed to whichever application is setup as the default handler. Luckily, either of the more capable Chrome or Firefox browsers can be set as the default handler for files with the various markdown extensions, which ultimately solves the problem.

Conventions Used in This Book

The following typographical conventions are used in this book:

Plain text

Indicates menu titles, menu options, menu buttons, keyboard accelerators (such as Alt and Ctrl), plugins, gems, and libraries.

Italic

Indicates new terms, URLs, email addresses, filenames, file extensions, path names, directories, controls, and Unix utilities.

Constant width

Indicates commands, options, switches, variables, attributes, keys, functions, types, classes, namespaces, methods, modules, properties, parameters, values, objects, events, event handlers, interfaces, XML tags, HTML tags, macros, the contents of files, or the output from commands.

Constant width italic

Shows text that should be replaced with user-supplied values.

Constant width bold

Used to highlight portions of code.

Done.