` tags in the HTML output. For example, this input:
* Bird
* Magic
will turn into:
It's worth noting that it's possible to trigger an ordered list by
accident, by writing something like this:
1986. What a great season.
In other words, a *number-period-space* sequence at the beginning of a
line. To avoid this, you can backslash-escape the period:
1986\. What a great season.
Code Blocks
Pre-formatted code blocks are used for writing about programming or
markup source code. Rather than forming normal paragraphs, the lines
of a code block are interpreted literally. Markdown wraps a code block
in both `` and `` tags.
To produce a code block in Markdown, simply indent every line of the
block by at least 4 spaces or 1 tab. For example, given this input:
This is a normal paragraph:
This is a code block.
Markdown will generate:
This is a normal paragraph:
This is a code block.
One level of indentation -- 4 spaces or 1 tab -- is removed from each
line of the code block. For example, this:
Here is an example of AppleScript:
tell application "Foo"
beep
end tell
will turn into:
Here is an example of AppleScript:
tell application "Foo"
beep
end tell
A code block continues until it reaches a line that is not indented
(or the end of the article).
Within a code block, ampersands (`&`) and angle brackets (`<` and `>`)
are automatically converted into HTML entities. This makes it very
easy to include example HTML source code using Markdown -- just paste
it and indent it, and Markdown will handle the hassle of encoding the
ampersands and angle brackets. For example, this:
will turn into:
<div class="footer">
© 2004 Foo Corporation
</div>
Regular Markdown syntax is not processed within code blocks. E.g.,
asterisks are just literal asterisks within a code block. This means
it's also easy to use Markdown to write about Markdown's own syntax.
Horizontal Rules
You can produce a horizontal rule tag (` `) by placing three or
more hyphens, asterisks, or underscores on a line by themselves. If you
wish, you may use spaces between the hyphens or asterisks. Each of the
following lines will produce a horizontal rule:
* * *
***
*****
- - -
---------------------------------------
* * *
Span Elements
Links
Markdown supports two style of links: *inline* and *reference*.
In both styles, the link text is delimited by [square brackets].
To create an inline link, use a set of regular parentheses immediately
after the link text's closing square bracket. Inside the parentheses,
put the URL where you want the link to point, along with an *optional*
title for the link, surrounded in quotes. For example:
This is [an example](http://example.com/ "Title") inline link.
[This link](http://example.net/) has no title attribute.
Will produce:
This is
an example inline link.
This link has no
title attribute.
If you're referring to a local resource on the same server, you can
use relative paths:
See my [About](/about/) page for details.
Reference-style links use a second set of square brackets, inside
which you place a label of your choosing to identify the link:
This is [an example][id] reference-style link.
You can optionally use a space to separate the sets of brackets:
This is [an example] [id] reference-style link.
Then, anywhere in the document, you define your link label like this,
on a line by itself:
[id]: http://example.com/ "Optional Title Here"
That is:
* Square brackets containing the link identifier (optionally
indented from the left margin using up to three spaces);
* followed by a colon;
* followed by one or more spaces (or tabs);
* followed by the URL for the link;
* optionally followed by a title attribute for the link, enclosed
in double or single quotes, or enclosed in parentheses.
The following three link definitions are equivalent:
[foo]: http://example.com/ "Optional Title Here"
[foo]: http://example.com/ 'Optional Title Here'
[foo]: http://example.com/ (Optional Title Here)
**Note:** There is a known bug in Markdown.pl 1.0.1 which prevents
single quotes from being used to delimit link titles.
The link URL may, optionally, be surrounded by angle brackets:
[id]: "Optional Title Here"
You can put the title attribute on the next line and use extra spaces
or tabs for padding, which tends to look better with longer URLs:
[id]: http://example.com/longish/path/to/resource/here
"Optional Title Here"
Link definitions are only used for creating links during Markdown
processing, and are stripped from your document in the HTML output.
Link definition names may constist of letters, numbers, spaces, and
punctuation -- but they are *not* case sensitive. E.g. these two
links:
[link text][a]
[link text][A]
are equivalent.
The *implicit link name* shortcut allows you to omit the name of the
link, in which case the link text itself is used as the name.
Just use an empty set of square brackets -- e.g., to link the word
"Google" to the google.com web site, you could simply write:
[Google][]
And then define the link:
[Google]: http://google.com/
Because link names may contain spaces, this shortcut even works for
multiple words in the link text:
Visit [Daring Fireball][] for more information.
And then define the link:
[Daring Fireball]: http://daringfireball.net/
Link definitions can be placed anywhere in your Markdown document. I
tend to put them immediately after each paragraph in which they're
used, but if you want, you can put them all at the end of your
document, sort of like footnotes.
Here's an example of reference links in action:
I get 10 times more traffic from [Google] [1] than from
[Yahoo] [2] or [MSN] [3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
Using the implicit link name shortcut, you could instead write:
I get 10 times more traffic from [Google][] than from
[Yahoo][] or [MSN][].
[google]: http://google.com/ "Google"
[yahoo]: http://search.yahoo.com/ "Yahoo Search"
[msn]: http://search.msn.com/ "MSN Search"
Both of the above examples will produce the following HTML output:
I get 10 times more traffic from Google than from
Yahoo
or MSN .
For comparison, here is the same paragraph written using
Markdown's inline link style:
I get 10 times more traffic from [Google](http://google.com/ "Google")
than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or
[MSN](http://search.msn.com/ "MSN Search").
The point of reference-style links is not that they're easier to
write. The point is that with reference-style links, your document
source is vastly more readable. Compare the above examples: using
reference-style links, the paragraph itself is only 81 characters
long; with inline-style links, it's 176 characters; and as raw HTML,
it's 234 characters. In the raw HTML, there's more markup than there
is text.
With Markdown's reference-style links, a source document much more
closely resembles the final output, as rendered in a browser. By
allowing you to move the markup-related metadata out of the paragraph,
you can add links without interrupting the narrative flow of your
prose.
Emphasis
Markdown treats asterisks (`*`) and underscores (`_`) as indicators of
emphasis. Text wrapped with one `*` or `_` will be wrapped with an
HTML `` tag; double `*`'s or `_`'s will be wrapped with an HTML
`` tag. E.g., this input:
*single asterisks*
_single underscores_
**double asterisks**
__double underscores__
will produce:
single asterisks
single underscores
double asterisks
double underscores
You can use whichever style you prefer; the lone restriction is that
the same character must be used to open and close an emphasis span.
Emphasis can be used in the middle of a word:
un*fucking*believable
But if you surround an `*` or `_` with spaces, it'll be treated as a
literal asterisk or underscore.
To produce a literal asterisk or underscore at a position where it
would otherwise be used as an emphasis delimiter, you can backslash
escape it:
\*this text is surrounded by literal asterisks\*
Code
To indicate a span of code, wrap it with backtick quotes (`` ` ``).
Unlike a pre-formatted code block, a code span indicates code within a
normal paragraph. For example:
Use the `printf()` function.
will produce:
Use the printf()
function.
To include a literal backtick character within a code span, you can use
multiple backticks as the opening and closing delimiters:
``There is a literal backtick (`) here.``
which will produce this:
There is a literal backtick (`) here.
The backtick delimiters surrounding a code span may include spaces --
one after the opening, one before the closing. This allows you to place
literal backtick characters at the beginning or end of a code span:
A single backtick in a code span: `` ` ``
A backtick-delimited string in a code span: `` `foo` ``
will produce:
A single backtick in a code span: `
A backtick-delimited string in a code span: `foo`
With a code span, ampersands and angle brackets are encoded as HTML
entities automatically, which makes it easy to include example HTML
tags. Markdown will turn this:
Please don't use any `` tags.
into:
Please don't use any <blink>
tags.
You can write this:
`—` is the decimal-encoded equivalent of `—`.
to produce:
—
is the decimal-encoded
equivalent of —
.
Images
Admittedly, it's fairly difficult to devise a "natural" syntax for
placing images into a plain text document format.
Markdown uses an image syntax that is intended to resemble the syntax
for links, allowing for two styles: *inline* and *reference*.
Inline image syntax looks like this:


That is:
* An exclamation mark: `!`;
* followed by a set of square brackets, containing the `alt`
attribute text for the image;
* followed by a set of parentheses, containing the URL or path to
the image, and an optional `title` attribute enclosed in double
or single quotes.
Reference-style image syntax looks like this:
![Alt text][id]
Where "id" is the name of a defined image reference. Image references
are defined using syntax identical to link references:
[id]: url/to/image "Optional title attribute"
As of this writing, Markdown has no syntax for specifying the
dimensions of an image; if this is important to you, you can simply
use regular HTML ` ` tags.
* * *
Miscellaneous
Automatic Links
Markdown supports a shortcut style for creating "automatic" links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:
Markdown will turn this into:
http://example.com/
Automatic links for email addresses work similarly, except that
Markdown will also perform a bit of randomized decimal and hex
entity-encoding to help obscure your address from address-harvesting
spambots. For example, Markdown will turn this:
into something like this:
address@exa
mple.com
which will render in a browser as a clickable link to "address@example.com".
(This sort of entity-encoding trick will indeed fool many, if not
most, address-harvesting bots, but it definitely won't fool all of
them. It's better than nothing, but an address published in this way
will probably eventually start receiving spam.)
Backslash Escapes
Markdown allows you to use backslash escapes to generate literal
characters which would otherwise have special meaning in Markdown's
formatting syntax. For example, if you wanted to surround a word with
literal asterisks (instead of an HTML `` tag), you can backslashes
before the asterisks, like this:
\*literal asterisks\*
Markdown provides backslash escapes for the following characters:
\ backslash
` backtick
* asterisk
_ underscore
{} curly braces
[] square brackets
() parentheses
# hash mark
+ plus sign
- minus sign (hyphen)
. dot
! exclamation mark
maruku-0.6.0/docs/other_stuff.md 0000644 0001750 0001750 00000003672 11573154515 016540 0 ustar vincent vincent * *Jan. 22* With very minimal changes, Maruku now works in JRuby.
It is very slow, though.
Some benchmarks:
* G4 1.5GhZ, Ruby 1.8.5:
Maruku (to_html): parsing 0.65 sec + rendering 0.40 sec = 1.04 sec
Maruku (to_latex): parsing 0.70 sec + rendering 0.21 sec = 0.91 sec
* G4 1.5GhZ, JRuby 1.9.2:
Maruku (to_html): parsing 4.77 sec + rendering 2.24 sec = 7.01 sec
Maruku (to_latex): parsing 4.04 sec + rendering 1.12 sec = 5.16 sec
* *Jan. 21* Integration of Blahtex. PNG export of formula and alignment works
ok in Mozilla, Safari, Camino, Opera. IE7 is acting strangely.
* Support for LaTeX-style formula input, and export to MathML.
[Jacques Distler] is integrating Maruku into Instiki (a Ruby On Rails-based wiki software), as to have a Ruby wiki with proper math support. You know, these physicists like all those funny symbols.
* To have the MathML export, it is needed to install one of:
* [RiTeX] (`gem install ritex`)
* [itex2MML] supports much more complex formulas than Ritex.
* PNG for old browser is not here yet. The plan is to use
BlahTeX.
* Command line options for the `maruku` command:
Usage: maruku [options] [file1.md [file2.md ...
-v, --[no-]verbose Run verbosely
-u, --[no-]unsafe Use unsafe features
-b Break on error
-m, --math-engine ENGINE Uses ENGINE to render MathML
--pdf Write PDF
--html Write HTML
--tex Write LaTeX
--inspect Shows the parsing result
--version Show version
-h, --help Show this message
* Other things:
* Created the embryo of an extension system. Please don't use it
yet, as probably the API is bound to change.
* There are a couple of hidden, unsafe, features that are not enabled by default.
maruku-0.6.0/docs/math.md 0000644 0001750 0001750 00000010353 11573154515 015133 0 ustar vincent vincent Title: Math support in Maruku
LaTeX preamble: math_preamble.tex
LaTeX use listings: true
CSS: math.css style.css
use numbered headers: true
Math support in Maruku
======================
This document describes Maruku's support of inline LaTeX-style math.
At the moment, **these features are experimental**, are probably
buggy and the syntax and implementation are bound to change in
the near future.
Also, there are many subtleties of which one must care for
correctly serving the XHTML+MathML document to browsers.
In fact, *this documentation is __not__ enough to get you started*,
unless you feel very adventurous.
* toc
{:toc}
Syntax
---------------------------------------
### Inline math
Inline math is contained inside couples of `$`.
Everything inside will be passed as-is to LaTeX: no Markdown
interpretation will take place.
Example: $x^{n}+y^{n} \neq z^{n}$ for $n \geq 3$
> Example: $x^{n}+y^{n} \neq z^{n}$ for $n \geq 3$
### Equations
Equations are specified using either the `$$ ... $$` or `\[ ... \]`
LaTeX notation. Equations can span multiple lines.
\[
\sum_{n=1}^\infty \frac{1}{n}
\text{ is divergent, but }
\lim_{n \to \infty} \sum_{i=1}^n \frac{1}{i} - \ln n \text{exists.}
\]
> \[
> \sum_{n=1}^\infty \frac{1}{n}
> \text{ is divergent, but }
> \lim_{n \to \infty} \sum_{i=1}^n \frac{1}{i} - \ln n \quad \text{exists.}
> \]
Some random AMSTeX symbols:
$$ \beth \Subset \bigtriangleup \bumpeq \ggg \pitchfork $$
$$ \beth \Subset \bigtriangleup \bumpeq \ggg \pitchfork $$
## Cross references ## {#cross}
Create a label for an equation in two ways:
* LaTeX style:
Consider \eqref{a}:
$$ \alpha = \beta \label{a} $$
* More readable style:
Consider (eq:a):
$$ \alpha = \beta $$ (a)
You can mix the two.
Labels will work as expected also in the PDF output, whatever
style you use: Maruku will insert the necessary `\label` commands.
The following are 4 equations, labeled A,B,C,D:
$$ \alpha $$ (A)
\[
\beta
\] (B)
$$ \gamma \label{C} $$
\[
\delta \label{D}
\]
You can now refer to (eq:A), (eq:B), \eqref{C}, \eqref{D}.
Enabling the extension
---------------------------------------
### On the command line
Use the `-m` option to choose the kind of output. Possible choices are:
`--math-engine itex2mml` : Outputs MathML using [itex2mml](#using_itex2mml).
`--math-engine ritex` : Outputs MathML using [ritex](#using_ritex).
`--math-engine blahtex` : Outputs MathML using [blahtex](#using_blahtex).
`--math-images blahtex` : Outputs PNGs using [blahtex](#using_blahtex).
### With embedded Maruku
You have to enable the math extension like this:
require 'maruku' # loads maruku
require 'maruku/ext/math' # loads the math extension
Use the following to choose the engine:
MaRuKu::Globals[:html_math_engine] = 'ritex'
MaRuKu::Globals[:html_png_engine] = 'blahtex'
Available MathML engines are 'none', 'itex2mml', 'blahtex'.
'blahtex' is the only PNG engine available.
External libraries needed
-------------------------
To output MathML or PNGs, it is needed to install one of the following libraries
### Using `ritex` ### {#using_ritex}
Install with
$ gem install ritex
ritex's abilities are very limited, but it is the easiest to install.
### Using `itex2mml` ### {#using_itex2mml}
itex2mml supports much more LaTeX commands/environments than ritex.
Install itex2mml using the instructions at:
>
This is a summary of the available LaTeX commands:
>
Moreover, [Jacques Distler] is integrating Maruku+itex2mml+[Instiki].
You can find more information here:
>
[Jacques Distler]: http://golem.ph.utexas.edu/~distler
[instiki]: http://www.instiki.org
### Using `blahtex` ### {#using_blahtex}
Download from . Make sure you have
the command-line `blahtex` in your path.
Subtleties
----------
### Serving the right content/type ###
* Mozilla wants files to have the `.xhtml` extension.
...
### Where PNGS are put ###
* `Globals[:math_png_dir]`
* `Globals[:math_png_dir_url]`
### Styling equations ####
...
### Aligning PNGs ####
* using `ex`
* **IE7 bug**
...
maruku-0.6.0/docs/changelog.md 0000644 0001750 0001750 00000022444 11573154515 016135 0 ustar vincent vincent CSS: style.css
LaTeX CJK: true
HTML use syntax: true
#### Changes in 0.5.6 #### {#stable}
* News:
- Now Maruku is in the official Gentoo Portage tree (done by [Aggelos Orfanakos])
* New stuff:
- Attribute `maruku_signature` defaults to false. (many people asked this)
- unittests scripts are included in the distribution.
- New attribute `filter_html`: if true, raw HTML/XML is discarded. (asked by Marik)
- Command line: if output file is `-`, Maruku writes to stdout.
* Bug fixes:
* Another tiny bug in HTML parsing.
* In latex, `\linebreak` was used instead of `\newline` (reported by Sam Kleinman)
* Fixed bug with non-alpha numeric characters in ref.ids (reported by Aggelos Orfanakos)
* Pending bugs/feature requests:
- Maruku does not allow 3-space indented lists.
- Lists item whose first character is UTF8 are not recognized (reported by Aggelos Orfanakos)
- Maruku cannot output `"`-delimited attributes, because `REXML` does not support it.
[Aggelos Orfanakos]: http://agorf.gr/
#### Changes in 0.5.5 ####
* Features:
* Input of HTML numeric entities:
Examples of numeric character references include © or ©
for the copyright symbol, Α or Α for the Greek capital
letter alpha, and ا or ا for the Arabic letter alef.
> Examples of numeric character references include © or ©
> for the copyright symbol, Α or Α for the Greek capital
> letter alpha, and ا or ا for the Arabic letter alef.
* Bug fixes:
* Alt text was ignored for images.
* Fixed minor bug in reading HTML inside paragraph.
* Changed rules for block-level HTML to make it similar to Markdown.pl.
For example:
Paragraph
will be translated to
Paragraph
while this:
Paragraph
becomes
Paragraph
* **Pending bugs**: there are some problems when parsing lists. It is difficult
to get it right because the spec is very fuzzy. At the moment, list items
cannot be indented by more than 1 space.
#### Changes in 0.5.4 ####
* Features:
* [All HTML attributes](http://www.w3.org/TR/html4/index/attributes.html) are supported.
> Science is a wonderful thing if one does not
> have to earn one's living at it.
{: cite="http://en.wikiquote.org/wiki/Albert_Einstein"}
* Attribute `doc_prefix`.
* Math:
* `\begin{equation}` and `\end{equation}` are understood.
* Math parsing enabled per-instance using the `math_enabled` attribute.
* `math_numbered` attribute.
* Bug fixes:
* Runs quietly with `ruby -w`.
* Fixed a bug which could cause data-loss when reading indented lines.
#### Changes in 0.5.3 ####
* Features:
* [All HTML `table` attributes](http://www.w3.org/TR/html4/struct/tables.html#h-11.2.1)
can be used (`summary`, `width`, `frame`, `rules`,
`border`, `cellspacing`, `cellpadding`).
The next version will hopefully use all HTML attributes.
* Bug fixes:
* Crash on this line: (found by Aggelos Orfanakos)
[test][]:
* Regression with attribute system (found by Charles)
#### Changes in 0.5.1 ####
* Bug fixes:
* Workaround for Internet Explorer bug:
be very sure that `'` is always written as `'`.
* Support for empty images ref: `![image]` and `![image][]`.
* Fixed bug in parsing attribute lists definitions.
* Minor things:
* Now code blocks are written as a `` element inside a ``, and
`` elements have both `class` and `lang` attributes set
to the specified language.
Example:
Example
{:lang=ruby}
{:lang=markdown}
produces:
Example
{:lang=xml}
#### Changes in 0.5.0 ####
* Syntax changes:
* Compatibility with newest Markdown.pl: `[text]` as a synonim of `[text][]`.
* Meta data: the first IAL in a span environment now refers to the parent.
This makes it possible to set attributes for cells:
Head | Head |
---------------+-------+--
{:r} Hello + ...
{:r: scope='row'}
The first cell will have the `scope` attribute set to `row`.
* New settings:
* Disable the Maruku signature by setting `maruku signature: false`
* Stricter doctype. By the way -- did I mention it? --
**Maruku HTML has always been proper validating XHTML strict**
(if a page does not validate, please report it as a bug).
Of course, this only matters when using `maruku` as a standalone
program.
* I have updated the XHTML DTD used to support MathML:
currently using XHTML+MathML+SVG.
* Content-type set to `application/xhtml+xml`
* All entities are written as numeric entities.
* Bug fixes
* Many fixes in the code handling the sanitizing of inline HTML.
* `markdown=1` did not propagate to children.
* LaTeX: An exception was raised if an unknown entity was used.
#### Changes in 0.4.2 ####
* Adapted syntax to the [new meta-data proposal][proposal].
* Changes in LaTeX export:
* Links to external URLs are blue by default.
* New attributes: `latex_preamble` to add a custom preamble,
and `latex_cjk` to add packages for UTF-8 Japanese characters.
(**support for this is still shaky**). Example:
Title: my document
LaTeX CJK: true
LaTeX preamble: preamble.tex
Content
* Bug fixes
+ Images were not given `id` or `class` attributes.
+ Fixed bug in LaTeX export with handling of `<`,`>` enclosed URLs: ``.
#### Changes in 0.4.1 aka "Typographer" ####
* Implemented SmartyPants support:
'Twas a "test" to 'remember' -- in the '90s
--- while I was <>. She was 6\"12\'.
> 'Twas a "test" to 'remember' -- in the '90s --- while I was <>.
> She was 6\"12\'.
I adapted the code from RubyPants.
* Server directives between ` ?>` are properly preserved.
* Changes in LaTeX export:
* Now Japanese text rendering sort of works, using the following packages:
\usepackage[C40]{fontenc}
\usepackage[cjkjis]{ucs}
\usepackage[utf8x]{inputenc}
Nevertheless, I could only get bitmap fonts working -- probably it's a problem
with my setup.
A quick test: 日本、中国、ひらがな、カタカナ。
* Fixed bugs in rendering of immediate links.
* External packages are `require`d only if needed.
* More symbols supported.
See the symbol list
[in HTML](http://maruku.rubyforge.org/entity_test.html) and
[in PDF](http://maruku.rubyforge.org/entity_test.pdf).
#### Changes in 0.4 ####
* First implementation of [the new meta-data syntax][meta].
* General refactorization of the code and much cleaner error reporting.
* Created [the RDOC documentation][rdoc].
* The `add_whitespace` method took too much time -- it was O(n^2).
* Added unit-tests for block-level elements.
[rdoc]: http://maruku.rubyforge.org/rdoc/
[meta]: http://maruku.rubyforge.org/proposal.html
[Jacques Distler]: http://golem.ph.utexas.edu/~distler
[itex2MML]: http://golem.ph.utexas.edu/~distler/blog/itex2MML.html
[math]: http://rubyforge.maruku.org/math.html
#### Changes in 0.3 ####
* A real parser is used instead of a regexp-based system, also for span-level
elements.
Now Maruku is almost 2x faster than Bluecloth, while having more features.
Here are some benchmarks:
BlueCloth (to_html): parsing 0.00 sec + rendering 1.54 sec = 1.55 sec
Maruku (to_html): parsing 0.47 sec + rendering 0.38 sec = 0.85 sec
Maruku (to_latex): parsing 0.49 sec + rendering 0.25 sec = 0.73 sec
This is the result of running `lib/maruku/tests/benchmark.rb` on the Markdown
specification.
* Prettier HTML output by adding whitespace.
* Added a full suite of unit-tests for the span-level parser.
* Error management: Having a real parser, Maruku warns you about syntax issues.
The default action is to warn and try to continue. If you do this:
Maruku.new(string, {:on_error => :raise})
then syntax errors will cause an exception to be raised (you can catch this
and retry).
* Fixed a series of bugs in handling inline HTML code.
Immediate TODO-list:
* UTF-8 input/output works OK for HTML, however I am having pain trying to export
to LaTeX. I want at least Japanese characters support, so if you know how to
do this you are very welcome to give me an hand.
For example: in the HTML version, you should see accented characters in this
parenthesis:
> (àèìòù)
and Japanese text in these other parentheses:
> (カタカナで 私の 名前は アンドレア チェンシ です).
>
> (日本のガルは 大好き、でも、日本語は難しですから、そうぞ 英語話すガルを おしえてください).
In the LaTeX version, these do not appear. I know how to do LaTeX with
ISO-8859-1 encoding (European characters), but I'm struggling with half-baked
solutions for UTF-8 encoded documents.
* Implement the [new meta-data proposal][proposal].
* Exporting to Markdown (pretty printing).
* Exporting to HTML splitting in multiple files.
* RubyPants.
* Support for images in PDF.
[proposal]: http://maruku.rubyforge.org/proposal.html
[contact]: http://www.dis.uniroma1.it/~acensi/contact.html
[markdown-discuss]: http://six.pairlist.net/mailman/listinfo/markdown-discuss
[tracker]: http://rubyforge.org/tracker/?group_id=2795
maruku-0.6.0/docs/maruku.md 0000644 0001750 0001750 00000021204 11573154515 015503 0 ustar vincent vincent CSS: style.css
Use numbered headers: true
HTML use syntax: true
LaTeX use listings: true
LaTeX CJK: false
LaTeX preamble: preamble.tex
{#logo}
Mar**u**k**u**: a Markdown-superset interpreter
===============================================
[Maruku] is a Markdown interpreter written in [Ruby].
> [Last release](#release_notes) is version 0.5.6 -- 2007-05-22.
>
> Install using [rubygems]:
>
> $ gem install maruku
>
> Use this command to update to latest version:
>
> $ gem update maruku
>
{#news}
[rubygems]: http://rubygems.org
* * *
Maruku allows you to write in an easy-to-read-and-write syntax, like this:
> [This document in Markdown][this_md]
Then it can be translated to HTML:
> [This document in HTML][this_html]
or LaTeX, which is then converted to PDF:
> [This document in PDF][this_pdf]
Maruku implements:
* the original [Markdown syntax][markdown_html]
([HTML][markdown_html] or [PDF][markdown_pdf]), translated by Maruku).
* all the improvements in [PHP Markdown Extra].
* a new [meta-data syntax][meta_data_proposal]
__Authors__: Maruku has been developed so far by [Andrea Censi].
Contributors are most welcome!
__The name of the game__: Maruku is the [romaji] transliteration of
the [katakana] transliteration
of "Mark", the first word in Markdown. I chose this name because Ruby
is Japanese, and also the sillable "ru" appears in Maruku.
[romaji]: http://en.wikipedia.org/wiki/Romaji
[katakana]: http://en.wikipedia.org/wiki/Katakana
[tests]: http://maruku.rubyforge.org/tests/
[maruku]: http://maruku.rubyforge.org/
[markdown_html]: http://maruku.rubyforge.org/markdown_syntax.html
[markdown_pdf]: http://maruku.rubyforge.org/markdown_syntax.pdf
[this_md]: http://maruku.rubyforge.org/maruku.md
[this_html]: http://maruku.rubyforge.org/maruku.html
[this_pdf]: http://maruku.rubyforge.org/maruku.pdf
[Andrea Censi]: http://www.dis.uniroma1.it/~acensi/
[contact]: http://www.dis.uniroma1.it/~acensi/contact.html
[gem]: http://rubygems.rubyforge.org/
[tracker]: http://rubyforge.org/tracker/?group_id=2795
[ruby]: http://www.ruby-lang.org
[bluecloth]: http://www.deveiate.org/projects/BlueCloth
[Markdown syntax]: http://daringfireball.net/projects/markdown/syntax
[PHP Markdown Extra]: http://www.michelf.com/projects/php-markdown/extra/
[math syntax]: http://maruku.rubyforge.org/math.xhtml
[blahtex]: http://www.blahtex.org
[ritex]: http://ritex.rubyforge.org
[itex2mml]: http://golem.ph.utexas.edu/~distler/code/itexToMML/
[syntax]: http://syntax.rubyforge.org/
[listings]: http://www.ctan.org/tex-archive/macros/latex/contrib/listings/
[meta_data_proposal]: http://maruku.rubyforge.org/proposal.html
[markdown-discuss]: http://six.pairlist.net/mailman/listinfo/markdown-discuss
* * *
Table of contents: (**auto-generated by Maruku!**)
* This list will contain the toc (it doesn't matter what you write here)
{:toc}
* * *
{:ruby: lang=ruby code_background_color='#efffef'}
{:shell: lang=sh code_background_color='#efefff'}
{:markdown: code_background_color='#ffefef'}
{:html: lang=xml}
Release notes {#release_notes}
--------------
Note: Maruku seems to be very robust, nevertheless it is still beta-level
software. So if you want to use it in production environments, please
check back in a month or so, while we squash the remaining bugs.
In the meantime, feel free to toy around, and please signal problems,
request features, by [contacting me][contact] or using the [tracker][tracker].
For issues about the Markdown syntax itself and improvements to it,
please write to the [Markdown-discuss mailing list][markdown-discuss].
Have fun!
See the [changelog](http://maruku.rubyforge.org/changelog.html#stable).
Usage
--------
### Embedded Maruku ###
This is the basic usage:
require 'rubygems'
require 'maruku'
doc = Maruku.new(markdown_string)
puts doc.to_html
{:ruby}
The method `to_html` outputs only an HTML fragment, while the method `to_html_document` outputs a complete XHTML 1.0 document:
puts doc.to_html_document
{:ruby}
You can have the REXML document tree with:
tree = doc.to_html_document_tree
{:ruby}
### From the command line ###
There is one command-line program installed: `maruku`.
Without arguments, it converts Markdown to HTML:
$ maruku file.md # creates file.html
{:shell}
With the `--pdf` arguments, it converts Markdown to LaTeX, then calls `pdflatex` to
transform to PDF:
$ maruku --pdf file.md # creates file.tex and file.pdf
{:shell}
Maruku summary of features {#features}
--------------------------
* Supported syntax
* [Basic Markdown][markdown_syntax]
* [Markdown Extra](#extra)
* [Meta-data syntax](#meta)
* Output
* XHTML
* Syntax highlighting via the [`syntax`][syntax] library.
* LaTeX
* [Translation of HTML entities to LaTeX](#entities)
* Syntax highlighting via the [`listings`][listings] package.
* Misc
* [Documentation for supported attributes][supported_attributes]
* [Automatic generation of the TOC](#toc-generation)
[supported_attributes]: exd.html
**Experimental features (not released yet)**
* [LaTeX Math syntax][math_syntax] (not enabled by default)
* An extension system for adding new syntax is available,
but the API is bound to change in the future,
so please don't use it.
* LaTeX to MathML using either one of [`ritex`][ritex], [`itex2mml`][itex2mml],
[`blahtex`][blahtex].
* LaTeX to PNG using [`blahtex`][blahtex].
### New meta-data syntax {#meta}
Maruku implements a syntax that allows to attach "meta" information
to objects.
See [this proposal][meta_data_proposal] for how to attach
metadata to the elements.
See the [documentation for supported attributes][supported_attributes].
Meta-data for the document itself is specified through the use
of email headers:
Title: A simple document containing meta-headers
CSS: style.css
Content of the document
{:markdown}
When creating the document through
Maruku.new(s).to_html_document
{:ruby}
the title and stylesheet are added as expected.
Meta-data keys are assumed to be case-insensitive.
### Automatic generation of the table of contents ### {#toc-generation}
If you create a list, and then set the `toc` attribute, when rendering
Maruku will create an auto-generated table of contents.
* This will become a table of contents (this text will be scraped).
{:toc}
You can see an example of this at the beginning of this document.
### Use HTML entities ### {#entities}
If you want to use HTML entities, go on! We will take care
of the translation to LaTeX:
Entity | Result
------------|----------
`©` | ©
`£` | £
`λ` | λ
`—` | —
See the [list of supported entities][ent_html] ([pdf][ent_pdf]).
[ent_html]: http://maruku.rubyforge.org/entity_test.html
[ent_pdf]: http://maruku.rubyforge.org/entity_test.pdf
### This header contains *emphasis* **strong text** and `code` ####
Note that this header contains formatting and it still works, also in the table of contents.
And [This is a *link* with **all** ***sort*** of `weird stuff`](#features) in the text.
Examples of PHP Markdown Extra syntax {#extra}
-------------------------------------
* tables
Col1 | Very very long head | Very very long head|
-----|:-------------------:|-------------------:|
cell | center-align | right-align |
{:markdown}
Col1 | Very very long head | Very very long head|
-----|:-------------------:|-------------------:|
cell | center-align | right-align |
* footnotes [^foot]
* footnotes [^foot]
[^foot]: I really was missing those.
{:markdown}
[^foot]: I really was missing those.
* Markdown inside HTML elements
This is a div with Markdown **strong text**
{:html}
This is a div with Markdown **strong text**
* header ids
## Download ## {#download}
{:markdown}
For example, [a link to the download](#download) header.
* definition lists
Definition list
: something very hard to parse
{:markdown}
Definition list
: something very hard to parse
* abbreviations or ABB for short.
*[ABB]: Simply an abbreviation
maruku-0.6.0/docs/entity_test.md 0000644 0001750 0001750 00000001031 11573154515 016546 0 ustar vincent vincent
List of symbols supported by Maruku
===================================
maruku-0.6.0/docs/proposal.md 0000644 0001750 0001750 00000015175 11573154515 016050 0 ustar vincent vincent CSS: style.css
LaTeX_use_listings: true
html_use_syntax: true
use_numbered_headers: true
Proposal for adding a meta-data syntax to Markdown
=============================================
This document describes a syntax for attaching meta-data to
block-level elements (headers, paragraphs, code blocks,…),
and to span-level elements (links, images,…).
***Note: this is an evolving proposal***
Last updated **January 10th, 2007**:
* Changed the syntax for compatibility with a future extension mechanism.
The first character in the curly braces must be a colon, optionally
followed by a space:
{: ref .class #id}
The old syntax was `{ref .class #id}`.
For ALDs, the new syntax is:
{:ref_id: key=val .class #id }
instead of:
{ref_id}: key=val .class #id
Converters that don't use this syntax may just ignore everything
which is in curly braces and starts with ":".
* IAL can be put both *before* and *after* the element.
There is no ambiguity as a blank line is needed between elements:
Paragraph 1
{:par2}
Paragraph 2
is equivalent to:
Paragraph 1
Paragraph 2
{:par2}
* Simplified rules for escaping.
*Table of contents:*
> * Table of contents
> {:toc}
Overview
--------
This proposal describes two additions to the Markdown syntax:
1. inline attribute lists (IAL)
## Header ## {: key=val .class #id ref_id}
2. attribute lists definitions (ALD)
{:ref_id: key=val .class #id}
Every span-level or block-level element can be followed by an IAL:
### Header ### {: #header1 class=c1}
Paragraph *with emphasis*{: class=c1}
second line of paragraph
{: class=c1}
In this example, the three IALs refer to the header, the emphasis span, and the entire paragraph, respectively.
IALs can reference ALDs. The result of the following example is the same as the previous one:
### Header ### {: #header1 c1}
Paragraph *with emphasis*{:c1}
second line of paragraph
{:c1}
{:c1: class=c1}
Attribute lists
---------------
This is an example attribute list, which shows
everything you can put inside:
{: key1=val key2="long val" #myid .class1 .class2 ref1 ref2}
More in particular, an attribute list is a whitespace-separated list
of elements of 4 different kinds:
1. key/value pairs (quoted if necessary)
2. [references to ALD](#using_tags) (`ref1`,`ref2`)
3. [id specifiers](#class_id) (`#myid`)
4. [class specifiers](#class_id) (`.myclass`)
### `id` and `class` are special ### {#class_id}
For ID and classes there are special shortcuts:
* `#myid` is a shortcut for `id=myid`
* `.myclass` means "add `myclass` to the current `class` attribute".
So these are equivalent:
{: .class1 .class2}
{: class="class1 class2"}
The following attribute lists are equivalent:
{: #myid .class1 .class2}
{: id=myid class=class1 .class2}
{: id=myid class="class1 class2"}
{: id=myid class="will be overridden" class=class1 .class2}
Where to put inline attribute lists
----------------------------------
### For block-level elements ###
For paragraphs and other block-level elements, IAL go
**after** the element:
This is a paragraph.
Line 2 of the paragraph.
{: #myid .myclass}
A quote with a citation url:
> Who said that?
{: cite=google.com}
Note: empty lines between the block and the IAL are not tolerated.
So this is not legal:
This is a paragraph.
Line 2 of the paragraph.
{: #myid .myclass}
Attribute lists may be indented up to 3 spaces:
Paragraph1
{:ok}
Paragraph2
{:ok}
Paragraph2
{:ok}
{:code_show_spaces}
### For headers ###
For headers, you can put attribute lists on the same line:
### Header ### {: #myid}
Header {: #myid .myclass}
------
or, as like other block-level elements, on the line below:
### Header ###
{: #myid}
Header
------
{: #myid .myclass}
### For span-level elements ###
For span-level elements, meta-data goes immediately **after** in the
flow.
For example, in this:
This is a *chunky paragraph*{: #id1}
{: #id2}
the ID of the `em` element is set to `id1`
and the ID of the paragraph is set to `id2`.
This works also for links, like this:
This is [a link][ref]{:#myid rel=abc rev=abc}
For images, this:
This is 
is equivalent to:
This is {:title="fresh carrots"}
Using attributes lists definition {#using_tags}
---------------------------------
In an attribute list, you can have:
1. `key=value` pairs,
2. id attributes (`#myid`)
3. class attributes (`.myclass`)
Everything else is interpreted as a reference to
an ALD.
# Header # {:ref}
Blah blah blah.
{:ref: #myhead .myclass lang=fr}
Of course, more than one IAL can reference the same ALD:
# Header 1 # {:1}
...
# Header 2 # {:1}
{:1: .myclass lang=fr}
The rules {:#grammar}
---------
### The issue of escaping ###
1. No escaping in code spans/blocks.
2. Everywhere else, **all** PUNCTUATION characters **can** be escaped,
and **must** be escaped when they could trigger links, tables, etc.
A punctuation character is anything not a letter, a number, or whitespace
(`[^a-zA-Z0-9\s\n]`).
3. As a rule, quotes **must** be escaped inside quoted values:
* Inside `"quoted values"`, you **must** escape `"`.
* Inside `'quoted values'`, you **must** escape `'`.
* Other examples:
`"bah 'bah' bah"` = `"bah \'bah\' bah"` = `'bah \'bah\' bah'`
`'bah "bah" bah'` = `'bah \"bah\" bah'` = `"bah \"bah\" bah"`
4. There is an exception for backward compatibility, in links/images titles:
[text](url "title"with"quotes")
The exception is not valid for attribute lists and in other
contexts, where you have to use the canonical syntax.
### Syntax for attribute lists ####
Consider the following attribute list:
{: key=value ref key2="quoted value" }
In this string, `key`, `value`, and `ref` can be substituted by any
string that does not contain whitespace, or the unescaped characters `}`,`=`,`'`,`"`.
Inside a quoted value you **must** escape the other kind of quote.
Also, you **must** escape a closing curly brace `}` inside quoted values.
This rule is for making life easier for interpreter that just want to skip
the meta-data.
If you don't implement this syntax, you can get rid of the IAL by using this
regular expression (this is written in Ruby):
r = /\{:(\\\}|[^\}])*\}/
s.gsub(r, '') # ignore metadata
{:ruby}
Basically: match everything contained in a couple of `{:` and `}`, taking care
of escaping of `}`. This `\\\}|[^\}]` means: eat either any character which
is not a `}` or an escape sequence `\}`.
For this example,
this is
{: skipped="\}" val=\} bar}
for me
{: also this}
the result is:
this is
for me
maruku-0.6.0/docs/div_syntax.md 0000644 0001750 0001750 00000001021 11573154515 016362 0 ustar vincent vincent ## Option number 1 ##
* `[ ]{0,3}\+={2,}` pushes the stack
* `[ ]{0,3}\-={2,}` pops the stack
+================ {#id}
IAL can be put on the same line of a push
+== {#id2}
Or on the same line of a pop:
-==
-==============
## Option number 2 ##
Double braces:
{{
}}{}
I don't like, it gets too messy because there are
too many braces.
+================ {#id}
nested div:
+========================
inside nested DIV
-========================
-==============
maruku-0.6.0/lib/ 0000755 0001750 0001750 00000000000 11573154515 013474 5 ustar vincent vincent maruku-0.6.0/lib/maruku/ 0000755 0001750 0001750 00000000000 11573154515 015000 5 ustar vincent vincent maruku-0.6.0/lib/maruku/defaults.rb 0000644 0001750 0001750 00000003547 11573154515 017145 0 ustar vincent vincent #--
# Copyright (C) 2006 Andrea Censi
#
# This file is part of Maruku.
#
# Maruku is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Maruku is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Maruku; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#++
module MaRuKu
Globals = {
:unsafe_features => false,
:on_error => :warning,
:use_numbered_headers => false,
:maruku_signature => false,
:code_background_color => '#fef',
:code_show_spaces => false,
:filter_html => false,
:html_math_output_mathml => true, # also set :html_math_engine
:html_math_engine => 'none', #ritex, itex2mml
:html_math_output_png => false,
:html_png_engine => 'none',
:html_png_dir => 'pngs',
:html_png_url => 'pngs/',
:html_png_resolution => 200,
:html_use_syntax => false,
:latex_use_listings => false,
:latex_cjk => false,
:latex_cache_file => "blahtex_cache.pstore", # cache file for blahtex filter
:debug_keep_ials => false,
:doc_prefix => ''
}
class MDElement
def get_setting(sym)
if self.attributes.has_key?(sym) then
return self.attributes[sym]
elsif self.doc && self.doc.attributes.has_key?(sym) then
return self.doc.attributes[sym]
elsif MaRuKu::Globals.has_key?(sym)
return MaRuKu::Globals[sym]
else
$stderr.puts "Bug: no default for #{sym.inspect}"
nil
end
end
end
end maruku-0.6.0/lib/maruku/usage/ 0000755 0001750 0001750 00000000000 11573154515 016104 5 ustar vincent vincent maruku-0.6.0/lib/maruku/usage/example1.rb 0000644 0001750 0001750 00000000723 11573154515 020147 0 ustar vincent vincent require 'maruku'
text = < :raise, :error_stream => s})
puts "Error! It should have thrown an exception."
rescue
# puts "ok, got error"
end
begin
Maruku.new(invalid, {:on_error => :warning, :error_stream => s})
rescue
puts "Error! It should not have thrown an exception."
end
maruku-0.6.0/lib/maruku/structures.rb 0000644 0001750 0001750 00000010234 11573154515 017550 0 ustar vincent vincent #--
# Copyright (C) 2006 Andrea Censi
#
# This file is part of Maruku.
#
# Maruku is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Maruku is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Maruku; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#++
class Module
def safe_attr_accessor1(symbol, klass)
attr_reader symbol
code = <<-EOF
def #{symbol}=(val)
if not val.kind_of? #{klass}
s = "\nCould not assign an object of type \#{val.class} to #{symbol}.\n\n"
s += "Tried to assign object of class \#{val.class}:\n"+
"\#{val.inspect}\n"+
"to \#{self.class}::#{symbol} constrained to be of class #{klass}.\n"
raise s
end
@#{symbol} = val
end
EOF
module_eval code
end
def safe_attr_accessor2(symbol, klass)
attr_accessor symbol
end
alias safe_attr_accessor safe_attr_accessor2
end
module MaRuKu
# I did not want to have a class for each possible element.
# Instead I opted to have only the class "MDElement"
# that represents eveything in the document (paragraphs, headers, etc).
#
# You can tell what it is by the variable `node_type`.
#
# In the instance-variable `children` there are the children. These
# can be of class 1) String or 2) MDElement.
#
# The @doc variable points to the document to which the MDElement
# belongs (which is an instance of Maruku, subclass of MDElement).
#
# Attributes are contained in the hash `attributes`.
# Keys are symbols (downcased, with spaces substituted by underscores)
#
# For example, if you write in the source document.
#
# Title: test document
# My property: value
#
# content content
#
# You can access `value` by writing:
#
# @doc.attributes[:my_property] # => 'value'
#
# from whichever MDElement in the hierarchy.
#
class MDElement
# See helpers.rb for the list of allowed #node_type values
safe_attr_accessor :node_type, Symbol
# Children are either Strings or MDElement
safe_attr_accessor :children, Array
# An attribute list, may not be nil
safe_attr_accessor :al, Array #Maruku::AttributeList
# These are the processed attributes
safe_attr_accessor :attributes, Hash
# Reference of the document (which is of class Maruku)
attr_accessor :doc
def initialize(node_type=:unset, children=[], meta={},
al=MaRuKu::AttributeList.new )
super();
self.children = children
self.node_type = node_type
@attributes = {}
meta.each do |symbol, value|
self.instance_eval "
def #{symbol}; @#{symbol}; end
def #{symbol}=(val); @#{symbol}=val; end"
self.send "#{symbol}=", value
end
self.al = al || AttributeList.new
self.meta_priv = meta
end
attr_accessor :meta_priv
def ==(o)
ok = o.kind_of?(MDElement) &&
(self.node_type == o.node_type) &&
(self.meta_priv == o.meta_priv) &&
(self.children == o.children)
if not ok
# puts "This:\n"+self.inspect+"\nis different from\n"+o.inspect+"\n\n"
end
ok
end
end
# This represents the whole document and holds global data.
class MDDocument
safe_attr_accessor :refs, Hash
safe_attr_accessor :footnotes, Hash
# This is an hash. The key might be nil.
safe_attr_accessor :abbreviations, Hash
# Attribute lists definition
safe_attr_accessor :ald, Hash
# The order in which footnotes are used. Contains the id.
safe_attr_accessor :footnotes_order, Array
safe_attr_accessor :latex_required_packages, Array
safe_attr_accessor :refid2ref, Hash
def initialize(s=nil)
super(:document)
@doc = self
self.refs = {}
self.footnotes = {}
self.footnotes_order = []
self.abbreviations = {}
self.ald = {}
self.latex_required_packages = []
parse_doc(s) if s
end
end
end # MaRuKu
maruku-0.6.0/lib/maruku/structures_inspect.rb 0000644 0001750 0001750 00000003547 11573154515 021306 0 ustar vincent vincent #--
# Copyright (C) 2006 Andrea Censi
#
# This file is part of Maruku.
#
# Maruku is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Maruku is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Maruku; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#++
class String
def inspect_more(a=nil,b=nil)
inspect
end
end
class Object
def inspect_more(a=nil,b=nil)
inspect
end
end
class Array
def inspect_more(compact, join_string, add_brackets=true)
s = map {|x|
x.kind_of?(String) ? x.inspect :
x.kind_of?(MaRuKu::MDElement) ? x.inspect(compact) :
(raise "WTF #{x.class} #{x.inspect}")
}.join(join_string)
add_brackets ? "[#{s}]" : s
end
end
class Hash
def inspect_ordered(a=nil,b=nil)
"{"+keys.map{|x|x.to_s}.sort.map{|x|x.to_sym}.
map{|k| k.inspect + "=>"+self[k].inspect}.join(',')+"}"
end
end
module MaRuKu
class MDElement
def inspect(compact=true)
if compact
i2 = inspect2
return i2 if i2
end
"md_el(:%s,%s,%s,%s)" %
[
self.node_type,
children_inspect(compact),
@meta_priv.inspect_ordered,
self.al.inspect
]
end
def children_inspect(compact=true)
s = @children.inspect_more(compact,', ')
if @children.empty?
"[]"
elsif s.size < 70
s
else
"[\n"+
add_tabs(@children.inspect_more(compact,",\n",false))+
"\n]"
end
end
end
end
maruku-0.6.0/lib/maruku/output/ 0000755 0001750 0001750 00000000000 11573154515 016340 5 ustar vincent vincent maruku-0.6.0/lib/maruku/output/to_markdown.rb 0000644 0001750 0001750 00000007072 11573154515 021217 0 ustar vincent vincent #--
# Copyright (C) 2006 Andrea Censi
#
# This file is part of Maruku.
#
# Maruku is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Maruku is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Maruku; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#++
class String
# XXX: markdown escaping
def to_md(c=nil)
to_s
end
# " andrea censi " => [" andrea ", "censi "]
def mysplit
split.map{|x| x+" "}
end
end
module MaRuKu; module Out; module Markdown
DefaultLineLength = 40
def to_md(context={})
children_to_md(context)
end
def to_md_paragraph(context)
line_length = context[:line_length] || DefaultLineLength
wrap(@children, line_length, context)+"\n"
end
def to_md_li_span(context)
len = (context[:line_length] || DefaultLineLength) - 2
s = add_tabs(wrap(@children, len-2, context), 1, ' ')
s[0] = ?*
s + "\n"
end
def to_md_abbr_def(context)
"*[#{self.abbr}]: #{self.text}\n"
end
def to_md_ol(context)
len = (context[:line_length] || DefaultLineLength) - 2
md = ""
self.children.each_with_index do |li, i|
s = add_tabs(w=wrap(li.children, len-2, context), 1, ' ')+"\n"
s[0,4] = "#{i+1}. "[0,4]
# puts w.inspect
md += s
end
md + "\n"
end
def to_md_ul(context)
len = (context[:line_length] || DefaultLineLength) - 2
md = ""
self.children.each_with_index do |li, i|
w = wrap(li.children, len-2, context)
# puts "W: "+ w.inspect
s = add_indent(w)
# puts "S: " +s.inspect
s[0,1] = "-"
md += s
end
md + "\n"
end
def add_indent(s,char=" ")
t = s.split("\n").map{|x| char+x }.join("\n")
s << ?\n if t[-1] == ?\n
s
end
# Convert each child to html
def children_to_md(context)
array_to_md(@children, context)
end
def wrap(array, line_length, context)
out = ""
line = ""
array.each do |c|
if c.kind_of?(MDElement) && c.node_type == :linebreak
out << line.strip << " \n"; line="";
next
end
pieces =
if c.kind_of? String
c.to_md.mysplit
else
[c.to_md(context)].flatten
end
# puts "Pieces: #{pieces.inspect}"
pieces.each do |p|
if p.size + line.size > line_length
out << line.strip << "\n";
line = ""
end
line << p
end
end
out << line.strip << "\n" if line.size > 0
out << ?\n if not out[-1] == ?\n
out
end
def array_to_md(array, context, join_char='')
e = []
array.each do |c|
method = c.kind_of?(MDElement) ?
"to_md_#{c.node_type}" : "to_md"
if not c.respond_to?(method)
#raise "Object does not answer to #{method}: #{c.class} #{c.inspect[0,100]}"
# tell_user "Using default for #{c.node_type}"
method = 'to_md'
end
# puts "#{c.inspect} created with method #{method}"
h = c.send(method, context)
if h.nil?
raise "Nil md for #{c.inspect} created with method #{method}"
end
if h.kind_of?Array
e = e + h
else
e << h
end
end
e.join(join_char)
end
end end end
module MaRuKu; class MDDocument
alias old_md to_md
def to_md(context={})
s = old_md(context)
# puts s
s
end
end end maruku-0.6.0/lib/maruku/output/s5/ 0000755 0001750 0001750 00000000000 11573154515 016667 5 ustar vincent vincent maruku-0.6.0/lib/maruku/output/s5/to_s5.rb 0000644 0001750 0001750 00000007742 11573154515 020257 0 ustar vincent vincent # This module groups all functions related to HTML export.
module MaRuKu
begin
require 'rexml/formatters/pretty'
require 'rexml/formatters/default'
$rexml_new_version = true
rescue LoadError
$rexml_new_version = false
end
class MDDocument
def s5_theme
html_escape(self.attributes[:slide_theme] || "default")
end
def html_escape(string)
string.gsub( /&/, "&" ).
gsub( /, "<" ).
gsub( />/, ">" ).
gsub( /'/, "'" ).
gsub( /"/, """ )
end
# Render as an HTML fragment (no head, just the content of BODY). (returns a string)
def to_s5(context={})
indent = context[:indent] || -1
ie_hack = !context[:ie_hack].kind_of?(FalseClass)
content_only = !context[:content_only].kind_of?(FalseClass)
doc = Document.new(nil,{:respect_whitespace =>:all})
if content_only
body = Element.new('div', doc)
else
html = Element.new('html', doc)
html.add_namespace('http://www.w3.org/1999/xhtml')
html.add_namespace('svg', "http://www.w3.org/2000/svg" )
head = Element.new('head', html)
me = Element.new 'meta', head
me.attributes['http-equiv'] = 'Content-type'
me.attributes['content'] = 'text/html;charset=utf-8'
# Create title element
doc_title = self.attributes[:title] || self.attributes[:subject] || ""
title = Element.new 'title', head
title << Text.new(doc_title)
body = Element.new('body', html)
end
slide_header = self.attributes[:slide_header]
slide_footer = self.attributes[:slide_footer]
slide_subfooter = self.attributes[:slide_subfooter]
slide_topleft = self.attributes[:slide_topleft]
slide_topright = self.attributes[:slide_topright]
slide_bottomleft = self.attributes[:slide_bottomleft]
slide_bottomright = self.attributes[:slide_bottomright]
dummy_layout_slide =
"
#{slide_topleft}
#{slide_topright}
#{slide_bottomleft}
#{slide_bottomright}
"
body.add_element Document.new(dummy_layout_slide, {:respect_whitespace =>:all}).root
presentation = Element.new 'div', body
presentation.attributes['class'] = 'presentation'
first_slide="
#{self.attributes[:title] ||context[:title]}
#{self.attributes[:subtitle] ||context[:subtitle]}
#{self.attributes[:author] ||context[:author]}
#{self.attributes[:company] ||context[:company]}
"
presentation.add_element Document.new(first_slide).root
slide_num = 0
self.toc.section_children.each do |slide|
slide_num += 1
@doc.attributes[:doc_prefix] = "s#{slide_num}"
puts "Slide #{slide_num}: " + slide.header_element.to_s
div = Element.new('div', presentation)
div.attributes['class'] = 'slide'
h1 = Element.new 'h1', div
slide.header_element.children_to_html.each do |e| h1 << e; end
array_to_html(slide.immediate_children).each do |e| div << e end
# render footnotes
if @doc.footnotes_order.size > 0
div << render_footnotes
@doc.footnotes_order = []
end
end
xml = ""
if (content_only)
if $rexml_new_version
formatter = REXML::Formatters::Default.new(ie_hack)
formatter.write(body, xml)
else
body.write(xml,indent,transitive=true,ie_hack);
end
else
doc2 = Document.new(""+S5_external+"
",{:respect_whitespace =>:all})
doc2.root.children.each{ |child| head << child }
add_css_to(head)
# REXML Bug? if indent!=-1 whitespace is not respected for 'pre' elements
# containing code.
html.write(xml,indent,transitive=true,ie_hack);
Xhtml11_mathml2_svg11 + xml
end
end
end
end
maruku-0.6.0/lib/maruku/output/s5/fancy.rb 0000644 0001750 0001750 00000056206 11573154515 020325 0 ustar vincent vincent module MaRuKu
S5_external =<
EOF
S5_Fancy =<
EOF
end
maruku-0.6.0/lib/maruku/output/to_html.rb 0000644 0001750 0001750 00000056556 11573154515 020354 0 ustar vincent vincent #--
# Copyright (C) 2006 Andrea Censi
#
# This file is part of Maruku.
#
# Maruku is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Maruku is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Maruku; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#++
require 'rexml/document'
begin
require 'rexml/formatters/pretty'
require 'rexml/formatters/default'
$rexml_new_version = true
rescue LoadError
$rexml_new_version = false
end
class String
# A string is rendered into HTML by creating
# a REXML::Text node. REXML takes care of all the encoding.
def to_html
REXML::Text.new(self)
end
end
# This module groups all functions related to HTML export.
module MaRuKu; module Out; module HTML
include REXML
# Render as an HTML fragment (no head, just the content of BODY). (returns a string)
def to_html(context={})
indent = context[:indent] || -1
ie_hack = context[:ie_hack] || true
div = Element.new 'dummy'
children_to_html.each do |e|
div << e
end
# render footnotes
if @doc.footnotes_order.size > 0
div << render_footnotes
end
doc = Document.new(nil,{:respect_whitespace =>:all})
doc << div
# REXML Bug? if indent!=-1 whitespace is not respected for 'pre' elements
# containing code.
xml =""
if $rexml_new_version
formatter = if indent > -1
REXML::Formatters::Pretty.new( indent, ie_hack )
else
REXML::Formatters::Default.new( ie_hack )
end
formatter.write( div, xml)
else
div.write(xml,indent,transitive=true,ie_hack)
end
xml.gsub!(/\A\s*/,'')
xml.gsub!(/\s*<\/dummy>\Z/,'')
xml.gsub!(/\A /,'')
xml
end
# Render to a complete HTML document (returns a string)
def to_html_document(context={})
indent = context[:indent] || -1
ie_hack = context[:ie_hack] ||true
doc = to_html_document_tree
xml = ""
# REXML Bug? if indent!=-1 whitespace is not respected for 'pre' elements
# containing code.
doc.write(xml,indent,transitive=true,ie_hack);
Xhtml11_mathml2_svg11 + xml
end
Xhtml10strict =
"
\n"
Xhtml11strict_mathml2 = '
]>
'
Xhtml11_mathml2_svg11 =
'
'
def xml_newline() Text.new("\n") end
=begin maruku_doc
Attribute: title
Scope: document
Sets the title of the document.
If a title is not specified, the first header will be used.
These should be equivalent:
Title: my document
Content
and
my document
===========
Content
In both cases, the title is set to "my document".
=end
=begin maruku_doc
Attribute: doc_prefix
Scope: document
String to disambiguate footnote links.
=end
=begin maruku_doc
Attribute: subject
Scope: document
Synonim for `title`.
=end
# Render to an HTML fragment (returns a REXML document tree)
def to_html_tree
div = Element.new 'div'
div.attributes['class'] = 'maruku_wrapper_div'
children_to_html.each do |e|
div << e
end
# render footnotes
if @doc.footnotes_order.size > 0
div << render_footnotes
end
doc = Document.new(nil,{:respect_whitespace =>:all})
doc << div
end
=begin maruku_doc
Attribute: css
Scope: document
Output: HTML
Summary: Activates CSS stylesheets for HTML.
`css` should be a space-separated list of urls.
Example:
CSS: style.css math.css
=end
METAS = %w{description keywords author revised}
# Render to a complete HTML document (returns a REXML document tree)
def to_html_document_tree
doc = Document.new(nil,{:respect_whitespace =>:all})
# doc << XMLDecl.new
root = Element.new('html', doc)
root.add_namespace('http://www.w3.org/1999/xhtml')
root.add_namespace('svg', "http://www.w3.org/2000/svg" )
lang = self.attributes[:lang] || 'en'
root.attributes['xml:lang'] = lang
root << xml_newline
head = Element.new 'head', root
#
me = Element.new 'meta', head
me.attributes['http-equiv'] = 'Content-type'
# me.attributes['content'] = 'text/html;charset=utf-8'
me.attributes['content'] = 'application/xhtml+xml;charset=utf-8'
METAS.each do |m|
if value = self.attributes[m.to_sym]
meta = Element.new 'meta', head
meta.attributes['name'] = m
meta.attributes['content'] = value.to_s
end
end
self.attributes.each do |k,v|
if k.to_s =~ /\Ameta-(.*)\Z/
meta = Element.new 'meta', head
meta.attributes['name'] = $1
meta.attributes['content'] = v.to_s
end
end
# Create title element
doc_title = self.attributes[:title] || self.attributes[:subject] || ""
title = Element.new 'title', head
title << Text.new(doc_title)
add_css_to(head)
root << xml_newline
body = Element.new 'body'
children_to_html.each do |e|
body << e
end
# render footnotes
if @doc.footnotes_order.size > 0
body << render_footnotes
end
# When we are rendering a whole document, we add a signature
# at the bottom.
if get_setting(:maruku_signature)
body << maruku_html_signature
end
root << body
doc
end
def add_css_to(head)
if css_list = self.attributes[:css]
css_list.split.each do |css|
#
link = Element.new 'link'
link.attributes['type'] = 'text/css'
link.attributes['rel'] = 'stylesheet'
link.attributes['href'] = css
head << link
head << xml_newline
end
end
end
# returns "st","nd","rd" or "th" as appropriate
def day_suffix(day)
s = {
1 => 'st',
2 => 'nd',
3 => 'rd',
21 => 'st',
22 => 'nd',
23 => 'rd',
31 => 'st'
}
return s[day] || 'th';
end
# formats a nice date
def nice_date
t = Time.now
t.strftime(" at %H:%M on ")+
t.strftime("%A, %B %d")+
day_suffix(t.day)+
t.strftime(", %Y")
end
def maruku_html_signature
div = Element.new 'div'
div.attributes['class'] = 'maruku_signature'
Element.new 'hr', div
span = Element.new 'span', div
span.attributes['style'] = 'font-size: small; font-style: italic'
span << Text.new('Created by ')
a = Element.new('a', span)
a.attributes['href'] = 'http://maruku.rubyforge.org'
a.attributes['title'] = 'Maruku: a Markdown-superset interpreter for Ruby'
a << Text.new('Maruku')
span << Text.new(nice_date+".")
div
end
def render_footnotes()
div = Element.new 'div'
div.attributes['class'] = 'footnotes'
div << Element.new('hr')
ol = Element.new 'ol'
@doc.footnotes_order.each_with_index do |fid, i| num = i+1
f = self.footnotes[fid]
if f
li = f.wrap_as_element('li')
li.attributes['id'] = "#{get_setting(:doc_prefix)}fn:#{num}"
a = Element.new 'a'
a.attributes['href'] = "\##{get_setting(:doc_prefix)}fnref:#{num}"
a.attributes['rev'] = 'footnote'
a<< Text.new('↩', true, nil, true)
li.insert_after(li.children.last, a)
ol << li
else
maruku_error "Could not find footnote id '#{fid}' among ["+
self.footnotes.keys.map{|s|"'"+s+"'"}.join(', ')+"]."
end
end
div << ol
div
end
def to_html_hrule; create_html_element 'hr' end
def to_html_linebreak; Element.new 'br' end
# renders children as html and wraps into an element of given name
#
# Sets 'id' if meta is set
def wrap_as_element(name, attributes_to_copy=[])
m = create_html_element(name, attributes_to_copy)
children_to_html.each do |e| m << e; end
# m << Comment.new( "{"+self.al.to_md+"}") if not self.al.empty?
# m << Comment.new( @attributes.inspect) if not @attributes.empty?
m
end
=begin maruku_doc
Attribute: id
Scope: element
Output: LaTeX, HTML
It is copied as a standard HTML attribute.
Moreover, it used as a label name for hyperlinks in both HTML and
in PDF.
=end
=begin maruku_doc
Attribute: class
Scope: element
Output: HTML
It is copied as a standard HTML attribute.
=end
=begin maruku_doc
Attribute: style
Scope: element
Output: HTML
It is copied as a standard HTML attribute.
=end
HTML4Attributes = {}
coreattrs = [:id, :class, :style, :title]
i18n = [:lang, 'xml:lang'.to_sym]
events = [
:onclick, :ondblclick, :onmousedown, :onmouseup, :onmouseover,
:onmousemove, :onmouseout,
:onkeypress, :onkeydown, :onkeyup]
attrs = coreattrs + i18n + events
cellhalign = [:align, :char, :charoff]
cellvalign = [:valign]
[
['body', attrs + [:onload, :onunload]],
['address', attrs],
['div', attrs],
['a', attrs+[:charset, :type, :name, :rel, :rev, :accesskey, :shape, :coords, :tabindex,
:onfocus,:onblur]],
['img', attrs + [:longdesc, :name, :height, :width, :alt] ],
['p', attrs],
[['h1','h2','h3','h4','h5','h6'], attrs],
[['pre'], attrs],
[['q', 'blockquote'], attrs+[:cite]],
[['ins','del'], attrs+[:cite,:datetime]],
[['ol','ul','li'], attrs],
['table',attrs+[:summary, :width, :frame, :rules, :border, :cellspacing, :cellpadding]],
['caption',attrs],
[['colgroup','col'],attrs+[:span, :width]+cellhalign+cellvalign],
[['thead','tbody','tfoot'], attrs+cellhalign+cellvalign],
[['td','td','th'], attrs+[:abbr, :axis, :headers, :scope, :rowspan, :colspan, :cellvalign, :cellhalign]],
# altri
[['em','code','strong','hr','span','dl','dd','dt'], attrs]
].each do |el, a| [*el].each do |e| HTML4Attributes[e] = a end end
def create_html_element(name, attributes_to_copy=[])
m = Element.new name
if atts = HTML4Attributes[name] then
atts.each do |att|
if v = @attributes[att] then
m.attributes[att.to_s] = v.to_s
end
end
else
# puts "not atts for #{name.inspect}"
end
m
end
def to_html_ul
if @attributes[:toc]
# render toc
html_toc = @doc.toc.to_html
return html_toc
else
add_ws wrap_as_element('ul')
end
end
def to_html_paragraph; add_ws wrap_as_element('p') end
def to_html_ol; add_ws wrap_as_element('ol') end
def to_html_li; add_ws wrap_as_element('li') end
def to_html_li_span; add_ws wrap_as_element('li') end
def to_html_quote; add_ws wrap_as_element('blockquote') end
def to_html_strong; wrap_as_element('strong') end
def to_html_emphasis; wrap_as_element('em') end
=begin maruku_doc
Attribute: use_numbered_headers
Scope: document
Summary: Activates the numbering of headers.
If `true`, section headers will be numbered.
In LaTeX export, the numbering of headers is managed
by Maruku, to have the same results in both HTML and LaTeX.
=end
# nil if not applicable, else string
def section_number
return nil if not get_setting(:use_numbered_headers)
n = @attributes[:section_number]
if n && (not n.empty?)
n.join('.')+". "
else
nil
end
end
# nil if not applicable, else SPAN element
def render_section_number
# if we are bound to a section, add section number
if num = section_number
span = Element.new 'span'
span.attributes['class'] = 'maruku_section_number'
span << Text.new(section_number)
span
else
nil
end
end
def to_html_header
element_name = "h#{self.level}"
h = wrap_as_element element_name
if span = render_section_number
h.insert_before(h.children.first, span)
end
add_ws h
end
def source2html(source)
# source = source.gsub(/&/,'&')
source = Text.normalize(source)
source = source.gsub(/\'/,''') # IE bug
source = source.gsub(/'/,''') # IE bug
Text.new(source, true, nil, true )
end
=begin maruku_doc
Attribute: html_use_syntax
Scope: global, document, element
Output: HTML
Summary: Enables the use of the `syntax` package.
Related: lang, code_lang
Default:
If true, the `syntax` package is used. It supports the `ruby` and `xml`
languages. Remember to set the `lang` attribute of the code block.
Examples:
require 'maruku'
{:lang=ruby html_use_syntax=true}
and
Div
{:lang=html html_use_syntax=true}
produces:
require 'maruku'
{:lang=ruby html_use_syntax=true}
and
Div
{:lang=html html_use_syntax=true}
=end
$syntax_loaded = false
def to_html_code;
source = self.raw_code
lang = self.attributes[:lang] || @doc.attributes[:code_lang]
lang = 'xml' if lang=='html'
use_syntax = get_setting :html_use_syntax
element =
if use_syntax && lang
begin
if not $syntax_loaded
require 'rubygems'
require 'syntax'
require 'syntax/convertors/html'
$syntax_loaded = true
end
convertor = Syntax::Convertors::HTML.for_syntax lang
# eliminate trailing newlines otherwise Syntax crashes
source = source.gsub(/\n*\Z/,'')
html = convertor.convert( source )
html = html.gsub(/\'/,''') # IE bug
html = html.gsub(/'/,''') # IE bug
# html = html.gsub(/&/,'&')
code = Document.new(html, {:respect_whitespace =>:all}).root
code.name = 'code'
code.attributes['class'] = lang
code.attributes['lang'] = lang
pre = Element.new 'pre'
pre << code
pre
rescue LoadError => e
maruku_error "Could not load package 'syntax'.\n"+
"Please install it, for example using 'gem install syntax'."
to_html_code_using_pre(source)
rescue Object => e
maruku_error"Error while using the syntax library for code:\n#{source.inspect}"+
"Lang is #{lang} object is: \n"+
self.inspect +
"\nException: #{e.class}: #{e.message}\n\t#{e.backtrace.join("\n\t")}"
tell_user("Using normal PRE because the syntax library did not work.")
to_html_code_using_pre(source)
end
else
to_html_code_using_pre(source)
end
color = get_setting(:code_background_color)
if color != Globals[:code_background_color]
element.attributes['style'] = "background-color: #{color};"
end
add_ws element
end
=begin maruku_doc
Attribute: code_background_color
Scope: global, document, element
Summary: Background color for code blocks.
The format is either a named color (`green`, `red`) or a CSS color
of the form `#ff00ff`.
* for **HTML output**, the value is put straight in the `background-color` CSS
property of the block.
* for **LaTeX output**, if it is a named color, it must be a color accepted
by the LaTeX `color` packages. If it is of the form `#ff00ff`, Maruku
defines a color using the `\color[rgb]{r,g,b}` macro.
For example, for `#0000ff`, the macro is called as: `\color[rgb]{0,0,1}`.
=end
def to_html_code_using_pre(source)
pre = create_html_element 'pre'
code = Element.new 'code', pre
s = source
# s = s.gsub(/&/,'&')
s = Text.normalize(s)
s = s.gsub(/\'/,''') # IE bug
s = s.gsub(/'/,''') # IE bug
if get_setting(:code_show_spaces)
# 187 = raquo
# 160 = nbsp
# 172 = not
s.gsub!(/\t/,'»'+' '*3)
s.gsub!(/ /,'¬')
end
text = Text.new(s, respect_ws=true, parent=nil, raw=true )
if lang = self.attributes[:lang]
code.attributes['lang'] = lang
code.attributes['class'] = lang
end
code << text
pre
end
def to_html_inline_code;
pre = create_html_element 'code'
source = self.raw_code
pre << source2html(source)
color = get_setting(:code_background_color)
if color != Globals[:code_background_color]
pre.attributes['style'] = "background-color: #{color};"+(pre.attributes['style']||"")
end
pre
end
def add_class_to(el, cl)
el.attributes['class'] =
if already = el.attributes['class']
already + " " + cl
else
cl
end
end
def add_class_to_link(a)
return # not ready yet
# url = a.attributes['href']
# return if not url
#
# if url =~ /^#/
# add_class_to(a, 'maruku-link-samedoc')
# elsif url =~ /^http:/
# add_class_to(a, 'maruku-link-external')
# else
# add_class_to(a, 'maruku-link-local')
# end
#
# puts a.attributes['class']
end
def to_html_immediate_link
a = create_html_element 'a'
url = self.url
text = url.gsub(/^mailto:/,'') # don't show mailto
a << Text.new(text)
a.attributes['href'] = url
add_class_to_link(a)
a
end
def to_html_link
a = wrap_as_element 'a'
id = self.ref_id
if ref = @doc.refs[id]
url = ref[:url]
title = ref[:title]
a.attributes['href'] = url if url
a.attributes['title'] = title if title
else
maruku_error "Could not find ref_id = #{id.inspect} for #{self.inspect}\n"+
"Available refs are #{@doc.refs.keys.inspect}"
tell_user "Not creating a link for ref_id = #{id.inspect}."
return wrap_as_element('span')
end
# add_class_to_link(a)
return a
end
def to_html_im_link
if url = self.url
title = self.title
a = wrap_as_element 'a'
a.attributes['href'] = url
a.attributes['title'] = title if title
return a
else
maruku_error"Could not find url in #{self.inspect}"
tell_user "Not creating a link for ref_id = #{id.inspect}."
return wrap_as_element('span')
end
end
def add_ws(e)
[Text.new("\n"), e, Text.new("\n")]
end
##### Email address
def obfuscate(s)
res = ''
s.each_byte do |char|
res += "%03d;" % char
end
res
end
def to_html_email_address
email = self.email
a = create_html_element 'a'
#a.attributes['href'] = Text.new("mailto:"+obfuscate(email),false,nil,true)
#a.attributes.add Attribute.new('href',Text.new(
#"mailto:"+obfuscate(email),false,nil,true))
# Sorry, for the moment it doesn't work
a.attributes['href'] = "mailto:#{email}"
a << Text.new(obfuscate(email),false,nil,true)
a
end
##### Images
def to_html_image
a = create_html_element 'img'
id = self.ref_id
if ref = @doc.refs[id]
url = ref[:url]
title = ref[:title]
a.attributes['src'] = url.to_s
a.attributes['alt'] = children_to_s
else
maruku_error"Could not find id = #{id.inspect} for\n #{self.inspect}"
tell_user "Could not create image with ref_id = #{id.inspect};"+
" Using SPAN element as replacement."
return wrap_as_element('span')
end
return a
end
def to_html_im_image
if not url = self.url
maruku_error "Image with no url: #{self.inspect}"
tell_user "Could not create image with ref_id = #{id.inspect};"+
" Using SPAN element as replacement."
return wrap_as_element('span')
end
title = self.title
a = create_html_element 'img'
a.attributes['src'] = url.to_s
a.attributes['alt'] = children_to_s
return a
end
=begin maruku_doc
Attribute: filter_html
Scope: document
If true, raw HTML is discarded from the output.
=end
def to_html_raw_html
return [] if get_setting(:filter_html)
raw_html = self.raw_html
if rexml_doc = @parsed_html
root = rexml_doc.root
if root.nil?
s = "Bug in REXML: root() of Document is nil: \n#{rexml_doc.inspect}\n"+
"Raw HTML:\n#{raw_html.inspect}"
maruku_error s
tell_user 'The REXML version you have has a bug, omitting HTML'
div = Element.new 'div'
#div << Text.new(s)
return div
end
# copies the @children array (FIXME is it deep?)
elements = root.to_a
return elements
else # invalid
# Creates red box with offending HTML
tell_user "Wrapping bad html in a PRE with class 'markdown-html-error'\n"+
add_tabs(raw_html,1,'|')
pre = Element.new('pre')
pre.attributes['style'] = 'border: solid 3px red; background-color: pink'
pre.attributes['class'] = 'markdown-html-error'
pre << Text.new("REXML could not parse this XML/HTML: \n#{raw_html}", true)
return pre
end
end
def to_html_abbr
abbr = Element.new 'abbr'
abbr << Text.new(children[0])
abbr.attributes['title'] = self.title if self.title
abbr
end
def to_html_footnote_reference
id = self.footnote_id
# save the order of used footnotes
order = @doc.footnotes_order
if order.include? id
# footnote has already been used
return []
end
if not @doc.footnotes[id]
return []
end
# take next number
order << id
#num = order.size;
num = order.index(id) + 1
sup = Element.new 'sup'
sup.attributes['id'] = "#{get_setting(:doc_prefix)}fnref:#{num}"
a = Element.new 'a'
a << Text.new(num.to_s)
a.attributes['href'] = "\##{get_setting(:doc_prefix)}fn:#{num}"
a.attributes['rel'] = 'footnote'
sup << a
sup
end
## Definition lists ###
def to_html_definition_list() add_ws wrap_as_element('dl') end
def to_html_definition() children_to_html end
def to_html_definition_term() add_ws wrap_as_element('dt') end
def to_html_definition_data() add_ws wrap_as_element('dd') end
# FIXME: Ugly code
def to_html_table
align = self.align
num_columns = align.size
head = @children.slice(0, num_columns)
rows = []
i = num_columns
while i<@children.size
rows << @children.slice(i, num_columns)
i += num_columns
end
table = create_html_element 'table'
thead = Element.new 'thead'
tr = Element.new 'tr'
array_to_html(head).each do |x| tr<