]> git.lyx.org Git - lyx.git/blob - src/mathed/MathMacro.cpp
Fix bug #6989: Be somewhat more secure with the homebrew dynamic asserts that were...
[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.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
647                         return true;
648                 }
649         }
650         cur.screenUpdateFlags(Update::Force);
651         return InsetMathNest::notifyCursorLeaves(old, cur);
652 }
653
654
655 void MathMacro::fold(Cursor & cur)
656 {
657         if (!nextFoldMode_) {
658                 nextFoldMode_ = true;
659                 cur.screenUpdateFlags(Update::SinglePar);
660         }
661 }
662
663
664 void MathMacro::unfold(Cursor & cur)
665 {
666         if (nextFoldMode_) {
667                 nextFoldMode_ = false;
668                 cur.screenUpdateFlags(Update::SinglePar);
669         }
670 }
671
672
673 bool MathMacro::folded() const
674 {
675         return nextFoldMode_;
676 }
677
678
679 void MathMacro::write(WriteStream & os) const
680 {
681         MathEnsurer ensurer(os, macro_ != 0, true);
682
683         // non-normal mode
684         if (displayMode_ != DISPLAY_NORMAL) {
685                 os << "\\" << name();
686                 if (name().size() != 1 || isAlphaASCII(name()[0]))
687                         os.pendingSpace(true);
688                 return;
689         }
690
691         // normal mode
692         LASSERT(macro_, /**/);
693
694         // optional arguments make macros fragile
695         if (optionals_ > 0 && os.fragile())
696                 os << "\\protect";
697         
698         os << "\\" << name();
699         bool first = true;
700         
701         // Optional arguments:
702         // First find last non-empty optional argument
703         idx_type emptyOptFrom = 0;
704         idx_type i = 0;
705         for (; i < cells_.size() && i < optionals_; ++i) {
706                 if (!cell(i).empty())
707                         emptyOptFrom = i + 1;
708         }
709         
710         // print out optionals
711         for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
712                 first = false;
713                 os << "[" << cell(i) << "]";
714         }
715         
716         // skip the tailing empty optionals
717         i = optionals_;
718         
719         // Print remaining arguments
720         for (; i < cells_.size(); ++i) {
721                 if (cell(i).size() == 1 
722                         && cell(i)[0].nucleus()->asCharInset()
723                         && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
724                         if (first)
725                                 os << " ";
726                         os << cell(i);
727                 } else
728                         os << "{" << cell(i) << "}";
729                 first = false;
730         }
731
732         // add space if there was no argument
733         if (first)
734                 os.pendingSpace(true);
735 }
736
737
738 void MathMacro::maple(MapleStream & os) const
739 {
740         lyx::maple(expanded_.cell(0), os);
741 }
742
743
744 void MathMacro::mathmlize(MathStream & os) const
745 {
746         os << expanded_.cell(0);
747 }
748
749
750 void MathMacro::htmlize(HtmlStream & os) const
751 {
752         os << expanded_.cell(0);
753 }
754
755
756 void MathMacro::octave(OctaveStream & os) const
757 {
758         lyx::octave(expanded_.cell(0), os);
759 }
760
761
762 void MathMacro::infoize(odocstream & os) const
763 {
764         os << "Macro: " << name();
765 }
766
767
768 void MathMacro::infoize2(odocstream & os) const
769 {
770         os << "Macro: " << name();
771
772 }
773
774
775 bool MathMacro::completionSupported(Cursor const & cur) const
776 {
777         if (displayMode() != DISPLAY_UNFOLDED)
778                 return InsetMathNest::completionSupported(cur);
779
780         return lyxrc.completion_popup_math
781                 && displayMode() == DISPLAY_UNFOLDED
782                 && cur.bv().cursor().pos() == int(name().size());
783 }
784
785
786 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
787 {
788         if (displayMode() != DISPLAY_UNFOLDED)
789                 return InsetMathNest::inlineCompletionSupported(cur);
790
791         return lyxrc.completion_inline_math
792                 && displayMode() == DISPLAY_UNFOLDED
793                 && cur.bv().cursor().pos() == int(name().size());
794 }
795
796
797 bool MathMacro::automaticInlineCompletion() const
798 {
799         if (displayMode() != DISPLAY_UNFOLDED)
800                 return InsetMathNest::automaticInlineCompletion();
801
802         return lyxrc.completion_inline_math;
803 }
804
805
806 bool MathMacro::automaticPopupCompletion() const
807 {
808         if (displayMode() != DISPLAY_UNFOLDED)
809                 return InsetMathNest::automaticPopupCompletion();
810
811         return lyxrc.completion_popup_math;
812 }
813
814
815 CompletionList const * 
816 MathMacro::createCompletionList(Cursor const & cur) const
817 {
818         if (displayMode() != DISPLAY_UNFOLDED)
819                 return InsetMathNest::createCompletionList(cur);
820
821         return new MathCompletionList(cur.bv().cursor());
822 }
823
824
825 docstring MathMacro::completionPrefix(Cursor const & cur) const
826 {
827         if (displayMode() != DISPLAY_UNFOLDED)
828                 return InsetMathNest::completionPrefix(cur);
829
830         if (!completionSupported(cur))
831                 return docstring();
832         
833         return "\\" + name();
834 }
835
836
837 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
838                                         bool finished)
839 {
840         if (displayMode() != DISPLAY_UNFOLDED)
841                 return InsetMathNest::insertCompletion(cur, s, finished);
842
843         if (!completionSupported(cur))
844                 return false;
845
846         // append completion
847         docstring newName = name() + s;
848         asArray(newName, cell(0));
849         cur.bv().cursor().pos() = name().size();
850         cur.screenUpdateFlags(Update::SinglePar);
851         
852         // finish macro
853         if (finished) {
854                 cur.bv().cursor().pop();
855                 ++cur.bv().cursor().pos();
856                 cur.screenUpdateFlags(Update::SinglePar);
857         }
858         
859         return true;
860 }
861
862
863 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
864         Dimension & dim) const
865 {
866         if (displayMode() != DISPLAY_UNFOLDED)
867                 InsetMathNest::completionPosAndDim(cur, x, y, dim);
868         
869         // get inset dimensions
870         dim = cur.bv().coordCache().insets().dim(this);
871         // FIXME: these 3 are no accurate, but should depend on the font.
872         // Now the popup jumps down if you enter a char with descent > 0.
873         dim.des += 3;
874         dim.asc += 3;
875         
876         // and position
877         Point xy
878         = cur.bv().coordCache().insets().xy(this);
879         x = xy.x_;
880         y = xy.y_;
881 }
882
883
884 } // namespace lyx