or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

exceptions.mdindex.mdpane.mdserver.mdsession.mdutilities.mdwindow.md

utilities.mddocs/

0

# Utilities

1

2

libtmux provides utility functions for version checking, tmux compatibility validation, session name validation, and other helper operations. These utilities support the core functionality and provide tools for applications built on libtmux.

3

4

## Capabilities

5

6

### Version Detection and Compatibility

7

8

Functions to detect tmux version and check compatibility requirements.

9

10

```python { .api }

11

def get_version() -> LooseVersion:

12

"""

13

Return tmux version.

14

15

If tmux is built from git master, the version returned will be the latest

16

version appended with -master, e.g. 2.4-master.

17

18

If using OpenBSD's base system tmux, the version will have -openbsd

19

appended to the latest version, e.g. 2.4-openbsd.

20

21

Returns:

22

LooseVersion object containing tmux version

23

24

Raises:

25

TmuxCommandNotFound: If tmux binary not found

26

LibTmuxException: If version detection fails

27

VersionTooLow: If tmux version is too old

28

"""

29

30

def has_version(version: str) -> bool:

31

"""

32

Check if current tmux version matches exactly.

33

34

Parameters:

35

- version: Version string to match

36

37

Returns:

38

True if versions match exactly

39

"""

40

41

def has_gt_version(version: str) -> bool:

42

"""

43

Check if current tmux version is greater than specified version.

44

45

Parameters:

46

- version: Version string to compare against

47

48

Returns:

49

True if current version is greater

50

"""

51

52

def has_gte_version(version: str) -> bool:

53

"""

54

Check if current tmux version is greater than or equal to specified version.

55

56

Parameters:

57

- version: Version string to compare against

58

59

Returns:

60

True if current version is greater than or equal

61

"""

62

63

def has_lte_version(version: str) -> bool:

64

"""

65

Check if current tmux version is less than or equal to specified version.

66

67

Parameters:

68

- version: Version string to compare against

69

70

Returns:

71

True if current version is less than or equal

72

"""

73

74

def has_lt_version(version: str) -> bool:

75

"""

76

Check if current tmux version is less than specified version.

77

78

Parameters:

79

- version: Version string to compare against

80

81

Returns:

82

True if current version is less than

83

"""

84

85

def has_minimum_version(raises: bool = True) -> bool:

86

"""

87

Return True if tmux meets version requirement. Version >1.8 or above.

88

89

Parameters:

90

- raises: Raise exception if below minimum version requirement

91

92

Returns:

93

True if tmux meets minimum required version

94

95

Raises:

96

VersionTooLow: If tmux version below minimum required for libtmux and raises=True

97

"""

98

```

99

100

### Library Information

101

102

Functions to get libtmux library version and metadata.

103

104

```python { .api }

105

def get_libtmux_version() -> LooseVersion:

106

"""

107

Return libtmux version is a PEP386 compliant format.

108

109

Returns:

110

LooseVersion object containing libtmux version

111

"""

112

```

113

114

### Session Name Validation

115

116

Functions to validate and sanitize tmux session names.

117

118

```python { .api }

119

def session_check_name(session_name: str | None) -> None:

120

"""

121

Raise exception session name invalid, modeled after tmux function.

122

123

tmux(1) session names may not be empty, or include periods or colons.

124

These delimiters are reserved for noting session, window and pane.

125

126

Parameters:

127

- session_name: Name of session

128

129

Raises:

130

BadSessionName: Invalid session name

131

"""

132

```

133

134

### Error Handling Utilities

135

136

Functions to process and handle tmux command errors.

137

138

```python { .api }

139

def handle_option_error(error: str) -> type[OptionError]:

140

"""

141

Raise exception if error in option command found.

142

143

In tmux 3.0, show-option and show-window-option return invalid option instead of

144

unknown option.

145

146

In tmux >2.4, there are 3 different types of option errors:

147

- unknown option

148

- invalid option

149

- ambiguous option

150

151

In tmux <2.4, unknown option was the only option.

152

153

All errors raised will have the base error of OptionError. So to

154

catch any option error, use except OptionError.

155

156

Parameters:

157

- error: Error response from subprocess call

158

159

Raises:

160

OptionError, UnknownOption, InvalidOption, AmbiguousOption

161

"""

162

```

163

164

### Command Execution Utilities

165

166

Low-level command execution and process management.

167

168

```python { .api }

169

class tmux_cmd:

170

"""

171

Run any tmux(1) command through subprocess.

172

173

Attributes:

174

- cmd: Command that was executed

175

- stdout: Command stdout as list of strings

176

- stderr: Command stderr as list of strings

177

- returncode: Process return code

178

- process: Subprocess.Popen object

179

"""

180

181

def __init__(self, *args: t.Any) -> None:

182

"""

183

Execute tmux command.

184

185

Parameters:

186

- *args: Command arguments (converted to strings)

187

188

Raises:

189

TmuxCommandNotFound: If tmux binary not found in PATH

190

"""

191

```

192

193

### Environment Variable Management

194

195

Mixin class providing environment variable operations for sessions.

196

197

```python { .api }

198

class EnvironmentMixin:

199

"""Mixin for manager session and server level environment variables in tmux."""

200

201

def __init__(self, add_option: str | None = None) -> None:

202

"""Initialize mixin with optional add_option for command scope."""

203

204

def set_environment(self, name: str, value: str) -> None:

205

"""

206

Set environment $ tmux set-environment <name> <value>.

207

208

Parameters:

209

- name: Environment variable name (e.g., 'PATH')

210

- value: Environment variable value

211

212

Raises:

213

ValueError: If tmux command returns error

214

"""

215

216

def unset_environment(self, name: str) -> None:

217

"""

218

Unset environment variable $ tmux set-environment -u <name>.

219

220

Parameters:

221

- name: Environment variable name (e.g., 'PATH')

222

223

Raises:

224

ValueError: If tmux command returns error

225

"""

226

227

def remove_environment(self, name: str) -> None:

228

"""

229

Remove environment variable $ tmux set-environment -r <name>.

230

231

Parameters:

232

- name: Environment variable name (e.g., 'PATH')

233

234

Raises:

235

ValueError: If tmux command returns error

236

"""

237

238

def show_environment(self) -> dict[str, bool | str]:

239

"""

240

Show environment $ tmux show-environment -t [session].

241

242

Return dict of environment variables for the session.

243

244

Returns:

245

Dictionary of environmental variables

246

"""

247

248

def getenv(self, name: str) -> str | bool | None:

249

"""

250

Show environment variable $ tmux show-environment -t [session] <name>.

251

252

Return the value of a specific variable if the name is specified.

253

254

Parameters:

255

- name: Environment variable name (e.g., 'PATH')

256

257

Returns:

258

Value of environment variable or None if not found

259

"""

260

```

261

262

### Constants

263

264

Version compatibility and feature support constants.

265

266

```python { .api }

267

TMUX_MIN_VERSION: str = "1.8"

268

"""Minimum version of tmux required to run libtmux."""

269

270

TMUX_MAX_VERSION: str = "3.4"

271

"""Most recent version of tmux supported."""

272

273

# Type definitions

274

SessionDict = dict[str, t.Any]

275

WindowDict = dict[str, t.Any]

276

WindowOptionDict = dict[str, t.Any]

277

PaneDict = dict[str, t.Any]

278

```

279

280

## Usage Examples

281

282

### Version Checking

283

284

```python

285

import libtmux.common as common

286

287

# Get current tmux version

288

try:

289

version = common.get_version()

290

print(f"tmux version: {version}")

291

except TmuxCommandNotFound:

292

print("tmux not found")

293

294

# Check version compatibility

295

if common.has_minimum_version("2.0"):

296

print("tmux supports modern features")

297

else:

298

print("tmux version is too old")

299

300

# Feature-specific version checks

301

if common.has_gte_version("2.1"):

302

# Use features introduced in 2.1+

303

pass

304

305

if common.has_lt_version("3.0"):

306

# Handle older tmux versions

307

pass

308

```

309

310

### Session Name Validation

311

312

```python

313

import libtmux.common as common

314

from libtmux.exc import BadSessionName

315

316

session_names = ["valid-name", "invalid:name", "another$bad", "good_name"]

317

318

for name in session_names:

319

try:

320

validated = common.session_check_name(name)

321

print(f"'{name}' -> '{validated}' (valid)")

322

except BadSessionName as e:

323

print(f"'{name}' is invalid: {e}")

324

```

325

326

### Command Execution

327

328

```python

329

import libtmux.common as common

330

331

# Execute raw tmux command

332

cmd = common.tmux_cmd(['list-sessions'])

333

if cmd.returncode == 0:

334

print("Sessions:")

335

for line in cmd.stdout:

336

print(f" {line}")

337

else:

338

print("Error:", cmd.stderr)

339

```

340

341

### Library Information

342

343

```python

344

import libtmux.common as common

345

346

# Get library version

347

lib_version = common.get_libtmux_version()

348

tmux_version = common.get_version()

349

350

print(f"libtmux version: {lib_version}")

351

print(f"tmux version: {tmux_version}")

352

353

# Check compatibility matrix

354

min_version = common.TMUX_MIN_VERSION

355

max_version = common.TMUX_MAX_VERSION

356

print(f"Supported tmux versions: {min_version} - {max_version}")

357

```

358

359

### Environment Management Usage

360

361

```python

362

import libtmux

363

364

# EnvironmentMixin is used by Session class

365

server = libtmux.Server()

366

session = server.new_session('env_test')

367

368

# Set environment variables

369

session.set_environment('PROJECT_ROOT', '/home/user/project')

370

session.set_environment('DEBUG_MODE', '1')

371

372

# Get environment variables

373

project_root = session.getenv('PROJECT_ROOT')

374

all_env = session.show_environment()

375

376

print(f"Project root: {project_root}")

377

print("All environment variables:")

378

for key, value in all_env.items():

379

print(f" {key}={value}")

380

381

# Clean up

382

session.unset_environment('DEBUG_MODE')

383

```

384

385

### Error Handling Integration

386

387

```python

388

import libtmux.common as common

389

from libtmux.exc import UnknownOption, InvalidOption

390

391

# Example of option error handling

392

try:

393

# This would normally be called internally by libtmux

394

common.handle_option_error(

395

"unknown option: invalid-option",

396

"invalid-option",

397

"some-value"

398

)

399

except UnknownOption as e:

400

print(f"Option '{e.option}' is not recognized by tmux")

401

402

try:

403

common.handle_option_error(

404

"invalid value for option",

405

"mouse",

406

"invalid-value"

407

)

408

except InvalidOption as e:

409

print(f"Invalid value '{e.value}' for option '{e.option}'")

410

```

411

412

### Comprehensive Utility Usage

413

414

```python

415

import libtmux

416

import libtmux.common as common

417

from libtmux.exc import LibTmuxException

418

419

def setup_development_environment():

420

"""Set up a development environment with version checking."""

421

422

# Check tmux availability and version

423

try:

424

version = common.get_version()

425

print(f"Found tmux version: {version}")

426

427

if not common.has_minimum_version("2.0"):

428

print("Warning: tmux version may not support all features")

429

430

except Exception as e:

431

print(f"tmux not available: {e}")

432

return None

433

434

# Validate session name

435

try:

436

session_name = common.session_check_name("dev-environment")

437

except Exception as e:

438

print(f"Invalid session name: {e}")

439

session_name = "dev_environment"

440

441

# Create session with environment

442

try:

443

server = libtmux.Server()

444

session = server.new_session(session_name)

445

446

# Set up environment

447

session.set_environment('DEV_MODE', '1')

448

session.set_environment('TMUX_VERSION', version)

449

session.set_environment('LIBTMUX_VERSION', common.get_libtmux_version())

450

451

print(f"Development environment '{session_name}' created successfully")

452

return session

453

454

except LibTmuxException as e:

455

print(f"Failed to create development environment: {e}")

456

return None

457

458

# Usage

459

dev_session = setup_development_environment()

460

if dev_session:

461

print("Development environment ready!")

462

```