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