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