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