2 * \file InsetMathNest.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathNest.h"
15 #include "InsetMathArray.h"
16 #include "InsetMathAMSArray.h"
17 #include "InsetMathBig.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathBrace.h"
20 #include "InsetMathChar.h"
21 #include "InsetMathColor.h"
22 #include "InsetMathComment.h"
23 #include "InsetMathDelim.h"
24 #include "InsetMathEnsureMath.h"
25 #include "InsetMathHull.h"
26 #include "InsetMathRef.h"
27 #include "InsetMathScript.h"
28 #include "InsetMathSpace.h"
29 #include "InsetMathSymbol.h"
30 #include "InsetMathUnknown.h"
31 #include "MathAutoCorrect.h"
32 #include "MathCompletionList.h"
34 #include "MathFactory.h"
35 #include "MathMacro.h"
36 #include "MathMacroArgument.h"
37 #include "MathParser.h"
38 #include "MathStream.h"
39 #include "MathSupport.h"
43 #include "BufferView.h"
44 #include "CoordCache.h"
46 #include "CutAndPaste.h"
47 #include "DispatchResult.h"
49 #include "FuncRequest.h"
50 #include "FuncStatus.h"
53 #include "OutputParams.h"
56 #include "frontends/Clipboard.h"
57 #include "frontends/Painter.h"
58 #include "frontends/Selection.h"
60 #include "support/lassert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
65 #include "support/docstream.h"
71 using namespace lyx::support;
75 using cap::copySelection;
76 using cap::grabAndEraseSelection;
77 using cap::cutSelection;
78 using cap::replaceSelection;
79 using cap::selClearOrDel;
82 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
83 : InsetMath(buf), cells_(nargs), lock_(false)
89 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
90 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
94 InsetMathNest::~InsetMathNest()
96 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
97 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
98 for (; it != end; ++it)
100 it->first->clearLastInset(this);
104 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
106 cells_ = inset.cells_;
108 mouse_hover_.clear();
109 InsetMath::operator=(inset);
114 void InsetMathNest::setBuffer(Buffer & buffer)
116 InsetMath::setBuffer(buffer);
117 for (idx_type i = 0, n = nargs(); i != n; ++i) {
118 MathData & data = cell(i);
119 for (size_t j = 0; j != data.size(); ++j)
120 data[j].nucleus()->setBuffer(buffer);
125 InsetMath::idx_type InsetMathNest::nargs() const
127 return cells_.size();
131 void InsetMathNest::cursorPos(BufferView const & bv,
132 CursorSlice const & sl, bool /*boundary*/,
133 int & x, int & y) const
135 // FIXME: This is a hack. Ideally, the coord cache should not store
136 // absolute positions, but relative ones. This would mean to call
137 // setXY() not in MathData::draw(), but in the parent insets' draw()
138 // with the correctly adjusted x,y values. But this means that we'd have
139 // to touch all (math)inset's draw() methods. Right now, we'll store
140 // absolute value, and make them here relative, only to make them
141 // absolute again when actually drawing the cursor. What a mess.
142 LASSERT(&sl.inset() == this, /**/);
143 MathData const & ar = sl.cell();
144 CoordCache const & coord_cache = bv.coordCache();
145 if (!coord_cache.getArrays().has(&ar)) {
146 // this can (semi-)legally happen if we just created this cell
147 // and it never has been drawn before. So don't ASSERT.
148 //lyxerr << "no cached data for array " << &ar << endl;
153 Point const pt = coord_cache.getArrays().xy(&ar);
154 if (!coord_cache.getInsets().has(this)) {
156 //lyxerr << "no cached data for inset " << this << endl;
161 Point const pt2 = coord_cache.getInsets().xy(this);
162 //lyxerr << "retrieving position cache for MathData "
163 // << pt.x_ << ' ' << pt.y_ << endl;
164 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
166 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
167 // << " asc: " << ascent() << " des: " << descent()
168 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
169 // move cursor visually into empty cells ("blue rectangles");
175 void InsetMathNest::metrics(MetricsInfo const & mi) const
178 for (idx_type i = 0, n = nargs(); i != n; ++i) {
180 cell(i).metrics(m, dim);
185 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
187 for (idx_type i = 0, n = nargs(); i != n; ++i)
188 cell(i).updateBuffer(it, utype);
193 bool InsetMathNest::idxNext(Cursor & cur) const
195 LASSERT(&cur.inset() == this, /**/);
196 if (cur.idx() == cur.lastidx())
204 bool InsetMathNest::idxForward(Cursor & cur) const
210 bool InsetMathNest::idxPrev(Cursor & cur) const
212 LASSERT(&cur.inset() == this, /**/);
216 cur.pos() = cur.lastpos();
221 bool InsetMathNest::idxBackward(Cursor & cur) const
227 bool InsetMathNest::idxFirst(Cursor & cur) const
229 LASSERT(&cur.inset() == this, /**/);
238 bool InsetMathNest::idxLast(Cursor & cur) const
240 LASSERT(&cur.inset() == this, /**/);
243 cur.idx() = cur.lastidx();
244 cur.pos() = cur.lastpos();
249 void InsetMathNest::dump() const
251 odocstringstream oss;
253 os << "---------------------------------------------\n";
256 for (idx_type i = 0, n = nargs(); i != n; ++i)
257 os << cell(i) << "\n";
258 os << "---------------------------------------------\n";
259 lyxerr << to_utf8(oss.str());
263 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
267 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
270 setPosCache(pi, x, y);
274 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
276 BufferView & bv = *pi.base.bv;
277 // this should use the x/y values given, not the cached values
278 Cursor & cur = bv.cursor();
279 if (!cur.selection())
281 if (&cur.inset() != this)
284 // FIXME: hack to get position cache warm
285 bool const original_drawing_state = pi.pain.isDrawingEnabled();
286 pi.pain.setDrawingEnabled(false);
288 pi.pain.setDrawingEnabled(original_drawing_state);
290 CursorSlice s1 = cur.selBegin();
291 CursorSlice s2 = cur.selEnd();
293 //lyxerr << "InsetMathNest::drawing selection: "
294 // << " s1: " << s1 << " s2: " << s2 << endl;
295 if (s1.idx() == s2.idx()) {
296 MathData const & c = cell(s1.idx());
297 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
298 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
299 int y1 = g.pos.y_ - g.dim.ascent();
300 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
301 int y2 = g.pos.y_ + g.dim.descent();
302 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
303 //lyxerr << "InsetMathNest::drawing selection 3: "
304 // << " x1: " << x1 << " x2: " << x2
305 // << " y1: " << y1 << " y2: " << y2 << endl;
307 for (idx_type i = 0; i < nargs(); ++i) {
308 if (idxBetween(i, s1.idx(), s2.idx())) {
309 MathData const & c = cell(i);
310 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
312 int y1 = g.pos.y_ - g.dim.ascent();
313 int x2 = g.pos.x_ + g.dim.width();
314 int y2 = g.pos.y_ + g.dim.descent();
315 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
322 void InsetMathNest::validate(LaTeXFeatures & features) const
324 for (idx_type i = 0; i < nargs(); ++i)
325 cell(i).validate(features);
329 void InsetMathNest::replace(ReplaceData & rep)
331 for (idx_type i = 0; i < nargs(); ++i)
332 cell(i).replace(rep);
336 bool InsetMathNest::contains(MathData const & ar) const
338 for (idx_type i = 0; i < nargs(); ++i)
339 if (cell(i).contains(ar))
345 bool InsetMathNest::lock() const
351 void InsetMathNest::lock(bool l)
357 bool InsetMathNest::isActive() const
363 MathData InsetMathNest::glue() const
366 for (size_t i = 0; i < nargs(); ++i)
372 void InsetMathNest::write(WriteStream & os) const
374 ModeSpecifier specifier(os, currentMode(), lockedMode());
375 docstring const latex_name = name();
376 os << '\\' << latex_name;
377 for (size_t i = 0; i < nargs(); ++i)
378 os << '{' << cell(i) << '}';
380 os.pendingSpace(true);
381 if (lock_ && !os.latex()) {
383 os.pendingSpace(true);
388 void InsetMathNest::normalize(NormalStream & os) const
391 for (size_t i = 0; i < nargs(); ++i)
392 os << ' ' << cell(i);
397 int InsetMathNest::latex(odocstream & os, OutputParams const & runparams) const
399 WriteStream wi(os, runparams.moving_arg, true,
400 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
407 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
409 mouse_hover_[bv] = mouse_hover;
414 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
418 MathData & ar = cur.cell();
419 // remove base-only "scripts"
420 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
421 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
422 if (p && p->nargs() == 1) {
423 MathData ar = p->nuc();
426 cur.adjust(i, ar.size() - 1);
430 // glue adjacent font insets of the same kind
431 for (pos_type i = 0; i + 1 < size(); ++i) {
432 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
433 InsetMathFont const * q = operator[](i + 1)->asFontInset();
434 if (p && q && p->name() == q->name()) {
435 p->cell(0).append(q->cell(0));
445 void InsetMathNest::handleFont
446 (Cursor & cur, docstring const & arg, char const * const font)
448 handleFont(cur, arg, from_ascii(font));
452 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
453 docstring const & font)
455 cur.recordUndoSelection();
457 // this whole function is a hack and won't work for incremental font
459 if (cur.inset().asInsetMath()->name() == font)
460 cur.handleFont(to_utf8(font));
462 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
466 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
468 handleNest(cur, nest, docstring());
472 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
473 docstring const & arg)
475 CursorSlice i1 = cur.selBegin();
476 CursorSlice i2 = cur.selEnd();
477 if (!i1.inset().asInsetMath())
479 if (i1.idx() == i2.idx()) {
480 // the easy case where only one cell is selected
481 cur.handleNest(nest);
486 // multiple selected cells in a simple non-grid inset
487 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
488 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
493 cur.pos() = cur.lastpos();
496 // change font of cell
497 cur.handleNest(nest);
500 // cur is in the font inset now. If the loop continues,
501 // we need to get outside again for the next cell
502 if (i + 1 <= i2.idx())
508 // the complicated case with multiple selected cells in a grid
511 cap::region(i1, i2, r1, r2, c1, c2);
512 for (row_type row = r1; row <= r2; ++row) {
513 for (col_type col = c1; col <= c2; ++col) {
515 cur.idx() = i1.asInsetMath()->index(row, col);
518 cur.pos() = cur.lastpos();
522 cur.handleNest(nest);
525 // cur is in the font inset now. If the loop continues,
526 // we need to get outside again for the next cell
527 if (col + 1 <= c2 || row + 1 <= r2)
534 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
536 cur.recordUndoSelection();
539 font.fromString(to_utf8(arg), b);
540 if (font.fontInfo().color() != Color_inherit &&
541 font.fontInfo().color() != Color_ignore)
542 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
544 // FIXME: support other font changes here as well?
548 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
550 //LYXERR0("InsetMathNest: request: " << cmd);
552 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
554 FuncCode const act = cmd.action();
557 case LFUN_CLIPBOARD_PASTE:
558 parseflg |= Parse::VERBATIM;
561 if (cur.currentMode() <= TEXT_MODE)
562 parseflg |= Parse::TEXTMODE;
563 cur.recordUndoSelection();
564 cur.message(_("Paste"));
565 replaceSelection(cur);
567 if (cmd.argument().empty() && !theClipboard().isInternal())
568 topaste = theClipboard().getAsText();
571 idocstringstream is(cmd.argument());
573 topaste = cap::selection(n);
575 cur.niceInsert(topaste, parseflg, false);
576 cur.clearSelection(); // bug 393
577 // FIXME audit setBuffer/updateBuffer calls
578 cur.buffer()->updateBuffer();
585 cutSelection(cur, true, true);
586 cur.message(_("Cut"));
587 // Prevent stale position >= size crash
588 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
590 // FIXME audit setBuffer/updateBuffer calls
591 cur.buffer()->updateBuffer();
596 cur.message(_("Copy"));
599 case LFUN_MOUSE_PRESS:
600 lfunMousePress(cur, cmd);
603 case LFUN_MOUSE_MOTION:
604 lfunMouseMotion(cur, cmd);
607 case LFUN_MOUSE_RELEASE:
608 lfunMouseRelease(cur, cmd);
611 case LFUN_FINISHED_LEFT: // in math, left is backwards
612 case LFUN_FINISHED_BACKWARD:
613 cur.bv().cursor() = cur;
616 case LFUN_FINISHED_RIGHT: // in math, right is forward
617 case LFUN_FINISHED_FORWARD:
619 cur.bv().cursor() = cur;
622 case LFUN_CHAR_RIGHT:
624 case LFUN_CHAR_BACKWARD:
625 case LFUN_CHAR_FORWARD:
626 cur.updateFlags(Update::Decoration | Update::FitCursor);
627 case LFUN_CHAR_RIGHT_SELECT:
628 case LFUN_CHAR_LEFT_SELECT:
629 case LFUN_CHAR_BACKWARD_SELECT:
630 case LFUN_CHAR_FORWARD_SELECT: {
631 // are we in a selection?
632 bool select = (act == LFUN_CHAR_RIGHT_SELECT
633 || act == LFUN_CHAR_LEFT_SELECT
634 || act == LFUN_CHAR_BACKWARD_SELECT
635 || act == LFUN_CHAR_FORWARD_SELECT);
636 // are we moving forward or backwards?
637 // If the command was RIGHT or LEFT, then whether we're moving forward
638 // or backwards depends on the cursor movement mode (logical or visual):
639 // * in visual mode, since math is always LTR, right -> forward,
641 // * in logical mode, the mapping is determined by the
642 // reverseDirectionNeeded() function
645 FuncCode finish_lfun;
647 if (act == LFUN_CHAR_FORWARD
648 || act == LFUN_CHAR_FORWARD_SELECT) {
650 finish_lfun = LFUN_FINISHED_FORWARD;
652 else if (act == LFUN_CHAR_BACKWARD
653 || act == LFUN_CHAR_BACKWARD_SELECT) {
655 finish_lfun = LFUN_FINISHED_BACKWARD;
658 bool right = (act == LFUN_CHAR_RIGHT_SELECT
659 || act == LFUN_CHAR_RIGHT);
660 if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
666 finish_lfun = LFUN_FINISHED_RIGHT;
668 finish_lfun = LFUN_FINISHED_LEFT;
670 // Now that we know exactly what we want to do, let's do it!
671 cur.selHandle(select);
673 cur.macroModeClose();
674 // try moving forward or backwards as necessary...
675 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
676 // ... and if movement failed, then finish forward or backwards
678 cmd = FuncRequest(finish_lfun);
686 cur.updateFlags(Update::Decoration | Update::FitCursor);
687 case LFUN_DOWN_SELECT:
688 case LFUN_UP_SELECT: {
689 // close active macro
690 if (cur.inMacroMode()) {
691 cur.macroModeClose();
695 // stop/start the selection
696 bool select = act == LFUN_DOWN_SELECT ||
697 act == LFUN_UP_SELECT;
698 cur.selHandle(select);
701 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
702 bool successful = cur.upDownInMath(up);
706 if (cur.fixIfBroken())
707 // FIXME: Something bad happened. We pass the corrected Cursor
708 // instead of letting things go worse.
711 // We did not manage to move the cursor.
716 case LFUN_MOUSE_DOUBLE:
717 case LFUN_MOUSE_TRIPLE:
718 case LFUN_WORD_SELECT:
722 cur.setSelection(true);
723 cur.pos() = cur.lastpos();
724 cur.idx() = cur.lastidx();
727 case LFUN_PARAGRAPH_UP:
728 case LFUN_PARAGRAPH_DOWN:
729 cur.updateFlags(Update::Decoration | Update::FitCursor);
730 case LFUN_PARAGRAPH_UP_SELECT:
731 case LFUN_PARAGRAPH_DOWN_SELECT:
734 case LFUN_LINE_BEGIN:
735 case LFUN_WORD_BACKWARD:
737 cur.updateFlags(Update::Decoration | Update::FitCursor);
738 case LFUN_LINE_BEGIN_SELECT:
739 case LFUN_WORD_BACKWARD_SELECT:
740 case LFUN_WORD_LEFT_SELECT:
741 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
742 act == LFUN_WORD_LEFT_SELECT ||
743 act == LFUN_LINE_BEGIN_SELECT);
744 cur.macroModeClose();
745 if (cur.pos() != 0) {
747 } else if (cur.col() != 0) {
748 cur.idx() -= cur.col();
750 } else if (cur.idx() != 0) {
754 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
759 case LFUN_WORD_FORWARD:
760 case LFUN_WORD_RIGHT:
762 cur.updateFlags(Update::Decoration | Update::FitCursor);
763 case LFUN_WORD_FORWARD_SELECT:
764 case LFUN_WORD_RIGHT_SELECT:
765 case LFUN_LINE_END_SELECT:
766 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
767 act == LFUN_WORD_RIGHT_SELECT ||
768 act == LFUN_LINE_END_SELECT);
769 cur.macroModeClose();
771 if (cur.pos() != cur.lastpos()) {
772 cur.pos() = cur.lastpos();
773 } else if (ncols() && (cur.col() != cur.lastcol())) {
774 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
775 cur.pos() = cur.lastpos();
776 } else if (cur.idx() != cur.lastidx()) {
777 cur.idx() = cur.lastidx();
778 cur.pos() = cur.lastpos();
780 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
785 case LFUN_CELL_FORWARD:
786 cur.updateFlags(Update::Decoration | Update::FitCursor);
787 cur.inset().idxNext(cur);
790 case LFUN_CELL_BACKWARD:
791 cur.updateFlags(Update::Decoration | Update::FitCursor);
792 cur.inset().idxPrev(cur);
795 case LFUN_WORD_DELETE_BACKWARD:
796 case LFUN_CHAR_DELETE_BACKWARD:
798 // May affect external cell:
799 cur.recordUndoInset();
801 cur.recordUndoSelection();
802 // if the inset can not be removed from within, delete it
803 if (!cur.backspace()) {
804 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
805 cur.innerText()->dispatch(cur, cmd);
809 case LFUN_WORD_DELETE_FORWARD:
810 case LFUN_CHAR_DELETE_FORWARD:
811 if (cur.pos() == cur.lastpos())
812 // May affect external cell:
813 cur.recordUndoInset();
815 cur.recordUndoSelection();
816 // if the inset can not be removed from within, delete it
818 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
819 cur.innerText()->dispatch(cur, cmd);
825 cur.clearSelection();
827 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
832 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
833 // that is traversed by a single <CursorLeft>/<CursorRight>.
834 case LFUN_INSET_TOGGLE:
840 case LFUN_SELF_INSERT:
841 if (cmd.argument().size() != 1) {
842 cur.recordUndoSelection();
843 docstring const arg = cmd.argument();
844 if (!interpretString(cur, arg))
848 // Don't record undo steps if we are in macro mode and thus
849 // cmd.argument is the next character of the macro name.
850 // Otherwise we'll get an invalid cursor if we undo after
851 // the macro was finished and the macro is a known command,
852 // e.g. sqrt. Cursor::macroModeClose replaces in this case
853 // the InsetMathUnknown with name "frac" by an empty
854 // InsetMathFrac -> a pos value > 0 is invalid.
855 // A side effect is that an undo before the macro is finished
856 // undoes the complete macro, not only the last character.
857 // At the time we hit '\' we are not in macro mode, still.
858 if (!cur.inMacroMode())
859 cur.recordUndoSelection();
861 // spacial handling of space. If we insert an inset
862 // via macro mode, we want to put the cursor inside it
863 // if relevant. Think typing "\frac<space>".
864 if (cmd.argument()[0] == ' '
865 && cur.inMacroMode() && cur.macroName() != "\\"
866 && cur.macroModeClose()) {
867 MathAtom const atom = cur.prevAtom();
868 if (atom->asNestInset() && atom->isActive()) {
870 cur.pushBackward(*cur.nextInset());
872 } else if (!interpretChar(cur, cmd.argument()[0])) {
873 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
878 //case LFUN_SERVER_GET_XY:
881 case LFUN_SERVER_SET_XY: {
882 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
885 istringstream is(to_utf8(cmd.argument()));
887 cur.setScreenPos(x, y);
891 // Special casing for superscript in case of LyX handling
893 case LFUN_ACCENT_CIRCUMFLEX:
894 if (cmd.argument().empty()) {
895 // do superscript if LyX handles
897 cur.recordUndoSelection();
898 script(cur, true, grabAndEraseSelection(cur));
902 case LFUN_ACCENT_UMLAUT:
903 case LFUN_ACCENT_ACUTE:
904 case LFUN_ACCENT_GRAVE:
905 case LFUN_ACCENT_BREVE:
906 case LFUN_ACCENT_DOT:
907 case LFUN_ACCENT_MACRON:
908 case LFUN_ACCENT_CARON:
909 case LFUN_ACCENT_TILDE:
910 case LFUN_ACCENT_CEDILLA:
911 case LFUN_ACCENT_CIRCLE:
912 case LFUN_ACCENT_UNDERDOT:
913 case LFUN_ACCENT_TIE:
914 case LFUN_ACCENT_OGONEK:
915 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
919 case LFUN_TEXTSTYLE_APPLY:
920 case LFUN_TEXTSTYLE_UPDATE:
921 handleFont2(cur, cmd.argument());
925 if (currentMode() <= TEXT_MODE)
926 handleFont(cur, cmd.argument(), "textbf");
928 handleFont(cur, cmd.argument(), "mathbf");
930 case LFUN_FONT_BOLDSYMBOL:
931 if (currentMode() <= TEXT_MODE)
932 handleFont(cur, cmd.argument(), "textbf");
934 handleFont(cur, cmd.argument(), "boldsymbol");
937 if (currentMode() <= TEXT_MODE)
938 handleFont(cur, cmd.argument(), "textsf");
940 handleFont(cur, cmd.argument(), "mathsf");
943 if (currentMode() <= TEXT_MODE)
944 handleFont(cur, cmd.argument(), "emph");
946 handleFont(cur, cmd.argument(), "mathcal");
948 case LFUN_FONT_ROMAN:
949 if (currentMode() <= TEXT_MODE)
950 handleFont(cur, cmd.argument(), "textrm");
952 handleFont(cur, cmd.argument(), "mathrm");
954 case LFUN_FONT_TYPEWRITER:
955 if (currentMode() <= TEXT_MODE)
956 handleFont(cur, cmd.argument(), "texttt");
958 handleFont(cur, cmd.argument(), "mathtt");
961 handleFont(cur, cmd.argument(), "mathfrak");
964 if (currentMode() <= TEXT_MODE)
965 handleFont(cur, cmd.argument(), "textit");
967 handleFont(cur, cmd.argument(), "mathit");
970 if (currentMode() <= TEXT_MODE)
971 // FIXME: should be "noun"
972 handleFont(cur, cmd.argument(), "textsc");
974 handleFont(cur, cmd.argument(), "mathbb");
976 case LFUN_FONT_DEFAULT:
977 handleFont(cur, cmd.argument(), "textnormal");
980 case LFUN_FONT_UNDERLINE:
982 cur.handleNest(createInsetMath("underline", cur.buffer()));
984 case LFUN_MATH_MODE: {
986 // ignore math-mode on when already in math mode
987 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
989 cur.recordUndoSelection();
990 cur.macroModeClose();
991 docstring const save_selection = grabAndEraseSelection(cur);
993 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
994 if (currentMode() <= Inset::TEXT_MODE)
995 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
997 cur.plainInsert(MathAtom(new InsetMathBox(buffer_, from_ascii("mbox"))));
999 cur.pushBackward(*cur.nextInset());
1000 cur.niceInsert(save_selection);
1001 // FIXME audit setBuffer/updateBuffer calls
1002 cur.buffer()->updateBuffer();
1004 if (currentMode() == Inset::TEXT_MODE) {
1005 cur.recordUndoSelection();
1006 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1007 cur.message(_("create new math text environment ($...$)"));
1009 handleFont(cur, cmd.argument(), "textrm");
1010 cur.message(_("entered math text mode (textrm)"));
1016 case LFUN_REGEXP_MODE: {
1017 InsetMathHull * i = dynamic_cast<InsetMathHull *>(cur.inset().asInsetMath());
1018 if (i && i->getType() == hullRegexp) {
1019 cur.message(_("Already in regular expression mode"));
1022 cur.macroModeClose();
1023 docstring const save_selection = grabAndEraseSelection(cur);
1025 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1027 cur.pushBackward(*cur.nextInset());
1028 cur.niceInsert(save_selection);
1029 cur.message(_("Regular expression editor mode"));
1033 case LFUN_MATH_FONT_STYLE: {
1034 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1035 doDispatch(cur, fr);
1039 case LFUN_MATH_SIZE: {
1040 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1041 doDispatch(cur, fr);
1045 case LFUN_MATH_MATRIX: {
1051 idocstringstream is(cmd.argument());
1052 is >> m >> n >> v_align >> h_align;
1058 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1059 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1063 case LFUN_MATH_AMS_MATRIX: {
1068 idocstringstream is(cmd.argument());
1069 is >> m >> n >> name;
1075 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1079 case LFUN_MATH_DELIM: {
1081 docstring rs = split(cmd.argument(), ls, ' ');
1082 // Reasonable default values
1088 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1092 case LFUN_MATH_BIGDELIM: {
1093 docstring const lname = from_utf8(cmd.getArg(0));
1094 docstring const ldelim = from_utf8(cmd.getArg(1));
1095 docstring const rname = from_utf8(cmd.getArg(2));
1096 docstring const rdelim = from_utf8(cmd.getArg(3));
1097 latexkeys const * l = in_word_set(lname);
1098 bool const have_l = l && l->inset == "big" &&
1099 InsetMathBig::isBigInsetDelim(ldelim);
1100 l = in_word_set(rname);
1101 bool const have_r = l && l->inset == "big" &&
1102 InsetMathBig::isBigInsetDelim(rdelim);
1103 // We mimic LFUN_MATH_DELIM in case we have an empty left
1104 // or right delimiter.
1105 if (have_l || have_r) {
1107 docstring const selection = grabAndEraseSelection(cur);
1110 cur.insert(MathAtom(new InsetMathBig(lname,
1112 cur.niceInsert(selection);
1114 cur.insert(MathAtom(new InsetMathBig(rname,
1117 // Don't call cur.undispatched() if we did nothing, this would
1118 // lead to infinite recursion via Text::dispatch().
1122 case LFUN_SPACE_INSERT:
1123 cur.recordUndoSelection();
1124 cur.insert(MathAtom(new InsetMathSpace));
1127 case LFUN_MATH_SPACE:
1128 cur.recordUndoSelection();
1129 if (cmd.argument().empty())
1130 cur.insert(MathAtom(new InsetMathSpace));
1132 string const name = cmd.getArg(0);
1133 string const len = cmd.getArg(1);
1134 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1138 case LFUN_ERT_INSERT:
1139 // interpret this as if a backslash was typed
1141 interpretChar(cur, '\\');
1144 case LFUN_MATH_SUBSCRIPT:
1145 // interpret this as if a _ was typed
1146 cur.recordUndoSelection();
1147 interpretChar(cur, '_');
1150 case LFUN_MATH_SUPERSCRIPT:
1151 // interpret this as if a ^ was typed
1152 cur.recordUndoSelection();
1153 interpretChar(cur, '^');
1156 case LFUN_MATH_MACRO_FOLD:
1157 case LFUN_MATH_MACRO_UNFOLD: {
1159 bool fold = act == LFUN_MATH_MACRO_FOLD;
1160 bool found = findMacroToFoldUnfold(it, fold);
1162 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1163 cur.recordUndoInset();
1172 case LFUN_QUOTE_INSERT:
1173 // interpret this as if a straight " was typed
1174 cur.recordUndoSelection();
1175 interpretChar(cur, '\"');
1178 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1179 // handling such that "self-insert" works on "arbitrary stuff" too, and
1180 // math-insert only handles special math things like "matrix".
1181 case LFUN_MATH_INSERT: {
1182 cur.recordUndoSelection();
1183 if (cmd.argument() == "^" || cmd.argument() == "_")
1184 interpretChar(cur, cmd.argument()[0]);
1187 asArray(cmd.argument(), ar);
1188 if (cur.selection() && ar.size() == 1
1189 && ar[0]->asNestInset()
1190 && ar[0]->asNestInset()->nargs() > 1)
1191 handleNest(cur, ar[0]);
1193 cur.niceInsert(cmd.argument());
1198 case LFUN_UNICODE_INSERT: {
1199 if (cmd.argument().empty())
1201 docstring hexstring = cmd.argument();
1202 if (isHex(hexstring)) {
1203 char_type c = hexToInt(hexstring);
1204 if (c >= 32 && c < 0x10ffff) {
1205 docstring s = docstring(1, c);
1206 FuncCode code = currentMode() == MATH_MODE ?
1207 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1208 lyx::dispatch(FuncRequest(code, s));
1214 case LFUN_DIALOG_SHOW_NEW_INSET: {
1215 docstring const & name = cmd.argument();
1217 if (name == "ref") {
1218 InsetMathRef tmp(buffer_, name);
1219 data = tmp.createDialogStr(to_utf8(name));
1220 cur.bv().showDialog(to_utf8(name), data);
1221 } else if (name == "mathspace") {
1222 cur.bv().showDialog(to_utf8(name));
1227 case LFUN_INSET_INSERT: {
1229 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1230 cur.recordUndoSelection();
1232 // FIXME audit setBuffer/updateBuffer calls
1233 cur.buffer()->updateBuffer();
1238 case LFUN_INSET_DISSOLVE:
1239 if (!asHullInset()) {
1240 cur.recordUndoInset();
1246 InsetMath::doDispatch(cur, cmd);
1252 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1253 // look for macro to open/close, but stay in mathed
1254 for (; !it.empty(); it.pop_back()) {
1256 // go backward through the current cell
1257 Inset * inset = it.nextInset();
1258 while (inset && inset->asInsetMath()) {
1259 MathMacro * macro = inset->asInsetMath()->asMacro();
1261 // found the an macro to open/close?
1262 if (macro->folded() != fold)
1265 // Wrong folding state.
1266 // If this was the first we see in this slice, look further left,
1268 if (inset != it.nextInset())
1272 // go up if this was the left most position
1278 inset = it.nextInset();
1286 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1287 FuncStatus & flag) const
1289 // the font related toggles
1290 //string tc = "mathnormal";
1292 string const arg = to_utf8(cmd.argument());
1293 switch (cmd.action()) {
1294 case LFUN_INSET_MODIFY:
1295 flag.setEnabled(false);
1298 case LFUN_INSET_MODIFY:
1299 // FIXME: check temporarily disabled
1301 char align = mathcursor::valign();
1302 if (align == '\0') {
1306 if (cmd.argument().empty()) {
1310 if (!contains("tcb", cmd.argument()[0])) {
1314 flag.setOnOff(cmd.argument()[0] == align);
1317 /// We have to handle them since 1.4 blocks all unhandled actions
1318 case LFUN_FONT_ITAL:
1319 case LFUN_FONT_BOLD:
1320 case LFUN_FONT_BOLDSYMBOL:
1321 case LFUN_FONT_SANS:
1322 case LFUN_FONT_EMPH:
1323 case LFUN_FONT_TYPEWRITER:
1324 case LFUN_FONT_NOUN:
1325 case LFUN_FONT_ROMAN:
1326 case LFUN_FONT_DEFAULT:
1327 flag.setEnabled(true);
1330 // we just need to be in math mode to enable that
1331 case LFUN_MATH_SIZE:
1332 case LFUN_MATH_SPACE:
1333 case LFUN_MATH_LIMITS:
1334 case LFUN_MATH_EXTERN:
1335 flag.setEnabled(true);
1338 case LFUN_FONT_UNDERLINE:
1339 case LFUN_FONT_FRAK:
1340 flag.setEnabled(currentMode() != TEXT_MODE);
1343 case LFUN_MATH_FONT_STYLE: {
1344 bool const textarg =
1345 arg == "textbf" || arg == "textsf" ||
1346 arg == "textrm" || arg == "textmd" ||
1347 arg == "textit" || arg == "textsc" ||
1348 arg == "textsl" || arg == "textup" ||
1349 arg == "texttt" || arg == "textbb" ||
1350 arg == "textnormal";
1351 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1355 case LFUN_MATH_INSERT:
1356 flag.setEnabled(currentMode() != TEXT_MODE);
1359 case LFUN_MATH_AMS_MATRIX:
1360 case LFUN_MATH_MATRIX:
1361 flag.setEnabled(currentMode() == MATH_MODE);
1364 case LFUN_INSET_INSERT: {
1365 // Don't test createMathInset_fromDialogStr(), since
1366 // getStatus is not called with a valid reference and the
1367 // dialog would not be applyable.
1368 string const name = cmd.getArg(0);
1369 flag.setEnabled(name == "ref" || name == "mathspace");
1373 case LFUN_MATH_DELIM:
1374 case LFUN_MATH_BIGDELIM:
1375 // Don't do this with multi-cell selections
1376 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1379 case LFUN_MATH_MACRO_FOLD:
1380 case LFUN_MATH_MACRO_UNFOLD: {
1382 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1383 flag.setEnabled(found);
1387 case LFUN_SPECIALCHAR_INSERT:
1388 // FIXME: These would probably make sense in math-text mode
1389 flag.setEnabled(false);
1392 case LFUN_INSET_DISSOLVE:
1393 flag.setEnabled(!asHullInset());
1404 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1407 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1408 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1409 cur.idx() = enter_front ? 0 : cur.lastidx();
1410 cur.pos() = enter_front ? 0 : cur.lastpos();
1412 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1416 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1419 int dist_min = 1000000;
1420 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1421 int const d = cell(i).dist(cur.bv(), x, y);
1427 MathData & ar = cell(idx_min);
1429 cur.idx() = idx_min;
1430 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1432 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1433 if (dist_min == 0) {
1435 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1436 if (ar[i]->covers(cur.bv(), x, y))
1437 return ar[i].nucleus()->editXY(cur, x, y);
1443 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1445 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1446 BufferView & bv = cur.bv();
1447 bool do_selection = cmd.button() == mouse_button::button1
1448 && cmd.argument() == "region-select";
1449 bv.mouseSetCursor(cur, do_selection);
1450 if (cmd.button() == mouse_button::button1) {
1451 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1452 // Update the cursor update flags as needed:
1454 // Update::Decoration: tells to update the decoration
1455 // (visual box corners that define
1457 // Update::FitCursor: adjust the screen to the cursor
1458 // position if needed
1459 // cur.result().update(): don't overwrite previously set flags.
1460 cur.updateFlags(Update::Decoration | Update::FitCursor
1461 | cur.result().update());
1462 } else if (cmd.button() == mouse_button::button2) {
1463 if (cap::selection()) {
1464 // See comment in Text::dispatch why we do this
1465 cap::copySelectionToStack();
1466 cmd = FuncRequest(LFUN_PASTE, "0");
1467 doDispatch(bv.cursor(), cmd);
1470 asArray(theSelection().get(), ar);
1471 bv.cursor().insert(ar);
1477 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1479 // only select with button 1
1480 if (cmd.button() == mouse_button::button1) {
1481 Cursor & bvcur = cur.bv().cursor();
1482 if (bvcur.realAnchor().hasPart(cur)) {
1483 //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1484 bvcur.setCursor(cur);
1485 bvcur.setSelection(true);
1486 //lyxerr << "MOTION " << bvcur << endl;
1493 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1495 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1497 if (cmd.button() == mouse_button::button1) {
1498 if (!cur.selection())
1501 Cursor & bvcur = cur.bv().cursor();
1502 bvcur.setSelection(true);
1511 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1513 //lyxerr << "interpret 2: '" << c << "'" << endl;
1514 docstring save_selection;
1515 if (c == '^' || c == '_')
1516 save_selection = grabAndEraseSelection(cur);
1519 Buffer * buf = cur.buffer();
1522 if (cur.inMacroMode()) {
1523 docstring name = cur.macroName();
1525 /// are we currently typing '#1' or '#2' or...?
1526 if (name == "\\#") {
1529 if (n >= 1 && n <= 9)
1530 cur.insert(new MathMacroArgument(n));
1534 // do not finish macro for known * commands
1535 MathWordList const & mwl = mathedWordList();
1536 bool star_macro = c == '*'
1537 && (mwl.find(name.substr(1) + "*") != mwl.end()
1538 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1539 if (isAlphaASCII(c) || star_macro) {
1540 cur.activeMacro()->setName(name + docstring(1, c));
1544 // handle 'special char' macros
1549 if (currentMode() <= InsetMath::TEXT_MODE)
1550 cur.niceInsert(createInsetMath("textbackslash", buf));
1552 cur.niceInsert(createInsetMath("backslash", buf));
1553 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1555 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1556 } else if (c == '{') {
1558 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1559 } else if (c == '%') {
1561 cur.niceInsert(MathAtom(new InsetMathComment(buf)));
1562 } else if (c == '#') {
1563 LASSERT(cur.activeMacro(), /**/);
1564 cur.activeMacro()->setName(name + docstring(1, c));
1567 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1572 // One character big delimiters. The others are handled in
1573 // interpretString().
1574 latexkeys const * l = in_word_set(name.substr(1));
1575 if (name[0] == '\\' && l && l->inset == "big") {
1579 delim = from_ascii("\\{");
1582 delim = from_ascii("\\}");
1585 delim = docstring(1, c);
1588 if (InsetMathBig::isBigInsetDelim(delim)) {
1589 // name + delim ared a valid InsetMathBig.
1590 // We can't use cur.macroModeClose() because
1591 // it does not handle delim.
1592 InsetMathUnknown * p = cur.activeMacro();
1595 cur.cell().erase(cur.pos());
1596 cur.plainInsert(MathAtom(
1597 new InsetMathBig(name.substr(1), delim)));
1602 // leave macro mode and try again if necessary
1603 if (cur.macroModeClose()) {
1604 MathAtom const atom = cur.prevAtom();
1605 if (atom->asNestInset() && atom->isActive()) {
1607 cur.pushBackward(*cur.nextInset());
1611 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1613 interpretChar(cur, c);
1618 // leave autocorrect mode if necessary
1619 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1620 cur.autocorrect() = false;
1621 cur.message(_("Autocorrect Off ('!' to enter)"));
1624 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1625 cur.autocorrect() = true;
1626 cur.message(_("Autocorrect On (<space> to exit)"));
1630 // just clear selection on pressing the space bar
1631 if (cur.selection() && c == ' ') {
1632 cur.setSelection(false);
1637 //lyxerr << "starting with macro" << endl;
1638 bool reduced = cap::reduceSelectionToOneCell(cur);
1639 if (reduced || !cur.selection()) {
1640 docstring const safe = cap::grabAndEraseSelection(cur);
1641 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1649 if (currentMode() <= InsetMath::TEXT_MODE)
1655 if (currentMode() <= InsetMath::TEXT_MODE) {
1656 // insert spaces in text or undecided mode,
1657 // but suppress direct insertion of two spaces in a row
1658 // the still allows typing '<space>a<space>' and deleting the 'a', but
1659 // it is better than nothing...
1660 if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1662 // FIXME: we have to enable full redraw here because of the
1663 // visual box corners that define the inset. If we know for
1664 // sure that we stay within the same cell we can optimize for
1666 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1670 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1671 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1672 // FIXME: we have to enable full redraw here because of the
1673 // visual box corners that define the inset. If we know for
1674 // sure that we stay within the same cell we can optimize for
1676 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1680 if (cur.popForward()) {
1681 // FIXME: we have to enable full redraw here because of the
1682 // visual box corners that define the inset. If we know for
1683 // sure that we stay within the same cell we can optimize for
1685 //cur.updateFlags(Update::FitCursor);
1689 // if we are at the very end, leave the formula
1690 return cur.pos() != cur.lastpos();
1693 // These should be treated differently when not in text mode:
1694 if (currentMode() != InsetMath::TEXT_MODE) {
1696 script(cur, false, save_selection);
1700 script(cur, true, save_selection);
1704 cur.niceInsert(createInsetMath("sim", buf));
1707 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1708 MathAtom at = createInsetMath("text", buf);
1709 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1716 cur.niceInsert(createInsetMath("textasciicircum", buf));
1720 cur.niceInsert(createInsetMath("textasciitilde", buf));
1725 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1726 c == '%' || c == '_') {
1727 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1732 // try auto-correction
1733 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1734 && math_autocorrect(cur.prevAtom(), c))
1737 // no special circumstances, so insert the character without any fuss
1739 if (lyxrc.autocorrection_math) {
1740 if (!cur.autocorrect())
1741 cur.message(_("Autocorrect Off ('!' to enter)"));
1743 cur.message(_("Autocorrect On (<space> to exit)"));
1749 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1751 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1753 if (!cur.empty() && cur.pos() > 0 &&
1754 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1755 if (InsetMathBig::isBigInsetDelim(str)) {
1756 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1757 if (prev[0] == '\\') {
1758 prev = prev.substr(1);
1759 latexkeys const * l = in_word_set(prev);
1760 if (l && l->inset == "big") {
1761 cur.cell()[cur.pos() - 1] =
1762 MathAtom(new InsetMathBig(prev, str));
1772 bool InsetMathNest::script(Cursor & cur, bool up)
1774 return script(cur, up, docstring());
1778 bool InsetMathNest::script(Cursor & cur, bool up,
1779 docstring const & save_selection)
1781 // Hack to get \^ and \_ working
1782 //lyxerr << "handling script: up: " << up << endl;
1783 if (cur.inMacroMode() && cur.macroName() == "\\") {
1785 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1787 interpretChar(cur, '_');
1791 cur.macroModeClose();
1792 if (asScriptInset() && cur.idx() == 0) {
1793 // we are in a nucleus of a script inset, move to _our_ script
1794 InsetMathScript * inset = asScriptInset();
1795 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1797 cur.idx() = inset->idxOfScript(up);
1799 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1801 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1804 cur.idx() = inset->idxOfScript(up);
1805 cur.pos() = cur.lastpos();
1807 // convert the thing to our left to a scriptinset or create a new
1808 // one if in the very first position of the array
1809 if (cur.pos() == 0) {
1810 //lyxerr << "new scriptinset" << endl;
1811 cur.insert(new InsetMathScript(buffer_, up));
1813 //lyxerr << "converting prev atom " << endl;
1814 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1817 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1818 // See comment in MathParser.cpp for special handling of {}-bases
1824 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1825 cur.niceInsert(save_selection);
1827 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1832 bool InsetMathNest::completionSupported(Cursor const & cur) const
1834 return cur.inMacroMode();
1838 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1840 return cur.inMacroMode();
1844 bool InsetMathNest::automaticInlineCompletion() const
1846 return lyxrc.completion_inline_math;
1850 bool InsetMathNest::automaticPopupCompletion() const
1852 return lyxrc.completion_popup_math;
1856 CompletionList const *
1857 InsetMathNest::createCompletionList(Cursor const & cur) const
1859 if (!cur.inMacroMode())
1862 return new MathCompletionList(cur);
1866 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1868 if (!cur.inMacroMode())
1871 return cur.activeMacro()->name();
1875 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1878 if (!cur.inMacroMode())
1881 // append completion to active macro
1882 InsetMathUnknown * inset = cur.activeMacro();
1883 inset->setName(inset->name() + s);
1888 // FIXME: this creates duplicates in the completion popup
1889 // which looks ugly. Moreover the changes the list lengths
1891 confuse the popup as well.
1892 MathCompletionList::addToFavorites(inset->name());
1894 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1901 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
1902 Dimension & dim) const
1904 Inset const * inset = cur.activeMacro();
1908 // get inset dimensions
1909 dim = cur.bv().coordCache().insets().dim(inset);
1910 // FIXME: these 3 are no accurate, but should depend on the font.
1911 // Now the popup jumps down if you enter a char with descent > 0.
1916 Point xy = cur.bv().coordCache().insets().xy(inset);
1922 bool InsetMathNest::cursorMathForward(Cursor & cur)
1924 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1925 cur.pushBackward(*cur.nextAtom().nucleus());
1926 cur.inset().idxFirst(cur);
1929 if (cur.posForward() || idxForward(cur))
1931 // try to pop forwards --- but don't pop out of math! leave that to
1933 int s = cur.depth() - 2;
1934 if (s >= 0 && cur[s].inset().asInsetMath())
1935 return cur.popForward();
1940 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1942 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1944 cur.push(*cur.nextAtom().nucleus());
1945 cur.inset().idxLast(cur);
1948 if (cur.posBackward() || idxBackward(cur))
1950 // try to pop backwards --- but don't pop out of math! leave that to
1952 int s = cur.depth() - 2;
1953 if (s >= 0 && cur[s].inset().asInsetMath())
1954 return cur.popBackward();
1959 ////////////////////////////////////////////////////////////////////
1961 MathCompletionList::MathCompletionList(Cursor const & cur)
1963 // fill it with macros from the buffer
1964 MacroNameSet macros;
1965 cur.buffer()->listMacroNames(macros);
1966 MacroNameSet::const_iterator it;
1967 for (it = macros.begin(); it != macros.end(); ++it) {
1968 if (cur.buffer()->getMacro(*it, cur, false))
1969 locals.push_back("\\" + *it);
1971 sort(locals.begin(), locals.end());
1973 if (globals.size() > 0)
1976 // fill in global macros
1978 MacroTable::globalMacros().getMacroNames(macros);
1979 //lyxerr << "Globals completion macros: ";
1980 for (it = macros.begin(); it != macros.end(); ++it) {
1981 //lyxerr << "\\" + *it << " ";
1982 globals.push_back("\\" + *it);
1984 //lyxerr << std::endl;
1986 // fill in global commands
1987 globals.push_back(from_ascii("\\boxed"));
1988 globals.push_back(from_ascii("\\fbox"));
1989 globals.push_back(from_ascii("\\framebox"));
1990 globals.push_back(from_ascii("\\makebox"));
1991 globals.push_back(from_ascii("\\kern"));
1992 globals.push_back(from_ascii("\\xrightarrow"));
1993 globals.push_back(from_ascii("\\xleftarrow"));
1994 globals.push_back(from_ascii("\\split"));
1995 globals.push_back(from_ascii("\\gathered"));
1996 globals.push_back(from_ascii("\\aligned"));
1997 globals.push_back(from_ascii("\\alignedat"));
1998 globals.push_back(from_ascii("\\cases"));
1999 globals.push_back(from_ascii("\\substack"));
2000 globals.push_back(from_ascii("\\xymatrix"));
2001 globals.push_back(from_ascii("\\subarray"));
2002 globals.push_back(from_ascii("\\array"));
2003 globals.push_back(from_ascii("\\sqrt"));
2004 globals.push_back(from_ascii("\\root"));
2005 globals.push_back(from_ascii("\\tabular"));
2006 globals.push_back(from_ascii("\\stackrel"));
2007 globals.push_back(from_ascii("\\binom"));
2008 globals.push_back(from_ascii("\\choose"));
2009 globals.push_back(from_ascii("\\brace"));
2010 globals.push_back(from_ascii("\\brack"));
2011 globals.push_back(from_ascii("\\frac"));
2012 globals.push_back(from_ascii("\\over"));
2013 globals.push_back(from_ascii("\\nicefrac"));
2014 globals.push_back(from_ascii("\\unitfrac"));
2015 globals.push_back(from_ascii("\\unitfracthree"));
2016 globals.push_back(from_ascii("\\unitone"));
2017 globals.push_back(from_ascii("\\unittwo"));
2018 globals.push_back(from_ascii("\\infer"));
2019 globals.push_back(from_ascii("\\atop"));
2020 globals.push_back(from_ascii("\\lefteqn"));
2021 globals.push_back(from_ascii("\\boldsymbol"));
2022 globals.push_back(from_ascii("\\bm"));
2023 globals.push_back(from_ascii("\\color"));
2024 globals.push_back(from_ascii("\\normalcolor"));
2025 globals.push_back(from_ascii("\\textcolor"));
2026 globals.push_back(from_ascii("\\cfrac"));
2027 globals.push_back(from_ascii("\\cfracleft"));
2028 globals.push_back(from_ascii("\\cfracright"));
2029 globals.push_back(from_ascii("\\dfrac"));
2030 globals.push_back(from_ascii("\\tfrac"));
2031 globals.push_back(from_ascii("\\dbinom"));
2032 globals.push_back(from_ascii("\\tbinom"));
2033 globals.push_back(from_ascii("\\hphantom"));
2034 globals.push_back(from_ascii("\\phantom"));
2035 globals.push_back(from_ascii("\\vphantom"));
2036 MathWordList const & words = mathedWordList();
2037 MathWordList::const_iterator it2;
2038 //lyxerr << "Globals completion commands: ";
2039 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2040 globals.push_back("\\" + (*it2).first);
2041 //lyxerr << "\\" + (*it2).first << " ";
2043 //lyxerr << std::endl;
2044 sort(globals.begin(), globals.end());
2048 MathCompletionList::~MathCompletionList()
2053 size_type MathCompletionList::size() const
2055 return locals.size() + globals.size();
2059 docstring const & MathCompletionList::data(size_t idx) const
2061 size_t lsize = locals.size();
2063 return globals[idx - lsize];
2069 std::string MathCompletionList::icon(size_t idx) const
2071 // get the latex command
2073 size_t lsize = locals.size();
2075 cmd = globals[idx - lsize];
2079 // get the icon resource name by stripping the backslash
2080 return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
2083 std::vector<docstring> MathCompletionList::globals;