pretty_symbology.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. """Symbolic primitives + unicode/ASCII abstraction for pretty.py"""
  2. import sys
  3. import warnings
  4. from string import ascii_lowercase, ascii_uppercase
  5. import unicodedata
  6. unicode_warnings = ''
  7. def U(name):
  8. """
  9. Get a unicode character by name or, None if not found.
  10. This exists because older versions of Python use older unicode databases.
  11. """
  12. try:
  13. return unicodedata.lookup(name)
  14. except KeyError:
  15. global unicode_warnings
  16. unicode_warnings += 'No \'%s\' in unicodedata\n' % name
  17. return None
  18. from sympy.printing.conventions import split_super_sub
  19. from sympy.core.alphabets import greeks
  20. from sympy.utilities.exceptions import sympy_deprecation_warning
  21. # prefix conventions when constructing tables
  22. # L - LATIN i
  23. # G - GREEK beta
  24. # D - DIGIT 0
  25. # S - SYMBOL +
  26. __all__ = ['greek_unicode', 'sub', 'sup', 'xsym', 'vobj', 'hobj', 'pretty_symbol',
  27. 'annotated']
  28. _use_unicode = False
  29. def pretty_use_unicode(flag=None):
  30. """Set whether pretty-printer should use unicode by default"""
  31. global _use_unicode
  32. global unicode_warnings
  33. if flag is None:
  34. return _use_unicode
  35. if flag and unicode_warnings:
  36. # print warnings (if any) on first unicode usage
  37. warnings.warn(unicode_warnings)
  38. unicode_warnings = ''
  39. use_unicode_prev = _use_unicode
  40. _use_unicode = flag
  41. return use_unicode_prev
  42. def pretty_try_use_unicode():
  43. """See if unicode output is available and leverage it if possible"""
  44. encoding = getattr(sys.stdout, 'encoding', None)
  45. # this happens when e.g. stdout is redirected through a pipe, or is
  46. # e.g. a cStringIO.StringO
  47. if encoding is None:
  48. return # sys.stdout has no encoding
  49. symbols = []
  50. # see if we can represent greek alphabet
  51. symbols += greek_unicode.values()
  52. # and atoms
  53. symbols += atoms_table.values()
  54. for s in symbols:
  55. if s is None:
  56. return # common symbols not present!
  57. try:
  58. s.encode(encoding)
  59. except UnicodeEncodeError:
  60. return
  61. # all the characters were present and encodable
  62. pretty_use_unicode(True)
  63. def xstr(*args):
  64. sympy_deprecation_warning(
  65. """
  66. The sympy.printing.pretty.pretty_symbology.xstr() function is
  67. deprecated. Use str() instead.
  68. """,
  69. deprecated_since_version="1.7",
  70. active_deprecations_target="deprecated-pretty-printing-functions"
  71. )
  72. return str(*args)
  73. # GREEK
  74. g = lambda l: U('GREEK SMALL LETTER %s' % l.upper())
  75. G = lambda l: U('GREEK CAPITAL LETTER %s' % l.upper())
  76. greek_letters = list(greeks) # make a copy
  77. # deal with Unicode's funny spelling of lambda
  78. greek_letters[greek_letters.index('lambda')] = 'lamda'
  79. # {} greek letter -> (g,G)
  80. greek_unicode = {L: g(L) for L in greek_letters}
  81. greek_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_letters)
  82. # aliases
  83. greek_unicode['lambda'] = greek_unicode['lamda']
  84. greek_unicode['Lambda'] = greek_unicode['Lamda']
  85. greek_unicode['varsigma'] = '\N{GREEK SMALL LETTER FINAL SIGMA}'
  86. # BOLD
  87. b = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper())
  88. B = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper())
  89. bold_unicode = {l: b(l) for l in ascii_lowercase}
  90. bold_unicode.update((L, B(L)) for L in ascii_uppercase)
  91. # GREEK BOLD
  92. gb = lambda l: U('MATHEMATICAL BOLD SMALL %s' % l.upper())
  93. GB = lambda l: U('MATHEMATICAL BOLD CAPITAL %s' % l.upper())
  94. greek_bold_letters = list(greeks) # make a copy, not strictly required here
  95. # deal with Unicode's funny spelling of lambda
  96. greek_bold_letters[greek_bold_letters.index('lambda')] = 'lamda'
  97. # {} greek letter -> (g,G)
  98. greek_bold_unicode = {L: g(L) for L in greek_bold_letters}
  99. greek_bold_unicode.update((L[0].upper() + L[1:], G(L)) for L in greek_bold_letters)
  100. greek_bold_unicode['lambda'] = greek_unicode['lamda']
  101. greek_bold_unicode['Lambda'] = greek_unicode['Lamda']
  102. greek_bold_unicode['varsigma'] = '\N{MATHEMATICAL BOLD SMALL FINAL SIGMA}'
  103. digit_2txt = {
  104. '0': 'ZERO',
  105. '1': 'ONE',
  106. '2': 'TWO',
  107. '3': 'THREE',
  108. '4': 'FOUR',
  109. '5': 'FIVE',
  110. '6': 'SIX',
  111. '7': 'SEVEN',
  112. '8': 'EIGHT',
  113. '9': 'NINE',
  114. }
  115. symb_2txt = {
  116. '+': 'PLUS SIGN',
  117. '-': 'MINUS',
  118. '=': 'EQUALS SIGN',
  119. '(': 'LEFT PARENTHESIS',
  120. ')': 'RIGHT PARENTHESIS',
  121. '[': 'LEFT SQUARE BRACKET',
  122. ']': 'RIGHT SQUARE BRACKET',
  123. '{': 'LEFT CURLY BRACKET',
  124. '}': 'RIGHT CURLY BRACKET',
  125. # non-std
  126. '{}': 'CURLY BRACKET',
  127. 'sum': 'SUMMATION',
  128. 'int': 'INTEGRAL',
  129. }
  130. # SUBSCRIPT & SUPERSCRIPT
  131. LSUB = lambda letter: U('LATIN SUBSCRIPT SMALL LETTER %s' % letter.upper())
  132. GSUB = lambda letter: U('GREEK SUBSCRIPT SMALL LETTER %s' % letter.upper())
  133. DSUB = lambda digit: U('SUBSCRIPT %s' % digit_2txt[digit])
  134. SSUB = lambda symb: U('SUBSCRIPT %s' % symb_2txt[symb])
  135. LSUP = lambda letter: U('SUPERSCRIPT LATIN SMALL LETTER %s' % letter.upper())
  136. DSUP = lambda digit: U('SUPERSCRIPT %s' % digit_2txt[digit])
  137. SSUP = lambda symb: U('SUPERSCRIPT %s' % symb_2txt[symb])
  138. sub = {} # symb -> subscript symbol
  139. sup = {} # symb -> superscript symbol
  140. # latin subscripts
  141. for l in 'aeioruvxhklmnpst':
  142. sub[l] = LSUB(l)
  143. for l in 'in':
  144. sup[l] = LSUP(l)
  145. for gl in ['beta', 'gamma', 'rho', 'phi', 'chi']:
  146. sub[gl] = GSUB(gl)
  147. for d in [str(i) for i in range(10)]:
  148. sub[d] = DSUB(d)
  149. sup[d] = DSUP(d)
  150. for s in '+-=()':
  151. sub[s] = SSUB(s)
  152. sup[s] = SSUP(s)
  153. # Variable modifiers
  154. # TODO: Make brackets adjust to height of contents
  155. modifier_dict = {
  156. # Accents
  157. 'mathring': lambda s: center_accent(s, '\N{COMBINING RING ABOVE}'),
  158. 'ddddot': lambda s: center_accent(s, '\N{COMBINING FOUR DOTS ABOVE}'),
  159. 'dddot': lambda s: center_accent(s, '\N{COMBINING THREE DOTS ABOVE}'),
  160. 'ddot': lambda s: center_accent(s, '\N{COMBINING DIAERESIS}'),
  161. 'dot': lambda s: center_accent(s, '\N{COMBINING DOT ABOVE}'),
  162. 'check': lambda s: center_accent(s, '\N{COMBINING CARON}'),
  163. 'breve': lambda s: center_accent(s, '\N{COMBINING BREVE}'),
  164. 'acute': lambda s: center_accent(s, '\N{COMBINING ACUTE ACCENT}'),
  165. 'grave': lambda s: center_accent(s, '\N{COMBINING GRAVE ACCENT}'),
  166. 'tilde': lambda s: center_accent(s, '\N{COMBINING TILDE}'),
  167. 'hat': lambda s: center_accent(s, '\N{COMBINING CIRCUMFLEX ACCENT}'),
  168. 'bar': lambda s: center_accent(s, '\N{COMBINING OVERLINE}'),
  169. 'vec': lambda s: center_accent(s, '\N{COMBINING RIGHT ARROW ABOVE}'),
  170. 'prime': lambda s: s+'\N{PRIME}',
  171. 'prm': lambda s: s+'\N{PRIME}',
  172. # # Faces -- these are here for some compatibility with latex printing
  173. # 'bold': lambda s: s,
  174. # 'bm': lambda s: s,
  175. # 'cal': lambda s: s,
  176. # 'scr': lambda s: s,
  177. # 'frak': lambda s: s,
  178. # Brackets
  179. 'norm': lambda s: '\N{DOUBLE VERTICAL LINE}'+s+'\N{DOUBLE VERTICAL LINE}',
  180. 'avg': lambda s: '\N{MATHEMATICAL LEFT ANGLE BRACKET}'+s+'\N{MATHEMATICAL RIGHT ANGLE BRACKET}',
  181. 'abs': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}',
  182. 'mag': lambda s: '\N{VERTICAL LINE}'+s+'\N{VERTICAL LINE}',
  183. }
  184. # VERTICAL OBJECTS
  185. HUP = lambda symb: U('%s UPPER HOOK' % symb_2txt[symb])
  186. CUP = lambda symb: U('%s UPPER CORNER' % symb_2txt[symb])
  187. MID = lambda symb: U('%s MIDDLE PIECE' % symb_2txt[symb])
  188. EXT = lambda symb: U('%s EXTENSION' % symb_2txt[symb])
  189. HLO = lambda symb: U('%s LOWER HOOK' % symb_2txt[symb])
  190. CLO = lambda symb: U('%s LOWER CORNER' % symb_2txt[symb])
  191. TOP = lambda symb: U('%s TOP' % symb_2txt[symb])
  192. BOT = lambda symb: U('%s BOTTOM' % symb_2txt[symb])
  193. # {} '(' -> (extension, start, end, middle) 1-character
  194. _xobj_unicode = {
  195. # vertical symbols
  196. # (( ext, top, bot, mid ), c1)
  197. '(': (( EXT('('), HUP('('), HLO('(') ), '('),
  198. ')': (( EXT(')'), HUP(')'), HLO(')') ), ')'),
  199. '[': (( EXT('['), CUP('['), CLO('[') ), '['),
  200. ']': (( EXT(']'), CUP(']'), CLO(']') ), ']'),
  201. '{': (( EXT('{}'), HUP('{'), HLO('{'), MID('{') ), '{'),
  202. '}': (( EXT('{}'), HUP('}'), HLO('}'), MID('}') ), '}'),
  203. '|': U('BOX DRAWINGS LIGHT VERTICAL'),
  204. '<': ((U('BOX DRAWINGS LIGHT VERTICAL'),
  205. U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'),
  206. U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT')), '<'),
  207. '>': ((U('BOX DRAWINGS LIGHT VERTICAL'),
  208. U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'),
  209. U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), '>'),
  210. 'lfloor': (( EXT('['), EXT('['), CLO('[') ), U('LEFT FLOOR')),
  211. 'rfloor': (( EXT(']'), EXT(']'), CLO(']') ), U('RIGHT FLOOR')),
  212. 'lceil': (( EXT('['), CUP('['), EXT('[') ), U('LEFT CEILING')),
  213. 'rceil': (( EXT(']'), CUP(']'), EXT(']') ), U('RIGHT CEILING')),
  214. 'int': (( EXT('int'), U('TOP HALF INTEGRAL'), U('BOTTOM HALF INTEGRAL') ), U('INTEGRAL')),
  215. 'sum': (( U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'), '_', U('OVERLINE'), U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT')), U('N-ARY SUMMATION')),
  216. # horizontal objects
  217. #'-': '-',
  218. '-': U('BOX DRAWINGS LIGHT HORIZONTAL'),
  219. '_': U('LOW LINE'),
  220. # We used to use this, but LOW LINE looks better for roots, as it's a
  221. # little lower (i.e., it lines up with the / perfectly. But perhaps this
  222. # one would still be wanted for some cases?
  223. # '_': U('HORIZONTAL SCAN LINE-9'),
  224. # diagonal objects '\' & '/' ?
  225. '/': U('BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT'),
  226. '\\': U('BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT'),
  227. }
  228. _xobj_ascii = {
  229. # vertical symbols
  230. # (( ext, top, bot, mid ), c1)
  231. '(': (( '|', '/', '\\' ), '('),
  232. ')': (( '|', '\\', '/' ), ')'),
  233. # XXX this looks ugly
  234. # '[': (( '|', '-', '-' ), '['),
  235. # ']': (( '|', '-', '-' ), ']'),
  236. # XXX not so ugly :(
  237. '[': (( '[', '[', '[' ), '['),
  238. ']': (( ']', ']', ']' ), ']'),
  239. '{': (( '|', '/', '\\', '<' ), '{'),
  240. '}': (( '|', '\\', '/', '>' ), '}'),
  241. '|': '|',
  242. '<': (( '|', '/', '\\' ), '<'),
  243. '>': (( '|', '\\', '/' ), '>'),
  244. 'int': ( ' | ', ' /', '/ ' ),
  245. # horizontal objects
  246. '-': '-',
  247. '_': '_',
  248. # diagonal objects '\' & '/' ?
  249. '/': '/',
  250. '\\': '\\',
  251. }
  252. def xobj(symb, length):
  253. """Construct spatial object of given length.
  254. return: [] of equal-length strings
  255. """
  256. if length <= 0:
  257. raise ValueError("Length should be greater than 0")
  258. # TODO robustify when no unicodedat available
  259. if _use_unicode:
  260. _xobj = _xobj_unicode
  261. else:
  262. _xobj = _xobj_ascii
  263. vinfo = _xobj[symb]
  264. c1 = top = bot = mid = None
  265. if not isinstance(vinfo, tuple): # 1 entry
  266. ext = vinfo
  267. else:
  268. if isinstance(vinfo[0], tuple): # (vlong), c1
  269. vlong = vinfo[0]
  270. c1 = vinfo[1]
  271. else: # (vlong), c1
  272. vlong = vinfo
  273. ext = vlong[0]
  274. try:
  275. top = vlong[1]
  276. bot = vlong[2]
  277. mid = vlong[3]
  278. except IndexError:
  279. pass
  280. if c1 is None:
  281. c1 = ext
  282. if top is None:
  283. top = ext
  284. if bot is None:
  285. bot = ext
  286. if mid is not None:
  287. if (length % 2) == 0:
  288. # even height, but we have to print it somehow anyway...
  289. # XXX is it ok?
  290. length += 1
  291. else:
  292. mid = ext
  293. if length == 1:
  294. return c1
  295. res = []
  296. next = (length - 2)//2
  297. nmid = (length - 2) - next*2
  298. res += [top]
  299. res += [ext]*next
  300. res += [mid]*nmid
  301. res += [ext]*next
  302. res += [bot]
  303. return res
  304. def vobj(symb, height):
  305. """Construct vertical object of a given height
  306. see: xobj
  307. """
  308. return '\n'.join( xobj(symb, height) )
  309. def hobj(symb, width):
  310. """Construct horizontal object of a given width
  311. see: xobj
  312. """
  313. return ''.join( xobj(symb, width) )
  314. # RADICAL
  315. # n -> symbol
  316. root = {
  317. 2: U('SQUARE ROOT'), # U('RADICAL SYMBOL BOTTOM')
  318. 3: U('CUBE ROOT'),
  319. 4: U('FOURTH ROOT'),
  320. }
  321. # RATIONAL
  322. VF = lambda txt: U('VULGAR FRACTION %s' % txt)
  323. # (p,q) -> symbol
  324. frac = {
  325. (1, 2): VF('ONE HALF'),
  326. (1, 3): VF('ONE THIRD'),
  327. (2, 3): VF('TWO THIRDS'),
  328. (1, 4): VF('ONE QUARTER'),
  329. (3, 4): VF('THREE QUARTERS'),
  330. (1, 5): VF('ONE FIFTH'),
  331. (2, 5): VF('TWO FIFTHS'),
  332. (3, 5): VF('THREE FIFTHS'),
  333. (4, 5): VF('FOUR FIFTHS'),
  334. (1, 6): VF('ONE SIXTH'),
  335. (5, 6): VF('FIVE SIXTHS'),
  336. (1, 8): VF('ONE EIGHTH'),
  337. (3, 8): VF('THREE EIGHTHS'),
  338. (5, 8): VF('FIVE EIGHTHS'),
  339. (7, 8): VF('SEVEN EIGHTHS'),
  340. }
  341. # atom symbols
  342. _xsym = {
  343. '==': ('=', '='),
  344. '<': ('<', '<'),
  345. '>': ('>', '>'),
  346. '<=': ('<=', U('LESS-THAN OR EQUAL TO')),
  347. '>=': ('>=', U('GREATER-THAN OR EQUAL TO')),
  348. '!=': ('!=', U('NOT EQUAL TO')),
  349. ':=': (':=', ':='),
  350. '+=': ('+=', '+='),
  351. '-=': ('-=', '-='),
  352. '*=': ('*=', '*='),
  353. '/=': ('/=', '/='),
  354. '%=': ('%=', '%='),
  355. '*': ('*', U('DOT OPERATOR')),
  356. '-->': ('-->', U('EM DASH') + U('EM DASH') +
  357. U('BLACK RIGHT-POINTING TRIANGLE') if U('EM DASH')
  358. and U('BLACK RIGHT-POINTING TRIANGLE') else None),
  359. '==>': ('==>', U('BOX DRAWINGS DOUBLE HORIZONTAL') +
  360. U('BOX DRAWINGS DOUBLE HORIZONTAL') +
  361. U('BLACK RIGHT-POINTING TRIANGLE') if
  362. U('BOX DRAWINGS DOUBLE HORIZONTAL') and
  363. U('BOX DRAWINGS DOUBLE HORIZONTAL') and
  364. U('BLACK RIGHT-POINTING TRIANGLE') else None),
  365. '.': ('*', U('RING OPERATOR')),
  366. }
  367. def xsym(sym):
  368. """get symbology for a 'character'"""
  369. op = _xsym[sym]
  370. if _use_unicode:
  371. return op[1]
  372. else:
  373. return op[0]
  374. # SYMBOLS
  375. atoms_table = {
  376. # class how-to-display
  377. 'Exp1': U('SCRIPT SMALL E'),
  378. 'Pi': U('GREEK SMALL LETTER PI'),
  379. 'Infinity': U('INFINITY'),
  380. 'NegativeInfinity': U('INFINITY') and ('-' + U('INFINITY')), # XXX what to do here
  381. #'ImaginaryUnit': U('GREEK SMALL LETTER IOTA'),
  382. #'ImaginaryUnit': U('MATHEMATICAL ITALIC SMALL I'),
  383. 'ImaginaryUnit': U('DOUBLE-STRUCK ITALIC SMALL I'),
  384. 'EmptySet': U('EMPTY SET'),
  385. 'Naturals': U('DOUBLE-STRUCK CAPITAL N'),
  386. 'Naturals0': (U('DOUBLE-STRUCK CAPITAL N') and
  387. (U('DOUBLE-STRUCK CAPITAL N') +
  388. U('SUBSCRIPT ZERO'))),
  389. 'Integers': U('DOUBLE-STRUCK CAPITAL Z'),
  390. 'Rationals': U('DOUBLE-STRUCK CAPITAL Q'),
  391. 'Reals': U('DOUBLE-STRUCK CAPITAL R'),
  392. 'Complexes': U('DOUBLE-STRUCK CAPITAL C'),
  393. 'Union': U('UNION'),
  394. 'SymmetricDifference': U('INCREMENT'),
  395. 'Intersection': U('INTERSECTION'),
  396. 'Ring': U('RING OPERATOR'),
  397. 'Modifier Letter Low Ring':U('Modifier Letter Low Ring'),
  398. 'EmptySequence': 'EmptySequence',
  399. }
  400. def pretty_atom(atom_name, default=None, printer=None):
  401. """return pretty representation of an atom"""
  402. if _use_unicode:
  403. if printer is not None and atom_name == 'ImaginaryUnit' and printer._settings['imaginary_unit'] == 'j':
  404. return U('DOUBLE-STRUCK ITALIC SMALL J')
  405. else:
  406. return atoms_table[atom_name]
  407. else:
  408. if default is not None:
  409. return default
  410. raise KeyError('only unicode') # send it default printer
  411. def pretty_symbol(symb_name, bold_name=False):
  412. """return pretty representation of a symbol"""
  413. # let's split symb_name into symbol + index
  414. # UC: beta1
  415. # UC: f_beta
  416. if not _use_unicode:
  417. return symb_name
  418. name, sups, subs = split_super_sub(symb_name)
  419. def translate(s, bold_name) :
  420. if bold_name:
  421. gG = greek_bold_unicode.get(s)
  422. else:
  423. gG = greek_unicode.get(s)
  424. if gG is not None:
  425. return gG
  426. for key in sorted(modifier_dict.keys(), key=lambda k:len(k), reverse=True) :
  427. if s.lower().endswith(key) and len(s)>len(key):
  428. return modifier_dict[key](translate(s[:-len(key)], bold_name))
  429. if bold_name:
  430. return ''.join([bold_unicode[c] for c in s])
  431. return s
  432. name = translate(name, bold_name)
  433. # Let's prettify sups/subs. If it fails at one of them, pretty sups/subs are
  434. # not used at all.
  435. def pretty_list(l, mapping):
  436. result = []
  437. for s in l:
  438. pretty = mapping.get(s)
  439. if pretty is None:
  440. try: # match by separate characters
  441. pretty = ''.join([mapping[c] for c in s])
  442. except (TypeError, KeyError):
  443. return None
  444. result.append(pretty)
  445. return result
  446. pretty_sups = pretty_list(sups, sup)
  447. if pretty_sups is not None:
  448. pretty_subs = pretty_list(subs, sub)
  449. else:
  450. pretty_subs = None
  451. # glue the results into one string
  452. if pretty_subs is None: # nice formatting of sups/subs did not work
  453. if subs:
  454. name += '_'+'_'.join([translate(s, bold_name) for s in subs])
  455. if sups:
  456. name += '__'+'__'.join([translate(s, bold_name) for s in sups])
  457. return name
  458. else:
  459. sups_result = ' '.join(pretty_sups)
  460. subs_result = ' '.join(pretty_subs)
  461. return ''.join([name, sups_result, subs_result])
  462. def annotated(letter):
  463. """
  464. Return a stylised drawing of the letter ``letter``, together with
  465. information on how to put annotations (super- and subscripts to the
  466. left and to the right) on it.
  467. See pretty.py functions _print_meijerg, _print_hyper on how to use this
  468. information.
  469. """
  470. ucode_pics = {
  471. 'F': (2, 0, 2, 0, '\N{BOX DRAWINGS LIGHT DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
  472. '\N{BOX DRAWINGS LIGHT VERTICAL AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\n'
  473. '\N{BOX DRAWINGS LIGHT UP}'),
  474. 'G': (3, 0, 3, 1, '\N{BOX DRAWINGS LIGHT ARC DOWN AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC DOWN AND LEFT}\n'
  475. '\N{BOX DRAWINGS LIGHT VERTICAL}\N{BOX DRAWINGS LIGHT RIGHT}\N{BOX DRAWINGS LIGHT DOWN AND LEFT}\n'
  476. '\N{BOX DRAWINGS LIGHT ARC UP AND RIGHT}\N{BOX DRAWINGS LIGHT HORIZONTAL}\N{BOX DRAWINGS LIGHT ARC UP AND LEFT}')
  477. }
  478. ascii_pics = {
  479. 'F': (3, 0, 3, 0, ' _\n|_\n|\n'),
  480. 'G': (3, 0, 3, 1, ' __\n/__\n\\_|')
  481. }
  482. if _use_unicode:
  483. return ucode_pics[letter]
  484. else:
  485. return ascii_pics[letter]
  486. _remove_combining = dict.fromkeys(list(range(ord('\N{COMBINING GRAVE ACCENT}'), ord('\N{COMBINING LATIN SMALL LETTER X}')))
  487. + list(range(ord('\N{COMBINING LEFT HARPOON ABOVE}'), ord('\N{COMBINING ASTERISK ABOVE}'))))
  488. def is_combining(sym):
  489. """Check whether symbol is a unicode modifier. """
  490. return ord(sym) in _remove_combining
  491. def center_accent(string, accent):
  492. """
  493. Returns a string with accent inserted on the middle character. Useful to
  494. put combining accents on symbol names, including multi-character names.
  495. Parameters
  496. ==========
  497. string : string
  498. The string to place the accent in.
  499. accent : string
  500. The combining accent to insert
  501. References
  502. ==========
  503. .. [1] https://en.wikipedia.org/wiki/Combining_character
  504. .. [2] https://en.wikipedia.org/wiki/Combining_Diacritical_Marks
  505. """
  506. # Accent is placed on the previous character, although it may not always look
  507. # like that depending on console
  508. midpoint = len(string) // 2 + 1
  509. firstpart = string[:midpoint]
  510. secondpart = string[midpoint:]
  511. return firstpart + accent + secondpart
  512. def line_width(line):
  513. """Unicode combining symbols (modifiers) are not ever displayed as
  514. separate symbols and thus should not be counted
  515. """
  516. return len(line.translate(_remove_combining))