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 // For now we do not linearize in the following cases (can be improved)
307 // - display mode different from normal
308 // - editing with parameter list
309 // - editing with box around macro
310 if (displayMode() != MathMacro::DISPLAY_NORMAL
311 || (d->editing_[mi.base.bv] && lyxrc.macro_edit_style != LyXRC::MACRO_EDIT_INLINE))
312 return InsetMath::addToMathRow(mrow, mi);
314 /// The macro nesting can change display of insets. Change it locally.
315 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
317 MathRow::Element e_beg(mi, MathRow::BEG_MACRO);
320 e_beg.marker = (d->nesting_ == 1 && nargs()) ? marker() : NO_MARKER;
321 mrow.push_back(e_beg);
324 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
327 // if there was no contents and the array is editable, then we
328 // insert a grey box instead.
329 if (!has_contents && mi.base.macro_nesting == 1) {
330 // mathclass is unknown because it is irrelevant for spacing
331 MathRow::Element e(mi, MathRow::BOX);
332 e.color = Color_mathmacroblend;
337 MathRow::Element e_end(mi, MathRow::END_MACRO);
339 mrow.push_back(e_end);
345 Inset * MathMacro::clone() const
347 MathMacro * copy = new MathMacro(*this);
348 copy->d->needsUpdate_ = true;
349 //copy->d->expanded_.clear();
354 void MathMacro::normalize(NormalStream & os) const
356 os << "[macro " << name();
357 for (size_t i = 0; i < nargs(); ++i)
358 os << ' ' << cell(i);
363 MathMacro::DisplayMode MathMacro::displayMode() const
365 return d->displayMode_;
369 bool MathMacro::extraBraces() const
371 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
375 docstring MathMacro::name() const
377 if (d->displayMode_ == DISPLAY_UNFOLDED)
378 return asString(cell(0));
384 docstring MathMacro::macroName() const
390 int MathMacro::nesting() const
396 void MathMacro::cursorPos(BufferView const & bv,
397 CursorSlice const & sl, bool boundary, int & x, int & y) const
399 // We may have 0 arguments, but InsetMathNest requires at least one.
401 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
405 bool MathMacro::editMode(BufferView const * bv) const {
406 // find this in cursor trace
407 Cursor const & cur = bv->cursor();
408 for (size_t i = 0; i != cur.depth(); ++i)
409 if (&cur[i].inset() == this) {
410 // look if there is no other macro in edit mode above
412 for (; i != cur.depth(); ++i) {
413 InsetMath * im = cur[i].asInsetMath();
415 MathMacro const * macro = im->asMacro();
416 if (macro && macro->displayMode() == DISPLAY_NORMAL)
421 // ok, none found, I am the highest one
429 MacroData const * MathMacro::macro() const
435 bool MathMacro::editMetrics(BufferView const * bv) const
437 return d->editing_[bv];
441 Inset::marker_type MathMacro::marker() const
443 switch (d->displayMode_) {
445 case DISPLAY_INTERACTIVE_INIT:
447 case DISPLAY_UNFOLDED:
450 switch (lyxrc.macro_edit_style) {
451 case LyXRC::MACRO_EDIT_LIST:
453 case LyXRC::MACRO_EDIT_INLINE_BOX:
462 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
464 /// The macro nesting can change display of insets. Change it locally.
465 Changer chg = make_change(mi.base.macro_nesting, d->nesting_);
467 // set edit mode for which we will have calculated metrics. But only
468 d->editing_[mi.base.bv] = editMode(mi.base.bv);
470 // calculate new metrics according to display mode
471 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
472 Changer dummy = mi.base.changeFontSet("lyxtex");
473 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
474 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
475 Changer dummy = mi.base.changeFontSet("lyxtex");
476 cell(0).metrics(mi, dim);
478 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
479 dim.wid += bsdim.width() + 1;
480 dim.asc = max(bsdim.ascent(), dim.ascent());
481 dim.des = max(bsdim.descent(), dim.descent());
482 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
483 && d->editing_[mi.base.bv]) {
484 // Macro will be edited in a old-style list mode here:
488 FontInfo labelFont = sane_font;
489 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
491 // get dimension of components of list view
493 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
494 nameDim.asc = fontDim.asc;
495 nameDim.des = fontDim.des;
498 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
499 argDim.asc = fontDim.asc;
500 argDim.des = fontDim.des;
503 d->definition_.metrics(mi, defDim);
506 dim.wid = nameDim.wid + defDim.wid;
507 dim.asc = max(nameDim.asc, defDim.asc);
508 dim.des = max(nameDim.des, defDim.des);
510 for (idx_type i = 0; i < nargs(); ++i) {
512 cell(i).metrics(mi, cdim);
513 dim.des += max(argDim.height(), cdim.height()) + 1;
514 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
517 // make space for box and markers, 2 pixels
524 // calculate metrics, hoping that all cells are seen
526 d->expanded_.metrics(mi, dim);
528 // otherwise do a manual metrics call
529 CoordCache & coords = mi.base.bv->coordCache();
530 for (idx_type i = 0; i < nargs(); ++i) {
531 if (!coords.getArrays().hasDim(&cell(i))) {
533 cell(i).metrics(mi, tdim);
538 // calculate dimension with label while editing
539 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
540 && d->editing_[mi.base.bv]) {
541 FontInfo font = mi.base.font;
542 augmentFont(font, "lyxtex");
544 mathed_string_dim(font, name(), namedim);
546 dim.wid += 2 + namedim.wid + 2 + 2;
547 dim.asc = max(dim.asc, namedim.asc) + 2;
548 dim.des = max(dim.des, namedim.des) + 2;
550 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
551 dim.asc += 1 + namedim.height() + 1;
558 int MathMacro::kerning(BufferView const * bv) const {
559 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
560 return d->expanded_.kerning(bv);
566 void MathMacro::updateMacro(MacroContext const & mc)
569 d->macro_ = mc.get(name());
570 if (d->macro_ && d->macroBackup_ != *d->macro_) {
571 d->macroBackup_ = *d->macro_;
572 d->needsUpdate_ = true;
580 class MathMacro::UpdateLocker
583 explicit UpdateLocker(MathMacro & mm) : mac(mm)
585 mac.d->isUpdating_ = true;
587 ~UpdateLocker() { mac.d->isUpdating_ = false; }
591 /** Avoid wrong usage of UpdateLocker.
592 To avoid wrong usage:
593 UpdateLocker(...); // wrong
594 UpdateLocker locker(...); // right
596 #define UpdateLocker(x) unnamed_UpdateLocker;
597 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
600 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
601 UpdateType utype, int nesting)
603 // block recursive calls (bug 8999)
607 UpdateLocker locker(*this);
613 // remember nesting level of this macro
614 d->nesting_ = nesting;
617 d->requires_ = d->macro_->requires();
620 // non-normal mode? We are done!
621 || (d->displayMode_ != DISPLAY_NORMAL))
624 d->needsUpdate_ = false;
626 // get default values of macro
627 vector<docstring> const & defaults = d->macro_->defaults();
629 // create MathMacroArgumentValue objects pointing to the cells of the macro
630 vector<MathData> values(nargs());
631 for (size_t i = 0; i < nargs(); ++i) {
632 ArgumentProxy * proxy;
633 if (i < defaults.size())
634 proxy = new ArgumentProxy(this, i, defaults[i]);
636 proxy = new ArgumentProxy(this, i);
637 values[i].insert(0, MathAtom(proxy));
639 // expanding macro with the values
640 // Only update the argument macros if anything was expanded, otherwise
641 // we would get an endless loop (bug 9140). UpdateLocker does not work
642 // in this case, since MacroData::expand() creates new MathMacro
643 // objects, so this would be a different recursion path than the one
644 // protected by UpdateLocker.
645 if (d->macro_->expand(values, d->expanded_)) {
646 if (utype == OutputUpdate && !d->expanded_.empty())
647 d->expanded_.updateMacros(cur, mc, utype, nesting);
649 // get definition for list edit mode
650 docstring const & display = d->macro_->display();
651 asArray(display.empty() ? d->macro_->definition() : display,
652 d->definition_, Parse::QUIET);
656 void MathMacro::draw(PainterInfo & pi, int x, int y) const
658 Dimension const dim = dimension(*pi.base.bv);
663 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
664 Changer dummy = pi.base.changeFontSet("lyxtex");
665 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
666 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
667 Changer dummy = pi.base.changeFontSet("lyxtex");
668 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
669 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
670 cell(0).draw(pi, x, y);
671 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
672 && d->editing_[pi.base.bv]) {
673 // Macro will be edited in a old-style list mode here:
675 CoordCache const & coords = pi.base.bv->coordCache();
676 FontInfo const & labelFont = sane_font;
678 // box needs one pixel
681 // get maximal font height
683 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
686 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
687 pi.pain.text(x, y, label, labelFont);
688 x += mathed_string_width(labelFont, label);
691 d->definition_.draw(pi, x, y);
692 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
693 y += max(fontDim.des, defDim.des);
696 docstring str = from_ascii("#9");
697 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
698 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
700 for (idx_type i = 0; i < nargs(); ++i) {
702 Dimension const & cdim = coords.getArrays().dim(&cell(i));
704 y += max(fontDim.asc, cdim.asc) + 1;
708 pi.pain.text(x, y, str, labelFont);
710 pi.pain.text(x, y, from_ascii(":"), labelFont);
714 cell(i).draw(pi, x, y);
717 y += max(fontDim.des, cdim.des);
720 pi.pain.rectangle(expx, expy - dim.asc + 1, dim.wid - 3,
721 dim.height() - 2, Color_mathmacroframe);
723 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
726 for (size_t i = 0; i < nargs(); ++i)
727 cell(i).setXY(*pi.base.bv, x, y);
729 if (drawBox && d->editing_[pi.base.bv]) {
730 // draw header and rectangle around
731 FontInfo font = pi.base.font;
732 augmentFont(font, "lyxtex");
733 font.setSize(FONT_SIZE_TINY);
734 font.setColor(Color_mathmacrolabel);
736 mathed_string_dim(font, name(), namedim);
738 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
739 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
740 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
743 if (d->editing_[pi.base.bv]) {
744 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
745 d->expanded_.draw(pi, expx, expy);
746 pi.pain.leaveMonochromeMode();
749 pi.pain.rectangle(x, y - dim.asc, dim.wid,
750 dim.height(), Color_mathmacroframe);
752 d->expanded_.draw(pi, expx, expy);
755 // edit mode changed?
756 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
757 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
761 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
763 // We may have 0 arguments, but InsetMathNest requires at least one.
765 InsetMathNest::drawSelection(pi, x, y);
769 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
771 if (d->displayMode_ != mode) {
772 // transfer name if changing from or to DISPLAY_UNFOLDED
773 if (mode == DISPLAY_UNFOLDED) {
775 asArray(d->name_, cell(0));
776 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
777 d->name_ = asString(cell(0));
781 d->displayMode_ = mode;
782 d->needsUpdate_ = true;
785 // the interactive init mode is non-greedy by default
787 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
789 d->appetite_ = size_t(appetite);
793 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
795 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
796 return DISPLAY_NORMAL;
798 return DISPLAY_UNFOLDED;
802 bool MathMacro::validName() const
804 docstring n = name();
809 // converting back and force doesn't swallow anything?
812 if (asString(ma) != n)
816 for (size_t i = 0; i<n.size(); ++i) {
817 if (!(n[i] >= 'a' && n[i] <= 'z')
818 && !(n[i] >= 'A' && n[i] <= 'Z')
827 size_t MathMacro::arity() const
829 if (d->displayMode_ == DISPLAY_NORMAL )
830 return cells_.size();
836 size_t MathMacro::optionals() const
838 return d->optionals_;
842 void MathMacro::setOptionals(int n)
844 if (n <= int(nargs()))
849 size_t MathMacro::appetite() const
855 MathClass MathMacro::mathClass() const
857 // This can be just a heuristic, since it is only considered for display
858 // when the macro is not linearised. Therefore it affects:
859 // * The spacing of the inset while being edited,
860 // * Intelligent splitting
861 // * Cursor word movement (Ctrl-Arrow).
862 if (MacroData const * m = macroBackup()) {
863 // If it is a global macro and is defined explicitly
865 MathClass mc = string_to_class(m->symbol()->extra);
866 if (mc != MC_UNKNOWN)
870 // Otherwise guess from the expanded macro
871 return d->expanded_.mathClass();
875 InsetMath::mode_type MathMacro::currentMode() const
877 // There is no way to guess the mode of user defined macros, so they are
878 // always assumed to be mathmode. Only the global macros defined in
879 // lib/symbols may be textmode.
880 mode_type mode = modeToEnsure();
881 return (mode == UNDECIDED_MODE) ? MATH_MODE : mode;
885 InsetMath::mode_type MathMacro::modeToEnsure() const
887 // User defined macros can be either text mode or math mode for output and
888 // display. There is no way to guess. For global macros defined in
889 // lib/symbols, we ensure textmode if flagged as such, otherwise we ensure
891 if (MacroData const * m = macroBackup())
893 return (m->symbol()->extra == "textmode") ? TEXT_MODE : MATH_MODE;
894 return UNDECIDED_MODE;
898 MacroData const * MathMacro::macroBackup() const
901 return &d->macroBackup_;
902 if (MacroData const * data = MacroTable::globalMacros().get(name()))
908 void MathMacro::validate(LaTeXFeatures & features) const
910 // Immediately after a document is loaded, in some cases the MacroData
911 // of the global macros defined in the lib/symbols file may still not
912 // be known to the macro machinery because it will be set only after
913 // the first call to updateMacros(). This is not a problem unless
914 // instant preview is on for math, in which case we will be missing
915 // the corresponding requirements.
916 // In this case, we get the required info from the global macro table.
917 if (!d->requires_.empty())
918 features.require(d->requires_);
919 else if (!d->macro_) {
920 // Update requires for known global macros.
921 MacroData const * data = MacroTable::globalMacros().get(name());
922 if (data && !data->requires().empty())
923 features.require(data->requires());
926 if (name() == "binom")
927 features.require("binom");
929 // validate the cells and the definition
930 if (displayMode() == DISPLAY_NORMAL) {
931 d->definition_.validate(features);
932 InsetMathNest::validate(features);
937 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
939 cur.screenUpdateFlags(Update::SinglePar);
940 InsetMathNest::edit(cur, front, entry_from);
944 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
946 // We may have 0 arguments, but InsetMathNest requires at least one.
948 cur.screenUpdateFlags(Update::SinglePar);
949 return InsetMathNest::editXY(cur, x, y);
955 void MathMacro::removeArgument(Inset::pos_type pos) {
956 if (d->displayMode_ == DISPLAY_NORMAL) {
957 LASSERT(size_t(pos) < cells_.size(), return);
958 cells_.erase(cells_.begin() + pos);
959 if (size_t(pos) < d->attachedArgsNum_)
960 --d->attachedArgsNum_;
961 if (size_t(pos) < d->optionals_) {
965 d->needsUpdate_ = true;
970 void MathMacro::insertArgument(Inset::pos_type pos) {
971 if (d->displayMode_ == DISPLAY_NORMAL) {
972 LASSERT(size_t(pos) <= cells_.size(), return);
973 cells_.insert(cells_.begin() + pos, MathData());
974 if (size_t(pos) < d->attachedArgsNum_)
975 ++d->attachedArgsNum_;
976 if (size_t(pos) < d->optionals_)
979 d->needsUpdate_ = true;
984 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
986 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
989 // strip off empty cells, but not more than arity-attachedArgsNum_
992 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
993 if (!cell(i - 1).empty()) break;
997 d->attachedArgsNum_ = 0;
998 d->expanded_ = MathData();
1001 d->needsUpdate_ = true;
1005 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
1007 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
1009 d->attachedArgsNum_ = args.size();
1010 cells_.resize(arity);
1011 d->expanded_ = MathData();
1012 d->optionals_ = optionals;
1014 d->needsUpdate_ = true;
1018 bool MathMacro::idxFirst(Cursor & cur) const
1020 cur.screenUpdateFlags(Update::SinglePar);
1021 return InsetMathNest::idxFirst(cur);
1025 bool MathMacro::idxLast(Cursor & cur) const
1027 cur.screenUpdateFlags(Update::SinglePar);
1028 return InsetMathNest::idxLast(cur);
1032 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1034 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1035 docstring const & unfolded_name = name();
1036 if (unfolded_name != d->name_) {
1037 // The macro name was changed
1038 Cursor inset_cursor = old;
1039 int macroSlice = inset_cursor.find(this);
1040 // returning true means the cursor is "now" invalid,
1042 LASSERT(macroSlice != -1, return true);
1043 inset_cursor.cutOff(macroSlice);
1044 inset_cursor.recordUndoInset();
1046 inset_cursor.cell().erase(inset_cursor.pos());
1047 inset_cursor.cell().insert(inset_cursor.pos(),
1048 createInsetMath(unfolded_name, cur.buffer()));
1050 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1054 cur.screenUpdateFlags(Update::Force);
1055 return InsetMathNest::notifyCursorLeaves(old, cur);
1059 void MathMacro::fold(Cursor & cur)
1061 if (!d->nextFoldMode_) {
1062 d->nextFoldMode_ = true;
1063 cur.screenUpdateFlags(Update::SinglePar);
1068 void MathMacro::unfold(Cursor & cur)
1070 if (d->nextFoldMode_) {
1071 d->nextFoldMode_ = false;
1072 cur.screenUpdateFlags(Update::SinglePar);
1077 bool MathMacro::folded() const
1079 return d->nextFoldMode_;
1083 void MathMacro::write(WriteStream & os) const
1085 mode_type mode = modeToEnsure();
1086 bool textmode_macro = mode == TEXT_MODE;
1087 bool needs_mathmode = mode == MATH_MODE;
1088 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1091 if (d->displayMode_ != DISPLAY_NORMAL) {
1092 os << "\\" << name();
1093 if (name().size() != 1 || isAlphaASCII(name()[0]))
1094 os.pendingSpace(true);
1099 // we should be ok to continue even if this fails.
1102 // We may already be in the argument of a macro
1103 bool const inside_macro = os.insideMacro();
1104 os.insideMacro(true);
1106 // Enclose in braces to avoid latex errors with xargs if we have
1107 // optional arguments and are in the optional argument of a macro
1108 if (d->optionals_ && inside_macro)
1111 // Always protect macros in a fragile environment
1115 os << "\\" << name();
1118 // Optional arguments:
1119 // First find last non-empty optional argument
1120 idx_type emptyOptFrom = 0;
1122 for (; i < cells_.size() && i < d->optionals_; ++i) {
1123 if (!cell(i).empty())
1124 emptyOptFrom = i + 1;
1127 // print out optionals
1128 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1130 os << "[" << cell(i) << "]";
1133 // skip the tailing empty optionals
1136 // Print remaining arguments
1137 for (; i < cells_.size(); ++i) {
1138 if (cell(i).size() == 1
1139 && cell(i)[0].nucleus()->asCharInset()
1140 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1145 os << "{" << cell(i) << "}";
1149 // Close the opened brace or add space if there was no argument
1150 if (d->optionals_ && inside_macro)
1153 os.pendingSpace(true);
1155 os.insideMacro(inside_macro);
1159 void MathMacro::maple(MapleStream & os) const
1161 lyx::maple(d->expanded_, os);
1165 void MathMacro::maxima(MaximaStream & os) const
1167 lyx::maxima(d->expanded_, os);
1171 void MathMacro::mathematica(MathematicaStream & os) const
1173 lyx::mathematica(d->expanded_, os);
1177 void MathMacro::mathmlize(MathStream & os) const
1179 // macro_ is 0 if this is an unknown macro
1180 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1182 docstring const xmlname = d->macro_->xmlname();
1183 if (!xmlname.empty()) {
1184 char const * type = d->macro_->MathMLtype();
1185 os << '<' << type << "> " << xmlname << " </"
1190 if (d->expanded_.empty()) {
1191 // this means that we do not recognize the macro
1192 throw MathExportException();
1198 void MathMacro::htmlize(HtmlStream & os) const
1200 // macro_ is 0 if this is an unknown macro
1201 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1203 docstring const xmlname = d->macro_->xmlname();
1204 if (!xmlname.empty()) {
1205 os << ' ' << xmlname << ' ';
1209 if (d->expanded_.empty()) {
1210 // this means that we do not recognize the macro
1211 throw MathExportException();
1217 void MathMacro::octave(OctaveStream & os) const
1219 lyx::octave(d->expanded_, os);
1223 void MathMacro::infoize(odocstream & os) const
1225 os << bformat(_("Macro: %1$s"), name());
1229 void MathMacro::infoize2(odocstream & os) const
1231 os << bformat(_("Macro: %1$s"), name());
1235 bool MathMacro::completionSupported(Cursor const & cur) const
1237 if (displayMode() != DISPLAY_UNFOLDED)
1238 return InsetMathNest::completionSupported(cur);
1240 return lyxrc.completion_popup_math
1241 && displayMode() == DISPLAY_UNFOLDED
1242 && cur.bv().cursor().pos() == int(name().size());
1246 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1248 if (displayMode() != DISPLAY_UNFOLDED)
1249 return InsetMathNest::inlineCompletionSupported(cur);
1251 return lyxrc.completion_inline_math
1252 && displayMode() == DISPLAY_UNFOLDED
1253 && cur.bv().cursor().pos() == int(name().size());
1257 bool MathMacro::automaticInlineCompletion() const
1259 if (displayMode() != DISPLAY_UNFOLDED)
1260 return InsetMathNest::automaticInlineCompletion();
1262 return lyxrc.completion_inline_math;
1266 bool MathMacro::automaticPopupCompletion() const
1268 if (displayMode() != DISPLAY_UNFOLDED)
1269 return InsetMathNest::automaticPopupCompletion();
1271 return lyxrc.completion_popup_math;
1275 CompletionList const *
1276 MathMacro::createCompletionList(Cursor const & cur) const
1278 if (displayMode() != DISPLAY_UNFOLDED)
1279 return InsetMathNest::createCompletionList(cur);
1281 return new MathCompletionList(cur.bv().cursor());
1285 docstring MathMacro::completionPrefix(Cursor const & cur) const
1287 if (displayMode() != DISPLAY_UNFOLDED)
1288 return InsetMathNest::completionPrefix(cur);
1290 if (!completionSupported(cur))
1293 return "\\" + name();
1297 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1300 if (displayMode() != DISPLAY_UNFOLDED)
1301 return InsetMathNest::insertCompletion(cur, s, finished);
1303 if (!completionSupported(cur))
1306 // append completion
1307 docstring newName = name() + s;
1308 asArray(newName, cell(0));
1309 cur.bv().cursor().pos() = name().size();
1310 cur.screenUpdateFlags(Update::SinglePar);
1314 cur.bv().cursor().pop();
1315 ++cur.bv().cursor().pos();
1316 cur.screenUpdateFlags(Update::SinglePar);
1323 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1324 Dimension & dim) const
1326 if (displayMode() != DISPLAY_UNFOLDED)
1327 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1329 // get inset dimensions
1330 dim = cur.bv().coordCache().insets().dim(this);
1331 // FIXME: these 3 are no accurate, but should depend on the font.
1332 // Now the popup jumps down if you enter a char with descent > 0.
1338 = cur.bv().coordCache().insets().xy(this);