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 docstring MathMacro::name() const
143 if (displayMode_ == DISPLAY_UNFOLDED)
144 return asString(cell(0));
150 void MathMacro::cursorPos(BufferView const & bv,
151 CursorSlice const & sl, bool boundary, int & x, int & y) const
153 // We may have 0 arguments, but InsetMathNest requires at least one.
155 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
159 bool MathMacro::editMode(BufferView const * bv) const {
160 // find this in cursor trace
161 Cursor const & cur = bv->cursor();
162 for (size_t i = 0; i != cur.depth(); ++i)
163 if (&cur[i].inset() == this) {
164 // look if there is no other macro in edit mode above
166 for (; i != cur.depth(); ++i) {
167 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
168 if (macro && macro->displayMode() == DISPLAY_NORMAL)
172 // ok, none found, I am the highest one
180 bool MathMacro::editMetrics(BufferView const * bv) const
186 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
188 // set edit mode for which we will have calculated metrics. But only
189 editing_[mi.base.bv] = editMode(mi.base.bv);
191 // calculate new metrics according to display mode
192 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
193 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
194 } else if (displayMode_ == DISPLAY_UNFOLDED) {
195 cell(0).metrics(mi, dim);
197 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
198 dim.wid += bsdim.width() + 1;
199 dim.asc = max(bsdim.ascent(), dim.ascent());
200 dim.des = max(bsdim.descent(), dim.descent());
202 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
203 && editing_[mi.base.bv]) {
204 // Macro will be edited in a old-style list mode here:
206 LASSERT(macro_ != 0, /**/);
208 FontInfo labelFont = sane_font;
209 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
211 // get dimension of components of list view
213 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
214 nameDim.asc = fontDim.asc;
215 nameDim.des = fontDim.des;
218 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
219 argDim.asc = fontDim.asc;
220 argDim.des = fontDim.des;
223 definition_.metrics(mi, defDim);
226 dim.wid = nameDim.wid + defDim.wid;
227 dim.asc = max(nameDim.asc, defDim.asc);
228 dim.des = max(nameDim.des, defDim.des);
230 for (idx_type i = 0; i < nargs(); ++i) {
232 cell(i).metrics(mi, cdim);
233 dim.des += max(argDim.height(), cdim.height()) + 1;
234 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
237 // make space for box and markers, 2 pixels
241 metricsMarkers2(dim);
243 LASSERT(macro_ != 0, /**/);
245 // calculate metrics, hoping that all cells are seen
247 expanded_.cell(0).metrics(mi, dim);
249 // otherwise do a manual metrics call
250 CoordCache & coords = mi.base.bv->coordCache();
251 for (idx_type i = 0; i < nargs(); ++i) {
252 if (!coords.getArrays().has(&cell(i))) {
254 cell(i).metrics(mi, tdim);
259 // calculate dimension with label while editing
260 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
261 && editing_[mi.base.bv]) {
262 FontInfo font = mi.base.font;
263 augmentFont(font, from_ascii("lyxtex"));
265 mathed_string_dim(font, name(), namedim);
267 dim.wid += 2 + namedim.wid + 2 + 2;
268 dim.asc = max(dim.asc, namedim.asc) + 2;
269 dim.des = max(dim.des, namedim.des) + 2;
271 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
272 dim.asc += 1 + namedim.height() + 1;
280 int MathMacro::kerning(BufferView const * bv) const {
281 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
282 return expanded_.kerning(bv);
288 void MathMacro::updateMacro(MacroContext const & mc)
291 macro_ = mc.get(name());
292 if (macro_ && macroBackup_ != *macro_) {
293 macroBackup_ = *macro_;
302 void MathMacro::updateRepresentation()
309 requires_ = macro_->requires();
312 // non-normal mode? We are done!
313 || (displayMode_ != DISPLAY_NORMAL))
316 needsUpdate_ = false;
318 // get default values of macro
319 vector<docstring> const & defaults = macro_->defaults();
321 // create MathMacroArgumentValue objects pointing to the cells of the macro
322 vector<MathData> values(nargs());
323 for (size_t i = 0; i < nargs(); ++i) {
324 ArgumentProxy * proxy;
325 if (i < defaults.size())
326 proxy = new ArgumentProxy(*this, i, defaults[i]);
328 proxy = new ArgumentProxy(*this, i);
329 values[i].insert(0, MathAtom(proxy));
331 // expanding macro with the values
332 macro_->expand(values, expanded_.cell(0));
333 // get definition for list edit mode
334 docstring const & display = macro_->display();
335 asArray(display.empty() ? macro_->definition() : display, definition_);
339 void MathMacro::draw(PainterInfo & pi, int x, int y) const
341 Dimension const dim = dimension(*pi.base.bv);
343 setPosCache(pi, x, y);
347 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
348 FontSetChanger dummy(pi.base, "lyxtex");
349 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
350 } else if (displayMode_ == DISPLAY_UNFOLDED) {
351 FontSetChanger dummy(pi.base, "lyxtex");
352 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
353 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
354 cell(0).draw(pi, x, y);
355 drawMarkers(pi, expx, expy);
356 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
357 && editing_[pi.base.bv]) {
358 // Macro will be edited in a old-style list mode here:
360 CoordCache const & coords = pi.base.bv->coordCache();
361 FontInfo const & labelFont = sane_font;
363 // markers and box needs two pixels
366 // get maximal font height
368 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
371 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
372 pi.pain.text(x, y, label, labelFont);
373 x += mathed_string_width(labelFont, label);
376 definition_.draw(pi, x, y);
377 Dimension const & defDim = coords.getArrays().dim(&definition_);
378 y += max(fontDim.des, defDim.des);
381 docstring str = from_ascii("#9");
382 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
383 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
385 for (idx_type i = 0; i < nargs(); ++i) {
387 Dimension const & cdim = coords.getArrays().dim(&cell(i));
389 y += max(fontDim.asc, cdim.asc) + 1;
393 pi.pain.text(x, y, str, labelFont);
395 pi.pain.text(x, y, from_ascii(":"), labelFont);
399 cell(i).draw(pi, x, y);
402 y += max(fontDim.des, cdim.des);
405 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
406 dim.height() - 2, Color_mathmacroframe);
407 drawMarkers2(pi, expx, expy);
409 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
412 for (size_t i = 0; i < nargs(); ++i)
413 cell(i).setXY(*pi.base.bv, x, y);
415 if (drawBox && editing_[pi.base.bv]) {
416 // draw header and rectangle around
417 FontInfo font = pi.base.font;
418 augmentFont(font, from_ascii("lyxtex"));
419 font.setSize(FONT_SIZE_TINY);
420 font.setColor(Color_mathmacrolabel);
422 mathed_string_dim(font, name(), namedim);
424 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
425 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
426 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
429 if (editing_[pi.base.bv]) {
430 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
431 expanded_.cell(0).draw(pi, expx, expy);
432 pi.pain.leaveMonochromeMode();
435 pi.pain.rectangle(x, y - dim.asc, dim.wid,
436 dim.height(), Color_mathmacroframe);
438 expanded_.cell(0).draw(pi, expx, expy);
441 drawMarkers(pi, x, y);
444 // edit mode changed?
445 if (editing_[pi.base.bv] != editMode(pi.base.bv))
446 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
450 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
452 // We may have 0 arguments, but InsetMathNest requires at least one.
453 if (cells_.size() > 0)
454 InsetMathNest::drawSelection(pi, x, y);
458 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
460 if (displayMode_ != mode) {
461 // transfer name if changing from or to DISPLAY_UNFOLDED
462 if (mode == DISPLAY_UNFOLDED) {
464 asArray(name_, cell(0));
465 } else if (displayMode_ == DISPLAY_UNFOLDED) {
466 name_ = asString(cell(0));
474 // the interactive init mode is non-greedy by default
476 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
478 appetite_ = size_t(appetite);
482 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
484 if (nextFoldMode_ == true && macro_ && !macro_->locked())
485 return DISPLAY_NORMAL;
487 return DISPLAY_UNFOLDED;
491 bool MathMacro::validName() const
493 docstring n = name();
499 // converting back and force doesn't swallow anything?
502 if (asString(ma) != n)
506 for (size_t i = 0; i<n.size(); ++i) {
507 if (!(n[i] >= 'a' && n[i] <= 'z')
508 && !(n[i] >= 'A' && n[i] <= 'Z')
517 void MathMacro::validate(LaTeXFeatures & features) const
519 if (!requires_.empty())
520 features.require(requires_);
522 if (name() == "binom")
523 features.require("binom");
525 // validate the cells and the definition
526 if (displayMode() == DISPLAY_NORMAL) {
527 definition_.validate(features);
528 InsetMathNest::validate(features);
533 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
535 cur.screenUpdateFlags(Update::SinglePar);
536 InsetMathNest::edit(cur, front, entry_from);
540 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
542 // We may have 0 arguments, but InsetMathNest requires at least one.
544 cur.screenUpdateFlags(Update::SinglePar);
545 return InsetMathNest::editXY(cur, x, y);
551 void MathMacro::removeArgument(Inset::pos_type pos) {
552 if (displayMode_ == DISPLAY_NORMAL) {
553 LASSERT(size_t(pos) < cells_.size(), /**/);
554 cells_.erase(cells_.begin() + pos);
555 if (size_t(pos) < attachedArgsNum_)
557 if (size_t(pos) < optionals_) {
566 void MathMacro::insertArgument(Inset::pos_type pos) {
567 if (displayMode_ == DISPLAY_NORMAL) {
568 LASSERT(size_t(pos) <= cells_.size(), /**/);
569 cells_.insert(cells_.begin() + pos, MathData());
570 if (size_t(pos) < attachedArgsNum_)
572 if (size_t(pos) < optionals_)
580 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
582 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
585 // strip off empty cells, but not more than arity-attachedArgsNum_
588 for (i = cells_.size(); i > attachedArgsNum_; --i)
589 if (!cell(i - 1).empty()) break;
593 attachedArgsNum_ = 0;
594 expanded_.cell(0) = MathData();
601 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
603 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
605 attachedArgsNum_ = args.size();
606 cells_.resize(arity);
607 expanded_.cell(0) = MathData();
608 optionals_ = optionals;
614 bool MathMacro::idxFirst(Cursor & cur) const
616 cur.screenUpdateFlags(Update::SinglePar);
617 return InsetMathNest::idxFirst(cur);
621 bool MathMacro::idxLast(Cursor & cur) const
623 cur.screenUpdateFlags(Update::SinglePar);
624 return InsetMathNest::idxLast(cur);
628 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
630 if (displayMode_ == DISPLAY_UNFOLDED) {
631 docstring const & unfolded_name = name();
632 if (unfolded_name != name_) {
633 // The macro name was changed
634 Cursor inset_cursor = old;
635 int macroSlice = inset_cursor.find(this);
636 LASSERT(macroSlice != -1, /**/);
637 inset_cursor.cutOff(macroSlice);
638 inset_cursor.recordUndoInset();
640 inset_cursor.cell().erase(inset_cursor.pos());
641 inset_cursor.cell().insert(inset_cursor.pos(),
642 createInsetMath(unfolded_name, cur.buffer()));
643 cur.screenUpdateFlags(cur.result().update() | Update::SinglePar);
647 cur.screenUpdateFlags(Update::Force);
648 return InsetMathNest::notifyCursorLeaves(old, cur);
652 void MathMacro::fold(Cursor & cur)
654 if (!nextFoldMode_) {
655 nextFoldMode_ = true;
656 cur.screenUpdateFlags(Update::SinglePar);
661 void MathMacro::unfold(Cursor & cur)
664 nextFoldMode_ = false;
665 cur.screenUpdateFlags(Update::SinglePar);
670 bool MathMacro::folded() const
672 return nextFoldMode_;
676 void MathMacro::write(WriteStream & os) const
678 MathEnsurer ensurer(os, macro_ != 0, true);
681 if (displayMode_ != DISPLAY_NORMAL) {
682 os << "\\" << name();
683 if (name().size() != 1 || isAlphaASCII(name()[0]))
684 os.pendingSpace(true);
689 LASSERT(macro_, /**/);
691 // optional arguments make macros fragile
692 if (optionals_ > 0 && os.fragile())
695 os << "\\" << name();
698 // Optional arguments:
699 // First find last non-empty optional argument
700 idx_type emptyOptFrom = 0;
702 for (; i < cells_.size() && i < optionals_; ++i) {
703 if (!cell(i).empty())
704 emptyOptFrom = i + 1;
707 // print out optionals
708 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
710 os << "[" << cell(i) << "]";
713 // skip the tailing empty optionals
716 // Print remaining arguments
717 for (; i < cells_.size(); ++i) {
718 if (cell(i).size() == 1
719 && cell(i)[0].nucleus()->asCharInset()
720 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
725 os << "{" << cell(i) << "}";
729 // add space if there was no argument
731 os.pendingSpace(true);
735 void MathMacro::maple(MapleStream & os) const
737 lyx::maple(expanded_.cell(0), os);
741 void MathMacro::mathmlize(MathStream & os) const
743 os << expanded_.cell(0);
747 void MathMacro::htmlize(HtmlStream & os) const
749 os << expanded_.cell(0);
753 void MathMacro::octave(OctaveStream & os) const
755 lyx::octave(expanded_.cell(0), os);
759 void MathMacro::infoize(odocstream & os) const
761 os << "Macro: " << name();
765 void MathMacro::infoize2(odocstream & os) const
767 os << "Macro: " << name();
772 bool MathMacro::completionSupported(Cursor const & cur) const
774 if (displayMode() != DISPLAY_UNFOLDED)
775 return InsetMathNest::completionSupported(cur);
777 return lyxrc.completion_popup_math
778 && displayMode() == DISPLAY_UNFOLDED
779 && cur.bv().cursor().pos() == int(name().size());
783 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
785 if (displayMode() != DISPLAY_UNFOLDED)
786 return InsetMathNest::inlineCompletionSupported(cur);
788 return lyxrc.completion_inline_math
789 && displayMode() == DISPLAY_UNFOLDED
790 && cur.bv().cursor().pos() == int(name().size());
794 bool MathMacro::automaticInlineCompletion() const
796 if (displayMode() != DISPLAY_UNFOLDED)
797 return InsetMathNest::automaticInlineCompletion();
799 return lyxrc.completion_inline_math;
803 bool MathMacro::automaticPopupCompletion() const
805 if (displayMode() != DISPLAY_UNFOLDED)
806 return InsetMathNest::automaticPopupCompletion();
808 return lyxrc.completion_popup_math;
812 CompletionList const *
813 MathMacro::createCompletionList(Cursor const & cur) const
815 if (displayMode() != DISPLAY_UNFOLDED)
816 return InsetMathNest::createCompletionList(cur);
818 return new MathCompletionList(cur.bv().cursor());
822 docstring MathMacro::completionPrefix(Cursor const & cur) const
824 if (displayMode() != DISPLAY_UNFOLDED)
825 return InsetMathNest::completionPrefix(cur);
827 if (!completionSupported(cur))
830 return "\\" + name();
834 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
837 if (displayMode() != DISPLAY_UNFOLDED)
838 return InsetMathNest::insertCompletion(cur, s, finished);
840 if (!completionSupported(cur))
844 docstring newName = name() + s;
845 asArray(newName, cell(0));
846 cur.bv().cursor().pos() = name().size();
847 cur.screenUpdateFlags(Update::SinglePar);
851 cur.bv().cursor().pop();
852 ++cur.bv().cursor().pos();
853 cur.screenUpdateFlags(Update::SinglePar);
860 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
861 Dimension & dim) const
863 if (displayMode() != DISPLAY_UNFOLDED)
864 InsetMathNest::completionPosAndDim(cur, x, y, dim);
866 // get inset dimensions
867 dim = cur.bv().coordCache().insets().dim(this);
868 // FIXME: these 3 are no accurate, but should depend on the font.
869 // Now the popup jumps down if you enter a char with descent > 0.
875 = cur.bv().coordCache().insets().xy(this);