├── .eslintignore ├── .github ├── FUNDING.yml ├── workflows │ ├── main.yml │ └── release.yml └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── versions.json ├── resources └── screenshots │ ├── task-move.png │ ├── configure-repetition.gif │ ├── move-incomplete-tasks.gif │ ├── slated-command-palette.png │ ├── task-repeat-config-1.png │ └── task-repeat-config-2.png ├── tests ├── __mocks__ │ └── obsidian.ts ├── task-handler.test.ts └── task-line.test.ts ├── .gitignore ├── jest.config.js ├── .gitattributes ├── manifest.json ├── .prettierrc ├── yarn ├── tsconfig.json ├── src ├── settings.ts ├── ui │ ├── TaskMove.svelte │ ├── ButtonGroup.svelte │ ├── WeekDaysOfMonthSelector.svelte │ └── TaskRepeat.svelte ├── localization.ts ├── vault.ts ├── task-handler.ts ├── task-cache.ts ├── repeat.ts ├── file-helpers.ts ├── task-line.ts ├── main.ts └── graphics.ts ├── rollup.config.js ├── styles.css ├── package.json ├── README.md ├── Design.md ├── .eslintrc.js └── LICENSE /.eslintignore: -------------------------------------------------------------------------------- 1 | main.js -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [tgrosinger] 2 | custom: ["https://paypal.me/tgrosinger", "https://buymeacoffee.com/tgrosinger"] 3 | -------------------------------------------------------------------------------- /versions.json: -------------------------------------------------------------------------------- 1 | { 2 | "0.4.0": "0.12.1", 3 | "0.3.0": "0.11.13", 4 | "0.2.1": "0.11.0", 5 | "0.0.1": "0.10.2" 6 | } 7 | -------------------------------------------------------------------------------- /resources/screenshots/task-move.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tgrosinger/slated-obsidian/HEAD/resources/screenshots/task-move.png -------------------------------------------------------------------------------- /resources/screenshots/configure-repetition.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tgrosinger/slated-obsidian/HEAD/resources/screenshots/configure-repetition.gif -------------------------------------------------------------------------------- /resources/screenshots/move-incomplete-tasks.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tgrosinger/slated-obsidian/HEAD/resources/screenshots/move-incomplete-tasks.gif -------------------------------------------------------------------------------- /resources/screenshots/slated-command-palette.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tgrosinger/slated-obsidian/HEAD/resources/screenshots/slated-command-palette.png -------------------------------------------------------------------------------- /resources/screenshots/task-repeat-config-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tgrosinger/slated-obsidian/HEAD/resources/screenshots/task-repeat-config-1.png -------------------------------------------------------------------------------- /resources/screenshots/task-repeat-config-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tgrosinger/slated-obsidian/HEAD/resources/screenshots/task-repeat-config-2.png -------------------------------------------------------------------------------- /tests/__mocks__/obsidian.ts: -------------------------------------------------------------------------------- 1 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class 2 | export class Notice { 3 | constructor(message: string) {} 4 | } 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Intellij 2 | *.iml 3 | .idea 4 | 5 | # npm 6 | node_modules 7 | package-lock.json 8 | 9 | # build 10 | main.js 11 | *.js.map 12 | 13 | # yarn 14 | yarn-error.log 15 | yarn-cache 16 | 17 | # Obsidian 18 | 19 | data.json 20 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | verbose: true, 3 | preset: 'ts-jest', 4 | transform: { 5 | '^.+\\.svelte$': ['svelte-jester', { preprocess: true }], 6 | '^.+\\.ts$': 'ts-jest', 7 | }, 8 | moduleFileExtensions: ['js', 'ts', 'svelte'], 9 | modulePathIgnorePatterns: ['yarn-cache'], 10 | }; 11 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Set the default behavior, in case people don’t have core.autocrlf set. 2 | * text=auto 3 | 4 | # Declare files that will always have LF line endings on checkout. 5 | *.css text eol=lf 6 | *.js text eol=lf 7 | *.json text eol=lf 8 | *.md text eol=lf 9 | *.md text eol=lf 10 | *.sh text eol=lf 11 | *.ts text eol=lf 12 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "slated-obsidian", 3 | "name": "Slated", 4 | "author": "Tony Grosinger", 5 | "authorUrl": "https://grosinger.net", 6 | "description": "Task Management - schedule, move, and repeat tasks", 7 | "isDesktopOnly": false, 8 | "version": "0.5.2", 9 | "minAppVersion": "0.12.1", 10 | "js": "main.js" 11 | } 12 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "tabWidth": 2, 4 | "trailingComma": "all", 5 | "overrides": [ 6 | { 7 | "files": ".prettierrc", 8 | "options": { 9 | "parser": "json" 10 | } 11 | }, 12 | { 13 | "files": "*.yml", 14 | "options": { 15 | "tabWidth": 2, 16 | "singleQuote": false 17 | } 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | branches: [main] 5 | pull_request: 6 | branches: [main] 7 | jobs: 8 | validate: 9 | runs-on: ubuntu-latest 10 | steps: 11 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 12 | - uses: actions/checkout@v2 13 | 14 | - name: Install modules 15 | run: yarn 16 | 17 | - name: Run build 18 | run: yarn run build 19 | 20 | - name: Run ESLint 21 | run: yarn run eslint 22 | 23 | - name: Run tests 24 | run: yarn run test 25 | -------------------------------------------------------------------------------- /yarn: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Use this command just as you would `yarn`. 4 | # Examples: 5 | # 6 | # ./yarn.sh help 7 | # ./yarn.sh i # Install dependencies locally using package-lock.json 8 | # ./yarn.sh run eslint 9 | # ./yarn.sh i -E -D "eslint" # Install the eslint package as a dev-only dep 10 | # ./yarn.sh i -E "react" # Install the react package as a dep 11 | 12 | docker run --rm \ 13 | -it \ 14 | --env YARN_CACHE_FOLDER=/code/yarn-cache \ 15 | -v "$(pwd)":/code \ 16 | -w /code \ 17 | --entrypoint yarn \ 18 | node:14.15.1-slim \ 19 | "$@" 20 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/svelte/tsconfig.json", 3 | "include": [ "src/**/*", "tests/**/*" ], 4 | "exclude": [ "node_modules/*" ], 5 | "compilerOptions": { 6 | "baseUrl": ".", 7 | "inlineSources": true, 8 | "sourceMap": true, 9 | "module": "ESNext", 10 | "target": "es6", 11 | "noImplicitAny": true, 12 | "importHelpers": true, 13 | "types": [ 14 | "node", 15 | "svelte", 16 | "jest" 17 | ], 18 | "lib": [ 19 | "dom", 20 | "es6", 21 | "scripthost", 22 | "es2019" 23 | ], 24 | "paths": { 25 | "src": ["src/*", "tests/*"] 26 | } 27 | }, 28 | } 29 | -------------------------------------------------------------------------------- /src/settings.ts: -------------------------------------------------------------------------------- 1 | import type { ILocaleOverride, IWeekStartOption } from 'obsidian-calendar-ui'; 2 | 3 | export interface ISettings { 4 | tasksHeader: string; 5 | blankLineAfterHeader: boolean; 6 | preserveMovedTasks: boolean; 7 | 8 | // Calendar view 9 | localeOverride: ILocaleOverride; 10 | weekStart: IWeekStartOption; 11 | } 12 | 13 | const defaultSettings: ISettings = { 14 | tasksHeader: '## Tasks', 15 | blankLineAfterHeader: true, 16 | preserveMovedTasks: false, 17 | 18 | localeOverride: 'system-default', 19 | weekStart: 'locale', 20 | }; 21 | 22 | export const settingsWithDefaults = ( 23 | settings: Partial, 24 | ): ISettings => ({ ...defaultSettings, ...settings }); 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: enhancement, needs-review 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /src/ui/TaskMove.svelte: -------------------------------------------------------------------------------- 1 | 22 | 23 |

Select a day for the task to be moved to:

24 | 25 | 31 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import svelte from 'rollup-plugin-svelte'; 2 | import autoPreprocess from 'svelte-preprocess'; 3 | import typescript from '@rollup/plugin-typescript'; 4 | import { nodeResolve } from '@rollup/plugin-node-resolve'; 5 | import commonjs from '@rollup/plugin-commonjs'; 6 | 7 | export default { 8 | input: 'src/main.ts', 9 | output: { 10 | dir: '.', 11 | sourcemap: 'inline', 12 | format: 'cjs', 13 | exports: 'default', 14 | }, 15 | external: ['obsidian'], 16 | plugins: [ 17 | svelte({ 18 | emitCss: false, 19 | preprocess: autoPreprocess(), 20 | }), 21 | typescript({ sourceMap: true }), 22 | nodeResolve({ 23 | browser: true, 24 | dedupe: ['svelte'], 25 | }), 26 | commonjs({ 27 | include: 'node_modules/**', 28 | }), 29 | ], 30 | }; 31 | -------------------------------------------------------------------------------- /src/localization.ts: -------------------------------------------------------------------------------- 1 | import type { App } from 'obsidian'; 2 | import { configureGlobalMomentLocale } from 'obsidian-calendar-ui'; 3 | import type { ISettings } from 'src/settings'; 4 | 5 | export const shouldConfigureGlobalMoment = (app: App): boolean => 6 | // XXX: If the calendar plugin is installed, just use those settings. 7 | // Otherwise, we are responsible for configuring weekStart and localeOverride. 8 | !(app as any).plugins.getPlugin('calendar')?._loaded; 9 | 10 | export const tryToConfigureGlobalMoment = ( 11 | app: App, 12 | settings: ISettings, 13 | ): void => { 14 | // XXX: If the calendar plugin is installed, just use those settings. 15 | // Otherwise, we are responsible for configuring weekStart and localeOverride. 16 | if (shouldConfigureGlobalMoment(app)) { 17 | configureGlobalMomentLocale(settings.localeOverride, settings.weekStart); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug, needs-review 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Obsidian Version: [e.g. v0.9.10] (Settings → About → Current Version) 29 | - Slated Version: [e.g. 0.4.0] (Settings → Third-party plugin → Scroll to Slated) 30 | 31 | **Additional context** 32 | Add any other context about the problem here. 33 | -------------------------------------------------------------------------------- /src/ui/ButtonGroup.svelte: -------------------------------------------------------------------------------- 1 | 48 | 49 | {#each _buttons as button} 50 | 61 | {/each} 62 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | /* 2 | * Custom preview-mode rendering 3 | */ 4 | 5 | .slated-task-icon { 6 | height: 17px; 7 | width: 17px; 8 | margin-left: 5px; 9 | margin-right: 6px; 10 | position: relative; 11 | top: 3px; 12 | fill: var(--text-muted); 13 | stroke: var(--text-muted); 14 | } 15 | 16 | /* 17 | * Slated Task View 18 | */ 19 | 20 | .slated-task-view-filter-icon { 21 | height: 20px; 22 | width: 20px; 23 | margin-left: 5px; 24 | margin-right: 6px; 25 | position: relative; 26 | top: 3px; 27 | fill: var(--text-on-accent); 28 | stroke: var(--text-on-accent); 29 | } 30 | 31 | .slated-task-view-filter-button { 32 | padding: 8px 5px; 33 | } 34 | 35 | /* 36 | * Task Repetition Modal 37 | */ 38 | 39 | .slated-modal input { 40 | border-radius: 0.5em; 41 | padding: 19px 14px; 42 | } 43 | 44 | #slated-interval-selector { 45 | width: 60px; 46 | } 47 | 48 | #slated-frequency-selector { 49 | width: 103px; 50 | } 51 | 52 | #slated-onthe-selector { 53 | width: 60px; 54 | } 55 | 56 | .slated-months-btn-group button { 57 | padding: 6px 8px; 58 | margin: 3px 6px 3px 0; 59 | } 60 | 61 | .slated-days-btn-group button { 62 | padding: 6px 8px; 63 | margin: 3px 6px 3px 0; 64 | } 65 | 66 | #slated-selected-weeks ul { 67 | list-style: none; 68 | } 69 | 70 | #slated-repetition-preview { 71 | width: 100%; 72 | } 73 | 74 | #slated-save-repetition-config { 75 | margin-top: 3px; 76 | } 77 | 78 | /* 79 | * Task Move Modal 80 | */ 81 | 82 | .slated-move-option label { 83 | color: var(--text-muted); 84 | font-size: small; 85 | } 86 | 87 | /* 88 | * Donate - in Settings 89 | */ 90 | 91 | .slated-donation { 92 | width: 70%; 93 | margin: 0 auto; 94 | text-align: center; 95 | } 96 | 97 | .slated-donate-button { 98 | margin: 10px; 99 | } 100 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "slated-obsidian", 3 | "version": "0.5.2", 4 | "description": "Task management - schedule, move, and repeat tasks", 5 | "main": "main.js", 6 | "scripts": { 7 | "test": "jest", 8 | "test-watch": "jest --watchAll", 9 | "dev": "rollup --config rollup.config.js -w", 10 | "build": "rollup --config rollup.config.js", 11 | "prettier": "prettier --write 'src/**/*.+(ts|tsx|json|html|css)'", 12 | "eslint": "eslint . --ext .ts,.tsx --fix" 13 | }, 14 | "keywords": [], 15 | "author": "Tony Grosinger", 16 | "license": "GPL-3.0", 17 | "devDependencies": { 18 | "@rollup/plugin-commonjs": "17.0.0", 19 | "@rollup/plugin-node-resolve": "11.0.1", 20 | "@rollup/plugin-typescript": "8.1.0", 21 | "@testing-library/svelte": "3.0.2", 22 | "@tsconfig/svelte": "1.0.10", 23 | "@types/jest": "26.0.18", 24 | "@types/node": "^14.14.2", 25 | "@typescript-eslint/eslint-plugin": "4.6.0", 26 | "@typescript-eslint/parser": "4.6.0", 27 | "eslint": "7.12.1", 28 | "eslint-plugin-import": "2.22.1", 29 | "eslint-plugin-jsdoc": "30.7.3", 30 | "eslint-plugin-prefer-arrow": "1.2.2", 31 | "eslint-plugin-simple-import-sort": "5.0.3", 32 | "jest": "26.6.3", 33 | "jest-mock-extended": "1.0.10", 34 | "moment": "2.29.1", 35 | "obsidian": "https://github.com/obsidianmd/obsidian-api/archive/eb459522e7e35983e3e6c2358301a21b26de7b64.tar.gz", 36 | "rollup": "2.35.1", 37 | "rollup-plugin-svelte": "7.0.0", 38 | "svelte-check": "1.1.34", 39 | "svelte-jester": "1.3.0", 40 | "svelte-preprocess": "4.6.9", 41 | "ts-jest": "26.4.4", 42 | "tslib": "^2.0.3", 43 | "typescript": "^4.0.3" 44 | }, 45 | "dependencies": { 46 | "neverthrow": "3.0.0", 47 | "obsidian-calendar-ui": "0.3.12", 48 | "obsidian-daily-notes-interface": "0.9.2", 49 | "rrule": "2.6.8", 50 | "svelte": "3.32.3" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/ui/WeekDaysOfMonthSelector.svelte: -------------------------------------------------------------------------------- 1 | 52 | 53 |
54 |
    55 | {#each $selectedWeeks as week} 56 |
  • 57 | 65 | 74 | {#if $selectedWeeks.length > 1} 75 | 76 | {/if} 77 |
  • 78 | {/each} 79 |
80 | 81 |
82 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | on: 3 | push: 4 | tags: ["*"] 5 | env: 6 | PLUGIN_NAME: slated-obsidian 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 12 | - uses: actions/checkout@v2 13 | 14 | - name: Install modules 15 | run: yarn 16 | 17 | - name: Run build 18 | run: yarn run build 19 | 20 | - name: Package 21 | run: | 22 | mkdir ${{ env.PLUGIN_NAME }} 23 | cp main.js manifest.json styles.css ${{ env.PLUGIN_NAME }} 24 | zip -r ${{ env.PLUGIN_NAME}}.zip ${{ env.PLUGIN_NAME }} 25 | echo "::set-output name=tag_name::$(git tag --sort version:refname | tail -n 1)" 26 | 27 | - name: Create Release 28 | id: create_release 29 | uses: actions/create-release@v1 30 | env: 31 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 32 | VERSION: ${{ github.ref }} 33 | with: 34 | tag_name: ${{ github.ref }} 35 | release_name: ${{ github.ref }} 36 | draft: true 37 | prerelease: false 38 | 39 | - name: Upload artifacts 40 | id: upload-artifacts 41 | uses: actions/upload-release-asset@v1 42 | env: 43 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 44 | with: 45 | upload_url: ${{ steps.create_release.outputs.upload_url }} 46 | asset_path: ./${{ env.PLUGIN_NAME }}.zip 47 | asset_name: ${{ env.PLUGIN_NAME }}-${{ github.ref }}.zip 48 | asset_content_type: application/zip 49 | 50 | - name: Upload main.js 51 | id: upload-main 52 | uses: actions/upload-release-asset@v1 53 | env: 54 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 55 | with: 56 | upload_url: ${{ steps.create_release.outputs.upload_url }} 57 | asset_path: ./main.js 58 | asset_name: main.js 59 | asset_content_type: text/javascript 60 | 61 | - name: Upload manifest.json 62 | id: upload-manifest 63 | uses: actions/upload-release-asset@v1 64 | env: 65 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 66 | with: 67 | upload_url: ${{ steps.create_release.outputs.upload_url }} 68 | asset_path: ./manifest.json 69 | asset_name: manifest.json 70 | asset_content_type: application/json 71 | 72 | - name: Upload styles.css 73 | id: upload-styles 74 | uses: actions/upload-release-asset@v1 75 | env: 76 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 77 | with: 78 | upload_url: ${{ steps.create_release.outputs.upload_url }} 79 | asset_path: ./styles.css 80 | asset_name: styles.css 81 | asset_content_type: text/css 82 | -------------------------------------------------------------------------------- /src/vault.ts: -------------------------------------------------------------------------------- 1 | import type { Moment } from 'moment'; 2 | import type { TFile, Vault } from 'obsidian'; 3 | import { 4 | createDailyNote, 5 | getAllDailyNotes, 6 | getAllMonthlyNotes, 7 | getAllWeeklyNotes, 8 | getDailyNote, 9 | getDailyNoteSettings, 10 | getMonthlyNoteSettings, 11 | getWeeklyNoteSettings, 12 | IPeriodicNoteSettings, 13 | } from 'obsidian-daily-notes-interface'; 14 | 15 | export type PeriodicNoteID = string; 16 | 17 | type IGranularity = 'day' | 'week' | 'month'; 18 | 19 | export class VaultIntermediate { 20 | private readonly vault: Vault; 21 | 22 | constructor(vault: Vault) { 23 | this.vault = vault; 24 | } 25 | 26 | public getDailyNotes = (): Record => getAllDailyNotes(); 27 | public getWeeklyNotes = (): Record => getAllWeeklyNotes(); 28 | public getMonthlyNotes = (): Record => getAllMonthlyNotes(); 29 | 30 | public getDailyNote = (date: Moment): Promise => { 31 | const desiredNote = getDailyNote(date, getAllDailyNotes()); 32 | if (desiredNote) { 33 | return Promise.resolve(desiredNote); 34 | } 35 | return this.createDailyNote(date); 36 | }; 37 | 38 | public createDailyNote = (date: Moment): Promise => 39 | createDailyNote(date); 40 | 41 | public findMomentForDailyNote = (file: TFile): Moment | undefined => { 42 | const { format } = getDailyNoteSettings(); 43 | const date = window.moment(file.basename, format, true); 44 | return date.isValid() ? date : null; 45 | }; 46 | 47 | public fileNameForMoment = (date: Moment): string => 48 | date.format(getDailyNoteSettings().format); 49 | 50 | public readFile = (file: TFile, useCache: boolean): Promise => 51 | useCache ? this.vault.cachedRead(file) : this.vault.read(file); 52 | 53 | public writeFile = (file: TFile, data: string): Promise => 54 | this.vault.modify(file, data); 55 | 56 | /** 57 | * NOTE: Untested, ended up needing after writing this, 58 | * but it seemed useful so I kept it just in case. 59 | * 60 | * Returns a periodic note ID for the file. 61 | * NOTE: The values returned are not actually file names, but values similar to: 62 | * - day-2021-02-12T00:00:00-08:00 63 | * - week-2021-02-21T00:00:00-08:00 64 | * - month-2021-02-01T00:00:00-08:00 65 | */ 66 | public getPeriodicNoteIDForFile = (file: TFile): PeriodicNoteID => { 67 | const dSettings = getDailyNoteSettings(); 68 | let uid = this.getDateUID(file, dSettings, 'day'); 69 | if (uid) { 70 | return uid; 71 | } 72 | 73 | const wSettings = getWeeklyNoteSettings(); 74 | uid = this.getDateUID(file, wSettings, 'week'); 75 | if (uid) { 76 | return uid; 77 | } 78 | 79 | const mSettings = getMonthlyNoteSettings(); 80 | uid = this.getDateUID(file, mSettings, 'month'); 81 | if (uid) { 82 | return uid; 83 | } 84 | }; 85 | 86 | /** 87 | * NOTE: Untested, ended up needing after writing this, 88 | * but it seemed useful so I kept it just in case. 89 | */ 90 | private readonly getDateUID = ( 91 | file: TFile, 92 | settings: IPeriodicNoteSettings, 93 | granularity: IGranularity, 94 | ): PeriodicNoteID | undefined => { 95 | if (settings.folder && !file.path.startsWith(settings.folder)) { 96 | return undefined; // Not in the right folder 97 | } 98 | 99 | const date = window.moment(file.basename, settings.format, true); 100 | if (date.isValid()) { 101 | return `${granularity}-${date.startOf(granularity).format()}`; 102 | } 103 | }; 104 | } 105 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Slated for Obsidian 2 | 3 | ## ⚠ Project Archived 4 | 5 | Afer much thought and experimentation, I have decided to change directions with how I manage tasks in Obsidian. The approach I am taking now is different enough that I felt it warranted a new plugin, rather than adapting Slated and foisting it on the existing users. The new plugin is called [tq](https://github.com/tgrosinger/tq-obsidian) and is availalbe in the community plugins list. 6 | 7 | If you would like to carry on the torch of Slated, please reach out to me and we can discuss un-archiving this repository. 8 | 9 | Thank you for your understanding and support! 10 | 11 | ## Overview 12 | 13 | Advanced task management in the Obsidian knowledgebase. 14 | 15 | - Setup repeating tasks 16 | - Defer tasks to another daily note 17 | - Move all incomplete tasks to today's daily note 18 | - Works in Obsidian Mobile 19 | - All in 100% Obsidian Markdown! 20 | 21 | ## Screenshots 22 | 23 | ![move-incomplete-tasks](https://raw.githubusercontent.com/tgrosinger/slated-obsidian/main/resources/screenshots/move-incomplete-tasks.gif) 24 | 25 | ![task-repeat-config-1](https://raw.githubusercontent.com/tgrosinger/slated-obsidian/main/resources/screenshots/task-repeat-config-1.png) 26 | 27 | ![configure-repetition](https://raw.githubusercontent.com/tgrosinger/slated-obsidian/main/resources/screenshots/configure-repetition.gif) 28 | 29 | ## How to use 30 | 31 | Tasks are created using normal markdown syntax, for example `- [ ] Water the 32 | plants`. Once a task is created, configure repetition or move the task using 33 | the commands added by this plugin. This is easiest to do by either binding 34 | them to a hotkey, or using the command palette. 35 | 36 | ![slated-command-palette](https://raw.githubusercontent.com/tgrosinger/slated-obsidian/main/resources/screenshots/slated-command-palette.png) 37 | 38 | Repetition configs can also be edited manually, however using the interface 39 | helps ensure a valid repetition config has been created. 40 | 41 | Tasks can also be moved to another day. 42 | 43 | ![task-move](https://raw.githubusercontent.com/tgrosinger/slated-obsidian/main/resources/screenshots/task-move.png) 44 | 45 | ## Task Format 46 | 47 | - [ ] This task is incomplete and repeats ; Every Monday and Tuesday 48 | - [-] This repeating task occurence was skipped ; Every Sunday 49 | - [x] This task was completed 50 | - [ ] This task has sub-items that will move with it 51 | - [ ] Sub items can be a task 52 | - Or not 53 | - [ ] Tasks can have non-list subcontent too 54 | Such as this line 55 | 56 | ### More Examples 57 | 58 | - [ ] Go to the dentist ;8:30am 59 | - [x] Make ferry reservation 📅 7:00am 60 | - [ ] (A) Vacuum the stairs 61 | - [ ] Make bread ;Every Sunday 62 | - [ ] Bring dog to the vet 63 | - [ ] Do the dishes 📅 Every weekday at 5pm 64 | 65 | ## Pricing 66 | 67 | This plugin is provided to everyone for free, however if you would like to 68 | say thanks or help support continued development, feel free to send a little 69 | my way through one of the following methods: 70 | 71 | [![GitHub Sponsors](https://img.shields.io/github/sponsors/tgrosinger?style=social)](https://github.com/sponsors/tgrosinger) 72 | [![Paypal](https://img.shields.io/badge/paypal-tgrosinger-yellow?style=social&logo=paypal)](https://paypal.me/tgrosinger) 73 | [BuyMeACoffee](https://www.buymeacoffee.com/tgrosinger) 74 | 75 | ## Credits 76 | 77 | A huge thank you to [Liam Cain](https://github.com/liamcain) for adapting the 78 | [Obsidian Calendar 79 | Plugin](https://github.com/liamcain/obsidian-calendar-plugin) and making it 80 | broadly usable by other plugins! 81 | -------------------------------------------------------------------------------- /Design.md: -------------------------------------------------------------------------------- 1 | # Design of Slated 2 | 3 | This space contains some of the original design brainstorming for this 4 | plugin. Not all of it is what was actually implemented, but it might be 5 | useful to see how the plugin got to where it is today. 6 | 7 | ## Design Requirements 8 | 9 | - Maintain compatibility with Markdown 10 | - This is essential for ease of use (especially on mobile) and to avoid lock-in 11 | - Obsidian variations from official Markdown are allowed, such as block links 12 | - Use well understood patterns wherever possible 13 | - Checkboxes to indicate open/done status for example 14 | - Existing tag and link syntax 15 | - Adopt priority syntax from todo.txt 16 | 17 | ## Inspiration 18 | 19 | - org-mode 20 | - [TODO items manual](https://orgmode.org/manual/TODO-Items.html) 21 | - [Date and times manual](https://orgmode.org/manual/Dates-and-Times.html) 22 | - [NotePlan](https://noteplan.co/) 23 | 24 | ## User Experience 25 | 26 | - Use markdown task lists for each todo item 27 | - Sub-lists can be used to add subtasks, if the list item has a checkbox 28 | - The markdown should always be the source of truth, but alternate view can improve user experience: 29 | - A modal can be used for appending repetition config to a task 30 | - Tasks with due-dates should be either stored in, or transcluded into the daily note for that day 31 | - See the [Review plugin](https://github.com/ryanjamurphy/review-obsidian) 32 | - With this simplification, dates no longer need to be stored, only repeat config 33 | - Priorities 34 | - todo.txt uses `(A)` at the beginning of a task 35 | - org-mode uses `[A]` just after the `TODO` 36 | - Block IDs 37 | - When a task is going to be moved or has a repetition pattern added, generate a block ID 38 | - The block ID will be used to tie all tasks in a repetition back to the original 39 | - The block ID will be used to tie a task that has been moved back to it's originally scheduled location 40 | - A popup will make it easy to navigate to previous/upcoming occurences of this task 41 | - Recurrence 42 | - Denoted with either a semicolon, or 📅 43 | - If the task recurrence has a definite end, all tasks should be created and put into daily notes right away 44 | - For tasks which have no definite end, a configurable number into the future will be created 45 | - This is checked dynamically whenever a recurring task is detected 46 | - Optionally, generate and include links to next and previous occurrence of a task 47 | - This may not be necessary if a popup can aid in navigating to other occurences using the block ID 48 | - Using [rrule](https://www.npmjs.com/package/rrule) library, which supports NLP or very advanced config 49 | - Recurrence is stored in plain text after a task, but a popup will help configure the pattern. 50 | - Task moving 51 | - Inspired by NotePlan, tasks can be moved to another date. 52 | - Moved tasks will contain the block ID from the original location. 53 | - Original location will remain in place, be crossed out, checked, and have block ID 54 | 55 | ## Integration 56 | 57 | Let's try to prevent proliferation of similar plugins that each has a subset of what a user is looking for by making it clear this plugin is for and by the community! Additionally, look for areas where tight integration with other plugins will make both richer. 58 | 59 | - How can this integrate with the Calendar plugin? (@liamcain) 60 | - This plugin already adds a fantastic calendar to Obsidian which links to daily notes 61 | - The calendar plugin might be usable embedded as a date picker ([tracking thread](https://github.com/liamcain/obsidian-calendar-plugin/issues/59)) 62 | - See [this Github thread](https://github.com/ryanjamurphy/review-obsidian/issues/8) 63 | - How can this integrate with the Daily Notes plugin? (built-in) 64 | - [This library](https://www.npmjs.com/package/obsidian-daily-notes-interface) replicates the daily notes functionality, but allows creating notes in the future. 65 | - A task which has a due date should be stored or transcluded into the corresponding daily note 66 | - The [review plugin](https://github.com/ryanjamurphy/review-obsidian) is perfect for this 67 | - Agenda view may be solved by an upcoming plugin from @ryanjamurphy 68 | > An Obsidian plugin to track overdue items (e.g., tasks in daily notes before today not yet completed/moved/cancelled) 69 | - Tasks with specified times can show OS notifications 70 | - [Example from Day Planner](https://github.com/lynchjames/obsidian-day-planner/blob/main/src/main.ts#L120) 71 | -------------------------------------------------------------------------------- /src/ui/TaskRepeat.svelte: -------------------------------------------------------------------------------- 1 | 67 | 68 |
69 |

Task Repetition

70 |
71 | Every 72 | 77 | 78 | 79 | 96 | 97 | {#if $repeater.frequency === Frequency.Weekly} 98 |
99 | 103 |
104 | {/if} 105 | 106 | {#if $repeater.frequency === Frequency.Yearly} 107 |
108 | 112 |
113 | {/if} 114 | 115 | {#if $repeater.frequency === Frequency.Monthly || $repeater.frequency === Frequency.Yearly} 116 |
117 | 121 | 122 | {#if monthlyRepeatType == 'onThe'} 123 | 129 | 133 | {:else} 134 | 135 | 138 | 139 | {/if} 140 |
141 | {/if} 142 |
143 | 144 |

Preview

145 | 146 | 151 | 152 | 153 |
154 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | parser: "@typescript-eslint/parser", 4 | parserOptions: { 5 | ecmaVersion: 2020, 6 | sourceType: "module", 7 | project: ["./tsconfig.json"], 8 | }, 9 | plugins: [ 10 | "@typescript-eslint", 11 | "import", 12 | "jsdoc", 13 | "prefer-arrow", 14 | "simple-import-sort", 15 | ], 16 | rules: { 17 | "@typescript-eslint/array-type": "error", 18 | "@typescript-eslint/await-thenable": "error", 19 | "@typescript-eslint/consistent-type-assertions": "error", 20 | "@typescript-eslint/consistent-type-definitions": "error", 21 | "@typescript-eslint/explicit-function-return-type": [ 22 | "error", 23 | { allowExpressions: true }, 24 | ], 25 | "@typescript-eslint/explicit-member-accessibility": [ 26 | "error", 27 | { 28 | accessibility: "explicit", 29 | overrides: { 30 | accessors: "explicit", 31 | constructors: "off", 32 | parameterProperties: "explicit", 33 | }, 34 | }, 35 | ], 36 | "@typescript-eslint/member-ordering": [ 37 | "error", 38 | { 39 | default: [ 40 | "public-static-field", 41 | "protected-static-field", 42 | "private-static-field", 43 | "public-static-method", 44 | "protected-static-method", 45 | "private-static-method", 46 | "public-instance-field", 47 | "protected-instance-field", 48 | "private-instance-field", 49 | "constructor", 50 | "public-instance-method", 51 | "protected-instance-method", 52 | "private-instance-method", 53 | ], 54 | }, 55 | ], 56 | "@typescript-eslint/naming-convention": [ 57 | "error", 58 | { 59 | selector: "variable", 60 | format: ["camelCase", "PascalCase", "snake_case", "UPPER_CASE"], 61 | leadingUnderscore: "allow", 62 | }, 63 | { selector: "typeLike", format: ["PascalCase"] }, 64 | { selector: "enumMember", format: ["PascalCase"] }, 65 | ], 66 | // "@typescript-eslint/no-explicit-any": "error", 67 | "@typescript-eslint/no-extraneous-class": "error", 68 | //"@typescript-eslint/no-namespace": "error", 69 | "@typescript-eslint/no-non-null-assertion": "error", 70 | "@typescript-eslint/no-this-alias": ["error", { allowDestructuring: true }], 71 | "@typescript-eslint/no-unnecessary-boolean-literal-compare": "error", 72 | "@typescript-eslint/no-unnecessary-type-assertion": "error", 73 | "@typescript-eslint/no-unused-expressions": "error", 74 | "@typescript-eslint/prefer-function-type": "error", 75 | "@typescript-eslint/prefer-readonly": "error", 76 | "@typescript-eslint/quotes": ["error", "single", { avoidEscape: true }], 77 | "arrow-body-style": ["error", "as-needed"], 78 | "constructor-super": "error", 79 | curly: ["error", "multi-line"], 80 | eqeqeq: "error", 81 | "import/no-duplicates": "error", 82 | "jsdoc/check-alignment": "error", 83 | "new-parens": "error", 84 | "no-caller": "error", 85 | "no-cond-assign": ["error", "always"], 86 | "no-debugger": "error", 87 | "no-duplicate-case": "error", 88 | "no-else-return": "error", 89 | "no-empty": "error", 90 | "no-eval": "error", 91 | "no-fallthrough": "error", 92 | "no-new-wrappers": "error", 93 | "no-param-reassign": "error", 94 | "no-restricted-globals": [ 95 | "error", 96 | "length", 97 | "name", 98 | { 99 | name: "isFinite", 100 | message: "Use the more strict Number.isFinite.", 101 | }, 102 | { 103 | name: "isNaN", 104 | message: "Use the more strict Number.isNaN.", 105 | }, 106 | ], 107 | "no-restricted-properties": [ 108 | "error", 109 | { 110 | property: "bind", 111 | message: "Native? Use an arrow function. jQuery? Use .on()", 112 | }, 113 | ], 114 | "no-return-await": "error", 115 | "no-self-compare": "error", 116 | "no-shadow": "off", 117 | "@typescript-eslint/no-shadow": "error", 118 | "no-sequences": "error", 119 | "no-sparse-arrays": "error", 120 | "no-template-curly-in-string": "error", 121 | "no-throw-literal": "error", 122 | "no-unsafe-finally": "error", 123 | "no-var": "error", 124 | "no-with": "error", 125 | "object-shorthand": "error", 126 | "one-var": ["error", "never"], 127 | "prefer-arrow/prefer-arrow-functions": "error", 128 | "prefer-const": ["error", { destructuring: "all" }], 129 | "prefer-object-spread": "error", 130 | "prefer-rest-params": "error", 131 | radix: "error", 132 | "simple-import-sort/sort": [ 133 | "error", 134 | { 135 | groups: [ 136 | // Side effect imports (e.g. `import 'foo';`) 137 | ["^\\u0000"], 138 | // Third-party code 139 | [ 140 | "^(@susisu/mte-kernel,obsidian)(/.*|$)", 141 | ], 142 | // Our intra-package imports 143 | ["(?; 15 | 16 | constructor( 17 | vault: VaultIntermediate, 18 | metadataCache: MetadataCache, 19 | settings: ISettings, 20 | ) { 21 | this.vault = vault; 22 | this.metadataCache = metadataCache; 23 | this.settings = settings; 24 | this.taskCache = {}; 25 | } 26 | 27 | /** 28 | * Scan the whole file, looking for tasks with repetition configs. 29 | * For each task found, ensure that subsequent tasks have been created. 30 | * 31 | * This function will: 32 | * - Modify the provided file to add block references to repeating tasks 33 | * - Create missing daily notes needed by repeating tasks 34 | * - Insert all occurences of a finite repeating task 35 | * - Insert a configurable number of infinite repeating tasks 36 | */ 37 | public readonly processFile = async (file: TFile): Promise => { 38 | if (!fileIsDailyNote(file, this.vault)) { 39 | console.debug( 40 | 'Slated: Not in a daily note, not processing contained tasks', 41 | ); 42 | return; 43 | } 44 | 45 | const tasks = await this.getFileTasks(file); 46 | const newlyCompletedTasks = this.filterNewlyCompletedTasks( 47 | file.basename, 48 | tasks, 49 | ); 50 | this.taskCache[file.basename] = tasks; 51 | return this.propogateCompletedTasks(newlyCompletedTasks); 52 | }; 53 | 54 | /** 55 | * moveIncompleted moves all tasks in a file which are not complete to the 56 | * daily note for the provided moment. 57 | * 58 | * Tasks are moved one at a time so that we do not duplicate sub-tasks, and 59 | * so that we are not confused by changing line numbers in the source file as 60 | * we remove tasks. It's not very efficient, but it does seem to work. 61 | */ 62 | public readonly moveIncompleted = async ( 63 | file: TFile, 64 | to: Moment, 65 | ): Promise => { 66 | while (true) { 67 | const tasks = await this.getFileTasks(file); 68 | if (!tasks || !tasks.length) { 69 | return; 70 | } 71 | const firstIncomplete = tasks.find((task) => task.incomplete); 72 | if (!firstIncomplete) { 73 | return; 74 | } 75 | 76 | await firstIncomplete.move(to); 77 | } 78 | }; 79 | 80 | public readonly getCachedTasksForFile = (file: TFile): TaskLine[] => 81 | this.taskCache[file.basename]; 82 | 83 | public readonly getFileTasks = async (file: TFile): Promise => { 84 | const cachedListItems = this.metadataCache.getFileCache(file).listItems; 85 | if (!cachedListItems || cachedListItems.length === 0) { 86 | return []; 87 | } 88 | 89 | const fileContents = await this.vault.readFile(file, false); 90 | const splitFileContents = fileContents.split('\n'); 91 | 92 | // TODO: Pass info about list start and parent 93 | 94 | return cachedListItems 95 | .filter((li) => li.task) 96 | .map((li) => { 97 | return new TaskLine( 98 | li.position.start.line, 99 | file, 100 | splitFileContents, 101 | this.vault, 102 | this.settings, 103 | ); 104 | }); 105 | }; 106 | 107 | /** 108 | * Test if this line is a task. This is called for every line in a file after 109 | * every save, so performance is essential. 110 | */ 111 | public readonly isLineTask = (line: string): boolean => { 112 | const trimmed = line.trimStart(); 113 | 114 | // We can rule out anything that is not a list by testing a single char 115 | if (trimmed[0] !== '-') { 116 | return false; 117 | } 118 | 119 | return ( 120 | trimmed.startsWith('- [ ] ') || 121 | trimmed.startsWith('- [x] ') || 122 | trimmed.startsWith('- [X] ') || 123 | trimmed.startsWith('- [-] ') 124 | ); 125 | }; 126 | 127 | private readonly filterNewlyCompletedTasks = ( 128 | filename: string, 129 | tasks: TaskLine[], 130 | ): TaskLine[] => { 131 | const prevTasks = this.taskCache[filename]; 132 | return tasks.filter((task) => { 133 | if (!task.complete) { 134 | return false; 135 | } 136 | 137 | if (!prevTasks) { 138 | // it's complete and there were no previous tasks, so must be new 139 | return true; 140 | } 141 | 142 | for (let i = 0; i < prevTasks.length; i++) { 143 | const prevTask = prevTasks[i]; 144 | if (task.line === prevTask.line) { 145 | // if prevTask complete then not newly completed 146 | return !prevTask.complete; 147 | } 148 | } 149 | 150 | // A newly added task that is also complete. 151 | return true; 152 | }); 153 | }; 154 | 155 | /** 156 | * Create the next occurence for each of the provided tasks. 157 | */ 158 | private readonly propogateCompletedTasks = async ( 159 | tasks: TaskLine[], 160 | ): Promise => { 161 | await Promise.all( 162 | tasks 163 | .filter((task) => task.repeats) 164 | .map((task) => task.createNextRepetition()), 165 | ); 166 | }; 167 | } 168 | -------------------------------------------------------------------------------- /tests/task-handler.test.ts: -------------------------------------------------------------------------------- 1 | import { ISettings, settingsWithDefaults } from '../src/settings'; 2 | import { TaskHandler } from '../src/task-handler'; 3 | import type { VaultIntermediate } from '../src/vault'; 4 | import { mock, MockProxy } from 'jest-mock-extended'; 5 | import moment from 'moment'; 6 | import type { MetadataCache, TFile } from 'obsidian'; 7 | 8 | declare global { 9 | namespace jest { 10 | interface Matchers { 11 | toHaveLines( 12 | expected: string[], 13 | regexLines: number[], 14 | ): CustomMatcherResult; 15 | } 16 | } 17 | } 18 | 19 | expect.extend({ 20 | toHaveLines: ( 21 | received: string, 22 | expected: string[], 23 | regexLines: number[], 24 | ): jest.CustomMatcherResult => { 25 | const receivedLines = received.split('\n'); 26 | 27 | if (receivedLines.length !== expected.length) { 28 | return { 29 | message: () => 30 | `Received array of length ${receivedLines.length} but expected array of length ${expected.length}`, 31 | pass: false, 32 | }; 33 | } 34 | 35 | for (let i = 0; i < receivedLines.length; i++) { 36 | if (regexLines.indexOf(i) !== -1) { 37 | if (!new RegExp(expected[i]).test(receivedLines[i])) { 38 | return { 39 | message: () => 40 | `Index ${i} in received (${receivedLines[i]}) does not Regex-match expected (${expected[i]})`, 41 | pass: false, 42 | }; 43 | } 44 | } else if (receivedLines[i] !== expected[i]) { 45 | return { 46 | message: () => 47 | `Index ${i} in received (${receivedLines[i]}) does not match expected (${expected[i]})`, 48 | pass: false, 49 | }; 50 | } 51 | } 52 | 53 | return { pass: true, message: () => '' }; 54 | }, 55 | }); 56 | 57 | const format = 'YYYY-MM-DD'; 58 | const startDateStr = '2020-12-31'; 59 | const startDate = moment(startDateStr); 60 | 61 | const getMockFileWithBasename = (basename: string): MockProxy => { 62 | const mockFile = mock(); 63 | mockFile.basename = basename; 64 | return mockFile; 65 | }; 66 | 67 | const getMockFileForMoment = (date: moment.Moment): MockProxy => 68 | getMockFileWithBasename(date.format(format)); 69 | 70 | const p = (str: string): Promise => Promise.resolve(str); 71 | 72 | let file: MockProxy; 73 | let vault: jest.Mocked; 74 | let metadataCache: jest.Mocked; 75 | let settings: jest.Mocked; 76 | let taskHandler: TaskHandler; 77 | let fileContents: Record; 78 | 79 | beforeAll(() => { 80 | file = getMockFileForMoment(startDate); 81 | settings = settingsWithDefaults({ 82 | blankLineAfterHeader: true, 83 | }); 84 | }); 85 | 86 | beforeEach(() => { 87 | window.moment = moment; 88 | vault = mock(); 89 | metadataCache = mock(); 90 | taskHandler = new TaskHandler(vault, metadataCache, settings); 91 | 92 | vault.findMomentForDailyNote.mockImplementation((dailyNote) => { 93 | const date = moment(dailyNote.basename, format, true); 94 | return date.isValid() ? date : undefined; 95 | }); 96 | 97 | fileContents = {}; 98 | vault.readFile.mockImplementation((f, useCache) => 99 | Promise.resolve(fileContents[f.basename]), 100 | ); 101 | 102 | vault.writeFile.mockImplementation((f, data) => { 103 | fileContents[f.basename] = data; 104 | return Promise.resolve(); 105 | }); 106 | }); 107 | 108 | describe('taskHandler.processFile', () => { 109 | test('When the file contains only a single task', async () => { 110 | fileContents[file.basename] = '- [ ] a test task ; Every Sunday'; 111 | 112 | await taskHandler.processFile(file); 113 | 114 | expect(fileContents[file.basename]).toEqual( 115 | '- [ ] a test task ; Every Sunday', 116 | ); 117 | }); 118 | 119 | test('When the file contains multiple tasks', async () => { 120 | fileContents[file.basename] = 121 | '- [ ] a test task ; Every Sunday\n- [ ] another task; Every Thursday'; 122 | 123 | await taskHandler.processFile(file); 124 | 125 | expect(fileContents[file.basename]).toHaveLines( 126 | [ 127 | '- [ ] a test task ; Every Sunday', 128 | '- [ ] another task; Every Thursday', 129 | ], 130 | [], 131 | ); 132 | }); 133 | 134 | test('When there is other content in the file too', async () => { 135 | fileContents[file.basename] = [ 136 | '# 2020-12-31', 137 | '', 138 | '## Tasks', 139 | '', 140 | '- [ ] a test task; Every Monday', 141 | ' - a subtask', 142 | '', 143 | '## Notes', 144 | '', 145 | '- These are my notes', 146 | '', 147 | ].join('\n'); 148 | 149 | await taskHandler.processFile(file); 150 | 151 | expect(fileContents[file.basename]).toHaveLines( 152 | [ 153 | '# 2020-12-31', 154 | '', 155 | '## Tasks', 156 | '', 157 | '- [ ] a test task; Every Monday', 158 | ' - a subtask', 159 | '', 160 | '## Notes', 161 | '', 162 | '- These are my notes', 163 | '', 164 | ], 165 | [], 166 | ); 167 | }); 168 | 169 | test('Newly completed tasks are propogated', async () => { 170 | fileContents[file.basename] = '- [ ] a test task ; Every Sunday'; 171 | 172 | const futureFiles: TFile[] = []; 173 | vault.getDailyNote.mockImplementation((date) => { 174 | const mockFile = getMockFileForMoment(date); 175 | futureFiles.push(mockFile); 176 | return Promise.resolve(mockFile); 177 | }); 178 | 179 | await taskHandler.processFile(file); 180 | 181 | fileContents[file.basename] = '- [x] a test task ; Every Sunday'; 182 | 183 | await taskHandler.processFile(file); 184 | 185 | expect(futureFiles).toHaveLength(1); 186 | expect(fileContents[futureFiles[0].basename]).toEqual( 187 | '## Tasks\n\n- [ ] a test task ; Every Sunday\n', 188 | ); 189 | }); 190 | }); 191 | -------------------------------------------------------------------------------- /src/task-cache.ts: -------------------------------------------------------------------------------- 1 | import type { TaskHandler } from './task-handler'; 2 | import type { TaskLine } from './task-line'; 3 | import type { PeriodicNoteID, VaultIntermediate } from './vault'; 4 | import type { TAbstractFile, TFile } from 'obsidian'; 5 | 6 | export enum NoteType { 7 | Day = 1, 8 | Week, 9 | Month, 10 | } 11 | export interface FileTasks { 12 | file: TFile; 13 | type: NoteType; 14 | tasks: TaskLine[]; 15 | } 16 | export class TaskCache { 17 | private dailyNotes: Record; 18 | private weeklyNotes: Record; 19 | private monthlyNotes: Record; 20 | private hasLoaded: boolean; 21 | private subscriptions: { id: number; hook: (val: any) => void }[]; 22 | 23 | private readonly vault: VaultIntermediate; 24 | private readonly taskHandler: TaskHandler; 25 | 26 | /** 27 | * List of Daily, Weekly, and Monthly notes ordered chronologically. 28 | */ 29 | private periodicNoteList: PeriodicNoteID[]; 30 | private taskLineCache: FileTasks[]; 31 | 32 | constructor(taskHandler: TaskHandler, vault: VaultIntermediate) { 33 | this.vault = vault; 34 | this.taskHandler = taskHandler; 35 | this.subscriptions = []; 36 | this.taskLineCache = []; 37 | this.hasLoaded = false; 38 | 39 | // this.initialize(); // non-blocking, calls notify when complete 40 | } 41 | 42 | /** 43 | * The subscribe function implements the Store interface in Svelte. The 44 | * subscribers must be called any time there is a change to the task. 45 | */ 46 | public readonly subscribe = ( 47 | subscription: (value: any) => void, 48 | ): (() => void) => { 49 | const maxID = this.subscriptions.reduce( 50 | (prev, { id }): number => Math.max(prev, id), 51 | 0, 52 | ); 53 | const newID = maxID + 1; 54 | 55 | this.subscriptions.push({ id: newID, hook: subscription }); 56 | subscription(this); 57 | 58 | // Return an unsubscribe function 59 | return () => { 60 | this.subscriptions = this.subscriptions.filter(({ id }) => id !== newID); 61 | console.log(`Removing subscription ${newID}`); 62 | }; 63 | }; 64 | 65 | public get loading(): boolean { 66 | return !this.hasLoaded; 67 | } 68 | 69 | /** 70 | * The set function implements the Store interface in Svelte. We are not 71 | * actually using it to store new values, but it is needed when binding to 72 | * properties. 73 | */ 74 | public readonly set = (_: any): void => {}; 75 | 76 | public get files(): FileTasks[] { 77 | return this.taskLineCache; 78 | } 79 | 80 | public readonly fileOpenHook = async (file: TFile): Promise => { 81 | const cache = this.taskLineCache.find((ft) => ft.file === file); 82 | if (cache) { 83 | cache.tasks = await this.taskHandler.getFileTasks(file); 84 | this.notify(); 85 | } 86 | }; 87 | 88 | public readonly fileCreateHook = (file: TAbstractFile): void => { 89 | // TODO: A more granular addition of the new file would be more efficient 90 | // Cannot call initialize on every file-create event because Obsidian fires 91 | // that event for ever single file when first starting. 92 | // this.initialize(); // non-blocking 93 | }; 94 | 95 | public readonly fileDeleteHook = (file: TAbstractFile): void => { 96 | // TODO: A more granular removal of the file would be more efficient 97 | this.initialize(); // non-blocking 98 | }; 99 | 100 | public readonly fileRenameHook = ( 101 | file: TAbstractFile, 102 | oldPath: string, 103 | ): void => { 104 | // TODO: A more granular update of the file would be more efficient 105 | this.initialize(); // non-blocking 106 | }; 107 | 108 | /** 109 | * Notify subscriptions of a change. 110 | */ 111 | public readonly notify = (): void => { 112 | this.subscriptions.forEach(({ hook }) => hook(this)); 113 | }; 114 | 115 | /** 116 | * Load any necessary state asynchronously 117 | */ 118 | public readonly initialize = async (): Promise => { 119 | console.log('initializing'); 120 | this.dailyNotes = this.vault.getDailyNotes(); 121 | this.weeklyNotes = this.vault.getWeeklyNotes(); 122 | this.monthlyNotes = this.vault.getMonthlyNotes(); 123 | this.periodicNoteList = this.listFiles(); 124 | await this.populateTaskLineCache(); 125 | 126 | this.hasLoaded = true; 127 | this.notify(); 128 | }; 129 | 130 | private readonly getFileForPeriodicNote = (id: PeriodicNoteID): TFile => { 131 | switch (id.split('-', 1)[0]) { 132 | case 'day': 133 | return this.dailyNotes[id]; 134 | case 'week': 135 | return this.weeklyNotes[id]; 136 | case 'month': 137 | return this.monthlyNotes[id]; 138 | } 139 | return undefined; 140 | }; 141 | 142 | private readonly noteTypeForPeriodicNote = (id: PeriodicNoteID): NoteType => { 143 | switch (id.split('-', 1)[0]) { 144 | case 'day': 145 | return NoteType.Day; 146 | case 'week': 147 | return NoteType.Week; 148 | case 'month': 149 | return NoteType.Month; 150 | } 151 | return undefined; 152 | }; 153 | 154 | private readonly populateTaskLineCache = async (): Promise => { 155 | const files = await Promise.all( 156 | this.periodicNoteList.map( 157 | async (periodicNoteID): Promise => { 158 | const file = this.getFileForPeriodicNote(periodicNoteID); 159 | return { 160 | file, 161 | type: this.noteTypeForPeriodicNote(periodicNoteID), 162 | tasks: file ? await this.taskHandler.getFileTasks(file) : [], 163 | }; 164 | }, 165 | ), 166 | ); 167 | 168 | this.taskLineCache = files.filter((f) => f.tasks.length > 0); 169 | this.hasLoaded = true; 170 | }; 171 | 172 | /** 173 | * Returns a list of daily/weekly/monthly note files. 174 | * NOTE: The values returned are not actually file names, but values similar to: 175 | * - day-2021-02-12T00:00:00-08:00 176 | * - week-2021-02-21T00:00:00-08:00 177 | * - month-2021-02-01T00:00:00-08:00 178 | */ 179 | private readonly listFiles = (): PeriodicNoteID[] => { 180 | const dailyNoteKeys = Object.keys(this.dailyNotes).reverse(); 181 | const weeklyNoteKeys = Object.keys(this.weeklyNotes).reverse(); 182 | const monthlyNoteKeys = Object.keys(this.monthlyNotes).reverse(); 183 | 184 | let weeklyI = 0; 185 | let monthlyI = 0; 186 | 187 | const orderedNoteNames: PeriodicNoteID[] = []; 188 | 189 | for (const currentDailyNote of dailyNoteKeys) { 190 | if ( 191 | monthlyNoteKeys.length > monthlyI && 192 | this.after(currentDailyNote, monthlyNoteKeys[monthlyI]) 193 | ) { 194 | orderedNoteNames.push(monthlyNoteKeys[monthlyI]); 195 | monthlyI++; 196 | } 197 | if ( 198 | weeklyNoteKeys.length > weeklyI && 199 | this.after(currentDailyNote, weeklyNoteKeys[weeklyI]) 200 | ) { 201 | orderedNoteNames.push(weeklyNoteKeys[weeklyI]); 202 | weeklyI++; 203 | } 204 | orderedNoteNames.push(currentDailyNote); 205 | } 206 | 207 | for (; weeklyI < weeklyNoteKeys.length; weeklyI++) { 208 | const currentWeeklyNote = weeklyNoteKeys[weeklyI]; 209 | if ( 210 | monthlyNoteKeys.length > monthlyI && 211 | this.after(currentWeeklyNote, monthlyNoteKeys[monthlyI]) 212 | ) { 213 | orderedNoteNames.push(monthlyNoteKeys[monthlyI]); 214 | monthlyI++; 215 | } 216 | orderedNoteNames.push(currentWeeklyNote); 217 | } 218 | 219 | for (; monthlyI < monthlyNoteKeys.length; monthlyI++) { 220 | orderedNoteNames.push(monthlyNoteKeys[monthlyI]); 221 | } 222 | 223 | return orderedNoteNames; 224 | }; 225 | 226 | /** 227 | * Returns true if the first note name is later chronologically than the first. 228 | * Expects note names to be similar to: 229 | * - day-2021-02-12T00:00:00-08:00 230 | * - week-2021-02-21T00:00:00-08:00 231 | * - month-2021-02-01T00:00:00-08:00 232 | */ 233 | private readonly after = (name1: string, name2: string): boolean => { 234 | const d1 = window.moment(name1.substring(name1.indexOf('-') + 1)); 235 | const d2 = window.moment(name2.substring(name2.indexOf('-') + 1)); 236 | return d1.isAfter(d2); 237 | }; 238 | } 239 | -------------------------------------------------------------------------------- /src/repeat.ts: -------------------------------------------------------------------------------- 1 | import RRule, { ByWeekday, Frequency as RFrequency, Weekday } from 'rrule'; 2 | 3 | export enum Frequency { 4 | None = 'NONE', 5 | Daily = 'DAILY', 6 | Weekly = 'WEEKLY', 7 | Monthly = 'MONTHLY', 8 | Yearly = 'YEARLY', 9 | } 10 | 11 | export class RepeatAdapter { 12 | private readonly rrule: RRule; 13 | private subscriptions: { id: number; hook: (val: any) => void }[]; 14 | 15 | constructor(rrule: RRule) { 16 | this.rrule = rrule; 17 | this.subscriptions = []; 18 | } 19 | 20 | /** 21 | * The subscribe function implements the Store interface in Svelte. The 22 | * subscribers must be called any time there is a change to the task. 23 | */ 24 | public readonly subscribe = ( 25 | subscription: (value: any) => void, 26 | ): (() => void) => { 27 | const maxID = this.subscriptions.reduce( 28 | (prev, { id }): number => Math.max(prev, id), 29 | 0, 30 | ); 31 | const newID = maxID + 1; 32 | 33 | this.subscriptions.push({ id: newID, hook: subscription }); 34 | subscription(this); 35 | 36 | // Return an unsubscribe function 37 | return () => { 38 | this.subscriptions = this.subscriptions.filter(({ id }) => id !== newID); 39 | console.log(`Removing subscription ${newID}`); 40 | }; 41 | }; 42 | 43 | /** 44 | * The set function implements the Store interface in Svelte. We are not 45 | * actually using it to store new values, but it is needed when binding to 46 | * properties. 47 | */ 48 | public readonly set = (_: any): void => {}; 49 | 50 | public isValid = (): boolean => this.rrule.toString() !== ''; 51 | 52 | public next = (count: number): Date[] => 53 | this.rrule.all((_, len) => len < count); 54 | 55 | public toText = (): string => 56 | this.rrule.isFullyConvertibleToText() 57 | ? this.rrule.toText() 58 | : this.rrule.toString(); 59 | 60 | public toString = (): string => this.rrule.toString(); 61 | 62 | public asRRule = (): RRule => RRule.fromText(this.toText()); 63 | 64 | public get frequency(): Frequency { 65 | switch (this.rrule.options.freq) { 66 | case RFrequency.YEARLY: 67 | return Frequency.Yearly; 68 | case RFrequency.MONTHLY: 69 | return Frequency.Monthly; 70 | case RFrequency.WEEKLY: 71 | return Frequency.Weekly; 72 | case RFrequency.DAILY: 73 | return Frequency.Daily; 74 | default: 75 | // TODO: Display a notification instead? 76 | throw new Error( 77 | `Invalid frequency ${this.rrule.options.freq} in repetition`, 78 | ); 79 | } 80 | } 81 | 82 | public set frequency(frequency: Frequency) { 83 | switch (frequency) { 84 | case Frequency.Yearly: 85 | this.rrule.options.freq = RFrequency.YEARLY; 86 | this.rrule.origOptions.freq = RFrequency.YEARLY; 87 | break; 88 | case Frequency.Monthly: 89 | this.rrule.options.freq = RFrequency.MONTHLY; 90 | this.rrule.origOptions.freq = RFrequency.MONTHLY; 91 | break; 92 | case Frequency.Weekly: 93 | this.rrule.options.freq = RFrequency.WEEKLY; 94 | this.rrule.origOptions.freq = RFrequency.WEEKLY; 95 | break; 96 | case Frequency.Daily: 97 | this.rrule.options.freq = RFrequency.DAILY; 98 | this.rrule.origOptions.freq = RFrequency.DAILY; 99 | break; 100 | default: 101 | // TODO: Display a notification instead? 102 | throw new Error(`Invalid frequency ${frequency} requested`); 103 | } 104 | 105 | // reset other config options 106 | this.rrule.options.bymonth = undefined; 107 | this.rrule.origOptions.bymonth = undefined; 108 | this.rrule.options.bymonthday = undefined; 109 | this.rrule.origOptions.bymonthday = undefined; 110 | this.rrule.options.byweekday = undefined; 111 | this.rrule.origOptions.byweekday = undefined; 112 | 113 | this.notify(); 114 | } 115 | 116 | public get interval(): number { 117 | return this.rrule.options.interval; 118 | } 119 | 120 | public set interval(n: number) { 121 | // do not set to null or 0 122 | const newVal = n ? n : 1; 123 | 124 | if (newVal !== this.rrule.options.interval) { 125 | this.rrule.options.interval = n ? n : 1; 126 | this.notify(); 127 | } 128 | } 129 | 130 | public setDaysOfWeek = (ids: number[]): void => { 131 | const weekdayList: Weekday[] = new Array(ids.length); 132 | const numberList: number[] = new Array(ids.length); 133 | 134 | for (let i = 0; i < ids.length; i++) { 135 | weekdayList[i] = new Weekday(ids[i]); 136 | numberList[i] = ids[i]; 137 | } 138 | 139 | this.rrule.origOptions.byweekday = weekdayList; 140 | this.rrule.options.byweekday = numberList; 141 | 142 | this.notify(); 143 | }; 144 | 145 | public get daysOfWeek(): number[] { 146 | const weekdays = this.rrule.origOptions.byweekday; 147 | if (!weekdays) { 148 | return []; 149 | } else if (Array.isArray(weekdays)) { 150 | return weekdays.map(this.ByWeekdayToNumber); 151 | } 152 | return [this.ByWeekdayToNumber(weekdays)]; 153 | } 154 | 155 | public get dayOfMonth(): number | null { 156 | const day = this.rrule.origOptions.bymonthday; 157 | if (Array.isArray(day)) { 158 | if (day.length > 0) { 159 | return day[0]; 160 | } 161 | return null; 162 | } 163 | 164 | return day; 165 | } 166 | 167 | public set dayOfMonth(n: number) { 168 | this.rrule.origOptions.bymonthday = n; 169 | this.rrule.options.bymonthday = [n]; 170 | 171 | // Incompatible with day of month 172 | this.rrule.origOptions.byweekday = []; 173 | 174 | this.notify(); 175 | } 176 | 177 | public set lastDayOfMonth(val: boolean) { 178 | if (val) { 179 | this.rrule.origOptions.bymonthday = -1; 180 | this.rrule.options.bymonthday = [-1]; 181 | } else { 182 | this.rrule.origOptions.bymonthday = []; 183 | this.rrule.options.bymonthday = []; 184 | } 185 | 186 | this.notify(); 187 | } 188 | 189 | public get lastDayOfMonth(): boolean { 190 | const day = this.rrule.origOptions.bymonthday; 191 | if (Array.isArray(day)) { 192 | return day.length > 0 ? day[0] === -1 : false; 193 | } 194 | return day === -1; 195 | } 196 | 197 | public setWeekDaysOfMonth = ( 198 | selected: { week: string; weekDay: string }[], 199 | ): void => { 200 | this.rrule.origOptions.byweekday = selected.map( 201 | ({ week, weekDay }): Weekday => 202 | new Weekday(parseInt(weekDay, 10), parseInt(week, 10)), 203 | ); 204 | 205 | // Incompatible with week days of month 206 | this.rrule.origOptions.bymonthday = undefined; 207 | this.rrule.options.bymonthday = []; 208 | 209 | this.notify(); 210 | }; 211 | 212 | public getWeekDaysOfMonth = (): { week: string; weekDay: string }[] => { 213 | const weekdays = this.rrule.origOptions.byweekday; 214 | if (Array.isArray(weekdays)) { 215 | return weekdays 216 | .filter( 217 | (day): day is Weekday => 218 | typeof day !== 'string' && typeof day !== 'number', 219 | ) 220 | .filter((day) => day.n !== undefined) 221 | .map((day) => ({ 222 | week: day.n.toString(), 223 | weekDay: day.weekday.toString(), 224 | })); 225 | } 226 | 227 | // TODO: This might be overly restrictive, if people write custom RRule syntax. 228 | return []; 229 | }; 230 | 231 | public get monthsOfYear(): number[] { 232 | const months = this.rrule.origOptions.bymonth; 233 | if (months === undefined) { 234 | return []; 235 | } 236 | if (typeof months === 'number') { 237 | return [months]; 238 | } 239 | return months; 240 | } 241 | 242 | public setMonthsOfYear = (ids: number[]): void => { 243 | this.rrule.origOptions.bymonth = ids; 244 | this.rrule.options.bymonth = this.rrule.origOptions.bymonth; 245 | 246 | this.notify(); 247 | }; 248 | 249 | /** 250 | * Notify subscriptions of a change. 251 | */ 252 | private readonly notify = (): void => 253 | this.subscriptions.forEach(({ hook }) => hook(this)); 254 | 255 | private ByWeekdayToNumber(wd: ByWeekday): number { 256 | if (typeof wd === 'number') { 257 | return wd; 258 | } else if (typeof wd === 'string') { 259 | return 0; // TODO 260 | } 261 | return wd.weekday; 262 | } 263 | } 264 | -------------------------------------------------------------------------------- /src/file-helpers.ts: -------------------------------------------------------------------------------- 1 | import type { ISettings } from './settings'; 2 | import type { TaskLine } from './task-line'; 3 | import type { VaultIntermediate } from './vault'; 4 | import type { TFile } from 'obsidian'; 5 | 6 | /** 7 | * Adds a line for the provided task to the specified file in the tasks section. 8 | */ 9 | export const addTaskRepetition = async ( 10 | file: TFile, 11 | task: TaskLine, 12 | settings: ISettings, 13 | vault: VaultIntermediate, 14 | ): Promise => { 15 | console.debug( 16 | 'Slated: Ensuring repeating task exists in file: ' + file.basename, 17 | ); 18 | 19 | return withFileContents(file, vault, (lines: string[]): boolean => { 20 | const taskSectionIndex = getIndexTasksHeading( 21 | lines, 22 | task.headings, 23 | settings, 24 | ); 25 | const taskSectionEndIndex = getIndexSectionLastContent( 26 | lines, 27 | taskSectionIndex, 28 | ); 29 | 30 | const linesToInsert = task.subContent.slice(); 31 | linesToInsert.unshift(task.lineAsRepeated()); 32 | 33 | insertLines(lines, linesToInsert, taskSectionEndIndex + 1, settings); 34 | return true; 35 | }); 36 | }; 37 | 38 | export const addTaskMove = async ( 39 | file: TFile, 40 | task: TaskLine, 41 | settings: ISettings, 42 | vault: VaultIntermediate, 43 | ): Promise => { 44 | console.debug('Slated: Moving task to file: ' + file.basename); 45 | 46 | const linesToInsert = task.subContent.slice(); 47 | linesToInsert.unshift(task.line); 48 | 49 | return withFileContents(file, vault, (lines: string[]): boolean => { 50 | const taskSectionIndex = getIndexTasksHeading( 51 | lines, 52 | task.headings, 53 | settings, 54 | ); 55 | const taskSectionEndIndex = getIndexSectionLastContent( 56 | lines, 57 | taskSectionIndex, 58 | ); 59 | 60 | insertLines(lines, linesToInsert, taskSectionEndIndex + 1, settings); 61 | return true; 62 | }); 63 | }; 64 | 65 | export const removeTask = async ( 66 | file: TFile, 67 | task: TaskLine, 68 | vault: VaultIntermediate, 69 | ): Promise => 70 | removeLines(file, task.lineNum, 1 + task.subContent.length, vault); 71 | 72 | export const removeLines = async ( 73 | file: TFile, 74 | start: number, 75 | count: number, 76 | vault: VaultIntermediate, 77 | ): Promise => 78 | withFileContents(file, vault, (lines: string[]): boolean => { 79 | lines.splice(start, count); 80 | return true; 81 | }); 82 | 83 | /** 84 | * @description marks {count} the tasks starting on line {start} as copied by inserting '>' between brackets 85 | * @param {TFile} file 86 | * @param {number} start -- the line number of the first task to mark as copied 87 | * @param {number} count -- the number of tasks to mark as copied 88 | * @param {VaultIntermediate} vault 89 | * @returns 90 | */ 91 | export const markTaskAsCopied = async ( 92 | file: TFile, 93 | start: number, 94 | count: number, 95 | vault: VaultIntermediate, 96 | ): Promise => 97 | withFileContents(file, vault, (lines: string[]): boolean => { 98 | const tasksToMark = lines.slice(start, start + count); 99 | const markedTasks = tasksToMark.map((t) => t.replace('[ ]', '[>]')); 100 | lines.splice(start, count, ...markedTasks); 101 | return true; 102 | }); 103 | 104 | /** 105 | * Read the file contents and pass to the provided function as a list of lines. 106 | * If the provided function returns true, write the array back to the file. 107 | * NOTE: If useCache is true, the fn is not allowed to update the file! 108 | */ 109 | const withFileContents = async ( 110 | file: TFile, 111 | vault: VaultIntermediate, 112 | fn: (lines: string[]) => boolean, 113 | useCache = false, 114 | ): Promise => { 115 | const fileContents = (await vault.readFile(file, useCache)) || ''; 116 | const lines = fileContents.split('\n'); 117 | 118 | const updated = fn(lines); 119 | if (!useCache && updated) { 120 | return vault.writeFile(file, lines.join('\n')); 121 | } 122 | }; 123 | 124 | /** 125 | * Search the provided lines for the index of the tasks section heading. 126 | * NOTE: This may modifiy the array to add the header if missing. 127 | */ 128 | export const getIndexTasksHeading = ( 129 | lines: string[], 130 | headings: string[], 131 | settings: ISettings, 132 | ): number => { 133 | if (headings.length === 0) { 134 | headings.push(settings.tasksHeader); 135 | } 136 | 137 | let startIdx = 0; 138 | let endIdx = lines.length; 139 | headings.forEach((heading) => { 140 | startIdx = getIndexHeadingHelper( 141 | lines, 142 | startIdx, 143 | endIdx, 144 | heading, 145 | settings, 146 | ); 147 | endIdx = getIndexSectionNextSibling(lines, startIdx); 148 | }); 149 | 150 | return startIdx; 151 | }; 152 | 153 | const getIndexHeadingHelper = ( 154 | lines: string[], 155 | startIdx: number, 156 | endIdx: number, 157 | heading: string, 158 | settings: ISettings, 159 | ): number => { 160 | const actualEndIdx = Math.min(endIdx, lines.length); 161 | for (let i = startIdx; i < actualEndIdx; i++) { 162 | if (lines[i] === heading) { 163 | return i; 164 | } 165 | } 166 | 167 | // Tasks section not found, so add it 168 | 169 | if (lines.length === 1 && lines[0] === '') { 170 | // Empty file, just replace the first line 171 | lines[0] = heading; 172 | return 0; 173 | } 174 | 175 | if (settings.blankLineAfterHeader && lines[endIdx - 1] !== '') { 176 | lines.splice(endIdx, 0, '', heading); 177 | return endIdx + 1; 178 | } 179 | 180 | lines.splice(endIdx, 0, heading); 181 | return endIdx; 182 | }; 183 | 184 | export const getIndexSectionNextSibling = ( 185 | lines: string[], 186 | sectionHeader: number, 187 | ): number => { 188 | const desiredHeaderDepth = getHeaderDepth(lines[sectionHeader]); 189 | 190 | // Start on the line after the header. 191 | // NOTE: That could be the end of the file! 192 | for (let i = sectionHeader + 1; i < lines.length; i++) { 193 | const line = lines[i]; 194 | if (line.startsWith('#') && getHeaderDepth(line) <= desiredHeaderDepth) { 195 | return i; 196 | } 197 | } 198 | return lines.length; 199 | }; 200 | 201 | /** 202 | * Search the provided lines for the index of the last line of content starting 203 | * after the provided section header index. 204 | */ 205 | export const getIndexSectionLastContent = ( 206 | lines: string[], 207 | sectionHeader: number, 208 | ): number => { 209 | let lastContentLine = -1; 210 | let nextHeaderLine = -1; 211 | 212 | // Start on the line after the header. 213 | // NOTE: That could be the end of the file! 214 | for (let i = sectionHeader + 1; i < lines.length; i++) { 215 | const line = lines[i]; 216 | 217 | if (line.startsWith('#')) { 218 | nextHeaderLine = i; 219 | break; 220 | } 221 | 222 | if (line.trim() !== '') { 223 | lastContentLine = i; 224 | } 225 | } 226 | 227 | if (lastContentLine === -1) { 228 | // There is no content in this section, so return the header index 229 | return sectionHeader; 230 | } 231 | // There is content in this section, return the last line of it. 232 | return lastContentLine; 233 | }; 234 | 235 | /** 236 | * Insert the provided line before the provided index. If the settings call 237 | * for a blank line around headings, insert blank lines as necessary. 238 | */ 239 | export const insertLines = ( 240 | fileLines: string[], 241 | linesToAdd: string[], 242 | i: number, 243 | settings: ISettings, 244 | ): void => { 245 | if (!settings.blankLineAfterHeader) { 246 | fileLines.splice(i, 0, ...linesToAdd); 247 | return; 248 | } 249 | 250 | if (i > 0 && fileLines[i - 1].startsWith('#')) { 251 | // Line before is a heading, leave a space 252 | linesToAdd.unshift(''); 253 | } 254 | if (i < fileLines.length && fileLines[i].startsWith('#')) { 255 | // Next line is a heading, leave a space 256 | linesToAdd.push(''); 257 | } else if (i === fileLines.length) { 258 | // Last line of the file, leave a space 259 | linesToAdd.push(''); 260 | } 261 | 262 | fileLines.splice(i, 0, ...linesToAdd); 263 | }; 264 | 265 | /** 266 | * Return true if the name of this daily note can be parsed into a date using 267 | * the configured daily note naming settings. 268 | */ 269 | export const fileIsDailyNote = ( 270 | file: TFile, 271 | vault: VaultIntermediate, 272 | ): boolean => vault.findMomentForDailyNote(file) !== undefined; 273 | 274 | export const getBlockIDIndex = (lines: string[], blockID: string): number => { 275 | for (let i = 0; i < lines.length; i++) { 276 | if (lines[i].indexOf(blockID) > -1) { 277 | return i; 278 | } 279 | } 280 | return -1; 281 | }; 282 | 283 | export const getHeaderDepth = (line: string): number => { 284 | const trimmedLine = line.trimStart(); 285 | for (let i = 0; i < trimmedLine.length; i++) { 286 | if (trimmedLine[i] === '#') { 287 | continue; 288 | } 289 | 290 | return i; 291 | } 292 | 293 | return trimmedLine.length; 294 | }; 295 | -------------------------------------------------------------------------------- /src/task-line.ts: -------------------------------------------------------------------------------- 1 | import { 2 | addTaskMove, 3 | addTaskRepetition, 4 | getHeaderDepth, 5 | markTaskAsCopied, 6 | removeLines, 7 | } from './file-helpers'; 8 | import { RepeatAdapter } from './repeat'; 9 | import type { ISettings } from './settings'; 10 | import type { VaultIntermediate } from './vault'; 11 | import type { Moment } from 'moment'; 12 | import type { TFile } from 'obsidian'; 13 | import { Notice } from 'obsidian'; 14 | import RRule, { Frequency } from 'rrule'; 15 | 16 | const taskRe = /^\s*- \[[ xX>\-]\] /; 17 | 18 | /** 19 | * Matches the text following a semicolon or calendar emoji. 20 | * Does not match links or <> 21 | */ 22 | const repeatScheduleRe = /[;📅]\s*([-a-zA-Z0-9 =;:\,]+)/; 23 | 24 | export class TaskLine { 25 | public readonly lineNum: number; 26 | public readonly subContent: string[]; 27 | public readonly headings: string[]; 28 | 29 | private readonly file: TFile; 30 | private readonly vault: VaultIntermediate; 31 | private readonly settings: ISettings; 32 | 33 | private _line: string; 34 | 35 | private _repeats: boolean; 36 | private _repeatConfig: string; 37 | 38 | constructor( 39 | lineNum: number, 40 | file: TFile, 41 | fileLines: string[], // Can not use async in a constructor 42 | vault: VaultIntermediate, 43 | settings: ISettings, 44 | ) { 45 | this._line = fileLines[lineNum]; 46 | this.lineNum = lineNum; 47 | this.file = file; 48 | this.vault = vault; 49 | this.settings = settings; 50 | 51 | if (!this.isTask()) { 52 | return; 53 | } 54 | 55 | this.subContent = this.getSubContent(fileLines); 56 | this.headings = this.getHeadings(fileLines); 57 | 58 | const repeatMatches = repeatScheduleRe.exec(this._line); 59 | if (repeatMatches && repeatMatches.length === 2) { 60 | this._repeats = true; 61 | this._repeatConfig = repeatMatches[1]; 62 | } else { 63 | this._repeats = false; 64 | } 65 | } 66 | 67 | /** 68 | * line returns the current (possibly modified) value of this task line. 69 | */ 70 | public get line(): string { 71 | return this._line; 72 | } 73 | 74 | public get repeats(): boolean { 75 | return this._repeats; 76 | } 77 | 78 | public get repeater(): RepeatAdapter { 79 | if (this._repeatConfig) { 80 | return new RepeatAdapter(RRule.fromText(this._repeatConfig)); 81 | } 82 | 83 | return new RepeatAdapter( 84 | new RRule({ freq: Frequency.WEEKLY, interval: 1 }), 85 | ); 86 | } 87 | 88 | public get complete(): boolean { 89 | const matches = taskRe.exec(this._line); 90 | if (!matches) { 91 | return false; 92 | } 93 | 94 | const innerChar = matches[0].trimStart()[3]; 95 | return innerChar === 'x' || innerChar === 'X'; 96 | } 97 | 98 | public get incomplete(): boolean { 99 | const matches = taskRe.exec(this._line); 100 | if (!matches) { 101 | return false; 102 | } 103 | 104 | const innerChar = matches[0].trimStart()[3]; 105 | return innerChar === ' '; 106 | } 107 | 108 | public get skipped(): boolean { 109 | const matches = taskRe.exec(this._line); 110 | if (!matches) { 111 | return false; 112 | } 113 | 114 | const innerChar = matches[0].trimStart()[3]; 115 | return innerChar === '-'; 116 | } 117 | 118 | // Converts the line to be used in places where it was copied to another note 119 | // because it repeats. 120 | // Something like: 121 | // - [ ] This is the task ; Every Sunday 122 | // - [ ] This is the task ; Every Sunday 123 | public lineAsRepeated = (): string => this.line.replace(/\[[xX]\]/, '[ ]'); 124 | 125 | /** 126 | * Return whether the line stored is actually a valid Markdown task. NOTE: 127 | * This uses regex and is not quite as performant as TaskHandler.isLineTask() 128 | */ 129 | public readonly isTask = (): boolean => taskRe.test(this.line); 130 | 131 | /** 132 | * Save the contents of this TaskLine back to the file. 133 | */ 134 | public readonly save = async (): Promise => { 135 | const fileContents = await this.vault.readFile(this.file, false); 136 | const lines = fileContents.split('\n'); 137 | lines[this.lineNum] = this._line; 138 | const newFileContents = lines.join('\n'); 139 | 140 | await this.vault.writeFile(this.file, newFileContents); 141 | }; 142 | 143 | public readonly createNextRepetition = async (): Promise => { 144 | if (!this._repeats) { 145 | return; 146 | } 147 | 148 | const currentNoteDate = this.vault.findMomentForDailyNote(this.file); 149 | const nextDate = window 150 | .moment.utc( 151 | this.repeater.asRRule().after(currentNoteDate.endOf('day').toDate()), 152 | ) 153 | .startOf('day'); 154 | 155 | console.debug({ 156 | msg: 'Creating next task repetition', 157 | repeater: this.repeater.toString(), 158 | completed_note_date: currentNoteDate, 159 | next_note_date: nextDate, 160 | }); 161 | 162 | const nextOccurenceFile = await this.vault.getDailyNote(nextDate); 163 | return addTaskRepetition( 164 | nextOccurenceFile, 165 | this, 166 | this.settings, 167 | this.vault, 168 | ); 169 | }; 170 | 171 | public readonly move = async (date: Moment): Promise => { 172 | const newFile = await this.vault.getDailyNote(date); 173 | 174 | await addTaskMove(newFile, this, this.settings, this.vault); 175 | 176 | if (this.settings.preserveMovedTasks) { 177 | // MARK WITH [>], and preserve 178 | return markTaskAsCopied( 179 | this.file, 180 | this.lineNum, 181 | this.subContent.length + 1, 182 | this.vault, 183 | ); 184 | } 185 | 186 | // Remove this task and subcontent 187 | return removeLines( 188 | this.file, 189 | this.lineNum, 190 | this.subContent.length + 1, 191 | this.vault, 192 | ); 193 | }; 194 | 195 | /** 196 | * Apply the provided repeater to this task, updating the current value if 197 | * there is already a repeat config, or creating one if not. A blockID will 198 | * be generated if one does not already exist. 199 | */ 200 | public readonly handleRepeaterUpdated = ( 201 | repeater: RepeatAdapter, 202 | ): Promise => { 203 | if (!this._repeatConfig) { 204 | // Adding a repeat config to a task that previously did not have one 205 | this._line = this._line.trimRight() + ' 📅 ' + repeater.toText(); 206 | } else { 207 | this._line = this._line 208 | .replace(this._repeatConfig, repeater.toText() + ' ') 209 | .trim(); 210 | } 211 | 212 | this._repeatConfig = repeater.toText(); 213 | this._repeats = repeater.isValid(); 214 | return this.save(); 215 | }; 216 | 217 | public readonly skipOccurence = async (): Promise => { 218 | if (!this._repeatConfig) { 219 | new Notice('Cannot skip an occurence of a non-repeating task'); 220 | return; 221 | } 222 | 223 | if (!this.incomplete) { 224 | new Notice( 225 | 'Cannot skip a task which has already been checked, moved, or skipped', 226 | ); 227 | return; 228 | } 229 | 230 | await this.createNextRepetition(); 231 | 232 | this._line = this._line.replace(/\[ \]/, '[-]'); 233 | return this.save(); 234 | }; 235 | 236 | /** 237 | * getSubContent checks for lines which are nested under this task. They may 238 | * start with any character, they just must be indented more than this line. 239 | * 240 | * No blank lines are allowed between this line and the nested content. 241 | */ 242 | private readonly getSubContent = (lines: string[]): string[] => { 243 | const toReturn: string[] = []; 244 | const taskIndentLevel = getLineIndentLevel(this._line); 245 | // Starting on the line after task, look for sub lines 246 | for (let i = this.lineNum + 1; i < lines.length; i++) { 247 | const currentLine = lines[i]; 248 | if (getLineIndentLevel(currentLine) > taskIndentLevel) { 249 | toReturn.push(currentLine); 250 | } else { 251 | break; 252 | } 253 | } 254 | return toReturn; 255 | }; 256 | 257 | /** 258 | * getHeadings returns all headings this task is under up to and including 259 | * the settings.tasksHeader. If the task is not nested under 260 | * settings.tasksHeader, no headings will be returned. 261 | */ 262 | private readonly getHeadings = (lines: string[]): string[] => { 263 | const headings: string[] = []; 264 | // Search up through the file from this task, looking for the first heading 265 | let nextHeading = -1; 266 | for (let i = this.lineNum - 1; i >= 0; i--) { 267 | if (getHeaderDepth(lines[i]) > 0) { 268 | nextHeading = i; 269 | break; 270 | } 271 | } 272 | 273 | if (nextHeading === -1) { 274 | // found no headings above this task line 275 | return []; 276 | } 277 | 278 | do { 279 | headings.push(lines[nextHeading]); 280 | if (lines[nextHeading] === this.settings.tasksHeader) { 281 | // This is the top level that we care about, so stop searching 282 | break; 283 | } 284 | 285 | nextHeading = getParentHeaderIndex(nextHeading, lines); 286 | } while (nextHeading > -1); 287 | 288 | return headings.reverse(); 289 | }; 290 | } 291 | 292 | const getParentHeaderIndex = ( 293 | startingHeaderIdx: number, 294 | lines: string[], 295 | ): number => { 296 | const startingHeaderDepth = getHeaderDepth(lines[startingHeaderIdx]); 297 | 298 | for (let i = startingHeaderIdx - 1; i >= 0; i--) { 299 | const currentHeaderDepth = getHeaderDepth(lines[i]); 300 | if (currentHeaderDepth > 0 && currentHeaderDepth < startingHeaderDepth) { 301 | return i; 302 | } 303 | } 304 | return -1; 305 | }; 306 | 307 | const getLineIndentLevel = (line: string): number => 308 | line.length - line.trimStart().length; 309 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { buyMeACoffee, Element, paypal, skippedIconSvg } from './graphics'; 2 | import { 3 | shouldConfigureGlobalMoment, 4 | tryToConfigureGlobalMoment, 5 | } from './localization'; 6 | import { ISettings, settingsWithDefaults } from './settings'; 7 | import { TaskCache } from './task-cache'; 8 | import { TaskHandler } from './task-handler'; 9 | import { TaskLine } from './task-line'; 10 | import TaskMove from './ui/TaskMove.svelte'; 11 | import TaskRepeat from './ui/TaskRepeat.svelte'; 12 | import { VaultIntermediate } from './vault'; 13 | import type { default as MomentType, WeekSpec } from 'moment'; 14 | import { 15 | App, 16 | MarkdownPostProcessorContext, 17 | MarkdownPreviewRenderer, 18 | MarkdownView, 19 | Modal, 20 | Notice, 21 | Plugin, 22 | PluginSettingTab, 23 | Setting, 24 | TFile, 25 | } from 'obsidian'; 26 | import type { IWeekStartOption } from 'obsidian-calendar-ui'; 27 | 28 | declare global { 29 | interface Window { 30 | moment: typeof MomentType; 31 | _bundledLocaleWeekSpec: WeekSpec; 32 | } 33 | } 34 | 35 | export default class SlatedPlugin extends Plugin { 36 | public settings: ISettings; 37 | 38 | private vault: VaultIntermediate; 39 | private taskHandler: TaskHandler; 40 | private taskCache: TaskCache; 41 | 42 | private lastFile: TFile | undefined; 43 | 44 | public async onload(): Promise { 45 | await this.loadSettings(); 46 | 47 | this.vault = new VaultIntermediate(this.app.vault); 48 | this.taskHandler = new TaskHandler( 49 | this.vault, 50 | this.app.metadataCache, 51 | this.settings, 52 | ); 53 | this.taskCache = new TaskCache(this.taskHandler, this.vault); 54 | 55 | this.app.workspace.onLayoutReady(() => { 56 | this.taskCache.initialize(); 57 | }); 58 | 59 | MarkdownPreviewRenderer.registerPostProcessor(this.renderMovedTasks); 60 | 61 | this.registerEvent( 62 | this.app.workspace.on('file-open', (file: TFile) => { 63 | if (!file || !file.basename) { 64 | return; 65 | } 66 | 67 | // This callback is fired whenever a file receives focus 68 | // not just when the file is first opened. 69 | console.debug('Slated: File opened: ' + file.basename); 70 | 71 | if (this.lastFile) { 72 | this.taskHandler.processFile(this.lastFile); 73 | this.taskCache.fileOpenHook(this.lastFile); 74 | } 75 | 76 | this.lastFile = file; 77 | this.taskHandler.processFile(file); 78 | this.taskCache.fileOpenHook(file); 79 | }), 80 | ); 81 | 82 | this.addCommand({ 83 | id: 'task-skip', 84 | name: 'Skip Task Occurence', 85 | checkCallback: (checking: boolean) => { 86 | if (checking) { 87 | return this.taskChecker(); 88 | } 89 | 90 | this.withTaskLine((tl) => tl.skipOccurence()); 91 | }, 92 | }); 93 | 94 | this.addCommand({ 95 | id: 'task-move-modal', 96 | name: 'Move Task', 97 | checkCallback: (checking: boolean) => { 98 | if (checking) { 99 | return this.taskChecker(); 100 | } 101 | 102 | this.withTaskLine((task: TaskLine) => { 103 | new TaskMoveModal(this.app, task).open(); 104 | }); 105 | }, 106 | }); 107 | 108 | this.addCommand({ 109 | id: 'task-repeat-modal', 110 | name: 'Configure Task Repetition', 111 | checkCallback: (checking: boolean) => { 112 | if (checking) { 113 | return this.taskChecker(); 114 | } 115 | 116 | this.withTaskLine((task: TaskLine) => { 117 | new TaskRepeatModal(this.app, task).open(); 118 | }); 119 | }, 120 | }); 121 | 122 | this.addCommand({ 123 | id: 'move-incompleted-today', 124 | name: 'Move incomplete tasks from current file to today', 125 | checkCallback: (checking: boolean) => { 126 | const activeLeaf = this.app.workspace.activeLeaf; 127 | if (!(activeLeaf.view instanceof MarkdownView)) { 128 | return; 129 | } 130 | 131 | if (checking) { 132 | // Disallow moving tasks if currently looking at today's note 133 | const m = this.vault.findMomentForDailyNote(activeLeaf.view.file); 134 | return !(m && m.isSame(new Date(), 'day')); 135 | } 136 | 137 | this.taskHandler.moveIncompleted( 138 | activeLeaf.view.file, 139 | window.moment().startOf('day'), 140 | ); 141 | }, 142 | }); 143 | 144 | this.addSettingTab(new SettingsTab(this.app, this)); 145 | } 146 | 147 | private async loadSettings(): Promise { 148 | this.settings = settingsWithDefaults(await this.loadData()); 149 | 150 | if (shouldConfigureGlobalMoment(this.app)) { 151 | tryToConfigureGlobalMoment(this.app, this.settings); 152 | } 153 | } 154 | 155 | private readonly taskChecker = (): boolean => { 156 | if ( 157 | this.app.workspace.activeLeaf === undefined || 158 | !(this.app.workspace.activeLeaf.view instanceof MarkdownView) 159 | ) { 160 | return false; 161 | } 162 | 163 | const activeLeaf = this.app.workspace.activeLeaf; 164 | if (!(activeLeaf.view instanceof MarkdownView)) { 165 | return; 166 | } 167 | 168 | const editor = activeLeaf.view.sourceMode.cmEditor; 169 | const currentLine = editor.getLine(editor.getCursor().line); 170 | return this.taskHandler.isLineTask(currentLine); 171 | }; 172 | 173 | private readonly withTaskLine = async ( 174 | fn: (task: TaskLine) => void, 175 | ): Promise => { 176 | const activeLeaf = this.app.workspace.activeLeaf; 177 | if (!(activeLeaf.view instanceof MarkdownView)) { 178 | return; 179 | } 180 | 181 | const editor = activeLeaf.view.sourceMode.cmEditor; 182 | const cursorPos = editor.getCursor(); 183 | const task = new TaskLine( 184 | cursorPos.line, 185 | activeLeaf.view.file, 186 | (await this.vault.readFile(activeLeaf.view.file, true)).split('\n'), 187 | this.vault, 188 | this.settings, 189 | ); 190 | fn(task); 191 | }; 192 | 193 | private readonly renderMovedTasks = ( 194 | el: HTMLElement, 195 | ctx: MarkdownPostProcessorContext, 196 | ): Promise | void => { 197 | // TODO: When processing before rendering is possible in the Obsidian API, 198 | // switch to using TaskLine.svelte 199 | 200 | Object.values(el.getElementsByTagName('li')) 201 | .filter( 202 | (listItem) => 203 | !listItem.hasClass('task-list-item') && 204 | listItem.getText().trimStart().startsWith('[-]'), 205 | ) 206 | .forEach((listItem) => { 207 | let innerEl: HTMLElement = listItem; 208 | const pElements = listItem.getElementsByTagName('p'); 209 | if (pElements.length > 0) { 210 | // If there are lines in the list which do not start with a `-` then 211 | // the renderer will wrap everything in `p` elements. In this case 212 | // look at the first text node in the p element. 213 | innerEl = pElements[0]; 214 | } 215 | 216 | let removedPrefix = ''; 217 | for (let i = 0; i < innerEl.childNodes.length; i++) { 218 | const child = innerEl.childNodes[i]; 219 | if (child.nodeType !== 3) { 220 | continue; 221 | } 222 | 223 | removedPrefix = child.textContent.slice(0, 4); 224 | child.textContent = child.textContent.slice(4); 225 | break; // Only perform the replacement on the first textnode in an
  • 226 | } 227 | 228 | const icon = ((): string => { 229 | switch (removedPrefix) { 230 | case '[-] ': 231 | return skippedIconSvg; 232 | default: 233 | console.error('Unrecognized task type: ' + removedPrefix); 234 | return ''; 235 | } 236 | })(); 237 | 238 | listItem.addClass('task-list-item'); 239 | if (icon === skippedIconSvg) { 240 | listItem.addClass('is-skipped'); 241 | } 242 | innerEl.insertBefore(Element(icon), innerEl.firstChild); 243 | }); 244 | }; 245 | } 246 | 247 | class NotificationModal extends Modal { 248 | private readonly title: string; 249 | private readonly body: HTMLElement; 250 | 251 | constructor(app: App, title: string, body: HTMLElement) { 252 | super(app); 253 | this.title = title; 254 | this.body = body; 255 | } 256 | 257 | public onOpen = (): void => { 258 | const { titleEl, contentEl } = this; 259 | titleEl.setText(this.title); 260 | contentEl.appendChild(this.body); 261 | }; 262 | } 263 | 264 | class TaskMoveModal extends Modal { 265 | private readonly task: TaskLine; 266 | 267 | constructor(app: App, task: TaskLine) { 268 | super(app); 269 | this.task = task; 270 | } 271 | 272 | public onOpen = (): void => { 273 | const { contentEl } = this; 274 | new TaskMove({ 275 | target: contentEl, 276 | props: { 277 | task: this.task, 278 | close: () => this.close(), 279 | }, 280 | }); 281 | }; 282 | 283 | public onClose = (): void => { 284 | const { contentEl } = this; 285 | contentEl.empty(); 286 | }; 287 | } 288 | 289 | class TaskRepeatModal extends Modal { 290 | private readonly task: TaskLine; 291 | 292 | constructor(app: App, task: TaskLine) { 293 | super(app); 294 | this.task = task; 295 | } 296 | 297 | public onOpen = (): void => { 298 | const { contentEl } = this; 299 | new TaskRepeat({ 300 | target: contentEl, 301 | props: { 302 | task: this.task, 303 | close: () => this.close(), 304 | }, 305 | }); 306 | }; 307 | 308 | public onClose = (): void => { 309 | const { contentEl } = this; 310 | contentEl.empty(); 311 | }; 312 | } 313 | 314 | class SettingsTab extends PluginSettingTab { 315 | private readonly plugin: SlatedPlugin; 316 | 317 | constructor(app: App, plugin: SlatedPlugin) { 318 | super(app, plugin); 319 | this.plugin = plugin; 320 | } 321 | 322 | public display(): void { 323 | const { containerEl } = this; 324 | containerEl.empty(); 325 | 326 | containerEl.createEl('h2', { text: 'Slated Plugin - Settings' }); 327 | 328 | containerEl.createEl('p', { 329 | text: 'This plugin is in beta testing. Back up your data!', 330 | }); 331 | containerEl.createEl('p', { 332 | text: 'If you encounter bugs, or have feature requests, please submit them on Github.', 333 | }); 334 | containerEl.createEl('p', { text: 'Thank you.' }); 335 | 336 | new Setting(containerEl) 337 | .setName('Empty line after headings') 338 | .setDesc( 339 | 'When creating headings or adding tasks, leave an empty line below any headings.', 340 | ) 341 | .addToggle((toggle) => { 342 | toggle 343 | .setValue(this.plugin.settings.blankLineAfterHeader) 344 | .onChange((value) => { 345 | this.plugin.settings.blankLineAfterHeader = value; 346 | this.plugin.saveData(this.plugin.settings); 347 | }); 348 | }); 349 | 350 | new Setting(containerEl) 351 | .setName('Preserve incomplete tasks when moving') 352 | .setDesc( 353 | 'When moving a task to a different note, mark the task as moved with [>] in the current note rather than deleting it.', 354 | ) 355 | .addToggle((toggle) => { 356 | toggle 357 | .setValue(this.plugin.settings.preserveMovedTasks) 358 | .onChange((value) => { 359 | this.plugin.settings.preserveMovedTasks = value; 360 | this.plugin.saveData(this.plugin.settings); 361 | }); 362 | }); 363 | 364 | new Setting(containerEl) 365 | .setName('Tasks section header') 366 | .setDesc( 367 | 'Markdown header to use when creating tasks section in a document', 368 | ) 369 | .addText((text) => { 370 | text.setValue(this.plugin.settings.tasksHeader).onChange((value) => { 371 | if (!value.startsWith('#')) { 372 | new Notice('Tasks section header must start with "#"'); 373 | } 374 | 375 | this.plugin.settings.tasksHeader = value; 376 | this.plugin.saveData(this.plugin.settings); 377 | }); 378 | }); 379 | 380 | if (shouldConfigureGlobalMoment(this.app)) { 381 | const sysLocale = navigator.language?.toLowerCase(); 382 | 383 | const localizedWeekdays = window.moment.weekdays(); 384 | const localeWeekStartNum = window._bundledLocaleWeekSpec?.dow; 385 | const localeWeekStart = window.moment.weekdays()[localeWeekStartNum]; 386 | const weekdays = [ 387 | 'sunday', 388 | 'monday', 389 | 'tuesday', 390 | 'wednesday', 391 | 'thursday', 392 | 'friday', 393 | 'saturday', 394 | ]; 395 | 396 | new Setting(this.containerEl) 397 | .setName('Start week on:') 398 | .setDesc( 399 | "Choose what day of the week to start. Select 'Locale default' to use the default specified by moment.js", 400 | ) 401 | .addDropdown((dropdown) => { 402 | dropdown.addOption('locale', `Locale default (${localeWeekStart})`); 403 | localizedWeekdays.forEach((day, i) => { 404 | dropdown.addOption(weekdays[i], day); 405 | }); 406 | dropdown.setValue(this.plugin.settings.weekStart); 407 | dropdown.onChange(async (value) => { 408 | this.plugin.settings.weekStart = value as IWeekStartOption; 409 | this.plugin.saveData(this.plugin.settings); 410 | tryToConfigureGlobalMoment(this.app, this.plugin.settings); 411 | }); 412 | }); 413 | 414 | new Setting(containerEl) 415 | .setName('Override locale:') 416 | .setDesc( 417 | 'Set this if you want to use a locale different from the default', 418 | ) 419 | .addDropdown((dropdown) => { 420 | dropdown.addOption('system-default', `Same as system (${sysLocale})`); 421 | window.moment.locales().forEach((locale) => { 422 | dropdown.addOption(locale, locale); 423 | }); 424 | dropdown.setValue(this.plugin.settings.localeOverride); 425 | dropdown.onChange(async (value) => { 426 | this.plugin.settings.localeOverride = value; 427 | this.plugin.saveData(this.plugin.settings); 428 | tryToConfigureGlobalMoment(this.app, this.plugin.settings); 429 | }); 430 | }); 431 | } 432 | 433 | const div = containerEl.createEl('div', { 434 | cls: 'slated-donation', 435 | }); 436 | 437 | const donateText = document.createElement('p'); 438 | donateText.appendText( 439 | 'If this plugin adds value for you and you would like to help support ' + 440 | 'continued development, please use the buttons below:', 441 | ); 442 | div.appendChild(donateText); 443 | 444 | const parser = new DOMParser(); 445 | 446 | div.appendChild( 447 | createDonateButton( 448 | 'https://paypal.me/tgrosinger', 449 | parser.parseFromString(paypal, 'text/xml').documentElement, 450 | ), 451 | ); 452 | 453 | div.appendChild( 454 | createDonateButton( 455 | 'https://www.buymeacoffee.com/tgrosinger', 456 | parser.parseFromString(buyMeACoffee, 'text/xml').documentElement, 457 | ), 458 | ); 459 | } 460 | } 461 | 462 | const createDonateButton = (link: string, img: HTMLElement): HTMLElement => { 463 | const a = document.createElement('a'); 464 | a.setAttribute('href', link); 465 | a.addClass('slated-donate-button'); 466 | a.appendChild(img); 467 | return a; 468 | }; 469 | -------------------------------------------------------------------------------- /tests/task-line.test.ts: -------------------------------------------------------------------------------- 1 | import { ISettings, settingsWithDefaults } from '../src/settings'; 2 | import { TaskHandler } from '../src/task-handler'; 3 | import { TaskLine } from '../src/task-line'; 4 | import type { VaultIntermediate } from '../src/vault'; 5 | import { mock, MockProxy } from 'jest-mock-extended'; 6 | import moment from 'moment'; 7 | import type { TFile } from 'obsidian'; 8 | 9 | jest.mock('obsidian'); 10 | 11 | declare global { 12 | namespace jest { 13 | interface Matchers { 14 | toHaveLines( 15 | expected: string[], 16 | regexLines: number[], 17 | ): CustomMatcherResult; 18 | } 19 | } 20 | } 21 | 22 | expect.extend({ 23 | toHaveLines: ( 24 | received: string, 25 | expected: string[], 26 | regexLines: number[], 27 | ): jest.CustomMatcherResult => { 28 | const receivedLines = received.split('\n'); 29 | 30 | if (receivedLines.length !== expected.length) { 31 | return { 32 | message: () => 33 | `Received array of length ${receivedLines.length} but expected array of length ${expected.length}`, 34 | pass: false, 35 | }; 36 | } 37 | 38 | for (let i = 0; i < receivedLines.length; i++) { 39 | if (regexLines.indexOf(i) !== -1) { 40 | if (!new RegExp(expected[i]).test(receivedLines[i])) { 41 | return { 42 | message: () => 43 | `Index ${i} in received (${receivedLines[i]}) does not Regex-match expected (${expected[i]})`, 44 | pass: false, 45 | }; 46 | } 47 | } else if (receivedLines[i] !== expected[i]) { 48 | return { 49 | message: () => 50 | `Index ${i} in received (${receivedLines[i]}) does not match expected (${expected[i]})`, 51 | pass: false, 52 | }; 53 | } 54 | } 55 | 56 | return { pass: true, message: () => '' }; 57 | }, 58 | }); 59 | 60 | const format = 'YYYY-MM-DD'; 61 | const startDateStr = '2020-12-31'; 62 | const startDate = moment(startDateStr); 63 | 64 | const escapeRegExp = (str: string): string => 65 | str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string 66 | 67 | const getMockFileWithBasename = (basename: string): MockProxy => { 68 | const mockFile = mock(); 69 | mockFile.basename = basename; 70 | return mockFile; 71 | }; 72 | 73 | const getMockFileForMoment = (date: moment.Moment): MockProxy => 74 | getMockFileWithBasename(date.format(format)); 75 | 76 | const p = (str: string): Promise => Promise.resolve(str); 77 | 78 | let file: MockProxy; 79 | let vault: jest.Mocked; 80 | let settings: ISettings; 81 | let fileContents: Record; 82 | 83 | const simpleTestSetup = (line: string): TaskLine => { 84 | fileContents[file.basename] = line; 85 | return new TaskLine(0, file, [line], vault, settings); 86 | }; 87 | 88 | beforeEach(() => { 89 | window.moment = moment; 90 | vault = mock(); 91 | 92 | fileContents = {}; 93 | vault.readFile.mockImplementation((f, useCache) => 94 | Promise.resolve(fileContents[f.basename]), 95 | ); 96 | 97 | vault.writeFile.mockImplementation((f, data) => { 98 | fileContents[f.basename] = data; 99 | return Promise.resolve(); 100 | }); 101 | 102 | vault.findMomentForDailyNote.mockImplementation((dailyNote) => { 103 | const date = moment(dailyNote.basename, format, true); 104 | return date.isValid() ? date : undefined; 105 | }); 106 | 107 | vault.fileNameForMoment.mockImplementation((date) => 108 | date.format('YYYY-MM-DD'), 109 | ); 110 | }); 111 | 112 | describe('Tasks are parsed correctly', () => { 113 | beforeAll(() => { 114 | file = getMockFileForMoment(startDate); 115 | settings = settingsWithDefaults({}); 116 | }); 117 | 118 | test('When line is not a ul', () => { 119 | const line = '1. This is not a task'; 120 | const tl = simpleTestSetup(line); 121 | }); 122 | test('When the line is indented', () => { 123 | const line = ' - [ ] This is a simple task'; 124 | const tl = simpleTestSetup(line); 125 | expect(tl.line).toEqual(line); 126 | expect(tl.isTask()).toBeTruthy(); 127 | expect(tl.complete).toBeFalsy(); 128 | }); 129 | test('When the checkbox is invalid', () => { 130 | const line = '- [y] This is not a task'; 131 | const tl = simpleTestSetup(line); 132 | expect(tl.isTask()).toBeFalsy(); 133 | expect(tl.complete).toBeFalsy(); 134 | }); 135 | test('When the checkbox is the moved symbol', () => { 136 | const line = '- [>] This is not a task'; 137 | const tl = simpleTestSetup(line); 138 | expect(tl.isTask()).toBeTruthy(); 139 | expect(tl.complete).toBeFalsy(); 140 | }); 141 | test('When the checkbox is checked', () => { 142 | const line = '- [x] This task is done'; 143 | const tl = simpleTestSetup(line); 144 | expect(tl.line).toEqual(line); 145 | expect(tl.isTask()).toBeTruthy(); 146 | expect(tl.complete).toBeTruthy(); 147 | expect(tl.repeats).toBeFalsy(); 148 | }); 149 | test('When the checkbox is checked', () => { 150 | const line = '- [X] This task is done'; 151 | const tl = simpleTestSetup(line); 152 | expect(tl.line).toEqual(line); 153 | expect(tl.isTask()).toBeTruthy(); 154 | expect(tl.complete).toBeTruthy(); 155 | expect(tl.repeats).toBeFalsy(); 156 | }); 157 | 158 | describe('When there is a repeat config', () => { 159 | test('When there are no spaces', async () => { 160 | const line = '- [ ] The task;Every Sunday'; 161 | const tl = simpleTestSetup(line); 162 | expect(tl.repeater.isValid()).toBeTruthy(); 163 | expect(tl.repeats).toBeTruthy(); 164 | expect(tl.repeater.toText()).toEqual('every week on Sunday'); 165 | expect(tl.repeater.toString()).toEqual('RRULE:FREQ=WEEKLY;BYDAY=SU'); 166 | }); 167 | test('When there are spaces', async () => { 168 | const line = '- [ ] The task ; Every Sunday'; 169 | const tl = simpleTestSetup(line); 170 | expect(tl.repeater.isValid()).toBeTruthy(); 171 | expect(tl.repeats).toBeTruthy(); 172 | expect(tl.repeater.toText()).toEqual('every week on Sunday'); 173 | expect(tl.repeater.toString()).toEqual('RRULE:FREQ=WEEKLY;BYDAY=SU'); 174 | }); 175 | test('When the calendar emoji is used', async () => { 176 | const line = '- [ ] The task 📅 Every Sunday'; 177 | const tl = simpleTestSetup(line); 178 | expect(tl.repeater.isValid()).toBeTruthy(); 179 | expect(tl.repeats).toBeTruthy(); 180 | expect(tl.repeater.toText()).toEqual('every week on Sunday'); 181 | expect(tl.repeater.toString()).toEqual('RRULE:FREQ=WEEKLY;BYDAY=SU'); 182 | }); 183 | test('When there are trailing spaces', async () => { 184 | const line = '- [ ] The task 📅 Every Sunday '; 185 | const tl = simpleTestSetup(line); 186 | expect(tl.repeater.isValid()).toBeTruthy(); 187 | expect(tl.repeats).toBeTruthy(); 188 | expect(tl.repeater.toText()).toEqual('every week on Sunday'); 189 | expect(tl.repeater.toString()).toEqual('RRULE:FREQ=WEEKLY;BYDAY=SU'); 190 | }); 191 | test('When there are trailing spaces on a subtask', async () => { 192 | const line = ' - [ ] The task 📅 Every Sunday '; 193 | const tl = simpleTestSetup(line); 194 | expect(tl.repeater.isValid()).toBeTruthy(); 195 | expect(tl.repeats).toBeTruthy(); 196 | expect(tl.repeater.toText()).toEqual('every week on Sunday'); 197 | expect(tl.repeater.toString()).toEqual('RRULE:FREQ=WEEKLY;BYDAY=SU'); 198 | }); 199 | }); 200 | }); 201 | 202 | describe('taskLine.move', () => { 203 | let futureFiles: TFile[]; 204 | 205 | beforeAll(() => { 206 | file = getMockFileForMoment(startDate); 207 | }); 208 | 209 | beforeEach(() => { 210 | futureFiles = []; 211 | vault.getDailyNote.mockImplementation((date) => { 212 | const mockFile = getMockFileForMoment(date); 213 | futureFiles.push(mockFile); 214 | return Promise.resolve(mockFile); 215 | }); 216 | }); 217 | 218 | test('when the task has sub-items', async () => { 219 | fileContents[file.basename] = `# Original File 220 | 221 | ## Tasks 222 | 223 | - [ ] a test task 224 | - this is a nested item 225 | - so is this 226 | - [ ] another task 227 | `; 228 | 229 | const tl = new TaskLine( 230 | 4, 231 | file, 232 | fileContents[file.basename].split('\n'), 233 | vault, 234 | settings, 235 | ); 236 | await tl.move(moment('2021-01-01')); 237 | 238 | expect(futureFiles.length).toEqual(1); 239 | expect(fileContents[futureFiles[0].basename]).toHaveLines( 240 | [ 241 | '## Tasks', 242 | '', 243 | '- [ ] a test task', 244 | ' - this is a nested item', 245 | ' - so is this', 246 | '', 247 | ], 248 | [0], 249 | ); 250 | expect(fileContents[file.basename]).toHaveLines( 251 | ['# Original File', '', '## Tasks', '', '- [ ] another task', ''], 252 | [], 253 | ); 254 | }); 255 | 256 | test('when the task has repeating', async () => { 257 | fileContents[file.basename] = `# Original File 258 | 259 | ## Tasks 260 | 261 | - [ ] a test task ; Every Sunday 262 | `; 263 | 264 | const tl = new TaskLine( 265 | 4, 266 | file, 267 | fileContents[file.basename].split('\n'), 268 | vault, 269 | settings, 270 | ); 271 | await tl.move(moment('2021-01-01')); 272 | 273 | expect(futureFiles.length).toEqual(1); 274 | expect(fileContents[futureFiles[0].basename]).toEqual( 275 | '## Tasks\n\n- [ ] a test task ; Every Sunday\n', 276 | ); 277 | expect(fileContents[file.basename]).toEqual( 278 | '# Original File\n\n## Tasks\n\n', 279 | ); 280 | }); 281 | }); 282 | 283 | describe('taskLine.createNextRepetition', () => { 284 | let futureFiles: TFile[]; 285 | 286 | beforeAll(() => { 287 | file = getMockFileForMoment(startDate); 288 | settings = settingsWithDefaults({}); 289 | }); 290 | 291 | beforeEach(() => { 292 | futureFiles = []; 293 | vault.getDailyNote.mockImplementation((date) => { 294 | const mockFile = getMockFileForMoment(date); 295 | futureFiles.push(mockFile); 296 | return Promise.resolve(mockFile); 297 | }); 298 | }); 299 | 300 | describe('when a newline should be inserted after headings', () => { 301 | beforeAll(() => { 302 | settings = settingsWithDefaults({}); 303 | }); 304 | 305 | test('if it has a tasks section, the task is appended to existing', async () => { 306 | fileContents[file.basename] = '- [ ] a test task ; Every Sunday'; 307 | 308 | vault.readFile.mockReturnValueOnce( 309 | p( 310 | '# Hello\n\n## Tasks\n\n- [ ] Something\n - A sub item\n\n## Another Header\n', 311 | ), 312 | ); 313 | 314 | const tl = new TaskLine( 315 | 0, 316 | file, 317 | fileContents[file.basename].split('\n'), 318 | vault, 319 | settings, 320 | ); 321 | await tl.createNextRepetition(); 322 | 323 | expect(futureFiles.length).toEqual(1); 324 | expect(fileContents[futureFiles[0].basename]).toHaveLines( 325 | [ 326 | '# Hello', 327 | '', 328 | '## Tasks', 329 | '', 330 | '- [ ] Something', 331 | ' - A sub item', 332 | '- [ ] a test task ; Every Sunday', 333 | '', 334 | '## Another Header', 335 | '', 336 | ], 337 | [], 338 | ); 339 | }); 340 | 341 | test('if it has a tasks section, the task is appended', async () => { 342 | fileContents[file.basename] = '- [ ] a test task ; Every Sunday'; 343 | vault.readFile.mockReturnValueOnce(p('# Hello\n\n## Tasks\n')); 344 | 345 | const tl = new TaskLine( 346 | 0, 347 | file, 348 | fileContents[file.basename].split('\n'), 349 | vault, 350 | settings, 351 | ); 352 | await tl.createNextRepetition(); 353 | 354 | expect(futureFiles.length).toEqual(1); 355 | expect(fileContents[futureFiles[0].basename]).toHaveLines( 356 | ['# Hello', '', '## Tasks', '', '- [ ] a test task ; Every Sunday', ''], 357 | [], 358 | ); 359 | }); 360 | 361 | test('if it does not have a tasks section, one is created', async () => { 362 | fileContents[file.basename] = '- [ ] a test task ; Every Sunday'; 363 | vault.readFile.mockReturnValueOnce(p('# Hello\n\n## Another Section\n')); 364 | 365 | const tl = new TaskLine( 366 | 0, 367 | file, 368 | fileContents[file.basename].split('\n'), 369 | vault, 370 | settings, 371 | ); 372 | await tl.createNextRepetition(); 373 | 374 | expect(futureFiles.length).toEqual(1); 375 | expect(fileContents[futureFiles[0].basename]).toHaveLines( 376 | [ 377 | '# Hello', 378 | '', 379 | '## Another Section', 380 | '', 381 | '## Tasks', 382 | '', 383 | '- [ ] a test task ; Every Sunday', 384 | '', 385 | ], 386 | [], 387 | ); 388 | }); 389 | 390 | test('when the task has nested content', async () => { 391 | fileContents[file.basename] = `# Original File 392 | 393 | ## Tasks 394 | 395 | - [ ] a test task ; Every Sunday 396 | this is embeded content 397 | so is this 398 | - [ ] another task 399 | `; 400 | 401 | const tl = new TaskLine( 402 | 4, 403 | file, 404 | fileContents[file.basename].split('\n'), 405 | vault, 406 | settings, 407 | ); 408 | await tl.createNextRepetition(); 409 | 410 | expect(futureFiles.length).toEqual(1); 411 | expect(fileContents[futureFiles[0].basename]).toHaveLines( 412 | [ 413 | '## Tasks', 414 | '', 415 | '- [ ] a test task ; Every Sunday', 416 | ' this is embeded content', 417 | ' so is this', 418 | '', 419 | ], 420 | [], 421 | ); 422 | }); 423 | 424 | test('when the task has nested sub-items', async () => { 425 | fileContents[file.basename] = `# Original File 426 | 427 | ## Tasks 428 | 429 | - [ ] a test task ; Every Sunday 430 | - this is a nested item 431 | - so is this 432 | - [ ] another task 433 | `; 434 | 435 | const tl = new TaskLine( 436 | 4, 437 | file, 438 | fileContents[file.basename].split('\n'), 439 | vault, 440 | settings, 441 | ); 442 | await tl.createNextRepetition(); 443 | 444 | expect(futureFiles.length).toEqual(1); 445 | expect(fileContents[futureFiles[0].basename]).toHaveLines( 446 | [ 447 | '## Tasks', 448 | '', 449 | '- [ ] a test task ; Every Sunday', 450 | ' - this is a nested item', 451 | ' - so is this', 452 | '', 453 | ], 454 | [], 455 | ); 456 | }); 457 | 458 | test('when the task has additional headers', async () => { 459 | fileContents[file.basename] = `# Original File 460 | 461 | ## Tasks 462 | 463 | ### Work Tasks 464 | 465 | - [x] The task to move ; Every Sunday 466 | 467 | ### Personal Tasks 468 | 469 | - [ ] Mow the lawn 470 | `; 471 | 472 | vault.readFile.mockReturnValueOnce( 473 | p(`# Another File 474 | 475 | ## Tasks 476 | 477 | ### Personal Tasks 478 | 479 | - [ ] Buy milk 480 | `), 481 | ); 482 | 483 | const tl = new TaskLine( 484 | 6, 485 | file, 486 | fileContents[file.basename].split('\n'), 487 | vault, 488 | settings, 489 | ); 490 | await tl.createNextRepetition(); 491 | 492 | expect(futureFiles.length).toEqual(1); 493 | expect(fileContents[futureFiles[0].basename]).toHaveLines( 494 | [ 495 | '# Another File', 496 | '', 497 | '## Tasks', 498 | '', 499 | '### Personal Tasks', 500 | '', 501 | '- [ ] Buy milk', 502 | '', 503 | '### Work Tasks', 504 | '', 505 | '- [ ] The task to move ; Every Sunday', 506 | '', 507 | ], 508 | [], 509 | ); 510 | }); 511 | }); 512 | }); 513 | -------------------------------------------------------------------------------- /src/graphics.ts: -------------------------------------------------------------------------------- 1 | export const Element = (svgText: string): HTMLElement => { 2 | const parser = new DOMParser(); 3 | return parser.parseFromString(svgText, 'text/xml').documentElement; 4 | }; 5 | 6 | /** 7 | * Icon used in the side ribbon 8 | */ 9 | export const checkboxIcon = ` 10 | 11 | 12 | 13 | `; 14 | 15 | // 16 | // Icons for use when rendering notes 17 | // Sized to fit inline with actual checkbox inputs 18 | // 19 | 20 | /** 21 | * Sized so that this fits inline with actual checkbox inputs 22 | */ 23 | export const skippedIconSvg = ` 24 | 25 | 26 | 27 | 28 | 29 | `; 30 | 31 | // 32 | // Icons for the TaskView header 33 | // NOT sized to fit inline with actual checkbox inputs 34 | // 35 | 36 | export const repeatingIconSvg = ` 37 | 38 | 39 | 40 | 41 | 42 | `; 43 | 44 | export const nonRepeatingIconSvg = ` 45 | 46 | 47 | 48 | 49 | 50 | 51 | `; 52 | 53 | export const cbUncheckedIconSvg = ` 54 | 55 | 56 | 57 | 58 | `; 59 | 60 | export const cbCheckedIconSvg = ` 61 | 62 | 63 | 64 | 65 | 66 | `; 67 | 68 | export const moved2IconSvg = ` 69 | 70 | 71 | 72 | 73 | 74 | `; 75 | 76 | export const dailyIconSvg = ` 77 | 78 | 79 | 80 | 81 | 82 | `; 83 | 84 | export const weeklyIconSvg = ` 85 | 86 | 87 | 88 | 89 | 90 | 91 | `; 92 | 93 | export const monthlyIconSvg = ` 94 | 95 | 96 | 97 | 98 | 99 | 100 | `; 101 | 102 | export const buyMeACoffee = ` 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | `; 131 | 132 | export const paypal = ` 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | `; 141 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------