3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Alejandro Aguilar Sierra
8 * \author Stefan Schimanski
10 * Full author contact details are available in file CREDITS.
15 #include "MathMacro.h"
17 #include "InsetMathChar.h"
18 #include "MathCompletionList.h"
19 #include "MathExtern.h"
20 #include "MathFactory.h"
21 #include "MathStream.h"
22 #include "MathSupport.h"
25 #include "BufferView.h"
26 #include "CoordCache.h"
28 #include "FuncStatus.h"
29 #include "FuncRequest.h"
30 #include "LaTeXFeatures.h"
34 #include "frontends/Painter.h"
36 #include "support/debug.h"
37 #include "support/gettext.h"
38 #include "support/lassert.h"
39 #include "support/lstrings.h"
40 #include "support/textutils.h"
45 using namespace lyx::support;
51 /// A proxy for the macro values
52 class ArgumentProxy : public InsetMath {
55 ArgumentProxy(MathMacro & mathMacro, size_t idx)
56 : mathMacro_(mathMacro), idx_(idx) {}
58 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
59 : mathMacro_(mathMacro), idx_(idx)
64 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
66 void metrics(MetricsInfo & mi, Dimension & dim) const {
67 mathMacro_.macro()->unlock();
68 mathMacro_.cell(idx_).metrics(mi, dim);
70 if (!mathMacro_.editMetrics(mi.base.bv)
71 && mathMacro_.cell(idx_).empty())
72 def_.metrics(mi, dim);
74 mathMacro_.macro()->lock();
76 // FIXME Other external things need similar treatment.
78 void mathmlize(MathStream & ms) const { ms << mathMacro_.cell(idx_); }
80 void htmlize(HtmlStream & ms) const { ms << mathMacro_.cell(idx_); }
82 void draw(PainterInfo & pi, int x, int y) const {
83 if (mathMacro_.editMetrics(pi.base.bv)) {
84 // The only way a ArgumentProxy can appear is in a cell of the
85 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
86 // mode and then, if the macro is edited the monochrome
87 // mode is entered by the MathMacro before calling the cells' draw
88 // method. Then eventually this code is reached and the proxy leaves
89 // monochrome mode temporarely. Hence, if it is not in monochrome
90 // here (and the assert triggers in pain.leaveMonochromeMode())
92 pi.pain.leaveMonochromeMode();
93 mathMacro_.cell(idx_).draw(pi, x, y);
94 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
95 } else if (mathMacro_.cell(idx_).empty()) {
96 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
99 mathMacro_.cell(idx_).draw(pi, x, y);
102 size_t idx() const { return idx_; }
104 int kerning(BufferView const * bv) const
106 if (mathMacro_.editMetrics(bv)
107 || !mathMacro_.cell(idx_).empty())
108 return mathMacro_.cell(idx_).kerning(bv);
110 return def_.kerning(bv);
115 Inset * clone() const
117 return new ArgumentProxy(*this);
120 MathMacro & mathMacro_;
128 MathMacro::MathMacro(Buffer * buf, docstring const & name)
129 : InsetMathNest(buf, 0), name_(name), displayMode_(DISPLAY_INIT),
130 expanded_(buf), attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
131 macroBackup_(buf), macro_(0), needsUpdate_(false),
132 isUpdating_(false), appetite_(9)
136 Inset * MathMacro::clone() const
138 MathMacro * copy = new MathMacro(*this);
139 copy->needsUpdate_ = true;
140 //copy->expanded_.cell(0).clear();
145 void MathMacro::normalize(NormalStream & os) const
147 os << "[macro " << name();
148 for (size_t i = 0; i < nargs(); ++i)
149 os << ' ' << cell(i);
154 docstring MathMacro::name() const
156 if (displayMode_ == DISPLAY_UNFOLDED)
157 return asString(cell(0));
163 void MathMacro::cursorPos(BufferView const & bv,
164 CursorSlice const & sl, bool boundary, int & x, int & y) const
166 // We may have 0 arguments, but InsetMathNest requires at least one.
168 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
172 bool MathMacro::editMode(BufferView const * bv) const {
173 // find this in cursor trace
174 Cursor const & cur = bv->cursor();
175 for (size_t i = 0; i != cur.depth(); ++i)
176 if (&cur[i].inset() == this) {
177 // look if there is no other macro in edit mode above
179 for (; i != cur.depth(); ++i) {
180 InsetMath * im = cur[i].asInsetMath();
182 MathMacro const * macro = im->asMacro();
183 if (macro && macro->displayMode() == DISPLAY_NORMAL)
188 // ok, none found, I am the highest one
196 bool MathMacro::editMetrics(BufferView const * bv) const
202 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
204 // set edit mode for which we will have calculated metrics. But only
205 editing_[mi.base.bv] = editMode(mi.base.bv);
207 // calculate new metrics according to display mode
208 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
209 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
210 } else if (displayMode_ == DISPLAY_UNFOLDED) {
211 cell(0).metrics(mi, dim);
213 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
214 dim.wid += bsdim.width() + 1;
215 dim.asc = max(bsdim.ascent(), dim.ascent());
216 dim.des = max(bsdim.descent(), dim.descent());
218 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
219 && editing_[mi.base.bv]) {
220 // Macro will be edited in a old-style list mode here:
224 FontInfo labelFont = sane_font;
225 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
227 // get dimension of components of list view
229 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
230 nameDim.asc = fontDim.asc;
231 nameDim.des = fontDim.des;
234 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
235 argDim.asc = fontDim.asc;
236 argDim.des = fontDim.des;
239 definition_.metrics(mi, defDim);
242 dim.wid = nameDim.wid + defDim.wid;
243 dim.asc = max(nameDim.asc, defDim.asc);
244 dim.des = max(nameDim.des, defDim.des);
246 for (idx_type i = 0; i < nargs(); ++i) {
248 cell(i).metrics(mi, cdim);
249 dim.des += max(argDim.height(), cdim.height()) + 1;
250 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
253 // make space for box and markers, 2 pixels
257 metricsMarkers2(dim);
261 // calculate metrics, hoping that all cells are seen
263 expanded_.cell(0).metrics(mi, dim);
265 // otherwise do a manual metrics call
266 CoordCache & coords = mi.base.bv->coordCache();
267 for (idx_type i = 0; i < nargs(); ++i) {
268 if (!coords.getArrays().hasDim(&cell(i))) {
270 cell(i).metrics(mi, tdim);
275 // calculate dimension with label while editing
276 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
277 && editing_[mi.base.bv]) {
278 FontInfo font = mi.base.font;
279 augmentFont(font, from_ascii("lyxtex"));
281 mathed_string_dim(font, name(), namedim);
283 dim.wid += 2 + namedim.wid + 2 + 2;
284 dim.asc = max(dim.asc, namedim.asc) + 2;
285 dim.des = max(dim.des, namedim.des) + 2;
287 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
288 dim.asc += 1 + namedim.height() + 1;
296 int MathMacro::kerning(BufferView const * bv) const {
297 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
298 return expanded_.kerning(bv);
304 void MathMacro::updateMacro(MacroContext const & mc)
307 macro_ = mc.get(name());
308 if (macro_ && macroBackup_ != *macro_) {
309 macroBackup_ = *macro_;
318 class MathMacro::UpdateLocker
321 explicit UpdateLocker(MathMacro & mm) : mac(mm)
323 mac.isUpdating_ = true;
325 ~UpdateLocker() { mac.isUpdating_ = false; }
329 /** Avoid wrong usage of UpdateLocker.
330 To avoid wrong usage:
331 UpdateLocker(...); // wrong
332 UpdateLocker locker(...); // right
334 #define UpdateLocker(x) unnamed_UpdateLocker;
335 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
338 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
341 // block recursive calls (bug 8999)
345 UpdateLocker locker(*this);
352 requires_ = macro_->requires();
355 // non-normal mode? We are done!
356 || (displayMode_ != DISPLAY_NORMAL))
359 needsUpdate_ = false;
361 // get default values of macro
362 vector<docstring> const & defaults = macro_->defaults();
364 // create MathMacroArgumentValue objects pointing to the cells of the macro
365 vector<MathData> values(nargs());
366 for (size_t i = 0; i < nargs(); ++i) {
367 ArgumentProxy * proxy;
368 if (i < defaults.size())
369 proxy = new ArgumentProxy(*this, i, defaults[i]);
371 proxy = new ArgumentProxy(*this, i);
372 values[i].insert(0, MathAtom(proxy));
374 // expanding macro with the values
375 // Only update the argument macros if anything was expanded, otherwise
376 // we would get an endless loop (bug 9140). UpdateLocker does not work
377 // in this case, since MacroData::expand() creates new MathMacro
378 // objects, so this would be a different recursion path than the one
379 // protected by UpdateLocker.
380 if (macro_->expand(values, expanded_.cell(0))) {
381 if (utype == OutputUpdate && !expanded_.cell(0).empty())
382 expanded_.cell(0).updateMacros(cur, mc, utype);
384 // get definition for list edit mode
385 docstring const & display = macro_->display();
386 asArray(display.empty() ? macro_->definition() : display, definition_);
390 void MathMacro::draw(PainterInfo & pi, int x, int y) const
392 Dimension const dim = dimension(*pi.base.bv);
394 setPosCache(pi, x, y);
398 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
399 FontSetChanger dummy(pi.base, "lyxtex");
400 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
401 } else if (displayMode_ == DISPLAY_UNFOLDED) {
402 FontSetChanger dummy(pi.base, "lyxtex");
403 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
404 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
405 cell(0).draw(pi, x, y);
406 drawMarkers(pi, expx, expy);
407 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
408 && editing_[pi.base.bv]) {
409 // Macro will be edited in a old-style list mode here:
411 CoordCache const & coords = pi.base.bv->coordCache();
412 FontInfo const & labelFont = sane_font;
414 // markers and box needs two pixels
417 // get maximal font height
419 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
422 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
423 pi.pain.text(x, y, label, labelFont);
424 x += mathed_string_width(labelFont, label);
427 definition_.draw(pi, x, y);
428 Dimension const & defDim = coords.getArrays().dim(&definition_);
429 y += max(fontDim.des, defDim.des);
432 docstring str = from_ascii("#9");
433 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
434 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
436 for (idx_type i = 0; i < nargs(); ++i) {
438 Dimension const & cdim = coords.getArrays().dim(&cell(i));
440 y += max(fontDim.asc, cdim.asc) + 1;
444 pi.pain.text(x, y, str, labelFont);
446 pi.pain.text(x, y, from_ascii(":"), labelFont);
450 cell(i).draw(pi, x, y);
453 y += max(fontDim.des, cdim.des);
456 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
457 dim.height() - 2, Color_mathmacroframe);
458 drawMarkers2(pi, expx, expy);
460 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
463 for (size_t i = 0; i < nargs(); ++i)
464 cell(i).setXY(*pi.base.bv, x, y);
466 if (drawBox && editing_[pi.base.bv]) {
467 // draw header and rectangle around
468 FontInfo font = pi.base.font;
469 augmentFont(font, from_ascii("lyxtex"));
470 font.setSize(FONT_SIZE_TINY);
471 font.setColor(Color_mathmacrolabel);
473 mathed_string_dim(font, name(), namedim);
475 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
476 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
477 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
480 if (editing_[pi.base.bv]) {
481 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
482 expanded_.cell(0).draw(pi, expx, expy);
483 pi.pain.leaveMonochromeMode();
486 pi.pain.rectangle(x, y - dim.asc, dim.wid,
487 dim.height(), Color_mathmacroframe);
489 expanded_.cell(0).draw(pi, expx, expy);
492 drawMarkers(pi, x, y);
495 // edit mode changed?
496 if (editing_[pi.base.bv] != editMode(pi.base.bv))
497 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
501 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
503 // We may have 0 arguments, but InsetMathNest requires at least one.
505 InsetMathNest::drawSelection(pi, x, y);
509 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
511 if (displayMode_ != mode) {
512 // transfer name if changing from or to DISPLAY_UNFOLDED
513 if (mode == DISPLAY_UNFOLDED) {
515 asArray(name_, cell(0));
516 } else if (displayMode_ == DISPLAY_UNFOLDED) {
517 name_ = asString(cell(0));
525 // the interactive init mode is non-greedy by default
527 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
529 appetite_ = size_t(appetite);
533 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
535 if (nextFoldMode_ == true && macro_ && !macro_->locked())
536 return DISPLAY_NORMAL;
538 return DISPLAY_UNFOLDED;
542 bool MathMacro::validName() const
544 docstring n = name();
549 // converting back and force doesn't swallow anything?
552 if (asString(ma) != n)
556 for (size_t i = 0; i<n.size(); ++i) {
557 if (!(n[i] >= 'a' && n[i] <= 'z')
558 && !(n[i] >= 'A' && n[i] <= 'Z')
567 void MathMacro::validate(LaTeXFeatures & features) const
569 if (!requires_.empty())
570 features.require(requires_);
572 if (name() == "binom")
573 features.require("binom");
575 // validate the cells and the definition
576 if (displayMode() == DISPLAY_NORMAL) {
577 definition_.validate(features);
578 InsetMathNest::validate(features);
583 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
585 cur.screenUpdateFlags(Update::SinglePar);
586 InsetMathNest::edit(cur, front, entry_from);
590 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
592 // We may have 0 arguments, but InsetMathNest requires at least one.
594 cur.screenUpdateFlags(Update::SinglePar);
595 return InsetMathNest::editXY(cur, x, y);
601 void MathMacro::removeArgument(Inset::pos_type pos) {
602 if (displayMode_ == DISPLAY_NORMAL) {
603 LASSERT(size_t(pos) < cells_.size(), return);
604 cells_.erase(cells_.begin() + pos);
605 if (size_t(pos) < attachedArgsNum_)
607 if (size_t(pos) < optionals_) {
616 void MathMacro::insertArgument(Inset::pos_type pos) {
617 if (displayMode_ == DISPLAY_NORMAL) {
618 LASSERT(size_t(pos) <= cells_.size(), return);
619 cells_.insert(cells_.begin() + pos, MathData());
620 if (size_t(pos) < attachedArgsNum_)
622 if (size_t(pos) < optionals_)
630 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
632 LASSERT(displayMode_ == DISPLAY_NORMAL, return);
635 // strip off empty cells, but not more than arity-attachedArgsNum_
638 for (i = cells_.size(); i > attachedArgsNum_; --i)
639 if (!cell(i - 1).empty()) break;
643 attachedArgsNum_ = 0;
644 expanded_.cell(0) = MathData();
651 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
653 LASSERT(displayMode_ == DISPLAY_NORMAL, return);
655 attachedArgsNum_ = args.size();
656 cells_.resize(arity);
657 expanded_.cell(0) = MathData();
658 optionals_ = optionals;
664 bool MathMacro::idxFirst(Cursor & cur) const
666 cur.screenUpdateFlags(Update::SinglePar);
667 return InsetMathNest::idxFirst(cur);
671 bool MathMacro::idxLast(Cursor & cur) const
673 cur.screenUpdateFlags(Update::SinglePar);
674 return InsetMathNest::idxLast(cur);
678 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
680 if (displayMode_ == DISPLAY_UNFOLDED) {
681 docstring const & unfolded_name = name();
682 if (unfolded_name != name_) {
683 // The macro name was changed
684 Cursor inset_cursor = old;
685 int macroSlice = inset_cursor.find(this);
686 // returning true means the cursor is "now" invalid,
688 LASSERT(macroSlice != -1, return true);
689 inset_cursor.cutOff(macroSlice);
690 inset_cursor.recordUndoInset();
692 inset_cursor.cell().erase(inset_cursor.pos());
693 inset_cursor.cell().insert(inset_cursor.pos(),
694 createInsetMath(unfolded_name, cur.buffer()));
696 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
700 cur.screenUpdateFlags(Update::Force);
701 return InsetMathNest::notifyCursorLeaves(old, cur);
705 void MathMacro::fold(Cursor & cur)
707 if (!nextFoldMode_) {
708 nextFoldMode_ = true;
709 cur.screenUpdateFlags(Update::SinglePar);
714 void MathMacro::unfold(Cursor & cur)
717 nextFoldMode_ = false;
718 cur.screenUpdateFlags(Update::SinglePar);
723 bool MathMacro::folded() const
725 return nextFoldMode_;
729 void MathMacro::write(WriteStream & os) const
731 MathEnsurer ensurer(os, macro_ != 0, true);
734 if (displayMode_ != DISPLAY_NORMAL) {
735 os << "\\" << name();
736 if (name().size() != 1 || isAlphaASCII(name()[0]))
737 os.pendingSpace(true);
742 // we should be ok to continue even if this fails.
745 // Always protect macros in a fragile environment
749 os << "\\" << name();
752 // Optional arguments:
753 // First find last non-empty optional argument
754 idx_type emptyOptFrom = 0;
756 for (; i < cells_.size() && i < optionals_; ++i) {
757 if (!cell(i).empty())
758 emptyOptFrom = i + 1;
761 // print out optionals
762 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
764 os << "[" << cell(i) << "]";
767 // skip the tailing empty optionals
770 // Print remaining arguments
771 for (; i < cells_.size(); ++i) {
772 if (cell(i).size() == 1
773 && cell(i)[0].nucleus()->asCharInset()
774 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
779 os << "{" << cell(i) << "}";
783 // add space if there was no argument
785 os.pendingSpace(true);
789 void MathMacro::maple(MapleStream & os) const
791 lyx::maple(expanded_.cell(0), os);
795 void MathMacro::mathmlize(MathStream & os) const
797 MathData const & data = expanded_.cell(0);
799 // this means that we do not recognize the macro
800 throw MathExportException();
806 void MathMacro::htmlize(HtmlStream & os) const
808 MathData const & data = expanded_.cell(0);
810 // this means that we do not recognize the macro
811 throw MathExportException();
817 void MathMacro::octave(OctaveStream & os) const
819 lyx::octave(expanded_.cell(0), os);
823 void MathMacro::infoize(odocstream & os) const
825 os << bformat(_("Macro: %1$s"), name());
829 void MathMacro::infoize2(odocstream & os) const
831 os << bformat(_("Macro: %1$s"), name());
835 bool MathMacro::completionSupported(Cursor const & cur) const
837 if (displayMode() != DISPLAY_UNFOLDED)
838 return InsetMathNest::completionSupported(cur);
840 return lyxrc.completion_popup_math
841 && displayMode() == DISPLAY_UNFOLDED
842 && cur.bv().cursor().pos() == int(name().size());
846 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
848 if (displayMode() != DISPLAY_UNFOLDED)
849 return InsetMathNest::inlineCompletionSupported(cur);
851 return lyxrc.completion_inline_math
852 && displayMode() == DISPLAY_UNFOLDED
853 && cur.bv().cursor().pos() == int(name().size());
857 bool MathMacro::automaticInlineCompletion() const
859 if (displayMode() != DISPLAY_UNFOLDED)
860 return InsetMathNest::automaticInlineCompletion();
862 return lyxrc.completion_inline_math;
866 bool MathMacro::automaticPopupCompletion() const
868 if (displayMode() != DISPLAY_UNFOLDED)
869 return InsetMathNest::automaticPopupCompletion();
871 return lyxrc.completion_popup_math;
875 CompletionList const *
876 MathMacro::createCompletionList(Cursor const & cur) const
878 if (displayMode() != DISPLAY_UNFOLDED)
879 return InsetMathNest::createCompletionList(cur);
881 return new MathCompletionList(cur.bv().cursor());
885 docstring MathMacro::completionPrefix(Cursor const & cur) const
887 if (displayMode() != DISPLAY_UNFOLDED)
888 return InsetMathNest::completionPrefix(cur);
890 if (!completionSupported(cur))
893 return "\\" + name();
897 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
900 if (displayMode() != DISPLAY_UNFOLDED)
901 return InsetMathNest::insertCompletion(cur, s, finished);
903 if (!completionSupported(cur))
907 docstring newName = name() + s;
908 asArray(newName, cell(0));
909 cur.bv().cursor().pos() = name().size();
910 cur.screenUpdateFlags(Update::SinglePar);
914 cur.bv().cursor().pop();
915 ++cur.bv().cursor().pos();
916 cur.screenUpdateFlags(Update::SinglePar);
923 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
924 Dimension & dim) const
926 if (displayMode() != DISPLAY_UNFOLDED)
927 InsetMathNest::completionPosAndDim(cur, x, y, dim);
929 // get inset dimensions
930 dim = cur.bv().coordCache().insets().dim(this);
931 // FIXME: these 3 are no accurate, but should depend on the font.
932 // Now the popup jumps down if you enter a char with descent > 0.
938 = cur.bv().coordCache().insets().xy(this);