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