Files
cours/.obsidian/plugins/darlal-switcher-plus/main.js
T

3 lines
131 KiB
JavaScript

"use strict";var e,t,s,i,n,a=require("obsidian");!function(e){e[e.None=0]="None",e[e.Full=1]="Full",e[e.FolderOnly=2]="FolderOnly",e[e.FolderWithFilename=3]="FolderWithFilename",e[e.FolderPathFilenameOptional=4]="FolderPathFilenameOptional"}(e||(e={})),function(e){e[e.Standard=1]="Standard",e[e.EditorList=2]="EditorList",e[e.SymbolList=4]="SymbolList",e[e.WorkspaceList=8]="WorkspaceList",e[e.HeadingsList=16]="HeadingsList",e[e.BookmarksList=32]="BookmarksList",e[e.CommandList=64]="CommandList",e[e.RelatedItemsList=128]="RelatedItemsList",e[e.VaultList=256]="VaultList"}(t||(t={})),function(e){e[e.Link=1]="Link",e[e.Embed=2]="Embed",e[e.Tag=4]="Tag",e[e.Heading=8]="Heading",e[e.Callout=16]="Callout",e[e.CanvasNode=32]="CanvasNode",e[e.BaseView=64]="BaseView"}(s||(s={})),function(e){e[e.None=0]="None",e[e.Normal=1]="Normal",e[e.Heading=2]="Heading",e[e.Block=4]="Block"}(i||(i={})),function(e){e.Both="both",e.Inline="inline",e.Frontmatter="frontmatter"}(n||(n={}));const o={};o[s.Link]="🔗",o[s.Embed]="!",o[s.Tag]="#",o[s.Heading]="H";const r={};var l,d,c;r[1]="H₁",r[2]="H₂",r[3]="H₃",r[4]="H₄",r[5]="H₅",r[6]="H₆",function(e){e.EditorList="editorList",e.SymbolList="symbolList",e.WorkspaceList="workspaceList",e.HeadingsList="headingsList",e.Bookmark="bookmark",e.CommandList="commandList",e.RelatedItemsList="relatedItemsList",e.VaultList="vaultList",e.File="file",e.Alias="alias",e.Unresolved="unresolved"}(l||(l={})),function(e){e[e.None=0]="None",e[e.Primary=1]="Primary",e[e.Basename=2]="Basename",e[e.Path=3]="Path"}(d||(d={})),function(e){e.DiskLocation="disk-location",e.Backlink="backlink",e.OutgoingLink="outgoing-link"}(c||(c={}));class h{static getAliases(e){let t=[];return e&&(t=h.getValueForKey(e,/^alias(es)?$/i)),t}static getTags(e){let t=[];return e&&(t=h.getValueForKey(e,/^tags?$/i)),t}static getValueForKey(e,t){const s=[],i=Object.keys(e).find((e=>t.test(e)));if(i){let t=e[i];"string"==typeof t&&(t=t.split(",")),Array.isArray(t)&&t.forEach((e=>{"string"==typeof e&&s.push(e.trim())}))}return s}}function m(e,t,s){let i=!1;return e&&void 0!==e[t]&&(i=!0,void 0!==s&&s!==e[t]&&(i=!1)),i}function u(e){return m(e,"type",l.SymbolList)}function g(e){return m(e,"type",l.HeadingsList)}function p(e){return m(e,"type",l.File)}function f(e){return m(e,"type",l.Alias)}function y(e){return m(e,"type",l.Unresolved)}function b(e){return e&&!(p(t=e)||y(t)||f(t));var t}function S(e){return m(e,"level")}function k(e){return m(e,"tag")}function v(e){return m(e,"type","callout")}function w(e){return m(e,"extension")}function C(e){return m(e,"children")}function I(e,t){return e?.internalPlugins?.getEnabledPluginById(t)}function L(e){const t=function(e,t){return e?.internalPlugins?.getPluginById(t)}(e,"switcher");return t?.instance}function T(e){return I(e,"global-search")}function E(){return Object.values(t).filter((e=>isNaN(Number(e)))).sort()}function F(){return[t.RelatedItemsList,t.SymbolList]}function x(e){let t=null;if(e){const s=a.normalizePath(e),i=s.lastIndexOf("/");t=-1===i?s:s.slice(i+1)}return t}function A(e,t){new a.Notice(`Switcher++: ${e}`),O(e,t)}function O(e,...t){console.error(`Switcher++: ${e}`,...t)}function P(e,...t){console.warn(`Switcher++: ${e}`,...t)}function M(e){e=e??[];const t=[];for(const s of e)try{const e=new RegExp(s);t.push(e)}catch(e){O(`Error creating RegExp from string: ${s}`,e)}return e=>{for(const s of t)if(s.test(e))return!0;return!1}}function B(e){let t=i.None;if(e){const s=e.link.split("|")[0];t=s.includes("#^")?i.Block:s.includes("#")?i.Heading:i.Normal}return t}function R(e,t){return t?.getFileByPath(e)}function H(e){let t=null;if(!e)return t;if(e.isDeferred){const s=e.getViewState()?.state?.file;s&&(t=R(s,e.app?.vault))}else e.view?.file&&(t=e.view.file);return t}function D(e,t,s,i,n){let o=null;if(n=Object.assign({useBasenameAsAlias:!0,useHeadingAsAlias:!0},n),s){let r=W(s),d=null,c=null;switch(s.type){case l.Unresolved:o=N(s.linktext);break;case l.Alias:d=s.alias;break;case l.Bookmark:{const{item:e}=s;"file"===e.type&&e.title&&(d=e.title);break}case l.HeadingsList:{const{heading:e}=s.item;({subpath:c,alias:d}=V(e,n.useHeadingAsAlias));break}case l.SymbolList:{const{item:{symbol:l}}=s;if(S(l))({subpath:c,alias:d}=V(l.heading,n.useHeadingAsAlias));else if(m(l,"link")){o=new RegExp(/^\[(.*?)\]\((.+?)\)/).test(l.original)?l.original:function(e,t,s,i,n,o){const{link:r,displayText:l}=i,{path:d,subpath:c}=a.parseLinktext(r);let h=l,m=null,u=null;m=d?.length?R(d,t):n;m?(!h?.length&&o&&(h=m.basename),u=e.generateMarkdownLink(m,s,c,h)):u=N(d,h);return u}(e,t,i,l,r,n.useBasenameAsAlias)}else r=null;break}case l.RelatedItemsList:{const{item:e}=s;e.unresolvedText&&(o=N(e.unresolvedText));break}}r&&!o&&(!d&&n.useBasenameAsAlias&&(d=r.basename),o=e.generateMarkdownLink(r,i,c,d))}return o}function V(e,t){const s=a.stripHeadingForLink(e);return{subpath:`#${s}`,alias:t?s:null}}function W(e){let t=null;return[l.Alias,l.Bookmark,l.HeadingsList,l.SymbolList,l.RelatedItemsList,l.EditorList,l.File].includes(e?.type)&&(t=e.file),t}function N(e,t){return`[[${e}${t=t?.length?`|${t}`:""}]]`}function K(e,t){return e?.view?.getViewType()===t&&!e.isDeferred}class q{static rootComponent;static getRootComponent(){return this.rootComponent||(this.rootComponent=new a.Component),this.rootComponent}static unload(){this.rootComponent?.unload()}}const j={file:"canvas-node-file",text:"canvas-node-text",link:"canvas-node-link",group:"canvas-node-group"},$={table:"base-view-table",list:"base-view-list",cards:"base-view-cards"},U=[{id:s[s.Heading],mode:t.SymbolList,label:"headings",isActive:!1,isAvailable:!0},{id:s[s.Tag],mode:t.SymbolList,label:"tags",isActive:!1,isAvailable:!0},{id:s[s.Callout],mode:t.SymbolList,label:"callouts",isActive:!1,isAvailable:!0},{id:s[s.Link],mode:t.SymbolList,label:"links",isActive:!1,isAvailable:!0},{id:s[s.Embed],mode:t.SymbolList,label:"embeds",isActive:!1,isAvailable:!0},{id:j.file,mode:t.SymbolList,label:"file cards",isActive:!1,isAvailable:!0},{id:j.text,mode:t.SymbolList,label:"text cards",isActive:!1,isAvailable:!0},{id:j.link,mode:t.SymbolList,label:"link cards",isActive:!1,isAvailable:!0},{id:j.group,mode:t.SymbolList,label:"groups",isActive:!1,isAvailable:!0},{id:$.table,mode:t.SymbolList,label:"table views",isActive:!1,isAvailable:!0},{id:$.list,mode:t.SymbolList,label:"list views",isActive:!1,isAvailable:!0},{id:$.cards,mode:t.SymbolList,label:"card views",isActive:!1,isAvailable:!0}],Q=[{id:c.Backlink,mode:t.RelatedItemsList,label:"backlinks",isActive:!1,isAvailable:!0},{id:c.OutgoingLink,mode:t.RelatedItemsList,label:"outgoing links",isActive:!1,isAvailable:!0},{id:c.DiskLocation,mode:t.RelatedItemsList,label:"disk location",isActive:!1,isAvailable:!0}],G={file:"bookmarks-file",folder:"bookmarks-folder",search:"bookmarks-search",group:"bookmarks-group"},_=[{id:G.file,mode:t.BookmarksList,label:"files",isActive:!1,isAvailable:!0},{id:G.folder,mode:t.BookmarksList,label:"folders",isActive:!1,isAvailable:!0},{id:G.search,mode:t.BookmarksList,label:"searches",isActive:!1,isAvailable:!0}];var z;!function(e){e.Pinned="pinnedCommands",e.Recent="recentCommands"}(z||(z={}));const Z=[{id:z.Pinned,mode:t.CommandList,label:"pinned",isActive:!1,isAvailable:!0},{id:z.Recent,mode:t.CommandList,label:"recent",isActive:!1,isAvailable:!0}];var J;!function(e){e.RecentFiles="recentFilesSearch",e.Bookmarks="bookmarksSearch",e.Filenames="filenamesSearch",e.Headings="headingsSearch",e.ExternalFiles="externalFilesSearch"}(J||(J={}));const Y=[{id:J.RecentFiles,mode:t.HeadingsList,label:"recent files",isActive:!1,isAvailable:!0},{id:J.Bookmarks,mode:t.HeadingsList,label:"bookmarks",isActive:!1,isAvailable:!0},{id:J.Filenames,mode:t.HeadingsList,label:"filenames",isActive:!1,isAvailable:!0},{id:J.Headings,mode:t.HeadingsList,label:"headings",isActive:!1,isAvailable:!0},{id:J.ExternalFiles,mode:t.HeadingsList,label:"external files",isActive:!1,isAvailable:!0}];function X(){const e={};return[U,Q,_,Z,Y].flat().reduce(((e,t)=>(e[t.id]=Object.assign({},t),e)),e),e}const ee=e=>{if("object"==typeof e&&null!==e){if("function"==typeof Object.getPrototypeOf){const t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}return"[object Object]"===Object.prototype.toString.call(e)}return!1},te=(...e)=>e.reduce(((e,t)=>{if(void 0===t)return e;if(Array.isArray(t))throw new TypeError("Arguments provided to ts-deepmerge must be objects, not arrays.");return Object.keys(t).forEach((s=>{["__proto__","constructor","prototype"].includes(s)||(Array.isArray(e[s])&&Array.isArray(t[s])?e[s]=te.options.mergeArrays?te.options.uniqueArrayItems?Array.from(new Set(e[s].concat(t[s]))):[...e[s],...t[s]]:t[s]:ee(e[s])&&ee(t[s])?e[s]=te(e[s],t[s]):!ee(e[s])&&ee(t[s])?e[s]=te(t[s],void 0):e[s]=void 0===t[s]?te.options.allowUndefinedOverrides?t[s]:e[s]:t[s])})),e}),{}),se={allowUndefinedOverrides:!0,mergeArrays:!0,uniqueArrayItems:!0};te.options=se,te.withOptions=(e,...t)=>{te.options=Object.assign(Object.assign({},se),e);const s=te(...t);return te.options=se,s};class ie{plugin;data;static get defaults(){const i={};return i[s.Link]=!0,i[s.Embed]=!0,i[s.Tag]=!0,i[s.Heading]=!0,i[s.Callout]=!0,{version:"2.0.0",onOpenPreferNewTab:!0,alwaysNewTabForSymbols:!1,useActiveTabForSymbolsOnMobile:!1,symbolsInLineOrder:!0,editorListCommand:"edt ",symbolListCommand:"@",symbolListActiveEditorCommand:"$ ",workspaceListCommand:"+",headingsListCommand:"#",bookmarksListCommand:"'",commandListCommand:">",recentCommandDisplayOrder:"desc",maxRecentCommands:25,vaultListCommand:"vault ",relatedItemsListCommand:"~",relatedItemsListActiveEditorCommand:"^ ",shouldSearchHeadings:!0,strictHeadingsOnly:!1,searchAllHeadings:!0,headingsSearchDebounceMilli:250,excludeViewTypes:["empty"],referenceViews:["backlink","localgraph","outgoing-link","outline"],limit:50,includeSidePanelViewTypes:["backlink","image","markdown","pdf"],enabledSymbolTypes:i,selectNearestHeading:!0,excludeFolders:[],excludeLinkSubTypes:0,excludeRelatedFolders:[""],excludeOpenRelatedFiles:!1,excludeObsidianIgnoredFiles:!1,shouldSearchFilenames:!1,shouldSearchBookmarks:!1,shouldSearchRecentFiles:!0,pathDisplayFormat:e.FolderWithFilename,hidePathIfRoot:!0,enabledRelatedItems:Object.values(c),showOptionalIndicatorIcons:!0,isFileExtensionIndicatorsEnabled:!0,excludeFileExtensionIndicators:["md"],overrideStandardModeBehaviors:!0,overrideStandardModeRendering:!0,enabledRibbonCommands:[t[t.HeadingsList],t[t.SymbolList]],fileExtAllowList:["canvas"],matchPriorityAdjustments:{isEnabled:!1,adjustments:{isOpenInEditor:{value:0,label:"Open items"},isBookmarked:{value:0,label:"Bookmarked items"},isRecent:{value:0,label:"Recent items"},isAttachment:{value:0,label:"Attachment file types"},file:{value:0,label:"Filenames"},alias:{value:0,label:"Aliases"},unresolved:{value:0,label:"Unresolved filenames"},h1:{value:0,label:"H₁ headings"}},fileExtAdjustments:{canvas:{value:0,label:"Canvas files"}}},quickFilters:{resetKey:"0",keyList:["1","2","3","4","5","6","7","8","9"],modifiers:["Ctrl","Alt"],facetList:X(),shouldResetActiveFacets:!1,shouldShowFacetInstructions:!0},preserveCommandPaletteLastInput:!1,preserveQuickSwitcherLastInput:!1,shouldCloseModalOnBackspace:!1,maxRecentFileSuggestionsOnInit:25,orderEditorListByAccessTime:!0,insertLinkInEditor:{isEnabled:!0,keymap:{modifiers:["Mod"],key:"i",purpose:"insert in editor"},insertableEditorTypes:["markdown"],useBasenameAsAlias:!0,useHeadingAsAlias:!0},removeDefaultTabBinding:!0,navigationKeys:{nextKeys:[{modifiers:["Ctrl"],key:"n"},{modifiers:["Ctrl"],key:"j"}],prevKeys:[{modifiers:["Ctrl"],key:"p"},{modifiers:["Ctrl"],key:"k"}]},preferredSourceForTitle:"H1",frontmatterTitleProperty:"title",closeWhenEmptyKeys:[{modifiers:null,key:"Backspace"}],navigateToHotkeySelectorKeys:{modifiers:["Ctrl","Shift"],key:"h"},togglePinnedCommandKeys:{modifiers:["Ctrl","Shift"],key:"p"},escapeCmdChar:"!",mobileLauncher:{isEnabled:!1,isMobileButtonEnabled:!0,isEmptyTabButtonEnabled:!0,modeString:t[t.HeadingsList],iconName:"",coreLauncherButtonIconSelector:"span.clickable-icon",coreLauncherButtonSelector:".mobile-navbar-action.mobile-navbar-action-quick-switcher"},allowCreateNewFileInModeNames:[t[t.Standard],t[t.HeadingsList]],showModeTriggerInstructions:!0,renderMarkdownContentInSuggestions:{isEnabled:!1,renderHeadings:!1,renderLinks:!1,renderTags:!1,renderCallouts:!1,toggleContentRenderingKeys:{modifiers:["Shift","Ctrl"],key:"m"}},quickOpen:{isEnabled:!0,modifiers:["Alt"],keyList:["1","2","3","4","5","6","7","8","9"]},openDefaultApp:{isEnabled:!0,openInDefaultAppKeys:{modifiers:["Shift","Ctrl"],key:"o"},excludeFileExtensions:[]},fulltextSearch:{isEnabled:!0,searchKeys:{modifiers:["Mod","Shift"],key:"f"}},openInBackground:{isEnabled:!0,openKeys:[{openType:"tab",hotkey:{modifiers:["Mod","Shift"],key:"t"}},{openType:"vertical",hotkey:null},{openType:"horizontal",hotkey:null},{openType:"window",hotkey:null}]},saveWorkspaceAndSwitchKeys:{modifiers:["Mod","Shift"],key:"s"},showHeadingBreadcrumbs:!0,headingBreadcrumbSeparator:" > ",maxBreadcrumbDepth:0,showHeadingBreadcrumbsInSymbolMode:!1,showTagsInSuggestions:!1,tagSource:n.Both,excludeTagsFromDisplay:[],tagDisplaySeparator:" ",removeHashPrefixFromTags:!1,maxTagsToDisplay:0}}shouldShowAlias;get version(){return this.data.version}set version(e){this.data.version=e}get builtInSystemOptions(){return L(this.plugin.app)?.options}get showAllFileTypes(){return this.builtInSystemOptions?.showAllFileTypes}get showAttachments(){return this.builtInSystemOptions?.showAttachments}get showExistingOnly(){return this.builtInSystemOptions?.showExistingOnly}get onOpenPreferNewTab(){return this.data.onOpenPreferNewTab}set onOpenPreferNewTab(e){this.data.onOpenPreferNewTab=e}get alwaysNewTabForSymbols(){return this.data.alwaysNewTabForSymbols}set alwaysNewTabForSymbols(e){this.data.alwaysNewTabForSymbols=e}get useActiveTabForSymbolsOnMobile(){return this.data.useActiveTabForSymbolsOnMobile}set useActiveTabForSymbolsOnMobile(e){this.data.useActiveTabForSymbolsOnMobile=e}get symbolsInLineOrder(){return this.data.symbolsInLineOrder}set symbolsInLineOrder(e){this.data.symbolsInLineOrder=e}get editorListPlaceholderText(){return ie.defaults.editorListCommand}get editorListCommand(){return this.data.editorListCommand}set editorListCommand(e){this.data.editorListCommand=e}get symbolListPlaceholderText(){return ie.defaults.symbolListCommand}get symbolListCommand(){return this.data.symbolListCommand}set symbolListCommand(e){this.data.symbolListCommand=e}get symbolListActiveEditorCommand(){return this.data.symbolListActiveEditorCommand}set symbolListActiveEditorCommand(e){this.data.symbolListActiveEditorCommand=e}get workspaceListCommand(){return this.data.workspaceListCommand}set workspaceListCommand(e){this.data.workspaceListCommand=e}get workspaceListPlaceholderText(){return ie.defaults.workspaceListCommand}get headingsListCommand(){return this.data.headingsListCommand}set headingsListCommand(e){this.data.headingsListCommand=e}get headingsListPlaceholderText(){return ie.defaults.headingsListCommand}get bookmarksListCommand(){return this.data.bookmarksListCommand}set bookmarksListCommand(e){this.data.bookmarksListCommand=e}get bookmarksListPlaceholderText(){return ie.defaults.bookmarksListCommand}get commandListCommand(){return this.data.commandListCommand}set commandListCommand(e){this.data.commandListCommand=e}get recentCommandDisplayOrder(){return this.data.recentCommandDisplayOrder}set recentCommandDisplayOrder(e){this.data.recentCommandDisplayOrder=e}get maxRecentCommands(){return this.data.maxRecentCommands}set maxRecentCommands(e){this.data.maxRecentCommands=e}get commandListPlaceholderText(){return ie.defaults.commandListCommand}get vaultListCommand(){return this.data.vaultListCommand}set vaultListCommand(e){this.data.vaultListCommand=e}get vaultListPlaceholderText(){return ie.defaults.vaultListCommand}get relatedItemsListCommand(){return this.data.relatedItemsListCommand}set relatedItemsListCommand(e){this.data.relatedItemsListCommand=e}get relatedItemsListPlaceholderText(){return ie.defaults.relatedItemsListCommand}get relatedItemsListActiveEditorCommand(){return this.data.relatedItemsListActiveEditorCommand}set relatedItemsListActiveEditorCommand(e){this.data.relatedItemsListActiveEditorCommand=e}get shouldSearchHeadings(){return this.data.shouldSearchHeadings}set shouldSearchHeadings(e){this.data.shouldSearchHeadings=e}get strictHeadingsOnly(){return this.data.strictHeadingsOnly}set strictHeadingsOnly(e){this.data.strictHeadingsOnly=e}get searchAllHeadings(){return this.data.searchAllHeadings}set searchAllHeadings(e){this.data.searchAllHeadings=e}get headingsSearchDebounceMilli(){return this.data.headingsSearchDebounceMilli}set headingsSearchDebounceMilli(e){this.data.headingsSearchDebounceMilli=e}get excludeViewTypes(){return this.data.excludeViewTypes}set excludeViewTypes(e){this.data.excludeViewTypes=e}get referenceViews(){return this.data.referenceViews}set referenceViews(e){this.data.referenceViews=e}get limit(){return this.data.limit}set limit(e){this.data.limit=e}get includeSidePanelViewTypes(){return this.data.includeSidePanelViewTypes}set includeSidePanelViewTypes(e){this.data.includeSidePanelViewTypes=[...new Set(e)]}get includeSidePanelViewTypesPlaceholder(){return ie.defaults.includeSidePanelViewTypes.join("\n")}get selectNearestHeading(){return this.data.selectNearestHeading}set selectNearestHeading(e){this.data.selectNearestHeading=e}get excludeFolders(){return this.data.excludeFolders}set excludeFolders(e){this.data.excludeFolders=[...new Set(e)]}get excludeLinkSubTypes(){return this.data.excludeLinkSubTypes}set excludeLinkSubTypes(e){this.data.excludeLinkSubTypes=e}get excludeRelatedFolders(){return this.data.excludeRelatedFolders}set excludeRelatedFolders(e){this.data.excludeRelatedFolders=[...new Set(e)]}get excludeOpenRelatedFiles(){return this.data.excludeOpenRelatedFiles}set excludeOpenRelatedFiles(e){this.data.excludeOpenRelatedFiles=e}get excludeObsidianIgnoredFiles(){return this.data.excludeObsidianIgnoredFiles}set excludeObsidianIgnoredFiles(e){this.data.excludeObsidianIgnoredFiles=e}get shouldSearchFilenames(){return this.data.shouldSearchFilenames}set shouldSearchFilenames(e){this.data.shouldSearchFilenames=e}get shouldSearchBookmarks(){return this.data.shouldSearchBookmarks}set shouldSearchBookmarks(e){this.data.shouldSearchBookmarks=e}get shouldSearchRecentFiles(){return this.data.shouldSearchRecentFiles}set shouldSearchRecentFiles(e){this.data.shouldSearchRecentFiles=e}get pathDisplayFormat(){return this.data.pathDisplayFormat}set pathDisplayFormat(e){this.data.pathDisplayFormat=e}get hidePathIfRoot(){return this.data.hidePathIfRoot}set hidePathIfRoot(e){this.data.hidePathIfRoot=e}get enabledRelatedItems(){return this.data.enabledRelatedItems}set enabledRelatedItems(e){this.data.enabledRelatedItems=e}get showOptionalIndicatorIcons(){return this.data.showOptionalIndicatorIcons}set showOptionalIndicatorIcons(e){this.data.showOptionalIndicatorIcons=e}get isFileExtensionIndicatorsEnabled(){return this.data.isFileExtensionIndicatorsEnabled}set isFileExtensionIndicatorsEnabled(e){this.data.isFileExtensionIndicatorsEnabled=e}get excludeFileExtensionIndicators(){return this.data.excludeFileExtensionIndicators}set excludeFileExtensionIndicators(e){this.data.excludeFileExtensionIndicators=[...new Set(e)]}get overrideStandardModeBehaviors(){return this.data.overrideStandardModeBehaviors}set overrideStandardModeBehaviors(e){this.data.overrideStandardModeBehaviors=e}get overrideStandardModeRendering(){return this.data.overrideStandardModeRendering}set overrideStandardModeRendering(e){this.data.overrideStandardModeRendering=e}get enabledRibbonCommands(){return this.data.enabledRibbonCommands}set enabledRibbonCommands(e){this.data.enabledRibbonCommands=[...new Set(e)]}get fileExtAllowList(){return this.data.fileExtAllowList}set fileExtAllowList(e){this.data.fileExtAllowList=e}get matchPriorityAdjustments(){return this.data.matchPriorityAdjustments}set matchPriorityAdjustments(e){this.data.matchPriorityAdjustments=e}get quickFilters(){return this.data.quickFilters}set quickFilters(e){this.data.quickFilters=e}get preserveCommandPaletteLastInput(){return this.data.preserveCommandPaletteLastInput}set preserveCommandPaletteLastInput(e){this.data.preserveCommandPaletteLastInput=e}get preserveQuickSwitcherLastInput(){return this.data.preserveQuickSwitcherLastInput}set preserveQuickSwitcherLastInput(e){this.data.preserveQuickSwitcherLastInput=e}get shouldCloseModalOnBackspace(){return this.data.shouldCloseModalOnBackspace}set shouldCloseModalOnBackspace(e){this.data.shouldCloseModalOnBackspace=e}get maxRecentFileSuggestionsOnInit(){return this.data.maxRecentFileSuggestionsOnInit}set maxRecentFileSuggestionsOnInit(e){this.data.maxRecentFileSuggestionsOnInit=e}get orderEditorListByAccessTime(){return this.data.orderEditorListByAccessTime}set orderEditorListByAccessTime(e){this.data.orderEditorListByAccessTime=e}get insertLinkInEditor(){return this.data.insertLinkInEditor}set insertLinkInEditor(e){this.data.insertLinkInEditor=e}get removeDefaultTabBinding(){return this.data.removeDefaultTabBinding}set removeDefaultTabBinding(e){this.data.removeDefaultTabBinding=e}get navigationKeys(){return this.data.navigationKeys}set navigationKeys(e){this.data.navigationKeys=e}get preferredSourceForTitle(){return this.data.preferredSourceForTitle}set preferredSourceForTitle(e){this.data.preferredSourceForTitle=e}get frontmatterTitleProperty(){return this.data.frontmatterTitleProperty}set frontmatterTitleProperty(e){this.data.frontmatterTitleProperty=e}get closeWhenEmptyKeys(){return this.data.closeWhenEmptyKeys}set closeWhenEmptyKeys(e){this.data.closeWhenEmptyKeys=e}get navigateToHotkeySelectorKeys(){return this.data.navigateToHotkeySelectorKeys}set navigateToHotkeySelectorKeys(e){this.data.navigateToHotkeySelectorKeys=e}get togglePinnedCommandKeys(){return this.data.togglePinnedCommandKeys}set togglePinnedCommandKeys(e){this.data.togglePinnedCommandKeys=e}get escapeCmdChar(){return this.data.escapeCmdChar}set escapeCmdChar(e){this.data.escapeCmdChar=e}get mobileLauncher(){return this.data.mobileLauncher}set mobileLauncher(e){this.data.mobileLauncher=e}get allowCreateNewFileInModeNames(){return this.data.allowCreateNewFileInModeNames}set allowCreateNewFileInModeNames(e){this.data.allowCreateNewFileInModeNames=[...new Set(e)]}get showModeTriggerInstructions(){return this.data.showModeTriggerInstructions}set showModeTriggerInstructions(e){this.data.showModeTriggerInstructions=e}get renderMarkdownContentInSuggestions(){return this.data.renderMarkdownContentInSuggestions}set renderMarkdownContentInSuggestions(e){this.data.renderMarkdownContentInSuggestions=e}get quickOpen(){return this.data.quickOpen}set quickOpen(e){this.data.quickOpen=e}get openDefaultApp(){return this.data.openDefaultApp}set openDefaultApp(e){this.data.openDefaultApp=e}get fulltextSearch(){return this.data.fulltextSearch}set fulltextSearch(e){this.data.fulltextSearch=e}get openInBackground(){return this.data.openInBackground}set openInBackground(e){this.data.openInBackground=e}get saveWorkspaceAndSwitchKeys(){return this.data.saveWorkspaceAndSwitchKeys}set saveWorkspaceAndSwitchKeys(e){this.data.saveWorkspaceAndSwitchKeys=e}get showHeadingBreadcrumbs(){return this.data.showHeadingBreadcrumbs}set showHeadingBreadcrumbs(e){this.data.showHeadingBreadcrumbs=e}get headingBreadcrumbSeparator(){return this.data.headingBreadcrumbSeparator}set headingBreadcrumbSeparator(e){this.data.headingBreadcrumbSeparator=e}get maxBreadcrumbDepth(){return this.data.maxBreadcrumbDepth}set maxBreadcrumbDepth(e){this.data.maxBreadcrumbDepth=e}get showHeadingBreadcrumbsInSymbolMode(){return this.data.showHeadingBreadcrumbsInSymbolMode}set showHeadingBreadcrumbsInSymbolMode(e){this.data.showHeadingBreadcrumbsInSymbolMode=e}get showTagsInSuggestions(){return this.data.showTagsInSuggestions}set showTagsInSuggestions(e){this.data.showTagsInSuggestions=e}get tagSource(){return this.data.tagSource}set tagSource(e){this.data.tagSource=e}get excludeTagsFromDisplay(){return this.data.excludeTagsFromDisplay}set excludeTagsFromDisplay(e){this.data.excludeTagsFromDisplay=e}get tagDisplaySeparator(){return this.data.tagDisplaySeparator}set tagDisplaySeparator(e){this.data.tagDisplaySeparator=e}get removeHashPrefixFromTags(){return this.data.removeHashPrefixFromTags}set removeHashPrefixFromTags(e){this.data.removeHashPrefixFromTags=e}get maxTagsToDisplay(){return this.data.maxTagsToDisplay}set maxTagsToDisplay(e){this.data.maxTagsToDisplay=e}constructor(e){this.plugin=e,this.data=ie.defaults}async updateDataAndLoadSettings(){return await ie.transformDataFile(this.plugin,ie.defaults),await this.loadSettings()}async loadSettings(){try{const e=await(this.plugin?.loadData());if(e){const t=Object.keys(ie.defaults);((e,t,s)=>{const i=["matchPriorityAdjustments","quickFilters","mobileLauncher"],n=s=>te.withOptions({mergeArrays:!1},t[s],e[s]);for(const a of s)a in e&&(t[a]=i.includes(a)?n(a):e[a])})(e,this.data,t)}}catch(e){O("Error loading settings, using defaults. ",e)}}async saveSettings(){const{plugin:e,data:t}=this;await(e?.saveData(t))}save(){this.saveSettings().catch((e=>{O("Error saving changes to settings",e)}))}isSymbolTypeEnabled(e){const{enabledSymbolTypes:t}=this.data;let s=ie.defaults.enabledSymbolTypes[e];return Object.prototype.hasOwnProperty.call(t,e)&&(s=t[e]),s}setSymbolTypeEnabled(e,t){this.data.enabledSymbolTypes[e]=t}shouldRenderSymbolAsHTML(e){const{renderMarkdownContentInSuggestions:t}=this.data;if(!t.isEnabled)return!1;const i={[s.Heading]:"renderHeadings",[s.Link]:"renderLinks",[s.Tag]:"renderTags",[s.Callout]:"renderCallouts"}[e];return!!i&&t[i]}static async transformDataFile(e,t){await ie.transformDataFileToV1(e,t),await ie.transformDataFileToV2(e,t)}static async transformDataFileToV1(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if(!Object.prototype.hasOwnProperty.call(i,n)){const a="starredListCommand";Object.prototype.hasOwnProperty.call(i,a)&&(i.bookmarksListCommand=i[a]??t.bookmarksListCommand,delete i[a]);const o="isStarred",r=i.matchPriorityAdjustments;r&&Object.prototype.hasOwnProperty.call(r,o)&&(r.isBookmarked=r[o],delete r[o]),i[n]="1.0.0",await(e?.saveData(i)),s=!0}}}catch(e){O("Error transforming data.json to v1.0.0",e)}return s}static async transformDataFileToV2(e,t){let s=!1;try{const i=await(e?.loadData());if(i&&"object"==typeof i){const n="version";if("1.0.0"===i[n]){const a="matchPriorityAdjustments";if(Object.prototype.hasOwnProperty.call(i,a)){const e=i[a],s={};i[a]={isEnabled:!!i.enableMatchPriorityAdjustments,adjustments:s},delete i.enableMatchPriorityAdjustments,Object.entries(e).forEach((([e,i])=>{const n=t.matchPriorityAdjustments.adjustments[e]?.label??"";s[e]={value:i,label:n}}))}const o="quickFilters";if(Object.prototype.hasOwnProperty.call(i,o)){const e="facetList",t=i[o],s=t[e],n=s?.reduce(((e,t)=>(e[t.id]=t,e)),{});t[e]=n}i[n]="2.0.0",await(e?.saveData(i)),s=!0}}}catch(e){O("Error transforming data.json to v2.0.0",e)}return s}}class ne{app;mainSettingsTab;config;constructor(e,t,s){this.app=e,this.mainSettingsTab=t,this.config=s}createSetting(e,t,s){let i;return e instanceof a.SettingGroup?e.addSetting((e=>{i=e,e.setName(t),e.setDesc(s)})):(i=new a.Setting(e),i.setName(t),i.setDesc(s)),i}withSetting(e,t,s,i){let n;return e instanceof a.SettingGroup?e.addSetting((e=>{n=e,e.setName(t).setDesc(s),i(e)})):(n=this.createSetting(e,t,s),i(n)),n}createOnChangeHandler(e,t){return s=>{t?t(s,this.config):e&&this.saveChangesToConfig(e,s)}}addSectionTitle(e,t,s=""){const i=this.createSetting(e,t,s);return i.setHeading(),i}addTextSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addText((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{const t=e.length?e:i;this.saveChangesToConfig(n,t)}))}))}))}addToggleSetting(e,t,s,i,n,a){return this.withSetting(e,t,s,(e=>{e.addToggle((e=>{e.setValue(i),e.onChange(this.createOnChangeHandler(n,a))}))}))}addTextAreaSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addTextArea((e=>{e.setPlaceholder(a),e.setValue(i),e.onChange((e=>{if(o)o(e,this.config);else{const t=e.length?e:i,s=Array.isArray(this.config[n]);this.saveChangesToConfig(n,s?t.split("\n"):t)}}))}))}))}addDropdownSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addDropdown((e=>{e.addOptions(n),e.setValue(i),e.onChange(this.createOnChangeHandler(a,o))}))}))}addSliderSetting(e,t,s,i,n,a,o){return this.withSetting(e,t,s,(e=>{e.addExtraButton((t=>(t.setIcon("lucide-rotate-ccw"),t.setTooltip("Restore default"),t.onClick((()=>e.components[1].setValue(n[3]))),t))),e.addSlider((e=>{e.setLimits(n[0],n[1],n[2]),e.setValue(i),e.setDynamicTooltip(),e.onChange(this.createOnChangeHandler(a,o))}))}))}saveChangesToConfig(e,t){if(e){const{config:s}=this;s[e]=t,s.save()}}showErrorPopup(e,t,s){const i=new a.Modal(this.app);i.titleEl.setText(e),i.contentEl.empty(),i.contentEl.createSpan({text:t}),i.contentEl.createEl("br"),i.contentEl.createEl("br"),s.forEach(((e,t)=>{t>0&&i.contentEl.createEl("br"),e.forEach(((e,t)=>{t>0&&i.contentEl.createEl("br");const s={text:e.text};void 0!==e.cls&&(s.cls=e.cls),i.contentEl.createSpan(s)}))})),i.open()}}class ae extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Bookmarks List Mode"),this.addTextSetting(e,"Bookmarks list mode trigger","Character that will trigger bookmarks list mode in the switcher",t.bookmarksListCommand,"bookmarksListCommand",t.bookmarksListPlaceholderText)}}class oe extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Command List Mode"),this.addTextSetting(e,"Command list mode trigger","Character that will trigger command list mode in the switcher",t.commandListCommand,"commandListCommand",t.commandListPlaceholderText),this.addSliderSetting(e,"Max recent commands","The maximum number of commands to save in the recent list.",t.maxRecentCommands,[0,75,1,25],"maxRecentCommands"),this.showRecentCommandDisplayOrder(e,t)}showRecentCommandDisplayOrder(e,t){this.addDropdownSetting(e,"Recent commands display order","Select the sort order for recently used commands.",t.recentCommandDisplayOrder,{desc:"Most recent first (descending)",asc:"Most recent last (ascending)"},"recentCommandDisplayOrder")}}class re extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Related Items List Mode"),this.addTextSetting(e,"Related Items list mode trigger","Character that will trigger related items list mode in the switcher. This triggers a display of Related Items for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.relatedItemsListCommand,"relatedItemsListCommand",t.relatedItemsListPlaceholderText),this.addTextSetting(e,"Related Items list mode trigger - Active editor only","Character that will trigger related items list mode in the switcher. This always triggers a display of Related Items for the active editor only.",t.relatedItemsListActiveEditorCommand,"relatedItemsListActiveEditorCommand",t.relatedItemsListActiveEditorCommand),this.showEnabledRelatedItems(e,t),this.addToggleSetting(e,"Exclude open files","Enable, related files which are already open will not be displayed in the list. Disabled, All related files will be displayed in the list.",t.excludeOpenRelatedFiles,"excludeOpenRelatedFiles")}showEnabledRelatedItems(e,t){const s=Object.values(c).sort(),i=s.join(", "),n=`The types of related items to show in the list. Add one type per line. Available types: ${i}`;this.createSetting(e,"Show related item types",n).addTextArea((e=>{e.setValue(t.enabledRelatedItems.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=[...new Set(n)].filter((e=>!s.includes(e)));a?.length?this.showErrorPopup("Invalid related item type",`Changes not saved. Available relation types are: ${i}. The following types are invalid:`,a.map((e=>[{text:e}]))):(t.enabledRelatedItems=n,t.save())}))}))}}class le extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"General"),this.addToggleSetting(e,"Default to open in new tab","When enabled, navigating to un-opened files will open a new editor tab whenever possible (as if cmd/ctrl were held). When the file is already open, the existing tab will be activated. This overrides all other tab settings.",t.onOpenPreferNewTab,"onOpenPreferNewTab"),this.showLauncherButtonOverrides(e,t),this.showEnabledRibbonCommands(e,t),this.addToggleSetting(e,"Show indicator icons","Display icons to indicate that an item is recent, bookmarked, etc..",t.showOptionalIndicatorIcons,"showOptionalIndicatorIcons"),this.addToggleSetting(e,"Display mode trigger instructions","When enabled, the trigger key for each mode will be displayed in the instructions section of the Switcher.",t.showModeTriggerInstructions,"showModeTriggerInstructions"),this.showStandardModeOverrides(e,t),this.showPathDisplayGroup(e,t),this.showPreferredSourceForTitle(e,t),this.showTagDisplaySettings(e,t),this.showQuickOpen(e,t),this.showRenderMarkdownContentAsHTML(e,t),this.addTextSetting(e,"Mode trigger escape character","Character to indicate that a mode trigger character should be treated just as a normal text.",t.escapeCmdChar,"escapeCmdChar"),this.addToggleSetting(e,"Allow Backspace key to close the Switcher","When the search box is empty, pressing the backspace key will close Switcher++.",t.shouldCloseModalOnBackspace,"shouldCloseModalOnBackspace"),this.showRestoreInput(e,t),this.showInsertLinkInEditor(e,t),this.showResetFacetEachSession(e,t),this.showMatchPriorityAdjustments(e,t)}showPreferredSourceForTitle(e,t){const s=new a.SettingGroup(e);this.addDropdownSetting(s,"Preferred suggestion title source",'The preferred source to use for the "title" text that will be searched and displayed for file based suggestions',t.preferredSourceForTitle,{H1:"First H₁ heading",Default:"Default",FrontMatter:"Frontmatter property"},"preferredSourceForTitle",((e,t)=>{t.preferredSourceForTitle=e,t.save(),this.mainSettingsTab.display()})),"FrontMatter"===t.preferredSourceForTitle&&this.addTextSetting(s,"Frontmatter property path",'The path to the frontmatter property to use as the title. Use dot notation for nested properties (e.g., "title" or "meta.display_name"). The property value must be a string, number, or boolean. If the property doesn\'t exist or has an invalid type, the default filename will be used.',t.frontmatterTitleProperty,"frontmatterTitleProperty","title")}showPathDisplayFormat(t,s){const i={};i[e.None.toString()]="Hide path",i[e.Full.toString()]="Full path",i[e.FolderOnly.toString()]="Only parent folder",i[e.FolderWithFilename.toString()]="Parent folder & filename",i[e.FolderPathFilenameOptional.toString()]="Parent folder path (filename optional)",this.addDropdownSetting(t,"Preferred file path display format","The preferred way to display file paths in suggestions",s.pathDisplayFormat.toString(),i,null,((e,t)=>{t.pathDisplayFormat=Number(e),t.save()}))}showPathDisplayGroup(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Path Display Settings","Configure how file paths are displayed in suggestions."),this.showPathDisplayFormat(s,t),this.addToggleSetting(s,"Hide path for root items","When enabled, path information will be hidden for items at the root of the vault.",t.hidePathIfRoot,"hidePathIfRoot")}showStandardModeOverrides(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Standard Mode Overrides","Configure how Switcher++ overrides the default Obsidian Switcher behavior in Standard mode."),this.addToggleSetting(s,"Override Standard mode file open behavior","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to inject custom file open behavior.",t.overrideStandardModeBehaviors,"overrideStandardModeBehaviors"),this.addToggleSetting(s,"Override Standard mode rendering","When enabled, Switcher++ will change the default Obsidian builtin Switcher functionality (Standard mode) to render suggestions as multi-line.",t.overrideStandardModeRendering,"overrideStandardModeRendering")}showRestoreInput(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Restore Previous Input","Configure whether to restore the last typed input when launching the Switcher."),this.addToggleSetting(s,"Restore previous input in Command Mode","When enabled, restore the last typed input in Command Mode when launched via global command hotkey.",t.preserveCommandPaletteLastInput,"preserveCommandPaletteLastInput"),this.addToggleSetting(s,"Restore previous input","When enabled, restore the last typed input when launched via global command hotkey.",t.preserveQuickSwitcherLastInput,"preserveQuickSwitcherLastInput")}showEnabledRibbonCommands(e,t){const s=E(),i=s.join(" "),n=`Display an icon in the ribbon menu to launch specific modes. Add one mode per line. Available modes: ${i}`;this.createSetting(e,"Show ribbon icons",n).addTextArea((e=>{e.setValue(t.enabledRibbonCommands.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const n=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0)),a=Array.from(new Set(n)).filter((e=>!s.includes(e)));a.length?this.showErrorPopup("Invalid mode",`Changes not saved. Available modes are: ${i}. The following are invalid:`,a.map((e=>[{text:e}]))):(t.enabledRibbonCommands=n,t.save(),this.mainSettingsTab.plugin.registerRibbonCommandIcons())}))}))}showLauncherButtonOverrides(e,t){const{mobileLauncher:s}=t,i=new a.SettingGroup(e),n="disabled",o={[n]:"Do not override"},r=E();r.forEach((e=>{o[e]=e}));let l=n;s.isEnabled&&r.includes(s.modeString)&&(l=s.modeString),this.addDropdownSetting(i,"New tab and mobile launcher buttons",'Select the Mode to launch Switcher++ in from the empty tab page and mobile navigation Bar button, or select "Do not override" to disable the feature.',l,o,null,((e,t)=>{const s=e!==n;t.mobileLauncher.isEnabled=s,s&&(t.mobileLauncher.modeString=e),t.save(),this.mainSettingsTab.display(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(s)})),s.isEnabled&&(this.addToggleSetting(i,"Override default Switcher launch button on mobile platforms",'When enabled, override the "🔍" button (in the Navigation Bar) on mobile platforms to launch Switcher++ instead of the default system switcher.',s.isMobileButtonEnabled,null,((e,t)=>{t.mobileLauncher.isMobileButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})),this.addToggleSetting(i,'Display launch button on the "New tab" page','When enabled, a button to launch Switcher++ using the selected mode above will be added to the default Obsidian "New tab" page.',s.isEmptyTabButtonEnabled,null,((e,t)=>{t.mobileLauncher.isEmptyTabButtonEnabled=e,t.save(),this.mainSettingsTab.plugin.updateLauncherButtonOverrides(t.mobileLauncher.isEnabled)})))}showMatchPriorityAdjustments(e,t){const{matchPriorityAdjustments:{isEnabled:s,adjustments:i,fileExtAdjustments:n}}=t,o=new a.SettingGroup(e);this.addToggleSetting(o,"Result priority adjustments","Artificially increase the match score of the specified item types by a fixed percentage so they appear higher in the results list (does not apply to Standard Mode).",s,null,((e,t)=>{t.matchPriorityAdjustments.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Result Priority Adjustments" setting. ',e)))})),s&&[i,n].forEach((e=>{Object.entries(e).forEach((([t,s])=>{const{value:i,label:n}=s;this.addSliderSetting(o,n,s.desc??"",i,[-1,1,.05,0],null,((s,i)=>{e[t].value=s,i.save()}))}))}))}showResetFacetEachSession(e,t){this.addToggleSetting(e,"Reset active Quick Filters","When enabled, the switcher will reset all Quick Filters back to inactive for each session.",t.quickFilters.shouldResetActiveFacets,null,((e,t)=>{t.quickFilters.shouldResetActiveFacets=e,t.save()}))}showRenderMarkdownContentAsHTML(e,t){const{renderMarkdownContentInSuggestions:s}=t,i=new a.SettingGroup(e),n=this.addToggleSetting(i,"Display markdown content as Live Preview",'When enabled, markdown content in symbol suggestions will be rendered as HTML similar to the Obsidian "Live Preview" display. When disabled, content will be rendered as raw text. Use the "toggle preview (selected item)" hotkey to toggle the display for individual items.',s.isEnabled,null,((e,t)=>{const{renderMarkdownContentInSuggestions:s}=t;s.isEnabled=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Display markdown content as Live Preview" setting. ',e)))}));if(n?.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),s.isEnabled){[{name:"Headings",property:"renderHeadings",description:"Render headings as HTML"},{name:"Links",property:"renderLinks",description:"Render links as HTML"},{name:"Tags",property:"renderTags",description:"Render tags as HTML"},{name:"Callouts",property:"renderCallouts",description:"Render callouts as HTML"}].forEach((({name:e,property:t,description:n})=>{this.addToggleSetting(i,e,n,s[t],null,((e,s)=>{s.renderMarkdownContentInSuggestions[t]=e,s.save()}))}))}}showInsertLinkInEditor(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Insert link in editor","Configure alias options when inserting links into the editor."),this.addToggleSetting(s,"Use filename as alias","When enabled, the file basename will be set as the link alias.",t.insertLinkInEditor.useBasenameAsAlias,null,((e,t)=>{t.insertLinkInEditor.useBasenameAsAlias=e,t.save()})),this.addToggleSetting(s,"Use heading as alias",'When enabled, the file heading will be set as the link alias. This overrides the "use filename as alias" setting.',t.insertLinkInEditor.useHeadingAsAlias,null,((e,t)=>{t.insertLinkInEditor.useHeadingAsAlias=e,t.save()}))}showQuickOpen(e,t){this.addToggleSetting(e,"Enable quick open hotkeys for top results","When enabled, hotkeys will be defined for each of the top N results displayed in the Switcher. These hotkeys can be used to quickly open the associated suggestion directly. when disabled, no hotkeys are defined.",t.quickOpen.isEnabled,null,((e,t)=>{t.quickOpen.isEnabled=e,t.save()}))}showTagDisplaySettings(e,t){const{showTagsInSuggestions:s}=t,i=new a.SettingGroup(e);if(this.addToggleSetting(i,"Show tags in suggestions","When enabled, tags associated with a file will be displayed in suggestions.",s,null,((e,t)=>{t.showTagsInSuggestions=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Show tags in suggestions" setting. ',e)))})),s){const e={[n.Both]:"Both",[n.Inline]:"Inline only",[n.Frontmatter]:"Frontmatter only"};this.addDropdownSetting(i,"Tag source","Select which tags to display: inline tags (in document body), frontmatter tags, or both.",t.tagSource,e,null,((e,t)=>{t.tagSource=e,t.save()})),this.addTextAreaSetting(i,"Excluded tags","Tags to exclude from display, one per line. Tags should be entered without the # prefix.",t.excludeTagsFromDisplay.join("\n"),null,"tag1\ntag2\ntag3",((e,t)=>{const s=e.split("\n").map((e=>e.trim())).filter((e=>e.length>0));t.excludeTagsFromDisplay=s,t.save()})),this.addSliderSetting(i,"Max tags to display","Maximum number of tags to show per suggestion. Set to 0 for unlimited.",t.maxTagsToDisplay,[0,20,1,5],"maxTagsToDisplay"),this.addTextSetting(i,"Tag separator","The string used to separate multiple tags in the display.",t.tagDisplaySeparator,"tagDisplaySeparator",", "),this.addToggleSetting(i,"Remove # prefix from tags","When enabled, the # prefix will be removed from tags when displayed.",t.removeHashPrefixFromTags,"removeHashPrefixFromTags")}}}class de extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Workspace List Mode"),this.addTextSetting(e,"Workspace list mode trigger","Character that will trigger workspace list mode in the switcher",t.workspaceListCommand,"workspaceListCommand",t.workspaceListPlaceholderText)}}class ce extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Editor List Mode"),this.addTextSetting(e,"Editor list mode trigger","Character that will trigger editor list mode in the switcher",t.editorListCommand,"editorListCommand",t.editorListPlaceholderText),this.showIncludeSidePanelViews(e,t),this.addToggleSetting(e,"Order default editor list by most recently accessed","When there is no search term, order the list of editors by most recent access time.",t.orderEditorListByAccessTime,"orderEditorListByAccessTime")}showIncludeSidePanelViews(e,t){const s=`When in Editor list mode, show the following view types from the side panels. Add one view type per line. Available view types: ${Object.keys(this.app.viewRegistry.viewByType).sort().join(" ")}`;this.addTextAreaSetting(e,"Include side panel views",s,t.includeSidePanelViewTypes.join("\n"),"includeSidePanelViewTypes",t.includeSidePanelViewTypesPlaceholder)}}class he extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Headings List Mode"),this.addTextSetting(e,"Headings list mode trigger","Character that will trigger headings list mode in the switcher",t.headingsListCommand,"headingsListCommand",t.headingsListPlaceholderText),this.addSliderSetting(e,"Max recent files to show","The maximum number of recent files to show when there is no search term",t.maxRecentFileSuggestionsOnInit,[0,75,1,25],"maxRecentFileSuggestionsOnInit"),this.showFileExtAllowList(e,t),this.addToggleSetting(e,"Search Filenames","Enabled, search and show suggestions for filenames. Disabled, Don't search through filenames (except for fallback searches)",t.shouldSearchFilenames,"shouldSearchFilenames"),this.addToggleSetting(e,"Search Bookmarks","Enabled, search and show suggestions for Bookmarks. Disabled, Don't search through Bookmarks",t.shouldSearchBookmarks,"shouldSearchBookmarks"),this.showHeadingSettings(e,t),this.showExclusionsGroup(e,t)}showHeadingSettings(e,t){const s=t.shouldSearchHeadings,i=new a.SettingGroup(e);this.addToggleSetting(i,"Search Headings","Enabled, search and show suggestions for Headings. Disabled, Don't search through Headings",s,null,((e,t)=>{t.shouldSearchHeadings=e,t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Search Headings" setting. ',e)))})),s&&(this.addToggleSetting(i,"Turn off filename fallback","Enabled, strictly search through only the headings contained in the file. Do not fallback to searching the filename when an H1 match is not found. Disabled, fallback to searching against the filename when there is not a match in the first H1 contained in the file.",t.strictHeadingsOnly,"strictHeadingsOnly"),this.addToggleSetting(i,"Search all headings","Enabled, search through all headings contained in each file. Disabled, only search through the first H1 in each file.",t.searchAllHeadings,"searchAllHeadings"),this.showBreadcrumbSettings(i,t))}showFileExtAllowList(e,t){this.createSetting(e,"File extension override",'Override the "Show attachments" and the "Show all file types" builtin, system Switcher settings and always search files with the listed extensions. Add one path per line. For example to add ".canvas" file extension, just add "canvas".').addTextArea((e=>{e.setValue(t.fileExtAllowList.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const s=e.getValue().split("\n").map((e=>e.trim())).filter((e=>e.length>0));t.fileExtAllowList=s,t.save()}))}))}showExclusionsGroup(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Exclusions","Configure which folders and files should be excluded from search results in Headings list mode."),this.showExcludeFolders(s,t),this.addToggleSetting(s,'Hide Obsidian "Excluded files"','Enabled, do not display suggestions for files that are in Obsidian\'s "Options > Files & Links > Excluded files" list. Disabled, suggestions for those files will be displayed but downranked.',t.excludeObsidianIgnoredFiles,"excludeObsidianIgnoredFiles")}showExcludeFolders(e,t){const s="Exclude folders";this.createSetting(e,s,"When in Headings list mode, folder path that match any regex listed here will not be searched for suggestions. Path should start from the Vault Root. Add one path per line.").addTextArea((e=>{e.setValue(t.excludeFolders.join("\n")),e.inputEl.addEventListener("focusout",(()=>{const i=e.getValue().split("\n").filter((e=>e.length>0));this.validateExcludeFolderList(s,i)&&(t.excludeFolders=i,t.save())}))}))}showBreadcrumbSettings(e,t){this.addToggleSetting(e,"Show heading breadcrumbs","Enabled, display the hierarchical path of parent headings leading to each heading suggestion.",t.showHeadingBreadcrumbs,"showHeadingBreadcrumbs"),this.addTextSetting(e,"Breadcrumb separator","The string used to separate heading levels in breadcrumbs",t.headingBreadcrumbSeparator,"headingBreadcrumbSeparator"),this.addSliderSetting(e,"Max breadcrumb depth","Maximum number of heading levels to show in breadcrumbs. Set to 0 for unlimited depth.",t.maxBreadcrumbDepth,[0,6,1,0],"maxBreadcrumbDepth")}validateExcludeFolderList(e,t){let s=!0;const i=[];for(const e of t)try{new RegExp(e)}catch(t){i.push({regex:e,error:t}),s=!1}return s||this.showErrorPopup(e,"Changes not saved. The following regex contain errors:",i.map((({regex:e,error:t})=>[{text:e,cls:"qsp-warning"},{text:t.toString()}]))),s}}class me extends ne{display(e){const{config:t}=this;this.addSectionTitle(e,"Symbol List Mode"),this.addTextSetting(e,"Symbol list mode trigger","Character that will trigger symbol list mode in the switcher. This triggers a display of Symbols for the source file of the currently selected (highlighted) suggestion in the switcher. If there is not a suggestion, display results for the active editor.",t.symbolListCommand,"symbolListCommand",t.symbolListPlaceholderText),this.addTextSetting(e,"Symbol list mode trigger - Active editor only","Character that will trigger symbol list mode in the switcher. This always triggers a display of Symbols for the active editor only.",t.symbolListActiveEditorCommand,"symbolListActiveEditorCommand",t.symbolListActiveEditorCommand),this.addToggleSetting(e,"List symbols as indented outline","Enabled, symbols will be displayed in the (line) order they appear in the source text, indented under any preceding heading. Disabled, symbols will be grouped by type: Headings, Tags, Links, Embeds.",t.symbolsInLineOrder,"symbolsInLineOrder"),this.addToggleSetting(e,"Auto-select nearest heading","Enabled, in an unfiltered symbol list, select the closest preceding Heading to the current cursor position. Disabled, the first symbol in the list is selected.",t.selectNearestHeading,"selectNearestHeading"),this.addToggleSetting(e,"Show heading breadcrumbs in Symbol mode","Enabled, display the hierarchical path of parent headings when showing heading symbols in Symbol mode.",t.showHeadingBreadcrumbsInSymbolMode,"showHeadingBreadcrumbsInSymbolMode"),this.showEnableSymbolTypesToggle(e,t),this.showEnableLinksToggle(e,t),this.showSymbolTabNavigationBehavior(e,t)}showSymbolTabNavigationBehavior(e,t){const s=new a.SettingGroup(e);this.createSetting(s,"Symbol Tab navigation behavior","Configure how symbols are opened when navigating from the symbol list."),this.addToggleSetting(s,"Open Symbols in new tab","Enabled, always open a new tab when navigating to Symbols. Disabled, navigate in an already open tab (if one exists).",t.alwaysNewTabForSymbols,"alwaysNewTabForSymbols"),this.addToggleSetting(s,"Open Symbols in active tab on mobile devices","Enabled, navigate to the target file and symbol in the active editor tab. Disabled, open a new tab when navigating to Symbols, even on mobile devices.",t.useActiveTabForSymbolsOnMobile,"useActiveTabForSymbolsOnMobile")}showEnableSymbolTypesToggle(e,t){[["Show Headings",s.Heading],["Show Tags",s.Tag],["Show Embeds",s.Embed],["Show Callouts",s.Callout]].forEach((([s,i])=>{this.addToggleSetting(e,s,"",t.isSymbolTypeEnabled(i),null,(e=>{t.setSymbolTypeEnabled(i,e),t.save()}))}))}showEnableLinksToggle(e,t){const n=t.isSymbolTypeEnabled(s.Link),o=new a.SettingGroup(e);if(this.addToggleSetting(o,"Show Links","",n,null,(e=>{t.setSymbolTypeEnabled(s.Link,e),t.saveSettings().then((()=>{this.mainSettingsTab.display()}),(e=>A('Error saving "Show Links" setting. ',e)))})),n){[["Links to headings",i.Heading],["Links to blocks",i.Block]].forEach((([e,s])=>{const i=(t.excludeLinkSubTypes&s)===s;this.addToggleSetting(o,e,"",!i,null,(e=>this.saveEnableSubLinkChange(s,e)))}))}}saveEnableSubLinkChange(e,t){const{config:s}=this;let i=s.excludeLinkSubTypes;t?i&=~e:i|=e,s.excludeLinkSubTypes=i,s.save()}}class ue extends ne{display(e){const{config:t}=this,s=this.addSectionTitle(e,"Vault List Mode");s.nameEl?.createSpan({cls:["qsp-tag","qsp-warning"],text:"Experimental"}),this.addTextSetting(e,"Vault list mode trigger","Character that will trigger vault list mode in the switcher",t.vaultListCommand,"vaultListCommand",t.vaultListPlaceholderText)}}class ge extends a.PluginSettingTab{plugin;config;constructor(e,t,s){super(e,t),this.plugin=t,this.config=s,this.containerEl.addClass("qsp-settings-container")}display(){const{containerEl:e}=this,t=[le,me,he,ce,re,ae,oe,de,ue];e.empty(),t.forEach((e=>{this.displayTabSection(e)}))}displayTabSection(e){const{app:t,config:s,containerEl:i}=this;new e(t,this,s).display(i)}}class pe{inputText;mode;parsedCommands;_cleanInput=null;static get defaultParsedCommand(){return{isValidated:!1,index:-1,parsedInput:null}}sessionOpts;currentWorkspaceEnvList={openWorkspaceLeaves:new Set,openWorkspaceFiles:new Set,fileBookmarks:new Map,nonFileBookmarks:new Set,mostRecentFiles:new Set,attachmentFileExtensions:new Set};get parsedInputQuery(){const e=(this.parsedCommand()?.parsedInput??"").trim().toLowerCase();return{query:e,hasSearchTerm:!!e.length}}get cleanInput(){return this._cleanInput??this.inputText}set cleanInput(e){this._cleanInput=e}constructor(e="",s=t.Standard,i){this.inputText=e,this.mode=s,this.sessionOpts=i??{};const n=F();this.parsedCommands={},E().forEach((e=>{const s=t[e];n.includes(s)?this.parsedCommands[s]={...pe.defaultParsedCommand,source:null}:this.parsedCommands[s]=pe.defaultParsedCommand}))}parsedCommand(e){return e=e??this.mode,this.parsedCommands[e]}}class fe{app;settings;facets;constructor(e,t){this.app=e,this.settings=t}reset(){}onNoResultsCreateAction(e,t){return!1}getFacets(e){if(!this.facets){const t=this.settings?.quickFilters?.facetList;t&&(this.facets=Object.values(t).filter((t=>t.mode===e)))}return this.facets??[]}getAvailableFacets(e){return this.getFacets(e.mode).filter((e=>e.isAvailable))}activateFacet(e,t){e.forEach((e=>e.isActive=t)),this.settings.quickFilters.shouldResetActiveFacets||this.settings.save()}getActiveFacetIds(e){const t=this.getAvailableFacets(e).filter((e=>e.isActive)).map((e=>e.id));return new Set(t)}isFacetedWith(e,t){const s=!!e.size;return s&&e.has(t)||!s}getEditorInfo(e){const{excludeViewTypes:t}=this.settings;let s=null,i=!1,n=null;if(e){s=H(e),n=this.getCursorPosition(e);i=!t.includes(e.view.getViewType())&&!!s}return{isValidSource:i,leaf:e,file:s,suggestion:null,cursor:n}}getSuggestionInfo(e){const t=this.getSourceInfoFromSuggestion(e);let s=t.leaf;t.isValidSource&&({leaf:s}=this.findMatchingLeaf(t.file,t.leaf));const i=this.getCursorPosition(s);return{...t,leaf:s,cursor:i}}getSourceInfoFromSuggestion(e){let t=null,s=null;const i=[l.SymbolList,l.Unresolved,l.WorkspaceList,l.CommandList,l.VaultList];e&&!i.includes(e.type)&&(t=e.file),m(e,"type",l.EditorList)&&(s=e.item);return{isValidSource:!!t,leaf:s,file:t,suggestion:e}}getCursorPosition(e){let t=null;if(K(e,"markdown")){const s=e.view;"preview"!==s.getMode()&&(t=s.editor.getCursor("head"))}return t}getTitleText(e){const t=function(e){let t=null;if(e){const{path:s}=e;if(t=s,"md"===e.extension){const e=s.lastIndexOf(".");-1!==e&&e!==s.length-1&&0!==e&&(t=s.slice(0,e))}}return t}(e),s=this.getFirstH1(e);return s?.heading??t}getFirstH1(e){return fe.getFirstH1(e,this.app.metadataCache)}static getFirstH1(e,t){let s=null;const i=t.getFileCache(e)?.headings?.filter((e=>1===e.level))??[];return i.length&&(s=i.reduce(((e,t)=>{const{line:s}=t.position.start;return s<e.position.start.line?t:e}))),s}static getFrontmatterProperty(e,t){if(!e||!t)return null;const s=t.split(".");let i=e;for(const e of s){if(!i||"object"!=typeof i||!(e in i))return null;i=i[e]}return"string"==typeof i&&i.trim().length>0?i.trim():"number"==typeof i||"boolean"==typeof i?String(i):null}findMatchingLeaf(e,t,s=!1){let i=null;const n=!!t,{settings:{referenceViews:a,excludeViewTypes:o,includeSidePanelViewTypes:r}}=this,l=i=>{let o=!1;if(i?.view){const r=a.includes(i.view.getViewType()),l=s||!r,d=n&&a.includes(t.view.getViewType());l&&(o=!n||!s&&d?H(i)===e:i===t)}return o},d=this.getActiveLeaf();if(l(d))i=d;else{const e=this.getOpenLeaves(o,r);i=[t,...e].find(l)}return{leaf:i??null,file:e,suggestion:null,isValidSource:!1}}extractTabNavigationType(e,t,s){const i=e?.shiftKey?"horizontal":"vertical",n=e?.key;let o=a.Keymap.isModEvent(e)??!1;return!0!==o&&"tab"!==o||("o"===n?o="window":"\\"===n&&(o="split")),o=this.applyTabCreationPreferences(o,t,s),{navType:o,splitDirection:i}}applyTabCreationPreferences(e,s=!1,i){let n=e;const{onOpenPreferNewTab:o,alwaysNewTabForSymbols:r,useActiveTabForSymbolsOnMobile:l}=this.settings;return!1===e&&(o?n=!s:i===t.SymbolList&&(n=a.Platform.isMobile?!l:r)),n}isMainPanelLeaf(e){const{workspace:t}=this.app,s=e?.getRoot();return s===t.rootSplit||s===t.floatingSplit}async activateLeaf(e,t){const{workspace:s}=this.app;try{await s.revealLeaf(e),s.setActiveLeaf(e,{focus:!0}),e.view.setEphemeralState({focus:!0,...t})}catch(t){const s=e?.getDisplayText();A(`Error activating WorkspaceLeaf with title: ${s}`,t)}}getOpenLeaves(e,t,s){const i=[];return this.app.workspace.iterateAllLeaves((s=>{const n=s?.view?.getViewType();this.isMainPanelLeaf(s)?e?.includes(n)||i.push(s):t?.includes(n)&&i.push(s)})),s?.orderByAccessTime&&i.sort(((e,t)=>{const s=e?.activeTime??0;return(t?.activeTime??0)-s})),i}static async openFileInLeaf(e,t,s,i,n="vertical"){const a="split"===t?s.getLeaf(t,n):s.getLeaf(t);await a.openFile(e,i)}navigateToLeafOrOpenFile(e,t,s,i,n,a,o=!1){this.navigateToLeafOrOpenFileAsync(e,t,i,n,a,o).catch((e=>{A(`Error navigating to open file. ${s}`,e)}))}async navigateToLeafOrOpenFileAsync(e,t,s,i,n,a=!1){const{leaf:o}=this.findMatchingLeaf(t,i,a),r=!!o,{navType:l,splitDirection:d}=this.extractTabNavigationType(e,r,n);await this.activateLeafOrOpenFile(l,t,o,s,d)}async activateLeafOrOpenFile(e,t,s,i,n){if(i=i??this.getOpenViewActiveState(),s&&!1===e){const e=i?.eState;await this.activateLeaf(s,e)}else await fe.openFileInLeaf(t,e,this.app.workspace,i,n)}renderPath(t,s,i,n,a){if(!t||!s)return;const o=s.parent.isRoot();let r=this.settings.pathDisplayFormat,l=r===e.None||o&&this.settings.hidePathIfRoot;if(a&&(r=e.FolderPathFilenameOptional,l=!1),!l){const e=this.getPathDisplayText(s,r,i);this.renderBreadcrumb(t,e,"lucide-folder-open",n,["qsp-path"])}}renderBreadcrumb(e,t,s,i,n){if(!e||!t)return;const o=["suggestion-note","qsp-note"];n&&o.push(...n);const r=e.createDiv({cls:o}),l=r.createSpan({cls:["qsp-breadcrumb-indicator"]});a.setIcon(l,s);const d=r.createSpan({cls:"qsp-breadcrumb"});a.renderResults(d,t,i)}renderHeadingBreadcrumbs(e,t,s,i){if(!((i??this.settings.showHeadingBreadcrumbs)&&e&&t&&s))return;if(1===t.level)return;const n=function(e,t,s){const i=s.getFileCache(t)?.headings??[],n=e.position.start.line,a=new Map;for(const t of i){const s=t.position.start.line;if(s>=n)continue;if(t.level>=e.level)continue;const i=a.get(t.level);(!i||s>i.position.start.line)&&a.set(t.level,t)}const o=[];for(let t=1;t<e.level;t++){const e=a.get(t);e&&o.push(e)}return o}(t,s,this.app.metadataCache);if(0===n.length)return;const{maxBreadcrumbDepth:a}=this.settings,o=["qsp-heading-breadcrumbs"];a>0&&n.length>a&&o.push("qsp-truncated");const r=function(e,t=" > ",s=0){let i=e;return s>0&&e.length>s&&(i=e.slice(-s)),i.map((e=>e.heading)).join(t)}(n,this.settings.headingBreadcrumbSeparator,a);r&&this.renderBreadcrumb(e,r,"lucide-heading",void 0,o)}renderTags(e,t){const{settings:s}=this;if(!s.showTagsInSuggestions||!e||!t)return;const i=new Set(s.excludeTagsFromDisplay),a=function(e,t,s=n.Both,i){const a=t.getFileCache(e);if(!a)return[];const o=new Set;s!==n.Inline&&s!==n.Both||(a.tags??[]).forEach((e=>o.add(e.tag)));s!==n.Frontmatter&&s!==n.Both||h.getTags(a.frontmatter).forEach((e=>{o.add(e.startsWith("#")?e:`#${e}`)}));let r=Array.from(o);return i&&i.size>0&&(r=r.filter((e=>{const t=e.startsWith("#")?e.slice(1):e;return!i.has(t)}))),r.sort()}(t,this.app.metadataCache,s.tagSource,i);if(0===a.length)return;let o=a;const r=["qsp-tags-breadcrumbs"];s.maxTagsToDisplay>0&&a.length>s.maxTagsToDisplay&&(o=a.slice(0,s.maxTagsToDisplay),r.push("qsp-truncated"));const l=function(e,t=" ",s=!1){return e&&0!==e.length?(s?e.map((e=>e.startsWith("#")?e.slice(1):e)):e).join(t):""}(o,s.tagDisplaySeparator,s.removeHashPrefixFromTags);l&&this.renderBreadcrumb(e,l,"lucide-tags",void 0,r)}getPathDisplayText(t,s,i){let n="";if(t){const{parent:o}=t,r=o.name,l=o.isRoot(),d=this.app.vault.getRoot().path;switch(s){case e.FolderWithFilename:n=l?`${t.name}`:a.normalizePath(`${r}/${t.name}`);break;case e.FolderOnly:n=l?d:r;break;case e.Full:n=t.path;break;case e.FolderPathFilenameOptional:i?(n=o.path,l||(n+=d)):n=this.getPathDisplayText(t,e.Full)}}return n}renderContent(e,t,s,i){const{contentEl:n,titleEl:o}=fe.createContentStructureElements(e);return a.renderResults(o,t,s,i),n}static createContentStructureElements(e){const t=e.createDiv({cls:["suggestion-content","qsp-content"]}),s=t.createDiv({cls:["suggestion-title","qsp-title"]});return{contentEl:t,titleEl:s}}static renderMarkdownContentAsync(e,t,s,i){fe.renderMarkdownContent(e,t,s,i,q.getRootComponent()).catch((e=>{O("Error rendering markdown to html. ",e,`content: ${s}`)}))}static async renderMarkdownContent(e,t,s,i,n){const o=t.createDiv({cls:["qsp-rendered-container"]});if(await a.MarkdownRenderer.render(e,s,o,i,n),1===o.childNodes.length&&"P"===o.firstChild.nodeName){const e=o.firstChild;e.replaceWith(...Array.from(e.childNodes))}return o}addClassesToSuggestionContainer(e,t){const s=["mod-complex"];t&&s.push(...t),e?.addClasses(s)}splitSearchMatchesAtBasename(e,t){let s=null,i=null;const n=(e,t)=>{e.forEach((e=>{e[0]-=t,e[1]-=t}))};if(e&&t?.matches){const a=e.path.lastIndexOf(e.basename);if(a>=0){const{matches:e,score:o}=t,r=e[0][0],l=e[e.length-1][1];if(r>=a)s=t,n(s.matches,a);else if(l<=a)i=t;else{let t=e.length;for(;t--;){const r=e[t][0],l=t+1;if(e[t][1]<=a){i={score:o,matches:e.slice(0,l)},s={score:o,matches:e.slice(l)},n(s.matches,a);break}if(r<a){let d=e.slice(0,l);d[d.length-1]=[r,a],i={score:o,matches:d},d=e.slice(t),n(d,a),d[0][0]=0,s={score:o,matches:d};break}}}}}return{pathMatch:i,basenameMatch:s}}renderAsFileInfoPanel(e,t,s,i,n,a,o=!0){let r=null,l=null;s?.length?n===d.Primary?r=a:n===d.Path&&(l=a):i&&(s=i.basename,n===d.Basename?r=a:n===d.Path&&({pathMatch:l,basenameMatch:r}=this.splitSearchMatchesAtBasename(i,a))),this.addClassesToSuggestionContainer(e,t);const c=this.renderContent(e,s,r);return this.renderPath(c,i,o,l,!!l),this.renderTags(c,i),c}getActiveLeaf(){return fe.getActiveLeaf(this.app.workspace)}static getActiveLeaf(e){const t=e?.getActiveViewOfType(a.View)?.leaf;return t??null}renderOptionalIndicators(e,t,s=null){const{settings:i}=this,n=new Map;if(n.set("isRecent",{iconName:"history",parentElClass:"qsp-recent-file",indicatorElClass:"qsp-recent-indicator"}),n.set("isOpenInEditor",{iconName:"lucide-file-edit",parentElClass:"qsp-open-editor",indicatorElClass:"qsp-editor-indicator"}),n.set("isBookmarked",{iconName:"lucide-bookmark",parentElClass:"qsp-bookmarked-file",indicatorElClass:"qsp-bookmarked-indicator"}),s||(s=this.createFlairContainer(e)),i.showOptionalIndicatorIcons){const a=W(t);this.renderFileExtensionIndicator(s,a,i);for(const[i,a]of n.entries())!0===t[i]&&(a.parentElClass&&e?.addClass(a.parentElClass),this.renderIndicator(s,[a.indicatorElClass],a.iconName))}return s}renderIndicator(e,t,s,i){const n=["suggestion-flair",...t],o=e?.createSpan({cls:n});return o&&(s&&(o.addClass("svg-icon"),a.setIcon(o,s)),i&&o.setText(i)),o}renderFileExtensionIndicator(e,t,s){let i=null;const{isFileExtensionIndicatorsEnabled:n,excludeFileExtensionIndicators:a}=s;return n&&t?(a?.includes(t.extension)||(i=e?.createDiv({cls:["suggestion-flair","nav-file-tag","qsp-file-ext-indicator"],text:t.extension})),i):i}createFlairContainer(e){return e?.createDiv({cls:["suggestion-aux","qsp-aux"]})}getTFileByPath(e){return R(e,this.app.vault)}applyMatchPriorityPreferences(e){return fe.applyMatchPriorityPreferences(e,this.settings,this.app.metadataCache)}static applyMatchPriorityPreferences(e,t,s){if(e?.match){const{match:i,type:n,file:a}=e;if(a&&s?.isUserIgnored(a.path))e.downranked=!0,e.match.score-=10;else if(t?.matchPriorityAdjustments?.isEnabled){const{matchPriorityAdjustments:s}=t,o=s.adjustments??{},r=s.fileExtAdjustments??{};let d=0;const c=(e,t)=>{t=t??o;let s=0;return Object.prototype.hasOwnProperty.call(t,e)&&(s=Number(t[e]?.value)),isNaN(s)?0:s},h=(t,s)=>{let i=0;return(null!==t&&t===n||e[s])&&(i=c(s)),i};d+=h(l.Bookmark,"isBookmarked"),d+=h(l.EditorList,"isOpenInEditor"),d+=h(null,"isRecent"),d+=h(null,"isAttachment"),d+=c(a?.extension,r),g(e)&&(d+=c(`h${e.item?.level}`));const m=n.toString();d+=c(m),i.score+=Math.abs(i.score)/100*(100*d)}}return e}static updateWorkspaceEnvListStatus(e,t){if(e&&t?.file){const{file:s}=t;t.isOpenInEditor=e.openWorkspaceFiles?.has(s),t.isRecent=e.mostRecentFiles?.has(s),t.isBookmarked=e.fileBookmarks?.has(s),t.isAttachment=e.attachmentFileExtensions?.has(s.extension)}return t}renderFileCreationSuggestion(e,t){this.addClassesToSuggestionContainer(e);const s=this.renderContent(e,t,null),i=this.createFlairContainer(e);return i?.createSpan({cls:"suggestion-hotkey",text:"Enter to create"}),s}createFile(e,t){const{workspace:s}=this.app,{navType:i}=this.extractTabNavigationType(t),n=s.getActiveViewOfType(a.FileView);let o="";n?.file&&(o=n.file.path),s.openLinkText(e,o,i,{active:!0}).catch((e=>{A("Error creating new file. ",e)}))}getOpenViewState(e,t){const s=this.getPreferredViewLinePosition(e),{eState:i}=this.getOpenViewLinePositionState(s),n=this.getOpenViewActiveState(t);return Object.assign(n.eState,i),n}getOpenViewActiveState(e){const{active:t,focus:s}=Object.assign({active:!0,focus:!0},e);return{active:t,eState:{active:t,focus:s}}}getPreferredViewLinePosition(e){const t={line:0,col:0,offset:0};return{start:t,end:t}}getOpenViewLinePositionState(e){const t=Object.assign({line:0,col:0,offset:0},e?.start),s=Object.assign({line:0,col:0,offset:0},e?.end),{line:i,col:n}=t;return{eState:{startLoc:t,endLoc:s,line:i,cursor:{from:{line:i,ch:n},to:{line:i,ch:n}}}}}}class ye{useSimpleSearch;_searchDelegate;query;hasSearchTerm;constructor(e,t){this.useSimpleSearch=t,this.query=(e??"").trim().toLowerCase(),this.hasSearchTerm=!!this.query.length}static create(e,t=!1){return new ye(e,t)}searchWithFallback(e,t){let s,i=d.None,n=null,a=this.searchAndDownrankSecondaryMatch(e);if(a.match)n=a.match,i=d.Primary,s=e;else if(t){const{basename:e,path:o}=t;a=this.searchAndDownrankSecondaryMatch(e,o),a.isPrimary?(i=d.Basename,s=e):a.match&&(i=d.Path,s=o),n=a.match}return{matchType:i,matchText:s,match:n}}searchAndDownrankSecondaryMatch(e,t){let s=!1,i=null;return e&&(i=this.executeSearch(e),s=!!i),!i&&t&&(i=this.executeSearch(t),i&&(i.score-=1)),{isPrimary:s,match:i}}executeSearch(e){const t=this.getSearchDelegate();return t?t(e):null}getSearchDelegate(){if(!this._searchDelegate){const{query:e,useSimpleSearch:t}=this;this._searchDelegate=t?a.prepareSimpleSearch(e):a.prepareFuzzySearch(e)}return this._searchDelegate}}class be extends fe{getCommandString(e){return this.settings?.workspaceListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.WorkspaceList);return this.getEnabledWorkspacesPluginInstance()&&(e.mode=t.WorkspaceList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((e=>{let s=!0,a=null;i&&(({match:a}=n.searchWithFallback(e.id)),s=!!a),s&&t.push({type:l.WorkspaceList,item:e,match:a})})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-workspace"]),this.renderContent(t,e.item.id,e.match),s=!0),s}onChooseSuggestion(e,t){let s=!1;if(e){const{id:t}=e.item,i=this.getEnabledWorkspacesPluginInstance();i&&i.loadWorkspace(t),s=!0}return s}onNoResultsCreateAction(e,s){const i=this.getEnabledWorkspacesPluginInstance();if(i){const s=e.parsedCommand(t.WorkspaceList)?.parsedInput;i.saveWorkspace(s),i.setActiveWorkspace(s)}return!0}getItems(){const e=[],t=this.getEnabledWorkspacesPluginInstance()?.workspaces;return t&&Object.keys(t).forEach((t=>e.push({id:t,type:"workspaceInfo"}))),e.sort(((e,t)=>e.id.localeCompare(t.id)))}getEnabledWorkspacesPluginInstance(){return be.getEnabledWorkspacesPluginInstance(this.app)}static getEnabledWorkspacesPluginInstance(e){return I(e,"workspaces")}}class Se extends fe{getCommandString(e){return""}validateCommand(e,t,s,i,n){throw new Error("Method not implemented.")}getSuggestions(e){throw new Error("Method not implemented.")}renderSuggestion(e,t){let s=!1;return p(e)?s=this.renderFileSuggestion(e,t):f(e)&&(s=this.renderAliasSuggestion(e,t)),e?.downranked&&t.addClass("mod-downranked"),s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open file from SystemSuggestion ${i.path}`),s=!0}return s}renderFileSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-file"],null,i,n,a),this.renderOptionalIndicators(t,e),s=!0}return s}renderAliasSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-alias"],e.alias,i,n,a,!1);const o=this.renderOptionalIndicators(t,e);this.renderIndicator(o,["qsp-alias-indicator"],"lucide-forward"),s=!0}return s}addPropertiesToStandardSuggestions(e,t){const{match:s}=t;let i=d.None,n=null;s?.matches&&(f(t)?(i=d.Primary,n=t.alias):p(t)&&(i=d.Path,n=t.file.path)),t.matchType=i,t.matchText=n,fe.updateWorkspaceEnvListStatus(e,t)}static createUnresolvedSuggestion(e,t,s,i){const n={linktext:e,type:l.Unresolved,...t};return fe.applyMatchPriorityPreferences(n,s,i)}}class ke extends fe{getCommandString(e){return this.settings?.editorListCommand}validateCommand(e,s,i,n,a){e.mode=t.EditorList;const o=e.parsedCommand(t.EditorList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((s=>{const a=H(s);let o=!0,r={matchType:d.None,match:null};const l=this.getPreferredTitle(s,this.settings.preferredSourceForTitle);i&&(r=n.searchWithFallback(l,a),o=r.matchType!==d.None),o&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,a,r,l))})),i&&a.sortSearchResults(t)}return t}getPreferredTitle(e,t){return ke.getPreferredTitle(e,t,this.app.metadataCache,this.settings.frontmatterTitleProperty)}static getPreferredTitle(e,t,s,i){const n=H(e);let a=e.getDisplayText();if("H1"===t&&n){const e=ke.getFirstH1(n,s);e&&(a=a.replace(n.basename,e.heading))}else if("FrontMatter"===t&&n&&i){const e=s.getFileCache(n)?.frontmatter,t=fe.getFrontmatterProperty(e,i);t&&(a=a.replace(n.basename,t))}return a}getItems(){const{excludeViewTypes:e,includeSidePanelViewTypes:t,orderEditorListByAccessTime:s}=this.settings;return this.getOpenLeaves(e,t,{orderByAccessTime:s})}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a}=e,o=[d.None,d.Primary].includes(n);this.renderAsFileInfoPanel(t,["qsp-suggestion-editor"],e.preferredTitle,i,n,a,o),this.renderOptionalIndicators(t,e),s=!0}return s}onChooseSuggestion(e,t){let s=!1;return e&&(this.navigateToLeafOrOpenFile(t,e.file,"Unable to reopen existing editor in new Leaf.",null,e.item,null,!0),s=!0),s}createSuggestion(e,t,s,i,n){return ke.createSuggestion(e,t,s,this.settings,this.app.metadataCache,n,i)}static createSuggestion(e,t,s,i,n,a,o){o=o??{matchType:d.None,match:null,matchText:null};let r={item:t,file:s,preferredTitle:a=a??null,type:l.EditorList,...o};return r=fe.updateWorkspaceEnvListStatus(e,r),fe.applyMatchPriorityPreferences(r,i,n)}}class ve extends fe{getCommandString(e){return this.settings?.bookmarksListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.BookmarksList);return this.getEnabledBookmarksPluginInstance()&&(e.mode=t.BookmarksList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s),{allBookmarks:o}=this.getItems(e);o.forEach((s=>{let a=!0,o={matchType:d.None,match:null};i&&(o=n.searchWithFallback(s.bookmarkPath),a=o.matchType!==d.None),a&&t.push(this.createSuggestion(e.currentWorkspaceEnvList,s,o))})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;if(e&&ve.isBookmarksPluginFileItem(e.item)){const{file:i,matchType:n,match:a,bookmarkPath:o}=e;this.renderAsFileInfoPanel(t,["qsp-suggestion-bookmark"],o,i,n,a),this.renderOptionalIndicators(t,e),s=!0}return s}onChooseSuggestion(e,t){let s=!1;if(ve.isBookmarksPluginFileItem(e?.item)){const{file:i}=e,n=`Unable to open file from BookmarkSuggestion ${i?.path}`,a=this.getOpenViewState(e);this.navigateToLeafOrOpenFile(t,i,n,a),s=!0}return s}getPreferredViewLinePosition(e){if(e&&ve.isBookmarksPluginFileItem(e.item)){const t=this.getBookmarkSubpathPosition(e.file,e.item.subpath);if(t)return t}return super.getPreferredViewLinePosition(e)}getBookmarkSubpathPosition(e,t){if(!t)return null;const s=this.app.metadataCache.getFileCache(e),i=s?a.resolveSubpath(s,t):null;return"block"===i?.type?i.block.position:"heading"===i?.type?i.current.position:null}getPreferredTitle(e,t,s,i){let n=e.getItemTitle(t);if(s&&!t.title)if("H1"===i){const e=this.getFirstH1(s);e&&(n=n.replace(/^[^#]*/,e.heading))}else if("FrontMatter"===i){const e=this.app.metadataCache.getFileCache(s)?.frontmatter,t=fe.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty);t&&(n=n.replace(/^[^#]*/,t))}return n}getItems(e){const t=[],s=new Map,i=new Set,n=this.getEnabledBookmarksPluginInstance();if(n){const a=e?this.getActiveFacetIds(e):new Set,o=(e,r)=>{e?.forEach((e=>{if(ve.isBookmarksPluginGroupItem(e))o(e.items,`${r}${e.title}/`);else if(this.isFacetedWith(a,G[e.type])){let a;if(ve.isBookmarksPluginFileItem(e)){const t=this.getTFileByPath(e.path);if(t){a={item:e,bookmarkPath:null,file:t};const i=s.get(t)??[];i.push(a),s.set(t,i)}}else a={item:e,bookmarkPath:null,file:null},i.add(a);if(a){const s=this.getPreferredTitle(n,e,a.file,this.settings.preferredSourceForTitle);a.bookmarkPath=r+s,t.push(a)}}}))};o(n.items,"")}return{allBookmarks:t,fileBookmarks:s,nonFileBookmarks:i}}getEnabledBookmarksPluginInstance(){return I(this.app,"bookmarks")}createSuggestion(e,t,s){return ve.createSuggestion(e,t,this.settings,this.app.metadataCache,s)}static createSuggestion(e,t,s,i,n){let a={type:l.Bookmark,item:t.item,bookmarkPath:t.bookmarkPath,file:t.file,...n};return a=fe.updateWorkspaceEnvListStatus(e,a),fe.applyMatchPriorityPreferences(a,s,i)}static isBookmarksPluginFileItem(e){return m(e,"type","file")}static isBookmarksPluginGroupItem(e){return m(e,"type","group")}addPropertiesToStandardSuggestions(e,t){const{match:s,item:i}=t;let n=d.None,a=null;if(!t.file&&ve.isBookmarksPluginFileItem(i)){const e=i.path;t.file=this.getTFileByPath(e)}s?.matches&&(n=d.Primary,a=t.bookmarkPath),t.matchType=n,t.matchText=a,fe.updateWorkspaceEnvListStatus(e,t)}}const we={file:"lucide-file-text",text:"lucide-sticky-note",link:"lucide-globe",group:"create-group"},Ce={table:"lucide-table",list:"lucide-list",cards:"lucide-layout-grid"};class Ie extends fe{inputInfo;getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.symbolListActiveEditorCommand:t.symbolListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.SymbolList),r=this.getSourceInfoForSymbolOperation(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.SymbolList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}async getSuggestions(e){const s=[];if(e){this.inputInfo=e;const{query:i,hasSearchTerm:n}=e.parsedInputQuery,o=ye.create(i),r=e.parsedCommand(t.SymbolList);(await this.getItems(r.source,n)).forEach((e=>{let t=!0,i=null;if(n){const s=Ie.getSuggestionTextForSymbol(e);({match:i}=o.searchWithFallback(s)),t=!!i}if(t){const{file:t}=r.source;s.push({type:l.SymbolList,file:t,item:e,match:i})}})),n&&a.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,o=["qsp-suggestion-symbol"];Object.prototype.hasOwnProperty.call(i,"indentLevel")&&this.settings.symbolsInLineOrder&&!this.inputInfo?.parsedInputQuery?.hasSearchTerm&&o.push(`qsp-symbol-l${i.indentLevel}`),this.addClassesToSuggestionContainer(t,o);const{contentEl:r,titleEl:l}=fe.createContentStructureElements(t);Ie.renderSymbolContent(this.app,this.settings,l,i,n,a),this.renderHeadingBreadcrumbsInSymbolMode(r,i.symbol,n),this.addSymbolIndicator(i,t),s=!0}return s}onChooseSuggestion(e,t){return!!e&&(this.navigateAndCompleteSymbol(t,e),!0)}async navigateAndCompleteSymbol(e,s){const i=this.inputInfo.parsedCommand(),{leaf:n,file:a}=i.source,o=this.getOpenViewState(s),{item:r}=s;try{await this.navigateToLeafOrOpenFileAsync(e,a,o,n,t.SymbolList)}catch(e){return void A(`Unable to navigate to symbols for file ${a?.path}`,e)}if(Ie.isCanvasSymbolPayload(r))this.zoomToCanvasNode(this.getActiveLeaf().view,r.symbol);else if(Ie.isBaseViewSymbolPayload(r)){const e=r.symbol,t=s.file?.path,i=`${t}#${e.name}`;try{await this.app.workspace.openLinkText(i,t,!1)}catch(s){A(`Unable to navigate to Base view ${e.name} in file ${t}`,s)}}}reset(){this.inputInfo=null}getAvailableFacets(e){const i=e.parsedCommand(t.SymbolList),n=Ie.isBaseFile(i?.source?.file),a=Ie.isCanvasFile(i?.source?.file),o=this.getFacets(e.mode),r=new Set(Object.values($)),l=new Set(Object.values(j)),d=new Set(Object.values(s).filter((e=>isNaN(Number(e)))));return o.forEach((e=>{const{id:t}=e;e.isAvailable=n?r.has(t):a?l.has(t):d.has(t)})),o.filter((e=>e.isAvailable))}zoomToCanvasNode(e,t){if(Ie.isCanvasView(e)&&t){const s=e.canvas,i=s.nodes.get(t.id);s.selectOnly(i),s.zoomToSelection()}}getPreferredViewLinePosition(e){let t=super.getPreferredViewLinePosition();if(e?.item?.symbol){const{item:s}=e;if(!Ie.isCanvasSymbolPayload(s)&&!Ie.isBaseViewSymbolPayload(s)){t=s.symbol.position}}return t}getSourceInfoForSymbolOperation(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.SymbolList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}async getItems(e,t){let s=[],i=!1,n=!1;return t||({selectNearestHeading:n,symbolsInLineOrder:i}=this.settings),s=await this.getSymbolsFromSource(e,i),n&&Ie.FindNearestHeadingSymbol(s,e),s}static FindNearestHeadingSymbol(e,t){const s=t?.cursor?.line;if(s){let t=null;const i=e.filter((e=>S(e.symbol)));i.length&&(t=i.reduce(((e,t)=>{const{line:i}=t.symbol.position.start,n=e?e.symbol.position.start.line:-1;return e?i>n&&i<=s?t:e:i<=s?t:null}),null)),t&&(t.isSelected=!0)}}async getSymbolsFromSource(e,t){const{app:{metadataCache:i},inputInfo:n}=this,a=[];if(e?.file){const{file:o}=e,r=this.getActiveFacetIds(n);if(Ie.isBaseFile(o))await this.addBaseViewsFromSource(o,a,r);else if(Ie.isCanvasFile(o))await this.addCanvasSymbolsFromSource(o,a,r);else{const e=i.getFileCache(o);if(e){const i=(e=[],t)=>{this.shouldIncludeSymbol(t,r)&&e.forEach((e=>a.push({type:"symbolInfo",symbol:e,symbolType:t})))};i(e.headings,s.Heading),this.addTagsFromSource(e,a,r),this.addLinksFromSource(e,a,r),i(e.embeds,s.Embed),await this.addCalloutsFromSource(o,e.sections?.filter((e=>"callout"===e.type)),a,r),t&&Ie.orderSymbolsByLineNumber(a)}}}return a}shouldIncludeSymbol(e,t){let i=!1;return i="string"==typeof e?this.isFacetedWith(t,e):this.settings.isSymbolTypeEnabled(e)&&this.isFacetedWith(t,s[e]),i}async addCanvasSymbolsFromSource(e,t,i){let n;try{const t=await this.app.vault.cachedRead(e);n=JSON.parse(t).nodes}catch(t){O(`Error reading file to extract canvas node information. ${e.path} `,t)}Array.isArray(n)&&n.forEach((e=>{this.shouldIncludeSymbol(j[e.type],i)&&t.push({type:"symbolInfo",symbolType:s.CanvasNode,symbol:{...e}})}))}async addBaseViewsFromSource(e,t,i){let n;try{const t=await this.app.vault.cachedRead(e);n=a.parseYaml(t)}catch(t){return void O(`Error reading file to extract base view information. ${e.path} `,t)}n&&n?.views&&Array.isArray(n.views)&&n.views.forEach((e=>{const n=$[e.type];(n?this.shouldIncludeSymbol(n,i):0===i.size)&&t.push({type:"symbolInfo",symbolType:s.BaseView,symbol:{type:e.type,name:e.name}})}))}async addCalloutsFromSource(e,t,i,n){const{app:{vault:a}}=this;if(this.shouldIncludeSymbol(s.Callout,n)&&t?.length&&e){let n=null;try{n=await a.cachedRead(e)}catch(t){O(`Error reading file to extract callout information. ${e.path} `,t)}if(n)for(const e of t){const{start:t,end:a}=e.position,o=n.slice(t.offset,a.offset).match(/^> \[!([^\]]+)\][+-]?(.*?)(?:\n>|$)/);if(o){const t=o[1],n={calloutTitle:o[o.length-1].trim(),calloutType:t,...e};i.push({type:"symbolInfo",symbolType:s.Callout,symbol:n})}}}}addLinksFromSource(e,t,i){const{settings:n}=this;if(!this.shouldIncludeSymbol(s.Link,i))return;const a=e?.links??[],o=e?.frontmatterLinks??[],r=Ie.getFrontmatterPositionOrZero(e),l=[...a,...o.map((e=>{const t={link:e.link,original:e.original,position:r};return e.displayText&&(t.displayText=e.displayText),t}))];for(const e of l){const i=B(e);(n.excludeLinkSubTypes&i)===i||t.push({type:"symbolInfo",symbol:e,symbolType:s.Link})}}addTagsFromSource(e,t,i){if(!this.shouldIncludeSymbol(s.Tag,i))return;const n=new Set,a=e.tags??[];for(const e of a)n.add(e.tag.toLowerCase()),t.push({type:"symbolInfo",symbol:e,symbolType:s.Tag});const o=e.frontmatter;if(o){const i=h.getTags(o),a=Ie.getFrontmatterPositionOrZero(e);for(const e of i){const i=e.startsWith("#")?e:`#${e}`;if(n.has(i.toLowerCase()))continue;const o={tag:i,position:a};t.push({type:"symbolInfo",symbol:o,symbolType:s.Tag})}}}static orderSymbolsByLineNumber(e){const t=e.sort(((e,t)=>{const{start:s}=e.symbol.position,{start:i}=t.symbol.position,n=s.line-i.line;return 0===n?s.col-i.col:n}));let s=0;return t.forEach((e=>{let t=0;S(e.symbol)?(s=e.symbol.level,t=e.symbol.level-1):t=s,e.indentLevel=t})),t}static getMarkdownContentForSymbol(e,t){const{symbol:s}=e;if(S(s))return s.heading.replace(/^(\d+)\./,"$1\\.");if(k(s))return s.tag;if(v(s))return s.calloutTitle;const i=s;return i.original?i.original:null}static renderSymbolContent(e,t,s,i,n,o,r){const l=Ie.getMarkdownContentForSymbol(i,n);if((r??(null!==l&&t.shouldRenderSymbolAsHTML(i.symbolType)))&&null!==l)fe.renderMarkdownContentAsync(e,s,l,n.path);else{const e=Ie.getSuggestionTextForSymbol(i);a.renderResults(s,e,o)}}static getSuggestionTextForSymbol(e){const{symbol:t}=e;let s;if(S(t))s=t.heading;else if(k(t))s=t.tag.slice(1);else if(v(t))s=t.calloutTitle;else if(Ie.isCanvasSymbolPayload(e))s=Ie.getSuggestionTextForCanvasNode(e.symbol);else if(Ie.isBaseViewSymbolPayload(e))s=e.symbol.name;else{const e=t;({link:s}=e);const{displayText:i}=e;i&&i!==s&&(s+=`|${i}`)}return s}static getSuggestionTextForCanvasNode(e){let t="";const s={file:()=>e.file,text:()=>e.text,link:()=>e.url,group:()=>e.label}[e?.type];return s&&(t=s()),t}addSymbolIndicator(e,t){const{symbolType:s,symbol:i}=e,n=["qsp-symbol-indicator"],l=this.createFlairContainer(t);if(v(i)){n.push("suggestion-flair","callout","callout-icon","svg-icon");const e=l.createSpan({cls:n,attr:{"data-callout":i.calloutType}}),t=e.getCssPropertyValue("--callout-icon");a.setIcon(e,t)}else if(Ie.isCanvasSymbolPayload(e)){const t=we[e.symbol.type];this.renderIndicator(l,n,t,null)}else if(Ie.isBaseViewSymbolPayload(e)){const t=e.symbol,s=Ce[t.type]||Ce.table;this.renderIndicator(l,n,s,null)}else{let e;e=S(i)?r[i.level]:o[s],this.renderIndicator(l,n,null,e)}}renderHeadingBreadcrumbsInSymbolMode(e,t,s){S(t)&&this.renderHeadingBreadcrumbs(e,t,s,this.settings.showHeadingBreadcrumbsInSymbolMode)}static getFrontmatterPositionOrZero(e){return e.frontmatterPosition??{start:{line:0,col:0,offset:0},end:{line:0,col:0,offset:0}}}static isCanvasSymbolPayload(e){return e.symbolType===s.CanvasNode}static isBaseViewSymbolPayload(e){return e.symbolType===s.BaseView}static isCanvasFile(e){return"canvas"===e?.extension}static isCanvasView(e){return"canvas"===e?.getViewType()}static isBaseFile(e){return"base"===e?.extension}static isBaseView(e){return"bases"===e?.getViewType()}}class Le extends fe{getCommandString(e){return this.settings?.headingsListCommand}validateCommand(e,s,i,n,a){e.mode=t.HeadingsList;const o=e.parsedCommand(t.HeadingsList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}onChooseSuggestion(e,t){let s=!1;if(e){const i=this.getOpenViewState(e);this.navigateToLeafOrOpenFile(t,e.file,"Unable to navigate to heading for file.",i),s=!0}return s}getPreferredViewLinePosition(e){return e?.item?.position}renderSuggestion(e,t){let s=!1;if(e){const{item:i,file:n,match:a}=e,{app:o,settings:l}=this;this.addClassesToSuggestionContainer(t,["qsp-suggestion-headings",`qsp-headings-l${i.level}`]);const{contentEl:d,titleEl:c}=fe.createContentStructureElements(t);Le.renderHeadingContent(o,l,c,i,n,a),this.renderHeadingBreadcrumbs(d,i,n),this.renderTags(d,n),this.renderPath(d,n);const h=this.createFlairContainer(t);this.renderOptionalIndicators(t,e,h),this.renderIndicator(h,["qsp-headings-indicator"],null,r[i.level]),e.downranked&&t.addClass("mod-downranked"),s=!0}return s}static renderHeadingContent(e,t,i,n,a,o,r){const l={type:"symbolInfo",symbol:n,symbolType:s.Heading};Ie.renderSymbolContent(e,t,i,l,a,o,r)}getAvailableFacets(e){const{settings:{shouldSearchHeadings:t,shouldSearchBookmarks:s,shouldSearchFilenames:i,shouldSearchRecentFiles:n,builtInSystemOptions:{showAttachments:a,showAllFileTypes:o}}}=this,r=a||o,l={[J.RecentFiles]:n,[J.Bookmarks]:s,[J.Filenames]:i,[J.Headings]:t,[J.ExternalFiles]:r};return this.getFacets(e.mode).filter((e=>(Object.prototype.hasOwnProperty.call(l,e.id)&&(e.isAvailable=l[e.id]),e.isAvailable)))}getSuggestions(e){let t=[];if(e){const{hasSearchTerm:s}=e.parsedInputQuery,{settings:i}=this,n=this.getActiveFacetIds(e),o=!!n.size;if(s||o){const{limit:s}=i,{app:{vault:o}}=this,r={headings:i.shouldSearchHeadings,allHeadings:i.searchAllHeadings,aliases:i.shouldShowAlias,bookmarks:i.shouldSearchBookmarks,filename:i.shouldSearchFilenames,filenameAsFallback:!i.strictHeadingsOnly,unresolved:!i.showExistingOnly};this.getItems([o.getRoot()],e,t,n,r),a.sortSearchResults(t),s>0&&t.length>s&&(t=t.slice(0,s))}else this.getSuggestionsForEditorsAndRecentFiles(e,t,new Set,{editors:!0,recentFiles:i.shouldSearchRecentFiles})}return t}getItems(e,t,s,i,n){const a=!!i.size,o=ye.create(t.parsedInputQuery.query);this.getSuggestionsForEditorsAndRecentFiles(t,s,i,{editors:!1,recentFiles:!1});const r={fileBookmarks:n.bookmarks,nonFileBookmarks:n.bookmarks};this.getSuggestionsForBookmarks(t,o,s,i,r);const l={headings:n.headings,allHeadings:n.allHeadings,aliases:n.aliases,filename:n.filename,filenameAsFallback:n.filenameAsFallback};this.getSuggestionForFiles(t,o,e,s,i,l),n.unresolved&&!a&&this.addUnresolvedSuggestions(s,o)}getSuggestionsForBookmarks(e,t,s,i,n){const a=!!i.size,{fileBookmarks:o,nonFileBookmarks:r}=e.currentWorkspaceEnvList;if(a){const e=i.has(J.Bookmarks);n=Object.assign(n,{fileBookmarks:e,nonFileBookmarks:e})}const l=i=>{for(const n of i)this.addBookmarkSuggestion(e,s,t,n)};n.fileBookmarks&&o.forEach((e=>{l(e)})),n.nonFileBookmarks&&l(r)}getSuggestionForFiles(e,t,s,i,n,a){if(!!n.size){const e=this.isFacetedWith(n,J.Headings),t=this.isFacetedWith(n,J.ExternalFiles)||this.isFacetedWith(n,J.Filenames);let s=!1,i=!1;e&&(s=!0===a.allHeadings,i=!0===a.filenameAsFallback),a=Object.assign(a,{headings:e,aliases:!1,filename:t,allHeadings:s,filenameAsFallback:i})}else a=Object.assign({headings:!0,allHeadings:!0,aliases:!0,filename:!0,filenameAsFallback:!0},a);if([a.headings,a.aliases,a.filename].some((e=>!0===e))){const{excludeFolders:o}=this.settings,r=M(o);let l=Array.prototype.concat(s);for(;l.length>0;){const s=l.pop();w(s)?this.shouldIncludeFile(s,n)&&this.addSuggestionsForFile(e,t,i,s,a):C(s)&&!r(s.path)&&(l=l.concat(s.children))}}}addSuggestionsForFile(e,t,s,i,n){let a=!1;n.headings&&(a=this.addHeadingSuggestions(e,t,s,i,n.allHeadings)),(n.filename||!a&&n.filenameAsFallback)&&this.addFileSuggestions(e,t,s,i),n.aliases&&this.addAliasSuggestions(e,t,s,i)}shouldIncludeFile(e,t=new Set){let s=!1;if(e){const i=new Set(["md","canvas"]),{extension:n}=e,{app:{viewRegistry:a,metadataCache:o},settings:{excludeObsidianIgnoredFiles:r,fileExtAllowList:l,builtInSystemOptions:{showAttachments:d,showAllFileTypes:c}}}=this;if(!(r&&o.isUserIgnored(e.path)))if(t.has(J.ExternalFiles)){const e=d||c;s=!i.has(n)&&e}else{s=this.isExternalFileTypeAllowed(e,a,d,c,l)||i.has(n)}}return s}isExternalFileTypeAllowed(e,t,s,i,n){const{extension:a}=e;let o=t.isExtensionRegistered(a)?s:i;if(!o){o=new Set(n).has(a)}return o}addAliasSuggestions(e,t,s,i){const{metadataCache:n}=this.app,a=n.getFileCache(i)?.frontmatter;if(a){const n=h.getAliases(a);let o=n.length;for(;o--;){const a=n[o],{match:r}=t.searchWithFallback(a);r&&s.push(this.createAliasSuggestion(e,a,i,r))}}}addFileSuggestions(e,t,s,i){const{match:n,matchType:a,matchText:o}=t.searchWithFallback(null,i);n&&s.push(this.createFileSuggestion(e,i,n,a,o))}addBookmarkSuggestion(e,t,s,i){const n=s.searchWithFallback(i.bookmarkPath);if(n.match){const s=ve.createSuggestion(e.currentWorkspaceEnvList,i,this.settings,this.app.metadataCache,n);t.push(s)}}addHeadingSuggestions(e,t,s,i,n){const{metadataCache:a}=this.app,o=a.getFileCache(i)?.headings??[];let r=null,l=!1,d=o.length;for(;d--;){const a=o[d];let c=!1;if(n&&(c=this.matchAndPushHeading(e,t,s,i,a)),1===a.level){const{line:e}=a.position.start;(null===r||e<r.position.start.line)&&(r=a,l=c)}}return!n&&r&&(l=this.matchAndPushHeading(e,t,s,i,r)),l}matchAndPushHeading(e,t,s,i,n){const{match:a}=t.searchWithFallback(n.heading);return a&&s.push(this.createHeadingSuggestion(e,n,i,a)),!!a}addUnresolvedSuggestions(e,t){const{metadataCache:s}=this.app,{unresolvedLinks:i}=s,n=new Set,a=Object.keys(i);let o=a.length;for(;o--;){const e=a[o],t=Object.keys(i[e]);let s=t.length;for(;s--;)n.add(t[s])}const r=Array.from(n);for(o=r.length;o--;){const i=r[o],n=t.searchWithFallback(i);n.matchType!==d.None&&e.push(Se.createUnresolvedSuggestion(i,n,this.settings,s))}}createAliasSuggestion(e,t,s,i){let n={alias:t,file:s,...this.createSearchMatch(i,d.Primary,t),type:l.Alias};return n=fe.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,n),this.applyMatchPriorityPreferences(n)}createFileSuggestion(e,t,s,i,n){let a={file:t,match:s,matchType:i,matchText:n,type:l.File};return a=fe.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,a),this.applyMatchPriorityPreferences(a)}createHeadingSuggestion(e,t,s,i){let n={item:t,file:s,...this.createSearchMatch(i,d.Primary,t.heading),type:l.HeadingsList};return n=fe.updateWorkspaceEnvListStatus(e.currentWorkspaceEnvList,n),this.applyMatchPriorityPreferences(n)}createSearchMatch(e,t,s){let i=d.None,n=null;return e&&(i=t,n=s),{match:e,matchType:i,matchText:n}}addRecentFilesSuggestions(e,t,s,i){const n=this.getFirstH1(e),{match:a,matchType:o,matchText:r}=s.searchWithFallback(n?.heading,e);if(a){let s;s=o===d.Primary?this.createHeadingSuggestion(t,n,e,a):this.createFileSuggestion(t,e,a,o,r),i.push(s)}}addOpenEditorSuggestions(e,t,s,i){const n=H(e),{settings:a,app:{metadataCache:o}}=this,r=ke.getPreferredTitle(e,a.preferredSourceForTitle,o,a.frontmatterTitleProperty),l=s.searchWithFallback(r,n);if(l.match){const s=ke.createSuggestion(t.currentWorkspaceEnvList,e,n,a,o,r,l);i.push(s)}}getSuggestionsForEditorsAndRecentFiles(e,t,s,i){const{query:n}=e.parsedInputQuery,a=ye.create(n);if((i=s.has(J.RecentFiles)?Object.assign(i,{editors:!1,recentFiles:!0}):Object.assign({editors:!0,recentFiles:!0},i)).editors){const s=e.currentWorkspaceEnvList?.openWorkspaceLeaves;s?.forEach((s=>{this.addOpenEditorSuggestions(s,e,a,t)}))}if(i.recentFiles){const i=e.currentWorkspaceEnvList?.mostRecentFiles;i?.forEach((i=>{this.shouldIncludeFile(i,s)&&this.addRecentFilesSuggestions(i,e,a,t)}))}}onNoResultsCreateAction(e,s){const i=e.parsedCommand(t.HeadingsList)?.parsedInput;return this.createFile(i,s),!0}}class Te extends fe{static recentlyUsedCommandIds=[];getCommandString(e){return this.settings?.commandListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.CommandList);return this.getEnabledCommandPalettePluginInstance()&&(e.mode=t.CommandList,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems(e,i).forEach((e=>{let s=!0,a=null;i&&(({match:a}=n.searchWithFallback(e.cmd.name)),s=!!a),s&&t.push(this.createSuggestion(e,a))})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;if(e){const{item:i,match:n,isPinned:a,isRecent:o}=e;this.addClassesToSuggestionContainer(t,["qsp-suggestion-command"]),this.renderContent(t,i.name,n);const r=this.createFlairContainer(t);this.renderHotkeyForCommand(i.id,this.app,r),i.icon&&this.renderIndicator(r,[],i.icon),a?this.renderIndicator(r,[],"filled-pin"):o&&this.renderOptionalIndicators(t,e,r),s=!0}return s}renderHotkeyForCommand(e,t,s){try{const{hotkeyManager:i}=t;if(i.getHotkeys(e)||i.getDefaultHotkeys(e)){const t=i.printHotkeyForCommand(e);t?.length&&s.createEl("kbd",{cls:"suggestion-hotkey",text:t})}}catch(t){O("Error rendering hotkey for command id: ",e,t)}}onChooseSuggestion(e){let t=!1;if(e){const{item:s}=e;this.app.commands.executeCommandById(s.id),this.saveUsageToList(s.id,Te.recentlyUsedCommandIds),t=!0}return t}saveUsageToList(e,t){if(t){const s=t.indexOf(e);s>-1&&t.splice(s,1),t.unshift(e),t.splice(this.settings.maxRecentCommands)}}getItems(e,t){let s=[];const i=this.getActiveFacetIds(e);if(!!i.size)s=this.getPinnedAndRecentCommands(i);else if(t)s=this.getAllCommands();else{const e=this.getPinnedAndRecentCommands(i);s=e.length?e:this.getAllCommands()}return s}getPinnedAndRecentCommands(e){const t=[],s=this.getPinnedCommandIds(),i=this.getRecentCommandIds(),n=e=>{let t=null;const n=this.app.commands.findCommand(e);return n&&(t={isPinned:s.has(e),isRecent:i.has(e),cmd:n}),t},a=(s,i)=>{this.isFacetedWith(e,s)&&i.forEach((e=>{const s=n(e);s&&t.push(s)}))};a(z.Pinned,Array.from(s));const o=this.isFacetedWith(e,z.Pinned),r=Array.from(i).filter((e=>!o||o&&!s.has(e)));return"asc"===this.settings.recentCommandDisplayOrder&&r.reverse(),a(z.Recent,r),t}getAllCommands(){const e=this.getPinnedCommandIds(),t=this.getRecentCommandIds();return this.app.commands.listCommands()?.sort(((e,t)=>e.name.localeCompare(t.name))).map((s=>({isPinned:e.has(s.id),isRecent:t.has(s.id),cmd:s})))}getPinnedCommandIds(){const e=this.getEnabledCommandPalettePluginInstance()?.options?.pinned;return new Set(e??[])}getRecentCommandIds(){return new Set(Te.recentlyUsedCommandIds)}createSuggestion(e,t){const{cmd:s,isPinned:i,isRecent:n}=e,a={type:l.CommandList,item:s,isPinned:i,isRecent:n,match:t};return this.applyMatchPriorityPreferences(a)}getEnabledCommandPalettePluginInstance(){return Te.getEnabledCommandPalettePluginInstance(this.app)}static getEnabledCommandPalettePluginInstance(e){return I(e,"command-palette")}}class Ee extends fe{inputInfo;getCommandString(e){const{settings:t}=this;return e?.useActiveEditorAsSource?t.relatedItemsListActiveEditorCommand:t.relatedItemsListCommand}validateCommand(e,s,i,n,a){const o=e.parsedCommand(t.RelatedItemsList),r=this.getSourceInfo(n,a,0===s,e.sessionOpts);return r&&(e.mode=t.RelatedItemsList,o.source=r,o.index=s,o.parsedInput=i,o.isValidated=!0),o}getSuggestions(e){const s=[];if(e){this.inputInfo=e;const i=ye.create(e.parsedInputQuery.query),n=e.parsedCommand(t.RelatedItemsList);this.getItems(n.source,e).forEach((t=>{const n=this.searchAndCreateSuggestion(e,i,t);n&&s.push(n)})),i.hasSearchTerm&&a.sortSearchResults(s)}return s}renderSuggestion(e,t){let s=!1;if(e){const{file:i,matchType:n,match:a,item:o}=e,r=new Map([[c.Backlink,"links-coming-in"],[c.DiskLocation,"folder-tree"],[c.OutgoingLink,"links-going-out"]]);t.setAttribute("data-relation-type",o.relationType),this.renderAsFileInfoPanel(t,["qsp-suggestion-related"],e.preferredTitle,i,n,a);const l=this.renderOptionalIndicators(t,e);e.item.count&&this.renderIndicator(l,[],null,`${e.item.count}`),this.renderIndicator(l,["qsp-related-indicator"],r.get(o.relationType)),s=!0}return s}onChooseSuggestion(e,t){let s=!1;if(e){const{file:i}=e;this.navigateToLeafOrOpenFile(t,i,`Unable to open related file ${i.path}`),s=!0}return s}getPreferredTitle(e,t){let s=null;const{file:i,unresolvedText:n}=e;if(i){if("H1"===t)s=this.getFirstH1(i)?.heading??null;else if("FrontMatter"===t){const e=this.app.metadataCache.getFileCache(i)?.frontmatter;s=fe.getFrontmatterProperty(e,this.settings.frontmatterTitleProperty)}}else{!!n?.length&&(s=n)}return s}searchAndCreateSuggestion(e,t,s){const{file:i,unresolvedText:n}=s;let a={matchType:d.None,match:null};const o=null===i&&n?.length,{currentWorkspaceEnvList:r}=e,{settings:l,app:{metadataCache:c}}=this,h=this.getPreferredTitle(s,l.preferredSourceForTitle);return t.hasSearchTerm&&(a=t.searchWithFallback(h,i),a.matchType===d.None)?null:o?Se.createUnresolvedSuggestion(h,a,l,c):this.createSuggestion(r,s,a,h)}getItems(e,t){const s=[],{metadataCache:i}=this.app,{file:n,suggestion:a}=e,o=new Set(this.settings.enabledRelatedItems),r=this.getActiveFacetIds(t),l=e=>o.has(e)&&this.isFacetedWith(r,e);if(l(c.Backlink)){let e=n?.path,t=i.resolvedLinks;y(a)&&(e=a.linktext,t=i.unresolvedLinks),this.addBacklinks(e,t,s)}return l(c.DiskLocation)&&this.addRelatedDiskFiles(n,s),l(c.OutgoingLink)&&this.addOutgoingLinks(n,s),s}addRelatedDiskFiles(e,t){const{excludeRelatedFolders:s,excludeOpenRelatedFiles:i}=this.settings;if(e){const n=M(s);let a=[...e.parent.children];for(;a.length>0;){const s=a.pop();if(w(s)){s===e||i&&!!this.findMatchingLeaf(s).leaf||t.push({file:s,relationType:c.DiskLocation})}else C(s)&&!n(s.path)&&(a=a.concat(s.children))}}}addOutgoingLinks(e,t){if(!e)return;const{metadataCache:s}=this.app,i=e.path,n=s.resolvedLinks[i]??{};for(const[e,a]of Object.entries(n)){if(e===i)continue;const n=s.getFirstLinkpathDest(e,i);n&&t.push({file:n,relationType:c.OutgoingLink,count:a})}const a=s.unresolvedLinks[i]??{};for(const[e,s]of Object.entries(a))t.push({file:null,relationType:c.OutgoingLink,unresolvedText:e,count:s})}addBacklinks(e,t,s){for(const[i,n]of Object.entries(t))if(i!==e&&Object.prototype.hasOwnProperty.call(n,e)){const t=n[e],a=this.getTFileByPath(i);a&&s.push({count:t,file:a,relationType:c.Backlink})}}reset(){this.inputInfo=null}getSourceInfo(e,s,i,n){const a=this.inputInfo;let o=null,r=t.Standard;a&&(o=a.parsedCommand().source,r=a.mode);const l=r===t.RelatedItemsList&&!!o,d=this.getEditorInfo(s),c=this.getSuggestionInfo(e);!c.isValidSource&&y(e)&&(c.isValidSource=!0);let h=null;return l?h=o:c.isValidSource&&!n.useActiveEditorAsSource?h=c:d.isValidSource&&i&&(h=d),h}createSuggestion(e,t,s,i){let n={item:t,file:t?.file,type:l.RelatedItemsList,preferredTitle:i,...s};return n=fe.updateWorkspaceEnvListStatus(e,n),this.applyMatchPriorityPreferences(n)}}class Fe extends fe{mobileVaultChooserMarker={type:l.VaultList,match:null,item:null,pathSegments:null};getCommandString(e){return this.settings?.vaultListCommand}validateCommand(e,s,i,n,a){e.mode=t.VaultList;const o=e.parsedCommand(t.VaultList);return o.index=s,o.parsedInput=i,o.isValidated=!0,o}getSuggestions(e){const t=[];if(e){const{query:s,hasSearchTerm:i}=e.parsedInputQuery,n=ye.create(s);this.getItems().forEach((e=>{let s=!0;if(i){const t=n.searchWithFallback(null,e.pathSegments);Object.assign(e,t),s=!!t.match}s&&t.push(e)})),i&&a.sortSearchResults(t)}return t}renderSuggestion(e,t){let s=!1;return e&&(this.addClassesToSuggestionContainer(t,["qsp-suggestion-vault"]),s=!0,a.Platform.isDesktop?this.renderVaultSuggestion(e,t):e===this.mobileVaultChooserMarker&&this.renderMobileHintSuggestion(t)),s}renderMobileHintSuggestion(e){this.renderContent(e,"Show mobile vault chooser",null)}renderVaultSuggestion(e,t){const{pathSegments:s,matchType:i}=e;let{match:n}=e,o=null;i===d.Basename&&(o=n,n=null);const r=this.renderContent(t,s.basename,o).createDiv({cls:["suggestion-note","qsp-note"]}),l=r.createSpan({cls:["qsp-path-indicator"]}),c=r.createSpan({cls:"qsp-path"});a.setIcon(l,"folder"),a.renderResults(c,s.path,n)}onChooseSuggestion(e,t){let s=!1;return e&&(a.Platform.isDesktop?(this.openVaultOnDesktop(e.pathSegments?.path),s=!0):e===this.mobileVaultChooserMarker&&(this.app.openVaultChooser(),s=!0)),s}getItems(){const e=[];if(a.Platform.isDesktop)try{const t=this.getVaultListDataOnDesktop();for(const[s,{path:i,open:n}]of Object.entries(t)){const t=x(i),a={type:l.VaultList,match:null,item:s,isOpen:!!n,pathSegments:{basename:t,path:i}};e.push(a)}}catch(e){O("Error parsing vault data. ",e)}else e.push(this.mobileVaultChooserMarker);return e.sort(((e,t)=>e.pathSegments.basename.localeCompare(t.pathSegments.basename)))}getIpcRenderer(){if(!a.Platform.isDesktop)return null;try{return window.require("electron").ipcRenderer}catch{return null}}openVaultOnDesktop(e){const t=this.getIpcRenderer();if(t)try{t.sendSync("vault-open",e,!1)}catch(t){A(`Error opening vault with path: ${e} `,t)}}getVaultListDataOnDesktop(){let e=null;const t=this.getIpcRenderer();if(t)try{e=t.sendSync("vault-list")}catch(e){A("Error retrieving list of available vaults.",e)}return e}}class xe{app;config;static instance;instanceCache=new Map;modeToHandlerClass=new Map;suggestionTypeToMode=new Map;cmdStrToMode=new Map;sourcedHandlerModes=new Set;constructor(e,t,s){this.app=e,this.config=t;for(const e of s)e.handlerClass&&(this.modeToHandlerClass.set(e.mode,e.handlerClass),this.mapSuggestionTypesToMode(e),this.mapCommandStrToMode(e),this.registerSourcedHandler(e))}static initialize(e,t,s){this.instance?P("HandlerRegistry already initialized."):this.instance=new xe(e,t,s)}static reset(){this.instance=null}static getInstance(){return this.instance??null}getHandler(e){let t=null;const s=this.resolveMode(e);if(s)if(this.instanceCache.has(s))t=this.instanceCache.get(s)??null;else{const e=this.modeToHandlerClass.get(s);if(e){const i=new e(this.app,this.config);this.instanceCache.set(s,i),t=i}}return t}resetSourcedHandlers(e){const t=new Set(e);for(const e of this.sourcedHandlerModes){const s=this.instanceCache.get(e);s&&!t.has(s)&&s.reset()}}mapSuggestionTypesToMode(e){e.ownSuggestionTypes?.forEach((t=>{this.suggestionTypeToMode.set(t,e.mode)}))}mapCommandStrToMode(e){const t=e.parserCommand?.getCommandStr();t?.length&&this.cmdStrToMode.set(t,e.mode)}registerSourcedHandler(e){"sourced"===e.parserCommand?.type&&this.sourcedHandlerModes.add(e.mode)}resolveMode(e){let s;return"number"==typeof e&&Object.values(t).includes(e)?s=e:m(e,"type")?s=this.suggestionTypeToMode.get(e.type):"string"==typeof e&&(s=this.cmdStrToMode.get(e)),s}}class Ae{commandMap=new Map;escapeCmdChar;handlerRegistry;constructor(e,t,s){this.handlerRegistry=e,this.escapeCmdChar=t.escapeCmdChar,this.commandMap=this.buildCommandMap(s)}parseInputForMode(e,s,i){const{cleanInput:n,resolvedCommands:a}=this.parse(e.inputText);e.cleanInput=n;this.findFirstValidCommand(a,e,s,i)||(this.handlerRegistry.resetSourcedHandlers(),e.mode=t.Standard)}parse(e){let t="";const s=[],i=this.escapeCmdChar.length;let n=0;for(;n<e.length;){if(e.startsWith(this.escapeCmdChar,n)){const s=this.findCommandMatch(e,n+i);if(s){t+=s.cmdStr,n+=i+s.cmdStr.length;continue}}const a=this.findCommandMatch(e,n);a?(s.push({...a,indexInCleanInput:t.length}),t+=a.cmdStr,n+=a.cmdStr.length):(t+=e[n],n+=1)}return{cleanInput:t,resolvedCommands:this.resolveCommandPrecedence(s,t)}}buildCommandMap(e){const t=new Map;for(const s of e){const e=s.parserCommand.getCommandStr()??"";if(e.length>0){const i=e[0];t.has(i)||t.set(i,[]),t.get(i)?.push({cmdDef:s,cmdStr:e})}}for(const e of t.values())e.sort(((e,t)=>t.cmdStr.length-e.cmdStr.length));return t}findCommandMatch(e,t){const s=this.commandMap.get(e[t]);if(!s)return null;for(const i of s)if(e.startsWith(i.cmdStr,t))return i;return null}resolveCommandPrecedence(e,t){const s=[];let i;for(const n of e){const e=n.indexInCleanInput+n.cmdStr.length,a=t.substring(e),o={cmdDef:n.cmdDef,cmdStr:n.cmdStr,indexInCleanInput:n.indexInCleanInput,filterText:a},r=n.cmdDef.parserCommand.type;"prefix"!==r||0!==n.indexInCleanInput||i?"sourced"===r&&s.push(o):i=o}return s.sort(((e,t)=>e.indexInCleanInput-t.indexInCleanInput)),i?[...s,i]:s}findFirstValidCommand(e,t,s,i){for(const n of e){const e=this.handlerRegistry.getHandler(n.cmdDef.mode);if(!e)continue;t.sessionOpts.useActiveEditorAsSource=n.cmdDef.parserCommand.useActiveEditorAsSource;if(e.validateCommand(t,n.indexInCleanInput,n.filterText,s,i).isValidated){const t="sourced"===n.cmdDef.parserCommand.type?[e]:[];return this.handlerRegistry.resetSourcedHandlers(t),!0}}return!1}}const Oe={};class Pe{app;settings;exKeymap;_inputInfo;get inputInfo(){return this._inputInfo}get previousInputHistory(){return Oe}_handlerRegistry;get handlerRegistry(){return this._handlerRegistry}_inputParser;get inputParser(){return this._inputParser}debouncedGetSuggestions;workspaceEnvList=null;sessionOpts={};noResultActionModes=[t.HeadingsList,t.WorkspaceList];constructor(e,s,i){this.app=e,this.settings=s,this.exKeymap=i;const n=(o=s,[{commandId:"switcher-plus:open",commandName:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",handlerClass:Se,ownSuggestionTypes:[l.Alias,l.File],parserCommand:{type:"none",getCommandStr:()=>""}},{commandId:"switcher-plus:open-editors",commandName:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",handlerClass:ke,ownSuggestionTypes:[l.EditorList],parserCommand:{type:"prefix",getCommandStr:()=>o.editorListCommand}},{commandId:"switcher-plus:open-symbols",commandName:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Ie,ownSuggestionTypes:[l.SymbolList],parserCommand:{type:"sourced",getCommandStr:()=>o.symbolListCommand}},{commandId:"switcher-plus:open-symbols-active",commandName:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",handlerClass:Ie,parserCommand:{type:"prefix",getCommandStr:()=>o.symbolListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-workspaces",commandName:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",handlerClass:be,ownSuggestionTypes:[l.WorkspaceList],parserCommand:{type:"prefix",getCommandStr:()=>o.workspaceListCommand}},{commandId:"switcher-plus:open-headings",commandName:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",handlerClass:Le,ownSuggestionTypes:[l.HeadingsList],parserCommand:{type:"prefix",getCommandStr:()=>o.headingsListCommand}},{commandId:"switcher-plus:open-starred",commandName:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",handlerClass:ve,ownSuggestionTypes:[l.Bookmark],parserCommand:{type:"prefix",getCommandStr:()=>o.bookmarksListCommand}},{commandId:"switcher-plus:open-commands",commandName:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",handlerClass:Te,ownSuggestionTypes:[l.CommandList],parserCommand:{type:"prefix",getCommandStr:()=>o.commandListCommand}},{commandId:"switcher-plus:open-related-items",commandName:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:Ee,ownSuggestionTypes:[l.RelatedItemsList],parserCommand:{type:"sourced",getCommandStr:()=>o.relatedItemsListCommand}},{commandId:"switcher-plus:open-related-items-active",commandName:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",handlerClass:Ee,parserCommand:{type:"prefix",getCommandStr:()=>o.relatedItemsListActiveEditorCommand,useActiveEditorAsSource:!0}},{commandId:"switcher-plus:open-vaults",commandName:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",handlerClass:Fe,ownSuggestionTypes:[l.VaultList],parserCommand:{type:"prefix",getCommandStr:()=>o.vaultListCommand}}]);var o;xe.getInstance()||xe.initialize(e,s,n),this._handlerRegistry=xe.getInstance(),this._inputParser=new Ae(this._handlerRegistry,s,n),this.debouncedGetSuggestions=a.debounce(this.getSuggestions.bind(this),s.headingsSearchDebounceMilli,!0),this.reset()}onOpen(){const{app:e,exKeymap:t,handlerRegistry:s,settings:i}=this;t.isOpen=!0,i.quickFilters?.shouldResetActiveFacets&&Object.values(i.quickFilters.facetList).forEach((e=>e.isActive=!1)),this.workspaceEnvList=this.buildWorkspaceEnvList(e.workspace,e.vault,e.viewRegistry,s,i)}onClose(){this.exKeymap.isOpen=!1,q.unload()}setSessionOpenMode(e,t){this.reset(),e?.setSuggestions([]),this.sessionOpts=Object.assign({},t)}setInitialInputForSession(e){const{mode:s}=this.sessionOpts;if(!s)return;this.sessionOpts.mode=null;const i=s===t.Standard?this.previousInputHistory[s]?.inputText:this.previousInputHistory[s]?.parsedCommand(s)?.parsedInput,n=this.handlerRegistry.getHandler(s),a=s!==t.Standard?n.getCommandString(this.sessionOpts):"";if((s===t.CommandList&&this.settings.preserveCommandPaletteLastInput||s!==t.CommandList&&this.settings.preserveQuickSwitcherLastInput)&&i?.length){e.value=a+i;const t=a?.length??0;e.setSelectionRange(t,e.value.length)}else a&&(e.value=a)}updateSuggestions(e,s,i){const{exKeymap:n,settings:a,sessionOpts:o}=this;let r=!1;this.debouncedGetSuggestions.cancel();const l=fe.getActiveLeaf(this.app.workspace),d=Pe.getActiveSuggestion(s),c=this.determineRunMode(e,d,l,o);this._inputInfo=c;const{mode:h}=c;return this.previousInputHistory[h]=c,this.updatedKeymapForMode(c,s,i,n,a,l),this.toggleMobileCreateFileButton(i,h,a),h!==t.Standard&&(h===t.HeadingsList&&c.parsedCommand().parsedInput?.length?this.debouncedGetSuggestions(c,s,i):this.getSuggestions(c,s,i),r=!0),r}toggleMobileCreateFileButton(e,s,i){if(!a.Platform.isMobile)return;const n=t[s];e.allowCreateNewFile=i.allowCreateNewFileInModeNames.includes(n),e.allowCreateNewFile||e.createButtonEl?.detach()}updatedKeymapForMode(e,t,s,i,n,a){const{mode:o}=e,r=this.handlerRegistry.getHandler(o),l=r?.getAvailableFacets(e)??[],d={mode:o,activeLeaf:a,facets:{facetList:l,facetSettings:n.quickFilters,onToggleFacet:((o,l)=>{if(l){const e=o.some((e=>!0===e.isActive));r.activateFacet(o,!e)}else r.activateFacet(o,!o[0].isActive);return this.updatedKeymapForMode(e,t,s,i,n,a),this.getSuggestions(e,t,s),!1}).bind(this)}};i.updateKeymapForMode(d)}renderSuggestion(e,s){const{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeRendering:a}}=this,{mode:o}=n,r=o===t.HeadingsList;let d=!1;const c=new Set([l.Unresolved]);if(null===e){if(r){const e=i.getHandler(o),t=n.parsedCommand(o)?.parsedInput;e.renderFileCreationSuggestion(s,t),d=!0}}else if(!c.has(e.type)&&(a||r||b(e))){const t=i.getHandler(e);t&&(d=t.renderSuggestion(e,s))}return d}onChooseSuggestion(e,s){const{handlerRegistry:i,inputInfo:n,settings:{overrideStandardModeBehaviors:a}}=this,{mode:o}=n,r=o===t.HeadingsList;let d=!1;const c=new Set([l.Unresolved]);if(null===e){if(this.noResultActionModes.includes(o)){const e=i.getHandler(o);d=!!e?.onNoResultsCreateAction(n,s)}}else if(!c.has(e.type)&&(a||r||b(e))){const t=i.getHandler(e);t&&(d=t.onChooseSuggestion(e,s))}return d}determineRunMode(e,s,i,n){const a=e??"",o=new pe(a,t.Standard,n);return 0===a.length?(this.reset(),o):(o.currentWorkspaceEnvList=this.workspaceEnvList,this.inputParser.parseInputForMode(o,s,i),o)}getSuggestions(e,t,s){t.setSuggestions([]);const{mode:i}=e,n=this.handlerRegistry.getHandler(i).getSuggestions(e),a=n=>{n?.length?(t.setSuggestions(n),Pe.setActiveSuggestion(i,t),this.exKeymap?.renderQuickOpenFlairIcons(t.suggestions,this.settings)):this.noResultActionModes.includes(i)&&e.parsedCommand(i).parsedInput?s.onNoSuggestion():t.setSuggestions(null)};Array.isArray(n)?a(n):n.then((e=>{a(e)}),(e=>{A("Error retrieving suggestions as Promise. ",e)}))}static setActiveSuggestion(e,s){if(e===t.SymbolList){const e=s.values.filter((e=>u(e))).findIndex((e=>e.item.isSelected));-1!==e&&(s.setSelectedItem(e,null),s.suggestions[s.selectedItem].scrollIntoView(!1))}}static getActiveSuggestion(e){let t=null;return e?.values&&(t=e.values[e.selectedItem]),t}reset(){this._inputInfo=new pe,this.sessionOpts={},this.handlerRegistry.resetSourcedHandlers()}buildWorkspaceEnvList(e,s,i,n,a){const o=n.getHandler(t.EditorList).getItems(),r=o.reduce(((e,t)=>{const s=H(t);return s&&e.add(s),e}),new Set),{fileBookmarks:l,nonFileBookmarks:d}=n.getHandler(t.BookmarksList).getItems(null),c=this.getAttachmentFileExtensions(i,a.fileExtAllowList),h=r.size+a.maxRecentFileSuggestionsOnInit,m=this.getRecentFiles(e,s,r,h);return{openWorkspaceLeaves:new Set(o),openWorkspaceFiles:r,fileBookmarks:l,nonFileBookmarks:d,attachmentFileExtensions:c,mostRecentFiles:m}}getAttachmentFileExtensions(e,t){const s=new Set;try{const i=new Set(["md","canvas",...t]);Object.keys(e.typeByExtension).reduce(((e,t)=>(i.has(t)||e.add(t),e)),s)}catch(e){O("Error retrieving attachment list from ViewRegistry",e)}return s}getRecentFiles(e,t,s,i=75){s=s??new Set;const n=new Set;if(i>0){const a=e.getRecentFiles({showMarkdown:!0,showCanvas:!0,showNonImageAttachments:!0,showImages:!0,maxCount:i});a?.forEach((e=>{const i=t.getAbstractFileByPath(e);w(i)&&!s.has(i)&&n.add(i)}))}return n}inputTextForStandardMode(e){const{mode:s,cleanInput:i}=this.inputInfo;let n=e;return s===t.Standard&&i?.length&&(n=i),n}inputTextForFulltextSearch(){const{inputInfo:e}=this,s=e.mode;let i=null,n=e.cleanInput;if(s!==t.Standard){const t=e.parsedCommand();n=t.parsedInput,F().includes(s)&&(i=t.source?.file)}return{mode:s,parsedInput:n,file:i}}addPropertiesToStandardSuggestions(e,s){if(!e||!s.overrideStandardModeBehaviors&&!s.overrideStandardModeRendering)return;const{handlerRegistry:i,inputInfo:{currentWorkspaceEnvList:n}}=this;for(let s=0;s<e.length;s++){const a=e[s];if(m(a,"type",l.Bookmark)){i.getHandler(t.BookmarksList).addPropertiesToStandardSuggestions(n,a)}else if(p(a)||f(a)){i.getHandler(t.Standard).addPropertiesToStandardSuggestions(n,a)}}}openSuggestionInBackground(e,t,s){const i=W(e);if(!i)return void A("Error cannot open in background. The selected suggestion object does not seem to have an associated file.",e);const n=this.handlerRegistry.getHandler(e)?.getOpenViewState(e,{active:!1,focus:!1});fe.openFileInLeaf(i,t,this.app.workspace,n,s).catch((e=>{A(`Error opening file (${i?.path}) in background. `,e)}))}}const Me={Enter:"↵",Backspace:"⌫",ArrowLeft:"←",ArrowUp:"↑",ArrowDown:"↓",ArrowRight:"→",Tab:"↹"},Be={...Me,Mod:"Ctrl",Ctrl:"Ctrl",Meta:"Win",Alt:"Alt",Shift:"Shift"},Re={...Me,Mod:"⌘",Ctrl:"⌃",Meta:"⌘",Alt:"⌥",Shift:"⇧"},He=[t.EditorList,t.HeadingsList,t.RelatedItemsList,t.BookmarksList,t.SymbolList],De=[t.CommandList,t.VaultList,t.WorkspaceList,...He];class Ve{app;scope;chooser;modal;config;standardKeysInfo=[];customKeysInfo=[];savedStandardKeysInfo=[];_isOpen;customInstructionEls=new Map;standardInstructionsEl;facetKeysInfo=[];insertIntoEditorKeysInfo=[];get isOpen(){return this._isOpen}set isOpen(e){this._isOpen=e}static get modKey(){return a.Platform.isMacOS?"Meta":"Ctrl"}static get keyDisplayStr(){return a.Platform.isMacOS?Re:Be}get exModeHandler(){return this.modal?.exMode}constructor(e,t,s,i,n){this.app=e,this.scope=t,this.chooser=s,this.modal=i,this.config=n,this.initKeysInfo(n,t),this.renderModeTriggerInstructions(i.modalEl,n),this.standardInstructionsEl=i.modalEl.find(".prompt-instructions")}initKeysInfo(e,t){this.standardKeysInfo.push(),this.addCustomKeymaps(this.config),this.removeDefaultTabKeyBinding(t,e),this.registerNavigationBindings(t,e.navigationKeys),this.registerEditorTabBindings(t),this.registerCloseWhenEmptyBindings(t,e),this.registerQuickOpenBindings(t,e),this.registerFulltextSearchBindings(t,e),this.registerOpenInBackgroundBindings(t,e)}removeDefaultTabKeyBinding(e,t){if(t?.removeDefaultTabBinding){const t=e.keys.find((({modifiers:e,key:t})=>null===e&&"Tab"===t));e.unregister(t)}}registerNavigationBindings(e,t){const s=(t,s)=>{t.forEach((({modifiers:t,key:i})=>{e.register(t,i,((e,t)=>(this.navigateItems(e,s),!1)))}))};s(t?.nextKeys??[],!0),s(t?.prevKeys??[],!1)}registerFacetBinding(e,s){const{mode:i,facets:n}=s;if(n?.facetList?.length){const{facetList:s,facetSettings:a,onToggleFacet:o}=n,{keyList:r,modifiers:l,resetKey:d,resetModifiers:c}=a;let h=0;const m=(t,s,i,n)=>e.register(t,s,(()=>o(i,n)));for(let e=0;e<s.length;e++){const n=s[e],a=n.modifiers??l;let o;if(n.key?.length)o=n.key;else{if(!(h<r.length)){P(`Unable to register hotkey for facet: ${n.label} in mode: ${t[i]} because a trigger key is not specified`);continue}o=r[h],++h}m(a,o,[n],!1),this.facetKeysInfo.push({facet:n,command:o,purpose:n.label,modifiers:a,key:o})}const u=c??l;m(u,d,s,!0),this.facetKeysInfo.push({facet:null,command:d,purpose:"toggle all",modifiers:u,key:d})}}registerEditorTabBindings(e){const{modKey:t}=Ve;[[[t],"\\"],[[t,"Shift"],"\\"],[[t],"o"]].forEach((t=>{e.register(t[0],t[1],this.useSelectedItem.bind(this))}))}registerCloseWhenEmptyBindings(e,t){const s=t.closeWhenEmptyKeys;s?.forEach((({modifiers:t,key:s})=>{e.register(t,s,this.closeModalIfEmpty.bind(this))}))}registerQuickOpenBindings(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;s&&n?.forEach((t=>{e.register(i,t,this.quickOpenByIndex.bind(this))}))}quickOpenByIndex(e,t){const s=this.config.quickOpen.keyList.indexOf(t.vkey);if(-1!==s){const{chooser:i}=this;i.values.length>s&&(i.setSelectedItem(s,e),this.useSelectedItem(e,t))}return!1}registerFulltextSearchBindings(e,t){const{isEnabled:s,searchKeys:i}=t.fulltextSearch;if(s){T(this.app)&&e.register(i.modifiers,i.key,this.LaunchSystemGlobalSearch.bind(this))}}LaunchSystemGlobalSearch(e,t){const{parsedInput:s,file:i}=this.modal.exMode.inputTextForFulltextSearch();let n="";return i&&(n=`path:"${i.path}" `),this.modal.close(),T(this.app)?.openGlobalSearch(`${n}${s}`),!1}registerOpenInBackgroundBindings(e,t){const{openInBackground:{isEnabled:s,openKeys:i}}=t;if(s){const t={tab:"open in background tab",vertical:"open in background to the right",horizontal:"open in background below",window:"open in background window"};i?.filter((e=>e.hotkey)).forEach((({openType:s,hotkey:i})=>{e.register(i.modifiers,i.key,(()=>this.openInBackground(this.chooser,s))),this.createCustomKeymap(t[s],De,i,null,!0,!0)}))}}openInBackground(e,t){let s,i="vertical";"vertical"===t||"horizontal"===t?(s="split",i=t):s=t;const n=e?.values?.[e.selectedItem];return this.exModeHandler.openSuggestionInBackground(n,s,i),!1}renderQuickOpenFlairIcons(e,t){const{isEnabled:s,modifiers:i,keyList:n}=t.quickOpen;if(s)for(let t=0;t<n.length&&t<e.length;t++){const s=n[t],a=e[t].createDiv({cls:"qsp-quick-open-aux"});a?.createEl("kbd",{cls:["suggestion-flair","suggestion-hotkey","qsp-quick-open-hotkey"],text:Ve.commandDisplayStr(i,s)})}}updateInsertIntoEditorCommand(e,s,i,n){let a=null;if(n?.isEnabled){const{keymap:o,insertableEditorTypes:r}=n,l=[t.CommandList,t.WorkspaceList,t.VaultList],d=s?.view?.getViewType();if(!(d&&!r.includes(d)||l.includes(e))){if(a=i.find((e=>e.purpose===o.purpose)),!a){const{modifiers:e,key:t,purpose:s}=o;a={isInstructionOnly:!1,command:Ve.commandDisplayStr(e,t),modifiers:e,key:t,purpose:s},i.push(a)}a.eventListener=()=>{const{modal:e,chooser:t}=this;e.close();const i=t.values?.[t.selectedItem];return this.insertIntoEditorAsLink(i,s,n),!1},a.modes=[e]}}return a}updateKeymapForMode(e){const{mode:s,activeLeaf:i}=e,{modal:n,scope:a,customKeysInfo:o,facetKeysInfo:r,standardKeysInfo:l,savedStandardKeysInfo:d,config:{insertLinkInEditor:c,showModeTriggerInstructions:h}}=this;this.updateInsertIntoEditorCommand(s,i,o,c);const m=o.filter((e=>!e.isInstructionOnly));this.unregisterKeys(a,m),this.unregisterKeys(a,r),r.length=0;const u=m.filter((e=>e.modes?.includes(s)));s===t.Standard?this.updateKeymapForStandardMode(a,u,d):this.updateKeymapForCustomModes(a,u,l,e,n),this.showModeTriggerInstructions(n.modalEl,h)}updateKeymapForStandardMode(e,t,s){const i=s.map((([e,t])=>({eventListener:t.func,...e})));this.registerKeys(e,i),s.length=0,this.registerKeys(e,t),this.toggleStandardInstructions(!0)}updateKeymapForCustomModes(e,t,s,i,n){const{savedStandardKeysInfo:a,customKeysInfo:o,facetKeysInfo:r}=this,l=this.unregisterKeys(e,s);l.length&&a.push(...l),this.registerKeys(e,t),this.registerFacetBinding(e,i),this.showCustomInstructions(n,i,o,r)}registerKeys(e,t){t.forEach((({modifiers:t,key:s,eventListener:i})=>{e.register(t,s,i)}))}unregisterKeys(e,t){const s=[],i={};t.map((e=>{const{key:t,modifiers:s}=e,n=Ve.modifiersToKeymapInfoStr(s),a=i[t];a?a[n]=e:i[t]={[n]:e}}));let n=e.keys.length;for(;n--;){const t=e.keys[n],a=i[t.key],o=a?.[t.modifiers];o&&(e.unregister(t),s.push([o,t]))}return s}detachCustomInstructionEls(){this.customInstructionEls.forEach((e=>{e.detach()}))}toggleStandardInstructions(e){const{standardInstructionsEl:t}=this;let s="none";e&&(s="",this.detachCustomInstructionEls()),t&&(t.style.display=s)}showCustomInstructions(e,t,s,i){const{mode:n,facets:a}=t,{modalEl:o}=e,r=s.filter((e=>e.modes?.includes(n)));this.toggleStandardInstructions(!1),this.renderCustomInstructions(o,r),this.renderFacetInstructions(o,a?.facetSettings,i)}renderFacetInstructions(e,t,s){if(s?.length&&t.shouldShowFacetInstructions){const i=this.getCustomInstructionsEl("facets",e);i.empty(),e.appendChild(i);const n=`filters | ${Ve.commandDisplayStr(t.modifiers)}`;this.createPromptInstructionCommandEl(i,n),s.forEach((e=>{const{facet:s,command:n,purpose:a}=e;let o,r,l=null;s?(r=n,o=s.modifiers,s.isActive&&(l=["qsp-filter-active"])):(r=t.resetKey,o=t.resetModifiers);const d=o?`(${Ve.commandDisplayStr(o)}) ${r}`:`${r}`;this.createPromptInstructionCommandEl(i,d,a,[],l)}))}}renderCustomInstructions(e,t){const s=this.getCustomInstructionsEl("custom",e);s.empty(),e.appendChild(s),t.forEach((e=>{this.createPromptInstructionCommandEl(s,e.command,e.purpose)}))}showModeTriggerInstructions(e,t){if(t){const t=this.customInstructionEls.get("modes");t&&e.appendChild(t)}}renderModeTriggerInstructions(e,t){const s=new Map([[t.headingsListCommand,"heading list"],[t.editorListCommand,"editor list"],[t.bookmarksListCommand,"bookmark list"],[t.commandListCommand,"command list"],[t.workspaceListCommand,"workspace list"],[t.vaultListCommand,"vault list"],[t.symbolListActiveEditorCommand,"symbol list (active editor)"],[t.symbolListCommand,"symbol list (embedded)"],[t.relatedItemsListActiveEditorCommand,"related items (active editor)"],[t.relatedItemsListCommand,"related items (embedded)"]]),i=this.getCustomInstructionsEl("modes",e);i.detach(),i.empty(),this.createPromptInstructionCommandEl(i,"mode triggers |"),s.forEach(((e,t)=>{this.createPromptInstructionCommandEl(i,t,e)}))}getCustomInstructionsEl(e,t){let s=this.customInstructionEls.get(e);if(!s){const i={custom:["qsp-prompt-instructions"],facets:["qsp-prompt-instructions-facets"],modes:["qsp-prompt-instructions-modes"]};s=this.createPromptInstructionsEl(i[e],t),this.customInstructionEls.set(e,s)}return s}createPromptInstructionsEl(e,t){const s={cls:["prompt-instructions",...e]};return t.createDiv(s)}createPromptInstructionCommandEl(e,t,s,i,n){i=i??[];const a=e.createDiv();return a.createSpan({cls:["prompt-instruction-command",...i],text:t}),s&&(n=n??[],a.createSpan({cls:n,text:s})),a}closeModalIfEmpty(e,t){const{modal:s,config:i}=this;i.shouldCloseModalOnBackspace&&!s?.inputEl.value&&(s.close(),e.preventDefault())}navigateToCommandHotkeySelector(e,t){const{modal:s,chooser:i,app:{setting:n}}=this,a=i.values?.[i.selectedItem];if(a){n.open();const e=n.openTabById("hotkeys");if(e){s.close();const t=a.item.id;e.setQuery(`${t}`)}}return!1}togglePinnedCommand(e,t){const{app:s,config:i,chooser:n}=this,a=n.values?.[n.selectedItem],o=Te.getEnabledCommandPalettePluginInstance(s);if(a&&o){const e=a.item.id,t=n.suggestions[n.selectedItem];let r=o.options?.pinned;if(r){const t=r.indexOf(e);a.isPinned=-1===t,a.isPinned?r.push(e):r.splice(t,1)}else r=[e],o.options.pinned=r;o.saveSettings(o.plugin),t.empty(),new Te(s,i).renderSuggestion(a,t)}return!1}toggleMarkdownContentRendering(e,t){const{app:i,config:n,chooser:a}=this,o=a.values?.[a.selectedItem],r=o.file;let l=null;if(u(o)?l=o.item:g(o)&&(l={type:"symbolInfo",symbol:o.item,symbolType:s.Heading}),l&&r&&n.shouldRenderSymbolAsHTML(l.symbolType)){const e=a.suggestions[a.selectedItem].find(".qsp-title"),t=0===e.findAll(".qsp-rendered-container").length;e.empty(),Ie.renderSymbolContent(i,n,e,l,r,o.match,t)}return!1}openDefaultApp(e,t){const{app:s,config:{openDefaultApp:{excludeFileExtensions:i}},chooser:n}=this,a=n.values?.[n.selectedItem],o=W(a);if(o&&!i.includes(o.extension)){const e=`Error opening file (${o.path}) in default app. `;s.openWithDefaultApp(o.path).catch((t=>{A(e,t)}))}return!1}saveCurrentAndOpenSelectedWorkspace(){const{app:e,chooser:t,modal:s}=this,i=t?.values?.[t.selectedItem];if(i&&i.item){const t=be.getEnabledWorkspacesPluginInstance(e);t&&(t.saveWorkspace(t.activeWorkspace),t.loadWorkspace(i.item.id),s.close())}return!1}useSelectedItem(e,t){return this.chooser.useSelectedItem(e),!1}insertIntoEditorAsLink(e,t,s){const{app:{workspace:i,fileManager:n,vault:o}}=this,r=i.getActiveViewOfType(a.MarkdownView),l=r?.leaf===t,d=r?.file;if(l&&d){const t=D(n,o,e,d.path,s);t&&r.editor?.replaceSelection(t)}}navigateItems(e,t){const{isOpen:s,chooser:i}=this;if(s){let s=i.selectedItem;s=t?++s:--s,i.setSelectedItem(s,e)}}static commandDisplayStr(e,t){const{keyDisplayStr:s}=this;let i=null,n=null;return e&&(i=e.map((e=>s[e]?.toLocaleLowerCase())).sort().join(" ")),t&&(n=Object.prototype.hasOwnProperty.call(s,t)?s[t]:t),[i,n].filter((e=>e)).join(" ")}static modifiersToKeymapInfoStr(e){return e?.map((e=>"Mod"===e?this.modKey:e)).sort().join(",")}createCustomKeymap(e,t,s,i,n=!0,a=!1){let o=null;if(s){const{modifiers:r,key:l}=s;o={modes:t,modifiers:r,key:l,eventListener:i,purpose:e,command:Ve.commandDisplayStr(r,l),isInstructionOnly:a},n&&this.customKeysInfo.push(o)}return o}addCustomKeymaps(e){const{quickOpen:s}=e,i=s?.keyList;if(i?.length){const e=`${i[0]}~${i[i.length-1]}`;this.createCustomKeymap("open nth item",De,{modifiers:s.modifiers,key:e},null,s.isEnabled,!0)}this.createCustomKeymap("open in new tab",He,{modifiers:["Mod"],key:"Enter"},null,!0,!0),this.createCustomKeymap("open to the right",He,{modifiers:["Mod"],key:"\\"},null,!0,!0),this.createCustomKeymap("open below",He,{modifiers:["Mod","Shift"],key:"\\"},null,!0,!0),this.createCustomKeymap("open in new window",He,{modifiers:["Mod"],key:"o"},null,!0,!0),this.createCustomKeymap("execute command",[t.CommandList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("open workspace",[t.WorkspaceList],{modifiers:[],key:"Enter"},null,!0,!0),this.createCustomKeymap("save and switch workspace",[t.WorkspaceList],e.saveWorkspaceAndSwitchKeys,this.saveCurrentAndOpenSelectedWorkspace.bind(this)),this.createCustomKeymap("set hotkey",[t.CommandList],e.navigateToHotkeySelectorKeys,this.navigateToCommandHotkeySelector.bind(this)),this.createCustomKeymap("toggle pinned",[t.CommandList],e.togglePinnedCommandKeys,this.togglePinnedCommand.bind(this));const{renderMarkdownContentInSuggestions:n}=e;this.createCustomKeymap("toggle preview (selected item)",[t.HeadingsList,t.SymbolList],n.toggleContentRenderingKeys,this.toggleMarkdownContentRendering.bind(this),n.isEnabled);const{openDefaultApp:a}=e;this.createCustomKeymap("open default app",He,a.openInDefaultAppKeys,this.openDefaultApp.bind(this),a.isEnabled);const{fulltextSearch:o}=e;this.createCustomKeymap("fulltext search",De,o.searchKeys,null,o.isEnabled,!0)}}class We{static coreMobileLauncherButtonEl;static qspMobileLauncherButtonEl;static installMobileLauncherOverride(e,t,s){let i=null;if(!(a.Platform.isMobile&&t.isEnabled&&t.isMobileButtonEnabled)||We.coreMobileLauncherButtonEl)return null;const n=function(e,t){let s=null;const i=e?.mobileNavbar?.containerEl;return i&&(s=i.find(ie.defaults.mobileLauncher.coreLauncherButtonSelector),s||(s=i.find(t.coreLauncherButtonSelector))),s}(e,t);if(n){const e=function(e,t,s){let i=null;if(e&&(i=e.cloneNode(!0),i)){const{iconName:e,coreLauncherButtonIconSelector:n}=t;if(i.addClass("qsp-mobile-launcher-button"),i.addEventListener("click",s),e?.length){const t=i.find(n);t&&a.setIcon(t,e)}}return i}(n,t,s);(function(e,t){let s=!1;return e&&t&&(t.toggleClass("qsp-hidden",!0),e.insertAdjacentElement("beforebegin",t)&&(e.remove(),s=!0),t.toggleClass("qsp-hidden",!1)),s})(n,e)&&(We.coreMobileLauncherButtonEl=n,We.qspMobileLauncherButtonEl=e,i=e)}return i}static removeMobileLauncherOverride(){let e=!1;if(!We.coreMobileLauncherButtonEl)return e;if(We.qspMobileLauncherButtonEl?.parentElement){const t=We.qspMobileLauncherButtonEl,s=We.coreMobileLauncherButtonEl;s.toggleClass("qsp-hidden",!0),t.insertAdjacentElement("beforebegin",s)&&(t.remove(),We.qspMobileLauncherButtonEl=null,We.coreMobileLauncherButtonEl=null,e=!0),s.toggleClass("qsp-hidden",!1)}return e}}class Ne{static emptyLeaves=new Map;static layoutChangeEventRef;static installEmptyTabMonitor(e,t){if(!t?.isEnabled)return;const{workspace:s}=e.app;Ne.layoutChangeEventRef=s.on("layout-change",(()=>{Ne.updateEmptyTabs(s,t)})),e.registerEvent(Ne.layoutChangeEventRef),s.onLayoutReady((()=>{Ne.updateEmptyTabs(s,t)}))}static removeEmptyTabButtons(e){e.offref(Ne.layoutChangeEventRef),Ne.layoutChangeEventRef=null;const{emptyLeaves:t}=Ne;for(const e of t.keys())t.get(e)?.detach(),t.delete(e)}static updateEmptyTabs(e,t){if(!t.isEnabled)return;const{buttonLabel:s,onclickListener:i}=t;e.iterateAllLeaves((e=>{const{emptyLeaves:t}=Ne;if(K(e,"empty")&&!t.has(e)){const{containerEl:n}=e.view,a=function(e,t,s){let i=null;const n=e.find(".empty-state-action-list");return n&&(i=n.createDiv({cls:["empty-state-action","tappable","qsp-empty-state-action-launch"],text:t}),i.addEventListener("click",s),n.firstElementChild!==i&&n.insertAfter(i,n.firstElementChild)),i}(n,s,i);a&&t.set(e,a)}}))}}const Ke=[{id:"switcher-plus:open",name:"Open in Standard Mode",mode:t.Standard,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-editors",name:"Open in Editor Mode",mode:t.EditorList,iconId:"lucide-file-edit",ribbonIconEl:null},{id:"switcher-plus:open-symbols",name:"Open Symbols for selected suggestion or editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null},{id:"switcher-plus:open-symbols-active",name:"Open Symbols for the active editor",mode:t.SymbolList,iconId:"lucide-dollar-sign",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-workspaces",name:"Open in Workspaces Mode",mode:t.WorkspaceList,iconId:"lucide-album",ribbonIconEl:null},{id:"switcher-plus:open-headings",name:"Open in Headings Mode",mode:t.HeadingsList,iconId:"lucide-file-search",ribbonIconEl:null},{id:"switcher-plus:open-starred",name:"Open in Bookmarks Mode",mode:t.BookmarksList,iconId:"lucide-bookmark",ribbonIconEl:null},{id:"switcher-plus:open-commands",name:"Open in Commands Mode",mode:t.CommandList,iconId:"run-command",ribbonIconEl:null},{id:"switcher-plus:open-related-items",name:"Open Related Items for selected suggestion or editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null},{id:"switcher-plus:open-related-items-active",name:"Open Related Items for the active editor",mode:t.RelatedItemsList,iconId:"lucide-file-plus-2",ribbonIconEl:null,sessionOpts:{useActiveEditorAsSource:!0}},{id:"switcher-plus:open-vaults",name:"Open in Vaults Mode",mode:t.VaultList,iconId:"vault",ribbonIconEl:null}];class qe extends a.Plugin{options;async onload(){const e=new ie(this);await e.updateDataAndLoadSettings(),this.options=e,this.addSettingTab(new ge(this.app,this,e)),this.registerRibbonCommandIcons(),this.updateLauncherButtonOverrides(!0),Ke.forEach((({id:e,name:t,mode:s,iconId:i,sessionOpts:n})=>{this.registerCommand(e,t,s,i,n)}))}onunload(){this.updateLauncherButtonOverrides(!1)}registerCommand(e,t,s,i,n){this.addCommand({id:e,name:t,icon:i,checkCallback:e=>this.createModalAndOpen(s,e,n)})}registerRibbonCommandIcons(){Ke.forEach((e=>{e.ribbonIconEl?.remove(),e.ribbonIconEl=null}));const e=Ke.reduce(((e,t)=>(e[t.mode]=t,e)),{});this.options.enabledRibbonCommands.forEach((s=>{const i=e[t[s]];i&&(i.ribbonIconEl=this.addRibbonIcon(i.iconId,i.name,(()=>{this.createModalAndOpen(i.mode,!1)})))}))}createModalAndOpen(e,t,s){if(!t){const t=function(e,t){const s=L(e)?.QuickSwitcherModal;return s?new class extends s{plugin;_exMode;get exMode(){return this._exMode}constructor(e,t){super(e,t.options.builtInSystemOptions),this.plugin=t;const{options:s}=t;s.shouldShowAlias=this.shouldShowAlias;const i=new Ve(e,this.scope,this.chooser,this,s);this._exMode=new Pe(e,s,i)}openInMode(e){this.exMode.setSessionOpenMode(this.chooser,e),super.open()}onOpen(){this.exMode.onOpen(),super.onOpen()}onClose(){super.onClose(),this.exMode.onClose()}updateSuggestions(){const{exMode:e,inputEl:t,chooser:s}=this;e.setInitialInputForSession(t),e.updateSuggestions(t.value,s,this)||super.updateSuggestions()}getSuggestions(e){const{exMode:t,plugin:s}=this,i=t.inputTextForStandardMode(e),n=super.getSuggestions(i);return t.addPropertiesToStandardSuggestions(n,s.options),n}onChooseSuggestion(e,t){this.exMode.onChooseSuggestion(e,t)||super.onChooseSuggestion(e,t)}renderSuggestion(e,t){this.exMode.renderSuggestion(e,t)||super.renderSuggestion(e,t)}}(e,t):(O("Unable to extend system switcher. Plugin UI will not be loaded. Use the builtin switcher instead."),null)}(this.app,this);if(!t)return!1;const i=Object.assign({mode:e},s);t.openInMode(i)}return!0}updateLauncherButtonOverrides(e){const{app:s,options:{mobileLauncher:i}}=this;if(We.removeMobileLauncherOverride(),Ne.removeEmptyTabButtons(s.workspace),e){const e=i.modeString,n=t[e],a=()=>{n&&this.createModalAndOpen(n,!1)};We.installMobileLauncherOverride(s,i,a);const o=Ke.find((e=>e.mode===n)),r="Switcher++: "+(o?.name??"");Ne.installEmptyTabMonitor(this,{isEnabled:i.isEnabled&&i.isEmptyTabButtonEnabled,buttonLabel:r,onclickListener:a})}}}module.exports=qe;
/* nosourcemap */