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