summaryrefslogtreecommitdiffstats
path: root/powerline/bindings/tmux/__init__.py
blob: eb84e7a79c3df55ec2d07d1ee4f6c0b0c4924b85 (plain)
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
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)

import re
import os
import subprocess

from collections import namedtuple

from powerline.lib.shell import run_cmd


TmuxVersionInfo = namedtuple('TmuxVersionInfo', ('major', 'minor', 'suffix'))


def get_tmux_executable_name():
	'''Returns tmux executable name

	It should be defined in POWERLINE_TMUX_EXE environment variable, otherwise 
	it is simply “tmux”.
	'''

	return os.environ.get('POWERLINE_TMUX_EXE', 'tmux')


def _run_tmux(runner, args):
	return runner([get_tmux_executable_name()] + list(args))


def run_tmux_command(*args):
	'''Run tmux command, ignoring the output'''
	_run_tmux(subprocess.check_call, args)


def get_tmux_output(pl, *args):
	'''Run tmux command and return its output'''
	return _run_tmux(lambda cmd: run_cmd(pl, cmd), args)


def set_tmux_environment(varname, value, remove=True):
	'''Set tmux global environment variable

	:param str varname:
		Name of the variable to set.
	:param str value:
		Variable value.
	:param bool remove:
		True if variable should be removed from the environment prior to 
		attaching any client (runs ``tmux set-environment -r {varname}``).
	'''
	run_tmux_command('set-environment', '-g', varname, value)
	if remove:
		try:
			run_tmux_command('set-environment', '-r', varname)
		except subprocess.CalledProcessError:
			# On tmux-2.0 this command may fail for whatever reason. Since it is 
			# critical just ignore the failure.
			pass


def source_tmux_file(fname):
	'''Source tmux configuration file

	:param str fname:
		Full path to the sourced file.
	'''
	run_tmux_command('source', fname)


NON_DIGITS = re.compile('[^0-9]+')
DIGITS = re.compile('[0-9]+')
NON_LETTERS = re.compile('[^a-z]+')


def get_tmux_version(pl):
	version_string = get_tmux_output(pl, '-V')
	_, version_string = version_string.split(' ')
	version_string = version_string.strip()
	if version_string == 'master':
		return TmuxVersionInfo(float('inf'), 0, version_string)
	major, minor = version_string.split('.')
	major = NON_DIGITS.subn('', major)[0]
	suffix = DIGITS.subn('', minor)[0] or None
	minor = NON_DIGITS.subn('', minor)[0]
	return TmuxVersionInfo(int(major), int(minor), suffix)