From ee5cac4f217f811070c532fe53c4ff8ae7590b99 Mon Sep 17 00:00:00 2001 From: Přemysl Eric Janouch Date: Sat, 10 Oct 2020 17:55:14 +0200 Subject: degesch: add a plugin to highlight prime numbers --- plugins/degesch/prime.lua | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 plugins/degesch/prime.lua (limited to 'plugins/degesch') diff --git a/plugins/degesch/prime.lua b/plugins/degesch/prime.lua new file mode 100644 index 0000000..bffc0e1 --- /dev/null +++ b/plugins/degesch/prime.lua @@ -0,0 +1,50 @@ +-- +-- prime.lua: highlight prime numbers in messages +-- +-- Copyright (c) 2020, Přemysl Eric Janouch +-- +-- Permission to use, copy, modify, and/or distribute this software for any +-- purpose with or without fee is hereby granted. +-- +-- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +-- WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +-- MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +-- SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +-- WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION +-- OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN +-- CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +-- + +-- The prime test is actually very fast, so there is no DoS concern +local is_prime = function (n) + if tonumber (n) < 2 then return false end + for i = 2, n ^ (1 / 2) do if (n % i) == 0 then return false end end + return true +end + +local do_interlink = function (run) + -- Let's not cripple formatting, colours especially + -- TODO: we can just employ the same approach as in do_text and skip over + if run:find ('%c') then return run end + + return run:gsub ("%f[%w_]%d+%f[^%w_]", function (number) + if is_prime (number) then return "\x1f" .. number .. "\x1f" end + return number + end) +end + +local do_text = function (text) + local rebuilt, last = {""}, 1 + for run, link, endpos in text:gmatch ('(.-)(%f[%g]https?://%g+)()') do + last = endpos + table.insert (rebuilt, do_interlink (run) .. link) + end + return table.concat (rebuilt, "") .. do_interlink (text:sub (last)) +end + +-- XXX: sadly it won't typically highlight primes in our own messages, +-- unless IRCv3 echo-message is on +degesch.hook_irc (function (hook, server, line) + local start, message = line:match ("^(.- PRIVMSG .- :)(.*)$") + return message and start .. do_text (message) or line +end) -- cgit v1.2.3-70-g09d2