3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
8 * \author Stefan Schimanski
10 * Full author contact details are available in file CREDITS.
15 #include "MathMacro.h"
17 #include "InsetMathChar.h"
18 #include "MathCompletionList.h"
19 #include "MathExtern.h"
20 #include "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
28 #include "FuncStatus.h"
29 #include "FuncRequest.h"
30 #include "LaTeXFeatures.h"
34 #include "frontends/Painter.h"
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"
45 using namespace lyx::support;
51 /// A proxy for the macro values
52 class ArgumentProxy : public InsetMath {
55 ArgumentProxy(MathMacro * mathMacro, size_t idx)
56 : mathMacro_(mathMacro), idx_(idx) {}
58 ArgumentProxy(MathMacro * mathMacro, size_t idx, docstring const & def)
59 : mathMacro_(mathMacro), idx_(idx)
64 void setOwner(MathMacro * mathMacro) { mathMacro_ = mathMacro; }
66 MathMacro const * owner() { return mathMacro_; }
68 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
70 void metrics(MetricsInfo & mi, Dimension & dim) const {
71 mathMacro_->macro()->unlock();
72 mathMacro_->cell(idx_).metrics(mi, dim);
74 if (!mathMacro_->editMetrics(mi.base.bv)
75 && mathMacro_->cell(idx_).empty())
76 def_.metrics(mi, dim);
78 mathMacro_->macro()->lock();
80 // write(), normalize(), infoize() and infoize2() are not needed since
81 // MathMacro uses the definition and not the expanded cells.
83 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
85 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
87 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
89 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
91 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
93 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
95 void draw(PainterInfo & pi, int x, int y) const {
96 if (mathMacro_->editMetrics(pi.base.bv)) {
97 // The only way a ArgumentProxy can appear is in a cell of the
98 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
99 // mode and then, if the macro is edited the monochrome
100 // mode is entered by the MathMacro before calling the cells' draw
101 // method. Then eventually this code is reached and the proxy leaves
102 // monochrome mode temporarely. Hence, if it is not in monochrome
103 // here (and the assert triggers in pain.leaveMonochromeMode())
105 pi.pain.leaveMonochromeMode();
106 mathMacro_->cell(idx_).draw(pi, x, y);
107 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
108 } else if (mathMacro_->cell(idx_).empty()) {
109 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
112 mathMacro_->cell(idx_).draw(pi, x, y);
115 size_t idx() const { return idx_; }
117 int kerning(BufferView const * bv) const
119 if (mathMacro_->editMetrics(bv)
120 || !mathMacro_->cell(idx_).empty())
121 return mathMacro_->cell(idx_).kerning(bv);
123 return def_.kerning(bv);
128 Inset * clone() const
130 return new ArgumentProxy(*this);
133 MathMacro * mathMacro_;
141 /// Private implementation of MathMacro
142 class MathMacro::Private {
144 Private(Buffer * buf, docstring const & name)
145 : name_(name), displayMode_(DISPLAY_INIT),
146 expanded_(buf), definition_(buf), attachedArgsNum_(0),
147 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
148 macro_(0), needsUpdate_(false), isUpdating_(false),
152 /// Update the pointers to our owner of all expanded macros.
153 /// This needs to be called every time a copy of the owner is created
155 void updateChildren(MathMacro * owner);
156 /// Recursively update the pointers of all expanded macros
157 /// appearing in the arguments of the current macro
158 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
161 /// current display mode
162 DisplayMode displayMode_;
163 /// expanded macro with ArgumentProxies
165 /// macro definition with #1,#2,.. insets
166 MathData definition_;
167 /// number of arguments that were really attached
168 size_t attachedArgsNum_;
169 /// optional argument attached? (only in DISPLAY_NORMAL mode)
171 /// fold mode to be set in next metrics call?
173 /// if macro_ == true, then here is a copy of the macro
174 /// don't use it for locking
175 MacroData macroBackup_;
176 /// if macroNotFound_ == false, then here is a reference to the macro
177 /// this might invalidate after metrics was called
178 MacroData const * macro_;
180 mutable std::map<BufferView const *, bool> editing_;
182 std::string requires_;
183 /// update macro representation
187 /// maximal number of arguments the macro is greedy for
192 void MathMacro::Private::updateChildren(MathMacro * owner)
194 for (size_t i = 0; i < expanded_.size(); ++i) {
195 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
199 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
201 updateNestedChildren(owner, ni);
205 // The macro_ pointer is updated when MathData::metrics() is
206 // called. However, when instant preview is on or the macro is
207 // not on screen, MathData::metrics() is not called and we may
208 // have a dangling pointer. As a safety measure, when a macro
209 // is copied, always let macro_ point to the backup copy of the
210 // MacroData structure. This backup is updated every time the
211 // macro is changed, so it will not become stale.
212 macro_ = ¯oBackup_;
217 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
219 for (size_t i = 0; i < ni->nargs(); ++i) {
220 MathData & ar = ni->cell(i);
221 for (size_t j = 0; j < ar.size(); ++j) {
222 ArgumentProxy * ap = dynamic_cast
223 <ArgumentProxy *>(ar[j].nucleus());
225 MathMacro::Private * md = ap->owner()->d;
227 md->macro_ = &md->macroBackup_;
230 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
232 updateNestedChildren(owner, imn);
238 MathMacro::MathMacro(Buffer * buf, docstring const & name)
239 : InsetMathNest(buf, 0), d(new Private(buf, name))
243 MathMacro::MathMacro(MathMacro const & that)
244 : InsetMathNest(that), d(new Private(*that.d))
246 setBuffer(*that.buffer_);
247 d->updateChildren(this);
251 MathMacro & MathMacro::operator=(MathMacro const & that)
255 InsetMathNest::operator=(that);
257 d->updateChildren(this);
262 MathMacro::~MathMacro()
268 Inset * MathMacro::clone() const
270 MathMacro * copy = new MathMacro(*this);
271 copy->d->needsUpdate_ = true;
272 //copy->d->expanded_.clear();
277 void MathMacro::normalize(NormalStream & os) const
279 os << "[macro " << name();
280 for (size_t i = 0; i < nargs(); ++i)
281 os << ' ' << cell(i);
286 MathMacro::DisplayMode MathMacro::displayMode() const
288 return d->displayMode_;
292 bool MathMacro::extraBraces() const
294 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
298 docstring MathMacro::name() const
300 if (d->displayMode_ == DISPLAY_UNFOLDED)
301 return asString(cell(0));
307 docstring MathMacro::macroName() const
313 void MathMacro::cursorPos(BufferView const & bv,
314 CursorSlice const & sl, bool boundary, int & x, int & y) const
316 // We may have 0 arguments, but InsetMathNest requires at least one.
318 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
322 bool MathMacro::editMode(BufferView const * bv) const {
323 // find this in cursor trace
324 Cursor const & cur = bv->cursor();
325 for (size_t i = 0; i != cur.depth(); ++i)
326 if (&cur[i].inset() == this) {
327 // look if there is no other macro in edit mode above
329 for (; i != cur.depth(); ++i) {
330 InsetMath * im = cur[i].asInsetMath();
332 MathMacro const * macro = im->asMacro();
333 if (macro && macro->displayMode() == DISPLAY_NORMAL)
338 // ok, none found, I am the highest one
346 MacroData const * MathMacro::macro()
352 bool MathMacro::editMetrics(BufferView const * bv) const
354 return d->editing_[bv];
358 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
360 // set edit mode for which we will have calculated metrics. But only
361 d->editing_[mi.base.bv] = editMode(mi.base.bv);
363 // calculate new metrics according to display mode
364 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
365 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
366 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
367 cell(0).metrics(mi, dim);
369 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
370 dim.wid += bsdim.width() + 1;
371 dim.asc = max(bsdim.ascent(), dim.ascent());
372 dim.des = max(bsdim.descent(), dim.descent());
374 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
375 && d->editing_[mi.base.bv]) {
376 // Macro will be edited in a old-style list mode here:
380 FontInfo labelFont = sane_font;
381 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
383 // get dimension of components of list view
385 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
386 nameDim.asc = fontDim.asc;
387 nameDim.des = fontDim.des;
390 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
391 argDim.asc = fontDim.asc;
392 argDim.des = fontDim.des;
395 d->definition_.metrics(mi, defDim);
398 dim.wid = nameDim.wid + defDim.wid;
399 dim.asc = max(nameDim.asc, defDim.asc);
400 dim.des = max(nameDim.des, defDim.des);
402 for (idx_type i = 0; i < nargs(); ++i) {
404 cell(i).metrics(mi, cdim);
405 dim.des += max(argDim.height(), cdim.height()) + 1;
406 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
409 // make space for box and markers, 2 pixels
413 metricsMarkers2(dim);
417 // calculate metrics, hoping that all cells are seen
419 d->expanded_.metrics(mi, dim);
421 // otherwise do a manual metrics call
422 CoordCache & coords = mi.base.bv->coordCache();
423 for (idx_type i = 0; i < nargs(); ++i) {
424 if (!coords.getArrays().hasDim(&cell(i))) {
426 cell(i).metrics(mi, tdim);
431 // calculate dimension with label while editing
432 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
433 && d->editing_[mi.base.bv]) {
434 FontInfo font = mi.base.font;
435 augmentFont(font, from_ascii("lyxtex"));
437 mathed_string_dim(font, name(), namedim);
439 dim.wid += 2 + namedim.wid + 2 + 2;
440 dim.asc = max(dim.asc, namedim.asc) + 2;
441 dim.des = max(dim.des, namedim.des) + 2;
443 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
444 dim.asc += 1 + namedim.height() + 1;
451 int MathMacro::kerning(BufferView const * bv) const {
452 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
453 return d->expanded_.kerning(bv);
459 void MathMacro::updateMacro(MacroContext const & mc)
462 d->macro_ = mc.get(name());
463 if (d->macro_ && d->macroBackup_ != *d->macro_) {
464 d->macroBackup_ = *d->macro_;
465 d->needsUpdate_ = true;
473 class MathMacro::UpdateLocker
476 explicit UpdateLocker(MathMacro & mm) : mac(mm)
478 mac.d->isUpdating_ = true;
480 ~UpdateLocker() { mac.d->isUpdating_ = false; }
484 /** Avoid wrong usage of UpdateLocker.
485 To avoid wrong usage:
486 UpdateLocker(...); // wrong
487 UpdateLocker locker(...); // right
489 #define UpdateLocker(x) unnamed_UpdateLocker;
490 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
493 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
496 // block recursive calls (bug 8999)
500 UpdateLocker locker(*this);
507 d->requires_ = d->macro_->requires();
510 // non-normal mode? We are done!
511 || (d->displayMode_ != DISPLAY_NORMAL))
514 d->needsUpdate_ = false;
516 // get default values of macro
517 vector<docstring> const & defaults = d->macro_->defaults();
519 // create MathMacroArgumentValue objects pointing to the cells of the macro
520 vector<MathData> values(nargs());
521 for (size_t i = 0; i < nargs(); ++i) {
522 ArgumentProxy * proxy;
523 if (i < defaults.size())
524 proxy = new ArgumentProxy(this, i, defaults[i]);
526 proxy = new ArgumentProxy(this, i);
527 values[i].insert(0, MathAtom(proxy));
529 // expanding macro with the values
530 // Only update the argument macros if anything was expanded, otherwise
531 // we would get an endless loop (bug 9140). UpdateLocker does not work
532 // in this case, since MacroData::expand() creates new MathMacro
533 // objects, so this would be a different recursion path than the one
534 // protected by UpdateLocker.
535 if (d->macro_->expand(values, d->expanded_)) {
536 if (utype == OutputUpdate && !d->expanded_.empty())
537 d->expanded_.updateMacros(cur, mc, utype);
539 // get definition for list edit mode
540 docstring const & display = d->macro_->display();
541 asArray(display.empty() ? d->macro_->definition() : display, d->definition_);
545 void MathMacro::draw(PainterInfo & pi, int x, int y) const
547 Dimension const dim = dimension(*pi.base.bv);
549 setPosCache(pi, x, y);
553 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
554 FontSetChanger dummy(pi.base, "lyxtex");
555 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
556 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
557 FontSetChanger dummy(pi.base, "lyxtex");
558 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
559 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
560 cell(0).draw(pi, x, y);
561 drawMarkers(pi, expx, expy);
562 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
563 && d->editing_[pi.base.bv]) {
564 // Macro will be edited in a old-style list mode here:
566 CoordCache const & coords = pi.base.bv->coordCache();
567 FontInfo const & labelFont = sane_font;
569 // markers and box needs two pixels
572 // get maximal font height
574 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
577 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
578 pi.pain.text(x, y, label, labelFont);
579 x += mathed_string_width(labelFont, label);
582 d->definition_.draw(pi, x, y);
583 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
584 y += max(fontDim.des, defDim.des);
587 docstring str = from_ascii("#9");
588 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
589 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
591 for (idx_type i = 0; i < nargs(); ++i) {
593 Dimension const & cdim = coords.getArrays().dim(&cell(i));
595 y += max(fontDim.asc, cdim.asc) + 1;
599 pi.pain.text(x, y, str, labelFont);
601 pi.pain.text(x, y, from_ascii(":"), labelFont);
605 cell(i).draw(pi, x, y);
608 y += max(fontDim.des, cdim.des);
611 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
612 dim.height() - 2, Color_mathmacroframe);
613 drawMarkers2(pi, expx, expy);
615 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
618 for (size_t i = 0; i < nargs(); ++i)
619 cell(i).setXY(*pi.base.bv, x, y);
621 if (drawBox && d->editing_[pi.base.bv]) {
622 // draw header and rectangle around
623 FontInfo font = pi.base.font;
624 augmentFont(font, from_ascii("lyxtex"));
625 font.setSize(FONT_SIZE_TINY);
626 font.setColor(Color_mathmacrolabel);
628 mathed_string_dim(font, name(), namedim);
630 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
631 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
632 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
635 if (d->editing_[pi.base.bv]) {
636 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
637 d->expanded_.draw(pi, expx, expy);
638 pi.pain.leaveMonochromeMode();
641 pi.pain.rectangle(x, y - dim.asc, dim.wid,
642 dim.height(), Color_mathmacroframe);
644 d->expanded_.draw(pi, expx, expy);
647 drawMarkers(pi, x, y);
650 // edit mode changed?
651 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
652 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
656 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
658 // We may have 0 arguments, but InsetMathNest requires at least one.
660 InsetMathNest::drawSelection(pi, x, y);
664 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
666 if (d->displayMode_ != mode) {
667 // transfer name if changing from or to DISPLAY_UNFOLDED
668 if (mode == DISPLAY_UNFOLDED) {
670 asArray(d->name_, cell(0));
671 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
672 d->name_ = asString(cell(0));
676 d->displayMode_ = mode;
677 d->needsUpdate_ = true;
680 // the interactive init mode is non-greedy by default
682 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
684 d->appetite_ = size_t(appetite);
688 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
690 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
691 return DISPLAY_NORMAL;
693 return DISPLAY_UNFOLDED;
697 bool MathMacro::validName() const
699 docstring n = name();
704 // converting back and force doesn't swallow anything?
707 if (asString(ma) != n)
711 for (size_t i = 0; i<n.size(); ++i) {
712 if (!(n[i] >= 'a' && n[i] <= 'z')
713 && !(n[i] >= 'A' && n[i] <= 'Z')
722 size_t MathMacro::arity() const
724 if (d->displayMode_ == DISPLAY_NORMAL )
725 return cells_.size();
731 size_t MathMacro::optionals() const
733 return d->optionals_;
737 void MathMacro::setOptionals(int n)
739 if (n <= int(nargs()))
744 size_t MathMacro::appetite() const
750 void MathMacro::validate(LaTeXFeatures & features) const
752 // Immediately after a document is loaded, in some cases the MacroData
753 // of the global macros defined in the lib/symbols file may still not
754 // be known to the macro machinery because it will be set only after
755 // the first call to updateMacros(). This is not a problem unless
756 // instant preview is on for math, in which case we will be missing
757 // the corresponding requirements.
758 // In this case, we get the required info from the global macro table.
759 if (!d->requires_.empty())
760 features.require(d->requires_);
761 else if (!d->macro_) {
762 // Update requires for known global macros.
763 MacroData const * data = MacroTable::globalMacros().get(name());
764 if (data && !data->requires().empty())
765 features.require(data->requires());
768 if (name() == "binom")
769 features.require("binom");
771 // validate the cells and the definition
772 if (displayMode() == DISPLAY_NORMAL) {
773 d->definition_.validate(features);
774 InsetMathNest::validate(features);
779 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
781 cur.screenUpdateFlags(Update::SinglePar);
782 InsetMathNest::edit(cur, front, entry_from);
786 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
788 // We may have 0 arguments, but InsetMathNest requires at least one.
790 cur.screenUpdateFlags(Update::SinglePar);
791 return InsetMathNest::editXY(cur, x, y);
797 void MathMacro::removeArgument(Inset::pos_type pos) {
798 if (d->displayMode_ == DISPLAY_NORMAL) {
799 LASSERT(size_t(pos) < cells_.size(), return);
800 cells_.erase(cells_.begin() + pos);
801 if (size_t(pos) < d->attachedArgsNum_)
802 --d->attachedArgsNum_;
803 if (size_t(pos) < d->optionals_) {
807 d->needsUpdate_ = true;
812 void MathMacro::insertArgument(Inset::pos_type pos) {
813 if (d->displayMode_ == DISPLAY_NORMAL) {
814 LASSERT(size_t(pos) <= cells_.size(), return);
815 cells_.insert(cells_.begin() + pos, MathData());
816 if (size_t(pos) < d->attachedArgsNum_)
817 ++d->attachedArgsNum_;
818 if (size_t(pos) < d->optionals_)
821 d->needsUpdate_ = true;
826 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
828 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
831 // strip off empty cells, but not more than arity-attachedArgsNum_
834 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
835 if (!cell(i - 1).empty()) break;
839 d->attachedArgsNum_ = 0;
840 d->expanded_ = MathData();
843 d->needsUpdate_ = true;
847 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
849 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
851 d->attachedArgsNum_ = args.size();
852 cells_.resize(arity);
853 d->expanded_ = MathData();
854 d->optionals_ = optionals;
856 d->needsUpdate_ = true;
860 bool MathMacro::idxFirst(Cursor & cur) const
862 cur.screenUpdateFlags(Update::SinglePar);
863 return InsetMathNest::idxFirst(cur);
867 bool MathMacro::idxLast(Cursor & cur) const
869 cur.screenUpdateFlags(Update::SinglePar);
870 return InsetMathNest::idxLast(cur);
874 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
876 if (d->displayMode_ == DISPLAY_UNFOLDED) {
877 docstring const & unfolded_name = name();
878 if (unfolded_name != d->name_) {
879 // The macro name was changed
880 Cursor inset_cursor = old;
881 int macroSlice = inset_cursor.find(this);
882 // returning true means the cursor is "now" invalid,
884 LASSERT(macroSlice != -1, return true);
885 inset_cursor.cutOff(macroSlice);
886 inset_cursor.recordUndoInset();
888 inset_cursor.cell().erase(inset_cursor.pos());
889 inset_cursor.cell().insert(inset_cursor.pos(),
890 createInsetMath(unfolded_name, cur.buffer()));
892 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
896 cur.screenUpdateFlags(Update::Force);
897 return InsetMathNest::notifyCursorLeaves(old, cur);
901 void MathMacro::fold(Cursor & cur)
903 if (!d->nextFoldMode_) {
904 d->nextFoldMode_ = true;
905 cur.screenUpdateFlags(Update::SinglePar);
910 void MathMacro::unfold(Cursor & cur)
912 if (d->nextFoldMode_) {
913 d->nextFoldMode_ = false;
914 cur.screenUpdateFlags(Update::SinglePar);
919 bool MathMacro::folded() const
921 return d->nextFoldMode_;
925 void MathMacro::write(WriteStream & os) const
927 MathEnsurer ensurer(os, d->macro_ != 0, true);
930 if (d->displayMode_ != DISPLAY_NORMAL) {
931 os << "\\" << name();
932 if (name().size() != 1 || isAlphaASCII(name()[0]))
933 os.pendingSpace(true);
938 // we should be ok to continue even if this fails.
941 // Always protect macros in a fragile environment
945 os << "\\" << name();
948 // Optional arguments:
949 // First find last non-empty optional argument
950 idx_type emptyOptFrom = 0;
952 for (; i < cells_.size() && i < d->optionals_; ++i) {
953 if (!cell(i).empty())
954 emptyOptFrom = i + 1;
957 // print out optionals
958 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
960 os << "[" << cell(i) << "]";
963 // skip the tailing empty optionals
966 // Print remaining arguments
967 for (; i < cells_.size(); ++i) {
968 if (cell(i).size() == 1
969 && cell(i)[0].nucleus()->asCharInset()
970 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
975 os << "{" << cell(i) << "}";
979 // add space if there was no argument
981 os.pendingSpace(true);
985 void MathMacro::maple(MapleStream & os) const
987 lyx::maple(d->expanded_, os);
991 void MathMacro::maxima(MaximaStream & os) const
993 lyx::maxima(d->expanded_, os);
997 void MathMacro::mathematica(MathematicaStream & os) const
999 lyx::mathematica(d->expanded_, os);
1003 void MathMacro::mathmlize(MathStream & os) const
1005 // macro_ is 0 if this is an unknown macro
1006 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1008 docstring const xmlname = d->macro_->xmlname();
1009 if (!xmlname.empty()) {
1010 char const * type = d->macro_->MathMLtype();
1011 os << '<' << type << "> " << xmlname << " </"
1016 if (d->expanded_.empty()) {
1017 // this means that we do not recognize the macro
1018 throw MathExportException();
1024 void MathMacro::htmlize(HtmlStream & os) const
1026 // macro_ is 0 if this is an unknown macro
1027 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1029 docstring const xmlname = d->macro_->xmlname();
1030 if (!xmlname.empty()) {
1031 os << ' ' << xmlname << ' ';
1035 if (d->expanded_.empty()) {
1036 // this means that we do not recognize the macro
1037 throw MathExportException();
1043 void MathMacro::octave(OctaveStream & os) const
1045 lyx::octave(d->expanded_, os);
1049 void MathMacro::infoize(odocstream & os) const
1051 os << bformat(_("Macro: %1$s"), name());
1055 void MathMacro::infoize2(odocstream & os) const
1057 os << bformat(_("Macro: %1$s"), name());
1061 bool MathMacro::completionSupported(Cursor const & cur) const
1063 if (displayMode() != DISPLAY_UNFOLDED)
1064 return InsetMathNest::completionSupported(cur);
1066 return lyxrc.completion_popup_math
1067 && displayMode() == DISPLAY_UNFOLDED
1068 && cur.bv().cursor().pos() == int(name().size());
1072 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1074 if (displayMode() != DISPLAY_UNFOLDED)
1075 return InsetMathNest::inlineCompletionSupported(cur);
1077 return lyxrc.completion_inline_math
1078 && displayMode() == DISPLAY_UNFOLDED
1079 && cur.bv().cursor().pos() == int(name().size());
1083 bool MathMacro::automaticInlineCompletion() const
1085 if (displayMode() != DISPLAY_UNFOLDED)
1086 return InsetMathNest::automaticInlineCompletion();
1088 return lyxrc.completion_inline_math;
1092 bool MathMacro::automaticPopupCompletion() const
1094 if (displayMode() != DISPLAY_UNFOLDED)
1095 return InsetMathNest::automaticPopupCompletion();
1097 return lyxrc.completion_popup_math;
1101 CompletionList const *
1102 MathMacro::createCompletionList(Cursor const & cur) const
1104 if (displayMode() != DISPLAY_UNFOLDED)
1105 return InsetMathNest::createCompletionList(cur);
1107 return new MathCompletionList(cur.bv().cursor());
1111 docstring MathMacro::completionPrefix(Cursor const & cur) const
1113 if (displayMode() != DISPLAY_UNFOLDED)
1114 return InsetMathNest::completionPrefix(cur);
1116 if (!completionSupported(cur))
1119 return "\\" + name();
1123 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1126 if (displayMode() != DISPLAY_UNFOLDED)
1127 return InsetMathNest::insertCompletion(cur, s, finished);
1129 if (!completionSupported(cur))
1132 // append completion
1133 docstring newName = name() + s;
1134 asArray(newName, cell(0));
1135 cur.bv().cursor().pos() = name().size();
1136 cur.screenUpdateFlags(Update::SinglePar);
1140 cur.bv().cursor().pop();
1141 ++cur.bv().cursor().pos();
1142 cur.screenUpdateFlags(Update::SinglePar);
1149 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1150 Dimension & dim) const
1152 if (displayMode() != DISPLAY_UNFOLDED)
1153 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1155 // get inset dimensions
1156 dim = cur.bv().coordCache().insets().dim(this);
1157 // FIXME: these 3 are no accurate, but should depend on the font.
1158 // Now the popup jumps down if you enter a char with descent > 0.
1164 = cur.bv().coordCache().insets().xy(this);