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