]> git.lyx.org Git - lyx.git/blob - src/mathed/MathFactory.cpp
Natbib authoryear uses (Ref1; Ref2) by default.
[lyx.git] / src / mathed / MathFactory.cpp
1 /**
2  * \file MathFactory.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "MathFactory.h"
14
15 #include "InsetMathAMSArray.h"
16 #include "InsetMathArray.h"
17 #include "InsetMathBoldSymbol.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathCancel.h"
20 #include "InsetMathCancelto.h"
21 #include "InsetMathCases.h"
22 #include "InsetMathColor.h"
23 #include "InsetMathDecoration.h"
24 #include "InsetMathDots.h"
25 #include "InsetMathEnsureMath.h"
26 #include "InsetMathFont.h"
27 #include "InsetMathFontOld.h"
28 #include "InsetMathFrac.h"
29 #include "InsetMathKern.h"
30 #include "InsetMathLefteqn.h"
31 #include "InsetMathOverset.h"
32 #include "InsetMathPhantom.h"
33 #include "InsetMathRef.h"
34 #include "InsetMathRoot.h"
35 #include "InsetMathSideset.h"
36 #include "InsetMathSize.h"
37 #include "InsetMathSpace.h"
38 #include "InsetMathSpecialChar.h"
39 #include "InsetMathSplit.h"
40 #include "InsetMathSqrt.h"
41 #include "InsetMathStackrel.h"
42 #include "InsetMathSubstack.h"
43 #include "InsetMathSymbol.h"
44 #include "InsetMathTabular.h"
45 #include "InsetMathUnderset.h"
46 #include "InsetMathUnknown.h"
47 #include "InsetMathHull.h"
48 #include "InsetMathXArrow.h"
49 #include "InsetMathXYMatrix.h"
50 #include "InsetMathDiagram.h"
51 #include "MacroTable.h"
52 #include "MathMacro.h"
53 #include "MathMacroArgument.h"
54 #include "MathParser.h"
55 #include "MathStream.h"
56 #include "MathSupport.h"
57
58 #include "insets/InsetCommand.h"
59 #include "insets/InsetSpace.h"
60
61 #include "support/debug.h"
62 #include "support/docstream.h"
63 #include "support/FileName.h"
64 #include "support/filetools.h" // LibFileSearch
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
67
68 #include "frontends/FontLoader.h"
69
70 #include "Buffer.h"
71 #include "BufferParams.h"
72 #include "Encoding.h"
73 #include "LyX.h" // use_gui
74 #include "OutputParams.h"
75
76 using namespace std;
77 using namespace lyx::support;
78
79 namespace lyx {
80
81 bool has_math_fonts;
82
83
84 namespace {
85
86 MathWordList theMathWordList;
87
88
89 bool isMathFontAvailable(docstring & name)
90 {
91         if (!use_gui)
92                 return false;
93
94         FontInfo f;
95         augmentFont(f, name);
96
97         // Do we have the font proper?
98         if (theFontLoader().available(f))
99                 return true;
100
101         // can we fake it?
102         if (name == "eufrak") {
103                 name = from_ascii("lyxfakefrak");
104                 return true;
105         }
106
107         LYXERR(Debug::MATHED,
108                 "font " << to_utf8(name) << " not available and I can't fake it");
109         return false;
110 }
111
112
113 void initSymbols()
114 {
115         FileName const filename = libFileSearch(string(), "symbols");
116         LYXERR(Debug::MATHED, "read symbols from " << filename);
117         if (filename.empty()) {
118                 lyxerr << "Could not find symbols file" << endl;
119                 return;
120         }
121
122         ifstream fs(filename.toFilesystemEncoding().c_str());
123         string line;
124         bool skip = false;
125         while (getline(fs, line)) {
126                 int charid     = 0;
127                 int fallbackid = 0;
128                 if (line.empty() || line[0] == '#')
129                         continue;
130
131                 // special case of iffont/else/endif
132                 if (line.size() >= 7 && line.substr(0, 6) == "iffont") {
133                         istringstream is(line);
134                         string tmp;
135                         is >> tmp;
136                         is >> tmp;
137                         docstring t = from_utf8(tmp);
138                         skip = !isMathFontAvailable(t);
139                         continue;
140                 } else if (line.size() >= 4 && line.substr(0, 4) == "else") {
141                         skip = !skip;
142                         continue;
143                 } else if (line.size() >= 5 && line.substr(0, 5) == "endif") {
144                         skip = false;
145                         continue;
146                 } else if (skip)
147                         continue;
148
149                 // special case of pre-defined macros
150                 if (line.size() > 8 && line.substr(0, 5) == "\\def\\") {
151                         //lyxerr << "macro definition: '" << line << '\'' << endl;
152                         istringstream is(line);
153                         string macro;
154                         string requires;
155                         is >> macro >> requires;
156                         MacroTable::iterator it = MacroTable::globalMacros().insert(
157                                         0, from_utf8(macro), requires);
158                         // If you change the following output, please adjust
159                         // development/tools/generate_symbols_images.py.
160                         LYXERR(Debug::MATHED, "read symbol '" << to_utf8(it->first)
161                                 << "  inset: macro"
162                                 << "  draw: 0"
163                                 << "  extra: "
164                                 << "  requires: " << requires << '\'');
165                         continue;
166                 }
167
168                 idocstringstream is(from_utf8(line));
169                 latexkeys tmp;
170                 is >> tmp.name >> tmp.inset;
171                 if (isFontName(tmp.inset))
172                         is >> charid >> fallbackid >> tmp.extra >> tmp.xmlname;
173                 else
174                         is >> tmp.extra;
175                 // requires is optional
176                 if (is) {
177                         is >> tmp.requires;
178                         // backward compatibility
179                         if (tmp.requires == "esintoramsmath")
180                                 tmp.requires = from_ascii("esint|amsmath");
181                 } else {
182                         LYXERR(Debug::MATHED, "skipping line '" << line << "'\n"
183                                 << to_utf8(tmp.name) << ' ' << to_utf8(tmp.inset) << ' '
184                                 << to_utf8(tmp.extra));
185                         continue;
186                 }
187
188                 if (isFontName(tmp.inset)) {
189                         // tmp.inset _is_ the fontname here.
190                         // create fallbacks if necessary
191
192                         // store requirements as long as we can
193                         if (tmp.requires.empty()) {
194                                 if (tmp.inset == "msa" || tmp.inset == "msb")
195                                         tmp.requires = from_ascii("amssymb");
196                                 else if (tmp.inset == "wasy")
197                                         tmp.requires = from_ascii("wasysym");
198                                 else if (tmp.inset == "mathscr")
199                                         tmp.requires = from_ascii("mathrsfs");
200                         }
201
202                         // symbol font is not available sometimes
203                         docstring symbol_font = from_ascii("lyxsymbol");
204
205                         if (tmp.extra == "func" || tmp.extra == "funclim" || tmp.extra == "special") {
206                                 LYXERR(Debug::MATHED, "symbol abuse for " << to_utf8(tmp.name));
207                                 tmp.draw = tmp.name;
208                         } else if (isMathFontAvailable(tmp.inset)) {
209                                 LYXERR(Debug::MATHED, "symbol available for " << to_utf8(tmp.name));
210                                 tmp.draw.push_back(char_type(charid));
211                         } else if (fallbackid && isMathFontAvailable(symbol_font)) {
212                                 if (tmp.inset == "cmex")
213                                         tmp.inset = from_ascii("lyxsymbol");
214                                 else
215                                         tmp.inset = from_ascii("lyxboldsymbol");
216                                 LYXERR(Debug::MATHED, "symbol fallback for " << to_utf8(tmp.name));
217                                 tmp.draw.push_back(char_type(fallbackid));
218                         } else {
219                                 LYXERR(Debug::MATHED, "faking " << to_utf8(tmp.name));
220                                 tmp.draw = tmp.name;
221                                 tmp.inset = from_ascii("lyxtex");
222                         }
223                 } else {
224                         // it's a proper inset
225                         LYXERR(Debug::MATHED, "inset " << to_utf8(tmp.inset)
226                                               << " used for " << to_utf8(tmp.name));
227                 }
228
229                 if (theMathWordList.find(tmp.name) != theMathWordList.end())
230                         LYXERR(Debug::MATHED, "readSymbols: inset " << to_utf8(tmp.name)
231                                 << " already exists.");
232                 else
233                         theMathWordList[tmp.name] = tmp;
234
235                 // If you change the following output, please adjust
236                 // development/tools/generate_symbols_images.py.
237                 LYXERR(Debug::MATHED, "read symbol '" << to_utf8(tmp.name)
238                         << "  inset: " << to_utf8(tmp.inset)
239                         << "  draw: " << int(tmp.draw.empty() ? 0 : tmp.draw[0])
240                         << "  extra: " << to_utf8(tmp.extra)
241                         << "  requires: " << to_utf8(tmp.requires) << '\'');
242         }
243         docstring tmp = from_ascii("cmm");
244         docstring tmp2 = from_ascii("cmsy");
245         has_math_fonts = isMathFontAvailable(tmp) && isMathFontAvailable(tmp2);
246 }
247
248
249 bool isSpecialChar(docstring const & name)
250 {
251         if (name.size() != 1)
252                 return  name == "textasciicircum" || name == "mathcircumflex" ||
253                         name == "textasciitilde"  || name == "textbackslash";
254
255         char_type const c = name.at(0);
256         return  c == '{' || c == '}' || c == '&' || c == '$' ||
257                 c == '#' || c == '%' || c == '_';
258 }
259
260
261 } // namespace anon
262
263 MathWordList const & mathedWordList()
264 {
265         return theMathWordList;
266 }
267
268
269 void initMath()
270 {
271         static bool initialized = false;
272         if (!initialized) {
273                 initialized = true;
274                 initParser();
275                 initSymbols();
276         }
277 }
278
279
280 bool ensureMath(WriteStream & os, bool needs_math_mode, bool macro)
281 {
282         bool brace = os.pendingBrace();
283         os.pendingBrace(false);
284         if (!os.latex())
285                 return brace;
286         if (os.textMode() && needs_math_mode) {
287                 os << "\\ensuremath{";
288                 os.textMode(false);
289                 brace = true;
290         } else if (macro && brace && !needs_math_mode) {
291                 // This is a user defined macro, but not a MathMacro, so we
292                 // cannot be sure what mode is needed. As it was entered in
293                 // a text box, we restore the text mode.
294                 os << '}';
295                 os.textMode(true);
296                 brace = false;
297         }
298         return brace;
299 }
300
301
302 int ensureMode(WriteStream & os, InsetMath::mode_type mode,
303                 bool locked, bool ascii)
304 {
305         bool textmode = mode == InsetMath::TEXT_MODE;
306         if (os.latex() && textmode && os.pendingBrace()) {
307                 os.os() << '}';
308                 os.pendingBrace(false);
309                 os.pendingSpace(false);
310                 os.textMode(true);
311         }
312         int oldmodes = os.textMode() ? 0x01 : 0;
313         os.textMode(textmode);
314         oldmodes |= os.lockedMode() ? 0x02 : 0;
315         os.lockedMode(locked);
316         oldmodes |= os.asciiOnly() ? 0x04 : 0;
317         os.asciiOnly(ascii);
318         return oldmodes;
319 }
320
321
322 latexkeys const * in_word_set(docstring const & str)
323 {
324         MathWordList::iterator it = theMathWordList.find(str);
325         return it != theMathWordList.end() ? &(it->second) : 0;
326 }
327
328
329 MathAtom createInsetMath(char const * const s, Buffer * buf)
330 {
331         return createInsetMath(from_utf8(s), buf);
332 }
333
334
335 MathAtom createInsetMath(docstring const & s, Buffer * buf)
336 {
337         //lyxerr << "creating inset with name: '" << to_utf8(s) << '\'' << endl;
338         if ((s == "ce" || s == "cf") && buf
339             && buf->params().use_package("mhchem") == BufferParams::package_off)
340                 return MathAtom(new MathMacro(buf, s));
341
342         latexkeys const * l = in_word_set(s);
343         if (l) {
344                 docstring const & inset = l->inset;
345                 //lyxerr << " found inset: '" << inset << '\'' << endl;
346                 if (inset == "ref")
347                         return MathAtom(new InsetMathRef(buf, l->name));
348                 if (inset == "overset")
349                         return MathAtom(new InsetMathOverset(buf));
350                 if (inset == "underset")
351                         return MathAtom(new InsetMathUnderset(buf));
352                 if (inset == "decoration")
353                         return MathAtom(new InsetMathDecoration(buf, l));
354                 if (inset == "space")
355                         return MathAtom(new InsetMathSpace(to_ascii(l->name), ""));
356                 if (inset == "dots")
357                         return MathAtom(new InsetMathDots(l));
358                 if (inset == "mbox")
359                         // return MathAtom(new InsetMathMBox);
360                         // InsetMathMBox is proposed to replace InsetMathBox,
361                         // but is not ready yet (it needs a BufferView for
362                         // construction)
363                         return MathAtom(new InsetMathBox(buf, l->name));
364 //              if (inset == "fbox")
365 //                      return MathAtom(new InsetMathFBox(l));
366                 if (inset == "style")
367                         return MathAtom(new InsetMathSize(buf, l));
368                 if (inset == "font")
369                         return MathAtom(new InsetMathFont(buf, l));
370                 if (inset == "oldfont")
371                         return MathAtom(new InsetMathFontOld(buf, l));
372                 if (inset == "matrix")
373                         return MathAtom(new InsetMathAMSArray(buf, s));
374                 if (inset == "split")
375                         return MathAtom(new InsetMathSplit(buf, s));
376                 if (inset == "big")
377                         // we can't create a InsetMathBig, since the argument
378                         // is missing.
379                         return MathAtom(new InsetMathUnknown(s));
380                 return MathAtom(new InsetMathSymbol(l));
381         }
382
383         if (s.size() == 2 && s[0] == '#' && s[1] >= '1' && s[1] <= '9')
384                 return MathAtom(new MathMacroArgument(s[1] - '0'));
385         if (s.size() == 3 && s[0] == '\\' && s[1] == '#'
386                         && s[2] >= '1' && s[2] <= '9')
387                 return MathAtom(new MathMacroArgument(s[2] - '0'));
388         if (s == "boxed")
389                 return MathAtom(new InsetMathBoxed(buf));
390         if (s == "fbox")
391                 return MathAtom(new InsetMathFBox(buf));
392         if (s == "framebox")
393                 return MathAtom(new InsetMathMakebox(buf, true));
394         if (s == "makebox")
395                 return MathAtom(new InsetMathMakebox(buf, false));
396         if (s == "kern")
397                 return MathAtom(new InsetMathKern);
398         if (s.substr(0, 8) == "xymatrix") {
399                 char spacing_code = '\0';
400                 Length spacing;
401                 bool equal_spacing = false;
402                 size_t const len = s.length();
403                 size_t i = 8;
404                 if (i < len && s[i] == '@') {
405                         ++i;
406                         if (i < len && s[i] == '!') {
407                                 equal_spacing = true;
408                                 ++i;
409                                 if (i < len) {
410                                         switch (s[i]) {
411                                         case '0':
412                                         case 'R':
413                                         case 'C':
414                                                 spacing_code = static_cast<char>(s[i]);
415                                         }
416                                 }
417                         } else if (i < len) {
418                                 switch (s[i]) {
419                                 case 'R':
420                                 case 'C':
421                                 case 'M':
422                                 case 'W':
423                                 case 'H':
424                                 case 'L':
425                                         spacing_code = static_cast<char>(s[i]);
426                                         ++i;
427                                         break;
428                                 }
429                                 if (i < len && s[i] == '=') {
430                                         ++i;
431                                         spacing = Length(to_ascii(s.substr(i)));
432                                 }
433                         }
434                 }
435                 return MathAtom(new InsetMathXYMatrix(buf, spacing, spacing_code,
436                         equal_spacing));
437         }
438
439         if (s == "Diagram")
440                 return MathAtom(new InsetMathDiagram(buf));
441         if (s == "xrightarrow" || s == "xleftarrow")
442                 return MathAtom(new InsetMathXArrow(buf, s));
443         if (s == "split" || s == "alignedat")
444                 return MathAtom(new InsetMathSplit(buf, s));
445         if (s == "cases")
446                 return MathAtom(new InsetMathCases(buf));
447         if (s == "substack")
448                 return MathAtom(new InsetMathSubstack(buf));
449         if (s == "subarray" || s == "array")
450                 return MathAtom(new InsetMathArray(buf, s, 1, 1));
451         if (s == "sqrt")
452                 return MathAtom(new InsetMathSqrt(buf));
453         if (s == "root")
454                 return MathAtom(new InsetMathRoot(buf));
455         if (s == "tabular")
456                 return MathAtom(new InsetMathTabular(buf, s, 1, 1));
457         if (s == "stackrel")
458                 return MathAtom(new InsetMathStackrel(buf, false));
459         // This string value is only for math toolbar use, no LaTeX name
460         if (s == "stackrelthree")
461                 return MathAtom(new InsetMathStackrel(buf, true));
462         if (s == "binom")
463                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BINOM));
464         if (s == "dbinom")
465                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::DBINOM));
466         if (s == "tbinom")
467                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::TBINOM));
468         if (s == "choose")
469                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::CHOOSE));
470         if (s == "brace")
471                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BRACE));
472         if (s == "brack")
473                 return MathAtom(new InsetMathBinom(buf, InsetMathBinom::BRACK));
474         if (s == "frac")
475                 return MathAtom(new InsetMathFrac(buf));
476         if (s == "cfrac")
477                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRAC));
478         if (s == "dfrac")
479                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::DFRAC));
480         if (s == "tfrac")
481                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::TFRAC));
482         if (s == "over")
483                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::OVER));
484         if (s == "nicefrac")
485                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::NICEFRAC));
486         if (s == "unitfrac")
487                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC));
488         // These string values are only for math toolbar use, no LaTeX names
489         if (s == "unitfracthree")
490                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNITFRAC, 3));
491         if (s == "unitone")
492                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT, 1));
493         if (s == "unittwo")
494                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::UNIT));
495         if (s == "cfracleft")
496                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACLEFT));
497         if (s == "cfracright")
498                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::CFRACRIGHT));
499         //if (s == "infer")
500         //      return MathAtom(new MathInferInset);
501         if (s == "atop")
502                 return MathAtom(new InsetMathFrac(buf, InsetMathFrac::ATOP));
503         if (s == "lefteqn")
504                 return MathAtom(new InsetMathLefteqn(buf));
505         if (s == "boldsymbol")
506                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::AMS_BOLD));
507         if (s == "bm")
508                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::BM_BOLD));
509         if (s == "heavysymbol" || s == "hm")
510                 return MathAtom(new InsetMathBoldSymbol(buf, InsetMathBoldSymbol::BM_HEAVY));
511         if (s == "color" || s == "normalcolor")
512                 return MathAtom(new InsetMathColor(buf, true));
513         if (s == "textcolor")
514                 return MathAtom(new InsetMathColor(buf, false));
515         if (s == "hphantom")
516                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::hphantom));
517         if (s == "phantom")
518                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::phantom));
519         if (s == "vphantom")
520                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::vphantom));
521         if (s == "cancel")
522                 return MathAtom(new InsetMathCancel(buf, InsetMathCancel::cancel));
523         if (s == "bcancel")
524                 return MathAtom(new InsetMathCancel(buf, InsetMathCancel::bcancel));
525         if (s == "xcancel")
526                 return MathAtom(new InsetMathCancel(buf, InsetMathCancel::xcancel));
527         if (s == "cancelto")
528                 return MathAtom(new InsetMathCancelto(buf));
529         if (s == "smash")
530                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::smash));
531         if (s == "mathclap")
532                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::mathclap));
533         if (s == "mathllap")
534                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::mathllap));
535         if (s == "mathrlap")
536                 return MathAtom(new InsetMathPhantom(buf, InsetMathPhantom::mathrlap));
537         if (s == "ensuremath")
538                 return MathAtom(new InsetMathEnsureMath(buf));
539         if (s == "sideset")
540                 return MathAtom(new InsetMathSideset(buf, true, true));
541         // The following 3 string values are only for math toolbar use, no LaTeX names
542         if (s == "sidesetr")
543                 return MathAtom(new InsetMathSideset(buf, false, true));
544         if (s == "sidesetl")
545                 return MathAtom(new InsetMathSideset(buf, true, false));
546         if (s == "sidesetn")
547                 return MathAtom(new InsetMathSideset(buf, false, false));
548         if (isSpecialChar(s))
549                 return MathAtom(new InsetMathSpecialChar(s));
550         if (s == " ")
551                 return MathAtom(new InsetMathSpace(" ", ""));
552
553         if (s == "regexp")
554                 return MathAtom(new InsetMathHull(buf, hullRegexp));
555
556         return MathAtom(new MathMacro(buf, s));
557 }
558
559
560 bool createInsetMath_fromDialogStr(docstring const & str, MathData & ar)
561 {
562         // An example str:
563         // "ref LatexCommand ref\nreference \"sec:Title\"\n\\end_inset\n\n";
564         docstring name;
565         docstring body = split(str, name, ' ');
566
567         if (name == "ref") {
568                 InsetCommandParams icp(REF_CODE);
569                 // FIXME UNICODE
570                 InsetCommand::string2params(to_utf8(str), icp);
571                 Encoding const * const utf8 = encodings.fromLyXName("utf8");
572                 OutputParams op(utf8);
573                 mathed_parse_cell(ar, icp.getCommand(op));
574         } else if (name == "mathspace") {
575                 InsetSpaceParams isp(true);
576                 InsetSpace::string2params(to_utf8(str), isp);
577                 InsetSpace is(isp);
578                 TexRow texrow;
579                 odocstringstream ods;
580                 otexstream os(ods, texrow);
581                 Encoding const * const ascii = encodings.fromLyXName("ascii");
582                 OutputParams op(ascii);
583                 is.latex(os, op);
584                 mathed_parse_cell(ar, ods.str());
585                 if (ar.size() == 2) {
586                         // remove "{}"
587                         if (ar[1].nucleus()->asBraceInset())
588                                 ar.pop_back();
589                 }
590         } else
591                 return false;
592
593         if (ar.size() != 1)
594                 return false;
595
596         return ar[0].nucleus();
597 }
598
599
600 bool isAsciiOrMathAlpha(char_type c)
601 {
602         return isASCII(c) || Encodings::isMathAlpha(c);
603 }
604
605
606 } // namespace lyx