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