scr.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. from pygments import lexers
  2. from pygments.styles import get_all_styles
  3. from pygments.util import ClassNotFound
  4. from rich.syntax import Syntax
  5. from rich.traceback import Traceback
  6. from textual import on
  7. from textual.containers import Horizontal
  8. from textual.screen import Screen
  9. from textual.widgets import Static, OptionList
  10. from textual.widgets.option_list import Option
  11. class Main(Screen):
  12. CSS = '''
  13. #styles{
  14. width: 3fr;
  15. }
  16. #preview{
  17. width: 9fr;
  18. }
  19. '''
  20. BINDINGS = [
  21. ("escape", "exit", "Exit"),
  22. ]
  23. def compose(self):
  24. styles = [
  25. Option(style, style)
  26. for style in get_all_styles()
  27. ]
  28. with Horizontal():
  29. self.themes = OptionList(*styles, id='styles')
  30. yield self.themes
  31. self.preview = Static(id="preview", expand=True)
  32. yield self.preview
  33. def on_mount(self, event):
  34. self.themes.focus()
  35. def on_key(self, event):
  36. if event.key == 'delete':
  37. self.themes.remove_option(self.theme)
  38. self.themes.action_cursor_down()
  39. self.themes.action_cursor_up()
  40. @on(OptionList.OptionHighlighted, '#styles')
  41. def highlight(self, event):
  42. event.stop()
  43. self.theme = event.option.prompt
  44. path = self.app.path
  45. try:
  46. content = open(path).read()
  47. except Exception as x:
  48. content = f'{x}'
  49. file_type = None
  50. try:
  51. lexer = lexers.guess_lexer_for_filename(path, content)
  52. file_type = lexer.name
  53. except ClassNotFound:
  54. file_type = None
  55. syntax = Syntax(
  56. content,
  57. file_type,
  58. line_numbers = True,
  59. word_wrap = False,
  60. indent_guides = False,
  61. theme = self.theme,
  62. )
  63. self.preview.update(syntax)
  64. self.preview.scroll_home(animate=False)
  65. def action_exit(self):
  66. self.app.exit(self.theme)