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"
35 #include "frontends/Painter.h"
37 #include "support/debug.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 docstring MathMacro::name() const
144 if (displayMode_ == DISPLAY_UNFOLDED)
145 return asString(cell(0));
151 void MathMacro::cursorPos(BufferView const & bv,
152 CursorSlice const & sl, bool boundary, int & x, int & y) const
154 // We may have 0 arguments, but InsetMathNest requires at least one.
156 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
160 bool MathMacro::editMode(BufferView const * bv) const {
161 // find this in cursor trace
162 Cursor const & cur = bv->cursor();
163 for (size_t i = 0; i != cur.depth(); ++i)
164 if (&cur[i].inset() == this) {
165 // look if there is no other macro in edit mode above
167 for (; i != cur.depth(); ++i) {
168 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
169 if (macro && macro->displayMode() == DISPLAY_NORMAL)
173 // ok, none found, I am the highest one
181 bool MathMacro::editMetrics(BufferView const * bv) const
187 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
189 // set edit mode for which we will have calculated metrics. But only
190 editing_[mi.base.bv] = editMode(mi.base.bv);
192 // calculate new metrics according to display mode
193 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
194 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
195 } else if (displayMode_ == DISPLAY_UNFOLDED) {
196 cell(0).metrics(mi, dim);
198 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
199 dim.wid += bsdim.width() + 1;
200 dim.asc = max(bsdim.ascent(), dim.ascent());
201 dim.des = max(bsdim.descent(), dim.descent());
203 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
204 && editing_[mi.base.bv]) {
205 // Macro will be edited in a old-style list mode here:
207 LASSERT(macro_ != 0, /**/);
209 FontInfo labelFont = sane_font;
210 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
212 // get dimension of components of list view
214 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
215 nameDim.asc = fontDim.asc;
216 nameDim.des = fontDim.des;
219 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
220 argDim.asc = fontDim.asc;
221 argDim.des = fontDim.des;
224 definition_.metrics(mi, defDim);
227 dim.wid = nameDim.wid + defDim.wid;
228 dim.asc = max(nameDim.asc, defDim.asc);
229 dim.des = max(nameDim.des, defDim.des);
231 for (idx_type i = 0; i < nargs(); ++i) {
233 cell(i).metrics(mi, cdim);
234 dim.des += max(argDim.height(), cdim.height()) + 1;
235 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
238 // make space for box and markers, 2 pixels
242 metricsMarkers2(dim);
244 LASSERT(macro_ != 0, /**/);
246 // calculate metrics, hoping that all cells are seen
248 expanded_.cell(0).metrics(mi, dim);
250 // otherwise do a manual metrics call
251 CoordCache & coords = mi.base.bv->coordCache();
252 for (idx_type i = 0; i < nargs(); ++i) {
253 if (!coords.getArrays().has(&cell(i))) {
255 cell(i).metrics(mi, tdim);
260 // calculate dimension with label while editing
261 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
262 && editing_[mi.base.bv]) {
263 FontInfo font = mi.base.font;
264 augmentFont(font, from_ascii("lyxtex"));
266 mathed_string_dim(font, name(), namedim);
268 dim.wid += 2 + namedim.wid + 2 + 2;
269 dim.asc = max(dim.asc, namedim.asc) + 2;
270 dim.des = max(dim.des, namedim.des) + 2;
272 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
273 dim.asc += 1 + namedim.height() + 1;
281 int MathMacro::kerning(BufferView const * bv) const {
282 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
283 return expanded_.kerning(bv);
289 void MathMacro::updateMacro(MacroContext const & mc)
292 macro_ = mc.get(name());
293 if (macro_ && macroBackup_ != *macro_) {
294 macroBackup_ = *macro_;
303 void MathMacro::updateRepresentation()
310 requires_ = macro_->requires();
313 // non-normal mode? We are done!
314 || (displayMode_ != DISPLAY_NORMAL))
317 needsUpdate_ = false;
319 // get default values of macro
320 vector<docstring> const & defaults = macro_->defaults();
322 // create MathMacroArgumentValue objects pointing to the cells of the macro
323 vector<MathData> values(nargs());
324 for (size_t i = 0; i < nargs(); ++i) {
325 ArgumentProxy * proxy;
326 if (i < defaults.size())
327 proxy = new ArgumentProxy(*this, i, defaults[i]);
329 proxy = new ArgumentProxy(*this, i);
330 values[i].insert(0, MathAtom(proxy));
332 // expanding macro with the values
333 macro_->expand(values, expanded_.cell(0));
334 // get definition for list edit mode
335 docstring const & display = macro_->display();
336 asArray(display.empty() ? macro_->definition() : display, definition_);
340 void MathMacro::draw(PainterInfo & pi, int x, int y) const
342 Dimension const dim = dimension(*pi.base.bv);
344 setPosCache(pi, x, y);
348 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
349 FontSetChanger dummy(pi.base, "lyxtex");
350 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
351 } else if (displayMode_ == DISPLAY_UNFOLDED) {
352 FontSetChanger dummy(pi.base, "lyxtex");
353 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
354 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
355 cell(0).draw(pi, x, y);
356 drawMarkers(pi, expx, expy);
357 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
358 && editing_[pi.base.bv]) {
359 // Macro will be edited in a old-style list mode here:
361 CoordCache const & coords = pi.base.bv->coordCache();
362 FontInfo const & labelFont = sane_font;
364 // markers and box needs two pixels
367 // get maximal font height
369 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
372 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
373 pi.pain.text(x, y, label, labelFont);
374 x += mathed_string_width(labelFont, label);
377 definition_.draw(pi, x, y);
378 Dimension const & defDim = coords.getArrays().dim(&definition_);
379 y += max(fontDim.des, defDim.des);
382 docstring str = from_ascii("#9");
383 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
384 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
386 for (idx_type i = 0; i < nargs(); ++i) {
388 Dimension const & cdim = coords.getArrays().dim(&cell(i));
390 y += max(fontDim.asc, cdim.asc) + 1;
394 pi.pain.text(x, y, str, labelFont);
396 pi.pain.text(x, y, from_ascii(":"), labelFont);
400 cell(i).draw(pi, x, y);
403 y += max(fontDim.des, cdim.des);
406 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
407 dim.height() - 2, Color_mathmacroframe);
408 drawMarkers2(pi, expx, expy);
410 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
413 for (size_t i = 0; i < nargs(); ++i)
414 cell(i).setXY(*pi.base.bv, x, y);
416 if (drawBox && editing_[pi.base.bv]) {
417 // draw header and rectangle around
418 FontInfo font = pi.base.font;
419 augmentFont(font, from_ascii("lyxtex"));
420 font.setSize(FONT_SIZE_TINY);
421 font.setColor(Color_mathmacrolabel);
423 mathed_string_dim(font, name(), namedim);
425 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
426 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
427 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
430 if (editing_[pi.base.bv]) {
431 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
432 expanded_.cell(0).draw(pi, expx, expy);
433 pi.pain.leaveMonochromeMode();
436 pi.pain.rectangle(x, y - dim.asc, dim.wid,
437 dim.height(), Color_mathmacroframe);
439 expanded_.cell(0).draw(pi, expx, expy);
442 drawMarkers(pi, x, y);
445 // edit mode changed?
446 if (editing_[pi.base.bv] != editMode(pi.base.bv))
447 pi.base.bv->cursor().updateFlags(Update::SinglePar);
451 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
453 // We may have 0 arguments, but InsetMathNest requires at least one.
454 if (cells_.size() > 0)
455 InsetMathNest::drawSelection(pi, x, y);
459 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
461 if (displayMode_ != mode) {
462 // transfer name if changing from or to DISPLAY_UNFOLDED
463 if (mode == DISPLAY_UNFOLDED) {
465 asArray(name_, cell(0));
466 } else if (displayMode_ == DISPLAY_UNFOLDED) {
467 name_ = asString(cell(0));
475 // the interactive init mode is non-greedy by default
477 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
479 appetite_ = size_t(appetite);
483 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
485 if (nextFoldMode_ == true && macro_ && !macro_->locked())
486 return DISPLAY_NORMAL;
488 return DISPLAY_UNFOLDED;
492 bool MathMacro::validName() const
494 docstring n = name();
500 // converting back and force doesn't swallow anything?
503 if (asString(ma) != n)
507 for (size_t i = 0; i<n.size(); ++i) {
508 if (!(n[i] >= 'a' && n[i] <= 'z')
509 && !(n[i] >= 'A' && n[i] <= 'Z')
518 void MathMacro::validate(LaTeXFeatures & features) const
520 if (!requires_.empty())
521 features.require(requires_);
523 if (name() == "binom")
524 features.require("binom");
526 // validate the cells and the definition
527 if (displayMode() == DISPLAY_NORMAL) {
528 definition_.validate(features);
529 InsetMathNest::validate(features);
534 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
536 cur.updateFlags(Update::SinglePar);
537 InsetMathNest::edit(cur, front, entry_from);
541 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
543 // We may have 0 arguments, but InsetMathNest requires at least one.
545 cur.updateFlags(Update::SinglePar);
546 return InsetMathNest::editXY(cur, x, y);
552 void MathMacro::removeArgument(Inset::pos_type pos) {
553 if (displayMode_ == DISPLAY_NORMAL) {
554 LASSERT(size_t(pos) < cells_.size(), /**/);
555 cells_.erase(cells_.begin() + pos);
556 if (size_t(pos) < attachedArgsNum_)
558 if (size_t(pos) < optionals_) {
567 void MathMacro::insertArgument(Inset::pos_type pos) {
568 if (displayMode_ == DISPLAY_NORMAL) {
569 LASSERT(size_t(pos) <= cells_.size(), /**/);
570 cells_.insert(cells_.begin() + pos, MathData());
571 if (size_t(pos) < attachedArgsNum_)
573 if (size_t(pos) < optionals_)
581 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
583 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
586 // strip off empty cells, but not more than arity-attachedArgsNum_
589 for (i = cells_.size(); i > attachedArgsNum_; --i)
590 if (!cell(i - 1).empty()) break;
594 attachedArgsNum_ = 0;
595 expanded_.cell(0) = MathData();
602 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
604 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
606 attachedArgsNum_ = args.size();
607 cells_.resize(arity);
608 expanded_.cell(0) = MathData();
609 optionals_ = optionals;
615 bool MathMacro::idxFirst(Cursor & cur) const
617 cur.updateFlags(Update::SinglePar);
618 return InsetMathNest::idxFirst(cur);
622 bool MathMacro::idxLast(Cursor & cur) const
624 cur.updateFlags(Update::SinglePar);
625 return InsetMathNest::idxLast(cur);
629 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
631 if (displayMode_ == DISPLAY_UNFOLDED) {
632 docstring const & unfolded_name = name();
633 if (unfolded_name != name_) {
634 // The macro name was changed
635 Cursor inset_cursor = old;
636 int macroSlice = inset_cursor.find(this);
637 LASSERT(macroSlice != -1, /**/);
638 inset_cursor.cutOff(macroSlice);
639 inset_cursor.recordUndoInset();
641 inset_cursor.cell().erase(inset_cursor.pos());
642 inset_cursor.cell().insert(inset_cursor.pos(),
643 createInsetMath(unfolded_name, cur.buffer()));
644 cur.updateFlags(cur.result().update() | Update::SinglePar);
648 cur.updateFlags(Update::Force);
649 return InsetMathNest::notifyCursorLeaves(old, cur);
653 void MathMacro::fold(Cursor & cur)
655 if (!nextFoldMode_) {
656 nextFoldMode_ = true;
657 cur.updateFlags(Update::SinglePar);
662 void MathMacro::unfold(Cursor & cur)
665 nextFoldMode_ = false;
666 cur.updateFlags(Update::SinglePar);
671 bool MathMacro::folded() const
673 return nextFoldMode_;
677 void MathMacro::write(WriteStream & os) const
679 MathEnsurer ensurer(os, macro_ != 0, true);
682 if (displayMode_ != DISPLAY_NORMAL) {
683 os << "\\" << name();
684 if (name().size() != 1 || isAlphaASCII(name()[0]))
685 os.pendingSpace(true);
690 LASSERT(macro_, /**/);
692 // optional arguments make macros fragile
693 if (optionals_ > 0 && os.fragile())
696 os << "\\" << name();
699 // Optional arguments:
700 // First find last non-empty optional argument
701 idx_type emptyOptFrom = 0;
703 for (; i < cells_.size() && i < optionals_; ++i) {
704 if (!cell(i).empty())
705 emptyOptFrom = i + 1;
708 // print out optionals
709 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
711 os << "[" << cell(i) << "]";
714 // skip the tailing empty optionals
717 // Print remaining arguments
718 for (; i < cells_.size(); ++i) {
719 if (cell(i).size() == 1
720 && cell(i)[0].nucleus()->asCharInset()
721 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
726 os << "{" << cell(i) << "}";
730 // add space if there was no argument
732 os.pendingSpace(true);
736 void MathMacro::maple(MapleStream & os) const
738 lyx::maple(expanded_.cell(0), os);
742 void MathMacro::mathmlize(MathStream & os) const
744 os << expanded_.cell(0);
748 void MathMacro::htmlize(HtmlStream & os) const
750 os << expanded_.cell(0);
754 void MathMacro::octave(OctaveStream & os) const
756 lyx::octave(expanded_.cell(0), os);
760 void MathMacro::infoize(odocstream & os) const
762 os << "Macro: " << name();
766 void MathMacro::infoize2(odocstream & os) const
768 os << "Macro: " << name();
773 bool MathMacro::completionSupported(Cursor const & cur) const
775 if (displayMode() != DISPLAY_UNFOLDED)
776 return InsetMathNest::completionSupported(cur);
778 return lyxrc.completion_popup_math
779 && displayMode() == DISPLAY_UNFOLDED
780 && cur.bv().cursor().pos() == int(name().size());
784 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
786 if (displayMode() != DISPLAY_UNFOLDED)
787 return InsetMathNest::inlineCompletionSupported(cur);
789 return lyxrc.completion_inline_math
790 && displayMode() == DISPLAY_UNFOLDED
791 && cur.bv().cursor().pos() == int(name().size());
795 bool MathMacro::automaticInlineCompletion() const
797 if (displayMode() != DISPLAY_UNFOLDED)
798 return InsetMathNest::automaticInlineCompletion();
800 return lyxrc.completion_inline_math;
804 bool MathMacro::automaticPopupCompletion() const
806 if (displayMode() != DISPLAY_UNFOLDED)
807 return InsetMathNest::automaticPopupCompletion();
809 return lyxrc.completion_popup_math;
813 CompletionList const *
814 MathMacro::createCompletionList(Cursor const & cur) const
816 if (displayMode() != DISPLAY_UNFOLDED)
817 return InsetMathNest::createCompletionList(cur);
819 return new MathCompletionList(cur.bv().cursor());
823 docstring MathMacro::completionPrefix(Cursor const & cur) const
825 if (displayMode() != DISPLAY_UNFOLDED)
826 return InsetMathNest::completionPrefix(cur);
828 if (!completionSupported(cur))
831 return "\\" + name();
835 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
838 if (displayMode() != DISPLAY_UNFOLDED)
839 return InsetMathNest::insertCompletion(cur, s, finished);
841 if (!completionSupported(cur))
845 docstring newName = name() + s;
846 asArray(newName, cell(0));
847 cur.bv().cursor().pos() = name().size();
848 cur.updateFlags(Update::SinglePar);
852 cur.bv().cursor().pop();
853 ++cur.bv().cursor().pos();
854 cur.updateFlags(Update::SinglePar);
861 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
862 Dimension & dim) const
864 if (displayMode() != DISPLAY_UNFOLDED)
865 InsetMathNest::completionPosAndDim(cur, x, y, dim);
867 // get inset dimensions
868 dim = cur.bv().coordCache().insets().dim(this);
869 // FIXME: these 3 are no accurate, but should depend on the font.
870 // Now the popup jumps down if you enter a char with descent > 0.
876 = cur.bv().coordCache().insets().xy(this);