]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacro.cpp
Merge branch 'betterspacing'
[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                 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
460         } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
461                 cell(0).metrics(mi, dim);
462                 Dimension bsdim;
463                 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
464                 dim.wid += bsdim.width() + 1;
465                 dim.asc = max(bsdim.ascent(), dim.ascent());
466                 dim.des = max(bsdim.descent(), dim.descent());
467                 metricsMarkers(mi, dim);
468         } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
469                    && d->editing_[mi.base.bv]) {
470                 // Macro will be edited in a old-style list mode here:
471
472                 LBUFERR(d->macro_);
473                 Dimension fontDim;
474                 FontInfo labelFont = sane_font;
475                 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
476
477                 // get dimension of components of list view
478                 Dimension nameDim;
479                 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
480                 nameDim.asc = fontDim.asc;
481                 nameDim.des = fontDim.des;
482
483                 Dimension argDim;
484                 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
485                 argDim.asc = fontDim.asc;
486                 argDim.des = fontDim.des;
487
488                 Dimension defDim;
489                 d->definition_.metrics(mi, defDim);
490
491                 // add them up
492                 dim.wid = nameDim.wid + defDim.wid;
493                 dim.asc = max(nameDim.asc, defDim.asc);
494                 dim.des = max(nameDim.des, defDim.des);
495
496                 for (idx_type i = 0; i < nargs(); ++i) {
497                         Dimension cdim;
498                         cell(i).metrics(mi, cdim);
499                         dim.des += max(argDim.height(), cdim.height()) + 1;
500                         dim.wid = max(dim.wid, argDim.wid + cdim.wid);
501                 }
502
503                 // make space for box and markers, 2 pixels
504                 dim.asc += 1;
505                 dim.des += 1;
506                 dim.wid += 2;
507                 metricsMarkers2(mi, dim);
508         } else {
509                 LBUFERR(d->macro_);
510
511                 // calculate metrics, hoping that all cells are seen
512                 d->macro_->lock();
513                 d->expanded_.metrics(mi, dim);
514
515                 // otherwise do a manual metrics call
516                 CoordCache & coords = mi.base.bv->coordCache();
517                 for (idx_type i = 0; i < nargs(); ++i) {
518                         if (!coords.getArrays().hasDim(&cell(i))) {
519                                 Dimension tdim;
520                                 cell(i).metrics(mi, tdim);
521                         }
522                 }
523                 d->macro_->unlock();
524
525                 // calculate dimension with label while editing
526                 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
527                     && d->editing_[mi.base.bv]) {
528                         FontInfo font = mi.base.font;
529                         augmentFont(font, "lyxtex");
530                         Dimension namedim;
531                         mathed_string_dim(font, name(), namedim);
532 #if 0
533                         dim.wid += 2 + namedim.wid + 2 + 2;
534                         dim.asc = max(dim.asc, namedim.asc) + 2;
535                         dim.des = max(dim.des, namedim.des) + 2;
536 #endif
537                         dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
538                         dim.asc += 1 + namedim.height() + 1;
539                         dim.des += 2;
540                 }
541         }
542
543         // restore macro nesting
544         --mi.base.macro_nesting;
545 }
546
547
548 int MathMacro::kerning(BufferView const * bv) const {
549         if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
550                 return d->expanded_.kerning(bv);
551         else
552                 return 0;
553 }
554
555
556 void MathMacro::updateMacro(MacroContext const & mc)
557 {
558         if (validName()) {
559                 d->macro_ = mc.get(name());
560                 if (d->macro_ && d->macroBackup_ != *d->macro_) {
561                         d->macroBackup_ = *d->macro_;
562                         d->needsUpdate_ = true;
563                 }
564         } else {
565                 d->macro_ = 0;
566         }
567 }
568
569
570 class MathMacro::UpdateLocker
571 {
572 public:
573         explicit UpdateLocker(MathMacro & mm) : mac(mm)
574         {
575                 mac.d->isUpdating_ = true;
576         }
577         ~UpdateLocker() { mac.d->isUpdating_ = false; }
578 private:
579         MathMacro & mac;
580 };
581 /** Avoid wrong usage of UpdateLocker.
582     To avoid wrong usage:
583     UpdateLocker(...); // wrong
584     UpdateLocker locker(...); // right
585 */
586 #define UpdateLocker(x) unnamed_UpdateLocker;
587 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
588
589
590 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
591                 UpdateType utype)
592 {
593         // block recursive calls (bug 8999)
594         if (d->isUpdating_)
595                 return;
596
597         UpdateLocker locker(*this);
598
599         // known macro?
600         if (d->macro_ == 0)
601                 return;
602
603         // update requires
604         d->requires_ = d->macro_->requires();
605
606         if (!d->needsUpdate_
607                 // non-normal mode? We are done!
608                 || (d->displayMode_ != DISPLAY_NORMAL))
609                 return;
610
611         d->needsUpdate_ = false;
612
613         // get default values of macro
614         vector<docstring> const & defaults = d->macro_->defaults();
615
616         // create MathMacroArgumentValue objects pointing to the cells of the macro
617         vector<MathData> values(nargs());
618         for (size_t i = 0; i < nargs(); ++i) {
619                 ArgumentProxy * proxy;
620                 if (i < defaults.size())
621                         proxy = new ArgumentProxy(this, i, defaults[i]);
622                 else
623                         proxy = new ArgumentProxy(this, i);
624                 values[i].insert(0, MathAtom(proxy));
625         }
626         // expanding macro with the values
627         // Only update the argument macros if anything was expanded, otherwise
628         // we would get an endless loop (bug 9140). UpdateLocker does not work
629         // in this case, since MacroData::expand() creates new MathMacro
630         // objects, so this would be a different recursion path than the one
631         // protected by UpdateLocker.
632         if (d->macro_->expand(values, d->expanded_)) {
633                 if (utype == OutputUpdate && !d->expanded_.empty())
634                         d->expanded_.updateMacros(cur, mc, utype);
635         }
636         // get definition for list edit mode
637         docstring const & display = d->macro_->display();
638         asArray(display.empty() ? d->macro_->definition() : display,
639                 d->definition_, Parse::QUIET);
640 }
641
642
643 void MathMacro::draw(PainterInfo & pi, int x, int y) const
644 {
645         Dimension const dim = dimension(*pi.base.bv);
646
647         setPosCache(pi, x, y);
648         int expx = x;
649         int expy = y;
650
651         if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
652                 Changer dummy = pi.base.changeFontSet("lyxtex");
653                 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
654         } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
655                 Changer dummy = pi.base.changeFontSet("lyxtex");
656                 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
657                 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
658                 cell(0).draw(pi, x, y);
659                 drawMarkers(pi, expx, expy);
660         } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
661                    && d->editing_[pi.base.bv]) {
662                 // Macro will be edited in a old-style list mode here:
663
664                 CoordCache const & coords = pi.base.bv->coordCache();
665                 FontInfo const & labelFont = sane_font;
666
667                 // markers and box needs two pixels
668                 x += 2;
669
670                 // get maximal font height
671                 Dimension fontDim;
672                 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
673
674                 // draw label
675                 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
676                 pi.pain.text(x, y, label, labelFont);
677                 x += mathed_string_width(labelFont, label);
678
679                 // draw definition
680                 d->definition_.draw(pi, x, y);
681                 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
682                 y += max(fontDim.des, defDim.des);
683
684                 // draw parameters
685                 docstring str = from_ascii("#9");
686                 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
687                 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
688
689                 for (idx_type i = 0; i < nargs(); ++i) {
690                         // position of label
691                         Dimension const & cdim = coords.getArrays().dim(&cell(i));
692                         x = expx + 2;
693                         y += max(fontDim.asc, cdim.asc) + 1;
694
695                         // draw label
696                         str[1] = '1' + i;
697                         pi.pain.text(x, y, str, labelFont);
698                         x += strw1;
699                         pi.pain.text(x, y, from_ascii(":"), labelFont);
700                         x += strw2;
701
702                         // draw paramter
703                         cell(i).draw(pi, x, y);
704
705                         // next line
706                         y += max(fontDim.des, cdim.des);
707                 }
708
709                 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
710                                   dim.height() - 2, Color_mathmacroframe);
711                 drawMarkers2(pi, expx, expy);
712         } else {
713                 // the macro contents is not editable (except the arguments)
714                 ++pi.base.macro_nesting;
715
716                 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
717                 bool upshape = currentMode() == TEXT_MODE;
718                 Changer dummy = pi.base.font.changeShape(upshape ? UP_SHAPE
719                                                         : pi.base.font.shape());
720
721                 // warm up cells
722                 for (size_t i = 0; i < nargs(); ++i)
723                         cell(i).setXY(*pi.base.bv, x, y);
724
725                 if (drawBox && d->editing_[pi.base.bv]) {
726                         // draw header and rectangle around
727                         FontInfo font = pi.base.font;
728                         augmentFont(font, "lyxtex");
729                         font.setSize(FONT_SIZE_TINY);
730                         font.setColor(Color_mathmacrolabel);
731                         Dimension namedim;
732                         mathed_string_dim(font, name(), namedim);
733
734                         pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
735                         pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
736                         expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
737                 }
738
739                 if (d->editing_[pi.base.bv]) {
740                         pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
741                         d->expanded_.draw(pi, expx, expy);
742                         pi.pain.leaveMonochromeMode();
743
744                         if (drawBox)
745                                 pi.pain.rectangle(x, y - dim.asc, dim.wid,
746                                                   dim.height(), Color_mathmacroframe);
747                 } else
748                         d->expanded_.draw(pi, expx, expy);
749
750                 --pi.base.macro_nesting;
751
752                 if (!drawBox)
753                         drawMarkers(pi, x, y);
754
755         }
756
757         // edit mode changed?
758         if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
759                 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
760 }
761
762
763 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
764 {
765         // We may have 0 arguments, but InsetMathNest requires at least one.
766         if (!cells_.empty())
767                 InsetMathNest::drawSelection(pi, x, y);
768 }
769
770
771 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
772 {
773         if (d->displayMode_ != mode) {
774                 // transfer name if changing from or to DISPLAY_UNFOLDED
775                 if (mode == DISPLAY_UNFOLDED) {
776                         cells_.resize(1);
777                         asArray(d->name_, cell(0));
778                 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
779                         d->name_ = asString(cell(0));
780                         cells_.resize(0);
781                 }
782
783                 d->displayMode_ = mode;
784                 d->needsUpdate_ = true;
785         }
786
787         // the interactive init mode is non-greedy by default
788         if (appetite == -1)
789                 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
790         else
791                 d->appetite_ = size_t(appetite);
792 }
793
794
795 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
796 {
797         if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
798                 return DISPLAY_NORMAL;
799         else
800                 return DISPLAY_UNFOLDED;
801 }
802
803
804 bool MathMacro::validName() const
805 {
806         docstring n = name();
807
808         if (n.empty())
809                 return false;
810
811         // converting back and force doesn't swallow anything?
812         /*MathData ma;
813         asArray(n, ma);
814         if (asString(ma) != n)
815                 return false;*/
816
817         // valid characters?
818         for (size_t i = 0; i<n.size(); ++i) {
819                 if (!(n[i] >= 'a' && n[i] <= 'z')
820                     && !(n[i] >= 'A' && n[i] <= 'Z')
821                     && n[i] != '*')
822                         return false;
823         }
824
825         return true;
826 }
827
828
829 size_t MathMacro::arity() const
830 {
831         if (d->displayMode_ == DISPLAY_NORMAL )
832                 return cells_.size();
833         else
834                 return 0;
835 }
836
837
838 size_t MathMacro::optionals() const
839 {
840         return d->optionals_;
841 }
842
843
844 void MathMacro::setOptionals(int n)
845 {
846         if (n <= int(nargs()))
847                 d->optionals_ = n;
848 }
849
850
851 size_t MathMacro::appetite() const
852 {
853         return d->appetite_;
854 }
855
856
857 InsetMath::mode_type MathMacro::currentMode() const
858 {
859         // User defined macros are always assumed to be mathmode macros.
860         // Only the global macros defined in lib/symbols may be textmode.
861
862         MacroData const * data = MacroTable::globalMacros().get(name());
863         bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
864         return textmode ? TEXT_MODE : MATH_MODE;
865 }
866
867
868 void MathMacro::validate(LaTeXFeatures & features) const
869 {
870         // Immediately after a document is loaded, in some cases the MacroData
871         // of the global macros defined in the lib/symbols file may still not
872         // be known to the macro machinery because it will be set only after
873         // the first call to updateMacros(). This is not a problem unless
874         // instant preview is on for math, in which case we will be missing
875         // the corresponding requirements.
876         // In this case, we get the required info from the global macro table.
877         if (!d->requires_.empty())
878                 features.require(d->requires_);
879         else if (!d->macro_) {
880                 // Update requires for known global macros.
881                 MacroData const * data = MacroTable::globalMacros().get(name());
882                 if (data && !data->requires().empty())
883                         features.require(data->requires());
884         }
885
886         if (name() == "binom")
887                 features.require("binom");
888
889         // validate the cells and the definition
890         if (displayMode() == DISPLAY_NORMAL) {
891                 d->definition_.validate(features);
892                 InsetMathNest::validate(features);
893         }
894 }
895
896
897 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
898 {
899         cur.screenUpdateFlags(Update::SinglePar);
900         InsetMathNest::edit(cur, front, entry_from);
901 }
902
903
904 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
905 {
906         // We may have 0 arguments, but InsetMathNest requires at least one.
907         if (nargs() > 0) {
908                 cur.screenUpdateFlags(Update::SinglePar);
909                 return InsetMathNest::editXY(cur, x, y);
910         } else
911                 return this;
912 }
913
914
915 void MathMacro::removeArgument(Inset::pos_type pos) {
916         if (d->displayMode_ == DISPLAY_NORMAL) {
917                 LASSERT(size_t(pos) < cells_.size(), return);
918                 cells_.erase(cells_.begin() + pos);
919                 if (size_t(pos) < d->attachedArgsNum_)
920                         --d->attachedArgsNum_;
921                 if (size_t(pos) < d->optionals_) {
922                         --d->optionals_;
923                 }
924
925                 d->needsUpdate_ = true;
926         }
927 }
928
929
930 void MathMacro::insertArgument(Inset::pos_type pos) {
931         if (d->displayMode_ == DISPLAY_NORMAL) {
932                 LASSERT(size_t(pos) <= cells_.size(), return);
933                 cells_.insert(cells_.begin() + pos, MathData());
934                 if (size_t(pos) < d->attachedArgsNum_)
935                         ++d->attachedArgsNum_;
936                 if (size_t(pos) < d->optionals_)
937                         ++d->optionals_;
938
939                 d->needsUpdate_ = true;
940         }
941 }
942
943
944 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
945 {
946         LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
947         args = cells_;
948
949         // strip off empty cells, but not more than arity-attachedArgsNum_
950         if (strip) {
951                 size_t i;
952                 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
953                         if (!cell(i - 1).empty()) break;
954                 args.resize(i);
955         }
956
957         d->attachedArgsNum_ = 0;
958         d->expanded_ = MathData();
959         cells_.resize(0);
960
961         d->needsUpdate_ = true;
962 }
963
964
965 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
966 {
967         LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
968         cells_ = args;
969         d->attachedArgsNum_ = args.size();
970         cells_.resize(arity);
971         d->expanded_ = MathData();
972         d->optionals_ = optionals;
973
974         d->needsUpdate_ = true;
975 }
976
977
978 bool MathMacro::idxFirst(Cursor & cur) const
979 {
980         cur.screenUpdateFlags(Update::SinglePar);
981         return InsetMathNest::idxFirst(cur);
982 }
983
984
985 bool MathMacro::idxLast(Cursor & cur) const
986 {
987         cur.screenUpdateFlags(Update::SinglePar);
988         return InsetMathNest::idxLast(cur);
989 }
990
991
992 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
993 {
994         if (d->displayMode_ == DISPLAY_UNFOLDED) {
995                 docstring const & unfolded_name = name();
996                 if (unfolded_name != d->name_) {
997                         // The macro name was changed
998                         Cursor inset_cursor = old;
999                         int macroSlice = inset_cursor.find(this);
1000                         // returning true means the cursor is "now" invalid,
1001                         // which it was.
1002                         LASSERT(macroSlice != -1, return true);
1003                         inset_cursor.cutOff(macroSlice);
1004                         inset_cursor.recordUndoInset();
1005                         inset_cursor.pop();
1006                         inset_cursor.cell().erase(inset_cursor.pos());
1007                         inset_cursor.cell().insert(inset_cursor.pos(),
1008                                 createInsetMath(unfolded_name, cur.buffer()));
1009                         cur.resetAnchor();
1010                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1011                         return true;
1012                 }
1013         }
1014         cur.screenUpdateFlags(Update::Force);
1015         return InsetMathNest::notifyCursorLeaves(old, cur);
1016 }
1017
1018
1019 void MathMacro::fold(Cursor & cur)
1020 {
1021         if (!d->nextFoldMode_) {
1022                 d->nextFoldMode_ = true;
1023                 cur.screenUpdateFlags(Update::SinglePar);
1024         }
1025 }
1026
1027
1028 void MathMacro::unfold(Cursor & cur)
1029 {
1030         if (d->nextFoldMode_) {
1031                 d->nextFoldMode_ = false;
1032                 cur.screenUpdateFlags(Update::SinglePar);
1033         }
1034 }
1035
1036
1037 bool MathMacro::folded() const
1038 {
1039         return d->nextFoldMode_;
1040 }
1041
1042
1043 void MathMacro::write(WriteStream & os) const
1044 {
1045         MacroData const * data = MacroTable::globalMacros().get(name());
1046         bool textmode_macro = data && data->symbol()
1047                                    && data->symbol()->extra == "textmode";
1048         bool needs_mathmode = data && (!data->symbol()
1049                                        || data->symbol()->extra != "textmode");
1050
1051         MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1052
1053         // non-normal mode
1054         if (d->displayMode_ != DISPLAY_NORMAL) {
1055                 os << "\\" << name();
1056                 if (name().size() != 1 || isAlphaASCII(name()[0]))
1057                         os.pendingSpace(true);
1058                 return;
1059         }
1060
1061         // normal mode
1062         // we should be ok to continue even if this fails.
1063         LATTEST(d->macro_);
1064
1065         // Always protect macros in a fragile environment
1066         if (os.fragile())
1067                 os << "\\protect";
1068
1069         os << "\\" << name();
1070         bool first = true;
1071
1072         // Optional arguments:
1073         // First find last non-empty optional argument
1074         idx_type emptyOptFrom = 0;
1075         idx_type i = 0;
1076         for (; i < cells_.size() && i < d->optionals_; ++i) {
1077                 if (!cell(i).empty())
1078                         emptyOptFrom = i + 1;
1079         }
1080
1081         // print out optionals
1082         for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1083                 first = false;
1084                 os << "[" << cell(i) << "]";
1085         }
1086
1087         // skip the tailing empty optionals
1088         i = d->optionals_;
1089
1090         // Print remaining arguments
1091         for (; i < cells_.size(); ++i) {
1092                 if (cell(i).size() == 1
1093                         && cell(i)[0].nucleus()->asCharInset()
1094                         && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1095                         if (first)
1096                                 os << " ";
1097                         os << cell(i);
1098                 } else
1099                         os << "{" << cell(i) << "}";
1100                 first = false;
1101         }
1102
1103         // add space if there was no argument
1104         if (first)
1105                 os.pendingSpace(true);
1106 }
1107
1108
1109 void MathMacro::maple(MapleStream & os) const
1110 {
1111         lyx::maple(d->expanded_, os);
1112 }
1113
1114
1115 void MathMacro::maxima(MaximaStream & os) const
1116 {
1117         lyx::maxima(d->expanded_, os);
1118 }
1119
1120
1121 void MathMacro::mathematica(MathematicaStream & os) const
1122 {
1123         lyx::mathematica(d->expanded_, os);
1124 }
1125
1126
1127 void MathMacro::mathmlize(MathStream & os) const
1128 {
1129         // macro_ is 0 if this is an unknown macro
1130         LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1131         if (d->macro_) {
1132                 docstring const xmlname = d->macro_->xmlname();
1133                 if (!xmlname.empty()) {
1134                         char const * type = d->macro_->MathMLtype();
1135                         os << '<' << type << "> " << xmlname << " </"
1136                            << type << '>';
1137                         return;
1138                 }
1139         }
1140         if (d->expanded_.empty()) {
1141                 // this means that we do not recognize the macro
1142                 throw MathExportException();
1143         }
1144         os << d->expanded_;
1145 }
1146
1147
1148 void MathMacro::htmlize(HtmlStream & os) const
1149 {
1150         // macro_ is 0 if this is an unknown macro
1151         LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1152         if (d->macro_) {
1153                 docstring const xmlname = d->macro_->xmlname();
1154                 if (!xmlname.empty()) {
1155                         os << ' ' << xmlname << ' ';
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::octave(OctaveStream & os) const
1168 {
1169         lyx::octave(d->expanded_, os);
1170 }
1171
1172
1173 void MathMacro::infoize(odocstream & os) const
1174 {
1175         os << bformat(_("Macro: %1$s"), name());
1176 }
1177
1178
1179 void MathMacro::infoize2(odocstream & os) const
1180 {
1181         os << bformat(_("Macro: %1$s"), name());
1182 }
1183
1184
1185 bool MathMacro::completionSupported(Cursor const & cur) const
1186 {
1187         if (displayMode() != DISPLAY_UNFOLDED)
1188                 return InsetMathNest::completionSupported(cur);
1189
1190         return lyxrc.completion_popup_math
1191                 && displayMode() == DISPLAY_UNFOLDED
1192                 && cur.bv().cursor().pos() == int(name().size());
1193 }
1194
1195
1196 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1197 {
1198         if (displayMode() != DISPLAY_UNFOLDED)
1199                 return InsetMathNest::inlineCompletionSupported(cur);
1200
1201         return lyxrc.completion_inline_math
1202                 && displayMode() == DISPLAY_UNFOLDED
1203                 && cur.bv().cursor().pos() == int(name().size());
1204 }
1205
1206
1207 bool MathMacro::automaticInlineCompletion() const
1208 {
1209         if (displayMode() != DISPLAY_UNFOLDED)
1210                 return InsetMathNest::automaticInlineCompletion();
1211
1212         return lyxrc.completion_inline_math;
1213 }
1214
1215
1216 bool MathMacro::automaticPopupCompletion() const
1217 {
1218         if (displayMode() != DISPLAY_UNFOLDED)
1219                 return InsetMathNest::automaticPopupCompletion();
1220
1221         return lyxrc.completion_popup_math;
1222 }
1223
1224
1225 CompletionList const *
1226 MathMacro::createCompletionList(Cursor const & cur) const
1227 {
1228         if (displayMode() != DISPLAY_UNFOLDED)
1229                 return InsetMathNest::createCompletionList(cur);
1230
1231         return new MathCompletionList(cur.bv().cursor());
1232 }
1233
1234
1235 docstring MathMacro::completionPrefix(Cursor const & cur) const
1236 {
1237         if (displayMode() != DISPLAY_UNFOLDED)
1238                 return InsetMathNest::completionPrefix(cur);
1239
1240         if (!completionSupported(cur))
1241                 return docstring();
1242
1243         return "\\" + name();
1244 }
1245
1246
1247 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1248                                         bool finished)
1249 {
1250         if (displayMode() != DISPLAY_UNFOLDED)
1251                 return InsetMathNest::insertCompletion(cur, s, finished);
1252
1253         if (!completionSupported(cur))
1254                 return false;
1255
1256         // append completion
1257         docstring newName = name() + s;
1258         asArray(newName, cell(0));
1259         cur.bv().cursor().pos() = name().size();
1260         cur.screenUpdateFlags(Update::SinglePar);
1261
1262         // finish macro
1263         if (finished) {
1264                 cur.bv().cursor().pop();
1265                 ++cur.bv().cursor().pos();
1266                 cur.screenUpdateFlags(Update::SinglePar);
1267         }
1268
1269         return true;
1270 }
1271
1272
1273 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1274         Dimension & dim) const
1275 {
1276         if (displayMode() != DISPLAY_UNFOLDED)
1277                 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1278
1279         // get inset dimensions
1280         dim = cur.bv().coordCache().insets().dim(this);
1281         // FIXME: these 3 are no accurate, but should depend on the font.
1282         // Now the popup jumps down if you enter a char with descent > 0.
1283         dim.des += 3;
1284         dim.asc += 3;
1285
1286         // and position
1287         Point xy
1288         = cur.bv().coordCache().insets().xy(this);
1289         x = xy.x_;
1290         y = xy.y_;
1291 }
1292
1293
1294 } // namespace lyx