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().has(&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()
321 requires_ = macro_->requires();
324 // non-normal mode? We are done!
325 || (displayMode_ != DISPLAY_NORMAL))
328 needsUpdate_ = false;
330 // get default values of macro
331 vector<docstring> const & defaults = macro_->defaults();
333 // create MathMacroArgumentValue objects pointing to the cells of the macro
334 vector<MathData> values(nargs());
335 for (size_t i = 0; i < nargs(); ++i) {
336 ArgumentProxy * proxy;
337 if (i < defaults.size())
338 proxy = new ArgumentProxy(*this, i, defaults[i]);
340 proxy = new ArgumentProxy(*this, i);
341 values[i].insert(0, MathAtom(proxy));
343 // expanding macro with the values
344 macro_->expand(values, expanded_.cell(0));
345 // get definition for list edit mode
346 docstring const & display = macro_->display();
347 asArray(display.empty() ? macro_->definition() : display, definition_);
351 void MathMacro::draw(PainterInfo & pi, int x, int y) const
353 Dimension const dim = dimension(*pi.base.bv);
355 setPosCache(pi, x, y);
359 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
360 FontSetChanger dummy(pi.base, "lyxtex");
361 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
362 } else if (displayMode_ == DISPLAY_UNFOLDED) {
363 FontSetChanger dummy(pi.base, "lyxtex");
364 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
365 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
366 cell(0).draw(pi, x, y);
367 drawMarkers(pi, expx, expy);
368 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
369 && editing_[pi.base.bv]) {
370 // Macro will be edited in a old-style list mode here:
372 CoordCache const & coords = pi.base.bv->coordCache();
373 FontInfo const & labelFont = sane_font;
375 // markers and box needs two pixels
378 // get maximal font height
380 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
383 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
384 pi.pain.text(x, y, label, labelFont);
385 x += mathed_string_width(labelFont, label);
388 definition_.draw(pi, x, y);
389 Dimension const & defDim = coords.getArrays().dim(&definition_);
390 y += max(fontDim.des, defDim.des);
393 docstring str = from_ascii("#9");
394 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
395 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
397 for (idx_type i = 0; i < nargs(); ++i) {
399 Dimension const & cdim = coords.getArrays().dim(&cell(i));
401 y += max(fontDim.asc, cdim.asc) + 1;
405 pi.pain.text(x, y, str, labelFont);
407 pi.pain.text(x, y, from_ascii(":"), labelFont);
411 cell(i).draw(pi, x, y);
414 y += max(fontDim.des, cdim.des);
417 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
418 dim.height() - 2, Color_mathmacroframe);
419 drawMarkers2(pi, expx, expy);
421 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
424 for (size_t i = 0; i < nargs(); ++i)
425 cell(i).setXY(*pi.base.bv, x, y);
427 if (drawBox && editing_[pi.base.bv]) {
428 // draw header and rectangle around
429 FontInfo font = pi.base.font;
430 augmentFont(font, from_ascii("lyxtex"));
431 font.setSize(FONT_SIZE_TINY);
432 font.setColor(Color_mathmacrolabel);
434 mathed_string_dim(font, name(), namedim);
436 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
437 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
438 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
441 if (editing_[pi.base.bv]) {
442 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
443 expanded_.cell(0).draw(pi, expx, expy);
444 pi.pain.leaveMonochromeMode();
447 pi.pain.rectangle(x, y - dim.asc, dim.wid,
448 dim.height(), Color_mathmacroframe);
450 expanded_.cell(0).draw(pi, expx, expy);
453 drawMarkers(pi, x, y);
456 // edit mode changed?
457 if (editing_[pi.base.bv] != editMode(pi.base.bv))
458 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
462 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
464 // We may have 0 arguments, but InsetMathNest requires at least one.
465 if (cells_.size() > 0)
466 InsetMathNest::drawSelection(pi, x, y);
470 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
472 if (displayMode_ != mode) {
473 // transfer name if changing from or to DISPLAY_UNFOLDED
474 if (mode == DISPLAY_UNFOLDED) {
476 asArray(name_, cell(0));
477 } else if (displayMode_ == DISPLAY_UNFOLDED) {
478 name_ = asString(cell(0));
486 // the interactive init mode is non-greedy by default
488 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
490 appetite_ = size_t(appetite);
494 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
496 if (nextFoldMode_ == true && macro_ && !macro_->locked())
497 return DISPLAY_NORMAL;
499 return DISPLAY_UNFOLDED;
503 bool MathMacro::validName() const
505 docstring n = name();
511 // converting back and force doesn't swallow anything?
514 if (asString(ma) != n)
518 for (size_t i = 0; i<n.size(); ++i) {
519 if (!(n[i] >= 'a' && n[i] <= 'z')
520 && !(n[i] >= 'A' && n[i] <= 'Z')
529 void MathMacro::validate(LaTeXFeatures & features) const
531 if (!requires_.empty())
532 features.require(requires_);
534 if (name() == "binom")
535 features.require("binom");
537 // validate the cells and the definition
538 if (displayMode() == DISPLAY_NORMAL) {
539 definition_.validate(features);
540 InsetMathNest::validate(features);
545 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
547 cur.screenUpdateFlags(Update::SinglePar);
548 InsetMathNest::edit(cur, front, entry_from);
552 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
554 // We may have 0 arguments, but InsetMathNest requires at least one.
556 cur.screenUpdateFlags(Update::SinglePar);
557 return InsetMathNest::editXY(cur, x, y);
563 void MathMacro::removeArgument(Inset::pos_type pos) {
564 if (displayMode_ == DISPLAY_NORMAL) {
565 LASSERT(size_t(pos) < cells_.size(), /**/);
566 cells_.erase(cells_.begin() + pos);
567 if (size_t(pos) < attachedArgsNum_)
569 if (size_t(pos) < optionals_) {
578 void MathMacro::insertArgument(Inset::pos_type pos) {
579 if (displayMode_ == DISPLAY_NORMAL) {
580 LASSERT(size_t(pos) <= cells_.size(), /**/);
581 cells_.insert(cells_.begin() + pos, MathData());
582 if (size_t(pos) < attachedArgsNum_)
584 if (size_t(pos) < optionals_)
592 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
594 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
597 // strip off empty cells, but not more than arity-attachedArgsNum_
600 for (i = cells_.size(); i > attachedArgsNum_; --i)
601 if (!cell(i - 1).empty()) break;
605 attachedArgsNum_ = 0;
606 expanded_.cell(0) = MathData();
613 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
615 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
617 attachedArgsNum_ = args.size();
618 cells_.resize(arity);
619 expanded_.cell(0) = MathData();
620 optionals_ = optionals;
626 bool MathMacro::idxFirst(Cursor & cur) const
628 cur.screenUpdateFlags(Update::SinglePar);
629 return InsetMathNest::idxFirst(cur);
633 bool MathMacro::idxLast(Cursor & cur) const
635 cur.screenUpdateFlags(Update::SinglePar);
636 return InsetMathNest::idxLast(cur);
640 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
642 if (displayMode_ == DISPLAY_UNFOLDED) {
643 docstring const & unfolded_name = name();
644 if (unfolded_name != name_) {
645 // The macro name was changed
646 Cursor inset_cursor = old;
647 int macroSlice = inset_cursor.find(this);
648 LASSERT(macroSlice != -1, /**/);
649 inset_cursor.cutOff(macroSlice);
650 inset_cursor.recordUndoInset();
652 inset_cursor.cell().erase(inset_cursor.pos());
653 inset_cursor.cell().insert(inset_cursor.pos(),
654 createInsetMath(unfolded_name, cur.buffer()));
656 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
660 cur.screenUpdateFlags(Update::Force);
661 return InsetMathNest::notifyCursorLeaves(old, cur);
665 void MathMacro::fold(Cursor & cur)
667 if (!nextFoldMode_) {
668 nextFoldMode_ = true;
669 cur.screenUpdateFlags(Update::SinglePar);
674 void MathMacro::unfold(Cursor & cur)
677 nextFoldMode_ = false;
678 cur.screenUpdateFlags(Update::SinglePar);
683 bool MathMacro::folded() const
685 return nextFoldMode_;
689 void MathMacro::write(WriteStream & os) const
691 MathEnsurer ensurer(os, macro_ != 0, true);
694 if (displayMode_ != DISPLAY_NORMAL) {
695 os << "\\" << name();
696 if (name().size() != 1 || isAlphaASCII(name()[0]))
697 os.pendingSpace(true);
702 LASSERT(macro_, /**/);
704 // optional arguments make macros fragile
705 if (optionals_ > 0 && os.fragile())
708 os << "\\" << name();
711 // Optional arguments:
712 // First find last non-empty optional argument
713 idx_type emptyOptFrom = 0;
715 for (; i < cells_.size() && i < optionals_; ++i) {
716 if (!cell(i).empty())
717 emptyOptFrom = i + 1;
720 // print out optionals
721 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
723 os << "[" << cell(i) << "]";
726 // skip the tailing empty optionals
729 // Print remaining arguments
730 for (; i < cells_.size(); ++i) {
731 if (cell(i).size() == 1
732 && cell(i)[0].nucleus()->asCharInset()
733 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
738 os << "{" << cell(i) << "}";
742 // add space if there was no argument
744 os.pendingSpace(true);
748 void MathMacro::maple(MapleStream & os) const
750 lyx::maple(expanded_.cell(0), os);
754 void MathMacro::mathmlize(MathStream & os) const
756 os << expanded_.cell(0);
760 void MathMacro::htmlize(HtmlStream & os) const
762 os << expanded_.cell(0);
766 void MathMacro::octave(OctaveStream & os) const
768 lyx::octave(expanded_.cell(0), os);
772 void MathMacro::infoize(odocstream & os) const
774 os << "Macro: " << name();
778 void MathMacro::infoize2(odocstream & os) const
780 os << "Macro: " << name();
785 bool MathMacro::completionSupported(Cursor const & cur) const
787 if (displayMode() != DISPLAY_UNFOLDED)
788 return InsetMathNest::completionSupported(cur);
790 return lyxrc.completion_popup_math
791 && displayMode() == DISPLAY_UNFOLDED
792 && cur.bv().cursor().pos() == int(name().size());
796 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
798 if (displayMode() != DISPLAY_UNFOLDED)
799 return InsetMathNest::inlineCompletionSupported(cur);
801 return lyxrc.completion_inline_math
802 && displayMode() == DISPLAY_UNFOLDED
803 && cur.bv().cursor().pos() == int(name().size());
807 bool MathMacro::automaticInlineCompletion() const
809 if (displayMode() != DISPLAY_UNFOLDED)
810 return InsetMathNest::automaticInlineCompletion();
812 return lyxrc.completion_inline_math;
816 bool MathMacro::automaticPopupCompletion() const
818 if (displayMode() != DISPLAY_UNFOLDED)
819 return InsetMathNest::automaticPopupCompletion();
821 return lyxrc.completion_popup_math;
825 CompletionList const *
826 MathMacro::createCompletionList(Cursor const & cur) const
828 if (displayMode() != DISPLAY_UNFOLDED)
829 return InsetMathNest::createCompletionList(cur);
831 return new MathCompletionList(cur.bv().cursor());
835 docstring MathMacro::completionPrefix(Cursor const & cur) const
837 if (displayMode() != DISPLAY_UNFOLDED)
838 return InsetMathNest::completionPrefix(cur);
840 if (!completionSupported(cur))
843 return "\\" + name();
847 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
850 if (displayMode() != DISPLAY_UNFOLDED)
851 return InsetMathNest::insertCompletion(cur, s, finished);
853 if (!completionSupported(cur))
857 docstring newName = name() + s;
858 asArray(newName, cell(0));
859 cur.bv().cursor().pos() = name().size();
860 cur.screenUpdateFlags(Update::SinglePar);
864 cur.bv().cursor().pop();
865 ++cur.bv().cursor().pos();
866 cur.screenUpdateFlags(Update::SinglePar);
873 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
874 Dimension & dim) const
876 if (displayMode() != DISPLAY_UNFOLDED)
877 InsetMathNest::completionPosAndDim(cur, x, y, dim);
879 // get inset dimensions
880 dim = cur.bv().coordCache().insets().dim(this);
881 // FIXME: these 3 are no accurate, but should depend on the font.
882 // Now the popup jumps down if you enter a char with descent > 0.
888 = cur.bv().coordCache().insets().xy(this);