2 * \file MathMacroTemplate.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 "MathMacroTemplate.h"
16 #include "DocIterator.h"
17 #include "LaTeXFeatures.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathChar.h"
20 #include "InsetMathHull.h"
21 #include "InsetMathSqrt.h"
22 #include "MathMacro.h"
23 #include "MathMacroArgument.h"
24 #include "MathStream.h"
25 #include "MathParser.h"
26 #include "MathSupport.h"
27 #include "MathMacroArgument.h"
30 #include "BufferView.h"
33 #include "DispatchResult.h"
34 #include "FuncRequest.h"
35 #include "FuncStatus.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/lstrings.h"
56 using support::bformat;
58 //////////////////////////////////////////////////////////////////////
60 class InsetLabelBox : public InsetMathNest {
63 InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
64 MathMacroTemplate const & parent, bool frame = false);
65 InsetLabelBox(Buffer * buf, docstring label, MathMacroTemplate const & parent,
68 void metrics(MetricsInfo & mi, Dimension & dim) const;
70 void draw(PainterInfo &, int x, int y) const;
74 MathMacroTemplate const & parent_;
76 Inset * clone() const;
78 docstring const label_;
84 InsetLabelBox::InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
85 MathMacroTemplate const & parent, bool frame)
86 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
88 cell(0).insert(0, atom);
92 InsetLabelBox::InsetLabelBox(Buffer * buf, docstring label,
93 MathMacroTemplate const & parent, bool frame)
94 : InsetMathNest(buf, 1), parent_(parent), label_(label), frame_(frame)
99 Inset * InsetLabelBox::clone() const
101 return new InsetLabelBox(*this);
105 void InsetLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
108 cell(0).metrics(mi, dim);
117 // adjust to common height in main metrics phase
118 if (!parent_.premetrics()) {
119 dim.asc = max(dim.asc, parent_.commonLabelBoxAscent());
120 dim.des = max(dim.des, parent_.commonLabelBoxDescent());
124 if (parent_.editing(mi.base.bv) && label_.length() > 0) {
126 FontInfo font = sane_font;
127 font.setSize(FONT_SIZE_TINY);
128 font.setColor(Color_mathmacrolabel);
130 // make space for label and box
131 int lwid = mathed_string_width(font, label_);
134 math_font_max_dim(font, maxasc, maxdes);
136 dim.wid = max(dim.wid, lwid + 2);
138 // space for the label
139 if (!parent_.premetrics())
140 dim.des += maxasc + maxdes + 1;
145 void InsetLabelBox::draw(PainterInfo & pi, int x, int y) const
147 Dimension const dim = dimension(*pi.base.bv);
148 Dimension const cdim = cell(0).dimension(*pi.base.bv);
151 cell(0).draw(pi, x + (dim.wid - cdim.wid) / 2, y);
154 if (parent_.editing(pi.base.bv) && label_.length() > 0) {
156 FontInfo font = sane_font;
157 font.setSize(FONT_SIZE_TINY);
158 font.setColor(Color_mathmacrolabel);
160 // make space for label and box
161 int lwid = mathed_string_width(font, label_);
164 math_font_max_dim(font, maxasc, maxdes);
167 pi.pain.text(x + (dim.wid - lwid) / 2, y + dim.des - maxdes, label_, font);
169 pi.pain.text(x, y + dim.des - maxdes, label_, font);
173 int boxHeight = parent_.commonLabelBoxAscent() + parent_.commonLabelBoxDescent();
175 pi.pain.rectangle(x + 1, y - dim.ascent() + 1,
176 dim.wid - 2, boxHeight - 2,
182 //////////////////////////////////////////////////////////////////////
184 class DisplayLabelBox : public InsetLabelBox {
187 DisplayLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
188 MathMacroTemplate const & parent);
191 void metrics(MetricsInfo & mi, Dimension & dim) const;
193 void draw(PainterInfo &, int x, int y) const;
197 Inset * clone() const;
201 DisplayLabelBox::DisplayLabelBox(Buffer * buf, MathAtom const & atom,
203 MathMacroTemplate const & parent)
204 : InsetLabelBox(buf, atom, label, parent, true)
210 Inset * DisplayLabelBox::clone() const
212 return new DisplayLabelBox(*this);
216 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
218 InsetLabelBox::metrics(mi, dim);
219 if (!parent_.editing(mi.base.bv)
220 && parent_.cell(parent_.displayIdx()).empty()) {
228 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
230 if (parent_.editing(pi.base.bv)
231 || !parent_.cell(parent_.displayIdx()).empty()) {
232 InsetLabelBox::draw(pi, x, y);
234 bool enabled = pi.pain.isDrawingEnabled();
235 pi.pain.setDrawingEnabled(false);
236 InsetLabelBox::draw(pi, x, y);
237 pi.pain.setDrawingEnabled(enabled);
242 //////////////////////////////////////////////////////////////////////
244 class InsetMathWrapper : public InsetMath {
247 InsetMathWrapper(MathData const * value) : value_(value) {}
249 void metrics(MetricsInfo & mi, Dimension & dim) const;
251 void draw(PainterInfo &, int x, int y) const;
255 Inset * clone() const;
257 MathData const * value_;
261 Inset * InsetMathWrapper::clone() const
263 return new InsetMathWrapper(*this);
267 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
269 value_->metrics(mi, dim);
270 //metricsMarkers2(dim);
274 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
276 value_->draw(pi, x, y);
277 //drawMarkers(pi, x, y);
281 ///////////////////////////////////////////////////////////////////////
282 class InsetColoredCell : public InsetMathNest {
285 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max);
287 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom);
289 void draw(PainterInfo &, int x, int y) const;
291 void metrics(MetricsInfo & mi, Dimension & dim) const;
295 Inset * clone() const;
303 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max)
304 : InsetMathNest(buf, 1), min_(min), max_(max)
309 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom)
310 : InsetMathNest(buf, 1), min_(min), max_(max)
312 cell(0).insert(0, atom);
316 Inset * InsetColoredCell::clone() const
318 return new InsetColoredCell(*this);
322 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
324 cell(0).metrics(mi, dim);
328 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
330 pi.pain.enterMonochromeMode(min_, max_);
331 cell(0).draw(pi, x, y);
332 pi.pain.leaveMonochromeMode();
336 ///////////////////////////////////////////////////////////////////////
338 class InsetNameWrapper : public InsetMathWrapper {
341 InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
343 void metrics(MetricsInfo & mi, Dimension & dim) const;
345 void draw(PainterInfo &, int x, int y) const;
349 MathMacroTemplate const & parent_;
351 Inset * clone() const;
355 InsetNameWrapper::InsetNameWrapper(MathData const * value,
356 MathMacroTemplate const & parent)
357 : InsetMathWrapper(value), parent_(parent)
362 Inset * InsetNameWrapper::clone() const
364 return new InsetNameWrapper(*this);
368 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
370 InsetMathWrapper::metrics(mi, dim);
371 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
375 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
378 PainterInfo namepi = pi;
379 if (parent_.validMacro())
380 namepi.base.font.setColor(Color_latex);
382 namepi.base.font.setColor(Color_error);
385 pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
386 x += mathed_string_width(namepi.base.font, from_ascii("\\"));
389 InsetMathWrapper::draw(namepi, x, y);
393 ///////////////////////////////////////////////////////////////////////
396 MathMacroTemplate::MathMacroTemplate(Buffer * buf)
397 : InsetMathNest(buf, 3), numargs_(0), argsInLook_(0), optionals_(0),
398 type_(MacroTypeNewcommand), lookOutdated_(true)
404 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
405 int optionals, MacroType type, vector<MathData> const & optionalValues,
406 MathData const & def, MathData const & display)
407 : InsetMathNest(buf, optionals + 3), numargs_(numargs), argsInLook_(numargs),
408 optionals_(optionals), optionalValues_(optionalValues),
409 type_(type), lookOutdated_(true)
414 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
417 asArray(name, cell(0));
418 optionalValues_.resize(9);
419 for (int i = 0; i < optionals_; ++i)
420 cell(optIdx(i)) = optionalValues_[i];
421 cell(defIdx()) = def;
422 cell(displayIdx()) = display;
428 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & str)
429 : InsetMathNest(buf, 3), numargs_(0), optionals_(0),
430 type_(MacroTypeNewcommand), lookOutdated_(true)
436 mathed_parse_cell(ar, str, Parse::NORMAL);
437 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
438 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
439 asArray(from_ascii("invalidmacro"), cell(0));
440 // FIXME: The macro template does not make sense after this.
441 // The whole parsing should not be in a constructor which
442 // has no chance to report failure.
445 operator=( *(ar[0]->asMacroTemplate()) );
451 Inset * MathMacroTemplate::clone() const
453 MathMacroTemplate * inset = new MathMacroTemplate(*this);
454 // the parent pointers of the proxy insets above will point to
455 // to the old template. Hence, the look must be updated.
461 docstring MathMacroTemplate::name() const
463 return asString(cell(0));
467 void MathMacroTemplate::updateToContext(MacroContext const & mc)
469 redefinition_ = mc.get(name()) != 0;
473 void MathMacroTemplate::updateLook() const
475 lookOutdated_ = true;
479 void MathMacroTemplate::createLook(int args) const
485 look_.push_back(MathAtom(
486 new InsetLabelBox(buffer_, _("Name"), *this, false)));
487 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
488 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
492 if (optionals_ > 0) {
493 look_.push_back(MathAtom(
494 new InsetLabelBox(buffer_, _("optional"), *this, false)));
496 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
497 for (; i < optionals_; ++i) {
498 // color it light grey, if it is to be removed when the cursor leaves
499 if (i == argsInLook_) {
500 optData->push_back(MathAtom(
501 new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
502 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
505 optData->push_back(MathAtom(new InsetMathChar('[')));
506 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
507 optData->push_back(MathAtom(new InsetMathChar(']')));
512 for (; i < numargs_; ++i) {
514 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
515 if (i >= argsInLook_) {
516 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
517 Color_mathbg, Color_mathmacrooldarg,
518 MathAtom(new InsetMathBrace(arg)))));
520 look_.push_back(MathAtom(new InsetMathBrace(arg)));
522 for (; i < argsInLook_; ++i) {
524 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
525 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
526 Color_mathbg, Color_mathmacronewarg,
527 MathAtom(new InsetMathBrace(arg)))));
531 look_.push_back(MathAtom(new InsetMathChar(':')));
532 look_.push_back(MathAtom(new InsetMathChar('=')));
535 look_.push_back(MathAtom(
536 new InsetLabelBox(buffer_, MathAtom(
537 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
540 look_.push_back(MathAtom(
541 new DisplayLabelBox(buffer_, MathAtom(
542 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
546 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
548 FontSetChanger dummy1(mi.base, from_ascii("mathnormal"));
549 StyleChanger dummy2(mi.base, LM_ST_TEXT);
552 MacroData const * macro = 0;
554 macro = mi.macrocontext.get(name());
557 int argsInDef = maxArgumentInDefinition();
558 if (lookOutdated_ || argsInDef != argsInLook_) {
559 lookOutdated_ = false;
560 createLook(argsInDef);
563 /// metrics for inset contents
567 // first phase, premetric:
569 look_.metrics(mi, dim);
570 labelBoxAscent_ = dim.asc;
571 labelBoxDescent_ = dim.des;
573 // second phase, main metric:
575 look_.metrics(mi, dim);
584 setDimCache(mi, dim);
588 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
590 ColorChanger dummy0(pi.base.font, Color_math);
591 FontSetChanger dummy1(pi.base, from_ascii("mathnormal"));
592 StyleChanger dummy2(pi.base, LM_ST_TEXT);
594 setPosCache(pi, x, y);
595 Dimension const dim = dimension(*pi.base.bv);
598 int const a = y - dim.asc + 1;
599 int const w = dim.wid - 2;
600 int const h = dim.height() - 2;
601 pi.pain.rectangle(x, a, w, h, Color_mathframe);
603 // just to be sure: set some dummy values for coord cache
604 for (idx_type i = 0; i < nargs(); ++i)
605 cell(i).setXY(*pi.base.bv, x, y);
608 look_.draw(pi, x + 3, y);
612 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
615 cur.screenUpdateFlags(Update::SinglePar);
616 InsetMathNest::edit(cur, front, entry_from);
620 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
622 unsigned int const nargs_before = nargs();
623 commitEditChanges(cur, old);
625 cur.screenUpdateFlags(Update::Force);
626 // If we have removed a cell, we might have invalidated the cursor
627 return InsetMathNest::notifyCursorLeaves(old, cur)
628 || nargs() < nargs_before;
632 void MathMacroTemplate::removeArguments(Cursor & cur,
633 DocIterator const & /*inset_pos*/, int from, int to)
635 DocIterator it = doc_iterator_begin(&buffer(), this);
636 for (; it; it.forwardChar()) {
639 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
641 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
642 int n = arg->number() - 1;
643 if (from <= n && n <= to) {
644 int cellSlice = cur.find(it.cell());
645 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
646 --cur[cellSlice].pos();
648 it.cell().erase(it.pos());
656 void MathMacroTemplate::shiftArguments(size_t from, int by)
658 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
661 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
663 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
664 if (arg->number() >= int(from) + 1)
665 arg->setNumber(arg->number() + by);
672 int MathMacroTemplate::maxArgumentInDefinition() const
674 // We don't have a buffer when pasting from the clipboard (bug 6014).
675 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
677 DocIterator it = doc_iterator_begin(macro_buffer, this);
679 for (; it; it.forwardChar()) {
682 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
684 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
685 maxArg = std::max(int(arg->number()), maxArg);
691 void MathMacroTemplate::insertMissingArguments(int maxArg)
693 bool found[9] = { false, false, false, false, false, false, false, false, false };
694 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
696 // search for #n macros arguments
697 DocIterator it = doc_iterator_begin(&buffer(), this);
699 for (; it && it[0].idx() == idx; it.forwardChar()) {
702 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
704 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
705 found[arg->number() - 1] = true;
709 for (int i = 0; i < maxArg; ++i) {
713 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
718 void MathMacroTemplate::changeArity(Cursor & cur,
719 DocIterator const & inset_pos, int newNumArg)
721 // remove parameter which do not appear anymore in the definition
722 for (int i = numargs_; i > newNumArg; --i)
723 removeParameter(cur, inset_pos, numargs_ - 1, true);
725 // add missing parameter
726 for (int i = numargs_; i < newNumArg; ++i)
727 insertParameter(cur, inset_pos, numargs_, true, false);
732 class AddRemoveMacroInstanceFix
736 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
738 void operator()(MathMacro * macro)
740 if (macro->folded()) {
742 macro->insertArgument(n_);
744 macro->removeArgument(n_);
757 class OptionalsMacroInstanceFix
761 OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
763 void operator()(MathMacro * macro)
765 macro->setOptionals(optionals_);
775 class NullMacroInstanceFix
779 void operator()(MathMacro * ) {}
784 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
785 docstring const & name, F & fix)
787 // goto position behind macro template
788 DocIterator dit = inset_pos;
790 dit.top().forwardPos();
792 // remember hull to trigger preview reload
793 DocIterator hull(dit.buffer());
794 bool preview_reload_needed = false;
795 set<DocIterator> preview_hulls;
797 // iterate over all positions until macro is redefined
798 for (; dit; dit.forwardPos()) {
799 // left the outer hull?
800 if (!hull.empty() && dit.depth() == hull.depth()) {
801 // schedule reload of the preview if necessary
802 if (preview_reload_needed) {
803 preview_hulls.insert(hull);
804 preview_reload_needed = false;
809 // only until a macro is redefined
810 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
811 MathMacroTemplate const & macroTemplate
812 = static_cast<MathMacroTemplate const &>(dit.inset());
813 if (macroTemplate.name() == name)
817 // in front of macro instance?
818 Inset * inset = dit.nextInset();
821 InsetMath * insetMath = inset->asInsetMath();
825 // in front of outer hull?
826 InsetMathHull * inset_hull = insetMath->asHullInset();
827 if (inset_hull && hull.empty()) {
828 // remember this for later preview reload
832 MathMacro * macro = insetMath->asMacro();
833 if (macro && macro->name() == name && macro->folded()) {
835 if (RenderPreview::previewMath())
836 preview_reload_needed = true;
840 if (!preview_hulls.empty()) {
841 // reload the scheduled previews
842 set<DocIterator>::const_iterator sit = preview_hulls.begin();
843 set<DocIterator>::const_iterator end = preview_hulls.end();
844 for (; sit != end; ++sit) {
845 InsetMathHull * inset_hull =
846 sit->nextInset()->asInsetMath()->asHullInset();
848 inset_hull->reloadPreview(*sit);
850 cur.screenUpdateFlags(Update::Force);
855 void MathMacroTemplate::commitEditChanges(Cursor & cur,
856 DocIterator const & inset_pos)
858 int args_in_def = maxArgumentInDefinition();
859 if (args_in_def != numargs_) {
860 // FIXME: implement precise undo handling (only a few places
862 cur.recordUndoFullBuffer();
863 changeArity(cur, inset_pos, args_in_def);
865 insertMissingArguments(args_in_def);
867 // make sure the preview are up to date
868 NullMacroInstanceFix fix;
869 fixMacroInstances(cur, inset_pos, name(), fix);
873 void MathMacroTemplate::insertParameter(Cursor & cur,
874 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
876 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
881 shiftArguments(pos, 1);
883 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
884 if (!cell(displayIdx()).empty())
885 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
889 // fix macro instances
890 AddRemoveMacroInstanceFix fix(pos, true);
891 fixMacroInstances(cur, inset_pos, name(), fix);
899 void MathMacroTemplate::removeParameter(Cursor & cur,
900 DocIterator const & inset_pos, int pos, bool greedy)
902 if (pos < numargs_ && pos >= 0) {
904 removeArguments(cur, inset_pos, pos, pos);
905 shiftArguments(pos + 1, -1);
907 // removed optional parameter?
908 if (pos < optionals_) {
910 optionalValues_[pos] = cell(optIdx(pos));
911 cells_.erase(cells_.begin() + optIdx(pos));
914 int macroSlice = cur.find(this);
915 if (macroSlice != -1) {
916 if (cur[macroSlice].idx() == optIdx(pos)) {
917 cur.cutOff(macroSlice);
918 cur[macroSlice].idx() = 1;
919 cur[macroSlice].pos() = 0;
920 } else if (cur[macroSlice].idx() > optIdx(pos))
921 --cur[macroSlice].idx();
926 // fix macro instances
927 AddRemoveMacroInstanceFix fix(pos, false);
928 fixMacroInstances(cur, inset_pos, name(), fix);
936 void MathMacroTemplate::makeOptional(Cursor & cur,
937 DocIterator const & inset_pos)
939 if (numargs_ > 0 && optionals_ < numargs_) {
941 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
943 int macroSlice = cur.find(this);
944 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
945 ++cur[macroSlice].idx();
947 // fix macro instances
948 OptionalsMacroInstanceFix fix(optionals_);
949 fixMacroInstances(cur, inset_pos, name(), fix);
956 void MathMacroTemplate::makeNonOptional(Cursor & cur,
957 DocIterator const & inset_pos)
959 if (numargs_ > 0 && optionals_ > 0) {
962 // store default value for later if the user changes his mind
963 optionalValues_[optionals_] = cell(optIdx(optionals_));
964 cells_.erase(cells_.begin() + optIdx(optionals_));
967 int macroSlice = cur.find(this);
968 if (macroSlice != -1) {
969 if (cur[macroSlice].idx() > optIdx(optionals_))
970 --cur[macroSlice].idx();
971 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
972 cur.cutOff(macroSlice);
973 cur[macroSlice].idx() = optIdx(optionals_);
974 cur[macroSlice].pos() = 0;
978 // fix macro instances
979 OptionalsMacroInstanceFix fix(optionals_);
980 fixMacroInstances(cur, inset_pos, name(), fix);
987 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
989 string const arg = to_utf8(cmd.argument());
990 switch (cmd.action()) {
992 case LFUN_MATH_MACRO_ADD_PARAM:
994 commitEditChanges(cur, cur);
995 // FIXME: implement precise undo handling (only a few places
997 cur.recordUndoFullBuffer();
998 size_t pos = numargs_;
1000 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1001 insertParameter(cur, cur, pos);
1006 case LFUN_MATH_MACRO_REMOVE_PARAM:
1008 commitEditChanges(cur, cur);
1009 // FIXME: implement precise undo handling (only a few places
1011 cur.recordUndoFullBuffer();
1012 size_t pos = numargs_ - 1;
1014 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1015 removeParameter(cur, cur, pos);
1019 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1021 commitEditChanges(cur, cur);
1022 // FIXME: implement precise undo handling (only a few places
1024 cur.recordUndoFullBuffer();
1025 insertParameter(cur, cur, numargs_, true);
1029 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1031 commitEditChanges(cur, cur);
1032 // FIXME: implement precise undo handling (only a few places
1034 cur.recordUndoFullBuffer();
1035 removeParameter(cur, cur, numargs_ - 1, true);
1039 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1040 commitEditChanges(cur, cur);
1041 // FIXME: implement precise undo handling (only a few places
1043 cur.recordUndoFullBuffer();
1044 makeOptional(cur, cur);
1047 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1048 commitEditChanges(cur, cur);
1049 // FIXME: implement precise undo handling (only a few places
1051 cur.recordUndoFullBuffer();
1052 makeNonOptional(cur, cur);
1055 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1057 commitEditChanges(cur, cur);
1058 // FIXME: implement precise undo handling (only a few places
1060 cur.recordUndoFullBuffer();
1061 insertParameter(cur, cur, optionals_);
1062 makeOptional(cur, cur);
1066 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1067 if (optionals_ > 0) {
1068 commitEditChanges(cur, cur);
1069 // FIXME: implement precise undo handling (only a few places
1071 cur.recordUndoFullBuffer();
1072 removeParameter(cur, cur, optionals_ - 1);
1075 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1076 if (numargs_ == optionals_) {
1077 commitEditChanges(cur, cur);
1078 // FIXME: implement precise undo handling (only a few places
1080 cur.recordUndoFullBuffer();
1081 insertParameter(cur, cur, 0, true);
1082 makeOptional(cur, cur);
1087 InsetMathNest::doDispatch(cur, cmd);
1093 bool MathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1094 FuncStatus & flag) const
1097 string const arg = to_utf8(cmd.argument());
1098 switch (cmd.action()) {
1099 case LFUN_MATH_MACRO_ADD_PARAM: {
1100 int num = numargs_ + 1;
1102 num = convert<int>(arg);
1103 bool on = (num >= optionals_
1104 && numargs_ < 9 && num <= numargs_ + 1);
1105 flag.setEnabled(on);
1109 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1110 flag.setEnabled(numargs_ < 9);
1113 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1114 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1117 num = convert<int>(arg);
1118 flag.setEnabled(num >= 1 && num <= numargs_);
1122 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1123 flag.setEnabled(numargs_ > 0
1124 && optionals_ < numargs_
1125 && type_ != MacroTypeDef);
1128 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1129 flag.setEnabled(optionals_ > 0
1130 && type_ != MacroTypeDef);
1133 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1134 flag.setEnabled(numargs_ < 9);
1137 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1138 flag.setEnabled(optionals_ > 0);
1141 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1142 flag.setEnabled(numargs_ == 0
1143 && type_ != MacroTypeDef);
1146 case LFUN_IN_MATHMACROTEMPLATE:
1147 flag.setEnabled(true);
1151 ret = InsetMathNest::getStatus(cur, cmd, flag);
1158 void MathMacroTemplate::read(Lexer & lex)
1160 MathData ar(buffer_);
1161 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1162 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1163 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1164 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1167 operator=( *(ar[0]->asMacroTemplate()) );
1173 void MathMacroTemplate::write(ostream & os) const
1175 odocstringstream oss;
1176 WriteStream wi(oss, false, false, WriteStream::wsDefault);
1177 oss << "FormulaMacro\n";
1179 os << to_utf8(oss.str());
1183 void MathMacroTemplate::write(WriteStream & os) const
1189 int MathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1194 if (optionals_ > 0) {
1195 // macros with optionals use the xargs package, e.g.:
1196 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1197 // \long is implicit by xargs
1198 if (redefinition_ && !overwriteRedefinition)
1199 os << "\\renewcommandx";
1201 os << "\\newcommandx";
1203 os << "\\" << name()
1204 << "[" << numargs_ << "]"
1205 << "[usedefault, addprefix=\\global";
1206 for (int i = 0; i < optionals_; ++i) {
1207 docstring optValue = asString(cell(optIdx(i)));
1208 if (optValue.find(']') != docstring::npos
1209 || optValue.find(',') != docstring::npos)
1210 os << ", " << i + 1 << "="
1211 << "{" << cell(optIdx(i)) << "}";
1213 os << ", " << i + 1 << "="
1218 // Macros without optionals use standard _global_ \def macros:
1219 // \global\def\long\foo#1#2{#1,#2}
1220 // We use the \long prefix as this is the equivalent to \newcommand.
1221 // We cannot use \newcommand directly because \global does not work with it.
1222 os << "\\global\\long\\def\\" << name();
1223 docstring param = from_ascii("#0");
1224 for (int i = 1; i <= numargs_; ++i) {
1230 // in LyX output we use some pseudo syntax which is implementation
1231 // independent, e.g.
1232 // \newcommand{\foo}[2][default]{#1,#2}
1233 if (redefinition_ && !overwriteRedefinition)
1234 os << "\\renewcommand";
1236 os << "\\newcommand";
1237 os << "{\\" << name() << '}';
1239 os << '[' << numargs_ << ']';
1241 for (int i = 0; i < optionals_; ++i) {
1242 docstring optValue = asString(cell(optIdx(i)));
1243 if (optValue.find(']') != docstring::npos)
1244 os << "[{" << cell(optIdx(i)) << "}]";
1246 os << "[" << cell(optIdx(i)) << "]";
1250 os << "{" << cell(defIdx()) << "}";
1253 // writing .tex. done.
1257 // writing .lyx, write special .tex export only if necessary
1258 if (!cell(displayIdx()).empty()) {
1259 os << "\n{" << cell(displayIdx()) << '}';
1268 docstring MathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1273 int MathMacroTemplate::plaintext(odocstringstream & os,
1274 OutputParams const &, size_t) const
1276 static docstring const str = '[' + buffer().B_("math macro") + ']';
1283 bool MathMacroTemplate::validName() const
1285 docstring n = name();
1290 // converting back and force doesn't swallow anything?
1293 if (asString(ma) != n)
1296 // valid characters?
1297 for (size_t i = 0; i < n.size(); ++i) {
1298 if (!(n[i] >= 'a' && n[i] <= 'z')
1299 && !(n[i] >= 'A' && n[i] <= 'Z')
1308 bool MathMacroTemplate::validMacro() const
1314 bool MathMacroTemplate::fixNameAndCheckIfValid()
1316 // check all the characters/insets in the name cell
1318 MathData & data = cell(0);
1319 while (i < data.size()) {
1320 InsetMathChar const * cinset = data[i]->asCharInset();
1322 // valid character in [a-zA-Z]?
1323 char_type c = cinset->getChar();
1324 if ((c >= 'a' && c <= 'z')
1325 || (c >= 'A' && c <= 'Z')) {
1335 // now it should be valid if anything in the name survived
1336 return !data.empty();
1340 void MathMacroTemplate::validate(LaTeXFeatures & features) const
1342 // we need global optional macro arguments. They are not available
1343 // with \def, and \newcommand does not support global macros. So we
1344 // are bound to xargs also for the single-optional-parameter case.
1346 features.require("xargs");
1349 void MathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1351 defaults.resize(numargs_);
1352 for (int i = 0; i < optionals_; ++i)
1353 defaults[i] = asString(cell(optIdx(i)));
1357 docstring MathMacroTemplate::definition() const
1359 return asString(cell(defIdx()));
1363 docstring MathMacroTemplate::displayDefinition() const
1365 return asString(cell(displayIdx()));
1369 size_t MathMacroTemplate::numArgs() const
1375 size_t MathMacroTemplate::numOptionals() const
1381 void MathMacroTemplate::infoize(odocstream & os) const
1383 os << bformat(_("Math Macro: \\%1$s"), name());
1387 string MathMacroTemplate::contextMenuName() const
1389 return "context-math-macro-definition";