confOS/.config/fish/functions/latex-color.fish

56 lines
1.5 KiB
Fish
Raw Permalink Normal View History

2024-10-06 20:39:35 +02:00
function latex-color --description "Get the LaTeX color from HEX code"
2024-10-06 18:07:45 +02:00
# Declare our arguments
argparse h/help -- $argv
# Get function name
set current_name $(status current-function)
# Check if not enough arguments provided, or help menu
2024-10-06 20:39:35 +02:00
if set -ql _flag_help || test -z $argv[1]
echo -e "Usage: $current_name \"hexcode\""
echo -e " $current_name [-h|--help] - Show this help message"
2024-10-06 18:07:45 +02:00
return 0
end
2024-10-06 20:39:35 +02:00
# Remove '#'
2024-10-06 18:07:45 +02:00
set hex $argv[1]
2024-10-06 20:39:35 +02:00
if string match -qr '^#' -- $hex
2024-10-06 18:07:45 +02:00
set hex (string sub -s 2 $hex)
end
2024-10-06 20:54:57 +02:00
# Check if the hex code is valid
if not string match -qir '^[0-9A-F]{3,8}$' $hex
and not contains $(string length $hex) $(string split " " "3 4 6 8")
echo "Error: Invalid HEX code" 1>&2
2024-10-06 20:47:19 +02:00
return 1
end
2024-10-06 20:54:57 +02:00
# Expand 3 to 4
2024-10-06 20:39:35 +02:00
if test (string length $hex) -eq 3
set hex $(string join "" $hex "F")
2024-10-06 20:41:05 +02:00
end
2024-10-06 20:54:57 +02:00
# Expand 4 to 8
2024-10-06 20:41:05 +02:00
if test (string length $hex) -eq 4
set hex "$(string replace -ar '(.)' '$1$1' $hex)FF"
2024-10-06 20:39:35 +02:00
end
2024-10-06 20:54:57 +02:00
# Expand 6 to 8
2024-10-06 20:39:35 +02:00
if test (string length $hex) -eq 6
set hex $(string join "" $hex "FF")
2024-10-06 20:39:35 +02:00
end
2024-10-06 18:07:45 +02:00
# Convert hex to RGB
2024-10-06 20:39:35 +02:00
set r (math "0x$(string sub -s 1 -l 2 $hex) / 255")
set g (math "0x$(string sub -s 3 -l 2 $hex) / 255")
set b (math "0x$(string sub -s 5 -l 2 $hex) / 255")
set a (math "0x$(string sub -s 7 -l 2 $hex) / 255")
2024-10-06 18:07:45 +02:00
2024-10-06 21:08:09 +02:00
set -x LC_NUMERIC C
if test $a -eq 1
printf "{%.2f, %.2f, %.2f}\n" $r $g $b
else
printf "{%.2f, %.2f, %.2f, %.2f}\n" $r $g $b $a
end
2024-10-06 18:07:45 +02:00
end