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 wi(os, runparams.moving_arg, true,
362 runparams.dryrun ? TeXMathStream::wsDryrun : TeXMathStream::wsDefault,
364 wi.strikeoutMath(runparams.inDeletedInset);
365 if (runparams.inulemcmd) {
366 wi.ulemCmd(TeXMathStream::UNDERLINE);
367 if (runparams.local_font) {
368 FontInfo f = runparams.local_font->fontInfo();
369 if (f.strikeout() == FONT_ON)
370 wi.ulemCmd(TeXMathStream::STRIKEOUT);
373 wi.canBreakLine(os.canBreakLine());
374 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
377 // Reset parbreak and command termination status after a math inset.
379 os.canBreakLine(wi.canBreakLine());
380 os.terminateCommand(false);
384 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
387 mouse_hover_[bv] = mouse_hover;
392 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
396 MathData & ar = cur.cell();
397 // remove base-only "scripts"
398 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
399 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
400 if (p && p->nargs() == 1) {
401 MathData ar = p->nuc();
404 cur.adjust(i, ar.size() - 1);
408 // glue adjacent font insets of the same kind
409 for (pos_type i = 0; i + 1 < size(); ++i) {
410 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
411 InsetMathFont const * q = operator[](i + 1)->asFontInset();
412 if (p && q && p->name() == q->name()) {
413 p->cell(0).append(q->cell(0));
423 void InsetMathNest::handleFont
424 (Cursor & cur, docstring const & arg, char const * const font)
426 handleFont(cur, arg, from_ascii(font));
430 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
431 docstring const & font)
433 cur.recordUndoSelection();
435 // this whole function is a hack and won't work for incremental font
437 if (cur.inset().asInsetMath()->name() == font)
438 cur.handleFont(to_utf8(font));
440 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
444 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
446 handleNest(cur, nest, docstring());
450 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
451 docstring const & arg)
453 DocIterator const i1 = cur.selectionBegin();
454 DocIterator const i2 = cur.selectionEnd();
455 if (!i1.inset().asInsetMath())
457 if (i1.idx() == i2.idx()) {
458 // the easy case where only one cell is selected
459 cur.handleNest(nest);
464 // multiple selected cells in a simple non-grid inset
465 if (i1.inset().nrows() == 0 || i1.inset().ncols() == 0) {
466 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
472 cur.pos() = cur.lastpos();
476 cur.handleNest(nest);
482 // the complicated case with multiple selected cells in a grid
485 cap::region(i1.top(), i2.top(), r1, r2, c1, c2);
486 for (row_type row = r1; row <= r2; ++row) {
487 for (col_type col = c1; col <= c2; ++col) {
490 cur.idx() = i1.inset().index(row, col);
493 cur.pos() = cur.lastpos();
497 cur.handleNest(nest);
504 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
506 cur.recordUndoSelection();
509 font.fromString(to_utf8(arg), b);
510 if (font.fontInfo().color() != Color_inherit &&
511 font.fontInfo().color() != Color_ignore)
512 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
514 // FIXME: support other font changes here as well?
517 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
519 //LYXERR0("InsetMathNest: request: " << cmd);
521 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
523 FuncCode const act = cmd.action();
526 case LFUN_CLIPBOARD_PASTE:
527 parseflg |= Parse::VERBATIM;
530 if (cur.currentMode() != MATH_MODE)
531 parseflg |= Parse::TEXTMODE;
532 cur.recordUndoSelection();
533 cur.message(_("Paste"));
534 replaceSelection(cur);
536 if (cmd.argument().empty() && !theClipboard().isInternal())
537 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
540 idocstringstream is(cmd.argument());
542 topaste = cap::selection(n, buffer().params().documentClassPtr());
544 cur.niceInsert(topaste, parseflg, false);
545 cur.clearSelection(); // bug 393
546 cur.forceBufferUpdate();
553 cutSelection(cur, true);
554 cur.message(_("Cut"));
555 // Prevent stale position >= size crash
556 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
558 cur.forceBufferUpdate();
563 cur.message(_("Copy"));
566 case LFUN_MOUSE_PRESS:
567 lfunMousePress(cur, cmd);
570 case LFUN_MOUSE_MOTION:
571 lfunMouseMotion(cur, cmd);
574 case LFUN_MOUSE_RELEASE:
575 lfunMouseRelease(cur, cmd);
578 case LFUN_FINISHED_LEFT: // in math, left is backwards
579 case LFUN_FINISHED_BACKWARD:
580 cur.bv().cursor() = cur;
583 case LFUN_FINISHED_RIGHT: // in math, right is forward
584 case LFUN_FINISHED_FORWARD:
586 cur.bv().cursor() = cur;
589 case LFUN_WORD_RIGHT:
591 case LFUN_WORD_BACKWARD:
592 case LFUN_WORD_FORWARD:
593 case LFUN_CHAR_RIGHT:
595 case LFUN_CHAR_BACKWARD:
596 case LFUN_CHAR_FORWARD:
597 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
599 case LFUN_WORD_RIGHT_SELECT:
600 case LFUN_WORD_LEFT_SELECT:
601 case LFUN_WORD_BACKWARD_SELECT:
602 case LFUN_WORD_FORWARD_SELECT:
603 case LFUN_CHAR_RIGHT_SELECT:
604 case LFUN_CHAR_LEFT_SELECT:
605 case LFUN_CHAR_BACKWARD_SELECT:
606 case LFUN_CHAR_FORWARD_SELECT: {
607 // are we in a selection?
608 bool select = (act == LFUN_WORD_RIGHT_SELECT
609 || act == LFUN_WORD_LEFT_SELECT
610 || act == LFUN_WORD_BACKWARD_SELECT
611 || act == LFUN_WORD_FORWARD_SELECT
612 || act == LFUN_CHAR_RIGHT_SELECT
613 || act == LFUN_CHAR_LEFT_SELECT
614 || act == LFUN_CHAR_BACKWARD_SELECT
615 || act == LFUN_CHAR_FORWARD_SELECT);
617 bool word = (act == LFUN_WORD_RIGHT_SELECT
618 || act == LFUN_WORD_LEFT_SELECT
619 || act == LFUN_WORD_BACKWARD_SELECT
620 || act == LFUN_WORD_FORWARD_SELECT
621 || act == LFUN_WORD_RIGHT
622 || act == LFUN_WORD_LEFT
623 || act == LFUN_WORD_BACKWARD
624 || act == LFUN_WORD_FORWARD);
625 // are we moving forward or backwards?
626 // If the command was RIGHT or LEFT, then whether we're moving forward
627 // or backwards depends on the cursor movement mode (logical or visual):
628 // * in visual mode, since math is always LTR, right -> forward,
630 // * in logical mode, the mapping is determined by the
631 // reverseDirectionNeeded() function
634 FuncCode finish_lfun;
636 if (act == LFUN_CHAR_FORWARD
637 || act == LFUN_CHAR_FORWARD_SELECT
638 || act == LFUN_WORD_FORWARD
639 || act == LFUN_WORD_FORWARD_SELECT) {
641 finish_lfun = LFUN_FINISHED_FORWARD;
643 else if (act == LFUN_CHAR_BACKWARD
644 || act == LFUN_CHAR_BACKWARD_SELECT
645 || act == LFUN_WORD_BACKWARD
646 || act == LFUN_WORD_BACKWARD_SELECT) {
648 finish_lfun = LFUN_FINISHED_BACKWARD;
651 bool right = (act == LFUN_CHAR_RIGHT_SELECT
652 || act == LFUN_CHAR_RIGHT
653 || act == LFUN_WORD_RIGHT_SELECT
654 || act == LFUN_WORD_RIGHT);
655 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
661 finish_lfun = LFUN_FINISHED_RIGHT;
663 finish_lfun = LFUN_FINISHED_LEFT;
665 // Now that we know exactly what we want to do, let's do it!
666 cur.selHandle(select);
668 cur.macroModeClose();
669 // try moving forward or backwards as necessary...
670 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
671 // ... and if movement failed, then finish forward or backwards
673 cmd = FuncRequest(finish_lfun);
681 case LFUN_PARAGRAPH_UP:
682 case LFUN_PARAGRAPH_DOWN:
683 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
685 case LFUN_DOWN_SELECT:
687 case LFUN_PARAGRAPH_UP_SELECT:
688 case LFUN_PARAGRAPH_DOWN_SELECT: {
689 // close active macro
690 if (cur.inMacroMode()) {
691 cur.macroModeClose();
695 // stop/start the selection
696 bool select = act == LFUN_DOWN_SELECT
697 || act == LFUN_UP_SELECT
698 || act == LFUN_PARAGRAPH_DOWN_SELECT
699 || act == LFUN_PARAGRAPH_UP_SELECT;
700 cur.selHandle(select);
703 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
704 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
705 bool successful = cur.upDownInMath(up);
709 if (cur.fixIfBroken())
710 // FIXME: Something bad happened. We pass the corrected Cursor
711 // instead of letting things go worse.
714 // We did not manage to move the cursor.
719 case LFUN_MOUSE_DOUBLE:
720 case LFUN_WORD_SELECT:
722 cur.bv().mouseSetCursor(cur);
723 cur.pos() = cur.lastpos();
724 cur.bv().mouseSetCursor(cur, true);
727 case LFUN_MOUSE_TRIPLE:
730 cur.bv().mouseSetCursor(cur);
731 cur.idx() = cur.lastidx();
732 cur.pos() = cur.lastpos();
733 cur.bv().mouseSetCursor(cur, true);
736 case LFUN_LINE_BEGIN:
737 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
739 case LFUN_LINE_BEGIN_SELECT:
740 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
741 act == LFUN_WORD_LEFT_SELECT ||
742 act == LFUN_LINE_BEGIN_SELECT);
743 cur.macroModeClose();
744 if (cur.pos() != 0) {
746 } else if (cur.col() != 0) {
747 cur.idx() -= cur.col();
749 } else if (cur.idx() != 0) {
753 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
759 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
761 case LFUN_LINE_END_SELECT:
762 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
763 act == LFUN_WORD_RIGHT_SELECT ||
764 act == LFUN_LINE_END_SELECT);
765 cur.macroModeClose();
767 if (cur.pos() != cur.lastpos()) {
768 cur.pos() = cur.lastpos();
769 } else if (ncols() && (cur.col() != cur.lastcol())) {
770 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
771 cur.pos() = cur.lastpos();
772 } else if (cur.idx() != cur.lastidx()) {
773 cur.idx() = cur.lastidx();
774 cur.pos() = cur.lastpos();
776 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
781 case LFUN_CELL_FORWARD:
782 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
783 cur.selHandle(false);
785 cur.macroModeClose();
786 if (!cur.inset().idxNext(cur)) {
787 cur.idx() = firstIdx();
792 case LFUN_CELL_BACKWARD:
793 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
794 cur.selHandle(false);
796 cur.macroModeClose();
797 if (!cur.inset().idxPrev(cur)) {
798 cur.idx() = lastIdx();
799 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
803 case LFUN_WORD_DELETE_BACKWARD:
804 case LFUN_CHAR_DELETE_BACKWARD:
806 // May affect external cell:
807 cur.recordUndoInset();
808 else if (!cur.inMacroMode())
809 cur.recordUndoSelection();
810 // if the inset can not be removed from within, delete it
811 if (!cur.backspace(cmd.getArg(0) == "force")) {
812 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
813 cur.innerText()->dispatch(cur, newcmd);
817 case LFUN_WORD_DELETE_FORWARD:
818 case LFUN_CHAR_DELETE_FORWARD:
819 if (cur.pos() == cur.lastpos())
820 // May affect external cell:
821 cur.recordUndoInset();
823 cur.recordUndoSelection();
824 // if the inset can not be removed from within, delete it
825 if (!cur.erase(cmd.getArg(0) == "force")) {
826 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
827 cur.innerText()->dispatch(cur, newcmd);
833 cur.clearSelection();
835 if (cur.inMacroMode())
836 cur.macroModeClose(true);
838 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
844 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
845 // that is traversed by a single <CursorLeft>/<CursorRight>.
846 case LFUN_INSET_TOGGLE:
852 case LFUN_SELF_INSERT:
853 // special case first for big delimiters
854 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
857 for (char_type c : cmd.argument()) {
858 // Don't record undo steps if we are in macro mode and thus
859 // cmd.argument is the next character of the macro name.
860 // Otherwise we'll get an invalid cursor if we undo after
861 // the macro was finished and the macro is a known command,
862 // e.g. sqrt. Cursor::macroModeClose replaces in this case
863 // the InsetMathUnknown with name "frac" by an empty
864 // InsetMathFrac -> a pos value > 0 is invalid.
865 // A side effect is that an undo before the macro is finished
866 // undoes the complete macro, not only the last character.
867 // At the time we hit '\' we are not in macro mode, still.
868 if (!cur.inMacroMode())
869 cur.recordUndoSelection();
871 // special handling of space. If we insert an inset
872 // via macro mode, we want to put the cursor inside it
873 // if relevant. Think typing "\frac<space>".
875 && cur.inMacroMode() && cur.macroName() != "\\"
876 && cur.macroModeClose() && cur.pos() > 0)
877 cur.editInsertedInset();
878 else if (!interpretChar(cur, c)) {
879 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
881 // FIXME: can we avoid skipping the end of the string?
887 //case LFUN_SERVER_GET_XY:
890 case LFUN_SERVER_SET_XY: {
891 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
894 istringstream is(to_utf8(cmd.argument()));
900 // Special casing for superscript in case of LyX handling
902 case LFUN_ACCENT_CIRCUMFLEX:
903 if (cmd.argument().empty()) {
904 // do superscript if LyX handles
906 cur.recordUndoSelection();
907 script(cur, true, grabAndEraseSelection(cur));
911 case LFUN_ACCENT_UMLAUT:
912 case LFUN_ACCENT_ACUTE:
913 case LFUN_ACCENT_GRAVE:
914 case LFUN_ACCENT_BREVE:
915 case LFUN_ACCENT_DOT:
916 case LFUN_ACCENT_MACRON:
917 case LFUN_ACCENT_CARON:
918 case LFUN_ACCENT_TILDE:
919 case LFUN_ACCENT_CEDILLA:
920 case LFUN_ACCENT_CIRCLE:
921 case LFUN_ACCENT_UNDERDOT:
922 case LFUN_ACCENT_TIE:
923 case LFUN_ACCENT_OGONEK:
924 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
928 case LFUN_TEXTSTYLE_APPLY:
929 case LFUN_TEXTSTYLE_UPDATE:
930 handleFont2(cur, cmd.argument());
934 if (currentMode() != MATH_MODE)
935 handleFont(cur, cmd.argument(), "textbf");
937 handleFont(cur, cmd.argument(), "mathbf");
939 case LFUN_FONT_BOLDSYMBOL:
940 if (currentMode() != MATH_MODE)
941 handleFont(cur, cmd.argument(), "textbf");
943 handleFont(cur, cmd.argument(), "boldsymbol");
946 if (currentMode() != MATH_MODE)
947 handleFont(cur, cmd.argument(), "textsf");
949 handleFont(cur, cmd.argument(), "mathsf");
952 if (currentMode() != MATH_MODE)
953 handleFont(cur, cmd.argument(), "emph");
955 handleFont(cur, cmd.argument(), "mathcal");
957 case LFUN_FONT_ROMAN:
958 if (currentMode() != MATH_MODE)
959 handleFont(cur, cmd.argument(), "textrm");
961 handleFont(cur, cmd.argument(), "mathrm");
963 case LFUN_FONT_TYPEWRITER:
964 if (currentMode() != MATH_MODE)
965 handleFont(cur, cmd.argument(), "texttt");
967 handleFont(cur, cmd.argument(), "mathtt");
970 handleFont(cur, cmd.argument(), "mathfrak");
973 if (currentMode() != MATH_MODE)
974 handleFont(cur, cmd.argument(), "textit");
976 handleFont(cur, cmd.argument(), "mathit");
979 if (currentMode() != MATH_MODE)
980 // FIXME: should be "noun"
981 handleFont(cur, cmd.argument(), "textsc");
983 handleFont(cur, cmd.argument(), "mathbb");
985 case LFUN_FONT_DEFAULT:
986 handleFont(cur, cmd.argument(), "textnormal");
988 case LFUN_FONT_UNDERLINE:
990 cur.handleNest(createInsetMath("underline", cur.buffer()));
993 case LFUN_MATH_MODE: {
995 // ignore math-mode on when already in math mode
996 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
998 cur.recordUndoSelection();
999 cur.macroModeClose();
1000 docstring const save_selection = grabAndEraseSelection(cur);
1002 if (currentMode() != Inset::MATH_MODE)
1003 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1005 cur.plainInsert(createInsetMath("text", buffer_));
1007 cur.pushBackward(*cur.nextInset());
1008 cur.niceInsert(save_selection);
1009 cur.forceBufferUpdate();
1011 if (currentMode() == Inset::TEXT_MODE) {
1012 cur.recordUndoSelection();
1013 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1014 cur.message(_("create new math text environment ($...$)"));
1016 handleFont(cur, cmd.argument(), "textrm");
1017 cur.message(_("entered math text mode (textrm)"));
1023 case LFUN_REGEXP_MODE: {
1024 InsetMath * im = cur.inset().asInsetMath();
1026 InsetMathHull * i = im->asHullInset();
1027 if (i && i->getType() == hullRegexp) {
1028 cur.message(_("Already in regular expression mode"));
1032 cur.macroModeClose();
1033 docstring const save_selection = grabAndEraseSelection(cur);
1035 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1037 cur.pushBackward(*cur.nextInset());
1038 cur.niceInsert(save_selection);
1039 cur.message(_("Regular expression editor mode"));
1043 case LFUN_MATH_FONT_STYLE: {
1044 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1045 doDispatch(cur, fr);
1049 case LFUN_MATH_SIZE: {
1050 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1051 doDispatch(cur, fr);
1055 case LFUN_MATH_MATRIX: {
1061 idocstringstream is(cmd.argument());
1062 is >> m >> n >> v_align >> h_align;
1068 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1069 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1073 case LFUN_MATH_AMS_MATRIX: {
1077 docstring name = from_ascii("matrix");
1078 idocstringstream is(cmd.argument());
1079 is >> m >> n >> name;
1084 // check if we have a valid decoration
1085 if (name != "pmatrix" && name != "bmatrix"
1086 && name != "Bmatrix" && name != "vmatrix"
1087 && name != "Vmatrix" && name != "matrix"
1088 && name != "smallmatrix")
1089 name = from_ascii("matrix");
1092 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1096 case LFUN_MATH_DELIM: {
1098 docstring rs = split(cmd.argument(), ls, ' ');
1099 // Reasonable default values
1105 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1109 case LFUN_MATH_BIGDELIM: {
1110 docstring const lname = from_utf8(cmd.getArg(0));
1111 docstring const ldelim = from_utf8(cmd.getArg(1));
1112 docstring const rname = from_utf8(cmd.getArg(2));
1113 docstring const rdelim = from_utf8(cmd.getArg(3));
1114 latexkeys const * l = in_word_set(lname);
1115 bool const have_l = l && l->inset == "big" &&
1116 InsetMathBig::isBigInsetDelim(ldelim);
1117 l = in_word_set(rname);
1118 bool const have_r = l && l->inset == "big" &&
1119 InsetMathBig::isBigInsetDelim(rdelim);
1120 // We mimic LFUN_MATH_DELIM in case we have an empty left
1121 // or right delimiter.
1122 if (have_l || have_r) {
1124 docstring const selection = grabAndEraseSelection(cur);
1127 cur.insert(MathAtom(new InsetMathBig(lname,
1129 // first insert the right delimiter and then go back
1130 // and re-insert the selection (bug 7088)
1132 cur.insert(MathAtom(new InsetMathBig(rname,
1136 cur.niceInsert(selection);
1138 // Don't call cur.undispatched() if we did nothing, this would
1139 // lead to infinite recursion via Text::dispatch().
1143 case LFUN_SPACE_INSERT: {
1144 cur.recordUndoSelection();
1145 string const name = cmd.getArg(0);
1146 if (name == "normal")
1147 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1148 else if (name == "protected")
1149 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1150 else if (name == "thin" || name == "med" || name == "thick")
1151 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1152 else if (name == "hfill*")
1153 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1154 else if (name == "quad" || name == "qquad" ||
1155 name == "enspace" || name == "enskip" ||
1156 name == "negthinspace" || name == "negmedspace" ||
1157 name == "negthickspace" || name == "hfill")
1158 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1159 else if (name == "hspace" || name == "hspace*") {
1160 string const len = cmd.getArg(1);
1161 if (len.empty() || !isValidLength(len)) {
1162 lyxerr << "LyX function 'space-insert " << name << "' "
1163 "needs a valid length argument." << endl;
1166 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1168 cur.insert(MathAtom(new InsetMathSpace));
1172 case LFUN_MATH_SPACE:
1173 cur.recordUndoSelection();
1174 if (cmd.argument().empty())
1175 cur.insert(MathAtom(new InsetMathSpace));
1177 string const name = cmd.getArg(0);
1178 string const len = cmd.getArg(1);
1179 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1183 case LFUN_ERT_INSERT:
1184 // interpret this as if a backslash was typed
1186 interpretChar(cur, '\\');
1189 case LFUN_MATH_SUBSCRIPT:
1190 // interpret this as if a _ was typed
1191 cur.recordUndoSelection();
1192 interpretChar(cur, '_');
1195 case LFUN_MATH_SUPERSCRIPT:
1196 // interpret this as if a ^ was typed
1197 cur.recordUndoSelection();
1198 interpretChar(cur, '^');
1201 case LFUN_MATH_MACRO_FOLD:
1202 case LFUN_MATH_MACRO_UNFOLD: {
1204 bool fold = act == LFUN_MATH_MACRO_FOLD;
1205 bool found = findMacroToFoldUnfold(it, fold);
1207 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1208 cur.recordUndoInset();
1217 case LFUN_QUOTE_INSERT:
1218 // interpret this as if a straight " was typed
1219 cur.recordUndoSelection();
1220 interpretChar(cur, '\"');
1223 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1224 // handling such that "self-insert" works on "arbitrary stuff" too, and
1225 // math-insert only handles special math things like "matrix".
1226 case LFUN_MATH_INSERT: {
1227 cur.recordUndoSelection();
1228 if (cmd.argument() == "^" || cmd.argument() == "_")
1229 interpretChar(cur, cmd.argument()[0]);
1230 else if (!cur.selection())
1231 cur.niceInsert(cmd.argument());
1233 MathData ar(cur.buffer());
1234 asArray(cmd.argument(), ar);
1236 && ar[0]->asNestInset()
1237 && ar[0]->asNestInset()->nargs() > 1)
1238 handleNest(cur, ar[0]);
1240 cur.niceInsert(cmd.argument());
1245 case LFUN_DIALOG_SHOW_NEW_INSET: {
1246 docstring const & name = cmd.argument();
1248 if (name == "ref") {
1249 InsetMathRef tmp(buffer_, name);
1250 data = tmp.createDialogStr();
1251 cur.bv().showDialog(to_utf8(name), data);
1252 } else if (name == "mathspace") {
1253 cur.bv().showDialog(to_utf8(name));
1258 case LFUN_INSET_INSERT: {
1260 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1261 cur.recordUndoSelection();
1263 cur.forceBufferUpdate();
1268 case LFUN_INSET_DISSOLVE:
1269 if (!asHullInset()) {
1270 cur.recordUndoInset();
1275 case LFUN_MATH_LIMITS: {
1277 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1278 in = &cur.nextMath();
1279 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1280 in = &cur.prevMath();
1281 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1282 in = cur.cell().back().nucleus();
1283 // only when nucleus allows this
1286 cur.recordUndoInset();
1287 if (!cmd.argument().empty()) {
1288 if (cmd.argument() == "limits")
1290 else if (cmd.argument() == "nolimits")
1291 in->limits(NO_LIMITS);
1293 in->limits(AUTO_LIMITS);
1294 } else if (in->limits() != AUTO_LIMITS)
1295 in->limits(AUTO_LIMITS);
1296 else if (in->defaultLimits(cur.cell().displayStyle()) == LIMITS)
1297 in->limits(NO_LIMITS);
1304 InsetMath::doDispatch(cur, cmd);
1310 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1311 // look for macro to open/close, but stay in mathed
1312 for (; !it.empty(); it.pop_back()) {
1314 // go backward through the current cell
1315 Inset * inset = it.nextInset();
1316 while (inset && inset->asInsetMath()) {
1317 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1319 // found the an macro to open/close?
1320 if (macro->folded() != fold)
1323 // Wrong folding state.
1324 // If this was the first we see in this slice, look further left,
1326 if (inset != it.nextInset())
1330 // go up if this was the left most position
1336 inset = it.nextInset();
1344 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1345 FuncStatus & flag) const
1347 // the font related toggles
1348 //string tc = "mathnormal";
1350 string const arg = to_utf8(cmd.argument());
1351 switch (cmd.action()) {
1353 case LFUN_INSET_MODIFY:
1354 // FIXME: check temporarily disabled
1356 char align = mathcursor::valign();
1357 if (align == '\0') {
1361 if (cmd.argument().empty()) {
1365 if (!contains("tcb", cmd.argument()[0])) {
1369 flag.setOnOff(cmd.argument()[0] == align);
1372 /// We have to handle them since 1.4 blocks all unhandled actions
1373 case LFUN_FONT_ITAL:
1374 case LFUN_FONT_BOLD:
1375 case LFUN_FONT_BOLDSYMBOL:
1376 case LFUN_FONT_SANS:
1377 case LFUN_FONT_EMPH:
1378 case LFUN_FONT_TYPEWRITER:
1379 case LFUN_FONT_NOUN:
1380 case LFUN_FONT_ROMAN:
1381 case LFUN_FONT_DEFAULT:
1382 flag.setEnabled(true);
1385 // we just need to be in math mode to enable that
1386 case LFUN_MATH_SIZE:
1387 case LFUN_MATH_SPACE:
1388 case LFUN_MATH_EXTERN:
1389 flag.setEnabled(true);
1392 case LFUN_FONT_UNDERLINE:
1393 case LFUN_FONT_FRAK:
1394 flag.setEnabled(currentMode() != TEXT_MODE);
1397 case LFUN_MATH_FONT_STYLE: {
1398 bool const textarg =
1399 arg == "textbf" || arg == "textsf" ||
1400 arg == "textrm" || arg == "textmd" ||
1401 arg == "textit" || arg == "textsc" ||
1402 arg == "textsl" || arg == "textup" ||
1403 arg == "texttt" || arg == "textbb" ||
1404 arg == "textnormal";
1405 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1409 case LFUN_MATH_MODE:
1410 // forbid "math-mode on" in math mode to prevent irritating
1411 // behaviour of menu entries (bug 6709)
1412 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1415 case LFUN_MATH_INSERT:
1416 flag.setEnabled(currentMode() != TEXT_MODE);
1419 case LFUN_MATH_AMS_MATRIX:
1420 case LFUN_MATH_MATRIX:
1421 flag.setEnabled(currentMode() == MATH_MODE);
1424 case LFUN_INSET_INSERT: {
1425 // Don't test createMathInset_fromDialogStr(), since
1426 // getStatus is not called with a valid reference and the
1427 // dialog would not be applicable.
1428 string const name = cmd.getArg(0);
1429 flag.setEnabled(name == "ref" || name == "mathspace");
1433 case LFUN_DIALOG_SHOW_NEW_INSET: {
1434 docstring const & name = cmd.argument();
1435 if (name == "space")
1436 flag.setEnabled(false);
1441 case LFUN_MATH_DELIM:
1442 case LFUN_MATH_BIGDELIM:
1443 // Don't do this with multi-cell selections
1444 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1447 case LFUN_MATH_MACRO_FOLD:
1448 case LFUN_MATH_MACRO_UNFOLD: {
1450 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1451 flag.setEnabled(found);
1455 case LFUN_SPECIALCHAR_INSERT:
1456 case LFUN_SCRIPT_INSERT:
1457 // FIXME: These would probably make sense in math-text mode
1458 flag.setEnabled(false);
1461 case LFUN_CAPTION_INSERT:
1462 flag.setEnabled(false);
1465 case LFUN_SPACE_INSERT: {
1466 docstring const & name = cmd.argument();
1467 if (name == "visible")
1468 flag.setEnabled(false);
1472 case LFUN_INSET_DISSOLVE:
1473 flag.setEnabled(!asHullInset());
1477 docstring const & name = cmd.argument();
1478 if (name == "html" || name == "latex")
1479 flag.setEnabled(false);
1483 case LFUN_MATH_LIMITS: {
1485 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1486 in = &cur.nextMath();
1487 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1488 in = &cur.prevMath();
1489 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1490 in = cur.cell().back().nucleus();
1492 if (!cmd.argument().empty()) {
1493 if (cmd.argument() == "limits")
1494 flag.setOnOff(in->limits() == LIMITS);
1495 else if (cmd.argument() == "nolimits")
1496 flag.setOnOff(in->limits() == NO_LIMITS);
1498 flag.setOnOff(in->limits() == AUTO_LIMITS);
1500 flag.setEnabled(true);
1502 flag.setEnabled(false);
1514 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1517 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1518 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1519 enter_front ? idxFirst(cur) : idxLast(cur);
1521 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1525 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1528 int dist_min = 1000000;
1529 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1530 int const d = cell(i).dist(cur.bv(), x, y);
1539 MathData & ar = cell(idx_min);
1541 cur.idx() = idx_min;
1542 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1544 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1545 if (dist_min == 0) {
1547 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1548 if (ar[i]->covers(cur.bv(), x, y))
1549 return ar[i].nucleus()->editXY(cur, x, y);
1555 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1557 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1558 BufferView & bv = cur.bv();
1559 if (cmd.button() == mouse_button::button3) {
1560 // Don't do anything if we right-click a
1561 // selection, a context menu will popup.
1562 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1563 && cur < bv.cursor().selectionEnd()) {
1564 cur.noScreenUpdate();
1569 // set cursor after the inset if x is nearer to that position (bug 9748)
1570 cur.moveToClosestEdge(cmd.x(), true);
1572 bool do_selection = cmd.button() == mouse_button::button1
1573 && cmd.modifier() == ShiftModifier;
1574 bv.mouseSetCursor(cur, do_selection);
1575 if (cmd.button() == mouse_button::button1) {
1576 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1577 // Update the cursor update flags as needed:
1579 // Update::Decoration: tells to update the decoration
1580 // (visual box corners that define
1582 // Update::FitCursor: adjust the screen to the cursor
1583 // position if needed
1584 // cur.result().update(): don't overwrite previously set flags.
1585 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1586 | cur.result().screenUpdate());
1587 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1588 if (cap::selection()) {
1589 // See comment in Text::dispatch why we do this
1590 cap::copySelectionToStack();
1591 cmd = FuncRequest(LFUN_PASTE, "0");
1592 doDispatch(bv.cursor(), cmd);
1595 asArray(theSelection().get(), ar);
1596 bv.cursor().insert(ar);
1602 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1604 // only select with button 1
1605 if (cmd.button() != mouse_button::button1)
1608 Cursor & bvcur = cur.bv().cursor();
1610 // ignore motions deeper nested than the real anchor
1611 if (!bvcur.realAnchor().hasPart(cur)) {
1616 // set cursor after the inset if x is nearer to that position (bug 9748)
1617 cur.moveToClosestEdge(cmd.x());
1619 CursorSlice old = bvcur.top();
1621 // We continue with our existing selection or start a new one, so don't
1622 // reset the anchor.
1623 bvcur.setCursor(cur);
1624 // Did we actually move?
1625 if (cur.top() == old)
1626 // We didn't move one iota, so no need to change selection status
1627 // or update the screen.
1628 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1630 bvcur.setSelection();
1634 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1636 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1638 if (cmd.button() == mouse_button::button1) {
1639 if (!cur.selection())
1640 cur.noScreenUpdate();
1642 Cursor & bvcur = cur.bv().cursor();
1643 bvcur.selection(true);
1652 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1654 // try auto-correction
1655 if (lyxrc.autocorrection_math && cur.pos() != 0
1656 && math_autocorrect(cur, c))
1659 //lyxerr << "interpret 2: '" << c << "'" << endl;
1660 docstring save_selection;
1661 if (c == '^' || c == '_')
1662 save_selection = grabAndEraseSelection(cur);
1665 Buffer * buf = cur.buffer();
1668 if (cur.inMacroMode()) {
1669 docstring name = cur.macroName();
1671 /// are we currently typing '#1' or '#2' or...?
1672 if (name == "\\#") {
1675 if (n >= 1 && n <= 9)
1676 cur.insert(new InsetMathMacroArgument(n));
1680 // do not finish macro for known * commands
1681 bool star_macro = c == '*'
1682 && (in_word_set(name.substr(1) + '*')
1683 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1684 if (isAlphaASCII(c) || star_macro) {
1685 cur.activeMacro()->setName(name + docstring(1, c));
1689 // handle 'special char' macros
1694 if (currentMode() != InsetMath::MATH_MODE)
1695 cur.niceInsert(createInsetMath("textbackslash", buf));
1697 cur.niceInsert(createInsetMath("backslash", buf));
1698 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1700 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1701 } else if (c == '{' || c == '%') {
1702 //using the saved selection as argument
1703 InsetMathUnknown * p = cur.activeMacro();
1705 MathData sel(cur.buffer());
1706 asArray(p->selection(), sel);
1709 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1711 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1712 } else if (c == '#') {
1713 LASSERT(cur.activeMacro(), return false);
1714 cur.activeMacro()->setName(name + docstring(1, c));
1717 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1722 // One character big delimiters. The others are handled in
1723 // interpretString().
1724 latexkeys const * l = in_word_set(name.substr(1));
1725 if (name[0] == '\\' && l && l->inset == "big") {
1729 delim = from_ascii("\\{");
1732 delim = from_ascii("\\}");
1735 delim = docstring(1, c);
1738 if (InsetMathBig::isBigInsetDelim(delim)) {
1739 // name + delim ared a valid InsetMathBig.
1740 // We can't use cur.macroModeClose() because
1741 // it does not handle delim.
1742 InsetMathUnknown * p = cur.activeMacro();
1745 cur.cell().erase(cur.pos());
1746 cur.plainInsert(MathAtom(
1747 new InsetMathBig(name.substr(1), delim)));
1750 } else if (name == "\\smash" && c == '[') {
1751 // We can't use cur.macroModeClose() because
1752 // it would create an InsetMathPhantom
1753 InsetMathUnknown * p = cur.activeMacro();
1755 interpretChar(cur, c);
1759 // leave macro mode and try again if necessary
1760 if (cur.macroModeClose()) {
1761 MathAtom const atom = cur.prevAtom();
1762 if (atom->asNestInset() && atom->isActive()) {
1764 cur.nextInset()->edit(cur, true);
1768 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1770 interpretChar(cur, c);
1775 // just clear selection on pressing the space bar
1776 if (cur.selection() && c == ' ') {
1777 cur.selection(false);
1782 //lyxerr << "starting with macro" << endl;
1783 bool reduced = cap::reduceSelectionToOneCell(cur);
1784 if (reduced || !cur.selection()) {
1785 cur.recordUndoInset();
1786 docstring const safe = cap::grabAndEraseSelection(cur);
1787 if (!cur.inRegexped())
1788 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1790 cur.niceInsert(createInsetMath("backslash", buf));
1798 if (currentMode() != InsetMath::MATH_MODE)
1804 if (currentMode() != InsetMath::MATH_MODE) {
1805 // insert spaces in text or undecided mode,
1806 // but suppress direct insertion of two spaces in a row
1807 // the still allows typing '<space>a<space>' and deleting the 'a', but
1808 // it is better than nothing...
1809 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1811 // FIXME: we have to enable full redraw here because of the
1812 // visual box corners that define the inset. If we know for
1813 // sure that we stay within the same cell we can optimize for
1815 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1819 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1820 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1821 // FIXME: we have to enable full redraw here because of the
1822 // visual box corners that define the inset. If we know for
1823 // sure that we stay within the same cell we can optimize for
1825 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1829 if (cur.popForward()) {
1830 // FIXME: we have to enable full redraw here because of the
1831 // visual box corners that define the inset. If we know for
1832 // sure that we stay within the same cell we can optimize for
1834 //cur.screenUpdateFlags(Update::FitCursor);
1838 // if we are at the very end, leave the formula
1839 return cur.pos() != cur.lastpos();
1842 // These should be treated differently when not in text mode:
1843 if (cur.inRegexped()) {
1846 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1853 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1856 cur.niceInsert(createInsetMath("sim", buf));
1862 } else if (currentMode() != InsetMath::TEXT_MODE) {
1864 script(cur, false, save_selection);
1868 script(cur, true, save_selection);
1872 cur.niceInsert(createInsetMath("sim", buf));
1875 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1876 MathAtom at = createInsetMath("text", buf);
1877 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1884 cur.niceInsert(createInsetMath("textasciicircum", buf));
1888 cur.niceInsert(createInsetMath("textasciitilde", buf));
1893 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1894 c == '%' || c == '_') {
1895 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1899 // no special circumstances, so insert the character without any fuss
1905 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1907 if (str == "\\limits" || str == "\\nolimits") {
1908 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1909 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1912 cur.message(bformat(_("Cannot apply %1$s here."), str));
1916 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1918 if (!cur.empty() && cur.pos() > 0 &&
1919 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1920 if (InsetMathBig::isBigInsetDelim(str)) {
1921 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1922 if (prev[0] == '\\') {
1923 prev = prev.substr(1);
1924 latexkeys const * l = in_word_set(prev);
1925 if (l && l->inset == "big") {
1926 cur.recordUndoSelection();
1927 cur.cell()[cur.pos() - 1] =
1928 MathAtom(new InsetMathBig(prev, str));
1938 bool InsetMathNest::script(Cursor & cur, bool up)
1940 return script(cur, up, docstring());
1944 bool InsetMathNest::script(Cursor & cur, bool up,
1945 docstring const & save_selection)
1947 // Hack to get \^ and \_ working
1948 //lyxerr << "handling script: up: " << up << endl;
1949 if (cur.inMacroMode() && cur.macroName() == "\\") {
1951 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1953 interpretChar(cur, '_');
1957 cur.macroModeClose();
1958 if (asScriptInset() && cur.idx() == 0) {
1959 // we are in a nucleus of a script inset, move to _our_ script
1960 InsetMathScript * inset = asScriptInset();
1961 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1963 cur.idx() = inset->idxOfScript(up);
1965 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1967 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1970 cur.idx() = inset->idxOfScript(up);
1971 cur.pos() = cur.lastpos();
1973 // convert the thing to our left to a scriptinset or create a new
1974 // one if in the very first position of the array
1975 if (cur.pos() == 0) {
1976 //lyxerr << "new scriptinset" << endl;
1977 cur.insert(new InsetMathScript(buffer_, up));
1979 //lyxerr << "converting prev atom " << endl;
1980 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1983 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1984 // See comment in MathParser.cpp for special handling of {}-bases
1990 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1991 cur.niceInsert(save_selection);
1993 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1998 bool InsetMathNest::completionSupported(Cursor const & cur) const
2000 return cur.inMacroMode();
2004 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2006 return cur.inMacroMode();
2010 bool InsetMathNest::automaticInlineCompletion() const
2012 return lyxrc.completion_inline_math;
2016 bool InsetMathNest::automaticPopupCompletion() const
2018 return lyxrc.completion_popup_math;
2022 CompletionList const *
2023 InsetMathNest::createCompletionList(Cursor const & cur) const
2025 if (!cur.inMacroMode())
2028 return new MathCompletionList(cur);
2032 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2034 if (!cur.inMacroMode())
2037 return cur.activeMacro()->name();
2041 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2044 if (!cur.inMacroMode())
2047 // append completion to active macro
2048 InsetMathUnknown * inset = cur.activeMacro();
2049 inset->setName(inset->name() + s);
2054 // FIXME: this creates duplicates in the completion popup
2055 // which looks ugly. Moreover the changes the list lengths
2056 // which seems to confuse the popup as well.
2057 MathCompletionList::addToFavorites(inset->name());
2059 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2066 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2067 Dimension & dim) const
2069 Inset const * inset = cur.activeMacro();
2073 // get inset dimensions
2074 dim = cur.bv().coordCache().insets().dim(inset);
2075 // FIXME: these 3 are no accurate, but should depend on the font.
2076 // Now the popup jumps down if you enter a char with descent > 0.
2081 Point xy = cur.bv().coordCache().insets().xy(inset);
2087 ////////////////////////////////////////////////////////////////////
2089 MathCompletionList::MathCompletionList(Cursor const & cur)
2091 // fill it with macros from the buffer
2092 MacroNameSet macros;
2093 cur.buffer()->listMacroNames(macros);
2094 MacroNameSet::const_iterator it;
2095 for (it = macros.begin(); it != macros.end(); ++it) {
2096 if (cur.buffer()->getMacro(*it, cur, false))
2097 locals.push_back("\\" + *it);
2099 sort(locals.begin(), locals.end());
2101 if (!globals.empty())
2104 // fill in global macros
2106 MacroTable::globalMacros().getMacroNames(macros, false);
2107 //lyxerr << "Globals completion macros: ";
2108 for (it = macros.begin(); it != macros.end(); ++it) {
2109 //lyxerr << "\\" + *it << " ";
2110 globals.push_back("\\" + *it);
2112 //lyxerr << std::endl;
2114 // fill in global commands
2115 globals.push_back(from_ascii("\\boxed"));
2116 globals.push_back(from_ascii("\\fbox"));
2117 globals.push_back(from_ascii("\\framebox"));
2118 globals.push_back(from_ascii("\\makebox"));
2119 globals.push_back(from_ascii("\\kern"));
2120 globals.push_back(from_ascii("\\xhookrightarrow"));
2121 globals.push_back(from_ascii("\\xhookleftarrow"));
2122 globals.push_back(from_ascii("\\xrightarrow"));
2123 globals.push_back(from_ascii("\\xRightarrow"));
2124 globals.push_back(from_ascii("\\xrightharpoondown"));
2125 globals.push_back(from_ascii("\\xrightharpoonup"));
2126 globals.push_back(from_ascii("\\xrightleftharpoons"));
2127 globals.push_back(from_ascii("\\xleftarrow"));
2128 globals.push_back(from_ascii("\\xLeftarrow"));
2129 globals.push_back(from_ascii("\\xleftharpoondown"));
2130 globals.push_back(from_ascii("\\xleftharpoonup"));
2131 globals.push_back(from_ascii("\\xleftrightarrow"));
2132 globals.push_back(from_ascii("\\xLeftrightarrow"));
2133 globals.push_back(from_ascii("\\xleftrightharpoons"));
2134 globals.push_back(from_ascii("\\xmapsto"));
2135 globals.push_back(from_ascii("\\split"));
2136 globals.push_back(from_ascii("\\gathered"));
2137 globals.push_back(from_ascii("\\aligned"));
2138 globals.push_back(from_ascii("\\alignedat"));
2139 globals.push_back(from_ascii("\\cases"));
2140 globals.push_back(from_ascii("\\substack"));
2141 globals.push_back(from_ascii("\\xymatrix"));
2142 globals.push_back(from_ascii("\\Diagram"));
2143 globals.push_back(from_ascii("\\subarray"));
2144 globals.push_back(from_ascii("\\array"));
2145 globals.push_back(from_ascii("\\sqrt"));
2146 globals.push_back(from_ascii("\\root"));
2147 globals.push_back(from_ascii("\\tabular"));
2148 globals.push_back(from_ascii("\\sideset"));
2149 globals.push_back(from_ascii("\\stackrel"));
2150 globals.push_back(from_ascii("\\stackrelthree"));
2151 globals.push_back(from_ascii("\\binom"));
2152 globals.push_back(from_ascii("\\choose"));
2153 globals.push_back(from_ascii("\\brace"));
2154 globals.push_back(from_ascii("\\brack"));
2155 globals.push_back(from_ascii("\\frac"));
2156 globals.push_back(from_ascii("\\over"));
2157 globals.push_back(from_ascii("\\nicefrac"));
2158 globals.push_back(from_ascii("\\unitfrac"));
2159 globals.push_back(from_ascii("\\unitfracthree"));
2160 globals.push_back(from_ascii("\\unitone"));
2161 globals.push_back(from_ascii("\\unittwo"));
2162 globals.push_back(from_ascii("\\infer"));
2163 globals.push_back(from_ascii("\\atop"));
2164 globals.push_back(from_ascii("\\lefteqn"));
2165 globals.push_back(from_ascii("\\boldsymbol"));
2166 globals.push_back(from_ascii("\\bm"));
2167 globals.push_back(from_ascii("\\color"));
2168 globals.push_back(from_ascii("\\normalcolor"));
2169 globals.push_back(from_ascii("\\textcolor"));
2170 globals.push_back(from_ascii("\\cfrac"));
2171 globals.push_back(from_ascii("\\cfracleft"));
2172 globals.push_back(from_ascii("\\cfracright"));
2173 globals.push_back(from_ascii("\\dfrac"));
2174 globals.push_back(from_ascii("\\tfrac"));
2175 globals.push_back(from_ascii("\\dbinom"));
2176 globals.push_back(from_ascii("\\tbinom"));
2177 globals.push_back(from_ascii("\\hphantom"));
2178 globals.push_back(from_ascii("\\phantom"));
2179 globals.push_back(from_ascii("\\vphantom"));
2180 globals.push_back(from_ascii("\\cancel"));
2181 globals.push_back(from_ascii("\\bcancel"));
2182 globals.push_back(from_ascii("\\xcancel"));
2183 globals.push_back(from_ascii("\\cancelto"));
2184 globals.push_back(from_ascii("\\smash"));
2185 globals.push_back(from_ascii("\\mathclap"));
2186 globals.push_back(from_ascii("\\mathllap"));
2187 globals.push_back(from_ascii("\\mathrlap"));
2188 globals.push_back(from_ascii("\\ensuremath"));
2189 MathWordList const & words = mathedWordList();
2190 MathWordList::const_iterator it2;
2191 //lyxerr << "Globals completion commands: ";
2192 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2193 if (it2->second.inset != "macro" && !it2->second.hidden) {
2194 // macros are already read from MacroTable::globalMacros()
2195 globals.push_back('\\' + it2->first);
2196 //lyxerr << '\\' + it2->first << ' ';
2199 //lyxerr << std::endl;
2200 sort(globals.begin(), globals.end());
2204 MathCompletionList::~MathCompletionList()
2209 size_type MathCompletionList::size() const
2211 return locals.size() + globals.size();
2215 docstring const & MathCompletionList::data(size_t idx) const
2217 size_t lsize = locals.size();
2219 return globals[idx - lsize];
2225 std::string MathCompletionList::icon(size_t idx) const
2227 // get the latex command
2229 size_t lsize = locals.size();
2231 cmd = globals[idx - lsize];
2235 // get the icon name by stripping the backslash
2236 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2237 if (icon_name.empty())
2238 return std::string();
2239 return "math/" + to_utf8(icon_name);
2242 std::vector<docstring> MathCompletionList::globals;