diff --git a/share/functions/__fish_anypython.fish b/share/functions/__fish_anypython.fish
index 3a3819864..aec4ed659 100644
--- a/share/functions/__fish_anypython.fish
+++ b/share/functions/__fish_anypython.fish
@@ -1,6 +1,6 @@
function __fish_anypython
# Try python3 first, because that's usually faster and generally nicer.
- for py in python3 python2 python
+ for py in python3 python2 python
command -sq $py
and echo $py
and return 0
diff --git a/share/functions/__fish_clang_complete.fish b/share/functions/__fish_clang_complete.fish
index 188799919..de1bdb677 100644
--- a/share/functions/__fish_clang_complete.fish
+++ b/share/functions/__fish_clang_complete.fish
@@ -2,15 +2,15 @@
# by clang.fish and clang++.fish.
# We dynamically query the head at `(commandline -o)[1]` to get the correct completions.
function __fish_clang_complete
- # If the result is for a value, clang only prints the value, so completions
- # for `-std=` print `c++11` and not `-std=c++11` like we need. See #4174.
- set -l prefix (commandline -ct | string replace -fr -- '^(.*=)[^=]*' '$1')
+ # If the result is for a value, clang only prints the value, so completions
+ # for `-std=` print `c++11` and not `-std=c++11` like we need. See #4174.
+ set -l prefix (commandline -ct | string replace -fr -- '^(.*=)[^=]*' '$1')
- # Don't hard-code the name of the clang binary
- set -l clang (commandline -o)[1]
- # first get the completions from clang, with the prefix separated from the value by a comma
- $clang --autocomplete=(commandline -ct | string replace -- "$prefix" "$prefix,") 2>/dev/null |
- # and put it in a format that fish understands
- string replace -r -- '^([^ ]+)\s*(.*)' "$prefix\$1\t\$2"
+ # Don't hard-code the name of the clang binary
+ set -l clang (commandline -o)[1]
+ # first get the completions from clang, with the prefix separated from the value by a comma
+ $clang --autocomplete=(commandline -ct | string replace -- "$prefix" "$prefix,") 2>/dev/null |
+ # and put it in a format that fish understands
+ string replace -r -- '^([^ ]+)\s*(.*)' "$prefix\$1\t\$2"
end
diff --git a/share/functions/__fish_complete_man.fish b/share/functions/__fish_complete_man.fish
index a8d3daf97..5fbe87345 100644
--- a/share/functions/__fish_complete_man.fish
+++ b/share/functions/__fish_complete_man.fish
@@ -19,7 +19,7 @@ function __fish_complete_man
set -l exclude_fish_commands
# Only include fish commands when section is empty or 1
if test -z "$section" -o "$section" = "1"
- set -e exclude_fish_commands
+ set -e exclude_fish_commands
end
set section $section"[^)]*"
@@ -71,8 +71,8 @@ function __fish_complete_man
# Fish commands are not given by apropos
if not set -ql exclude_fish_commands
- set -l files $__fish_data_dir/man/man1/*.1
- string replace -r '.*/([^/]+)\.1$' '$1\t1: fish command' -- $files
+ set -l files $__fish_data_dir/man/man1/*.1
+ string replace -r '.*/([^/]+)\.1$' '$1\t1: fish command' -- $files
end
else
return 1
diff --git a/share/functions/__fish_complete_suffix.fish b/share/functions/__fish_complete_suffix.fish
index 7397e252c..401461cf0 100644
--- a/share/functions/__fish_complete_suffix.fish
+++ b/share/functions/__fish_complete_suffix.fish
@@ -94,7 +94,7 @@ function __fish_complete_suffix -d "Complete using files"
if set -q files[1]
if string match -qr -- . "$desc"
- set desc "\t$desc"
+ set desc "\t$desc"
end
if string match -qr -- . "$prefix"
# Ideally, only replace in the beginning of the string, but we have no
diff --git a/share/functions/__fish_complete_zfs_mountpoint_properties.fish b/share/functions/__fish_complete_zfs_mountpoint_properties.fish
index 07b3a45da..e361b8206 100644
--- a/share/functions/__fish_complete_zfs_mountpoint_properties.fish
+++ b/share/functions/__fish_complete_zfs_mountpoint_properties.fish
@@ -1,5 +1,5 @@
function __fish_complete_zfs_mountpoint_properties -d "Completes with ZFS mountpoint properties"
- set -l OS ""
+ set -l OS ""
switch (uname)
case Linux
set OS "Linux"
@@ -9,21 +9,21 @@ function __fish_complete_zfs_mountpoint_properties -d "Completes with ZFS mountp
set OS "FreeBSD"
case SunOS
set OS "SunOS"
- # Others?
+ # Others?
case "*"
set OS "unknown"
end
- echo -e "atime\t"(_ "Update access time on read")" (on, off)"
- echo -e "devices\t"(_ "Are contained device nodes openable")" (on, off)"
- echo -e "exec\t"(_ "Can contained executables be executed")" (on, off)"
- echo -e "readonly\t"(_ "Read-only")" (on, off)"
- echo -e "setuid\t"(_ "Respect set-UID bit")" (on, off)"
- if test $OS = "SunOS"
- echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
- echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
- else if test $OS = "Linux"
- echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
- echo -e "relatime\t"(_ "Sometimes update access time on read")" (on, off)"
- echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
- end
+ echo -e "atime\t"(_ "Update access time on read")" (on, off)"
+ echo -e "devices\t"(_ "Are contained device nodes openable")" (on, off)"
+ echo -e "exec\t"(_ "Can contained executables be executed")" (on, off)"
+ echo -e "readonly\t"(_ "Read-only")" (on, off)"
+ echo -e "setuid\t"(_ "Respect set-UID bit")" (on, off)"
+ if test $OS = "SunOS"
+ echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
+ echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
+ else if test $OS = "Linux"
+ echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
+ echo -e "relatime\t"(_ "Sometimes update access time on read")" (on, off)"
+ echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
+ end
end
diff --git a/share/functions/__fish_complete_zfs_pools.fish b/share/functions/__fish_complete_zfs_pools.fish
index c5ed4e3c3..fb2471567 100644
--- a/share/functions/__fish_complete_zfs_pools.fish
+++ b/share/functions/__fish_complete_zfs_pools.fish
@@ -1,3 +1,3 @@
function __fish_complete_zfs_pools -d "Completes with available ZFS pools"
- zpool list -o name,comment -H | string replace -a \t'-' ''
+ zpool list -o name,comment -H | string replace -a \t'-' ''
end
diff --git a/share/functions/__fish_complete_zfs_ro_properties.fish b/share/functions/__fish_complete_zfs_ro_properties.fish
index c896b5c14..5013070cc 100644
--- a/share/functions/__fish_complete_zfs_ro_properties.fish
+++ b/share/functions/__fish_complete_zfs_ro_properties.fish
@@ -1,44 +1,44 @@
function __fish_complete_zfs_ro_properties -d "Completes with ZFS read-only properties"
- echo -e "available\t"(_ "Available space")
- echo -e "avail\t"(_ "Available space")
- echo -e "compressratio\t"(_ "Achieved compression ratio")
- echo -e "creation\t"(_ "Dataset creation time")
- echo -e "clones\t"(_ "Snapshot clones")
- echo -e "defer_destroy\t"(_ "Marked for deferred destruction")
- echo -e "filesystem_count\t"(_ "Total lower-level filesystems and volumes")
- echo -e "logicalreferenced\t"(_ "Logical total space")
- echo -e "lrefer\t"(_ "Logical total space")
- echo -e "logicalused\t"(_ "Logical used space")
- echo -e "lused\t"(_ "Logical used space")
- echo -e "mounted\t"(_ "Is currently mounted?")
- echo -e "origin\t"(_ "Source snapshot")
- if __fish_is_zfs_feature_enabled "feature@extensible_dataset"
- echo -e "receive_resume_token\t"(_ "Token for interrupted reception resumption")
- end
- echo -e "referenced\t"(_ "Total space")
- echo -e "refer\t"(_ "Total space")
- echo -e "refcompressratio\t"(_ "Achieved compression ratio of referenced space")
- echo -e "snapshot_count\t"(_ "Total lower-level snapshots")
- echo -e "type\t"(_ "Dataset type")
- echo -e "used\t"(_ "Space used by dataset and children")
- echo -e "usedbychildren\t"(_ "Space used by children datasets")
- echo -e "usedbydataset\t"(_ "Space used by dataset itself")
- echo -e "usedbyrefreservation\t"(_ "Space used by refreservation")
- echo -e "usedbysnapshots\t"(_ "Space used by dataset snapshots")
- echo -e "userrefs\t"(_ "Holds count")
- echo -e "volblocksize\t"(_ "Volume block size")
- echo -e "written\t"(_ "Referenced data written since previous snapshot")
- # Autogenerate userused@$USER list; only usernames are supported by the completion, but the zfs command supports more formats
+ echo -e "available\t"(_ "Available space")
+ echo -e "avail\t"(_ "Available space")
+ echo -e "compressratio\t"(_ "Achieved compression ratio")
+ echo -e "creation\t"(_ "Dataset creation time")
+ echo -e "clones\t"(_ "Snapshot clones")
+ echo -e "defer_destroy\t"(_ "Marked for deferred destruction")
+ echo -e "filesystem_count\t"(_ "Total lower-level filesystems and volumes")
+ echo -e "logicalreferenced\t"(_ "Logical total space")
+ echo -e "lrefer\t"(_ "Logical total space")
+ echo -e "logicalused\t"(_ "Logical used space")
+ echo -e "lused\t"(_ "Logical used space")
+ echo -e "mounted\t"(_ "Is currently mounted?")
+ echo -e "origin\t"(_ "Source snapshot")
+ if __fish_is_zfs_feature_enabled "feature@extensible_dataset"
+ echo -e "receive_resume_token\t"(_ "Token for interrupted reception resumption")
+ end
+ echo -e "referenced\t"(_ "Total space")
+ echo -e "refer\t"(_ "Total space")
+ echo -e "refcompressratio\t"(_ "Achieved compression ratio of referenced space")
+ echo -e "snapshot_count\t"(_ "Total lower-level snapshots")
+ echo -e "type\t"(_ "Dataset type")
+ echo -e "used\t"(_ "Space used by dataset and children")
+ echo -e "usedbychildren\t"(_ "Space used by children datasets")
+ echo -e "usedbydataset\t"(_ "Space used by dataset itself")
+ echo -e "usedbyrefreservation\t"(_ "Space used by refreservation")
+ echo -e "usedbysnapshots\t"(_ "Space used by dataset snapshots")
+ echo -e "userrefs\t"(_ "Holds count")
+ echo -e "volblocksize\t"(_ "Volume block size")
+ echo -e "written\t"(_ "Referenced data written since previous snapshot")
+ # Autogenerate userused@$USER list; only usernames are supported by the completion, but the zfs command supports more formats
for user in (__fish_print_users)
set -l tabAndBefore (echo -e "userused@$user\t")
printf (_ "%sDataset space use by user %s\n") $tabAndBefore $user
end
- # Autogenerate groupused@$USER list
+ # Autogenerate groupused@$USER list
for group in (__fish_print_groups)
set -l tabAndBefore (echo -e "groupused@$group\t")
printf (_ "%sDataset space use by group %s\n") $tabAndBefore $group
end
- # Autogenerate written@$SNAPSHOT list
+ # Autogenerate written@$SNAPSHOT list
for snapshot in (__fish_print_zfs_snapshots)
set -l tabAndBefore (echo -e "written@$snapshot\t")
printf (_ "%sReferenced data written since snapshot %s\n") $tabAndBefore $snapshot
diff --git a/share/functions/__fish_complete_zfs_rw_properties.fish b/share/functions/__fish_complete_zfs_rw_properties.fish
index ebc8572e9..5905490c2 100644
--- a/share/functions/__fish_complete_zfs_rw_properties.fish
+++ b/share/functions/__fish_complete_zfs_rw_properties.fish
@@ -1,5 +1,5 @@
function __fish_complete_zfs_rw_properties -d "Completes with ZFS read-write properties"
- set -l OS ""
+ set -l OS ""
switch (uname)
case Linux
set OS "Linux"
@@ -9,89 +9,89 @@ function __fish_complete_zfs_rw_properties -d "Completes with ZFS read-write pro
set OS "FreeBSD"
case SunOS
set OS "SunOS"
- # Others?
+ # Others?
case "*"
set OS "unknown"
- end
- echo -e "aclinherit\t"(_ "Inheritance of ACL entries")" (discard, noallow, restricted, passthrough, passthrough-x)"
- echo -e "atime\t"(_ "Update access time on read")" (on, off)"
- echo -e "canmount\t"(_ "Is the dataset mountable")" (on, off, noauto)"
- set -l additional_algs ''
- if contains -- $OS FreeBSD SunOS
- set additional_algs "$additional_algs, noparity"
end
- if __fish_is_zfs_feature_enabled "feature@sha512"
- set additional_algs "$additional_algs, sha512"
- end
- if __fish_is_zfs_feature_enabled "feature@skein"
- set additional_algs "$additional_algs, skein"
- end
- if __fish_is_zfs_feature_enabled "feature@edonr"
- set additional_algs "$additional_algs, edonr"
- end
- echo -e "checksum\t"(_ "Data checksum")" (on, off, fletcher2, fletcher4, sha256$additional_algs)"
- if __fish_is_zfs_feature_enabled "feature@lz4_compress"
- set additional_algs ", lz4"
- end
- echo -e "compression\t"(_ "Compression algorithm")" (on, off, lzjb$additional_algs, gzip, gzip-[1-9], zle)"
- set -e additional_algs
- echo -e "copies\t"(_ "Number of copies of data")" (1, 2, 3)"
- echo -e "dedup\t"(_ "Deduplication")" (on, off, verify, sha256[,verify])"
- echo -e "devices\t"(_ "Are contained device nodes openable")" (on, off)"
- echo -e "exec\t"(_ "Can contained executables be executed")" (on, off)"
- echo -e "filesystem_limit\t"(_ "Max number of filesystems and volumes")" (COUNT, none)"
- echo -e "mountpoint\t"(_ "Mountpoint")" (PATH, none, legacy)"
- echo -e "primarycache\t"(_ "Which data to cache in ARC")" (all, none, metadata)"
- echo -e "quota\t"(_ "Max size of dataset and children")" (SIZE, none)"
- echo -e "snapshot_limit\t"(_ "Max number of snapshots")" (COUNT, none)"
- echo -e "readonly\t"(_ "Read-only")" (on, off)"
- echo -e "recordsize\t"(_ "Suggest block size")" (SIZE)"
- echo -e "redundant_metadata\t"(_ "How redundant are the metadata")" (all, most)"
- echo -e "refquota\t"(_ "Max space used by dataset itself")" (SIZE, none)"
- echo -e "refreservation\t"(_ "Min space guaranteed to dataset itself")" (SIZE, none)"
- echo -e "reservation\t"(_ "Min space guaranteed to dataset")" (SIZE, none)"
- echo -e "secondarycache\t"(_ "Which data to cache in L2ARC")" (all, none, metadata)"
- echo -e "setuid\t"(_ "Respect set-UID bit")" (on, off)"
- echo -e "sharenfs\t"(_ "Share in NFS")" (on, off, OPTS)"
- echo -e "logbias\t"(_ "Hint for handling of synchronous requests")" (latency, throughput)"
- echo -e "snapdir\t"(_ "Hide .zfs directory")" (hidden, visible)"
- echo -e "sync\t"(_ "Handle of synchronous requests")" (standard, always, disabled)"
- echo -e "volsize\t"(_ "Volume logical size")" (SIZE)"
+ echo -e "aclinherit\t"(_ "Inheritance of ACL entries")" (discard, noallow, restricted, passthrough, passthrough-x)"
+ echo -e "atime\t"(_ "Update access time on read")" (on, off)"
+ echo -e "canmount\t"(_ "Is the dataset mountable")" (on, off, noauto)"
+ set -l additional_algs ''
+ if contains -- $OS FreeBSD SunOS
+ set additional_algs "$additional_algs, noparity"
+ end
+ if __fish_is_zfs_feature_enabled "feature@sha512"
+ set additional_algs "$additional_algs, sha512"
+ end
+ if __fish_is_zfs_feature_enabled "feature@skein"
+ set additional_algs "$additional_algs, skein"
+ end
+ if __fish_is_zfs_feature_enabled "feature@edonr"
+ set additional_algs "$additional_algs, edonr"
+ end
+ echo -e "checksum\t"(_ "Data checksum")" (on, off, fletcher2, fletcher4, sha256$additional_algs)"
+ if __fish_is_zfs_feature_enabled "feature@lz4_compress"
+ set additional_algs ", lz4"
+ end
+ echo -e "compression\t"(_ "Compression algorithm")" (on, off, lzjb$additional_algs, gzip, gzip-[1-9], zle)"
+ set -e additional_algs
+ echo -e "copies\t"(_ "Number of copies of data")" (1, 2, 3)"
+ echo -e "dedup\t"(_ "Deduplication")" (on, off, verify, sha256[,verify])"
+ echo -e "devices\t"(_ "Are contained device nodes openable")" (on, off)"
+ echo -e "exec\t"(_ "Can contained executables be executed")" (on, off)"
+ echo -e "filesystem_limit\t"(_ "Max number of filesystems and volumes")" (COUNT, none)"
+ echo -e "mountpoint\t"(_ "Mountpoint")" (PATH, none, legacy)"
+ echo -e "primarycache\t"(_ "Which data to cache in ARC")" (all, none, metadata)"
+ echo -e "quota\t"(_ "Max size of dataset and children")" (SIZE, none)"
+ echo -e "snapshot_limit\t"(_ "Max number of snapshots")" (COUNT, none)"
+ echo -e "readonly\t"(_ "Read-only")" (on, off)"
+ echo -e "recordsize\t"(_ "Suggest block size")" (SIZE)"
+ echo -e "redundant_metadata\t"(_ "How redundant are the metadata")" (all, most)"
+ echo -e "refquota\t"(_ "Max space used by dataset itself")" (SIZE, none)"
+ echo -e "refreservation\t"(_ "Min space guaranteed to dataset itself")" (SIZE, none)"
+ echo -e "reservation\t"(_ "Min space guaranteed to dataset")" (SIZE, none)"
+ echo -e "secondarycache\t"(_ "Which data to cache in L2ARC")" (all, none, metadata)"
+ echo -e "setuid\t"(_ "Respect set-UID bit")" (on, off)"
+ echo -e "sharenfs\t"(_ "Share in NFS")" (on, off, OPTS)"
+ echo -e "logbias\t"(_ "Hint for handling of synchronous requests")" (latency, throughput)"
+ echo -e "snapdir\t"(_ "Hide .zfs directory")" (hidden, visible)"
+ echo -e "sync\t"(_ "Handle of synchronous requests")" (standard, always, disabled)"
+ echo -e "volsize\t"(_ "Volume logical size")" (SIZE)"
- # Autogenerate userquota@$USER list; only usernames are supported by the completion, but the zfs command supports more formats
+ # Autogenerate userquota@$USER list; only usernames are supported by the completion, but the zfs command supports more formats
for user in (__fish_print_users)
set -l tabAndBefore (echo -e "userquota@$user\t")
printf (_ "%sMax usage by user %s\n") $tabAndBefore $user
end
- # Autogenerate groupquota@$USER list
+ # Autogenerate groupquota@$USER list
for group in (__fish_print_groups)
set -l tabAndBefore (echo -e "groupquota@$group\t")
printf (_ "%sMax usage by group %s\n") $tabAndBefore $group
end
- if test $OS = "SunOS"
- echo -e "aclmode\t"(_ "How is ACL modified by chmod")" (discard, groupmask, passthrough, restricted)"
- echo -e "mlslabel\t"(_ "Can the dataset be mounted in a zone with Trusted Extensions enabled")" (LABEL, none)"
- echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
- echo -e "sharesmb\t"(_ "Share in Samba")" (on, off)"
- echo -e "shareiscsi\t"(_ "Share as an iSCSI target")" (on, off)"
- echo -e "version\t"(_ "On-disk version of filesystem")" (1, 2, current)"
- echo -e "vscan\t"(_ "Scan regular files for viruses on opening and closing")" (on, off)"
- echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
- echo -e "zoned\t"(_ "Managed from a non-global zone")" (on, off)"
- else if test $OS = "Linux"
- echo -e "acltype\t"(_ "Use no ACL or POSIX ACL")" (noacl, posixacl)"
- echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
- echo -e "relatime\t"(_ "Sometimes update access time on read")" (on, off)"
- echo -e "shareiscsi\t"(_ "Share as an iSCSI target")" (on, off)"
- echo -e "sharesmb\t"(_ "Share in Samba")" (on, off)"
- echo -e "snapdev\t"(_ "Hide volume snapshots")" (hidden, visible)"
- echo -e "version\t"(_ "On-disk version of filesystem")" (1, 2, current)"
- echo -e "vscan\t"(_ "Scan regular files for viruses on opening and closing")" (on, off)"
- echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
- else if test $OS = "FreeBSD"
- echo -e "aclmode\t"(_ "How is ACL modified by chmod")" (discard, groupmask, passthrough, restricted)"
- echo -e "volmode\t"(_ "How to expose volumes to OS")" (default, geom, dev, none)"
- end
- # User properties; the /dev/null redirection masks the possible "no datasets available"
- zfs list -o all 2>/dev/null | head -n 1 | string replace -a -r "\s+" "\n" | string match -e ":" | string lower
+ if test $OS = "SunOS"
+ echo -e "aclmode\t"(_ "How is ACL modified by chmod")" (discard, groupmask, passthrough, restricted)"
+ echo -e "mlslabel\t"(_ "Can the dataset be mounted in a zone with Trusted Extensions enabled")" (LABEL, none)"
+ echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
+ echo -e "sharesmb\t"(_ "Share in Samba")" (on, off)"
+ echo -e "shareiscsi\t"(_ "Share as an iSCSI target")" (on, off)"
+ echo -e "version\t"(_ "On-disk version of filesystem")" (1, 2, current)"
+ echo -e "vscan\t"(_ "Scan regular files for viruses on opening and closing")" (on, off)"
+ echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
+ echo -e "zoned\t"(_ "Managed from a non-global zone")" (on, off)"
+ else if test $OS = "Linux"
+ echo -e "acltype\t"(_ "Use no ACL or POSIX ACL")" (noacl, posixacl)"
+ echo -e "nbmand\t"(_ "Mount with Non Blocking mandatory locks")" (on, off)"
+ echo -e "relatime\t"(_ "Sometimes update access time on read")" (on, off)"
+ echo -e "shareiscsi\t"(_ "Share as an iSCSI target")" (on, off)"
+ echo -e "sharesmb\t"(_ "Share in Samba")" (on, off)"
+ echo -e "snapdev\t"(_ "Hide volume snapshots")" (hidden, visible)"
+ echo -e "version\t"(_ "On-disk version of filesystem")" (1, 2, current)"
+ echo -e "vscan\t"(_ "Scan regular files for viruses on opening and closing")" (on, off)"
+ echo -e "xattr\t"(_ "Extended attributes")" (on, off, sa)"
+ else if test $OS = "FreeBSD"
+ echo -e "aclmode\t"(_ "How is ACL modified by chmod")" (discard, groupmask, passthrough, restricted)"
+ echo -e "volmode\t"(_ "How to expose volumes to OS")" (default, geom, dev, none)"
+ end
+ # User properties; the /dev/null redirection masks the possible "no datasets available"
+ zfs list -o all 2>/dev/null | head -n 1 | string replace -a -r "\s+" "\n" | string match -e ":" | string lower
end
diff --git a/share/functions/__fish_complete_zfs_write_once_properties.fish b/share/functions/__fish_complete_zfs_write_once_properties.fish
index cb99360d0..524a922b2 100644
--- a/share/functions/__fish_complete_zfs_write_once_properties.fish
+++ b/share/functions/__fish_complete_zfs_write_once_properties.fish
@@ -1,5 +1,5 @@
function __fish_complete_zfs_write_once_properties -d "Completes with ZFS properties which can only be written at filesystem creation, and only be read thereafter"
- set -l OS ""
+ set -l OS ""
switch (uname)
case Linux
set OS "Linux"
@@ -9,22 +9,22 @@ function __fish_complete_zfs_write_once_properties -d "Completes with ZFS proper
set OS "FreeBSD"
case SunOS
set OS "SunOS"
- # Others?
+ # Others?
case "*"
set OS "unknown"
end
- echo -e "normalization\t"(_ "Unicode normalization")" (none, formC, formD, formKC, formKD)"
- echo -e "utf8only\t"(_ "Reject non-UTF-8-compliant filenames")" (on, off)"
- if test $OS = "Linux"
- echo -e "overlay\t"(_ "Allow overlay mount")" (on, off)"
- if command -sq sestatus # SELinux is enabled
- echo -e "context\t"(_ "SELinux context for the child filesystem")
- echo -e "fscontext\t"(_ "SELinux context for the filesystem being mounted")
- echo -e "defcontext\t"(_ "SELinux context for unlabeled files")
- echo -e "rootcontext\t"(_ "SELinux context for the root inode of the filesystem")
- end
- echo -e "casesensitivity\t"(_ "Case sensitivity")" (sensitive, insensitive)"
- else
- echo -e "casesensitivity\t"(_ "Case sensitivity")" (sensitive, insensitive, mixed)"
- end
+ echo -e "normalization\t"(_ "Unicode normalization")" (none, formC, formD, formKC, formKD)"
+ echo -e "utf8only\t"(_ "Reject non-UTF-8-compliant filenames")" (on, off)"
+ if test $OS = "Linux"
+ echo -e "overlay\t"(_ "Allow overlay mount")" (on, off)"
+ if command -sq sestatus # SELinux is enabled
+ echo -e "context\t"(_ "SELinux context for the child filesystem")
+ echo -e "fscontext\t"(_ "SELinux context for the filesystem being mounted")
+ echo -e "defcontext\t"(_ "SELinux context for unlabeled files")
+ echo -e "rootcontext\t"(_ "SELinux context for the root inode of the filesystem")
+ end
+ echo -e "casesensitivity\t"(_ "Case sensitivity")" (sensitive, insensitive)"
+ else
+ echo -e "casesensitivity\t"(_ "Case sensitivity")" (sensitive, insensitive, mixed)"
+ end
end
diff --git a/share/functions/__fish_describe_command.fish b/share/functions/__fish_describe_command.fish
index 7fb334d78..d850a6152 100644
--- a/share/functions/__fish_describe_command.fish
+++ b/share/functions/__fish_describe_command.fish
@@ -8,7 +8,8 @@ function __fish_describe_command -d "Command used to find descriptions for comma
# TODO: stop interpolating argv into regex, and remove this hack.
string match --quiet --regex '^[a-zA-Z0-9_ ]+$' -- "$argv"
or return
- type -q apropos; or return
+ type -q apropos
+ or return
apropos $argv 2>/dev/null | awk -v FS=" +- +" '{
split($1, names, ", ");
for (name in names)
diff --git a/share/functions/__fish_first_token.fish b/share/functions/__fish_first_token.fish
index 65b560899..a80dfcb8c 100644
--- a/share/functions/__fish_first_token.fish
+++ b/share/functions/__fish_first_token.fish
@@ -1,9 +1,9 @@
# Retrieves the first non-switch argument from the command line buffer
function __fish_first_token
- set -l tokens (commandline -co)
- set -e tokens[1]
- set -l tokens (string replace -r --filter '^([^-].*)' '$1' -- $tokens)
- if set -q tokens[1]
- echo $tokens[1]
- end
+ set -l tokens (commandline -co)
+ set -e tokens[1]
+ set -l tokens (string replace -r --filter '^([^-].*)' '$1' -- $tokens)
+ if set -q tokens[1]
+ echo $tokens[1]
+ end
end
diff --git a/share/functions/__fish_is_first_arg.fish b/share/functions/__fish_is_first_arg.fish
index b026a11df..499b143ae 100644
--- a/share/functions/__fish_is_first_arg.fish
+++ b/share/functions/__fish_is_first_arg.fish
@@ -1,5 +1,5 @@
# determine if this is the very first argument (regardless if switch or not)
function __fish_is_first_arg
- set -l tokens (commandline -co)
- test (count $tokens) -eq 1
+ set -l tokens (commandline -co)
+ test (count $tokens) -eq 1
end
diff --git a/share/functions/__fish_is_switch.fish b/share/functions/__fish_is_switch.fish
index c513f0e09..5981afa58 100644
--- a/share/functions/__fish_is_switch.fish
+++ b/share/functions/__fish_is_switch.fish
@@ -1,4 +1,4 @@
# Whether or not the current token is a switch
function __fish_is_switch
- string match -qr -- '^-' ""(commandline -ct)
+ string match -qr -- '^-' ""(commandline -ct)
end
diff --git a/share/functions/__fish_parent_directories.fish b/share/functions/__fish_parent_directories.fish
index 9cdacdcc7..8c101f97d 100644
--- a/share/functions/__fish_parent_directories.fish
+++ b/share/functions/__fish_parent_directories.fish
@@ -1,25 +1,25 @@
# Generates a list of parent directories for a given path
# i.e. /a/b/c/d -> [/a/b/c/, /a/b/, /a/, and /a]
function __fish_parent_directories
- if test (count $argv) -ne 1
- # for use in completions, so don't spew error messages
- return 1
- end
+ if test (count $argv) -ne 1
+ # for use in completions, so don't spew error messages
+ return 1
+ end
- set -l splits (string split '/' $argv[1])
- set -l parents
+ set -l splits (string split '/' $argv[1])
+ set -l parents
- for split in $splits
- if test (string length "$split") -eq 0
- continue
- end
+ for split in $splits
+ if test (string length "$split") -eq 0
+ continue
+ end
- set parents "$parents[1]/$split" $parents
- end
+ set parents "$parents[1]/$split" $parents
+ end
- for parent in $parents
- echo $parent
- end
+ for parent in $parents
+ echo $parent
+ end
- return 0
+ return 0
end
diff --git a/share/functions/__fish_parse_configure.fish b/share/functions/__fish_parse_configure.fish
index ccd4cb916..b99e93ed8 100644
--- a/share/functions/__fish_parse_configure.fish
+++ b/share/functions/__fish_parse_configure.fish
@@ -1,14 +1,14 @@
function __fish_parse_configure
- if test (count $argv) -ne 1
- echo "Usage: parse_configure path/to/configure" 1>&2
- return 1
- end
+ if test (count $argv) -ne 1
+ echo "Usage: parse_configure path/to/configure" 1>&2
+ return 1
+ end
- # `complete` parses `./configure` as `configure` so we have to handle all paths, not just ./
- if not test -x $argv[1]
- printf "Cannot find or execute '%s'\n" $argv[1] 1>&2
- return 1
- end
+ # `complete` parses `./configure` as `configure` so we have to handle all paths, not just ./
+ if not test -x $argv[1]
+ printf "Cannot find or execute '%s'\n" $argv[1] 1>&2
+ return 1
+ end
# Must support output along the lines of
# -h, --help display this help and exit
@@ -17,56 +17,56 @@ function __fish_parse_configure
# -V, --version display version information and exit
# -q, --quiet, --silent do not print `checking ...' messages
- set -l next_line
- set -l line
- set -l buffer
- # Just fish's `./configure --help` takes ~350ms to run, before parsing
- # The following chain attempts to extract the help message:
- cat $argv[1] | tr \n \u0e | sed -n 's/.*Report the --help message\(.*\?\)ac_status.*/\1/; s/ac_status.*//p' | tr \u0e \n |
- while test "$next_line" != "" || read -lL next_line
- # In autoconfigure scripts, the first column wraps at 26 chars
- # echo next_line: $next_line
- # echo old_line: $line
- if test "$line" = ""
- set line $next_line
- set next_line "" # mark it as consumed
- continue
- else if string match -qr '^( |\t){2,}[^-]\S*' -- $next_line
- # echo "continuation line found. Old value of line: " \"$line\"
- set line "$line "(string trim $next_line)
- set next_line "" # mark it as consumed
- continue
- end
+ set -l next_line
+ set -l line
+ set -l buffer
+ # Just fish's `./configure --help` takes ~350ms to run, before parsing
+ # The following chain attempts to extract the help message:
+ cat $argv[1] | tr \n \u0e | sed -n 's/.*Report the --help message\(.*\?\)ac_status.*/\1/; s/ac_status.*//p' | tr \u0e \n |
+ while test "$next_line" != "" || read -lL next_line
+ # In autoconfigure scripts, the first column wraps at 26 chars
+ # echo next_line: $next_line
+ # echo old_line: $line
+ if test "$line" = ""
+ set line $next_line
+ set next_line "" # mark it as consumed
+ continue
+ else if string match -qr '^( |\t){2,}[^-]\S*' -- $next_line
+ # echo "continuation line found. Old value of line: " \"$line\"
+ set line "$line "(string trim $next_line)
+ set next_line "" # mark it as consumed
+ continue
+ end
- # echo line: $line
+ # echo line: $line
- # Search for one or more strings starting with `-` separated by commas
- if string replace -fr '^\s+(-.*?)\s+([^\s\-].*)' '$1\n$2' -- $line | read -lL opts description
- for opt in (string split -n , -- $opts | string trim)
+ # Search for one or more strings starting with `-` separated by commas
+ if string replace -fr '^\s+(-.*?)\s+([^\s\-].*)' '$1\n$2' -- $line | read -lL opts description
+ for opt in (string split -n , -- $opts | string trim)
- if string match -qr -- '--[a-z_0-9-]+=\[.*\]' $opt
- # --option=[OPTIONAL_VALUE]
- string replace -r -- '(--[a-z_0-9-]+)=.*' '$1' $opt | read opt
- else if string match -qr -- '--[a-z_0-9-]+\[=.*\]' $opt
- # --option[=OPTIONAL_VALUE]
- string replace -r -- '(--[a-z_0-9-]+)\[=.*' '$1' $opt | read opt
- else if string match -qr -- '--[a-z_0-9-]+=[A-Z]+' $opt
- # --option=CLASS_OF_VALUE (eg FILE or DIR)
- string replace -r -- '(--[a-z_0-9-]+)=.*' '$1' $opt | read opt
- else if string match -qr -- '--[a-z_0-9-]+=\S+' $opt
- # --option=literal_value, leave as-is
- else if string match -qr -- '--[a-z_0-9-]+$' $opt
- # long option, leave as-is
- else if string match -qr -- '-[^-]$' $opt
- # short option, leave as-is
- else
- continue
- end
+ if string match -qr -- '--[a-z_0-9-]+=\[.*\]' $opt
+ # --option=[OPTIONAL_VALUE]
+ string replace -r -- '(--[a-z_0-9-]+)=.*' '$1' $opt | read opt
+ else if string match -qr -- '--[a-z_0-9-]+\[=.*\]' $opt
+ # --option[=OPTIONAL_VALUE]
+ string replace -r -- '(--[a-z_0-9-]+)\[=.*' '$1' $opt | read opt
+ else if string match -qr -- '--[a-z_0-9-]+=[A-Z]+' $opt
+ # --option=CLASS_OF_VALUE (eg FILE or DIR)
+ string replace -r -- '(--[a-z_0-9-]+)=.*' '$1' $opt | read opt
+ else if string match -qr -- '--[a-z_0-9-]+=\S+' $opt
+ # --option=literal_value, leave as-is
+ else if string match -qr -- '--[a-z_0-9-]+$' $opt
+ # long option, leave as-is
+ else if string match -qr -- '-[^-]$' $opt
+ # short option, leave as-is
+ else
+ continue
+ end
- echo "$opt"\t"$description" # parsed by `complete` as value and description
- end
- end
+ echo "$opt"\t"$description" # parsed by `complete` as value and description
+ end
+ end
- set line ""
- end
+ set line ""
+ end
end
diff --git a/share/functions/__fish_pipestatus_with_signal.fish b/share/functions/__fish_pipestatus_with_signal.fish
index b8c0fa35d..116090fa3 100644
--- a/share/functions/__fish_pipestatus_with_signal.fish
+++ b/share/functions/__fish_pipestatus_with_signal.fish
@@ -1,5 +1,5 @@
function __fish_pipestatus_with_signal --description "Print arguments from \$pipestatus replacing values with signal names where appropriate"
for pstat in $argv
- __fish_status_to_signal $pstat
+ __fish_status_to_signal $pstat
end
end
diff --git a/share/functions/__fish_portage_print_available_pkgs.fish b/share/functions/__fish_portage_print_available_pkgs.fish
index 65c4f6443..11ff2b6d7 100644
--- a/share/functions/__fish_portage_print_available_pkgs.fish
+++ b/share/functions/__fish_portage_print_available_pkgs.fish
@@ -1,3 +1,3 @@
function __fish_portage_print_available_pkgs --description 'Print all available packages'
- find (__fish_portage_print_repository_paths) -mindepth 2 -maxdepth 2 -type d ! '(' '(' -path '*/eclass/*' -o -path '*/metadata/*' -o -path '*/profiles/*' -o -path '*/.*/*' ')' -prune ')' -printf '%P\n'
+ find (__fish_portage_print_repository_paths) -mindepth 2 -maxdepth 2 -type d ! '(' '(' -path '*/eclass/*' -o -path '*/metadata/*' -o -path '*/profiles/*' -o -path '*/.*/*' ')' -prune ')' -printf '%P\n'
end
diff --git a/share/functions/__fish_portage_print_installed_pkgs.fish b/share/functions/__fish_portage_print_installed_pkgs.fish
index 41c66530d..9dfbaed3a 100644
--- a/share/functions/__fish_portage_print_installed_pkgs.fish
+++ b/share/functions/__fish_portage_print_installed_pkgs.fish
@@ -1,3 +1,3 @@
function __fish_portage_print_installed_pkgs --description 'Print all installed packages (non-deduplicated)'
- find /var/db/pkg -mindepth 2 -maxdepth 2 -type d -printf '%P\n' | string replace -r -- '-[0-9][0-9.]*.*$' ''
+ find /var/db/pkg -mindepth 2 -maxdepth 2 -type d -printf '%P\n' | string replace -r -- '-[0-9][0-9.]*.*$' ''
end
diff --git a/share/functions/__fish_portage_print_repository_names.fish b/share/functions/__fish_portage_print_repository_names.fish
index 336567ff4..d3a898ac1 100644
--- a/share/functions/__fish_portage_print_repository_names.fish
+++ b/share/functions/__fish_portage_print_repository_names.fish
@@ -1,4 +1,4 @@
function __fish_portage_print_repository_names --description 'Print the names of all configured repositories'
- # repos.conf may be a file or a directory
- find /etc/portage/repos.conf -type f -exec cat '{}' + | string replace -r --filter '^\s*\[([[:alnum:]_][[:alnum:]_-]*)\]' '$1' | string match -v -e DEFAULT
+ # repos.conf may be a file or a directory
+ find /etc/portage/repos.conf -type f -exec cat '{}' + | string replace -r --filter '^\s*\[([[:alnum:]_][[:alnum:]_-]*)\]' '$1' | string match -v -e DEFAULT
end
diff --git a/share/functions/__fish_portage_print_repository_paths.fish b/share/functions/__fish_portage_print_repository_paths.fish
index 48dd738a5..b290ec78b 100644
--- a/share/functions/__fish_portage_print_repository_paths.fish
+++ b/share/functions/__fish_portage_print_repository_paths.fish
@@ -1,4 +1,4 @@
function __fish_portage_print_repository_paths --description 'Print the paths of all configured repositories'
- # repos.conf may be a file or a directory
- find /etc/portage/repos.conf -type f -exec cat '{}' + | string replace -r --filter '^\s*location\s*=\s*(\S+)' '$1'
+ # repos.conf may be a file or a directory
+ find /etc/portage/repos.conf -type f -exec cat '{}' + | string replace -r --filter '^\s*location\s*=\s*(\S+)' '$1'
end
diff --git a/share/functions/__fish_prev_arg_in.fish b/share/functions/__fish_prev_arg_in.fish
index 1fd1662bd..cddc3ebfc 100644
--- a/share/functions/__fish_prev_arg_in.fish
+++ b/share/functions/__fish_prev_arg_in.fish
@@ -1,16 +1,16 @@
# returns 0 only if previous argument is one of the supplied arguments
function __fish_prev_arg_in
- set -l tokens (commandline -co)
- set -l tokenCount (count $tokens)
- if test $tokenCount -lt 2
- # need at least cmd and prev argument
- return 1
- end
- for arg in $argv
- if string match -q -- $tokens[-1] $arg
- return 0
- end
- end
+ set -l tokens (commandline -co)
+ set -l tokenCount (count $tokens)
+ if test $tokenCount -lt 2
+ # need at least cmd and prev argument
+ return 1
+ end
+ for arg in $argv
+ if string match -q -- $tokens[-1] $arg
+ return 0
+ end
+ end
- return 1
+ return 1
end
diff --git a/share/functions/__fish_print_help.fish b/share/functions/__fish_print_help.fish
index 0d74aa084..ef95b7470 100644
--- a/share/functions/__fish_print_help.fish
+++ b/share/functions/__fish_print_help.fish
@@ -73,18 +73,23 @@ function __fish_print_help --description "Print help message for the specified f
# Remove man's bolding
set -l name (string replace -ra '(.)'\b'.' '$1' -- $line)
# We start after we have the name
- contains -- $name NAME; and set have_name 1; and continue
+ contains -- $name NAME
+ and set have_name 1
+ and continue
# We ignore the SYNOPSIS header
- contains -- $name SYNOPSIS; and continue
+ contains -- $name SYNOPSIS
+ and continue
# Everything after COPYRIGHT is useless
- contains -- $name COPYRIGHT; and break
+ contains -- $name COPYRIGHT
+ and break
# not leading space, and not empty, so must contain a non-space
# in the first column. That makes it a header/footer.
set line_type meta
end
- set -q have_name[1]; or continue
+ set -q have_name[1]
+ or continue
switch $state
case normal
switch $line_type
diff --git a/share/functions/__fish_print_hostnames.fish b/share/functions/__fish_print_hostnames.fish
index 4545938fe..f18483b9a 100644
--- a/share/functions/__fish_print_hostnames.fish
+++ b/share/functions/__fish_print_hostnames.fish
@@ -100,10 +100,10 @@ function __fish_print_hostnames -d "Print a list of known hostnames"
set known_hosts $known_hosts (string replace -rfi '.*KnownHostsFile\s*' '' <$file)
end
end
- for file in $known_hosts
+ for file in $known_hosts
if test -r $file
- # Ignore hosts that are hashed, commented or @-marked and strip the key.
- awk '$1 !~ /[|#@]/ {
+ # Ignore hosts that are hashed, commented or @-marked and strip the key.
+ awk '$1 !~ /[|#@]/ {
n=split($1, entries, ",")
for (i=1; i<=n; i++) {
# Ignore negated/wildcarded hosts.
diff --git a/share/functions/__fish_print_packages.fish b/share/functions/__fish_print_packages.fish
index 09e162460..8ed0a9a2e 100644
--- a/share/functions/__fish_print_packages.fish
+++ b/share/functions/__fish_print_packages.fish
@@ -1,7 +1,8 @@
# Use --installed to limit to installed packages only
function __fish_print_packages
argparse --name=__fish_print_packages 'i/installed' -- $argv
- or return;
+ or return
+
set -l only_installed 1
if not set -q _flag_installed
diff --git a/share/functions/__fish_print_pipestatus.fish b/share/functions/__fish_print_pipestatus.fish
index 1cec49653..0fbf17ad6 100644
--- a/share/functions/__fish_print_pipestatus.fish
+++ b/share/functions/__fish_print_pipestatus.fish
@@ -11,7 +11,7 @@ function __fish_print_pipestatus --description "Print pipestatus for prompt"
set -l sep (set_color normal){$brace_sep_color}{$separator}(set_color normal){$status_color}
set -l last_pipestatus_string (string join "$sep" (__fish_pipestatus_with_signal $argv))
printf "%s%s%s%s%s%s%s%s%s%s" (set_color normal )$brace_sep_color $left_brace \
- (set_color normal) $status_color $last_pipestatus_string (set_color normal) \
- $brace_sep_color $right_brace (set_color normal)
+ (set_color normal) $status_color $last_pipestatus_string (set_color normal) \
+ $brace_sep_color $right_brace (set_color normal)
end
end
diff --git a/share/functions/__fish_print_xwindows.fish b/share/functions/__fish_print_xwindows.fish
index 7eef1a6b1..ab5a4140b 100644
--- a/share/functions/__fish_print_xwindows.fish
+++ b/share/functions/__fish_print_xwindows.fish
@@ -1,3 +1,3 @@
function __fish_print_xwindows --description 'Print X windows'
- xwininfo -root -children | sed '/^\s\+0x/!d; /(has no name)/d; s/^\s*\(\S\+\)\s\+"\(.\+\)":\s\+(\(.*\)).*$/\1\t\2 (\3)/'
+ xwininfo -root -children | sed '/^\s\+0x/!d; /(has no name)/d; s/^\s*\(\S\+\)\s\+"\(.\+\)":\s\+(\(.*\)).*$/\1\t\2 (\3)/'
end
diff --git a/share/functions/__fish_print_zfs_bookmarks.fish b/share/functions/__fish_print_zfs_bookmarks.fish
index edc65d448..569e7a9a4 100644
--- a/share/functions/__fish_print_zfs_bookmarks.fish
+++ b/share/functions/__fish_print_zfs_bookmarks.fish
@@ -1,5 +1,5 @@
function __fish_print_zfs_bookmarks -d "Lists ZFS bookmarks, if the feature is enabled"
- if __fish_is_zfs_feature_enabled 'feature@bookmarks'
- zfs list -t bookmark -o name -H
- end
+ if __fish_is_zfs_feature_enabled 'feature@bookmarks'
+ zfs list -t bookmark -o name -H
+ end
end
diff --git a/share/functions/__fish_print_zfs_filesystems.fish b/share/functions/__fish_print_zfs_filesystems.fish
index 5badea5ed..8b314669d 100644
--- a/share/functions/__fish_print_zfs_filesystems.fish
+++ b/share/functions/__fish_print_zfs_filesystems.fish
@@ -1,3 +1,3 @@
function __fish_print_zfs_filesystems -d "Lists ZFS filesystems"
- zfs list -t filesystem -o name -H
+ zfs list -t filesystem -o name -H
end
diff --git a/share/functions/__fish_print_zfs_snapshots.fish b/share/functions/__fish_print_zfs_snapshots.fish
index f32e38869..6f10eb628 100644
--- a/share/functions/__fish_print_zfs_snapshots.fish
+++ b/share/functions/__fish_print_zfs_snapshots.fish
@@ -1,3 +1,3 @@
function __fish_print_zfs_snapshots -d "Lists ZFS snapshots"
- zfs list -t snapshot -o name -H
+ zfs list -t snapshot -o name -H
end
diff --git a/share/functions/__fish_print_zfs_volumes.fish b/share/functions/__fish_print_zfs_volumes.fish
index 3f371b64a..ec1eb5842 100644
--- a/share/functions/__fish_print_zfs_volumes.fish
+++ b/share/functions/__fish_print_zfs_volumes.fish
@@ -1,3 +1,3 @@
function __fish_print_zfs_volumes -d "Lists ZFS volumes"
- zfs list -t volume -o name -H
+ zfs list -t volume -o name -H
end
diff --git a/share/functions/__fish_seen_argument.fish b/share/functions/__fish_seen_argument.fish
index 20fed3279..877554dfd 100644
--- a/share/functions/__fish_seen_argument.fish
+++ b/share/functions/__fish_seen_argument.fish
@@ -1,22 +1,22 @@
function __fish_seen_argument
- argparse 's/short=+' 'l/long=+' -- $argv
+ argparse 's/short=+' 'l/long=+' -- $argv
- set cmd (commandline -co)
- set -e cmd[1]
- for t in $cmd
- for s in $_flag_s
- if string match -qr "^-[A-z0-9]*"$s"[A-z0-9]*\$" -- $t
- return 0
- end
- end
+ set cmd (commandline -co)
+ set -e cmd[1]
+ for t in $cmd
+ for s in $_flag_s
+ if string match -qr "^-[A-z0-9]*"$s"[A-z0-9]*\$" -- $t
+ return 0
+ end
+ end
- for l in $_flag_l
- if string match -q -- "--$l" $t
- return 0
- end
- end
- end
+ for l in $_flag_l
+ if string match -q -- "--$l" $t
+ return 0
+ end
+ end
+ end
- return 1
+ return 1
end
diff --git a/share/functions/__fish_should_complete_switches.fish b/share/functions/__fish_should_complete_switches.fish
index 2563190fb..81a71926a 100644
--- a/share/functions/__fish_should_complete_switches.fish
+++ b/share/functions/__fish_should_complete_switches.fish
@@ -1,14 +1,14 @@
# Returns whether we *should* complete a -s or --long argument.
# The preference is NOT to do so, i.e. prefer subcommands over switches.
function __fish_should_complete_switches
- for arg in (commandline -ct)[-1..1]
- if not string match -qr -- "^-\S*\$" "$arg"
- return 1
- end
- end
- if string match -qr -- "^-" (commandline -ct)[-1]
- return 0
- end
+ for arg in (commandline -ct)[-1..1]
+ if not string match -qr -- "^-\S*\$" "$arg"
+ return 1
+ end
+ end
+ if string match -qr -- "^-" (commandline -ct)[-1]
+ return 0
+ end
- return 1
+ return 1
end
diff --git a/share/functions/__fish_whatis.fish b/share/functions/__fish_whatis.fish
index 4899d99f4..2a4eebc56 100644
--- a/share/functions/__fish_whatis.fish
+++ b/share/functions/__fish_whatis.fish
@@ -1,21 +1,21 @@
# uses `whatis` if available to describe a command
function __fish_whatis
- set -l cmd $argv[1]
- set -l fallback
- if set -q argv[2]
- set fallback $argv[2]
- end
+ set -l cmd $argv[1]
+ set -l fallback
+ if set -q argv[2]
+ set fallback $argv[2]
+ end
- set -l description (whatis $cmd 2>/dev/null | string replace -r '.*? - ' '')[1]
- if not string match -qr -- "." "$description"
- printf '%s\n' $description
- return 0
- else if not string match -q -- "$fallback" ""
- printf '%s\n' $fallback
- return 0
- else
- return 1
- end
+ set -l description (whatis $cmd 2>/dev/null | string replace -r '.*? - ' '')[1]
+ if not string match -qr -- "." "$description"
+ printf '%s\n' $description
+ return 0
+ else if not string match -q -- "$fallback" ""
+ printf '%s\n' $fallback
+ return 0
+ else
+ return 1
+ end
end
diff --git a/share/functions/__terlar_git_prompt.fish b/share/functions/__terlar_git_prompt.fish
index 617ef944f..46b4c241d 100644
--- a/share/functions/__terlar_git_prompt.fish
+++ b/share/functions/__terlar_git_prompt.fish
@@ -16,7 +16,7 @@ set -g fish_prompt_git_status_renamed '➜'
set -g fish_prompt_git_status_copied '⇒'
set -g fish_prompt_git_status_deleted '✖'
set -g fish_prompt_git_status_untracked '?'
-set -g fish_prompt_git_status_unmerged '!'
+set -g fish_prompt_git_status_unmerged !
set -g fish_prompt_git_status_order added modified renamed copied deleted untracked unmerged
diff --git a/share/functions/_fish_systemctl.fish b/share/functions/_fish_systemctl.fish
index 669bd41e5..2fea85e58 100644
--- a/share/functions/_fish_systemctl.fish
+++ b/share/functions/_fish_systemctl.fish
@@ -33,23 +33,30 @@ function _fish_systemctl --description 'Call systemctl with some options from th
help reset-failed list-dependencies list-units revert add-{wants,requires} edit
case enable
# This will only work for "list-unit-files", but won't print an error for "list-units".
- set -q _flag_state; or set _flag_state disabled
+ set -q _flag_state
+ or set _flag_state disabled
case disable
- set -q _flag_state; or set _flag_state enabled
+ set -q _flag_state
+ or set _flag_state enabled
case start
# Running `start` on an already started unit isn't an _error_, but useless.
- set -q _flag_state; or set _flag_state dead,failed
+ set -q _flag_state
+ or set _flag_state dead,failed
case mask
- set -q _flag_state; or set _flag_state loaded
+ set -q _flag_state
+ or set _flag_state loaded
case unmask
- set -q _flag_state; or set _flag_state masked
+ set -q _flag_state
+ or set _flag_state masked
case stop kill
# TODO: Is "kill" useful on other unit types?
# Running as the catch-all, "mounted" for .mount units, "active" for .target.
- set -q _flag_state; or set _flag_state running,mounted,active
+ set -q _flag_state
+ or set _flag_state running,mounted,active
case isolate set-default
# These only take one unit.
- set -q argv[1]; and return
+ set -q argv[1]
+ and return
case list-sockets
set _flag_type socket
case list-timers
@@ -65,11 +72,16 @@ function _fish_systemctl --description 'Call systemctl with some options from th
end
# Add the flags back so we can pass them to our systemctl invocations.
- set -q _flag_type; and set passflags $passflags --type=$_flag_type
- set -q _flag_state; and set passflags $passflags --state=$_flag_state
- set -q _flag_property; and set passflags $passflags --property=$_flag_property
- set -q _flag_machine; and set passflags $passflags --machine=$_flag_machine
- set -q _flag_host; and set passflags $passflags --host=$_flag_host
+ set -q _flag_type
+ and set passflags $passflags --type=$_flag_type
+ set -q _flag_state
+ and set passflags $passflags --state=$_flag_state
+ set -q _flag_property
+ and set passflags $passflags --property=$_flag_property
+ set -q _flag_machine
+ and set passflags $passflags --machine=$_flag_machine
+ set -q _flag_host
+ and set passflags $passflags --host=$_flag_host
# Output looks like
# systemd-tmpfiles-clean.timer [more whitespace] loaded active waiting Daily Cleanup[...]
diff --git a/share/functions/abbr.fish b/share/functions/abbr.fish
index b328c5120..e37c1557b 100644
--- a/share/functions/abbr.fish
+++ b/share/functions/abbr.fish
@@ -53,12 +53,14 @@ function abbr --description "Manage abbreviations"
else if set -q _flag_query[1]
# "--query": Check if abbrs exist.
# If we don't have an argument, it's an automatic failure.
- set -q argv[1]; or return 1
+ set -q argv[1]
+ or return 1
set -l escaped _fish_abbr_(string escape --style=var -- $argv)
# We return 0 if any arg exists, whereas `set -q` returns the number of undefined arguments.
# But we should be consistent with `type -q` and `command -q`.
for var in $escaped
- set -q $escaped; and return 0
+ set -q $escaped
+ and return 0
end
return 1
else
diff --git a/share/functions/fish_clipboard_copy.fish b/share/functions/fish_clipboard_copy.fish
index 0054198aa..088c9c921 100644
--- a/share/functions/fish_clipboard_copy.fish
+++ b/share/functions/fish_clipboard_copy.fish
@@ -1,7 +1,8 @@
function fish_clipboard_copy
# Copy the current selection, or the entire commandline if that is empty.
set -l cmdline (commandline --current-selection)
- test -n "$cmdline"; or set cmdline (commandline)
+ test -n "$cmdline"
+ or set cmdline (commandline)
if type -q pbcopy
printf '%s\n' $cmdline | pbcopy
else if type -q xsel
diff --git a/share/functions/fish_config.fish b/share/functions/fish_config.fish
index aa05fa0f0..e09a4aa24 100644
--- a/share/functions/fish_config.fish
+++ b/share/functions/fish_config.fish
@@ -3,12 +3,12 @@ function fish_config --description "Launch fish's web based configuration"
if set -l python (__fish_anypython)
$python "$__fish_data_dir/tools/web_config/webconfig.py" $argv
else
- echo (set_color $fish_color_error)Cannot launch the web configuration tool:(set_color normal)
- echo (set_color -o)fish_config(set_color normal) requires Python.
- echo Installing python2 or python3 will fix this, and also enable completions to be
- echo automatically generated from man pages.\n
- echo To change your prompt, create a (set_color -o)fish_prompt(set_color normal) function.
- echo There are examples in (set_color $fish_color_valid_path)$__fish_data_dir/tools/web_config/sample_prompts(set_color normal).\n
- echo You can tweak your colors by setting the (set_color $fish_color_search_match)\$fish_color_\*(set_color normal) variables.
+ echo (set_color $fish_color_error)Cannot launch the web configuration tool:(set_color normal)
+ echo (set_color -o)fish_config(set_color normal) requires Python.
+ echo Installing python2 or python3 will fix this, and also enable completions to be
+ echo automatically generated from man pages.\n
+ echo To change your prompt, create a (set_color -o)fish_prompt(set_color normal) function.
+ echo There are examples in (set_color $fish_color_valid_path)$__fish_data_dir/tools/web_config/sample_prompts(set_color normal).\n
+ echo You can tweak your colors by setting the (set_color $fish_color_search_match)\$fish_color_\*(set_color normal) variables.
end
end
diff --git a/share/functions/fish_git_prompt.fish b/share/functions/fish_git_prompt.fish
index cf3623bfa..eef67866a 100644
--- a/share/functions/fish_git_prompt.fish
+++ b/share/functions/fish_git_prompt.fish
@@ -454,7 +454,8 @@ function fish_git_prompt --description "Prompt function for Git"
set b (string replace refs/heads/ '' -- $b)
set -q __fish_git_prompt_shorten_branch_char_suffix
or set -l __fish_git_prompt_shorten_branch_char_suffix "…"
- if string match -qr '^\d+$' "$__fish_git_prompt_shorten_branch_len"; and test (string length "$b") -gt $__fish_git_prompt_shorten_branch_len
+ if string match -qr '^\d+$' "$__fish_git_prompt_shorten_branch_len"
+ and test (string length "$b") -gt $__fish_git_prompt_shorten_branch_len
set b (string sub -l "$__fish_git_prompt_shorten_branch_len" "$b")"$__fish_git_prompt_shorten_branch_char_suffix"
end
if test -n "$b"
@@ -548,7 +549,8 @@ function __fish_git_prompt_informative_status
set -l untrackedfiles (command git ls-files --others --exclude-standard | count)
set -l stashstate 0
set -l stashfile "$argv[1]/logs/refs/stash"
- if set -q __fish_git_prompt_showstashstate; and test -e "$stashfile"
+ if set -q __fish_git_prompt_showstashstate
+ and test -e "$stashfile"
set stashstate (count < $stashfile)
end
diff --git a/share/functions/fish_hg_prompt.fish b/share/functions/fish_hg_prompt.fish
index 3ec08cf6e..8911fbfdc 100644
--- a/share/functions/fish_hg_prompt.fish
+++ b/share/functions/fish_hg_prompt.fish
@@ -16,7 +16,7 @@ set -g fish_prompt_hg_status_modified '*'
set -g fish_prompt_hg_status_copied '⇒'
set -g fish_prompt_hg_status_deleted '✖'
set -g fish_prompt_hg_status_untracked '?'
-set -g fish_prompt_hg_status_unmerged '!'
+set -g fish_prompt_hg_status_unmerged !
set -g fish_prompt_hg_status_order added modified copied deleted untracked unmerged
diff --git a/share/functions/fish_npm_helper.fish b/share/functions/fish_npm_helper.fish
index 810154c01..4686b3475 100644
--- a/share/functions/fish_npm_helper.fish
+++ b/share/functions/fish_npm_helper.fish
@@ -59,7 +59,7 @@ function __yarn_installed_packages
if set -l python (__fish_anypython)
$python -c 'import json, sys; data = json.load(sys.stdin);
-print("\n".join(data["dependencies"])); print("\n".join(data["devDependencies"]))' < $package_json 2>/dev/null
+print("\n".join(data["dependencies"])); print("\n".join(data["devDependencies"]))' <$package_json 2>/dev/null
else if type -q jq
jq -r '.dependencies as $a1 | .devDependencies as $a2 | ($a1 + $a2) | to_entries[] | .key' $package_json
else
diff --git a/share/functions/fish_print_hg_root.fish b/share/functions/fish_print_hg_root.fish
index 6b28f4416..3b64609d6 100644
--- a/share/functions/fish_print_hg_root.fish
+++ b/share/functions/fish_print_hg_root.fish
@@ -19,4 +19,4 @@ function fish_print_hg_root
return 1
end
-
+
diff --git a/share/functions/fish_svn_prompt.fish b/share/functions/fish_svn_prompt.fish
index c010cda94..bfef4661a 100644
--- a/share/functions/fish_svn_prompt.fish
+++ b/share/functions/fish_svn_prompt.fish
@@ -37,7 +37,7 @@ set -g __fish_svn_prompt_char_unversioned_external_color --underline cyan
set -g __fish_svn_prompt_char_unversioned_display '?'
set -g __fish_svn_prompt_char_unversioned_color purple
-set -g __fish_svn_prompt_char_missing_display '!'
+set -g __fish_svn_prompt_char_missing_display !
set -g __fish_svn_prompt_char_missing_color yellow
set -g __fish_svn_prompt_char_versioned_obstructed_display '~'
diff --git a/share/functions/help.fish b/share/functions/help.fish
index 0a6c94dfd..56210688f 100644
--- a/share/functions/help.fish
+++ b/share/functions/help.fish
@@ -67,9 +67,10 @@ function help --description 'Show help for the fish shell'
# If the OS appears to be Windows (graphical), try to use cygstart
if type -q cygstart
set fish_browser cygstart
- # If xdg-open is available, just use that
- # but only if an X session is running
- else if type -q xdg-open; and set -q -x DISPLAY
+ # If xdg-open is available, just use that
+ # but only if an X session is running
+ else if type -q xdg-open
+ and set -q -x DISPLAY
set fish_browser xdg-open
end
@@ -158,7 +159,7 @@ function help --description 'Show help for the fish shell'
or set -l TMPDIR /tmp
set -l tmpdir (mktemp -d $TMPDIR/help.XXXXXX)
set -l tmpname $tmpdir/help.html
- echo '' > $tmpname
+ echo '' >$tmpname
set page_url file://$tmpname
end
end
@@ -166,7 +167,7 @@ function help --description 'Show help for the fish shell'
# cmd.exe needs more coaxing.
if string match -qr 'cmd.exe$' -- $fish_browser[1]
$fish_browser /c "start $page_url"
- # If browser is known to be graphical, put into background
+ # If browser is known to be graphical, put into background
else if contains -- $fish_browser[1] $graphical_browsers
switch $fish_browser[1]
case 'htmlview' 'x-www-browser'
diff --git a/share/functions/ls.fish b/share/functions/ls.fish
index aab2f0e49..368c67c69 100644
--- a/share/functions/ls.fish
+++ b/share/functions/ls.fish
@@ -16,7 +16,7 @@ for opt in --color=auto -G --color -F
command ls $opt $argv
end
- if [ $opt = --color=auto ] &&! set -qx LS_COLORS && set -l cmd (command -s {g,}dircolors)[1]
+ if [ $opt = --color=auto ] && ! set -qx LS_COLORS && set -l cmd (command -s {g,}dircolors)[1]
set -l colorfile
for file in ~/.dir_colors ~/.dircolors /etc/DIR_COLORS
if test -f $file
diff --git a/share/functions/type.fish b/share/functions/type.fish
index e779739bc..ba2b81dd4 100644
--- a/share/functions/type.fish
+++ b/share/functions/type.fish
@@ -61,7 +61,8 @@ function type --description 'Print the type of a command'
switch $func_path
case "n/a"
case "stdin"
- break;
+ break
+
case "*"
echo $func_path
end
diff --git a/share/tools/create_manpage_completions.py b/share/tools/create_manpage_completions.py
index bbee8d102..d87fe93f6 100755
--- a/share/tools/create_manpage_completions.py
+++ b/share/tools/create_manpage_completions.py
@@ -51,45 +51,52 @@ VERY_VERBOSE, BRIEF_VERBOSE, NOT_VERBOSE = 2, 1, 0
global VERBOSITY, WRITE_TO_STDOUT, DEROFF_ONLY
VERBOSITY, WRITE_TO_STDOUT, DEROFF_ONLY = NOT_VERBOSE, False, False
-def add_diagnostic(dgn, msg_verbosity = VERY_VERBOSE):
+
+def add_diagnostic(dgn, msg_verbosity=VERY_VERBOSE):
# Add a diagnostic message, if msg_verbosity <= VERBOSITY
if msg_verbosity <= VERBOSITY:
- diagnostic_output.append(' '*diagnostic_indent + dgn)
+ diagnostic_output.append(" " * diagnostic_indent + dgn)
+
def flush_diagnostics(where):
if diagnostic_output:
- output_str = '\n'.join(diagnostic_output) + '\n'
+ output_str = "\n".join(diagnostic_output) + "\n"
where.write(output_str)
diagnostic_output[:] = []
+
# Make sure we don't output the same completion multiple times, which can happen
# For example, xsubpp.1.gz and xsubpp5.10.1.gz
# This maps commands to lists of completions
already_output_completions = {}
+
def compile_and_search(regex, input):
- options_section_regex = re.compile(regex , re.DOTALL)
- options_section_matched = re.search( options_section_regex, input)
+ options_section_regex = re.compile(regex, re.DOTALL)
+ options_section_matched = re.search(options_section_regex, input)
return options_section_matched
+
def unquote_double_quotes(data):
- if (len(data) < 2):
+ if len(data) < 2:
return data
- if data[0] == '"' and data[len(data)-1] == '"':
- data = data[1:len(data)-1]
+ if data[0] == '"' and data[len(data) - 1] == '"':
+ data = data[1 : len(data) - 1]
return data
+
def unquote_single_quotes(data):
- if (len(data) < 2):
+ if len(data) < 2:
return data
- if data[0] == '`' and data[len(data)-1] == '\'':
- data = data[1:len(data)-1]
+ if data[0] == "`" and data[len(data) - 1] == "'":
+ data = data[1 : len(data) - 1]
return data
# Make a string of characters that are deemed safe in fish without needing to be escaped
# Note that space is not included
-g_fish_safe_chars = frozenset(string.ascii_letters + string.digits + '_+-|/:=@~')
+g_fish_safe_chars = frozenset(string.ascii_letters + string.digits + "_+-|/:=@~")
+
def fish_escape_single_quote(str):
# Escape a string if necessary so that it can be put in single quotes
@@ -97,55 +104,61 @@ def fish_escape_single_quote(str):
if g_fish_safe_chars.issuperset(str):
return str
- str = str.replace('\\', '\\\\') # Replace one backslash with two
- str = str.replace("'", "\\'") # Replace one single quote with a backslash-single-quote
+ str = str.replace("\\", "\\\\") # Replace one backslash with two
+ str = str.replace(
+ "'", "\\'"
+ ) # Replace one single quote with a backslash-single-quote
return "'" + str + "'"
+
# Make a string Unicode by attempting to decode it as latin-1, or UTF8. See #658
def lossy_unicode(s):
# All strings are unicode in Python 3
- if IS_PY3 or isinstance(s, unicode): return s
+ if IS_PY3 or isinstance(s, unicode):
+ return s
try:
- return s.decode('latin-1')
+ return s.decode("latin-1")
except UnicodeEncodeError:
pass
try:
- return s.decode('utf-8')
+ return s.decode("utf-8")
except UnicodeEncodeError:
pass
- return s.decode('latin-1', 'ignore')
+ return s.decode("latin-1", "ignore")
def output_complete_command(cmdname, args, description, output_list):
- comps = ['complete -c', cmdname]
+ comps = ["complete -c", cmdname]
comps.extend(args)
if description:
- comps.append('--description')
+ comps.append("--description")
comps.append(description)
- output_list.append(lossy_unicode(' ').join([lossy_unicode(c) for c in comps]))
+ output_list.append(lossy_unicode(" ").join([lossy_unicode(c) for c in comps]))
+
def built_command(options, description):
-# print "Options are: ", options
- man_optionlist = re.split(" |,|\"|=|[|]", options)
+ # print "Options are: ", options
+ man_optionlist = re.split(' |,|"|=|[|]', options)
fish_options = []
for optionstr in man_optionlist:
option = re.sub(r"(\[.*\])", "", optionstr)
option = option.strip(" \t\r\n[](){}.,:!")
-
# Skip some problematic cases
- if option in ['-', '--']: continue
- if any(c in "{}()" for c in option): continue
+ if option in ["-", "--"]:
+ continue
+ if any(c in "{}()" for c in option):
+ continue
- if option.startswith('--'):
+ if option.startswith("--"):
# New style long option (--recursive)
- fish_options.append('-l ' + fish_escape_single_quote(option[2:]))
- elif option.startswith('-') and len(option) == 2:
+ fish_options.append("-l " + fish_escape_single_quote(option[2:]))
+ elif option.startswith("-") and len(option) == 2:
# New style short option (-r)
- fish_options.append('-s ' + fish_escape_single_quote(option[1:]))
- elif option.startswith('-') and len(option) > 2:
+ fish_options.append("-s " + fish_escape_single_quote(option[1:]))
+ elif option.startswith("-") and len(option) > 2:
# Old style long option (-recursive)
- fish_options.append('-o ' + fish_escape_single_quote(option[1:]))
+ fish_options.append("-o " + fish_escape_single_quote(option[1:]))
# Determine which options are new (not already in existing_options)
# Then add those to the existing options
@@ -154,12 +167,13 @@ def built_command(options, description):
existing_options.update(fish_options)
# Maybe it's all for naught
- if not fish_options: return
+ if not fish_options:
+ return
# Here's what we'll use to truncate if necessary
max_description_width = 78
if IS_PY3:
- truncation_suffix = '…'
+ truncation_suffix = "…"
else:
ELLIPSIS_CODE_POINT = 0x2026
truncation_suffix = unichr(ELLIPSIS_CODE_POINT)
@@ -167,20 +181,24 @@ def built_command(options, description):
# Try to include as many whole sentences as will fit
# Clean up some probably bogus escapes in the process
clean_desc = description.replace("\\'", "'").replace("\\.", ".")
- sentences = clean_desc.split('.')
+ sentences = clean_desc.split(".")
# Clean up "sentences" that are just whitespace
# But don't let it be empty
sentences = [x for x in sentences if x.strip()]
- if not sentences: sentences = ['']
+ if not sentences:
+ sentences = [""]
- udot = lossy_unicode('.')
- uspace = lossy_unicode(' ')
+ udot = lossy_unicode(".")
+ uspace = lossy_unicode(" ")
truncated_description = lossy_unicode(sentences[0]) + udot
for line in sentences[1:]:
- if not line: continue
- proposed_description = lossy_unicode(truncated_description) + uspace + lossy_unicode(line) + udot
+ if not line:
+ continue
+ proposed_description = (
+ lossy_unicode(truncated_description) + uspace + lossy_unicode(line) + udot
+ )
if len(proposed_description) <= max_description_width:
# It fits
truncated_description = proposed_description
@@ -197,32 +215,36 @@ def built_command(options, description):
truncated_description = fish_escape_single_quote(truncated_description)
escaped_cmd = fish_escape_single_quote(CMDNAME)
- output_complete_command(escaped_cmd, fish_options, truncated_description, built_command_output)
+ output_complete_command(
+ escaped_cmd, fish_options, truncated_description, built_command_output
+ )
+
def remove_groff_formatting(data):
- data = data.replace("\\fI","")
- data = data.replace("\\fP","")
- data = data.replace("\\f1","")
- data = data.replace("\\fB","")
- data = data.replace("\\fR","")
- data = data.replace("\\e","")
- data = re.sub(".PD( \d+)","",data)
- data = data.replace(".BI","")
- data = data.replace(".BR","")
- data = data.replace("0.5i","")
- data = data.replace(".rb","")
- data = data.replace("\\^","")
- data = data.replace("{ ","")
- data = data.replace(" }","")
- data = data.replace("\ ","")
- data = data.replace("\-","-")
- data = data.replace("\&","")
- data = data.replace(".B","")
- data = data.replace("\-","-")
- data = data.replace(".I","")
- data = data.replace("\f","")
+ data = data.replace("\\fI", "")
+ data = data.replace("\\fP", "")
+ data = data.replace("\\f1", "")
+ data = data.replace("\\fB", "")
+ data = data.replace("\\fR", "")
+ data = data.replace("\\e", "")
+ data = re.sub(".PD( \d+)", "", data)
+ data = data.replace(".BI", "")
+ data = data.replace(".BR", "")
+ data = data.replace("0.5i", "")
+ data = data.replace(".rb", "")
+ data = data.replace("\\^", "")
+ data = data.replace("{ ", "")
+ data = data.replace(" }", "")
+ data = data.replace("\ ", "")
+ data = data.replace("\-", "-")
+ data = data.replace("\&", "")
+ data = data.replace(".B", "")
+ data = data.replace("\-", "-")
+ data = data.replace(".I", "")
+ data = data.replace("\f", "")
return data
+
class ManParser(object):
def is_my_type(self, manpage):
return False
@@ -230,10 +252,11 @@ class ManParser(object):
def parse_man_page(self, manpage):
return False
+
class Type1ManParser(ManParser):
def is_my_type(self, manpage):
# print manpage
- options_section_matched = compile_and_search("\.SH \"OPTIONS\"(.*?)", manpage)
+ options_section_matched = compile_and_search('\.SH "OPTIONS"(.*?)', manpage)
if options_section_matched == None:
return False
@@ -241,8 +264,8 @@ class Type1ManParser(ManParser):
return True
def parse_man_page(self, manpage):
- options_section_regex = re.compile( "\.SH \"OPTIONS\"(.*?)(\.SH|\Z)", re.DOTALL)
- options_section_matched = re.search( options_section_regex, manpage)
+ options_section_regex = re.compile('\.SH "OPTIONS"(.*?)(\.SH|\Z)', re.DOTALL)
+ options_section_matched = re.search(options_section_regex, manpage)
options_section = options_section_matched.group(0)
# print options_section
@@ -252,104 +275,105 @@ class Type1ManParser(ManParser):
add_diagnostic("Command is %r" % CMDNAME)
if options_matched == None:
- add_diagnostic('Unable to find options')
- if( self.fallback(options_section) ):
+ add_diagnostic("Unable to find options")
+ if self.fallback(options_section):
return True
- elif (self.fallback2(options_section) ):
+ elif self.fallback2(options_section):
return True
return False
- while (options_matched != None):
+ while options_matched != None:
data = options_matched.group(1)
last_dotpp_index = data.rfind(".PP")
- if (last_dotpp_index != -1):
- data = data[last_dotpp_index+3:]
+ if last_dotpp_index != -1:
+ data = data[last_dotpp_index + 3 :]
data = remove_groff_formatting(data)
data = data.split(".RS 4")
- if (len (data) > 1): #and len(data[1]) <= 300):
+ if len(data) > 1: # and len(data[1]) <= 300):
optionName = data[0].strip()
- if ( optionName.find("-") == -1):
+ if optionName.find("-") == -1:
add_diagnostic("%r doesn't contain '-' " % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
- optionDescription = data[1].strip().replace("\n"," ")
+ optionDescription = data[1].strip().replace("\n", " ")
built_command(optionName, optionDescription)
else:
- add_diagnostic('Unable to split option from description')
+ add_diagnostic("Unable to split option from description")
return False
- options_section = options_section[options_matched.end()-3:]
+ options_section = options_section[options_matched.end() - 3 :]
options_matched = re.search(options_parts_regex, options_section)
def fallback(self, options_section):
- add_diagnostic('Trying fallback')
+ add_diagnostic("Trying fallback")
options_parts_regex = re.compile("\.TP( \d+)?(.*?)\.TP", re.DOTALL)
options_matched = re.search(options_parts_regex, options_section)
if options_matched == None:
- add_diagnostic('Still not found')
+ add_diagnostic("Still not found")
return False
while options_matched != None:
data = options_matched.group(2)
data = remove_groff_formatting(data)
data = data.strip()
- data = data.split("\n",1)
- if (len(data)>1 and len(data[1].strip())>0): # and len(data[1])<400):
+ data = data.split("\n", 1)
+ if len(data) > 1 and len(data[1].strip()) > 0: # and len(data[1])<400):
optionName = data[0].strip()
- if ( optionName.find("-") == -1):
+ if optionName.find("-") == -1:
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
- optionDescription = data[1].strip().replace("\n"," ")
+ optionDescription = data[1].strip().replace("\n", " ")
built_command(optionName, optionDescription)
else:
- add_diagnostic('Unable to split option from description')
+ add_diagnostic("Unable to split option from description")
return False
- options_section = options_section[options_matched.end()-3:]
+ options_section = options_section[options_matched.end() - 3 :]
options_matched = re.search(options_parts_regex, options_section)
return True
def fallback2(self, options_section):
- add_diagnostic('Trying last chance fallback')
+ add_diagnostic("Trying last chance fallback")
ix_remover_regex = re.compile("\.IX.*")
- trailing_num_regex = re.compile('\\d+$')
+ trailing_num_regex = re.compile("\\d+$")
options_parts_regex = re.compile("\.IP (.*?)\.IP", re.DOTALL)
options_section = re.sub(ix_remover_regex, "", options_section)
options_matched = re.search(options_parts_regex, options_section)
if options_matched == None:
- add_diagnostic('Still (still!) not found')
+ add_diagnostic("Still (still!) not found")
return False
while options_matched != None:
data = options_matched.group(1)
data = remove_groff_formatting(data)
data = data.strip()
- data = data.split("\n",1)
- if (len(data)>1 and len(data[1].strip())>0): # and len(data[1])<400):
+ data = data.split("\n", 1)
+ if len(data) > 1 and len(data[1].strip()) > 0: # and len(data[1])<400):
optionName = re.sub(trailing_num_regex, "", data[0].strip())
- if ('-' not in optionName):
+ if "-" not in optionName:
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = optionName.strip()
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
- optionDescription = data[1].strip().replace("\n"," ")
+ optionDescription = data[1].strip().replace("\n", " ")
built_command(optionName, optionDescription)
else:
- add_diagnostic('Unable to split option from description')
+ add_diagnostic("Unable to split option from description")
return False
- options_section = options_section[options_matched.end()-3:]
+ options_section = options_section[options_matched.end() - 3 :]
options_matched = re.search(options_parts_regex, options_section)
return True
+
class Type2ManParser(ManParser):
def is_my_type(self, manpage):
options_section_matched = compile_and_search("\.SH OPTIONS(.*?)", manpage)
@@ -360,40 +384,42 @@ class Type2ManParser(ManParser):
return True
def parse_man_page(self, manpage):
- options_section_regex = re.compile( "\.SH OPTIONS(.*?)(\.SH|\Z)", re.DOTALL)
- options_section_matched = re.search( options_section_regex, manpage)
+ options_section_regex = re.compile("\.SH OPTIONS(.*?)(\.SH|\Z)", re.DOTALL)
+ options_section_matched = re.search(options_section_regex, manpage)
options_section = options_section_matched.group(1)
- options_parts_regex = re.compile("\.[I|T]P( \d+(\.\d)?i?)?(.*?)\.([I|T]P|UNINDENT)", re.DOTALL)
+ options_parts_regex = re.compile(
+ "\.[I|T]P( \d+(\.\d)?i?)?(.*?)\.([I|T]P|UNINDENT)", re.DOTALL
+ )
options_matched = re.search(options_parts_regex, options_section)
- add_diagnostic('Command is %r' % CMDNAME)
+ add_diagnostic("Command is %r" % CMDNAME)
if options_matched == None:
add_diagnostic("%r: Unable to find options" % self)
return False
- while (options_matched != None):
+ while options_matched != None:
data = options_matched.group(3)
data = remove_groff_formatting(data)
data = data.strip()
- data = data.split("\n",1)
- if (len(data)>1 and len(data[1].strip())>0): # and len(data[1])<400):
+ data = data.split("\n", 1)
+ if len(data) > 1 and len(data[1].strip()) > 0: # and len(data[1])<400):
optionName = data[0].strip()
- if '-' not in optionName:
+ if "-" not in optionName:
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
- optionDescription = data[1].strip().replace("\n"," ")
+ optionDescription = data[1].strip().replace("\n", " ")
built_command(optionName, optionDescription)
else:
- add_diagnostic('Unable to split option from description')
+ add_diagnostic("Unable to split option from description")
- options_section = options_section[options_matched.end()-3:]
+ options_section = options_section[options_matched.end() - 3 :]
options_matched = re.search(options_parts_regex, options_section)
@@ -407,8 +433,8 @@ class Type3ManParser(ManParser):
return True
def parse_man_page(self, manpage):
- options_section_regex = re.compile( "\.SH DESCRIPTION(.*?)(\.SH|\Z)", re.DOTALL)
- options_section_matched = re.search( options_section_regex, manpage)
+ options_section_regex = re.compile("\.SH DESCRIPTION(.*?)(\.SH|\Z)", re.DOTALL)
+ options_section_matched = re.search(options_section_regex, manpage)
options_section = options_section_matched.group(1)
options_parts_regex = re.compile("\.TP(.*?)\.TP", re.DOTALL)
@@ -416,37 +442,39 @@ class Type3ManParser(ManParser):
add_diagnostic("Command is %r" % CMDNAME)
if options_matched == None:
- add_diagnostic('Unable to find options section')
+ add_diagnostic("Unable to find options section")
return False
- while (options_matched != None):
+ while options_matched != None:
data = options_matched.group(1)
data = remove_groff_formatting(data)
data = data.strip()
- data = data.split("\n",1)
+ data = data.split("\n", 1)
- if (len(data)>1): # and len(data[1])<400):
+ if len(data) > 1: # and len(data[1])<400):
optionName = data[0].strip()
- if ( optionName.find("-") == -1):
+ if optionName.find("-") == -1:
add_diagnostic("%r doesn't contain '-'" % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
- optionDescription = data[1].strip().replace("\n"," ")
+ optionDescription = data[1].strip().replace("\n", " ")
built_command(optionName, optionDescription)
else:
- add_diagnostic('Unable to split option from description')
+ add_diagnostic("Unable to split option from description")
return False
- options_section = options_section[options_matched.end()-3:]
+ options_section = options_section[options_matched.end() - 3 :]
options_matched = re.search(options_parts_regex, options_section)
class Type4ManParser(ManParser):
def is_my_type(self, manpage):
- options_section_matched = compile_and_search("\.SH FUNCTION LETTERS(.*?)", manpage)
+ options_section_matched = compile_and_search(
+ "\.SH FUNCTION LETTERS(.*?)", manpage
+ )
if options_section_matched == None:
return False
@@ -454,8 +482,10 @@ class Type4ManParser(ManParser):
return True
def parse_man_page(self, manpage):
- options_section_regex = re.compile( "\.SH FUNCTION LETTERS(.*?)(\.SH|\Z)", re.DOTALL)
- options_section_matched = re.search( options_section_regex, manpage)
+ options_section_regex = re.compile(
+ "\.SH FUNCTION LETTERS(.*?)(\.SH|\Z)", re.DOTALL
+ )
+ options_section_matched = re.search(options_section_regex, manpage)
options_section = options_section_matched.group(1)
options_parts_regex = re.compile("\.TP(.*?)\.TP", re.DOTALL)
@@ -463,35 +493,36 @@ class Type4ManParser(ManParser):
add_diagnostic("Command is %r" % CMDNAME)
if options_matched == None:
- print >> sys.stderr, "Unable to find options section"
+ print >>sys.stderr, "Unable to find options section"
return False
- while (options_matched != None):
+ while options_matched != None:
data = options_matched.group(1)
data = remove_groff_formatting(data)
data = data.strip()
- data = data.split("\n",1)
+ data = data.split("\n", 1)
- if (len(data)>1): # and len(data[1])<400):
+ if len(data) > 1: # and len(data[1])<400):
optionName = data[0].strip()
- if ( optionName.find("-") == -1):
+ if optionName.find("-") == -1:
add_diagnostic("%r doesn't contain '-' " % optionName)
else:
optionName = unquote_double_quotes(optionName)
optionName = unquote_single_quotes(optionName)
- optionDescription = data[1].strip().replace("\n"," ")
+ optionDescription = data[1].strip().replace("\n", " ")
built_command(optionName, optionDescription)
else:
- add_diagnostic('Unable to split option from description')
+ add_diagnostic("Unable to split option from description")
return False
- options_section = options_section[options_matched.end()-3:]
+ options_section = options_section[options_matched.end() - 3 :]
options_matched = re.search(options_parts_regex, options_section)
return True
+
class TypeDarwinManParser(ManParser):
def is_my_type(self, manpage):
options_section_matched = compile_and_search("\.S[hH] DESCRIPTION", manpage)
@@ -499,15 +530,15 @@ class TypeDarwinManParser(ManParser):
def trim_groff(self, line):
# Remove initial period
- if line.startswith('.'):
+ if line.startswith("."):
line = line[1:]
# Skip leading groff crud
- while re.match('[A-Z][a-z]\s', line):
+ while re.match("[A-Z][a-z]\s", line):
line = line[3:]
# If the line ends with a space and then a period or comma, then erase the space
# This hack handles lines of the form '.Ar projectname .'
- if line.endswith(' ,') or line.endswith(' .'):
+ if line.endswith(" ,") or line.endswith(" ."):
line = line[:-2] + line[-1]
return line
@@ -516,28 +547,31 @@ class TypeDarwinManParser(ManParser):
# Look for the start of a line, followed by a dot, then a sequence of
# one or more dashes ('Fl')
result = 0
- if line.startswith('.'):
+ if line.startswith("."):
line = line[4:]
- while line.startswith('Fl '):
+ while line.startswith("Fl "):
result = result + 1
line = line[3:]
return result
# Replace some groff escapes. There's a lot we don't bother to handle.
def groff_replace_escapes(self, line):
- line = line.replace('.Nm', CMDNAME)
- line = line.replace('\\ ', ' ')
- line = line.replace('\& ', '')
+ line = line.replace(".Nm", CMDNAME)
+ line = line.replace("\\ ", " ")
+ line = line.replace("\& ", "")
return line
def is_option(self, line):
- return line.startswith('.It Fl')
+ return line.startswith(".It Fl")
def parse_man_page(self, manpage):
got_something = False
- lines = manpage.splitlines()
+ lines = manpage.splitlines()
# Discard lines until we get to ".sh Description"
- while lines and not (lines[0].startswith('.Sh DESCRIPTION') or lines[0].startswith('.SH DESCRIPTION')):
+ while lines and not (
+ lines[0].startswith(".Sh DESCRIPTION")
+ or lines[0].startswith(".SH DESCRIPTION")
+ ):
lines.pop(0)
while lines:
@@ -557,7 +591,8 @@ class TypeDarwinManParser(ManParser):
line = self.groff_replace_escapes(line)
line = self.trim_groff(line)
line = line.strip()
- if not line: continue
+ if not line:
+ continue
# Extract the name
name = line.split(None, 2)[0]
@@ -567,24 +602,24 @@ class TypeDarwinManParser(ManParser):
while lines and not self.is_option(lines[0]):
line = lossy_unicode(lines.pop(0).strip())
# Ignore comments
- if line.startswith(r'.\"'):
+ if line.startswith(r".\""):
continue
- if line.startswith('.'):
+ if line.startswith("."):
line = self.groff_replace_escapes(line)
line = self.trim_groff(line).strip()
if line:
desc_lines.append(line)
- desc = ' '.join(desc_lines)
+ desc = " ".join(desc_lines)
- if name == '-':
+ if name == "-":
# Skip double -- arguments
continue
elif len(name) > 1:
# Output the command
- built_command(('-' * dash_count) + name, desc)
+ built_command(("-" * dash_count) + name, desc)
got_something = True
elif len(name) == 1:
- built_command('-' + name, desc)
+ built_command("-" + name, desc)
got_something = True
return got_something
@@ -592,30 +627,34 @@ class TypeDarwinManParser(ManParser):
class TypeDeroffManParser(ManParser):
def is_my_type(self, manpage):
- return True # We're optimists
+ return True # We're optimists
def is_option(self, line):
- return line.startswith('-')
+ return line.startswith("-")
def could_be_description(self, line):
- return len(line) > 0 and not line.startswith('-')
+ return len(line) > 0 and not line.startswith("-")
def parse_man_page(self, manpage):
d = Deroffer()
d.deroff(manpage)
output = d.get_output()
- lines = output.split('\n')
+ lines = output.split("\n")
got_something = False
# Discard lines until we get to DESCRIPTION or OPTIONS
- while lines and not (lines[0].startswith('DESCRIPTION') or lines[0].startswith('OPTIONS') or lines[0].startswith('COMMAND OPTIONS')):
+ while lines and not (
+ lines[0].startswith("DESCRIPTION")
+ or lines[0].startswith("OPTIONS")
+ or lines[0].startswith("COMMAND OPTIONS")
+ ):
lines.pop(0)
# Look for BUGS and stop there
for idx in range(len(lines)):
line = lines[idx]
- if line.startswith('BUGS'):
+ if line.startswith("BUGS"):
# Drop remaining elements
lines[idx:] = []
break
@@ -631,9 +670,10 @@ class TypeDeroffManParser(ManParser):
options = lines.pop(0)
# Pop until we get to either an empty line or a line starting with -
- description = ''
+ description = ""
while lines and self.could_be_description(lines[0]):
- if description: description += ' '
+ if description:
+ description += " "
description += lines.pop(0)
built_command(options, description)
@@ -641,6 +681,7 @@ class TypeDeroffManParser(ManParser):
return got_something
+
# Return whether the file at the given path is overwritable
# Raises IOError if it cannot be opened
def file_is_overwritable(path):
@@ -653,23 +694,25 @@ def file_is_overwritable(path):
continue
# We look in the initial run of lines that start with #
- if not line.startswith('#'):
+ if not line.startswith("#"):
break
# See if this contains the magic word
- if 'Autogenerated' in line:
+ if "Autogenerated" in line:
result = True
break
file.close()
return result
+
# Remove any and all autogenerated completions in the given directory
def cleanup_autogenerated_completions_in_directory(dir):
try:
for filename in os.listdir(dir):
# Skip non .fish files
- if not filename.endswith('.fish'): continue
+ if not filename.endswith(".fish"):
+ continue
path = os.path.join(dir, filename)
cleanup_autogenerated_file(path)
except OSError as err:
@@ -684,6 +727,7 @@ def cleanup_autogenerated_file(path):
except (OSError, IOError):
pass
+
def parse_manpage_at_path(manpage_path, output_directory):
filename = os.path.basename(manpage_path)
@@ -693,28 +737,31 @@ def parse_manpage_at_path(manpage_path, output_directory):
diagnostic_indent = 0
# Set up some diagnostics
- add_diagnostic('Considering ' + manpage_path)
+ add_diagnostic("Considering " + manpage_path)
diagnostic_indent += 1
- if manpage_path.endswith('.gz'):
- fd = gzip.open(manpage_path, 'r')
+ if manpage_path.endswith(".gz"):
+ fd = gzip.open(manpage_path, "r")
manpage = fd.read()
- if IS_PY3: manpage = manpage.decode('latin-1')
- elif manpage_path.endswith('.bz2'):
- fd = bz2.BZ2File(manpage_path, 'r')
+ if IS_PY3:
+ manpage = manpage.decode("latin-1")
+ elif manpage_path.endswith(".bz2"):
+ fd = bz2.BZ2File(manpage_path, "r")
manpage = fd.read()
- if IS_PY3: manpage = manpage.decode('latin-1')
- elif manpage_path.endswith('.xz') or manpage_path.endswith('.lzma'):
+ if IS_PY3:
+ manpage = manpage.decode("latin-1")
+ elif manpage_path.endswith(".xz") or manpage_path.endswith(".lzma"):
if not lzma_available:
return
- fd = lzma.LZMAFile(str(manpage_path), 'r')
+ fd = lzma.LZMAFile(str(manpage_path), "r")
manpage = fd.read()
- if IS_PY3: manpage = manpage.decode('latin-1')
+ if IS_PY3:
+ manpage = manpage.decode("latin-1")
elif manpage_path.endswith((".1", ".2", ".3", ".4", ".5", ".6", ".7", ".8", ".9")):
if IS_PY3:
- fd = open(manpage_path, 'r', encoding='latin-1')
+ fd = open(manpage_path, "r", encoding="latin-1")
else:
- fd = open(manpage_path, 'r')
+ fd = open(manpage_path, "r")
manpage = fd.read()
else:
return
@@ -723,19 +770,30 @@ def parse_manpage_at_path(manpage_path, output_directory):
manpage = str(manpage)
# Get the "base" command, e.g. gcc.1.gz -> gcc
- cmd_base = CMDNAME.split('.', 1)[0]
- ignoredcommands = ["cc", "g++", "gcc", "c++", "cpp", "emacs", "gprof", "wget", "ld", "awk"]
+ cmd_base = CMDNAME.split(".", 1)[0]
+ ignoredcommands = [
+ "cc",
+ "g++",
+ "gcc",
+ "c++",
+ "cpp",
+ "emacs",
+ "gprof",
+ "wget",
+ "ld",
+ "awk",
+ ]
if cmd_base in ignoredcommands:
return
# Ignore perl's gazillion man pages
- ignored_prefixes = ['perl', 'zsh']
+ ignored_prefixes = ["perl", "zsh"]
for prefix in ignored_prefixes:
if cmd_base.startswith(prefix):
return
# Ignore the millions of links to BUILTIN(1)
- if 'BUILTIN 1' in manpage or 'builtin.1' in manpage:
+ if "BUILTIN 1" in manpage or "builtin.1" in manpage:
return
# Clear the output list
@@ -744,7 +802,14 @@ def parse_manpage_at_path(manpage_path, output_directory):
if DEROFF_ONLY:
parsers = [TypeDeroffManParser()]
else:
- parsers = [Type1ManParser(), Type2ManParser(), Type4ManParser(), Type3ManParser(), TypeDarwinManParser(), TypeDeroffManParser()]
+ parsers = [
+ Type1ManParser(),
+ Type2ManParser(),
+ Type4ManParser(),
+ Type3ManParser(),
+ TypeDarwinManParser(),
+ TypeDeroffManParser(),
+ ]
parsersToTry = [p for p in parsers if p.is_my_type(manpage)]
success = False
@@ -752,7 +817,7 @@ def parse_manpage_at_path(manpage_path, output_directory):
add_diagnostic(manpage_path + ": Not supported")
else:
for parser in parsersToTry:
- add_diagnostic('Trying %s' % parser.__class__.__name__)
+ add_diagnostic("Trying %s" % parser.__class__.__name__)
diagnostic_indent += 1
success = parser.parse_man_page(manpage)
diagnostic_indent -= 1
@@ -767,33 +832,43 @@ def parse_manpage_at_path(manpage_path, output_directory):
if WRITE_TO_STDOUT:
output_file = sys.stdout
else:
- fullpath = os.path.join(output_directory, CMDNAME + '.fish')
+ fullpath = os.path.join(output_directory, CMDNAME + ".fish")
try:
output_file = codecs.open(fullpath, "w", encoding="utf-8")
except IOError as err:
- add_diagnostic("Unable to open file '%s': error(%d): %s" % (fullpath, err.errno, err.strerror))
+ add_diagnostic(
+ "Unable to open file '%s': error(%d): %s"
+ % (fullpath, err.errno, err.strerror)
+ )
return False
built_command_output.insert(0, "# " + CMDNAME)
# Output the magic word Autogenerated so we can tell if we can overwrite this
- built_command_output.insert(1, "# Autogenerated from man page " + manpage_path)
+ built_command_output.insert(
+ 1, "# Autogenerated from man page " + manpage_path
+ )
# built_command_output.insert(2, "# using " + parser.__class__.__name__) # XXX MISATTRIBUTES THE CULPABILE PARSER! Was really using Type2 but reporting TypeDeroffManParser
for line in built_command_output:
output_file.write(line)
- output_file.write('\n')
- output_file.write('\n')
- add_diagnostic(manpage_path + ' parsed successfully')
+ output_file.write("\n")
+ output_file.write("\n")
+ add_diagnostic(manpage_path + " parsed successfully")
if output_file != sys.stdout:
output_file.close()
else:
- parser_names = ', '.join(p.__class__.__name__ for p in parsersToTry)
- #add_diagnostic('%s contains no options or is unparsable' % manpage_path, BRIEF_VERBOSE)
- add_diagnostic('%s contains no options or is unparsable (tried parser %s)' % (manpage_path, parser_names), BRIEF_VERBOSE)
+ parser_names = ", ".join(p.__class__.__name__ for p in parsersToTry)
+ # add_diagnostic('%s contains no options or is unparsable' % manpage_path, BRIEF_VERBOSE)
+ add_diagnostic(
+ "%s contains no options or is unparsable (tried parser %s)"
+ % (manpage_path, parser_names),
+ BRIEF_VERBOSE,
+ )
return success
+
def parse_and_output_man_pages(paths, output_directory, show_progress):
global diagnostic_indent, CMDNAME
paths.sort()
@@ -802,14 +877,18 @@ def parse_and_output_man_pages(paths, output_directory, show_progress):
padding_len = len(str(total_count))
last_progress_string_length = 0
if show_progress and not WRITE_TO_STDOUT:
- print("Parsing man pages and writing completions to {0}".format(output_directory))
+ print(
+ "Parsing man pages and writing completions to {0}".format(output_directory)
+ )
man_page_suffixes = set([os.path.splitext(m)[1][1:] for m in paths])
lzma_xz_occurs = "xz" in man_page_suffixes or "lzma" in man_page_suffixes
if lzma_xz_occurs and not lzma_available:
- add_diagnostic('At least one man page is compressed with lzma or xz, but the "lzma" module is not available.'
- ' Any man page compressed with either will be skipped.',
- NOT_VERBOSE)
+ add_diagnostic(
+ 'At least one man page is compressed with lzma or xz, but the "lzma" module is not available.'
+ " Any man page compressed with either will be skipped.",
+ NOT_VERBOSE,
+ )
flush_diagnostics(sys.stderr)
for manpage_path in paths:
@@ -817,12 +896,14 @@ def parse_and_output_man_pages(paths, output_directory, show_progress):
# Get the "base" command, e.g. gcc.1.gz -> gcc
man_file_name = os.path.basename(manpage_path)
- CMDNAME = man_file_name.split('.', 1)[0]
- output_file_name = CMDNAME + '.fish'
+ CMDNAME = man_file_name.split(".", 1)[0]
+ output_file_name = CMDNAME + ".fish"
# Show progress if we're doing that
if show_progress:
- progress_str = ' {0} / {1} : {2}'.format((str(index).rjust(padding_len)), total_count, man_file_name)
+ progress_str = " {0} / {1} : {2}".format(
+ (str(index).rjust(padding_len)), total_count, man_file_name
+ )
# Pad on the right with spaces so we overwrite whatever we wrote last time
padded_progress_str = progress_str.ljust(last_progress_string_length)
last_progress_string_length = len(progress_str)
@@ -844,52 +925,64 @@ def parse_and_output_man_pages(paths, output_directory, show_progress):
successful_count += 1
except IOError:
diagnostic_indent = 0
- add_diagnostic('Cannot open ' + manpage_path)
+ add_diagnostic("Cannot open " + manpage_path)
except (KeyboardInterrupt, SystemExit):
raise
except:
- add_diagnostic('Error parsing %s: %s' % (manpage_path, sys.exc_info()[0]), BRIEF_VERBOSE)
+ add_diagnostic(
+ "Error parsing %s: %s" % (manpage_path, sys.exc_info()[0]),
+ BRIEF_VERBOSE,
+ )
flush_diagnostics(sys.stderr)
traceback.print_exc(file=sys.stderr)
flush_diagnostics(sys.stderr)
- print("") #Newline after loop
- add_diagnostic("Successfully parsed %d / %d pages" % (successful_count, total_count), BRIEF_VERBOSE)
+ print("") # Newline after loop
+ add_diagnostic(
+ "Successfully parsed %d / %d pages" % (successful_count, total_count),
+ BRIEF_VERBOSE,
+ )
flush_diagnostics(sys.stderr)
+
def get_paths_from_man_locations():
# Return all the paths to man(1) and man(8) files in the manpath
import subprocess, os
+
proc = None
# $MANPATH takes precedence, just like with `man` on the CLI.
if os.getenv("MANPATH"):
- parent_paths = os.getenv("MANPATH").strip().split(':')
+ parent_paths = os.getenv("MANPATH").strip().split(":")
else:
# Some systems have manpath, others have `man --path` (like Haiku).
- for prog in [['manpath'], ['man', '--path']]:
+ for prog in [["manpath"], ["man", "--path"]]:
try:
- proc = subprocess.Popen(prog, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- except OSError: # Command does not exist, keep trying
+ proc = subprocess.Popen(
+ prog, stdout=subprocess.PIPE, stderr=subprocess.PIPE
+ )
+ except OSError: # Command does not exist, keep trying
continue
- break # Command exists, use it.
+ break # Command exists, use it.
manpath, err_data = proc.communicate()
- parent_paths = manpath.decode().strip().split(':')
+ parent_paths = manpath.decode().strip().split(":")
if (not parent_paths) or (proc and proc.returncode > 0):
# HACK: Use some fallbacks in case we can't get anything else.
# `mandoc` does not provide `manpath` or `man --path` and $MANPATH might not be set.
# The alternative is reading its config file (/etc/man.conf)
- if os.path.isfile('/etc/man.conf'):
- data = open('/etc/man.conf', 'r')
+ if os.path.isfile("/etc/man.conf"):
+ data = open("/etc/man.conf", "r")
for line in data:
- if ('manpath' in line or 'MANPATH' in line):
- p = line.split(' ')[1]
+ if "manpath" in line or "MANPATH" in line:
+ p = line.split(" ")[1]
p = p.split()[0]
parent_paths.append(p)
- if (not parent_paths):
- sys.stderr.write("Unable to get the manpath, falling back to /usr/share/man:/usr/local/share/man. Please set $MANPATH if that is not correct.\n")
+ if not parent_paths:
+ sys.stderr.write(
+ "Unable to get the manpath, falling back to /usr/share/man:/usr/local/share/man. Please set $MANPATH if that is not correct.\n"
+ )
parent_paths = ["/usr/share/man", "/usr/local/share/man"]
result = []
for parent_path in parent_paths:
- for section in ['man1', 'man6', 'man8']:
+ for section in ["man1", "man6", "man8"]:
directory_path = os.path.join(parent_path, section)
try:
names = os.listdir(directory_path)
@@ -900,23 +993,43 @@ def get_paths_from_man_locations():
result.append(os.path.join(directory_path, name))
return result
+
def usage(script_name):
- print("Usage: {0} [-v, --verbose] [-s, --stdout] [-d, --directory] [-p, --progress] files...".format(script_name))
- print("""Command options are:
+ print(
+ "Usage: {0} [-v, --verbose] [-s, --stdout] [-d, --directory] [-p, --progress] files...".format(
+ script_name
+ )
+ )
+ print(
+ """Command options are:
-h, --help\t\tShow this help message
-v, --verbose [0, 1, 2]\tShow debugging output to stderr. Larger is more verbose.
-s, --stdout\tWrite all completions to stdout (trumps the --directory option)
-d, --directory [dir]\tWrite all completions to the given directory, instead of to ~/.local/share/fish/generated_completions
-m, --manpath\tProcess all man1 and man8 files available in the manpath (as determined by manpath)
-p, --progress\tShow progress
- """)
+ """
+ )
+
if __name__ == "__main__":
script_name = sys.argv[0]
try:
- opts, file_paths = getopt.gnu_getopt(sys.argv[1:], 'v:sd:hmpc:z', ['verbose=', 'stdout', 'directory=', 'cleanup-in=', 'help', 'manpath', 'progress'])
+ opts, file_paths = getopt.gnu_getopt(
+ sys.argv[1:],
+ "v:sd:hmpc:z",
+ [
+ "verbose=",
+ "stdout",
+ "directory=",
+ "cleanup-in=",
+ "help",
+ "manpath",
+ "progress",
+ ],
+ )
except getopt.GetoptError as err:
- print(err.msg) # will print something like "option -a not recognized"
+ print(err.msg) # will print something like "option -a not recognized"
usage(script_name)
sys.exit(2)
@@ -926,24 +1039,24 @@ if __name__ == "__main__":
cleanup_directories = []
use_manpath, show_progress, custom_dir = False, False, False
- output_directory = ''
+ output_directory = ""
for opt, value in opts:
- if opt in ('-v', '--verbose'):
+ if opt in ("-v", "--verbose"):
VERBOSITY = int(value)
- elif opt in ('-s', '--stdout'):
+ elif opt in ("-s", "--stdout"):
WRITE_TO_STDOUT = True
- elif opt in ('-d', '--directory'):
+ elif opt in ("-d", "--directory"):
output_directory = value
- elif opt in ('-h', '--help'):
+ elif opt in ("-h", "--help"):
usage(script_name)
sys.exit(0)
- elif opt in ('-m', '--manpath'):
+ elif opt in ("-m", "--manpath"):
use_manpath = True
- elif opt in ('-p', '--progress'):
+ elif opt in ("-p", "--progress"):
show_progress = True
- elif opt in ('-c', '--cleanup-in'):
+ elif opt in ("-c", "--cleanup-in"):
cleanup_directories.append(value)
- elif opt in ('-z',):
+ elif opt in ("-z",):
DEROFF_ONLY = True
else:
assert False, "unhandled option"
@@ -963,8 +1076,10 @@ if __name__ == "__main__":
if not WRITE_TO_STDOUT and not output_directory:
# Default to ~/.local/share/fish/generated_completions/
# Create it if it doesn't exist
- xdg_data_home = os.getenv('XDG_DATA_HOME', '~/.local/share')
- output_directory = os.path.expanduser(xdg_data_home + '/fish/generated_completions/')
+ xdg_data_home = os.getenv("XDG_DATA_HOME", "~/.local/share")
+ output_directory = os.path.expanduser(
+ xdg_data_home + "/fish/generated_completions/"
+ )
try:
os.makedirs(output_directory)
except OSError as e:
diff --git a/share/tools/deroff.py b/share/tools/deroff.py
index ac3d89650..84d20e544 100755
--- a/share/tools/deroff.py
+++ b/share/tools/deroff.py
@@ -6,291 +6,297 @@ import sys, re, string
IS_PY3 = sys.version_info[0] >= 3
+
class Deroffer:
g_specs_specletter = {
# Output composed latin1 letters
- '-D': '\320',
- 'Sd': '\360',
- 'Tp': '\376',
- 'TP': '\336',
- 'AE': '\306',
- 'ae': '\346',
- 'OE': "OE",
- 'oe': "oe",
- ':a': '\344',
- ':A': '\304',
- ':e': '\353',
- ':E': '\313',
- ':i': '\357',
- ':I': '\317',
- ':o': '\366',
- ':O': '\326',
- ':u': '\374',
- ':U': '\334',
- ':y': '\377',
- 'ss': '\337',
- '\'A': '\301',
- '\'E': '\311',
- '\'I': '\315',
- '\'O': '\323',
- '\'U': '\332',
- '\'Y': '\335',
- '\'a': '\341',
- '\'e': '\351',
- '\'i': '\355',
- '\'o': '\363',
- '\'u': '\372',
- '\'y': '\375',
- '^A': '\302',
- '^E': '\312',
- '^I': '\316',
- '^O': '\324',
- '^U': '\333',
- '^a': '\342',
- '^e': '\352',
- '^i': '\356',
- '^o': '\364',
- '^u': '\373',
- '`A': '\300',
- '`E': '\310',
- '`I': '\314',
- '`O': '\322',
- '`U': '\331',
- '`a': '\340',
- '`e': '\350',
- '`i': '\354',
- '`o': '\362',
- '`u': '\371',
- '~A': '\303',
- '~N': '\321',
- '~O': '\325',
- '~a': '\343',
- '~n': '\361',
- '~o': '\365',
- ',C': '\307',
- ',c': '\347',
- '/l': "/l",
- '/L': "/L",
- '/o': '\370',
- '/O': '\330',
- 'oA': '\305',
- 'oa': '\345',
-
+ "-D": "\320",
+ "Sd": "\360",
+ "Tp": "\376",
+ "TP": "\336",
+ "AE": "\306",
+ "ae": "\346",
+ "OE": "OE",
+ "oe": "oe",
+ ":a": "\344",
+ ":A": "\304",
+ ":e": "\353",
+ ":E": "\313",
+ ":i": "\357",
+ ":I": "\317",
+ ":o": "\366",
+ ":O": "\326",
+ ":u": "\374",
+ ":U": "\334",
+ ":y": "\377",
+ "ss": "\337",
+ "'A": "\301",
+ "'E": "\311",
+ "'I": "\315",
+ "'O": "\323",
+ "'U": "\332",
+ "'Y": "\335",
+ "'a": "\341",
+ "'e": "\351",
+ "'i": "\355",
+ "'o": "\363",
+ "'u": "\372",
+ "'y": "\375",
+ "^A": "\302",
+ "^E": "\312",
+ "^I": "\316",
+ "^O": "\324",
+ "^U": "\333",
+ "^a": "\342",
+ "^e": "\352",
+ "^i": "\356",
+ "^o": "\364",
+ "^u": "\373",
+ "`A": "\300",
+ "`E": "\310",
+ "`I": "\314",
+ "`O": "\322",
+ "`U": "\331",
+ "`a": "\340",
+ "`e": "\350",
+ "`i": "\354",
+ "`o": "\362",
+ "`u": "\371",
+ "~A": "\303",
+ "~N": "\321",
+ "~O": "\325",
+ "~a": "\343",
+ "~n": "\361",
+ "~o": "\365",
+ ",C": "\307",
+ ",c": "\347",
+ "/l": "/l",
+ "/L": "/L",
+ "/o": "\370",
+ "/O": "\330",
+ "oA": "\305",
+ "oa": "\345",
# Ligatures
- 'fi': 'fi',
- 'ff': 'ff',
- 'fl': 'fl',
-
- 'Fi': 'ffi',
- 'Ff': 'fff',
- 'Fl': 'ffl'
+ "fi": "fi",
+ "ff": "ff",
+ "fl": "fl",
+ "Fi": "ffi",
+ "Ff": "fff",
+ "Fl": "ffl",
}
g_specs = {
- 'mi': '-',
- 'en': '-',
- 'hy': '-',
- 'em': "--",
- 'lq': '“',
- 'rq': '”',
- 'Bq': ",,",
- 'oq': '`',
- 'cq': '\'',
- 'aq': '\'',
- 'dq': '"',
- 'or': '|',
- 'at': '@',
- 'sh': '#',
- 'Eu': '\244',
- 'eu': '\244',
- 'Do': '$',
- 'ct': '\242',
- 'Fo': '\253',
- 'Fc': '\273',
- 'fo': '<',
- 'fc': '>',
- 'r!': '\241',
- 'r?': '\277',
- 'Of': '\252',
- 'Om': '\272',
- 'pc': '\267',
- 'S1': '\271',
- 'S2': '\262',
- 'S3': '\263',
- '<-': "<-",
- '->': "->",
- '<>': "<->",
- 'ua': '^',
- 'da': 'v',
- 'lA': "<=",
- 'rA': "=>",
- 'hA': "<=>",
- 'uA': "^^",
- 'dA': "vv",
- 'ba': '|',
- 'bb': '|',
- 'br': '|',
- 'bv': '|',
- 'ru': '_',
- 'ul': '_',
- 'ci': 'O',
- 'bu': 'o',
- 'co': '\251',
- 'rg': '\256',
- 'tm': "(TM)",
- 'dd': "||",
- 'dg': '|',
- 'ps': '\266',
- 'sc': '\247',
- 'de': '\260',
- '%0': "0/00",
- '14': '\274',
- '12': '\275',
- '34': '\276',
- 'f/': '/',
- 'sl': '/',
- 'rs': '\\',
- 'sq': "[]",
- 'fm': '\'',
- 'ha': '^',
- 'ti': '~',
- 'lB': '[',
- 'rB': ']',
- 'lC': '{',
- 'rC': '}',
- 'la': '<',
- 'ra': '>',
- 'lh': "<=",
- 'rh': "=>",
- 'tf': "therefore",
- '~~': "~~",
- '~=': "~=",
- '!=': "!=",
- '**': '*',
- '+-': '\261',
- '<=': "<=",
- '==': "==",
- '=~': "=~",
- '>=': ">=",
- 'AN': "\\/",
- 'OR': "/\\",
- 'no': '\254',
- 'te': "there exists",
- 'fa': "for all",
- 'Ah': "aleph",
- 'Im': "imaginary",
- 'Re': "real",
- 'if': "infinity",
- 'md': "\267",
- 'mo': "member of",
- 'mu': '\327',
- 'nm': "not member of",
- 'pl': '+',
- 'eq': '=',
- 'pt': "oc",
- 'pp': "perpendicular",
- 'sb': "(=",
- 'sp': "=)",
- 'ib': "(-",
- 'ip': "-)",
- 'ap': '~',
- 'is': 'I',
- 'sr': "root",
- 'pd': 'd',
- 'c*': "(x)",
- 'c+': "(+)",
- 'ca': "cap",
- 'cu': 'U',
- 'di': '\367',
- 'gr': 'V',
- 'es': "{}",
- 'CR': "_|",
- 'st': "such that",
- '/_': "/_",
- 'lz': "<>",
- 'an': '-',
-
+ "mi": "-",
+ "en": "-",
+ "hy": "-",
+ "em": "--",
+ "lq": "“",
+ "rq": "”",
+ "Bq": ",,",
+ "oq": "`",
+ "cq": "'",
+ "aq": "'",
+ "dq": '"',
+ "or": "|",
+ "at": "@",
+ "sh": "#",
+ "Eu": "\244",
+ "eu": "\244",
+ "Do": "$",
+ "ct": "\242",
+ "Fo": "\253",
+ "Fc": "\273",
+ "fo": "<",
+ "fc": ">",
+ "r!": "\241",
+ "r?": "\277",
+ "Of": "\252",
+ "Om": "\272",
+ "pc": "\267",
+ "S1": "\271",
+ "S2": "\262",
+ "S3": "\263",
+ "<-": "<-",
+ "->": "->",
+ "<>": "<->",
+ "ua": "^",
+ "da": "v",
+ "lA": "<=",
+ "rA": "=>",
+ "hA": "<=>",
+ "uA": "^^",
+ "dA": "vv",
+ "ba": "|",
+ "bb": "|",
+ "br": "|",
+ "bv": "|",
+ "ru": "_",
+ "ul": "_",
+ "ci": "O",
+ "bu": "o",
+ "co": "\251",
+ "rg": "\256",
+ "tm": "(TM)",
+ "dd": "||",
+ "dg": "|",
+ "ps": "\266",
+ "sc": "\247",
+ "de": "\260",
+ "%0": "0/00",
+ "14": "\274",
+ "12": "\275",
+ "34": "\276",
+ "f/": "/",
+ "sl": "/",
+ "rs": "\\",
+ "sq": "[]",
+ "fm": "'",
+ "ha": "^",
+ "ti": "~",
+ "lB": "[",
+ "rB": "]",
+ "lC": "{",
+ "rC": "}",
+ "la": "<",
+ "ra": ">",
+ "lh": "<=",
+ "rh": "=>",
+ "tf": "therefore",
+ "~~": "~~",
+ "~=": "~=",
+ "!=": "!=",
+ "**": "*",
+ "+-": "\261",
+ "<=": "<=",
+ "==": "==",
+ "=~": "=~",
+ ">=": ">=",
+ "AN": "\\/",
+ "OR": "/\\",
+ "no": "\254",
+ "te": "there exists",
+ "fa": "for all",
+ "Ah": "aleph",
+ "Im": "imaginary",
+ "Re": "real",
+ "if": "infinity",
+ "md": "\267",
+ "mo": "member of",
+ "mu": "\327",
+ "nm": "not member of",
+ "pl": "+",
+ "eq": "=",
+ "pt": "oc",
+ "pp": "perpendicular",
+ "sb": "(=",
+ "sp": "=)",
+ "ib": "(-",
+ "ip": "-)",
+ "ap": "~",
+ "is": "I",
+ "sr": "root",
+ "pd": "d",
+ "c*": "(x)",
+ "c+": "(+)",
+ "ca": "cap",
+ "cu": "U",
+ "di": "\367",
+ "gr": "V",
+ "es": "{}",
+ "CR": "_|",
+ "st": "such that",
+ "/_": "/_",
+ "lz": "<>",
+ "an": "-",
# Output Greek
- '*A': "Alpha",
- '*B': "Beta",
- '*C': "Xi",
- '*D': "Delta",
- '*E': "Epsilon",
- '*F': "Phi",
- '*G': "Gamma",
- '*H': "Theta",
- '*I': "Iota",
- '*K': "Kappa",
- '*L': "Lambda",
- '*M': "Mu",
- '*N': "Nu",
- '*O': "Omicron",
- '*P': "Pi",
- '*Q': "Psi",
- '*R': "Rho",
- '*S': "Sigma",
- '*T': "Tau",
- '*U': "Upsilon",
- '*W': "Omega",
- '*X': "Chi",
- '*Y': "Eta",
- '*Z': "Zeta",
- '*a': "alpha",
- '*b': "beta",
- '*c': "xi",
- '*d': "delta",
- '*e': "epsilon",
- '*f': "phi",
- '+f': "phi",
- '*g': "gamma",
- '*h': "theta",
- '+h': "theta",
- '*i': "iota",
- '*k': "kappa",
- '*l': "lambda",
- '*m': "\265",
- '*n': "nu",
- '*o': "omicron",
- '*p': "pi",
- '+p': "omega",
- '*q': "psi",
- '*r': "rho",
- '*s': "sigma",
- '*t': "tau",
- '*u': "upsilon",
- '*w': "omega",
- '*x': "chi",
- '*y': "eta",
- '*z': "zeta",
- 'ts': "sigma",
+ "*A": "Alpha",
+ "*B": "Beta",
+ "*C": "Xi",
+ "*D": "Delta",
+ "*E": "Epsilon",
+ "*F": "Phi",
+ "*G": "Gamma",
+ "*H": "Theta",
+ "*I": "Iota",
+ "*K": "Kappa",
+ "*L": "Lambda",
+ "*M": "Mu",
+ "*N": "Nu",
+ "*O": "Omicron",
+ "*P": "Pi",
+ "*Q": "Psi",
+ "*R": "Rho",
+ "*S": "Sigma",
+ "*T": "Tau",
+ "*U": "Upsilon",
+ "*W": "Omega",
+ "*X": "Chi",
+ "*Y": "Eta",
+ "*Z": "Zeta",
+ "*a": "alpha",
+ "*b": "beta",
+ "*c": "xi",
+ "*d": "delta",
+ "*e": "epsilon",
+ "*f": "phi",
+ "+f": "phi",
+ "*g": "gamma",
+ "*h": "theta",
+ "+h": "theta",
+ "*i": "iota",
+ "*k": "kappa",
+ "*l": "lambda",
+ "*m": "\265",
+ "*n": "nu",
+ "*o": "omicron",
+ "*p": "pi",
+ "+p": "omega",
+ "*q": "psi",
+ "*r": "rho",
+ "*s": "sigma",
+ "*t": "tau",
+ "*u": "upsilon",
+ "*w": "omega",
+ "*x": "chi",
+ "*y": "eta",
+ "*z": "zeta",
+ "ts": "sigma",
}
- g_re_word = re.compile(r'[a-zA-Z_]+') # equivalent to the word() method
- g_re_number = re.compile(r'[+-]?\d+') # equivalent to the number() method
- g_re_esc_char = re.compile(r"""([a-zA-Z_]) | # Word
+ g_re_word = re.compile(r"[a-zA-Z_]+") # equivalent to the word() method
+ g_re_number = re.compile(r"[+-]?\d+") # equivalent to the number() method
+ g_re_esc_char = re.compile(
+ r"""([a-zA-Z_]) | # Word
([+-]?\d) | # Number
\\ # Backslash (for escape seq)
- """, re.VERBOSE)
+ """,
+ re.VERBOSE,
+ )
- g_re_not_backslash_or_whitespace = re.compile(r'[^ \t\n\r\f\v\\]+') # Match a sequence of not backslash or whitespace
+ g_re_not_backslash_or_whitespace = re.compile(
+ r"[^ \t\n\r\f\v\\]+"
+ ) # Match a sequence of not backslash or whitespace
- g_re_newline_collapse = re.compile(r'\n{3,}')
+ g_re_newline_collapse = re.compile(r"\n{3,}")
- g_re_font = re.compile(r"""\\f( # Starts with backslash f
+ g_re_font = re.compile(
+ r"""\\f( # Starts with backslash f
(\(\S{2}) | # Open paren, then two printable chars
(\[\S*?\]) | # Open bracket, zero or more printable characters, then close bracket
\S) # Any printable character
- """, re.VERBOSE)
+ """,
+ re.VERBOSE,
+ )
# This gets filled in in __init__ below
g_macro_dict = False
def __init__(self):
self.reg_table = {}
- self.tr_from = ''
- self.tr_to = ''
- self.tr = ''
+ self.tr_from = ""
+ self.tr_to = ""
+ self.tr = ""
self.nls = 2
self.specletter = False
self.refer = False
@@ -301,13 +307,13 @@ class Deroffer:
self.pic = False
self.tbl = False
self.tblstate = 0
- self.tblTab = ''
+ self.tblTab = ""
self.eqn = False
self.skipheaders = False
self.skiplists = False
self.ignore_sonx = False
self.output = []
- self.name = ''
+ self.name = ""
self.OPTIONS = 0
self.FORMAT = 1
@@ -317,49 +323,49 @@ class Deroffer:
if not Deroffer.g_macro_dict:
Deroffer.g_macro_dict = {
- 'SH': Deroffer.macro_sh,
- 'SS': Deroffer.macro_ss_ip,
- 'IP': Deroffer.macro_ss_ip,
- 'H ': Deroffer.macro_ss_ip,
- 'I ': Deroffer.macro_i_ir,
- 'IR': Deroffer.macro_i_ir,
- 'IB': Deroffer.macro_i_ir,
- 'B ': Deroffer.macro_i_ir,
- 'BR': Deroffer.macro_i_ir,
- 'BI': Deroffer.macro_i_ir,
- 'R ': Deroffer.macro_i_ir,
- 'RB': Deroffer.macro_i_ir,
- 'RI': Deroffer.macro_i_ir,
- 'AB': Deroffer.macro_i_ir,
- 'Nm': Deroffer.macro_Nm,
- '] ': Deroffer.macro_close_bracket,
- 'PS': Deroffer.macro_ps,
- 'PE': Deroffer.macro_pe,
- 'TS': Deroffer.macro_ts,
- 'T&': Deroffer.macro_t_and,
- 'TE': Deroffer.macro_te,
- 'EQ': Deroffer.macro_eq,
- 'EN': Deroffer.macro_en,
- 'R1': Deroffer.macro_r1,
- 'R2': Deroffer.macro_r2,
- 'de': Deroffer.macro_de,
- 'BL': Deroffer.macro_bl_vl,
- 'VL': Deroffer.macro_bl_vl,
- 'AL': Deroffer.macro_bl_vl,
- 'LB': Deroffer.macro_bl_vl,
- 'RL': Deroffer.macro_bl_vl,
- 'ML': Deroffer.macro_bl_vl,
- 'DL': Deroffer.macro_bl_vl,
- 'BV': Deroffer.macro_bv,
- 'LE': Deroffer.macro_le,
- 'LP': Deroffer.macro_lp_pp,
- 'PP': Deroffer.macro_lp_pp,
- 'P\n': Deroffer.macro_lp_pp,
- 'ds': Deroffer.macro_ds,
- 'so': Deroffer.macro_so_nx,
- 'nx': Deroffer.macro_so_nx,
- 'tr': Deroffer.macro_tr,
- 'sp': Deroffer.macro_sp
+ "SH": Deroffer.macro_sh,
+ "SS": Deroffer.macro_ss_ip,
+ "IP": Deroffer.macro_ss_ip,
+ "H ": Deroffer.macro_ss_ip,
+ "I ": Deroffer.macro_i_ir,
+ "IR": Deroffer.macro_i_ir,
+ "IB": Deroffer.macro_i_ir,
+ "B ": Deroffer.macro_i_ir,
+ "BR": Deroffer.macro_i_ir,
+ "BI": Deroffer.macro_i_ir,
+ "R ": Deroffer.macro_i_ir,
+ "RB": Deroffer.macro_i_ir,
+ "RI": Deroffer.macro_i_ir,
+ "AB": Deroffer.macro_i_ir,
+ "Nm": Deroffer.macro_Nm,
+ "] ": Deroffer.macro_close_bracket,
+ "PS": Deroffer.macro_ps,
+ "PE": Deroffer.macro_pe,
+ "TS": Deroffer.macro_ts,
+ "T&": Deroffer.macro_t_and,
+ "TE": Deroffer.macro_te,
+ "EQ": Deroffer.macro_eq,
+ "EN": Deroffer.macro_en,
+ "R1": Deroffer.macro_r1,
+ "R2": Deroffer.macro_r2,
+ "de": Deroffer.macro_de,
+ "BL": Deroffer.macro_bl_vl,
+ "VL": Deroffer.macro_bl_vl,
+ "AL": Deroffer.macro_bl_vl,
+ "LB": Deroffer.macro_bl_vl,
+ "RL": Deroffer.macro_bl_vl,
+ "ML": Deroffer.macro_bl_vl,
+ "DL": Deroffer.macro_bl_vl,
+ "BV": Deroffer.macro_bv,
+ "LE": Deroffer.macro_le,
+ "LP": Deroffer.macro_lp_pp,
+ "PP": Deroffer.macro_lp_pp,
+ "P\n": Deroffer.macro_lp_pp,
+ "ds": Deroffer.macro_ds,
+ "so": Deroffer.macro_so_nx,
+ "nx": Deroffer.macro_so_nx,
+ "tr": Deroffer.macro_tr,
+ "sp": Deroffer.macro_sp,
}
def flush_output(self, where):
@@ -368,8 +374,8 @@ class Deroffer:
self.output[:] = []
def get_output(self):
- res = ''.join(self.output)
- clean_res = Deroffer.g_re_newline_collapse.sub('\n', res)
+ res = "".join(self.output)
+ clean_res = Deroffer.g_re_newline_collapse.sub("\n", res)
return clean_res
def putchar(self, c):
@@ -378,17 +384,31 @@ class Deroffer:
# This gets swapped in in place of condputs the first time tr gets modified
def condputs_tr(self, str):
- special = self.pic or self.eqn or self.refer or self.macro or (self.skiplists and self.inlist) or (self.skipheaders and self.inheader)
+ special = (
+ self.pic
+ or self.eqn
+ or self.refer
+ or self.macro
+ or (self.skiplists and self.inlist)
+ or (self.skipheaders and self.inheader)
+ )
if not special:
self.output.append(str.translate(self.tr))
def condputs(self, str):
- special = self.pic or self.eqn or self.refer or self.macro or (self.skiplists and self.inlist) or (self.skipheaders and self.inheader)
+ special = (
+ self.pic
+ or self.eqn
+ or self.refer
+ or self.macro
+ or (self.skiplists and self.inlist)
+ or (self.skipheaders and self.inheader)
+ )
if not special:
self.output.append(str)
def str_at(self, idx):
- return self.s[idx:idx+1]
+ return self.s[idx : idx + 1]
def skip_char(self, amt=1):
self.s = self.s[amt:]
@@ -398,32 +418,35 @@ class Deroffer:
def is_white(self, idx):
# Note this returns false for empty strings (idx >= len(self.s))
- return self.s[idx:idx+1].isspace()
+ return self.s[idx : idx + 1].isspace()
def str_eq(offset, other, len):
- return self.s[offset:offset+len] == other[:len]
+ return self.s[offset : offset + len] == other[:len]
def prch(self, idx):
# Note that this return False for the empty string (idx >= len(self.s))
- ch = self.s[idx:idx+1]
- return ch not in ' \t\n'
+ ch = self.s[idx : idx + 1]
+ return ch not in " \t\n"
def font(self):
match = Deroffer.g_re_font.match(self.s)
- if not match: return False
+ if not match:
+ return False
self.skip_char(match.end())
return True
def font2(self):
- if self.s[0:2] == '\\f':
+ if self.s[0:2] == "\\f":
c = self.str_at(2)
- if c == '(' and self.prch(3) and self.prch(4):
+ if c == "(" and self.prch(3) and self.prch(4):
self.skip_char(5)
return True
- elif c == '[':
+ elif c == "[":
self.skip_char(2)
- while self.prch(0) and self.str_at(0) != ']': self.skip_char()
- if self.str_at(0) == ']': self.skip_char()
+ while self.prch(0) and self.str_at(0) != "]":
+ self.skip_char()
+ if self.str_at(0) == "]":
+ self.skip_char()
elif self.prch(2):
self.skip_char(3)
return True
@@ -431,50 +454,51 @@ class Deroffer:
def comment(self):
# Here we require that the string start with \"
- while self.str_at(0) and self.str_at(0) != '\n': self.skip_char()
+ while self.str_at(0) and self.str_at(0) != "\n":
+ self.skip_char()
return True
def numreq(self):
# We require that the string starts with backslash
- if self.str_at(1) in 'hvwud' and self.str_at(2) == '\'':
+ if self.str_at(1) in "hvwud" and self.str_at(2) == "'":
self.macro += 1
self.skip_char(3)
- while self.str_at(0) != '\'' and self.esc_char():
- pass # Weird
- if self.str_at(0) == '\'':
+ while self.str_at(0) != "'" and self.esc_char():
+ pass # Weird
+ if self.str_at(0) == "'":
self.skip_char()
self.macro -= 1
return True
return False
def var(self):
- reg = ''
+ reg = ""
s0s1 = self.s[0:2]
- if s0s1 == '\\n':
- if self.s[3:5] == 'dy':
+ if s0s1 == "\\n":
+ if self.s[3:5] == "dy":
self.skip_char(5)
return True
- elif self.str_at(2) == '(' and self.prch(3) and self.prch(4):
+ elif self.str_at(2) == "(" and self.prch(3) and self.prch(4):
self.skip_char(5)
return True
- elif self.str_at(2) == '[' and self.prch(3):
+ elif self.str_at(2) == "[" and self.prch(3):
self.skip_char(3)
- while self.str_at(0) and self.str_at(0) != ']':
+ while self.str_at(0) and self.str_at(0) != "]":
self.skip_char()
return True
elif self.prch(2):
self.skip_char(3)
return True
- elif s0s1 == '\\*':
- if self.str_at(2) == '(' and self.prch(3) and self.prch(4):
+ elif s0s1 == "\\*":
+ if self.str_at(2) == "(" and self.prch(3) and self.prch(4):
reg = self.s[3:5]
self.skip_char(5)
- elif self.str_at(2) == '[' and self.prch(3):
+ elif self.str_at(2) == "[" and self.prch(3):
self.skip_char(3)
- while self.str_at(0) and self.str_at(0) != ']':
+ while self.str_at(0) and self.str_at(0) != "]":
reg = reg + self.str_at(0)
self.skip_char()
- if self.s[0:1] == ']':
+ if self.s[0:1] == "]":
self.skip_char()
else:
return False
@@ -493,15 +517,16 @@ class Deroffer:
def size(self):
# We require that the string starts with \s
- if self.digit(2) or (self.str_at(2) in '-+' and self.digit(3)):
+ if self.digit(2) or (self.str_at(2) in "-+" and self.digit(3)):
self.skip_char(3)
- while self.digit(0): self.skip_char()
+ while self.digit(0):
+ self.skip_char()
return True
return False
def spec(self):
self.specletter = False
- if self.s[0:2] == '\\(' and self.prch(2) and self.prch(3):
+ if self.s[0:2] == "\\(" and self.prch(2) and self.prch(3):
key = self.s[2:4]
if key in Deroffer.g_specs_specletter:
self.condputs(Deroffer.g_specs_specletter[key])
@@ -510,7 +535,7 @@ class Deroffer:
self.condputs(Deroffer.g_specs[key])
self.skip_char(4)
return True
- elif self.s.startswith('\\%'):
+ elif self.s.startswith("\\%"):
self.specletter = True
self.skip_char(2)
return True
@@ -520,14 +545,15 @@ class Deroffer:
def esc(self):
# We require that the string start with backslash
c = self.s[1:2]
- if not c: return False
- if c in 'eE':
- self.condputs('\\')
- elif c in 't':
- self.condputs('\t')
- elif c in '0~':
- self.condputs(' ')
- elif c in '|^&:':
+ if not c:
+ return False
+ if c in "eE":
+ self.condputs("\\")
+ elif c in "t":
+ self.condputs("\t")
+ elif c in "0~":
+ self.condputs(" ")
+ elif c in "|^&:":
pass
else:
self.condputs(c)
@@ -538,24 +564,25 @@ class Deroffer:
got_something = False
while True:
match = Deroffer.g_re_word.match(self.s)
- if not match: break
+ if not match:
+ break
got_something = True
self.condputs(match.group(0))
self.skip_char(match.end(0))
# Consume all specials
while self.spec():
- if not self.specletter: break
+ if not self.specletter:
+ break
return got_something
-
def text(self):
while True:
- idx = self.s.find('\\')
+ idx = self.s.find("\\")
if idx == -1:
self.condputs(self.s)
- self.s = ''
+ self.s = ""
break
else:
self.condputs(self.s[:idx])
@@ -567,8 +594,7 @@ class Deroffer:
def letter(self, idx):
ch = self.str_at(idx)
- return ch.isalpha() or ch == '_' # underscore is used in C identifiers
-
+ return ch.isalpha() or ch == "_" # underscore is used in C identifiers
def digit(self, idx):
ch = self.str_at(idx)
@@ -588,22 +614,21 @@ class Deroffer:
c = self.s[1:2]
if c == '"':
return self.comment()
- elif c == 'f':
+ elif c == "f":
return self.font()
- elif c == 's':
+ elif c == "s":
return self.size()
- elif c in 'hvwud':
+ elif c in "hvwud":
return self.numreq()
- elif c in 'n*':
+ elif c in "n*":
return self.var()
- elif c == '(':
+ elif c == "(":
return self.spec()
else:
return self.esc()
-
def esc_char(self):
- if self.s[0:1] == '\\':
+ if self.s[0:1] == "\\":
return self.esc_char_backslash()
return self.word() or self.number()
@@ -643,8 +668,6 @@ class Deroffer:
self.skip_char()
got_something = True
-
-
def text_arg2(self):
if not self.esc_char():
if self.s and not self.is_white(0):
@@ -660,10 +683,9 @@ class Deroffer:
else:
return True
-
# Macro functions
def macro_sh(self):
- for header_str in [' SYNOPSIS', ' "SYNOPSIS', ' ‹BERSICHT', ' "‹BERSICHT']:
+ for header_str in [" SYNOPSIS", ' "SYNOPSIS', " ‹BERSICHT", ' "‹BERSICHT']:
if self.s[2:].startswith(header_str):
self.inheader = True
break
@@ -681,10 +703,10 @@ class Deroffer:
return False
def macro_Nm(self):
- if self.s == 'Nm\n':
+ if self.s == "Nm\n":
self.condputs(self.name)
else:
- self.name = self.s[3:].strip() + ' '
+ self.name = self.s[3:].strip() + " "
return True
def macro_close_bracket(self):
@@ -692,72 +714,84 @@ class Deroffer:
return False
def macro_ps(self):
- if self.is_white(2): self.pic = True
- self.condputs('\n')
+ if self.is_white(2):
+ self.pic = True
+ self.condputs("\n")
return True
def macro_pe(self):
- if self.is_white(2): self.pic = False
- self.condputs('\n')
+ if self.is_white(2):
+ self.pic = False
+ self.condputs("\n")
return True
def macro_ts(self):
- if self.is_white(2): self.tbl, self.tblstate = True, self.OPTIONS
- self.condputs('\n')
+ if self.is_white(2):
+ self.tbl, self.tblstate = True, self.OPTIONS
+ self.condputs("\n")
return True
def macro_t_and(self):
- if self.is_white(2): self.tbl, self.tblstate = True, self.FORMAT
- self.condputs('\n')
+ if self.is_white(2):
+ self.tbl, self.tblstate = True, self.FORMAT
+ self.condputs("\n")
return True
def macro_te(self):
- if self.is_white(2): self.tbl = False
- self.condputs('\n')
+ if self.is_white(2):
+ self.tbl = False
+ self.condputs("\n")
return True
def macro_eq(self):
- if self.is_white(2): self.eqn = True
- self.condputs('\n')
+ if self.is_white(2):
+ self.eqn = True
+ self.condputs("\n")
return True
def macro_en(self):
- if self.is_white(2): self.eqn = False
- self.condputs('\n')
+ if self.is_white(2):
+ self.eqn = False
+ self.condputs("\n")
return True
def macro_r1(self):
- if self.is_white(2): self.refer2 = True
- self.condputs('\n')
+ if self.is_white(2):
+ self.refer2 = True
+ self.condputs("\n")
return True
def macro_r2(self):
- if self.is_white(2): self.refer2 = False
- self.condputs('\n')
+ if self.is_white(2):
+ self.refer2 = False
+ self.condputs("\n")
return True
def macro_de(self):
- macro=True
- self.condputs('\n')
+ macro = True
+ self.condputs("\n")
return True
def macro_bl_vl(self):
- if self.is_white(2): self.inlist = True
- self.condputs('\n')
+ if self.is_white(2):
+ self.inlist = True
+ self.condputs("\n")
return True
def macro_bv(self):
- if self.str_at(2) == 'L' and self.white(self.str_at(3)): self.inlist = True
- self.condputs('\n')
+ if self.str_at(2) == "L" and self.white(self.str_at(3)):
+ self.inlist = True
+ self.condputs("\n")
return True
def macro_le(self):
- if self.is_white(2): self.inlist = False
- self.condputs('\n')
+ if self.is_white(2):
+ self.inlist = False
+ self.condputs("\n")
return True
def macro_lp_pp(self):
- self.condputs('\n')
+ self.condputs("\n")
return True
def macro_ds(self):
@@ -770,7 +804,7 @@ class Deroffer:
name, value = comps
value = value.rstrip()
self.reg_table[name] = value
- self.condputs('\n')
+ self.condputs("\n")
return True
def macro_so_nx(self):
@@ -782,51 +816,52 @@ class Deroffer:
def macro_tr(self):
self.skip_char(2)
self.skip_leading_whitespace()
- while self.s and self.str_at(0) != '\n':
+ while self.s and self.str_at(0) != "\n":
c = self.str_at(0)
ns = self.str_at(1)
self.skip_char(2)
- if not ns or ns == '\n': ns = ' '
+ if not ns or ns == "\n":
+ ns = " "
self.tr_from += c
self.tr_to += ns
# Update our table, then swap in the slower tr-savvy condputs
- try: #Python2
+ try: # Python2
self.tr = string.maketrans(self.tr_from, self.tr_to)
- except AttributeError: #Python3
+ except AttributeError: # Python3
self.tr = "".maketrans(self.tr_from, self.tr_to)
self.condputs = self.condputs_tr
return True
def macro_sp(self):
- self.condputs('\n')
+ self.condputs("\n")
return True
def macro_other(self):
- self.condputs('\n')
+ self.condputs("\n")
return True
def request_or_macro(self):
# s[0] is period or open single quote
self.skip_char()
s0 = self.s[1:2]
- if s0 == '\\':
+ if s0 == "\\":
if self.str_at(1) == '"':
- self.condputs('\n')
+ self.condputs("\n")
return True
else:
pass
- elif s0 == '[':
+ elif s0 == "[":
self.refer = True
- self.condputs('\n')
+ self.condputs("\n")
return True
- elif s0 == ']':
+ elif s0 == "]":
self.refer = False
self.skip_char()
return self.text()
- elif s0 == '.':
+ elif s0 == ".":
self.macro = False
- self.condputs('\n')
+ self.condputs("\n")
return True
self.nobody = False
@@ -836,10 +871,12 @@ class Deroffer:
if macro_func(self):
return True
- if self.skipheaders and self.nobody: return True
+ if self.skipheaders and self.nobody:
+ return True
self.skip_leading_whitespace()
- while self.s and not self.is_white(0): self.skip_char()
+ while self.s and not self.is_white(0):
+ self.skip_char()
self.skip_leading_whitespace()
while True:
if not self.quoted_arg() and not self.text_arg():
@@ -849,33 +886,32 @@ class Deroffer:
else:
return True
-
def request_or_macro2(self):
self.skip_char()
s0 = self.s[0:1]
- if s0 == '\\':
+ if s0 == "\\":
if self.str_at(1) == '"':
- self.condputs('\n')
+ self.condputs("\n")
return True
else:
pass
- elif s0 == '[':
+ elif s0 == "[":
self.refer = True
- self.condputs('\n')
+ self.condputs("\n")
return True
- elif s0 == ']':
+ elif s0 == "]":
self.refer = False
self.skip_char()
return self.text()
- elif s0 == '.':
+ elif s0 == ".":
self.macro = False
- self.condputs('\n')
+ self.condputs("\n")
return True
self.nobody = False
s0s1 = self.s[0:2]
- if s0s1 == 'SH':
- for header_str in [' SYNOPSIS', ' "SYNOPSIS', ' ‹BERSICHT', ' "‹BERSICHT']:
+ if s0s1 == "SH":
+ for header_str in [" SYNOPSIS", ' "SYNOPSIS', " ‹BERSICHT", ' "‹BERSICHT']:
if self.s[2:].startswith(header_str):
self.inheader = True
break
@@ -883,68 +919,80 @@ class Deroffer:
# Did not find a header string
self.inheader = False
self.nobody = True
- elif s0s1 in ['SS', 'IP', 'H ']:
+ elif s0s1 in ["SS", "IP", "H "]:
self.nobody = True
- elif s0s1 in ['I ', 'IR', 'IB', 'B ', 'BR', 'BI', 'R ', 'RB', 'RI', 'AB']:
+ elif s0s1 in ["I ", "IR", "IB", "B ", "BR", "BI", "R ", "RB", "RI", "AB"]:
pass
- elif s0s1 in ['] ']:
+ elif s0s1 in ["] "]:
self.refer = False
- elif s0s1 in ['PS']:
- if self.is_white(2): self.pic = True
- self.condputs('\n')
+ elif s0s1 in ["PS"]:
+ if self.is_white(2):
+ self.pic = True
+ self.condputs("\n")
return True
- elif s0s1 in ['PE']:
- if self.is_white(2): self.pic = False
- self.condputs('\n')
+ elif s0s1 in ["PE"]:
+ if self.is_white(2):
+ self.pic = False
+ self.condputs("\n")
return True
- elif s0s1 in ['TS']:
- if self.is_white(2): self.tbl, self.tblstate = True, self.OPTIONS
- self.condputs('\n')
+ elif s0s1 in ["TS"]:
+ if self.is_white(2):
+ self.tbl, self.tblstate = True, self.OPTIONS
+ self.condputs("\n")
return True
- elif s0s1 in ['T&']:
- if self.is_white(2): self.tbl, self.tblstate = True, self.FORMAT
- self.condputs('\n')
+ elif s0s1 in ["T&"]:
+ if self.is_white(2):
+ self.tbl, self.tblstate = True, self.FORMAT
+ self.condputs("\n")
return True
- elif s0s1 in ['TE']:
- if self.is_white(2): self.tbl = False
- self.condputs('\n')
+ elif s0s1 in ["TE"]:
+ if self.is_white(2):
+ self.tbl = False
+ self.condputs("\n")
return True
- elif s0s1 in ['EQ']:
- if self.is_white(2): self.eqn = True
- self.condputs('\n')
+ elif s0s1 in ["EQ"]:
+ if self.is_white(2):
+ self.eqn = True
+ self.condputs("\n")
return True
- elif s0s1 in ['EN']:
- if self.is_white(2): self.eqn = False
- self.condputs('\n')
+ elif s0s1 in ["EN"]:
+ if self.is_white(2):
+ self.eqn = False
+ self.condputs("\n")
return True
- elif s0s1 in ['R1']:
- if self.is_white(2): self.refer2 = True
- self.condputs('\n')
+ elif s0s1 in ["R1"]:
+ if self.is_white(2):
+ self.refer2 = True
+ self.condputs("\n")
return True
- elif s0s1 in ['R2']:
- if self.is_white(2): self.refer2 = False
- self.condputs('\n')
+ elif s0s1 in ["R2"]:
+ if self.is_white(2):
+ self.refer2 = False
+ self.condputs("\n")
return True
- elif s0s1 in ['de']:
- macro=True
- self.condputs('\n')
+ elif s0s1 in ["de"]:
+ macro = True
+ self.condputs("\n")
return True
- elif s0s1 in ['BL', 'VL', 'AL', 'LB', 'RL', 'ML', 'DL']:
- if self.is_white(2): self.inlist = True
- self.condputs('\n')
+ elif s0s1 in ["BL", "VL", "AL", "LB", "RL", "ML", "DL"]:
+ if self.is_white(2):
+ self.inlist = True
+ self.condputs("\n")
return True
- elif s0s1 in ['BV']:
- if self.str_at(2) == 'L' and self.white(self.str_at(3)): self.inlist = True
- self.condputs('\n')
+ elif s0s1 in ["BV"]:
+ if self.str_at(2) == "L" and self.white(self.str_at(3)):
+ self.inlist = True
+ self.condputs("\n")
return True
- elif s0s1 in ['LE']:
- if self.is_white(2): self.inlist = False
- self.condputs('\n')
+ elif s0s1 in ["LE"]:
+ if self.is_white(2):
+ self.inlist = False
+ self.condputs("\n")
return True
- elif s0s1 in ['LP', 'PP', 'P\n']:
- self.condputs('\n')
+ elif s0s1 in ["LP", "PP", "P\n"]:
+ self.condputs("\n")
return True
- elif s0s1 in ['ds']:
+ elif s0s1 in ["ds"]:
self.skip_char(2)
self.skip_leading_whitespace()
if self.str_at(0):
@@ -954,43 +1002,46 @@ class Deroffer:
name, value = comps
value = value.rstrip()
self.reg_table[name] = value
- self.condputs('\n')
+ self.condputs("\n")
return True
- elif s0s1 in ['so', 'nx']:
+ elif s0s1 in ["so", "nx"]:
# We always ignore include directives
# deroff.c for some reason allowed this to fall through to the 'tr' case
# I think that was just a bug so I won't replicate it
return True
- elif s0s1 in ['tr']:
+ elif s0s1 in ["tr"]:
self.skip_char(2)
self.skip_leading_whitespace()
- while self.s and self.str_at(0) != '\n':
+ while self.s and self.str_at(0) != "\n":
c = self.str_at(0)
ns = self.str_at(1)
self.skip_char(2)
- if not ns or ns == '\n': ns = ' '
+ if not ns or ns == "\n":
+ ns = " "
self.tr_from += c
self.tr_to += ns
# Update our table, then swap in the slower tr-savvy condputs
- try: #Python2
+ try: # Python2
self.tr = string.maketrans(self.tr_from, self.tr_to)
- except AttributeError: #Python3
+ except AttributeError: # Python3
self.tr = "".maketrans(self.tr_from, self.tr_to)
self.condputs = self.condputs_tr
return True
- elif s0s1 in ['sp']:
- self.condputs('\n')
+ elif s0s1 in ["sp"]:
+ self.condputs("\n")
return True
else:
- self.condputs('\n')
+ self.condputs("\n")
return True
- if self.skipheaders and self.nobody: return True
+ if self.skipheaders and self.nobody:
+ return True
self.skip_leading_whitespace()
- while self.s and not self.is_white(0): self.skip_char()
+ while self.s and not self.is_white(0):
+ self.skip_char()
self.skip_leading_whitespace()
while True:
if not self.quoted_arg() and not self.text_arg():
@@ -1000,61 +1051,63 @@ class Deroffer:
else:
return True
-
def do_tbl(self):
if self.tblstate == self.OPTIONS:
- while self.s and self.str_at(0) != ';' and self.str_at(0) != '\n':
+ while self.s and self.str_at(0) != ";" and self.str_at(0) != "\n":
self.skip_leading_whitespace()
if not self.str_at(0).isalpha():
# deroff.c has a bug where it can loop forever here...we try to work around it
self.skip_char()
- else: # Parse option
+ else: # Parse option
option = self.s
- arg = ''
+ arg = ""
idx = 0
- while option[idx:idx+1].isalpha():
+ while option[idx : idx + 1].isalpha():
idx += 1
- if option[idx:idx+1] == '(':
+ if option[idx : idx + 1] == "(":
option = option[:idx]
- self.s = self.s[idx+1:]
+ self.s = self.s[idx + 1 :]
arg = self.s
else:
- self.s = ''
+ self.s = ""
if arg:
- idx = arg.find(')')
+ idx = arg.find(")")
if idx != -1:
arg = arg[:idx]
- self.s = self.s[idx+1:]
+ self.s = self.s[idx + 1 :]
else:
- #self.skip_char()
+ # self.skip_char()
pass
- if option.lower() == 'tab':
+ if option.lower() == "tab":
self.tblTab = arg[0:1]
self.tblstate = self.FORMAT
- self.condputs('\n')
+ self.condputs("\n")
elif self.tblstate == self.FORMAT:
- while self.s and self.str_at(0) != '.' and self.str_at(0) != '\n':
+ while self.s and self.str_at(0) != "." and self.str_at(0) != "\n":
self.skip_leading_whitespace()
- if self.str_at(0): self.skip_char()
+ if self.str_at(0):
+ self.skip_char()
- if self.str_at(0) == '.': self.tblstate = self.DATA
- self.condputs('\n')
+ if self.str_at(0) == ".":
+ self.tblstate = self.DATA
+ self.condputs("\n")
elif self.tblstate == self.DATA:
if self.tblTab:
- self.s = self.s.replace(self.tblTab, '\t')
+ self.s = self.s.replace(self.tblTab, "\t")
self.text()
return True
def do_line(self):
if self.s[0:1] in ".'":
- if not self.request_or_macro(): return False
+ if not self.request_or_macro():
+ return False
elif self.tbl:
self.do_tbl()
else:
@@ -1062,22 +1115,24 @@ class Deroffer:
return True
def deroff(self, str):
- lines = str.split('\n')
+ lines = str.split("\n")
for line in lines:
- self.s = line + '\n'
+ self.s = line + "\n"
if not self.do_line():
break
- #self.putchar('\n')
+ # self.putchar('\n')
+
def deroff_files(files):
for arg in files:
- sys.stderr.write(arg + '\n')
- if arg.endswith('.gz'):
- f = gzip.open(arg, 'r')
+ sys.stderr.write(arg + "\n")
+ if arg.endswith(".gz"):
+ f = gzip.open(arg, "r")
str = f.read()
- if IS_PY3: str = str.decode('latin-1')
+ if IS_PY3:
+ str = str.decode("latin-1")
else:
- f = open(arg, 'r')
+ f = open(arg, "r")
str = f.read()
d = Deroffer()
d.deroff(str)
@@ -1085,15 +1140,16 @@ def deroff_files(files):
f.close()
-
if __name__ == "__main__":
import gzip
+
paths = sys.argv[1:]
if True:
deroff_files(paths)
else:
import cProfile, profile, pstats
- profile.run('deroff_files(paths)', 'fooprof')
- p = pstats.Stats('fooprof')
- p.sort_stats('time').print_stats(100)
- #p.sort_stats('calls').print_callers(.5, 'startswith')
+
+ profile.run("deroff_files(paths)", "fooprof")
+ p = pstats.Stats("fooprof")
+ p.sort_stats("time").print_stats(100)
+ # p.sort_stats('calls').print_callers(.5, 'startswith')
diff --git a/share/tools/web_config/sample_prompts/debian_chroot.fish b/share/tools/web_config/sample_prompts/debian_chroot.fish
index aec17ff11..6daa90f41 100644
--- a/share/tools/web_config/sample_prompts/debian_chroot.fish
+++ b/share/tools/web_config/sample_prompts/debian_chroot.fish
@@ -23,11 +23,11 @@ function fish_prompt --description 'Write out the prompt, prepending the Debian
echo -n -s "$USER" @ (prompt_hostname) ' ' (set -q fish_color_cwd_root
and set_color $fish_color_cwd_root
or set_color $fish_color_cwd) (prompt_pwd) \
- (set_color normal) '# '
+ (set_color normal) '# '
case '*'
echo -n -s "$USER" @ (prompt_hostname) ' ' (set_color $fish_color_cwd) (prompt_pwd) \
- (set_color normal) '> '
+ (set_color normal) '> '
end
end
diff --git a/share/tools/web_config/sample_prompts/informative.fish b/share/tools/web_config/sample_prompts/informative.fish
index 072d409de..fde4c3dfd 100644
--- a/share/tools/web_config/sample_prompts/informative.fish
+++ b/share/tools/web_config/sample_prompts/informative.fish
@@ -18,13 +18,13 @@ function fish_prompt --description 'Informative prompt'
printf '%s@%s %s%s%s# ' $USER (prompt_hostname) (set -q fish_color_cwd_root
and set_color $fish_color_cwd_root
or set_color $fish_color_cwd) \
- (prompt_pwd) (set_color normal)
+ (prompt_pwd) (set_color normal)
case '*'
set -l pipestatus_string (__fish_print_pipestatus "[" "] " "|" (set_color yellow) \
(set_color bryellow) $last_pipestatus)
printf '[%s] %s%s@%s %s%s %s%s(%s)%s \f\r> ' (date "+%H:%M:%S") (set_color brblue) \
- $USER (prompt_hostname) (set_color $fish_color_cwd) $PWD "$pipestatus_string" \
- $status_color $last_status (set_color normal)
+ $USER (prompt_hostname) (set_color $fish_color_cwd) $PWD "$pipestatus_string" \
+ $status_color $last_status (set_color normal)
end
end
diff --git a/share/tools/web_config/webconfig.py b/share/tools/web_config/webconfig.py
index 1fdd83218..1832f19ac 100755
--- a/share/tools/web_config/webconfig.py
+++ b/share/tools/web_config/webconfig.py
@@ -2,6 +2,7 @@ from __future__ import unicode_literals
from __future__ import print_function
import binascii
import cgi
+
try:
from html import escape as escape_html
except ImportError:
@@ -33,27 +34,30 @@ else:
import socketserver as SocketServer
from urllib.parse import parse_qs
+
def isMacOS10_12_5_OrLater():
""" Return whether this system is macOS 10.12.5 or a later version. """
version = platform.mac_ver()[0]
- return version and LooseVersion(version) >= LooseVersion('10.12.5')
+ return version and LooseVersion(version) >= LooseVersion("10.12.5")
+
def is_wsl():
""" Return whether we are running under the Windows Subsystem for Linux """
- if 'linux' in platform.system().lower():
- with open('/proc/version', 'r') as f:
- if 'Microsoft' in f.read():
+ if "linux" in platform.system().lower():
+ with open("/proc/version", "r") as f:
+ if "Microsoft" in f.read():
return True
return False
# Disable CLI web browsers
-term = os.environ.pop('TERM', None)
+term = os.environ.pop("TERM", None)
# This import must be done with an empty $TERM, otherwise a command-line browser may be started
# which will block the whole process - see https://docs.python.org/3/library/webbrowser.html
import webbrowser
+
if term:
- os.environ['TERM'] = term
+ os.environ["TERM"] = term
try:
import json
@@ -63,8 +67,7 @@ except ImportError:
def run_fish_cmd(text):
# Ensure that fish is using UTF-8.
- ctype = os.environ.get("LC_ALL", os.environ.get("LC_CTYPE",
- os.environ.get("LANG")))
+ ctype = os.environ.get("LC_ALL", os.environ.get("LC_CTYPE", os.environ.get("LANG")))
env = None
if ctype is None or re.search(r"\.utf-?8$", ctype, flags=re.I) is None:
# override LC_CTYPE with en_US.UTF-8
@@ -74,28 +77,48 @@ def run_fish_cmd(text):
env.update(LC_CTYPE="en_US.UTF-8", LANG="en_US.UTF-8")
print("$ " + text)
- p = subprocess.Popen([FISH_BIN_PATH], stdin=subprocess.PIPE,
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
- env=env)
- out, err = p.communicate(text.encode('utf-8'))
- out = out.decode('utf-8', 'replace')
- err = err.decode('utf-8', 'replace')
+ p = subprocess.Popen(
+ [FISH_BIN_PATH],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ env=env,
+ )
+ out, err = p.communicate(text.encode("utf-8"))
+ out = out.decode("utf-8", "replace")
+ err = err.decode("utf-8", "replace")
return out, err
def escape_fish_cmd(text):
# Replace one backslash with two, and single quotes with backslash-quote
- escaped = text.replace('\\', '\\\\').replace("'", "\\'")
+ escaped = text.replace("\\", "\\\\").replace("'", "\\'")
return "'" + escaped + "'"
+
named_colors = {
- 'black': '000000', 'red': '800000', 'green': '008000', 'brown': '725000',
- 'yellow': '808000', 'blue': '000080', 'magenta': '800080',
- 'purple': '800080', 'cyan': '008080', 'grey': 'e5e5e5', 'brgrey': '555555',
- 'white': 'c0c0c0', 'brblack': '808080', 'brred': 'ff0000',
- 'brgreen': '00ff00', 'brbrown': 'ffff00', 'bryellow': 'ffff00',
- 'brblue': '0000ff', 'brmagenta': 'ff00ff', 'brpurple': 'ff00ff',
- 'brcyan': '00ffff', 'brwhite': 'ffffff'
+ "black": "000000",
+ "red": "800000",
+ "green": "008000",
+ "brown": "725000",
+ "yellow": "808000",
+ "blue": "000080",
+ "magenta": "800080",
+ "purple": "800080",
+ "cyan": "008080",
+ "grey": "e5e5e5",
+ "brgrey": "555555",
+ "white": "c0c0c0",
+ "brblack": "808080",
+ "brred": "ff0000",
+ "brgreen": "00ff00",
+ "brbrown": "ffff00",
+ "bryellow": "ffff00",
+ "brblue": "0000ff",
+ "brmagenta": "ff00ff",
+ "brpurple": "ff00ff",
+ "brcyan": "00ffff",
+ "brwhite": "ffffff",
}
bindings_blacklist = set(["self-insert", "'begin;end'"])
@@ -106,13 +129,15 @@ def parse_one_color(comp):
if comp in named_colors:
# Named color
return named_colors[comp]
- elif (re.match(r"[0-9a-fA-F]{3}", comp) is not None or
- re.match(r"[0-9a-fA-F]{6}", comp) is not None):
+ elif (
+ re.match(r"[0-9a-fA-F]{3}", comp) is not None
+ or re.match(r"[0-9a-fA-F]{6}", comp) is not None
+ ):
# Hex color
return comp
else:
# Unknown
- return ''
+ return ""
def better_color(c1, c2):
@@ -121,9 +146,9 @@ def better_color(c1, c2):
return c1
if not c1:
return c2
- if c1 == 'normal':
+ if c1 == "normal":
return c2
- if c2 == 'normal':
+ if c2 == "normal":
return c1
if c2 in named_colors:
return c1
@@ -135,93 +160,317 @@ def better_color(c1, c2):
def parse_color(color_str):
""" A basic function to parse a color string, for example, 'red' '--bold'.
"""
- comps = color_str.split(' ')
- color = 'normal'
- background_color = ''
+ comps = color_str.split(" ")
+ color = "normal"
+ background_color = ""
bold, underline, italics, dim, reverse = False, False, False, False, False
for comp in comps:
# Remove quotes
comp = comp.strip("'\" ")
- if comp == '--bold':
+ if comp == "--bold":
bold = True
- elif comp == '--underline':
+ elif comp == "--underline":
underline = True
- elif comp == '--italics':
+ elif comp == "--italics":
italics = True
- elif comp == '--dim':
+ elif comp == "--dim":
dim = True
- elif comp == '--reverse':
+ elif comp == "--reverse":
reverse = True
- elif comp.startswith('--background='):
+ elif comp.startswith("--background="):
# Background color
background_color = better_color(
- background_color, parse_one_color(comp[len('--background='):]))
+ background_color, parse_one_color(comp[len("--background=") :])
+ )
else:
# Regular color
color = better_color(color, parse_one_color(comp))
- return {"color": color, "background": background_color, "bold": bold,
- "underline": underline, "italics": italics, "dim": dim, "reverse": reverse}
+ return {
+ "color": color,
+ "background": background_color,
+ "bold": bold,
+ "underline": underline,
+ "italics": italics,
+ "dim": dim,
+ "reverse": reverse,
+ }
def parse_bool(val):
val = val.lower()
- if val.startswith('f') or val.startswith('0'):
+ if val.startswith("f") or val.startswith("0"):
return False
- if val.startswith('t') or val.startswith('1'):
+ if val.startswith("t") or val.startswith("1"):
return True
return bool(val)
def html_color_for_ansi_color_index(val):
- arr = ['black', '#AA0000', '#00AA00', '#AA5500', '#0000AA', '#AA00AA',
- '#00AAAA', '#AAAAAA', '#555555', '#FF5555', '#55FF55', '#FFFF55',
- '#5555FF', '#FF55FF', '#55FFFF', 'white', '#000000', '#00005f',
- '#000087', '#0000af', '#0000d7', '#0000ff', '#005f00', '#005f5f',
- '#005f87', '#005faf', '#005fd7', '#005fff', '#008700', '#00875f',
- '#008787', '#0087af', '#0087d7', '#0087ff', '#00af00', '#00af5f',
- '#00af87', '#00afaf', '#00afd7', '#00afff', '#00d700', '#00d75f',
- '#00d787', '#00d7af', '#00d7d7', '#00d7ff', '#00ff00', '#00ff5f',
- '#00ff87', '#00ffaf', '#00ffd7', '#00ffff', '#5f0000', '#5f005f',
- '#5f0087', '#5f00af', '#5f00d7', '#5f00ff', '#5f5f00', '#5f5f5f',
- '#5f5f87', '#5f5faf', '#5f5fd7', '#5f5fff', '#5f8700', '#5f875f',
- '#5f8787', '#5f87af', '#5f87d7', '#5f87ff', '#5faf00', '#5faf5f',
- '#5faf87', '#5fafaf', '#5fafd7', '#5fafff', '#5fd700', '#5fd75f',
- '#5fd787', '#5fd7af', '#5fd7d7', '#5fd7ff', '#5fff00', '#5fff5f',
- '#5fff87', '#5fffaf', '#5fffd7', '#5fffff', '#870000', '#87005f',
- '#870087', '#8700af', '#8700d7', '#8700ff', '#875f00', '#875f5f',
- '#875f87', '#875faf', '#875fd7', '#875fff', '#878700', '#87875f',
- '#878787', '#8787af', '#8787d7', '#8787ff', '#87af00', '#87af5f',
- '#87af87', '#87afaf', '#87afd7', '#87afff', '#87d700', '#87d75f',
- '#87d787', '#87d7af', '#87d7d7', '#87d7ff', '#87ff00', '#87ff5f',
- '#87ff87', '#87ffaf', '#87ffd7', '#87ffff', '#af0000', '#af005f',
- '#af0087', '#af00af', '#af00d7', '#af00ff', '#af5f00', '#af5f5f',
- '#af5f87', '#af5faf', '#af5fd7', '#af5fff', '#af8700', '#af875f',
- '#af8787', '#af87af', '#af87d7', '#af87ff', '#afaf00', '#afaf5f',
- '#afaf87', '#afafaf', '#afafd7', '#afafff', '#afd700', '#afd75f',
- '#afd787', '#afd7af', '#afd7d7', '#afd7ff', '#afff00', '#afff5f',
- '#afff87', '#afffaf', '#afffd7', '#afffff', '#d70000', '#d7005f',
- '#d70087', '#d700af', '#d700d7', '#d700ff', '#d75f00', '#d75f5f',
- '#d75f87', '#d75faf', '#d75fd7', '#d75fff', '#d78700', '#d7875f',
- '#d78787', '#d787af', '#d787d7', '#d787ff', '#d7af00', '#d7af5f',
- '#d7af87', '#d7afaf', '#d7afd7', '#d7afff', '#d7d700', '#d7d75f',
- '#d7d787', '#d7d7af', '#d7d7d7', '#d7d7ff', '#d7ff00', '#d7ff5f',
- '#d7ff87', '#d7ffaf', '#d7ffd7', '#d7ffff', '#ff0000', '#ff005f',
- '#ff0087', '#ff00af', '#ff00d7', '#ff00ff', '#ff5f00', '#ff5f5f',
- '#ff5f87', '#ff5faf', '#ff5fd7', '#ff5fff', '#ff8700', '#ff875f',
- '#ff8787', '#ff87af', '#ff87d7', '#ff87ff', '#ffaf00', '#ffaf5f',
- '#ffaf87', '#ffafaf', '#ffafd7', '#ffafff', '#ffd700', '#ffd75f',
- '#ffd787', '#ffd7af', '#ffd7d7', '#ffd7ff', '#ffff00', '#ffff5f',
- '#ffff87', '#ffffaf', '#ffffd7', '#ffffff', '#080808', '#121212',
- '#1c1c1c', '#262626', '#303030', '#3a3a3a', '#444444', '#4e4e4e',
- '#585858', '#626262', '#6c6c6c', '#767676', '#808080', '#8a8a8a',
- '#949494', '#9e9e9e', '#a8a8a8', '#b2b2b2', '#bcbcbc', '#c6c6c6',
- '#d0d0d0', '#dadada', '#e4e4e4', '#eeeeee']
+ arr = [
+ "black",
+ "#AA0000",
+ "#00AA00",
+ "#AA5500",
+ "#0000AA",
+ "#AA00AA",
+ "#00AAAA",
+ "#AAAAAA",
+ "#555555",
+ "#FF5555",
+ "#55FF55",
+ "#FFFF55",
+ "#5555FF",
+ "#FF55FF",
+ "#55FFFF",
+ "white",
+ "#000000",
+ "#00005f",
+ "#000087",
+ "#0000af",
+ "#0000d7",
+ "#0000ff",
+ "#005f00",
+ "#005f5f",
+ "#005f87",
+ "#005faf",
+ "#005fd7",
+ "#005fff",
+ "#008700",
+ "#00875f",
+ "#008787",
+ "#0087af",
+ "#0087d7",
+ "#0087ff",
+ "#00af00",
+ "#00af5f",
+ "#00af87",
+ "#00afaf",
+ "#00afd7",
+ "#00afff",
+ "#00d700",
+ "#00d75f",
+ "#00d787",
+ "#00d7af",
+ "#00d7d7",
+ "#00d7ff",
+ "#00ff00",
+ "#00ff5f",
+ "#00ff87",
+ "#00ffaf",
+ "#00ffd7",
+ "#00ffff",
+ "#5f0000",
+ "#5f005f",
+ "#5f0087",
+ "#5f00af",
+ "#5f00d7",
+ "#5f00ff",
+ "#5f5f00",
+ "#5f5f5f",
+ "#5f5f87",
+ "#5f5faf",
+ "#5f5fd7",
+ "#5f5fff",
+ "#5f8700",
+ "#5f875f",
+ "#5f8787",
+ "#5f87af",
+ "#5f87d7",
+ "#5f87ff",
+ "#5faf00",
+ "#5faf5f",
+ "#5faf87",
+ "#5fafaf",
+ "#5fafd7",
+ "#5fafff",
+ "#5fd700",
+ "#5fd75f",
+ "#5fd787",
+ "#5fd7af",
+ "#5fd7d7",
+ "#5fd7ff",
+ "#5fff00",
+ "#5fff5f",
+ "#5fff87",
+ "#5fffaf",
+ "#5fffd7",
+ "#5fffff",
+ "#870000",
+ "#87005f",
+ "#870087",
+ "#8700af",
+ "#8700d7",
+ "#8700ff",
+ "#875f00",
+ "#875f5f",
+ "#875f87",
+ "#875faf",
+ "#875fd7",
+ "#875fff",
+ "#878700",
+ "#87875f",
+ "#878787",
+ "#8787af",
+ "#8787d7",
+ "#8787ff",
+ "#87af00",
+ "#87af5f",
+ "#87af87",
+ "#87afaf",
+ "#87afd7",
+ "#87afff",
+ "#87d700",
+ "#87d75f",
+ "#87d787",
+ "#87d7af",
+ "#87d7d7",
+ "#87d7ff",
+ "#87ff00",
+ "#87ff5f",
+ "#87ff87",
+ "#87ffaf",
+ "#87ffd7",
+ "#87ffff",
+ "#af0000",
+ "#af005f",
+ "#af0087",
+ "#af00af",
+ "#af00d7",
+ "#af00ff",
+ "#af5f00",
+ "#af5f5f",
+ "#af5f87",
+ "#af5faf",
+ "#af5fd7",
+ "#af5fff",
+ "#af8700",
+ "#af875f",
+ "#af8787",
+ "#af87af",
+ "#af87d7",
+ "#af87ff",
+ "#afaf00",
+ "#afaf5f",
+ "#afaf87",
+ "#afafaf",
+ "#afafd7",
+ "#afafff",
+ "#afd700",
+ "#afd75f",
+ "#afd787",
+ "#afd7af",
+ "#afd7d7",
+ "#afd7ff",
+ "#afff00",
+ "#afff5f",
+ "#afff87",
+ "#afffaf",
+ "#afffd7",
+ "#afffff",
+ "#d70000",
+ "#d7005f",
+ "#d70087",
+ "#d700af",
+ "#d700d7",
+ "#d700ff",
+ "#d75f00",
+ "#d75f5f",
+ "#d75f87",
+ "#d75faf",
+ "#d75fd7",
+ "#d75fff",
+ "#d78700",
+ "#d7875f",
+ "#d78787",
+ "#d787af",
+ "#d787d7",
+ "#d787ff",
+ "#d7af00",
+ "#d7af5f",
+ "#d7af87",
+ "#d7afaf",
+ "#d7afd7",
+ "#d7afff",
+ "#d7d700",
+ "#d7d75f",
+ "#d7d787",
+ "#d7d7af",
+ "#d7d7d7",
+ "#d7d7ff",
+ "#d7ff00",
+ "#d7ff5f",
+ "#d7ff87",
+ "#d7ffaf",
+ "#d7ffd7",
+ "#d7ffff",
+ "#ff0000",
+ "#ff005f",
+ "#ff0087",
+ "#ff00af",
+ "#ff00d7",
+ "#ff00ff",
+ "#ff5f00",
+ "#ff5f5f",
+ "#ff5f87",
+ "#ff5faf",
+ "#ff5fd7",
+ "#ff5fff",
+ "#ff8700",
+ "#ff875f",
+ "#ff8787",
+ "#ff87af",
+ "#ff87d7",
+ "#ff87ff",
+ "#ffaf00",
+ "#ffaf5f",
+ "#ffaf87",
+ "#ffafaf",
+ "#ffafd7",
+ "#ffafff",
+ "#ffd700",
+ "#ffd75f",
+ "#ffd787",
+ "#ffd7af",
+ "#ffd7d7",
+ "#ffd7ff",
+ "#ffff00",
+ "#ffff5f",
+ "#ffff87",
+ "#ffffaf",
+ "#ffffd7",
+ "#ffffff",
+ "#080808",
+ "#121212",
+ "#1c1c1c",
+ "#262626",
+ "#303030",
+ "#3a3a3a",
+ "#444444",
+ "#4e4e4e",
+ "#585858",
+ "#626262",
+ "#6c6c6c",
+ "#767676",
+ "#808080",
+ "#8a8a8a",
+ "#949494",
+ "#9e9e9e",
+ "#a8a8a8",
+ "#b2b2b2",
+ "#bcbcbc",
+ "#c6c6c6",
+ "#d0d0d0",
+ "#dadada",
+ "#e4e4e4",
+ "#eeeeee",
+ ]
if val < 0 or val >= len(arr):
- return ''
+ return ""
else:
return arr[val]
+
# Function to return special ANSI escapes like exit_attribute_mode
g_special_escapes_dict = None
@@ -230,6 +479,7 @@ def get_special_ansi_escapes():
global g_special_escapes_dict
if g_special_escapes_dict is None:
import curses
+
g_special_escapes_dict = {}
curses.setupterm()
@@ -240,16 +490,17 @@ def get_special_ansi_escapes():
if key:
val = curses.tparm(key)
if val:
- val = val.decode('utf-8')
+ val = val.decode("utf-8")
return val
# Just a few for now
- g_special_escapes_dict['exit_attribute_mode'] = get_tparm('sgr0')
- g_special_escapes_dict['bold'] = get_tparm('bold')
- g_special_escapes_dict['underline'] = get_tparm('smul')
+ g_special_escapes_dict["exit_attribute_mode"] = get_tparm("sgr0")
+ g_special_escapes_dict["bold"] = get_tparm("bold")
+ g_special_escapes_dict["underline"] = get_tparm("smul")
return g_special_escapes_dict
+
# Given a known ANSI escape sequence, convert it to HTML and append to the list
# Returns whether we have an open
@@ -261,10 +512,10 @@ def append_html_for_ansi_escape(full_val, result, span_open):
# Helper function to close a span if it's open
def close_span():
if span_open:
- result.append('')
+ result.append("")
# term256 foreground color
- match = re.match('38;5;(\d+)', val)
+ match = re.match("38;5;(\d+)", val)
if match is not None:
close_span()
html_color = html_color_for_ansi_color_index(int(match.group(1)))
@@ -274,13 +525,15 @@ def append_html_for_ansi_escape(full_val, result, span_open):
# term16 foreground color
if val in (str(x) for x in chain(range(90, 97), range(30, 38))):
close_span()
- html_color = html_color_for_ansi_color_index(int(val) - (30 if int(val) < 90 else 82))
+ html_color = html_color_for_ansi_color_index(
+ int(val) - (30 if int(val) < 90 else 82)
+ )
result.append('')
return True # span now open
# Try special escapes
special_escapes = get_special_ansi_escapes()
- if full_val == special_escapes['exit_attribute_mode']:
+ if full_val == special_escapes["exit_attribute_mode"]:
close_span()
return False
@@ -294,7 +547,7 @@ def strip_ansi(val):
# Make a half-assed effort to strip ANSI control sequences
# We assume that all such sequences start with 0x1b and end with m or ctrl-o,
# which catches most cases
- return re.sub("\x1b[^m]*m\x0f?", '', val)
+ return re.sub("\x1b[^m]*m\x0f?", "", val)
def ansi_prompt_line_width(val):
@@ -303,7 +556,7 @@ def ansi_prompt_line_width(val):
stripped_val = strip_ansi(val)
# Now count the longest line
- return max([len(x) for x in stripped_val.split('\n')])
+ return max([len(x) for x in stripped_val.split("\n")])
def ansi_to_html(val):
@@ -311,14 +564,17 @@ def ansi_to_html(val):
# standard color codes, but also things like sgr0. Hence this lame check.
# Note that Python 2.6 doesn't have a flag param to re.split, so we have to
# compile it first.
- reg = re.compile("""
+ reg = re.compile(
+ """
( # Capture
\x1b # Escape
[^m]* # Zero or more non-'m's
m # Literal m terminates the sequence
\x0f? # HACK: A ctrl-o - this is how tmux' sgr0 ends
) # End capture
- """, re.VERBOSE)
+ """,
+ re.VERBOSE,
+ )
separated = reg.split(val)
# We have to HTML escape the text and convert ANSI escapes into HTML
@@ -336,12 +592,11 @@ def ansi_to_html(val):
result.append(escape_html(strip_ansi(component)))
else:
# It's an escape sequence. Close the previous escape.
- span_open = append_html_for_ansi_escape(component, result,
- span_open)
+ span_open = append_html_for_ansi_escape(component, result, span_open)
# Close final escape
if span_open:
- result.append('')
+ result.append("")
# Remove empty elements
result = [x for x in result if x]
@@ -349,17 +604,18 @@ def ansi_to_html(val):
# Clean up empty spans, the nasty way
idx = len(result) - 1
while idx >= 1:
- if result[idx] == '' and result[idx-1].startswith('" and result[idx - 1].startswith("= len(self.buffer):
- return '\0'
+ return "\0"
c = self.buffer[self.index]
self.index += 1
return c
@@ -439,55 +705,55 @@ class BindingParser:
def parse_control_sequence(self):
""" Parses terminal specifiec control sequences """
- result = ''
+ result = ""
c = self.get_char()
# \e0 is used to denote start of control sequence
- if c == 'O':
+ if c == "O":
c = self.get_char()
# \[1\; is start of control sequence
- if c == '1':
+ if c == "1":
b = self.get_char()
c = self.get_char()
- if b == '\\' and c == '~':
+ if b == "\\" and c == "~":
result += "Home"
elif c == ";":
c = self.get_char()
# 3 is Alt
- if c == '3':
+ if c == "3":
result += "ALT - "
c = self.get_char()
# \[4\~ is End
- if c == '4':
+ if c == "4":
b = self.get_char()
c = self.get_char()
- if b == '\\' and c == '~':
+ if b == "\\" and c == "~":
result += "End"
# 5 is Ctrl
- if c == '5':
+ if c == "5":
result += "CTRL - "
c = self.get_char()
# 9 is Alt
- if c == '9':
+ if c == "9":
result += "ALT - "
c = self.get_char()
- if c == 'A':
- result += 'Up Arrow'
- elif c == 'B':
- result += 'Down Arrow'
- elif c == 'C':
- result += 'Right Arrow'
- elif c == 'D':
+ if c == "A":
+ result += "Up Arrow"
+ elif c == "B":
+ result += "Down Arrow"
+ elif c == "C":
+ result += "Right Arrow"
+ elif c == "D":
result += "Left Arrow"
- elif c == 'F':
+ elif c == "F":
result += "End"
- elif c == 'H':
+ elif c == "H":
result += "Home"
return result
@@ -503,62 +769,63 @@ class BindingParser:
return result
def parse_binding(self):
- readable_command = ''
- result = ''
+ readable_command = ""
+ result = ""
alt = ctrl = False
while not self.end():
c = self.get_char()
- if c == '\\':
+ if c == "\\":
c = self.get_char()
- if c == 'e':
+ if c == "e":
d = self.get_char()
- if d == 'O':
+ if d == "O":
self.unget_char()
result += self.parse_control_sequence()
- elif d == '\\':
- if self.get_char() == '[':
+ elif d == "\\":
+ if self.get_char() == "[":
result += self.parse_control_sequence()
else:
self.unget_char()
self.unget_char()
alt = True
- elif d == '\0':
- result += 'ESC'
+ elif d == "\0":
+ result += "ESC"
else:
alt = True
self.unget_char()
- elif c == 'c':
+ elif c == "c":
ctrl = True
- elif c == 'n':
- result += 'Enter'
- elif c == 't':
- result += 'Tab'
- elif c == 'b':
- result += 'Backspace'
+ elif c == "n":
+ result += "Enter"
+ elif c == "t":
+ result += "Tab"
+ elif c == "b":
+ result += "Backspace"
elif c.isalpha():
- result += '\\' + c
+ result += "\\" + c
else:
result += c
- elif c == '\x7f':
- result += 'Backspace'
+ elif c == "\x7f":
+ result += "Backspace"
else:
result += c
if ctrl:
- readable_command += 'CTRL - '
+ readable_command += "CTRL - "
if alt:
- readable_command += 'ALT - '
+ readable_command += "ALT - "
- if result == '':
- return 'unknown-control-sequence'
+ if result == "":
+ return "unknown-control-sequence"
return readable_command + result
class FishConfigTCPServer(SocketServer.TCPServer):
"""TCPServer that only accepts connections from localhost (IPv4/IPv6)."""
- WHITELIST = set(['::1', '::ffff:127.0.0.1', '127.0.0.1'])
+
+ WHITELIST = set(["::1", "::ffff:127.0.0.1", "127.0.0.1"])
address_family = socket.AF_INET6 if socket.has_ipv6 else socket.AF_INET
@@ -567,9 +834,8 @@ class FishConfigTCPServer(SocketServer.TCPServer):
class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
-
def write_to_wfile(self, txt):
- self.wfile.write(txt.encode('utf-8'))
+ self.wfile.write(txt.encode("utf-8"))
def do_get_colors(self):
# Looks for fish_color_*.
@@ -577,132 +843,136 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
result = []
# Make sure we return at least these
- remaining = set(['normal',
- 'error',
- 'command',
- 'end',
- 'param',
- 'comment',
- 'match',
- 'selection',
- 'search_match',
- 'operator',
- 'escape',
- 'quote',
- 'redirection',
- 'valid_path',
- 'autosuggestion'
- 'user',
- 'host',
- 'cancel'
- ])
+ remaining = set(
+ [
+ "normal",
+ "error",
+ "command",
+ "end",
+ "param",
+ "comment",
+ "match",
+ "selection",
+ "search_match",
+ "operator",
+ "escape",
+ "quote",
+ "redirection",
+ "valid_path",
+ "autosuggestion" "user",
+ "host",
+ "cancel",
+ ]
+ )
# Here are our color descriptions
descriptions = {
- 'normal': 'Default text',
- 'command': 'Ordinary commands',
- 'quote': 'Text within quotes',
- 'redirection': 'Like | and >',
- 'end': 'Like ; and &',
- 'error': 'Potential errors',
- 'param': 'Command parameters',
- 'comment': 'Comments start with #',
- 'match': 'Matching parenthesis',
- 'selection': 'Selected text',
- 'search_match': 'History searching',
- 'history_current': 'Directory history',
- 'operator': 'Like * and ~',
- 'escape': 'Escapes like \\n',
- 'cwd': 'Current directory',
- 'cwd_root': 'cwd for root user',
- 'valid_path': 'Valid paths',
- 'autosuggestion': 'Suggested completion',
- 'user': 'Username in the prompt',
- 'host': 'Hostname in the prompt',
- 'cancel': 'The ^C cancel indicator'
+ "normal": "Default text",
+ "command": "Ordinary commands",
+ "quote": "Text within quotes",
+ "redirection": "Like | and >",
+ "end": "Like ; and &",
+ "error": "Potential errors",
+ "param": "Command parameters",
+ "comment": "Comments start with #",
+ "match": "Matching parenthesis",
+ "selection": "Selected text",
+ "search_match": "History searching",
+ "history_current": "Directory history",
+ "operator": "Like * and ~",
+ "escape": "Escapes like \\n",
+ "cwd": "Current directory",
+ "cwd_root": "cwd for root user",
+ "valid_path": "Valid paths",
+ "autosuggestion": "Suggested completion",
+ "user": "Username in the prompt",
+ "host": "Hostname in the prompt",
+ "cancel": "The ^C cancel indicator",
}
- out, err = run_fish_cmd('set -L')
- for line in out.split('\n'):
+ out, err = run_fish_cmd("set -L")
+ for line in out.split("\n"):
for match in re.finditer(r"^fish_color_(\S+) ?(.*)", line):
color_name, color_value = [x.strip() for x in match.group(1, 2)]
- color_desc = descriptions.get(color_name, '')
+ color_desc = descriptions.get(color_name, "")
data = {"name": color_name, "description": color_desc}
data.update(parse_color(color_value))
result.append(data)
remaining.discard(color_name)
# Sort our result (by their keys)
- result.sort(key=operator.itemgetter('name'))
+ result.sort(key=operator.itemgetter("name"))
# Ensure that we have all the color names we know about, so that if the
# user deletes one he can still set it again via the web interface
for color_name in remaining:
- color_desc = descriptions.get(color_name, '')
- result.append([color_name, color_desc, parse_color('')])
+ color_desc = descriptions.get(color_name, "")
+ result.append([color_name, color_desc, parse_color("")])
return result
def do_get_functions(self):
- out, err = run_fish_cmd('functions')
+ out, err = run_fish_cmd("functions")
out = out.strip()
# Not sure why fish sometimes returns this with newlines
if "\n" in out:
- return out.split('\n')
+ return out.split("\n")
else:
- return out.strip().split(', ')
+ return out.strip().split(", ")
def do_get_variable_names(self, cmd):
" Given a command like 'set -U' return all the variable names "
out, err = run_fish_cmd(cmd)
- return out.split('\n')
+ return out.split("\n")
def do_get_variables(self):
- out, err = run_fish_cmd('set -L')
+ out, err = run_fish_cmd("set -L")
# Put all the variables into a dictionary
vars = {}
- for line in out.split('\n'):
- comps = line.split(' ', 1)
+ for line in out.split("\n"):
+ comps = line.split(" ", 1)
if len(comps) < 2:
continue
fish_var = FishVar(comps[0], comps[1])
vars[fish_var.name] = fish_var
# Mark universal variables. L means don't abbreviate.
- for name in self.do_get_variable_names('set -nUL'):
+ for name in self.do_get_variable_names("set -nUL"):
if name in vars:
vars[name].universal = True
# Mark exported variables. L means don't abbreviate.
- for name in self.do_get_variable_names('set -nxL'):
+ for name in self.do_get_variable_names("set -nxL"):
if name in vars:
vars[name].exported = True
- return [vars[key].get_json_obj() for key
- in sorted(vars.keys(), key=lambda x: x.lower())]
+ return [
+ vars[key].get_json_obj()
+ for key in sorted(vars.keys(), key=lambda x: x.lower())
+ ]
def do_get_bindings(self):
""" Get key bindings """
# Running __fish_config_interactive print fish greeting and
# loads key bindings
- greeting, err = run_fish_cmd(' __fish_config_interactive')
+ greeting, err = run_fish_cmd(" __fish_config_interactive")
# Load the key bindings and then list them with bind
- out, err = run_fish_cmd('__fish_config_interactive; bind')
+ out, err = run_fish_cmd("__fish_config_interactive; bind")
# Remove fish greeting from output
- out = out[len(greeting):]
+ out = out[len(greeting) :]
# Put all the bindings into a list
bindings = []
command_to_binding = {}
binding_parser = BindingParser()
- for line in out.split('\n'):
- comps = line.split(' ', 2)
+ for line in out.split("\n"):
+ comps = line.split(" ", 2)
# If we don't have "bind", a sequence and a mapping,
# it's not a valid binding.
@@ -710,19 +980,19 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
continue
# Store the "--preset" value for later
- if comps[1] == '--preset':
+ if comps[1] == "--preset":
preset = True
# There's possibly a way to do this faster, but it's not important.
- comps = line.split(' ', 3)[1:]
- elif comps[1] == '--user':
+ comps = line.split(" ", 3)[1:]
+ elif comps[1] == "--user":
preset = False
- comps = line.split(' ', 3)[1:]
+ comps = line.split(" ", 3)[1:]
# Check again if we removed the level.
if len(comps) < 3:
continue
- if comps[1] == '-k':
- key_name, command = comps[2].split(' ', 1)
+ if comps[1] == "-k":
+ key_name, command = comps[2].split(" ", 1)
binding_parser.set_buffer(key_name.capitalize())
else:
key_name = None
@@ -745,8 +1015,8 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_get_history(self):
# Use NUL to distinguish between history items.
- out, err = run_fish_cmd('builtin history -z')
- result = out.split('\0')
+ out, err = run_fish_cmd("builtin history -z")
+ result = out.split("\0")
if result:
result.pop() # trim off the trailing element
return result
@@ -757,49 +1027,52 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
out, err = run_fish_cmd("echo -n $" + name)
return out
- def do_set_color_for_variable(self, name, color, background_color, bold,
- underline, italics, dim, reverse):
+ def do_set_color_for_variable(
+ self, name, color, background_color, bold, underline, italics, dim, reverse
+ ):
"Sets a color for a fish color name, like 'autosuggestion'"
if not color:
- color = 'normal'
- varname = 'fish_color_' + name
+ color = "normal"
+ varname = "fish_color_" + name
# If the name already starts with "fish_", use it as the varname
# This is needed for 'fish_pager_color' vars.
- if name.startswith('fish_'):
+ if name.startswith("fish_"):
varname = name
# TODO: Check if the varname is allowable.
- command = 'set -U ' + varname
+ command = "set -U " + varname
if color:
- command += ' ' + color
+ command += " " + color
if background_color:
- command += ' --background=' + background_color
+ command += " --background=" + background_color
if bold:
- command += ' --bold'
+ command += " --bold"
if underline:
- command += ' --underline'
+ command += " --underline"
if italics:
- command += ' --italics'
+ command += " --italics"
if dim:
- command += ' --dim'
+ command += " --dim"
if reverse:
- command += ' --reverse'
+ command += " --reverse"
out, err = run_fish_cmd(command)
return out
def do_get_function(self, func_name):
- out, err = run_fish_cmd('functions ' + func_name + ' | fish_indent --html')
+ out, err = run_fish_cmd("functions " + func_name + " | fish_indent --html")
return out
def do_delete_history_item(self, history_item_text):
# It's really lame that we always return success here
- cmd = ('builtin history delete --case-sensitive --exact -- %s; builtin history save' %
- escape_fish_cmd(history_item_text))
+ cmd = (
+ "builtin history delete --case-sensitive --exact -- %s; builtin history save"
+ % escape_fish_cmd(history_item_text)
+ )
out, err = run_fish_cmd(cmd)
return True
def do_set_prompt_function(self, prompt_func):
- cmd = prompt_func + '\n' + 'funcsave fish_prompt'
+ cmd = prompt_func + "\n" + "funcsave fish_prompt"
out, err = run_fish_cmd(cmd)
return len(err) == 0
@@ -808,8 +1081,11 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
prompt_demo_ansi, err = run_fish_cmd(command_to_run)
prompt_demo_html = ansi_to_html(prompt_demo_ansi)
prompt_demo_font_size = self.font_size_for_ansi_prompt(prompt_demo_ansi)
- result = {'function': prompt_function_text, 'demo': prompt_demo_html,
- 'font_size': prompt_demo_font_size}
+ result = {
+ "function": prompt_function_text,
+ "demo": prompt_demo_html,
+ "font_size": prompt_demo_font_size,
+ }
if extras_dict:
result.update(extras_dict)
return result
@@ -817,18 +1093,19 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_get_current_prompt(self):
# Return the current prompt. We run 'false' to demonstrate how the
# prompt shows the command status (#1624).
- prompt_func, err = run_fish_cmd('functions fish_prompt')
+ prompt_func, err = run_fish_cmd("functions fish_prompt")
result = self.do_get_prompt(
'builtin cd "' + initial_wd + '" ; false ; fish_prompt',
- prompt_func.strip(), {'name': 'Current'})
+ prompt_func.strip(),
+ {"name": "Current"},
+ )
return result
def do_get_sample_prompt(self, text, extras_dict):
# Return the prompt you get from the given text. Extras_dict is a
# dictionary whose values get merged in. We run 'false' to demonstrate
# how the prompt shows the command status (#1624)
- cmd = (text + "\n builtin cd \"" + initial_wd +
- "\" \n false \n fish_prompt\n")
+ cmd = text + '\n builtin cd "' + initial_wd + '" \n false \n fish_prompt\n'
return self.do_get_prompt(cmd, text.strip(), extras_dict)
def parse_one_sample_prompt_hash(self, line, result_dict):
@@ -846,27 +1123,28 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
result_dict[key] = value
return True
# Skip other hash comments
- return line.startswith('#')
+ return line.startswith("#")
def read_one_sample_prompt(self, path):
try:
- with open(path, 'rb') as fd:
+ with open(path, "rb") as fd:
extras_dict = {}
# Read one sample prompt from fd
function_lines = []
parsing_hashes = True
- unicode_lines = (line.decode('utf-8') for line in fd)
+ unicode_lines = (line.decode("utf-8") for line in fd)
for line in unicode_lines:
# Parse hashes until parse_one_sample_prompt_hash return
# False.
if parsing_hashes:
parsing_hashes = self.parse_one_sample_prompt_hash(
- line, extras_dict)
+ line, extras_dict
+ )
# Maybe not we're not parsing hashes, or maybe we already
# were not.
if not parsing_hashes:
function_lines.append(line)
- func = ''.join(function_lines).strip()
+ func = "".join(function_lines).strip()
result = self.do_get_sample_prompt(func, extras_dict)
return result
except IOError:
@@ -880,7 +1158,7 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
current_metasample_async = pool.apply_async(self.do_get_current_prompt)
# Read all of the prompts in sample_prompts
- paths = glob.iglob('sample_prompts/*.fish')
+ paths = glob.iglob("sample_prompts/*.fish")
sample_results = pool.map(self.read_one_sample_prompt, paths, 1)
# Finish up
@@ -893,24 +1171,26 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
# Example abbreviation line:
# abbr -a -U -- ls 'ls -a'
result = []
- out, err = run_fish_cmd('abbr --show')
- for line in out.rstrip().split('\n'):
- if not line: continue
- _, abbr = line.split(' -- ', 1)
- word, phrase = abbr.split(' ', 1)
- result.append({'word':word, 'phrase':phrase})
+ out, err = run_fish_cmd("abbr --show")
+ for line in out.rstrip().split("\n"):
+ if not line:
+ continue
+ _, abbr = line.split(" -- ", 1)
+ word, phrase = abbr.split(" ", 1)
+ result.append({"word": word, "phrase": phrase})
return result
def do_remove_abbreviation(self, abbreviation):
- out, err = run_fish_cmd('abbr --erase %s' % abbreviation['word'])
+ out, err = run_fish_cmd("abbr --erase %s" % abbreviation["word"])
if err:
return err
else:
return None
def do_save_abbreviation(self, abbreviation):
- out, err = run_fish_cmd('abbr --add \'%s\' \'%s\'' % (
- abbreviation['word'], abbreviation['phrase']))
+ out, err = run_fish_cmd(
+ "abbr --add '%s' '%s'" % (abbreviation["word"], abbreviation["phrase"])
+ )
if err:
return err
else:
@@ -928,61 +1208,61 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
width = ansi_prompt_line_width(prompt_demo_ansi)
# Pick a font size
if width >= 70:
- font_size = '8pt'
+ font_size = "8pt"
if width >= 60:
- font_size = '10pt'
+ font_size = "10pt"
elif width >= 50:
- font_size = '11pt'
+ font_size = "11pt"
elif width >= 40:
- font_size = '13pt'
+ font_size = "13pt"
elif width >= 30:
- font_size = '15pt'
+ font_size = "15pt"
elif width >= 25:
- font_size = '16pt'
+ font_size = "16pt"
elif width >= 20:
- font_size = '17pt'
+ font_size = "17pt"
else:
- font_size = '18pt'
+ font_size = "18pt"
return font_size
def do_GET(self):
p = self.path
- authpath = '/' + authkey
+ authpath = "/" + authkey
if self.secure_startswith(p, authpath):
- p = p[len(authpath):]
+ p = p[len(authpath) :]
else:
return self.send_error(403)
self.path = p
- if p == '/colors/':
+ if p == "/colors/":
output = self.do_get_colors()
- elif p == '/functions/':
+ elif p == "/functions/":
output = self.do_get_functions()
- elif p == '/variables/':
+ elif p == "/variables/":
output = self.do_get_variables()
- elif p == '/history/':
+ elif p == "/history/":
# start = time.time()
output = self.do_get_history()
# end = time.time()
# print "History: ", end - start
- elif p == '/sample_prompts/':
+ elif p == "/sample_prompts/":
output = self.do_get_sample_prompts_list()
elif re.match(r"/color/(\w+)/", p):
name = re.match(r"/color/(\w+)/", p).group(1)
output = self.do_get_color_for_variable(name)
- elif p == '/bindings/':
+ elif p == "/bindings/":
output = self.do_get_bindings()
- elif p == '/abbreviations/':
+ elif p == "/abbreviations/":
output = self.do_get_abbreviations()
else:
return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
# Return valid output
self.send_response(200)
- self.send_header('Content-type', 'application/json')
+ self.send_header("Content-type", "application/json")
self.end_headers()
- self.write_to_wfile('\n')
+ self.write_to_wfile("\n")
# Output JSON
self.write_to_wfile(json.dumps(output))
@@ -990,68 +1270,74 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_POST(self):
p = self.path
- authpath = '/' + authkey
+ authpath = "/" + authkey
if self.secure_startswith(p, authpath):
- p = p[len(authpath):]
+ p = p[len(authpath) :]
else:
return self.send_error(403)
self.path = p
- ctype, pdict = cgi.parse_header(self.headers['content-type'])
+ ctype, pdict = cgi.parse_header(self.headers["content-type"])
- if ctype == 'multipart/form-data':
+ if ctype == "multipart/form-data":
postvars = cgi.parse_multipart(self.rfile, pdict)
- elif ctype == 'application/x-www-form-urlencoded':
- length = int(self.headers['content-length'])
- url_str = self.rfile.read(length).decode('utf-8')
+ elif ctype == "application/x-www-form-urlencoded":
+ length = int(self.headers["content-length"])
+ url_str = self.rfile.read(length).decode("utf-8")
postvars = parse_qs(url_str, keep_blank_values=1)
- elif ctype == 'application/json':
- length = int(self.headers['content-length'])
- url_str = self.rfile.read(length).decode(pdict['charset'])
+ elif ctype == "application/json":
+ length = int(self.headers["content-length"])
+ url_str = self.rfile.read(length).decode(pdict["charset"])
postvars = json.loads(url_str)
else:
postvars = {}
- if p == '/set_color/':
- what = postvars.get('what')
- color = postvars.get('color')
- background_color = postvars.get('background_color')
- bold = postvars.get('bold')
- italics = postvars.get('italics')
- reverse = postvars.get('reverse')
- dim = postvars.get('dim')
- underline = postvars.get('underline')
+ if p == "/set_color/":
+ what = postvars.get("what")
+ color = postvars.get("color")
+ background_color = postvars.get("background_color")
+ bold = postvars.get("bold")
+ italics = postvars.get("italics")
+ reverse = postvars.get("reverse")
+ dim = postvars.get("dim")
+ underline = postvars.get("underline")
if what:
# Not sure why we get lists here?
output = self.do_set_color_for_variable(
- what[0], color[0], background_color[0],
- parse_bool(bold[0]), parse_bool(underline[0]), parse_bool(italics[0]),
- parse_bool(dim[0]), parse_bool(reverse[0]))
+ what[0],
+ color[0],
+ background_color[0],
+ parse_bool(bold[0]),
+ parse_bool(underline[0]),
+ parse_bool(italics[0]),
+ parse_bool(dim[0]),
+ parse_bool(reverse[0]),
+ )
else:
- output = 'Bad request'
- elif p == '/get_function/':
- what = postvars.get('what')
+ output = "Bad request"
+ elif p == "/get_function/":
+ what = postvars.get("what")
output = [self.do_get_function(what[0])]
- elif p == '/delete_history_item/':
- what = postvars.get('what')
+ elif p == "/delete_history_item/":
+ what = postvars.get("what")
if self.do_delete_history_item(what[0]):
output = ["OK"]
else:
output = ["Unable to delete history item"]
- elif p == '/set_prompt/':
- what = postvars.get('fish_prompt')
+ elif p == "/set_prompt/":
+ what = postvars.get("fish_prompt")
if self.do_set_prompt_function(what):
output = ["OK"]
else:
output = ["Unable to set prompt"]
- elif p == '/save_abbreviation/':
+ elif p == "/save_abbreviation/":
errmsg = self.do_save_abbreviation(postvars)
if errmsg:
output = [errmsg]
else:
output = ["OK"]
- elif p == '/remove_abbreviation/':
+ elif p == "/remove_abbreviation/":
errmsg = self.do_remove_abbreviation(postvars)
if errmsg:
output = [errmsg]
@@ -1062,26 +1348,27 @@ class FishConfigHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
# Return valid output
self.send_response(200)
- self.send_header('Content-type', 'application/json')
+ self.send_header("Content-type", "application/json")
self.end_headers()
- self.write_to_wfile('\n')
+ self.write_to_wfile("\n")
# Output JSON
self.write_to_wfile(json.dumps(output))
- def log_request(self, code='-', size='-'):
+ def log_request(self, code="-", size="-"):
""" Disable request logging """
pass
def log_error(self, format, *args):
- if format == 'code %d, message %s':
+ if format == "code %d, message %s":
# This appears to be a send_error() message
# We want to include the path
(code, msg) = args
- format = 'code %d, message %s, path %s'
+ format = "code %d, message %s, path %s"
args = (code, msg, self.path)
SimpleHTTPServer.SimpleHTTPRequestHandler.log_error(self, format, *args)
+
redirect_template_html = """
@@ -1095,15 +1382,14 @@ redirect_template_html = """
"""
# find fish
-fish_bin_dir = os.environ.get('__fish_bin_dir')
+fish_bin_dir = os.environ.get("__fish_bin_dir")
fish_bin_path = None
if not fish_bin_dir:
- print('The $__fish_bin_dir environment variable is not set. '
- 'Looking in $PATH...')
+ print("The $__fish_bin_dir environment variable is not set. " "Looking in $PATH...")
# distutils.spawn is terribly broken, because it looks in wd before PATH,
# and doesn't actually validate that the file is even executable
- for p in os.environ['PATH'].split(os.pathsep):
- proposed_path = os.path.join(p, 'fish')
+ for p in os.environ["PATH"].split(os.pathsep):
+ proposed_path = os.path.join(p, "fish")
if os.access(proposed_path, os.X_OK):
fish_bin_path = proposed_path
break
@@ -1114,11 +1400,13 @@ if not fish_bin_dir:
print("fish found at '%s'" % fish_bin_path)
else:
- fish_bin_path = os.path.join(fish_bin_dir, 'fish')
+ fish_bin_path = os.path.join(fish_bin_dir, "fish")
if not os.access(fish_bin_path, os.X_OK):
- print("fish could not be executed at path '%s'. "
- "Is fish installed correctly?" % fish_bin_path)
+ print(
+ "fish could not be executed at path '%s'. "
+ "Is fish installed correctly?" % fish_bin_path
+ )
sys.exit(-1)
FISH_BIN_PATH = fish_bin_path
@@ -1132,7 +1420,7 @@ where = os.path.dirname(sys.argv[0])
os.chdir(where)
# Generate a 16-byte random key as a hexadecimal string
-authkey = binascii.b2a_hex(os.urandom(16)).decode('ascii')
+authkey = binascii.b2a_hex(os.urandom(16)).decode("ascii")
# Try to find a suitable port
PORT = 8000
@@ -1146,7 +1434,7 @@ while PORT <= 9000:
except socket.error:
err_type, err_value = sys.exc_info()[:2]
# str(err_value) handles Python3 correctly
- if 'Address already in use' not in str(err_value):
+ if "Address already in use" not in str(err_value):
print(str(err_value))
break
PORT += 1
@@ -1158,23 +1446,30 @@ if PORT > 9000:
# Get any initial tab (functions, colors, etc)
# Just look at the first letter
-initial_tab = ''
+initial_tab = ""
if len(sys.argv) > 1:
- for tab in ['functions', 'prompt', 'colors', 'variables', 'history',
- 'bindings', 'abbreviations']:
+ for tab in [
+ "functions",
+ "prompt",
+ "colors",
+ "variables",
+ "history",
+ "bindings",
+ "abbreviations",
+ ]:
if tab.startswith(sys.argv[1]):
- initial_tab = '#' + tab
+ initial_tab = "#" + tab
break
-url = 'http://localhost:%d/%s/%s' % (PORT, authkey, initial_tab)
+url = "http://localhost:%d/%s/%s" % (PORT, authkey, initial_tab)
# Create temporary file to hold redirect to real server. This prevents exposing
# the URL containing the authentication key on the command line (see
# CVE-2014-2914 or https://github.com/fish-shell/fish-shell/issues/1438).
-if 'XDG_CACHE_HOME' in os.environ:
- dirname = os.path.expanduser(os.path.expandvars('$XDG_CACHE_HOME/fish/'))
+if "XDG_CACHE_HOME" in os.environ:
+ dirname = os.path.expanduser(os.path.expandvars("$XDG_CACHE_HOME/fish/"))
else:
- dirname = os.path.expanduser('~/.cache/fish/')
+ dirname = os.path.expanduser("~/.cache/fish/")
os.umask(0o0077)
try:
@@ -1185,26 +1480,30 @@ except OSError as e:
else:
raise e
-randtoken = ''.join(random.choice(string.ascii_uppercase + string.digits)
- for _ in range(6))
-filename = dirname + 'web_config-%s.html' % randtoken
+randtoken = "".join(
+ random.choice(string.ascii_uppercase + string.digits) for _ in range(6)
+)
+filename = dirname + "web_config-%s.html" % randtoken
-f = open(filename, 'w')
+f = open(filename, "w")
f.write(redirect_template_html % (url, url))
f.close()
# Open temporary file as URL
# Use open on macOS >= 10.12.5 to work around #4035.
-fileurl = 'file://' + filename
+fileurl = "file://" + filename
esc = get_special_ansi_escapes()
-print("Web config started at %s%s%s" % (esc['underline'], fileurl, esc['exit_attribute_mode']))
-print("%sHit ENTER to stop.%s" % (esc['bold'], esc['exit_attribute_mode']))
+print(
+ "Web config started at %s%s%s"
+ % (esc["underline"], fileurl, esc["exit_attribute_mode"])
+)
+print("%sHit ENTER to stop.%s" % (esc["bold"], esc["exit_attribute_mode"]))
if isMacOS10_12_5_OrLater():
- subprocess.check_call(['open', fileurl])
+ subprocess.check_call(["open", fileurl])
elif is_wsl():
- subprocess.call(['cmd.exe', '/c', "start %s" % url])
+ subprocess.call(["cmd.exe", "/c", "start %s" % url])
else:
webbrowser.open(fileurl)
diff --git a/sphinx_doc_src/conf.py b/sphinx_doc_src/conf.py
index e2abca392..7689bf091 100644
--- a/sphinx_doc_src/conf.py
+++ b/sphinx_doc_src/conf.py
@@ -13,21 +13,25 @@ from sphinx.errors import SphinxError, SphinxWarning
# -- Helper functions --------------------------------------------------------
+
def strip_ext(path):
""" Remove the extension from a path. """
return os.path.splitext(path)[0]
+
# -- Load our Pygments lexer -------------------------------------------------
def setup(app):
from sphinx.highlighting import lexers
+
this_dir = os.path.dirname(os.path.realpath(__file__))
fish_indent_lexer = pygments.lexers.load_lexer_from_file(
- os.path.join(this_dir, 'fish_indent_lexer.py'),
- lexername='FishIndentLexer')
- lexers['fish-docs-samples'] = fish_indent_lexer
+ os.path.join(this_dir, "fish_indent_lexer.py"), lexername="FishIndentLexer"
+ )
+ lexers["fish-docs-samples"] = fish_indent_lexer
+
# The default language to assume
-highlight_language = 'fish-docs-samples'
+highlight_language = "fish-docs-samples"
# -- Path setup --------------------------------------------------------------
@@ -42,14 +46,14 @@ highlight_language = 'fish-docs-samples'
# -- Project information -----------------------------------------------------
-project = 'fish-shell'
-copyright = '2019, fish-shell developers'
-author = 'fish-shell developers'
+project = "fish-shell"
+copyright = "2019, fish-shell developers"
+author = "fish-shell developers"
# The short X.Y version
-version = '3.1'
+version = "3.1"
# The full version, including alpha/beta/rc tags
-release = '3.1.0'
+release = "3.1.0"
# -- General configuration ---------------------------------------------------
@@ -61,20 +65,19 @@ release = '3.1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
-extensions = [
-]
+extensions = []
# Add any paths that contain templates here, relative to this directory.
-templates_path = ['_templates']
+templates_path = ["_templates"]
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
-source_suffix = '.rst'
+source_suffix = ".rst"
# The master toctree document.
-master_doc = 'index'
+master_doc = "index"
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
@@ -98,7 +101,7 @@ pygments_style = None
# a list of builtin themes.
# !!! If you change this you also need to update the @import at the top
# of _static/fish-syntax-style.css
-html_theme = 'nature'
+html_theme = "nature"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
@@ -109,7 +112,7 @@ html_theme = 'nature'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
-html_static_path = ['_static']
+html_static_path = ["_static"]
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
@@ -119,13 +122,13 @@ html_static_path = ['_static']
# default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
# 'searchbox.html']``.
#
-html_sidebars = { '**': ['globaltoc.html', 'localtoc.html', 'searchbox.html'] }
+html_sidebars = {"**": ["globaltoc.html", "localtoc.html", "searchbox.html"]}
# -- Options for HTMLHelp output ---------------------------------------------
# Output file base name for HTML help builder.
-htmlhelp_basename = 'fish-shelldoc'
+htmlhelp_basename = "fish-shelldoc"
# -- Options for LaTeX output ------------------------------------------------
@@ -134,15 +137,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
-
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
-
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
-
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
@@ -152,34 +152,36 @@ latex_elements = {
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
- (master_doc, 'fish-shell.tex', 'fish-shell Documentation',
- 'fish-shell developers', 'manual'),
+ (
+ master_doc,
+ "fish-shell.tex",
+ "fish-shell Documentation",
+ "fish-shell developers",
+ "manual",
+ )
]
# -- Options for manual page output ------------------------------------------
+
def get_command_description(path, name):
""" Return the description for a command, by parsing its synopsis line """
with open(path) as fd:
for line in fd:
if line.startswith(name + " - "):
- _, desc = line.split(' - ', 1)
+ _, desc = line.split(" - ", 1)
return desc.strip()
- raise SphinxWarning('No description in file %s' % os.path.basename(path))
-
+ raise SphinxWarning("No description in file %s" % os.path.basename(path))
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
-man_pages = [
- (master_doc, 'fish', 'fish-shell Documentation',
- [author], 1)
-]
-for path in sorted(glob.glob('cmds/*')):
+man_pages = [(master_doc, "fish", "fish-shell Documentation", [author], 1)]
+for path in sorted(glob.glob("cmds/*")):
docname = strip_ext(path)
cmd = os.path.basename(docname)
- man_pages.append((docname, cmd, get_command_description(path, cmd), '', 1))
+ man_pages.append((docname, cmd, get_command_description(path, cmd), "", 1))
# -- Options for Texinfo output ----------------------------------------------
@@ -188,9 +190,15 @@ for path in sorted(glob.glob('cmds/*')):
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- (master_doc, 'fish-shell', 'fish-shell Documentation',
- author, 'fish-shell', 'One line description of project.',
- 'Miscellaneous'),
+ (
+ master_doc,
+ "fish-shell",
+ "fish-shell Documentation",
+ author,
+ "fish-shell",
+ "One line description of project.",
+ "Miscellaneous",
+ )
]
@@ -209,7 +217,7 @@ epub_title = project
# epub_uid = ''
# A list of files that should not be packed into the epub file.
-epub_exclude_files = ['search.html']
+epub_exclude_files = ["search.html"]
# Disable smart-quotes to prevent double dashes from becoming emdashes.
smartquotes = False
diff --git a/sphinx_doc_src/fish_indent_lexer.py b/sphinx_doc_src/fish_indent_lexer.py
index 1bc978731..e904023df 100644
--- a/sphinx_doc_src/fish_indent_lexer.py
+++ b/sphinx_doc_src/fish_indent_lexer.py
@@ -91,9 +91,9 @@ def tokenize_fish_command(code, offset):
stdout=subprocess.PIPE,
universal_newlines=False,
)
- stdout, _ = proc.communicate(code.encode('utf-8'))
+ stdout, _ = proc.communicate(code.encode("utf-8"))
result = []
- for line in stdout.decode('utf-8').splitlines():
+ for line in stdout.decode("utf-8").splitlines():
start, end, role = line.split(",")
start, end = int(start), int(end)
value = code[start:end]
diff --git a/src/builtin.cpp b/src/builtin.cpp
index 4179e0f63..4db430b19 100644
--- a/src/builtin.cpp
+++ b/src/builtin.cpp
@@ -19,8 +19,8 @@
#include
#include
-#include
#include
+#include
#include
#include
diff --git a/src/builtin_argparse.cpp b/src/builtin_argparse.cpp
index d1a9ec576..1b75a40a4 100644
--- a/src/builtin_argparse.cpp
+++ b/src/builtin_argparse.cpp
@@ -59,14 +59,11 @@ struct argparse_cmd_opts_t {
};
static const wchar_t *const short_options = L"+:hn:six:N:X:";
-static const struct woption long_options[] = {{L"stop-nonopt", no_argument, NULL, 's'},
- {L"ignore-unknown", no_argument, NULL, 'i'},
- {L"name", required_argument, NULL, 'n'},
- {L"exclusive", required_argument, NULL, 'x'},
- {L"help", no_argument, NULL, 'h'},
- {L"min-args", required_argument, NULL, 'N'},
- {L"max-args", required_argument, NULL, 'X'},
- {NULL, 0, NULL, 0}};
+static const struct woption long_options[] = {
+ {L"stop-nonopt", no_argument, NULL, 's'}, {L"ignore-unknown", no_argument, NULL, 'i'},
+ {L"name", required_argument, NULL, 'n'}, {L"exclusive", required_argument, NULL, 'x'},
+ {L"help", no_argument, NULL, 'h'}, {L"min-args", required_argument, NULL, 'N'},
+ {L"max-args", required_argument, NULL, 'X'}, {NULL, 0, NULL, 0}};
// Check if any pair of mutually exclusive options was seen. Note that since every option must have
// a short name we only need to check those.
@@ -584,12 +581,12 @@ static int argparse_parse_flags(parser_t &parser, argparse_cmd_opts_t &opts,
// A non-option argument.
// We use `-` as the first option-string-char to disable GNU getopt's reordering,
// otherwise we'd get ignored options first and normal arguments later.
- // E.g. `argparse -i -- -t tango -w` needs to keep `-t tango -w` in $argv, not `-t -w tango`.
+ // E.g. `argparse -i -- -t tango -w` needs to keep `-t tango -w` in $argv, not `-t -w
+ // tango`.
opts.argv.push_back(argv[w.woptind - 1]);
continue;
}
-
// It's a recognized flag.
auto found = opts.options.find(opt);
assert(found != opts.options.end());
@@ -610,7 +607,8 @@ static int argparse_parse_args(argparse_cmd_opts_t &opts, const wcstring_list_t
parser_t &parser, io_streams_t &streams) {
if (args.empty()) return STATUS_CMD_OK;
- // "+" means stop at nonopt, "-" means give nonoptions the option character code `1`, and don't reorder.
+ // "+" means stop at nonopt, "-" means give nonoptions the option character code `1`, and don't
+ // reorder.
wcstring short_options = opts.stop_nonopt ? L"+:" : L"-";
std::vector long_options;
populate_option_strings(opts, &short_options, &long_options);
diff --git a/src/builtin_bind.cpp b/src/builtin_bind.cpp
index dbf717347..72d00be1a 100644
--- a/src/builtin_bind.cpp
+++ b/src/builtin_bind.cpp
@@ -52,7 +52,7 @@ struct bind_cmd_opts_t {
/// List a single key binding.
/// Returns false if no binding with that sequence and mode exists.
bool builtin_bind_t::list_one(const wcstring &seq, const wcstring &bind_mode, bool user,
- io_streams_t &streams) {
+ io_streams_t &streams) {
wcstring_list_t ecmds;
wcstring sets_mode;
@@ -102,8 +102,8 @@ bool builtin_bind_t::list_one(const wcstring &seq, const wcstring &bind_mode, bo
// Overload with both kinds of bindings.
// Returns false only if neither exists.
-bool builtin_bind_t::list_one(const wcstring &seq, const wcstring &bind_mode, bool user, bool preset,
- io_streams_t &streams) {
+bool builtin_bind_t::list_one(const wcstring &seq, const wcstring &bind_mode, bool user,
+ bool preset, io_streams_t &streams) {
bool retval = false;
if (preset) {
retval |= list_one(seq, bind_mode, false, streams);
@@ -151,7 +151,8 @@ void builtin_bind_t::function_names(io_streams_t &streams) {
}
/// Wraps input_terminfo_get_sequence(), appending the correct error messages as needed.
-bool builtin_bind_t::get_terminfo_sequence(const wchar_t *seq, wcstring *out_seq, io_streams_t &streams) {
+bool builtin_bind_t::get_terminfo_sequence(const wchar_t *seq, wcstring *out_seq,
+ io_streams_t &streams) {
if (input_terminfo_get_sequence(seq, out_seq)) {
return true;
}
@@ -159,7 +160,8 @@ bool builtin_bind_t::get_terminfo_sequence(const wchar_t *seq, wcstring *out_seq
wcstring eseq = escape_string(seq, 0);
if (!opts->silent) {
if (errno == ENOENT) {
- streams.err.append_format(_(L"%ls: No key with name '%ls' found\n"), L"bind", eseq.c_str());
+ streams.err.append_format(_(L"%ls: No key with name '%ls' found\n"), L"bind",
+ eseq.c_str());
} else if (errno == EILSEQ) {
streams.err.append_format(_(L"%ls: Key with name '%ls' does not have any mapping\n"),
L"bind", eseq.c_str());
@@ -174,7 +176,7 @@ bool builtin_bind_t::get_terminfo_sequence(const wchar_t *seq, wcstring *out_seq
/// Add specified key binding.
bool builtin_bind_t::add(const wchar_t *seq, const wchar_t *const *cmds, size_t cmds_len,
const wchar_t *mode, const wchar_t *sets_mode, bool terminfo, bool user,
- io_streams_t &streams) {
+ io_streams_t &streams) {
if (terminfo) {
wcstring seq2;
if (get_terminfo_sequence(seq, &seq2, streams)) {
@@ -202,8 +204,8 @@ bool builtin_bind_t::add(const wchar_t *seq, const wchar_t *const *cmds, size_t
/// @param use_terminfo
/// Whether to look use terminfo -k name
///
-bool builtin_bind_t::erase(wchar_t **seq, bool all, const wchar_t *mode, bool use_terminfo, bool user,
- io_streams_t &streams) {
+bool builtin_bind_t::erase(wchar_t **seq, bool all, const wchar_t *mode, bool use_terminfo,
+ bool user, io_streams_t &streams) {
if (all) {
input_mapping_clear(mode, user);
return false;
@@ -228,8 +230,7 @@ bool builtin_bind_t::erase(wchar_t **seq, bool all, const wchar_t *mode, bool us
return res;
}
-bool builtin_bind_t::insert(int optind, int argc, wchar_t **argv,
- io_streams_t &streams) {
+bool builtin_bind_t::insert(int optind, int argc, wchar_t **argv, io_streams_t &streams) {
wchar_t *cmd = argv[0];
int arg_count = argc - optind;
@@ -242,8 +243,9 @@ bool builtin_bind_t::insert(int optind, int argc, wchar_t **argv,
} else {
// Inserting both on the other hand makes no sense.
if (opts->have_preset && opts->have_user) {
- streams.err.append_format(BUILTIN_ERR_COMBO2, cmd,
- L"--preset and --user can not be used together when inserting bindings.");
+ streams.err.append_format(
+ BUILTIN_ERR_COMBO2, cmd,
+ L"--preset and --user can not be used together when inserting bindings.");
return true;
}
}
@@ -314,7 +316,7 @@ void builtin_bind_t::list_modes(io_streams_t &streams) {
}
int parse_cmd_opts(bind_cmd_opts_t &opts, int *optind, //!OCLINT(high ncss method)
- int argc, wchar_t **argv, parser_t &parser, io_streams_t &streams) {
+ int argc, wchar_t **argv, parser_t &parser, io_streams_t &streams) {
wchar_t *cmd = argv[0];
static const wchar_t *const short_options = L":aehkKfM:Lm:s";
static const struct woption long_options[] = {{L"all", no_argument, NULL, 'a'},
diff --git a/src/builtin_bind.h b/src/builtin_bind.h
index 12ba7cf49..501d81724 100644
--- a/src/builtin_bind.h
+++ b/src/builtin_bind.h
@@ -11,30 +11,30 @@ struct io_streams_t;
struct bind_cmd_opts_t;
class builtin_bind_t {
-public:
- int builtin_bind(parser_t &parser, io_streams_t &streams, wchar_t **argv);
-private:
- bind_cmd_opts_t *opts;
+ public:
+ int builtin_bind(parser_t &parser, io_streams_t &streams, wchar_t **argv);
- void list(const wchar_t *bind_mode, bool user, io_streams_t &streams);
- void key_names(bool all, io_streams_t &streams);
- void function_names(io_streams_t &streams);
- bool add(const wchar_t *seq, const wchar_t *const *cmds, size_t cmds_len,
- const wchar_t *mode, const wchar_t *sets_mode, bool terminfo, bool user,
- io_streams_t &streams);
- bool erase(wchar_t **seq, bool all, const wchar_t *mode, bool use_terminfo, bool user,
- io_streams_t &streams);
- bool get_terminfo_sequence(const wchar_t *seq, wcstring *out_seq, io_streams_t &streams);
- bool insert(int optind, int argc, wchar_t **argv,
- io_streams_t &streams);
- void list_modes(io_streams_t &streams);
- bool list_one(const wcstring &seq, const wcstring &bind_mode, bool user, io_streams_t &streams);
- bool list_one(const wcstring &seq, const wcstring &bind_mode, bool user, bool preset, io_streams_t &streams);
+ private:
+ bind_cmd_opts_t *opts;
+
+ void list(const wchar_t *bind_mode, bool user, io_streams_t &streams);
+ void key_names(bool all, io_streams_t &streams);
+ void function_names(io_streams_t &streams);
+ bool add(const wchar_t *seq, const wchar_t *const *cmds, size_t cmds_len, const wchar_t *mode,
+ const wchar_t *sets_mode, bool terminfo, bool user, io_streams_t &streams);
+ bool erase(wchar_t **seq, bool all, const wchar_t *mode, bool use_terminfo, bool user,
+ io_streams_t &streams);
+ bool get_terminfo_sequence(const wchar_t *seq, wcstring *out_seq, io_streams_t &streams);
+ bool insert(int optind, int argc, wchar_t **argv, io_streams_t &streams);
+ void list_modes(io_streams_t &streams);
+ bool list_one(const wcstring &seq, const wcstring &bind_mode, bool user, io_streams_t &streams);
+ bool list_one(const wcstring &seq, const wcstring &bind_mode, bool user, bool preset,
+ io_streams_t &streams);
};
inline int builtin_bind(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
- builtin_bind_t bind;
- return bind.builtin_bind(parser, streams, argv);
+ builtin_bind_t bind;
+ return bind.builtin_bind(parser, streams, argv);
}
#endif
diff --git a/src/builtin_builtin.cpp b/src/builtin_builtin.cpp
index 4ac852b60..c27eeae35 100644
--- a/src/builtin_builtin.cpp
+++ b/src/builtin_builtin.cpp
@@ -20,10 +20,10 @@ struct builtin_cmd_opts_t {
bool query = false;
};
static const wchar_t *const short_options = L":hnq";
-static const struct woption long_options[] = {
- {L"help", no_argument, NULL, 'h'}, {L"names", no_argument, NULL, 'n'},
- {L"query", no_argument, NULL, 'q'},
- {NULL, 0, NULL, 0}};
+static const struct woption long_options[] = {{L"help", no_argument, NULL, 'h'},
+ {L"names", no_argument, NULL, 'n'},
+ {L"query", no_argument, NULL, 'q'},
+ {NULL, 0, NULL, 0}};
static int parse_cmd_opts(builtin_cmd_opts_t &opts, int *optind, int argc, wchar_t **argv,
parser_t &parser, io_streams_t &streams) {
diff --git a/src/builtin_command.cpp b/src/builtin_command.cpp
index e8308bb76..28a98c1ad 100644
--- a/src/builtin_command.cpp
+++ b/src/builtin_command.cpp
@@ -102,7 +102,7 @@ int builtin_command(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
if (!opts.quiet) streams.out.append_format(L"%ls\n", path.c_str());
++found;
}
- } else { // Either find_path explicitly or just quiet.
+ } else { // Either find_path explicitly or just quiet.
wcstring path;
if (path_get_path(command_name, &path, parser.vars())) {
if (!opts.quiet) streams.out.append_format(L"%ls\n", path.c_str());
diff --git a/src/builtin_commandline.h b/src/builtin_commandline.h
index 4fa8ef083..5237d240f 100644
--- a/src/builtin_commandline.h
+++ b/src/builtin_commandline.h
@@ -2,8 +2,8 @@
#ifndef FISH_BUILTIN_COMMANDLINE_H
#define FISH_BUILTIN_COMMANDLINE_H
-#include
#include
+#include
class parser_t;
diff --git a/src/builtin_complete.cpp b/src/builtin_complete.cpp
index 1f3dcb6d4..cf5b14df5 100644
--- a/src/builtin_complete.cpp
+++ b/src/builtin_complete.cpp
@@ -263,7 +263,6 @@ int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
// Use one left-over arg as the do-complete argument
// to enable `complete -C "git check"`.
if (do_complete && !have_do_complete_param && argc == w.woptind + 1) {
-
do_complete_param = argv[argc - 1];
have_do_complete_param = true;
} else {
@@ -306,7 +305,7 @@ int builtin_complete(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
if (do_complete) {
if (!have_do_complete_param) {
// No argument given, try to use the current commandline.
- const wchar_t* cmd = reader_get_buffer();
+ const wchar_t *cmd = reader_get_buffer();
if (cmd == NULL) {
// This corresponds to using 'complete -C' in non-interactive mode.
// See #2361 .
diff --git a/src/builtin_echo.cpp b/src/builtin_echo.cpp
index 74d6db059..cbd7949e0 100644
--- a/src/builtin_echo.cpp
+++ b/src/builtin_echo.cpp
@@ -18,7 +18,7 @@ struct echo_cmd_opts_t {
bool interpret_special_chars = false;
};
static const wchar_t *const short_options = L"+:Eens";
-static const struct woption * const long_options = NULL;
+static const struct woption *const long_options = NULL;
static int parse_cmd_opts(echo_cmd_opts_t &opts, int *optind, int argc, wchar_t **argv,
parser_t &parser, io_streams_t &streams) {
@@ -89,7 +89,9 @@ static unsigned int builtin_echo_digit(wchar_t wc, unsigned int base) {
return 6;
case L'7':
return 7;
- default: { break; }
+ default: {
+ break;
+ }
}
if (base != 16) return UINT_MAX;
@@ -117,7 +119,9 @@ static unsigned int builtin_echo_digit(wchar_t wc, unsigned int base) {
case L'f':
case L'F':
return 15;
- default: { break; }
+ default: {
+ break;
+ }
}
return UINT_MAX;
diff --git a/src/builtin_fg.cpp b/src/builtin_fg.cpp
index 7a27f254c..ad37f9c67 100644
--- a/src/builtin_fg.cpp
+++ b/src/builtin_fg.cpp
@@ -99,7 +99,7 @@ int builtin_fg(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
}
const wcstring ft = tok_first(job->command());
- //For compatibility with fish 2.0's $_, now replaced with `status current-command`
+ // For compatibility with fish 2.0's $_, now replaced with `status current-command`
if (!ft.empty()) parser.vars().set_one(L"_", ENV_EXPORT, ft);
reader_write_title(job->command(), parser);
diff --git a/src/builtin_functions.cpp b/src/builtin_functions.cpp
index b7e66746b..6b53c2b3c 100644
--- a/src/builtin_functions.cpp
+++ b/src/builtin_functions.cpp
@@ -40,13 +40,18 @@ struct functions_cmd_opts_t {
wchar_t *description = NULL;
};
static const wchar_t *const short_options = L":HDacd:ehnqv";
-static const struct woption long_options[] = {
- {L"erase", no_argument, NULL, 'e'}, {L"description", required_argument, NULL, 'd'},
- {L"names", no_argument, NULL, 'n'}, {L"all", no_argument, NULL, 'a'},
- {L"help", no_argument, NULL, 'h'}, {L"query", no_argument, NULL, 'q'},
- {L"copy", no_argument, NULL, 'c'}, {L"details", no_argument, NULL, 'D'},
- {L"verbose", no_argument, NULL, 'v'}, {L"handlers", no_argument, NULL, 'H'},
- {L"handlers-type", required_argument, NULL, 't'}, {NULL, 0, NULL, 0}};
+static const struct woption long_options[] = {{L"erase", no_argument, NULL, 'e'},
+ {L"description", required_argument, NULL, 'd'},
+ {L"names", no_argument, NULL, 'n'},
+ {L"all", no_argument, NULL, 'a'},
+ {L"help", no_argument, NULL, 'h'},
+ {L"query", no_argument, NULL, 'q'},
+ {L"copy", no_argument, NULL, 'c'},
+ {L"details", no_argument, NULL, 'D'},
+ {L"verbose", no_argument, NULL, 'v'},
+ {L"handlers", no_argument, NULL, 'H'},
+ {L"handlers-type", required_argument, NULL, 't'},
+ {NULL, 0, NULL, 0}};
static int parse_cmd_opts(functions_cmd_opts_t &opts, int *optind, //!OCLINT(high ncss method)
int argc, wchar_t **argv, parser_t &parser, io_streams_t &streams) {
@@ -327,9 +332,10 @@ int builtin_functions(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
maybe_t type_filter;
if (opts.handlers_type) {
type_filter = event_type_for_name(opts.handlers_type);
- if (! type_filter) {
- streams.err.append_format(_(L"%ls: Expected generic | variable | signal | exit | job-id for --handlers-type\n"),
- cmd);
+ if (!type_filter) {
+ streams.err.append_format(_(L"%ls: Expected generic | variable | signal | exit | "
+ L"job-id for --handlers-type\n"),
+ cmd);
return STATUS_INVALID_ARGS;
}
}
diff --git a/src/builtin_history.cpp b/src/builtin_history.cpp
index 09610b3c7..877e88e1c 100644
--- a/src/builtin_history.cpp
+++ b/src/builtin_history.cpp
@@ -68,8 +68,8 @@ static bool set_hist_cmd(wchar_t *const cmd, hist_cmd_t *hist_cmd, hist_cmd_t su
const wchar_t *subcmd_str1 = enum_to_str(*hist_cmd, hist_enum_map);
const wchar_t *subcmd_str2 = enum_to_str(sub_cmd, hist_enum_map);
std::swprintf(err_text, sizeof(err_text) / sizeof(wchar_t),
- _(L"you cannot do both '%ls' and '%ls' in the same invocation"), subcmd_str1,
- subcmd_str2);
+ _(L"you cannot do both '%ls' and '%ls' in the same invocation"), subcmd_str1,
+ subcmd_str2);
streams.err.append_format(BUILTIN_ERR_COMBO2, cmd, err_text);
return false;
}
diff --git a/src/builtin_jobs.cpp b/src/builtin_jobs.cpp
index ec8bb0373..2f5c264a0 100644
--- a/src/builtin_jobs.cpp
+++ b/src/builtin_jobs.cpp
@@ -21,7 +21,7 @@ enum {
JOBS_PRINT_PID, // print pid of each process in job
JOBS_PRINT_COMMAND, // print command name of each process in job
JOBS_PRINT_GROUP, // print group id of job
- JOBS_PRINT_NOTHING, // print nothing (exit status only)
+ JOBS_PRINT_NOTHING, // print nothing (exit status only)
};
/// Calculates the cpu usage (in percent) of the specified job.
@@ -117,14 +117,13 @@ int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
int print_last = 0;
static const wchar_t *const short_options = L":cghlpq";
- static const struct woption long_options[] = {
- {L"command", no_argument, NULL, 'c'},
- {L"group", no_argument, NULL, 'g'},
- {L"help", no_argument, NULL, 'h'},
- {L"last", no_argument, NULL, 'l'},
- {L"pid", no_argument, NULL, 'p'},
- {L"quiet", no_argument, NULL, 'q'},
- {nullptr, 0, NULL, 0}};
+ static const struct woption long_options[] = {{L"command", no_argument, NULL, 'c'},
+ {L"group", no_argument, NULL, 'g'},
+ {L"help", no_argument, NULL, 'h'},
+ {L"last", no_argument, NULL, 'l'},
+ {L"pid", no_argument, NULL, 'p'},
+ {L"quiet", no_argument, NULL, 'q'},
+ {nullptr, 0, NULL, 0}};
int opt;
wgetopter_t w;
@@ -189,15 +188,16 @@ int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
int jobId = -1;
jobId = fish_wcstoi(argv[i] + 1);
if (errno || jobId < -1) {
- streams.err.append_format(_(L"%ls: '%ls' is not a valid job id"), cmd, argv[i]);
+ streams.err.append_format(_(L"%ls: '%ls' is not a valid job id"), cmd,
+ argv[i]);
return STATUS_INVALID_ARGS;
}
j = job_t::from_job_id(jobId);
- }
- else {
+ } else {
int pid = fish_wcstoi(argv[i]);
if (errno || pid < 0) {
- streams.err.append_format(_(L"%ls: '%ls' is not a valid process id\n"), cmd, argv[i]);
+ streams.err.append_format(_(L"%ls: '%ls' is not a valid process id\n"), cmd,
+ argv[i]);
return STATUS_INVALID_ARGS;
}
j = job_t::from_pid(pid);
@@ -215,7 +215,8 @@ int builtin_jobs(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
for (const auto &j : jobs()) {
// Ignore unconstructed jobs, i.e. ourself.
if (j->is_visible()) {
- builtin_jobs_print(j.get(), mode, !found && !streams.out_is_redirected, streams);
+ builtin_jobs_print(j.get(), mode, !found && !streams.out_is_redirected,
+ streams);
found = true;
}
}
diff --git a/src/builtin_math.cpp b/src/builtin_math.cpp
index fdbe0a980..ebe3918af 100644
--- a/src/builtin_math.cpp
+++ b/src/builtin_math.cpp
@@ -54,8 +54,8 @@ static int parse_cmd_opts(math_cmd_opts_t &opts, int *optind, //!OCLINT(high nc
} else {
opts.scale = fish_wcstoi(w.woptarg);
if (errno || opts.scale < 0 || opts.scale > 15) {
- streams.err.append_format(_(L"%ls: '%ls' is not a valid scale value\n"), cmd,
- w.woptarg);
+ streams.err.append_format(_(L"%ls: '%ls' is not a valid scale value\n"),
+ cmd, w.woptarg);
return STATUS_INVALID_ARGS;
}
}
@@ -129,19 +129,28 @@ static const wchar_t *math_get_arg(int *argidx, wchar_t **argv, wcstring *storag
return math_get_arg_argv(argidx, argv);
}
-static const wchar_t *math_describe_error(te_error_t& error) {
+static const wchar_t *math_describe_error(te_error_t &error) {
if (error.position == 0) return L"NO ERROR?!?";
- switch(error.type) {
- case TE_ERROR_NONE: DIE("Error has no position");
- case TE_ERROR_UNKNOWN_VARIABLE: return _(L"Unknown variable");
- case TE_ERROR_MISSING_CLOSING_PAREN: return _(L"Missing closing parenthesis");
- case TE_ERROR_MISSING_OPENING_PAREN: return _(L"Missing opening parenthesis");
- case TE_ERROR_TOO_FEW_ARGS: return _(L"Too few arguments");
- case TE_ERROR_TOO_MANY_ARGS: return _(L"Too many arguments");
- case TE_ERROR_MISSING_OPERATOR: return _(L"Missing operator");
- case TE_ERROR_UNKNOWN: return _(L"Expression is bogus");
- default: return L"Unknown error";
+ switch (error.type) {
+ case TE_ERROR_NONE:
+ DIE("Error has no position");
+ case TE_ERROR_UNKNOWN_VARIABLE:
+ return _(L"Unknown variable");
+ case TE_ERROR_MISSING_CLOSING_PAREN:
+ return _(L"Missing closing parenthesis");
+ case TE_ERROR_MISSING_OPENING_PAREN:
+ return _(L"Missing opening parenthesis");
+ case TE_ERROR_TOO_FEW_ARGS:
+ return _(L"Too few arguments");
+ case TE_ERROR_TOO_MANY_ARGS:
+ return _(L"Too many arguments");
+ case TE_ERROR_MISSING_OPERATOR:
+ return _(L"Missing operator");
+ case TE_ERROR_UNKNOWN:
+ return _(L"Expression is bogus");
+ default:
+ return L"Unknown error";
}
}
@@ -212,7 +221,7 @@ static int evaluate_expression(const wchar_t *cmd, parser_t &parser, io_streams_
} else {
streams.err.append_format(L"%ls: Error: %ls\n", cmd, math_describe_error(error));
streams.err.append_format(L"'%ls'\n", expression.c_str());
- streams.err.append_format(L"%*ls%ls\n", error.position - 1, L" ",L"^");
+ streams.err.append_format(L"%*ls%ls\n", error.position - 1, L" ", L"^");
retval = STATUS_CMD_ERROR;
}
setlocale(LC_NUMERIC, saved_locale);
diff --git a/src/builtin_printf.cpp b/src/builtin_printf.cpp
index 09b3a9283..55c4be7b6 100644
--- a/src/builtin_printf.cpp
+++ b/src/builtin_printf.cpp
@@ -57,10 +57,10 @@
#include
#include
#include
-#include
#include
-#include
#include
+#include
+#include
#include "builtin.h"
#include "common.h"
@@ -93,7 +93,6 @@ struct builtin_printf_state_t {
void nonfatal_error(const wchar_t *fmt, ...);
void fatal_error(const wchar_t *format, ...);
-
long print_esc(const wchar_t *escstart, bool octal_0);
void print_esc_string(const wchar_t *str);
void print_esc_char(wchar_t c);
@@ -161,7 +160,9 @@ static int hex_to_bin(const wchar_t &c) {
case L'F': {
return 15;
}
- default: { return -1; }
+ default: {
+ return -1;
+ }
}
}
@@ -191,7 +192,9 @@ static int octal_to_bin(wchar_t c) {
case L'7': {
return 7;
}
- default: { return -1; }
+ default: {
+ return -1;
+ }
}
}
@@ -472,7 +475,9 @@ void builtin_printf_state_t::print_direc(const wchar_t *start, size_t length, wc
fmt.append(L"l");
break;
}
- default: { break; }
+ default: {
+ break;
+ }
}
// Append the conversion itself.
diff --git a/src/builtin_pwd.cpp b/src/builtin_pwd.cpp
index 66fb64efc..143bc6e8c 100644
--- a/src/builtin_pwd.cpp
+++ b/src/builtin_pwd.cpp
@@ -13,7 +13,7 @@
#include "wutil.h" // IWYU pragma: keep
/// The pwd builtin. Respect -P to resolve symbolic links. Respect -L to not do that (the default).
-static const wchar_t * const short_options = L"LPh";
+static const wchar_t *const short_options = L"LPh";
static const struct woption long_options[] = {{L"help", no_argument, NULL, 'h'},
{NULL, 0, NULL, 0}};
int builtin_pwd(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
diff --git a/src/builtin_read.cpp b/src/builtin_read.cpp
index ec8dc974a..7210a983e 100644
--- a/src/builtin_read.cpp
+++ b/src/builtin_read.cpp
@@ -6,8 +6,8 @@
#include
#include
#include
-#include
#include
+#include
#include
#include
@@ -55,27 +55,25 @@ struct read_cmd_opts_t {
};
static const wchar_t *const short_options = L":ac:d:ghiLlm:n:p:sSuxzP:UR:LB";
-static const struct woption long_options[] = {
- {L"array", no_argument, NULL, 'a'},
- {L"command", required_argument, NULL, 'c'},
- {L"delimiter", required_argument, NULL, 'd'},
- {L"export", no_argument, NULL, 'x'},
- {L"global", no_argument, NULL, 'g'},
- {L"help", no_argument, NULL, 'h'},
- {L"line", no_argument, NULL, 'L'},
- {L"local", no_argument, NULL, 'l'},
- {L"mode-name", required_argument, NULL, 'm'},
- {L"nchars", required_argument, NULL, 'n'},
- {L"null", no_argument, NULL, 'z'},
- {L"prompt", required_argument, NULL, 'p'},
- {L"prompt-str", required_argument, NULL, 'P'},
- {L"right-prompt", required_argument, NULL, 'R'},
- {L"shell", no_argument, NULL, 'S'},
- {L"silent", no_argument, NULL, 's'},
- {L"unexport", no_argument, NULL, 'u'},
- {L"universal", no_argument, NULL, 'U'},
- {NULL, 0, NULL, 0}
-};
+static const struct woption long_options[] = {{L"array", no_argument, NULL, 'a'},
+ {L"command", required_argument, NULL, 'c'},
+ {L"delimiter", required_argument, NULL, 'd'},
+ {L"export", no_argument, NULL, 'x'},
+ {L"global", no_argument, NULL, 'g'},
+ {L"help", no_argument, NULL, 'h'},
+ {L"line", no_argument, NULL, 'L'},
+ {L"local", no_argument, NULL, 'l'},
+ {L"mode-name", required_argument, NULL, 'm'},
+ {L"nchars", required_argument, NULL, 'n'},
+ {L"null", no_argument, NULL, 'z'},
+ {L"prompt", required_argument, NULL, 'p'},
+ {L"prompt-str", required_argument, NULL, 'P'},
+ {L"right-prompt", required_argument, NULL, 'R'},
+ {L"shell", no_argument, NULL, 'S'},
+ {L"silent", no_argument, NULL, 's'},
+ {L"unexport", no_argument, NULL, 'u'},
+ {L"universal", no_argument, NULL, 'U'},
+ {NULL, 0, NULL, 0}};
static int parse_cmd_opts(read_cmd_opts_t &opts, int *optind, //!OCLINT(high ncss method)
int argc, wchar_t **argv, parser_t &parser, io_streams_t &streams) {
@@ -98,8 +96,9 @@ static int parse_cmd_opts(read_cmd_opts_t &opts, int *optind, //!OCLINT(high nc
break;
}
case 'i': {
- streams.err.append_format(_(L"%ls: usage of -i for --silent is deprecated. Please use -s or --silent instead.\n"),
- cmd);
+ streams.err.append_format(_(L"%ls: usage of -i for --silent is deprecated. Please "
+ L"use -s or --silent instead.\n"),
+ cmd);
return STATUS_INVALID_ARGS;
}
case L'g': {
@@ -350,17 +349,20 @@ static int read_one_char_at_a_time(int fd, wcstring &buff, int nchars, bool spli
static int validate_read_args(const wchar_t *cmd, read_cmd_opts_t &opts, int argc,
const wchar_t *const *argv, parser_t &parser, io_streams_t &streams) {
if (opts.prompt && opts.prompt_str) {
- streams.err.append_format(_(L"%ls: Options %ls and %ls cannot be used together\n"), cmd, L"-p", L"-P");
+ streams.err.append_format(_(L"%ls: Options %ls and %ls cannot be used together\n"), cmd,
+ L"-p", L"-P");
builtin_print_error_trailer(parser, streams.err, cmd);
return STATUS_INVALID_ARGS;
}
if (opts.have_delimiter && opts.one_line) {
- streams.err.append_format(_(L"%ls: Options %ls and %ls cannot be used together\n"), cmd, L"--delimiter", L"--line");
+ streams.err.append_format(_(L"%ls: Options %ls and %ls cannot be used together\n"), cmd,
+ L"--delimiter", L"--line");
return STATUS_INVALID_ARGS;
}
if (opts.one_line && opts.split_null) {
- streams.err.append_format(_(L"%ls: Options %ls and %ls cannot be used together\n"), cmd, L"-z", L"--line");
+ streams.err.append_format(_(L"%ls: Options %ls and %ls cannot be used together\n"), cmd,
+ L"-z", L"--line");
return STATUS_INVALID_ARGS;
}
@@ -449,22 +451,23 @@ int builtin_read(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
opts.shell = false;
}
- wchar_t * const *var_ptr = argv;
- auto vars_left = [&] () { return argv + argc - var_ptr; };
- auto clear_remaining_vars = [&] () {
+ wchar_t *const *var_ptr = argv;
+ auto vars_left = [&]() { return argv + argc - var_ptr; };
+ auto clear_remaining_vars = [&]() {
while (vars_left()) {
parser.vars().set_empty(*var_ptr, opts.place);
++var_ptr;
}
};
- // Normally, we either consume a line of input or all available input. But if we are reading a line at
- // a time, we need a middle ground where we only consume as many lines as we need to fill the given vars.
+ // Normally, we either consume a line of input or all available input. But if we are reading a
+ // line at a time, we need a middle ground where we only consume as many lines as we need to
+ // fill the given vars.
do {
buff.clear();
- // TODO: Determine if the original set of conditions for interactive reads should be reinstated:
- // if (isatty(0) && streams.stdin_fd == STDIN_FILENO && !split_null) {
+ // TODO: Determine if the original set of conditions for interactive reads should be
+ // reinstated: if (isatty(0) && streams.stdin_fd == STDIN_FILENO && !split_null) {
int stream_stdin_is_a_tty = isatty(streams.stdin_fd);
if (stream_stdin_is_a_tty && !opts.split_null) {
// Read interactively using reader_readline(). This does not support splitting on null.
@@ -474,7 +477,8 @@ int builtin_read(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
lseek(streams.stdin_fd, 0, SEEK_CUR) != -1) {
exit_res = read_in_chunks(streams.stdin_fd, buff, opts.split_null);
} else {
- exit_res = read_one_char_at_a_time(streams.stdin_fd, buff, opts.nchars, opts.split_null);
+ exit_res =
+ read_one_char_at_a_time(streams.stdin_fd, buff, opts.nchars, opts.split_null);
}
if (exit_res != STATUS_CMD_OK) {
@@ -496,7 +500,8 @@ int builtin_read(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
// Every character is a separate token with one wrinkle involving non-array mode where
// the final var gets the remaining characters as a single string.
size_t x = std::max(static_cast(1), buff.size());
- size_t n_splits = (opts.array || static_cast(vars_left()) > x) ? x : vars_left();
+ size_t n_splits =
+ (opts.array || static_cast(vars_left()) > x) ? x : vars_left();
wcstring_list_t chars;
chars.reserve(n_splits);
@@ -563,7 +568,7 @@ int builtin_read(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
// is set to the remaining string.
split_about(buff.begin(), buff.end(), opts.delimiter.begin(), opts.delimiter.end(),
&splits, argc - 1);
- assert(splits.size() <= (size_t) vars_left());
+ assert(splits.size() <= (size_t)vars_left());
for (const auto &split : splits) {
vars.set_one(*var_ptr++, opts.place, split);
}
diff --git a/src/builtin_realpath.cpp b/src/builtin_realpath.cpp
index 62edae85b..98f51234c 100644
--- a/src/builtin_realpath.cpp
+++ b/src/builtin_realpath.cpp
@@ -30,7 +30,7 @@ int builtin_realpath(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
return STATUS_CMD_OK;
}
- if (optind + 1 != argc) { // TODO: allow arbitrary args. `realpath *` should print many paths
+ if (optind + 1 != argc) { // TODO: allow arbitrary args. `realpath *` should print many paths
streams.err.append_format(BUILTIN_ERR_ARG_COUNT1, cmd, 1, argc - optind);
builtin_print_help(parser, streams, cmd, streams.out);
return STATUS_INVALID_ARGS;
diff --git a/src/builtin_set.cpp b/src/builtin_set.cpp
index b511b03f7..94554f2e5 100644
--- a/src/builtin_set.cpp
+++ b/src/builtin_set.cpp
@@ -4,9 +4,9 @@
#include
#include
#include
-#include
#include
#include
+#include
#include
#include
@@ -304,8 +304,7 @@ static bool validate_path_warning_on_colons(const wchar_t *cmd,
}
static void handle_env_return(int retval, const wchar_t *cmd, const wchar_t *key,
- io_streams_t &streams) {
-
+ io_streams_t &streams) {
switch (retval) {
case ENV_OK: {
break;
@@ -317,19 +316,18 @@ static void handle_env_return(int retval, const wchar_t *cmd, const wchar_t *key
}
case ENV_SCOPE: {
streams.err.append_format(
- _(L"%ls: Tried to modify the special variable '%ls' with the wrong scope\n"),
- cmd, key);
+ _(L"%ls: Tried to modify the special variable '%ls' with the wrong scope\n"), cmd,
+ key);
break;
}
case ENV_INVALID: {
streams.err.append_format(
- _(L"%ls: Tried to modify the special variable '%ls' to an invalid value\n"),
- cmd, key);
+ _(L"%ls: Tried to modify the special variable '%ls' to an invalid value\n"), cmd,
+ key);
break;
}
case ENV_NOT_FOUND: {
- streams.err.append_format(
- _(L"%ls: The variable '%ls' does not exist\n"), cmd, key);
+ streams.err.append_format(_(L"%ls: The variable '%ls' does not exist\n"), cmd, key);
break;
}
default: {
@@ -579,8 +577,7 @@ static void show_scope(const wchar_t *var_name, int scope, io_streams_t &streams
if (i >= 50 && i < vals.size() - 50) continue;
}
const wcstring value = vals[i];
- const wcstring escaped_val =
- escape_string(value, ESCAPE_NO_QUOTED, STRING_STYLE_SCRIPT);
+ const wcstring escaped_val = escape_string(value, ESCAPE_NO_QUOTED, STRING_STYLE_SCRIPT);
streams.out.append_format(_(L"$%ls[%d]: length=%d value=|%ls|\n"), var_name, i + 1,
value.size(), escaped_val.c_str());
}
diff --git a/src/builtin_set_color.cpp b/src/builtin_set_color.cpp
index d48d61319..98a74db3e 100644
--- a/src/builtin_set_color.cpp
+++ b/src/builtin_set_color.cpp
@@ -65,12 +65,12 @@ int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
// By the time this is called we should have initialized the curses subsystem.
assert(curses_initialized);
- // Hack in missing italics and dim capabilities omitted from MacOS xterm-256color terminfo
- // Helps Terminal.app/iTerm
- #if __APPLE__
+// Hack in missing italics and dim capabilities omitted from MacOS xterm-256color terminfo
+// Helps Terminal.app/iTerm
+#if __APPLE__
const auto term_prog = parser.vars().get(L"TERM_PROGRAM");
- if (!term_prog.missing_or_empty() && (term_prog->as_string() == L"Apple_Terminal"
- || term_prog->as_string() == L"iTerm.app")) {
+ if (!term_prog.missing_or_empty() &&
+ (term_prog->as_string() == L"Apple_Terminal" || term_prog->as_string() == L"iTerm.app")) {
const auto term = parser.vars().get(L"TERM");
if (!term.missing_or_empty() && (term->as_string() == L"xterm-256color")) {
enter_italics_mode = sitm_esc;
@@ -78,7 +78,7 @@ int builtin_set_color(parser_t &parser, io_streams_t &streams, wchar_t **argv) {
enter_dim_mode = dim_esc;
}
}
- #endif
+#endif
// Variables used for parsing the argument list.
wchar_t *cmd = argv[0];
diff --git a/src/builtin_status.cpp b/src/builtin_status.cpp
index 455df9fe5..1230d6e5c 100644
--- a/src/builtin_status.cpp
+++ b/src/builtin_status.cpp
@@ -102,24 +102,25 @@ struct status_cmd_opts_t {
/// least until fish 3.0 and possibly longer to avoid breaking everyones config.fish and other
/// scripts.
static const wchar_t *const short_options = L":L:cbilfnhj:t";
-static const struct woption long_options[] = {{L"help", no_argument, NULL, 'h'},
- {L"current-filename", no_argument, NULL, 'f'},
- {L"current-line-number", no_argument, NULL, 'n'},
- {L"filename", no_argument, NULL, 'f'},
- {L"fish-path", no_argument, NULL, STATUS_FISH_PATH},
- {L"is-block", no_argument, NULL, 'b'},
- {L"is-command-substitution", no_argument, NULL, 'c'},
- {L"is-full-job-control", no_argument, NULL, STATUS_IS_FULL_JOB_CTRL},
- {L"is-interactive", no_argument, NULL, 'i'},
- {L"is-interactive-job-control", no_argument, NULL, STATUS_IS_INTERACTIVE_JOB_CTRL},
- {L"is-login", no_argument, NULL, 'l'},
- {L"is-no-job-control", no_argument, NULL, STATUS_IS_NO_JOB_CTRL},
- {L"job-control", required_argument, NULL, 'j'},
- {L"level", required_argument, NULL, 'L'},
- {L"line", no_argument, NULL, 'n'},
- {L"line-number", no_argument, NULL, 'n'},
- {L"print-stack-trace", no_argument, NULL, 't'},
- {NULL, 0, NULL, 0}};
+static const struct woption long_options[] = {
+ {L"help", no_argument, NULL, 'h'},
+ {L"current-filename", no_argument, NULL, 'f'},
+ {L"current-line-number", no_argument, NULL, 'n'},
+ {L"filename", no_argument, NULL, 'f'},
+ {L"fish-path", no_argument, NULL, STATUS_FISH_PATH},
+ {L"is-block", no_argument, NULL, 'b'},
+ {L"is-command-substitution", no_argument, NULL, 'c'},
+ {L"is-full-job-control", no_argument, NULL, STATUS_IS_FULL_JOB_CTRL},
+ {L"is-interactive", no_argument, NULL, 'i'},
+ {L"is-interactive-job-control", no_argument, NULL, STATUS_IS_INTERACTIVE_JOB_CTRL},
+ {L"is-login", no_argument, NULL, 'l'},
+ {L"is-no-job-control", no_argument, NULL, STATUS_IS_NO_JOB_CTRL},
+ {L"job-control", required_argument, NULL, 'j'},
+ {L"level", required_argument, NULL, 'L'},
+ {L"line", no_argument, NULL, 'n'},
+ {L"line-number", no_argument, NULL, 'n'},
+ {L"print-stack-trace", no_argument, NULL, 't'},
+ {NULL, 0, NULL, 0}};
/// Remember the status subcommand and disallow selecting more than one status subcommand.
static bool set_status_cmd(wchar_t *const cmd, status_cmd_opts_t &opts, status_cmd_t sub_cmd,
@@ -129,8 +130,8 @@ static bool set_status_cmd(wchar_t *const cmd, status_cmd_opts_t &opts, status_c
const wchar_t *subcmd_str1 = enum_to_str(opts.status_cmd, status_enum_map);
const wchar_t *subcmd_str2 = enum_to_str(sub_cmd, status_enum_map);
std::swprintf(err_text, sizeof(err_text) / sizeof(wchar_t),
- _(L"you cannot do both '%ls' and '%ls' in the same invocation"), subcmd_str1,
- subcmd_str2);
+ _(L"you cannot do both '%ls' and '%ls' in the same invocation"), subcmd_str1,
+ subcmd_str2);
streams.err.append_format(BUILTIN_ERR_COMBO2, cmd, err_text);
return false;
}
diff --git a/src/builtin_string.cpp b/src/builtin_string.cpp
index 201e7ab25..d35cb276c 100644
--- a/src/builtin_string.cpp
+++ b/src/builtin_string.cpp
@@ -11,8 +11,8 @@
#include
#include
#include
-#include
#include
+#include
#include
#include
diff --git a/src/builtin_test.cpp b/src/builtin_test.cpp
index b36921297..928d797d8 100644
--- a/src/builtin_test.cpp
+++ b/src/builtin_test.cpp
@@ -5,12 +5,12 @@
#include
#include
-#include
#include
#include
#include
-#include
#include
+#include
+#include
#include
#include
@@ -24,8 +24,8 @@
#include "parser.h"
#include "wutil.h" // IWYU pragma: keep
-using std::unique_ptr;
using std::move;
+using std::unique_ptr;
namespace {
namespace test_expressions {
@@ -530,7 +530,9 @@ unique_ptr test_parser::parse_expression(unsigned int start, unsigne
case 4: {
return parse_4_arg_expression(start, end);
}
- default: { return parse_combining_expression(start, end); }
+ default: {
+ return parse_combining_expression(start, end);
+ }
}
}
@@ -673,8 +675,8 @@ static bool parse_number(const wcstring &arg, number_t *number, wcstring_list_t
// We could not parse a float or an int.
// Check for special fish_wcsto* value or show standard EINVAL/ERANGE error.
if (errno == -1) {
- errors.push_back(format_string(_(L"Integer %lld in '%ls' followed by non-digit"),
- integral, argcs));
+ errors.push_back(
+ format_string(_(L"Integer %lld in '%ls' followed by non-digit"), integral, argcs));
} else {
errors.push_back(format_string(L"%s: '%ls'", std::strerror(errno), argcs));
}
diff --git a/src/color.cpp b/src/color.cpp
index ceaec1ffd..e27545b92 100644
--- a/src/color.cpp
+++ b/src/color.cpp
@@ -79,7 +79,9 @@ static int parse_hex_digit(wchar_t x) {
case L'F': {
return 0xF;
}
- default: { return -1; }
+ default: {
+ return -1;
+ }
}
}
@@ -329,7 +331,9 @@ wcstring rgb_color_t::description() const {
case type_normal: {
return L"normal";
}
- default: { break; }
+ default: {
+ break;
+ }
}
DIE("unknown color type");
}
diff --git a/src/common.cpp b/src/common.cpp
index 89f9725ec..29a6a17fc 100644
--- a/src/common.cpp
+++ b/src/common.cpp
@@ -14,13 +14,13 @@
#include
#include
#include
-#include
#include
#include
#include
#include
-#include
#include
+#include
+#include
#ifdef HAVE_EXECINFO_H
#include
#endif
@@ -63,7 +63,7 @@ constexpr wint_t NOT_A_WCHAR = static_cast(WEOF);
struct termios shell_modes;
/// This allows us to determine if we're running on the main thread
-static std::atomic thread_id { 0 };
+static std::atomic thread_id{0};
/// This allows us to notice when we've forked.
static relaxed_atomic_bool_t is_forked_proc{false};
/// This allows us to bypass the main thread checks
@@ -168,8 +168,10 @@ bool is_windows_subsystem_for_linux() {
if (std::strstr(info.release, "Microsoft") != nullptr) {
const char *dash = std::strchr(info.release, '-');
if (dash == nullptr || strtod(dash + 1, nullptr) < 17763) {
- debug(1, "This version of WSL is not supported and fish will probably not work correctly!\n"
- "Please upgrade to Windows 10 1809 (17763) or higher to use fish!");
+ debug(1,
+ "This version of WSL is not supported and fish will probably not work "
+ "correctly!\n"
+ "Please upgrade to Windows 10 1809 (17763) or higher to use fish!");
}
return true;
@@ -187,8 +189,8 @@ bool is_windows_subsystem_for_linux() {
#ifdef HAVE_BACKTRACE_SYMBOLS
// This function produces a stack backtrace with demangled function & method names. It is based on
// https://gist.github.com/fmela/591333 but adapted to the style of the fish project.
-[[gnu::noinline]] static const wcstring_list_t
-demangled_backtrace(int max_frames, int skip_levels) {
+[[gnu::noinline]] static const wcstring_list_t demangled_backtrace(int max_frames,
+ int skip_levels) {
void *callstack[128];
const int n_max_frames = sizeof(callstack) / sizeof(callstack[0]);
int n_frames = backtrace(callstack, n_max_frames);
@@ -576,9 +578,9 @@ void fish_setlocale() {
if (is_windows_subsystem_for_linux()) {
// neither of \u23CE and \u25CF can be displayed in the default fonts on Windows, though
// they can be *encoded* just fine. Use alternative glyphs.
- omitted_newline_str = L"\u00b6"; // "pilcrow"
+ omitted_newline_str = L"\u00b6"; // "pilcrow"
omitted_newline_width = 1;
- obfuscation_read_char = L'\u2022'; // "bullet"
+ obfuscation_read_char = L'\u2022'; // "bullet"
} else if (is_console_session()) {
omitted_newline_str = L"^J";
omitted_newline_width = 2;
@@ -653,8 +655,8 @@ static void debug_shared(const wchar_t level, const wcstring &msg) {
std::fwprintf(stderr, L"<%lc> %ls: %ls\n", (unsigned long)level, program_name, msg.c_str());
} else {
current_pid = getpid();
- std::fwprintf(stderr, L"<%lc> %ls: %d: %ls\n", (unsigned long)level, program_name, current_pid,
- msg.c_str());
+ std::fwprintf(stderr, L"<%lc> %ls: %d: %ls\n", (unsigned long)level, program_name,
+ current_pid, msg.c_str());
}
}
@@ -1139,7 +1141,7 @@ static void escape_string_script(const wchar_t *orig_in, size_t in_len, wcstring
/// \param in is the raw string to be searched for literally when substituted in a PCRE2 expression.
static wcstring escape_string_pcre2(const wcstring &in) {
wcstring out;
- out.reserve(in.size() * 1.3); // a wild guess
+ out.reserve(in.size() * 1.3); // a wild guess
for (auto c : in) {
switch (c) {
@@ -1156,8 +1158,9 @@ static wcstring escape_string_pcre2(const wcstring &in) {
case L'}':
case L'\\':
case L'|':
- // these two only *need* to be escaped within a character class, and technically it makes
- // no sense to ever use process substitution output to compose a character class, but...
+ // these two only *need* to be escaped within a character class, and technically it
+ // makes no sense to ever use process substitution output to compose a character class,
+ // but...
case L'-':
case L']':
out.push_back('\\');
@@ -1652,7 +1655,9 @@ static bool unescape_string_internal(const wchar_t *const input, const size_t in
}
break;
}
- default: { break; }
+ default: {
+ break;
+ }
}
}
@@ -2232,9 +2237,7 @@ void set_main_thread() {
void configure_thread_assertions_for_testing() { thread_asserts_cfg_for_testing = true; }
-bool is_forked_child() {
- return is_forked_proc;
-}
+bool is_forked_child() { return is_forked_proc; }
void setup_fork_guards() {
is_forked_proc = false;
@@ -2426,12 +2429,11 @@ std::string get_executable_path(const char *argv0) {
// Linux compatibility layer. Per sysctl(3), passing in a process ID of -1 returns
// the value for the current process.
size_t buff_size = sizeof buff;
- int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
+ int name[] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
int result = sysctl(name, sizeof(name) / sizeof(int), buff, &buff_size, nullptr, 0);
if (result != 0) {
wperror(L"sysctl KERN_PROC_PATHNAME");
- }
- else {
+ } else {
return std::string(buff);
}
#else
@@ -2494,9 +2496,10 @@ bool is_console_session() {
const char *TERM = getenv("TERM");
return
// Test that the tty matches /dev/(console|dcons|tty[uv\d])
- tty_name && ((strncmp(tty_name, "/dev/tty", len) == 0 &&
- (tty_name[len] == 'u' || tty_name[len] == 'v' || isdigit(tty_name[len])))
- || strcmp(tty_name, "/dev/dcons") == 0 || strcmp(tty_name, "/dev/console") == 0)
+ tty_name &&
+ ((strncmp(tty_name, "/dev/tty", len) == 0 &&
+ (tty_name[len] == 'u' || tty_name[len] == 'v' || isdigit(tty_name[len]))) ||
+ strcmp(tty_name, "/dev/dcons") == 0 || strcmp(tty_name, "/dev/console") == 0)
// and that $TERM is simple, e.g. `xterm` or `vt100`, not `xterm-something`
&& (!TERM || !strchr(TERM, '-') || !strcmp(TERM, "sun-color"));
}();
diff --git a/src/common.h b/src/common.h
index a10db8906..5c423a929 100644
--- a/src/common.h
+++ b/src/common.h
@@ -6,7 +6,7 @@
#include
#include
// Needed for va_list et al.
-#include // IWYU pragma: keep
+#include // IWYU pragma: keep
#ifdef HAVE_SYS_IOCTL_H
#include // IWYU pragma: keep
#endif
@@ -248,7 +248,8 @@ extern const bool has_working_tty_timestamps;
[[noreturn]] void __fish_assert(const char *msg, const char *file, size_t line, int error);
-/// Shorthand for wgettext call in situations where a C-style string is needed (e.g., std::fwprintf()).
+/// Shorthand for wgettext call in situations where a C-style string is needed (e.g.,
+/// std::fwprintf()).
#define _(wstr) wgettext(wstr).c_str()
/// Noop, used to tell xgettext that a string should be translated. Use this when a string cannot be
@@ -348,26 +349,22 @@ class line_iterator_t {
// The current location in the iteration.
typename Collection::const_iterator current;
-public:
+ public:
/// Construct from a collection (presumably std::string or std::wcstring).
line_iterator_t(const Collection &coll) : coll(coll), current(coll.cbegin()) {}
/// Access the storage in which the last line was stored.
- const Collection &line() const {
- return storage;
- }
+ const Collection &line() const { return storage; }
/// Advances to the next line. \return true on success, false if we have exhausted the string.
bool next() {
- if (current == coll.end())
- return false;
+ if (current == coll.end()) return false;
auto newline_or_end = std::find(current, coll.cend(), '\n');
storage.assign(current, newline_or_end);
current = newline_or_end;
// Skip the newline.
- if (current != coll.cend())
- ++current;
+ if (current != coll.cend()) ++current;
return true;
}
};
@@ -531,7 +528,9 @@ inline bool bool_from_string(const std::string &x) {
}
}
-inline bool bool_from_string(const wcstring &x) { return !x.empty() && std::wcschr(L"YTyt1", x.at(0)); }
+inline bool bool_from_string(const wcstring &x) {
+ return !x.empty() && std::wcschr(L"YTyt1", x.at(0));
+}
wchar_t **make_null_terminated_array(const wcstring_list_t &lst);
char **make_null_terminated_array(const std::vector &lst);
@@ -1014,16 +1013,14 @@ std::string get_executable_path(const char *fallback);
/// A RAII wrapper for resources that don't recur, so we don't have to create a separate RAII
/// wrapper for each function. Avoids needing to call "return cleanup()" or similar / everywhere.
struct cleanup_t {
-private:
+ private:
const std::function cleanup;
-public:
- cleanup_t(std::function exit_actions)
- : cleanup{std::move(exit_actions)} {}
- ~cleanup_t() {
- cleanup();
- }
+
+ public:
+ cleanup_t(std::function exit_actions) : cleanup{std::move(exit_actions)} {}
+ ~cleanup_t() { cleanup(); }
};
bool is_console_session();
-#endif // FISH_COMMON_H
+#endif // FISH_COMMON_H
diff --git a/src/complete.cpp b/src/complete.cpp
index 51e9ac33e..392425fe1 100644
--- a/src/complete.cpp
+++ b/src/complete.cpp
@@ -8,8 +8,8 @@
#include
#include
#include
-#include
#include
+#include
#include
#include
@@ -180,13 +180,9 @@ static bool compare_completions_by_order(const completion_entry_t &p1,
return p1.order < p2.order;
}
-void completion_entry_t::add_option(const complete_entry_opt_t &opt) {
- options.push_front(opt);
-}
+void completion_entry_t::add_option(const complete_entry_opt_t &opt) { options.push_front(opt); }
-const option_list_t &completion_entry_t::get_options() const {
- return options;
-}
+const option_list_t &completion_entry_t::get_options() const { return options; }
description_func_t const_desc(const wcstring &s) {
return [=](const wcstring &ignored) {
@@ -202,7 +198,8 @@ static complete_flags_t resolve_auto_space(const wcstring &comp, complete_flags_
if (flags & COMPLETE_AUTO_SPACE) {
new_flags &= ~COMPLETE_AUTO_SPACE;
size_t len = comp.size();
- if (len > 0 && (std::wcschr(L"/=@:", comp.at(len - 1)) != 0)) new_flags |= COMPLETE_NO_SPACE;
+ if (len > 0 && (std::wcschr(L"/=@:", comp.at(len - 1)) != 0))
+ new_flags |= COMPLETE_NO_SPACE;
}
return new_flags;
}
diff --git a/src/complete.h b/src/complete.h
index 397904f11..f45888a25 100644
--- a/src/complete.h
+++ b/src/complete.h
@@ -195,7 +195,6 @@ void append_completion(std::vector *completions, wcstring comp,
wcstring desc = wcstring(), int flags = 0,
string_fuzzy_match_t match = string_fuzzy_match_t(fuzzy_match_exact));
-
/// Support for "wrap targets." A wrap target is a command that completes like another command.
bool complete_add_wrapper(const wcstring &command, const wcstring &wrap_target);
bool complete_remove_wrapper(const wcstring &command, const wcstring &wrap_target);
diff --git a/src/env.cpp b/src/env.cpp
index 4a58201c8..cec2f59fe 100644
--- a/src/env.cpp
+++ b/src/env.cpp
@@ -306,9 +306,7 @@ struct var_stack_t {
}
/// Copy this vars_stack.
- var_stack_t clone() const {
- return var_stack_t(*this);
- }
+ var_stack_t clone() const { return var_stack_t(*this); }
/// Snapshot this vars_stack. That is, return a new vars_stack that has copies of all local
/// variables. Note that this drops all shadowed nodes: only the currently executing function is
@@ -610,7 +608,7 @@ void env_init(const struct config_paths_t *paths /* or NULL */) {
vars.set_empty(key_and_val, ENV_EXPORT | ENV_GLOBAL);
} else {
key.assign(key_and_val, 0, eql);
- val.assign(key_and_val, eql+1, wcstring::npos);
+ val.assign(key_and_val, eql + 1, wcstring::npos);
if (is_read_only(key) || is_electric(key)) continue;
vars.set(key, ENV_EXPORT | ENV_GLOBAL, {val});
}
@@ -722,7 +720,7 @@ void env_init(const struct config_paths_t *paths /* or NULL */) {
} else {
vars.set_pwd_from_getcwd();
}
- vars.set_termsize(); // initialize the terminal size variables
+ vars.set_termsize(); // initialize the terminal size variables
// Set fish_bind_mode to "default".
vars.set_one(FISH_BIND_MODE_VAR, ENV_GLOBAL, DEFAULT_BIND_MODE);
@@ -822,7 +820,8 @@ static void env_set_internal_universal(const wcstring &key, wcstring_list_t val,
/// * ENV_SCOPE, the variable cannot be set in the given scope. This applies to readonly/electric
/// variables set from the local or universal scopes, or set as exported.
/// * ENV_INVALID, the variable value was invalid. This applies only to special variables.
-int env_stack_t::set_internal(const wcstring &key, env_mode_flags_t input_var_mode, wcstring_list_t val) {
+int env_stack_t::set_internal(const wcstring &key, env_mode_flags_t input_var_mode,
+ wcstring_list_t val) {
ASSERT_IS_MAIN_THREAD();
env_mode_flags_t var_mode = input_var_mode;
bool has_changed_old = vars_stack().has_changed_exported();
diff --git a/src/env.h b/src/env.h
index 6a1a60c85..a883a0098 100644
--- a/src/env.h
+++ b/src/env.h
@@ -164,7 +164,7 @@ class env_var_t {
bool operator==(const env_var_t &rhs) const {
return *vals_ == *rhs.vals_ && flags_ == rhs.flags_;
}
- bool operator!=(const env_var_t &rhs) const { return ! (*this == rhs); }
+ bool operator!=(const env_var_t &rhs) const { return !(*this == rhs); }
};
typedef std::map var_table_t;
@@ -241,7 +241,6 @@ class env_stack_t final : public env_scoped_t {
env_stack_t(env_stack_t &&);
public:
-
/// Sets the variable with the specified name to the given values.
int set(const wcstring &key, env_mode_flags_t mode, wcstring_list_t vals);
diff --git a/src/env_dispatch.cpp b/src/env_dispatch.cpp
index 3d7ef5263..ce21444d8 100644
--- a/src/env_dispatch.cpp
+++ b/src/env_dispatch.cpp
@@ -24,8 +24,8 @@
#include
#endif
-#include
#include
+#include
#include
#include
#include
diff --git a/src/env_universal_common.cpp b/src/env_universal_common.cpp
index 5ab4ad7ad..39d7831d8 100644
--- a/src/env_universal_common.cpp
+++ b/src/env_universal_common.cpp
@@ -43,8 +43,8 @@
#include "path.h"
#include "utf8.h"
#include "util.h" // IWYU pragma: keep
-#include "wutil.h"
#include "wcstringutil.h"
+#include "wutil.h"
#if __APPLE__
#define FISH_NOTIFYD_AVAILABLE 1
@@ -229,7 +229,7 @@ static bool append_file_entry(env_var_t::env_var_flags_t flags, const wcstring &
}
/// Encoding of a null string.
-static const wchar_t * const ENV_NULL = L"\x1d";
+static const wchar_t *const ENV_NULL = L"\x1d";
/// Character used to separate arrays in universal variables file.
/// This is 30, the ASCII record separator.
@@ -433,7 +433,8 @@ std::string env_universal_t::serialize_with_vars(const var_table_t &vars) {
// variable; soldier on.
const wcstring &key = kv.first;
const env_var_t &var = kv.second;
- append_file_entry(var.get_flags(), key, encode_serialized(var.as_list()), &contents, &storage);
+ append_file_entry(var.get_flags(), key, encode_serialized(var.as_list()), &contents,
+ &storage);
}
return contents;
}
@@ -902,7 +903,7 @@ void env_universal_t::parse_message_30_internal(const wcstring &msgstr, var_tabl
/// Parse message msg per fish 2.x format.
void env_universal_t::parse_message_2x_internal(const wcstring &msgstr, var_table_t *vars,
- wcstring *storage) {
+ wcstring *storage) {
namespace f2x = fish2x_uvars;
const wchar_t *const msg = msgstr.c_str();
const wchar_t *cursor = msg;
@@ -996,8 +997,9 @@ static bool get_mac_address(unsigned char macaddr[MAC_ADDRESS_MAX_LEN]) { return
/// Function to get an identifier based on the hostname.
bool get_hostname_identifier(wcstring &result) {
- //The behavior of gethostname if the buffer size is insufficient differs by implementation and libc version
- //Work around this by using a "guaranteed" sufficient buffer size then truncating the result.
+ // The behavior of gethostname if the buffer size is insufficient differs by implementation and
+ // libc version Work around this by using a "guaranteed" sufficient buffer size then truncating
+ // the result.
bool success = false;
char hostname[256] = {};
if (gethostname(hostname, sizeof(hostname)) == 0) {
diff --git a/src/event.cpp b/src/event.cpp
index 9cab7d427..a1f63f5f1 100644
--- a/src/event.cpp
+++ b/src/event.cpp
@@ -35,7 +35,7 @@ class pending_signals_t {
/// This is not accessed from a signal handler.
owning_lock last_counter_{0};
-public:
+ public:
pending_signals_t() = default;
/// No copying.
@@ -64,7 +64,8 @@ public:
return {};
}
- // The signal count has changed. Store the new counter and fetch all the signals that are set.
+ // The signal count has changed. Store the new counter and fetch all the signals that are
+ // set.
*current = count;
std::bitset result{};
uint32_t bit = 0;
@@ -183,7 +184,9 @@ wcstring event_get_desc(const event_t &evt) {
case event_type_t::generic: {
return format_string(_(L"handler for generic event '%ls'"), ed.str_param1.c_str());
}
- case event_type_t::any: { DIE("Unreachable"); }
+ case event_type_t::any: {
+ DIE("Unreachable");
+ }
default:
DIE("Unknown event type");
}
@@ -291,8 +294,7 @@ static void event_fire_internal(const event_t &event) {
void event_fire_delayed() {
ASSERT_IS_MAIN_THREAD();
// Do not invoke new event handlers from within event handlers.
- if (is_event)
- return;
+ if (is_event) return;
event_list_t to_send;
to_send.swap(blocked);
@@ -301,7 +303,7 @@ void event_fire_delayed() {
// Append all signal events to to_send.
auto signals = s_pending_signals.acquire_pending();
if (signals.any()) {
- for (uint32_t sig=0; sig < signals.size(); sig++) {
+ for (uint32_t sig = 0; sig < signals.size(); sig++) {
if (signals.test(sig)) {
auto e = std::make_shared(event_type_t::signal);
e->desc.param1.signal = sig;
@@ -368,7 +370,6 @@ static const wchar_t *event_name_for_type(event_type_t type) {
return L"";
}
-
void event_print(io_streams_t &streams, maybe_t type_filter) {
event_handler_list_t tmp = s_event_handlers;
std::sort(tmp.begin(), tmp.end(),
@@ -401,8 +402,7 @@ void event_print(io_streams_t &streams, maybe_t type_filter) {
}
if (!last_type || *last_type != evt->desc.type) {
- if (last_type)
- streams.out.append(L"\n");
+ if (last_type) streams.out.append(L"\n");
last_type = static_cast(evt->desc.type);
streams.out.append_format(L"Event %ls\n", event_name_for_type(*last_type));
}
@@ -421,7 +421,8 @@ void event_print(io_streams_t &streams, maybe_t type_filter) {
streams.out.append_format(L"%ls %ls\n", evt->desc.str_param1.c_str(),
evt->function_name.c_str());
break;
- case event_type_t::any: DIE("Unreachable");
+ case event_type_t::any:
+ DIE("Unreachable");
default:
streams.out.append_format(L"%ls\n", evt->function_name.c_str());
break;
diff --git a/src/exec.cpp b/src/exec.cpp
index 414665927..f5d2003a0 100644
--- a/src/exec.cpp
+++ b/src/exec.cpp
@@ -14,9 +14,9 @@
#include
#endif
#include
-#include
#include
#include
+#include
#include
#include
@@ -675,8 +675,8 @@ static bool handle_builtin_output(const std::shared_ptr &j, process_t *p,
/// Executes an external command.
/// \return true on success, false if there is an exec error.
-static bool exec_external_command(env_stack_t &vars, const std::shared_ptr &j,
- process_t *p, const io_chain_t &proc_io_chain) {
+static bool exec_external_command(env_stack_t &vars, const std::shared_ptr &j, process_t *p,
+ const io_chain_t &proc_io_chain) {
assert(p->type == process_type_t::external && "Process is not external");
// Get argv and envv before we fork.
null_terminated_array_t argv_array;
@@ -684,8 +684,7 @@ static bool exec_external_command(env_stack_t &vars, const std::shared_ptr
#include
#include
-#include
#include
-#include
#include
+#include
+#include
#ifdef HAVE_SYS_SYSCTL_H
#include // IWYU pragma: keep
@@ -124,9 +124,7 @@ static void append_cmdsub_error(parse_error_list_t *errors, size_t source_start,
/// Test if the specified string does not contain character which can not be used inside a quoted
/// string.
-static bool is_quotable(const wchar_t *str) {
- return !std::wcspbrk(str, L"\n\t\r\b\x1B");
-}
+static bool is_quotable(const wchar_t *str) { return !std::wcspbrk(str, L"\n\t\r\b\x1B"); }
static bool is_quotable(const wcstring &str) { return is_quotable(str.c_str()); }
@@ -168,7 +166,8 @@ wcstring expand_escape_variable(const env_var_t &var) {
/// Parse an array slicing specification Returns 0 on success. If a parse error occurs, returns the
/// index of the bad token. Note that 0 can never be a bad index because the string always starts
/// with [.
-static size_t parse_slice(const wchar_t *in, wchar_t **end_ptr, std::vector &idx, size_t array_size) {
+static size_t parse_slice(const wchar_t *in, wchar_t **end_ptr, std::vector &idx,
+ size_t array_size) {
const long size = (long)array_size;
size_t pos = 1; // skip past the opening square brace
@@ -360,11 +359,12 @@ static bool expand_variables(wcstring instr, std::vector *out, siz
} else if (history) {
effective_val_count = history->size();
}
- size_t bad_pos = parse_slice(in + slice_start, &slice_end, var_idx_list, effective_val_count);
+ size_t bad_pos =
+ parse_slice(in + slice_start, &slice_end, var_idx_list, effective_val_count);
if (bad_pos != 0) {
if (in[slice_start + bad_pos] == L'0') {
append_syntax_error(errors, slice_start + bad_pos,
- L"array indices start at 1, not 0.");
+ L"array indices start at 1, not 0.");
} else {
append_syntax_error(errors, slice_start + bad_pos, L"Invalid index value");
}
@@ -638,8 +638,7 @@ static bool expand_cmdsubst(wcstring input, parser_t &parser, std::vector // IWYU pragma: keep
#include // IWYU pragma: keep
#include
-#include
#include // IWYU pragma: keep
#include // IWYU pragma: keep
#include
-#include
#include
#include
+#include
+#include
#if HAVE_GETTEXT
#include
#endif
@@ -37,7 +37,7 @@
#include
#endif
#include // IWYU pragma: keep
-#include // IWYU pragma: keep
+#include // IWYU pragma: keep
#include "common.h" // IWYU pragma: keep
#include "fallback.h" // IWYU pragma: keep
@@ -45,8 +45,8 @@
#if defined(TPARM_SOLARIS_KLUDGE)
#undef tparm
-char *tparm_solaris_kludge(char *str, long p1, long p2, long p3, long p4,
- long p5, long p6, long p7, long p8, long p9) {
+char *tparm_solaris_kludge(char *str, long p1, long p2, long p3, long p4, long p5, long p6, long p7,
+ long p8, long p9) {
return tparm(str, p1, p2, p3, p4, p5, p6, p7, p8, p9);
}
@@ -97,8 +97,7 @@ int fish_mkstemp_cloexec(char *name_template) {
return wcscasecmp_fallback(a + 1, b + 1);
}
-[[gnu::unused]] static int wcsncasecmp_fallback(const wchar_t *a, const wchar_t *b,
- size_t count) {
+[[gnu::unused]] static int wcsncasecmp_fallback(const wchar_t *a, const wchar_t *b, size_t count) {
if (count == 0) return 0;
if (*a == 0) {
@@ -281,8 +280,10 @@ int fish_wcwidth(wchar_t wc) {
// (width 1) to an emoji (probably width 2). So treat it as width 1 so the sums work. See #2652.
// VS15 selects text presentation.
const wchar_t variation_selector_16 = L'\uFE0F', variation_selector_15 = L'\uFE0E';
- if (wc == variation_selector_16) return 1;
- else if (wc == variation_selector_15) return 0;
+ if (wc == variation_selector_16)
+ return 1;
+ else if (wc == variation_selector_15)
+ return 0;
// Korean Hangul Jamo median vowels and final consonants.
// These can either appear in combined form, taking 0 width themselves,
@@ -403,4 +404,4 @@ double fish_compat::wcstod_l(const wchar_t *enptr, wchar_t **endptr, locale_t lo
uselocale(prev_locale);
return ret;
}
-#endif // defined(wcstod_l)
+#endif // defined(wcstod_l)
diff --git a/src/fallback.h b/src/fallback.h
index 50796cad6..0c5ddb237 100644
--- a/src/fallback.h
+++ b/src/fallback.h
@@ -196,8 +196,8 @@ int flock(int fd, int op);
#endif
// NetBSD _has_ wcstod_l, but it's doing some weak linking hullabaloo that I don't get.
-// Since it doesn't have uselocale (yes, the standard function isn't there, the non-standard extension is),
-// we can't try to use the fallback.
+// Since it doesn't have uselocale (yes, the standard function isn't there, the non-standard
+// extension is), we can't try to use the fallback.
#if !defined(HAVE_WCSTOD_L) && !defined(__NetBSD__)
// On some platforms if this is incorrectly detected and a system-defined
// defined version of `wcstod_l` exists, calling `wcstod` from our own
@@ -207,7 +207,7 @@ int flock(int fd, int op);
// duplication.
#undef wcstod_l
namespace fish_compat {
- double wcstod_l(const wchar_t *enptr, wchar_t **endptr, locale_t loc);
+double wcstod_l(const wchar_t *enptr, wchar_t **endptr, locale_t loc);
}
#define wcstod_l(x, y, z) fish_compat::wcstod_l(x, y, z)
#endif
diff --git a/src/fish.cpp b/src/fish.cpp
index 92092fe0a..34d231cd0 100644
--- a/src/fish.cpp
+++ b/src/fish.cpp
@@ -27,10 +27,10 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#include
#include
#include
-#include
#include
#include
#include
+#include
#include
#include
@@ -73,8 +73,8 @@ static const char *s_profiling_output_filename = NULL;
/// \return a timeval converted to milliseconds.
long long tv_to_msec(const struct timeval &tv) {
- long long msec = (long long)tv.tv_sec * 1000; // milliseconds per second
- msec += tv.tv_usec / 1000; // microseconds per millisecond
+ long long msec = (long long)tv.tv_sec * 1000; // milliseconds per second
+ msec += tv.tv_usec / 1000; // microseconds per millisecond
return msec;
}
@@ -130,7 +130,9 @@ static struct config_paths_t determine_config_directory_paths(const char *argv0)
#ifdef CMAKE_BINARY_DIR
// Detect if we're running right out of the CMAKE build directory
if (string_prefixes_string(CMAKE_BINARY_DIR, exec_path.c_str())) {
- debug(2, "Running out of build directory, using paths relative to CMAKE_SOURCE_DIR:\n %s", CMAKE_SOURCE_DIR);
+ debug(2,
+ "Running out of build directory, using paths relative to CMAKE_SOURCE_DIR:\n %s",
+ CMAKE_SOURCE_DIR);
done = true;
paths.data = wcstring{L"" CMAKE_SOURCE_DIR} + L"/share";
@@ -249,7 +251,7 @@ int run_command_list(std::vector *cmds, const io_chain_t &io) {
/// Parse the argument list, return the index of the first non-flag arguments.
static int fish_parse_opt(int argc, char **argv, fish_cmd_opts_t *opts) {
- static const char * const short_opts = "+hPilnvc:C:p:d:f:D:";
+ static const char *const short_opts = "+hPilnvc:C:p:d:f:D:";
static const struct option long_opts[] = {{"command", required_argument, NULL, 'c'},
{"init-command", required_argument, NULL, 'C'},
{"features", required_argument, NULL, 'f'},
@@ -339,7 +341,8 @@ static int fish_parse_opt(int argc, char **argv, fish_cmd_opts_t *opts) {
if (tmp > 0 && tmp <= 128 && !*end && !errno) {
set_debug_stack_frames((int)tmp);
} else {
- std::fwprintf(stderr, _(L"Invalid value '%s' for debug-stack-frames flag"), optarg);
+ std::fwprintf(stderr, _(L"Invalid value '%s' for debug-stack-frames flag"),
+ optarg);
exit(1);
}
break;
diff --git a/src/fish_indent.cpp b/src/fish_indent.cpp
index 7591dcc89..4c53484ae 100644
--- a/src/fish_indent.cpp
+++ b/src/fish_indent.cpp
@@ -23,15 +23,15 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
#include
#include
#include
-#include
#include
+#include
#include
#include
-#include
-#include
#include
+#include
#include
+#include
#include "color.h"
#include "common.h"
@@ -62,7 +62,7 @@ static wcstring read_file(FILE *f) {
if (errno == EILSEQ) {
// Illegal byte sequence. Try to skip past it.
clearerr(f);
- int ch = fgetc(f); // for printing the warning, and seeks forward 1 byte.
+ int ch = fgetc(f); // for printing the warning, and seeks forward 1 byte.
debug(1, "%s (byte=%X)", std::strerror(errno), ch);
ret = 1;
continue;
@@ -119,8 +119,8 @@ struct prettifier_t {
line_continuation_indent = is_continuation ? 1 : 0;
}
- // Append whitespace as necessary. If we have a newline, append the appropriate indent. Otherwise,
- // append a space.
+ // Append whitespace as necessary. If we have a newline, append the appropriate indent.
+ // Otherwise, append a space.
void append_whitespace(indent_t node_indent) {
if (needs_continuation_newline) {
append_newline(true);
@@ -131,7 +131,6 @@ struct prettifier_t {
output.append((node_indent + line_continuation_indent) * SPACES_PER_INDENT, L' ');
}
}
-
};
// Dump a parse tree node in a form helpful to someone debugging the behavior of this program.
@@ -160,8 +159,9 @@ static void dump_node(indent_t node_indent, const parse_node_t &node, const wcst
nextc_str[2] = nextc + '@';
}
std::fwprintf(stderr, L"{off %4u, len %4u, indent %2u, kw %ls, %ls} [%ls|%ls|%ls]\n",
- node.source_start, node.source_length, node_indent, keyword_description(node.keyword),
- token_type_description(node.type), prevc_str, source_txt.c_str(), nextc_str);
+ node.source_start, node.source_length, node_indent,
+ keyword_description(node.keyword), token_type_description(node.type), prevc_str,
+ source_txt.c_str(), nextc_str);
}
void prettifier_t::prettify_node(const parse_node_tree_t &tree, node_offset_t node_idx,
@@ -185,16 +185,17 @@ void prettifier_t::prettify_node(const parse_node_tree_t &tree, node_offset_t no
const parse_node_t &node = tree.at(node_idx);
const parse_token_type_t node_type = node.type;
const parse_token_type_t prev_node_type =
- node_idx > 0 ? tree.at(node_idx - 1).type : token_type_invalid;
+ node_idx > 0 ? tree.at(node_idx - 1).type : token_type_invalid;
- // Increment the indent if we are either a root job_list, or root case_item_list, or in an if or
- // while header (#1665).
- const bool is_root_job_list = node_type == symbol_job_list && parent_type != symbol_job_list;
+ // Increment the indent if we are either a root job_list, or root case_item_list, or in an
+ // if or while header (#1665).
+ const bool is_root_job_list =
+ node_type == symbol_job_list && parent_type != symbol_job_list;
const bool is_root_case_list =
- node_type == symbol_case_item_list && parent_type != symbol_case_item_list;
+ node_type == symbol_case_item_list && parent_type != symbol_case_item_list;
const bool is_if_while_header =
- (node_type == symbol_job_conjunction || node_type == symbol_andor_job_list) &&
- (parent_type == symbol_if_clause || parent_type == symbol_while_header);
+ (node_type == symbol_job_conjunction || node_type == symbol_andor_job_list) &&
+ (parent_type == symbol_if_clause || parent_type == symbol_while_header);
if (is_root_job_list || is_root_case_list || is_if_while_header) {
node_indent += 1;
@@ -253,7 +254,8 @@ void prettifier_t::prettify_node(const parse_node_tree_t &tree, node_offset_t no
for (node_offset_t idx = node.child_count; idx > 0; idx--) {
// Note: We pass our type to our child, which becomes its parent node type.
// Note: While node.child_start could be -1 (NODE_OFFSET_INVALID) the addition is safe
- // because we won't execute this call in that case since node.child_count should be zero.
+ // because we won't execute this call in that case since node.child_count should be
+ // zero.
pending_node_stack.push({node.child_start + (idx - 1), node_indent, node_type});
}
}
@@ -435,7 +437,9 @@ static const wchar_t *html_class_name_for_color(highlight_spec_t spec) {
case highlight_role_t::selection: {
return P(selection);
}
- default: { return P(other); }
+ default: {
+ return P(other);
+ }
}
}
@@ -593,7 +597,8 @@ int main(int argc, char *argv[]) {
if (tmp > 0 && tmp <= 128 && !*end && !errno) {
set_debug_stack_frames((int)tmp);
} else {
- std::fwprintf(stderr, _(L"Invalid value '%s' for debug-stack-frames flag"), optarg);
+ std::fwprintf(stderr, _(L"Invalid value '%s' for debug-stack-frames flag"),
+ optarg);
exit(1);
}
break;
@@ -612,8 +617,9 @@ int main(int argc, char *argv[]) {
wcstring src;
if (argc == 0) {
if (output_type == output_type_file) {
- std::fwprintf(stderr, _(L"Expected file path to read/write for -w:\n\n $ %ls -w foo.fish\n"),
- program_name);
+ std::fwprintf(stderr,
+ _(L"Expected file path to read/write for -w:\n\n $ %ls -w foo.fish\n"),
+ program_name);
exit(1);
}
src = read_file(stdin);
@@ -661,7 +667,7 @@ int main(int argc, char *argv[]) {
exit(0);
} else {
std::fwprintf(stderr, _(L"Opening \"%s\" failed: %s\n"), output_location,
- std::strerror(errno));
+ std::strerror(errno));
exit(1);
}
break;
diff --git a/src/fish_key_reader.cpp b/src/fish_key_reader.cpp
index 4549d927a..0100d690d 100644
--- a/src/fish_key_reader.cpp
+++ b/src/fish_key_reader.cpp
@@ -14,9 +14,9 @@
#include
#include
#include
-#include
#include
#include
+#include
#include
#include
@@ -191,7 +191,8 @@ static double output_elapsed_time(double prev_tstamp, bool first_char_seen) {
if (delta_tstamp_us >= 1000000) {
std::fwprintf(stderr, L" ");
} else {
- std::fwprintf(stderr, L"(%3lld.%03lld ms) ", delta_tstamp_us / 1000, delta_tstamp_us % 1000);
+ std::fwprintf(stderr, L"(%3lld.%03lld ms) ", delta_tstamp_us / 1000,
+ delta_tstamp_us % 1000);
}
return now;
}
@@ -293,9 +294,10 @@ static void setup_and_process_keys(bool continuous_mode) {
if (continuous_mode) {
std::fwprintf(stderr, L"\n");
- std::fwprintf(stderr, L"To terminate this program type \"exit\" or \"quit\" in this window,\n");
+ std::fwprintf(stderr,
+ L"To terminate this program type \"exit\" or \"quit\" in this window,\n");
std::fwprintf(stderr, L"or press [ctrl-%c] or [ctrl-%c] twice in a row.\n",
- shell_modes.c_cc[VINTR] + 0x40, shell_modes.c_cc[VEOF] + 0x40);
+ shell_modes.c_cc[VINTR] + 0x40, shell_modes.c_cc[VEOF] + 0x40);
std::fwprintf(stderr, L"\n");
}
diff --git a/src/fish_tests.cpp b/src/fish_tests.cpp
index eca2a2060..9f995b990 100644
--- a/src/fish_tests.cpp
+++ b/src/fish_tests.cpp
@@ -14,7 +14,6 @@
#include
#include
#include
-#include
#include
#include
#include
@@ -23,8 +22,9 @@
#include
#include
#include
-#include
#include
+#include
+#include
#include
#include
@@ -494,7 +494,7 @@ static char *str2hex(const char *input) {
/// comes back through double conversion.
static void test_convert() {
int i;
- std::vector sb {};
+ std::vector sb{};
say(L"Testing wide/narrow string conversion");
@@ -612,10 +612,11 @@ static void test_tokenizer() {
}
if (types[i] != token.type) {
err(L"Tokenization error:");
- std::fwprintf(stdout,
- L"Token number %zu of string \n'%ls'\n, expected type %ld, got token type "
- L"%ld\n",
- i + 1, str, (long)types[i], (long)token.type);
+ std::fwprintf(
+ stdout,
+ L"Token number %zu of string \n'%ls'\n, expected type %ld, got token type "
+ L"%ld\n",
+ i + 1, str, (long)types[i], (long)token.type);
}
i++;
}
@@ -734,9 +735,7 @@ static void test_pthread() {
say(L"Testing pthreads");
pthread_t result = {};
int val = 3;
- bool made = make_pthread(&result, [&val](){
- val += 2;
- });
+ bool made = make_pthread(&result, [&val]() { val += 2; });
do_test(made);
void *ignore = nullptr;
int ret = pthread_join(result, &ignore);
@@ -1900,18 +1899,20 @@ static void test_abbreviations() {
err(L"gc incorrectly expanded on line %ld to '%ls'", (long)__LINE__, result.c_str());
// If commands should be expanded.
- expanded = reader_expand_abbreviation_in_command(L"if gc", std::wcslen(L"if gc"), vars, &result);
+ expanded =
+ reader_expand_abbreviation_in_command(L"if gc", std::wcslen(L"if gc"), vars, &result);
if (!expanded) err(L"gc not expanded on line %ld", (long)__LINE__);
if (result != L"if git checkout")
err(L"gc incorrectly expanded on line %ld to '%ls'", (long)__LINE__, result.c_str());
// Others should not be.
- expanded = reader_expand_abbreviation_in_command(L"of gc", std::wcslen(L"of gc"), vars, &result);
+ expanded =
+ reader_expand_abbreviation_in_command(L"of gc", std::wcslen(L"of gc"), vars, &result);
if (expanded) err(L"gc incorrectly expanded on line %ld", (long)__LINE__);
// Others should not be.
- expanded =
- reader_expand_abbreviation_in_command(L"command gc", std::wcslen(L"command gc"), vars, &result);
+ expanded = reader_expand_abbreviation_in_command(L"command gc", std::wcslen(L"command gc"),
+ vars, &result);
if (expanded) err(L"gc incorrectly expanded on line %ld", (long)__LINE__);
vars.pop();
@@ -2055,11 +2056,11 @@ struct pager_layout_testcase_t {
wcstring text = sd.line(0).to_string();
if (text != expected) {
std::fwprintf(stderr, L"width %zu got %zu<%ls>, expected %zu<%ls>\n", this->width,
- text.length(), text.c_str(), expected.length(), expected.c_str());
+ text.length(), text.c_str(), expected.length(), expected.c_str());
for (size_t i = 0; i < std::max(text.length(), expected.length()); i++) {
std::fwprintf(stderr, L"i %zu got <%lx> expected <%lx>\n", i,
- i >= text.length() ? 0xffff : text[i],
- i >= expected.length() ? 0xffff : expected[i]);
+ i >= text.length() ? 0xffff : text[i],
+ i >= expected.length() ? 0xffff : expected[i]);
}
}
do_test(text == expected);
@@ -2252,8 +2253,7 @@ static bool run_one_test_test(int expected, wcstring_list_t &lst, bool bracket)
io_streams_t streams(0);
int result = builtin_test(parser, streams, argv);
- if (expected != result)
- err(L"expected builtin_test() to return %d, got %d", expected, result);
+ if (expected != result) err(L"expected builtin_test() to return %d, got %d", expected, result);
delete[] argv;
@@ -2716,7 +2716,7 @@ static void test_1_completion(wcstring line, const wcstring &completion, complet
completion_apply_to_command_line(completion, flags, line, &cursor_pos, append_only);
if (result != expected) {
std::fwprintf(stderr, L"line %ld: %ls + %ls -> [%ls], expected [%ls]\n", source_line,
- line.c_str(), completion.c_str(), result.c_str(), expected.c_str());
+ line.c_str(), completion.c_str(), result.c_str(), expected.c_str());
}
do_test(result == expected);
do_test(cursor_pos == out_cursor_pos);
@@ -2759,15 +2759,15 @@ static void perform_one_autosuggestion_cd_test(const wcstring &command, const wc
bool expects_error = (expected == L"");
if (comps.empty() && !expects_error) {
- std::fwprintf(stderr, L"line %ld: autosuggest_suggest_special() failed for command %ls\n", line,
- command.c_str());
+ std::fwprintf(stderr, L"line %ld: autosuggest_suggest_special() failed for command %ls\n",
+ line, command.c_str());
do_test_from(!comps.empty(), line);
return;
} else if (!comps.empty() && expects_error) {
std::fwprintf(stderr,
- L"line %ld: autosuggest_suggest_special() was expected to fail but did not, "
- L"for command %ls\n",
- line, command.c_str());
+ L"line %ld: autosuggest_suggest_special() was expected to fail but did not, "
+ L"for command %ls\n",
+ line, command.c_str());
do_test_from(comps.empty(), line);
}
@@ -2795,15 +2795,15 @@ static void perform_one_completion_cd_test(const wcstring &command, const wcstri
bool expects_error = (expected == L"");
if (comps.empty() && !expects_error) {
- std::fwprintf(stderr, L"line %ld: autosuggest_suggest_special() failed for command %ls\n", line,
- command.c_str());
+ std::fwprintf(stderr, L"line %ld: autosuggest_suggest_special() failed for command %ls\n",
+ line, command.c_str());
do_test_from(!comps.empty(), line);
return;
} else if (!comps.empty() && expects_error) {
std::fwprintf(stderr,
- L"line %ld: autosuggest_suggest_special() was expected to fail but did not, "
- L"for command %ls\n",
- line, command.c_str());
+ L"line %ld: autosuggest_suggest_special() was expected to fail but did not, "
+ L"for command %ls\n",
+ line, command.c_str());
do_test_from(comps.empty(), line);
}
@@ -2813,9 +2813,9 @@ static void perform_one_completion_cd_test(const wcstring &command, const wcstri
if (suggestion.completion != expected) {
std::fwprintf(stderr,
- L"line %ld: complete() for cd tab completion returned the wrong expected "
- L"string for command %ls\n",
- line, command.c_str());
+ L"line %ld: complete() for cd tab completion returned the wrong expected "
+ L"string for command %ls\n",
+ line, command.c_str());
std::fwprintf(stderr, L" actual: %ls\n", suggestion.completion.c_str());
std::fwprintf(stderr, L"expected: %ls\n", expected.c_str());
do_test_from(suggestion.completion == expected, line);
@@ -2935,7 +2935,7 @@ static void perform_one_autosuggestion_should_ignore_test(const wcstring &comman
if (!comps.empty()) {
const wcstring &suggestion = comps.front().completion;
std::fwprintf(stderr, L"line %ld: complete() expected to return nothing for %ls\n", line,
- command.c_str());
+ command.c_str());
std::fwprintf(stderr, L" instead got: %ls\n", suggestion.c_str());
}
}
@@ -3194,8 +3194,8 @@ static void test_universal_callbacks() {
// Change uvars1.
uvars1.set(L"alpha", env_var_t{L"2", noflags}); // changes value
uvars1.set(L"beta", env_var_t{L"1", env_var_t::flag_export}); // changes export
- uvars1.remove(L"delta"); // erases value
- uvars1.set(L"epsilon", env_var_t{L"1", noflags}); // changes nothing
+ uvars1.remove(L"delta"); // erases value
+ uvars1.set(L"epsilon", env_var_t{L"1", noflags}); // changes nothing
uvars1.sync(callbacks);
// Change uvars2. It should treat its value as correct and ignore changes from uvars1.
@@ -4547,7 +4547,7 @@ static void test_pcre2_escape() {
// all the following are intended to be ultimately matched literally - even if they don't look
// like that's the intent - so we escape them.
- const wchar_t * const tests[][2] = {
+ const wchar_t *const tests[][2] = {
{L".ext", L"\\.ext"},
{L"{word}", L"\\{word\\}"},
{L"hola-mundo", L"hola\\-mundo"},
@@ -4558,7 +4558,8 @@ static void test_pcre2_escape() {
for (const auto &test : tests) {
auto escaped = escape_string(test[0], 0, STRING_STYLE_REGEX);
if (escaped != test[1]) {
- err(L"pcre2_escape error: pcre2_escape(%ls) -> %ls, expected %ls", test[0], escaped.c_str(), test[1]);
+ err(L"pcre2_escape error: pcre2_escape(%ls) -> %ls, expected %ls", test[0],
+ escaped.c_str(), test[1]);
}
}
}
@@ -4947,9 +4948,9 @@ static void test_env_vars() {
env_var_t v2 = {wcstring_list_t{L"abc"}, env_var_t::flag_export};
env_var_t v3 = {wcstring_list_t{L"abc"}, 0};
env_var_t v4 = {wcstring_list_t{L"abc", L"def"}, env_var_t::flag_export};
- do_test(v1 == v2 && ! (v1 != v2));
- do_test(v1 != v3 && ! (v1 == v3));
- do_test(v1 != v4 && ! (v1 == v4));
+ do_test(v1 == v2 && !(v1 != v2));
+ do_test(v1 != v3 && !(v1 == v3));
+ do_test(v1 != v4 && !(v1 == v4));
}
static void test_illegal_command_exit_code() {
@@ -5211,8 +5212,8 @@ int main(int argc, char **argv) {
exit(-1);
}
if (!std::strcmp(wd, "/")) {
- std::fwprintf(stderr,
- L"Unable to find 'tests' directory, which should contain file test.fish\n");
+ std::fwprintf(
+ stderr, L"Unable to find 'tests' directory, which should contain file test.fish\n");
exit(EXIT_FAILURE);
}
if (chdir(dirname(wd)) < 0) {
diff --git a/src/fish_version.cpp b/src/fish_version.cpp
index d3095575b..da8bd4ea8 100644
--- a/src/fish_version.cpp
+++ b/src/fish_version.cpp
@@ -8,7 +8,7 @@
// The contents of FISH-BUILD-VERSION-FILE looks like:
// FISH_BUILD_VERSION="2.7.1-62-gc0480092-dirty"
// Arrange for it to become a variable.
-static const char * const
+static const char *const
#include "FISH-BUILD-VERSION-FILE"
;
#endif
diff --git a/src/future_feature_flags.cpp b/src/future_feature_flags.cpp
index 2caf145f5..f8e430cb9 100644
--- a/src/future_feature_flags.cpp
+++ b/src/future_feature_flags.cpp
@@ -13,7 +13,8 @@ features_t &mutable_fish_features() { return global_features; }
const features_t::metadata_t features_t::metadata[features_t::flag_count] = {
{stderr_nocaret, L"stderr-nocaret", L"3.0", L"^ no longer redirects stderr"},
{qmark_noglob, L"qmark-noglob", L"3.0", L"? no longer globs"},
- {string_replace_backslash, L"string-replace-fewer-backslashes", L"3.1", L"string replace -r needs fewer backslashes in the replacement"},
+ {string_replace_backslash, L"string-replace-fewer-backslashes", L"3.1",
+ L"string replace -r needs fewer backslashes in the replacement"},
};
const struct features_t::metadata_t *features_t::metadata_for(const wchar_t *name) {
diff --git a/src/future_feature_flags.h b/src/future_feature_flags.h
index 1c42cb21a..822c127ee 100644
--- a/src/future_feature_flags.h
+++ b/src/future_feature_flags.h
@@ -8,26 +8,26 @@
#include "common.h"
class features_t {
-public:
+ public:
/// The list of flags.
- enum flag_t {
- /// Whether ^ is supported for stderr redirection.
- stderr_nocaret,
+ enum flag_t {
+ /// Whether ^ is supported for stderr redirection.
+ stderr_nocaret,
- /// Whether ? is supported as a glob.
- qmark_noglob,
+ /// Whether ? is supported as a glob.
+ qmark_noglob,
- /// Whether string replace -r double-unescapes the replacement.
- string_replace_backslash,
+ /// Whether string replace -r double-unescapes the replacement.
+ string_replace_backslash,
- /// The number of flags.
- flag_count
- };
+ /// The number of flags.
+ flag_count
+ };
- /// Return whether a flag is set.
- bool test(flag_t f) const {
- assert(f >= 0 && f < flag_count && "Invalid flag");
- return values[f];
+ /// Return whether a flag is set.
+ bool test(flag_t f) const {
+ assert(f >= 0 && f < flag_count && "Invalid flag");
+ return values[f];
}
/// Set a flag.
diff --git a/src/highlight.cpp b/src/highlight.cpp
index e79627afc..f7075795a 100644
--- a/src/highlight.cpp
+++ b/src/highlight.cpp
@@ -696,7 +696,7 @@ static void color_string_internal(const wcstring &buffstr, highlight_spec_t base
if (escaped_char == L'\\' || escaped_char == L'\'') {
colors[in_pos] = highlight_role_t::escape; // backslash
colors[in_pos + 1] = highlight_role_t::escape; // escaped char
- in_pos += 1; // skip over backslash
+ in_pos += 1; // skip over backslash
}
}
} else if (c == L'\'') {
@@ -723,7 +723,7 @@ static void color_string_internal(const wcstring &buffstr, highlight_spec_t base
if (std::wcschr(L"\\\"\n$", escaped_char)) {
colors[in_pos] = highlight_role_t::escape; // backslash
colors[in_pos + 1] = highlight_role_t::escape; // escaped char
- in_pos += 1; // skip over backslash
+ in_pos += 1; // skip over backslash
}
}
break;
@@ -1247,7 +1247,9 @@ const highlighter_t::color_array_t &highlighter_t::highlight() {
this->color_node(node, highlight_role_t::comment);
break;
}
- default: { break; }
+ default: {
+ break;
+ }
}
}
diff --git a/src/history.cpp b/src/history.cpp
index 02ba92aa1..3805e59f0 100644
--- a/src/history.cpp
+++ b/src/history.cpp
@@ -8,8 +8,8 @@
#include
#include
#include
-#include
#include
+#include
// We need the sys/file.h for the flock() declaration on Linux but not OS X.
#include // IWYU pragma: keep
#include
@@ -554,7 +554,6 @@ bool history_item_t::merge(const history_item_t &item) {
history_item_t::history_item_t(const wcstring &str, time_t when, history_identifier_t ident)
: creation_timestamp(when), identifier(ident) {
-
contents = trim(str);
contents_lower.reserve(contents.size());
for (const auto &c : contents) {
@@ -1971,7 +1970,6 @@ void history_t::resolve_pending() {
this->has_pending_item = false;
}
-
static std::atomic private_mode{false};
void start_private_mode() {
@@ -1981,6 +1979,4 @@ void start_private_mode() {
vars.set_one(L"fish_private_mode", ENV_GLOBAL, L"1");
}
-bool in_private_mode() {
- return private_mode.load();
-}
+bool in_private_mode() { return private_mode.load(); }
diff --git a/src/input.cpp b/src/input.cpp
index e36a24593..8332b0bf9 100644
--- a/src/input.cpp
+++ b/src/input.cpp
@@ -2,8 +2,8 @@
#include "config.h"
#include
-#include
#include
+#include
#if HAVE_TERM_H
#include
#include
@@ -229,7 +229,7 @@ void input_mapping_add(const wchar_t *sequence, const wchar_t *const *commands,
mapping_list_t &ml = user ? s_mapping_list : s_preset_mapping_list;
- for (input_mapping_t& m : ml) {
+ for (input_mapping_t &m : ml) {
if (m.seq == sequence && m.mode == mode) {
m.commands = commands_vector;
m.sets_mode = sets_mode;
@@ -289,7 +289,8 @@ void init_input() {
input_mapping_add(L"\x3", L"commandline ''", DEFAULT_BIND_MODE, DEFAULT_BIND_MODE, false);
input_mapping_add(L"\x4", L"exit", DEFAULT_BIND_MODE, DEFAULT_BIND_MODE, false);
input_mapping_add(L"\x5", L"bind", DEFAULT_BIND_MODE, DEFAULT_BIND_MODE, false);
- input_mapping_add(L"\x7f", L"backward-delete-char", DEFAULT_BIND_MODE, DEFAULT_BIND_MODE, false);
+ input_mapping_add(L"\x7f", L"backward-delete-char", DEFAULT_BIND_MODE, DEFAULT_BIND_MODE,
+ false);
// Arrows - can't have functions, so *-or-search isn't available.
input_mapping_add(L"\x1B[A", L"up-line", DEFAULT_BIND_MODE, DEFAULT_BIND_MODE, false);
input_mapping_add(L"\x1B[B", L"down-line", DEFAULT_BIND_MODE, DEFAULT_BIND_MODE, false);
@@ -498,7 +499,9 @@ char_event_t input_readch(bool allow_commands) {
input_common_next_ch(evt);
return input_readch();
}
- default: { return evt; }
+ default: {
+ return evt;
+ }
}
} else if (evt.is_eof()) {
// If we have EOF, we need to immediately quit.
@@ -540,8 +543,7 @@ bool input_mapping_erase(const wcstring &sequence, const wcstring &mode, bool us
ASSERT_IS_MAIN_THREAD();
bool result = false;
mapping_list_t &ml = user ? s_mapping_list : s_preset_mapping_list;
- for (std::vector::iterator it = ml.begin(), end = ml.end();
- it != end; ++it) {
+ for (std::vector::iterator it = ml.begin(), end = ml.end(); it != end; ++it) {
if (sequence == it->seq && mode == it->mode) {
ml.erase(it);
result = true;
@@ -551,8 +553,8 @@ bool input_mapping_erase(const wcstring &sequence, const wcstring &mode, bool us
return result;
}
-bool input_mapping_get(const wcstring &sequence, const wcstring &mode, wcstring_list_t *out_cmds, bool user,
- wcstring *out_sets_mode) {
+bool input_mapping_get(const wcstring &sequence, const wcstring &mode, wcstring_list_t *out_cmds,
+ bool user, wcstring *out_sets_mode) {
bool result = false;
mapping_list_t &ml = user ? s_mapping_list : s_preset_mapping_list;
for (const input_mapping_t &m : ml) {
@@ -571,52 +573,21 @@ static std::vector create_input_terminfo() {
assert(curses_initialized);
if (!cur_term) return {}; // setupterm() failed so we can't referency any key definitions
return {
- TERMINFO_ADD(key_a1),
- TERMINFO_ADD(key_a3),
- TERMINFO_ADD(key_b2),
- TERMINFO_ADD(key_backspace),
- TERMINFO_ADD(key_beg),
- TERMINFO_ADD(key_btab),
- TERMINFO_ADD(key_c1),
- TERMINFO_ADD(key_c3),
- TERMINFO_ADD(key_cancel),
- TERMINFO_ADD(key_catab),
- TERMINFO_ADD(key_clear),
- TERMINFO_ADD(key_close),
- TERMINFO_ADD(key_command),
- TERMINFO_ADD(key_copy),
- TERMINFO_ADD(key_create),
- TERMINFO_ADD(key_ctab),
- TERMINFO_ADD(key_dc),
- TERMINFO_ADD(key_dl),
- TERMINFO_ADD(key_down),
- TERMINFO_ADD(key_eic),
- TERMINFO_ADD(key_end),
- TERMINFO_ADD(key_enter),
- TERMINFO_ADD(key_eol),
- TERMINFO_ADD(key_eos),
- TERMINFO_ADD(key_exit),
- TERMINFO_ADD(key_f0),
- TERMINFO_ADD(key_f1),
- TERMINFO_ADD(key_f2),
- TERMINFO_ADD(key_f3),
- TERMINFO_ADD(key_f4),
- TERMINFO_ADD(key_f5),
- TERMINFO_ADD(key_f6),
- TERMINFO_ADD(key_f7),
- TERMINFO_ADD(key_f8),
- TERMINFO_ADD(key_f9),
- TERMINFO_ADD(key_f10),
- TERMINFO_ADD(key_f11),
- TERMINFO_ADD(key_f12),
- TERMINFO_ADD(key_f13),
- TERMINFO_ADD(key_f14),
- TERMINFO_ADD(key_f15),
- TERMINFO_ADD(key_f16),
- TERMINFO_ADD(key_f17),
- TERMINFO_ADD(key_f18),
- TERMINFO_ADD(key_f19),
- TERMINFO_ADD(key_f20),
+ TERMINFO_ADD(key_a1), TERMINFO_ADD(key_a3), TERMINFO_ADD(key_b2),
+ TERMINFO_ADD(key_backspace), TERMINFO_ADD(key_beg), TERMINFO_ADD(key_btab),
+ TERMINFO_ADD(key_c1), TERMINFO_ADD(key_c3), TERMINFO_ADD(key_cancel),
+ TERMINFO_ADD(key_catab), TERMINFO_ADD(key_clear), TERMINFO_ADD(key_close),
+ TERMINFO_ADD(key_command), TERMINFO_ADD(key_copy), TERMINFO_ADD(key_create),
+ TERMINFO_ADD(key_ctab), TERMINFO_ADD(key_dc), TERMINFO_ADD(key_dl),
+ TERMINFO_ADD(key_down), TERMINFO_ADD(key_eic), TERMINFO_ADD(key_end),
+ TERMINFO_ADD(key_enter), TERMINFO_ADD(key_eol), TERMINFO_ADD(key_eos),
+ TERMINFO_ADD(key_exit), TERMINFO_ADD(key_f0), TERMINFO_ADD(key_f1),
+ TERMINFO_ADD(key_f2), TERMINFO_ADD(key_f3), TERMINFO_ADD(key_f4), TERMINFO_ADD(key_f5),
+ TERMINFO_ADD(key_f6), TERMINFO_ADD(key_f7), TERMINFO_ADD(key_f8), TERMINFO_ADD(key_f9),
+ TERMINFO_ADD(key_f10), TERMINFO_ADD(key_f11), TERMINFO_ADD(key_f12),
+ TERMINFO_ADD(key_f13), TERMINFO_ADD(key_f14), TERMINFO_ADD(key_f15),
+ TERMINFO_ADD(key_f16), TERMINFO_ADD(key_f17), TERMINFO_ADD(key_f18),
+ TERMINFO_ADD(key_f19), TERMINFO_ADD(key_f20),
#if 0
// I know of no keyboard with more than 20 function keys, so adding the rest here makes very
// little sense, since it will take up a lot of room in any listings (like tab completions),
@@ -665,66 +636,26 @@ static std::vector create_input_terminfo() {
TERMINFO_ADD(key_f62),
TERMINFO_ADD(key_f63),
#endif
- TERMINFO_ADD(key_find),
- TERMINFO_ADD(key_help),
- TERMINFO_ADD(key_home),
- TERMINFO_ADD(key_ic),
- TERMINFO_ADD(key_il),
- TERMINFO_ADD(key_left),
- TERMINFO_ADD(key_ll),
- TERMINFO_ADD(key_mark),
- TERMINFO_ADD(key_message),
- TERMINFO_ADD(key_move),
- TERMINFO_ADD(key_next),
- TERMINFO_ADD(key_npage),
- TERMINFO_ADD(key_open),
- TERMINFO_ADD(key_options),
- TERMINFO_ADD(key_ppage),
- TERMINFO_ADD(key_previous),
- TERMINFO_ADD(key_print),
- TERMINFO_ADD(key_redo),
- TERMINFO_ADD(key_reference),
- TERMINFO_ADD(key_refresh),
- TERMINFO_ADD(key_replace),
- TERMINFO_ADD(key_restart),
- TERMINFO_ADD(key_resume),
- TERMINFO_ADD(key_right),
- TERMINFO_ADD(key_save),
- TERMINFO_ADD(key_sbeg),
- TERMINFO_ADD(key_scancel),
- TERMINFO_ADD(key_scommand),
- TERMINFO_ADD(key_scopy),
- TERMINFO_ADD(key_screate),
- TERMINFO_ADD(key_sdc),
- TERMINFO_ADD(key_sdl),
- TERMINFO_ADD(key_select),
- TERMINFO_ADD(key_send),
- TERMINFO_ADD(key_seol),
- TERMINFO_ADD(key_sexit),
- TERMINFO_ADD(key_sf),
- TERMINFO_ADD(key_sfind),
- TERMINFO_ADD(key_shelp),
- TERMINFO_ADD(key_shome),
- TERMINFO_ADD(key_sic),
- TERMINFO_ADD(key_sleft),
- TERMINFO_ADD(key_smessage),
- TERMINFO_ADD(key_smove),
- TERMINFO_ADD(key_snext),
- TERMINFO_ADD(key_soptions),
- TERMINFO_ADD(key_sprevious),
- TERMINFO_ADD(key_sprint),
- TERMINFO_ADD(key_sr),
- TERMINFO_ADD(key_sredo),
- TERMINFO_ADD(key_sreplace),
- TERMINFO_ADD(key_sright),
- TERMINFO_ADD(key_srsume),
- TERMINFO_ADD(key_ssave),
- TERMINFO_ADD(key_ssuspend),
- TERMINFO_ADD(key_stab),
- TERMINFO_ADD(key_sundo),
- TERMINFO_ADD(key_suspend),
- TERMINFO_ADD(key_undo),
- TERMINFO_ADD(key_up)
+ TERMINFO_ADD(key_find), TERMINFO_ADD(key_help), TERMINFO_ADD(key_home),
+ TERMINFO_ADD(key_ic), TERMINFO_ADD(key_il), TERMINFO_ADD(key_left),
+ TERMINFO_ADD(key_ll), TERMINFO_ADD(key_mark), TERMINFO_ADD(key_message),
+ TERMINFO_ADD(key_move), TERMINFO_ADD(key_next), TERMINFO_ADD(key_npage),
+ TERMINFO_ADD(key_open), TERMINFO_ADD(key_options), TERMINFO_ADD(key_ppage),
+ TERMINFO_ADD(key_previous), TERMINFO_ADD(key_print), TERMINFO_ADD(key_redo),
+ TERMINFO_ADD(key_reference), TERMINFO_ADD(key_refresh), TERMINFO_ADD(key_replace),
+ TERMINFO_ADD(key_restart), TERMINFO_ADD(key_resume), TERMINFO_ADD(key_right),
+ TERMINFO_ADD(key_save), TERMINFO_ADD(key_sbeg), TERMINFO_ADD(key_scancel),
+ TERMINFO_ADD(key_scommand), TERMINFO_ADD(key_scopy), TERMINFO_ADD(key_screate),
+ TERMINFO_ADD(key_sdc), TERMINFO_ADD(key_sdl), TERMINFO_ADD(key_select),
+ TERMINFO_ADD(key_send), TERMINFO_ADD(key_seol), TERMINFO_ADD(key_sexit),
+ TERMINFO_ADD(key_sf), TERMINFO_ADD(key_sfind), TERMINFO_ADD(key_shelp),
+ TERMINFO_ADD(key_shome), TERMINFO_ADD(key_sic), TERMINFO_ADD(key_sleft),
+ TERMINFO_ADD(key_smessage), TERMINFO_ADD(key_smove), TERMINFO_ADD(key_snext),
+ TERMINFO_ADD(key_soptions), TERMINFO_ADD(key_sprevious), TERMINFO_ADD(key_sprint),
+ TERMINFO_ADD(key_sr), TERMINFO_ADD(key_sredo), TERMINFO_ADD(key_sreplace),
+ TERMINFO_ADD(key_sright), TERMINFO_ADD(key_srsume), TERMINFO_ADD(key_ssave),
+ TERMINFO_ADD(key_ssuspend), TERMINFO_ADD(key_stab), TERMINFO_ADD(key_sundo),
+ TERMINFO_ADD(key_suspend), TERMINFO_ADD(key_undo), TERMINFO_ADD(key_up)
};
}
diff --git a/src/input.h b/src/input.h
index f76cede6a..08b271ad4 100644
--- a/src/input.h
+++ b/src/input.h
@@ -63,12 +63,13 @@ std::vector input_mapping_get_names(bool user = true);
void input_mapping_clear(const wchar_t *mode = NULL, bool user = true);
/// Erase binding for specified key sequence.
-bool input_mapping_erase(const wcstring &sequence, const wcstring &mode = DEFAULT_BIND_MODE, bool user = true);
+bool input_mapping_erase(const wcstring &sequence, const wcstring &mode = DEFAULT_BIND_MODE,
+ bool user = true);
/// Gets the command bound to the specified key sequence in the specified mode. Returns true if it
/// exists, false if not.
-bool input_mapping_get(const wcstring &sequence, const wcstring &mode, wcstring_list_t *out_cmds, bool user,
- wcstring *out_new_mode);
+bool input_mapping_get(const wcstring &sequence, const wcstring &mode, wcstring_list_t *out_cmds,
+ bool user, wcstring *out_new_mode);
/// Return the current bind mode.
wcstring input_get_bind_mode(const environment_t &vars);
diff --git a/src/input_common.cpp b/src/input_common.cpp
index 6301aac5e..fb82b1842 100644
--- a/src/input_common.cpp
+++ b/src/input_common.cpp
@@ -2,8 +2,8 @@
#include "config.h"
#include
-#include
#include
+#include
#ifdef HAVE_SYS_SELECT_H
#include
#endif
@@ -167,9 +167,9 @@ void update_wait_on_escape_ms(const environment_t &vars) {
long tmp = fish_wcstol(escape_time_ms->as_string().c_str());
if (errno || tmp < 10 || tmp >= 5000) {
std::fwprintf(stderr,
- L"ignoring fish_escape_delay_ms: value '%ls' "
- L"is not an integer or is < 10 or >= 5000 ms\n",
- escape_time_ms->as_string().c_str());
+ L"ignoring fish_escape_delay_ms: value '%ls' "
+ L"is not an integer or is < 10 or >= 5000 ms\n",
+ escape_time_ms->as_string().c_str());
} else {
wait_on_escape_ms = (int)tmp;
}
@@ -208,7 +208,9 @@ char_event_t input_common_readch() {
case 0: {
return 0;
}
- default: { return res; }
+ default: {
+ return res;
+ }
}
}
}
diff --git a/src/io.cpp b/src/io.cpp
index 535be1ea0..d1a53ff97 100644
--- a/src/io.cpp
+++ b/src/io.cpp
@@ -4,8 +4,8 @@
#include
#include
#include
-#include
#include
+#include
#include
#include "common.h"
@@ -49,7 +49,8 @@ void io_buffer_t::run_background_fillthread(autoclose_fd_t readfd) {
// 3. read until EAGAIN (would block), appending
// 4. release the lock
// The purpose of holding the lock around the read calls is to ensure that data from background
- // processes isn't weirdly interspersed with data directly transferred (from a builtin to a buffer).
+ // processes isn't weirdly interspersed with data directly transferred (from a builtin to a
+ // buffer).
const int fd = readfd.fd();
@@ -90,7 +91,7 @@ void io_buffer_t::run_background_fillthread(autoclose_fd_t readfd) {
// It's important that if select() indicated we were readable, that we call select() again
// allowing it to time out. Note the typical case is that the fd will be closed, in which
// case select will return immediately.
- if (! readable) {
+ if (!readable) {
shutdown = this->shutdown_fillthread_.load(std::memory_order_relaxed);
}
@@ -191,7 +192,7 @@ io_pipe_t::~io_pipe_t() = default;
io_bufferfill_t::~io_bufferfill_t() = default;
io_buffer_t::~io_buffer_t() {
- assert(! fillthread_ && "io_buffer_t destroyed with outstanding fillthread");
+ assert(!fillthread_ && "io_buffer_t destroyed with outstanding fillthread");
}
void io_chain_t::remove(const shared_ptr &element) {
@@ -247,7 +248,6 @@ void io_print(const io_chain_t &chain)
}
#endif
-
int move_fd_to_unused(int fd, const io_chain_t &io_chain, bool cloexec) {
if (fd < 0 || io_chain.get_io_for_fd(fd).get() == NULL) {
return fd;
diff --git a/src/io.h b/src/io.h
index e72a00291..042e8a9bf 100644
--- a/src/io.h
+++ b/src/io.h
@@ -76,42 +76,40 @@ class separated_buffer_t {
separated_buffer_t(const separated_buffer_t &) = delete;
void operator=(const separated_buffer_t &) = delete;
-public:
- /// Construct a separated_buffer_t with the given buffer limit \p limit, or 0 for no limit.
- separated_buffer_t(size_t limit) : buffer_limit_(limit) {}
+ public:
+ /// Construct a separated_buffer_t with the given buffer limit \p limit, or 0 for no limit.
+ separated_buffer_t(size_t limit) : buffer_limit_(limit) {}
- /// \return the buffer limit size, or 0 for no limit.
- size_t limit() const { return buffer_limit_; }
+ /// \return the buffer limit size, or 0 for no limit.
+ size_t limit() const { return buffer_limit_; }
- /// \return the contents size.
- size_t size() const { return contents_size_; }
+ /// \return the contents size.
+ size_t size() const { return contents_size_; }
- /// \return whether the output has been discarded.
- bool discarded() const { return discard; }
+ /// \return whether the output has been discarded.
+ bool discarded() const { return discard; }
- /// Mark the contents as discarded.
- void set_discard() {
- elements_.clear();
- contents_size_ = 0;
- discard = true;
- }
+ /// Mark the contents as discarded.
+ void set_discard() {
+ elements_.clear();
+ contents_size_ = 0;
+ discard = true;
+ }
- void reset_discard() {
- discard = false;
- }
+ void reset_discard() { discard = false; }
- /// Serialize the contents to a single string, where explicitly separated elements have a
- /// newline appended.
- StringType newline_serialized() const {
- StringType result;
- result.reserve(size());
- for (const auto &elem : elements_) {
- result.append(elem.contents);
- if (elem.is_explicitly_separated()) {
- result.push_back('\n');
- }
- }
- return result;
+ /// Serialize the contents to a single string, where explicitly separated elements have a
+ /// newline appended.
+ StringType newline_serialized() const {
+ StringType result;
+ result.reserve(size());
+ for (const auto &elem : elements_) {
+ result.append(elem.contents);
+ if (elem.is_explicitly_separated()) {
+ result.push_back('\n');
+ }
+ }
+ return result;
}
/// \return the list of elements.
@@ -122,7 +120,8 @@ public:
void append(Iterator begin, Iterator end, separation_type_t sep = separation_type_t::inferred) {
if (!try_add_size(std::distance(begin, end))) return;
// Try merging with the last element.
- if (sep == separation_type_t::inferred && !elements_.empty() && !elements_.back().is_explicitly_separated()) {
+ if (sep == separation_type_t::inferred && !elements_.empty() &&
+ !elements_.back().is_explicitly_separated()) {
elements_.back().contents.append(begin, end);
} else {
elements_.emplace_back(StringType(begin, end), sep);
diff --git a/src/iothread.cpp b/src/iothread.cpp
index 8034d3183..eb07ac854 100644
--- a/src/iothread.cpp
+++ b/src/iothread.cpp
@@ -4,12 +4,12 @@
#include
#include
#include
-#include
#include
#include
#include
#include
#include
+#include
#include
#include
@@ -246,7 +246,7 @@ void iothread_drain_all() {
#if TIME_DRAIN
double after = timef();
std::fwprintf(stdout, L"(Waited %.02f msec for %d thread(s) to drain)\n", 1000 * (after - now),
- thread_count);
+ thread_count);
#endif
}
diff --git a/src/maybe.h b/src/maybe.h
index b86b1c1ee..4f0a78800 100644
--- a/src/maybe.h
+++ b/src/maybe.h
@@ -191,9 +191,9 @@ class maybe_t : private maybe_detail::conditionally_copyable_t