Last active
August 29, 2015 14:19
-
-
Save junegunn/d779dff10a3d0a708cb7 to your computer and use it in GitHub Desktop.
Managing notes with fzf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# | |
# Managing notes with fzf (https://github.com/junegunn/fzf) | |
# - CTRL-L: List txt files in descending order by their modified time | |
# - CTRL-F: Search file contents | |
NOTE_DIR="${NOTE_DIR:-$(dirname "${BASH_SOURCE[0]}")}" | |
TRASH_DIR="$NOTE_DIR/trash" | |
cd "$NOTE_DIR" | |
delete() { | |
echo -n "Delete $1? (y/n) " | |
read yn | |
if [[ "$yn" =~ ^y ]]; then | |
mkdir -p "$TRASH_DIR" | |
mv "$NOTE_DIR/${1}.txt" "$TRASH_DIR" | |
fi | |
} | |
key=ctrl-l | |
query="$*" | |
opts='--reverse --no-hscroll --no-multi --ansi --print-query --tiebreak=index' | |
while [ 1 ]; do | |
if [ "$key" = ctrl-l ]; then | |
out=$( | |
/usr/bin/ruby -x "$0" "$NOTE_DIR" list | | |
fzf $opts --prompt="list> " --expect=ctrl-f,alt-d,alt-n --query="$query") || exit 1 | |
query=$(head -1 <<< "$out") | |
[ $(wc -l <<< "$out") -lt 2 ] && continue | |
newkey=$(head -2 <<< "$out" | tail -1) | |
file=$(tail -1 <<< "$out" | awk 'BEGIN { FS = "\t" } { gsub(/ +$/, "", $1); print $1 }') | |
case "$newkey" in | |
ctrl-f) key=$newkey ;; | |
alt-d) delete "$file" ;; | |
alt-n) [ -n "$query" ] && vim "$NOTE_DIR/${query}.txt" ;; | |
*) [ -n "$file" ] && vim "$NOTE_DIR/${file}.txt" ;; | |
esac | |
else | |
out=$( | |
/usr/bin/ruby -x "$0" "$NOTE_DIR" find | | |
fzf $opts --prompt="find> " --expect=ctrl-l,alt-d,alt-n \ | |
--delimiter=":" --nth 3.. --query="$query") || exit 1 | |
query=$(head -1 <<< "$out") | |
[ $(wc -l <<< "$out") -lt 2 ] && continue | |
newkey=$(head -2 <<< "$out" | tail -1) | |
case "$newkey" in | |
ctrl-l) key=$newkey ;; | |
alt-d) delete "$file" ;; | |
alt-n) [ -n "$query" ] && vim "$NOTE_DIR/${query}.txt" ;; | |
*) | |
cmd=$(tail -1 <<< "$out" | | |
awk 'BEGIN { FS = ":" } { print "vim \"'$NOTE_DIR'/" $1 ".txt\" +" $2 }') | |
sh -c "$cmd" | |
esac | |
fi | |
done | |
#!ruby | |
# encoding: utf-8 | |
def list | |
Dir[ARGV.first + '/*.txt'] | |
.map { |f| { time: File.mtime(f), | |
path: f, | |
name: File.basename(f).chomp('.txt') } } | |
.sort_by { |h| [- h[:time].to_f, h[:name]] } | |
end | |
if ARGV.last == 'list' | |
list.each do |h| | |
puts "\x1b[1m#{h[:name].ljust(50)}\t\x1b[0;36m#{h[:time]}\x1b[m" | |
end rescue exit | |
else | |
list.each do |h| | |
File.open(h[:path]).each_with_index do |line, no| | |
next if line =~ /^\s*$/ | |
puts "\x1b[1m#{h[:name]}\x1b[m:\x1b[33m#{no + 1}\x1b[m: " | |
.ljust(40) << line | |
end | |
end rescue exit | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment