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