nvim-gdb-pretty-printers.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. # Register a gdb pretty printer for UGrid instances. Usage:
  2. #
  3. # - start gdb
  4. # - run `source contrib/gdb/nvim-gdb-pretty-printers.py`
  5. # - when a `UGrid` pointer can be evaluated in the current frame, just print
  6. # it's value normally: `p *grid` (assuming `grid` is the variable name
  7. # holding the pointer)
  8. # - highlighting can be activated by setting the NVIM_GDB_HIGHLIGHT_UGRID
  9. # environment variable(only xterm-compatible terminals supported). This
  10. # can be done while gdb is running through the python interface:
  11. # `python os.environ['NVIM_GDB_HIGHLIGHT_UGRID'] = '1'`
  12. import os
  13. import gdb
  14. import gdb.printing
  15. SGR0 = '\x1b(B\x1b[m'
  16. def get_color_code(bg, color_num):
  17. if color_num < 16:
  18. prefix = 3
  19. if color_num > 7:
  20. prefix = 9
  21. if bg:
  22. prefix += 1
  23. color_num %= 8
  24. else:
  25. prefix = '48;5;' if bg else '38;5;'
  26. return '\x1b[{0}{1}m'.format(prefix, color_num)
  27. def highlight(attrs):
  28. fg, bg = [int(attrs['foreground']), int(attrs['background'])]
  29. rv = [SGR0] # start with sgr0
  30. if fg != -1:
  31. rv.append(get_color_code(False, fg))
  32. if bg != -1:
  33. rv.append(get_color_code(True, bg))
  34. if bool(attrs['bold']):
  35. rv.append('\x1b[1m')
  36. if bool(attrs['italic']):
  37. rv.append('\x1b[3m')
  38. if bool(attrs['undercurl']) or bool(attrs['underline']):
  39. rv.append('\x1b[4m')
  40. if bool(attrs['reverse']):
  41. rv.append('\x1b[7m')
  42. return ''.join(rv)
  43. class UGridPrinter(object):
  44. def __init__(self, val):
  45. self.val = val
  46. def to_string(self):
  47. do_hl = (os.getenv('NVIM_GDB_HIGHLIGHT_UGRID') and
  48. os.getenv('NVIM_GDB_HIGHLIGHT_UGRID') != '0')
  49. grid = self.val
  50. height = int(grid['height'])
  51. width = int(grid['width'])
  52. delimiter = '-' * (width + 2)
  53. rows = [delimiter]
  54. for row in range(height):
  55. cols = []
  56. if do_hl:
  57. cols.append(SGR0)
  58. curhl = None
  59. for col in range(width):
  60. cell = grid['cells'][row][col]
  61. if do_hl:
  62. hl = highlight(cell['attrs'])
  63. if hl != curhl:
  64. cols.append(hl)
  65. curhl = hl
  66. cols.append(cell['data'].string('utf-8'))
  67. if do_hl:
  68. cols.append(SGR0)
  69. rows.append('|' + ''.join(cols) + '|')
  70. rows.append(delimiter)
  71. return '\n' + '\n'.join(rows)
  72. def display_hint(self):
  73. return 'hint'
  74. def pretty_printers():
  75. pp = gdb.printing.RegexpCollectionPrettyPrinter('nvim')
  76. pp.add_printer('UGrid', '^ugrid$', UGridPrinter)
  77. return pp
  78. gdb.printing.register_pretty_printer(gdb, pretty_printers(), replace=True)