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