bat Documentation

A cat(1) clone with wings.

RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy bat on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name bat -p 80:80 --restart always sharkdp/bat:latest

File: README.md

Syntax highlighting

bat supports syntax highlighting for a large number of programming and markup
languages:

Git integration

bat communicates with git to show modifications with respect to the index
(see left sidebar):

Show non-printable characters

You can use the -A/--show-all option to show and highlight non-printable
characters:

Automatic paging

By default, bat pipes its own output to a pager (e.g. less) if the output is too large for one screen.
If you would rather bat work like cat all the time (never page output), you can set --paging=never as an option, either on the command line or in your configuration file.
If you intend to alias cat to bat in your shell configuration, you can use alias cat='bat --paging=never' to preserve the default behavior.

File concatenation

Even with a pager set, you can still use bat to concatenate files :wink:.
Whenever bat detects a non-interactive terminal (i.e. when you pipe into another process or into a file), bat will act as a drop-in replacement for cat and fall back to printing the plain file contents, regardless of the --pager option's value.

How to use

Display a single file on the terminal

bash
bat README.md

Display multiple files at once

bash
bat src/*.rs

Read from stdin, determine the syntax automatically (note, highlighting will
only work if the syntax can be determined from the first line of the file,
usually through a shebang such as #!/bin/sh)

bash
curl -s https://sh.rustup.rs | bat

Read from stdin, specify the language explicitly

bash
yaml2json .travis.yml | json_pp | bat -l json

Show and highlight non-printable characters:

bash
bat -A /etc/hosts

Use it as a cat replacement:

bash
bat > note.md  # quickly create a new file

bat header.md content.md footer.md > document.md

bat -n main.rs  # show line numbers (only)

bat f - g  # output 'f', then stdin, then 'g'.

Integration with other tools

`fzf`

You can use bat as a previewer for fzf. To do this,
use bat's --color=always option to force colorized output. You can also use --line-range
option to restrict the load times for long files:

bash
fzf --preview "bat --color=always --style=numbers --line-range=:500 {}"

For more information, see fzf's README.

`find` or `fd`

You can use the -exec option of find to preview all search results with bat:

bash
find … -exec bat {} +

If you happen to use fd, you can use the -X/--exec-batch option to do the same:

bash
fd … -X bat

`ripgrep`

With batgrep, bat can be used as the printer for ripgrep search results.

bash
batgrep needle src/

`tail -f`

bat can be combined with tail -f to continuously monitor a given file with syntax highlighting.

bash
tail -f /var/log/pacman.log | bat --paging=never -l log

Note that we have to switch off paging in order for this to work. We have also specified the syntax
explicitly (-l log), as it can not be auto-detected in this case.

`git`

You can combine bat with git show to view an older version of a given file with proper syntax
highlighting:

bash
git show v0.6.0:src/main.rs | bat -l rs

`git diff`

You can combine bat with git diff to view lines around code changes with proper syntax
highlighting:

bash
batdiff() {
    git diff --name-only --relative --diff-filter=d -z | xargs -0 bat --diff
}

If you prefer to use this as a separate tool, check out batdiff in bat-extras.

If you are looking for more support for git and diff operations, check out delta.

`xclip`

The line numbers and Git modification markers in the output of bat can make it hard to copy
the contents of a file. To prevent this, you can call bat with the -p/--plain option or
simply pipe the output into xclip:

bash
bat main.cpp | xclip

bat will detect that the output is being redirected and print the plain file contents.

`man`

bat can be used as a colorizing pager for man, by setting the
MANPAGER environment variable:

bash
export MANPAGER="bat -plman"
man 2 select

(on some older Debian or Ubuntu releases, the executable is named batcat instead of bat)

If you prefer to have this bundled in a new command, you can also use batman.

Note that the Manpage syntax is developed in this repository and still needs some work.

`prettier` / `shfmt` / `rustfmt`

The prettybat script is a wrapper that will format code and print it with bat.

Highlighting `--help` messages

You can use bat to colorize help text: $ cp --help | bat -plhelp

You can also use a wrapper around this:

bash
# in your .bashrc/.zshrc/*rc
alias bathelp='bat --plain --language=help'
help() {
    "$@" --help 2>&1 | bathelp
}

Then you can do $ help cp or $ help git commit.

When you are using zsh, you can also use global aliases to override -h and --help entirely:

bash
alias -g -- -h='-h 2>&1 | bat --language=help --style=plain'
alias -g -- --help='--help 2>&1 | bat --language=help --style=plain'

For fish, you can use abbreviations:

fish
abbr -a --position anywhere -- --help '--help | bat -plhelp'
abbr -a --position anywhere -- -h '-h | bat -plhelp'

This way, you can keep on using cp --help, but get colorized help pages.

[!TIP]
To remove these abbreviations later, run:

fish
abbr -e -- --help
abbr -e -- -h

The -- before the abbreviation name is required because --help and -h start with dashes, which would otherwise be interpreted as flags to abbr itself.

Be aware that in some cases, -h may not be a shorthand of --help (for example with ls). In cases where you need to use -h
as a command argument you can prepend \ to the argument (eg. ls \-h) to escape the aliasing defined above.

Please report any issues with the help syntax in this repository.

Installation

On Ubuntu (using `apt`)

... and other Debian-based Linux distributions.

bat is available on Ubuntu since 20.04 ("Focal") and Debian since August 2021 (Debian 11 - "Bullseye").

If your Ubuntu/Debian installation is new enough you can simply run:

bash
sudo apt install bat

Important: On some older Ubuntu/Debian releases, the executable is installed as batcat instead of bat (due to a name
clash with another package
). On newer releases, the executable is available as bat. If bat --version does not work after installation, try batcat --version instead. You can set up a bat -> batcat symlink or alias to prevent any issues that may come up because of this and to be consistent with other distributions:

bash
mkdir -p ~/.local/bin
ln -s /usr/bin/batcat ~/.local/bin/bat

an example alias for batcat as bat:

bash
alias bat="batcat"

On Ubuntu (using most recent `.deb` packages)

... and other Debian-based Linux distributions.

If the package has not yet been promoted to your Ubuntu/Debian installation, or you want
the most recent release of bat, download the latest .deb package from the
release page and install it via:

bash
sudo dpkg -i bat_0.18.3_amd64.deb  # adapt version number and architecture

On Alpine Linux

You can install the bat package
from the official sources, provided you have the appropriate repository enabled:

bash
apk add bat

On Arch Linux

You can install the bat package
from the official sources:

bash
pacman -S bat

On Fedora

You can install the bat package from the official sources:

bash
dnf install bat

On Gentoo Linux

You can install the bat package
from the official sources:

bash
emerge sys-apps/bat

On FreeBSD

You can install a precompiled bat package with pkg:

bash
pkg install bat

or build it on your own from the FreeBSD ports:

bash
cd /usr/ports/textproc/bat
make install

On OpenBSD

You can install bat package using pkg_add(1):

bash
pkg_add bat

Via nix

You can install bat using the nix package manager:

bash
nix-env -i bat

On openSUSE

You can install bat with zypper:

bash
zypper install bat

Via snap package

There is currently no recommended snap package available.
Existing packages may be available, but are not officially supported and may contain issues.

On macOS (or Linux) via Homebrew

You can install bat with Homebrew:

bash
brew install bat

On macOS via MacPorts

Or install bat with MacPorts:

bash
port install bat

On Windows

There are a few options to install bat on Windows. Once you have installed bat,
take a look at the "Using bat on Windows" section.

Prerequisites

You will need to install the Visual C++ Redistributable

With WinGet

You can install bat via WinGet:

bash
winget install sharkdp.bat

With Chocolatey

You can install bat via Chocolatey:

bash
choco install bat

With Scoop

You can install bat via scoop:

bash
scoop install bat

From prebuilt binaries:

You can download prebuilt binaries from the Release page,

You will need to install the Visual C++ Redistributable package.

From binaries

Check out the Release page for
prebuilt versions of bat for many different architectures. Statically-linked
binaries are also available: look for archives with musl in the file name.

From source

If you want to build bat from source, you need Rust 1.79.0 or
higher. You can then use cargo to build everything:

From local source

bash
cargo install --path . --locked

[!NOTE]
The --path . above specifies the directory of the source code and NOT where bat will be installed.
For more information see the docs for cargo install.

From `crates.io`

bash
cargo install --locked bat

Note that additional files like the man page or shell completion
files can not be installed automatically in both these ways.
If installing from a local source, they will be generated by cargo
and should be available in the cargo target folder under build.

Furthermore, shell completions are also available by running:

bash
bat --completion <shell>
# see --help for supported shells

Customization

Highlighting theme

Use bat --list-themes to get a list of all available themes for syntax
highlighting. By default, bat uses Monokai Extended or Monokai Extended Light
for dark and light themes respectively. To select the TwoDark theme, call bat
with the --theme=TwoDark option or set the BAT_THEME environment variable to
TwoDark. Use export BAT_THEME="TwoDark" in your shell's startup file to
make the change permanent. Alternatively, use bat's
configuration file.

If you want to preview the different themes on a custom file, you can use
the following command (you need fzf for this):

bash
bat --list-themes | fzf --preview="bat --theme={} --color=always /path/to/file"

bat automatically picks a fitting theme depending on your terminal's background color.
You can use the --theme-dark / --theme-light options or the BAT_THEME_DARK / BAT_THEME_LIGHT environment variables
to customize the themes used. This is especially useful if you frequently switch between dark and light mode.

You can also use a custom theme by following the
'Adding new themes' section below.

8-bit themes

bat has three themes that always use 8-bit colors,
even when truecolor support is available:

  • ansi looks decent on any terminal. It uses 3-bit colors: black, red, green,
    yellow, blue, magenta, cyan, and white.
  • base16 is designed for base16 terminal themes. It uses
    4-bit colors (3-bit colors plus bright variants) in accordance with the
    base16 styling guidelines.
  • base16-256 is designed for tinted-shell.
    It replaces certain bright colors with 8-bit colors from 16 to 21. Do not use this simply
    because you have a 256-color terminal but are not using tinted-shell.

Although these themes are more restricted, they have three advantages over truecolor themes. They:

  • Enjoy maximum compatibility. Some terminal utilities do not support more than 3-bit colors.
  • Adapt to terminal theme changes. Even for already printed output.
  • Visually harmonize better with other terminal software.

Output style

You can use the --style option to control the appearance of bat's output.
You can use --style=numbers,changes, for example, to show only Git changes
and line numbers but no grid and no file header. Set the BAT_STYLE environment
variable to make these changes permanent or use bat's
configuration file.

By default, bat enables changes, grid, header-filename, numbers, and snip.

The available pre-defined styles are:

Style Description
default Enables the recommended style components listed above.
full Enables all available components.
auto Same as default, unless the output is piped.
plain Disables all available components.

The available individual components are:

Component Description
changes Show Git modification markers.
header Alias for header-filename.
header-filename Show filenames before the content.
header-filesize Show file sizes before the content.
grid Vertical/horizontal lines to separate the side bar and header from the content.
rule Horizontal lines to delimit files.
numbers Show line numbers in the side bar.
snip Draw separation lines between distinct line ranges.

[!tip]
If you specify a default style in bat's config file, you can change which components
are displayed during a single run of bat using the --style command-line argument.
By prefixing a component with + or -, it can be added or removed from the current style.

For example, if your config contains --style=full,-snip, you can run bat with
--style=-grid,+snip to remove the grid and add back the snip component.
Or, if you want to override the styles completely, you use --style=numbers to
only show the line numbers.

Decorations

By default, bat only shows decorations (such as line numbers, file headers, grid borders, etc.) when outputting to an interactive terminal. You can control this behavior with the --decorations option. Use --decorations=always to show decorations even when piping output to another command, or --decorations=never to disable them entirely. Possible values are auto (default), never, and always.

There is also the --force-colorization option, which is an alias for --decorations=always --color=always. This is useful if you want to keep colorization and decorations when piping bat's output to another program.

Adding new syntaxes / language definitions

Should you find that a particular syntax is not available within bat, you can follow these
instructions to easily add new syntaxes to your current bat installation.

bat uses the excellent syntect
library for syntax highlighting. syntect can read any
Sublime Text .sublime-syntax file
and theme.

A good resource for finding Sublime Syntax packages is Package Control. Once you found a
syntax:

  1. Create a folder with syntax definition files:

    bash
    mkdir -p "$(bat --config-dir)/syntaxes"
    cd "$(bat --config-dir)/syntaxes"
    
    # Put new '.sublime-syntax' language definition files
    # in this folder (or its subdirectories), for example:
    git clone https://github.com/tellnobody1/sublime-purescript-syntax
  2. Now use the following command to parse these files into a binary cache:

    bash
    bat cache --build
  3. Finally, use bat --list-languages to check if the new languages are available.

    If you ever want to go back to the default settings, call:

    bash
    bat cache --clear
  4. If you think that a specific syntax should be included in bat by default, please
    consider opening a "syntax request" ticket after reading the policies and
    instructions here: Open Syntax Request.

Adding new themes

This works very similar to how we add new syntax definitions.

[!NOTE]
Custom themes must be stored in .tmTheme files.
Newer .sublime-color-scheme files are currently not supported.

First, create a folder with the new syntax highlighting themes:

bash
mkdir -p "$(bat --config-dir)/themes"
cd "$(bat --config-dir)/themes"

# Download a theme in '.tmTheme' format, for example:
git clone https://github.com/greggb/sublime-snazzy

# Update the binary cache
bat cache --build

Finally, use bat --list-themes to check if the new themes are available.

[!NOTE]
bat uses the name of the .tmTheme file for the theme's name.

Adding or changing file type associations

You can add new (or change existing) file name patterns using the --map-syntax
command line option. The option takes an argument of the form pattern:syntax where
pattern is a glob pattern that is matched against the file name and
the absolute file path. The syntax part is the full name of a supported language
(use bat --list-languages for an overview).

Note: You probably want to use this option as an entry in bat's configuration file
for persistence instead of passing it on the command line as a one-off. Generally
you'd just use -l if you want to manually specify a language for a file.

Example: To use "INI" syntax highlighting for all files with a .conf file extension, use

bash
--map-syntax='*.conf:INI'

Example: To open all files called .ignore (exact match) with the "Git Ignore" syntax, use:

bash
--map-syntax='.ignore:Git Ignore'

Example: To open all .conf files in subfolders of /etc/apache2 with the "Apache Conf"
syntax, use (this mapping is already built in):

bash
--map-syntax='/etc/apache2/**/*.conf:Apache Conf'

Using a different pager

bat uses the pager that is specified in the PAGER environment variable. If this variable is not
set, less is used by default. You can also use bat's built-in pager with --pager=builtin or
by setting the BAT_PAGER environment variable to "builtin".

If you want to use a different pager, you can either modify the PAGER variable or set the
BAT_PAGER environment variable to override what is specified in PAGER.

[!NOTE]
If PAGER is more or most, bat will silently use less instead to ensure support for colors.

If you want to pass command-line arguments to the pager, you can also set them via the
PAGER/BAT_PAGER variables:

bash
export BAT_PAGER="less -RFK"

Instead of using environment variables, you can also use bat's configuration file to configure the pager (--pager option).

Using `less` as a pager

When using less as a pager, bat will automatically pass extra options along to less
to improve the experience. Specifically, -R/--RAW-CONTROL-CHARS, -F/--quit-if-one-screen,
-K/--quit-on-intr and under certain conditions, -X/--no-init and/or -S/--chop-long-lines.

[!IMPORTANT]
These options will not be added if:

  • The pager is not named less.
  • The --pager argument contains any command-line arguments (e.g. --pager="less -R").
  • The BAT_PAGER environment variable contains any command-line arguments (e.g. export BAT_PAGER="less -R")

The --quit-if-one-screen option will not be added when:

  • The --paging=always argument is used.
  • The BAT_PAGING environment is set to always.

The -R/--RAW-CONTROL-CHARS option is needed to interpret ANSI colors correctly.

The -F/--quit-if-one-screen option instructs less to exit immediately if the output size is smaller than
the vertical size of the terminal. This is convenient for small files because you do not
have to press q to quit the pager.

The -K/--quit-on-intr option instructs less to exit immediately when an interrupt signal is received.
This is useful to ensure that less quits together with bat on SIGINT.

The -X/--no-init option is added to versions of less older than version 530 (older than 558 on Windows) to
fix a bug with the -F/--quit-if-one-screen feature. Unfortunately, it also breaks mouse-wheel support in less.
If you want to enable mouse-wheel scrolling on older versions of less and do not mind losing
the quit-if-one-screen feature, you can set the pager (via --pager or BAT_PAGER) to less -R.
For less 530 or newer, it should work out of the box.

The -S/--chop-long-lines option is added when bat's -S/--chop-long-lines option is used. This tells less
to truncate any lines larger than the terminal width.

Indentation

bat expands tabs to 4 spaces by itself, not relying on the pager. To change this, simply add the
--tabs argument with the number of spaces you want to be displayed.

Note: Defining tab stops for the pager (via the --pager argument by bat, or via the LESS
environment variable for less) won't be taken into account because the pager will already get
expanded spaces instead of tabs. This behaviour is added to avoid indentation issues caused by the
sidebar. Calling bat with --tabs=0 will override it and let tabs be consumed by the pager.

Dark mode

If you make use of the dark mode feature in macOS, you might want to configure bat to use a different
theme based on the OS theme. The following snippet uses the default theme when in the dark mode
and the GitHub theme when in the light mode.

bash
alias cat="bat --theme auto:system --theme-dark default --theme-light GitHub"

The same dark mode feature is now available in GNOME and affects the org.gnome.desktop.interface color-scheme setting. The following code converts the above to use said setting.

bash
# .bashrc
sys_color_scheme_is_dark() {
    condition=$(gsettings get org.gnome.desktop.interface color-scheme)
    condition=$(echo "$condition" | tr -d "[:space:]'")
    if [ $condition == "prefer-dark" ]; then
        return 0
    else
        return 1
    fi
}

bat_alias_wrapper() {
    #get color scheme
    sys_color_scheme_is_dark
    if [[ $? -eq 0 ]]; then
        # bat command with dark color scheme
        bat --theme=default "$@"
    else
        # bat command with light color scheme
        bat --theme=GitHub "$@"
    fi
}
alias cat='bat_alias_wrapper'

Configuration file

bat can also be customized with a configuration file. The location of the file is dependent
on your operating system. To get the default path for your system, call

bash
bat --config-file

Alternatively, you can use BAT_CONFIG_PATH or BAT_CONFIG_DIR environment variables to point bat
to a non-default location of the configuration file or the configuration directory respectively:

bash
export BAT_CONFIG_PATH="/path/to/bat/bat.conf"
export BAT_CONFIG_DIR="/path/to/bat"

A default configuration file can be created with the --generate-config-file option.

bash
bat --generate-config-file

There is also now a systemwide configuration file, which is located under /etc/bat/config on
Linux and Mac OS and C:\ProgramData\bat\config on windows. If the system wide configuration
file is present, the content of the user configuration will simply be appended to it.

Format

The configuration file is a simple list of command line arguments. Use bat --help to see a full list of possible options and values. In addition, you can add comments by prepending a line with the # character.

Example configuration file:

bash
# Set the theme to "TwoDark"
--theme="TwoDark"

# Show line numbers, Git modifications and file header (but no grid)
--style="numbers,changes,header"

# Use italic text on the terminal (not supported on all terminals)
--italic-text=always

# Use C++ syntax for Arduino .ino files
--map-syntax "*.ino:C++"

Using `bat` on Windows

bat mostly works out-of-the-box on Windows, but a few features may need extra configuration.

Prerequisites

You will need to install the Visual C++ Redistributable package.

Paging

Windows only includes a very limited pager in the form of more. You can download a Windows binary
for less from its homepage or through
Chocolatey
. To use it, place the binary in a directory in
your PATH or define an environment variable. The Chocolatey package installs less automatically.

Colors

Windows 10 natively supports colors in both conhost.exe (Command Prompt) and PowerShell since
v1511, as
well as in newer versions of bash. On earlier versions of Windows, you can use
Cmder, which includes ConEmu.

Note: Old versions of less do not correctly interpret colors on Windows. To fix this, you can add the optional Unix tools to your PATH when installing Git. If you don’t have any other pagers installed, you can disable paging entirely by passing --paging=never or by setting BAT_PAGER to an empty string.

Cygwin

bat on Windows does not natively support Cygwin's unix-style paths (/cygdrive/*). When passed an absolute cygwin path as an argument, bat will encounter the following error: The system cannot find the path specified. (os error 3)

This can be solved by creating a wrapper or adding the following function to your .bash_profile file:

bash
bat() {
    local index
    local args=("$@")
    for index in $(seq 0 ${#args[@]}) ; do
        case "${args[index]}" in
        -*) continue;;
        *)  [ -e "${args[index]}" ] && args[index]="$(cygpath --windows "${args[index]}")";;
        esac
    done
    command bat "${args[@]}"
}

Troubleshooting

Garbled output

If an input file contains color codes or other ANSI escape sequences or control characters, bat will have problems
performing syntax highlighting and text wrapping, and thus the output can become garbled.

If your version of bat supports the --strip-ansi=auto option, it can be used to remove such sequences
before syntax highlighting. Alternatively, you may disable both syntax highlighting and wrapping by
passing the --color=never --wrap=never options to bat.

For untrusted input, the --sanitize=auto|always|never option additionally replaces terminal-active
control bytes and Unicode bidi / zero-width formatting characters with the Unicode replacement
character. It implies --strip-ansi at the same value.

[!NOTE]
The auto option of --strip-ansi avoids removing escape sequences when the syntax is plain text.

Terminals & colors

bat handles terminals with and without truecolor support. However, the colors in most syntax
highlighting themes are not optimized for 8-bit colors. It is therefore strongly recommended
that you use a terminal with 24-bit truecolor support (terminator, konsole, iTerm2, ...),
or use one of the basic 8-bit themes designed for a restricted set of colors.
See this article for more details and a full list of
terminals with truecolor support.

Make sure that your truecolor terminal sets the COLORTERM variable to either truecolor or
24bit. Otherwise, bat will not be able to determine whether or not 24-bit escape sequences
are supported (and fall back to 8-bit colors).

Line numbers and grid are hardly visible

Please try a different theme (see bat --list-themes for a list). The OneHalfDark and
OneHalfLight themes provide grid and line colors that are brighter.

File encodings

bat natively supports UTF-8 as well as UTF-16. For every other file encoding, you may need to
convert to UTF-8 first because the encodings can typically not be auto-detected. You can iconv
to do so.
Example: if you have a PHP file in Latin-1 (ISO-8859-1) encoding, you can call:

bash
iconv -f ISO-8859-1 -t UTF-8 my-file.php | bat

Note: you might have to use the -l/--language option if the syntax can not be auto-detected
by bat.

Development

bash
# Recursive clone to retrieve all submodules
git clone --recursive https://github.com/sharkdp/bat

# Build (debug version)
cd bat
cargo build --bins

# Run unit tests and integration tests
cargo test

# Install (release version)
cargo install --path . --locked

# Build a bat binary with modified syntaxes and themes
bash assets/create.sh
cargo install --path . --locked --force

If you want to build an application that uses bat's pretty-printing
features as a library, check out the API documentation.
Note that you have to use either regex-onig or regex-fancy as a feature
when you depend on bat as a library.

Contributing

Take a look at the CONTRIBUTING.md guide.

Maintainers

Security vulnerabilities

See SECURITY.md.

Project goals and alternatives

bat tries to achieve the following goals:

  • Provide beautiful, advanced syntax highlighting
  • Integrate with Git to show file modifications
  • Be a drop-in replacement for (POSIX) cat
  • Offer a user-friendly command-line interface

There are a lot of alternatives, if you are looking for similar programs. See
this document for a comparison.

License

Copyright (c) 2018-2025 bat-developers.

bat is made available under the terms of either the MIT License or the Apache License 2.0, at your option.

See the LICENSE-APACHE and LICENSE-MIT files for license details.


File: doc/alternatives.md

Alternatives

The following table tries to give an overview from bats perspective, i.e. we only compare
categories which are relevant for bat. Some of these projects have completely different goals and
if you are not looking for a program like bat, this comparison might not be for you.

bat pygments highlight ccat source-highlight hicat coderay rouge clp
Drop-in cat replacement :heavy_check_mark: * :x: :x: (✔️) :x: :x: * :x: :x: :x:
Git integration :heavy_check_mark: :x: :x: :x: :x: :x: :x: :x: :x:
Automatic paging :heavy_check_mark: :x: :x: :x: :x: :heavy_check_mark: :x: :x: :x:
Languages (circa) 150 300 200 7 80 130 30 130 150
Extensible (languages, themes) :heavy_check_mark: (✔️) (✔️) :x: (✔️) :x: :x: :x: :heavy_check_mark:
Advanced highlighting (e.g. nested syntaxes) :heavy_check_mark: :heavy_check_mark: (✔️) ? :x: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark: :heavy_check_mark:
Execution time [ms] (jquery-3.3.1.js) 422 455 299 39 208 287 128 740 22
Execution time [ms] (miniz.c) 27 169 19 4 36 131 58 231 4
Execution time [ms] (957 kB XML file) 215 296 236 165 83 412 135 386 127

If you think that some entries in this table are outdated or wrong, please open a ticket or pull
request.

Some other alternatives that are also related, but not yet included in the table:

Benchmarks

The benchmarks above have been created with this script:

bash
#!/usr/bin/env bash

cd "$(dirname "${BASH_SOURCE[0]}")" || exit

if ! command -v hyperfine > /dev/null 2>&1; then
    echo "'hyperfine' does not seem to be installed."
    echo "You can get it here: https://github.com/sharkdp/hyperfine"
    exit 1
fi

SRC="test-src/jquery-3.3.1.js"


cmd_bat="bat --style=full --color=always --paging=never '$SRC'"
cmd_bat_simple="bat --plain --wrap=never --tabs=0 --color=always --paging=never '$SRC'"
cmd_pygmentize="pygmentize -g '$SRC'"
cmd_highlight="highlight -O truecolor '$SRC'"
cmd_ccat="ccat --color=always '$SRC'"
cmd_source_highlight="source-highlight --failsafe --infer-lang -f esc -i '$SRC'"
cmd_hicat="hicat '$SRC'"
cmd_coderay="coderay '$SRC'"
cmd_rouge="rougify '$SRC'"
cmd_clp="clp '$SRC'"

hyperfine --warmup 3 \
    "$cmd_bat" \
    "$cmd_bat_simple" \
    "$cmd_pygmentize" \
    "$cmd_highlight" \
    "$cmd_ccat" \
    "$cmd_source_highlight" \
    "$cmd_hicat" \
    "$cmd_coderay" \
    "$cmd_rouge" \
    "$cmd_clp" \

File: doc/assets.md

Adding new builtin languages for syntax highlighting

Should you find that a particular syntax is not available within bat and think it should be included in bat by default, you can follow the instructions outlined below.

bat uses the excellent syntect library to highlight source
code. As a basis, syntect uses Sublime Text syntax definitions
in the .sublime-syntax format.

Important: Before proceeding, verify that the syntax you wish to add meets the criteria for inclusion.

  1. Find a Sublime Text syntax for the given language, preferably in a separate Git repository
    which can be included as a submodule (under assets/syntaxes) using
    git submodule add <https github link> ./assets/syntaxes/02_Extra/<repo name>, replacing
    the contents of the angle brackets as appropriate.

  2. If the Sublime Text syntax is only available as a .tmLanguage file, open the file in
    Sublime Text and convert it to a .sublime-syntax file via Tools -> Developer ->
    New Syntax from XXX.tmLanguage.... Save the new file in the assets/syntaxes folder.
    If only .tmLanguage.json or .tmLanguage.yml file is available, use
    PackageDev to convert it to .tmLanguage.plist
    format and then rename the converted file to .tmLanguage file.

  3. Run the assets/create.sh script. It calls bat cache --build to parse all available
    .sublime-syntax files and serialize them to a syntaxes.bin file.

  4. Re-compile bat. At compilation time, the syntaxes.bin file will be stored inside the
    bat binary.

  5. Use bat --list-languages to check if the new languages are available. You may want to do something like export PATH="`pwd`/target/debug:$PATH" to ensure the locally compiled version is the one being used.

  6. Add a syntax test for the new language. See below for details.

  7. If you send a pull request with your changes, please do not include the changed syntaxes.bin
    file. A new binary cache file will be created once before every new release of bat. This
    avoids bloating the repository size unnecessarily.

Syntax tests

bat has a set of syntax highlighting regression tests in tests/syntax-tests. The main idea is
make sure that we do not run into issues we had in the past where either (1) syntax highlighting
for some language is suddenly not working anymore or (2) bat suddenly crashes for some input (due
to regex incompatibilities between syntect and Sublime Text).

In order to add a new test file, please follow these steps (let's take "Ruby" as an example):

  1. Make sure that you are running the latest version of bat and that bat is available on
    the path. If you are creating a syntax test for a new builtin syntax (see above), make sure that
    your version of bat already has the new syntax builtin.
  2. Find an example Ruby source file or write one yourself. If possible, the file should aim to be
    "comprehensive" (i.e. include a lot of the possible syntax), but this is not strictly necessary.
    A simple file is better than none at all. Also, the files shouldn't be gigantic.
  3. Save the file in tests/syntax-tests/source/Ruby (adapt for your language). The file name could
    be test.rb (adapt extension) but can also be adapted if that is necessary in order for bat to
    highlight it correctly (e.g. Makefile).
  4. If you have copied the file from somewhere else, please make sure that the file may be copied
    under the respective license and that the license is compatible with bats license. If it
    requires attribution, please add a LICENSE.md in the same folder with a text like this:
    text
    The `test.rb` file has been added from [enter source here] under the following license:
    
    [add license text here]
  5. Go to tests/syntax-tests and run the update.sh Bash script. A new file should be generated
    in the highlighted folder (e.g. highlighted/Ruby/test.rb).
  6. Use cat or bat --language=txt to display the content of this file and make sure that the
    syntax highlighting looks correct.
  7. git add the new files in the source folder as well as the autogenerated files in the
    highlighted folder.

Troubleshooting

Make sure that the local cache does not interfere with the internally stored syntaxes and
themes (bat cache --clear).

Criteria for inclusion of new syntaxes

Manual modifications

The following files have been manually modified after converting from a .tmLanguage file:

  • Apache.sublime_syntax=> removed conf and CONF file types.
  • Dart.sublime-syntax => removed #regex.dart include.
  • DotENV.sublime-syntax => added .env.template, env and env.* file types (upstream PR).
  • INI.sublime-syntax => added .coveragerc, .pylintrc, .gitlint, .hgrc, hgrc, and desktop file types and support for comments after section headers.
  • Org mode.sublime-syntax => removed task file type.
  • Robot.sublime_syntax => changed name to "Robot Framework", added .resource extension.
  • SML.sublime_syntax => removed ml file type.
  • wgsl.sublime-syntax => added wgsl file extension.

Non-submodule additions


File: doc/README-ja.md

シンタックスハイライト

bat は多くのプログラミング言語やマークアップ言語の
シンタックスハイライトに対応しています:

Gitの統合

bat は git とも連携しており、差分を表現する記号が表示されます
(図の左端):

印刷できない文字の表示

-A/--show-all オプションをつけることで
印刷できない文字を可視化できます:

自動ページング

出力が1つの画面に対して大きすぎる場合、bat は自身の出力をページャー(例えば less) にパイプで繋げます。

ファイルの連結

あなたはさらにファイルを連結させるために使うことも可能です:wink:。
bat は非対話型のターミナルを検出すると(すなわち他のプロセスにパイプしたりファイル出力していると)、
bat は cat の完全互換として振る舞い、
プレーンなファイルを表示します。

使い方

単一のファイルを表示させたい場合

bash
> bat README.md

複数のファイルを一度に表示させたい場合

bash
> bat src/*.rs

標準入力から自動的に構文を決定させたい場合(ハイライトされるのは、
たいていは #!/bin/sh のようなシバンを利用して、
ファイルの一行目から構文を決定できる場合のみです)

bash
> curl -s https://sh.rustup.rs | bat

標準入力から明示的に言語を指定したい場合

bash
> yaml2json .travis.yml | json_pp | bat -l json

空白文字を可視化させたい場合:

bash
> bat -A /etc/hosts

cat の代わりに bat を使用する際の例:

bash
bat > note.md  # quickly create a new file

bat header.md content.md footer.md > document.md

bat -n main.rs  # show line numbers (only)

bat f - g  # output 'f', then stdin, then 'g'.

他のツールとの統合

`fzf`

fzf のプレビューウィンドウに bat を使用できます。
その場合、bat の --color=always オプションを用いてカラー出力を強制しなければなりません。
また、--line-range オプションを用いることで巨大なファイルの読み込み時間を制限できます:

bash
fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}'

詳しくは fzf の README を参照してください。

`find` or `fd`

find の -exec オプションを使用して、bat ですべての検索結果をプレビューできます:

bash
find … -exec bat {} +

fd を使用している場合は、-X /-exec-batch オプションを使用して同じことを行うことができます:

bash
fd … -X bat

`ripgrep`

batgrep では、ripgrep 検索結果のプリンターとして bat を使用できます。

bash
batgrep needle src/

`tail -f`

bat を tail -f と組み合わせて、構文強調表示を使用して特定のファイルを継続的に監視できます。

bash
tail -f /var/log/pacman.log | bat --paging=never -l log

注意事項:tail -fと組み合わせるには、ページングをオフにしなければなりません。また、この場合は構文が自動検出されないため、明示的に指定(-l log)しています。

`git`

bat を git show と組み合わせて、
適切な構文強調表示を使用して特定のファイルの古いバージョンを表示できます:

bash
git show v0.6.0:src/main.rs | bat -l rs

差分内の構文強調表示は現在サポートされていないことに注意してください。 これを探しているなら、delta をチェックしてください。

`xclip`

bat の出力の行番号と Git 変更マーカーにより、ファイルの内容をコピーするのが難しくなる場合があります。
これを防ぐには、-p / -plain オプションを使用して bat を呼び出すか、
単に出力を xclip にパイプします:

bash
bat main.cpp | xclip

bat は出力がリダイレクトされていることを検出し、プレーンファイルの内容を出力します。

`man`

bat は MANPAGER 環境変数を設定することにより、
man の色付けページャーとして使用できます:

bash
export MANPAGER="sh -c 'col -bx | bat -l man -p'"
man 2 select

フォーマットの問題が発生した場合は
MANROFFOPT="-c" を設定する必要もあります。

これを新しいコマンドにバンドルしたい場合は batman も使用できます。

Manpage syntax はこのリポジトリで開発されており、まだ作業が必要であることに注意してください。

`prettier` / `shfmt` / `rustfmt`

prettybat スクリプトは、コードをフォーマットし、bat で印刷するラッパーです。

インストール

On Ubuntu (`apt` を使用)

... や他のDebianベースのLinuxディストリビューション

20.04 ("Focal") 以降の Ubuntu または 2021 年 8 月以降の Debian (Debian 11 - "Bullseye") では bat パッケージが利用できます。

bash
apt install bat

apt を使用して bat をインストールした場合、実行可能ファイルの名前が bat ではなく batcat になることがあります(他のパッケージとの名前衝突のため)。bat -> batcat のシンボリックリンクまたはエイリアスを設定することで、実行可能ファイル名が異なることによる問題の発生を防ぎ、他のディストリビューションと一貫性を保てます。

bash
mkdir -p ~/.local/bin
ln -s /usr/bin/batcat ~/.local/bin/bat

On Ubuntu (最新の `.deb` パッケージを使用)

*... や他のDebianベースのLinuxディストリビューション

batの最新リリースを実行する場合、または Ubuntu/Debian の古いバージョンを使用している場合は、release page から最新の .deb パッケージをダウンロードし、
次の方法でインストールします:

bash
sudo dpkg -i bat_0.18.3_amd64.deb  # adapt version number and architecture

On Alpine Linux

適切なリポジトリが有効になっている場合は、
公式のソースから bat package をインストールできます:

bash
apk add bat

On Arch Linux

Arch Linuxの公式リソース
からインストールできます。

bash
pacman -S bat

On Fedora

公式の Fedora Modular リポジトリから the bat package をインストールできます。

bash
dnf install bat

On Gentoo Linux

公式ソースから
the bat package をインストールできます。

bash
emerge sys-apps/bat

On Void Linux

xbps-install経由で bat をインストールできます。

text
xbps-install -S bat

On FreeBSD

pkg を使用してプリコンパイルされた bat package をインストールできます:

bash
pkg install bat

または FreeBSD ポートから自分でビルドすることもできます:

bash
cd /usr/ports/textproc/bat
make install

Via nix

bat を nix package manager 経由でインストールすることができます:

bash
nix-env -i bat

On openSUSE

bat をzypperでインストールすることができます:

bash
zypper install bat

On macOS

Homebrewで bat をインストールできます:

bash
brew install bat

または MacPorts で bat をインストールします:

bash
port install bat

On Windows

Windowsにbatをインストールするいくつかのオプションがあります。
batをインストールしたら Windowsでのbatの使用 セクションをご覧ください。

With Chocolatey

Chocolatey から bat をインストールできます:

bash
choco install bat

With Scoop

scoop から bat をインストールできます:

bash
scoop install bat

Visual C ++再頒布可能 パッケージをインストールする必要があります。

From prebuilt binaries:

リリースページ からビルド済みのバイナリをダウンロードできます。

Visual C ++再頒布可能 パッケージをインストールする必要があります。

Via Docker

コンテナ内で bat を使いたい方のために Docker image が用意されています:

bash
docker pull danlynn/bat
alias bat='docker run -it --rm -e BAT_THEME -e BAT_STYLE -e BAT_TABS -v "$(pwd):/myapp" danlynn/bat'

Via Ansible

Ansible でインストールすることができます:

bash
# Install role on local machine
ansible-galaxy install aeimer.install_bat
yaml
---
# Playbook to install bat
- host: all
  roles:
    - aeimer.install_bat

これは以下のディストリビューションで動作するはずです:

  • Debian/Ubuntu
  • ARM (eg. Raspberry PI)
  • Arch Linux
  • Void Linux
  • FreeBSD
  • MacOS

From binaries

多くの異なるアーキテクチャのためのプレビルドバージョンをリリースページからチェックしてみてください。静的にリンクされている多くのバイナリも利用できます: ファイル名に musl を含むアーカイブを探してみてください。

From source

bat をソースからビルドしたいならば、Rust 1.79.0 以上の環境が必要です。
cargo を使用してビルドすることができます:

bash
cargo install --locked bat

一部のプラットフォームでは llvm および/または libclang-dev のインストールが必要になる場合があります。

カスタマイズ

ハイライト テーマ

bat --list-themes を使うと現在利用可能なシンタックスハイライトのテーマを入手できます。
TwoDark テーマを選ぶためには
--theme=TwoDark オプションをつけるか BAT_THEME という環境変数に
TwoDark を代入する必要があります。 シェルの起動ファイルに export BAT_THEME="TwoDark"
と定義すればその設定が変わることはないでしょう。あるいは、 bat の
設定ファイルを利用してください。

カスタムファイルでさまざまなテーマをプレビューする場合は、
次のコマンドを使用できます(これには fzf が必要です)。

bash
bat --list-themes | fzf --preview="bat --theme={} --color=always /path/to/file"

bat はデフォルトだと黒い背景色のターミナルに適しています。
しかし、GitHub や OneHalfLight のような白い背景色のテーマでもいい感じにすることができます。
'新しいテーマの追加' セクションに従って
カスタムテーマを使用することもできます。

出力のスタイル

--style を使うことで bat の表示の見た目を変更することができます。
例えば、 --style=numbers,changes と入力します。
すると、Gitの差分と行番号だけが表示され、グリッド線とファイルヘッダーは表示されません。
環境変数に BAT_STYLE を定義するとこれらの設定を永続的に使用することができます。
設定ファイル を参考にしても良いでしょう。

新しい構文の追加 / 言語の定義

bat はシンタックスハイライトのための syntect
という素晴らしいライブラリを使用しています。syntect は、
Sublime Text の .sublime-syntax ファイル
とテーマを読み取ることができます。新しい構文を定義するために以下の手順を行います。

構文定義ファイルを入れておくためのフォルダを作ります:

bash
mkdir -p "$(bat --config-dir)/syntaxes"
cd "$(bat --config-dir)/syntaxes"

# Put new '.sublime-syntax' language definition files
# in this folder (or its subdirectories), for example:
git clone https://github.com/tellnobody1/sublime-purescript-syntax

次のコマンドを使用して、これらのファイルをバイナリキャッシュに解析します:

bash
bat cache --build

最後に bat --list-languages と入力すると新しい言語が利用可能かどうかチェックします。

デフォルトの設定に戻したいときは以下のコマンドを実行します:

bash
bat cache --clear

新しいテーマの追加

これは構文を新しく定義するやり方と非常に似ています。

まず、新しいシンタックスハイライトのテーマのフォルダを作ります:

bash
mkdir -p "$(bat --config-dir)/themes"
cd "$(bat --config-dir)/themes"

# Download a theme in '.tmTheme' format, for example:
git clone https://github.com/greggb/sublime-snazzy

# Update the binary cache
bat cache --build

最後に、 bat --list-themes で新しいテーマが利用可能かチェックします

異なるページャーの使用

bat は環境変数 PAGER に使用するページャーを明記します。
この環境変数が定義されていない場合、デフォルトで less が使用されます。
もし、異なるページャーを使用したい場合は、PAGER を修正してください。
または、PAGER を上書きする環境変数として BAT_PAGER を定義することも可能です。

もし、ページャーにコマンドライン引数を渡したい場合は、
PAGER/BAT_PAGER 環境変数を定義してください:

bash
export BAT_PAGER="less -RF"

環境変数を利用する代わりに、 bat の 設定ファイル を使用して設定も可能です(--pager オプション)

注意: デフォルトにより、ページャーが less にセットされているならば
bat はページャーの以下のコマンドラインオプション を受け付けるでしょう:
-R/--RAW-CONTROL-CHARS, -F/--quit-if-one-screen そして -X/--no-init。
最後のオプション(-X)は、530 より古いバージョンにのみ使用されます。

-R オプションは、ANSIカラーを正しく解釈するために必要です。
2番目のオプション(-F)は、出力サイズが端末の垂直サイズよりも小さい場合、すぐに終了するようにlessに指示します。
これは、ページャーを終了するために q を押す必要がないため、小さなファイルに便利です。
3番目のオプション(-X)は、less の古いバージョンの --quit-if-one-screen 機能のバグを修正するために必要です。
残念ながら、less のマウスホイールのサポートも少なくなります。

less の古いバージョンでマウスホイールのスクロールを有効にしたい場合は、
-R だけを渡すことができます(上記の例のように、これは1画面終了機能を無効にします)。
530以下の場合は、そのまま使用できます。

Dark mode

macOSでダークモード機能を使用する場合、OSテーマに基づいて異なるテーマを使用するように bat を構成することができます。
次のスニペットは、ライトモードの場合は デフォルト のテーマを使用し、
ダークモードの場合は GitHub テーマを使用します。

bash
alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)"

設定ファイル

bat は設定ファイルでカスタマイズすることが可能です。ファイルの場所はOSに依存します。
使用しているOSのデフォルトパスを調べるには以下のコマンドを実行してください:

text
bat --config-file

または、BAT_CONFIG_PATH 環境変数を使用して、bat が
構成ファイルのデフォルト以外の場所を指すようにすることができます:

bash
export BAT_CONFIG_PATH="/path/to/bat.conf"

フォーマット

この設定ファイルはコマンドライン引数の単純なリストです。 bat --help を利用すると、利用可能なオプションとその値を閲覧することができます。さらに、# でコメント文を加えることができます。

設定ファイルの例:

bash
# Set the theme to "TwoDark"
--theme="TwoDark"

# Show line numbers, Git modifications and file header (but no grid)
--style="numbers,changes,header"

# Use italic text on the terminal (not supported on all terminals)
--italic-text=always

# Use C++ syntax for Arduino .ino files
--map-syntax "*.ino:C++"

# Use ".gitignore"-style highlighting for ".ignore" files
--map-syntax ".ignore:Git Ignore"

Windows での `bat` の利用

Windows 上で bat はほとんど動作しますが、いくつかの機能は設定を必要をする場合があります。

ページング

Windowsには、more 形式の非常に限られたページャーしか含まれていません。
less 用のWindowsバイナリは、ホームページ または
Chocolatey からダウンロードできます。
これを使用するには、バイナリを PATH のディレクトリに配置するか、環境変数を定義します。Chocolateyパッケージ は less を自動的にインストールします。

色

Windows 10では、conhost.exe (コマンドプロンプト)と
v1511 以降の PowerShell の両方、
およびbashの新しいバージョンの色がネイティブにサポートされています。 以前のバージョンのWindowsでは、
ConEmu を含む Cmder を使用できます。

注意: Git と MSYS の less はWindows上で色を正しく解釈しません。
もし、あなたが他のページャーをインストールしていないのであれば、 --paging=never オプションを付け加えるか
BAT_PAGER に空文字を設定することでページングを完全に無効にできます。

Cygwin

Windows上の bat は Cygwin のunix風のpath(/cygdrive/*)をネイティブサポートしていません。絶対的なcygwinパスを引数として受けたときに、 bat は以下のエラーを返すでしょう: The system cannot find the path specified. (os error 3)

wrapperを作成するか、以下の関数を .bash_profile に追記することで、この問題を解決することができます:

bash
bat() {
    local index
    local args=("$@")
    for index in $(seq 0 ${#args[@]}) ; do
        case "${args[index]}" in
        -*) continue;;
        *)  [ -e "${args[index]}" ] && args[index]="$(cygpath --windows "${args[index]}")";;
        esac
    done
    command bat "${args[@]}"
}

トラブルシューティング

ターミナルと色

bat はターミナルがトゥルーカラーをサポートしている/していないに関係なくサポートします。
しかし、シンタックスハイライトのテーマの色が8-bitカラーに最適化されていない場合、
24-bitであるトゥルーカラーをサポートしているターミナルを使用することを強く推奨します(terminator, konsole, iTerm2, ...)。
この 記事 には
24-bitカラーがサポートされているターミナルの一覧が掲載されています。

本当の色をターミナルにセットするために、環境変数 COLORTERM に truecolor か
24bit のどちらかを代入してください。さもなければ、bat はどの色を使うのか決定することができません。または、24-bit エスケープシーケンスがサポートされません
(そして、8-bit colorに戻ります)。

行番号とグリッド線がほとんど見えない

異なるテーマを試してみてください(bat --list-themes でテーマを閲覧できます)。
OneHalfDark と OneHalfLight テーマはグリッド線と線の色を明るくします。

ファイルエンコーディング

bat は UTF-16 と同様に UTF-8 をネイティブにサポートします。
他のすべてのファイルエンコーディングでは、エンコーディングは通常自動検出できないため、最初に UTF-8 に変換する必要があります。
これを行うには iconv を使用できます。
例: Latin-1(ISO-8859-1)エンコーディングの PHP ファイルがある場合、次のように呼び出すことができます:

bash
iconv -f ISO-8859-1 -t UTF-8 my-file.php | bat

注: bat が構文を自動検出できない場合は
-l / -language オプションを使用する必要がある場合があります。

開発

bash
# Recursive clone to retrieve all submodules
git clone --recursive https://github.com/sharkdp/bat

# Build (debug version)
cd bat
cargo build --bins

# Run unit tests and integration tests
cargo test

# Install (release version)
cargo install --locked

# Build a bat binary with modified syntaxes and themes
bash assets/create.sh
cargo install --locked --force

Maintainers

プロジェクトの目標と既存の類似したOSS

bat は以下の目標を達成しようと試みています:

  • 美しく高度なシンタックスハイライトの提供
  • ファイルの差分を表示するためのGitとの連携
  • (POSIX) cat との完全互換
  • ユーザーフレンドリーなコマンドラインインターフェースの提供

あなたが同様のプログラムを探しているなら、多くの選択肢があります。
比較については このドキュメント を参照してください。

ライセンス

Copyright (c) 2018-2021 bat-developers.

bat は MIT License 及び Apache License 2.0 の両方の条件の下で配布されています。

ライセンスの詳細については LICENSE-APACHE 及び LICENSE-MIT ファイルを参照して下さい。


File: doc/README-ko.md

문법 강조

bat은 다양한 프로그래밍 및 마크업 언어의 문법 강조(syntax highlighting) 기능을
지원합니다:

Git 통합

bat은 git을 통해 인덱스와 함께 변경분을 표시합니다
(왼쪽 사이드바를 확인하세요):

비인쇄 문자 처리

-A/--show-all 옵션을 사용하여 비인쇄 문자를 표시 및 강조할 수 있습니다:

자동 페이징

bat은 기본적으로 한 화면에 비해 출력이 큰 경우 less와 같은 페이저(pager)로
출력을 연결(pipe)합니다.
만약 bat을 언제나 cat처럼 작동하게 하려면 (출력을 페이지하지 않기),
--paging=never 옵션을 커맨드 라인이나 설정 파일에 넣을 수 있습니다.
셸(shell) 설정에서 cat을 bat의 alias로 사용하려면,
alias cat='bat --paging=never'를 써서 기본 행동을 유지할 수 있습니다.

파일 연결(concatenation)

페이저(pager)를 사용하더라도 bat은 파일들을 연결(concatenate)할 수 있습니다
:wink:.
bat이 비대화형(non-interactive) 터미널(예를 들어, 다른 프로세스나 파일에
연결(pipe)한 경우)을 감지하면, bat은 --pager 옵션의 값과 상관없이 cat과
동일하게 파일 내용을 그대로 출력합니다.

사용법

터미널에 하나의 파일 표시하기

bash
> bat README.md

여러 파일 한 번에 보여주기

bash
> bat src/*.rs

stdin에서 읽고, 자동으로 맞는 문법 결정하기 (참고로, 문법 강조는 파일의 첫
줄만으로 문법이 결정될 수 있을 때만 작동합니다.
이는 보통 #!/bin/sh와 같은 셔뱅(shebang)으로 판단합니다.)

bash
> curl -s https://sh.rustup.rs | bat

stdin에서 읽고, 명시적으로 언어 지정하기

bash
> yaml2json .travis.yml | json_pp | bat -l json

비인쇄 문자 표시 및 강조하기

bash
> bat -A /etc/hosts

cat 대신 사용하기:

bash
bat > note.md  # quickly create a new file

bat header.md content.md footer.md > document.md

bat -n main.rs  # show line numbers (only)

bat f - g  # output 'f', then stdin, then 'g'.

다른 도구들과 통합하기

`fzf`

bat을 fzf의 프리뷰로 쓸 수 있습니다.
이를 위해서는 bat의 --color=always 옵션으로 항상 컬러 출력이 나오게 해야
합니다.
또한 --line-range 옵션으로 긴 파일의 로드 시간을 제한할 수 있습니다:

bash
fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}'

더 많은 정보는
fzf의 README를 참고하세요.

`find`와 `fd`

find의 -exec 옵션을 사용하여 모든 검색 결과를 bat로 미리 볼 수 있습니다:

bash
find … -exec bat {} +

fd를 사용하는 경우, -X/--exec-batch
옵션을 이용하여 동일하게 사용할 수 있습니다:

bash
fd … -X bat

`ripgrep`

batgrep을
통해 bat로 ripgrep의 검색 결과를
출력할 수 있습니다.

bash
batgrep needle src/

`tail -f`

bat와 tail -f를 함께 사용하여 주어진 파일을 문법 강조하며 지속적으로
모니터할 수 있습니다.

bash
tail -f /var/log/pacman.log | bat --paging=never -l log

참고로 이 작업을 하려면 페이징 기능을 꺼야 합니다.
또한 이 경우 문법을 자동 감지할 수 없기 때문에, 적용할 문법을 직접 지정해야
합니다 (-l log).

`git`

bat과 git show를 함께 사용하여 주어진 파일의 이전 버전을 올바른 문법 강조로
볼 수 있습니다:

bash
git show v0.6.0:src/main.rs | bat -l rs

`git diff`

bat과 git diff를 함께 사용하여 수정된 코드 주위의 줄들을 올바른 문법 강조로
볼 수 있습니다:

bash
batdiff() {
    git diff --name-only --relative --diff-filter=d -z | xargs -0 bat --diff
}

이것을 별도의 도구로 쓰고 싶다면
bat-extras의 batdiff를 확인해 보세요.

Git과 diff의 더 많은 지원을 원한다면
delta를 확인해 보세요.

`xclip`

bat 출력에 줄 번호와 Git 수정 내역이 포함되어서 파일의 내용을 복사하기
어려울 수 있습니다.
이 경우에는 bat의 -p/--plain 옵션을 사용하거나 간단히 xclip으로 출력을
연결(pipe)하면 됩니다:

bash
bat main.cpp | xclip

bat는 출력이 우회되고 있다는 것을 감지하여 파일 내용 그대로를 출력합니다.

`man`

MANPAGER 환경 변수 설정을 통해 bat을 man의 컬러 페이저(pager)로 쓸 수
있습니다.

bash
export MANPAGER="sh -c 'col -bx | bat -l man -p'"
man 2 select

(Debian이나 Ubuntu를 사용한다면 bat을 batcat으로 치환하세요.)

포팻 문제가 발생한다면, MANROFFOPT="-c"을 써야 할 수 있습니다.

이 기능을 포함한 새로운 명령어를 선호한다면,
batman을 쓸
수도 있습니다.

참고로 Manpage 문법은 본 저장소에서
개발 중에 있으며, 아직 더 손봐야 합니다.

또한, 이는 Mandoc의 man 구현에서
작동하지 않습니다.

`prettier` / `shfmt` / `rustfmt`

prettybat
스크립트는 코드를 포맷하고 bat으로 출력하는 래퍼(wrapper)입니다.

설치

Ubuntu에서 (`apt` 사용)

... 그리고 다른 Debian 기반의 Linux 배포판들에서.

bat은 Ubuntu와
Debian 패키지 배포 과정에 도입되는 중이며,
Eoan 19.10 버전의 Ubuntu에서부터 제공됩니다.
현재 Debian에서는 불안정한 "Sid" 브랜치에서만 bat이 제공됩니다.

만약 충분히 최신 버전의 Ubuntu/Debian이 설치되어 있다면 간단히 다음을 실행하세요:

bash
apt install bat

중요: 만약 bat을 이와 같이 설치한다면, (다른 패키지와의 이름
충돌
로 인하여) bat 대신에
batcat이라는 이름의 실행 파일로 설치될 수 있음을 참고하세요.
이에 따른 문제들과 다른 배포판들과의 일관성을 위하여 bat -> batcat symlink
혹은 alias를 설정할 수 있습니다:

bash
mkdir -p ~/.local/bin
ln -s /usr/bin/batcat ~/.local/bin/bat

Ubuntu에서 (가장 최신 `.deb` 패키지들 사용)

... 그리고 다른 Debian 기반의 Linux 배포판들에서.

만약 여러분이 설치한 Ubuntu/Debian에 패키지가 배포되지 않거나 가장 최신 릴리즈된
bat을 원한다면, 릴리즈 페이지에서
다음과 같이 .deb 패키지를 받아 설치하세요:

bash
sudo dpkg -i bat_0.18.3_amd64.deb  # adapt version number and architecture

Alpine Linux에서

적절한 저장소가 활성화되어 있다면, 공식 소스를 통해
bat 패키지를 설치할 수
있습니다:

bash
apk add bat

Arch Linux에서

공식 소스를 통해
bat 패키지를
설치할 수 있습니다:

bash
pacman -S bat

Fedora에서

공식
Fedora 모듈
저장소에서
bat 패키지를
설치할 수 있습니다:

bash
dnf install bat

Funtoo Linux에서

dev-kit을 통해 bat 패키지를 설치할 수 있습니다:

bash
emerge sys-apps/bat

Gentoo Linux에서

공식 소스를 통해
bat 패키지를 설치할 수
있습니다:

bash
emerge sys-apps/bat

Void Linux에서

xbps-install을 이용해 bat을 설치할 수 있습니다:

bash
xbps-install -S bat

Termux에서

pkg를 이용해 bat을 설치할 수 있습니다:

bash
pkg install bat

FreeBSD에서

pkg를 이용하여 미리 컴파일된
bat 패키지를 설치할 수 있습니다:

bash
pkg install bat

또는 FreeBSD 포트에서 직접 빌드할 수도 있습니다:

bash
cd /usr/ports/textproc/bat
make install

nix를 써서

nix package manager를 이용해 bat을 설치할 수
있습니다:

bash
nix-env -i bat

openSUSE에서

zypper를 이용해 bat을 설치할 수 있습니다:

bash
zypper install bat

snap 패키지를 써서

지금으로서는 추천하는 snap 패키지가 없습니다.
제공되는 패키지들이 존재할 수는 있지만, 공식적으로 지원되지 않으며
문제가 있을 수 있습니다.

macOS (또는 Linux)에서 Homebrew를 써서

macOS의 Homebrew 또는
Linux의 Homebrew를 이용하여
bat을 설치할 수 있습니다.

bash
brew install bat

macOS에서 MacPorts를 써서

MacPorts를 이용하여 bat을
설치할 수 있습니다:

bash
port install bat

Windows에서

Windows에서 bat을 설치할 수 있는 몇 가지 옵션들이 있습니다.
먼저 bat을 설치한 후,
"Windows에서 bat 사용하기" 섹션을 살펴보세요.

전제 조건

Visual C++ 재배포 가능
패키지를 설치해야 합니다.

Chocolatey를 써서

Chocolatey를 이용해 bat을 설치할 수
있습니다:

bash
choco install bat

Scoop을 써서

scoop을 이용해 bat을 설치할 수 있습니다:

bash
scoop install bat

사전 빌드된 바이너리들로

릴리즈 페이지에서 사전 빌드된
바이너리를 다운받을 수 있습니다.

Visual C++ 재배포 가능
패키지를 설치해야 합니다.

바이너리들로

릴리즈 페이지에서 다양한 아키텍처를
위해 사전 빌드된 버전들을 확인할 수 있습니다.
정적 링크 바이너리들은 파일 이름에 musl 이 포함된 아카이브들을 확인하세요.

소스에서

bat의 소스를 빌드하기 위해서는, Rust 1.79.0 이상이 필요합니다.
cargo를 이용해 전부 빌드할 수 있습니다:

bash
cargo install --locked bat

참고로 man 페이지나 셸 자동 완성 파일과 같은 부가 파일들은 이 방법으로 설치될 수
없습니다.
이것들은 cargo에 의해 생성이 되고 (build 밑의) cargo 타켓 폴더에서 찾을 수
있습니다.

사용자화

문법 강조 테마

bat --list-themes을 사용하여 사용 가능한 문법 강조 테마들의 목록을 확인할 수
있습니다.
TwoDark 테마를 선택하려면, --theme=TwoDark 옵션과 함께 bat을 사용하거나
BAT_THEME 환경 변수를 TwoDark로 설정하세요.
셸 시작 파일에 export BAT_THEME="TwoDark" 를 정의해 영구적으로 설정할 수
있습니다.
이 밖에 bat의 설정 파일을 이용할 수 있습니다.

만약 다른 테마들을 사용하여 특정 파일을 보고 싶다면, 다음 명령어를 쓸 수
있습니다(이 경우 fzf가 필요합니다.)

bash
bat --list-themes | fzf --preview="bat --theme={} --color=always /path/to/file"

bat은 기본적으로 어두운 배경에 적합합니다.
그러나 밝은 배경의 터미널을 사용한다면 GitHub이나 OneHalfLight과 같은 테마가
더 잘 어울립니다.
아래 새로운 테마 추가하기 섹션에 따라 커스텀 테마를
사용할 수도 있습니다.

8비트 테마

bat은 트루컬러 지원이 되더라도 항상
8비트 색상을 사용하는
세 개의 테마가 있습니다.

  • ansi는 어떤 터미널에서도 무난하게 보입니다. 이는 3비트 색상을 사용합니다:
    검정, 빨강, 녹색, 노랑, 파랑, 마젠타, 시안, 하양.
  • base16은 base16 터미널 테마를 위해
    디자인되었습니다.
    이는 base16 스타일 가이드라인에
    따라 4비트 색상(3비트 색상에 밝은 변형 추가)을 사용합니다.
  • base16-256는 base16-shell을
    위해 디자인되었습니다.
    이는 16부터 21의 일부 밝은 색상을 8비트 색상으로 대치합니다.
    단지 256-색상 터미널을 쓰지만 base16-shell을 쓰지 않는다고 해서 이것을
    사용하지 마십시오.

이들 테마는 더 제한적이지만, 트루컬러 테마에 비해 두 장점이 있습니다:

  • 이들은 3비트 혹은 4비트 색상을 쓰는 다른 터미널 소프트웨어와 더 잘
    어울립니다.
  • 만약 터미널 테마를 바꾼다면, 이미 화면 상의 bat의 출력도 이에 맞추어
    업데이트됩니다.

출력 스타일

--style 옵션을 이용하면 bat의 출력 모양을 조절할 수 있습니다.
예를 들어, --style=numbers,changes를 통해 Git 변경분과 줄 번호는 출력하지만
격자와 파일 헤더는 출력하지 않을 수 있습니다.
BAT_STYLE 환경 변수를 정의하여 이러한 수정을 영구적으로 하거나 bat의
설정 파일을 사용하세요.

새로운 문법 / 언어 정의 추가하기

만약 bat에서 특정 문법이 지원되지 않을 경우, 다음의 절차를 통해 현재 bat
설치본에 새로운 문법을 쉽게 추가할 수 있습니다.

bat은 문법 강조를 위해 훌륭한
syntect 라이브러리를 사용합니다.
syntect는 임의의 Sublime Text의 .sublime-syntax
파일
과 테마를 읽을 수 있습니다.

Package Control에 Sublime 문법 패키지를 찾는
방법이 잘 정리되어 있습니다.
일단 문법을 찾았다면:

  1. 문법 정의 파일들을 넣을 폴더를 만듭니다:
bash
mkdir -p "$(bat --config-dir)/syntaxes"
cd "$(bat --config-dir)/syntaxes"

# Put new '.sublime-syntax' language definition files
# in this folder (or its subdirectories), for example:
git clone https://github.com/tellnobody1/sublime-purescript-syntax
  1. 이제 다음 명령어를 통해 파일들을 파싱(parse)하여 바이너리 캐시를 만듭니다.
bash
bat cache --build
  1. 마지막으로, bat --list-languages로 새로 추가한 언어가 사용 가능한지
    확인합니다.

만약 기본 설정으로 돌아갈 일이 생긴다면, 다음 명령어를 이용합니다:

bash
bat cache --clear
  1. 만약 특정 문법이 bat에 기본적으로 포함되어 있어야 한다고 생각한다면, 방침과
    절차를 여기서 읽은 후 "문법 요청(syntax request)"을 열어
    주세요: 문법 요청하기.

새로운 테마 추가하기

이 과정은 새로운 문법 정의 추가 방식과 매우 비슷합니다.

먼저, 새로운 문법 강조 테마 폴더를 만듭니다.

bash
mkdir -p "$(bat --config-dir)/themes"
cd "$(bat --config-dir)/themes"

# Download a theme in '.tmTheme' format, for example:
git clone https://github.com/greggb/sublime-snazzy

# Update the binary cache
bat cache --build

마지막으로 bat --list-themes을 통해 새로 추가한 테마들이 사용 가능한지
확인합니다.

파일 타입 설정을 추가하거나 변경하기

새로운 파일 이름 패턴을 추가하려면 (혹은 이미 존재하는 것을 변경하려면)
--map-syntax 커맨드 라인 옵션을 사용하세요.
이 옵션은 pattern:syntax 꼴의 인자를 받습니다.
이때 pattern은 파일 이름과 절대 파일 경로를 매치할 글로브(glob) 패턴입니다.
syntax 부분은 지원되는 언어의 전체 이름입니다
(bat --list-languages를 통해 개요를 확인하세요).

참고: 이 옵션은 커맨드 라인에 넘겨 주는 것보다는 bat의 설정 파일에 넣는 것이
좋을 것입니다 (아래를 보세요).

예시: "INI" 문법 강조를 .conf 파일 확장자의 모든 파일에 적용하려면, 다음을
사용하세요:

bash
--map-syntax='*.conf:INI'

예시: .ignore(완전 일치)이라는 이름의 모든 파일을 "Git Ignore" 문법으로
열려면, 다음을 사용하세요:

bash
--map-syntax='.ignore:Git Ignore'

예시: /etc/apache2의 하위 폴더들에 있는 모든 .conf 파일들을 "Apache Conf"
문법으로 열려면, 다음을 사용하세요 (이 대응(mapping)은 이미 내장되어 있습니다):

bash
--map-syntax='/etc/apache2/**/*.conf:Apache Conf'

다른 페이저 사용하기

bat은 환경 변수 PAGER에 명시된 페이저를 사용합니다.
이 변수가 정의되어 있지 않다면, less가 기본으로 사용됩니다.
만약 다른 페이저를 사용하고 싶다면, PAGER 변수를 수정하거나 BAT_PAGER 환경
변수를 설정하여 PAGER의 설정을 오버라이드(override)할 수 있습니다.

만약 커맨드라인 인수들을 페이저에게 넘겨 주려면, PAGER/BAT_PAGER 변수로
설정할 수 있습니다:

bash
export BAT_PAGER="less -RF"

환경 변수를 사용하는 대신, bat의 설정 파일로 페이저를 설정할
수도 있습니다 (--pager 옵션).

참고: 기본적으로, 페이저가 less로 설정되어 있다면 (그리고 커맨드 라인
옵션이 지정되어 있지 않다면), bat은 다음 옵션들을 페이저로 넘겨줍니다:
-R/--RAW-CONTROL-CHARS, -F/--quit-if-one-screen 그리고 -X/--no-init.
마지막 옵션(-X)은 530 이전 버전의 less에만 사용됩니다.

-R 옵션은 ANSI 색상을 올바르게 해석하기 위해 필요합니다.
두 번째 옵션(-F)은 출력 크기가 터미널의 세로 크기보다 작을 경우 less가 즉시
종료되도록 합니다.
이는 작은 파일을 다룰 때 페이저를 종료하기 위해 q를 누를 필요 없어서
편리합니다.
세 번째 옵션(-X)는 예전 버전의 less에 있는 --quit-if-one-screen 기능의
버그를 고치기 위해 필요합니다.
안타깝게도, 이는 less의 마우스 휠 지원과 호환되지 않습니다.

less의 예전 버전에서 마우스 휠 기능을 활성화하려면, -R 옵션을 넘겨주세요
(위의 예제처럼, 이 옵션은 quit-if-one-screen 기능을 비활성화합니다).
less 530과 이후 버전에서는 그대로 사용할 수 있습니다.

들여쓰기

bat은 페이저에 의존하지 않고 탭을 4 스페이스로 확장합니다.
이를 변경하려면 간단히 --tabs 인자에 표시되기를 원하는 스페이스 개수를
추가하세요.

참고: (bat의 --pager 인자 혹은 less의 LESS 환경 변수를 통해)
페이저의 탭 길이를 지정하는 것은 효과가 없을 것인데, 이는 페이저가 이미
스페이스로 확장된 탭을 받기 때문입니다.
이 기능은 사이드바에 의한 들여쓰기 문제를 회피하기 위해 추가되었습니다.
bat을 --tabs=0과 함께 호출하면 이를 오버라이드하여 페이저가 탭을 처리하게
합니다.

다크 모드

macOS에서 다크 모드를 사용하고 있다면, bat가 OS 테마에 따라 다른 테마를
사용하도록 구성할 수 있습니다.
아래 스니펫은 _다크 모드_에서는 default 테마를, _라이트 모드_에서는 GitHub
테마를 사용하는 방법입니다.

bash
alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)"

설정 파일

bat는 설정 파일로도 사용자화 할 수 있습니다.
설정 파일의 위치는 운영 체제에 따라 다릅니다.
아래 커맨드를 통해 시스템의 기본 경로를 확인할 수 있습니다.

text
bat --config-file

또는, BAT_CONFIG_PATH 환경 변수를 사용하여 bat가 설정 파일의 기본 경로
이외의 위치를 사용하도록 할 수 있습니다.

bash
export BAT_CONFIG_PATH="/path/to/bat.conf"

기본 설정 파일은 --generate-config-file 옵션으로 생성할 수 있습니다.

bash
bat --generate-config-file

포맷

설정 파일은 단순히 커맨드 라인 인자들의 리스트입니다.
bat --help로 가능한 모든 옵션과 값들을 확인하세요.
추가적으로, 줄 앞에 # 문자를 추가해 주석을 넣을 수 있습니다.

설정 파일 예시:

bash
# "TwoDark" 테마 설정하기
--theme="TwoDark"

# 줄 번호, Git 변경 내용, 파일 헤더 보이기 (격자 없이)
--style="numbers,changes,header"

# 터미널에서 이탤릭체 쓰기 (일부 터미널에서 미지원)
--italic-text=always

# Arduino .ino 파일에 C++ 문법 쓰기
--map-syntax "*.ino:C++"

Windows에서 `bat` 사용하기

bat는 대부분의 경우 Windows에서 기본적으로 잘 작동하지만, 일부 기능은 추가적인
구성이 필요할 수 있습니다.

전제 조건

Visual C++ 재배포 가능
패키지를 설치해야 합니다.

페이징

Windows는 more 형식의 매우 제한된 페이저만 포함합니다.
Windows용 less 바이너리는
공식 홈페이지나
Chocolatey를 통해 다운로드 받을 수
있습니다.
이를 사용하려면 디렉터리 안의 바이너리를 PATH에 넣거나
환경 변수로 정의하세요.
Chocolatey 패키지는 less를 자동으로 설치합니다.

색상

Windows 10은
v1511부터
기본적으로 conhost.exe(Command Prompt)와 PowerShell에서 색상을 지원하며,
최신 버전의 bash에서도 색상을 지원합니다.
이전 버전의 Windows에서는, ConEmu가 포함된
Cmder를 사용할 수 있습니다.

참고: Git과 MSYS 버전의 less는 Windows에서 색상을 올바르게 해석하지
않습니다.
다른 페이저가 설치되어 있지 않은 경우, --paging=never을 넘겨주거나
BAT_PAGER을 빈 문자열로 설정하여 페이징을 완전히 비활성화 할 수 있습니다.

Cygwin

Windows에서의 bat은 기본적으로 Cygwin의 unix 스타일 경로(/cygdrive/*)를
지원하지 않습니다.
Cygwin 절대 경로를 인자로 받았을 때, bat은 다음과 같은 오류를 반환합니다:
The system cannot find the path specified. (os error 3)

이는 wrapper를 만들거나 다음 함수를 .bash_profile에 추가하여 해결할 수
있습니다:

bash
bat() {
    local index
    local args=("$@")
    for index in $(seq 0 ${#args[@]}) ; do
        case "${args[index]}" in
        -*) continue;;
        *)  [ -e "${args[index]}" ] && args[index]="$(cygpath --windows "${args[index]}")";;
        esac
    done
    command bat "${args[@]}"
}

문제 해결

터미널과 색상

bat은 터미널의 트루컬러 지원 여부와 상관 없이 동작합니다.
그러나 대부분 문법 강조 테마의 색상은 8비트 색상에 최적화되어 있지 않습니다.
따라서 24비트 트루컬러 지원이 되는 터미널(terminator, konsole, iTerm2,
...)을 사용하는 것을 적극 권장합니다.
트루컬러를 지원하는 터미널들과 더 자세한 정보는
이 글에서 찾아보실 수 있습니다.

사용하고 있는 트루컬러 터미널에서 COLORTERM 변수를 truecolor 혹은
24bit로 설정되어 있는지 확인하세요.
그렇지 않을 경우, bat은 24비트 확장열(escape sequence)이 지원되는지 여부를
판단할 수 없습니다 (그리고 8비트 색상을 사용합니다).

줄 번호와 격자가 잘 보이지 않는 경우

다른 테마를 사용해 보세요 (bat --list-themes에서 목록을 볼 수 있습니다).
OneHalfDark와 OneHalfLight 테마는 더 밝은 눈금과 선의 색상을 사용합니다.

파일 인코딩

bat은 기본적으로 UTF-8과 UTF-16을 지원합니다.
다른 모든 종류의 파일 인코딩에 대해서는, 일반적으로 인코딩을 자동으로 판별하는
방법이 없기 때문에 먼저 UTF-8으로 변환해야 할 수 있습니다.
이를 위해 iconv를 사용할 수 있습니다.
예시: Latin-1(ISO-8859-1)로 인코딩된 PHP 파일은 다음과 같이 처리할 수 있습니다:

bash
iconv -f ISO-8859-1 -t UTF-8 my-file.php | bat

참고: bat으로 문법 자동 감지가 되지 않는 경우에는 -l/--language 옵션을
사용할 수 있습니다.

개발

bash
# 모든 서브모듈을 받기 위해 재귀적으로 복제하기
git clone --recursive https://github.com/sharkdp/bat

# (디버그 버전) 빌드
cd bat
cargo build --bins

# 단위 테스트와 통합 테스트 실행
cargo test

# (배포 버전) 설치
cargo install --locked

# 수정된 문법과 테마가 적용된 bat 바이너리 빌드
bash assets/create.sh
cargo install --locked --force

bat의 pretty-printing 기능을 라이브러리로 사용하는 애플리케이션을 만들고
싶다면, API 문서를 살펴보세요.
참고로 bat에 라이브러리로써 의존한다면, regex-onig나 regex-fancy를
기능으로 사용해야 합니다.

기여하기

CONTRIBUTING.md 가이드를 살펴보세요.

메인테이너들

보안 취약점

만약 bat의 취약점을 발견하였다면, David Peter에게 메일로 연락주시기 바랍니다.

프로젝트 목표와 대안들

bat은 다음과 같은 목표를 달성하려고 합니다:

  • 아름답고 발전된 문법 강조 기능 제공
  • Git과의 연동을 통한 파일 변경 내용 확인
  • (POSIX) cat의 대체제
  • 사용자 친화적인 커맨드 라인 인터페이스 제공

비슷한 프로그램들을 찾고 있다면 많은 대안들이 있습니다.
비교는 이 문서를 참조해 주세요.

라이센스

Copyright (c) 2018-2021 bat-developers.

bat는 여러분의 선택에 따라 MIT 라이센스 또는 Apache 라이센스 2.0의 조건에 따라
배포됩니다.

라이센스의 세부사항은 LICENSE-APACHE와
LICENSE-MIT를 참조하세요.


File: doc/README-ru.md

Подсветка синтаксиса

bat поддерживает подсветку синтаксиса для огромного количества языков программирования и разметки:

Интеграция с Git

bat использует git, чтобы показать изменения в коде
(смотрите на левый сайдбар):

Показ непечатных символов

Вы можете использовать флаг -A / --show-all, чтобы показать непечатные символы:

Автоматический пейджинг терминала

bat умеет перенаправлять вывод в пейджер терминала (например, в less), если вывод не помещается на экране полностью.
Если вы хотите, чтобы bat работал как cat всё время, вы можете установить опцию --paging=never в командной строке или в конфигурационном файле.
Если вы намерены использовать bat в качестве алиаса для cat, вы можете установить alias cat='bat --paging=never', чтобы сохранить изначальное поведение.

Объединение файлов

О... Вы также можете объединять файлы :wink:. Когда
bat обнаружит неинтерактивный терминал (например, когда вы перенаправляете вывод в файл или процесс), он будет работать как утилита cat и выведет содержимое файлов как обычный текст (без подсветки синтаксиса).

Как использовать

Вывести единственный файл в терминале

bash
> bat README.md

Отобразить сразу несколько файлов в терминале

bash
> bat src/*.rs

Читаем из stdin и определяем синтаксис автоматически (внимание: это делается по заглавной строке файла, например, #!/bin/sh)

bash
> curl -s https://sh.rustup.rs | bat

Прочитать из stdin с явным указанием языка

bash
> yaml2json .travis.yml | json_pp | bat -l json

Вывести и выделить неотображаемые символы

bash
> bat -A /etc/hosts

Использование в качестве замены cat

bash
bat > note.md  # мгновенно создаем новый файл

bat header.md content.md footer.md > document.md

bat -n main.rs  # показываем только количество строк

bat f - g  # выводит 'f', потом stdin, а потом 'g'.

Интеграция с другими утилитами

`fzf`

Вы можете использовать bat как просмотрщик для fzf.
Чтобы это заработало, используйте опцию --color=always, чтобы вывод был всегда цветным.
Вы можете также использовать опцию --line-range, чтобы уменьшить время загрузки для больших файлов:

bash
fzf --preview "bat --color=always --style=numbers --line-range=:500 {}"

Больше деталей смотрите в README программы fzf.

`find` или `fd`

Вы можете использовать флаг -exec в find, чтобы посмотреть превью всех файлов в bat

bash
find … -exec bat {} +

Если вы используете fd, применяйте для этого флаг -X/--exec-batch:

bash
fd … -X bat

`ripgrep`

С помощью batgrep, bat может быть использован для вывода результата запроса ripgrep

bash
batgrep needle src/

`tail -f`

bat может быть использован вместе с tail -f, чтобы выводить содержимое файла с подсветкой синтаксиса в реальном времени.

bash
tail -f /var/log/pacman.log | bat --paging=never -l log

Заметьте, что мы должны отключить пэйджинг, чтобы это заработало. Мы также явно указали синтаксис (-l log), так как он не может быть автоматически определен в данном случае.

`git`

Вы можете использовать bat с git show, чтобы просмотреть старую версию файла с подсветкой синтаксиса:

bash
git show v0.6.0:src/main.rs | bat -l rs

`git diff`

Вы можете использовать bat с git diff для просмотра строк кода вокруг изменений с подсветкой синтаксиса:

bash
batdiff() {
    git diff --name-only --relative --diff-filter=d -z | xargs -0 bat --diff
}

Если вы хотите использовать это как отдельную программу, посмотрите batdiff из bat-extras.

Если вам это нужна более полная поддержка для операций с git и diff, посмотрите delta.

`xclip`

Нумерация строк и отображение изменений затрудняет копирование содержимого файлов в буфер обмена.
Чтобы справиться с этим, используйте флаг -p/--plain или просто перенаправьте стандартный вывод в xclip:

bash
bat main.cpp | xclip

bat обнаружит перенаправление вывода и выведет обычный текст без подсветки синтаксиса.

`man`

bat может быть использован для раскрашивания вывода man, для этого установите переменную окружения
MANPAGER:

bash
export MANPAGER="sh -c 'col -bx | bat -l man -p'"
man 2 select

(замените bat на batcat, если у вас Debian или Ubuntu)

Возможно вам понадобится также установить MANROFFOPT="-c", если у вас есть проблемы с форматированием.

Если вы хотите сделать этой одной командой, вы можете использовать batman.

Обратите внимание, что синтаксис manpage разрабатывается в этом репозитории и все еще находится в разработке.

Также заметьте, что это не заработает с реализацией man через Mandocs.

`prettier` / `shfmt` / `rustfmt`

Prettybat — скрипт, который форматирует код и выводит его с помощью bat.

Подсветка сообщений `--help`

Вы можете использовать bat, чтобы подсвечивать текст справки комманд: $ cp --help | bat -plhelp

Вы можете сделать такую вспомогательную команду для этого:

bash
# in your .bashrc/.zshrc/*rc
alias bathelp='bat --plain --language=help'
help() {
    "$@" --help 2>&1 | bathelp
}

В этом случае, вы можете просто писать $ help cp или $ help git commit.

Если вы используете zsh, вы можете объявить глобальные алиасы для -h и --help:

bash
alias -g -- -h='-h 2>&1 | bat --language=help --style=plain'
alias -g -- --help='--help 2>&1 | bat --language=help --style=plain'

В этом случае, вы можете продолжать использовать cp --help, но при этом получать подцвеченный вывод.

Обратите внимание, что не всегда опция -h является краткой формы опции --help (например, у ls).

Пожалуйста, сообщайте о проблемах с подсветкой справки в этот репозиторий.

Установка

Ubuntu (с помощью `apt`)

... и другие дистрибутивы основанные на Debian.

bat доступен на Ubuntu since 20.04 ("Focal") и Debian since August 2021 (Debian 11 - "Bullseye").

Если ваша версия Ubuntu/Debian достаточно новая, вы можете установить bat так:

bash
apt install bat

Если вы установили bat таким образом, то бинарный файл может быть установлен как batcat вместо bat (из-за конфликта имени с другим пакетом). Вы можете сделать симлинк или алиас bat -> batcat, чтобы предотвратить подобные проблемы и в других дистрибутивах.

bash
mkdir -p ~/.local/bin
ln -s /usr/bin/batcat ~/.local/bin/bat

Ubuntu (С помощью самого нового `.deb` пакета)

... и другие дистрибутивы Linux основанные на Debian

Если пакет еще недоступен в вашем Ubuntu/Debian дистрибутиве или вы хотите установить самую последнюю версию bat, то вы можете скачать самый последний deb-пакет отсюда:
release page и установить так:

bash
sudo dpkg -i bat_0.18.3_amd64.deb  # измените архитектуру и версию

Alpine Linux

Вы можете установить bat из официальных источников:

bash
apk add bat

Arch Linux

Вы можете установить bat из официального источника:

bash
pacman -S bat

Fedora

Вы можете установить bat из официального репозитория Fedora Modular.

bash
dnf install bat

Gentoo Linux

Вы можете установить bat из официальных источников:

bash
emerge sys-apps/bat

Void Linux

Вы можете установить bat с помощью xbps-install:

bash
xbps-install -S bat

FreeBSD

Вы можете установить bat с помощью pkg:

bash
pkg install bat

или самому скомпилировать его:

bash
cd /usr/ports/textproc/bat
make install

On OpenBSD

Вы можете установить bat с помощью pkg_add(1):

bash
pkg_add bat

С помощью nix

Вы можете установить bat, используя nix package manager:

bash
nix-env -i bat

Через flox

Вы можете установить bat используя Flox

bash
flox install bat

openSUSE

Вы можете установить bat с помощью zypper:

bash
zypper install bat

На macOS (или Linux) через Homebrew

Вы можете установить bat с помощью Homebrew:

bash
brew install bat

На macOS через MacPorts

Или же установить его с помощью MacPorts:

bash
port install bat

Windows

Есть несколько способов установить bat. Как только вы установили его, посмотрите на секцию "Использование bat в Windows".

Пререквитизы

Вам нужно установить пакет Visual C++ Redistributable.

С помощью WinGet

Вы можете установить bat через WinGet:

bash
winget install sharkdp.bat

С помощью Chocolatey

Вы можете установить bat с помощью Chocolatey:

bash
choco install bat

С помощью Scoop

Вы можете установить bat с помощью scoop:

bash
scoop install bat

Из заранее скомпилированных файлов:

Их вы можете скачать на странице релизов.

Из скомпилированных файлов

Перейдите на страницу релизов для
скомпилированных файлов bat для различных платформ. Бинарные файлы со статической связкой так же доступны: выбирайте архив с musl в имени.

Из исходников

Если вы желаете установить bat из исходников, вам понадобится Rust 1.79.0 или выше. После этого используйте cargo, чтобы всё скомпилировать:

bash
cargo install --locked bat

Заметьте, что дополнительные файлы, такие как документация man и подсказки командной строки, не могут быть установлены таким способом.
Они будут сгенерированы командой cargo должны быть доступны в папке сборки (в build).

Подсказки командной строки также доступны при таком запуске:

bash
bat --completion <shell>
# see --help for supported shells

Кастомизация

Темы для подсветки синтаксиса

Используйте bat --list-themes, чтобы вывести список всех доступных тем. Для выбора темы TwoDark используйте bat с флагом
--theme=TwoDark или выставьте переменную окружения BAT_THEME в TwoDark. Используйте export BAT_THEME="TwoDark" в конфигурационном файле вашей оболочки, чтобы изменить ее навсегда. Или же используйте конфигурационный файл bat.

Если вы хотите просто просмотреть темы, используйте следующую команду (для этого вам понадобится fzf):

bash
bat --list-themes | fzf --preview="bat --theme={} --color=always /путь/к/файлу"

bat отлично смотрится на темном фоне. Однако если ваш терминал использует светлую тему, то такие темы как GitHub или OneHalfLight будут смотреться куда лучше!
Вы также можете использовать новую тему, для этого перейдите в раздел добавления тем.

Изменение внешнего вывода

Вы можете использовать флаг --style, чтобы изменять внешний вид вывода в bat.
Например, вы можете использовать --style=numbers,changes, чтобы показать только количество строк и изменений в Git. Установите переменную окружения BAT_STYLE чтобы изменить это навсегда, или используйте конфиг файл bat.

Добавление новых синтаксисов

bat использует syntect для подсветки синтаксиса. syntect может читать
файл .sublime-syntax
и темы. Чтобы добавить новый синтаксис, сделайте следующее:

Создайте каталог с синтаксисом:

bash
mkdir -p "$(bat --config-dir)/syntaxes"
cd "$(bat --config-dir)/syntaxes"

# Разместите файлы '.sublime-syntax'
# в каталоге (или субкаталогах), например:
git clone https://github.com/tellnobody1/sublime-purescript-syntax

Теперь используйте следующую команду, чтобы превратить эти файлы в бинарный кеш:

bash
bat cache --build

Теперь вы можете использовать bat --list-languages, чтобы проверить, доступны ли новые языки.

Если когда-нибудь вы заходите вернуться к настройкам по умолчанию, введите

bash
bat cache --clear

Добавление новых тем

Это работает похожим образом, так же как и добавление новых тем подсветки синтаксиса

Во-первых, создайте каталог с новыми темами для синтаксиса:

bash
mkdir -p "$(bat --config-dir)/themes"
cd "$(bat --config-dir)/themes"

# Загрузите тему в формате '.tmTheme':
git clone https://github.com/greggb/sublime-snazzy

# Обновите кеш
bat cache --build

Теперь используйте bat --list-themes, чтобы проверить доступность новых тем.

Использование другого пейджера.

bat использует пейджер, указанный в переменной окружения PAGER. Если она не задана, то используется less.
Если вы желаете использовать другой пейджер, вы можете либо изменить переменную PAGER, либо BAT_PAGER чтобы перезаписать то, что указано в PAGER.

Чтобы передать дополнительные аргументы вашему пейджеру, перечислите их в этой переменной:

bash
export BAT_PAGER="less -RF"

Так же вы можете использовать файл конфигурации bat (флаг --pager).

Внимание: По умолчанию пейджером являетсяless (без каких-либо аргументов),
bat задаст следующие флаги для пейджера:
-R/--RAW-CONTROL-CHARS,
-F/--quit-if-one-screen и -X/--no-init. Последний флаг(-X) используется только для less, чья версия раньше 530.

Флаг -R нужен чтобы корректно воспроизвести ANSI цвета. Второй флаг (-F) говорит
less чтобы тот сразу же завершился, если размер вывода меньше чем вертикальный размер терминала.
Это удобно для небольших файлов, так как вам не надо каждый раз нажимать q, чтобы выйти из пейджера. Третий флаг (-X) нужен для того, чтобы исправить баг с --quit-if-one-screen в старых версиях less. К сожалению, это блокирует возможность использования колеса мышки.

Если вы хотите все же его включить, вы можете добавить флаг -R.
Для less новее чем 530 оно должно работать из коробки.

Темная тема

Если вы используете темный режим в macOS, возможно вы захотите чтобы bat использовал другую тему, основанную на теме вашей ОС. Следующий сниппет использует тему default, когда у вас включен темный режим, и тему GitHub, когда включен светлый.

bash
alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)"

Файл конфигурации

bat также может быть кастомизирован с помощью файла конфигурации. Его местоположение зависит от вашей ОС: чтобы посмотреть его путь, введите

text
bat --config-file

Также вы можете установить переменную окружения BAT_CONFIG_PATH, чтобы изменить путь к файлу конфигурации.

bash
export BAT_CONFIG_PATH="/path/to/bat.conf"

Файл конфигурации «по умолчанию» может быть создан с помощью флага --generate-config-file.

bash
bat --generate-config-file

Формат

Файл конфигурации - это всего лишь набор аргументов. Введите bat --help, чтобы просмотреть список всех возможных флагов и аргументов. Также вы можете закомментировать строку с помощью #.

Пример файла конфигурации:

bash
# Установить тему "TwoDark"
--theme="TwoDark"

# Показывать количество строк, изменений в Git и заголовок файла
--style="numbers,changes,header"

# Использовать курсив (поддерживается не всеми терминалами)
--italic-text=always

# Использовать синтаксис C++ для всех Arduino .ino файлов
--map-syntax "*.ino:C++"

# Использовать синтаксис Git Ignore для всех файлов .ignore
--map-syntax ".ignore:Git Ignore"

Использование `bat` в Windows

bat полностью работоспособен "из коробки", но для некоторых возможностей могут понадобиться дополнительные настройки.

Пейджинг

Windows поддерживает только очень простой пейджер more. Вы можете скачать установщик для less с его сайта или через Chocolatey. Чтобы его использовать, скопируйте исполняемый файл в ваш PATH или используйте переменную окружения. Пакет из Chocolatey установит все автоматически.

Цвета

Windows 10 поддерживает цвета и в conhost.exe (Command Prompt), и в PowerShell начиная с версии Windows
[v1511](https://ru.wikipedia.org/wiki/Windows_10#Обновления и поддержка), так же как и в bash. На ранних версиях Windows вы можете использовать
Cmder, в котором есть ConEmu.

Внимание: Версия less в Git и MSYS2 воспроизводит цвета некорректно. Если у вас нет других пейджеров, мы можете отключить использование пейджеров с помощью флага --paging=never
или установить BAT_PAGER равным пустой строке.

Cygwin

Из коробки bat не поддерживает пути в стиле Unix (/cygdrive/*). Когда указан абсолютный путь cygwin, bat выдаст следующую ошибку: The system cannot find the path specified. (os error 3)

Она может быть решена добавлением следующей функции в .bash_profile:

bash
bat() {
    local index
    local args=("$@")
    for index in $(seq 0 ${#args[@]}) ; do
        case "${args[index]}" in
        -*) continue;;
        *)  [ -e "${args[index]}" ] && args[index]="$(cygpath --windows "${args[index]}")";;
        esac
    done
    command bat "${args[@]}"
}

Проблемы и их решение

Терминалы и цвета

bat поддерживает терминалы с и без поддержки truecolor. Однако подсветка синтаксиса не оптимизирована для терминалов с 8-битными цветами, и рекомендуется использовать терминалы с поддержкой 24-битных цветов (terminator, konsole, iTerm2, ...).
Смотрите эту статью для полного списка терминалов.

Удостоверьтесь, что переменная COLORTERM равна truecolor или
24bit. Иначе bat не сможет определить поддержку 24-битных цветов (и будет использовать 8-битные).

Текст и номера строк плохо видны

Используйте другую тему (bat --list-themes выведет список всех установленных тем). Темы OneHalfDark и
OneHalfLight имеют более яркие номера строк и тексты.

Кодировки файлов

bat поддерживает UTF-8 и UTF-16. Файлы в других кодировках, возможно, придётся перекодировать, так как кодировка может быть распознана неверно. Используйте iconv.
Пример: у вас есть PHP файл в кодировке Latin-1 (ISO-8859-1):

bash
iconv -f ISO-8859-1 -t UTF-8 my-file.php | bat

Внимание: вам может понадобиться флаг -l/--language, если bat не сможет автоматически определить синтаксис.

Разработка

bash
# Рекурсивно клонирует все модули
git clone --recursive https://github.com/sharkdp/bat

# Компиляции в режиме разработки
cd bat
cargo build --bins

# Запуск тестов
cargo test

# Установка (релизная версия)
cargo install --locked

# Компилирование исполняемого файла bat с другим синтаксисом и темами
bash assets/create.sh
cargo install --locked --force

Разработчики

Цели и альтернативы

Цели проекта bat:

  • Красивая и продвинутая подсветка синтаксиса.
  • Интеграция с Git.
  • Полноценная замена cat.
  • Дружелюбный интерфейс и аргументы.

Есть очень много альтернатив bat. Смотрите этот документ для сравнения.

Лицензия

Copyright (c) 2018-2024 Разработчики bat.

bat распространяется под лицензиями MIT License и Apache License 2.0 (на выбор пользователя).

Смотрите LICENSE-APACHE и LICENSE-MIT для более подробного ознакомления.


File: doc/README-zh.md

语法高亮

bat 对大部分编程语言和标记语言提供语法高亮:

Git 集成

bat 能从 git 中获取文件的修改并展示在边栏(见下图):

不可打印(non-printable)字符可视化

添加-A/--show-all参数可以文件文件中的不可打印字符:

自动分页

bat会在一般情况下将大于屏幕可显示范围的内容输出到分页器(pager, e.g. less)。

你可以在调用时添加--paging=never参数来使bat不使用分页器(就像cat一样)。如果你想要用为cat使用bat别名,可以在 shell 配置文件(shell configuration)中添加alias cat='bat --paging=never'。

智能输出

bat能够在设置了分页器选项的同时进行管道:wink:。
当bat检测到当前环境为非可交互终端或管道时(例如使用bat并将内容用管道输出到文件),bat会像cat一样,一次输出文件内容为纯文本且无视--paging参数。

如何使用

在终端中查看一个文件

bash
> bat README.md

一次性展示多个文件

bash
> bat src/*.rs

从stdin读入流,自动为内容添加语法高亮(前提是输入内容的语言可以被正确识别,通常根据内容第一行的 shebang 标记,形如#!bin/sh)

bash
> curl -s https://sh.rustup.rs | bat

显式指定stdin输入的语言

bash
> yaml2json .travis.yml | json_pp | bat -l json

显示不可打印字符

bash
> bat -A /etc/hosts

与cat的兼容性

bash
bat > note.md  # 创建一个空文件

bat header.md content.md footer.md > document.md

bat -n main.rs  # 只显示行号

bat f - g  # 输出 f,接着是标准输入流,最后 g

第三方工具交互

`fzf`

你可以使用bat作为fzf的预览器。这需要在bat后添加--color=always选项,以及--line-range 选项来限制大文件的加载次数。

bash
fzf --preview 'bat --color=always --style=numbers --line-range=:500 {}'

更多信息请参阅fzf的说明。

`find` 或 `fd`

你可以使用find的-exec选项来用bat预览搜索结果:

bash
find … -exec bat {} +

亦或者在用fd时添加-X/--exec-batch选项:

bash
fd … -X bat

`ripgrep`

bat也能用batgrep来显示ripgrep的搜索结果。

bash
batgrep needle src/

`tail -f`

当与tail -f一起使用,bat可以持续监视文件内容并为其添加语法高亮。

bash
tail -f /var/log/pacman.log | bat --paging=never -l log

注意:这项功能需要在关闭分页时使用,同时要手动指定输入的内容语法(通过-l log)。

`git`

bat也能直接接受来自git show的输出并为其添加语法高亮(当然也需要手动指定语法):

bash
git show v0.6.0:src/main.rs | bat -l rs

`git diff`

bat也可以和git diff一起使用:

bash
batdiff() {
    git diff --name-only --relative --diff-filter=d -z | xargs -0 bat --diff
}

该功能也作为一个独立工具提供,你可以在bat-extras中找到batdiff。

如果你想了解更多 git 和 diff 的信息,参阅delta。

`xclip`

当需要拷贝文件内容时,行号以及 git 标记会影响输出,此时可以使用-p/--plain参数来把纯文本传递给xclip。

bash
bat main.cpp | xclip

bat会检测输出是否是管道重定向来决定是否使用纯文本输出。

`man`

bat 可以通过设置 MANPAGER 环境变量,用作 man 的彩色分页器:

bash
export MANPAGER="sh -c 'awk '\''{ gsub(/\x1B\[[0-9;]*m/, \"\", \$0); gsub(/.\x08/, \"\", \$0); print }'\'' | bat -p -lman'"
man 2 select

(如果你使用 Debian 或 Ubuntu,请将 batcat 替换为 bat)

如果你希望将其打包为一个新的命令,也可以使用 batman。

[!WARNING]
在使用 Mandoc 的 man 实现时,这无法直接工作。

请使用 batman,或将此 Shell 脚本包装为 Shebang 可执行文件,并将 MANPAGER 指向该文件。

注意,Manpage 语法是在此仓库中开发的,仍需一些改进。

`prettier` / `shfmt` / `rustfmt`

prettybat脚本能够格式化代码并用bat输出。

安装

Ubuntu (使用 `apt`)

... 以及其他基于 Debian的发行版.

bat 要求的版本: Ubuntu 高于 20.04 ("Focal") 和 Debian 高于 August 2021 (Debian 11 - "Bullseye").

当你的发行版满足条件那么直接在终端运执行:

bash
sudo apt install bat

重要:如果你通过这种方法安装bat,请留意你所安装的可执行文件是否为batcat(由其他包的可执行文件名冲突造成)。你可以创建一个bat -> batcat的符号链接(symlink)或别名来避免因为可执行文件不同带来的问题并与其他发行版保持一致性。

bash
mkdir -p ~/.local/bin
ln -s /usr/bin/batcat ~/.local/bin/bat

Ubuntu (使用`.deb`包)

... 以及其他基于 Debian的发行版.

如果你无法使用上一种方法安装,或需要用最新版的bat,你可以从release 页面下载最新的.deb包并通过下述方法安装:

bash
sudo dpkg -i bat_0.18.3_amd64.deb  # adapt version number and architecture

Alpine Linux

你可以用下面下列命令从官方源中安装bat 包:

bash
apk add bat

Arch Linux

你可以用下面下列命令从官方源中安装bat包:

bash
pacman -S bat

Fedora

你可以使用下列命令从官方Fedora Modular仓库安装bat 包:

bash
dnf install bat

Funtoo Linux

你可以从 dev-kit 中安装bat 包:

bash
emerge sys-apps/bat

Gentoo Linux

你可以使用下列命令从官方源中安装 bat 包:

bash
emerge sys-apps/bat

Void Linux

你可以用 xbps-install 安装bat:

bash
xbps-install -S bat

Termux:

你可以用 pkg 安装`bat:

bash
pkg install bat

FreeBSD

你可以用 pkg 来安装一份预编译的bat 包:

bash
pkg install bat

或从 FreeBSD ports 自己编译一份:

bash
cd /usr/ports/textproc/bat
make install

OpenBSD

你可以用pkg——add安装bat包

bash
pkg_add bat

通过 nix

你可以用nix 包管理器安装bat:

bash
nix-env -i bat

openSUSE

你可以用 zypper 安装bat:

bash
zypper install bat

通过 snap

目前还没有推荐的 snap 包可用。可以使用其他现存的包但不会受到官方支持且可能会遇到问题。

macOS (或 Linux) 通过 Homebrew

你可以用 Homebrew on MacOS 或者 Homebrew on Linux 安装bat:

bash
brew install bat

macOS 通过 MacPorts

或用 MacPorts 安装bat:

bash
port install bat

Windows

在 Windows 上具有多种安装bat的方法。若你已完成安装,记得看看 "在 Windows 上使用bat" 。

前置条件

你必须已安装 Visual C++ Redistributable 包。

使用 Chocolatey

你可以用Chocolatey 安装bat:

bash
choco install bat

使用 Scoop

你可以用 scoop 安装bat:

bash
scoop install bat

使用预编译二进制版本

直接从 Release 发布页 下载已经编译好的二进制包,前提是你安装了 Visual C++ Redistributable 包。

使用二进制版本

在 Release 发布页 中可以找到为多种架构构建的bat版本和静态编译的二进制文件(文件名带有musl)。

从源码编译

如果你想要自己构建bat,那么你需要安装有高于1.74.0版本的 Rust。

使用以下命令编译。

bash
cargo install --locked bat

注意:man page或 shell 自动补全所需要的额外文件无法通过该方法安装。但你可以在cargo的生成目录找到这些文件(build目录下)。

自定义

语法高亮主题

使用 bat --list-themes 一份语法高亮主题的清单,然后用--theme=TwoDark来指定主题为TwoDark,也可以通过设置BAT_THEME环境变量来选定主题。把export BAT_THEME="TwoDark"添加到 shell 的启动脚本(shell startup file)来取得永久效果。或者使用bat的配置文件

若想要查看所有主题在一个文件上的显示效果可以用一下命令(需要安装fzf):

bash
bat --list-themes | fzf --preview="bat --theme={} --color=always /path/to/file"

bat在默认情况下能够在黑色主题背景下获得较好的效果,如果你的终端使用亮色背景,可以试试GitHub或OneHalfLight。想要添加自定义主题可以参考添加主题。

8-bit 主题

bat 自带三个 8-bit 色彩 主题:

  • ansi 适应于大部分终端。它使用 3-bit 色彩:黑红绿黄蓝洋红靛青白。
  • base16专为 base16 终端设计。它使用 4-bit 色彩(带有亮度的 3-bit 色彩)。根据 base16 styling guidelines 制作。
  • base16-25专为 base16-shell 设计。它把部分亮色替换为 8-bit 色彩。请不要直接使用该主题,除非你清楚你的256色终端是否使用 base16-shell。

尽管这些主题具有诸多限制,但具有一些 truecolor 主题不具有的三个优点:

  • 享有最佳兼容性。并不是所有终端工具都支持高于 3-bit 的色彩。
  • 适应终端主题。
  • 视觉上和其他的终端工具更协调。

输出样式

你可以用--style参数来控制bat输出的样式。使用--style=numbers,changes可以只开启 Git 修改和行号显示而不添加其他内容。BAT_STYLE环境变量具有相同功能。

添加新的语言和语法

当现有的bat不支持某个语言或语法时你可以自己添加。

bat使用syntect库来支持语法高亮,该库使用 Sublime Text .sublime-syntax 语法文件和主题。而后者中的大部分可以在 Package Control 找到。

当你找到一份语法文件,按照下列方法:

  1. 创建包含语法描述文件的目录:

    bash
    mkdir -p "$(bat --config-dir)/syntaxes"
    cd "$(bat --config-dir)/syntaxes"
    
    # Put new '.sublime-syntax' language definition files
    # in this folder (or its subdirectories), for example:
    git clone https://github.com/tellnobody1/sublime-purescript-syntax
  2. 调用下面指令把文件转换为二进制缓存:

    bash
    bat cache --build
  3. 最后用bat --list-languages来检查新的语法是否被成功导入。如果想要回滚到最初状态,执行:

    bash
    bat cache --clear
  4. 如果你觉得bat有必要自带该语法支持,请在阅读指导后向仓库提交 Syntax Request。

添加主题

类似添加语法支持,第一步也是创建一个带有语法高亮的目录

bash
mkdir -p "$(bat --config-dir)/themes"
cd "$(bat --config-dir)/themes"

# 下载一个主题
git clone https://github.com/greggb/sublime-snazzy

# 更新二进制缓存
bat cache --build

然后用bat --list-themes检查添加是否成功。

添加或修改文件关联

你可以用--map-syntax参数添加或修改文件名模板。它需要一个类似pattern:syntax的参数来指定,其中pattern是 glob 文件匹配模板,syntax则是支持的语法的完整名(使用bat --list-languages来查看获取一份清单)。

注意:方便起见,你可能需要把参数添加到配置文件,而不是每次都在命令行中传递该参数。

以下展示了把“INI”关联到具有.conf扩展名的文件

bash
--map-syntax='*.conf:INI'

把.ignore文件与“Git Ignore”关联

bash
--map-syntax='.ignore:Git Ignore'

把/etc/apache2内的.conf文件关联到“Apache Conf”语法(bat已默认绑定)

bash
--map-syntax='/etc/apache2/**/*.conf:Apache Conf'

使用自定义分页器

bat默认使用PAGER环境变量定义的分页器,如果没有定义则使用less。bat提供了BAT_PAGER环境变量来专为bat选择分页器(优先级高于PAGER)。

注意:当PAGER设置为more或most时,bat会使用less来代替以确保能提供色彩支持。

bash
export BAT_PAGER="less -RF"

除了使用环境变量来改变bat使用的的分页器,也可以在配置文件中提供--pager参数。

注意:bat会把部分命令行参数直接传递给分页器:-R/--RAW-CONTROL-CHARS,-F/--quit-if-one-screen以及-X/--no-init(该参数仅适用于高于530版本的less)。其中-R 参数需要在解释 ANSI 标准颜色时起作用。-F则指示less在输出内容的垂直尺寸小于终端尺寸时立即退出。当文件内容可以在一个屏幕里完全显示时,就不需要按q键退出阅读模式,很方便就是了。-X则能修复-F在less的老版本中的一些bug(代价是不支持鼠标滚轮,但可以用-R来取消quit-if-one-screen功能。)。

缩进

bat 使用四个空格宽的制表符,而不受分页器影响,同时也可以用--tabs参数来自定义。

注意:通过其他方法针对分页器的制表符设置不会生效(例如通过bat的--pager参数传递或less使用的LESS环境变量)。因为在输出提交给分页器之前,内容中的制表符就已经被bat替换为了特定长度的空格以避免由于边栏导致的缩进问题。你可以用给bat传递--tabs=0参数来取消该设定并让分页器自己处理制表符。

暗色模式

如果你用的 macOS 处于暗色模式,你可以为bat启用基于系统主题的主题。如下所示操作会让bat在系统处于亮色模式时加载GitHub主题和暗色模式时加载default主题。

bash
alias cat="bat --theme=\$(defaults read -globalDomain AppleInterfaceStyle &> /dev/null && echo default || echo GitHub)"

配置文件

bash
bat --config-file

你也可以用BAT_CONFIG_PATH来为bat指定自定义位置的配置文件:

bash
export BAT_CONFIG_PATH="/path/to/bat.conf"

使用--generate-config-file参数调用bat会在指定位置生成一份默认的bat配置文件:

bash
bat --generate-config-file

格式

配置文件其实是一份按行分割的命令行参数列表。你可以用bat --help来查看所有可用的参数和适用的值。配置文件中#打头的行会被视为注释而不生效。

以下是一份示例:

bash
# 设置主题为 TwoDark
--theme="TwoDark"

# 显示行号和 Git 修改信息, 但没有边框
--style="numbers,changes,header"

# 在终端中以斜体输出文本(不是所有终端都支持)
--italic-text=always

# 使用 C++ 语法来给 Arduino 的 .ino 文件提供高亮
--map-syntax "*.ino:C++"

在 Windows 中使用 `bat`

bat 在 Windows 上开箱即用,除了部分功能需要额外配置。

前置条件

你需要先安装 Visual C++ Redistributable 包。

分页

Windows 只有一个提供有限功能的分页器,你可以从这里下载或用 Chocolatey 安装 Windows 版本的less。第一种方法需要你把它所在目录加入PATH环境变量或定义分页器变量

色彩

Windows 10 从 v1511 开始 shell(conhost.exe,命令提示符或 Powershell)原生支持色彩。在早些版本的 Windows 中你可以用第三方终端如 Cmder (使用ConEmu)。

注意:Git 和 MSYS 版本的 less 没法正确在 Windows 表达色彩。如果你没有安装其他分页器,你可以直接用--paging=never或设置BAT_PAGER为空字符串来关闭分页功能。

Cygwin

Windows 上的bat原生不支持 Cygwin' unix-style 路径(/cygdrive/*)。当传递一个绝对 cygwin 路径作为参数值时,bat会产生The system cannot find the path specified. (os error 3)的错误。你可以.bash_profile文件中添加以下函数来解决这个问题。

bash
bat() {
    local index
    local args=("$@")
    for index in $(seq 0 ${#args[@]}) ; do
        case "${args[index]}" in
        -*) continue;;
        *)  [ -e "${args[index]}" ] && args[index]="$(cygpath --windows "${args[index]}")";;
        esac
    done
    command bat "${args[@]}"
}

疑难解答

输出内容含糊不清

当输入文件包含颜色代码和其他 ANSI 转义符号时,bat会产生错误的语法高亮和文本,导致输出看起来令人无法理解。当你需要输出该文件时,请使用--color=never --wrap=never参数来关闭上色和文字包裹。

终端与色彩

bat会区分支持 truecolor 和不支持 truecolor 的终端。但是大部分语法高亮主题都是用了没有为 8-bit 色彩支持的颜色,因此强烈推荐使用一个支持 24-bit 色彩的终端(terminator,konsole,iTerm2...),或使用一个 8-bit 主题来限制一些颜色。查看这篇文章使用自定义分页器了解更多支持 truecolor 的终端。你需要定义COLORTERM变量为truecolor或24bit来确保bat能够识别终端的对颜色的支持,否则会使用 8 bit 模式。

行号和边框很难看清

试试其他主题,说不定能有所改善(用bat --list-themes查看主题列表)。

文件编码

bat原生支持 UTF-8 和 UTF-16。至于其他文件你可能需要在使用bat之前先把编码转换到UTF-8。

这里展示了使用iconv来把 Latin-1(ISO-8859-1) 编码的 PHP 文件转换到 UTF-8:

bash
iconv -f ISO-8859-1 -t UTF-8 my-file.php | bat

注意: 当bat无法识别语言时你可能会需要-l/--language参数。

开发

bash
# 递归 clone 以获取所有子模块
git clone --recursive https://github.com/sharkdp/bat

# 构建(调试版本)
cd bat
cargo build --bins

# 运行单元测试和集成测试
cargo test

# 安装(发布版本)
cargo install --path . --locked

# 使用修改后的语法和主题构建一个 bat 二进制文件
bash assets/create.sh
cargo install --path . --locked --force

如果你想构建一个使用 bat 美化打印功能的应用程序,请查看 API 文档。请注意,当你依赖 bat 作为库时,必须使用 regex-onig 或 regex-fancy 作为特性。

贡献指南

请查看 CONTRIBUTING.md 指南。

维护者

安全漏洞

如果你想报告 bat 中的漏洞,请通过邮件联系 David Peter。

项目目标和替代方案

bat 试图实现以下目标:

  • 提供美观的高级语法高亮
  • 与 Git 集成以显示文件修改
  • 成为 (POSIX) cat 的替代品
  • 提供用户友好的命令行界面

如果你在寻找类似的程序,有很多替代方案。请参阅本文档进行比较。

许可证

版权所有 (c) 2018-2021 bat-developers。

bat 可根据 MIT 许可证或 Apache 许可证 2.0 的条款使用,任选其一。

有关许可证的详细信息,请参阅 LICENSE-APACHE 和 LICENSE-MIT 文件。


File: doc/release-checklist.md

Release checklist

Version bump

  • Update version in Cargo.toml. Run cargo build to update Cargo.lock.
    Make sure to git add the Cargo.lock changes as well.
  • Find the current min. supported Rust version by running
    cargo metadata --no-deps --format-version 1 | jq -r '.packages[0].rust_version'.
  • Update the version and the min. supported Rust version in README.md and
    doc/README-*.md. Check with
    git grep -i -e 'rust.*1\.' -e '1\..*rust' | grep README | grep -v tests/.

CHANGELOG.md updates

  • Go to https://github.com/sharkdp/bat/releases/new, click "Choose a tag",
    type the name of the tag that will be created later, click "Generate release
    notes". DO NOT ACTUALLY CREATE ANY RELEASE IN THIS STEP.
  • Compare current CHANGELOG.md with auto-generated release notes and add
    missing entries. Expect in particular dependabot PRs to not be in
    CHANGELOG.md since they are auto-merged if CI passes.
  • Introduce a section for the new release and perform final touch-ups.

Update syntaxes and themes (build assets)

  • Install the latest master version (cargo clean && cargo install --locked -f --path .) and make
    sure that it is available on the PATH (bat --version should show the
    new version).
  • Run assets/create.sh and check in the binary asset files.

Documentation

  • Review -h, --help, and the man page. The man page is shown in
    the output of the CI job called Documentation, so look there.
    The CI workflow corresponding to the tip of the master branch is a good place to look.

Pre-release checks

  • Push all changes and wait for CI to succeed (before continuing with the
    next section).
  • Optional: manually test the new features and command-line options. To do
    this, install the latest bat version again (to include the new syntaxes
    and themes).
  • Run cargo publish --dry-run to make sure that it will
    succeed later (after creating the GitHub release).

Release

  • Create a tag and push it: git tag vX.Y.Z; git push origin tag vX.Y.Z.
    This will trigger the deployment via GitHub Actions.
    REMINDER: If your origin is a fork, don't forget to push to e.g. upstream instead!
  • Go to https://github.com/sharkdp/bat/releases/new to create the new
    release. Select the new tag and also use it as the release title. For the
    release notes, copy the corresponding section from CHANGELOG.md and
    possibly add additional remarks for package maintainers.
    Publish the release.
  • Check if the binary deployment works (archives and Debian packages should
    appear when the CI run for the Git tag has finished).
  • Publish to crates.io by running cargo publish in a clean repository.
    The safest way to do this is to clone a fresh copy.

Post-release

  • Prepare a new "unreleased" section at the top of CHANGELOG.md.
    Put this at the top:
text
# unreleased

## Features

## Bugfixes

## Other

## Syntaxes

## Themes

## `bat` as a library

File: doc/sponsors.md

Sponsors

bat development is sponsored by many individuals and companies. Thank you very much!

Please note, that being sponsored does not affect the individuality of the bat
project or affect the maintainers' actions in any way.
We remain impartial and continue to assess pull requests solely on merit - the
features added, bugs solved, and effect on the overall complexity of the code.
No issue will have a different priority based on sponsorship status of the
reporter.

Contributions from anybody are most welcomed, please see our CONTRIBUTING.md guide.


File: src/syntax_mapping/builtins/README.md

`/src/syntax_mapping/builtins`

The files in this directory define path/name-based syntax mappings, which amend
and take precedence over the extension/content-based syntax mappings provided by
syntect.

File organisation

Each TOML file should describe the syntax mappings of a single application, or
otherwise a set of logically-related rules.

What defines "a single application" here is deliberately vague, since the
file-splitting is purely for maintainability reasons. (Technically, we could
just as well use a single TOML file.) So just use common sense.

TOML files should reside in the corresponding subdirectory of the platform(s)
that they intend to target. At compile time, the build script will go through
each subdirectory that is applicable to the compilation target, collect the
syntax mappings defined by all TOML files, and embed them into the binary.

File syntax

Each TOML file should contain a single section named mappings, with each of its keys being a language
identifier (first column of bat -L; also referred to as "target").

The value of each key should be an array of "rules". The rules are expected to be objects with a glob string and a case_sensitive boolean. For simplification, a rule can be just a glob string, which is shorthand for the default case insensitive mode.

For example, if foo-application uses both TOML and YAML configuration files,
we could write something like this:

toml
# 30-foo-application.toml
[mappings]
"TOML" = [
    # rules for TOML syntax go here
    "/usr/share/foo-application/toml-config/*.conf",
    "/etc/foo-application/toml-config/*.conf",
]
"YAML" = [
    # rules for YAML syntax go here
    # ...
]

Dynamic environment variable replacement

In additional to the standard glob matcher syntax, rules also support dynamic
replacement of environment variables at runtime. This allows us to concisely
handle things like XDG.

All environment variables intended to be replaced at runtime must be enclosed in
${}, for example "/foo/*/${YOUR_ENV}-suffix/*.log". Note that this is the
only admissible syntax; other variable substitution syntaxes are not
supported and will either cause a compile time error, or be treated as plain
text.

For example, if foo-application also supports per-user configuration files, we
could write something like this:

toml
# 30-foo-application.toml
[mappings]
"TOML" = [
    # rules for TOML syntax go here
    "/usr/share/foo-application/toml-config/*.conf",
    "/etc/foo-application/toml-config/*.conf",
    "${XDG_CONFIG_HOME}/foo-application/toml-config/*.conf",
    "${HOME}/.config/foo-application/toml-config/*.conf",
]
"YAML" = [
    # rules for YAML syntax go here
    # ...
]

If any environment variable replacement in a rule fails (for example when a
variable is unset), or if the glob string after replacements is invalid, the
entire rule will be ignored.

Explicitly mapping to unknown

Sometimes it may be necessary to "unset" a particular syntect mapping - perhaps
a syntax's matching rules are "too greedy", and is claiming files that it should
not. In this case, there are two special identifiers:
MappingTarget::MapToUnknown and MappingTarget::MapExtensionToUnknown
(corresponding to the two variants of the syntax_mapping::MappingTarget enum).

An example of this would be *.conf files in general. So we may write something
like this:

toml
# 99-unset-ambiguous-extensions.toml
[mappings]
"MappingTarget::MapExtensionToUnknown" = [
    "*.conf",
]

Case sensitivity

By default, all glob patterns are matched case-insensitively. To match a pattern case-sensitively, use the object form of the rule with the case_sensitive option:

toml
[mappings]
"Python" = [{ glob = "BUILD", case_sensitive = true }]

Ordering

At compile time, all TOML files applicable to the target are processed in
lexicographical filename order. So 00-foo.toml takes precedence over
10-bar.toml, which takes precedence over 20-baz.toml, and so on. Note that
only the filenames of the TOML files are taken into account; the
subdirectories they are placed in have no influence on ordering.

This behaviour can be occasionally useful for creating high/low priority rules,
such as in the aforementioned example of explicitly mapping *.conf files to
unknown. Generally this should not be much of a concern though, since rules
should be written as specifically as possible for each application.

Rules within each TOML file are processed (and therefore matched) in the order
in which they are defined. At runtime, the syntax selection algorithm will
short-circuit and return the target of the first matching rule.