colorize.lua 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. -- State transitions while colorizing a single line.
  2. -- Just for comments and strings.
  3. -- Limitation: each fragment gets a uniform color so we can only change color
  4. -- at word boundaries.
  5. Next_state = {
  6. normal={
  7. {prefix='--[[', target='block_comment'}, -- only single-line for now
  8. {prefix='--', target='comment'},
  9. -- these don't mostly work well until we can change color within words
  10. -- {prefix='"', target='dstring'},
  11. -- {prefix="'", target='sstring'},
  12. {prefix='[[', target='block_string'}, -- only single line for now
  13. },
  14. dstring={
  15. {suffix='"', target='normal'},
  16. },
  17. sstring={
  18. {suffix="'", target='normal'},
  19. },
  20. block_string={
  21. {suffix=']]', target='normal'},
  22. },
  23. block_comment={
  24. {suffix=']]', target='normal'},
  25. },
  26. -- comments are a sink
  27. }
  28. Comment_color = {r=0, g=0, b=1}
  29. String_color = {r=0, g=0.5, b=0.5}
  30. Divider_color = {r=0.7, g=0.7, b=0.7}
  31. Colors = {
  32. normal=Text_color,
  33. comment=Comment_color,
  34. sstring=String_color,
  35. dstring=String_color,
  36. block_string=String_color,
  37. block_comment=Comment_color,
  38. }
  39. Current_state = 'normal'
  40. function initialize_color()
  41. --? print('new line')
  42. Current_state = 'normal'
  43. end
  44. function select_color(frag)
  45. --? print('before', '^'..frag..'$', Current_state)
  46. switch_color_based_on_prefix(frag)
  47. --? print('using color', Current_state, Colors[Current_state])
  48. App.color(Colors[Current_state])
  49. switch_color_based_on_suffix(frag)
  50. --? print('state after suffix', Current_state)
  51. end
  52. function switch_color_based_on_prefix(frag)
  53. if Next_state[Current_state] == nil then
  54. return
  55. end
  56. frag = rtrim(frag)
  57. for _,edge in pairs(Next_state[Current_state]) do
  58. if edge.prefix and starts_with(frag, edge.prefix) then
  59. Current_state = edge.target
  60. break
  61. end
  62. end
  63. end
  64. function switch_color_based_on_suffix(frag)
  65. if Next_state[Current_state] == nil then
  66. return
  67. end
  68. frag = rtrim(frag)
  69. for _,edge in pairs(Next_state[Current_state]) do
  70. if edge.suffix and ends_with(frag, edge.suffix) then
  71. Current_state = edge.target
  72. break
  73. end
  74. end
  75. end