### Complete Field Management Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md An example demonstrating smart task creation using field suggestions to dynamically populate task properties like type, priority, and assignee. ```javascript module.exports = async (params) => { const { quickAddApi, app, variables } = params; // Smart task creation with field suggestions const taskType = await quickAddApi.suggester( await quickAddApi.fieldSuggestions.getFieldValues("type", { folder: "tasks" }), await quickAddApi.fieldSuggestions.getFieldValues("type", { folder: "tasks" }) ); const priority = await quickAddApi.suggester( ["🔴 High", "🟡 Medium", "🟢 Low"], await quickAddApi.fieldSuggestions.getFieldValues("priority") || ["high", "medium", "low"] ); const assignee = await quickAddApi.suggester( await quickAddApi.fieldSuggestions.getFieldValues("assignee", { tags: ["person"], includeInline: true }), await quickAddApi.fieldSuggestions.getFieldValues("assignee", { tags: ["person"], includeInline: true }) ); // Create task with consistent field values variables.type = taskType; variables.priority = priority; variables.assignee = assignee; await quickAddApi.executeChoice("Create Task", variables); }; ``` -------------------------------- ### Start Local Development Server Source: https://github.com/chhoumann/quickadd/blob/master/docs/README.md Starts a local development server and opens the project in your browser. Changes are reflected live without server restarts. ```bash $ yarn start ``` -------------------------------- ### Complete User Script Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/UserScripts.md A comprehensive example demonstrating various configuration options for a user script, including text, dropdown, toggle, and format types for settings. It also shows how to access these settings and use the QuickAdd API within the script's main function. ```javascript module.exports = { entry: start, settings: { name: "Advanced Script", author: "Your Name", options: { "API Key": { type: "text", defaultValue: "", placeholder: "sk-…", secret: true, description: "OpenAI API key" }, "Model": { type: "dropdown", defaultValue: "gpt-3.5-turbo", options: ["gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"], description: "AI model to use" }, "Include Metadata": { type: "toggle", defaultValue: true, description: "Include file metadata in output" }, "Output Template": { type: "format", defaultValue: "## {{DATE:YYYY-MM-DD}}\n{{VALUE:content}}", placeholder: "Template for output", description: "Format for the output" }, "Max Results": { type: "text", defaultValue: "10", placeholder: "Number", description: "Maximum number of results" } } } }; async function start(params, settings) { const { quickAddApi, app, variables } = params; // Access settings const apiKey = settings["API Key"]; const model = settings["Model"]; const includeMetadata = settings["Include Metadata"]; const outputTemplate = settings["Output Template"]; const maxResults = parseInt(settings["Max Results"]); // Validate inputs if (!apiKey) { new Notice("Please configure your API key in the script settings"); throw new Error("API key not configured"); } // Use QuickAdd API const query = await quickAddApi.inputPrompt("Enter your search query:"); if (!query) return; // Your logic here... console.log(`Using model: ${model}`); console.log(`Max results: ${maxResults}`); if (includeMetadata) { // Include metadata logic } // Set variables for use in templates variables.model = model; variables.query = query; variables.resultCount = maxResults; } ``` -------------------------------- ### Minimal Macro Script Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Advanced/APIOverview.md This example demonstrates a minimal macro script using the QuickAdd API to prompt the user for a book title and return it formatted as a markdown heading. The returned value can be used by subsequent macro steps or inserted via format syntax. ```APIDOC ## Minimal macro script ```javascript module.exports = async ({ quickAddApi }) => { const title = await quickAddApi.inputPrompt("Book title"); return `# ${title}`; }; ``` The returned value can be used by later macro steps or inserted through format syntax. ``` -------------------------------- ### Open Suggester with Placeholder Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md This `suggester` example demonstrates how to include placeholder text to guide the user's selection process. ```javascript const fruit = await quickAddApi.suggester( ["🍎 Apple", "🍌 Banana", "🍊 Orange"], ["apple", "banana", "orange"], "Choose your favorite fruit" ); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/chhoumann/quickadd/blob/master/docs/README.md Run this command to install all necessary project dependencies using Yarn. ```bash $ yarn ``` -------------------------------- ### Template File Example Source: https://context7.com/chhoumann/quickadd/llms.txt An example Markdown template file for QuickAdd's Template choice. Uses QuickAdd format syntax for dynamic fields like date, attendees, status, title, and agenda. ```markdown --- date: {{DATE}} attendees: {{VALUE:attendees}} status: {{VALUE:status|label:Status|default:Draft}} --- # {{VALUE:title}} ## Agenda {{VALUE:agenda|type:multiline|label:Agenda items}} ## Action Items - Source: {{LINKCURRENT}} ``` -------------------------------- ### Check Plugin Dependency Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Verifies if a required plugin is installed and enabled before proceeding with plugin-specific operations. ```javascript module.exports = async (params) => { const { app } = params; const requiredPlugin = app.plugins.plugins["plugin-id"]; if (!requiredPlugin) { new Notice("Required plugin not found!"); return; } // Continue with plugin operations }; ``` -------------------------------- ### Complete Research Assistant Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md A comprehensive example demonstrating the creation of a research assistant. It combines input prompts, AI-assisted outline generation, folder creation, variable assignment, and template execution. This script requires 'app' and 'variables' from the params object. ```javascript module.exports = async (params) => { const { quickAddApi, app, variables } = params; try { // Get research parameters const topic = await quickAddApi.inputPrompt("Research Topic:"); if (!topic) return; const sources = await quickAddApi.checkboxPrompt( ["Web Search", "Academic Papers", "Books", "Videos"], ["Web Search", "Academic Papers"] ); // AI-assisted outline generation const { outline } = await quickAddApi.ai.prompt( `Create a research outline for: ${topic}`, "gpt-4", { variableName: "outline", shouldAssignVariables: true, modelOptions: { temperature: 0.7 } } ); // Create folder structure const folder = `Research/${topic}`; // Check if folder exists before creating try { const folderExists = await app.vault.adapter.exists(folder); if (!folderExists) { await app.vault.createFolder(folder); } } catch (err) { console.error(`Failed to create folder: ${err}`); new Notice(`Failed to create research folder: ${err.message}`); return; } // Set variables for templates variables.topic = topic; variables.sources = sources.join(", "); variables.date = quickAddApi.date.now("YYYY-MM-DD HH:mm"); variables.outline = outline; // Execute template choice await quickAddApi.executeChoice("Research Template", variables); // Show completion await quickAddApi.infoDialog( "Research Project Created", [ `Topic: ${topic}`, `Sources: ${sources.length} selected`, `Location: ${folder}`, "AI outline generated successfully" ] ); } catch (error) { console.error("Research assistant error:", error); new Notice(`Error: ${error.message}`); } }; ``` -------------------------------- ### Error Handling Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md Illustrates best practices for handling errors when using QuickAdd API methods. ```APIDOC ## Error Handling Best Practices Always wrap API calls in try-catch blocks to gracefully handle potential errors. ```javascript module.exports = async (params) => { const { quickAddApi } = params; try { const input = await quickAddApi.inputPrompt("Enter value:"); if (!input) { // User cancelled - handle gracefully return; } // Process input... } catch (error) { console.error("Script error:", error); await quickAddApi.infoDialog( "Error", `An error occurred: ${error.message}` ); } }; ``` ``` -------------------------------- ### Template Choice Settings Example Source: https://context7.com/chhoumann/quickadd/llms.txt Configuration for a Template choice in QuickAdd UI. Specifies the template file, file name format, destination folder, and opening behavior. ```yaml Settings example (QuickAdd UI): Template Path: Templates/Meeting.md File Name Format: Meetings/{{DATE:YYYY-MM-DD}} {{VALUE:title}} Create in Folder: Meetings/2024, Meetings/Archive (offers a suggester) Append Link: Enabled (skip if no active file) Link placement: New line Open: ✅ New tab → right ``` -------------------------------- ### QuickAdd URI with Vault and Value Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Advanced/ObsidianUri.md An example demonstrating how to specify a target vault and pass a value to a QuickAdd choice. Remember to URL encode all parts of the URI. ```uri obsidian://quickadd?vault=My%20Vault&choice=Daily%20log&value-contents=Lorem%20ipsum. ``` -------------------------------- ### Capture Choice Settings Example Source: https://context7.com/chhoumann/quickadd/llms.txt Configuration for a Capture choice in QuickAdd UI. Defines the destination file, capture format, write position, and file creation options. ```yaml Settings example (QuickAdd UI): Capture To: bins/daily/{{DATE:gggg-MM-DD - ddd MMM D}}.md Capture Format: - {{DATE:HH:mm}} {{VALUE}} Write Position: After line → ## Journal Blank lines after match: Auto (headings only) Create file if not found: ✅ (from template: Templates/Daily.md) Task: ☐ ``` -------------------------------- ### Development Watch Mode Source: https://github.com/chhoumann/quickadd/blob/master/AGENTS.md Starts a development server that watches for file changes and rebuilds the project. Uses esbuild for bundling. ```bash bun run dev ``` -------------------------------- ### Zettelizer Core Logic Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Examples/Macro_Zettelizer.md This snippet illustrates how the script identifies headers, extracts text, and prepares to create a new file. It ignores the first 'word' before creating the filename. ```javascript if (heading.level === 3) { // Ignore the first 'word' (any sequence of characters followed by a space) const headingText = heading.text.replace(/^\S+\s+/, ''); // Create a file with a name containing the remaining text in the heading // and link to the heading it created the file from. await T.createNote({ name: headingText, content: `[[${heading.text}]]` }); } ``` -------------------------------- ### Task Management Macro Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Creates a task with user-defined description and priority, setting variables for subsequent commands. ```javascript module.exports = async (params) => { const { quickAddApi, app, variables } = params; // Get task details const task = await quickAddApi.inputPrompt("Task description:"); const priority = await quickAddApi.suggester( ["🔴 High", "🟡 Medium", "🟢 Low"], ["high", "medium", "low"] ); // Set variables for use in template variables.taskDescription = task; variables.taskPriority = priority; variables.taskCreated = new Date().toISOString(); // Create task note using template (in next macro command) }; ``` -------------------------------- ### Migrate Inline Properties to Frontmatter Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Examples/Macro_MigrateDataviewProperties.md This example shows how inline properties are migrated to frontmatter, including basic key-value pairs and lists. ```markdown --- Reference: "[[Main Document]]" Related: - "[[Doc A]]" - "[[Doc B]]" Author: "John Doe" Status: "In Progress" Priority: "High" --- # Project Notes ``` -------------------------------- ### Example YAML Output for List and Scalar Properties Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/TemplatePropertyTypes.md Demonstrates how QuickAdd resolves list-style placeholders into YAML arrays and ensures scalar values remain as single strings, respecting Obsidian's property types. ```yaml sources: - [[Episode 1]] - [[Episode 2]] description: This stays a single string, even with commas. ``` -------------------------------- ### YAML Front Matter with List-Style Placeholders Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/TemplatePropertyTypes.md Example of YAML front matter using list-style placeholders for 'sources' and a scalar placeholder for 'description'. QuickAdd analyzes the generated front matter to correctly parse these values. ```yaml --- sources: - "{{VALUE:sources}}" description: "{{VALUE:description}}" --- ``` -------------------------------- ### QuickAdd API Execute Choice Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/UserScripts.md An example of how to programmatically trigger another QuickAdd choice from within a user script, optionally passing custom variables. ```javascript await quickAddApi.executeChoice("My Other Choice", { customVariable: "value" }); ``` -------------------------------- ### Research Workflow Macro Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Creates a research folder structure based on user input and sets variables for template usage. ```javascript module.exports = async (params) => { const { quickAddApi, app, variables } = params; // Get research topic const topic = await quickAddApi.inputPrompt("Research topic:"); // Create folder structure const vault = app.vault; const researchFolder = `Research/${topic}`; // Check if folder exists if (!await vault.adapter.exists(researchFolder)) { await vault.createFolder(researchFolder); await vault.createFolder(`${researchFolder}/Sources`); await vault.createFolder(`${researchFolder}/Notes`); } // Set variables for template variables.researchTopic = topic; variables.researchFolder = researchFolder; // Next commands in macro will create the overview note }; ``` -------------------------------- ### QuickAdd API User Input Prompts Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/UserScripts.md Examples of using the QuickAdd API to gather user input through various prompt types. These include text, multi-line text, yes/no confirmations, dropdown selections, and checkbox lists. ```javascript // Text input const text = await quickAddApi.inputPrompt("Enter text:"); ``` ```javascript // Wide text input (multi-line) const longText = await quickAddApi.wideInputPrompt("Enter description:"); ``` ```javascript // Yes/No confirmation const confirmed = await quickAddApi.yesNoPrompt("Are you sure?"); ``` ```javascript // Suggester (dropdown selection) const choice = await quickAddApi.suggester( ["Option 1", "Option 2", "Option 3"], ["value1", "value2", "value3"] ); ``` ```javascript // Checkbox selection const selected = await quickAddApi.checkboxPrompt( ["Item 1", "Item 2", "Item 3"], ["Item 1"] // Pre-selected items ); ``` -------------------------------- ### Minimal Macro Script Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Advanced/APIOverview.md This script prompts the user for a book title and returns it formatted as a Markdown heading. It demonstrates basic input prompting within a macro script. ```javascript module.exports = async ({ quickAddApi }) => { const title = await quickAddApi.inputPrompt("Book title"); return `# ${title}`; }; ``` -------------------------------- ### Open Suggester with Complex Objects Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md This `suggester` example shows how to handle complex objects. A function is used to format the display string from the object, while the object itself is returned upon selection. ```javascript const tasks = [ { id: 1, title: "Task 1", priority: "high" }, { id: 2, title: "Task 2", priority: "low" } ]; const selectedTask = await quickAddApi.suggester( task => `${task.title} (${task.priority})`, tasks, "Select a task to edit" ); ``` -------------------------------- ### QuickAdd Dynamic Token Examples Source: https://context7.com/chhoumann/quickadd/llms.txt These tokens are substituted in file names, capture formats, template content, and script settings. They can be composed freely to create dynamic file paths and content. ```markdown {{DATE}} {{DATE:YYYY-MM-DD HH:mm}} {{DATE+7}} {{VDATE:due,YYYY-MM-DD}} {{VDATE:due,YYYY-MM-DD|next monday}} ``` ```markdown {{VALUE}} {{VALUE:title}} {{VALUE:title|label:Note title|default:Untitled}} {{VALUE:status|label:Status}} {{VALUE:Todo,Doing,Done}} {{VALUE:Todo,Doing,Done|custom}} {{VALUE:🔽,🔼,⏫|text:Low,Normal,High}} {{VALUE:summary|type:multiline}} ``` ```markdown {{FIELD:project}} {{FIELD:status|folder:projects|default:Draft|default-always:true}} {{FIELD:Id|inline:true|inline-code-blocks:ad-note}} ``` ```markdown {{LINKCURRENT}} {{FILENAMECURRENT}} {{CLIPBOARD}} {{selected}} {{TITLE}} {{RANDOM:8}} {{MACRO:Generate summary}} {{TEMPLATE:Templates/Header.md}} {{GLOBAL_VAR:Meeting Header}} ``` ```markdown {{DATE:YYYY-MM-DD}}-{{VALUE:title|case:slug}}.md → 2024-01-15-project-review.md ``` -------------------------------- ### Get Available AI Models Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md Retrieves a list of all AI models currently available to QuickAdd. The returned list can be used with suggesters or other UI elements. ```javascript const models = quickAddApi.ai.getModels(); const selectedModel = await quickAddApi.suggester(models, models); ``` -------------------------------- ### Mixed-mode Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/FormatSyntax.md Demonstrates using single-line for a title and multi-line for a body with the VALUE placeholder. Note that commas and pipes are not supported within individual items or text entries. ```markdown - {{VALUE:Title|label:Title}} {{VALUE:Body|type:multiline|label:Body}} ``` -------------------------------- ### QuickAdd Variable Prompt Control Examples Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Demonstrates how QuickAdd determines whether to prompt for user input based on how variables are set in scripts. Unset, undefined, or null variables trigger prompts, while empty strings or other values do not. ```javascript // Data import script example module.exports = async (params) => { const { quickAddApi, variables } = params; // These will NOT prompt when used in templates: variables.rating = ""; // Intentionally empty variables.score = "0"; // Valid value (zero as string) variables.status = "draft"; // Has content variables.description = ""; // User chose to leave blank // These WILL prompt when used in templates: variables.author = undefined; // Explicitly undefined variables.reviewer = null; // Explicitly null // variables.category is never set - will prompt }; ``` ```javascript // Movie import example module.exports = async (params) => { const { variables } = params; const movieData = await fetchMovieData(); variables.title = movieData.title; variables.year = movieData.year.toString(); if (movieData.hasWatched) { variables.rating = movieData.userRating || ""; // Empty if no rating variables.watchDate = movieData.watchDate; } else { // For unwatched movies, set empty strings to avoid prompts variables.rating = ""; // Don't prompt for rating variables.watchDate = ""; // Don't prompt for watch date variables.review = ""; // Don't prompt for review } // This will prompt because we want user input variables.personalNotes = undefined; // Will ask for notes }; ``` -------------------------------- ### Summarizer Prompt Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/AIAssistant.md This prompt can be used to summarize selected text. It instructs the AI to use only the provided text, focus on brevity, and present the summary in an outline form. The {{value}} placeholder is where the selected text will be inserted. ```markdown Please summarize the following text. Use only the text itself as material for summarization, and do not add anything new. Rewrite this for brevity, in outline form: {{value}} ``` -------------------------------- ### Example Template for Movie/Series Notes Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Examples/Macro_MovieAndSeriesScript.md This template defines the structure for notes created by the Movie & Series Script. It uses QuickAdd's templating syntax to insert data fetched from the OMDb API. ```markdown --- cover: { { VALUE:Poster } } --- category:: {{VALUE:typeLink}} director:: {{VALUE:directorLink}} genre:: {{VALUE:genreLinks}} imdbId:: {{VALUE:imdbID}} imdb:: [IMDb]({{VALUE:imdbUrl}}) ratingImdb:: {{VALUE:imdbRating}} rating:: year:: {{VALUE:Year}} cast:: {{VALUE:actorLinks}} plot:: {{VALUE:Plot}} ![poster]({{VALUE:Poster}}) ``` -------------------------------- ### QuickAdd Macro Capture Step Format Source: https://context7.com/chhoumann/quickadd/llms.txt This is an example of a capture format used in a QuickAdd macro. It utilizes the variables set in a preceding User Script command to populate the note content. ```markdown - [ ] {{VALUE:taskDescription}} | priority:: {{VALUE:taskPriority}} | created:: {{VALUE:taskCreated}} ``` -------------------------------- ### QuickAdd API Input Prompt Methods Source: https://context7.com/chhoumann/quickadd/llms.txt These JavaScript examples show how to use `inputPrompt` for single-line text input and `wideInputPrompt` for multi-line text input within QuickAdd user scripts. Both methods automatically stop the macro on cancellation. ```javascript module.exports = async (params) => { const { quickAddApi } = params; // Single-line prompt const title = await quickAddApi.inputPrompt( "Note title", // header "e.g. Project Review", // placeholder "Untitled" // default value ); // Multi-line prompt const body = await quickAddApi.wideInputPrompt( "Body content", "Write your notes here..." ); params.variables.title = title; params.variables.body = body; }; ``` -------------------------------- ### Activate Obsidian and Send Keypresses with AutoHotkey Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Misc/AHK_OpenQuickAddFromDesktop.md Use this script to unminimize, focus, and send a specific hotkey combination to Obsidian to open QuickAdd. It's useful if you don't have the Advanced URI plugin installed. Ensure your Obsidian hotkey for QuickAdd matches the script's hotkey. ```ahk #SingleInstance, Force SendMode Input SetWorkingDir, %A_ScriptDir% SetTitleMatchMode, RegEx !^+g:: WinActivate, i) Obsidian ControlSend,, {CtrlDown}{AltDown}{ShiftDown}G{CtrlUp}{CtrlUp}{ShiftUp}, i)Obsidian Return ``` -------------------------------- ### Trigger QuickAdd Choice via Obsidian URI Source: https://context7.com/chhoumann/quickadd/llms.txt Example of an Obsidian URI to trigger a QuickAdd choice named 'Daily log' in the 'My Vault' vault, passing 'QuickAdd' as the project and 'focused' as the mood. ```uri obsidian://quickadd?vault=My%20Vault&choice=Daily%20log&value-project=QuickAdd&value-mood=focused ``` -------------------------------- ### Book Finder Template Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Examples/Macro_BookFinder.md Use this template to structure the book details when creating a new note with the Book Finder script. It includes placeholders for poster, author, title, category, status, related books, core questions, actions, notes, and a detailed description. ```markdown ![poster]({{VALUE:Poster}}) **Author**:: {{VALUE:authors}} **Title**:: {{VALUE:title}} **Category**::{{VALUE:categories}} **Status**:: 📥 **Related Books** ### Core Questions for Me ### Actions ### My Notes ## Details {{VALUE:description}} ``` -------------------------------- ### Get Yesterday's and Tomorrow's Date Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md Provides shorthand functions to get yesterday's and tomorrow's date, with optional custom formatting. These are equivalents to using `now()` with a day offset of -1 or 1 respectively. ```javascript const yesterdayLog = `Daily Notes/${quickAddApi.date.yesterday()}.md`; const tomorrowTask = `Tasks for ${quickAddApi.date.tomorrow("dddd, MMMM D")}`; ``` -------------------------------- ### Main Script Logic for Readwise Integration Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Examples/Template_AutomaticBookNotesFromReadwise.md This is the main entry point for the script. It handles user interaction for selecting highlight categories and processing the fetched highlights. It requires `quickAddApi` to be passed in the params. ```javascript module.exports = { start, getDailyQuote, instaFetchBook, getBooks }; const apiUrl = "https://readwise.io/api/v2/"; const books = "📚 Books", articles = "📰 Articles", tweets = "🐤 Tweets", supplementals = "💭 Supplementals", podcasts = "🎙 Podcasts", searchAll = "🔍 Search All Highlights (slow!)"; const categories = { books, articles, tweets, supplementals, podcasts, searchAll, }; const randomNumberInRange = (max) => Math.floor(Math.random() * max); const token = "YOUR_READWISE_TOKEN"; let quickAddApi; async function start(params) { ({ quickAddApi } = params); let highlights; const category = await categoryPromptHandler(); if (!category) return; if (category === "searchAll") { highlights = await getAllHighlights(); } else { let res = await getHighlightsByCategory(category); if (!res) return; const { results } = res; const item = await quickAddApi.suggester( results.map((item) => item.title), results ); if (!item) return; params.variables["author"] = `[[${item.author}]]`; const res2 = await getHighlightsForElement(item); if (!res2) return; highlights = res2.results.reverse(); } const textToAppend = await highlightsPromptHandler(highlights); return !textToAppend ? "" : textToAppend; } async function getBooks(params) { const { results: books } = await getHighlightsByCategory("books"); const bookNames = books.map((book) => book.title); const selectedBook = await params.quickAddApi.suggester( bookNames, bookNames ); params.variables["Book Title"] = selectedBook; return selectedBook; } async function instaFetchBook(params) { const bookTitle = params.variables["Book Title"]; if (!bookTitle) return await start(params); const { results: books } = await getHighlightsByCategory("books"); const book = books.find((b) => b.title.toLowerCase().contains(bookTitle.toLowerCase()) ); if (!book) throw new Error("Book " + bookTitle + " not found."); params.variables["author"] = `[[${book.author}]]`; const highlights = (await getHighlightsForElement(book)).results.reverse(); return writeAllHandler(highlights); } async function getDailyQuote(params) { const category = "supplementals"; const res = await getHighlightsByCategory(category); if (!res) return; const { results } = res; const targetItem = results[randomNumberInRange(results.length)]; const { results: highlights } = await getHighlightsForElement(targetItem); if (!highlights) return; const randomHighlight = highlights[randomNumberInRange(highlights.length)]; const quote = formatDailyQuote(randomHighlight.text, targetItem); return `${quote}`; } async function categoryPromptHandler() { const choice = await quickAddApi.suggester( Object.values(categories), Object.keys(categories) ); if (!choice) return null; return choice; } async function highlightsPromptHandler(highlights) { const writeAll = "Write all highlights to page", writeOne = "Write one highlight to page"; const choices = [writeAll, writeOne]; const choice = await quickAddApi.suggester(choices, choices); if (!choice) return null; if (choice == writeAll) return writeAllHandler(highlights); else return await writeOneHandler(highlights); } function writeAllHandler(highlights) { return highlights .map((hl) => { if (hl.text == "No title") return; const { quote, note } = textFormatter(hl.text, hl.note); return `${quote}${note}`; }) .join("\n\n"); } async function writeOneHandler(highlights) { const chosenHighlight = await quickAddApi.suggester( highlights.map((hl) => hl.text), highlights ); if (!chosenHighlight) return null; const { quote, note } = textFormatter( chosenHighlight.text, chosenHighlight.note ); return `${quote}${note}`; } function formatDailyQuote(sourceText, sourceItem) { let quote = sourceText .split("\n") .filter((line) => line != "") .map((line) => { return `> ${line}`; }); const attr = `\n>\\- ${sourceItem.author}, _${sourceItem.title}_`; return `${quote}${attr}`; } function textFormatter(sourceText, sourceNote) { let quote = sourceText .split("\n") .filter((line) => line != "") .map((line) => { if (sourceNote.includes(".h1")) return `## ${line}`; else return `> ${line}`; }) .join("\n"); let note; if (sourceNote.includes(".h1") || sourceNote == "" || !sourceNote) { note = ""; } else { note = "\n\n" + sourceNote; } return { quote, note }; } async function getHighlightsByCategory(category) { return apiGet(`${apiUrl}books`, { category, page_size: 1000 }); } async function getHighlightsForElement(element) { return apiGet(`${apiUrl}highlights`, { book_id: element.id, page_size: 1000, }); } async function getAllHighlights() { const MAX_PAGE_SIZE = 1000; const URL = `${apiUrl}highlights`; let promises = []; const { count } = await apiGet(URL); const requestsToMake = Math.ceil(count / MAX_PAGE_SIZE); ``` -------------------------------- ### Basic Inline Script with Input Prompt Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/InlineScripts.md Demonstrates how to use the QuickAdd API to prompt the user for input and return a formatted string. Ensure the language is set to `js quickadd`. ```javascript const input = await this.quickAddApi.inputPrompt("✍"); return `Input given: ${input}`; ``` -------------------------------- ### date.tomorrow Source: https://context7.com/chhoumann/quickadd/llms.txt Gets tomorrow's date in 'YYYY-MM-DD' format. ```APIDOC ## date module - Tomorrow's Date ### Description Retrieves tomorrow's date. ### Method `date.tomorrow(): string` ### Returns - Tomorrow's date in 'YYYY-MM-DD' format. ``` -------------------------------- ### Access QuickAdd API from Scripts Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md Demonstrates how to access the QuickAdd API within different scripting environments. ```javascript module.exports = async (params) => { const { quickAddApi, app, variables } = params; // Use quickAddApi here }; ``` ```javascript const quickAddApi = app.plugins.plugins.quickadd.api; // Use the API methods ``` ```javascript <%* const quickAddApi = app.plugins.plugins.quickadd.api; const result = await quickAddApi.inputPrompt("Enter value:"); tR += result; %> ``` -------------------------------- ### date.now Source: https://context7.com/chhoumann/quickadd/llms.txt Gets the current date or a formatted date string. ```APIDOC ## date module - Current Date ### Description Provides the current date in various formats. ### Methods - `date.now(): string`: Returns the current date in 'YYYY-MM-DD' format. - `date.now(format: string): string`: Returns the current date formatted according to the provided format string. - `date.now(format: string, daysToAdd: number): string`: Returns the date after adding the specified number of days, formatted as specified. ``` -------------------------------- ### Using QuickAdd API in User Scripts Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Demonstrates how to use various QuickAdd API methods within a user script to interact with the user, such as taking input, confirming actions, and making selections. ```javascript module.exports = async (params) => { const { quickAddApi } = params; // Input prompt - get text from user const name = await quickAddApi.inputPrompt("Enter your name:"); // Yes/No prompt const confirmed = await quickAddApi.yesNoPrompt("Are you sure?"); // Suggester - let user choose from options const choice = await quickAddApi.suggester( ["Option 1", "Option 2", "Option 3"], // Display values ["value1", "value2", "value3"] // Actual values ); // Wide input prompt - for longer text const longText = await quickAddApi.wideInputPrompt("Enter description:"); // Checkbox prompt - multiple selections const selections = await quickAddApi.checkboxPrompt( ["Task 1", "Task 2", "Task 3"] ); }; ``` -------------------------------- ### Date Module: Get Current and Relative Dates Source: https://context7.com/chhoumann/quickadd/llms.txt The `date` module offers functions to get the current date and time in various formats, as well as calculate relative dates like next week or yesterday. A custom format string can be provided to `now` and a day offset can be specified. ```javascript module.exports = async (params) => { const { quickAddApi } = params; const today = quickAddApi.date.now(); // "2024-01-15" const timestamp = quickAddApi.date.now("YYYY-MM-DD HH:mm:ss"); const nextWeek = quickAddApi.date.now("YYYY-MM-DD", 7); const yesterday = quickAddApi.date.yesterday("dddd, MMMM D"); // "Sunday, January 14" const tomorrow = quickAddApi.date.tomorrow(); params.variables.created = today; params.variables.followUp = nextWeek; }; ``` -------------------------------- ### Processing Input and Handoff to Variables Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/InlineScripts.md Shows how to fetch input, transform it (e.g., to uppercase), and optionally assign it to QuickAdd variables for later use by formatters. Handles cases where no input is provided. ```javascript const raw = await this.quickAddApi.inputPrompt("Text"); if (!raw) return ""; const transformed = raw.toUpperCase(); this.variables.value = transformed; // optional handoff to formatter variables return transformed; ``` -------------------------------- ### ai.getMaxTokens Source: https://context7.com/chhoumann/quickadd/llms.txt Gets the maximum token limit for a specified AI model. ```APIDOC ## ai.getMaxTokens ### Description Returns the maximum number of tokens that a specific AI model can process in a single request. ### Parameters - `model` (string) - The identifier of the AI model. ### Returns - (number) - The maximum token count for the specified model. ### Usage Example ```javascript const maxTokens = quickAddApi.ai.getMaxTokens("gpt-4o"); ``` ``` -------------------------------- ### date.yesterday Source: https://context7.com/chhoumann/quickadd/llms.txt Gets yesterday's date formatted according to the specified format. ```APIDOC ## date module - Yesterday's Date ### Description Retrieves yesterday's date formatted according to a specified format. ### Method `date.yesterday(format?: string): string` ### Parameters - `format`: Optional. The desired format string for the date. Defaults to 'YYYY-MM-DD'. ``` -------------------------------- ### Macro Error Handling Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Implements a try-catch block to handle errors gracefully, log them, and stop macro execution. ```javascript module.exports = async (params) => { try { // Your code here } catch (error) { console.error("Macro error:", error); new Notice(`Macro failed: ${error.message}`); throw error; // Re-throw to stop remaining macro commands } }; ``` -------------------------------- ### List All QuickAdd Choices via CLI Source: https://context7.com/chhoumann/quickadd/llms.txt Command to list all available QuickAdd choices in the 'dev' vault. An optional `type` filter can be applied. ```bash # List all choices (optionally filter by type) obisidian vault=dev quickadd:list obisidian vault=dev quickadd:list type=Capture ``` -------------------------------- ### Book Logging Macro Example Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Logs a book title to your daily note using the MetaEdit plugin and a formatted date. ```javascript module.exports = async (params) => { const { quickAddApi: { inputPrompt }, app } = params; // Get book name from user const bookName = await inputPrompt("📖 Book Name"); // Get MetaEdit plugin const { update } = app.plugins.plugins["metaedit"].api; // Format today's date const date = window.moment().format("YYYY-MM-DD"); // Update the daily note await update("Book", bookName, `Daily Notes/${date}.md`); }; ``` -------------------------------- ### Import QuickAdd Package Source: https://context7.com/chhoumann/quickadd/llms.txt Import a QuickAdd package from a JSON file. This process includes resolving conflicts for choices and assets. ```text Settings → QuickAdd → Import package… → paste .quickadd.json content → for each choice: Import | Overwrite | Duplicate | Skip → for each asset: Write | Overwrite | Skip (adjust path if needed) → Click "Import package" ``` -------------------------------- ### Markdown Example: Insert After Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/CaptureChoice.md Demonstrates inserting text 'X' after a line matching '# H' in Markdown, preserving heading spacing. ```markdown # H X A ``` -------------------------------- ### Passing Variables to QuickAdd CLI Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Advanced/CLI.md Demonstrates how to pass variables to QuickAdd choices when running them from the CLI. ```APIDOC ## Passing variables QuickAdd CLI supports three variable patterns: 1. `value-=...` (URI-compatible) 2. extra `key=value` args 3. `vars=` for structured values ### Examples ```bash obsidian vault=dev quickadd \ choice="Daily log" \ value-project="QuickAdd" \ mood="focused" obsidian vault=dev quickadd \ choice="Daily log" \ vars='{"project":"QuickAdd","sprint":42}' ``` ### Description This section explains the different methods for providing input variables to QuickAdd choices when invoked via the CLI. You can pass simple key-value pairs, use a `value-` prefix for URI-compatible values, or provide structured data using a JSON object within the `vars` parameter. ``` -------------------------------- ### Get Clipboard Contents Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md Retrieves the current text content from the system clipboard. Use this to read data that the user has copied. ```javascript const clipboardText = await quickAddApi.utility.getClipboard(); console.log("Clipboard contains:", clipboardText); ``` -------------------------------- ### QuickAdd API: inputPrompt / wideInputPrompt Source: https://context7.com/chhoumann/quickadd/llms.txt Demonstrates how to use `inputPrompt` for single-line text input and `wideInputPrompt` for multi-line text input within QuickAdd macros. These methods allow users to provide information that can be stored in variables for later use. ```APIDOC ## QuickAdd API: inputPrompt / wideInputPrompt ### Description These methods allow you to prompt the user for input within a macro. `inputPrompt` is for single-line input, while `wideInputPrompt` is for multi-line input, suitable for longer text entries. Both methods reject with `MacroAbortError` if the user cancels the prompt, which automatically stops the macro unless caught. ### Method `quickAddApi.inputPrompt(header, placeholder, defaultValue)` `quickAddApi.wideInputPrompt(header, placeholder)` ### Parameters #### `inputPrompt` Parameters - **header** (string) - Required - The header text displayed to the user. - **placeholder** (string) - Optional - Placeholder text shown in the input field. - **defaultValue** (string) - Optional - The default value pre-filled in the input field. #### `wideInputPrompt` Parameters - **header** (string) - Required - The header text displayed to the user. - **placeholder** (string) - Optional - Placeholder text shown in the input field. ### Request Example ```javascript module.exports = async (params) => { const { quickAddApi } = params; // Single-line prompt const title = await quickAddApi.inputPrompt( "Note title", // header "e.g. Project Review", // placeholder "Untitled" // default value ); // Multi-line prompt const body = await quickAddApi.wideInputPrompt( "Body content", "Write your notes here..." ); params.variables.title = title; params.variables.body = body; }; ``` ### Response User input is typically stored in `params.variables` for use in subsequent steps. ``` -------------------------------- ### Get Field Values Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md Retrieves all unique values for a specific field across your vault. Use this to populate suggesters or validate input. ```javascript // Get all status values in vault const statuses = await quickAddApi.fieldSuggestions.getFieldValues("status"); const selected = await quickAddApi.suggester(statuses, statuses); ``` ```javascript // Get project types only from projects folder const projectTypes = await quickAddApi.fieldSuggestions.getFieldValues( "type", { folder: "projects" } ); ``` ```javascript // Get priorities from work-tagged files const priorities = await quickAddApi.fieldSuggestions.getFieldValues( "priority", { tags: ["work", "important"] } ); ``` ```javascript // Get all client names including inline fields const clients = await quickAddApi.fieldSuggestions.getFieldValues( "client", { folder: "work/projects", includeInline: true } ); ``` ```javascript const ids = await quickAddApi.fieldSuggestions.getFieldValues( "Id", { folder: "work/projects", includeInline: true, includeInlineCodeBlocks: ["ad-note"] } ); ``` -------------------------------- ### Get Current Date and Time Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/QuickAddAPI.md Fetches the current date and time, with options for custom formatting and day offsets. Defaults to 'YYYY-MM-DD' format. ```javascript // Current date const today = quickAddApi.date.now(); // "2024-01-15" // Custom format const timestamp = quickAddApi.date.now("YYYY-MM-DD HH:mm:ss"); // With offset const nextWeek = quickAddApi.date.now("YYYY-MM-DD", 7); const lastMonth = quickAddApi.date.now("YYYY-MM-DD", -30); ``` -------------------------------- ### Run a QuickAdd Choice Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Advanced/CLI.md Execute a specific QuickAdd choice by its name or ID from the CLI. Ensure the vault is specified. ```bash obsidian vault=dev quickadd choice="Daily log" ``` ```bash obsidian vault=dev quickadd:run id="choice-id" ``` -------------------------------- ### Edit Active File Content Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/UserScripts.md Manipulate the content of the currently active file, including getting selections, cursor position, and replacing text. ```javascript async function start(params, settings) { const { app, obsidian } = params; // Get active file const activeFile = app.workspace.getActiveFile(); if (!activeFile) { new obsidian.Notice("No active file"); return; } // Get active editor const activeView = app.workspace.getActiveViewOfType(obsidian.MarkdownView); if (activeView) { const editor = activeView.editor; // Get selected text const selection = editor.getSelection(); // Get current line const cursor = editor.getCursor(); const line = editor.getLine(cursor.line); // Replace selection editor.replaceSelection("New text"); // Insert at cursor editor.replaceRange( "Inserted text", cursor ); // Get entire document const fullText = editor.getValue(); // Replace entire document editor.setValue("Completely new content"); } } ``` -------------------------------- ### Get Current Filename with FILENAMECURRENT Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/FormatSyntax.md Use `{{FILENAMECURRENT}}` to insert the basename of the file from which the template or capture was triggered. It honors the same required/optional behavior as `{{LINKCURRENT}}`. ```markdown Notes from {{FILENAMECURRENT}} ``` -------------------------------- ### List QuickAdd Choices Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Advanced/CLI.md View all available QuickAdd choices, optionally filtering by type or command. This is useful for discovering available automations. ```bash obsidian vault=dev quickadd:list ``` ```bash obsidian vault=dev quickadd:list type=Capture ``` ```bash obsidian vault=dev quickadd:list commands ``` -------------------------------- ### Access Obsidian Plugins in JavaScript Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Choices/MacroChoice.md Interact with other installed Obsidian plugins by accessing them through the `app.plugins.plugins` object. Check for plugin existence before attempting to use their APIs. ```javascript module.exports = async (params) => { const { app } = params; // Access Templater const templater = app.plugins.plugins["templater-obsidian"]; if (templater) { // Use Templater API } // Access MetaEdit const metaedit = app.plugins.plugins["metaedit"]; if (metaedit) { const { update } = metaedit.api; await update("property", "value", "path/to/file.md"); } }; ``` -------------------------------- ### JavaScript Script with Settings Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/Advanced/scriptsWithSettings.md Define a script with user-configurable settings. The 'entry' function receives QuickAdd and the user-defined settings. The 'settings' object defines the name, author, and options for the configuration menu. ```javascript const TEXT_FIELD = "Text field"; module.exports = { entry: async (QuickAdd, settings) => { // Logic here const textFieldSettingValue = settings[TEXT_FIELD]; }, settings: { name: "Demo", author: "Christian B. B. Houmann", options: { [TEXT_FIELD]: { type: "text", defaultValue: "", placeholder: "Placeholder", description: "Description here.", }, "Checkbox": { type: "checkbox", defaultValue: false, }, "Dropdown": { type: "dropdown", defaultValue: "Option 1", options: [ "Option 1", "Option 2", "Option 3", ], }, "Format": { type: "format", defaultValue: "{{DATE:YYYY-MM-DD}}", placeholder: "Placeholder", }, } }, }; ``` -------------------------------- ### QuickAdd API String Formatting Source: https://github.com/chhoumann/quickadd/blob/master/docs/versioned_docs/version-2.12.0/UserScripts.md Shows how to format strings using QuickAdd's template syntax, allowing dynamic insertion of dates and variable values. ```javascript const formatted = await quickAddApi.format( "Today is {{DATE}} and the title is {{VALUE:title}}", { title: "My Document" } ); ```