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