├── .github ├── ISSUE_TEMPLATE │ ├── FR.yml │ └── bug.yml └── workflows │ ├── auto_assign.yml │ └── publish.yaml ├── .gitignore ├── .hotreload ├── CHANGELOG-LATEST.md ├── CHANGELOG-beta.md ├── CHANGELOG.md ├── LICENSE ├── README.md ├── biome.json ├── bun.lockb ├── commit-and-tag-version.mjs ├── esbuild.config.mjs ├── manifest-beta.json ├── manifest.json ├── package.json ├── pnpm-lock.yaml ├── src ├── @types │ └── i18next.d.ts ├── i18n │ ├── i18next.ts │ └── locales │ │ ├── en.json │ │ └── fr.json ├── interface.ts ├── main.ts ├── modal.ts ├── settings.ts ├── styles.css └── utils │ ├── conversion.ts │ ├── dataview.ts │ ├── node_edit.ts │ ├── pluginFix.ts │ └── selection.ts └── tsconfig.json /.github/ISSUE_TEMPLATE/FR.yml: -------------------------------------------------------------------------------- 1 | name: "Feature request" 2 | description: "Suggest an idea for this project" 3 | title: "[FR]: " 4 | labels: ["enhancement"] 5 | assignees: 6 | - Mara-Li 7 | body: 8 | - type: markdown 9 | attributes: 10 | value: | 11 | Thanks for taking the time to fill out this Feature request! 12 | Some limitation of the plugin: 13 | - The text selected in reading-view is a little different from the original selection, because `windows.getSelection()` doesn't give the exact same selection as the one in the editor. 14 | - The plugin can't copy "un-selectable" (for example text between in `$`) 15 | - In reading view, already "HTML writing" are not copied as HTML (like ``). They are copied as markdown, or only the text is copied (if not basic html). You can prevent this using the `data-type="html"` attribute on the element. For example, `b data-type="html"` will be copied as ``. 16 | - Selecting text with image will copy the name of the image. If you want to copy the image, you need to select the image itself (not the text). 17 | - type: checkboxes 18 | attributes: 19 | label: Issue validation 20 | description: "Thanks to check if your issue is relative to the repository. Any non relative or duplicate issue will be closed." 21 | options: 22 | - label: "I checked the issue to prevent duplicate" 23 | required: true 24 | - label: "I checked my configurations files and the documentation" 25 | required: true 26 | - type: textarea 27 | id: describe-request 28 | attributes: 29 | label: Is your feature related to a problem ? 30 | description: If you found a solution with the inherent limit I had with Obsidian, please, add it here! 31 | placeholder: "Tell me the original problem" 32 | - type: textarea 33 | id: describe-solution 34 | attributes: 35 | label: What solution do you want to see ? 36 | description: Describe your idea here! 37 | validations: 38 | required: true 39 | - type: textarea 40 | id: alternative 41 | attributes: 42 | label: Describe the alternative you've considered 43 | - type: textarea 44 | attributes: 45 | label: Anything else? 46 | description: | 47 | Links? References? Anything that will give us more context about the issue you are encountering! 48 | Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. 49 | validations: 50 | required: false 51 | - type: markdown 52 | attributes: 53 | value: | 54 | ## Environment 55 | Please fill out the following information about your environment. If you are unsure about any of them, just leave it blank. 56 | - type: dropdown 57 | id: version 58 | attributes: 59 | label: OS 60 | description: Check your OS 61 | multiple: true 62 | options: 63 | - IOS 64 | - Android 65 | - MacOS 66 | - Windows 67 | - Linux 68 | - type: textarea 69 | attributes: 70 | label: Obsidian information 71 | description: | 72 | Please copy and paste the information about your Obsidian version using the command "show debug info" in the obsidian's commands palette. 73 | render: bash session 74 | validations: 75 | required: true 76 | - type: input 77 | id: plugin-version 78 | attributes: 79 | label: Plugin version 80 | description: Please copy and paste the version of the plugin you are using. 81 | placeholder: "1.0.0" 82 | validations: 83 | required: true 84 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug.yml: -------------------------------------------------------------------------------- 1 | name: "Bug report" 2 | description: Fill a bug report 3 | title: "[Bug]: " 4 | labels: ["bug"] 5 | assignees: 6 | - Mara-Li 7 | body: 8 | - type: markdown 9 | attributes: 10 | value: | 11 | Thanks for taking the time to fill out this bug report. 12 | Some limitation of the plugin: 13 | - The text selected in reading-view is a little different from the original selection, because `windows.getSelection()` doesn't give the exact same selection as the one in the editor. 14 | - The plugin can't copy "un-selectable" (for example text between in `$`) 15 | - In reading view, already "HTML writing" are not copied as HTML (like ``). They are copied as markdown, or only the text is copied (if not basic html). You can prevent this using the `data-type="html"` attribute on the element. For example, `b data-type="html"` will be copied as ``. 16 | - Selecting text with image will copy the name of the image. If you want to copy the image, you need to select the image itself (not the text). 17 | - type: checkboxes 18 | attributes: 19 | label: Issue validation 20 | description: "Thanks to check if your issue is relative to the repository. Any non relative or duplicate issue will be closed." 21 | options: 22 | - label: "I checked the issue to prevent duplicate" 23 | required: true 24 | - label: "I checked my configurations files and the documentation" 25 | required: true 26 | - type: textarea 27 | id: describe-bug 28 | attributes: 29 | label: Describe the bug 30 | description: A clear and concise description of what the bug is. 31 | placeholder: "Tell us what you see! And don't forget the error" 32 | validations: 33 | required: true 34 | - type: textarea 35 | id: repro-bug 36 | attributes: 37 | label: How to reproduce ? 38 | description: Step to reproduce the behavior 39 | placeholder: | 40 | 1. Go to '...' 41 | 2. Click on '....' 42 | 3. Scroll down to '....' 43 | 4. See error 44 | validations: 45 | required: false 46 | - type: textarea 47 | id: minimal-repro 48 | attributes: 49 | label: Minimal Reproducible Example 50 | description: Please provide a minimal reproducible example. 51 | validations: 52 | required: true 53 | - type: textarea 54 | attributes: 55 | label: Configuration 56 | description: | 57 | Open the configuration settings with any text editor. The settings are located in `.obsidian/plugins/copy-reading-in-markdown` 58 | render: JSON 59 | validations: 60 | required: true 61 | - type: textarea 62 | id: logs 63 | attributes: 64 | label: Relevant log output 65 | description: | 66 | Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks. You can open the Obsidian's console with "CTRL+MAJ+I." 67 | render: bash session 68 | - type: textarea 69 | attributes: 70 | label: Anything else? 71 | description: | 72 | Links? References? Anything that will give us more context about the issue you are encountering! 73 | Tip: You can attach images or log files by clicking this area to highlight it and then dragging files in. 74 | validations: 75 | required: false 76 | - type: markdown 77 | attributes: 78 | value: | 79 | ## Environment 80 | Please fill out the following information about your environment. If you are unsure about any of them, just leave it blank. 81 | - type: dropdown 82 | id: version 83 | attributes: 84 | label: OS 85 | description: Check your OS 86 | multiple: true 87 | options: 88 | - IOS 89 | - Android 90 | - MacOS 91 | - Windows 92 | - Linux 93 | - type: textarea 94 | attributes: 95 | label: Obsidian information 96 | description: | 97 | Please copy and paste the information about your Obsidian version using the command "show debug info" in the obsidian's commands palette. 98 | render: bash session 99 | validations: 100 | required: true 101 | - type: input 102 | id: plugin-version 103 | attributes: 104 | label: Plugin version 105 | description: Please copy and paste the version of the plugin you are using. 106 | placeholder: "1.0.0" 107 | validations: 108 | required: true 109 | -------------------------------------------------------------------------------- /.github/workflows/auto_assign.yml: -------------------------------------------------------------------------------- 1 | name: Auto Assign 2 | on: 3 | issues: 4 | types: [opened, edited, labeled, unlabeled] 5 | pull_request: 6 | types: [opened, edited, labeled, unlabeled] 7 | jobs: 8 | auto-assign: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: wow-actions/auto-assign@v3 12 | with: 13 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 14 | reviewers: | 15 | mara-li 16 | assignees: mara-li 17 | skipKeywords: wip, draft 18 | -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: Release obsidian plugin 2 | on: 3 | workflow_dispatch: 4 | inputs: 5 | bump: 6 | default: false 7 | description: "Bump version based on semantic release" 8 | type: boolean 9 | required: false 10 | beta: 11 | default: false 12 | description: "Make a beta release" 13 | type: boolean 14 | required: false 15 | push: 16 | tags: 17 | - "*" 18 | permissions: 19 | contents: write 20 | jobs: 21 | release: 22 | if: (github.event_name == 'push') || (github.event_name == 'workflow_dispatch' && !inputs.bump) 23 | uses: mara-li/reusable-workflows/.github/workflows/obsidian-plugin-release.yaml@main 24 | with: 25 | PLUGIN_NAME: "enhanced-copy" 26 | CACHE: bun 27 | secrets: 28 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 29 | bump-version: 30 | if: ${{ inputs.bump }} 31 | uses: mara-li/reusable-workflows/.github/workflows/obsidian-plugin-bump-version.yaml@main 32 | with: 33 | PLUGIN_NAME: "enhanced-copy" 34 | BETA: ${{ inputs.beta }} 35 | CACHE: bun 36 | secrets: 37 | GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} 38 | 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .env 3 | *-error.log 4 | package-lock.json 5 | yarn.lock 6 | .npmrc 7 | .env.json 8 | dist/** 9 | main.js 10 | .idea 11 | .vscode 12 | data.json 13 | style.css 14 | styles.css 15 | -------------------------------------------------------------------------------- /.hotreload: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mara-Li/obsidian-enhanced-copy/d88744399a6678766327e3eb2ee6bc198610881d/.hotreload -------------------------------------------------------------------------------- /CHANGELOG-LATEST.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mara-Li/obsidian-enhanced-copy/d88744399a6678766327e3eb2ee6bc198610881d/CHANGELOG-LATEST.md -------------------------------------------------------------------------------- /CHANGELOG-beta.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines. 4 | 5 | ## [0.2.13-2](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.13-1...0.2.13-2) (2024-08-07) 6 | 7 | 8 | ### Bug Fixes 9 | 10 | * **metabind:** another fix for metabind cursed html ([d683e18](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/d683e18ac3e6b9d452a665baebbc0bfd1a1f82f7)) 11 | 12 | ## [0.2.13-1](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.13-0...0.2.13-1) (2024-08-07) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * crash onunload with activemonkey ([f4361c9](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f4361c95e2683f84a5e6271811d999ff101fa41e)) 18 | * in some case, the language of moment can be changed, breaking the translation ([b33fc94](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/b33fc942aa06f743354733f41d6923e4ed88596d)) 19 | * **metabind:** fix code format ([dc4c018](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/dc4c01819f467d373c1e2824a0fdd7246759e9ff)) 20 | 21 | ## [0.2.13-0](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.12...0.2.13-0) (2024-08-03) 22 | 23 | 24 | ### Features 25 | 26 | * reorder autorules, and not equal rules ([837c38c](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/837c38cfa7e10d82f5de9add17c884c6d3945a0b)) 27 | 28 | ## [0.2.12-4](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.12-3...0.2.12-4) (2024-07-30) 29 | 30 | 31 | ### Features 32 | 33 | * better option for DJS convertion (allow to choose which one to export, like inlineDQL, inlineDJS...) ([e3b4ab5](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/e3b4ab5aa6cca09382a727a0f4edd57ee2260e6f)) 34 | 35 | ## [0.2.12-3](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.12-2...0.2.12-3) (2024-07-28) 36 | 37 | 38 | ### Bug Fixes 39 | 40 | * dataviewjs in codeblock ([3afa1e5](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/3afa1e589effcd97cd56ce5a89ca8acad43f7b35)) 41 | 42 | ## [0.2.12-2](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.12-1...0.2.12-2) (2024-07-23) 43 | 44 | 45 | ### Features 46 | 47 | * in edit mode, convert dataview into markdown :tada: ([b97bb9e](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/b97bb9ed2c460737e0c2b8c93ce61892a84f920e)) 48 | 49 | ## [0.2.12-1](https://github.com/Mara-Li/obsidian-enhanced-copy/compare/0.2.12-0...0.2.12-1) (2024-07-16) 50 | 51 | 52 | ### Bug Fixes 53 | 54 | * better style in regex modal ([ce20e5f](https://github.com/Mara-Li/obsidian-enhanced-copy/commit/ce20e5f8a045bdce8902e232a4729842a2fbf48a)) 55 | 56 | ## [0.2.12-0](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.11...0.2.12-0) (2024-07-16) 57 | 58 | 59 | ### Bug Fixes 60 | 61 | * metabind input view ([8a9b645](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/8a9b6457abc7bbea76179fcbf5bd73f1dc5a5253)) 62 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [commit-and-tag-version](https://github.com/absolute-version/commit-and-tag-version) for commit guidelines. 4 | 5 | ## [0.2.14](https://github.com/Mara-Li/obsidian-enhanced-copy/compare/0.2.13...0.2.14) (2025-02-21) 6 | 7 | 8 | ### Bug Fixes 9 | 10 | * **textReplacement:** replace string should be "replaceAll" instead of first replace ([7dcd3ce](https://github.com/Mara-Li/obsidian-enhanced-copy/commit/7dcd3cee0e8157bfcd0c728bfd2206931a57c7be)), closes [#4](https://github.com/Mara-Li/obsidian-enhanced-copy/issues/4) 11 | 12 | ## [0.2.13](https://github.com/Mara-Li/obsidian-enhanced-copy/compare/0.2.13-2...0.2.13) (2024-10-31) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * **build:** [@obsidian](https://github.com/obsidian)_publisher was renamed to [@enveloppe](https://github.com/enveloppe) ([f0abfc8](https://github.com/Mara-Li/obsidian-enhanced-copy/commit/f0abfc8baa4b214abb15df7f21a330c3ab93c7e9)) 18 | * **regex:** regex-replace should follow the same order in edit than reading ([b9eb20d](https://github.com/Mara-Li/obsidian-enhanced-copy/commit/b9eb20d69380f6cead764b0eb974b1acf7fd620a)) 19 | * **settings:** duplicate regex when using on "all" (edit+read) ([a3542c7](https://github.com/Mara-Li/obsidian-enhanced-copy/commit/a3542c7a234be55850d916c075d486c2f82e55cf)) 20 | 21 | ## [0.2.12](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.12-4...0.2.12) (2024-07-30) 22 | 23 | ## [0.2.11](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.10...0.2.11) (2024-07-02) 24 | 25 | ## [0.2.10](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.9...0.2.10) (2024-06-08) 26 | 27 | 28 | ### Features 29 | 30 | * add a command to use the native copy of Obsidian ([58980c4](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/58980c4a3eaad94b7c7fca3c7d3252e588864c4d)) 31 | 32 | ## [0.2.9](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.8...0.2.9) (2024-06-07) 33 | 34 | 35 | ### Features 36 | 37 | * support autoapply profile ([f3e09e5](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f3e09e599dfc4a135241e0a06842f7f744b50ebe)) 38 | 39 | 40 | ### Bug Fixes 41 | 42 | * autoSave in regex modals ([95e5e48](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/95e5e48a07df2f50a150f447361c494e987d4863)) 43 | * selection of inline-title and view-header when using editor ([93c0407](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/93c04074a9d15eabc439377e484dbed26618f5cc)) 44 | 45 | ## [0.2.8](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.7...0.2.8) (2024-05-28) 46 | 47 | ## [0.2.7](https://github.com/Lisandra-dev/obsidian-enhanced-copy/compare/0.2.6...0.2.7) (2024-03-07) 48 | 49 | ## [0.2.6](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.5...0.2.6) (2024-02-07) 50 | 51 | 52 | ### Features 53 | 54 | * add profile settings ([e9e3def](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/e9e3defe12192a2d71429a4116d2df46d7a56620)) 55 | * allow to copy profile ([37e330a](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/37e330ab94ef49a8ecb18d3445ee7c31dab88c2a)) 56 | * allow to separate commands even if applying is not set to all ([528a0de](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/528a0de2975f9add5e787a987c805482dbc3902b)) 57 | * profile for commands ([63a77bc](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/63a77bc7fbe6f7e704067fe9826121304aecb03f)) 58 | 59 | ## [0.2.5](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.4...0.2.5) (2024-01-19) 60 | 61 | 62 | ### Bug Fixes 63 | 64 | * cut doesn't work in canvas ([efd6651](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/efd66514b981c73ef4d62805505e97b6b94e26f3)) 65 | 66 | ## [0.2.4](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.3...0.2.4) (2024-01-11) 67 | 68 | 69 | ### Bug Fixes 70 | 71 | * collapse icon broke title & list when converting to markdown ([9d88501](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/9d88501e9c76ecebe1ea6111a919119bc00319e1)) 72 | 73 | ## [0.2.3](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.2...0.2.3) (2023-12-10) 74 | 75 | 76 | ### Bug Fixes 77 | 78 | * disable the enhanced copy on any modal open (settings) ([80389cf](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/80389cf781e3bb013f15fa69dc3ac454c0dfbbfc)) 79 | 80 | ## [0.2.2](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.1...0.2.2) (2023-12-04) 81 | 82 | ## [0.2.1](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.2.0...0.2.1) (2023-10-29) 83 | 84 | 85 | ### Features 86 | 87 | * allow copy for canvas (natif) ([b7f340e](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/b7f340e6df484b3416de05ea76327e45ad5bd4f9)) 88 | 89 | ## [0.2.0](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.1.4...0.2.0) (2023-10-27) 90 | 91 | 92 | ### ⚠ BREAKING CHANGES 93 | 94 | * change the id of the plugin 95 | 96 | * change the id of the plugin ([8361509](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/836150964520761e7bebf52f027c96d1f834e6ac)) 97 | 98 | 99 | ### Features 100 | 101 | * allow to override the default copy function, so natif "copy" copy (using the menu) ([42052b9](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/42052b93762cea69ca2cb3e79ba3c2b30c0e8cce)) 102 | 103 | ## [0.1.4](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.1.3...0.1.4) (2023-10-04) 104 | 105 | 106 | ### Bug Fixes 107 | 108 | * **callout:** callout collision between type & title ([7b4024c](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/7b4024c7e5c3d1a418415cd552598978078d3e05)) 109 | * **callout:** callout return $3 instead of the first line ([f016910](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f0169102dd404485a30220e0df1a4070d288dbae)) 110 | * **callout:** return $3 instead of the real p3 ([f745023](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f745023b1ba88c5513658e2621598bad9afba2bd)) 111 | * **settings:** fix reloading of the reading settings tabs ([4172fef](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/4172fefe5c118142e247253b5ae14b942e0f85e4)) 112 | 113 | ## [0.1.3](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.1.2...0.1.3) (2023-09-08) 114 | 115 | 116 | ### Bug Fixes 117 | 118 | * **translation:** wrong translation for global ([4f9b370](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/4f9b370379575a2e616160bf4009d1c0ba9b7be6)) 119 | 120 | ## [0.1.2](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.1.1...0.1.2) (2023-08-09) 121 | 122 | 123 | ### Bug Fixes 124 | 125 | * **css:** prevent css applied outside the plugin ([f50bfde](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f50bfdedf8b942429aa1eadc562682464c49d52a)) 126 | 127 | ## [0.1.1](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.1.0...0.1.1) (2023-08-08) 128 | 129 | 130 | ### Features 131 | 132 | * **settings:** allow to copy settings between view ([9a625cf](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/9a625cfc1b9a0147ca5008f0d125127a9d3dc5ac)) 133 | 134 | ## [0.1.0](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.31...0.1.0) (2023-08-07) 135 | 136 | 137 | ### ⚠ BREAKING CHANGES 138 | 139 | * **manifest:** As the id was edited, you need to save your settings (if any) before upgrading. 140 | As the old plugin won't be deleted, you need to do it yourself. 141 | 142 | * **manifest:** rename ([8e1ff87](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/8e1ff8759c90a20877329114c597f50dd01477fd)) 143 | 144 | ## [0.0.31](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.30...0.0.31) (2023-08-06) 145 | 146 | 147 | ### Bug Fixes 148 | 149 | * **callout:** prevent duplicate ([f1590ce](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f1590ced22cda34f5bb97da077d0bd14d9e42149)) 150 | * **commands:** the separated commands appear same if disabled ([b7e8974](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/b7e8974e8427387de080522bdb595629ae9739c1)) 151 | * **footnote:** fix footnote contents ([bd2bd52](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/bd2bd5238ca5ed4057e35f6e024150dfa080c876)) 152 | 153 | ## [0.0.30](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.29...0.0.30) (2023-08-06) 154 | 155 | 156 | ### Features 157 | 158 | * **hotkey:** allow to separate hotkeys for each view type ([6bc11e2](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/6bc11e2449b24d8c2b48095b6cb2c9ae7f66e566)) 159 | * **reading:** allow to change space size in reading view ([1366113](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/13661135efcbbac5d453202ac0fc33dd52d2c6bb)) 160 | 161 | 162 | ### Bug Fixes 163 | 164 | * **callout:** fix callout malconvert/blockquote ignored ([73c8472](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/73c8472ee8a6e68c5eae682fdda433409029358c)) 165 | 166 | ## [0.0.29](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.28...0.0.29) (2023-08-05) 167 | 168 | 169 | ### Bug Fixes 170 | 171 | * following update of settings, fix callout and issue in reading mode ([e9a9690](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/e9a9690a300056cfb1d917044ba81103e683ec26)) 172 | * **logs:** fix process not exist on mobile ([0e32e9e](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/0e32e9e514907a74a225fadd6ea5ea96df2518e0)) 173 | * **readingMode: callout:** problem with callout indent ([0332ce8](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/0332ce88757505d59033287f2c71afba99a83e60)) 174 | 175 | ## [0.0.28](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.27...0.0.28) (2023-08-03) 176 | 177 | 178 | ### Features 179 | 180 | * **settings:** refactor all settings & separate editing & reading ([a14fb30](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/a14fb30727a58c24fb9d799cf887ed605d8956eb)) 181 | 182 | 183 | ### Bug Fixes 184 | 185 | * **callout:** fix some callout and forgot links ([d537ba9](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/d537ba9daf628945c4719d951c7aac6a113df538)) 186 | * **editView:** add condition for links ([14477b5](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/14477b56deaf1a6e7626165a4557b4a144f587c2)) 187 | * **links:** some info about links to markdown mandatory settings ([bf198aa](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/bf198aac0e4f83aa82ac959a3f761138b3b9f2df)) 188 | 189 | ## [0.0.27](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.26...0.0.27) (2023-06-15) 190 | 191 | ## [0.0.26](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.25...0.0.26) (2023-06-15) 192 | 193 | 194 | ### Bug Fixes 195 | 196 | * **conversion:** strict space regex ([34317a9](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/34317a910ee5c9277680935fc14edff1fdffbe72)) 197 | 198 | ## [0.0.25](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.24...0.0.25) (2023-06-15) 199 | 200 | ## [0.0.24](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.23...0.0.24) (2023-06-15) 201 | 202 | 203 | ### Bug Fixes 204 | 205 | * can't copy frontmatter (Make.MD) ([c7b290b](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/c7b290b90d9ff07e1d8fb3ebe5949b1259688893)) 206 | * extra space at the end of line ([cc7779b](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/cc7779bea30881471ff541593eadc1377ae0c322)) 207 | 208 | ## 0.0.23 (2023-06-14) 209 | 210 | ## [0.0.22](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.21...0.0.22) (2023-05-30) 211 | 212 | 213 | ### Bug Fixes 214 | 215 | * an empty line is added before list ([fb6c226](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/fb6c2260ddf9e2f33e91ce438afe08103881a3c7)) 216 | * you want to keep empty line in markdown ([1de1466](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/1de14666a923a992c3dc5f7c8ea3b580c8390eca)) 217 | 218 | ## 0.0.21 (2023-05-21) 219 | 220 | ## [0.0.20](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.19...0.0.20) (2023-05-21) 221 | 222 | 223 | ### Bug Fixes 224 | 225 | * remove ! when copying image links ([31446fc](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/31446fcdd84ff90a131cc0bafe83990acf07a4ff)) 226 | * use replaceAll for replacing all links ([f002d3d](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f002d3dc3c2ee2f884901cb3bf2d43be8bf1b200)) 227 | 228 | ## [0.0.19](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.18...0.0.19) (2023-05-14) 229 | 230 | 231 | ### Bug Fixes 232 | 233 | * whitespace in editor doesn't be copied ([d2700c7](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/d2700c73c1bd05254571db9a092ea2c21cf78984)) 234 | 235 | ## [0.0.18](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.17...0.0.18) (2023-05-14) 236 | 237 | 238 | ### Features 239 | 240 | * allow copy whitespace in editor ([44736c4](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/44736c41952c89725a8afb14825f8c9b029f61b2)) 241 | 242 | ## 0.0.17 (2023-05-12) 243 | 244 | ## 0.0.16 (2023-05-12) 245 | 246 | ## [0.0.15](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.14...0.0.15) (2023-05-10) 247 | 248 | ## [0.0.14](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.13...0.0.14) (2023-05-10) 249 | 250 | 251 | ### Bug Fixes 252 | 253 | * range backward/forward when anchor < head ([2d36eed](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/2d36eed8294b028608b14a1dd5f03edf3c9add43)) 254 | 255 | ## [0.0.13](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.12...0.0.13) (2023-05-10) 256 | 257 | 258 | ### Bug Fixes 259 | 260 | * part of a document in editor is empty ([2806acd](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/2806acdad68ae88c40b2261dc5135f5291c8b916)) 261 | 262 | ## [0.0.12](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.11...0.0.12) (2023-05-10) 263 | 264 | ## [0.0.11](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.10...0.0.11) (2023-05-10) 265 | 266 | 267 | ### Features 268 | 269 | * export as HTML (only in reading view) ([9352810](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/935281078c03dc1b9aa19d9bebda8fbe0f3b077a)) 270 | * hard line break export ([22fb20c](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/22fb20cc5be42248352bd953864f5def0e245e99)) 271 | * keep callout type ([bed5e41](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/bed5e417c61f6169a90aae059cd3679455d51274)) 272 | * prevent HTML to be converted as markdown (using a special class "no-convert") ([162a4bf](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/162a4bff17090f4561c41a33ce4fb5f514718291)) 273 | * set view for conversion/export ([7156b2d](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/7156b2dea9371bafa37600a483155a74324db490)) 274 | 275 | 276 | ### Bug Fixes 277 | 278 | * callout type doesn't keep on multiline selection outer ([621ce6d](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/621ce6d498e6420129ca08951f1f861cdf4c6790)) 279 | * database plugin copy add relationship number ([aa7dd06](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/aa7dd06ba8cd6a02a43b7667aba291bd29120a15)) 280 | * multiple line selection broken ([0f0dddd](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/0f0dddda8a9b722f8200171b24a8930289f67d02)) 281 | * selection doesn't work on mono line ([13e5c1e](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/13e5c1e9282693fdce16059f341bb4c97877878c)) 282 | 283 | ## [0.0.10](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.9...0.0.10) (2023-05-09) 284 | 285 | 286 | ### Bug Fixes 287 | 288 | * new pdf view broken copy ([071a55f](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/071a55fe4202007d2bfe3af1d38918ea7bde8610)) 289 | 290 | ## [0.0.9](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.8...0.0.9) (2023-05-09) 291 | 292 | ## [0.0.8](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.7...0.0.8) (2023-05-09) 293 | 294 | ## [0.0.7](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.6...0.0.7) (2023-05-09) 295 | 296 | 297 | ### Bug Fixes 298 | 299 | * export not found ([62ca940](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/62ca940306ea9eb9f6d556a3c30ce739e8f4e553)) 300 | 301 | ## [0.0.6](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.5...0.0.6) (2023-05-09) 302 | 303 | ## [0.0.5](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.4...0.0.5) (2023-05-09) 304 | 305 | 306 | ### Features 307 | 308 | * add options for links copying ([d4af6e3](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/d4af6e344f62e78a29ea9035df6835f6f387287a)) 309 | * remove links options & remove highlight mark ([837fe59](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/837fe59938c7712ed11fc1f4cb7b2240ffb3f659)) 310 | * **translation:** adjust french ([1436c76](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/1436c76c9970598880cd8cd252f4b6f17d7916b3)) 311 | 312 | 313 | ### Bug Fixes 314 | 315 | * remove↩︎from converted links ([d296de1](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/d296de1155ed22de3614849300195cffabac7455)) 316 | 317 | ## [0.0.4](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.3...0.0.4) (2023-05-09) 318 | 319 | 320 | ### Bug Fixes 321 | 322 | * callout as blockquote ([f25a6a5](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/f25a6a51e2ec7162dbeae63d3acb0f01cfc7d795)) 323 | 324 | ## [0.0.3](https://github.com/Lisandra-dev/copy-reading-in-markdown/compare/0.0.2...0.0.3) (2023-05-09) 325 | 326 | 327 | ### Bug Fixes 328 | 329 | * in editor, can't copy multipleSelection ([ce01126](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/ce011263abd34c28058e4284495fc8b137147298)) 330 | * only copy when selected text is not empty ([08d3d3b](https://github.com/Lisandra-dev/copy-reading-in-markdown/commit/08d3d3b88cb575b769c73017cdc4ae1aa9892b52)) 331 | 332 | ## 0.0.2 (2023-05-09) 333 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright © 2007 Free Software Foundation, Inc. 5 | 6 | Everyone is permitted to copy and distribute verbatim copies 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 software and other kinds of works. 11 | 12 | The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. 13 | 14 | When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. 15 | 16 | To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. 17 | 18 | For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. 19 | 20 | Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. 21 | 22 | For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. 23 | 24 | Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. 25 | 26 | Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. 27 | 28 | The precise terms and conditions for copying, distribution and modification follow. 29 | 30 | TERMS AND CONDITIONS 31 | 32 | 0. Definitions. 33 | 34 | “This License” refers to version 3 of the GNU General Public License. 35 | 36 | “Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. 37 | 38 | “The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. 39 | 40 | To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. 41 | 42 | A “covered work” means either the unmodified Program or a work based on the Program. 43 | 44 | To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. 45 | 46 | To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. 47 | 48 | An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 49 | 50 | 1. Source Code. 51 | The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. 52 | 53 | A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. 54 | 55 | The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. 56 | 57 | The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. 58 | 59 | The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. 60 | 61 | The Corresponding Source for a work in source code form is that same work. 62 | 63 | 2. Basic Permissions. 64 | All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. 65 | 66 | You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. 67 | 68 | Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 69 | 70 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 71 | No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. 72 | 73 | When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 74 | 75 | 4. Conveying Verbatim Copies. 76 | You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. 77 | 78 | You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 79 | 80 | 5. Conveying Modified Source Versions. 81 | You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: 82 | 83 | a) The work must carry prominent notices stating that you modified it, and giving a relevant date. 84 | 85 | b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. 86 | 87 | c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. 88 | 89 | d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. 90 | 91 | A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 92 | 93 | 6. Conveying Non-Source Forms. 94 | You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: 95 | 96 | a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. 97 | 98 | b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. 99 | 100 | c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. 101 | 102 | d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. 103 | 104 | e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. 105 | 106 | A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. 107 | 108 | A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. 109 | 110 | “Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. 111 | 112 | If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). 113 | 114 | The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. 115 | 116 | Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 117 | 118 | 7. Additional Terms. 119 | “Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. 120 | 121 | When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. 122 | 123 | Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: 124 | 125 | a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or 126 | 127 | b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or 128 | 129 | c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or 130 | 131 | d) Limiting the use for publicity purposes of names of licensors or authors of the material; or 132 | 133 | e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or 134 | 135 | f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. 136 | 137 | All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. 138 | 139 | If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. 140 | 141 | Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 142 | 143 | 8. Termination. 144 | You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). 145 | 146 | However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. 147 | 148 | Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. 149 | 150 | Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 151 | 152 | 9. Acceptance Not Required for Having Copies. 153 | You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 154 | 155 | 10. Automatic Licensing of Downstream Recipients. 156 | Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. 157 | 158 | An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. 159 | 160 | You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 161 | 162 | 11. Patents. 163 | A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. 164 | 165 | A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. 166 | 167 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. 168 | 169 | In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. 170 | 171 | If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. 172 | 173 | If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. 174 | 175 | A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. 176 | 177 | Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 178 | 179 | 12. No Surrender of Others' Freedom. 180 | If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 181 | 182 | 13. Use with the GNU Affero General Public License. 183 | Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 184 | 185 | 14. Revised Versions of this License. 186 | The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. 187 | 188 | Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. 189 | 190 | If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. 191 | 192 | Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 193 | 194 | 15. Disclaimer of Warranty. 195 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 196 | 197 | 16. Limitation of Liability. 198 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 199 | 200 | 17. Interpretation of Sections 15 and 16. 201 | If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 202 | 203 | END OF TERMS AND CONDITIONS 204 | 205 | How to Apply These Terms to Your New Programs 206 | 207 | If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. 208 | 209 | To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. 210 | 211 | 212 | Copyright (C) 213 | 214 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. 215 | 216 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 217 | 218 | You should have received a copy of the GNU General Public License along with this program. If not, see . 219 | 220 | Also add information on how to contact you by electronic and paper mail. 221 | 222 | If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: 223 | 224 | Copyright (C) 225 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 226 | This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. 227 | 228 | The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. 229 | 230 | You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . 231 | 232 | The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Copy Reading In Markdown 2 | 3 | Copy a selection in reading view while keeping the markdown formatting 4 | 5 | ## 🛠️ Usage 6 | 7 | - Select the text you want to copy 8 | - Open the command palette 9 | - Select `Copy selected text` 10 | 11 | > [!NOTE] 12 | > The goal is to replace the native copy function of Obsidian. You can set the command on CTRL + C (+C on MacOS) 13 | > Some selection doesn't work as in the native copy in Obsidian, but I didn't find a way to process the native copy function in the plugin. 14 | 15 | ## ⚙️ Settings 16 | 17 | You can adjust the way the content is copied in the settings. 18 | 19 | First, you need to set the view mode to use. You can choose between: 20 | 21 | - `reading`: Only the selected text in reading view will be edited 22 | - `editing` : Only the selected text in editing view will be edited 23 | - `all` : The selected text will be edited in both views 24 | 25 | You can also choose to add a command for each copy-mode. It will create a command for : 26 | 27 | - Reading view (with checkCallback) 28 | - Editing view 29 | - Non markdown view (canvas, database-plugin...) 30 | 31 | Finally, you can to choose to override the default copy (from menu and the CTRL/ + C). Pretty useful for mobile! 32 | 33 | > [!Note] 34 | > The default copy is disabled on canvas, so I advice you to use the command separator to set an hotkey/button for "other" view & use the default copy on markdown view (reading and LP/source mode). 35 | 36 | The reading view and editing view have ~ the same settings, but you need to set them separately. It will allow having different copy settings for each view. 37 | 38 | You can enable the overriding of native copy for each view, so it could be disabled for reading view and enabled for editing view (and vice versa). 39 | 40 | You can create "profile", that will add a command (after reloadig Obsidian), so you can create a profile for copying on Discord and use it some times. 41 | 42 | ### Common settings 43 | 44 | These settings are the same for both views. As they are separate for each view, if you want some edit in the two views, you need to set them twice. 45 | It is done on purpose to prevent surprise when you use the plugin on editing view but don't want some changes. 46 | 47 | > **Info** 48 | > The button in the first tab "copy" will allow you to copy the settings for one view to the other. 49 | 50 | - You can change the aspect of the links: 51 | - `Keep` : Don't change the link (so they will be in `[link](url)` format) 52 | - `Remove all` : Remove all the links, and keep only the alias (so `[link](url)` will be `link`) 53 | - `Remove only for internal links` : Remove only the internal links (so `[link](url)` will be `link` but `[link](https://example.com)` will be `[link](https://example.com)`) 54 | - Same, you can change the footnote settings: 55 | - `Keep` : Don't change the footnote (so they will be in the strange format of Obsidian turndown: `footnote[[1]](#fn-1-xxx)`) 56 | - `Remove all` : Remove all the footnotes, and keep only the alias (so `footnote[[1]](#fn-1-xxx)` will be `footnote`) 57 | - `Format as [^1]`: Convert `footnote[[1]](#fn-1-xxx)` to `footnote[^1]` 58 | These settings will also fix the "markdown contents," aka the footnote at the end of the documents. 59 | > **Info** 60 | > With the **format** option, if you copy multiple footnote, they will be `[^1]:` `[^2]:` etc..., not a numbered list! 61 | - Unconventional markdown: 62 | - Highlight: Remove `==` around the highlighted text 63 | - Fix callout: 64 | - `Obsidian format` : Keep the same format 65 | - `Type to strong` : Convert all in blockquote and transform the type to bold: `> [!info]` will become `> **Info**` (à la GitHub Callout) 66 | - `Simple blockquote` : Remove type, keep title and convert to blockquote. 67 | - Other: 68 | - Strict line breaks: Add two spaces at the end of each line 69 | - Regex replacement: You can add more replacement to the copy with the button that will open a modal. Note that the replacement will be done **after all other changes**. 70 | 71 | ### Not common settings 72 | 73 | #### Reading view 74 | 75 | - You can copy to HTML but it will disable all the other options. 76 | - Space number : By default, turndown will convert tabulation to 4 spaces. You can change this size here. 77 | 78 | #### Editing view 79 | 80 | - Convert wikilinks to Markdown links: Convert `[[link]]` to `[link](link)`. Needed to convert the links (as in reading view). 81 | - Convert tabulation to space and choose the size 82 | 83 | ## 📝 Limitations 84 | 85 | - For a strange reason, the first line of a blockquote / list / callout is not selected totally properly as HTML. If you want to format only a part of this, you need to select the line before (or after). You can use "invisible" characters, `$~~$` for example. 86 | - Not support Mathjax copying (as you can't select them in reading view). 87 | - In reading view, already "HTML writing" are not copied as HTML (like ``). They are copied as markdown, or only the text is copied (if not basic html). You can prevent this using the `data-type="html"` attribute on the element. For example, `b data-type="html"` will be copied as ``. 88 | - Selecting text with image will copy the name of the image. If you want to copy the image, you need to select the image itself (not the text). 89 | 90 | ## 📥 Installation 91 | 92 | - [x] From Obsidian's community plugins 93 | - [x] Using BRAT with `https://github.com/Mara-Li/obsidian-enhanced-copy` 94 | - [x] From the release page: 95 | - Download the latest release 96 | - Unzip `obsidian-enhanced-copy.zip` in `.obsidian/plugins/` path 97 | - In Obsidian settings, reload the plugin 98 | - Enable the plugin 99 | 100 | ## 🤖 Developing 101 | 102 | To make changes to this plugin, first ensure you have the dependencies installed. First, don't forget that you need Node. The package manager used in the project is `pnpm` so you need to install it globally. 103 | 104 | ``` 105 | npm i pnpm -g 106 | pnpm install 107 | ``` 108 | 109 | To start building the plugin with what mode enabled run the following command: 110 | 111 | ``` 112 | pnpm run dev 113 | ``` 114 | 115 | > **Note** 116 | > If you haven't already installed the hot-reload-plugin you'll be prompted to. You need to enable that plugin in your obsidian vault before hot-reloading will start. You might need to refresh your plugin list for it to show up. 117 | > To start a release build run the following command: 118 | 119 | ``` 120 | pnpm run build 121 | ``` 122 | 123 | > **Note** 124 | > You can use the `.env` file with adding the key `VAULT_DEV` to specify the path to your Obsidian (development) vault. This will allow you to test your plugin without specify each times the path to the vault. 125 | 126 | ### 📤 Export 127 | 128 | You can use the `npm run export` command to export your plugin to your Obsidian Main Vault. To do that, you need the `.env` file with the following content: 129 | 130 | ```dotenv 131 | VAULT=path/to/main/vault 132 | VAULT_DEV=path/to/dev/vault 133 | ``` 134 | 135 | ### 🎼 Languages 136 | 137 | - [x] English 138 | - [x] French 139 | 140 | To add a translation: 141 | 142 | - Fork the repository 143 | - Add the translation in the `src/i18n/locales` folder with the name of the language (ex: `fr.json`) 144 | - Copy the content of the [`en.json`](./src/i18n/locales/en.json) file in the new file 145 | - Translate the content 146 | - Create a pull request 147 | 148 | --- 149 | 150 | This plugin was generated by create-obsidian-plugin 151 | -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://biomejs.dev/schemas/1.7.3/schema.json", 3 | "organizeImports": { 4 | "enabled": true 5 | }, 6 | "linter": { 7 | "enabled": true, 8 | "rules": { 9 | "recommended": false, 10 | "complexity": { 11 | "noExtraBooleanCast": "error", 12 | "noMultipleSpacesInRegularExpressionLiterals": "error", 13 | "noUselessCatch": "error", 14 | "noWith": "error" 15 | }, 16 | "style": { 17 | "noVar": "error", 18 | "useFilenamingConvention": "error", 19 | "useImportType": "error", 20 | "useNamingConvention": { 21 | "level": "warn", 22 | "options": { 23 | "strictCase": false 24 | } 25 | }, 26 | "useTemplate": "warn", 27 | "useConst": "error" 28 | }, 29 | "correctness": { 30 | "noConstAssign": "error", 31 | "noConstantCondition": "error", 32 | "noEmptyCharacterClassInRegex": "error", 33 | "noEmptyPattern": "error", 34 | "noGlobalObjectCalls": "error", 35 | "noInnerDeclarations": "error", 36 | "noInvalidConstructorSuper": "error", 37 | "noNewSymbol": "error", 38 | "noNonoctalDecimalEscape": "error", 39 | "noPrecisionLoss": "error", 40 | "noSelfAssign": "error", 41 | "noSetterReturn": "error", 42 | "noSwitchDeclarations": "error", 43 | "noUnreachable": "error", 44 | "noUnreachableSuper": "error", 45 | "noUnsafeFinally": "error", 46 | "noUnsafeOptionalChaining": "error", 47 | "noUnusedLabels": "error", 48 | "noUnusedVariables": "warn", 49 | "noUnusedImports": "warn", 50 | "useIsNan": "error", 51 | "useValidForDirection": "error", 52 | "useYield": "error" 53 | }, 54 | "suspicious": { 55 | "noAssignInExpressions": "error", 56 | "noAsyncPromiseExecutor": "error", 57 | "noCatchAssign": "error", 58 | "noClassAssign": "error", 59 | "noCompareNegZero": "error", 60 | "noControlCharactersInRegex": "error", 61 | "noDebugger": "error", 62 | "noDuplicateCase": "error", 63 | "noDuplicateClassMembers": "error", 64 | "noDuplicateObjectKeys": "error", 65 | "noDuplicateParameters": "error", 66 | "noEmptyBlockStatements": "error", 67 | "noFallthroughSwitchClause": "error", 68 | "noFunctionAssign": "error", 69 | "noGlobalAssign": "error", 70 | "noImportAssign": "error", 71 | "noMisleadingCharacterClass": "error", 72 | "noPrototypeBuiltins": "error", 73 | "noRedeclare": "error", 74 | "noShadowRestrictedNames": "error", 75 | "noUnsafeNegation": "error", 76 | "useGetterReturn": "error", 77 | "useValidTypeof": "error" 78 | }, 79 | "nursery": { 80 | "noDuplicateJsonKeys": "error" 81 | } 82 | }, 83 | "ignore": [ 84 | "**/npm node_modules", 85 | "**/build", 86 | "**/dist", 87 | "**/src/i18n/locales" 88 | ] 89 | }, 90 | "overrides": [ 91 | { 92 | "ignore": [ 93 | "**/*.js" 94 | ], 95 | "include": [ 96 | "**/*.ts", 97 | "**/*.tsx" 98 | ] 99 | }, 100 | { 101 | "include": [ 102 | "**/*.js" 103 | ] 104 | }, 105 | { 106 | "include": [ 107 | "*.json" 108 | ] 109 | }, 110 | { 111 | "include": [ 112 | "src/settings/help.ts" 113 | ], 114 | "formatter": { 115 | "lineWidth": 320 116 | } 117 | } 118 | ], 119 | "formatter": { 120 | "enabled": true, 121 | "indentStyle": "tab", 122 | "indentWidth": 2, 123 | "lineWidth": 90 124 | }, 125 | "javascript": { 126 | "formatter": { 127 | "quoteStyle": "double", 128 | "semicolons": "always", 129 | "trailingComma": "es5" 130 | } 131 | }, 132 | "json": { 133 | "formatter": { 134 | "trailingCommas": "none" 135 | } 136 | } 137 | } -------------------------------------------------------------------------------- /bun.lockb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Mara-Li/obsidian-enhanced-copy/d88744399a6678766327e3eb2ee6bc198610881d/bun.lockb -------------------------------------------------------------------------------- /commit-and-tag-version.mjs: -------------------------------------------------------------------------------- 1 | import pkg from "ansi-colors"; 2 | import { Command, Option } from "commander"; 3 | import commitAndTagVersion from "commit-and-tag-version"; 4 | import dedent from "dedent"; 5 | 6 | const { red, dim, gray, italic, bold, cyan, blue, green, underline, yellow } = pkg; 7 | 8 | const program = new Command(); 9 | 10 | pkg.theme({ 11 | danger: red, 12 | dark: dim.gray, 13 | disabled: gray, 14 | em: italic, 15 | heading: bold.underline, 16 | info: cyan, 17 | muted: dim, 18 | primary: blue, 19 | strong: bold, 20 | success: green.bold, 21 | underline, 22 | warning: yellow.underline, 23 | }); 24 | 25 | const info = (msg) => pkg.info(msg); 26 | const heading = (msg) => pkg.heading(msg); 27 | const em = (msg) => pkg.em(msg); 28 | program 29 | .description("Bump version and create a new tag") 30 | .option("-b, --beta", "Pre-release version") 31 | .option("--dry-run", "Dry run") 32 | .addOption( 33 | new Option("-r, --release-as ", "release type version").choices([ 34 | "major", 35 | "minor", 36 | "patch", 37 | ]) 38 | ); 39 | 40 | program.parse(); 41 | const opt = program.opts(); 42 | 43 | const betaMsg = opt.beta ? em("- Pre-release\n\t") : ""; 44 | const dryRunMsg = opt.dryRun ? em("- Dry run\n\t") : ""; 45 | const releaseAsMsg = opt.releaseAs 46 | ? em(`- Release as ${underline(opt.releaseAs)}`) 47 | : ""; 48 | 49 | const msg = dedent(` 50 | ${heading("Options :")} 51 | ${betaMsg}${dryRunMsg}${releaseAsMsg} 52 | `); 53 | 54 | console.log(msg); 55 | console.log(); 56 | 57 | if (opt.beta) { 58 | console.log(`${bold.green(">")} ${info(pkg.underline("Bumping beta version..."))}`); 59 | console.log(); 60 | const bumpFiles = [ 61 | { 62 | filename: "manifest-beta.json", 63 | type: "json", 64 | }, 65 | { 66 | filename: "package.json", 67 | type: "json", 68 | }, 69 | { 70 | filename: "package-lock.json", 71 | type: "json", 72 | }, 73 | ]; 74 | commitAndTagVersion({ 75 | infile: "CHANGELOG-beta.md", 76 | bumpFiles, 77 | prerelease: "", 78 | dryRun: opt.dryRun, 79 | tagPrefix: "", 80 | }) 81 | .then(() => { 82 | console.log("Done"); 83 | }) 84 | .catch((err) => { 85 | console.error(err); 86 | }); 87 | } else { 88 | const versionBumped = opt.releaseAs 89 | ? info(`Release as ${underline(opt.releaseAs)}`) 90 | : info("Release"); 91 | console.log(`${bold.green(">")} ${underline(versionBumped)}`); 92 | console.log(); 93 | 94 | const bumpFiles = [ 95 | { 96 | filename: "manifest-beta.json", 97 | type: "json", 98 | }, 99 | { 100 | filename: "package.json", 101 | type: "json", 102 | }, 103 | { 104 | filename: "package-lock.json", 105 | type: "json", 106 | }, 107 | { 108 | filename: "manifest.json", 109 | type: "json", 110 | } 111 | ]; 112 | 113 | 114 | commitAndTagVersion({ 115 | infile: "CHANGELOG.md", 116 | bumpFiles: bumpFiles, 117 | dryRun: opt.dryRun, 118 | tagPrefix: "", 119 | releaseAs: opt.releaseAs, 120 | }) 121 | .then(() => { 122 | console.log("Done"); 123 | }) 124 | .catch((err) => { 125 | console.error(err); 126 | }); 127 | } -------------------------------------------------------------------------------- /esbuild.config.mjs: -------------------------------------------------------------------------------- 1 | import builtins from "builtin-modules"; 2 | import { Command } from "commander"; 3 | import dotenv from "dotenv"; 4 | import esbuild from "esbuild"; 5 | import * as fs from "fs"; 6 | import * as path from "path"; 7 | import packageJson from "./package.json" with { type: "json" }; 8 | import manifest from "./manifest.json" with { type: "json" }; 9 | 10 | const banner = `/* 11 | THIS IS A GENERATED/BUNDLED FILE BY ESBUILD 12 | if you want to view the source, please visit the github repository of this plugin: ${packageJson.repository} 13 | */ 14 | `; 15 | 16 | function cleanOutDir(outdir) { 17 | if (fs.existsSync(outdir)) { 18 | fs.rm(outdir, { recursive: true }); 19 | } 20 | } 21 | 22 | 23 | /** 24 | * @typedef Options 25 | * @prop {boolean|undefined} production 26 | * @prop {string|boolean|undefined} vault 27 | * @prop {string|undefined} outputDir 28 | * @prop {boolean|undefined} beta 29 | */ 30 | 31 | dotenv.config({path: [".env"]}); 32 | 33 | const program = new Command(); 34 | program 35 | .option("-p, --production", "Production build") 36 | .option("-v, --vault [vault]", "Use vault path").action((v) => { 37 | if (!v) return false; 38 | if (typeof v === "string") return path.resolve(v.replace(/\\/g, "/")); 39 | return process.env.VAULT; 40 | }) 41 | .option("-o, --output-dir ", "Output path") 42 | .option("-b, --beta", "Pre-release version") 43 | .parse(); 44 | program.parse(); 45 | 46 | /** OPTIONS */ 47 | /** @type {Options} */ 48 | const opt = program.opts(); 49 | /** @type {boolean} */ 50 | const prod = opt.production ?? false; 51 | 52 | /** VARIABLES **/ 53 | const isStyled = fs.existsSync("src/styles.css"); 54 | const pluginID = manifest.id; 55 | 56 | /** FOLDER PATHS **/ 57 | const folderPlugin = opt.vault 58 | ? path.join(opt.vault, ".obsidian", "plugins", pluginID) 59 | : undefined; 60 | 61 | if (folderPlugin && !fs.existsSync(folderPlugin)) { 62 | fs.mkdirSync(folderPlugin, { recursive: true }); 63 | } 64 | if (opt.beta && !fs.existsSync("manifest-beta.json")) { 65 | fs.copyFileSync("manifest.json", "manifest-beta.json"); 66 | } 67 | 68 | let outDir = "./"; 69 | if (opt.outputDir) { 70 | outDir = opt.outputDir; 71 | cleanOutDir(outDir); 72 | } else if (opt.vault) { 73 | outDir = folderPlugin; 74 | if (!prod) fs.writeFileSync(path.join(folderPlugin, ".hotreload"), ""); 75 | } else if (prod) { 76 | outDir = "./dist"; 77 | //clean dist if 78 | cleanOutDir(outDir); 79 | } 80 | 81 | /** 82 | * Move styles.css to output directory 83 | */ 84 | const moveStyles = { 85 | name: "move-styles", 86 | setup(build) { 87 | build.onEnd(() => { 88 | fs.copyFileSync("src/styles.css", "./styles.css"); 89 | }); 90 | }, 91 | }; 92 | 93 | /** 94 | * Export to vault if set in environment variable 95 | */ 96 | const exportToVaultFunc = { 97 | name: "export-to-vault", 98 | setup(build) { 99 | build.onEnd(() => { 100 | if (!folderPlugin) 101 | throw new Error("VAULT environment variable not set, skipping export to vault"); 102 | 103 | fs.copyFileSync(`${outDir}/main.js`, path.join(folderPlugin, "main.js")); 104 | if (fs.existsSync(`${outDir}/styles.css`)) 105 | fs.copyFileSync("./styles.css", path.join(folderPlugin, "styles.css")); 106 | if (opt.beta) fs.copyFileSync("manifest-beta.json", path.join(folderPlugin, "manifest.json")); 107 | else fs.copyFileSync("./manifest.json", path.join(folderPlugin, "manifest.json")); 108 | }); 109 | }, 110 | }; 111 | 112 | /** 113 | * Export to production folder 114 | */ 115 | const exportToDist = { 116 | name: "export-to-dist", 117 | setup(build) { 118 | build.onEnd(() => { 119 | if (opt.beta) fs.copyFileSync("manifest-beta.json", path.join(outDir, "manifest.json")); 120 | else fs.copyFileSync("manifest.json", path.join(outDir, "manifest.json")); 121 | }); 122 | }, 123 | }; 124 | 125 | /** 126 | * ENTRIES * 127 | */ 128 | const entryPoints = ["src/main.ts"]; 129 | if (isStyled) entryPoints.push("src/styles.css"); 130 | 131 | /** PLUGINS **/ 132 | const plugins = []; 133 | if (isStyled) plugins.push(moveStyles); 134 | if (prod) plugins.push(exportToDist); 135 | if (prod && opt.vault) plugins.push(exportToVaultFunc); 136 | 137 | /** 138 | * BUILD 139 | */ 140 | const context = await esbuild.context({ 141 | banner: { 142 | js: banner, 143 | }, 144 | entryPoints, 145 | bundle: true, 146 | external: [ 147 | "obsidian", 148 | "electron", 149 | "@codemirror/autocomplete", 150 | "@codemirror/collab", 151 | "@codemirror/commands", 152 | "@codemirror/language", 153 | "@codemirror/lint", 154 | "@codemirror/search", 155 | "@codemirror/state", 156 | "@codemirror/view", 157 | "@lezer/common", 158 | "@lezer/highlight", 159 | "@lezer/lr", 160 | ...builtins, 161 | ], 162 | format: "cjs", 163 | target: "esnext", 164 | logLevel: "info", 165 | sourcemap: prod ? false : "inline", 166 | treeShaking: true, 167 | minifySyntax: prod, 168 | minifyWhitespace: prod, 169 | outdir: outDir, 170 | plugins, 171 | }); 172 | 173 | if (prod) { 174 | console.log("🎉 Build for production"); 175 | console.log(`📤 Output directory: ${outDir}`); 176 | await context.rebuild(); 177 | console.log("✅ Build successful"); 178 | process.exit(0); 179 | } else { 180 | console.log("🚀 Start development build"); 181 | console.log(`📤 Output directory: ${outDir}`); 182 | await context.watch(); 183 | } 184 | -------------------------------------------------------------------------------- /manifest-beta.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Mara-Li", 3 | "authorUrl": "https://github.com/Mara-Li", 4 | "description": "Copy your selection and add it some edit to paste in other markdown software. Allows to keep markdown in reading view, removing wikilinks in editing, copy from locked canvas, and more!", 5 | "fundingUrl": "https://ko-fi.com/Mara__Li", 6 | "id": "enhanced-copy", 7 | "isDesktopOnly": false, 8 | "minAppVersion": "0.16.0", 9 | "name": "Enhanced Copy", 10 | "version": "0.2.14" 11 | } 12 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "author": "Mara-Li", 3 | "authorUrl": "https://github.com/Mara-Li", 4 | "description": "Copy your selection and add it some edit to paste in other markdown software. Allows to keep markdown in reading view, removing wikilinks in editing, copy from locked canvas, and more!", 5 | "fundingUrl": "https://ko-fi.com/Mara__Li", 6 | "id": "enhanced-copy", 7 | "isDesktopOnly": false, 8 | "minAppVersion": "0.16.0", 9 | "name": "Enhanced Copy", 10 | "version": "0.2.14" 11 | } 12 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "commit-and-tag-version": { 3 | "t": "" 4 | }, 5 | "dependencies": { 6 | "ansi-colors": "^4.1.3", 7 | "builtin-modules": "^3.3.0", 8 | "commit-and-tag-version": "^11.2.2", 9 | "dotenv": "^16.3.1", 10 | "dotenv-cli": "^7.2.1", 11 | "esbuild": "^0.18.18", 12 | "i18next": "^23.4.1", 13 | "tslib": "^2.6.1" 14 | }, 15 | "description": "Copy a selection in reading view while keeping the markdown formatting", 16 | "devDependencies": { 17 | "@biomejs/biome": "1.7.3", 18 | "@codemirror/view": "^6.21.4", 19 | "@enveloppe/obsidian-dataview": "^0.5.66", 20 | "@types/electron": "npm:@ophidian/electron-types@^24.3.1", 21 | "@types/node": "^20.4.8", 22 | "@types/obsidian-typings": "npm:obsidian-typings@^1.1.6", 23 | "commander": "^11.0.0", 24 | "cross-env": "^7.0.3", 25 | "dedent": "^1.5.1", 26 | "env-cmd": "^10.1.0", 27 | "monkey-around": "^2.3.0", 28 | "obsidian": "^1.4.0", 29 | "ts-deepmerge": "^6.2.0", 30 | "typescript": "^5.1.6" 31 | }, 32 | "license": "GPL-3.0-only", 33 | "main": "lib/main.js", 34 | "name": "advanced-copy", 35 | "scripts": { 36 | "lint": "biome lint src/ --apply", 37 | "prebuild": "tsc --noEmit --skipLibCheck", 38 | "build": "node esbuild.config.mjs --production", 39 | "dev:prod": "node esbuild.config.mjs --vault", 40 | "dev": "node esbuild.config.mjs", 41 | "export": "node esbuild.config.mjs --production --vault", 42 | "bump": "node commit-and-tag-version.mjs", 43 | "postbump": "git push --follow-tags origin master", 44 | "predeploy": "bun run bump", 45 | "deploy": "pnpm run export" 46 | }, 47 | "private": true, 48 | "version": "0.2.14", 49 | "pnpm": true 50 | } 51 | -------------------------------------------------------------------------------- /src/@types/i18next.d.ts: -------------------------------------------------------------------------------- 1 | import type { resources } from "../i18n/i18next"; 2 | 3 | declare module "i18next" { 4 | interface CustomTypeOptions { 5 | resources: (typeof resources)["en"]; 6 | returnNull: false; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/i18n/i18next.ts: -------------------------------------------------------------------------------- 1 | import { moment } from "obsidian"; 2 | 3 | import * as en from "./locales/en.json"; 4 | import * as fr from "./locales/fr.json"; 5 | 6 | export const resources = { 7 | en: { translation: en }, 8 | fr: { translation: fr }, 9 | } as const; 10 | 11 | const localeUsed = window.localStorage.language || moment.locale(); 12 | 13 | export const translationLanguage = Object.keys(resources).find((i) => i == localeUsed) 14 | ? localeUsed 15 | : "en"; 16 | -------------------------------------------------------------------------------- /src/i18n/locales/en.json: -------------------------------------------------------------------------------- 1 | { 2 | "auto": { 3 | "EQUAL": "EQUAL TO", 4 | "and": "", 5 | "desc": "Allow to automatically use this profile based on the path, tag or properties.
For properties, it will be matched on the enhanced_copy key.
It also supports regex (without the need to enclose them in /)!", 6 | "frontmatter": "Properties", 7 | "is": "", 8 | "not": "NOT EQUAL TO", 9 | "or": "OR", 10 | "path": "Path", 11 | "placeholder": "Value to match", 12 | "tag": "Tags", 13 | "title": "Automatic use" 14 | }, 15 | "callout": { 16 | "desc": "Format of the callout type. All format will be in blockquote.", 17 | "obsidian": "Use Obsidian's default callout format", 18 | "remove": "Remove the type & title", 19 | "removeKeepTitle": "Keeping the title but removing the type.", 20 | "strong": "Convert the type to a simple strong text, keep the title", 21 | "title": "Callout type" 22 | }, 23 | "commands": { 24 | "all": "Copy selected text", 25 | "brute": "Native copy", 26 | "editor": "Copy selected text from edit view", 27 | "other": "Copy selected text from opened view", 28 | "reading": "Copy selected text from reading view" 29 | }, 30 | "common": { 31 | "add": "Add", 32 | "cancel": "Cancel", 33 | "delete": "Delete", 34 | "from": "From", 35 | "pattern": "pattern", 36 | "profile": "Profile name", 37 | "replacement": "replacement", 38 | "save": "Save", 39 | "to": "To" 40 | }, 41 | "convertDataview": { 42 | "block": "Code block", 43 | "djs": { 44 | "block": { 45 | }, 46 | "inline": { 47 | }, 48 | "title": "Dataview JS" 49 | }, 50 | "dql": { 51 | "block": { 52 | }, 53 | "inline": { 54 | }, 55 | "title": "Dataview Query Language" 56 | }, 57 | "global": { 58 | "desc": "Allows you to convert dataview queries (inline DQL, Djs...) to markdown. \nDoes not always work, use with moderation.", 59 | "title": "Convert Dataview queries to markdown" 60 | }, 61 | "inline": "Inline" 62 | }, 63 | "copyAsHTML": "Copy as HTML instead of Markdown. Some options may not be available.", 64 | "copyLinksAsText": { 65 | "desc": "Adjust the way links are formatted when copying to the clipboard.", 66 | "external": "Remove markup for internal links only", 67 | "keep": "Keep markup", 68 | "remove": "Remove markup for all links", 69 | "title": "Links format" 70 | }, 71 | "debug": { 72 | "desc": "Show debug log in console", 73 | "title": "Debug information" 74 | }, 75 | "delete": { 76 | }, 77 | "edit": { 78 | "desc": "Edit view settings", 79 | "title": "Edit" 80 | }, 81 | "global": { 82 | "copy": "Copy settings between profile", 83 | "title": "General parameters" 84 | }, 85 | "hardBreaks": { 86 | "desc": "Add a standard markdown line break (two spaces at the end of the line) at the end of each line.", 87 | "title": "Hard breaks" 88 | }, 89 | "highlight": { 90 | "desc": "Remove the highlight markup (==).", 91 | "title": "Highlight" 92 | }, 93 | "hotkey": { 94 | "desc": "Create a separate command for each mode. This allows you to assign a different hotkey for each mode. ⚠️️ You need to reload the plugin to apply the changes.", 95 | "title": "Separate commands" 96 | }, 97 | "links": "Links", 98 | "log": { 99 | "callout": { 100 | "remove": "Remove callout title", 101 | "title": "Convert callout" 102 | }, 103 | "editMode": "Edit mode", 104 | "empty": "selectedText is empty // Fallback on activeWindow.getSelection().toString()", 105 | "noHardBreaks": "No hard breaks - Remove extra spaces at the end of each line", 106 | "readingMode": "Reading mode" 107 | }, 108 | "modal": { 109 | "copyView": { 110 | "copy": "Copy", 111 | "editing": "Editing", 112 | "reading": "Reading" 113 | }, 114 | "replaceText": { 115 | "down": "Move down", 116 | "title": "Replace Text", 117 | "up": "Move up" 118 | } 119 | }, 120 | "openTextReplacer": "Open Text replacer", 121 | "other": "Other options", 122 | "overrideCopy": { 123 | "desc": "Replace the native copy (CTRL C, right-click...) with the enhanced copy (need a reload of Obsidian)", 124 | "title": "Override native copy" 125 | }, 126 | "profile": { 127 | "add": { 128 | "desc": "Add a copy profile. \nAn Obsidian reload is required to use it as a command.", 129 | "title": "Add profile" 130 | }, 131 | "delete": "Delete profile" 132 | }, 133 | "reading": { 134 | "desc": "Reading view settings", 135 | "title": "Reading" 136 | }, 137 | "removeFootnotesLinks": { 138 | "desc": "Adjust the way footnotes are formatted when copying them to the clipboard.", 139 | "format": "Remove all links but keep contents as [^1]", 140 | "keep": "Keep all links markup and contents", 141 | "remove": "Remove all links markup and contents", 142 | "title": "Footnotes format" 143 | }, 144 | "spaceSize": { 145 | "desc": "Number of spaces to be used for indentation. Use -1 to disable the conversion.", 146 | "title": "Space size" 147 | }, 148 | "tabSpaceSize": "Number of spaces to be used for indentation", 149 | "tabToSpace": "Convert tabs to spaces", 150 | "unconventionalMarkdown": { 151 | "desc": "Removed unconventional Markdown markup because they are not supported by all Markdown interpreters.", 152 | "title": "Unconventional Markdown" 153 | }, 154 | "view": { 155 | "all": "All view", 156 | "desc": "Choose on which view the conversion should be applied.", 157 | "edit": "Edit view", 158 | "reading": "Reading view only", 159 | "title": "Apply settings" 160 | }, 161 | "wikiToMarkdown": { 162 | "desc": "Mandatory to edit the links when copying them to the clipboard. If disabled, the settings for links format will be ignored.", 163 | "title": "Convert wiki links to Markdown link" 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/i18n/locales/fr.json: -------------------------------------------------------------------------------- 1 | { 2 | "auto": { 3 | "EQUAL": "ÉGAL À", 4 | "and": "ET", 5 | "desc": "Permet d'utiliser automatiquement ce profil en se basant sur le chemin, un tag ou les propriétés.
Pour les propriétés, la valeur sera sélectionnée à partir de la clé enhanced_copy.
Les regex sont aussi supportés (sans avoir besoin de les mettre entre /) !", 6 | "frontmatter": "Propriétés", 7 | "is": "Activer uniquement SI VALIDE la condition", 8 | "not": "DIFFÉRENT DE", 9 | "or": "OU", 10 | "path": "Chemin", 11 | "placeholder": "Valeur à trouver", 12 | "tag": "Tags", 13 | "title": "Utilisation automatique" 14 | }, 15 | "callout": { 16 | "desc": "Format du type de callout. Tous les formats seront sous formes de citations.", 17 | "obsidian": "Utiliser le format de callout d'Obsidian", 18 | "remove": "Suppression du type et titre", 19 | "removeKeepTitle": "Conservation du titre mais suppression du type", 20 | "strong": "Convertir le type en gras", 21 | "title": "Type de callout" 22 | }, 23 | "commands": { 24 | "all": "Copier le texte sélectionné", 25 | "brute": "Copie native", 26 | "editor": "Copier le texte sélectionné depuis l'éditeur", 27 | "other": "Copier le texte sélectionné depuis la vue non markdown", 28 | "reading": "Copier le texte sélectionné depuis la vue de lecture" 29 | }, 30 | "common": { 31 | "add": "Ajouter", 32 | "cancel": "Annuler", 33 | "delete": "Supprimer", 34 | "from": "Depuis", 35 | "pattern": "pattern", 36 | "profile": "Nom du profil", 37 | "replacement": "remplacement", 38 | "save": "Sauvegarder", 39 | "to": "Vers" 40 | }, 41 | "convertDataview": { 42 | "block": "Bloc de code", 43 | "djs": { 44 | "block": { 45 | }, 46 | "inline": { 47 | }, 48 | "title": "Dataview JS" 49 | }, 50 | "dql": { 51 | "block": { 52 | }, 53 | "inline": { 54 | }, 55 | "title": "Dataview Query Language" 56 | }, 57 | "global": { 58 | "desc": "Permet de convertir les queries dataview (inline DQL, Djs...) en markdown. Ne fonctionne pas toujours, à utiliser avec modération.", 59 | "title": "Convertir les queries Dataview en markdown" 60 | }, 61 | "inline": "Inline" 62 | }, 63 | "copyAsHTML": "Copier en HTML au lieu de Markdown. Certaines options peuvent ne pas être disponibles.", 64 | "copyLinksAsText": { 65 | "desc": "Modifier l'aspect des liens lorsqu'ils sont copiés dans le presse-papiers.", 66 | "external": "Supprimer les balises pour les liens internes seulement", 67 | "keep": "Conserver toutes les balises", 68 | "remove": "Supprimer les balises pour tous les liens", 69 | "title": "Format des liens" 70 | }, 71 | "debug": { 72 | "desc": "Affiche le journal de débogage dans la console", 73 | "title": "Informations de débogage" 74 | }, 75 | "delete": { 76 | }, 77 | "edit": { 78 | "desc": "Paramètre pour la vue d'édition", 79 | "title": "Édition" 80 | }, 81 | "global": { 82 | "copy": "Copier les paramètres entre les profiles", 83 | "title": "Paramètres généraux" 84 | }, 85 | "hardBreaks": { 86 | "desc": "Ajouter un saut de ligne strict (deux espaces en fin de ligne) à la fin de chaque ligne.", 87 | "title": "Saut de ligne strict" 88 | }, 89 | "highlight": { 90 | "desc": "Suppression de la balise de surlignage (==)", 91 | "title": "Surlignage" 92 | }, 93 | "hotkey": { 94 | "desc": "Créez une commande distincte pour chaque mode. Cela vous permet d'attribuer un raccourci clavier différent pour chaque mode. ⚠ Nécessite le rechargement du plugin pour prendre effet.", 95 | "title": "Séparer les commandes" 96 | }, 97 | "links": "Liens", 98 | "log": { 99 | "callout": { 100 | "remove": "Supprimer le titre de l'accroche", 101 | "title": "Convertir l'accroche" 102 | }, 103 | "editMode": "Mode édition", 104 | "empty": "selectedText est vide // Repli sur activeWindow.getSelection().toString()", 105 | "noHardBreaks": "Pas de pauses dures - Supprimez les espaces supplémentaires à la fin de chaque ligne", 106 | "readingMode": "Mode de lecture" 107 | }, 108 | "modal": { 109 | "copyView": { 110 | "copy": "Copier", 111 | "editing": "Édition", 112 | "reading": "Lecture" 113 | }, 114 | "replaceText": { 115 | "down": "Descendre", 116 | "title": "Remplacer du texte", 117 | "up": "Monter" 118 | } 119 | }, 120 | "openTextReplacer": "Ouvrir le remplacement de texte", 121 | "other": "Autres options", 122 | "overrideCopy": { 123 | "desc": "Remplacer la copie native (CTRL + C, clic-droit...) par la copie améliorée (nécessite un rechargement d'Obsidian)", 124 | "title": "Prendre en charge la copie native" 125 | }, 126 | "profile": { 127 | "add": { 128 | "desc": "Ajouter un profil de copy. Un rechargement d'Obsidian est nécessaire pour l'utiliser comme commande.", 129 | "title": "Ajouter un profile" 130 | }, 131 | "delete": "Supprimer le profile" 132 | }, 133 | "reading": { 134 | "desc": "Paramètre pour la vue de lecture", 135 | "title": "Lecture" 136 | }, 137 | "removeFootnotesLinks": { 138 | "desc": "Modifier les balises des notes de bas de page lorsqu'elles sont copiées dans le presse-papiers.", 139 | "format": "Supprimer les liens, mais conserver le contenu sous forme de [^1]", 140 | "keep": "Conserver balises et contenu", 141 | "remove": "Supprimer balises et contenu", 142 | "title": "Format des footnotes" 143 | }, 144 | "spaceSize": { 145 | "desc": "Modification du nombre d'espace pour la mise en retrait. Utiliser -1 pour désactiver la fonction de conversion.", 146 | "title": "Nombre d'espace" 147 | }, 148 | "tabSpaceSize": "Nombre d'espaces à utiliser pour la mise en retrait", 149 | "tabToSpace": "Convertir les tabulations en espace", 150 | "unconventionalMarkdown": { 151 | "desc": "Suppression des balises Markdown non conventionnelles car elles ne sont pas prise en charge par tous les interpréteurs Markdown.", 152 | "title": "Markdown non conventionnel" 153 | }, 154 | "view": { 155 | "all": "Tous les modes", 156 | "desc": "Choisissez le mode sur lequel les conversions doivent être appliqués.", 157 | "edit": "Mode Édition", 158 | "reading": "Mode lecture uniquement", 159 | "title": "Appliquer les paramètres" 160 | }, 161 | "wikiToMarkdown": { 162 | "desc": "Obligatoire pour éditer les liens lors de leur copie dans le presse-papiers. Si cette option est désactivée, les paramètres pour le format des liens sera ignoré.", 163 | "title": "Convertir les liens Wiki en liens Markdown" 164 | } 165 | } 166 | -------------------------------------------------------------------------------- /src/interface.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @file interface.ts 3 | * @description Interface for the plugin 4 | * 5 | */ 6 | 7 | /** 8 | * How to convert the footnotes 9 | * @example `remove` : Remove all footnotes in markdown 10 | * `[[1]](#text)` -> `` 11 | * @example `format` : Keep the content of the footnote but remove the footnote format 12 | * `[[1]](#text)` -> `[^1]` 13 | * @example `keep` : Keep all footnotes in markdown 14 | * `[[1]](#text)` -> `[[1]](#text)` 15 | * @enum {string} ConversionOfFootnotes 16 | */ 17 | export enum ConversionOfFootnotes { 18 | Keep = "keep", 19 | Remove = "remove", 20 | Format = "format", 21 | } 22 | 23 | /** 24 | * How to convert the links 25 | * @example `keep` : Keep all links in markdown 26 | * `[text](#link)` -> `[text](#link)` 27 | * @example `remove` : Remove all links in markdown 28 | * `[text](#link)` -> `text` 29 | * @example `external` : Remove all links in markdown except the external ones 30 | * `[text](#link)` -> `text` 31 | * `[text](https://example.com)` -> `[text](https://example.com)` 32 | * @enum {string} ConversionOfLinks 33 | */ 34 | export enum ConversionOfLinks { 35 | Keep = "keep", 36 | Remove = "remove", 37 | External = "external", 38 | } 39 | 40 | /** 41 | * How to keep the title of the callout 42 | * @example `obsidian` : Keep the title as it is in Obsidian 43 | * `> [!note]` -> `> [!note]` 44 | * @example `strong` : Make the title bold 45 | * `> [!note]` -> `> **Note**` 46 | * @example `remove` : Remove the title 47 | * `> [!note]` -> `>` 48 | */ 49 | export enum CalloutKeepType { 50 | Obsidian = "obsidian", 51 | Strong = "strong", 52 | Remove = "remove", 53 | RemoveKeepTitle = "removeKeepTitle", 54 | } 55 | 56 | /** 57 | * Where to apply the markdown conversion (reading, edit or both) 58 | * @example `all` : Apply the markdown conversion to both edit and reading mode 59 | * @example `reading` : Apply the markdown conversion to reading mode only 60 | * @example `edit` : Apply the markdown conversion to edit mode only 61 | */ 62 | export enum ApplyingToView { 63 | All = "all", 64 | Reading = "reading", 65 | Edit = "edit", 66 | } 67 | 68 | export const COLLAPSE_INDICATOR = new RegExp( 69 | '
', 70 | "gi" 71 | ); 72 | 73 | export interface EnhancedCopySettings { 74 | copyAsHTML: boolean; 75 | applyingTo: ApplyingToView; 76 | separateHotkey: boolean; 77 | editing: GlobalSettings; 78 | reading: GlobalSettings; 79 | devMode: boolean; 80 | profiles: GlobalSettings[]; 81 | } 82 | 83 | /** 84 | * Default settings of the plugin 85 | * @type {EnhancedCopySettings} 86 | * @constant 87 | * @default 88 | * @readonly 89 | */ 90 | export const DEFAULT_SETTINGS: EnhancedCopySettings = { 91 | copyAsHTML: false, 92 | applyingTo: ApplyingToView.All, 93 | separateHotkey: false, 94 | editing: { 95 | footnotes: ConversionOfFootnotes.Keep, 96 | links: ConversionOfLinks.Keep, 97 | callout: CalloutKeepType.Obsidian, 98 | highlight: false, 99 | hardBreak: false, 100 | replaceText: [], 101 | overrideNativeCopy: false, 102 | }, 103 | reading: { 104 | footnotes: ConversionOfFootnotes.Keep, 105 | links: ConversionOfLinks.Keep, 106 | callout: CalloutKeepType.Obsidian, 107 | highlight: false, 108 | hardBreak: false, 109 | replaceText: [], 110 | overrideNativeCopy: false, 111 | spaceReadingSize: -1, // -1 disabled 112 | wikiToMarkdown: false, 113 | }, 114 | devMode: false, 115 | profiles: [], 116 | }; 117 | 118 | export interface AutoRules { 119 | type: "path" | "tag" | "frontmatter"; 120 | value: string; 121 | not?: boolean; 122 | } 123 | 124 | export interface ConvertDataview { 125 | enable: boolean; 126 | djs: { 127 | inline: boolean; 128 | block: boolean; 129 | }; 130 | dql: { 131 | inline: boolean; 132 | block: boolean; 133 | }; 134 | } 135 | 136 | export const DEFAULT_DATAVIEW_SETTINGS_DISABLED: ConvertDataview = { 137 | enable: false, 138 | djs: { 139 | inline: false, 140 | block: false, 141 | }, 142 | dql: { 143 | inline: false, 144 | block: false, 145 | }, 146 | }; 147 | 148 | export const DEFAULT_DATAVIEW_SETTINGS_ENABLED: ConvertDataview = { 149 | enable: true, 150 | djs: { 151 | inline: true, 152 | block: true, 153 | }, 154 | dql: { 155 | inline: true, 156 | block: true, 157 | }, 158 | }; 159 | 160 | export interface GlobalSettings { 161 | name?: string; 162 | copyAsHTML?: boolean; 163 | footnotes: ConversionOfFootnotes; 164 | links: ConversionOfLinks; 165 | callout: CalloutKeepType; 166 | convertDataview?: ConvertDataview; 167 | highlight: boolean; 168 | hardBreak: boolean; 169 | replaceText: ReplaceText[]; 170 | overrideNativeCopy: boolean; 171 | spaceReadingSize?: number; //only work in reading mode 172 | tabToSpace?: boolean; //only work in edit mode 173 | tabSpaceSize?: number; //only work in edit mode 174 | wikiToMarkdown?: boolean; 175 | applyingTo?: ApplyingToView; //only work in profiles 176 | /** 177 | * Allow to automatically use this profile based on the path, tag or frontmatter 178 | */ 179 | autoRules?: AutoRules[]; //only work in profiles 180 | } 181 | 182 | export interface ReplaceText { 183 | pattern: string; 184 | replacement: string; 185 | } 186 | 187 | export enum CopySettingsView { 188 | Reading = "reading", 189 | Editing = "editing", 190 | } 191 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { EditorView } from "@codemirror/view"; 2 | import i18next from "i18next"; 3 | import { around } from "monkey-around"; 4 | import { 5 | getAllTags, 6 | ItemView, 7 | MarkdownView, 8 | Platform, 9 | Plugin, 10 | type WorkspaceLeaf, 11 | } from "obsidian"; 12 | import merge from "ts-deepmerge"; 13 | 14 | import { resources, translationLanguage } from "./i18n/i18next"; 15 | import { 16 | ApplyingToView, 17 | type AutoRules, 18 | DEFAULT_SETTINGS, 19 | type EnhancedCopySettings, 20 | type GlobalSettings, 21 | } from "./interface"; 22 | import { EnhancedCopySettingTab } from "./settings"; 23 | import { convertEditMarkdown, convertMarkdown } from "./utils/conversion"; 24 | import { removeDataBasePluginRelationShip } from "./utils/pluginFix"; 25 | import { 26 | canvasSelectionText, 27 | copySelectionRange, 28 | getSelectionAsHTML, 29 | } from "./utils/selection"; 30 | 31 | export default class EnhancedCopy extends Plugin { 32 | settings: EnhancedCopySettings = DEFAULT_SETTINGS; 33 | //eslint-disable-next-line @typescript-eslint/no-explicit-any 34 | activeMonkeys: Record = {}; 35 | 36 | checkByRules(rule: AutoRules, path: string, tags: string[], frontmatter?: string[]) { 37 | if (rule.type === "path" && path.match(rule.value)) { 38 | return true; 39 | } 40 | if (rule.type === "tag" && tags.find((tag) => tag.match(rule.value))) { 41 | return true; 42 | } 43 | if (rule.type === "frontmatter" && frontmatter?.find((fm) => fm.match(rule.value))) { 44 | return true; 45 | } 46 | return false; 47 | } 48 | 49 | /** 50 | * Get the profile based on file path, tag or frontmatter 51 | * Needs a active file to work 52 | */ 53 | getProfile(viewOfType?: ApplyingToView) { 54 | const activeFile = this.app.workspace.getActiveFile(); 55 | if (!activeFile) return; 56 | const path = activeFile.path; 57 | const cache = this.app.metadataCache.getFileCache(activeFile); 58 | const cacheFrontmatterKeys = cache?.frontmatter?.enhanced_copy ?? undefined; 59 | const enhancedCopyFrontmatter: string[] | undefined = 60 | cacheFrontmatterKeys && typeof cacheFrontmatterKeys === "string" 61 | ? [cacheFrontmatterKeys] 62 | : cacheFrontmatterKeys; 63 | const tags = cache ? getAllTags(cache) ?? [] : []; 64 | const profiles = this.settings.profiles; 65 | 66 | for (const profile of profiles) { 67 | if ( 68 | viewOfType && 69 | profile.applyingTo !== ApplyingToView.All && 70 | profile.applyingTo !== viewOfType 71 | ) 72 | continue; 73 | if (profile.autoRules) { 74 | //search if [NOT] path, tag or frontmatter is in the profile and check if it matches 75 | const matchNote = profile.autoRules.find( 76 | (rule) => 77 | rule.not && this.checkByRules(rule, path, tags, enhancedCopyFrontmatter) 78 | ); 79 | if (matchNote) continue; 80 | for (const rule of profile.autoRules) { 81 | if (rule.not) continue; 82 | if (this.checkByRules(rule, path, tags, enhancedCopyFrontmatter)) 83 | return profile; 84 | } 85 | } 86 | } 87 | } 88 | 89 | async enhancedCopy(profile?: GlobalSettings) { 90 | //get default if a modal is opened 91 | if (document.querySelector(".modal-container")) { 92 | return activeWindow.getSelection()?.toString() ?? ""; 93 | } 94 | const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); 95 | const file = this.app.workspace.getActiveFile(); 96 | let viewIn: ApplyingToView; 97 | let selectedText: string; 98 | if (activeView && activeView.getMode() !== "source") { 99 | this.devLog(i18next.t("log.readingMode")); 100 | selectedText = getSelectionAsHTML(profile ?? this.settings.reading); 101 | viewIn = ApplyingToView.Reading; 102 | } else if (activeView) { 103 | this.devLog(i18next.t("log.editMode")); 104 | const editor = activeView.editor; 105 | selectedText = copySelectionRange(editor, this); 106 | viewIn = ApplyingToView.Edit; 107 | } else { 108 | const leafType = this.app.workspace.getActiveViewOfType(ItemView)?.getViewType(); 109 | if (leafType === "canvas") { 110 | selectedText = canvasSelectionText(this.app, this); 111 | viewIn = this.app.workspace.activeEditor 112 | ? ApplyingToView.Edit 113 | : ApplyingToView.Reading; 114 | } else { 115 | selectedText = 116 | leafType === "database-plugin" 117 | ? removeDataBasePluginRelationShip() 118 | : activeWindow.getSelection()?.toString() ?? ""; 119 | viewIn = ApplyingToView.Reading; 120 | } 121 | } 122 | if (!profile) profile = this.getProfile(viewIn); 123 | this.devLog("Profile: ", profile); 124 | const exportAsHTML = profile 125 | ? profile?.copyAsHTML ?? false 126 | : this.settings.reading.copyAsHTML; 127 | const applyingTo = profile?.applyingTo ?? this.settings.applyingTo; 128 | if (selectedText && selectedText.trim().length > 0) { 129 | if (!exportAsHTML && (applyingTo === ApplyingToView.All || applyingTo === viewIn)) { 130 | selectedText = 131 | viewIn === ApplyingToView.Edit 132 | ? await convertEditMarkdown( 133 | selectedText, 134 | profile ?? this.settings.editing, 135 | this, 136 | file?.path 137 | ) 138 | : convertMarkdown(selectedText, profile ?? this.settings.reading, this); 139 | } 140 | return selectedText; 141 | } else if (viewIn === ApplyingToView.Edit) { 142 | return selectedText; 143 | } 144 | return selectedText; 145 | } 146 | 147 | async overrideNativeCopy(leaf: WorkspaceLeaf) { 148 | const activeView = this.app.workspace.getActiveViewOfType(MarkdownView); 149 | if ( 150 | activeView && 151 | activeView.getMode() !== "source" && 152 | !this.settings.reading.overrideNativeCopy 153 | ) 154 | return; 155 | if ( 156 | activeView && 157 | activeView.getMode() === "source" && 158 | !this.settings.editing.overrideNativeCopy 159 | ) 160 | return; 161 | try { 162 | return around(leaf.view, { 163 | //@ts-ignore 164 | handleCopy: () => { 165 | return async (event: ClipboardEvent) => { 166 | try { 167 | const selectedText = await this.enhancedCopy(); 168 | if (selectedText) { 169 | event.preventDefault(); 170 | event.clipboardData?.setData("text/plain", selectedText); 171 | } 172 | //old(event); 173 | } catch (e) { 174 | console.error(e); 175 | } 176 | }; 177 | }, 178 | }); 179 | } catch (e) { 180 | console.error(e); 181 | } 182 | } 183 | 184 | async editorCopyHandler(event: ClipboardEvent, _editor?: EditorView) { 185 | const selectedText = await this.enhancedCopy(); 186 | event.preventDefault(); 187 | event.clipboardData?.setData("text/plain", selectedText); 188 | return true; 189 | } 190 | 191 | async editorCutHandler(event: ClipboardEvent, _editor?: EditorView) { 192 | const selectedText = await this.enhancedCopy(); 193 | event.clipboardData?.setData("text/plain", selectedText); 194 | event.preventDefault(); 195 | //mimic cut behavior 196 | const editorObs = this.app.workspace.activeEditor?.editor; 197 | if (editorObs) { 198 | editorObs.replaceSelection(""); 199 | } 200 | } 201 | 202 | async onload() { 203 | console.log(`Enhanced copy v.${this.manifest.version} loaded.`); 204 | 205 | await i18next.init({ 206 | lng: translationLanguage, 207 | fallbackLng: "en", 208 | resources, 209 | returnNull: false, 210 | returnEmptyString: false, 211 | }); 212 | 213 | await this.loadSettings(); 214 | this.addSettingTab(new EnhancedCopySettingTab(this.app, this)); 215 | 216 | for (const profile of this.settings.profiles) { 217 | if (!profile.name) continue; 218 | this.addCommand({ 219 | id: `copy-${profile.name}-in-markdown`, 220 | name: profile.name, 221 | //@ts-ignore 222 | checkCallback: async (checking: boolean) => { 223 | const view = this.app.workspace.getActiveViewOfType(MarkdownView); 224 | const readingMode = view && view.getMode() !== "source"; 225 | if ( 226 | profile.applyingTo === ApplyingToView.All || 227 | (profile.applyingTo === ApplyingToView.Reading && readingMode) || 228 | (profile.applyingTo === ApplyingToView.Edit && !readingMode) 229 | ) { 230 | if (!checking) { 231 | navigator.clipboard.writeText(await this.enhancedCopy(profile)); 232 | } 233 | return true; 234 | } 235 | return false; 236 | }, 237 | }); 238 | } 239 | 240 | if ( 241 | !this.settings.separateHotkey || 242 | this.settings.applyingTo !== ApplyingToView.All 243 | ) { 244 | this.addCommand({ 245 | id: "copy-all-in-markdown", 246 | name: i18next.t("commands.all"), 247 | callback: async () => { 248 | navigator.clipboard.writeText(await this.enhancedCopy()); 249 | }, 250 | }); 251 | } else if (this.settings.separateHotkey) { 252 | if ( 253 | this.settings.applyingTo === ApplyingToView.All || 254 | this.settings.applyingTo === ApplyingToView.Edit 255 | ) { 256 | this.addCommand({ 257 | id: "copy-editor-in-markdown", 258 | name: i18next.t("commands.editor"), 259 | editorCallback: async (editor) => { 260 | const file = this.app.workspace.getActiveFile(); 261 | let selectedText = copySelectionRange(editor, this); 262 | if (selectedText && selectedText.trim().length > 0) { 263 | const profile = 264 | this.getProfile(ApplyingToView.Edit) ?? this.settings.editing; 265 | selectedText = await convertEditMarkdown( 266 | selectedText, 267 | profile, 268 | this, 269 | file?.path 270 | ); 271 | navigator.clipboard.writeText(selectedText); 272 | } 273 | }, 274 | }); 275 | } 276 | if ( 277 | this.settings.applyingTo === ApplyingToView.All || 278 | this.settings.applyingTo === ApplyingToView.Reading 279 | ) { 280 | this.addCommand({ 281 | id: "copy-reading-in-markdown", 282 | name: i18next.t("commands.reading"), 283 | checkCallback: (checking: boolean) => { 284 | const view = this.app.workspace.getActiveViewOfType(MarkdownView); 285 | const readingMode = view && view.getMode() !== "source"; 286 | if (readingMode) { 287 | if (!checking) { 288 | const profile = 289 | this.getProfile(ApplyingToView.Reading) ?? this.settings.reading; 290 | let selectedText = getSelectionAsHTML(profile); 291 | if (!this.settings.copyAsHTML) { 292 | selectedText = convertMarkdown(selectedText, profile, this); 293 | } 294 | navigator.clipboard.writeText(selectedText); 295 | } 296 | return true; 297 | } 298 | return false; 299 | }, 300 | }); 301 | } 302 | 303 | this.addCommand({ 304 | id: "copy-other-in-markdown", 305 | name: i18next.t("commands.other"), 306 | //@ts-ignore 307 | checkCallback: async (checking: boolean) => { 308 | //everything not markdown view 309 | const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView); 310 | this.devLog(!markdownView, checking); 311 | if (!markdownView) { 312 | if (!checking) { 313 | const leafType = this.app.workspace 314 | .getActiveViewOfType(ItemView) 315 | ?.getViewType(); 316 | let selectedText: string; 317 | let viewIn: ApplyingToView; 318 | if (leafType === "canvas") { 319 | selectedText = canvasSelectionText(this.app, this); 320 | viewIn = this.app.workspace.activeEditor 321 | ? ApplyingToView.Edit 322 | : ApplyingToView.Reading; 323 | } else { 324 | selectedText = 325 | leafType === "database-plugin" 326 | ? removeDataBasePluginRelationShip() 327 | : activeWindow.getSelection()?.toString() ?? ""; 328 | viewIn = ApplyingToView.Reading; 329 | } 330 | if (selectedText && selectedText.trim().length > 0) { 331 | const isProfile = this.getProfile(viewIn); 332 | const profile = isProfile ?? this.settings; 333 | if ( 334 | !profile.copyAsHTML && 335 | (profile.applyingTo === ApplyingToView.All || 336 | profile.applyingTo === viewIn) 337 | ) { 338 | selectedText = 339 | viewIn === ApplyingToView.Edit 340 | ? await convertEditMarkdown( 341 | selectedText, 342 | isProfile ?? this.settings.editing, 343 | this, 344 | this.app.workspace.getActiveFile()?.path 345 | ) 346 | : convertMarkdown( 347 | selectedText, 348 | isProfile ?? this.settings.reading, 349 | this 350 | ); 351 | } 352 | navigator.clipboard.writeText(selectedText); 353 | } 354 | } 355 | return true; 356 | } 357 | return false; 358 | }, 359 | }); 360 | } 361 | 362 | if ( 363 | this.settings.reading.overrideNativeCopy || 364 | this.settings.editing.overrideNativeCopy 365 | ) { 366 | this.registerEvent( 367 | this.app.workspace.on("active-leaf-change", async (leaf) => { 368 | if (!leaf) { 369 | for (const monkey of Object.values(this.activeMonkeys)) { 370 | monkey(); 371 | } 372 | this.activeMonkeys = {}; 373 | return; 374 | } 375 | //@ts-ignore 376 | this.activeMonkeys[leaf.id] = this.overrideNativeCopy(leaf); 377 | //enable clipboard event in canvas read-only 378 | if ( 379 | leaf.view instanceof ItemView && 380 | leaf.view.getViewType() === "canvas" && 381 | this.settings.reading.overrideNativeCopy 382 | ) { 383 | leaf.view.containerEl.addEventListener("copy", (event) => { 384 | this.editorCopyHandler(event); 385 | }); 386 | leaf.view.containerEl.addEventListener("cut", (event) => { 387 | this.editorCutHandler(event); 388 | }); 389 | } 390 | }) 391 | ); 392 | if (this.settings.editing.overrideNativeCopy) { 393 | //register for editor 394 | const copyExt = EditorView.domEventHandlers({ 395 | //@ts-ignore 396 | copy: this.editorCopyHandler.bind(this), 397 | }); 398 | const cutExt = EditorView.domEventHandlers({ 399 | //@ts-ignore 400 | cut: this.editorCutHandler.bind(this), 401 | }); 402 | 403 | this.registerEditorExtension(copyExt); 404 | this.registerEditorExtension(cutExt); 405 | } 406 | } 407 | //file menu 408 | this.registerEvent( 409 | this.app.workspace.on("editor-menu", (menu, editor, _view) => { 410 | menu.addItem((item) => { 411 | item.setTitle(i18next.t("commands.brute")); 412 | item.setIcon("clipboard"); 413 | item.onClick(() => { 414 | navigator.clipboard.writeText(copySelectionRange(editor, this)); 415 | }); 416 | }); 417 | }) 418 | ); 419 | //use the native copy 420 | this.addCommand({ 421 | id: "copy-brute", 422 | name: i18next.t("commands.brute"), 423 | callback: () => { 424 | const editor = this.app.workspace.activeEditor?.editor; 425 | if (editor) { 426 | navigator.clipboard.writeText(copySelectionRange(editor, this)); 427 | } else { 428 | navigator.clipboard.writeText(activeWindow.getSelection()?.toString() ?? ""); 429 | } 430 | }, 431 | }); 432 | } 433 | async onunload() { 434 | console.log(`CopyReadingInMarkdown v.${this.manifest.version} unloaded.`); 435 | for (const monkey of Object.values(this.activeMonkeys)) { 436 | const actived = await monkey.remove; 437 | if (actived) await monkey.remove(); 438 | } 439 | } 440 | async loadSettings() { 441 | const loadedData = await this.loadData(); 442 | try { 443 | this.settings = merge( 444 | DEFAULT_SETTINGS, 445 | loadedData 446 | ) as unknown as EnhancedCopySettings; 447 | } catch (_e) { 448 | console.warn( 449 | "[Enhanced copy] Error while deep merging settings, using default loading method" 450 | ); 451 | this.settings = Object.assign({}, DEFAULT_SETTINGS, loadedData); 452 | } 453 | } 454 | async saveSettings() { 455 | await this.saveData(this.settings); 456 | } 457 | devLog(...args: unknown[]) { 458 | if (!(Platform.isDesktop && this.settings.devMode)) { 459 | return; 460 | } 461 | let callFunction = new Error().stack?.split("\n")[2].trim(); 462 | callFunction = callFunction?.substring( 463 | callFunction.indexOf("at ") + 3, 464 | callFunction.lastIndexOf(" (") 465 | ); 466 | callFunction = callFunction!.replace("Object.callback", ""); 467 | callFunction = callFunction.length > 0 ? callFunction : "main"; 468 | const date = new Date().toISOString().slice(11, 23); 469 | console.log(`[${date}](${callFunction}):\n`, ...args); 470 | } 471 | } 472 | -------------------------------------------------------------------------------- /src/modal.ts: -------------------------------------------------------------------------------- 1 | import i18next from "i18next"; 2 | import { type App, Modal, Notice, Setting } from "obsidian"; 3 | 4 | import { 5 | CopySettingsView, 6 | type EnhancedCopySettings, 7 | type GlobalSettings, 8 | type ReplaceText, 9 | } from "./interface"; 10 | 11 | export class AllReplaceTextModal extends Modal { 12 | replaceText: ReplaceText[]; 13 | onSubmit: (result: ReplaceText[]) => void; 14 | 15 | constructor( 16 | app: App, 17 | replaceText: ReplaceText[], 18 | onSubmit: (result: ReplaceText[]) => void 19 | ) { 20 | super(app); 21 | this.onSubmit = onSubmit; 22 | this.replaceText = replaceText; 23 | } 24 | 25 | validateRegex(pattern: string): boolean { 26 | try { 27 | if (pattern.match(/^\/.*\/([gmiyus]+)?$/)) { 28 | const flags = pattern.replace(/^\/.*\/([gmiyus]+)?$/, "$1"); 29 | const regex = pattern.replace(/^\/(.*)\/(.*)$/, "$1"); 30 | new RegExp(regex, flags.length > 0 ? flags : undefined); 31 | } 32 | return true; //valid or string 33 | } catch (_e) { 34 | return false; 35 | } 36 | } 37 | 38 | onOpen() { 39 | const { contentEl } = this; 40 | contentEl.empty(); 41 | contentEl.addClass("enhanced-copy"); 42 | new Setting(contentEl) 43 | .setName(i18next.t("modal.replaceText.title")) 44 | .setClass("modal-title") 45 | .addButton((button) => 46 | button 47 | .setIcon("plus") 48 | .setTooltip(i18next.t("common.add")) 49 | .onClick(() => { 50 | this.replaceText.unshift({ 51 | pattern: "", 52 | replacement: "", 53 | }); 54 | this.onOpen(); 55 | }) 56 | ); 57 | 58 | for (const replacer of this.replaceText) { 59 | new Setting(contentEl) 60 | .addText((text) => 61 | text 62 | .setPlaceholder(i18next.t("common.pattern")) 63 | .setValue(replacer.pattern) 64 | .onChange(async (value) => { 65 | replacer.pattern = value; 66 | text.inputEl.setAttribute("data-pattern", value); 67 | }) 68 | .inputEl.classList.add("full-width") 69 | ) 70 | .addText((text) => 71 | text 72 | .setPlaceholder(i18next.t("common.replacement")) 73 | .setValue(replacer.replacement) 74 | .onChange(async (value) => { 75 | replacer.replacement = value; 76 | text.inputEl.setAttribute("data-replacement", value); 77 | }) 78 | .inputEl.classList.add("full-width") 79 | ) 80 | /** Allow to change order with two arrow up / down **/ 81 | .addExtraButton((button) => 82 | button 83 | .setIcon("chevron-up") 84 | .setTooltip(i18next.t("modal.replaceText.up")) 85 | .onClick(() => { 86 | const index = this.replaceText.indexOf(replacer); 87 | if (index <= 0) { 88 | return; 89 | } 90 | this.replaceText.splice(index, 1); 91 | this.replaceText.splice(index - 1, 0, replacer); 92 | this.onOpen(); 93 | }) 94 | ) 95 | .addExtraButton((button) => 96 | button 97 | .setIcon("chevron-down") 98 | .setTooltip(i18next.t("modal.replaceText.down")) 99 | .onClick(() => { 100 | const index = this.replaceText.indexOf(replacer); 101 | if (index >= this.replaceText.length - 1) { 102 | return; 103 | } 104 | this.replaceText.splice(index, 1); 105 | this.replaceText.splice(index + 1, 0, replacer); 106 | this.onOpen(); 107 | }) 108 | ) 109 | .addExtraButton((button) => 110 | button 111 | .setIcon("trash") 112 | .setTooltip(i18next.t("common.delete")) 113 | .onClick(() => { 114 | const index = this.replaceText.indexOf(replacer); 115 | if (index > -1) { 116 | this.replaceText.splice(index, 1); 117 | this.onOpen(); 118 | } 119 | }) 120 | ) 121 | .infoEl.classList.add("hide-info"); 122 | } 123 | new Setting(contentEl) 124 | .addButton((button) => 125 | button 126 | .setButtonText(i18next.t("common.save")) 127 | .setCta() 128 | .onClick(async () => { 129 | for (const replacer of this.replaceText) { 130 | if (!this.validateRegex(replacer.pattern)) { 131 | new Notice(`Invalid regex for ${replacer.pattern}`); 132 | //search the faulty input 133 | const input = contentEl.querySelector( 134 | `[data-pattern="${replacer.pattern}"]` 135 | ); 136 | if (input) input.addClass("error"); 137 | return; 138 | } 139 | } 140 | this.onSubmit(this.replaceText); 141 | this.close(); 142 | }) 143 | ) 144 | .addButton((button) => 145 | button 146 | .setButtonText(i18next.t("common.cancel")) 147 | .setWarning() 148 | .onClick(async () => { 149 | this.close(); 150 | }) 151 | ); 152 | } 153 | onClose() { 154 | const { contentEl } = this; 155 | contentEl.empty(); 156 | } 157 | } 158 | 159 | export class EnhancedCopyViewModal extends Modal { 160 | settings: EnhancedCopySettings; 161 | from: CopySettingsView; 162 | to: CopySettingsView; 163 | onSubmit: (result: EnhancedCopySettings) => void; 164 | 165 | constructor( 166 | app: App, 167 | settings: EnhancedCopySettings, 168 | onSubmit: (result: EnhancedCopySettings) => void 169 | ) { 170 | super(app); 171 | this.onSubmit = onSubmit; 172 | this.settings = settings; 173 | this.from = CopySettingsView.Reading; 174 | this.to = CopySettingsView.Editing; 175 | } 176 | 177 | onOpen() { 178 | const { contentEl } = this; 179 | contentEl.empty(); 180 | contentEl.addClass("enhanced-copy"); 181 | 182 | const profileOptions: Record = {}; 183 | for (const profile of this.settings.profiles) { 184 | if (!profile.name) continue; 185 | profileOptions[profile.name] = profile.name; 186 | } 187 | 188 | new Setting(contentEl) 189 | .setName(i18next.t("common.from")) 190 | .addDropdown((dropdown) => 191 | dropdown 192 | .addOptions({ 193 | reading: i18next.t("modal.copyView.reading"), 194 | editing: i18next.t("modal.copyView.editing"), 195 | ...profileOptions, 196 | }) 197 | .setValue(this.from) 198 | .onChange(async (value) => { 199 | this.from = value as CopySettingsView; 200 | }) 201 | .selectEl.classList.add("full-width") 202 | ) 203 | .infoEl.classList.add("min-width"); 204 | new Setting(contentEl) 205 | .setName(i18next.t("common.to")) 206 | .addDropdown((dropdown) => 207 | dropdown 208 | .addOptions({ 209 | reading: i18next.t("modal.copyView.reading"), 210 | editing: i18next.t("modal.copyView.editing"), 211 | ...profileOptions, 212 | }) 213 | .setValue(this.to) 214 | .onChange(async (value) => { 215 | this.to = value as CopySettingsView; 216 | }) 217 | .selectEl.classList.add("full-width") 218 | ) 219 | .infoEl.classList.add("min-width"); 220 | 221 | new Setting(contentEl) 222 | .addButton((button) => 223 | button 224 | .setButtonText(i18next.t("modal.copyView.copy")) 225 | .setCta() 226 | .onClick(async () => { 227 | if (this.from === this.to) { 228 | return; 229 | } 230 | let override: GlobalSettings | undefined; 231 | switch (this.from) { 232 | case CopySettingsView.Reading: 233 | override = this.settings.reading; 234 | break; 235 | case CopySettingsView.Editing: 236 | override = this.settings.editing; 237 | break; 238 | default: { 239 | const profile = this.settings.profiles.find( 240 | (profile) => profile.name === this.from 241 | ); 242 | if (profile) { 243 | override = profile; 244 | } 245 | } 246 | } 247 | 248 | if (!override) return; 249 | switch (this.to) { 250 | case CopySettingsView.Reading: 251 | this.settings.reading = override; 252 | break; 253 | case CopySettingsView.Editing: 254 | this.settings.editing = override; 255 | break; 256 | default: { 257 | const profileIndex = this.settings.profiles.findIndex( 258 | (profile) => profile.name === this.to 259 | ); 260 | if (profileIndex) { 261 | this.settings.profiles[profileIndex] = override; 262 | } 263 | } 264 | } 265 | this.onSubmit(this.settings); 266 | this.close(); 267 | }) 268 | ) 269 | .addButton((button) => 270 | button 271 | .setButtonText(i18next.t("common.cancel")) 272 | .setWarning() 273 | .onClick(async () => { 274 | this.close(); 275 | }) 276 | ); 277 | } 278 | 279 | onClose() { 280 | const { contentEl } = this; 281 | contentEl.empty(); 282 | } 283 | } 284 | 285 | export class NameProfile extends Modal { 286 | name: string = ""; 287 | onSubmit: (result: string) => void; 288 | constructor(app: App, onSubmit: (result: string) => void) { 289 | super(app); 290 | this.onSubmit = onSubmit; 291 | } 292 | onOpen() { 293 | const { contentEl } = this; 294 | contentEl.empty(); 295 | contentEl.addClass("enhanced-copy"); 296 | new Setting(contentEl) 297 | .setName(i18next.t("common.profile")) 298 | .setClass("modal-title") 299 | .addText((text) => 300 | text 301 | .setPlaceholder(i18next.t("common.profile")) 302 | .setValue(this.name) 303 | .onChange(async (value) => { 304 | this.name = value; 305 | }) 306 | .inputEl.classList.add("full-width") 307 | ); 308 | 309 | new Setting(contentEl) 310 | .addButton((button) => 311 | button 312 | .setButtonText(i18next.t("common.save")) 313 | .setCta() 314 | .onClick(async () => { 315 | this.onSubmit(this.name); 316 | this.close(); 317 | }) 318 | ) 319 | .addButton((button) => 320 | button 321 | .setButtonText(i18next.t("common.cancel")) 322 | .setWarning() 323 | .onClick(async () => { 324 | this.close(); 325 | }) 326 | ); 327 | } 328 | onClose() { 329 | const { contentEl } = this; 330 | contentEl.empty(); 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /src/settings.ts: -------------------------------------------------------------------------------- 1 | import i18next from "i18next"; 2 | import { 3 | type App, 4 | PluginSettingTab, 5 | sanitizeHTMLToDom, 6 | setIcon, 7 | Setting, 8 | } from "obsidian"; 9 | 10 | import { 11 | ApplyingToView, 12 | DEFAULT_DATAVIEW_SETTINGS_DISABLED, 13 | DEFAULT_DATAVIEW_SETTINGS_ENABLED, 14 | type CalloutKeepType, 15 | type ConversionOfFootnotes, 16 | type ConversionOfLinks, 17 | type EnhancedCopySettings, 18 | type GlobalSettings, 19 | } from "./interface"; 20 | import type EnhancedCopy from "./main"; 21 | import { AllReplaceTextModal, EnhancedCopyViewModal, NameProfile } from "./modal"; 22 | 23 | interface Tab { 24 | name: string; 25 | id: string; 26 | icon: string; 27 | } 28 | 29 | export class EnhancedCopySettingTab extends PluginSettingTab { 30 | plugin: EnhancedCopy; 31 | settingsPage!: HTMLElement; 32 | settings: EnhancedCopySettings; 33 | 34 | reading: Tab = { 35 | name: i18next.t("reading.title"), 36 | id: "reading", 37 | icon: "book-open", 38 | }; 39 | 40 | edit: Tab = { 41 | name: i18next.t("edit.title"), 42 | id: "edit", 43 | icon: "pencil", 44 | }; 45 | 46 | tab: Tab[] = [ 47 | { 48 | name: i18next.t("global.title"), 49 | id: "global", 50 | icon: "globe", 51 | }, 52 | ]; 53 | 54 | createReadingSettings(settings: GlobalSettings, profile?: boolean, noRegex?: boolean) { 55 | new Setting(this.settingsPage).setName(i18next.t("reading.desc")).setHeading(); 56 | new Setting(this.settingsPage) 57 | .setName(i18next.t("copyAsHTML")) 58 | .addToggle((toggle) => { 59 | toggle.setValue(settings.copyAsHTML ?? false).onChange(async (value) => { 60 | settings.copyAsHTML = value; 61 | await this.plugin.saveSettings(); 62 | this.renderSettingsPage(settings.name ?? "reading"); 63 | }); 64 | }); 65 | if (!settings.copyAsHTML) { 66 | new Setting(this.settingsPage) 67 | .setName(i18next.t("links")) 68 | .setHeading() 69 | .setClass("h3"); 70 | this.links(settings); 71 | this.footnotes(settings); 72 | 73 | new Setting(this.settingsPage) 74 | .setName(i18next.t("unconventionalMarkdown.title")) 75 | .setHeading() 76 | .setClass("h3") 77 | .setDesc(i18next.t("unconventionalMarkdown.desc")); 78 | this.highlight(settings); 79 | } 80 | 81 | this.calloutTitle(settings); 82 | 83 | if (!settings.copyAsHTML) { 84 | new Setting(this.settingsPage) 85 | .setName(i18next.t("other")) 86 | .setHeading() 87 | .setClass("h3"); 88 | this.hardBreak(settings); 89 | new Setting(this.settingsPage) 90 | .setName(i18next.t("spaceSize.title")) 91 | .setDesc(i18next.t("spaceSize.desc")) 92 | .addText((text) => { 93 | text 94 | .setPlaceholder("-1") 95 | .setValue(String(settings.spaceReadingSize ?? -1)) 96 | .onChange(async (value) => { 97 | settings.spaceReadingSize = Number(value); 98 | await this.plugin.saveSettings(); 99 | }); 100 | }); 101 | } 102 | if (!profile) this.overrideSetting(settings); 103 | if (!noRegex) 104 | this.regexReplacementButton(settings); 105 | } 106 | 107 | createEditSettings(settings: GlobalSettings, profile?: boolean, noRegex?: boolean) { 108 | new Setting(this.settingsPage).setName(i18next.t("edit.desc")).setHeading(); 109 | 110 | if (this.app.plugins.enabledPlugins.has("dataview")) { 111 | if (!settings.convertDataview) 112 | settings.convertDataview = structuredClone(DEFAULT_DATAVIEW_SETTINGS_DISABLED); 113 | //@ts-ignore 114 | else if (settings.convertDataview === true) 115 | settings.convertDataview = structuredClone(DEFAULT_DATAVIEW_SETTINGS_ENABLED); 116 | 117 | new Setting(this.settingsPage) 118 | .setName(i18next.t("convertDataview.global.title")) 119 | .setDesc(i18next.t("convertDataview.global.desc")) 120 | .addToggle((toggle) => { 121 | toggle 122 | .setValue(settings.convertDataview?.enable ?? false) 123 | .onChange(async (value) => { 124 | if (value) 125 | settings.convertDataview = structuredClone( 126 | DEFAULT_DATAVIEW_SETTINGS_ENABLED 127 | ); 128 | else 129 | settings.convertDataview = structuredClone( 130 | DEFAULT_DATAVIEW_SETTINGS_DISABLED 131 | ); 132 | await this.plugin.saveSettings(); 133 | this.renderSettingsPage(settings.name ?? "edit"); 134 | }); 135 | }); 136 | 137 | if (settings.convertDataview?.enable) { 138 | new Setting(this.settingsPage) 139 | .setHeading() 140 | .setClass("dataview") 141 | .setName(i18next.t("convertDataview.dql.title")); 142 | new Setting(this.settingsPage) 143 | .setName(i18next.t("convertDataview.block")) 144 | .setClass("dataview") 145 | .addToggle((toggle) => { 146 | toggle 147 | .setValue(settings.convertDataview?.djs.block ?? false) 148 | .onChange(async (value) => { 149 | settings.convertDataview!.djs.block = value; 150 | await this.plugin.saveSettings(); 151 | }); 152 | }); 153 | new Setting(this.settingsPage) 154 | .setName(i18next.t("convertDataview.inline")) 155 | .setClass("dataview") 156 | .addToggle((toggle) => { 157 | toggle 158 | .setValue(settings.convertDataview?.djs.inline ?? false) 159 | .onChange(async (value) => { 160 | settings.convertDataview!.djs.inline = value; 161 | await this.plugin.saveSettings(); 162 | this.renderSettingsPage(settings.name ?? "edit"); 163 | }); 164 | }); 165 | new Setting(this.settingsPage) 166 | .setHeading() 167 | .setClass("dataview") 168 | .setName(i18next.t("convertDataview.djs.title")); 169 | new Setting(this.settingsPage) 170 | .setName(i18next.t("convertDataview.block")) 171 | .setClass("dataview") 172 | .addToggle((toggle) => { 173 | toggle 174 | .setValue(settings.convertDataview?.dql.block ?? false) 175 | .onChange(async (value) => { 176 | settings.convertDataview!.dql.block = value; 177 | await this.plugin.saveSettings(); 178 | }); 179 | }); 180 | 181 | new Setting(this.settingsPage) 182 | .setName(i18next.t("convertDataview.inline")) 183 | .setClass("dataview") 184 | .addToggle((toggle) => { 185 | toggle 186 | .setValue(settings.convertDataview?.dql.inline ?? false) 187 | .onChange(async (value) => { 188 | settings.convertDataview!.dql.inline = value; 189 | await this.plugin.saveSettings(); 190 | this.renderSettingsPage(settings.name ?? "edit"); 191 | }); 192 | }); 193 | } 194 | } 195 | 196 | new Setting(this.settingsPage) 197 | .setName(i18next.t("wikiToMarkdown.title")) 198 | .setDesc(i18next.t("wikiToMarkdown.desc")) 199 | .addToggle((toggle) => { 200 | toggle.setValue(settings.wikiToMarkdown ?? false).onChange(async (value) => { 201 | settings.wikiToMarkdown = value; 202 | await this.plugin.saveSettings(); 203 | this.renderSettingsPage(settings.name ?? "edit"); 204 | }); 205 | }); 206 | 207 | new Setting(this.settingsPage) 208 | .setName(i18next.t("tabToSpace")) 209 | .addToggle((toggle) => { 210 | toggle.setValue(settings.tabToSpace ?? false).onChange(async (value) => { 211 | settings.tabToSpace = value; 212 | await this.plugin.saveSettings(); 213 | this.renderSettingsPage(settings.name ?? "edit"); 214 | }); 215 | }); 216 | 217 | if (settings.tabToSpace) { 218 | new Setting(this.settingsPage) 219 | .setName(i18next.t("tabSpaceSize")) 220 | .addText((text) => { 221 | text 222 | .setValue(settings.tabSpaceSize ? settings.tabSpaceSize.toString() : "4") 223 | .onChange(async (value) => { 224 | settings.tabSpaceSize = parseInt(value); 225 | text.inputEl.toggleClass( 226 | "error", 227 | isNaN(settings.tabSpaceSize) || settings.tabSpaceSize < 0 228 | ); 229 | if (isNaN(settings.tabSpaceSize) || settings.tabSpaceSize < 0) 230 | settings.tabSpaceSize = 4; 231 | await this.plugin.saveSettings(); 232 | }); 233 | }); 234 | } 235 | new Setting(this.settingsPage) 236 | .setName(i18next.t("links")) 237 | .setHeading() 238 | .setClass("h3"); 239 | if (settings.wikiToMarkdown) { 240 | this.links(settings); 241 | } 242 | this.footnotes(settings); 243 | new Setting(this.settingsPage) 244 | .setName(i18next.t("unconventionalMarkdown.title")) 245 | .setHeading() 246 | .setClass("h3") 247 | .setDesc(i18next.t("unconventionalMarkdown.desc")); 248 | 249 | this.calloutTitle(settings); 250 | this.highlight(settings); 251 | 252 | new Setting(this.settingsPage) 253 | .setName(i18next.t("other")) 254 | .setHeading() 255 | .setClass("h3"); 256 | 257 | this.hardBreak(settings); 258 | if (!profile) this.overrideSetting(settings); 259 | if (!noRegex) 260 | this.regexReplacementButton(settings); 261 | } 262 | 263 | constructor(app: App, plugin: EnhancedCopy) { 264 | super(app, plugin); 265 | this.plugin = plugin; 266 | this.settings = plugin.settings; 267 | } 268 | 269 | display(): void { 270 | const { containerEl } = this; 271 | containerEl.empty(); 272 | this.containerEl.addClasses(["enhanced-copy", "setting-tab"]); 273 | const tabBar = containerEl.createEl("nav", { cls: "settings-tab-bar" }); 274 | //remove Tab based on applying 275 | if (this.settings.applyingTo === ApplyingToView.Reading) { 276 | this.tab.push(this.reading); 277 | this.tab.remove(this.edit); 278 | } else if (this.settings.applyingTo === ApplyingToView.Edit) { 279 | this.tab.push(this.edit); 280 | this.tab.remove(this.reading); 281 | } else { 282 | this.tab.push(this.edit); 283 | this.tab.push(this.reading); 284 | } 285 | 286 | for (const profile of this.settings.profiles) { 287 | //remove all previous profile 288 | this.tab = this.tab.filter((tab) => tab.id !== profile.name); 289 | this.tab.push({ 290 | name: profile.name ?? "profile", 291 | id: profile.name ?? "profile", 292 | icon: "layers-2", 293 | }); 294 | } 295 | this.tab = [...new Set(this.tab)]; 296 | 297 | for (const tabInfo of this.tab) { 298 | const tabEl = tabBar.createEl("div", { cls: "settings-tab" }); 299 | const tabIcon = tabEl.createEl("div", { cls: "settings-tab-icon" }); 300 | setIcon(tabIcon, tabInfo.icon); 301 | if (tabInfo.id === "global") tabEl.addClasses(["settings-tab-active"]); 302 | tabEl.createEl("div", { cls: "tabName", text: tabInfo.name }); 303 | tabEl.addEventListener("click", () => { 304 | // @ts-ignore 305 | for (const tabEl of tabBar.children) tabEl.removeClasses(["settings-tab-active"]); 306 | 307 | tabEl.addClasses(["settings-tab-active"]); 308 | this.renderSettingsPage(tabInfo.id); 309 | }); 310 | } 311 | this.settingsPage = containerEl.createEl("div", { cls: "settings-tab-page" }); 312 | this.renderSettingsPage("global"); 313 | } 314 | 315 | renderSettingsPage(tab: string) { 316 | this.settingsPage.empty(); 317 | switch (tab) { 318 | case "global": 319 | this.renderGlobal(); 320 | break; 321 | case "reading": 322 | this.renderReading(); 323 | break; 324 | case "edit": 325 | this.renderEdit(); 326 | break; 327 | default: 328 | this.renderProfile(tab); 329 | break; 330 | } 331 | } 332 | 333 | renderProfile(tab: string) { 334 | const profile = this.settings.profiles.find((profile) => profile.name === tab); 335 | if (!profile) return; 336 | this.settingsPage.empty(); 337 | new Setting(this.settingsPage) 338 | .addButton((button) => { 339 | button 340 | .setButtonText(i18next.t("profile.delete")) 341 | .onClick(async () => { 342 | const index = this.settings.profiles.findIndex( 343 | (profile) => profile.name === tab 344 | ); 345 | this.settings.profiles.splice(index, 1); 346 | //remove from tabs 347 | this.tab = this.tab.filter((tab) => tab.id !== profile.name); 348 | await this.plugin.saveSettings(); 349 | this.display(); 350 | this.renderGlobal(); 351 | }) 352 | .buttonEl.classList.add("full-width"); 353 | }) 354 | .infoEl.classList.add("hide-info"); 355 | profile.applyingTo = profile.applyingTo ?? ApplyingToView.All; 356 | 357 | new Setting(this.settingsPage).setName(profile.name ?? "profile").setHeading(); 358 | 359 | new Setting(this.settingsPage) 360 | .setName(i18next.t("view.title")) 361 | .setDesc(i18next.t("view.desc")) 362 | .addDropdown((dropdown) => { 363 | dropdown 364 | .addOption("all", i18next.t("view.all")) 365 | .addOption("reading", i18next.t("view.reading")) 366 | .addOption("edit", i18next.t("view.edit")) 367 | .setValue(profile.applyingTo ?? ApplyingToView.All) 368 | .onChange(async (value) => { 369 | profile.applyingTo = value as ApplyingToView; 370 | await this.plugin.saveSettings(); 371 | this.renderSettingsPage(tab); 372 | }); 373 | }); 374 | 375 | new Setting(this.settingsPage) 376 | .setName(i18next.t("auto.title")) 377 | .setDesc(sanitizeHTMLToDom(i18next.t("auto.desc"))) 378 | .addExtraButton((button) => 379 | button 380 | .setIcon("plus") 381 | .setTooltip("Add new rule") 382 | .onClick(async () => { 383 | profile.autoRules = profile.autoRules ?? []; 384 | profile.autoRules.unshift({ 385 | type: "path", 386 | value: "", 387 | }); 388 | await this.plugin.saveSettings(); 389 | this.renderSettingsPage(tab); 390 | }) 391 | ); 392 | for (const rules of profile.autoRules ?? []) { 393 | new Setting(this.settingsPage) 394 | .addDropdown((dp) => { 395 | dp.addOption("not", i18next.t("auto.not")) 396 | .addOption("equal", i18next.t("auto.EQUAL")) 397 | .setValue(!rules.not ? "equal" : "not") 398 | .onChange(async (value) => { 399 | rules.not = value === "not"; 400 | await this.plugin.saveSettings(); 401 | }); 402 | }) 403 | .setClass("no-display") 404 | .setClass("full-width") 405 | .addDropdown((dropdown) => { 406 | dropdown 407 | .addOption("path", i18next.t("auto.path")) 408 | .addOption("tag", i18next.t("auto.tag")) 409 | .addOption("frontmatter", i18next.t("auto.frontmatter")) 410 | .setValue(rules.type) 411 | .onChange(async (value) => { 412 | rules.type = value as "path" | "tag" | "frontmatter"; 413 | await this.plugin.saveSettings(); 414 | }); 415 | }) 416 | .addText((text) => { 417 | text 418 | .setValue(rules.value) 419 | .setPlaceholder(i18next.t("auto.placeholder")) 420 | .onChange(async (value) => { 421 | rules.value = value; 422 | await this.plugin.saveSettings(); 423 | }); 424 | }) 425 | .addExtraButton((button) => { 426 | button.setIcon("trash").onClick(async () => { 427 | const index = profile.autoRules?.findIndex((rule) => rule === rules); 428 | if (index === undefined) return; 429 | profile.autoRules?.splice(index, 1); 430 | await this.plugin.saveSettings(); 431 | this.renderSettingsPage(tab); 432 | }); 433 | }) 434 | .addExtraButton((button) => { 435 | button.setIcon("chevron-up").onClick(async () => { 436 | const index = profile.autoRules?.findIndex((rule) => rule === rules); 437 | if (index === undefined || index <= 0) return; 438 | profile.autoRules?.splice(index, 1); 439 | profile.autoRules?.splice(index - 1, 0, rules); 440 | await this.plugin.saveSettings(); 441 | this.renderSettingsPage(tab); 442 | }); 443 | }) 444 | .addExtraButton((button) => { 445 | button.setIcon("chevron-down").onClick(async () => { 446 | const index = profile.autoRules?.findIndex((rule) => rule === rules); 447 | if ( 448 | index === undefined || 449 | (profile.autoRules && index >= profile.autoRules.length - 1) 450 | ) 451 | return; 452 | profile.autoRules?.splice(index, 1); 453 | profile.autoRules?.splice(index + 1, 0, rules); 454 | await this.plugin.saveSettings(); 455 | this.renderSettingsPage(tab); 456 | }); 457 | }); 458 | } 459 | if (profile.applyingTo === ApplyingToView.All) { 460 | this.createReadingSettings(profile, true, true); 461 | this.createEditSettings(profile, true, true); 462 | this.regexReplacementButton(profile); 463 | } else if (profile.applyingTo === ApplyingToView.Reading) { 464 | this.createReadingSettings(profile, true); 465 | } else if (profile.applyingTo === ApplyingToView.Edit) { 466 | this.createEditSettings(profile, true); 467 | } 468 | } 469 | 470 | renderGlobal() { 471 | this.settingsPage.empty(); 472 | this.settingsPage.addClasses(["global"]); 473 | new Setting(this.settingsPage).addButton((button) => { 474 | button 475 | .setButtonText(i18next.t("profile.add.title")) 476 | .setTooltip(i18next.t("profile.add.desc")) 477 | .onClick(async () => { 478 | new NameProfile(this.app, (result) => { 479 | this.settings.profiles.push({ 480 | name: result, 481 | ...this.settings.editing, 482 | }); 483 | this.plugin.saveSettings(); 484 | this.display(); 485 | }).open(); 486 | }); 487 | }); 488 | new Setting(this.settingsPage).setName(i18next.t("global.title")).setHeading(); 489 | new Setting(this.settingsPage) 490 | .setName(i18next.t("view.title")) 491 | .setDesc(i18next.t("view.desc")) 492 | .addDropdown((dropdown) => { 493 | dropdown 494 | .addOption("all", i18next.t("view.all")) 495 | .addOption("reading", i18next.t("view.reading")) 496 | .addOption("edit", i18next.t("view.edit")) 497 | .setValue(this.settings.applyingTo) 498 | .onChange(async (value) => { 499 | this.settings.applyingTo = value as ApplyingToView; 500 | await this.plugin.saveSettings(); 501 | if (this.settings.applyingTo === ApplyingToView.Edit) { 502 | this.settings.copyAsHTML = false; 503 | await this.plugin.saveSettings(); 504 | } 505 | this.display(); 506 | }); 507 | }); 508 | 509 | new Setting(this.settingsPage) 510 | .setName(i18next.t("hotkey.title")) 511 | .setDesc(i18next.t("hotkey.desc")) 512 | .addToggle((toggle) => { 513 | toggle.setValue(this.settings.separateHotkey).onChange(async (value) => { 514 | this.settings.separateHotkey = value; 515 | await this.plugin.saveSettings(); 516 | this.renderSettingsPage("global"); 517 | }); 518 | }); 519 | 520 | new Setting(this.settingsPage) 521 | .addButton((button) => { 522 | button 523 | .setButtonText(i18next.t("global.copy")) 524 | .onClick(async () => { 525 | new EnhancedCopyViewModal(this.app, this.settings, (result) => { 526 | this.settings = result; 527 | this.plugin.saveSettings(); 528 | this.display(); 529 | }).open(); 530 | }) 531 | .buttonEl.classList.add("full-width"); 532 | }) 533 | .infoEl.classList.add("hide-info"); 534 | 535 | new Setting(this.settingsPage) 536 | .setName(i18next.t("debug.title")) 537 | .setDesc(i18next.t("debug.desc")) 538 | .addToggle((toggle) => { 539 | toggle.setValue(this.settings.devMode).onChange(async (value) => { 540 | this.settings.devMode = value; 541 | await this.plugin.saveSettings(); 542 | }); 543 | }); 544 | } 545 | 546 | renderReading() { 547 | this.settingsPage.empty(); 548 | this.settingsPage.addClasses(["reading"]); 549 | this.createReadingSettings(this.settings.reading); 550 | } 551 | 552 | renderEdit() { 553 | this.settingsPage.empty(); 554 | this.settingsPage.addClasses(["edit"]); 555 | this.createEditSettings(this.settings.editing); 556 | } 557 | 558 | highlight(settings: GlobalSettings) { 559 | return new Setting(this.settingsPage) 560 | .setName(i18next.t("highlight.title")) 561 | .setDesc(i18next.t("highlight.desc")) 562 | .addToggle((toggle) => { 563 | toggle.setValue(settings.highlight).onChange(async (value) => { 564 | settings.highlight = value; 565 | await this.plugin.saveSettings(); 566 | }); 567 | }); 568 | } 569 | 570 | overrideSetting(settings: GlobalSettings) { 571 | return new Setting(this.settingsPage) 572 | .setName(i18next.t("overrideCopy.title")) 573 | .setDesc(i18next.t("overrideCopy.desc")) 574 | .addToggle((toggle) => { 575 | toggle.setValue(settings.overrideNativeCopy).onChange(async (value) => { 576 | settings.overrideNativeCopy = value; 577 | await this.plugin.saveSettings(); 578 | }); 579 | }); 580 | } 581 | 582 | calloutTitle(settings: GlobalSettings) { 583 | return new Setting(this.settingsPage) 584 | .setName(i18next.t("callout.title")) 585 | .setDesc(i18next.t("callout.desc")) 586 | .setClass("enhanced-copy-dp") 587 | .addDropdown((dropdown) => { 588 | dropdown 589 | .addOption("obsidian", i18next.t("callout.obsidian")) 590 | .addOption("strong", i18next.t("callout.strong")) 591 | .addOption("remove", i18next.t("callout.remove")) 592 | .addOption("removeKeepTitle", i18next.t("callout.removeKeepTitle")) 593 | .setValue(settings.callout) 594 | .onChange(async (value) => { 595 | settings.callout = value as CalloutKeepType; 596 | await this.plugin.saveSettings(); 597 | }); 598 | }); 599 | } 600 | 601 | footnotes(settings: GlobalSettings) { 602 | return new Setting(this.settingsPage) 603 | .setName(i18next.t("removeFootnotesLinks.title")) 604 | .setDesc(i18next.t("removeFootnotesLinks.desc")) 605 | .setClass("enhanced-copy-dp") 606 | .addDropdown((dropdown) => { 607 | dropdown 608 | .addOption("keep", i18next.t("removeFootnotesLinks.keep")) 609 | .addOption("remove", i18next.t("removeFootnotesLinks.remove")) 610 | .addOption("format", i18next.t("removeFootnotesLinks.format")) 611 | .setValue(settings.footnotes) 612 | .onChange(async (value) => { 613 | settings.footnotes = value as ConversionOfFootnotes; 614 | await this.plugin.saveSettings(); 615 | }); 616 | }); 617 | } 618 | 619 | links(settings: GlobalSettings) { 620 | return new Setting(this.settingsPage) 621 | .setName(i18next.t("copyLinksAsText.title")) 622 | .setDesc(i18next.t("copyLinksAsText.desc")) 623 | .setClass("enhanced-copy-dp") 624 | .addDropdown((dropdown) => { 625 | dropdown 626 | .addOption("keep", i18next.t("copyLinksAsText.keep")) 627 | .addOption("remove", i18next.t("copyLinksAsText.remove")) 628 | .addOption("external", i18next.t("copyLinksAsText.external")) 629 | .setValue(settings.links) 630 | .onChange(async (value) => { 631 | settings.links = value as ConversionOfLinks; 632 | await this.plugin.saveSettings(); 633 | }); 634 | }); 635 | } 636 | 637 | hardBreak(settings: GlobalSettings) { 638 | return new Setting(this.settingsPage) 639 | .setName(i18next.t("hardBreaks.title")) 640 | .setDesc(i18next.t("hardBreaks.desc")) 641 | .addToggle((toggle) => { 642 | toggle.setValue(settings.hardBreak).onChange(async (value) => { 643 | settings.hardBreak = value; 644 | await this.plugin.saveSettings(); 645 | }); 646 | }); 647 | } 648 | 649 | regexReplacementButton(settings: GlobalSettings) { 650 | return new Setting(this.settingsPage) 651 | .addButton((button) => { 652 | button 653 | .setButtonText(i18next.t("openTextReplacer")) 654 | .onClick(async () => { 655 | if (!settings.replaceText) settings.replaceText = []; 656 | new AllReplaceTextModal( 657 | this.app, 658 | structuredClone(settings.replaceText), 659 | async (result) => { 660 | settings.replaceText = result; 661 | } 662 | ).open(); 663 | await this.plugin.saveSettings(); 664 | }) 665 | .buttonEl.classList.add("full-width"); 666 | }) 667 | .infoEl.classList.add("hide-info"); 668 | } 669 | } 670 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | .setting-item.enhanced-copy-dp select.dropdown { 2 | width: 100%; 3 | height: auto; 4 | white-space: break-spaces; 5 | padding: 1em; 6 | } 7 | 8 | .enhanced-copy.setting-tab .settings-tab-bar { 9 | display: flex; 10 | flex-direction: row; 11 | } 12 | 13 | .enhanced-copy.setting-tab 14 | .setting-item.setting-item-heading 15 | .setting-item-name { 16 | font-size: var(--h1-size); 17 | } 18 | 19 | .enhanced-copy.setting-tab 20 | .setting-item.setting-item-heading.h3 21 | .setting-item-name { 22 | font-size: var(--h3-size); 23 | } 24 | 25 | .enhanced-copy.setting-tab .settings-tab { 26 | display: flex; 27 | flex-direction: row; 28 | align-items: center; 29 | gap: var(--size-4-2); 30 | padding: 10px; 31 | border: 1px solid var(--background-modifier-border); 32 | } 33 | 34 | .enhanced-copy.setting-tab .settings-tab-active { 35 | background-color: var(--color-accent); 36 | color: var(--text-on-accent); 37 | } 38 | 39 | .enhanced-copy.setting-tab .tabName { 40 | font-weight: bold; 41 | } 42 | 43 | .enhanced-copy.setting-tab .settings-tab-icon { 44 | display: flex; 45 | } 46 | 47 | @media screen and (max-width: 600px) { 48 | .enhanced-copy.setting-tab .settings-tab-bar, 49 | .enhanced-copy.setting-tab .setting-item > .setting-item-control { 50 | flex-direction: column; 51 | width: 100%; 52 | } 53 | 54 | .enhanced-copy.setting-tab .settings-tab { 55 | border-bottom: 1px solid var(--background-modifier-border) !important; 56 | border-radius: 5px !important; 57 | margin-bottom: 5px; 58 | } 59 | 60 | .enhanced-copy.setting-tab .settings-tab-bar { 61 | border-bottom: transparent !important; 62 | } 63 | } 64 | 65 | .enhanced-copy.setting-tab .settings-tab { 66 | padding: 10px; 67 | border: 1px solid var(--background-modifier-border); 68 | border-radius: 5px 5px 0 0; 69 | } 70 | .enhanced-copy.setting-tab .settings-tab:hover { 71 | background-color: var(--background-modifier-hover); 72 | } 73 | 74 | .enhanced-copy.setting-tab .settings-tab-active { 75 | background-color: var(--color-accent); 76 | color: var(--text-on-accent); 77 | border: 0; 78 | border-bottom-right-radius: 0; 79 | border-bottom-left-radius: 0; 80 | } 81 | .enhanced-copy.setting-tab .settings-tab-name { 82 | font-weight: bold; 83 | text-align: center; 84 | } 85 | .enhanced-copy.setting-tab .settings-tab-icon { 86 | text-align: center; 87 | } 88 | .enhanced-copy.setting-tab .settings-tab-page > .setting-item:first-child { 89 | margin-top: 15px; 90 | } 91 | 92 | .enhanced-copy.setting-tab nav.settings-tab-bar { 93 | border-bottom: 1px solid var(--background-modifier-border); 94 | } 95 | 96 | .enhanced-copy.setting-tab .settings-tab { 97 | border-bottom: transparent; 98 | } 99 | 100 | .enhanced-copy > .text-area .setting-item-info { 101 | display: none; 102 | } 103 | 104 | .modal-content.enhanced-copy { 105 | padding-top: 1em; 106 | } 107 | 108 | .modal-content.enhanced-copy .setting-item { 109 | border-top: 0; 110 | } 111 | 112 | .modal-content.enhanced-copy .modal-title { 113 | margin-bottom: 0; 114 | padding-bottom: 0; 115 | } 116 | 117 | .enhanced-copy.setting-tab input.error { 118 | border-color: var(--text-error); 119 | } 120 | 121 | .enhanced-copy .full-width input { 122 | width: 100%; 123 | } 124 | .enhanced-copy .full-width { 125 | width: 100%; 126 | } 127 | 128 | .enhanced-copy .min-width { 129 | width: 10%; 130 | } 131 | 132 | .enhanced-copy .hide-info { 133 | display: none; 134 | } 135 | 136 | .enhanced-copy .no-display .setting-item-info { 137 | display: none; 138 | } 139 | 140 | .enhanced-copy input.error { 141 | border-color: var(--text-error); 142 | --background-modifier-border-focus: var(--background-modifier-error); 143 | } 144 | 145 | .enhanced-copy code { 146 | font-size: var(--font-ui-smaller); 147 | padding: 0; 148 | position: revert; 149 | bottom: 0; 150 | } 151 | 152 | .enhanced-copy input { 153 | font-family: var(--font-monospace); 154 | } 155 | 156 | .enhanced-copy .dataview:not(.setting-item.setting-item-heading) { 157 | position: relative; 158 | left: 20px; 159 | } 160 | 161 | .enhanced-copy .setting-item.setting-item-heading.dataview { 162 | position: relative; 163 | left: 10px; 164 | } 165 | -------------------------------------------------------------------------------- /src/utils/conversion.ts: -------------------------------------------------------------------------------- 1 | import i18next from "i18next"; 2 | 3 | import { 4 | CalloutKeepType, 5 | ConversionOfFootnotes, 6 | ConversionOfLinks, 7 | type GlobalSettings, 8 | } from "../interface"; 9 | import type EnhancedCopy from "../main"; 10 | import { convertDataviewQueries } from "./dataview"; 11 | 12 | /** 13 | * If a list is preceded by an empty line, remove the empty line 14 | * @param {string} markdown Markdown to convert 15 | * @returns {string} Markdown with empty line removed before list 16 | */ 17 | function removeEmptyLineBeforeList(markdown: string): string { 18 | const lines = markdown.split("\n"); 19 | const newLines = []; 20 | for (let i = 0; i < lines.length; i++) { 21 | const line = lines[i]; 22 | if ( 23 | !(line.trim().length === 0 && i + 1 < lines.length && lines[i + 1].startsWith("-")) 24 | ) { 25 | newLines.push(line); 26 | } 27 | } 28 | return newLines.join("\n"); 29 | } 30 | 31 | /** 32 | * Allow to remove the links in the markdown if the settings are set to remove it. 33 | * Also remove the `!` in front of the link if it's an image/embed link 34 | * Remove `↩︎` for footnotes 35 | * @example `external` : Keep only external links in markdown (links that don't start with `http` or `https`) 36 | * - `[link](https://example.com)` -> `[link](https://example.com)` 37 | * - `[link](example.md) -> link` 38 | * @example `remove` : Remove all links in markdown (including external links) 39 | * - `[link](https://example.com)` -> `link` 40 | * - `[link](example.md) -> link` 41 | * @example `keep` : Keep all links in markdown 42 | * - `[link](https://example.com)` -> `[link](https://example.com)` 43 | * - `[link](example.md) -> [link](example.md)` 44 | * @param markdown {string} Markdown to convert 45 | * @param settings {EnhancedCopySettings} Settings of the plugin 46 | * @returns {string} Markdown with links removed if needed 47 | */ 48 | function removeLinksBracketsInMarkdown( 49 | markdown: string, 50 | settings: GlobalSettings 51 | ): string { 52 | const regexLinks = /!?\[([^\]]+)\]\(([^)]+)\)/g; 53 | if (settings.links === ConversionOfLinks.Remove) { 54 | markdown = markdown.replaceAll(regexLinks, "$1"); 55 | } else if (settings.links === ConversionOfLinks.External) { 56 | //convert links only if they don't have `http` or `https` in them 57 | markdown = markdown.replaceAll(regexLinks, (match, p1, p2) => { 58 | if (p2.startsWith("http")) { 59 | return match; 60 | } 61 | return p1; 62 | }); 63 | } 64 | return markdown.replaceAll("↩︎", ""); 65 | } 66 | 67 | /** 68 | * Convert wikilinks to markdown links 69 | * Only for edit view 70 | * @example `[[link]]` -> `[link](link)` 71 | * @example `[[link#anchor|text]]` -> `[text](link#anchor)` 72 | * @param markdown {string} Markdown to convert 73 | */ 74 | function convertWikiToMarkdown(markdown: string): string { 75 | const regexWikiLinks = /\[\[([^\]]+)\]\]/g; 76 | return markdown.replaceAll(regexWikiLinks, (_match, p1) => { 77 | const parts = p1.split("|"); 78 | if (parts.length === 1) { 79 | return `[${p1}](${p1})`; 80 | } 81 | return `[${parts[1]}](${parts[0]})`; 82 | }); 83 | } 84 | 85 | /** 86 | * Depending of the settings, will removing completely footnote or keeping content but removing the footnote format 87 | * @example `remove` : Remove all footnotes in markdown 88 | * `footnote[[1]](#fn-1-632b5699b7da7a44)` -> `footnote` 89 | * @example `format` : Keep the content of the footnote but remove the footnote format 90 | * `footnote[[1]](#fn-1-632b5699b7da7a44)` -> `footnote[^1]` 91 | * @example `keep` : Keep all footnotes in markdown 92 | * `footnote[[1]](#fn-1-632b5699b7da7a44)` -> `footnote[[1]](#fn-1-632b5699b7da7a44)` 93 | * @param markdown {string} Markdown to convert 94 | * @param settings {EnhancedCopySettings} Settings of the plugin 95 | * @returns {string} Markdown with footnotes removed if needed 96 | */ 97 | function fixFootNotes(markdown: string, settings: GlobalSettings): string { 98 | const regexFootNotes = /\[{2}(\w+)\]{2}\((.*)\)/g; 99 | if (settings.footnotes === ConversionOfFootnotes.Remove) { 100 | //keep links but remove footnotes format : [1](#text)[1] 101 | markdown = markdown.replace(regexFootNotes, ""); 102 | } else if (settings.footnotes === ConversionOfFootnotes.Format) { 103 | //keep links but format footnotes format : [[1]](#text) 104 | markdown = markdown.replace(regexFootNotes, "[^$1]"); 105 | } 106 | return fixFootnoteContents(markdown, settings); 107 | } 108 | 109 | /** 110 | * Convert the turndown format to proper reading markdown 111 | * @example Remove: `coucou[](#fnref-1-632b5699b7da7a44)` -> coucou 112 | * @example Format: `coucou[](#fnref-1-632b5699b7da7a44)` -> [^1]: coucou` 113 | * @param markdown 114 | * @param overrides 115 | */ 116 | function fixFootnoteContents(markdown: string, overrides: GlobalSettings): string { 117 | const regexFootNotes = /(.*)\[\]\(#fnref-(\d)-\w+\)/g; 118 | if (overrides.footnotes === ConversionOfFootnotes.Remove) { 119 | return markdown.replace(regexFootNotes, "$1"); 120 | } else if (overrides.footnotes === ConversionOfFootnotes.Format) { 121 | markdown = markdown.replace(regexFootNotes, "[^$2]: $1"); 122 | return markdown.replace(/(\[\^\w+\]): (\d+)\./gm, "$1:"); 123 | } 124 | return markdown; 125 | } 126 | 127 | function removeMarkdownFootNotes(markdown: string, overrides: GlobalSettings): string { 128 | if (overrides.footnotes === ConversionOfFootnotes.Remove) { 129 | /** regex replace only text[^1] and not the line that start with [^1]: 130 | * @example 131 | * `text[^1]` -> `text` 132 | * `[^1]: text` -> `[^1]: text` 133 | */ 134 | const regexFootNotes = /^\[\^(\w+)\]:/gm; 135 | markdown = markdown.replace(regexFootNotes, "$1:"); 136 | return markdown.replace(/\[\^\w+]/g, ""); 137 | } 138 | return markdown; 139 | } 140 | 141 | /** 142 | * As the highlight is not supported in all markdown editor, we can remove it if needed (depending of the settings) 143 | * @param markdown {string} Markdown to convert 144 | * @param settings {EnhancedCopySettings} Settings of the plugin 145 | * @returns {string} Markdown with highlight removed if needed 146 | */ 147 | function removeHighlightMark(markdown: string, settings: GlobalSettings): string { 148 | if (settings.highlight) { 149 | return markdown.replace(/==([^=]+)==/g, "$1"); 150 | } 151 | return markdown; 152 | } 153 | 154 | /** 155 | * If the settings are set to add hard breaks, add "two spaces and a new line" at the end of each line 156 | * @example 157 | * `line1\nline2` -> `line1 \nline2 \n` 158 | * @param markdown {string} Markdown to convert 159 | * @param settings {EnhancedCopySettings} Settings of the plugin 160 | * @param plugin 161 | * @returns {string} Markdown with hard breaks added if needed 162 | */ 163 | function hardBreak( 164 | markdown: string, 165 | settings: GlobalSettings, 166 | plugin: EnhancedCopy 167 | ): string { 168 | if (settings.hardBreak) { 169 | markdown = markdown.replace(/ *\n/g, " \n"); 170 | markdown += " "; 171 | } else { 172 | plugin.devLog(i18next.t("log.noHardBreaks")); 173 | markdown = markdown.replace(/ *\n/g, "\n"); 174 | } 175 | return markdown; 176 | } 177 | 178 | function convertCallout( 179 | markdown: string, 180 | overrides: GlobalSettings, 181 | plugin: EnhancedCopy 182 | ): string { 183 | plugin.devLog(i18next.t("log.callout.title"), overrides.callout); 184 | const calloutRegex = /^>* *\[!(\w+)\|?(.*)\] *(.*)$/gm; 185 | if ( 186 | overrides.callout === CalloutKeepType.RemoveKeepTitle || 187 | overrides.callout === CalloutKeepType.Remove 188 | ) { 189 | plugin.devLog(i18next.t("log.callout.remove")); 190 | //delete the type of the callout 191 | markdown = markdown.replace(calloutRegex, (_match, _p1, _p2, p3) => { 192 | if (p3 === "") { 193 | //remove the line without adding a new line / space 194 | return "undefined"; 195 | } 196 | if (overrides.callout === CalloutKeepType.RemoveKeepTitle) return `> **${p3}**`; 197 | return "undefined"; 198 | }); 199 | //remove line prepended by undefined 200 | return markdown.replace("undefined\n>", ">"); 201 | } else if (overrides.callout === CalloutKeepType.Strong) { 202 | return markdown.replace(calloutRegex, "> **$1** $3"); 203 | } 204 | 205 | return markdown; 206 | } 207 | 208 | function convertTabToSpace(markdown: string, settings: GlobalSettings) { 209 | if (settings.tabToSpace) { 210 | const spaces = " ".repeat(settings.tabSpaceSize ?? 4); 211 | return markdown.replace(/\t/g, spaces); 212 | } 213 | return markdown; 214 | } 215 | 216 | function convertSpaceSize(markdown: string, settings: GlobalSettings) { 217 | /** Note: 218 | * Turndown will always convert \t to 4 space 219 | * So if we want to reduce the space size, we need to count each 4 space as 1 space for each line 220 | */ 221 | const countSpace = markdown.match(/^ +/gm); 222 | if (!settings.spaceReadingSize) return markdown; 223 | if (settings.spaceReadingSize >= 0 && countSpace) { 224 | countSpace.forEach((space) => { 225 | const newSpace = " ".repeat((space.length / 4) * (settings.spaceReadingSize ?? 1)); 226 | markdown = markdown.replace(space, newSpace); 227 | }); 228 | } 229 | return markdown; 230 | } 231 | 232 | function textReplacement(markdown: string, settings: GlobalSettings) { 233 | const replacement = settings.replaceText; 234 | for (const replace of replacement) { 235 | let pattern: string | RegExp = replace.pattern; 236 | if (pattern.match(/^\/.*\/([gmiyus]+)?$/)) { 237 | const flags = pattern.replace(/^\/.*\/([gmiyus]+)?$/, "$1"); 238 | const regex = pattern.replace(/^\/(.*)\/(.*)$/, "$1"); 239 | pattern = new RegExp(regex, flags.length > 0 ? flags : undefined); 240 | markdown = markdown.replace(pattern, replace.replacement); 241 | } else markdown = markdown.replaceAll(pattern, replace.replacement); 242 | } 243 | return markdown; 244 | } 245 | 246 | /** 247 | * Main function of the plugin, will convert the markdown depending of the settings 248 | * @param markdown {string} Markdown to convert 249 | * @param overrides 250 | * @param plugin 251 | * @returns {string} converted markdown 252 | */ 253 | export function convertMarkdown( 254 | markdown: string, 255 | overrides: GlobalSettings, 256 | plugin: EnhancedCopy 257 | ): string { 258 | return removeEmptyLineBeforeList( 259 | convertSpaceSize( 260 | convertCallout( 261 | hardBreak( 262 | removeHighlightMark( 263 | fixFootNotes( 264 | removeLinksBracketsInMarkdown( 265 | textReplacement(markdown, overrides), 266 | overrides 267 | ), 268 | overrides 269 | ), 270 | overrides 271 | ), 272 | overrides, 273 | plugin 274 | ), 275 | overrides, 276 | plugin 277 | ), 278 | overrides 279 | ) 280 | ); 281 | } 282 | 283 | export async function convertEditMarkdown( 284 | markdown: string, 285 | overrides: GlobalSettings, 286 | plugin: EnhancedCopy, 287 | path?: string | null 288 | ) { 289 | markdown = textReplacement(markdown, overrides); 290 | if ( 291 | path && 292 | overrides.convertDataview && 293 | plugin.app.plugins.enabledPlugins.has("dataview") 294 | ) 295 | markdown = await convertDataviewQueries(overrides, path, markdown, plugin); 296 | if (overrides.wikiToMarkdown) { 297 | markdown = convertWikiToMarkdown(markdown); 298 | markdown = removeLinksBracketsInMarkdown(markdown, overrides); 299 | } 300 | markdown = convertTabToSpace(markdown, overrides); 301 | markdown = removeMarkdownFootNotes(markdown, overrides); 302 | markdown = convertCallout(markdown, overrides, plugin); 303 | markdown = removeHighlightMark(markdown, overrides); 304 | return hardBreak(markdown, overrides, plugin); 305 | } 306 | -------------------------------------------------------------------------------- /src/utils/dataview.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * @credit oleeskild 3 | * @link https://github.com/oleeskild/obsidian-digital-garden/blob/main/src/compiler/DataviewCompiler.ts 4 | */ 5 | 6 | import { Component, htmlToMarkdown } from "obsidian"; 7 | import type { GlobalSettings } from "../interface"; 8 | import { 9 | getAPI, 10 | isPluginEnabled, 11 | type DataviewApi, 12 | type Literal, 13 | } from "@enveloppe/obsidian-dataview"; 14 | import type EnhancedCopy from "../main"; 15 | 16 | class DataviewCompiler { 17 | settings: GlobalSettings; 18 | dvApi: DataviewApi; 19 | sourceText: string; 20 | path: string; 21 | 22 | constructor( 23 | settings: GlobalSettings, 24 | dvApi: DataviewApi, 25 | sourceText: string, 26 | path: string 27 | ) { 28 | this.settings = settings; 29 | this.dvApi = dvApi; 30 | this.sourceText = sourceText; 31 | this.path = path; 32 | } 33 | 34 | escapeRegex(filepath: string): string { 35 | return filepath.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&"); 36 | } 37 | 38 | dvJsMatch() { 39 | const dataviewJsPrefix = this.dvApi.settings.dataviewJsKeyword || "dataviewjs"; 40 | const dataViewJsRegex = new RegExp( 41 | `\`\`\`${this.escapeRegex(dataviewJsPrefix)}\\s(.+?)\`\`\``, 42 | "gsm" 43 | ); 44 | return this.sourceText.matchAll(dataViewJsRegex); 45 | } 46 | 47 | dvInlineQueryMatches() { 48 | const inlineQueryPrefix = this.dvApi.settings.inlineQueryPrefix || "="; 49 | const inlineDataViewRegex = new RegExp( 50 | `\`${this.escapeRegex(inlineQueryPrefix)}(.+?)\``, 51 | "gsm" 52 | ); 53 | return this.sourceText.matchAll(inlineDataViewRegex); 54 | } 55 | 56 | dvInlineJSMatches() { 57 | const inlineJsQueryPrefix = this.dvApi.settings.inlineJsQueryPrefix || "$="; 58 | const inlineJsDataViewRegex = new RegExp( 59 | `\`${this.escapeRegex(inlineJsQueryPrefix)}(.+?)\``, 60 | "gsm" 61 | ); 62 | return this.sourceText.matchAll(inlineJsDataViewRegex); 63 | } 64 | 65 | matches() { 66 | return { 67 | dataviewJsMatches: this.dvJsMatch(), 68 | inlineMatches: this.dvInlineQueryMatches(), 69 | inlineJsMatches: this.dvInlineJSMatches(), 70 | }; 71 | } 72 | 73 | sanitizeQuery(query: string): { isInsideCallout: boolean; finalQuery: string } { 74 | let isInsideCallout = false; 75 | const parts = query.split("\n"); 76 | const sanitized = []; 77 | 78 | for (const part of parts) { 79 | if (part.startsWith(">")) { 80 | isInsideCallout = true; 81 | sanitized.push(part.substring(1).trim()); 82 | } else { 83 | sanitized.push(part); 84 | } 85 | } 86 | const finalQuery = isInsideCallout ? sanitized.join("\n") : query; 87 | return { isInsideCallout, finalQuery }; 88 | } 89 | 90 | removeDataviewQueries(dataviewMarkdown: Literal): string { 91 | const toStr = dataviewMarkdown?.toString(); 92 | return this.settings.convertDataview && dataviewMarkdown && toStr ? toStr : ""; 93 | } 94 | 95 | surroundWithCalloutBlock(input: string): string { 96 | const tmp = input.split("\n"); 97 | 98 | return ` ${tmp.join("\n> ")}`; 99 | } 100 | /** 101 | * DQL Dataview - The SQL-like Dataview Query Language 102 | * Are in **code blocks** 103 | * @link https://blacksmithgu.github.io/obsidian-dataview/queries/dql-js-inline/#dataview-query-language-dql 104 | */ 105 | async dataviewDQL(query: string) { 106 | const { isInsideCallout, finalQuery } = this.sanitizeQuery(query); 107 | const markdown = this.removeDataviewQueries( 108 | (await this.dvApi.tryQueryMarkdown(finalQuery, this.path)) as string 109 | ); 110 | if (isInsideCallout) { 111 | return this.surroundWithCalloutBlock(markdown); 112 | } 113 | return markdown; 114 | } 115 | 116 | /** 117 | * DataviewJS - JavaScript API for Dataview 118 | * Are in **CODE BLOCKS** 119 | * @link https://blacksmithgu.github.io/obsidian-dataview/api/intro/ 120 | */ 121 | async dataviewJS(query: string) { 122 | const { isInsideCallout, finalQuery } = this.sanitizeQuery(query); 123 | const div = createEl("div"); 124 | const component = new Component(); 125 | await this.dvApi.executeJs(finalQuery, div, component, this.path); 126 | component.load(); 127 | const markdown = this.removeDataviewQueries(div.innerHTML); 128 | if (isInsideCallout) { 129 | return this.surroundWithCalloutBlock(markdown); 130 | } 131 | return markdown; 132 | } 133 | /** 134 | * Inline DQL Dataview - The SQL-like Dataview Query Language in inline 135 | * Syntax : `= query` 136 | * (the prefix can be changed in the settings) 137 | * @source https://blacksmithgu.github.io/obsidian-dataview/queries/dql-js-inline/#inline-dql 138 | */ 139 | 140 | async inlineDQLDataview(query: string) { 141 | const dataviewResult = this.dvApi.evaluateInline(query, this.path); 142 | if (dataviewResult.successful) { 143 | return this.removeDataviewQueries(dataviewResult.value); 144 | } else { 145 | return this.removeDataviewQueries(this.dvApi.settings.renderNullAs); 146 | } 147 | } 148 | /** 149 | * Inline DataviewJS - JavaScript API for Dataview in inline 150 | * Syntax : `$=js query` 151 | * For the moment, it is not possible to properly process the inlineJS. 152 | * Temporary solution : encapsulate the query into "pure" JS : 153 | * ```ts 154 | * const query = queryFound; 155 | * dv.paragraph(query); 156 | * ``` 157 | * After the evaluation, the div is converted to markdown with {@link htmlToMarkdown()} and the dataview queries are removed 158 | */ 159 | async inlineDataviewJS(query: string) { 160 | const evaluateQuery = ` 161 | const query = ${query}; 162 | dv.paragraph(query); 163 | `; 164 | const div = createEl("div"); 165 | const component = new Component(); 166 | await this.dvApi.executeJs(evaluateQuery, div, component, this.path); 167 | component.load(); 168 | return this.removeDataviewQueries(htmlToMarkdown(div.innerHTML)); 169 | } 170 | } 171 | 172 | export async function convertDataviewQueries( 173 | settings: GlobalSettings, 174 | path: string, 175 | text: string, 176 | plugin: EnhancedCopy 177 | ): Promise { 178 | const app = plugin.app; 179 | let replacedText = text; 180 | const dataViewRegex = /```dataview\s(.+?)```/gms; 181 | const isDataviewEnabled = app.plugins.plugins.dataview; 182 | if (!isDataviewEnabled || !isPluginEnabled(app) || !settings.convertDataview?.enable) 183 | return replacedText; 184 | const dvApi = getAPI(app); 185 | if (!dvApi || dvApi === undefined) return replacedText; 186 | const matches = text.matchAll(dataViewRegex); 187 | const compiler = new DataviewCompiler(settings, dvApi, text, path); 188 | const { dataviewJsMatches, inlineMatches, inlineJsMatches } = compiler.matches(); 189 | if (!matches && !inlineMatches && !dataviewJsMatches && !inlineJsMatches) { 190 | console.warn("No dataview queries found"); 191 | return replacedText; 192 | } 193 | /** 194 | * DQL Dataview - The SQL-like Dataview Query Language 195 | */ 196 | if (settings.convertDataview?.dql?.block) { 197 | for (const queryBlock of matches) { 198 | try { 199 | const block = queryBlock[0]; 200 | const markdown = await compiler.dataviewDQL(queryBlock[1]); 201 | replacedText = replacedText.replace(block, markdown); 202 | } catch (e) { 203 | console.error(e); 204 | return queryBlock[0]; 205 | } 206 | } 207 | } 208 | /** 209 | * DataviewJS - JavaScript API for Dataview 210 | */ 211 | if (settings.convertDataview?.djs?.block) { 212 | for (const queryBlock of dataviewJsMatches) { 213 | try { 214 | const block = queryBlock[0]; 215 | const markdown = await compiler.dataviewJS(queryBlock[1]); 216 | replacedText = replacedText.replace(block, markdown); 217 | } catch (e) { 218 | console.error(e); 219 | return queryBlock[0]; 220 | } 221 | } 222 | } 223 | 224 | //Inline queries 225 | if (settings.convertDataview?.dql?.inline) { 226 | for (const inlineQuery of inlineMatches) { 227 | try { 228 | const code = inlineQuery[0]; 229 | const query = inlineQuery[1].trim(); 230 | const markdown = await compiler.inlineDQLDataview(query); 231 | replacedText = replacedText.replace(code, markdown); 232 | } catch (e) { 233 | console.error(e); 234 | return inlineQuery[0]; 235 | } 236 | } 237 | } 238 | //Inline JS queries 239 | if (settings.convertDataview?.djs?.inline) { 240 | for (const inlineJsQuery of inlineJsMatches) { 241 | try { 242 | const code = inlineJsQuery[0]; 243 | const markdown = await compiler.inlineDataviewJS(inlineJsQuery[1].trim()); 244 | replacedText = replacedText.replace(code, markdown); 245 | } catch (e) { 246 | console.error(e); 247 | return inlineJsQuery[0]; 248 | } 249 | } 250 | } 251 | return replacedText; 252 | } 253 | -------------------------------------------------------------------------------- /src/utils/node_edit.ts: -------------------------------------------------------------------------------- 1 | import { CalloutKeepType, type GlobalSettings } from "../interface"; 2 | 3 | /** 4 | * Fix list that are not correctly converted to markdown 5 | * @param div {HTMLDivElement} : The div to transform 6 | * @param type {string} : The type of list to create (ol or ul) 7 | * @returns div {HTMLDivElement} : The div transformed 8 | */ 9 | export function reNumerateList(div: HTMLDivElement, type: string) { 10 | const allLi = div.querySelectorAll("li"); 11 | let allHaveDataLine = true; 12 | for (const li of allLi) { 13 | if (!li.hasAttribute("data-line")) { 14 | allHaveDataLine = false; 15 | break; 16 | } 17 | } 18 | if (allHaveDataLine) { 19 | const ol = document.createElement(type); 20 | for (const li of allLi) { 21 | ol.appendChild(li); 22 | } 23 | div.innerHTML = ""; 24 | div.appendChild(ol); 25 | } 26 | return div; 27 | } 28 | 29 | /** 30 | * Replace all div with class "callout" to blockquote with the same content 31 | * The title will be added differently in function of the settings: 32 | * - `remove`: The title will be removed ; 33 | * - `strong`: The title will be added as a strong text (ie GitHub Admonition flavored) 34 | * - `obsidian`: Will have the same behavior as the callout formatting in Obsidian 35 | * @param div {HTMLDivElement} The selected contents as HTML 36 | * @param commonAncestor {Node} The common ancestor of the selection 37 | * @param settings {GlobalSettings} 38 | * @returns {HTMLDivElement} The div transformed 39 | */ 40 | export function replaceAllDivCalloutToBlockquote( 41 | div: HTMLDivElement, 42 | commonAncestor: Node, 43 | settings: GlobalSettings 44 | ): HTMLDivElement { 45 | const allDivCallout = div.querySelectorAll("div[class*='callout']"); 46 | let calloutTitle = ""; 47 | for (const divCallout of allDivCallout) { 48 | if ( 49 | settings.callout !== CalloutKeepType.Remove && 50 | settings.callout !== CalloutKeepType.RemoveKeepTitle && 51 | divCallout.classList[0] === "callout-title" 52 | ) { 53 | const ancestor = commonAncestor as HTMLDivElement; 54 | const calloutType = 55 | ancestor.attributes.getNamedItem("data-callout")?.value ?? 56 | (divCallout.parentElement 57 | ? divCallout.parentElement.attributes.getNamedItem("data-callout")?.value 58 | : ""); 59 | calloutTitle = `[!${calloutType}] `; 60 | if (settings.callout === CalloutKeepType.Strong) { 61 | calloutTitle = `${capitalize(calloutType)} `; 62 | } 63 | //insert callout title in title-content-inner div as html, before the text 64 | const titleInner = divCallout.querySelector(".callout-title-inner"); 65 | if (titleInner && !calloutTitle.contains(titleInner.innerHTML.toLowerCase())) 66 | titleInner?.replaceWith(calloutTitle + titleInner?.innerHTML); 67 | else titleInner?.replaceWith(calloutTitle); 68 | } 69 | const blockquote = document.createElement("blockquote"); 70 | blockquote.innerHTML = divCallout.innerHTML; 71 | //replace div by blockquote< 72 | divCallout.replaceWith(blockquote); 73 | } 74 | const allTitleInner = div.querySelectorAll("div.callout-title-inner"); 75 | for (const titleInner of allTitleInner) { 76 | if (titleInner && settings.callout !== CalloutKeepType.Remove) { 77 | titleInner.innerHTML = calloutTitle 78 | .toLowerCase() 79 | .contains(titleInner.innerHTML.toLowerCase()) 80 | ? `${calloutTitle}` 81 | : `${calloutTitle}${titleInner.innerHTML}`; 82 | } else if (titleInner && settings.callout === CalloutKeepType.Remove) { 83 | titleInner.remove(); 84 | } 85 | } 86 | return simplifyBlockquote(div); 87 | } 88 | 89 | /** 90 | * This function will convert: 91 | * ```html 92 | *
93 | *
94 | *
...
95 | *
info
96 | *
97 | *

coucou

98 | *
99 | * ``` 100 | * to: 101 | * ```html 102 | *
103 | * info 104 | *

coucou

105 | *
106 | * ``` 107 | * @param div {HTMLDivElement} The selected contents as HTML 108 | * @returns {HTMLDivElement} The div transformed 109 | */ 110 | function simplifyBlockquote(div: HTMLDivElement): HTMLDivElement { 111 | const blockquotes = div.querySelectorAll("blockquote"); 112 | blockquotes.forEach((blockquote) => { 113 | const modifiedDivElement = document.createElement("div"); 114 | const calloutTitleInner = blockquote.querySelector(".callout-title-inner"); 115 | const calloutContent = blockquote.querySelector(".callout-content"); 116 | if (!calloutTitleInner && !calloutContent) return; 117 | const calloutTitleInnerText = calloutTitleInner?.innerHTML 118 | ? `${calloutTitleInner!.innerHTML}
` 119 | : ""; 120 | const calloutContentHTML = calloutContent?.innerHTML ?? ""; 121 | modifiedDivElement.innerHTML = ` 122 |
123 | ${calloutTitleInnerText} 124 | ${calloutContentHTML.replace("

", "").replace("

", "")} 125 |
126 | `; 127 | //we need to replace the the blockquote by the new simplified blockquote 128 | blockquote.replaceWith(modifiedDivElement); 129 | }); 130 | return div; 131 | } 132 | 133 | function capitalize(string: string | undefined) { 134 | if (string === undefined) return ""; 135 | return string.charAt(0).toUpperCase() + string.slice(1); 136 | } 137 | -------------------------------------------------------------------------------- /src/utils/pluginFix.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Some div are not correctly converted to markdown, this function fix them 3 | * It is a fix for the plugin dbfolder (@RafaelGB/obsidian-db-folder) 4 | * As the formatting is broken when copying the table from the plugin. 5 | * @note More function like that can be added in the future if needed 6 | * @returns {string} The selected text (copying behavior of Obsidian) 7 | */ 8 | 9 | export function removeDataBasePluginRelationShip(): string { 10 | if (activeDocument.querySelector("div.database-plugin__container")) { 11 | const div = document.createElement("div"); 12 | const getSelection = activeWindow.getSelection(); 13 | if (!getSelection) return ""; 14 | const selection = getSelection.getRangeAt(0); 15 | const fragment = selection.cloneContents(); 16 | div.appendChild(fragment); 17 | const allSpan = div.querySelectorAll("span"); 18 | for (const span of allSpan) { 19 | //remove database-plugin__relationship class 20 | if (span.classList[0] === "database-plugin__relationship") { 21 | //remove entire span 22 | //replace by br 23 | span.innerHTML = "\n"; 24 | } 25 | } 26 | return div.innerText; 27 | } else { 28 | const getSelection = activeWindow.getSelection(); 29 | if (!getSelection) return ""; 30 | return getSelection.toString(); 31 | } 32 | } 33 | 34 | /** 35 | * Metabind is rendered like this, in the HTML: 36 | * ```html 37 | *
xxx
38 | * ``` 39 | * This return a strange formated code block in markdown, this function fix it, with converting to text 40 | * @param html 41 | */ 42 | export function fixMetaBindCopy(html: string) { 43 | return html 44 | .replace( 45 | /
(.*?)<\/div><\/code>/gim, 46 | "$1" 47 | ) 48 | .replace( 49 | /

(.*)<\/p>/gim, 50 | "$1" 51 | ) 52 | .replace(/

(.*)/gim, "")
54 | 		.replace(/.*<\/span>(.*)/gim, "")
55 | 		.replace(/(.*)/gim, "")
56 | 		.replace(
57 | 			/
<\/div><\/code>/gim, 58 | "" 59 | ) 60 | .replace( 61 | '
', 62 | "" 63 | ); 64 | } 65 | -------------------------------------------------------------------------------- /src/utils/selection.ts: -------------------------------------------------------------------------------- 1 | import i18next from "i18next"; 2 | import { type App, type Editor, type EditorPosition, htmlToMarkdown } from "obsidian"; 3 | 4 | import { COLLAPSE_INDICATOR, type GlobalSettings } from "../interface"; 5 | import type EnhancedCopy from "../main"; 6 | import { reNumerateList, replaceAllDivCalloutToBlockquote } from "./node_edit"; 7 | import { fixMetaBindCopy } from "./pluginFix"; 8 | 9 | /** 10 | * Get the selection of the activeWindows and transform it as HTML 11 | * if the will apply all transformation needed and return the markdown or the HTML 12 | * @note HTML with data-type = "html" will not be converted to markdown 13 | * @param settings {EnhancedCopySettings} Settings of the plugin 14 | * @returns {string} 15 | */ 16 | export function getSelectionAsHTML(settings: GlobalSettings): string { 17 | const getSelection = activeWindow.getSelection(); 18 | if (getSelection === null) return ""; 19 | const range = getSelection.getRangeAt(0); 20 | if (!range) return ""; 21 | const fragment = range.cloneContents(); 22 | let div = document.createElement("div"); 23 | div.appendChild(fragment); 24 | const commonAncestor = range.commonAncestorContainer; 25 | if (commonAncestor.nodeName === "OL" || commonAncestor.nodeName === "UL") { 26 | //if so, create ol or ul and append all li to it 27 | const type = commonAncestor.nodeName.toLowerCase(); 28 | div = reNumerateList(div, type); 29 | } 30 | div = replaceAllDivCalloutToBlockquote(div, range.commonAncestorContainer, settings); 31 | if (settings.copyAsHTML) { 32 | return div.innerHTML; 33 | } 34 | const allNoConvert = div.querySelectorAll("[data-type='html']"); 35 | let markdown = htmlToMarkdown( 36 | fixMetaBindCopy(div.innerHTML.replace(COLLAPSE_INDICATOR, "")) 37 | ); 38 | //no converting html to markdown the div that contains a class with "no-convert" 39 | for (const noConvert of allNoConvert) { 40 | const converted = htmlToMarkdown(noConvert.outerHTML); 41 | markdown = markdown.replace( 42 | converted, 43 | noConvert.outerHTML.replace(/ ?data-type=["']html["']/, "") 44 | ); 45 | } 46 | return markdown; 47 | } 48 | 49 | /** Return the real "head" of the selection 50 | * The head will be ALWAYS the littlest line number or the littlest character number if the line number is the same 51 | * @param {EditorPosition} head Original head from EditorSelection 52 | * @param {EditorPosition} anchor Original anchor from EditorSelection 53 | */ 54 | 55 | export function getHead(head: EditorPosition, anchor: EditorPosition) { 56 | if (head.line === anchor.line) { 57 | if (head.ch < anchor.ch) { 58 | return head; 59 | } 60 | return anchor; 61 | } else if (head.line < anchor.line) { 62 | return head; 63 | } 64 | return anchor; 65 | } 66 | 67 | /** 68 | * Return the real "anchor" of the selection 69 | * The anchor will be ALWAYS the biggest line number or the biggest character number if the line number is the same 70 | * @param {EditorPosition} head Original head from EditorSelection 71 | * @param {EditorPosition} anchor Original anchor from EditorSelection 72 | */ 73 | 74 | export function getAnchor(head: EditorPosition, anchor: EditorPosition) { 75 | if (head.line === anchor.line) { 76 | if (head.ch < anchor.ch) { 77 | return anchor; 78 | } 79 | return head; 80 | } else if (head.line < anchor.line) { 81 | return anchor; 82 | } 83 | return head; 84 | } 85 | 86 | /** 87 | * In Editor, get the selected text for all selection 88 | * @param editor {Editor} Editor of the activeView 89 | * @returns {string} The selected text (copying behavior of Obsidian) 90 | */ 91 | export function copySelectionRange(editor: Editor, plugin: EnhancedCopy): string { 92 | let selectedText = ""; 93 | const selection = editor.listSelections(); 94 | const inlineTitle = activeWindow.document.querySelector(".inline-title:focus"); 95 | const viewHeader = activeWindow.document.querySelector(".view-header-title:focus"); 96 | if (inlineTitle?.textContent && inlineTitle.textContent !== "") 97 | return inlineTitle.textContent; 98 | else if (viewHeader?.textContent && viewHeader.textContent !== "") { 99 | return viewHeader.textContent; 100 | } 101 | for (const selected of selection) { 102 | const head = getHead(selected.head, selected.anchor); 103 | const anchor = getAnchor(selected.head, selected.anchor); 104 | selectedText += `${editor.getRange(head, anchor)}\n`; 105 | } 106 | selectedText = selectedText.substring(0, selectedText.length - 1); 107 | if (selectedText === "") { 108 | const getSelection = activeWindow.getSelection(); 109 | plugin.devLog(i18next.t("log.empty")); 110 | return getSelection === null ? "" : getSelection.toString(); 111 | } 112 | return selectedText; 113 | } 114 | 115 | /** 116 | * In Canvas only, check if the selection is in editor or not 117 | * If in editor, return the text as in Obsidian. If not, run getSelectionAsHTML and return the output 118 | * @param app {App}} 119 | * @param settings {EnhancedCopySettings} 120 | * @returns {string} 121 | */ 122 | export function canvasSelectionText(app: App, plugin: EnhancedCopy): string { 123 | const { settings } = plugin; 124 | const editor = app.workspace.activeEditor; 125 | if (editor) { 126 | const editorMode = editor.editor as Editor; 127 | return copySelectionRange(editorMode, plugin); 128 | } else { 129 | return getSelectionAsHTML(settings.reading); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "noEmit": true, 4 | "baseUrl": ".", 5 | "inlineSourceMap": true, 6 | "inlineSources": true, 7 | "skipLibCheck": true, 8 | "allowSyntheticDefaultImports": true, 9 | "strict": true, 10 | "module": "ESNext", 11 | "target": "ESNext", 12 | "allowJs": true, 13 | "noImplicitAny": true, 14 | "moduleResolution": "node", 15 | "importHelpers": true, 16 | "isolatedModules": true, 17 | "resolveJsonModule": true, 18 | "strictNullChecks": true, 19 | "lib": [ 20 | "DOM", 21 | "ES5", 22 | "ES6", 23 | "ES7", 24 | "ES2015", 25 | "ES2021", 26 | "ES2022", 27 | "DOM.Iterable" 28 | ] 29 | }, 30 | "include": [ 31 | "**/*.ts" 32 | ] 33 | } --------------------------------------------------------------------------------