PageRenderTime 50ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/kirby/parsers/smartypants.php

https://github.com/jordanstephens/kirbycms
PHP | 1194 lines | 796 code | 105 blank | 293 comment | 94 complexity | 0ffc6130dfa4a4f320190e1897d55a7d MD5 | raw file
  1. <?php
  2. // direct access protection
  3. if(!defined('KIRBY')) die('Direct access is not allowed');
  4. #
  5. # SmartyPants Typographer - Smart typography for web sites
  6. #
  7. # PHP SmartyPants & Typographer
  8. # Copyright (c) 2004-2013 Michel Fortin
  9. # <http://michelf.ca/>
  10. #
  11. # Original SmartyPants
  12. # Copyright (c) 2003-2004 John Gruber
  13. # <http://daringfireball.net/>
  14. #
  15. define( 'SMARTYPANTS_VERSION', "1.5.1f" ); # Sun 23 Jan 2013
  16. define( 'SMARTYPANTSTYPOGRAPHER_VERSION', "1.0.1" ); # Sun 23 Jan 2013
  17. #
  18. # Default configuration:
  19. #
  20. # 1 -> "--" for em-dashes; no en-dash support
  21. # 2 -> "---" for em-dashes; "--" for en-dashes
  22. # 3 -> "--" for em-dashes; "---" for en-dashes
  23. # See docs for more configuration options.
  24. #
  25. define( 'SMARTYPANTS_ATTR', 1 );
  26. # Openning and closing smart double-quotes.
  27. define( 'SMARTYPANTS_SMART_DOUBLEQUOTE_OPEN', c::get('smartypants.doublequote.open', '&#8220;') );
  28. define( 'SMARTYPANTS_SMART_DOUBLEQUOTE_CLOSE', c::get('smartypants.doublequote.close', '&#8221;') );
  29. # Space around em-dashes. "He_—_or she_—_should change that."
  30. define( 'SMARTYPANTS_SPACE_EMDASH', c::get('smartypants.space.emdash', ' ') );
  31. # Space around en-dashes. "He_–_or she_–_should change that."
  32. define( 'SMARTYPANTS_SPACE_ENDASH', c::get('smartypants.space.endash', ' ') );
  33. # Space before a colon. "He said_: here it is."
  34. define( 'SMARTYPANTS_SPACE_COLON', c::get('smartypants.space.colon', '&#160;') );
  35. # Space before a semicolon. "That's what I said_; that's what he said."
  36. define( 'SMARTYPANTS_SPACE_SEMICOLON', c::get('smartypants.space.semicolon', '&#160;') );
  37. # Space before a question mark and an exclamation mark: "¡_Holà_! What_?"
  38. define( 'SMARTYPANTS_SPACE_MARKS', c::get('smartypants.space.marks', '&#160;') );
  39. # Space inside french quotes. "Voici la «_chose_» qui m'a attaqué."
  40. define( 'SMARTYPANTS_SPACE_FRENCHQUOTE', c::get('smartypants.space.frenchquote', '&#160;') );
  41. # Space as thousand separator. "On compte 10_000 maisons sur cette liste."
  42. define( 'SMARTYPANTS_SPACE_THOUSAND', c::get('smartypants.space.thousand', '&#160;') );
  43. # Space before a unit abreviation. "This 12_kg of matter costs 10_$."
  44. define( 'SMARTYPANTS_SPACE_UNIT', c::get('smartypants.space.unit', '&#160;') );
  45. # SmartyPants will not alter the content of these tags:
  46. define( 'SMARTYPANTS_TAGS_TO_SKIP', c::get('smartypants.skip', 'pre|code|kbd|script|math') );
  47. ### Standard Function Interface ###
  48. define( 'SMARTYPANTS_PARSER_CLASS', 'SmartyPantsTypographer_Parser' );
  49. function SmartyPants($text, $attr = SMARTYPANTS_ATTR) {
  50. // global kirby switch for smartypants
  51. if(c::get('smartypants') === false) return $text;
  52. #
  53. # Initialize the parser and return the result of its transform method.
  54. #
  55. # Setup static parser array.
  56. static $parser = array();
  57. if (!isset($parser[$attr])) {
  58. $parser_class = SMARTYPANTS_PARSER_CLASS;
  59. $parser[$attr] = new $parser_class($attr);
  60. }
  61. # Transform text using parser.
  62. return $parser[$attr]->transform($text);
  63. }
  64. function SmartQuotes($text, $attr = 1) {
  65. switch ($attr) {
  66. case 0: return $text;
  67. case 2: $attr = 'qb'; break;
  68. default: $attr = 'q'; break;
  69. }
  70. return SmartyPants($text, $attr);
  71. }
  72. function SmartDashes($text, $attr = 1) {
  73. switch ($attr) {
  74. case 0: return $text;
  75. case 2: $attr = 'D'; break;
  76. case 3: $attr = 'i'; break;
  77. default: $attr = 'd'; break;
  78. }
  79. return SmartyPants($text, $attr);
  80. }
  81. function SmartEllipsis($text, $attr = 1) {
  82. switch ($attr) {
  83. case 0: return $text;
  84. default: $attr = 'e'; break;
  85. }
  86. return SmartyPants($text, $attr);
  87. }
  88. ### WordPress Plugin Interface ###
  89. /*
  90. Plugin Name: SmartyPants Typographer
  91. Plugin URI: http://michelf.ca/projects/php-smartypants/
  92. Description: SmartyPants is a web publishing utility that translates plain ASCII punctuation characters into &#8220;smart&#8221; typographic punctuation HTML entities. The Typographer extension will also replace normal spaces with unbrekable ones where appropriate to silently remove unwanted line breaks around punctuation and at some other places. This plugin <strong>replace the default WordPress Texturize algorithm</strong> for the content and the title of your posts, the comments body and author name, and everywhere else Texturize normally apply.
  93. Version: 1.0.1
  94. Author: Michel Fortin
  95. Author URI: http://michelf.ca/
  96. */
  97. if (isset($wp_version)) {
  98. # Remove default Texturize filter that would conflict with SmartyPants.
  99. remove_filter('category_description', 'wptexturize');
  100. remove_filter('list_cats', 'wptexturize');
  101. remove_filter('comment_author', 'wptexturize');
  102. remove_filter('comment_text', 'wptexturize');
  103. remove_filter('single_post_title', 'wptexturize');
  104. remove_filter('the_title', 'wptexturize');
  105. remove_filter('the_content', 'wptexturize');
  106. remove_filter('the_excerpt', 'wptexturize');
  107. remove_filter('the_tags', 'wptexturize');
  108. # Add SmartyPants filter.
  109. add_filter('category_description', 'SmartyPants', 11);
  110. add_filter('list_cats', 'SmartyPants', 11);
  111. add_filter('comment_author', 'SmartyPants', 11);
  112. add_filter('comment_text', 'SmartyPants', 11);
  113. add_filter('single_post_title', 'SmartyPants', 11);
  114. add_filter('the_title', 'SmartyPants', 11);
  115. add_filter('the_content', 'SmartyPants', 11);
  116. add_filter('the_excerpt', 'SmartyPants', 11);
  117. add_filter('the_tags', 'SmartyPants', 11);
  118. }
  119. ### Smarty Modifier Interface ###
  120. function smarty_modifier_smartypants($text, $attr = NULL) {
  121. return SmartyPants($text, $attr);
  122. }
  123. #
  124. # SmartyPants Parser Class
  125. #
  126. class SmartyPants_Parser {
  127. # Options to specify which transformations to make:
  128. var $do_nothing = 0;
  129. var $do_quotes = 0;
  130. var $do_backticks = 0;
  131. var $do_dashes = 0;
  132. var $do_ellipses = 0;
  133. var $do_stupefy = 0;
  134. var $convert_quot = 0; # should we translate &quot; entities into normal quotes?
  135. function SmartyPants_Parser($attr = SMARTYPANTS_ATTR) {
  136. #
  137. # Initialize a SmartyPants_Parser with certain attributes.
  138. #
  139. # Parser attributes:
  140. # 0 : do nothing
  141. # 1 : set all
  142. # 2 : set all, using old school en- and em- dash shortcuts
  143. # 3 : set all, using inverted old school en and em- dash shortcuts
  144. #
  145. # q : quotes
  146. # b : backtick quotes (``double'' only)
  147. # B : backtick quotes (``double'' and `single')
  148. # d : dashes
  149. # D : old school dashes
  150. # i : inverted old school dashes
  151. # e : ellipses
  152. # w : convert &quot; entities to " for Dreamweaver users
  153. #
  154. if ($attr == "0") {
  155. $this->do_nothing = 1;
  156. }
  157. else if ($attr == "1") {
  158. # Do everything, turn all options on.
  159. $this->do_quotes = 1;
  160. $this->do_backticks = 1;
  161. $this->do_dashes = 1;
  162. $this->do_ellipses = 1;
  163. }
  164. else if ($attr == "2") {
  165. # Do everything, turn all options on, use old school dash shorthand.
  166. $this->do_quotes = 1;
  167. $this->do_backticks = 1;
  168. $this->do_dashes = 2;
  169. $this->do_ellipses = 1;
  170. }
  171. else if ($attr == "3") {
  172. # Do everything, turn all options on, use inverted old school dash shorthand.
  173. $this->do_quotes = 1;
  174. $this->do_backticks = 1;
  175. $this->do_dashes = 3;
  176. $this->do_ellipses = 1;
  177. }
  178. else if ($attr == "-1") {
  179. # Special "stupefy" mode.
  180. $this->do_stupefy = 1;
  181. }
  182. else {
  183. $chars = preg_split('//', $attr);
  184. foreach ($chars as $c){
  185. if ($c == "q") { $this->do_quotes = 1; }
  186. else if ($c == "b") { $this->do_backticks = 1; }
  187. else if ($c == "B") { $this->do_backticks = 2; }
  188. else if ($c == "d") { $this->do_dashes = 1; }
  189. else if ($c == "D") { $this->do_dashes = 2; }
  190. else if ($c == "i") { $this->do_dashes = 3; }
  191. else if ($c == "e") { $this->do_ellipses = 1; }
  192. else if ($c == "w") { $this->convert_quot = 1; }
  193. else {
  194. # Unknown attribute option, ignore.
  195. }
  196. }
  197. }
  198. }
  199. function transform($text) {
  200. if ($this->do_nothing) {
  201. return $text;
  202. }
  203. $tokens = $this->tokenizeHTML($text);
  204. $result = '';
  205. $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
  206. $prev_token_last_char = ""; # This is a cheat, used to get some context
  207. # for one-character tokens that consist of
  208. # just a quote char. What we do is remember
  209. # the last character of the previous text
  210. # token, to use as context to curl single-
  211. # character quote tokens correctly.
  212. foreach ($tokens as $cur_token) {
  213. if ($cur_token[0] == "tag") {
  214. # Don't mess with quotes inside tags.
  215. $result .= $cur_token[1];
  216. if (preg_match('@<(/?)(?:'.SMARTYPANTS_TAGS_TO_SKIP.')[\s>]@', $cur_token[1], $matches)) {
  217. $in_pre = isset($matches[1]) && $matches[1] == '/' ? 0 : 1;
  218. }
  219. } else {
  220. $t = $cur_token[1];
  221. $last_char = substr($t, -1); # Remember last char of this token before processing.
  222. if (! $in_pre) {
  223. $t = $this->educate($t, $prev_token_last_char);
  224. }
  225. $prev_token_last_char = $last_char;
  226. $result .= $t;
  227. }
  228. }
  229. return $result;
  230. }
  231. function educate($t, $prev_token_last_char) {
  232. $t = $this->processEscapes($t);
  233. if ($this->convert_quot) {
  234. $t = preg_replace('/&quot;/', '"', $t);
  235. }
  236. if ($this->do_dashes) {
  237. if ($this->do_dashes == 1) $t = $this->educateDashes($t);
  238. if ($this->do_dashes == 2) $t = $this->educateDashesOldSchool($t);
  239. if ($this->do_dashes == 3) $t = $this->educateDashesOldSchoolInverted($t);
  240. }
  241. if ($this->do_ellipses) $t = $this->educateEllipses($t);
  242. # Note: backticks need to be processed before quotes.
  243. if ($this->do_backticks) {
  244. $t = $this->educateBackticks($t);
  245. if ($this->do_backticks == 2) $t = $this->educateSingleBackticks($t);
  246. }
  247. if ($this->do_quotes) {
  248. if ($t == "'") {
  249. # Special case: single-character ' token
  250. if (preg_match('/\S/', $prev_token_last_char)) {
  251. $t = "&#8217;";
  252. }
  253. else {
  254. $t = "&#8216;";
  255. }
  256. }
  257. else if ($t == '"') {
  258. # Special case: single-character " token
  259. if (preg_match('/\S/', $prev_token_last_char)) {
  260. $t = "&#8221;";
  261. }
  262. else {
  263. $t = "&#8220;";
  264. }
  265. }
  266. else {
  267. # Normal case:
  268. $t = $this->educateQuotes($t);
  269. }
  270. }
  271. if ($this->do_stupefy) $t = $this->stupefyEntities($t);
  272. return $t;
  273. }
  274. function educateQuotes($_) {
  275. #
  276. # Parameter: String.
  277. #
  278. # Returns: The string, with "educated" curly quote HTML entities.
  279. #
  280. # Example input: "Isn't this fun?"
  281. # Example output: &#8220;Isn&#8217;t this fun?&#8221;
  282. #
  283. # Make our own "punctuation" character class, because the POSIX-style
  284. # [:PUNCT:] is only available in Perl 5.6 or later:
  285. $punct_class = "[!\"#\\$\\%'()*+,-.\\/:;<=>?\\@\\[\\\\\]\\^_`{|}~]";
  286. # Special case if the very first character is a quote
  287. # followed by punctuation at a non-word-break. Close the quotes by brute force:
  288. $_ = preg_replace(
  289. array("/^'(?=$punct_class\\B)/", "/^\"(?=$punct_class\\B)/"),
  290. array('&#8217;', '&#8221;'), $_);
  291. # Special case for double sets of quotes, e.g.:
  292. # <p>He said, "'Quoted' words in a larger quote."</p>
  293. $_ = preg_replace(
  294. array("/\"'(?=\w)/", "/'\"(?=\w)/"),
  295. array('&#8220;&#8216;', '&#8216;&#8220;'), $_);
  296. # Special case for decade abbreviations (the '80s):
  297. $_ = preg_replace("/'(?=\\d{2}s)/", '&#8217;', $_);
  298. $close_class = '[^\ \t\r\n\[\{\(\-]';
  299. $dec_dashes = '&\#8211;|&\#8212;';
  300. # Get most opening single quotes:
  301. $_ = preg_replace("{
  302. (
  303. \\s | # a whitespace char, or
  304. &nbsp; | # a non-breaking space entity, or
  305. -- | # dashes, or
  306. &[mn]dash; | # named dash entities
  307. $dec_dashes | # or decimal entities
  308. &\\#x201[34]; # or hex
  309. )
  310. ' # the quote
  311. (?=\\w) # followed by a word character
  312. }x", '\1&#8216;', $_);
  313. # Single closing quotes:
  314. $_ = preg_replace("{
  315. ($close_class)?
  316. '
  317. (?(1)| # If $1 captured, then do nothing;
  318. (?=\\s | s\\b) # otherwise, positive lookahead for a whitespace
  319. ) # char or an 's' at a word ending position. This
  320. # is a special case to handle something like:
  321. # \"<i>Custer</i>'s Last Stand.\"
  322. }xi", '\1&#8217;', $_);
  323. # Any remaining single quotes should be opening ones:
  324. $_ = str_replace("'", '&#8216;', $_);
  325. # Get most opening double quotes:
  326. $_ = preg_replace("{
  327. (
  328. \\s | # a whitespace char, or
  329. &nbsp; | # a non-breaking space entity, or
  330. -- | # dashes, or
  331. &[mn]dash; | # named dash entities
  332. $dec_dashes | # or decimal entities
  333. &\\#x201[34]; # or hex
  334. )
  335. \" # the quote
  336. (?=\\w) # followed by a word character
  337. }x", '\1&#8220;', $_);
  338. # Double closing quotes:
  339. $_ = preg_replace("{
  340. ($close_class)?
  341. \"
  342. (?(1)|(?=\\s)) # If $1 captured, then do nothing;
  343. # if not, then make sure the next char is whitespace.
  344. }x", '\1&#8221;', $_);
  345. # Any remaining quotes should be opening ones.
  346. $_ = str_replace('"', '&#8220;', $_);
  347. return $_;
  348. }
  349. function educateBackticks($_) {
  350. #
  351. # Parameter: String.
  352. # Returns: The string, with ``backticks'' -style double quotes
  353. # translated into HTML curly quote entities.
  354. #
  355. # Example input: ``Isn't this fun?''
  356. # Example output: &#8220;Isn't this fun?&#8221;
  357. #
  358. $_ = str_replace(array("``", "''",),
  359. array('&#8220;', '&#8221;'), $_);
  360. return $_;
  361. }
  362. function educateSingleBackticks($_) {
  363. #
  364. # Parameter: String.
  365. # Returns: The string, with `backticks' -style single quotes
  366. # translated into HTML curly quote entities.
  367. #
  368. # Example input: `Isn't this fun?'
  369. # Example output: &#8216;Isn&#8217;t this fun?&#8217;
  370. #
  371. $_ = str_replace(array("`", "'",),
  372. array('&#8216;', '&#8217;'), $_);
  373. return $_;
  374. }
  375. function educateDashes($_) {
  376. #
  377. # Parameter: String.
  378. #
  379. # Returns: The string, with each instance of "--" translated to
  380. # an em-dash HTML entity.
  381. #
  382. $_ = str_replace('--', '&#8212;', $_);
  383. return $_;
  384. }
  385. function educateDashesOldSchool($_) {
  386. #
  387. # Parameter: String.
  388. #
  389. # Returns: The string, with each instance of "--" translated to
  390. # an en-dash HTML entity, and each "---" translated to
  391. # an em-dash HTML entity.
  392. #
  393. # em en
  394. $_ = str_replace(array("---", "--",),
  395. array('&#8212;', '&#8211;'), $_);
  396. return $_;
  397. }
  398. function educateDashesOldSchoolInverted($_) {
  399. #
  400. # Parameter: String.
  401. #
  402. # Returns: The string, with each instance of "--" translated to
  403. # an em-dash HTML entity, and each "---" translated to
  404. # an en-dash HTML entity. Two reasons why: First, unlike the
  405. # en- and em-dash syntax supported by
  406. # EducateDashesOldSchool(), it's compatible with existing
  407. # entries written before SmartyPants 1.1, back when "--" was
  408. # only used for em-dashes. Second, em-dashes are more
  409. # common than en-dashes, and so it sort of makes sense that
  410. # the shortcut should be shorter to type. (Thanks to Aaron
  411. # Swartz for the idea.)
  412. #
  413. # en em
  414. $_ = str_replace(array("---", "--",),
  415. array('&#8211;', '&#8212;'), $_);
  416. return $_;
  417. }
  418. function educateEllipses($_) {
  419. #
  420. # Parameter: String.
  421. # Returns: The string, with each instance of "..." translated to
  422. # an ellipsis HTML entity. Also converts the case where
  423. # there are spaces between the dots.
  424. #
  425. # Example input: Huh...?
  426. # Example output: Huh&#8230;?
  427. #
  428. $_ = str_replace(array("...", ". . .",), '&#8230;', $_);
  429. return $_;
  430. }
  431. function stupefyEntities($_) {
  432. #
  433. # Parameter: String.
  434. # Returns: The string, with each SmartyPants HTML entity translated to
  435. # its ASCII counterpart.
  436. #
  437. # Example input: &#8220;Hello &#8212; world.&#8221;
  438. # Example output: "Hello -- world."
  439. #
  440. # en-dash em-dash
  441. $_ = str_replace(array('&#8211;', '&#8212;'),
  442. array('-', '--'), $_);
  443. # single quote open close
  444. $_ = str_replace(array('&#8216;', '&#8217;'), "'", $_);
  445. # double quote open close
  446. $_ = str_replace(array('&#8220;', '&#8221;'), '"', $_);
  447. $_ = str_replace('&#8230;', '...', $_); # ellipsis
  448. return $_;
  449. }
  450. function processEscapes($_) {
  451. #
  452. # Parameter: String.
  453. # Returns: The string, with after processing the following backslash
  454. # escape sequences. This is useful if you want to force a "dumb"
  455. # quote or other character to appear.
  456. #
  457. # Escape Value
  458. # ------ -----
  459. # \\ &#92;
  460. # \" &#34;
  461. # \' &#39;
  462. # \. &#46;
  463. # \- &#45;
  464. # \` &#96;
  465. #
  466. $_ = str_replace(
  467. array('\\\\', '\"', "\'", '\.', '\-', '\`'),
  468. array('&#92;', '&#34;', '&#39;', '&#46;', '&#45;', '&#96;'), $_);
  469. return $_;
  470. }
  471. function tokenizeHTML($str) {
  472. #
  473. # Parameter: String containing HTML markup.
  474. # Returns: An array of the tokens comprising the input
  475. # string. Each token is either a tag (possibly with nested,
  476. # tags contained therein, such as <a href="<MTFoo>">, or a
  477. # run of text between tags. Each element of the array is a
  478. # two-element array; the first is either 'tag' or 'text';
  479. # the second is the actual value.
  480. #
  481. #
  482. # Regular expression derived from the _tokenize() subroutine in
  483. # Brad Choate's MTRegex plugin.
  484. # <http://www.bradchoate.com/past/mtregex.php>
  485. #
  486. $index = 0;
  487. $tokens = array();
  488. $match = '(?s:<!--.*?-->)|'. # comment
  489. '(?s:<\?.*?\?>)|'. # processing instruction
  490. # regular tags
  491. '(?:<[/!$]?[-a-zA-Z0-9:]+\b(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*>)';
  492. $parts = preg_split("{($match)}", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
  493. foreach ($parts as $part) {
  494. if (++$index % 2 && $part != '')
  495. $tokens[] = array('text', $part);
  496. else
  497. $tokens[] = array('tag', $part);
  498. }
  499. return $tokens;
  500. }
  501. }
  502. #
  503. # SmartyPants Typographer Parser Class
  504. #
  505. class SmartyPantsTypographer_Parser extends SmartyPants_Parser {
  506. # Options to specify which transformations to make:
  507. var $do_comma_quotes = 0;
  508. var $do_guillemets = 0;
  509. var $do_space_emdash = 0;
  510. var $do_space_endash = 0;
  511. var $do_space_colon = 0;
  512. var $do_space_semicolon = 0;
  513. var $do_space_marks = 0;
  514. var $do_space_frenchquote = 0;
  515. var $do_space_thousand = 0;
  516. var $do_space_unit = 0;
  517. # Smart quote characters:
  518. var $smart_doublequote_open = SMARTYPANTS_SMART_DOUBLEQUOTE_OPEN;
  519. var $smart_doublequote_close = SMARTYPANTS_SMART_DOUBLEQUOTE_CLOSE;
  520. var $smart_singlequote_open = '&#8216;';
  521. var $smart_singlequote_close = '&#8217;'; # Also apostrophe.
  522. # Space characters for different places:
  523. var $space_emdash = SMARTYPANTS_SPACE_EMDASH;
  524. var $space_endash = SMARTYPANTS_SPACE_ENDASH;
  525. var $space_colon = SMARTYPANTS_SPACE_COLON;
  526. var $space_semicolon = SMARTYPANTS_SPACE_SEMICOLON;
  527. var $space_marks = SMARTYPANTS_SPACE_MARKS;
  528. var $space_frenchquote = SMARTYPANTS_SPACE_FRENCHQUOTE;
  529. var $space_thousand = SMARTYPANTS_SPACE_THOUSAND;
  530. var $space_unit = SMARTYPANTS_SPACE_UNIT;
  531. # Expression of a space (breakable or not):
  532. var $space = '(?: | |&nbsp;|&#0*160;|&#x0*[aA]0;)';
  533. function SmartyPantsTypographer_Parser($attr = SMARTYPANTS_ATTR) {
  534. #
  535. # Initialize a SmartyPantsTypographer_Parser with certain attributes.
  536. #
  537. # Parser attributes:
  538. # 0 : do nothing
  539. # 1 : set all, except dash spacing
  540. # 2 : set all, except dash spacing, using old school en- and em- dash shortcuts
  541. # 3 : set all, except dash spacing, using inverted old school en and em- dash shortcuts
  542. #
  543. # Punctuation:
  544. # q -> quotes
  545. # b -> backtick quotes (``double'' only)
  546. # B -> backtick quotes (``double'' and `single')
  547. # c -> comma quotes (,,double`` only)
  548. # g -> guillemets (<<double>> only)
  549. # d -> dashes
  550. # D -> old school dashes
  551. # i -> inverted old school dashes
  552. # e -> ellipses
  553. # w -> convert &quot; entities to " for Dreamweaver users
  554. #
  555. # Spacing:
  556. # : -> colon spacing +-
  557. # ; -> semicolon spacing +-
  558. # m -> question and exclamation marks spacing +-
  559. # h -> em-dash spacing +-
  560. # H -> en-dash spacing +-
  561. # f -> french quote spacing +-
  562. # t -> thousand separator spacing -
  563. # u -> unit spacing +-
  564. # (you can add a plus sign after some of these options denoted by + to
  565. # add the space when it is not already present, or you can add a minus
  566. # sign to completly remove any space present)
  567. #
  568. # Initialize inherited SmartyPants parser.
  569. parent::SmartyPants_Parser($attr);
  570. if ($attr == "1" || $attr == "2" || $attr == "3") {
  571. # Do everything, turn all options on.
  572. $this->do_comma_quotes = 1;
  573. $this->do_guillemets = 1;
  574. $this->do_space_emdash = 1;
  575. $this->do_space_endash = 1;
  576. $this->do_space_colon = 1;
  577. $this->do_space_semicolon = 1;
  578. $this->do_space_marks = 1;
  579. $this->do_space_frenchquote = 1;
  580. $this->do_space_thousand = 1;
  581. $this->do_space_unit = 1;
  582. }
  583. else if ($attr == "-1") {
  584. # Special "stupefy" mode.
  585. $this->do_stupefy = 1;
  586. }
  587. else {
  588. $chars = preg_split('//', $attr);
  589. foreach ($chars as $c){
  590. if ($c == "c") { $current =& $this->do_comma_quotes; }
  591. else if ($c == "g") { $current =& $this->do_guillemets; }
  592. else if ($c == ":") { $current =& $this->do_space_colon; }
  593. else if ($c == ";") { $current =& $this->do_space_semicolon; }
  594. else if ($c == "m") { $current =& $this->do_space_marks; }
  595. else if ($c == "h") { $current =& $this->do_space_emdash; }
  596. else if ($c == "H") { $current =& $this->do_space_endash; }
  597. else if ($c == "f") { $current =& $this->do_space_frenchquote; }
  598. else if ($c == "t") { $current =& $this->do_space_thousand; }
  599. else if ($c == "u") { $current =& $this->do_space_unit; }
  600. else if ($c == "+") {
  601. $current = 2;
  602. unset($current);
  603. }
  604. else if ($c == "-") {
  605. $current = -1;
  606. unset($current);
  607. }
  608. else {
  609. # Unknown attribute option, ignore.
  610. }
  611. $current = 1;
  612. }
  613. }
  614. }
  615. function educate($t, $prev_token_last_char) {
  616. $t = parent::educate($t, $prev_token_last_char);
  617. if ($this->do_comma_quotes) $t = $this->educateCommaQuotes($t);
  618. if ($this->do_guillemets) $t = $this->educateGuillemets($t);
  619. if ($this->do_space_emdash) $t = $this->spaceEmDash($t);
  620. if ($this->do_space_endash) $t = $this->spaceEnDash($t);
  621. if ($this->do_space_colon) $t = $this->spaceColon($t);
  622. if ($this->do_space_semicolon) $t = $this->spaceSemicolon($t);
  623. if ($this->do_space_marks) $t = $this->spaceMarks($t);
  624. if ($this->do_space_frenchquote) $t = $this->spaceFrenchQuotes($t);
  625. if ($this->do_space_thousand) $t = $this->spaceThousandSeparator($t);
  626. if ($this->do_space_unit) $t = $this->spaceUnit($t);
  627. return $t;
  628. }
  629. function educateQuotes($_) {
  630. #
  631. # Parameter: String.
  632. #
  633. # Returns: The string, with "educated" curly quote HTML entities.
  634. #
  635. # Example input: "Isn't this fun?"
  636. # Example output: &#8220;Isn&#8217;t this fun?&#8221;
  637. #
  638. $dq_open = $this->smart_doublequote_open;
  639. $dq_close = $this->smart_doublequote_close;
  640. $sq_open = $this->smart_singlequote_open;
  641. $sq_close = $this->smart_singlequote_close;
  642. # Make our own "punctuation" character class, because the POSIX-style
  643. # [:PUNCT:] is only available in Perl 5.6 or later:
  644. $punct_class = "[!\"#\\$\\%'()*+,-.\\/:;<=>?\\@\\[\\\\\]\\^_`{|}~]";
  645. # Special case if the very first character is a quote
  646. # followed by punctuation at a non-word-break. Close the quotes by brute force:
  647. $_ = preg_replace(
  648. array("/^'(?=$punct_class\\B)/", "/^\"(?=$punct_class\\B)/"),
  649. array($sq_close, $dq_close), $_);
  650. # Special case for double sets of quotes, e.g.:
  651. # <p>He said, "'Quoted' words in a larger quote."</p>
  652. $_ = preg_replace(
  653. array("/\"'(?=\w)/", "/'\"(?=\w)/"),
  654. array($dq_open.$sq_open, $sq_open.$dq_open), $_);
  655. # Special case for decade abbreviations (the '80s):
  656. $_ = preg_replace("/'(?=\\d{2}s)/", $sq_close, $_);
  657. $close_class = '[^\ \t\r\n\[\{\(\-]';
  658. $dec_dashes = '&\#8211;|&\#8212;';
  659. # Get most opening single quotes:
  660. $_ = preg_replace("{
  661. (
  662. \\s | # a whitespace char, or
  663. &nbsp; | # a non-breaking space entity, or
  664. -- | # dashes, or
  665. &[mn]dash; | # named dash entities
  666. $dec_dashes | # or decimal entities
  667. &\\#x201[34]; # or hex
  668. )
  669. ' # the quote
  670. (?=\\w) # followed by a word character
  671. }x", '\1'.$sq_open, $_);
  672. # Single closing quotes:
  673. $_ = preg_replace("{
  674. ($close_class)?
  675. '
  676. (?(1)| # If $1 captured, then do nothing;
  677. (?=\\s | s\\b) # otherwise, positive lookahead for a whitespace
  678. ) # char or an 's' at a word ending position. This
  679. # is a special case to handle something like:
  680. # \"<i>Custer</i>'s Last Stand.\"
  681. }xi", '\1'.$sq_close, $_);
  682. # Any remaining single quotes should be opening ones:
  683. $_ = str_replace("'", $sq_open, $_);
  684. # Get most opening double quotes:
  685. $_ = preg_replace("{
  686. (
  687. \\s | # a whitespace char, or
  688. &nbsp; | # a non-breaking space entity, or
  689. -- | # dashes, or
  690. &[mn]dash; | # named dash entities
  691. $dec_dashes | # or decimal entities
  692. &\\#x201[34]; # or hex
  693. )
  694. \" # the quote
  695. (?=\\w) # followed by a word character
  696. }x", '\1'.$dq_open, $_);
  697. # Double closing quotes:
  698. $_ = preg_replace("{
  699. ($close_class)?
  700. \"
  701. (?(1)|(?=\\s)) # If $1 captured, then do nothing;
  702. # if not, then make sure the next char is whitespace.
  703. }x", '\1'.$dq_close, $_);
  704. # Any remaining quotes should be opening ones.
  705. $_ = str_replace('"', $dq_open, $_);
  706. return $_;
  707. }
  708. function educateCommaQuotes($_) {
  709. #
  710. # Parameter: String.
  711. # Returns: The string, with ,,comma,, -style double quotes
  712. # translated into HTML curly quote entities.
  713. #
  714. # Example input: ,,Isn't this fun?,,
  715. # Example output: &#8222;Isn't this fun?&#8222;
  716. #
  717. # Note: this is meant to be used alongside with backtick quotes; there is
  718. # no language that use only lower quotations alone mark like in the example.
  719. #
  720. $_ = str_replace(",,", '&#8222;', $_);
  721. return $_;
  722. }
  723. function educateGuillemets($_) {
  724. #
  725. # Parameter: String.
  726. # Returns: The string, with << guillemets >> -style quotes
  727. # translated into HTML guillemets entities.
  728. #
  729. # Example input: << Isn't this fun? >>
  730. # Example output: &#8222; Isn't this fun? &#8222;
  731. #
  732. $_ = preg_replace("/(?:<|&lt;){2}/", '&#171;', $_);
  733. $_ = preg_replace("/(?:>|&gt;){2}/", '&#187;', $_);
  734. return $_;
  735. }
  736. function spaceFrenchQuotes($_) {
  737. #
  738. # Parameters: String, replacement character, and forcing flag.
  739. # Returns: The string, with appropriates spaces replaced
  740. # inside french-style quotes, only french quotes.
  741. #
  742. # Example input: Quotes in « French », »German« and »Finnish» style.
  743. # Example output: Quotes in «_French_», »German« and »Finnish» style.
  744. #
  745. $opt = ( $this->do_space_frenchquote == 2 ? '?' : '' );
  746. $chr = ( $this->do_space_frenchquote != -1 ? $this->space_frenchquote : '' );
  747. # Characters allowed immediatly outside quotes.
  748. $outside_char = $this->space . '|\s|[.,:;!?\[\](){}|@*~=+-]|¡|¿';
  749. $_ = preg_replace(
  750. "/(^|$outside_char)(&#171;|«|&#8250;|‹)$this->space$opt/",
  751. "\\1\\2$chr", $_);
  752. $_ = preg_replace(
  753. "/$this->space$opt(&#187;|»|&#8249;|›)($outside_char|$)/",
  754. "$chr\\1\\2", $_);
  755. return $_;
  756. }
  757. function spaceColon($_) {
  758. #
  759. # Parameters: String, replacement character, and forcing flag.
  760. # Returns: The string, with appropriates spaces replaced
  761. # before colons.
  762. #
  763. # Example input: Ingredients : fun.
  764. # Example output: Ingredients_: fun.
  765. #
  766. $opt = ( $this->do_space_colon == 2 ? '?' : '' );
  767. $chr = ( $this->do_space_colon != -1 ? $this->space_colon : '' );
  768. $_ = preg_replace("/$this->space$opt(:)(\\s|$)/m",
  769. "$chr\\1\\2", $_);
  770. return $_;
  771. }
  772. function spaceSemicolon($_) {
  773. #
  774. # Parameters: String, replacement character, and forcing flag.
  775. # Returns: The string, with appropriates spaces replaced
  776. # before semicolons.
  777. #
  778. # Example input: There he goes ; there she goes.
  779. # Example output: There he goes_; there she goes.
  780. #
  781. $opt = ( $this->do_space_semicolon == 2 ? '?' : '' );
  782. $chr = ( $this->do_space_semicolon != -1 ? $this->space_semicolon : '' );
  783. $_ = preg_replace("/$this->space(;)(?=\\s|$)/m",
  784. " \\1", $_);
  785. $_ = preg_replace("/((?:^|\\s)(?>[^&;\\s]+|&#?[a-zA-Z0-9]+;)*)".
  786. " $opt(;)(?=\\s|$)/m",
  787. "\\1$chr\\2", $_);
  788. return $_;
  789. }
  790. function spaceMarks($_) {
  791. #
  792. # Parameters: String, replacement character, and forcing flag.
  793. # Returns: The string, with appropriates spaces replaced
  794. # around question and exclamation marks.
  795. #
  796. # Example input: ¡ Holà ! What ?
  797. # Example output: ¡_Holà_! What_?
  798. #
  799. $opt = ( $this->do_space_marks == 2 ? '?' : '' );
  800. $chr = ( $this->do_space_marks != -1 ? $this->space_marks : '' );
  801. // Regular marks.
  802. $_ = preg_replace("/$this->space$opt([?!]+)/", "$chr\\1", $_);
  803. // Inverted marks.
  804. $imarks = "(?:¡|&iexcl;|&#161;|&#x[Aa]1;|¿|&iquest;|&#191;|&#x[Bb][Ff];)";
  805. $_ = preg_replace("/($imarks+)$this->space$opt/", "\\1$chr", $_);
  806. return $_;
  807. }
  808. function spaceEmDash($_) {
  809. #
  810. # Parameters: String, two replacement characters separated by a hyphen (`-`),
  811. # and forcing flag.
  812. #
  813. # Returns: The string, with appropriates spaces replaced
  814. # around dashes.
  815. #
  816. # Example input: Then without any plan the fun happend.
  817. # Example output: Then__without any plan__the fun happend.
  818. #
  819. $opt = ( $this->do_space_emdash == 2 ? '?' : '' );
  820. $chr = ( $this->do_space_emdash != -1 ? $this->space_emdash : '' );
  821. $_ = preg_replace("/$this->space$opt(&#8212;|—)$this->space$opt/",
  822. "$chr\\1$chr", $_);
  823. return $_;
  824. }
  825. function spaceEnDash($_) {
  826. #
  827. # Parameters: String, two replacement characters separated by a hyphen (`-`),
  828. # and forcing flag.
  829. #
  830. # Returns: The string, with appropriates spaces replaced
  831. # around dashes.
  832. #
  833. # Example input: Then without any plan the fun happend.
  834. # Example output: Then__without any plan__the fun happend.
  835. #
  836. $opt = ( $this->do_space_endash == 2 ? '?' : '' );
  837. $chr = ( $this->do_space_endash != -1 ? $this->space_endash : '' );
  838. $_ = preg_replace("/$this->space$opt(&#8211;|–)$this->space$opt/",
  839. "$chr\\1$chr", $_);
  840. return $_;
  841. }
  842. function spaceThousandSeparator($_) {
  843. #
  844. # Parameters: String, replacement character, and forcing flag.
  845. # Returns: The string, with appropriates spaces replaced
  846. # inside numbers (thousand separator in french).
  847. #
  848. # Example input: Il y a 10 000 insectes amusants dans ton jardin.
  849. # Example output: Il y a 10_000 insectes amusants dans ton jardin.
  850. #
  851. $chr = ( $this->do_space_thousand != -1 ? $this->space_thousand : '' );
  852. $_ = preg_replace('/([0-9]) ([0-9])/', "\\1$chr\\2", $_);
  853. return $_;
  854. }
  855. var $units = '
  856. ### Metric units (with prefixes)
  857. (?:
  858. p |
  859. µ | &micro; | &\#0*181; | &\#[xX]0*[Bb]5; |
  860. [mcdhkMGT]
  861. )?
  862. (?:
  863. [mgstAKNJWCVFSTHBL]|mol|cd|rad|Hz|Pa|Wb|lm|lx|Bq|Gy|Sv|kat|
  864. Ω | Ohm | &Omega; | &\#0*937; | &\#[xX]0*3[Aa]9;
  865. )|
  866. ### Computers units (KB, Kb, TB, Kbps)
  867. [kKMGT]?(?:[oBb]|[oBb]ps|flops)|
  868. ### Money
  869. ¢ | &cent; | &\#0*162; | &\#[xX]0*[Aa]2; |
  870. M?(?:
  871. £ | &pound; | &\#0*163; | &\#[xX]0*[Aa]3; |
  872. ¥ | &yen; | &\#0*165; | &\#[xX]0*[Aa]5; |
  873. | &euro; | &\#0*8364; | &\#[xX]0*20[Aa][Cc]; |
  874. $
  875. )|
  876. ### Other units
  877. (?: ° | &deg; | &\#0*176; | &\#[xX]0*[Bb]0; ) [CF]? |
  878. %|pt|pi|M?px|em|en|gal|lb|[NSEOW]|[NS][EOW]|ha|mbar
  879. '; //x
  880. function spaceUnit($_) {
  881. #
  882. # Parameters: String, replacement character, and forcing flag.
  883. # Returns: The string, with appropriates spaces replaced
  884. # before unit symbols.
  885. #
  886. # Example input: Get 3 mol of fun for 3 $.
  887. # Example output: Get 3_mol of fun for 3_$.
  888. #
  889. $opt = ( $this->do_space_unit == 2 ? '?' : '' );
  890. $chr = ( $this->do_space_unit != -1 ? $this->space_unit : '' );
  891. $_ = preg_replace('/
  892. (?:([0-9])[ ]'.$opt.') # Number followed by space.
  893. ('.$this->units.') # Unit.
  894. (?![a-zA-Z0-9]) # Negative lookahead for other unit characters.
  895. /x',
  896. "\\1$chr\\2", $_);
  897. return $_;
  898. }
  899. function spaceAbbr($_) {
  900. #
  901. # Parameters: String, replacement character, and forcing flag.
  902. # Returns: The string, with appropriates spaces replaced
  903. # around abbreviations.
  904. #
  905. # Example input: Fun i.e. something pleasant.
  906. # Example output: Fun i.e._something pleasant.
  907. #
  908. $opt = ( $this->do_space_abbr == 2 ? '?' : '' );
  909. $_ = preg_replace("/(^|\s)($this->abbr_after) $opt/m",
  910. "\\1\\2$this->space_abbr", $_);
  911. $_ = preg_replace("/( )$opt($this->abbr_sp_before)(?![a-zA-Z'])/m",
  912. "\\1$this->space_abbr\\2", $_);
  913. return $_;
  914. }
  915. function stupefyEntities($_) {
  916. #
  917. # Adding angle quotes and lower quotes to SmartyPants's stupefy mode.
  918. #
  919. $_ = parent::stupefyEntities($_);
  920. $_ = str_replace(array('&#8222;', '&#171;', '&#187'), '"', $_);
  921. return $_;
  922. }
  923. function processEscapes($_) {
  924. #
  925. # Adding a few more escapes to SmartyPants's escapes:
  926. #
  927. # Escape Value
  928. # ------ -----
  929. # \, &#44;
  930. # \< &#60;
  931. # \> &#62;
  932. #
  933. $_ = parent::processEscapes($_);
  934. $_ = str_replace(
  935. array('\,', '\<', '\>', '\&lt;', '\&gt;'),
  936. array('&#44;', '&#60;', '&#62;', '&#60;', '&#62;'), $_);
  937. return $_;
  938. }
  939. }
  940. /*
  941. PHP SmartyPants Typographer
  942. ===========================
  943. Version History
  944. ---------------
  945. 1.0 (28 Jun 2006)
  946. * First public release of PHP SmartyPants Typographer.
  947. Bugs
  948. ----
  949. To file bug reports or feature requests (other than topics listed in the
  950. Caveats section above) please send email to:
  951. <michel.fortin@michelf.com>
  952. If the bug involves quotes being curled the wrong way, please send example
  953. text to illustrate.
  954. ### Algorithmic Shortcomings ###
  955. One situation in which quotes will get curled the wrong way is when
  956. apostrophes are used at the start of leading contractions. For example:
  957. 'Twas the night before Christmas.
  958. In the case above, SmartyPants will turn the apostrophe into an opening
  959. single-quote, when in fact it should be a closing one. I don't think
  960. this problem can be solved in the general case -- every word processor
  961. I've tried gets this wrong as well. In such cases, it's best to use the
  962. proper HTML entity for closing single-quotes (`&#8217;`) by hand.
  963. Copyright and License
  964. ---------------------
  965. PHP SmartyPants & Typographer
  966. Copyright (c) 2004-2006 Michel Fortin
  967. <http://www.michelf.com>
  968. All rights reserved.
  969. Original SmartyPants
  970. Copyright (c) 2003-2004 John Gruber
  971. <http://daringfireball.net/>
  972. All rights reserved.
  973. Redistribution and use in source and binary forms, with or without
  974. modification, are permitted provided that the following conditions are met:
  975. * Redistributions of source code must retain the above copyright
  976. notice, this list of conditions and the following disclaimer.
  977. * Redistributions in binary form must reproduce the above copyright
  978. notice, this list of conditions and the following disclaimer in the
  979. documentation and/or other materials provided with the distribution.
  980. * Neither the name "SmartyPants" nor the names of its contributors may
  981. be used to endorse or promote products derived from this software
  982. without specific prior written permission.
  983. This software is provided by the copyright holders and contributors "as is"
  984. and any express or implied warranties, including, but not limited to, the
  985. implied warranties of merchantability and fitness for a particular purpose
  986. are disclaimed. In no event shall the copyright owner or contributors be
  987. liable for any direct, indirect, incidental, special, exemplary, or
  988. consequential damages (including, but not limited to, procurement of
  989. substitute goods or services; loss of use, data, or profits; or business
  990. interruption) however caused and on any theory of liability, whether in
  991. contract, strict liability, or tort (including negligence or otherwise)
  992. arising in any way out of the use of this software, even if advised of the
  993. possibility of such damage.
  994. */
  995. ?>