diff options
author | Wu Cheng-Han | 2017-03-15 22:13:05 +0800 |
---|---|---|
committer | Wu Cheng-Han | 2017-03-15 22:13:05 +0800 |
commit | b07eeed0c5a3c8de28e27326967cea592071ca6a (patch) | |
tree | 1c9c101b13554abc3cb5e5ce8161fb4c79ced535 /public/js/lib/editor/utils.js | |
parent | 4a1d08c653070e856bceb1bc4a7d8ff7ab1aa203 (diff) | |
parent | 16d80edc653dc02407cd570adfc485300ec9a66b (diff) |
Merge branch 'master' of https://github.com/jackycute/HackMD
Diffstat (limited to 'public/js/lib/editor/utils.js')
-rw-r--r-- | public/js/lib/editor/utils.js | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/public/js/lib/editor/utils.js b/public/js/lib/editor/utils.js new file mode 100644 index 00000000..3702a166 --- /dev/null +++ b/public/js/lib/editor/utils.js @@ -0,0 +1,48 @@ +const wrapSymbols = ['*', '_', '~', '^', '+', '='] +export function wrapTextWith (editor, cm, symbol) { + if (!cm.getSelection()) { + return CodeMirror.Pass + } else { + var ranges = cm.listSelections() + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i] + if (!range.empty()) { + const from = range.from() + const to = range.to() + + if (symbol !== 'Backspace') { + cm.replaceRange(symbol, to, to, '+input') + cm.replaceRange(symbol, from, from, '+input') + // workaround selection range not correct after add symbol + var _ranges = cm.listSelections() + var anchorIndex = editor.indexFromPos(_ranges[i].anchor) + var headIndex = editor.indexFromPos(_ranges[i].head) + if (anchorIndex > headIndex) { + _ranges[i].anchor.ch-- + } else { + _ranges[i].head.ch-- + } + cm.setSelections(_ranges) + } else { + var preEndPos = { + line: to.line, + ch: to.ch + 1 + } + var preText = cm.getRange(to, preEndPos) + var preIndex = wrapSymbols.indexOf(preText) + var postEndPos = { + line: from.line, + ch: from.ch - 1 + } + var postText = cm.getRange(postEndPos, from) + var postIndex = wrapSymbols.indexOf(postText) + // check if surround symbol are list in array and matched + if (preIndex > -1 && postIndex > -1 && preIndex === postIndex) { + cm.replaceRange('', to, preEndPos, '+delete') + cm.replaceRange('', postEndPos, from, '+delete') + } + } + } + } + } +} |