Skip to content

Commit 7b1fa74

Browse files
author
Linus Wallgren
committed
bash-completion: Support spaces in note names
This also introduces a basic test-suite for the bash completion
1 parent b52e0b5 commit 7b1fa74

File tree

2 files changed

+56
-3
lines changed

2 files changed

+56
-3
lines changed

notes.bash_completion

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,25 @@
33
_notes_complete_notes() {
44
local configured_dir=${NOTES_DIRECTORY%/} # Remove trailing slashes
55
local notes_dir="${configured_dir:-$HOME/notes}"
6-
local items=($(compgen -f "$notes_dir/$1"))
6+
local OLD_IFS="$IFS"
7+
IFS=$'\n'
8+
local items=($(compgen -f "$notes_dir/$1" | sort ))
9+
IFS="$OLD_IFS"
710
for item in "${items[@]}"; do
811
[[ -d $item ]] && item="$item/"
912
local filename=${item#$notes_dir/}
1013
COMPREPLY+=("${filename%.md}")
1114
done
1215
}
1316

17+
_notes_complete_commands() {
18+
local valid_commands="new find grep open"
19+
COMPREPLY=($(compgen -W "${valid_commands}" -- "${1}"))
20+
}
21+
1422
_notes()
1523
{
1624
local cur
17-
readonly commands="new find grep open"
1825

1926
COMPREPLY=() # Array variable storing the possible completions.
2027
cur=${COMP_WORDS[COMP_CWORD]}
@@ -35,7 +42,7 @@ _notes()
3542
esac
3643
else
3744
compopt +o nospace
38-
COMPREPLY=($(compgen -W "${commands}" -- "${cur}"))
45+
_notes_complete_commands "$cur"
3946
fi
4047
return 0
4148
}

test/test-bash-completion.bats

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
#!./libs/bats/bin/bats
2+
3+
load 'libs/bats-support/load'
4+
load 'libs/bats-assert/load'
5+
load 'helpers'
6+
7+
setup() {
8+
setupNotesEnv
9+
source notes.bash_completion
10+
COMP_WORDS=()
11+
}
12+
13+
teardown() {
14+
teardownNotesEnv
15+
}
16+
17+
@test "Should list all commands" {
18+
touch $NOTES_DIRECTORY/note1.md
19+
_notes_complete_commands ""
20+
assert_equal "${COMPREPLY[0]}" 'new'
21+
assert_equal "${COMPREPLY[1]}" 'find'
22+
assert_equal "${COMPREPLY[2]}" 'grep'
23+
assert_equal "${COMPREPLY[3]}" 'open'
24+
}
25+
26+
@test "Should show matching note when found" {
27+
touch $NOTES_DIRECTORY/note1.md
28+
_notes_complete_notes "no"
29+
assert_equal "${COMPREPLY[@]}" "note1"
30+
}
31+
32+
@test "Should show multiple matching notes" {
33+
touch $NOTES_DIRECTORY/note1.md
34+
touch $NOTES_DIRECTORY/note2.md
35+
_notes_complete_notes "no"
36+
assert_equal "${COMPREPLY[0]}" 'note1'
37+
assert_equal "${COMPREPLY[1]}" 'note2'
38+
assert_equal 2 "${#COMPREPLY[@]}"
39+
}
40+
41+
@test "Should show one completion for note with space" {
42+
touch "$NOTES_DIRECTORY/my note.md"
43+
_notes_complete_notes ""
44+
assert_equal "${COMPREPLY[0]}" 'my note'
45+
assert_equal 1 "${#COMPREPLY[@]}"
46+
}

0 commit comments

Comments
 (0)