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