catfist
9/23/2014 - 8:54 PM

cebe\markdownを拡張してMarkdownにルビと傍点の記法を追加する

cebe\markdownを拡張してMarkdownにルビと傍点の記法を追加する

<?php
class MarkdownStory extends cebe\markdown\Markdown
{
	/**
	 * @var boolean whether to interpret newlines as `<br />`-tags.
	 * This feature is useful for comments where newlines are often meant to be real new lines.
	 */
	public $enableNewlines = true;

	/**
	 * @inheritDoc
	 */
	protected $escapeCharacters = [
		// from Markdown
		'\\', // backslash
		'`', // backtick
		'*', // asterisk
		'_', // underscore
		'{', '}', // curly braces
		'[', ']', // square brackets
		'(', ')', // parentheses
		'#', // hash mark
		'+', // plus sign
		'-', // minus sign (hyphen)
		'.', // dot
		'!', // exclamation mark
		'<', '>',
		// from GithubMarkdown
		':', // colon
		'|', // pipe
		// added by Yarkdown
		'^', // circumflex
	];

	private $_specialAttributesRegex = '\{(([#\.][A-z0-9-_]+\s*)+)\}';

	protected $first_section = true;

	/**
	 * @inheritDoc
	 */
	protected function inlineMarkers()
	{
		return parent::inlineMarkers() + [
			'^'  => 'parseRuby',
			'.'  => 'parseEmphDot',
		];
	}


	// inline parsing


	/**
	 * Parses the ruby annotation feature.
	 */
	protected function parseRuby($markdown)
	{
		if (preg_match('/^\^(.+?)\((.+?)\)/', $markdown, $matches)) {
			return [
				"<ruby><rb>{$matches[1]}</rb><rp>(</rp><rt>{$matches[2]}</rt><rp>)</rp></ruby>",
				strlen($matches[0])
			];
		}
		return [$markdown[0] . $markdown[1], 2];
	}

	/**
	 * Parses the emphasis dot feature.
	 */
	protected function parseEmphDot($markdown)
	{
		if (preg_match('/^\.\.(.+?)\.\./', $markdown, $matches)) {
			return [
				implode('', array_map(function($char){
					return "<em><span>{$char}</span></em>";
				}, preg_split("//u", $matches[1], -1, PREG_SPLIT_NO_EMPTY))),
				strlen($matches[0])
			];
		}
		return [$markdown[0] . $markdown[1], 2];
	}
}