or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

completers.mdcompletion-engine.mdindex.mdscripts.mdshell-integration.mdutilities.md

utilities.mddocs/

0

# Utility Functions

1

2

Support functions for debugging, output control, and command line parsing during completion operations. These utilities help with development, troubleshooting, and advanced completion scenarios.

3

4

## Capabilities

5

6

### Debug and Output Functions

7

8

Functions for controlling output during completion and debugging completion issues.

9

10

```python { .api }

11

def debug(*args) -> None:

12

"""

13

Print debug information when _ARC_DEBUG environment variable is set.

14

15

Parameters:

16

- *args: Arguments to print to debug stream

17

18

Note: Only outputs when _ARC_DEBUG environment variable is present

19

"""

20

```

21

22

```python { .api }

23

def warn(*args) -> None:

24

"""

25

Print warning messages to stderr during completion.

26

27

Parameters:

28

- *args: Warning messages to display

29

30

This interrupts the user's command line interaction and should only

31

be used to indicate error conditions preventing completion.

32

"""

33

```

34

35

**Usage:**

36

37

```bash

38

# Enable debug output

39

export _ARC_DEBUG=1

40

my-script --<TAB> # Shows debug information

41

```

42

43

```python

44

# In custom completers

45

from argcomplete import debug, warn

46

47

class MyCompleter(BaseCompleter):

48

def __call__(self, prefix, **kwargs):

49

debug("MyCompleter called with prefix:", prefix)

50

51

try:

52

completions = self._get_completions(prefix)

53

debug("Generated completions:", completions)

54

return completions

55

except Exception as e:

56

warn(f"Completion failed: {e}")

57

return []

58

```

59

60

### Output Stream Control

61

62

Context manager for suppressing stderr during completion operations.

63

64

```python { .api }

65

@contextlib.contextmanager

66

def mute_stderr():

67

"""

68

Context manager to temporarily suppress stderr.

69

Used internally to prevent argparse error messages during completion.

70

"""

71

```

72

73

**Usage:**

74

75

```python

76

from argcomplete import mute_stderr

77

78

# Suppress error output during completion parsing

79

with mute_stderr():

80

try:

81

parser.parse_args(incomplete_args)

82

except SystemExit:

83

pass # Expected during completion

84

```

85

86

**Note:** `mute_stdout` is available in `argcomplete.io` but not exported in the main public API.

87

88

### Safe Actions Set

89

90

Set of argparse action classes that are safe to execute during completion.

91

92

```python { .api }

93

safe_actions: Set[Type[argparse.Action]]

94

```

95

96

**Usage:**

97

98

```python

99

from argcomplete import safe_actions

100

import argparse

101

102

# Check if an action is safe to execute during completion

103

def is_safe_action(action):

104

return action.__class__ in safe_actions

105

106

# Add custom safe actions

107

class MyCustomAction(argparse.Action):

108

def __call__(self, parser, namespace, values, option_string=None):

109

setattr(namespace, self.dest, values)

110

111

safe_actions.add(MyCustomAction)

112

```

113

114

### Command Line Parsing

115

116

Utility for parsing command lines while respecting shell quoting and word boundaries.

117

118

```python { .api }

119

def split_line(line: str, point: Optional[int] = None) -> Tuple[str, str, str, List[str], Optional[int]]:

120

"""

121

Split command line respecting shell quoting and word boundaries.

122

123

Parameters:

124

- line: Command line string to split

125

- point: Cursor position in the line (default: end of line)

126

127

Returns:

128

- Tuple containing:

129

- cword_prequote: Quote character before current word

130

- cword_prefix: Prefix of current word being completed

131

- cword_suffix: Suffix of current word after cursor

132

- comp_words: List of complete words before current position

133

- last_wordbreak_pos: Position of last word break character

134

"""

135

```

136

137

**Usage:**

138

139

```python

140

from argcomplete import split_line

141

142

# Parse a command line

143

line = 'my-script --config "path with spaces" --output'

144

point = len(line) # Cursor at end

145

146

prequote, prefix, suffix, words, wordbreak_pos = split_line(line, point)

147

148

print(f"Prequote: {repr(prequote)}")

149

print(f"Prefix: {repr(prefix)}")

150

print(f"Suffix: {repr(suffix)}")

151

print(f"Words: {words}")

152

print(f"Wordbreak position: {wordbreak_pos}")

153

```

154

155

## Advanced Utilities

156

157

**Note:** The following are suggested utility functions you can implement in your own code. These are **not** part of the argcomplete API but are common patterns for working with completion environments.

158

159

### Environment Variable Helpers

160

161

Check for completion environment and get debug status:

162

163

```python

164

import os

165

166

def is_completion_active():

167

"""Check if currently running in completion mode."""

168

return "_ARGCOMPLETE" in os.environ

169

170

def is_debug_enabled():

171

"""Check if debug output is enabled."""

172

return "_ARC_DEBUG" in os.environ

173

174

# Usage in custom code

175

if is_completion_active():

176

# Special behavior during completion

177

return get_completions_quickly()

178

else:

179

# Normal execution

180

return process_normally()

181

```

182

183

### Shell Environment Detection

184

185

Detect the shell environment during completion:

186

187

```python

188

import os

189

190

def get_completion_shell():

191

"""Get the shell being used for completion."""

192

return os.environ.get("_ARGCOMPLETE_SHELL", "unknown")

193

194

def is_zsh_completion():

195

"""Check if completion is running under zsh."""

196

return get_completion_shell() == "zsh"

197

198

def is_bash_completion():

199

"""Check if completion is running under bash."""

200

return get_completion_shell() == "bash"

201

202

# Usage

203

shell = get_completion_shell()

204

if shell == "zsh":

205

# ZSH supports descriptions

206

return {"option": "description"}

207

else:

208

# Other shells

209

return ["option"]

210

```

211

212

### Completion Data Extraction

213

214

Extract completion-specific data from the environment:

215

216

```python

217

import os

218

219

def get_completion_line():

220

"""Get the full command line being completed."""

221

return os.environ.get("COMP_LINE", "")

222

223

def get_completion_point():

224

"""Get cursor position in the command line."""

225

return int(os.environ.get("COMP_POINT", 0))

226

227

def get_completion_type():

228

"""Get the type of completion being performed."""

229

return os.environ.get("COMP_TYPE", "")

230

231

# Usage in advanced completers

232

class AdvancedCompleter(BaseCompleter):

233

def __call__(self, prefix, **kwargs):

234

comp_line = get_completion_line()

235

comp_point = get_completion_point()

236

237

# Analyze full command line for context

238

if "--verbose" in comp_line:

239

return self._get_verbose_completions(prefix)

240

else:

241

return self._get_normal_completions(prefix)

242

```

243

244

245

## Debugging Techniques

246

247

### Comprehensive Debug Output

248

249

```python

250

from argcomplete import debug

251

import os

252

253

def debug_completion_state():

254

"""Output comprehensive debug information."""

255

debug("=== Completion Debug Info ===")

256

debug("COMP_LINE:", os.environ.get("COMP_LINE"))

257

debug("COMP_POINT:", os.environ.get("COMP_POINT"))

258

debug("Shell:", os.environ.get("_ARGCOMPLETE_SHELL"))

259

debug("Args:", sys.argv)

260

debug("===========================")

261

262

# Use at start of completion

263

if "_ARC_DEBUG" in os.environ:

264

debug_completion_state()

265

```

266

267

### Error Isolation

268

269

```python

270

from argcomplete import warn

271

272

def safe_completion_wrapper(func):

273

"""Decorator to safely handle completion errors."""

274

def wrapper(*args, **kwargs):

275

try:

276

return func(*args, **kwargs)

277

except Exception as e:

278

warn(f"Completion error in {func.__name__}: {e}")

279

return []

280

return wrapper

281

282

# Use with custom completers

283

@safe_completion_wrapper

284

def my_completion_function(prefix):

285

# Potentially error-prone completio logic

286

return risky_completion_logic(prefix)

287

```

288

289

### Performance Monitoring

290

291

```python

292

import time

293

from argcomplete import debug

294

295

def timed_completion(func):

296

"""Decorator to monitor completion performance."""

297

def wrapper(*args, **kwargs):

298

start_time = time.time()

299

result = func(*args, **kwargs)

300

elapsed = time.time() - start_time

301

debug(f"Completion took {elapsed:.3f}s")

302

return result

303

return wrapper

304

305

# Monitor completion performance

306

@timed_completion

307

def slow_completer(prefix):

308

# Completion logic that might be slow

309

return expensive_completion_logic(prefix)

310

```