s around # "paragraphs" that are wrapped in non-block-level tags, such as anchors, # phrase emphasis, and spans. The list of tags we're looking for is # hard-coded: $block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. 'script|noscript|form|fieldset|iframe|math|ins|del'; $block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. 'script|noscript|form|fieldset|iframe|math'; # Regular expression for the content of a block tag. $nested_tags_level = 4; $attr = ' (?> # optional tag attributes \s # starts with whitespace (?> [^>"/]+ # text outside quotes | /+(?!>) # slash not followed by ">" | "[^"]*" # text inside double quotes (tolerate ">") | \'[^\']*\' # text inside single quotes (tolerate ">") )* )? '; $content = str_repeat(' (?> [^<]+ # content without tag | <\2 # nested opening tag '.$attr.' # attributes (?: /> | >', $nested_tags_level). # end of opening tag '.*?'. # last level nested tag content str_repeat(' \2\s*> # closing nested tag ) | <(?!/\2\s*> # other tags with a different name ) )*', $nested_tags_level); # First, look for nested blocks, e.g.: #
` blocks.
#
$text = preg_replace_callback('{
(?:\n\n|\A)
( # $1 = the code block -- one or more lines, starting with a space/tab
(?:
(?:[ ]{'.$this->tab_width.'} | \t) # Lines must start with a tab or a tab-width of spaces
.*\n+
)+
)
((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
}xm',
array(&$this, '_doCodeBlocks_callback'), $text);
return $text;
}
function _doCodeBlocks_callback($matches) {
$codeblock = $matches[1];
$codeblock = $this->encodeCode($this->outdent($codeblock));
// $codeblock = $this->detab($codeblock);
# trim leading newlines and trailing whitespace
$codeblock = preg_replace(array('/\A\n+/', '/\n+\z/'), '', $codeblock);
$result = "\n\n".$this->hashBlock("" . $codeblock . "\n
")."\n\n";
return $result;
}
function doCodeSpans($text) {
#
# * Backtick quotes are used for spans.
#
# * You can use multiple backticks as the delimiters if you want to
# include literal backticks in the code span. So, this input:
#
# Just type ``foo `bar` baz`` at the prompt.
#
# Will translate to:
#
# Just type foo `bar` baz at the prompt.
#
# There's no arbitrary limit to the number of backticks you
# can use as delimters. If you need three consecutive backticks
# in your code, use four for delimiters, etc.
#
# * You can use spaces to get literal backticks at the edges:
#
# ... type `` `bar` `` ...
#
# Turns to:
#
# ... type `bar` ...
#
$text = preg_replace_callback('@
(?encodeCode($c);
return $this->hashSpan("$c");
}
function encodeCode($_) {
#
# Encode/escape certain characters inside Markdown code runs.
# The point is that in code, these characters are literals,
# and lose their special Markdown meanings.
#
# Encode all ampersands; HTML entities are not
# entities within a Markdown code span.
$_ = str_replace('&', '&', $_);
# Do the angle bracket song and dance:
$_ = str_replace(array('<', '>'),
array('<', '>'), $_);
# Now, escape characters that are magic in Markdown:
// $_ = str_replace(array_keys($this->escape_table),
// array_values($this->escape_table), $_);
return $_;
}
function doItalicsAndBold($text) {
# must go first:
$text = preg_replace_callback('{
( # $1: Marker
(?
[^*_]+? # Anthing not em markers.
|
# Balence any regular emphasis inside.
\1 (?=\S) .+? (?<=\S) \1
|
. # Allow unbalenced * and _.
)+?
)
(?<=\S) \1\1 # End mark not preceded by whitespace.
}sx',
array(&$this, '_doItalicAndBold_strong_callback'), $text);
# Then :
$text = preg_replace_callback(
'{ ( (?runSpanGamut($text);
return $this->hashSpan("$text");
}
function _doItalicAndBold_strong_callback($matches) {
$text = $matches[2];
$text = $this->runSpanGamut($text);
return $this->hashSpan("$text");
}
function doBlockQuotes($text) {
$text = preg_replace_callback('/
( # Wrap whole match in $1
(
^[ ]*>[ ]? # ">" at the start of a line
.+\n # rest of the first line
(.+\n)* # subsequent consecutive lines
\n* # blanks
)+
)
/xm',
array(&$this, '_doBlockQuotes_callback'), $text);
return $text;
}
function _doBlockQuotes_callback($matches) {
$bq = $matches[1];
# trim one level of quoting - trim whitespace-only lines
$bq = preg_replace(array('/^[ ]*>[ ]?/m', '/^[ ]+$/m'), '', $bq);
$bq = $this->runBlockGamut($bq); # recurse
$bq = preg_replace('/^/m', " ", $bq);
# These leading spaces cause problem with content,
# so we need to fix that:
$bq = preg_replace_callback('{(\s*.+?
)}sx',
array(&$this, '_DoBlockQuotes_callback2'), $bq);
return "\n". $this->hashBlock("\n$bq\n
")."\n\n";
}
function _doBlockQuotes_callback2($matches) {
$pre = $matches[1];
$pre = preg_replace('/^ /m', '', $pre);
return $pre;
}
function formParagraphs($text) {
#
# Params:
# $text - string to process with html tags
#
# Strip leading and trailing lines:
$text = preg_replace(array('/\A\n+/', '/\n+\z/'), '', $text);
$grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
#
# Wrap
tags.
#
foreach ($grafs as $key => $value) {
if (!isset( $this->html_blocks[$value] )) {
$value = $this->runSpanGamut($value);
$value = preg_replace('/^([ ]*)/', "
", $value);
$value .= "
";
$grafs[$key] = $this->unhash($value);
}
}
#
# Unhashify HTML blocks
#
foreach ($grafs as $key => $graf) {
# Modify elements of @grafs in-place...
if (isset($this->html_blocks[$graf])) {
$block = $this->html_blocks[$graf];
$graf = $block;
// if (preg_match('{
// \A
// ( # $1 = tag
// ]*
// \b
// markdown\s*=\s* ([\'"]) # $2 = attr quote char
// 1
// \2
// [^>]*
// >
// )
// ( # $3 = contents
// .*
// )
// () # $4 = closing tag
// \z
// }xs', $block, $matches))
// {
// list(, $div_open, , $div_content, $div_close) = $matches;
//
// # We can't call Markdown(), because that resets the hash;
// # that initialization code should be pulled into its own sub, though.
// $div_content = $this->hashHTMLBlocks($div_content);
//
// # Run document gamut methods on the content.
// foreach ($this->document_gamut as $method => $priority) {
// $div_content = $this->$method($div_content);
// }
//
// $div_open = preg_replace(
// '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
//
// $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
// }
$grafs[$key] = $graf;
}
}
return implode("\n\n", $grafs);
}
function encodeAmpsAndAngles($text) {
# Smart processing for ampersands and angle brackets that need to be encoded.
# Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
# http://bumppo.net/projects/amputator/
$text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
'&', $text);;
# Encode naked <'s
$text = preg_replace('{<(?![a-z/?\$!%])}i', '<', $text);
return $text;
}
function encodeBackslashEscapes($text) {
#
# Parameter: String.
# Returns: The string, with after processing the following backslash
# escape sequences.
#
# Must process escaped backslashes first.
return str_replace(array_keys($this->backslash_escape_table),
array_values($this->backslash_escape_table), $text);
}
function doAutoLinks($text) {
$text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}',
array(&$this, '_doAutoLinks_url_callback'), $text);
# Email addresses:
$text = preg_replace_callback('{
<
(?:mailto:)?
(
[-.\w\x80-\xFF]+
\@
[-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
)
>
}xi',
array(&$this, '_doAutoLinks_email_callback'), $text);
return $text;
}
function _doAutoLinks_url_callback($matches) {
$url = $this->encodeAmpsAndAngles($matches[1]);
$link = "$url";
return $this->hashSpan($link);
}
function _doAutoLinks_email_callback($matches) {
$address = $matches[1];
$link = $this->encodeEmailAddress($address);
return $this->hashSpan($link);
}
function encodeEmailAddress($addr) {
#
# Input: an email address, e.g. "foo@example.com"
#
# Output: the email address as a mailto link, with each character
# of the address encoded as either a decimal or hex entity, in
# the hopes of foiling most address harvesting spam bots. E.g.:
#
#
#
# Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
# With some optimizations by Milian Wolff.
#
$addr = "mailto:" . $addr;
$chars = preg_split('/(? $char) {
$ord = ord($char);
# Ignore non-ascii chars.
if ($ord < 128) {
$r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
# roughly 10% raw, 45% hex, 45% dec
# '@' *must* be encoded. I insist.
if ($r > 90 && $char != '@') /* do nothing */;
else if ($r < 45) $chars[$key] = ''.dechex($ord).';';
else $chars[$key] = ''.$ord.';';
}
}
$addr = implode('', $chars);
$text = implode('', array_slice($chars, 7)); # text without `mailto:`
$addr = "$text";
return $addr;
}
function tokenizeHTML($str) {
#
# Parameter: String containing HTML + Markdown markup.
# Returns: An array of the tokens comprising the input
# string. Each token is either a tag or a run of text
# between tags. Each element of the array is a
# two-element array; the first is either 'tag' or 'text';
# the second is the actual value.
# Note: Markdown code spans are taken into account: no tag token is
# generated within a code span.
#
$tokens = array();
while ($str != "") {
#
# Each loop iteration seach for either the next tag or the next
# openning code span marker. If a code span marker is found, the
# code span is extracted in entierty and will result in an extra
# text token.
#
$parts = preg_split('{
(
(? # comment
|
<\?.*?\?> | <%.*?%> # processing instruction
|
<[/!$]?[-a-zA-Z0-9:]+ # regular tags
(?:
\s
(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
)?
>
)
}xs', $str, 2, PREG_SPLIT_DELIM_CAPTURE);
# Create token from text preceding tag.
if ($parts[0] != "") {
$tokens[] = array('text', $parts[0]);
}
# Check if we reach the end.
if (count($parts) < 3) {
break;
}
# Create token from tag or code span.
if ($parts[1]{0} == "`") {
$tokens[] = array('text', $parts[1]);
$str = $parts[2];
# Skip the whole code span, pass as text token.
if (preg_match('/^(.*(?tab_width})/m", "", $text);
}
# String length function for detab. `_initDetab` will create a function to
# hanlde UTF-8 if the default function does not exist.
var $utf8_strlen = 'mb_strlen';
function detab($text) {
#
# Replace tabs with the appropriate amount of space.
#
# For each line we separate the line in blocks delemited by
# tab characters. Then we reconstruct every line by adding the
# appropriate number of space between each blocks.
$strlen = $this->utf8_strlen; # strlen function for UTF-8.
$lines = explode("\n", $text);
$text = "";
foreach ($lines as $line) {
# Split in blocks.
$blocks = explode("\t", $line);
# Add each blocks to the line.
$line = $blocks[0];
unset($blocks[0]); # Do not add first block twice.
foreach ($blocks as $block) {
# Calculate amount of space, insert spaces, insert block.
$amount = $this->tab_width -
$strlen($line, 'UTF-8') % $this->tab_width;
$line .= str_repeat(" ", $amount) . $block;
}
$text .= "$line\n";
}
return $text;
}
function _initDetab() {
#
# Check for the availability of the function in the `utf8_strlen` property
# (initially `mb_strlen`). If the function is not available, create a
# function that will loosely count the number of UTF-8 characters with a
# regular expression.
#
if (function_exists($this->utf8_strlen)) return;
$this->utf8_strlen = create_function('$text', 'return preg_match_all(
"/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
$text, $m);');
}
function unhash($text) {
#
# Swap back in all the tags hashed by _HashHTMLBlocks.
#
return str_replace(array_keys($this->html_hashes),
array_values($this->html_hashes), $text);
}
}
} // end defined( 'GRUBER_MARKDOWN' );
/*
PHP Markdown
============
Description
-----------
This is a PHP translation of the original Markdown formatter written in
Perl by John Gruber.
Markdown is a text-to-HTML filter; it translates an easy-to-read /
easy-to-write structured text format into HTML. Markdown's text format
is most similar to that of plain text email, and supports features such
as headers, *emphasis*, code blocks, blockquotes, and links.
Markdown's syntax is designed not as a generic markup language, but
specifically to serve as a front-end to (X)HTML. You can use span-level
HTML tags anywhere in a Markdown document, and you can use block level
HTML tags (like and as well).
For more information about Markdown's syntax, see:
Bugs
----
To file bug reports please send email to:
Please include with your report: (1) the example input; (2) the output you
expected; (3) the output Markdown actually produced.
Version History
---------------
See the readme file for detailed release notes for this version.
1.0.1g (3 Jul 2007)
1.0.1f (7 Feb 2007)
1.0.1e (28 Dec 2006)
1.0.1d (1 Dec 2006)
1.0.1c (9 Dec 2005)
1.0.1b (6 Jun 2005)
1.0.1a (15 Apr 2005)
1.0.1 (16 Dec 2004)
1.0 (21 Aug 2004)
Copyright and License
---------------------
PHP Markdown
Copyright (c) 2004-2007 Michel Fortin
All rights reserved.
Based on Markdown
Copyright (c) 2003-2006 John Gruber
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name "Markdown" nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.
This software is provided by the copyright holders and contributors "as
is" and any express or implied warranties, including, but not limited
to, the implied warranties of merchantability and fitness for a
particular purpose are disclaimed. In no event shall the copyright owner
or contributors be liable for any direct, indirect, incidental, special,
exemplary, or consequential damages (including, but not limited to,
procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including
negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/
?>