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/lassert.h"
38 #include "support/textutils.h"
48 /// A proxy for the macro values
49 class ArgumentProxy : public InsetMath {
52 ArgumentProxy(MathMacro & mathMacro, size_t idx)
53 : mathMacro_(mathMacro), idx_(idx) {}
55 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
56 : mathMacro_(mathMacro), idx_(idx)
61 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
63 void metrics(MetricsInfo & mi, Dimension & dim) const {
64 mathMacro_.macro()->unlock();
65 mathMacro_.cell(idx_).metrics(mi, dim);
67 if (!mathMacro_.editMetrics(mi.base.bv)
68 && mathMacro_.cell(idx_).empty())
69 def_.metrics(mi, dim);
71 mathMacro_.macro()->lock();
73 // FIXME Other external things need similar treatment.
75 void mathmlize(MathStream & ms) const { ms << mathMacro_.cell(idx_); }
77 void htmlize(HtmlStream & ms) const { ms << mathMacro_.cell(idx_); }
79 void draw(PainterInfo & pi, int x, int y) const {
80 if (mathMacro_.editMetrics(pi.base.bv)) {
81 // The only way a ArgumentProxy can appear is in a cell of the
82 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
83 // mode and then, if the macro is edited the monochrome
84 // mode is entered by the MathMacro before calling the cells' draw
85 // method. Then eventually this code is reached and the proxy leaves
86 // monochrome mode temporarely. Hence, if it is not in monochrome
87 // here (and the assert triggers in pain.leaveMonochromeMode())
89 pi.pain.leaveMonochromeMode();
90 mathMacro_.cell(idx_).draw(pi, x, y);
91 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
92 } else if (mathMacro_.cell(idx_).empty()) {
93 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
96 mathMacro_.cell(idx_).draw(pi, x, y);
99 size_t idx() const { return idx_; }
101 int kerning(BufferView const * bv) const
103 if (mathMacro_.editMetrics(bv)
104 || !mathMacro_.cell(idx_).empty())
105 return mathMacro_.cell(idx_).kerning(bv);
107 return def_.kerning(bv);
112 Inset * clone() const
114 return new ArgumentProxy(*this);
117 MathMacro & mathMacro_;
125 MathMacro::MathMacro(Buffer * buf, docstring const & name)
126 : InsetMathNest(buf, 0), name_(name), displayMode_(DISPLAY_INIT),
127 expanded_(buf), attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
128 macroBackup_(buf), macro_(0), needsUpdate_(false), appetite_(9)
132 Inset * MathMacro::clone() const
134 MathMacro * copy = new MathMacro(*this);
135 copy->needsUpdate_ = true;
136 //copy->expanded_.cell(0).clear();
141 void MathMacro::normalize(NormalStream & os) const
143 os << "[macro " << name();
144 for (size_t i = 0; i < nargs(); ++i)
145 os << ' ' << cell(i);
150 docstring MathMacro::name() const
152 if (displayMode_ == DISPLAY_UNFOLDED)
153 return asString(cell(0));
159 void MathMacro::cursorPos(BufferView const & bv,
160 CursorSlice const & sl, bool boundary, int & x, int & y) const
162 // We may have 0 arguments, but InsetMathNest requires at least one.
164 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
168 bool MathMacro::editMode(BufferView const * bv) const {
169 // find this in cursor trace
170 Cursor const & cur = bv->cursor();
171 for (size_t i = 0; i != cur.depth(); ++i)
172 if (&cur[i].inset() == this) {
173 // look if there is no other macro in edit mode above
175 for (; i != cur.depth(); ++i) {
176 InsetMath * im = cur[i].asInsetMath();
178 MathMacro const * macro = im->asMacro();
179 if (macro && macro->displayMode() == DISPLAY_NORMAL)
184 // ok, none found, I am the highest one
192 bool MathMacro::editMetrics(BufferView const * bv) const
198 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
200 // set edit mode for which we will have calculated metrics. But only
201 editing_[mi.base.bv] = editMode(mi.base.bv);
203 // calculate new metrics according to display mode
204 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
205 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
206 } else if (displayMode_ == DISPLAY_UNFOLDED) {
207 cell(0).metrics(mi, dim);
209 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
210 dim.wid += bsdim.width() + 1;
211 dim.asc = max(bsdim.ascent(), dim.ascent());
212 dim.des = max(bsdim.descent(), dim.descent());
214 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
215 && editing_[mi.base.bv]) {
216 // Macro will be edited in a old-style list mode here:
218 LASSERT(macro_ != 0, /**/);
220 FontInfo labelFont = sane_font;
221 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
223 // get dimension of components of list view
225 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
226 nameDim.asc = fontDim.asc;
227 nameDim.des = fontDim.des;
230 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
231 argDim.asc = fontDim.asc;
232 argDim.des = fontDim.des;
235 definition_.metrics(mi, defDim);
238 dim.wid = nameDim.wid + defDim.wid;
239 dim.asc = max(nameDim.asc, defDim.asc);
240 dim.des = max(nameDim.des, defDim.des);
242 for (idx_type i = 0; i < nargs(); ++i) {
244 cell(i).metrics(mi, cdim);
245 dim.des += max(argDim.height(), cdim.height()) + 1;
246 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
249 // make space for box and markers, 2 pixels
253 metricsMarkers2(dim);
255 LASSERT(macro_ != 0, /**/);
257 // calculate metrics, hoping that all cells are seen
259 expanded_.cell(0).metrics(mi, dim);
261 // otherwise do a manual metrics call
262 CoordCache & coords = mi.base.bv->coordCache();
263 for (idx_type i = 0; i < nargs(); ++i) {
264 if (!coords.getArrays().hasDim(&cell(i))) {
266 cell(i).metrics(mi, tdim);
271 // calculate dimension with label while editing
272 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
273 && editing_[mi.base.bv]) {
274 FontInfo font = mi.base.font;
275 augmentFont(font, from_ascii("lyxtex"));
277 mathed_string_dim(font, name(), namedim);
279 dim.wid += 2 + namedim.wid + 2 + 2;
280 dim.asc = max(dim.asc, namedim.asc) + 2;
281 dim.des = max(dim.des, namedim.des) + 2;
283 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
284 dim.asc += 1 + namedim.height() + 1;
292 int MathMacro::kerning(BufferView const * bv) const {
293 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
294 return expanded_.kerning(bv);
300 void MathMacro::updateMacro(MacroContext const & mc)
303 macro_ = mc.get(name());
304 if (macro_ && macroBackup_ != *macro_) {
305 macroBackup_ = *macro_;
314 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
322 requires_ = macro_->requires();
325 // non-normal mode? We are done!
326 || (displayMode_ != DISPLAY_NORMAL))
329 needsUpdate_ = false;
331 // get default values of macro
332 vector<docstring> const & defaults = macro_->defaults();
334 // create MathMacroArgumentValue objects pointing to the cells of the macro
335 vector<MathData> values(nargs());
336 for (size_t i = 0; i < nargs(); ++i) {
337 ArgumentProxy * proxy;
338 if (i < defaults.size())
339 proxy = new ArgumentProxy(*this, i, defaults[i]);
341 proxy = new ArgumentProxy(*this, i);
342 values[i].insert(0, MathAtom(proxy));
344 // expanding macro with the values
345 macro_->expand(values, expanded_.cell(0));
346 if (utype == OutputUpdate && !expanded_.cell(0).empty())
347 expanded_.cell(0).updateMacros(cur, mc, utype);
348 // get definition for list edit mode
349 docstring const & display = macro_->display();
350 asArray(display.empty() ? macro_->definition() : display, definition_);
354 void MathMacro::draw(PainterInfo & pi, int x, int y) const
356 Dimension const dim = dimension(*pi.base.bv);
358 setPosCache(pi, x, y);
362 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
363 FontSetChanger dummy(pi.base, "lyxtex");
364 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
365 } else if (displayMode_ == DISPLAY_UNFOLDED) {
366 FontSetChanger dummy(pi.base, "lyxtex");
367 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
368 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
369 cell(0).draw(pi, x, y);
370 drawMarkers(pi, expx, expy);
371 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
372 && editing_[pi.base.bv]) {
373 // Macro will be edited in a old-style list mode here:
375 CoordCache const & coords = pi.base.bv->coordCache();
376 FontInfo const & labelFont = sane_font;
378 // markers and box needs two pixels
381 // get maximal font height
383 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
386 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
387 pi.pain.text(x, y, label, labelFont);
388 x += mathed_string_width(labelFont, label);
391 definition_.draw(pi, x, y);
392 Dimension const & defDim = coords.getArrays().dim(&definition_);
393 y += max(fontDim.des, defDim.des);
396 docstring str = from_ascii("#9");
397 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
398 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
400 for (idx_type i = 0; i < nargs(); ++i) {
402 Dimension const & cdim = coords.getArrays().dim(&cell(i));
404 y += max(fontDim.asc, cdim.asc) + 1;
408 pi.pain.text(x, y, str, labelFont);
410 pi.pain.text(x, y, from_ascii(":"), labelFont);
414 cell(i).draw(pi, x, y);
417 y += max(fontDim.des, cdim.des);
420 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
421 dim.height() - 2, Color_mathmacroframe);
422 drawMarkers2(pi, expx, expy);
424 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
427 for (size_t i = 0; i < nargs(); ++i)
428 cell(i).setXY(*pi.base.bv, x, y);
430 if (drawBox && editing_[pi.base.bv]) {
431 // draw header and rectangle around
432 FontInfo font = pi.base.font;
433 augmentFont(font, from_ascii("lyxtex"));
434 font.setSize(FONT_SIZE_TINY);
435 font.setColor(Color_mathmacrolabel);
437 mathed_string_dim(font, name(), namedim);
439 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
440 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
441 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
444 if (editing_[pi.base.bv]) {
445 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
446 expanded_.cell(0).draw(pi, expx, expy);
447 pi.pain.leaveMonochromeMode();
450 pi.pain.rectangle(x, y - dim.asc, dim.wid,
451 dim.height(), Color_mathmacroframe);
453 expanded_.cell(0).draw(pi, expx, expy);
456 drawMarkers(pi, x, y);
459 // edit mode changed?
460 if (editing_[pi.base.bv] != editMode(pi.base.bv))
461 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
465 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
467 // We may have 0 arguments, but InsetMathNest requires at least one.
469 InsetMathNest::drawSelection(pi, x, y);
473 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
475 if (displayMode_ != mode) {
476 // transfer name if changing from or to DISPLAY_UNFOLDED
477 if (mode == DISPLAY_UNFOLDED) {
479 asArray(name_, cell(0));
480 } else if (displayMode_ == DISPLAY_UNFOLDED) {
481 name_ = asString(cell(0));
489 // the interactive init mode is non-greedy by default
491 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
493 appetite_ = size_t(appetite);
497 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
499 if (nextFoldMode_ == true && macro_ && !macro_->locked())
500 return DISPLAY_NORMAL;
502 return DISPLAY_UNFOLDED;
506 bool MathMacro::validName() const
508 docstring n = name();
513 // converting back and force doesn't swallow anything?
516 if (asString(ma) != n)
520 for (size_t i = 0; i<n.size(); ++i) {
521 if (!(n[i] >= 'a' && n[i] <= 'z')
522 && !(n[i] >= 'A' && n[i] <= 'Z')
531 void MathMacro::validate(LaTeXFeatures & features) const
533 if (!requires_.empty())
534 features.require(requires_);
536 if (name() == "binom")
537 features.require("binom");
539 // validate the cells and the definition
540 if (displayMode() == DISPLAY_NORMAL) {
541 definition_.validate(features);
542 InsetMathNest::validate(features);
547 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
549 cur.screenUpdateFlags(Update::SinglePar);
550 InsetMathNest::edit(cur, front, entry_from);
554 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
556 // We may have 0 arguments, but InsetMathNest requires at least one.
558 cur.screenUpdateFlags(Update::SinglePar);
559 return InsetMathNest::editXY(cur, x, y);
565 void MathMacro::removeArgument(Inset::pos_type pos) {
566 if (displayMode_ == DISPLAY_NORMAL) {
567 LASSERT(size_t(pos) < cells_.size(), /**/);
568 cells_.erase(cells_.begin() + pos);
569 if (size_t(pos) < attachedArgsNum_)
571 if (size_t(pos) < optionals_) {
580 void MathMacro::insertArgument(Inset::pos_type pos) {
581 if (displayMode_ == DISPLAY_NORMAL) {
582 LASSERT(size_t(pos) <= cells_.size(), /**/);
583 cells_.insert(cells_.begin() + pos, MathData());
584 if (size_t(pos) < attachedArgsNum_)
586 if (size_t(pos) < optionals_)
594 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
596 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
599 // strip off empty cells, but not more than arity-attachedArgsNum_
602 for (i = cells_.size(); i > attachedArgsNum_; --i)
603 if (!cell(i - 1).empty()) break;
607 attachedArgsNum_ = 0;
608 expanded_.cell(0) = MathData();
615 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
617 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
619 attachedArgsNum_ = args.size();
620 cells_.resize(arity);
621 expanded_.cell(0) = MathData();
622 optionals_ = optionals;
628 bool MathMacro::idxFirst(Cursor & cur) const
630 cur.screenUpdateFlags(Update::SinglePar);
631 return InsetMathNest::idxFirst(cur);
635 bool MathMacro::idxLast(Cursor & cur) const
637 cur.screenUpdateFlags(Update::SinglePar);
638 return InsetMathNest::idxLast(cur);
642 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
644 if (displayMode_ == DISPLAY_UNFOLDED) {
645 docstring const & unfolded_name = name();
646 if (unfolded_name != name_) {
647 // The macro name was changed
648 Cursor inset_cursor = old;
649 int macroSlice = inset_cursor.find(this);
650 LASSERT(macroSlice != -1, /**/);
651 inset_cursor.cutOff(macroSlice);
652 inset_cursor.recordUndoInset();
654 inset_cursor.cell().erase(inset_cursor.pos());
655 inset_cursor.cell().insert(inset_cursor.pos(),
656 createInsetMath(unfolded_name, cur.buffer()));
658 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
662 cur.screenUpdateFlags(Update::Force);
663 return InsetMathNest::notifyCursorLeaves(old, cur);
667 void MathMacro::fold(Cursor & cur)
669 if (!nextFoldMode_) {
670 nextFoldMode_ = true;
671 cur.screenUpdateFlags(Update::SinglePar);
676 void MathMacro::unfold(Cursor & cur)
679 nextFoldMode_ = false;
680 cur.screenUpdateFlags(Update::SinglePar);
685 bool MathMacro::folded() const
687 return nextFoldMode_;
691 void MathMacro::write(WriteStream & os) const
693 MathEnsurer ensurer(os, macro_ != 0, true);
696 if (displayMode_ != DISPLAY_NORMAL) {
697 os << "\\" << name();
698 if (name().size() != 1 || isAlphaASCII(name()[0]))
699 os.pendingSpace(true);
704 LASSERT(macro_, /**/);
706 // optional arguments make macros fragile
707 if (optionals_ > 0 && os.fragile())
710 os << "\\" << name();
713 // Optional arguments:
714 // First find last non-empty optional argument
715 idx_type emptyOptFrom = 0;
717 for (; i < cells_.size() && i < optionals_; ++i) {
718 if (!cell(i).empty())
719 emptyOptFrom = i + 1;
722 // print out optionals
723 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
725 os << "[" << cell(i) << "]";
728 // skip the tailing empty optionals
731 // Print remaining arguments
732 for (; i < cells_.size(); ++i) {
733 if (cell(i).size() == 1
734 && cell(i)[0].nucleus()->asCharInset()
735 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
740 os << "{" << cell(i) << "}";
744 // add space if there was no argument
746 os.pendingSpace(true);
750 void MathMacro::maple(MapleStream & os) const
752 lyx::maple(expanded_.cell(0), os);
756 void MathMacro::mathmlize(MathStream & os) const
758 MathData const & data = expanded_.cell(0);
760 // this means that we do not recognize the macro
761 throw MathExportException();
767 void MathMacro::htmlize(HtmlStream & os) const
769 MathData const & data = expanded_.cell(0);
771 // this means that we do not recognize the macro
772 throw MathExportException();
778 void MathMacro::octave(OctaveStream & os) const
780 lyx::octave(expanded_.cell(0), os);
784 void MathMacro::infoize(odocstream & os) const
786 os << "Macro: " << name();
790 void MathMacro::infoize2(odocstream & os) const
792 os << "Macro: " << name();
797 bool MathMacro::completionSupported(Cursor const & cur) const
799 if (displayMode() != DISPLAY_UNFOLDED)
800 return InsetMathNest::completionSupported(cur);
802 return lyxrc.completion_popup_math
803 && displayMode() == DISPLAY_UNFOLDED
804 && cur.bv().cursor().pos() == int(name().size());
808 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
810 if (displayMode() != DISPLAY_UNFOLDED)
811 return InsetMathNest::inlineCompletionSupported(cur);
813 return lyxrc.completion_inline_math
814 && displayMode() == DISPLAY_UNFOLDED
815 && cur.bv().cursor().pos() == int(name().size());
819 bool MathMacro::automaticInlineCompletion() const
821 if (displayMode() != DISPLAY_UNFOLDED)
822 return InsetMathNest::automaticInlineCompletion();
824 return lyxrc.completion_inline_math;
828 bool MathMacro::automaticPopupCompletion() const
830 if (displayMode() != DISPLAY_UNFOLDED)
831 return InsetMathNest::automaticPopupCompletion();
833 return lyxrc.completion_popup_math;
837 CompletionList const *
838 MathMacro::createCompletionList(Cursor const & cur) const
840 if (displayMode() != DISPLAY_UNFOLDED)
841 return InsetMathNest::createCompletionList(cur);
843 return new MathCompletionList(cur.bv().cursor());
847 docstring MathMacro::completionPrefix(Cursor const & cur) const
849 if (displayMode() != DISPLAY_UNFOLDED)
850 return InsetMathNest::completionPrefix(cur);
852 if (!completionSupported(cur))
855 return "\\" + name();
859 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
862 if (displayMode() != DISPLAY_UNFOLDED)
863 return InsetMathNest::insertCompletion(cur, s, finished);
865 if (!completionSupported(cur))
869 docstring newName = name() + s;
870 asArray(newName, cell(0));
871 cur.bv().cursor().pos() = name().size();
872 cur.screenUpdateFlags(Update::SinglePar);
876 cur.bv().cursor().pop();
877 ++cur.bv().cursor().pos();
878 cur.screenUpdateFlags(Update::SinglePar);
885 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
886 Dimension & dim) const
888 if (displayMode() != DISPLAY_UNFOLDED)
889 InsetMathNest::completionPosAndDim(cur, x, y, dim);
891 // get inset dimensions
892 dim = cur.bv().coordCache().insets().dim(this);
893 // FIXME: these 3 are no accurate, but should depend on the font.
894 // Now the popup jumps down if you enter a char with descent > 0.
900 = cur.bv().coordCache().insets().xy(this);