]>
git.rmz.io Git - dotfiles.git/blob - weechat/python/colorize_nicks.py
1 # -*- coding: utf-8 -*-
3 # Copyright (c) 2010 by xt <xt@bash.no>
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
19 # This script colors nicks in IRC channels in the actual message
20 # not just in the prefix section.
24 # 2022-07-11: ncfavier
25 # version 29: check nick for exclusion *after* stripping
26 # decrease minimum min_nick_length to 1
28 # version 28: fix ignore_tags having been broken by weechat 2.9 changes
29 # 2020-05-09: Sébastien Helleu <flashcode@flashtux.org>
30 # version 27: add compatibility with new weechat_print modifier data
32 # 2018-04-06: Joey Pabalinas <joeypabalinas@gmail.com>
33 # version 26: fix freezes with too many nicks in one line
35 # version 25: fix unable to run function colorize_config_reload_cb()
36 # 2017-06-20: lbeziaud <louis.beziaud@ens-rennes.fr>
37 # version 24: colorize utf8 nicks
38 # 2017-03-01, arza <arza@arza.us>
39 # version 23: don't colorize nicklist group names
40 # 2016-05-01, Simmo Saan <simmo.saan@gmail.com>
41 # version 22: invalidate cached colors on hash algorithm change
43 # version 21: fix problems with nicks with commas in them
45 # version 20: fix ignore of nicks in URLs
47 # version 19: new option ignore nicks in URLs
49 # version 18: iterate buffers looking for nicklists instead of servers
50 # 2015-02-23, holomorph
51 # version 17: fix coloring in non-channel buffers (#58)
52 # 2014-09-17, holomorph
53 # version 16: use weechat config facilities
54 # clean unused, minor linting, some simplification
55 # 2014-05-05, holomorph
56 # version 15: fix python2-specific re.search check
58 # version 14: make script compatible with Python 3.x
60 # version 13: Iterate over every word to prevent incorrect colorization of
61 # nicks. Added option greedy_matching.
63 # version 12: added ignore_tags to avoid colorizing nicks if tags are present
65 # version 11: input_text_display hook and modifier to colorize nicks in input bar
67 # version 10: hook config option for updating blacklist
69 # version 0.9: hook new config option for weechat 0.3.4
71 # version 0.8: hook_modifier() added to communicate with rainbow_text
73 # version 0.7: changes to support non-irc-plugins
75 # version 0.6: compile regexp as per patch from Chris quigybo@hotmail.com
77 # version 0.5: fix bug with incorrect coloring of own nick
79 # version 0.4: update to reflect API changes
81 # version 0.3: fix error with exception
83 # version 0.2: use ignore_channels when populating to increase performance.
85 # version 0.1: initial (based on ruby script by dominikh)
87 # Known issues: nicks will not get colorized if they begin with a character
88 # such as ~ (which some irc networks do happen to accept)
94 SCRIPT_NAME
= "colorize_nicks"
95 SCRIPT_AUTHOR
= "xt <xt@bash.no>"
97 SCRIPT_LICENSE
= "GPL"
98 SCRIPT_DESC
= "Use the weechat nick colors in the chat area"
100 # Based on the recommendations in RFC 7613. A valid nick is composed
101 # of anything but " ,*?.!@".
102 VALID_NICK
= r
'([@~&!%+-])?([^\s,\*?\.!@]+)'
103 valid_nick_re
= re
.compile(VALID_NICK
)
107 # Dict with every nick on every channel with its color as lookup value
110 CONFIG_FILE_NAME
= "colorize_nicks"
112 # config file and options
113 colorize_config_file
= ""
114 colorize_config_option
= {}
116 def colorize_config_init():
118 Initialization of configuration file.
121 global colorize_config_file
, colorize_config_option
122 colorize_config_file
= weechat
.config_new(CONFIG_FILE_NAME
,
124 if colorize_config_file
== "":
128 section_look
= weechat
.config_new_section(
129 colorize_config_file
, "look", 0, 0, "", "", "", "", "", "", "", "", "", "")
130 if section_look
== "":
131 weechat
.config_free(colorize_config_file
)
133 colorize_config_option
["blacklist_channels"] = weechat
.config_new_option(
134 colorize_config_file
, section_look
, "blacklist_channels",
135 "string", "Comma separated list of channels", "", 0, 0,
136 "", "", 0, "", "", "", "", "", "")
137 colorize_config_option
["blacklist_nicks"] = weechat
.config_new_option(
138 colorize_config_file
, section_look
, "blacklist_nicks",
139 "string", "Comma separated list of nicks", "", 0, 0,
140 "so,root", "so,root", 0, "", "", "", "", "", "")
141 colorize_config_option
["min_nick_length"] = weechat
.config_new_option(
142 colorize_config_file
, section_look
, "min_nick_length",
143 "integer", "Minimum length nick to colorize", "",
144 1, 20, "2", "2", 0, "", "", "", "", "", "")
145 colorize_config_option
["colorize_input"] = weechat
.config_new_option(
146 colorize_config_file
, section_look
, "colorize_input",
147 "boolean", "Whether to colorize input", "", 0,
148 0, "off", "off", 0, "", "", "", "", "", "")
149 colorize_config_option
["ignore_tags"] = weechat
.config_new_option(
150 colorize_config_file
, section_look
, "ignore_tags",
151 "string", "Comma separated list of tags to ignore; i.e. irc_join,irc_part,irc_quit", "", 0, 0,
152 "", "", 0, "", "", "", "", "", "")
153 colorize_config_option
["greedy_matching"] = weechat
.config_new_option(
154 colorize_config_file
, section_look
, "greedy_matching",
155 "boolean", "If off, then use lazy matching instead", "", 0,
156 0, "on", "on", 0, "", "", "", "", "", "")
157 colorize_config_option
["match_limit"] = weechat
.config_new_option(
158 colorize_config_file
, section_look
, "match_limit",
159 "integer", "Fall back to lazy matching if greedy matches exceeds this number", "",
160 20, 1000, "", "", 0, "", "", "", "", "", "")
161 colorize_config_option
["ignore_nicks_in_urls"] = weechat
.config_new_option(
162 colorize_config_file
, section_look
, "ignore_nicks_in_urls",
163 "boolean", "If on, don't colorize nicks inside URLs", "", 0,
164 0, "off", "off", 0, "", "", "", "", "", "")
166 def colorize_config_read():
167 ''' Read configuration file. '''
168 global colorize_config_file
169 return weechat
.config_read(colorize_config_file
)
171 def colorize_nick_color(nick
, my_nick
):
172 ''' Retrieve nick color from weechat. '''
174 return w
.color(w
.config_string(w
.config_get('weechat.color.chat_nick_self')))
176 return w
.info_get('nick_color', nick
)
178 def colorize_cb(data
, modifier
, modifier_data
, line
):
179 ''' Callback that does the colorizing, and returns new line if changed '''
181 global ignore_nicks
, ignore_channels
, colored_nicks
183 if modifier_data
.startswith('0x'):
185 buffer, tags
= modifier_data
.split(';', 1)
188 plugin
, buffer_name
, tags
= modifier_data
.split(';', 2)
189 buffer = w
.buffer_search(plugin
, buffer_name
)
191 channel
= w
.buffer_get_string(buffer, 'localvar_channel')
192 tags
= tags
.split(',')
194 # Check if buffer has colorized nicks
195 if buffer not in colored_nicks
:
198 if channel
and channel
in ignore_channels
:
201 min_length
= w
.config_integer(colorize_config_option
['min_nick_length'])
202 reset
= w
.color('reset')
204 # Don't colorize if the ignored tag is present in message
205 tag_ignores
= w
.config_string(colorize_config_option
['ignore_tags']).split(',')
207 if tag
in tag_ignores
:
210 for words
in valid_nick_re
.findall(line
):
213 # If the matched word is not a known nick, we try to match the
214 # word without its first or last character (if not a letter).
215 # This is necessary as "foo:" is a valid nick, which could be
216 # adressed as "foo::".
217 if nick
not in colored_nicks
[buffer]:
218 if not nick
[-1].isalpha() and not nick
[0].isalpha():
219 if nick
[1:-1] in colored_nicks
[buffer]:
221 elif not nick
[0].isalpha():
222 if nick
[1:] in colored_nicks
[buffer]:
224 elif not nick
[-1].isalpha():
225 if nick
[:-1] in colored_nicks
[buffer]:
228 # Check that nick is not ignored and longer than minimum length
229 if len(nick
) < min_length
or nick
in ignore_nicks
:
232 # Check that nick is in the dictionary colored_nicks
233 if nick
in colored_nicks
[buffer]:
234 nick_color
= colored_nicks
[buffer][nick
]
237 # Let's use greedy matching. Will check against every word in a line.
238 if w
.config_boolean(colorize_config_option
['greedy_matching']):
240 limit
= w
.config_integer(colorize_config_option
['match_limit'])
242 for word
in line
.split():
246 # raise RuntimeError('Exceeded colorize_nicks.look.match_limit.');
248 if w
.config_boolean(colorize_config_option
['ignore_nicks_in_urls']) and \
249 word
.startswith(('http://', 'https://')):
253 # Is there a nick that contains nick and has a greater lenght?
254 # If so let's save that nick into var biggest_nick
256 for i
in colored_nicks
[buffer]:
260 if nick
in i
and nick
!= i
and len(i
) > len(nick
):
262 # If a nick with greater len is found, and that word
263 # also happens to be in word, then let's save this nick
265 # If there's a nick with greater len, then let's skip this
266 # As we will have the chance to colorize when biggest_nick
267 # iterates being nick.
268 if len(biggest_nick
) > 0 and biggest_nick
in word
:
270 elif len(word
) < len(biggest_nick
) or len(biggest_nick
) == 0:
271 new_word
= word
.replace(nick
, '%s%s%s' % (nick_color
, nick
, reset
))
272 line
= line
.replace(word
, new_word
)
274 # Switch to lazy matching
278 except AssertionError:
279 # Let's use lazy matching for nick
280 nick_color
= colored_nicks
[buffer][nick
]
281 # The two .? are in case somebody writes "nick:", "nick,", etc
282 # to address somebody
283 regex
= r
"(\A|\s).?(%s).?(\Z|\s)" % re
.escape(nick
)
284 match
= re
.search(regex
, line
)
285 if match
is not None:
286 new_line
= line
[:match
.start(2)] + nick_color
+nick
+reset
+ line
[match
.end(2):]
291 def colorize_input_cb(data
, modifier
, modifier_data
, line
):
292 ''' Callback that does the colorizing in input '''
294 global ignore_nicks
, ignore_channels
, colored_nicks
296 min_length
= w
.config_integer(colorize_config_option
['min_nick_length'])
298 if not w
.config_boolean(colorize_config_option
['colorize_input']):
301 buffer = w
.current_buffer()
302 # Check if buffer has colorized nicks
303 if buffer not in colored_nicks
:
306 channel
= w
.buffer_get_string(buffer, 'name')
307 if channel
and channel
in ignore_channels
:
310 reset
= w
.color('reset')
312 for words
in valid_nick_re
.findall(line
):
314 # Check that nick is not ignored and longer than minimum length
315 if len(nick
) < min_length
or nick
in ignore_nicks
:
317 if nick
in colored_nicks
[buffer]:
318 nick_color
= colored_nicks
[buffer][nick
]
319 line
= line
.replace(nick
, '%s%s%s' % (nick_color
, nick
, reset
))
323 def populate_nicks(*args
):
324 ''' Fills entire dict with all nicks weechat can see and what color it has
330 buffers
= w
.infolist_get('buffer', '', '')
331 while w
.infolist_next(buffers
):
332 buffer_ptr
= w
.infolist_pointer(buffers
, 'pointer')
333 my_nick
= w
.buffer_get_string(buffer_ptr
, 'localvar_nick')
334 nicklist
= w
.infolist_get('nicklist', buffer_ptr
, '')
335 while w
.infolist_next(nicklist
):
336 if buffer_ptr
not in colored_nicks
:
337 colored_nicks
[buffer_ptr
] = {}
339 if w
.infolist_string(nicklist
, 'type') != 'nick':
342 nick
= w
.infolist_string(nicklist
, 'name')
343 nick_color
= colorize_nick_color(nick
, my_nick
)
345 colored_nicks
[buffer_ptr
][nick
] = nick_color
347 w
.infolist_free(nicklist
)
349 w
.infolist_free(buffers
)
351 return w
.WEECHAT_RC_OK
353 def add_nick(data
, signal
, type_data
):
354 ''' Add nick to dict of colored nicks '''
357 # Nicks can have , in them in some protocols
358 splitted
= type_data
.split(',')
359 pointer
= splitted
[0]
360 nick
= ",".join(splitted
[1:])
361 if pointer
not in colored_nicks
:
362 colored_nicks
[pointer
] = {}
364 my_nick
= w
.buffer_get_string(pointer
, 'localvar_nick')
365 nick_color
= colorize_nick_color(nick
, my_nick
)
367 colored_nicks
[pointer
][nick
] = nick_color
369 return w
.WEECHAT_RC_OK
371 def remove_nick(data
, signal
, type_data
):
372 ''' Remove nick from dict with colored nicks '''
375 # Nicks can have , in them in some protocols
376 splitted
= type_data
.split(',')
377 pointer
= splitted
[0]
378 nick
= ",".join(splitted
[1:])
380 if pointer
in colored_nicks
and nick
in colored_nicks
[pointer
]:
381 del colored_nicks
[pointer
][nick
]
383 return w
.WEECHAT_RC_OK
385 def update_blacklist(*args
):
386 ''' Set the blacklist for channels and nicks. '''
387 global ignore_channels
, ignore_nicks
388 ignore_channels
= w
.config_string(colorize_config_option
['blacklist_channels']).split(',')
389 ignore_nicks
= w
.config_string(colorize_config_option
['blacklist_nicks']).split(',')
390 return w
.WEECHAT_RC_OK
392 if __name__
== "__main__":
393 if w
.register(SCRIPT_NAME
, SCRIPT_AUTHOR
, SCRIPT_VERSION
, SCRIPT_LICENSE
,
394 SCRIPT_DESC
, "", ""):
395 colorize_config_init()
396 colorize_config_read()
398 # Run once to get data ready
402 w
.hook_signal('nicklist_nick_added', 'add_nick', '')
403 w
.hook_signal('nicklist_nick_removed', 'remove_nick', '')
404 w
.hook_modifier('weechat_print', 'colorize_cb', '')
405 # Hook config for changing colors
406 w
.hook_config('weechat.color.chat_nick_colors', 'populate_nicks', '')
407 w
.hook_config('weechat.look.nick_color_hash', 'populate_nicks', '')
408 # Hook for working togheter with other scripts (like colorize_lines)
409 w
.hook_modifier('colorize_nicks', 'colorize_cb', '')
410 # Hook for modifying input
411 w
.hook_modifier('250|input_text_display', 'colorize_input_cb', '')
412 # Hook for updating blacklist (this could be improved to use fnmatch)
413 weechat
.hook_config('%s.look.blacklist*' % SCRIPT_NAME
, 'update_blacklist', '')