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; }
331 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
337 UpdateLocker locker(*this);
344 requires_ = macro_->requires();
347 // non-normal mode? We are done!
348 || (displayMode_ != DISPLAY_NORMAL))
351 needsUpdate_ = false;
353 // get default values of macro
354 vector<docstring> const & defaults = macro_->defaults();
356 // create MathMacroArgumentValue objects pointing to the cells of the macro
357 vector<MathData> values(nargs());
358 for (size_t i = 0; i < nargs(); ++i) {
359 ArgumentProxy * proxy;
360 if (i < defaults.size())
361 proxy = new ArgumentProxy(*this, i, defaults[i]);
363 proxy = new ArgumentProxy(*this, i);
364 values[i].insert(0, MathAtom(proxy));
366 // expanding macro with the values
367 macro_->expand(values, expanded_.cell(0));
368 if (utype == OutputUpdate && !expanded_.cell(0).empty())
369 expanded_.cell(0).updateMacros(cur, mc, utype);
370 // get definition for list edit mode
371 docstring const & display = macro_->display();
372 asArray(display.empty() ? macro_->definition() : display, definition_);
376 void MathMacro::draw(PainterInfo & pi, int x, int y) const
378 Dimension const dim = dimension(*pi.base.bv);
380 setPosCache(pi, x, y);
384 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
385 FontSetChanger dummy(pi.base, "lyxtex");
386 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
387 } else if (displayMode_ == DISPLAY_UNFOLDED) {
388 FontSetChanger dummy(pi.base, "lyxtex");
389 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
390 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
391 cell(0).draw(pi, x, y);
392 drawMarkers(pi, expx, expy);
393 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
394 && editing_[pi.base.bv]) {
395 // Macro will be edited in a old-style list mode here:
397 CoordCache const & coords = pi.base.bv->coordCache();
398 FontInfo const & labelFont = sane_font;
400 // markers and box needs two pixels
403 // get maximal font height
405 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
408 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
409 pi.pain.text(x, y, label, labelFont);
410 x += mathed_string_width(labelFont, label);
413 definition_.draw(pi, x, y);
414 Dimension const & defDim = coords.getArrays().dim(&definition_);
415 y += max(fontDim.des, defDim.des);
418 docstring str = from_ascii("#9");
419 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
420 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
422 for (idx_type i = 0; i < nargs(); ++i) {
424 Dimension const & cdim = coords.getArrays().dim(&cell(i));
426 y += max(fontDim.asc, cdim.asc) + 1;
430 pi.pain.text(x, y, str, labelFont);
432 pi.pain.text(x, y, from_ascii(":"), labelFont);
436 cell(i).draw(pi, x, y);
439 y += max(fontDim.des, cdim.des);
442 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
443 dim.height() - 2, Color_mathmacroframe);
444 drawMarkers2(pi, expx, expy);
446 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
449 for (size_t i = 0; i < nargs(); ++i)
450 cell(i).setXY(*pi.base.bv, x, y);
452 if (drawBox && editing_[pi.base.bv]) {
453 // draw header and rectangle around
454 FontInfo font = pi.base.font;
455 augmentFont(font, from_ascii("lyxtex"));
456 font.setSize(FONT_SIZE_TINY);
457 font.setColor(Color_mathmacrolabel);
459 mathed_string_dim(font, name(), namedim);
461 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
462 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
463 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
466 if (editing_[pi.base.bv]) {
467 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
468 expanded_.cell(0).draw(pi, expx, expy);
469 pi.pain.leaveMonochromeMode();
472 pi.pain.rectangle(x, y - dim.asc, dim.wid,
473 dim.height(), Color_mathmacroframe);
475 expanded_.cell(0).draw(pi, expx, expy);
478 drawMarkers(pi, x, y);
481 // edit mode changed?
482 if (editing_[pi.base.bv] != editMode(pi.base.bv))
483 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
487 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
489 // We may have 0 arguments, but InsetMathNest requires at least one.
491 InsetMathNest::drawSelection(pi, x, y);
495 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
497 if (displayMode_ != mode) {
498 // transfer name if changing from or to DISPLAY_UNFOLDED
499 if (mode == DISPLAY_UNFOLDED) {
501 asArray(name_, cell(0));
502 } else if (displayMode_ == DISPLAY_UNFOLDED) {
503 name_ = asString(cell(0));
511 // the interactive init mode is non-greedy by default
513 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
515 appetite_ = size_t(appetite);
519 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
521 if (nextFoldMode_ == true && macro_ && !macro_->locked())
522 return DISPLAY_NORMAL;
524 return DISPLAY_UNFOLDED;
528 bool MathMacro::validName() const
530 docstring n = name();
535 // converting back and force doesn't swallow anything?
538 if (asString(ma) != n)
542 for (size_t i = 0; i<n.size(); ++i) {
543 if (!(n[i] >= 'a' && n[i] <= 'z')
544 && !(n[i] >= 'A' && n[i] <= 'Z')
553 void MathMacro::validate(LaTeXFeatures & features) const
555 if (!requires_.empty())
556 features.require(requires_);
558 if (name() == "binom")
559 features.require("binom");
561 // validate the cells and the definition
562 if (displayMode() == DISPLAY_NORMAL) {
563 definition_.validate(features);
564 InsetMathNest::validate(features);
569 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
571 cur.screenUpdateFlags(Update::SinglePar);
572 InsetMathNest::edit(cur, front, entry_from);
576 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
578 // We may have 0 arguments, but InsetMathNest requires at least one.
580 cur.screenUpdateFlags(Update::SinglePar);
581 return InsetMathNest::editXY(cur, x, y);
587 void MathMacro::removeArgument(Inset::pos_type pos) {
588 if (displayMode_ == DISPLAY_NORMAL) {
589 LASSERT(size_t(pos) < cells_.size(), return);
590 cells_.erase(cells_.begin() + pos);
591 if (size_t(pos) < attachedArgsNum_)
593 if (size_t(pos) < optionals_) {
602 void MathMacro::insertArgument(Inset::pos_type pos) {
603 if (displayMode_ == DISPLAY_NORMAL) {
604 LASSERT(size_t(pos) <= cells_.size(), return);
605 cells_.insert(cells_.begin() + pos, MathData());
606 if (size_t(pos) < attachedArgsNum_)
608 if (size_t(pos) < optionals_)
616 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
618 LASSERT(displayMode_ == DISPLAY_NORMAL, return);
621 // strip off empty cells, but not more than arity-attachedArgsNum_
624 for (i = cells_.size(); i > attachedArgsNum_; --i)
625 if (!cell(i - 1).empty()) break;
629 attachedArgsNum_ = 0;
630 expanded_.cell(0) = MathData();
637 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
639 LASSERT(displayMode_ == DISPLAY_NORMAL, return);
641 attachedArgsNum_ = args.size();
642 cells_.resize(arity);
643 expanded_.cell(0) = MathData();
644 optionals_ = optionals;
650 bool MathMacro::idxFirst(Cursor & cur) const
652 cur.screenUpdateFlags(Update::SinglePar);
653 return InsetMathNest::idxFirst(cur);
657 bool MathMacro::idxLast(Cursor & cur) const
659 cur.screenUpdateFlags(Update::SinglePar);
660 return InsetMathNest::idxLast(cur);
664 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
666 if (displayMode_ == DISPLAY_UNFOLDED) {
667 docstring const & unfolded_name = name();
668 if (unfolded_name != name_) {
669 // The macro name was changed
670 Cursor inset_cursor = old;
671 int macroSlice = inset_cursor.find(this);
672 // returning true means the cursor is "now" invalid,
674 LASSERT(macroSlice != -1, return true);
675 inset_cursor.cutOff(macroSlice);
676 inset_cursor.recordUndoInset();
678 inset_cursor.cell().erase(inset_cursor.pos());
679 inset_cursor.cell().insert(inset_cursor.pos(),
680 createInsetMath(unfolded_name, cur.buffer()));
682 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
686 cur.screenUpdateFlags(Update::Force);
687 return InsetMathNest::notifyCursorLeaves(old, cur);
691 void MathMacro::fold(Cursor & cur)
693 if (!nextFoldMode_) {
694 nextFoldMode_ = true;
695 cur.screenUpdateFlags(Update::SinglePar);
700 void MathMacro::unfold(Cursor & cur)
703 nextFoldMode_ = false;
704 cur.screenUpdateFlags(Update::SinglePar);
709 bool MathMacro::folded() const
711 return nextFoldMode_;
715 void MathMacro::write(WriteStream & os) const
717 MathEnsurer ensurer(os, macro_ != 0, true);
720 if (displayMode_ != DISPLAY_NORMAL) {
721 os << "\\" << name();
722 if (name().size() != 1 || isAlphaASCII(name()[0]))
723 os.pendingSpace(true);
728 // we should be ok to continue even if this fails.
731 // Always protect macros in a fragile environment
735 os << "\\" << name();
738 // Optional arguments:
739 // First find last non-empty optional argument
740 idx_type emptyOptFrom = 0;
742 for (; i < cells_.size() && i < optionals_; ++i) {
743 if (!cell(i).empty())
744 emptyOptFrom = i + 1;
747 // print out optionals
748 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
750 os << "[" << cell(i) << "]";
753 // skip the tailing empty optionals
756 // Print remaining arguments
757 for (; i < cells_.size(); ++i) {
758 if (cell(i).size() == 1
759 && cell(i)[0].nucleus()->asCharInset()
760 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
765 os << "{" << cell(i) << "}";
769 // add space if there was no argument
771 os.pendingSpace(true);
775 void MathMacro::maple(MapleStream & os) const
777 lyx::maple(expanded_.cell(0), os);
781 void MathMacro::mathmlize(MathStream & os) const
783 MathData const & data = expanded_.cell(0);
785 // this means that we do not recognize the macro
786 throw MathExportException();
792 void MathMacro::htmlize(HtmlStream & os) const
794 MathData const & data = expanded_.cell(0);
796 // this means that we do not recognize the macro
797 throw MathExportException();
803 void MathMacro::octave(OctaveStream & os) const
805 lyx::octave(expanded_.cell(0), os);
809 void MathMacro::infoize(odocstream & os) const
811 os << bformat(_("Macro: %1$s"), name());
815 void MathMacro::infoize2(odocstream & os) const
817 os << bformat(_("Macro: %1$s"), name());
821 bool MathMacro::completionSupported(Cursor const & cur) const
823 if (displayMode() != DISPLAY_UNFOLDED)
824 return InsetMathNest::completionSupported(cur);
826 return lyxrc.completion_popup_math
827 && displayMode() == DISPLAY_UNFOLDED
828 && cur.bv().cursor().pos() == int(name().size());
832 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
834 if (displayMode() != DISPLAY_UNFOLDED)
835 return InsetMathNest::inlineCompletionSupported(cur);
837 return lyxrc.completion_inline_math
838 && displayMode() == DISPLAY_UNFOLDED
839 && cur.bv().cursor().pos() == int(name().size());
843 bool MathMacro::automaticInlineCompletion() const
845 if (displayMode() != DISPLAY_UNFOLDED)
846 return InsetMathNest::automaticInlineCompletion();
848 return lyxrc.completion_inline_math;
852 bool MathMacro::automaticPopupCompletion() const
854 if (displayMode() != DISPLAY_UNFOLDED)
855 return InsetMathNest::automaticPopupCompletion();
857 return lyxrc.completion_popup_math;
861 CompletionList const *
862 MathMacro::createCompletionList(Cursor const & cur) const
864 if (displayMode() != DISPLAY_UNFOLDED)
865 return InsetMathNest::createCompletionList(cur);
867 return new MathCompletionList(cur.bv().cursor());
871 docstring MathMacro::completionPrefix(Cursor const & cur) const
873 if (displayMode() != DISPLAY_UNFOLDED)
874 return InsetMathNest::completionPrefix(cur);
876 if (!completionSupported(cur))
879 return "\\" + name();
883 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
886 if (displayMode() != DISPLAY_UNFOLDED)
887 return InsetMathNest::insertCompletion(cur, s, finished);
889 if (!completionSupported(cur))
893 docstring newName = name() + s;
894 asArray(newName, cell(0));
895 cur.bv().cursor().pos() = name().size();
896 cur.screenUpdateFlags(Update::SinglePar);
900 cur.bv().cursor().pop();
901 ++cur.bv().cursor().pos();
902 cur.screenUpdateFlags(Update::SinglePar);
909 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
910 Dimension & dim) const
912 if (displayMode() != DISPLAY_UNFOLDED)
913 InsetMathNest::completionPosAndDim(cur, x, y, dim);
915 // get inset dimensions
916 dim = cur.bv().coordCache().insets().dim(this);
917 // FIXME: these 3 are no accurate, but should depend on the font.
918 // Now the popup jumps down if you enter a char with descent > 0.
924 = cur.bv().coordCache().insets().xy(this);