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