Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Markdown_Parser often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Markdown_Parser, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
223 | class Markdown_Parser { |
||
224 | |||
225 | ### Configuration Variables ### |
||
226 | |||
227 | # Change to ">" for HTML output. |
||
228 | var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX; |
||
229 | var $tab_width = MARKDOWN_TAB_WIDTH; |
||
230 | |||
231 | # Change to `true` to disallow markup or entities. |
||
232 | var $no_markup = false; |
||
233 | var $no_entities = false; |
||
234 | |||
235 | # Predefined urls and titles for reference links and images. |
||
236 | var $predef_urls = array(); |
||
237 | var $predef_titles = array(); |
||
238 | |||
239 | |||
240 | ### Parser Implementation ### |
||
241 | |||
242 | # Regex to match balanced [brackets]. |
||
243 | # Needed to insert a maximum bracked depth while converting to PHP. |
||
244 | var $nested_brackets_depth = 6; |
||
245 | var $nested_brackets_re; |
||
246 | |||
247 | var $nested_url_parenthesis_depth = 4; |
||
248 | var $nested_url_parenthesis_re; |
||
249 | |||
250 | # Table of hash values for escaped characters: |
||
251 | var $escape_chars = '\`*_{}[]()>#+-.!'; |
||
252 | var $escape_chars_re; |
||
253 | |||
254 | |||
255 | function Markdown_Parser() { |
||
256 | # |
||
257 | # Constructor function. Initialize appropriate member variables. |
||
258 | # |
||
259 | $this->_initDetab(); |
||
260 | $this->prepareItalicsAndBold(); |
||
261 | |||
262 | $this->nested_brackets_re = |
||
263 | str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). |
||
264 | str_repeat('\])*', $this->nested_brackets_depth); |
||
265 | |||
266 | $this->nested_url_parenthesis_re = |
||
267 | str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). |
||
268 | str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); |
||
269 | |||
270 | $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; |
||
271 | |||
272 | # Sort document, block, and span gamut in ascendent priority order. |
||
273 | asort($this->document_gamut); |
||
274 | asort($this->block_gamut); |
||
275 | asort($this->span_gamut); |
||
276 | } |
||
277 | |||
278 | |||
279 | # Internal hashes used during transformation. |
||
280 | var $urls = array(); |
||
281 | var $titles = array(); |
||
282 | var $html_hashes = array(); |
||
283 | |||
284 | # Status flag to avoid invalid nesting. |
||
285 | var $in_anchor = false; |
||
286 | |||
287 | |||
288 | function setup() { |
||
289 | # |
||
290 | # Called before the transformation process starts to setup parser |
||
291 | # states. |
||
292 | # |
||
293 | # Clear global hashes. |
||
294 | $this->urls = $this->predef_urls; |
||
295 | $this->titles = $this->predef_titles; |
||
296 | $this->html_hashes = array(); |
||
297 | |||
298 | $this->in_anchor = false; |
||
299 | } |
||
300 | |||
301 | function teardown() { |
||
302 | # |
||
303 | # Called after the transformation process to clear any variable |
||
304 | # which may be taking up memory unnecessarly. |
||
305 | # |
||
306 | $this->urls = array(); |
||
307 | $this->titles = array(); |
||
308 | $this->html_hashes = array(); |
||
309 | } |
||
310 | |||
311 | |||
312 | function transform($text) { |
||
313 | # |
||
314 | # Main function. Performs some preprocessing on the input text |
||
315 | # and pass it through the document gamut. |
||
316 | # |
||
317 | $this->setup(); |
||
318 | |||
319 | # Remove UTF-8 BOM and marker character in input, if present. |
||
320 | $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); |
||
321 | |||
322 | # Standardize line endings: |
||
323 | # DOS to Unix and Mac to Unix |
||
324 | $text = preg_replace('{\r\n?}', "\n", $text); |
||
325 | |||
326 | # Make sure $text ends with a couple of newlines: |
||
327 | $text .= "\n\n"; |
||
328 | |||
329 | # Convert all tabs to spaces. |
||
330 | $text = $this->detab($text); |
||
331 | |||
332 | # Turn block-level HTML blocks into hash entries |
||
333 | $text = $this->hashHTMLBlocks($text); |
||
334 | |||
335 | # Strip any lines consisting only of spaces and tabs. |
||
336 | # This makes subsequent regexen easier to write, because we can |
||
337 | # match consecutive blank lines with /\n+/ instead of something |
||
338 | # contorted like /[ ]*\n+/ . |
||
339 | $text = preg_replace('/^[ ]+$/m', '', $text); |
||
340 | |||
341 | # Run document gamut methods. |
||
342 | foreach ($this->document_gamut as $method => $priority) { |
||
343 | $text = $this->$method($text); |
||
344 | } |
||
345 | |||
346 | $this->teardown(); |
||
347 | |||
348 | return $text . "\n"; |
||
349 | } |
||
350 | |||
351 | var $document_gamut = array( |
||
352 | # Strip link definitions, store in hashes. |
||
353 | "stripLinkDefinitions" => 20, |
||
354 | |||
355 | "runBasicBlockGamut" => 30, |
||
356 | ); |
||
357 | |||
358 | |||
359 | function stripLinkDefinitions($text) { |
||
360 | # |
||
361 | # Strips link definitions from text, stores the URLs and titles in |
||
362 | # hash references. |
||
363 | # |
||
364 | $less_than_tab = $this->tab_width - 1; |
||
365 | |||
366 | # Link defs are in the form: ^[id]: url "optional title" |
||
367 | $text = preg_replace_callback('{ |
||
368 | ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 |
||
369 | [ ]* |
||
370 | \n? # maybe *one* newline |
||
371 | [ ]* |
||
372 | (?: |
||
373 | <(.+?)> # url = $2 |
||
374 | | |
||
375 | (\S+?) # url = $3 |
||
376 | ) |
||
377 | [ ]* |
||
378 | \n? # maybe one newline |
||
379 | [ ]* |
||
380 | (?: |
||
381 | (?<=\s) # lookbehind for whitespace |
||
382 | ["(] |
||
383 | (.*?) # title = $4 |
||
384 | [")] |
||
385 | [ ]* |
||
386 | )? # title is optional |
||
387 | (?:\n+|\Z) |
||
388 | }xm', |
||
389 | array(&$this, '_stripLinkDefinitions_callback'), |
||
390 | $text); |
||
391 | return $text; |
||
392 | } |
||
393 | function _stripLinkDefinitions_callback($matches) { |
||
394 | $link_id = strtolower($matches[1]); |
||
395 | $url = $matches[2] == '' ? $matches[3] : $matches[2]; |
||
396 | $this->urls[$link_id] = $url; |
||
397 | $this->titles[$link_id] =& $matches[4]; |
||
398 | return ''; # String that will replace the block |
||
399 | } |
||
400 | |||
401 | |||
402 | function hashHTMLBlocks($text) { |
||
403 | if ($this->no_markup) return $text; |
||
404 | |||
405 | $less_than_tab = $this->tab_width - 1; |
||
406 | |||
407 | # Hashify HTML blocks: |
||
408 | # We only want to do this for block-level HTML tags, such as headers, |
||
409 | # lists, and tables. That's because we still want to wrap <p>s around |
||
410 | # "paragraphs" that are wrapped in non-block-level tags, such as anchors, |
||
411 | # phrase emphasis, and spans. The list of tags we're looking for is |
||
412 | # hard-coded: |
||
413 | # |
||
414 | # * List "a" is made of tags which can be both inline or block-level. |
||
415 | # These will be treated block-level when the start tag is alone on |
||
416 | # its line, otherwise they're not matched here and will be taken as |
||
417 | # inline later. |
||
418 | # * List "b" is made of tags which are always block-level; |
||
419 | # |
||
420 | $block_tags_a_re = 'ins|del'; |
||
421 | $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. |
||
422 | 'script|noscript|form|fieldset|iframe|math|svg|'. |
||
423 | 'article|section|nav|aside|hgroup|header|footer|'. |
||
424 | 'figure'; |
||
425 | |||
426 | # Regular expression for the content of a block tag. |
||
427 | $nested_tags_level = 4; |
||
428 | $attr = ' |
||
429 | (?> # optional tag attributes |
||
430 | \s # starts with whitespace |
||
431 | (?> |
||
432 | [^>"/]+ # text outside quotes |
||
433 | | |
||
434 | /+(?!>) # slash not followed by ">" |
||
435 | | |
||
436 | "[^"]*" # text inside double quotes (tolerate ">") |
||
437 | | |
||
438 | \'[^\']*\' # text inside single quotes (tolerate ">") |
||
439 | )* |
||
440 | )? |
||
441 | '; |
||
442 | $content = |
||
443 | str_repeat(' |
||
444 | (?> |
||
445 | [^<]+ # content without tag |
||
446 | | |
||
447 | <\2 # nested opening tag |
||
448 | '.$attr.' # attributes |
||
449 | (?> |
||
450 | /> |
||
451 | | |
||
452 | >', $nested_tags_level). # end of opening tag |
||
453 | '.*?'. # last level nested tag content |
||
454 | str_repeat(' |
||
455 | </\2\s*> # closing nested tag |
||
456 | ) |
||
457 | | |
||
458 | <(?!/\2\s*> # other tags with a different name |
||
459 | ) |
||
460 | )*', |
||
461 | $nested_tags_level); |
||
462 | $content2 = str_replace('\2', '\3', $content); |
||
463 | |||
464 | # First, look for nested blocks, e.g.: |
||
465 | # <div> |
||
466 | # <div> |
||
467 | # tags for inner block must be indented. |
||
468 | # </div> |
||
469 | # </div> |
||
470 | # |
||
471 | # The outermost tags must start at the left margin for this to match, and |
||
472 | # the inner nested divs must be indented. |
||
473 | # We need to do this before the next, more liberal match, because the next |
||
474 | # match will start at the first `<div>` and stop at the first `</div>`. |
||
475 | $text = preg_replace_callback('{(?> |
||
476 | (?> |
||
477 | (?<=\n\n) # Starting after a blank line |
||
478 | | # or |
||
479 | \A\n? # the beginning of the doc |
||
480 | ) |
||
481 | ( # save in $1 |
||
482 | |||
483 | # Match from `\n<tag>` to `</tag>\n`, handling nested tags |
||
484 | # in between. |
||
485 | |||
486 | [ ]{0,'.$less_than_tab.'} |
||
487 | <('.$block_tags_b_re.')# start tag = $2 |
||
488 | '.$attr.'> # attributes followed by > and \n |
||
489 | '.$content.' # content, support nesting |
||
490 | </\2> # the matching end tag |
||
491 | [ ]* # trailing spaces/tabs |
||
492 | (?=\n+|\Z) # followed by a newline or end of document |
||
493 | |||
494 | | # Special version for tags of group a. |
||
495 | |||
496 | [ ]{0,'.$less_than_tab.'} |
||
497 | <('.$block_tags_a_re.')# start tag = $3 |
||
498 | '.$attr.'>[ ]*\n # attributes followed by > |
||
499 | '.$content2.' # content, support nesting |
||
500 | </\3> # the matching end tag |
||
501 | [ ]* # trailing spaces/tabs |
||
502 | (?=\n+|\Z) # followed by a newline or end of document |
||
503 | |||
504 | | # Special case just for <hr />. It was easier to make a special |
||
505 | # case than to make the other regex more complicated. |
||
506 | |||
507 | [ ]{0,'.$less_than_tab.'} |
||
508 | <(hr) # start tag = $2 |
||
509 | '.$attr.' # attributes |
||
510 | /?> # the matching end tag |
||
511 | [ ]* |
||
512 | (?=\n{2,}|\Z) # followed by a blank line or end of document |
||
513 | |||
514 | | # Special case for standalone HTML comments: |
||
515 | |||
516 | [ ]{0,'.$less_than_tab.'} |
||
517 | (?s: |
||
518 | <!-- .*? --> |
||
519 | ) |
||
520 | [ ]* |
||
521 | (?=\n{2,}|\Z) # followed by a blank line or end of document |
||
522 | |||
523 | | # PHP and ASP-style processor instructions (<? and <%) |
||
524 | |||
525 | [ ]{0,'.$less_than_tab.'} |
||
526 | (?s: |
||
527 | <([?%]) # $2 |
||
528 | .*? |
||
529 | \2> |
||
530 | ) |
||
531 | [ ]* |
||
532 | (?=\n{2,}|\Z) # followed by a blank line or end of document |
||
533 | |||
534 | ) |
||
535 | )}Sxmi', |
||
536 | array(&$this, '_hashHTMLBlocks_callback'), |
||
537 | $text); |
||
538 | |||
539 | return $text; |
||
540 | } |
||
541 | function _hashHTMLBlocks_callback($matches) { |
||
542 | $text = $matches[1]; |
||
543 | $key = $this->hashBlock($text); |
||
544 | return "\n\n$key\n\n"; |
||
545 | } |
||
546 | |||
547 | |||
548 | function hashPart($text, $boundary = 'X') { |
||
549 | # |
||
550 | # Called whenever a tag must be hashed when a function insert an atomic |
||
551 | # element in the text stream. Passing $text to through this function gives |
||
552 | # a unique text-token which will be reverted back when calling unhash. |
||
553 | # |
||
554 | # The $boundary argument specify what character should be used to surround |
||
555 | # the token. By convension, "B" is used for block elements that needs not |
||
556 | # to be wrapped into paragraph tags at the end, ":" is used for elements |
||
557 | # that are word separators and "X" is used in the general case. |
||
558 | # |
||
559 | # Swap back any tag hash found in $text so we do not have to `unhash` |
||
560 | # multiple times at the end. |
||
561 | $text = $this->unhash($text); |
||
562 | |||
563 | # Then hash the block. |
||
564 | static $i = 0; |
||
565 | $key = "$boundary\x1A" . ++$i . $boundary; |
||
566 | $this->html_hashes[$key] = $text; |
||
567 | return $key; # String that will replace the tag. |
||
568 | } |
||
569 | |||
570 | |||
571 | function hashBlock($text) { |
||
572 | # |
||
573 | # Shortcut function for hashPart with block-level boundaries. |
||
574 | # |
||
575 | return $this->hashPart($text, 'B'); |
||
576 | } |
||
577 | |||
578 | |||
579 | var $block_gamut = array( |
||
580 | # |
||
581 | # These are all the transformations that form block-level |
||
582 | # tags like paragraphs, headers, and list items. |
||
583 | # |
||
584 | "doHeaders" => 10, |
||
585 | "doHorizontalRules" => 20, |
||
586 | |||
587 | "doLists" => 40, |
||
588 | "doCodeBlocks" => 50, |
||
589 | "doBlockQuotes" => 60, |
||
590 | ); |
||
591 | |||
592 | function runBlockGamut($text) { |
||
593 | # |
||
594 | # Run block gamut tranformations. |
||
595 | # |
||
596 | # We need to escape raw HTML in Markdown source before doing anything |
||
597 | # else. This need to be done for each block, and not only at the |
||
598 | # begining in the Markdown function since hashed blocks can be part of |
||
599 | # list items and could have been indented. Indented blocks would have |
||
600 | # been seen as a code block in a previous pass of hashHTMLBlocks. |
||
601 | $text = $this->hashHTMLBlocks($text); |
||
602 | |||
603 | return $this->runBasicBlockGamut($text); |
||
604 | } |
||
605 | |||
606 | function runBasicBlockGamut($text) { |
||
607 | # |
||
608 | # Run block gamut tranformations, without hashing HTML blocks. This is |
||
609 | # useful when HTML blocks are known to be already hashed, like in the first |
||
610 | # whole-document pass. |
||
611 | # |
||
612 | foreach ($this->block_gamut as $method => $priority) { |
||
613 | $text = $this->$method($text); |
||
614 | } |
||
615 | |||
616 | # Finally form paragraph and restore hashed blocks. |
||
617 | $text = $this->formParagraphs($text); |
||
618 | |||
619 | return $text; |
||
620 | } |
||
621 | |||
622 | |||
623 | function doHorizontalRules($text) { |
||
624 | # Do Horizontal Rules: |
||
625 | return preg_replace( |
||
626 | '{ |
||
627 | ^[ ]{0,3} # Leading space |
||
628 | ([-*_]) # $1: First marker |
||
629 | (?> # Repeated marker group |
||
630 | [ ]{0,2} # Zero, one, or two spaces. |
||
631 | \1 # Marker character |
||
632 | ){2,} # Group repeated at least twice |
||
633 | [ ]* # Tailing spaces |
||
634 | $ # End of line. |
||
635 | }mx', |
||
636 | "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n", |
||
637 | $text); |
||
638 | } |
||
639 | |||
640 | |||
641 | var $span_gamut = array( |
||
642 | # |
||
643 | # These are all the transformations that occur *within* block-level |
||
644 | # tags like paragraphs, headers, and list items. |
||
645 | # |
||
646 | # Process character escapes, code spans, and inline HTML |
||
647 | # in one shot. |
||
648 | "parseSpan" => -30, |
||
649 | |||
650 | # Process anchor and image tags. Images must come first, |
||
651 | # because ![foo][f] looks like an anchor. |
||
652 | "doImages" => 10, |
||
653 | "doAnchors" => 20, |
||
654 | |||
655 | # Make links out of things like `<http://example.com/>` |
||
656 | # Must come after doAnchors, because you can use < and > |
||
657 | # delimiters in inline links like [this](<url>). |
||
658 | "doAutoLinks" => 30, |
||
659 | "encodeAmpsAndAngles" => 40, |
||
660 | |||
661 | "doItalicsAndBold" => 50, |
||
662 | "doHardBreaks" => 60, |
||
663 | ); |
||
664 | |||
665 | function runSpanGamut($text) { |
||
666 | # |
||
667 | # Run span gamut tranformations. |
||
668 | # |
||
669 | foreach ($this->span_gamut as $method => $priority) { |
||
670 | $text = $this->$method($text); |
||
671 | } |
||
672 | |||
673 | return $text; |
||
674 | } |
||
675 | |||
676 | |||
677 | function doHardBreaks($text) { |
||
678 | # Do hard breaks: |
||
679 | return preg_replace_callback('/ {2,}\n/', |
||
680 | array(&$this, '_doHardBreaks_callback'), $text); |
||
681 | } |
||
682 | function _doHardBreaks_callback($matches) { |
||
683 | return $this->hashPart("<br$this->empty_element_suffix\n"); |
||
684 | } |
||
685 | |||
686 | |||
687 | function doAnchors($text) { |
||
688 | # |
||
689 | # Turn Markdown link shortcuts into XHTML <a> tags. |
||
690 | # |
||
691 | if ($this->in_anchor) return $text; |
||
692 | $this->in_anchor = true; |
||
693 | |||
694 | # |
||
695 | # First, handle reference-style links: [link text] [id] |
||
696 | # |
||
697 | $text = preg_replace_callback('{ |
||
698 | ( # wrap whole match in $1 |
||
699 | \[ |
||
700 | ('.$this->nested_brackets_re.') # link text = $2 |
||
701 | \] |
||
702 | |||
703 | [ ]? # one optional space |
||
704 | (?:\n[ ]*)? # one optional newline followed by spaces |
||
705 | |||
706 | \[ |
||
707 | (.*?) # id = $3 |
||
708 | \] |
||
709 | ) |
||
710 | }xs', |
||
711 | array(&$this, '_doAnchors_reference_callback'), $text); |
||
712 | |||
713 | # |
||
714 | # Next, inline-style links: [link text](url "optional title") |
||
715 | # |
||
716 | $text = preg_replace_callback('{ |
||
717 | ( # wrap whole match in $1 |
||
718 | \[ |
||
719 | ('.$this->nested_brackets_re.') # link text = $2 |
||
720 | \] |
||
721 | \( # literal paren |
||
722 | [ \n]* |
||
723 | (?: |
||
724 | <(.+?)> # href = $3 |
||
725 | | |
||
726 | ('.$this->nested_url_parenthesis_re.') # href = $4 |
||
727 | ) |
||
728 | [ \n]* |
||
729 | ( # $5 |
||
730 | ([\'"]) # quote char = $6 |
||
731 | (.*?) # Title = $7 |
||
732 | \6 # matching quote |
||
733 | [ \n]* # ignore any spaces/tabs between closing quote and ) |
||
734 | )? # title is optional |
||
735 | \) |
||
736 | ) |
||
737 | }xs', |
||
738 | array(&$this, '_doAnchors_inline_callback'), $text); |
||
739 | |||
740 | # |
||
741 | # Last, handle reference-style shortcuts: [link text] |
||
742 | # These must come last in case you've also got [link text][1] |
||
743 | # or [link text](/foo) |
||
744 | # |
||
745 | $text = preg_replace_callback('{ |
||
746 | ( # wrap whole match in $1 |
||
747 | \[ |
||
748 | ([^\[\]]+) # link text = $2; can\'t contain [ or ] |
||
749 | \] |
||
750 | ) |
||
751 | }xs', |
||
752 | array(&$this, '_doAnchors_reference_callback'), $text); |
||
753 | |||
754 | $this->in_anchor = false; |
||
755 | return $text; |
||
756 | } |
||
757 | function _doAnchors_reference_callback($matches) { |
||
758 | $whole_match = $matches[1]; |
||
759 | $link_text = $matches[2]; |
||
760 | $link_id =& $matches[3]; |
||
761 | |||
762 | if ($link_id == "") { |
||
763 | # for shortcut links like [this][] or [this]. |
||
764 | $link_id = $link_text; |
||
765 | } |
||
766 | |||
767 | # lower-case and turn embedded newlines into spaces |
||
768 | $link_id = strtolower($link_id); |
||
769 | $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); |
||
770 | |||
771 | if (isset($this->urls[$link_id])) { |
||
772 | $url = $this->urls[$link_id]; |
||
773 | $url = $this->encodeAttribute($url); |
||
774 | |||
775 | $result = "<a href=\"$url\""; |
||
776 | if ( isset( $this->titles[$link_id] ) ) { |
||
777 | $title = $this->titles[$link_id]; |
||
778 | $title = $this->encodeAttribute($title); |
||
779 | $result .= " title=\"$title\""; |
||
780 | } |
||
781 | |||
782 | $link_text = $this->runSpanGamut($link_text); |
||
783 | $result .= ">$link_text</a>"; |
||
784 | $result = $this->hashPart($result); |
||
785 | } |
||
786 | else { |
||
787 | $result = $whole_match; |
||
788 | } |
||
789 | return $result; |
||
790 | } |
||
791 | function _doAnchors_inline_callback($matches) { |
||
792 | $whole_match = $matches[1]; |
||
793 | $link_text = $this->runSpanGamut($matches[2]); |
||
794 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; |
||
795 | $title =& $matches[7]; |
||
796 | |||
797 | $url = $this->encodeAttribute($url); |
||
798 | |||
799 | $result = "<a href=\"$url\""; |
||
800 | if (isset($title)) { |
||
801 | $title = $this->encodeAttribute($title); |
||
802 | $result .= " title=\"$title\""; |
||
803 | } |
||
804 | |||
805 | $link_text = $this->runSpanGamut($link_text); |
||
806 | $result .= ">$link_text</a>"; |
||
807 | |||
808 | return $this->hashPart($result); |
||
809 | } |
||
810 | |||
811 | |||
812 | function doImages($text) { |
||
813 | # |
||
814 | # Turn Markdown image shortcuts into <img> tags. |
||
815 | # |
||
816 | # |
||
817 | # First, handle reference-style labeled images: ![alt text][id] |
||
818 | # |
||
819 | $text = preg_replace_callback('{ |
||
820 | ( # wrap whole match in $1 |
||
821 | !\[ |
||
822 | ('.$this->nested_brackets_re.') # alt text = $2 |
||
823 | \] |
||
824 | |||
825 | [ ]? # one optional space |
||
826 | (?:\n[ ]*)? # one optional newline followed by spaces |
||
827 | |||
828 | \[ |
||
829 | (.*?) # id = $3 |
||
830 | \] |
||
831 | |||
832 | ) |
||
833 | }xs', |
||
834 | array(&$this, '_doImages_reference_callback'), $text); |
||
835 | |||
836 | # |
||
837 | # Next, handle inline images:  |
||
838 | # Don't forget: encode * and _ |
||
839 | # |
||
840 | $text = preg_replace_callback('{ |
||
841 | ( # wrap whole match in $1 |
||
842 | !\[ |
||
843 | ('.$this->nested_brackets_re.') # alt text = $2 |
||
844 | \] |
||
845 | \s? # One optional whitespace character |
||
846 | \( # literal paren |
||
847 | [ \n]* |
||
848 | (?: |
||
849 | <(\S*)> # src url = $3 |
||
850 | | |
||
851 | ('.$this->nested_url_parenthesis_re.') # src url = $4 |
||
852 | ) |
||
853 | [ \n]* |
||
854 | ( # $5 |
||
855 | ([\'"]) # quote char = $6 |
||
856 | (.*?) # title = $7 |
||
857 | \6 # matching quote |
||
858 | [ \n]* |
||
859 | )? # title is optional |
||
860 | \) |
||
861 | ) |
||
862 | }xs', |
||
863 | array(&$this, '_doImages_inline_callback'), $text); |
||
864 | |||
865 | return $text; |
||
866 | } |
||
867 | function _doImages_reference_callback($matches) { |
||
868 | $whole_match = $matches[1]; |
||
869 | $alt_text = $matches[2]; |
||
870 | $link_id = strtolower($matches[3]); |
||
871 | |||
872 | if ($link_id == "") { |
||
873 | $link_id = strtolower($alt_text); # for shortcut links like ![this][]. |
||
874 | } |
||
875 | |||
876 | $alt_text = $this->encodeAttribute($alt_text); |
||
877 | if (isset($this->urls[$link_id])) { |
||
878 | $url = $this->encodeAttribute($this->urls[$link_id]); |
||
879 | $result = "<img src=\"$url\" alt=\"$alt_text\""; |
||
880 | if (isset($this->titles[$link_id])) { |
||
881 | $title = $this->titles[$link_id]; |
||
882 | $title = $this->encodeAttribute($title); |
||
883 | $result .= " title=\"$title\""; |
||
884 | } |
||
885 | $result .= $this->empty_element_suffix; |
||
886 | $result = $this->hashPart($result); |
||
887 | } |
||
888 | else { |
||
889 | # If there's no such link ID, leave intact: |
||
890 | $result = $whole_match; |
||
891 | } |
||
892 | |||
893 | return $result; |
||
894 | } |
||
895 | function _doImages_inline_callback($matches) { |
||
896 | $whole_match = $matches[1]; |
||
897 | $alt_text = $matches[2]; |
||
898 | $url = $matches[3] == '' ? $matches[4] : $matches[3]; |
||
899 | $title =& $matches[7]; |
||
900 | |||
901 | $alt_text = $this->encodeAttribute($alt_text); |
||
902 | $url = $this->encodeAttribute($url); |
||
903 | $result = "<img src=\"$url\" alt=\"$alt_text\""; |
||
904 | if (isset($title)) { |
||
905 | $title = $this->encodeAttribute($title); |
||
906 | $result .= " title=\"$title\""; # $title already quoted |
||
907 | } |
||
908 | $result .= $this->empty_element_suffix; |
||
909 | |||
910 | return $this->hashPart($result); |
||
911 | } |
||
912 | |||
913 | |||
914 | function doHeaders($text) { |
||
915 | # Setext-style headers: |
||
916 | # Header 1 |
||
917 | # ======== |
||
918 | # |
||
919 | # Header 2 |
||
920 | # -------- |
||
921 | # |
||
922 | $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', |
||
923 | array(&$this, '_doHeaders_callback_setext'), $text); |
||
924 | |||
925 | # atx-style headers: |
||
926 | # # Header 1 |
||
927 | # ## Header 2 |
||
928 | # ## Header 2 with closing hashes ## |
||
929 | # ... |
||
930 | # ###### Header 6 |
||
931 | # |
||
932 | $text = preg_replace_callback('{ |
||
933 | ^(\#{1,6}) # $1 = string of #\'s |
||
934 | [ ]* |
||
935 | (.+?) # $2 = Header text |
||
936 | [ ]* |
||
937 | \#* # optional closing #\'s (not counted) |
||
938 | \n+ |
||
939 | }xm', |
||
940 | array(&$this, '_doHeaders_callback_atx'), $text); |
||
941 | |||
942 | return $text; |
||
943 | } |
||
944 | function _doHeaders_callback_setext($matches) { |
||
945 | # Terrible hack to check we haven't found an empty list item. |
||
946 | if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) |
||
947 | return $matches[0]; |
||
948 | |||
949 | $level = $matches[2]{0} == '=' ? 1 : 2; |
||
950 | $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>"; |
||
951 | return "\n" . $this->hashBlock($block) . "\n\n"; |
||
952 | } |
||
953 | function _doHeaders_callback_atx($matches) { |
||
954 | $level = strlen($matches[1]); |
||
955 | $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>"; |
||
956 | return "\n" . $this->hashBlock($block) . "\n\n"; |
||
957 | } |
||
958 | |||
959 | |||
960 | function doLists($text) { |
||
961 | # |
||
962 | # Form HTML ordered (numbered) and unordered (bulleted) lists. |
||
963 | # |
||
964 | $less_than_tab = $this->tab_width - 1; |
||
965 | |||
966 | # Re-usable patterns to match list item bullets and number markers: |
||
967 | $marker_ul_re = '[*+-]'; |
||
968 | $marker_ol_re = '\d+[\.]'; |
||
969 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; |
||
970 | |||
971 | $markers_relist = array( |
||
972 | $marker_ul_re => $marker_ol_re, |
||
973 | $marker_ol_re => $marker_ul_re, |
||
974 | ); |
||
975 | |||
976 | foreach ($markers_relist as $marker_re => $other_marker_re) { |
||
977 | # Re-usable pattern to match any entirel ul or ol list: |
||
978 | $whole_list_re = ' |
||
979 | ( # $1 = whole list |
||
980 | ( # $2 |
||
981 | ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces |
||
982 | ('.$marker_re.') # $4 = first list item marker |
||
983 | [ ]+ |
||
984 | ) |
||
985 | (?s:.+?) |
||
986 | ( # $5 |
||
987 | \z |
||
988 | | |
||
989 | \n{2,} |
||
990 | (?=\S) |
||
991 | (?! # Negative lookahead for another list item marker |
||
992 | [ ]* |
||
993 | '.$marker_re.'[ ]+ |
||
994 | ) |
||
995 | | |
||
996 | (?= # Lookahead for another kind of list |
||
997 | \n |
||
998 | \3 # Must have the same indentation |
||
999 | '.$other_marker_re.'[ ]+ |
||
1000 | ) |
||
1001 | ) |
||
1002 | ) |
||
1003 | '; // mx |
||
1004 | |||
1005 | # We use a different prefix before nested lists than top-level lists. |
||
1006 | # See extended comment in _ProcessListItems(). |
||
1007 | |||
1008 | if ($this->list_level) { |
||
1009 | $text = preg_replace_callback('{ |
||
1010 | ^ |
||
1011 | '.$whole_list_re.' |
||
1012 | }mx', |
||
1013 | array(&$this, '_doLists_callback'), $text); |
||
1014 | } |
||
1015 | else { |
||
1016 | $text = preg_replace_callback('{ |
||
1017 | (?:(?<=\n)\n|\A\n?) # Must eat the newline |
||
1018 | '.$whole_list_re.' |
||
1019 | }mx', |
||
1020 | array(&$this, '_doLists_callback'), $text); |
||
1021 | } |
||
1022 | } |
||
1023 | |||
1024 | return $text; |
||
1025 | } |
||
1026 | function _doLists_callback($matches) { |
||
1027 | # Re-usable patterns to match list item bullets and number markers: |
||
1028 | $marker_ul_re = '[*+-]'; |
||
1029 | $marker_ol_re = '\d+[\.]'; |
||
1030 | $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; |
||
1031 | |||
1032 | $list = $matches[1]; |
||
1033 | $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol"; |
||
1034 | |||
1035 | $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); |
||
1036 | |||
1037 | $list .= "\n"; |
||
1038 | $result = $this->processListItems($list, $marker_any_re); |
||
1039 | |||
1040 | $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>"); |
||
1041 | return "\n". $result ."\n\n"; |
||
1042 | } |
||
1043 | |||
1044 | var $list_level = 0; |
||
1045 | |||
1046 | function processListItems($list_str, $marker_any_re) { |
||
1047 | # |
||
1048 | # Process the contents of a single ordered or unordered list, splitting it |
||
1049 | # into individual list items. |
||
1050 | # |
||
1051 | # The $this->list_level global keeps track of when we're inside a list. |
||
1052 | # Each time we enter a list, we increment it; when we leave a list, |
||
1053 | # we decrement. If it's zero, we're not in a list anymore. |
||
1054 | # |
||
1055 | # We do this because when we're not inside a list, we want to treat |
||
1056 | # something like this: |
||
1057 | # |
||
1058 | # I recommend upgrading to version |
||
1059 | # 8. Oops, now this line is treated |
||
1060 | # as a sub-list. |
||
1061 | # |
||
1062 | # As a single paragraph, despite the fact that the second line starts |
||
1063 | # with a digit-period-space sequence. |
||
1064 | # |
||
1065 | # Whereas when we're inside a list (or sub-list), that line will be |
||
1066 | # treated as the start of a sub-list. What a kludge, huh? This is |
||
1067 | # an aspect of Markdown's syntax that's hard to parse perfectly |
||
1068 | # without resorting to mind-reading. Perhaps the solution is to |
||
1069 | # change the syntax rules such that sub-lists must start with a |
||
1070 | # starting cardinal number; e.g. "1." or "a.". |
||
1071 | |||
1072 | $this->list_level++; |
||
1073 | |||
1074 | # trim trailing blank lines: |
||
1075 | $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); |
||
1076 | |||
1077 | $list_str = preg_replace_callback('{ |
||
1078 | (\n)? # leading line = $1 |
||
1079 | (^[ ]*) # leading whitespace = $2 |
||
1080 | ('.$marker_any_re.' # list marker and space = $3 |
||
1081 | (?:[ ]+|(?=\n)) # space only required if item is not empty |
||
1082 | ) |
||
1083 | ((?s:.*?)) # list item text = $4 |
||
1084 | (?:(\n+(?=\n))|\n) # tailing blank line = $5 |
||
1085 | (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) |
||
1086 | }xm', |
||
1087 | array(&$this, '_processListItems_callback'), $list_str); |
||
1088 | |||
1089 | $this->list_level--; |
||
1090 | return $list_str; |
||
1091 | } |
||
1092 | function _processListItems_callback($matches) { |
||
1093 | $item = $matches[4]; |
||
1094 | $leading_line =& $matches[1]; |
||
1095 | $leading_space =& $matches[2]; |
||
1096 | $marker_space = $matches[3]; |
||
1097 | $tailing_blank_line =& $matches[5]; |
||
1098 | |||
1099 | if ($leading_line || $tailing_blank_line || |
||
1100 | preg_match('/\n{2,}/', $item)) |
||
1101 | { |
||
1102 | # Replace marker with the appropriate whitespace indentation |
||
1103 | $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; |
||
1104 | $item = $this->runBlockGamut($this->outdent($item)."\n"); |
||
1105 | } |
||
1106 | else { |
||
1107 | # Recursion for sub-lists: |
||
1108 | $item = $this->doLists($this->outdent($item)); |
||
1109 | $item = preg_replace('/\n+$/', '', $item); |
||
1110 | $item = $this->runSpanGamut($item); |
||
1111 | } |
||
1112 | |||
1113 | return "<li>" . $item . "</li>\n"; |
||
1114 | } |
||
1115 | |||
1116 | |||
1117 | function doCodeBlocks($text) { |
||
1118 | # |
||
1119 | # Process Markdown `<pre><code>` blocks. |
||
1120 | # |
||
1121 | $text = preg_replace_callback('{ |
||
1122 | (?:\n\n|\A\n?) |
||
1123 | ( # $1 = the code block -- one or more lines, starting with a space/tab |
||
1124 | (?> |
||
1125 | [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces |
||
1126 | .*\n+ |
||
1127 | )+ |
||
1128 | ) |
||
1129 | ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc |
||
1130 | }xm', |
||
1131 | array(&$this, '_doCodeBlocks_callback'), $text); |
||
1132 | |||
1133 | return $text; |
||
1134 | } |
||
1135 | function _doCodeBlocks_callback($matches) { |
||
1136 | $codeblock = $matches[1]; |
||
1137 | |||
1138 | $codeblock = $this->outdent($codeblock); |
||
1139 | $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES); |
||
1140 | |||
1141 | # trim leading newlines and trailing newlines |
||
1142 | $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock); |
||
1143 | |||
1144 | $codeblock = "<pre><code>$codeblock\n</code></pre>"; |
||
1145 | return "\n\n".$this->hashBlock($codeblock)."\n\n"; |
||
1146 | } |
||
1147 | |||
1148 | |||
1149 | function makeCodeSpan($code) { |
||
1150 | # |
||
1151 | # Create a code span markup for $code. Called from handleSpanToken. |
||
1152 | # |
||
1153 | $code = htmlspecialchars(trim($code), ENT_NOQUOTES); |
||
1154 | return $this->hashPart("<code>$code</code>"); |
||
1155 | } |
||
1156 | |||
1157 | |||
1158 | var $em_relist = array( |
||
1159 | '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)', |
||
1160 | '*' => '(?<=\S|^)(?<!\*)\*(?!\*)', |
||
1161 | '_' => '(?<=\S|^)(?<!_)_(?!_)', |
||
1162 | ); |
||
1163 | var $strong_relist = array( |
||
1164 | '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)', |
||
1165 | '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)', |
||
1166 | '__' => '(?<=\S|^)(?<!_)__(?!_)', |
||
1167 | ); |
||
1168 | var $em_strong_relist = array( |
||
1169 | '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)', |
||
1170 | '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)', |
||
1171 | '___' => '(?<=\S|^)(?<!_)___(?!_)', |
||
1172 | ); |
||
1173 | var $em_strong_prepared_relist; |
||
1174 | |||
1175 | function prepareItalicsAndBold() { |
||
1176 | # |
||
1177 | # Prepare regular expressions for searching emphasis tokens in any |
||
1178 | # context. |
||
1179 | # |
||
1180 | foreach ($this->em_relist as $em => $em_re) { |
||
1181 | foreach ($this->strong_relist as $strong => $strong_re) { |
||
1182 | # Construct list of allowed token expressions. |
||
1183 | $token_relist = array(); |
||
1184 | if (isset($this->em_strong_relist["$em$strong"])) { |
||
1185 | $token_relist[] = $this->em_strong_relist["$em$strong"]; |
||
1186 | } |
||
1187 | $token_relist[] = $em_re; |
||
1188 | $token_relist[] = $strong_re; |
||
1189 | |||
1190 | # Construct master expression from list. |
||
1191 | $token_re = '{('. implode('|', $token_relist) .')}'; |
||
1192 | $this->em_strong_prepared_relist["$em$strong"] = $token_re; |
||
1193 | } |
||
1194 | } |
||
1195 | } |
||
1196 | |||
1197 | function doItalicsAndBold($text) { |
||
1198 | $token_stack = array(''); |
||
1199 | $text_stack = array(''); |
||
1200 | $em = ''; |
||
1201 | $strong = ''; |
||
1202 | $tree_char_em = false; |
||
1203 | |||
1204 | while (1) { |
||
1205 | # |
||
1206 | # Get prepared regular expression for seraching emphasis tokens |
||
1207 | # in current context. |
||
1208 | # |
||
1209 | $token_re = $this->em_strong_prepared_relist["$em$strong"]; |
||
1210 | |||
1211 | # |
||
1212 | # Each loop iteration search for the next emphasis token. |
||
1213 | # Each token is then passed to handleSpanToken. |
||
1214 | # |
||
1215 | $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); |
||
1216 | $text_stack[0] .= $parts[0]; |
||
1217 | $token =& $parts[1]; |
||
1218 | $text =& $parts[2]; |
||
1219 | |||
1220 | if (empty($token)) { |
||
1221 | # Reached end of text span: empty stack without emitting. |
||
1222 | # any more emphasis. |
||
1223 | while ($token_stack[0]) { |
||
1224 | $text_stack[1] .= array_shift($token_stack); |
||
1225 | $text_stack[0] .= array_shift($text_stack); |
||
1226 | } |
||
1227 | break; |
||
1228 | } |
||
1229 | |||
1230 | $token_len = strlen($token); |
||
1231 | if ($tree_char_em) { |
||
1232 | # Reached closing marker while inside a three-char emphasis. |
||
1233 | if ($token_len == 3) { |
||
1234 | # Three-char closing marker, close em and strong. |
||
1235 | array_shift($token_stack); |
||
1236 | $span = array_shift($text_stack); |
||
1237 | $span = $this->runSpanGamut($span); |
||
1238 | $span = "<strong><em>$span</em></strong>"; |
||
1239 | $text_stack[0] .= $this->hashPart($span); |
||
1240 | $em = ''; |
||
1241 | $strong = ''; |
||
1242 | } else { |
||
1243 | # Other closing marker: close one em or strong and |
||
1244 | # change current token state to match the other |
||
1245 | $token_stack[0] = str_repeat($token{0}, 3-$token_len); |
||
1246 | $tag = $token_len == 2 ? "strong" : "em"; |
||
1247 | $span = $text_stack[0]; |
||
1248 | $span = $this->runSpanGamut($span); |
||
1249 | $span = "<$tag>$span</$tag>"; |
||
1250 | $text_stack[0] = $this->hashPart($span); |
||
1251 | $$tag = ''; # $$tag stands for $em or $strong |
||
1252 | } |
||
1253 | $tree_char_em = false; |
||
1254 | } else if ($token_len == 3) { |
||
1255 | if ($em) { |
||
1256 | # Reached closing marker for both em and strong. |
||
1257 | # Closing strong marker: |
||
1258 | for ($i = 0; $i < 2; ++$i) { |
||
1259 | $shifted_token = array_shift($token_stack); |
||
1260 | $tag = strlen($shifted_token) == 2 ? "strong" : "em"; |
||
1261 | $span = array_shift($text_stack); |
||
1262 | $span = $this->runSpanGamut($span); |
||
1263 | $span = "<$tag>$span</$tag>"; |
||
1264 | $text_stack[0] .= $this->hashPart($span); |
||
1265 | $$tag = ''; # $$tag stands for $em or $strong |
||
1266 | } |
||
1267 | } else { |
||
1268 | # Reached opening three-char emphasis marker. Push on token |
||
1269 | # stack; will be handled by the special condition above. |
||
1270 | $em = $token{0}; |
||
1271 | $strong = "$em$em"; |
||
1272 | array_unshift($token_stack, $token); |
||
1273 | array_unshift($text_stack, ''); |
||
1274 | $tree_char_em = true; |
||
1275 | } |
||
1276 | } else if ($token_len == 2) { |
||
1277 | if ($strong) { |
||
1278 | # Unwind any dangling emphasis marker: |
||
1279 | if (strlen($token_stack[0]) == 1) { |
||
1280 | $text_stack[1] .= array_shift($token_stack); |
||
1281 | $text_stack[0] .= array_shift($text_stack); |
||
1282 | } |
||
1283 | # Closing strong marker: |
||
1284 | array_shift($token_stack); |
||
1285 | $span = array_shift($text_stack); |
||
1286 | $span = $this->runSpanGamut($span); |
||
1287 | $span = "<strong>$span</strong>"; |
||
1288 | $text_stack[0] .= $this->hashPart($span); |
||
1289 | $strong = ''; |
||
1290 | } else { |
||
1291 | array_unshift($token_stack, $token); |
||
1292 | array_unshift($text_stack, ''); |
||
1293 | $strong = $token; |
||
1294 | } |
||
1295 | } else { |
||
1296 | # Here $token_len == 1 |
||
1297 | if ($em) { |
||
1298 | if (strlen($token_stack[0]) == 1) { |
||
1299 | # Closing emphasis marker: |
||
1300 | array_shift($token_stack); |
||
1301 | $span = array_shift($text_stack); |
||
1302 | $span = $this->runSpanGamut($span); |
||
1303 | $span = "<em>$span</em>"; |
||
1304 | $text_stack[0] .= $this->hashPart($span); |
||
1305 | $em = ''; |
||
1306 | } else { |
||
1307 | $text_stack[0] .= $token; |
||
1308 | } |
||
1309 | } else { |
||
1310 | array_unshift($token_stack, $token); |
||
1311 | array_unshift($text_stack, ''); |
||
1312 | $em = $token; |
||
1313 | } |
||
1314 | } |
||
1315 | } |
||
1316 | return $text_stack[0]; |
||
1317 | } |
||
1318 | |||
1319 | |||
1320 | function doBlockQuotes($text) { |
||
1321 | $text = preg_replace_callback('/ |
||
1322 | ( # Wrap whole match in $1 |
||
1323 | (?> |
||
1324 | ^[ ]*>[ ]? # ">" at the start of a line |
||
1325 | .+\n # rest of the first line |
||
1326 | (.+\n)* # subsequent consecutive lines |
||
1327 | \n* # blanks |
||
1328 | )+ |
||
1329 | ) |
||
1330 | /xm', |
||
1331 | array(&$this, '_doBlockQuotes_callback'), $text); |
||
1332 | |||
1333 | return $text; |
||
1334 | } |
||
1335 | function _doBlockQuotes_callback($matches) { |
||
1336 | $bq = $matches[1]; |
||
1337 | # trim one level of quoting - trim whitespace-only lines |
||
1338 | $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); |
||
1339 | $bq = $this->runBlockGamut($bq); # recurse |
||
1340 | |||
1341 | $bq = preg_replace('/^/m', " ", $bq); |
||
1342 | # These leading spaces cause problem with <pre> content, |
||
1343 | # so we need to fix that: |
||
1344 | $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx', |
||
1345 | array(&$this, '_doBlockQuotes_callback2'), $bq); |
||
1346 | |||
1347 | return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n"; |
||
1348 | } |
||
1349 | function _doBlockQuotes_callback2($matches) { |
||
1350 | $pre = $matches[1]; |
||
1351 | $pre = preg_replace('/^ /m', '', $pre); |
||
1352 | return $pre; |
||
1353 | } |
||
1354 | |||
1355 | |||
1356 | function formParagraphs($text) { |
||
1357 | # |
||
1358 | # Params: |
||
1359 | # $text - string to process with html <p> tags |
||
1360 | # |
||
1361 | # Strip leading and trailing lines: |
||
1362 | $text = preg_replace('/\A\n+|\n+\z/', '', $text); |
||
1363 | |||
1364 | $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); |
||
1365 | |||
1366 | # |
||
1367 | # Wrap <p> tags and unhashify HTML blocks |
||
1368 | # |
||
1369 | foreach ($grafs as $key => $value) { |
||
1370 | if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { |
||
1371 | # Is a paragraph. |
||
1372 | $value = $this->runSpanGamut($value); |
||
1373 | $value = preg_replace('/^([ ]*)/', "<p>", $value); |
||
1374 | $value .= "</p>"; |
||
1375 | $grafs[$key] = $this->unhash($value); |
||
1376 | } |
||
1377 | else { |
||
1378 | # Is a block. |
||
1379 | # Modify elements of @grafs in-place... |
||
1380 | $graf = $value; |
||
1381 | $block = $this->html_hashes[$graf]; |
||
1382 | $graf = $block; |
||
1383 | // if (preg_match('{ |
||
1384 | // \A |
||
1385 | // ( # $1 = <div> tag |
||
1386 | // <div \s+ |
||
1387 | // [^>]* |
||
1388 | // \b |
||
1389 | // markdown\s*=\s* ([\'"]) # $2 = attr quote char |
||
1390 | // 1 |
||
1391 | // \2 |
||
1392 | // [^>]* |
||
1393 | // > |
||
1394 | // ) |
||
1395 | // ( # $3 = contents |
||
1396 | // .* |
||
1397 | // ) |
||
1398 | // (</div>) # $4 = closing tag |
||
1399 | // \z |
||
1400 | // }xs', $block, $matches)) |
||
1401 | // { |
||
1402 | // list(, $div_open, , $div_content, $div_close) = $matches; |
||
1403 | // |
||
1404 | // # We can't call Markdown(), because that resets the hash; |
||
1405 | // # that initialization code should be pulled into its own sub, though. |
||
1406 | // $div_content = $this->hashHTMLBlocks($div_content); |
||
1407 | // |
||
1408 | // # Run document gamut methods on the content. |
||
1409 | // foreach ($this->document_gamut as $method => $priority) { |
||
1410 | // $div_content = $this->$method($div_content); |
||
1411 | // } |
||
1412 | // |
||
1413 | // $div_open = preg_replace( |
||
1414 | // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); |
||
1415 | // |
||
1416 | // $graf = $div_open . "\n" . $div_content . "\n" . $div_close; |
||
1417 | // } |
||
1418 | $grafs[$key] = $graf; |
||
1419 | } |
||
1420 | } |
||
1421 | |||
1422 | return implode("\n\n", $grafs); |
||
1423 | } |
||
1424 | |||
1425 | |||
1426 | function encodeAttribute($text) { |
||
1427 | # |
||
1428 | # Encode text for a double-quoted HTML attribute. This function |
||
1429 | # is *not* suitable for attributes enclosed in single quotes. |
||
1430 | # |
||
1431 | $text = $this->encodeAmpsAndAngles($text); |
||
1432 | $text = str_replace('"', '"', $text); |
||
1433 | return $text; |
||
1434 | } |
||
1435 | |||
1436 | |||
1437 | function encodeAmpsAndAngles($text) { |
||
1438 | # |
||
1439 | # Smart processing for ampersands and angle brackets that need to |
||
1440 | # be encoded. Valid character entities are left alone unless the |
||
1441 | # no-entities mode is set. |
||
1442 | # |
||
1443 | if ($this->no_entities) { |
||
1444 | $text = str_replace('&', '&', $text); |
||
1445 | } else { |
||
1446 | # Ampersand-encoding based entirely on Nat Irons's Amputator |
||
1447 | # MT plugin: <http://bumppo.net/projects/amputator/> |
||
1448 | $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', |
||
1449 | '&', $text);; |
||
1450 | } |
||
1451 | # Encode remaining <'s |
||
1452 | $text = str_replace('<', '<', $text); |
||
1453 | |||
1454 | return $text; |
||
1455 | } |
||
1456 | |||
1457 | |||
1458 | function doAutoLinks($text) { |
||
1459 | $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i', |
||
1460 | array(&$this, '_doAutoLinks_url_callback'), $text); |
||
1461 | |||
1462 | # Email addresses: <[email protected]> |
||
1463 | $text = preg_replace_callback('{ |
||
1464 | < |
||
1465 | (?:mailto:)? |
||
1466 | ( |
||
1467 | (?: |
||
1468 | [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+ |
||
1469 | | |
||
1470 | ".*?" |
||
1471 | ) |
||
1472 | \@ |
||
1473 | (?: |
||
1474 | [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ |
||
1475 | | |
||
1476 | \[[\d.a-fA-F:]+\] # IPv4 & IPv6 |
||
1477 | ) |
||
1478 | ) |
||
1479 | > |
||
1480 | }xi', |
||
1481 | array(&$this, '_doAutoLinks_email_callback'), $text); |
||
1482 | $text = preg_replace_callback('{<(tel:([^\'">\s]+))>}i',array(&$this, '_doAutoLinks_tel_callback'), $text); |
||
1483 | |||
1484 | return $text; |
||
1485 | } |
||
1486 | function _doAutoLinks_tel_callback($matches) { |
||
1487 | $url = $this->encodeAttribute($matches[1]); |
||
1488 | $tel = $this->encodeAttribute($matches[2]); |
||
1489 | $link = "<a href=\"$url\">$tel</a>"; |
||
1490 | return $this->hashPart($link); |
||
1491 | } |
||
1492 | function _doAutoLinks_url_callback($matches) { |
||
1493 | $url = $this->encodeAttribute($matches[1]); |
||
1494 | $link = "<a href=\"$url\">$url</a>"; |
||
1495 | return $this->hashPart($link); |
||
1496 | } |
||
1497 | function _doAutoLinks_email_callback($matches) { |
||
1498 | $address = $matches[1]; |
||
1499 | $link = $this->encodeEmailAddress($address); |
||
1500 | return $this->hashPart($link); |
||
1501 | } |
||
1502 | |||
1503 | |||
1504 | function encodeEmailAddress($addr) { |
||
1505 | # |
||
1506 | # Input: an email address, e.g. "[email protected]" |
||
1507 | # |
||
1508 | # Output: the email address as a mailto link, with each character |
||
1509 | # of the address encoded as either a decimal or hex entity, in |
||
1510 | # the hopes of foiling most address harvesting spam bots. E.g.: |
||
1511 | # |
||
1512 | # <p><a href="mailto:foo |
||
1513 | # @example.co |
||
1514 | # m">foo@exampl |
||
1515 | # e.com</a></p> |
||
1516 | # |
||
1517 | # Based by a filter by Matthew Wickline, posted to BBEdit-Talk. |
||
1518 | # With some optimizations by Milian Wolff. |
||
1519 | # |
||
1520 | $addr = "mailto:" . $addr; |
||
1521 | $chars = preg_split('/(?<!^)(?!$)/', $addr); |
||
1522 | $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed. |
||
1523 | |||
1524 | foreach ($chars as $key => $char) { |
||
1525 | $ord = ord($char); |
||
1526 | # Ignore non-ascii chars. |
||
1527 | if ($ord < 128) { |
||
1528 | $r = ($seed * (1 + $key)) % 100; # Pseudo-random function. |
||
1529 | # roughly 10% raw, 45% hex, 45% dec |
||
1530 | # '@' *must* be encoded. I insist. |
||
1531 | if ($r > 90 && $char != '@') /* do nothing */; |
||
1532 | else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';'; |
||
1533 | else $chars[$key] = '&#'.$ord.';'; |
||
1534 | } |
||
1535 | } |
||
1536 | |||
1537 | $addr = implode('', $chars); |
||
1538 | $text = implode('', array_slice($chars, 7)); # text without `mailto:` |
||
1539 | $addr = "<a href=\"$addr\">$text</a>"; |
||
1540 | |||
1541 | return $addr; |
||
1542 | } |
||
1543 | |||
1544 | |||
1545 | function parseSpan($str) { |
||
1546 | # |
||
1547 | # Take the string $str and parse it into tokens, hashing embeded HTML, |
||
1548 | # escaped characters and handling code spans. |
||
1549 | # |
||
1550 | $output = ''; |
||
1551 | |||
1552 | $span_re = '{ |
||
1553 | ( |
||
1554 | \\\\'.$this->escape_chars_re.' |
||
1555 | | |
||
1556 | (?<![`\\\\]) |
||
1557 | `+ # code span marker |
||
1558 | '.( $this->no_markup ? '' : ' |
||
1559 | | |
||
1560 | <!-- .*? --> # comment |
||
1561 | | |
||
1562 | <\?.*?\?> | <%.*?%> # processing instruction |
||
1563 | | |
||
1564 | <[!$]?[-a-zA-Z0-9:_]+ # regular tags |
||
1565 | (?> |
||
1566 | \s |
||
1567 | (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* |
||
1568 | )? |
||
1569 | > |
||
1570 | | |
||
1571 | <[-a-zA-Z0-9:_]+\s*/> # xml-style empty tag |
||
1572 | | |
||
1573 | </[-a-zA-Z0-9:_]+\s*> # closing tag |
||
1574 | ').' |
||
1575 | ) |
||
1576 | }xs'; |
||
1577 | |||
1578 | while (1) { |
||
1579 | # |
||
1580 | # Each loop iteration seach for either the next tag, the next |
||
1581 | # openning code span marker, or the next escaped character. |
||
1582 | # Each token is then passed to handleSpanToken. |
||
1583 | # |
||
1584 | $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); |
||
1585 | |||
1586 | # Create token from text preceding tag. |
||
1587 | if ($parts[0] != "") { |
||
1588 | $output .= $parts[0]; |
||
1589 | } |
||
1590 | |||
1591 | # Check if we reach the end. |
||
1592 | if (isset($parts[1])) { |
||
1593 | $output .= $this->handleSpanToken($parts[1], $parts[2]); |
||
1594 | $str = $parts[2]; |
||
1595 | } |
||
1596 | else { |
||
1597 | break; |
||
1598 | } |
||
1599 | } |
||
1600 | |||
1601 | return $output; |
||
1602 | } |
||
1603 | |||
1604 | |||
1605 | function handleSpanToken($token, &$str) { |
||
1606 | # |
||
1607 | # Handle $token provided by parseSpan by determining its nature and |
||
1608 | # returning the corresponding value that should replace it. |
||
1609 | # |
||
1610 | switch ($token{0}) { |
||
1611 | case "\\": |
||
1612 | return $this->hashPart("&#". ord($token{1}). ";"); |
||
1613 | case "`": |
||
1614 | # Search for end marker in remaining text. |
||
1615 | if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', |
||
1616 | $str, $matches)) |
||
1617 | { |
||
1618 | $str = $matches[2]; |
||
1619 | $codespan = $this->makeCodeSpan($matches[1]); |
||
1620 | return $this->hashPart($codespan); |
||
1621 | } |
||
1622 | return $token; // return as text since no ending marker found. |
||
1623 | default: |
||
1624 | return $this->hashPart($token); |
||
1625 | } |
||
1626 | } |
||
1627 | |||
1628 | |||
1629 | function outdent($text) { |
||
1630 | # |
||
1631 | # Remove one level of line-leading tabs or spaces |
||
1632 | # |
||
1633 | return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text); |
||
1634 | } |
||
1635 | |||
1636 | |||
1637 | # String length function for detab. `_initDetab` will create a function to |
||
1638 | # hanlde UTF-8 if the default function does not exist. |
||
1639 | var $utf8_strlen = 'mb_strlen'; |
||
1640 | |||
1641 | function detab($text) { |
||
1642 | # |
||
1643 | # Replace tabs with the appropriate amount of space. |
||
1644 | # |
||
1645 | # For each line we separate the line in blocks delemited by |
||
1646 | # tab characters. Then we reconstruct every line by adding the |
||
1647 | # appropriate number of space between each blocks. |
||
1648 | |||
1649 | $text = preg_replace_callback('/^.*\t.*$/m', |
||
1650 | array(&$this, '_detab_callback'), $text); |
||
1651 | |||
1652 | return $text; |
||
1653 | } |
||
1654 | function _detab_callback($matches) { |
||
1655 | $line = $matches[0]; |
||
1656 | $strlen = $this->utf8_strlen; # strlen function for UTF-8. |
||
1657 | |||
1658 | # Split in blocks. |
||
1659 | $blocks = explode("\t", $line); |
||
1660 | # Add each blocks to the line. |
||
1661 | $line = $blocks[0]; |
||
1662 | unset($blocks[0]); # Do not add first block twice. |
||
1663 | foreach ($blocks as $block) { |
||
1664 | # Calculate amount of space, insert spaces, insert block. |
||
1665 | $amount = $this->tab_width - |
||
1666 | $strlen($line, 'UTF-8') % $this->tab_width; |
||
1667 | $line .= str_repeat(" ", $amount) . $block; |
||
1668 | } |
||
1669 | return $line; |
||
1670 | } |
||
1671 | function _initDetab() { |
||
1672 | # |
||
1673 | # Check for the availability of the function in the `utf8_strlen` property |
||
1674 | # (initially `mb_strlen`). If the function is not available, create a |
||
1675 | # function that will loosely count the number of UTF-8 characters with a |
||
1676 | # regular expression. |
||
1677 | # |
||
1678 | if (function_exists($this->utf8_strlen)) return; |
||
1679 | $this->utf8_strlen = create_function('$text', 'return preg_match_all( |
||
1680 | "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", |
||
1681 | $text, $m);'); |
||
1682 | } |
||
1683 | |||
1684 | |||
1685 | function unhash($text) { |
||
1686 | # |
||
1687 | # Swap back in all the tags hashed by _HashHTMLBlocks. |
||
1688 | # |
||
1689 | return preg_replace_callback('/(.)\x1A[0-9]+\1/', |
||
1690 | array(&$this, '_unhash_callback'), $text); |
||
1691 | } |
||
1692 | function _unhash_callback($matches) { |
||
1693 | return $this->html_hashes[$matches[0]]; |
||
1694 | } |
||
1695 | |||
1696 | } |
||
1697 | |||
3348 |