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