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"
16 #include "MathSupport.h"
17 #include "MathExtern.h"
18 #include "MathStream.h"
21 #include "BufferView.h"
23 #include "support/debug.h"
24 #include "LaTeXFeatures.h"
25 #include "FuncStatus.h"
26 #include "FuncRequest.h"
29 #include "frontends/Painter.h"
39 /// A proxy for the macro values
40 class ArgumentProxy : public InsetMath {
43 ArgumentProxy(MathMacro & mathMacro, size_t idx)
44 : mathMacro_(mathMacro), idx_(idx) {}
46 ArgumentProxy(MathMacro & mathMacro, size_t idx, docstring const & def)
47 : mathMacro_(mathMacro), idx_(idx)
52 void metrics(MetricsInfo & mi, Dimension & dim) const {
53 mathMacro_.macro()->unlock();
54 mathMacro_.cell(idx_).metrics(mi, dim);
55 if (!mathMacro_.editMetrics(mi.base.bv) && !def_.empty())
56 def_.metrics(mi, dim);
57 mathMacro_.macro()->lock();
60 void draw(PainterInfo & pi, int x, int y) const {
61 if (mathMacro_.editMetrics(pi.base.bv)) {
62 // The only way a ArgumentProxy can appear is in a cell of the
63 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
64 // mode and then, if the macro is edited the monochrome
65 // mode is entered by the MathMacro before calling the cells' draw
66 // method. Then eventually this code is reached and the proxy leaves
67 // monochrome mode temporarely. Hence, if it is not in monochrome
68 // here (and the assert triggers in pain.leaveMonochromeMode())
70 pi.pain.leaveMonochromeMode();
71 mathMacro_.cell(idx_).draw(pi, x, y);
72 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
75 mathMacro_.cell(idx_).draw(pi, x, y);
77 mathMacro_.cell(idx_).setXY(*pi.base.bv, x, y);
83 size_t idx() const { return idx_; }
85 int kerning(BufferView const * bv) const
87 if (mathMacro_.editMetrics(bv) || def_.empty())
88 return mathMacro_.cell(idx_).kerning(bv);
90 return def_.kerning(bv);
97 return new ArgumentProxy(*this);
100 MathMacro & mathMacro_;
108 MathMacro::MathMacro(docstring const & name)
109 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
110 attachedArgsNum_(0), optionals_(0), nextFoldMode_(true),
111 macro_(0), needsUpdate_(false)
115 Inset * MathMacro::clone() const
117 MathMacro * copy = new MathMacro(*this);
118 copy->needsUpdate_ = true;
119 copy->expanded_.cell(0).clear();
124 docstring MathMacro::name() const
126 if (displayMode_ == DISPLAY_UNFOLDED)
127 return asString(cell(0));
133 void MathMacro::cursorPos(BufferView const & bv,
134 CursorSlice const & sl, bool boundary, int & x, int & y) const
136 // We may have 0 arguments, but InsetMathNest requires at least one.
138 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
142 int MathMacro::cursorIdx(Cursor const & cur) const {
143 for (size_t i = 0; i != cur.depth(); ++i)
144 if (&cur[i].inset() == this)
150 bool MathMacro::editMode(BufferView const * bv) const {
151 // find this in cursor trace
152 Cursor const & cur = bv->cursor();
153 for (size_t i = 0; i != cur.depth(); ++i)
154 if (&cur[i].inset() == this) {
155 // look if there is no other macro in edit mode above
157 for (; i != cur.depth(); ++i) {
158 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
159 if (macro && macro->displayMode() == DISPLAY_NORMAL)
163 // ok, none found, I am the highest one
171 bool MathMacro::editMetrics(BufferView const * bv) const
177 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
179 // set edit mode for which we will have calculated metrics. But only
180 editing_[mi.base.bv] = editMode(mi.base.bv);
182 // calculate new metrics according to display mode
183 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
184 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
185 } else if (displayMode_ == DISPLAY_UNFOLDED) {
186 cell(0).metrics(mi, dim);
188 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
189 dim.wid += bsdim.width() + 1;
190 dim.asc = max(bsdim.ascent(), dim.ascent());
191 dim.des = max(bsdim.descent(), dim.descent());
194 BOOST_ASSERT(macro_ != 0);
196 // calculate metrics finally
198 expanded_.cell(0).metrics(mi, dim);
201 // calculate dimension with label while editing
202 if (editing_[mi.base.bv]) {
203 FontInfo font = mi.base.font;
204 augmentFont(font, from_ascii("lyxtex"));
206 mathed_string_dim(font, name(), namedim);
208 dim.wid += 2 + namedim.wid + 2 + 2;
209 dim.asc = max(dim.asc, namedim.asc) + 2;
210 dim.des = max(dim.des, namedim.des) + 2;
212 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
213 dim.asc += 1 + namedim.height() + 1;
220 int MathMacro::kerning(BufferView const * bv) const {
221 if (displayMode_ == DISPLAY_NORMAL && !editing_[bv])
222 return expanded_.kerning(bv);
228 void MathMacro::updateMacro(MacroContext const & mc)
231 macro_ = mc.get(name());
232 if (macro_ && macroBackup_ != *macro_) {
233 macroBackup_ = *macro_;
242 void MathMacro::updateRepresentation(Cursor const * bvCur)
244 // index of child where the cursor is (or -1 if none is edited)
247 curIdx = cursorIdx(*bvCur);
248 previousCurIdx_[&bvCur->bv()] = curIdx;
256 requires_ = macro_->requires();
258 // non-normal mode? We are done!
259 if (displayMode_ != DISPLAY_NORMAL)
264 needsUpdate_ = false;
266 // get default values of macro
267 vector<docstring> const & defaults = macro_->defaults();
269 // create MathMacroArgumentValue objects pointing to the cells of the macro
270 vector<MathData> values(nargs());
271 for (size_t i = 0; i < nargs(); ++i) {
272 ArgumentProxy * proxy;
274 || i >= defaults.size()
275 || defaults[i].empty()
277 proxy = new ArgumentProxy(*this, i);
279 proxy = new ArgumentProxy(*this, i, defaults[i]);
280 values[i].insert(0, MathAtom(proxy));
283 // expanding macro with the values
284 macro_->expand(values, expanded_.cell(0));
289 void MathMacro::draw(PainterInfo & pi, int x, int y) const
291 Dimension const dim = dimension(*pi.base.bv);
293 setPosCache(pi, x, y);
297 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
298 PainterInfo pi2(pi.base.bv, pi.pain);
299 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
300 //pi2.base.style = LM_ST_TEXT;
301 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
302 } else if (displayMode_ == DISPLAY_UNFOLDED) {
303 PainterInfo pi2(pi.base.bv, pi.pain);
304 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
305 //pi2.base.style = LM_ST_TEXT;
306 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
307 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
308 cell(0).draw(pi2, x, y);
309 drawMarkers(pi2, expx, expy);
312 for (size_t i = 0; i < nargs(); ++i)
313 cell(i).setXY(*pi.base.bv, x, y);
315 if (editing_[pi.base.bv]) {
316 // draw header and rectangle around
317 FontInfo font = pi.base.font;
318 augmentFont(font, from_ascii("lyxtex"));
319 font.setSize(FONT_SIZE_TINY);
320 font.setColor(Color_mathmacrolabel);
322 mathed_string_dim(font, name(), namedim);
324 pi.pain.fillRectangle(x, y - dim.asc, 2 + namedim.width() + 2, dim.height(), Color_mathmacrobg);
325 pi.pain.text(x + 2, y, name(), font);
326 expx += 2 + namew + 2;
328 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
329 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
330 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
332 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
333 expanded_.cell(0).draw(pi, expx, expy);
334 pi.pain.leaveMonochromeMode();
336 expanded_.cell(0).draw(pi, expx, expy);
338 // draw frame while editing
339 if (editing_[pi.base.bv])
340 pi.pain.rectangle(x, y - dim.asc, dim.wid, dim.height(), Color_mathmacroframe);
343 // another argument selected or edit mode changed?
344 idx_type curIdx = cursorIdx(pi.base.bv->cursor());
345 if (previousCurIdx_[pi.base.bv] != curIdx
346 || editing_[pi.base.bv] != editMode(pi.base.bv))
347 pi.base.bv->cursor().updateFlags(Update::Force);
351 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
353 // We may have 0 arguments, but InsetMathNest requires at least one.
354 if (cells_.size() > 0)
355 InsetMathNest::drawSelection(pi, x, y);
359 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
361 if (displayMode_ != mode) {
362 // transfer name if changing from or to DISPLAY_UNFOLDED
363 if (mode == DISPLAY_UNFOLDED) {
365 asArray(name_, cell(0));
366 } else if (displayMode_ == DISPLAY_UNFOLDED) {
367 name_ = asString(cell(0));
377 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
379 if (nextFoldMode_ == true && macro_ && !macro_->locked())
380 return DISPLAY_NORMAL;
382 return DISPLAY_UNFOLDED;
386 bool MathMacro::validName() const
388 docstring n = name();
394 // converting back and force doesn't swallow anything?
397 if (asString(ma) != n)
401 for (size_t i = 0; i<n.size(); ++i) {
402 if (!(n[i] >= 'a' && n[i] <= 'z') &&
403 !(n[i] >= 'A' && n[i] <= 'Z'))
411 void MathMacro::validate(LaTeXFeatures & features) const
413 if (!requires_.empty())
414 features.require(requires_);
416 if (name() == "binom" || name() == "mathcircumflex")
417 features.require(to_utf8(name()));
421 void MathMacro::edit(Cursor & cur, bool left)
423 cur.updateFlags(Update::Force);
424 InsetMathNest::edit(cur, left);
428 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
430 // We may have 0 arguments, but InsetMathNest requires at least one.
432 cur.updateFlags(Update::Force);
433 return InsetMathNest::editXY(cur, x, y);
439 void MathMacro::removeArgument(Inset::pos_type pos) {
440 if (displayMode_ == DISPLAY_NORMAL) {
441 BOOST_ASSERT(size_t(pos) < cells_.size());
442 cells_.erase(cells_.begin() + pos);
443 if (size_t(pos) < attachedArgsNum_)
445 if (size_t(pos) < optionals_) {
454 void MathMacro::insertArgument(Inset::pos_type pos) {
455 if (displayMode_ == DISPLAY_NORMAL) {
456 BOOST_ASSERT(size_t(pos) <= cells_.size());
457 cells_.insert(cells_.begin() + pos, MathData());
458 if (size_t(pos) < attachedArgsNum_)
460 if (size_t(pos) < optionals_)
468 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
470 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
473 // strip off empty cells, but not more than arity-attachedArgsNum_
476 for (i = cells_.size(); i > attachedArgsNum_; --i)
477 if (!cell(i - 1).empty()) break;
481 attachedArgsNum_ = 0;
482 expanded_.cell(0) = MathData();
489 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
491 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
493 attachedArgsNum_ = args.size();
494 cells_.resize(arity);
495 expanded_.cell(0) = MathData();
496 optionals_ = optionals;
502 bool MathMacro::idxFirst(Cursor & cur) const
504 cur.updateFlags(Update::Force);
505 return InsetMathNest::idxFirst(cur);
509 bool MathMacro::idxLast(Cursor & cur) const
511 cur.updateFlags(Update::Force);
512 return InsetMathNest::idxLast(cur);
516 bool MathMacro::notifyCursorLeaves(Cursor & cur)
518 cur.updateFlags(Update::Force);
519 return InsetMathNest::notifyCursorLeaves(cur);
523 void MathMacro::fold(Cursor & cur)
525 if (!nextFoldMode_) {
526 nextFoldMode_ = true;
527 cur.updateFlags(Update::Force);
532 void MathMacro::unfold(Cursor & cur)
535 nextFoldMode_ = false;
536 cur.updateFlags(Update::Force);
541 bool MathMacro::folded() const
543 return nextFoldMode_;
547 void MathMacro::write(WriteStream & os) const
550 if (displayMode_ != DISPLAY_NORMAL) {
551 os << "\\" << name() << " ";
552 os.pendingSpace(true);
557 BOOST_ASSERT(macro_);
559 // optional arguments make macros fragile
560 if (optionals_ > 0 && os.fragile())
563 os << "\\" << name();
566 // Optional arguments:
567 // First find last non-empty optional argument
568 idx_type emptyOptFrom = 0;
570 for (; i < cells_.size() && i < optionals_; ++i) {
571 if (!cell(i).empty())
572 emptyOptFrom = i + 1;
575 // print out optionals
576 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
578 os << "[" << cell(i) << "]";
581 // skip the tailing empty optionals
584 // Print remaining macros
585 for (; i < cells_.size(); ++i) {
586 if (cell(i).size() == 1
587 && cell(i)[0].nucleus()->asCharInset()) {
592 os << "{" << cell(i) << "}";
596 // add space if there was no argument
598 os.pendingSpace(true);
602 void MathMacro::maple(MapleStream & os) const
604 lyx::maple(expanded_.cell(0), os);
608 void MathMacro::mathmlize(MathStream & os) const
610 lyx::mathmlize(expanded_.cell(0), os);
614 void MathMacro::octave(OctaveStream & os) const
616 lyx::octave(expanded_.cell(0), os);
620 void MathMacro::infoize(odocstream & os) const
622 os << "Macro: " << name();
626 void MathMacro::infoize2(odocstream & os) const
628 os << "Macro: " << name();