File: sbs-compat.sh
   1 #!/bin/sh
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright (c) 2026 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...] [files...]
  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 # This version is compatible with busybox/alpine-linux.
  38 
  39 case "$1" in
  40     -h|--h|-help|--help)
  41         awk '/^# +sbs /, /^$/ { gsub(/^# ?/, ""); print }' "$0"
  42         exit 0
  43     ;;
  44 esac
  45 
  46 num_columns=0
  47 if echo "$1" | grep -q -E '^[+-]?[0-9]+$'; then
  48     num_columns="$1"
  49     shift
  50 fi
  51 
  52 fancy_sep=1
  53 case "$1" in
  54     -no-sep|--no-sep|-s|--s|-simple|--simple)
  55         fancy_sep=0
  56         shift
  57     ;;
  58 esac
  59 
  60 [ "$1" = '--' ] && shift
  61 
  62 # show all non-existing files given
  63 failed=0
  64 for arg in "$@"; do
  65     if [ "${arg}" = "-" ]; then
  66         continue
  67     fi
  68     if [ ! -e "${arg}" ]; then
  69         printf "\e[38;2;204;0;0mno file named \"%s\"\e[0m\n" "${arg}" >&2
  70         failed=1
  71     fi
  72 done
  73 
  74 # in case of errors, avoid showing an empty screen
  75 if [ "${failed}" -gt 0 ]; then
  76     exit 2
  77 fi
  78 
  79 # allow loading lines from multiple files, ensuring no lines are accidentally
  80 # joined across inputs
  81 awk 1 "$@" |
  82 
  83 # ignore leading UTF-8 BOMs (byte-order marks) and trailing carriage-returns:
  84 # the latter in particular will ruin side-by-side output; doing it separately
  85 # using `sed` is faster overall for the script
  86 sed 's-^\xef\xbb\xbf--; s-\r$--' |
  87 
  88 # before laying out lines side-by-side, expand all tabs, using 4 as the
  89 # tabstop width
  90 expand -t 4 |
  91 
  92 # lay lines into side-by-side columns
  93 awk -v fancy="${fancy_sep}" -v num_columns="${num_columns}" '
  94     BEGIN {
  95         sep = fancy ? " █" : " "
  96         sep_width = width(sep)
  97         total_max_width = 79
  98         max_auto_cols = 26
  99 
 100         # num_columns = 0
 101         # detect a leading number, and use it as the max-number of columns
 102         if (ARGV[1] + 0 != 0) {
 103             num_columns = ARGV[1] + 0
 104             delete ARGV[1]
 105         }
 106     }
 107 
 108     # remember all lines; carriage-returns are already removed
 109     { lines[NR] = $0 }
 110 
 111     # width counts items in the string given, ignoring ANSI-style sequences
 112     function width(s) {
 113         gsub(/\x1b\[[0-9;]*[A-Za-z]/, "", s)
 114         return length(s)
 115     }
 116 
 117     # pick a line using a row-column pair as an index
 118     function pick(lines, height, row, col) {
 119         return lines[(col - 1) * height + row]
 120     }
 121 
 122     # see if a list of lines can fit the number of columns given exactly
 123     function fits(lines, line_count, num_cols, height, max_widths, i, j, w, l) {
 124         height = ceil(line_count / num_cols)
 125 
 126         # prevent too many empty columns
 127         if (height * num_cols - line_count >= height) {
 128             return 0
 129         }
 130 
 131         for (i = 1; i <= height; i++) {
 132             for (j = 1; j <= num_cols; j++) {
 133                 w = width(pick(lines, height, i, j))
 134                 if (w > total_max_width) return 0
 135                 if (max_widths[j] < w) max_widths[j] = w
 136             }
 137         }
 138 
 139         for (i = 1; i <= height; i++) {
 140             w = 0
 141 
 142             for (j = 1; j <= num_cols; j++) {
 143                 if (j > 1) w += sep_width
 144 
 145                 l = pick(lines, height, i, j)
 146                 if (j > 1 && l != "") w++
 147 
 148                 w += width(l)
 149 
 150                 if (j < num_cols) {
 151                     pad = max_widths[j] - width(l)
 152                     if (pad > 0) {
 153                         if (l == "") pad++
 154                         w += pad
 155                     }
 156                 }
 157 
 158                 if (w > total_max_width) return 0
 159             }
 160         }
 161 
 162         return 1
 163     }
 164 
 165     # auto-detect an appropriate column-count for the list of lines given
 166     function find_max_fit(lines, num_columns) {
 167         if (!fits(lines, NR, 1)) {
 168             return 1
 169         }
 170 
 171         for (num_columns = max_auto_cols; num_columns >= 2; num_columns--) {
 172             if (fits(lines, NR, num_columns)) {
 173                 return num_columns
 174             }
 175         }
 176         return 1
 177     }
 178 
 179     # round up non-integers
 180     function ceil(n) {
 181         return (n % 1) ? n - (n % 1) + 1 : n
 182     }
 183 
 184     END {
 185         # prevent errors when input has no lines
 186         if (NR < 1) exit
 187 
 188         # auto-fit when given a non-positive count, or when not given a count
 189         if (num_columns < 1) num_columns = find_max_fit(lines)
 190 
 191         # prevent column-count from exceeding the number of input lines
 192         if (num_columns > NR) num_columns = NR
 193 
 194         # emit a single column as lines, quitting right away
 195         if (num_columns < 2) {
 196             for (i = 1; i <= NR; i++) print lines[i]
 197             exit
 198         }
 199 
 200         # prevent a trailing empty column
 201         num_lines = ceil(NR / num_columns)
 202         if (num_lines * num_columns - NR >= num_lines) {
 203             num_columns--
 204         }
 205 
 206         num_lines = ceil(NR / num_columns)
 207         for (i = 1; i <= num_lines; i++) {
 208             for (j = 1; j <= num_columns; j++) {
 209                 w = width(pick(lines, num_lines, i, j))
 210                 if (max_widths[j] < w) max_widths[j] = w
 211             }
 212         }
 213 
 214         widest = 0
 215         for (i in max_widths) {
 216             if (widest < max_widths[i]) widest = max_widths[i]
 217         }
 218 
 219         # emit lines side by side
 220         for (i = 1; i <= num_lines; i++) {
 221             for (j = 1; j <= num_columns; j++) {
 222                 l = pick(lines, num_lines, i, j)
 223 
 224                 if (j > 1) {
 225                     printf "%s", sep
 226                     if (j != num_columns || l != "") printf " "
 227                 }
 228 
 229                 printf "%s", l
 230 
 231                 if (j < num_columns) {
 232                     pad = max_widths[j] - width(l)
 233                     for (k = 1; k <= pad; k++) printf " "
 234                 }
 235             }
 236 
 237             print ""
 238         }
 239     }
 240 ' |
 241 
 242 # view the result interactively, if possible
 243 { less -MKiCRS 2> /dev/null || cat; }