]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacro.cpp
Better fix for bug #8679
[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
296 int MathMacro::kerning(BufferView const * bv) const {
297         if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
298                 return expanded_.kerning(bv);
299         else
300                 return 0;
301 }
302
303
304 void MathMacro::updateMacro(MacroContext const & mc) 
305 {
306         if (validName()) {
307                 macro_ = mc.get(name());    
308                 if (macro_ && macroBackup_ != *macro_) {
309                         macroBackup_ = *macro_;
310                         needsUpdate_ = true;
311                 }
312         } else {
313                 macro_ = 0;
314         }
315 }
316
317
318 class MathMacro::UpdateLocker
319 {
320 public:
321         explicit UpdateLocker(MathMacro & mm) : mac(mm)
322         {
323                 mac.isUpdating_ = true;
324         }
325         ~UpdateLocker() { mac.isUpdating_ = false; }
326 private:
327         MathMacro & mac;
328 };
329 /** Avoid wrong usage of UpdateLocker.
330     To avoid wrong usage:
331     UpdateLocker(...); // wrong
332     UpdateLocker locker(...); // right
333 */
334 #define UpdateLocker(x) unnamed_UpdateLocker;
335 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
336
337
338 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
339                 UpdateType utype)
340 {
341         // block recursive calls (bug 8999)
342         if (isUpdating_)
343                 return;
344
345         UpdateLocker locker(*this);
346
347         // known macro?
348         if (macro_ == 0)
349                 return;
350
351         // update requires
352         requires_ = macro_->requires();
353         
354         if (!needsUpdate_
355                 // non-normal mode? We are done!
356                 || (displayMode_ != DISPLAY_NORMAL))
357                 return;
358
359         needsUpdate_ = false;
360         
361         // get default values of macro
362         vector<docstring> const & defaults = macro_->defaults();
363         
364         // create MathMacroArgumentValue objects pointing to the cells of the macro
365         vector<MathData> values(nargs());
366         for (size_t i = 0; i < nargs(); ++i) {
367                 ArgumentProxy * proxy;
368                 if (i < defaults.size()) 
369                         proxy = new ArgumentProxy(*this, i, defaults[i]);
370                 else
371                         proxy = new ArgumentProxy(*this, i);
372                 values[i].insert(0, MathAtom(proxy));
373         }
374         // expanding macro with the values
375         // Only update the argument macros if anything was expanded, otherwise
376         // we would get an endless loop (bug 9140). UpdateLocker does not work
377         // in this case, since MacroData::expand() creates new MathMacro
378         // objects, so this would be a different recursion path than the one
379         // protected by UpdateLocker.
380         if (macro_->expand(values, expanded_.cell(0))) {
381                 if (utype == OutputUpdate && !expanded_.cell(0).empty())
382                         expanded_.cell(0).updateMacros(cur, mc, utype);
383         }
384         // get definition for list edit mode
385         docstring const & display = macro_->display();
386         asArray(display.empty() ? macro_->definition() : display, definition_);
387 }
388
389
390 void MathMacro::draw(PainterInfo & pi, int x, int y) const
391 {
392         Dimension const dim = dimension(*pi.base.bv);
393
394         setPosCache(pi, x, y);
395         int expx = x;
396         int expy = y;
397
398         if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {         
399                 FontSetChanger dummy(pi.base, "lyxtex");
400                 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
401         } else if (displayMode_ == DISPLAY_UNFOLDED) {
402                 FontSetChanger dummy(pi.base, "lyxtex");
403                 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
404                 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
405                 cell(0).draw(pi, x, y);
406                 drawMarkers(pi, expx, expy);
407         } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
408                    && editing_[pi.base.bv]) {
409                 // Macro will be edited in a old-style list mode here:
410                 
411                 CoordCache const & coords = pi.base.bv->coordCache();
412                 FontInfo const & labelFont = sane_font;
413                 
414                 // markers and box needs two pixels
415                 x += 2;
416                 
417                 // get maximal font height
418                 Dimension fontDim;
419                 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
420                 
421                 // draw label
422                 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
423                 pi.pain.text(x, y, label, labelFont);
424                 x += mathed_string_width(labelFont, label);
425
426                 // draw definition
427                 definition_.draw(pi, x, y);
428                 Dimension const & defDim = coords.getArrays().dim(&definition_);
429                 y += max(fontDim.des, defDim.des);
430                                 
431                 // draw parameters
432                 docstring str = from_ascii("#9");
433                 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
434                 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
435                 
436                 for (idx_type i = 0; i < nargs(); ++i) {
437                         // position of label
438                         Dimension const & cdim = coords.getArrays().dim(&cell(i));
439                         x = expx + 2;
440                         y += max(fontDim.asc, cdim.asc) + 1;
441                         
442                         // draw label
443                         str[1] = '1' + i;
444                         pi.pain.text(x, y, str, labelFont);
445                         x += strw1;
446                         pi.pain.text(x, y, from_ascii(":"), labelFont);
447                         x += strw2;
448                         
449                         // draw paramter
450                         cell(i).draw(pi, x, y);
451                         
452                         // next line
453                         y += max(fontDim.des, cdim.des);
454                 }
455                 
456                 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3, 
457                                   dim.height() - 2, Color_mathmacroframe);
458                 drawMarkers2(pi, expx, expy);
459         } else {
460                 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
461                 
462                 // warm up cells
463                 for (size_t i = 0; i < nargs(); ++i)
464                         cell(i).setXY(*pi.base.bv, x, y);
465
466                 if (drawBox && editing_[pi.base.bv]) {
467                         // draw header and rectangle around
468                         FontInfo font = pi.base.font;
469                         augmentFont(font, from_ascii("lyxtex"));
470                         font.setSize(FONT_SIZE_TINY);
471                         font.setColor(Color_mathmacrolabel);
472                         Dimension namedim;
473                         mathed_string_dim(font, name(), namedim);
474
475                         pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
476                         pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
477                         expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
478                 }
479
480                 if (editing_[pi.base.bv]) {
481                         pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
482                         expanded_.cell(0).draw(pi, expx, expy);
483                         pi.pain.leaveMonochromeMode();
484
485                         if (drawBox)
486                                 pi.pain.rectangle(x, y - dim.asc, dim.wid, 
487                                                   dim.height(), Color_mathmacroframe);
488                 } else
489                         expanded_.cell(0).draw(pi, expx, expy);
490
491                 if (!drawBox)
492                         drawMarkers(pi, x, y);
493         }
494
495         // edit mode changed?
496         if (editing_[pi.base.bv] != editMode(pi.base.bv))
497                 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
498 }
499
500
501 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
502 {
503         // We may have 0 arguments, but InsetMathNest requires at least one.
504         if (!cells_.empty())
505                 InsetMathNest::drawSelection(pi, x, y);
506 }
507
508
509 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
510 {
511         if (displayMode_ != mode) {             
512                 // transfer name if changing from or to DISPLAY_UNFOLDED
513                 if (mode == DISPLAY_UNFOLDED) {
514                         cells_.resize(1);
515                         asArray(name_, cell(0));
516                 } else if (displayMode_ == DISPLAY_UNFOLDED) {
517                         name_ = asString(cell(0));
518                         cells_.resize(0);
519                 }
520
521                 displayMode_ = mode;
522                 needsUpdate_ = true;
523         }
524         
525         // the interactive init mode is non-greedy by default
526         if (appetite == -1)
527                 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
528         else
529                 appetite_ = size_t(appetite);
530 }
531
532
533 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
534 {
535         if (nextFoldMode_ == true && macro_ && !macro_->locked())
536                 return DISPLAY_NORMAL;
537         else
538                 return DISPLAY_UNFOLDED;
539 }
540
541
542 bool MathMacro::validName() const
543 {
544         docstring n = name();
545
546         if (n.empty())
547                 return false;
548
549         // converting back and force doesn't swallow anything?
550         /*MathData ma;
551         asArray(n, ma);
552         if (asString(ma) != n)
553                 return false;*/
554
555         // valid characters?
556         for (size_t i = 0; i<n.size(); ++i) {
557                 if (!(n[i] >= 'a' && n[i] <= 'z')
558                     && !(n[i] >= 'A' && n[i] <= 'Z')
559                     && n[i] != '*') 
560                         return false;
561         }
562
563         return true;
564 }
565
566
567 void MathMacro::validate(LaTeXFeatures & features) const
568 {
569         if (!requires_.empty())
570                 features.require(requires_);
571
572         if (name() == "binom")
573                 features.require("binom");
574         
575         // validate the cells and the definition
576         if (displayMode() == DISPLAY_NORMAL) {
577                 definition_.validate(features);
578                 InsetMathNest::validate(features);
579         }
580 }
581
582
583 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
584 {
585         cur.screenUpdateFlags(Update::SinglePar);
586         InsetMathNest::edit(cur, front, entry_from);
587 }
588
589
590 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
591 {
592         // We may have 0 arguments, but InsetMathNest requires at least one.
593         if (nargs() > 0) {
594                 cur.screenUpdateFlags(Update::SinglePar);
595                 return InsetMathNest::editXY(cur, x, y);                
596         } else
597                 return this;
598 }
599
600
601 void MathMacro::removeArgument(Inset::pos_type pos) {
602         if (displayMode_ == DISPLAY_NORMAL) {
603                 LASSERT(size_t(pos) < cells_.size(), return);
604                 cells_.erase(cells_.begin() + pos);
605                 if (size_t(pos) < attachedArgsNum_)
606                         --attachedArgsNum_;
607                 if (size_t(pos) < optionals_) {
608                         --optionals_;
609                 }
610
611                 needsUpdate_ = true;
612         }
613 }
614
615
616 void MathMacro::insertArgument(Inset::pos_type pos) {
617         if (displayMode_ == DISPLAY_NORMAL) {
618                 LASSERT(size_t(pos) <= cells_.size(), return);
619                 cells_.insert(cells_.begin() + pos, MathData());
620                 if (size_t(pos) < attachedArgsNum_)
621                         ++attachedArgsNum_;
622                 if (size_t(pos) < optionals_)
623                         ++optionals_;
624
625                 needsUpdate_ = true;
626         }
627 }
628
629
630 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
631 {
632         LASSERT(displayMode_ == DISPLAY_NORMAL, return);
633         args = cells_;
634
635         // strip off empty cells, but not more than arity-attachedArgsNum_
636         if (strip) {
637                 size_t i;
638                 for (i = cells_.size(); i > attachedArgsNum_; --i)
639                         if (!cell(i - 1).empty()) break;
640                 args.resize(i);
641         }
642
643         attachedArgsNum_ = 0;
644         expanded_.cell(0) = MathData();
645         cells_.resize(0);
646
647         needsUpdate_ = true;
648 }
649
650
651 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
652 {
653         LASSERT(displayMode_ == DISPLAY_NORMAL, return);
654         cells_ = args;
655         attachedArgsNum_ = args.size();
656         cells_.resize(arity);
657         expanded_.cell(0) = MathData();
658         optionals_ = optionals;
659
660         needsUpdate_ = true;
661 }
662
663
664 bool MathMacro::idxFirst(Cursor & cur) const 
665 {
666         cur.screenUpdateFlags(Update::SinglePar);
667         return InsetMathNest::idxFirst(cur);
668 }
669
670
671 bool MathMacro::idxLast(Cursor & cur) const 
672 {
673         cur.screenUpdateFlags(Update::SinglePar);
674         return InsetMathNest::idxLast(cur);
675 }
676
677
678 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
679 {
680         if (displayMode_ == DISPLAY_UNFOLDED) {
681                 docstring const & unfolded_name = name();
682                 if (unfolded_name != name_) {
683                         // The macro name was changed
684                         Cursor inset_cursor = old;
685                         int macroSlice = inset_cursor.find(this);
686                         // returning true means the cursor is "now" invalid,
687                         // which it was.
688                         LASSERT(macroSlice != -1, return true);
689                         inset_cursor.cutOff(macroSlice);
690                         inset_cursor.recordUndoInset();
691                         inset_cursor.pop();
692                         inset_cursor.cell().erase(inset_cursor.pos());
693                         inset_cursor.cell().insert(inset_cursor.pos(),
694                                 createInsetMath(unfolded_name, cur.buffer()));
695                         cur.resetAnchor();
696                         cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
697                         return true;
698                 }
699         }
700         cur.screenUpdateFlags(Update::Force);
701         return InsetMathNest::notifyCursorLeaves(old, cur);
702 }
703
704
705 void MathMacro::fold(Cursor & cur)
706 {
707         if (!nextFoldMode_) {
708                 nextFoldMode_ = true;
709                 cur.screenUpdateFlags(Update::SinglePar);
710         }
711 }
712
713
714 void MathMacro::unfold(Cursor & cur)
715 {
716         if (nextFoldMode_) {
717                 nextFoldMode_ = false;
718                 cur.screenUpdateFlags(Update::SinglePar);
719         }
720 }
721
722
723 bool MathMacro::folded() const
724 {
725         return nextFoldMode_;
726 }
727
728
729 void MathMacro::write(WriteStream & os) const
730 {
731         MathEnsurer ensurer(os, macro_ != 0, true);
732
733         // non-normal mode
734         if (displayMode_ != DISPLAY_NORMAL) {
735                 os << "\\" << name();
736                 if (name().size() != 1 || isAlphaASCII(name()[0]))
737                         os.pendingSpace(true);
738                 return;
739         }
740
741         // normal mode
742         // we should be ok to continue even if this fails.
743         LATTEST(macro_);
744
745         // Always protect macros in a fragile environment
746         if (os.fragile())
747                 os << "\\protect";
748         
749         os << "\\" << name();
750         bool first = true;
751         
752         // Optional arguments:
753         // First find last non-empty optional argument
754         idx_type emptyOptFrom = 0;
755         idx_type i = 0;
756         for (; i < cells_.size() && i < optionals_; ++i) {
757                 if (!cell(i).empty())
758                         emptyOptFrom = i + 1;
759         }
760         
761         // print out optionals
762         for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
763                 first = false;
764                 os << "[" << cell(i) << "]";
765         }
766         
767         // skip the tailing empty optionals
768         i = optionals_;
769         
770         // Print remaining arguments
771         for (; i < cells_.size(); ++i) {
772                 if (cell(i).size() == 1 
773                         && cell(i)[0].nucleus()->asCharInset()
774                         && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
775                         if (first)
776                                 os << " ";
777                         os << cell(i);
778                 } else
779                         os << "{" << cell(i) << "}";
780                 first = false;
781         }
782
783         // add space if there was no argument
784         if (first)
785                 os.pendingSpace(true);
786 }
787
788
789 void MathMacro::maple(MapleStream & os) const
790 {
791         lyx::maple(expanded_.cell(0), os);
792 }
793
794
795 void MathMacro::mathmlize(MathStream & os) const
796 {
797         MathData const & data = expanded_.cell(0);
798         if (data.empty()) {
799                 // this means that we do not recognize the macro
800                 throw MathExportException();
801         }
802         os << data;
803 }
804
805
806 void MathMacro::htmlize(HtmlStream & os) const
807 {
808         MathData const & data = expanded_.cell(0);
809         if (data.empty()) {
810                 // this means that we do not recognize the macro
811                 throw MathExportException();
812         }
813         os << data;
814 }
815
816
817 void MathMacro::octave(OctaveStream & os) const
818 {
819         lyx::octave(expanded_.cell(0), os);
820 }
821
822
823 void MathMacro::infoize(odocstream & os) const
824 {
825         os << bformat(_("Macro: %1$s"), name());
826 }
827
828
829 void MathMacro::infoize2(odocstream & os) const
830 {
831         os << bformat(_("Macro: %1$s"), name());
832 }
833
834
835 bool MathMacro::completionSupported(Cursor const & cur) const
836 {
837         if (displayMode() != DISPLAY_UNFOLDED)
838                 return InsetMathNest::completionSupported(cur);
839
840         return lyxrc.completion_popup_math
841                 && displayMode() == DISPLAY_UNFOLDED
842                 && cur.bv().cursor().pos() == int(name().size());
843 }
844
845
846 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
847 {
848         if (displayMode() != DISPLAY_UNFOLDED)
849                 return InsetMathNest::inlineCompletionSupported(cur);
850
851         return lyxrc.completion_inline_math
852                 && displayMode() == DISPLAY_UNFOLDED
853                 && cur.bv().cursor().pos() == int(name().size());
854 }
855
856
857 bool MathMacro::automaticInlineCompletion() const
858 {
859         if (displayMode() != DISPLAY_UNFOLDED)
860                 return InsetMathNest::automaticInlineCompletion();
861
862         return lyxrc.completion_inline_math;
863 }
864
865
866 bool MathMacro::automaticPopupCompletion() const
867 {
868         if (displayMode() != DISPLAY_UNFOLDED)
869                 return InsetMathNest::automaticPopupCompletion();
870
871         return lyxrc.completion_popup_math;
872 }
873
874
875 CompletionList const * 
876 MathMacro::createCompletionList(Cursor const & cur) const
877 {
878         if (displayMode() != DISPLAY_UNFOLDED)
879                 return InsetMathNest::createCompletionList(cur);
880
881         return new MathCompletionList(cur.bv().cursor());
882 }
883
884
885 docstring MathMacro::completionPrefix(Cursor const & cur) const
886 {
887         if (displayMode() != DISPLAY_UNFOLDED)
888                 return InsetMathNest::completionPrefix(cur);
889
890         if (!completionSupported(cur))
891                 return docstring();
892         
893         return "\\" + name();
894 }
895
896
897 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
898                                         bool finished)
899 {
900         if (displayMode() != DISPLAY_UNFOLDED)
901                 return InsetMathNest::insertCompletion(cur, s, finished);
902
903         if (!completionSupported(cur))
904                 return false;
905
906         // append completion
907         docstring newName = name() + s;
908         asArray(newName, cell(0));
909         cur.bv().cursor().pos() = name().size();
910         cur.screenUpdateFlags(Update::SinglePar);
911         
912         // finish macro
913         if (finished) {
914                 cur.bv().cursor().pop();
915                 ++cur.bv().cursor().pos();
916                 cur.screenUpdateFlags(Update::SinglePar);
917         }
918         
919         return true;
920 }
921
922
923 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
924         Dimension & dim) const
925 {
926         if (displayMode() != DISPLAY_UNFOLDED)
927                 InsetMathNest::completionPosAndDim(cur, x, y, dim);
928         
929         // get inset dimensions
930         dim = cur.bv().coordCache().insets().dim(this);
931         // FIXME: these 3 are no accurate, but should depend on the font.
932         // Now the popup jumps down if you enter a char with descent > 0.
933         dim.des += 3;
934         dim.asc += 3;
935         
936         // and position
937         Point xy
938         = cur.bv().coordCache().insets().xy(this);
939         x = xy.x_;
940         y = xy.y_;
941 }
942
943
944 } // namespace lyx