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