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