]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacro.cpp
Don't print useless messages while parsing math macros
[lyx.git] / src / mathed / MathMacro.cpp
1 /**
2  * \file MathMacro.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alejandro Aguilar Sierra
7  * \author André Pönitz
8  * \author Stefan Schimanski
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "MathMacro.h"
16
17 #include "InsetMathChar.h"
18 #include "MathCompletionList.h"
19 #include "MathExtern.h"
20 #include "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
23
24 #include "Buffer.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
27 #include "Cursor.h"
28 #include "FuncStatus.h"
29 #include "FuncRequest.h"
30 #include "LaTeXFeatures.h"
31 #include "LyX.h"
32 #include "LyXRC.h"
33 #include "MetricsInfo.h"
34
35 #include "frontends/Painter.h"
36
37 #include "support/debug.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
41 #include "support/textutils.h"
42
43 #include <ostream>
44 #include <vector>
45
46 using namespace lyx::support;
47 using namespace std;
48
49 namespace lyx {
50
51
52 /// A proxy for the macro values
53 class ArgumentProxy : public InsetMath {
54 public:
55         ///
56         ArgumentProxy(MathMacro * mathMacro, size_t idx)
57                 : mathMacro_(mathMacro), idx_(idx) {}
58         ///
59         ArgumentProxy(MathMacro * mathMacro, size_t idx, docstring const & def)
60                 : mathMacro_(mathMacro), idx_(idx)
61         {
62                         asArray(def, def_);
63         }
64         ///
65         void setOwner(MathMacro * mathMacro) { mathMacro_ = mathMacro; }
66         ///
67         MathMacro const * owner() { return mathMacro_; }
68         ///
69         InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
70         ///
71         void metrics(MetricsInfo & mi, Dimension & dim) const {
72                 mathMacro_->macro()->unlock();
73                 mathMacro_->cell(idx_).metrics(mi, dim);
74
75                 if (!mathMacro_->editMetrics(mi.base.bv)
76                     && mathMacro_->cell(idx_).empty())
77                         def_.metrics(mi, dim);
78
79                 mathMacro_->macro()->lock();
80         }
81         // write(), normalize(), infoize() and infoize2() are not needed since
82         // MathMacro uses the definition and not the expanded cells.
83         ///
84         void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
85         ///
86         void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
87         ///
88         void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
89         ///
90         void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
91         ///
92         void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
93         ///
94         void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
95         ///
96         void draw(PainterInfo & pi, int x, int y) const {
97                 if (mathMacro_->editMetrics(pi.base.bv)) {
98                         // The only way a ArgumentProxy can appear is in a cell of the
99                         // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
100                         // mode and then, if the macro is edited the monochrome
101                         // mode is entered by the MathMacro before calling the cells' draw
102                         // method. Then eventually this code is reached and the proxy leaves
103                         // monochrome mode temporarely. Hence, if it is not in monochrome
104                         // here (and the assert triggers in pain.leaveMonochromeMode())
105                         // it's a bug.
106                         pi.pain.leaveMonochromeMode();
107                         mathMacro_->cell(idx_).draw(pi, x, y);
108                         pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
109                 } else if (mathMacro_->cell(idx_).empty()) {
110                         mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
111                         def_.draw(pi, x, y);
112                 } else
113                         mathMacro_->cell(idx_).draw(pi, x, y);
114         }
115         ///
116         size_t idx() const { return idx_; }
117         ///
118         int kerning(BufferView const * bv) const
119         {
120                 if (mathMacro_->editMetrics(bv)
121                     || !mathMacro_->cell(idx_).empty())
122                         return mathMacro_->cell(idx_).kerning(bv);
123                 else
124                         return def_.kerning(bv);
125         }
126
127 private:
128         ///
129         Inset * clone() const
130         {
131                 return new ArgumentProxy(*this);
132         }
133         ///
134         MathMacro * mathMacro_;
135         ///
136         size_t idx_;
137         ///
138         MathData def_;
139 };
140
141
142 /// Private implementation of MathMacro
143 class MathMacro::Private {
144 public:
145         Private(Buffer * buf, docstring const & name)
146                 : name_(name), displayMode_(DISPLAY_INIT),
147                   expanded_(buf), definition_(buf), attachedArgsNum_(0),
148                   optionals_(0), nextFoldMode_(true), macroBackup_(buf),
149                   macro_(0), needsUpdate_(false), isUpdating_(false),
150                   appetite_(9)
151         {
152         }
153         /// Update the pointers to our owner of all expanded macros.
154         /// This needs to be called every time a copy of the owner is created
155         /// (bug 9418).
156         void updateChildren(MathMacro * owner);
157         /// Recursively update the pointers of all expanded macros
158         /// appearing in the arguments of the current macro
159         void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
160         /// name of macro
161         docstring name_;
162         /// current display mode
163         DisplayMode displayMode_;
164         /// expanded macro with ArgumentProxies
165         MathData expanded_;
166         /// macro definition with #1,#2,.. insets
167         MathData definition_;
168         /// number of arguments that were really attached
169         size_t attachedArgsNum_;
170         /// optional argument attached? (only in DISPLAY_NORMAL mode)
171         size_t optionals_;
172         /// fold mode to be set in next metrics call?
173         bool nextFoldMode_;
174         /// if macro_ == true, then here is a copy of the macro
175         /// don't use it for locking
176         MacroData macroBackup_;
177         /// if macroNotFound_ == false, then here is a reference to the macro
178         /// this might invalidate after metrics was called
179         MacroData const * macro_;
180         ///
181         mutable std::map<BufferView const *, bool> editing_;
182         ///
183         std::string requires_;
184         /// update macro representation
185         bool needsUpdate_;
186         ///
187         bool isUpdating_;
188         /// maximal number of arguments the macro is greedy for
189         size_t appetite_;
190 };
191
192
193 void MathMacro::Private::updateChildren(MathMacro * owner)
194 {
195         for (size_t i = 0; i < expanded_.size(); ++i) {
196                 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
197                 if (p)
198                         p->setOwner(owner);
199
200                 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
201                 if (ni)
202                         updateNestedChildren(owner, ni);
203         }
204
205         if (macro_) {
206                 // The macro_ pointer is updated when MathData::metrics() is
207                 // called. However, when instant preview is on or the macro is
208                 // not on screen, MathData::metrics() is not called and we may
209                 // have a dangling pointer. As a safety measure, when a macro
210                 // is copied, always let macro_ point to the backup copy of the
211                 // MacroData structure. This backup is updated every time the
212                 // macro is changed, so it will not become stale.
213                 macro_ = &macroBackup_;
214         }
215 }
216
217
218 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
219 {
220         for (size_t i = 0; i < ni->nargs(); ++i) {
221                 MathData & ar = ni->cell(i);
222                 for (size_t j = 0; j < ar.size(); ++j) {
223                         ArgumentProxy * ap = dynamic_cast
224                                 <ArgumentProxy *>(ar[j].nucleus());
225                         if (ap) {
226                                 MathMacro::Private * md = ap->owner()->d;
227                                 if (md->macro_)
228                                         md->macro_ = &md->macroBackup_;
229                                 ap->setOwner(owner);
230                         }
231                         InsetMathNest * imn = ar[j].nucleus()->asNestInset();
232                         if (imn)
233                                 updateNestedChildren(owner, imn);
234                 }
235         }
236 }
237
238
239 MathMacro::MathMacro(Buffer * buf, docstring const & name)
240         : InsetMathNest(buf, 0), d(new Private(buf, name))
241 {}
242
243
244 MathMacro::MathMacro(MathMacro const & that)
245         : InsetMathNest(that), d(new Private(*that.d))
246 {
247         setBuffer(*that.buffer_);
248         d->updateChildren(this);
249 }
250
251
252 MathMacro & MathMacro::operator=(MathMacro const & that)
253 {
254         if (&that == this)
255                 return *this;
256         InsetMathNest::operator=(that);
257         *d = *that.d;
258         d->updateChildren(this);
259         return *this;
260 }
261
262
263 MathMacro::~MathMacro()
264 {
265         delete d;
266 }
267
268
269 Inset * MathMacro::clone() const
270 {
271         MathMacro * copy = new MathMacro(*this);
272         copy->d->needsUpdate_ = true;
273         //copy->d->expanded_.clear();
274         return copy;
275 }
276
277
278 void MathMacro::normalize(NormalStream & os) const
279 {
280         os << "[macro " << name();
281         for (size_t i = 0; i < nargs(); ++i)
282                 os << ' ' << cell(i);
283         os << ']';
284 }
285
286
287 MathMacro::DisplayMode MathMacro::displayMode() const
288 {
289         return d->displayMode_;
290 }
291
292
293 bool MathMacro::extraBraces() const
294 {
295         return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
296 }
297
298
299 docstring MathMacro::name() const
300 {
301         if (d->displayMode_ == DISPLAY_UNFOLDED)
302                 return asString(cell(0));
303
304         return d->name_;
305 }
306
307
308 docstring MathMacro::macroName() const
309 {
310         return d->name_;
311 }
312
313
314 void MathMacro::cursorPos(BufferView const & bv,
315                 CursorSlice const & sl, bool boundary, int & x, int & y) const
316 {
317         // We may have 0 arguments, but InsetMathNest requires at least one.
318         if (nargs() > 0)
319                 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
320 }
321
322
323 bool MathMacro::editMode(BufferView const * bv) const {
324         // find this in cursor trace
325         Cursor const & cur = bv->cursor();
326         for (size_t i = 0; i != cur.depth(); ++i)
327                 if (&cur[i].inset() == this) {
328                         // look if there is no other macro in edit mode above
329                         ++i;
330                         for (; i != cur.depth(); ++i) {
331                                 InsetMath * im = cur[i].asInsetMath();
332                                 if (im) {
333                                         MathMacro const * macro = im->asMacro();
334                                         if (macro && macro->displayMode() == DISPLAY_NORMAL)
335                                                 return false;
336                                 }
337                         }
338
339                         // ok, none found, I am the highest one
340                         return true;
341                 }
342
343         return false;
344 }
345
346
347 MacroData const * MathMacro::macro()
348 {
349         return d->macro_;
350 }
351
352
353 bool MathMacro::editMetrics(BufferView const * bv) const
354 {
355         return d->editing_[bv];
356 }
357
358
359 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
360 {
361         // set edit mode for which we will have calculated metrics. But only
362         d->editing_[mi.base.bv] = editMode(mi.base.bv);
363
364         // calculate new metrics according to display mode
365         if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
366                 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
367         } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
368                 cell(0).metrics(mi, dim);
369                 Dimension bsdim;
370                 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
371                 dim.wid += bsdim.width() + 1;
372                 dim.asc = max(bsdim.ascent(), dim.ascent());
373                 dim.des = max(bsdim.descent(), dim.descent());
374                 metricsMarkers(dim);
375         } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
376                    && d->editing_[mi.base.bv]) {
377                 // Macro will be edited in a old-style list mode here:
378
379                 LBUFERR(d->macro_);
380                 Dimension fontDim;
381                 FontInfo labelFont = sane_font;
382                 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
383
384                 // get dimension of components of list view
385                 Dimension nameDim;
386                 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
387                 nameDim.asc = fontDim.asc;
388                 nameDim.des = fontDim.des;
389
390                 Dimension argDim;
391                 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
392                 argDim.asc = fontDim.asc;
393                 argDim.des = fontDim.des;
394
395                 Dimension defDim;
396                 d->definition_.metrics(mi, defDim);
397
398                 // add them up
399                 dim.wid = nameDim.wid + defDim.wid;
400                 dim.asc = max(nameDim.asc, defDim.asc);
401                 dim.des = max(nameDim.des, defDim.des);
402
403                 for (idx_type i = 0; i < nargs(); ++i) {
404                         Dimension cdim;
405                         cell(i).metrics(mi, cdim);
406                         dim.des += max(argDim.height(), cdim.height()) + 1;
407                         dim.wid = max(dim.wid, argDim.wid + cdim.wid);
408                 }
409
410                 // make space for box and markers, 2 pixels
411                 dim.asc += 1;
412                 dim.des += 1;
413                 dim.wid += 2;
414                 metricsMarkers2(dim);
415         } else {
416                 LBUFERR(d->macro_);
417
418                 // calculate metrics, hoping that all cells are seen
419                 d->macro_->lock();
420                 d->expanded_.metrics(mi, dim);
421
422                 // otherwise do a manual metrics call
423                 CoordCache & coords = mi.base.bv->coordCache();
424                 for (idx_type i = 0; i < nargs(); ++i) {
425                         if (!coords.getArrays().hasDim(&cell(i))) {
426                                 Dimension tdim;
427                                 cell(i).metrics(mi, tdim);
428                         }
429                 }
430                 d->macro_->unlock();
431
432                 // calculate dimension with label while editing
433                 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
434                     && d->editing_[mi.base.bv]) {
435                         FontInfo font = mi.base.font;
436                         augmentFont(font, "lyxtex");
437                         Dimension namedim;
438                         mathed_string_dim(font, name(), namedim);
439 #if 0
440                         dim.wid += 2 + namedim.wid + 2 + 2;
441                         dim.asc = max(dim.asc, namedim.asc) + 2;
442                         dim.des = max(dim.des, namedim.des) + 2;
443 #endif
444                         dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
445                         dim.asc += 1 + namedim.height() + 1;
446                         dim.des += 2;
447                 }
448         }
449 }
450
451
452 int MathMacro::kerning(BufferView const * bv) const {
453         if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
454                 return d->expanded_.kerning(bv);
455         else
456                 return 0;
457 }
458
459
460 void MathMacro::updateMacro(MacroContext const & mc)
461 {
462         if (validName()) {
463                 d->macro_ = mc.get(name());
464                 if (d->macro_ && d->macroBackup_ != *d->macro_) {
465                         d->macroBackup_ = *d->macro_;
466                         d->needsUpdate_ = true;
467                 }
468         } else {
469                 d->macro_ = 0;
470         }
471 }
472
473
474 class MathMacro::UpdateLocker
475 {
476 public:
477         explicit UpdateLocker(MathMacro & mm) : mac(mm)
478         {
479                 mac.d->isUpdating_ = true;
480         }
481         ~UpdateLocker() { mac.d->isUpdating_ = false; }
482 private:
483         MathMacro & mac;
484 };
485 /** Avoid wrong usage of UpdateLocker.
486     To avoid wrong usage:
487     UpdateLocker(...); // wrong
488     UpdateLocker locker(...); // right
489 */
490 #define UpdateLocker(x) unnamed_UpdateLocker;
491 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
492
493
494 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
495                 UpdateType utype)
496 {
497         // block recursive calls (bug 8999)
498         if (d->isUpdating_)
499                 return;
500
501         UpdateLocker locker(*this);
502
503         // known macro?
504         if (d->macro_ == 0)
505                 return;
506
507         // update requires
508         d->requires_ = d->macro_->requires();
509
510         if (!d->needsUpdate_
511                 // non-normal mode? We are done!
512                 || (d->displayMode_ != DISPLAY_NORMAL))
513                 return;
514
515         d->needsUpdate_ = false;
516
517         // get default values of macro
518         vector<docstring> const & defaults = d->macro_->defaults();
519
520         // create MathMacroArgumentValue objects pointing to the cells of the macro
521         vector<MathData> values(nargs());
522         for (size_t i = 0; i < nargs(); ++i) {
523                 ArgumentProxy * proxy;
524                 if (i < defaults.size())
525                         proxy = new ArgumentProxy(this, i, defaults[i]);
526                 else
527                         proxy = new ArgumentProxy(this, i);
528                 values[i].insert(0, MathAtom(proxy));
529         }
530         // expanding macro with the values
531         // Only update the argument macros if anything was expanded, otherwise
532         // we would get an endless loop (bug 9140). UpdateLocker does not work
533         // in this case, since MacroData::expand() creates new MathMacro
534         // objects, so this would be a different recursion path than the one
535         // protected by UpdateLocker.
536         if (d->macro_->expand(values, d->expanded_)) {
537                 if (utype == OutputUpdate && !d->expanded_.empty())
538                         d->expanded_.updateMacros(cur, mc, utype);
539         }
540         // get definition for list edit mode
541         docstring const & display = d->macro_->display();
542         asArray(display.empty() ? d->macro_->definition() : display,
543                 d->definition_, Parse::QUIET);
544 }
545
546
547 void MathMacro::draw(PainterInfo & pi, int x, int y) const
548 {
549         Dimension const dim = dimension(*pi.base.bv);
550
551         setPosCache(pi, x, y);
552         int expx = x;
553         int expy = y;
554
555         if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
556                 Changer dummy = pi.base.changeFontSet("lyxtex");
557                 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
558         } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
559                 Changer dummy = pi.base.changeFontSet("lyxtex");
560                 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
561                 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
562                 cell(0).draw(pi, x, y);
563                 drawMarkers(pi, expx, expy);
564         } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
565                    && d->editing_[pi.base.bv]) {
566                 // Macro will be edited in a old-style list mode here:
567
568                 CoordCache const & coords = pi.base.bv->coordCache();
569                 FontInfo const & labelFont = sane_font;
570
571                 // markers and box needs two pixels
572                 x += 2;
573
574                 // get maximal font height
575                 Dimension fontDim;
576                 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
577
578                 // draw label
579                 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
580                 pi.pain.text(x, y, label, labelFont);
581                 x += mathed_string_width(labelFont, label);
582
583                 // draw definition
584                 d->definition_.draw(pi, x, y);
585                 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
586                 y += max(fontDim.des, defDim.des);
587
588                 // draw parameters
589                 docstring str = from_ascii("#9");
590                 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
591                 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
592
593                 for (idx_type i = 0; i < nargs(); ++i) {
594                         // position of label
595                         Dimension const & cdim = coords.getArrays().dim(&cell(i));
596                         x = expx + 2;
597                         y += max(fontDim.asc, cdim.asc) + 1;
598
599                         // draw label
600                         str[1] = '1' + i;
601                         pi.pain.text(x, y, str, labelFont);
602                         x += strw1;
603                         pi.pain.text(x, y, from_ascii(":"), labelFont);
604                         x += strw2;
605
606                         // draw paramter
607                         cell(i).draw(pi, x, y);
608
609                         // next line
610                         y += max(fontDim.des, cdim.des);
611                 }
612
613                 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
614                                   dim.height() - 2, Color_mathmacroframe);
615                 drawMarkers2(pi, expx, expy);
616         } else {
617                 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
618                 bool upshape = currentMode() == TEXT_MODE;
619                 Changer dummy = pi.base.font.changeShape(upshape ? UP_SHAPE
620                                                         : pi.base.font.shape());
621
622                 // warm up cells
623                 for (size_t i = 0; i < nargs(); ++i)
624                         cell(i).setXY(*pi.base.bv, x, y);
625
626                 if (drawBox && d->editing_[pi.base.bv]) {
627                         // draw header and rectangle around
628                         FontInfo font = pi.base.font;
629                         augmentFont(font, "lyxtex");
630                         font.setSize(FONT_SIZE_TINY);
631                         font.setColor(Color_mathmacrolabel);
632                         Dimension namedim;
633                         mathed_string_dim(font, name(), namedim);
634
635                         pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
636                         pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
637                         expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
638                 }
639
640                 if (d->editing_[pi.base.bv]) {
641                         pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
642                         d->expanded_.draw(pi, expx, expy);
643                         pi.pain.leaveMonochromeMode();
644
645                         if (drawBox)
646                                 pi.pain.rectangle(x, y - dim.asc, dim.wid,
647                                                   dim.height(), Color_mathmacroframe);
648                 } else
649                         d->expanded_.draw(pi, expx, expy);
650
651                 if (!drawBox)
652                         drawMarkers(pi, x, y);
653         }
654
655         // edit mode changed?
656         if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
657                 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
658 }
659
660
661 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
662 {
663         // We may have 0 arguments, but InsetMathNest requires at least one.
664         if (!cells_.empty())
665                 InsetMathNest::drawSelection(pi, x, y);
666 }
667
668
669 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
670 {
671         if (d->displayMode_ != mode) {
672                 // transfer name if changing from or to DISPLAY_UNFOLDED
673                 if (mode == DISPLAY_UNFOLDED) {
674                         cells_.resize(1);
675                         asArray(d->name_, cell(0));
676                 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
677                         d->name_ = asString(cell(0));
678                         cells_.resize(0);
679                 }
680
681                 d->displayMode_ = mode;
682                 d->needsUpdate_ = true;
683         }
684
685         // the interactive init mode is non-greedy by default
686         if (appetite == -1)
687                 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
688         else
689                 d->appetite_ = size_t(appetite);
690 }
691
692
693 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
694 {
695         if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
696                 return DISPLAY_NORMAL;
697         else
698                 return DISPLAY_UNFOLDED;
699 }
700
701
702 bool MathMacro::validName() const
703 {
704         docstring n = name();
705
706         if (n.empty())
707                 return false;
708
709         // converting back and force doesn't swallow anything?
710         /*MathData ma;
711         asArray(n, ma);
712         if (asString(ma) != n)
713                 return false;*/
714
715         // valid characters?
716         for (size_t i = 0; i<n.size(); ++i) {
717                 if (!(n[i] >= 'a' && n[i] <= 'z')
718                     && !(n[i] >= 'A' && n[i] <= 'Z')
719                     && n[i] != '*')
720                         return false;
721         }
722
723         return true;
724 }
725
726
727 size_t MathMacro::arity() const
728 {
729         if (d->displayMode_ == DISPLAY_NORMAL )
730                 return cells_.size();
731         else
732                 return 0;
733 }
734
735
736 size_t MathMacro::optionals() const
737 {
738         return d->optionals_;
739 }
740
741
742 void MathMacro::setOptionals(int n)
743 {
744         if (n <= int(nargs()))
745                 d->optionals_ = n;
746 }
747
748
749 size_t MathMacro::appetite() const
750 {
751         return d->appetite_;
752 }
753
754
755 InsetMath::mode_type MathMacro::currentMode() const
756 {
757         // User defined macros are always assumed to be mathmode macros.
758         // Only the global macros defined in lib/symbols may be textmode.
759
760         MacroData const * data = MacroTable::globalMacros().get(name());
761         bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
762         return textmode ? TEXT_MODE : MATH_MODE;
763 }
764
765
766 void MathMacro::validate(LaTeXFeatures & features) const
767 {
768         // Immediately after a document is loaded, in some cases the MacroData
769         // of the global macros defined in the lib/symbols file may still not
770         // be known to the macro machinery because it will be set only after
771         // the first call to updateMacros(). This is not a problem unless
772         // instant preview is on for math, in which case we will be missing
773         // the corresponding requirements.
774         // In this case, we get the required info from the global macro table.
775         if (!d->requires_.empty())
776                 features.require(d->requires_);
777         else if (!d->macro_) {
778                 // Update requires for known global macros.
779                 MacroData const * data = MacroTable::globalMacros().get(name());
780                 if (data && !data->requires().empty())
781                         features.require(data->requires());
782         }
783
784         if (name() == "binom")
785                 features.require("binom");
786
787         // validate the cells and the definition
788         if (displayMode() == DISPLAY_NORMAL) {
789                 d->definition_.validate(features);
790                 InsetMathNest::validate(features);
791         }
792 }
793
794
795 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
796 {
797         cur.screenUpdateFlags(Update::SinglePar);
798         InsetMathNest::edit(cur, front, entry_from);
799 }
800
801
802 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
803 {
804         // We may have 0 arguments, but InsetMathNest requires at least one.
805         if (nargs() > 0) {
806                 cur.screenUpdateFlags(Update::SinglePar);
807                 return InsetMathNest::editXY(cur, x, y);
808         } else
809                 return this;
810 }
811
812
813 void MathMacro::removeArgument(Inset::pos_type pos) {
814         if (d->displayMode_ == DISPLAY_NORMAL) {
815                 LASSERT(size_t(pos) < cells_.size(), return);
816                 cells_.erase(cells_.begin() + pos);
817                 if (size_t(pos) < d->attachedArgsNum_)
818                         --d->attachedArgsNum_;
819                 if (size_t(pos) < d->optionals_) {
820                         --d->optionals_;
821                 }
822
823                 d->needsUpdate_ = true;
824         }
825 }
826
827
828 void MathMacro::insertArgument(Inset::pos_type pos) {
829         if (d->displayMode_ == DISPLAY_NORMAL) {
830                 LASSERT(size_t(pos) <= cells_.size(), return);
831                 cells_.insert(cells_.begin() + pos, MathData());
832                 if (size_t(pos) < d->attachedArgsNum_)
833                         ++d->attachedArgsNum_;
834                 if (size_t(pos) < d->optionals_)
835                         ++d->optionals_;
836
837                 d->needsUpdate_ = true;
838         }
839 }
840
841
842 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
843 {
844         LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
845         args = cells_;
846
847         // strip off empty cells, but not more than arity-attachedArgsNum_
848         if (strip) {
849                 size_t i;
850                 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
851                         if (!cell(i - 1).empty()) break;
852                 args.resize(i);
853         }
854
855         d->attachedArgsNum_ = 0;
856         d->expanded_ = MathData();
857         cells_.resize(0);
858
859         d->needsUpdate_ = true;
860 }
861
862
863 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
864 {
865         LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
866         cells_ = args;
867         d->attachedArgsNum_ = args.size();
868         cells_.resize(arity);
869         d->expanded_ = MathData();
870         d->optionals_ = optionals;
871
872         d->needsUpdate_ = true;
873 }
874
875
876 bool MathMacro::idxFirst(Cursor & cur) const
877 {
878         cur.screenUpdateFlags(Update::SinglePar);
879         return InsetMathNest::idxFirst(cur);
880 }
881
882
883 bool MathMacro::idxLast(Cursor & cur) const
884 {
885         cur.screenUpdateFlags(Update::SinglePar);
886         return InsetMathNest::idxLast(cur);
887 }
888
889
890 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
891 {
892         if (d->displayMode_ == DISPLAY_UNFOLDED) {
893                 docstring const & unfolded_name = name();
894                 if (unfolded_name != d->name_) {
895                         // The macro name was changed
896                         Cursor inset_cursor = old;
897                         int macroSlice = inset_cursor.find(this);
898                         // returning true means the cursor is "now" invalid,
899                         // which it was.
900                         LASSERT(macroSlice != -1, return true);
901                         inset_cursor.cutOff(macroSlice);
902                         inset_cursor.recordUndoInset();
903                         inset_cursor.pop();
904                         inset_cursor.cell().erase(inset_cursor.pos());
905                         inset_cursor.cell().insert(inset_cursor.pos(),
906                                 createInsetMath(unfolded_name, cur.buffer()));
907                         cur.resetAnchor();
908                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
909                         return true;
910                 }
911         }
912         cur.screenUpdateFlags(Update::Force);
913         return InsetMathNest::notifyCursorLeaves(old, cur);
914 }
915
916
917 void MathMacro::fold(Cursor & cur)
918 {
919         if (!d->nextFoldMode_) {
920                 d->nextFoldMode_ = true;
921                 cur.screenUpdateFlags(Update::SinglePar);
922         }
923 }
924
925
926 void MathMacro::unfold(Cursor & cur)
927 {
928         if (d->nextFoldMode_) {
929                 d->nextFoldMode_ = false;
930                 cur.screenUpdateFlags(Update::SinglePar);
931         }
932 }
933
934
935 bool MathMacro::folded() const
936 {
937         return d->nextFoldMode_;
938 }
939
940
941 void MathMacro::write(WriteStream & os) const
942 {
943         MacroData const * data = MacroTable::globalMacros().get(name());
944         bool textmode_macro = data && data->symbol()
945                                    && data->symbol()->extra == "textmode";
946         bool needs_mathmode = data && (!data->symbol()
947                                        || data->symbol()->extra != "textmode");
948
949         MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
950
951         // non-normal mode
952         if (d->displayMode_ != DISPLAY_NORMAL) {
953                 os << "\\" << name();
954                 if (name().size() != 1 || isAlphaASCII(name()[0]))
955                         os.pendingSpace(true);
956                 return;
957         }
958
959         // normal mode
960         // we should be ok to continue even if this fails.
961         LATTEST(d->macro_);
962
963         // Always protect macros in a fragile environment
964         if (os.fragile())
965                 os << "\\protect";
966
967         os << "\\" << name();
968         bool first = true;
969
970         // Optional arguments:
971         // First find last non-empty optional argument
972         idx_type emptyOptFrom = 0;
973         idx_type i = 0;
974         for (; i < cells_.size() && i < d->optionals_; ++i) {
975                 if (!cell(i).empty())
976                         emptyOptFrom = i + 1;
977         }
978
979         // print out optionals
980         for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
981                 first = false;
982                 os << "[" << cell(i) << "]";
983         }
984
985         // skip the tailing empty optionals
986         i = d->optionals_;
987
988         // Print remaining arguments
989         for (; i < cells_.size(); ++i) {
990                 if (cell(i).size() == 1
991                         && cell(i)[0].nucleus()->asCharInset()
992                         && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
993                         if (first)
994                                 os << " ";
995                         os << cell(i);
996                 } else
997                         os << "{" << cell(i) << "}";
998                 first = false;
999         }
1000
1001         // add space if there was no argument
1002         if (first)
1003                 os.pendingSpace(true);
1004 }
1005
1006
1007 void MathMacro::maple(MapleStream & os) const
1008 {
1009         lyx::maple(d->expanded_, os);
1010 }
1011
1012
1013 void MathMacro::maxima(MaximaStream & os) const
1014 {
1015         lyx::maxima(d->expanded_, os);
1016 }
1017
1018
1019 void MathMacro::mathematica(MathematicaStream & os) const
1020 {
1021         lyx::mathematica(d->expanded_, os);
1022 }
1023
1024
1025 void MathMacro::mathmlize(MathStream & os) const
1026 {
1027         // macro_ is 0 if this is an unknown macro
1028         LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1029         if (d->macro_) {
1030                 docstring const xmlname = d->macro_->xmlname();
1031                 if (!xmlname.empty()) {
1032                         char const * type = d->macro_->MathMLtype();
1033                         os << '<' << type << "> " << xmlname << " </"
1034                            << type << '>';
1035                         return;
1036                 }
1037         }
1038         if (d->expanded_.empty()) {
1039                 // this means that we do not recognize the macro
1040                 throw MathExportException();
1041         }
1042         os << d->expanded_;
1043 }
1044
1045
1046 void MathMacro::htmlize(HtmlStream & os) const
1047 {
1048         // macro_ is 0 if this is an unknown macro
1049         LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1050         if (d->macro_) {
1051                 docstring const xmlname = d->macro_->xmlname();
1052                 if (!xmlname.empty()) {
1053                         os << ' ' << xmlname << ' ';
1054                         return;
1055                 }
1056         }
1057         if (d->expanded_.empty()) {
1058                 // this means that we do not recognize the macro
1059                 throw MathExportException();
1060         }
1061         os << d->expanded_;
1062 }
1063
1064
1065 void MathMacro::octave(OctaveStream & os) const
1066 {
1067         lyx::octave(d->expanded_, os);
1068 }
1069
1070
1071 void MathMacro::infoize(odocstream & os) const
1072 {
1073         os << bformat(_("Macro: %1$s"), name());
1074 }
1075
1076
1077 void MathMacro::infoize2(odocstream & os) const
1078 {
1079         os << bformat(_("Macro: %1$s"), name());
1080 }
1081
1082
1083 bool MathMacro::completionSupported(Cursor const & cur) const
1084 {
1085         if (displayMode() != DISPLAY_UNFOLDED)
1086                 return InsetMathNest::completionSupported(cur);
1087
1088         return lyxrc.completion_popup_math
1089                 && displayMode() == DISPLAY_UNFOLDED
1090                 && cur.bv().cursor().pos() == int(name().size());
1091 }
1092
1093
1094 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1095 {
1096         if (displayMode() != DISPLAY_UNFOLDED)
1097                 return InsetMathNest::inlineCompletionSupported(cur);
1098
1099         return lyxrc.completion_inline_math
1100                 && displayMode() == DISPLAY_UNFOLDED
1101                 && cur.bv().cursor().pos() == int(name().size());
1102 }
1103
1104
1105 bool MathMacro::automaticInlineCompletion() const
1106 {
1107         if (displayMode() != DISPLAY_UNFOLDED)
1108                 return InsetMathNest::automaticInlineCompletion();
1109
1110         return lyxrc.completion_inline_math;
1111 }
1112
1113
1114 bool MathMacro::automaticPopupCompletion() const
1115 {
1116         if (displayMode() != DISPLAY_UNFOLDED)
1117                 return InsetMathNest::automaticPopupCompletion();
1118
1119         return lyxrc.completion_popup_math;
1120 }
1121
1122
1123 CompletionList const *
1124 MathMacro::createCompletionList(Cursor const & cur) const
1125 {
1126         if (displayMode() != DISPLAY_UNFOLDED)
1127                 return InsetMathNest::createCompletionList(cur);
1128
1129         return new MathCompletionList(cur.bv().cursor());
1130 }
1131
1132
1133 docstring MathMacro::completionPrefix(Cursor const & cur) const
1134 {
1135         if (displayMode() != DISPLAY_UNFOLDED)
1136                 return InsetMathNest::completionPrefix(cur);
1137
1138         if (!completionSupported(cur))
1139                 return docstring();
1140
1141         return "\\" + name();
1142 }
1143
1144
1145 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1146                                         bool finished)
1147 {
1148         if (displayMode() != DISPLAY_UNFOLDED)
1149                 return InsetMathNest::insertCompletion(cur, s, finished);
1150
1151         if (!completionSupported(cur))
1152                 return false;
1153
1154         // append completion
1155         docstring newName = name() + s;
1156         asArray(newName, cell(0));
1157         cur.bv().cursor().pos() = name().size();
1158         cur.screenUpdateFlags(Update::SinglePar);
1159
1160         // finish macro
1161         if (finished) {
1162                 cur.bv().cursor().pop();
1163                 ++cur.bv().cursor().pos();
1164                 cur.screenUpdateFlags(Update::SinglePar);
1165         }
1166
1167         return true;
1168 }
1169
1170
1171 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1172         Dimension & dim) const
1173 {
1174         if (displayMode() != DISPLAY_UNFOLDED)
1175                 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1176
1177         // get inset dimensions
1178         dim = cur.bv().coordCache().insets().dim(this);
1179         // FIXME: these 3 are no accurate, but should depend on the font.
1180         // Now the popup jumps down if you enter a char with descent > 0.
1181         dim.des += 3;
1182         dim.asc += 3;
1183
1184         // and position
1185         Point xy
1186         = cur.bv().coordCache().insets().xy(this);
1187         x = xy.x_;
1188         y = xy.y_;
1189 }
1190
1191
1192 } // namespace lyx