### Complete Event Handling Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/events.md A comprehensive example demonstrating setup, event registration, and conditional handling based on whether the script is triggered by an Obsidian event. ```python import os import sys from obsidian_python_bridge import ( ObsidianPluginDevPythonToJS, define_settings, _handle_cli_args, is_handling_event, get_event_name, get_event_payload ) # --- Setup --- MY_SETTINGS = [ {"key": "enable_logging", "type": "toggle", "label": "Log events", "default": True} ] define_settings(MY_SETTINGS) _handle_cli_args() ``` -------------------------------- ### Complete Links and Backlinks Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/links.md A comprehensive example demonstrating the setup and usage of both get_links and get_backlinks methods. It retrieves and displays outgoing links and incoming backlinks for the currently active note, then shows a notification with the total connection count. ```python from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, define_settings, _handle_cli_args ) # Setup MY_SETTINGS = [] define_settings(MY_SETTINGS) _handle_cli_args() if __name__ == "__main__": obsidian = ObsidianPluginDevPythonToJS() # Get current note info current_note = obsidian.get_active_note_relative_path() if not current_note.endswith(".md"): current_note = current_note.replace(".md", "") obsidian.show_notification(f"Analyzing: {current_note}") # Get links from current note outgoing = obsidian.get_links(current_note, type="outgoing") print(f"\nOutgoing links ({len(outgoing)}):") for link in outgoing: print(f" -> {link}") # Get backlinks to current note incoming = obsidian.get_backlinks(current_note) print(f"\nIncoming backlinks ({len(incoming)} sources):") for source, link_list in incoming.items(): print(f"\n From: {source}") for link_info in link_list: display = link_info.get("displayText", "") print(f" - {display}") # Report total_connections = len(outgoing) + sum(len(l) for l in incoming.values()) obsidian.show_notification( f"Note has {total_connections} link connections" ) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md Install all necessary Node.js dependencies for the project using Bun. ```bash bun install ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/configuration.md A comprehensive example demonstrating script settings definition, client initialization with connection and request timeouts, retrieving user settings, and making an API request using configured values. ```python import os from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, define_settings, _handle_cli_args ) # --- 1. Define script settings (user-configurable via Obsidian UI) --- MY_SETTINGS = [ { "key": "api_url", "type": "text", "label": "API Base URL", "default": "https://api.example.com" }, { "key": "timeout', "type": "number", "label": "Request Timeout (seconds)", "min": 1, "max": 60, "default": 10 }, { "key": "debug", "type": "toggle", "label": "Enable Debug Logging", "default": False } ] define_settings(MY_SETTINGS) _handle_cli_args() # --- 2. Initialize client with environment configuration --- if __name__ == "__main__": # Client reads OBSIDIAN_HTTP_PORT automatically obsidian = ObsidianPluginDevPythonToJS( connect_timeout=2.0, request_timeout=10.0 ) # --- 3. Get script-specific settings from Obsidian UI --- user_settings = obsidian.get_script_settings() api_url = user_settings.get("api_url") timeout = user_settings.get("timeout", 10) debug = user_settings.get("debug", False) # --- 4. Use configuration in script --- if debug: obsidian.show_notification("Debug mode enabled") # Make API request with configured timeout import requests response = requests.get(api_url, timeout=timeout) ``` -------------------------------- ### Simple Settings System Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md A basic example demonstrating how to define, register, and retrieve settings within a Python script for Obsidian. ```python from ObsidianPluginDevPythonToJS import ( define_settings, _handle_cli_args, ObsidianPluginDevPythonToJS ) # Step 1: Define settings MY_SETTINGS = [ {"key": "api_key", "type": "text", "label": "API Key", "default": ""} ] # Step 2: Register settings (required) define_settings(MY_SETTINGS) # Step 3: Handle discovery (required) _handle_cli_args() # Step 4: Main script logic if __name__ == "__main__": obsidian = ObsidianPluginDevPythonToJS() settings = obsidian.get_script_settings() api_key = settings.get("api_key") print(f"Using API key: {api_key}") ``` -------------------------------- ### Complete Python Script Example with Settings Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md A comprehensive example demonstrating how to define, register, and handle settings, then use them within a script that interacts with an external API. It includes error handling for both API requests and Obsidian communication. ```python import os import sys from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, ObsidianCommError, define_settings, _handle_cli_args, ) # --- Step 1: Define Settings --- MY_SETTINGS = [ { "key": "api_endpoint", "type": "text", "label": "API Endpoint", "description": "The base URL for the API", "default": "https://api.example.com" }, { "key": "api_key", "type": "text", "label": "API Key", "description": "Your authentication token", "default": "" }, { "key": "timeout", "type": "number", "label": "Request Timeout (seconds)", "min": 1, "max": 300, "step": 1, "default": 30 }, { "key": "retry_count", "type": "number", "label": "Retry Count", "min": 0, "max": 10, "default": 3 }, { "key": "verbose", "type": "toggle", "label": "Verbose Logging", "default": False }, { "key": "priority", "type": "dropdown", "label": "Default Priority", "options": ["low", "normal", "high"], "default": "normal" } ] # --- Step 2: Register Settings --- define_settings(MY_SETTINGS) # --- Step 3: Handle Settings Discovery --- _handle_cli_args() # --- Step 4: Main Script Logic --- if __name__ == "__main__": try: # Initialize client obsidian = ObsidianPluginDevPythonToJS() # Retrieve user-configured settings settings = obsidian.get_script_settings() api_endpoint = settings.get("api_endpoint") api_key = settings.get("api_key") timeout = settings.get("timeout", 30) retry_count = settings.get("retry_count", 3) verbose = settings.get("verbose", False) priority = settings.get("priority", "normal") if verbose: obsidian.show_notification("Script started with settings loaded") # Use settings in your API calls or logic import requests try: response = requests.get( f"{api_endpoint}/status", headers={"Authorization": f"Bearer {api_key}"}, timeout=timeout ) if verbose: obsidian.show_notification(f"API Status: {response.status_code}") obsidian.show_notification("Script completed successfully!") except requests.exceptions.RequestException as e: obsidian.show_notification(f"API Error: {e}") if verbose: print(f"Error details: {e}", file=sys.stderr) except ObsidianCommError as e: print(f"Obsidian connection error: {e}", file=sys.stderr) obsidian.show_notification(f"Error: Cannot connect to Obsidian") sys.exit(1) except Exception as e: print(f"Unexpected error: {e}", file=sys.stderr) sys.exit(1) ``` -------------------------------- ### Get Script Settings Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/types.md Fetches user-configured settings for the current script and accesses specific values with default fallbacks. Assumes settings keys like 'api_key', 'enabled', and 'threshold'. ```python settings = obsidian.get_script_settings() api_key = settings.get("api_key", "") is_enabled = settings.get("enabled", True) threshold = settings.get("threshold", 10) ``` -------------------------------- ### Define Settings Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Demonstrates how to use the `define_settings` function to register a list of setting definitions for a script. ```python from ObsidianPluginDevPythonToJS import define_settings MY_SETTINGS = [ {"key": "setting1", "type": "text", "label": "Setting 1"}, {"key": "setting2", "type": "number", "label": "Setting 2"}, ] define_settings(MY_SETTINGS) ``` -------------------------------- ### Initialize Plugin and Get Settings Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Initialize the Obsidian plugin and retrieve script settings. Ensure initialization happens before getting settings. ```python obsidian = ObsidianPluginDevPythonToJS() # Initialize first settings = obsidian.get_script_settings() # Then get settings ``` -------------------------------- ### Install Python requests Library Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md Install the 'requests' library for HTTP communication. This is a mandatory dependency for the plugin. ```bash pip install requests ``` ```bash python3 -m pip install requests ``` -------------------------------- ### Combined Editor Operations Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/editor.md This example demonstrates a sequence of editor operations including getting context, modifying the current line to uppercase, setting the cursor position, and scrolling to a specific line. Ensure the `ObsidianPluginDevPythonToJS` class is correctly imported. ```python from ObsidianPluginDevPythonToJS import ObsidianPluginDevPythonToJS obsidian = ObsidianPluginDevPythonToJS() # Get editor context context = obsidian.get_editor_context() if not context: print("No active editor") exit(1) # Get current cursor position cursor = context["cursor"] current_line = cursor["line"] # Get current line content line_content = obsidian.get_line(current_line) print(f"Current line: {line_content}") # Replace current line with uppercase obsidian.set_line(current_line, line_content.upper()) # Move cursor to line 10 obsidian.set_cursor(10, 0) # Scroll to line 10 and center it obsidian.scroll_into_view(from_line=10, from_ch=0, center=True) ``` -------------------------------- ### Install Optional PyYAML Library Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md Install the 'PyYAML' library if you plan to use specific property management functions. This is an optional dependency. ```bash pip install PyYAML ``` ```bash python3 -m pip install PyYAML ``` -------------------------------- ### Clone the Repository Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md Clone the plugin's source code from GitHub to start development. ```bash git clone https://github.com/mathe00/obsidian-plugin-python-bridge.git ``` -------------------------------- ### Handle CLI Arguments Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Shows how to use `_handle_cli_args` to manage script discovery and prevent main logic from running during that process. ```python from ObsidianPluginDevPythonToJS import define_settings, _handle_cli_args MY_SETTINGS = [] define_settings(MY_SETTINGS) _handle_cli_args() # Exits here if discovery is running # Main script logic starts here if __name__ == "__main__": # Safe to proceed - discovery is not running print("Script started") ``` -------------------------------- ### Install PyYAML Dependency Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/frontmatter.md Shows the command to install the required PyYAML library. This is necessary for frontmatter operations; missing it will result in a NameError. ```bash pip install PyYAML ``` -------------------------------- ### Get Backlinks Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/types.md Retrieves and iterates through backlinks for a target note, printing the display text of each link. Maps source note paths to lists of link information. ```python backlinks = obsidian.get_backlinks("target-note") for source_path, links in backlinks.items(): print(f"\n{source_path}:") for link in links: print(f" - {link.get('displayText', '')}") ``` -------------------------------- ### Install Dependencies Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/INDEX.md Provides the command to install the required Python dependencies for the Obsidian Plugin Python Bridge. Ensure these are installed before running scripts that utilize the bridge. ```bash pip install requests PyYAML ``` -------------------------------- ### Initialize Obsidian Client Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/client.md Instantiate the client using default settings or specify connection parameters. Handles potential communication or configuration errors during setup. ```python from ObsidianPluginDevPythonToJS import ObsidianPluginDevPythonToJS, ObsidianCommError try: # Create client using default port from environment or 27123 obsidian = ObsidianPluginDevPythonToJS() # Use client methods (inherited from mixins) obsidian.show_notification("Hello from Python!") content = obsidian.get_active_note_content() except ObsidianCommError as e: print(f"Error: {e.action} failed with status {e.status_code}") except ValueError as e: print(f"Invalid configuration: {e}") ``` -------------------------------- ### List Folder Contents Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/types.md Lists files and subfolders within a specified project folder. Iterates through the returned dictionary to print each item. ```python contents = obsidian.list_folder("project") for file in contents["files"]: print(f"File: {file}") for folder in contents["folders"]: print(f"Folder: {folder}") ``` -------------------------------- ### Complete Frontmatter Management Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/frontmatter.md Demonstrates adding and updating various frontmatter properties like status, priority, and tags for an active note. Ensure the ObsidianPluginDevPythonToJS class and necessary functions are imported. ```python from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, define_settings, _handle_cli_args ) # Setup MY_SETTINGS = [] define_settings(MY_SETTINGS) _handle_cli_args() if __name__ == "__main__": obsidian = ObsidianPluginDevPythonToJS() # Get active note path abs_path = obsidian.get_active_note_absolute_path() # Add metadata fields obsidian.manage_properties_key(abs_path, "add", "status") obsidian.manage_properties_key(abs_path, "add", "priority") obsidian.manage_properties_key(abs_path, "add", "tags") # Set values obsidian.manage_properties_value( abs_path, "status", "add", "in-progress" ) obsidian.manage_properties_value( abs_path, "priority", "add", 5 ) obsidian.manage_properties_value( abs_path, "tags", "add", ["work", "important"] ) # Update values obsidian.manage_properties_value( abs_path, "status", "update", new_value="completed" ) # Add more tags obsidian.manage_properties_value( abs_path, "tags", "add", "archived" ) obsidian.show_notification("Frontmatter updated!") ``` -------------------------------- ### Define and Use Script-Specific Settings Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md This example shows how to define script-specific settings (like API keys or toggles) that will be discovered and managed by the Obsidian UI. It includes the recommended structure for settings discovery and handling CLI arguments. ```python # Example snippet from your script import sys import os from ObsidianPluginDevPythonToJS import define_settings, _handle_cli_args, ObsidianPluginDevPythonToJS # --- Event Check (Recommended) --- # ... # --- Settings Definition & Discovery Handling (Recommended) --- MY_SETTINGS = [ { "key": "api_key", "type": "text", "label": "API Key", "default": "" }, { "key": "enabled", "type": "toggle", "label": "Enable Feature", "default": True } ] define_settings(MY_SETTINGS) _handle_cli_args() # Handles discovery request from Obsidian and exits # --- Main Script Logic --- if __name__ == "__main__" and not os.environ.get("OBSIDIAN_EVENT_NAME"): obsidian = ObsidianPluginDevPythonToJS() settings = obsidian.get_script_settings() api_key = settings.get("api_key") feature_enabled = settings.get("enabled") # ... use settings ... ``` -------------------------------- ### Create a Note with User Input Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/ui.md This example demonstrates how to collect various types of user input (text, boolean, range) and use them to create a new note in Obsidian. It includes error handling for communication issues. ```python from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, ObsidianCommError, define_settings, _handle_cli_args ) # Setup MY_SETTINGS = [] define_settings(MY_SETTINGS) _handle_cli_args() if __name__ == "__main__": obsidian = ObsidianPluginDevPythonToJS() try: # Collect user input title = obsidian.request_user_input( script_name="Create Note", input_type="text", message="Note title" ) is_important = obsidian.request_user_input( script_name="Create Note", input_type="boolean", message="Is this important?" ) priority = obsidian.request_user_input( script_name="Create Note", input_type="range", message="Priority level", min_value=1, max_value=10, step=1 ) # Create note with collected data content = f"# {title}\n\n**Priority:** {priority}/10\n**Important:** {is_important}\n\nContent here...\n" obsidian.create_note(f"notes/{title}.md", content) obsidian.show_notification(f"Note '{title}' created!") except ObsidianCommError as e: obsidian.show_notification(f"Error: {e}") ``` -------------------------------- ### Textarea Input Setting Definition Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Example of a setting definition for a multi-line text input field. ```json { "key": "notes", "type": "textarea", "label": "Additional Notes", "default": "", "description": "Multi-line notes" } ``` -------------------------------- ### Manage Properties Key Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/types.md Attempts to add a new key to properties and prints a success or error message based on the operation result. Requires the absolute path, operation type, and key name. ```python result = obsidian.manage_properties_key(abs_path, "add", "new_key") if result["success"]: print("Key added successfully") else: print(f"Failed: {result['error']}") ``` -------------------------------- ### Good Descriptive Setting Label Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Use descriptive labels and descriptions for settings to improve user understanding. This example shows a good practice for a text input. ```python {"key": "api_endpoint", "type": "text", "label": "API Endpoint", "description": "The base URL for the REST API"} ``` -------------------------------- ### Get All Note Paths Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Fetch a list of all note paths within the vault, either as vault-relative paths or absolute filesystem paths. ```python obsidian = ObsidianPluginDevPythonToJS() # Vault-relative paths rel_paths = obsidian.get_all_note_paths(absolute=False) print(f"Found {len(rel_paths)} notes") ``` -------------------------------- ### Basic Python-Obsidian Bridge Interaction Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md A fundamental example of initializing the Obsidian bridge and handling potential events. It includes the recommended structure for settings discovery, even when no specific settings are defined for the script. ```python # Import the Python-Obsidian bridge module # Make sure 'requests' is installed: pip install requests import sys import os import json from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, ObsidianCommError, define_settings, _handle_cli_args ) # --- Event Check --- event_name_from_env = os.environ.get("OBSIDIAN_EVENT_NAME") if event_name_from_env: print(f"Event triggered: {event_name_from_env}. Exiting basic example.") sys.exit(0) # --- Settings Definition & Discovery Handling (Recommended) --- MY_SETTINGS: list = [] # No settings for this basic example define_settings(MY_SETTINGS) _handle_cli_args() # Handles --get-settings-json and exits if found ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/errors.md Illustrates robust error handling for Obsidian Plugin Python Bridge, including connection errors during initialization and API usage errors like ObsidianCommError and ValueError. ```python from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, ObsidianCommError ) import sys try: # Initialize obsidian = ObsidianPluginDevPythonToJS() except ObsidianCommError as e: print("Cannot connect to Obsidian", file=sys.stderr) print(f"Details: {e}", file=sys.stderr) sys.exit(1) try: # Use API content = obsidian.get_active_note_content() except ObsidianCommError as e: obsidian.show_notification(f"Error: {e.action} failed") print(f"API error: {e}", file=sys.stderr) sys.exit(1) except ValueError as e: print(f"Invalid argument: {e}", file=sys.stderr) sys.exit(1) ``` -------------------------------- ### Recommended Script Structure Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/README.md Provides a template for structuring Python scripts that interact with the Obsidian plugin. It includes setup for settings, event handling, and main script logic with error handling. ```python import os import sys from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, ObsidianCommError, define_settings, _handle_cli_args, is_handling_event, get_event_name, get_event_payload, ) # --- 1. Settings Definition --- MY_SETTINGS = [ # Define user-configurable settings here ] define_settings(MY_SETTINGS) # --- 2. Settings Discovery (MUST come early) --- _handle_cli_args() # --- 3. Event Detection (if script handles events) --- if is_handling_event(): obsidian = ObsidianPluginDevPythonToJS() event_name = get_event_name() # Handle event... sys.exit(0) # --- 4. Main Script Logic --- if __name__ == "__main__": try: obsidian = ObsidianPluginDevPythonToJS() # Get user settings settings = obsidian.get_script_settings() # Perform operations content = obsidian.get_active_note_content() # Show result obsidian.show_notification("Done!") except ObsidianCommError as e: print(f"Obsidian error: {e}", file=sys.stderr) sys.exit(1) except Exception as e: print(f"Script error: {e}", file=sys.stderr) sys.exit(1) ``` -------------------------------- ### Get Editor Context Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/types.md Retrieves and prints the cursor position and line count from the editor context. Requires a valid editor context. ```python context = obsidian.get_editor_context() if context: line = context["cursor"]["line"] ch = context["cursor"]["ch"] print(f"Cursor at line {line}, char {ch}") ``` -------------------------------- ### Get Active Note Frontmatter Example Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/types.md Retrieves and accesses frontmatter data from the currently active note. Handles cases where frontmatter might be missing or empty. ```python frontmatter = obsidian.get_active_note_frontmatter() if frontmatter: title = frontmatter.get("title", "Untitled") tags = frontmatter.get("tags", []) status = frontmatter.get("status") ``` -------------------------------- ### Client Constructor Parameters Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/README.md Shows how to instantiate the `ObsidianPluginDevPythonToJS` client with custom timeouts for connection and API requests. Defaults are used if not specified. ```python ObsidianPluginDevPythonToJS( http_port=27123, # HTTP port (default from env) connect_timeout=2.0, # Connection test timeout request_timeout=10.0 # API request timeout ) ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md Change the current directory to the cloned plugin repository. ```bash cd obsidian-plugin-python-bridge/ ``` -------------------------------- ### Handle Missing PyYAML Error Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/errors.md Catch NameError when PyYAML is not installed, which is required for frontmatter management. Provides instructions to install PyYAML. ```python try: result = obsidian.manage_properties_key(path, "add", "key") except NameError as e: print("PyYAML is required") print("Install with: pip install PyYAML") ``` -------------------------------- ### Importing Library Helper Functions Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md Demonstrates how to import helper functions like `define_settings` and `_handle_cli_args` from the `obsidian_python_bridge` package or the backward-compatible shim. ```python from obsidian_python_bridge import define_settings, _handle_cli_args # or from ObsidianPluginDevPythonToJS import define_settings, _handle_cli_args ``` -------------------------------- ### Toggle (Boolean) Setting Definition Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Example of a setting definition for a boolean toggle switch. ```json { "key": "enabled", "type": "toggle", "label": "Enable Feature", "default": true } ``` -------------------------------- ### Build the Project Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/README.md Compile the project's TypeScript code into JavaScript. Use 'bun run dev' for automatic rebuilding on changes. ```bash bun run build ``` -------------------------------- ### Text Input Setting Definition Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Example of a setting definition for a single-line text input field. ```json { "key": "username", "type": "text", "label": "Username", "default": "user", "description": "Your login username" } ``` -------------------------------- ### Initializing Obsidian Plugin Client Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md Instantiates the `ObsidianPluginDevPythonToJS` class to create a client for interacting with the Obsidian plugin. ```python obsidian = ObsidianPluginDevPythonToJS() ``` -------------------------------- ### Get All Tags Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/vault.md Retrieves a list of all unique tags present in the Obsidian vault. Tags are returned with the '#' prefix. ```python obsidian = ObsidianPluginDevPythonToJS() tags = obsidian.get_all_tags() print(f"All tags: {tags}") ``` -------------------------------- ### Python Script with Event Check and Settings Handling Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md This script demonstrates how to check for environment variables to trigger events, define settings for user configuration, and handle command-line arguments for settings discovery. It includes the main script logic that initializes the Obsidian plugin, retrieves settings, and displays notifications. ```python import os import sys from obsidian_python_bridge import ObsidianPluginDevPythonToJS, ObsidianCommError, define_settings, _handle_cli_args # --- Event Check (Recommended) --- event_name_from_env = os.environ.get("OBSIDIAN_EVENT_NAME") if event_name_from_env: print(f"Event triggered: {event_name_from_env}. Exiting settings example.") sys.exit(0) # --- Settings Definition & Discovery Handling (Recommended) --- # 1. Define Settings MY_SCRIPT_SETTINGS = [ {"key": "api_key", "type": "text", "label": "Your API Key", "default": "", "description": "Enter the API key for the service."}, {"key": "enable_feature_x", "type": "toggle", "label": "Enable Feature X", "default": True, "description": "Toggle Feature X on or off."} ] define_settings(MY_SCRIPT_SETTINGS) # 2. Handle Settings Discovery (MUST be called after define_settings) _handle_cli_args() # This will exit if --get-settings-json is passed # --- Main Script Logic (only runs if not discovery and not event) --- if __name__ == "__main__": print("--- Configurable script running ---") try: # 3. Initialize Client obsidian = ObsidianPluginDevPythonToJS() # 4. Get User-Configured Values settings = obsidian.get_script_settings() api_key = settings.get("api_key", MY_SCRIPT_SETTINGS[0]["default"]) # Use default from definition if not found feature_x_enabled = settings.get("enable_feature_x", MY_SCRIPT_SETTINGS[1]["default"]) obsidian.show_notification(f"API Key: '{api_key}', Feature X: {feature_x_enabled}") if feature_x_enabled: print("Feature X is enabled and running...") else: print("Feature X is disabled.") except ObsidianCommError as e: print(f"Error: {e}", file=sys.stderr) except Exception as e: print(f"Unexpected Python error: {e}", file=sys.stderr) ``` -------------------------------- ### Initialize Client Before Retrieving Settings Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Ensure the ObsidianPluginDevPythonToJS client is initialized before calling get_script_settings(). This is crucial for establishing the connection and accessing configuration values. ```python # Initialize client obsidian = ObsidianPluginDevPythonToJS() # Retrieve user-configured settings settings = obsidian.get_script_settings() ``` -------------------------------- ### Project File Structure Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/INDEX.md Overview of the project's directory and file organization. ```tree output/ ├── README.md (Master index) ├── INDEX.md (This file) ├── settings-system.md (Settings guide) ├── configuration.md (Config options) ├── types.md (Type definitions) ├── errors.md (Error reference) └── api-reference/ ├── client.md (Main class) ├── notes.md (Note ops) ├── vault.md (Vault ops) ├── editor.md (Editor ops) ├── ui.md (UI/modals) ├── events.md (Events) ├── frontmatter.md (Frontmatter) └── links.md (Links/backlinks) ``` -------------------------------- ### Get Active Note Title Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Extract the title (filename without the .md extension) of the currently active note. ```python obsidian = ObsidianPluginDevPythonToJS() title = obsidian.get_active_note_title() print(f"Note title: {title}") ``` -------------------------------- ### Get Active Note Relative Path Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Retrieve the path of the active note relative to the root of the Obsidian vault. ```python obsidian = ObsidianPluginDevPythonToJS() rel_path = obsidian.get_active_note_relative_path() print(f"Relative path: {rel_path}") ``` -------------------------------- ### Script with Settings Configuration Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/INDEX.md Demonstrates how to define and access script settings. This pattern is useful for creating configurable scripts that can be customized by the user through the Obsidian interface. ```python MY_SETTINGS = [ {"key": "option", "type": "toggle", "label": "Option", "default": True} ] define_settings(MY_SETTINGS) _handle_cli_args() if __name__ == "__main__": obsidian = ObsidianPluginDevPythonToJS() settings = obsidian.get_script_settings() option = settings.get("option", True) ``` -------------------------------- ### Get Active Note Absolute Path Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Obtain the full, absolute filesystem path of the currently active note. ```python obsidian = ObsidianPluginDevPythonToJS() abs_path = obsidian.get_active_note_absolute_path() print(f"Absolute path: {abs_path}") ``` -------------------------------- ### Initialize ObsidianPluginDevPythonToJS Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md Instantiate the ObsidianPluginDevPythonToJS class, typically within the main execution block. It's recommended to handle potential `ObsidianCommError` during initialization. ```python if __name__ == "__main__" and not os.environ.get("OBSIDIAN_EVENT_NAME"): try: obsidian = ObsidianPluginDevPythonToJS(http_port=None, connect_timeout=2.0, request_timeout=10.0) # ... rest of your script ... except ObsidianCommError as e: print(f"Error: {e}", file=sys.stderr) ``` -------------------------------- ### Get Selected Text Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/editor.md Retrieves the currently selected text in the editor. Returns an empty string if no text is selected. ```python obsidian = ObsidianPluginDevPythonToJS() selected = obsidian.get_selected_text() if selected: print(f"Selected: {selected}") else: print("No text selected") ``` -------------------------------- ### _handle_cli_args Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md Checks for the `--get-settings-json` argument. If present, it prints the settings JSON (defined by `define_settings`) to stdout and exits the script. This must be called immediately after `define_settings()` and before main script logic or `ObsidianPluginDevPythonToJS` initialization. ```APIDOC ## _handle_cli_args() -> None ### Description Checks for `--get-settings-json` argument. If present, prints settings JSON (defined by `define_settings`) to stdout and exits the script using `sys.exit(0)`. Must be called immediately after `define_settings()` and before main script logic or `ObsidianPluginDevPythonToJS` initialization. This function is essential for settings discovery by the plugin. ### Parameters None ### Returns `None` (or exits the script) ``` -------------------------------- ### Number Input Setting Definition Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Example of a setting definition for a numeric input field with range and step constraints. ```json { "key": "timeout", "type": "number", "label": "Timeout (seconds)", "min": 1, "max": 300, "step": 5, "default": 30 } ``` -------------------------------- ### Define and Get Script Settings Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/README.md Define custom settings for your script and retrieve them after they have been processed. This allows for user-configurable script parameters. ```python from ObsidianPluginDevPythonToJS import define_settings, _handle_cli_args MY_SETTINGS = [ {"key": "api_key", "type": "text", "label": "API Key", "default": ""} ] define_settings(MY_SETTINGS) _handle_cli_args() obsidian = ObsidianPluginDevPythonToJS() settings = obsidian.get_script_settings() api_key = settings.get("api_key") ``` -------------------------------- ### Get Theme Mode Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/vault.md Retrieves the current theme mode of Obsidian, which can be either 'light' or 'dark'. Useful for UI adjustments. ```python obsidian = ObsidianPluginDevPythonToJS() theme = obsidian.get_theme_mode() print(f"Current theme: {theme}") ``` -------------------------------- ### Get Obsidian Language Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/vault.md Retrieves the language code configured within Obsidian settings. This can be used for localization or conditional logic. ```python obsidian = ObsidianPluginDevPythonToJS() lang = obsidian.get_obsidian_language() print(f"Obsidian language: {lang}") ``` -------------------------------- ### Recovering from Connection Errors Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/errors.md Shows how to handle ObsidianCommError during initialization if the Obsidian plugin server is unreachable. This is useful for checking if Obsidian is running and the plugin is enabled. ```python from ObsidianPluginDevPythonToJS import ObsidianCommError try: obsidian = ObsidianPluginDevPythonToJS() except ObsidianCommError as e: print("Obsidian is not running or plugin is disabled") print("Please start Obsidian and enable the Python Bridge plugin") exit(1) ``` -------------------------------- ### Get Active Note Frontmatter Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Retrieve the parsed YAML frontmatter from the active note. Returns None if no frontmatter is present. ```python obsidian = ObsidianPluginDevPythonToJS() frontmatter = obsidian.get_active_note_frontmatter() if frontmatter: tags = frontmatter.get("tags", []) title = frontmatter.get("title", "Untitled") print(f"Title: {title}, Tags: {tags}") ``` -------------------------------- ### Retrieve Script Settings Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Initializes the Obsidian client and retrieves all user-configured settings. Use the .get() method to access individual settings, providing a default value if the setting might be absent. ```python from ObsidianPluginDevPythonToJS import ObsidianPluginDevPythonToJS obsidian = ObsidianPluginDevPythonToJS() settings = obsidian.get_script_settings() api_key = settings.get("api_key") timeout = settings.get("timeout", 30) # Default to 30 if not set ``` -------------------------------- ### Get Vault Name Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/vault.md Retrieves the name of the currently open Obsidian vault. This is typically the name of the folder containing the vault. ```python obsidian = ObsidianPluginDevPythonToJS() vault_name = obsidian.get_vault_name() print(f"Vault name: {vault_name}") ``` -------------------------------- ### Handle Empty Settings Dictionary Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md Provide a fallback to an empty dictionary if `get_script_settings()` returns an empty dictionary, indicating no settings are configured or the script is not run via the plugin. ```python settings = obsidian.get_script_settings() if not settings: print("No settings configured, using defaults") settings = {} ``` -------------------------------- ### get_backlinks() Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/links.md Retrieves backlinks (incoming links) for a specified note. It can optionally utilize a cache for improved performance if the 'obsidian-backlink-cache' plugin is installed. ```APIDOC ## get_backlinks() ### Description Retrieve backlinks (incoming links) for a note. Can optionally use a cache for performance improvements. ### Method ```python def get_backlinks( self, path: str, use_cache_if_available: bool = True, cache_mode: str = "fast", ) -> dict[str, list[dict[str, Any]]] ``` ### Parameters #### Path Parameters - **path** (str) - Required - Vault-relative path of the note (without `.md` extension). #### Query Parameters - **use_cache_if_available** (bool) - Optional - Attempt to use the `obsidian-backlink-cache` plugin if installed for better performance. Defaults to `True`. - **cache_mode** (str) - Optional - Cache query mode: `"fast"` (prioritize speed) or `"safe"` (prioritize accuracy). Defaults to `"fast"`. ### Returns - `dict[str, list[dict[str, Any]]]` — A dict mapping absolute source-note paths to lists of link info dicts. Empty dict if no backlinks exist. Each link info dict may contain: - `path` — The linking note's path - `displayText` — The text of the link - `position` — Position information (line, column) if available ### Raises - `ValueError` — If path is empty or cache_mode is invalid. - `ObsidianCommError` — If the request fails. ### Example ```python from ObsidianPluginDevPythonToJS import ObsidianPluginDevPythonToJS obsidian = ObsidianPluginDevPythonToJS() # Get backlinks to current note backlinks = obsidian.get_backlinks("target-note", use_cache_if_available=True) # Iterate through source notes for source_path, links in backlinks.items(): print(f"\n{source_path} links to target-note:") for link_info in links: display = link_info.get("displayText", "") print(f" - {display}") ``` ``` -------------------------------- ### Get Active Note Content Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/README.md Retrieve the content of the currently active note in Obsidian. Specify the desired return format, such as 'string'. ```python obsidian = ObsidianPluginDevPythonToJS() content = obsidian.get_active_note_content(return_format="string") ``` -------------------------------- ### Define Empty Settings List Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/settings-system.md It is good practice to always define a settings list, even if it's empty, to ensure reliable discovery and prevent potential failures. ```python # Good practice - works reliably MY_SETTINGS = [] define_settings(MY_SETTINGS) _handle_cli_args() # Without this structure, discovery may fail ``` -------------------------------- ### Request User Input - Date Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/ui.md Opens a modal for date selection. The returned value is a string in ISO format. ```python obsidian = ObsidianPluginDevPythonToJS() # Date input deadline = obsidian.request_user_input( script_name="Set Deadline", input_type="date", message="Select a deadline date" ) print(f"Deadline: {deadline}") # ISO format: "2024-12-31" ``` -------------------------------- ### Get Note Frontmatter Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Retrieves the parsed YAML frontmatter from a note specified by its vault-relative path. Returns None if no valid frontmatter exists. ```python obsidian = ObsidianPluginDevPythonToJS() frontmatter = obsidian.get_note_frontmatter("folder/my-note") ``` -------------------------------- ### Get All Note Paths (Absolute) Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Retrieves the absolute filesystem paths for all Markdown notes in the vault. Useful for direct file system operations. ```python abs_paths = obsidian.get_all_note_paths(absolute=True) for path in abs_paths: print(path) ``` -------------------------------- ### Import client library symbols (legacy shim) Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md Import symbols from the legacy shim file. This method works with all existing scripts. ```python from ObsidianPluginDevPythonToJS import ( ObsidianPluginDevPythonToJS, ObsidianCommError, define_settings, _handle_cli_args, ) ``` -------------------------------- ### Get Obsidian Event Name Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/events.md Retrieve the name of the Obsidian event that triggered the current script execution. Returns None if the script was not event-triggered. ```python from obsidian_python_bridge import get_event_name event = get_event_name() if event: print(f"Event triggered: {event}") ``` -------------------------------- ### Initialize Obsidian Python Bridge Client Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/README.md Instantiate the main client class for interacting with Obsidian. This is the primary entry point for all operations. ```python from ObsidianPluginDevPythonToJS import ObsidianPluginDevPythonToJS obsidian = ObsidianPluginDevPythonToJS() ``` -------------------------------- ### Validate User Input for Filename Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md Always validate user input from modals to prevent security vulnerabilities. This example checks if the input is alphanumeric. ```python # Always validate user input from modals user_input = obsidian.request_user_input("My Script", "text", "Enter filename:") if not user_input or not user_input.isalnum(): obsidian.show_notification("Invalid filename!", duration=3000) return ``` -------------------------------- ### Defining Script Settings Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md Shows the structure for defining script settings, including key, type, label, default value, and description for each setting. ```python MY_SCRIPT_SETTINGS = [ {"key": "api_key", "type": "text", "label": "Your API Key", "default": "", "description": "Enter the API key for the service."}, {"key": "enable_feature_x", "type": "toggle", "label": "Enable Feature X", "default": True, "description": "Toggle Feature X on or off."} ] define_settings(MY_SCRIPT_SETTINGS) ``` -------------------------------- ### Get All Note Titles Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/api-reference/notes.md Retrieves a list of all note titles (filenames without extensions) in the Obsidian vault. Use this when you need a list of note names. ```python obsidian = ObsidianPluginDevPythonToJS() titles = obsidian.get_all_note_titles() print(f"Note titles: {titles}") ``` -------------------------------- ### Create a New Note Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/_autodocs/README.md Create a new note file within the Obsidian vault. Specify the desired path and initial content for the new note. ```python obsidian.create_note("folder/new-note.md", "Initial content") ``` -------------------------------- ### Handling Command-Line Arguments for Settings Discovery Source: https://github.com/mathe00/obsidian-plugin-python-bridge/blob/main/docs/PYTHON_LIBRARY_DOCS.md This function checks for the `--get-settings-json` argument, prints settings JSON to stdout, and exits the script. It must be called immediately after `define_settings`. ```python _handle_cli_args() ```