or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

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

completion-engine.mddocs/

0

# Core Completion Engine

1

2

The core completion system provides the primary interface for enabling tab completion in Python scripts using argparse. The completion engine intercepts argparse operations during shell completion and generates appropriate completion candidates.

3

4

## Capabilities

5

6

### Main Completion Interface

7

8

The primary interface for adding completion to argparse-based scripts. This is a pre-instantiated CompletionFinder instance.

9

10

```python { .api }

11

autocomplete: CompletionFinder # Pre-instantiated completion finder

12

13

# Equivalent to: CompletionFinder().__call__(parser, **kwargs)

14

```

15

16

The autocomplete instance accepts the same parameters as CompletionFinder.__call__():

17

18

- `argument_parser`: The argparse ArgumentParser to enable completion on

19

- `always_complete_options`: Controls completion of option strings (`True`, `False`, `"long"`, `"short"`)

20

- `exit_method`: Method to exit after completion (default: `os._exit`)

21

- `output_stream`: Stream for completion output (default: file descriptor 8)

22

- `exclude`: List of option strings to exclude from completion

23

- `validator`: Function to filter completions (receives completion and prefix)

24

- `print_suppressed`: Whether to complete suppressed options

25

- `append_space`: Whether to append space to unique matches

26

- `default_completer`: Completer used when no specific completer is set

27

28

**Usage:**

29

30

```python

31

#!/usr/bin/env python

32

# PYTHON_ARGCOMPLETE_OK

33

34

import argparse

35

import argcomplete

36

37

parser = argparse.ArgumentParser()

38

parser.add_argument('--verbose', action='store_true')

39

parser.add_argument('--output', type=argparse.FileType('w'))

40

41

# Enable completion

42

argcomplete.autocomplete(parser)

43

44

args = parser.parse_args()

45

```

46

47

### CompletionFinder Class

48

49

Core class for finding and generating completions. Inherit from this class to customize completion behavior.

50

51

```python { .api }

52

class CompletionFinder:

53

def __init__(

54

self,

55

argument_parser=None,

56

always_complete_options=True,

57

exclude=None,

58

validator=None,

59

print_suppressed=False,

60

default_completer=FilesCompleter(),

61

append_space=None

62

)

63

```

64

65

**Main Completion Method:**

66

67

```python { .api }

68

def __call__(

69

self,

70

argument_parser: argparse.ArgumentParser,

71

always_complete_options: Union[bool, str] = True,

72

exit_method: Callable = os._exit,

73

output_stream: Optional[TextIO] = None,

74

exclude: Optional[Sequence[str]] = None,

75

validator: Optional[Callable] = None,

76

print_suppressed: bool = False,

77

append_space: Optional[bool] = None,

78

default_completer: BaseCompleter = FilesCompleter()

79

) -> None

80

```

81

82

**Completion Collection Methods:**

83

84

```python { .api }

85

def collect_completions(

86

self,

87

active_parsers: List[argparse.ArgumentParser],

88

parsed_args: argparse.Namespace,

89

cword_prefix: str

90

) -> List[str]

91

```

92

93

```python { .api }

94

def filter_completions(self, completions: List[str]) -> List[str]

95

```

96

97

```python { .api }

98

def quote_completions(

99

self,

100

completions: List[str],

101

cword_prequote: str,

102

last_wordbreak_pos: Optional[int]

103

) -> List[str]

104

```

105

106

**Readline Integration:**

107

108

```python { .api }

109

def rl_complete(self, text: str, state: int) -> Optional[str]

110

```

111

112

```python { .api }

113

def get_display_completions(self) -> Dict[str, str]

114

```

115

116

**Usage:**

117

118

```python

119

import argcomplete

120

121

# Custom completion finder

122

completer = argcomplete.CompletionFinder(

123

always_complete_options="long",

124

exclude=["--debug"],

125

validator=lambda completion, prefix: not completion.startswith("_")

126

)

127

128

# Use with parser

129

completer(parser)

130

131

# Or for readline integration

132

import readline

133

readline.set_completer(completer.rl_complete)

134

readline.parse_and_bind("tab: complete")

135

```

136

137

### ExclusiveCompletionFinder

138

139

Variant of CompletionFinder that provides exclusive completion behavior, preventing completion of conflicting options.

140

141

```python { .api }

142

class ExclusiveCompletionFinder(CompletionFinder):

143

"""

144

CompletionFinder that only completes options that haven't been used yet,

145

except for append actions which can be used multiple times.

146

"""

147

```

148

149

**Usage:**

150

151

```python

152

import argcomplete

153

154

finder = argcomplete.ExclusiveCompletionFinder()

155

finder(parser)

156

```

157

158

## Advanced Usage

159

160

### Custom Validator

161

162

```python

163

def custom_validator(completion, prefix):

164

"""Only allow completions that don't start with underscore"""

165

return not completion.startswith('_')

166

167

argcomplete.autocomplete(parser, validator=custom_validator)

168

```

169

170

### Output Stream Redirection

171

172

```python

173

import io

174

175

output_buffer = io.StringIO()

176

argcomplete.autocomplete(parser, output_stream=output_buffer)

177

```

178

179

### Exception Handling

180

181

The completion engine uses `ArgcompleteException` for completion-related errors:

182

183

```python

184

from argcomplete import ArgcompleteException

185

186

try:

187

argcomplete.autocomplete(parser)

188

except ArgcompleteException as e:

189

print(f"Completion error: {e}")

190

```