From 36f1f938bfa35a2698935bcaba78190cbee1977f Mon Sep 17 00:00:00 2001
From: terminaldweller <thabogre@gmail.com>
Date: Sun, 6 Feb 2022 00:22:20 +0330
Subject: fix

---
 bin/clipd | 31 ++++++++++++++++++++++++++-----
 1 file changed, 26 insertions(+), 5 deletions(-)

diff --git a/bin/clipd b/bin/clipd
index e25fcb0..ce14a08 100755
--- a/bin/clipd
+++ b/bin/clipd
@@ -24,11 +24,12 @@ end
 default_luarocks_modules()
 
 local string = require("string")
--- local signal = require("posix.signal")
+local signal = require("posix.signal")
 
--- signal.signal(signal.SIGINT, function(signum) os.exit(128 + signum) end)
+signal.signal(signal.SIGINT, function(signum) os.exit(128 + signum) end)
+
+local function sleep(n) os.execute("sleep " .. tonumber(n)) end
 
--- FIXME-clip history size is not being used
 local function loop()
     local clip_hist_size = 100
     local clip_hist = "/home/devi/.clip_history"
@@ -39,18 +40,38 @@ local function loop()
 
         local handle = io.popen("xsel -ob")
         local last_clip_entry = handle:read("*a")
-        local hist_file = io.open(clip_hist, "a+")
+        local hist_file = io.open(clip_hist, "r")
+        local hist_current_count = 0
+        local clips_table = {}
 
         for line in hist_file:lines() do
+            hist_current_count = hist_current_count + 1
             if (string.sub(line, 0, string.len(line)) == last_clip_entry) then
                 matched = true
             end
+            if line ~= "\n" and line ~= "" and line ~= "\r\n" and line ~= " " then
+                table.insert(clips_table, line)
+            end
+        end
+        hist_file:close()
+        hist_file = io.open(clip_hist, "w")
+        if matched ~= true then
+            if last_clip_entry[-1] == "\n" then
+                table.insert(clips_table, string.sub(last_clip_entry, 0,
+                                                     string.len(last_clip_entry)))
+            else
+                table.insert(clips_table, last_clip_entry)
+            end
+        end
+        if hist_current_count >= clip_hist_size then
+            table.remove(clips_table, 1)
         end
-        if matched ~= true then hist_file:write(last_clip_entry .. "\n") end
+        for _, v in ipairs(clips_table) do hist_file:write(v .. "\n") end
         matched = false
         hist_file:close()
         wait_for_event:close()
         handle:close()
+        sleep(.2)
     end
 end
 
-- 
cgit v1.2.3