bugfix: never use utf8 pos in string.sub
[view.love.git] / colorize.lua
blobe42630a6c781071f3a93e5119ea9dc0b6182de88
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 {prefix='"', target='dstring'},
10 {prefix="'", target='sstring'},
11 {prefix='[[', target='block_string'}, -- only single line for now
13 dstring={
14 {suffix='"', target='normal'},
16 sstring={
17 {suffix="'", target='normal'},
19 block_string={
20 {suffix=']]', target='normal'},
22 block_comment={
23 {suffix=']]', target='normal'},
25 -- comments are a sink
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}
32 Colors = {
33 normal=Text_color,
34 comment=Comment_color,
35 sstring=String_color,
36 dstring=String_color,
37 block_string=String_color,
38 block_comment=Comment_color,
41 Current_state = 'normal'
43 function initialize_color()
44 --? print('new line')
45 Current_state = 'normal'
46 end
48 function select_color(frag)
49 --? print('before', '^'..frag..'$', Current_state)
50 switch_color_based_on_prefix(frag)
51 --? print('using color', Current_state, Colors[Current_state])
52 App.color(Colors[Current_state])
53 switch_color_based_on_suffix(frag)
54 --? print('state after suffix', Current_state)
55 end
57 function switch_color_based_on_prefix(frag)
58 if Next_state[Current_state] == nil then
59 return
60 end
61 frag = rtrim(frag)
62 for _,edge in pairs(Next_state[Current_state]) do
63 if edge.prefix and starts_with(frag, edge.prefix) then
64 Current_state = edge.target
65 break
66 end
67 end
68 end
70 function switch_color_based_on_suffix(frag)
71 if Next_state[Current_state] == nil then
72 return
73 end
74 frag = rtrim(frag)
75 for _,edge in pairs(Next_state[Current_state]) do
76 if edge.suffix and ends_with(frag, edge.suffix) then
77 Current_state = edge.target
78 break
79 end
80 end
81 end