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