diff options
author | Yukai Huang | 2017-03-07 22:35:54 +0800 |
---|---|---|
committer | Yukai Huang | 2017-03-08 21:43:32 +0800 |
commit | 6556c284e504790bd9ed0facac3322320e0c347b (patch) | |
tree | 6400dfbb9207c71aa3cd5d5c28a7c476f5c124b7 /public/js/lib/editor/utils.js | |
parent | 121d84863a055dbe259cdcfb98583a376bd8e2fa (diff) |
Extract editor related code
- in public/js/lib/editor/index.js
Diffstat (limited to '')
-rw-r--r-- | public/js/lib/editor/utils.js | 46 |
1 files changed, 46 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..120d3646 --- /dev/null +++ b/public/js/lib/editor/utils.js @@ -0,0 +1,46 @@ +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()) { + var from = range.from(), 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'); + } + } + } + } + } +} |