]> git.gir.st - ircpipe.git/blob - contrib/highlight
highlight: make sure own nick is delimetered properly
[ircpipe.git] / contrib / highlight
1 #!/usr/bin/python3
2
3 import re, sys
4
5 def parse(line): #-> [nick, user, host], command, arguments
6 prefix, params = b"", []
7 command, arguments = None, []
8 nick, user, host = None, None, None
9
10 line = line.rstrip(b"\r\n")
11 # handle prefix:
12 if line.startswith(b":"):
13 prefix, line = line.split(b" ", 1)
14 # handle command and arguments:
15 while b" " in line and not line.startswith(b":"):
16 word, line = line.split(b" ", 1)
17 params += [word]
18 # handle final parameter:
19 params += [line.removeprefix(b":")]
20
21 if params:
22 # note: command may also be a numeric reply
23 command, *arguments = params
24
25 if b"!" in prefix and b"@" in prefix:
26 nick, rest = prefix.removeprefix(b":").split(b"!", 1)
27 user, host = rest.split(b"@", 1)
28 elif prefix: # server
29 host = prefix.removeprefix(b":")
30
31 return [nick, user, host], command, arguments
32
33 DIM = b"\033[0;2m"
34 BOLD = b"\033[0;1m"
35 RESET = b"\033[0m"
36 REV = b"\033[0;7m"
37
38 def say(*args):
39 sys.stdout.buffer.write(b"".join(args)+b"\n")
40 sys.stdout.buffer.flush()
41
42 myself = None
43 for line in sys.stdin.buffer:
44 [nick, user, host], command, arguments = parse(line)
45
46 if command in (b"PRIVMSG", b"NOTICE") and len(arguments) == 2 and nick:
47 chan, msg = arguments
48 nick_start = len(b":")
49 nick_end = nick_start+len(nick)
50 cmd_start = nick_end+len(b"!")+len(user)+len(b"@")+len(host)+len(b" ")
51 cmd_end = cmd_start+len(command)
52 chan_start = cmd_end+len(b" ")
53 chan_end = chan_start+len(chan)
54 msg_start = chan_end+len(b" ")
55 msg_end = msg_start+len(msg)
56 if line[msg_start] == ord(':'):
57 msg_start +=1
58 msg_end +=1
59
60 hi_start, hi_end = msg_start, msg_start
61 if m := re.search(rb"\b%s\b" % re.escape(myself), msg):
62 hi_start = msg_start + m.start(0)
63 hi_end = msg_start + m.end(0)
64
65 say(
66 DIM, line[:nick_start],
67 BOLD, line[nick_start:nick_end],
68 DIM, line[nick_end:chan_start],
69 BOLD, line[chan_start:chan_end],
70 DIM, line[chan_end:msg_start],
71 RESET, line[msg_start:hi_start],
72 REV, line[hi_start:hi_end],
73 RESET, line[hi_end:msg_end],
74 REV, line[msg_end:].rstrip(b"\r\n"),
75 RESET)
76 elif command in (b"PING", b"PONG"):
77 pass # hide
78 else:
79 if command == b"001" and arguments:
80 myself = arguments[0] # store own username for later highlighting it
81
82 say(DIM, line.rstrip(b"\r\n"), RESET)
Imprint / Impressum