OILS / builtin / readline_osh.py View on Github | oils.pub

298 lines, 182 significant
1#!/usr/bin/env python2
2"""
3readline_osh.py - Builtins that are dependent on GNU readline.
4"""
5from __future__ import print_function
6
7from _devbuild.gen import arg_types
8from _devbuild.gen.syntax_asdl import loc
9from _devbuild.gen.value_asdl import value_e
10from core import pyutil
11from core import vm
12from core.error import e_usage
13from frontend import flag_util
14from mycpp import mops
15from mycpp import mylib
16from mycpp.mylib import log
17
18from typing import Optional, Any, TYPE_CHECKING
19if TYPE_CHECKING:
20 from _devbuild.gen.runtime_asdl import cmd_value
21 from frontend.py_readline import Readline
22 from core import sh_init
23 from display import ui
24 from state import Mem
25
26_ = log
27
28import sys # REMOVE ME
29
30
31class ctx_Keymap(object):
32
33 def __init__(self, readline, keymap_name=None):
34 # type: (Readline, str) -> None
35 self.readline = readline
36 self.orig_keymap_name = keymap_name
37
38 def __enter__(self):
39 # type: () -> None
40 if self.orig_keymap_name is not None:
41 self.readline.use_temp_keymap(self.orig_keymap_name)
42
43 def __exit__(self, type, value, traceback):
44 # type: (Any, Any, Any) -> None
45 if self.orig_keymap_name is not None:
46 self.readline.restore_orig_keymap()
47
48
49class Bind(vm._Builtin):
50 """Interactive interface to readline bindings"""
51
52 def __init__(self, readline, errfmt, mem):
53 # type: (Optional[Readline], ui.ErrorFormatter, Mem) -> None
54 self.readline = readline
55 self.errfmt = errfmt
56 self.mem = mem
57 self.exclusive_flags = ["q", "u", "r", "x", "f"]
58
59 readline.set_bind_shell_command_hook(
60 lambda *args: self.bind_shell_command_hook(*args))
61
62 def Run(self, cmd_val):
63 # type: (cmd_value.Argv) -> int
64 readline = self.readline
65 if not readline:
66 e_usage("is disabled because Oils wasn't compiled with 'readline'",
67 loc.Missing)
68
69 attrs, arg_r = flag_util.ParseCmdVal('bind', cmd_val)
70
71 # print("attrs:\n", attrs)
72 # print("attrs.attrs:\n", attrs.attrs)
73 # print("attrs.attrs.m:\n", attrs.attrs["m"])
74 # print("type(attrs.attrs.m):\n", type(attrs.attrs["m"]))
75 # print("type(attrs.attrs[m]):\n", type(attrs.attrs["m"]))
76 # print("attrs.attrs[m].tag() :\n", attrs.attrs["m"].tag())
77 # print("attrs.attrs[m].tag() == value_e.Undef:\n", attrs.attrs["m"].tag() == value_e.Undef)
78 # print(arg_r)
79 # print("Reader argv=%s locs=%s n=%i i=%i" % (arg_r.argv, str(arg_r.locs), arg_r.n, arg_r.i))
80
81 # Check mutually-exclusive flags and non-flag args
82 found = False
83 for flag in self.exclusive_flags:
84 if (flag in attrs.attrs and
85 attrs.attrs[flag].tag() != value_e.Undef):
86 # print("\tFound flag: {0} with tag: {1}".format(flag, attrs.attrs[flag].tag()))
87 if found:
88 self.errfmt.Print_(
89 "error: Can only use one of the following flags at a time: -"
90 + ", -".join(self.exclusive_flags),
91 blame_loc=cmd_val.arg_locs[0])
92 return 1
93 else:
94 found = True
95 if found and not arg_r.AtEnd():
96 self.errfmt.Print_(
97 "error: Too many arguments. Check your quoting. Also, you cannot mix normal bindings with the following flags: -"
98 + ", -".join(self.exclusive_flags),
99 blame_loc=cmd_val.arg_locs[0])
100 return 1
101
102 arg = arg_types.bind(attrs.attrs)
103 # print("arg:\n", arg)
104 # print("dir(arg):\n", dir(arg))
105 # for prop in dir(arg):
106 # if not prop.startswith('__'):
107 # value = getattr(arg, prop)
108 # print("Property: {0}, Value: {1}".format(prop, value))
109 # print("arg.m:\n", arg.m)
110
111 try:
112 with ctx_Keymap(readline, arg.m): # Replicates bind's -m behavior
113
114 # This gauntlet of ifs is meant to replicate bash behavior, in case we
115 # need to relax the mutual exclusion of flags like bash does
116
117 # List names of functions
118 if arg.l:
119 readline.list_funmap_names()
120
121 # Print function names and bindings
122 if arg.p:
123 readline.function_dumper(True) # reusable as input
124 if arg.P:
125 readline.function_dumper(False)
126
127 # Print macros
128 if arg.s:
129 readline.macro_dumper(True) # reusable as input
130 if arg.S:
131 readline.macro_dumper(False)
132
133 # Print readline variable names
134 if arg.v:
135 readline.variable_dumper(True)
136 if arg.V:
137 readline.variable_dumper(False)
138
139 if arg.f is not None:
140 readline.read_init_file(arg.f)
141
142 if arg.q is not None:
143 readline.query_bindings(arg.q)
144
145 if arg.u is not None:
146 readline.unbind_rl_function(arg.u)
147
148 if arg.r is not None:
149 readline.unbind_keyseq(arg.r)
150
151 if arg.x is not None:
152 # print("arg.x: %s" % arg.x)
153 readline.bind_shell_command(arg.x)
154
155 if arg.X:
156 readline.print_shell_cmd_map()
157
158 bindings, arg_locs = arg_r.Rest2()
159 #log('bindings %d locs %d', len(arg_r.argv), len(arg_r.locs))
160
161 for i, binding in enumerate(bindings):
162 try:
163 #log("Binding %s (%d)", binding, i)
164 #log("Arg loc %s (%d)", arg_locs[i], i)
165 readline.parse_and_bind(binding)
166 except ValueError as e:
167 msg = e.message # type: str
168 self.errfmt.Print_("bind error: %s" % msg, arg_locs[i])
169 return 1
170
171 except ValueError as e:
172 # only print out the exception message if non-empty
173 # some bash bind errors return non-zero, but print to stdout
174 # temp var to work around mycpp runtime limitation
175 msg2 = e.message # type: str
176 if msg2 is not None and len(msg2) > 0:
177 self.errfmt.Print_("bind error: %s" % msg2, loc.Missing)
178 return 1
179
180 return 0
181
182 def bind_shell_command_hook(self, cmd, line_buffer, point):
183 # type: (str, str, int) -> (int, str, str)
184 print("Executing cmd: %s" % cmd)
185 print("Setting READLINE_LINE to: %s" % line_buffer)
186 print("Setting READLINE_POINT to: %s" % point)
187 sys.stdout.flush()
188
189 self.mem
190
191 temp_return_code = 0
192 return (temp_return_code, line_buffer, str(point))
193
194
195class History(vm._Builtin):
196 """Show interactive command history."""
197
198 def __init__(
199 self,
200 readline, # type: Optional[Readline]
201 sh_files, # type: sh_init.ShellFiles
202 errfmt, # type: ui.ErrorFormatter
203 f, # type: mylib.Writer
204 ):
205 # type: (...) -> None
206 self.readline = readline
207 self.sh_files = sh_files
208 self.errfmt = errfmt
209 self.f = f # this hook is for unit testing only
210
211 def Run(self, cmd_val):
212 # type: (cmd_value.Argv) -> int
213 # NOTE: This builtin doesn't do anything in non-interactive mode in bash?
214 # It silently exits zero.
215 # zsh -c 'history' produces an error.
216 readline = self.readline
217 if not readline:
218 e_usage("is disabled because Oils wasn't compiled with 'readline'",
219 loc.Missing)
220
221 attrs, arg_r = flag_util.ParseCmdVal('history', cmd_val)
222 arg = arg_types.history(attrs.attrs)
223
224 # Clear all history
225 if arg.c:
226 readline.clear_history()
227 return 0
228
229 if arg.a:
230 hist_file = self.sh_files.HistoryFile()
231 if hist_file is None:
232 return 1
233
234 try:
235 readline.write_history_file(hist_file)
236 except (IOError, OSError) as e:
237 self.errfmt.Print_(
238 'Error writing HISTFILE %r: %s' %
239 (hist_file, pyutil.strerror(e)), loc.Missing)
240 return 1
241
242 return 0
243
244 if arg.r:
245 hist_file = self.sh_files.HistoryFile()
246 if hist_file is None:
247 return 1
248
249 try:
250 readline.read_history_file(hist_file)
251 except (IOError, OSError) as e:
252 self.errfmt.Print_(
253 'Error reading HISTFILE %r: %s' %
254 (hist_file, pyutil.strerror(e)), loc.Missing)
255 return 1
256
257 return 0
258
259 # Delete history entry by id number
260 arg_d = mops.BigTruncate(arg.d)
261 if arg_d >= 0:
262 cmd_index = arg_d - 1
263
264 try:
265 readline.remove_history_item(cmd_index)
266 except ValueError:
267 e_usage("couldn't find item %d" % arg_d, loc.Missing)
268
269 return 0
270
271 # Returns 0 items in non-interactive mode?
272 num_items = readline.get_current_history_length()
273 #log('len = %d', num_items)
274
275 num_arg, num_arg_loc = arg_r.Peek2()
276
277 if num_arg is None:
278 start_index = 1
279 else:
280 try:
281 num_to_show = int(num_arg)
282 except ValueError:
283 e_usage('got invalid argument %r' % num_arg, num_arg_loc)
284 start_index = max(1, num_items + 1 - num_to_show)
285
286 arg_r.Next()
287 if not arg_r.AtEnd():
288 e_usage('got too many arguments', loc.Missing)
289
290 # TODO:
291 # - Exclude lines that don't parse from the history! bash and zsh don't do
292 # that.
293 # - Consolidate multiline commands.
294
295 for i in xrange(start_index, num_items + 1): # 1-based index
296 item = readline.get_history_item(i)
297 self.f.write('%5d %s\n' % (i, item))
298 return 0