extension.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /******/ (() => { // webpackBootstrap
  2. /******/ var __webpack_modules__ = ([
  3. /* 0 */,
  4. /* 1 */
  5. /***/ ((module) => {
  6. "use strict";
  7. module.exports = require("vscode");
  8. /***/ }),
  9. /* 2 */
  10. /***/ ((__unused_webpack_module, exports) => {
  11. "use strict";
  12. /**
  13. * Copyright (C) 2017-present by Andrea Giammarchi - @WebReflection
  14. *
  15. * Permission is hereby granted, free of charge, to any person obtaining a copy
  16. * of this software and associated documentation files (the "Software"), to deal
  17. * in the Software without restriction, including without limitation the rights
  18. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  19. * copies of the Software, and to permit persons to whom the Software is
  20. * furnished to do so, subject to the following conditions:
  21. *
  22. * The above copyright notice and this permission notice shall be included in
  23. * all copies or substantial portions of the Software.
  24. *
  25. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  27. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  28. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  30. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  31. * THE SOFTWARE.
  32. */
  33. const {replace} = '';
  34. // escape
  35. const es = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g;
  36. const ca = /[&<>'"]/g;
  37. const esca = {
  38. '&': '&amp;',
  39. '<': '&lt;',
  40. '>': '&gt;',
  41. "'": '&#39;',
  42. '"': '&quot;'
  43. };
  44. const pe = m => esca[m];
  45. /**
  46. * Safely escape HTML entities such as `&`, `<`, `>`, `"`, and `'`.
  47. * @param {string} es the input to safely escape
  48. * @returns {string} the escaped input, and it **throws** an error if
  49. * the input type is unexpected, except for boolean and numbers,
  50. * converted as string.
  51. */
  52. const escape = es => replace.call(es, ca, pe);
  53. exports.escape = escape;
  54. // unescape
  55. const unes = {
  56. '&amp;': '&',
  57. '&#38;': '&',
  58. '&lt;': '<',
  59. '&#60;': '<',
  60. '&gt;': '>',
  61. '&#62;': '>',
  62. '&apos;': "'",
  63. '&#39;': "'",
  64. '&quot;': '"',
  65. '&#34;': '"'
  66. };
  67. const cape = m => unes[m];
  68. /**
  69. * Safely unescape previously escaped entities such as `&`, `<`, `>`, `"`,
  70. * and `'`.
  71. * @param {string} un a previously escaped string
  72. * @returns {string} the unescaped input, and it **throws** an error if
  73. * the input type is unexpected, except for boolean and numbers,
  74. * converted as string.
  75. */
  76. const unescape = un => replace.call(un, es, cape);
  77. exports.unescape = unescape;
  78. /***/ }),
  79. /* 3 */
  80. /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
  81. "use strict";
  82. Object.defineProperty(exports, "__esModule", ({ value: true }));
  83. exports.request = void 0;
  84. const url_1 = __webpack_require__(4);
  85. const https = __webpack_require__(5);
  86. const qs = __webpack_require__(6);
  87. /**
  88. * Parse a request body based on known MIME types, based on the Content-Type
  89. * header. If unknown or undefined, will return the original request body.
  90. * @param {Object} opts - The request options.
  91. * @param {Object|string} body - The request body.
  92. * @returns {Object|string} A parsed request body for known MIME types, or the original request body.
  93. */
  94. function parse(opts = {}, body) {
  95. if (opts.headers == null) {
  96. return body;
  97. }
  98. switch (opts.headers['Content-Type']) {
  99. case 'application/json': return JSON.stringify(body);
  100. case 'application/x-www-form-urlencoded': return qs.stringify(body);
  101. default: return body;
  102. }
  103. }
  104. /**
  105. * Make an asynchronous request to an HTTP or HTTPS address. Automatically
  106. * derives protocol from URL input, and content length from the request body.
  107. * @param {URL|string} url - The request URL.
  108. * @param {Object} opts - The request options.
  109. * @param {Object|string} body - The request body.
  110. * @returns {Promise} A promise to return either a response object, or an error.
  111. */
  112. function request(url, opts = {}, body = '') {
  113. const data = parse(opts, body);
  114. if (opts.headers == null) {
  115. opts.headers = {};
  116. }
  117. return new Promise((resolve, reject) => {
  118. if (!(url instanceof url_1.URL)) {
  119. url = new url_1.URL(url);
  120. }
  121. const request = https.request(url, opts, (response) => {
  122. const chunks = [];
  123. response.on('data', (chunk) => {
  124. chunks.push(chunk);
  125. });
  126. response.on('end', () => {
  127. try {
  128. const { headers } = response;
  129. const body = chunks.join('');
  130. resolve({ headers, body });
  131. }
  132. catch (error) {
  133. reject(error);
  134. }
  135. });
  136. response.on('error', (error) => {
  137. reject(error);
  138. });
  139. });
  140. request.write(data);
  141. request.end();
  142. });
  143. }
  144. exports.request = request;
  145. /***/ }),
  146. /* 4 */
  147. /***/ ((module) => {
  148. "use strict";
  149. module.exports = require("url");
  150. /***/ }),
  151. /* 5 */
  152. /***/ ((module) => {
  153. "use strict";
  154. module.exports = require("https");
  155. /***/ }),
  156. /* 6 */
  157. /***/ ((module) => {
  158. "use strict";
  159. module.exports = require("querystring");
  160. /***/ }),
  161. /* 7 */
  162. /***/ ((module) => {
  163. var replacements = [
  164. [/\*/g, '\\*', 'asterisks'],
  165. [/#/g, '\\#', 'number signs'],
  166. [/\//g, '\\/', 'slashes'],
  167. [/\(/g, '\\(', 'parentheses'],
  168. [/\)/g, '\\)', 'parentheses'],
  169. [/\[/g, '\\[', 'square brackets'],
  170. [/\]/g, '\\]', 'square brackets'],
  171. [/</g, '&lt;', 'angle brackets'],
  172. [/>/g, '&gt;', 'angle brackets'],
  173. [/_/g, '\\_', 'underscores']
  174. ]
  175. module.exports = function (string, skips) {
  176. skips = skips || []
  177. return replacements.reduce(function (string, replacement) {
  178. var name = replacement[2]
  179. return name && skips.indexOf(name) !== -1
  180. ? string
  181. : string.replace(replacement[0], replacement[1])
  182. }, string)
  183. }
  184. /***/ })
  185. /******/ ]);
  186. /************************************************************************/
  187. /******/ // The module cache
  188. /******/ var __webpack_module_cache__ = {};
  189. /******/
  190. /******/ // The require function
  191. /******/ function __webpack_require__(moduleId) {
  192. /******/ // Check if module is in cache
  193. /******/ var cachedModule = __webpack_module_cache__[moduleId];
  194. /******/ if (cachedModule !== undefined) {
  195. /******/ return cachedModule.exports;
  196. /******/ }
  197. /******/ // Create a new module (and put it into the cache)
  198. /******/ var module = __webpack_module_cache__[moduleId] = {
  199. /******/ // no module.id needed
  200. /******/ // no module.loaded needed
  201. /******/ exports: {}
  202. /******/ };
  203. /******/
  204. /******/ // Execute the module function
  205. /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
  206. /******/
  207. /******/ // Return the exports of the module
  208. /******/ return module.exports;
  209. /******/ }
  210. /******/
  211. /************************************************************************/
  212. var __webpack_exports__ = {};
  213. // This entry need to be wrapped in an IIFE because it need to be in strict mode.
  214. (() => {
  215. "use strict";
  216. var exports = __webpack_exports__;
  217. Object.defineProperty(exports, "__esModule", ({ value: true }));
  218. exports.deactivate = exports.activate = void 0;
  219. // The module 'vscode' contains the VS Code extensibility API
  220. // Import the module and reference it with the alias vscode in your code below
  221. const vscode = __webpack_require__(1);
  222. const html_escaper_1 = __webpack_require__(2);
  223. const requests_1 = __webpack_require__(3);
  224. const markdownEscape = __webpack_require__(7);
  225. // this method is called when your extension is activated
  226. // your extension is activated the very first time the command is executed
  227. function activate(context) {
  228. let disposable = vscode.commands.registerCommand('wikipedia-hyperlinker.addHyperlink', () => {
  229. var editor = vscode.window.activeTextEditor;
  230. if (editor !== undefined) {
  231. const currentSelection = editor.selection;
  232. const text = editor.document.getText(currentSelection);
  233. if (text.trim() === '') {
  234. vscode.window.showErrorMessage('No text is selected');
  235. return false;
  236. }
  237. vscode.window.withProgress({
  238. location: vscode.ProgressLocation.Window,
  239. cancellable: false,
  240. title: 'Loading article from wikipedia...'
  241. }, async (progress) => {
  242. progress.report({ increment: 0 });
  243. try {
  244. const response = await (0, requests_1.request)(`https://en.wikipedia.org/w/api.php?format=json&action=query&prop=info|extracts&exintro&explaintext&&inprop=url&redirects=1&titles=${encodeURIComponent(text)}`);
  245. const body = JSON.parse(response.body);
  246. progress.report({ increment: 100 });
  247. console.log(response);
  248. const summary = body['query']['pages'][Object.keys(body['query']['pages'])[0]]['extract'];
  249. const url = body['query']['pages'][Object.keys(body['query']['pages'])[0]]['fullurl'];
  250. if (summary.includes("may refer to:")) {
  251. vscode.window
  252. .showInformationMessage(`There are multiple articles under the term ${text}. Do you want to see all the possible articles in wikipedia inside your browser?`, { modal: true }, ...["Yes", "No"])
  253. .then((answer) => {
  254. if (answer === "Yes") {
  255. vscode.env.openExternal(vscode.Uri.parse(url));
  256. }
  257. else {
  258. vscode.window.showInformationMessage("Okay, you can refine your text anytime and use the command again");
  259. }
  260. });
  261. return false;
  262. }
  263. var currentLanguage = editor?.document.languageId;
  264. if (currentLanguage === "markdown") {
  265. editor?.edit(editBuilder => {
  266. editBuilder.replace(currentSelection, `[${markdownEscape(text)}](${url})`);
  267. });
  268. }
  269. else if (currentLanguage === "html" || currentLanguage === "jinja") {
  270. editor?.edit(editBuilder => {
  271. editBuilder.replace(currentSelection, `<a href="${url}" title="${(0, html_escaper_1.escape)(summary)}">${(0, html_escaper_1.escape)(text)}</a>`);
  272. });
  273. }
  274. else {
  275. vscode.window.showWarningMessage(`The current language (${currentLanguage}) is not supported`, ...["Use HTML", "Use Markdown", "Cancel"]).then((answer) => {
  276. if (answer === "Use HTML") {
  277. editor?.edit(editBuilder => {
  278. editBuilder.replace(currentSelection, `<a href="${url}" title="${(0, html_escaper_1.escape)(summary)}">${(0, html_escaper_1.escape)(text)}</a>`);
  279. });
  280. }
  281. else if (answer === "Use Markdown") {
  282. editor?.edit(editBuilder => {
  283. editBuilder.replace(currentSelection, `[${markdownEscape(text)}](${url})`);
  284. });
  285. }
  286. });
  287. }
  288. }
  289. catch (error) {
  290. vscode.window.showErrorMessage(`Request failed`);
  291. console.error(error);
  292. }
  293. });
  294. }
  295. else {
  296. vscode.window.showInformationMessage('No window is active');
  297. }
  298. });
  299. context.subscriptions.push(disposable);
  300. }
  301. exports.activate = activate;
  302. // this method is called when your extension is deactivated
  303. function deactivate() { }
  304. exports.deactivate = deactivate;
  305. })();
  306. module.exports = __webpack_exports__;
  307. /******/ })()
  308. ;
  309. //# sourceMappingURL=extension.js.map