Bat: How to Use It with the fzf Preview

Updated

Learn how to use bat as the file preview in fzf, with syntax highlighting

Bat: How to Use It with the fzf Preview

Before we start, make sure you have bat and fzf installed on your computer and some files ready in a folder. If you don't have them yet, you can install both with Homebrew:

brew install bat fzf

First, open your terminal and navigate to the folder with your files. To add a bat preview to fzf, run this command:

fzf --preview 'bat --color=always {}'

The --preview flag runs a command for whichever file is highlighted, and {} gets replaced with that file name. The --color=always flag matters, because bat turns its colors off when it runs inside another program, so without it your preview would be plain text.

You should now see your list of files on the left and a live preview on the right. Type a few letters to filter the list, and the preview follows along.

For a cleaner preview that stays fast on big files, use this version:

fzf --preview 'bat --color=always --style=numbers --line-range :500 {}' --preview-window 'right:60%'

The --style=numbers flag drops bat's header and borders, --line-range :500 only loads the first 500 lines, and --preview-window 'right:60%' gives the preview 60% of the width.

undefined

To get the same preview when you press control + T in your terminal, add this line to your ~/.zshrc file. It only works if fzf's shell integration is loaded, which is source <(fzf --zsh):

export FZF_CTRL_T_OPTS="--preview 'bat --color=always --style=numbers --line-range :500 {}'"