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