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"
33 #include "MathFactory.h"
34 #include "InsetMathMacro.h"
35 #include "InsetMathMacroArgument.h"
36 #include "MathParser.h"
37 #include "MathStream.h"
38 #include "MathSupport.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
43 #include "CoordCache.h"
45 #include "CutAndPaste.h"
46 #include "DispatchResult.h"
48 #include "FuncRequest.h"
49 #include "FuncStatus.h"
50 #include "LaTeXFeatures.h"
53 #include "MetricsInfo.h"
57 #include "frontends/Application.h"
58 #include "frontends/Clipboard.h"
59 #include "frontends/Painter.h"
60 #include "frontends/Selection.h"
62 #include "support/debug.h"
63 #include "support/docstream.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.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)
87 // FIXME This should not really be necessary, but when we are
88 // initializing the table of global macros, we create macros
89 // with no associated Buffer.
95 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
96 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
100 InsetMathNest::~InsetMathNest()
102 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
103 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
104 for (; it != end; ++it)
106 it->first->clearLastInset(this);
110 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
112 cells_ = inset.cells_;
114 mouse_hover_.clear();
115 InsetMath::operator=(inset);
120 void InsetMathNest::setBuffer(Buffer & buffer)
122 InsetMath::setBuffer(buffer);
123 for (MathData & data : cells_)
124 data.setBuffer(buffer);
128 idx_type InsetMathNest::nargs() const
130 return cells_.size();
134 void InsetMathNest::cursorPos(BufferView const & bv,
135 CursorSlice const & sl, bool /*boundary*/,
136 int & x, int & y) const
138 // FIXME: This is a hack. Ideally, the coord cache should not store
139 // absolute positions, but relative ones. This would mean to call
140 // setXY() not in MathData::draw(), but in the parent insets' draw()
141 // with the correctly adjusted x,y values. But this means that we'd have
142 // to touch all (math)inset's draw() methods. Right now, we'll store
143 // absolute value, and make them here relative, only to make them
144 // absolute again when actually drawing the cursor. What a mess.
145 LASSERT(&sl.inset() == this, return);
146 MathData const & ar = sl.cell();
147 CoordCache const & coord_cache = bv.coordCache();
148 if (!coord_cache.getArrays().has(&ar)) {
149 // this can (semi-)legally happen if we just created this cell
150 // and it never has been drawn before. So don't ASSERT.
151 //lyxerr << "no cached data for array " << &ar << endl;
156 Point const pt = coord_cache.getArrays().xy(&ar);
157 if (!coord_cache.getInsets().has(this)) {
159 //lyxerr << "no cached data for inset " << this << endl;
164 Point const pt2 = coord_cache.getInsets().xy(this);
165 //lyxerr << "retrieving position cache for MathData "
166 // << pt.x_ << ' ' << pt.y_ << endl;
167 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
169 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
170 // << " asc: " << ascent() << " des: " << descent()
171 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
172 // move cursor visually into empty cells ("blue rectangles");
174 Dimension const dim = coord_cache.getArrays().dim(&ar);
180 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
183 for (auto const & cell : cells_) {
185 cell.metrics(m, dim);
190 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
192 for (idx_type i = 0, n = nargs(); i != n; ++i)
193 cell(i).updateBuffer(it, utype, deleted);
198 bool InsetMathNest::idxNext(Cursor & cur) const
200 LASSERT(&cur.inset() == this, return false);
201 if (cur.idx() == cur.lastidx())
209 bool InsetMathNest::idxForward(Cursor & cur) const
215 bool InsetMathNest::idxPrev(Cursor & cur) const
217 LASSERT(&cur.inset() == this, return false);
221 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
226 bool InsetMathNest::idxBackward(Cursor & cur) const
232 bool InsetMathNest::idxFirst(Cursor & cur) const
234 LASSERT(&cur.inset() == this, return false);
237 cur.idx() = firstIdx();
243 bool InsetMathNest::idxLast(Cursor & cur) const
245 LASSERT(&cur.inset() == this, return false);
248 cur.idx() = lastIdx();
249 cur.pos() = cur.lastpos();
254 void InsetMathNest::dump() const
256 odocstringstream oss;
257 otexrowstream ots(oss);
258 TeXMathStream os(ots);
259 os << "---------------------------------------------\n";
262 for (idx_type i = 0, n = nargs(); i != n; ++i)
263 os << cell(i) << "\n";
264 os << "---------------------------------------------\n";
265 lyxerr << to_utf8(oss.str());
269 void InsetMathNest::draw(PainterInfo &, int, int) const
273 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
279 void InsetMathNest::validate(LaTeXFeatures & features) const
281 for (idx_type i = 0; i < nargs(); ++i)
282 cell(i).validate(features);
286 void InsetMathNest::replace(ReplaceData & rep)
288 for (idx_type i = 0; i < nargs(); ++i)
289 cell(i).replace(rep);
293 bool InsetMathNest::contains(MathData const & ar) const
295 for (idx_type i = 0; i < nargs(); ++i)
296 if (cell(i).contains(ar))
302 bool InsetMathNest::lock() const
308 void InsetMathNest::lock(bool l)
314 bool InsetMathNest::isActive() const
320 MathData InsetMathNest::glue() const
323 for (size_t i = 0; i < nargs(); ++i)
329 void InsetMathNest::write(TeXMathStream & os) const
331 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
332 ModeSpecifier specifier(os, currentMode(), lockedMode());
333 docstring const latex_name = name();
334 os << '\\' << latex_name;
335 os.inMathClass(asClassInset());
336 for (size_t i = 0; i < nargs(); ++i) {
337 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
338 os << '{' << cell(i) << '}';
341 os.pendingSpace(true);
342 if (lock_ && !os.latex()) {
344 os.pendingSpace(true);
346 os.inMathClass(false);
350 void InsetMathNest::normalize(NormalStream & os) const
353 for (size_t i = 0; i < nargs(); ++i)
354 os << ' ' << cell(i);
359 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
361 TeXMathStream::OutputType ot;
362 if (runparams.find_effective())
363 ot = TeXMathStream::wsSearchAdv;
364 else if (runparams.dryrun)
365 ot = TeXMathStream::wsDryrun;
367 ot = TeXMathStream::wsDefault;
368 TeXMathStream wi(os, runparams.moving_arg, true, ot,
370 wi.strikeoutMath(runparams.inDeletedInset);
371 if (runparams.inulemcmd) {
372 wi.ulemCmd(TeXMathStream::UNDERLINE);
373 if (runparams.local_font) {
374 FontInfo f = runparams.local_font->fontInfo();
375 if (f.strikeout() == FONT_ON)
376 wi.ulemCmd(TeXMathStream::STRIKEOUT);
379 wi.canBreakLine(os.canBreakLine());
380 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
383 // Reset parbreak and command termination status after a math inset.
385 os.canBreakLine(wi.canBreakLine());
386 os.terminateCommand(false);
390 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
393 mouse_hover_[bv] = mouse_hover;
398 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
402 MathData & ar = cur.cell();
403 // remove base-only "scripts"
404 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
405 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
406 if (p && p->nargs() == 1) {
407 MathData ar = p->nuc();
410 cur.adjust(i, ar.size() - 1);
414 // glue adjacent font insets of the same kind
415 for (pos_type i = 0; i + 1 < size(); ++i) {
416 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
417 InsetMathFont const * q = operator[](i + 1)->asFontInset();
418 if (p && q && p->name() == q->name()) {
419 p->cell(0).append(q->cell(0));
429 void InsetMathNest::handleFont
430 (Cursor & cur, docstring const & arg, char const * const font)
432 handleFont(cur, arg, from_ascii(font));
436 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
437 docstring const & font)
439 cur.recordUndoSelection();
441 // this whole function is a hack and won't work for incremental font
443 if (cur.inset().asInsetMath()->name() == font)
444 cur.handleFont(to_utf8(font));
446 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
450 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
452 handleNest(cur, nest, docstring());
456 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
457 docstring const & arg)
459 DocIterator const i1 = cur.selectionBegin();
460 DocIterator const i2 = cur.selectionEnd();
461 if (!i1.inset().asInsetMath())
463 if (i1.idx() == i2.idx()) {
464 // the easy case where only one cell is selected
465 cur.handleNest(nest);
470 // multiple selected cells in a simple non-grid inset
471 if (i1.inset().nrows() == 0 || i1.inset().ncols() == 0) {
472 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
478 cur.pos() = cur.lastpos();
482 cur.handleNest(nest);
488 // the complicated case with multiple selected cells in a grid
491 cap::region(i1.top(), i2.top(), r1, r2, c1, c2);
492 for (row_type row = r1; row <= r2; ++row) {
493 for (col_type col = c1; col <= c2; ++col) {
496 cur.idx() = i1.inset().index(row, col);
499 cur.pos() = cur.lastpos();
503 cur.handleNest(nest);
510 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
512 cur.recordUndoSelection();
515 font.fromString(to_utf8(arg), b);
516 if (font.fontInfo().color() != Color_inherit &&
517 font.fontInfo().color() != Color_ignore)
518 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
520 // FIXME: support other font changes here as well?
523 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
525 //LYXERR0("InsetMathNest: request: " << cmd);
527 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
529 FuncCode const act = cmd.action();
532 case LFUN_CLIPBOARD_PASTE:
533 parseflg |= Parse::VERBATIM;
536 if (cur.currentMode() != MATH_MODE)
537 parseflg |= Parse::TEXTMODE;
538 cur.recordUndoSelection();
539 cur.message(_("Paste"));
540 replaceSelection(cur);
542 if (cmd.argument().empty() && !theClipboard().isInternal())
543 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
546 idocstringstream is(cmd.argument());
548 topaste = cap::selection(n, make_pair(buffer().params().documentClassPtr(),
549 buffer().params().authors()));
551 InsetMath const * im = cur.inset().asInsetMath();
552 InsetMathMacro const * macro = im ? im->asMacro() : nullptr;
553 // do not allow pasting a backslash in the name of a macro
555 && macro->displayMode() == InsetMathMacro::DISPLAY_UNFOLDED
556 && support::contains(topaste, char_type('\\'))) {
557 LYXERR0("Removing backslash from pasted string");
558 topaste = subst(topaste, from_ascii("\\"), docstring());
560 cur.niceInsert(topaste, parseflg, false);
561 cur.clearSelection(); // bug 393
562 cur.forceBufferUpdate();
569 cutSelection(cur, true);
570 cur.message(_("Cut"));
571 // Prevent stale position >= size crash
572 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
574 cur.forceBufferUpdate();
577 case LFUN_MOUSE_PRESS:
578 lfunMousePress(cur, cmd);
581 case LFUN_MOUSE_MOTION:
582 lfunMouseMotion(cur, cmd);
585 case LFUN_MOUSE_RELEASE:
586 lfunMouseRelease(cur, cmd);
589 case LFUN_FINISHED_LEFT: // in math, left is backwards
590 case LFUN_FINISHED_BACKWARD:
591 cur.bv().cursor() = cur;
594 case LFUN_FINISHED_RIGHT: // in math, right is forward
595 case LFUN_FINISHED_FORWARD:
597 cur.bv().cursor() = cur;
600 case LFUN_WORD_RIGHT:
602 case LFUN_WORD_BACKWARD:
603 case LFUN_WORD_FORWARD:
604 case LFUN_CHAR_RIGHT:
606 case LFUN_CHAR_BACKWARD:
607 case LFUN_CHAR_FORWARD:
608 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
610 case LFUN_WORD_RIGHT_SELECT:
611 case LFUN_WORD_LEFT_SELECT:
612 case LFUN_WORD_BACKWARD_SELECT:
613 case LFUN_WORD_FORWARD_SELECT:
614 case LFUN_CHAR_RIGHT_SELECT:
615 case LFUN_CHAR_LEFT_SELECT:
616 case LFUN_CHAR_BACKWARD_SELECT:
617 case LFUN_CHAR_FORWARD_SELECT: {
618 // are we in a selection?
619 bool select = (act == LFUN_WORD_RIGHT_SELECT
620 || act == LFUN_WORD_LEFT_SELECT
621 || act == LFUN_WORD_BACKWARD_SELECT
622 || act == LFUN_WORD_FORWARD_SELECT
623 || act == LFUN_CHAR_RIGHT_SELECT
624 || act == LFUN_CHAR_LEFT_SELECT
625 || act == LFUN_CHAR_BACKWARD_SELECT
626 || act == LFUN_CHAR_FORWARD_SELECT);
628 bool word = (act == LFUN_WORD_RIGHT_SELECT
629 || act == LFUN_WORD_LEFT_SELECT
630 || act == LFUN_WORD_BACKWARD_SELECT
631 || act == LFUN_WORD_FORWARD_SELECT
632 || act == LFUN_WORD_RIGHT
633 || act == LFUN_WORD_LEFT
634 || act == LFUN_WORD_BACKWARD
635 || act == LFUN_WORD_FORWARD);
636 // are we moving forward or backwards?
637 // If the command was RIGHT or LEFT, then whether we're moving forward
638 // or backwards depends on the cursor movement mode (logical or visual):
639 // * in visual mode, since math is always LTR, right -> forward,
641 // * in logical mode, the mapping is determined by the
642 // reverseDirectionNeeded() function
645 FuncCode finish_lfun;
647 if (act == LFUN_CHAR_FORWARD
648 || act == LFUN_CHAR_FORWARD_SELECT
649 || act == LFUN_WORD_FORWARD
650 || act == LFUN_WORD_FORWARD_SELECT) {
652 finish_lfun = LFUN_FINISHED_FORWARD;
654 else if (act == LFUN_CHAR_BACKWARD
655 || act == LFUN_CHAR_BACKWARD_SELECT
656 || act == LFUN_WORD_BACKWARD
657 || act == LFUN_WORD_BACKWARD_SELECT) {
659 finish_lfun = LFUN_FINISHED_BACKWARD;
662 bool right = (act == LFUN_CHAR_RIGHT_SELECT
663 || act == LFUN_CHAR_RIGHT
664 || act == LFUN_WORD_RIGHT_SELECT
665 || act == LFUN_WORD_RIGHT);
666 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
672 finish_lfun = LFUN_FINISHED_RIGHT;
674 finish_lfun = LFUN_FINISHED_LEFT;
676 // Now that we know exactly what we want to do, let's do it!
677 cur.selHandle(select);
679 cur.macroModeClose();
680 // try moving forward or backwards as necessary...
681 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
682 // ... and if movement failed, then finish forward or backwards
684 cmd = FuncRequest(finish_lfun);
692 case LFUN_PARAGRAPH_UP:
693 case LFUN_PARAGRAPH_DOWN:
694 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
696 case LFUN_DOWN_SELECT:
698 case LFUN_PARAGRAPH_UP_SELECT:
699 case LFUN_PARAGRAPH_DOWN_SELECT: {
700 // close active macro
701 if (cur.inMacroMode()) {
702 cur.macroModeClose();
706 // stop/start the selection
707 bool select = act == LFUN_DOWN_SELECT
708 || act == LFUN_UP_SELECT
709 || act == LFUN_PARAGRAPH_DOWN_SELECT
710 || act == LFUN_PARAGRAPH_UP_SELECT;
711 cur.selHandle(select);
714 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
715 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
716 bool successful = cur.upDownInMath(up);
720 if (cur.fixIfBroken())
721 // FIXME: Something bad happened. We pass the corrected Cursor
722 // instead of letting things go worse.
725 // We did not manage to move the cursor.
730 case LFUN_MOUSE_DOUBLE:
731 case LFUN_WORD_SELECT:
733 cur.bv().mouseSetCursor(cur);
734 cur.pos() = cur.lastpos();
735 cur.bv().mouseSetCursor(cur, true);
738 case LFUN_MOUSE_TRIPLE:
741 cur.bv().mouseSetCursor(cur);
742 cur.idx() = cur.lastidx();
743 cur.pos() = cur.lastpos();
744 cur.bv().mouseSetCursor(cur, true);
747 case LFUN_LINE_BEGIN:
748 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
750 case LFUN_LINE_BEGIN_SELECT:
751 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
752 act == LFUN_WORD_LEFT_SELECT ||
753 act == LFUN_LINE_BEGIN_SELECT);
754 cur.macroModeClose();
755 if (cur.pos() != 0) {
757 } else if (cur.col() != 0) {
758 cur.idx() -= cur.col();
760 } else if (cur.idx() != 0) {
764 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
770 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
772 case LFUN_LINE_END_SELECT:
773 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
774 act == LFUN_WORD_RIGHT_SELECT ||
775 act == LFUN_LINE_END_SELECT);
776 cur.macroModeClose();
778 if (cur.pos() != cur.lastpos()) {
779 cur.pos() = cur.lastpos();
780 } else if (ncols() && (cur.col() != cur.lastcol())) {
781 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
782 cur.pos() = cur.lastpos();
783 } else if (cur.idx() != cur.lastidx()) {
784 cur.idx() = cur.lastidx();
785 cur.pos() = cur.lastpos();
787 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
792 case LFUN_CELL_FORWARD:
793 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
794 cur.selHandle(false);
796 cur.macroModeClose();
797 if (!cur.inset().idxNext(cur)) {
798 if (cur.lastidx() == 0)
801 cur.idx() = firstIdx();
807 case LFUN_CELL_BACKWARD:
808 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
809 cur.selHandle(false);
811 cur.macroModeClose();
812 if (!cur.inset().idxPrev(cur)) {
813 if (cur.lastidx() == 0)
816 cur.idx() = cur.lastidx();
817 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
822 case LFUN_WORD_DELETE_BACKWARD:
823 case LFUN_CHAR_DELETE_BACKWARD:
825 // May affect external cell:
826 cur.recordUndoInset();
827 else if (!cur.inMacroMode())
828 cur.recordUndoSelection();
829 // if the inset can not be removed from within, delete it
830 if (!cur.backspace(cmd.getArg(0) != "confirm")) {
831 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
832 cur.innerText()->dispatch(cur, newcmd);
836 case LFUN_WORD_DELETE_FORWARD:
837 case LFUN_CHAR_DELETE_FORWARD:
838 if (cur.pos() == cur.lastpos())
839 // May affect external cell:
840 cur.recordUndoInset();
842 cur.recordUndoSelection();
843 // if the inset can not be removed from within, delete it
844 if (!cur.erase(cmd.getArg(0) != "confirm")) {
845 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
846 cur.innerText()->dispatch(cur, newcmd);
852 cur.clearSelection();
854 if (cur.inMacroMode())
855 cur.macroModeClose(true);
857 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
863 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
864 // that is traversed by a single <CursorLeft>/<CursorRight>.
865 case LFUN_INSET_TOGGLE:
871 case LFUN_SELF_INSERT:
872 // special case first for big delimiters
873 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
876 for (char_type c : cmd.argument()) {
877 // Don't record undo steps if we are in macro mode and thus
878 // cmd.argument is the next character of the macro name.
879 // Otherwise we'll get an invalid cursor if we undo after
880 // the macro was finished and the macro is a known command,
881 // e.g. sqrt. Cursor::macroModeClose replaces in this case
882 // the InsetMathUnknown with name "frac" by an empty
883 // InsetMathFrac -> a pos value > 0 is invalid.
884 // A side effect is that an undo before the macro is finished
885 // undoes the complete macro, not only the last character.
886 // At the time we hit '\' we are not in macro mode, still.
887 if (!cur.inMacroMode())
888 cur.recordUndoSelection();
890 // special handling of space. If we insert an inset
891 // via macro mode, we want to put the cursor inside it
892 // if relevant. Think typing "\frac<space>".
894 && cur.inMacroMode() && cur.macroName() != "\\"
895 && cur.macroModeClose() && cur.pos() > 0)
896 cur.editInsertedInset();
897 else if (!interpretChar(cur, c)) {
898 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
900 // FIXME: can we avoid skipping the end of the string?
906 //case LFUN_SERVER_GET_XY:
909 case LFUN_SERVER_SET_XY: {
910 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
913 istringstream is(to_utf8(cmd.argument()));
919 // Special casing for superscript in case of LyX handling
921 case LFUN_ACCENT_CIRCUMFLEX:
922 if (cmd.argument().empty()) {
923 // do superscript if LyX handles
925 cur.recordUndoInset();
926 script(cur, true, grabAndEraseSelection(cur));
930 case LFUN_ACCENT_UMLAUT:
931 case LFUN_ACCENT_ACUTE:
932 case LFUN_ACCENT_GRAVE:
933 case LFUN_ACCENT_BREVE:
934 case LFUN_ACCENT_DOT:
935 case LFUN_ACCENT_MACRON:
936 case LFUN_ACCENT_CARON:
937 case LFUN_ACCENT_TILDE:
938 case LFUN_ACCENT_CEDILLA:
939 case LFUN_ACCENT_CIRCLE:
940 case LFUN_ACCENT_UNDERDOT:
941 case LFUN_ACCENT_TIE:
942 case LFUN_ACCENT_OGONEK:
943 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
947 case LFUN_TEXTSTYLE_APPLY:
948 case LFUN_TEXTSTYLE_UPDATE:
949 handleFont2(cur, cmd.argument());
953 if (currentMode() != MATH_MODE)
954 handleFont(cur, cmd.argument(), "textbf");
956 handleFont(cur, cmd.argument(), "mathbf");
958 case LFUN_FONT_BOLDSYMBOL:
959 if (currentMode() != MATH_MODE)
960 handleFont(cur, cmd.argument(), "textbf");
962 handleFont(cur, cmd.argument(), "boldsymbol");
965 if (currentMode() != MATH_MODE)
966 handleFont(cur, cmd.argument(), "textsf");
968 handleFont(cur, cmd.argument(), "mathsf");
971 if (currentMode() != MATH_MODE)
972 handleFont(cur, cmd.argument(), "emph");
974 handleFont(cur, cmd.argument(), "mathcal");
976 case LFUN_FONT_ROMAN:
977 if (currentMode() != MATH_MODE)
978 handleFont(cur, cmd.argument(), "textrm");
980 handleFont(cur, cmd.argument(), "mathrm");
982 case LFUN_FONT_TYPEWRITER:
983 if (currentMode() != MATH_MODE)
984 handleFont(cur, cmd.argument(), "texttt");
986 handleFont(cur, cmd.argument(), "mathtt");
989 handleFont(cur, cmd.argument(), "mathfrak");
992 if (currentMode() != MATH_MODE)
993 handleFont(cur, cmd.argument(), "textit");
995 handleFont(cur, cmd.argument(), "mathit");
998 if (currentMode() != MATH_MODE)
999 // FIXME: should be "noun"
1000 handleFont(cur, cmd.argument(), "textsc");
1002 handleFont(cur, cmd.argument(), "mathbb");
1004 case LFUN_FONT_DEFAULT:
1005 handleFont(cur, cmd.argument(), "textnormal");
1007 case LFUN_FONT_UNDERLINE:
1009 cur.handleNest(createInsetMath("underline", cur.buffer()));
1012 case LFUN_MATH_MODE: {
1014 // ignore math-mode on when already in math mode
1015 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1017 cur.recordUndoSelection();
1018 cur.macroModeClose();
1019 docstring const save_selection = grabAndEraseSelection(cur);
1021 if (currentMode() != Inset::MATH_MODE)
1022 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1024 cur.plainInsert(createInsetMath("text", buffer_));
1026 cur.pushBackward(*cur.nextInset());
1027 cur.niceInsert(save_selection);
1028 cur.forceBufferUpdate();
1030 if (currentMode() == Inset::TEXT_MODE) {
1031 cur.recordUndoSelection();
1032 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1033 cur.message(_("create new math text environment ($...$)"));
1035 handleFont(cur, cmd.argument(), "textrm");
1036 cur.message(_("entered math text mode (textrm)"));
1042 case LFUN_REGEXP_MODE: {
1043 InsetMath * im = cur.inset().asInsetMath();
1045 InsetMathHull * i = im->asHullInset();
1046 if (i && i->getType() == hullRegexp) {
1047 cur.message(_("Already in regular expression mode"));
1051 cur.macroModeClose();
1052 docstring const save_selection = grabAndEraseSelection(cur);
1054 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1056 cur.pushBackward(*cur.nextInset());
1057 cur.niceInsert(save_selection);
1058 cur.message(_("Regular expression editor mode"));
1062 case LFUN_MATH_FONT_STYLE: {
1063 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1064 doDispatch(cur, fr);
1068 case LFUN_MATH_SIZE: {
1069 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1070 doDispatch(cur, fr);
1074 case LFUN_MATH_MATRIX: {
1080 idocstringstream is(cmd.argument());
1081 is >> m >> n >> v_align >> h_align;
1087 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1088 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1092 case LFUN_MATH_AMS_MATRIX: {
1096 docstring name = from_ascii("matrix");
1097 idocstringstream is(cmd.argument());
1098 is >> m >> n >> name;
1103 // check if we have a valid decoration
1104 if (name != "pmatrix" && name != "bmatrix"
1105 && name != "Bmatrix" && name != "vmatrix"
1106 && name != "Vmatrix" && name != "matrix"
1107 && name != "smallmatrix")
1108 name = from_ascii("matrix");
1111 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1115 case LFUN_MATH_DELIM: {
1117 docstring rs = split(cmd.argument(), ls, ' ');
1118 // Reasonable default values
1124 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1128 case LFUN_MATH_BIGDELIM: {
1129 docstring const lname = from_utf8(cmd.getArg(0));
1130 docstring const ldelim = from_utf8(cmd.getArg(1));
1131 docstring const rname = from_utf8(cmd.getArg(2));
1132 docstring const rdelim = from_utf8(cmd.getArg(3));
1133 latexkeys const * l = in_word_set(lname);
1134 bool const have_l = l && l->inset == "big" &&
1135 InsetMathBig::isBigInsetDelim(ldelim);
1136 l = in_word_set(rname);
1137 bool const have_r = l && l->inset == "big" &&
1138 InsetMathBig::isBigInsetDelim(rdelim);
1139 // We mimic LFUN_MATH_DELIM in case we have an empty left
1140 // or right delimiter.
1141 if (have_l || have_r) {
1143 docstring const selection = grabAndEraseSelection(cur);
1146 cur.insert(MathAtom(new InsetMathBig(lname,
1148 // first insert the right delimiter and then go back
1149 // and re-insert the selection (bug 7088)
1151 cur.insert(MathAtom(new InsetMathBig(rname,
1155 cur.niceInsert(selection);
1157 // Don't call cur.undispatched() if we did nothing, this would
1158 // lead to infinite recursion via Text::dispatch().
1162 case LFUN_SPACE_INSERT: {
1163 cur.recordUndoSelection();
1164 string const name = cmd.getArg(0);
1165 if (name == "normal")
1166 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1167 else if (name == "protected")
1168 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1169 else if (name == "thin" || name == "med" || name == "thick")
1170 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1171 else if (name == "hfill*")
1172 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1173 else if (name == "quad" || name == "qquad" ||
1174 name == "enspace" || name == "enskip" ||
1175 name == "negthinspace" || name == "negmedspace" ||
1176 name == "negthickspace" || name == "hfill")
1177 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1178 else if (name == "hspace" || name == "hspace*") {
1179 string const len = cmd.getArg(1);
1180 if (len.empty() || !isValidLength(len)) {
1181 lyxerr << "LyX function 'space-insert " << name << "' "
1182 "needs a valid length argument." << endl;
1185 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1187 cur.insert(MathAtom(new InsetMathSpace));
1191 case LFUN_MATH_SPACE:
1192 cur.recordUndoSelection();
1193 if (cmd.argument().empty())
1194 cur.insert(MathAtom(new InsetMathSpace));
1196 string const name = cmd.getArg(0);
1197 string const len = cmd.getArg(1);
1198 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1202 case LFUN_ERT_INSERT:
1203 // interpret this as if a backslash was typed
1205 interpretChar(cur, '\\');
1208 case LFUN_MATH_SUBSCRIPT:
1209 // interpret this as if a _ was typed
1210 cur.recordUndoSelection();
1211 interpretChar(cur, '_');
1214 case LFUN_MATH_SUPERSCRIPT:
1215 // interpret this as if a ^ was typed
1216 cur.recordUndoSelection();
1217 interpretChar(cur, '^');
1220 case LFUN_MATH_MACRO_FOLD:
1221 case LFUN_MATH_MACRO_UNFOLD: {
1223 bool fold = act == LFUN_MATH_MACRO_FOLD;
1224 bool found = findMacroToFoldUnfold(it, fold);
1226 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1227 cur.recordUndoInset();
1236 case LFUN_QUOTE_INSERT:
1237 // interpret this as if a straight " was typed
1238 cur.recordUndoSelection();
1239 interpretChar(cur, '\"');
1242 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1243 // handling such that "self-insert" works on "arbitrary stuff" too, and
1244 // math-insert only handles special math things like "matrix".
1245 case LFUN_MATH_INSERT: {
1246 cur.recordUndoSelection();
1247 if (cmd.argument() == "^" || cmd.argument() == "_")
1248 interpretChar(cur, cmd.argument()[0]);
1249 else if (!cur.selection())
1250 cur.niceInsert(cmd.argument());
1252 MathData ar(cur.buffer());
1253 asArray(cmd.argument(), ar);
1255 && ar[0]->asNestInset()
1256 && ar[0]->asNestInset()->nargs() > 1)
1257 handleNest(cur, ar[0]);
1259 cur.niceInsert(cmd.argument());
1264 case LFUN_DIALOG_SHOW_NEW_INSET: {
1265 docstring const & name = cmd.argument();
1267 if (name == "ref") {
1268 InsetMathRef tmp(buffer_, name);
1269 data = tmp.createDialogStr();
1270 cur.bv().showDialog(to_utf8(name), data);
1271 } else if (name == "mathspace") {
1272 cur.bv().showDialog(to_utf8(name));
1277 case LFUN_INSET_INSERT: {
1279 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1280 cur.recordUndoSelection();
1282 cur.forceBufferUpdate();
1287 case LFUN_INSET_DISSOLVE: {
1288 bool const enabled = cur.inMathed()
1289 && (&cur.inset() != this || cur[cur.depth() - 1].inset().inMathed());
1291 cur.recordUndoInset();
1292 // FIXME: this loses data
1297 case LFUN_MATH_LIMITS: {
1299 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1300 in = &cur.nextMath();
1301 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1302 in = &cur.prevMath();
1303 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1304 in = cur.cell().back().nucleus();
1305 // only when nucleus allows this
1308 cur.recordUndoInset();
1309 if (!cmd.argument().empty()) {
1310 if (cmd.argument() == "limits")
1312 else if (cmd.argument() == "nolimits")
1313 in->limits(NO_LIMITS);
1315 in->limits(AUTO_LIMITS);
1316 } else if (in->limits() != AUTO_LIMITS)
1317 in->limits(AUTO_LIMITS);
1318 else if (in->defaultLimits(cur.cell().displayStyle()) == LIMITS)
1319 in->limits(NO_LIMITS);
1325 case LFUN_PHANTOM_INSERT: {
1326 docstring const & arg = cmd.argument();
1328 if (arg == "Phantom")
1329 newarg = from_ascii("\\phantom");
1330 else if (arg == "HPhantom")
1331 newarg = from_ascii("\\hphantom");
1332 else if (arg == "VPhantom")
1333 newarg = from_ascii("\\vphantom");
1335 LYXERR0("Unknown phantom type " + newarg);
1337 FuncRequest const newfunc(LFUN_MATH_INSERT, newarg);
1338 lyx::dispatch(newfunc);
1344 InsetMath::doDispatch(cur, cmd);
1350 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1351 // look for macro to open/close, but stay in mathed
1352 for (; !it.empty(); it.pop_back()) {
1354 // go backward through the current cell
1355 Inset * inset = it.nextInset();
1356 while (inset && inset->asInsetMath()) {
1357 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1359 // found the an macro to open/close?
1360 if (macro->folded() != fold)
1363 // Wrong folding state.
1364 // If this was the first we see in this slice, look further left,
1366 if (inset != it.nextInset())
1370 // go up if this was the left most position
1376 inset = it.nextInset();
1384 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1385 FuncStatus & flag) const
1387 // the font related toggles
1388 //string tc = "mathnormal";
1390 string const arg = to_utf8(cmd.argument());
1391 switch (cmd.action()) {
1393 case LFUN_INSET_MODIFY:
1394 // FIXME: check temporarily disabled
1396 char align = mathcursor::valign();
1397 if (align == '\0') {
1401 if (cmd.argument().empty()) {
1405 if (!contains("tcb", cmd.argument()[0])) {
1409 flag.setOnOff(cmd.argument()[0] == align);
1412 /// We have to handle them since 1.4 blocks all unhandled actions
1413 case LFUN_FONT_ITAL:
1414 case LFUN_FONT_BOLD:
1415 case LFUN_FONT_BOLDSYMBOL:
1416 case LFUN_FONT_SANS:
1417 case LFUN_FONT_EMPH:
1418 case LFUN_FONT_TYPEWRITER:
1419 case LFUN_FONT_NOUN:
1420 case LFUN_FONT_ROMAN:
1421 case LFUN_FONT_DEFAULT:
1422 flag.setEnabled(true);
1425 // we just need to be in math mode to enable that
1426 case LFUN_MATH_SIZE:
1427 case LFUN_MATH_SPACE:
1428 case LFUN_MATH_EXTERN:
1429 flag.setEnabled(true);
1432 case LFUN_FONT_UNDERLINE:
1433 case LFUN_FONT_FRAK:
1434 flag.setEnabled(currentMode() != TEXT_MODE);
1437 case LFUN_MATH_FONT_STYLE: {
1438 bool const textarg =
1439 arg == "textbf" || arg == "textsf" ||
1440 arg == "textrm" || arg == "textmd" ||
1441 arg == "textit" || arg == "textsc" ||
1442 arg == "textsl" || arg == "textup" ||
1443 arg == "texttt" || arg == "textbb" ||
1444 arg == "textnormal";
1445 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1449 case LFUN_MATH_MODE:
1450 // forbid "math-mode on" in math mode to prevent irritating
1451 // behaviour of menu entries (bug 6709)
1452 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1455 case LFUN_MATH_INSERT:
1456 flag.setEnabled(currentMode() != TEXT_MODE);
1459 case LFUN_MATH_AMS_MATRIX:
1460 case LFUN_MATH_MATRIX:
1461 flag.setEnabled(currentMode() == MATH_MODE);
1464 case LFUN_INSET_INSERT: {
1465 // Don't test createMathInset_fromDialogStr(), since
1466 // getStatus is not called with a valid reference and the
1467 // dialog would not be applicable.
1468 string const name = cmd.getArg(0);
1469 flag.setEnabled(name == "ref" || name == "mathspace");
1473 case LFUN_DIALOG_SHOW_NEW_INSET: {
1474 docstring const & name = cmd.argument();
1475 flag.setEnabled(name == "ref" || name == "mathspace");
1480 case LFUN_MATH_DELIM:
1481 case LFUN_MATH_BIGDELIM:
1482 // Don't do this with multi-cell selections
1483 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1486 case LFUN_MATH_MACRO_FOLD:
1487 case LFUN_MATH_MACRO_UNFOLD: {
1489 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1490 flag.setEnabled(found);
1494 case LFUN_SPECIALCHAR_INSERT:
1495 case LFUN_SCRIPT_INSERT:
1496 // FIXME: These would probably make sense in math-text mode
1497 flag.setEnabled(false);
1500 // these are nonfunctional in math
1501 case LFUN_BOX_INSERT:
1502 case LFUN_BRANCH_INSERT:
1503 case LFUN_BRANCH_ADD_INSERT:
1504 case LFUN_CAPTION_INSERT:
1505 case LFUN_FLEX_INSERT:
1506 case LFUN_FLOAT_INSERT:
1507 case LFUN_FLOAT_LIST_INSERT:
1508 case LFUN_FOOTNOTE_INSERT:
1509 case LFUN_HREF_INSERT:
1510 case LFUN_INDEX_INSERT:
1511 case LFUN_INDEX_PRINT:
1512 case LFUN_INFO_INSERT:
1513 case LFUN_IPA_INSERT:
1514 case LFUN_LISTING_INSERT:
1515 case LFUN_MARGINALNOTE_INSERT:
1516 case LFUN_NEWPAGE_INSERT:
1517 case LFUN_NOMENCL_INSERT:
1518 case LFUN_NOMENCL_PRINT:
1519 case LFUN_NOTE_INSERT:
1520 case LFUN_PREVIEW_INSERT:
1521 case LFUN_TABULAR_INSERT:
1522 case LFUN_WRAP_INSERT:
1523 flag.setEnabled(false);
1526 case LFUN_SPACE_INSERT: {
1527 docstring const & name = cmd.argument();
1528 if (name == "visible")
1529 flag.setEnabled(false);
1533 case LFUN_INSET_DISSOLVE: {
1534 // Do not dissolve a math inset which is in text
1535 bool const enabled = cur.inMathed()
1536 && (&cur.inset() != this || cur[cur.depth() - 1].inset().inMathed());
1537 flag.setEnabled(enabled);
1541 docstring const & name = cmd.argument();
1542 if (name == "html" || name == "latex")
1543 flag.setEnabled(false);
1547 case LFUN_MATH_LIMITS: {
1549 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1550 in = &cur.nextMath();
1551 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1552 in = &cur.prevMath();
1553 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1554 in = cur.cell().back().nucleus();
1556 if (!cmd.argument().empty()) {
1557 if (cmd.argument() == "limits")
1558 flag.setOnOff(in->limits() == LIMITS);
1559 else if (cmd.argument() == "nolimits")
1560 flag.setOnOff(in->limits() == NO_LIMITS);
1562 flag.setOnOff(in->limits() == AUTO_LIMITS);
1564 flag.setEnabled(true);
1566 flag.setEnabled(false);
1578 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1581 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1582 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1583 enter_front ? idxFirst(cur) : idxLast(cur);
1585 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1589 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1592 int dist_min = 1000000;
1593 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1594 int const d = cell(i).dist(cur.bv(), x, y);
1603 MathData & ar = cell(idx_min);
1605 cur.idx() = idx_min;
1606 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1608 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1609 if (dist_min == 0) {
1611 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1612 if (ar[i]->covers(cur.bv(), x, y))
1613 return ar[i].nucleus()->editXY(cur, x, y);
1619 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1621 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1622 BufferView & bv = cur.bv();
1623 if (cmd.button() == mouse_button::button3) {
1624 // Don't do anything if we right-click a
1625 // selection, a context menu will popup.
1626 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1627 && cur < bv.cursor().selectionEnd()) {
1628 cur.noScreenUpdate();
1633 // set cursor after the inset if x is nearer to that position (bug 9748)
1634 cur.moveToClosestEdge(cmd.x(), true);
1636 bool do_selection = cmd.button() == mouse_button::button1
1637 && cmd.modifier() == ShiftModifier;
1638 bv.mouseSetCursor(cur, do_selection);
1639 if (cmd.button() == mouse_button::button1) {
1640 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1641 // Update the cursor update flags as needed:
1643 // Update::Decoration: tells to update the decoration
1644 // (visual box corners that define
1646 // Update::FitCursor: adjust the screen to the cursor
1647 // position if needed
1648 // cur.result().update(): don't overwrite previously set flags.
1649 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1650 | cur.result().screenUpdate());
1651 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1652 if (cap::selection()) {
1653 // See comment in Text::dispatch why we do this
1654 cap::copySelectionToStack();
1655 cmd = FuncRequest(LFUN_PASTE, "0");
1656 doDispatch(bv.cursor(), cmd);
1659 asArray(theSelection().get(), ar);
1660 bv.cursor().insert(ar);
1666 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1668 // only select with button 1
1669 if (cmd.button() != mouse_button::button1)
1672 Cursor & bvcur = cur.bv().cursor();
1674 // ignore motions deeper nested than the real anchor
1675 if (!bvcur.realAnchor().hasPart(cur)) {
1680 // set cursor after the inset if x is nearer to that position (bug 9748)
1681 cur.moveToClosestEdge(cmd.x());
1683 CursorSlice old = bvcur.top();
1685 // We continue with our existing selection or start a new one, so don't
1686 // reset the anchor.
1687 bvcur.setCursor(cur);
1688 // Did we actually move?
1689 if (cur.top() == old)
1690 // We didn't move one iota, so no need to change selection status
1691 // or update the screen.
1692 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1694 bvcur.setSelection();
1698 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1700 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1702 if (cmd.button() == mouse_button::button1) {
1703 if (!cur.selection())
1704 cur.noScreenUpdate();
1706 Cursor & bvcur = cur.bv().cursor();
1707 bvcur.selection(true);
1716 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1718 // try auto-correction
1719 if (lyxrc.autocorrection_math && cur.pos() != 0 && !cur.selection()
1720 && math_autocorrect(cur, c))
1723 //lyxerr << "interpret 2: '" << c << "'" << endl;
1724 docstring save_selection;
1725 if (c == '^' || c == '_')
1726 save_selection = grabAndEraseSelection(cur);
1729 Buffer * buf = cur.buffer();
1732 if (cur.inMacroMode()) {
1733 docstring name = cur.macroName();
1735 /// are we currently typing '#1' or '#2' or...?
1736 if (name == "\\#") {
1739 if (n >= 1 && n <= 9)
1740 cur.insert(new InsetMathMacroArgument(n));
1744 // do not finish macro for known * commands
1745 bool star_macro = c == '*'
1746 && (in_word_set(name.substr(1) + '*')
1747 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1748 if (isAlphaASCII(c) || star_macro) {
1749 cur.activeMacro()->setName(name + docstring(1, c));
1753 // handle 'special char' macros
1758 if (currentMode() != InsetMath::MATH_MODE)
1759 cur.niceInsert(createInsetMath("textbackslash", buf));
1761 cur.niceInsert(createInsetMath("backslash", buf));
1762 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1764 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1765 } else if (c == '{' || c == '%') {
1766 //using the saved selection as argument
1767 InsetMathUnknown * p = cur.activeMacro();
1769 MathData sel(cur.buffer());
1770 asArray(p->selection(), sel);
1773 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1775 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1776 } else if (c == '#') {
1777 LASSERT(cur.activeMacro(), return false);
1778 cur.activeMacro()->setName(name + docstring(1, c));
1781 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1786 // One character big delimiters. The others are handled in
1787 // interpretString().
1788 latexkeys const * l = in_word_set(name.substr(1));
1789 if (name[0] == '\\' && l && l->inset == "big") {
1793 delim = from_ascii("\\{");
1796 delim = from_ascii("\\}");
1799 delim = docstring(1, c);
1802 if (InsetMathBig::isBigInsetDelim(delim)) {
1803 // name + delim ared a valid InsetMathBig.
1804 // We can't use cur.macroModeClose() because
1805 // it does not handle delim.
1806 InsetMathUnknown * p = cur.activeMacro();
1809 cur.cell().erase(cur.pos());
1810 cur.plainInsert(MathAtom(
1811 new InsetMathBig(name.substr(1), delim)));
1814 } else if (name == "\\smash" && c == '[') {
1815 // We can't use cur.macroModeClose() because
1816 // it would create an InsetMathPhantom
1817 InsetMathUnknown * p = cur.activeMacro();
1819 interpretChar(cur, c);
1823 // leave macro mode and try again if necessary
1824 if (cur.macroModeClose()) {
1825 MathAtom const atom = cur.prevAtom();
1826 if (atom->asNestInset() && atom->isActive()) {
1828 cur.nextInset()->edit(cur, true);
1832 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1834 interpretChar(cur, c);
1839 // just clear selection on pressing the space bar
1840 if (cur.selection() && c == ' ') {
1841 cur.selection(false);
1846 //lyxerr << "starting with macro" << endl;
1847 bool reduced = cap::reduceSelectionToOneCell(cur);
1848 if (reduced || !cur.selection()) {
1849 InsetMath const * im = cur.inset().asInsetMath();
1850 InsetMathMacro const * macro = im ? im->asMacro()
1852 bool in_macro_name = macro
1853 && macro->displayMode() ==
1854 InsetMathMacro::DISPLAY_UNFOLDED;
1855 cur.recordUndoInset();
1856 docstring const safe = cap::grabAndEraseSelection(cur);
1857 if (!cur.inRegexped() && !in_macro_name)
1858 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1860 cur.niceInsert(createInsetMath("backslash", buf));
1868 if (currentMode() != InsetMath::MATH_MODE)
1874 if (currentMode() != InsetMath::MATH_MODE) {
1875 // insert spaces in text or undecided mode,
1876 // but suppress direct insertion of two spaces in a row
1877 // the still allows typing '<space>a<space>' and deleting the 'a', but
1878 // it is better than nothing...
1879 pos_type const pos = cur.pos();
1880 pos_type const lastpos = cur.lastpos();
1881 if ((pos == 0 && lastpos == 0)
1882 || (pos == 0 && cur.nextAtom()->getChar() != ' ')
1883 || (pos == lastpos && cur.prevAtom()->getChar() != ' ')
1884 || (pos > 0 && cur.prevAtom()->getChar() != ' '
1885 && cur.nextAtom()->getChar() != ' ')) {
1887 // FIXME: we have to enable full redraw here because of the
1888 // visual box corners that define the inset. If we know for
1889 // sure that we stay within the same cell we can optimize for
1891 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1895 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1896 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1897 // FIXME: we have to enable full redraw here because of the
1898 // visual box corners that define the inset. If we know for
1899 // sure that we stay within the same cell we can optimize for
1901 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1905 if (cur.popForward()) {
1906 // FIXME: we have to enable full redraw here because of the
1907 // visual box corners that define the inset. If we know for
1908 // sure that we stay within the same cell we can optimize for
1910 //cur.screenUpdateFlags(Update::FitCursor);
1914 // if we are at the very end, leave the formula
1915 return cur.pos() != cur.lastpos();
1918 // These should be treated differently when not in text mode:
1919 if (cur.inRegexped()) {
1922 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1929 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1932 cur.niceInsert(createInsetMath("sim", buf));
1938 } else if (currentMode() != InsetMath::TEXT_MODE) {
1940 cur.recordUndoInset();
1941 script(cur, false, save_selection);
1945 cur.recordUndoInset();
1946 script(cur, true, save_selection);
1950 cur.niceInsert(createInsetMath("sim", buf));
1953 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1954 MathAtom const atom(new InsetMathChar(c));
1955 if (cur.prevInset() && cur.prevInset()->asInsetMath()->name() == "text") {
1956 // reuse existing \text inset
1957 cur.prevInset()->asInsetMath()->cell(0).push_back(atom);
1959 MathAtom at = createInsetMath("text", buf);
1960 at.nucleus()->cell(0).push_back(atom);
1968 cur.niceInsert(createInsetMath("textasciicircum", buf));
1972 cur.niceInsert(createInsetMath("textasciitilde", buf));
1977 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1978 c == '%' || c == '_') {
1979 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1983 // no special circumstances, so insert the character without any fuss
1989 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1991 if (str == "\\limits" || str == "\\nolimits") {
1992 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1993 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1996 cur.message(bformat(_("Cannot apply %1$s here."), str));
2000 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
2002 if (!cur.empty() && cur.pos() > 0 &&
2003 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
2004 if (InsetMathBig::isBigInsetDelim(str)) {
2005 docstring prev = asString(cur.cell()[cur.pos() - 1]);
2006 if (prev[0] == '\\') {
2007 prev = prev.substr(1);
2008 latexkeys const * l = in_word_set(prev);
2009 if (l && l->inset == "big") {
2010 cur.recordUndoSelection();
2011 cur.cell()[cur.pos() - 1] =
2012 MathAtom(new InsetMathBig(prev, str));
2022 bool InsetMathNest::script(Cursor & cur, bool up)
2024 return script(cur, up, docstring());
2028 bool InsetMathNest::script(Cursor & cur, bool up,
2029 docstring const & save_selection)
2031 // Hack to get \^ and \_ working
2032 //lyxerr << "handling script: up: " << up << endl;
2033 if (cur.inMacroMode() && cur.macroName() == "\\") {
2035 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
2037 interpretChar(cur, '_');
2041 cur.macroModeClose();
2042 if (asScriptInset() && cur.idx() == 0) {
2043 // we are in a nucleus of a script inset, move to _our_ script
2044 InsetMathScript * inset = asScriptInset();
2045 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
2047 cur.idx() = inset->idxOfScript(up);
2049 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
2051 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2054 cur.idx() = inset->idxOfScript(up);
2055 cur.pos() = cur.lastpos();
2057 // convert the thing to our left to a scriptinset or create a new
2058 // one if in the very first position of the array
2059 if (cur.pos() == 0) {
2060 //lyxerr << "new scriptinset" << endl;
2061 cur.insert(new InsetMathScript(buffer_, up));
2063 //lyxerr << "converting prev atom " << endl;
2064 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
2067 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2068 // See comment in MathParser.cpp for special handling of {}-bases
2074 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
2075 cur.niceInsert(save_selection);
2077 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2082 bool InsetMathNest::completionSupported(Cursor const & cur) const
2084 return cur.inMacroMode();
2088 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2090 return cur.inMacroMode();
2094 bool InsetMathNest::automaticInlineCompletion() const
2096 return lyxrc.completion_inline_math;
2100 bool InsetMathNest::automaticPopupCompletion() const
2102 return lyxrc.completion_popup_math;
2106 CompletionList const *
2107 InsetMathNest::createCompletionList(Cursor const & cur) const
2109 if (!cur.inMacroMode())
2112 return new MathCompletionList(cur);
2116 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2118 if (!cur.inMacroMode())
2121 return cur.activeMacro()->name();
2125 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s, bool finished)
2127 if (cur.buffer()->isReadonly() || !cur.inMacroMode())
2130 // Contrary to Text, the whole inset should be recorded (#12581).
2131 cur.recordUndoInset();
2133 // append completion to active macro
2134 InsetMathUnknown * inset = cur.activeMacro();
2135 inset->setName(inset->name() + s);
2140 // FIXME: this creates duplicates in the completion popup
2141 // which looks ugly. Moreover the changes the list lengths
2142 // which seems to confuse the popup as well.
2143 MathCompletionList::addToFavorites(inset->name());
2145 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2152 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2153 Dimension & dim) const
2155 Inset const * inset = cur.activeMacro();
2159 // get inset dimensions
2160 dim = cur.bv().coordCache().insets().dim(inset);
2161 // FIXME: these 3 are no accurate, but should depend on the font.
2162 // Now the popup jumps down if you enter a char with descent > 0.
2167 Point xy = cur.bv().coordCache().insets().xy(inset);
2173 ////////////////////////////////////////////////////////////////////
2175 MathCompletionList::MathCompletionList(Cursor const & cur)
2177 // fill it with macros from the buffer
2178 MacroNameSet macros;
2179 cur.buffer()->listMacroNames(macros);
2180 MacroNameSet::const_iterator it;
2181 for (it = macros.begin(); it != macros.end(); ++it) {
2182 if (cur.buffer()->getMacro(*it, cur, false))
2183 locals.push_back("\\" + *it);
2185 sort(locals.begin(), locals.end());
2187 if (!globals.empty())
2190 // fill in global macros
2192 MacroTable::globalMacros().getMacroNames(macros, false);
2193 //lyxerr << "Globals completion macros: ";
2194 for (it = macros.begin(); it != macros.end(); ++it) {
2195 //lyxerr << "\\" + *it << " ";
2196 globals.push_back("\\" + *it);
2198 //lyxerr << std::endl;
2200 // fill in global commands
2201 globals.push_back(from_ascii("\\boxed"));
2202 globals.push_back(from_ascii("\\fbox"));
2203 globals.push_back(from_ascii("\\framebox"));
2204 globals.push_back(from_ascii("\\makebox"));
2205 globals.push_back(from_ascii("\\kern"));
2206 globals.push_back(from_ascii("\\xhookrightarrow"));
2207 globals.push_back(from_ascii("\\xhookleftarrow"));
2208 globals.push_back(from_ascii("\\xrightarrow"));
2209 globals.push_back(from_ascii("\\xRightarrow"));
2210 globals.push_back(from_ascii("\\xrightharpoondown"));
2211 globals.push_back(from_ascii("\\xrightharpoonup"));
2212 globals.push_back(from_ascii("\\xrightleftharpoons"));
2213 globals.push_back(from_ascii("\\xleftarrow"));
2214 globals.push_back(from_ascii("\\xLeftarrow"));
2215 globals.push_back(from_ascii("\\xleftharpoondown"));
2216 globals.push_back(from_ascii("\\xleftharpoonup"));
2217 globals.push_back(from_ascii("\\xleftrightarrow"));
2218 globals.push_back(from_ascii("\\xLeftrightarrow"));
2219 globals.push_back(from_ascii("\\xleftrightharpoons"));
2220 globals.push_back(from_ascii("\\xmapsto"));
2221 globals.push_back(from_ascii("\\split"));
2222 globals.push_back(from_ascii("\\gathered"));
2223 globals.push_back(from_ascii("\\aligned"));
2224 globals.push_back(from_ascii("\\alignedat"));
2225 globals.push_back(from_ascii("\\cases"));
2226 globals.push_back(from_ascii("\\substack"));
2227 globals.push_back(from_ascii("\\xymatrix"));
2228 globals.push_back(from_ascii("\\Diagram"));
2229 globals.push_back(from_ascii("\\subarray"));
2230 globals.push_back(from_ascii("\\array"));
2231 globals.push_back(from_ascii("\\sqrt"));
2232 globals.push_back(from_ascii("\\root"));
2233 globals.push_back(from_ascii("\\tabular"));
2234 globals.push_back(from_ascii("\\sideset"));
2235 globals.push_back(from_ascii("\\stackrel"));
2236 globals.push_back(from_ascii("\\stackrelthree"));
2237 globals.push_back(from_ascii("\\binom"));
2238 globals.push_back(from_ascii("\\choose"));
2239 globals.push_back(from_ascii("\\brace"));
2240 globals.push_back(from_ascii("\\brack"));
2241 globals.push_back(from_ascii("\\frac"));
2242 globals.push_back(from_ascii("\\over"));
2243 globals.push_back(from_ascii("\\nicefrac"));
2244 globals.push_back(from_ascii("\\unitfrac"));
2245 globals.push_back(from_ascii("\\unitfracthree"));
2246 globals.push_back(from_ascii("\\unitone"));
2247 globals.push_back(from_ascii("\\unittwo"));
2248 globals.push_back(from_ascii("\\infer"));
2249 globals.push_back(from_ascii("\\atop"));
2250 globals.push_back(from_ascii("\\lefteqn"));
2251 globals.push_back(from_ascii("\\boldsymbol"));
2252 globals.push_back(from_ascii("\\bm"));
2253 globals.push_back(from_ascii("\\color"));
2254 globals.push_back(from_ascii("\\normalcolor"));
2255 globals.push_back(from_ascii("\\textcolor"));
2256 globals.push_back(from_ascii("\\cfrac"));
2257 globals.push_back(from_ascii("\\cfracleft"));
2258 globals.push_back(from_ascii("\\cfracright"));
2259 globals.push_back(from_ascii("\\dfrac"));
2260 globals.push_back(from_ascii("\\tfrac"));
2261 globals.push_back(from_ascii("\\dbinom"));
2262 globals.push_back(from_ascii("\\tbinom"));
2263 globals.push_back(from_ascii("\\hphantom"));
2264 globals.push_back(from_ascii("\\phantom"));
2265 globals.push_back(from_ascii("\\vphantom"));
2266 globals.push_back(from_ascii("\\cancel"));
2267 globals.push_back(from_ascii("\\bcancel"));
2268 globals.push_back(from_ascii("\\xcancel"));
2269 globals.push_back(from_ascii("\\cancelto"));
2270 globals.push_back(from_ascii("\\smash"));
2271 globals.push_back(from_ascii("\\mathclap"));
2272 globals.push_back(from_ascii("\\mathllap"));
2273 globals.push_back(from_ascii("\\mathrlap"));
2274 globals.push_back(from_ascii("\\ensuremath"));
2275 MathWordList const & words = mathedWordList();
2276 MathWordList::const_iterator it2;
2277 //lyxerr << "Globals completion commands: ";
2278 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2279 if (it2->second.inset != "macro" && !it2->second.hidden) {
2280 // macros are already read from MacroTable::globalMacros()
2281 globals.push_back('\\' + it2->first);
2282 //lyxerr << '\\' + it2->first << ' ';
2285 //lyxerr << std::endl;
2286 sort(globals.begin(), globals.end());
2290 MathCompletionList::~MathCompletionList()
2295 size_type MathCompletionList::size() const
2297 return locals.size() + globals.size();
2301 docstring const & MathCompletionList::data(size_t idx) const
2303 size_t lsize = locals.size();
2305 return globals[idx - lsize];
2311 std::string MathCompletionList::icon(size_t idx) const
2313 // get the latex command
2315 size_t lsize = locals.size();
2317 cmd = globals[idx - lsize];
2321 // get the icon name by stripping the backslash
2322 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2323 if (icon_name.empty())
2324 return std::string();
2325 return "math/" + to_utf8(icon_name);
2328 std::vector<docstring> MathCompletionList::globals;