How to use visidata - 10 common examples

To help you get started, we’ve selected a few visidata examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github saulpw / visidata / visidata / sheets.py View on Github external
def drawColHeader(self, scr, y, h, vcolidx):
        'Compose and draw column header for given vcolidx.'
        col = self.visibleCols[vcolidx]

        # hdrattr highlights whole column header
        # sepattr is for header separators and indicators
        sepcattr = colors.get_color('color_column_sep')

        hdrcattr = self._colorize(col, None)
        if vcolidx == self.cursorVisibleColIndex:
            hdrcattr = update_attr(hdrcattr, colors.color_current_hdr, 2)

        C = options.disp_column_sep
        if (self.keyCols and col is self.keyCols[-1]) or vcolidx == self.rightVisibleColIndex:
            C = options.disp_keycol_sep

        x, colwidth = self.visibleColLayout[vcolidx]

        # AnameTC
        T = getType(col.type).icon
        if T is None:  # still allow icon to be explicitly non-displayed ''
            T = '?'

        hdrs = col.name.split('\n')
        for i in range(h):
            name = ' '  # save room at front for LeftMore
            if h-i-1 < len(hdrs):
                name += hdrs[::-1][h-i-1]
github saulpw / visidata / visidata / _sheet.py View on Github external
T = '?'

        hdrs = col.name.split('\n')
        for i in range(h):
            name = ' '  # save room at front for LeftMore
            if h-i-1 < len(hdrs):
                name += hdrs[::-1][h-i-1]

            if len(name) > colwidth-1:
                name = name[:colwidth-len(options.disp_truncator)] + options.disp_truncator

            if i == h-1:
                hdrattr = hdrattr.update_attr(colors.color_bottom_hdr, 5)

            clipdraw(scr, y+i, x, name, hdrattr.attr, colwidth)
            vd.onMouse(scr, y+i, x, 1, colwidth, BUTTON3_RELEASED='rename-col')

            if C and x+colwidth+len(C) < self.windowWidth:
                scr.addstr(y+i, x+colwidth, C, sepattr)

        clipdraw(scr, y+h-1, x+colwidth-len(T), T, hdrattr.attr, len(T))

        try:
            if vcolidx == self.leftVisibleColIndex and col not in self.keyCols and self.nonKeyVisibleCols.index(col) > 0:
                A = options.disp_more_left
                scr.addstr(y, x, A, sepattr)
        except ValueError:  # from .index
            pass
github saulpw / visidata / visidata / saving.py View on Github external
from visidata import BaseSheet, Sheet, Column, fail, confirm, CellColorizer, RowColorizer, asyncthread, options, saveSheets, inputPath, getDefaultSaveName, warning, status, Path, copy, Progress, option


option('color_add_pending', 'green', 'color for rows pending add')
option('color_change_pending', 'reverse yellow', 'color for cells pending modification')
option('color_delete_pending', 'red', 'color for rows pending delete')


# deferred cached
Sheet.init('_deferredAdds', dict) # [s.rowid(row)] -> row
Sheet.init('_deferredMods', dict) # [s.rowid(row)] -> (row, { [col] -> val })
Sheet.init('_deferredDels', dict) # [s.rowid(row)] -> row

Sheet.colorizers += [
        CellColorizer(8, 'color_change_pending', lambda s,c,r,v: s.changed(c, r)),
        RowColorizer(9, 'color_delete_pending', lambda s,c,r,v: s.rowid(r) in s._deferredDels),
        RowColorizer(9, 'color_add_pending', lambda s,c,r,v: s.rowid(r) in s._deferredAdds),
    ]


@Sheet.api
def reset(self, *rows):
    self._deferredAdds.clear()
    self._deferredMods.clear()
    self._deferredDels.clear()
github saulpw / visidata / visidata / shell.py View on Github external
import shlex
            args = []
            lmr = LazyMapRow(self.source, row)
            for arg in shlex.split(self.expr):
                if arg.startswith('$'):
                    args.append(str(lmr[arg[1:]]))
                else:
                    args.append(arg)

            p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            return p.communicate()
        except Exception as e:
            exceptionCaught(e)


class DirSheet(Sheet):
    'Sheet displaying directory, using ENTER to open a particular file.  Edited fields are applied to the filesystem.'
    rowtype = 'files' # rowdef: Path
    columns = [
        DeferredSetColumn('directory',
            getter=lambda col,row: row.parent.relpath(col.sheet.source.resolve()),
            setter=lambda col,row,val: col.sheet.moveFile(row, val)),
        DeferredSetColumn('filename',
            getter=lambda col,row: row.name + row.ext,
            setter=lambda col,row,val: col.sheet.renameFile(row, val)),
        DeferredSetColumn('pathname', width=0,
            getter=lambda col,row: row.resolve(),
            setter=lambda col,row,val: os.rename(row.resolve(), val)),
        Column('ext', getter=lambda col,row: row.is_dir() and '/' or row.suffix),
        DeferredSetColumn('size', type=int,
            getter=lambda col,row: row.stat().st_size,
            setter=lambda col,row,val: os.truncate(row.resolve(), int(val))),
github saulpw / visidata / vgit / overview.py View on Github external
cmdparts = cmd.split()
        if cmdparts[0] == 'git':
            cmdparts = cmdparts[1:]
        self.cmd = cmdparts + list(args)

    def calcValue(self, r):
        return list(vgit.git_lines('--git-dir', r.path.joinpath('.git'), *self.cmd))


class GitAllColumn(GitLinesColumn):
    def calcValue(self, r):
        return vgit.git_all('--git-dir', r.path.joinpath('.git'), *self.cmd).strip()



class GitOverview(Sheet):
    rowtype = 'repos'  # rowdef: GitRepo
    columns = [
        ColumnAttr('repo', 'path', type=str),
        GitLinesColumn('stashes', 'git stash list', type=vlen),
        GitLinesColumn('cached', 'git diff --cached', type=vlen),
        GitLinesColumn('branches', 'git branch --no-color', type=vlen),
        GitAllColumn('branch', 'git rev-parse --abbrev-ref HEAD'),
        Column('modtime', type=date, getter=lambda c,r: modtime(r.path)),
    ]
    nKeys = 1

    @asyncthread
    def reload(self):
        import glob
        import os.path
        self.rows = []
github saulpw / visidata / plugins / defermods.py View on Github external
if rowid not in col.sheet._deferredMods:
                rowmods = {}
                col.sheet._deferredMods[rowid] = (row, rowmods)
            else:
                _, rowmods = col.sheet._deferredMods[rowid]
            rowmods[col] = val
    else:
        col._dm_setValue(row, val)

Sheet.addCommand('^S', 'commit-sheet', 'commit()')
unbindkey('g^S')
Sheet.bindkey('g^S', 'save-sheet')
BaseSheet.addCommand('^R', 'reload-sheet', '_dm_reload(); recalc(); status("reloaded")'),
Sheet.addCommand('z^R', 'reload-row', 'undoMod(cursorRow)')
Sheet.addCommand('z^R', 'reload-row', 'undoMod(cursorRow)')
Sheet.addCommand('gz^R', 'reload-rows', 'for r in selectedRows: undoMod(r)')

JoinSheet.trackmods = False
vd.cmdlog.trackmods = False
ColumnsSheet.trackmods = False
OptionsSheet.trackmods = False
PivotSheet.trackmods = False
IndexSheet.trackmods = False
MeltedSheet.trackmods = False
TransposeSheet.trackmods = False

Sheet.addCommand('d', 'delete-row', 'vd.cliprows = [(sheet, cursorRowIndex, deleteRows([cursorRow]))]; not sheet.defermods or cursorDown(1)')
github saulpw / visidata / visidata / _profile.py View on Github external
if self.thread.profile:
            self.thread.profile.disable()
            self.thread.profile.dump_stats(options.profile + str(self.profileNumber))

        if exc_val:
            self.thread.exception = exc_val
        else:
            # remove very-short-lived async actions
            if elapsed_s(self.thread) < min_thread_time_s:
                vd().threads.remove(self.thread)

class ProfileSheet(Sheet):
    columns = [
        Column('funcname', getter=lambda col,row: codestr(row.code)),
        Column('filename', getter=lambda col,row: os.path.split(row.code.co_filename)[-1] if not isinstance(row.code, str) else ''),
        Column('linenum', type=int, getter=lambda col,row: row.code.co_firstlineno if not isinstance(row.code, str) else None),

        Column('inlinetime_us', type=int, getter=lambda col,row: row.inlinetime*1000000),
        Column('totaltime_us', type=int, getter=lambda col,row: row.totaltime*1000000),
        ColumnAttr('callcount', type=int),
        Column('avg_inline_us', type=int, getter=lambda col,row: row.inlinetime*1000000/row.callcount),
        Column('avg_total_us', type=int, getter=lambda col,row: row.totaltime*1000000/row.callcount),
        ColumnAttr('reccallcount', type=int),
        ColumnAttr('calls'),
        Column('callers', getter=lambda col,row: col.sheet.callers[row.code]),
    ]

    nKeys=3

    def reload(self):
        self.rows = self.source
        self.orderBy(self.column('inlinetime_us'), reverse=True)
github saulpw / visidata / plugins / defermods.py View on Github external
@Sheet.api
def putChanges(sheet, path, adds, changes, deletes):
    'Commit changes to path.  adds/changes/deletes are a diffset to apply to the last load from or commit to path.  By default this overwrites completely, saving as filetype to path, with filetype from path ext.'
    sheet.commitAdds()
    sheet.commitMods()
    sheet.commitDeletes()
    if sheet.defermods:
        saveSheets(path, sheet, confirm_overwrite=False)
    else:
        saveSheets(inputPath("save to: ", value=sheet.getDefaultSaveName()), sheet, confirm_overwrite=options.confirm_overwrite)

    # clear after save, to ensure cstr (in commit()) is aware of deletes
    # specifically, for the case where deletes are committed automatically (defermods = False)
    sheet._deferredDels.clear()
github saulpw / visidata / visidata / saving.py View on Github external
from visidata import BaseSheet, Sheet, Column, fail, confirm, CellColorizer, RowColorizer, asyncthread, options, saveSheets, inputPath, getDefaultSaveName, warning, status, Path, copy, Progress, option


option('color_add_pending', 'green', 'color for rows pending add')
option('color_change_pending', 'reverse yellow', 'color for cells pending modification')
option('color_delete_pending', 'red', 'color for rows pending delete')


# deferred cached
Sheet.init('_deferredAdds', dict) # [s.rowid(row)] -> row
Sheet.init('_deferredMods', dict) # [s.rowid(row)] -> (row, { [col] -> val })
Sheet.init('_deferredDels', dict) # [s.rowid(row)] -> row

Sheet.colorizers += [
        CellColorizer(8, 'color_change_pending', lambda s,c,r,v: s.changed(c, r)),
        RowColorizer(9, 'color_delete_pending', lambda s,c,r,v: s.rowid(r) in s._deferredDels),
        RowColorizer(9, 'color_add_pending', lambda s,c,r,v: s.rowid(r) in s._deferredAdds),
    ]


@Sheet.api
github saulpw / visidata / visidata / _profile.py View on Github external
if exc_val:
            self.thread.exception = exc_val
        else:
            # remove very-short-lived async actions
            if elapsed_s(self.thread) < min_thread_time_s:
                vd().threads.remove(self.thread)

class ProfileSheet(Sheet):
    columns = [
        Column('funcname', getter=lambda col,row: codestr(row.code)),
        Column('filename', getter=lambda col,row: os.path.split(row.code.co_filename)[-1] if not isinstance(row.code, str) else ''),
        Column('linenum', type=int, getter=lambda col,row: row.code.co_firstlineno if not isinstance(row.code, str) else None),

        Column('inlinetime_us', type=int, getter=lambda col,row: row.inlinetime*1000000),
        Column('totaltime_us', type=int, getter=lambda col,row: row.totaltime*1000000),
        ColumnAttr('callcount', type=int),
        Column('avg_inline_us', type=int, getter=lambda col,row: row.inlinetime*1000000/row.callcount),
        Column('avg_total_us', type=int, getter=lambda col,row: row.totaltime*1000000/row.callcount),
        ColumnAttr('reccallcount', type=int),
        ColumnAttr('calls'),
        Column('callers', getter=lambda col,row: col.sheet.callers[row.code]),
    ]

    nKeys=3

    def reload(self):
        self.rows = self.source
        self.orderBy(self.column('inlinetime_us'), reverse=True)
        self.callers = collections.defaultdict(list)  # [row.code] -> list(code)

        for r in self.rows:
            calls = getattr(r, 'calls', None)