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