package termstate // Resize changes the terminal's size without reflowing, as the app's live // emulator does: narrowing cuts rows (scrollback too) at the new width; // fewer rows move the rows above the cursor into the scrollback (main // screen) so the cursor's row stays on screen; more rows bring scrollback // back. The scroll region becomes the whole screen. func (t *Terminal) Resize(cols, rows int) { cols, rows = max(cols, 1), max(rows, 1) if cols == t.cols && rows == t.rows { return } if cols < t.cols { for _, lines := range [][]*line{t.main.lines, t.alt.lines, t.history} { for _, l := range lines { l.truncate(cols) } } } mainY, altY := &t.main.saved.y, &t.alt.saved.y if t.scr == &t.main { mainY = &t.cur.y } else { altY = &t.cur.y } t.main.lines = t.resizeRows(t.main.lines, rows, cols, mainY, true) t.alt.lines = t.resizeRows(t.alt.lines, rows, cols, altY, false) // The last row's continuation (if any) is gone. t.main.lines[rows-1].cont, t.alt.lines[rows-1].cont = false, false old := t.tabs t.cols, t.rows = cols, rows t.resetTabs() copy(t.tabs, old) t.top, t.bottom = 0, rows-1 t.cur.x, t.cur.y = min(t.cur.x, cols-1), min(max(t.cur.y, 0), rows-1) t.cur.wrap = t.cur.wrap && t.cur.x == cols-1 for _, s := range []*screen{&t.main, &t.alt} { s.saved.x, s.saved.y = min(s.saved.x, cols-1), min(max(s.saved.y, 0), rows-1) } } // resizeRows gives one screen rows rows, keeping the row at *anchor // visible and moving it with the content. func (t *Terminal) resizeRows(lines []*line, rows, cols int, anchor *int, main bool) []*line { n := len(lines) if rows < n { push := min(max(0, *anchor-(rows-1)), n-rows) for _, l := range lines[:push] { if main { t.keep(l) } } *anchor -= push return append([]*line(nil), lines[push:push+rows]...) } resized := make([]*line, 0, rows) if main { var back []*line for len(back) < rows-n { l := t.popScrollback() if l == nil { break } back = append(back, l) } for i := len(back) - 1; i >= 0; i-- { resized = append(resized, back[i]) } *anchor += len(back) } resized = append(resized, lines...) for len(resized) < rows { resized = append(resized, &line{}) } return resized }