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