def lex_document(self, document): """ Call the lexer and return a get_tokens_for_line function. """ location = self.editor_buffer.location if location: return PygmentsLexer.from_filename( location, sync_from_start=False).lex_document(document) return SimpleLexer().lex_document(document)
def open_file(self, filename): """ Open this file. """ lexer = PygmentsLexer.from_filename(filename, sync_from_start=False) try: source = FileSource(filename, lexer=lexer) except IOError as e: self.message = '{}'.format(e) else: self.add_source(source)
def lex_document(self, document): """ Call the lexer and return a get_tokens_for_line function. """ location = self.editor_buffer.location if location: if self.editor_buffer.in_file_explorer_mode: return PygmentsLexer(DirectoryListingLexer, sync_from_start=False).lex_document(document) return PygmentsLexer.from_filename(location, sync_from_start=False).lex_document(document) return SimpleLexer().lex_document(document)
def __init__(self): super().__init__() self.paused = True self.app_thread = threading.Thread(target=self.start_gui, args=(asyncio.get_event_loop(),)) self.frame_history = FrameHistory() self.search_toolbar = SearchToolbar( text_if_not_searching=[("class:not-searching", "Press '/' to start searching.")] ) def get_view_file(): if len(self.frame_history.history) > 0: return self.frame_history.hist_frame.filename return ".py" self.text_area = TextArea( lexer=DynamicLexer( lambda: PygmentsLexer.from_filename( get_view_file(), sync_from_start=False ) ), search_field=self.search_toolbar, scrollbar=True, line_numbers=True, ) self.container = HSplit( [ self.text_area, self.search_toolbar, ] ) kb = KeyBindings() @kb.add("c-q") def _(event: KeyPressEvent): self.paused = False self._quit() @kb.add("c-n") def _(event): self.set_next(self.frame_history.exec_frame.raw_frame) self.paused = False # allow another frame to be processed self.app = Application( full_screen=True, layout=Layout(container=self.container), key_bindings=kb, ) self.app.loop = asyncio.get_event_loop()
def lex_document(self, document): """ Call the lexer and return a get_tokens_for_line function. """ location = self.editor_buffer.location if location: if self.editor_buffer.in_file_explorer_mode: return PygmentsLexer( DirectoryListingLexer, sync_from_start=False).lex_document(document) return PygmentsLexer.from_filename( location, sync_from_start=False).lex_document(document) return SimpleLexer().lex_document(document)
def run(): if not PTK3: if is_windows(): from prompt_toolkit.eventloop.win32 import Win32EventLoop loop = Win32EventLoop() else: from prompt_toolkit.eventloop.posix import PosixEventLoop from prompt_toolkit.eventloop.select import SelectSelector loop = PosixEventLoop(selector=SelectSelector) set_event_loop(loop) if not sys.stdin.isatty(): pager = Pager.from_pipe() pager.run() else: parser = argparse.ArgumentParser( description='Browse through a text file.') parser.add_argument('filename', metavar='filename', nargs='+', help='The file to be displayed.') parser.add_argument('--vi', help='Prefer Vi key bindings.', action='store_true') parser.add_argument('--emacs', help='Prefer Emacs key bindings.', action='store_true') args = parser.parse_args() # Determine input mode. vi_mode = 'vi' in os.environ.get('EDITOR', '').lower() if args.vi: vi_mode = True if args.emacs: vi_mode = False pager = Pager(vi_mode=vi_mode) # Open files. for filename in args.filename: # When a filename is given, take a lexer from that filename. lexer = PygmentsLexer.from_filename(filename, sync_from_start=False) pager.add_source(FileSource(filename, lexer=lexer)) # Run UI. pager.run()
def handle_info_frame(self, output): m = search('\((.+):(\d+)\);', output) if not m: self.buffer.document = Document() self.filename = None self.handle_source_change = True self.info.set_info(self.default_title) return self.handle_source_change = False filename = m[1] if filename and filename != self.filename: self.log('***Opening %s\n' % (filename)) with open(filename, "r") as f: self.info.set_info('[%s]' % filename) text = f.read().replace('\t', ' ') self.lexer = PygmentsLexer.from_filename( filename, sync_from_start=False) if filename.endswith('.s') or filename.endswith('.S'): self.lexer = PygmentsLexer(GasLexer, sync_from_start=False) self.buffer.text = text self.basename = basename(filename) self.filename = filename self.handle_source_change = True self._set_cursor(0) self.info.set_info('[ %s ]' % filename) line = int(m[2]) - 1 self.current_line = line self.log('*** Current line %d' % (self.current_line)) render_info = self.window.render_info if render_info and not self.handle_source_change: fv_line = render_info.first_visible_line() lv_line = render_info.last_visible_line() if line <= fv_line or line >= lv_line - 1: self._set_cursor(line) else: self._set_cursor(line) self.handle_source_change = False
def run(): if not sys.stdin.isatty(): pager = Pager.from_pipe() pager.run() else: parser = argparse.ArgumentParser( description="Browse through a text file.") parser.add_argument("filename", metavar="filename", nargs="+", help="The file to be displayed.") parser.add_argument("--vi", help="Prefer Vi key bindings.", action="store_true") parser.add_argument("--emacs", help="Prefer Emacs key bindings.", action="store_true") args = parser.parse_args() # Determine input mode. vi_mode = "vi" in os.environ.get("EDITOR", "").lower() if args.vi: vi_mode = True if args.emacs: vi_mode = False pager = Pager(vi_mode=vi_mode) # Open files. for filename in args.filename: # When a filename is given, take a lexer from that filename. lexer = PygmentsLexer.from_filename(filename, sync_from_start=False) pager.add_source(FileSource(filename, lexer=lexer)) # Run UI. pager.run()
def run(): if is_windows(): from prompt_toolkit.eventloop.win32 import Win32EventLoop loop = Win32EventLoop() else: from prompt_toolkit.eventloop.posix import PosixEventLoop from prompt_toolkit.eventloop.select import SelectSelector loop = PosixEventLoop(selector=SelectSelector) set_event_loop(loop) if not sys.stdin.isatty(): pager = Pager.from_pipe() pager.run() else: parser = argparse.ArgumentParser(description='Browse through a text file.') parser.add_argument('filename', metavar='filename', nargs='+', help='The file to be displayed.') parser.add_argument('--vi', help='Prefer Vi key bindings.', action='store_true') parser.add_argument('--emacs', help='Prefer Emacs key bindings.', action='store_true') args = parser.parse_args() # Determine input mode. vi_mode = 'vi' in os.environ.get('EDITOR', '').lower() if args.vi: vi_mode = True if args.emacs: vi_mode = False pager = Pager(vi_mode=vi_mode) # Open files. for filename in args.filename: # When a filename is given, take a lexer from that filename. lexer = PygmentsLexer.from_filename(filename, sync_from_start=False) pager.add_source(FileSource(filename, lexer=lexer)) # Run UI. pager.run()
def get_statusbar_text(): return ' Press Ctrl-C to open menu. ' def get_statusbar_right_text(): return ' {}:{} '.format( text_field.document.cursor_position_row + 1, text_field.document.cursor_position_col + 1) search_toolbar = SearchToolbar() text_field = TextArea( lexer=DynamicLexer( lambda: PygmentsLexer.from_filename( ApplicationState.current_path or '.txt', sync_from_start=False)), scrollbar=True, line_numbers=True, search_field=search_toolbar, ) class TextInputDialog(object): def __init__(self, title='', label_text='', completer=None): self.future = Future() def accept_text(): get_app().layout.focus(ok_button) self.text_area.buffer.complete_state = None
def get_statusbar_text(): return " Press Ctrl-C to open menu. " def get_statusbar_right_text(): return " {}:{} ".format( text_field.document.cursor_position_row + 1, text_field.document.cursor_position_col + 1, ) search_toolbar = SearchToolbar() text_field = TextArea( lexer=DynamicLexer(lambda: PygmentsLexer.from_filename( ApplicationState.current_path or ".txt", sync_from_start=False)), scrollbar=True, line_numbers=True, search_field=search_toolbar, ) class TextInputDialog: def __init__(self, title="", label_text="", completer=None): self.future = Future() def accept_text(buf): get_app().layout.focus(ok_button) buf.complete_state = None return True
def get_statusbar_text(): return ' Press Ctrl-C to open menu. ' def get_statusbar_right_text(): return ' {}:{} '.format( text_field.document.cursor_position_row + 1, text_field.document.cursor_position_col + 1) search_toolbar = SearchToolbar() text_field = TextArea( lexer=DynamicLexer( lambda: PygmentsLexer.from_filename( ApplicationState.current_path or '.txt', sync_from_start=False)), scrollbar=True, line_numbers=True, search_field=search_toolbar, ) class TextInputDialog(object): def __init__(self, title='', label_text='', completer=None): self.future = Future() def accept_text(buf): get_app().layout.focus(ok_button) buf.complete_state = None return True
def lex_document(self, document): return PygmentsLexer.from_filename( 'x.py', sync_from_start=False).lex_document(document)
def create_application(): def get_statusbar_text(): return "Ctrl-C: Close. Ctrl-E: Execute. Ctrl-S: Stop music. F2: Open Menu. " def get_statusbar_right_text(): return " {}:{} ".format( text_field.document.cursor_position_row + 1, text_field.document.cursor_position_col + 1, ) search_toolbar = SearchToolbar() text_field = TextArea( lexer=PygmentsLexer.from_filename('.mkl', sync_from_start=False), completer=VariableCompleter(ApplicationState.context), scrollbar=True, line_numbers=True, search_field=search_toolbar, ) class TextInputDialog: def __init__(self, title="", label_text="", completer=None): self.future = Future() def accept_text(buf): get_app().layout.focus(ok_button) buf.complete_state = None return True def accept(): self.future.set_result(self.text_area.text) def cancel(): self.future.set_result(None) self.text_area = TextArea( completer=completer, multiline=False, width=D(preferred=40), accept_handler=accept_text, ) ok_button = Button(text="OK", handler=accept) cancel_button = Button(text="Cancel", handler=cancel) self.dialog = Dialog( title=title, body=HSplit([Label(text=label_text), self.text_area]), buttons=[ok_button, cancel_button], width=D(preferred=80), modal=True, ) def __pt_container__(self): return self.dialog class MessageDialog: def __init__(self, title, text): self.future = Future() def set_done(): self.future.set_result(None) ok_button = Button(text="OK", handler=(lambda: set_done())) self.dialog = Dialog( title=title, body=HSplit([ Label(text=text), ]), buttons=[ok_button], width=D(preferred=80), modal=True, ) def __pt_container__(self): return self.dialog body = HSplit([ text_field, search_toolbar, ConditionalContainer( content=VSplit( [ Window(FormattedTextControl(get_statusbar_text), style="class:status"), Window( FormattedTextControl(get_statusbar_right_text), style="class:status.right", width=9, align=WindowAlign.RIGHT, ), ], height=1, ), filter=Condition(lambda: ApplicationState.show_status_bar), ), ]) # Global key bindings. bindings = KeyBindings() @bindings.add("f2") def _(event): " Focus menu. " event.app.layout.focus(root_container.window) # # Handlers for menu items. # def do_open_file(): async def coroutine(): open_dialog = TextInputDialog( title="Open file", label_text="Enter the path of a file:", completer=PathCompleter(), ) path = await show_dialog_as_float(open_dialog) ApplicationState.current_path = path if path is not None: try: with open(path, "rb") as f: text_field.text = f.read().decode("utf-8", errors="ignore") except IOError as e: show_message("Error", "{}".format(e)) ensure_future(coroutine()) def do_about(): show_message("About", "Text editor demo.\nCreated by Jonathan Slenders.") def show_message(title, text): async def coroutine(): dialog = MessageDialog(title, text) await show_dialog_as_float(dialog) ensure_future(coroutine()) async def show_dialog_as_float(dialog): " Coroutine. " float_ = Float(content=dialog) root_container.floats.insert(0, float_) app = get_app() focused_before = app.layout.current_window app.layout.focus(dialog) result = await dialog.future app.layout.focus(focused_before) if float_ in root_container.floats: root_container.floats.remove(float_) return result @bindings.add('c-n') def do_new_file(event=None): text_field.text = "" @bindings.add('c-c') def do_exit(event=None): get_app().exit() def do_time_date(): text = datetime.datetime.now().isoformat() text_field.buffer.insert_text(text) def do_go_to(): async def coroutine(): dialog = TextInputDialog(title="Go to line", label_text="Line number:") line_number = await show_dialog_as_float(dialog) try: line_number = int(line_number) except ValueError: show_message("Invalid line number") else: text_field.buffer.cursor_position = text_field.buffer.document.translate_row_col_to_index( line_number - 1, 0) ensure_future(coroutine()) def do_undo(): text_field.buffer.undo() def do_cut(): data = text_field.buffer.cut_selection() get_app().clipboard.set_data(data) def do_copy(): data = text_field.buffer.copy_selection() get_app().clipboard.set_data(data) def do_delete(): text_field.buffer.cut_selection() def do_find(): start_search(text_field.control) def do_find_next(): search_state = get_app().current_search_state cursor_position = text_field.buffer.get_search_position( search_state, include_current_position=False) text_field.buffer.cursor_position = cursor_position def do_paste(): text_field.buffer.paste_clipboard_data(get_app().clipboard.get_data()) def do_select_all(): text_field.buffer.cursor_position = 0 text_field.buffer.start_selection() text_field.buffer.cursor_position = len(text_field.buffer.text) @bindings.add("c-e") def do_eval(event=None): if ApplicationState.context is None or ApplicationState.player is None: show_message("Error", "Cannot evaluate because no context is defined") return code = text_field.buffer.text try: script = ApplicationState.context.script now = ApplicationState.player.get_time() ctx = ApplicationState.context.fork(cursor=now) val = script.eval(code, context=ctx) if val is not None and isinstance(val, Music): pl = InteractivePlayer(lambda: val.expand(ctx), ApplicationState.player, realtime=True) ApplicationState.interactive_players.append(pl) create_task(pl.start()) except BaseException as e: if hasattr(e, 'message'): show_message("Eval Error", str(cast(Any, e).message)) else: show_message("Eval Error", str(e)) @bindings.add("c-s") def do_mute_players(event=None): for p in ApplicationState.interactive_players: create_task(p.stop()) ApplicationState.interactive_players = [] def do_status_bar(): ApplicationState.show_status_bar = not ApplicationState.show_status_bar # # The menu container. # root_container = MenuContainer( body=body, menu_items=[ MenuItem( "File", children=[ MenuItem("New...", handler=do_new_file), MenuItem("Open...", handler=do_open_file), MenuItem("Save"), MenuItem("Save as..."), MenuItem("-", disabled=True), MenuItem("Exit", handler=do_exit), ], ), MenuItem( "Edit", children=[ MenuItem("Undo", handler=do_undo), MenuItem("Cut", handler=do_cut), MenuItem("Copy", handler=do_copy), MenuItem("Paste", handler=do_paste), MenuItem("Delete", handler=do_delete), MenuItem("-", disabled=True), MenuItem("Find", handler=do_find), MenuItem("Find next", handler=do_find_next), MenuItem("Replace"), MenuItem("Go To", handler=do_go_to), MenuItem("Select All", handler=do_select_all), MenuItem("Time/Date", handler=do_time_date), ], ), MenuItem("View", children=[ MenuItem("Status Bar", handler=do_status_bar), ]), MenuItem("Info", children=[ MenuItem("About", handler=do_about), ]), ], floats=[ Float( xcursor=True, ycursor=True, content=CompletionsMenu(max_height=16, scroll_offset=1), ), ], key_bindings=bindings, ) style = Style.from_dict({ "status": "reverse", "shadow": "bg:#440044", }) layout = Layout(root_container, focused_element=text_field) application = Application( layout=layout, enable_page_navigation_bindings=True, style=style, mouse_support=True, full_screen=True, ) return application, text_field