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