### Install @logseq/libs Source: https://context7.com/logseq/plugins/llms.txt Install the SDK using yarn or npm. This makes the `logseq` global namespace available for your plugin. ```shell yarn add @logseq/libs # or npm install @logseq/libs ``` -------------------------------- ### Start Development Server Source: https://github.com/logseq/plugins/blob/master/docs/README.md Run this command in your project's root directory to start the development server. Use `npm` or `yarn` depending on your package manager. Access the running application at http://localhost:3000. ```bash npm run dev # or yarn dev ``` -------------------------------- ### Example: Provide Custom UI Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html An example of providing a UI element, a link with an icon, that triggers a JavaScript alert when clicked. ```html ``` -------------------------------- ### Install @logseq/libs Package Source: https://github.com/logseq/plugins/blob/master/index.html Installs the @logseq/libs package using yarn. This is the first step to using the Logseq SDK. ```bash yarn add @logseq/libs ``` -------------------------------- ### Example: Provide Custom CSS Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html An example of injecting custom CSS, including importing an external font stylesheet. ```css @import url("https://at.alicdn.com/t/font_2409735_r7em724douf.css"); ``` -------------------------------- ### Example: Register Simple Slash Command Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html An example demonstrating how to register a simple slash command with a basic console log action. ```typescript logseq.Editor.registerSlashCommand("Say Hi", () => { console.log('Hi!')}) ``` -------------------------------- ### Install React Markdown with npm Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md Install the react-markdown package using npm. This package is ESM only. ```sh npm install react-markdown ``` -------------------------------- ### _installPluginHook Source: https://github.com/logseq/plugins/blob/master/interfaces/IAppProxy.html Installs a hook for a specific plugin. ```APIDOC ## _installPluginHook ### Description Installs a hook for a specific plugin. ### Signature `_installPluginHook(pid: string, hook: string, opts?: any) => void` ``` -------------------------------- ### _installPluginHook Source: https://github.com/logseq/plugins/blob/master/interfaces/IAppProxy.html Installs a hook for a specific plugin and event. ```APIDOC ## _installPluginHook ### Description Installs a hook for a specific plugin and event. ### Method (pid: string, hook: string, opts?: any) => void ### Parameters - **pid** (string) - The plugin ID. - **hook** (string) - The name of the hook. - **opts** (any) - Optional parameters for the hook. ``` -------------------------------- ### Example: Register Slash Command with Multiple Actions Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html An example showing how to register a slash command that triggers multiple predefined actions, including editor hooks and clearing the current slash command. ```typescript logseq.Editor.registerSlashCommand("πŸ’₯ Big Bang", [ ["editor/hook", "customCallback"], ["editor/clear-current-slash"],]); ``` -------------------------------- ### onIndiceInit Source: https://github.com/logseq/plugins/blob/master/interfaces/IPluginSearchServiceHooks.html This method is called when the search index for a graph is initialized. It can be used to perform setup tasks. ```APIDOC ## onIndiceInit ### Description Callback function executed when the search index for a specific graph is initialized. Plugins can use this to perform initial setup. ### Method Signature ```typescript onIndiceInit(graph: string): Promise ``` ### Parameters #### Path Parameters - `graph` (string) - The name of the graph for which the index was initialized. ### Returns - `Promise` - A promise that resolves with a boolean indicating success or status. ``` -------------------------------- ### Basic React Markdown Usage Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md A simple example demonstrating how to render a markdown string using ReactMarkdown. It requires React and ReactDOM. ```jsx import React from 'react' import ReactMarkdown from 'react-markdown' import ReactDom from 'react-dom' ReactDom.render(# Hello, *world*!, document.body) ``` -------------------------------- ### get version() Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Gets the current version of the Logseq plugin API. ```APIDOC ## get version() ### Description Gets the current version of the Logseq plugin API. ### Returns - string ``` -------------------------------- ### getInfo Source: https://github.com/logseq/plugins/blob/master/interfaces/IAppProxy.html Retrieves general application information. You can specify a key to get a particular piece of information. ```APIDOC ## getInfo ### Description Retrieves general application information. You can specify a key to get a particular piece of information. ### Method `getInfo(key?: keyof AppInfo)` ### Parameters #### Query Parameters - **key** (keyof AppInfo) - Optional - The specific key for the application information to retrieve. ### Returns `Promise` - A promise that resolves to the requested application information. ``` -------------------------------- ### get Utils() Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Retrieves the IUtilsProxy object, which provides utility functions for plugin development. ```APIDOC ## get Utils() ### Description Retrieves the IUtilsProxy object, which provides utility functions for plugin development. ### Returns - [IUtilsProxy](../interfaces/IUtilsProxy.html) ``` -------------------------------- ### Run Logseq DSL Query with logseq.DB Source: https://context7.com/logseq/plugins/llms.txt Execute queries using Logseq's query DSL, similar to `{{query ...}}` blocks in the editor. This example finds blocks tagged #meeting within the last 7 days. ```typescript // Find all blocks tagged #meeting from the last 7 days const results = await logseq.DB.q( "(and (page-tags #meeting) (between -7d today))" ) results?.forEach((block: any) => { console.log("Meeting note:", block.content) }) ``` -------------------------------- ### Provide Logseq Plugin UI Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Inject custom UI at a specific DOM node. Event handlers must be created in `provideModel`. The example shows adding a link with an icon that triggers the `openCalendar` method. ```typescript logseq.provideUI({key: 'open-calendar',path: '#search',template: ` `}) ``` -------------------------------- ### Use remark-gfm Plugin Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md Integrates the remark-gfm plugin to enable GitHub Flavored Markdown features like strikethrough, tables, and tasklists. Ensure remark-gfm is installed. ```jsx import React from 'react' import ReactMarkdown from 'react-markdown' import ReactDom from 'react-dom' import remarkGfm from 'remark-gfm' const markdown = `A paragraph with *emphasis* and **strong importance**. > A block quote with ~strikethrough~ and a URL: https://reactjs.org. * Lists * [ ] todo * [x] done A table: | a | b | | - | - | ` ReactDom.render( , document.body ) ``` -------------------------------- ### setupPluginUserInstance Source: https://github.com/logseq/plugins/blob/master/modules.html Function to set up and initialize a plugin user instance. ```APIDOC ## Function: setupPluginUserInstance ### Description Initializes the plugin user instance, making it available for use. ### Parameters (Details of parameters would be listed here if available in the source) ``` -------------------------------- ### logseq.ready() - Plugin entry point Source: https://context7.com/logseq/plugins/llms.txt The main entry point for every plugin. It signals to Logseq that the plugin is ready to run and accepts an optional model object and callback. It returns a Promise. ```APIDOC ## logseq.ready() ### Description The main entry point for every plugin. Signals to Logseq that the plugin is ready to run. Accepts an optional model object (same as `provideModel`) and an optional callback, and returns a `Promise`. ### Usage ```typescript import "@logseq/libs" // Minimal plugin β€” just show a message when Logseq is ready logseq.ready(async () => { console.log("Plugin loaded!", logseq.baseInfo.name) await logseq.UI.showMsg("Hello from my plugin!", "success") }).catch(console.error) ``` ``` -------------------------------- ### setupPluginUserInstance() Source: https://context7.com/logseq/plugins/llms.txt Initializes the plugin instance. This factory function creates and configures the global `LSPluginUser` instance. It is typically called internally by the SDK during `import "@logseq/libs"`, but can be called directly when building a custom plugin host. ```APIDOC ## `setupPluginUserInstance()` β€” Initialize the plugin instance The exported factory function that creates and configures the global `LSPluginUser` instance. Called internally by the SDK when `import "@logseq/libs"` runs. You do not normally call this directly unless building a custom plugin host. ```ts import { setupPluginUserInstance } from "@logseq/libs" // For custom host environments only: const pluginUser = setupPluginUserInstance(baseInfo, caller) pluginUser.ready(() => { pluginUser.UI.showMsg("Custom host initialized") }) ``` ``` -------------------------------- ### Initialize Plugin with logseq.ready() Source: https://context7.com/logseq/plugins/llms.txt The main entry point for every plugin. Call `logseq.ready()` before invoking any other API to signal that the plugin is ready to run. It accepts an optional model object and callback. ```typescript import "@logseq/libs" // Minimal plugin β€” just show a message when Logseq is ready logseq.ready(async () => { console.log("Plugin loaded!", logseq.baseInfo.name) await logseq.UI.showMsg("Hello from my plugin!", "success") }).catch(console.error) ``` -------------------------------- ### Initialize Plugin User Instance with setupPluginUserInstance Source: https://context7.com/logseq/plugins/llms.txt Use this function to create and configure the global `LSPluginUser` instance. This is typically called internally by the SDK during `import "@logseq/libs"`. Direct use is reserved for custom plugin host environments. ```typescript import { setupPluginUserInstance } from "@logseq/libs" // For custom host environments only: const pluginUser = setupPluginUserInstance(baseInfo, caller) pluginUser.ready(() => { pluginUser.UI.showMsg("Custom host initialized") }) ``` -------------------------------- ### Initialize Logseq Theme and Show Page Source: https://github.com/logseq/plugins/blob/master/index.html Sets the theme based on local storage and ensures the page is displayed after a short delay. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => window.app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### setupPluginUserInstance Source: https://github.com/logseq/plugins/blob/master/modules.html Initializes and returns an instance of the plugin user interface, allowing plugins to interact with Logseq's user-facing features. ```APIDOC ## Function: setupPluginUserInstance ### Description Sets up and returns an instance of `LSPluginUser`. This instance provides methods for plugins to interact with the Logseq user interface and manage plugin-specific user data. ### Signature ```typescript setupPluginUserInstance(): LSPluginUser ``` ### Returns - An instance of `LSPluginUser` which exposes methods for UI interactions and user data management. ``` -------------------------------- ### getSelectedBlocks Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Gets all currently selected blocks in the editor. ```APIDOC ## getSelectedBlocks ### Description Gets all currently selected blocks in the editor. ### Method APIDOC ### Endpoint APIDOC ``` -------------------------------- ### getPreviousSiblingBlock Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Gets the previous sibling block of a given block. ```APIDOC ## getPreviousSiblingBlock ### Description Gets the previous sibling block of a given block. ### Method APIDOC ### Endpoint APIDOC ### Parameters #### Path Parameters - **srcBlock** (number | BlockIdentity) - Required - The identity of the block whose previous sibling is to be retrieved. ``` -------------------------------- ### Get the current block being edited Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves the block entity that is currently in focus for editing. ```typescript getCurrentBlock: () => Promise<[BlockEntity](BlockEntity.html)> ``` -------------------------------- ### ready Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Initializes the plugin when the main Logseq app is ready. It can optionally accept a model and a callback function. ```APIDOC ## ready ### Description The main Logseq app is ready to run the plugin. ### Method ready(model?: any, callback?: any): Promise ### Parameters #### Optional Parameters - **model** (any) - same as the model in `provideModel` - **callback** (any) ### Returns Promise ``` -------------------------------- ### ready Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html The main Logseq app is ready to run the plugin. This method can be called with an optional model object or a callback function, or both. ```APIDOC ## ready ### Description The main Logseq app is ready to run the plugin. ### Method Overloaded ### Parameters #### Optional Parameters - **model** (Record) - Same as the model in `provideModel`. - **callback** ((e: any) => void | {}) - A function to run when the main Logseq app is ready. ### Returns Promise ``` -------------------------------- ### Get content of the editing block Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves the plain text content of the block that is currently being edited. ```typescript getEditingBlockContent: () => Promise ``` -------------------------------- ### Get all properties of a block Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves all properties associated with a specific block, returned as a key-value record. ```typescript getBlockProperties: ( block: number | [BlockIdentity](../types/BlockIdentity.html), ) => Promise> ``` -------------------------------- ### Get a specific block Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves a block by its identifier. Optionally, include its children in the returned data. ```typescript getBlock: ( srcBlock: number | [BlockIdentity](../types/BlockIdentity.html), opts?: Partial<{ includeChildren: boolean }>, ) => Promise<[BlockEntity](BlockEntity.html)> ``` -------------------------------- ### showSettingsUI Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Displays the plugin's settings UI. ```APIDOC ## showSettingsUI ### Description Displays the plugin's settings UI. ### Method Overloaded ### Returns void ``` -------------------------------- ### setupPluginUserInstance Function Source: https://github.com/logseq/plugins/blob/master/functions/setupPluginUserInstance.html The setupPluginUserInstance function is used internally to set up a plugin's user instance. It takes plugin base information and a caller object, returning an array of LSPluginUser objects. ```APIDOC ## Function: setupPluginUserInstance ### Description Internal function to set up a plugin user instance. ### Parameters * **pluginBaseInfo** (LSPluginBaseInfo) - Information about the plugin's base setup. * **pluginCaller** (LSPluginCaller) - The caller object for the plugin. ### Returns * [LSPluginUser[]] - An array of LSPluginUser objects. ``` -------------------------------- ### Get all tags Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves a list of all tags present in the Logseq graph. Tags are typically represented as pages. ```typescript getAllTags: () => Promise<[PageEntity](PageEntity.html)[]> ``` -------------------------------- ### showSettingsUI Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Displays the plugin's settings UI. This method is part of the ILSPluginUser interface. ```APIDOC ## showSettingsUI ### Description Displays the plugin's settings UI. ### Method void ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```javascript logseq.showSettingsUI(); ``` ### Response #### Success Response (void) Returns void. ### Response Example N/A ``` -------------------------------- ### Get the current page Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves the page entity that is currently active or being viewed. This could be a regular page or a journal page. ```typescript getCurrentPage: () => Promise<[BlockEntity](BlockEntity.html) | [PageEntity](PageEntity.html)> ``` -------------------------------- ### Math Rendering with Remark and Rehype Plugins Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md Enable math rendering in markdown by using `remark-math` and `rehype-katex` plugins. Ensure `katex` CSS is imported. ```jsx import React from 'react' import ReactDom from 'react-dom' import ReactMarkdown from 'react-markdown' import remarkMath from 'remark-math' import rehypeKatex from 'rehype-katex' import 'katex/dist/katex.min.css' // `rehype-katex` does not import the CSS for you ReactDom.render( , document.body ) ``` ```jsx

The lift coefficient ( ) is a dimensionless coefficient.

``` -------------------------------- ### Get Active Page Entity Source: https://context7.com/logseq/plugins/llms.txt Retrieves the `PageEntity` for the currently open page in the main view. Returns `null` if on the home screen. ```typescript const page = await logseq.Editor.getCurrentPage() if (page) { console.log("Page name:", page.name) console.log("Page UUID:", page.uuid) console.log("Is journal:", page["journal?"]) } ``` -------------------------------- ### Get Current Focused Block Source: https://context7.com/logseq/plugins/llms.txt Returns the `BlockEntity` of the block currently in focus (where the editor cursor is). Returns `null` if no block is being edited. ```typescript const block = await logseq.Editor.getCurrentBlock() if (block) { console.log("Editing block:", block.uuid) console.log("Content:", block.content) console.log("On page:", block.page) } ``` -------------------------------- ### provideTheme Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Sets the theme for the main Logseq application. ```APIDOC ## provideTheme ### Description Set the theme for the main Logseq app. ### Method Signature provideTheme(theme: [Theme](Theme.html)): this[] ### Parameters #### theme - **theme**: [Theme](Theme.html) - The theme object to apply. ### Returns - this[] - Returns the emitter instance for chaining. ``` -------------------------------- ### provideTheme Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Sets the theme for the main Logseq application. ```APIDOC ## provideTheme ### Description Sets the theme for the main Logseq application. This allows plugins to customize the overall look and feel. ### Method Signature provideTheme(theme: [Theme](../interfaces/Theme.html)): LSPluginUser ### Parameters #### Theme - **theme** ([Theme](../interfaces/Theme.html)) - An object conforming to the Theme interface, defining the theme properties. ### Returns - LSPluginUser - The LSPluginUser instance for chaining. ``` -------------------------------- ### Get Block Tree for a Named Page Source: https://context7.com/logseq/plugins/llms.txt Fetches all blocks for a specified page, identified by its name or UUID. The result is a nested tree structure. ```typescript const blocks = await logseq.Editor.getPageBlocksTree("My Project Notes") blocks.forEach(block => { console.log(block.content) if (block.children?.length) { console.log(" Children:", block.children.length) } }) ``` -------------------------------- ### Get all pages Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves a list of all pages present in the Logseq graph. An optional repository string can be provided, though its specific use case is not detailed here. ```typescript getAllPages: (repo?: string) => Promise<[PageEntity](PageEntity.html)[]> ``` -------------------------------- ### provideModel Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Creates an object to hold methods that can be referenced in `provideUI`. ```APIDOC ## provideModel ### Description Create an object to hold the methods referenced in `provideUI`. ### Method Signature provideModel(model: Record): this[] ### Parameters #### model - **model**: Record - An object containing methods to be exposed. ### Returns - this[] - Returns the emitter instance for chaining. ### Example ```javascript logseq.provideModel({ openCalendar () { console.log('Open the calendar!') }}) ``` ``` -------------------------------- ### Get SDK version with logseq.version Source: https://context7.com/logseq/plugins/llms.txt A getter that returns the current version string of the `@logseq/libs` SDK as reported at runtime. Useful for debugging or compatibility checks. ```typescript logseq.ready(() => { console.log("SDK version:", logseq.version) // β†’ e.g. "0.0.16" }) ``` -------------------------------- ### provideModel Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Creates an object to hold methods that can be referenced in `provideUI`. ```APIDOC ## provideModel ### Description Creates an object to hold methods that can be referenced in `provideUI`. This allows for modularity and separation of concerns in UI interactions. ### Method Signature provideModel(model: Record): LSPluginUser ### Parameters #### Model - **model** (Record) - An object containing methods to be exposed. ### Returns - LSPluginUser - The LSPluginUser instance for chaining. ### Example ```javascript logseq.provideModel({ openCalendar () { console.log('Open the calendar!') }}) ``` ``` -------------------------------- ### Get cursor position in editing block Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves the current cursor position within the block that is being edited. This includes the block's UUID and the character offset. ```typescript getEditingCursorPosition: () => Promise<[BlockCursorPosition](../types/BlockCursorPosition.html)> ``` -------------------------------- ### logseq.App.getUserConfigs() Source: https://context7.com/logseq/plugins/llms.txt Returns the current user's app configuration, such as preferred date format, preferred workflow, and language. ```APIDOC ## `logseq.App.getUserConfigs()` β€” Read user configuration Returns the current user's app configuration, such as preferred date format, preferred workflow, and language. ```ts const configs = await logseq.App.getUserConfigs() // configs.preferredDateFormat β†’ "MMM do, yyyy" // configs.preferredWorkflow β†’ ":now" | ":later" // configs.currentGraph β†’ "/Users/alice/notes" console.log("Date format:", configs.preferredDateFormat) ``` ``` -------------------------------- ### Get Active Graph with logseq.App.getCurrentGraph() Source: https://context7.com/logseq/plugins/llms.txt Retrieve metadata about the currently active Logseq graph, including its name, path, and URL. Returns null if no graph is open. ```typescript const graph = await logseq.App.getCurrentGraph() // graph: { name: "my-notes", path: "/Users/alice/notes", url: "logseq://graph/my-notes" } if (graph) { console.log("Active graph:", graph.name) console.log("Graph path:", graph.path) } ``` -------------------------------- ### Register a Logseq Theme with provideTheme() Source: https://context7.com/logseq/plugins/llms.txt Registers a theme that appears in Logseq's built-in theme picker. Requires a `name`, `url` to the theme CSS file, and optional `mode` (`"light"` | `"dark"`). ```typescript logseq.provideTheme({ name: "My Awesome Theme", url: "lsp://logseq.io/my-plugin/dist/theme.css", description: "A clean, minimal dark theme", mode: "dark", pid: logseq.baseInfo.id, }) ``` -------------------------------- ### Syntax Highlighting with Custom Code Component Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md Overwrite the default code handling to apply syntax highlighting using `react-syntax-highlighter`. Ensure `react-syntax-highlighter` is installed and imported. ```jsx import React from 'react' import ReactDom from 'react-dom' import ReactMarkdown from 'react-markdown' import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter' import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism' // Did you know you can use tildes instead of backticks for code in markdown? ✨ const markdown = `Here is some JavaScript code: ~~~js console.log('It works!') ~~~ ` ReactDom.render( ) : ( {children} ) } }} />, document.body ) ``` ```jsx <>

Here is some JavaScript code:

    
  
``` -------------------------------- ### provideStyle Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Injects custom CSS into the main Logseq application. ```APIDOC ## provideStyle ### Description Inject custom css for the main Logseq app. ### Method Signature provideStyle(style: string | [StyleOptions](../types/StyleOptions.html)): this[] ### Parameters #### style - **style**: string | [StyleOptions](../types/StyleOptions.html) - The CSS style to inject, either as a string or a StyleOptions object. ### Returns - this[] - Returns the emitter instance for chaining. ### Example ```javascript logseq.provideStyle(` @import url("https://at.alicdn.com/t/font_2409735_r7em724douf.css");`) ``` ``` -------------------------------- ### Get a specific property of a block Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves the value of a specific property for a given block. Note: The return type is BlockEntity, which might be a typo and should perhaps be the property value itself. ```typescript getBlockProperty: ( block: number | [BlockIdentity](../types/BlockIdentity.html), key: string, ) => Promise<[BlockEntity](BlockEntity.html)> ``` -------------------------------- ### provideStyle Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Injects custom CSS into the main Logseq application. ```APIDOC ## provideStyle ### Description Injects custom CSS styles into the main Logseq application, allowing for UI customization. ### Method Signature provideStyle(style: string): LSPluginUser ### Parameters #### Style - **style** (string) - A string containing the CSS rules to inject. ### Returns - LSPluginUser - The LSPluginUser instance for chaining. ### Example ```css logseq.provideStyle(` @import url("https://at.alicdn.com/t/font_2409735_r7em724douf.css"); `) ``` ``` -------------------------------- ### loadIgnoreFile Source: https://github.com/logseq/plugins/blob/master/interfaces/IGitProxy.html Loads the content of the .gitignore file. ```APIDOC ## loadIgnoreFile ### Description Loads the content of the .gitignore file. ### Method () => Promise ### Response #### Success Response (Promise) - **content** (string) - The content of the .gitignore file. ``` -------------------------------- ### Get State from App Store Source: https://github.com/logseq/plugins/blob/master/interfaces/IAppProxy.html Retrieve a specific piece of state from the Logseq app store. The state path corresponds to keys in the application's state management. ```typescript const isDocMode = await logseq.App.getStateFromStore('document/mode?') ``` -------------------------------- ### Insert Text at Cursor with logseq.Editor Source: https://context7.com/logseq/plugins/llms.txt Use `insertAtEditingCursor` to insert text at the current cursor position within the active block editor. This example is triggered by a keyboard shortcut. ```typescript logseq.App.registerCommandShortcut( { binding: "ctrl+shift+t" }, async () => { const now = new Date() const timestamp = `[[${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")} ]]` await logseq.Editor.insertAtEditingCursor(timestamp) } ) ``` -------------------------------- ### Create a New Page Source: https://context7.com/logseq/plugins/llms.txt Creates a new page with specified properties and options. Use `redirect: true` to navigate to the new page and `createFirstBlock: true` to add an initial empty block. ```typescript const newPage = await logseq.Editor.createPage( "2024 Goals", { author: "Alice", status: "active" }, { redirect: true, createFirstBlock: true, journal: false, } ) console.log("Created page:", newPage?.uuid) ``` -------------------------------- ### logseq.provideModel() - Register UI interaction handlers Source: https://context7.com/logseq/plugins/llms.txt Creates an object holding handler methods that can be called from HTML templates injected via `provideUI`. The method names become callable via `data-on-click` attributes on injected elements. ```APIDOC ## logseq.provideModel() ### Description Creates an object holding handler methods that can be called from HTML templates injected via `provideUI`. The method names become callable via `data-on-click` attributes on injected elements. ### Usage ```typescript logseq.provideModel({ openCalendar() { console.log("Opening calendar…") logseq.App.pushState("page", { name: "Journal" }) }, async insertDate() { const block = await logseq.Editor.getCurrentBlock() if (block) { await logseq.Editor.insertAtEditingCursor( new Date().toISOString().split("T")[0] ) } }, }) ``` ``` -------------------------------- ### Add Block Context Menu Item with logseq.Editor Source: https://context7.com/logseq/plugins/llms.txt Add custom items to the right-click context menu for blocks. This example copies the block's UUID to the clipboard. ```typescript logseq.Editor.registerBlockContextMenuItem( "Copy block UUID", async ({ uuid }) => { await navigator.clipboard.writeText(uuid) await logseq.App.showMsg("UUID copied to clipboard!", "success") } ) ``` -------------------------------- ### getInfo Source: https://github.com/logseq/plugins/blob/master/interfaces/IAppProxy.html Retrieves application information. ```APIDOC ## getInfo ### Description Retrieves application information. ### Method (key?: keyof AppInfo) => Promise ### Parameters - **key** (keyof AppInfo) - Optional. The specific key of the application information to retrieve. ``` -------------------------------- ### Get all properties Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves all properties defined across pages in the Logseq graph. The return type suggests it might return page entities, implying properties are associated with pages. ```typescript getAllProperties: () => Promise<[PageEntity](PageEntity.html)[]> ``` -------------------------------- ### Get Backlinks for a Page Source: https://context7.com/logseq/plugins/llms.txt Retrieves all blocks across the graph that reference a given page. Returns an array of tuples, where each tuple contains the referenced page and an array of its referencing blocks. ```typescript const refs = await logseq.Editor.getPageLinkedReferences("Project Alpha") // refs is an array of [PageEntity, BlockEntity[]] tuples refs?.forEach(([page, blocks]) => { console.log(`Page: ${page.name}, ${blocks.length} reference(s)`) blocks.forEach(b => console.log(" β†’", b.content)) }) ``` -------------------------------- ### showMainUI Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Makes the plugin's main UI visible. Optionally, it can automatically focus the UI. ```APIDOC ## showMainUI ### Description Show the plugin's UI. ### Method showMainUI(opts?: { autoFocus: boolean }): void ### Parameters #### Optional Parameters - **opts** ({ autoFocus: boolean }) - Configuration options for showing the UI. - **autoFocus** (boolean) - Whether to automatically focus the UI when shown. ### Returns void ``` -------------------------------- ### Get Full Block Tree of Current Page Source: https://context7.com/logseq/plugins/llms.txt Fetches all blocks on the current page as a nested tree structure. Useful for visualizing page content or processing hierarchical data. ```typescript const blocks = await logseq.Editor.getCurrentPageBlocksTree() // Flatten and print all block contents function flatten(nodes: typeof blocks): string[] { return nodes.flatMap(b => [b.content, ...flatten(b.children ?? [])]) } console.log("All blocks:", flatten(blocks)) // Example: initialize a mind-map visualization initMindMap(blocks) ``` -------------------------------- ### q Source: https://github.com/logseq/plugins/blob/master/interfaces/IDBProxy.html Run a DSL (Domain Specific Language) query. This method is useful for simpler queries defined in Logseq's DSL. ```APIDOC ## q ### Description Run a DSL query. ### Method `q` ### Parameters * **dsl** (string) - Required - The DSL query string. ### Returns Promise - A promise that resolves with an array of results. ``` -------------------------------- ### makeSandboxStorage Source: https://github.com/logseq/plugins/blob/master/interfaces/IAssetsProxy.html Creates and returns an asynchronous storage instance for use within a sandbox environment. This allows for isolated data storage. ```APIDOC ## makeSandboxStorage ### Description Creates a sandbox storage. ### Method makeSandboxStorage ### Returns IAsyncStorage ### Example ```typescript const storage = logseq.Assets.makeSandboxStorage(); await storage.setItem("key", "value"); const value = await storage.getItem("key"); ``` ``` -------------------------------- ### Provide Logseq Plugin Styles Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Inject custom CSS for the main Logseq application. This can be a CSS string or a StyleOptions object. Example shows importing an external CSS file. ```typescript logseq.provideStyle(` @import url("https://at.alicdn.com/t/font_2409735_r7em724douf.css"); ) ``` -------------------------------- ### Customize ReactMarkdown Components Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md Map markdown elements to custom React components to alter their rendering. For example, `h1` can be rendered as `h2`, and `em` can be styled with a red foreground color. ```jsx }} /> ``` -------------------------------- ### Import Logseq Plugin SDK Source: https://github.com/logseq/plugins/blob/master/index.html Imports the logseq plugin SDK to be available as a global namespace in your project. ```javascript import "@logseq/libs" ``` -------------------------------- ### logseq.provideTheme() - Register a Logseq theme Source: https://context7.com/logseq/plugins/llms.txt Registers a theme that appears in Logseq's built-in theme picker. Requires a `name`, `url` pointing to the theme CSS file, and optional `mode` (`"light"` | `"dark"`). ```APIDOC ## logseq.provideTheme() ### Description Registers a theme that appears in Logseq's built-in theme picker. Requires a `name`, `url` pointing to the theme CSS file, and optional `mode` (`"light"` | `"dark"`). ### Usage ```typescript logseq.provideTheme({ name: "My Awesome Theme", url: "lsp://logseq.io/my-plugin/dist/theme.css", description: "A clean, minimal dark theme", mode: "dark", pid: logseq.baseInfo.id, }) ``` ``` -------------------------------- ### React Markdown with remark-gfm Plugin Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md Example of using the remark-gfm plugin to enable GitHub Flavored Markdown features like links, tables, and tasklists. The markdown content is passed as a string. ```jsx import React from 'react' import ReactDom from 'react-dom' import ReactMarkdown from 'react-markdown' import remarkGfm from 'remark-gfm' const markdown = `Just a link: https://reactjs.com.` ReactDom.render( , document.body ) ``` -------------------------------- ### execCommand Source: https://github.com/logseq/plugins/blob/master/interfaces/IGitProxy.html Executes a Git command with the provided arguments and returns the result. ```APIDOC ## execCommand ### Description Executes a Git command with the provided arguments and returns the result. ### Method (args: string[]) => Promise ### Parameters #### Path Parameters - **args** (string[]) - Required - The arguments to pass to the Git command. ### Response #### Success Response (Promise) - **result** (IGitResult) - The result of the Git command execution. ``` -------------------------------- ### logseq.DB.q() Source: https://context7.com/logseq/plugins/llms.txt Runs a Logseq query DSL query (the same syntax used in `{{query ...}}` blocks in the editor). See https://docs.logseq.com/#/page/queries for syntax. ```APIDOC ## `logseq.DB.q()` β€” Run a Logseq DSL query Runs a Logseq query DSL query (the same syntax used in `{{query ...}}` blocks in the editor). See https://docs.logseq.com/#/page/queries for syntax. ```ts // Find all blocks tagged #meeting from the last 7 days const results = await logseq.DB.q( `(and (page-tags #meeting) (between -7d today))` ) results?.forEach((block: any) => { console.log("Meeting note:", block.content) }) ``` ``` -------------------------------- ### getAllProperties Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Retrieves all properties available in the system. ```APIDOC ## getAllProperties ### Description Retrieves all properties available in the system. ### Method getAllProperties ### Response #### Success Response (PageEntity[]) An array of PageEntity objects representing all properties. ``` -------------------------------- ### logseq.beforeunload() Source: https://context7.com/logseq/plugins/llms.txt Registers a callback that runs just before the plugin is unloaded, allowing for cleanup of resources, data flushing, or cancellation of subscriptions. ```APIDOC ## `logseq.beforeunload()` β€” Cleanup before plugin unload Registers a callback that runs just before the plugin is unloaded (e.g., when the user disables it or Logseq closes). Use this to clean up resources, flush data, or cancel subscriptions. ```ts logseq.beforeunload(async (e) => { console.log("Plugin unloading…", e) // Save unsaved state await logseq.FileStorage.setItem("dirty-buffer", pendingContent) // Cancel any ongoing polling clearInterval(syncTimer) }) ``` ``` -------------------------------- ### beforeunload(callback: (e: any) => Promise) Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Registers a callback function to be executed before the plugin is unloaded. ```APIDOC ## beforeunload(callback: (e: any) => Promise) ### Description Registers a callback function to be executed before the plugin is unloaded. ### Parameters - callback: (e: any) => Promise ### Returns - void ``` -------------------------------- ### Run a git command with logseq.Git.execCommand() Source: https://context7.com/logseq/plugins/llms.txt Executes a git command on the current graph's repository. Available only for file-based graphs. Handles command execution and provides results including exit code and standard error. ```typescript // Commit all changes with a timestamped message const result = await logseq.Git.execCommand([ "commit", "--all", "--message", `Auto-commit: ${new Date().toISOString()}`, ]) if (result.exitCode === 0) { await logseq.App.showMsg("Graph committed to git!", "success") } else { await logseq.App.showMsg(`Git error: ${result.stderr}`, "error") } ``` -------------------------------- ### Import React Markdown in Browser Source: https://github.com/logseq/plugins/blob/master/docs/pages/_index.md Import ReactMarkdown from esm.sh for use in browser projects. The ?bundle flag is used for bundling. ```html ``` -------------------------------- ### builtInOpen Source: https://github.com/logseq/plugins/blob/master/interfaces/IAssetsProxy.html Attempts to open a specified asset file within the Logseq application. Returns a promise that resolves to a boolean indicating success or failure. ```APIDOC ## builtInOpen ### Description Try to open asset type file in Logseq app. ### Method builtInOpen ### Parameters #### Path Parameters - **path** (string) - Description of the path parameter ### Returns Promise ### Example ```typescript await logseq.Assets.builtInOpen("path/to/asset.png"); ``` ``` -------------------------------- ### Provide Plugin Model Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Define methods that can be referenced in `provideUI`. This allows for creating interactive UI components. ```typescript provideModel(model: Record): LSPluginUser ``` -------------------------------- ### showMainUI Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Shows the plugin's main UI element. ```APIDOC ## showMainUI ### Description Show the plugin's UI. ### Method Overloaded ### Parameters #### Optional Parameters - **opts** ({ autoFocus: boolean }) - Options for showing the UI, such as whether to auto-focus. ### Returns void ``` -------------------------------- ### Read User Configurations with logseq.App.getUserConfigs() Source: https://context7.com/logseq/plugins/llms.txt Fetch the current user's application configuration settings, such as date format, workflow preference, and current graph. ```typescript const configs = await logseq.App.getUserConfigs() // configs.preferredDateFormat β†’ "MMM do, yyyy" // configs.preferredWorkflow β†’ ":now" | ":later" // configs.currentGraph β†’ "/Users/alice/notes" console.log("Date format:", configs.preferredDateFormat) ``` -------------------------------- ### logseq.App.registerCommandPalette() Source: https://context7.com/logseq/plugins/llms.txt Registers a named action directly in the command palette without a keyboard shortcut. ```APIDOC ## `logseq.App.registerCommandPalette()` β€” Add a palette entry Registers a named action directly in the command palette without a keyboard shortcut. ```ts logseq.App.registerCommandPalette( { key: "open-dashboard", label: "Open Plugin Dashboard" }, () => logseq.showMainUI() ) ``` ``` -------------------------------- ### createTemplate Source: https://github.com/logseq/plugins/blob/master/interfaces/IAppProxy.html Creates a new template. ```APIDOC ## createTemplate ### Description Creates a new template. ### Signature `createTemplate(target: string, name: string, opts?: { overwrite: boolean }) => Promise` ``` -------------------------------- ### LSPluginUser Methods Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html This section details the methods available on the LSPluginUser interface, allowing plugins to perform actions and interact with Logseq. ```APIDOC ## Methods ### `addListener(eventName: string, listener: (...args: any[]) => void): void` Adds an event listener. ### `emit(eventName: string, ...args: any[]): void` Emits an event. ### `eventNames(): string[]` Returns an array of all event names. ### `hideMainUI(): void` Hides the main UI. ### `hideSettingsUI(): void` Hides the settings UI. ### `listenerCount(eventName: string): number` Returns the number of listeners for a given event. ### `listeners(eventName: string): Function[]` Returns an array of listeners for a given event. ### `off(eventName: string, listener: (...args: any[]) => void): void` Removes an event listener. ### `on(eventName: string, listener: (...args: any[]) => void): void` Registers an event listener. ### `once(eventName: string, listener: (...args: any[]) => void): void` Registers a one-time event listener. ### `onSettingsChanged(callback: (newSettings: Record) => void): void` Registers a callback to be invoked when plugin settings change. ### `provideModel(model: any): void` Provides a model to the plugin system. ### `provideStyle(css: string): void` Provides custom CSS styles to the plugin. ### `provideTheme(theme: Record): void` Provides theme variables to the plugin. ### `provideUI(element: HTMLElement): void` Provides a UI element to be rendered in Logseq. ### `ready(): Promise` Returns a promise that resolves when the plugin is ready. ### `removeAllListeners(eventName?: string): void` Removes all event listeners, or all listeners for a specific event. ### `removeListener(eventName: string, listener: (...args: any[]) => void): void` Removes a specific event listener. ### `resolveResourceFullUrl(url: string): string` Resolves a resource URL to its full, absolute path. ### `setMainUIAttrs(attrs: Record): void` Sets attributes for the main UI. ### `setMainUIInlineStyle(style: Record): void` Sets inline styles for the main UI. ### `showMainUI(): void` Shows the main UI. ### `showSettingsUI(): void` Shows the settings UI. ### `toggleMainUI(): void` Toggles the visibility of the main UI. ### `updateSettings(newSettings: Record): void` Updates the plugin's settings. ### `useSettingsSchema(schema: Record): void` Defines the schema for the plugin's settings. ``` -------------------------------- ### _execCallableAPI(method: string, ...args: any[]) Source: https://github.com/logseq/plugins/blob/master/classes/LSPluginUser.html Internal method to execute a callable API method. ```APIDOC ## _execCallableAPI(method: string, ...args: any[]) ### Description Internal method to execute a callable API method. ### Parameters - method: string - ...args: any[] ### Returns - void ``` -------------------------------- ### logseq.Git.execCommand() Source: https://context7.com/logseq/plugins/llms.txt Executes a git command on the graph repository using dugite. Available only for file-based graphs. ```APIDOC ## `logseq.Git.execCommand()` β€” Run a git command on the graph repository Executes a git command (via [dugite](https://github.com/desktop/dugite/blob/master/docs/api/exec.md)) in the directory of the current graph. Available only for file-based graphs. ```ts // Commit all changes with a timestamped message const result = await logseq.Git.execCommand([ "commit", "--all", "--message", `Auto-commit: ${new Date().toISOString()}`, ]) if (result.exitCode === 0) { await logseq.App.showMsg("Graph committed to git!", "success") } else { await logseq.App.showMsg(`Git error: ${result.stderr}`, "error") } ``` ``` -------------------------------- ### logseq.Editor.createPage() Source: https://context7.com/logseq/plugins/llms.txt Creates a new page with optional initial properties. Returns the new `PageEntity`. ```APIDOC ## `logseq.Editor.createPage()` β€” Create a new page Creates a new page with optional initial properties. Returns the new `PageEntity`. ```ts const newPage = await logseq.Editor.createPage( "2024 Goals", { author: "Alice", status: "active" }, { redirect: true, createFirstBlock: true, journal: false, } ) console.log("Created page:", newPage?.uuid) ``` ``` -------------------------------- ### Provide Logseq Plugin Theme Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Set the theme for the main Logseq application. Accepts a `Theme` object. ```typescript provideTheme(theme: Theme): this ``` -------------------------------- ### Command and Event Registration Source: https://github.com/logseq/plugins/blob/master/interfaces/IEditorProxy.html Functions for registering custom commands and context menu items. ```APIDOC ## registerBlockContextMenuItem ### Description Registers a custom context menu item for blocks. ### Method Not specified (assumed SDK method) ### Endpoint Not applicable ## registerHighlightContextMenuItem ### Description Registers a custom context menu item for highlights. ### Method Not specified (assumed SDK method) ### Endpoint Not applicable ## registerSlashCommand ### Description Registers a new slash command. ### Method Not specified (assumed SDK method) ### Endpoint Not applicable ``` -------------------------------- ### Provide Logseq Plugin Model Source: https://github.com/logseq/plugins/blob/master/interfaces/ILSPluginUser.html Create an object to hold methods referenced in `provideUI`. This is used to define actions that can be triggered by UI elements. ```typescript logseq.provideModel({ openCalendar () { console.log('Open the calendar!') }}) ```