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 "MathCompletionList.h"
18 #include "MathExtern.h"
19 #include "MathStream.h"
20 #include "MathSupport.h"
23 #include "BufferView.h"
24 #include "CoordCache.h"
26 #include "FuncStatus.h"
27 #include "FuncRequest.h"
28 #include "LaTeXFeatures.h"
33 #include "frontends/Painter.h"
35 #include "support/debug.h"
36 #include "support/lassert.h"
37 #include "support/textutils.h"
47 /// A proxy for the macro values
48 class ArgumentProxy : public InsetMath {
51 ArgumentProxy(MathMacro & mathMacro, size_t idx)
52 : mathMacro_(mathMacro), idx_(idx) {}
54 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
55 : mathMacro_(mathMacro), idx_(idx)
60 void metrics(MetricsInfo & mi, Dimension & dim) const {
61 mathMacro_.macro()->unlock();
62 if (!mathMacro_.editMetrics(mi.base.bv)
63 && mathMacro_.cell(idx_).empty())
64 def_.metrics(mi, dim);
66 CoordCache & coords = mi.base.bv->coordCache();
67 dim = coords.arrays().dim(&mathMacro_.cell(idx_));
69 mathMacro_.macro()->lock();
72 void draw(PainterInfo & pi, int x, int y) const {
73 if (mathMacro_.editMetrics(pi.base.bv)) {
74 // The only way a ArgumentProxy can appear is in a cell of the
75 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
76 // mode and then, if the macro is edited the monochrome
77 // mode is entered by the MathMacro before calling the cells' draw
78 // method. Then eventually this code is reached and the proxy leaves
79 // monochrome mode temporarely. Hence, if it is not in monochrome
80 // here (and the assert triggers in pain.leaveMonochromeMode())
82 pi.pain.leaveMonochromeMode();
83 mathMacro_.cell(idx_).draw(pi, x, y);
84 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
85 } else if (mathMacro_.cell(idx_).empty()) {
86 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
89 mathMacro_.cell(idx_).draw(pi, x, y);
92 size_t idx() const { return idx_; }
94 int kerning(BufferView const * bv) const
96 if (mathMacro_.editMetrics(bv)
97 || !mathMacro_.cell(idx_).empty())
98 return mathMacro_.cell(idx_).kerning(bv);
100 return def_.kerning(bv);
105 Inset * clone() const
107 return new ArgumentProxy(*this);
110 MathMacro & mathMacro_;
118 MathMacro::MathMacro(docstring const & name)
119 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
120 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
121 macro_(0), needsUpdate_(false), appetite_(9)
125 Inset * MathMacro::clone() const
127 MathMacro * copy = new MathMacro(*this);
128 copy->needsUpdate_ = true;
129 copy->expanded_.cell(0).clear();
134 docstring MathMacro::name() const
136 if (displayMode_ == DISPLAY_UNFOLDED
137 && (name_.size() > 1 || (name_[0] != '_' && name_[0] != '^')))
138 return asString(cell(0));
144 void MathMacro::cursorPos(BufferView const & bv,
145 CursorSlice const & sl, bool boundary, int & x, int & y) const
147 // We may have 0 arguments, but InsetMathNest requires at least one.
149 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
153 bool MathMacro::editMode(BufferView const * bv) const {
154 // find this in cursor trace
155 Cursor const & cur = bv->cursor();
156 for (size_t i = 0; i != cur.depth(); ++i)
157 if (&cur[i].inset() == this) {
158 // look if there is no other macro in edit mode above
160 for (; i != cur.depth(); ++i) {
161 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
162 if (macro && macro->displayMode() == DISPLAY_NORMAL)
166 // ok, none found, I am the highest one
174 bool MathMacro::editMetrics(BufferView const * bv) const
180 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
182 // set edit mode for which we will have calculated metrics. But only
183 editing_[mi.base.bv] = editMode(mi.base.bv);
185 // calculate new metrics according to display mode
186 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
187 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
188 } else if (displayMode_ == DISPLAY_UNFOLDED) {
189 cell(0).metrics(mi, dim);
191 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
192 dim.wid += bsdim.width() + 1;
193 dim.asc = max(bsdim.ascent(), dim.ascent());
194 dim.des = max(bsdim.descent(), dim.descent());
196 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
197 && editing_[mi.base.bv]) {
198 // Macro will be edited in a old-style list mode here:
200 LASSERT(macro_ != 0, /**/);
202 FontInfo labelFont = sane_font;
203 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
205 // get dimension of components of list view
207 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
208 nameDim.asc = fontDim.asc;
209 nameDim.des = fontDim.des;
212 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
213 argDim.asc = fontDim.asc;
214 argDim.des = fontDim.des;
217 definition_.metrics(mi, defDim);
220 dim.wid = nameDim.wid + defDim.wid;
221 dim.asc = max(nameDim.asc, defDim.asc);
222 dim.des = max(nameDim.des, defDim.des);
224 for (idx_type i = 0; i < nargs(); ++i) {
226 cell(i).metrics(mi, cdim);
227 dim.des += max(argDim.height(), cdim.height()) + 1;
228 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
231 // make space for box and markers, 2 pixels
235 metricsMarkers2(dim);
237 LASSERT(macro_ != 0, /**/);
239 // metrics are computed here for the cells,
240 // in the proxy we will then use the dim from the cache
241 InsetMathNest::metrics(mi);
243 // calculate metrics finally
245 expanded_.cell(0).metrics(mi, dim);
248 // calculate dimension with label while editing
249 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
250 && editing_[mi.base.bv]) {
251 FontInfo font = mi.base.font;
252 augmentFont(font, from_ascii("lyxtex"));
254 mathed_string_dim(font, name(), namedim);
256 dim.wid += 2 + namedim.wid + 2 + 2;
257 dim.asc = max(dim.asc, namedim.asc) + 2;
258 dim.des = max(dim.des, namedim.des) + 2;
260 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
261 dim.asc += 1 + namedim.height() + 1;
269 int MathMacro::kerning(BufferView const * bv) const {
270 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
271 return expanded_.kerning(bv);
277 void MathMacro::updateMacro(MacroContext const & mc)
280 macro_ = mc.get(name());
281 if (macro_ && macroBackup_ != *macro_) {
282 macroBackup_ = *macro_;
291 void MathMacro::updateRepresentation()
298 requires_ = macro_->requires();
300 // non-normal mode? We are done!
301 if (displayMode_ != DISPLAY_NORMAL)
308 needsUpdate_ = false;
310 // get default values of macro
311 vector<docstring> const & defaults = macro_->defaults();
313 // create MathMacroArgumentValue objects pointing to the cells of the macro
314 vector<MathData> values(nargs());
315 for (size_t i = 0; i < nargs(); ++i) {
316 ArgumentProxy * proxy;
317 if (i < defaults.size())
318 proxy = new ArgumentProxy(*this, i, defaults[i]);
320 proxy = new ArgumentProxy(*this, i);
321 values[i].insert(0, MathAtom(proxy));
324 // expanding macro with the values
325 macro_->expand(values, expanded_.cell(0));
326 // get definition for list edit mode
327 docstring const & display = macro_->display();
328 asArray(display.empty() ? macro_->definition() : display, definition_);
332 void MathMacro::draw(PainterInfo & pi, int x, int y) const
334 Dimension const dim = dimension(*pi.base.bv);
336 setPosCache(pi, x, y);
340 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
341 FontSetChanger dummy(pi.base, "lyxtex");
342 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
343 } else if (displayMode_ == DISPLAY_UNFOLDED) {
344 FontSetChanger dummy(pi.base, "lyxtex");
345 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
346 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
347 cell(0).draw(pi, x, y);
348 drawMarkers(pi, expx, expy);
349 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
350 && editing_[pi.base.bv]) {
351 // Macro will be edited in a old-style list mode here:
353 CoordCache & coords = pi.base.bv->coordCache();
354 FontInfo const & labelFont = sane_font;
356 // markers and box needs two pixels
359 // get maximal font height
361 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
364 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
365 pi.pain.text(x, y, label, labelFont);
366 x += mathed_string_width(labelFont, label);
369 definition_.draw(pi, x, y);
371 = coords.arrays().dim(&definition_);
372 y += max(fontDim.des, defDim.des);
375 docstring str = from_ascii("#9");
376 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
377 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
379 for (idx_type i = 0; i < nargs(); ++i) {
382 = coords.arrays().dim(&cell(i));
384 y += max(fontDim.asc, cdim.asc) + 1;
388 pi.pain.text(x, y, str, labelFont);
390 pi.pain.text(x, y, from_ascii(":"), labelFont);
394 cell(i).draw(pi, x, y);
397 y += max(fontDim.des, cdim.des);
400 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
401 dim.height() - 2, Color_mathmacroframe);
402 drawMarkers2(pi, expx, expy);
404 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
407 for (size_t i = 0; i < nargs(); ++i)
408 cell(i).setXY(*pi.base.bv, x, y);
410 if (drawBox && editing_[pi.base.bv]) {
411 // draw header and rectangle around
412 FontInfo font = pi.base.font;
413 augmentFont(font, from_ascii("lyxtex"));
414 font.setSize(FONT_SIZE_TINY);
415 font.setColor(Color_mathmacrolabel);
417 mathed_string_dim(font, name(), namedim);
419 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
420 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
421 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
424 if (editing_[pi.base.bv]) {
425 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
426 expanded_.cell(0).draw(pi, expx, expy);
427 pi.pain.leaveMonochromeMode();
430 pi.pain.rectangle(x, y - dim.asc, dim.wid,
431 dim.height(), Color_mathmacroframe);
433 expanded_.cell(0).draw(pi, expx, expy);
436 drawMarkers(pi, x, y);
439 // edit mode changed?
440 if (editing_[pi.base.bv] != editMode(pi.base.bv))
441 pi.base.bv->cursor().updateFlags(Update::SinglePar);
445 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
447 // We may have 0 arguments, but InsetMathNest requires at least one.
448 if (cells_.size() > 0)
449 InsetMathNest::drawSelection(pi, x, y);
453 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
455 if (displayMode_ != mode) {
456 // transfer name if changing from or to DISPLAY_UNFOLDED
457 if (mode == DISPLAY_UNFOLDED) {
459 asArray(name_, cell(0));
460 } else if (displayMode_ == DISPLAY_UNFOLDED) {
461 name_ = asString(cell(0));
469 // the interactive init mode is non-greedy by default
471 appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
473 appetite_ = size_t(appetite);
477 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
479 if (nextFoldMode_ == true && macro_ && !macro_->locked())
480 return DISPLAY_NORMAL;
482 return DISPLAY_UNFOLDED;
486 bool MathMacro::validName() const
488 docstring n = name();
494 // converting back and force doesn't swallow anything?
497 if (asString(ma) != n)
501 for (size_t i = 0; i<n.size(); ++i) {
502 if (!(n[i] >= 'a' && n[i] <= 'z')
503 && !(n[i] >= 'A' && n[i] <= 'Z')
512 void MathMacro::validate(LaTeXFeatures & features) const
514 if (!requires_.empty())
515 features.require(requires_);
517 if (name() == "binom" || name() == "mathcircumflex")
518 features.require(to_utf8(name()));
520 // validate the cells and the definition
521 if (displayMode() == DISPLAY_NORMAL) {
522 definition_.validate(features);
523 InsetMathNest::validate(features);
528 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
530 cur.updateFlags(Update::SinglePar);
531 InsetMathNest::edit(cur, front, entry_from);
535 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
537 // We may have 0 arguments, but InsetMathNest requires at least one.
539 cur.updateFlags(Update::SinglePar);
540 return InsetMathNest::editXY(cur, x, y);
546 void MathMacro::removeArgument(Inset::pos_type pos) {
547 if (displayMode_ == DISPLAY_NORMAL) {
548 LASSERT(size_t(pos) < cells_.size(), /**/);
549 cells_.erase(cells_.begin() + pos);
550 if (size_t(pos) < attachedArgsNum_)
552 if (size_t(pos) < optionals_) {
561 void MathMacro::insertArgument(Inset::pos_type pos) {
562 if (displayMode_ == DISPLAY_NORMAL) {
563 LASSERT(size_t(pos) <= cells_.size(), /**/);
564 cells_.insert(cells_.begin() + pos, MathData());
565 if (size_t(pos) < attachedArgsNum_)
567 if (size_t(pos) < optionals_)
575 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
577 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
580 // strip off empty cells, but not more than arity-attachedArgsNum_
583 for (i = cells_.size(); i > attachedArgsNum_; --i)
584 if (!cell(i - 1).empty()) break;
588 attachedArgsNum_ = 0;
589 expanded_.cell(0) = MathData();
596 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
598 LASSERT(displayMode_ == DISPLAY_NORMAL, /**/);
600 attachedArgsNum_ = args.size();
601 cells_.resize(arity);
602 expanded_.cell(0) = MathData();
603 optionals_ = optionals;
609 bool MathMacro::idxFirst(Cursor & cur) const
611 cur.updateFlags(Update::SinglePar);
612 return InsetMathNest::idxFirst(cur);
616 bool MathMacro::idxLast(Cursor & cur) const
618 cur.updateFlags(Update::SinglePar);
619 return InsetMathNest::idxLast(cur);
623 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
625 cur.updateFlags(Update::Force);
626 return InsetMathNest::notifyCursorLeaves(old, cur);
630 void MathMacro::fold(Cursor & cur)
632 if (!nextFoldMode_) {
633 nextFoldMode_ = true;
634 cur.updateFlags(Update::SinglePar);
639 void MathMacro::unfold(Cursor & cur)
642 nextFoldMode_ = false;
643 cur.updateFlags(Update::SinglePar);
648 bool MathMacro::folded() const
650 return nextFoldMode_;
654 void MathMacro::write(WriteStream & os) const
656 MathEnsurer ensurer(os, macro_ != 0, true);
659 if (displayMode_ != DISPLAY_NORMAL) {
660 os << "\\" << name();
661 if (name().size() != 1 || isAlphaASCII(name()[0]))
662 os.pendingSpace(true);
667 LASSERT(macro_, /**/);
669 // optional arguments make macros fragile
670 if (optionals_ > 0 && os.fragile())
673 os << "\\" << name();
676 // Optional arguments:
677 // First find last non-empty optional argument
678 idx_type emptyOptFrom = 0;
680 for (; i < cells_.size() && i < optionals_; ++i) {
681 if (!cell(i).empty())
682 emptyOptFrom = i + 1;
685 // print out optionals
686 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
688 os << "[" << cell(i) << "]";
691 // skip the tailing empty optionals
694 // Print remaining macros
695 for (; i < cells_.size(); ++i) {
696 if (cell(i).size() == 1
697 && cell(i)[0].nucleus()->asCharInset()) {
702 os << "{" << cell(i) << "}";
706 // add space if there was no argument
708 os.pendingSpace(true);
712 void MathMacro::maple(MapleStream & os) const
714 lyx::maple(expanded_.cell(0), os);
718 void MathMacro::mathmlize(MathStream & os) const
720 lyx::mathmlize(expanded_.cell(0), os);
724 void MathMacro::octave(OctaveStream & os) const
726 lyx::octave(expanded_.cell(0), os);
730 void MathMacro::infoize(odocstream & os) const
732 os << "Macro: " << name();
736 void MathMacro::infoize2(odocstream & os) const
738 os << "Macro: " << name();
743 bool MathMacro::completionSupported(Cursor const & cur) const
745 if (displayMode() != DISPLAY_UNFOLDED)
746 return InsetMathNest::completionSupported(cur);
748 return lyxrc.completion_popup_math
749 && displayMode() == DISPLAY_UNFOLDED
750 && cur.bv().cursor().pos() == int(name().size());
754 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
756 if (displayMode() != DISPLAY_UNFOLDED)
757 return InsetMathNest::inlineCompletionSupported(cur);
759 return lyxrc.completion_inline_math
760 && displayMode() == DISPLAY_UNFOLDED
761 && cur.bv().cursor().pos() == int(name().size());
765 bool MathMacro::automaticInlineCompletion() const
767 if (displayMode() != DISPLAY_UNFOLDED)
768 return InsetMathNest::automaticInlineCompletion();
770 return lyxrc.completion_inline_math;
774 bool MathMacro::automaticPopupCompletion() const
776 if (displayMode() != DISPLAY_UNFOLDED)
777 return InsetMathNest::automaticPopupCompletion();
779 return lyxrc.completion_popup_math;
783 CompletionList const *
784 MathMacro::createCompletionList(Cursor const & cur) const
786 if (displayMode() != DISPLAY_UNFOLDED)
787 return InsetMathNest::createCompletionList(cur);
789 return new MathCompletionList(cur.bv().cursor());
793 docstring MathMacro::completionPrefix(Cursor const & cur) const
795 if (displayMode() != DISPLAY_UNFOLDED)
796 return InsetMathNest::completionPrefix(cur);
798 if (!completionSupported(cur))
801 return "\\" + name();
805 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
808 if (displayMode() != DISPLAY_UNFOLDED)
809 return InsetMathNest::insertCompletion(cur, s, finished);
811 if (!completionSupported(cur))
815 docstring newName = name() + s;
816 asArray(newName, cell(0));
817 cur.bv().cursor().pos() = name().size();
818 cur.updateFlags(Update::SinglePar);
822 cur.bv().cursor().pop();
823 ++cur.bv().cursor().pos();
824 cur.updateFlags(Update::SinglePar);
831 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
832 Dimension & dim) const
834 if (displayMode() != DISPLAY_UNFOLDED)
835 InsetMathNest::completionPosAndDim(cur, x, y, dim);
837 // get inset dimensions
838 dim = cur.bv().coordCache().insets().dim(this);
839 // FIXME: these 3 are no accurate, but should depend on the font.
840 // Now the popup jumps down if you enter a char with descent > 0.
846 = cur.bv().coordCache().insets().xy(this);