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/textutils.h"
49 /// A proxy for the macro values
50 class ArgumentProxy : public InsetMath {
53 ArgumentProxy(MathMacro & mathMacro, size_t idx)
54 : mathMacro_(mathMacro), idx_(idx) {}
56 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
57 : mathMacro_(mathMacro), idx_(idx)
62 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
64 void metrics(MetricsInfo & mi, Dimension & dim) const {
65 mathMacro_.macro()->unlock();
66 mathMacro_.cell(idx_).metrics(mi, dim);
68 if (!mathMacro_.editMetrics(mi.base.bv)
69 && mathMacro_.cell(idx_).empty())
70 def_.metrics(mi, dim);
72 mathMacro_.macro()->lock();
74 // FIXME Other external things need similar treatment.
76 void mathmlize(MathStream & ms) const { ms << mathMacro_.cell(idx_); }
78 void htmlize(HtmlStream & ms) const { ms << mathMacro_.cell(idx_); }
80 void draw(PainterInfo & pi, int x, int y) const {
81 if (mathMacro_.editMetrics(pi.base.bv)) {
82 // The only way a ArgumentProxy can appear is in a cell of the
83 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
84 // mode and then, if the macro is edited the monochrome
85 // mode is entered by the MathMacro before calling the cells' draw
86 // method. Then eventually this code is reached and the proxy leaves
87 // monochrome mode temporarely. Hence, if it is not in monochrome
88 // here (and the assert triggers in pain.leaveMonochromeMode())
90 pi.pain.leaveMonochromeMode();
91 mathMacro_.cell(idx_).draw(pi, x, y);
92 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
93 } else if (mathMacro_.cell(idx_).empty()) {
94 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
97 mathMacro_.cell(idx_).draw(pi, x, y);
100 size_t idx() const { return idx_; }
102 int kerning(BufferView const * bv) const
104 if (mathMacro_.editMetrics(bv)
105 || !mathMacro_.cell(idx_).empty())
106 return mathMacro_.cell(idx_).kerning(bv);
108 return def_.kerning(bv);
113 Inset * clone() const
115 return new ArgumentProxy(*this);
118 MathMacro & mathMacro_;
126 MathMacro::MathMacro(Buffer * buf, docstring const & name)
127 : InsetMathNest(buf, 0), name_(name), displayMode_(DISPLAY_INIT),
128 expanded_(buf), attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
129 macroBackup_(buf), macro_(0), needsUpdate_(false), appetite_(9)
133 Inset * MathMacro::clone() const
135 MathMacro * copy = new MathMacro(*this);
136 copy->needsUpdate_ = true;
137 //copy->expanded_.cell(0).clear();
142 void MathMacro::normalize(NormalStream & os) const
144 os << "[macro " << name();
145 for (size_t i = 0; i < nargs(); ++i)
146 os << ' ' << cell(i);
151 docstring MathMacro::name() const
153 if (displayMode_ == DISPLAY_UNFOLDED)
154 return asString(cell(0));
160 void MathMacro::cursorPos(BufferView const & bv,
161 CursorSlice const & sl, bool boundary, int & x, int & y) const
163 // We may have 0 arguments, but InsetMathNest requires at least one.
165 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
169 bool MathMacro::editMode(BufferView const * bv) const {
170 // find this in cursor trace
171 Cursor const & cur = bv->cursor();
172 for (size_t i = 0; i != cur.depth(); ++i)
173 if (&cur[i].inset() == this) {
174 // look if there is no other macro in edit mode above
176 for (; i != cur.depth(); ++i) {
177 InsetMath * im = cur[i].asInsetMath();
179 MathMacro const * macro = im->asMacro();
180 if (macro && macro->displayMode() == DISPLAY_NORMAL)
185 // ok, none found, I am the highest one
193 bool MathMacro::editMetrics(BufferView const * bv) const
199 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
201 // set edit mode for which we will have calculated metrics. But only
202 editing_[mi.base.bv] = editMode(mi.base.bv);
204 // calculate new metrics according to display mode
205 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
206 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
207 } else if (displayMode_ == DISPLAY_UNFOLDED) {
208 cell(0).metrics(mi, dim);
210 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
211 dim.wid += bsdim.width() + 1;
212 dim.asc = max(bsdim.ascent(), dim.ascent());
213 dim.des = max(bsdim.descent(), dim.descent());
215 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
216 && editing_[mi.base.bv]) {
217 // Macro will be edited in a old-style list mode here:
219 LBUFERR(macro_, _("Text metrics error."));
221 FontInfo labelFont = sane_font;
222 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
224 // get dimension of components of list view
226 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
227 nameDim.asc = fontDim.asc;
228 nameDim.des = fontDim.des;
231 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
232 argDim.asc = fontDim.asc;
233 argDim.des = fontDim.des;
236 definition_.metrics(mi, defDim);
239 dim.wid = nameDim.wid + defDim.wid;
240 dim.asc = max(nameDim.asc, defDim.asc);
241 dim.des = max(nameDim.des, defDim.des);
243 for (idx_type i = 0; i < nargs(); ++i) {
245 cell(i).metrics(mi, cdim);
246 dim.des += max(argDim.height(), cdim.height()) + 1;
247 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
250 // make space for box and markers, 2 pixels
254 metricsMarkers2(dim);
256 LBUFERR(macro_, _("Text metrics error."));
258 // calculate metrics, hoping that all cells are seen
260 expanded_.cell(0).metrics(mi, dim);
262 // otherwise do a manual metrics call
263 CoordCache & coords = mi.base.bv->coordCache();
264 for (idx_type i = 0; i < nargs(); ++i) {
265 if (!coords.getArrays().hasDim(&cell(i))) {
267 cell(i).metrics(mi, tdim);
272 // calculate dimension with label while editing
273 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
274 && editing_[mi.base.bv]) {
275 FontInfo font = mi.base.font;
276 augmentFont(font, from_ascii("lyxtex"));
278 mathed_string_dim(font, name(), namedim);
280 dim.wid += 2 + namedim.wid + 2 + 2;
281 dim.asc = max(dim.asc, namedim.asc) + 2;
282 dim.des = max(dim.des, namedim.des) + 2;
284 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
285 dim.asc += 1 + namedim.height() + 1;
293 int MathMacro::kerning(BufferView const * bv) const {
294 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
295 return expanded_.kerning(bv);
301 void MathMacro::updateMacro(MacroContext const & mc)
304 macro_ = mc.get(name());
305 if (macro_ && macroBackup_ != *macro_) {
306 macroBackup_ = *macro_;
315 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
323 requires_ = macro_->requires();
326 // non-normal mode? We are done!
327 || (displayMode_ != DISPLAY_NORMAL))
330 needsUpdate_ = false;
332 // get default values of macro
333 vector<docstring> const & defaults = macro_->defaults();
335 // create MathMacroArgumentValue objects pointing to the cells of the macro
336 vector<MathData> values(nargs());
337 for (size_t i = 0; i < nargs(); ++i) {
338 ArgumentProxy * proxy;
339 if (i < defaults.size())
340 proxy = new ArgumentProxy(*this, i, defaults[i]);
342 proxy = new ArgumentProxy(*this, i);
343 values[i].insert(0, MathAtom(proxy));
345 // expanding macro with the values
346 macro_->expand(values, expanded_.cell(0));
347 if (utype == OutputUpdate && !expanded_.cell(0).empty())
348 expanded_.cell(0).updateMacros(cur, mc, utype);
349 // get definition for list edit mode
350 docstring const & display = macro_->display();
351 asArray(display.empty() ? macro_->definition() : display, definition_);
355 void MathMacro::draw(PainterInfo & pi, int x, int y) const
357 Dimension const dim = dimension(*pi.base.bv);
359 setPosCache(pi, x, y);
363 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
364 FontSetChanger dummy(pi.base, "lyxtex");
365 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
366 } else if (displayMode_ == DISPLAY_UNFOLDED) {
367 FontSetChanger dummy(pi.base, "lyxtex");
368 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
369 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
370 cell(0).draw(pi, x, y);
371 drawMarkers(pi, expx, expy);
372 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
373 && editing_[pi.base.bv]) {
374 // Macro will be edited in a old-style list mode here:
376 CoordCache const & coords = pi.base.bv->coordCache();
377 FontInfo const & labelFont = sane_font;
379 // markers and box needs two pixels
382 // get maximal font height
384 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
387 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
388 pi.pain.text(x, y, label, labelFont);
389 x += mathed_string_width(labelFont, label);
392 definition_.draw(pi, x, y);
393 Dimension const & defDim = coords.getArrays().dim(&definition_);
394 y += max(fontDim.des, defDim.des);
397 docstring str = from_ascii("#9");
398 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
399 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
401 for (idx_type i = 0; i < nargs(); ++i) {
403 Dimension const & cdim = coords.getArrays().dim(&cell(i));
405 y += max(fontDim.asc, cdim.asc) + 1;
409 pi.pain.text(x, y, str, labelFont);
411 pi.pain.text(x, y, from_ascii(":"), labelFont);
415 cell(i).draw(pi, x, y);
418 y += max(fontDim.des, cdim.des);
421 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
422 dim.height() - 2, Color_mathmacroframe);
423 drawMarkers2(pi, expx, expy);
425 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
428 for (size_t i = 0; i < nargs(); ++i)
429 cell(i).setXY(*pi.base.bv, x, y);
431 if (drawBox && editing_[pi.base.bv]) {
432 // draw header and rectangle around
433 FontInfo font = pi.base.font;
434 augmentFont(font, from_ascii("lyxtex"));
435 font.setSize(FONT_SIZE_TINY);
436 font.setColor(Color_mathmacrolabel);
438 mathed_string_dim(font, name(), namedim);
440 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
441 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
442 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
445 if (editing_[pi.base.bv]) {
446 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
447 expanded_.cell(0).draw(pi, expx, expy);
448 pi.pain.leaveMonochromeMode();
451 pi.pain.rectangle(x, y - dim.asc, dim.wid,
452 dim.height(), Color_mathmacroframe);
454 expanded_.cell(0).draw(pi, expx, expy);
457 drawMarkers(pi, x, y);
460 // edit mode changed?
461 if (editing_[pi.base.bv] != editMode(pi.base.bv))
462 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
466 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
468 // We may have 0 arguments, but InsetMathNest requires at least one.
470 InsetMathNest::drawSelection(pi, x, y);
474 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
476 if (displayMode_ != mode) {
477 // transfer name if changing from or to DISPLAY_UNFOLDED
478 if (mode == DISPLAY_UNFOLDED) {
480 asArray(name_, cell(0));
481 } else if (displayMode_ == DISPLAY_UNFOLDED) {
482 name_ = asString(cell(0));
490 // the interactive init mode is non-greedy by default
492 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
494 appetite_ = size_t(appetite);
498 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
500 if (nextFoldMode_ == true && macro_ && !macro_->locked())
501 return DISPLAY_NORMAL;
503 return DISPLAY_UNFOLDED;
507 bool MathMacro::validName() const
509 docstring n = name();
514 // converting back and force doesn't swallow anything?
517 if (asString(ma) != n)
521 for (size_t i = 0; i<n.size(); ++i) {
522 if (!(n[i] >= 'a' && n[i] <= 'z')
523 && !(n[i] >= 'A' && n[i] <= 'Z')
532 void MathMacro::validate(LaTeXFeatures & features) const
534 if (!requires_.empty())
535 features.require(requires_);
537 if (name() == "binom")
538 features.require("binom");
540 // validate the cells and the definition
541 if (displayMode() == DISPLAY_NORMAL) {
542 definition_.validate(features);
543 InsetMathNest::validate(features);
548 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
550 cur.screenUpdateFlags(Update::SinglePar);
551 InsetMathNest::edit(cur, front, entry_from);
555 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
557 // We may have 0 arguments, but InsetMathNest requires at least one.
559 cur.screenUpdateFlags(Update::SinglePar);
560 return InsetMathNest::editXY(cur, x, y);
566 void MathMacro::removeArgument(Inset::pos_type pos) {
567 if (displayMode_ == DISPLAY_NORMAL) {
568 LASSERT(size_t(pos) < cells_.size(), return);
569 cells_.erase(cells_.begin() + pos);
570 if (size_t(pos) < attachedArgsNum_)
572 if (size_t(pos) < optionals_) {
581 void MathMacro::insertArgument(Inset::pos_type pos) {
582 if (displayMode_ == DISPLAY_NORMAL) {
583 LASSERT(size_t(pos) <= cells_.size(), return);
584 cells_.insert(cells_.begin() + pos, MathData());
585 if (size_t(pos) < attachedArgsNum_)
587 if (size_t(pos) < optionals_)
595 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
597 LASSERT(displayMode_ == DISPLAY_NORMAL, return);
600 // strip off empty cells, but not more than arity-attachedArgsNum_
603 for (i = cells_.size(); i > attachedArgsNum_; --i)
604 if (!cell(i - 1).empty()) break;
608 attachedArgsNum_ = 0;
609 expanded_.cell(0) = MathData();
616 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
618 LASSERT(displayMode_ == DISPLAY_NORMAL, return);
620 attachedArgsNum_ = args.size();
621 cells_.resize(arity);
622 expanded_.cell(0) = MathData();
623 optionals_ = optionals;
629 bool MathMacro::idxFirst(Cursor & cur) const
631 cur.screenUpdateFlags(Update::SinglePar);
632 return InsetMathNest::idxFirst(cur);
636 bool MathMacro::idxLast(Cursor & cur) const
638 cur.screenUpdateFlags(Update::SinglePar);
639 return InsetMathNest::idxLast(cur);
643 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
645 if (displayMode_ == DISPLAY_UNFOLDED) {
646 docstring const & unfolded_name = name();
647 if (unfolded_name != name_) {
648 // The macro name was changed
649 Cursor inset_cursor = old;
650 int macroSlice = inset_cursor.find(this);
651 // returning true means the cursor is "now" invalid,
653 LASSERT(macroSlice != -1, return true);
654 inset_cursor.cutOff(macroSlice);
655 inset_cursor.recordUndoInset();
657 inset_cursor.cell().erase(inset_cursor.pos());
658 inset_cursor.cell().insert(inset_cursor.pos(),
659 createInsetMath(unfolded_name, cur.buffer()));
661 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
665 cur.screenUpdateFlags(Update::Force);
666 return InsetMathNest::notifyCursorLeaves(old, cur);
670 void MathMacro::fold(Cursor & cur)
672 if (!nextFoldMode_) {
673 nextFoldMode_ = true;
674 cur.screenUpdateFlags(Update::SinglePar);
679 void MathMacro::unfold(Cursor & cur)
682 nextFoldMode_ = false;
683 cur.screenUpdateFlags(Update::SinglePar);
688 bool MathMacro::folded() const
690 return nextFoldMode_;
694 void MathMacro::write(WriteStream & os) const
696 MathEnsurer ensurer(os, macro_ != 0, true);
699 if (displayMode_ != DISPLAY_NORMAL) {
700 os << "\\" << name();
701 if (name().size() != 1 || isAlphaASCII(name()[0]))
702 os.pendingSpace(true);
707 // we should be ok to continue even if this fails.
710 // optional arguments make macros fragile
711 if (optionals_ > 0 && os.fragile())
714 os << "\\" << name();
717 // Optional arguments:
718 // First find last non-empty optional argument
719 idx_type emptyOptFrom = 0;
721 for (; i < cells_.size() && i < optionals_; ++i) {
722 if (!cell(i).empty())
723 emptyOptFrom = i + 1;
726 // print out optionals
727 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
729 os << "[" << cell(i) << "]";
732 // skip the tailing empty optionals
735 // Print remaining arguments
736 for (; i < cells_.size(); ++i) {
737 if (cell(i).size() == 1
738 && cell(i)[0].nucleus()->asCharInset()
739 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
744 os << "{" << cell(i) << "}";
748 // add space if there was no argument
750 os.pendingSpace(true);
754 void MathMacro::maple(MapleStream & os) const
756 lyx::maple(expanded_.cell(0), os);
760 void MathMacro::mathmlize(MathStream & os) const
762 MathData const & data = expanded_.cell(0);
764 // this means that we do not recognize the macro
765 throw MathExportException();
771 void MathMacro::htmlize(HtmlStream & os) const
773 MathData const & data = expanded_.cell(0);
775 // this means that we do not recognize the macro
776 throw MathExportException();
782 void MathMacro::octave(OctaveStream & os) const
784 lyx::octave(expanded_.cell(0), os);
788 void MathMacro::infoize(odocstream & os) const
790 os << "Macro: " << name();
794 void MathMacro::infoize2(odocstream & os) const
796 os << "Macro: " << name();
801 bool MathMacro::completionSupported(Cursor const & cur) const
803 if (displayMode() != DISPLAY_UNFOLDED)
804 return InsetMathNest::completionSupported(cur);
806 return lyxrc.completion_popup_math
807 && displayMode() == DISPLAY_UNFOLDED
808 && cur.bv().cursor().pos() == int(name().size());
812 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
814 if (displayMode() != DISPLAY_UNFOLDED)
815 return InsetMathNest::inlineCompletionSupported(cur);
817 return lyxrc.completion_inline_math
818 && displayMode() == DISPLAY_UNFOLDED
819 && cur.bv().cursor().pos() == int(name().size());
823 bool MathMacro::automaticInlineCompletion() const
825 if (displayMode() != DISPLAY_UNFOLDED)
826 return InsetMathNest::automaticInlineCompletion();
828 return lyxrc.completion_inline_math;
832 bool MathMacro::automaticPopupCompletion() const
834 if (displayMode() != DISPLAY_UNFOLDED)
835 return InsetMathNest::automaticPopupCompletion();
837 return lyxrc.completion_popup_math;
841 CompletionList const *
842 MathMacro::createCompletionList(Cursor const & cur) const
844 if (displayMode() != DISPLAY_UNFOLDED)
845 return InsetMathNest::createCompletionList(cur);
847 return new MathCompletionList(cur.bv().cursor());
851 docstring MathMacro::completionPrefix(Cursor const & cur) const
853 if (displayMode() != DISPLAY_UNFOLDED)
854 return InsetMathNest::completionPrefix(cur);
856 if (!completionSupported(cur))
859 return "\\" + name();
863 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
866 if (displayMode() != DISPLAY_UNFOLDED)
867 return InsetMathNest::insertCompletion(cur, s, finished);
869 if (!completionSupported(cur))
873 docstring newName = name() + s;
874 asArray(newName, cell(0));
875 cur.bv().cursor().pos() = name().size();
876 cur.screenUpdateFlags(Update::SinglePar);
880 cur.bv().cursor().pop();
881 ++cur.bv().cursor().pos();
882 cur.screenUpdateFlags(Update::SinglePar);
889 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
890 Dimension & dim) const
892 if (displayMode() != DISPLAY_UNFOLDED)
893 InsetMathNest::completionPosAndDim(cur, x, y, dim);
895 // get inset dimensions
896 dim = cur.bv().coordCache().insets().dim(this);
897 // FIXME: these 3 are no accurate, but should depend on the font.
898 // Now the popup jumps down if you enter a char with descent > 0.
904 = cur.bv().coordCache().insets().xy(this);