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