├── .github ├── ISSUE_TEMPLATE │ └── feature_request.md └── workflows │ └── release.yml ├── .gitignore ├── .prettierrc ├── .vscode ├── settings.json └── tasks.json ├── @types ├── obsidian-callout-manager.d.ts └── obsidian.d.ts ├── LICENSE ├── README.md ├── eslint.config.mjs ├── manifest.json ├── package-lock.json ├── package.json ├── readme_gifs ├── main-demo-switching.gif ├── settings │ ├── foldable-callouts.gif │ └── select-text-after-inserting-callout.gif └── usage_examples │ ├── 0-insert-fresh.gif │ ├── 1-current-line.gif │ ├── 2-multi-line.gif │ ├── 3-remove-callout.gif │ ├── 4a-custom-title.gif │ └── 4b-custom-title-fast.gif ├── src ├── callouts │ ├── builtinCallouts.ts │ └── calloutManager.ts ├── commands │ ├── commandIDs.ts │ ├── removeCallout.ts │ └── wrapInCallout │ │ ├── wrapCurrentLineInCallout.ts │ │ ├── wrapLinesInCallout.ts │ │ └── wrapSelectedLinesInCallout.ts ├── main.ts ├── pluginCommandManager.ts ├── pluginSettingsManager.ts ├── settings │ ├── autoSelectionModes.ts │ └── typedSettingsHelpers.ts ├── tests │ └── autoSelectionModes │ │ ├── afterRemovingCallout.test.ts │ │ ├── testAutoSelectionMode.ts │ │ ├── whenNothingSelected.test.ts │ │ └── whenTextSelected.test.ts └── utils │ ├── arrayUtils.ts │ ├── calloutTitleUtils.ts │ ├── editorCheckCallbackUtils.ts │ ├── errorUtils.ts │ ├── numberUtils.ts │ ├── regexUtils.ts │ ├── selectionUtils.ts │ └── stringUtils.ts ├── tsconfig.json ├── vitest.config.ts └── webpack.config.cjs /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: "[FR] " 5 | labels: enhancement 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **How would this feature improve your workflow or enhance your experience?** 20 | Please describe how important or beneficial this feature would be for your workflow or overall experience with the plugin. If you like, you can rate its importance on a scale of 1-10 (1 = a minor improvement, 10 = absolutely essential). 21 | 22 | **Additional context** 23 | Add any other context or screenshots about the feature request here. 24 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release Obsidian Callout Toggles plugin 2 | 3 | on: 4 | push: 5 | tags: 6 | - "*" 7 | workflow_dispatch: 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Use Node.js 17 | uses: actions/setup-node@v4 18 | with: 19 | node-version: 20 20 | 21 | - name: Build plugin 22 | run: | 23 | npm install 24 | npm run build 25 | 26 | - name: Create release 27 | env: 28 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 29 | run: | 30 | tag="${GITHUB_REF#refs/tags/}" 31 | 32 | gh release create "$tag" \ 33 | --title="$tag" \ 34 | --draft \ 35 | main.js manifest.json 36 | 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | 3 | data.json 4 | 5 | data-json-snapshots 6 | 7 | .DS_Store 8 | 9 | main.js 10 | 11 | .aider* 12 | 13 | .env 14 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 100 3 | } 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": ["Callout", "callouts", "tldr", "unfoldable"], 3 | "[javascript][typescript][typescriptreact][json][jsonc]": { 4 | // Prettier 5 | "editor.defaultFormatter": "esbenp.prettier-vscode", 6 | "editor.formatOnSave": true, 7 | "editor.tabSize": 2, 8 | "editor.rulers": [100], // goes with printWidth: 100 in prettierrc 9 | // Eslint 10 | "editor.codeActionsOnSave": { 11 | "source.fixAll.eslint": "explicit", 12 | "source.organizeImports": "explicit" 13 | }, 14 | // TypeScript 15 | "typescript.preferences.importModuleSpecifier": "relative" 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "npm", 6 | "script": "build", 7 | "group": "build", 8 | "problemMatcher": [], 9 | "label": "npm: build", 10 | "detail": "npx webpack" 11 | }, 12 | { 13 | "type": "npm", 14 | "script": "watch", 15 | "group": { 16 | "kind": "build", 17 | "isDefault": true 18 | }, 19 | "problemMatcher": [], 20 | "label": "npm: watch", 21 | "detail": "npx webpack --watch" 22 | } 23 | ] 24 | } 25 | -------------------------------------------------------------------------------- /@types/obsidian-callout-manager.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file was manually copied from the Callout Manager package (for some reason, the package's 3 | * types file isn't being recognized by TypeScript). I made a PR there in case the package author 4 | * thinks it's a good fix: https://github.com/eth-p/obsidian-callout-manager/pull/27 5 | * 6 | * In the meantime, this is a workaround. The original file can be found in node_modules at: 7 | * node_modules/obsidian-callout-manager/dist/api.d.ts 8 | * 9 | */ 10 | 11 | declare module "obsidian-callout-manager" { 12 | import { type App, type Plugin, type RGB } from "obsidian"; 13 | 14 | /** 15 | * A type representing the ID of a callout. 16 | */ 17 | declare type CalloutID = string; 18 | /** 19 | * A description of a markdown callout. 20 | */ 21 | declare type Callout = CalloutProperties & { 22 | /** 23 | * The list of known sources for the callout. 24 | * A source is a stylesheet that provides styles for a callout with this ID. 25 | */ 26 | sources: CalloutSource[]; 27 | }; 28 | type CalloutProperties = { 29 | /** 30 | * The ID of the callout. 31 | * This is the part that goes in the callout header. 32 | */ 33 | id: CalloutID; 34 | /** 35 | * The current color of the callout. 36 | */ 37 | color: string; 38 | /** 39 | * The icon associated with the callout. 40 | */ 41 | icon: string; 42 | }; 43 | /** 44 | * The source of a callout. 45 | * This is what declares the style information for the callout with the given ID. 46 | */ 47 | declare type CalloutSource = 48 | | CalloutSourceObsidian 49 | | CalloutSourceSnippet 50 | | CalloutSourceTheme 51 | | CalloutSourceCustom; 52 | /** 53 | * The callout is a built-in Obsidian callout. 54 | */ 55 | type CalloutSourceObsidian = { 56 | type: "builtin"; 57 | }; 58 | /** 59 | * The callout is from a snippet. 60 | */ 61 | type CalloutSourceSnippet = { 62 | type: "snippet"; 63 | snippet: string; 64 | }; 65 | /** 66 | * The callout is from a theme. 67 | */ 68 | type CalloutSourceTheme = { 69 | type: "theme"; 70 | theme: string; 71 | }; 72 | /** 73 | * The callout was added by the user. 74 | */ 75 | type CalloutSourceCustom = { 76 | type: "custom"; 77 | }; 78 | 79 | type CalloutManagerEventMap = { 80 | /** 81 | * Called whenever one or more callouts have changed. 82 | */ 83 | change(): void; 84 | }; 85 | /** 86 | * A Callout Manager event that can be listened for. 87 | */ 88 | declare type CalloutManagerEvent = keyof CalloutManagerEventMap; 89 | /** 90 | * A type which maps event names to their associated listener functions. 91 | */ 92 | declare type CalloutManagerEventListener = 93 | CalloutManagerEventMap[Event]; 94 | 95 | /** 96 | * A handle for the Callout Manager API. 97 | */ 98 | declare type CalloutManager = 99 | WithPluginReference extends true ? CalloutManagerOwnedHandle : CalloutManagerUnownedHandle; 100 | /** 101 | * An unowned handle for the Callout Manager API. 102 | */ 103 | type CalloutManagerUnownedHandle = { 104 | /** 105 | * Gets the list of available callouts. 106 | */ 107 | getCallouts(): readonly Callout[]; 108 | /** 109 | * Tries to parse the color of a {@link Callout callout} into an Obsidian {@link RGB} object. 110 | * If the color is not a valid callout color, you can access the invalid color string through the `invalid` property. 111 | * 112 | * @param callout The callout. 113 | */ 114 | getColor(callout: Callout): 115 | | RGB 116 | | { 117 | invalid: string; 118 | }; 119 | /** 120 | * Gets the title text of a {@link Callout callout}. 121 | * 122 | * @param callout The callout. 123 | */ 124 | getTitle(callout: Callout): string; 125 | }; 126 | /** 127 | * An owned handle for the Callout Manager API. 128 | */ 129 | type CalloutManagerOwnedHandle = { 130 | /** 131 | * Registers an event listener. 132 | * If Callout Manager or the handle owner plugin are unloaded, all events will be unregistered automatically. 133 | * 134 | * @param event The event to listen for. 135 | * @param listener The listener function. 136 | */ 137 | on(event: E, listener: CalloutManagerEventListener): void; 138 | /** 139 | * Unregisters an event listener. 140 | * 141 | * In order to unregister a listener successfully, the exact reference of the listener function provided to 142 | * {@link on} must be provided as the listener parameter to this function. 143 | * 144 | * @param event The event which the listener was bound to. 145 | * @param listener The listener function to unregister. 146 | */ 147 | off(event: E, listener: CalloutManagerEventListener): void; 148 | } & CalloutManagerUnownedHandle; 149 | 150 | declare const PLUGIN_ID = "callout-manager"; 151 | declare const PLUGIN_API_VERSION = "v1"; 152 | /** 153 | * Gets an owned handle to the Callout Manager plugin API. 154 | * The provided plugin will be used as the owner. 155 | */ 156 | declare function getApi(plugin: Plugin): Promise | undefined>; 157 | /** 158 | * Gets an unowned handle to the Callout Manager plugin API. 159 | * This handle cannot be used to register events. 160 | */ 161 | declare function getApi(): Promise; 162 | /** 163 | * Checks if Callout Manager is installed. 164 | */ 165 | declare function isInstalled(app?: App): boolean; 166 | 167 | export { 168 | Callout, 169 | CalloutID, 170 | CalloutManager, 171 | CalloutManagerEvent, 172 | CalloutManagerEventListener, 173 | CalloutProperties, 174 | CalloutSource, 175 | CalloutSourceCustom, 176 | CalloutSourceObsidian, 177 | CalloutSourceSnippet, 178 | CalloutSourceTheme, 179 | getApi, 180 | isInstalled, 181 | PLUGIN_API_VERSION, 182 | PLUGIN_ID, 183 | }; 184 | } 185 | -------------------------------------------------------------------------------- /@types/obsidian.d.ts: -------------------------------------------------------------------------------- 1 | import {} from "obsidian"; 2 | 3 | declare module "obsidian" { 4 | export interface App { 5 | commands: { 6 | removeCommand: (commandID: string) => void; 7 | }; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Callout Toggles 2 | 3 | An [Obsidian plugin](https://obsidian.md/plugins?id=callout-toggles) to quickly add, switch, or remove callouts in your notes. Provides a separate command for every possible callout type, so you can easily assign hotkeys for your favorite callouts. 4 | 5 | ![Switching between callout types demonstration](./readme_gifs/main-demo-switching.gif) 6 | 7 | ## Features 8 | 9 | - Quickly insert or remove a callout of your choice with a single command 10 | - Insert a fresh callout, or wrap existing text in a callout 11 | - Retains [custom titles](#retaining-custom-titles) when wrapping or removing callouts 12 | - Supports [custom callouts](#custom-callouts-callout-manager) (automatically syncs with [Callout Manager] if installed) 13 | - Configurable settings for default formatting, foldable callouts, and more 14 | 15 | ## Table of contents 16 | 17 | 1. [Features](#features) 18 | 2. [Table of contents](#table-of-contents) 19 | 3. [Commands provided](#commands-provided) 20 | 1. [Wrap lines in X callout](#wrap-lines-in-x-callout) 21 | 2. [Remove callout from selected lines](#remove-callout-from-selected-lines) 22 | 4. [Usage examples](#usage-examples) 23 | 1. [Inserting a fresh callout](#inserting-a-fresh-callout) 24 | 2. [Wrapping the current line](#wrapping-the-current-line) 25 | 3. [Wrapping multiple lines](#wrapping-multiple-lines) 26 | 4. [Removing a callout](#removing-a-callout) 27 | 5. [Retaining custom titles](#retaining-custom-titles) 28 | 5. [Custom callouts (Callout Manager)](#custom-callouts-callout-manager) 29 | 6. [Related plugins](#related-plugins) 30 | 7. [Feedback](#feedback) 31 | 8. [Appreciation](#appreciation) 32 | 33 | ## Commands provided 34 | 35 | Two types of commands are provided: `Wrap lines in X callout` and `Remove callout from selected lines`. Using them together, you can easily change the type of an existing callout. 36 | 37 | > [!TIP] 38 | > Both commands work on full lines of text, so your cursor position within a given line doesn't matter. As long as part of a line is selected, the entire line will be included. 39 | 40 | ### Wrap lines in X callout 41 | 42 | One `Wrap lines in X callout` command is provided for every possible callout type `X` (❞ Quote, ⚠ Warning, 🔥 Tip, 🐞 Bug, 📝 Note, etc.), so that you can assign separate hotkeys for each of your favorite callouts. This can be used both for inserting fresh callouts, and for turning existing text into callouts. 43 | 44 | ### Remove callout from selected lines 45 | 46 | > [!IMPORTANT] 47 | > Note that a callout must begin on the first selected line of text for this command to be available. 48 | 49 | This will remove the callout syntax from the selected lines, turning the callout back into regular text. If a custom title is present, it will be retained as a Markdown heading (see [Retaining custom titles](#retaining-custom-titles)). 50 | 51 | ## Usage examples 52 | 53 | ### Inserting a fresh callout 54 | 55 | To insert a fresh callout of your choice, simply run `Wrap lines in X callout` on a blank line: 56 | 57 | ![Inserting a fresh callout](./readme_gifs/usage_examples/0-insert-fresh.gif) 58 | 59 | ### Wrapping the current line 60 | 61 | If the current line is not blank and nothing is selected, the current line will be turned into a callout: 62 | 63 | ![Wrapping the current line in a callout](./readme_gifs/usage_examples/1-current-line.gif) 64 | 65 | ### Wrapping multiple lines 66 | 67 | To turn multiple lines of text into a callout, first select the lines, and then run `Wrap lines in X callout`: 68 | 69 | ![Wrapping multiple lines in a callout](./readme_gifs/usage_examples/2-multi-line.gif) 70 | 71 | ### Removing a callout 72 | 73 | To turn a callout back into regular text, run `Remove callout from selected lines` with the given lines selected (make sure the callout header is on the first selected line): 74 | 75 | ![Unwrapping a callout block](./readme_gifs/usage_examples/3-remove-callout.gif) 76 | 77 | ### Retaining custom titles 78 | 79 | If a callout has a default title (e.g. `> [!quote] Quote`), the entire header line will be removed when calling `Remove callout from selected lines`. If a custom title is present (e.g. `> [!quote] Aristotle`), it will be retained as a Markdown heading, so that you don't lose your hard work in choosing that title. 80 | 81 | If you call `Wrap lines in X callout` on a selection whose first line is a Markdown heading, the heading will be used as the custom title for the new callout block: 82 | 83 | ![Retaining custom titles](./readme_gifs/usage_examples/4a-custom-title.gif) 84 | 85 | This makes it easy to switch between callout types while retaining your custom titles: 86 | 87 | ![Retaining custom titles while switching between callout types](./readme_gifs/usage_examples/4b-custom-title-fast.gif) 88 | 89 | ## Custom callouts (Callout Manager) 90 | 91 | This plugin automatically integrates with the [Callout Manager] plugin, if you have it installed. This means that the callout types available in this plugin will be automatically synced with your custom callout types in Callout Manager. 92 | 93 | If you don't have Callout Manager installed, [no worries](https://www.youtube.com/watch?v=4P-YBqVzJg0)—this plugin will still work as expected. A default set of callout types will be available for you to use. 94 | 95 | ## Related plugins 96 | 97 | As mentioned above, you can use [Callout Manager] (by [eth-p]) to customize how Obsidian handles callouts—e.g. adjust callout colors/icons, add your own custom callouts, etc. 98 | 99 | If you'd like to be able to insert a fresh callout by choosing from a styled (with icons!) dropdown of callout types, you can also consider installing either/both: 100 | 101 | 1. [Personal Assistant](https://github.com/edonyzpc/personal-assistant) (by [edonyzpc](https://github.com/edonyzpc/)): Shows dropdown when running command "List callout for quickly insert" 102 | 2. [Callout Suggestions](https://github.com/cwfryer/obsidian-callout-suggestions) (by [cwfryer](https://github.com/cwfryer/)): Shows inline dropdown when typing `>!` 103 | 104 | ## Feedback 105 | 106 | If you have any feedback or suggestions, feel free to [open an issue](https://github.com/alythobani/obsidian-callout-toggles/issues) and I'd be happy to take a look when I can. 107 | 108 | ## Appreciation 109 | 110 | Thanks to the creators of Obsidian, seriously an awesome note-taking app! And big thanks to [eth-p] for providing a [Callout Manager API](https://github.com/eth-p/obsidian-callout-manager/tree/master/api)—super cool. 111 | 112 | [Callout Manager]: https://github.com/eth-p/obsidian-callout-manager/ 113 | [eth-p]: https://github.com/eth-p/ 114 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | 3 | import eslint from "@eslint/js"; 4 | import tseslint from "typescript-eslint"; 5 | 6 | export default tseslint.config( 7 | eslint.configs.recommended, 8 | ...tseslint.configs.strictTypeChecked, 9 | ...tseslint.configs.stylisticTypeChecked, 10 | { 11 | files: ["**/*.ts"], 12 | ignores: ["vitest.config.ts"], 13 | languageOptions: { 14 | parserOptions: { 15 | projectService: true, 16 | tsconfigRootDir: import.meta.dirname, 17 | }, 18 | }, 19 | rules: { 20 | "@typescript-eslint/consistent-type-imports": ["error", { fixStyle: "inline-type-imports" }], 21 | "@typescript-eslint/consistent-type-definitions": ["error", "type"], 22 | "@typescript-eslint/explicit-function-return-type": "error", 23 | "@typescript-eslint/restrict-template-expressions": [ 24 | "error", 25 | { 26 | allowBoolean: true, 27 | allowNumber: true, 28 | }, 29 | ], 30 | "@typescript-eslint/no-confusing-void-expression": ["error", { ignoreArrowShorthand: true }], 31 | "@typescript-eslint/no-non-null-assertion": "error", 32 | "@typescript-eslint/no-unused-vars": [ 33 | "error", 34 | { 35 | args: "all", 36 | argsIgnorePattern: "^_", 37 | caughtErrorsIgnorePattern: "^_", 38 | destructuredArrayIgnorePattern: "^_", 39 | varsIgnorePattern: "^_", 40 | }, 41 | ], 42 | "@typescript-eslint/strict-boolean-expressions": [ 43 | "error", 44 | { 45 | allowString: false, 46 | allowNumber: false, 47 | }, 48 | ], 49 | "object-shorthand": "error", 50 | }, 51 | } 52 | ); 53 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "callout-toggles", 3 | "name": "Callout Toggles", 4 | "version": "1.2.1", 5 | "minAppVersion": "1.6.7", 6 | "description": "Quickly add, change, or remove callouts in your notes.", 7 | "author": "Aly Thobani", 8 | "authorUrl": "https://github.com/alythobani/", 9 | "fundingUrl": "https://buymeacoffee.com/alythobani", 10 | "isDesktopOnly": false 11 | } 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "type": "module", 4 | "name": "obsidian-callout-toggles", 5 | "description": "An Obsidian plugin to quickly add, change, or remove callouts in your notes.", 6 | "main": "./main.js", 7 | "author": "Aly Thobani", 8 | "license": "GPL-3.0-only", 9 | "version": "1.2.1", 10 | "dependencies": { 11 | "obsidian": "^1.6.6", 12 | "obsidian-callout-manager": "^1.0.2-alpha1" 13 | }, 14 | "devDependencies": { 15 | "@eslint/js": "^9.10.0", 16 | "@types/eslint__js": "^8.42.3", 17 | "@types/node": "^22.5.5", 18 | "@vitest/ui": "^2.1.8", 19 | "eslint": "^9.10.0", 20 | "ts-loader": "^9.5.1", 21 | "typescript": "^5.6.2", 22 | "typescript-eslint": "^8.18.2", 23 | "vitest": "^2.1.8", 24 | "webpack": "^5.94.0", 25 | "webpack-cli": "^5.1.4" 26 | }, 27 | "scripts": { 28 | "build": "npx webpack", 29 | "watch": "npx webpack --watch", 30 | "lint": "eslint . --ext .ts", 31 | "test": "vitest", 32 | "test:ui": "vitest --ui" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /readme_gifs/main-demo-switching.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/main-demo-switching.gif -------------------------------------------------------------------------------- /readme_gifs/settings/foldable-callouts.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/settings/foldable-callouts.gif -------------------------------------------------------------------------------- /readme_gifs/settings/select-text-after-inserting-callout.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/settings/select-text-after-inserting-callout.gif -------------------------------------------------------------------------------- /readme_gifs/usage_examples/0-insert-fresh.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/usage_examples/0-insert-fresh.gif -------------------------------------------------------------------------------- /readme_gifs/usage_examples/1-current-line.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/usage_examples/1-current-line.gif -------------------------------------------------------------------------------- /readme_gifs/usage_examples/2-multi-line.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/usage_examples/2-multi-line.gif -------------------------------------------------------------------------------- /readme_gifs/usage_examples/3-remove-callout.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/usage_examples/3-remove-callout.gif -------------------------------------------------------------------------------- /readme_gifs/usage_examples/4a-custom-title.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/usage_examples/4a-custom-title.gif -------------------------------------------------------------------------------- /readme_gifs/usage_examples/4b-custom-title-fast.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alythobani/obsidian-callout-toggles/d277f8e83b20b970013323accf961f24c9feacfc/readme_gifs/usage_examples/4b-custom-title-fast.gif -------------------------------------------------------------------------------- /src/callouts/builtinCallouts.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file contains the built-in callouts that are available to be used in Obsidian. 3 | * 4 | * See Obsidian docs: 5 | * https://help.obsidian.md/Editing+and+formatting/Callouts#Supported%20types 6 | */ 7 | 8 | export const BUILTIN_CALLOUT_IDS = [ 9 | "note", 10 | "abstract", 11 | "info", 12 | "todo", 13 | "tip", 14 | "success", 15 | "question", 16 | "warning", 17 | "failure", 18 | "danger", 19 | "bug", 20 | "example", 21 | "quote", 22 | ] as const; 23 | -------------------------------------------------------------------------------- /src/callouts/calloutManager.ts: -------------------------------------------------------------------------------- 1 | import { type Plugin } from "obsidian"; 2 | import { 3 | type CalloutID, 4 | type CalloutManager, 5 | getApi, 6 | isInstalled as isCalloutManagerInstalled, 7 | } from "obsidian-callout-manager"; 8 | 9 | export type CalloutManagerOwnedHandle = CalloutManager; 10 | 11 | export async function getCalloutManagerAPIHandleIfInstalled( 12 | plugin: Plugin 13 | ): Promise { 14 | if (!isCalloutManagerInstalled(plugin.app)) { 15 | return undefined; 16 | } 17 | return getApi(plugin); 18 | } 19 | 20 | export function getCalloutIDsFromCalloutManager( 21 | calloutManager: CalloutManagerOwnedHandle 22 | ): readonly CalloutID[] { 23 | return calloutManager.getCallouts().map((callout) => callout.id); 24 | } 25 | -------------------------------------------------------------------------------- /src/commands/commandIDs.ts: -------------------------------------------------------------------------------- 1 | import { type CalloutID } from "obsidian-callout-manager"; 2 | 3 | /** 4 | * Returns the full command ID for wrapping the current line or selected lines in the given callout. 5 | */ 6 | export function getFullWrapLinesInCalloutCommandID({ 7 | pluginID, 8 | calloutID, 9 | }: { 10 | pluginID: string; 11 | calloutID: CalloutID; 12 | }): string { 13 | const partialCommandID = getPartialWrapLinesInCalloutCommandID(calloutID); 14 | return getFullPluginCommandID(pluginID, partialCommandID); 15 | } 16 | 17 | /** 18 | * Returns the command ID for wrapping the current line or selected lines in a callout. 19 | * 20 | * This is a partial command ID, so it should be combined with the plugin ID to form the full 21 | * command ID, e.g. when removing the command from the app. 22 | */ 23 | export function getPartialWrapLinesInCalloutCommandID(calloutID: CalloutID): string { 24 | return `wrap-lines-in-${calloutID}-callout`; 25 | } 26 | 27 | function getFullPluginCommandID(pluginID: string, partialCommandID: string): string { 28 | return `${pluginID}:${partialCommandID}`; 29 | } 30 | -------------------------------------------------------------------------------- /src/commands/removeCallout.ts: -------------------------------------------------------------------------------- 1 | import { type Command, type Editor } from "obsidian"; 2 | import { type PluginSettingsManager } from "../pluginSettingsManager"; 3 | import { type AutoSelectionAfterRemovingCalloutMode } from "../settings/autoSelectionModes"; 4 | import { getLastElement, isNonEmptyArray, type NonEmptyStringArray } from "../utils/arrayUtils"; 5 | import { 6 | getCalloutIDAndExplicitTitle, 7 | isCustomTitle, 8 | makeH6Line, 9 | } from "../utils/calloutTitleUtils"; 10 | import { makeCalloutSelectionCheckCallback } from "../utils/editorCheckCallbackUtils"; 11 | import { throwNever } from "../utils/errorUtils"; 12 | import { 13 | type ClearSelectionAction, 14 | type CursorOrSelectionAction, 15 | type CursorPositions, 16 | getCalloutStartPos, 17 | getClearSelectionCursorStartAction, 18 | getCursorPositions, 19 | getNewPositionWithinLine, 20 | getNewToPosition, 21 | getSelectedLinesRangeAndText, 22 | runCursorOrSelectionAction, 23 | type SelectedLinesDiff, 24 | type SetSelectionInCorrectDirectionAction, 25 | } from "../utils/selectionUtils"; 26 | import { getTextLines } from "../utils/stringUtils"; 27 | 28 | export function makeRemoveCalloutFromSelectedLinesCommand( 29 | pluginSettingsManager: PluginSettingsManager 30 | ): Command { 31 | return { 32 | id: "remove-callout-from-selected-lines", 33 | name: "Remove callout from selected lines", 34 | editorCheckCallback: makeCalloutSelectionCheckCallback({ 35 | editorAction: removeCalloutFromSelectedLines, 36 | pluginSettingsManager, 37 | }), 38 | }; 39 | } 40 | 41 | /** 42 | * Removes the callout from the selected lines. Retains the title if it's not the default header for 43 | * the given callout, else removes the entire header line. 44 | */ 45 | function removeCalloutFromSelectedLines({ 46 | editor, 47 | pluginSettingsManager, 48 | }: { 49 | editor: Editor; 50 | pluginSettingsManager: PluginSettingsManager; 51 | }): void { 52 | const originalCursorPositions = getCursorPositions(editor); 53 | const { selectedLinesRange, selectedLinesText } = getSelectedLinesRangeAndText(editor); // Full selected lines range and text 54 | const selectedLines = getTextLines(selectedLinesText); 55 | const { calloutID, maybeExplicitTitle } = getCalloutIDAndExplicitTitle(selectedLinesText); 56 | const newLines = getNewLinesAfterRemovingCallout({ 57 | calloutID, 58 | maybeExplicitTitle, 59 | selectedLines, 60 | }); 61 | const selectedLinesDiff = { oldLines: selectedLines, newLines }; 62 | const newText = newLines.join("\n"); 63 | editor.replaceRange(newText, selectedLinesRange.from, selectedLinesRange.to); 64 | setSelectionAfterRemovingCallout({ 65 | editor, 66 | selectedLinesDiff, 67 | originalCursorPositions, 68 | pluginSettingsManager, 69 | }); 70 | } 71 | 72 | /** 73 | * Gets the new lines after removing the callout from the selected lines. 74 | */ 75 | function getNewLinesAfterRemovingCallout({ 76 | calloutID, 77 | maybeExplicitTitle, 78 | selectedLines, 79 | }: { 80 | calloutID: string; 81 | maybeExplicitTitle: string | undefined; 82 | selectedLines: NonEmptyStringArray; 83 | }): NonEmptyStringArray { 84 | if (maybeExplicitTitle !== undefined && isCustomTitle({ calloutID, title: maybeExplicitTitle })) { 85 | return getNewLinesAfterRemovingCalloutWithCustomTitle(maybeExplicitTitle, selectedLines); 86 | } 87 | return getNewLinesAfterRemovingCalloutWithDefaultTitle(selectedLines); 88 | } 89 | 90 | function getNewLinesAfterRemovingCalloutWithCustomTitle( 91 | customTitle: string, 92 | selectedLines: NonEmptyStringArray 93 | ): NonEmptyStringArray { 94 | const customTitleHeadingLine = makeH6Line(customTitle); 95 | const unquotedLines = selectedLines.slice(1).map((line) => line.replace(/^> /, "")); 96 | return [customTitleHeadingLine, ...unquotedLines]; 97 | } 98 | 99 | function getNewLinesAfterRemovingCalloutWithDefaultTitle( 100 | selectedLines: NonEmptyStringArray 101 | ): NonEmptyStringArray { 102 | const linesWithoutHeader = selectedLines.slice(1); 103 | const unquotedLinesWithoutHeader = linesWithoutHeader.map((line) => line.replace(/^> /, "")); 104 | if (!isNonEmptyArray(unquotedLinesWithoutHeader)) { 105 | return [""]; 106 | } 107 | return unquotedLinesWithoutHeader; 108 | } 109 | 110 | function setSelectionAfterRemovingCallout({ 111 | editor, 112 | selectedLinesDiff, 113 | originalCursorPositions, 114 | pluginSettingsManager, 115 | }: { 116 | editor: Editor; 117 | selectedLinesDiff: SelectedLinesDiff; 118 | originalCursorPositions: CursorPositions; 119 | pluginSettingsManager: PluginSettingsManager; 120 | }): void { 121 | const { afterRemovingCallout } = pluginSettingsManager.getSetting("autoSelectionModes"); 122 | const cursorOrSelectionAction = getCursorOrSelectionActionAfterRemovingCallout({ 123 | selectedLinesDiff, 124 | originalCursorPositions, 125 | afterRemovingCallout, 126 | }); 127 | runCursorOrSelectionAction({ editor, action: cursorOrSelectionAction }); 128 | } 129 | 130 | /** 131 | * Sets the selection or cursor (depending on user setting) after removing the callout from the 132 | * selected lines. 133 | */ 134 | export function getCursorOrSelectionActionAfterRemovingCallout({ 135 | afterRemovingCallout, 136 | selectedLinesDiff, 137 | originalCursorPositions, 138 | }: { 139 | afterRemovingCallout: AutoSelectionAfterRemovingCalloutMode; 140 | selectedLinesDiff: SelectedLinesDiff; 141 | originalCursorPositions: CursorPositions; 142 | }): CursorOrSelectionAction { 143 | const { oldLines, newLines } = selectedLinesDiff; 144 | const didRemoveHeaderLine = oldLines.length !== newLines.length; 145 | switch (afterRemovingCallout) { 146 | case "originalSelection": { 147 | return getOriginalSelectionAction({ 148 | selectedLinesDiff, 149 | originalCursorPositions, 150 | didRemoveHeaderLine, 151 | }); 152 | } 153 | case "selectFull": { 154 | return getFullTextSelectionAction({ selectedLinesDiff, originalCursorPositions }); 155 | } 156 | case "clearSelectionCursorTo": { 157 | return getClearSelectionCursorToAction({ selectedLinesDiff, originalCursorPositions }); 158 | } 159 | case "clearSelectionCursorStart": { 160 | return getClearSelectionCursorStartAction({ originalCursorPositions }); 161 | } 162 | case "clearSelectionCursorEnd": { 163 | return getClearSelectionCursorEndAction({ 164 | selectedLinesDiff, 165 | originalCursorPositions, 166 | didRemoveHeaderLine, 167 | }); 168 | } 169 | default: 170 | throwNever(afterRemovingCallout); 171 | } 172 | } 173 | 174 | function getFullTextSelectionAction({ 175 | selectedLinesDiff, 176 | originalCursorPositions, 177 | }: { 178 | selectedLinesDiff: SelectedLinesDiff; 179 | originalCursorPositions: CursorPositions; 180 | }): SetSelectionInCorrectDirectionAction { 181 | const newFrom = getCalloutStartPos({ originalCursorPositions }); 182 | 183 | const { oldLines, newLines } = selectedLinesDiff; 184 | const didRemoveHeaderLine = oldLines.length !== newLines.length; 185 | const { to: oldTo } = originalCursorPositions; 186 | const newToLine = didRemoveHeaderLine ? oldTo.line - 1 : oldTo.line; 187 | const newLastLine = getLastElement(newLines); 188 | const newTo = { line: newToLine, ch: newLastLine.length }; 189 | 190 | const newRange = { from: newFrom, to: newTo }; 191 | return { type: "setSelectionInCorrectDirection", newRange, originalCursorPositions }; 192 | } 193 | 194 | function getOriginalSelectionAction({ 195 | selectedLinesDiff, 196 | originalCursorPositions, 197 | didRemoveHeaderLine, 198 | }: { 199 | selectedLinesDiff: SelectedLinesDiff; 200 | originalCursorPositions: CursorPositions; 201 | didRemoveHeaderLine: boolean; 202 | }): SetSelectionInCorrectDirectionAction { 203 | const { oldLines, newLines } = selectedLinesDiff; 204 | const { from: oldFrom, to: oldTo } = originalCursorPositions; 205 | const newFromCh = didRemoveHeaderLine 206 | ? 0 207 | : getNewPositionWithinLine({ 208 | oldCh: oldFrom.ch, 209 | lineDiff: { oldLine: oldLines[0], newLine: newLines[0] }, 210 | }); 211 | const newFrom = { line: oldFrom.line, ch: newFromCh }; 212 | 213 | const newTo = getNewToPosition({ oldTo, selectedLinesDiff }); 214 | 215 | const newRange = { from: newFrom, to: newTo }; 216 | return { type: "setSelectionInCorrectDirection", newRange, originalCursorPositions }; 217 | } 218 | 219 | function getClearSelectionCursorToAction({ 220 | selectedLinesDiff, 221 | originalCursorPositions, 222 | }: { 223 | selectedLinesDiff: SelectedLinesDiff; 224 | originalCursorPositions: CursorPositions; 225 | }): ClearSelectionAction { 226 | const { to: oldTo } = originalCursorPositions; 227 | const newTo = getNewToPosition({ oldTo, selectedLinesDiff }); 228 | // TODO: If user is in insert mode (with selection) or non-vim mode, we shouldn't subtract one 229 | const newCursor = { line: newTo.line, ch: newTo.ch - 1 }; 230 | return { type: "clearSelection", newCursor }; 231 | } 232 | 233 | /** 234 | * Clears the selection and moves the cursor to the end of the callout after wrapping the selected 235 | * lines in a callout. 236 | */ 237 | function getClearSelectionCursorEndAction({ 238 | selectedLinesDiff, 239 | originalCursorPositions, 240 | didRemoveHeaderLine, 241 | }: { 242 | selectedLinesDiff: SelectedLinesDiff; 243 | originalCursorPositions: CursorPositions; 244 | didRemoveHeaderLine: boolean; 245 | }): ClearSelectionAction { 246 | const { to: oldTo } = originalCursorPositions; 247 | const endLine = didRemoveHeaderLine ? oldTo.line - 1 : oldTo.line; 248 | const endCh = getLastElement(selectedLinesDiff.newLines).length; 249 | const endPos = { line: endLine, ch: endCh }; 250 | return { type: "clearSelection", newCursor: endPos }; 251 | } 252 | -------------------------------------------------------------------------------- /src/commands/wrapInCallout/wrapCurrentLineInCallout.ts: -------------------------------------------------------------------------------- 1 | import { type Editor, type EditorPosition } from "obsidian"; 2 | import { type CalloutID } from "obsidian-callout-manager"; 3 | import { type PluginSettingsManager } from "../../pluginSettingsManager"; 4 | import { type AutoSelectionWhenNothingSelectedMode } from "../../settings/autoSelectionModes"; 5 | import { 6 | type CalloutHeaderParts, 7 | constructCalloutHeaderFromParts, 8 | getNewCalloutHeaderParts, 9 | getTitleRange, 10 | } from "../../utils/calloutTitleUtils"; 11 | import { throwNever } from "../../utils/errorUtils"; 12 | import { 13 | type CursorOrSelectionAction, 14 | runCursorOrSelectionAction, 15 | type SetCursorAction, 16 | type SetSelectionAction, 17 | } from "../../utils/selectionUtils"; 18 | 19 | /** 20 | * Wraps the cursor's current line in a callout. 21 | */ 22 | export function wrapCurrentLineInCallout({ 23 | editor, 24 | calloutID, 25 | pluginSettingsManager, 26 | }: { 27 | editor: Editor; 28 | calloutID: CalloutID; 29 | pluginSettingsManager: PluginSettingsManager; 30 | }): void { 31 | const oldCursor = editor.getCursor(); 32 | const { line } = oldCursor; 33 | const oldLineText = editor.getLine(line); 34 | const calloutHeaderParts = getNewCalloutHeaderParts({ 35 | calloutID, 36 | maybeTitleFromHeading: null, 37 | pluginSettingsManager, 38 | }); 39 | const calloutHeader = constructCalloutHeaderFromParts(calloutHeaderParts); 40 | const newCalloutText = getNewCalloutText({ calloutHeader, oldLineText }); 41 | editor.replaceRange(newCalloutText, { line, ch: 0 }, { line, ch: oldLineText.length }); 42 | setSelectionOrCursorAfterWrappingCurrentLine({ 43 | editor, 44 | oldCursor, 45 | oldLineText, 46 | pluginSettingsManager, 47 | calloutHeaderParts, 48 | }); 49 | } 50 | 51 | function getNewCalloutText({ 52 | calloutHeader, 53 | oldLineText, 54 | }: { 55 | calloutHeader: string; 56 | oldLineText: string; 57 | }): string { 58 | const prependedLine = `> ${oldLineText}`; 59 | const newCalloutText = `${calloutHeader}\n${prependedLine}`; 60 | return newCalloutText; 61 | } 62 | 63 | /** 64 | * Sets the selection or cursor (depending on user setting) after wrapping the current line in a 65 | * callout. 66 | */ 67 | function setSelectionOrCursorAfterWrappingCurrentLine({ 68 | editor, 69 | oldCursor, 70 | oldLineText, 71 | pluginSettingsManager, 72 | calloutHeaderParts, 73 | }: { 74 | editor: Editor; 75 | oldCursor: EditorPosition; 76 | oldLineText: string; 77 | pluginSettingsManager: PluginSettingsManager; 78 | calloutHeaderParts: CalloutHeaderParts; 79 | }): void { 80 | const { whenNothingSelected } = pluginSettingsManager.getSetting("autoSelectionModes"); 81 | const cursorOrSelectionAction = getCursorOrSelectionActionAfterWrappingCurrentLine({ 82 | oldCursor, 83 | oldLineText, 84 | whenNothingSelected, 85 | calloutHeaderParts, 86 | }); 87 | runCursorOrSelectionAction({ editor, action: cursorOrSelectionAction }); 88 | } 89 | 90 | export function getCursorOrSelectionActionAfterWrappingCurrentLine({ 91 | oldCursor, 92 | oldLineText, 93 | whenNothingSelected, 94 | calloutHeaderParts, 95 | }: { 96 | oldCursor: EditorPosition; 97 | oldLineText: string; 98 | whenNothingSelected: AutoSelectionWhenNothingSelectedMode; 99 | calloutHeaderParts: CalloutHeaderParts; 100 | }): CursorOrSelectionAction { 101 | switch (whenNothingSelected) { 102 | case "selectHeaderToCursor": { 103 | return getSelectHeaderToCursorAction({ oldCursor, oldLineText }); 104 | } 105 | case "selectFull": { 106 | return getSelectFullCalloutAction({ oldCursor, oldLineText }); 107 | } 108 | case "selectTitle": { 109 | return getSelectTitleAction({ oldCursor, calloutHeaderParts }); 110 | } 111 | case "originalCursor": { 112 | return getCursorToOriginalRelativePositionAction({ oldCursor }); 113 | } 114 | case "cursorEnd": { 115 | return getCursorToEndOfLineAction({ oldCursor, oldLineText }); 116 | } 117 | default: 118 | throwNever(whenNothingSelected); 119 | } 120 | } 121 | 122 | /** 123 | * Selects the full callout after wrapping the current line in a callout. 124 | */ 125 | function getSelectFullCalloutAction({ 126 | oldCursor, 127 | oldLineText, 128 | }: { 129 | oldCursor: EditorPosition; 130 | oldLineText: string; 131 | }): SetSelectionAction { 132 | const newFrom = { line: oldCursor.line, ch: 0 }; 133 | const newTo = { line: oldCursor.line + 1, ch: oldLineText.length + 2 }; 134 | return { type: "setSelection", newRange: { from: newFrom, to: newTo } }; 135 | } 136 | 137 | /** 138 | * Selects from the start of the callout header to the cursor's original relative position within 139 | * the text. 140 | */ 141 | function getSelectHeaderToCursorAction({ 142 | oldCursor, 143 | oldLineText, 144 | }: { 145 | oldCursor: EditorPosition; 146 | oldLineText: string; 147 | }): SetSelectionAction { 148 | const newFrom = { line: oldCursor.line, ch: 0 }; 149 | // TODO: If the user is in insert mode or non-vim mode, we should only add 2 to the cursor's ch 150 | const newToCh = Math.min(oldCursor.ch + 3, oldLineText.length + 2); 151 | const newTo = { line: oldCursor.line + 1, ch: newToCh }; 152 | return { type: "setSelection", newRange: { from: newFrom, to: newTo } }; 153 | } 154 | 155 | function getSelectTitleAction({ 156 | oldCursor, 157 | calloutHeaderParts, 158 | }: { 159 | oldCursor: EditorPosition; 160 | calloutHeaderParts: CalloutHeaderParts; 161 | }): SetSelectionAction { 162 | const titleRange = getTitleRange({ calloutHeaderParts, line: oldCursor.line }); 163 | return { type: "setSelection", newRange: titleRange }; 164 | } 165 | 166 | function getCursorToOriginalRelativePositionAction({ 167 | oldCursor, 168 | }: { 169 | oldCursor: EditorPosition; 170 | }): SetCursorAction { 171 | const { line, ch } = oldCursor; 172 | return { type: "setCursor", newPosition: { line: line + 1, ch: ch + 2 } }; 173 | } 174 | 175 | function getCursorToEndOfLineAction({ 176 | oldCursor, 177 | oldLineText, 178 | }: { 179 | oldCursor: EditorPosition; 180 | oldLineText: string; 181 | }): SetCursorAction { 182 | return { 183 | type: "setCursor", 184 | newPosition: { line: oldCursor.line + 1, ch: oldLineText.length + 2 }, 185 | }; 186 | } 187 | -------------------------------------------------------------------------------- /src/commands/wrapInCallout/wrapLinesInCallout.ts: -------------------------------------------------------------------------------- 1 | import { type Command, type Editor } from "obsidian"; 2 | import { type CalloutID } from "obsidian-callout-manager"; 3 | import { type PluginSettingsManager } from "../../pluginSettingsManager"; 4 | import { getPartialWrapLinesInCalloutCommandID } from "../commandIDs"; 5 | import { wrapCurrentLineInCallout } from "./wrapCurrentLineInCallout"; 6 | import { wrapSelectedLinesInCallout } from "./wrapSelectedLinesInCallout"; 7 | 8 | /** 9 | * Makes a command that wraps the current line, or selected lines if there are any, in the given 10 | * callout. 11 | */ 12 | export function makeWrapLinesInCalloutCommand( 13 | calloutID: CalloutID, 14 | pluginSettingsManager: PluginSettingsManager 15 | ): Command { 16 | return { 17 | id: getPartialWrapLinesInCalloutCommandID(calloutID), 18 | name: `Wrap lines in ${calloutID} callout`, 19 | editorCallback: (editor) => wrapLinesInCallout(editor, calloutID, pluginSettingsManager), 20 | }; 21 | } 22 | 23 | function wrapLinesInCallout( 24 | editor: Editor, 25 | calloutID: CalloutID, 26 | pluginSettingsManager: PluginSettingsManager 27 | ): void { 28 | if (editor.somethingSelected()) { 29 | wrapSelectedLinesInCallout(editor, calloutID, pluginSettingsManager); 30 | return; 31 | } 32 | wrapCurrentLineInCallout({ 33 | editor, 34 | calloutID, 35 | pluginSettingsManager, 36 | }); 37 | } 38 | -------------------------------------------------------------------------------- /src/commands/wrapInCallout/wrapSelectedLinesInCallout.ts: -------------------------------------------------------------------------------- 1 | import { type Editor, type EditorPosition } from "obsidian"; 2 | import { type CalloutID } from "obsidian-callout-manager"; 3 | import { type PluginSettingsManager } from "../../pluginSettingsManager"; 4 | import { type AutoSelectionWhenTextSelectedMode } from "../../settings/autoSelectionModes"; 5 | import { getLastElement, type NonEmptyStringArray } from "../../utils/arrayUtils"; 6 | import { 7 | type CalloutHeaderParts, 8 | constructCalloutHeaderFromParts, 9 | getCustomHeadingTitleIfExists, 10 | getNewCalloutHeaderParts, 11 | getTitleRange, 12 | } from "../../utils/calloutTitleUtils"; 13 | import { throwNever } from "../../utils/errorUtils"; 14 | import { 15 | type ClearSelectionAction, 16 | type CursorOrSelectionAction, 17 | type CursorPositions, 18 | getCalloutStartPos, 19 | getClearSelectionCursorStartAction, 20 | getCursorPositions, 21 | getLastLineDiff, 22 | getNewFromPosition, 23 | getNewPositionWithinLine, 24 | getNewToPosition, 25 | getSelectedLinesRangeAndText, 26 | type LineDiff, 27 | runCursorOrSelectionAction, 28 | type SelectedLinesDiff, 29 | type SetSelectionAction, 30 | type SetSelectionInCorrectDirectionAction, 31 | } from "../../utils/selectionUtils"; 32 | import { getTextLines } from "../../utils/stringUtils"; 33 | 34 | /** 35 | * Wraps the selected lines in a callout. 36 | */ 37 | export function wrapSelectedLinesInCallout( 38 | editor: Editor, 39 | calloutID: CalloutID, 40 | pluginSettingsManager: PluginSettingsManager 41 | ): void { 42 | const originalCursorPositions = getCursorPositions(editor); // Save cursor positions before editing 43 | const { selectedLinesRange, selectedLinesText } = getSelectedLinesRangeAndText(editor); 44 | const selectedLines = getTextLines(selectedLinesText); 45 | const { maybeTitleFromHeading, rawBodyLines } = 46 | getCalloutTitleAndBodyFromSelectedLines(selectedLines); 47 | const calloutHeaderParts = getNewCalloutHeaderParts({ 48 | calloutID, 49 | maybeTitleFromHeading, 50 | pluginSettingsManager, 51 | }); 52 | const newLines = getNewCalloutLines({ calloutHeaderParts, rawBodyLines }); 53 | const selectedLinesDiff = { oldLines: selectedLines, newLines }; 54 | const newText = newLines.join("\n"); 55 | editor.replaceRange(newText, selectedLinesRange.from, selectedLinesRange.to); 56 | setSelectionOrCursorAfterWrappingSelectedLines({ 57 | editor, 58 | selectedLinesDiff, 59 | originalCursorPositions, 60 | pluginSettingsManager, 61 | calloutHeaderParts, 62 | }); 63 | } 64 | 65 | /** 66 | * Gets the callout title (if provided via first selected line as a heading) and raw (i.e. not yet 67 | * prepended) body lines from the selected text lines. Whether the first selected line is a heading 68 | * determines whether it is included in the raw body lines. 69 | */ 70 | function getCalloutTitleAndBodyFromSelectedLines(selectedLines: NonEmptyStringArray): { 71 | maybeTitleFromHeading: string | null; 72 | rawBodyLines: string[]; 73 | } { 74 | const [firstSelectedLine, ...restSelectedLines] = selectedLines; 75 | const maybeTitleFromHeading = getCustomHeadingTitleIfExists({ firstSelectedLine }); 76 | const rawBodyLines = maybeTitleFromHeading === null ? selectedLines : restSelectedLines; 77 | return { maybeTitleFromHeading, rawBodyLines }; 78 | } 79 | 80 | /** 81 | * Gets the new callout lines to replace the selected lines with. 82 | */ 83 | function getNewCalloutLines({ 84 | calloutHeaderParts, 85 | rawBodyLines, 86 | }: { 87 | calloutHeaderParts: CalloutHeaderParts; 88 | rawBodyLines: string[]; 89 | }): NonEmptyStringArray { 90 | const calloutHeader = constructCalloutHeaderFromParts(calloutHeaderParts); 91 | const calloutBodyLines = rawBodyLines.map((line) => `> ${line}`); 92 | return [calloutHeader, ...calloutBodyLines]; 93 | } 94 | 95 | /** 96 | * Sets the selection or cursor (depending on user setting) after wrapping the selected lines in a 97 | * callout. 98 | */ 99 | function setSelectionOrCursorAfterWrappingSelectedLines({ 100 | editor, 101 | selectedLinesDiff, 102 | originalCursorPositions, 103 | pluginSettingsManager, 104 | calloutHeaderParts, 105 | }: { 106 | editor: Editor; 107 | selectedLinesDiff: SelectedLinesDiff; 108 | originalCursorPositions: CursorPositions; 109 | pluginSettingsManager: PluginSettingsManager; 110 | calloutHeaderParts: CalloutHeaderParts; 111 | }): void { 112 | const { whenTextSelected } = pluginSettingsManager.getSetting("autoSelectionModes"); 113 | const cursorOrSelectionAction = getCursorOrSelectionActionAfterWrappingSelectedLines({ 114 | whenTextSelected, 115 | selectedLinesDiff, 116 | originalCursorPositions, 117 | calloutHeaderParts, 118 | }); 119 | runCursorOrSelectionAction({ editor, action: cursorOrSelectionAction }); 120 | } 121 | 122 | export function getCursorOrSelectionActionAfterWrappingSelectedLines({ 123 | whenTextSelected, 124 | selectedLinesDiff, 125 | originalCursorPositions, 126 | calloutHeaderParts, 127 | }: { 128 | whenTextSelected: AutoSelectionWhenTextSelectedMode; 129 | selectedLinesDiff: SelectedLinesDiff; 130 | originalCursorPositions: CursorPositions; 131 | calloutHeaderParts: CalloutHeaderParts; 132 | }): CursorOrSelectionAction { 133 | const { oldLines, newLines } = selectedLinesDiff; 134 | const didAddHeaderLine = oldLines.length !== newLines.length; 135 | switch (whenTextSelected) { 136 | case "selectHeaderToCursor": { 137 | return getSelectHeaderToCursorAction({ 138 | selectedLinesDiff, 139 | originalCursorPositions, 140 | didAddHeaderLine, 141 | }); 142 | } 143 | case "selectFull": { 144 | return getSelectFullAction({ selectedLinesDiff, originalCursorPositions, didAddHeaderLine }); 145 | } 146 | case "selectTitle": { 147 | return getSelectTitleAction({ originalCursorPositions, calloutHeaderParts }); 148 | } 149 | case "originalSelection": { 150 | return getOriginalSelectionAction({ 151 | selectedLinesDiff, 152 | originalCursorPositions, 153 | didAddHeaderLine, 154 | }); 155 | } 156 | case "clearSelectionCursorTo": { 157 | return getClearSelectionCursorToAction({ selectedLinesDiff, originalCursorPositions }); 158 | } 159 | case "clearSelectionCursorStart": { 160 | return getClearSelectionCursorStartAction({ originalCursorPositions }); 161 | } 162 | case "clearSelectionCursorEnd": { 163 | return getClearSelectionCursorEndAction({ 164 | selectedLinesDiff, 165 | originalCursorPositions, 166 | didAddHeaderLine, 167 | }); 168 | } 169 | default: 170 | throwNever(whenTextSelected); 171 | } 172 | } 173 | 174 | /** 175 | * Selects the callout header to the cursor position. 176 | */ 177 | function getSelectHeaderToCursorAction({ 178 | selectedLinesDiff, 179 | originalCursorPositions, 180 | didAddHeaderLine, 181 | }: { 182 | selectedLinesDiff: SelectedLinesDiff; 183 | originalCursorPositions: CursorPositions; 184 | didAddHeaderLine: boolean; 185 | }): SetSelectionInCorrectDirectionAction { 186 | const { from: oldFrom, to: oldTo } = originalCursorPositions; 187 | const newFrom = getNewFromPosition({ oldFrom, selectedLinesDiff }); 188 | 189 | const newToLine = didAddHeaderLine ? oldTo.line + 1 : oldTo.line; 190 | const lastLineDiff = getLastLineDiff(selectedLinesDiff); 191 | const newToCh = getNewPositionWithinLine({ oldCh: oldTo.ch, lineDiff: lastLineDiff }); 192 | const newTo = { line: newToLine, ch: newToCh }; 193 | 194 | const newRange = { from: newFrom, to: newTo }; 195 | return { type: "setSelectionInCorrectDirection", newRange, originalCursorPositions }; 196 | } 197 | 198 | /** 199 | * Selects the original selection after wrapping the selected lines in a callout. 200 | */ 201 | function getOriginalSelectionAction({ 202 | selectedLinesDiff, 203 | originalCursorPositions, 204 | didAddHeaderLine, 205 | }: { 206 | selectedLinesDiff: SelectedLinesDiff; 207 | originalCursorPositions: CursorPositions; 208 | didAddHeaderLine: boolean; 209 | }): SetSelectionInCorrectDirectionAction { 210 | const { from: oldFrom, to: oldTo } = originalCursorPositions; 211 | const newFromLine = didAddHeaderLine ? oldFrom.line + 1 : oldFrom.line; 212 | const firstLineDiff = getFirstLineDiff({ selectedLinesDiff, didAddHeaderLine }); 213 | const newFromCh = getNewPositionWithinLine({ oldCh: oldFrom.ch, lineDiff: firstLineDiff }); 214 | const newFrom = { line: newFromLine, ch: newFromCh }; 215 | 216 | const newTo = getNewToPosition({ oldTo, selectedLinesDiff }); 217 | 218 | const newRange = { from: newFrom, to: newTo }; 219 | return { type: "setSelectionInCorrectDirection", newRange, originalCursorPositions }; 220 | } 221 | 222 | /** 223 | * Gets the line diff for the first selected line. Matches that line with the second new line if a 224 | * header line was added. Otherwise, the first selected line was a heading line that we can match 225 | * with the first new line (which is the header line). 226 | */ 227 | function getFirstLineDiff({ 228 | selectedLinesDiff: { oldLines, newLines }, 229 | didAddHeaderLine, 230 | }: { 231 | selectedLinesDiff: SelectedLinesDiff; 232 | didAddHeaderLine: boolean; 233 | }): LineDiff { 234 | const oldLine = oldLines[0]; 235 | if (!didAddHeaderLine) { 236 | // `oldLine` is a heading line that we can match with the callout header 237 | return { oldLine, newLine: newLines[0] }; 238 | } 239 | // Match `oldLine` with the second new line (first new body line) 240 | const secondNewLine = newLines[1]; 241 | if (secondNewLine === undefined) { 242 | throw new Error("Expected first non-header line to be defined"); 243 | } 244 | return { oldLine, newLine: secondNewLine }; 245 | } 246 | 247 | /** 248 | * Selects the full callout after wrapping the selected lines in a callout. 249 | */ 250 | function getSelectFullAction({ 251 | selectedLinesDiff, 252 | originalCursorPositions, 253 | didAddHeaderLine, 254 | }: { 255 | selectedLinesDiff: SelectedLinesDiff; 256 | originalCursorPositions: CursorPositions; 257 | didAddHeaderLine: boolean; 258 | }): SetSelectionInCorrectDirectionAction { 259 | const startPos = getCalloutStartPos({ originalCursorPositions }); 260 | const endPos = getCalloutEndPos({ selectedLinesDiff, originalCursorPositions, didAddHeaderLine }); 261 | const newRange = { from: startPos, to: endPos }; 262 | return { type: "setSelectionInCorrectDirection", newRange, originalCursorPositions }; 263 | } 264 | 265 | /** 266 | * Selects the callout title after wrapping the selected lines in a callout. 267 | */ 268 | function getSelectTitleAction({ 269 | originalCursorPositions, 270 | calloutHeaderParts, 271 | }: { 272 | originalCursorPositions: CursorPositions; 273 | calloutHeaderParts: CalloutHeaderParts; 274 | }): SetSelectionAction { 275 | const titleRange = getTitleRange({ calloutHeaderParts, line: originalCursorPositions.from.line }); 276 | return { type: "setSelection", newRange: titleRange }; 277 | } 278 | 279 | function getClearSelectionCursorToAction({ 280 | selectedLinesDiff, 281 | originalCursorPositions, 282 | }: { 283 | selectedLinesDiff: SelectedLinesDiff; 284 | originalCursorPositions: CursorPositions; 285 | }): ClearSelectionAction { 286 | const { to: oldTo } = originalCursorPositions; 287 | const newTo = getNewToPosition({ oldTo, selectedLinesDiff }); 288 | // TODO: If user is in insert mode (with selection) or non-vim mode, we shouldn't subtract one 289 | const newCursor = { line: newTo.line, ch: newTo.ch - 1 }; 290 | return { type: "clearSelection", newCursor }; 291 | } 292 | 293 | /** 294 | * Clears the selection and moves the cursor to the end of the callout after wrapping the selected 295 | * lines in a callout. 296 | */ 297 | function getClearSelectionCursorEndAction({ 298 | selectedLinesDiff, 299 | originalCursorPositions, 300 | didAddHeaderLine, 301 | }: { 302 | selectedLinesDiff: SelectedLinesDiff; 303 | originalCursorPositions: CursorPositions; 304 | didAddHeaderLine: boolean; 305 | }): ClearSelectionAction { 306 | const endPos = getCalloutEndPos({ selectedLinesDiff, originalCursorPositions, didAddHeaderLine }); 307 | return { type: "clearSelection", newCursor: endPos }; 308 | } 309 | 310 | function getCalloutEndPos({ 311 | selectedLinesDiff, 312 | originalCursorPositions, 313 | didAddHeaderLine, 314 | }: { 315 | selectedLinesDiff: SelectedLinesDiff; 316 | originalCursorPositions: CursorPositions; 317 | didAddHeaderLine: boolean; 318 | }): EditorPosition { 319 | const { to: oldTo } = originalCursorPositions; 320 | const endLine = didAddHeaderLine ? oldTo.line + 1 : oldTo.line; 321 | const endCh = getLastElement(selectedLinesDiff.newLines).length; 322 | return { line: endLine, ch: endCh }; 323 | } 324 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { Plugin } from "obsidian"; 2 | import { PluginCommandManager } from "./pluginCommandManager"; 3 | import { PluginSettingsManager } from "./pluginSettingsManager"; 4 | 5 | export default class CalloutToggleCommandsPlugin extends Plugin { 6 | public pluginSettingsManager = new PluginSettingsManager(this); 7 | private pluginCommandManager = new PluginCommandManager(this, this.pluginSettingsManager); 8 | 9 | private logInfo(message: string): void { 10 | console.log(`${this.manifest.name}: ${message}`); 11 | } 12 | 13 | // eslint-disable-next-line @typescript-eslint/no-misused-promises 14 | async onload(): Promise { 15 | // this.logInfo("Plugin loaded."); 16 | 17 | await this.pluginSettingsManager.setupSettingsTab(); 18 | 19 | this.app.workspace.onLayoutReady(this.onLayoutReady.bind(this)); 20 | } 21 | 22 | /** 23 | * It's recommended to put setup code here in `onLayoutReady` over `onload` when possible, for 24 | * better Obsidian loading performance. See Obsidian docs: 25 | * https://docs.obsidian.md/Plugins/Guides/Optimizing+plugin+load+time 26 | */ 27 | private async onLayoutReady(): Promise { 28 | await this.pluginCommandManager.setupCommands(); 29 | } 30 | 31 | onunload(): void { 32 | // this.logInfo("Plugin unloaded."); 33 | this.pluginCommandManager.onPluginUnload(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/pluginCommandManager.ts: -------------------------------------------------------------------------------- 1 | import { type Command, type Plugin } from "obsidian"; 2 | import { type CalloutID } from "obsidian-callout-manager"; 3 | import { BUILTIN_CALLOUT_IDS } from "./callouts/builtinCallouts"; 4 | import { 5 | type CalloutManagerOwnedHandle, 6 | getCalloutIDsFromCalloutManager, 7 | getCalloutManagerAPIHandleIfInstalled, 8 | } from "./callouts/calloutManager"; 9 | import { getFullWrapLinesInCalloutCommandID } from "./commands/commandIDs"; 10 | import { makeRemoveCalloutFromSelectedLinesCommand } from "./commands/removeCallout"; 11 | import { makeWrapLinesInCalloutCommand } from "./commands/wrapInCallout/wrapLinesInCallout"; 12 | import { type PluginSettingsManager } from "./pluginSettingsManager"; 13 | import { filterOutElements } from "./utils/arrayUtils"; 14 | 15 | export class PluginCommandManager { 16 | calloutManager?: CalloutManagerOwnedHandle; 17 | addedCommandCalloutIDsSet = new Set(); 18 | onCalloutManagerChange = this.resyncCalloutCommands.bind(this); 19 | 20 | constructor(private plugin: Plugin, private pluginSettingsManager: PluginSettingsManager) {} 21 | 22 | public onPluginUnload(): void { 23 | if (this.calloutManager === undefined) { 24 | return; 25 | } 26 | this.calloutManager.off("change", this.onCalloutManagerChange); 27 | } 28 | 29 | public async setupCommands(): Promise { 30 | await this.setupCalloutManagerIfInstalled(); 31 | this.addAllCommands(); 32 | } 33 | 34 | private async setupCalloutManagerIfInstalled(): Promise { 35 | const maybeAPIHandle = await getCalloutManagerAPIHandleIfInstalled(this.plugin); 36 | if (maybeAPIHandle === undefined) { 37 | return; 38 | } 39 | this.calloutManager = maybeAPIHandle; 40 | this.calloutManager.on("change", this.onCalloutManagerChange); 41 | } 42 | 43 | private resyncCalloutCommands(): void { 44 | const allCalloutIDs = this.getAllCalloutIDs(); 45 | this.removeOutdatedCalloutCommands(allCalloutIDs); 46 | this.addMissingCalloutCommands(allCalloutIDs); 47 | } 48 | 49 | /** 50 | * Returns all available Obsidian callout IDs. Uses the Callout Manager plugin API if available; 51 | * otherwise uses a hard-coded list of built-in callout IDs. 52 | */ 53 | private getAllCalloutIDs(): readonly CalloutID[] { 54 | if (this.calloutManager === undefined) { 55 | return BUILTIN_CALLOUT_IDS; 56 | } 57 | return getCalloutIDsFromCalloutManager(this.calloutManager); 58 | } 59 | 60 | private removeOutdatedCalloutCommands(newCalloutIDs: readonly CalloutID[]): void { 61 | const existingCommandCalloutIDs = Array.from(this.addedCommandCalloutIDsSet); 62 | const newCalloutIDsSet = new Set(newCalloutIDs); 63 | const outdatedCalloutIDs = filterOutElements(existingCommandCalloutIDs, newCalloutIDsSet); 64 | outdatedCalloutIDs.forEach((calloutID) => this.removeWrapLinesInCalloutCommand(calloutID)); 65 | } 66 | 67 | private removeWrapLinesInCalloutCommand(calloutID: CalloutID): void { 68 | const pluginID = this.plugin.manifest.id; 69 | const fullCommandID = getFullWrapLinesInCalloutCommandID({ pluginID, calloutID }); 70 | this.removeCommand({ fullCommandID }); 71 | this.addedCommandCalloutIDsSet.delete(calloutID); 72 | } 73 | 74 | private addMissingCalloutCommands(newCalloutIDs: readonly CalloutID[]): void { 75 | const missingCalloutIDs = filterOutElements(newCalloutIDs, this.addedCommandCalloutIDsSet); 76 | missingCalloutIDs.forEach((calloutID) => this.addWrapLinesInCalloutCommand(calloutID)); 77 | } 78 | 79 | private addAllCommands(): void { 80 | this.addAllWrapLinesInCalloutCommands(); 81 | this.addRemoveCalloutFromSelectedLinesCommand(); 82 | } 83 | 84 | private addAllWrapLinesInCalloutCommands(): void { 85 | const allCalloutIDs = this.getAllCalloutIDs(); 86 | allCalloutIDs.forEach((calloutID) => this.addWrapLinesInCalloutCommand(calloutID)); 87 | } 88 | 89 | private addWrapLinesInCalloutCommand(calloutID: CalloutID): void { 90 | const wrapLinesInCalloutCommand = makeWrapLinesInCalloutCommand( 91 | calloutID, 92 | this.pluginSettingsManager 93 | ); 94 | this.addCommand(wrapLinesInCalloutCommand); 95 | this.addedCommandCalloutIDsSet.add(calloutID); 96 | } 97 | 98 | private addCommand(command: Command): void { 99 | this.plugin.addCommand(command); 100 | } 101 | 102 | private addRemoveCalloutFromSelectedLinesCommand(): void { 103 | const removeCalloutFromSelectedLinesCommand = makeRemoveCalloutFromSelectedLinesCommand( 104 | this.pluginSettingsManager 105 | ); 106 | this.addCommand(removeCalloutFromSelectedLinesCommand); 107 | } 108 | 109 | private removeCommand({ fullCommandID }: { fullCommandID: string }): void { 110 | this.plugin.app.commands.removeCommand(fullCommandID); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /src/pluginSettingsManager.ts: -------------------------------------------------------------------------------- 1 | import { type Plugin, PluginSettingTab, Setting } from "obsidian"; 2 | import { 3 | afterRemovingCalloutAutoSelectionOptions, 4 | type AutoSelectionModes, 5 | DEFAULT_AUTO_SELECTION_MODES, 6 | migrateV1SettingToV2AutoSelectionModes, 7 | whenNothingSelectedAutoSelectionOptions, 8 | whenTextSelectedAutoSelectionOptions, 9 | } from "./settings/autoSelectionModes"; 10 | import { createTypedDropdownSetting } from "./settings/typedSettingsHelpers"; 11 | 12 | type DefaultFoldableState = "unfoldable" | "foldable-expanded" | "foldable-collapsed"; 13 | type CalloutIDCapitalization = "lower" | "upper" | "sentence" | "title"; 14 | 15 | type PluginSettingsV1 = { 16 | pluginVersion: undefined; // 1.1.0, but not set 17 | shouldUseExplicitTitle: boolean; 18 | calloutIDCapitalization: CalloutIDCapitalization; 19 | defaultFoldableState: DefaultFoldableState; 20 | shouldSetSelectionAfterCurrentLineWrap: boolean; 21 | }; 22 | 23 | type PluginSettingsV2 = { 24 | pluginVersion: "1.2.0"; 25 | shouldUseExplicitTitle: boolean; 26 | calloutIDCapitalization: CalloutIDCapitalization; 27 | defaultFoldableState: DefaultFoldableState; 28 | autoSelectionModes: Readonly; 29 | }; 30 | 31 | /** 32 | * Migrates empty or old settings to the current version (1.2.0), with default values as well as V1 33 | * settings migrated to V2 equivalents. 34 | */ 35 | function migrateSettingsToV2(oldSettings: Partial): PluginSettingsV2 { 36 | const { shouldSetSelectionAfterCurrentLineWrap, pluginVersion: _, ...rest } = oldSettings; 37 | if (shouldSetSelectionAfterCurrentLineWrap === undefined) { 38 | return { ...deepCloneSettings(DEFAULT_SETTINGS), ...rest }; 39 | } 40 | const autoSelectionModes = migrateV1SettingToV2AutoSelectionModes({ 41 | shouldSetSelectionAfterCurrentLineWrap, 42 | }); 43 | return { ...DEFAULT_SETTINGS, ...rest, autoSelectionModes }; 44 | } 45 | 46 | type SettingKey = keyof PluginSettingsV2; 47 | 48 | /** 49 | * Deep-clones the given settings. There's currently only one nested object: `autoSelectionModes`. 50 | */ 51 | function deepCloneSettings(settings: PluginSettingsV2): PluginSettingsV2 { 52 | const clone: PluginSettingsV2 = { ...settings }; 53 | clone.autoSelectionModes = { ...settings.autoSelectionModes }; 54 | return clone; 55 | } 56 | 57 | export const DEFAULT_SETTINGS: PluginSettingsV2 = { 58 | pluginVersion: "1.2.0", 59 | shouldUseExplicitTitle: true, 60 | calloutIDCapitalization: "lower", 61 | defaultFoldableState: "unfoldable", 62 | autoSelectionModes: DEFAULT_AUTO_SELECTION_MODES, 63 | }; 64 | 65 | export class PluginSettingsManager extends PluginSettingTab { 66 | private settings: PluginSettingsV2 = deepCloneSettings(DEFAULT_SETTINGS); 67 | 68 | constructor(private plugin: Plugin) { 69 | super(plugin.app, plugin); 70 | } 71 | 72 | public async setupSettingsTab(): Promise { 73 | this.settings = await this.loadSettings(); 74 | this.addSettingTab(); 75 | } 76 | 77 | private async loadSettings(): Promise { 78 | const loadedSettings = ((await this.plugin.loadData()) ?? {}) as 79 | | Partial // `Partial` since we didn't used to save full settings 80 | | PluginSettingsV2; 81 | if (loadedSettings.pluginVersion !== "1.2.0") { 82 | // Either empty or old settings (v1.1.0) 83 | const migratedSettings = migrateSettingsToV2(loadedSettings); 84 | await this.plugin.saveData(migratedSettings); 85 | return migratedSettings; 86 | } 87 | return loadedSettings; 88 | } 89 | 90 | private addSettingTab(): void { 91 | this.plugin.addSettingTab(this); 92 | } 93 | 94 | public getSetting(settingKey: K): PluginSettingsV2[K] { 95 | return this.settings[settingKey]; 96 | } 97 | 98 | private async setSetting( 99 | settingKey: K, 100 | value: PluginSettingsV2[K] 101 | ): Promise { 102 | this.settings[settingKey] = value; 103 | await this.saveSettings(); 104 | } 105 | 106 | private async setAutoSelectionMode( 107 | modeKey: K, 108 | value: AutoSelectionModes[K] 109 | ): Promise { 110 | const newAutoSelectionModes = { ...this.settings.autoSelectionModes, [modeKey]: value }; 111 | await this.setSetting("autoSelectionModes", newAutoSelectionModes); 112 | } 113 | 114 | display(): void { 115 | const { containerEl } = this; 116 | 117 | containerEl.empty(); 118 | 119 | new Setting(containerEl).setName("Callout headers").setHeading(); 120 | this.displayExplicitCalloutTitlesSetting(); 121 | this.displayCalloutIDCapitalizationSetting(); 122 | this.displayDefaultFoldableStateSetting(); 123 | 124 | this.displayAutoSelectionModeSettings(); 125 | } 126 | 127 | private displayExplicitCalloutTitlesSetting(): void { 128 | new Setting(this.containerEl) 129 | .setName("Explicit callout titles") 130 | .setDesc( 131 | "Whether inserted callouts should have an explicit or implicit title by default. E.g. `> [!quote] Quote` vs `> [!quote]`." 132 | ) 133 | .addToggle((toggle) => 134 | toggle 135 | .setValue(this.settings.shouldUseExplicitTitle) 136 | .onChange((value) => this.setSetting("shouldUseExplicitTitle", value)) 137 | ); 138 | } 139 | 140 | private displayCalloutIDCapitalizationSetting(): void { 141 | createTypedDropdownSetting({ 142 | containerEl: this.containerEl, 143 | settingName: "Callout ID capitalization", 144 | settingDescription: 145 | "The default capitalization for inserted callout IDs. E.g. `> [!quote]` vs `> [!QUOTE]`.", 146 | dropdownOptions: [ 147 | { value: "lower", displayText: "lower-case" }, 148 | { value: "upper", displayText: "UPPER-CASE" }, 149 | { value: "sentence", displayText: "Sentence-case" }, 150 | { value: "title", displayText: "Title-Case" }, 151 | ], 152 | currentValue: this.settings.calloutIDCapitalization, 153 | onChange: (newValue) => this.setSetting("calloutIDCapitalization", newValue), 154 | }); 155 | } 156 | 157 | private displayDefaultFoldableStateSetting(): void { 158 | createTypedDropdownSetting({ 159 | containerEl: this.containerEl, 160 | settingName: "Foldable callouts", 161 | settingDescription: 162 | "The default folded state for inserted callouts: unfoldable, expanded, or collapsed. E.g. `> [!quote]` vs `> [!quote]+` vs `> [!quote]-`.", 163 | dropdownOptions: [ 164 | { value: "unfoldable", displayText: "Unfoldable" }, 165 | { value: "foldable-expanded", displayText: "Foldable, expanded" }, 166 | { value: "foldable-collapsed", displayText: "Foldable, collapsed" }, 167 | ], 168 | currentValue: this.settings.defaultFoldableState, 169 | onChange: (newValue) => this.setSetting("defaultFoldableState", newValue), 170 | }); 171 | } 172 | 173 | private displayAutoSelectionModeSettings(): void { 174 | new Setting(this.containerEl) 175 | .setName("Auto-selection / auto-cursor") 176 | .setHeading() 177 | .setDesc( 178 | "What to select, or where to place the cursor, after running a command. Selecting up to the header (or full text) can help with switching callout types quickly (by running remove/wrap back to back). But the other modes have their own merits as well. Experiment around to see what you prefer!" 179 | ); 180 | createTypedDropdownSetting({ 181 | containerEl: this.containerEl, 182 | settingName: "After inserting/wrapping with nothing selected", 183 | settingDescription: 184 | "What to select, or where to move the cursor, after inserting a fresh callout or wrapping the current line without any text selected.", 185 | dropdownOptions: whenNothingSelectedAutoSelectionOptions, 186 | currentValue: this.settings.autoSelectionModes.whenNothingSelected, 187 | onChange: (newValue) => this.setAutoSelectionMode("whenNothingSelected", newValue), 188 | }); 189 | createTypedDropdownSetting({ 190 | containerEl: this.containerEl, 191 | settingName: "After wrapping a text selection", 192 | settingDescription: 193 | "What to select, or where to move the cursor, after wrapping selected text in a callout.", 194 | dropdownOptions: whenTextSelectedAutoSelectionOptions, 195 | currentValue: this.settings.autoSelectionModes.whenTextSelected, 196 | onChange: (newValue) => this.setAutoSelectionMode("whenTextSelected", newValue), 197 | }); 198 | createTypedDropdownSetting({ 199 | containerEl: this.containerEl, 200 | settingName: "After removing a callout", 201 | settingDescription: "What to select, or where to move the cursor, after removing a callout.", 202 | dropdownOptions: afterRemovingCalloutAutoSelectionOptions, 203 | currentValue: this.settings.autoSelectionModes.afterRemovingCallout, 204 | onChange: (newValue) => this.setAutoSelectionMode("afterRemovingCallout", newValue), 205 | }); 206 | } 207 | 208 | private async saveSettings(): Promise { 209 | await this.plugin.saveData(this.settings); 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /src/settings/autoSelectionModes.ts: -------------------------------------------------------------------------------- 1 | import { type TypedDropdownOption } from "./typedSettingsHelpers"; 2 | 3 | export const whenNothingSelectedAutoSelectionOptions: readonly TypedDropdownOption[] = 4 | [ 5 | { value: "selectHeaderToCursor", displayText: "Select up to header" }, 6 | { value: "selectFull", displayText: "Select full callout" }, 7 | { value: "selectTitle", displayText: "Select callout title" }, 8 | { value: "originalCursor", displayText: "Keep relative cursor position" }, 9 | { value: "cursorEnd", displayText: "Cursor at end" }, 10 | ]; 11 | 12 | export const whenTextSelectedAutoSelectionOptions: readonly TypedDropdownOption[] = 13 | [ 14 | { value: "selectHeaderToCursor", displayText: "Select up to header" }, 15 | { value: "selectFull", displayText: "Select full callout" }, 16 | { value: "selectTitle", displayText: "Select callout title" }, 17 | { value: "originalSelection", displayText: "Keep relative selection" }, 18 | { value: "clearSelectionCursorTo", displayText: "Clear selection" }, 19 | { value: "clearSelectionCursorStart", displayText: "Clear selection, cursor at start" }, 20 | { value: "clearSelectionCursorEnd", displayText: "Clear selection, cursor at end" }, 21 | ]; 22 | 23 | export const afterRemovingCalloutAutoSelectionOptions: readonly TypedDropdownOption[] = 24 | [ 25 | { value: "originalSelection", displayText: "Keep relative selection" }, 26 | { value: "selectFull", displayText: "Select full remaining lines" }, 27 | { value: "clearSelectionCursorTo", displayText: "Clear selection" }, 28 | { value: "clearSelectionCursorStart", displayText: "Clear selection, cursor at start" }, 29 | { value: "clearSelectionCursorEnd", displayText: "Clear selection, cursor at end" }, 30 | ]; 31 | 32 | export type AutoSelectionWhenNothingSelectedMode = 33 | | "selectHeaderToCursor" 34 | | "selectFull" 35 | | "selectTitle" 36 | | "originalCursor" 37 | | "cursorEnd"; 38 | 39 | export type AutoSelectionWhenTextSelectedMode = 40 | | "selectHeaderToCursor" 41 | | "selectFull" 42 | | "selectTitle" 43 | | "originalSelection" 44 | | "clearSelectionCursorTo" 45 | | "clearSelectionCursorStart" 46 | | "clearSelectionCursorEnd"; 47 | 48 | export type AutoSelectionAfterRemovingCalloutMode = 49 | | "originalSelection" 50 | | "selectFull" 51 | | "clearSelectionCursorTo" 52 | | "clearSelectionCursorStart" 53 | | "clearSelectionCursorEnd"; 54 | 55 | export type AutoSelectionModes = { 56 | /** Cursor/selection behavior after wrapping with no text selected. */ 57 | whenNothingSelected: AutoSelectionWhenNothingSelectedMode; 58 | /** Cursor/selection behavior after wrapping a selection. */ 59 | whenTextSelected: AutoSelectionWhenTextSelectedMode; 60 | /** Cursor/selection behavior after removing a callout. */ 61 | afterRemovingCallout: AutoSelectionAfterRemovingCalloutMode; 62 | }; 63 | 64 | export const DEFAULT_AUTO_SELECTION_MODES: AutoSelectionModes = { 65 | whenNothingSelected: "selectHeaderToCursor", 66 | whenTextSelected: "selectHeaderToCursor", 67 | afterRemovingCallout: "originalSelection", 68 | }; 69 | 70 | export function migrateV1SettingToV2AutoSelectionModes({ 71 | shouldSetSelectionAfterCurrentLineWrap, 72 | }: { 73 | shouldSetSelectionAfterCurrentLineWrap: boolean; 74 | }): AutoSelectionModes { 75 | const whenNothingSelected = shouldSetSelectionAfterCurrentLineWrap 76 | ? "selectHeaderToCursor" 77 | : "originalCursor"; 78 | const { whenTextSelected, afterRemovingCallout } = DEFAULT_AUTO_SELECTION_MODES; 79 | return { whenNothingSelected, whenTextSelected, afterRemovingCallout }; 80 | } 81 | -------------------------------------------------------------------------------- /src/settings/typedSettingsHelpers.ts: -------------------------------------------------------------------------------- 1 | import { Setting } from "obsidian"; 2 | 3 | export type TypedDropdownOption = { 4 | value: ValidOption; 5 | displayText: string; 6 | }; 7 | 8 | /** 9 | * More precisely-typed Obsidian API helper function for creating a dropdown setting. Typing helps 10 | * ensure that the dropdown options provided are valid for the given setting. 11 | */ 12 | export function createTypedDropdownSetting({ 13 | containerEl, 14 | settingName, 15 | settingDescription, 16 | dropdownOptions, 17 | currentValue, 18 | onChange, 19 | }: { 20 | containerEl: HTMLElement; 21 | settingName: string; 22 | settingDescription: string; 23 | dropdownOptions: readonly TypedDropdownOption[]; 24 | currentValue: ValidOption; 25 | onChange: (newValue: ValidOption) => void | Promise; 26 | }): void { 27 | const isValidOption = (value: string): value is ValidOption => 28 | dropdownOptions.some((option) => option.value === value); 29 | new Setting(containerEl) 30 | .setName(settingName) 31 | .setDesc(settingDescription) 32 | .addDropdown((dropdown) => { 33 | for (const { value, displayText } of dropdownOptions) { 34 | dropdown.addOption(value, displayText); 35 | } 36 | dropdown.setValue(currentValue); 37 | dropdown.onChange((value) => { 38 | if (!isValidOption(value)) { 39 | throw new Error(`Invalid dropdown value: ${value}`); 40 | } 41 | return onChange(value); 42 | }); 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /src/tests/autoSelectionModes/afterRemovingCallout.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it, test } from "vitest"; 2 | import { getCursorOrSelectionActionAfterRemovingCallout } from "../../commands/removeCallout"; 3 | import { type AutoSelectionAfterRemovingCalloutMode } from "../../settings/autoSelectionModes"; 4 | import { type CursorPositions, type SelectedLinesDiff } from "../../utils/selectionUtils"; 5 | import { type BeforeAndAfter, type GetExpected } from "./testAutoSelectionMode"; 6 | 7 | type TestParams = { 8 | selectedLinesDiff: SelectedLinesDiff; 9 | originalCursorPositions: CursorPositions; 10 | beforeAndAfter: BeforeAndAfter; 11 | }; 12 | 13 | type AfterRemovingCalloutTest = (testParams: TestParams) => void; 14 | 15 | function testAfterRemovingCallout({ 16 | afterRemovingCallout, 17 | testParams: { selectedLinesDiff, originalCursorPositions, beforeAndAfter }, 18 | getExpected, 19 | }: { 20 | afterRemovingCallout: AutoSelectionAfterRemovingCalloutMode; 21 | testParams: TestParams; 22 | getExpected: GetExpected; 23 | }): void { 24 | const result = getCursorOrSelectionActionAfterRemovingCallout({ 25 | afterRemovingCallout, 26 | selectedLinesDiff, 27 | originalCursorPositions, 28 | }); 29 | const { after } = beforeAndAfter; 30 | const expectedResult = getExpected({ after, originalCursorPositions }); 31 | expect(result).toEqual(expectedResult); 32 | } 33 | 34 | const selectedLinesDiff1: SelectedLinesDiff = { 35 | oldLines: [ 36 | "> [!quote]+ Quote", 37 | "> This is a quote by Aristotle:", 38 | "> It is the mark of an educated mind to be able to entertain a thought without accepting it.", 39 | ], 40 | newLines: [ 41 | "This is a quote by Aristotle:", 42 | "It is the mark of an educated mind to be able to entertain a thought without accepting it.", 43 | ], 44 | }; 45 | const beforeAndAfter1: BeforeAndAfter = { 46 | before: { 47 | start: { line: 2, ch: 0 }, // ">" in "> [!quote]" 48 | end: { line: 4, ch: 92 }, // After "." in "it." 49 | from: { line: 2, ch: 12 }, // "Q" in "Quote" 50 | to: { line: 4, ch: 13 }, // After "m" in "mark" 51 | }, 52 | after: { 53 | start: { line: 2, ch: 0 }, // "T" in "This" 54 | end: { line: 3, ch: 90 }, // After "." in "it." 55 | from: { line: 2, ch: 0 }, // "T" in "This" (clamped here since header is gone) 56 | to: { line: 3, ch: 11 }, // After "m" in "mark" 57 | titleStart: { line: 2, ch: 0 }, // No title 58 | titleEnd: { line: 2, ch: 0 }, // No title 59 | }, 60 | }; 61 | const originalCursorPositions1 = { 62 | anchor: beforeAndAfter1.before.from, 63 | head: beforeAndAfter1.before.to, 64 | from: beforeAndAfter1.before.from, 65 | to: beforeAndAfter1.before.to, 66 | }; 67 | const testParams1: TestParams = { 68 | selectedLinesDiff: selectedLinesDiff1, 69 | originalCursorPositions: originalCursorPositions1, 70 | beforeAndAfter: beforeAndAfter1, 71 | }; 72 | 73 | const selectedLinesDiff2: SelectedLinesDiff = { 74 | oldLines: [ 75 | "> [!quote]+ Custom title", 76 | "> This is a quote by Aristotle:", 77 | "> It is the mark of an educated mind to be able to entertain a thought without accepting it.", 78 | ], 79 | newLines: [ 80 | "### Custom title", 81 | "This is a quote by Aristotle:", 82 | "It is the mark of an educated mind to be able to entertain a thought without accepting it.", 83 | ], 84 | }; 85 | const beforeAndAfter2: BeforeAndAfter = { 86 | before: { 87 | start: { line: 2, ch: 0 }, // ">" in header 88 | end: { line: 4, ch: 92 }, // After "." in "it." 89 | from: { line: 2, ch: 12 }, // "C" in "Custom title" 90 | to: { line: 4, ch: 13 }, // After "m" in "mark" 91 | }, 92 | after: { 93 | start: { line: 2, ch: 0 }, // First "#" in heading 94 | end: { line: 4, ch: 90 }, // After "." in "it." 95 | from: { line: 2, ch: 4 }, // "C" in "Custom title" 96 | to: { line: 4, ch: 11 }, // After "m" in "mark" 97 | titleStart: { line: 2, ch: 4 }, // "C" in "Custom title" 98 | titleEnd: { line: 2, ch: 16 }, // After "e" in "title" 99 | }, 100 | }; 101 | const originalCursorPositions2 = { 102 | anchor: beforeAndAfter2.before.from, 103 | head: beforeAndAfter2.before.to, 104 | from: beforeAndAfter2.before.from, 105 | to: beforeAndAfter2.before.to, 106 | }; 107 | const testParams2: TestParams = { 108 | selectedLinesDiff: selectedLinesDiff2, 109 | originalCursorPositions: originalCursorPositions2, 110 | beforeAndAfter: beforeAndAfter2, 111 | }; 112 | 113 | describe("afterRemovingCallout", () => { 114 | describe("originalSelection", () => { 115 | const testOriginalSelection: AfterRemovingCalloutTest = (testParams) => 116 | testAfterRemovingCallout({ 117 | afterRemovingCallout: "originalSelection", 118 | testParams, 119 | getExpected: ({ after, originalCursorPositions }) => ({ 120 | type: "setSelectionInCorrectDirection", 121 | newRange: { from: after.from, to: after.to }, 122 | originalCursorPositions, 123 | }), 124 | }); 125 | it("should select from the start of the header to the cursor (inclusive)", () => { 126 | testOriginalSelection(testParams1); 127 | }); 128 | test("with custom title", () => { 129 | testOriginalSelection(testParams2); 130 | }); 131 | }); 132 | 133 | describe("selectFull", () => { 134 | const testSelectFull: AfterRemovingCalloutTest = (testParams) => 135 | testAfterRemovingCallout({ 136 | afterRemovingCallout: "selectFull", 137 | testParams, 138 | getExpected: ({ after, originalCursorPositions }) => ({ 139 | type: "setSelectionInCorrectDirection", 140 | newRange: { from: after.start, to: after.end }, 141 | originalCursorPositions, 142 | }), 143 | }); 144 | it("should select the full callout", () => { 145 | testSelectFull(testParams1); 146 | }); 147 | test("with custom title", () => { 148 | testSelectFull(testParams2); 149 | }); 150 | }); 151 | 152 | describe("clearSelectionCursorTo", () => { 153 | const testClearSelectionCursorTo: AfterRemovingCalloutTest = (testParams) => 154 | testAfterRemovingCallout({ 155 | afterRemovingCallout: "clearSelectionCursorTo", 156 | testParams, 157 | getExpected: ({ after }) => ({ 158 | type: "clearSelection", 159 | newCursor: { line: after.to.line, ch: after.to.ch - 1 }, 160 | }), 161 | }); 162 | it("should select the title", () => { 163 | testClearSelectionCursorTo(testParams1); 164 | }); 165 | test("with custom title", () => { 166 | testClearSelectionCursorTo(testParams2); 167 | }); 168 | }); 169 | 170 | describe("clearSelectionCursorStart", () => { 171 | const testClearSelectionCursorStart: AfterRemovingCalloutTest = (testParams) => 172 | testAfterRemovingCallout({ 173 | afterRemovingCallout: "clearSelectionCursorStart", 174 | testParams, 175 | getExpected: ({ after }) => ({ 176 | type: "clearSelection", 177 | newCursor: after.start, 178 | }), 179 | }); 180 | it("should select the original selection", () => { 181 | testClearSelectionCursorStart(testParams1); 182 | }); 183 | test("with custom title", () => { 184 | testClearSelectionCursorStart(testParams2); 185 | }); 186 | }); 187 | 188 | describe("clearSelectionCursorEnd", () => { 189 | const testClearSelectionCursorEnd: AfterRemovingCalloutTest = (testParams) => 190 | testAfterRemovingCallout({ 191 | afterRemovingCallout: "clearSelectionCursorEnd", 192 | testParams, 193 | getExpected: ({ after }) => ({ 194 | type: "clearSelection", 195 | newCursor: after.end, 196 | }), 197 | }); 198 | it("should clear the selection and move the cursor to the end of the callout", () => { 199 | testClearSelectionCursorEnd(testParams1); 200 | }); 201 | test("with custom title", () => { 202 | testClearSelectionCursorEnd(testParams2); 203 | }); 204 | }); 205 | }); 206 | -------------------------------------------------------------------------------- /src/tests/autoSelectionModes/testAutoSelectionMode.ts: -------------------------------------------------------------------------------- 1 | import { type EditorPosition } from "obsidian"; 2 | import { type CursorOrSelectionAction, type CursorPositions } from "../../utils/selectionUtils"; 3 | 4 | export type BeforePositions = { 5 | start: EditorPosition; 6 | end: EditorPosition; 7 | from: EditorPosition; 8 | to: EditorPosition; 9 | }; 10 | 11 | export type AfterPositions = { 12 | start: EditorPosition; 13 | end: EditorPosition; 14 | from: EditorPosition; 15 | to: EditorPosition; 16 | titleStart: EditorPosition; 17 | titleEnd: EditorPosition; 18 | }; 19 | 20 | export type BeforeAndAfter = { 21 | before: BeforePositions; 22 | after: AfterPositions; 23 | }; 24 | 25 | export type GetExpected = ({ 26 | after, 27 | originalCursorPositions, 28 | }: { 29 | after: AfterPositions; 30 | originalCursorPositions: CursorPositions; 31 | }) => CursorOrSelectionAction; 32 | -------------------------------------------------------------------------------- /src/tests/autoSelectionModes/whenNothingSelected.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it, test } from "vitest"; 2 | import { getCursorOrSelectionActionAfterWrappingCurrentLine } from "../../commands/wrapInCallout/wrapCurrentLineInCallout"; 3 | import { type CalloutHeaderParts } from "../../utils/calloutTitleUtils"; 4 | import { type SetCursorAction, type SetSelectionAction } from "../../utils/selectionUtils"; 5 | 6 | describe("whenNothingSelected", () => { 7 | const calloutHeaderParts: CalloutHeaderParts = { 8 | baseCalloutHeader: "> [!quote]", 9 | foldableSuffix: "+", 10 | maybeTitle: "Quote", 11 | }; 12 | const aristotleQuote = "This is a quote by Aristotle."; 13 | describe("selectHeaderToCursor", () => { 14 | it("should select from the start of the header to the cursor (inclusive)", () => { 15 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 16 | oldCursor: { line: 2, ch: 5 }, 17 | oldLineText: aristotleQuote, 18 | whenNothingSelected: "selectHeaderToCursor", 19 | calloutHeaderParts, 20 | }); 21 | const expectedResult: SetSelectionAction = { 22 | type: "setSelection", 23 | newRange: { from: { line: 2, ch: 0 }, to: { line: 3, ch: 8 } }, 24 | }; 25 | expect(result).toEqual(expectedResult); 26 | }); 27 | }); 28 | describe("selectFull", () => { 29 | it("should select the full callout", () => { 30 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 31 | oldCursor: { line: 2, ch: 5 }, 32 | oldLineText: aristotleQuote, 33 | whenNothingSelected: "selectFull", 34 | calloutHeaderParts, 35 | }); 36 | const expectedResult: SetSelectionAction = { 37 | type: "setSelection", 38 | newRange: { from: { line: 2, ch: 0 }, to: { line: 3, ch: aristotleQuote.length + 2 } }, 39 | }; 40 | expect(result).toEqual(expectedResult); 41 | }); 42 | test("even if the current line is empty", () => { 43 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 44 | oldCursor: { line: 4, ch: 0 }, 45 | oldLineText: "", 46 | whenNothingSelected: "selectFull", 47 | calloutHeaderParts, 48 | }); 49 | const expectedResult: SetSelectionAction = { 50 | type: "setSelection", 51 | newRange: { from: { line: 4, ch: 0 }, to: { line: 5, ch: 2 } }, 52 | }; 53 | expect(result).toEqual(expectedResult); 54 | }); 55 | }); 56 | describe("selectTitle", () => { 57 | it("should select the title", () => { 58 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 59 | oldCursor: { line: 2, ch: 5 }, 60 | oldLineText: aristotleQuote, 61 | whenNothingSelected: "selectTitle", 62 | calloutHeaderParts, 63 | }); 64 | const expectedResult: SetSelectionAction = { 65 | type: "setSelection", 66 | newRange: { from: { line: 2, ch: 12 }, to: { line: 2, ch: 17 } }, 67 | }; 68 | expect(result).toEqual(expectedResult); 69 | }); 70 | test("even if the current line is empty", () => { 71 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 72 | oldCursor: { line: 4, ch: 0 }, 73 | oldLineText: "", 74 | whenNothingSelected: "selectTitle", 75 | calloutHeaderParts, 76 | }); 77 | const expectedResult: SetSelectionAction = { 78 | type: "setSelection", 79 | newRange: { from: { line: 4, ch: 12 }, to: { line: 4, ch: 17 } }, 80 | }; 81 | expect(result).toEqual(expectedResult); 82 | }); 83 | }); 84 | describe("originalCursor", () => { 85 | it("should keep the cursor at the same relative position", () => { 86 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 87 | oldCursor: { line: 2, ch: 5 }, 88 | oldLineText: aristotleQuote, 89 | whenNothingSelected: "originalCursor", 90 | calloutHeaderParts, 91 | }); 92 | const expectedResult: SetCursorAction = { 93 | type: "setCursor", 94 | newPosition: { line: 3, ch: 7 }, 95 | }; 96 | expect(result).toEqual(expectedResult); 97 | }); 98 | test("even if the current line is empty", () => { 99 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 100 | oldCursor: { line: 4, ch: 0 }, 101 | oldLineText: "", 102 | whenNothingSelected: "originalCursor", 103 | calloutHeaderParts, 104 | }); 105 | const expectedResult: SetCursorAction = { 106 | type: "setCursor", 107 | newPosition: { line: 5, ch: 2 }, 108 | }; 109 | expect(result).toEqual(expectedResult); 110 | }); 111 | }); 112 | describe("cursorEnd", () => { 113 | it("should move the cursor to the end of the callout", () => { 114 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 115 | oldCursor: { line: 2, ch: 5 }, 116 | oldLineText: aristotleQuote, 117 | whenNothingSelected: "cursorEnd", 118 | calloutHeaderParts, 119 | }); 120 | const expectedResult: SetCursorAction = { 121 | type: "setCursor", 122 | newPosition: { line: 3, ch: aristotleQuote.length + 2 }, 123 | }; 124 | expect(result).toEqual(expectedResult); 125 | }); 126 | test("even if the current line is empty", () => { 127 | const result = getCursorOrSelectionActionAfterWrappingCurrentLine({ 128 | oldCursor: { line: 4, ch: 0 }, 129 | oldLineText: "", 130 | whenNothingSelected: "cursorEnd", 131 | calloutHeaderParts, 132 | }); 133 | const expectedResult: SetCursorAction = { 134 | type: "setCursor", 135 | newPosition: { line: 5, ch: 2 }, 136 | }; 137 | expect(result).toEqual(expectedResult); 138 | }); 139 | }); 140 | }); 141 | -------------------------------------------------------------------------------- /src/tests/autoSelectionModes/whenTextSelected.test.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, it, test } from "vitest"; 2 | import { getCursorOrSelectionActionAfterWrappingSelectedLines } from "../../commands/wrapInCallout/wrapSelectedLinesInCallout"; 3 | import { type AutoSelectionWhenTextSelectedMode } from "../../settings/autoSelectionModes"; 4 | import { type CalloutHeaderParts } from "../../utils/calloutTitleUtils"; 5 | import { type CursorPositions, type SelectedLinesDiff } from "../../utils/selectionUtils"; 6 | import { type BeforeAndAfter, type GetExpected } from "./testAutoSelectionMode"; 7 | 8 | export type TestParams = { 9 | calloutHeaderParts: CalloutHeaderParts; 10 | selectedLinesDiff: SelectedLinesDiff; 11 | originalCursorPositions: CursorPositions; 12 | beforeAndAfter: BeforeAndAfter; 13 | }; 14 | 15 | export type AutoSelectionModeTestFn = (testParams: TestParams) => void; 16 | 17 | function testWhenTextSelected({ 18 | whenTextSelected, 19 | testParams: { calloutHeaderParts, selectedLinesDiff, originalCursorPositions, beforeAndAfter }, 20 | getExpected, 21 | }: { 22 | whenTextSelected: AutoSelectionWhenTextSelectedMode; 23 | testParams: TestParams; 24 | getExpected: GetExpected; 25 | }): void { 26 | const result = getCursorOrSelectionActionAfterWrappingSelectedLines({ 27 | whenTextSelected, 28 | selectedLinesDiff, 29 | originalCursorPositions, 30 | calloutHeaderParts, 31 | }); 32 | const { after } = beforeAndAfter; 33 | const expectedResult = getExpected({ after, originalCursorPositions }); 34 | expect(result).toEqual(expectedResult); 35 | } 36 | 37 | const calloutHeaderParts1: CalloutHeaderParts = { 38 | baseCalloutHeader: "> [!quote]", 39 | foldableSuffix: "+", 40 | maybeTitle: "Quote", 41 | }; 42 | const selectedLinesDiff1: SelectedLinesDiff = { 43 | oldLines: [ 44 | "This is a quote by Aristotle:", 45 | "It is the mark of an educated mind to be able to entertain a thought without accepting it.", 46 | ], 47 | newLines: [ 48 | "> [!quote]+ Quote", 49 | "> This is a quote by Aristotle:", 50 | "> It is the mark of an educated mind to be able to entertain a thought without accepting it.", 51 | ], 52 | }; 53 | const beforeAndAfter1: BeforeAndAfter = { 54 | before: { 55 | start: { line: 2, ch: 0 }, // "T" in "This" 56 | end: { line: 3, ch: 90 }, // After "." in "it." 57 | from: { line: 2, ch: 19 }, // "A" in "Aristotle" 58 | to: { line: 3, ch: 11 }, // After "m" in "mark" 59 | }, 60 | after: { 61 | start: { line: 2, ch: 0 }, // ">" in "> [!quote]" 62 | end: { line: 4, ch: 92 }, // After "." in "it." 63 | from: { line: 3, ch: 21 }, // "A" in "Aristotle" 64 | to: { line: 4, ch: 13 }, // After "m" in "mark" 65 | titleStart: { line: 2, ch: 12 }, // "Q" in "Quote" 66 | titleEnd: { line: 2, ch: 17 }, // After "e" in "Quote 67 | }, 68 | }; 69 | const originalCursorPositions1 = { 70 | anchor: beforeAndAfter1.before.from, 71 | head: beforeAndAfter1.before.to, 72 | from: beforeAndAfter1.before.from, 73 | to: beforeAndAfter1.before.to, 74 | }; 75 | const testParams1: TestParams = { 76 | calloutHeaderParts: calloutHeaderParts1, 77 | selectedLinesDiff: selectedLinesDiff1, 78 | originalCursorPositions: originalCursorPositions1, 79 | beforeAndAfter: beforeAndAfter1, 80 | }; 81 | 82 | const calloutHeaderParts2: CalloutHeaderParts = { 83 | baseCalloutHeader: "> [!quote]", 84 | foldableSuffix: "+", 85 | maybeTitle: "Custom title", 86 | }; 87 | const selectedLinesDiff2: SelectedLinesDiff = { 88 | oldLines: [ 89 | "### Custom title", 90 | "This is a quote by Aristotle:", 91 | "It is the mark of an educated mind to be able to entertain a thought without accepting it.", 92 | ], 93 | newLines: [ 94 | "> [!quote]+ Custom title", 95 | "> This is a quote by Aristotle:", 96 | "> It is the mark of an educated mind to be able to entertain a thought without accepting it.", 97 | ], 98 | }; 99 | const beforeAndAfter2: BeforeAndAfter = { 100 | before: { 101 | start: { line: 2, ch: 0 }, // First "#" in heading 102 | end: { line: 4, ch: 90 }, // After "." in "it." 103 | from: { line: 2, ch: 4 }, // "C" in "Custom title" 104 | to: { line: 4, ch: 11 }, // After "m" in "mark" 105 | }, 106 | after: { 107 | start: { line: 2, ch: 0 }, // ">" in header 108 | end: { line: 4, ch: 92 }, // After "." in "it." 109 | from: { line: 2, ch: 12 }, // "C" in "Custom title" 110 | to: { line: 4, ch: 13 }, // After "m" in "mark" 111 | titleStart: { line: 2, ch: 12 }, // "C" in "Custom title" 112 | titleEnd: { line: 2, ch: 24 }, // After "e" in "title" 113 | }, 114 | }; 115 | const originalCursorPositions2 = { 116 | anchor: beforeAndAfter2.before.from, 117 | head: beforeAndAfter2.before.to, 118 | from: beforeAndAfter2.before.from, 119 | to: beforeAndAfter2.before.to, 120 | }; 121 | const testParams2: TestParams = { 122 | calloutHeaderParts: calloutHeaderParts2, 123 | selectedLinesDiff: selectedLinesDiff2, 124 | originalCursorPositions: originalCursorPositions2, 125 | beforeAndAfter: beforeAndAfter2, 126 | }; 127 | 128 | describe("whenTextSelected", () => { 129 | describe("selectHeaderToCursor", () => { 130 | const testHeaderToCursor = (testParams: TestParams, getExpected: GetExpected): void => 131 | testWhenTextSelected({ 132 | whenTextSelected: "selectHeaderToCursor", 133 | testParams, 134 | getExpected, 135 | }); 136 | it("header line added", () => { 137 | testHeaderToCursor(testParams1, ({ after, originalCursorPositions }) => ({ 138 | type: "setSelectionInCorrectDirection", 139 | newRange: { from: after.start, to: after.to }, 140 | originalCursorPositions, 141 | })); 142 | }); 143 | test("with custom title", () => { 144 | testHeaderToCursor(testParams2, ({ after, originalCursorPositions }) => ({ 145 | type: "setSelectionInCorrectDirection", 146 | newRange: { from: after.from, to: after.to }, 147 | originalCursorPositions, 148 | })); 149 | }); 150 | }); 151 | 152 | describe("selectFull", () => { 153 | const testSelectFull: AutoSelectionModeTestFn = (testParams) => 154 | testWhenTextSelected({ 155 | whenTextSelected: "selectFull", 156 | testParams, 157 | getExpected: ({ after, originalCursorPositions }) => ({ 158 | type: "setSelectionInCorrectDirection", 159 | newRange: { from: after.start, to: after.end }, 160 | originalCursorPositions, 161 | }), 162 | }); 163 | it("should select the full callout", () => { 164 | testSelectFull(testParams1); 165 | }); 166 | test("with custom title", () => { 167 | testSelectFull(testParams2); 168 | }); 169 | }); 170 | 171 | describe("selectTitle", () => { 172 | const testSelectTitle: AutoSelectionModeTestFn = (testParams) => 173 | testWhenTextSelected({ 174 | whenTextSelected: "selectTitle", 175 | testParams, 176 | getExpected: ({ after }) => ({ 177 | type: "setSelection", 178 | newRange: { from: after.titleStart, to: after.titleEnd }, 179 | }), 180 | }); 181 | it("should select the title", () => { 182 | testSelectTitle(testParams1); 183 | }); 184 | test("with custom title", () => { 185 | testSelectTitle(testParams2); 186 | }); 187 | }); 188 | 189 | describe("originalSelection", () => { 190 | const testOriginalSelection: AutoSelectionModeTestFn = (testParams) => 191 | testWhenTextSelected({ 192 | whenTextSelected: "originalSelection", 193 | testParams, 194 | getExpected: ({ after, originalCursorPositions }) => ({ 195 | type: "setSelectionInCorrectDirection", 196 | newRange: { from: after.from, to: after.to }, 197 | originalCursorPositions, 198 | }), 199 | }); 200 | it("should select the original selection", () => { 201 | testOriginalSelection(testParams1); 202 | }); 203 | test("with custom title", () => { 204 | testOriginalSelection(testParams2); 205 | }); 206 | }); 207 | 208 | describe("clearSelectionCursorTo", () => { 209 | const testClearSelectionCursorTo: AutoSelectionModeTestFn = (testParams) => 210 | testWhenTextSelected({ 211 | whenTextSelected: "clearSelectionCursorTo", 212 | testParams, 213 | getExpected: ({ after }) => ({ 214 | type: "clearSelection", 215 | newCursor: { line: after.to.line, ch: after.to.ch - 1 }, 216 | }), 217 | }); 218 | it("should clear the selection and move the cursor to the end of the callout", () => { 219 | testClearSelectionCursorTo(testParams1); 220 | }); 221 | test("with custom title", () => { 222 | testClearSelectionCursorTo(testParams2); 223 | }); 224 | }); 225 | 226 | describe("clearSelectionCursorStart", () => { 227 | const testClearSelectionCursorStart: AutoSelectionModeTestFn = (testParams) => 228 | testWhenTextSelected({ 229 | whenTextSelected: "clearSelectionCursorStart", 230 | testParams, 231 | getExpected: ({ after }) => ({ 232 | type: "clearSelection", 233 | newCursor: after.start, 234 | }), 235 | }); 236 | it("should select the original selection", () => { 237 | testClearSelectionCursorStart(testParams1); 238 | }); 239 | test("with custom title", () => { 240 | testClearSelectionCursorStart(testParams2); 241 | }); 242 | }); 243 | 244 | describe("clearSelectionCursorEnd", () => { 245 | const testClearSelectionCursorEnd: AutoSelectionModeTestFn = (testParams) => 246 | testWhenTextSelected({ 247 | whenTextSelected: "clearSelectionCursorEnd", 248 | testParams, 249 | getExpected: ({ after }) => ({ 250 | type: "clearSelection", 251 | newCursor: after.end, 252 | }), 253 | }); 254 | it("should clear the selection and move the cursor to the end of the callout", () => { 255 | testClearSelectionCursorEnd(testParams1); 256 | }); 257 | test("with custom title", () => { 258 | testClearSelectionCursorEnd(testParams2); 259 | }); 260 | }); 261 | }); 262 | -------------------------------------------------------------------------------- /src/utils/arrayUtils.ts: -------------------------------------------------------------------------------- 1 | export type NonEmptyArray = [T, ...T[]]; 2 | export type NonEmptyStringArray = NonEmptyArray; 3 | 4 | type LastElement = A extends NonEmptyArray 5 | ? T 6 | : A extends (infer T)[] 7 | ? T | undefined 8 | : never; 9 | 10 | /** 11 | * Returns the last element of the array. Typed so that if we know we're passing a non-empty array, 12 | * then we know the return value is not undefined. 13 | */ 14 | export function getLastElement(arr: A): LastElement { 15 | const lastElement = arr[arr.length - 1]; 16 | return lastElement as LastElement; 17 | } 18 | 19 | export function isNonEmptyArray(arr: readonly T[]): arr is NonEmptyArray { 20 | return arr.length > 0; 21 | } 22 | 23 | export function filterOutElements(arr: readonly T[], elementsToFilterOut: Set): T[] { 24 | return arr.filter((element) => !elementsToFilterOut.has(element)); 25 | } 26 | -------------------------------------------------------------------------------- /src/utils/calloutTitleUtils.ts: -------------------------------------------------------------------------------- 1 | import { type EditorRange } from "obsidian"; 2 | import { type PluginSettingsManager } from "../pluginSettingsManager"; 3 | import { throwNever } from "./errorUtils"; 4 | import { getTrimmedFirstCapturingGroupIfExists } from "./regexUtils"; 5 | import { toSentenceCase } from "./stringUtils"; 6 | 7 | export const CALLOUT_HEADER_WITH_ID_CAPTURE_REGEX = /^> \[!(.+)\]/; 8 | const CALLOUT_TITLE_REGEX = /^> \[!.+\][+-]? (.+)/; 9 | const HEADING_TITLE_REGEX = /^#+ (.+)/; 10 | 11 | export type CalloutHeaderParts = { 12 | /** The base part of the header, e.g. `> [!quote]` */ 13 | baseCalloutHeader: string; 14 | /** The foldable suffix: `+`, `-`, or "" */ 15 | foldableSuffix: string; 16 | /** The title part of the header, e.g. `Quote` */ 17 | maybeTitle: string | null; 18 | }; 19 | 20 | export function makeCalloutHeader({ 21 | calloutID, 22 | maybeTitleFromHeading, 23 | pluginSettingsManager, 24 | }: { 25 | calloutID: string; 26 | /** The title parsed from the first selected line if it was a heading, else null */ 27 | maybeTitleFromHeading: string | null; 28 | pluginSettingsManager: PluginSettingsManager; 29 | }): string { 30 | const calloutHeaderParts = getNewCalloutHeaderParts({ 31 | calloutID, 32 | maybeTitleFromHeading, 33 | pluginSettingsManager, 34 | }); 35 | return constructCalloutHeaderFromParts(calloutHeaderParts); 36 | } 37 | 38 | /** 39 | * Returns the parts of the header of a new callout, including the base callout header, foldable 40 | * suffix, and title, based on the user's settings. Uses the given title parsed from the first 41 | * selected line if that line was a non-empty heading; otherwise, if the user's settings call for an 42 | * explicit title, uses the default title for the callout. 43 | */ 44 | export function getNewCalloutHeaderParts({ 45 | calloutID, 46 | maybeTitleFromHeading, 47 | pluginSettingsManager, 48 | }: { 49 | calloutID: string; 50 | /** The title parsed from the first selected line if it was a heading, else null */ 51 | maybeTitleFromHeading: string | null; 52 | pluginSettingsManager: PluginSettingsManager; 53 | }): CalloutHeaderParts { 54 | const baseCalloutHeader = makeBaseCalloutHeader(calloutID, pluginSettingsManager); 55 | const foldableSuffix = makeFoldableSuffix(pluginSettingsManager); 56 | const maybeTitle = 57 | maybeTitleFromHeading ?? maybeMakeExplicitTitle(calloutID, pluginSettingsManager); 58 | return { baseCalloutHeader, foldableSuffix, maybeTitle }; 59 | } 60 | 61 | export function constructCalloutHeaderFromParts({ 62 | baseCalloutHeader, 63 | foldableSuffix, 64 | maybeTitle, 65 | }: CalloutHeaderParts): string { 66 | const titleText = maybeTitle !== null ? ` ${maybeTitle}` : ""; 67 | return `${baseCalloutHeader}${foldableSuffix}${titleText}`; 68 | } 69 | 70 | function makeBaseCalloutHeader( 71 | calloutID: string, 72 | pluginSettingsManager: PluginSettingsManager 73 | ): string { 74 | const capitalizedCalloutID = makeCapitalizedCalloutID(calloutID, pluginSettingsManager); 75 | return `> [!${capitalizedCalloutID}]`; 76 | } 77 | 78 | function makeCapitalizedCalloutID( 79 | calloutID: string, 80 | pluginSettingsManager: PluginSettingsManager 81 | ): string { 82 | const calloutIDCapitalization = pluginSettingsManager.getSetting("calloutIDCapitalization"); 83 | switch (calloutIDCapitalization) { 84 | case "lower": 85 | return calloutID.toLowerCase(); 86 | case "upper": 87 | return calloutID.toUpperCase(); 88 | case "sentence": 89 | return toSentenceCase(calloutID); 90 | case "title": 91 | return calloutID 92 | .split("-") 93 | .map((word) => toSentenceCase(word)) 94 | .join("-"); 95 | default: 96 | throwNever(calloutIDCapitalization); 97 | } 98 | } 99 | 100 | function makeFoldableSuffix(pluginSettingsManager: PluginSettingsManager): string { 101 | const defaultFoldableState = pluginSettingsManager.getSetting("defaultFoldableState"); 102 | switch (defaultFoldableState) { 103 | case "unfoldable": 104 | return ""; 105 | case "foldable-expanded": 106 | return "+"; 107 | case "foldable-collapsed": 108 | return "-"; 109 | default: 110 | throwNever(defaultFoldableState); 111 | } 112 | } 113 | 114 | /** 115 | * Returns an explicit default title for the callout, if one should be used (depending on the user's 116 | * settings), else null. 117 | */ 118 | export function maybeMakeExplicitTitle( 119 | calloutID: string, 120 | pluginSettingsManager: PluginSettingsManager 121 | ): string | null { 122 | const shouldUseExplicitTitle = pluginSettingsManager.getSetting("shouldUseExplicitTitle"); 123 | if (!shouldUseExplicitTitle) { 124 | return null; 125 | } 126 | return getDefaultCalloutTitle(calloutID); 127 | } 128 | 129 | export function makeH6Line(title: string): string { 130 | return `###### ${title}`; 131 | } 132 | 133 | /** 134 | * Parses the callout ID and explicit title (if present) from the full text of a callout. 135 | * 136 | * @param fullCalloutText The full text of the callout (both the header and the body). 137 | */ 138 | export function getCalloutIDAndExplicitTitle(fullCalloutText: string): { 139 | calloutID: string; 140 | maybeExplicitTitle: string | undefined; 141 | } { 142 | const calloutID = getCalloutID(fullCalloutText); 143 | const maybeExplicitTitle = getTrimmedExplicitTitleIfExists(fullCalloutText); 144 | return { calloutID, maybeExplicitTitle }; 145 | } 146 | 147 | function getCalloutID(fullCalloutText: string): string { 148 | const maybeCalloutID = getTrimmedCalloutIDIfExists(fullCalloutText); 149 | if (maybeCalloutID === undefined) { 150 | throw new Error("Callout ID not found in callout text."); 151 | } 152 | return maybeCalloutID; 153 | } 154 | 155 | function getTrimmedCalloutIDIfExists(fullCalloutText: string): string | undefined { 156 | return getTrimmedFirstCapturingGroupIfExists( 157 | CALLOUT_HEADER_WITH_ID_CAPTURE_REGEX, 158 | fullCalloutText 159 | ); 160 | } 161 | 162 | /** 163 | * Gets the explicit title (trimmed of surrounding whitespace) of a callout, if one is present. 164 | * 165 | * @param fullCalloutText The full text of the callout (both the header and the body). 166 | */ 167 | function getTrimmedExplicitTitleIfExists(fullCalloutText: string): string | undefined { 168 | return getTrimmedFirstCapturingGroupIfExists(CALLOUT_TITLE_REGEX, fullCalloutText); 169 | } 170 | 171 | /** 172 | * Gets the heading title text (trimmed of surrounding whitespace) from the first line of selected 173 | * text to be wrapped in a callout, if such a heading text exists. If none is found or the trimmed 174 | * string is empty, returns null. 175 | * 176 | * @param firstSelectedLine The first line of the text to be wrapped in a callout. 177 | * @returns The trimmed heading text if it exists and is non-empty, otherwise null. 178 | */ 179 | export function getCustomHeadingTitleIfExists({ 180 | firstSelectedLine, 181 | }: { 182 | firstSelectedLine: string; 183 | }): string | null { 184 | const maybeTitleFromHeading = getTrimmedHeadingTitleIfExists(firstSelectedLine); 185 | if (maybeTitleFromHeading === "" || maybeTitleFromHeading === undefined) { 186 | return null; 187 | } 188 | return maybeTitleFromHeading; 189 | } 190 | 191 | function getTrimmedHeadingTitleIfExists(firstSelectedLine: string): string | undefined { 192 | return getTrimmedFirstCapturingGroupIfExists(HEADING_TITLE_REGEX, firstSelectedLine); 193 | } 194 | 195 | /** 196 | * Determines whether the given explicit title, if it even exists, is a custom title or the same as 197 | * the default title for the given callout. 198 | */ 199 | export function isCustomTitle({ calloutID, title }: { calloutID: string; title: string }): boolean { 200 | return title !== "" && title !== getDefaultCalloutTitle(calloutID); 201 | } 202 | 203 | function getDefaultCalloutTitle(calloutID: string): string { 204 | return toSentenceCase(calloutID).replace(/-/g, " "); 205 | } 206 | 207 | /** 208 | * Gets the title's editor range, given the parts of the callout header and the title's line number. 209 | */ 210 | export function getTitleRange({ 211 | calloutHeaderParts, 212 | line, 213 | }: { 214 | calloutHeaderParts: CalloutHeaderParts; 215 | line: number; 216 | }): EditorRange { 217 | const { baseCalloutHeader, foldableSuffix, maybeTitle } = calloutHeaderParts; 218 | if (maybeTitle === null) { 219 | const ch = baseCalloutHeader.length + foldableSuffix.length; 220 | return { from: { line, ch }, to: { line, ch } }; 221 | } 222 | const titleLength = maybeTitle.length; 223 | const titleStart = baseCalloutHeader.length + foldableSuffix.length + 1; 224 | const titleEnd = titleStart + titleLength; 225 | return { from: { line, ch: titleStart }, to: { line, ch: titleEnd } }; 226 | } 227 | -------------------------------------------------------------------------------- /src/utils/editorCheckCallbackUtils.ts: -------------------------------------------------------------------------------- 1 | import { type Command, type Editor } from "obsidian"; 2 | import { type PluginSettingsManager } from "../pluginSettingsManager"; 3 | import { CALLOUT_HEADER_WITH_ID_CAPTURE_REGEX } from "./calloutTitleUtils"; 4 | import { getSelectedLinesRangeAndText } from "./selectionUtils"; 5 | 6 | /** 7 | * See Obsidian docs for `editorCheckCallback` for more information: 8 | * https://docs.obsidian.md/Reference/TypeScript+API/Command/editorCheckCallback 9 | */ 10 | type EditorCheckCallback = Required["editorCheckCallback"]; 11 | 12 | type EditorActionParams = { editor: Editor; pluginSettingsManager: PluginSettingsManager }; 13 | type EditorAction = ({ editor, pluginSettingsManager }: EditorActionParams) => void; 14 | 15 | /** 16 | * Creates an editor check callback for a command that should only be available when the currently 17 | * selected lines begin with a callout. 18 | */ 19 | export function makeCalloutSelectionCheckCallback({ 20 | editorAction, 21 | pluginSettingsManager, 22 | }: { 23 | editorAction: EditorAction; 24 | pluginSettingsManager: PluginSettingsManager; 25 | }): EditorCheckCallback { 26 | return (checking, editor, _ctx) => { 27 | if (!editor.somethingSelected()) return false; // Only show the command if text is selected 28 | if (!isFirstSelectedLineCalloutHeader(editor)) return false; // Only show the command if the selected lines begin with a callout 29 | return showOrRunCommand({ checking, editorAction, editor, pluginSettingsManager }); 30 | }; 31 | } 32 | 33 | function isFirstSelectedLineCalloutHeader(editor: Editor): boolean { 34 | const { selectedLinesText } = getSelectedLinesRangeAndText(editor); 35 | return CALLOUT_HEADER_WITH_ID_CAPTURE_REGEX.test(selectedLinesText); 36 | } 37 | 38 | /** 39 | * Shows or runs the given editor action depending on whether `checking` is true. Helper function 40 | * for creating editor check callbacks. 41 | */ 42 | function showOrRunCommand({ 43 | checking, 44 | editorAction, 45 | editor, 46 | pluginSettingsManager, 47 | }: { 48 | checking: boolean; 49 | editorAction: ({ 50 | editor, 51 | pluginSettingsManager, 52 | }: { 53 | editor: Editor; 54 | pluginSettingsManager: PluginSettingsManager; 55 | }) => void; 56 | editor: Editor; 57 | pluginSettingsManager: PluginSettingsManager; 58 | }): boolean { 59 | if (checking) return true; 60 | editorAction({ editor, pluginSettingsManager }); 61 | return true; 62 | } 63 | -------------------------------------------------------------------------------- /src/utils/errorUtils.ts: -------------------------------------------------------------------------------- 1 | export function throwNever(value: never): never { 2 | throw new Error(`Unexpected value: ${value}`); // eslint-disable-line @typescript-eslint/restrict-template-expressions 3 | } 4 | -------------------------------------------------------------------------------- /src/utils/numberUtils.ts: -------------------------------------------------------------------------------- 1 | export function clamp({ value, min, max }: { value: number; min: number; max: number }): number { 2 | return Math.min(Math.max(value, min), max); 3 | } 4 | -------------------------------------------------------------------------------- /src/utils/regexUtils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Returns the first capturing group match of the regex if it exists, otherwise returns undefined. 3 | * @param regex The regex to use, with at least one capturing group 4 | * @param text The text to search 5 | * @returns The first capturing group match if it exists, otherwise undefined 6 | */ 7 | export function getFirstCapturingGroupIfExists(regex: RegExp, text: string): string | undefined { 8 | const match = regex.exec(text); 9 | return match?.[1]; 10 | } 11 | 12 | /** 13 | * Returns the first capturing group match (trimmed of surrounding whitespace) of the regex executed 14 | * on the text, if found. If the match is not found, returns undefined. 15 | * @param regex The regex to use, with at least one capturing group 16 | * @param text The text to search 17 | * @returns The first capturing group match (trimmed) if it exists, otherwise undefined 18 | */ 19 | export function getTrimmedFirstCapturingGroupIfExists( 20 | regex: RegExp, 21 | text: string 22 | ): string | undefined { 23 | const maybeRawMatch = getFirstCapturingGroupIfExists(regex, text); 24 | return maybeRawMatch?.trim(); 25 | } 26 | -------------------------------------------------------------------------------- /src/utils/selectionUtils.ts: -------------------------------------------------------------------------------- 1 | import { type Editor, type EditorPosition, type EditorRange } from "obsidian"; 2 | import { getLastElement, type NonEmptyStringArray } from "./arrayUtils"; 3 | import { throwNever } from "./errorUtils"; 4 | import { clamp } from "./numberUtils"; 5 | 6 | export type CursorPositions = { 7 | anchor: EditorPosition; 8 | head: EditorPosition; 9 | from: EditorPosition; 10 | to: EditorPosition; 11 | }; 12 | 13 | export type SelectedLinesDiff = { 14 | oldLines: NonEmptyStringArray; 15 | newLines: NonEmptyStringArray; 16 | }; 17 | 18 | export type LineDiff = { 19 | oldLine: string; 20 | newLine: string; 21 | }; 22 | 23 | export type SetCursorAction = { 24 | type: "setCursor"; 25 | newPosition: EditorPosition; 26 | }; 27 | 28 | export type SetSelectionAction = { 29 | type: "setSelection"; 30 | newRange: EditorRange; 31 | }; 32 | 33 | export type SetSelectionInCorrectDirectionAction = { 34 | type: "setSelectionInCorrectDirection"; 35 | newRange: EditorRange; 36 | originalCursorPositions: CursorPositions; 37 | }; 38 | 39 | export type ClearSelectionAction = { 40 | type: "clearSelection"; 41 | newCursor: EditorPosition; 42 | }; 43 | 44 | export type CursorOrSelectionAction = 45 | | SetCursorAction 46 | | SetSelectionAction 47 | | SetSelectionInCorrectDirectionAction 48 | | ClearSelectionAction; 49 | 50 | /** 51 | * Replaces the selected lines with the new lines, and adjusts the editor selection to maintain its 52 | * position relative to the original text. 53 | */ 54 | export function replaceLinesAndAdjustSelection({ 55 | editor, 56 | selectedLinesDiff, 57 | originalCursorPositions, 58 | selectedLinesRange, 59 | }: { 60 | editor: Editor; 61 | selectedLinesDiff: SelectedLinesDiff; 62 | originalCursorPositions: CursorPositions; 63 | selectedLinesRange: EditorRange; 64 | }): void { 65 | const newSelectionRange = getNewSelectionRangeAfterReplacingLines({ 66 | originalCursorPositions, 67 | selectedLinesDiff, 68 | }); 69 | const newText = selectedLinesDiff.newLines.join("\n"); 70 | editor.replaceRange(newText, selectedLinesRange.from, selectedLinesRange.to); 71 | setSelectionInCorrectDirection({ editor, originalCursorPositions, newRange: newSelectionRange }); 72 | } 73 | 74 | function getNewSelectionRangeAfterReplacingLines({ 75 | originalCursorPositions, 76 | selectedLinesDiff, 77 | }: { 78 | originalCursorPositions: CursorPositions; 79 | selectedLinesDiff: SelectedLinesDiff; 80 | }): EditorRange { 81 | const { from: oldFrom, to: oldTo } = originalCursorPositions; 82 | const newFrom = getNewFromPosition({ oldFrom, selectedLinesDiff }); 83 | const newTo = getNewToPosition({ oldTo, selectedLinesDiff }); 84 | return { from: newFrom, to: newTo }; 85 | } 86 | 87 | /** 88 | * Gets the new cursor `from` position after the selected lines have been altered, while keeping the 89 | * relative `from` position within the text the same. 90 | */ 91 | export function getNewFromPosition({ 92 | oldFrom, 93 | selectedLinesDiff, 94 | }: { 95 | oldFrom: EditorPosition; 96 | selectedLinesDiff: SelectedLinesDiff; 97 | }): EditorPosition { 98 | const { oldLines, newLines } = selectedLinesDiff; 99 | const didAddOrRemoveHeaderLine = oldLines.length !== newLines.length; 100 | if (didAddOrRemoveHeaderLine) { 101 | // Select from the start of the header line if we added a new header line. If we removed a 102 | // header line, we should still select from the start of the first line. 103 | return { line: oldFrom.line, ch: 0 }; 104 | } 105 | const lineDiff = { oldLine: oldLines[0], newLine: newLines[0] }; 106 | const newFromCh = getNewPositionWithinLine({ oldCh: oldFrom.ch, lineDiff }); 107 | return { line: oldFrom.line, ch: newFromCh }; 108 | } 109 | 110 | /** 111 | * Gets the new cursor `to` position after the selected lines have been altered, while keeping the 112 | * relative `to` position within the text the same. 113 | */ 114 | export function getNewToPosition({ 115 | oldTo, 116 | selectedLinesDiff, 117 | }: { 118 | oldTo: EditorPosition; 119 | selectedLinesDiff: SelectedLinesDiff; 120 | }): EditorPosition { 121 | const { oldLines, newLines } = selectedLinesDiff; 122 | const numLinesDiff = newLines.length - oldLines.length; // we may have added or removed a header line 123 | const newToLine = oldTo.line + numLinesDiff; 124 | const lastLineDiff = getLastLineDiff(selectedLinesDiff); 125 | const newToCh = getNewPositionWithinLine({ oldCh: oldTo.ch, lineDiff: lastLineDiff }); 126 | return { line: newToLine, ch: newToCh }; 127 | } 128 | 129 | /** 130 | * Gets the line diff for the last line of the selected lines. 131 | */ 132 | export function getLastLineDiff({ oldLines, newLines }: SelectedLinesDiff): LineDiff { 133 | return { oldLine: getLastElement(oldLines), newLine: getLastElement(newLines) }; 134 | } 135 | 136 | /** 137 | * Gets the new cursor `ch` position within a given line after it's been altered, while keeping the 138 | * cursor's relative position in the line the same. 139 | */ 140 | export function getNewPositionWithinLine({ 141 | oldCh, 142 | lineDiff, 143 | }: { 144 | oldCh: number; 145 | lineDiff: LineDiff; 146 | }): number { 147 | const { oldLine, newLine } = lineDiff; 148 | const lineLengthDiff = oldLine.length - newLine.length; 149 | const newCh = clamp({ value: oldCh - lineLengthDiff, min: 0, max: newLine.length }); 150 | return newCh; 151 | } 152 | 153 | export function setSelectionInCorrectDirection({ 154 | editor, 155 | originalCursorPositions, 156 | newRange, 157 | }: { 158 | editor: Editor; 159 | originalCursorPositions: CursorPositions; 160 | newRange: EditorRange; 161 | }): void { 162 | const { newAnchor, newHead } = getNewAnchorAndHead(originalCursorPositions, newRange); 163 | editor.setSelection(newAnchor, newHead); 164 | } 165 | 166 | function getNewAnchorAndHead( 167 | originalCursorPositions: CursorPositions, 168 | newRange: EditorRange 169 | ): { newAnchor: EditorPosition; newHead: EditorPosition } { 170 | const { from: newFrom, to: newTo } = newRange; 171 | return isHeadBeforeAnchor(originalCursorPositions) 172 | ? { newAnchor: newTo, newHead: newFrom } 173 | : { newAnchor: newFrom, newHead: newTo }; 174 | } 175 | 176 | function isHeadBeforeAnchor({ anchor, head }: Pick): boolean { 177 | return head.line < anchor.line || (head.line === anchor.line && head.ch < anchor.ch); 178 | } 179 | 180 | /** 181 | * Returns the range and text of the selected lines, from the start of the first 182 | * selected line to the end of the last selected line (regardless of where in 183 | * the line each selection boundary is). 184 | */ 185 | export function getSelectedLinesRangeAndText(editor: Editor): { 186 | selectedLinesRange: EditorRange; 187 | selectedLinesText: string; 188 | } { 189 | const { from, to } = getSelectedLinesRange(editor); 190 | const text = editor.getRange(from, to); 191 | return { selectedLinesRange: { from, to }, selectedLinesText: text }; 192 | } 193 | 194 | function getSelectedLinesRange(editor: Editor): EditorRange { 195 | const { from, to } = getSelectionRange(editor); 196 | const startOfFirstSelectedLine = { line: from.line, ch: 0 }; 197 | const endOfLastSelectedLine = { line: to.line, ch: editor.getLine(to.line).length }; 198 | return { from: startOfFirstSelectedLine, to: endOfLastSelectedLine }; 199 | } 200 | 201 | export function getCursorPositions(editor: Editor): CursorPositions { 202 | const { anchor, head } = getAnchorAndHead(editor); 203 | const { from, to } = getSelectionRange(editor); 204 | return { anchor, head, from, to }; 205 | } 206 | 207 | function getAnchorAndHead(editor: Editor): { anchor: EditorPosition; head: EditorPosition } { 208 | const anchor = editor.getCursor("anchor"); 209 | const head = editor.getCursor("head"); 210 | return { anchor, head }; 211 | } 212 | 213 | function getSelectionRange(editor: Editor): EditorRange { 214 | const from = editor.getCursor("from"); 215 | const to = editor.getCursor("to"); 216 | return { from, to }; 217 | } 218 | 219 | export function runCursorOrSelectionAction({ 220 | editor, 221 | action, 222 | }: { 223 | editor: Editor; 224 | action: CursorOrSelectionAction; 225 | }): void { 226 | switch (action.type) { 227 | case "setCursor": { 228 | editor.setCursor(action.newPosition); 229 | return; 230 | } 231 | case "setSelection": { 232 | editor.setSelection(action.newRange.from, action.newRange.to); 233 | return; 234 | } 235 | case "setSelectionInCorrectDirection": { 236 | const { newRange, originalCursorPositions } = action; 237 | setSelectionInCorrectDirection({ editor, originalCursorPositions, newRange }); 238 | return; 239 | } 240 | case "clearSelection": { 241 | clearSelectionAndSetCursor({ editor, newCursor: action.newCursor }); 242 | return; 243 | } 244 | default: 245 | throwNever(action); 246 | } 247 | } 248 | 249 | /** 250 | * Clears the selection and sets the cursor to the given position. 251 | */ 252 | export function clearSelectionAndSetCursor({ 253 | editor, 254 | newCursor, 255 | }: { 256 | editor: Editor; 257 | newCursor: EditorPosition; 258 | }): void { 259 | editor.setSelection(newCursor, newCursor); 260 | } 261 | 262 | export function getCalloutStartPos({ 263 | originalCursorPositions, 264 | }: { 265 | originalCursorPositions: CursorPositions; 266 | }): EditorPosition { 267 | const { from: oldFrom } = originalCursorPositions; 268 | return { line: oldFrom.line, ch: 0 }; 269 | } 270 | 271 | export function getClearSelectionCursorStartAction({ 272 | originalCursorPositions, 273 | }: { 274 | originalCursorPositions: CursorPositions; 275 | }): ClearSelectionAction { 276 | const startPos = { line: originalCursorPositions.from.line, ch: 0 }; 277 | return { type: "clearSelection", newCursor: startPos }; 278 | } 279 | -------------------------------------------------------------------------------- /src/utils/stringUtils.ts: -------------------------------------------------------------------------------- 1 | import { type NonEmptyStringArray } from "./arrayUtils"; 2 | 3 | /** 4 | * Better-typed version of `text.split("\n")` where we know the result will always have at least one 5 | * element, since `String.prototype.split` only returns an empty array when the input string and 6 | * separator are both empty strings, and in this case the separator is "\n" which is not empty. 7 | */ 8 | export function getTextLines(text: string): NonEmptyStringArray { 9 | return text.split("\n") as NonEmptyStringArray; 10 | } 11 | 12 | export function toTitleCase(text: string): string { 13 | const words = text.split(/\s|-/); 14 | const capitalizedWords = words.map((word) => toSentenceCase(word)); 15 | return capitalizedWords.join(" "); 16 | } 17 | 18 | export function toSentenceCase(text: string): string { 19 | const firstLetter = text.charAt(0).toUpperCase(); 20 | const rest = text.slice(1).toLowerCase(); 21 | return `${firstLetter}${rest}`; 22 | } 23 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "module": "ESNext", 5 | "moduleResolution": "Bundler", 6 | "strict": true, 7 | "strictNullChecks": true, 8 | "noUncheckedIndexedAccess": true, 9 | "exactOptionalPropertyTypes": true, 10 | "esModuleInterop": true, 11 | "skipLibCheck": true, 12 | "forceConsistentCasingInFileNames": true 13 | }, 14 | "include": ["src", "@types"] 15 | } 16 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "vitest/config"; 2 | 3 | export default defineConfig({ 4 | test: { 5 | globals: true, 6 | environment: "node", 7 | coverage: { 8 | provider: "istanbul", 9 | reporter: ["text", "lcov"], 10 | }, 11 | }, 12 | }); 13 | -------------------------------------------------------------------------------- /webpack.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | entry: "./src/main.ts", 3 | mode: "production", 4 | module: { 5 | rules: [ 6 | { 7 | test: /\.ts$/, 8 | use: "ts-loader", 9 | exclude: /node_modules/, 10 | }, 11 | ], 12 | }, 13 | resolve: { 14 | extensions: [".ts", ".js"], 15 | }, 16 | externals: { 17 | obsidian: "commonjs2 obsidian", 18 | }, 19 | output: { 20 | filename: "main.js", 21 | path: __dirname, 22 | libraryTarget: "commonjs", 23 | }, 24 | }; 25 | --------------------------------------------------------------------------------