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 "InsetMathDecoration.h"
24 #include "InsetMathDelim.h"
25 #include "InsetMathEnsureMath.h"
26 #include "InsetMathFont.h"
27 #include "InsetMathHull.h"
28 #include "InsetMathRef.h"
29 #include "InsetMathScript.h"
30 #include "InsetMathSpace.h"
31 #include "InsetMathSymbol.h"
32 #include "InsetMathUnknown.h"
33 #include "MathAutoCorrect.h"
34 #include "MathCompletionList.h"
35 #include "MathFactory.h"
36 #include "InsetMathMacro.h"
37 #include "InsetMathMacroArgument.h"
38 #include "MathParser.h"
39 #include "MathStream.h"
40 #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"
52 #include "LaTeXFeatures.h"
55 #include "MetricsInfo.h"
59 #include "frontends/Application.h"
60 #include "frontends/Clipboard.h"
61 #include "frontends/Painter.h"
62 #include "frontends/Selection.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
75 using namespace lyx::support;
79 using cap::copySelection;
80 using cap::grabAndEraseSelection;
81 using cap::cutSelection;
82 using cap::replaceSelection;
83 using cap::selClearOrDel;
86 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
87 : InsetMath(buf), cells_(nargs), lock_(false)
89 // FIXME This should not really be necessary, but when we are
90 // initializing the table of global macros, we create macros
91 // with no associated Buffer.
97 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
98 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
102 InsetMathNest::~InsetMathNest()
104 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
105 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
106 for (; it != end; ++it)
108 it->first->clearLastInset(this);
112 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
114 cells_ = inset.cells_;
116 mouse_hover_.clear();
117 InsetMath::operator=(inset);
122 void InsetMathNest::setBuffer(Buffer & buffer)
124 InsetMath::setBuffer(buffer);
125 for (MathData & data : cells_)
126 data.setBuffer(buffer);
130 idx_type InsetMathNest::nargs() const
132 return cells_.size();
136 void InsetMathNest::cursorPos(BufferView const & bv,
137 CursorSlice const & sl, bool /*boundary*/,
138 int & x, int & y) const
140 // FIXME: This is a hack. Ideally, the coord cache should not store
141 // absolute positions, but relative ones. This would mean to call
142 // setXY() not in MathData::draw(), but in the parent insets' draw()
143 // with the correctly adjusted x,y values. But this means that we'd have
144 // to touch all (math)inset's draw() methods. Right now, we'll store
145 // absolute value, and make them here relative, only to make them
146 // absolute again when actually drawing the cursor. What a mess.
147 LASSERT(&sl.inset() == this, return);
148 MathData const & ar = sl.cell();
149 CoordCache const & coord_cache = bv.coordCache();
150 if (!coord_cache.getArrays().has(&ar)) {
151 // this can (semi-)legally happen if we just created this cell
152 // and it never has been drawn before. So don't ASSERT.
153 //lyxerr << "no cached data for array " << &ar << endl;
158 Point const pt = coord_cache.getArrays().xy(&ar);
159 if (!coord_cache.getInsets().has(this)) {
161 //lyxerr << "no cached data for inset " << this << endl;
166 Point const pt2 = coord_cache.getInsets().xy(this);
167 //lyxerr << "retrieving position cache for MathData "
168 // << pt.x_ << ' ' << pt.y_ << endl;
169 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
171 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
172 // << " asc: " << ascent() << " des: " << descent()
173 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
174 // move cursor visually into empty cells ("blue rectangles");
176 Dimension const dim = coord_cache.getArrays().dim(&ar);
182 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
185 for (auto const & cell : cells_) {
187 cell.metrics(m, dim);
192 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
194 for (idx_type i = 0, n = nargs(); i != n; ++i)
195 cell(i).updateBuffer(it, utype, deleted);
200 bool InsetMathNest::idxNext(Cursor & cur) const
202 LASSERT(&cur.inset() == this, return false);
203 if (cur.idx() == cur.lastidx())
211 bool InsetMathNest::idxForward(Cursor & cur) const
217 bool InsetMathNest::idxPrev(Cursor & cur) const
219 LASSERT(&cur.inset() == this, return false);
223 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
228 bool InsetMathNest::idxBackward(Cursor & cur) const
234 bool InsetMathNest::idxFirst(Cursor & cur) const
236 LASSERT(&cur.inset() == this, return false);
239 cur.idx() = firstIdx();
245 bool InsetMathNest::idxLast(Cursor & cur) const
247 LASSERT(&cur.inset() == this, return false);
250 cur.idx() = lastIdx();
251 cur.pos() = cur.lastpos();
256 void InsetMathNest::dump() const
258 odocstringstream oss;
259 otexrowstream ots(oss);
260 TeXMathStream os(ots);
261 os << "---------------------------------------------\n";
264 for (idx_type i = 0, n = nargs(); i != n; ++i)
265 os << cell(i) << "\n";
266 os << "---------------------------------------------\n";
267 lyxerr << to_utf8(oss.str());
271 void InsetMathNest::draw(PainterInfo &, int, int) const
275 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
281 void InsetMathNest::validate(LaTeXFeatures & features) const
283 for (idx_type i = 0; i < nargs(); ++i)
284 cell(i).validate(features);
288 void InsetMathNest::replace(ReplaceData & rep)
290 for (idx_type i = 0; i < nargs(); ++i)
291 cell(i).replace(rep);
295 bool InsetMathNest::contains(MathData const & ar) const
297 for (idx_type i = 0; i < nargs(); ++i)
298 if (cell(i).contains(ar))
304 bool InsetMathNest::lock() const
310 void InsetMathNest::lock(bool l)
316 bool InsetMathNest::isActive() const
322 MathData InsetMathNest::glue() const
325 for (size_t i = 0; i < nargs(); ++i)
331 void InsetMathNest::write(TeXMathStream & os) const
333 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
334 ModeSpecifier specifier(os, currentMode(), lockedMode());
335 docstring const latex_name = name();
336 os << '\\' << latex_name;
337 os.inMathClass(asClassInset());
338 for (size_t i = 0; i < nargs(); ++i) {
339 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
340 os << '{' << cell(i) << '}';
343 os.pendingSpace(true);
344 if (lock_ && !os.latex()) {
346 os.pendingSpace(true);
348 os.inMathClass(false);
352 void InsetMathNest::normalize(NormalStream & os) const
355 for (size_t i = 0; i < nargs(); ++i)
356 os << ' ' << cell(i);
361 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
363 TeXMathStream::OutputType ot;
364 if (runparams.find_effective())
365 ot = TeXMathStream::wsSearchAdv;
366 else if (runparams.dryrun)
367 ot = TeXMathStream::wsDryrun;
369 ot = TeXMathStream::wsDefault;
370 TeXMathStream wi(os, runparams.moving_arg, true, ot,
372 wi.strikeoutMath(runparams.inDeletedInset);
373 if (runparams.inulemcmd) {
374 wi.ulemCmd(TeXMathStream::UNDERLINE);
375 if (runparams.local_font) {
376 FontInfo f = runparams.local_font->fontInfo();
377 if (f.strikeout() == FONT_ON)
378 wi.ulemCmd(TeXMathStream::STRIKEOUT);
381 wi.canBreakLine(os.canBreakLine());
382 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
385 // Reset parbreak and command termination status after a math inset.
387 os.canBreakLine(wi.canBreakLine());
388 os.terminateCommand(false);
392 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
395 mouse_hover_[bv] = mouse_hover;
400 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
404 MathData & ar = cur.cell();
405 // remove base-only "scripts"
406 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
407 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
408 if (p && p->nargs() == 1) {
409 MathData ar = p->nuc();
412 cur.adjust(i, ar.size() - 1);
416 // glue adjacent font insets of the same kind
417 for (pos_type i = 0; i + 1 < size(); ++i) {
418 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
419 InsetMathFont const * q = operator[](i + 1)->asFontInset();
420 if (p && q && p->name() == q->name()) {
421 p->cell(0).append(q->cell(0));
431 void InsetMathNest::handleFont
432 (Cursor & cur, docstring const & arg, char const * const font)
434 handleFont(cur, arg, from_ascii(font));
438 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
439 docstring const & font)
441 cur.recordUndoSelection();
443 // this whole function is a hack and won't work for incremental font
445 if (cur.inset().asInsetMath()->name() == font)
446 cur.handleFont(to_utf8(font));
448 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
452 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
454 handleNest(cur, nest, docstring());
458 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
459 docstring const & arg)
461 DocIterator const i1 = cur.selectionBegin();
462 DocIterator const i2 = cur.selectionEnd();
463 if (!i1.inset().asInsetMath())
465 if (i1.idx() == i2.idx()) {
466 // the easy case where only one cell is selected
467 cur.handleNest(nest);
472 // multiple selected cells in a simple non-grid inset
473 if (i1.inset().nrows() == 0 || i1.inset().ncols() == 0) {
474 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
480 cur.pos() = cur.lastpos();
484 cur.handleNest(nest);
490 // the complicated case with multiple selected cells in a grid
493 cap::region(i1.top(), i2.top(), r1, r2, c1, c2);
494 for (row_type row = r1; row <= r2; ++row) {
495 for (col_type col = c1; col <= c2; ++col) {
498 cur.idx() = i1.inset().index(row, col);
501 cur.pos() = cur.lastpos();
505 cur.handleNest(nest);
512 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
514 bool font_changed = false;
515 cur.recordUndoSelection();
518 font.fromString(to_utf8(arg), b);
519 if (font.fontInfo().color() != Color_inherit &&
520 font.fontInfo().color() != Color_ignore) {
521 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
526 InsetMathFont const * f = asFontInset();
528 switch(font.fontInfo().family()) {
530 if (!f || (f->name() != "textrm" && f->name() != "mathrm"))
531 im = currentMode() != MATH_MODE ? from_ascii("textrm")
532 : from_ascii("mathrm");
535 if (!f || (f->name() != "textsf" && f->name() != "mathsf"))
536 im = currentMode() != MATH_MODE ? from_ascii("textsf")
537 : from_ascii("mathsf");
539 case TYPEWRITER_FAMILY:
540 if (!f || (f->name() != "texttt" && f->name() != "mathtt"))
541 im = currentMode() != MATH_MODE ? from_ascii("texttt")
542 : from_ascii("mathtt");
569 handleNest(cur, createInsetMath(im, cur.buffer()));
574 switch(font.fontInfo().series()) {
576 if (!f || (f->name() != "textmd" && f->name() != "mathrm"))
577 im = currentMode() != MATH_MODE ? from_ascii("textmd")
578 : from_ascii("mathrm");
581 if (!f || (f->name() != "textbf" && f->name() != "mathbf"))
582 im = currentMode() != MATH_MODE ? from_ascii("textbf")
583 : from_ascii("mathbf");
597 handleNest(cur, createInsetMath(im, cur.buffer()));
602 switch(font.fontInfo().shape()) {
604 if (!f || (f->name() != "textup" && f->name() != "mathrm"))
605 im = currentMode() != MATH_MODE ? from_ascii("textup")
606 : from_ascii("mathrm");
609 if (!f || (f->name() != "textit" && f->name() != "mathit"))
610 im = currentMode() != MATH_MODE ? from_ascii("textit")
611 : from_ascii("mathit");
614 if (!f || f->name() != "textsl")
615 im = currentMode() != MATH_MODE ? from_ascii("textsl")
616 : from_ascii("error");
618 case SMALLCAPS_SHAPE:
619 if (!f || f->name() != "textsc")
620 im = currentMode() != MATH_MODE ? from_ascii("textsc")
621 : from_ascii("error");
627 if (!im.empty() && im != "error") {
635 handleNest(cur, createInsetMath(im, cur.buffer()));
640 switch(font.fontInfo().size()) {
642 im = from_ascii("tiny");
645 im = from_ascii("scriptsize");
648 im = from_ascii("footnotesize");
651 im = from_ascii("small");
654 im = from_ascii("normalsize");
657 im = from_ascii("large");
660 im = from_ascii("Large");
663 im = from_ascii("LARGE");
666 im = from_ascii("huge");
669 im = from_ascii("Huge");
685 handleNest(cur, createInsetMath(im, cur.buffer()));
690 InsetMathDecoration const * d = asDecorationInset();
692 if (font.fontInfo().underbar() == FONT_OFF && d && d->name() == "uline") {
693 lyxerr << "Remove uline" << endl;
695 if (font.fontInfo().uuline() == FONT_OFF && d && d->name() == "uuline") {
696 lyxerr << "Remove uuline" << endl;
698 if (font.fontInfo().uwave() == FONT_OFF && d && d->name() == "uwave") {
699 lyxerr << "Remove uwave" << endl;
702 switch(font.fontInfo().underbar()) {
704 if (!d || d->name() != "uline")
705 im = from_ascii("uline");
721 handleNest(cur, createInsetMath(im, cur.buffer()));
726 switch(font.fontInfo().uuline()) {
728 if (!d || d->name() != "uuline")
729 im = from_ascii("uuline");
745 handleNest(cur, createInsetMath(im, cur.buffer()));
750 switch(font.fontInfo().uwave()) {
752 if (!d || d->name() != "uwave")
753 im = from_ascii("uwave");
769 handleNest(cur, createInsetMath(im, cur.buffer()));
774 // FIXME: support other font changes here as well?
777 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
779 //LYXERR0("InsetMathNest: request: " << cmd);
781 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
783 FuncCode const act = cmd.action();
786 case LFUN_CLIPBOARD_PASTE:
787 parseflg |= Parse::VERBATIM;
790 if (cur.currentMode() != MATH_MODE)
791 parseflg |= Parse::TEXTMODE;
792 cur.recordUndoSelection();
793 cur.message(_("Paste"));
794 replaceSelection(cur);
796 if (cmd.argument().empty() && !theClipboard().isInternal())
797 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
800 idocstringstream is(cmd.argument());
802 topaste = cap::selection(n, make_pair(buffer().params().documentClassPtr(),
803 buffer().params().authors()));
805 InsetMath const * im = cur.inset().asInsetMath();
806 InsetMathMacro const * macro = im ? im->asMacro() : nullptr;
807 // do not allow pasting a backslash in the name of a macro
809 && macro->displayMode() == InsetMathMacro::DISPLAY_UNFOLDED
810 && support::contains(topaste, char_type('\\'))) {
811 LYXERR0("Removing backslash from pasted string");
812 topaste = subst(topaste, from_ascii("\\"), docstring());
814 cur.niceInsert(topaste, parseflg, false);
815 cur.clearSelection(); // bug 393
816 cur.forceBufferUpdate();
823 cutSelection(cur, true);
824 cur.message(_("Cut"));
825 // Prevent stale position >= size crash
826 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
828 cur.forceBufferUpdate();
831 case LFUN_MOUSE_PRESS:
832 lfunMousePress(cur, cmd);
835 case LFUN_MOUSE_MOTION:
836 lfunMouseMotion(cur, cmd);
839 case LFUN_MOUSE_RELEASE:
840 lfunMouseRelease(cur, cmd);
843 case LFUN_FINISHED_LEFT: // in math, left is backwards
844 case LFUN_FINISHED_BACKWARD:
845 cur.bv().cursor() = cur;
848 case LFUN_FINISHED_RIGHT: // in math, right is forward
849 case LFUN_FINISHED_FORWARD:
851 cur.bv().cursor() = cur;
854 case LFUN_WORD_RIGHT:
856 case LFUN_WORD_BACKWARD:
857 case LFUN_WORD_FORWARD:
858 case LFUN_CHAR_RIGHT:
860 case LFUN_CHAR_BACKWARD:
861 case LFUN_CHAR_FORWARD:
862 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
864 case LFUN_WORD_RIGHT_SELECT:
865 case LFUN_WORD_LEFT_SELECT:
866 case LFUN_WORD_BACKWARD_SELECT:
867 case LFUN_WORD_FORWARD_SELECT:
868 case LFUN_CHAR_RIGHT_SELECT:
869 case LFUN_CHAR_LEFT_SELECT:
870 case LFUN_CHAR_BACKWARD_SELECT:
871 case LFUN_CHAR_FORWARD_SELECT: {
872 // are we in a selection?
873 bool select = (act == LFUN_WORD_RIGHT_SELECT
874 || act == LFUN_WORD_LEFT_SELECT
875 || act == LFUN_WORD_BACKWARD_SELECT
876 || act == LFUN_WORD_FORWARD_SELECT
877 || act == LFUN_CHAR_RIGHT_SELECT
878 || act == LFUN_CHAR_LEFT_SELECT
879 || act == LFUN_CHAR_BACKWARD_SELECT
880 || act == LFUN_CHAR_FORWARD_SELECT);
882 bool word = (act == LFUN_WORD_RIGHT_SELECT
883 || act == LFUN_WORD_LEFT_SELECT
884 || act == LFUN_WORD_BACKWARD_SELECT
885 || act == LFUN_WORD_FORWARD_SELECT
886 || act == LFUN_WORD_RIGHT
887 || act == LFUN_WORD_LEFT
888 || act == LFUN_WORD_BACKWARD
889 || act == LFUN_WORD_FORWARD);
890 // are we moving forward or backwards?
891 // If the command was RIGHT or LEFT, then whether we're moving forward
892 // or backwards depends on the cursor movement mode (logical or visual):
893 // * in visual mode, since math is always LTR, right -> forward,
895 // * in logical mode, the mapping is determined by the
896 // reverseDirectionNeeded() function
899 FuncCode finish_lfun;
901 if (act == LFUN_CHAR_FORWARD
902 || act == LFUN_CHAR_FORWARD_SELECT
903 || act == LFUN_WORD_FORWARD
904 || act == LFUN_WORD_FORWARD_SELECT) {
906 finish_lfun = LFUN_FINISHED_FORWARD;
908 else if (act == LFUN_CHAR_BACKWARD
909 || act == LFUN_CHAR_BACKWARD_SELECT
910 || act == LFUN_WORD_BACKWARD
911 || act == LFUN_WORD_BACKWARD_SELECT) {
913 finish_lfun = LFUN_FINISHED_BACKWARD;
916 bool right = (act == LFUN_CHAR_RIGHT_SELECT
917 || act == LFUN_CHAR_RIGHT
918 || act == LFUN_WORD_RIGHT_SELECT
919 || act == LFUN_WORD_RIGHT);
920 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
926 finish_lfun = LFUN_FINISHED_RIGHT;
928 finish_lfun = LFUN_FINISHED_LEFT;
930 // Now that we know exactly what we want to do, let's do it!
931 cur.selHandle(select);
933 cur.macroModeClose();
934 // try moving forward or backwards as necessary...
935 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
936 // ... and if movement failed, then finish forward or backwards
938 cmd = FuncRequest(finish_lfun);
946 case LFUN_PARAGRAPH_UP:
947 case LFUN_PARAGRAPH_DOWN:
948 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
950 case LFUN_DOWN_SELECT:
952 case LFUN_PARAGRAPH_UP_SELECT:
953 case LFUN_PARAGRAPH_DOWN_SELECT: {
954 // close active macro
955 if (cur.inMacroMode()) {
956 cur.macroModeClose();
960 // stop/start the selection
961 bool select = act == LFUN_DOWN_SELECT
962 || act == LFUN_UP_SELECT
963 || act == LFUN_PARAGRAPH_DOWN_SELECT
964 || act == LFUN_PARAGRAPH_UP_SELECT;
965 cur.selHandle(select);
968 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
969 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
970 bool successful = cur.upDownInMath(up);
974 if (cur.fixIfBroken())
975 // FIXME: Something bad happened. We pass the corrected Cursor
976 // instead of letting things go worse.
979 // We did not manage to move the cursor.
984 case LFUN_MOUSE_DOUBLE:
985 case LFUN_WORD_SELECT:
987 cur.bv().mouseSetCursor(cur);
988 cur.pos() = cur.lastpos();
989 cur.bv().mouseSetCursor(cur, true);
992 case LFUN_MOUSE_TRIPLE:
995 cur.bv().mouseSetCursor(cur);
996 cur.idx() = cur.lastidx();
997 cur.pos() = cur.lastpos();
998 cur.bv().mouseSetCursor(cur, true);
1001 case LFUN_LINE_BEGIN:
1002 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1004 case LFUN_LINE_BEGIN_SELECT:
1005 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
1006 act == LFUN_WORD_LEFT_SELECT ||
1007 act == LFUN_LINE_BEGIN_SELECT);
1008 cur.macroModeClose();
1009 if (cur.pos() != 0) {
1011 } else if (cur.col() != 0) {
1012 cur.idx() -= cur.col();
1014 } else if (cur.idx() != 0) {
1018 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
1024 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1026 case LFUN_LINE_END_SELECT:
1027 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
1028 act == LFUN_WORD_RIGHT_SELECT ||
1029 act == LFUN_LINE_END_SELECT);
1030 cur.macroModeClose();
1032 if (cur.pos() != cur.lastpos()) {
1033 cur.pos() = cur.lastpos();
1034 } else if (ncols() && (cur.col() != cur.lastcol())) {
1035 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
1036 cur.pos() = cur.lastpos();
1037 } else if (cur.idx() != cur.lastidx()) {
1038 cur.idx() = cur.lastidx();
1039 cur.pos() = cur.lastpos();
1041 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1046 case LFUN_CELL_FORWARD:
1047 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1048 cur.selHandle(false);
1050 cur.macroModeClose();
1051 if (!cur.inset().idxNext(cur)) {
1052 if (cur.lastidx() == 0)
1055 cur.idx() = firstIdx();
1061 case LFUN_CELL_BACKWARD:
1062 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
1063 cur.selHandle(false);
1065 cur.macroModeClose();
1066 if (!cur.inset().idxPrev(cur)) {
1067 if (cur.lastidx() == 0)
1070 cur.idx() = cur.lastidx();
1071 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
1076 case LFUN_WORD_DELETE_BACKWARD:
1077 case LFUN_CHAR_DELETE_BACKWARD:
1079 // May affect external cell:
1080 cur.recordUndoInset();
1081 else if (!cur.inMacroMode())
1082 cur.recordUndoSelection();
1083 // if the inset can not be removed from within, delete it
1084 if (!cur.backspace(cmd.getArg(0) != "confirm")) {
1085 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
1086 cur.innerText()->dispatch(cur, newcmd);
1090 case LFUN_WORD_DELETE_FORWARD:
1091 case LFUN_CHAR_DELETE_FORWARD:
1092 if (cur.pos() == cur.lastpos())
1093 // May affect external cell:
1094 cur.recordUndoInset();
1096 cur.recordUndoSelection();
1097 // if the inset can not be removed from within, delete it
1098 if (!cur.erase(cmd.getArg(0) != "confirm")) {
1099 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
1100 cur.innerText()->dispatch(cur, newcmd);
1105 if (cur.selection())
1106 cur.clearSelection();
1108 if (cur.inMacroMode())
1109 cur.macroModeClose(true);
1111 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1117 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
1118 // that is traversed by a single <CursorLeft>/<CursorRight>.
1119 case LFUN_INSET_TOGGLE:
1125 case LFUN_SELF_INSERT:
1126 // special case first for big delimiters
1127 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
1130 for (char_type c : cmd.argument()) {
1131 // Don't record undo steps if we are in macro mode and thus
1132 // cmd.argument is the next character of the macro name.
1133 // Otherwise we'll get an invalid cursor if we undo after
1134 // the macro was finished and the macro is a known command,
1135 // e.g. sqrt. Cursor::macroModeClose replaces in this case
1136 // the InsetMathUnknown with name "frac" by an empty
1137 // InsetMathFrac -> a pos value > 0 is invalid.
1138 // A side effect is that an undo before the macro is finished
1139 // undoes the complete macro, not only the last character.
1140 // At the time we hit '\' we are not in macro mode, still.
1141 if (!cur.inMacroMode())
1142 cur.recordUndoSelection();
1144 // special handling of space. If we insert an inset
1145 // via macro mode, we want to put the cursor inside it
1146 // if relevant. Think typing "\frac<space>".
1148 && cur.inMacroMode() && cur.macroName() != "\\"
1149 && cur.macroModeClose() && cur.pos() > 0)
1150 cur.editInsertedInset();
1151 else if (!interpretChar(cur, c)) {
1152 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1154 // FIXME: can we avoid skipping the end of the string?
1160 //case LFUN_SERVER_GET_XY:
1163 case LFUN_SERVER_SET_XY: {
1164 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
1167 istringstream is(to_utf8(cmd.argument()));
1173 // Special casing for superscript in case of LyX handling
1175 case LFUN_ACCENT_CIRCUMFLEX:
1176 if (cmd.argument().empty()) {
1177 // do superscript if LyX handles
1179 cur.recordUndoInset();
1180 script(cur, true, grabAndEraseSelection(cur));
1184 case LFUN_ACCENT_UMLAUT:
1185 case LFUN_ACCENT_ACUTE:
1186 case LFUN_ACCENT_GRAVE:
1187 case LFUN_ACCENT_BREVE:
1188 case LFUN_ACCENT_DOT:
1189 case LFUN_ACCENT_MACRON:
1190 case LFUN_ACCENT_CARON:
1191 case LFUN_ACCENT_TILDE:
1192 case LFUN_ACCENT_CEDILLA:
1193 case LFUN_ACCENT_CIRCLE:
1194 case LFUN_ACCENT_UNDERDOT:
1195 case LFUN_ACCENT_TIE:
1196 case LFUN_ACCENT_OGONEK:
1197 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1201 case LFUN_TEXTSTYLE_APPLY:
1202 case LFUN_TEXTSTYLE_UPDATE:
1203 handleFont2(cur, cmd.argument());
1206 case LFUN_FONT_BOLD:
1207 if (currentMode() != MATH_MODE)
1208 handleFont(cur, cmd.argument(), "textbf");
1210 handleFont(cur, cmd.argument(), "mathbf");
1212 case LFUN_FONT_BOLDSYMBOL:
1213 if (currentMode() != MATH_MODE)
1214 handleFont(cur, cmd.argument(), "textbf");
1216 handleFont(cur, cmd.argument(), "boldsymbol");
1218 case LFUN_FONT_SANS:
1219 if (currentMode() != MATH_MODE)
1220 handleFont(cur, cmd.argument(), "textsf");
1222 handleFont(cur, cmd.argument(), "mathsf");
1224 case LFUN_FONT_EMPH:
1225 if (currentMode() != MATH_MODE)
1226 handleFont(cur, cmd.argument(), "emph");
1228 handleFont(cur, cmd.argument(), "mathcal");
1230 case LFUN_FONT_ROMAN:
1231 if (currentMode() != MATH_MODE)
1232 handleFont(cur, cmd.argument(), "textrm");
1234 handleFont(cur, cmd.argument(), "mathrm");
1236 case LFUN_FONT_TYPEWRITER:
1237 if (currentMode() != MATH_MODE)
1238 handleFont(cur, cmd.argument(), "texttt");
1240 handleFont(cur, cmd.argument(), "mathtt");
1242 case LFUN_FONT_FRAK:
1243 handleFont(cur, cmd.argument(), "mathfrak");
1245 case LFUN_FONT_ITAL:
1246 if (currentMode() != MATH_MODE)
1247 handleFont(cur, cmd.argument(), "textit");
1249 handleFont(cur, cmd.argument(), "mathit");
1251 case LFUN_FONT_NOUN:
1252 if (currentMode() != MATH_MODE)
1253 // FIXME: should be "noun"
1254 handleFont(cur, cmd.argument(), "textsc");
1256 handleFont(cur, cmd.argument(), "mathbb");
1258 case LFUN_FONT_DEFAULT:
1259 handleFont(cur, cmd.argument(), "textnormal");
1261 case LFUN_FONT_UNDERLINE:
1263 cur.handleNest(createInsetMath("underline", cur.buffer()));
1266 case LFUN_MATH_MODE: {
1268 // ignore math-mode on when already in math mode
1269 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1271 cur.recordUndoSelection();
1272 cur.macroModeClose();
1273 docstring const save_selection = grabAndEraseSelection(cur);
1275 if (currentMode() != Inset::MATH_MODE)
1276 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1278 cur.plainInsert(createInsetMath("text", buffer_));
1280 cur.pushBackward(*cur.nextInset());
1281 cur.niceInsert(save_selection);
1282 cur.forceBufferUpdate();
1284 if (currentMode() == Inset::TEXT_MODE) {
1285 cur.recordUndoSelection();
1286 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1287 cur.message(_("create new math text environment ($...$)"));
1289 handleFont(cur, cmd.argument(), "textrm");
1290 cur.message(_("entered math text mode (textrm)"));
1296 case LFUN_REGEXP_MODE: {
1297 InsetMath * im = cur.inset().asInsetMath();
1299 InsetMathHull * i = im->asHullInset();
1300 if (i && i->getType() == hullRegexp) {
1301 cur.message(_("Already in regular expression mode"));
1305 cur.macroModeClose();
1306 docstring const save_selection = grabAndEraseSelection(cur);
1308 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1310 cur.pushBackward(*cur.nextInset());
1311 cur.niceInsert(save_selection);
1312 cur.message(_("Regular expression editor mode"));
1316 case LFUN_MATH_FONT_STYLE: {
1317 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1318 doDispatch(cur, fr);
1322 case LFUN_MATH_SIZE: {
1323 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1324 doDispatch(cur, fr);
1328 case LFUN_MATH_MATRIX: {
1334 idocstringstream is(cmd.argument());
1335 is >> m >> n >> v_align >> h_align;
1341 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1342 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1346 case LFUN_MATH_AMS_MATRIX: {
1350 docstring name = from_ascii("matrix");
1351 idocstringstream is(cmd.argument());
1352 is >> m >> n >> name;
1357 // check if we have a valid decoration
1358 if (name != "pmatrix" && name != "bmatrix"
1359 && name != "Bmatrix" && name != "vmatrix"
1360 && name != "Vmatrix" && name != "matrix"
1361 && name != "smallmatrix")
1362 name = from_ascii("matrix");
1365 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1369 case LFUN_MATH_DELIM: {
1371 docstring rs = split(cmd.argument(), ls, ' ');
1372 // Reasonable default values
1378 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1382 case LFUN_MATH_BIGDELIM: {
1383 docstring const lname = from_utf8(cmd.getArg(0));
1384 docstring const ldelim = from_utf8(cmd.getArg(1));
1385 docstring const rname = from_utf8(cmd.getArg(2));
1386 docstring const rdelim = from_utf8(cmd.getArg(3));
1387 latexkeys const * l = in_word_set(lname);
1388 bool const have_l = l && l->inset == "big" &&
1389 InsetMathBig::isBigInsetDelim(ldelim);
1390 l = in_word_set(rname);
1391 bool const have_r = l && l->inset == "big" &&
1392 InsetMathBig::isBigInsetDelim(rdelim);
1393 // We mimic LFUN_MATH_DELIM in case we have an empty left
1394 // or right delimiter.
1395 if (have_l || have_r) {
1397 docstring const selection = grabAndEraseSelection(cur);
1400 cur.insert(MathAtom(new InsetMathBig(lname,
1402 // first insert the right delimiter and then go back
1403 // and re-insert the selection (bug 7088)
1405 cur.insert(MathAtom(new InsetMathBig(rname,
1409 cur.niceInsert(selection);
1411 // Don't call cur.undispatched() if we did nothing, this would
1412 // lead to infinite recursion via Text::dispatch().
1416 case LFUN_SPACE_INSERT: {
1417 cur.recordUndoSelection();
1418 string const name = cmd.getArg(0);
1419 if (name == "normal")
1420 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1421 else if (name == "protected")
1422 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1423 else if (name == "thin" || name == "med" || name == "thick")
1424 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1425 else if (name == "hfill*")
1426 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1427 else if (name == "quad" || name == "qquad" ||
1428 name == "enspace" || name == "enskip" ||
1429 name == "negthinspace" || name == "negmedspace" ||
1430 name == "negthickspace" || name == "hfill")
1431 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1432 else if (name == "hspace" || name == "hspace*") {
1433 string const len = cmd.getArg(1);
1434 if (len.empty() || !isValidLength(len)) {
1435 lyxerr << "LyX function 'space-insert " << name << "' "
1436 "needs a valid length argument." << endl;
1439 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1441 cur.insert(MathAtom(new InsetMathSpace));
1445 case LFUN_MATH_SPACE:
1446 cur.recordUndoSelection();
1447 if (cmd.argument().empty())
1448 cur.insert(MathAtom(new InsetMathSpace));
1450 string const name = cmd.getArg(0);
1451 string const len = cmd.getArg(1);
1452 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1456 case LFUN_ERT_INSERT:
1457 // interpret this as if a backslash was typed
1459 interpretChar(cur, '\\');
1462 case LFUN_MATH_SUBSCRIPT:
1463 // interpret this as if a _ was typed
1464 cur.recordUndoSelection();
1465 interpretChar(cur, '_');
1468 case LFUN_MATH_SUPERSCRIPT:
1469 // interpret this as if a ^ was typed
1470 cur.recordUndoSelection();
1471 interpretChar(cur, '^');
1474 case LFUN_MATH_MACRO_FOLD:
1475 case LFUN_MATH_MACRO_UNFOLD: {
1477 bool fold = act == LFUN_MATH_MACRO_FOLD;
1478 bool found = findMacroToFoldUnfold(it, fold);
1480 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1481 cur.recordUndoInset();
1490 case LFUN_QUOTE_INSERT:
1491 // interpret this as if a straight " was typed
1492 cur.recordUndoSelection();
1493 interpretChar(cur, '\"');
1496 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1497 // handling such that "self-insert" works on "arbitrary stuff" too, and
1498 // math-insert only handles special math things like "matrix".
1499 case LFUN_MATH_INSERT: {
1500 cur.recordUndoSelection();
1501 if (cmd.argument() == "^" || cmd.argument() == "_")
1502 interpretChar(cur, cmd.argument()[0]);
1503 else if (!cur.selection())
1504 cur.niceInsert(cmd.argument());
1506 MathData ar(cur.buffer());
1507 asArray(cmd.argument(), ar);
1509 && ar[0]->asNestInset()
1510 && ar[0]->asNestInset()->nargs() > 1)
1511 handleNest(cur, ar[0]);
1513 cur.niceInsert(cmd.argument());
1518 case LFUN_DIALOG_SHOW_NEW_INSET: {
1519 docstring const & name = cmd.argument();
1521 if (name == "ref") {
1522 InsetMathRef tmp(buffer_, name);
1523 data = tmp.createDialogStr();
1524 cur.bv().showDialog(to_utf8(name), data);
1525 } else if (name == "mathspace") {
1526 cur.bv().showDialog(to_utf8(name));
1531 case LFUN_INSET_INSERT: {
1533 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1534 cur.recordUndoSelection();
1536 cur.forceBufferUpdate();
1541 case LFUN_INSET_DISSOLVE:
1542 if (cmd.argument().empty() && !asHullInset() && !asMacroTemplate()) {
1543 // we have been triggered via the AtPoint mechanism
1544 if (cur.nextInset() == this)
1546 cur.recordUndoInset();
1551 case LFUN_MATH_LIMITS: {
1553 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1554 in = &cur.nextMath();
1555 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1556 in = &cur.prevMath();
1557 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1558 in = cur.cell().back().nucleus();
1559 // only when nucleus allows this
1562 cur.recordUndoInset();
1563 if (!cmd.argument().empty()) {
1564 if (cmd.argument() == "limits")
1566 else if (cmd.argument() == "nolimits")
1567 in->limits(NO_LIMITS);
1569 in->limits(AUTO_LIMITS);
1570 } else if (in->limits() != AUTO_LIMITS)
1571 in->limits(AUTO_LIMITS);
1572 else if (in->defaultLimits(cur.cell().displayStyle()) == LIMITS)
1573 in->limits(NO_LIMITS);
1579 case LFUN_PHANTOM_INSERT: {
1580 docstring const & arg = cmd.argument();
1582 if (arg == "Phantom")
1583 newarg = from_ascii("\\phantom");
1584 else if (arg == "HPhantom")
1585 newarg = from_ascii("\\hphantom");
1586 else if (arg == "VPhantom")
1587 newarg = from_ascii("\\vphantom");
1589 LYXERR0("Unknown phantom type " + newarg);
1591 FuncRequest const newfunc(LFUN_MATH_INSERT, newarg);
1592 lyx::dispatch(newfunc);
1598 InsetMath::doDispatch(cur, cmd);
1604 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1605 // look for macro to open/close, but stay in mathed
1606 for (; !it.empty(); it.pop_back()) {
1608 // go backward through the current cell
1609 Inset * inset = it.nextInset();
1610 while (inset && inset->asInsetMath()) {
1611 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1613 // found the an macro to open/close?
1614 if (macro->folded() != fold)
1617 // Wrong folding state.
1618 // If this was the first we see in this slice, look further left,
1620 if (inset != it.nextInset())
1624 // go up if this was the left most position
1630 inset = it.nextInset();
1638 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1639 FuncStatus & flag) const
1641 // the font related toggles
1642 //string tc = "mathnormal";
1644 string const arg = to_utf8(cmd.argument());
1645 switch (cmd.action()) {
1647 case LFUN_INSET_MODIFY:
1648 // FIXME: check temporarily disabled
1650 char align = mathcursor::valign();
1651 if (align == '\0') {
1655 if (cmd.argument().empty()) {
1659 if (!contains("tcb", cmd.argument()[0])) {
1663 flag.setOnOff(cmd.argument()[0] == align);
1666 /// We have to handle them since 1.4 blocks all unhandled actions
1667 case LFUN_FONT_ITAL:
1668 case LFUN_FONT_BOLD:
1669 case LFUN_FONT_BOLDSYMBOL:
1670 case LFUN_FONT_SANS:
1671 case LFUN_FONT_EMPH:
1672 case LFUN_FONT_TYPEWRITER:
1673 case LFUN_FONT_NOUN:
1674 case LFUN_FONT_ROMAN:
1675 case LFUN_FONT_DEFAULT:
1676 flag.setEnabled(true);
1679 // we just need to be in math mode to enable that
1680 case LFUN_MATH_SIZE:
1681 case LFUN_MATH_SPACE:
1682 case LFUN_MATH_EXTERN:
1683 flag.setEnabled(true);
1686 case LFUN_FONT_UNDERLINE:
1687 case LFUN_FONT_FRAK:
1688 flag.setEnabled(currentMode() != TEXT_MODE);
1691 case LFUN_MATH_FONT_STYLE: {
1692 bool const textarg =
1693 arg == "textbf" || arg == "textsf" ||
1694 arg == "textrm" || arg == "textmd" ||
1695 arg == "textit" || arg == "textsc" ||
1696 arg == "textsl" || arg == "textup" ||
1697 arg == "texttt" || arg == "textbb" ||
1698 arg == "textnormal";
1699 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1703 case LFUN_MATH_MODE:
1704 // forbid "math-mode on" in math mode to prevent irritating
1705 // behaviour of menu entries (bug 6709)
1706 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1709 case LFUN_MATH_INSERT:
1710 flag.setEnabled(currentMode() != TEXT_MODE);
1713 case LFUN_MATH_AMS_MATRIX:
1714 case LFUN_MATH_MATRIX:
1715 flag.setEnabled(currentMode() == MATH_MODE);
1718 case LFUN_INSET_INSERT: {
1719 // Don't test createMathInset_fromDialogStr(), since
1720 // getStatus is not called with a valid reference and the
1721 // dialog would not be applicable.
1722 string const name = cmd.getArg(0);
1723 flag.setEnabled(name == "ref" || name == "mathspace");
1727 case LFUN_DIALOG_SHOW_NEW_INSET: {
1728 docstring const & name = cmd.argument();
1729 flag.setEnabled(name == "ref" || name == "mathspace");
1734 case LFUN_MATH_DELIM:
1735 case LFUN_MATH_BIGDELIM:
1736 // Don't do this with multi-cell selections
1737 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1740 case LFUN_MATH_MACRO_FOLD:
1741 case LFUN_MATH_MACRO_UNFOLD: {
1743 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1744 flag.setEnabled(found);
1748 case LFUN_SPECIALCHAR_INSERT:
1749 case LFUN_SCRIPT_INSERT:
1750 // FIXME: These would probably make sense in math-text mode
1751 flag.setEnabled(false);
1754 // these are nonfunctional in math
1755 case LFUN_BOX_INSERT:
1756 case LFUN_BRANCH_INSERT:
1757 case LFUN_BRANCH_ADD_INSERT:
1758 case LFUN_CAPTION_INSERT:
1759 case LFUN_FLEX_INSERT:
1760 case LFUN_FLOAT_INSERT:
1761 case LFUN_FLOAT_LIST_INSERT:
1762 case LFUN_FOOTNOTE_INSERT:
1763 case LFUN_HREF_INSERT:
1764 case LFUN_INDEX_INSERT:
1765 case LFUN_INDEX_PRINT:
1766 case LFUN_INFO_INSERT:
1767 case LFUN_IPA_INSERT:
1768 case LFUN_LISTING_INSERT:
1769 case LFUN_MARGINALNOTE_INSERT:
1770 case LFUN_NEWPAGE_INSERT:
1771 case LFUN_NOMENCL_INSERT:
1772 case LFUN_NOMENCL_PRINT:
1773 case LFUN_NOTE_INSERT:
1774 case LFUN_PREVIEW_INSERT:
1775 case LFUN_TABULAR_INSERT:
1776 case LFUN_WRAP_INSERT:
1777 flag.setEnabled(false);
1780 case LFUN_SPACE_INSERT: {
1781 docstring const & name = cmd.argument();
1782 if (name == "visible")
1783 flag.setEnabled(false);
1787 case LFUN_INSET_DISSOLVE:
1788 flag.setEnabled(cmd.argument().empty() && !asHullInset() && !asMacroTemplate());
1792 docstring const & name = cmd.argument();
1793 if (name == "html" || name == "latex")
1794 flag.setEnabled(false);
1798 case LFUN_MATH_LIMITS: {
1800 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1801 in = &cur.nextMath();
1802 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1803 in = &cur.prevMath();
1804 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1805 in = cur.cell().back().nucleus();
1807 if (!cmd.argument().empty()) {
1808 if (cmd.argument() == "limits")
1809 flag.setOnOff(in->limits() == LIMITS);
1810 else if (cmd.argument() == "nolimits")
1811 flag.setOnOff(in->limits() == NO_LIMITS);
1813 flag.setOnOff(in->limits() == AUTO_LIMITS);
1815 flag.setEnabled(true);
1817 flag.setEnabled(false);
1829 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1832 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1833 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1834 enter_front ? idxFirst(cur) : idxLast(cur);
1836 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1840 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1843 int dist_min = 1000000;
1844 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1845 int const d = cell(i).dist(cur.bv(), x, y);
1854 MathData & ar = cell(idx_min);
1856 cur.idx() = idx_min;
1857 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1859 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1860 if (dist_min == 0) {
1862 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1863 if (ar[i]->covers(cur.bv(), x, y))
1864 return ar[i].nucleus()->editXY(cur, x, y);
1870 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1872 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1873 BufferView & bv = cur.bv();
1874 if (cmd.button() == mouse_button::button3) {
1875 // Don't do anything if we right-click a
1876 // selection, a context menu will popup.
1877 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1878 && cur < bv.cursor().selectionEnd()) {
1879 cur.noScreenUpdate();
1884 // set cursor after the inset if x is nearer to that position (bug 9748)
1885 cur.moveToClosestEdge(cmd.x(), true);
1887 bool do_selection = cmd.button() == mouse_button::button1
1888 && cmd.modifier() == ShiftModifier;
1889 bv.mouseSetCursor(cur, do_selection);
1890 if (cmd.button() == mouse_button::button1) {
1891 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1892 // Update the cursor update flags as needed:
1894 // Update::Decoration: tells to update the decoration
1895 // (visual box corners that define
1897 // Update::FitCursor: adjust the screen to the cursor
1898 // position if needed
1899 // cur.result().update(): don't overwrite previously set flags.
1900 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1901 | cur.result().screenUpdate());
1902 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1903 if (cap::selection()) {
1904 // See comment in Text::dispatch why we do this
1905 cap::copySelectionToStack();
1906 cmd = FuncRequest(LFUN_PASTE, "0");
1907 doDispatch(bv.cursor(), cmd);
1910 asArray(theSelection().get(), ar);
1911 bv.cursor().insert(ar);
1917 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1919 // only select with button 1
1920 if (cmd.button() != mouse_button::button1)
1923 Cursor & bvcur = cur.bv().cursor();
1925 // ignore motions deeper nested than the real anchor
1926 if (!bvcur.realAnchor().hasPart(cur)) {
1931 // set cursor after the inset if x is nearer to that position (bug 9748)
1932 cur.moveToClosestEdge(cmd.x());
1934 CursorSlice old = bvcur.top();
1936 // We continue with our existing selection or start a new one, so don't
1937 // reset the anchor.
1938 bvcur.setCursor(cur);
1939 // Did we actually move?
1940 if (cur.top() == old)
1941 // We didn't move one iota, so no need to change selection status
1942 // or update the screen.
1943 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1945 bvcur.setSelection();
1949 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1951 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1953 if (cmd.button() == mouse_button::button1) {
1954 if (!cur.selection())
1955 cur.noScreenUpdate();
1957 Cursor & bvcur = cur.bv().cursor();
1958 bvcur.selection(true);
1967 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1969 // try auto-correction
1970 if (lyxrc.autocorrection_math && cur.pos() != 0 && !cur.selection()
1971 && math_autocorrect(cur, c))
1974 //lyxerr << "interpret 2: '" << c << "'" << endl;
1975 docstring save_selection;
1976 if (c == '^' || c == '_')
1977 save_selection = grabAndEraseSelection(cur);
1980 Buffer * buf = cur.buffer();
1983 if (cur.inMacroMode()) {
1984 docstring name = cur.macroName();
1986 /// are we currently typing '#1' or '#2' or...?
1987 if (name == "\\#") {
1990 if (n >= 1 && n <= 9)
1991 cur.insert(new InsetMathMacroArgument(n));
1995 // do not finish macro for known * commands
1996 bool star_macro = c == '*'
1997 && (in_word_set(name.substr(1) + '*')
1998 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1999 if (isAlphaASCII(c) || star_macro) {
2000 cur.activeMacro()->setName(name + docstring(1, c));
2004 // handle 'special char' macros
2009 if (currentMode() != InsetMath::MATH_MODE)
2010 cur.niceInsert(createInsetMath("textbackslash", buf));
2012 cur.niceInsert(createInsetMath("backslash", buf));
2013 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
2015 cur.niceInsert(createInsetMath("mathcircumflex", buf));
2016 } else if (c == '{' || c == '%') {
2017 //using the saved selection as argument
2018 InsetMathUnknown * p = cur.activeMacro();
2020 MathData sel(cur.buffer());
2021 asArray(p->selection(), sel);
2024 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
2026 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
2027 } else if (c == '#') {
2028 LASSERT(cur.activeMacro(), return false);
2029 cur.activeMacro()->setName(name + docstring(1, c));
2032 cur.niceInsert(createInsetMath(docstring(1, c), buf));
2037 // One character big delimiters. The others are handled in
2038 // interpretString().
2039 latexkeys const * l = in_word_set(name.substr(1));
2040 if (name[0] == '\\' && l && l->inset == "big") {
2044 delim = from_ascii("\\{");
2047 delim = from_ascii("\\}");
2050 delim = docstring(1, c);
2053 if (InsetMathBig::isBigInsetDelim(delim)) {
2054 // name + delim ared a valid InsetMathBig.
2055 // We can't use cur.macroModeClose() because
2056 // it does not handle delim.
2057 InsetMathUnknown * p = cur.activeMacro();
2060 cur.cell().erase(cur.pos());
2061 cur.plainInsert(MathAtom(
2062 new InsetMathBig(name.substr(1), delim)));
2065 } else if (name == "\\smash" && c == '[') {
2066 // We can't use cur.macroModeClose() because
2067 // it would create an InsetMathPhantom
2068 InsetMathUnknown * p = cur.activeMacro();
2070 interpretChar(cur, c);
2074 // leave macro mode and try again if necessary
2075 if (cur.macroModeClose()) {
2076 MathAtom const atom = cur.prevAtom();
2077 if (atom->asNestInset() && atom->isActive()) {
2079 cur.nextInset()->edit(cur, true);
2083 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
2085 interpretChar(cur, c);
2090 // just clear selection on pressing the space bar
2091 if (cur.selection() && c == ' ') {
2092 cur.selection(false);
2097 //lyxerr << "starting with macro" << endl;
2098 bool reduced = cap::reduceSelectionToOneCell(cur);
2099 if (reduced || !cur.selection()) {
2100 InsetMath const * im = cur.inset().asInsetMath();
2101 InsetMathMacro const * macro = im ? im->asMacro()
2103 bool in_macro_name = macro
2104 && macro->displayMode() ==
2105 InsetMathMacro::DISPLAY_UNFOLDED;
2106 cur.recordUndoInset();
2107 docstring const safe = cap::grabAndEraseSelection(cur);
2108 if (!cur.inRegexped() && !in_macro_name)
2109 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
2111 cur.niceInsert(createInsetMath("backslash", buf));
2119 if (currentMode() != InsetMath::MATH_MODE)
2125 if (currentMode() != InsetMath::MATH_MODE) {
2126 // insert spaces in text or undecided mode,
2127 // but suppress direct insertion of two spaces in a row
2128 // the still allows typing '<space>a<space>' and deleting the 'a', but
2129 // it is better than nothing...
2130 pos_type const pos = cur.pos();
2131 pos_type const lastpos = cur.lastpos();
2132 if ((pos == 0 && lastpos == 0)
2133 || (pos == 0 && cur.nextAtom()->getChar() != ' ')
2134 || (pos == lastpos && cur.prevAtom()->getChar() != ' ')
2135 || (pos > 0 && cur.prevAtom()->getChar() != ' '
2136 && cur.nextAtom()->getChar() != ' ')) {
2138 // FIXME: we have to enable full redraw here because of the
2139 // visual box corners that define the inset. If we know for
2140 // sure that we stay within the same cell we can optimize for
2142 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2146 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
2147 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
2148 // FIXME: we have to enable full redraw here because of the
2149 // visual box corners that define the inset. If we know for
2150 // sure that we stay within the same cell we can optimize for
2152 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2156 if (cur.popForward()) {
2157 // FIXME: we have to enable full redraw here because of the
2158 // visual box corners that define the inset. If we know for
2159 // sure that we stay within the same cell we can optimize for
2161 //cur.screenUpdateFlags(Update::FitCursor);
2165 // if we are at the very end, leave the formula
2166 return cur.pos() != cur.lastpos();
2169 // These should be treated differently when not in text mode:
2170 if (cur.inRegexped()) {
2173 cur.niceInsert(createInsetMath("mathcircumflex", buf));
2180 cur.niceInsert(createInsetMath(docstring(1, c), buf));
2183 cur.niceInsert(createInsetMath("sim", buf));
2189 } else if (currentMode() != InsetMath::TEXT_MODE) {
2191 cur.recordUndoInset();
2192 script(cur, false, save_selection);
2196 cur.recordUndoInset();
2197 script(cur, true, save_selection);
2201 cur.niceInsert(createInsetMath("sim", buf));
2204 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
2205 MathAtom const atom(new InsetMathChar(c));
2206 if (cur.prevInset() && cur.prevInset()->asInsetMath()->name() == "text") {
2207 // reuse existing \text inset
2208 cur.prevInset()->asInsetMath()->cell(0).push_back(atom);
2210 MathAtom at = createInsetMath("text", buf);
2211 at.nucleus()->cell(0).push_back(atom);
2219 cur.niceInsert(createInsetMath("textasciicircum", buf));
2223 cur.niceInsert(createInsetMath("textasciitilde", buf));
2228 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
2229 c == '%' || c == '_') {
2230 cur.niceInsert(createInsetMath(docstring(1, c), buf));
2234 // no special circumstances, so insert the character without any fuss
2240 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
2242 if (str == "\\limits" || str == "\\nolimits") {
2243 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
2244 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
2247 cur.message(bformat(_("Cannot apply %1$s here."), str));
2251 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
2253 if (!cur.empty() && cur.pos() > 0 &&
2254 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
2255 if (InsetMathBig::isBigInsetDelim(str)) {
2256 docstring prev = asString(cur.cell()[cur.pos() - 1]);
2257 if (prev[0] == '\\') {
2258 prev = prev.substr(1);
2259 latexkeys const * l = in_word_set(prev);
2260 if (l && l->inset == "big") {
2261 cur.recordUndoSelection();
2262 cur.cell()[cur.pos() - 1] =
2263 MathAtom(new InsetMathBig(prev, str));
2273 bool InsetMathNest::script(Cursor & cur, bool up)
2275 return script(cur, up, docstring());
2279 bool InsetMathNest::script(Cursor & cur, bool up,
2280 docstring const & save_selection)
2282 // Hack to get \^ and \_ working
2283 //lyxerr << "handling script: up: " << up << endl;
2284 if (cur.inMacroMode() && cur.macroName() == "\\") {
2286 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
2288 interpretChar(cur, '_');
2292 cur.macroModeClose();
2293 if (asScriptInset() && cur.idx() == 0) {
2294 // we are in a nucleus of a script inset, move to _our_ script
2295 InsetMathScript * inset = asScriptInset();
2296 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
2298 cur.idx() = inset->idxOfScript(up);
2300 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
2302 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2305 cur.idx() = inset->idxOfScript(up);
2306 cur.pos() = cur.lastpos();
2308 // convert the thing to our left to a scriptinset or create a new
2309 // one if in the very first position of the array
2310 if (cur.pos() == 0) {
2311 //lyxerr << "new scriptinset" << endl;
2312 cur.insert(new InsetMathScript(buffer_, up));
2314 //lyxerr << "converting prev atom " << endl;
2315 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
2318 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2319 // See comment in MathParser.cpp for special handling of {}-bases
2325 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
2326 cur.niceInsert(save_selection);
2328 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2333 bool InsetMathNest::completionSupported(Cursor const & cur) const
2335 return cur.inMacroMode();
2339 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2341 return cur.inMacroMode();
2345 bool InsetMathNest::automaticInlineCompletion() const
2347 return lyxrc.completion_inline_math;
2351 bool InsetMathNest::automaticPopupCompletion() const
2353 return lyxrc.completion_popup_math;
2357 CompletionList const *
2358 InsetMathNest::createCompletionList(Cursor const & cur) const
2360 if (!cur.inMacroMode())
2363 return new MathCompletionList(cur);
2367 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2369 if (!cur.inMacroMode())
2372 return cur.activeMacro()->name();
2376 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s, bool finished)
2378 if (cur.buffer()->isReadonly() || !cur.inMacroMode())
2381 // Contrary to Text, the whole inset should be recorded (#12581).
2382 cur.recordUndoInset();
2384 // append completion to active macro
2385 InsetMathUnknown * inset = cur.activeMacro();
2386 inset->setName(inset->name() + s);
2391 // FIXME: this creates duplicates in the completion popup
2392 // which looks ugly. Moreover the changes the list lengths
2393 // which seems to confuse the popup as well.
2394 MathCompletionList::addToFavorites(inset->name());
2396 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2398 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2404 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2405 Dimension & dim) const
2407 Inset const * inset = cur.activeMacro();
2411 // get inset dimensions
2412 dim = cur.bv().coordCache().insets().dim(inset);
2413 // FIXME: these 3 are no accurate, but should depend on the font.
2414 // Now the popup jumps down if you enter a char with descent > 0.
2419 Point xy = cur.bv().coordCache().insets().xy(inset);
2425 ////////////////////////////////////////////////////////////////////
2427 MathCompletionList::MathCompletionList(Cursor const & cur)
2429 // fill it with macros from the buffer
2430 MacroNameSet macros;
2431 cur.buffer()->listMacroNames(macros);
2432 MacroNameSet::const_iterator it;
2433 for (it = macros.begin(); it != macros.end(); ++it) {
2434 if (cur.buffer()->getMacro(*it, cur, false))
2435 locals.push_back("\\" + *it);
2437 sort(locals.begin(), locals.end());
2439 if (!globals.empty())
2442 // fill in global macros
2444 MacroTable::globalMacros().getMacroNames(macros, false);
2445 //lyxerr << "Globals completion macros: ";
2446 for (it = macros.begin(); it != macros.end(); ++it) {
2447 //lyxerr << "\\" + *it << " ";
2448 globals.push_back("\\" + *it);
2450 //lyxerr << std::endl;
2452 // fill in global commands
2453 globals.push_back(from_ascii("\\boxed"));
2454 globals.push_back(from_ascii("\\fbox"));
2455 globals.push_back(from_ascii("\\framebox"));
2456 globals.push_back(from_ascii("\\makebox"));
2457 globals.push_back(from_ascii("\\kern"));
2458 globals.push_back(from_ascii("\\xhookrightarrow"));
2459 globals.push_back(from_ascii("\\xhookleftarrow"));
2460 globals.push_back(from_ascii("\\xrightarrow"));
2461 globals.push_back(from_ascii("\\xRightarrow"));
2462 globals.push_back(from_ascii("\\xrightharpoondown"));
2463 globals.push_back(from_ascii("\\xrightharpoonup"));
2464 globals.push_back(from_ascii("\\xrightleftharpoons"));
2465 globals.push_back(from_ascii("\\xleftarrow"));
2466 globals.push_back(from_ascii("\\xLeftarrow"));
2467 globals.push_back(from_ascii("\\xleftharpoondown"));
2468 globals.push_back(from_ascii("\\xleftharpoonup"));
2469 globals.push_back(from_ascii("\\xleftrightarrow"));
2470 globals.push_back(from_ascii("\\xLeftrightarrow"));
2471 globals.push_back(from_ascii("\\xleftrightharpoons"));
2472 globals.push_back(from_ascii("\\xmapsto"));
2473 globals.push_back(from_ascii("\\split"));
2474 globals.push_back(from_ascii("\\gathered"));
2475 globals.push_back(from_ascii("\\aligned"));
2476 globals.push_back(from_ascii("\\alignedat"));
2477 globals.push_back(from_ascii("\\cases"));
2478 globals.push_back(from_ascii("\\substack"));
2479 globals.push_back(from_ascii("\\xymatrix"));
2480 globals.push_back(from_ascii("\\Diagram"));
2481 globals.push_back(from_ascii("\\subarray"));
2482 globals.push_back(from_ascii("\\array"));
2483 globals.push_back(from_ascii("\\sqrt"));
2484 globals.push_back(from_ascii("\\root"));
2485 globals.push_back(from_ascii("\\tabular"));
2486 globals.push_back(from_ascii("\\sideset"));
2487 globals.push_back(from_ascii("\\stackrel"));
2488 globals.push_back(from_ascii("\\stackrelthree"));
2489 globals.push_back(from_ascii("\\binom"));
2490 globals.push_back(from_ascii("\\choose"));
2491 globals.push_back(from_ascii("\\brace"));
2492 globals.push_back(from_ascii("\\brack"));
2493 globals.push_back(from_ascii("\\frac"));
2494 globals.push_back(from_ascii("\\over"));
2495 globals.push_back(from_ascii("\\nicefrac"));
2496 globals.push_back(from_ascii("\\unitfrac"));
2497 globals.push_back(from_ascii("\\unitfracthree"));
2498 globals.push_back(from_ascii("\\unitone"));
2499 globals.push_back(from_ascii("\\unittwo"));
2500 globals.push_back(from_ascii("\\infer"));
2501 globals.push_back(from_ascii("\\atop"));
2502 globals.push_back(from_ascii("\\lefteqn"));
2503 globals.push_back(from_ascii("\\boldsymbol"));
2504 globals.push_back(from_ascii("\\bm"));
2505 globals.push_back(from_ascii("\\color"));
2506 globals.push_back(from_ascii("\\normalcolor"));
2507 globals.push_back(from_ascii("\\textcolor"));
2508 globals.push_back(from_ascii("\\cfrac"));
2509 globals.push_back(from_ascii("\\cfracleft"));
2510 globals.push_back(from_ascii("\\cfracright"));
2511 globals.push_back(from_ascii("\\dfrac"));
2512 globals.push_back(from_ascii("\\tfrac"));
2513 globals.push_back(from_ascii("\\dbinom"));
2514 globals.push_back(from_ascii("\\tbinom"));
2515 globals.push_back(from_ascii("\\hphantom"));
2516 globals.push_back(from_ascii("\\phantom"));
2517 globals.push_back(from_ascii("\\vphantom"));
2518 globals.push_back(from_ascii("\\cancel"));
2519 globals.push_back(from_ascii("\\bcancel"));
2520 globals.push_back(from_ascii("\\xcancel"));
2521 globals.push_back(from_ascii("\\cancelto"));
2522 globals.push_back(from_ascii("\\smash"));
2523 globals.push_back(from_ascii("\\mathclap"));
2524 globals.push_back(from_ascii("\\mathllap"));
2525 globals.push_back(from_ascii("\\mathrlap"));
2526 globals.push_back(from_ascii("\\ensuremath"));
2527 MathWordList const & words = mathedWordList();
2528 MathWordList::const_iterator it2;
2529 //lyxerr << "Globals completion commands: ";
2530 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2531 if (it2->second.inset != "macro" && !it2->second.hidden) {
2532 // macros are already read from MacroTable::globalMacros()
2533 globals.push_back('\\' + it2->first);
2534 //lyxerr << '\\' + it2->first << ' ';
2537 //lyxerr << std::endl;
2538 sort(globals.begin(), globals.end());
2542 MathCompletionList::~MathCompletionList()
2547 size_type MathCompletionList::size() const
2549 return locals.size() + globals.size();
2553 docstring const & MathCompletionList::data(size_t idx) const
2555 size_t lsize = locals.size();
2557 return globals[idx - lsize];
2563 std::string MathCompletionList::icon(size_t idx) const
2565 // get the latex command
2567 size_t lsize = locals.size();
2569 cmd = globals[idx - lsize];
2573 // get the icon name by stripping the backslash
2574 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2575 if (icon_name.empty())
2576 return std::string();
2577 return "math/" + to_utf8(icon_name);
2580 std::vector<docstring> MathCompletionList::globals;