bopher-ng

A better Gopher client in pure Bash
git clone git://git.luxferre.top/bopher-ng.git
Log | Files | Refs | README | LICENSE

phlow.sh (1815B)


      1 #!/bin/bash
      2 # A simple helper tool to reflow the text from the standard input to a given width
      3 #
      4 # Usage: cat [file] | phlow.sh [width] [leading_spaces] [trailing_spaces]
      5 #
      6 # Created by Luxferre in 2023, released into public domain
      7 
      8 TARGET_WIDTH="$1"
      9 LSPACES="$2"
     10 TSPACES="$3"
     11 
     12 CRLF=$'\r\n'
     13 SPC=$'\x20'
     14 
     15 [[ -z "$TARGET_WIDTH" ]] && TARGET_WIDTH=67 # default page width
     16 [[ -z "$LSPACES" ]] && LSPACES=0
     17 [[ -z "$TSPACES" ]] && TSPACES=0
     18 
     19 fmtstr="%-$(( LSPACES ))s%-${TARGET_WIDTH}s%-$(( TSPACES ))s${CRLF}" # params: smth, line, smth
     20 
     21 while read -rs line; do # fully line-based operation
     22   line="${line%%$'\r'}" # remove a trailing CR if it is there
     23   llen="${#line}" # get effective line length
     24   if (( llen < TARGET_WIDTH )); then # no need to run the logic for smaller lines
     25     printf "$fmtstr" '' "$line" ''
     26     continue
     27   fi
     28   lastws=0 # variable to track last whitespace
     29   cpos=0 # variable to track current position within the page line
     30   pagepos=0 # variable to track the position of new line start
     31   outbuf='' # temporary output buffer
     32   for ((i=0;i<llen;i++,cpos++)); do # start iterating over characters
     33     c="${line:i:1}" # get the current one
     34     if (( cpos >= TARGET_WIDTH )); then # we already exceeded the page width
     35       (( lastws == 0 )) && lastws=$TARGET_WIDTH # no whitespace encountered here
     36       printf "$fmtstr" '' "${outbuf:0:$lastws}" '' # truncate the buffer
     37       outbuf=''
     38       pagepos=$(( pagepos + lastws ))
     39       cpos=0
     40       lastws=0
     41       i=$pagepos # update current iteration index from the last valid whitespace
     42     else # save the whitespace position if found
     43       [[ "$c" == "$SPC" ]] && lastws="$cpos"
     44       outbuf="${outbuf}${c}" # save the character itself
     45     fi
     46   done
     47   [[ ! -z "$outbuf" ]] && printf "$fmtstr" '' "$outbuf" '' # output the last unprocessed chunk
     48 done