File: sbs.sh
   1 #!/bin/sh
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2020-2025 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the “Software”), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 # sbs [column count...] [filepaths...]
  27 #
  28 # Side-By-Side lays out lines read from all inputs given into several columns,
  29 # separating them with a special symbol. If no named inputs are given, lines
  30 # are read from the standard input, instead of files.
  31 #
  32 # If a column-count isn't given, the script tries to find the most columns
  33 # which can fit a reasonable width-limit; when even a single column can't fit
  34 # that limit, it simply emits all lines, which is the same as using 1 column.
  35 
  36 
  37 case "$1" in
  38     -h|--h|-help|--help)
  39         awk '/^# +sbs /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  40         exit 0
  41     ;;
  42 esac
  43 
  44 num_columns=0
  45 if [ "$(echo "$1" | grep -E '^[+-]?[0-9]+$' 2> /dev/null)" ]; then
  46     num_columns="$1"
  47     shift
  48 fi
  49 
  50 [ "$1" = "--" ] && shift
  51 
  52 # show all non-existing files given
  53 failed=0
  54 for arg in "$@"; do
  55     if [ "${arg}" = "-" ]; then
  56         continue
  57     fi
  58     if [ ! -e "${arg}" ]; then
  59         printf "\e[38;2;204;0;0mno file named \"%s\"\e[0m\n" "${arg}" >&2
  60         failed=1
  61     fi
  62 done
  63 
  64 # in case of errors, avoid showing an empty screen
  65 if [ "${failed}" -gt 0 ]; then
  66     exit 2
  67 fi
  68 
  69 command='awk'
  70 if [ -e /usr/bin/gawk ]; then
  71     command='gawk'
  72 fi
  73 
  74 # allow loading lines from multiple files, ensuring no lines are accidentally
  75 # joined across inputs
  76 awk 1 "$@" |
  77 
  78 # ignore leading UTF-8 BOMs (byte-order marks) and trailing carriage-returns:
  79 # the latter in particular will ruin side-by-side output; doing it separately
  80 # using `sed` is faster overall for the script
  81 sed 's-^\xef\xbb\xbf--; s-\r$--' |
  82 
  83 # before laying out lines side-by-side, expand all tabs, using 4 as the
  84 # tabstop width
  85 expand -t 4 |
  86 
  87 # lay lines into side-by-side columns
  88 ${command} -v num_columns="${num_columns}" '
  89     BEGIN {
  90         sep = " █"
  91         sep_width = width(sep)
  92         total_max_width = 79
  93         max_auto_cols = 26
  94 
  95         # num_columns = 0
  96         # detect a leading number, and use it as the max-number of columns
  97         if (ARGV[1] + 0 != 0) {
  98             num_columns = ARGV[1] + 0
  99             delete ARGV[1]
 100         }
 101     }
 102 
 103     # remember all lines; carriage-returns are already removed
 104     { lines[NR] = $0 }
 105 
 106     # width counts items in the string given, ignoring ANSI-style sequences
 107     function width(s) {
 108         gsub(/\x1b\[[0-9;]*[A-Za-z]/, "", s)
 109         return length(s)
 110     }
 111 
 112     # pick a line using a row-column pair as an index
 113     function pick(lines, height, row, col) {
 114         return lines[(col - 1) * height + row]
 115     }
 116 
 117     # see if a list of lines can fit the number of columns given exactly
 118     function fits(lines, line_count, num_cols, height, max_widths, i, j, w, l) {
 119         height = ceil(line_count / num_cols)
 120 
 121         # prevent too many empty columns
 122         if (height * num_cols - line_count >= height) {
 123             return 0
 124         }
 125 
 126         for (i = 1; i <= height; i++) {
 127             for (j = 1; j <= num_cols; j++) {
 128                 w = width(pick(lines, height, i, j))
 129                 if (w > total_max_width) return 0
 130                 if (max_widths[j] < w) max_widths[j] = w
 131             }
 132         }
 133 
 134         for (i = 1; i <= height; i++) {
 135             w = 0
 136 
 137             for (j = 1; j <= num_cols; j++) {
 138                 if (j > 1) w += sep_width
 139 
 140                 l = pick(lines, height, i, j)
 141                 if (j > 1 && l != "") w++
 142 
 143                 w += width(l)
 144 
 145                 if (j < num_cols) {
 146                     pad = max_widths[j] - width(l)
 147                     if (pad > 0) {
 148                         if (l == "") pad++
 149                         w += pad
 150                     }
 151                 }
 152 
 153                 if (w > total_max_width) return 0
 154             }
 155         }
 156 
 157         return 1
 158     }
 159 
 160     # auto-detect an appropriate column-count for the list of lines given
 161     function find_max_fit(lines, num_columns) {
 162         if (!fits(lines, NR, 1)) {
 163             return 1
 164         }
 165 
 166         for (num_columns = max_auto_cols; num_columns >= 2; num_columns--) {
 167             if (fits(lines, NR, num_columns)) {
 168                 return num_columns
 169             }
 170         }
 171         return 1
 172     }
 173 
 174     # round up non-integers
 175     function ceil(n) {
 176         return (n % 1) ? n - (n % 1) + 1 : n
 177     }
 178 
 179     END {
 180         # prevent errors when input has no lines
 181         if (NR < 1) exit
 182 
 183         # auto-fit when given a non-positive count, or when not given a count
 184         if (num_columns < 1) num_columns = find_max_fit(lines)
 185 
 186         # prevent column-count from exceeding the number of input lines
 187         if (num_columns > NR) num_columns = NR
 188 
 189         # emit a single column as lines, quitting right away
 190         if (num_columns < 2) {
 191             for (i = 1; i <= NR; i++) print lines[i]
 192             exit
 193         }
 194 
 195         # prevent a trailing empty column
 196         num_lines = ceil(NR / num_columns)
 197         if (num_lines * num_columns - NR >= num_lines) {
 198             num_columns--
 199         }
 200 
 201         num_lines = ceil(NR / num_columns)
 202         for (i = 1; i <= num_lines; i++) {
 203             for (j = 1; j <= num_columns; j++) {
 204                 w = width(pick(lines, num_lines, i, j))
 205                 if (max_widths[j] < w) max_widths[j] = w
 206             }
 207         }
 208 
 209         widest = 0
 210         for (i in max_widths) {
 211             if (widest < max_widths[i]) widest = max_widths[i]
 212         }
 213 
 214         # emit lines side by side
 215         for (i = 1; i <= num_lines; i++) {
 216             for (j = 1; j <= num_columns; j++) {
 217                 l = pick(lines, num_lines, i, j)
 218 
 219                 if (j > 1) {
 220                     printf "%s", sep
 221                     if (j != num_columns || l != "") printf " "
 222                 }
 223 
 224                 printf "%s", l
 225 
 226                 if (j < num_columns) {
 227                     pad = max_widths[j] - width(l)
 228                     if (pad > 0) printf "%*s", pad, ""
 229                 }
 230             }
 231 
 232             print ""
 233         }
 234     }
 235 ' |
 236 
 237 # view the result interactively
 238 less -MKiCRS