Greasy Fork镜像 还支持 简体中文。

Github Comment Enhancer

Enhances Github comments

目前為 2015-11-21 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @id Github_Comment_Enhancer@https://github.com/jerone/UserScripts
  3. // @name Github Comment Enhancer
  4. // @namespace https://github.com/jerone/UserScripts
  5. // @description Enhances Github comments
  6. // @author jerone
  7. // @copyright 2014+, jerone (http://jeroenvanwarmerdam.nl)
  8. // @license GNU GPLv3
  9. // @homepage https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer
  10. // @homepageURL https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer
  11. // @supportURL https://github.com/jerone/UserScripts/issues
  12. // @contributionURL https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=VCYMHWQ7ZMBKW
  13. // @version 2.7.0
  14. // @grant none
  15. // @run-at document-end
  16. // @include https://github.com/*
  17. // @include https://gist.github.com/*
  18. // ==/UserScript==
  19. /* global unsafeWindow */
  20.  
  21. (function(unsafeWindow) {
  22.  
  23. String.format = function(string) {
  24. var args = Array.prototype.slice.call(arguments, 1, arguments.length);
  25. return string.replace(/{(\d+)}/g, function(match, number) {
  26. return typeof args[number] !== "undefined" ? args[number] : match;
  27. });
  28. };
  29.  
  30. // Choose the character that precedes the list;
  31. var listCharacter = ["*", "-", "+"][0];
  32.  
  33. // Choose the characters that makes up a horizontal line;
  34. var lineCharacter = ["***", "---", "___"][0];
  35.  
  36. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/langs/markdown.js
  37. var MarkDown = (function MarkDown() {
  38. return {
  39. "bold": {
  40. search: /^(\s*)([\s\S]*?)(\s*)$/g,
  41. replace: "$1**$2**$3",
  42. shortcut: "ctrl+b"
  43. },
  44. "function-italic": {
  45. search: /^(\s*)([\s\S]*?)(\s*)$/g,
  46. replace: "$1_$2_$3",
  47. shortcut: "ctrl+i"
  48. },
  49. "underline": {
  50. search: /^(\s*)([\s\S]*?)(\s*)$/g,
  51. replace: "$1<ins>$2</ins>$3",
  52. shortcut: "ctrl+u"
  53. },
  54. "strikethrough": {
  55. search: /^(\s*)([\s\S]*?)(\s*)$/g,
  56. replace: "$1~~$2~~$3",
  57. shortcut: "ctrl+s"
  58. },
  59.  
  60. "h1": {
  61. search: /(.+)([\n]?)/g,
  62. replace: "# $1$2",
  63. forceNewline: true,
  64. shortcut: "ctrl+1"
  65. },
  66. "h2": {
  67. search: /(.+)([\n]?)/g,
  68. replace: "## $1$2",
  69. forceNewline: true,
  70. shortcut: "ctrl+2"
  71. },
  72. "h3": {
  73. search: /(.+)([\n]?)/g,
  74. replace: "### $1$2",
  75. forceNewline: true,
  76. shortcut: "ctrl+3"
  77. },
  78. "h4": {
  79. search: /(.+)([\n]?)/g,
  80. replace: "#### $1$2",
  81. forceNewline: true,
  82. shortcut: "ctrl+4"
  83. },
  84. "h5": {
  85. search: /(.+)([\n]?)/g,
  86. replace: "##### $1$2",
  87. forceNewline: true,
  88. shortcut: "ctrl+5"
  89. },
  90. "h6": {
  91. search: /(.+)([\n]?)/g,
  92. replace: "###### $1$2",
  93. forceNewline: true,
  94. shortcut: "ctrl+6"
  95. },
  96.  
  97. "link": {
  98. exec: function(button, selText, commentForm, next) {
  99. var selTxt = selText.trim(),
  100. isUrl = selTxt && /(?:https?:\/\/)|(?:www\.)/.test(selTxt),
  101. href = window.prompt("Link href:", isUrl ? selTxt : ""),
  102. text = window.prompt("Link text:", isUrl ? "" : selTxt);
  103. if (href) {
  104. next(String.format("[{0}]({1}){2}", text || href, href, (/\s+$/.test(selText) ? " " : "")));
  105. }
  106. },
  107. shortcut: "ctrl+l"
  108. },
  109. "image": {
  110. exec: function(button, selText, commentForm, next) {
  111. var selTxt = selText.trim(),
  112. isUrl = selTxt && /(?:https?:\/\/)|(?:www\.)/.test(selTxt),
  113. href = window.prompt("Image href:", isUrl ? selTxt : ""),
  114. text = window.prompt("Image text:", isUrl ? "" : selTxt);
  115. if (href) {
  116. next(String.format("![{0}]({1}){2}", text || href, href, (/\s+$/.test(selText) ? " " : "")));
  117. }
  118. },
  119. shortcut: "ctrl+g"
  120. },
  121.  
  122. "ul": {
  123. search: /(.+)([\n]?)/g,
  124. replace: String.format("{0} $1$2", listCharacter),
  125. forceNewline: true,
  126. shortcut: "alt+ctrl+u"
  127. },
  128. "ol": {
  129. exec: function(button, selText, commentForm, next) {
  130. var repText = "";
  131. if (!selText) {
  132. repText = "1. ";
  133. } else {
  134. var lines = selText.split("\n"),
  135. hasContent = /[\w]+/;
  136. for (var i = 0; i < lines.length; i++) {
  137. if (hasContent.test(lines[i])) {
  138. repText += String.format("{0}. {1}\n", i + 1, lines[i]);
  139. }
  140. }
  141. }
  142. next(repText);
  143. },
  144. shortcut: "alt+ctrl+o"
  145. },
  146. "checklist": {
  147. search: /(.+)([\n]?)/g,
  148. replace: String.format("{0} [ ] $1$2", listCharacter),
  149. forceNewline: true,
  150. shortcut: "alt+ctrl+t"
  151. },
  152.  
  153. "code": {
  154. exec: function(button, selText, commentForm, next) {
  155. var rt = selText.indexOf("\n") > -1 ? "$1\n```\n$2\n```$3" : "$1`$2`$3";
  156. next(selText.replace(/^(\s*)([\s\S]*?)(\s*)$/g, rt));
  157. },
  158. shortcut: "ctrl+k"
  159. },
  160. "code-syntax": {
  161. exec: function(button, selText, commentForm, next) {
  162. var rt = "$1\n```" + button.dataset.value + "\n$2\n```$3";
  163. next(selText.replace(/^(\s*)([\s\S]*?)(\s*)$/g, rt));
  164. }
  165. },
  166.  
  167. "blockquote": {
  168. search: /(.+)([\n]?)/g,
  169. replace: "> $1$2",
  170. forceNewline: true,
  171. shortcut: "ctrl+q"
  172. },
  173. "rule": {
  174. append: String.format("\n{0}\n", lineCharacter),
  175. forceNewline: true,
  176. shortcut: "ctrl+r"
  177. },
  178. "table": {
  179. append: "\n" +
  180. "| Head | Head | Head |\n" +
  181. "| :--- | :----: | ----: |\n" +
  182. "| Cell | Cell | Cell |\n" +
  183. "| Left | Center | Right |\n",
  184. forceNewline: true,
  185. shortcut: "alt+shift+t"
  186. },
  187.  
  188. "clear": {
  189. exec: function(button, selText, commentForm, next) {
  190. commentForm.value = "";
  191. next("");
  192. },
  193. shortcut: "alt+ctrl+x"
  194. },
  195.  
  196. "snippets-tab": {
  197. exec: function(button, selText, commentForm, next) {
  198. next("\t");
  199. }
  200. },
  201. "snippets-useragent": {
  202. exec: function(button, selText, commentForm, next) {
  203. next("`" + navigator.userAgent + "`");
  204. }
  205. },
  206. "snippets-contributing": {
  207. exec: function(button, selText, commentForm, next) {
  208. next("Please, always consider reviewing the [guidelines for contributing](../blob/master/CONTRIBUTING.md) to this repository.");
  209. }
  210. },
  211.  
  212. "emoji": {
  213. exec: function(button, selText, commentForm, next) {
  214. next(button.dataset.value);
  215. }
  216. }
  217. };
  218. })();
  219.  
  220. var editorHTML = (function editorHTML() {
  221. return '<div id="gollum-editor-function-buttons" style="float: left;">' +
  222. ' <div class="button-group btn-group">' +
  223. ' <a href="#" data-function="bold" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Bold (ctrl+b)">' +
  224. ' <b style="font-weight: bolder;">B</b>' +
  225. ' </a>' +
  226. ' <a href="#" data-function="italic" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Italic (ctrl+i)">' +
  227. ' <em>i</em>' +
  228. ' </a>' +
  229. ' <a href="#" data-function="underline" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Underline (ctrl+u)">' +
  230. ' <ins>U</ins>' +
  231. ' </a>' +
  232. ' <a href="#" data-function="strikethrough" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Strikethrough (ctrl+s)">' +
  233. ' <s>S</s>' +
  234. ' </a>' +
  235. ' </div>' +
  236.  
  237. ' <div class="button-group btn-group">' +
  238. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Headers">' +
  239. ' <span class="btn btn-sm minibutton select-menu-button icon-only js-menu-target" aria-label="Headers" style="padding-left:7px; padding-right:7px; width:auto; border-bottom-right-radius:3px; border-top-right-radius:3px;">' +
  240. ' <span class="js-select-button">h#</span>' +
  241. ' </span>' +
  242. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  243. ' <div class="select-menu-modal" style="width:auto; overflow:visible;">' +
  244. ' <div class="select-menu-header">' +
  245. ' <span class="select-menu-title">Choose header</span>' +
  246. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  247. ' </div>' +
  248. ' <div class="button-group btn-group" style="min-width:175px;">' +
  249. ' <a href="#" data-function="h1" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 1 (ctrl+1)">' +
  250. ' <b class="select-menu-item-text js-select-button-text">h1</b>' +
  251. ' </a>' +
  252. ' <a href="#" data-function="h2" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 2 (ctrl+2)">' +
  253. ' <b class="select-menu-item-text js-select-button-text">h2</b>' +
  254. ' </a>' +
  255. ' <a href="#" data-function="h3" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 3 (ctrl+3)">' +
  256. ' <b class="select-menu-item-text js-select-button-text">h3</b>' +
  257. ' </a>' +
  258. ' <a href="#" data-function="h4" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 4 (ctrl+4)">' +
  259. ' <b class="select-menu-item-text js-select-button-text">h4</b>' +
  260. ' </a>' +
  261. ' <a href="#" data-function="h5" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 5 (ctrl+5)">' +
  262. ' <b class="select-menu-item-text js-select-button-text">h5</b>' +
  263. ' </a>' +
  264. ' <a href="#" data-function="h6" class="btn btn-sm minibutton function-button js-navigation-item js-menu-close tooltipped tooltipped-s" aria-label="Header 6 (ctrl+6)">' +
  265. ' <b class="select-menu-item-text js-select-button-text">h6</b>' +
  266. ' </a>' +
  267. ' </div>' +
  268. ' </div>' +
  269. ' </div>' +
  270. ' </div>' +
  271. ' </div>' +
  272.  
  273. ' <div class="button-group btn-group">' +
  274. ' <a href="#" data-function="link" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Link (ctrl+l)">' +
  275. ' <span class="octicon octicon-link"></span>' +
  276. ' </a>' +
  277. ' <a href="#" data-function="image" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Image (ctrl+g)">' +
  278. ' <span class="octicon octicon-file-media"></span>' +
  279. ' </a>' +
  280. ' </div>' +
  281. ' <div class="button-group btn-group">' +
  282. ' <a href="#" data-function="ul" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Unordered List (alt+ctrl+u)">' +
  283. ' <span class="octicon octicon-list-unordered"></span>' +
  284. ' </a>' +
  285. ' <a href="#" data-function="ol" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Ordered List (alt+ctrl+o)">' +
  286. ' <span class="octicon octicon-list-ordered"></span>' +
  287. ' </a>' +
  288. ' <a href="#" data-function="checklist" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Task List (alt+ctrl+t)">' +
  289. ' <span class="octicon octicon-checklist"></span>' +
  290. ' </a>' +
  291. ' </div>' +
  292.  
  293. ' <div class="button-group btn-group">' +
  294. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Code (ctrl+k)">' +
  295. ' <a href="#" data-function="code" class="btn btn-sm minibutton function-button">' +
  296. ' <span class="octicon octicon-code"></span>' +
  297. ' </a>' +
  298. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  299. ' <div class="select-menu-modal" style="overflow:visible;">' +
  300. ' <div class="select-menu-header">' +
  301. ' <span class="select-menu-title">Code syntax</span>' +
  302. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  303. ' </div>' +
  304. ' <div class="select-menu-filters">' +
  305. ' <div class="select-menu-text-filter">' +
  306. ' <input type="text" placeholder="Filter code syntax..." class="js-filterable-field js-navigation-enable" id="context-code-syntax-filter-field">' +
  307. ' </div>' +
  308. ' </div>' +
  309. ' <div class="code-syntaxes select-menu-list" style="overflow:visible;">' +
  310. ' <div class="select-menu-no-results">Nothing to show</div>' +
  311. ' </div>' +
  312. ' </div>' +
  313. ' </div>' +
  314. ' <a href="#" class="btn btn-sm minibutton select-menu-button js-menu-target" style="width:20px; margin-left:-1px;"></a>' +
  315. ' </div>' +
  316. ' </div>' +
  317.  
  318. ' <div class="button-group btn-group">' +
  319. ' <a href="#" data-function="blockquote" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Blockquote (ctrl+q)">' +
  320. ' <span class="octicon octicon-quote"></span>' +
  321. ' </a>' +
  322. ' <a href="#" data-function="rule" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Horizontal Rule (ctrl+r)">' +
  323. ' <span class="octicon octicon-horizontal-rule"></span>' +
  324. ' </a>' +
  325. ' <a href="#" data-function="table" class="btn btn-sm minibutton function-button tooltipped tooltipped-ne" aria-label="Table (alt+shift+t)">' +
  326. ' <span class="octicon octicon-three-bars"></span>' +
  327. ' </a>' +
  328. ' </div>' +
  329.  
  330. ' <div class="button-group btn-group">' +
  331. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Snippets">' +
  332. ' <span class="btn btn-sm minibutton select-menu-button js-menu-target" aria-label="Snippets" style="padding-left:7px; padding-right:7px; width:auto; border-bottom-right-radius:3px; border-top-right-radius:3px;">' +
  333. ' <span class="octicon octicon-pin"></span>' +
  334. ' </span>' +
  335. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  336. ' <div class="select-menu-modal" style="overflow:visible;">' +
  337. ' <div class="select-menu-header">' +
  338. ' <span class="select-menu-title">Snippets</span>' +
  339. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  340. ' </div>' +
  341. ' <div class="select-menu-filters">' +
  342. ' <div class="select-menu-text-filter">' +
  343. ' <input type="text" placeholder="Filter snippets..." class="js-filterable-field js-navigation-enable" id="context-snippets-filter-field">' +
  344. ' </div>' +
  345. ' </div>' +
  346. ' <div class="select-menu-list" style="overflow:visible;">' +
  347. ' <div data-filterable-type="substring" data-filterable-for="context-snippets-filter-field">' +
  348. ' <a href="#" data-function="snippets-tab" class="function-button select-menu-item js-navigation-item tooltipped tooltipped-w" aria-label="Add tab character" style="table-layout:initial;">' +
  349. ' <span class="select-menu-item-text js-select-button-text">Add tab character</span>' +
  350. ' </a>' +
  351. ' <a href="#" data-function="snippets-useragent" class="function-button select-menu-item js-navigation-item tooltipped tooltipped-w" aria-label="Add UserAgent" style="table-layout:initial;">' +
  352. ' <span class="select-menu-item-text js-select-button-text">Add UserAgent</span>' +
  353. ' </a>' +
  354. ' <a href="#" data-function="snippets-contributing" class="function-button select-menu-item js-navigation-item tooltipped tooltipped-w" aria-label="Add contributing message" style="table-layout:initial;">' +
  355. ' <span class="select-menu-item-text">' +
  356. ' <span class="js-select-button-text">Contributing</span>' +
  357. ' <span class="description">Add contributing message</span>' +
  358. ' </span>' +
  359. ' </a>' +
  360. ' </div>' +
  361. ' <div class="select-menu-no-results">Nothing to show</div>' +
  362. ' </div>' +
  363. ' </div>' +
  364. ' </div>' +
  365. ' </div>' +
  366. ' </div>' +
  367.  
  368. ' <div class="button-group btn-group">' +
  369. ' <div class="select-menu js-menu-container js-select-menu tooltipped tooltipped-ne" aria-label="Emoji">' +
  370. ' <span class="btn btn-sm minibutton select-menu-button js-menu-target" aria-label="Emoji" style="padding-left:7px; padding-right:7px; width:auto; border-bottom-right-radius:3px; border-top-right-radius:3px;">' +
  371. ' <span class="octicon octicon-octoface"></span>' +
  372. ' </span>' +
  373. ' <div class="select-menu-modal-holder js-menu-content js-navigation-container" style="top:26px; z-index:22;">' +
  374. ' <div class="select-menu-modal" style="overflow:visible;">' +
  375. ' <div class="select-menu-header">' +
  376. ' <span class="select-menu-title">Emoji</span>' +
  377. ' <span class="octicon octicon-remove-close js-menu-close"></span>' +
  378. ' </div>' +
  379. ' <div class="select-menu-filters">' +
  380. ' <div class="select-menu-text-filter">' +
  381. ' <input type="text" placeholder="Filter emoji..." class="js-filterable-field js-navigation-enable" id="context-emoji-filter-field">' +
  382. ' </div>' +
  383. ' </div>' +
  384. ' <div class="suggester select-menu-list" style="overflow:visible;">' +
  385. ' <div class="select-menu-no-results">Nothing to show</div>' +
  386. ' </div>' +
  387. ' </div>' +
  388. ' </div>' +
  389. ' </div>' +
  390. ' </div>' +
  391.  
  392. '</div>' +
  393.  
  394. '<div style="float:right;">' +
  395. ' <a href="#" data-function="clear" class="btn btn-sm minibutton function-button tooltipped tooltipped-nw" aria-label="Clear (alt+ctrl+x)">' +
  396. ' <span class="octicon octicon-trashcan"></span>' +
  397. ' </a>' +
  398. '</div>';
  399. })();
  400.  
  401. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/gollum.editor.js#L516
  402. function executeAction(definitionObject, commentForm, button) {
  403. var txt = commentForm.value,
  404. selPos = {
  405. start: commentForm.selectionStart,
  406. end: commentForm.selectionEnd
  407. },
  408. selText = txt.substring(selPos.start, selPos.end),
  409. repText = selText,
  410. reselect = true,
  411. cursor = null;
  412.  
  413. // execute replacement function;
  414. if (definitionObject.exec) {
  415. definitionObject.exec(button, selText, commentForm, function(repText) {
  416. replaceFieldSelection(commentForm, repText);
  417. });
  418. return;
  419. }
  420.  
  421. // execute a search;
  422. var searchExp = new RegExp(definitionObject.search || /([^\n]+)/gi);
  423.  
  424. // replace text;
  425. if (definitionObject.replace) {
  426. var rt = definitionObject.replace;
  427. repText = repText.replace(searchExp, rt);
  428. repText = repText.replace(/\$[\d]/g, "");
  429. if (repText === "") {
  430. cursor = rt.indexOf("$1");
  431. repText = rt.replace(/\$[\d]/g, "");
  432. if (cursor === -1) {
  433. cursor = Math.floor(rt.length / 2);
  434. }
  435. }
  436. }
  437.  
  438. // append if necessary;
  439. if (definitionObject.append) {
  440. if (repText === selText) {
  441. reselect = false;
  442. }
  443. repText += definitionObject.append;
  444. }
  445.  
  446. if (repText) {
  447. if (definitionObject.forceNewline === true && (selPos.start > 0 && txt.substr(Math.max(0, selPos.start - 1), 1) !== "\n")) {
  448. repText = "\n" + repText;
  449. }
  450. replaceFieldSelection(commentForm, repText, reselect, cursor);
  451. }
  452. }
  453.  
  454. // Source: https://github.com/gollum/gollum/blob/9c714e768748db4560bc017cacef4afa0c751a63/lib/gollum/public/gollum/javascript/editor/gollum.editor.js#L708
  455. function replaceFieldSelection(commentForm, replaceText, reselect, cursorOffset) {
  456. var txt = commentForm.value,
  457. selPos = {
  458. start: commentForm.selectionStart,
  459. end: commentForm.selectionEnd
  460. };
  461.  
  462. var selectNew = true;
  463. if (reselect === false) {
  464. selectNew = false;
  465. }
  466.  
  467. var scrollTop = null;
  468. if (commentForm.scrollTop) {
  469. scrollTop = commentForm.scrollTop;
  470. }
  471.  
  472. commentForm.value = txt.substring(0, selPos.start) + replaceText + txt.substring(selPos.end);
  473. commentForm.focus();
  474.  
  475. if (selectNew) {
  476. if (cursorOffset) {
  477. commentForm.setSelectionRange(selPos.start + cursorOffset, selPos.start + cursorOffset);
  478. } else {
  479. commentForm.setSelectionRange(selPos.start, selPos.start + replaceText.length);
  480. }
  481. }
  482.  
  483. if (scrollTop) {
  484. commentForm.scrollTop = scrollTop;
  485. }
  486. }
  487.  
  488. function isWiki() {
  489. return /\/wiki\//.test(location.href);
  490. }
  491.  
  492. function isGist() {
  493. return location.host === "gist.github.com";
  494. }
  495.  
  496. function overrideGollumMarkdown() {
  497. unsafeWindow.$.GollumEditor.defineLanguage("markdown", MarkDown);
  498. }
  499.  
  500. function unbindGollumFunctions() {
  501. window.setTimeout(function() {
  502. unsafeWindow.$(".function-button:not(#function-help)").unbind("click");
  503. }, 1);
  504. }
  505.  
  506. var buttonEvent = function(e) {
  507. e.preventDefault();
  508. executeAction(MarkDown[this.dataset.function], this.commentForm, this);
  509. return false;
  510. };
  511.  
  512. var codeSyntaxTop = ["JavaScript", "Java", "Ruby", "PHP", "Python", "CSS", "C++", "C#", "C", "HTML"]; // https://github.com/blog/2047-language-trends-on-github
  513. var codeSyntaxList = ["ABAP", "abl", "aconf", "ActionScript", "actionscript 3",
  514. "actionscript3", "Ada", "ada2005", "ada95", "advpl", "Agda", "ags",
  515. "AGS Script", "ahk", "Alloy", "AMPL", "Ant Build System", "ANTLR",
  516. "apache", "ApacheConf", "Apex", "API Blueprint", "APL", "AppleScript",
  517. "Arc", "Arduino", "as3", "AsciiDoc", "ASP", "AspectJ", "aspx",
  518. "aspx-vb", "Assembly", "ATS", "ats2", "au3", "Augeas", "AutoHotkey",
  519. "AutoIt", "AutoIt3", "AutoItScript", "Awk", "b3d", "bash",
  520. "bash session", "bat", "batch", "Batchfile", "Befunge", "Bison",
  521. "BitBake", "blitz3d", "BlitzBasic", "BlitzMax", "blitzplus",
  522. "Bluespec", "bmax", "Boo", "bplus", "Brainfuck", "Brightscript", "Bro",
  523. "bsdmake", "byond", "C", "C#", "C++", "c++-objdumb", "C-ObjDump",
  524. "c2hs", "C2hs Haskell", "Cap'n Proto", "Carto", "CartoCSS", "Ceylon",
  525. "cfc", "cfm", "cfml", "Chapel", "Charity", "chpl", "ChucK", "Cirru",
  526. "Clarion", "Clean", "clipper", "CLIPS", "Clojure", "CMake", "COBOL",
  527. "coffee", "coffee-script", "CoffeeScript", "ColdFusion",
  528. "ColdFusion CFC", "coldfusion html", "Common Lisp", "Component Pascal",
  529. "console", "Cool", "Coq", "cpp", "Cpp-ObjDump", "Creole", "Crystal",
  530. "csharp", "CSS", "Cucumber", "Cuda", "Cycript", "Cython", "D",
  531. "D-ObjDump", "Darcs Patch", "Dart", "dcl", "delphi", "desktop", "Diff",
  532. "DIGITAL Command Language", "DM", "DNS Zone", "Dockerfile",
  533. "Dogescript", "dosbatch", "dosini", "dpatch", "DTrace",
  534. "dtrace-script", "Dylan", "E", "Eagle", "eC", "Ecere Projects", "ECL",
  535. "ECLiPSe", "edn", "Eiffel", "elisp", "Elixir", "Elm", "emacs",
  536. "Emacs Lisp", "EmberScript", "erb", "Erlang", "F#", "Factor", "Fancy",
  537. "Fantom", "Filterscript", "fish", "flex", "FLUX", "Formatted", "Forth",
  538. "FORTRAN", "foxpro", "Frege", "fsharp", "fundamental", "G-code",
  539. "Game Maker Language", "GAMS", "GAP", "GAS", "GDScript", "Genshi",
  540. "Gentoo Ebuild", "Gentoo Eclass", "Gettext Catalog", "gf", "gherkin",
  541. "GLSL", "Glyph", "Gnuplot", "Go", "Golo", "Gosu", "Grace", "Gradle",
  542. "Grammatical Framework", "Graph Modeling Language", "Graphviz (DOT)",
  543. "Groff", "Groovy", "Groovy Server Pages", "gsp", "Hack", "Haml",
  544. "Handlebars", "Harbour", "Haskell", "Haxe", "hbs", "HCL", "HTML",
  545. "HTML+Django", "html+django/jinja", "HTML+ERB", "html+jinja",
  546. "HTML+PHP", "html+ruby", "htmlbars", "htmldjango", "HTTP", "Hy",
  547. "hylang", "HyPhy", "i7", "IDL", "Idris", "igor", "IGOR Pro", "igorpro",
  548. "inc", "Inform 7", "inform7", "INI", "Inno Setup", "Io", "Ioke", "irc",
  549. "IRC log", "irc logs", "Isabelle", "Isabelle ROOT", "J", "Jade",
  550. "Jasmin", "Java", "java server page", "Java Server Pages",
  551. "JavaScript", "JFlex", "jruby", "js", "JSON", "JSON5", "JSONiq",
  552. "JSONLD", "jsp", "JSX", "Julia", "KiCad", "Kit", "Kotlin", "KRL",
  553. "LabVIEW", "Lasso", "lassoscript", "latex", "Latte", "Lean", "Less",
  554. "Lex", "LFE", "lhaskell", "lhs", "LilyPond", "Limbo", "Linker Script",
  555. "Linux Kernel Module", "Liquid", "lisp", "litcoffee", "Literate Agda",
  556. "Literate CoffeeScript", "Literate Haskell", "live-script",
  557. "LiveScript", "LLVM", "Logos", "Logtalk", "LOLCODE", "LookML",
  558. "LoomScript", "ls", "LSL", "Lua", "M", "macruby", "make", "Makefile",
  559. "Mako", "Markdown", "Mask", "Mathematica", "Matlab", "Maven POM",
  560. "Max", "max/msp", "maxmsp", "MediaWiki", "Mercury", "mf", "MiniD",
  561. "Mirah", "mma", "Modelica", "Modula-2", "Module Management System",
  562. "Monkey", "Moocode", "MoonScript", "MTML", "MUF", "mumps", "mupad",
  563. "Myghty", "nasm", "NCL", "Nemerle", "nesC", "NetLinx", "NetLinx+ERB",
  564. "NetLogo", "NewLisp", "Nginx", "nginx configuration file", "Nimrod",
  565. "Ninja", "Nit", "Nix", "nixos", "NL", "node", "nroff", "NSIS", "Nu",
  566. "NumPy", "nush", "nvim", "obj-c", "obj-c++", "obj-j", "objc", "objc++",
  567. "ObjDump", "Objective-C", "Objective-C++", "Objective-J", "objectivec",
  568. "objectivec++", "objectivej", "objectpascal", "objj", "OCaml",
  569. "Omgrofl", "ooc", "Opa", "Opal", "OpenCL", "openedge", "OpenEdge ABL",
  570. "OpenSCAD", "Org", "osascript", "Ox", "Oxygene", "Oz", "Pan",
  571. "Papyrus", "Parrot", "Parrot Assembly",
  572. "Parrot Internal Representation", "Pascal", "pasm", "PAWN", "Perl",
  573. "Perl6", "PHP", "PicoLisp", "PigLatin", "Pike", "pir", "PLpgSQL",
  574. "PLSQL", "Pod", "PogoScript", "posh", "postscr", "PostScript", "pot",
  575. "PowerShell", "Processing", "progress", "Prolog", "Propeller Spin",
  576. "protobuf", "Protocol Buffer", "Protocol Buffers", "Public Key",
  577. "Puppet", "Pure Data", "PureBasic", "PureScript", "pyrex", "Python",
  578. "Python traceback", "QMake", "QML", "R", "Racket",
  579. "Ragel in Ruby Host", "ragel-rb", "ragel-ruby", "rake", "RAML", "raw",
  580. "Raw token data", "rb", "rbx", "RDoc", "REALbasic", "Rebol", "Red",
  581. "red/system", "Redcode", "RenderScript", "reStructuredText", "RHTML",
  582. "RMarkdown", "RobotFramework", "Rouge", "Rscript", "rss", "rst",
  583. "Ruby", "Rust", "rusthon", "Sage", "salt", "SaltStack", "saltstate",
  584. "SAS", "Sass", "Scala", "Scaml", "Scheme", "Scilab", "SCSS", "Self",
  585. "sh", "Shell", "ShellSession", "Shen", "Slash", "Slim", "Smali",
  586. "Smalltalk", "Smarty", "sml", "SMT", "sourcemod", "SourcePawn",
  587. "SPARQL", "splus", "SQF", "SQL", "SQLPL", "squeak", "Squirrel",
  588. "Standard ML", "Stata", "STON", "Stylus", "SuperCollider", "SVG",
  589. "Swift", "SystemVerilog", "Tcl", "Tcsh", "Tea", "TeX", "Text",
  590. "Textile", "Thrift", "TOML", "ts", "Turing", "Turtle", "Twig", "TXL",
  591. "TypeScript", "udiff", "Unified Parallel C", "Unity3D Asset",
  592. "UnrealScript", "Vala", "vb.net", "vbnet", "VCL", "Verilog", "VHDL",
  593. "vim", "VimL", "Visual Basic", "Volt", "Vue", "Web Ontology Language",
  594. "WebIDL", "winbatch", "wisp", "wsdl", "X10", "xBase", "XC", "xhtml",
  595. "XML", "xml+genshi", "xml+kid", "Xojo", "XPages", "XProc", "XQuery",
  596. "XS", "xsd", "xsl", "XSLT", "xten", "Xtend", "Yacc", "YAML", "yml",
  597. "Zephir", "Zimpl", "zsh"
  598. ]; // https://github.com/jerone/UserScripts/issues/18
  599. var codeSyntaxes = [].concat(codeSyntaxTop, codeSyntaxList).filter(function(a, b, c) {
  600. return c.indexOf(a) === b;
  601. });
  602.  
  603. function addCodeSyntax(commentForm) {
  604. var syntaxSuggestions = document.createElement("div");
  605. syntaxSuggestions.dataset.filterableType = "substring";
  606. syntaxSuggestions.dataset.filterableFor = "context-code-syntax-filter-field";
  607. syntaxSuggestions.dataset.filterableLimit = codeSyntaxTop.length; // Show top code syntaxes on open;
  608.  
  609. codeSyntaxes.forEach(function(syntax) {
  610. var syntaxSuggestion = document.createElement("a");
  611. syntaxSuggestion.setAttribute("href", "#");
  612. syntaxSuggestion.classList.add("function-button", "select-menu-item", "js-navigation-item");
  613. syntaxSuggestion.dataset.value = syntax;
  614. syntaxSuggestion.dataset.function = "code-syntax";
  615. syntaxSuggestions.appendChild(syntaxSuggestion);
  616.  
  617. var syntaxSuggestionText = document.createElement("span");
  618. syntaxSuggestionText.classList.add("select-menu-item-text", "js-select-button-text");
  619. syntaxSuggestionText.appendChild(document.createTextNode(syntax));
  620. syntaxSuggestion.appendChild(syntaxSuggestionText);
  621. });
  622.  
  623. var suggester = commentForm.parentNode.parentNode.querySelector(".code-syntaxes");
  624. suggester.appendChild(syntaxSuggestions);
  625. }
  626.  
  627. var suggestionsCache = {};
  628.  
  629. function addSuggestions(commentForm) {
  630. var jssuggester = commentForm.parentNode.parentNode.querySelector(".suggester-container .suggester");
  631. var url = jssuggester.getAttribute("data-url");
  632.  
  633. if (suggestionsCache[url]) {
  634. parseSuggestions(commentForm, suggestionsCache[url]);
  635. } else {
  636. unsafeWindow.$.ajax({
  637. url: url,
  638. success: function(suggestionsData) {
  639. suggestionsCache[url] = suggestionsData;
  640. parseSuggestions(commentForm, suggestionsData);
  641. }
  642. });
  643. }
  644. }
  645.  
  646. function parseSuggestions(commentForm, suggestionsData) {
  647. suggestionsData = suggestionsData.replace(/js-navigation-item/g,
  648. "function-button js-navigation-item select-menu-item");
  649.  
  650. var suggestions = document.createElement("div");
  651. suggestions.innerHTML = suggestionsData;
  652.  
  653. var emojiSuggestions = suggestions.querySelector(".emoji-suggestions");
  654. emojiSuggestions.style.display = "block";
  655. emojiSuggestions.dataset.filterableType = "substring";
  656. emojiSuggestions.dataset.filterableFor = "context-emoji-filter-field";
  657. emojiSuggestions.dataset.filterableLimit = "10";
  658.  
  659. var suggester = commentForm.parentNode.parentNode.querySelector(".suggester");
  660. suggester.style.display = "block";
  661. suggester.style.marginTop = "0";
  662. suggester.appendChild(emojiSuggestions);
  663.  
  664. var buttons = suggester.querySelectorAll(".function-button");
  665. Array.prototype.forEach.call(buttons, function(button) {
  666. button.commentForm = commentForm;
  667. button.dataset.function = "emoji";
  668. button.addEventListener("click", buttonEvent, false);
  669. unsafeWindow.$(button).on("navigation:keydown", function(e) {
  670. if (e.hotkey === "enter") {
  671. buttonEvent.call(this, e);
  672. }
  673. });
  674. });
  675. }
  676.  
  677. function commentFormKeyEvent(commentForm, e) {
  678. var keys = [];
  679. if (e.altKey) {
  680. keys.push('alt');
  681. }
  682. if (e.ctrlKey) {
  683. keys.push('ctrl');
  684. }
  685. if (e.shiftKey) {
  686. keys.push('shift');
  687. }
  688. keys.push(String.fromCharCode(e.which).toLowerCase());
  689. var keyCombination = keys.join('+');
  690.  
  691. var action;
  692. for (var actionName in MarkDown) {
  693. if (MarkDown[actionName].shortcut && MarkDown[actionName].shortcut.toLowerCase() === keyCombination) {
  694. action = MarkDown[actionName];
  695. break;
  696. }
  697. }
  698. if (action) {
  699. e.preventDefault();
  700. e.stopPropagation();
  701. executeAction(action, commentForm, null);
  702. return false;
  703. }
  704. }
  705.  
  706. function addToolbar() {
  707. if (isWiki()) {
  708. // Override existing language with improved & missing functions and remove existing click events;
  709. overrideGollumMarkdown();
  710. unbindGollumFunctions();
  711.  
  712. // Remove existing click events when changing languages;
  713. document.getElementById("wiki_format").addEventListener("change", function() {
  714. unbindGollumFunctions();
  715.  
  716. var buttons = document.querySelectorAll(".comment-form-textarea .function-button");
  717. Array.prototype.forEach.call(buttons, function(button) {
  718. button.removeEventListener("click", buttonEvent);
  719. });
  720. });
  721. }
  722.  
  723. Array.prototype.forEach.call(document.querySelectorAll(".comment-form-textarea,.js-comment-field"), function(commentForm) {
  724. var gollumEditor;
  725. if (commentForm.classList.contains("GithubCommentEnhancer")) {
  726. gollumEditor = commentForm.previousSibling;
  727. } else {
  728. commentForm.classList.add("GithubCommentEnhancer");
  729.  
  730. if (isWiki()) {
  731. gollumEditor = document.getElementById("gollum-editor-function-bar");
  732. var temp = document.createElement("div");
  733. temp.innerHTML = editorHTML;
  734. temp.firstElementChild.appendChild(document.getElementById("function-help")); // restore the help button;
  735. gollumEditor.replaceChild(temp.querySelector("#gollum-editor-function-buttons"), document.getElementById("gollum-editor-function-buttons"));
  736. Array.prototype.forEach.call(temp.children, function(elm) {
  737. elm.style.position = "absolute";
  738. elm.style.right = "30px";
  739. elm.style.top = "0";
  740. commentForm.parentNode.insertBefore(elm, commentForm);
  741. });
  742. temp = null;
  743. } else {
  744. gollumEditor = document.createElement("div");
  745. gollumEditor.innerHTML = editorHTML;
  746. gollumEditor.id = "gollum-editor-function-bar";
  747. gollumEditor.style.height = "26px";
  748. gollumEditor.style.margin = "10px 0";
  749. gollumEditor.classList.add("active");
  750. commentForm.parentNode.insertBefore(gollumEditor, commentForm);
  751. }
  752.  
  753. addSuggestions(commentForm);
  754.  
  755. addCodeSyntax(commentForm);
  756.  
  757. var tabnavExtras = commentForm.parentNode.parentNode.querySelector(".comment-form-head .tabnav-right, .comment-form-head .right");
  758. if (tabnavExtras) {
  759. var elem = commentForm;
  760. while ((elem = elem.parentNode) && elem.nodeType !== 9 && !elem.classList.contains("timeline-inline-comments")) {}
  761. var sponsoredText = elem !== document ? " Github Comment Enhancer" : " Enhanced by Github Comment Enhancer";
  762. var sponsored = document.createElement("a");
  763. sponsored.setAttribute("target", "_blank");
  764. sponsored.setAttribute("href", "https://github.com/jerone/UserScripts/tree/master/Github_Comment_Enhancer");
  765. sponsored.classList.add("tabnav-widget", "text", "tabnav-extras", "tabnav-extra");
  766. var sponsoredIcon = document.createElement("span");
  767. sponsoredIcon.classList.add("octicon", "octicon-question");
  768. sponsored.appendChild(sponsoredIcon);
  769. sponsored.appendChild(document.createTextNode(sponsoredText));
  770. tabnavExtras.insertBefore(sponsored, tabnavExtras.firstElementChild);
  771. }
  772. }
  773.  
  774. Array.prototype.forEach.call(gollumEditor.parentNode.querySelectorAll(".function-button"), function(button) {
  775. button.commentForm = commentForm; // remove event listener doesn't accept `bind`;
  776. button.addEventListener("click", buttonEvent, false);
  777. unsafeWindow.$(button).on("navigation:keydown", function(e) {
  778. if (e.hotkey === "enter") {
  779. buttonEvent.call(this, e);
  780. }
  781. });
  782. });
  783.  
  784. commentForm.addEventListener('keydown', commentFormKeyEvent.bind(this, commentForm));
  785. });
  786. }
  787.  
  788. /*
  789. * to-markdown - an HTML to Markdown converter
  790. * Copyright 2011, Dom Christie
  791. * Licenced under the MIT licence
  792. * Source: https://github.com/domchristie/to-markdown
  793. *
  794. * Code is altered:
  795. * - Added task list support: https://github.com/domchristie/to-markdown/pull/62
  796. * - He dependecy is removed
  797. */
  798. var toMarkdown = function(string) {
  799.  
  800. var ELEMENTS = [{
  801. patterns: 'p',
  802. replacement: function(str, attrs, innerHTML) {
  803. return innerHTML ? '\n\n' + innerHTML + '\n' : '';
  804. }
  805. }, {
  806. patterns: 'br',
  807. type: 'void',
  808. replacement: ' \n'
  809. }, {
  810. patterns: 'h([1-6])',
  811. replacement: function(str, hLevel, attrs, innerHTML) {
  812. var hPrefix = '';
  813. for (var i = 0; i < hLevel; i++) {
  814. hPrefix += '#';
  815. }
  816. return '\n\n' + hPrefix + ' ' + innerHTML + '\n';
  817. }
  818. }, {
  819. patterns: 'hr',
  820. type: 'void',
  821. replacement: '\n\n* * *\n'
  822. }, {
  823. patterns: 'a',
  824. replacement: function(str, attrs, innerHTML) {
  825. var href = attrs.match(attrRegExp('href')),
  826. title = attrs.match(attrRegExp('title'));
  827. return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str;
  828. }
  829. }, {
  830. patterns: ['b', 'strong'],
  831. replacement: function(str, attrs, innerHTML) {
  832. return innerHTML ? '**' + innerHTML + '**' : '';
  833. }
  834. }, {
  835. patterns: ['i', 'em'],
  836. replacement: function(str, attrs, innerHTML) {
  837. return innerHTML ? '_' + innerHTML + '_' : '';
  838. }
  839. }, {
  840. patterns: 'code',
  841. replacement: function(str, attrs, innerHTML) {
  842. return innerHTML ? '`' + innerHTML + '`' : '';
  843. }
  844. }, {
  845. patterns: 'img',
  846. type: 'void',
  847. replacement: function(str, attrs, innerHTML) {
  848. var src = attrs.match(attrRegExp('src')),
  849. alt = attrs.match(attrRegExp('alt')),
  850. title = attrs.match(attrRegExp('title'));
  851. return src ? '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : '';
  852. }
  853. }];
  854.  
  855. for (var i = 0, len = ELEMENTS.length; i < len; i++) {
  856. if (typeof ELEMENTS[i].patterns === 'string') {
  857. string = replaceEls(string, {
  858. tag: ELEMENTS[i].patterns,
  859. replacement: ELEMENTS[i].replacement,
  860. type: ELEMENTS[i].type
  861. });
  862. } else {
  863. for (var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) {
  864. string = replaceEls(string, {
  865. tag: ELEMENTS[i].patterns[j],
  866. replacement: ELEMENTS[i].replacement,
  867. type: ELEMENTS[i].type
  868. });
  869. }
  870. }
  871. }
  872.  
  873. function replaceEls(html, elProperties) {
  874. var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>',
  875. regex = new RegExp(pattern, 'gi'),
  876. markdown = '';
  877. if (typeof elProperties.replacement === 'string') {
  878. markdown = html.replace(regex, elProperties.replacement);
  879. } else {
  880. markdown = html.replace(regex, function(str, p1, p2, p3) {
  881. return elProperties.replacement.call(this, str, p1, p2, p3);
  882. });
  883. }
  884. return markdown;
  885. }
  886.  
  887. function attrRegExp(attr) {
  888. return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i');
  889. }
  890.  
  891. // Pre code blocks
  892.  
  893. string = string.replace(/<pre\b[^>]*>`([\s\S]*?)`<\/pre>/gi, function(str, innerHTML) {
  894. var text = innerHTML;
  895. text = text.replace(/^\t+/g, ' '); // convert tabs to spaces (you know it makes sense)
  896. text = text.replace(/\n/g, '\n ');
  897. return '\n\n ' + text + '\n';
  898. });
  899.  
  900. // Lists
  901.  
  902. // Escape numbers that could trigger an ol
  903. // If there are more than three spaces before the code, it would be in a pre tag
  904. // Make sure we are escaping the period not matching any character
  905. string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. ');
  906.  
  907. // Converts lists that have no child lists (of same type) first, then works its way up
  908. var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi;
  909. while (string.match(noChildrenRegex)) {
  910. string = string.replace(noChildrenRegex, function(str) {
  911. return replaceLists(str);
  912. });
  913. }
  914.  
  915. function replaceLists(html) {
  916.  
  917. html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function(str, listType, innerHTML) {
  918. var lis = innerHTML.split('</li>');
  919. lis.splice(lis.length - 1, 1);
  920.  
  921. for (i = 0, len = lis.length; i < len; i++) {
  922. if (lis[i]) {
  923. var prefix = (listType === 'ol') ? (i + 1) + ". " : "* ";
  924. lis[i] = lis[i].replace(/\s*<li[^>]*>([\s\S]*)/i, function(str, innerHTML) {
  925. innerHTML = innerHTML.replace(/\s*<input[^>]*?(checked[^>]*)?type=['"]?checkbox['"]?[^>]>/, function(inputStr, checked) {
  926. return checked ? '[X]' : '[ ]';
  927. });
  928. innerHTML = innerHTML.replace(/^\s+/, '');
  929. innerHTML = innerHTML.replace(/\n\n/g, '\n\n ');
  930. // indent nested lists
  931. innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1 $2 ');
  932. return prefix + innerHTML;
  933. });
  934. }
  935. lis[i] = lis[i].replace(/(.) +$/m, '$1');
  936. }
  937. return lis.join('\n');
  938. });
  939.  
  940. return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, '');
  941. }
  942.  
  943. // Blockquotes
  944. var deepest = /<blockquote\b[^>]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi;
  945. while (string.match(deepest)) {
  946. string = string.replace(deepest, function(str) {
  947. return replaceBlockquotes(str);
  948. });
  949. }
  950.  
  951. function replaceBlockquotes(html) {
  952. html = html.replace(/<blockquote\b[^>]*>([\s\S]*?)<\/blockquote>/gi, function(str, inner) {
  953. inner = inner.replace(/^\s+|\s+$/g, '');
  954. inner = cleanUp(inner);
  955. inner = inner.replace(/^/gm, '> ');
  956. inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >');
  957. return inner;
  958. });
  959. return html;
  960. }
  961.  
  962. function cleanUp(string) {
  963. string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace
  964. string = string.replace(/\n\s+\n/g, '\n\n');
  965. string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2
  966. return string;
  967. }
  968.  
  969. return cleanUp(string);
  970. };
  971.  
  972. function getCommentTextarea(replyBtn) {
  973. var newComment = replyBtn;
  974. while (newComment && !newComment.classList.contains('js-quote-selection-container')) {
  975. newComment = newComment.parentNode;
  976. }
  977. if (newComment) {
  978. var lastElementChild = newComment.lastElementChild;
  979. lastElementChild.classList.add('open');
  980. newComment = lastElementChild.querySelector(".comment-form-textarea");
  981. } else {
  982. newComment = document.querySelector(".timeline-new-comment .comment-form-textarea");
  983. }
  984. return newComment;
  985. }
  986.  
  987. function addReplyButtons() {
  988. Array.prototype.forEach.call(document.querySelectorAll(".comment"), function(comment) {
  989. var oldReply = comment.querySelector(".GithubCommentEnhancerReply");
  990. if (oldReply) {
  991. oldReply.parentNode.removeChild(oldReply);
  992. }
  993.  
  994. var header = comment.querySelector(".timeline-comment-header"),
  995. actions = comment.querySelector(".timeline-comment-actions");
  996.  
  997. if (!header) {
  998. return;
  999. }
  1000. if (!actions) {
  1001. actions = document.createElement("div");
  1002. actions.classList.add("timeline-comment-actions");
  1003. header.insertBefore(actions, header.firstElementChild);
  1004. }
  1005.  
  1006. var reply = document.createElement("a");
  1007. reply.setAttribute("href", "#");
  1008. reply.setAttribute("aria-label", "Reply to this comment");
  1009. reply.classList.add("GithubCommentEnhancerReply", "timeline-comment-action", "tooltipped", "tooltipped-ne");
  1010. reply.addEventListener("click", function(e) {
  1011. e.preventDefault();
  1012.  
  1013. var newComment = getCommentTextarea(this);
  1014.  
  1015. var timestamp = comment.querySelector(".timestamp");
  1016.  
  1017. var commentText = comment.querySelector(".comment-form-textarea");
  1018. if (commentText) {
  1019. commentText = commentText.value;
  1020. } else {
  1021. commentText = toMarkdown(comment.querySelector(".comment-body").innerHTML);
  1022. }
  1023. commentText = commentText.trim().split("\n").map(function(line) {
  1024. return "> " + line;
  1025. }).join("\n");
  1026.  
  1027. var text = newComment.value.length > 0 ? "\n" : "";
  1028. text += String.format('[**@{0}**]({1}/{0}) commented on [{2}]({3} "{4} - Replied by Github Comment Enhancer"):\n{5}\n\n',
  1029. comment.querySelector(".author").textContent,
  1030. location.origin,
  1031. timestamp.firstElementChild.getAttribute("title"),
  1032. timestamp.href,
  1033. timestamp.firstElementChild.getAttribute("datetime"),
  1034. commentText);
  1035.  
  1036. newComment.value += text;
  1037. newComment.setSelectionRange(newComment.value.length, newComment.value.length);
  1038. newComment.focus();
  1039. });
  1040.  
  1041. var replyIcon = document.createElement("span");
  1042. replyIcon.classList.add("octicon", "octicon-mail-reply");
  1043. reply.appendChild(replyIcon);
  1044.  
  1045. actions.appendChild(reply);
  1046. });
  1047. }
  1048.  
  1049. // init;
  1050. function init() {
  1051. addToolbar();
  1052. addReplyButtons();
  1053. }
  1054. init();
  1055.  
  1056. // on pjax;
  1057. unsafeWindow.$(document).on("pjax:end", init); // `pjax:end` also runs on history back;
  1058.  
  1059. // For inline comments on commits;
  1060. var files = document.querySelectorAll('.diff-table');
  1061. Array.prototype.forEach.call(files, function(file) {
  1062. file = file.firstElementChild;
  1063. new MutationObserver(function(mutations) {
  1064. mutations.forEach(function(mutation) {
  1065. if (mutation.target === file) {
  1066. addToolbar();
  1067. }
  1068. });
  1069. }).observe(file, {
  1070. childList: true,
  1071. subtree: true
  1072. });
  1073. });
  1074.  
  1075. })(typeof unsafeWindow !== "undefined" ? unsafeWindow : window);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址