about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2023-01-13 09:33:34 -0800
committerKartik K. Agaram <vc@akkartik.com>2023-01-13 09:33:34 -0800
commitd8ec2597110ac95fcb61c5a46af95bf094c95268 (patch)
tree5b17c74ef8a3a6d6dd0c72c30759612bba14ec3c
parentab44ed033209cd3d016f65f6e7fe1f0267d74527 (diff)
parent22bf3da7de9074c6b99d8e43e3ab1772aed7b059 (diff)
downloadtext.love-d8ec2597110ac95fcb61c5a46af95bf094c95268.tar.gz
Merge lines.love
-rw-r--r--colorize.lua16
-rw-r--r--search.lua2
-rw-r--r--text.lua24
3 files changed, 28 insertions, 14 deletions
diff --git a/colorize.lua b/colorize.lua
index 6c2057c..e42630a 100644
--- a/colorize.lua
+++ b/colorize.lua
@@ -60,7 +60,7 @@ function switch_color_based_on_prefix(frag)
   end
   frag = rtrim(frag)
   for _,edge in pairs(Next_state[Current_state]) do
-    if edge.prefix and find(frag, edge.prefix, nil, --[[plain]] true) == 1 then
+    if edge.prefix and starts_with(frag, edge.prefix) then
       Current_state = edge.target
       break
     end
@@ -73,21 +73,9 @@ function switch_color_based_on_suffix(frag)
   end
   frag = rtrim(frag)
   for _,edge in pairs(Next_state[Current_state]) do
-    if edge.suffix and rfind(frag, edge.suffix, nil, --[[plain]] true) == #frag - #edge.suffix + 1 then
+    if edge.suffix and ends_with(frag, edge.suffix) then
       Current_state = edge.target
       break
     end
   end
 end
-
-function trim(s)
-  return s:gsub('^%s+', ''):gsub('%s+$', '')
-end
-
-function ltrim(s)
-  return s:gsub('^%s+', '')
-end
-
-function rtrim(s)
-  return s:gsub('%s+$', '')
-end
diff --git a/search.lua b/search.lua
index 37306f8..f7d4732 100644
--- a/search.lua
+++ b/search.lua
@@ -116,6 +116,8 @@ function find(s, pat, i, plain)
   return s:find(pat, i, plain)
 end
 
+-- TODO: avoid the expensive reverse() operations
+-- Particularly if we only care about literal matches, we don't need all of string.find
 function rfind(s, pat, i, plain)
   if s == nil then return end
   local rs = s:reverse()
diff --git a/text.lua b/text.lua
index 9447a0d..961faba 100644
--- a/text.lua
+++ b/text.lua
@@ -925,3 +925,27 @@ end
 function rtrim(s)
   return s:gsub('%s+$', '')
 end
+
+function starts_with(s, prefix)
+  if #s < #prefix then
+    return false
+  end
+  for i=1,#prefix do
+    if s:sub(i,i) ~= prefix:sub(i,i) then
+      return false
+    end
+  end
+  return true
+end
+
+function ends_with(s, suffix)
+  if #s < #suffix then
+    return false
+  end
+  for i=0,#suffix-1 do
+    if s:sub(#s-i,#s-i) ~= suffix:sub(#suffix-i,#suffix-i) then
+      return false
+    end
+  end
+  return true
+end