forked from Granitosaurus/macos-compose
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convcompose.py
120 lines (108 loc) · 3.01 KB
/
convcompose.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import click
import re
from click import echo
KEY_MAP = {
'bracketleft': '[',
'bracketright': ']',
'parenleft': '(',
'parenright': ')',
'Multi_key': '',
'period': '.',
'minus': '-',
'plus': '+',
'dollar': '$',
'at': '@',
'exclam': '!',
'less': '<',
'greater': '>',
'slash': '/',
'backslash': '\\',
'question': '?',
'space': ' ',
'equal': '=',
'asciitilde': '~',
'numbersign': '#',
'asterisk': '*',
'colon': ':',
'semicolon': ';',
'percent': '%',
'underscore': '_',
'asciicircum': '^',
'comma': ',',
'apostrophe': "'",
'quotedbl': '"',
'bar': "|",
'grave': "`",
'ampersand': "&",
'braceright': "}",
'braceleft': "{",
'KP_Multiply': "*",
'exclamdown': "¡",
'questiondown': "¿",
}
def quote(char):
"""
quote yaml key
- replaces `\` to `\\`
- replace `"` to `\"`
"""
char = char.replace('\\', '\\\\')
char = char.replace('"', '\\"')
return char
def remap_keys(keys):
"""remap xcompose keys to unicode characters"""
result = []
for key in keys:
key = key.strip('<>')
if len(key) > 1:
# convert unicode hexes to unicode characters
# e.g. U220B == ∋
if key.startswith('U') and any(c.isdigit() for c in key):
key = key.split('U', 1)[1]
key = chr(int(key, 16))
elif key not in KEY_MAP:
raise ValueError(f'unsupported keymap: {key}')
result.append(KEY_MAP.get(key, key))
return result
@click.group()
def main():
"""convert alternative formats to yaml key: value format"""
pass
@main.command()
@click.argument('files', type=click.File(), nargs=-1)
@click.option('-c', '--keep-comments', is_flag=True, help='keep inline comments')
def xcompose(files, keep_comments):
"""
Convert xcompose file, that follows format like:
<Multi_key> <parenleft> <period> <1> <parenright>: "⑴"
"""
# e.g. < Multi_key > < parenleft > < period > < 1 > < parenright >: "⑴"
for file in files:
for row in file:
row = row.strip()
if not row:
continue
if row.startswith('#') or row.startswith('include'):
continue
if '#' in row:
row, comment = row.split('#', 1)
else:
comment = ''
try:
from_, to = row.split(':', 1)
except ValueError:
echo(f'malformed line:\n{row}', err=True)
continue
from_ = re.split(r'\s+', from_)
try:
from_ = ''.join(remap_keys(from_))
except ValueError as e:
echo(f'{e}; skipping:\n {row}', err=True)
continue
to = to.split('"')[1]
value = f'"{quote(from_)}": "{quote(to)}"'
if keep_comments and comment:
value += f' #{comment}'
echo(value)
if __name__ == '__main__':
main()