mc

#!/bin/sh
# splits input into as many columns as will fit into the terminal
# like Plan 9 mc(1) <http://plan9.bell-labs.com/magic/man2html/1/mc>
# Copyright © 2014 Nils Dagsson Moskopp (erlehmann) – license: GPLv3+

towords() {
  while read line; do
    for word in $line; do
      printf '%s\n' $word
    done
  done
}

tolengths() {
  while read line; do
    printf '%s\n' ${#line}
  done;
}

max() {
  max=0
  while read line; do
   if [ $line -gt $max ]; then
      max=$line
    fi
  done;
  printf '%s\n' $max
}

columnate() {
  columns=$1
  maxlength=$2
  currentcolumn=0
  while read line; do
    for word in $line; do
      printf '%-'"$maxlength"'s' $word
      currentcolumn=$(expr $currentcolumn + 1)
      if [ $currentcolumn -eq $columns ]; then
        printf '\n'
        currentcolumn=0
      fi
    done
  done
  printf '\n'
}

input=$(cat)
maxwidth=$(tput cols)
maxwidth=${maxwidth:-80}
while getopts N: OPT; do
  case $OPT in
    N) maxwidth=$OPTARG;;
  esac
done
maxlength=$(printf '%s\n' "$input" | towords | tolengths | max)
fieldlength=$(expr $maxlength + 1)
columns=$(expr $maxwidth / $fieldlength)
printf '%s\n' "$input" | columnate $columns $fieldlength