Skip to content

Instantly share code, notes, and snippets.

@chrisdickinson
Created April 27, 2021 16:37
Show Gist options
  • Save chrisdickinson/06f4fbef686c1959de174758497a7b2a to your computer and use it in GitHub Desktop.
Save chrisdickinson/06f4fbef686c1959de174758497a7b2a to your computer and use it in GitHub Desktop.
#!/bin/bash
set -e
if [ ! -z "${1:-""}" ]; then
case "$1" in
"last"|"-")
$EDITOR ~/notes/$(ls ~/notes | grep -E '\.md$' | tail -n1)
;;
"search")
shift
files=$(ag "$@" ~/notes -l)
if [ ! -z "$files" ]; then
if [ $(wc -l <<< "$files") = "1" ]; then
$EDITOR -p -- $files
else
files=$(while read file; do basename $file; done <<< "$files" | fzf -m --preview 'ag '$@' ~/notes/{} --color ' | while read file; do echo "$HOME/notes/$file"; done)
if [ ! -z "$files" ]; then
$EDITOR -p -- $files
fi
fi
fi
;;
*)
>&2 echo "note [search|last]"
exit 1
;;
esac
exit
fi
file=$(mktemp)
mv "$file"{,.md}
file="${file}.md"
mtime_in=$(date -r "$file" "+%s")
if ${EDITOR:-/usr/bin/vim} $file; then
mtime_out=$(date -r "$file" "+%s")
if [ $mtime_in -eq $mtime_out ]; then
>&2 echo 'No changes to file. Discarding note.'
rm $file
exit 1
fi
else
>&2 echo '$EDITOR returned a non-zero exit code. Discarding note.'
rm $file
exit 1
fi
slug=$(sed '/[^[:blank:]]/q;d' < "$file" |
sed -e 's/[^a-zA-Z0-9]/-/g' |
sed -E 's/[\-]+/-/g' |
sed -e 's/^-//g' |
sed -e 's/-$//g' |
tr '[[:upper:]]' '[[:lower:]]')
dest="$HOME/notes/$(date -r "$file" "+%Y%m%d")-${slug:-untitled-note}"
suffix=""
while [ -e "${dest}${suffix}.md" ]; do
suffix=$((${suffix:-0} - 1))
done
mv "$file" "${dest}${suffix}.md"
echo "Stored note at \"${dest}${suffix}.md\"."
@leophys
Copy link

leophys commented Mar 30, 2022

Hi!
Thanks for this nicety. I changed it to use ripgrep instead of ag (just a matter of taste) and bat as previewer.
Also, now the path to the notes is configurable via the NOTES_PATH env variable.

https://gist.github.com/leophys/38093e4093e49a3bb0e0cdb584ec5679

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