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