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 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
375 ModeSpecifier specifier(os, currentMode(), lockedMode());
376 docstring const latex_name = name();
377 os << '\\' << latex_name;
378 for (size_t i = 0; i < nargs(); ++i)
379 os << '{' << cell(i) << '}';
381 os.pendingSpace(true);
382 if (lock_ && !os.latex()) {
384 os.pendingSpace(true);
389 void InsetMathNest::normalize(NormalStream & os) const
392 for (size_t i = 0; i < nargs(); ++i)
393 os << ' ' << cell(i);
398 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
400 WriteStream wi(os.os(), runparams.moving_arg, true,
401 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
403 wi.canBreakLine(os.canBreakLine());
405 os.canBreakLine(wi.canBreakLine());
408 if (lf > 0 && runparams.lastid != -1) {
410 os.texrow().newline();
411 os.texrow().start(runparams.lastid, runparams.lastpos);
413 os.texrow().newlines(lf);
417 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
420 mouse_hover_[bv] = mouse_hover;
425 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
429 MathData & ar = cur.cell();
430 // remove base-only "scripts"
431 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
432 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
433 if (p && p->nargs() == 1) {
434 MathData ar = p->nuc();
437 cur.adjust(i, ar.size() - 1);
441 // glue adjacent font insets of the same kind
442 for (pos_type i = 0; i + 1 < size(); ++i) {
443 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
444 InsetMathFont const * q = operator[](i + 1)->asFontInset();
445 if (p && q && p->name() == q->name()) {
446 p->cell(0).append(q->cell(0));
456 void InsetMathNest::handleFont
457 (Cursor & cur, docstring const & arg, char const * const font)
459 handleFont(cur, arg, from_ascii(font));
463 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
464 docstring const & font)
466 cur.recordUndoSelection();
468 // this whole function is a hack and won't work for incremental font
470 if (cur.inset().asInsetMath()->name() == font)
471 cur.handleFont(to_utf8(font));
473 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
477 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
479 handleNest(cur, nest, docstring());
483 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
484 docstring const & arg)
486 CursorSlice i1 = cur.selBegin();
487 CursorSlice i2 = cur.selEnd();
488 if (!i1.inset().asInsetMath())
490 if (i1.idx() == i2.idx()) {
491 // the easy case where only one cell is selected
492 cur.handleNest(nest);
497 // multiple selected cells in a simple non-grid inset
498 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
499 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
504 cur.pos() = cur.lastpos();
507 // change font of cell
508 cur.handleNest(nest);
511 // cur is in the font inset now. If the loop continues,
512 // we need to get outside again for the next cell
513 if (i + 1 <= i2.idx())
519 // the complicated case with multiple selected cells in a grid
522 cap::region(i1, i2, r1, r2, c1, c2);
523 for (row_type row = r1; row <= r2; ++row) {
524 for (col_type col = c1; col <= c2; ++col) {
526 cur.idx() = i1.asInsetMath()->index(row, col);
529 cur.pos() = cur.lastpos();
533 cur.handleNest(nest);
536 // cur is in the font inset now. If the loop continues,
537 // we need to get outside again for the next cell
538 if (col + 1 <= c2 || row + 1 <= r2)
545 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
547 cur.recordUndoSelection();
550 font.fromString(to_utf8(arg), b);
551 if (font.fontInfo().color() != Color_inherit &&
552 font.fontInfo().color() != Color_ignore)
553 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
555 // FIXME: support other font changes here as well?
559 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
561 //LYXERR0("InsetMathNest: request: " << cmd);
563 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
565 FuncCode const act = cmd.action();
568 case LFUN_CLIPBOARD_PASTE:
569 parseflg |= Parse::VERBATIM;
572 if (cur.currentMode() <= TEXT_MODE)
573 parseflg |= Parse::TEXTMODE;
574 cur.recordUndoSelection();
575 cur.message(_("Paste"));
576 replaceSelection(cur);
578 if (cmd.argument().empty() && !theClipboard().isInternal())
579 topaste = theClipboard().getAsText();
582 idocstringstream is(cmd.argument());
584 topaste = cap::selection(n);
586 cur.niceInsert(topaste, parseflg, false);
587 cur.clearSelection(); // bug 393
588 cur.forceBufferUpdate();
595 cutSelection(cur, true, true);
596 cur.message(_("Cut"));
597 // Prevent stale position >= size crash
598 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
600 cur.forceBufferUpdate();
605 cur.message(_("Copy"));
608 case LFUN_MOUSE_PRESS:
609 lfunMousePress(cur, cmd);
612 case LFUN_MOUSE_MOTION:
613 lfunMouseMotion(cur, cmd);
616 case LFUN_MOUSE_RELEASE:
617 lfunMouseRelease(cur, cmd);
620 case LFUN_FINISHED_LEFT: // in math, left is backwards
621 case LFUN_FINISHED_BACKWARD:
622 cur.bv().cursor() = cur;
625 case LFUN_FINISHED_RIGHT: // in math, right is forward
626 case LFUN_FINISHED_FORWARD:
628 cur.bv().cursor() = cur;
631 case LFUN_CHAR_RIGHT:
633 case LFUN_CHAR_BACKWARD:
634 case LFUN_CHAR_FORWARD:
635 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
636 case LFUN_CHAR_RIGHT_SELECT:
637 case LFUN_CHAR_LEFT_SELECT:
638 case LFUN_CHAR_BACKWARD_SELECT:
639 case LFUN_CHAR_FORWARD_SELECT: {
640 // are we in a selection?
641 bool select = (act == LFUN_CHAR_RIGHT_SELECT
642 || act == LFUN_CHAR_LEFT_SELECT
643 || act == LFUN_CHAR_BACKWARD_SELECT
644 || act == LFUN_CHAR_FORWARD_SELECT);
645 // are we moving forward or backwards?
646 // If the command was RIGHT or LEFT, then whether we're moving forward
647 // or backwards depends on the cursor movement mode (logical or visual):
648 // * in visual mode, since math is always LTR, right -> forward,
650 // * in logical mode, the mapping is determined by the
651 // reverseDirectionNeeded() function
654 FuncCode finish_lfun;
656 if (act == LFUN_CHAR_FORWARD
657 || act == LFUN_CHAR_FORWARD_SELECT) {
659 finish_lfun = LFUN_FINISHED_FORWARD;
661 else if (act == LFUN_CHAR_BACKWARD
662 || act == LFUN_CHAR_BACKWARD_SELECT) {
664 finish_lfun = LFUN_FINISHED_BACKWARD;
667 bool right = (act == LFUN_CHAR_RIGHT_SELECT
668 || act == LFUN_CHAR_RIGHT);
669 if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
675 finish_lfun = LFUN_FINISHED_RIGHT;
677 finish_lfun = LFUN_FINISHED_LEFT;
679 // Now that we know exactly what we want to do, let's do it!
680 cur.selHandle(select);
682 cur.macroModeClose();
683 // try moving forward or backwards as necessary...
684 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
685 // ... and if movement failed, then finish forward or backwards
687 cmd = FuncRequest(finish_lfun);
695 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
696 case LFUN_DOWN_SELECT:
697 case LFUN_UP_SELECT: {
698 // close active macro
699 if (cur.inMacroMode()) {
700 cur.macroModeClose();
704 // stop/start the selection
705 bool select = act == LFUN_DOWN_SELECT ||
706 act == LFUN_UP_SELECT;
707 cur.selHandle(select);
710 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
711 bool successful = cur.upDownInMath(up);
715 if (cur.fixIfBroken())
716 // FIXME: Something bad happened. We pass the corrected Cursor
717 // instead of letting things go worse.
720 // We did not manage to move the cursor.
725 case LFUN_MOUSE_DOUBLE:
726 case LFUN_MOUSE_TRIPLE:
727 case LFUN_WORD_SELECT:
731 cur.setSelection(true);
732 cur.pos() = cur.lastpos();
733 cur.idx() = cur.lastidx();
736 case LFUN_PARAGRAPH_UP:
737 case LFUN_PARAGRAPH_DOWN:
738 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
739 case LFUN_PARAGRAPH_UP_SELECT:
740 case LFUN_PARAGRAPH_DOWN_SELECT:
743 case LFUN_LINE_BEGIN:
744 case LFUN_WORD_BACKWARD:
746 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
747 case LFUN_LINE_BEGIN_SELECT:
748 case LFUN_WORD_BACKWARD_SELECT:
749 case LFUN_WORD_LEFT_SELECT:
750 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
751 act == LFUN_WORD_LEFT_SELECT ||
752 act == LFUN_LINE_BEGIN_SELECT);
753 cur.macroModeClose();
754 if (cur.pos() != 0) {
756 } else if (cur.col() != 0) {
757 cur.idx() -= cur.col();
759 } else if (cur.idx() != 0) {
763 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
768 case LFUN_WORD_FORWARD:
769 case LFUN_WORD_RIGHT:
771 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
772 case LFUN_WORD_FORWARD_SELECT:
773 case LFUN_WORD_RIGHT_SELECT:
774 case LFUN_LINE_END_SELECT:
775 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
776 act == LFUN_WORD_RIGHT_SELECT ||
777 act == LFUN_LINE_END_SELECT);
778 cur.macroModeClose();
780 if (cur.pos() != cur.lastpos()) {
781 cur.pos() = cur.lastpos();
782 } else if (ncols() && (cur.col() != cur.lastcol())) {
783 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
784 cur.pos() = cur.lastpos();
785 } else if (cur.idx() != cur.lastidx()) {
786 cur.idx() = cur.lastidx();
787 cur.pos() = cur.lastpos();
789 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
794 case LFUN_CELL_FORWARD:
795 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
796 cur.inset().idxNext(cur);
799 case LFUN_CELL_BACKWARD:
800 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
801 cur.inset().idxPrev(cur);
804 case LFUN_WORD_DELETE_BACKWARD:
805 case LFUN_CHAR_DELETE_BACKWARD:
807 // May affect external cell:
808 cur.recordUndoInset();
810 cur.recordUndoSelection();
811 // if the inset can not be removed from within, delete it
812 if (!cur.backspace()) {
813 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
814 cur.innerText()->dispatch(cur, cmd);
818 case LFUN_WORD_DELETE_FORWARD:
819 case LFUN_CHAR_DELETE_FORWARD:
820 if (cur.pos() == cur.lastpos())
821 // May affect external cell:
822 cur.recordUndoInset();
824 cur.recordUndoSelection();
825 // if the inset can not be removed from within, delete it
827 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
828 cur.innerText()->dispatch(cur, cmd);
834 cur.clearSelection();
836 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
841 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
842 // that is traversed by a single <CursorLeft>/<CursorRight>.
843 case LFUN_INSET_TOGGLE:
849 case LFUN_SELF_INSERT:
850 if (cmd.argument().size() != 1) {
851 // use a group because interpretString() might
852 // record an extra undo step
853 cur.beginUndoGroup();
854 cur.recordUndoSelection();
855 docstring const arg = cmd.argument();
856 if (!interpretString(cur, arg))
861 // Don't record undo steps if we are in macro mode and thus
862 // cmd.argument is the next character of the macro name.
863 // Otherwise we'll get an invalid cursor if we undo after
864 // the macro was finished and the macro is a known command,
865 // e.g. sqrt. Cursor::macroModeClose replaces in this case
866 // the InsetMathUnknown with name "frac" by an empty
867 // InsetMathFrac -> a pos value > 0 is invalid.
868 // A side effect is that an undo before the macro is finished
869 // undoes the complete macro, not only the last character.
870 // At the time we hit '\' we are not in macro mode, still.
871 if (!cur.inMacroMode())
872 cur.recordUndoSelection();
874 // spacial handling of space. If we insert an inset
875 // via macro mode, we want to put the cursor inside it
876 // if relevant. Think typing "\frac<space>".
877 if (cmd.argument()[0] == ' '
878 && cur.inMacroMode() && cur.macroName() != "\\"
879 && cur.macroModeClose() && cur.pos() > 0) {
880 MathAtom const atom = cur.prevAtom();
881 if (atom->asNestInset() && atom->isActive()) {
883 cur.pushBackward(*cur.nextInset());
885 } else if (!interpretChar(cur, cmd.argument()[0])) {
886 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
891 //case LFUN_SERVER_GET_XY:
894 case LFUN_SERVER_SET_XY: {
895 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
898 istringstream is(to_utf8(cmd.argument()));
900 cur.setScreenPos(x, y);
904 // Special casing for superscript in case of LyX handling
906 case LFUN_ACCENT_CIRCUMFLEX:
907 if (cmd.argument().empty()) {
908 // do superscript if LyX handles
910 cur.recordUndoSelection();
911 script(cur, true, grabAndEraseSelection(cur));
915 case LFUN_ACCENT_UMLAUT:
916 case LFUN_ACCENT_ACUTE:
917 case LFUN_ACCENT_GRAVE:
918 case LFUN_ACCENT_BREVE:
919 case LFUN_ACCENT_DOT:
920 case LFUN_ACCENT_MACRON:
921 case LFUN_ACCENT_CARON:
922 case LFUN_ACCENT_TILDE:
923 case LFUN_ACCENT_CEDILLA:
924 case LFUN_ACCENT_CIRCLE:
925 case LFUN_ACCENT_UNDERDOT:
926 case LFUN_ACCENT_TIE:
927 case LFUN_ACCENT_OGONEK:
928 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
932 case LFUN_TEXTSTYLE_APPLY:
933 case LFUN_TEXTSTYLE_UPDATE:
934 handleFont2(cur, cmd.argument());
938 if (currentMode() <= TEXT_MODE)
939 handleFont(cur, cmd.argument(), "textbf");
941 handleFont(cur, cmd.argument(), "mathbf");
943 case LFUN_FONT_BOLDSYMBOL:
944 if (currentMode() <= TEXT_MODE)
945 handleFont(cur, cmd.argument(), "textbf");
947 handleFont(cur, cmd.argument(), "boldsymbol");
950 if (currentMode() <= TEXT_MODE)
951 handleFont(cur, cmd.argument(), "textsf");
953 handleFont(cur, cmd.argument(), "mathsf");
956 if (currentMode() <= TEXT_MODE)
957 handleFont(cur, cmd.argument(), "emph");
959 handleFont(cur, cmd.argument(), "mathcal");
961 case LFUN_FONT_ROMAN:
962 if (currentMode() <= TEXT_MODE)
963 handleFont(cur, cmd.argument(), "textrm");
965 handleFont(cur, cmd.argument(), "mathrm");
967 case LFUN_FONT_TYPEWRITER:
968 if (currentMode() <= TEXT_MODE)
969 handleFont(cur, cmd.argument(), "texttt");
971 handleFont(cur, cmd.argument(), "mathtt");
974 handleFont(cur, cmd.argument(), "mathfrak");
977 if (currentMode() <= TEXT_MODE)
978 handleFont(cur, cmd.argument(), "textit");
980 handleFont(cur, cmd.argument(), "mathit");
983 if (currentMode() <= TEXT_MODE)
984 // FIXME: should be "noun"
985 handleFont(cur, cmd.argument(), "textsc");
987 handleFont(cur, cmd.argument(), "mathbb");
989 case LFUN_FONT_DEFAULT:
990 handleFont(cur, cmd.argument(), "textnormal");
993 case LFUN_FONT_UNDERLINE:
995 cur.handleNest(createInsetMath("underline", cur.buffer()));
997 case LFUN_MATH_MODE: {
999 // ignore math-mode on when already in math mode
1000 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1002 cur.recordUndoSelection();
1003 cur.macroModeClose();
1004 docstring const save_selection = grabAndEraseSelection(cur);
1006 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
1007 if (currentMode() <= Inset::TEXT_MODE)
1008 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1010 cur.plainInsert(MathAtom(new InsetMathBox(buffer_, from_ascii("mbox"))));
1012 cur.pushBackward(*cur.nextInset());
1013 cur.niceInsert(save_selection);
1014 cur.forceBufferUpdate();
1016 if (currentMode() == Inset::TEXT_MODE) {
1017 cur.recordUndoSelection();
1018 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1019 cur.message(_("create new math text environment ($...$)"));
1021 handleFont(cur, cmd.argument(), "textrm");
1022 cur.message(_("entered math text mode (textrm)"));
1028 case LFUN_REGEXP_MODE: {
1029 InsetMath * im = cur.inset().asInsetMath();
1031 InsetMathHull * i = im->asHullInset();
1032 if (i && i->getType() == hullRegexp) {
1033 cur.message(_("Already in regular expression mode"));
1037 cur.macroModeClose();
1038 docstring const save_selection = grabAndEraseSelection(cur);
1040 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1042 cur.pushBackward(*cur.nextInset());
1043 cur.niceInsert(save_selection);
1044 cur.message(_("Regular expression editor mode"));
1048 case LFUN_MATH_FONT_STYLE: {
1049 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1050 doDispatch(cur, fr);
1054 case LFUN_MATH_SIZE: {
1055 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1056 doDispatch(cur, fr);
1060 case LFUN_MATH_MATRIX: {
1066 idocstringstream is(cmd.argument());
1067 is >> m >> n >> v_align >> h_align;
1073 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1074 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1078 case LFUN_MATH_AMS_MATRIX: {
1083 idocstringstream is(cmd.argument());
1084 is >> m >> n >> name;
1090 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1094 case LFUN_MATH_DELIM: {
1096 docstring rs = split(cmd.argument(), ls, ' ');
1097 // Reasonable default values
1103 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1107 case LFUN_MATH_BIGDELIM: {
1108 docstring const lname = from_utf8(cmd.getArg(0));
1109 docstring const ldelim = from_utf8(cmd.getArg(1));
1110 docstring const rname = from_utf8(cmd.getArg(2));
1111 docstring const rdelim = from_utf8(cmd.getArg(3));
1112 latexkeys const * l = in_word_set(lname);
1113 bool const have_l = l && l->inset == "big" &&
1114 InsetMathBig::isBigInsetDelim(ldelim);
1115 l = in_word_set(rname);
1116 bool const have_r = l && l->inset == "big" &&
1117 InsetMathBig::isBigInsetDelim(rdelim);
1118 // We mimic LFUN_MATH_DELIM in case we have an empty left
1119 // or right delimiter.
1120 if (have_l || have_r) {
1122 docstring const selection = grabAndEraseSelection(cur);
1125 cur.insert(MathAtom(new InsetMathBig(lname,
1127 // first insert the right delimiter and then go back
1128 // and re-insert the selection (bug 7088)
1130 cur.insert(MathAtom(new InsetMathBig(rname,
1134 cur.niceInsert(selection);
1136 // Don't call cur.undispatched() if we did nothing, this would
1137 // lead to infinite recursion via Text::dispatch().
1141 case LFUN_SPACE_INSERT: {
1142 cur.recordUndoSelection();
1143 string const name = cmd.getArg(0);
1144 if (name == "normal")
1145 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1146 else if (name == "protected")
1147 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1148 else if (name == "thin" || name == "med" || name == "thick")
1149 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1150 else if (name == "hfill*")
1151 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1152 else if (name == "quad" || name == "qquad" ||
1153 name == "enspace" || name == "enskip" ||
1154 name == "negthinspace" || name == "negmedspace" ||
1155 name == "negthickspace" || name == "hfill")
1156 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1157 else if (name == "hspace" || name == "hspace*") {
1158 string const len = cmd.getArg(1);
1159 if (len.empty() || !isValidLength(len)) {
1160 lyxerr << "LyX function 'space-insert " << name << "' "
1161 "needs a valid length argument." << endl;
1164 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1166 cur.insert(MathAtom(new InsetMathSpace));
1170 case LFUN_MATH_SPACE:
1171 cur.recordUndoSelection();
1172 if (cmd.argument().empty())
1173 cur.insert(MathAtom(new InsetMathSpace));
1175 string const name = cmd.getArg(0);
1176 string const len = cmd.getArg(1);
1177 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1181 case LFUN_ERT_INSERT:
1182 // interpret this as if a backslash was typed
1184 interpretChar(cur, '\\');
1187 case LFUN_MATH_SUBSCRIPT:
1188 // interpret this as if a _ was typed
1189 cur.recordUndoSelection();
1190 interpretChar(cur, '_');
1193 case LFUN_MATH_SUPERSCRIPT:
1194 // interpret this as if a ^ was typed
1195 cur.recordUndoSelection();
1196 interpretChar(cur, '^');
1199 case LFUN_MATH_MACRO_FOLD:
1200 case LFUN_MATH_MACRO_UNFOLD: {
1202 bool fold = act == LFUN_MATH_MACRO_FOLD;
1203 bool found = findMacroToFoldUnfold(it, fold);
1205 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1206 cur.recordUndoInset();
1215 case LFUN_QUOTE_INSERT:
1216 // interpret this as if a straight " was typed
1217 cur.recordUndoSelection();
1218 interpretChar(cur, '\"');
1221 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1222 // handling such that "self-insert" works on "arbitrary stuff" too, and
1223 // math-insert only handles special math things like "matrix".
1224 case LFUN_MATH_INSERT: {
1225 cur.recordUndoSelection();
1226 if (cmd.argument() == "^" || cmd.argument() == "_")
1227 interpretChar(cur, cmd.argument()[0]);
1230 asArray(cmd.argument(), ar);
1231 if (cur.selection() && ar.size() == 1
1232 && ar[0]->asNestInset()
1233 && ar[0]->asNestInset()->nargs() > 1)
1234 handleNest(cur, ar[0]);
1236 cur.niceInsert(cmd.argument());
1241 case LFUN_UNICODE_INSERT: {
1242 if (cmd.argument().empty())
1244 docstring hexstring = cmd.argument();
1245 if (isHex(hexstring)) {
1246 char_type c = hexToInt(hexstring);
1247 if (c >= 32 && c < 0x10ffff) {
1248 docstring s = docstring(1, c);
1249 FuncCode code = currentMode() == MATH_MODE ?
1250 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1251 lyx::dispatch(FuncRequest(code, s));
1257 case LFUN_DIALOG_SHOW_NEW_INSET: {
1258 docstring const & name = cmd.argument();
1260 if (name == "ref") {
1261 InsetMathRef tmp(buffer_, name);
1262 data = tmp.createDialogStr();
1263 cur.bv().showDialog(to_utf8(name), data);
1264 } else if (name == "mathspace") {
1265 cur.bv().showDialog(to_utf8(name));
1270 case LFUN_INSET_INSERT: {
1272 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1273 cur.recordUndoSelection();
1275 cur.forceBufferUpdate();
1280 case LFUN_INSET_DISSOLVE:
1281 if (!asHullInset()) {
1282 cur.recordUndoInset();
1288 InsetMath::doDispatch(cur, cmd);
1294 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1295 // look for macro to open/close, but stay in mathed
1296 for (; !it.empty(); it.pop_back()) {
1298 // go backward through the current cell
1299 Inset * inset = it.nextInset();
1300 while (inset && inset->asInsetMath()) {
1301 MathMacro * macro = inset->asInsetMath()->asMacro();
1303 // found the an macro to open/close?
1304 if (macro->folded() != fold)
1307 // Wrong folding state.
1308 // If this was the first we see in this slice, look further left,
1310 if (inset != it.nextInset())
1314 // go up if this was the left most position
1320 inset = it.nextInset();
1328 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1329 FuncStatus & flag) const
1331 // the font related toggles
1332 //string tc = "mathnormal";
1334 string const arg = to_utf8(cmd.argument());
1335 switch (cmd.action()) {
1336 case LFUN_INSET_MODIFY:
1337 flag.setEnabled(false);
1340 case LFUN_INSET_MODIFY:
1341 // FIXME: check temporarily disabled
1343 char align = mathcursor::valign();
1344 if (align == '\0') {
1348 if (cmd.argument().empty()) {
1352 if (!contains("tcb", cmd.argument()[0])) {
1356 flag.setOnOff(cmd.argument()[0] == align);
1359 /// We have to handle them since 1.4 blocks all unhandled actions
1360 case LFUN_FONT_ITAL:
1361 case LFUN_FONT_BOLD:
1362 case LFUN_FONT_BOLDSYMBOL:
1363 case LFUN_FONT_SANS:
1364 case LFUN_FONT_EMPH:
1365 case LFUN_FONT_TYPEWRITER:
1366 case LFUN_FONT_NOUN:
1367 case LFUN_FONT_ROMAN:
1368 case LFUN_FONT_DEFAULT:
1369 flag.setEnabled(true);
1372 // we just need to be in math mode to enable that
1373 case LFUN_MATH_SIZE:
1374 case LFUN_MATH_SPACE:
1375 case LFUN_MATH_EXTERN:
1376 flag.setEnabled(true);
1379 case LFUN_FONT_UNDERLINE:
1380 case LFUN_FONT_FRAK:
1381 flag.setEnabled(currentMode() != TEXT_MODE);
1384 case LFUN_MATH_FONT_STYLE: {
1385 bool const textarg =
1386 arg == "textbf" || arg == "textsf" ||
1387 arg == "textrm" || arg == "textmd" ||
1388 arg == "textit" || arg == "textsc" ||
1389 arg == "textsl" || arg == "textup" ||
1390 arg == "texttt" || arg == "textbb" ||
1391 arg == "textnormal";
1392 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1396 case LFUN_MATH_MODE:
1397 // forbid "math-mode on" in math mode to prevent irritating
1398 // behaviour of menu entries (bug 6709)
1399 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1402 case LFUN_MATH_INSERT:
1403 flag.setEnabled(currentMode() != TEXT_MODE);
1406 case LFUN_MATH_AMS_MATRIX:
1407 case LFUN_MATH_MATRIX:
1408 flag.setEnabled(currentMode() == MATH_MODE);
1411 case LFUN_INSET_INSERT: {
1412 // Don't test createMathInset_fromDialogStr(), since
1413 // getStatus is not called with a valid reference and the
1414 // dialog would not be applyable.
1415 string const name = cmd.getArg(0);
1416 flag.setEnabled(name == "ref" || name == "mathspace");
1420 case LFUN_DIALOG_SHOW_NEW_INSET: {
1421 docstring const & name = cmd.argument();
1422 if (name == "space")
1423 flag.setEnabled(false);
1428 case LFUN_MATH_DELIM:
1429 case LFUN_MATH_BIGDELIM:
1430 // Don't do this with multi-cell selections
1431 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1434 case LFUN_MATH_MACRO_FOLD:
1435 case LFUN_MATH_MACRO_UNFOLD: {
1437 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1438 flag.setEnabled(found);
1442 case LFUN_SPECIALCHAR_INSERT:
1443 case LFUN_SCRIPT_INSERT:
1444 // FIXME: These would probably make sense in math-text mode
1445 flag.setEnabled(false);
1448 case LFUN_SPACE_INSERT: {
1449 docstring const & name = cmd.argument();
1450 if (name == "visible")
1451 flag.setEnabled(false);
1455 case LFUN_INSET_DISSOLVE:
1456 flag.setEnabled(!asHullInset());
1467 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1470 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1471 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1472 cur.idx() = enter_front ? 0 : cur.lastidx();
1473 cur.pos() = enter_front ? 0 : cur.lastpos();
1475 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1479 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1482 int dist_min = 1000000;
1483 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1484 int const d = cell(i).dist(cur.bv(), x, y);
1490 MathData & ar = cell(idx_min);
1492 cur.idx() = idx_min;
1493 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1495 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1496 if (dist_min == 0) {
1498 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1499 if (ar[i]->covers(cur.bv(), x, y))
1500 return ar[i].nucleus()->editXY(cur, x, y);
1506 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1508 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1509 BufferView & bv = cur.bv();
1510 if (cmd.button() == mouse_button::button3) {
1511 // Don't do anything if we right-click a
1512 // selection, a context menu will popup.
1513 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1514 && cur < bv.cursor().selectionEnd()) {
1515 cur.noScreenUpdate();
1519 bool do_selection = cmd.button() == mouse_button::button1
1520 && cmd.argument() == "region-select";
1521 bv.mouseSetCursor(cur, do_selection);
1522 if (cmd.button() == mouse_button::button1) {
1523 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1524 // Update the cursor update flags as needed:
1526 // Update::Decoration: tells to update the decoration
1527 // (visual box corners that define
1529 // Update::FitCursor: adjust the screen to the cursor
1530 // position if needed
1531 // cur.result().update(): don't overwrite previously set flags.
1532 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1533 | cur.result().screenUpdate());
1534 } else if (cmd.button() == mouse_button::button2) {
1535 if (cap::selection()) {
1536 // See comment in Text::dispatch why we do this
1537 cap::copySelectionToStack();
1538 cmd = FuncRequest(LFUN_PASTE, "0");
1539 doDispatch(bv.cursor(), cmd);
1542 asArray(theSelection().get(), ar);
1543 bv.cursor().insert(ar);
1549 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1551 // only select with button 1
1552 if (cmd.button() == mouse_button::button1) {
1553 Cursor & bvcur = cur.bv().cursor();
1554 if (bvcur.realAnchor().hasPart(cur)) {
1555 //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1556 bvcur.setCursor(cur);
1557 bvcur.setSelection(true);
1558 //lyxerr << "MOTION " << bvcur << endl;
1565 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1567 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1569 if (cmd.button() == mouse_button::button1) {
1570 if (!cur.selection())
1571 cur.noScreenUpdate();
1573 Cursor & bvcur = cur.bv().cursor();
1574 bvcur.setSelection(true);
1583 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1585 //lyxerr << "interpret 2: '" << c << "'" << endl;
1586 docstring save_selection;
1587 if (c == '^' || c == '_')
1588 save_selection = grabAndEraseSelection(cur);
1591 Buffer * buf = cur.buffer();
1594 if (cur.inMacroMode()) {
1595 docstring name = cur.macroName();
1597 /// are we currently typing '#1' or '#2' or...?
1598 if (name == "\\#") {
1601 if (n >= 1 && n <= 9)
1602 cur.insert(new MathMacroArgument(n));
1606 // do not finish macro for known * commands
1607 MathWordList const & mwl = mathedWordList();
1608 bool star_macro = c == '*'
1609 && (mwl.find(name.substr(1) + "*") != mwl.end()
1610 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1611 if (isAlphaASCII(c) || star_macro) {
1612 cur.activeMacro()->setName(name + docstring(1, c));
1616 // handle 'special char' macros
1621 if (currentMode() <= InsetMath::TEXT_MODE)
1622 cur.niceInsert(createInsetMath("textbackslash", buf));
1624 cur.niceInsert(createInsetMath("backslash", buf));
1625 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1627 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1628 } else if (c == '{') {
1630 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1631 } else if (c == '%') {
1633 cur.niceInsert(MathAtom(new InsetMathComment(buf)));
1634 } else if (c == '#') {
1635 LASSERT(cur.activeMacro(), /**/);
1636 cur.activeMacro()->setName(name + docstring(1, c));
1639 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1644 // One character big delimiters. The others are handled in
1645 // interpretString().
1646 latexkeys const * l = in_word_set(name.substr(1));
1647 if (name[0] == '\\' && l && l->inset == "big") {
1651 delim = from_ascii("\\{");
1654 delim = from_ascii("\\}");
1657 delim = docstring(1, c);
1660 if (InsetMathBig::isBigInsetDelim(delim)) {
1661 // name + delim ared a valid InsetMathBig.
1662 // We can't use cur.macroModeClose() because
1663 // it does not handle delim.
1664 InsetMathUnknown * p = cur.activeMacro();
1667 cur.cell().erase(cur.pos());
1668 cur.plainInsert(MathAtom(
1669 new InsetMathBig(name.substr(1), delim)));
1670 // end undo group that was opened before p was created
1676 // leave macro mode and try again if necessary
1677 if (cur.macroModeClose()) {
1678 MathAtom const atom = cur.prevAtom();
1679 if (atom->asNestInset() && atom->isActive()) {
1681 cur.pushBackward(*cur.nextInset());
1685 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1687 interpretChar(cur, c);
1692 // leave autocorrect mode if necessary
1693 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1694 cur.autocorrect() = false;
1695 cur.message(_("Autocorrect Off ('!' to enter)"));
1698 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1699 cur.autocorrect() = true;
1700 cur.message(_("Autocorrect On (<space> to exit)"));
1704 // just clear selection on pressing the space bar
1705 if (cur.selection() && c == ' ') {
1706 cur.setSelection(false);
1711 //lyxerr << "starting with macro" << endl;
1712 bool reduced = cap::reduceSelectionToOneCell(cur);
1713 if (reduced || !cur.selection()) {
1714 docstring const safe = cap::grabAndEraseSelection(cur);
1715 if (!cur.inRegexped()) {
1716 // open a group because interpretString() might
1717 // record an extra undo step when finalizing
1718 cur.beginUndoGroup();
1719 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1721 cur.niceInsert(createInsetMath("backslash", buf));
1729 if (currentMode() <= InsetMath::TEXT_MODE)
1735 if (currentMode() <= InsetMath::TEXT_MODE) {
1736 // insert spaces in text or undecided mode,
1737 // but suppress direct insertion of two spaces in a row
1738 // the still allows typing '<space>a<space>' and deleting the 'a', but
1739 // it is better than nothing...
1740 if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1742 // FIXME: we have to enable full redraw here because of the
1743 // visual box corners that define the inset. If we know for
1744 // sure that we stay within the same cell we can optimize for
1746 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1750 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1751 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1752 // FIXME: we have to enable full redraw here because of the
1753 // visual box corners that define the inset. If we know for
1754 // sure that we stay within the same cell we can optimize for
1756 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1760 if (cur.popForward()) {
1761 // FIXME: we have to enable full redraw here because of the
1762 // visual box corners that define the inset. If we know for
1763 // sure that we stay within the same cell we can optimize for
1765 //cur.screenUpdateFlags(Update::FitCursor);
1769 // if we are at the very end, leave the formula
1770 return cur.pos() != cur.lastpos();
1773 // These should be treated differently when not in text mode:
1774 if (cur.inRegexped()) {
1777 cur.niceInsert(createInsetMath("backslash", buf));
1780 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1787 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1790 cur.niceInsert(createInsetMath("sim", buf));
1796 } else if (currentMode() != InsetMath::TEXT_MODE) {
1798 script(cur, false, save_selection);
1802 script(cur, true, save_selection);
1806 cur.niceInsert(createInsetMath("sim", buf));
1809 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1810 MathAtom at = createInsetMath("text", buf);
1811 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1818 cur.niceInsert(createInsetMath("textasciicircum", buf));
1822 cur.niceInsert(createInsetMath("textasciitilde", buf));
1827 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1828 c == '%' || c == '_') {
1829 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1834 // try auto-correction
1835 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1836 && math_autocorrect(cur.prevAtom(), c))
1839 // no special circumstances, so insert the character without any fuss
1841 if (lyxrc.autocorrection_math) {
1842 if (!cur.autocorrect())
1843 cur.message(_("Autocorrect Off ('!' to enter)"));
1845 cur.message(_("Autocorrect On (<space> to exit)"));
1851 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1853 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1855 if (!cur.empty() && cur.pos() > 0 &&
1856 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1857 if (InsetMathBig::isBigInsetDelim(str)) {
1858 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1859 if (prev[0] == '\\') {
1860 prev = prev.substr(1);
1861 latexkeys const * l = in_word_set(prev);
1862 if (l && l->inset == "big") {
1863 cur.cell()[cur.pos() - 1] =
1864 MathAtom(new InsetMathBig(prev, str));
1874 bool InsetMathNest::script(Cursor & cur, bool up)
1876 return script(cur, up, docstring());
1880 bool InsetMathNest::script(Cursor & cur, bool up,
1881 docstring const & save_selection)
1883 // Hack to get \^ and \_ working
1884 //lyxerr << "handling script: up: " << up << endl;
1885 if (cur.inMacroMode() && cur.macroName() == "\\") {
1887 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1889 interpretChar(cur, '_');
1893 cur.macroModeClose();
1894 if (asScriptInset() && cur.idx() == 0) {
1895 // we are in a nucleus of a script inset, move to _our_ script
1896 InsetMathScript * inset = asScriptInset();
1897 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1899 cur.idx() = inset->idxOfScript(up);
1901 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1903 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1906 cur.idx() = inset->idxOfScript(up);
1907 cur.pos() = cur.lastpos();
1909 // convert the thing to our left to a scriptinset or create a new
1910 // one if in the very first position of the array
1911 if (cur.pos() == 0) {
1912 //lyxerr << "new scriptinset" << endl;
1913 cur.insert(new InsetMathScript(buffer_, up));
1915 //lyxerr << "converting prev atom " << endl;
1916 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1919 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1920 // See comment in MathParser.cpp for special handling of {}-bases
1926 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1927 cur.niceInsert(save_selection);
1929 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1934 bool InsetMathNest::completionSupported(Cursor const & cur) const
1936 return cur.inMacroMode();
1940 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1942 return cur.inMacroMode();
1946 bool InsetMathNest::automaticInlineCompletion() const
1948 return lyxrc.completion_inline_math;
1952 bool InsetMathNest::automaticPopupCompletion() const
1954 return lyxrc.completion_popup_math;
1958 CompletionList const *
1959 InsetMathNest::createCompletionList(Cursor const & cur) const
1961 if (!cur.inMacroMode())
1964 return new MathCompletionList(cur);
1968 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1970 if (!cur.inMacroMode())
1973 return cur.activeMacro()->name();
1977 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1980 if (!cur.inMacroMode())
1983 // append completion to active macro
1984 InsetMathUnknown * inset = cur.activeMacro();
1985 inset->setName(inset->name() + s);
1990 // FIXME: this creates duplicates in the completion popup
1991 // which looks ugly. Moreover the changes the list lengths
1993 confuse the popup as well.
1994 MathCompletionList::addToFavorites(inset->name());
1996 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2003 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2004 Dimension & dim) const
2006 Inset const * inset = cur.activeMacro();
2010 // get inset dimensions
2011 dim = cur.bv().coordCache().insets().dim(inset);
2012 // FIXME: these 3 are no accurate, but should depend on the font.
2013 // Now the popup jumps down if you enter a char with descent > 0.
2018 Point xy = cur.bv().coordCache().insets().xy(inset);
2024 bool InsetMathNest::cursorMathForward(Cursor & cur)
2026 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2027 cur.pushBackward(*cur.nextAtom().nucleus());
2028 cur.inset().idxFirst(cur);
2031 if (cur.posForward() || idxForward(cur))
2033 // try to pop forwards --- but don't pop out of math! leave that to
2035 int s = cur.depth() - 2;
2036 if (s >= 0 && cur[s].inset().asInsetMath())
2037 return cur.popForward();
2042 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2044 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2046 cur.push(*cur.nextAtom().nucleus());
2047 cur.inset().idxLast(cur);
2050 if (cur.posBackward() || idxBackward(cur))
2052 // try to pop backwards --- but don't pop out of math! leave that to
2054 int s = cur.depth() - 2;
2055 if (s >= 0 && cur[s].inset().asInsetMath())
2056 return cur.popBackward();
2061 ////////////////////////////////////////////////////////////////////
2063 MathCompletionList::MathCompletionList(Cursor const & cur)
2065 // fill it with macros from the buffer
2066 MacroNameSet macros;
2067 cur.buffer()->listMacroNames(macros);
2068 MacroNameSet::const_iterator it;
2069 for (it = macros.begin(); it != macros.end(); ++it) {
2070 if (cur.buffer()->getMacro(*it, cur, false))
2071 locals.push_back("\\" + *it);
2073 sort(locals.begin(), locals.end());
2075 if (globals.size() > 0)
2078 // fill in global macros
2080 MacroTable::globalMacros().getMacroNames(macros);
2081 //lyxerr << "Globals completion macros: ";
2082 for (it = macros.begin(); it != macros.end(); ++it) {
2083 //lyxerr << "\\" + *it << " ";
2084 globals.push_back("\\" + *it);
2086 //lyxerr << std::endl;
2088 // fill in global commands
2089 globals.push_back(from_ascii("\\boxed"));
2090 globals.push_back(from_ascii("\\fbox"));
2091 globals.push_back(from_ascii("\\framebox"));
2092 globals.push_back(from_ascii("\\makebox"));
2093 globals.push_back(from_ascii("\\kern"));
2094 globals.push_back(from_ascii("\\xrightarrow"));
2095 globals.push_back(from_ascii("\\xleftarrow"));
2096 globals.push_back(from_ascii("\\split"));
2097 globals.push_back(from_ascii("\\gathered"));
2098 globals.push_back(from_ascii("\\aligned"));
2099 globals.push_back(from_ascii("\\alignedat"));
2100 globals.push_back(from_ascii("\\cases"));
2101 globals.push_back(from_ascii("\\substack"));
2102 globals.push_back(from_ascii("\\xymatrix"));
2103 globals.push_back(from_ascii("\\Diagram"));
2104 globals.push_back(from_ascii("\\subarray"));
2105 globals.push_back(from_ascii("\\array"));
2106 globals.push_back(from_ascii("\\sqrt"));
2107 globals.push_back(from_ascii("\\root"));
2108 globals.push_back(from_ascii("\\tabular"));
2109 globals.push_back(from_ascii("\\stackrel"));
2110 globals.push_back(from_ascii("\\binom"));
2111 globals.push_back(from_ascii("\\choose"));
2112 globals.push_back(from_ascii("\\brace"));
2113 globals.push_back(from_ascii("\\brack"));
2114 globals.push_back(from_ascii("\\frac"));
2115 globals.push_back(from_ascii("\\over"));
2116 globals.push_back(from_ascii("\\nicefrac"));
2117 globals.push_back(from_ascii("\\unitfrac"));
2118 globals.push_back(from_ascii("\\unitfracthree"));
2119 globals.push_back(from_ascii("\\unitone"));
2120 globals.push_back(from_ascii("\\unittwo"));
2121 globals.push_back(from_ascii("\\infer"));
2122 globals.push_back(from_ascii("\\atop"));
2123 globals.push_back(from_ascii("\\lefteqn"));
2124 globals.push_back(from_ascii("\\boldsymbol"));
2125 globals.push_back(from_ascii("\\bm"));
2126 globals.push_back(from_ascii("\\color"));
2127 globals.push_back(from_ascii("\\normalcolor"));
2128 globals.push_back(from_ascii("\\textcolor"));
2129 globals.push_back(from_ascii("\\cfrac"));
2130 globals.push_back(from_ascii("\\cfracleft"));
2131 globals.push_back(from_ascii("\\cfracright"));
2132 globals.push_back(from_ascii("\\dfrac"));
2133 globals.push_back(from_ascii("\\tfrac"));
2134 globals.push_back(from_ascii("\\dbinom"));
2135 globals.push_back(from_ascii("\\tbinom"));
2136 globals.push_back(from_ascii("\\hphantom"));
2137 globals.push_back(from_ascii("\\phantom"));
2138 globals.push_back(from_ascii("\\vphantom"));
2139 globals.push_back(from_ascii("\\cancel"));
2140 globals.push_back(from_ascii("\\bcancel"));
2141 globals.push_back(from_ascii("\\xcancel"));
2142 globals.push_back(from_ascii("\\cancelto"));
2143 globals.push_back(from_ascii("\\smash"));
2144 globals.push_back(from_ascii("\\mathclap"));
2145 globals.push_back(from_ascii("\\mathllap"));
2146 globals.push_back(from_ascii("\\mathrlap"));
2147 MathWordList const & words = mathedWordList();
2148 MathWordList::const_iterator it2;
2149 //lyxerr << "Globals completion commands: ";
2150 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2151 globals.push_back("\\" + (*it2).first);
2152 //lyxerr << "\\" + (*it2).first << " ";
2154 //lyxerr << std::endl;
2155 sort(globals.begin(), globals.end());
2159 MathCompletionList::~MathCompletionList()
2164 size_type MathCompletionList::size() const
2166 return locals.size() + globals.size();
2170 docstring const & MathCompletionList::data(size_t idx) const
2172 size_t lsize = locals.size();
2174 return globals[idx - lsize];
2180 std::string MathCompletionList::icon(size_t idx) const
2182 // get the latex command
2184 size_t lsize = locals.size();
2186 cmd = globals[idx - lsize];
2190 // get the icon resource name by stripping the backslash
2191 return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
2194 std::vector<docstring> MathCompletionList::globals;