diff --git a/src/parser/parser.ts b/src/parser/parser.ts index b61eb0de8..350505040 100644 --- a/src/parser/parser.ts +++ b/src/parser/parser.ts @@ -3,7 +3,11 @@ import { parseTimestamp } from "../timestamp/timestamp"; import { timestampRegExp } from "../regexp"; import { isTopLevelListItem } from "../../obsidian-metadata-utils/src/list"; import { getTextAtPosition } from "../../obsidian-metadata-utils/src/position"; -import { getDiffInMinutes, getMinutesSinceMidnightTo, minutesToMoment } from "../util/moment"; +import { + getDiffInMinutes, + getMinutesSinceMidnightTo, + minutesToMoment, +} from "../util/moment"; import { DEFAULT_DURATION_MINUTES } from "../constants"; import { getTimeFromYOffset, roundToSnapStep } from "src/store/timeline-store"; import { getDailyNoteForToday } from "src/util/daily-notes"; @@ -40,6 +44,10 @@ export function parsePlanItems( planHeadingContent, ); + if (!listItemsUnderPlan) { + return []; + } + const listItemsWithContent = getListItemContent(content, listItemsUnderPlan); return listItemsWithContent diff --git a/src/plan.ts b/src/plan.ts index 5e13fa40a..4895959dc 100644 --- a/src/plan.ts +++ b/src/plan.ts @@ -25,18 +25,25 @@ export async function appendToPlan(path: string, planItem: PlanItem) { let result = replaceTimestamp(planItem, { ...planItem }); - const headingMetadata = getHeadingByText(metadata, plannerHeading); + const headingLine = getHeadingByText(metadata, plannerHeading); - if (!headingMetadata) { + let line = editor.lastLine(); + + if (!headingLine) { result = `${createPlannerHeading()}\n\n${result}`; + } else { + line = headingLine.position.start.line; } const listItems = getListItemsUnderHeading(metadata, plannerHeading); - const lastListItem = listItems[listItems.length - 1]; - const line = lastListItem - ? lastListItem.position.start.line - : editor.lastLine(); + if (listItems?.length > 0) { + const lastListItem = listItems[listItems.length - 1]; + + line = lastListItem.position.start.line; + } else if (headingLine) { + result = `\n${result}` + } const ch = editor.getLine(line).length; diff --git a/src/util/editor.ts b/src/util/editor.ts index 1ce6a652c..7715e5e45 100644 --- a/src/util/editor.ts +++ b/src/util/editor.ts @@ -1,7 +1,7 @@ import type { Editor } from "obsidian"; export function selectText(editor: Editor, text: string) { - const startOffset = editor.getValue().indexOf(text); + const startOffset = editor.getValue().lastIndexOf(text); const endOffset = startOffset + text.length; editor.setSelection(