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