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