🏠 Home 

punctuation_convert

Punctuation: English<->Chinese

  1. // ==UserScript==
  2. // @name punctuation_convert
  3. // @name:zh-CN 中英标点转换
  4. // @name:zh-TW 中英標點轉換
  5. // @namespace punctuation_convert
  6. // @description Punctuation: English<->Chinese
  7. // @description:zh-CN Punctuation: English<->Chinese
  8. // @description:zh-TW Punctuation: English<->Chinese
  9. // @include http://*
  10. // @include https://*
  11. // @run-at document-end
  12. // @grant GM_registerMenuCommand
  13. // @grant GM_setValue
  14. // @grant GM_getValue
  15. // @author zhuzemin
  16. // @version 1.01
  17. // ==/UserScript==
  18. //config
  19. let config = {
  20. 'debug': false,
  21. 'mode': GM_getValue('mode') || 1
  22. }
  23. let debug = config.debug ? console.log.bind(console) : function () {
  24. };
  25. // prepare UserPrefs
  26. setUserPref(
  27. 'mode',
  28. config.mode,
  29. 'Punctuation: English<->Chinese',
  30. `English->Chinese: "1"; Chinese->English: "0"`,
  31. );
  32. let init = function () {
  33. try {
  34. document.title = convert(document.title);
  35. findTextNode(document.documentElement);
  36. debug(document.title);
  37. } catch (e) {
  38. debug(e);
  39. }
  40. }
  41. window.addEventListener('load', init);
  42. function findTextNode(o) {
  43. let obj = o.childNodes;
  44. let olen = obj.length;
  45. for (let i = 0; i < olen; i++) {
  46. if (obj[i].splitText)
  47. obj[i].data = convert(obj[i].data);
  48. else if (obj[i].childNodes)
  49. findTextNode(obj[i]);
  50. }
  51. }
  52. function convert(cc) {
  53. let E_pun = ',.!?[]()<>"\'';
  54. let C_pun = ',。!?【】()《》“‘';
  55. let str = "";
  56. let find;
  57. let clen = cc.length;
  58. let src = null;
  59. let dest = null;
  60. let pattern = null;
  61. if (config.mode == 1) {
  62. src = E_pun;
  63. dest = C_pun;
  64. pattern = '[/x00-xff]';
  65. }
  66. else if (config.mode == 0) {
  67. src = C_pun;
  68. dest = E_pun;
  69. pattern = "[^\x00-\xff]";
  70. }
  71. for (let i = 0; i < clen; i++) {
  72. let ch = cc.charAt(i);
  73. let rerr = new RegExp(pattern);
  74. if (ch.search(rerr) == -1)
  75. find = -1;
  76. else
  77. find = src.indexOf(ch);
  78. if (find != -1)
  79. str += dest.charAt(find);
  80. else
  81. str += ch;
  82. }
  83. return str
  84. }
  85. /**
  86. * Create a user setting prompt
  87. * @param {string} varName
  88. * @param {any} defaultVal
  89. * @param {string} menuText
  90. * @param {string} promtText
  91. * @param {function} func
  92. */
  93. function setUserPref(varName, defaultVal, menuText, promtText, func = null) {
  94. GM_registerMenuCommand(menuText, function () {
  95. let val = prompt(promtText, GM_getValue(varName, defaultVal));
  96. if (val === null) { return; } // end execution if clicked CANCEL
  97. GM_setValue(varName, val);
  98. if (func != null) {
  99. func(val);
  100. }
  101. });
  102. }