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 "BufferList.h"
26 #include "BufferView.h"
27 #include "CoordCache.h"
29 #include "FuncStatus.h"
30 #include "FuncRequest.h"
31 #include "LaTeXFeatures.h"
35 #include "frontends/Painter.h"
37 #include "support/debug.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
41 #include "support/textutils.h"
46 using namespace lyx::support;
52 /// A proxy for the macro values
53 class ArgumentProxy : public InsetMath {
56 ArgumentProxy(MathMacro * mathMacro, size_t idx)
57 : mathMacro_(mathMacro), idx_(idx) {}
59 ArgumentProxy(MathMacro * mathMacro, size_t idx, docstring const & def)
60 : mathMacro_(mathMacro), idx_(idx)
65 void setOwner(MathMacro * mathMacro) { mathMacro_ = mathMacro; }
67 InsetCode lyxCode() const { return ARGUMENT_PROXY_CODE; }
69 void metrics(MetricsInfo & mi, Dimension & dim) const {
70 mathMacro_->macro()->unlock();
71 mathMacro_->cell(idx_).metrics(mi, dim);
73 if (!mathMacro_->editMetrics(mi.base.bv)
74 && mathMacro_->cell(idx_).empty())
75 def_.metrics(mi, dim);
77 mathMacro_->macro()->lock();
79 // write(), normalize(), infoize() and infoize2() are not needed since
80 // MathMacro uses the definition and not the expanded cells.
82 void maple(MapleStream & ms) const { ms << mathMacro_->cell(idx_); }
84 void maxima(MaximaStream & ms) const { ms << mathMacro_->cell(idx_); }
86 void mathematica(MathematicaStream & ms) const { ms << mathMacro_->cell(idx_); }
88 void mathmlize(MathStream & ms) const { ms << mathMacro_->cell(idx_); }
90 void htmlize(HtmlStream & ms) const { ms << mathMacro_->cell(idx_); }
92 void octave(OctaveStream & os) const { os << mathMacro_->cell(idx_); }
94 void draw(PainterInfo & pi, int x, int y) const {
95 if (mathMacro_->editMetrics(pi.base.bv)) {
96 // The only way a ArgumentProxy can appear is in a cell of the
97 // MathMacro. Moreover the cells are only drawn in the DISPLAY_FOLDED
98 // mode and then, if the macro is edited the monochrome
99 // mode is entered by the MathMacro before calling the cells' draw
100 // method. Then eventually this code is reached and the proxy leaves
101 // monochrome mode temporarely. Hence, if it is not in monochrome
102 // here (and the assert triggers in pain.leaveMonochromeMode())
104 pi.pain.leaveMonochromeMode();
105 mathMacro_->cell(idx_).draw(pi, x, y);
106 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
107 } else if (mathMacro_->cell(idx_).empty()) {
108 mathMacro_->cell(idx_).setXY(*pi.base.bv, x, y);
111 mathMacro_->cell(idx_).draw(pi, x, y);
114 size_t idx() const { return idx_; }
116 int kerning(BufferView const * bv) const
118 if (mathMacro_->editMetrics(bv)
119 || !mathMacro_->cell(idx_).empty())
120 return mathMacro_->cell(idx_).kerning(bv);
122 return def_.kerning(bv);
127 Inset * clone() const
129 return new ArgumentProxy(*this);
132 MathMacro * mathMacro_;
140 /// Private implementation of MathMacro
141 class MathMacro::Private {
143 Private(Buffer * buf, docstring const & name)
144 : name_(name), displayMode_(DISPLAY_INIT),
145 expanded_(buf), definition_(buf), attachedArgsNum_(0),
146 optionals_(0), nextFoldMode_(true), macroBackup_(buf),
147 macro_(0), needsUpdate_(false), isUpdating_(false),
151 /// Update the pointers to our owner of all expanded macros.
152 /// This needs to be called every time a copy of the owner is created
154 void updateChildren(MathMacro * owner);
157 /// current display mode
158 DisplayMode displayMode_;
159 /// expanded macro with ArgumentProxies
161 /// macro definition with #1,#2,.. insets
162 MathData definition_;
163 /// number of arguments that were really attached
164 size_t attachedArgsNum_;
165 /// optional argument attached? (only in DISPLAY_NORMAL mode)
167 /// fold mode to be set in next metrics call?
169 /// if macro_ == true, then here is a copy of the macro
170 /// don't use it for locking
171 MacroData macroBackup_;
172 /// if macroNotFound_ == false, then here is a reference to the macro
173 /// this might invalidate after metrics was called
174 MacroData const * macro_;
176 mutable std::map<BufferView const *, bool> editing_;
178 std::string requires_;
179 /// update macro representation
183 /// maximal number of arguments the macro is greedy for
188 void MathMacro::Private::updateChildren(MathMacro * owner)
190 for (size_t i = 0; i < expanded_.size(); ++i) {
191 ArgumentProxy * p = dynamic_cast<ArgumentProxy *>(expanded_[i].nucleus());
196 if (macro_ && lyxrc.preview == LyXRC::PREVIEW_ON) {
197 // We need to update macro_ by ourselves because in this case
198 // MathData::metrics() is not called when selecting a math inset
199 DocIterator const & pos = macroBackup_.pos();
200 Buffer const * buf = pos.buffer();
201 if (buf && !theBufferList().isLoaded(buf))
203 macro_ = buf ? buf->getMacro(owner->name(), pos) : 0;
205 macro_ = ¯oBackup_;
210 MathMacro::MathMacro(Buffer * buf, docstring const & name)
211 : InsetMathNest(buf, 0), d(new Private(buf, name))
215 MathMacro::MathMacro(MathMacro const & that)
216 : InsetMathNest(that), d(new Private(*that.d))
218 d->updateChildren(this);
222 MathMacro & MathMacro::operator=(MathMacro const & that)
226 InsetMathNest::operator=(that);
228 d->updateChildren(this);
233 MathMacro::~MathMacro()
239 Inset * MathMacro::clone() const
241 MathMacro * copy = new MathMacro(*this);
242 copy->d->needsUpdate_ = true;
243 //copy->d->expanded_.clear();
248 void MathMacro::normalize(NormalStream & os) const
250 os << "[macro " << name();
251 for (size_t i = 0; i < nargs(); ++i)
252 os << ' ' << cell(i);
257 MathMacro::DisplayMode MathMacro::displayMode() const
259 return d->displayMode_;
263 bool MathMacro::extraBraces() const
265 return d->displayMode_ == DISPLAY_NORMAL && arity() > 0;
269 docstring MathMacro::name() const
271 if (d->displayMode_ == DISPLAY_UNFOLDED)
272 return asString(cell(0));
278 docstring MathMacro::macroName() const
284 void MathMacro::cursorPos(BufferView const & bv,
285 CursorSlice const & sl, bool boundary, int & x, int & y) const
287 // We may have 0 arguments, but InsetMathNest requires at least one.
289 InsetMathNest::cursorPos(bv, sl, boundary, x, y);
293 bool MathMacro::editMode(BufferView const * bv) const {
294 // find this in cursor trace
295 Cursor const & cur = bv->cursor();
296 for (size_t i = 0; i != cur.depth(); ++i)
297 if (&cur[i].inset() == this) {
298 // look if there is no other macro in edit mode above
300 for (; i != cur.depth(); ++i) {
301 InsetMath * im = cur[i].asInsetMath();
303 MathMacro const * macro = im->asMacro();
304 if (macro && macro->displayMode() == DISPLAY_NORMAL)
309 // ok, none found, I am the highest one
317 MacroData const * MathMacro::macro()
323 bool MathMacro::editMetrics(BufferView const * bv) const
325 return d->editing_[bv];
329 void MathMacro::metrics(MetricsInfo & mi, Dimension & dim) const
331 // set edit mode for which we will have calculated metrics. But only
332 d->editing_[mi.base.bv] = editMode(mi.base.bv);
334 // calculate new metrics according to display mode
335 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
336 mathed_string_dim(mi.base.font, from_ascii("\\") + name(), dim);
337 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
338 cell(0).metrics(mi, dim);
340 mathed_string_dim(mi.base.font, from_ascii("\\"), bsdim);
341 dim.wid += bsdim.width() + 1;
342 dim.asc = max(bsdim.ascent(), dim.ascent());
343 dim.des = max(bsdim.descent(), dim.descent());
345 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
346 && d->editing_[mi.base.bv]) {
347 // Macro will be edited in a old-style list mode here:
351 FontInfo labelFont = sane_font;
352 math_font_max_dim(labelFont, fontDim.asc, fontDim.des);
354 // get dimension of components of list view
356 nameDim.wid = mathed_string_width(mi.base.font, from_ascii("Macro \\") + name() + ": ");
357 nameDim.asc = fontDim.asc;
358 nameDim.des = fontDim.des;
361 argDim.wid = mathed_string_width(labelFont, from_ascii("#9: "));
362 argDim.asc = fontDim.asc;
363 argDim.des = fontDim.des;
366 d->definition_.metrics(mi, defDim);
369 dim.wid = nameDim.wid + defDim.wid;
370 dim.asc = max(nameDim.asc, defDim.asc);
371 dim.des = max(nameDim.des, defDim.des);
373 for (idx_type i = 0; i < nargs(); ++i) {
375 cell(i).metrics(mi, cdim);
376 dim.des += max(argDim.height(), cdim.height()) + 1;
377 dim.wid = max(dim.wid, argDim.wid + cdim.wid);
380 // make space for box and markers, 2 pixels
384 metricsMarkers2(dim);
388 // calculate metrics, hoping that all cells are seen
390 d->expanded_.metrics(mi, dim);
392 // otherwise do a manual metrics call
393 CoordCache & coords = mi.base.bv->coordCache();
394 for (idx_type i = 0; i < nargs(); ++i) {
395 if (!coords.getArrays().hasDim(&cell(i))) {
397 cell(i).metrics(mi, tdim);
402 // calculate dimension with label while editing
403 if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX
404 && d->editing_[mi.base.bv]) {
405 FontInfo font = mi.base.font;
406 augmentFont(font, from_ascii("lyxtex"));
408 mathed_string_dim(font, name(), namedim);
410 dim.wid += 2 + namedim.wid + 2 + 2;
411 dim.asc = max(dim.asc, namedim.asc) + 2;
412 dim.des = max(dim.des, namedim.des) + 2;
414 dim.wid = max(1 + namedim.wid + 1, 2 + dim.wid + 2);
415 dim.asc += 1 + namedim.height() + 1;
422 int MathMacro::kerning(BufferView const * bv) const {
423 if (d->displayMode_ == DISPLAY_NORMAL && !d->editing_[bv])
424 return d->expanded_.kerning(bv);
430 void MathMacro::updateMacro(MacroContext const & mc)
433 d->macro_ = mc.get(name());
434 if (d->macro_ && d->macroBackup_ != *d->macro_) {
435 d->macroBackup_ = *d->macro_;
436 d->needsUpdate_ = true;
444 class MathMacro::UpdateLocker
447 explicit UpdateLocker(MathMacro & mm) : mac(mm)
449 mac.d->isUpdating_ = true;
451 ~UpdateLocker() { mac.d->isUpdating_ = false; }
455 /** Avoid wrong usage of UpdateLocker.
456 To avoid wrong usage:
457 UpdateLocker(...); // wrong
458 UpdateLocker locker(...); // right
460 #define UpdateLocker(x) unnamed_UpdateLocker;
461 // Tip gotten from Bobby Schmidt's column in C/C++ Users Journal
464 void MathMacro::updateRepresentation(Cursor * cur, MacroContext const & mc,
467 // block recursive calls (bug 8999)
471 UpdateLocker locker(*this);
478 d->requires_ = d->macro_->requires();
481 // non-normal mode? We are done!
482 || (d->displayMode_ != DISPLAY_NORMAL))
485 d->needsUpdate_ = false;
487 // get default values of macro
488 vector<docstring> const & defaults = d->macro_->defaults();
490 // create MathMacroArgumentValue objects pointing to the cells of the macro
491 vector<MathData> values(nargs());
492 for (size_t i = 0; i < nargs(); ++i) {
493 ArgumentProxy * proxy;
494 if (i < defaults.size())
495 proxy = new ArgumentProxy(this, i, defaults[i]);
497 proxy = new ArgumentProxy(this, i);
498 values[i].insert(0, MathAtom(proxy));
500 // expanding macro with the values
501 // Only update the argument macros if anything was expanded, otherwise
502 // we would get an endless loop (bug 9140). UpdateLocker does not work
503 // in this case, since MacroData::expand() creates new MathMacro
504 // objects, so this would be a different recursion path than the one
505 // protected by UpdateLocker.
506 if (d->macro_->expand(values, d->expanded_)) {
507 if (utype == OutputUpdate && !d->expanded_.empty())
508 d->expanded_.updateMacros(cur, mc, utype);
510 // get definition for list edit mode
511 docstring const & display = d->macro_->display();
512 asArray(display.empty() ? d->macro_->definition() : display, d->definition_);
516 void MathMacro::draw(PainterInfo & pi, int x, int y) const
518 Dimension const dim = dimension(*pi.base.bv);
520 setPosCache(pi, x, y);
524 if (d->displayMode_ == DISPLAY_INIT || d->displayMode_ == DISPLAY_INTERACTIVE_INIT) {
525 FontSetChanger dummy(pi.base, "lyxtex");
526 pi.pain.text(x, y, from_ascii("\\") + name(), pi.base.font);
527 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
528 FontSetChanger dummy(pi.base, "lyxtex");
529 pi.pain.text(x, y, from_ascii("\\"), pi.base.font);
530 x += mathed_string_width(pi.base.font, from_ascii("\\")) + 1;
531 cell(0).draw(pi, x, y);
532 drawMarkers(pi, expx, expy);
533 } else if (lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_LIST
534 && d->editing_[pi.base.bv]) {
535 // Macro will be edited in a old-style list mode here:
537 CoordCache const & coords = pi.base.bv->coordCache();
538 FontInfo const & labelFont = sane_font;
540 // markers and box needs two pixels
543 // get maximal font height
545 math_font_max_dim(pi.base.font, fontDim.asc, fontDim.des);
548 docstring label = from_ascii("Macro \\") + name() + from_ascii(": ");
549 pi.pain.text(x, y, label, labelFont);
550 x += mathed_string_width(labelFont, label);
553 d->definition_.draw(pi, x, y);
554 Dimension const & defDim = coords.getArrays().dim(&d->definition_);
555 y += max(fontDim.des, defDim.des);
558 docstring str = from_ascii("#9");
559 int strw1 = mathed_string_width(labelFont, from_ascii("#9"));
560 int strw2 = mathed_string_width(labelFont, from_ascii(": "));
562 for (idx_type i = 0; i < nargs(); ++i) {
564 Dimension const & cdim = coords.getArrays().dim(&cell(i));
566 y += max(fontDim.asc, cdim.asc) + 1;
570 pi.pain.text(x, y, str, labelFont);
572 pi.pain.text(x, y, from_ascii(":"), labelFont);
576 cell(i).draw(pi, x, y);
579 y += max(fontDim.des, cdim.des);
582 pi.pain.rectangle(expx + 1, expy - dim.asc + 1, dim.wid - 3,
583 dim.height() - 2, Color_mathmacroframe);
584 drawMarkers2(pi, expx, expy);
586 bool drawBox = lyxrc.macro_edit_style == LyXRC::MACRO_EDIT_INLINE_BOX;
589 for (size_t i = 0; i < nargs(); ++i)
590 cell(i).setXY(*pi.base.bv, x, y);
592 if (drawBox && d->editing_[pi.base.bv]) {
593 // draw header and rectangle around
594 FontInfo font = pi.base.font;
595 augmentFont(font, from_ascii("lyxtex"));
596 font.setSize(FONT_SIZE_TINY);
597 font.setColor(Color_mathmacrolabel);
599 mathed_string_dim(font, name(), namedim);
601 pi.pain.fillRectangle(x, y - dim.asc, dim.wid, 1 + namedim.height() + 1, Color_mathmacrobg);
602 pi.pain.text(x + 1, y - dim.asc + namedim.asc + 2, name(), font);
603 expx += (dim.wid - d->expanded_.dimension(*pi.base.bv).width()) / 2;
606 if (d->editing_[pi.base.bv]) {
607 pi.pain.enterMonochromeMode(Color_mathbg, Color_mathmacroblend);
608 d->expanded_.draw(pi, expx, expy);
609 pi.pain.leaveMonochromeMode();
612 pi.pain.rectangle(x, y - dim.asc, dim.wid,
613 dim.height(), Color_mathmacroframe);
615 d->expanded_.draw(pi, expx, expy);
618 drawMarkers(pi, x, y);
621 // edit mode changed?
622 if (d->editing_[pi.base.bv] != editMode(pi.base.bv))
623 pi.base.bv->cursor().screenUpdateFlags(Update::SinglePar);
627 void MathMacro::drawSelection(PainterInfo & pi, int x, int y) const
629 // We may have 0 arguments, but InsetMathNest requires at least one.
631 InsetMathNest::drawSelection(pi, x, y);
635 void MathMacro::setDisplayMode(MathMacro::DisplayMode mode, int appetite)
637 if (d->displayMode_ != mode) {
638 // transfer name if changing from or to DISPLAY_UNFOLDED
639 if (mode == DISPLAY_UNFOLDED) {
641 asArray(d->name_, cell(0));
642 } else if (d->displayMode_ == DISPLAY_UNFOLDED) {
643 d->name_ = asString(cell(0));
647 d->displayMode_ = mode;
648 d->needsUpdate_ = true;
651 // the interactive init mode is non-greedy by default
653 d->appetite_ = (mode == DISPLAY_INTERACTIVE_INIT) ? 0 : 9;
655 d->appetite_ = size_t(appetite);
659 MathMacro::DisplayMode MathMacro::computeDisplayMode() const
661 if (d->nextFoldMode_ == true && d->macro_ && !d->macro_->locked())
662 return DISPLAY_NORMAL;
664 return DISPLAY_UNFOLDED;
668 bool MathMacro::validName() const
670 docstring n = name();
675 // converting back and force doesn't swallow anything?
678 if (asString(ma) != n)
682 for (size_t i = 0; i<n.size(); ++i) {
683 if (!(n[i] >= 'a' && n[i] <= 'z')
684 && !(n[i] >= 'A' && n[i] <= 'Z')
693 size_t MathMacro::arity() const
695 if (d->displayMode_ == DISPLAY_NORMAL )
696 return cells_.size();
702 size_t MathMacro::optionals() const
704 return d->optionals_;
708 void MathMacro::setOptionals(int n)
710 if (n <= int(nargs()))
715 size_t MathMacro::appetite() const
721 void MathMacro::validate(LaTeXFeatures & features) const
723 // Immediately after a document is loaded, in some cases the MacroData
724 // of the global macros defined in the lib/symbols file may still not
725 // be known to the macro machinery because it will be set only after
726 // the first call to updateMacros(). This is not a problem unless
727 // instant preview is on for math, in which case we will be missing
728 // the corresponding requirements.
729 // In this case, we get the required info from the global macro table.
730 if (!d->requires_.empty())
731 features.require(d->requires_);
732 else if (!d->macro_) {
733 // Update requires for known global macros.
734 MacroData const * data = MacroTable::globalMacros().get(name());
735 if (data && !data->requires().empty())
736 features.require(data->requires());
739 if (name() == "binom")
740 features.require("binom");
742 // validate the cells and the definition
743 if (displayMode() == DISPLAY_NORMAL) {
744 d->definition_.validate(features);
745 InsetMathNest::validate(features);
750 void MathMacro::edit(Cursor & cur, bool front, EntryDirection entry_from)
752 cur.screenUpdateFlags(Update::SinglePar);
753 InsetMathNest::edit(cur, front, entry_from);
757 Inset * MathMacro::editXY(Cursor & cur, int x, int y)
759 // We may have 0 arguments, but InsetMathNest requires at least one.
761 cur.screenUpdateFlags(Update::SinglePar);
762 return InsetMathNest::editXY(cur, x, y);
768 void MathMacro::removeArgument(Inset::pos_type pos) {
769 if (d->displayMode_ == DISPLAY_NORMAL) {
770 LASSERT(size_t(pos) < cells_.size(), return);
771 cells_.erase(cells_.begin() + pos);
772 if (size_t(pos) < d->attachedArgsNum_)
773 --d->attachedArgsNum_;
774 if (size_t(pos) < d->optionals_) {
778 d->needsUpdate_ = true;
783 void MathMacro::insertArgument(Inset::pos_type pos) {
784 if (d->displayMode_ == DISPLAY_NORMAL) {
785 LASSERT(size_t(pos) <= cells_.size(), return);
786 cells_.insert(cells_.begin() + pos, MathData());
787 if (size_t(pos) < d->attachedArgsNum_)
788 ++d->attachedArgsNum_;
789 if (size_t(pos) < d->optionals_)
792 d->needsUpdate_ = true;
797 void MathMacro::detachArguments(vector<MathData> & args, bool strip)
799 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
802 // strip off empty cells, but not more than arity-attachedArgsNum_
805 for (i = cells_.size(); i > d->attachedArgsNum_; --i)
806 if (!cell(i - 1).empty()) break;
810 d->attachedArgsNum_ = 0;
811 d->expanded_ = MathData();
814 d->needsUpdate_ = true;
818 void MathMacro::attachArguments(vector<MathData> const & args, size_t arity, int optionals)
820 LASSERT(d->displayMode_ == DISPLAY_NORMAL, return);
822 d->attachedArgsNum_ = args.size();
823 cells_.resize(arity);
824 d->expanded_ = MathData();
825 d->optionals_ = optionals;
827 d->needsUpdate_ = true;
831 bool MathMacro::idxFirst(Cursor & cur) const
833 cur.screenUpdateFlags(Update::SinglePar);
834 return InsetMathNest::idxFirst(cur);
838 bool MathMacro::idxLast(Cursor & cur) const
840 cur.screenUpdateFlags(Update::SinglePar);
841 return InsetMathNest::idxLast(cur);
845 bool MathMacro::notifyCursorLeaves(Cursor const & old, Cursor & cur)
847 if (d->displayMode_ == DISPLAY_UNFOLDED) {
848 docstring const & unfolded_name = name();
849 if (unfolded_name != d->name_) {
850 // The macro name was changed
851 Cursor inset_cursor = old;
852 int macroSlice = inset_cursor.find(this);
853 // returning true means the cursor is "now" invalid,
855 LASSERT(macroSlice != -1, return true);
856 inset_cursor.cutOff(macroSlice);
857 inset_cursor.recordUndoInset();
859 inset_cursor.cell().erase(inset_cursor.pos());
860 inset_cursor.cell().insert(inset_cursor.pos(),
861 createInsetMath(unfolded_name, cur.buffer()));
863 cur.screenUpdateFlags(cur.result().screenUpdate() | Update::SinglePar);
867 cur.screenUpdateFlags(Update::Force);
868 return InsetMathNest::notifyCursorLeaves(old, cur);
872 void MathMacro::fold(Cursor & cur)
874 if (!d->nextFoldMode_) {
875 d->nextFoldMode_ = true;
876 cur.screenUpdateFlags(Update::SinglePar);
881 void MathMacro::unfold(Cursor & cur)
883 if (d->nextFoldMode_) {
884 d->nextFoldMode_ = false;
885 cur.screenUpdateFlags(Update::SinglePar);
890 bool MathMacro::folded() const
892 return d->nextFoldMode_;
896 void MathMacro::write(WriteStream & os) const
898 MathEnsurer ensurer(os, d->macro_ != 0, true);
901 if (d->displayMode_ != DISPLAY_NORMAL) {
902 os << "\\" << name();
903 if (name().size() != 1 || isAlphaASCII(name()[0]))
904 os.pendingSpace(true);
909 // we should be ok to continue even if this fails.
912 // Always protect macros in a fragile environment
916 os << "\\" << name();
919 // Optional arguments:
920 // First find last non-empty optional argument
921 idx_type emptyOptFrom = 0;
923 for (; i < cells_.size() && i < d->optionals_; ++i) {
924 if (!cell(i).empty())
925 emptyOptFrom = i + 1;
928 // print out optionals
929 for (i=0; i < cells_.size() && i < emptyOptFrom; ++i) {
931 os << "[" << cell(i) << "]";
934 // skip the tailing empty optionals
937 // Print remaining arguments
938 for (; i < cells_.size(); ++i) {
939 if (cell(i).size() == 1
940 && cell(i)[0].nucleus()->asCharInset()
941 && isASCII(cell(i)[0].nucleus()->asCharInset()->getChar())) {
946 os << "{" << cell(i) << "}";
950 // add space if there was no argument
952 os.pendingSpace(true);
956 void MathMacro::maple(MapleStream & os) const
958 lyx::maple(d->expanded_, os);
962 void MathMacro::maxima(MaximaStream & os) const
964 lyx::maxima(d->expanded_, os);
968 void MathMacro::mathematica(MathematicaStream & os) const
970 lyx::mathematica(d->expanded_, os);
974 void MathMacro::mathmlize(MathStream & os) const
976 // macro_ is 0 if this is an unknown macro
977 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
979 docstring const xmlname = d->macro_->xmlname();
980 if (!xmlname.empty()) {
981 char const * type = d->macro_->MathMLtype();
982 os << '<' << type << "> " << xmlname << " /<"
987 if (d->expanded_.empty()) {
988 // this means that we do not recognize the macro
989 throw MathExportException();
995 void MathMacro::htmlize(HtmlStream & os) const
997 // macro_ is 0 if this is an unknown macro
998 LATTEST(d->macro_ || d->displayMode_ != DISPLAY_NORMAL);
1000 docstring const xmlname = d->macro_->xmlname();
1001 if (!xmlname.empty()) {
1002 os << ' ' << xmlname << ' ';
1006 if (d->expanded_.empty()) {
1007 // this means that we do not recognize the macro
1008 throw MathExportException();
1014 void MathMacro::octave(OctaveStream & os) const
1016 lyx::octave(d->expanded_, os);
1020 void MathMacro::infoize(odocstream & os) const
1022 os << bformat(_("Macro: %1$s"), name());
1026 void MathMacro::infoize2(odocstream & os) const
1028 os << bformat(_("Macro: %1$s"), name());
1032 bool MathMacro::completionSupported(Cursor const & cur) const
1034 if (displayMode() != DISPLAY_UNFOLDED)
1035 return InsetMathNest::completionSupported(cur);
1037 return lyxrc.completion_popup_math
1038 && displayMode() == DISPLAY_UNFOLDED
1039 && cur.bv().cursor().pos() == int(name().size());
1043 bool MathMacro::inlineCompletionSupported(Cursor const & cur) const
1045 if (displayMode() != DISPLAY_UNFOLDED)
1046 return InsetMathNest::inlineCompletionSupported(cur);
1048 return lyxrc.completion_inline_math
1049 && displayMode() == DISPLAY_UNFOLDED
1050 && cur.bv().cursor().pos() == int(name().size());
1054 bool MathMacro::automaticInlineCompletion() const
1056 if (displayMode() != DISPLAY_UNFOLDED)
1057 return InsetMathNest::automaticInlineCompletion();
1059 return lyxrc.completion_inline_math;
1063 bool MathMacro::automaticPopupCompletion() const
1065 if (displayMode() != DISPLAY_UNFOLDED)
1066 return InsetMathNest::automaticPopupCompletion();
1068 return lyxrc.completion_popup_math;
1072 CompletionList const *
1073 MathMacro::createCompletionList(Cursor const & cur) const
1075 if (displayMode() != DISPLAY_UNFOLDED)
1076 return InsetMathNest::createCompletionList(cur);
1078 return new MathCompletionList(cur.bv().cursor());
1082 docstring MathMacro::completionPrefix(Cursor const & cur) const
1084 if (displayMode() != DISPLAY_UNFOLDED)
1085 return InsetMathNest::completionPrefix(cur);
1087 if (!completionSupported(cur))
1090 return "\\" + name();
1094 bool MathMacro::insertCompletion(Cursor & cur, docstring const & s,
1097 if (displayMode() != DISPLAY_UNFOLDED)
1098 return InsetMathNest::insertCompletion(cur, s, finished);
1100 if (!completionSupported(cur))
1103 // append completion
1104 docstring newName = name() + s;
1105 asArray(newName, cell(0));
1106 cur.bv().cursor().pos() = name().size();
1107 cur.screenUpdateFlags(Update::SinglePar);
1111 cur.bv().cursor().pop();
1112 ++cur.bv().cursor().pos();
1113 cur.screenUpdateFlags(Update::SinglePar);
1120 void MathMacro::completionPosAndDim(Cursor const & cur, int & x, int & y,
1121 Dimension & dim) const
1123 if (displayMode() != DISPLAY_UNFOLDED)
1124 InsetMathNest::completionPosAndDim(cur, x, y, dim);
1126 // get inset dimensions
1127 dim = cur.bv().coordCache().insets().dim(this);
1128 // FIXME: these 3 are no accurate, but should depend on the font.
1129 // Now the popup jumps down if you enter a char with descent > 0.
1135 = cur.bv().coordCache().insets().xy(this);