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 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
68 void metrics(MetricsInfo & mi, Dimension & dim) const {
69 mathMacro_->macro()->unlock();
70 mathMacro_->cell(idx_).metrics(mi, dim);
72 if (!mathMacro_->editMetrics(mi.base.bv)
73 && mathMacro_->cell(idx_).empty())
74 def_.metrics(mi, dim);
76 mathMacro_->macro()->lock();
78 // write(), normalize(), infoize() and infoize2() are not needed since
79 // MathMacro uses the definition and not the expanded cells.
81 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
83 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
85 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
87 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
89 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
91 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
93 void draw(PainterInfo & pi, int x, int y) const {
94 if (mathMacro_->editMetrics(pi.base.bv)) {
95 // The only way a ArgumentProxy can appear is in a cell of the
96 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
97 // mode and then, if the macro is edited the monochrome
98 // mode is entered by the MathMacro before calling the cells' draw
99 // method. Then eventually this code is reached and the proxy leaves
100 // monochrome mode temporarely. Hence, if it is not in monochrome
101 // here (and the assert triggers in pain.leaveMonochromeMode())
103 pi.pain.leaveMonochromeMode();
104 mathMacro_->cell(idx_).draw(pi, x, y);
105 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
106 } else if (mathMacro_->cell(idx_).empty()) {
107 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
110 mathMacro_->cell(idx_).draw(pi, x, y);
113 size_t idx() const { return idx_; }
115 int kerning(BufferView const * bv) const
117 if (mathMacro_->editMetrics(bv)
118 || !mathMacro_->cell(idx_).empty())
119 return mathMacro_->cell(idx_).kerning(bv);
121 return def_.kerning(bv);
126 Inset * clone() const
128 return new ArgumentProxy(*this);
131 MathMacro * mathMacro_;
139 /// Private implementation of MathMacro
140 class MathMacro::Private {
142 Private(Buffer * buf, docstring const & name)
143 : name_(name), displayMode_(DISPLAY_INIT),
144 expanded_(buf), definition_(buf), attachedArgsNum_(0),
145 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
146 macro_(0), needsUpdate_(false), isUpdating_(false),
150 /// Update the pointers to our owner of all expanded macros.
151 /// This needs to be called every time a copy of the owner is created
153 void updateChildren(MathMacro * owner);
156 /// current display mode
157 DisplayMode displayMode_;
158 /// expanded macro with ArgumentProxies
160 /// macro definition with #1,#2,.. insets
161 MathData definition_;
162 /// number of arguments that were really attached
163 size_t attachedArgsNum_;
164 /// optional argument attached? (only in DISPLAY_NORMAL mode)
166 /// fold mode to be set in next metrics call?
168 /// if macro_ == true, then here is a copy of the macro
169 /// don't use it for locking
170 MacroData macroBackup_;
171 /// if macroNotFound_ == false, then here is a reference to the macro
172 /// this might invalidate after metrics was called
173 MacroData const * macro_;
175 mutable std::map<BufferView const *, bool> editing_;
177 std::string requires_;
178 /// update macro representation
182 /// maximal number of arguments the macro is greedy for
187 void MathMacro::Private::updateChildren(MathMacro * owner)
189 for (size_t i = 0; i < expanded_.size(); ++i) {
190 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
197 MathMacro::MathMacro(Buffer * buf, docstring const & name)
198 : InsetMathNest(buf, 0), d(new Private(buf, name))
202 MathMacro::MathMacro(MathMacro const & that)
203 : InsetMathNest(that), d(new Private(*that.d))
205 d->updateChildren(this);
206 if (d->macro_ && lyxrc.preview == LyXRC::PREVIEW_ON) {
207 // We need to update d->macro_ by ourselves because in this case
208 // MathData::metrics() is not called when selecting a math inset
209 DocIterator const & pos = d->macroBackup_.pos();
210 d->macro_ = pos.buffer() ? pos.buffer()->getMacro(name(), pos) : 0;
212 d->macro_ = &d->macroBackup_;
217 MathMacro & MathMacro::operator=(MathMacro const & that)
221 InsetMathNest::operator=(that);
223 d->updateChildren(this);
224 if (d->macro_ && lyxrc.preview == LyXRC::PREVIEW_ON) {
225 // We need to update d->macro_ by ourselves because in this case
226 // MathData::metrics() is not called when selecting a math inset
227 DocIterator const & pos = d->macroBackup_.pos();
228 d->macro_ = pos.buffer() ? pos.buffer()->getMacro(name(), pos) : 0;
230 d->macro_ = &d->macroBackup_;
236 MathMacro::~MathMacro()
242 Inset * MathMacro::clone() const
244 MathMacro * copy = new MathMacro(*this);
245 copy->d->needsUpdate_ = true;
246 //copy->d->expanded_.clear();
251 void MathMacro::normalize(NormalStream & os) const
253 os << "[macro " << name();
254 for (size_t i = 0; i < nargs(); ++i)
255 os << ' ' << cell(i);
260 MathMacro::DisplayMode MathMacro::displayMode() const
262 return d->displayMode_;
266 bool MathMacro::extraBraces() const
268 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
272 docstring MathMacro::name() const
274 if (d->displayMode_ == DISPLAY_UNFOLDED)
275 return asString(cell(0));
281 docstring MathMacro::macroName() const
287 void MathMacro::cursorPos(BufferView const & bv,
288 CursorSlice const & sl, bool boundary, int & x, int & y) const
290 // We may have 0 arguments, but InsetMathNest requires at least one.
292 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
296 bool MathMacro::editMode(BufferView const * bv) const {
297 // find this in cursor trace
298 Cursor const & cur = bv->cursor();
299 for (size_t i = 0; i != cur.depth(); ++i)
300 if (&cur[i].inset() == this) {
301 // look if there is no other macro in edit mode above
303 for (; i != cur.depth(); ++i) {
304 InsetMath * im = cur[i].asInsetMath();
306 MathMacro const * macro = im->asMacro();
307 if (macro && macro->displayMode() == DISPLAY_NORMAL)
312 // ok, none found, I am the highest one
320 MacroData const * MathMacro::macro()
326 bool MathMacro::editMetrics(BufferView const * bv) const
328 return d->editing_[bv];
332 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
334 // set edit mode for which we will have calculated metrics. But only
335 d->editing_[mi.base.bv] = editMode(mi.base.bv);
337 // calculate new metrics according to display mode
338 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
339 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
340 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
341 cell(0).metrics(mi, dim);
343 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
344 dim.wid += bsdim.width() + 1;
345 dim.asc = max(bsdim.ascent(), dim.ascent());
346 dim.des = max(bsdim.descent(), dim.descent());
348 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
349 && d->editing_[mi.base.bv]) {
350 // Macro will be edited in a old-style list mode here:
354 FontInfo labelFont = sane_font;
355 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
357 // get dimension of components of list view
359 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
360 nameDim.asc = fontDim.asc;
361 nameDim.des = fontDim.des;
364 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
365 argDim.asc = fontDim.asc;
366 argDim.des = fontDim.des;
369 d->definition_.metrics(mi, defDim);
372 dim.wid = nameDim.wid + defDim.wid;
373 dim.asc = max(nameDim.asc, defDim.asc);
374 dim.des = max(nameDim.des, defDim.des);
376 for (idx_type i = 0; i < nargs(); ++i) {
378 cell(i).metrics(mi, cdim);
379 dim.des += max(argDim.height(), cdim.height()) + 1;
380 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
383 // make space for box and markers, 2 pixels
387 metricsMarkers2(dim);
391 // calculate metrics, hoping that all cells are seen
393 d->expanded_.metrics(mi, dim);
395 // otherwise do a manual metrics call
396 CoordCache & coords = mi.base.bv->coordCache();
397 for (idx_type i = 0; i < nargs(); ++i) {
398 if (!coords.getArrays().hasDim(&cell(i))) {
400 cell(i).metrics(mi, tdim);
405 // calculate dimension with label while editing
406 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
407 && d->editing_[mi.base.bv]) {
408 FontInfo font = mi.base.font;
409 augmentFont(font, from_ascii("lyxtex"));
411 mathed_string_dim(font, name(), namedim);
413 dim.wid += 2 + namedim.wid + 2 + 2;
414 dim.asc = max(dim.asc, namedim.asc) + 2;
415 dim.des = max(dim.des, namedim.des) + 2;
417 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
418 dim.asc += 1 + namedim.height() + 1;
425 int MathMacro::kerning(BufferView const * bv) const {
426 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
427 return d->expanded_.kerning(bv);
433 void MathMacro::updateMacro(MacroContext const & mc)
436 d->macro_ = mc.get(name());
437 if (d->macro_ && d->macroBackup_ != *d->macro_) {
438 d->macroBackup_ = *d->macro_;
439 d->needsUpdate_ = true;
447 class MathMacro::UpdateLocker
450 explicit UpdateLocker(MathMacro & mm) : mac(mm)
452 mac.d->isUpdating_ = true;
454 ~UpdateLocker() { mac.d->isUpdating_ = false; }
458 /** Avoid wrong usage of UpdateLocker.
459 To avoid wrong usage:
460 UpdateLocker(...); // wrong
461 UpdateLocker locker(...); // right
463 #define UpdateLocker(x) unnamed_UpdateLocker;
464 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
467 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
470 // block recursive calls (bug 8999)
474 UpdateLocker locker(*this);
481 d->requires_ = d->macro_->requires();
484 // non-normal mode? We are done!
485 || (d->displayMode_ != DISPLAY_NORMAL))
488 d->needsUpdate_ = false;
490 // get default values of macro
491 vector<docstring> const & defaults = d->macro_->defaults();
493 // create MathMacroArgumentValue objects pointing to the cells of the macro
494 vector<MathData> values(nargs());
495 for (size_t i = 0; i < nargs(); ++i) {
496 ArgumentProxy * proxy;
497 if (i < defaults.size())
498 proxy = new ArgumentProxy(this, i, defaults[i]);
500 proxy = new ArgumentProxy(this, i);
501 values[i].insert(0, MathAtom(proxy));
503 // expanding macro with the values
504 // Only update the argument macros if anything was expanded, otherwise
505 // we would get an endless loop (bug 9140). UpdateLocker does not work
506 // in this case, since MacroData::expand() creates new MathMacro
507 // objects, so this would be a different recursion path than the one
508 // protected by UpdateLocker.
509 if (d->macro_->expand(values, d->expanded_)) {
510 if (utype == OutputUpdate && !d->expanded_.empty())
511 d->expanded_.updateMacros(cur, mc, utype);
513 // get definition for list edit mode
514 docstring const & display = d->macro_->display();
515 asArray(display.empty() ? d->macro_->definition() : display, d->definition_);
519 void MathMacro::draw(PainterInfo & pi, int x, int y) const
521 Dimension const dim = dimension(*pi.base.bv);
523 setPosCache(pi, x, y);
527 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
528 FontSetChanger dummy(pi.base, "lyxtex");
529 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
530 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
531 FontSetChanger dummy(pi.base, "lyxtex");
532 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
533 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
534 cell(0).draw(pi, x, y);
535 drawMarkers(pi, expx, expy);
536 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
537 && d->editing_[pi.base.bv]) {
538 // Macro will be edited in a old-style list mode here:
540 CoordCache const & coords = pi.base.bv->coordCache();
541 FontInfo const & labelFont = sane_font;
543 // markers and box needs two pixels
546 // get maximal font height
548 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
551 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
552 pi.pain.text(x, y, label, labelFont);
553 x += mathed_string_width(labelFont, label);
556 d->definition_.draw(pi, x, y);
557 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
558 y += max(fontDim.des, defDim.des);
561 docstring str = from_ascii("#9");
562 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
563 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
565 for (idx_type i = 0; i < nargs(); ++i) {
567 Dimension const & cdim = coords.getArrays().dim(&cell(i));
569 y += max(fontDim.asc, cdim.asc) + 1;
573 pi.pain.text(x, y, str, labelFont);
575 pi.pain.text(x, y, from_ascii(":"), labelFont);
579 cell(i).draw(pi, x, y);
582 y += max(fontDim.des, cdim.des);
585 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
586 dim.height() - 2, Color_mathmacroframe);
587 drawMarkers2(pi, expx, expy);
589 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
592 for (size_t i = 0; i < nargs(); ++i)
593 cell(i).setXY(*pi.base.bv, x, y);
595 if (drawBox && d->editing_[pi.base.bv]) {
596 // draw header and rectangle around
597 FontInfo font = pi.base.font;
598 augmentFont(font, from_ascii("lyxtex"));
599 font.setSize(FONT_SIZE_TINY);
600 font.setColor(Color_mathmacrolabel);
602 mathed_string_dim(font, name(), namedim);
604 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
605 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
606 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
609 if (d->editing_[pi.base.bv]) {
610 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
611 d->expanded_.draw(pi, expx, expy);
612 pi.pain.leaveMonochromeMode();
615 pi.pain.rectangle(x, y - dim.asc, dim.wid,
616 dim.height(), Color_mathmacroframe);
618 d->expanded_.draw(pi, expx, expy);
621 drawMarkers(pi, x, y);
624 // edit mode changed?
625 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
626 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
630 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
632 // We may have 0 arguments, but InsetMathNest requires at least one.
634 InsetMathNest::drawSelection(pi, x, y);
638 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
640 if (d->displayMode_ != mode) {
641 // transfer name if changing from or to DISPLAY_UNFOLDED
642 if (mode == DISPLAY_UNFOLDED) {
644 asArray(d->name_, cell(0));
645 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
646 d->name_ = asString(cell(0));
650 d->displayMode_ = mode;
651 d->needsUpdate_ = true;
654 // the interactive init mode is non-greedy by default
656 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
658 d->appetite_ = size_t(appetite);
662 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
664 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
665 return DISPLAY_NORMAL;
667 return DISPLAY_UNFOLDED;
671 bool MathMacro::validName() const
673 docstring n = name();
678 // converting back and force doesn't swallow anything?
681 if (asString(ma) != n)
685 for (size_t i = 0; i<n.size(); ++i) {
686 if (!(n[i] >= 'a' && n[i] <= 'z')
687 && !(n[i] >= 'A' && n[i] <= 'Z')
696 size_t MathMacro::arity() const
698 if (d->displayMode_ == DISPLAY_NORMAL )
699 return cells_.size();
705 size_t MathMacro::optionals() const
707 return d->optionals_;
711 void MathMacro::setOptionals(int n)
713 if (n <= int(nargs()))
718 size_t MathMacro::appetite() const
724 void MathMacro::validate(LaTeXFeatures & features) const
726 // Immediately after a document is loaded, in some cases the MacroData
727 // of the global macros defined in the lib/symbols file may still not
728 // be known to the macro machinery because it will be set only after
729 // the first call to updateMacros(). This is not a problem unless
730 // instant preview is on for math, in which case we will be missing
731 // the corresponding requirements.
732 // In this case, we get the required info from the global macro table.
733 if (!d->requires_.empty())
734 features.require(d->requires_);
735 else if (!d->macro_) {
736 // Update requires for known global macros.
737 MacroData const * data = MacroTable::globalMacros().get(name());
738 if (data && !data->requires().empty())
739 features.require(data->requires());
742 if (name() == "binom")
743 features.require("binom");
745 // validate the cells and the definition
746 if (displayMode() == DISPLAY_NORMAL) {
747 d->definition_.validate(features);
748 InsetMathNest::validate(features);
753 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
755 cur.screenUpdateFlags(Update::SinglePar);
756 InsetMathNest::edit(cur, front, entry_from);
760 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
762 // We may have 0 arguments, but InsetMathNest requires at least one.
764 cur.screenUpdateFlags(Update::SinglePar);
765 return InsetMathNest::editXY(cur, x, y);
771 void MathMacro::removeArgument(Inset::pos_type pos) {
772 if (d->displayMode_ == DISPLAY_NORMAL) {
773 LASSERT(size_t(pos) < cells_.size(), return);
774 cells_.erase(cells_.begin() + pos);
775 if (size_t(pos) < d->attachedArgsNum_)
776 --d->attachedArgsNum_;
777 if (size_t(pos) < d->optionals_) {
781 d->needsUpdate_ = true;
786 void MathMacro::insertArgument(Inset::pos_type pos) {
787 if (d->displayMode_ == DISPLAY_NORMAL) {
788 LASSERT(size_t(pos) <= cells_.size(), return);
789 cells_.insert(cells_.begin() + pos, MathData());
790 if (size_t(pos) < d->attachedArgsNum_)
791 ++d->attachedArgsNum_;
792 if (size_t(pos) < d->optionals_)
795 d->needsUpdate_ = true;
800 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
802 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
805 // strip off empty cells, but not more than arity-attachedArgsNum_
808 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
809 if (!cell(i - 1).empty()) break;
813 d->attachedArgsNum_ = 0;
814 d->expanded_ = MathData();
817 d->needsUpdate_ = true;
821 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
823 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
825 d->attachedArgsNum_ = args.size();
826 cells_.resize(arity);
827 d->expanded_ = MathData();
828 d->optionals_ = optionals;
830 d->needsUpdate_ = true;
834 bool MathMacro::idxFirst(Cursor & cur) const
836 cur.screenUpdateFlags(Update::SinglePar);
837 return InsetMathNest::idxFirst(cur);
841 bool MathMacro::idxLast(Cursor & cur) const
843 cur.screenUpdateFlags(Update::SinglePar);
844 return InsetMathNest::idxLast(cur);
848 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
850 if (d->displayMode_ == DISPLAY_UNFOLDED) {
851 docstring const & unfolded_name = name();
852 if (unfolded_name != d->name_) {
853 // The macro name was changed
854 Cursor inset_cursor = old;
855 int macroSlice = inset_cursor.find(this);
856 // returning true means the cursor is "now" invalid,
858 LASSERT(macroSlice != -1, return true);
859 inset_cursor.cutOff(macroSlice);
860 inset_cursor.recordUndoInset();
862 inset_cursor.cell().erase(inset_cursor.pos());
863 inset_cursor.cell().insert(inset_cursor.pos(),
864 createInsetMath(unfolded_name, cur.buffer()));
866 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
870 cur.screenUpdateFlags(Update::Force);
871 return InsetMathNest::notifyCursorLeaves(old, cur);
875 void MathMacro::fold(Cursor & cur)
877 if (!d->nextFoldMode_) {
878 d->nextFoldMode_ = true;
879 cur.screenUpdateFlags(Update::SinglePar);
884 void MathMacro::unfold(Cursor & cur)
886 if (d->nextFoldMode_) {
887 d->nextFoldMode_ = false;
888 cur.screenUpdateFlags(Update::SinglePar);
893 bool MathMacro::folded() const
895 return d->nextFoldMode_;
899 void MathMacro::write(WriteStream & os) const
901 MathEnsurer ensurer(os, d->macro_ != 0, true);
904 if (d->displayMode_ != DISPLAY_NORMAL) {
905 os << "\\" << name();
906 if (name().size() != 1 || isAlphaASCII(name()[0]))
907 os.pendingSpace(true);
912 // we should be ok to continue even if this fails.
915 // Always protect macros in a fragile environment
919 os << "\\" << name();
922 // Optional arguments:
923 // First find last non-empty optional argument
924 idx_type emptyOptFrom = 0;
926 for (; i < cells_.size() && i < d->optionals_; ++i) {
927 if (!cell(i).empty())
928 emptyOptFrom = i + 1;
931 // print out optionals
932 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
934 os << "[" << cell(i) << "]";
937 // skip the tailing empty optionals
940 // Print remaining arguments
941 for (; i < cells_.size(); ++i) {
942 if (cell(i).size() == 1
943 && cell(i)[0].nucleus()->asCharInset()
944 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
949 os << "{" << cell(i) << "}";
953 // add space if there was no argument
955 os.pendingSpace(true);
959 void MathMacro::maple(MapleStream & os) const
961 lyx::maple(d->expanded_, os);
965 void MathMacro::maxima(MaximaStream & os) const
967 lyx::maxima(d->expanded_, os);
971 void MathMacro::mathematica(MathematicaStream & os) const
973 lyx::mathematica(d->expanded_, os);
977 void MathMacro::mathmlize(MathStream & os) const
979 // macro_ is 0 if this is an unknown macro
980 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
982 docstring const xmlname = d->macro_->xmlname();
983 if (!xmlname.empty()) {
984 char const * type = d->macro_->MathMLtype();
985 os << '<' << type << "> " << xmlname << " /<"
990 if (d->expanded_.empty()) {
991 // this means that we do not recognize the macro
992 throw MathExportException();
998 void MathMacro::htmlize(HtmlStream & os) const
1000 // macro_ is 0 if this is an unknown macro
1001 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1003 docstring const xmlname = d->macro_->xmlname();
1004 if (!xmlname.empty()) {
1005 os << ' ' << xmlname << ' ';
1009 if (d->expanded_.empty()) {
1010 // this means that we do not recognize the macro
1011 throw MathExportException();
1017 void MathMacro::octave(OctaveStream & os) const
1019 lyx::octave(d->expanded_, os);
1023 void MathMacro::infoize(odocstream & os) const
1025 os << bformat(_("Macro: %1$s"), name());
1029 void MathMacro::infoize2(odocstream & os) const
1031 os << bformat(_("Macro: %1$s"), name());
1035 bool MathMacro::completionSupported(Cursor const & cur) const
1037 if (displayMode() != DISPLAY_UNFOLDED)
1038 return InsetMathNest::completionSupported(cur);
1040 return lyxrc.completion_popup_math
1041 && displayMode() == DISPLAY_UNFOLDED
1042 && cur.bv().cursor().pos() == int(name().size());
1046 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1048 if (displayMode() != DISPLAY_UNFOLDED)
1049 return InsetMathNest::inlineCompletionSupported(cur);
1051 return lyxrc.completion_inline_math
1052 && displayMode() == DISPLAY_UNFOLDED
1053 && cur.bv().cursor().pos() == int(name().size());
1057 bool MathMacro::automaticInlineCompletion() const
1059 if (displayMode() != DISPLAY_UNFOLDED)
1060 return InsetMathNest::automaticInlineCompletion();
1062 return lyxrc.completion_inline_math;
1066 bool MathMacro::automaticPopupCompletion() const
1068 if (displayMode() != DISPLAY_UNFOLDED)
1069 return InsetMathNest::automaticPopupCompletion();
1071 return lyxrc.completion_popup_math;
1075 CompletionList const *
1076 MathMacro::createCompletionList(Cursor const & cur) const
1078 if (displayMode() != DISPLAY_UNFOLDED)
1079 return InsetMathNest::createCompletionList(cur);
1081 return new MathCompletionList(cur.bv().cursor());
1085 docstring MathMacro::completionPrefix(Cursor const & cur) const
1087 if (displayMode() != DISPLAY_UNFOLDED)
1088 return InsetMathNest::completionPrefix(cur);
1090 if (!completionSupported(cur))
1093 return "\\" + name();
1097 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1100 if (displayMode() != DISPLAY_UNFOLDED)
1101 return InsetMathNest::insertCompletion(cur, s, finished);
1103 if (!completionSupported(cur))
1106 // append completion
1107 docstring newName = name() + s;
1108 asArray(newName, cell(0));
1109 cur.bv().cursor().pos() = name().size();
1110 cur.screenUpdateFlags(Update::SinglePar);
1114 cur.bv().cursor().pop();
1115 ++cur.bv().cursor().pos();
1116 cur.screenUpdateFlags(Update::SinglePar);
1123 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1124 Dimension & dim) const
1126 if (displayMode() != DISPLAY_UNFOLDED)
1127 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1129 // get inset dimensions
1130 dim = cur.bv().coordCache().insets().dim(this);
1131 // FIXME: these 3 are no accurate, but should depend on the font.
1132 // Now the popup jumps down if you enter a char with descent > 0.
1138 = cur.bv().coordCache().insets().xy(this);