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