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