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 "InsetMathBrace.h"
17 #include "InsetMathChar.h"
18 #include "InsetMathHull.h"
19 #include "InsetMathSqrt.h"
20 #include "MathMacro.h"
21 #include "MathMacroArgument.h"
22 #include "MathStream.h"
23 #include "MathParser.h"
24 #include "MathSupport.h"
25 #include "MathMacroArgument.h"
28 #include "BufferView.h"
31 #include "DispatchResult.h"
32 #include "DocIterator.h"
33 #include "FuncRequest.h"
34 #include "FuncStatus.h"
35 #include "LaTeXFeatures.h"
37 #include "MetricsInfo.h"
38 #include "TocBackend.h"
40 #include "frontends/Painter.h"
42 #include "insets/RenderPreview.h"
44 #include "support/lassert.h"
45 #include "support/convert.h"
46 #include "support/debug.h"
47 #include "support/gettext.h"
48 #include "support/docstream.h"
49 #include "support/lstrings.h"
58 using support::bformat;
60 //////////////////////////////////////////////////////////////////////
62 class InsetLabelBox : public InsetMathNest {
65 InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
66 MathMacroTemplate const & parent, bool frame = false);
67 InsetLabelBox(Buffer * buf, docstring label, MathMacroTemplate const & parent,
70 void metrics(MetricsInfo & mi, Dimension & dim) const;
72 void draw(PainterInfo &, int x, int y) const;
76 MathMacroTemplate const & parent_;
78 Inset * clone() const;
80 docstring const label_;
86 InsetLabelBox::InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
87 MathMacroTemplate 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 label,
95 MathMacroTemplate 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(FONT_SIZE_TINY);
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(FONT_SIZE_TINY);
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 DisplayLabelBox : public InsetLabelBox {
189 DisplayLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
190 MathMacroTemplate const & parent);
193 void metrics(MetricsInfo & mi, Dimension & dim) const;
195 void draw(PainterInfo &, int x, int y) const;
199 Inset * clone() const;
203 DisplayLabelBox::DisplayLabelBox(Buffer * buf, MathAtom const & atom,
205 MathMacroTemplate const & parent)
206 : InsetLabelBox(buf, atom, label, parent, true)
212 Inset * DisplayLabelBox::clone() const
214 return new DisplayLabelBox(*this);
218 void DisplayLabelBox::metrics(MetricsInfo & mi, Dimension & dim) const
220 InsetLabelBox::metrics(mi, dim);
221 if (!parent_.editing(mi.base.bv)
222 && parent_.cell(parent_.displayIdx()).empty()) {
230 void DisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
232 if (parent_.editing(pi.base.bv)
233 || !parent_.cell(parent_.displayIdx()).empty()) {
234 InsetLabelBox::draw(pi, x, y);
236 bool enabled = pi.pain.isDrawingEnabled();
237 pi.pain.setDrawingEnabled(false);
238 InsetLabelBox::draw(pi, x, y);
239 pi.pain.setDrawingEnabled(enabled);
244 //////////////////////////////////////////////////////////////////////
246 class InsetMathWrapper : public InsetMath {
249 InsetMathWrapper(MathData const * value) : value_(value) {}
251 void metrics(MetricsInfo & mi, Dimension & dim) const;
253 void draw(PainterInfo &, int x, int y) const;
257 Inset * clone() const;
259 MathData const * value_;
263 Inset * InsetMathWrapper::clone() const
265 return new InsetMathWrapper(*this);
269 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
271 value_->metrics(mi, dim);
272 //metricsMarkers2(dim);
276 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
278 value_->draw(pi, x, y);
279 //drawMarkers(pi, x, y);
283 ///////////////////////////////////////////////////////////////////////
284 class InsetColoredCell : public InsetMathNest {
287 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max);
289 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom);
291 void draw(PainterInfo &, int x, int y) const;
293 void metrics(MetricsInfo & mi, Dimension & dim) const;
297 Inset * clone() const;
305 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max)
306 : InsetMathNest(buf, 1), min_(min), max_(max)
311 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom)
312 : InsetMathNest(buf, 1), min_(min), max_(max)
314 cell(0).insert(0, atom);
318 Inset * InsetColoredCell::clone() const
320 return new InsetColoredCell(*this);
324 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
326 cell(0).metrics(mi, dim);
330 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
332 pi.pain.enterMonochromeMode(min_, max_);
333 cell(0).draw(pi, x, y);
334 pi.pain.leaveMonochromeMode();
338 ///////////////////////////////////////////////////////////////////////
340 class InsetNameWrapper : public InsetMathWrapper {
343 InsetNameWrapper(MathData const * value, MathMacroTemplate const & parent);
345 void metrics(MetricsInfo & mi, Dimension & dim) const;
347 void draw(PainterInfo &, int x, int y) const;
351 MathMacroTemplate const & parent_;
353 Inset * clone() const;
357 InsetNameWrapper::InsetNameWrapper(MathData const * value,
358 MathMacroTemplate const & parent)
359 : InsetMathWrapper(value), parent_(parent)
364 Inset * InsetNameWrapper::clone() const
366 return new InsetNameWrapper(*this);
370 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
372 InsetMathWrapper::metrics(mi, dim);
373 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
377 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
380 PainterInfo namepi = pi;
381 if (parent_.validMacro())
382 namepi.base.font.setColor(Color_latex);
384 namepi.base.font.setColor(Color_error);
387 pi.pain.text(x, y, from_ascii("\\"), namepi.base.font);
388 x += mathed_string_width(namepi.base.font, from_ascii("\\"));
391 InsetMathWrapper::draw(namepi, x, y);
395 ///////////////////////////////////////////////////////////////////////
398 MathMacroTemplate::MathMacroTemplate(Buffer * buf)
399 : InsetMathNest(buf, 3), numargs_(0), argsInLook_(0), optionals_(0),
400 type_(MacroTypeNewcommand), redefinition_(false), lookOutdated_(true),
401 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
407 MathMacroTemplate::MathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
408 int optionals, MacroType type, vector<MathData> const & optionalValues,
409 MathData const & def, MathData const & display)
410 : InsetMathNest(buf, optionals + 3), numargs_(numargs), argsInLook_(numargs),
411 optionals_(optionals), optionalValues_(optionalValues),
412 type_(type), redefinition_(false), lookOutdated_(true),
413 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
418 lyxerr << "MathMacroTemplate::MathMacroTemplate: wrong # of arguments: "
421 asArray(name, cell(0));
422 optionalValues_.resize(9);
423 for (int i = 0; i < optionals_; ++i)
424 cell(optIdx(i)) = optionalValues_[i];
425 cell(defIdx()) = def;
426 cell(displayIdx()) = display;
432 bool MathMacroTemplate::fromString(docstring const & str)
434 MathData ar(buffer_);
435 mathed_parse_cell(ar, str, Parse::NORMAL);
436 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
437 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
438 asArray(from_ascii("invalidmacro"), cell(0));
439 // The macro template does not make sense after this.
442 operator=( *(ar[0]->asMacroTemplate()) );
449 Inset * MathMacroTemplate::clone() const
451 MathMacroTemplate * inset = new MathMacroTemplate(*this);
452 // the parent pointers of the proxy insets above will point to
453 // to the old template. Hence, the look must be updated.
459 docstring MathMacroTemplate::name() const
461 return asString(cell(0));
465 void MathMacroTemplate::updateToContext(MacroContext const & mc)
467 redefinition_ = mc.get(name()) != 0;
471 void MathMacroTemplate::updateLook() const
473 lookOutdated_ = true;
477 void MathMacroTemplate::createLook(int args) const
483 look_.push_back(MathAtom(
484 new InsetLabelBox(buffer_, _("Name"), *this, false)));
485 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
486 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
490 if (optionals_ > 0) {
491 look_.push_back(MathAtom(
492 new InsetLabelBox(buffer_, _("optional"), *this, false)));
494 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
495 for (; i < optionals_; ++i) {
496 // color it light grey, if it is to be removed when the cursor leaves
497 if (i == argsInLook_) {
498 optData->push_back(MathAtom(
499 new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
500 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
503 optData->push_back(MathAtom(new InsetMathChar('[')));
504 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
505 optData->push_back(MathAtom(new InsetMathChar(']')));
510 for (; i < numargs_; ++i) {
512 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
513 if (i >= argsInLook_) {
514 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
515 Color_mathbg, Color_mathmacrooldarg,
516 MathAtom(new InsetMathBrace(arg)))));
518 look_.push_back(MathAtom(new InsetMathBrace(arg)));
520 for (; i < argsInLook_; ++i) {
522 arg.push_back(MathAtom(new MathMacroArgument(i + 1)));
523 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
524 Color_mathbg, Color_mathmacronewarg,
525 MathAtom(new InsetMathBrace(arg)))));
529 look_.push_back(MathAtom(new InsetMathChar(':')));
530 look_.push_back(MathAtom(new InsetMathChar('=')));
533 look_.push_back(MathAtom(
534 new InsetLabelBox(buffer_, MathAtom(
535 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
538 look_.push_back(MathAtom(
539 new DisplayLabelBox(buffer_, MathAtom(
540 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
544 void MathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
546 Changer dummy1 = mi.base.changeFontSet("mathnormal");
547 Changer dummy2 = mi.base.changeStyle(LM_ST_TEXT);
550 MacroData const * macro = 0;
552 macro = mi.macrocontext.get(name());
555 int argsInDef = maxArgumentInDefinition();
556 if (lookOutdated_ || argsInDef != argsInLook_) {
557 lookOutdated_ = false;
558 createLook(argsInDef);
561 /// metrics for inset contents
565 // first phase, premetric:
567 look_.metrics(mi, dim);
568 labelBoxAscent_ = dim.asc;
569 labelBoxDescent_ = dim.des;
571 // second phase, main metric:
573 look_.metrics(mi, dim);
582 setDimCache(mi, dim);
586 void MathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
588 // FIXME: Calling Changer on the same object repeatedly is inefficient.
589 Changer dummy0 = pi.base.font.changeColor(Color_math);
590 Changer dummy1 = pi.base.changeFontSet("mathnormal");
591 Changer dummy2 = pi.base.changeStyle(LM_ST_TEXT);
593 setPosCache(pi, x, y);
594 Dimension const dim = dimension(*pi.base.bv);
597 int const a = y - dim.asc + 1;
598 int const w = dim.wid - 2;
599 int const h = dim.height() - 2;
600 pi.pain.rectangle(x, a, w, h, Color_mathframe);
602 // just to be sure: set some dummy values for coord cache
603 for (idx_type i = 0; i < nargs(); ++i)
604 cell(i).setXY(*pi.base.bv, x, y);
607 look_.draw(pi, x + 3, y);
611 void MathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
614 cur.screenUpdateFlags(Update::SinglePar);
615 InsetMathNest::edit(cur, front, entry_from);
619 bool MathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
621 unsigned int const nargs_before = nargs();
622 commitEditChanges(cur, old);
624 cur.screenUpdateFlags(Update::Force);
625 // If we have removed a cell, we might have invalidated the cursor
626 return InsetMathNest::notifyCursorLeaves(old, cur)
627 || nargs() < nargs_before;
631 void MathMacroTemplate::removeArguments(Cursor & cur,
632 DocIterator const & /*inset_pos*/, int from, int to)
634 DocIterator it = doc_iterator_begin(&buffer(), this);
635 for (; it; it.forwardChar()) {
638 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
640 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
641 int n = arg->number() - 1;
642 if (from <= n && n <= to) {
643 int cellSlice = cur.find(it.cell());
644 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
645 --cur[cellSlice].pos();
647 it.cell().erase(it.pos());
655 void MathMacroTemplate::shiftArguments(size_t from, int by)
657 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
660 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
662 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
663 if (arg->number() >= int(from) + 1)
664 arg->setNumber(arg->number() + by);
671 int MathMacroTemplate::maxArgumentInDefinition() const
673 // We don't have a buffer when pasting from the clipboard (bug 6014).
674 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
676 DocIterator it = doc_iterator_begin(macro_buffer, this);
678 for (; it; it.forwardChar()) {
681 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
683 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
684 maxArg = std::max(int(arg->number()), maxArg);
690 void MathMacroTemplate::insertMissingArguments(int maxArg)
692 bool found[9] = { false, false, false, false, false, false, false, false, false };
693 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
695 // search for #n macros arguments
696 DocIterator it = doc_iterator_begin(&buffer(), this);
698 for (; it && it[0].idx() == idx; it.forwardChar()) {
701 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
703 MathMacroArgument * arg = static_cast<MathMacroArgument*>(it.nextInset());
704 found[arg->number() - 1] = true;
708 for (int i = 0; i < maxArg; ++i) {
712 cell(idx).push_back(MathAtom(new MathMacroArgument(i + 1)));
717 void MathMacroTemplate::changeArity(Cursor & cur,
718 DocIterator const & inset_pos, int newNumArg)
720 // remove parameter which do not appear anymore in the definition
721 for (int i = numargs_; i > newNumArg; --i)
722 removeParameter(cur, inset_pos, numargs_ - 1, true);
724 // add missing parameter
725 for (int i = numargs_; i < newNumArg; ++i)
726 insertParameter(cur, inset_pos, numargs_, true, false);
731 class AddRemoveMacroInstanceFix
735 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
737 void operator()(MathMacro * macro)
739 if (macro->folded()) {
741 macro->insertArgument(n_);
743 macro->removeArgument(n_);
756 class OptionalsMacroInstanceFix
760 OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
762 void operator()(MathMacro * macro)
764 macro->setOptionals(optionals_);
774 class NullMacroInstanceFix
778 void operator()(MathMacro * ) {}
783 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
784 docstring const & name, F & fix)
786 // goto position behind macro template
787 DocIterator dit = inset_pos;
789 dit.top().forwardPos();
791 // remember hull to trigger preview reload
792 DocIterator hull(dit.buffer());
793 bool preview_reload_needed = false;
794 set<DocIterator> preview_hulls;
796 // iterate over all positions until macro is redefined
797 for (; dit; dit.forwardPos()) {
798 // left the outer hull?
799 if (!hull.empty() && dit.depth() == hull.depth()) {
800 // schedule reload of the preview if necessary
801 if (preview_reload_needed) {
802 preview_hulls.insert(hull);
803 preview_reload_needed = false;
808 // only until a macro is redefined
809 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
810 MathMacroTemplate const & macroTemplate
811 = static_cast<MathMacroTemplate const &>(dit.inset());
812 if (macroTemplate.name() == name)
816 // in front of macro instance?
817 Inset * inset = dit.nextInset();
820 InsetMath * insetMath = inset->asInsetMath();
824 // in front of outer hull?
825 InsetMathHull * inset_hull = insetMath->asHullInset();
826 if (inset_hull && hull.empty()) {
827 // remember this for later preview reload
831 MathMacro * macro = insetMath->asMacro();
832 if (macro && macro->name() == name && macro->folded()) {
834 if (RenderPreview::previewMath())
835 preview_reload_needed = true;
839 if (!preview_hulls.empty()) {
840 // reload the scheduled previews
841 set<DocIterator>::const_iterator sit = preview_hulls.begin();
842 set<DocIterator>::const_iterator end = preview_hulls.end();
843 for (; sit != end; ++sit) {
844 InsetMathHull * inset_hull =
845 sit->nextInset()->asInsetMath()->asHullInset();
847 inset_hull->reloadPreview(*sit);
849 cur.screenUpdateFlags(Update::Force);
854 void MathMacroTemplate::commitEditChanges(Cursor & cur,
855 DocIterator const & inset_pos)
857 int args_in_def = maxArgumentInDefinition();
858 if (args_in_def != numargs_) {
859 // FIXME: implement precise undo handling (only a few places
861 cur.recordUndoFullBuffer();
862 changeArity(cur, inset_pos, args_in_def);
864 insertMissingArguments(args_in_def);
866 // make sure the preview are up to date
867 NullMacroInstanceFix fix;
868 fixMacroInstances(cur, inset_pos, name(), fix);
872 void MathMacroTemplate::insertParameter(Cursor & cur,
873 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
875 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
880 shiftArguments(pos, 1);
882 cell(defIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
883 if (!cell(displayIdx()).empty())
884 cell(displayIdx()).push_back(MathAtom(new MathMacroArgument(pos + 1)));
888 // fix macro instances
889 AddRemoveMacroInstanceFix fix(pos, true);
890 fixMacroInstances(cur, inset_pos, name(), fix);
898 void MathMacroTemplate::removeParameter(Cursor & cur,
899 DocIterator const & inset_pos, int pos, bool greedy)
901 if (pos < numargs_ && pos >= 0) {
903 removeArguments(cur, inset_pos, pos, pos);
904 shiftArguments(pos + 1, -1);
906 // removed optional parameter?
907 if (pos < optionals_) {
909 optionalValues_[pos] = cell(optIdx(pos));
910 cells_.erase(cells_.begin() + optIdx(pos));
913 int macroSlice = cur.find(this);
914 if (macroSlice != -1) {
915 if (cur[macroSlice].idx() == optIdx(pos)) {
916 cur.cutOff(macroSlice);
917 cur[macroSlice].idx() = 1;
918 cur[macroSlice].pos() = 0;
919 } else if (cur[macroSlice].idx() > optIdx(pos))
920 --cur[macroSlice].idx();
925 // fix macro instances
926 AddRemoveMacroInstanceFix fix(pos, false);
927 fixMacroInstances(cur, inset_pos, name(), fix);
935 void MathMacroTemplate::makeOptional(Cursor & cur,
936 DocIterator const & inset_pos)
938 if (numargs_ > 0 && optionals_ < numargs_) {
940 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
942 int macroSlice = cur.find(this);
943 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
944 ++cur[macroSlice].idx();
946 // fix macro instances
947 OptionalsMacroInstanceFix fix(optionals_);
948 fixMacroInstances(cur, inset_pos, name(), fix);
955 void MathMacroTemplate::makeNonOptional(Cursor & cur,
956 DocIterator const & inset_pos)
958 if (numargs_ > 0 && optionals_ > 0) {
961 // store default value for later if the user changes his mind
962 optionalValues_[optionals_] = cell(optIdx(optionals_));
963 cells_.erase(cells_.begin() + optIdx(optionals_));
966 int macroSlice = cur.find(this);
967 if (macroSlice != -1) {
968 if (cur[macroSlice].idx() > optIdx(optionals_))
969 --cur[macroSlice].idx();
970 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
971 cur.cutOff(macroSlice);
972 cur[macroSlice].idx() = optIdx(optionals_);
973 cur[macroSlice].pos() = 0;
977 // fix macro instances
978 OptionalsMacroInstanceFix fix(optionals_);
979 fixMacroInstances(cur, inset_pos, name(), fix);
986 void MathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
988 string const arg = to_utf8(cmd.argument());
989 switch (cmd.action()) {
991 case LFUN_MATH_MACRO_ADD_PARAM:
993 commitEditChanges(cur, cur);
994 // FIXME: implement precise undo handling (only a few places
996 cur.recordUndoFullBuffer();
997 size_t pos = numargs_;
999 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1000 insertParameter(cur, cur, pos);
1005 case LFUN_MATH_MACRO_REMOVE_PARAM:
1007 commitEditChanges(cur, cur);
1008 // FIXME: implement precise undo handling (only a few places
1010 cur.recordUndoFullBuffer();
1011 size_t pos = numargs_ - 1;
1013 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1014 removeParameter(cur, cur, pos);
1018 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1020 commitEditChanges(cur, cur);
1021 // FIXME: implement precise undo handling (only a few places
1023 cur.recordUndoFullBuffer();
1024 insertParameter(cur, cur, numargs_, true);
1028 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1030 commitEditChanges(cur, cur);
1031 // FIXME: implement precise undo handling (only a few places
1033 cur.recordUndoFullBuffer();
1034 removeParameter(cur, cur, numargs_ - 1, true);
1038 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1039 commitEditChanges(cur, cur);
1040 // FIXME: implement precise undo handling (only a few places
1042 cur.recordUndoFullBuffer();
1043 makeOptional(cur, cur);
1046 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1047 commitEditChanges(cur, cur);
1048 // FIXME: implement precise undo handling (only a few places
1050 cur.recordUndoFullBuffer();
1051 makeNonOptional(cur, cur);
1054 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1056 commitEditChanges(cur, cur);
1057 // FIXME: implement precise undo handling (only a few places
1059 cur.recordUndoFullBuffer();
1060 insertParameter(cur, cur, optionals_);
1061 makeOptional(cur, cur);
1065 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1066 if (optionals_ > 0) {
1067 commitEditChanges(cur, cur);
1068 // FIXME: implement precise undo handling (only a few places
1070 cur.recordUndoFullBuffer();
1071 removeParameter(cur, cur, optionals_ - 1);
1074 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1075 if (numargs_ == optionals_) {
1076 commitEditChanges(cur, cur);
1077 // FIXME: implement precise undo handling (only a few places
1079 cur.recordUndoFullBuffer();
1080 insertParameter(cur, cur, 0, true);
1081 makeOptional(cur, cur);
1086 InsetMathNest::doDispatch(cur, cmd);
1092 bool MathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1093 FuncStatus & flag) const
1096 string const arg = to_utf8(cmd.argument());
1097 switch (cmd.action()) {
1098 case LFUN_MATH_MACRO_ADD_PARAM: {
1099 int num = numargs_ + 1;
1101 num = convert<int>(arg);
1102 bool on = (num >= optionals_
1103 && numargs_ < 9 && num <= numargs_ + 1);
1104 flag.setEnabled(on);
1108 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1109 flag.setEnabled(numargs_ < 9);
1112 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1113 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1116 num = convert<int>(arg);
1117 flag.setEnabled(num >= 1 && num <= numargs_);
1121 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1122 flag.setEnabled(numargs_ > 0
1123 && optionals_ < numargs_
1124 && type_ != MacroTypeDef);
1127 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1128 flag.setEnabled(optionals_ > 0
1129 && type_ != MacroTypeDef);
1132 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1133 flag.setEnabled(numargs_ < 9);
1136 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1137 flag.setEnabled(optionals_ > 0);
1140 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1141 flag.setEnabled(numargs_ == 0
1142 && type_ != MacroTypeDef);
1145 case LFUN_IN_MATHMACROTEMPLATE:
1146 flag.setEnabled(true);
1150 ret = InsetMathNest::getStatus(cur, cmd, flag);
1157 void MathMacroTemplate::read(Lexer & lex)
1159 MathData ar(buffer_);
1160 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1161 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1162 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1163 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1166 operator=( *(ar[0]->asMacroTemplate()) );
1172 void MathMacroTemplate::write(ostream & os) const
1174 odocstringstream oss;
1175 otexrowstream ots(oss, false);
1176 WriteStream wi(ots, 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 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";
1392 void MathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1395 shared_ptr<Toc> toc = buffer().tocBackend().toc("math-macro");
1398 str = bformat(_("Invalid macro! \\%1$s"), name());
1400 str = "\\" + name();
1401 toc->push_back(TocItem(pit, 0, str, output_active));