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 "BufferParams.h"
44 #include "BufferView.h"
45 #include "CoordCache.h"
47 #include "CutAndPaste.h"
48 #include "DispatchResult.h"
50 #include "FuncRequest.h"
51 #include "FuncStatus.h"
54 #include "OutputParams.h"
57 #include "frontends/Application.h"
58 #include "frontends/Clipboard.h"
59 #include "frontends/Painter.h"
60 #include "frontends/Selection.h"
62 #include "support/lassert.h"
63 #include "support/debug.h"
64 #include "support/gettext.h"
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
67 #include "support/docstream.h"
73 using namespace lyx::support;
77 using cap::copySelection;
78 using cap::grabAndEraseSelection;
79 using cap::cutSelection;
80 using cap::replaceSelection;
81 using cap::selClearOrDel;
84 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
85 : InsetMath(buf), cells_(nargs), lock_(false)
91 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
92 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
96 InsetMathNest::~InsetMathNest()
98 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
99 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
100 for (; it != end; ++it)
102 it->first->clearLastInset(this);
106 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
108 cells_ = inset.cells_;
110 mouse_hover_.clear();
111 InsetMath::operator=(inset);
116 void InsetMathNest::setBuffer(Buffer & buffer)
118 InsetMath::setBuffer(buffer);
119 for (idx_type i = 0, n = nargs(); i != n; ++i) {
120 MathData & data = cell(i);
121 for (size_t j = 0; j != data.size(); ++j)
122 data[j].nucleus()->setBuffer(buffer);
127 InsetMath::idx_type InsetMathNest::nargs() const
129 return cells_.size();
133 void InsetMathNest::cursorPos(BufferView const & bv,
134 CursorSlice const & sl, bool /*boundary*/,
135 int & x, int & y) const
137 // FIXME: This is a hack. Ideally, the coord cache should not store
138 // absolute positions, but relative ones. This would mean to call
139 // setXY() not in MathData::draw(), but in the parent insets' draw()
140 // with the correctly adjusted x,y values. But this means that we'd have
141 // to touch all (math)inset's draw() methods. Right now, we'll store
142 // absolute value, and make them here relative, only to make them
143 // absolute again when actually drawing the cursor. What a mess.
144 LASSERT(&sl.inset() == this, return);
145 MathData const & ar = sl.cell();
146 CoordCache const & coord_cache = bv.coordCache();
147 if (!coord_cache.getArrays().has(&ar)) {
148 // this can (semi-)legally happen if we just created this cell
149 // and it never has been drawn before. So don't ASSERT.
150 //lyxerr << "no cached data for array " << &ar << endl;
155 Point const pt = coord_cache.getArrays().xy(&ar);
156 if (!coord_cache.getInsets().has(this)) {
158 //lyxerr << "no cached data for inset " << this << endl;
163 Point const pt2 = coord_cache.getInsets().xy(this);
164 //lyxerr << "retrieving position cache for MathData "
165 // << pt.x_ << ' ' << pt.y_ << endl;
166 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
168 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
169 // << " asc: " << ascent() << " des: " << descent()
170 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
171 // move cursor visually into empty cells ("blue rectangles");
177 void InsetMathNest::metrics(MetricsInfo const & mi) const
180 for (idx_type i = 0, n = nargs(); i != n; ++i) {
182 cell(i).metrics(m, dim);
187 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
189 for (idx_type i = 0, n = nargs(); i != n; ++i)
190 cell(i).updateBuffer(it, utype);
195 bool InsetMathNest::idxNext(Cursor & cur) const
197 LASSERT(&cur.inset() == this, return false);
198 if (cur.idx() == cur.lastidx())
206 bool InsetMathNest::idxForward(Cursor & cur) const
212 bool InsetMathNest::idxPrev(Cursor & cur) const
214 LASSERT(&cur.inset() == this, return false);
218 cur.pos() = cur.lastpos();
223 bool InsetMathNest::idxBackward(Cursor & cur) const
229 bool InsetMathNest::idxFirst(Cursor & cur) const
231 LASSERT(&cur.inset() == this, return false);
240 bool InsetMathNest::idxLast(Cursor & cur) const
242 LASSERT(&cur.inset() == this, return false);
245 cur.idx() = cur.lastidx();
246 cur.pos() = cur.lastpos();
251 void InsetMathNest::dump() const
253 odocstringstream oss;
255 os << "---------------------------------------------\n";
258 for (idx_type i = 0, n = nargs(); i != n; ++i)
259 os << cell(i) << "\n";
260 os << "---------------------------------------------\n";
261 lyxerr << to_utf8(oss.str());
265 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
269 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
272 setPosCache(pi, x, y);
276 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
278 BufferView & bv = *pi.base.bv;
279 // this should use the x/y values given, not the cached values
280 Cursor & cur = bv.cursor();
281 if (!cur.selection())
283 if (&cur.inset() != this)
286 // FIXME: hack to get position cache warm
287 bool const original_drawing_state = pi.pain.isDrawingEnabled();
288 pi.pain.setDrawingEnabled(false);
290 pi.pain.setDrawingEnabled(original_drawing_state);
292 CursorSlice s1 = cur.selBegin();
293 CursorSlice s2 = cur.selEnd();
295 //lyxerr << "InsetMathNest::drawing selection: "
296 // << " s1: " << s1 << " s2: " << s2 << endl;
297 if (s1.idx() == s2.idx()) {
298 MathData const & c = cell(s1.idx());
299 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
300 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
301 int y1 = g.pos.y_ - g.dim.ascent();
302 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
303 int y2 = g.pos.y_ + g.dim.descent();
304 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
305 //lyxerr << "InsetMathNest::drawing selection 3: "
306 // << " x1: " << x1 << " x2: " << x2
307 // << " y1: " << y1 << " y2: " << y2 << endl;
309 for (idx_type i = 0; i < nargs(); ++i) {
310 if (idxBetween(i, s1.idx(), s2.idx())) {
311 MathData const & c = cell(i);
312 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
314 int y1 = g.pos.y_ - g.dim.ascent();
315 int x2 = g.pos.x_ + g.dim.width();
316 int y2 = g.pos.y_ + g.dim.descent();
317 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
324 void InsetMathNest::validate(LaTeXFeatures & features) const
326 for (idx_type i = 0; i < nargs(); ++i)
327 cell(i).validate(features);
331 void InsetMathNest::replace(ReplaceData & rep)
333 for (idx_type i = 0; i < nargs(); ++i)
334 cell(i).replace(rep);
338 bool InsetMathNest::contains(MathData const & ar) const
340 for (idx_type i = 0; i < nargs(); ++i)
341 if (cell(i).contains(ar))
347 bool InsetMathNest::lock() const
353 void InsetMathNest::lock(bool l)
359 bool InsetMathNest::isActive() const
365 MathData InsetMathNest::glue() const
368 for (size_t i = 0; i < nargs(); ++i)
374 void InsetMathNest::write(WriteStream & os) const
376 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
377 ModeSpecifier specifier(os, currentMode(), lockedMode());
378 docstring const latex_name = name();
379 os << '\\' << latex_name;
380 for (size_t i = 0; i < nargs(); ++i)
381 os << '{' << cell(i) << '}';
383 os.pendingSpace(true);
384 if (lock_ && !os.latex()) {
386 os.pendingSpace(true);
391 void InsetMathNest::normalize(NormalStream & os) const
394 for (size_t i = 0; i < nargs(); ++i)
395 os << ' ' << cell(i);
400 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
402 WriteStream wi(os.os(), runparams.moving_arg, true,
403 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
405 wi.canBreakLine(os.canBreakLine());
407 // Reset parbreak status after a math inset.
409 os.canBreakLine(wi.canBreakLine());
412 if (lf > 0 && runparams.lastid != -1) {
414 os.texrow().newline();
415 os.texrow().start(runparams.lastid, runparams.lastpos);
417 os.texrow().newlines(lf);
421 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
424 mouse_hover_[bv] = mouse_hover;
429 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
433 MathData & ar = cur.cell();
434 // remove base-only "scripts"
435 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
436 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
437 if (p && p->nargs() == 1) {
438 MathData ar = p->nuc();
441 cur.adjust(i, ar.size() - 1);
445 // glue adjacent font insets of the same kind
446 for (pos_type i = 0; i + 1 < size(); ++i) {
447 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
448 InsetMathFont const * q = operator[](i + 1)->asFontInset();
449 if (p && q && p->name() == q->name()) {
450 p->cell(0).append(q->cell(0));
460 void InsetMathNest::handleFont
461 (Cursor & cur, docstring const & arg, char const * const font)
463 handleFont(cur, arg, from_ascii(font));
467 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
468 docstring const & font)
470 cur.recordUndoSelection();
472 // this whole function is a hack and won't work for incremental font
474 if (cur.inset().asInsetMath()->name() == font)
475 cur.handleFont(to_utf8(font));
477 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
481 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
483 handleNest(cur, nest, docstring());
487 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
488 docstring const & arg)
490 CursorSlice i1 = cur.selBegin();
491 CursorSlice i2 = cur.selEnd();
492 if (!i1.inset().asInsetMath())
494 if (i1.idx() == i2.idx()) {
495 // the easy case where only one cell is selected
496 cur.handleNest(nest);
501 // multiple selected cells in a simple non-grid inset
502 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
503 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
508 cur.pos() = cur.lastpos();
511 // change font of cell
512 cur.handleNest(nest);
515 // cur is in the font inset now. If the loop continues,
516 // we need to get outside again for the next cell
517 if (i + 1 <= i2.idx())
523 // the complicated case with multiple selected cells in a grid
526 cap::region(i1, i2, r1, r2, c1, c2);
527 for (row_type row = r1; row <= r2; ++row) {
528 for (col_type col = c1; col <= c2; ++col) {
530 cur.idx() = i1.asInsetMath()->index(row, col);
533 cur.pos() = cur.lastpos();
537 cur.handleNest(nest);
540 // cur is in the font inset now. If the loop continues,
541 // we need to get outside again for the next cell
542 if (col + 1 <= c2 || row + 1 <= r2)
549 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
551 cur.recordUndoSelection();
554 font.fromString(to_utf8(arg), b);
555 if (font.fontInfo().color() != Color_inherit &&
556 font.fontInfo().color() != Color_ignore)
557 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
559 // FIXME: support other font changes here as well?
563 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
565 //LYXERR0("InsetMathNest: request: " << cmd);
567 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
569 FuncCode const act = cmd.action();
572 case LFUN_CLIPBOARD_PASTE:
573 parseflg |= Parse::VERBATIM;
576 if (cur.currentMode() <= TEXT_MODE)
577 parseflg |= Parse::TEXTMODE;
578 cur.recordUndoSelection();
579 cur.message(_("Paste"));
580 replaceSelection(cur);
582 if (cmd.argument().empty() && !theClipboard().isInternal())
583 topaste = theClipboard().getAsText(Clipboard::PlainTextType);
586 idocstringstream is(cmd.argument());
588 topaste = cap::selection(n, buffer().params().documentClassPtr());
590 cur.niceInsert(topaste, parseflg, false);
591 cur.clearSelection(); // bug 393
592 cur.forceBufferUpdate();
599 cutSelection(cur, true, true);
600 cur.message(_("Cut"));
601 // Prevent stale position >= size crash
602 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
604 cur.forceBufferUpdate();
609 cur.message(_("Copy"));
612 case LFUN_MOUSE_PRESS:
613 lfunMousePress(cur, cmd);
616 case LFUN_MOUSE_MOTION:
617 lfunMouseMotion(cur, cmd);
620 case LFUN_MOUSE_RELEASE:
621 lfunMouseRelease(cur, cmd);
624 case LFUN_FINISHED_LEFT: // in math, left is backwards
625 case LFUN_FINISHED_BACKWARD:
626 cur.bv().cursor() = cur;
629 case LFUN_FINISHED_RIGHT: // in math, right is forward
630 case LFUN_FINISHED_FORWARD:
632 cur.bv().cursor() = cur;
635 case LFUN_CHAR_RIGHT:
637 case LFUN_CHAR_BACKWARD:
638 case LFUN_CHAR_FORWARD:
639 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
640 case LFUN_CHAR_RIGHT_SELECT:
641 case LFUN_CHAR_LEFT_SELECT:
642 case LFUN_CHAR_BACKWARD_SELECT:
643 case LFUN_CHAR_FORWARD_SELECT: {
644 // are we in a selection?
645 bool select = (act == LFUN_CHAR_RIGHT_SELECT
646 || act == LFUN_CHAR_LEFT_SELECT
647 || act == LFUN_CHAR_BACKWARD_SELECT
648 || act == LFUN_CHAR_FORWARD_SELECT);
649 // are we moving forward or backwards?
650 // If the command was RIGHT or LEFT, then whether we're moving forward
651 // or backwards depends on the cursor movement mode (logical or visual):
652 // * in visual mode, since math is always LTR, right -> forward,
654 // * in logical mode, the mapping is determined by the
655 // reverseDirectionNeeded() function
658 FuncCode finish_lfun;
660 if (act == LFUN_CHAR_FORWARD
661 || act == LFUN_CHAR_FORWARD_SELECT) {
663 finish_lfun = LFUN_FINISHED_FORWARD;
665 else if (act == LFUN_CHAR_BACKWARD
666 || act == LFUN_CHAR_BACKWARD_SELECT) {
668 finish_lfun = LFUN_FINISHED_BACKWARD;
671 bool right = (act == LFUN_CHAR_RIGHT_SELECT
672 || act == LFUN_CHAR_RIGHT);
673 if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
679 finish_lfun = LFUN_FINISHED_RIGHT;
681 finish_lfun = LFUN_FINISHED_LEFT;
683 // Now that we know exactly what we want to do, let's do it!
684 cur.selHandle(select);
686 cur.macroModeClose();
687 // try moving forward or backwards as necessary...
688 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
689 // ... and if movement failed, then finish forward or backwards
691 cmd = FuncRequest(finish_lfun);
699 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
700 case LFUN_DOWN_SELECT:
701 case LFUN_UP_SELECT: {
702 // close active macro
703 if (cur.inMacroMode()) {
704 cur.macroModeClose();
708 // stop/start the selection
709 bool select = act == LFUN_DOWN_SELECT ||
710 act == LFUN_UP_SELECT;
711 cur.selHandle(select);
713 // handle autocorrect:
714 cur.autocorrect() = false;
715 cur.message(_("Autocorrect Off ('!' to enter)"));
718 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
719 bool successful = cur.upDownInMath(up);
723 if (cur.fixIfBroken())
724 // FIXME: Something bad happened. We pass the corrected Cursor
725 // instead of letting things go worse.
728 // We did not manage to move the cursor.
733 case LFUN_MOUSE_DOUBLE:
734 case LFUN_MOUSE_TRIPLE:
735 case LFUN_WORD_SELECT:
739 cur.setSelection(true);
740 cur.idx() = cur.lastidx();
741 cur.pos() = cur.lastpos();
742 cur.bv().cursor() = cur;
745 case LFUN_PARAGRAPH_UP:
746 case LFUN_PARAGRAPH_DOWN:
747 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
748 case LFUN_PARAGRAPH_UP_SELECT:
749 case LFUN_PARAGRAPH_DOWN_SELECT:
752 case LFUN_LINE_BEGIN:
753 case LFUN_WORD_BACKWARD:
755 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
756 case LFUN_LINE_BEGIN_SELECT:
757 case LFUN_WORD_BACKWARD_SELECT:
758 case LFUN_WORD_LEFT_SELECT:
759 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
760 act == LFUN_WORD_LEFT_SELECT ||
761 act == LFUN_LINE_BEGIN_SELECT);
762 cur.macroModeClose();
763 if (cur.pos() != 0) {
765 } else if (cur.col() != 0) {
766 cur.idx() -= cur.col();
768 } else if (cur.idx() != 0) {
772 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
777 case LFUN_WORD_FORWARD:
778 case LFUN_WORD_RIGHT:
780 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
781 case LFUN_WORD_FORWARD_SELECT:
782 case LFUN_WORD_RIGHT_SELECT:
783 case LFUN_LINE_END_SELECT:
784 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
785 act == LFUN_WORD_RIGHT_SELECT ||
786 act == LFUN_LINE_END_SELECT);
787 cur.macroModeClose();
789 if (cur.pos() != cur.lastpos()) {
790 cur.pos() = cur.lastpos();
791 } else if (ncols() && (cur.col() != cur.lastcol())) {
792 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
793 cur.pos() = cur.lastpos();
794 } else if (cur.idx() != cur.lastidx()) {
795 cur.idx() = cur.lastidx();
796 cur.pos() = cur.lastpos();
798 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
803 case LFUN_CELL_FORWARD:
804 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
805 cur.inset().idxNext(cur);
808 case LFUN_CELL_BACKWARD:
809 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
810 cur.inset().idxPrev(cur);
813 case LFUN_WORD_DELETE_BACKWARD:
814 case LFUN_CHAR_DELETE_BACKWARD:
816 // May affect external cell:
817 cur.recordUndoInset();
818 else if (!cur.inMacroMode())
819 cur.recordUndoSelection();
820 // if the inset can not be removed from within, delete it
821 if (!cur.backspace()) {
822 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
823 cur.innerText()->dispatch(cur, cmd);
827 case LFUN_WORD_DELETE_FORWARD:
828 case LFUN_CHAR_DELETE_FORWARD:
829 if (cur.pos() == cur.lastpos())
830 // May affect external cell:
831 cur.recordUndoInset();
833 cur.recordUndoSelection();
834 // if the inset can not be removed from within, delete it
836 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
837 cur.innerText()->dispatch(cur, cmd);
843 cur.clearSelection();
845 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
850 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
851 // that is traversed by a single <CursorLeft>/<CursorRight>.
852 case LFUN_INSET_TOGGLE:
858 case LFUN_SELF_INSERT:
859 if (cmd.argument().size() != 1) {
860 cur.recordUndoSelection();
861 docstring const arg = cmd.argument();
862 if (!interpretString(cur, arg))
866 // Don't record undo steps if we are in macro mode and thus
867 // cmd.argument is the next character of the macro name.
868 // Otherwise we'll get an invalid cursor if we undo after
869 // the macro was finished and the macro is a known command,
870 // e.g. sqrt. Cursor::macroModeClose replaces in this case
871 // the InsetMathUnknown with name "frac" by an empty
872 // InsetMathFrac -> a pos value > 0 is invalid.
873 // A side effect is that an undo before the macro is finished
874 // undoes the complete macro, not only the last character.
875 // At the time we hit '\' we are not in macro mode, still.
876 if (!cur.inMacroMode())
877 cur.recordUndoSelection();
879 // spacial handling of space. If we insert an inset
880 // via macro mode, we want to put the cursor inside it
881 // if relevant. Think typing "\frac<space>".
882 if (cmd.argument()[0] == ' '
883 && cur.inMacroMode() && cur.macroName() != "\\"
884 && cur.macroModeClose() && cur.pos() > 0) {
885 MathAtom const atom = cur.prevAtom();
886 if (atom->asNestInset() && atom->isActive()) {
888 cur.pushBackward(*cur.nextInset());
890 } else if (!interpretChar(cur, cmd.argument()[0])) {
891 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
896 //case LFUN_SERVER_GET_XY:
899 case LFUN_SERVER_SET_XY: {
900 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
903 istringstream is(to_utf8(cmd.argument()));
905 cur.setScreenPos(x, y);
909 // Special casing for superscript in case of LyX handling
911 case LFUN_ACCENT_CIRCUMFLEX:
912 if (cmd.argument().empty()) {
913 // do superscript if LyX handles
915 cur.recordUndoSelection();
916 script(cur, true, grabAndEraseSelection(cur));
920 case LFUN_ACCENT_UMLAUT:
921 case LFUN_ACCENT_ACUTE:
922 case LFUN_ACCENT_GRAVE:
923 case LFUN_ACCENT_BREVE:
924 case LFUN_ACCENT_DOT:
925 case LFUN_ACCENT_MACRON:
926 case LFUN_ACCENT_CARON:
927 case LFUN_ACCENT_TILDE:
928 case LFUN_ACCENT_CEDILLA:
929 case LFUN_ACCENT_CIRCLE:
930 case LFUN_ACCENT_UNDERDOT:
931 case LFUN_ACCENT_TIE:
932 case LFUN_ACCENT_OGONEK:
933 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
937 case LFUN_TEXTSTYLE_APPLY:
938 case LFUN_TEXTSTYLE_UPDATE:
939 handleFont2(cur, cmd.argument());
943 if (currentMode() <= TEXT_MODE)
944 handleFont(cur, cmd.argument(), "textbf");
946 handleFont(cur, cmd.argument(), "mathbf");
948 case LFUN_FONT_BOLDSYMBOL:
949 if (currentMode() <= TEXT_MODE)
950 handleFont(cur, cmd.argument(), "textbf");
952 handleFont(cur, cmd.argument(), "boldsymbol");
955 if (currentMode() <= TEXT_MODE)
956 handleFont(cur, cmd.argument(), "textsf");
958 handleFont(cur, cmd.argument(), "mathsf");
961 if (currentMode() <= TEXT_MODE)
962 handleFont(cur, cmd.argument(), "emph");
964 handleFont(cur, cmd.argument(), "mathcal");
966 case LFUN_FONT_ROMAN:
967 if (currentMode() <= TEXT_MODE)
968 handleFont(cur, cmd.argument(), "textrm");
970 handleFont(cur, cmd.argument(), "mathrm");
972 case LFUN_FONT_TYPEWRITER:
973 if (currentMode() <= TEXT_MODE)
974 handleFont(cur, cmd.argument(), "texttt");
976 handleFont(cur, cmd.argument(), "mathtt");
979 handleFont(cur, cmd.argument(), "mathfrak");
982 if (currentMode() <= TEXT_MODE)
983 handleFont(cur, cmd.argument(), "textit");
985 handleFont(cur, cmd.argument(), "mathit");
988 if (currentMode() <= TEXT_MODE)
989 // FIXME: should be "noun"
990 handleFont(cur, cmd.argument(), "textsc");
992 handleFont(cur, cmd.argument(), "mathbb");
994 case LFUN_FONT_DEFAULT:
995 handleFont(cur, cmd.argument(), "textnormal");
998 case LFUN_FONT_UNDERLINE:
1000 cur.handleNest(createInsetMath("underline", cur.buffer()));
1002 case LFUN_MATH_MODE: {
1004 // ignore math-mode on when already in math mode
1005 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1007 cur.recordUndoSelection();
1008 cur.macroModeClose();
1009 docstring const save_selection = grabAndEraseSelection(cur);
1011 if (currentMode() <= Inset::TEXT_MODE)
1012 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1014 cur.plainInsert(MathAtom(new InsetMathBox(buffer_, from_ascii("mbox"))));
1016 cur.pushBackward(*cur.nextInset());
1017 cur.niceInsert(save_selection);
1018 cur.forceBufferUpdate();
1020 if (currentMode() == Inset::TEXT_MODE) {
1021 cur.recordUndoSelection();
1022 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1023 cur.message(_("create new math text environment ($...$)"));
1025 handleFont(cur, cmd.argument(), "textrm");
1026 cur.message(_("entered math text mode (textrm)"));
1032 case LFUN_REGEXP_MODE: {
1033 InsetMath * im = cur.inset().asInsetMath();
1035 InsetMathHull * i = im->asHullInset();
1036 if (i && i->getType() == hullRegexp) {
1037 cur.message(_("Already in regular expression mode"));
1041 cur.macroModeClose();
1042 docstring const save_selection = grabAndEraseSelection(cur);
1044 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1046 cur.pushBackward(*cur.nextInset());
1047 cur.niceInsert(save_selection);
1048 cur.message(_("Regular expression editor mode"));
1052 case LFUN_MATH_FONT_STYLE: {
1053 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1054 doDispatch(cur, fr);
1058 case LFUN_MATH_SIZE: {
1059 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1060 doDispatch(cur, fr);
1064 case LFUN_MATH_MATRIX: {
1070 idocstringstream is(cmd.argument());
1071 is >> m >> n >> v_align >> h_align;
1077 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1078 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1082 case LFUN_MATH_AMS_MATRIX: {
1086 docstring name = from_ascii("matrix");
1087 idocstringstream is(cmd.argument());
1088 is >> m >> n >> name;
1093 // check if we have a valid decoration
1094 if (name != "pmatrix" && name != "bmatrix"
1095 && name != "Bmatrix" && name != "vmatrix"
1096 && name != "Vmatrix" && name != "matrix")
1097 name = from_ascii("matrix");
1100 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1104 case LFUN_MATH_DELIM: {
1106 docstring rs = split(cmd.argument(), ls, ' ');
1107 // Reasonable default values
1113 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1117 case LFUN_MATH_BIGDELIM: {
1118 docstring const lname = from_utf8(cmd.getArg(0));
1119 docstring const ldelim = from_utf8(cmd.getArg(1));
1120 docstring const rname = from_utf8(cmd.getArg(2));
1121 docstring const rdelim = from_utf8(cmd.getArg(3));
1122 latexkeys const * l = in_word_set(lname);
1123 bool const have_l = l && l->inset == "big" &&
1124 InsetMathBig::isBigInsetDelim(ldelim);
1125 l = in_word_set(rname);
1126 bool const have_r = l && l->inset == "big" &&
1127 InsetMathBig::isBigInsetDelim(rdelim);
1128 // We mimic LFUN_MATH_DELIM in case we have an empty left
1129 // or right delimiter.
1130 if (have_l || have_r) {
1132 docstring const selection = grabAndEraseSelection(cur);
1135 cur.insert(MathAtom(new InsetMathBig(lname,
1137 // first insert the right delimiter and then go back
1138 // and re-insert the selection (bug 7088)
1140 cur.insert(MathAtom(new InsetMathBig(rname,
1144 cur.niceInsert(selection);
1146 // Don't call cur.undispatched() if we did nothing, this would
1147 // lead to infinite recursion via Text::dispatch().
1151 case LFUN_SPACE_INSERT: {
1152 cur.recordUndoSelection();
1153 string const name = cmd.getArg(0);
1154 if (name == "normal")
1155 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1156 else if (name == "protected")
1157 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1158 else if (name == "thin" || name == "med" || name == "thick")
1159 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1160 else if (name == "hfill*")
1161 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1162 else if (name == "quad" || name == "qquad" ||
1163 name == "enspace" || name == "enskip" ||
1164 name == "negthinspace" || name == "negmedspace" ||
1165 name == "negthickspace" || name == "hfill")
1166 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1167 else if (name == "hspace" || name == "hspace*") {
1168 string const len = cmd.getArg(1);
1169 if (len.empty() || !isValidLength(len)) {
1170 lyxerr << "LyX function 'space-insert " << name << "' "
1171 "needs a valid length argument." << endl;
1174 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1176 cur.insert(MathAtom(new InsetMathSpace));
1180 case LFUN_MATH_SPACE:
1181 cur.recordUndoSelection();
1182 if (cmd.argument().empty())
1183 cur.insert(MathAtom(new InsetMathSpace));
1185 string const name = cmd.getArg(0);
1186 string const len = cmd.getArg(1);
1187 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1191 case LFUN_ERT_INSERT:
1192 // interpret this as if a backslash was typed
1194 interpretChar(cur, '\\');
1197 case LFUN_MATH_SUBSCRIPT:
1198 // interpret this as if a _ was typed
1199 cur.recordUndoSelection();
1200 interpretChar(cur, '_');
1203 case LFUN_MATH_SUPERSCRIPT:
1204 // interpret this as if a ^ was typed
1205 cur.recordUndoSelection();
1206 interpretChar(cur, '^');
1209 case LFUN_MATH_MACRO_FOLD:
1210 case LFUN_MATH_MACRO_UNFOLD: {
1212 bool fold = act == LFUN_MATH_MACRO_FOLD;
1213 bool found = findMacroToFoldUnfold(it, fold);
1215 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1216 cur.recordUndoInset();
1225 case LFUN_QUOTE_INSERT:
1226 // interpret this as if a straight " was typed
1227 cur.recordUndoSelection();
1228 interpretChar(cur, '\"');
1231 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1232 // handling such that "self-insert" works on "arbitrary stuff" too, and
1233 // math-insert only handles special math things like "matrix".
1234 case LFUN_MATH_INSERT: {
1235 cur.recordUndoSelection();
1236 if (cmd.argument() == "^" || cmd.argument() == "_")
1237 interpretChar(cur, cmd.argument()[0]);
1240 asArray(cmd.argument(), ar);
1241 if (cur.selection() && ar.size() == 1
1242 && ar[0]->asNestInset()
1243 && ar[0]->asNestInset()->nargs() > 1)
1244 handleNest(cur, ar[0]);
1246 cur.niceInsert(cmd.argument());
1251 case LFUN_UNICODE_INSERT: {
1252 if (cmd.argument().empty())
1254 docstring hexstring = cmd.argument();
1255 if (isHex(hexstring)) {
1256 char_type c = hexToInt(hexstring);
1257 if (c >= 32 && c < 0x10ffff) {
1258 docstring s = docstring(1, c);
1259 FuncCode code = currentMode() == MATH_MODE ?
1260 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1261 lyx::dispatch(FuncRequest(code, s));
1267 case LFUN_DIALOG_SHOW_NEW_INSET: {
1268 docstring const & name = cmd.argument();
1270 if (name == "ref") {
1271 InsetMathRef tmp(buffer_, name);
1272 data = tmp.createDialogStr();
1273 cur.bv().showDialog(to_utf8(name), data);
1274 } else if (name == "mathspace") {
1275 cur.bv().showDialog(to_utf8(name));
1280 case LFUN_INSET_INSERT: {
1282 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1283 cur.recordUndoSelection();
1285 cur.forceBufferUpdate();
1290 case LFUN_INSET_DISSOLVE:
1291 if (!asHullInset()) {
1292 cur.recordUndoInset();
1298 InsetMath::doDispatch(cur, cmd);
1304 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1305 // look for macro to open/close, but stay in mathed
1306 for (; !it.empty(); it.pop_back()) {
1308 // go backward through the current cell
1309 Inset * inset = it.nextInset();
1310 while (inset && inset->asInsetMath()) {
1311 MathMacro * macro = inset->asInsetMath()->asMacro();
1313 // found the an macro to open/close?
1314 if (macro->folded() != fold)
1317 // Wrong folding state.
1318 // If this was the first we see in this slice, look further left,
1320 if (inset != it.nextInset())
1324 // go up if this was the left most position
1330 inset = it.nextInset();
1338 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1339 FuncStatus & flag) const
1341 // the font related toggles
1342 //string tc = "mathnormal";
1344 string const arg = to_utf8(cmd.argument());
1345 switch (cmd.action()) {
1346 case LFUN_INSET_MODIFY:
1347 flag.setEnabled(false);
1350 case LFUN_INSET_MODIFY:
1351 // FIXME: check temporarily disabled
1353 char align = mathcursor::valign();
1354 if (align == '\0') {
1358 if (cmd.argument().empty()) {
1362 if (!contains("tcb", cmd.argument()[0])) {
1366 flag.setOnOff(cmd.argument()[0] == align);
1369 /// We have to handle them since 1.4 blocks all unhandled actions
1370 case LFUN_FONT_ITAL:
1371 case LFUN_FONT_BOLD:
1372 case LFUN_FONT_BOLDSYMBOL:
1373 case LFUN_FONT_SANS:
1374 case LFUN_FONT_EMPH:
1375 case LFUN_FONT_TYPEWRITER:
1376 case LFUN_FONT_NOUN:
1377 case LFUN_FONT_ROMAN:
1378 case LFUN_FONT_DEFAULT:
1379 flag.setEnabled(true);
1382 // we just need to be in math mode to enable that
1383 case LFUN_MATH_SIZE:
1384 case LFUN_MATH_SPACE:
1385 case LFUN_MATH_EXTERN:
1386 flag.setEnabled(true);
1389 case LFUN_FONT_UNDERLINE:
1390 case LFUN_FONT_FRAK:
1391 flag.setEnabled(currentMode() != TEXT_MODE);
1394 case LFUN_MATH_FONT_STYLE: {
1395 bool const textarg =
1396 arg == "textbf" || arg == "textsf" ||
1397 arg == "textrm" || arg == "textmd" ||
1398 arg == "textit" || arg == "textsc" ||
1399 arg == "textsl" || arg == "textup" ||
1400 arg == "texttt" || arg == "textbb" ||
1401 arg == "textnormal";
1402 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1406 case LFUN_MATH_MODE:
1407 // forbid "math-mode on" in math mode to prevent irritating
1408 // behaviour of menu entries (bug 6709)
1409 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1412 case LFUN_MATH_INSERT:
1413 flag.setEnabled(currentMode() != TEXT_MODE);
1416 case LFUN_MATH_AMS_MATRIX:
1417 case LFUN_MATH_MATRIX:
1418 flag.setEnabled(currentMode() == MATH_MODE);
1421 case LFUN_INSET_INSERT: {
1422 // Don't test createMathInset_fromDialogStr(), since
1423 // getStatus is not called with a valid reference and the
1424 // dialog would not be applyable.
1425 string const name = cmd.getArg(0);
1426 flag.setEnabled(name == "ref" || name == "mathspace");
1430 case LFUN_DIALOG_SHOW_NEW_INSET: {
1431 docstring const & name = cmd.argument();
1432 if (name == "space")
1433 flag.setEnabled(false);
1438 case LFUN_MATH_DELIM:
1439 case LFUN_MATH_BIGDELIM:
1440 // Don't do this with multi-cell selections
1441 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1444 case LFUN_MATH_MACRO_FOLD:
1445 case LFUN_MATH_MACRO_UNFOLD: {
1447 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1448 flag.setEnabled(found);
1452 case LFUN_SPECIALCHAR_INSERT:
1453 case LFUN_SCRIPT_INSERT:
1454 // FIXME: These would probably make sense in math-text mode
1455 flag.setEnabled(false);
1458 case LFUN_CAPTION_INSERT:
1459 flag.setEnabled(false);
1462 case LFUN_SPACE_INSERT: {
1463 docstring const & name = cmd.argument();
1464 if (name == "visible")
1465 flag.setEnabled(false);
1469 case LFUN_INSET_DISSOLVE:
1470 flag.setEnabled(!asHullInset());
1474 docstring const & name = cmd.argument();
1475 if (name == "html" || name == "latex")
1476 flag.setEnabled(false);
1488 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1491 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1492 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1493 cur.idx() = enter_front ? 0 : cur.lastidx();
1494 cur.pos() = enter_front ? 0 : cur.lastpos();
1496 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1500 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1503 int dist_min = 1000000;
1504 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1505 int const d = cell(i).dist(cur.bv(), x, y);
1511 MathData & ar = cell(idx_min);
1513 cur.idx() = idx_min;
1514 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1516 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1517 if (dist_min == 0) {
1519 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1520 if (ar[i]->covers(cur.bv(), x, y))
1521 return ar[i].nucleus()->editXY(cur, x, y);
1527 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1529 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1530 BufferView & bv = cur.bv();
1531 if (cmd.button() == mouse_button::button3) {
1532 // Don't do anything if we right-click a
1533 // selection, a context menu will popup.
1534 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1535 && cur < bv.cursor().selectionEnd()) {
1536 cur.noScreenUpdate();
1540 bool do_selection = cmd.button() == mouse_button::button1
1541 && cmd.argument() == "region-select";
1542 bv.mouseSetCursor(cur, do_selection);
1543 if (cmd.button() == mouse_button::button1) {
1544 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1545 // Update the cursor update flags as needed:
1547 // Update::Decoration: tells to update the decoration
1548 // (visual box corners that define
1550 // Update::FitCursor: adjust the screen to the cursor
1551 // position if needed
1552 // cur.result().update(): don't overwrite previously set flags.
1553 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1554 | cur.result().screenUpdate());
1555 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1556 if (cap::selection()) {
1557 // See comment in Text::dispatch why we do this
1558 cap::copySelectionToStack();
1559 cmd = FuncRequest(LFUN_PASTE, "0");
1560 doDispatch(bv.cursor(), cmd);
1563 asArray(theSelection().get(), ar);
1564 bv.cursor().insert(ar);
1570 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1572 // only select with button 1
1573 if (cmd.button() != mouse_button::button1)
1576 Cursor & bvcur = cur.bv().cursor();
1578 // ignore motions deeper nested than the real anchor
1579 if (!bvcur.realAnchor().hasPart(cur)) {
1584 CursorSlice old = bvcur.top();
1586 // We continue with our existing selection or start a new one, so don't
1587 // reset the anchor.
1588 bvcur.setCursor(cur);
1589 // Did we actually move?
1590 if (cur.top() == old)
1591 // We didn't move one iota, so no need to change selection status
1592 // or update the screen.
1593 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1595 bvcur.setSelection();
1599 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1601 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1603 if (cmd.button() == mouse_button::button1) {
1604 if (!cur.selection())
1605 cur.noScreenUpdate();
1607 Cursor & bvcur = cur.bv().cursor();
1608 bvcur.setSelection(true);
1617 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1619 //lyxerr << "interpret 2: '" << c << "'" << endl;
1620 docstring save_selection;
1621 if (c == '^' || c == '_')
1622 save_selection = grabAndEraseSelection(cur);
1625 Buffer * buf = cur.buffer();
1628 if (cur.inMacroMode()) {
1629 docstring name = cur.macroName();
1631 /// are we currently typing '#1' or '#2' or...?
1632 if (name == "\\#") {
1635 if (n >= 1 && n <= 9)
1636 cur.insert(new MathMacroArgument(n));
1640 // do not finish macro for known * commands
1641 bool star_macro = c == '*'
1642 && (in_word_set(name.substr(1) + '*')
1643 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1644 if (isAlphaASCII(c) || star_macro) {
1645 cur.activeMacro()->setName(name + docstring(1, c));
1649 // handle 'special char' macros
1654 if (currentMode() <= InsetMath::TEXT_MODE)
1655 cur.niceInsert(createInsetMath("textbackslash", buf));
1657 cur.niceInsert(createInsetMath("backslash", buf));
1658 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1660 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1661 } else if (c == '{') {
1663 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1664 } else if (c == '%') {
1666 cur.niceInsert(MathAtom(new InsetMathComment(buf)));
1667 } else if (c == '#') {
1668 LASSERT(cur.activeMacro(), return false);
1669 cur.activeMacro()->setName(name + docstring(1, c));
1672 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1677 // One character big delimiters. The others are handled in
1678 // interpretString().
1679 latexkeys const * l = in_word_set(name.substr(1));
1680 if (name[0] == '\\' && l && l->inset == "big") {
1684 delim = from_ascii("\\{");
1687 delim = from_ascii("\\}");
1690 delim = docstring(1, c);
1693 if (InsetMathBig::isBigInsetDelim(delim)) {
1694 // name + delim ared a valid InsetMathBig.
1695 // We can't use cur.macroModeClose() because
1696 // it does not handle delim.
1697 InsetMathUnknown * p = cur.activeMacro();
1700 cur.cell().erase(cur.pos());
1701 cur.plainInsert(MathAtom(
1702 new InsetMathBig(name.substr(1), delim)));
1705 } else if (name == "\\smash" && c == '[') {
1706 // We can't use cur.macroModeClose() because
1707 // it would create an InsetMathPhantom
1708 InsetMathUnknown * p = cur.activeMacro();
1710 interpretChar(cur, c);
1714 // leave macro mode and try again if necessary
1715 if (cur.macroModeClose()) {
1716 MathAtom const atom = cur.prevAtom();
1717 if (atom->asNestInset() && atom->isActive()) {
1719 cur.pushBackward(*cur.nextInset());
1723 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1725 interpretChar(cur, c);
1730 // leave autocorrect mode if necessary
1731 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1732 cur.autocorrect() = false;
1733 cur.message(_("Autocorrect Off ('!' to enter)"));
1736 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1737 cur.autocorrect() = true;
1738 cur.message(_("Autocorrect On (<space> to exit)"));
1742 // just clear selection on pressing the space bar
1743 if (cur.selection() && c == ' ') {
1744 cur.setSelection(false);
1749 //lyxerr << "starting with macro" << endl;
1750 bool reduced = cap::reduceSelectionToOneCell(cur);
1751 if (reduced || !cur.selection()) {
1752 cur.recordUndoInset();
1753 docstring const safe = cap::grabAndEraseSelection(cur);
1754 if (!cur.inRegexped())
1755 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1757 cur.niceInsert(createInsetMath("backslash", buf));
1765 if (currentMode() <= InsetMath::TEXT_MODE)
1771 if (currentMode() <= InsetMath::TEXT_MODE) {
1772 // insert spaces in text or undecided mode,
1773 // but suppress direct insertion of two spaces in a row
1774 // the still allows typing '<space>a<space>' and deleting the 'a', but
1775 // it is better than nothing...
1776 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1778 // FIXME: we have to enable full redraw here because of the
1779 // visual box corners that define the inset. If we know for
1780 // sure that we stay within the same cell we can optimize for
1782 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1786 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1787 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1788 // FIXME: we have to enable full redraw here because of the
1789 // visual box corners that define the inset. If we know for
1790 // sure that we stay within the same cell we can optimize for
1792 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1796 if (cur.popForward()) {
1797 // FIXME: we have to enable full redraw here because of the
1798 // visual box corners that define the inset. If we know for
1799 // sure that we stay within the same cell we can optimize for
1801 //cur.screenUpdateFlags(Update::FitCursor);
1805 // if we are at the very end, leave the formula
1806 return cur.pos() != cur.lastpos();
1809 // These should be treated differently when not in text mode:
1810 if (cur.inRegexped()) {
1813 cur.niceInsert(createInsetMath("backslash", buf));
1816 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1823 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1826 cur.niceInsert(createInsetMath("sim", buf));
1832 } else if (currentMode() != InsetMath::TEXT_MODE) {
1834 script(cur, false, save_selection);
1838 script(cur, true, save_selection);
1842 cur.niceInsert(createInsetMath("sim", buf));
1845 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1846 MathAtom at = createInsetMath("text", buf);
1847 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1854 cur.niceInsert(createInsetMath("textasciicircum", buf));
1858 cur.niceInsert(createInsetMath("textasciitilde", buf));
1863 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1864 c == '%' || c == '_') {
1865 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1870 // try auto-correction
1871 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1872 && math_autocorrect(cur.prevAtom(), c))
1875 // no special circumstances, so insert the character without any fuss
1877 if (lyxrc.autocorrection_math) {
1878 if (!cur.autocorrect())
1879 cur.message(_("Autocorrect Off ('!' to enter)"));
1881 cur.message(_("Autocorrect On (<space> to exit)"));
1887 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1889 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1891 if (!cur.empty() && cur.pos() > 0 &&
1892 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1893 if (InsetMathBig::isBigInsetDelim(str)) {
1894 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1895 if (prev[0] == '\\') {
1896 prev = prev.substr(1);
1897 latexkeys const * l = in_word_set(prev);
1898 if (l && l->inset == "big") {
1899 cur.cell()[cur.pos() - 1] =
1900 MathAtom(new InsetMathBig(prev, str));
1910 bool InsetMathNest::script(Cursor & cur, bool up)
1912 return script(cur, up, docstring());
1916 bool InsetMathNest::script(Cursor & cur, bool up,
1917 docstring const & save_selection)
1919 // Hack to get \^ and \_ working
1920 //lyxerr << "handling script: up: " << up << endl;
1921 if (cur.inMacroMode() && cur.macroName() == "\\") {
1923 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1925 interpretChar(cur, '_');
1929 cur.macroModeClose();
1930 if (asScriptInset() && cur.idx() == 0) {
1931 // we are in a nucleus of a script inset, move to _our_ script
1932 InsetMathScript * inset = asScriptInset();
1933 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1935 cur.idx() = inset->idxOfScript(up);
1937 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1939 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1942 cur.idx() = inset->idxOfScript(up);
1943 cur.pos() = cur.lastpos();
1945 // convert the thing to our left to a scriptinset or create a new
1946 // one if in the very first position of the array
1947 if (cur.pos() == 0) {
1948 //lyxerr << "new scriptinset" << endl;
1949 cur.insert(new InsetMathScript(buffer_, up));
1951 //lyxerr << "converting prev atom " << endl;
1952 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1955 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1956 // See comment in MathParser.cpp for special handling of {}-bases
1962 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1963 cur.niceInsert(save_selection);
1965 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1970 bool InsetMathNest::completionSupported(Cursor const & cur) const
1972 return cur.inMacroMode();
1976 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1978 return cur.inMacroMode();
1982 bool InsetMathNest::automaticInlineCompletion() const
1984 return lyxrc.completion_inline_math;
1988 bool InsetMathNest::automaticPopupCompletion() const
1990 return lyxrc.completion_popup_math;
1994 CompletionList const *
1995 InsetMathNest::createCompletionList(Cursor const & cur) const
1997 if (!cur.inMacroMode())
2000 return new MathCompletionList(cur);
2004 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2006 if (!cur.inMacroMode())
2009 return cur.activeMacro()->name();
2013 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2016 if (!cur.inMacroMode())
2019 // append completion to active macro
2020 InsetMathUnknown * inset = cur.activeMacro();
2021 inset->setName(inset->name() + s);
2026 // FIXME: this creates duplicates in the completion popup
2027 // which looks ugly. Moreover the changes the list lengths
2029 confuse the popup as well.
2030 MathCompletionList::addToFavorites(inset->name());
2032 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2039 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2040 Dimension & dim) const
2042 Inset const * inset = cur.activeMacro();
2046 // get inset dimensions
2047 dim = cur.bv().coordCache().insets().dim(inset);
2048 // FIXME: these 3 are no accurate, but should depend on the font.
2049 // Now the popup jumps down if you enter a char with descent > 0.
2054 Point xy = cur.bv().coordCache().insets().xy(inset);
2060 bool InsetMathNest::cursorMathForward(Cursor & cur)
2062 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2063 cur.pushBackward(*cur.nextAtom().nucleus());
2064 cur.inset().idxFirst(cur);
2067 if (cur.posForward() || idxForward(cur))
2069 // try to pop forwards --- but don't pop out of math! leave that to
2071 int s = cur.depth() - 2;
2072 if (s >= 0 && cur[s].inset().asInsetMath())
2073 return cur.popForward();
2078 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2080 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2082 cur.push(*cur.nextAtom().nucleus());
2083 cur.inset().idxLast(cur);
2086 if (cur.posBackward() || idxBackward(cur))
2088 // try to pop backwards --- but don't pop out of math! leave that to
2090 int s = cur.depth() - 2;
2091 if (s >= 0 && cur[s].inset().asInsetMath())
2092 return cur.popBackward();
2097 ////////////////////////////////////////////////////////////////////
2099 MathCompletionList::MathCompletionList(Cursor const & cur)
2101 // fill it with macros from the buffer
2102 MacroNameSet macros;
2103 cur.buffer()->listMacroNames(macros);
2104 MacroNameSet::const_iterator it;
2105 for (it = macros.begin(); it != macros.end(); ++it) {
2106 if (cur.buffer()->getMacro(*it, cur, false))
2107 locals.push_back("\\" + *it);
2109 sort(locals.begin(), locals.end());
2111 if (!globals.empty())
2114 // fill in global macros
2116 MacroTable::globalMacros().getMacroNames(macros);
2117 //lyxerr << "Globals completion macros: ";
2118 for (it = macros.begin(); it != macros.end(); ++it) {
2119 //lyxerr << "\\" + *it << " ";
2120 globals.push_back("\\" + *it);
2122 //lyxerr << std::endl;
2124 // fill in global commands
2125 globals.push_back(from_ascii("\\boxed"));
2126 globals.push_back(from_ascii("\\fbox"));
2127 globals.push_back(from_ascii("\\framebox"));
2128 globals.push_back(from_ascii("\\makebox"));
2129 globals.push_back(from_ascii("\\kern"));
2130 globals.push_back(from_ascii("\\xhookrightarrow"));
2131 globals.push_back(from_ascii("\\xhookleftarrow"));
2132 globals.push_back(from_ascii("\\xrightarrow"));
2133 globals.push_back(from_ascii("\\xRightarrow"));
2134 globals.push_back(from_ascii("\\xrightharpoondown"));
2135 globals.push_back(from_ascii("\\xrightharpoonup"));
2136 globals.push_back(from_ascii("\\xrightleftharpoons"));
2137 globals.push_back(from_ascii("\\xleftarrow"));
2138 globals.push_back(from_ascii("\\xLeftarrow"));
2139 globals.push_back(from_ascii("\\xleftharpoondown"));
2140 globals.push_back(from_ascii("\\xleftharpoonup"));
2141 globals.push_back(from_ascii("\\xleftrightarrow"));
2142 globals.push_back(from_ascii("\\xLeftrightarrow"));
2143 globals.push_back(from_ascii("\\xleftrightharpoons"));
2144 globals.push_back(from_ascii("\\xmapsto"));
2145 globals.push_back(from_ascii("\\split"));
2146 globals.push_back(from_ascii("\\gathered"));
2147 globals.push_back(from_ascii("\\aligned"));
2148 globals.push_back(from_ascii("\\alignedat"));
2149 globals.push_back(from_ascii("\\cases"));
2150 globals.push_back(from_ascii("\\substack"));
2151 globals.push_back(from_ascii("\\xymatrix"));
2152 globals.push_back(from_ascii("\\Diagram"));
2153 globals.push_back(from_ascii("\\subarray"));
2154 globals.push_back(from_ascii("\\array"));
2155 globals.push_back(from_ascii("\\sqrt"));
2156 globals.push_back(from_ascii("\\root"));
2157 globals.push_back(from_ascii("\\tabular"));
2158 globals.push_back(from_ascii("\\stackrel"));
2159 globals.push_back(from_ascii("\\stackrelthree"));
2160 globals.push_back(from_ascii("\\binom"));
2161 globals.push_back(from_ascii("\\choose"));
2162 globals.push_back(from_ascii("\\brace"));
2163 globals.push_back(from_ascii("\\brack"));
2164 globals.push_back(from_ascii("\\frac"));
2165 globals.push_back(from_ascii("\\over"));
2166 globals.push_back(from_ascii("\\nicefrac"));
2167 globals.push_back(from_ascii("\\unitfrac"));
2168 globals.push_back(from_ascii("\\unitfracthree"));
2169 globals.push_back(from_ascii("\\unitone"));
2170 globals.push_back(from_ascii("\\unittwo"));
2171 globals.push_back(from_ascii("\\infer"));
2172 globals.push_back(from_ascii("\\atop"));
2173 globals.push_back(from_ascii("\\lefteqn"));
2174 globals.push_back(from_ascii("\\boldsymbol"));
2175 globals.push_back(from_ascii("\\bm"));
2176 globals.push_back(from_ascii("\\color"));
2177 globals.push_back(from_ascii("\\normalcolor"));
2178 globals.push_back(from_ascii("\\textcolor"));
2179 globals.push_back(from_ascii("\\cfrac"));
2180 globals.push_back(from_ascii("\\cfracleft"));
2181 globals.push_back(from_ascii("\\cfracright"));
2182 globals.push_back(from_ascii("\\dfrac"));
2183 globals.push_back(from_ascii("\\tfrac"));
2184 globals.push_back(from_ascii("\\dbinom"));
2185 globals.push_back(from_ascii("\\tbinom"));
2186 globals.push_back(from_ascii("\\hphantom"));
2187 globals.push_back(from_ascii("\\phantom"));
2188 globals.push_back(from_ascii("\\vphantom"));
2189 globals.push_back(from_ascii("\\cancel"));
2190 globals.push_back(from_ascii("\\bcancel"));
2191 globals.push_back(from_ascii("\\xcancel"));
2192 globals.push_back(from_ascii("\\cancelto"));
2193 globals.push_back(from_ascii("\\smash"));
2194 globals.push_back(from_ascii("\\mathclap"));
2195 globals.push_back(from_ascii("\\mathllap"));
2196 globals.push_back(from_ascii("\\mathrlap"));
2197 MathWordList const & words = mathedWordList();
2198 MathWordList::const_iterator it2;
2199 //lyxerr << "Globals completion commands: ";
2200 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2201 if (it2->second.inset != "macro") {
2202 // macros are already read from MacroTable::globalMacros()
2203 globals.push_back('\\' + it2->first);
2204 //lyxerr << '\\' + it2->first << ' ';
2207 //lyxerr << std::endl;
2208 sort(globals.begin(), globals.end());
2212 MathCompletionList::~MathCompletionList()
2217 size_type MathCompletionList::size() const
2219 return locals.size() + globals.size();
2223 docstring const & MathCompletionList::data(size_t idx) const
2225 size_t lsize = locals.size();
2227 return globals[idx - lsize];
2233 std::string MathCompletionList::icon(size_t idx) const
2235 // get the latex command
2237 size_t lsize = locals.size();
2239 cmd = globals[idx - lsize];
2243 // get the icon resource name by stripping the backslash
2244 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2245 if (icon_name.empty())
2246 return std::string();
2247 return "images/math/" + to_utf8(icon_name);
2250 std::vector<docstring> MathCompletionList::globals;