1
0

smartquotes.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991
  1. #!/usr/bin/python3
  2. # :Id: $Id: smartquotes.py 9068 2022-06-13 12:05:08Z milde $
  3. # :Copyright: © 2010 Günter Milde,
  4. # original `SmartyPants`_: © 2003 John Gruber
  5. # smartypants.py: © 2004, 2007 Chad Miller
  6. # :Maintainer: docutils-develop@lists.sourceforge.net
  7. # :License: Released under the terms of the `2-Clause BSD license`_, in short:
  8. #
  9. # Copying and distribution of this file, with or without modification,
  10. # are permitted in any medium without royalty provided the copyright
  11. # notices and this notice are preserved.
  12. # This file is offered as-is, without any warranty.
  13. #
  14. # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
  15. r"""
  16. =========================
  17. Smart Quotes for Docutils
  18. =========================
  19. Synopsis
  20. ========
  21. "SmartyPants" is a free web publishing plug-in for Movable Type, Blosxom, and
  22. BBEdit that easily translates plain ASCII punctuation characters into "smart"
  23. typographic punctuation characters.
  24. ``smartquotes.py`` is an adaption of "SmartyPants" to Docutils_.
  25. * Using Unicode instead of HTML entities for typographic punctuation
  26. characters, it works for any output format that supports Unicode.
  27. * Supports `language specific quote characters`__.
  28. __ https://en.wikipedia.org/wiki/Non-English_usage_of_quotation_marks
  29. Authors
  30. =======
  31. `John Gruber`_ did all of the hard work of writing this software in Perl for
  32. `Movable Type`_ and almost all of this useful documentation. `Chad Miller`_
  33. ported it to Python to use with Pyblosxom_.
  34. Adapted to Docutils_ by Günter Milde.
  35. Additional Credits
  36. ==================
  37. Portions of the SmartyPants original work are based on Brad Choate's nifty
  38. MTRegex plug-in. `Brad Choate`_ also contributed a few bits of source code to
  39. this plug-in. Brad Choate is a fine hacker indeed.
  40. `Jeremy Hedley`_ and `Charles Wiltgen`_ deserve mention for exemplary beta
  41. testing of the original SmartyPants.
  42. `Rael Dornfest`_ ported SmartyPants to Blosxom.
  43. .. _Brad Choate: http://bradchoate.com/
  44. .. _Jeremy Hedley: http://antipixel.com/
  45. .. _Charles Wiltgen: http://playbacktime.com/
  46. .. _Rael Dornfest: http://raelity.org/
  47. Copyright and License
  48. =====================
  49. SmartyPants_ license (3-Clause BSD license):
  50. Copyright (c) 2003 John Gruber (http://daringfireball.net/)
  51. All rights reserved.
  52. Redistribution and use in source and binary forms, with or without
  53. modification, are permitted provided that the following conditions are
  54. met:
  55. * Redistributions of source code must retain the above copyright
  56. notice, this list of conditions and the following disclaimer.
  57. * Redistributions in binary form must reproduce the above copyright
  58. notice, this list of conditions and the following disclaimer in
  59. the documentation and/or other materials provided with the
  60. distribution.
  61. * Neither the name "SmartyPants" nor the names of its contributors
  62. may be used to endorse or promote products derived from this
  63. software without specific prior written permission.
  64. This software is provided by the copyright holders and contributors
  65. "as is" and any express or implied warranties, including, but not
  66. limited to, the implied warranties of merchantability and fitness for
  67. a particular purpose are disclaimed. In no event shall the copyright
  68. owner or contributors be liable for any direct, indirect, incidental,
  69. special, exemplary, or consequential damages (including, but not
  70. limited to, procurement of substitute goods or services; loss of use,
  71. data, or profits; or business interruption) however caused and on any
  72. theory of liability, whether in contract, strict liability, or tort
  73. (including negligence or otherwise) arising in any way out of the use
  74. of this software, even if advised of the possibility of such damage.
  75. smartypants.py license (2-Clause BSD license):
  76. smartypants.py is a derivative work of SmartyPants.
  77. Redistribution and use in source and binary forms, with or without
  78. modification, are permitted provided that the following conditions are
  79. met:
  80. * Redistributions of source code must retain the above copyright
  81. notice, this list of conditions and the following disclaimer.
  82. * Redistributions in binary form must reproduce the above copyright
  83. notice, this list of conditions and the following disclaimer in
  84. the documentation and/or other materials provided with the
  85. distribution.
  86. This software is provided by the copyright holders and contributors
  87. "as is" and any express or implied warranties, including, but not
  88. limited to, the implied warranties of merchantability and fitness for
  89. a particular purpose are disclaimed. In no event shall the copyright
  90. owner or contributors be liable for any direct, indirect, incidental,
  91. special, exemplary, or consequential damages (including, but not
  92. limited to, procurement of substitute goods or services; loss of use,
  93. data, or profits; or business interruption) however caused and on any
  94. theory of liability, whether in contract, strict liability, or tort
  95. (including negligence or otherwise) arising in any way out of the use
  96. of this software, even if advised of the possibility of such damage.
  97. .. _John Gruber: http://daringfireball.net/
  98. .. _Chad Miller: http://web.chad.org/
  99. .. _Pyblosxom: http://pyblosxom.bluesock.org/
  100. .. _SmartyPants: http://daringfireball.net/projects/smartypants/
  101. .. _Movable Type: http://www.movabletype.org/
  102. .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
  103. .. _Docutils: https://docutils.sourceforge.io/
  104. Description
  105. ===========
  106. SmartyPants can perform the following transformations:
  107. - Straight quotes ( " and ' ) into "curly" quote characters
  108. - Backticks-style quotes (\`\`like this'') into "curly" quote characters
  109. - Dashes (``--`` and ``---``) into en- and em-dash entities
  110. - Three consecutive dots (``...`` or ``. . .``) into an ellipsis entity
  111. This means you can write, edit, and save your posts using plain old
  112. ASCII straight quotes, plain dashes, and plain dots, but your published
  113. posts (and final HTML output) will appear with smart quotes, em-dashes,
  114. and proper ellipses.
  115. SmartyPants does not modify characters within ``<pre>``, ``<code>``, ``<kbd>``,
  116. ``<math>`` or ``<script>`` tag blocks. Typically, these tags are used to
  117. display text where smart quotes and other "smart punctuation" would not be
  118. appropriate, such as source code or example markup.
  119. Backslash Escapes
  120. =================
  121. If you need to use literal straight quotes (or plain hyphens and periods),
  122. `smartquotes` accepts the following backslash escape sequences to force
  123. ASCII-punctuation. Mind, that you need two backslashes as Docutils expands it,
  124. too.
  125. ======== =========
  126. Escape Character
  127. ======== =========
  128. ``\\`` \\
  129. ``\\"`` \\"
  130. ``\\'`` \\'
  131. ``\\.`` \\.
  132. ``\\-`` \\-
  133. ``\\``` \\`
  134. ======== =========
  135. This is useful, for example, when you want to use straight quotes as
  136. foot and inch marks: 6\\'2\\" tall; a 17\\" iMac.
  137. Caveats
  138. =======
  139. Why You Might Not Want to Use Smart Quotes in Your Weblog
  140. ---------------------------------------------------------
  141. For one thing, you might not care.
  142. Most normal, mentally stable individuals do not take notice of proper
  143. typographic punctuation. Many design and typography nerds, however, break
  144. out in a nasty rash when they encounter, say, a restaurant sign that uses
  145. a straight apostrophe to spell "Joe's".
  146. If you're the sort of person who just doesn't care, you might well want to
  147. continue not caring. Using straight quotes -- and sticking to the 7-bit
  148. ASCII character set in general -- is certainly a simpler way to live.
  149. Even if you *do* care about accurate typography, you still might want to
  150. think twice before educating the quote characters in your weblog. One side
  151. effect of publishing curly quote characters is that it makes your
  152. weblog a bit harder for others to quote from using copy-and-paste. What
  153. happens is that when someone copies text from your blog, the copied text
  154. contains the 8-bit curly quote characters (as well as the 8-bit characters
  155. for em-dashes and ellipses, if you use these options). These characters
  156. are not standard across different text encoding methods, which is why they
  157. need to be encoded as characters.
  158. People copying text from your weblog, however, may not notice that you're
  159. using curly quotes, and they'll go ahead and paste the unencoded 8-bit
  160. characters copied from their browser into an email message or their own
  161. weblog. When pasted as raw "smart quotes", these characters are likely to
  162. get mangled beyond recognition.
  163. That said, my own opinion is that any decent text editor or email client
  164. makes it easy to stupefy smart quote characters into their 7-bit
  165. equivalents, and I don't consider it my problem if you're using an
  166. indecent text editor or email client.
  167. Algorithmic Shortcomings
  168. ------------------------
  169. One situation in which quotes will get curled the wrong way is when
  170. apostrophes are used at the start of leading contractions. For example::
  171. 'Twas the night before Christmas.
  172. In the case above, SmartyPants will turn the apostrophe into an opening
  173. secondary quote, when in fact it should be the `RIGHT SINGLE QUOTATION MARK`
  174. character which is also "the preferred character to use for apostrophe"
  175. (Unicode). I don't think this problem can be solved in the general case --
  176. every word processor I've tried gets this wrong as well. In such cases, it's
  177. best to inset the `RIGHT SINGLE QUOTATION MARK` (’) by hand.
  178. In English, the same character is used for apostrophe and closing secondary
  179. quote (both plain and "smart" ones). For other locales (French, Italean,
  180. Swiss, ...) "smart" secondary closing quotes differ from the curly apostrophe.
  181. .. class:: language-fr
  182. Il dit : "C'est 'super' !"
  183. If the apostrophe is used at the end of a word, it cannot be distinguished
  184. from a secondary quote by the algorithm. Therefore, a text like::
  185. .. class:: language-de-CH
  186. "Er sagt: 'Ich fass' es nicht.'"
  187. will get a single closing guillemet instead of an apostrophe.
  188. This can be prevented by use use of the `RIGHT SINGLE QUOTATION MARK` in
  189. the source::
  190. - "Er sagt: 'Ich fass' es nicht.'"
  191. + "Er sagt: 'Ich fass’ es nicht.'"
  192. Version History
  193. ===============
  194. 1.9 2022-03-04
  195. - Code cleanup. Require Python 3.
  196. 1.8.1 2017-10-25
  197. - Use open quote after Unicode whitespace, ZWSP, and ZWNJ.
  198. - Code cleanup.
  199. 1.8: 2017-04-24
  200. - Command line front-end.
  201. 1.7.1: 2017-03-19
  202. - Update and extend language-dependent quotes.
  203. - Differentiate apostrophe from single quote.
  204. 1.7: 2012-11-19
  205. - Internationalization: language-dependent quotes.
  206. 1.6.1: 2012-11-06
  207. - Refactor code, code cleanup,
  208. - `educate_tokens()` generator as interface for Docutils.
  209. 1.6: 2010-08-26
  210. - Adaption to Docutils:
  211. - Use Unicode instead of HTML entities,
  212. - Remove code special to pyblosxom.
  213. 1.5_1.6: Fri, 27 Jul 2007 07:06:40 -0400
  214. - Fixed bug where blocks of precious unalterable text was instead
  215. interpreted. Thanks to Le Roux and Dirk van Oosterbosch.
  216. 1.5_1.5: Sat, 13 Aug 2005 15:50:24 -0400
  217. - Fix bogus magical quotation when there is no hint that the
  218. user wants it, e.g., in "21st century". Thanks to Nathan Hamblen.
  219. - Be smarter about quotes before terminating numbers in an en-dash'ed
  220. range.
  221. 1.5_1.4: Thu, 10 Feb 2005 20:24:36 -0500
  222. - Fix a date-processing bug, as reported by jacob childress.
  223. - Begin a test-suite for ensuring correct output.
  224. - Removed import of "string", since I didn't really need it.
  225. (This was my first every Python program. Sue me!)
  226. 1.5_1.3: Wed, 15 Sep 2004 18:25:58 -0400
  227. - Abort processing if the flavour is in forbidden-list. Default of
  228. [ "rss" ] (Idea of Wolfgang SCHNERRING.)
  229. - Remove stray virgules from en-dashes. Patch by Wolfgang SCHNERRING.
  230. 1.5_1.2: Mon, 24 May 2004 08:14:54 -0400
  231. - Some single quotes weren't replaced properly. Diff-tesuji played
  232. by Benjamin GEIGER.
  233. 1.5_1.1: Sun, 14 Mar 2004 14:38:28 -0500
  234. - Support upcoming pyblosxom 0.9 plugin verification feature.
  235. 1.5_1.0: Tue, 09 Mar 2004 08:08:35 -0500
  236. - Initial release
  237. """
  238. import re
  239. import sys
  240. options = r"""
  241. Options
  242. =======
  243. Numeric values are the easiest way to configure SmartyPants' behavior:
  244. :0: Suppress all transformations. (Do nothing.)
  245. :1: Performs default SmartyPants transformations: quotes (including
  246. \`\`backticks'' -style), em-dashes, and ellipses. "``--``" (dash dash)
  247. is used to signify an em-dash; there is no support for en-dashes
  248. :2: Same as smarty_pants="1", except that it uses the old-school typewriter
  249. shorthand for dashes: "``--``" (dash dash) for en-dashes, "``---``"
  250. (dash dash dash)
  251. for em-dashes.
  252. :3: Same as smarty_pants="2", but inverts the shorthand for dashes:
  253. "``--``" (dash dash) for em-dashes, and "``---``" (dash dash dash) for
  254. en-dashes.
  255. :-1: Stupefy mode. Reverses the SmartyPants transformation process, turning
  256. the characters produced by SmartyPants into their ASCII equivalents.
  257. E.g. the LEFT DOUBLE QUOTATION MARK (“) is turned into a simple
  258. double-quote (\"), "—" is turned into two dashes, etc.
  259. The following single-character attribute values can be combined to toggle
  260. individual transformations from within the smarty_pants attribute. For
  261. example, ``"1"`` is equivalent to ``"qBde"``.
  262. :q: Educates normal quote characters: (") and (').
  263. :b: Educates \`\`backticks'' -style double quotes.
  264. :B: Educates \`\`backticks'' -style double quotes and \`single' quotes.
  265. :d: Educates em-dashes.
  266. :D: Educates em-dashes and en-dashes, using old-school typewriter
  267. shorthand: (dash dash) for en-dashes, (dash dash dash) for em-dashes.
  268. :i: Educates em-dashes and en-dashes, using inverted old-school typewriter
  269. shorthand: (dash dash) for em-dashes, (dash dash dash) for en-dashes.
  270. :e: Educates ellipses.
  271. :w: Translates any instance of ``&quot;`` into a normal double-quote
  272. character. This should be of no interest to most people, but
  273. of particular interest to anyone who writes their posts using
  274. Dreamweaver, as Dreamweaver inexplicably uses this entity to represent
  275. a literal double-quote character. SmartyPants only educates normal
  276. quotes, not entities (because ordinarily, entities are used for
  277. the explicit purpose of representing the specific character they
  278. represent). The "w" option must be used in conjunction with one (or
  279. both) of the other quote options ("q" or "b"). Thus, if you wish to
  280. apply all SmartyPants transformations (quotes, en- and em-dashes, and
  281. ellipses) and also translate ``&quot;`` entities into regular quotes
  282. so SmartyPants can educate them, you should pass the following to the
  283. smarty_pants attribute:
  284. """
  285. class smartchars:
  286. """Smart quotes and dashes"""
  287. endash = '–' # "&#8211;" EN DASH
  288. emdash = '—' # "&#8212;" EM DASH
  289. ellipsis = '…' # "&#8230;" HORIZONTAL ELLIPSIS
  290. apostrophe = '’' # "&#8217;" RIGHT SINGLE QUOTATION MARK
  291. # quote characters (language-specific, set in __init__())
  292. # https://en.wikipedia.org/wiki/Non-English_usage_of_quotation_marks
  293. # http://de.wikipedia.org/wiki/Anf%C3%BChrungszeichen#Andere_Sprachen
  294. # https://fr.wikipedia.org/wiki/Guillemet
  295. # http://typographisme.net/post/Les-espaces-typographiques-et-le-web
  296. # http://www.btb.termiumplus.gc.ca/tpv2guides/guides/redac/index-fra.html
  297. # https://en.wikipedia.org/wiki/Hebrew_punctuation#Quotation_marks
  298. # [7] http://www.tustep.uni-tuebingen.de/bi/bi00/bi001t1-anfuehrung.pdf
  299. # [8] http://www.korrekturavdelingen.no/anforselstegn.htm
  300. # [9] Typografisk håndbok. Oslo: Spartacus. 2000. s. 67. ISBN 8243001530.
  301. # [10] http://www.typografi.org/sitat/sitatart.html
  302. #
  303. # See also configuration option "smartquote-locales".
  304. quotes = {
  305. 'af': '“”‘’',
  306. 'af-x-altquot': '„”‚’',
  307. 'bg': '„“‚‘', # https://bg.wikipedia.org/wiki/Кавички
  308. 'ca': '«»“”',
  309. 'ca-x-altquot': '“”‘’',
  310. 'cs': '„“‚‘',
  311. 'cs-x-altquot': '»«›‹',
  312. 'da': '»«›‹',
  313. 'da-x-altquot': '„“‚‘',
  314. # 'da-x-altquot2': '””’’',
  315. 'de': '„“‚‘',
  316. 'de-x-altquot': '»«›‹',
  317. 'de-ch': '«»‹›',
  318. 'el': '«»“”',
  319. 'en': '“”‘’',
  320. 'en-uk-x-altquot': '‘’“”', # Attention: " → ‘ and ' → “ !
  321. 'eo': '“”‘’',
  322. 'es': '«»“”',
  323. 'es-x-altquot': '“”‘’',
  324. 'et': '„“‚‘', # no secondary quote listed in
  325. 'et-x-altquot': '«»‹›', # the sources above (wikipedia.org)
  326. 'eu': '«»‹›',
  327. 'fi': '””’’',
  328. 'fi-x-altquot': '»»››',
  329. 'fr': ('« ', ' »', '“', '”'), # full no-break space
  330. 'fr-x-altquot': ('« ', ' »', '“', '”'), # narrow no-break space
  331. 'fr-ch': '«»‹›', # http://typoguide.ch/
  332. 'fr-ch-x-altquot': ('« ', ' »', '‹ ', ' ›'), # narrow no-break space # noqa:E501
  333. 'gl': '«»“”',
  334. 'he': '”“»«', # Hebrew is RTL, test position:
  335. 'he-x-altquot': '„”‚’', # low quotation marks are opening.
  336. # 'he-x-altquot': '“„‘‚', # RTL: low quotation marks opening
  337. 'hr': '„”‘’', # http://hrvatska-tipografija.com/polunavodnici/ # noqa:E501
  338. 'hr-x-altquot': '»«›‹',
  339. 'hsb': '„“‚‘',
  340. 'hsb-x-altquot': '»«›‹',
  341. 'hu': '„”«»',
  342. 'is': '„“‚‘',
  343. 'it': '«»“”',
  344. 'it-ch': '«»‹›',
  345. 'it-x-altquot': '“”‘’',
  346. # 'it-x-altquot2': '“„‘‚', # [7] in headlines
  347. 'ja': '「」『』',
  348. 'ko': '“”‘’',
  349. 'lt': '„“‚‘',
  350. 'lv': '„“‚‘',
  351. 'mk': '„“‚‘', # Macedonian, https://mk.wikipedia.org/wiki/Правопис_и_правоговор_на_македонскиот_јазик # noqa:E501
  352. 'nl': '“”‘’',
  353. 'nl-x-altquot': '„”‚’',
  354. # 'nl-x-altquot2': '””’’',
  355. 'nb': '«»’’', # Norsk bokmål (canonical form 'no')
  356. 'nn': '«»’’', # Nynorsk [10]
  357. 'nn-x-altquot': '«»‘’', # [8], [10]
  358. # 'nn-x-altquot2': '«»«»', # [9], [10]
  359. # 'nn-x-altquot3': '„“‚‘', # [10]
  360. 'no': '«»’’', # Norsk bokmål [10]
  361. 'no-x-altquot': '«»‘’', # [8], [10]
  362. # 'no-x-altquot2': '«»«»', # [9], [10
  363. # 'no-x-altquot3': '„“‚‘', # [10]
  364. 'pl': '„”«»',
  365. 'pl-x-altquot': '«»‚’',
  366. # 'pl-x-altquot2': '„”‚’', # https://pl.wikipedia.org/wiki/Cudzys%C5%82%C3%B3w # noqa:E501
  367. 'pt': '«»“”',
  368. 'pt-br': '“”‘’',
  369. 'ro': '„”«»',
  370. 'ru': '«»„“',
  371. 'sh': '„”‚’', # Serbo-Croatian
  372. 'sh-x-altquot': '»«›‹',
  373. 'sk': '„“‚‘', # Slovak
  374. 'sk-x-altquot': '»«›‹',
  375. 'sl': '„“‚‘', # Slovenian
  376. 'sl-x-altquot': '»«›‹',
  377. 'sq': '«»‹›', # Albanian
  378. 'sq-x-altquot': '“„‘‚',
  379. 'sr': '„”’’',
  380. 'sr-x-altquot': '»«›‹',
  381. 'sv': '””’’',
  382. 'sv-x-altquot': '»»››',
  383. 'tr': '“”‘’',
  384. 'tr-x-altquot': '«»‹›',
  385. # 'tr-x-altquot2': '“„‘‚', # [7] antiquated?
  386. 'uk': '«»„“',
  387. 'uk-x-altquot': '„“‚‘',
  388. 'zh-cn': '“”‘’',
  389. 'zh-tw': '「」『』',
  390. }
  391. def __init__(self, language='en'):
  392. self.language = language
  393. try:
  394. (self.opquote, self.cpquote,
  395. self.osquote, self.csquote) = self.quotes[language.lower()]
  396. except KeyError:
  397. self.opquote, self.cpquote, self.osquote, self.csquote = '""\'\''
  398. default_smartypants_attr = '1'
  399. def smartyPants(text, attr=default_smartypants_attr, language='en'):
  400. """Main function for "traditional" use."""
  401. return "".join(t for t in educate_tokens(tokenize(text), attr, language))
  402. def educate_tokens(text_tokens, attr=default_smartypants_attr, language='en'):
  403. """Return iterator that "educates" the items of `text_tokens`."""
  404. # Parse attributes:
  405. # 0 : do nothing
  406. # 1 : set all
  407. # 2 : set all, using old school en- and em- dash shortcuts
  408. # 3 : set all, using inverted old school en and em- dash shortcuts
  409. #
  410. # q : quotes
  411. # b : backtick quotes (``double'' only)
  412. # B : backtick quotes (``double'' and `single')
  413. # d : dashes
  414. # D : old school dashes
  415. # i : inverted old school dashes
  416. # e : ellipses
  417. # w : convert &quot; entities to " for Dreamweaver users
  418. convert_quot = False # translate &quot; entities into normal quotes?
  419. do_dashes = False
  420. do_backticks = False
  421. do_quotes = False
  422. do_ellipses = False
  423. do_stupefy = False
  424. # if attr == "0": # pass tokens unchanged (see below).
  425. if attr == '1': # Do everything, turn all options on.
  426. do_quotes = True
  427. do_backticks = True
  428. do_dashes = 1
  429. do_ellipses = True
  430. elif attr == '2':
  431. # Do everything, turn all options on, use old school dash shorthand.
  432. do_quotes = True
  433. do_backticks = True
  434. do_dashes = 2
  435. do_ellipses = True
  436. elif attr == '3':
  437. # Do everything, use inverted old school dash shorthand.
  438. do_quotes = True
  439. do_backticks = True
  440. do_dashes = 3
  441. do_ellipses = True
  442. elif attr == '-1': # Special "stupefy" mode.
  443. do_stupefy = True
  444. else:
  445. if 'q' in attr: do_quotes = True # noqa: E701
  446. if 'b' in attr: do_backticks = True # noqa: E701
  447. if 'B' in attr: do_backticks = 2 # noqa: E701
  448. if 'd' in attr: do_dashes = 1 # noqa: E701
  449. if 'D' in attr: do_dashes = 2 # noqa: E701
  450. if 'i' in attr: do_dashes = 3 # noqa: E701
  451. if 'e' in attr: do_ellipses = True # noqa: E701
  452. if 'w' in attr: convert_quot = True # noqa: E701
  453. prev_token_last_char = ' '
  454. # Last character of the previous text token. Used as
  455. # context to curl leading quote characters correctly.
  456. for (ttype, text) in text_tokens:
  457. # skip HTML and/or XML tags as well as empty text tokens
  458. # without updating the last character
  459. if ttype == 'tag' or not text:
  460. yield text
  461. continue
  462. # skip literal text (math, literal, raw, ...)
  463. if ttype == 'literal':
  464. prev_token_last_char = text[-1:]
  465. yield text
  466. continue
  467. last_char = text[-1:] # Remember last char before processing.
  468. text = processEscapes(text)
  469. if convert_quot:
  470. text = text.replace('&quot;', '"')
  471. if do_dashes == 1:
  472. text = educateDashes(text)
  473. elif do_dashes == 2:
  474. text = educateDashesOldSchool(text)
  475. elif do_dashes == 3:
  476. text = educateDashesOldSchoolInverted(text)
  477. if do_ellipses:
  478. text = educateEllipses(text)
  479. # Note: backticks need to be processed before quotes.
  480. if do_backticks:
  481. text = educateBackticks(text, language)
  482. if do_backticks == 2:
  483. text = educateSingleBackticks(text, language)
  484. if do_quotes:
  485. # Replace plain quotes in context to prevent conversion to
  486. # 2-character sequence in French.
  487. context = prev_token_last_char.replace('"', ';').replace("'", ';')
  488. text = educateQuotes(context+text, language)[1:]
  489. if do_stupefy:
  490. text = stupefyEntities(text, language)
  491. # Remember last char as context for the next token
  492. prev_token_last_char = last_char
  493. text = processEscapes(text, restore=True)
  494. yield text
  495. def educateQuotes(text, language='en'):
  496. """
  497. Parameter: - text string (unicode or bytes).
  498. - language (`BCP 47` language tag.)
  499. Returns: The `text`, with "educated" curly quote characters.
  500. Example input: "Isn't this fun?"
  501. Example output: “Isn’t this fun?“;
  502. """
  503. smart = smartchars(language)
  504. ch_classes = {'open': '[([{]', # opening braces
  505. 'close': r'[^\s]', # everything except whitespace
  506. 'punct': r"""[-!" #\$\%'()*+,.\/:;<=>?\@\[\\\]\^_`{|}~]""",
  507. 'dash': '[-–—]' # hyphen and em/en dashes
  508. r'|&[mn]dash;|&\#8211;|&\#8212;|&\#x201[34];',
  509. 'sep': '[\\s\u200B\u200C]|&nbsp;', # Whitespace, ZWSP, ZWNJ
  510. }
  511. # Special case if the very first character is a quote
  512. # followed by punctuation at a non-word-break. Use closing quotes.
  513. # TODO: example (when does this match?)
  514. text = re.sub(r"^'(?=%s\\B)" % ch_classes['punct'], smart.csquote, text)
  515. text = re.sub(r'^"(?=%s\\B)' % ch_classes['punct'], smart.cpquote, text)
  516. # Special case for adjacent quotes
  517. # like "'Quoted' words in a larger quote."
  518. text = re.sub('"\'(?=\\w)', smart.opquote+smart.osquote, text)
  519. text = re.sub('\'"(?=\\w)', smart.osquote+smart.opquote, text)
  520. # Special case: "opening character" followed by quote,
  521. # optional punctuation and space like "[", '(', or '-'.
  522. text = re.sub(r"(%(open)s|%(dash)s)'(?=%(punct)s? )" % ch_classes,
  523. r'\1%s'%smart.csquote, text)
  524. text = re.sub(r'(%(open)s|%(dash)s)"(?=%(punct)s? )' % ch_classes,
  525. r'\1%s'%smart.cpquote, text)
  526. # Special case for decade abbreviations (the '80s):
  527. if language.startswith('en'): # TODO similar cases in other languages?
  528. text = re.sub(r"'(?=\d{2}s)", smart.apostrophe, text)
  529. # Get most opening secondary quotes:
  530. opening_secondary_quotes_regex = re.compile("""
  531. (# ?<= # look behind fails: requires fixed-width pattern
  532. %(sep)s | # a whitespace char, or
  533. %(open)s | # opening brace, or
  534. %(dash)s # em/en-dash
  535. )
  536. ' # the quote
  537. (?=\\w|%(punct)s) # word character or punctuation
  538. """ % ch_classes, re.VERBOSE)
  539. text = opening_secondary_quotes_regex.sub(r'\1'+smart.osquote, text)
  540. # In many locales, secondary closing quotes are different from apostrophe:
  541. if smart.csquote != smart.apostrophe:
  542. apostrophe_regex = re.compile(r"(?<=(\w|\d))'(?=\w)")
  543. text = apostrophe_regex.sub(smart.apostrophe, text)
  544. # TODO: keep track of quoting level to recognize apostrophe in, e.g.,
  545. # "Ich fass' es nicht."
  546. closing_secondary_quotes_regex = re.compile(r"(?<!\s)'")
  547. text = closing_secondary_quotes_regex.sub(smart.csquote, text)
  548. # Any remaining secondary quotes should be opening ones:
  549. text = text.replace(r"'", smart.osquote)
  550. # Get most opening primary quotes:
  551. opening_primary_quotes_regex = re.compile("""
  552. (
  553. %(sep)s | # a whitespace char, or
  554. %(open)s | # zero width separating char, or
  555. %(dash)s # em/en-dash
  556. )
  557. " # the quote, followed by
  558. (?=\\w|%(punct)s) # a word character or punctuation
  559. """ % ch_classes, re.VERBOSE)
  560. text = opening_primary_quotes_regex.sub(r'\1'+smart.opquote, text)
  561. # primary closing quotes:
  562. closing_primary_quotes_regex = re.compile(r"""
  563. (
  564. (?<!\s)" | # no whitespace before
  565. "(?=\s) # whitespace behind
  566. )
  567. """, re.VERBOSE)
  568. text = closing_primary_quotes_regex.sub(smart.cpquote, text)
  569. # Any remaining quotes should be opening ones.
  570. text = text.replace(r'"', smart.opquote)
  571. return text
  572. def educateBackticks(text, language='en'):
  573. """
  574. Parameter: String (unicode or bytes).
  575. Returns: The `text`, with ``backticks'' -style double quotes
  576. translated into HTML curly quote entities.
  577. Example input: ``Isn't this fun?''
  578. Example output: “Isn't this fun?“;
  579. """
  580. smart = smartchars(language)
  581. text = text.replace(r'``', smart.opquote)
  582. text = text.replace(r"''", smart.cpquote)
  583. return text
  584. def educateSingleBackticks(text, language='en'):
  585. """
  586. Parameter: String (unicode or bytes).
  587. Returns: The `text`, with `backticks' -style single quotes
  588. translated into HTML curly quote entities.
  589. Example input: `Isn't this fun?'
  590. Example output: ‘Isn’t this fun?’
  591. """
  592. smart = smartchars(language)
  593. text = text.replace(r'`', smart.osquote)
  594. text = text.replace(r"'", smart.csquote)
  595. return text
  596. def educateDashes(text):
  597. """
  598. Parameter: String (unicode or bytes).
  599. Returns: The `text`, with each instance of "--" translated to
  600. an em-dash character.
  601. """
  602. text = text.replace(r'---', smartchars.endash) # en (yes, backwards)
  603. text = text.replace(r'--', smartchars.emdash) # em (yes, backwards)
  604. return text
  605. def educateDashesOldSchool(text):
  606. """
  607. Parameter: String (unicode or bytes).
  608. Returns: The `text`, with each instance of "--" translated to
  609. an en-dash character, and each "---" translated to
  610. an em-dash character.
  611. """
  612. text = text.replace(r'---', smartchars.emdash)
  613. text = text.replace(r'--', smartchars.endash)
  614. return text
  615. def educateDashesOldSchoolInverted(text):
  616. """
  617. Parameter: String (unicode or bytes).
  618. Returns: The `text`, with each instance of "--" translated to
  619. an em-dash character, and each "---" translated to
  620. an en-dash character. Two reasons why: First, unlike the
  621. en- and em-dash syntax supported by
  622. EducateDashesOldSchool(), it's compatible with existing
  623. entries written before SmartyPants 1.1, back when "--" was
  624. only used for em-dashes. Second, em-dashes are more
  625. common than en-dashes, and so it sort of makes sense that
  626. the shortcut should be shorter to type. (Thanks to Aaron
  627. Swartz for the idea.)
  628. """
  629. text = text.replace(r'---', smartchars.endash) # em
  630. text = text.replace(r'--', smartchars.emdash) # en
  631. return text
  632. def educateEllipses(text):
  633. """
  634. Parameter: String (unicode or bytes).
  635. Returns: The `text`, with each instance of "..." translated to
  636. an ellipsis character.
  637. Example input: Huh...?
  638. Example output: Huh&#8230;?
  639. """
  640. text = text.replace(r'...', smartchars.ellipsis)
  641. text = text.replace(r'. . .', smartchars.ellipsis)
  642. return text
  643. def stupefyEntities(text, language='en'):
  644. """
  645. Parameter: String (unicode or bytes).
  646. Returns: The `text`, with each SmartyPants character translated to
  647. its ASCII counterpart.
  648. Example input: “Hello — world.”
  649. Example output: "Hello -- world."
  650. """
  651. smart = smartchars(language)
  652. text = text.replace(smart.endash, "-")
  653. text = text.replace(smart.emdash, "--")
  654. text = text.replace(smart.osquote, "'") # open secondary quote
  655. text = text.replace(smart.csquote, "'") # close secondary quote
  656. text = text.replace(smart.opquote, '"') # open primary quote
  657. text = text.replace(smart.cpquote, '"') # close primary quote
  658. text = text.replace(smart.ellipsis, '...')
  659. return text
  660. def processEscapes(text, restore=False):
  661. r"""
  662. Parameter: String (unicode or bytes).
  663. Returns: The `text`, with after processing the following backslash
  664. escape sequences. This is useful if you want to force a "dumb"
  665. quote or other character to appear.
  666. Escape Value
  667. ------ -----
  668. \\ &#92;
  669. \" &#34;
  670. \' &#39;
  671. \. &#46;
  672. \- &#45;
  673. \` &#96;
  674. """
  675. replacements = ((r'\\', r'&#92;'),
  676. (r'\"', r'&#34;'),
  677. (r"\'", r'&#39;'),
  678. (r'\.', r'&#46;'),
  679. (r'\-', r'&#45;'),
  680. (r'\`', r'&#96;'))
  681. if restore:
  682. for (ch, rep) in replacements:
  683. text = text.replace(rep, ch[1])
  684. else:
  685. for (ch, rep) in replacements:
  686. text = text.replace(ch, rep)
  687. return text
  688. def tokenize(text):
  689. """
  690. Parameter: String containing HTML markup.
  691. Returns: An iterator that yields the tokens comprising the input
  692. string. Each token is either a tag (possibly with nested,
  693. tags contained therein, such as <a href="<MTFoo>">, or a
  694. run of text between tags. Each yielded element is a
  695. two-element tuple; the first is either 'tag' or 'text';
  696. the second is the actual value.
  697. Based on the _tokenize() subroutine from Brad Choate's MTRegex plugin.
  698. <http://www.bradchoate.com/past/mtregex.php>
  699. """
  700. tag_soup = re.compile(r'([^<]*)(<[^>]*>)')
  701. token_match = tag_soup.search(text)
  702. previous_end = 0
  703. while token_match is not None:
  704. if token_match.group(1):
  705. yield 'text', token_match.group(1)
  706. yield 'tag', token_match.group(2)
  707. previous_end = token_match.end()
  708. token_match = tag_soup.search(text, token_match.end())
  709. if previous_end < len(text):
  710. yield 'text', text[previous_end:]
  711. if __name__ == "__main__":
  712. import itertools
  713. import locale
  714. try:
  715. locale.setlocale(locale.LC_ALL, '') # set to user defaults
  716. defaultlanguage = locale.getdefaultlocale()[0]
  717. except: # noqa catchall
  718. defaultlanguage = 'en'
  719. # Normalize and drop unsupported subtags:
  720. defaultlanguage = defaultlanguage.lower().replace('-', '_')
  721. # split (except singletons, which mark the following tag as non-standard):
  722. defaultlanguage = re.sub(r'_([a-zA-Z0-9])_', r'_\1-', defaultlanguage)
  723. _subtags = [subtag for subtag in defaultlanguage.split('_')]
  724. _basetag = _subtags.pop(0)
  725. # find all combinations of subtags
  726. for n in range(len(_subtags), 0, -1):
  727. for tags in itertools.combinations(_subtags, n):
  728. _tag = '-'.join((_basetag, *tags))
  729. if _tag in smartchars.quotes:
  730. defaultlanguage = _tag
  731. break
  732. else:
  733. if _basetag in smartchars.quotes:
  734. defaultlanguage = _basetag
  735. else:
  736. defaultlanguage = 'en'
  737. import argparse
  738. parser = argparse.ArgumentParser(
  739. description='Filter <input> making ASCII punctuation "smart".')
  740. # TODO: require input arg or other means to print USAGE instead of waiting.
  741. # parser.add_argument("input", help="Input stream, use '-' for stdin.")
  742. parser.add_argument("-a", "--action", default="1",
  743. help="what to do with the input (see --actionhelp)")
  744. parser.add_argument("-e", "--encoding", default="utf-8",
  745. help="text encoding")
  746. parser.add_argument("-l", "--language", default=defaultlanguage,
  747. help="text language (BCP47 tag), "
  748. f"Default: {defaultlanguage}")
  749. parser.add_argument("-q", "--alternative-quotes", action="store_true",
  750. help="use alternative quote style")
  751. parser.add_argument("--doc", action="store_true",
  752. help="print documentation")
  753. parser.add_argument("--actionhelp", action="store_true",
  754. help="list available actions")
  755. parser.add_argument("--stylehelp", action="store_true",
  756. help="list available quote styles")
  757. parser.add_argument("--test", action="store_true",
  758. help="perform short self-test")
  759. args = parser.parse_args()
  760. if args.doc:
  761. print(__doc__)
  762. elif args.actionhelp:
  763. print(options)
  764. elif args.stylehelp:
  765. print()
  766. print("Available styles (primary open/close, secondary open/close)")
  767. print("language tag quotes")
  768. print("============ ======")
  769. for key in sorted(smartchars.quotes.keys()):
  770. print("%-14s %s" % (key, smartchars.quotes[key]))
  771. elif args.test:
  772. # Unit test output goes to stderr.
  773. import unittest
  774. class TestSmartypantsAllAttributes(unittest.TestCase):
  775. # the default attribute is "1", which means "all".
  776. def test_dates(self):
  777. self.assertEqual(smartyPants("1440-80's"), "1440-80’s")
  778. self.assertEqual(smartyPants("1440-'80s"), "1440-’80s")
  779. self.assertEqual(smartyPants("1440---'80s"), "1440–’80s")
  780. self.assertEqual(smartyPants("1960's"), "1960’s")
  781. self.assertEqual(smartyPants("one two '60s"), "one two ’60s")
  782. self.assertEqual(smartyPants("'60s"), "’60s")
  783. def test_educated_quotes(self):
  784. self.assertEqual(smartyPants('"Isn\'t this fun?"'),
  785. '“Isn’t this fun?”')
  786. def test_html_tags(self):
  787. text = '<a src="foo">more</a>'
  788. self.assertEqual(smartyPants(text), text)
  789. suite = unittest.TestLoader().loadTestsFromTestCase(
  790. TestSmartypantsAllAttributes)
  791. unittest.TextTestRunner().run(suite)
  792. else:
  793. if args.alternative_quotes:
  794. if '-x-altquot' in args.language:
  795. args.language = args.language.replace('-x-altquot', '')
  796. else:
  797. args.language += '-x-altquot'
  798. text = sys.stdin.read()
  799. print(smartyPants(text, attr=args.action, language=args.language))