aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEuAndreh <eu@euandre.org>2022-01-18 12:39:05 -0300
committerEuAndreh <eu@euandre.org>2022-01-18 14:03:01 -0300
commitc31a9bf00125588682a20869924fc7b7a5c7d4a1 (patch)
tree288b50f51c355604ecc038d7f4f5694c748580a0
parentFirst commit, now with a clean history (diff)
downloadtd-c31a9bf00125588682a20869924fc7b7a5c7d4a1.tar.gz
td-c31a9bf00125588682a20869924fc7b7a5c7d4a1.tar.xz
src/td.in: Add optimal_line_for_type()
Use the new function in insert_at_line(): whenever a given line $N is equal to 0, meaning it doesn't exist yet in the file, the optimal_line_for_type() will scan the file and answer with the "optimal" line number that the the type should be inserted at. It does that by looking at the order in which types apper in $TD_TYPES, and compare that with $TD_FILE: - if a previous type has appeared already, it continues scanning the file until a different level 1 heading appears, or until the end of the file; - if a type that comes after appears, it gets inserted before it; - if no types exist in the file yet, it gets inserted at the end. It fixes #td-05580844-40db-0db6-b11e-9f041a08c0a7.
-rwxr-xr-xsrc/td.in44
1 files changed, 42 insertions, 2 deletions
diff --git a/src/td.in b/src/td.in
index 6f1c516..ecc19c8 100755
--- a/src/td.in
+++ b/src/td.in
@@ -184,6 +184,44 @@ mkdtemp() {
# Core functions
#
+optimal_line_for_type() {
+ GOAL_TYPE="$1"
+ GOAL_INDEX="$(echo "$TD_TYPES" | awk "/^$GOAL_TYPE:/ { printf NR }")"
+ TYPE_HEADINGS="$(mkstemp)"
+ echo "$TD_TYPES" | cut -d: -f2- | sed 's/^/# /' > "$TYPE_HEADINGS"
+ IN_TD_SECTION=false
+ IN_TD_ENTRY=false
+ LINE_NUMBER=0
+ LAST_MATCH=0
+ IN_TD_REGION=false
+ while read -r line; do
+ LINE_NUMBER=$((LINE_NUMBER + 1))
+ if ! echo "$line" | grep -Eq '^# .+$'; then
+ continue
+ fi
+ MATCH="$(grep -nF "$line" "$TYPE_HEADINGS" ||:)"
+ if [ -n "$MATCH" ]; then
+ MATCH_N="$(echo "$MATCH" | cut -d: -f1)"
+ MATCH_LINE="$(echo "$MATCH" | cut -d: -f2-)"
+ if [ "$line" = "$MATCH_LINE" ]; then
+ IN_TD_REGION=true
+ if [ "$MATCH_N" -lt "$GOAL_INDEX" ]; then
+ LAST_MATCH="$MATCH_N"
+ else
+ echo $((LINE_NUMBER - 1))
+ return
+ fi
+ fi
+ elif [ "$IN_TD_REGION" = true ]; then
+ echo $((LINE_NUMBER - 1))
+ echo uhu >&2
+ return
+ fi
+ done < "$TD_FILE"
+ echo "chegou" >&2
+ echo $((LINE_NUMBER))
+}
+
insert_at_line() {
N="$1"
F="$2"
@@ -194,10 +232,12 @@ insert_at_line() {
printf "$MSG_FILE_DOESNT_EXIST_CREATING\n" "$TD_FILE" >&2
cat - > "$TMPF"
elif [ "$N" = 0 ]; then
+ DESIRED_N="$(optimal_line_for_type "$TYPE")"
printf "$MSG_TYPE_DOESNT_EXIST_CREATING\n" "$TYPE" >&2
- printf '%s\n\n\n%s\n' \
+ printf '%s\n\n\n%s\n\n\n%s\n' \
+ "$(head -n "$DESIRED_N" "$F")" \
"$(cat -)" \
- "$(cat "$F")" \
+ "$(tail -n +$((DESIRED_N+1)) "$F")" \
> "$TMPF"
else
printf '%s\n\n%s\n\n%s\n' \