Skip to content

Instantly share code, notes, and snippets.

@floam
Forked from ttscoff/rule.fish
Last active January 11, 2019 14:17
Show Gist options
  • Save floam/b5f5bc1131e85a6ba0ad860731d6d534 to your computer and use it in GitHub Desktop.
Save floam/b5f5bc1131e85a6ba0ad860731d6d534 to your computer and use it in GitHub Desktop.
rule and rulem bash functions (http://brettterpstra.com/2015/02/20/shell-trick-printf-rules/) in fish
# rule and rulem bash functions in fish script
# Jay Berringer did this conversion and then Aaron Gyes fixed it up.
# a way to pad with something other than spaces... by replacing all spaces
# with another character
# based on this bash/printf technique: http://brettterpstra.com/2015/02/20/shell-trick-printf-rules/
# rule: Print a ruler in terminal window
#
# - instead of the non-standard printf -v option, sets the _hr variable using
# command substitution
# - printf %*s takes a numeric argument (here $COLUMNS, the terminal width)
# to pad the string to, using spaces
# - Replaces the spaces with a '-' (default) or the desired character using
# the `string replace` builtin
# - Example:
# $ rule
# ----------------------------------------------------------
# $ rule =
# ==========================================================
function rule
set -l _hr (printf "%*s" $COLUMNS)
if test -z $argv
printf $_hr | string replace -a ' ' -
else
printf $_hr | string replace -a ' ' $argv
end
end
# rulem: Print a ruler in terminal window with message
#
# - Same as `rule`, but then it moves cursor over 2 characters,
# and overwrites it with MESSAGE.
# - Example:
# $ rulem Hello
# --Hello---------------------------------------------------
# $ rulem '[Hello]' =
# ==[Hello]=================================================
function rulem
set -l _hr (printf "%*s" $COLUMNS)
if test -z $argv[1]
echo "Usage: rulem MESSAGE [RULE_CHARACTER]"
return
else
if test (count $argv) -eq 2
printf "$_hr\r\e[2C$argv[1]" | string replace -a ' ' $argv[2]
else
printf "$_hr\r\e[2C$argv[1]" | string replace -a ' ' -
end
end
end
@floam
Copy link
Author

floam commented Jan 11, 2019

This actually works now, and does not execute any external commands like tput or sed (eeek! but note the original used bash syntax to do the string substitution, not sed). This should probably have logic added to use a default of 80 if $COLUMNS is 0, for dumb terminals.

Don't actually use this script, moving the cursor is a lousy way to produce this output.
Keep in mind you can print a terminal-width line in fish without printf tricks easily:

$ string repeat -n $COLUMNS -
--------------------------------------------------------------------------------

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment