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