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