0
# History Management
1
2
Comprehensive history management including file operations, length control, and direct history manipulation. These functions provide complete control over command history persistence, size limits, and individual history entry management.
3
4
## Capabilities
5
6
### History File Operations
7
8
Functions for reading from and writing to history files, enabling persistent command history across sessions.
9
10
```python { .api }
11
def read_history_file(filename=None):
12
"""
13
Load a readline history file.
14
15
Parameters:
16
- filename (str, optional): Path to history file to read.
17
If None, defaults to ~/.history
18
19
Returns:
20
None
21
22
Raises:
23
IOError: If the file cannot be read
24
"""
25
26
def write_history_file(filename=None):
27
"""
28
Save a readline history file.
29
30
Parameters:
31
- filename (str, optional): Path to history file to write.
32
If None, defaults to ~/.history
33
34
Returns:
35
None
36
37
Raises:
38
IOError: If the file cannot be written
39
"""
40
```
41
42
**Usage Example:**
43
44
```python
45
import readline
46
import atexit
47
48
# Load history at startup
49
try:
50
readline.read_history_file()
51
except FileNotFoundError:
52
pass # No history file exists yet
53
54
# Save history at exit
55
atexit.register(readline.write_history_file)
56
57
# Use custom history file
58
readline.read_history_file('/path/to/custom_history')
59
readline.write_history_file('/path/to/custom_history')
60
```
61
62
### History Length Control
63
64
Functions for controlling the maximum number of history entries that will be maintained and saved to files.
65
66
```python { .api }
67
def set_history_length(length):
68
"""
69
Set the maximal number of items written to history file.
70
71
Parameters:
72
- length (int): Maximum history entries. Negative value inhibits truncation.
73
74
Returns:
75
None
76
"""
77
78
def get_history_length():
79
"""
80
Return the maximum number of items that will be written to history file.
81
82
Returns:
83
int: Maximum history length (-1 means no limit)
84
"""
85
```
86
87
**Usage Example:**
88
89
```python
90
import readline
91
92
# Set history to 1000 entries
93
readline.set_history_length(1000)
94
95
# Disable history truncation
96
readline.set_history_length(-1)
97
98
# Check current limit
99
max_entries = readline.get_history_length()
100
print(f"History limit: {max_entries}")
101
```
102
103
### History Access and Information
104
105
Functions for accessing current history state and retrieving specific history entries.
106
107
```python { .api }
108
def get_current_history_length():
109
"""
110
Return the current (not maximum) length of history.
111
112
Returns:
113
int: Current number of history entries
114
"""
115
116
def get_history_item(index):
117
"""
118
Return the current contents of history item at index.
119
120
Parameters:
121
- index (int): History item index (1-based on GNU readline,
122
0-based on libedit/Apple systems)
123
124
Returns:
125
str: History line content, or None if index is invalid
126
"""
127
```
128
129
**Usage Example:**
130
131
```python
132
import readline
133
134
# Check current history size
135
current_size = readline.get_current_history_length()
136
print(f"Current history has {current_size} entries")
137
138
# Access recent history entries
139
if current_size > 0:
140
# Get the most recent entry (last command)
141
last_command = readline.get_history_item(current_size)
142
print(f"Last command: {last_command}")
143
144
# Show last 5 commands
145
start = max(1, current_size - 4)
146
for i in range(start, current_size + 1):
147
command = readline.get_history_item(i)
148
print(f"{i}: {command}")
149
```
150
151
### History Manipulation
152
153
Functions for directly modifying history entries, including adding new entries and removing or replacing existing ones.
154
155
```python { .api }
156
def add_history(string):
157
"""
158
Add a line to the history buffer.
159
160
Parameters:
161
- string (str): Line to add to history
162
163
Returns:
164
None
165
"""
166
167
def remove_history_item(pos):
168
"""
169
Remove history item given by its position.
170
171
Parameters:
172
- pos (int): Position of history item to remove (0-based indexing)
173
174
Returns:
175
None
176
"""
177
178
def replace_history_item(pos, line):
179
"""
180
Replace history item given by its position with contents of line.
181
182
Parameters:
183
- pos (int): Position of history item to replace (0-based indexing)
184
- line (str): New content for history item
185
186
Returns:
187
None
188
"""
189
190
def clear_history():
191
"""
192
Clear the current readline history.
193
194
Returns:
195
None
196
197
Note: Only available when compiled with HAVE_RL_COMPLETION_APPEND_CHARACTER
198
"""
199
```
200
201
**Usage Example:**
202
203
```python
204
import readline
205
206
# Add custom entries to history
207
readline.add_history("ls -la")
208
readline.add_history("cd /tmp")
209
readline.add_history("python script.py")
210
211
# Replace a history entry (0-based indexing for manipulation)
212
readline.replace_history_item(0, "ls -la --color=auto")
213
214
# Remove unwanted history entry
215
readline.remove_history_item(1) # Remove "cd /tmp"
216
217
# Clear all history
218
readline.clear_history()
219
```
220
221
## Platform Considerations
222
223
**Apple/macOS Systems**: When using libedit emulation (default on macOS), `get_history_item()` uses 0-based indexing instead of the 1-based indexing used by GNU readline. However, `remove_history_item()` and `replace_history_item()` always use 0-based indexing on all platforms.