├── src ├── lib │ └── codemirror.js ├── mode │ ├── orgmode │ │ ├── orgmode-fold.js │ │ └── orgmode-mode.js │ └── simple │ │ └── simple.js └── main.ts ├── .prettierrc.json ├── .gitignore ├── manifest.json ├── upgrade-assets.cmd ├── versions.json ├── styles.css ├── tsconfig.json ├── README.md ├── rollup.config.js ├── package.json └── LICENSE /src/lib/codemirror.js: -------------------------------------------------------------------------------- 1 | module.exports = CodeMirror; 2 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "semi": true, 4 | "tabWidth": 4, 5 | "useTabs": false 6 | } 7 | -------------------------------------------------------------------------------- /.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 | # obsidian 14 | data.json 15 | -------------------------------------------------------------------------------- /manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "obsidian-org-mode", 3 | "name": "Org Mode", 4 | "version": "1.4.1", 5 | "minAppVersion": "0.10.12", 6 | "description": "Add Org Mode support to Obsidian.", 7 | "author": "ryanpcmcquen", 8 | "authorUrl": "https://github.com/ryanpcmcquen", 9 | "isDesktopOnly": false 10 | } 11 | -------------------------------------------------------------------------------- /upgrade-assets.cmd: -------------------------------------------------------------------------------- 1 | curl https://cdn.jsdelivr.net/npm/codemirror@5/addon/mode/simple.js -o src/mode/simple/simple.js 2 | curl https://cdn.jsdelivr.net/gh/mickael-kerjean/codemirror-orgmode/orgmode-fold.js -o src/mode/orgmode/orgmode-fold.js 3 | curl https://cdn.jsdelivr.net/gh/mickael-kerjean/codemirror-orgmode/orgmode-mode.js -o src/mode/orgmode/orgmode-mode.js 4 | -------------------------------------------------------------------------------- /versions.json: -------------------------------------------------------------------------------- 1 | { 2 | "1.4.1": "0.10.12", 3 | "1.4.0": "0.10.12", 4 | "1.3.3": "0.10.12", 5 | "1.3.2": "0.10.12", 6 | "1.3.1": "0.10.12", 7 | "1.3.0": "0.10.12", 8 | "1.2.1": "0.10.12", 9 | "1.2.0": "0.10.12", 10 | "1.1.1": "0.10.12", 11 | "1.1.0": "0.10.12", 12 | "1.0.1": "0.10.12", 13 | "1.0.0": "0.10.12" 14 | } 15 | -------------------------------------------------------------------------------- /styles.css: -------------------------------------------------------------------------------- 1 | /* This is how code is represented: */ 2 | .cm-comment { 3 | font-family: monospace; 4 | } 5 | 6 | .cm-header.cm-org-level-star { 7 | font-weight: 100; 8 | opacity: 0.9; 9 | } 10 | .cm-header.cm-org-level-star::after { 11 | font-weight: 900; 12 | opacity: 1; 13 | content: "*"; 14 | position: absolute; 15 | transform: translate(-135%, 0); 16 | } 17 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "inlineSourceMap": true, 5 | "inlineSources": true, 6 | "module": "ESNext", 7 | "target": "es6", 8 | "allowJs": false, 9 | "noImplicitAny": true, 10 | "moduleResolution": "node", 11 | "importHelpers": true, 12 | "lib": ["dom", "es5", "scripthost", "es2015"], 13 | "allowSyntheticDefaultImports": true 14 | }, 15 | "include": ["**/*.ts"] 16 | } 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Obsidian Org Mode 2 | 3 | Add Org Mode support to Obsidian. 4 | 5 | Screen Shot 2021-05-14 at 10 08 41 AM 6 | 7 | ## What is Org Mode? 8 | 9 | Read about it on the Org Mode site: 10 | https://orgmode.org/ 11 | 12 | ### Manually installing the plugin 13 | 14 | - Copy over `main.js`, `styles.css`, `manifest.json` to your vault `VaultFolder/.obsidian/plugins/obsidian-org-mode/`. 15 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from "@rollup/plugin-typescript"; 2 | import { nodeResolve } from "@rollup/plugin-node-resolve"; 3 | import commonjs from "@rollup/plugin-commonjs"; 4 | 5 | const isProd = process.env.BUILD === "production"; 6 | 7 | const banner = `/* 8 | THIS IS A GENERATED/BUNDLED FILE BY ROLLUP 9 | if you want to view the source visit the plugins github repository 10 | */ 11 | `; 12 | 13 | export default { 14 | input: "src/main.ts", 15 | output: { 16 | dir: ".", 17 | sourcemap: "inline", 18 | sourcemapExcludeSources: isProd, 19 | format: "cjs", 20 | exports: "default", 21 | banner, 22 | }, 23 | external: ["obsidian"], 24 | plugins: [typescript(), nodeResolve({ browser: true }), commonjs()], 25 | }; 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "obsidian-org-mode", 3 | "version": "1.4.1", 4 | "description": "Add Org Mode support to Obsidian.", 5 | "main": "main.js", 6 | "repository": "https://github.com/ryanpcmcquen/obsidian-org-mode", 7 | "scripts": { 8 | "dev": "rollup --config rollup.config.js -w", 9 | "build": "rollup --config rollup.config.js --environment BUILD:production" 10 | }, 11 | "keywords": [], 12 | "author": "", 13 | "license": "MPL-2.0", 14 | "devDependencies": { 15 | "@rollup/plugin-commonjs": "^18.0.0", 16 | "@rollup/plugin-node-resolve": "^11.2.1", 17 | "@rollup/plugin-typescript": "^8.2.1", 18 | "@types/node": "^14.17.1", 19 | "obsidian": "^0.12.0", 20 | "rollup": "^2.50.1", 21 | "tslib": "^2.2.0", 22 | "typescript": "^4.3.2" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/mode/orgmode/orgmode-fold.js: -------------------------------------------------------------------------------- 1 | (function(mod) { 2 | if (typeof exports == "object" && typeof module == "object") // CommonJS 3 | mod(require("../../lib/codemirror")); 4 | else if (typeof define == "function" && define.amd) // AMD 5 | define(["../../lib/codemirror"], mod); 6 | else // Plain browser env 7 | mod(CodeMirror); 8 | })(function(CodeMirror) { 9 | "use strict"; 10 | CodeMirror.registerHelper("fold", "orgmode", function(cm, start) { 11 | // init 12 | const levelToMatch = headerLevel(start.line); 13 | 14 | // no folding needed 15 | if(levelToMatch === null) return; 16 | 17 | // find folding limits 18 | const lastLine = cm.lastLine(); 19 | let end = start.line; 20 | while(end < lastLine){ 21 | end += 1; 22 | let level = headerLevel(end); 23 | if(level && level <= levelToMatch) { 24 | end = end - 1; 25 | break; 26 | }; 27 | } 28 | 29 | return { 30 | from: CodeMirror.Pos(start.line, cm.getLine(start.line).length), 31 | to: CodeMirror.Pos(end, cm.getLine(end).length) 32 | }; 33 | 34 | function headerLevel(lineNo) { 35 | var line = cm.getLine(lineNo); 36 | var match = /^\*+/.exec(line); 37 | if(match && match.length === 1 && /header/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0)))){ 38 | return match[0].length; 39 | } 40 | return null; 41 | } 42 | }); 43 | CodeMirror.registerGlobalHelper("fold", "drawer", function(mode) { 44 | return mode.name === 'orgmode' ? true : false; 45 | }, function(cm, start) { 46 | const drawer = isBeginningOfADrawer(start.line); 47 | if(drawer === false) return; 48 | 49 | // find folding limits 50 | const lastLine = cm.lastLine(); 51 | let end = start.line; 52 | while(end < lastLine){ 53 | end += 1; 54 | if(isEndOfADrawer(end)){ 55 | break; 56 | } 57 | } 58 | 59 | return { 60 | from: CodeMirror.Pos(start.line, cm.getLine(start.line).length), 61 | to: CodeMirror.Pos(end, cm.getLine(end).length) 62 | }; 63 | 64 | function isBeginningOfADrawer(lineNo) { 65 | var line = cm.getLine(lineNo); 66 | var match = /^\:.*\:$/.exec(line); 67 | if(match && match.length === 1 && match[0] !== ':END:'){ 68 | return true; 69 | } 70 | return false; 71 | } 72 | function isEndOfADrawer(lineNo){ 73 | var line = cm.getLine(lineNo); 74 | return line.trim() === ':END:' ? true : false; 75 | } 76 | }); 77 | }); 78 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import "./lib/codemirror.js"; 2 | import "./mode/simple/simple.js"; 3 | import "./mode/orgmode/orgmode-fold.js"; 4 | import "./mode/orgmode/orgmode-mode.js"; 5 | import { Plugin, TextFileView, WorkspaceLeaf } from "obsidian"; 6 | 7 | export default class OrgMode extends Plugin { 8 | async onload() { 9 | super.onload(); 10 | console.log("Loading Org Mode plugin ..."); 11 | 12 | this.registerView("orgmode", this.orgViewCreator); 13 | this.registerExtensions(["org", "org_archive"], "orgmode"); 14 | } 15 | 16 | orgViewCreator = (leaf: WorkspaceLeaf) => { 17 | return new OrgView(leaf); 18 | }; 19 | 20 | onunload() { 21 | console.log("Unloading Org Mode plugin ..."); 22 | } 23 | } 24 | 25 | // This is the custom view: 26 | class OrgView extends TextFileView { 27 | // Internal code mirror instance: 28 | codeMirror: CodeMirror.Editor; 29 | 30 | // this.contentEl is not exposed, so cheat a bit. 31 | public get extContentEl(): HTMLElement { 32 | // @ts-ignore 33 | return this.contentEl; 34 | } 35 | 36 | constructor(leaf: WorkspaceLeaf) { 37 | super(leaf); 38 | // @ts-ignore 39 | this.codeMirror = CodeMirror(this.extContentEl); 40 | 41 | this.codeMirror.on("changes", this.changed); 42 | } 43 | 44 | // When the view is resized, refresh CodeMirror (thanks Licat!). 45 | onResize() { 46 | this.codeMirror.refresh(); 47 | } 48 | 49 | changed = async () => { 50 | this.requestSave(); 51 | }; 52 | 53 | getViewData = () => { 54 | return this.codeMirror.getValue(); 55 | }; 56 | 57 | setViewData = (data: string, clear: boolean) => { 58 | if (clear) { 59 | // @ts-ignore 60 | this.codeMirror.swapDoc(CodeMirror.Doc(data, "orgmode")); 61 | } else { 62 | this.codeMirror.setValue(data); 63 | } 64 | 65 | // @ts-ignore 66 | if (this.app?.vault?.config?.vimMode) { 67 | this.codeMirror.setOption("keyMap", "vim"); 68 | } 69 | 70 | // This seems to fix some odd visual bugs: 71 | this.codeMirror.refresh(); 72 | 73 | // This focuses the editor, which is analogous to the 74 | // default Markdown behavior in Obsidian: 75 | this.codeMirror.focus(); 76 | }; 77 | 78 | clear = () => { 79 | this.codeMirror.setValue(""); 80 | this.codeMirror.clearHistory(); 81 | }; 82 | 83 | getDisplayText() { 84 | if (this.file) { 85 | return this.file.basename; 86 | } else { 87 | return "org (No File)"; 88 | } 89 | } 90 | 91 | canAcceptExtension(extension: string) { 92 | return extension === "org" || extension === "org_archive"; 93 | } 94 | 95 | getViewType() { 96 | return "orgmode"; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /src/mode/simple/simple.js: -------------------------------------------------------------------------------- 1 | // CodeMirror, copyright (c) by Marijn Haverbeke and others 2 | // Distributed under an MIT license: https://codemirror.net/LICENSE 3 | 4 | (function(mod) { 5 | if (typeof exports == "object" && typeof module == "object") // CommonJS 6 | mod(require("../../lib/codemirror")); 7 | else if (typeof define == "function" && define.amd) // AMD 8 | define(["../../lib/codemirror"], mod); 9 | else // Plain browser env 10 | mod(CodeMirror); 11 | })(function(CodeMirror) { 12 | "use strict"; 13 | 14 | CodeMirror.defineSimpleMode = function(name, states) { 15 | CodeMirror.defineMode(name, function(config) { 16 | return CodeMirror.simpleMode(config, states); 17 | }); 18 | }; 19 | 20 | CodeMirror.simpleMode = function(config, states) { 21 | ensureState(states, "start"); 22 | var states_ = {}, meta = states.meta || {}, hasIndentation = false; 23 | for (var state in states) if (state != meta && states.hasOwnProperty(state)) { 24 | var list = states_[state] = [], orig = states[state]; 25 | for (var i = 0; i < orig.length; i++) { 26 | var data = orig[i]; 27 | list.push(new Rule(data, states)); 28 | if (data.indent || data.dedent) hasIndentation = true; 29 | } 30 | } 31 | var mode = { 32 | startState: function() { 33 | return {state: "start", pending: null, 34 | local: null, localState: null, 35 | indent: hasIndentation ? [] : null}; 36 | }, 37 | copyState: function(state) { 38 | var s = {state: state.state, pending: state.pending, 39 | local: state.local, localState: null, 40 | indent: state.indent && state.indent.slice(0)}; 41 | if (state.localState) 42 | s.localState = CodeMirror.copyState(state.local.mode, state.localState); 43 | if (state.stack) 44 | s.stack = state.stack.slice(0); 45 | for (var pers = state.persistentStates; pers; pers = pers.next) 46 | s.persistentStates = {mode: pers.mode, 47 | spec: pers.spec, 48 | state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state), 49 | next: s.persistentStates}; 50 | return s; 51 | }, 52 | token: tokenFunction(states_, config), 53 | innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; }, 54 | indent: indentFunction(states_, meta) 55 | }; 56 | if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop)) 57 | mode[prop] = meta[prop]; 58 | return mode; 59 | }; 60 | 61 | function ensureState(states, name) { 62 | if (!states.hasOwnProperty(name)) 63 | throw new Error("Undefined state " + name + " in simple mode"); 64 | } 65 | 66 | function toRegex(val, caret) { 67 | if (!val) return /(?:)/; 68 | var flags = ""; 69 | if (val instanceof RegExp) { 70 | if (val.ignoreCase) flags = "i"; 71 | if (val.unicode) flags += "u" 72 | val = val.source; 73 | } else { 74 | val = String(val); 75 | } 76 | return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags); 77 | } 78 | 79 | function asToken(val) { 80 | if (!val) return null; 81 | if (val.apply) return val 82 | if (typeof val == "string") return val.replace(/\./g, " "); 83 | var result = []; 84 | for (var i = 0; i < val.length; i++) 85 | result.push(val[i] && val[i].replace(/\./g, " ")); 86 | return result; 87 | } 88 | 89 | function Rule(data, states) { 90 | if (data.next || data.push) ensureState(states, data.next || data.push); 91 | this.regex = toRegex(data.regex); 92 | this.token = asToken(data.token); 93 | this.data = data; 94 | } 95 | 96 | function tokenFunction(states, config) { 97 | return function(stream, state) { 98 | if (state.pending) { 99 | var pend = state.pending.shift(); 100 | if (state.pending.length == 0) state.pending = null; 101 | stream.pos += pend.text.length; 102 | return pend.token; 103 | } 104 | 105 | if (state.local) { 106 | if (state.local.end && stream.match(state.local.end)) { 107 | var tok = state.local.endToken || null; 108 | state.local = state.localState = null; 109 | return tok; 110 | } else { 111 | var tok = state.local.mode.token(stream, state.localState), m; 112 | if (state.local.endScan && (m = state.local.endScan.exec(stream.current()))) 113 | stream.pos = stream.start + m.index; 114 | return tok; 115 | } 116 | } 117 | 118 | var curState = states[state.state]; 119 | for (var i = 0; i < curState.length; i++) { 120 | var rule = curState[i]; 121 | var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex); 122 | if (matches) { 123 | if (rule.data.next) { 124 | state.state = rule.data.next; 125 | } else if (rule.data.push) { 126 | (state.stack || (state.stack = [])).push(state.state); 127 | state.state = rule.data.push; 128 | } else if (rule.data.pop && state.stack && state.stack.length) { 129 | state.state = state.stack.pop(); 130 | } 131 | 132 | if (rule.data.mode) 133 | enterLocalMode(config, state, rule.data.mode, rule.token); 134 | if (rule.data.indent) 135 | state.indent.push(stream.indentation() + config.indentUnit); 136 | if (rule.data.dedent) 137 | state.indent.pop(); 138 | var token = rule.token 139 | if (token && token.apply) token = token(matches) 140 | if (matches.length > 2 && rule.token && typeof rule.token != "string") { 141 | for (var j = 2; j < matches.length; j++) 142 | if (matches[j]) 143 | (state.pending || (state.pending = [])).push({text: matches[j], token: rule.token[j - 1]}); 144 | stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0)); 145 | return token[0]; 146 | } else if (token && token.join) { 147 | return token[0]; 148 | } else { 149 | return token; 150 | } 151 | } 152 | } 153 | stream.next(); 154 | return null; 155 | }; 156 | } 157 | 158 | function cmp(a, b) { 159 | if (a === b) return true; 160 | if (!a || typeof a != "object" || !b || typeof b != "object") return false; 161 | var props = 0; 162 | for (var prop in a) if (a.hasOwnProperty(prop)) { 163 | if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false; 164 | props++; 165 | } 166 | for (var prop in b) if (b.hasOwnProperty(prop)) props--; 167 | return props == 0; 168 | } 169 | 170 | function enterLocalMode(config, state, spec, token) { 171 | var pers; 172 | if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next) 173 | if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p; 174 | var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec); 175 | var lState = pers ? pers.state : CodeMirror.startState(mode); 176 | if (spec.persistent && !pers) 177 | state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates}; 178 | 179 | state.localState = lState; 180 | state.local = {mode: mode, 181 | end: spec.end && toRegex(spec.end), 182 | endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false), 183 | endToken: token && token.join ? token[token.length - 1] : token}; 184 | } 185 | 186 | function indexOf(val, arr) { 187 | for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true; 188 | } 189 | 190 | function indentFunction(states, meta) { 191 | return function(state, textAfter, line) { 192 | if (state.local && state.local.mode.indent) 193 | return state.local.mode.indent(state.localState, textAfter, line); 194 | if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1) 195 | return CodeMirror.Pass; 196 | 197 | var pos = state.indent.length - 1, rules = states[state.state]; 198 | scan: for (;;) { 199 | for (var i = 0; i < rules.length; i++) { 200 | var rule = rules[i]; 201 | if (rule.data.dedent && rule.data.dedentIfLineStart !== false) { 202 | var m = rule.regex.exec(textAfter); 203 | if (m && m[0]) { 204 | pos--; 205 | if (rule.next || rule.push) rules = states[rule.next || rule.push]; 206 | textAfter = textAfter.slice(m[0].length); 207 | continue scan; 208 | } 209 | } 210 | } 211 | break; 212 | } 213 | return pos < 0 ? 0 : state.indent[pos]; 214 | }; 215 | } 216 | }); 217 | -------------------------------------------------------------------------------- /src/mode/orgmode/orgmode-mode.js: -------------------------------------------------------------------------------- 1 | (function(mod) { 2 | if (typeof exports == "object" && typeof module == "object") 3 | mod(require("../../lib/codemirror")); 4 | else if (typeof define == "function" && define.amd) 5 | define(["../../lib/codemirror"], mod); 6 | else 7 | mod(CodeMirror); 8 | })(function(CodeMirror) { 9 | "use strict"; 10 | 11 | CodeMirror.defineSimpleMode("orgmode", { 12 | start: [ 13 | {regex: /(\*\s)(TODO|DOING|WAITING|NEXT|PENDING|)(CANCELLED|CANCELED|CANCEL|DONE|REJECTED|STOP|STOPPED|)(\s+\[\#[A-C]\]\s+|)(.*?)(?:(\s{10,}|))(\:[\S]+\:|)$/, sol: true, token: ["header level1 org-level-star","header level1 org-todo","header level1 org-done", "header level1 org-priority", "header level1", "header level1 void", "header level1 comment"]}, 14 | {regex: /(\*{1,}\s)(TODO|DOING|WAITING|NEXT|PENDING|)(CANCELLED|CANCELED|CANCEL|DEFERRED|DONE|REJECTED|STOP|STOPPED|)(\s+\[\#[A-C]\]\s+|)(.*?)(?:(\s{10,}|))(\:[\S]+\:|)$/, sol: true, token: ["header org-level-star","header org-todo","header org-done", "header org-priority", "header", "header void", "header comment"]}, 15 | {regex: /(\+[^\+]+\+)/, token: ["strikethrough"]}, 16 | {regex: /(\*[^\*]+\*)/, token: ["strong"]}, 17 | {regex: /(\/[^\/]+\/)/, token: ["em"]}, 18 | {regex: /(\_[^\_]+\_)/, token: ["link"]}, 19 | {regex: /(\~[^\~]+\~)/, token: ["comment"]}, 20 | {regex: /(\=[^\=]+\=)/, token: ["comment"]}, 21 | {regex: /\[\[[^\[\]]+\]\[[^\[\]]+\]\]/, token: "org-url"}, // links 22 | {regex: /\[\[[^\[\]]+\]\]/, token: "org-image"}, // image 23 | {regex: /\[[xX\s\-\_]\]/, token: 'qualifier org-toggle'}, // checkbox 24 | {regex: /\#\+(?:(BEGIN|begin))_[a-zA-Z]*/, token: "comment", next: "env", sol: true}, // comments 25 | {regex: /:?[A-Z_]+\:.*/, token: "comment", sol: true}, // property drawers 26 | {regex: /(\#\+[a-zA-Z_]*)(\:.*)/, token: ["keyword", 'qualifier'], sol: true}, // environments 27 | {regex: /(CLOCK\:|SHEDULED\:|DEADLINE\:)(\s.+)/, token: ["comment", "keyword"]} 28 | ], 29 | env: [ 30 | {regex: /\#\+(?:(END|end))_[a-zA-Z]*/, token: "comment", next: "start", sol: true}, 31 | {regex: /.*/, token: "comment"} 32 | ] 33 | }); 34 | 35 | 36 | CodeMirror.registerHelper("fold", "orgmode", function(cm, start) { 37 | // init 38 | const levelToMatch = headerLevel(start.line); 39 | 40 | // no folding needed 41 | if(levelToMatch === null) return; 42 | 43 | // find folding limits 44 | const lastLine = cm.lastLine(); 45 | let end = start.line; 46 | while(end < lastLine){ 47 | end += 1; 48 | let level = headerLevel(end); 49 | if(level && level <= levelToMatch) { 50 | end = end - 1; 51 | break; 52 | }; 53 | } 54 | 55 | return { 56 | from: CodeMirror.Pos(start.line, cm.getLine(start.line).length), 57 | to: CodeMirror.Pos(end, cm.getLine(end).length) 58 | }; 59 | 60 | function headerLevel(lineNo) { 61 | var line = cm.getLine(lineNo); 62 | var match = /^\*+/.exec(line); 63 | if(match && match.length === 1 && /header/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0)))){ 64 | return match[0].length; 65 | } 66 | return null; 67 | } 68 | }); 69 | CodeMirror.registerGlobalHelper("fold", "drawer", function(mode) { 70 | return mode.name === 'orgmode' ? true : false; 71 | }, function(cm, start) { 72 | const drawer = isBeginningOfADrawer(start.line); 73 | if(drawer === false) return; 74 | 75 | // find folding limits 76 | const lastLine = cm.lastLine(); 77 | let end = start.line; 78 | while(end < lastLine){ 79 | end += 1; 80 | if(isEndOfADrawer(end)){ 81 | break; 82 | } 83 | } 84 | 85 | return { 86 | from: CodeMirror.Pos(start.line, cm.getLine(start.line).length), 87 | to: CodeMirror.Pos(end, cm.getLine(end).length) 88 | }; 89 | 90 | function isBeginningOfADrawer(lineNo) { 91 | var line = cm.getLine(lineNo); 92 | var match = /^\:.*\:$/.exec(line); 93 | if(match && match.length === 1 && match[0] !== ':END:'){ 94 | return true; 95 | } 96 | return false; 97 | } 98 | function isEndOfADrawer(lineNo){ 99 | var line = cm.getLine(lineNo); 100 | return line.trim() === ':END:' ? true : false; 101 | } 102 | }); 103 | 104 | 105 | CodeMirror.registerHelper("orgmode", "init", (editor, fn) => { 106 | editor.setOption("extraKeys", { 107 | "Tab": function(cm) { org_cycle(cm); }, 108 | "Shift-Tab": function(cm){ fn('shifttab', org_shifttab(cm)); }, 109 | "Alt-Left": function(cm){ org_metaleft(cm); }, 110 | "Alt-Right": function(cm){ org_metaright(cm); }, 111 | "Alt-Enter": function(cm){ org_meta_return(cm); }, 112 | "Alt-Up": function(cm){ org_metaup(cm); }, 113 | "Alt-Down": function(cm){ org_metadown(cm); }, 114 | "Shift-Alt-Left": function(cm){ org_shiftmetaleft(cm); }, 115 | "Shift-Alt-Right": function(cm){ org_shiftmetaright(cm); }, 116 | "Shift-Alt-Enter": function(cm){ org_insert_todo_heading(cm); }, 117 | "Shift-Left": function(cm){ org_shiftleft(cm); }, 118 | "Shift-Right": function(cm){ org_shiftright(cm); } 119 | }); 120 | fn('shifttab', org_set_fold(editor)); 121 | 122 | editor.on('mousedown', toggleHandler); 123 | editor.on('touchstart', toggleHandler); 124 | editor.on('gutterClick', foldLine); 125 | 126 | // fold everything except headers by default 127 | editor.operation(function() { 128 | for (var i = 0; i < editor.lineCount() ; i++) { 129 | if(/header/.test(editor.getTokenTypeAt(CodeMirror.Pos(i, 0))) === false){ 130 | fold(editor, CodeMirror.Pos(i, 0)); 131 | } 132 | } 133 | }); 134 | return CodeMirror.orgmode.destroy.bind(this, editor); 135 | }); 136 | 137 | CodeMirror.registerHelper("orgmode", "destroy", (editor) => { 138 | editor.off('mousedown', toggleHandler); 139 | editor.off('touchstart', toggleHandler); 140 | editor.off('gutterClick', foldLine); 141 | }); 142 | 143 | function foldLine(cm, line){ 144 | const cursor = {line: line, ch: 0}; 145 | isFold(cm, cursor) ? unfold(cm, cursor) : fold(cm, cursor); 146 | } 147 | 148 | 149 | let widgets = []; 150 | function toggleHandler(cm, e){ 151 | const position = cm.coordsChar({ 152 | left: e.clientX || (e.targetTouches && e.targetTouches[0].clientX), 153 | top: e.clientY || (e.targetTouches && e.targetTouches[0].clientY) 154 | }, "page"), 155 | token = cm.getTokenAt(position); 156 | 157 | _disableSelection(); 158 | if(/org-level-star/.test(token.type)){ 159 | _preventIfShould(); 160 | _foldHeadline(); 161 | _disableSelection(); 162 | }else if(/org-toggle/.test(token.type)){ 163 | _preventIfShould(); 164 | _toggleCheckbox(); 165 | _disableSelection(); 166 | }else if(/org-todo/.test(token.type)){ 167 | _preventIfShould(); 168 | _toggleTodo(); 169 | _disableSelection(); 170 | }else if(/org-done/.test(token.type)){ 171 | _preventIfShould(); 172 | _toggleDone(); 173 | _disableSelection(); 174 | }else if(/org-priority/.test(token.type)){ 175 | _preventIfShould(); 176 | _togglePriority(); 177 | _disableSelection(); 178 | }else if(/org-url/.test(token.type)){ 179 | _disableSelection(); 180 | _navigateLink(); 181 | }else if(/org-image/.test(token.type)){ 182 | _disableSelection(); 183 | _toggleImageWidget(); 184 | } 185 | 186 | function _preventIfShould(){ 187 | if('ontouchstart' in window) e.preventDefault(); 188 | } 189 | function _disableSelection(){ 190 | cm.on('beforeSelectionChange', _onSelectionChangeHandler); 191 | function _onSelectionChangeHandler(cm, obj){ 192 | obj.update([{ 193 | anchor: position, 194 | head: position 195 | }]); 196 | cm.off('beforeSelectionChange', _onSelectionChangeHandler); 197 | } 198 | } 199 | 200 | function _foldHeadline(){ 201 | const line = position.line; 202 | if(line >= 0){ 203 | const cursor = {line: line, ch: 0}; 204 | isFold(cm, cursor) ? unfold(cm, cursor) : fold(cm, cursor); 205 | } 206 | } 207 | 208 | function _toggleCheckbox(){ 209 | const line = position.line; 210 | const content = cm.getRange({line: line, ch: token.start}, {line: line, ch: token.end}); 211 | let new_content = content === "[X]" || content === "[x]" ? "[ ]" : "[X]"; 212 | cm.replaceRange(new_content, {line: line, ch: token.start}, {line: line, ch: token.end}); 213 | } 214 | 215 | function _toggleTodo(){ 216 | const line = position.line; 217 | cm.replaceRange("DONE", {line: line, ch: token.start}, {line: line, ch: token.end}); 218 | } 219 | 220 | function _toggleDone(){ 221 | const line = position.line; 222 | cm.replaceRange("TODO", {line: line, ch: token.start}, {line: line, ch: token.end}); 223 | } 224 | 225 | function _togglePriority(){ 226 | const PRIORITIES = [" [#A] ", " [#B] ", " [#C] ", " [#A] "]; 227 | const line = position.line; 228 | const content = cm.getRange({line: line, ch: token.start}, {line: line, ch: token.end}); 229 | let new_content = PRIORITIES[PRIORITIES.indexOf(content) + 1]; 230 | cm.replaceRange(new_content, {line: line, ch: token.start}, {line: line, ch: token.end}); 231 | } 232 | 233 | function _toggleImageWidget(){ 234 | let exist = !!widgets 235 | .filter((line) => line === position.line)[0]; 236 | 237 | if(exist === false){ 238 | if(!token.string.match(/\[\[(.*)\]\]/)) return null; 239 | let $node = _buildImage(RegExp.$1); 240 | const widget = cm.addLineWidget(position.line, $node, {coverGutter: false}); 241 | widgets.push(position.line); 242 | $node.addEventListener('click', closeWidget); 243 | 244 | function closeWidget(){ 245 | widget.clear(); 246 | $node.removeEventListener('click', closeWidget); 247 | widgets = widgets.filter((line) => line !== position.line); 248 | } 249 | } 250 | function _buildImage(src){ 251 | let $el = document.createElement("div"); 252 | let $img = document.createElement("img"); 253 | 254 | if(/^https?\:\/\//.test(src)){ 255 | $img.src = src; 256 | }else{ 257 | const root_path = dirname(window.location.pathname.replace(/^\/view/, '')); 258 | const img_path = src; 259 | $img.src = "/api/files/cat?path="+encodeURIComponent(pathBuilder(root_path, img_path)); 260 | } 261 | $el.appendChild($img); 262 | return $el; 263 | } 264 | return null; 265 | } 266 | 267 | function _navigateLink(){ 268 | token.string.match(/\[\[(.*?)\]\[/); 269 | const link = RegExp.$1; 270 | if(!link) return; 271 | 272 | if(/^https?\:\/\//.test(link)){ 273 | window.open(link); 274 | }else{ 275 | const root_path = dirname(window.location.pathname.replace(/^\/view/, '')); 276 | const link_path = link; 277 | window.open("/view"+pathBuilder(root_path, link_path)); 278 | } 279 | } 280 | } 281 | 282 | CodeMirror.defineMIME("text/org", "org"); 283 | }); 284 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | --------------------------------------------------------------------------------