not really known
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2260 lines
81 KiB

  1. // needs Markdown.Converter.js at the moment
  2. (function () {
  3. var util = {},
  4. position = {},
  5. ui = {},
  6. doc = window.document,
  7. re = window.RegExp,
  8. nav = window.navigator,
  9. SETTINGS = { lineLength: 72 },
  10. // Used to work around some browser bugs where we can't use feature testing.
  11. uaSniffed = {
  12. isIE: /msie/.test(nav.userAgent.toLowerCase()),
  13. isIE_5or6: /msie 6/.test(nav.userAgent.toLowerCase()) || /msie 5/.test(nav.userAgent.toLowerCase()),
  14. isOpera: /opera/.test(nav.userAgent.toLowerCase())
  15. };
  16. var defaultsStrings = {
  17. bold: "Strong <strong> Ctrl+B",
  18. boldexample: "strong text",
  19. italic: "Emphasis <em> Ctrl+I",
  20. italicexample: "emphasized text",
  21. link: "Hyperlink <a> Ctrl+L",
  22. linkdescription: "enter link description here",
  23. linkdialog: "<p><b>Insert Hyperlink</b></p><p>http://example.com/ \"optional title\"</p>",
  24. quote: "Blockquote <blockquote> Ctrl+Q",
  25. quoteexample: "Blockquote",
  26. code: "Code Sample <pre><code> Ctrl+K",
  27. codeexample: "enter code here",
  28. image: "Image <img> Ctrl+G",
  29. imagedescription: "enter image description here",
  30. imagedialog: "<p><b>Insert Image</b></p><p>http://example.com/images/diagram.jpg \"optional title\"<br><br>Need <a href='http://www.google.com/search?q=free+image+hosting' target='_blank'>free image hosting?</a></p>",
  31. olist: "Numbered List <ol> Ctrl+O",
  32. ulist: "Bulleted List <ul> Ctrl+U",
  33. litem: "List item",
  34. heading: "Heading <h1>/<h2> Ctrl+H",
  35. headingexample: "Heading",
  36. hr: "Horizontal Rule <hr> Ctrl+R",
  37. undo: "Undo - Ctrl+Z",
  38. redo: "Redo - Ctrl+Y",
  39. redomac: "Redo - Ctrl+Shift+Z",
  40. help: "Markdown Editing Help"
  41. };
  42. // -------------------------------------------------------------------
  43. // YOUR CHANGES GO HERE
  44. //
  45. // I've tried to localize the things you are likely to change to
  46. // this area.
  47. // -------------------------------------------------------------------
  48. // The default text that appears in the dialog input box when entering
  49. // links.
  50. var imageDefaultText = "http://";
  51. var linkDefaultText = "http://";
  52. // -------------------------------------------------------------------
  53. // END OF YOUR CHANGES
  54. // -------------------------------------------------------------------
  55. // options, if given, can have the following properties:
  56. // options.helpButton = { handler: yourEventHandler }
  57. // options.strings = { italicexample: "slanted text" }
  58. // `yourEventHandler` is the click handler for the help button.
  59. // If `options.helpButton` isn't given, not help button is created.
  60. // `options.strings` can have any or all of the same properties as
  61. // `defaultStrings` above, so you can just override some string displayed
  62. // to the user on a case-by-case basis, or translate all strings to
  63. // a different language.
  64. //
  65. // For backwards compatibility reasons, the `options` argument can also
  66. // be just the `helpButton` object, and `strings.help` can also be set via
  67. // `helpButton.title`. This should be considered legacy.
  68. //
  69. // The constructed editor object has the methods:
  70. // - getConverter() returns the markdown converter object that was passed to the constructor
  71. // - run() actually starts the editor; should be called after all necessary plugins are registered. Calling this more than once is a no-op.
  72. // - refreshPreview() forces the preview to be updated. This method is only available after run() was called.
  73. Markdown.Editor = function (markdownConverter, idPostfix, options) {
  74. options = options || {};
  75. if (typeof options.handler === "function") { //backwards compatible behavior
  76. options = { helpButton: options };
  77. }
  78. options.strings = options.strings || {};
  79. if (options.helpButton) {
  80. options.strings.help = options.strings.help || options.helpButton.title;
  81. }
  82. var getString = function (identifier) { return options.strings[identifier] || defaultsStrings[identifier]; }
  83. idPostfix = idPostfix || "";
  84. var hooks = this.hooks = new Markdown.HookCollection();
  85. hooks.addNoop("onPreviewRefresh"); // called with no arguments after the preview has been refreshed
  86. hooks.addNoop("postBlockquoteCreation"); // called with the user's selection *after* the blockquote was created; should return the actual to-be-inserted text
  87. hooks.addFalse("insertImageDialog"); /* called with one parameter: a callback to be called with the URL of the image. If the application creates
  88. * its own image insertion dialog, this hook should return true, and the callback should be called with the chosen
  89. * image url (or null if the user cancelled). If this hook returns false, the default dialog will be used.
  90. */
  91. this.getConverter = function () { return markdownConverter; }
  92. var that = this,
  93. panels;
  94. this.run = function () {
  95. if (panels)
  96. return; // already initialized
  97. panels = new PanelCollection(idPostfix);
  98. var commandManager = new CommandManager(hooks, getString);
  99. var previewManager = new PreviewManager(markdownConverter, panels, function () { hooks.onPreviewRefresh(); });
  100. var undoManager, uiManager;
  101. if (!/\?noundo/.test(doc.location.href)) {
  102. undoManager = new UndoManager(function () {
  103. previewManager.refresh();
  104. if (uiManager) // not available on the first call
  105. uiManager.setUndoRedoButtonStates();
  106. }, panels);
  107. this.textOperation = function (f) {
  108. undoManager.setCommandMode();
  109. f();
  110. that.refreshPreview();
  111. }
  112. }
  113. uiManager = new UIManager(idPostfix, panels, undoManager, previewManager, commandManager, options.helpButton, getString);
  114. uiManager.setUndoRedoButtonStates();
  115. var forceRefresh = that.refreshPreview = function () { previewManager.refresh(true); };
  116. forceRefresh();
  117. };
  118. }
  119. // before: contains all the text in the input box BEFORE the selection.
  120. // after: contains all the text in the input box AFTER the selection.
  121. function Chunks() { }
  122. // startRegex: a regular expression to find the start tag
  123. // endRegex: a regular expresssion to find the end tag
  124. Chunks.prototype.findTags = function (startRegex, endRegex) {
  125. var chunkObj = this;
  126. var regex;
  127. if (startRegex) {
  128. regex = util.extendRegExp(startRegex, "", "$");
  129. this.before = this.before.replace(regex,
  130. function (match) {
  131. chunkObj.startTag = chunkObj.startTag + match;
  132. return "";
  133. });
  134. regex = util.extendRegExp(startRegex, "^", "");
  135. this.selection = this.selection.replace(regex,
  136. function (match) {
  137. chunkObj.startTag = chunkObj.startTag + match;
  138. return "";
  139. });
  140. }
  141. if (endRegex) {
  142. regex = util.extendRegExp(endRegex, "", "$");
  143. this.selection = this.selection.replace(regex,
  144. function (match) {
  145. chunkObj.endTag = match + chunkObj.endTag;
  146. return "";
  147. });
  148. regex = util.extendRegExp(endRegex, "^", "");
  149. this.after = this.after.replace(regex,
  150. function (match) {
  151. chunkObj.endTag = match + chunkObj.endTag;
  152. return "";
  153. });
  154. }
  155. };
  156. // If remove is false, the whitespace is transferred
  157. // to the before/after regions.
  158. //
  159. // If remove is true, the whitespace disappears.
  160. Chunks.prototype.trimWhitespace = function (remove) {
  161. var beforeReplacer, afterReplacer, that = this;
  162. if (remove) {
  163. beforeReplacer = afterReplacer = "";
  164. } else {
  165. beforeReplacer = function (s) { that.before += s; return ""; }
  166. afterReplacer = function (s) { that.after = s + that.after; return ""; }
  167. }
  168. this.selection = this.selection.replace(/^(\s*)/, beforeReplacer).replace(/(\s*)$/, afterReplacer);
  169. };
  170. Chunks.prototype.skipLines = function (nLinesBefore, nLinesAfter, findExtraNewlines) {
  171. if (nLinesBefore === undefined) {
  172. nLinesBefore = 1;
  173. }
  174. if (nLinesAfter === undefined) {
  175. nLinesAfter = 1;
  176. }
  177. nLinesBefore++;
  178. nLinesAfter++;
  179. var regexText;
  180. var replacementText;
  181. // chrome bug ... documented at: http://meta.stackoverflow.com/questions/63307/blockquote-glitch-in-editor-in-chrome-6-and-7/65985#65985
  182. if (navigator.userAgent.match(/Chrome/)) {
  183. "X".match(/()./);
  184. }
  185. this.selection = this.selection.replace(/(^\n*)/, "");
  186. this.startTag = this.startTag + re.$1;
  187. this.selection = this.selection.replace(/(\n*$)/, "");
  188. this.endTag = this.endTag + re.$1;
  189. this.startTag = this.startTag.replace(/(^\n*)/, "");
  190. this.before = this.before + re.$1;
  191. this.endTag = this.endTag.replace(/(\n*$)/, "");
  192. this.after = this.after + re.$1;
  193. if (this.before) {
  194. regexText = replacementText = "";
  195. while (nLinesBefore--) {
  196. regexText += "\\n?";
  197. replacementText += "\n";
  198. }
  199. if (findExtraNewlines) {
  200. regexText = "\\n*";
  201. }
  202. this.before = this.before.replace(new re(regexText + "$", ""), replacementText);
  203. }
  204. if (this.after) {
  205. regexText = replacementText = "";
  206. while (nLinesAfter--) {
  207. regexText += "\\n?";
  208. replacementText += "\n";
  209. }
  210. if (findExtraNewlines) {
  211. regexText = "\\n*";
  212. }
  213. this.after = this.after.replace(new re(regexText, ""), replacementText);
  214. }
  215. };
  216. // end of Chunks
  217. // A collection of the important regions on the page.
  218. // Cached so we don't have to keep traversing the DOM.
  219. // Also holds ieCachedRange and ieCachedScrollTop, where necessary; working around
  220. // this issue:
  221. // Internet explorer has problems with CSS sprite buttons that use HTML
  222. // lists. When you click on the background image "button", IE will
  223. // select the non-existent link text and discard the selection in the
  224. // textarea. The solution to this is to cache the textarea selection
  225. // on the button's mousedown event and set a flag. In the part of the
  226. // code where we need to grab the selection, we check for the flag
  227. // and, if it's set, use the cached area instead of querying the
  228. // textarea.
  229. //
  230. // This ONLY affects Internet Explorer (tested on versions 6, 7
  231. // and 8) and ONLY on button clicks. Keyboard shortcuts work
  232. // normally since the focus never leaves the textarea.
  233. function PanelCollection(postfix) {
  234. this.buttonBar = doc.getElementById("wmd-button-bar" + postfix);
  235. this.preview = doc.getElementById("wmd-preview" + postfix);
  236. this.input = doc.getElementById("wmd-input" + postfix);
  237. };
  238. // Returns true if the DOM element is visible, false if it's hidden.
  239. // Checks if display is anything other than none.
  240. util.isVisible = function (elem) {
  241. if (window.getComputedStyle) {
  242. // Most browsers
  243. return window.getComputedStyle(elem, null).getPropertyValue("display") !== "none";
  244. }
  245. else if (elem.currentStyle) {
  246. // IE
  247. return elem.currentStyle["display"] !== "none";
  248. }
  249. };
  250. // Adds a listener callback to a DOM element which is fired on a specified
  251. // event.
  252. util.addEvent = function (elem, event, listener) {
  253. if (elem.attachEvent) {
  254. // IE only. The "on" is mandatory.
  255. elem.attachEvent("on" + event, listener);
  256. }
  257. else {
  258. // Other browsers.
  259. elem.addEventListener(event, listener, false);
  260. }
  261. };
  262. // Removes a listener callback from a DOM element which is fired on a specified
  263. // event.
  264. util.removeEvent = function (elem, event, listener) {
  265. if (elem.detachEvent) {
  266. // IE only. The "on" is mandatory.
  267. elem.detachEvent("on" + event, listener);
  268. }
  269. else {
  270. // Other browsers.
  271. elem.removeEventListener(event, listener, false);
  272. }
  273. };
  274. // Converts \r\n and \r to \n.
  275. util.fixEolChars = function (text) {
  276. text = text.replace(/\r\n/g, "\n");
  277. text = text.replace(/\r/g, "\n");
  278. return text;
  279. };
  280. // Extends a regular expression. Returns a new RegExp
  281. // using pre + regex + post as the expression.
  282. // Used in a few functions where we have a base
  283. // expression and we want to pre- or append some
  284. // conditions to it (e.g. adding "$" to the end).
  285. // The flags are unchanged.
  286. //
  287. // regex is a RegExp, pre and post are strings.
  288. util.extendRegExp = function (regex, pre, post) {
  289. if (pre === null || pre === undefined) {
  290. pre = "";
  291. }
  292. if (post === null || post === undefined) {
  293. post = "";
  294. }
  295. var pattern = regex.toString();
  296. var flags;
  297. // Replace the flags with empty space and store them.
  298. pattern = pattern.replace(/\/([gim]*)$/, function (wholeMatch, flagsPart) {
  299. flags = flagsPart;
  300. return "";
  301. });
  302. // Remove the slash delimiters on the regular expression.
  303. pattern = pattern.replace(/(^\/|\/$)/g, "");
  304. pattern = pre + pattern + post;
  305. return new re(pattern, flags);
  306. }
  307. // UNFINISHED
  308. // The assignment in the while loop makes jslint cranky.
  309. // I'll change it to a better loop later.
  310. position.getTop = function (elem, isInner) {
  311. var result = elem.offsetTop;
  312. if (!isInner) {
  313. while (elem = elem.offsetParent) {
  314. result += elem.offsetTop;
  315. }
  316. }
  317. return result;
  318. };
  319. position.getHeight = function (elem) {
  320. return elem.offsetHeight || elem.scrollHeight;
  321. };
  322. position.getWidth = function (elem) {
  323. return elem.offsetWidth || elem.scrollWidth;
  324. };
  325. position.getPageSize = function () {
  326. var scrollWidth, scrollHeight;
  327. var innerWidth, innerHeight;
  328. // It's not very clear which blocks work with which browsers.
  329. if (self.innerHeight && self.scrollMaxY) {
  330. scrollWidth = doc.body.scrollWidth;
  331. scrollHeight = self.innerHeight + self.scrollMaxY;
  332. }
  333. else if (doc.body.scrollHeight > doc.body.offsetHeight) {
  334. scrollWidth = doc.body.scrollWidth;
  335. scrollHeight = doc.body.scrollHeight;
  336. }
  337. else {
  338. scrollWidth = doc.body.offsetWidth;
  339. scrollHeight = doc.body.offsetHeight;
  340. }
  341. if (self.innerHeight) {
  342. // Non-IE browser
  343. innerWidth = self.innerWidth;
  344. innerHeight = self.innerHeight;
  345. }
  346. else if (doc.documentElement && doc.documentElement.clientHeight) {
  347. // Some versions of IE (IE 6 w/ a DOCTYPE declaration)
  348. innerWidth = doc.documentElement.clientWidth;
  349. innerHeight = doc.documentElement.clientHeight;
  350. }
  351. else if (doc.body) {
  352. // Other versions of IE
  353. innerWidth = doc.body.clientWidth;
  354. innerHeight = doc.body.clientHeight;
  355. }
  356. var maxWidth = Math.max(scrollWidth, innerWidth);
  357. var maxHeight = Math.max(scrollHeight, innerHeight);
  358. return [maxWidth, maxHeight, innerWidth, innerHeight];
  359. };
  360. // Handles pushing and popping TextareaStates for undo/redo commands.
  361. // I should rename the stack variables to list.
  362. function UndoManager(callback, panels) {
  363. var undoObj = this;
  364. var undoStack = []; // A stack of undo states
  365. var stackPtr = 0; // The index of the current state
  366. var mode = "none";
  367. var lastState; // The last state
  368. var timer; // The setTimeout handle for cancelling the timer
  369. var inputStateObj;
  370. // Set the mode for later logic steps.
  371. var setMode = function (newMode, noSave) {
  372. if (mode != newMode) {
  373. mode = newMode;
  374. if (!noSave) {
  375. saveState();
  376. }
  377. }
  378. if (!uaSniffed.isIE || mode != "moving") {
  379. timer = setTimeout(refreshState, 1);
  380. }
  381. else {
  382. inputStateObj = null;
  383. }
  384. };
  385. var refreshState = function (isInitialState) {
  386. inputStateObj = new TextareaState(panels, isInitialState);
  387. timer = undefined;
  388. };
  389. this.setCommandMode = function () {
  390. mode = "command";
  391. saveState();
  392. timer = setTimeout(refreshState, 0);
  393. };
  394. this.canUndo = function () {
  395. return stackPtr > 1;
  396. };
  397. this.canRedo = function () {
  398. if (undoStack[stackPtr + 1]) {
  399. return true;
  400. }
  401. return false;
  402. };
  403. // Removes the last state and restores it.
  404. this.undo = function () {
  405. if (undoObj.canUndo()) {
  406. if (lastState) {
  407. // What about setting state -1 to null or checking for undefined?
  408. lastState.restore();
  409. lastState = null;
  410. }
  411. else {
  412. undoStack[stackPtr] = new TextareaState(panels);
  413. undoStack[--stackPtr].restore();
  414. if (callback) {
  415. callback();
  416. }
  417. }
  418. }
  419. mode = "none";
  420. panels.input.focus();
  421. refreshState();
  422. };
  423. // Redo an action.
  424. this.redo = function () {
  425. if (undoObj.canRedo()) {
  426. undoStack[++stackPtr].restore();
  427. if (callback) {
  428. callback();
  429. }
  430. }
  431. mode = "none";
  432. panels.input.focus();
  433. refreshState();
  434. };
  435. // Push the input area state to the stack.
  436. var saveState = function () {
  437. var currState = inputStateObj || new TextareaState(panels);
  438. if (!currState) {
  439. return false;
  440. }
  441. if (mode == "moving") {
  442. if (!lastState) {
  443. lastState = currState;
  444. }
  445. return;
  446. }
  447. if (lastState) {
  448. if (undoStack[stackPtr - 1].text != lastState.text) {
  449. undoStack[stackPtr++] = lastState;
  450. }
  451. lastState = null;
  452. }
  453. undoStack[stackPtr++] = currState;
  454. undoStack[stackPtr + 1] = null;
  455. if (callback) {
  456. callback();
  457. }
  458. };
  459. var handleCtrlYZ = function (event) {
  460. var handled = false;
  461. if ((event.ctrlKey || event.metaKey) && !event.altKey) {
  462. // IE and Opera do not support charCode.
  463. var keyCode = event.charCode || event.keyCode;
  464. var keyCodeChar = String.fromCharCode(keyCode);
  465. switch (keyCodeChar.toLowerCase()) {
  466. case "y":
  467. undoObj.redo();
  468. handled = true;
  469. break;
  470. case "z":
  471. if (!event.shiftKey) {
  472. undoObj.undo();
  473. }
  474. else {
  475. undoObj.redo();
  476. }
  477. handled = true;
  478. break;
  479. }
  480. }
  481. if (handled) {
  482. if (event.preventDefault) {
  483. event.preventDefault();
  484. }
  485. if (window.event) {
  486. window.event.returnValue = false;
  487. }
  488. return;
  489. }
  490. };
  491. // Set the mode depending on what is going on in the input area.
  492. var handleModeChange = function (event) {
  493. if (!event.ctrlKey && !event.metaKey) {
  494. var keyCode = event.keyCode;
  495. if ((keyCode >= 33 && keyCode <= 40) || (keyCode >= 63232 && keyCode <= 63235)) {
  496. // 33 - 40: page up/dn and arrow keys
  497. // 63232 - 63235: page up/dn and arrow keys on safari
  498. setMode("moving");
  499. }
  500. else if (keyCode == 8 || keyCode == 46 || keyCode == 127) {
  501. // 8: backspace
  502. // 46: delete
  503. // 127: delete
  504. setMode("deleting");
  505. }
  506. else if (keyCode == 13) {
  507. // 13: Enter
  508. setMode("newlines");
  509. }
  510. else if (keyCode == 27) {
  511. // 27: escape
  512. setMode("escape");
  513. }
  514. else if ((keyCode < 16 || keyCode > 20) && keyCode != 91) {
  515. // 16-20 are shift, etc.
  516. // 91: left window key
  517. // I think this might be a little messed up since there are
  518. // a lot of nonprinting keys above 20.
  519. setMode("typing");
  520. }
  521. }
  522. };
  523. var setEventHandlers = function () {
  524. util.addEvent(panels.input, "keypress", function (event) {
  525. // keyCode 89: y
  526. // keyCode 90: z
  527. if ((event.ctrlKey || event.metaKey) && !event.altKey && (event.keyCode == 89 || event.keyCode == 90)) {
  528. event.preventDefault();
  529. }
  530. });
  531. var handlePaste = function () {
  532. if (uaSniffed.isIE || (inputStateObj && inputStateObj.text != panels.input.value)) {
  533. if (timer == undefined) {
  534. mode = "paste";
  535. saveState();
  536. refreshState();
  537. }
  538. }
  539. };
  540. util.addEvent(panels.input, "keydown", handleCtrlYZ);
  541. util.addEvent(panels.input, "keydown", handleModeChange);
  542. util.addEvent(panels.input, "mousedown", function () {
  543. setMode("moving");
  544. });
  545. panels.input.onpaste = handlePaste;
  546. panels.input.ondrop = handlePaste;
  547. };
  548. var init = function () {
  549. setEventHandlers();
  550. refreshState(true);
  551. saveState();
  552. };
  553. init();
  554. }
  555. // end of UndoManager
  556. // The input textarea state/contents.
  557. // This is used to implement undo/redo by the undo manager.
  558. function TextareaState(panels, isInitialState) {
  559. // Aliases
  560. var stateObj = this;
  561. var inputArea = panels.input;
  562. this.init = function () {
  563. if (!util.isVisible(inputArea)) {
  564. return;
  565. }
  566. if (!isInitialState && doc.activeElement && doc.activeElement !== inputArea) { // this happens when tabbing out of the input box
  567. return;
  568. }
  569. this.setInputAreaSelectionStartEnd();
  570. this.scrollTop = inputArea.scrollTop;
  571. if (!this.text && inputArea.selectionStart || inputArea.selectionStart === 0) {
  572. this.text = inputArea.value;
  573. }
  574. }
  575. // Sets the selected text in the input box after we've performed an
  576. // operation.
  577. this.setInputAreaSelection = function () {
  578. if (!util.isVisible(inputArea)) {
  579. return;
  580. }
  581. if (inputArea.selectionStart !== undefined && !uaSniffed.isOpera) {
  582. inputArea.focus();
  583. inputArea.selectionStart = stateObj.start;
  584. inputArea.selectionEnd = stateObj.end;
  585. inputArea.scrollTop = stateObj.scrollTop;
  586. }
  587. else if (doc.selection) {
  588. if (doc.activeElement && doc.activeElement !== inputArea) {
  589. return;
  590. }
  591. inputArea.focus();
  592. var range = inputArea.createTextRange();
  593. range.moveStart("character", -inputArea.value.length);
  594. range.moveEnd("character", -inputArea.value.length);
  595. range.moveEnd("character", stateObj.end);
  596. range.moveStart("character", stateObj.start);
  597. range.select();
  598. }
  599. };
  600. this.setInputAreaSelectionStartEnd = function () {
  601. if (!panels.ieCachedRange && (inputArea.selectionStart || inputArea.selectionStart === 0)) {
  602. stateObj.start = inputArea.selectionStart;
  603. stateObj.end = inputArea.selectionEnd;
  604. }
  605. else if (doc.selection) {
  606. stateObj.text = util.fixEolChars(inputArea.value);
  607. // IE loses the selection in the textarea when buttons are
  608. // clicked. On IE we cache the selection. Here, if something is cached,
  609. // we take it.
  610. var range = panels.ieCachedRange || doc.selection.createRange();
  611. var fixedRange = util.fixEolChars(range.text);
  612. var marker = "\x07";
  613. var markedRange = marker + fixedRange + marker;
  614. range.text = markedRange;
  615. var inputText = util.fixEolChars(inputArea.value);
  616. range.moveStart("character", -markedRange.length);
  617. range.text = fixedRange;
  618. stateObj.start = inputText.indexOf(marker);
  619. stateObj.end = inputText.lastIndexOf(marker) - marker.length;
  620. var len = stateObj.text.length - util.fixEolChars(inputArea.value).length;
  621. if (len) {
  622. range.moveStart("character", -fixedRange.length);
  623. while (len--) {
  624. fixedRange += "\n";
  625. stateObj.end += 1;
  626. }
  627. range.text = fixedRange;
  628. }
  629. if (panels.ieCachedRange)
  630. stateObj.scrollTop = panels.ieCachedScrollTop; // this is set alongside with ieCachedRange
  631. panels.ieCachedRange = null;
  632. this.setInputAreaSelection();
  633. }
  634. };
  635. // Restore this state into the input area.
  636. this.restore = function () {
  637. if (stateObj.text != undefined && stateObj.text != inputArea.value) {
  638. inputArea.value = stateObj.text;
  639. }
  640. this.setInputAreaSelection();
  641. inputArea.scrollTop = stateObj.scrollTop;
  642. };
  643. // Gets a collection of HTML chunks from the inptut textarea.
  644. this.getChunks = function () {
  645. var chunk = new Chunks();
  646. chunk.before = util.fixEolChars(stateObj.text.substring(0, stateObj.start));
  647. chunk.startTag = "";
  648. chunk.selection = util.fixEolChars(stateObj.text.substring(stateObj.start, stateObj.end));
  649. chunk.endTag = "";
  650. chunk.after = util.fixEolChars(stateObj.text.substring(stateObj.end));
  651. chunk.scrollTop = stateObj.scrollTop;
  652. return chunk;
  653. };
  654. // Sets the TextareaState properties given a chunk of markdown.
  655. this.setChunks = function (chunk) {
  656. chunk.before = chunk.before + chunk.startTag;
  657. chunk.after = chunk.endTag + chunk.after;
  658. this.start = chunk.before.length;
  659. this.end = chunk.before.length + chunk.selection.length;
  660. this.text = chunk.before + chunk.selection + chunk.after;
  661. this.scrollTop = chunk.scrollTop;
  662. };
  663. this.init();
  664. };
  665. function PreviewManager(converter, panels, previewRefreshCallback) {
  666. var managerObj = this;
  667. var timeout;
  668. var elapsedTime;
  669. var oldInputText;
  670. var maxDelay = 3000;
  671. var startType = "delayed"; // The other legal value is "manual"
  672. // Adds event listeners to elements
  673. var setupEvents = function (inputElem, listener) {
  674. util.addEvent(inputElem, "input", listener);
  675. inputElem.onpaste = listener;
  676. inputElem.ondrop = listener;
  677. util.addEvent(inputElem, "keypress", listener);
  678. util.addEvent(inputElem, "keydown", listener);
  679. };
  680. var getDocScrollTop = function () {
  681. var result = 0;
  682. if (window.innerHeight) {
  683. result = window.pageYOffset;
  684. }
  685. else
  686. if (doc.documentElement && doc.documentElement.scrollTop) {
  687. result = doc.documentElement.scrollTop;
  688. }
  689. else
  690. if (doc.body) {
  691. result = doc.body.scrollTop;
  692. }
  693. return result;
  694. };
  695. var makePreviewHtml = function () {
  696. // If there is no registered preview panel
  697. // there is nothing to do.
  698. if (!panels.preview)
  699. return;
  700. var text = panels.input.value;
  701. if (text && text == oldInputText) {
  702. return; // Input text hasn't changed.
  703. }
  704. else {
  705. oldInputText = text;
  706. }
  707. var prevTime = new Date().getTime();
  708. text = converter.makeHtml(text);
  709. // Calculate the processing time of the HTML creation.
  710. // It's used as the delay time in the event listener.
  711. var currTime = new Date().getTime();
  712. elapsedTime = currTime - prevTime;
  713. pushPreviewHtml(text);
  714. };
  715. // setTimeout is already used. Used as an event listener.
  716. var applyTimeout = function () {
  717. if (timeout) {
  718. clearTimeout(timeout);
  719. timeout = undefined;
  720. }
  721. if (startType !== "manual") {
  722. var delay = 0;
  723. if (startType === "delayed") {
  724. delay = elapsedTime;
  725. }
  726. if (delay > maxDelay) {
  727. delay = maxDelay;
  728. }
  729. timeout = setTimeout(makePreviewHtml, delay);
  730. }
  731. };
  732. var getScaleFactor = function (panel) {
  733. if (panel.scrollHeight <= panel.clientHeight) {
  734. return 1;
  735. }
  736. return panel.scrollTop / (panel.scrollHeight - panel.clientHeight);
  737. };
  738. var setPanelScrollTops = function () {
  739. if (panels.preview) {
  740. panels.preview.scrollTop = (panels.preview.scrollHeight - panels.preview.clientHeight) * getScaleFactor(panels.preview);
  741. }
  742. };
  743. this.refresh = function (requiresRefresh) {
  744. if (requiresRefresh) {
  745. oldInputText = "";
  746. makePreviewHtml();
  747. }
  748. else {
  749. applyTimeout();
  750. }
  751. };
  752. this.processingTime = function () {
  753. return elapsedTime;
  754. };
  755. var isFirstTimeFilled = true;
  756. // IE doesn't let you use innerHTML if the element is contained somewhere in a table
  757. // (which is the case for inline editing) -- in that case, detach the element, set the
  758. // value, and reattach. Yes, that *is* ridiculous.
  759. var ieSafePreviewSet = function (text) {
  760. var preview = panels.preview;
  761. var parent = preview.parentNode;
  762. var sibling = preview.nextSibling;
  763. parent.removeChild(preview);
  764. preview.innerHTML = text;
  765. if (!sibling)
  766. parent.appendChild(preview);
  767. else
  768. parent.insertBefore(preview, sibling);
  769. }
  770. var nonSuckyBrowserPreviewSet = function (text) {
  771. var output = panels.preview.contentWindow.document;
  772. output.open();
  773. output.writeln(text);
  774. output.close();
  775. }
  776. var previewSetter;
  777. var previewSet = function (text) {
  778. if (previewSetter)
  779. return previewSetter(text);
  780. try {
  781. nonSuckyBrowserPreviewSet(text);
  782. previewSetter = nonSuckyBrowserPreviewSet;
  783. } catch (e) {
  784. previewSetter = ieSafePreviewSet;
  785. previewSetter(text);
  786. }
  787. };
  788. var pushPreviewHtml = function (text) {
  789. var emptyTop = position.getTop(panels.input) - getDocScrollTop();
  790. if (panels.preview) {
  791. previewSet(text);
  792. previewRefreshCallback();
  793. }
  794. setPanelScrollTops();
  795. if (isFirstTimeFilled) {
  796. isFirstTimeFilled = false;
  797. return;
  798. }
  799. var fullTop = position.getTop(panels.input) - getDocScrollTop();
  800. if (uaSniffed.isIE) {
  801. setTimeout(function () {
  802. window.scrollBy(0, fullTop - emptyTop);
  803. }, 0);
  804. }
  805. else {
  806. window.scrollBy(0, fullTop - emptyTop);
  807. }
  808. };
  809. var init = function () {
  810. setupEvents(panels.input, applyTimeout);
  811. makePreviewHtml();
  812. if (panels.preview) {
  813. panels.preview.scrollTop = 0;
  814. }
  815. };
  816. init();
  817. };
  818. // Creates the background behind the hyperlink text entry box.
  819. // And download dialog
  820. // Most of this has been moved to CSS but the div creation and
  821. // browser-specific hacks remain here.
  822. ui.createBackground = function () {
  823. var background = doc.createElement("div"),
  824. style = background.style;
  825. background.className = "wmd-prompt-background";
  826. style.position = "absolute";
  827. style.top = "0";
  828. style.zIndex = "1000";
  829. if (uaSniffed.isIE) {
  830. style.filter = "alpha(opacity=50)";
  831. }
  832. else {
  833. style.opacity = "0.5";
  834. }
  835. var pageSize = position.getPageSize();
  836. style.height = pageSize[1] + "px";
  837. if (uaSniffed.isIE) {
  838. style.left = doc.documentElement.scrollLeft;
  839. style.width = doc.documentElement.clientWidth;
  840. }
  841. else {
  842. style.left = "0";
  843. style.width = "100%";
  844. }
  845. doc.body.appendChild(background);
  846. return background;
  847. };
  848. // This simulates a modal dialog box and asks for the URL when you
  849. // click the hyperlink or image buttons.
  850. //
  851. // text: The html for the input box.
  852. // defaultInputText: The default value that appears in the input box.
  853. // callback: The function which is executed when the prompt is dismissed, either via OK or Cancel.
  854. // It receives a single argument; either the entered text (if OK was chosen) or null (if Cancel
  855. // was chosen).
  856. ui.prompt = function (text, defaultInputText, callback) {
  857. // These variables need to be declared at this level since they are used
  858. // in multiple functions.
  859. var dialog; // The dialog box.
  860. var input; // The text box where you enter the hyperlink.
  861. if (defaultInputText === undefined) {
  862. defaultInputText = "";
  863. }
  864. // Used as a keydown event handler. Esc dismisses the prompt.
  865. // Key code 27 is ESC.
  866. var checkEscape = function (key) {
  867. var code = (key.charCode || key.keyCode);
  868. if (code === 27) {
  869. close(true);
  870. }
  871. };
  872. // Dismisses the hyperlink input box.
  873. // isCancel is true if we don't care about the input text.
  874. // isCancel is false if we are going to keep the text.
  875. var close = function (isCancel) {
  876. util.removeEvent(doc.body, "keydown", checkEscape);
  877. var text = input.value;
  878. if (isCancel) {
  879. text = null;
  880. }
  881. else {
  882. // Fixes common pasting errors.
  883. text = text.replace(/^http:\/\/(https?|ftp):\/\//, '$1://');
  884. if (!/^(?:https?|ftp):\/\//.test(text))
  885. text = 'http://' + text;
  886. }
  887. dialog.parentNode.removeChild(dialog);
  888. callback(text);
  889. return false;
  890. };
  891. // Create the text input box form/window.
  892. var createDialog = function () {
  893. // The main dialog box.
  894. dialog = doc.createElement("div");
  895. dialog.className = "wmd-prompt-dialog";
  896. dialog.style.padding = "10px;";
  897. dialog.style.position = "fixed";
  898. dialog.style.width = "400px";
  899. dialog.style.zIndex = "1001";
  900. // The dialog text.
  901. var question = doc.createElement("div");
  902. question.innerHTML = text;
  903. question.style.padding = "5px";
  904. dialog.appendChild(question);
  905. // The web form container for the text box and buttons.
  906. var form = doc.createElement("form"),
  907. style = form.style;
  908. form.onsubmit = function () { return close(false); };
  909. style.padding = "0";
  910. style.margin = "0";
  911. style.cssFloat = "left";
  912. style.width = "100%";
  913. style.textAlign = "center";
  914. style.position = "relative";
  915. dialog.appendChild(form);
  916. // The input text box
  917. input = doc.createElement("input");
  918. input.type = "text";
  919. input.value = defaultInputText;
  920. style = input.style;
  921. style.display = "block";
  922. style.width = "80%";
  923. style.marginLeft = style.marginRight = "auto";
  924. form.appendChild(input);
  925. // The ok button
  926. var okButton = doc.createElement("input");
  927. okButton.type = "button";
  928. okButton.onclick = function () { return close(false); };
  929. okButton.value = "OK";
  930. style = okButton.style;
  931. style.margin = "10px";
  932. style.display = "inline";
  933. style.width = "7em";
  934. // The cancel button
  935. var cancelButton = doc.createElement("input");
  936. cancelButton.type = "button";
  937. cancelButton.onclick = function () { return close(true); };
  938. cancelButton.value = "Cancel";
  939. style = cancelButton.style;
  940. style.margin = "10px";
  941. style.display = "inline";
  942. style.width = "7em";
  943. form.appendChild(okButton);
  944. form.appendChild(cancelButton);
  945. util.addEvent(doc.body, "keydown", checkEscape);
  946. dialog.style.top = "50%";
  947. dialog.style.left = "50%";
  948. dialog.style.display = "block";
  949. if (uaSniffed.isIE_5or6) {
  950. dialog.style.position = "absolute";
  951. dialog.style.top = doc.documentElement.scrollTop + 200 + "px";
  952. dialog.style.left = "50%";
  953. }
  954. doc.body.appendChild(dialog);
  955. // This has to be done AFTER adding the dialog to the form if you
  956. // want it to be centered.
  957. dialog.style.marginTop = -(position.getHeight(dialog) / 2) + "px";
  958. dialog.style.marginLeft = -(position.getWidth(dialog) / 2) + "px";
  959. };
  960. // Why is this in a zero-length timeout?
  961. // Is it working around a browser bug?
  962. setTimeout(function () {
  963. createDialog();
  964. var defTextLen = defaultInputText.length;
  965. if (input.selectionStart !== undefined) {
  966. input.selectionStart = 0;
  967. input.selectionEnd = defTextLen;
  968. }
  969. else if (input.createTextRange) {
  970. var range = input.createTextRange();
  971. range.collapse(false);
  972. range.moveStart("character", -defTextLen);
  973. range.moveEnd("character", defTextLen);
  974. range.select();
  975. }
  976. input.focus();
  977. }, 0);
  978. };
  979. function UIManager(postfix, panels, undoManager, previewManager, commandManager, helpOptions, getString) {
  980. var inputBox = panels.input,
  981. buttons = {}; // buttons.undo, buttons.link, etc. The actual DOM elements.
  982. makeSpritedButtonRow();
  983. var keyEvent = "keydown";
  984. if (uaSniffed.isOpera) {
  985. keyEvent = "keypress";
  986. }
  987. util.addEvent(inputBox, keyEvent, function (key) {
  988. // Check to see if we have a button key and, if so execute the callback.
  989. if ((key.ctrlKey || key.metaKey) && !key.altKey && !key.shiftKey) {
  990. var keyCode = key.charCode || key.keyCode;
  991. var keyCodeStr = String.fromCharCode(keyCode).toLowerCase();
  992. switch (keyCodeStr) {
  993. case "b":
  994. doClick(buttons.bold);
  995. break;
  996. case "i":
  997. doClick(buttons.italic);
  998. break;
  999. case "l":
  1000. doClick(buttons.link);
  1001. break;
  1002. case "q":
  1003. doClick(buttons.quote);
  1004. break;
  1005. case "k":
  1006. doClick(buttons.code);
  1007. break;
  1008. case "g":
  1009. doClick(buttons.image);
  1010. break;
  1011. case "o":
  1012. doClick(buttons.olist);
  1013. break;
  1014. case "u":
  1015. doClick(buttons.ulist);
  1016. break;
  1017. case "h":
  1018. doClick(buttons.heading);
  1019. break;
  1020. case "r":
  1021. doClick(buttons.hr);
  1022. break;
  1023. case "y":
  1024. doClick(buttons.redo);
  1025. break;
  1026. case "z":
  1027. if (key.shiftKey) {
  1028. doClick(buttons.redo);
  1029. }
  1030. else {
  1031. doClick(buttons.undo);
  1032. }
  1033. break;
  1034. default:
  1035. return;
  1036. }
  1037. if (key.preventDefault) {
  1038. key.preventDefault();
  1039. }
  1040. if (window.event) {
  1041. window.event.returnValue = false;
  1042. }
  1043. }
  1044. });
  1045. // Auto-indent on shift-enter
  1046. util.addEvent(inputBox, "keyup", function (key) {
  1047. if (key.shiftKey && !key.ctrlKey && !key.metaKey) {
  1048. var keyCode = key.charCode || key.keyCode;
  1049. // Character 13 is Enter
  1050. if (keyCode === 13) {
  1051. var fakeButton = {};
  1052. fakeButton.textOp = bindCommand("doAutoindent");
  1053. doClick(fakeButton);
  1054. }
  1055. }
  1056. });
  1057. // special handler because IE clears the context of the textbox on ESC
  1058. if (uaSniffed.isIE) {
  1059. util.addEvent(inputBox, "keydown", function (key) {
  1060. var code = key.keyCode;
  1061. if (code === 27) {
  1062. return false;
  1063. }
  1064. });
  1065. }
  1066. // Perform the button's action.
  1067. function doClick(button) {
  1068. inputBox.focus();
  1069. if (button.textOp) {
  1070. if (undoManager) {
  1071. undoManager.setCommandMode();
  1072. }
  1073. var state = new TextareaState(panels);
  1074. if (!state) {
  1075. return;
  1076. }
  1077. var chunks = state.getChunks();
  1078. // Some commands launch a "modal" prompt dialog. Javascript
  1079. // can't really make a modal dialog box and the WMD code
  1080. // will continue to execute while the dialog is displayed.
  1081. // This prevents the dialog pattern I'm used to and means
  1082. // I can't do something like this:
  1083. //
  1084. // var link = CreateLinkDialog();
  1085. // makeMarkdownLink(link);
  1086. //
  1087. // Instead of this straightforward method of handling a
  1088. // dialog I have to pass any code which would execute
  1089. // after the dialog is dismissed (e.g. link creation)
  1090. // in a function parameter.
  1091. //
  1092. // Yes this is awkward and I think it sucks, but there's
  1093. // no real workaround. Only the image and link code
  1094. // create dialogs and require the function pointers.
  1095. var fixupInputArea = function () {
  1096. inputBox.focus();
  1097. if (chunks) {
  1098. state.setChunks(chunks);
  1099. }
  1100. state.restore();
  1101. previewManager.refresh();
  1102. };
  1103. var noCleanup = button.textOp(chunks, fixupInputArea);
  1104. if (!noCleanup) {
  1105. fixupInputArea();
  1106. }
  1107. }
  1108. if (button.execute) {
  1109. button.execute(undoManager);
  1110. }
  1111. };
  1112. function setupButton(button, isEnabled) {
  1113. var normalYShift = "0px";
  1114. var disabledYShift = "-20px";
  1115. var highlightYShift = "-40px";
  1116. var image = button.getElementsByTagName("span")[0];
  1117. if (isEnabled) {
  1118. image.style.backgroundPosition = button.XShift + " " + normalYShift;
  1119. button.onmouseover = function () {
  1120. image.style.backgroundPosition = this.XShift + " " + highlightYShift;
  1121. };
  1122. button.onmouseout = function () {
  1123. image.style.backgroundPosition = this.XShift + " " + normalYShift;
  1124. };
  1125. // IE tries to select the background image "button" text (it's
  1126. // implemented in a list item) so we have to cache the selection
  1127. // on mousedown.
  1128. if (uaSniffed.isIE) {
  1129. button.onmousedown = function () {
  1130. if (doc.activeElement && doc.activeElement !== panels.input) { // we're not even in the input box, so there's no selection
  1131. return;
  1132. }
  1133. panels.ieCachedRange = document.selection.createRange();
  1134. panels.ieCachedScrollTop = panels.input.scrollTop;
  1135. };
  1136. }
  1137. if (!button.isHelp) {
  1138. button.onclick = function () {
  1139. if (this.onmouseout) {
  1140. this.onmouseout();
  1141. }
  1142. doClick(this);
  1143. return false;
  1144. }
  1145. }
  1146. }
  1147. else {
  1148. image.style.backgroundPosition = button.XShift + " " + disabledYShift;
  1149. button.onmouseover = button.onmouseout = button.onclick = function () { };
  1150. }
  1151. }
  1152. function bindCommand(method) {
  1153. if (typeof method === "string")
  1154. {method = commandManager[method];
  1155. }
  1156. return function () { method.apply(commandManager, arguments); }
  1157. }
  1158. function makeSpritedButtonRow() {
  1159. //var buttonBar = panels.buttonBar;
  1160. /*var normalYShift = "0px";
  1161. var disabledYShift = "-20px";
  1162. var highlightYShift = "-40px";
  1163. <div id="main-toolbar" class="toolbar">
  1164. <button class="toolbutton" id="activity-button" title="My Activity"></button>
  1165. <button class="toolbutton wmd-button" id="wmd-bold-button-second" title="Strong <strong> (Ctrl + B)"></button>
  1166. <button class="toolbutton wmd-button" id="wmd-italic-button-second" title="Emphasis <em> (Ctrl + I)"></button>
  1167. */
  1168. var maintoolbar = document.getElementById("main-toolbar");
  1169. //console.log(maintoolbar);
  1170. //buttonRow.id = "wmd-button-row" + postfix;
  1171. //buttonRow.className = 'wmd-button-row';
  1172. //buttonRow = buttonBar.appendChild(buttonRow);
  1173. //var xPosition = 0;
  1174. var makeButton = function (id, title, XShift, textOp) {
  1175. var button = document.createElement("button");
  1176. button.className = "toolbutton";
  1177. //button.style.left = xPosition + "px";
  1178. //xPosition += 25;
  1179. //var buttonImage = document.createElement("span");
  1180. button.id = id;
  1181. button.title = title;
  1182. //button.XShift = XShift;
  1183. if (textOp)
  1184. button.textOp = textOp;
  1185. //setupButton(button, true);
  1186. //buttonRow.appendChild(button);
  1187. maintoolbar.appendChild(button);
  1188. return button;
  1189. };
  1190. /*
  1191. var makeSpacer = function (num) {
  1192. var spacer = document.createElement("li");
  1193. spacer.className = "wmd-spacer wmd-spacer" + num;
  1194. spacer.id = "wmd-spacer" + num + postfix;
  1195. buttonRow.appendChild(spacer);
  1196. xPosition += 25;
  1197. }
  1198. */
  1199. if(doc.getElementById("wmd-bold-button-second")==null){
  1200. buttons.bold = makeButton("wmd-bold-button-second", getString("bold"), "0px", bindCommand("doBold"));
  1201. buttons.bold.onclick = function (){doClick(buttons.bold);};
  1202. buttons.italic = makeButton("wmd-italic-button-second", getString("italic"), "-20px", bindCommand("doItalic"));
  1203. buttons.italic.onclick = function (){ doClick(buttons.italic);};
  1204. buttons.heading = makeButton("wmd-heading-button", getString("heading"), "-160px", bindCommand("doHeading"));
  1205. buttons.heading.onclick = function (){ doClick(buttons.heading);};
  1206. buttons.hr = makeButton("wmd-hr-button", getString("hr"), "-180px", bindCommand("doHorizontalRule"));
  1207. buttons.hr.onclick = function (){ doClick(buttons.hr);};
  1208. buttons.olist = makeButton("wmd-olist-button", getString("olist"), "-120px", bindCommand(function (chunk, postProcessing) {
  1209. this.doList(chunk, postProcessing, true);
  1210. }));
  1211. buttons.olist.onclick = function () {doClick(buttons.olist);};
  1212. buttons.ulist = makeButton("wmd-ulist-button", getString("ulist"), "-140px", bindCommand(function (chunk, postProcessing) {
  1213. this.doList(chunk, postProcessing, false);
  1214. }));
  1215. buttons.ulist.onclick = function () {doClick(buttons.ulist);};
  1216. buttons.code = makeButton("wmd-code-button", getString("code"), "-80px", bindCommand("doCode"));
  1217. buttons.code.onclick = function () {doClick(buttons.code);};
  1218. buttons.quote = makeButton("wmd-quote-button", getString("quote"), "-60px", bindCommand("doBlockquote"));
  1219. buttons.quote.onclick = function () {doClick(buttons.quote);};
  1220. buttons.link = makeButton("wmd-link-button", getString("link"), "-40px", bindCommand(function (chunk, postProcessing) {
  1221. return this.doLinkOrImage(chunk, postProcessing, false);
  1222. }));
  1223. buttons.link.onclick = function () {doClick(buttons.link);};
  1224. var redoTitle = /win/.test(nav.platform.toLowerCase()) ?
  1225. getString("redo") :
  1226. getString("redomac"); // mac and other non-Windows platforms
  1227. buttons.undo = makeButton("wmd-undo-button", getString("undo"), "-200px", null);
  1228. buttons.undo.execute = function (manager) { if (manager) manager.undo(); };
  1229. buttons.undo.onclick = function () {doClick(buttons.undo);}
  1230. buttons.redo = makeButton("wmd-redo-button", redoTitle, "-220px", null);
  1231. buttons.redo.execute = function (manager) { if (manager) manager.redo(); };
  1232. buttons.redo.onclick = function () {doClick(buttons.redo);}
  1233. }
  1234. //makeSpacer(1);
  1235. /*
  1236. buttons.code = makeButton("wmd-code-button", getString("code"), "-80px", bindCommand("doCode"));
  1237. buttons.image = makeButton("wmd-image-button", getString("image"), "-100px", bindCommand(function (chunk, postProcessing) {
  1238. return this.doLinkOrImage(chunk, postProcessing, true);
  1239. }));
  1240. //makeSpacer(2);
  1241. //makeSpacer(3);
  1242. */
  1243. if (helpOptions) {
  1244. var helpButton = document.createElement("li");
  1245. var helpButtonImage = document.createElement("span");
  1246. helpButton.appendChild(helpButtonImage);
  1247. helpButton.className = "wmd-button wmd-help-button";
  1248. helpButton.id = "wmd-help-button" + postfix;
  1249. helpButton.XShift = "-240px";
  1250. helpButton.isHelp = true;
  1251. helpButton.style.right = "0px";
  1252. helpButton.title = getString("help");
  1253. helpButton.onclick = helpOptions.handler;
  1254. //setupButton(helpButton, true);
  1255. //buttonRow.appendChild(helpButton);
  1256. buttons.help = helpButton;
  1257. }
  1258. setUndoRedoButtonStates();
  1259. }
  1260. function setUndoRedoButtonStates() {
  1261. if (undoManager) {
  1262. // setupButton(buttons.undo, undoManager.canUndo());
  1263. // setupButton(buttons.redo, undoManager.canRedo());
  1264. }
  1265. };
  1266. this.setUndoRedoButtonStates = setUndoRedoButtonStates;
  1267. }
  1268. function CommandManager(pluginHooks, getString) {
  1269. this.hooks = pluginHooks;
  1270. this.getString = getString;
  1271. }
  1272. var commandProto = CommandManager.prototype;
  1273. // The markdown symbols - 4 spaces = code, > = blockquote, etc.
  1274. commandProto.prefixes = "(?:\\s{4,}|\\s*>|\\s*-\\s+|\\s*\\d+\\.|=|\\+|-|_|\\*|#|\\s*\\[[^\n]]+\\]:)";
  1275. // Remove markdown symbols from the chunk selection.
  1276. commandProto.unwrap = function (chunk) {
  1277. var txt = new re("([^\\n])\\n(?!(\\n|" + this.prefixes + "))", "g");
  1278. chunk.selection = chunk.selection.replace(txt, "$1 $2");
  1279. };
  1280. commandProto.wrap = function (chunk, len) {
  1281. this.unwrap(chunk);
  1282. var regex = new re("(.{1," + len + "})( +|$\\n?)", "gm"),
  1283. that = this;
  1284. chunk.selection = chunk.selection.replace(regex, function (line, marked) {
  1285. if (new re("^" + that.prefixes, "").test(line)) {
  1286. return line;
  1287. }
  1288. return marked + "\n";
  1289. });
  1290. chunk.selection = chunk.selection.replace(/\s+$/, "");
  1291. };
  1292. commandProto.doBold = function (chunk, postProcessing) {
  1293. return this.doBorI(chunk, postProcessing, 2, this.getString("boldexample"));
  1294. };
  1295. commandProto.doItalic = function (chunk, postProcessing) {
  1296. return this.doBorI(chunk, postProcessing, 1, this.getString("italicexample"));
  1297. };
  1298. // chunk: The selected region that will be enclosed with */**
  1299. // nStars: 1 for italics, 2 for bold
  1300. // insertText: If you just click the button without highlighting text, this gets inserted
  1301. commandProto.doBorI = function (chunk, postProcessing, nStars, insertText) {
  1302. // Get rid of whitespace and fixup newlines.
  1303. chunk.trimWhitespace();
  1304. chunk.selection = chunk.selection.replace(/\n{2,}/g, "\n");
  1305. // Look for stars before and after. Is the chunk already marked up?
  1306. // note that these regex matches cannot fail
  1307. var starsBefore = /(\**$)/.exec(chunk.before)[0];
  1308. var starsAfter = /(^\**)/.exec(chunk.after)[0];
  1309. var prevStars = Math.min(starsBefore.length, starsAfter.length);
  1310. // Remove stars if we have to since the button acts as a toggle.
  1311. if ((prevStars >= nStars) && (prevStars != 2 || nStars != 1)) {
  1312. chunk.before = chunk.before.replace(re("[*]{" + nStars + "}$", ""), "");
  1313. chunk.after = chunk.after.replace(re("^[*]{" + nStars + "}", ""), "");
  1314. }
  1315. else if (!chunk.selection && starsAfter) {
  1316. // It's not really clear why this code is necessary. It just moves
  1317. // some arbitrary stuff around.
  1318. chunk.after = chunk.after.replace(/^([*_]*)/, "");
  1319. chunk.before = chunk.before.replace(/(\s?)$/, "");
  1320. var whitespace = re.$1;
  1321. chunk.before = chunk.before + starsAfter + whitespace;
  1322. }
  1323. else {
  1324. // In most cases, if you don't have any selected text and click the button
  1325. // you'll get a selected, marked up region with the default text inserted.
  1326. if (!chunk.selection && !starsAfter) {
  1327. chunk.selection = insertText;
  1328. }
  1329. // Add the true markup.
  1330. var markup = nStars <= 1 ? "*" : "**"; // shouldn't the test be = ?
  1331. chunk.before = chunk.before + markup;
  1332. chunk.after = markup + chunk.after;
  1333. }
  1334. return;
  1335. };
  1336. commandProto.stripLinkDefs = function (text, defsToAdd) {
  1337. text = text.replace(/^[ ]{0,3}\[(\d+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(\n*)["(](.+?)[")][ \t]*)?(?:\n+|$)/gm,
  1338. function (totalMatch, id, link, newlines, title) {
  1339. defsToAdd[id] = totalMatch.replace(/\s*$/, "");
  1340. if (newlines) {
  1341. // Strip the title and return that separately.
  1342. defsToAdd[id] = totalMatch.replace(/["(](.+?)[")]$/, "");
  1343. return newlines + title;
  1344. }
  1345. return "";
  1346. });
  1347. return text;
  1348. };
  1349. commandProto.addLinkDef = function (chunk, linkDef) {
  1350. var refNumber = 0; // The current reference number
  1351. var defsToAdd = {}; //
  1352. // Start with a clean slate by removing all previous link definitions.
  1353. chunk.before = this.stripLinkDefs(chunk.before, defsToAdd);
  1354. chunk.selection = this.stripLinkDefs(chunk.selection, defsToAdd);
  1355. chunk.after = this.stripLinkDefs(chunk.after, defsToAdd);
  1356. var defs = "";
  1357. var regex = /(\[)((?:\[[^\]]*\]|[^\[\]])*)(\][ ]?(?:\n[ ]*)?\[)(\d+)(\])/g;
  1358. var addDefNumber = function (def) {
  1359. refNumber++;
  1360. def = def.replace(/^[ ]{0,3}\[(\d+)\]:/, " [" + refNumber + "]:");
  1361. defs += "\n" + def;
  1362. };
  1363. // note that
  1364. // a) the recursive call to getLink cannot go infinite, because by definition
  1365. // of regex, inner is always a proper substring of wholeMatch, and
  1366. // b) more than one level of nesting is neither supported by the regex
  1367. // nor making a lot of sense (the only use case for nesting is a linked image)
  1368. var getLink = function (wholeMatch, before, inner, afterInner, id, end) {
  1369. inner = inner.replace(regex, getLink);
  1370. if (defsToAdd[id]) {
  1371. addDefNumber(defsToAdd[id]);
  1372. return before + inner + afterInner + refNumber + end;
  1373. }
  1374. return wholeMatch;
  1375. };
  1376. chunk.before = chunk.before.replace(regex, getLink);
  1377. if (linkDef) {
  1378. addDefNumber(linkDef);
  1379. }
  1380. else {
  1381. chunk.selection = chunk.selection.replace(regex, getLink);
  1382. }
  1383. var refOut = refNumber;
  1384. chunk.after = chunk.after.replace(regex, getLink);
  1385. if (chunk.after) {
  1386. chunk.after = chunk.after.replace(/\n*$/, "");
  1387. }
  1388. if (!chunk.after) {
  1389. chunk.selection = chunk.selection.replace(/\n*$/, "");
  1390. }
  1391. chunk.after += "\n\n" + defs;
  1392. return refOut;
  1393. };
  1394. // takes the line as entered into the add link/as image dialog and makes
  1395. // sure the URL and the optinal title are "nice".
  1396. function properlyEncoded(linkdef) {
  1397. return linkdef.replace(/^\s*(.*?)(?:\s+"(.+)")?\s*$/, function (wholematch, link, title) {
  1398. link = link.replace(/\?.*$/, function (querypart) {
  1399. return querypart.replace(/\+/g, " "); // in the query string, a plus and a space are identical
  1400. });
  1401. link = decodeURIComponent(link); // unencode first, to prevent double encoding
  1402. link = encodeURI(link).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  1403. link = link.replace(/\?.*$/, function (querypart) {
  1404. return querypart.replace(/\+/g, "%2b"); // since we replaced plus with spaces in the query part, all pluses that now appear where originally encoded
  1405. });
  1406. if (title) {
  1407. title = title.trim ? title.trim() : title.replace(/^\s*/, "").replace(/\s*$/, "");
  1408. title = title.replace(/"/g, "quot;").replace(/\(/g, "&#40;").replace(/\)/g, "&#41;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
  1409. }
  1410. return title ? link + ' "' + title + '"' : link;
  1411. });
  1412. }
  1413. commandProto.doLinkOrImage = function (chunk, postProcessing, isImage) {
  1414. chunk.trimWhitespace();
  1415. chunk.findTags(/\s*!?\[/, /\][ ]?(?:\n[ ]*)?(\[.*?\])?/);
  1416. var background;
  1417. if (chunk.endTag.length > 1 && chunk.startTag.length > 0) {
  1418. chunk.startTag = chunk.startTag.replace(/!?\[/, "");
  1419. chunk.endTag = "";
  1420. this.addLinkDef(chunk, null);
  1421. }
  1422. else {
  1423. // We're moving start and end tag back into the selection, since (as we're in the else block) we're not
  1424. // *removing* a link, but *adding* one, so whatever findTags() found is now back to being part of the
  1425. // link text. linkEnteredCallback takes care of escaping any brackets.
  1426. chunk.selection = chunk.startTag + chunk.selection + chunk.endTag;
  1427. chunk.startTag = chunk.endTag = "";
  1428. if (/\n\n/.test(chunk.selection)) {
  1429. this.addLinkDef(chunk, null);
  1430. return;
  1431. }
  1432. var that = this;
  1433. // The function to be executed when you enter a link and press OK or Cancel.
  1434. // Marks up the link and adds the ref.
  1435. var linkEnteredCallback = function (link) {
  1436. background.parentNode.removeChild(background);
  1437. if (link !== null) {
  1438. // ( $1
  1439. // [^\\] anything that's not a backslash
  1440. // (?:\\\\)* an even number (this includes zero) of backslashes
  1441. // )
  1442. // (?= followed by
  1443. // [[\]] an opening or closing bracket
  1444. // )
  1445. //
  1446. // In other words, a non-escaped bracket. These have to be escaped now to make sure they
  1447. // don't count as the end of the link or similar.
  1448. // Note that the actual bracket has to be a lookahead, because (in case of to subsequent brackets),
  1449. // the bracket in one match may be the "not a backslash" character in the next match, so it
  1450. // should not be consumed by the first match.
  1451. // The "prepend a space and finally remove it" steps makes sure there is a "not a backslash" at the
  1452. // start of the string, so this also works if the selection begins with a bracket. We cannot solve
  1453. // this by anchoring with ^, because in the case that the selection starts with two brackets, this
  1454. // would mean a zero-width match at the start. Since zero-width matches advance the string position,
  1455. // the first bracket could then not act as the "not a backslash" for the second.
  1456. chunk.selection = (" " + chunk.selection).replace(/([^\\](?:\\\\)*)(?=[[\]])/g, "$1\\").substr(1);
  1457. var linkDef = " [999]: " + properlyEncoded(link);
  1458. var num = that.addLinkDef(chunk, linkDef);
  1459. chunk.startTag = isImage ? "![" : "[";
  1460. chunk.endTag = "][" + num + "]";
  1461. if (!chunk.selection) {
  1462. if (isImage) {
  1463. chunk.selection = that.getString("imagedescription");
  1464. }
  1465. else {
  1466. chunk.selection = that.getString("linkdescription");
  1467. }
  1468. }
  1469. }
  1470. postProcessing();
  1471. };
  1472. background = ui.createBackground();
  1473. if (isImage) {
  1474. if (!this.hooks.insertImageDialog(linkEnteredCallback))
  1475. ui.prompt(this.getString("imagedialog"), imageDefaultText, linkEnteredCallback);
  1476. }
  1477. else {
  1478. ui.prompt(this.getString("linkdialog"), linkDefaultText, linkEnteredCallback);
  1479. }
  1480. return true;
  1481. }
  1482. };
  1483. // When making a list, hitting shift-enter will put your cursor on the next line
  1484. // at the current indent level.
  1485. commandProto.doAutoindent = function (chunk, postProcessing) {
  1486. var commandMgr = this,
  1487. fakeSelection = false;
  1488. chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]*\n$/, "\n\n");
  1489. chunk.before = chunk.before.replace(/(\n|^)[ ]{0,3}>[ \t]*\n$/, "\n\n");
  1490. chunk.before = chunk.before.replace(/(\n|^)[ \t]+\n$/, "\n\n");
  1491. // There's no selection, end the cursor wasn't at the end of the line:
  1492. // The user wants to split the current list item / code line / blockquote line
  1493. // (for the latter it doesn't really matter) in two. Temporarily select the
  1494. // (rest of the) line to achieve this.
  1495. if (!chunk.selection && !/^[ \t]*(?:\n|$)/.test(chunk.after)) {
  1496. chunk.after = chunk.after.replace(/^[^\n]*/, function (wholeMatch) {
  1497. chunk.selection = wholeMatch;
  1498. return "";
  1499. });
  1500. fakeSelection = true;
  1501. }
  1502. if (/(\n|^)[ ]{0,3}([*+-]|\d+[.])[ \t]+.*\n$/.test(chunk.before)) {
  1503. if (commandMgr.doList) {
  1504. commandMgr.doList(chunk);
  1505. }
  1506. }
  1507. if (/(\n|^)[ ]{0,3}>[ \t]+.*\n$/.test(chunk.before)) {
  1508. if (commandMgr.doBlockquote) {
  1509. commandMgr.doBlockquote(chunk);
  1510. }
  1511. }
  1512. if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
  1513. if (commandMgr.doCode) {
  1514. commandMgr.doCode(chunk);
  1515. }
  1516. }
  1517. if (fakeSelection) {
  1518. chunk.after = chunk.selection + chunk.after;
  1519. chunk.selection = "";
  1520. }
  1521. };
  1522. commandProto.doBlockquote = function (chunk, postProcessing) {
  1523. chunk.selection = chunk.selection.replace(/^(\n*)([^\r]+?)(\n*)$/,
  1524. function (totalMatch, newlinesBefore, text, newlinesAfter) {
  1525. chunk.before += newlinesBefore;
  1526. chunk.after = newlinesAfter + chunk.after;
  1527. return text;
  1528. });
  1529. chunk.before = chunk.before.replace(/(>[ \t]*)$/,
  1530. function (totalMatch, blankLine) {
  1531. chunk.selection = blankLine + chunk.selection;
  1532. return "";
  1533. });
  1534. chunk.selection = chunk.selection.replace(/^(\s|>)+$/, "");
  1535. chunk.selection = chunk.selection || this.getString("quoteexample");
  1536. // The original code uses a regular expression to find out how much of the
  1537. // text *directly before* the selection already was a blockquote:
  1538. /*
  1539. if (chunk.before) {
  1540. chunk.before = chunk.before.replace(/\n?$/, "\n");
  1541. }
  1542. chunk.before = chunk.before.replace(/(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*$)/,
  1543. function (totalMatch) {
  1544. chunk.startTag = totalMatch;
  1545. return "";
  1546. });
  1547. */
  1548. // This comes down to:
  1549. // Go backwards as many lines a possible, such that each line
  1550. // a) starts with ">", or
  1551. // b) is almost empty, except for whitespace, or
  1552. // c) is preceeded by an unbroken chain of non-empty lines
  1553. // leading up to a line that starts with ">" and at least one more character
  1554. // and in addition
  1555. // d) at least one line fulfills a)
  1556. //
  1557. // Since this is essentially a backwards-moving regex, it's susceptible to
  1558. // catstrophic backtracking and can cause the browser to hang;
  1559. // see e.g. http://meta.stackoverflow.com/questions/9807.
  1560. //
  1561. // Hence we replaced this by a simple state machine that just goes through the
  1562. // lines and checks for a), b), and c).
  1563. var match = "",
  1564. leftOver = "",
  1565. line;
  1566. if (chunk.before) {
  1567. var lines = chunk.before.replace(/\n$/, "").split("\n");
  1568. var inChain = false;
  1569. for (var i = 0; i < lines.length; i++) {
  1570. var good = false;
  1571. line = lines[i];
  1572. inChain = inChain && line.length > 0; // c) any non-empty line continues the chain
  1573. if (/^>/.test(line)) { // a)
  1574. good = true;
  1575. if (!inChain && line.length > 1) // c) any line that starts with ">" and has at least one more character starts the chain
  1576. inChain = true;
  1577. } else if (/^[ \t]*$/.test(line)) { // b)
  1578. good = true;
  1579. } else {
  1580. good = inChain; // c) the line is not empty and does not start with ">", so it matches if and only if we're in the chain
  1581. }
  1582. if (good) {
  1583. match += line + "\n";
  1584. } else {
  1585. leftOver += match + line;
  1586. match = "\n";
  1587. }
  1588. }
  1589. if (!/(^|\n)>/.test(match)) { // d)
  1590. leftOver += match;
  1591. match = "";
  1592. }
  1593. }
  1594. chunk.startTag = match;
  1595. chunk.before = leftOver;
  1596. // end of change
  1597. if (chunk.after) {
  1598. chunk.after = chunk.after.replace(/^\n?/, "\n");
  1599. }
  1600. chunk.after = chunk.after.replace(/^(((\n|^)(\n[ \t]*)*>(.+\n)*.*)+(\n[ \t]*)*)/,
  1601. function (totalMatch) {
  1602. chunk.endTag = totalMatch;
  1603. return "";
  1604. }
  1605. );
  1606. var replaceBlanksInTags = function (useBracket) {
  1607. var replacement = useBracket ? "> " : "";
  1608. if (chunk.startTag) {
  1609. chunk.startTag = chunk.startTag.replace(/\n((>|\s)*)\n$/,
  1610. function (totalMatch, markdown) {
  1611. return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
  1612. });
  1613. }
  1614. if (chunk.endTag) {
  1615. chunk.endTag = chunk.endTag.replace(/^\n((>|\s)*)\n/,
  1616. function (totalMatch, markdown) {
  1617. return "\n" + markdown.replace(/^[ ]{0,3}>?[ \t]*$/gm, replacement) + "\n";
  1618. });
  1619. }
  1620. };
  1621. if (/^(?![ ]{0,3}>)/m.test(chunk.selection)) {
  1622. this.wrap(chunk, SETTINGS.lineLength - 2);
  1623. chunk.selection = chunk.selection.replace(/^/gm, "> ");
  1624. replaceBlanksInTags(true);
  1625. chunk.skipLines();
  1626. } else {
  1627. chunk.selection = chunk.selection.replace(/^[ ]{0,3}> ?/gm, "");
  1628. this.unwrap(chunk);
  1629. replaceBlanksInTags(false);
  1630. if (!/^(\n|^)[ ]{0,3}>/.test(chunk.selection) && chunk.startTag) {
  1631. chunk.startTag = chunk.startTag.replace(/\n{0,2}$/, "\n\n");
  1632. }
  1633. if (!/(\n|^)[ ]{0,3}>.*$/.test(chunk.selection) && chunk.endTag) {
  1634. chunk.endTag = chunk.endTag.replace(/^\n{0,2}/, "\n\n");
  1635. }
  1636. }
  1637. chunk.selection = this.hooks.postBlockquoteCreation(chunk.selection);
  1638. if (!/\n/.test(chunk.selection)) {
  1639. chunk.selection = chunk.selection.replace(/^(> *)/,
  1640. function (wholeMatch, blanks) {
  1641. chunk.startTag += blanks;
  1642. return "";
  1643. });
  1644. }
  1645. };
  1646. commandProto.doCode = function (chunk, postProcessing) {
  1647. var hasTextBefore = /\S[ ]*$/.test(chunk.before);
  1648. var hasTextAfter = /^[ ]*\S/.test(chunk.after);
  1649. // Use 'four space' markdown if the selection is on its own
  1650. // line or is multiline.
  1651. if ((!hasTextAfter && !hasTextBefore) || /\n/.test(chunk.selection)) {
  1652. chunk.before = chunk.before.replace(/[ ]{4}$/,
  1653. function (totalMatch) {
  1654. chunk.selection = totalMatch + chunk.selection;
  1655. return "";
  1656. });
  1657. var nLinesBack = 1;
  1658. var nLinesForward = 1;
  1659. if (/(\n|^)(\t|[ ]{4,}).*\n$/.test(chunk.before)) {
  1660. nLinesBack = 0;
  1661. }
  1662. if (/^\n(\t|[ ]{4,})/.test(chunk.after)) {
  1663. nLinesForward = 0;
  1664. }
  1665. chunk.skipLines(nLinesBack, nLinesForward);
  1666. if (!chunk.selection) {
  1667. chunk.startTag = " ";
  1668. chunk.selection = this.getString("codeexample");
  1669. }
  1670. else {
  1671. if (/^[ ]{0,3}\S/m.test(chunk.selection)) {
  1672. if (/\n/.test(chunk.selection))
  1673. chunk.selection = chunk.selection.replace(/^/gm, " ");
  1674. else // if it's not multiline, do not select the four added spaces; this is more consistent with the doList behavior
  1675. chunk.before += " ";
  1676. }
  1677. else {
  1678. chunk.selection = chunk.selection.replace(/^(?:[ ]{4}|[ ]{0,3}\t)/gm, "");
  1679. }
  1680. }
  1681. }
  1682. else {
  1683. // Use backticks (`) to delimit the code block.
  1684. chunk.trimWhitespace();
  1685. chunk.findTags(/`/, /`/);
  1686. if (!chunk.startTag && !chunk.endTag) {
  1687. chunk.startTag = chunk.endTag = "`";
  1688. if (!chunk.selection) {
  1689. chunk.selection = this.getString("codeexample");
  1690. }
  1691. }
  1692. else if (chunk.endTag && !chunk.startTag) {
  1693. chunk.before += chunk.endTag;
  1694. chunk.endTag = "";
  1695. }
  1696. else {
  1697. chunk.startTag = chunk.endTag = "";
  1698. }
  1699. }
  1700. };
  1701. commandProto.doList = function (chunk, postProcessing, isNumberedList) {
  1702. // These are identical except at the very beginning and end.
  1703. // Should probably use the regex extension function to make this clearer.
  1704. var previousItemsRegex = /(\n|^)(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*$/;
  1705. var nextItemsRegex = /^\n*(([ ]{0,3}([*+-]|\d+[.])[ \t]+.*)(\n.+|\n{2,}([*+-].*|\d+[.])[ \t]+.*|\n{2,}[ \t]+\S.*)*)\n*/;
  1706. // The default bullet is a dash but others are possible.
  1707. // This has nothing to do with the particular HTML bullet,
  1708. // it's just a markdown bullet.
  1709. var bullet = "-";
  1710. // The number in a numbered list.
  1711. var num = 1;
  1712. // Get the item prefix - e.g. " 1. " for a numbered list, " - " for a bulleted list.
  1713. var getItemPrefix = function () {
  1714. var prefix;
  1715. if (isNumberedList) {
  1716. prefix = " " + num + ". ";
  1717. num++;
  1718. }
  1719. else {
  1720. prefix = " " + bullet + " ";
  1721. }
  1722. return prefix;
  1723. };
  1724. // Fixes the prefixes of the other list items.
  1725. var getPrefixedItem = function (itemText) {
  1726. // The numbering flag is unset when called by autoindent.
  1727. if (isNumberedList === undefined) {
  1728. isNumberedList = /^\s*\d/.test(itemText);
  1729. }
  1730. // Renumber/bullet the list element.
  1731. itemText = itemText.replace(/^[ ]{0,3}([*+-]|\d+[.])\s/gm,
  1732. function (_) {
  1733. return getItemPrefix();
  1734. });
  1735. return itemText;
  1736. };
  1737. chunk.findTags(/(\n|^)*[ ]{0,3}([*+-]|\d+[.])\s+/, null);
  1738. if (chunk.before && !/\n$/.test(chunk.before) && !/^\n/.test(chunk.startTag)) {
  1739. chunk.before += chunk.startTag;
  1740. chunk.startTag = "";
  1741. }
  1742. if (chunk.startTag) {
  1743. var hasDigits = /\d+[.]/.test(chunk.startTag);
  1744. chunk.startTag = "";
  1745. chunk.selection = chunk.selection.replace(/\n[ ]{4}/g, "\n");
  1746. this.unwrap(chunk);
  1747. chunk.skipLines();
  1748. if (hasDigits) {
  1749. // Have to renumber the bullet points if this is a numbered list.
  1750. chunk.after = chunk.after.replace(nextItemsRegex, getPrefixedItem);
  1751. }
  1752. if (isNumberedList == hasDigits) {
  1753. return;
  1754. }
  1755. }
  1756. var nLinesUp = 1;
  1757. chunk.before = chunk.before.replace(previousItemsRegex,
  1758. function (itemText) {
  1759. if (/^\s*([*+-])/.test(itemText)) {
  1760. bullet = re.$1;
  1761. }
  1762. nLinesUp = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
  1763. return getPrefixedItem(itemText);
  1764. });
  1765. if (!chunk.selection) {
  1766. chunk.selection = this.getString("litem");
  1767. }
  1768. var prefix = getItemPrefix();
  1769. var nLinesDown = 1;
  1770. chunk.after = chunk.after.replace(nextItemsRegex,
  1771. function (itemText) {
  1772. nLinesDown = /[^\n]\n\n[^\n]/.test(itemText) ? 1 : 0;
  1773. return getPrefixedItem(itemText);
  1774. });
  1775. chunk.trimWhitespace(true);
  1776. chunk.skipLines(nLinesUp, nLinesDown, true);
  1777. chunk.startTag = prefix;
  1778. var spaces = prefix.replace(/./g, " ");
  1779. this.wrap(chunk, SETTINGS.lineLength - spaces.length);
  1780. chunk.selection = chunk.selection.replace(/\n/g, "\n" + spaces);
  1781. };
  1782. commandProto.doHeading = function (chunk, postProcessing) {
  1783. // Remove leading/trailing whitespace and reduce internal spaces to single spaces.
  1784. chunk.selection = chunk.selection.replace(/\s+/g, " ");
  1785. chunk.selection = chunk.selection.replace(/(^\s+|\s+$)/g, "");
  1786. // If we clicked the button with no selected text, we just
  1787. // make a level 2 hash header around some default text.
  1788. if (!chunk.selection) {
  1789. chunk.startTag = "## ";
  1790. chunk.selection = this.getString("headingexample");
  1791. chunk.endTag = " ##";
  1792. return;
  1793. }
  1794. var headerLevel = 0; // The existing header level of the selected text.
  1795. // Remove any existing hash heading markdown and save the header level.
  1796. chunk.findTags(/#+[ ]*/, /[ ]*#+/);
  1797. if (/#+/.test(chunk.startTag)) {
  1798. headerLevel = re.lastMatch.length;
  1799. }
  1800. chunk.startTag = chunk.endTag = "";
  1801. // Try to get the current header level by looking for - and = in the line
  1802. // below the selection.
  1803. chunk.findTags(null, /\s?(-+|=+)/);
  1804. if (/=+/.test(chunk.endTag)) {
  1805. headerLevel = 1;
  1806. }
  1807. if (/-+/.test(chunk.endTag)) {
  1808. headerLevel = 2;
  1809. }
  1810. // Skip to the next line so we can create the header markdown.
  1811. chunk.startTag = chunk.endTag = "";
  1812. chunk.skipLines(1, 1);
  1813. // We make a level 2 header if there is no current header.
  1814. // If there is a header level, we substract one from the header level.
  1815. // If it's already a level 1 header, it's removed.
  1816. var headerLevelToCreate = headerLevel == 0 ? 2 : headerLevel - 1;
  1817. if (headerLevelToCreate > 0) {
  1818. // The button only creates level 1 and 2 underline headers.
  1819. // Why not have it iterate over hash header levels? Wouldn't that be easier and cleaner?
  1820. var headerChar = headerLevelToCreate >= 2 ? "-" : "=";
  1821. var len = chunk.selection.length;
  1822. if (len > SETTINGS.lineLength) {
  1823. len = SETTINGS.lineLength;
  1824. }
  1825. chunk.endTag = "\n";
  1826. while (len--) {
  1827. chunk.endTag += headerChar;
  1828. }
  1829. }
  1830. };
  1831. commandProto.doHorizontalRule = function (chunk, postProcessing) {
  1832. chunk.startTag = "----------\n";
  1833. chunk.selection = "";
  1834. chunk.skipLines(2, 1, true);
  1835. }
  1836. })();