Categories
DailyOps

How to pretty-print text files inside terminal

Pretty-print text files inside terminal using bat a cat clone with syntax highlighting and Git integration.

Install bat utility.

$ sudo apt install bat

Display help information.

$ batcat --help          
bat 0.12.1
A cat(1) clone with syntax highlighting and Git integration.

USAGE:
    batcat [OPTIONS] [FILE]...
    batcat <SUBCOMMAND>

OPTIONS:
    -l, --language <language>         
            Explicitly set the language for syntax highlighting. The language can be specified as a
            name (like 'C++' or 'LaTeX') or possible file extension (like 'cpp', 'hpp' or 'md'). Use
            '--list-languages' to show all supported language names and file extensions.
    -L, --list-languages              
            Display a list of supported languages for syntax highlighting.

    -m, --map-syntax <from:to>...     
            Map a file extension or file name to an existing syntax. For example, to highlight
            *.conf files with the INI syntax, use '-m conf:ini'. To highlight files named
            '.myignore' with the Git Ignore syntax, use '-m .myignore:gitignore'.
        --theme <theme>               
            Set the theme for syntax highlighting. Use '--list-themes' to see all available themes.
            To set a default theme, add the '--theme="..."' option to the configuration file or
            export the BAT_THEME environment variable (e.g.: export BAT_THEME="...").
        --list-themes                 
            Display a list of supported themes for syntax highlighting.

        --style <style-components>    
            Configure which elements (line numbers, file headers, grid borders, Git modifications,
            ..) to display in addition to the file contents. The argument is a comma-separated list
            of components to display (e.g. 'numbers,changes,grid') or a pre-defined style ('full').
            To set a default style, add the '--style=".."' option to the configuration file or
            export the BAT_STYLE environment variable (e.g.: export BAT_STYLE=".."). Possible
            values: *auto*, full, plain, changes, header, grid, numbers, snip.
    -p, --plain                       
            Only show plain style, no decorations. This is an alias for '--style=plain'. When '-p'
            is used twice ('-pp'), it also disables automatic paging (alias for '--style=plain
            --pager=never').
    -n, --number                      
            Only show line numbers, no other decorations. This is an alias for '--style=numbers'

    -A, --show-all                    
            Show non-printable characters like space, tab or newline. This option can also be used
            to print binary files. Use '--tabs' to control the width of the tab-placeholders.
    -r, --line-range <N:M>...         
            Only print the specified range of lines for each file. For example:
              '--line-range 30:40' prints lines 30 to 40
              '--line-range :40' prints lines 1 to 40
              '--line-range 40:' prints lines 40 to the end of the file
    -H, --highlight-line <N>...       
            Highlight the N-th line with a different background color

        --color <when>                
            Specify when to use colored output. The automatic mode only enables colors if an
            interactive terminal is detected. Possible values: *auto*, never, always.
        --italic-text <when>          
            Specify when to use ANSI sequences for italic text in the output. Possible values:
            always, *never*.
        --decorations <when>          
            Specify when to use the decorations that have been specified via '--style'. The
            automatic mode only enables decorations if an interactive terminal is detected. Possible
            values: *auto*, never, always.
        --paging <when>               
            Specify when to use the pager. To control which pager is used, set the PAGER or
            BAT_PAGER environment variables (the latter takes precedence) or use the '--pager'
            option. To disable the pager permanently, set BAT_PAGER to an empty string or set
            '--paging=never' in the configuration file. Possible values: *auto*, never, always.
        --pager <command>             
            Determine which pager is used. This option will overwrite the PAGER and BAT_PAGER
            environment variables. The default pager is 'less'. To disable the pager completely, use
            the '--paging' option. Example: '--pager "less -RF"'.
        --wrap <mode>                 
            Specify the text-wrapping mode (*auto*, never, character). The '--terminal-width' option
            can be used in addition to control the output width.
        --tabs <T>                    
            Set the tab width to T spaces. Use a width of 0 to pass tabs through directly

    -u, --unbuffered                  
            This option exists for POSIX-compliance reasons ('u' is for 'unbuffered'). The output is
            always unbuffered - this option is simply ignored.
        --terminal-width <width>      
            Explicitly set the width of the terminal instead of determining it automatically. If
            prefixed with '+' or '-', the value will be treated as an offset to the actual terminal
            width. See also: '--wrap'.
    -h, --help                        
            Print this help message.

    -V, --version                     
            Show version information.


ARGS:
    <FILE>...    
            File(s) to print / concatenate. Use a dash ('-') or no argument at all to read from
            standard input.

SUBCOMMANDS:
    cache    Modify the syntax-definition and theme cache

Display supported languages.

$ batcat --list-languages
ActionScript                         as
Advanced CSV                         csv, tsv
AppleScript                          applescript, script editor
ARM Assembly                         s, S
AsciiDoc                             adoc, asciidoc, asc
ASP                                  asa
Assembly (x86_64)                    yasm, nasm, asm, inc, mac
AWK                                  awk
Batch File                           bat, cmd
BibTeX                               bib
Bourne Again Shell (bash)            sh, bash, zsh, .bash_aliases, .bash_completions, .bash_functions, 
                                     .bash_login, .bash_logout, .bash_profile, .bash_variables, .bashrc, 
                                     .profile, .textmate_init, .zshrc, PKGBUILD, .ebuild, .eclass
C                                    c, h
C#                                   cs, csx
C++                                  cpp, cc, cp, cxx, c++, C, h, hh, hpp, hxx, h++, inl, ipp
Cabal                                cabal
Clojure                              clj, cljc, cljs, edn
CMake                                CMakeLists.txt, cmake
CMake C Header                       h.in
CMake C++ Header                     hh.in, hpp.in, hxx.in, h++.in
CMakeCache                           CMakeCache.txt
Crystal                              cr
CSS                                  css, css.erb, css.liquid
D                                    d, di
Dart                                 dart
Diff                                 diff, patch
Dockerfile                           Dockerfile, dockerfile
DotENV                               .env, .envrc, .env.dist, .env.local, .env.sample, .env.example, 
                                     .env.test, .env.test.local, .env.dev, .env.development, 
                                     .env.development.local, .env.prod, .env.production, 
                                     .env.production.local, .env.dusk.local
Elixir                               ex, exs
Elm                                  elm
Erlang                               erl, hrl, Emakefile, emakefile
F#                                   fs, fsi, fsx
F#                                   fs, fsi, fsx
friendly interactive shell (fish)    fish
Git Attributes                       attributes, gitattributes, .gitattributes
Git Commit                           COMMIT_EDITMSG, MERGE_MSG, TAG_EDITMSG
Git Config                           gitconfig, .gitconfig, .gitmodules
Git Ignore                           exclude, gitignore, .gitignore
Git Link                             .git
Git Log                              gitlog
Git Rebase Todo                      git-rebase-todo
Go                                   go
Graphviz (DOT)                       dot, DOT, gv
Groovy                               groovy, gvy, gradle, Jenkinsfile
Haskell                              hs
Haskell (improved)                   hs, hsc
Highlight non-printables             show-nonprintable
hosts                                hosts
HTML                                 html, htm, shtml, xhtml
HTML (ASP)                           asp
HTML (EEx)                           html.eex
HTML (Erlang)                        yaws
HTML (Rails)                         rails, rhtml, erb, html.erb
HTML (Tcl)                           adp
HTML (Twig)                          twig, html.twig
INI                                  ini, INI, INF, reg, REG, lng, cfg, CFG, desktop, url, URL, 
                                     .editorconfig, .hgrc, hgrc
Java                                 java, bsh
Java Properties                      properties
Java Server Page (JSP)               jsp
JavaScript                           js, htc
JavaScript (Babel)                   js, jsx, babel, es6
JavaScript (Rails)                   js.erb
JSON                                 json, sublime-settings, sublime-menu, sublime-keymap, 
                                     sublime-mousemap, sublime-theme, sublime-build, sublime-project, 
                                     sublime-completions, sublime-commands, sublime-macro, 
                                     sublime-color-scheme, ipynb, Pipfile.lock
jsonnet                              jsonnet, libsonnet, libjsonnet
Julia                                jl
Kotlin                               kt, kts
LaTeX                                tex, ltx
Less                                 less, css.less
Lisp                                 lisp, cl, clisp, l, mud, el, scm, ss, lsp, fasl
Literate Haskell                     lhs
Lua                                  lua
Makefile                             make, GNUmakefile, makefile, Makefile, makefile.am, Makefile.am, 
                                     makefile.in, Makefile.in, OCamlMakefile, mak, mk
Manpage                              man
Markdown                             md, mdown, markdown, markdn
MATLAB                               matlab
NAnt Build File                      build
Nix                                  nix
Objective-C                          m, h
Objective-C++                        mm, M, h
OCaml                                ml, mli
OCamllex                             mll
OCamlyacc                            mly
orgmode                              org
Pascal                               pas, p, dpr
Perl                                 pl, pm, pod, t, PL
PHP                                  php, php3, php4, php5, php7, phps, phpt, phtml
Plain Text                           txt
PowerShell                           ps1, psm1, psd1
Protocol Buffer                      proto, protodevel
Protocol Buffer (TEXT)               pb.txt, proto.text, textpb, pbtxt, prototxt
Puppet                               pp, epp
PureScript                           purs
Python                               py, py3, pyw, pyi, pyx, pyx.in, pxd, pxd.in, pxi, pxi.in, rpy, cpy, 
                                     SConstruct, Sconstruct, sconstruct, SConscript, gyp, gypi, Snakefile, 
                                     wscript
R                                    R, r, s, S, Rprofile
Rd (R Documentation)                 rd
Regular Expression                   re
requirements.txt                     requirements.txt
reStructuredText                     rst, rest
Robot Framework syntax highlighting. robot
Ruby                                 rb, Appfile, Appraisals, Berksfile, Brewfile, capfile, cgi, Cheffile, 
                                     config.ru, Deliverfile, Fastfile, fcgi, Gemfile, gemspec, Guardfile, 
                                     irbrc, jbuilder, Podfile, podspec, prawn, rabl, rake, Rakefile, 
                                     Rantfile, rbx, rjs, ruby.rail, Scanfile, simplecov, Snapfile, thor, 
                                     Thorfile, Vagrantfile
Ruby Haml                            haml, sass
Ruby on Rails                        rxml, builder
Rust                                 rs
Sass                                 sass
Scala                                scala, sbt
SCSS                                 scss
SQL                                  sql, ddl, dml
SQL (Rails)                          erbsql, sql.erb
SSH Config                           ssh_config
SSHD Config                          sshd_config
Strace                               strace
Swift                                swift
syslog                               log
Tcl                                  tcl
Terraform                            tf, tfvars, hcl
TeX                                  sty, cls
Textile                              textile
TOML                                 toml, tml, Cargo.lock, Gopkg.lock, Pipfile
TypeScript                           ts
TypeScriptReact                      tsx
varlink                              varlink
Verilog                              v, V
VimL                                 vim, .vimrc
XML                                  xml, xsd, xslt, tld, dtml, rss, opml, svg
YAML                                 yaml, yml, sublime-syntax

Display supported themes.

$ batcat --list-themes   
Theme: 1337

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: DarkNeon

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: GitHub

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: Monokai Extended

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: Monokai Extended Bright

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: Monokai Extended Light

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: Monokai Extended Origin

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: OneHalfDark

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: OneHalfLight

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: Sublime Snazzy

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: TwoDark

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: ansi-dark

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: ansi-light

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: base16

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Theme: zenburn

  // Output the square of a number.
  fn print_square(num: f64) {
      let result = f64::powf(num, 2.0);
      println!("The square of {:.2} is {:.2}.", num, result);
  }

Sample usage.

$ batcat --plain --line-range 23:41 --highlight-line 39 --highlight-line 40 --language go --theme "TwoDark"  src/crio-top/main.go        
    for {
        // clear screen
        terminal.Clear()

        // display date
        terminal.CreateDateLine()

        // create empty line
        terminal.CreateEmptyLine()

        // display header
        terminal.PrintHeader(appConfiguration)

        // display data
        terminal.PrintRows(appConfiguration, backgroundProcess)

        // sleep for a duration defined in YAML configuration                                                
        time.Sleep(time.Duration(appConfiguration.Application.Refresh.Window) * time.Second)                 
    }

Set BAT_THEME variable and export it.

$ export BAT_THEME="OneHalfDark"

Pretty print git diff.

$ git diff 31a5c52..6be13cb | batcat --plain
diff --git a/31a5c52 b/6be13cb
index 31a5c52..6be13cb 100644
--- a/31a5c52
+++ b/6be13cb
@@ -10,7 +10,7 @@ This is a playground to learn Go language.
 sample output using provided configuration
 
 ```
-$ crtop --configuration configuration.yaml 
+$ crio-top --configuration configuration.yaml 
 ```
 
 ```
$ git diff src/crio-top/main.go | batcat --plain                      
diff --git a/src/crio-top/main.go b/src/crio-top/main.go
index 7c23f5e..16b0083 100644
--- a/src/crio-top/main.go
+++ b/src/crio-top/main.go
@@ -3,10 +3,10 @@
 package main
 
 import (
+   "time"
    "golang/src/background"
    "golang/src/configuration"
    "golang/src/terminal"
-   "time"
 )
 
 func main() {
@@ -21,7 +21,7 @@ func main() {
 
    // display results
    for {
-       // clear screen and return to the right-left corner
+       // clear screen
        terminal.Clear()
 
        // display date
@@ -36,7 +36,7 @@ func main() {
        // display data
        terminal.PrintRows(appConfiguration, backgroundProcess)
 
-       // sleep for a defined duration
+       // sleep for a duration defined in YAML configuration
        time.Sleep(time.Duration(appConfiguration.Application.Refresh.Window) * time.Second)
    }
 }

Pretty print git log.

$ git log -1 | batcat --plain
commit 4052d3ad2bc1a7dc4cb8d960dfb2d409140ddb94
Author: Milosz Galazka <milosz@sleeplessbeastie.eu>
Date:   Sun May 16 22:41:34 2021 +0200

    readme fixes