From ab2b2cff45ee65e3c9f2d79da8c91e898f887b7c Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Fri, 9 Oct 2020 16:30:04 -0700 Subject: [PATCH] Add pane:get_lines_as_text() lua method Allows this: ```lua local wezterm = require 'wezterm'; local io = require 'io'; local os = require 'os'; wezterm.on("trigger-vim-with-scrollback", function(window, pane) -- Retrieve the current viewport's text. -- Pass an optional number of lines (eg: 2000) to retrieve -- that number of lines starting from the bottom of the viewport local scrollback = pane:get_lines_as_text(); -- Create a temporary file to pass to vim local name = os.tmpname(); local f = io.open(name, "w+"); f:write(scrollback); f:flush(); f:close(); -- Open a new window running vim and tell it to open the file window:perform_action(wezterm.action{SpawnCommandInNewWindow={ args={"vim", name}} }, pane) -- After vim is up and running we should remove the file, -- but we can't do this right now as the window and processing -- spawning are asynchronous and we'll probably delete the -- file while vim is starting up :-/ -- os.remove(name); end) return { keys = { {key="E", mods="CTRL", action=wezterm.action{EmitEvent="trigger-vim-with-scrollback"}}, } } ``` refs: #222 --- wezterm/src/scripting/pane.rs | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/wezterm/src/scripting/pane.rs b/wezterm/src/scripting/pane.rs index 8e45ef8a9..b804fb4a9 100644 --- a/wezterm/src/scripting/pane.rs +++ b/wezterm/src/scripting/pane.rs @@ -48,5 +48,30 @@ impl UserData for PaneObject { methods.add_method("get_dimensions", |_, this, _: ()| { Ok(this.pane()?.renderer().get_dimensions()) }); + + // When called with no arguments, returns the lines from the + // viewport as plain text (no escape sequences). + // When called with an optional integer argument, returns the + // last nlines lines of the terminal output. + // The returned string will have trailing whitespace trimmed. + methods.add_method("get_lines_as_text", |_, this, nlines: Option| { + let pane = this.pane()?; + let mut render = pane.renderer(); + let dims = render.get_dimensions(); + let nlines = nlines.unwrap_or(dims.viewport_rows); + let bottom_row = dims.physical_top + dims.viewport_rows as isize; + let top_row = bottom_row.saturating_sub(nlines as isize); + let (_first_row, lines) = render.get_lines(top_row..bottom_row); + let mut text = String::new(); + for line in lines { + for (_, cell) in line.visible_cells() { + text.push_str(cell.str()); + } + let trimmed = text.trim_end().len(); + text.truncate(trimmed); + text.push('\n'); + } + Ok(text) + }); } }