Skip to content

Commit

Permalink
feat: Add setting to Captures to consider subsections in Insert After
Browse files Browse the repository at this point in the history
  • Loading branch information
chhoumann committed Mar 27, 2023
2 parents 0fd8101 + 0cea9b4 commit 30b66c6
Show file tree
Hide file tree
Showing 27 changed files with 777 additions and 347 deletions.
24 changes: 14 additions & 10 deletions src/engine/CaptureChoiceEngine.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type ICaptureChoice from "../types/choices/ICaptureChoice";
import { TFile } from "obsidian";
import type { TFile } from "obsidian";
import type { App } from "obsidian";
import { log } from "../logger/logManager";
import { CaptureChoiceFormatter } from "../formatters/captureChoiceFormatter";
Expand All @@ -8,7 +8,7 @@ import {
openFile,
replaceTemplaterTemplatesInCreatedFile,
templaterParseTemplate,
} from "../utility";
} from "../utilityObsidian";
import { VALUE_SYNTAX } from "../constants";
import type QuickAdd from "../main";
import { QuickAddChoiceEngine } from "./QuickAddChoiceEngine";
Expand Down Expand Up @@ -55,14 +55,18 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {
});

const filePath = await this.formatFilePath(captureTo);
const content = await this.getCaptureContent();
const content = this.getCaptureContent();

let getFileAndAddContentFn: typeof this.onFileExists;

if (await this.fileExists(filePath)) {
getFileAndAddContentFn = this.onFileExists;
getFileAndAddContentFn = this.onFileExists.bind(
this
) as typeof this.onFileExists;
} else if (this.choice?.createFileIfItDoesntExist?.enabled) {
getFileAndAddContentFn = this.onCreateFileIfItDoesntExist;
getFileAndAddContentFn = this.onCreateFileIfItDoesntExist.bind(
this
) as typeof this.onCreateFileIfItDoesntExist;
} else {
log.logWarning(
`The file ${filePath} does not exist and "Create file if it doesn't exist" is disabled.`
Expand All @@ -71,7 +75,7 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {
}

const { file, content: newFileContent } =
await getFileAndAddContentFn.bind(this)(filePath, content);
await getFileAndAddContentFn(filePath, content);

await this.app.vault.modify(file, newFileContent);

Expand All @@ -92,11 +96,11 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {
});
}
} catch (e) {
log.logError(e);
log.logError(e as string);
}
}

private async getCaptureContent(): Promise<string> {
private getCaptureContent(): string {
let content: string;

if (!this.choice.format.enabled) content = VALUE_SYNTAX;
Expand Down Expand Up @@ -145,7 +149,7 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {
`\nThis is in order to prevent data loss.`
);

newFileContent = res.joinedResults();
newFileContent = res.joinedResults() as string;
}

return { file, content: newFileContent };
Expand Down Expand Up @@ -206,7 +210,7 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine {
return;
}

let content: string = await this.getCaptureContent();
let content: string = this.getCaptureContent();
content = await this.formatter.formatContent(content, this.choice);

if (this.choice.format.enabled) {
Expand Down
3 changes: 2 additions & 1 deletion src/engine/MacroChoiceEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import GenericSuggester from "../gui/GenericSuggester/genericSuggester";
import type { IChoiceCommand } from "../types/macros/IChoiceCommand";
import type QuickAdd from "../main";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import { getUserScript, waitFor } from "../utility";
import { getUserScript } from "../utilityObsidian";
import type { IWaitCommand } from "../types/macros/QuickCommands/IWaitCommand";
import type { INestedChoiceCommand } from "../types/macros/QuickCommands/INestedChoiceCommand";
import type IChoice from "../types/choices/IChoice";
Expand All @@ -24,6 +24,7 @@ import { CopyCommand } from "../types/macros/EditorCommands/CopyCommand";
import { PasteCommand } from "../types/macros/EditorCommands/PasteCommand";
import { SelectActiveLineCommand } from "../types/macros/EditorCommands/SelectActiveLineCommand";
import { SelectLinkOnActiveLineCommand } from "../types/macros/EditorCommands/SelectLinkOnActiveLineCommand";
import { waitFor } from "src/utility";

export class MacroChoiceEngine extends QuickAddChoiceEngine {
public choice: IMacroChoice;
Expand Down
10 changes: 6 additions & 4 deletions src/engine/QuickAddEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,13 @@ export abstract class QuickAddEngine {
let dirName = "";
if (dirMatch) dirName = dirMatch[1];

if (await this.app.vault.adapter.exists(dirName)) {
return await this.app.vault.create(filePath, fileContent);
} else {
const dir = app.vault.getAbstractFileByPath(dirName);

if (!dir || !(dir instanceof TFolder)) {
await this.createFolder(dirName);
return await this.app.vault.create(filePath, fileContent);

}

return await this.app.vault.create(filePath, fileContent);
}
}
2 changes: 1 addition & 1 deletion src/engine/SingleMacroEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { IMacro } from "../types/macros/IMacro";
import { MacroChoiceEngine } from "./MacroChoiceEngine";
import type QuickAdd from "../main";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import { getUserScriptMemberAccess } from "../utility";
import { getUserScriptMemberAccess } from "../utilityObsidian";
import { log } from "../logger/logManager";

export class SingleMacroEngine extends MacroChoiceEngine {
Expand Down
2 changes: 1 addition & 1 deletion src/engine/TemplateChoiceEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
appendToCurrentLine,
getAllFolderPathsInVault,
openFile,
} from "../utility";
} from "../utilityObsidian";
import {
fileExistsAppendToBottom,
fileExistsAppendToTop,
Expand Down
2 changes: 1 addition & 1 deletion src/engine/TemplateEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type QuickAdd from "../main";
import {
getTemplater,
replaceTemplaterTemplatesInCreatedFile,
} from "../utility";
} from "../utilityObsidian";
import GenericSuggester from "../gui/GenericSuggester/genericSuggester";
import { FILE_NUMBER_REGEX, MARKDOWN_FILE_EXTENSION_REGEX } from "../constants";
import { log } from "../logger/logManager";
Expand Down
68 changes: 19 additions & 49 deletions src/formatters/captureChoiceFormatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,13 @@ import type { App, TFile } from "obsidian";
import { log } from "../logger/logManager";
import type QuickAdd from "../main";
import type { IChoiceExecutor } from "../IChoiceExecutor";
import {
escapeRegExp,
getLinesInString,
templaterParseTemplate,
} from "../utility";
import { templaterParseTemplate } from "../utilityObsidian";
import {
CREATE_IF_NOT_FOUND_BOTTOM,
CREATE_IF_NOT_FOUND_TOP,
} from "../constants";
import { escapeRegExp, getLinesInString } from "src/utility";
import getEndOfSection from "./helpers/getEndOfSection";

export class CaptureChoiceFormatter extends CompleteFormatter {
private choice: ICaptureChoice;
Expand Down Expand Up @@ -40,7 +38,7 @@ export class CaptureChoiceFormatter extends CompleteFormatter {
formatted,
this.file
);
if (!templaterFormatted) return formatted;
if (!(await templaterFormatted)) return formatted;

return templaterFormatted;
}
Expand Down Expand Up @@ -74,7 +72,7 @@ export class CaptureChoiceFormatter extends CompleteFormatter {
}

const frontmatterEndPosition = this.file
? await this.getFrontmatterEndPosition(this.file)
? this.getFrontmatterEndPosition(this.file)
: null;
if (!frontmatterEndPosition) return `${formatted}${this.fileContent}`;

Expand All @@ -99,12 +97,13 @@ export class CaptureChoiceFormatter extends CompleteFormatter {
const targetString: string = await this.format(
this.choice.insertAfter.after
);

const targetRegex = new RegExp(
`\\s*${escapeRegExp(targetString.replace("\\n", ""))}\\s*`
);
const fileContentLines: string[] = getLinesInString(this.fileContent);

const targetPosition = fileContentLines.findIndex((line) =>
let targetPosition = fileContentLines.findIndex((line) =>
targetRegex.test(line)
);
const targetNotFound = targetPosition === -1;
Expand All @@ -117,44 +116,15 @@ export class CaptureChoiceFormatter extends CompleteFormatter {
}

if (this.choice.insertAfter?.insertAtEnd) {
const nextHeaderPositionAfterTargetPosition = fileContentLines
.slice(targetPosition + 1)
.findIndex((line) => /^#+ |---/.test(line));
const foundNextHeader =
nextHeaderPositionAfterTargetPosition !== -1;

let endOfSectionIndex: number | null = null;
if (foundNextHeader) {
for (
let i =
nextHeaderPositionAfterTargetPosition + targetPosition;
i > targetPosition;
i--
) {
const lineIsNewline: boolean = /^[\s\n ]*$/.test(
fileContentLines[i]
);

if (!lineIsNewline) {
endOfSectionIndex = i;
break;
}
}

if (!endOfSectionIndex) endOfSectionIndex = targetPosition;

return this.insertTextAfterPositionInBody(
formatted,
this.fileContent,
endOfSectionIndex
);
} else {
return this.insertTextAfterPositionInBody(
formatted,
this.fileContent,
fileContentLines.length - 1
);
}
if (!this.file)
throw new Error("Tried to get sections without file.");

const endOfSectionIndex = getEndOfSection(
fileContentLines,
targetPosition,
!!this.choice.insertAfter.considerSubsections
);
targetPosition = endOfSectionIndex ?? fileContentLines.length - 1;
}

return this.insertTextAfterPositionInBody(
Expand All @@ -175,7 +145,7 @@ export class CaptureChoiceFormatter extends CompleteFormatter {
CREATE_IF_NOT_FOUND_TOP
) {
const frontmatterEndPosition = this.file
? await this.getFrontmatterEndPosition(this.file)
? this.getFrontmatterEndPosition(this.file)
: -1;
return this.insertTextAfterPositionInBody(
insertAfterLineAndFormatted,
Expand All @@ -192,8 +162,8 @@ export class CaptureChoiceFormatter extends CompleteFormatter {
}
}

private async getFrontmatterEndPosition(file: TFile) {
const fileCache = await this.app.metadataCache.getFileCache(file);
private getFrontmatterEndPosition(file: TFile) {
const fileCache = this.app.metadataCache.getFileCache(file);

if (!fileCache || !fileCache.frontmatter) {
log.logMessage("could not get frontmatter. Maybe there isn't any.");
Expand Down
8 changes: 4 additions & 4 deletions src/formatters/completeFormatter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Formatter } from "./formatter";
import type { App } from "obsidian";
import { getNaturalLanguageDates } from "../utility";
import { getNaturalLanguageDates } from "../utilityObsidian";
import GenericSuggester from "../gui/GenericSuggester/genericSuggester";
import type QuickAdd from "../main";
import { SingleMacroEngine } from "../engine/SingleMacroEngine";
Expand Down Expand Up @@ -109,13 +109,13 @@ export class CompleteFormatter extends Formatter {
}

protected async suggestForField(variableName: string) {
const suggestedValues = new Set<string>()
const suggestedValues = new Set<string>();

for (const file of this.app.vault.getMarkdownFiles()) {
const cache = this.app.metadataCache.getFileCache(file);
const value = cache?.frontmatter?.[variableName];
if (!value || typeof value == "object") continue;

suggestedValues.add(value.toString());
}

Expand All @@ -134,7 +134,7 @@ export class CompleteFormatter extends Formatter {
suggestedValuesArr,
suggestedValuesArr,
{
placeholder: `Enter value for ${variableName}`
placeholder: `Enter value for ${variableName}`,
}
);
}
Expand Down
2 changes: 1 addition & 1 deletion src/formatters/fileNameDisplayFormatter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Formatter } from "./formatter";
import type { App } from "obsidian";
import { getNaturalLanguageDates } from "../utility";
import { getNaturalLanguageDates } from "../utilityObsidian";

export class FileNameDisplayFormatter extends Formatter {
constructor(private app: App) {
Expand Down
2 changes: 1 addition & 1 deletion src/formatters/formatDisplayFormatter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Formatter } from "./formatter";
import type { App } from "obsidian";
import { getNaturalLanguageDates } from "../utility";
import { getNaturalLanguageDates } from "../utilityObsidian";
import type QuickAdd from "../main";
import { SingleTemplateEngine } from "../engine/SingleTemplateEngine";

Expand Down
Loading

0 comments on commit 30b66c6

Please sign in to comment.