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/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 MathMacro const * owner() { return mathMacro_; }
69 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
71 bool addToMathRow(MathRow & mrow, MetricsInfo & mi) const
73 // macro arguments are in macros
74 LATTEST(mi.base.macro_nesting > 0);
75 if (mi.base.macro_nesting == 1)
76 mi.base.macro_nesting = 0;
78 MathRow::Element e_beg(MathRow::BEG_ARG, mi);
79 e_beg.macro = mathMacro_;
80 e_beg.ar = &mathMacro_->cell(idx_);
81 mrow.push_back(e_beg);
83 mathMacro_->macro()->unlock();
85 // handle default macro arguments
86 if (!mathMacro_->editMetrics(mi.base.bv)
87 && mathMacro_->cell(idx_).empty())
88 has_contents = def_.addToMathRow(mrow, mi);
90 has_contents = mathMacro_->cell(idx_).addToMathRow(mrow, mi);
91 mathMacro_->macro()->lock();
93 // if there was no contents, and the contents is editable,
94 // then we insert a box instead.
95 if (!has_contents && mi.base.macro_nesting == 0) {
96 MathRow::Element e(MathRow::BOX, mi);
97 e.color = Color_mathline;
102 if (mi.base.macro_nesting == 0)
103 mi.base.macro_nesting = 1;
105 MathRow::Element e_end(MathRow::END_ARG, mi);
106 e_end.macro = mathMacro_;
107 e_end.ar = &mathMacro_->cell(idx_);
109 mrow.push_back(e_end);
114 void metrics(MetricsInfo & mi, Dimension & dim) const {
115 // macro arguments are in macros
116 LATTEST(mi.base.macro_nesting > 0);
117 if (mi.base.macro_nesting == 1)
118 mi.base.macro_nesting = 0;
120 mathMacro_->macro()->unlock();
121 mathMacro_->cell(idx_).metrics(mi, dim);
123 if (!mathMacro_->editMetrics(mi.base.bv)
124 && mathMacro_->cell(idx_).empty())
125 def_.metrics(mi, dim);
127 mathMacro_->macro()->lock();
128 if (mi.base.macro_nesting == 0)
129 mi.base.macro_nesting = 1;
131 // write(), normalize(), infoize() and infoize2() are not needed since
132 // MathMacro uses the definition and not the expanded cells.
134 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
136 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
138 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
140 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
142 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
144 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
146 void draw(PainterInfo & pi, int x, int y) const {
147 LATTEST(pi.base.macro_nesting > 0);
148 if (pi.base.macro_nesting == 1)
149 pi.base.macro_nesting = 0;
151 if (mathMacro_->editMetrics(pi.base.bv)) {
152 // The only way a ArgumentProxy can appear is in a cell of the
153 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
154 // mode and then, if the macro is edited the monochrome
155 // mode is entered by the MathMacro before calling the cells' draw
156 // method. Then eventually this code is reached and the proxy leaves
157 // monochrome mode temporarely. Hence, if it is not in monochrome
158 // here (and the assert triggers in pain.leaveMonochromeMode())
160 pi.pain.leaveMonochromeMode();
161 mathMacro_->cell(idx_).draw(pi, x, y);
162 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
163 } else if (mathMacro_->cell(idx_).empty()) {
164 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
167 mathMacro_->cell(idx_).draw(pi, x, y);
169 if (pi.base.macro_nesting == 0)
170 pi.base.macro_nesting = 1;
173 size_t idx() const { return idx_; }
175 int kerning(BufferView const * bv) const
177 if (mathMacro_->editMetrics(bv)
178 || !mathMacro_->cell(idx_).empty())
179 return mathMacro_->cell(idx_).kerning(bv);
181 return def_.kerning(bv);
186 Inset * clone() const
188 return new ArgumentProxy(*this);
191 MathMacro * mathMacro_;
199 /// Private implementation of MathMacro
200 class MathMacro::Private {
202 Private(Buffer * buf, docstring const & name)
203 : name_(name), displayMode_(DISPLAY_INIT),
204 expanded_(buf), definition_(buf), attachedArgsNum_(0),
205 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
206 macro_(0), needsUpdate_(false), isUpdating_(false),
210 /// Update the pointers to our owner of all expanded macros.
211 /// This needs to be called every time a copy of the owner is created
213 void updateChildren(MathMacro * owner);
214 /// Recursively update the pointers of all expanded macros
215 /// appearing in the arguments of the current macro
216 void updateNestedChildren(MathMacro * owner, InsetMathNest * ni);
219 /// current display mode
220 DisplayMode displayMode_;
221 /// expanded macro with ArgumentProxies
223 /// macro definition with #1,#2,.. insets
224 MathData definition_;
225 /// number of arguments that were really attached
226 size_t attachedArgsNum_;
227 /// optional argument attached? (only in DISPLAY_NORMAL mode)
229 /// fold mode to be set in next metrics call?
231 /// if macro_ == true, then here is a copy of the macro
232 /// don't use it for locking
233 MacroData macroBackup_;
234 /// if macroNotFound_ == false, then here is a reference to the macro
235 /// this might invalidate after metrics was called
236 MacroData const * macro_;
238 mutable std::map<BufferView const *, bool> editing_;
240 std::string requires_;
241 /// update macro representation
245 /// maximal number of arguments the macro is greedy for
250 void MathMacro::Private::updateChildren(MathMacro * owner)
252 for (size_t i = 0; i < expanded_.size(); ++i) {
253 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
257 InsetMathNest * ni = expanded_[i].nucleus()->asNestInset();
259 updateNestedChildren(owner, ni);
263 // The macro_ pointer is updated when MathData::metrics() is
264 // called. However, when instant preview is on or the macro is
265 // not on screen, MathData::metrics() is not called and we may
266 // have a dangling pointer. As a safety measure, when a macro
267 // is copied, always let macro_ point to the backup copy of the
268 // MacroData structure. This backup is updated every time the
269 // macro is changed, so it will not become stale.
270 macro_ = ¯oBackup_;
275 void MathMacro::Private::updateNestedChildren(MathMacro * owner, InsetMathNest * ni)
277 for (size_t i = 0; i < ni->nargs(); ++i) {
278 MathData & ar = ni->cell(i);
279 for (size_t j = 0; j < ar.size(); ++j) {
280 ArgumentProxy * ap = dynamic_cast
281 <ArgumentProxy *>(ar[j].nucleus());
283 MathMacro::Private * md = ap->owner()->d;
285 md->macro_ = &md->macroBackup_;
288 InsetMathNest * imn = ar[j].nucleus()->asNestInset();
290 updateNestedChildren(owner, imn);
296 MathMacro::MathMacro(Buffer * buf, docstring const & name)
297 : InsetMathNest(buf, 0), d(new Private(buf, name))
301 MathMacro::MathMacro(MathMacro const & that)
302 : InsetMathNest(that), d(new Private(*that.d))
304 setBuffer(*that.buffer_);
305 d->updateChildren(this);
309 MathMacro & MathMacro::operator=(MathMacro const & that)
313 InsetMathNest::operator=(that);
315 d->updateChildren(this);
320 MathMacro::~MathMacro()
326 bool MathMacro::addToMathRow(MathRow & mrow, MetricsInfo & mi) const
328 // set edit mode for which we will have calculated row.
329 // This is the same as what is done in metrics().
330 d->editing_[mi.base.bv] = editMode(mi.base.bv);
332 if (displayMode() != MathMacro::DISPLAY_NORMAL
333 || d->editing_[mi.base.bv])
334 return InsetMath::addToMathRow(mrow, mi);
336 MathRow::Element e_beg(MathRow::BEG_MACRO, mi);
338 mrow.push_back(e_beg);
340 ++mi.base.macro_nesting;
343 bool has_contents = d->expanded_.addToMathRow(mrow, mi);
346 // if there was no contents and the array is editable, then we
347 // insert a grey box instead.
348 if (!has_contents && mi.base.macro_nesting == 1) {
349 MathRow::Element e(MathRow::BOX, mi);
350 e.color = Color_mathmacroblend;
355 --mi.base.macro_nesting;
357 MathRow::Element e_end(MathRow::END_MACRO, mi);
359 mrow.push_back(e_end);
365 Inset * MathMacro::clone() const
367 MathMacro * copy = new MathMacro(*this);
368 copy->d->needsUpdate_ = true;
369 //copy->d->expanded_.clear();
374 void MathMacro::normalize(NormalStream & os) const
376 os << "[macro " << name();
377 for (size_t i = 0; i < nargs(); ++i)
378 os << ' ' << cell(i);
383 MathMacro::DisplayMode MathMacro::displayMode() const
385 return d->displayMode_;
389 bool MathMacro::extraBraces() const
391 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
395 docstring MathMacro::name() const
397 if (d->displayMode_ == DISPLAY_UNFOLDED)
398 return asString(cell(0));
404 docstring MathMacro::macroName() const
410 void MathMacro::cursorPos(BufferView const & bv,
411 CursorSlice const & sl, bool boundary, int & x, int & y) const
413 // We may have 0 arguments, but InsetMathNest requires at least one.
415 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
419 bool MathMacro::editMode(BufferView const * bv) const {
420 // find this in cursor trace
421 Cursor const & cur = bv->cursor();
422 for (size_t i = 0; i != cur.depth(); ++i)
423 if (&cur[i].inset() == this) {
424 // look if there is no other macro in edit mode above
426 for (; i != cur.depth(); ++i) {
427 InsetMath * im = cur[i].asInsetMath();
429 MathMacro const * macro = im->asMacro();
430 if (macro && macro->displayMode() == DISPLAY_NORMAL)
435 // ok, none found, I am the highest one
443 MacroData const * MathMacro::macro() const
449 bool MathMacro::editMetrics(BufferView const * bv) const
451 return d->editing_[bv];
455 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
457 // the macro contents is not editable (except the arguments)
458 ++mi.base.macro_nesting;
460 // set edit mode for which we will have calculated metrics. But only
461 d->editing_[mi.base.bv] = editMode(mi.base.bv);
463 // calculate new metrics according to display mode
464 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
465 Changer dummy = mi.base.changeFontSet("lyxtex");
466 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
467 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
468 Changer dummy = mi.base.changeFontSet("lyxtex");
469 cell(0).metrics(mi, dim);
471 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
472 dim.wid += bsdim.width() + 1;
473 dim.asc = max(bsdim.ascent(), dim.ascent());
474 dim.des = max(bsdim.descent(), dim.descent());
475 metricsMarkers(mi, dim);
476 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
477 && d->editing_[mi.base.bv]) {
478 // Macro will be edited in a old-style list mode here:
482 FontInfo labelFont = sane_font;
483 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
485 // get dimension of components of list view
487 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
488 nameDim.asc = fontDim.asc;
489 nameDim.des = fontDim.des;
492 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
493 argDim.asc = fontDim.asc;
494 argDim.des = fontDim.des;
497 d->definition_.metrics(mi, defDim);
500 dim.wid = nameDim.wid + defDim.wid;
501 dim.asc = max(nameDim.asc, defDim.asc);
502 dim.des = max(nameDim.des, defDim.des);
504 for (idx_type i = 0; i < nargs(); ++i) {
506 cell(i).metrics(mi, cdim);
507 dim.des += max(argDim.height(), cdim.height()) + 1;
508 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
511 // make space for box and markers, 2 pixels
515 metricsMarkers2(mi, dim);
519 Changer dummy = (currentMode() == TEXT_MODE)
520 ? mi.base.font.changeShape(UP_SHAPE)
523 // calculate metrics, hoping that all cells are seen
525 d->expanded_.metrics(mi, dim);
527 // otherwise do a manual metrics call
528 CoordCache & coords = mi.base.bv->coordCache();
529 for (idx_type i = 0; i < nargs(); ++i) {
530 if (!coords.getArrays().hasDim(&cell(i))) {
532 cell(i).metrics(mi, tdim);
537 // calculate dimension with label while editing
538 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
539 && d->editing_[mi.base.bv]) {
540 FontInfo font = mi.base.font;
541 augmentFont(font, "lyxtex");
543 mathed_string_dim(font, name(), namedim);
545 dim.wid += 2 + namedim.wid + 2 + 2;
546 dim.asc = max(dim.asc, namedim.asc) + 2;
547 dim.des = max(dim.des, namedim.des) + 2;
549 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
550 dim.asc += 1 + namedim.height() + 1;
555 // restore macro nesting
556 --mi.base.macro_nesting;
560 int MathMacro::kerning(BufferView const * bv) const {
561 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
562 return d->expanded_.kerning(bv);
568 void MathMacro::updateMacro(MacroContext const & mc)
571 d->macro_ = mc.get(name());
572 if (d->macro_ && d->macroBackup_ != *d->macro_) {
573 d->macroBackup_ = *d->macro_;
574 d->needsUpdate_ = true;
582 class MathMacro::UpdateLocker
585 explicit UpdateLocker(MathMacro & mm) : mac(mm)
587 mac.d->isUpdating_ = true;
589 ~UpdateLocker() { mac.d->isUpdating_ = false; }
593 /** Avoid wrong usage of UpdateLocker.
594 To avoid wrong usage:
595 UpdateLocker(...); // wrong
596 UpdateLocker locker(...); // right
598 #define UpdateLocker(x) unnamed_UpdateLocker;
599 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
602 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
605 // block recursive calls (bug 8999)
609 UpdateLocker locker(*this);
616 d->requires_ = d->macro_->requires();
619 // non-normal mode? We are done!
620 || (d->displayMode_ != DISPLAY_NORMAL))
623 d->needsUpdate_ = false;
625 // get default values of macro
626 vector<docstring> const & defaults = d->macro_->defaults();
628 // create MathMacroArgumentValue objects pointing to the cells of the macro
629 vector<MathData> values(nargs());
630 for (size_t i = 0; i < nargs(); ++i) {
631 ArgumentProxy * proxy;
632 if (i < defaults.size())
633 proxy = new ArgumentProxy(this, i, defaults[i]);
635 proxy = new ArgumentProxy(this, i);
636 values[i].insert(0, MathAtom(proxy));
638 // expanding macro with the values
639 // Only update the argument macros if anything was expanded, otherwise
640 // we would get an endless loop (bug 9140). UpdateLocker does not work
641 // in this case, since MacroData::expand() creates new MathMacro
642 // objects, so this would be a different recursion path than the one
643 // protected by UpdateLocker.
644 if (d->macro_->expand(values, d->expanded_)) {
645 if (utype == OutputUpdate && !d->expanded_.empty())
646 d->expanded_.updateMacros(cur, mc, utype);
648 // get definition for list edit mode
649 docstring const & display = d->macro_->display();
650 asArray(display.empty() ? d->macro_->definition() : display,
651 d->definition_, Parse::QUIET);
655 void MathMacro::draw(PainterInfo & pi, int x, int y) const
657 Dimension const dim = dimension(*pi.base.bv);
659 setPosCache(pi, x, y);
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 drawMarkers(pi, expx, expy);
672 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
673 && d->editing_[pi.base.bv]) {
674 // Macro will be edited in a old-style list mode here:
676 CoordCache const & coords = pi.base.bv->coordCache();
677 FontInfo const & labelFont = sane_font;
679 // markers and box needs two pixels
682 // get maximal font height
684 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
687 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
688 pi.pain.text(x, y, label, labelFont);
689 x += mathed_string_width(labelFont, label);
692 d->definition_.draw(pi, x, y);
693 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
694 y += max(fontDim.des, defDim.des);
697 docstring str = from_ascii("#9");
698 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
699 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
701 for (idx_type i = 0; i < nargs(); ++i) {
703 Dimension const & cdim = coords.getArrays().dim(&cell(i));
705 y += max(fontDim.asc, cdim.asc) + 1;
709 pi.pain.text(x, y, str, labelFont);
711 pi.pain.text(x, y, from_ascii(":"), labelFont);
715 cell(i).draw(pi, x, y);
718 y += max(fontDim.des, cdim.des);
721 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
722 dim.height() - 2, Color_mathmacroframe);
723 drawMarkers2(pi, expx, expy);
725 // the macro contents is not editable (except the arguments)
726 ++pi.base.macro_nesting;
728 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
729 Changer dummy = (currentMode() == TEXT_MODE)
730 ? pi.base.font.changeShape(UP_SHAPE)
734 for (size_t i = 0; i < nargs(); ++i)
735 cell(i).setXY(*pi.base.bv, x, y);
737 if (drawBox && d->editing_[pi.base.bv]) {
738 // draw header and rectangle around
739 FontInfo font = pi.base.font;
740 augmentFont(font, "lyxtex");
741 font.setSize(FONT_SIZE_TINY);
742 font.setColor(Color_mathmacrolabel);
744 mathed_string_dim(font, name(), namedim);
746 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
747 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
748 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
751 if (d->editing_[pi.base.bv]) {
752 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
753 d->expanded_.draw(pi, expx, expy);
754 pi.pain.leaveMonochromeMode();
757 pi.pain.rectangle(x, y - dim.asc, dim.wid,
758 dim.height(), Color_mathmacroframe);
760 d->expanded_.draw(pi, expx, expy);
762 --pi.base.macro_nesting;
765 drawMarkers(pi, x, y);
769 // edit mode changed?
770 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
771 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
775 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
777 // We may have 0 arguments, but InsetMathNest requires at least one.
779 InsetMathNest::drawSelection(pi, x, y);
783 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
785 if (d->displayMode_ != mode) {
786 // transfer name if changing from or to DISPLAY_UNFOLDED
787 if (mode == DISPLAY_UNFOLDED) {
789 asArray(d->name_, cell(0));
790 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
791 d->name_ = asString(cell(0));
795 d->displayMode_ = mode;
796 d->needsUpdate_ = true;
799 // the interactive init mode is non-greedy by default
801 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
803 d->appetite_ = size_t(appetite);
807 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
809 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
810 return DISPLAY_NORMAL;
812 return DISPLAY_UNFOLDED;
816 bool MathMacro::validName() const
818 docstring n = name();
823 // converting back and force doesn't swallow anything?
826 if (asString(ma) != n)
830 for (size_t i = 0; i<n.size(); ++i) {
831 if (!(n[i] >= 'a' && n[i] <= 'z')
832 && !(n[i] >= 'A' && n[i] <= 'Z')
841 size_t MathMacro::arity() const
843 if (d->displayMode_ == DISPLAY_NORMAL )
844 return cells_.size();
850 size_t MathMacro::optionals() const
852 return d->optionals_;
856 void MathMacro::setOptionals(int n)
858 if (n <= int(nargs()))
863 size_t MathMacro::appetite() const
869 InsetMath::mode_type MathMacro::currentMode() const
871 // User defined macros are always assumed to be mathmode macros.
872 // Only the global macros defined in lib/symbols may be textmode.
874 MacroData const * data = MacroTable::globalMacros().get(name());
875 bool textmode = data && data->symbol() && data->symbol()->extra == "textmode";
876 return textmode ? TEXT_MODE : MATH_MODE;
880 void MathMacro::validate(LaTeXFeatures & features) const
882 // Immediately after a document is loaded, in some cases the MacroData
883 // of the global macros defined in the lib/symbols file may still not
884 // be known to the macro machinery because it will be set only after
885 // the first call to updateMacros(). This is not a problem unless
886 // instant preview is on for math, in which case we will be missing
887 // the corresponding requirements.
888 // In this case, we get the required info from the global macro table.
889 if (!d->requires_.empty())
890 features.require(d->requires_);
891 else if (!d->macro_) {
892 // Update requires for known global macros.
893 MacroData const * data = MacroTable::globalMacros().get(name());
894 if (data && !data->requires().empty())
895 features.require(data->requires());
898 if (name() == "binom")
899 features.require("binom");
901 // validate the cells and the definition
902 if (displayMode() == DISPLAY_NORMAL) {
903 d->definition_.validate(features);
904 InsetMathNest::validate(features);
909 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
911 cur.screenUpdateFlags(Update::SinglePar);
912 InsetMathNest::edit(cur, front, entry_from);
916 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
918 // We may have 0 arguments, but InsetMathNest requires at least one.
920 cur.screenUpdateFlags(Update::SinglePar);
921 return InsetMathNest::editXY(cur, x, y);
927 void MathMacro::removeArgument(Inset::pos_type pos) {
928 if (d->displayMode_ == DISPLAY_NORMAL) {
929 LASSERT(size_t(pos) < cells_.size(), return);
930 cells_.erase(cells_.begin() + pos);
931 if (size_t(pos) < d->attachedArgsNum_)
932 --d->attachedArgsNum_;
933 if (size_t(pos) < d->optionals_) {
937 d->needsUpdate_ = true;
942 void MathMacro::insertArgument(Inset::pos_type pos) {
943 if (d->displayMode_ == DISPLAY_NORMAL) {
944 LASSERT(size_t(pos) <= cells_.size(), return);
945 cells_.insert(cells_.begin() + pos, MathData());
946 if (size_t(pos) < d->attachedArgsNum_)
947 ++d->attachedArgsNum_;
948 if (size_t(pos) < d->optionals_)
951 d->needsUpdate_ = true;
956 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
958 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
961 // strip off empty cells, but not more than arity-attachedArgsNum_
964 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
965 if (!cell(i - 1).empty()) break;
969 d->attachedArgsNum_ = 0;
970 d->expanded_ = MathData();
973 d->needsUpdate_ = true;
977 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
979 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
981 d->attachedArgsNum_ = args.size();
982 cells_.resize(arity);
983 d->expanded_ = MathData();
984 d->optionals_ = optionals;
986 d->needsUpdate_ = true;
990 bool MathMacro::idxFirst(Cursor & cur) const
992 cur.screenUpdateFlags(Update::SinglePar);
993 return InsetMathNest::idxFirst(cur);
997 bool MathMacro::idxLast(Cursor & cur) const
999 cur.screenUpdateFlags(Update::SinglePar);
1000 return InsetMathNest::idxLast(cur);
1004 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
1006 if (d->displayMode_ == DISPLAY_UNFOLDED) {
1007 docstring const & unfolded_name = name();
1008 if (unfolded_name != d->name_) {
1009 // The macro name was changed
1010 Cursor inset_cursor = old;
1011 int macroSlice = inset_cursor.find(this);
1012 // returning true means the cursor is "now" invalid,
1014 LASSERT(macroSlice != -1, return true);
1015 inset_cursor.cutOff(macroSlice);
1016 inset_cursor.recordUndoInset();
1018 inset_cursor.cell().erase(inset_cursor.pos());
1019 inset_cursor.cell().insert(inset_cursor.pos(),
1020 createInsetMath(unfolded_name, cur.buffer()));
1022 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
1026 cur.screenUpdateFlags(Update::Force);
1027 return InsetMathNest::notifyCursorLeaves(old, cur);
1031 void MathMacro::fold(Cursor & cur)
1033 if (!d->nextFoldMode_) {
1034 d->nextFoldMode_ = true;
1035 cur.screenUpdateFlags(Update::SinglePar);
1040 void MathMacro::unfold(Cursor & cur)
1042 if (d->nextFoldMode_) {
1043 d->nextFoldMode_ = false;
1044 cur.screenUpdateFlags(Update::SinglePar);
1049 bool MathMacro::folded() const
1051 return d->nextFoldMode_;
1055 void MathMacro::write(WriteStream & os) const
1057 MacroData const * data = MacroTable::globalMacros().get(name());
1058 bool textmode_macro = data && data->symbol()
1059 && data->symbol()->extra == "textmode";
1060 bool needs_mathmode = data && (!data->symbol()
1061 || data->symbol()->extra != "textmode");
1063 MathEnsurer ensurer(os, needs_mathmode, true, textmode_macro);
1066 if (d->displayMode_ != DISPLAY_NORMAL) {
1067 os << "\\" << name();
1068 if (name().size() != 1 || isAlphaASCII(name()[0]))
1069 os.pendingSpace(true);
1074 // we should be ok to continue even if this fails.
1077 // We may already be in the argument of a macro
1078 bool const inside_macro = os.insideMacro();
1079 os.insideMacro(true);
1081 // Enclose in braces to avoid latex errors with xargs if we have
1082 // optional arguments and are in the optional argument of a macro
1083 if (d->optionals_ && inside_macro)
1086 // Always protect macros in a fragile environment
1090 os << "\\" << name();
1093 // Optional arguments:
1094 // First find last non-empty optional argument
1095 idx_type emptyOptFrom = 0;
1097 for (; i < cells_.size() && i < d->optionals_; ++i) {
1098 if (!cell(i).empty())
1099 emptyOptFrom = i + 1;
1102 // print out optionals
1103 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
1105 os << "[" << cell(i) << "]";
1108 // skip the tailing empty optionals
1111 // Print remaining arguments
1112 for (; i < cells_.size(); ++i) {
1113 if (cell(i).size() == 1
1114 && cell(i)[0].nucleus()->asCharInset()
1115 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
1120 os << "{" << cell(i) << "}";
1124 // Close the opened brace or add space if there was no argument
1125 if (d->optionals_ && inside_macro)
1128 os.pendingSpace(true);
1130 os.insideMacro(inside_macro);
1134 void MathMacro::maple(MapleStream & os) const
1136 lyx::maple(d->expanded_, os);
1140 void MathMacro::maxima(MaximaStream & os) const
1142 lyx::maxima(d->expanded_, os);
1146 void MathMacro::mathematica(MathematicaStream & os) const
1148 lyx::mathematica(d->expanded_, os);
1152 void MathMacro::mathmlize(MathStream & os) const
1154 // macro_ is 0 if this is an unknown macro
1155 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1157 docstring const xmlname = d->macro_->xmlname();
1158 if (!xmlname.empty()) {
1159 char const * type = d->macro_->MathMLtype();
1160 os << '<' << type << "> " << xmlname << " </"
1165 if (d->expanded_.empty()) {
1166 // this means that we do not recognize the macro
1167 throw MathExportException();
1173 void MathMacro::htmlize(HtmlStream & 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 os << ' ' << xmlname << ' ';
1184 if (d->expanded_.empty()) {
1185 // this means that we do not recognize the macro
1186 throw MathExportException();
1192 void MathMacro::octave(OctaveStream & os) const
1194 lyx::octave(d->expanded_, os);
1198 void MathMacro::infoize(odocstream & os) const
1200 os << bformat(_("Macro: %1$s"), name());
1204 void MathMacro::infoize2(odocstream & os) const
1206 os << bformat(_("Macro: %1$s"), name());
1210 bool MathMacro::completionSupported(Cursor const & cur) const
1212 if (displayMode() != DISPLAY_UNFOLDED)
1213 return InsetMathNest::completionSupported(cur);
1215 return lyxrc.completion_popup_math
1216 && displayMode() == DISPLAY_UNFOLDED
1217 && cur.bv().cursor().pos() == int(name().size());
1221 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1223 if (displayMode() != DISPLAY_UNFOLDED)
1224 return InsetMathNest::inlineCompletionSupported(cur);
1226 return lyxrc.completion_inline_math
1227 && displayMode() == DISPLAY_UNFOLDED
1228 && cur.bv().cursor().pos() == int(name().size());
1232 bool MathMacro::automaticInlineCompletion() const
1234 if (displayMode() != DISPLAY_UNFOLDED)
1235 return InsetMathNest::automaticInlineCompletion();
1237 return lyxrc.completion_inline_math;
1241 bool MathMacro::automaticPopupCompletion() const
1243 if (displayMode() != DISPLAY_UNFOLDED)
1244 return InsetMathNest::automaticPopupCompletion();
1246 return lyxrc.completion_popup_math;
1250 CompletionList const *
1251 MathMacro::createCompletionList(Cursor const & cur) const
1253 if (displayMode() != DISPLAY_UNFOLDED)
1254 return InsetMathNest::createCompletionList(cur);
1256 return new MathCompletionList(cur.bv().cursor());
1260 docstring MathMacro::completionPrefix(Cursor const & cur) const
1262 if (displayMode() != DISPLAY_UNFOLDED)
1263 return InsetMathNest::completionPrefix(cur);
1265 if (!completionSupported(cur))
1268 return "\\" + name();
1272 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1275 if (displayMode() != DISPLAY_UNFOLDED)
1276 return InsetMathNest::insertCompletion(cur, s, finished);
1278 if (!completionSupported(cur))
1281 // append completion
1282 docstring newName = name() + s;
1283 asArray(newName, cell(0));
1284 cur.bv().cursor().pos() = name().size();
1285 cur.screenUpdateFlags(Update::SinglePar);
1289 cur.bv().cursor().pop();
1290 ++cur.bv().cursor().pos();
1291 cur.screenUpdateFlags(Update::SinglePar);
1298 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1299 Dimension & dim) const
1301 if (displayMode() != DISPLAY_UNFOLDED)
1302 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1304 // get inset dimensions
1305 dim = cur.bv().coordCache().insets().dim(this);
1306 // FIXME: these 3 are no accurate, but should depend on the font.
1307 // Now the popup jumps down if you enter a char with descent > 0.
1313 = cur.bv().coordCache().insets().xy(this);