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