### Build StackEdit Project Dependencies and Serve Locally Source: https://github.com/benweet/stackedit/blob/master/README.md These commands are used to install project dependencies and start a development server with hot reloading. They are essential for local development and testing. ```bash npm install npm start ``` -------------------------------- ### Install StackEdit from Source (Bash) Source: https://github.com/benweet/stackedit/wiki/Install-Debian-8-[deprecated] Clones the StackEdit repository from GitHub into the /opt directory, navigates into the directory, and installs the project's dependencies using npm and Bower. This step fetches and prepares the StackEdit application code. ```bash cd /opt sudo git clone https://github.com/benweet/stackedit.git stackedit cd stackedit sudo npm install sudo bower install --allow-root ``` -------------------------------- ### User Contributed Examples Source: https://github.com/benweet/stackedit/wiki/_Sidebar Links to user-contributed examples and extensions for StackEdit. ```APIDOC ## User Contributed Examples ### Description Provides links to user-contributed examples and extensions. ### Endpoints - /templates - /userCustom extensions - /web utilities - /install On Debian 8 ``` -------------------------------- ### Deploy StackEdit using Helm - Initial Installation Source: https://github.com/benweet/stackedit/blob/master/README.md This section details the initial deployment of StackEdit to a Kubernetes cluster using Helm. It includes adding the Helm repository, updating the cache, and installing the chart with various service configurations. ```bash helm repo add stackedit https://benweet.github.io/stackedit-charts/ helm repo update helm install --name stackedit stackedit/stackedit \ --set dropboxAppKey=$DROPBOX_API_KEY \ --set dropboxAppKeyFull=$DROPBOX_FULL_ACCESS_API_KEY \ --set googleClientId=$GOOGLE_CLIENT_ID \ --set googleApiKey=$GOOGLE_API_KEY \ --set githubClientId=$GITHUB_CLIENT_ID \ --set githubClientSecret=$GITHUB_CLIENT_SECRET \ --set wordpressClientId="$WORDPRESS_CLIENT_ID" \ --set wordpressSecret=$WORDPRESS_CLIENT_SECRET ``` -------------------------------- ### Enable and Start StackEdit Service (Bash) Source: https://github.com/benweet/stackedit/wiki/Install-Debian-8-[deprecated] Enables the StackEdit systemd service to start automatically on boot, reloads the systemd daemon to recognize the new service, and then starts the StackEdit service. This command sequence ensures StackEdit is running and persistent. ```bash sudo systemctl enable stackedit.service sudo systemctl daemon-reload sudo systemctl start stackedit.service ``` -------------------------------- ### Server API Endpoints (Bash) Source: https://context7.com/benweet/stackedit/llms.txt Provides examples of interacting with the StackEdit server API using cURL. It demonstrates how to fetch server configuration, which includes settings like sponsorship enablement and GitHub client IDs. This is useful for understanding the server's capabilities and obtaining necessary configuration details. ```bash # Get server configuration curl https://stackedit.io/conf # Response: { "allowSponsorship": true, "githubClientId": "...", ... } ``` -------------------------------- ### Create StackEdit Systemd Service File (Systemd Unit) Source: https://github.com/benweet/stackedit/wiki/Install-Debian-8-[deprecated] Defines a systemd service unit for StackEdit. This configuration file specifies how to start the StackEdit daemon, including the command to run and restart policies. It ensures StackEdit runs as a background service. ```systemd [Unit] Description=Stackedit daemon [Service] ExecStart=/usr/bin/nodejs /opt/stackedit/server.js Restart=always [Install] WantedBy=multi-user.target ``` -------------------------------- ### Update Package List and Install Dependencies (Bash) Source: https://github.com/benweet/stackedit/wiki/Install-Debian-8-[deprecated] Updates the APT package list and installs essential dependencies such as Git and Node.js. This is a prerequisite for installing StackEdit and its build tools. ```bash sudo apt-get update sudo apt-get install git nodejs ``` -------------------------------- ### Extending Markdown Converter and Preview Source: https://context7.com/benweet/stackedit/llms.txt Provides examples for using extensionSvc hooks to modify converter options, initialize markdown-it plugins, and post-process preview elements for custom rendering. ```javascript import extensionSvc from './services/extensionSvc'; extensionSvc.onGetOptions((options, properties) => { options.customFeature = properties.extensions?.customFeature?.enabled ?? false; }); extensionSvc.onInitConverter(50, (markdown, options) => { if (options.customFeature) { markdown.use(customPlugin); } }); extensionSvc.onSectionPreview((element) => { element.querySelectorAll('.custom-block').forEach((block) => { block.classList.add('processed'); }); }); ``` -------------------------------- ### Update npm and Install Global Packages (Bash) Source: https://github.com/benweet/stackedit/wiki/Install-Debian-8-[deprecated] Updates the Node Package Manager (npm) to the latest version and installs Gulp and Bower globally. These are build automation and front-end package management tools required by StackEdit. ```bash sudo npm install npm -g sudo npm install --global gulp sudo npm install --global bower ``` -------------------------------- ### Get Stackedit Application URL (Kubernetes) Source: https://github.com/benweet/stackedit/blob/master/chart/templates/NOTES.txt This snippet provides commands to retrieve the application URL for Stackedit based on the configured Kubernetes service type. It handles Ingress, NodePort, LoadBalancer, and ClusterIP configurations, outputting the correct URL or instructions to access the application. ```bash {{- if .Values.ingress.enabled }} {{- range $host := .Values.ingress.hosts }} {{- range .paths }} http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ . }} {{- end }} {{- end }} {{- else if contains "NodePort" .Values.service.type }} export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "stackedit.fullname" . }}) export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT {{- else if contains "LoadBalancer" .Values.service.type }} NOTE: It may take a few minutes for the LoadBalancer IP to be available. You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "stackedit.fullname" . }}' export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "stackedit.fullname" . }} -o jsonpath='{.status.loadBalancer.ingress[0].ip}') echo http://$SERVICE_IP:{{ .Values.service.port }} {{- else if contains "ClusterIP" .Values.service.type }} export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "stackedit.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}") echo "Visit http://127.0.0.1:8080 to use your application" kubectl port-forward $POD_NAME 8080:80 {{- end }} ``` -------------------------------- ### Get User Information with StackEdit API Source: https://context7.com/benweet/stackedit/llms.txt This code demonstrates how to retrieve user information, such as username and sponsor expiration date, from the StackEdit API. It requires authentication using a Bearer token. The response is a JSON object containing user details. ```shell curl https://stackedit.io/userInfo \ -H "Authorization: Bearer YOUR_TOKEN" ``` -------------------------------- ### Managing File Synchronization with Sync Service Source: https://context7.com/benweet/stackedit/llms.txt Explains how to initialize the sync service, trigger manual synchronization, and configure sync locations for various providers like GitHub, Google Drive, and Dropbox. ```javascript import syncSvc from './services/syncSvc'; await syncSvc.init(); if (syncSvc.isSyncPossible()) { syncSvc.requestSync(true); } const syncLocation = { providerId: 'github', owner: 'username', repo: 'my-notes', branch: 'main', path: 'docs/my-document.md' }; syncSvc.createSyncLocation(syncLocation); ``` -------------------------------- ### Deploy StackEdit using Helm - With Custom Ingress and Cert-Manager Source: https://github.com/benweet/stackedit/blob/master/README.md This command demonstrates deploying StackEdit with custom ingress controller and cert-manager configurations. It allows for advanced network and TLS management, including specifying hosts, paths, and TLS secrets. ```bash helm install --name stackedit stackedit/stackedit \ --set dropboxAppKey=$DROPBOX_API_KEY \ --set dropboxAppKeyFull=$DROPBOX_FULL_ACCESS_API_KEY \ --set googleClientId=$GOOGLE_CLIENT_ID \ --set googleApiKey=$GOOGLE_API_KEY \ --set githubClientId=$GITHUB_CLIENT_ID \ --set githubClientSecret=$GITHUB_CLIENT_SECRET \ --set wordpressClientId="$WORDPRESS_CLIENT_ID" \ --set wordpressSecret=$WORDPRESS_CLIENT_SECRET \ --set ingress.enabled=true \ --set ingress.annotations."kubernetes.io/ingress.class"=nginx \ --set ingress.annotations."cert-manager.io/cluster-issuer"=letsencrypt-prod \ --set ingress.hosts[0].host=stackedit.example.com \ --set ingress.hosts[0].paths[0]=/ \ --set ingress.tls[0].secretName=stackedit-tls \ --set ingress.tls[0].hosts[0]=stackedit.example.com ``` -------------------------------- ### GET /userInfo Source: https://context7.com/benweet/stackedit/llms.txt Retrieves information about the currently authenticated user. ```APIDOC ## GET /userInfo ### Description Fetches profile details for the user associated with the provided Bearer token. ### Method GET ### Endpoint /userInfo ### Parameters #### Headers - **Authorization** (string) - Required - Bearer ### Response #### Success Response (200) - **name** (string) - The user's display name. - **sponsorExpires** (integer) - Timestamp for when the sponsorship expires. ### Response Example { "name": "username", "sponsorExpires": 1234567890 } ``` -------------------------------- ### GET /oauth2/githubToken Source: https://context7.com/benweet/stackedit/llms.txt Exchanges a GitHub OAuth code for an access token. ```APIDOC ## GET /oauth2/githubToken ### Description Exchanges a temporary GitHub authorization code for a permanent access token. ### Method GET ### Endpoint /oauth2/githubToken ### Parameters #### Query Parameters - **clientId** (string) - Required - The unique identifier for your GitHub OAuth application. - **code** (string) - Required - The authorization code received from the GitHub OAuth flow. ### Response #### Success Response (200) - **token** (string) - The GitHub access token. ### Response Example "github_access_token_here" ``` -------------------------------- ### Build StackEdit for Production Source: https://github.com/benweet/stackedit/blob/master/README.md Commands to build the StackEdit project for production, including minification and an optional bundle analyzer report. These are used for deploying a production-ready version. ```bash npm run build npm run build --report ``` -------------------------------- ### Vuex Store Usage for State Management (JavaScript) Source: https://context7.com/benweet/stackedit/llms.txt Illustrates how to interact with the application's Vuex store for managing state across different modules like files, content, and workspaces. It shows how to access getters for retrieving state, dispatch actions for performing operations, and commit mutations for direct state changes. This pattern centralizes application state, making it predictable and easier to manage. ```javascript import store from './store'; // Access file state const currentFile = store.getters['file/current']; console.log('Current file:', currentFile.name, currentFile.id); const allFiles = store.getters['file/items']; allFiles.forEach(file => { console.log(`${file.name} (${file.parentId || 'root'})`); }); // Access content state const currentContent = store.getters['content/current']; console.log('Content text:', currentContent.text); console.log('Properties:', currentContent.properties); console.log('Discussions:', Object.keys(currentContent.discussions).length); // Workspace management const currentWorkspace = store.getters['workspace/currentWorkspace']; console.log('Workspace:', currentWorkspace.id, currentWorkspace.name); const syncToken = store.getters['workspace/syncToken']; if (syncToken) { console.log('Sync enabled with:', syncToken.providerId); } // Settings and configuration const settings = store.getters['data/computedSettings']; console.log('Editor settings:', settings.editor); console.log('Sync interval:', settings.autoSyncEvery); // Show notifications store.dispatch('notification/info', 'File saved successfully!'); store.dispatch('notification/error', new Error('Sync failed')); // Open modals store.dispatch('modal/open', { type: 'settings' }); store.dispatch('modal/open', { type: 'link', callback: (url) => { console.log('Link selected:', url); }}); // Queue operations (for sequential execution) store.dispatch('queue/enqueue', async () => { await performOperation1(); await performOperation2(); }); // Mutation examples store.commit('file/setCurrentId', 'file123'); store.commit('content/patchItem', { id: 'file123/content', text: 'Updated content' }); store.commit('layout/setCanUndo', true); store.commit('setOffline', false); // Watch for state changes store.watch( () => store.getters['content/currentChangeTrigger'], () => { console.log('Content changed, update editor'); } ); ``` -------------------------------- ### Deploy StackEdit using Helm - Upgrade Source: https://github.com/benweet/stackedit/blob/master/README.md Instructions for upgrading an existing StackEdit deployment to the latest version using Helm. This ensures that the application is kept up-to-date with the latest features and bug fixes. ```bash helm repo update helm upgrade stackedit stackedit/stackedit ``` -------------------------------- ### Add Custom Keyboard Shortcuts in Ace Editor Source: https://github.com/benweet/stackedit/wiki/userCustom.onAceCreated This snippet demonstrates how to add custom keyboard shortcuts to the Ace Editor instance within StackEdit. It binds 'Ctrl+A' to navigate to the start of the line and 'Ctrl+E' to navigate to the end of the line. ```javascript userCustom.onAceCreated = function(aceEditor) { aceEditor.commands.addCommand({ name: 'customlinestart', bindKey: "Ctrl-A", exec: function(editor) { editor.navigateLineStart(); }, }); aceEditor.commands.addCommand({ name: 'customlineend', bindKey: "Ctrl-E", exec: function(editor) { editor.navigateLineEnd(); }, }); }; ``` -------------------------------- ### Custom User Ready Functionality in JavaScript Source: https://github.com/benweet/stackedit/wiki/UserCustom.globalSearch This function defines custom behavior to be executed when the user interface is ready. It checks the current location path and calls other initialization functions if the path is not '/viewer'. ```javascript userCustom.onReady = function() { if( location.pathname === '/viewer' ) return; B5F_SearchContent.onReady(); } ``` -------------------------------- ### Cledit Editor Initialization and Usage (JavaScript) Source: https://context7.com/benweet/stackedit/llms.txt Demonstrates how to create and initialize the Cledit editor, a contenteditable-based editor with syntax highlighting and undo/redo capabilities. It covers setting content, managing selections, performing undo/redo operations, adding custom keystrokes, and toggling the editable state. Dependencies include Prism for syntax highlighting and custom services for markdown conversion. ```javascript import cledit from './services/editor/cledit'; // Create an editor instance const contentElt = document.getElementById('editor-content'); const scrollElt = document.getElementById('editor-scroll'); const editor = cledit(contentElt, scrollElt, true); // true = markdown mode // Initialize with options editor.init({ content: '# Hello World\n\nStart typing...', selectionStart: 0, selectionEnd: 0, scrollTop: 0, // Custom section highlighter (uses Prism) sectionHighlighter(section) { return Prism.highlight(section.text, prismGrammar[section.data]); }, // Custom section parser sectionParser(text) { const parsingCtx = markdownConversionSvc.parseSections(converter, text); return parsingCtx.sections; }, // Cursor focus ratio for scrolling getCursorFocusRatio() { return store.getters['data/layoutSettings'].focusMode ? 1 : 0.15; } }); // Listen for content changes editor.on('contentChanged', (content, diffs, sectionList) => { console.log('New content:', content); console.log('Diff patches:', diffs); console.log('Sections:', sectionList.length); }); // Programmatic text manipulation editor.setContent('# New Content\n\nReplaced text.'); editor.replace(0, 5, '## Modified'); // Replace characters 0-5 editor.replaceAll(/hello/gi, 'world'); // Replace all occurrences // Selection management editor.setSelection(10, 20); // Select characters 10-20 const text = editor.selectionMgr.getSelectedText(); console.log('Selected:', text); // Undo/redo operations if (editor.undoMgr.canUndo()) { editor.undoMgr.undo(); } if (editor.undoMgr.canRedo()) { editor.undoMgr.redo(); } // Add custom keystrokes editor.addKeystroke({ priority: 50, handler(evt, state, editor) { // Handle Ctrl+Shift+K to delete line if (evt.ctrlKey && evt.shiftKey && evt.key === 'K') { const lineStart = state.before.lastIndexOf('\n') + 1; const lineEnd = state.after.indexOf('\n'); state.before = state.before.slice(0, lineStart); state.after = state.after.slice(lineEnd + 1); state.selection = ''; return true; // Handled } return false; // Not handled } }); // Focus and toggle editable state editor.focus(); editor.toggleEditable(false); // Make read-only editor.toggleEditable(true); // Make editable again ``` -------------------------------- ### Initialize and Manage Editor Service API Source: https://context7.com/benweet/stackedit/llms.txt Demonstrates how to initialize the editor service, listen for content and preview updates, and retrieve the Pandoc AST. This service handles Markdown conversion, preview rendering, and editor state synchronization. ```javascript import editorSvc from './services/editorSvc'; // Initialize the editor with DOM elements const editorElt = document.querySelector('.editor'); const previewElt = document.querySelector('.preview'); const tocElt = document.querySelector('.toc'); editorSvc.init(editorElt, previewElt, tocElt); // Listen for content changes editorSvc.$on('conversionCtx', (conversionCtx) => { console.log('Markdown converted:', conversionCtx.text); console.log('HTML sections:', conversionCtx.htmlSectionList); }); // Listen for preview updates editorSvc.$on('previewCtx', (previewCtx) => { console.log('Preview HTML:', previewCtx.html); console.log('Preview text:', previewCtx.text); console.log('Section descriptions:', previewCtx.sectionDescList); }); // Get the Pandoc AST for export const pandocAst = editorSvc.getPandocAst(); console.log('Pandoc AST:', JSON.stringify(pandocAst, null, 2)); ``` -------------------------------- ### GitHub Helper: Repository and Gist Management Source: https://context7.com/benweet/stackedit/llms.txt Provides methods to interact with GitHub's API for file synchronization, gist management, and repository operations. It requires authentication tokens and repository details as input. Outputs include file data, tree structures, and Gist information. ```javascript import githubHelper from './services/providers/helpers/githubHelper'; // Add a GitHub account (triggers OAuth flow) const token = await githubHelper.addAccount(true); // true = full repo access console.log('Authenticated as:', token.name); console.log('User ID:', token.sub); // Get repository tree structure const tree = await githubHelper.getTree({ token, owner: 'benweet', repo: 'stackedit', branch: 'master' }); console.log('Repository files:', tree.map(item => item.path)); // Download a file from repository const fileData = await githubHelper.downloadFile({ token, owner: 'benweet', repo: 'stackedit', branch: 'master', path: 'README.md' }); console.log('File content:', fileData.data); console.log('File SHA:', fileData.sha); // Upload/update a file in repository const uploadResult = await githubHelper.uploadFile({ token, owner: 'username', repo: 'my-notes', branch: 'main', path: 'docs/notes.md', content: '# My Notes\n\nContent here...', sha: fileData.sha // Include SHA for updates, omit for new files }); console.log('Commit SHA:', uploadResult.commit.sha); // Create or update a GitHub Gist const gist = await githubHelper.uploadGist({ token, description: 'My markdown notes', filename: 'notes.md', content: '# Notes\n\nSome content...', isPublic: false, gistId: null // null for new gist, gist ID for updates }); console.log('Gist URL:', gist.html_url); console.log('Gist ID:', gist.id); // Download a gist const gistContent = await githubHelper.downloadGist({ token, gistId: gist.id, filename: 'notes.md' }); console.log('Gist content:', gistContent); ``` -------------------------------- ### Inspect File Publisher and Sync Information in StackEdit Source: https://github.com/benweet/stackedit/wiki/userCustom.onFileOpen This JavaScript code provides functions to inspect file synchronization and publishing details. `onFileOpen` is an event handler that extracts Google Drive IDs, Gist IDs, and WordPress URLs from file descriptions. Helper functions `findPublisher` and `findSync` parse through location data to retrieve specific provider information like file IDs, filenames, or URLs. ```javascript userCustom.onFileOpen = function ( fileDesc, textContent ) { var gdriveId = findSync( fileDesc.syncLocations, 'gdrive' ); var gistId = findPublisher( fileDesc.publishLocations, 'gistId' ); var wpUrl = findPublisher( fileDesc.publishLocations, 'wordpress' ); }; /** * Inspect fileDesc.publishLocations */ function findPublisher( locations, providerId ) { var response = false; for ( var key in locations ) { var obj = locations[key]; if( obj[providerId] ) { // Gist response = new Object(); response.fileid = obj[providerId]; response.filename = obj.filename; } else if( obj['site'].indexOf(providerId) > -1 ) // WordPress response = obj['site'] + '/?p=' + obj['postId']; } return response; } /** * Inspect fileDesc.syncLocations */ function findSync( locations, providerName ) { var return_value = false; for (var key in locations ) { var obj = locations[key]; if( obj['syncIndex'].indexOf(providerName) > -1 && 'gdrive' === providerName ) { return_value = obj['id']; } if( obj['syncIndex'].indexOf(providerName) > -1 && 'dropbox' === providerName ) { return_value = obj['path']; } } return return_value; } ``` -------------------------------- ### Create Preview Button Element in JavaScript Source: https://github.com/benweet/stackedit/wiki/UserCustom.globalSearch This function generates and returns a new HTML element to be used as a preview button. It utilizes a helper function to create the necessary elements and wraps them in a div structure. The output is a DOM element. ```javascript userCustom.onCreatePreviewButton = function() { var elements = B5F_SearchContent.onCreatePreviewButton(); var insert = '
' + elements + '
'; return $(insert).wrap('
').parent()[0]; }; ``` -------------------------------- ### Implement Custom Keyboard Shortcuts with Mousetrap Source: https://github.com/benweet/stackedit/wiki/userCustom.onReady This snippet demonstrates how to hook into the StackEdit onReady event to define custom keyboard triggers. It uses the Mousetrap library to detect key combinations and a helper function to inject specific text snippets into the editor's textarea. ```javascript userCustom.onReady = function() { var $textarea = $('#wmd-input'); function insertSnippet(prefix, selection, suffix, combo) { var value = $textarea.val(); var caretPos = $textarea[0].selectionStart - (combo.length-3)/2 - 1; $textarea.val(value.substring(0, caretPos) + prefix + selection + suffix + value.substring($textarea[0].selectionEnd)); $textarea[0].selectionStart = caretPos+prefix.length; $textarea[0].selectionEnd = $textarea[0].selectionStart+selection.length; } var binders = [{ 'keys': 'e q tab', 'prefix': '$$', 'select': ' ', 'suffix': '$$' }, { 'keys': 'm a tab', 'prefix': '\\begin{pmatrix}\n', 'select': ' 1 & 2 \\\\n 3 & 4', 'suffix': '\n\\end{pmatrix}' }, { 'keys': 'f r tab', 'prefix': '\\frac{', 'select': ' ', 'suffix': '}{}' }, { 'keys': 'i n f tab', 'prefix': '\\infty', 'select': '', 'suffix': '' } ]; binders.forEach(function (ev, id, array) { Mousetrap.bind(ev.keys, function(e,combo) { var prefix = ev.prefix; var selection = ev.select; var suffix = ev.suffix; insertSnippet(prefix, selection, suffix, combo); }); }); }; ``` -------------------------------- ### Export Document using Pandoc with StackEdit API Source: https://context7.com/benweet/stackedit/llms.txt This snippet illustrates exporting content to various formats (e.g., DOCX) using the Pandoc engine via the StackEdit API. It specifies the input format (e.g., markdown), output format, content, and Pandoc options. The exported file is saved locally. ```shell curl -X POST https://stackedit.io/pandocExport \ -H "Content-Type: application/json" \ -d '{ "from": "markdown", "to": "docx", "content": "# Title\n\nSome **markdown** content.", "options": ["--standalone"] }' \ --output document.docx ``` -------------------------------- ### Provider: Content Serialization and Parsing Source: https://context7.com/benweet/stackedit/llms.txt The Provider base class offers static methods for serializing and parsing content, including embedded metadata for discussions, comments, and history tracking. It takes structured content as input and outputs a serialized string, and vice versa. Dependencies include the Provider module. ```javascript import Provider from './services/providers/common/Provider'; // Serialize content with metadata for storage const content = { text: '# My Document\n\nSome content here.', properties: 'title: My Document\nauthor: John Doe', discussions: { 'disc1': { text: 'This is a discussion', start: 0, end: 15 } }, comments: { 'comment1': { text: 'A comment', discussionId: 'disc1', created: Date.now() } }, history: ['hash1', 'hash2'] }; const serialized = Provider.serializeContent(content); console.log('Serialized markdown with embedded data:'); console.log(serialized); // Output: // # My Document // // Some content here. // // Parse serialized content back to structured format const parsed = Provider.parseContent(serialized, 'file123/content'); console.log('Parsed text:', parsed.text); console.log('Properties:', parsed.properties); console.log('Discussions:', parsed.discussions); console.log('Comments:', parsed.comments); console.log('History:', parsed.history); console.log('Content hash:', parsed.hash); ``` -------------------------------- ### HTML Export Template with Syntax Highlighting Source: https://github.com/benweet/stackedit/wiki/Template.Pacini A base HTML template for StackEdit exports. It includes placeholders for document content and integrates MathJax and Google Prettify libraries. ```html <%= documentTitle %> <%= documentHTML %> ``` -------------------------------- ### Markdown Conversion Service Operations Source: https://context7.com/benweet/stackedit/llms.txt Illustrates the usage of the markdownConversionSvc for parsing Markdown into sections and converting them to HTML. It shows how to initialize the service, create custom converters with options, and highlight Markdown content. ```javascript import markdownConversionSvc from './services/markdownConversionSvc'; // Initialize the service with default options markdownConversionSvc.init(); // Create a custom converter with specific options const options = { math: true, // Enable KaTeX math emoji: true, // Enable emoji support abc: false, // Disable ABC notation mermaid: true, // Enable Mermaid diagrams breaks: true, // Convert newlines to
linkify: true, // Auto-convert URLs to links typographer: true // Enable smart quotes }; const converter = markdownConversionSvc.createConverter(options); // Parse markdown into sections const markdown = "\n# Hello World\n\nThis is a paragraph with **bold** and *italic* text.\n\n$$E = mc^2$$\n\n\ ```javascript\nconsole.log('Hello');\n\ ```\n"; const parsingCtx = markdownConversionSvc.parseSections(converter, markdown); console.log('Sections:', parsingCtx.sections); // Convert parsed sections to HTML const conversionCtx = markdownConversionSvc.convert(parsingCtx); console.log('HTML output:', conversionCtx.htmlSectionList.join('\n')); // Highlight arbitrary markdown const highlighted = markdownConversionSvc.highlight(markdown); console.log('Highlighted HTML:', highlighted); ``` -------------------------------- ### Events Documentation Source: https://github.com/benweet/stackedit/wiki/_Sidebar Documentation for various events within StackEdit. ```APIDOC ## Events Documentation ### Description Details various events triggered within StackEdit, categorized for clarity. ### Event Categories #### Core Events - `onReady`: Triggered when the application is ready. #### File Operation Events - `onFileOpen`: Triggered when a file is opened. #### UI Layout Events - `onCreateButton`: Triggered when a button is created. - `onCreatePreviewButton`: Triggered when a preview button is created. #### Pagedown Events - `onPagedownConfigure`: Triggered during Pagedown configuration. - `onPreviewFinished`: Triggered when the preview is finished. #### ACE Events - `onAceCreated`: Triggered when the ACE editor is created. #### Editor Events - `onEditorPopover`: Triggered when an editor popover is shown. #### Comments Events - `onCommentsChanged`: Triggered when comments are changed. ``` -------------------------------- ### Code Block Syntax in Markdown Source: https://github.com/benweet/stackedit/blob/master/src/data/markdownSample.md Demonstrates how to include code blocks in Markdown. Supports basic blocks and syntax highlighting for various languages. ```markdown ``` // A code block var foo = 'bar'; ``` ``` ```markdown ```javascript // An highlighted block var foo = 'bar'; ``` ``` -------------------------------- ### Bookmarklet to Open Current Page in StackEdit Viewer (JavaScript) Source: https://github.com/benweet/stackedit/wiki/Web-utilities This bookmarklet, when clicked, redirects the current browser window to the StackEdit Viewer. It constructs a new URL by prepending 'https://stackedit.io/viewer#!url=' to the current page's URL. This allows users to quickly view and potentially edit the current markdown content within StackEdit. ```javascript javascript:(function(){ window.location.href = 'https://stackedit.io/viewer#!url=' + window.location.href; })() ``` -------------------------------- ### Integrate RefTagger into StackEdit Preview Source: https://github.com/benweet/stackedit/wiki/UserCustom.reftagger This script configures the RefTagger settings, dynamically injects the RefTagger library into the document head, and hooks into the StackEdit preview lifecycle to ensure references are tagged whenever the preview is updated. ```javascript // config window.refTagger = { settings: { noSearchClassNames: ['editor-content', 'navbar'], tagChapters: true } }; // create