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