1
0
mirror of https://github.com/sharkdp/bat.git synced 2025-09-01 10:52:24 +01:00

Compare commits

..

6 Commits

Author SHA1 Message Date
David Peter
aa35cb52c4 Add exemplary hexyl plugin 2022-05-29 22:51:10 +02:00
David Peter
446b9181e6 Add simple 'directories' plugin 2022-05-29 21:04:47 +02:00
David Peter
040242c9be Add initial version of curl plugin 2022-05-29 20:57:08 +02:00
David Peter
dbf78d280a Fix loading of several plugins 2022-05-29 20:57:01 +02:00
David Peter
bc91af3ee5 Better error handling 2022-05-29 20:48:37 +02:00
David Peter
3811615606 Initial prototype for Lua plugins 2022-05-29 20:40:05 +02:00
65 changed files with 657 additions and 1079 deletions

View File

@@ -1,7 +1,7 @@
name: CICD
env:
MIN_SUPPORTED_RUST_VERSION: "1.60.0"
MIN_SUPPORTED_RUST_VERSION: "1.51.0"
CICD_INTERMEDIATES_DIR: "_cicd-intermediates"
on:
@@ -39,8 +39,6 @@ jobs:
min_version:
name: Minimum supported rust version
runs-on: ubuntu-20.04
env:
MSRV_FEATURES: --no-default-features --features minimal-application,bugreport,build-assets
steps:
- name: Checkout source code
uses: actions/checkout@v2
@@ -56,12 +54,12 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: clippy
args: --locked --all-targets ${{ env.MSRV_FEATURES }}
args: --locked --all-targets --all-features
- name: Run tests
uses: actions-rs/cargo@v1
with:
command: test
args: --locked ${{ env.MSRV_FEATURES }}
args: --locked
test_with_new_syntaxes_and_themes:
name: Run tests with updated syntaxes and themes
@@ -98,7 +96,7 @@ jobs:
uses: actions-rs/cargo@v1
with:
command: test
args: --locked --release --test assets -- --ignored
args: --locked --release -- --ignored
- name: Syntax highlighting regression test
run: tests/syntax-tests/regression_test.sh
- name: List of languages
@@ -108,32 +106,6 @@ jobs:
- name: Test custom assets
run: tests/syntax-tests/test_custom_assets.sh
test_with_system_config:
name: Run tests with system wide configuration
runs-on: ubuntu-20.04
steps:
- name: Git checkout
uses: actions/checkout@v2
- name: Prepare environment variables
run: |
echo "BAT_SYSTEM_CONFIG_PREFIX=$GITHUB_WORKSPACE/tests/examples/system_config" >> $GITHUB_ENV
- name: Install Rust toolchain
uses: actions-rs/toolchain@v1
with:
toolchain: stable
default: true
profile: minimal
- name: Build and install bat
uses: actions-rs/cargo@v1
with:
command: install
args: --locked --path .
- name: Run unit tests
uses: actions-rs/cargo@v1
with:
command: test
args: --locked --test system_wide_config -- --ignored
documentation:
name: Documentation
runs-on: ubuntu-20.04

View File

@@ -1,45 +1,21 @@
# v0.22.1
## Bugfixes
- Bring back pre-processing of ANSI escape characters to so that some common `bat` use cases starts working again. See #2308 (@Enselic)
# v0.22.0
# unreleased
## Features
- Make the default macOS theme depend on Dark Mode. See #2197, #1746 (@Enselic)
- Support for separate system and user config files. See #668 (@patrickpichler)
## Bugfixes
- Prevent fork nightmare with `PAGER=batcat`. See #2235 (@johnmatthiggins)
- Make `--no-paging`/`-P` override `--paging=...` if passed as a later arg, see #2201 (@themkat)
- `--map-syntax` and `--ignored-suffix` now works together, see #2093 (@czzrr)
- Strips byte order mark from output when in non-loop-through mode. See #1922 (@dag-h)
## Other
- Relaxed glibc requirements on amd64, see #2106 and #2194 (@sharkdp)
- Improved fish completions. See #2275 (@zgracem)
- Stop pre-processing ANSI escape characters. Syntax highlighting on ANSI escaped input is not supported. See #2185 and #2189 (@Enselic)
## Syntaxes
- NSE (Nmap Scripting Engine) is mapped to Lua, see #2151 (@Cre3per)
- Correctly color `fstab` dump and pass fields, see #2246 (@yuvalmo)
- Update `Command Help` syntax, see #2255
- `Julia`: Fix syntax highlighting for function name starting with `struct`, see #2230
- Minor update to `LiveScript`, see #2291
- Associate `.mts` and `.cts` files with the `TypeScript` syntax. See #2236 (@kidonng)
- Fish history is mapped to YAML. See #2237 (@kidonng)
## Themes
## `bat` as a library
- Make `bat::PrettyPrinter::syntaxes()` iterate over new `bat::Syntax` struct instead of `&syntect::parsing::SyntaxReference`. See #2222 (@Enselic)
- Clear highlights after printing, see #1919 and #1920 (@rhysd)
# v0.21.0

173
Cargo.lock generated
View File

@@ -74,7 +74,7 @@ checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd"
[[package]]
name = "bat"
version = "0.22.1"
version = "0.21.0"
dependencies = [
"ansi_colours",
"ansi_term",
@@ -98,6 +98,7 @@ dependencies = [
"path_abs",
"predicates",
"regex",
"rlua",
"semver",
"serde",
"serde_yaml",
@@ -193,28 +194,18 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "3.2.20"
version = "2.34.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23b71c3ce99b7611011217b366d923f1d0a7e07a92bb2dbf1e84508c673ca3bd"
checksum = "a0610544180c38b88101fecf2dd634b174a62eef6946f84dfc6a7127512b381c"
dependencies = [
"ansi_term",
"atty",
"bitflags",
"clap_lex",
"indexmap",
"once_cell",
"strsim",
"termcolor",
"terminal_size",
"term_size",
"textwrap",
]
[[package]]
name = "clap_lex"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
dependencies = [
"os_str_bytes",
"unicode-width",
"vec_map",
]
[[package]]
@@ -231,13 +222,14 @@ dependencies = [
[[package]]
name = "console"
version = "0.15.1"
version = "0.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "89eab4d20ce20cea182308bca13088fecea9c05f6776cf287205d41a0ed3c847"
checksum = "a28b32d32ca44b70c3e4acd7db1babf555fa026e385fb95f18028f88848b3c31"
dependencies = [
"encode_unicode",
"libc",
"once_cell",
"regex",
"terminal_size",
"unicode-width",
"winapi",
@@ -391,11 +383,13 @@ dependencies = [
[[package]]
name = "flate2"
version = "1.0.24"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f82b0f4c27ad9f8bfd1f3208d882da2b09c301bc1c828fd3a00d0216d2fbbff6"
checksum = "b39522e96686d38f4bc984b9198e3a0613264abaebaff2c5c918bfa6b6da09af"
dependencies = [
"cfg-if",
"crc32fast",
"libc",
"miniz_oxide",
]
@@ -459,9 +453,9 @@ dependencies = [
[[package]]
name = "git2"
version = "0.15.0"
version = "0.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2994bee4a3a6a51eb90c218523be382fd7ea09b16380b9312e9dbe955ff7c7d1"
checksum = "3826a6e0e2215d7a41c2bfc7c9244123969273f3476b939a226aac0ab56e9e3c"
dependencies = [
"bitflags",
"libc",
@@ -478,9 +472,9 @@ checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574"
[[package]]
name = "globset"
version = "0.4.9"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0a1e17342619edbc21a964c2afbeb6c820c6a2560032872f397bb97ea127bd0a"
checksum = "10463d9ff00a2a068db14231982f5132edebad0d7660cd956a1c30292dbcbfbd"
dependencies = [
"aho-corasick",
"bstr",
@@ -595,9 +589,9 @@ checksum = "5916d2ae698f6de9bfb891ad7a8d65c09d232dc58cc4ac433c7da3b2fd84bc2b"
[[package]]
name = "libgit2-sys"
version = "0.14.0+1.5.0"
version = "0.13.2+1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47a00859c70c8a4f7218e6d1cc32875c4b55f6799445b842b0d8ed5e4c3d959b"
checksum = "3a42de9a51a5c12e00fc0e4ca6bc2ea43582fc6418488e8f615e905d886f258b"
dependencies = [
"cc",
"libc",
@@ -673,9 +667,9 @@ dependencies = [
[[package]]
name = "nix"
version = "0.24.2"
version = "0.24.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "195cdbc1741b8134346d515b3a56a1c94b0912758009cfd53f99ea0f57b065fc"
checksum = "8f17df307904acd05aa8e32e97bb20f2a0df1728bbc2d771ae8f9a90463441e9"
dependencies = [
"bitflags",
"cfg-if",
@@ -699,9 +693,9 @@ dependencies = [
[[package]]
name = "once_cell"
version = "1.13.1"
version = "1.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "074864da206b4973b84eb91683020dbefd6a8c3f0f38e054d93954e891935e4e"
checksum = "87f3e037eac156d1775da914196f0f37741a274155e34a0b7e427c35d2a2ecb9"
[[package]]
name = "onig"
@@ -725,12 +719,6 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "os_str_bytes"
version = "6.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ff7415e9ae3fff1225851df9e0d9e4e5479f947619774677a63572e55e80eff"
[[package]]
name = "parking_lot"
version = "0.11.2"
@@ -853,11 +841,11 @@ checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
[[package]]
name = "proc-macro2"
version = "1.0.39"
version = "1.0.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f"
checksum = "c7342d5883fbccae1cc37a2353b09c87c9b0f3afd73f5fb9bba687a1f733b029"
dependencies = [
"unicode-ident",
"unicode-xid",
]
[[package]]
@@ -890,9 +878,9 @@ dependencies = [
[[package]]
name = "regex"
version = "1.6.0"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b"
checksum = "1a11647b6b25ff05a515cb92c365cec08801e83423a235b51e231e1808747286"
dependencies = [
"aho-corasick",
"memchr",
@@ -907,9 +895,9 @@ checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"
[[package]]
name = "regex-syntax"
version = "0.6.27"
version = "0.6.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244"
checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b"
[[package]]
name = "remove_dir_all"
@@ -929,6 +917,30 @@ dependencies = [
"bytemuck",
]
[[package]]
name = "rlua"
version = "0.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "627ae78424400009e889c43b0c188d0b7af3fe7301b68c03d9cfacb29115408a"
dependencies = [
"bitflags",
"bstr",
"libc",
"num-traits",
"rlua-lua54-sys",
]
[[package]]
name = "rlua-lua54-sys"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4e1fdfc6a5f7acfa1b1fe26c5076b54f5ebd6818b5982460c39844c8b859370"
dependencies = [
"cc",
"libc",
"pkg-config",
]
[[package]]
name = "rustversion"
version = "1.0.6"
@@ -964,24 +976,24 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"
[[package]]
name = "semver"
version = "1.0.13"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93f6841e709003d68bb2deee8c343572bf446003ec20a583e76f7b15cebf3711"
checksum = "d65bd28f48be7196d222d95b9243287f48d27aca604e08497513019ff0502cc4"
[[package]]
name = "serde"
version = "1.0.144"
version = "1.0.136"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f747710de3dcd43b88c9168773254e809d8ddbdf9653b84e2554ab219f17860"
checksum = "ce31e24b01e1e524df96f1c2fdd054405f8d7376249a5110886fb4b658484789"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.144"
version = "1.0.136"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94ed3a816fb1d101812f83e789f888322c34e291f894f19590dc310963e87a00"
checksum = "08597e7152fcd306f41838ed3e37be9eaeed2b61c42e2117266a554fab4662f9"
dependencies = [
"proc-macro2",
"quote",
@@ -1001,9 +1013,9 @@ dependencies = [
[[package]]
name = "serde_yaml"
version = "0.8.24"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707d15895415db6628332b737c838b88c598522e4dc70647e59b72312924aebc"
checksum = "a4a521f2940385c165a24ee286aa8599633d162077a54bdcae2a6fd5a7bfa7a0"
dependencies = [
"indexmap",
"ryu",
@@ -1061,19 +1073,19 @@ checksum = "8207e78455ffdf55661170876f88daf85356e4edd54e0a3dbc79586ca1e50cbe"
[[package]]
name = "strsim"
version = "0.10.0"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a"
[[package]]
name = "syn"
version = "1.0.95"
version = "1.0.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbaf6116ab8924f39d52792136fb74fd60a80194cf1b1c6ffa6453eef1c3f942"
checksum = "a684ac3dcd8913827e18cd09a68384ee66c1de24157e3c556c9ab16d85695fb7"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
"unicode-xid",
]
[[package]]
@@ -1124,6 +1136,16 @@ dependencies = [
"winapi",
]
[[package]]
name = "term_size"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e4129646ca0ed8f45d09b929036bafad5377103edd06e50bf574b353d2b08d9"
dependencies = [
"libc",
"winapi",
]
[[package]]
name = "termcolor"
version = "1.1.2"
@@ -1151,27 +1173,28 @@ checksum = "13a4ec180a2de59b57434704ccfad967f789b12737738798fa08798cd5824c16"
[[package]]
name = "textwrap"
version = "0.15.0"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb"
checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060"
dependencies = [
"terminal_size",
"term_size",
"unicode-width",
]
[[package]]
name = "thiserror"
version = "1.0.33"
version = "1.0.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d0a539a918745651435ac7db7a18761589a94cd7e94cd56999f828bf73c8a57"
checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.33"
version = "1.0.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c251e90f708e16c49a16f4917dc2131e75222b72edfa9cb7f7c58ae56aae0c09"
checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a"
dependencies = [
"proc-macro2",
"quote",
@@ -1209,12 +1232,6 @@ version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a01404663e3db436ed2746d9fefef640d868edae3cceb81c3b8d5732fda678f"
[[package]]
name = "unicode-ident"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee"
[[package]]
name = "unicode-normalization"
version = "0.1.19"
@@ -1230,6 +1247,12 @@ version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ed742d4ea2bd1176e236172c8429aaf54486e7ac098db29ffe6529e0ce50973"
[[package]]
name = "unicode-xid"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3"
[[package]]
name = "url"
version = "2.2.2"
@@ -1248,6 +1271,12 @@ version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.4"
@@ -1282,9 +1311,9 @@ checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
[[package]]
name = "wild"
version = "2.1.0"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b116685a6be0c52f5a103334cbff26db643826c7b3735fc0a3ba9871310a74"
checksum = "035793abb854745033f01a07647a79831eba29ec0be377205f2a25b0aa830020"
dependencies = [
"glob",
]

View File

@@ -6,7 +6,7 @@ homepage = "https://github.com/sharkdp/bat"
license = "MIT/Apache-2.0"
name = "bat"
repository = "https://github.com/sharkdp/bat"
version = "0.22.1"
version = "0.21.0"
exclude = ["assets/syntaxes/*", "assets/themes/*"]
build = "build.rs"
edition = '2018'
@@ -30,6 +30,7 @@ minimal-application = [
"paging",
"regex-onig",
"wild",
"rlua"
]
git = ["git2"] # Support indicating git modifications
paging = ["shell-words", "grep-cli"] # Support applying a pager on the output
@@ -44,11 +45,11 @@ atty = { version = "0.2.14", optional = true }
ansi_term = "^0.12.1"
ansi_colours = "^1.1"
bincode = "1.0"
console = "0.15.1"
console = "0.15.0"
flate2 = "1.0"
once_cell = "1.13"
once_cell = "1.10"
thiserror = "1.0"
wild = { version = "2.1", optional = true }
wild = { version = "2.0", optional = true }
content_inspector = "0.2.4"
encoding = "0.2"
shell-words = { version = "1.1.0", optional = true }
@@ -62,12 +63,13 @@ clircle = "0.3"
bugreport = { version = "0.5.0", optional = true }
dirs-next = { version = "2.0.0", optional = true }
grep-cli = { version = "0.1.6", optional = true }
regex = { version = "1.6.0", optional = true }
regex = { version = "1.5.5", optional = true }
walkdir = { version = "2.0", optional = true }
bytesize = { version = "1.1.0" }
rlua = { version = "0.19", optional = true }
[dependencies.git2]
version = "0.15"
version = "0.14"
optional = true
default-features = false
@@ -77,10 +79,10 @@ default-features = false
features = ["parsing"]
[dependencies.clap]
version = "3.2.20"
version = "2.34"
optional = true
default-features = false
features = ["std", "suggestions", "color", "wrap_help", "cargo"]
features = ["suggestions", "color", "wrap_help"]
[dev-dependencies]
assert_cmd = "2.0.4"
@@ -90,10 +92,10 @@ wait-timeout = "0.2.0"
tempfile = "3.3.0"
[target.'cfg(unix)'.dev-dependencies]
nix = { version = "0.24.2", default-features = false, features = ["term"] }
nix = { version = "0.24.1", default-features = false, features = ["term"] }
[build-dependencies]
clap = { version = "3.2.20", optional = true }
clap = { version = "2.34", optional = true }
[profile.release]
lto = true

View File

@@ -418,7 +418,7 @@ 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.60.0 or
If you want to build `bat` from source, you need Rust 1.51 or
higher. You can then use `cargo` to build everything:
```bash
@@ -639,10 +639,6 @@ A default configuration file can be created with the `--generate-config-file` op
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.

View File

@@ -1,219 +1,78 @@
# Fish Shell Completions
# Copy or symlink to $XDG_CONFIG_HOME/fish/completions/{{PROJECT_EXECUTABLE}}.fish
# ($XDG_CONFIG_HOME is usually set to ~/.config)
# Place or symlink to $XDG_CONFIG_HOME/fish/completions/{{PROJECT_EXECUTABLE}}.fish ($XDG_CONFIG_HOME is usually set to ~/.config)
# `bat` is `batcat` on Debian and Ubuntu
set bat {{PROJECT_EXECUTABLE}}
# Helper function:
function __{{PROJECT_EXECUTABLE}}_autocomplete_languages --description "A helper function used by "(status filename)
{{PROJECT_EXECUTABLE}} --list-languages | awk -F':' '
{
lang=$1
split($2, exts, ",")
# Helper functions:
function __bat_complete_files -a token
# Cheat to complete files by calling `complete -C` on a fake command name,
# like `__fish_complete_directories` does.
set -l fake_command aaabccccdeeeeefffffffffgghhhhhhiiiii
complete -C"$fake_command $token"
for (i in exts) {
ext=exts[i]
if (ext !~ /[A-Z].*/ && ext !~ /^\..*rc$/) {
print ext"\t"lang
}
}
}
' | sort
end
function __bat_complete_one_language -a comp
command $bat --list-languages | string split -f1 : | string match -e "$comp"
end
function __bat_complete_list_languages
for spec in (command $bat --list-languages)
set -l name (string split -f1 : $spec)
for ext in (string split -f2 : $spec | string split ,)
test -n "$ext"; or continue
string match -rq '[/*]' $ext; and continue
printf "%s\t%s\n" $ext $name
end
printf "%s\t\n" $name
end
end
function __bat_complete_map_syntax
set -l token (commandline -ct)
if string match -qr '(?<glob>.+):(?<syntax>.*)' -- $token
# If token ends with a colon, complete with the list of language names.
set -f comps $glob:(__bat_complete_one_language $syntax)
else if string match -qr '\*' -- $token
# If token contains a globbing character (`*`), complete only possible
# globs in the current directory
set -f comps (__bat_complete_files $token | string match -er '[*]'):
else
# Complete files (and globs).
set -f comps (__bat_complete_files $token | string match -erv '/$'):
end
if set -q comps[1]
printf "%s\t\n" $comps
end
end
function __bat_cache_subcommand
__fish_seen_subcommand_from cache
end
# Returns true if no exclusive arguments seen.
function __bat_no_excl_args
not __bat_cache_subcommand; and not __fish_seen_argument \
-s h -l help \
-s V -l version \
-l acknowledgements \
-l config-dir -l config-file \
-l diagnostic \
-l list-languages -l list-themes
end
# Returns true if the 'cache' subcommand is seen without any exclusive arguments.
function __bat_cache_no_excl
__bat_cache_subcommand; and not __fish_seen_argument \
-s h -l help \
-l acknowledgements -l build -l clear
end
function __bat_style_opts
set -l style_opts \
"default,recommended components" \
"auto,same as 'default' unless piped" \
"full,all components" \
"plain,no components" \
"changes,Git change markers" \
"header,alias for header-filename" \
"header-filename,filename above content" \
"header-filesize,filesize above content" \
"grid,lines b/w sidebar/header/content" \
"numbers,line numbers in sidebar" \
"rule,separate files" \
"snip,separate ranges"
string replace , \t $style_opts
end
# Use option argument descriptions to indicate which is the default, saving
# horizontal space and making sure the option description isn't truncated.
set -l color_opts '
auto\tdefault
never\t
always\t
'
set -l decorations_opts $color_opts
set -l paging_opts $color_opts
# Include some examples so we can indicate the default.
set -l pager_opts '
less\tdefault
less\ -FR\t
more\t
vimpager\t
'
set -l italic_text_opts '
always\t
never\tdefault
'
set -l wrap_opts '
auto\tdefault
never\t
character\t
'
# While --tabs theoretically takes any number, most people should be OK with these.
# Specifying a list lets us explain what 0 does.
set -l tabs_opts '
0\tpass\ tabs\ through\ directly
1\t
2\t
4\t
8\t
'
# Completions:
complete -c $bat -l acknowledgements -d "Print acknowledgements" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -l color -xka "auto never always" -d "Specify when to use colored output (default: auto)" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l color -x -a "$color_opts" -d "When to use colored output" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l config-dir -d "Display location of '{{PROJECT_EXECUTABLE}}' configuration directory" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l config-dir -f -d "Display location of configuration directory" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -l config-file -d "Display location of '{{PROJECT_EXECUTABLE}}' configuration file" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l config-file -f -d "Display location of configuration file" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -l decorations -xka "auto never always" -d "Specify when to use the decorations specified with '--style' (default: auto)" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l decorations -x -a "$decorations_opts" -d "When to use --style decorations" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -s h -l help -d "Print help message" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l diagnostic -d "Print diagnostic info for bug reports" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -s H -l highlight-line -x -d "<N> Highlight the N-th line with a different background color" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s d -l diff -d "Only show lines with Git changes" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l italic-text -xka "always never" -d "Specify when to use ANSI sequences for italic text (default: never)" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l diff-context -x -d "Show N context lines around Git changes" -n "__fish_seen_argument -s d -l diff"
complete -c {{PROJECT_EXECUTABLE}} -s l -l language -d "Set the language for syntax highlighting" -n "not __fish_seen_subcommand_from cache" -xa "(__{{PROJECT_EXECUTABLE}}_autocomplete_languages)"
complete -c $bat -l file-name -x -d "Specify the display name" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -s r -l line-range -x -d "<N:M> Only print the specified range of lines for each file" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s f -l force-colorization -d "Force color and decorations" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l list-languages -d "Display list of supported languages for syntax highlighting" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s h -d "Print a concise overview" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -l list-themes -d "Display a list of supported themes for syntax highlighting" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l help -f -d "Print all help information" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -s m -l map-syntax -x -d "<from:to> Map a file extension or file name to an existing syntax" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s H -l highlight-line -x -d "Highlight line(s) N[:M]" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -s n -l number -d "Only show line numbers, no other decorations. Alias for '--style=numbers'" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l ignored-suffix -x -d "Ignore extension" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l pager -x -d "<command> Specify which pager program to use (default: less)" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l italic-text -x -a "$italic_text_opts" -d "When to use italic text in the output" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l paging -xka "auto never always" -d "Specify when to use the pager (default: auto)" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s l -l language -x -k -a "(__bat_complete_list_languages)" -d "Set the syntax highlighting language" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -s p -l plain -d "Only show plain style, no decorations. Alias for '--style=plain'" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s r -l line-range -x -d "Only print lines [M]:[N] (either optional)" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -s P -d "Disable paging. Alias for '--paging=never'" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l list-languages -f -d "List syntax highlighting languages" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -s A -l show-all -d "Show non-printable characters like space/tab/newline" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l list-themes -f -d "List syntax highlighting themes" -n __fish_is_first_arg
complete -c {{PROJECT_EXECUTABLE}} -l style -xka "default auto full plain changes header header-filename header-filesize grid rule numbers snip" -d "Comma-separated list of style elements or presets to display with file contents" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s m -l map-syntax -x -a "(__bat_complete_map_syntax)" -d "Map <glob pattern>:<language syntax>" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l tabs -x -d "<T> Set the tab width to T spaces (width of 0 passes tabs through directly)" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s n -l number -d "Only show line numbers, no other decorations" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l terminal-width -x -d "<width> Explicitly set terminal width; Prefix with '+' or '-' to offset (default width is auto determined)" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l pager -x -a "$pager_opts" -d "Which pager to use" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l theme -xka "({{PROJECT_EXECUTABLE}} --list-themes | cat)" -d "Set the theme for syntax highlighting" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l paging -x -a "$paging_opts" -d "When to use the pager" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -s u -l unbuffered -d "POSIX-compliant unbuffered output. Option is ignored" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -s p -l plain -d "Disable decorations" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -s V -l version -d "Show version information" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -o pp -d "Disable decorations and paging" -n __bat_no_excl_args
complete -c $bat -s P -d "Disable paging" -n __bat_no_excl_args
complete -c $bat -s A -l show-all -d "Show non-printable characters" -n __bat_no_excl_args
complete -c $bat -l style -x -k -a "(__fish_complete_list , __bat_style_opts)" -d "Specify which non-content elements to display" -n __bat_no_excl_args
complete -c $bat -l tabs -x -a "$tabs_opts" -d "Set tab width" -n __bat_no_excl_args
complete -c $bat -l terminal-width -x -d "Set terminal <width>, +<offset>, or -<offset>" -n __bat_no_excl_args
complete -c $bat -l theme -x -a "(command $bat --list-themes | command cat)" -d "Set the syntax highlighting theme" -n __bat_no_excl_args
complete -c $bat -s V -l version -f -d "Show version information" -n __fish_is_first_arg
complete -c $bat -l wrap -x -a "$wrap_opts" -d "Text-wrapping mode" -n __bat_no_excl_args
complete -c {{PROJECT_EXECUTABLE}} -l wrap -xka "auto never character" -d "<mode> Specify the text-wrapping mode (default: auto)" -n "not __fish_seen_subcommand_from cache"
# Sub-command 'cache' completions
complete -c $bat -a cache -d "Modify the syntax/language definition cache" -n __fish_use_subcommand
complete -c {{PROJECT_EXECUTABLE}} -a "cache" -d "Modify the syntax/language definition cache" -n "not __fish_seen_subcommand_from cache"
complete -c $bat -l build -f -d "Parse new definitions into cache" -n __bat_cache_no_excl
complete -c {{PROJECT_EXECUTABLE}} -l build -f -d "Parse syntaxes/language definitions into cache" -n "__fish_seen_subcommand_from cache"
complete -c $bat -l clear -f -d "Reset definitions to defaults" -n __bat_cache_no_excl
complete -c $bat -l blank -f -d "Create new data instead of appending" -n "__bat_cache_subcommand; and not __fish_seen_argument -l clear"
complete -c $bat -l source -x -a "(__fish_complete_directories)" -d "Load syntaxes and themes from DIR" -n "__bat_cache_subcommand; and not __fish_seen_argument -l clear"
complete -c $bat -l target -x -a "(__fish_complete_directories)" -d "Store cache in DIR" -n __bat_cache_subcommand
complete -c $bat -l acknowledgements -d "Build acknowledgements.bin" -n __bat_cache_no_excl
complete -c $bat -s h -d "Print a concise overview of $bat-cache help" -n __bat_cache_no_excl
complete -c $bat -l help -f -d "Print all $bat-cache help" -n __bat_cache_no_excl
# vim:ft=fish
complete -c {{PROJECT_EXECUTABLE}} -l clear -f -d "Reset syntaxes/language definitions to default settings" -n "__fish_seen_subcommand_from cache"

View File

@@ -29,7 +29,7 @@ control the width of the tab\-placeholders.
.IP
Only show plain style, no decorations. This is an alias for
\&'\-\-style=plain'. When '\-p' is used twice ('\-pp'), it also disables
automatic paging (alias for '\-\-style=plain \fB\-\-paging\fR=\fI\,never\/\fR').
automatic paging (alias for '\-\-style=plain \fB\-\-pager\fR=\fI\,never\/\fR').
.HP
\fB\-l\fR, \fB\-\-language\fR <language>
.IP

BIN
assets/syntaxes.bin vendored

Binary file not shown.

View File

@@ -95,7 +95,7 @@ contexts:
fstab_dump:
- include: comment
- match: '\s*[012]\s*'
- match: '\s*[01]\s*'
comment: dump field
scope: constant.numeric
set: fstab_pass
@@ -107,7 +107,7 @@ contexts:
fstab_pass:
- include: comment
- match: '\s*[012]\s*'
- match: '\s*[01]\s*'
comment: pass field
scope: constant.numeric
set: expected_eol

View File

@@ -4,8 +4,6 @@
name: TypeScript
file_extensions:
- ts
- mts
- cts
scope: source.ts
contexts:
main:

View File

@@ -7,15 +7,8 @@ scope: text.log
variables:
ipv4_part: (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)
hours_minutes_seconds: (?:[01]\d|2[0-3]):(?:[0-5]\d):(?:[0-5]\d)
error: \b(?i:fail(?:ure|ed)?|error|exception|fatal|critical)\b
warning: \b(?i:warn(?:ing)?)\b
info: \b(?i:info)\b
debug: \b(?i:debug)\b
contexts:
main:
- include: log_level_lines
- include: main_without_log_level_line
main_without_log_level_line:
- match: (\w+)(=)
captures:
1: variable.parameter.log
@@ -32,58 +25,16 @@ contexts:
- include: dates
- include: ip_addresses
- include: numbers
- include: log_levels
- match: \b(?i:fail(?:ure|ed)?|error|exception)\b
scope: markup.error.log
- match: \b(?i:warn(?:ing)?)\b
scope: markup.warning.log
- match: \b(?i:debug)\b
scope: markup.info.log
#- include: scope:text.html.markdown#autolink-inet
- match: \b\w+:/{2,3}
scope: markup.underline.link.scheme.log
push: url-host
log_level_lines:
- match: ^(?=.*{{error}})
push:
- error_line
- main_pop_at_eol
- match: ^(?=.*{{warning}})
push:
- warning_line
- main_pop_at_eol
- match: ^(?=.*{{info}})
push:
- info_line
- main_pop_at_eol
- match: ^(?=.*{{debug}})
push:
- debug_line
- main_pop_at_eol
log_levels:
- match: '{{error}}'
scope: markup.error.log
- match: '{{warning}}'
scope: markup.warning.log
- match: '{{info}}'
scope: markup.info.log
- match: '{{debug}}'
scope: markup.info.log
error_line:
- meta_scope: meta.annotation.error-line.log
- include: immediately_pop
warning_line:
- meta_scope: meta.annotation.warning-line.log
- include: immediately_pop
info_line:
- meta_scope: meta.annotation.info-line.log
- include: immediately_pop
debug_line:
- meta_scope: meta.annotation.debug-line.log
- include: immediately_pop
immediately_pop:
- match: ''
pop: true
pop_at_eol:
- match: $
pop: true
main_pop_at_eol:
- include: main_without_log_level_line
- include: pop_at_eol
dates:
- match: \b\d{4}-\d{2}-\d{2}(?=\b|T)
scope: meta.date.log meta.number.integer.decimal.log constant.numeric.value.log
@@ -98,12 +49,14 @@ contexts:
scope: meta.time.log meta.number.integer.decimal.log constant.numeric.value.log
captures:
1: punctuation.separator.decimal.log
- include: immediately_pop
- match: ''
pop: true
maybe_date_time_separator:
- match: T(?={{hours_minutes_seconds}})
scope: meta.date.log meta.time.log keyword.other.log
set: time
- include: immediately_pop
- match: ''
pop: true
ip_addresses:
- match: \b(?=(?:{{ipv4_part}}\.){3}{{ipv4_part}}\b)
push:
@@ -112,7 +65,8 @@ contexts:
scope: constant.numeric.value.log
- match: \.
scope: punctuation.separator.sequence.log
- include: immediately_pop
- match: ''
pop: true
- match: (?=(?:\h{0,4}:){2,6}\h{1,4}\b)
push:
- meta_scope: meta.ipaddress.v6.log meta.number.integer.hexadecimal.log
@@ -120,7 +74,8 @@ contexts:
scope: constant.numeric.value.log
- match: ':'
scope: punctuation.separator.sequence.log
- include: immediately_pop
- match: ''
pop: true
numbers:
- match: \b(0x)(\h+)(?:(\.)(\h+))?\b
scope: meta.number.float.hexadecimal.log
@@ -172,7 +127,8 @@ contexts:
pop: true
- match: '[^?!.,:*_~\s<&()%]+|\S'
scope: markup.underline.link.path.log
- include: immediately_pop
- match: ''
pop: true
double_quoted_string:
- meta_scope: string.quoted.double.log
- match: \\"

View File

@@ -366,7 +366,7 @@ ansible-galaxy install aeimer.install_bat
### From source
`bat` をソースからビルドしたいならば、Rust 1.60.0 以上の環境が必要です。
`bat` をソースからビルドしたいならば、Rust 1.51 以上の環境が必要です。
`cargo` を使用してビルドすることができます:
```bash

View File

@@ -416,7 +416,7 @@ scoop install bat
### 소스에서
`bat`의 소스를 빌드하기 위해서는, Rust 1.60.0 이상이 필요합니다.
`bat`의 소스를 빌드하기 위해서는, Rust 1.51 이상이 필요합니다.
`cargo`를 이용해 전부 빌드할 수 있습니다:
```bash

View File

@@ -344,7 +344,7 @@ ansible-galaxy install aeimer.install_bat
### Из исходников
Если вы желаете установить `bat` из исходников, вам понадобится Rust 1.60.0 или выше. После этого используйте `cargo`, чтобы все скомпилировать:
Если вы желаете установить `bat` из исходников, вам понадобится Rust 1.51 или выше. После этого используйте `cargo`, чтобы все скомпилировать:
```bash
cargo install --locked bat

View File

@@ -372,7 +372,7 @@ scoop install bat
### 从源码编译
如果你想要自己构建`bat`那么你需要安装有高于1.58.0版本的 Rust。
如果你想要自己构建`bat`那么你需要安装有高于1.51版本的 Rust。
使用以下命令编译。
@@ -550,7 +550,7 @@ bat --generate-config-file
# 在终端中以斜体输出文本(不是所有终端都支持)
--italic-text=always
# 使用 C++ 语法来给 Arduino 的 .ino 文件提供高亮
# 使用 C++ 语法来给 Ardiuno 的 .ino 文件提供高亮
--map-syntax "*.ino:C++"
```

View File

@@ -4,17 +4,17 @@ The following table tries to give an overview *from `bat`s perspective*, i.e. we
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](http://pygments.org/) | [highlight](http://www.andre-simon.de/doku/highlight/highlight.php) | [ccat](https://github.com/jingweno/ccat) | [source-highlight](https://www.gnu.org/software/src-highlite/) | [hicat](https://github.com/rstacruz/hicat) | [coderay](https://github.com/rubychan/coderay) | [rouge](https://github.com/jneen/rouge) | [clp](https://github.com/jpe90/clp) |
|----------------------------------------------|---------------------------------------------------------------------|----------------------------------|---------------------------------------------------------------------|------------------------------------------|----------------------------------------------------------------|-----------------------------------------------------|-----------------------------------------------------|-----------------------------------------------------|-----------------------------------------------------|
| Drop-in `cat` replacement | :heavy_check_mark: [*](https://github.com/sharkdp/bat/issues/134) | :x: | :x: | (:heavy_check_mark:) | :x: | :x: [*](https://github.com/rstacruz/hicat/issues/6) | :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: | (:heavy_check_mark:) | (:heavy_check_mark:) | :x: | (:heavy_check_mark:) | :x: | :x: | :x: | :heavy_check_mark: |
| Advanced highlighting (e.g. nested syntaxes) | :heavy_check_mark: | :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 |
| | bat | [pygments](http://pygments.org/) | [highlight](http://www.andre-simon.de/doku/highlight/highlight.php) | [ccat](https://github.com/jingweno/ccat) | [source-highlight](https://www.gnu.org/software/src-highlite/) | [hicat](https://github.com/rstacruz/hicat) | [coderay](https://github.com/rubychan/coderay) | [rouge](https://github.com/jneen/rouge) |
|----------------------------------------------|---------------------------------------------------------------------|----------------------------------|---------------------------------------------------------------------|------------------------------------------|----------------------------------------------------------------|-----------------------------------------------------|-----------------------------------------------------|-----------------------------------------------------|
| Drop-in `cat` replacement | :heavy_check_mark: [*](https://github.com/sharkdp/bat/issues/134) | :x: | :x: | (:heavy_check_mark:) | :x: | :x: [*](https://github.com/rstacruz/hicat/issues/6) | :x: | :x: |
| Git integration | :heavy_check_mark: | :x: | :x: | :x: | :x: | :x: | :x: | :x: |
| Automatic paging | :heavy_check_mark: | :x: | :x: | :x: | :x: | :heavy_check_mark: | :x: | :x: |
| Languages (circa) | 150 | 300 | 200 | 7 | 80 | 130 | 30 | 130 |
| Extensible (languages, themes) | :heavy_check_mark: | (:heavy_check_mark:) | (:heavy_check_mark:) | :x: | (:heavy_check_mark:) | :x: | :x: | :x: |
| Advanced highlighting (e.g. nested syntaxes) | :heavy_check_mark: | :heavy_check_mark: | (:heavy_check_mark:) ? | :x: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: | :heavy_check_mark: |
| Execution time [ms] (`jquery-3.3.1.js`) | 624 | 789 | 400 | 80 | 300 | 316 | 157 | 695 |
| Execution time [ms] (`miniz.c`) | 66 | 656 | 26 | 8 | 53 | 141 | 75 | 254 |
| Execution time [ms] (370 kB XML file) | 238 | 487 | 129 | 111 | 110 | 339 | 147 | 359 |
If you think that some entries in this table are outdated or wrong, please open a ticket or pull
request.
@@ -49,7 +49,6 @@ 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" \
@@ -61,5 +60,4 @@ hyperfine --warmup 3 \
"$cmd_hicat" \
"$cmd_coderay" \
"$cmd_rouge" \
"$cmd_clp" \
```

View File

@@ -1,4 +1,4 @@
/// A simple program that lists all supported syntaxes and themes.
/// A simple program that prints its own source code using the bat library
use bat::PrettyPrinter;
fn main() {

21
plugins/curl.lua Normal file
View File

@@ -0,0 +1,21 @@
function tempdir()
local stream = assert(io.popen('mktemp --directory'))
local output = stream:read('*all')
stream:close()
return string.gsub(output, "\n", "")
end
function preprocess(path_or_url)
filename_from_url = string.match(path_or_url, '^https?://.*/(.*)$')
if filename_from_url then
local temp_directory = tempdir()
local new_path = temp_directory .. "/" .. filename_from_url
-- TODO: how to prevent shell injection bugs?
os.execute("curl --silent '" .. path_or_url .. "' --output '" .. new_path .. "'")
return new_path
else
return path_or_url
end
end

17
plugins/directories.lua Normal file
View File

@@ -0,0 +1,17 @@
-- https://stackoverflow.com/a/3254007/704831
function is_dir(path)
local f = io.open(path, "r")
local ok, err, code = f:read(1)
f:close()
return code == 21
end
function preprocess(path)
if is_dir(path) then
tmpfile = os.tmpname()
os.execute("ls -alh --color=always '" .. path .. "' > '" .. tmpfile .. "'")
return tmpfile
else
return path
end
end

21
plugins/hexyl.lua Normal file
View File

@@ -0,0 +1,21 @@
-- Note: this plugin depends on the existence of 'inspect' [1] and 'hexyl' [2]
--
-- [1] https://github.com/sharkdp/content_inspector
-- [2] https://github.com/sharkdp/hexyl
function is_binary(path)
local stream = assert(io.popen("inspect '" .. path .. "'"))
local output = stream:read('*all')
stream:close()
return string.find(output, ": binary\n")
end
function preprocess(path)
if is_binary(path) then
tmpfile = os.tmpname()
os.execute("hexyl --length 1024 --no-position --border=none --no-squeezing '" .. path .. "' > '" .. tmpfile .. "'")
return tmpfile
else
return path
end
end

21
plugins/uncompress.lua Normal file
View File

@@ -0,0 +1,21 @@
function tempdir()
local stream = assert(io.popen('mktemp --directory'))
local output = stream:read('*all')
stream:close()
return string.gsub(output, "\n", "")
end
function preprocess(path)
prefix = string.match(path, '^(.*)%.gz$')
if prefix then
local temp_directory = tempdir()
local new_path = temp_directory .. "/" .. prefix
-- TODO: how to prevent shell injection bugs?
os.execute("gunzip < '" .. path .. "' > '" .. new_path .. "'")
return new_path
else
return path
end
end

View File

@@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};
use crate::error::*;
#[derive(Debug, PartialEq, Eq, Default, Serialize, Deserialize)]
#[derive(Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct AssetsMetadata {
bat_version: Option<String>,
creation_time: Option<SystemTime>,

View File

@@ -1,4 +1,3 @@
use std::fmt::Write;
use std::fs::read_to_string;
use std::path::{Path, PathBuf};
@@ -125,7 +124,7 @@ fn append_to_acknowledgements(
relative_path: &str,
license_text: &str,
) {
write!(acknowledgements, "## {}\n\n{}", relative_path, license_text).ok();
acknowledgements.push_str(&format!("## {}\n\n{}", relative_path, license_text));
// Make sure the last char is a newline to not mess up formatting later
if acknowledgements

View File

@@ -1,6 +1,6 @@
use std::collections::HashSet;
use std::env;
use std::path::{Path, PathBuf};
use std::path::Path;
use std::str::FromStr;
use atty::{self, Stream};
@@ -32,7 +32,7 @@ fn is_truecolor_terminal() -> bool {
}
pub struct App {
pub matches: ArgMatches,
pub matches: ArgMatches<'static>,
interactive_output: bool,
}
@@ -49,7 +49,7 @@ impl App {
})
}
fn matches(interactive_output: bool) -> Result<ArgMatches> {
fn matches(interactive_output: bool) -> Result<ArgMatches<'static>> {
let args = if wild::args_os().nth(1) == Some("cache".into())
|| wild::args_os().any(|arg| arg == "--no-config")
{
@@ -79,13 +79,13 @@ impl App {
pub fn config(&self, inputs: &[Input]) -> Result<Config> {
let style_components = self.style_components()?;
let paging_mode = match self.matches.get_one::<String>("paging").map(|s| s.as_str()) {
let paging_mode = match self.matches.value_of("paging") {
Some("always") => PagingMode::Always,
Some("never") => PagingMode::Never,
Some("auto") | None => {
// If we have -pp as an option when in auto mode, the pager should be disabled.
let extra_plain = self.matches.get_count("plain") > 1;
if extra_plain || self.matches.get_flag("no-paging") {
let extra_plain = self.matches.occurrences_of("plain") > 1;
if extra_plain || self.matches.is_present("no-paging") {
PagingMode::Never
} else if inputs.iter().any(Input::is_stdin) {
// If we are reading from stdin, only enable paging if we write to an
@@ -107,13 +107,13 @@ impl App {
let mut syntax_mapping = SyntaxMapping::builtin();
if let Some(values) = self.matches.get_many::<String>("ignored-suffix") {
if let Some(values) = self.matches.values_of("ignored-suffix") {
for suffix in values {
syntax_mapping.insert_ignored_suffix(suffix);
}
}
if let Some(values) = self.matches.get_many::<String>("map-syntax") {
if let Some(values) = self.matches.values_of("map-syntax") {
for from_to in values {
let parts: Vec<_> = from_to.split(':').collect();
@@ -125,43 +125,36 @@ impl App {
}
}
let maybe_term_width = self
.matches
.get_one::<String>("terminal-width")
.and_then(|w| {
if w.starts_with('+') || w.starts_with('-') {
// Treat argument as a delta to the current terminal width
w.parse().ok().map(|delta: i16| {
let old_width: u16 = Term::stdout().size().1;
let new_width: i32 = i32::from(old_width) + i32::from(delta);
let maybe_term_width = self.matches.value_of("terminal-width").and_then(|w| {
if w.starts_with('+') || w.starts_with('-') {
// Treat argument as a delta to the current terminal width
w.parse().ok().map(|delta: i16| {
let old_width: u16 = Term::stdout().size().1;
let new_width: i32 = i32::from(old_width) + i32::from(delta);
if new_width <= 0 {
old_width as usize
} else {
new_width as usize
}
})
} else {
w.parse().ok()
}
});
if new_width <= 0 {
old_width as usize
} else {
new_width as usize
}
})
} else {
w.parse().ok()
}
});
Ok(Config {
true_color: is_truecolor_terminal(),
language: self
.matches
.get_one::<String>("language")
.map(|s| s.as_str())
.or_else(|| {
if self.matches.get_flag("show-all") {
Some("show-nonprintable")
} else {
None
}
}),
show_nonprintable: self.matches.get_flag("show-all"),
language: self.matches.value_of("language").or_else(|| {
if self.matches.is_present("show-all") {
Some("show-nonprintable")
} else {
None
}
}),
show_nonprintable: self.matches.is_present("show-all"),
wrapping_mode: if self.interactive_output || maybe_term_width.is_some() {
match self.matches.get_one::<String>("wrap").map(|s| s.as_str()) {
match self.matches.value_of("wrap") {
Some("character") => WrappingMode::Character,
Some("never") => WrappingMode::NoWrapping(true),
Some("auto") | None => {
@@ -178,8 +171,8 @@ impl App {
// There's no point in wrapping when this is the case.
WrappingMode::NoWrapping(false)
},
colored_output: self.matches.get_flag("force-colorization")
|| match self.matches.get_one::<String>("color").map(|s| s.as_str()) {
colored_output: self.matches.is_present("force-colorization")
|| match self.matches.value_of("color") {
Some("always") => true,
Some("never") => false,
Some("auto") => env::var_os("NO_COLOR").is_none() && self.interactive_output,
@@ -188,16 +181,12 @@ impl App {
paging_mode,
term_width: maybe_term_width.unwrap_or(Term::stdout().size().1 as usize),
loop_through: !(self.interactive_output
|| self.matches.get_one::<String>("color").map(|s| s.as_str()) == Some("always")
|| self
.matches
.get_one::<String>("decorations")
.map(|s| s.as_str())
== Some("always")
|| self.matches.get_flag("force-colorization")),
|| self.matches.value_of("color") == Some("always")
|| self.matches.value_of("decorations") == Some("always")
|| self.matches.is_present("force-colorization")),
tab_width: self
.matches
.get_one::<String>("tabs")
.value_of("tabs")
.map(String::from)
.or_else(|| env::var("BAT_TABS").ok())
.and_then(|t| t.parse().ok())
@@ -210,7 +199,7 @@ impl App {
),
theme: self
.matches
.get_one::<String>("theme")
.value_of("theme")
.map(String::from)
.or_else(|| env::var("BAT_THEME").ok())
.map(|s| {
@@ -221,19 +210,19 @@ impl App {
}
})
.unwrap_or_else(|| String::from(HighlightingAssets::default_theme())),
visible_lines: match self.matches.contains_id("diff") && self.matches.get_flag("diff") {
visible_lines: match self.matches.is_present("diff") {
#[cfg(feature = "git")]
true => VisibleLines::DiffContext(
self.matches
.get_one::<String>("diff-context")
.value_of("diff-context")
.and_then(|t| t.parse().ok())
.unwrap_or(2),
),
_ => VisibleLines::Ranges(
self.matches
.get_many::<String>("line-range")
.map(|vs| vs.map(|s| LineRange::from(s.as_str())).collect())
.values_of("line-range")
.map(|vs| vs.map(LineRange::from).collect())
.transpose()?
.map(LineRanges::from)
.unwrap_or_default(),
@@ -241,47 +230,50 @@ impl App {
},
style_components,
syntax_mapping,
pager: self.matches.get_one::<String>("pager").map(|s| s.as_str()),
use_italic_text: self
.matches
.get_one::<String>("italic-text")
.map(|s| s.as_str())
== Some("always"),
pager: self.matches.value_of("pager"),
use_italic_text: self.matches.value_of("italic-text") == Some("always"),
highlighted_lines: self
.matches
.get_many::<String>("highlight-line")
.map(|ws| ws.map(|s| LineRange::from(s.as_str())).collect())
.values_of("highlight-line")
.map(|ws| ws.map(LineRange::from).collect())
.transpose()?
.map(LineRanges::from)
.map(HighlightedLineRanges)
.unwrap_or_default(),
use_custom_assets: !self.matches.get_flag("no-custom-assets"),
use_custom_assets: !self.matches.is_present("no-custom-assets"),
plugins: self
.matches
.values_of_os("load-plugin")
.unwrap_or_default()
.collect(),
})
}
pub fn inputs(&self) -> Result<Vec<Input>> {
// verify equal length of file-names and input FILEs
match self.matches.values_of("file-name") {
Some(ref filenames)
if self.matches.values_of_os("FILE").is_some()
&& filenames.len() != self.matches.values_of_os("FILE").unwrap().len() =>
{
return Err("Must be one file name per input type.".into());
}
_ => {}
}
let filenames: Option<Vec<&Path>> = self
.matches
.get_many::<PathBuf>("file-name")
.map(|vs| vs.map(|p| p.as_path()).collect::<Vec<_>>());
let files: Option<Vec<&Path>> = self
.matches
.get_many::<PathBuf>("FILE")
.map(|vs| vs.map(|p| p.as_path()).collect::<Vec<_>>());
// verify equal length of file-names and input FILEs
if filenames.is_some()
&& files.is_some()
&& filenames.as_ref().map(|v| v.len()) != files.as_ref().map(|v| v.len())
{
return Err("Must be one file name per input type.".into());
}
.values_of_os("file-name")
.map(|values| values.map(Path::new).collect());
let mut filenames_or_none: Box<dyn Iterator<Item = Option<&Path>>> = match filenames {
Some(filenames) => Box::new(filenames.into_iter().map(Some)),
None => Box::new(std::iter::repeat(None)),
};
let files: Option<Vec<&Path>> = self
.matches
.values_of_os("FILE")
.map(|vs| vs.map(Path::new).collect());
if files.is_none() {
return Ok(vec![new_stdin_input(
filenames_or_none.next().unwrap_or(None),
@@ -307,12 +299,12 @@ impl App {
fn style_components(&self) -> Result<StyleComponents> {
let matches = &self.matches;
let mut styled_components = StyleComponents(
if matches.get_one::<String>("decorations").map(|s| s.as_str()) == Some("never") {
let mut styled_components =
StyleComponents(if matches.value_of("decorations") == Some("never") {
HashSet::new()
} else if matches.get_flag("number") {
} else if matches.is_present("number") {
[StyleComponent::LineNumbers].iter().cloned().collect()
} else if 0 < matches.get_count("plain") {
} else if matches.is_present("plain") {
[StyleComponent::Plain].iter().cloned().collect()
} else {
let env_style_components: Option<Vec<StyleComponent>> = env::var("BAT_STYLE")
@@ -326,7 +318,7 @@ impl App {
.transpose()?;
matches
.get_one::<String>("style")
.value_of("style")
.map(|styles| {
styles
.split(',')
@@ -342,8 +334,7 @@ impl App {
acc.extend(components.iter().cloned());
acc
})
},
);
});
// If `grid` is set, remove `rule` as it is a subset of `grid`, and print a warning.
if styled_components.grid() && styled_components.0.remove(&StyleComponent::Rule) {

View File

@@ -1,10 +1,7 @@
use clap::{
crate_name, crate_version, value_parser, AppSettings, Arg, ArgAction, ArgGroup, ColorChoice,
Command,
};
use clap::{crate_name, crate_version, App as ClapApp, AppSettings, Arg, ArgGroup, SubCommand};
use once_cell::sync::Lazy;
use std::env;
use std::path::{Path, PathBuf};
use std::path::Path;
static VERSION: Lazy<String> = Lazy::new(|| {
#[cfg(feature = "bugreport")]
@@ -19,21 +16,23 @@ static VERSION: Lazy<String> = Lazy::new(|| {
}
});
pub fn build_app(interactive_output: bool) -> Command<'static> {
let color_when = if interactive_output && env::var_os("NO_COLOR").is_none() {
ColorChoice::Auto
pub fn build_app(interactive_output: bool) -> ClapApp<'static, 'static> {
let clap_color_setting = if interactive_output && env::var_os("NO_COLOR").is_none() {
AppSettings::ColoredHelp
} else {
ColorChoice::Never
AppSettings::ColorNever
};
let mut app = Command::new(crate_name!())
let mut app = ClapApp::new(crate_name!())
.version(VERSION.as_str())
.color(color_when)
.global_setting(clap_color_setting)
.global_setting(AppSettings::DeriveDisplayOrder)
.hide_possible_values(true)
.args_conflicts_with_subcommands(true)
.allow_external_subcommands(true)
.disable_help_subcommand(true)
.global_setting(AppSettings::UnifiedHelpMessage)
.global_setting(AppSettings::HidePossibleValuesInHelp)
.setting(AppSettings::ArgsNegateSubcommands)
.setting(AppSettings::AllowExternalSubcommands)
.setting(AppSettings::DisableHelpSubcommand)
.setting(AppSettings::VersionlessSubcommands)
.max_term_width(100)
.about(
"A cat(1) clone with wings.\n\n\
@@ -45,22 +44,20 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
)
.long_about("A cat(1) clone with syntax highlighting and Git integration.")
.arg(
Arg::new("FILE")
Arg::with_name("FILE")
.help("File(s) to print / concatenate. Use '-' for standard input.")
.long_help(
"File(s) to print / concatenate. Use a dash ('-') or no argument at all \
to read from standard input.",
)
.takes_value(true)
.multiple_values(true)
.value_parser(value_parser!(PathBuf)),
.multiple(true)
.empty_values(false),
)
.arg(
Arg::new("show-all")
Arg::with_name("show-all")
.long("show-all")
.alias("show-nonprintable")
.short('A')
.action(ArgAction::SetTrue)
.short("A")
.conflicts_with("language")
.help("Show non-printable characters (space, tab, newline, ..).")
.long_help(
@@ -70,22 +67,22 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("plain")
Arg::with_name("plain")
.overrides_with("plain")
.overrides_with("number")
.short('p')
.short("p")
.long("plain")
.action(ArgAction::Count)
.multiple(true)
.help("Show plain style (alias for '--style=plain').")
.long_help(
"Only show plain style, no decorations. This is an alias for \
'--style=plain'. When '-p' is used twice ('-pp'), it also disables \
automatic paging (alias for '--style=plain --paging=never').",
automatic paging (alias for '--style=plain --pager=never').",
),
)
.arg(
Arg::new("language")
.short('l')
Arg::with_name("language")
.short("l")
.long("language")
.overrides_with("language")
.help("Set the language for syntax highlighting.")
@@ -98,11 +95,12 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
.takes_value(true),
)
.arg(
Arg::new("highlight-line")
Arg::with_name("highlight-line")
.long("highlight-line")
.short('H')
.short("H")
.takes_value(true)
.action(ArgAction::Append)
.number_of_values(1)
.multiple(true)
.value_name("N:M")
.help("Highlight lines N through M.")
.long_help(
@@ -116,12 +114,12 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("file-name")
Arg::with_name("file-name")
.long("file-name")
.takes_value(true)
.action(ArgAction::Append)
.number_of_values(1)
.multiple(true)
.value_name("name")
.value_parser(value_parser!(PathBuf))
.help("Specify the name to display for a file.")
.long_help(
"Specify the name to display for a file. Useful when piping \
@@ -135,11 +133,9 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
{
app = app
.arg(
Arg::new("diff")
Arg::with_name("diff")
.long("diff")
.short('d')
.action(ArgAction::SetTrue)
.conflicts_with("line-range")
.short("d")
.help("Only show lines that have been added/removed/modified.")
.long_help(
"Only show lines that have been added/removed/modified with respect \
@@ -147,20 +143,20 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("diff-context")
Arg::with_name("diff-context")
.long("diff-context")
.overrides_with("diff-context")
.takes_value(true)
.value_name("N")
.value_parser(
|n: &str| {
.validator(
|n| {
n.parse::<usize>()
.map_err(|_| "must be a number")
.map(|_| n.to_owned()) // Convert to Result<String, &str>
.map(|_| ()) // Convert to Result<(), &str>
.map_err(|e| e.to_string())
}, // Convert to Result<(), String>
)
.hide_short_help(true)
.hidden_short_help(true)
.long_help(
"Include N lines of context around added/removed/modified lines when using '--diff'.",
),
@@ -168,16 +164,16 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
}
app = app.arg(
Arg::new("tabs")
Arg::with_name("tabs")
.long("tabs")
.overrides_with("tabs")
.takes_value(true)
.value_name("T")
.value_parser(
|t: &str| {
.validator(
|t| {
t.parse::<u32>()
.map_err(|_t| "must be a number")
.map(|_t| t.to_owned()) // Convert to Result<String, &str>
.map(|_t| ()) // Convert to Result<(), &str>
.map_err(|e| e.to_string())
}, // Convert to Result<(), String>
)
@@ -188,12 +184,12 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("wrap")
Arg::with_name("wrap")
.long("wrap")
.overrides_with("wrap")
.takes_value(true)
.value_name("mode")
.value_parser(["auto", "never", "character"])
.possible_values(&["auto", "never", "character"])
.default_value("auto")
.hide_default_value(true)
.help("Specify the text-wrapping mode (*auto*, never, character).")
@@ -202,21 +198,21 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
control the output width."),
)
.arg(
Arg::new("terminal-width")
Arg::with_name("terminal-width")
.long("terminal-width")
.takes_value(true)
.value_name("width")
.hide_short_help(true)
.hidden_short_help(true)
.allow_hyphen_values(true)
.value_parser(
|t: &str| {
.validator(
|t| {
let is_offset = t.starts_with('+') || t.starts_with('-');
t.parse::<i32>()
.map_err(|_e| "must be an offset or number")
.and_then(|v| if v == 0 && !is_offset {
Err("terminal width cannot be zero")
} else {
Ok(t.to_owned())
Ok(())
})
.map_err(|e| e.to_string())
})
@@ -227,11 +223,10 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("number")
Arg::with_name("number")
.long("number")
.overrides_with("number")
.short('n')
.action(ArgAction::SetTrue)
.short("n")
.help("Show line numbers (alias for '--style=numbers').")
.long_help(
"Only show line numbers, no other decorations. This is an alias for \
@@ -239,12 +234,12 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("color")
Arg::with_name("color")
.long("color")
.overrides_with("color")
.takes_value(true)
.value_name("when")
.value_parser(["auto", "never", "always"])
.possible_values(&["auto", "never", "always"])
.hide_default_value(true)
.default_value("auto")
.help("When to use colors (*auto*, never, always).")
@@ -256,23 +251,23 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("italic-text")
Arg::with_name("italic-text")
.long("italic-text")
.takes_value(true)
.value_name("when")
.value_parser(["always", "never"])
.possible_values(&["always", "never"])
.default_value("never")
.hide_default_value(true)
.help("Use italics in output (always, *never*)")
.long_help("Specify when to use ANSI sequences for italic text in the output. Possible values: always, *never*."),
)
.arg(
Arg::new("decorations")
Arg::with_name("decorations")
.long("decorations")
.overrides_with("decorations")
.takes_value(true)
.value_name("when")
.value_parser(["auto", "never", "always"])
.possible_values(&["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("When to show the decorations (*auto*, never, always).")
@@ -283,26 +278,24 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("force-colorization")
Arg::with_name("force-colorization")
.long("force-colorization")
.short('f')
.action(ArgAction::SetTrue)
.short("f")
.conflicts_with("color")
.conflicts_with("decorations")
.overrides_with("force-colorization")
.hide_short_help(true)
.hidden_short_help(true)
.long_help("Alias for '--decorations=always --color=always'. This is useful \
if the output of bat is piped to another program, but you want \
to keep the colorization/decorations.")
)
.arg(
Arg::new("paging")
Arg::with_name("paging")
.long("paging")
.overrides_with("paging")
.overrides_with("no-paging")
.takes_value(true)
.value_name("when")
.value_parser(["auto", "never", "always"])
.possible_values(&["auto", "never", "always"])
.default_value("auto")
.hide_default_value(true)
.help("Specify when to use the pager, or use `-P` to disable (*auto*, never, always).")
@@ -314,23 +307,22 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("no-paging")
.short('P')
Arg::with_name("no-paging")
.short("P")
.long("no-paging")
.alias("no-pager")
.action(ArgAction::SetTrue)
.overrides_with("no-paging")
.hide(true)
.hide_short_help(true)
.hidden(true)
.hidden_short_help(true)
.help("Alias for '--paging=never'")
)
.arg(
Arg::new("pager")
Arg::with_name("pager")
.long("pager")
.overrides_with("pager")
.takes_value(true)
.value_name("command")
.hide_short_help(true)
.hidden_short_help(true)
.help("Determine which pager to use.")
.long_help(
"Determine which pager is used. This option will override the \
@@ -340,11 +332,12 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("map-syntax")
.short('m')
Arg::with_name("map-syntax")
.short("m")
.long("map-syntax")
.action(ArgAction::Append)
.multiple(true)
.takes_value(true)
.number_of_values(1)
.value_name("glob:syntax")
.help("Use the specified syntax for files matching the glob pattern ('*.cpp:C++').")
.long_help(
@@ -357,18 +350,19 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
.takes_value(true),
)
.arg(
Arg::new("ignored-suffix")
.action(ArgAction::Append)
Arg::with_name("ignored-suffix")
.number_of_values(1)
.multiple(true)
.takes_value(true)
.long("ignored-suffix")
.hide_short_help(true)
.hidden_short_help(true)
.help(
"Ignore extension. For example:\n \
'bat --ignored-suffix \".dev\" my_file.json.dev' will use JSON syntax, and ignore '.dev'"
)
)
.arg(
Arg::new("theme")
Arg::with_name("theme")
.long("theme")
.overrides_with("theme")
.takes_value(true)
@@ -382,25 +376,24 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("list-themes")
Arg::with_name("list-themes")
.long("list-themes")
.action(ArgAction::SetTrue)
.help("Display all supported highlighting themes.")
.long_help("Display a list of supported themes for syntax highlighting."),
)
.arg(
Arg::new("style")
Arg::with_name("style")
.long("style")
.value_name("components")
// Need to turn this off for overrides_with to work as we want. See the bottom most
// example at https://docs.rs/clap/2.32.0/clap/struct.Arg.html#method.overrides_with
.use_value_delimiter(false)
.use_delimiter(false)
.takes_value(true)
.overrides_with("style")
.overrides_with("plain")
.overrides_with("number")
// Cannot use claps built in validation because we have to turn off clap's delimiters
.value_parser(|val: &str| {
.validator(|val| {
let mut invalid_vals = val.split(',').filter(|style| {
!&[
"auto",
@@ -422,7 +415,7 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
if let Some(invalid) = invalid_vals.next() {
Err(format!("Unknown style, '{}'", invalid))
} else {
Ok(val.to_owned())
Ok(())
}
})
.help(
@@ -454,12 +447,14 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("line-range")
Arg::with_name("line-range")
.long("line-range")
.short('r')
.action(ArgAction::Append)
.short("r")
.multiple(true)
.takes_value(true)
.number_of_values(1)
.value_name("N:M")
.conflicts_with("diff")
.help("Only print the lines from N to M.")
.long_help(
"Only print the specified range of lines for each file. \
@@ -472,19 +467,28 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("list-languages")
Arg::with_name("list-languages")
.long("list-languages")
.short('L')
.action(ArgAction::SetTrue)
.short("L")
.conflicts_with("list-themes")
.help("Display all supported languages.")
.long_help("Display a list of supported languages for syntax highlighting."),
)
.arg(
Arg::new("unbuffered")
.short('u')
Arg::with_name("load-plugin")
.long("load-plugin")
.multiple(true)
.takes_value(true)
.number_of_values(1)
.value_name("name")
.help("Load plugin with specified name.")
.hidden_short_help(true)
)
.arg(
Arg::with_name("unbuffered")
.short("u")
.long("unbuffered")
.hide_short_help(true)
.hidden_short_help(true)
.long_help(
"This option exists for POSIX-compliance reasons ('u' is for \
'unbuffered'). The output is always unbuffered - this option \
@@ -492,66 +496,60 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("no-config")
Arg::with_name("no-config")
.long("no-config")
.hide(true)
.hidden(true)
.help("Do not use the configuration file"),
)
.arg(
Arg::new("no-custom-assets")
Arg::with_name("no-custom-assets")
.long("no-custom-assets")
.action(ArgAction::SetTrue)
.hide(true)
.hidden(true)
.help("Do not load custom assets"),
)
.arg(
Arg::new("config-file")
Arg::with_name("config-file")
.long("config-file")
.action(ArgAction::SetTrue)
.conflicts_with("list-languages")
.conflicts_with("list-themes")
.hide(true)
.hidden(true)
.help("Show path to the configuration file."),
)
.arg(
Arg::new("generate-config-file")
Arg::with_name("generate-config-file")
.long("generate-config-file")
.action(ArgAction::SetTrue)
.conflicts_with("list-languages")
.conflicts_with("list-themes")
.hide(true)
.hidden(true)
.help("Generates a default configuration file."),
)
.arg(
Arg::new("config-dir")
Arg::with_name("config-dir")
.long("config-dir")
.action(ArgAction::SetTrue)
.hide(true)
.hidden(true)
.help("Show bat's configuration directory."),
)
.arg(
Arg::new("cache-dir")
Arg::with_name("cache-dir")
.long("cache-dir")
.action(ArgAction::SetTrue)
.hide(true)
.hidden(true)
.help("Show bat's cache directory."),
)
.arg(
Arg::new("diagnostic")
Arg::with_name("diagnostic")
.long("diagnostic")
.alias("diagnostics")
.action(ArgAction::SetTrue)
.hide_short_help(true)
.hidden_short_help(true)
.help("Show diagnostic information for bug reports.")
)
.arg(
Arg::new("acknowledgements")
Arg::with_name("acknowledgements")
.long("acknowledgements")
.action(ArgAction::SetTrue)
.hide_short_help(true)
.hidden_short_help(true)
.help("Show acknowledgements."),
)
.mut_arg("help", |arg| arg.help("Print this help message."));
.help_message("Print this help message.")
.version_message("Show version information.");
// Check if the current directory contains a file name cache. Otherwise,
// enable the 'bat cache' subcommand.
@@ -559,13 +557,12 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
app
} else {
app.subcommand(
Command::new("cache")
SubCommand::with_name("cache")
.about("Modify the syntax-definition and theme cache")
.arg(
Arg::new("build")
Arg::with_name("build")
.long("build")
.short('b')
.action(ArgAction::SetTrue)
.short("b")
.help("Initialize (or update) the syntax/theme cache.")
.long_help(
"Initialize (or update) the syntax/theme cache by loading from \
@@ -573,19 +570,18 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("clear")
Arg::with_name("clear")
.long("clear")
.short('c')
.action(ArgAction::SetTrue)
.short("c")
.help("Remove the cached syntax definitions and themes."),
)
.group(
ArgGroup::new("cache-actions")
ArgGroup::with_name("cache-actions")
.args(&["build", "clear"])
.required(true),
)
.arg(
Arg::new("source")
Arg::with_name("source")
.long("source")
.requires("build")
.takes_value(true)
@@ -593,7 +589,7 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
.help("Use a different directory to load syntaxes and themes from."),
)
.arg(
Arg::new("target")
Arg::with_name("target")
.long("target")
.requires("build")
.takes_value(true)
@@ -603,9 +599,8 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("blank")
Arg::with_name("blank")
.long("blank")
.action(ArgAction::SetTrue)
.requires("build")
.help(
"Create completely new syntax and theme sets \
@@ -613,17 +608,11 @@ pub fn build_app(interactive_output: bool) -> Command<'static> {
),
)
.arg(
Arg::new("acknowledgements")
Arg::with_name("acknowledgements")
.long("acknowledgements")
.action(ArgAction::SetTrue)
.requires("build")
.help("Build acknowledgements.bin."),
),
)
}
}
#[test]
fn verify_app() {
build_app(false).debug_assert();
}

View File

@@ -6,22 +6,6 @@ use std::path::PathBuf;
use crate::directories::PROJECT_DIRS;
#[cfg(not(target_os = "windows"))]
const DEFAULT_SYSTEM_CONFIG_PREFIX: &str = "/etc";
#[cfg(target_os = "windows")]
const DEFAULT_SYSTEM_CONFIG_PREFIX: &str = "C:\\ProgramData";
pub fn system_config_file() -> PathBuf {
let folder = option_env!("BAT_SYSTEM_CONFIG_PREFIX").unwrap_or(DEFAULT_SYSTEM_CONFIG_PREFIX);
let mut path = PathBuf::from(folder);
path.push("bat");
path.push("config");
path
}
pub fn config_file() -> PathBuf {
env::var("BAT_CONFIG_PATH")
.ok()
@@ -103,18 +87,11 @@ pub fn generate_config_file() -> bat::error::Result<()> {
}
pub fn get_args_from_config_file() -> Result<Vec<OsString>, shell_words::ParseError> {
let mut config = String::new();
if let Ok(c) = fs::read_to_string(system_config_file()) {
config.push_str(&c);
config.push('\n');
}
if let Ok(c) = fs::read_to_string(config_file()) {
config.push_str(&c);
}
get_args_from_str(&config)
Ok(fs::read_to_string(config_file())
.ok()
.map(|content| get_args_from_str(&content))
.transpose()?
.unwrap_or_default())
}
pub fn get_args_from_env_var() -> Option<Result<Vec<OsString>, shell_words::ParseError>> {

View File

@@ -8,7 +8,7 @@ mod directories;
mod input;
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::ffi::OsStr;
use std::io;
use std::io::{BufReader, Write};
use std::path::Path;
@@ -22,9 +22,6 @@ use crate::{
config::{config_file, generate_config_file},
};
#[cfg(feature = "bugreport")]
use crate::config::system_config_file;
use assets::{assets_from_cache_or_binary, cache_dir, clear_assets, config_dir};
use directories::PROJECT_DIRS;
use globset::GlobMatcher;
@@ -43,30 +40,30 @@ const THEME_PREVIEW_DATA: &[u8] = include_bytes!("../../../assets/theme_preview.
#[cfg(feature = "build-assets")]
fn build_assets(matches: &clap::ArgMatches) -> Result<()> {
let source_dir = matches
.get_one::<String>("source")
.value_of("source")
.map(Path::new)
.unwrap_or_else(|| PROJECT_DIRS.config_dir());
let target_dir = matches
.get_one::<String>("target")
.value_of("target")
.map(Path::new)
.unwrap_or_else(|| PROJECT_DIRS.cache_dir());
bat::assets::build(
source_dir,
!matches.get_flag("blank"),
matches.get_flag("acknowledgements"),
!matches.is_present("blank"),
matches.is_present("acknowledgements"),
target_dir,
clap::crate_version!(),
)
}
fn run_cache_subcommand(matches: &clap::ArgMatches) -> Result<()> {
if matches.get_flag("build") {
if matches.is_present("build") {
#[cfg(feature = "build-assets")]
build_assets(matches)?;
#[cfg(not(feature = "build-assets"))]
println!("bat has been built without the 'build-assets' feature. The 'cache --build' option is not available.");
} else if matches.get_flag("clear") {
} else if matches.is_present("clear") {
clear_assets();
}
@@ -129,7 +126,7 @@ pub fn get_languages(config: &Config) -> Result<String> {
if config.loop_through {
for lang in languages {
writeln!(result, "{}:{}", lang.name, lang.file_extensions.join(",")).ok();
result += &format!("{}:{}\n", lang.name, lang.file_extensions.join(","));
}
} else {
let longest = languages
@@ -150,7 +147,7 @@ pub fn get_languages(config: &Config) -> Result<String> {
};
for lang in languages {
write!(result, "{:width$}{}", lang.name, separator, width = longest).ok();
result += &format!("{:width$}{}", lang.name, separator, width = longest);
// Number of characters on this line so far, wrap before `desired_width`
let mut num_chars = 0;
@@ -161,11 +158,11 @@ pub fn get_languages(config: &Config) -> Result<String> {
let new_chars = word.len() + comma_separator.len();
if num_chars + new_chars >= desired_width {
num_chars = 0;
write!(result, "\n{:width$}{}", "", separator, width = longest).ok();
result += &format!("\n{:width$}{}", "", separator, width = longest);
}
num_chars += new_chars;
write!(result, "{}", style.paint(&word[..])).ok();
result += &format!("{}", style.paint(&word[..]));
if extension.peek().is_some() {
result += comma_separator;
}
@@ -222,7 +219,66 @@ pub fn list_themes(cfg: &Config) -> Result<()> {
Ok(())
}
fn run_controller(inputs: Vec<Input>, config: &Config) -> Result<bool> {
fn load_and_run_preprocess_plugins(plugins: &[&OsStr], inputs: &mut Vec<Input>) -> Result<()> {
use bat::input::InputKind;
use rlua::{Function, Lua, Result as LuaResult};
use std::fs;
use std::path::PathBuf;
if plugins.is_empty() {
// Do not create Lua context if there are no plugins
return Ok(());
}
let lua = Lua::new();
for plugin_name in plugins {
// TODO: properly load plugins from a central directory + user directories
// TODO: how to handle plugin priority?
let mut plugin_path = PathBuf::from("plugins");
plugin_path.push(plugin_name);
let plugin_source_code = fs::read_to_string(&plugin_path).map_err(|e| {
format!(
"Could not load bat plugin '{}': {}",
plugin_path.to_string_lossy(),
e
)
})?;
lua.context::<_, LuaResult<()>>(|lua_ctx| {
let globals = lua_ctx.globals();
lua_ctx.load(&plugin_source_code).exec()?;
// Plugins are expected to have a 'preprocess' function
let preprocess: Function = globals.get("preprocess")?;
for input in inputs.iter_mut() {
if let InputKind::OrdinaryFile(ref mut path) = &mut input.kind {
let path_str: String = path.to_string_lossy().into();
let new_path = preprocess.call::<_, String>(path_str)?;
*path = PathBuf::from(new_path);
// TODO: the following line overwrites actual user provided names. However,
// this is necessary to get proper syntax highlighting for the path that
// is being provided by the plugin.
input.metadata.user_provided_name = Some(path.clone());
}
}
Ok(())
})
.map_err(|e| format!("Error while executing Lua code: {}", e))?;
}
Ok(())
}
fn run_controller(mut inputs: Vec<Input>, config: &Config) -> Result<bool> {
load_and_run_preprocess_plugins(&config.plugins, &mut inputs)?;
let assets = assets_from_cache_or_binary(config.use_custom_assets)?;
let controller = Controller::new(config, &assets);
controller.run(inputs)
@@ -231,10 +287,8 @@ fn run_controller(inputs: Vec<Input>, config: &Config) -> Result<bool> {
#[cfg(feature = "bugreport")]
fn invoke_bugreport(app: &App) {
use bugreport::{bugreport, collector::*, format::Markdown};
let pager = bat::config::get_pager_executable(
app.matches.get_one::<String>("pager").map(|s| s.as_str()),
)
.unwrap_or_else(|| "less".to_owned()); // FIXME: Avoid non-canonical path to "less".
let pager = bat::config::get_pager_executable(app.matches.value_of("pager"))
.unwrap_or_else(|| "less".to_owned()); // FIXME: Avoid non-canonical path to "less".
let mut custom_assets_metadata = PROJECT_DIRS.cache_dir().to_path_buf();
custom_assets_metadata.push("metadata.yaml");
@@ -262,7 +316,6 @@ fn invoke_bugreport(app: &App) {
"NO_COLOR",
"MANPAGER",
]))
.info(FileContent::new("System Config file", system_config_file()))
.info(FileContent::new("Config file", config_file()))
.info(FileContent::new(
"Custom assets metadata",
@@ -291,7 +344,7 @@ fn invoke_bugreport(app: &App) {
fn run() -> Result<bool> {
let app = App::new()?;
if app.matches.get_flag("diagnostic") {
if app.matches.is_present("diagnostic") {
#[cfg(feature = "bugreport")]
invoke_bugreport(&app);
#[cfg(not(feature = "bugreport"))]
@@ -300,11 +353,11 @@ fn run() -> Result<bool> {
}
match app.matches.subcommand() {
Some(("cache", cache_matches)) => {
("cache", Some(cache_matches)) => {
// If there is a file named 'cache' in the current working directory,
// arguments for subcommand 'cache' are not mandatory.
// If there are non-zero arguments, execute the subcommand cache, else, open the file cache.
if cache_matches.args_present() {
if !cache_matches.args.is_empty() {
run_cache_subcommand(cache_matches)?;
Ok(true)
} else {
@@ -318,7 +371,7 @@ fn run() -> Result<bool> {
let inputs = app.inputs()?;
let config = app.config(&inputs)?;
if app.matches.get_flag("list-languages") {
if app.matches.is_present("list-languages") {
let languages: String = get_languages(&config)?;
let inputs: Vec<Input> = vec![Input::from_reader(Box::new(languages.as_bytes()))];
let plain_config = Config {
@@ -327,22 +380,22 @@ fn run() -> Result<bool> {
..Default::default()
};
run_controller(inputs, &plain_config)
} else if app.matches.get_flag("list-themes") {
} else if app.matches.is_present("list-themes") {
list_themes(&config)?;
Ok(true)
} else if app.matches.get_flag("config-file") {
} else if app.matches.is_present("config-file") {
println!("{}", config_file().to_string_lossy());
Ok(true)
} else if app.matches.get_flag("generate-config-file") {
} else if app.matches.is_present("generate-config-file") {
generate_config_file()?;
Ok(true)
} else if app.matches.get_flag("config-dir") {
} else if app.matches.is_present("config-dir") {
writeln!(io::stdout(), "{}", config_dir())?;
Ok(true)
} else if app.matches.get_flag("cache-dir") {
} else if app.matches.is_present("cache-dir") {
writeln!(io::stdout(), "{}", cache_dir())?;
Ok(true)
} else if app.matches.get_flag("acknowledgements") {
} else if app.matches.is_present("acknowledgements") {
writeln!(io::stdout(), "{}", bat::assets::get_acknowledgements())?;
Ok(true)
} else {

View File

@@ -5,6 +5,8 @@ use crate::style::StyleComponents;
use crate::syntax_mapping::SyntaxMapping;
use crate::wrapping::WrappingMode;
use std::ffi::OsStr;
#[derive(Debug, Clone)]
pub enum VisibleLines {
/// Show all lines which are included in the line ranges
@@ -86,6 +88,9 @@ pub struct Config<'a> {
/// Whether or not to allow custom assets. If this is false or if custom assets (a.k.a.
/// cached assets) are not available, assets from the binary will be used instead.
pub use_custom_assets: bool,
/// List of bat plugins to be loaded
pub plugins: Vec<&'a OsStr>,
}
#[cfg(all(feature = "minimal-application", feature = "paging"))]

View File

@@ -69,7 +69,8 @@ impl InputDescription {
}
}
pub(crate) enum InputKind<'a> {
pub enum InputKind<'a> {
// TODO
OrdinaryFile(PathBuf),
StdIn,
CustomReader(Box<dyn Read + 'a>),
@@ -86,14 +87,15 @@ impl<'a> InputKind<'a> {
}
#[derive(Clone, Default)]
pub(crate) struct InputMetadata {
pub(crate) user_provided_name: Option<PathBuf>,
pub struct InputMetadata {
// TODO
pub user_provided_name: Option<PathBuf>,
pub(crate) size: Option<u64>,
}
pub struct Input<'a> {
pub(crate) kind: InputKind<'a>,
pub(crate) metadata: InputMetadata,
pub kind: InputKind<'a>, // TODO
pub metadata: InputMetadata, // TODO
pub(crate) description: InputDescription,
}

View File

@@ -3,7 +3,7 @@
use std::ffi::OsStr;
use std::process::Command;
#[derive(Debug, PartialEq, Eq)]
#[derive(Debug, PartialEq)]
pub enum LessVersion {
Less(usize),
BusyBox,

View File

@@ -49,7 +49,7 @@ mod terminal;
mod vscreen;
pub(crate) mod wrapping;
pub use pretty_printer::{Input, PrettyPrinter, Syntax};
pub use pretty_printer::{Input, PrettyPrinter};
pub use syntax_mapping::{MappingTarget, SyntaxMapping};
pub use wrapping::WrappingMode;

View File

@@ -168,7 +168,7 @@ fn test_parse_minus_fail() {
assert!(range.is_err());
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum RangeCheckResult {
// Within one of the given ranges
InRange,

View File

@@ -40,23 +40,15 @@ impl PagerKind {
fn from_bin(bin: &str) -> PagerKind {
use std::path::Path;
// Set to `less` by default on most Linux distros.
let pager_bin = Path::new(bin).file_stem();
// The name of the current running binary. Normally `bat` but sometimes
// `batcat` for compatibility reasons.
let current_bin = env::args_os().next();
// Check if the current running binary is set to be our pager.
let is_current_bin_pager = current_bin
.map(|s| Path::new(&s).file_stem() == pager_bin)
.unwrap_or(false);
match pager_bin.map(|s| s.to_string_lossy()).as_deref() {
match Path::new(bin)
.file_stem()
.map(|s| s.to_string_lossy())
.as_deref()
{
Some("bat") => PagerKind::Bat,
Some("less") => PagerKind::Less,
Some("more") => PagerKind::More,
Some("most") => PagerKind::Most,
_ if is_current_bin_pager => PagerKind::Bat,
_ => PagerKind::Unknown,
}
}

View File

@@ -1,4 +1,4 @@
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PagingMode {
Always,
QuitIfOneScreen,

View File

@@ -1,5 +1,3 @@
use std::fmt::Write;
use console::AnsiCodeIterator;
/// Expand tabs like an ANSI-enabled expand(1).
@@ -103,7 +101,7 @@ pub fn replace_nonprintable(input: &[u8], tab_width: usize) -> String {
c => output.push_str(&c.escape_unicode().collect::<String>()),
}
} else {
write!(output, "\\x{:02X}", input[idx]).ok();
output.push_str(&format!("\\x{:02X}", input[idx]));
idx += 1;
}
}

View File

@@ -2,6 +2,7 @@ use std::io::Read;
use std::path::Path;
use console::Term;
use syntect::parsing::SyntaxReference;
use crate::{
assets::HighlightingAssets,
@@ -27,12 +28,6 @@ struct ActiveStyleComponents {
snip: bool,
}
#[non_exhaustive]
pub struct Syntax {
pub name: String,
pub file_extensions: Vec<String>,
}
pub struct PrettyPrinter<'a> {
inputs: Vec<Input<'a>>,
config: Config<'a>,
@@ -245,26 +240,18 @@ impl<'a> PrettyPrinter<'a> {
self.assets.themes()
}
pub fn syntaxes(&self) -> impl Iterator<Item = Syntax> + '_ {
pub fn syntaxes(&self) -> impl Iterator<Item = &SyntaxReference> {
// We always use assets from the binary, which are guaranteed to always
// be valid, so get_syntaxes() can never fail here
self.assets
.get_syntaxes()
.unwrap()
.iter()
.filter(|s| !s.hidden)
.map(|s| Syntax {
name: s.name.clone(),
file_extensions: s.file_extensions.clone(),
})
self.assets.get_syntaxes().unwrap().iter()
}
/// Pretty-print all specified inputs. This method will "use" all stored inputs.
/// If you want to call 'print' multiple times, you have to call the appropriate
/// input_* methods again.
pub fn print(&mut self) -> Result<bool> {
let highlight_lines = std::mem::take(&mut self.highlighted_lines);
self.config.highlighted_lines = HighlightedLineRanges(LineRanges::from(highlight_lines));
self.config.highlighted_lines =
HighlightedLineRanges(LineRanges::from(self.highlighted_lines.clone()));
self.config.term_width = self
.term_width
.unwrap_or_else(|| Term::stdout().size().1 as usize);

View File

@@ -424,7 +424,7 @@ impl<'a> Printer for InteractivePrinter<'a> {
let line = if self.config.show_nonprintable {
replace_nonprintable(line_buffer, self.config.tab_width)
} else {
let line = match self.content_type {
match self.content_type {
Some(ContentType::BINARY) | None => {
return Ok(());
}
@@ -435,15 +435,6 @@ impl<'a> Printer for InteractivePrinter<'a> {
.decode(line_buffer, DecoderTrap::Replace)
.map_err(|_| "Invalid UTF-16BE")?,
_ => String::from_utf8_lossy(line_buffer).to_string(),
};
// Remove byte order mark from the first line if it exists
if line_number == 1 {
match line.strip_prefix('\u{feff}') {
Some(stripped) => stripped.to_string(),
None => line,
}
} else {
line
}
};

View File

@@ -7,7 +7,7 @@ use globset::{Candidate, GlobBuilder, GlobMatcher};
pub mod ignored_suffixes;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum MappingTarget<'a> {
/// For mapping a path to a specific syntax.
@@ -66,14 +66,6 @@ impl<'a> SyntaxMapping<'a> {
mapping
.insert("*.pac", MappingTarget::MapTo("JavaScript (Babel)"))
.unwrap();
mapping
.insert("fish_history", MappingTarget::MapTo("YAML"))
.unwrap();
// See #2151, https://nmap.org/book/nse-language.html
mapping
.insert("*.nse", MappingTarget::MapTo("Lua"))
.unwrap();
// See #1008
mapping
@@ -194,7 +186,6 @@ impl<'a> SyntaxMapping<'a> {
}
pub(crate) fn get_syntax_for(&self, path: impl AsRef<Path>) -> Option<MappingTarget<'a>> {
// Try matching on the file name as-is.
let candidate = Candidate::new(&path);
let candidate_filename = path.as_ref().file_name().map(Candidate::new);
for (ref glob, ref syntax) in self.mappings.iter().rev() {
@@ -206,13 +197,7 @@ impl<'a> SyntaxMapping<'a> {
return Some(*syntax);
}
}
// Try matching on the file name after removing an ignored suffix.
let file_name = path.as_ref().file_name()?;
self.ignored_suffixes
.try_with_stripped_suffix(file_name, |stripped_file_name| {
Ok(self.get_syntax_for(stripped_file_name))
})
.ok()?
None
}
pub fn insert_ignored_suffix(&mut self, suffix: &'a str) {

View File

@@ -1,5 +1,5 @@
# Make sure that the pager gets executed
--paging=always
# Output a dummy message for the integration test and system wide config test.
# Output a dummy message for the integration test.
--pager="echo dummy-pager-from-config"

View File

@@ -1,5 +0,0 @@
# Make sure that the pager gets executed
--paging=always
# Output a dummy message for the integration test.
--pager="echo dummy-pager-from-system-config"

View File

@@ -1 +0,0 @@
{"test": "value"}

View File

@@ -1 +0,0 @@
{"test": "value"}

View File

@@ -1 +0,0 @@
hello world

View File

@@ -1,7 +1,9 @@
use assert_cmd::cargo::CommandCargoExt;
use predicates::boolean::PredicateBooleanExt;
use predicates::{prelude::predicate, str::PredicateStrExt};
use serial_test::serial;
use std::path::Path;
use std::process::Command;
use std::str::from_utf8;
use tempfile::tempdir;
@@ -26,14 +28,41 @@ mod unix {
use unix::*;
mod utils;
use utils::command::{bat, bat_with_config};
#[cfg(unix)]
use utils::command::bat_raw_command;
use utils::mocked_pagers;
const EXAMPLES_DIR: &str = "tests/examples";
fn bat_raw_command_with_config() -> Command {
let mut cmd = Command::cargo_bin("bat").unwrap();
cmd.current_dir("tests/examples");
cmd.env_remove("BAT_CACHE_PATH");
cmd.env_remove("BAT_CONFIG_DIR");
cmd.env_remove("BAT_CONFIG_PATH");
cmd.env_remove("BAT_OPTS");
cmd.env_remove("BAT_PAGER");
cmd.env_remove("BAT_STYLE");
cmd.env_remove("BAT_TABS");
cmd.env_remove("BAT_THEME");
cmd.env_remove("COLORTERM");
cmd.env_remove("NO_COLOR");
cmd.env_remove("PAGER");
cmd
}
fn bat_raw_command() -> Command {
let mut cmd = bat_raw_command_with_config();
cmd.arg("--no-config");
cmd
}
fn bat_with_config() -> assert_cmd::Command {
assert_cmd::Command::from_std(bat_raw_command_with_config())
}
fn bat() -> assert_cmd::Command {
assert_cmd::Command::from_std(bat_raw_command())
}
#[test]
fn basic() {
bat()
@@ -666,18 +695,6 @@ fn alias_pager_disable_long_overrides_short() {
.stdout(predicate::eq("pager-output\n").normalize());
}
#[test]
fn disable_pager_if_disable_paging_flag_comes_after_paging() {
bat()
.env("PAGER", "echo pager-output")
.arg("--paging=always")
.arg("-P")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("hello world\n").normalize());
}
#[test]
fn pager_failed_to_parse() {
bat()
@@ -758,66 +775,14 @@ fn config_read_arguments_from_file() {
#[test]
fn utf16() {
// The output will be converted to UTF-8 with the leading UTF-16
// BOM removed. This behavior is wanted in interactive mode as
// some terminals seem to display the BOM character as a space,
// and it also breaks syntax highlighting.
// The output will be converted to UTF-8 with a leading UTF-8 BOM
bat()
.arg("--plain")
.arg("--decorations=always")
.arg("test_UTF-16LE.txt")
.assert()
.success()
.stdout("hello world\n");
}
// Regression test for https://github.com/sharkdp/bat/issues/1922
#[test]
fn bom_not_stripped_in_loop_through_mode() {
bat()
.arg("--plain")
.arg("--decorations=never")
.arg("--color=never")
.arg("test_BOM.txt")
.assert()
.success()
.stdout("\u{feff}hello world\n");
}
// Regression test for https://github.com/sharkdp/bat/issues/1922
#[test]
fn bom_stripped_when_colored_output() {
bat()
.arg("--color=always")
.arg("--decorations=never")
.arg("test_BOM.txt")
.assert()
.success()
.stdout(
predicate::str::is_match("\u{1b}\\[38;5;[0-9]{3}mhello world\u{1b}\\[0m\n").unwrap(),
);
}
// Regression test for https://github.com/sharkdp/bat/issues/1922
#[test]
fn bom_stripped_when_no_color_and_not_loop_through() {
bat()
.arg("--color=never")
.arg("--decorations=always")
.arg("--style=numbers,grid,header")
.arg("--terminal-width=80")
.arg("test_BOM.txt")
.assert()
.success()
.stdout(
"\
─────┬──────────────────────────────────────────────────────────────────────────
│ File: test_BOM.txt
─────┼──────────────────────────────────────────────────────────────────────────
1 │ hello world
─────┴──────────────────────────────────────────────────────────────────────────
",
);
.stdout(std::str::from_utf8(b"\xEF\xBB\xBFhello world\n").unwrap());
}
#[test]
@@ -1010,7 +975,6 @@ fn header_full_binary() {
}
#[test]
#[cfg(feature = "git")] // Expected output assumes git is enabled
fn header_default() {
bat()
.arg("--paging=never")
@@ -1035,7 +999,6 @@ fn header_default() {
}
#[test]
#[cfg(feature = "git")] // Expected output assumes git is enabled
fn header_default_is_default() {
bat()
.arg("--paging=never")
@@ -1398,7 +1361,6 @@ fn plain_mode_does_not_add_nonexisting_newline() {
// Regression test for https://github.com/sharkdp/bat/issues/299
#[test]
#[cfg(feature = "git")] // Expected output assumes git is enabled
fn grid_for_file_without_newline() {
bat()
.arg("--paging=never")
@@ -1443,7 +1405,6 @@ fn ansi_highlight_underline() {
}
// Ensure that ANSI passthrough is emitted properly for both wrapping and non-wrapping printer.
// See https://github.com/sharkdp/bat/issues/2307 for what common use case this test tests.
#[test]
fn ansi_passthrough_emit() {
for wrapping in &["never", "character"] {
@@ -1563,36 +1524,6 @@ fn all_global_git_config_locations_syntax_mapping_work() {
.stderr("");
}
#[test]
fn map_syntax_and_ignored_suffix_work_together() {
bat()
.arg("-f")
.arg("--theme")
.arg("Monokai Extended")
.arg("-p")
.arg("--ignored-suffix=.suffix")
.arg("--map-syntax=*.demo:JSON")
.arg("test.demo.suffix")
.assert()
.success()
.stdout("\u{1b}[38;5;231m{\u{1b}[0m\u{1b}[38;5;208m\"\u{1b}[0m\u{1b}[38;5;208mtest\u{1b}[0m\u{1b}[38;5;208m\"\u{1b}[0m\u{1b}[38;5;231m:\u{1b}[0m\u{1b}[38;5;231m \u{1b}[0m\u{1b}[38;5;186m\"\u{1b}[0m\u{1b}[38;5;186mvalue\u{1b}[0m\u{1b}[38;5;186m\"\u{1b}[0m\u{1b}[38;5;231m}\u{1b}[0m")
.stderr("");
bat()
.arg("-f")
.arg("--theme")
.arg("Monokai Extended")
.arg("-p")
.arg("--ignored-suffix=.suffix")
.arg("--ignored-suffix=.foo")
.arg("--map-syntax=*.demo:JSON")
.arg("test.demo.foo.suffix")
.assert()
.success()
.stdout("\u{1b}[38;5;231m{\u{1b}[0m\u{1b}[38;5;208m\"\u{1b}[0m\u{1b}[38;5;208mtest\u{1b}[0m\u{1b}[38;5;208m\"\u{1b}[0m\u{1b}[38;5;231m:\u{1b}[0m\u{1b}[38;5;231m \u{1b}[0m\u{1b}[38;5;186m\"\u{1b}[0m\u{1b}[38;5;186mvalue\u{1b}[0m\u{1b}[38;5;186m\"\u{1b}[0m\u{1b}[38;5;231m}\u{1b}[0m")
.stderr("");
}
#[test]
fn acknowledgements() {
bat()

View File

@@ -18,7 +18,7 @@ gpl_occurances=$(git grep --recurse-submodules "${gpl_term}" -- "${gpl_excludes[
if [ -z "${gpl_occurances}" ]; then
echo "PASS: No files under GPL were found"
else
echo "FAIL: GPL:ed code is not compatible with bat, but occurrences of '${gpl_term}' were found:"
echo "FAIL: GPL:ed code is not compatible with bat, but occurances of '${gpl_term}' were found:"
echo "${gpl_occurances}"
exit 1
fi

View File

@@ -1,13 +1,13 @@
#[cfg(feature = "git")]
mod tester;
use crate::tester::BatTester;
macro_rules! snapshot_tests {
($($test_name: ident: $style: expr,)*) => {
$(
#[test]
#[cfg(feature = "git")]
fn $test_name() {
let bat_tester = tester::BatTester::default();
let bat_tester = BatTester::default();
bat_tester.test_snapshot(stringify!($test_name), $style);
}
)*

View File

@@ -3,6 +3,5 @@
# <file system> <dir> <type> <options> <dump> <pass>
UUID=9e6faddf-31ab-3f3e-9b50-2ad4fbc2ea8b / ext4 rw,relatime,data=ordered 0 0
UUID=9e6faddf-31ab-3f3e-9b50-2ad4fbc2ea8b / ext4 rw,relatime,data=ordered 1 1
UUID=62F8-2047 /boot vfat rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro 2 2
UUID=9e6faddf-31ab-3f3e-9b50-2ad4fbc2ea8b / ext4 rw,relatime,data=ordered 0 1
UUID=62F8-2047 /boot vfat rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro 0 2

View File

@@ -1,34 +0,0 @@
--- Finds factorial of a number.
-- @param value Number to find factorial.
-- @return Factorial of number.
local function factorial(value)
 if value <= 1 then
 return 1
 else
 return value * factorial(value - 1)
 end
end
--- Joins a table of strings into a new string.
-- @param table Table of strings.
-- @param separator Separator character.
-- @return Joined string.
local function join(table, separator)
 local data = ""
 
 for index, value in ipairs(table) do
 data = data .. value .. separator
 end
 
 data = data:sub(1, data:len() - 1)
 
 return data
end
local a = factorial(5)
print(a)
local b = join({ "l", "u", "a" }, ",")
print(b)

View File

@@ -1,4 +1,4 @@
# PowerShell script for testing syntax highlighting
# PowerShell script for testing syntax highlighting
function Get-FutureTime {
 param (

View File

@@ -1 +0,0 @@
const dummy: string = "Regression test for https://github.com/sharkdp/bat/pull/2236";

View File

@@ -1,11 +0,0 @@
- cmd: echo "hello world"
 when: 1656950812
- cmd: ls /tmp
 when: 1656950818
 paths:
 - /tmp
- cmd: cp .local/share/fish/fish_history .
 when: 1656950833
 paths:
 - .local/share/fish/fish_history
 - .

View File

@@ -3,6 +3,5 @@
# <file system> <dir> <type> <options> <dump> <pass>
UUID=9e6faddf-31ab-3f3e-9b50-2ad4fbc2ea8b / ext4 rw,relatime,data=ordered 0 0
UUID=9e6faddf-31ab-3f3e-9b50-2ad4fbc2ea8b / ext4 rw,relatime,data=ordered 1 1
UUID=62F8-2047 /boot vfat rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro 2 2
UUID=9e6faddf-31ab-3f3e-9b50-2ad4fbc2ea8b / ext4 rw,relatime,data=ordered 0 1
UUID=62F8-2047 /boot vfat rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro 0 2

View File

@@ -1,34 +0,0 @@
--- Finds factorial of a number.
-- @param value Number to find factorial.
-- @return Factorial of number.
local function factorial(value)
if value <= 1 then
return 1
else
return value * factorial(value - 1)
end
end
--- Joins a table of strings into a new string.
-- @param table Table of strings.
-- @param separator Separator character.
-- @return Joined string.
local function join(table, separator)
local data = ""
for index, value in ipairs(table) do
data = data .. value .. separator
end
data = data:sub(1, data:len() - 1)
return data
end
local a = factorial(5)
print(a)
local b = join({ "l", "u", "a" }, ",")
print(b)

View File

@@ -1 +0,0 @@
const dummy: string = "Regression test for https://github.com/sharkdp/bat/pull/2236";

View File

@@ -1,11 +0,0 @@
- cmd: echo "hello world"
when: 1656950812
- cmd: ls /tmp
when: 1656950818
paths:
- /tmp
- cmd: cp .local/share/fish/fish_history .
when: 1656950833
paths:
- .local/share/fish/fish_history
- .

View File

@@ -1,29 +0,0 @@
use predicates::{prelude::predicate, str::PredicateStrExt};
mod utils;
use utils::command::bat_with_config;
// This test is ignored, as it needs a special system wide config put into place.
// In order to run this tests, use `cargo test --test system_wide_config -- --ignored`
#[test]
#[ignore]
fn use_systemwide_config() {
bat_with_config()
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("dummy-pager-from-system-config\n").normalize());
}
// This test is ignored, as it needs a special system wide config put into place
// In order to run this tests, use `cargo test --test system_wide_config -- --ignored`
#[test]
#[ignore]
fn config_overrides_system_config() {
bat_with_config()
.env("BAT_CONFIG_PATH", "bat.conf")
.arg("test.txt")
.assert()
.success()
.stdout(predicate::eq("dummy-pager-from-config\n").normalize());
}

View File

@@ -1,16 +0,0 @@
use bat::PrettyPrinter;
#[test]
fn syntaxes() {
let printer = PrettyPrinter::new();
let syntaxes: Vec<String> = printer.syntaxes().map(|s| s.name).collect();
// Just do some sanity checking
assert!(syntaxes.contains(&"Rust".to_string()));
assert!(syntaxes.contains(&"Java".to_string()));
assert!(!syntaxes.contains(&"this-language-does-not-exist".to_string()));
// This language exists but is hidden, so we should not see it; it shall
// have been filtered out before getting to us
assert!(!syntaxes.contains(&"Git Common".to_string()));
}

View File

@@ -1,38 +0,0 @@
#![allow(unused)] // Because indirectly included by e.g.integration_tests.rs, but not everything inside is used
use assert_cmd::cargo::CommandCargoExt;
use std::process::Command;
pub fn bat_raw_command_with_config() -> Command {
let mut cmd = Command::cargo_bin("bat").unwrap();
cmd.current_dir("tests/examples");
cmd.env_remove("BAT_CACHE_PATH");
cmd.env_remove("BAT_CONFIG_DIR");
cmd.env_remove("BAT_CONFIG_PATH");
cmd.env_remove("BAT_OPTS");
cmd.env_remove("BAT_PAGER");
cmd.env_remove("BAT_STYLE");
cmd.env_remove("BAT_TABS");
cmd.env_remove("BAT_THEME");
cmd.env_remove("COLORTERM");
cmd.env_remove("NO_COLOR");
cmd.env_remove("PAGER");
cmd
}
#[cfg(test)]
pub fn bat_raw_command() -> Command {
let mut cmd = bat_raw_command_with_config();
cmd.arg("--no-config");
cmd
}
#[cfg(test)]
pub fn bat_with_config() -> assert_cmd::Command {
assert_cmd::Command::from_std(bat_raw_command_with_config())
}
#[cfg(test)]
pub fn bat() -> assert_cmd::Command {
assert_cmd::Command::from_std(bat_raw_command())
}

View File

@@ -1,5 +1,3 @@
#![allow(unused)] // Because indirectly included by e.g. system_wide_config.rs, but not used
use assert_cmd::Command;
use predicates::prelude::predicate;
use std::env;

View File

@@ -1,2 +1 @@
pub mod command;
pub mod mocked_pagers;