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