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_.editing() && !def_.empty())
56 def_.metrics(mi, dim);
57 mathMacro_.macro()->lock();
60 void draw(PainterInfo & pi, int x, int y) const {
61 if (mathMacro_.editing()) {
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, in the case of "editing_ == true" 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() const { return mathMacro_.cell(idx_).kerning(); }
91 return new ArgumentProxy(*this);
94 MathMacro & mathMacro_;
102 MathMacro::MathMacro(docstring const & name)
103 : InsetMathNest(0), name_(name), displayMode_(DISPLAY_INIT),
104 attachedArgsNum_(0), previousCurIdx_(-1),
105 optionals_(0), nextFoldMode_(true),
106 macro_(0), editing_(false), needsUpdate_(false)
110 Inset * MathMacro::clone() const
112 MathMacro * copy = new MathMacro(*this);
113 copy->needsUpdate_ = true;
114 copy->expanded_.cell(0).clear();
119 docstring MathMacro::name() const
121 if (displayMode_ == DISPLAY_UNFOLDED)
122 return asString(cell(0));
128 void MathMacro::cursorPos(BufferView const & bv,
129 CursorSlice const & sl, bool boundary, int & x, int & y) const
131 // We may have 0 arguments, but InsetMathNest requires at least one.
133 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
137 int MathMacro::cursorIdx(Cursor const & cur) const {
138 for (size_t i = 0; i != cur.depth(); ++i)
139 if (&cur[i].inset() == this)
145 bool MathMacro::editMode(Cursor const & cur) const {
146 // find this in cursor trace
147 for (size_t i = 0; i != cur.depth(); ++i)
148 if (&cur[i].inset() == this) {
149 // look if there is no other macro in edit mode above
151 for (; i != cur.depth(); ++i) {
152 MathMacro const * macro = dynamic_cast<MathMacro const *>(&cur[i].inset());
153 if (macro && macro->displayMode() == DISPLAY_NORMAL)
157 // ok, none found, I am the highest one
165 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
167 // calculate new metrics according to display mode
168 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
169 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
170 } else if (displayMode_ == DISPLAY_UNFOLDED) {
171 cell(0).metrics(mi, dim);
173 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
174 dim.wid += bsdim.width() + 1;
175 dim.asc = max(bsdim.ascent(), dim.ascent());
176 dim.des = max(bsdim.descent(), dim.descent());
179 BOOST_ASSERT(macro_ != 0);
181 // calculate metric finally
183 expanded_.cell(0).metrics(mi, dim);
186 // calculate dimension with label while editing
188 FontInfo font = mi.base.font;
189 augmentFont(font, from_ascii("lyxtex"));
191 mathed_string_dim(font, name(), namedim);
193 dim.wid += 2 + namedim.wid + 2 + 2;
194 dim.asc = max(dim.asc, namedim.asc) + 2;
195 dim.des = max(dim.des, namedim.des) + 2;
197 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
198 dim.asc += 1 + namedim.height() + 1;
203 // Cache the inset dimension.
204 setDimCache(mi, dim);
208 int MathMacro::kerning() const {
209 if (displayMode_ == DISPLAY_NORMAL && !editing_)
210 return expanded_.kerning();
216 void MathMacro::updateMacro(MacroContext const & mc)
219 macro_ = mc.get(name());
220 if (macro_ && macroBackup_ != *macro_) {
221 macroBackup_ = *macro_;
230 void MathMacro::updateRepresentation(Cursor const * bvCur)
232 // index of child where the cursor is (or -1 if none is edited)
235 curIdx = cursorIdx(*bvCur);
236 previousCurIdx_ = curIdx;
243 requires_ = macro_->requires();
245 // non-normal mode? We are done!
246 if (displayMode_ != DISPLAY_NORMAL)
249 // set edit mode to draw box around if needed
250 bool prevEditing = editing_;
253 editing_ = editMode(*bvCur);
255 // editMode changed and we have to switch default value and hole of optional?
256 if (optionals_ > 0 && nargs() > 0 &&
257 prevEditing != editing_)
262 needsUpdate_ = false;
264 // get default values of macro
265 vector<docstring> const & defaults = macro_->defaults();
267 // create MathMacroArgumentValue objects pointing to the cells of the macro
268 vector<MathData> values(nargs());
269 for (size_t i = 0; i < nargs(); ++i) {
270 ArgumentProxy * proxy;
272 || i >= defaults.size()
273 || defaults[i].empty()
275 proxy = new ArgumentProxy(*this, i);
277 proxy = new ArgumentProxy(*this, i, defaults[i]);
278 values[i].insert(0, MathAtom(proxy));
281 // expanding macro with the values
282 macro_->expand(values, expanded_.cell(0));
287 void MathMacro::draw(PainterInfo & pi, int x, int y) const
289 Dimension const dim = dimension(*pi.base.bv);
291 setPosCache(pi, x, y);
295 if (displayMode_ == DISPLAY_INIT || displayMode_ == DISPLAY_INTERACTIVE_INIT) {
296 PainterInfo pi2(pi.base.bv, pi.pain);
297 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
298 //pi2.base.style = LM_ST_TEXT;
299 pi2.pain.text(x, y, from_ascii("\\") + name(), pi2.base.font);
300 } else if (displayMode_ == DISPLAY_UNFOLDED) {
301 PainterInfo pi2(pi.base.bv, pi.pain);
302 pi2.base.font.setColor(macro_ ? Color_latex : Color_error);
303 //pi2.base.style = LM_ST_TEXT;
304 pi2.pain.text(x, y, from_ascii("\\"), pi2.base.font);
305 x += mathed_string_width(pi2.base.font, from_ascii("\\")) + 1;
306 cell(0).draw(pi2, x, y);
307 drawMarkers(pi2, expx, expy);
310 for (size_t i = 0; i < nargs(); ++i)
311 cell(i).setXY(*pi.base.bv, x, y);
314 // draw header and rectangle around
315 FontInfo font = pi.base.font;
316 augmentFont(font, from_ascii("lyxtex"));
317 font.setSize(FONT_SIZE_TINY);
318 font.setColor(Color_mathmacrolabel);
320 mathed_string_dim(font, name(), namedim);
322 pi.pain.fillRectangle(x, y - dim.asc, 2 + namedim.width() + 2, dim.height(), Color_mathmacrobg);
323 pi.pain.text(x + 2, y, name(), font);
324 expx += 2 + namew + 2;
326 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
327 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
328 expx += (dim.wid - expanded_.cell(0).dimension(*pi.base.bv).width()) / 2;
330 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
331 expanded_.cell(0).draw(pi, expx, expy);
332 pi.pain.leaveMonochromeMode();
334 expanded_.cell(0).draw(pi, expx, expy);
336 // draw frame while editing
338 pi.pain.rectangle(x, y - dim.asc, dim.wid, dim.height(), Color_mathmacroframe);
341 // another argument selected?
342 idx_type curIdx = cursorIdx(pi.base.bv->cursor());
343 if (previousCurIdx_ != curIdx || editing_ != editMode(pi.base.bv->cursor()))
344 pi.base.bv->cursor().updateFlags(Update::Force);
348 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
350 // We may have 0 arguments, but InsetMathNest requires at least one.
351 if (cells_.size() > 0)
352 InsetMathNest::drawSelection(pi, x, y);
356 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode)
358 if (displayMode_ != mode) {
359 // transfer name if changing from or to DISPLAY_UNFOLDED
360 if (mode == DISPLAY_UNFOLDED) {
362 asArray(name_, cell(0));
363 } else if (displayMode_ == DISPLAY_UNFOLDED) {
364 name_ = asString(cell(0));
374 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
376 if (nextFoldMode_ == true && macro_ && !macro_->locked())
377 return DISPLAY_NORMAL;
379 return DISPLAY_UNFOLDED;
383 bool MathMacro::validName() const
385 docstring n = name();
391 // converting back and force doesn't swallow anything?
394 if (asString(ma) != n)
398 for (size_t i = 0; i<n.size(); ++i) {
399 if (!(n[i] >= 'a' && n[i] <= 'z') &&
400 !(n[i] >= 'A' && n[i] <= 'Z'))
408 void MathMacro::validate(LaTeXFeatures & features) const
410 if (!requires_.empty())
411 features.require(requires_);
413 if (name() == "binom" || name() == "mathcircumflex")
414 features.require(to_utf8(name()));
418 void MathMacro::edit(Cursor & cur, bool left)
420 cur.updateFlags(Update::Force);
421 InsetMathNest::edit(cur, left);
425 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
427 // We may have 0 arguments, but InsetMathNest requires at least one.
429 cur.updateFlags(Update::Force);
430 return InsetMathNest::editXY(cur, x, y);
436 void MathMacro::removeArgument(Inset::pos_type pos) {
437 if (displayMode_ == DISPLAY_NORMAL) {
438 BOOST_ASSERT(size_t(pos) < cells_.size());
439 cells_.erase(cells_.begin() + pos);
440 if (size_t(pos) < attachedArgsNum_)
442 if (size_t(pos) < optionals_) {
451 void MathMacro::insertArgument(Inset::pos_type pos) {
452 if (displayMode_ == DISPLAY_NORMAL) {
453 BOOST_ASSERT(size_t(pos) <= cells_.size());
454 cells_.insert(cells_.begin() + pos, MathData());
455 if (size_t(pos) < attachedArgsNum_)
457 if (size_t(pos) < optionals_)
465 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
467 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
470 // strip off empty cells, but not more than arity-attachedArgsNum_
473 for (i = cells_.size(); i > attachedArgsNum_; --i)
474 if (!cell(i - 1).empty()) break;
478 attachedArgsNum_ = 0;
479 expanded_.cell(0) = MathData();
486 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
488 BOOST_ASSERT(displayMode_ == DISPLAY_NORMAL);
490 attachedArgsNum_ = args.size();
491 cells_.resize(arity);
492 expanded_.cell(0) = MathData();
493 optionals_ = optionals;
499 bool MathMacro::idxFirst(Cursor & cur) const
501 cur.updateFlags(Update::Force);
502 return InsetMathNest::idxFirst(cur);
506 bool MathMacro::idxLast(Cursor & cur) const
508 cur.updateFlags(Update::Force);
509 return InsetMathNest::idxLast(cur);
513 bool MathMacro::notifyCursorLeaves(Cursor & cur)
515 cur.updateFlags(Update::Force);
516 return InsetMathNest::notifyCursorLeaves(cur);
520 void MathMacro::fold(Cursor & cur)
522 if (!nextFoldMode_) {
523 nextFoldMode_ = true;
524 cur.updateFlags(Update::Force);
529 void MathMacro::unfold(Cursor & cur)
532 nextFoldMode_ = false;
533 cur.updateFlags(Update::Force);
538 bool MathMacro::folded() const
540 return nextFoldMode_;
544 void MathMacro::write(WriteStream & os) const
547 if (displayMode_ != DISPLAY_NORMAL) {
548 os << "\\" << name() << " ";
549 os.pendingSpace(true);
554 BOOST_ASSERT(macro_);
556 // optional arguments make macros fragile
557 if (optionals_ > 0 && os.fragile())
560 os << "\\" << name();
564 // Use macroBackup_ instead of macro_ here, because
565 // this is outside the metrics/draw calls, hence the macro_
566 // variable can point to a MacroData which was freed already.
567 vector<docstring> const & defaults = macroBackup_.defaults();
571 // Print first optional in LaTeX semantics
572 if (i < optionals_) {
573 // the first real optional, the others are non-optional in latex
574 if (!cell(i).empty()) {
576 os << "[" << cell(0) << "]";
582 // In lyx mode print all in any case
583 for (; i < cells_.size() && i < optionals_; ++i) {
585 os << "[" << cell(i) << "]";
589 // Print remaining macros
590 // (also the further optional parameters in LaTeX mode!)
591 for (; i < cells_.size(); ++i) {
592 if (cell(i).empty() && i < optionals_)
593 os << "{" << defaults[i] << "}";
594 else if (cell(i).size() == 1
595 && cell(i)[0].nucleus()->asCharInset()) {
600 os << "{" << cell(i) << "}";
604 // add space if there was no argument
606 os.pendingSpace(true);
610 void MathMacro::maple(MapleStream & os) const
612 lyx::maple(expanded_.cell(0), os);
616 void MathMacro::mathmlize(MathStream & os) const
618 lyx::mathmlize(expanded_.cell(0), os);
622 void MathMacro::octave(OctaveStream & os) const
624 lyx::octave(expanded_.cell(0), os);
628 void MathMacro::infoize(odocstream & os) const
630 os << "Macro: " << name();
634 void MathMacro::infoize2(odocstream & os) const
636 os << "Macro: " << name();