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 draw(PainterInfo & pi, int x, int y) const {
79 if (mathMacro_.editMetrics(pi.base.bv)) {
80 // The only way a ArgumentProxy can appear is in a cell of the
81 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
82 // mode and then, if the macro is edited the monochrome
83 // mode is entered by the MathMacro before calling the cells' draw
84 // method. Then eventually this code is reached and the proxy leaves
85 // monochrome mode temporarely. Hence, if it is not in monochrome
86 // here (and the assert triggers in pain.leaveMonochromeMode())
88 pi.pain.leaveMonochromeMode();
89 mathMacro_.cell(idx_).draw(pi, x, y);
90 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
91 } else if (mathMacro_.cell(idx_).empty()) {
92 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
95 mathMacro_.cell(idx_).draw(pi, x, y);
98 size_t idx() const { return idx_; }
100 int kerning(BufferView const * bv) const
102 if (mathMacro_.editMetrics(bv)
103 || !mathMacro_.cell(idx_).empty())
104 return mathMacro_.cell(idx_).kerning(bv);
106 return def_.kerning(bv);
111 Inset * clone() const
113 return new ArgumentProxy(*this);
116 MathMacro & mathMacro_;
124 MathMacro::MathMacro(Buffer * buf, docstring const & name)
125 : InsetMathNest(buf, 0), name_(name), displayMode_(DISPLAY_INIT),
126 expanded_(buf), attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
127 macroBackup_(buf), macro_(0), needsUpdate_(false), appetite_(9)
131 Inset * MathMacro::clone() const
133 MathMacro * copy = new MathMacro(*this);
134 copy->needsUpdate_ = true;
135 //copy->expanded_.cell(0).clear();
140 docstring MathMacro::name() const
142 if (displayMode_ == DISPLAY_UNFOLDED)
143 return asString(cell(0));
149 void MathMacro::cursorPos(BufferView const & bv,
150 CursorSlice const & sl, bool boundary, int & x, int & y) const
152 // We may have 0 arguments, but InsetMathNest requires at least one.
154 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
158 bool MathMacro::editMode(BufferView const * bv) const {
159 // find this in cursor trace
160 Cursor const & cur = bv->cursor();
161 for (size_t i = 0; i != cur.depth(); ++i)
162 if (&cur[i].inset() == this) {
163 // look if there is no other macro in edit mode above
165 for (; i != cur.depth(); ++i) {
166 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
167 if (macro && macro->displayMode() == DISPLAY_NORMAL)
171 // ok, none found, I am the highest one
179 bool MathMacro::editMetrics(BufferView const * bv) const
185 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
187 // set edit mode for which we will have calculated metrics. But only
188 editing_[mi.base.bv] = editMode(mi.base.bv);
190 // calculate new metrics according to display mode
191 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
192 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
193 } else if (displayMode_ == DISPLAY_UNFOLDED) {
194 cell(0).metrics(mi, dim);
196 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
197 dim.wid += bsdim.width() + 1;
198 dim.asc = max(bsdim.ascent(), dim.ascent());
199 dim.des = max(bsdim.descent(), dim.descent());
201 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
202 && editing_[mi.base.bv]) {
203 // Macro will be edited in a old-style list mode here:
205 LASSERT(macro_ != 0, /**/);
207 FontInfo labelFont = sane_font;
208 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
210 // get dimension of components of list view
212 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
213 nameDim.asc = fontDim.asc;
214 nameDim.des = fontDim.des;
217 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
218 argDim.asc = fontDim.asc;
219 argDim.des = fontDim.des;
222 definition_.metrics(mi, defDim);
225 dim.wid = nameDim.wid + defDim.wid;
226 dim.asc = max(nameDim.asc, defDim.asc);
227 dim.des = max(nameDim.des, defDim.des);
229 for (idx_type i = 0; i < nargs(); ++i) {
231 cell(i).metrics(mi, cdim);
232 dim.des += max(argDim.height(), cdim.height()) + 1;
233 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
236 // make space for box and markers, 2 pixels
240 metricsMarkers2(dim);
242 LASSERT(macro_ != 0, /**/);
244 // calculate metrics, hoping that all cells are seen
246 expanded_.cell(0).metrics(mi, dim);
248 // otherwise do a manual metrics call
249 CoordCache & coords = mi.base.bv->coordCache();
250 for (idx_type i = 0; i < nargs(); ++i) {
251 if (!coords.getArrays().has(&cell(i))) {
253 cell(i).metrics(mi, tdim);
258 // calculate dimension with label while editing
259 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
260 && editing_[mi.base.bv]) {
261 FontInfo font = mi.base.font;
262 augmentFont(font, from_ascii("lyxtex"));
264 mathed_string_dim(font, name(), namedim);
266 dim.wid += 2 + namedim.wid + 2 + 2;
267 dim.asc = max(dim.asc, namedim.asc) + 2;
268 dim.des = max(dim.des, namedim.des) + 2;
270 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
271 dim.asc += 1 + namedim.height() + 1;
279 int MathMacro::kerning(BufferView const * bv) const {
280 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
281 return expanded_.kerning(bv);
287 void MathMacro::updateMacro(MacroContext const & mc)
290 macro_ = mc.get(name());
291 if (macro_ && macroBackup_ != *macro_) {
292 macroBackup_ = *macro_;
301 void MathMacro::updateRepresentation()
308 requires_ = macro_->requires();
310 // non-normal mode? We are done!
311 if (displayMode_ != DISPLAY_NORMAL)
318 needsUpdate_ = false;
320 // get default values of macro
321 vector<docstring> const & defaults = macro_->defaults();
323 // create MathMacroArgumentValue objects pointing to the cells of the macro
324 vector<MathData> values(nargs());
325 for (size_t i = 0; i < nargs(); ++i) {
326 ArgumentProxy * proxy;
327 if (i < defaults.size())
328 proxy = new ArgumentProxy(*this, i, defaults[i]);
330 proxy = new ArgumentProxy(*this, i);
331 values[i].insert(0, MathAtom(proxy));
333 // expanding macro with the values
334 macro_->expand(values, expanded_.cell(0));
335 // get definition for list edit mode
336 docstring const & display = macro_->display();
337 asArray(display.empty() ? macro_->definition() : display, definition_);
341 void MathMacro::draw(PainterInfo & pi, int x, int y) const
343 Dimension const dim = dimension(*pi.base.bv);
345 setPosCache(pi, x, y);
349 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
350 FontSetChanger dummy(pi.base, "lyxtex");
351 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
352 } else if (displayMode_ == DISPLAY_UNFOLDED) {
353 FontSetChanger dummy(pi.base, "lyxtex");
354 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
355 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
356 cell(0).draw(pi, x, y);
357 drawMarkers(pi, expx, expy);
358 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
359 && editing_[pi.base.bv]) {
360 // Macro will be edited in a old-style list mode here:
362 CoordCache const & coords = pi.base.bv->coordCache();
363 FontInfo const & labelFont = sane_font;
365 // markers and box needs two pixels
368 // get maximal font height
370 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
373 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
374 pi.pain.text(x, y, label, labelFont);
375 x += mathed_string_width(labelFont, label);
378 definition_.draw(pi, x, y);
379 Dimension const & defDim = coords.getArrays().dim(&definition_);
380 y += max(fontDim.des, defDim.des);
383 docstring str = from_ascii("#9");
384 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
385 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
387 for (idx_type i = 0; i < nargs(); ++i) {
389 Dimension const & cdim = coords.getArrays().dim(&cell(i));
391 y += max(fontDim.asc, cdim.asc) + 1;
395 pi.pain.text(x, y, str, labelFont);
397 pi.pain.text(x, y, from_ascii(":"), labelFont);
401 cell(i).draw(pi, x, y);
404 y += max(fontDim.des, cdim.des);
407 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
408 dim.height() - 2, Color_mathmacroframe);
409 drawMarkers2(pi, expx, expy);
411 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
414 for (size_t i = 0; i < nargs(); ++i)
415 cell(i).setXY(*pi.base.bv, x, y);
417 if (drawBox && editing_[pi.base.bv]) {
418 // draw header and rectangle around
419 FontInfo font = pi.base.font;
420 augmentFont(font, from_ascii("lyxtex"));
421 font.setSize(FONT_SIZE_TINY);
422 font.setColor(Color_mathmacrolabel);
424 mathed_string_dim(font, name(), namedim);
426 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
427 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
428 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
431 if (editing_[pi.base.bv]) {
432 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
433 expanded_.cell(0).draw(pi, expx, expy);
434 pi.pain.leaveMonochromeMode();
437 pi.pain.rectangle(x, y - dim.asc, dim.wid,
438 dim.height(), Color_mathmacroframe);
440 expanded_.cell(0).draw(pi, expx, expy);
443 drawMarkers(pi, x, y);
446 // edit mode changed?
447 if (editing_[pi.base.bv] != editMode(pi.base.bv))
448 pi.base.bv->cursor().updateFlags(Update::SinglePar);
452 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
454 // We may have 0 arguments, but InsetMathNest requires at least one.
455 if (cells_.size() > 0)
456 InsetMathNest::drawSelection(pi, x, y);
460 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
462 if (displayMode_ != mode) {
463 // transfer name if changing from or to DISPLAY_UNFOLDED
464 if (mode == DISPLAY_UNFOLDED) {
466 asArray(name_, cell(0));
467 } else if (displayMode_ == DISPLAY_UNFOLDED) {
468 name_ = asString(cell(0));
476 // the interactive init mode is non-greedy by default
478 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
480 appetite_ = size_t(appetite);
484 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
486 if (nextFoldMode_ == true && macro_ && !macro_->locked())
487 return DISPLAY_NORMAL;
489 return DISPLAY_UNFOLDED;
493 bool MathMacro::validName() const
495 docstring n = name();
501 // converting back and force doesn't swallow anything?
504 if (asString(ma) != n)
508 for (size_t i = 0; i<n.size(); ++i) {
509 if (!(n[i] >= 'a' && n[i] <= 'z')
510 && !(n[i] >= 'A' && n[i] <= 'Z')
519 void MathMacro::validate(LaTeXFeatures & features) const
521 if (!requires_.empty())
522 features.require(requires_);
524 if (name() == "binom")
525 features.require("binom");
527 // validate the cells and the definition
528 if (displayMode() == DISPLAY_NORMAL) {
529 definition_.validate(features);
530 InsetMathNest::validate(features);
535 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
537 cur.updateFlags(Update::SinglePar);
538 InsetMathNest::edit(cur, front, entry_from);
542 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
544 // We may have 0 arguments, but InsetMathNest requires at least one.
546 cur.updateFlags(Update::SinglePar);
547 return InsetMathNest::editXY(cur, x, y);
553 void MathMacro::removeArgument(Inset::pos_type pos) {
554 if (displayMode_ == DISPLAY_NORMAL) {
555 LASSERT(size_t(pos) < cells_.size(), /**/);
556 cells_.erase(cells_.begin() + pos);
557 if (size_t(pos) < attachedArgsNum_)
559 if (size_t(pos) < optionals_) {
568 void MathMacro::insertArgument(Inset::pos_type pos) {
569 if (displayMode_ == DISPLAY_NORMAL) {
570 LASSERT(size_t(pos) <= cells_.size(), /**/);
571 cells_.insert(cells_.begin() + pos, MathData());
572 if (size_t(pos) < attachedArgsNum_)
574 if (size_t(pos) < optionals_)
582 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
584 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
587 // strip off empty cells, but not more than arity-attachedArgsNum_
590 for (i = cells_.size(); i > attachedArgsNum_; --i)
591 if (!cell(i - 1).empty()) break;
595 attachedArgsNum_ = 0;
596 expanded_.cell(0) = MathData();
603 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
605 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
607 attachedArgsNum_ = args.size();
608 cells_.resize(arity);
609 expanded_.cell(0) = MathData();
610 optionals_ = optionals;
616 bool MathMacro::idxFirst(Cursor & cur) const
618 cur.updateFlags(Update::SinglePar);
619 return InsetMathNest::idxFirst(cur);
623 bool MathMacro::idxLast(Cursor & cur) const
625 cur.updateFlags(Update::SinglePar);
626 return InsetMathNest::idxLast(cur);
630 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
632 if (displayMode_ == DISPLAY_UNFOLDED) {
633 docstring const & unfolded_name = name();
634 if (unfolded_name != name_) {
635 // The macro name was changed
636 Cursor inset_cursor = old;
637 int macroSlice = inset_cursor.find(this);
638 LASSERT(macroSlice != -1, /**/);
639 inset_cursor.cutOff(macroSlice);
640 inset_cursor.recordUndoInset();
642 inset_cursor.cell().erase(inset_cursor.pos());
643 inset_cursor.cell().insert(inset_cursor.pos(),
644 createInsetMath(unfolded_name, cur.buffer()));
645 cur.updateFlags(cur.disp_.update() | Update::SinglePar);
649 cur.updateFlags(Update::Force);
650 return InsetMathNest::notifyCursorLeaves(old, cur);
654 void MathMacro::fold(Cursor & cur)
656 if (!nextFoldMode_) {
657 nextFoldMode_ = true;
658 cur.updateFlags(Update::SinglePar);
663 void MathMacro::unfold(Cursor & cur)
666 nextFoldMode_ = false;
667 cur.updateFlags(Update::SinglePar);
672 bool MathMacro::folded() const
674 return nextFoldMode_;
678 void MathMacro::write(WriteStream & os) const
680 MathEnsurer ensurer(os, macro_ != 0, true);
683 if (displayMode_ != DISPLAY_NORMAL) {
684 os << "\\" << name();
685 if (name().size() != 1 || isAlphaASCII(name()[0]))
686 os.pendingSpace(true);
691 LASSERT(macro_, /**/);
693 // optional arguments make macros fragile
694 if (optionals_ > 0 && os.fragile())
697 os << "\\" << name();
700 // Optional arguments:
701 // First find last non-empty optional argument
702 idx_type emptyOptFrom = 0;
704 for (; i < cells_.size() && i < optionals_; ++i) {
705 if (!cell(i).empty())
706 emptyOptFrom = i + 1;
709 // print out optionals
710 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
712 os << "[" << cell(i) << "]";
715 // skip the tailing empty optionals
718 // Print remaining arguments
719 for (; i < cells_.size(); ++i) {
720 if (cell(i).size() == 1
721 && cell(i)[0].nucleus()->asCharInset()
722 && cell(i)[0].nucleus()->asCharInset()->getChar() < 0x80) {
727 os << "{" << cell(i) << "}";
731 // add space if there was no argument
733 os.pendingSpace(true);
737 void MathMacro::maple(MapleStream & os) const
739 lyx::maple(expanded_.cell(0), os);
743 void MathMacro::mathmlize(MathStream & os) const
745 os << expanded_.cell(0);
749 void MathMacro::octave(OctaveStream & os) const
751 lyx::octave(expanded_.cell(0), os);
755 void MathMacro::infoize(odocstream & os) const
757 os << "Macro: " << name();
761 void MathMacro::infoize2(odocstream & os) const
763 os << "Macro: " << name();
768 bool MathMacro::completionSupported(Cursor const & cur) const
770 if (displayMode() != DISPLAY_UNFOLDED)
771 return InsetMathNest::completionSupported(cur);
773 return lyxrc.completion_popup_math
774 && displayMode() == DISPLAY_UNFOLDED
775 && cur.bv().cursor().pos() == int(name().size());
779 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
781 if (displayMode() != DISPLAY_UNFOLDED)
782 return InsetMathNest::inlineCompletionSupported(cur);
784 return lyxrc.completion_inline_math
785 && displayMode() == DISPLAY_UNFOLDED
786 && cur.bv().cursor().pos() == int(name().size());
790 bool MathMacro::automaticInlineCompletion() const
792 if (displayMode() != DISPLAY_UNFOLDED)
793 return InsetMathNest::automaticInlineCompletion();
795 return lyxrc.completion_inline_math;
799 bool MathMacro::automaticPopupCompletion() const
801 if (displayMode() != DISPLAY_UNFOLDED)
802 return InsetMathNest::automaticPopupCompletion();
804 return lyxrc.completion_popup_math;
808 CompletionList const *
809 MathMacro::createCompletionList(Cursor const & cur) const
811 if (displayMode() != DISPLAY_UNFOLDED)
812 return InsetMathNest::createCompletionList(cur);
814 return new MathCompletionList(cur.bv().cursor());
818 docstring MathMacro::completionPrefix(Cursor const & cur) const
820 if (displayMode() != DISPLAY_UNFOLDED)
821 return InsetMathNest::completionPrefix(cur);
823 if (!completionSupported(cur))
826 return "\\" + name();
830 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
833 if (displayMode() != DISPLAY_UNFOLDED)
834 return InsetMathNest::insertCompletion(cur, s, finished);
836 if (!completionSupported(cur))
840 docstring newName = name() + s;
841 asArray(newName, cell(0));
842 cur.bv().cursor().pos() = name().size();
843 cur.updateFlags(Update::SinglePar);
847 cur.bv().cursor().pop();
848 ++cur.bv().cursor().pos();
849 cur.updateFlags(Update::SinglePar);
856 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
857 Dimension & dim) const
859 if (displayMode() != DISPLAY_UNFOLDED)
860 InsetMathNest::completionPosAndDim(cur, x, y, dim);
862 // get inset dimensions
863 dim = cur.bv().coordCache().insets().dim(this);
864 // FIXME: these 3 are no accurate, but should depend on the font.
865 // Now the popup jumps down if you enter a char with descent > 0.
871 = cur.bv().coordCache().insets().xy(this);