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"
25 #include "InsetMathMacroArgument.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 InsetMathMacroTemplate const & parent, bool frame = false);
67 InsetLabelBox(Buffer * buf, docstring label, InsetMathMacroTemplate const & parent,
70 void metrics(MetricsInfo & mi, Dimension & dim) const;
72 void draw(PainterInfo &, int x, int y) const;
76 InsetMathMacroTemplate const & parent_;
78 Inset * clone() const;
80 docstring const label_;
86 InsetLabelBox::InsetLabelBox(Buffer * buf, MathAtom const & atom, docstring 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 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(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 InsetDisplayLabelBox : public InsetLabelBox {
189 InsetDisplayLabelBox(Buffer * buf, MathAtom const & atom, docstring label,
190 InsetMathMacroTemplate const & parent);
193 marker_type marker(BufferView const *) const;
195 void metrics(MetricsInfo & mi, Dimension & dim) const;
197 void draw(PainterInfo &, int x, int y) const;
201 Inset * clone() const;
205 InsetDisplayLabelBox::InsetDisplayLabelBox(Buffer * buf, MathAtom const & atom,
207 InsetMathMacroTemplate const & parent)
208 : InsetLabelBox(buf, atom, label, parent, true)
214 Inset * InsetDisplayLabelBox::clone() const
216 return new InsetDisplayLabelBox(*this);
220 InsetMath::marker_type InsetDisplayLabelBox::marker(BufferView const * bv) const
222 if (parent_.editing(bv)
223 || !parent_.cell(parent_.displayIdx()).empty())
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()) {
242 void InsetDisplayLabelBox::draw(PainterInfo & pi, int x, int y) const
244 if (parent_.editing(pi.base.bv)
245 || !parent_.cell(parent_.displayIdx()).empty()) {
246 InsetLabelBox::draw(pi, x, y);
248 bool enabled = pi.pain.isDrawingEnabled();
249 pi.pain.setDrawingEnabled(false);
250 InsetLabelBox::draw(pi, x, y);
251 pi.pain.setDrawingEnabled(enabled);
256 //////////////////////////////////////////////////////////////////////
258 class InsetMathWrapper : public InsetMath {
261 InsetMathWrapper(MathData const * value) : value_(value) {}
263 void metrics(MetricsInfo & mi, Dimension & dim) const;
265 void draw(PainterInfo &, int x, int y) const;
269 Inset * clone() const;
271 MathData const * value_;
275 Inset * InsetMathWrapper::clone() const
277 return new InsetMathWrapper(*this);
281 void InsetMathWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
283 value_->metrics(mi, dim);
287 void InsetMathWrapper::draw(PainterInfo & pi, int x, int y) const
289 value_->draw(pi, x, y);
293 ///////////////////////////////////////////////////////////////////////
294 class InsetColoredCell : public InsetMathNest {
297 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max);
299 InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom);
301 void draw(PainterInfo &, int x, int y) const;
303 void metrics(MetricsInfo & mi, Dimension & dim) const;
307 Inset * clone() const;
315 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max)
316 : InsetMathNest(buf, 1), min_(min), max_(max)
321 InsetColoredCell::InsetColoredCell(Buffer * buf, ColorCode min, ColorCode max, MathAtom const & atom)
322 : InsetMathNest(buf, 1), min_(min), max_(max)
324 cell(0).insert(0, atom);
328 Inset * InsetColoredCell::clone() const
330 return new InsetColoredCell(*this);
334 void InsetColoredCell::metrics(MetricsInfo & mi, Dimension & dim) const
336 cell(0).metrics(mi, dim);
340 void InsetColoredCell::draw(PainterInfo & pi, int x, int y) const
342 pi.pain.enterMonochromeMode(min_, max_);
343 cell(0).draw(pi, x, y);
344 pi.pain.leaveMonochromeMode();
348 ///////////////////////////////////////////////////////////////////////
350 class InsetNameWrapper : public InsetMathWrapper {
353 InsetNameWrapper(MathData const * value, InsetMathMacroTemplate const & parent);
355 void metrics(MetricsInfo & mi, Dimension & dim) const;
357 void draw(PainterInfo &, int x, int y) const;
361 InsetMathMacroTemplate const & parent_;
363 Inset * clone() const;
367 InsetNameWrapper::InsetNameWrapper(MathData const * value,
368 InsetMathMacroTemplate const & parent)
369 : InsetMathWrapper(value), parent_(parent)
374 Inset * InsetNameWrapper::clone() const
376 return new InsetNameWrapper(*this);
380 void InsetNameWrapper::metrics(MetricsInfo & mi, Dimension & dim) const
382 Changer dummy = mi.base.changeFontSet("textit");
383 InsetMathWrapper::metrics(mi, dim);
384 dim.wid += mathed_string_width(mi.base.font, from_ascii("\\"));
388 void InsetNameWrapper::draw(PainterInfo & pi, int x, int y) const
390 ColorCode const color = parent_.validMacro() ? Color_latex : Color_error;
392 Changer dummy = pi.base.changeFontSet("textit");
393 Changer dummy2 = pi.base.font.changeColor(color);
396 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
397 x += mathed_string_width(pi.base.font, from_ascii("\\"));
400 InsetMathWrapper::draw(pi, x, y);
404 ///////////////////////////////////////////////////////////////////////
407 InsetMathMacroTemplate::InsetMathMacroTemplate(Buffer * buf)
408 : InsetMathNest(buf, 3), numargs_(0), argsInLook_(0), optionals_(0),
409 type_(MacroTypeNewcommand), redefinition_(false), lookOutdated_(true),
410 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
416 InsetMathMacroTemplate::InsetMathMacroTemplate(Buffer * buf, docstring const & name, int numargs,
417 int optionals, MacroType type, vector<MathData> const & optionalValues,
418 MathData const & def, MathData const & display)
419 : InsetMathNest(buf, optionals + 3), numargs_(numargs), argsInLook_(numargs),
420 optionals_(optionals), optionalValues_(optionalValues),
421 type_(type), redefinition_(false), lookOutdated_(true),
422 premetrics_(false), labelBoxAscent_(0), labelBoxDescent_(0)
427 lyxerr << "InsetMathMacroTemplate::InsetMathMacroTemplate: wrong # of arguments: "
430 asArray(name, cell(0));
431 optionalValues_.resize(9);
432 for (int i = 0; i < optionals_; ++i)
433 cell(optIdx(i)) = optionalValues_[i];
434 cell(defIdx()) = def;
435 cell(displayIdx()) = display;
441 bool InsetMathMacroTemplate::fromString(docstring const & str)
443 MathData ar(buffer_);
444 mathed_parse_cell(ar, str, Parse::NORMAL);
445 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
446 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
447 asArray(from_ascii("invalidmacro"), cell(0));
448 // The macro template does not make sense after this.
451 operator=( *(ar[0]->asMacroTemplate()) );
458 Inset * InsetMathMacroTemplate::clone() const
460 InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(*this);
461 // the parent pointers of the proxy insets above will point to
462 // to the old template. Hence, the look must be updated.
468 docstring InsetMathMacroTemplate::name() const
470 return asString(cell(0));
474 void InsetMathMacroTemplate::updateToContext(MacroContext const & mc)
476 redefinition_ = mc.get(name()) != 0;
480 void InsetMathMacroTemplate::updateLook() const
482 lookOutdated_ = true;
486 void InsetMathMacroTemplate::createLook(int args) const
492 look_.push_back(MathAtom(
493 new InsetLabelBox(buffer_, _("Name"), *this, false)));
494 MathData & nameData = look_[look_.size() - 1].nucleus()->cell(0);
495 nameData.push_back(MathAtom(new InsetNameWrapper(&cell(0), *this)));
499 if (optionals_ > 0) {
500 look_.push_back(MathAtom(
501 new InsetLabelBox(buffer_, _("optional"), *this, false)));
503 MathData * optData = &look_[look_.size() - 1].nucleus()->cell(0);
504 for (; i < optionals_; ++i) {
505 // color it light grey, if it is to be removed when the cursor leaves
506 if (i == argsInLook_) {
507 optData->push_back(MathAtom(
508 new InsetColoredCell(buffer_, Color_mathbg, Color_mathmacrooldarg)));
509 optData = &(*optData)[optData->size() - 1].nucleus()->cell(0);
512 optData->push_back(MathAtom(new InsetMathChar('[')));
513 optData->push_back(MathAtom(new InsetMathWrapper(&cell(1 + i))));
514 optData->push_back(MathAtom(new InsetMathChar(']')));
519 for (; i < numargs_; ++i) {
521 arg.push_back(MathAtom(new InsetMathMacroArgument(i + 1)));
522 if (i >= argsInLook_) {
523 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
524 Color_mathbg, Color_mathmacrooldarg,
525 MathAtom(new InsetMathBrace(arg)))));
527 look_.push_back(MathAtom(new InsetMathBrace(arg)));
529 for (; i < argsInLook_; ++i) {
531 arg.push_back(MathAtom(new InsetMathMacroArgument(i + 1)));
532 look_.push_back(MathAtom(new InsetColoredCell(buffer_,
533 Color_mathbg, Color_mathmacronewarg,
534 MathAtom(new InsetMathBrace(arg)))));
538 look_.push_back(MathAtom(new InsetMathChar(':')));
539 look_.push_back(MathAtom(new InsetMathChar('=')));
542 look_.push_back(MathAtom(
543 new InsetLabelBox(buffer_, MathAtom(
544 new InsetMathWrapper(&cell(defIdx()))), _("TeX"), *this, true)));
547 look_.push_back(MathAtom(
548 new InsetDisplayLabelBox(buffer_, MathAtom(
549 new InsetMathWrapper(&cell(displayIdx()))), _("LyX"), *this)));
553 void InsetMathMacroTemplate::metrics(MetricsInfo & mi, Dimension & dim) const
555 Changer dummy1 = mi.base.changeFontSet("mathnormal");
556 Changer dummy2 = mi.base.font.changeStyle(LM_ST_TEXT);
559 MacroData const * macro = 0;
561 macro = mi.macrocontext.get(name());
564 int argsInDef = maxArgumentInDefinition();
565 if (lookOutdated_ || argsInDef != argsInLook_) {
566 lookOutdated_ = false;
567 createLook(argsInDef);
570 /// metrics for inset contents
574 // first phase, premetric:
576 look_.metrics(mi, dim);
577 labelBoxAscent_ = dim.asc;
578 labelBoxDescent_ = dim.des;
580 // second phase, main metric:
582 look_.metrics(mi, dim);
593 void InsetMathMacroTemplate::draw(PainterInfo & pi, int x, int y) const
595 // FIXME: Calling Changer on the same object repeatedly is inefficient.
596 Changer dummy0 = pi.base.font.changeColor(Color_math);
597 Changer dummy1 = pi.base.changeFontSet("mathnormal");
598 Changer dummy2 = pi.base.font.changeStyle(LM_ST_TEXT);
600 Dimension const dim = dimension(*pi.base.bv);
603 int const a = y - dim.asc + 1;
604 int const w = dim.wid - 2;
605 int const h = dim.height() - 2;
606 pi.pain.rectangle(x + 1, a, w, h, Color_mathframe);
608 // just to be sure: set some dummy values for coord cache
609 for (idx_type i = 0; i < nargs(); ++i)
610 cell(i).setXY(*pi.base.bv, x, y);
613 look_.draw(pi, x + 3, y);
617 void InsetMathMacroTemplate::edit(Cursor & cur, bool front, EntryDirection entry_from)
620 cur.screenUpdateFlags(Update::SinglePar);
621 InsetMathNest::edit(cur, front, entry_from);
625 bool InsetMathMacroTemplate::notifyCursorLeaves(Cursor const & old, Cursor & cur)
627 unsigned int const nargs_before = nargs();
628 commitEditChanges(cur, old);
630 cur.screenUpdateFlags(Update::Force);
631 // If we have removed a cell, we might have invalidated the cursor
632 return InsetMathNest::notifyCursorLeaves(old, cur)
633 || nargs() < nargs_before;
637 void InsetMathMacroTemplate::removeArguments(Cursor & cur,
638 DocIterator const & /*inset_pos*/, int from, int to)
640 DocIterator it = doc_iterator_begin(&buffer(), this);
641 for (; it; it.forwardChar()) {
644 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
646 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
647 int n = arg->number() - 1;
648 if (from <= n && n <= to) {
649 int cellSlice = cur.find(it.cell());
650 if (cellSlice != -1 && cur[cellSlice].pos() > it.pos())
651 --cur[cellSlice].pos();
653 it.cell().erase(it.pos());
661 void InsetMathMacroTemplate::shiftArguments(size_t from, int by)
663 for (DocIterator it = doc_iterator_begin(&buffer(), this); it; it.forwardChar()) {
666 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
668 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
669 if (arg->number() >= int(from) + 1)
670 arg->setNumber(arg->number() + by);
677 int InsetMathMacroTemplate::maxArgumentInDefinition() const
679 // We don't have a buffer when pasting from the clipboard (bug 6014).
680 Buffer const * macro_buffer = isBufferLoaded() ? &buffer() : 0;
682 DocIterator it = doc_iterator_begin(macro_buffer, this);
684 for (; it; it.forwardChar()) {
687 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
689 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
690 maxArg = std::max(int(arg->number()), maxArg);
696 void InsetMathMacroTemplate::insertMissingArguments(int maxArg)
698 bool found[9] = { false, false, false, false, false, false, false, false, false };
699 idx_type idx = cell(displayIdx()).empty() ? defIdx() : displayIdx();
701 // search for #n macros arguments
702 DocIterator it = doc_iterator_begin(&buffer(), this);
704 for (; it && it[0].idx() == idx; it.forwardChar()) {
707 if (it.nextInset()->lyxCode() != MATH_MACROARG_CODE)
709 InsetMathMacroArgument * arg = static_cast<InsetMathMacroArgument*>(it.nextInset());
710 found[arg->number() - 1] = true;
714 for (int i = 0; i < maxArg; ++i) {
718 cell(idx).push_back(MathAtom(new InsetMathMacroArgument(i + 1)));
723 void InsetMathMacroTemplate::changeArity(Cursor & cur,
724 DocIterator const & inset_pos, int newNumArg)
726 // remove parameter which do not appear anymore in the definition
727 for (int i = numargs_; i > newNumArg; --i)
728 removeParameter(cur, inset_pos, numargs_ - 1, true);
730 // add missing parameter
731 for (int i = numargs_; i < newNumArg; ++i)
732 insertParameter(cur, inset_pos, numargs_, true, false);
737 class AddRemoveMacroInstanceFix
741 AddRemoveMacroInstanceFix(int n, bool insert) : n_(n), insert_(insert) {}
743 void operator()(InsetMathMacro * macro)
745 if (macro->folded()) {
747 macro->insertArgument(n_);
749 macro->removeArgument(n_);
762 class OptionalsMacroInstanceFix
766 OptionalsMacroInstanceFix(int optionals) : optionals_(optionals) {}
768 void operator()(InsetMathMacro * macro)
770 macro->setOptionals(optionals_);
780 class NullMacroInstanceFix
784 void operator()(InsetMathMacro * ) {}
789 void fixMacroInstances(Cursor & cur, DocIterator const & inset_pos,
790 docstring const & name, F & fix)
792 // goto position behind macro template
793 DocIterator dit = inset_pos;
795 dit.top().forwardPos();
797 // remember hull to trigger preview reload
798 DocIterator hull(dit.buffer());
799 bool preview_reload_needed = false;
800 set<DocIterator> preview_hulls;
802 // iterate over all positions until macro is redefined
803 for (; dit; dit.forwardPos()) {
804 // left the outer hull?
805 if (!hull.empty() && dit.depth() == hull.depth()) {
806 // schedule reload of the preview if necessary
807 if (preview_reload_needed) {
808 preview_hulls.insert(hull);
809 preview_reload_needed = false;
814 // only until a macro is redefined
815 if (dit.inset().lyxCode() == MATHMACRO_CODE) {
816 InsetMathMacroTemplate const & macroTemplate
817 = static_cast<InsetMathMacroTemplate const &>(dit.inset());
818 if (macroTemplate.name() == name)
822 // in front of macro instance?
823 Inset * inset = dit.nextInset();
826 InsetMath * insetMath = inset->asInsetMath();
830 // in front of outer hull?
831 InsetMathHull * inset_hull = insetMath->asHullInset();
832 if (inset_hull && hull.empty()) {
833 // remember this for later preview reload
837 InsetMathMacro * macro = insetMath->asMacro();
838 if (macro && macro->name() == name && macro->folded()) {
840 if (RenderPreview::previewMath())
841 preview_reload_needed = true;
845 if (!preview_hulls.empty()) {
846 // reload the scheduled previews
847 set<DocIterator>::const_iterator sit = preview_hulls.begin();
848 set<DocIterator>::const_iterator end = preview_hulls.end();
849 for (; sit != end; ++sit) {
850 InsetMathHull * inset_hull =
851 sit->nextInset()->asInsetMath()->asHullInset();
853 inset_hull->reloadPreview(*sit);
855 cur.screenUpdateFlags(Update::Force);
860 void InsetMathMacroTemplate::commitEditChanges(Cursor & cur,
861 DocIterator const & inset_pos)
863 int args_in_def = maxArgumentInDefinition();
864 if (args_in_def != numargs_) {
865 // FIXME: implement precise undo handling (only a few places
867 cur.recordUndoFullBuffer();
868 changeArity(cur, inset_pos, args_in_def);
870 insertMissingArguments(args_in_def);
872 // make sure the preview are up to date
873 NullMacroInstanceFix fix;
874 fixMacroInstances(cur, inset_pos, name(), fix);
878 void InsetMathMacroTemplate::insertParameter(Cursor & cur,
879 DocIterator const & inset_pos, int pos, bool greedy, bool addarg)
881 if (pos <= numargs_ && pos >= optionals_ && numargs_ < 9) {
886 shiftArguments(pos, 1);
888 cell(defIdx()).push_back(MathAtom(new InsetMathMacroArgument(pos + 1)));
889 if (!cell(displayIdx()).empty())
890 cell(displayIdx()).push_back(MathAtom(new InsetMathMacroArgument(pos + 1)));
894 // fix macro instances
895 AddRemoveMacroInstanceFix fix(pos, true);
896 fixMacroInstances(cur, inset_pos, name(), fix);
904 void InsetMathMacroTemplate::removeParameter(Cursor & cur,
905 DocIterator const & inset_pos, int pos, bool greedy)
907 if (pos < numargs_ && pos >= 0) {
909 removeArguments(cur, inset_pos, pos, pos);
910 shiftArguments(pos + 1, -1);
912 // removed optional parameter?
913 if (pos < optionals_) {
915 optionalValues_[pos] = cell(optIdx(pos));
916 cells_.erase(cells_.begin() + optIdx(pos));
919 int macroSlice = cur.find(this);
920 if (macroSlice != -1) {
921 if (cur[macroSlice].idx() == optIdx(pos)) {
922 cur.cutOff(macroSlice);
923 cur[macroSlice].idx() = 1;
924 cur[macroSlice].pos() = 0;
925 } else if (cur[macroSlice].idx() > optIdx(pos))
926 --cur[macroSlice].idx();
931 // fix macro instances
932 AddRemoveMacroInstanceFix fix(pos, false);
933 fixMacroInstances(cur, inset_pos, name(), fix);
941 void InsetMathMacroTemplate::makeOptional(Cursor & cur,
942 DocIterator const & inset_pos)
944 if (numargs_ > 0 && optionals_ < numargs_) {
946 cells_.insert(cells_.begin() + optIdx(optionals_ - 1), optionalValues_[optionals_ - 1]);
948 int macroSlice = cur.find(this);
949 if (macroSlice != -1 && cur[macroSlice].idx() >= optIdx(optionals_ - 1))
950 ++cur[macroSlice].idx();
952 // fix macro instances
953 OptionalsMacroInstanceFix fix(optionals_);
954 fixMacroInstances(cur, inset_pos, name(), fix);
961 void InsetMathMacroTemplate::makeNonOptional(Cursor & cur,
962 DocIterator const & inset_pos)
964 if (numargs_ > 0 && optionals_ > 0) {
967 // store default value for later if the user changes his mind
968 optionalValues_[optionals_] = cell(optIdx(optionals_));
969 cells_.erase(cells_.begin() + optIdx(optionals_));
972 int macroSlice = cur.find(this);
973 if (macroSlice != -1) {
974 if (cur[macroSlice].idx() > optIdx(optionals_))
975 --cur[macroSlice].idx();
976 else if (cur[macroSlice].idx() == optIdx(optionals_)) {
977 cur.cutOff(macroSlice);
978 cur[macroSlice].idx() = optIdx(optionals_);
979 cur[macroSlice].pos() = 0;
983 // fix macro instances
984 OptionalsMacroInstanceFix fix(optionals_);
985 fixMacroInstances(cur, inset_pos, name(), fix);
992 void InsetMathMacroTemplate::doDispatch(Cursor & cur, FuncRequest & cmd)
994 string const arg = to_utf8(cmd.argument());
995 switch (cmd.action()) {
997 case LFUN_MATH_MACRO_ADD_PARAM:
999 commitEditChanges(cur, cur);
1000 // FIXME: implement precise undo handling (only a few places
1002 cur.recordUndoFullBuffer();
1003 size_t pos = numargs_;
1005 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1006 insertParameter(cur, cur, pos);
1011 case LFUN_MATH_MACRO_REMOVE_PARAM:
1013 commitEditChanges(cur, cur);
1014 // FIXME: implement precise undo handling (only a few places
1016 cur.recordUndoFullBuffer();
1017 size_t pos = numargs_ - 1;
1019 pos = (size_t)convert<int>(arg) - 1; // it is checked for >=0 in getStatus
1020 removeParameter(cur, cur, pos);
1024 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1026 commitEditChanges(cur, cur);
1027 // FIXME: implement precise undo handling (only a few places
1029 cur.recordUndoFullBuffer();
1030 insertParameter(cur, cur, numargs_, true);
1034 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1036 commitEditChanges(cur, cur);
1037 // FIXME: implement precise undo handling (only a few places
1039 cur.recordUndoFullBuffer();
1040 removeParameter(cur, cur, numargs_ - 1, true);
1044 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1045 commitEditChanges(cur, cur);
1046 // FIXME: implement precise undo handling (only a few places
1048 cur.recordUndoFullBuffer();
1049 makeOptional(cur, cur);
1052 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1053 commitEditChanges(cur, cur);
1054 // FIXME: implement precise undo handling (only a few places
1056 cur.recordUndoFullBuffer();
1057 makeNonOptional(cur, cur);
1060 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1062 commitEditChanges(cur, cur);
1063 // FIXME: implement precise undo handling (only a few places
1065 cur.recordUndoFullBuffer();
1066 insertParameter(cur, cur, optionals_);
1067 makeOptional(cur, cur);
1071 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1072 if (optionals_ > 0) {
1073 commitEditChanges(cur, cur);
1074 // FIXME: implement precise undo handling (only a few places
1076 cur.recordUndoFullBuffer();
1077 removeParameter(cur, cur, optionals_ - 1);
1080 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1081 if (numargs_ == optionals_) {
1082 commitEditChanges(cur, cur);
1083 // FIXME: implement precise undo handling (only a few places
1085 cur.recordUndoFullBuffer();
1086 insertParameter(cur, cur, 0, true);
1087 makeOptional(cur, cur);
1092 InsetMathNest::doDispatch(cur, cmd);
1098 bool InsetMathMacroTemplate::getStatus(Cursor & cur, FuncRequest const & cmd,
1099 FuncStatus & flag) const
1102 string const arg = to_utf8(cmd.argument());
1103 switch (cmd.action()) {
1104 case LFUN_MATH_MACRO_ADD_PARAM: {
1105 int num = numargs_ + 1;
1107 num = convert<int>(arg);
1108 bool on = (num >= optionals_
1109 && numargs_ < 9 && num <= numargs_ + 1);
1110 flag.setEnabled(on);
1114 case LFUN_MATH_MACRO_APPEND_GREEDY_PARAM:
1115 flag.setEnabled(numargs_ < 9);
1118 case LFUN_MATH_MACRO_REMOVE_GREEDY_PARAM:
1119 case LFUN_MATH_MACRO_REMOVE_PARAM: {
1122 num = convert<int>(arg);
1123 flag.setEnabled(num >= 1 && num <= numargs_);
1127 case LFUN_MATH_MACRO_MAKE_OPTIONAL:
1128 flag.setEnabled(numargs_ > 0
1129 && optionals_ < numargs_
1130 && type_ != MacroTypeDef);
1133 case LFUN_MATH_MACRO_MAKE_NONOPTIONAL:
1134 flag.setEnabled(optionals_ > 0
1135 && type_ != MacroTypeDef);
1138 case LFUN_MATH_MACRO_ADD_OPTIONAL_PARAM:
1139 flag.setEnabled(numargs_ < 9);
1142 case LFUN_MATH_MACRO_REMOVE_OPTIONAL_PARAM:
1143 flag.setEnabled(optionals_ > 0);
1146 case LFUN_MATH_MACRO_ADD_GREEDY_OPTIONAL_PARAM:
1147 flag.setEnabled(numargs_ == 0
1148 && type_ != MacroTypeDef);
1151 case LFUN_IN_MATHMACROTEMPLATE:
1152 flag.setEnabled(true);
1156 ret = InsetMathNest::getStatus(cur, cmd, flag);
1163 void InsetMathMacroTemplate::read(Lexer & lex)
1165 MathData ar(buffer_);
1166 mathed_parse_cell(ar, lex.getStream(), Parse::TRACKMACRO);
1167 if (ar.size() != 1 || !ar[0]->asMacroTemplate()) {
1168 lyxerr << "Cannot read macro from '" << ar << "'" << endl;
1169 lyxerr << "Read: " << to_utf8(asString(ar)) << endl;
1172 operator=( *(ar[0]->asMacroTemplate()) );
1178 void InsetMathMacroTemplate::write(ostream & os) const
1180 odocstringstream oss;
1181 otexrowstream ots(oss);
1182 WriteStream wi(ots, false, false, WriteStream::wsDefault);
1183 oss << "FormulaMacro\n";
1185 os << to_utf8(oss.str());
1189 void InsetMathMacroTemplate::write(WriteStream & os) const
1195 int InsetMathMacroTemplate::write(WriteStream & os, bool overwriteRedefinition) const
1200 if (optionals_ > 0) {
1201 // macros with optionals use the xargs package, e.g.:
1202 // \newcommandx{\foo}[2][usedefault, addprefix=\global,1=default]{#1,#2}
1203 // \long is implicit by xargs
1204 if (redefinition_ && !overwriteRedefinition)
1205 os << "\\renewcommandx";
1207 os << "\\newcommandx";
1209 os << "\\" << name()
1210 << "[" << numargs_ << "]"
1211 << "[usedefault, addprefix=\\global";
1212 for (int i = 0; i < optionals_; ++i) {
1213 docstring optValue = asString(cell(optIdx(i)));
1214 if (optValue.find(']') != docstring::npos
1215 || optValue.find(',') != docstring::npos)
1216 os << ", " << i + 1 << "="
1217 << "{" << cell(optIdx(i)) << "}";
1219 os << ", " << i + 1 << "="
1224 // Macros without optionals use standard _global_ \def macros:
1225 // \global\def\long\foo#1#2{#1,#2}
1226 // We use the \long prefix as this is the equivalent to \newcommand.
1227 // We cannot use \newcommand directly because \global does not work with it.
1228 os << "\\global\\long\\def\\" << name();
1229 docstring param = from_ascii("#0");
1230 for (int i = 1; i <= numargs_; ++i) {
1236 // in LyX output we use some pseudo syntax which is implementation
1237 // independent, e.g.
1238 // \newcommand{\foo}[2][default]{#1,#2}
1239 if (redefinition_ && !overwriteRedefinition)
1240 os << "\\renewcommand";
1242 os << "\\newcommand";
1243 os << "{\\" << name() << '}';
1245 os << '[' << numargs_ << ']';
1247 for (int i = 0; i < optionals_; ++i) {
1248 docstring optValue = asString(cell(optIdx(i)));
1249 if (optValue.find(']') != docstring::npos)
1250 os << "[{" << cell(optIdx(i)) << "}]";
1252 os << "[" << cell(optIdx(i)) << "]";
1256 os << "{" << cell(defIdx()) << "}";
1259 // writing .tex. done.
1263 // writing .lyx, write special .tex export only if necessary
1264 if (!cell(displayIdx()).empty()) {
1265 os << "\n{" << cell(displayIdx()) << '}';
1274 docstring InsetMathMacroTemplate::xhtml(XHTMLStream &, OutputParams const &) const
1279 int InsetMathMacroTemplate::plaintext(odocstringstream & os,
1280 OutputParams const &, size_t) const
1282 docstring const str = '[' + buffer().B_("math macro") + ']';
1289 bool InsetMathMacroTemplate::validName() const
1291 docstring n = name();
1296 // converting back and force doesn't swallow anything?
1299 if (asString(ma) != n)
1302 // valid characters?
1303 for (size_t i = 0; i < n.size(); ++i) {
1304 if (!(n[i] >= 'a' && n[i] <= 'z')
1305 && !(n[i] >= 'A' && n[i] <= 'Z')
1314 bool InsetMathMacroTemplate::validMacro() const
1320 bool InsetMathMacroTemplate::fixNameAndCheckIfValid()
1322 // check all the characters/insets in the name cell
1324 MathData & data = cell(0);
1325 while (i < data.size()) {
1326 InsetMathChar const * cinset = data[i]->asCharInset();
1328 // valid character in [a-zA-Z]?
1329 char_type c = cinset->getChar();
1330 if ((c >= 'a' && c <= 'z')
1331 || (c >= 'A' && c <= 'Z')) {
1341 // now it should be valid if anything in the name survived
1342 return !data.empty();
1346 void InsetMathMacroTemplate::validate(LaTeXFeatures & features) const
1348 // we need global optional macro arguments. They are not available
1349 // with \def, and \newcommand does not support global macros. So we
1350 // are bound to xargs also for the single-optional-parameter case.
1352 features.require("xargs");
1355 void InsetMathMacroTemplate::getDefaults(vector<docstring> & defaults) const
1357 defaults.resize(numargs_);
1358 for (int i = 0; i < optionals_; ++i)
1359 defaults[i] = asString(cell(optIdx(i)));
1363 docstring InsetMathMacroTemplate::definition() const
1365 return asString(cell(defIdx()));
1369 docstring InsetMathMacroTemplate::displayDefinition() const
1371 return asString(cell(displayIdx()));
1375 size_t InsetMathMacroTemplate::numArgs() const
1381 size_t InsetMathMacroTemplate::numOptionals() const
1387 void InsetMathMacroTemplate::infoize(odocstream & os) const
1389 os << bformat(_("Math Macro: \\%1$s"), name());
1393 string InsetMathMacroTemplate::contextMenuName() const
1395 return "context-math-macro-definition";
1399 void InsetMathMacroTemplate::addToToc(DocIterator const & pit, bool output_active,
1400 UpdateType, TocBackend & backend) const
1404 str = bformat(_("Invalid macro! \\%1$s"), name());
1406 str = "\\" + name();
1407 TocBuilder & b = backend.builder("math-macro");
1408 b.pushItem(pit, str, output_active);