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