stringpict.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. """Prettyprinter by Jurjen Bos.
  2. (I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay).
  3. All objects have a method that create a "stringPict",
  4. that can be used in the str method for pretty printing.
  5. Updates by Jason Gedge (email <my last name> at cs mun ca)
  6. - terminal_string() method
  7. - minor fixes and changes (mostly to prettyForm)
  8. TODO:
  9. - Allow left/center/right alignment options for above/below and
  10. top/center/bottom alignment options for left/right
  11. """
  12. import shutil
  13. from .pretty_symbology import hobj, vobj, xsym, xobj, pretty_use_unicode, line_width, center
  14. from sympy.utilities.exceptions import sympy_deprecation_warning
  15. _GLOBAL_WRAP_LINE = None
  16. class stringPict:
  17. """An ASCII picture.
  18. The pictures are represented as a list of equal length strings.
  19. """
  20. #special value for stringPict.below
  21. LINE = 'line'
  22. def __init__(self, s, baseline=0):
  23. """Initialize from string.
  24. Multiline strings are centered.
  25. """
  26. self.s = s
  27. #picture is a string that just can be printed
  28. self.picture = stringPict.equalLengths(s.splitlines())
  29. #baseline is the line number of the "base line"
  30. self.baseline = baseline
  31. self.binding = None
  32. @staticmethod
  33. def equalLengths(lines):
  34. # empty lines
  35. if not lines:
  36. return ['']
  37. width = max(line_width(line) for line in lines)
  38. return [center(line, width) for line in lines]
  39. def height(self):
  40. """The height of the picture in characters."""
  41. return len(self.picture)
  42. def width(self):
  43. """The width of the picture in characters."""
  44. return line_width(self.picture[0])
  45. @staticmethod
  46. def next(*args):
  47. """Put a string of stringPicts next to each other.
  48. Returns string, baseline arguments for stringPict.
  49. """
  50. #convert everything to stringPicts
  51. objects = []
  52. for arg in args:
  53. if isinstance(arg, str):
  54. arg = stringPict(arg)
  55. objects.append(arg)
  56. #make a list of pictures, with equal height and baseline
  57. newBaseline = max(obj.baseline for obj in objects)
  58. newHeightBelowBaseline = max(
  59. obj.height() - obj.baseline
  60. for obj in objects)
  61. newHeight = newBaseline + newHeightBelowBaseline
  62. pictures = []
  63. for obj in objects:
  64. oneEmptyLine = [' '*obj.width()]
  65. basePadding = newBaseline - obj.baseline
  66. totalPadding = newHeight - obj.height()
  67. pictures.append(
  68. oneEmptyLine * basePadding +
  69. obj.picture +
  70. oneEmptyLine * (totalPadding - basePadding))
  71. result = [''.join(lines) for lines in zip(*pictures)]
  72. return '\n'.join(result), newBaseline
  73. def right(self, *args):
  74. r"""Put pictures next to this one.
  75. Returns string, baseline arguments for stringPict.
  76. (Multiline) strings are allowed, and are given a baseline of 0.
  77. Examples
  78. ========
  79. >>> from sympy.printing.pretty.stringpict import stringPict
  80. >>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0])
  81. 1
  82. 10 + -
  83. 2
  84. """
  85. return stringPict.next(self, *args)
  86. def left(self, *args):
  87. """Put pictures (left to right) at left.
  88. Returns string, baseline arguments for stringPict.
  89. """
  90. return stringPict.next(*(args + (self,)))
  91. @staticmethod
  92. def stack(*args):
  93. """Put pictures on top of each other,
  94. from top to bottom.
  95. Returns string, baseline arguments for stringPict.
  96. The baseline is the baseline of the second picture.
  97. Everything is centered.
  98. Baseline is the baseline of the second picture.
  99. Strings are allowed.
  100. The special value stringPict.LINE is a row of '-' extended to the width.
  101. """
  102. #convert everything to stringPicts; keep LINE
  103. objects = []
  104. for arg in args:
  105. if arg is not stringPict.LINE and isinstance(arg, str):
  106. arg = stringPict(arg)
  107. objects.append(arg)
  108. #compute new width
  109. newWidth = max(
  110. obj.width()
  111. for obj in objects
  112. if obj is not stringPict.LINE)
  113. lineObj = stringPict(hobj('-', newWidth))
  114. #replace LINE with proper lines
  115. for i, obj in enumerate(objects):
  116. if obj is stringPict.LINE:
  117. objects[i] = lineObj
  118. #stack the pictures, and center the result
  119. newPicture = [center(line, newWidth) for obj in objects for line in obj.picture]
  120. newBaseline = objects[0].height() + objects[1].baseline
  121. return '\n'.join(newPicture), newBaseline
  122. def below(self, *args):
  123. """Put pictures under this picture.
  124. Returns string, baseline arguments for stringPict.
  125. Baseline is baseline of top picture
  126. Examples
  127. ========
  128. >>> from sympy.printing.pretty.stringpict import stringPict
  129. >>> print(stringPict("x+3").below(
  130. ... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE
  131. x+3
  132. ---
  133. 3
  134. """
  135. s, baseline = stringPict.stack(self, *args)
  136. return s, self.baseline
  137. def above(self, *args):
  138. """Put pictures above this picture.
  139. Returns string, baseline arguments for stringPict.
  140. Baseline is baseline of bottom picture.
  141. """
  142. string, baseline = stringPict.stack(*(args + (self,)))
  143. baseline = len(string.splitlines()) - self.height() + self.baseline
  144. return string, baseline
  145. def parens(self, left='(', right=')', ifascii_nougly=False):
  146. """Put parentheses around self.
  147. Returns string, baseline arguments for stringPict.
  148. left or right can be None or empty string which means 'no paren from
  149. that side'
  150. """
  151. h = self.height()
  152. b = self.baseline
  153. # XXX this is a hack -- ascii parens are ugly!
  154. if ifascii_nougly and not pretty_use_unicode():
  155. h = 1
  156. b = 0
  157. res = self
  158. if left:
  159. lparen = stringPict(vobj(left, h), baseline=b)
  160. res = stringPict(*lparen.right(self))
  161. if right:
  162. rparen = stringPict(vobj(right, h), baseline=b)
  163. res = stringPict(*res.right(rparen))
  164. return ('\n'.join(res.picture), res.baseline)
  165. def leftslash(self):
  166. """Precede object by a slash of the proper size.
  167. """
  168. # XXX not used anywhere ?
  169. height = max(
  170. self.baseline,
  171. self.height() - 1 - self.baseline)*2 + 1
  172. slash = '\n'.join(
  173. ' '*(height - i - 1) + xobj('/', 1) + ' '*i
  174. for i in range(height)
  175. )
  176. return self.left(stringPict(slash, height//2))
  177. def root(self, n=None):
  178. """Produce a nice root symbol.
  179. Produces ugly results for big n inserts.
  180. """
  181. # XXX not used anywhere
  182. # XXX duplicate of root drawing in pretty.py
  183. #put line over expression
  184. result = self.above('_'*self.width())
  185. #construct right half of root symbol
  186. height = self.height()
  187. slash = '\n'.join(
  188. ' ' * (height - i - 1) + '/' + ' ' * i
  189. for i in range(height)
  190. )
  191. slash = stringPict(slash, height - 1)
  192. #left half of root symbol
  193. if height > 2:
  194. downline = stringPict('\\ \n \\', 1)
  195. else:
  196. downline = stringPict('\\')
  197. #put n on top, as low as possible
  198. if n is not None and n.width() > downline.width():
  199. downline = downline.left(' '*(n.width() - downline.width()))
  200. downline = downline.above(n)
  201. #build root symbol
  202. root = downline.right(slash)
  203. #glue it on at the proper height
  204. #normally, the root symbel is as high as self
  205. #which is one less than result
  206. #this moves the root symbol one down
  207. #if the root became higher, the baseline has to grow too
  208. root.baseline = result.baseline - result.height() + root.height()
  209. return result.left(root)
  210. def render(self, * args, **kwargs):
  211. """Return the string form of self.
  212. Unless the argument line_break is set to False, it will
  213. break the expression in a form that can be printed
  214. on the terminal without being broken up.
  215. """
  216. if _GLOBAL_WRAP_LINE is not None:
  217. kwargs["wrap_line"] = _GLOBAL_WRAP_LINE
  218. if kwargs["wrap_line"] is False:
  219. return "\n".join(self.picture)
  220. if kwargs["num_columns"] is not None:
  221. # Read the argument num_columns if it is not None
  222. ncols = kwargs["num_columns"]
  223. else:
  224. # Attempt to get a terminal width
  225. ncols = self.terminal_width()
  226. if ncols <= 0:
  227. ncols = 80
  228. # If smaller than the terminal width, no need to correct
  229. if self.width() <= ncols:
  230. return type(self.picture[0])(self)
  231. """
  232. Break long-lines in a visually pleasing format.
  233. without overflow indicators | with overflow indicators
  234. | 2 2 3 | | 2 2 3 ↪|
  235. |6*x *y + 4*x*y + | |6*x *y + 4*x*y + ↪|
  236. | | | |
  237. | 3 4 4 | |↪ 3 4 4 |
  238. |4*y*x + x + y | |↪ 4*y*x + x + y |
  239. |a*c*e + a*c*f + a*d | |a*c*e + a*c*f + a*d ↪|
  240. |*e + a*d*f + b*c*e | | |
  241. |+ b*c*f + b*d*e + b | |↪ *e + a*d*f + b*c* ↪|
  242. |*d*f | | |
  243. | | |↪ e + b*c*f + b*d*e ↪|
  244. | | | |
  245. | | |↪ + b*d*f |
  246. """
  247. overflow_first = ""
  248. if kwargs["use_unicode"] or pretty_use_unicode():
  249. overflow_start = "\N{RIGHTWARDS ARROW WITH HOOK} "
  250. overflow_end = " \N{RIGHTWARDS ARROW WITH HOOK}"
  251. else:
  252. overflow_start = "> "
  253. overflow_end = " >"
  254. def chunks(line):
  255. """Yields consecutive chunks of line_width ncols"""
  256. prefix = overflow_first
  257. width, start = line_width(prefix + overflow_end), 0
  258. for i, x in enumerate(line):
  259. wx = line_width(x)
  260. # Only flush the screen when the current character overflows.
  261. # This way, combining marks can be appended even when width == ncols.
  262. if width + wx > ncols:
  263. yield prefix + line[start:i] + overflow_end
  264. prefix = overflow_start
  265. width, start = line_width(prefix + overflow_end), i
  266. width += wx
  267. yield prefix + line[start:]
  268. # Concurrently assemble chunks of all lines into individual screens
  269. pictures = zip(*map(chunks, self.picture))
  270. # Join lines of each screen into sub-pictures
  271. pictures = ["\n".join(picture) for picture in pictures]
  272. # Add spacers between sub-pictures
  273. return "\n\n".join(pictures)
  274. def terminal_width(self):
  275. """Return the terminal width if possible, otherwise return 0.
  276. """
  277. size = shutil.get_terminal_size(fallback=(0, 0))
  278. return size.columns
  279. def __eq__(self, o):
  280. if isinstance(o, str):
  281. return '\n'.join(self.picture) == o
  282. elif isinstance(o, stringPict):
  283. return o.picture == self.picture
  284. return False
  285. def __hash__(self):
  286. return super().__hash__()
  287. def __str__(self):
  288. return '\n'.join(self.picture)
  289. def __repr__(self):
  290. return "stringPict(%r,%d)" % ('\n'.join(self.picture), self.baseline)
  291. def __getitem__(self, index):
  292. return self.picture[index]
  293. def __len__(self):
  294. return len(self.s)
  295. class prettyForm(stringPict):
  296. """
  297. Extension of the stringPict class that knows about basic math applications,
  298. optimizing double minus signs.
  299. "Binding" is interpreted as follows::
  300. ATOM this is an atom: never needs to be parenthesized
  301. FUNC this is a function application: parenthesize if added (?)
  302. DIV this is a division: make wider division if divided
  303. POW this is a power: only parenthesize if exponent
  304. MUL this is a multiplication: parenthesize if powered
  305. ADD this is an addition: parenthesize if multiplied or powered
  306. NEG this is a negative number: optimize if added, parenthesize if
  307. multiplied or powered
  308. OPEN this is an open object: parenthesize if added, multiplied, or
  309. powered (example: Piecewise)
  310. """
  311. ATOM, FUNC, DIV, POW, MUL, ADD, NEG, OPEN = range(8)
  312. def __init__(self, s, baseline=0, binding=0, unicode=None):
  313. """Initialize from stringPict and binding power."""
  314. stringPict.__init__(self, s, baseline)
  315. self.binding = binding
  316. if unicode is not None:
  317. sympy_deprecation_warning(
  318. """
  319. The unicode argument to prettyForm is deprecated. Only the s
  320. argument (the first positional argument) should be passed.
  321. """,
  322. deprecated_since_version="1.7",
  323. active_deprecations_target="deprecated-pretty-printing-functions")
  324. self._unicode = unicode or s
  325. @property
  326. def unicode(self):
  327. sympy_deprecation_warning(
  328. """
  329. The prettyForm.unicode attribute is deprecated. Use the
  330. prettyForm.s attribute instead.
  331. """,
  332. deprecated_since_version="1.7",
  333. active_deprecations_target="deprecated-pretty-printing-functions")
  334. return self._unicode
  335. # Note: code to handle subtraction is in _print_Add
  336. def __add__(self, *others):
  337. """Make a pretty addition.
  338. Addition of negative numbers is simplified.
  339. """
  340. arg = self
  341. if arg.binding > prettyForm.NEG:
  342. arg = stringPict(*arg.parens())
  343. result = [arg]
  344. for arg in others:
  345. #add parentheses for weak binders
  346. if arg.binding > prettyForm.NEG:
  347. arg = stringPict(*arg.parens())
  348. #use existing minus sign if available
  349. if arg.binding != prettyForm.NEG:
  350. result.append(' + ')
  351. result.append(arg)
  352. return prettyForm(binding=prettyForm.ADD, *stringPict.next(*result))
  353. def __truediv__(self, den, slashed=False):
  354. """Make a pretty division; stacked or slashed.
  355. """
  356. if slashed:
  357. raise NotImplementedError("Can't do slashed fraction yet")
  358. num = self
  359. if num.binding == prettyForm.DIV:
  360. num = stringPict(*num.parens())
  361. if den.binding == prettyForm.DIV:
  362. den = stringPict(*den.parens())
  363. if num.binding==prettyForm.NEG:
  364. num = num.right(" ")[0]
  365. return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
  366. num,
  367. stringPict.LINE,
  368. den))
  369. def __mul__(self, *others):
  370. """Make a pretty multiplication.
  371. Parentheses are needed around +, - and neg.
  372. """
  373. quantity = {
  374. 'degree': "\N{DEGREE SIGN}"
  375. }
  376. if len(others) == 0:
  377. return self # We aren't actually multiplying... So nothing to do here.
  378. # add parens on args that need them
  379. arg = self
  380. if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
  381. arg = stringPict(*arg.parens())
  382. result = [arg]
  383. for arg in others:
  384. if arg.picture[0] not in quantity.values():
  385. result.append(xsym('*'))
  386. #add parentheses for weak binders
  387. if arg.binding > prettyForm.MUL and arg.binding != prettyForm.NEG:
  388. arg = stringPict(*arg.parens())
  389. result.append(arg)
  390. len_res = len(result)
  391. for i in range(len_res):
  392. if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'):
  393. # substitute -1 by -, like in -1*x -> -x
  394. result.pop(i)
  395. result.pop(i)
  396. result.insert(i, '-')
  397. if result[0][0] == '-':
  398. # if there is a - sign in front of all
  399. # This test was failing to catch a prettyForm.__mul__(prettyForm("-1", 0, 6)) being negative
  400. bin = prettyForm.NEG
  401. if result[0] == '-':
  402. right = result[1]
  403. if right.picture[right.baseline][0] == '-':
  404. result[0] = '- '
  405. else:
  406. bin = prettyForm.MUL
  407. return prettyForm(binding=bin, *stringPict.next(*result))
  408. def __repr__(self):
  409. return "prettyForm(%r,%d,%d)" % (
  410. '\n'.join(self.picture),
  411. self.baseline,
  412. self.binding)
  413. def __pow__(self, b):
  414. """Make a pretty power.
  415. """
  416. a = self
  417. use_inline_func_form = False
  418. if b.binding == prettyForm.POW:
  419. b = stringPict(*b.parens())
  420. if a.binding > prettyForm.FUNC:
  421. a = stringPict(*a.parens())
  422. elif a.binding == prettyForm.FUNC:
  423. # heuristic for when to use inline power
  424. if b.height() > 1:
  425. a = stringPict(*a.parens())
  426. else:
  427. use_inline_func_form = True
  428. if use_inline_func_form:
  429. # 2
  430. # sin + + (x)
  431. b.baseline = a.prettyFunc.baseline + b.height()
  432. func = stringPict(*a.prettyFunc.right(b))
  433. return prettyForm(*func.right(a.prettyArgs))
  434. else:
  435. # 2 <-- top
  436. # (x+y) <-- bot
  437. top = stringPict(*b.left(' '*a.width()))
  438. bot = stringPict(*a.right(' '*b.width()))
  439. return prettyForm(binding=prettyForm.POW, *bot.above(top))
  440. simpleFunctions = ["sin", "cos", "tan"]
  441. @staticmethod
  442. def apply(function, *args):
  443. """Functions of one or more variables.
  444. """
  445. if function in prettyForm.simpleFunctions:
  446. #simple function: use only space if possible
  447. assert len(
  448. args) == 1, "Simple function %s must have 1 argument" % function
  449. arg = args[0].__pretty__()
  450. if arg.binding <= prettyForm.DIV:
  451. #optimization: no parentheses necessary
  452. return prettyForm(binding=prettyForm.FUNC, *arg.left(function + ' '))
  453. argumentList = []
  454. for arg in args:
  455. argumentList.append(',')
  456. argumentList.append(arg.__pretty__())
  457. argumentList = stringPict(*stringPict.next(*argumentList[1:]))
  458. argumentList = stringPict(*argumentList.parens())
  459. return prettyForm(binding=prettyForm.ATOM, *argumentList.left(function))