def lookupCb(thing): if not thing: self.stdout.write('No thing found for %s\n' % shortid.encode('utf-8')) return self.getRootCommand()._stdio.teardown() def pre_input_hook(): readline.insert_text(display.display( thing, shortid=False, colored=False)) readline.redisplay() # Unset the hook again readline.set_pre_input_hook(None) readline.set_pre_input_hook(pre_input_hook) line = raw_input("GTD edit> ").decode('utf-8') # Remove edited line from history: # oddly, get_history_item is 1-based, # but remove_history_item is 0-based readline.remove_history_item(readline.get_current_history_length() - 1) self.getRootCommand()._stdio.setup() try: d = parse.parse(line) except ValueError, e: self.stderr.write('Could not parse line: %s\n' % log.getExceptionMessage(e)) return 3
def main(): """ interactive move of a file. Instead of calling mv with two arguments, source and destination, call imv with just the source, and edit the destination in a GNU readline buffer. Once the line editor is started, it is possible to cancel with Ctrl-C without harming the filesystem. """ if (sys.argv[1] == '-h' or sys.argv[1] == '--help'): help(main) sys.exit(0) else: for src in sys.argv[1:]: if os.path.exists(src): def pre_input_hook(): readline.insert_text(src) readline.redisplay() readline.set_pre_input_hook(pre_input_hook) try: dst = raw_input('imv$ ') except KeyboardInterrupt: # die silently if user hits Ctrl-C pass else: shutil.move(src, dst) else: print 'ERROR: %s: no such file or directory' % src sys.exit(-1)
def pre_input_hook(): readline.insert_text(display.display( thing, shortid=False, colored=False)) readline.redisplay() # Unset the hook again readline.set_pre_input_hook(None)
def edit(self, entry=None): """Edits the specified `entry`. If `entry` is None, a new entry is created. This method supports the readline module for editing :returns: The entry with the new values as entered by the user""" if entry is None: entry = Entry() print _('Creating a new entry...\n' 'Please fill the following fields. To leave a ' 'field empty, just press ENTER without entering ' 'something.') else: self.edited_entry = entry print _('Editing entry %s\n' 'Please fill the following fields...') % repr(entry) # set input hook to show the current value readline.set_pre_input_hook(self._input_hook) print for field in self.fields: self.current_field = field[0] resp = raw_input(field[1]).strip() while not self.verify_field(field[0], resp): print field[2] resp = raw_input(field[1]).strip() setattr(entry, field[0], resp) # remove input hook readline.set_pre_input_hook(None) return entry
def operate_and_get_next(count, char): current_line = readline.where_history() offset = readline.get_current_history_length() - current_line # Accept the current line and set the hook to rewind history result = readline.accept_line(1, char) readline.set_pre_input_hook(pre_input_hook_factory(offset, char)) return result
def postcmd(self, stop, line): """Called just before execution of line. For readline, this handles the automatic indentation of code blocks. """ try: import readline except ImportError: return stop if self.need_more_lines: if len(line.strip()) == 0: readline.set_pre_input_hook(None) self._current_indent = '' elif line.rstrip()[-1] == ':': ind = line[:len(line) - len(line.lstrip())] ind += builtins.__xonsh_env__.get('INDENT') readline.set_pre_input_hook(_insert_text_func(ind, readline)) self._current_indent = ind elif line.split(maxsplit=1)[0] in DEDENT_TOKENS: env = builtins.__xonsh_env__ ind = self._current_indent[:-len(env.get('INDENT'))] readline.set_pre_input_hook(_insert_text_func(ind, readline)) self._current_indent = ind else: ind = line[:len(line) - len(line.lstrip())] if ind != self._current_indent: insert_func = _insert_text_func(ind, readline) readline.set_pre_input_hook(insert_func) self._current_indent = ind else: readline.set_pre_input_hook(None) return stop
def cmdloop(self, intro=None): self.old_completer = readline.get_completer() self.old_completer_delims = readline.get_completer_delims() readline.set_completer(self.complete) readline.parse_and_bind(self.completekey+": complete") readline.parse_and_bind("set bell-style none") readline.parse_and_bind("set show-all-if-ambiguous") readline.parse_and_bind("set completion-query-items -1") # If press help key, add the character and accept the line readline.parse_and_bind('"?": "\C-q?\C-j"') # Register a function for execute before read user # input. We can use it for insert text at command line readline.set_pre_input_hook(self.pre_input_hook) readline.set_completer_delims(' \t\n') try: stop = None while not stop: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' stop = self.onecmd(line) stop = self.postcmd(stop, line) finally: readline.set_completer(self.old_completer) readline.set_completer_delims(self.old_completer_delims)
def fix_entry(entry): """ Allow user to change name of an entry. It is called 'fix' because the only plausible reason to do so in this context is to correct a typo or other error. Returns True if the fix was successful, False if user chose an invalid new name (i.e., one that already exists). """ print "" readline.set_pre_input_hook(readline_prefiller(entry)) new_entry = raw_input(tc.RED+"Change to: "+tc.YELLOW) print tc.ENDC readline.set_pre_input_hook() if db.entries.get_eid(new_entry): print "That entry already exists! Try a different one, or use coalesce." print "~ Press any key to continue ~", termdisplay.getch() return False else: db.entries.correct_entry(entry, new_entry) screen(new_entry) return True
def update(phenotype): """Update the metadata for a given phenotype. :param phenotype: The phenotype for which the metadata will be updated. :type phenotype: str This will display a JSON string that the user can edit to update the database. Note that it is not possible to rename phenotypes using this function as it is used as the database key to access the data. TODO. Make this better for the new client/server architecture. """ data, meta = _get_data_meta(phenotype) meta.pop("name") def hook(): readline.insert_text(json.dumps(meta)) readline.redisplay() readline.set_pre_input_hook(hook) new_data = input("(json)>>> ") readline.set_pre_input_hook() new_data = json.loads(new_data) meta.update(new_data) # Update in db. _get_manager().update_phenotype(phenotype, **meta) return {"success": True, "message": "Phenotype updated in database."}
def prepopulate(default): """Prepopluates the input with the default text for the user to edit""" def hook(): readline.insert_text(str(default)) readline.redisplay() if default is not None: readline.set_pre_input_hook(hook) yield readline.set_pre_input_hook(None)
def query_user(prompt, text): def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def _input_default(prompt, default): def hook(): readline.insert_text(default) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def myinput(prompt, prefill): def hook(): readline.insert_text(prefill) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def cli_input_with_prefill(prompt, text): def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def input_prefill(prompt, text): """Prefills user input with text""" def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def editable_input(prompt, prefill=None): def hook(): readline.insert_text(prefill) readline.redisplay() readline.set_pre_input_hook(hook) result = input(green(prompt + ': ')) readline.set_pre_input_hook() return result
def finput(prompt='>>> ', text=''): text = str(text) def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt + '\n') readline.set_pre_input_hook() return result
def raw_input_with_default(prompt, default): def pre_input_hook(): readline.insert_text(default) readline.redisplay() readline.set_pre_input_hook(pre_input_hook) try: return raw_input(prompt) finally: readline.set_pre_input_hook(None)
def raw_input_def(prompt, default): def pre_input_hook(): readline.insert_text(default) readline.redisplay() readline.set_pre_input_hook(pre_input_hook) try: return raw_input(prompt) finally: readline.set_pre_input_hook(None)
def input_with_prefill(prompt: str, text: str) -> str: # https://stackoverflow.com/a/8505387 def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def my_input(prompt, default=None, completer=None): if default is not None: def pre_input_hook(): readline.insert_text(default) readline.redisplay() readline.set_pre_input_hook(pre_input_hook) # completer if completer: readline.set_completer(completer) readline.parse_and_bind('tab: complete') return input(prompt)
def preinput(self, label='', preinput=''): """ Pre-insert a text on a input function """ def hook(): readline.insert_text(preinput) readline.redisplay() readline.set_pre_input_hook(hook) print(label, end='') value = input(' ') readline.set_pre_input_hook() return value
def prompt_user(self, model, value, existing): def hook(): readline.insert_text( self.pre_process_existing_value_to_prefill_input(value)) readline.redisplay() if existing: readline.set_pre_input_hook(hook) result = input(self.input_text(model)) readline.set_pre_input_hook() return result
def init_readline(self): """Activates history and tab completion """ # - 1. history stuff # - mainly borrowed from site.enablerlcompleter() from py3.4+, # we can't simply call site.enablerlcompleter() because its # implementation overwrites the history file for each python # session whereas we prefer appending history from every # (potentially concurrent) session. # Reading the initialization (config) file may not be enough to set a # completion key, so we set one first and then read the file. readline_doc = getattr(readline, '__doc__', '') if readline_doc is not None and 'libedit' in readline_doc: readline.parse_and_bind('bind ^I rl_complete') else: readline.parse_and_bind('tab: complete') try: readline.read_init_file() except OSError: # An OSError here could have many causes, but the most likely one # is that there's no .inputrc file (or .editrc file in the case of # Mac OS X + libedit) in the expected location. In that case, we # want to ignore the exception. pass def append_history(len_at_start): current_len = readline.get_current_history_length() readline.append_history_file(current_len - len_at_start, config.HISTFILE) if readline.get_current_history_length() == 0: # If no history was loaded, default to .python_history. # The guard is necessary to avoid doubling history size at # each interpreter exit when readline was already configured # see: http://bugs.python.org/issue5845#msg198636 try: readline.read_history_file(config.HISTFILE) except IOError: pass len_at_start = readline.get_current_history_length() atexit.register(append_history, len_at_start) readline.set_history_length(config.HISTSIZE) # - 2. enable auto-indenting if config.AUTO_INDENT: readline.set_pre_input_hook(self.auto_indent_hook) # - 3. completion # - replace default completer self.completer = ImprovedCompleter(self.locals) readline.set_completer(self.completer.complete)
def input_with_prefill(prompt, text): def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = six.input(prompt) # nosec (bandit; python2) readline.set_pre_input_hook() return result
def input_with_prefill(prompt, text): if not interactive: return text def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def __inputWithDefault(prompt=None, default=None): if (default is not None): def hook(): readline.insert_text(default) readline.redisplay() readline.set_pre_input_hook(hook) ret = raw_input(prompt) if (default is not None): readline.set_pre_input_hook() # clear hook return ret
def raw_input_with_default(prompt, default): def pre_input_hook(): readline.insert_text(default) readline.redisplay() readline.set_pre_input_hook(pre_input_hook) try: return raw_input(prompt) except KeyboardInterrupt: sys.exit() finally: readline.set_pre_input_hook(None)
def input_with_prefill(prompt, text): try: import readline def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) return input2or3(prompt) except ImportError: return input2or3(prompt) finally: readline.set_pre_input_hook()
def input_with_prefill(self, prompt, text): if text is None: text = '' def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def custom_input(msg='', preselect=''): def pre_input_hook(): readline.insert_text(preselect) readline.redisplay() readline.set_pre_input_hook(pre_input_hook) ans = raw_input(msg + ': ') readline.set_pre_input_hook(None) if ans.strip() is '': return preselect return ans.strip()
def ask_for_name(fastqs, default): def hook(): readline.insert_text(default) readline.redisplay() readline.set_pre_input_hook(hook) while True: answer = input('''Enter a name for the VCF associated with the following FASTQ files (or "." to skip): - {fastq1} - {fastq2} > '''.format(fastq1=fastqs[0], fastq2=fastqs[1])) or default if answer: readline.set_pre_input_hook() return answer
def input_with_prefill(prompt, text): def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) if sys.version_info >= (3,): result = input(prompt) else: result = raw_input(prompt) readline.set_pre_input_hook() return result
def readLine(prompt, initialText=None): if initialText is not None: setReadlineText(initialText) try: return input('{}{c.userInput}'.format(prompt, c=promptColors)) except KeyboardInterrupt: colors.printControlChar('^C\r') sys.exit(1) finally: sys.stdout.write(colors.reset) sys.stdout.flush() readline.set_pre_input_hook() # Reset the pre-input hook so it doesn't keep inserting the last value.
def MyInput(prompt, defval=""): # A class function that help to improve input() (provided default value) def hook(): readline.insert_text(defval) if os.name != "nt": # windows does not have redisplay() nor require to use redisplay() readline.redisplay() readline.set_pre_input_hook(hook) ans = input(f"{prompt}") readline.set_pre_input_hook() # CLEAR THE preset if (ans == None or len(ans) == 0): return "" return ans
def main(): def prehook(): readline.insert_text("mristin/") readline.redisplay() readline.set_pre_input_hook(prehook) answer = input( bcolors.OKBLUE + "Name of the new branch (spaces will be replaced with '-'): " + bcolors.ENDC) readline.set_pre_input_hook() answer = answer.replace(' ', '-') subprocess.check_call(['git', 'checkout', '-b', answer])
def ask(question, default=u''): """Ask the user a question and return the typed answer. Optionally, a default answer can be provided which the user can edit. """ def pre_input_hook(): readline.insert_text(default.encode(sys.stdin.encoding)) readline.redisplay() readline.set_pre_input_hook(pre_input_hook) try: return raw_input(question).decode(sys.stdin.encoding) finally: readline.set_pre_input_hook(None)
def prefill_input(prompt, prefill): """ Prefills input No params Returns user response """ def hook(): readline.insert_text(prefill) readline.redisplay() readline.set_pre_input_hook(hook) response = input(prompt) readline.set_pre_input_hook() return response
def toggle_auto_indent(self, _): """{config.TOGGLE_AUTO_INDENT_CMD} - Toggles the auto-indentation behavior """ hook = None if config.AUTO_INDENT else self.auto_indent_hook msg = '# Auto-Indent has been {}abled\n'.format('en' if hook else 'dis') config.AUTO_INDENT = bool(hook) if hook is None: msg += ('# End of blocks will be detected after 3 empty lines\n' f'# Re-type {config.TOGGLE_AUTO_INDENT_CMD} on a line by itself to enable') readline.set_pre_input_hook(hook) print(grey(msg, bold=False)) return ''
def prefill_input(prompt, text): ''' Prefill user input with default text. https://stackoverflow.com/questions/8505163/is-it-possible-to-prefill-a-input-in-python-3s-command-line-interface ''' def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def main(args: List[str]) -> Response: # For some reason importing readline in a key handler in the main kitty process # causes a crash of the python interpreter, probably because of some global # lock global readline msg = 'Ask the user for input' try: cli_opts, items = parse_args(args[1:], option_text, '', msg, 'kitty ask', result_class=AskCLIOptions) except SystemExit as e: if e.code != 0: print(e.args[0]) input('Press enter to quit...') raise SystemExit(e.code) if cli_opts.type in ('yesno', 'choices'): loop = Loop() handler = Choose(cli_opts) loop.loop(handler) return {'items': items, 'response': handler.response} prompt = cli_opts.prompt if prompt[0] == prompt[-1] and prompt[0] in '\'"': prompt = prompt[1:-1] if cli_opts.type == 'password': loop = Loop() phandler = Password(cli_opts, prompt) loop.loop(phandler) return {'items': items, 'response': phandler.response} import readline as rl readline = rl from kitty.shell import init_readline init_readline() response = None with alternate_screen(), HistoryCompleter(cli_opts.name): if cli_opts.message: print(styled(cli_opts.message, bold=True)) with suppress(KeyboardInterrupt, EOFError): if cli_opts.default: def prefill_text() -> None: readline.insert_text(cli_opts.default or '') readline.redisplay() readline.set_pre_input_hook(prefill_text) response = input(prompt) readline.set_pre_input_hook() else: response = input(prompt) return {'items': items, 'response': response}
def main(): global default readline.set_pre_input_hook(p) name = raw_input("Enter Name: ") default = "http://chumbucket.emsl.pnl.gov/cluster/chinook" url = raw_input("Enter URL: ") if url[-1] != '/': url += '/' data = urllib.urlopen(url + "index") index = map(string.rstrip, data.readlines()) tic = urllib.urlopen(url + "xtick") gwidth = len(tic.read()) / 32 print len(index), "Data types found. Width:", gwidth gwidth += 150 metrics = select_metrics(index) print "Selected ", len(metrics), "metrics: ", ` metrics ` w = max(1, len(metrics) / 5) default = str(w) width = raw_input("Grid Width: ") ylenmax = 0 for met in metrics: ytick = urllib.urlopen(url + met + ".ytick") ylength = len(ytick.read()) / 32 ylenmax = max(ylenmax, ylength) # max y-axis length of all histos ylenmax += 150 # add some padding default = name.replace(" ", "_") + ".cview" filename = raw_input("Filename: ") file = open(filename, "w") file.write(header % (locals())) x = 0 y = 0 for key in metrics: if x >= int(width) * gwidth: x = 0 y += ylenmax # take into consideration max yaxis length file.write(oneobj % (locals())) x += gwidth file.write(footer % (locals()))
def main(): global default readline.set_pre_input_hook(p) name=raw_input("Enter Name: ") default="http://chumbucket.emsl.pnl.gov/cluster/chinook" url=raw_input("Enter URL: ") if url[-1] != '/': url+='/' data=urllib.urlopen(url+"index") index=map(string.rstrip,data.readlines()) tic=urllib.urlopen(url+"xtick"); gwidth=len(tic.read())/32 print len(index),"Data types found. Width:",gwidth gwidth+=150 metrics=select_metrics(index); print "Selected ",len(metrics),"metrics: ",`metrics` w=max(1,len(metrics)/5); default=str(w); width=raw_input("Grid Width: ") ylenmax = 0 for met in metrics: ytick = urllib.urlopen(url+met+".ytick") ylength = len(ytick.read())/32 ylenmax = max(ylenmax, ylength) # max y-axis length of all histos ylenmax += 150 # add some padding default = name.replace(" ","_")+".cview" filename = raw_input("Filename: "); file=open(filename,"w"); file.write(header%(locals())) x=0 y=0 for key in metrics: if x>=int(width)*gwidth: x=0 y += ylenmax # take into consideration max yaxis length file.write(oneobj%(locals())) x+=gwidth file.write(footer%(locals()))
def cmdloop(self, prompt=None, intro=None): """Repeatedly issue a prompt, accept input, parse the input, and dispatch to execute the function or shell commands.""" self.preloop() try: self.old_completer = readline.get_completer() readline.set_completer(self.complete) readline.parse_and_bind('tab: complete') if IS_WINDOWS: readline.parse_and_bind('?: "\C-alist \C-e\n"') else: readline.parse_and_bind('set comment-begin "? "') readline.parse_and_bind('?: insert-comment') delims = readline.get_completer_delims() delims = delims.replace('-', '') delims = delims.replace('.', '') delims = delims.replace('/', '') delims = delims.replace('~', '') delims = delims.replace('?', '') delims = delims.replace('!', '') readline.set_completer_delims(delims) readline.set_pre_input_hook(self._input_hook) except ImportError: self.stdout.write("Unable to initialize readline.") try: if intro is not None: self.intro = intro if self.intro: self.stdout.write(str(self.intro) + "\n") if prompt is not None: self.prompt = prompt stop = None while not stop: if self.cmdqueue: line = self.cmdqueue.pop(0) else: try: line = input(self.prompt) except EOFError: line = EOF line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) self.postloop() finally: try: readline.set_completer(self.old_completer) except ImportError: pass
def PromptRepoStr(): def default_hook(): readline.insert_text("") readline.redisplay() def remote_hook(): username = getpass.getuser() readline.insert_text( "[email protected]:{}/notes.git".format(username)) readline.redisplay() readline.set_pre_input_hook(remote_hook) repo_str = input("notes repo: ") readline.set_pre_input_hook(default_hook) return repo_str
def __call__(self): import sys,os,time,signal sys.stdin = os.fdopen(self.stdin_fid) import readline readline.set_pre_input_hook(self.pre_input_hook) readline.set_completer(self.rlc.complete) self.read_history() try: self.lock.acquire() while(1): self.queue.put(raw_input(self.prompt)) except (self.KillException, EOFError, KeyboardInterrupt): self.queue.put("exit()") self.lock.release() self.write_history()
def __init__(self): """Setup readline module and other init.""" self.line_buffer = None self.editing = False readline.parse_and_bind('set editing-mode vi') self.histfile = os.path.expanduser(ex_config.EDIT_HISTORY) try: readline.read_history_file(self.histfile) except FileNotFoundError: pass atexit.register(self.save_history) readline.set_pre_input_hook(self.pre_input_hook)
def input_with_prefill(prompt: str, text: str) -> str: """ prefills input and places your cursor at the end :param prompt: the prompt :param text: the prefill :return: any modifications you made to the input """ def hook(): readline.insert_text(text) readline.redisplay() readline.set_pre_input_hook(hook) result = input(prompt) readline.set_pre_input_hook() return result
def default_input(prompt, default=None): # https://chistera.yi.org/~dato/blog/entries/2008/02/14/python_raw_input_with_an_editable_default_value_using_readline.html if not default: default = "" def pre_input_hook(): readline.insert_text(default) readline.redisplay() prompt += ": " readline.set_pre_input_hook(pre_input_hook) try: return input(prompt) finally: readline.set_pre_input_hook(None)
def setup_readline(): """Initialize the readline module.""" # Edited to work with pyenv histpath = os.path.join(os.path.expanduser("~"), ".pyenv", "versions", sys.version.split(' ')[0] , "share") if sys.version[0] == '2': histfile = os.path.join(histpath, "py2hist") else: histfile = os.path.join(histpath, "py3hist") if not os.path.exists(histpath): os.mkdir(histpath) atexit.register(readline.write_history_file, histfile) try: readline.read_history_file(histfile) except IOError: pass # Complete with the tab key. M-tab completes on local file names. readline.parse_and_bind("tab: complete") # readline indentation keybinding # Control-j: indent 4 spaces # Control-u: unindent 4 spaces # First, create some dummy shortcuts: # Add four spaces: readline.parse_and_bind(r'"\M-j": " "') # Delete four characters (behind point): readline.parse_and_bind(r'"\M-h": delete-char') readline.parse_and_bind(r'"\M-k": "\M-h\M-h\M-h\M-h"') # Move point forward four characters: readline.parse_and_bind(r'"\M-e": "\C-f\C-f\C-f\C-f"') # Move point backward four characters: readline.parse_and_bind(r'"\M-g": "\C-b\C-b\C-b\C-b"') # Second, define another set-mark shortcut, since it only seems to # work when bound to a letter key. readline.parse_and_bind(r'"\M-\C-j": set-mark') # C-j macro: set mark, go to the beginning of the line, add four # spaces, exchange point and mark, and then move forward four # characters to the same point in the text where you were before, # regardless of the new indentation. readline.parse_and_bind(r'"\C-j": "\M-\C-j\C-a\M-j\C-x\C-x\M-e"') # C-u macro: Move back four characters, set mark, move to the # beginning of the line, move forward four characters, delete four # characters, then exchange mark and point. This would be shorter # readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-e\M-k\C-x\C-x"') readline.parse_and_bind(r'"\C-u": "\M-g\M-\C-j\C-a\M-k\C-x\C-x"') # load readline history readline.set_pre_input_hook(rl_autoindent) readline.set_completion_display_matches_hook(comp_disp_matches)
def reinjectInRawInput(line): """Next call to raw_input() will have line set as default text @param line: The default text """ # Set readline.pre_input_hook to feed it with our line # (Code copied from yagtd) def pre_input_hook(): readline.insert_text(line.encode(ENCODING)) readline.redisplay() # Unset the hook again readline.set_pre_input_hook(None) if sys.platform != 'win32': readline.set_pre_input_hook(pre_input_hook)
def activate(interactive): """Activate the thread at initialization time""" the_stdin_thread.input_buffer = input_buffer() if interactive: the_stdin_thread.raw_input_wanted = Event() the_stdin_thread.in_raw_input = Event() the_stdin_thread.out_of_raw_input = Event() the_stdin_thread.out_of_raw_input.set() s1, s2 = socket.socketpair() the_stdin_thread.socket_read, the_stdin_thread.socket_write = s1, s2 the_stdin_thread.interrupt_asked = False the_stdin_thread.setDaemon(True) the_stdin_thread.start() the_stdin_thread.socket_notification = socket_notification_reader() the_stdin_thread.prepend_text = None readline.set_pre_input_hook(the_stdin_thread.prepend_previous_text)
def run(self): Backend(self.queue).start() if self.use_rawinput: try: import readline self.old_completer = readline.get_completer() """ We want to list help stuff on ? but we can't really: http://bugs.python.org/issue1690201 Pretty much the same thing with space, where we want tab completion, though not tab help display """ readline.set_completer(self.tab_complete) readline.parse_and_bind('tab: complete') readline.parse_and_bind('?: "\C-v?\t\t\C-h"') # readline.parse_and_bind('space: complete') # readline.parse_and_bind('?: list_completions') except ImportError: pass try: while not self.stop: readline.set_pre_input_hook(self.pre_input_hook) if self.use_rawinput: try: line = raw_input(self.prompt) except EOFError: line = 'EOF' else: self.rprint(self.prompt) line = self.stdin.readline() if not len(line): line = 'EOF' else: line = line[:-1] # chop \n line = self.precmd(line) self.stop = self.evalcmd(line) # stop = self.postcmd(stop, line) # self.postloop() finally: if self.use_rawinput: try: import readline readline.set_completer(self.old_completer) except ImportError: pass
def init_readline(self): """Activates history and tab completion """ # - init history if os.path.exists(config['HISTFILE']): readline.read_history_file(config['HISTFILE']) readline.set_history_length(config['HISTSIZE']) atexit.register(partial(readline.write_history_file, config['HISTFILE'])) # - turn on tab completion readline.parse_and_bind('tab: complete') readline.set_completer(self.improved_rlcompleter()) # - enable auto-indenting readline.set_pre_input_hook(self.auto_indent_hook) # - other useful stuff readline.read_init_file()
def editline (text, notempty=True, usereadline=True, **kwargs): """ Edits a line of text. By default it will use the readline library, but you can set ask it to use the same parameters as edit() by setting readline to False either manually or with .setreadline () If the notempty parameter is True, then a blank input will cause the original string to be returned. """ if usereadline: if type(text) == unicode: toedit = text.encode(sys.stdout.encoding) else: toedit = text def readline_hook (): readline.insert_text (toedit) readline.redisplay () readline.set_pre_input_hook(lambda: False) readline.set_pre_input_hook (readline_hook) if type(text) == unicode: edited = raw_input ().decode(sys.stdout.encoding) else: edited = raw_input () else: edited = edit (text, **kwargs) while edited.endswith('\n'): edited = edited[:-1] if len(edited)== 0 and notempty: return text else: return edited