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