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