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