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