2 * \file InsetMathMacroTemplate.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Stefan Schimanski
9 * Full author contact details are available in file CREDITS.
14 #include "InsetMathMacroTemplate.h"
16 #include "InsetMathBrace.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathHull.h"
19 #include "InsetMathSqrt.h"
20 #include "InsetMathMacro.h"
21 #include "InsetMathMacroArgument.h"
22 #include "MathStream.h"
23 #include "MathParser.h"
24 #include "MathSupport.h"
27 #include "BufferView.h"
30 #include "DispatchResult.h"
31 #include "DocIterator.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "LaTeXFeatures.h"
35 #include "MetricsInfo.h"
36 #include "TocBackend.h"
38 #include "frontends/Painter.h"
40 #include "insets/RenderPreview.h"
42 #include "support/lassert.h"
43 #include "support/convert.h"
44 #include "support/debug.h"
45 #include "support/gettext.h"
46 #include "support/docstream.h"
47 #include "support/Lexer.h"
48 #include "support/lstrings.h"
57 using support::bformat;
60 //////////////////////////////////////////////////////////////////////
62 class InsetLabelBox : public InsetMathNest {
65 InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring const & label,
66 InsetMathMacroTemplate const & parent, bool frame = false);
67 InsetLabelBox(Buffer * buf, docstring const & label, InsetMathMacroTemplate const & parent,
70 void metrics(MetricsInfo & mi, Dimension & dim) const override;
72 void draw(PainterInfo &, int x, int y) const override;
76 InsetMathMacroTemplate const & parent_;
78 Inset * clone() const override;
80 docstring const label_;
86 InsetLabelBox::InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring const & label,
87 InsetMathMacroTemplate const & parent, bool frame)
88 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
90 cell(0).insert(0, atom);
94 InsetLabelBox::InsetLabelBox(Buffer * buf, docstring const & label,
95 InsetMathMacroTemplate const & parent, bool frame)
96 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
101 Inset * InsetLabelBox::clone() const
103 return new InsetLabelBox(*this);
107 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
110 cell(0).metrics(mi, dim);
119 // adjust to common height in main metrics phase
120 if (!parent_.premetrics()) {
121 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
122 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
126 if (parent_.editing(mi.base.bv) && label_.length() > 0) {
128 FontInfo font = sane_font;
129 font.setSize(TINY_SIZE);
130 font.setColor(Color_mathmacrolabel);
132 // make space for label and box
133 int lwid = mathed_string_width(font, label_);
136 math_font_max_dim(font, maxasc, maxdes);
138 dim.wid = max(dim.wid, lwid + 2);
140 // space for the label
141 if (!parent_.premetrics())
142 dim.des += maxasc + maxdes + 1;
147 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
149 Dimension const dim = dimension(*pi.base.bv);
150 Dimension const cdim = cell(0).dimension(*pi.base.bv);
153 cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
156 if (parent_.editing(pi.base.bv) && label_.length() > 0) {
158 FontInfo font = sane_font;
159 font.setSize(TINY_SIZE);
160 font.setColor(Color_mathmacrolabel);
162 // make space for label and box
163 int lwid = mathed_string_width(font, label_);
166 math_font_max_dim(font, maxasc, maxdes);
169 pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
171 pi.pain.text(x, y + dim.des - maxdes, label_, font);
175 int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
177 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
178 dim.wid - 2, boxHeight - 2,
184 //////////////////////////////////////////////////////////////////////
186 class InsetDisplayLabelBox : public InsetLabelBox {
189 InsetDisplayLabelBox(Buffer * buf, MathAtom const & atom, docstring const & label,
190 InsetMathMacroTemplate const & parent);
193 marker_type marker(BufferView const *) const override;
195 void metrics(MetricsInfo & mi, Dimension & dim) const override;
197 void draw(PainterInfo &, int x, int y) const override;
201 Inset * clone() const override;
205 InsetDisplayLabelBox::InsetDisplayLabelBox(Buffer * buf, MathAtom const & atom,
206 docstring const & label,
207 InsetMathMacroTemplate const & parent)
208 : InsetLabelBox(buf, atom, label, parent, true)
214 Inset * InsetDisplayLabelBox::clone() const
216 return new InsetDisplayLabelBox(*this);
220 marker_type InsetDisplayLabelBox::marker(BufferView const * bv) const
222 if (parent_.editing(bv)
223 || !parent_.cell(parent_.displayIdx()).empty())
224 return marker_type::MARKER;
226 return marker_type::NO_MARKER;
230 void InsetDisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
232 InsetLabelBox::metrics(mi, dim);
233 if (!parent_.editing(mi.base.bv)
234 && parent_.cell(parent_.displayIdx()).empty())
239 void InsetDisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
241 if (parent_.editing(pi.base.bv)
242 || !parent_.cell(parent_.displayIdx()).empty()
244 InsetLabelBox::draw(pi, x, y);
248 //////////////////////////////////////////////////////////////////////
250 class InsetMathWrapper : public InsetMath {
253 explicit InsetMathWrapper(Buffer * buf, MathData const * value)
254 : InsetMath(buf), value_(value) {}
256 void metrics(MetricsInfo & mi, Dimension & dim) const override;
258 void draw(PainterInfo &, int x, int y) const override;
262 Inset * clone() const override;
264 MathData const * value_;
268 Inset * InsetMathWrapper::clone() const
270 return new InsetMathWrapper(*this);
274 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
276 value_->metrics(mi, dim);
280 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
282 value_->draw(pi, x, y);
286 ///////////////////////////////////////////////////////////////////////
287 class InsetColoredCell : public InsetMathNest {
290 InsetColoredCell(Buffer * buf, ColorCode blend);
292 InsetColoredCell(Buffer * buf, ColorCode blend, MathAtom const & atom);
294 void draw(PainterInfo &, int x, int y) const override;
296 void metrics(MetricsInfo & mi, Dimension & dim) const override;
300 Inset * clone() const override;
306 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode blend)
307 : InsetMathNest(buf, 1), blend_(blend)
312 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode blend, MathAtom const & atom)
313 : InsetMathNest(buf, 1), blend_(blend)
315 cell(0).insert(0, atom);
319 Inset * InsetColoredCell::clone() const
321 return new InsetColoredCell(*this);
325 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
327 cell(0).metrics(mi, dim);
331 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
333 pi.pain.enterMonochromeMode(blend_);
334 cell(0).draw(pi, x, y);
335 pi.pain.leaveMonochromeMode();
339 ///////////////////////////////////////////////////////////////////////
341 class InsetNameWrapper : public InsetMathWrapper {
344 InsetNameWrapper(Buffer * buf, MathData const * value, InsetMathMacroTemplate const & parent);
346 void metrics(MetricsInfo & mi, Dimension & dim) const override;
348 void draw(PainterInfo &, int x, int y) const override;
352 InsetMathMacroTemplate const & parent_;
354 Inset * clone() const override;
358 InsetNameWrapper::InsetNameWrapper(Buffer * buf, MathData const * value,
359 InsetMathMacroTemplate const & parent)
360 : InsetMathWrapper(buf, value), parent_(parent)
365 Inset * InsetNameWrapper::clone() const
367 return new InsetNameWrapper(*this);
371 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
373 Changer dummy = mi.base.changeFontSet("textit");
374 InsetMathWrapper::metrics(mi, dim);
375 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
379 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
381 ColorCode const color = parent_.validMacro() ? Color_latex : Color_error;
383 Changer dummy = pi.base.changeFontSet("textit");
384 Changer dummy2 = pi.base.font.changeColor(color);
387 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
388 x += mathed_string_width(pi.base.font, from_ascii("\\"));
391 InsetMathWrapper::draw(pi, x, y);
395 ///////////////////////////////////////////////////////////////////////
398 InsetMathMacroTemplate::InsetMathMacroTemplate(Buffer * buf)
399 : InsetMathNest(buf, 3), look_(buf), numargs_(0), argsInLook_(0), optionals_(0),
400 type_(MacroTypeNewcommand), redefinition_(false), lookOutdated_(true),
401 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
407 InsetMathMacroTemplate::InsetMathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
408 int optionals, MacroType type)
409 : InsetMathMacroTemplate(buf, name, numargs, optionals, type,
410 vector<MathData>(), MathData(buf), MathData(buf))
415 InsetMathMacroTemplate::InsetMathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
416 int optionals, MacroType type, vector<MathData> const & optionalValues,
417 MathData const & def, MathData const & display)
418 : InsetMathNest(buf, optionals + 3), look_(buf), numargs_(numargs),
419 argsInLook_(numargs), optionals_(optionals), optionalValues_(optionalValues),
420 type_(type), redefinition_(false), lookOutdated_(true),
421 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
426 lyxerr << "InsetMathMacroTemplate::InsetMathMacroTemplate: wrong # of arguments: "
429 asArray(name, cell(0));
430 optionalValues_.resize(9, MathData(buffer_));
431 for (int i = 0; i < optionals_; ++i)
432 cell(optIdx(i)) = optionalValues_[i];
433 cell(defIdx()) = def;
434 cell(displayIdx()) = display;
440 bool InsetMathMacroTemplate::fromString(docstring const & str)
442 MathData ar(buffer_);
443 mathed_parse_cell(ar, str, Parse::NORMAL);
444 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
445 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
446 asArray(from_ascii("invalidmacro"), cell(0));
447 // The macro template does not make sense after this.
450 operator=( *(ar[0]->asMacroTemplate()) );
457 Inset * InsetMathMacroTemplate::clone() const
459 InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(*this);
460 // the parent pointers of the proxy insets above will point to
461 // to the old template. Hence, the look must be updated.
467 docstring InsetMathMacroTemplate::name() const
469 return asString(cell(0));
473 void InsetMathMacroTemplate::updateToContext(MacroContext const & mc)
475 redefinition_ = mc.get(name()) != 0;
479 void InsetMathMacroTemplate::updateLook() const
481 lookOutdated_ = true;
485 void InsetMathMacroTemplate::createLook(int args) const
491 look_.push_back(MathAtom(
492 new InsetLabelBox(buffer_, _("Name"), *this, false)));
493 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
494 nameData.push_back(MathAtom(new InsetNameWrapper(buffer_, &cell(0), *this)));
498 if (optionals_ > 0) {
499 look_.push_back(MathAtom(
500 new InsetLabelBox(buffer_, _("optional"), *this, false)));
502 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
503 for (; i < optionals_; ++i) {
504 // color it light grey, if it is to be removed when the cursor leaves
505 if (i == argsInLook_) {
506 optData->push_back(MathAtom(
507 new InsetColoredCell(buffer_, Color_mathmacrooldarg)));
508 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
511 optData->push_back(MathAtom(new InsetMathChar(buffer_, '[')));
512 optData->push_back(MathAtom(new InsetMathWrapper(buffer_, &cell(1 + i))));
513 optData->push_back(MathAtom(new InsetMathChar(buffer_, ']')));
518 for (; i < numargs_; ++i) {
519 MathData arg(buffer_);
520 arg.push_back(MathAtom(new InsetMathMacroArgument(buffer_, i + 1)));
521 if (i >= argsInLook_) {
522 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
523 Color_mathmacrooldarg,
524 MathAtom(new InsetMathBrace(buffer_, arg)))));
526 look_.push_back(MathAtom(new InsetMathBrace(buffer_, arg)));
528 for (; i < argsInLook_; ++i) {
529 MathData arg(buffer_);
530 arg.push_back(MathAtom(new InsetMathMacroArgument(buffer_, i + 1)));
531 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
532 Color_mathmacronewarg,
533 MathAtom(new InsetMathBrace(buffer_, arg)))));
537 look_.push_back(MathAtom(new InsetMathChar(buffer_, ':')));
538 look_.push_back(MathAtom(new InsetMathChar(buffer_, '=')));
541 look_.push_back(MathAtom(
542 new InsetLabelBox(buffer_, MathAtom(
543 new InsetMathWrapper(buffer_, &cell(defIdx()))), _("TeX"), *this, true)));
546 look_.push_back(MathAtom(
547 new InsetDisplayLabelBox(buffer_, MathAtom(
548 new InsetMathWrapper(buffer_, &cell(displayIdx()))), _("LyX"), *this)));
550 look_.setContentsBuffer();
554 void InsetMathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
556 Changer dummy1 = mi.base.changeFontSet("mathnormal");
557 Changer dummy2 = mi.base.font.changeStyle(TEXT_STYLE);
560 MacroData const * macro = 0;
562 macro = mi.macrocontext.get(name());
565 int argsInDef = maxArgumentInDefinition();
566 if (lookOutdated_ || argsInDef != argsInLook_) {
567 lookOutdated_ = false;
568 createLook(argsInDef);
571 /// metrics for inset contents
575 // first phase, premetric:
577 look_.metrics(mi, dim);
578 labelBoxAscent_ = dim.asc;
579 labelBoxDescent_ = dim.des;
581 // second phase, main metric:
583 look_.metrics(mi, dim);
588 dim.wid += leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
589 dim.des += bottomOffset(mi.base.bv);
590 dim.asc += topOffset(mi.base.bv);
594 void InsetMathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
596 // FIXME: Calling Changer on the same object repeatedly is inefficient.
597 Changer dummy0 = pi.base.font.changeColor(Color_math);
598 Changer dummy1 = pi.base.changeFontSet("mathnormal");
599 Changer dummy2 = pi.base.font.changeStyle(TEXT_STYLE);
601 Dimension const dim = dimension(*pi.base.bv);
604 int const hoffset = leftOffset(pi.base.bv) + rightOffset(pi.base.bv);
605 int const voffset = topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
606 int const a = y - dim.asc + topOffset(pi.base.bv) / 2;
607 int const w = dim.wid - (hoffset - hoffset / 2);
608 int const h = dim.height() - (voffset - voffset / 2);
609 pi.pain.rectangle(x + leftOffset(pi.base.bv) / 2, a, w, h, Color_mathframe);
611 // just to be sure: set some dummy values for coord cache
612 for (idx_type i = 0; i < nargs(); ++i)
613 cell(i).setXY(*pi.base.bv, x, y);
616 look_.draw(pi, x + leftOffset(pi.base.bv), y);
620 void InsetMathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
623 cur.screenUpdateFlags(Update::SinglePar);
624 InsetMathNest::edit(cur, front, entry_from);
628 Inset * InsetMathMacroTemplate::editXY(Cursor & cur, int x, int y)
631 cur.screenUpdateFlags(Update::SinglePar);
632 return InsetMathNest::editXY(cur, x, y);
636 bool InsetMathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
638 unsigned int const nargs_before = nargs();
639 commitEditChanges(cur, old);
641 cur.screenUpdateFlags(Update::Force);
642 // If we have removed a cell, we might have invalidated the cursor
643 return InsetMathNest::notifyCursorLeaves(old, cur)
644 || nargs() < nargs_before;
648 void InsetMathMacroTemplate::removeArguments(Cursor & cur,
649 DocIterator const & /*inset_pos*/, int from, int to)
651 DocIterator it = doc_iterator_begin(&buffer(), this);
652 for (; it; it.forwardChar()) {
655 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
657 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
658 int n = arg->number() - 1;
659 if (from <= n && n <= to) {
660 int cellSlice = cur.find(it.cell());
661 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
662 --cur[cellSlice].pos();
664 it.cell().erase(it.pos());
672 void InsetMathMacroTemplate::shiftArguments(size_t from, int by)
674 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
677 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
679 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
680 if (arg->number() >= int(from) + 1)
681 arg->setNumber(arg->number() + by);
688 int InsetMathMacroTemplate::maxArgumentInDefinition() const
690 // We don't have a buffer when pasting from the clipboard (bug 6014).
691 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
693 DocIterator it = doc_iterator_begin(macro_buffer, this);
695 for (; it; it.forwardChar()) {
698 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
700 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
701 maxArg = std::max(arg->number(), maxArg);
707 void InsetMathMacroTemplate::insertMissingArguments(int maxArg)
709 bool found[9] = { false, false, false, false, false, false, false, false, false };
710 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
712 // search for #n macros arguments
713 DocIterator it = doc_iterator_begin(&buffer(), this);
715 for (; it && it[0].idx() == idx; it.forwardChar()) {
718 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
720 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
721 found[arg->number() - 1] = true;
725 for (int i = 0; i < maxArg; ++i) {
729 cell(idx).push_back(MathAtom(new InsetMathMacroArgument(buffer_, i + 1)));
734 void InsetMathMacroTemplate::changeArity(Cursor & cur,
735 DocIterator const & inset_pos, int newNumArg)
737 // remove parameter which do not appear anymore in the definition
738 for (int i = numargs_; i > newNumArg; --i)
739 removeParameter(cur, inset_pos, numargs_ - 1, true);
741 // add missing parameter
742 for (int i = numargs_; i < newNumArg; ++i)
743 insertParameter(cur, inset_pos, numargs_, true, false);
748 class AddRemoveMacroInstanceFix
752 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
754 void operator()(InsetMathMacro * macro)
756 if (macro->folded()) {
758 macro->insertArgument(n_);
760 macro->removeArgument(n_);
773 class OptionalsMacroInstanceFix
777 explicit OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
779 void operator()(InsetMathMacro * macro)
781 macro->setOptionals(optionals_);
791 class NullMacroInstanceFix
795 void operator()(InsetMathMacro * ) {}
800 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
801 docstring const & name, F & fix)
803 // goto position behind macro template
804 DocIterator dit = inset_pos;
806 dit.top().forwardPos();
808 // remember hull to trigger preview reload
809 DocIterator hull(dit.buffer());
810 bool preview_reload_needed = false;
811 set<DocIterator> preview_hulls;
813 // iterate over all positions until macro is redefined
814 for (; dit; dit.forwardPos()) {
815 // left the outer hull?
816 if (!hull.empty() && dit.depth() == hull.depth()) {
817 // schedule reload of the preview if necessary
818 if (preview_reload_needed) {
819 preview_hulls.insert(hull);
820 preview_reload_needed = false;
825 // only until a macro is redefined
826 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
827 InsetMathMacroTemplate const & macroTemplate
828 = static_cast<InsetMathMacroTemplate const &>(dit.inset());
829 if (macroTemplate.name() == name)
833 // in front of macro instance?
834 Inset * inset = dit.nextInset();
837 InsetMath * insetMath = inset->asInsetMath();
841 // in front of outer hull?
842 InsetMathHull * inset_hull = insetMath->asHullInset();
843 if (inset_hull && hull.empty()) {
844 // remember this for later preview reload
848 InsetMathMacro * macro = insetMath->asMacro();
849 if (macro && macro->name() == name && macro->folded()) {
851 if (RenderPreview::previewMath())
852 preview_reload_needed = true;
856 if (!preview_hulls.empty()) {
857 // reload the scheduled previews
858 set<DocIterator>::const_iterator sit = preview_hulls.begin();
859 set<DocIterator>::const_iterator end = preview_hulls.end();
860 for (; sit != end; ++sit) {
861 InsetMathHull * inset_hull =
862 sit->nextInset()->asInsetMath()->asHullInset();
864 inset_hull->reloadPreview(*sit);
866 cur.screenUpdateFlags(Update::Force);
871 void InsetMathMacroTemplate::commitEditChanges(Cursor & cur,
872 DocIterator const & inset_pos)
874 int args_in_def = maxArgumentInDefinition();
875 if (args_in_def != numargs_) {
876 // FIXME: implement precise undo handling (only a few places
878 cur.recordUndoFullBuffer();
879 changeArity(cur, inset_pos, args_in_def);
881 insertMissingArguments(args_in_def);
883 // make sure the preview are up to date
884 NullMacroInstanceFix fix;
885 fixMacroInstances(cur, inset_pos, name(), fix);
889 void InsetMathMacroTemplate::insertParameter(Cursor & cur,
890 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
892 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
897 shiftArguments(pos, 1);
899 cell(defIdx()).push_back(MathAtom(new InsetMathMacroArgument(buffer_, pos + 1)));
900 if (!cell(displayIdx()).empty())
901 cell(displayIdx()).push_back(MathAtom(new InsetMathMacroArgument(buffer_, pos + 1)));
905 // fix macro instances
906 AddRemoveMacroInstanceFix fix(pos, true);
907 fixMacroInstances(cur, inset_pos, name(), fix);
915 void InsetMathMacroTemplate::removeParameter(Cursor & cur,
916 DocIterator const & inset_pos, int pos, bool greedy)
918 if (pos < numargs_ && pos >= 0) {
920 removeArguments(cur, inset_pos, pos, pos);
921 shiftArguments(pos + 1, -1);
923 // removed optional parameter?
924 if (pos < optionals_) {
926 optionalValues_[pos] = cell(optIdx(pos));
927 cells_.erase(cells_.begin() + optIdx(pos));
930 int macroSlice = cur.find(this);
931 if (macroSlice != -1) {
932 if (cur[macroSlice].idx() == optIdx(pos)) {
933 cur.cutOff(macroSlice);
934 cur[macroSlice].idx() = 1;
935 cur[macroSlice].pos() = 0;
936 } else if (cur[macroSlice].idx() > optIdx(pos))
937 --cur[macroSlice].idx();
942 // fix macro instances
943 AddRemoveMacroInstanceFix fix(pos, false);
944 fixMacroInstances(cur, inset_pos, name(), fix);
952 void InsetMathMacroTemplate::makeOptional(Cursor & cur,
953 DocIterator const & inset_pos)
955 if (numargs_ > 0 && optionals_ < numargs_) {
957 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
959 int macroSlice = cur.find(this);
960 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
961 ++cur[macroSlice].idx();
963 // fix macro instances
964 OptionalsMacroInstanceFix fix(optionals_);
965 fixMacroInstances(cur, inset_pos, name(), fix);
972 void InsetMathMacroTemplate::makeNonOptional(Cursor & cur,
973 DocIterator const & inset_pos)
975 if (numargs_ > 0 && optionals_ > 0) {
978 // store default value for later if the user changes his mind
979 optionalValues_[optionals_] = cell(optIdx(optionals_));
980 cells_.erase(cells_.begin() + optIdx(optionals_));
983 int macroSlice = cur.find(this);
984 if (macroSlice != -1) {
985 if (cur[macroSlice].idx() > optIdx(optionals_))
986 --cur[macroSlice].idx();
987 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
988 cur.cutOff(macroSlice);
989 cur[macroSlice].idx() = optIdx(optionals_);
990 cur[macroSlice].pos() = 0;
994 // fix macro instances
995 OptionalsMacroInstanceFix fix(optionals_);
996 fixMacroInstances(cur, inset_pos, name(), fix);
1003 void InsetMathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
1005 string const arg = to_utf8(cmd.argument());
1006 switch (cmd.action()) {
1008 case LFUN_MATH_MACRO_ADD_PARAM:
1010 commitEditChanges(cur, cur);
1011 // FIXME: implement precise undo handling (only a few places
1013 cur.recordUndoFullBuffer();
1014 size_t pos = numargs_;
1016 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1017 insertParameter(cur, cur, pos);
1022 case LFUN_MATH_MACRO_REMOVE_PARAM:
1024 commitEditChanges(cur, cur);
1025 // FIXME: implement precise undo handling (only a few places
1027 cur.recordUndoFullBuffer();
1028 size_t pos = numargs_ - 1;
1030 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1031 removeParameter(cur, cur, pos);
1035 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1037 commitEditChanges(cur, cur);
1038 // FIXME: implement precise undo handling (only a few places
1040 cur.recordUndoFullBuffer();
1041 insertParameter(cur, cur, numargs_, true);
1045 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1047 commitEditChanges(cur, cur);
1048 // FIXME: implement precise undo handling (only a few places
1050 cur.recordUndoFullBuffer();
1051 removeParameter(cur, cur, numargs_ - 1, true);
1055 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1056 commitEditChanges(cur, cur);
1057 // FIXME: implement precise undo handling (only a few places
1059 cur.recordUndoFullBuffer();
1060 makeOptional(cur, cur);
1063 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1064 commitEditChanges(cur, cur);
1065 // FIXME: implement precise undo handling (only a few places
1067 cur.recordUndoFullBuffer();
1068 makeNonOptional(cur, cur);
1071 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1073 commitEditChanges(cur, cur);
1074 // FIXME: implement precise undo handling (only a few places
1076 cur.recordUndoFullBuffer();
1077 insertParameter(cur, cur, optionals_);
1078 makeOptional(cur, cur);
1082 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1083 if (optionals_ > 0) {
1084 commitEditChanges(cur, cur);
1085 // FIXME: implement precise undo handling (only a few places
1087 cur.recordUndoFullBuffer();
1088 removeParameter(cur, cur, optionals_ - 1);
1091 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1092 if (numargs_ == optionals_) {
1093 commitEditChanges(cur, cur);
1094 // FIXME: implement precise undo handling (only a few places
1096 cur.recordUndoFullBuffer();
1097 insertParameter(cur, cur, 0, true);
1098 makeOptional(cur, cur);
1103 InsetMathNest::doDispatch(cur, cmd);
1109 bool InsetMathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1110 FuncStatus & status) const
1113 string const arg = to_utf8(cmd.argument());
1114 switch (cmd.action()) {
1115 case LFUN_MATH_MACRO_ADD_PARAM: {
1116 int num = numargs_ + 1;
1118 num = convert<int>(arg);
1119 bool on = (num >= optionals_
1120 && numargs_ < 9 && num <= numargs_ + 1);
1121 status.setEnabled(on);
1125 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1126 status.setEnabled(numargs_ < 9);
1129 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1130 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1133 num = convert<int>(arg);
1134 status.setEnabled(num >= 1 && num <= numargs_);
1138 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1139 status.setEnabled(numargs_ > 0
1140 && optionals_ < numargs_
1141 && type_ != MacroTypeDef);
1144 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1145 status.setEnabled(optionals_ > 0
1146 && type_ != MacroTypeDef);
1149 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1150 status.setEnabled(numargs_ < 9);
1153 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1154 status.setEnabled(optionals_ > 0);
1157 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1158 status.setEnabled(numargs_ == 0
1159 && type_ != MacroTypeDef);
1162 case LFUN_IN_MATHMACROTEMPLATE:
1163 status.setEnabled(true);
1167 ret = InsetMathNest::getStatus(cur, cmd, status);
1174 void InsetMathMacroTemplate::read(Lexer & lex)
1176 MathData ar(buffer_);
1177 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1178 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1179 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1180 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1183 operator=( *(ar[0]->asMacroTemplate()) );
1189 void InsetMathMacroTemplate::write(ostream & os) const
1191 odocstringstream oss;
1192 otexrowstream ots(oss);
1193 TeXMathStream wi(ots, false, false, TeXMathStream::wsDefault);
1194 oss << "FormulaMacro\n";
1196 os << to_utf8(oss.str());
1200 void InsetMathMacroTemplate::write(TeXMathStream & os) const
1206 int InsetMathMacroTemplate::write(TeXMathStream & os, bool overwriteRedefinition) const
1211 if (definition().empty())
1214 if (optionals_ > 0) {
1215 // macros with optionals use the xargs package, e.g.:
1216 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1217 // \long is implicit by xargs
1218 if (redefinition_ && !overwriteRedefinition)
1219 os << "\\renewcommandx";
1221 os << "\\newcommandx";
1223 os << "\\" << name()
1224 << "[" << numargs_ << "]"
1225 << "[usedefault, addprefix=\\global";
1226 for (int i = 0; i < optionals_; ++i) {
1227 docstring optValue = asString(cell(optIdx(i)));
1228 if (optValue.find(']') != docstring::npos
1229 || optValue.find(',') != docstring::npos)
1230 os << ", " << i + 1 << "="
1231 << "{" << cell(optIdx(i)) << "}";
1233 os << ", " << i + 1 << "="
1238 // Macros without optionals use standard _global_ \def macros:
1239 // \global\def\long\foo#1#2{#1,#2}
1240 // We use the \long prefix as this is the equivalent to \newcommand.
1241 // We cannot use \newcommand directly because \global does not work with it.
1242 os << "\n\\global\\long\\def\\" << name();
1243 docstring param = from_ascii("#0");
1244 for (int i = 1; i <= numargs_; ++i) {
1250 // in LyX output we use some pseudo syntax which is implementation
1251 // independent, e.g.
1252 // \newcommand{\foo}[2][default]{#1,#2}
1253 if (redefinition_ && !overwriteRedefinition)
1254 os << "\\renewcommand";
1256 os << "\\newcommand";
1257 os << "{\\" << name() << '}';
1259 os << '[' << numargs_ << ']';
1261 for (int i = 0; i < optionals_; ++i) {
1262 docstring optValue = asString(cell(optIdx(i)));
1263 if (optValue.find(']') != docstring::npos)
1264 os << "[{" << cell(optIdx(i)) << "}]";
1266 os << "[" << cell(optIdx(i)) << "]";
1270 os << "{" << cell(defIdx()) << "}";
1273 // writing .tex. done.
1277 // writing .lyx, write special .tex export only if necessary
1278 if (!cell(displayIdx()).empty()) {
1279 os << "\n{" << cell(displayIdx()) << '}';
1288 docstring InsetMathMacroTemplate::xhtml(XMLStream &, OutputParams const &) const
1293 int InsetMathMacroTemplate::plaintext(odocstringstream & os,
1294 OutputParams const &, size_t) const
1296 docstring const str = '[' + buffer().B_("math macro") + ']';
1303 bool InsetMathMacroTemplate::validName() const
1305 docstring n = name();
1310 // converting back and force doesn't swallow anything?
1313 if (asString(ma) != n)
1316 // valid characters?
1318 for (char_type c : n) {
1319 if (!(c >= 'a' && c <= 'z')
1320 && !(c >= 'A' && c <= 'Z')
1330 bool InsetMathMacroTemplate::validMacro() const
1336 bool InsetMathMacroTemplate::fixNameAndCheckIfValid()
1338 // check all the characters/insets in the name cell
1340 MathData & data = cell(0);
1341 while (i < data.size()) {
1342 InsetMathChar const * cinset = data[i]->asCharInset();
1344 // valid character in [a-zA-Z]?
1345 char_type c = cinset->getChar();
1346 if ((c >= 'a' && c <= 'z')
1347 || (c >= 'A' && c <= 'Z')) {
1357 // now it should be valid if anything in the name survived
1358 return !data.empty();
1362 void InsetMathMacroTemplate::validate(LaTeXFeatures & features) const
1364 // we need global optional macro arguments. They are not available
1365 // with \def, and \newcommand does not support global macros. So we
1366 // are bound to xargs also for the single-optional-parameter case.
1368 features.require("xargs");
1371 void InsetMathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1373 defaults.resize(numargs_);
1374 for (int i = 0; i < optionals_; ++i)
1375 defaults[i] = asString(cell(optIdx(i)));
1379 docstring InsetMathMacroTemplate::definition() const
1381 return asString(cell(defIdx()));
1385 docstring InsetMathMacroTemplate::displayDefinition() const
1387 return asString(cell(displayIdx()));
1391 size_t InsetMathMacroTemplate::numArgs() const
1397 size_t InsetMathMacroTemplate::numOptionals() const
1403 void InsetMathMacroTemplate::infoize(odocstream & os) const
1405 os << bformat(_("Math Macro: \\%1$s"), name());
1409 string InsetMathMacroTemplate::contextMenuName() const
1411 return "context-math-macro-definition";
1415 void InsetMathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1416 UpdateType, TocBackend & backend) const
1420 str = bformat(_("Invalid macro! \\%1$s"), name());
1422 str = "\\" + name();
1423 TocBuilder & b = backend.builder("math-macro");
1424 b.pushItem(pit, str, output_active);