www

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README

ParseError.js (2051B)


      1 /**
      2  * This is the ParseError class, which is the main error thrown by KaTeX
      3  * functions when something has gone wrong. This is used to distinguish internal
      4  * errors from errors in the expression that the user provided.
      5  *
      6  * If possible, a caller should provide a Token or ParseNode with information
      7  * about where in the source string the problem occurred.
      8  *
      9  * @param {string} message  The error message
     10  * @param {(Token|ParseNode)=} token  An object providing position information
     11  */
     12 function ParseError(message, token) {
     13     let error = "KaTeX parse error: " + message;
     14     let start;
     15     let end;
     16 
     17     if (token && token.lexer && token.start <= token.end) {
     18         // If we have the input and a position, make the error a bit fancier
     19 
     20         // Get the input
     21         const input = token.lexer.input;
     22 
     23         // Prepend some information
     24         start = token.start;
     25         end = token.end;
     26         if (start === input.length) {
     27             error += " at end of input: ";
     28         } else {
     29             error += " at position " + (start + 1) + ": ";
     30         }
     31 
     32         // Underline token in question using combining underscores
     33         const underlined = input.slice(start, end).replace(/[^]/g, "$&\u0332");
     34 
     35         // Extract some context from the input and add it to the error
     36         let left;
     37         if (start > 15) {
     38             left = "…" + input.slice(start - 15, start);
     39         } else {
     40             left = input.slice(0, start);
     41         }
     42         let right;
     43         if (end + 15 < input.length) {
     44             right = input.slice(end, end + 15) + "…";
     45         } else {
     46             right = input.slice(end);
     47         }
     48         error += left + underlined + right;
     49     }
     50 
     51     // Some hackery to make ParseError a prototype of Error
     52     // See http://stackoverflow.com/a/8460753
     53     const self = new Error(error);
     54     self.name = "ParseError";
     55     self.__proto__ = ParseError.prototype;
     56 
     57     self.position = start;
     58     return self;
     59 }
     60 
     61 // More hackery
     62 ParseError.prototype.__proto__ = Error.prototype;
     63 
     64 module.exports = ParseError;