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"
33 #include "MetricsInfo.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/RefChanger.h"
42 #include "support/textutils.h"
47 using namespace lyx::support;
53 /// A proxy for the macro values
54 class ArgumentProxy : public InsetMath {
57 ArgumentProxy(MathMacro * mathMacro, size_t idx)
58 : mathMacro_(mathMacro), idx_(idx) {}
60 ArgumentProxy(MathMacro * mathMacro, size_t idx, docstring const & def)
61 : mathMacro_(mathMacro), idx_(idx)
66 void setOwner(MathMacro * mathMacro) { mathMacro_ = mathMacro; }
68 MathMacro const * owner() { return mathMacro_; }
70 marker_type marker() const { return NO_MARKER; }
72 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
73 /// The math data to use for display
74 MathData const & displayCell(BufferView const * bv) const
76 // handle default macro arguments
77 bool use_def_arg = !mathMacro_->editMetrics(bv)
78 && mathMacro_->cell(idx_).empty();
79 return use_def_arg ? def_ : mathMacro_->cell(idx_);
82 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const
84 // macro arguments are in macros
85 LATTEST(mathMacro_->nesting() > 0);
86 /// The macro nesting can change display of insets. Change it locally.
87 Changer chg = make_change(mi.base.macro_nesting,
88 mathMacro_->nesting() == 1 ? 0 : mathMacro_->nesting());
90 MathRow::Element e_beg(mi, MathRow::BEG_ARG);
91 e_beg.macro = mathMacro_;
92 e_beg.ar = &mathMacro_->cell(idx_);
93 mrow.push_back(e_beg);
95 mathMacro_->macro()->unlock();
96 bool has_contents = displayCell(mi.base.bv).addToMathRow(mrow, mi);
97 mathMacro_->macro()->lock();
99 // if there was no contents, and the contents is editable,
100 // then we insert a box instead.
101 if (!has_contents && mathMacro_->nesting() == 1) {
102 // mathclass is ord because it should be spaced as a normal atom
103 MathRow::Element e(mi, MathRow::BOX, MC_ORD);
104 e.color = Color_mathline;
109 MathRow::Element e_end(mi, MathRow::END_ARG);
110 e_end.macro = mathMacro_;
111 e_end.ar = &mathMacro_->cell(idx_);
113 mrow.push_back(e_end);
118 void metrics(MetricsInfo &, Dimension &) const {
119 // This should never be invoked, since ArgumentProxy insets are linearized
123 int kerning(BufferView const * bv) const
125 return displayCell(bv).kerning(bv);
128 void draw(PainterInfo &, int, int) const {
129 // This should never be invoked, since ArgumentProxy insets are linearized
132 // write(), normalize(), infoize() and infoize2() are not needed since
133 // MathMacro uses the definition and not the expanded cells.
135 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
137 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
139 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
141 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
143 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
145 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
147 MathClass mathClass() const
150 // This can be refined once the pointer issues are fixed. I did not
151 // notice any immediate crash with the following code, but it is risky
153 //return mathMacro_->cell(idx_).mathClass();
158 Inset * clone() const
160 return new ArgumentProxy(*this);
163 MathMacro * mathMacro_;
171 /// Private implementation of MathMacro
172 class MathMacro::Private {
174 Private(Buffer * buf, docstring const & name)
175 : name_(name), displayMode_(DISPLAY_INIT),
176 expanded_(buf), definition_(buf), attachedArgsNum_(0),
177 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
178 macro_(0), needsUpdate_(false), isUpdating_(false),
182 /// Update the pointers to our owner of all expanded macros.
183 /// This needs to be called every time a copy of the owner is created
185 void updateChildren(MathMacro * owner);
186 /// Recursively update the pointers of all expanded macros
187 /// appearing in the arguments of the current macro
188 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
191 /// current display mode
192 DisplayMode displayMode_;
193 /// expanded macro with ArgumentProxies
195 /// macro definition with #1,#2,.. insets
196 MathData definition_;
197 /// number of arguments that were really attached
198 size_t attachedArgsNum_;
199 /// optional argument attached? (only in DISPLAY_NORMAL mode)
201 /// fold mode to be set in next metrics call?
203 /// if macro_ == true, then here is a copy of the macro
204 /// don't use it for locking
205 MacroData macroBackup_;
206 /// if macroNotFound_ == false, then here is a reference to the macro
207 /// this might invalidate after metrics was called
208 MacroData const * macro_;
210 mutable std::map<BufferView const *, bool> editing_;
212 std::string requires_;
213 /// update macro representation
217 /// maximal number of arguments the macro is greedy for
219 /// Level of nesting in macros (including this one)
224 void MathMacro::Private::updateChildren(MathMacro * owner)
226 for (size_t i = 0; i < expanded_.size(); ++i) {
227 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
231 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
233 updateNestedChildren(owner, ni);
237 // The macro_ pointer is updated when MathData::metrics() is
238 // called. However, when instant preview is on or the macro is
239 // not on screen, MathData::metrics() is not called and we may
240 // have a dangling pointer. As a safety measure, when a macro
241 // is copied, always let macro_ point to the backup copy of the
242 // MacroData structure. This backup is updated every time the
243 // macro is changed, so it will not become stale.
244 macro_ = ¯oBackup_;
249 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
251 for (size_t i = 0; i < ni->nargs(); ++i) {
252 MathData & ar = ni->cell(i);
253 for (size_t j = 0; j < ar.size(); ++j) {
254 ArgumentProxy * ap = dynamic_cast
255 <ArgumentProxy *>(ar[j].nucleus());
257 MathMacro::Private * md = ap->owner()->d;
259 md->macro_ = &md->macroBackup_;
262 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
264 updateNestedChildren(owner, imn);
270 MathMacro::MathMacro(Buffer * buf, docstring const & name)
271 : InsetMathNest(buf, 0), d(new Private(buf, name))
275 MathMacro::MathMacro(MathMacro const & that)
276 : InsetMathNest(that), d(new Private(*that.d))
278 setBuffer(*that.buffer_);
279 d->updateChildren(this);
283 MathMacro & MathMacro::operator=(MathMacro const & that)
287 InsetMathNest::operator=(that);
289 d->updateChildren(this);
294 MathMacro::~MathMacro()
300 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
302 // set edit mode for which we will have calculated row.
303 // This is the same as what is done in metrics().
304 d->editing_[mi.base.bv] = editMode(mi.base.bv);
306 if (displayMode() != MathMacro::DISPLAY_NORMAL
307 || d->editing_[mi.base.bv])
308 return InsetMath::addToMathRow(mrow, mi);
310 /// The macro nesting can change display of insets. Change it locally.
311 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
313 MathRow::Element e_beg(mi, MathRow::BEG_MACRO);
316 e_beg.marker = d->nesting_ == 1 ? marker() : NO_MARKER;
317 mrow.push_back(e_beg);
320 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
323 // if there was no contents and the array is editable, then we
324 // insert a grey box instead.
325 if (!has_contents && mi.base.macro_nesting == 1) {
326 // mathclass is unknown because it is irrelevant for spacing
327 MathRow::Element e(mi, MathRow::BOX);
328 e.color = Color_mathmacroblend;
333 MathRow::Element e_end(mi, MathRow::END_MACRO);
335 mrow.push_back(e_end);
341 Inset * MathMacro::clone() const
343 MathMacro * copy = new MathMacro(*this);
344 copy->d->needsUpdate_ = true;
345 //copy->d->expanded_.clear();
350 void MathMacro::normalize(NormalStream & os) const
352 os << "[macro " << name();
353 for (size_t i = 0; i < nargs(); ++i)
354 os << ' ' << cell(i);
359 MathMacro::DisplayMode MathMacro::displayMode() const
361 return d->displayMode_;
365 bool MathMacro::extraBraces() const
367 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
371 docstring MathMacro::name() const
373 if (d->displayMode_ == DISPLAY_UNFOLDED)
374 return asString(cell(0));
380 docstring MathMacro::macroName() const
386 int MathMacro::nesting() const
392 void MathMacro::cursorPos(BufferView const & bv,
393 CursorSlice const & sl, bool boundary, int & x, int & y) const
395 // We may have 0 arguments, but InsetMathNest requires at least one.
397 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
401 bool MathMacro::editMode(BufferView const * bv) const {
402 // find this in cursor trace
403 Cursor const & cur = bv->cursor();
404 for (size_t i = 0; i != cur.depth(); ++i)
405 if (&cur[i].inset() == this) {
406 // look if there is no other macro in edit mode above
408 for (; i != cur.depth(); ++i) {
409 InsetMath * im = cur[i].asInsetMath();
411 MathMacro const * macro = im->asMacro();
412 if (macro && macro->displayMode() == DISPLAY_NORMAL)
417 // ok, none found, I am the highest one
425 MacroData const * MathMacro::macro() const
431 bool MathMacro::editMetrics(BufferView const * bv) const
433 return d->editing_[bv];
437 Inset::marker_type MathMacro::marker() const
439 switch (d->displayMode_) {
441 case DISPLAY_INTERACTIVE_INIT:
443 case DISPLAY_UNFOLDED:
446 switch (lyxrc.macro_edit_style) {
447 case LyXRC::MACRO_EDIT_LIST:
449 case LyXRC::MACRO_EDIT_INLINE_BOX:
458 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
460 /// The macro nesting can change display of insets. Change it locally.
461 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
463 // set edit mode for which we will have calculated metrics. But only
464 d->editing_[mi.base.bv] = editMode(mi.base.bv);
466 // calculate new metrics according to display mode
467 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
468 Changer dummy = mi.base.changeFontSet("lyxtex");
469 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
470 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
471 Changer dummy = mi.base.changeFontSet("lyxtex");
472 cell(0).metrics(mi, dim);
474 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
475 dim.wid += bsdim.width() + 1;
476 dim.asc = max(bsdim.ascent(), dim.ascent());
477 dim.des = max(bsdim.descent(), dim.descent());
478 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
479 && d->editing_[mi.base.bv]) {
480 // Macro will be edited in a old-style list mode here:
484 FontInfo labelFont = sane_font;
485 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
487 // get dimension of components of list view
489 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
490 nameDim.asc = fontDim.asc;
491 nameDim.des = fontDim.des;
494 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
495 argDim.asc = fontDim.asc;
496 argDim.des = fontDim.des;
499 d->definition_.metrics(mi, defDim);
502 dim.wid = nameDim.wid + defDim.wid;
503 dim.asc = max(nameDim.asc, defDim.asc);
504 dim.des = max(nameDim.des, defDim.des);
506 for (idx_type i = 0; i < nargs(); ++i) {
508 cell(i).metrics(mi, cdim);
509 dim.des += max(argDim.height(), cdim.height()) + 1;
510 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
513 // make space for box and markers, 2 pixels
520 // calculate metrics, hoping that all cells are seen
522 d->expanded_.metrics(mi, dim);
524 // otherwise do a manual metrics call
525 CoordCache & coords = mi.base.bv->coordCache();
526 for (idx_type i = 0; i < nargs(); ++i) {
527 if (!coords.getArrays().hasDim(&cell(i))) {
529 cell(i).metrics(mi, tdim);
534 // calculate dimension with label while editing
535 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
536 && d->editing_[mi.base.bv]) {
537 FontInfo font = mi.base.font;
538 augmentFont(font, "lyxtex");
540 mathed_string_dim(font, name(), namedim);
542 dim.wid += 2 + namedim.wid + 2 + 2;
543 dim.asc = max(dim.asc, namedim.asc) + 2;
544 dim.des = max(dim.des, namedim.des) + 2;
546 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
547 dim.asc += 1 + namedim.height() + 1;
554 int MathMacro::kerning(BufferView const * bv) const {
555 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
556 return d->expanded_.kerning(bv);
562 void MathMacro::updateMacro(MacroContext const & mc)
565 d->macro_ = mc.get(name());
566 if (d->macro_ && d->macroBackup_ != *d->macro_) {
567 d->macroBackup_ = *d->macro_;
568 d->needsUpdate_ = true;
576 class MathMacro::UpdateLocker
579 explicit UpdateLocker(MathMacro & mm) : mac(mm)
581 mac.d->isUpdating_ = true;
583 ~UpdateLocker() { mac.d->isUpdating_ = false; }
587 /** Avoid wrong usage of UpdateLocker.
588 To avoid wrong usage:
589 UpdateLocker(...); // wrong
590 UpdateLocker locker(...); // right
592 #define UpdateLocker(x) unnamed_UpdateLocker;
593 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
596 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
597 UpdateType utype, int nesting)
599 // block recursive calls (bug 8999)
603 UpdateLocker locker(*this);
609 // remember nesting level of this macro
610 d->nesting_ = nesting;
613 d->requires_ = d->macro_->requires();
616 // non-normal mode? We are done!
617 || (d->displayMode_ != DISPLAY_NORMAL))
620 d->needsUpdate_ = false;
622 // get default values of macro
623 vector<docstring> const & defaults = d->macro_->defaults();
625 // create MathMacroArgumentValue objects pointing to the cells of the macro
626 vector<MathData> values(nargs());
627 for (size_t i = 0; i < nargs(); ++i) {
628 ArgumentProxy * proxy;
629 if (i < defaults.size())
630 proxy = new ArgumentProxy(this, i, defaults[i]);
632 proxy = new ArgumentProxy(this, i);
633 values[i].insert(0, MathAtom(proxy));
635 // expanding macro with the values
636 // Only update the argument macros if anything was expanded, otherwise
637 // we would get an endless loop (bug 9140). UpdateLocker does not work
638 // in this case, since MacroData::expand() creates new MathMacro
639 // objects, so this would be a different recursion path than the one
640 // protected by UpdateLocker.
641 if (d->macro_->expand(values, d->expanded_)) {
642 if (utype == OutputUpdate && !d->expanded_.empty())
643 d->expanded_.updateMacros(cur, mc, utype, nesting);
645 // get definition for list edit mode
646 docstring const & display = d->macro_->display();
647 asArray(display.empty() ? d->macro_->definition() : display,
648 d->definition_, Parse::QUIET);
652 void MathMacro::draw(PainterInfo & pi, int x, int y) const
654 Dimension const dim = dimension(*pi.base.bv);
659 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
660 Changer dummy = pi.base.changeFontSet("lyxtex");
661 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
662 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
663 Changer dummy = pi.base.changeFontSet("lyxtex");
664 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
665 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
666 cell(0).draw(pi, x, y);
667 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
668 && d->editing_[pi.base.bv]) {
669 // Macro will be edited in a old-style list mode here:
671 CoordCache const & coords = pi.base.bv->coordCache();
672 FontInfo const & labelFont = sane_font;
674 // box needs one pixel
677 // get maximal font height
679 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
682 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
683 pi.pain.text(x, y, label, labelFont);
684 x += mathed_string_width(labelFont, label);
687 d->definition_.draw(pi, x, y);
688 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
689 y += max(fontDim.des, defDim.des);
692 docstring str = from_ascii("#9");
693 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
694 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
696 for (idx_type i = 0; i < nargs(); ++i) {
698 Dimension const & cdim = coords.getArrays().dim(&cell(i));
700 y += max(fontDim.asc, cdim.asc) + 1;
704 pi.pain.text(x, y, str, labelFont);
706 pi.pain.text(x, y, from_ascii(":"), labelFont);
710 cell(i).draw(pi, x, y);
713 y += max(fontDim.des, cdim.des);
716 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 3,
717 dim.height() - 2, Color_mathmacroframe);
719 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
722 for (size_t i = 0; i < nargs(); ++i)
723 cell(i).setXY(*pi.base.bv, x, y);
725 if (drawBox && d->editing_[pi.base.bv]) {
726 // draw header and rectangle around
727 FontInfo font = pi.base.font;
728 augmentFont(font, "lyxtex");
729 font.setSize(FONT_SIZE_TINY);
730 font.setColor(Color_mathmacrolabel);
732 mathed_string_dim(font, name(), namedim);
734 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
735 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
736 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
739 if (d->editing_[pi.base.bv]) {
740 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
741 d->expanded_.draw(pi, expx, expy);
742 pi.pain.leaveMonochromeMode();
745 pi.pain.rectangle(x, y - dim.asc, dim.wid,
746 dim.height(), Color_mathmacroframe);
748 d->expanded_.draw(pi, expx, expy);
751 // edit mode changed?
752 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
753 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
757 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
759 // We may have 0 arguments, but InsetMathNest requires at least one.
761 InsetMathNest::drawSelection(pi, x, y);
765 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
767 if (d->displayMode_ != mode) {
768 // transfer name if changing from or to DISPLAY_UNFOLDED
769 if (mode == DISPLAY_UNFOLDED) {
771 asArray(d->name_, cell(0));
772 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
773 d->name_ = asString(cell(0));
777 d->displayMode_ = mode;
778 d->needsUpdate_ = true;
781 // the interactive init mode is non-greedy by default
783 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
785 d->appetite_ = size_t(appetite);
789 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
791 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
792 return DISPLAY_NORMAL;
794 return DISPLAY_UNFOLDED;
798 bool MathMacro::validName() const
800 docstring n = name();
805 // converting back and force doesn't swallow anything?
808 if (asString(ma) != n)
812 for (size_t i = 0; i<n.size(); ++i) {
813 if (!(n[i] >= 'a' && n[i] <= 'z')
814 && !(n[i] >= 'A' && n[i] <= 'Z')
823 size_t MathMacro::arity() const
825 if (d->displayMode_ == DISPLAY_NORMAL )
826 return cells_.size();
832 size_t MathMacro::optionals() const
834 return d->optionals_;
838 void MathMacro::setOptionals(int n)
840 if (n <= int(nargs()))
845 size_t MathMacro::appetite() const
851 MathClass MathMacro::mathClass() const
853 // This can be just a heuristic, since it is only considered for display
854 // when the macro is not linearised. Therefore it affects:
855 // * The spacing of the inset while being edited,
856 // * Intelligent splitting
857 // * Cursor word movement (Ctrl-Arrow).
858 if (MacroData const * m = macroBackup()) {
859 // If it is a global macro and is defined explicitly
861 MathClass mc = string_to_class(m->symbol()->extra);
862 if (mc != MC_UNKNOWN)
866 // Otherwise guess from the expanded macro
867 return d->expanded_.mathClass();
871 InsetMath::mode_type MathMacro::currentMode() const
873 // There is no way to guess the mode of user defined macros, so they are
874 // always assumed to be mathmode. Only the global macros defined in
875 // lib/symbols may be textmode.
876 mode_type mode = modeToEnsure();
877 return (mode == UNDECIDED_MODE) ? MATH_MODE : mode;
881 InsetMath::mode_type MathMacro::modeToEnsure() const
883 // User defined macros can be either text mode or math mode for output and
884 // display. There is no way to guess. For global macros defined in
885 // lib/symbols, we ensure textmode if flagged as such, otherwise we ensure
887 if (MacroData const * m = macroBackup())
889 return (m->symbol()->extra == "textmode") ? TEXT_MODE : MATH_MODE;
890 return UNDECIDED_MODE;
894 MacroData const * MathMacro::macroBackup() const
897 return &d->macroBackup_;
898 if (MacroData const * data = MacroTable::globalMacros().get(name()))
904 void MathMacro::validate(LaTeXFeatures & features) const
906 // Immediately after a document is loaded, in some cases the MacroData
907 // of the global macros defined in the lib/symbols file may still not
908 // be known to the macro machinery because it will be set only after
909 // the first call to updateMacros(). This is not a problem unless
910 // instant preview is on for math, in which case we will be missing
911 // the corresponding requirements.
912 // In this case, we get the required info from the global macro table.
913 if (!d->requires_.empty())
914 features.require(d->requires_);
915 else if (!d->macro_) {
916 // Update requires for known global macros.
917 MacroData const * data = MacroTable::globalMacros().get(name());
918 if (data && !data->requires().empty())
919 features.require(data->requires());
922 if (name() == "binom")
923 features.require("binom");
925 // validate the cells and the definition
926 if (displayMode() == DISPLAY_NORMAL) {
927 d->definition_.validate(features);
928 InsetMathNest::validate(features);
933 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
935 cur.screenUpdateFlags(Update::SinglePar);
936 InsetMathNest::edit(cur, front, entry_from);
940 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
942 // We may have 0 arguments, but InsetMathNest requires at least one.
944 cur.screenUpdateFlags(Update::SinglePar);
945 return InsetMathNest::editXY(cur, x, y);
951 void MathMacro::removeArgument(Inset::pos_type pos) {
952 if (d->displayMode_ == DISPLAY_NORMAL) {
953 LASSERT(size_t(pos) < cells_.size(), return);
954 cells_.erase(cells_.begin() + pos);
955 if (size_t(pos) < d->attachedArgsNum_)
956 --d->attachedArgsNum_;
957 if (size_t(pos) < d->optionals_) {
961 d->needsUpdate_ = true;
966 void MathMacro::insertArgument(Inset::pos_type pos) {
967 if (d->displayMode_ == DISPLAY_NORMAL) {
968 LASSERT(size_t(pos) <= cells_.size(), return);
969 cells_.insert(cells_.begin() + pos, MathData());
970 if (size_t(pos) < d->attachedArgsNum_)
971 ++d->attachedArgsNum_;
972 if (size_t(pos) < d->optionals_)
975 d->needsUpdate_ = true;
980 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
982 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
985 // strip off empty cells, but not more than arity-attachedArgsNum_
988 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
989 if (!cell(i - 1).empty()) break;
993 d->attachedArgsNum_ = 0;
994 d->expanded_ = MathData();
997 d->needsUpdate_ = true;
1001 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
1003 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1005 d->attachedArgsNum_ = args.size();
1006 cells_.resize(arity);
1007 d->expanded_ = MathData();
1008 d->optionals_ = optionals;
1010 d->needsUpdate_ = true;
1014 bool MathMacro::idxFirst(Cursor & cur) const
1016 cur.screenUpdateFlags(Update::SinglePar);
1017 return InsetMathNest::idxFirst(cur);
1021 bool MathMacro::idxLast(Cursor & cur) const
1023 cur.screenUpdateFlags(Update::SinglePar);
1024 return InsetMathNest::idxLast(cur);
1028 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1030 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1031 docstring const & unfolded_name = name();
1032 if (unfolded_name != d->name_) {
1033 // The macro name was changed
1034 Cursor inset_cursor = old;
1035 int macroSlice = inset_cursor.find(this);
1036 // returning true means the cursor is "now" invalid,
1038 LASSERT(macroSlice != -1, return true);
1039 inset_cursor.cutOff(macroSlice);
1040 inset_cursor.recordUndoInset();
1042 inset_cursor.cell().erase(inset_cursor.pos());
1043 inset_cursor.cell().insert(inset_cursor.pos(),
1044 createInsetMath(unfolded_name, cur.buffer()));
1046 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1050 cur.screenUpdateFlags(Update::Force);
1051 return InsetMathNest::notifyCursorLeaves(old, cur);
1055 void MathMacro::fold(Cursor & cur)
1057 if (!d->nextFoldMode_) {
1058 d->nextFoldMode_ = true;
1059 cur.screenUpdateFlags(Update::SinglePar);
1064 void MathMacro::unfold(Cursor & cur)
1066 if (d->nextFoldMode_) {
1067 d->nextFoldMode_ = false;
1068 cur.screenUpdateFlags(Update::SinglePar);
1073 bool MathMacro::folded() const
1075 return d->nextFoldMode_;
1079 void MathMacro::write(WriteStream & os) const
1081 mode_type mode = modeToEnsure();
1082 bool textmode_macro = mode == TEXT_MODE;
1083 bool needs_mathmode = mode == MATH_MODE;
1084 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1087 if (d->displayMode_ != DISPLAY_NORMAL) {
1088 os << "\\" << name();
1089 if (name().size() != 1 || isAlphaASCII(name()[0]))
1090 os.pendingSpace(true);
1095 // we should be ok to continue even if this fails.
1098 // We may already be in the argument of a macro
1099 bool const inside_macro = os.insideMacro();
1100 os.insideMacro(true);
1102 // Enclose in braces to avoid latex errors with xargs if we have
1103 // optional arguments and are in the optional argument of a macro
1104 if (d->optionals_ && inside_macro)
1107 // Always protect macros in a fragile environment
1111 os << "\\" << name();
1114 // Optional arguments:
1115 // First find last non-empty optional argument
1116 idx_type emptyOptFrom = 0;
1118 for (; i < cells_.size() && i < d->optionals_; ++i) {
1119 if (!cell(i).empty())
1120 emptyOptFrom = i + 1;
1123 // print out optionals
1124 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1126 os << "[" << cell(i) << "]";
1129 // skip the tailing empty optionals
1132 // Print remaining arguments
1133 for (; i < cells_.size(); ++i) {
1134 if (cell(i).size() == 1
1135 && cell(i)[0].nucleus()->asCharInset()
1136 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1141 os << "{" << cell(i) << "}";
1145 // Close the opened brace or add space if there was no argument
1146 if (d->optionals_ && inside_macro)
1149 os.pendingSpace(true);
1151 os.insideMacro(inside_macro);
1155 void MathMacro::maple(MapleStream & os) const
1157 lyx::maple(d->expanded_, os);
1161 void MathMacro::maxima(MaximaStream & os) const
1163 lyx::maxima(d->expanded_, os);
1167 void MathMacro::mathematica(MathematicaStream & os) const
1169 lyx::mathematica(d->expanded_, os);
1173 void MathMacro::mathmlize(MathStream & os) const
1175 // macro_ is 0 if this is an unknown macro
1176 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1178 docstring const xmlname = d->macro_->xmlname();
1179 if (!xmlname.empty()) {
1180 char const * type = d->macro_->MathMLtype();
1181 os << '<' << type << "> " << xmlname << " </"
1186 if (d->expanded_.empty()) {
1187 // this means that we do not recognize the macro
1188 throw MathExportException();
1194 void MathMacro::htmlize(HtmlStream & os) const
1196 // macro_ is 0 if this is an unknown macro
1197 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1199 docstring const xmlname = d->macro_->xmlname();
1200 if (!xmlname.empty()) {
1201 os << ' ' << xmlname << ' ';
1205 if (d->expanded_.empty()) {
1206 // this means that we do not recognize the macro
1207 throw MathExportException();
1213 void MathMacro::octave(OctaveStream & os) const
1215 lyx::octave(d->expanded_, os);
1219 void MathMacro::infoize(odocstream & os) const
1221 os << bformat(_("Macro: %1$s"), name());
1225 void MathMacro::infoize2(odocstream & os) const
1227 os << bformat(_("Macro: %1$s"), name());
1231 bool MathMacro::completionSupported(Cursor const & cur) const
1233 if (displayMode() != DISPLAY_UNFOLDED)
1234 return InsetMathNest::completionSupported(cur);
1236 return lyxrc.completion_popup_math
1237 && displayMode() == DISPLAY_UNFOLDED
1238 && cur.bv().cursor().pos() == int(name().size());
1242 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1244 if (displayMode() != DISPLAY_UNFOLDED)
1245 return InsetMathNest::inlineCompletionSupported(cur);
1247 return lyxrc.completion_inline_math
1248 && displayMode() == DISPLAY_UNFOLDED
1249 && cur.bv().cursor().pos() == int(name().size());
1253 bool MathMacro::automaticInlineCompletion() const
1255 if (displayMode() != DISPLAY_UNFOLDED)
1256 return InsetMathNest::automaticInlineCompletion();
1258 return lyxrc.completion_inline_math;
1262 bool MathMacro::automaticPopupCompletion() const
1264 if (displayMode() != DISPLAY_UNFOLDED)
1265 return InsetMathNest::automaticPopupCompletion();
1267 return lyxrc.completion_popup_math;
1271 CompletionList const *
1272 MathMacro::createCompletionList(Cursor const & cur) const
1274 if (displayMode() != DISPLAY_UNFOLDED)
1275 return InsetMathNest::createCompletionList(cur);
1277 return new MathCompletionList(cur.bv().cursor());
1281 docstring MathMacro::completionPrefix(Cursor const & cur) const
1283 if (displayMode() != DISPLAY_UNFOLDED)
1284 return InsetMathNest::completionPrefix(cur);
1286 if (!completionSupported(cur))
1289 return "\\" + name();
1293 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1296 if (displayMode() != DISPLAY_UNFOLDED)
1297 return InsetMathNest::insertCompletion(cur, s, finished);
1299 if (!completionSupported(cur))
1302 // append completion
1303 docstring newName = name() + s;
1304 asArray(newName, cell(0));
1305 cur.bv().cursor().pos() = name().size();
1306 cur.screenUpdateFlags(Update::SinglePar);
1310 cur.bv().cursor().pop();
1311 ++cur.bv().cursor().pos();
1312 cur.screenUpdateFlags(Update::SinglePar);
1319 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1320 Dimension & dim) const
1322 if (displayMode() != DISPLAY_UNFOLDED)
1323 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1325 // get inset dimensions
1326 dim = cur.bv().coordCache().insets().dim(this);
1327 // FIXME: these 3 are no accurate, but should depend on the font.
1328 // Now the popup jumps down if you enter a char with descent > 0.
1334 = cur.bv().coordCache().insets().xy(this);