-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheutmux.py
More file actions
489 lines (424 loc) · 18.6 KB
/
Copy patheutmux.py
File metadata and controls
489 lines (424 loc) · 18.6 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env python3
"""Provide utility functions for Tmux option reading and writing."""
import os
import yaml
from peelee import color
from utils import get_tmux_option, run_shell_command
UTF_8 = "utf-8"
EMPTY = ""
# file names and extensions
DEFAULT_CONFIG_FILE = "eutmux.yaml"
DEFAULT_THEME_FILE = "eutmux.theme.yaml"
THEME_FILE_EXTENSION = ".theme.yaml"
# tmux options
STYLE_START = "#["
STYLE_END = "]"
def get(_dict, key, default):
"""
'Rewrite' get method of dict.
When value is None or Empty, use default. Should be used in theme
configuration only. Lower theme configuration could reuse upper
level them configuration, then it's possible to configure less
items. However, user configuration should be able to overwrite theme
configuration. For example, if theme defined icons, but user don't
want to use icon, then they can set icon as Empty.
"""
value = _dict.get(key)
if value is None:
value = default
elif isinstance(value, str) and value.strip() == EMPTY:
value = default
return value
class Theme(dict):
"""Wrapper for theme configuration."""
def __init__(self, theme_config: dict):
self.terminal = theme_config.get("terminal")
self.status_line = theme_config.get("status_line")
self.status_left = ThemeStatusLeft(theme_config)
self.active_window = ThemeWindow(
self.status_line, theme_config.get("window").get("active")
)
self.inactive_window = ThemeWindow(
self.status_line, theme_config.get("window").get("inactive")
)
self.window = {
"active": self.active_window,
"inactive": self.inactive_window,
}
self.status_right = ThemeStatusRight(theme_config)
super().__init__(
terminal=self.terminal,
status_line=self.status_line,
status_left=self.status_left,
window=self.window,
status_right=self.status_right,
)
class ThemeComponent(dict):
"""Base class for theme section configuration."""
def _load_common(self, section, status_line):
"""Load fields common to all theme sections."""
self.fg_icon = get(section, "fg_icon", status_line.get("foreground"))
self.bg_icon = get(section, "bg_icon", status_line.get("background"))
self.fg_decorator = get(section, "fg_decorator", status_line.get("foreground"))
self.bg_decorator = get(section, "bg_decorator", status_line.get("background"))
self.icon = get(section, "icon", status_line.get("left_icon"))
self.decorator = get(section, "decorator", status_line.get("left_decorator"))
self.style = get(section, "style", status_line.get("style"))
def _common_dict(self):
"""Return common fields as dict."""
return dict(
fg_icon=self.fg_icon,
bg_icon=self.bg_icon,
fg_decorator=self.fg_decorator,
bg_decorator=self.bg_decorator,
icon=self.icon,
decorator=self.decorator,
style=self.style,
)
class ThemeStatusLeft(ThemeComponent):
"""Wrapper for status_left configuration."""
def __init__(self, theme_config):
"""Constructor."""
status_line = theme_config.get("status_line")
status_left = theme_config.get("status_left")
self.fg_format = get(status_left, "fg_format", status_line.get("foreground"))
self.bg_format = get(status_left, "bg_format", status_line.get("background"))
self.fg_format = color.convert_to_best_light_color(
self.fg_format, self.bg_format
)
self._load_common(status_left, status_line)
super().__init__(
fg_format=self.fg_format,
bg_format=self.bg_format,
**self._common_dict(),
)
class ThemeWindow(ThemeComponent):
"""Wrapper for window configuration."""
def __init__(self, status_line_theme_config, window_theme_config):
"""Constructor."""
self.fg_window = get(
window_theme_config,
"fg_window",
status_line_theme_config.get("foreground"),
)
self.bg_window = get(
window_theme_config,
"bg_window",
status_line_theme_config.get("background"),
)
self.fg_window_index = get(
window_theme_config,
"fg_window_index",
status_line_theme_config.get("foreground"),
)
self.bg_window_index = get(
window_theme_config,
"bg_window_index",
status_line_theme_config.get("background"),
)
self._load_common(window_theme_config, status_line_theme_config)
super().__init__(
fg_window=self.fg_window,
bg_window=self.bg_window,
fg_window_index=self.fg_window_index,
bg_window_index=self.bg_window_index,
**self._common_dict(),
)
class ThemeStatusRight(ThemeComponent):
"""Wrapper for status_right configuration."""
def __init__(self, theme_config):
"""Constructor."""
status_line = theme_config.get("status_line")
status_right = theme_config.get("status_right")
self.fg_format = get(status_right, "fg_format", status_line.get("foreground"))
self.bg_format = get(status_right, "bg_format", status_line.get("background"))
self.bg_format = color.convert_to_best_dark_color(
self.bg_format, self.fg_format
)
self._load_common(status_right, status_line)
super().__init__(
fg_format=self.fg_format,
bg_format=self.bg_format,
**self._common_dict(),
)
class Constructor:
"""Constructor for status line component."""
def __init__(self, eutmux: dict, theme: Theme):
"""Constructor."""
self._config = eutmux
self.general = eutmux.get("general")
self.terminal = eutmux.get("terminal", theme.get("terminal"))
self.status_line = eutmux.get("status_line", theme.get("status_line"))
self.foreground = self.status_line.get("foreground")
self.background = self.status_line.get("background")
self.status_left = eutmux.get("status_left") or {}
self.window = eutmux.get("window") or {}
self.status_right = eutmux.get("status_right") or {}
self.theme = theme
def produce_general_options_commands(self):
"""Produce general options."""
if self.general is None:
return None
general_commands = []
# global options
for name, value in self.general.get("options").items():
if name.startswith("_"):
name = f"@{name.lstrip('_')}"
general_commands.append(f"set-option -gq {name} '{value}'")
# window options
for name, value in (self.general.get("window") or {}).items():
general_commands.append(f"set-window-option -gq {name} '{value}'")
# styles options
for name, component in self.general.get("styles").items():
if name == "option-commands":
continue
foreground = component.get("fg", self.terminal.get("foreground"))
background = component.get("bg", self.terminal.get("background"))
style = component.get("style", self.status_line.get("style"))
style_command = self.get_style_command(foreground, background, style, name)
if style_command is not None:
general_commands.append(style_command)
# commands options
for command in self.general.get("commands"):
general_commands.append(command)
return ";".join(general_commands)
def produce_status_line(self):
"""Produce status line option."""
fg_status_line = self.foreground
bg_status_line = self.background
return f"fg={fg_status_line},bg={bg_status_line}"
def _produce_status_section(self, section, theme_section, order="idf"):
"""Produce status section option string.
Args:
section: config section dict (status_left or status_right values)
theme_section: theme defaults for the section
order: component order - 'idf' (icon,decorator,format) or 'dif'
"""
parts = []
for component in section.values():
if not component.get("enabled", "on"):
continue
icon = component.get("icon", theme_section.get("icon"))
decorator = component.get("decorator", theme_section.get("decorator"))
fg_format = component.get("fg_format", theme_section.get("fg_format"))
bg_format = component.get("bg_format", theme_section.get("bg_format"))
fg_icon = component.get("fg_icon", theme_section.get("fg_icon"))
bg_icon = component.get("bg_icon", theme_section.get("bg_icon"))
fg_decorator = component.get(
"fg_decorator", theme_section.get("fg_decorator")
)
bg_decorator = component.get(
"bg_decorator", theme_section.get("bg_decorator")
)
style = component.get("style", theme_section.get("style"))
_format = component.get("format", EMPTY)
fmt = self.get_style_for_option(fg_format, bg_format, style, _format)
ico = self.get_style_for_option(fg_icon, bg_icon, style, icon)
dec = self.get_style_for_option(
fg_decorator, bg_decorator, style, decorator
)
if order == "idf":
parts.append(f"{ico}{dec}{fmt}")
else:
parts.append(f"{dec}{ico}{fmt}")
return " ".join(parts)
def produce_status_left(self):
"""Produce status left option string."""
return self._produce_status_section(
self.status_left, self.theme.status_left, order="idf"
)
def produce_status_right(self):
"""Produce status right tmux options string.
If widgets are configured in eutmux.yaml, appends widget output
via shell command substitution.
"""
base_status = self._produce_status_section(
self.status_right, self.theme.status_right, order="dif"
)
# Append widget system output if configured
if hasattr(self, "_config") and self._config.get("widgets", {}).get(
"status_right"
):
widgets_script = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "widgets.py"
)
base_status += f" #(python3 {widgets_script} status_right)"
return base_status
def produce_window(self):
"""Return tuple with active window and inactive window option strings."""
windows = {}
for name, component in self.window.items():
style = component.get("style", self.theme.window.get(name).get("style"))
icon = component.get("icon", self.theme.window.get(name).get("icon"))
window_name = component.get(
"window_name", self.theme.window.get(name).get("window_name")
)
window_index = component.get(
"window_index",
self.theme.window.get(name).get("window_index"),
)
decorator = component.get(
"decorator", self.theme.window.get(name).get("decorator")
)
fg_icon = component.get(
"fg_icon", self.theme.window.get(name).get("fg_icon")
)
bg_icon = component.get(
"bg_icon", self.theme.window.get(name).get("bg_icon")
)
fg_decorator = component.get(
"fg_decorator", self.theme.window.get(name).get("fg_decorator")
)
bg_decorator = component.get(
"bg_decorator", self.theme.window.get(name).get("bg_decorator")
)
fg_window = component.get(
"fg_window", self.theme.window.get(name).get("fg_window")
)
bg_window = component.get(
"bg_window", self.theme.window.get(name).get("bg_window")
)
fg_window_index = component.get(
"fg_window_index",
self.theme.window.get(name).get("fg_window_index"),
)
bg_window_index = component.get(
"bg_window_index",
self.theme.window.get(name).get("bg_window_index"),
)
window_style = self.get_style_for_option(
fg_window, bg_window, style, window_name
)
window_index_style = self.get_style_for_option(
fg_window_index, bg_window_index, style, window_index
)
icon_style = self.get_style_for_option(fg_icon, bg_icon, style, icon)
decorator_style = self.get_style_for_option(
fg_decorator, bg_decorator, style, decorator
)
component_value = (
f"{window_style}{window_index_style}{icon_style}{decorator_style} "
)
windows[name] = component_value
return windows
def get_style_for_option(self, foreground, background, style, option):
"""Construct style string with foreground and background."""
if option is None:
option = ""
pieces = []
if foreground:
pieces.append(f"fg={foreground}")
if background:
pieces.append(f"bg={background}")
pieces.append(style)
_style = f"{STYLE_START}{','.join(pieces)}{STYLE_END}{option}"
pieces = []
if foreground:
pieces.append(f"fg={self.foreground}")
if background:
pieces.append(f"bg={self.background}")
pieces.append(style)
_default_style = f"{STYLE_START}{','.join(pieces)}{STYLE_END}"
return f"{_style}{_default_style}"
def get_style_command(self, foreground, background, style, style_name):
"""Return tmux set style option command.
Parameters:
foreground: The foreground color.
background: The background color.
style: The style.
style_name: The name of the style.
e.g. status-style, window-status-current-format, window-status-format
Return:
The tmux command string to set the style.
Example:
set-option -gq status-style 'fg=green,bg=black,italics'
"""
style_content = None
has_foreground = foreground and foreground.strip() != EMPTY
has_background = background and background.strip() != EMPTY
if has_foreground and has_background:
foreground = color.convert_to_best_light_color(foreground, background)
if foreground and foreground.strip() != EMPTY:
style_content = f"fg={foreground},"
if background and background.strip() != EMPTY:
style_content = f"{style_content}bg={background},"
if style and style.strip() != EMPTY:
style_content = f"{style_content}{style}"
if style_content is None:
return None
return f"set-option -gq {style_name} '{style_content}'"
def produce_option_command(self, option, value):
"""Return tmux set option command."""
return f"set-option -gq {option} '{value}'"
def produce_option_commands(self):
"""Return all tmux set option commands."""
status_line = self.produce_status_line()
status_left = self.produce_status_left()
window = self.produce_window()
status_right = self.produce_status_right()
status_line_cmd = self.produce_option_command("status-style", status_line)
status_left_cmd = self.produce_option_command("status-left", status_left)
active_window_cmd = self.produce_option_command(
"window-status-current-format", window["active"]
)
inactive_window_cmd = self.produce_option_command(
"window-status-format", window["inactive"]
)
status_right_cmd = self.produce_option_command("status-right", status_right)
general_commands = self.produce_general_options_commands()
option_commands = []
option_commands.append(general_commands)
option_commands.append(status_line_cmd)
option_commands.append(status_left_cmd)
option_commands.append(active_window_cmd)
option_commands.append(inactive_window_cmd)
option_commands.append(status_right_cmd)
return option_commands
def init(config_file=DEFAULT_CONFIG_FILE):
"""Load config file, overwrite options by value from tmux.conf."""
# user can set customized config file under EUTMUX_CONFIG_HOME
xdg_config_home = os.getenv("XDG_CONFIG_HOME", f'{os.getenv("HOME")}/.config')
eutmux_config_home = f"{xdg_config_home}/eutmux"
_config_file = f"{eutmux_config_home}/{config_file}"
if os.path.exists(_config_file):
config_file = _config_file
eutmux = {}
set_option_commands = []
eutmux_dynamic_config_file_name = get_tmux_option(
"@eutmux_dynamic_config_file_name", config_file
)
eutmux_workdir = os.getenv("EUTMUX_WORKDIR", os.curdir)
os.chdir(eutmux_workdir)
eutmux_dynamic_config_file_path = (
f"{eutmux_config_home}/{eutmux_dynamic_config_file_name}"
)
with open(eutmux_dynamic_config_file_path, "r", encoding=UTF_8) as config:
eutmux = yaml.safe_load(config)
# if specified theme doesn't have corresponding file, then fall-back to
# the default theme - eutmux theme.
theme_name = eutmux.get("theme", "eutmux")
# if dynamic theme is set, then use dynamic theme.
dynamic_theme_name = get_tmux_option("@eutmux_dynamic_theme_name", theme_name)
theme_filename = f"{dynamic_theme_name}{THEME_FILE_EXTENSION}"
# if dynamic theme file doesn't exist under project, then check if it
# exists under EUTMUX_CONFIG_HOME, if not, then fall-back to default them -
# eutmux theme, otherwise, load the theme file from EUTMUX_CONFIG_HOME
if not os.path.exists(theme_filename):
if os.path.exists(f"{eutmux_config_home}/{theme_filename}"):
theme_filename = f"{eutmux_config_home}/{theme_filename}"
else:
theme_filename = DEFAULT_THEME_FILE
with open(theme_filename, "r", encoding=UTF_8) as theme_file:
theme_config = yaml.safe_load(theme_file)
theme = Theme(theme_config)
constructor = Constructor(eutmux, theme)
set_option_commands = constructor.produce_option_commands()
return ";".join(set_option_commands)
def main():
"""Run."""
set_option_commands = init()
if set_option_commands:
for command in set_option_commands.split(";"):
run_shell_command(f"tmux {command}")
if __name__ == "__main__":
main()