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 "BufferList.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
29 #include "FuncStatus.h"
30 #include "FuncRequest.h"
31 #include "LaTeXFeatures.h"
35 #include "frontends/Painter.h"
37 #include "support/debug.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
41 #include "support/textutils.h"
46 using namespace lyx::support;
52 /// A proxy for the macro values
53 class ArgumentProxy : public InsetMath {
56 ArgumentProxy(MathMacro * mathMacro, size_t idx)
57 : mathMacro_(mathMacro), idx_(idx) {}
59 ArgumentProxy(MathMacro * mathMacro, size_t idx, docstring const & def)
60 : mathMacro_(mathMacro), idx_(idx)
65 void setOwner(MathMacro * mathMacro) { mathMacro_ = mathMacro; }
67 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
69 void metrics(MetricsInfo & mi, Dimension & dim) const {
70 mathMacro_->macro()->unlock();
71 mathMacro_->cell(idx_).metrics(mi, dim);
73 if (!mathMacro_->editMetrics(mi.base.bv)
74 && mathMacro_->cell(idx_).empty())
75 def_.metrics(mi, dim);
77 mathMacro_->macro()->lock();
79 // write(), normalize(), infoize() and infoize2() are not needed since
80 // MathMacro uses the definition and not the expanded cells.
82 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
84 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
86 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
88 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
90 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
92 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
94 void draw(PainterInfo & pi, int x, int y) const {
95 if (mathMacro_->editMetrics(pi.base.bv)) {
96 // The only way a ArgumentProxy can appear is in a cell of the
97 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
98 // mode and then, if the macro is edited the monochrome
99 // mode is entered by the MathMacro before calling the cells' draw
100 // method. Then eventually this code is reached and the proxy leaves
101 // monochrome mode temporarely. Hence, if it is not in monochrome
102 // here (and the assert triggers in pain.leaveMonochromeMode())
104 pi.pain.leaveMonochromeMode();
105 mathMacro_->cell(idx_).draw(pi, x, y);
106 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
107 } else if (mathMacro_->cell(idx_).empty()) {
108 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
111 mathMacro_->cell(idx_).draw(pi, x, y);
114 size_t idx() const { return idx_; }
116 int kerning(BufferView const * bv) const
118 if (mathMacro_->editMetrics(bv)
119 || !mathMacro_->cell(idx_).empty())
120 return mathMacro_->cell(idx_).kerning(bv);
122 return def_.kerning(bv);
127 Inset * clone() const
129 return new ArgumentProxy(*this);
132 MathMacro * mathMacro_;
140 /// Private implementation of MathMacro
141 class MathMacro::Private {
143 Private(Buffer * buf, docstring const & name)
144 : name_(name), displayMode_(DISPLAY_INIT),
145 expanded_(buf), definition_(buf), attachedArgsNum_(0),
146 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
147 macro_(0), needsUpdate_(false), isUpdating_(false),
151 /// Update the pointers to our owner of all expanded macros.
152 /// This needs to be called every time a copy of the owner is created
154 void updateChildren(MathMacro * owner);
157 /// current display mode
158 DisplayMode displayMode_;
159 /// expanded macro with ArgumentProxies
161 /// macro definition with #1,#2,.. insets
162 MathData definition_;
163 /// number of arguments that were really attached
164 size_t attachedArgsNum_;
165 /// optional argument attached? (only in DISPLAY_NORMAL mode)
167 /// fold mode to be set in next metrics call?
169 /// if macro_ == true, then here is a copy of the macro
170 /// don't use it for locking
171 MacroData macroBackup_;
172 /// if macroNotFound_ == false, then here is a reference to the macro
173 /// this might invalidate after metrics was called
174 MacroData const * macro_;
176 mutable std::map<BufferView const *, bool> editing_;
178 std::string requires_;
179 /// update macro representation
183 /// maximal number of arguments the macro is greedy for
188 void MathMacro::Private::updateChildren(MathMacro * owner)
190 for (size_t i = 0; i < expanded_.size(); ++i) {
191 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
198 MathMacro::MathMacro(Buffer * buf, docstring const & name)
199 : InsetMathNest(buf, 0), d(new Private(buf, name))
203 MathMacro::MathMacro(MathMacro const & that)
204 : InsetMathNest(that), d(new Private(*that.d))
206 d->updateChildren(this);
207 if (d->macro_ && lyxrc.preview == LyXRC::PREVIEW_ON) {
208 // We need to update d->macro_ by ourselves because in this case
209 // MathData::metrics() is not called when selecting a math inset
210 DocIterator const & pos = d->macroBackup_.pos();
211 Buffer const * buf = pos.buffer();
212 if (buf && !theBufferList().isLoaded(buf))
214 d->macro_ = buf ? buf->getMacro(name(), pos) : 0;
216 d->macro_ = &d->macroBackup_;
221 MathMacro & MathMacro::operator=(MathMacro const & that)
225 InsetMathNest::operator=(that);
227 d->updateChildren(this);
228 if (d->macro_ && lyxrc.preview == LyXRC::PREVIEW_ON) {
229 // We need to update d->macro_ by ourselves because in this case
230 // MathData::metrics() is not called when selecting a math inset
231 DocIterator const & pos = d->macroBackup_.pos();
232 Buffer const * buf = pos.buffer();
233 if (buf && !theBufferList().isLoaded(buf))
235 d->macro_ = buf ? buf->getMacro(name(), pos) : 0;
237 d->macro_ = &d->macroBackup_;
243 MathMacro::~MathMacro()
249 Inset * MathMacro::clone() const
251 MathMacro * copy = new MathMacro(*this);
252 copy->d->needsUpdate_ = true;
253 //copy->d->expanded_.clear();
258 void MathMacro::normalize(NormalStream & os) const
260 os << "[macro " << name();
261 for (size_t i = 0; i < nargs(); ++i)
262 os << ' ' << cell(i);
267 MathMacro::DisplayMode MathMacro::displayMode() const
269 return d->displayMode_;
273 bool MathMacro::extraBraces() const
275 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
279 docstring MathMacro::name() const
281 if (d->displayMode_ == DISPLAY_UNFOLDED)
282 return asString(cell(0));
288 docstring MathMacro::macroName() const
294 void MathMacro::cursorPos(BufferView const & bv,
295 CursorSlice const & sl, bool boundary, int & x, int & y) const
297 // We may have 0 arguments, but InsetMathNest requires at least one.
299 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
303 bool MathMacro::editMode(BufferView const * bv) const {
304 // find this in cursor trace
305 Cursor const & cur = bv->cursor();
306 for (size_t i = 0; i != cur.depth(); ++i)
307 if (&cur[i].inset() == this) {
308 // look if there is no other macro in edit mode above
310 for (; i != cur.depth(); ++i) {
311 InsetMath * im = cur[i].asInsetMath();
313 MathMacro const * macro = im->asMacro();
314 if (macro && macro->displayMode() == DISPLAY_NORMAL)
319 // ok, none found, I am the highest one
327 MacroData const * MathMacro::macro()
333 bool MathMacro::editMetrics(BufferView const * bv) const
335 return d->editing_[bv];
339 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
341 // set edit mode for which we will have calculated metrics. But only
342 d->editing_[mi.base.bv] = editMode(mi.base.bv);
344 // calculate new metrics according to display mode
345 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
346 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
347 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
348 cell(0).metrics(mi, dim);
350 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
351 dim.wid += bsdim.width() + 1;
352 dim.asc = max(bsdim.ascent(), dim.ascent());
353 dim.des = max(bsdim.descent(), dim.descent());
355 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
356 && d->editing_[mi.base.bv]) {
357 // Macro will be edited in a old-style list mode here:
361 FontInfo labelFont = sane_font;
362 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
364 // get dimension of components of list view
366 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
367 nameDim.asc = fontDim.asc;
368 nameDim.des = fontDim.des;
371 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
372 argDim.asc = fontDim.asc;
373 argDim.des = fontDim.des;
376 d->definition_.metrics(mi, defDim);
379 dim.wid = nameDim.wid + defDim.wid;
380 dim.asc = max(nameDim.asc, defDim.asc);
381 dim.des = max(nameDim.des, defDim.des);
383 for (idx_type i = 0; i < nargs(); ++i) {
385 cell(i).metrics(mi, cdim);
386 dim.des += max(argDim.height(), cdim.height()) + 1;
387 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
390 // make space for box and markers, 2 pixels
394 metricsMarkers2(dim);
398 // calculate metrics, hoping that all cells are seen
400 d->expanded_.metrics(mi, dim);
402 // otherwise do a manual metrics call
403 CoordCache & coords = mi.base.bv->coordCache();
404 for (idx_type i = 0; i < nargs(); ++i) {
405 if (!coords.getArrays().hasDim(&cell(i))) {
407 cell(i).metrics(mi, tdim);
412 // calculate dimension with label while editing
413 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
414 && d->editing_[mi.base.bv]) {
415 FontInfo font = mi.base.font;
416 augmentFont(font, from_ascii("lyxtex"));
418 mathed_string_dim(font, name(), namedim);
420 dim.wid += 2 + namedim.wid + 2 + 2;
421 dim.asc = max(dim.asc, namedim.asc) + 2;
422 dim.des = max(dim.des, namedim.des) + 2;
424 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
425 dim.asc += 1 + namedim.height() + 1;
432 int MathMacro::kerning(BufferView const * bv) const {
433 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
434 return d->expanded_.kerning(bv);
440 void MathMacro::updateMacro(MacroContext const & mc)
443 d->macro_ = mc.get(name());
444 if (d->macro_ && d->macroBackup_ != *d->macro_) {
445 d->macroBackup_ = *d->macro_;
446 d->needsUpdate_ = true;
454 class MathMacro::UpdateLocker
457 explicit UpdateLocker(MathMacro & mm) : mac(mm)
459 mac.d->isUpdating_ = true;
461 ~UpdateLocker() { mac.d->isUpdating_ = false; }
465 /** Avoid wrong usage of UpdateLocker.
466 To avoid wrong usage:
467 UpdateLocker(...); // wrong
468 UpdateLocker locker(...); // right
470 #define UpdateLocker(x) unnamed_UpdateLocker;
471 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
474 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
477 // block recursive calls (bug 8999)
481 UpdateLocker locker(*this);
488 d->requires_ = d->macro_->requires();
491 // non-normal mode? We are done!
492 || (d->displayMode_ != DISPLAY_NORMAL))
495 d->needsUpdate_ = false;
497 // get default values of macro
498 vector<docstring> const & defaults = d->macro_->defaults();
500 // create MathMacroArgumentValue objects pointing to the cells of the macro
501 vector<MathData> values(nargs());
502 for (size_t i = 0; i < nargs(); ++i) {
503 ArgumentProxy * proxy;
504 if (i < defaults.size())
505 proxy = new ArgumentProxy(this, i, defaults[i]);
507 proxy = new ArgumentProxy(this, i);
508 values[i].insert(0, MathAtom(proxy));
510 // expanding macro with the values
511 // Only update the argument macros if anything was expanded, otherwise
512 // we would get an endless loop (bug 9140). UpdateLocker does not work
513 // in this case, since MacroData::expand() creates new MathMacro
514 // objects, so this would be a different recursion path than the one
515 // protected by UpdateLocker.
516 if (d->macro_->expand(values, d->expanded_)) {
517 if (utype == OutputUpdate && !d->expanded_.empty())
518 d->expanded_.updateMacros(cur, mc, utype);
520 // get definition for list edit mode
521 docstring const & display = d->macro_->display();
522 asArray(display.empty() ? d->macro_->definition() : display, d->definition_);
526 void MathMacro::draw(PainterInfo & pi, int x, int y) const
528 Dimension const dim = dimension(*pi.base.bv);
530 setPosCache(pi, x, y);
534 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
535 FontSetChanger dummy(pi.base, "lyxtex");
536 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
537 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
538 FontSetChanger dummy(pi.base, "lyxtex");
539 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
540 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
541 cell(0).draw(pi, x, y);
542 drawMarkers(pi, expx, expy);
543 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
544 && d->editing_[pi.base.bv]) {
545 // Macro will be edited in a old-style list mode here:
547 CoordCache const & coords = pi.base.bv->coordCache();
548 FontInfo const & labelFont = sane_font;
550 // markers and box needs two pixels
553 // get maximal font height
555 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
558 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
559 pi.pain.text(x, y, label, labelFont);
560 x += mathed_string_width(labelFont, label);
563 d->definition_.draw(pi, x, y);
564 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
565 y += max(fontDim.des, defDim.des);
568 docstring str = from_ascii("#9");
569 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
570 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
572 for (idx_type i = 0; i < nargs(); ++i) {
574 Dimension const & cdim = coords.getArrays().dim(&cell(i));
576 y += max(fontDim.asc, cdim.asc) + 1;
580 pi.pain.text(x, y, str, labelFont);
582 pi.pain.text(x, y, from_ascii(":"), labelFont);
586 cell(i).draw(pi, x, y);
589 y += max(fontDim.des, cdim.des);
592 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
593 dim.height() - 2, Color_mathmacroframe);
594 drawMarkers2(pi, expx, expy);
596 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
599 for (size_t i = 0; i < nargs(); ++i)
600 cell(i).setXY(*pi.base.bv, x, y);
602 if (drawBox && d->editing_[pi.base.bv]) {
603 // draw header and rectangle around
604 FontInfo font = pi.base.font;
605 augmentFont(font, from_ascii("lyxtex"));
606 font.setSize(FONT_SIZE_TINY);
607 font.setColor(Color_mathmacrolabel);
609 mathed_string_dim(font, name(), namedim);
611 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
612 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
613 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
616 if (d->editing_[pi.base.bv]) {
617 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
618 d->expanded_.draw(pi, expx, expy);
619 pi.pain.leaveMonochromeMode();
622 pi.pain.rectangle(x, y - dim.asc, dim.wid,
623 dim.height(), Color_mathmacroframe);
625 d->expanded_.draw(pi, expx, expy);
628 drawMarkers(pi, x, y);
631 // edit mode changed?
632 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
633 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
637 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
639 // We may have 0 arguments, but InsetMathNest requires at least one.
641 InsetMathNest::drawSelection(pi, x, y);
645 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
647 if (d->displayMode_ != mode) {
648 // transfer name if changing from or to DISPLAY_UNFOLDED
649 if (mode == DISPLAY_UNFOLDED) {
651 asArray(d->name_, cell(0));
652 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
653 d->name_ = asString(cell(0));
657 d->displayMode_ = mode;
658 d->needsUpdate_ = true;
661 // the interactive init mode is non-greedy by default
663 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
665 d->appetite_ = size_t(appetite);
669 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
671 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
672 return DISPLAY_NORMAL;
674 return DISPLAY_UNFOLDED;
678 bool MathMacro::validName() const
680 docstring n = name();
685 // converting back and force doesn't swallow anything?
688 if (asString(ma) != n)
692 for (size_t i = 0; i<n.size(); ++i) {
693 if (!(n[i] >= 'a' && n[i] <= 'z')
694 && !(n[i] >= 'A' && n[i] <= 'Z')
703 size_t MathMacro::arity() const
705 if (d->displayMode_ == DISPLAY_NORMAL )
706 return cells_.size();
712 size_t MathMacro::optionals() const
714 return d->optionals_;
718 void MathMacro::setOptionals(int n)
720 if (n <= int(nargs()))
725 size_t MathMacro::appetite() const
731 void MathMacro::validate(LaTeXFeatures & features) const
733 // Immediately after a document is loaded, in some cases the MacroData
734 // of the global macros defined in the lib/symbols file may still not
735 // be known to the macro machinery because it will be set only after
736 // the first call to updateMacros(). This is not a problem unless
737 // instant preview is on for math, in which case we will be missing
738 // the corresponding requirements.
739 // In this case, we get the required info from the global macro table.
740 if (!d->requires_.empty())
741 features.require(d->requires_);
742 else if (!d->macro_) {
743 // Update requires for known global macros.
744 MacroData const * data = MacroTable::globalMacros().get(name());
745 if (data && !data->requires().empty())
746 features.require(data->requires());
749 if (name() == "binom")
750 features.require("binom");
752 // validate the cells and the definition
753 if (displayMode() == DISPLAY_NORMAL) {
754 d->definition_.validate(features);
755 InsetMathNest::validate(features);
760 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
762 cur.screenUpdateFlags(Update::SinglePar);
763 InsetMathNest::edit(cur, front, entry_from);
767 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
769 // We may have 0 arguments, but InsetMathNest requires at least one.
771 cur.screenUpdateFlags(Update::SinglePar);
772 return InsetMathNest::editXY(cur, x, y);
778 void MathMacro::removeArgument(Inset::pos_type pos) {
779 if (d->displayMode_ == DISPLAY_NORMAL) {
780 LASSERT(size_t(pos) < cells_.size(), return);
781 cells_.erase(cells_.begin() + pos);
782 if (size_t(pos) < d->attachedArgsNum_)
783 --d->attachedArgsNum_;
784 if (size_t(pos) < d->optionals_) {
788 d->needsUpdate_ = true;
793 void MathMacro::insertArgument(Inset::pos_type pos) {
794 if (d->displayMode_ == DISPLAY_NORMAL) {
795 LASSERT(size_t(pos) <= cells_.size(), return);
796 cells_.insert(cells_.begin() + pos, MathData());
797 if (size_t(pos) < d->attachedArgsNum_)
798 ++d->attachedArgsNum_;
799 if (size_t(pos) < d->optionals_)
802 d->needsUpdate_ = true;
807 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
809 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
812 // strip off empty cells, but not more than arity-attachedArgsNum_
815 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
816 if (!cell(i - 1).empty()) break;
820 d->attachedArgsNum_ = 0;
821 d->expanded_ = MathData();
824 d->needsUpdate_ = true;
828 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
830 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
832 d->attachedArgsNum_ = args.size();
833 cells_.resize(arity);
834 d->expanded_ = MathData();
835 d->optionals_ = optionals;
837 d->needsUpdate_ = true;
841 bool MathMacro::idxFirst(Cursor & cur) const
843 cur.screenUpdateFlags(Update::SinglePar);
844 return InsetMathNest::idxFirst(cur);
848 bool MathMacro::idxLast(Cursor & cur) const
850 cur.screenUpdateFlags(Update::SinglePar);
851 return InsetMathNest::idxLast(cur);
855 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
857 if (d->displayMode_ == DISPLAY_UNFOLDED) {
858 docstring const & unfolded_name = name();
859 if (unfolded_name != d->name_) {
860 // The macro name was changed
861 Cursor inset_cursor = old;
862 int macroSlice = inset_cursor.find(this);
863 // returning true means the cursor is "now" invalid,
865 LASSERT(macroSlice != -1, return true);
866 inset_cursor.cutOff(macroSlice);
867 inset_cursor.recordUndoInset();
869 inset_cursor.cell().erase(inset_cursor.pos());
870 inset_cursor.cell().insert(inset_cursor.pos(),
871 createInsetMath(unfolded_name, cur.buffer()));
873 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
877 cur.screenUpdateFlags(Update::Force);
878 return InsetMathNest::notifyCursorLeaves(old, cur);
882 void MathMacro::fold(Cursor & cur)
884 if (!d->nextFoldMode_) {
885 d->nextFoldMode_ = true;
886 cur.screenUpdateFlags(Update::SinglePar);
891 void MathMacro::unfold(Cursor & cur)
893 if (d->nextFoldMode_) {
894 d->nextFoldMode_ = false;
895 cur.screenUpdateFlags(Update::SinglePar);
900 bool MathMacro::folded() const
902 return d->nextFoldMode_;
906 void MathMacro::write(WriteStream & os) const
908 MathEnsurer ensurer(os, d->macro_ != 0, true);
911 if (d->displayMode_ != DISPLAY_NORMAL) {
912 os << "\\" << name();
913 if (name().size() != 1 || isAlphaASCII(name()[0]))
914 os.pendingSpace(true);
919 // we should be ok to continue even if this fails.
922 // Always protect macros in a fragile environment
926 os << "\\" << name();
929 // Optional arguments:
930 // First find last non-empty optional argument
931 idx_type emptyOptFrom = 0;
933 for (; i < cells_.size() && i < d->optionals_; ++i) {
934 if (!cell(i).empty())
935 emptyOptFrom = i + 1;
938 // print out optionals
939 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
941 os << "[" << cell(i) << "]";
944 // skip the tailing empty optionals
947 // Print remaining arguments
948 for (; i < cells_.size(); ++i) {
949 if (cell(i).size() == 1
950 && cell(i)[0].nucleus()->asCharInset()
951 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
956 os << "{" << cell(i) << "}";
960 // add space if there was no argument
962 os.pendingSpace(true);
966 void MathMacro::maple(MapleStream & os) const
968 lyx::maple(d->expanded_, os);
972 void MathMacro::maxima(MaximaStream & os) const
974 lyx::maxima(d->expanded_, os);
978 void MathMacro::mathematica(MathematicaStream & os) const
980 lyx::mathematica(d->expanded_, os);
984 void MathMacro::mathmlize(MathStream & os) const
986 // macro_ is 0 if this is an unknown macro
987 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
989 docstring const xmlname = d->macro_->xmlname();
990 if (!xmlname.empty()) {
991 char const * type = d->macro_->MathMLtype();
992 os << '<' << type << "> " << xmlname << " /<"
997 if (d->expanded_.empty()) {
998 // this means that we do not recognize the macro
999 throw MathExportException();
1005 void MathMacro::htmlize(HtmlStream & os) const
1007 // macro_ is 0 if this is an unknown macro
1008 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1010 docstring const xmlname = d->macro_->xmlname();
1011 if (!xmlname.empty()) {
1012 os << ' ' << xmlname << ' ';
1016 if (d->expanded_.empty()) {
1017 // this means that we do not recognize the macro
1018 throw MathExportException();
1024 void MathMacro::octave(OctaveStream & os) const
1026 lyx::octave(d->expanded_, os);
1030 void MathMacro::infoize(odocstream & os) const
1032 os << bformat(_("Macro: %1$s"), name());
1036 void MathMacro::infoize2(odocstream & os) const
1038 os << bformat(_("Macro: %1$s"), name());
1042 bool MathMacro::completionSupported(Cursor const & cur) const
1044 if (displayMode() != DISPLAY_UNFOLDED)
1045 return InsetMathNest::completionSupported(cur);
1047 return lyxrc.completion_popup_math
1048 && displayMode() == DISPLAY_UNFOLDED
1049 && cur.bv().cursor().pos() == int(name().size());
1053 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1055 if (displayMode() != DISPLAY_UNFOLDED)
1056 return InsetMathNest::inlineCompletionSupported(cur);
1058 return lyxrc.completion_inline_math
1059 && displayMode() == DISPLAY_UNFOLDED
1060 && cur.bv().cursor().pos() == int(name().size());
1064 bool MathMacro::automaticInlineCompletion() const
1066 if (displayMode() != DISPLAY_UNFOLDED)
1067 return InsetMathNest::automaticInlineCompletion();
1069 return lyxrc.completion_inline_math;
1073 bool MathMacro::automaticPopupCompletion() const
1075 if (displayMode() != DISPLAY_UNFOLDED)
1076 return InsetMathNest::automaticPopupCompletion();
1078 return lyxrc.completion_popup_math;
1082 CompletionList const *
1083 MathMacro::createCompletionList(Cursor const & cur) const
1085 if (displayMode() != DISPLAY_UNFOLDED)
1086 return InsetMathNest::createCompletionList(cur);
1088 return new MathCompletionList(cur.bv().cursor());
1092 docstring MathMacro::completionPrefix(Cursor const & cur) const
1094 if (displayMode() != DISPLAY_UNFOLDED)
1095 return InsetMathNest::completionPrefix(cur);
1097 if (!completionSupported(cur))
1100 return "\\" + name();
1104 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1107 if (displayMode() != DISPLAY_UNFOLDED)
1108 return InsetMathNest::insertCompletion(cur, s, finished);
1110 if (!completionSupported(cur))
1113 // append completion
1114 docstring newName = name() + s;
1115 asArray(newName, cell(0));
1116 cur.bv().cursor().pos() = name().size();
1117 cur.screenUpdateFlags(Update::SinglePar);
1121 cur.bv().cursor().pop();
1122 ++cur.bv().cursor().pos();
1123 cur.screenUpdateFlags(Update::SinglePar);
1130 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1131 Dimension & dim) const
1133 if (displayMode() != DISPLAY_UNFOLDED)
1134 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1136 // get inset dimensions
1137 dim = cur.bv().coordCache().insets().dim(this);
1138 // FIXME: these 3 are no accurate, but should depend on the font.
1139 // Now the popup jumps down if you enter a char with descent > 0.
1145 = cur.bv().coordCache().insets().xy(this);