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();
561 case LFUN_MOUSE_PRESS:
562 lfunMousePress(cur, cmd);
565 case LFUN_MOUSE_MOTION:
566 lfunMouseMotion(cur, cmd);
569 case LFUN_MOUSE_RELEASE:
570 lfunMouseRelease(cur, cmd);
573 case LFUN_FINISHED_LEFT: // in math, left is backwards
574 case LFUN_FINISHED_BACKWARD:
575 cur.bv().cursor() = cur;
578 case LFUN_FINISHED_RIGHT: // in math, right is forward
579 case LFUN_FINISHED_FORWARD:
581 cur.bv().cursor() = cur;
584 case LFUN_WORD_RIGHT:
586 case LFUN_WORD_BACKWARD:
587 case LFUN_WORD_FORWARD:
588 case LFUN_CHAR_RIGHT:
590 case LFUN_CHAR_BACKWARD:
591 case LFUN_CHAR_FORWARD:
592 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
594 case LFUN_WORD_RIGHT_SELECT:
595 case LFUN_WORD_LEFT_SELECT:
596 case LFUN_WORD_BACKWARD_SELECT:
597 case LFUN_WORD_FORWARD_SELECT:
598 case LFUN_CHAR_RIGHT_SELECT:
599 case LFUN_CHAR_LEFT_SELECT:
600 case LFUN_CHAR_BACKWARD_SELECT:
601 case LFUN_CHAR_FORWARD_SELECT: {
602 // are we in a selection?
603 bool select = (act == LFUN_WORD_RIGHT_SELECT
604 || act == LFUN_WORD_LEFT_SELECT
605 || act == LFUN_WORD_BACKWARD_SELECT
606 || act == LFUN_WORD_FORWARD_SELECT
607 || act == LFUN_CHAR_RIGHT_SELECT
608 || act == LFUN_CHAR_LEFT_SELECT
609 || act == LFUN_CHAR_BACKWARD_SELECT
610 || act == LFUN_CHAR_FORWARD_SELECT);
612 bool word = (act == LFUN_WORD_RIGHT_SELECT
613 || act == LFUN_WORD_LEFT_SELECT
614 || act == LFUN_WORD_BACKWARD_SELECT
615 || act == LFUN_WORD_FORWARD_SELECT
616 || act == LFUN_WORD_RIGHT
617 || act == LFUN_WORD_LEFT
618 || act == LFUN_WORD_BACKWARD
619 || act == LFUN_WORD_FORWARD);
620 // are we moving forward or backwards?
621 // If the command was RIGHT or LEFT, then whether we're moving forward
622 // or backwards depends on the cursor movement mode (logical or visual):
623 // * in visual mode, since math is always LTR, right -> forward,
625 // * in logical mode, the mapping is determined by the
626 // reverseDirectionNeeded() function
629 FuncCode finish_lfun;
631 if (act == LFUN_CHAR_FORWARD
632 || act == LFUN_CHAR_FORWARD_SELECT
633 || act == LFUN_WORD_FORWARD
634 || act == LFUN_WORD_FORWARD_SELECT) {
636 finish_lfun = LFUN_FINISHED_FORWARD;
638 else if (act == LFUN_CHAR_BACKWARD
639 || act == LFUN_CHAR_BACKWARD_SELECT
640 || act == LFUN_WORD_BACKWARD
641 || act == LFUN_WORD_BACKWARD_SELECT) {
643 finish_lfun = LFUN_FINISHED_BACKWARD;
646 bool right = (act == LFUN_CHAR_RIGHT_SELECT
647 || act == LFUN_CHAR_RIGHT
648 || act == LFUN_WORD_RIGHT_SELECT
649 || act == LFUN_WORD_RIGHT);
650 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
656 finish_lfun = LFUN_FINISHED_RIGHT;
658 finish_lfun = LFUN_FINISHED_LEFT;
660 // Now that we know exactly what we want to do, let's do it!
661 cur.selHandle(select);
663 cur.macroModeClose();
664 // try moving forward or backwards as necessary...
665 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
666 // ... and if movement failed, then finish forward or backwards
668 cmd = FuncRequest(finish_lfun);
676 case LFUN_PARAGRAPH_UP:
677 case LFUN_PARAGRAPH_DOWN:
678 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
680 case LFUN_DOWN_SELECT:
682 case LFUN_PARAGRAPH_UP_SELECT:
683 case LFUN_PARAGRAPH_DOWN_SELECT: {
684 // close active macro
685 if (cur.inMacroMode()) {
686 cur.macroModeClose();
690 // stop/start the selection
691 bool select = act == LFUN_DOWN_SELECT
692 || act == LFUN_UP_SELECT
693 || act == LFUN_PARAGRAPH_DOWN_SELECT
694 || act == LFUN_PARAGRAPH_UP_SELECT;
695 cur.selHandle(select);
698 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
699 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
700 bool successful = cur.upDownInMath(up);
704 if (cur.fixIfBroken())
705 // FIXME: Something bad happened. We pass the corrected Cursor
706 // instead of letting things go worse.
709 // We did not manage to move the cursor.
714 case LFUN_MOUSE_DOUBLE:
715 case LFUN_WORD_SELECT:
717 cur.bv().mouseSetCursor(cur);
718 cur.pos() = cur.lastpos();
719 cur.bv().mouseSetCursor(cur, true);
722 case LFUN_MOUSE_TRIPLE:
725 cur.bv().mouseSetCursor(cur);
726 cur.idx() = cur.lastidx();
727 cur.pos() = cur.lastpos();
728 cur.bv().mouseSetCursor(cur, true);
731 case LFUN_LINE_BEGIN:
732 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
734 case LFUN_LINE_BEGIN_SELECT:
735 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
736 act == LFUN_WORD_LEFT_SELECT ||
737 act == LFUN_LINE_BEGIN_SELECT);
738 cur.macroModeClose();
739 if (cur.pos() != 0) {
741 } else if (cur.col() != 0) {
742 cur.idx() -= cur.col();
744 } else if (cur.idx() != 0) {
748 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
754 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
756 case LFUN_LINE_END_SELECT:
757 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
758 act == LFUN_WORD_RIGHT_SELECT ||
759 act == LFUN_LINE_END_SELECT);
760 cur.macroModeClose();
762 if (cur.pos() != cur.lastpos()) {
763 cur.pos() = cur.lastpos();
764 } else if (ncols() && (cur.col() != cur.lastcol())) {
765 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
766 cur.pos() = cur.lastpos();
767 } else if (cur.idx() != cur.lastidx()) {
768 cur.idx() = cur.lastidx();
769 cur.pos() = cur.lastpos();
771 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
776 case LFUN_CELL_FORWARD:
777 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
778 cur.selHandle(false);
780 cur.macroModeClose();
781 if (!cur.inset().idxNext(cur)) {
782 cur.idx() = firstIdx();
787 case LFUN_CELL_BACKWARD:
788 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
789 cur.selHandle(false);
791 cur.macroModeClose();
792 if (!cur.inset().idxPrev(cur)) {
793 cur.idx() = lastIdx();
794 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
798 case LFUN_WORD_DELETE_BACKWARD:
799 case LFUN_CHAR_DELETE_BACKWARD:
801 // May affect external cell:
802 cur.recordUndoInset();
803 else if (!cur.inMacroMode())
804 cur.recordUndoSelection();
805 // if the inset can not be removed from within, delete it
806 if (!cur.backspace(cmd.getArg(0) == "force")) {
807 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
808 cur.innerText()->dispatch(cur, newcmd);
812 case LFUN_WORD_DELETE_FORWARD:
813 case LFUN_CHAR_DELETE_FORWARD:
814 if (cur.pos() == cur.lastpos())
815 // May affect external cell:
816 cur.recordUndoInset();
818 cur.recordUndoSelection();
819 // if the inset can not be removed from within, delete it
820 if (!cur.erase(cmd.getArg(0) == "force")) {
821 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
822 cur.innerText()->dispatch(cur, newcmd);
828 cur.clearSelection();
830 if (cur.inMacroMode())
831 cur.macroModeClose(true);
833 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
839 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
840 // that is traversed by a single <CursorLeft>/<CursorRight>.
841 case LFUN_INSET_TOGGLE:
847 case LFUN_SELF_INSERT:
848 // special case first for big delimiters
849 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
852 for (char_type c : cmd.argument()) {
853 // Don't record undo steps if we are in macro mode and thus
854 // cmd.argument is the next character of the macro name.
855 // Otherwise we'll get an invalid cursor if we undo after
856 // the macro was finished and the macro is a known command,
857 // e.g. sqrt. Cursor::macroModeClose replaces in this case
858 // the InsetMathUnknown with name "frac" by an empty
859 // InsetMathFrac -> a pos value > 0 is invalid.
860 // A side effect is that an undo before the macro is finished
861 // undoes the complete macro, not only the last character.
862 // At the time we hit '\' we are not in macro mode, still.
863 if (!cur.inMacroMode())
864 cur.recordUndoSelection();
866 // special handling of space. If we insert an inset
867 // via macro mode, we want to put the cursor inside it
868 // if relevant. Think typing "\frac<space>".
870 && cur.inMacroMode() && cur.macroName() != "\\"
871 && cur.macroModeClose() && cur.pos() > 0)
872 cur.editInsertedInset();
873 else if (!interpretChar(cur, c)) {
874 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
876 // FIXME: can we avoid skipping the end of the string?
882 //case LFUN_SERVER_GET_XY:
885 case LFUN_SERVER_SET_XY: {
886 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
889 istringstream is(to_utf8(cmd.argument()));
895 // Special casing for superscript in case of LyX handling
897 case LFUN_ACCENT_CIRCUMFLEX:
898 if (cmd.argument().empty()) {
899 // do superscript if LyX handles
901 cur.recordUndoInset();
902 script(cur, true, grabAndEraseSelection(cur));
906 case LFUN_ACCENT_UMLAUT:
907 case LFUN_ACCENT_ACUTE:
908 case LFUN_ACCENT_GRAVE:
909 case LFUN_ACCENT_BREVE:
910 case LFUN_ACCENT_DOT:
911 case LFUN_ACCENT_MACRON:
912 case LFUN_ACCENT_CARON:
913 case LFUN_ACCENT_TILDE:
914 case LFUN_ACCENT_CEDILLA:
915 case LFUN_ACCENT_CIRCLE:
916 case LFUN_ACCENT_UNDERDOT:
917 case LFUN_ACCENT_TIE:
918 case LFUN_ACCENT_OGONEK:
919 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
923 case LFUN_TEXTSTYLE_APPLY:
924 case LFUN_TEXTSTYLE_UPDATE:
925 handleFont2(cur, cmd.argument());
929 if (currentMode() != MATH_MODE)
930 handleFont(cur, cmd.argument(), "textbf");
932 handleFont(cur, cmd.argument(), "mathbf");
934 case LFUN_FONT_BOLDSYMBOL:
935 if (currentMode() != MATH_MODE)
936 handleFont(cur, cmd.argument(), "textbf");
938 handleFont(cur, cmd.argument(), "boldsymbol");
941 if (currentMode() != MATH_MODE)
942 handleFont(cur, cmd.argument(), "textsf");
944 handleFont(cur, cmd.argument(), "mathsf");
947 if (currentMode() != MATH_MODE)
948 handleFont(cur, cmd.argument(), "emph");
950 handleFont(cur, cmd.argument(), "mathcal");
952 case LFUN_FONT_ROMAN:
953 if (currentMode() != MATH_MODE)
954 handleFont(cur, cmd.argument(), "textrm");
956 handleFont(cur, cmd.argument(), "mathrm");
958 case LFUN_FONT_TYPEWRITER:
959 if (currentMode() != MATH_MODE)
960 handleFont(cur, cmd.argument(), "texttt");
962 handleFont(cur, cmd.argument(), "mathtt");
965 handleFont(cur, cmd.argument(), "mathfrak");
968 if (currentMode() != MATH_MODE)
969 handleFont(cur, cmd.argument(), "textit");
971 handleFont(cur, cmd.argument(), "mathit");
974 if (currentMode() != MATH_MODE)
975 // FIXME: should be "noun"
976 handleFont(cur, cmd.argument(), "textsc");
978 handleFont(cur, cmd.argument(), "mathbb");
980 case LFUN_FONT_DEFAULT:
981 handleFont(cur, cmd.argument(), "textnormal");
983 case LFUN_FONT_UNDERLINE:
985 cur.handleNest(createInsetMath("underline", cur.buffer()));
988 case LFUN_MATH_MODE: {
990 // ignore math-mode on when already in math mode
991 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
993 cur.recordUndoSelection();
994 cur.macroModeClose();
995 docstring const save_selection = grabAndEraseSelection(cur);
997 if (currentMode() != Inset::MATH_MODE)
998 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1000 cur.plainInsert(createInsetMath("text", buffer_));
1002 cur.pushBackward(*cur.nextInset());
1003 cur.niceInsert(save_selection);
1004 cur.forceBufferUpdate();
1006 if (currentMode() == Inset::TEXT_MODE) {
1007 cur.recordUndoSelection();
1008 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1009 cur.message(_("create new math text environment ($...$)"));
1011 handleFont(cur, cmd.argument(), "textrm");
1012 cur.message(_("entered math text mode (textrm)"));
1018 case LFUN_REGEXP_MODE: {
1019 InsetMath * im = cur.inset().asInsetMath();
1021 InsetMathHull * i = im->asHullInset();
1022 if (i && i->getType() == hullRegexp) {
1023 cur.message(_("Already in regular expression mode"));
1027 cur.macroModeClose();
1028 docstring const save_selection = grabAndEraseSelection(cur);
1030 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1032 cur.pushBackward(*cur.nextInset());
1033 cur.niceInsert(save_selection);
1034 cur.message(_("Regular expression editor mode"));
1038 case LFUN_MATH_FONT_STYLE: {
1039 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1040 doDispatch(cur, fr);
1044 case LFUN_MATH_SIZE: {
1045 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1046 doDispatch(cur, fr);
1050 case LFUN_MATH_MATRIX: {
1056 idocstringstream is(cmd.argument());
1057 is >> m >> n >> v_align >> h_align;
1063 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1064 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1068 case LFUN_MATH_AMS_MATRIX: {
1072 docstring name = from_ascii("matrix");
1073 idocstringstream is(cmd.argument());
1074 is >> m >> n >> name;
1079 // check if we have a valid decoration
1080 if (name != "pmatrix" && name != "bmatrix"
1081 && name != "Bmatrix" && name != "vmatrix"
1082 && name != "Vmatrix" && name != "matrix"
1083 && name != "smallmatrix")
1084 name = from_ascii("matrix");
1087 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1091 case LFUN_MATH_DELIM: {
1093 docstring rs = split(cmd.argument(), ls, ' ');
1094 // Reasonable default values
1100 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1104 case LFUN_MATH_BIGDELIM: {
1105 docstring const lname = from_utf8(cmd.getArg(0));
1106 docstring const ldelim = from_utf8(cmd.getArg(1));
1107 docstring const rname = from_utf8(cmd.getArg(2));
1108 docstring const rdelim = from_utf8(cmd.getArg(3));
1109 latexkeys const * l = in_word_set(lname);
1110 bool const have_l = l && l->inset == "big" &&
1111 InsetMathBig::isBigInsetDelim(ldelim);
1112 l = in_word_set(rname);
1113 bool const have_r = l && l->inset == "big" &&
1114 InsetMathBig::isBigInsetDelim(rdelim);
1115 // We mimic LFUN_MATH_DELIM in case we have an empty left
1116 // or right delimiter.
1117 if (have_l || have_r) {
1119 docstring const selection = grabAndEraseSelection(cur);
1122 cur.insert(MathAtom(new InsetMathBig(lname,
1124 // first insert the right delimiter and then go back
1125 // and re-insert the selection (bug 7088)
1127 cur.insert(MathAtom(new InsetMathBig(rname,
1131 cur.niceInsert(selection);
1133 // Don't call cur.undispatched() if we did nothing, this would
1134 // lead to infinite recursion via Text::dispatch().
1138 case LFUN_SPACE_INSERT: {
1139 cur.recordUndoSelection();
1140 string const name = cmd.getArg(0);
1141 if (name == "normal")
1142 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1143 else if (name == "protected")
1144 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1145 else if (name == "thin" || name == "med" || name == "thick")
1146 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1147 else if (name == "hfill*")
1148 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1149 else if (name == "quad" || name == "qquad" ||
1150 name == "enspace" || name == "enskip" ||
1151 name == "negthinspace" || name == "negmedspace" ||
1152 name == "negthickspace" || name == "hfill")
1153 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1154 else if (name == "hspace" || name == "hspace*") {
1155 string const len = cmd.getArg(1);
1156 if (len.empty() || !isValidLength(len)) {
1157 lyxerr << "LyX function 'space-insert " << name << "' "
1158 "needs a valid length argument." << endl;
1161 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1163 cur.insert(MathAtom(new InsetMathSpace));
1167 case LFUN_MATH_SPACE:
1168 cur.recordUndoSelection();
1169 if (cmd.argument().empty())
1170 cur.insert(MathAtom(new InsetMathSpace));
1172 string const name = cmd.getArg(0);
1173 string const len = cmd.getArg(1);
1174 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1178 case LFUN_ERT_INSERT:
1179 // interpret this as if a backslash was typed
1181 interpretChar(cur, '\\');
1184 case LFUN_MATH_SUBSCRIPT:
1185 // interpret this as if a _ was typed
1186 cur.recordUndoSelection();
1187 interpretChar(cur, '_');
1190 case LFUN_MATH_SUPERSCRIPT:
1191 // interpret this as if a ^ was typed
1192 cur.recordUndoSelection();
1193 interpretChar(cur, '^');
1196 case LFUN_MATH_MACRO_FOLD:
1197 case LFUN_MATH_MACRO_UNFOLD: {
1199 bool fold = act == LFUN_MATH_MACRO_FOLD;
1200 bool found = findMacroToFoldUnfold(it, fold);
1202 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1203 cur.recordUndoInset();
1212 case LFUN_QUOTE_INSERT:
1213 // interpret this as if a straight " was typed
1214 cur.recordUndoSelection();
1215 interpretChar(cur, '\"');
1218 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1219 // handling such that "self-insert" works on "arbitrary stuff" too, and
1220 // math-insert only handles special math things like "matrix".
1221 case LFUN_MATH_INSERT: {
1222 cur.recordUndoSelection();
1223 if (cmd.argument() == "^" || cmd.argument() == "_")
1224 interpretChar(cur, cmd.argument()[0]);
1225 else if (!cur.selection())
1226 cur.niceInsert(cmd.argument());
1228 MathData ar(cur.buffer());
1229 asArray(cmd.argument(), ar);
1231 && ar[0]->asNestInset()
1232 && ar[0]->asNestInset()->nargs() > 1)
1233 handleNest(cur, ar[0]);
1235 cur.niceInsert(cmd.argument());
1240 case LFUN_DIALOG_SHOW_NEW_INSET: {
1241 docstring const & name = cmd.argument();
1243 if (name == "ref") {
1244 InsetMathRef tmp(buffer_, name);
1245 data = tmp.createDialogStr();
1246 cur.bv().showDialog(to_utf8(name), data);
1247 } else if (name == "mathspace") {
1248 cur.bv().showDialog(to_utf8(name));
1253 case LFUN_INSET_INSERT: {
1255 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1256 cur.recordUndoSelection();
1258 cur.forceBufferUpdate();
1263 case LFUN_INSET_DISSOLVE:
1264 if (!asHullInset()) {
1265 cur.recordUndoInset();
1270 case LFUN_MATH_LIMITS: {
1272 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1273 in = &cur.nextMath();
1274 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1275 in = &cur.prevMath();
1276 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1277 in = cur.cell().back().nucleus();
1278 // only when nucleus allows this
1281 cur.recordUndoInset();
1282 if (!cmd.argument().empty()) {
1283 if (cmd.argument() == "limits")
1285 else if (cmd.argument() == "nolimits")
1286 in->limits(NO_LIMITS);
1288 in->limits(AUTO_LIMITS);
1289 } else if (in->limits() != AUTO_LIMITS)
1290 in->limits(AUTO_LIMITS);
1291 else if (in->defaultLimits(cur.cell().displayStyle()) == LIMITS)
1292 in->limits(NO_LIMITS);
1298 case LFUN_PHANTOM_INSERT: {
1299 docstring const & arg = cmd.argument();
1301 if (arg == "Phantom")
1302 newarg = from_ascii("\\phantom");
1303 else if (arg == "HPhantom")
1304 newarg = from_ascii("\\hphantom");
1305 else if (arg == "VPhantom")
1306 newarg = from_ascii("\\vphantom");
1308 LYXERR0("Unknown phantom type " + newarg);
1310 FuncRequest const newfunc(LFUN_MATH_INSERT, newarg);
1311 lyx::dispatch(newfunc);
1317 InsetMath::doDispatch(cur, cmd);
1323 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1324 // look for macro to open/close, but stay in mathed
1325 for (; !it.empty(); it.pop_back()) {
1327 // go backward through the current cell
1328 Inset * inset = it.nextInset();
1329 while (inset && inset->asInsetMath()) {
1330 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1332 // found the an macro to open/close?
1333 if (macro->folded() != fold)
1336 // Wrong folding state.
1337 // If this was the first we see in this slice, look further left,
1339 if (inset != it.nextInset())
1343 // go up if this was the left most position
1349 inset = it.nextInset();
1357 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1358 FuncStatus & flag) const
1360 // the font related toggles
1361 //string tc = "mathnormal";
1363 string const arg = to_utf8(cmd.argument());
1364 switch (cmd.action()) {
1366 case LFUN_INSET_MODIFY:
1367 // FIXME: check temporarily disabled
1369 char align = mathcursor::valign();
1370 if (align == '\0') {
1374 if (cmd.argument().empty()) {
1378 if (!contains("tcb", cmd.argument()[0])) {
1382 flag.setOnOff(cmd.argument()[0] == align);
1385 /// We have to handle them since 1.4 blocks all unhandled actions
1386 case LFUN_FONT_ITAL:
1387 case LFUN_FONT_BOLD:
1388 case LFUN_FONT_BOLDSYMBOL:
1389 case LFUN_FONT_SANS:
1390 case LFUN_FONT_EMPH:
1391 case LFUN_FONT_TYPEWRITER:
1392 case LFUN_FONT_NOUN:
1393 case LFUN_FONT_ROMAN:
1394 case LFUN_FONT_DEFAULT:
1395 flag.setEnabled(true);
1398 // we just need to be in math mode to enable that
1399 case LFUN_MATH_SIZE:
1400 case LFUN_MATH_SPACE:
1401 case LFUN_MATH_EXTERN:
1402 flag.setEnabled(true);
1405 case LFUN_FONT_UNDERLINE:
1406 case LFUN_FONT_FRAK:
1407 flag.setEnabled(currentMode() != TEXT_MODE);
1410 case LFUN_MATH_FONT_STYLE: {
1411 bool const textarg =
1412 arg == "textbf" || arg == "textsf" ||
1413 arg == "textrm" || arg == "textmd" ||
1414 arg == "textit" || arg == "textsc" ||
1415 arg == "textsl" || arg == "textup" ||
1416 arg == "texttt" || arg == "textbb" ||
1417 arg == "textnormal";
1418 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1422 case LFUN_MATH_MODE:
1423 // forbid "math-mode on" in math mode to prevent irritating
1424 // behaviour of menu entries (bug 6709)
1425 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1428 case LFUN_MATH_INSERT:
1429 flag.setEnabled(currentMode() != TEXT_MODE);
1432 case LFUN_MATH_AMS_MATRIX:
1433 case LFUN_MATH_MATRIX:
1434 flag.setEnabled(currentMode() == MATH_MODE);
1437 case LFUN_INSET_INSERT: {
1438 // Don't test createMathInset_fromDialogStr(), since
1439 // getStatus is not called with a valid reference and the
1440 // dialog would not be applicable.
1441 string const name = cmd.getArg(0);
1442 flag.setEnabled(name == "ref" || name == "mathspace");
1446 case LFUN_DIALOG_SHOW_NEW_INSET: {
1447 docstring const & name = cmd.argument();
1448 if (name == "space")
1449 flag.setEnabled(false);
1454 case LFUN_MATH_DELIM:
1455 case LFUN_MATH_BIGDELIM:
1456 // Don't do this with multi-cell selections
1457 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1460 case LFUN_MATH_MACRO_FOLD:
1461 case LFUN_MATH_MACRO_UNFOLD: {
1463 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1464 flag.setEnabled(found);
1468 case LFUN_SPECIALCHAR_INSERT:
1469 case LFUN_SCRIPT_INSERT:
1470 // FIXME: These would probably make sense in math-text mode
1471 flag.setEnabled(false);
1474 case LFUN_CAPTION_INSERT:
1475 flag.setEnabled(false);
1478 case LFUN_SPACE_INSERT: {
1479 docstring const & name = cmd.argument();
1480 if (name == "visible")
1481 flag.setEnabled(false);
1485 case LFUN_INSET_DISSOLVE:
1486 flag.setEnabled(!asHullInset());
1490 docstring const & name = cmd.argument();
1491 if (name == "html" || name == "latex")
1492 flag.setEnabled(false);
1496 case LFUN_MATH_LIMITS: {
1498 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1499 in = &cur.nextMath();
1500 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1501 in = &cur.prevMath();
1502 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1503 in = cur.cell().back().nucleus();
1505 if (!cmd.argument().empty()) {
1506 if (cmd.argument() == "limits")
1507 flag.setOnOff(in->limits() == LIMITS);
1508 else if (cmd.argument() == "nolimits")
1509 flag.setOnOff(in->limits() == NO_LIMITS);
1511 flag.setOnOff(in->limits() == AUTO_LIMITS);
1513 flag.setEnabled(true);
1515 flag.setEnabled(false);
1527 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1530 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1531 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1532 enter_front ? idxFirst(cur) : idxLast(cur);
1534 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1538 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1541 int dist_min = 1000000;
1542 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1543 int const d = cell(i).dist(cur.bv(), x, y);
1552 MathData & ar = cell(idx_min);
1554 cur.idx() = idx_min;
1555 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1557 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1558 if (dist_min == 0) {
1560 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1561 if (ar[i]->covers(cur.bv(), x, y))
1562 return ar[i].nucleus()->editXY(cur, x, y);
1568 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1570 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1571 BufferView & bv = cur.bv();
1572 if (cmd.button() == mouse_button::button3) {
1573 // Don't do anything if we right-click a
1574 // selection, a context menu will popup.
1575 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1576 && cur < bv.cursor().selectionEnd()) {
1577 cur.noScreenUpdate();
1582 // set cursor after the inset if x is nearer to that position (bug 9748)
1583 cur.moveToClosestEdge(cmd.x(), true);
1585 bool do_selection = cmd.button() == mouse_button::button1
1586 && cmd.modifier() == ShiftModifier;
1587 bv.mouseSetCursor(cur, do_selection);
1588 if (cmd.button() == mouse_button::button1) {
1589 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1590 // Update the cursor update flags as needed:
1592 // Update::Decoration: tells to update the decoration
1593 // (visual box corners that define
1595 // Update::FitCursor: adjust the screen to the cursor
1596 // position if needed
1597 // cur.result().update(): don't overwrite previously set flags.
1598 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1599 | cur.result().screenUpdate());
1600 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1601 if (cap::selection()) {
1602 // See comment in Text::dispatch why we do this
1603 cap::copySelectionToStack();
1604 cmd = FuncRequest(LFUN_PASTE, "0");
1605 doDispatch(bv.cursor(), cmd);
1608 asArray(theSelection().get(), ar);
1609 bv.cursor().insert(ar);
1615 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1617 // only select with button 1
1618 if (cmd.button() != mouse_button::button1)
1621 Cursor & bvcur = cur.bv().cursor();
1623 // ignore motions deeper nested than the real anchor
1624 if (!bvcur.realAnchor().hasPart(cur)) {
1629 // set cursor after the inset if x is nearer to that position (bug 9748)
1630 cur.moveToClosestEdge(cmd.x());
1632 CursorSlice old = bvcur.top();
1634 // We continue with our existing selection or start a new one, so don't
1635 // reset the anchor.
1636 bvcur.setCursor(cur);
1637 // Did we actually move?
1638 if (cur.top() == old)
1639 // We didn't move one iota, so no need to change selection status
1640 // or update the screen.
1641 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1643 bvcur.setSelection();
1647 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1649 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1651 if (cmd.button() == mouse_button::button1) {
1652 if (!cur.selection())
1653 cur.noScreenUpdate();
1655 Cursor & bvcur = cur.bv().cursor();
1656 bvcur.selection(true);
1665 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1667 // try auto-correction
1668 if (lyxrc.autocorrection_math && cur.pos() != 0
1669 && math_autocorrect(cur, c))
1672 //lyxerr << "interpret 2: '" << c << "'" << endl;
1673 docstring save_selection;
1674 if (c == '^' || c == '_')
1675 save_selection = grabAndEraseSelection(cur);
1678 Buffer * buf = cur.buffer();
1681 if (cur.inMacroMode()) {
1682 docstring name = cur.macroName();
1684 /// are we currently typing '#1' or '#2' or...?
1685 if (name == "\\#") {
1688 if (n >= 1 && n <= 9)
1689 cur.insert(new InsetMathMacroArgument(n));
1693 // do not finish macro for known * commands
1694 bool star_macro = c == '*'
1695 && (in_word_set(name.substr(1) + '*')
1696 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1697 if (isAlphaASCII(c) || star_macro) {
1698 cur.activeMacro()->setName(name + docstring(1, c));
1702 // handle 'special char' macros
1707 if (currentMode() != InsetMath::MATH_MODE)
1708 cur.niceInsert(createInsetMath("textbackslash", buf));
1710 cur.niceInsert(createInsetMath("backslash", buf));
1711 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1713 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1714 } else if (c == '{' || c == '%') {
1715 //using the saved selection as argument
1716 InsetMathUnknown * p = cur.activeMacro();
1718 MathData sel(cur.buffer());
1719 asArray(p->selection(), sel);
1722 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1724 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1725 } else if (c == '#') {
1726 LASSERT(cur.activeMacro(), return false);
1727 cur.activeMacro()->setName(name + docstring(1, c));
1730 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1735 // One character big delimiters. The others are handled in
1736 // interpretString().
1737 latexkeys const * l = in_word_set(name.substr(1));
1738 if (name[0] == '\\' && l && l->inset == "big") {
1742 delim = from_ascii("\\{");
1745 delim = from_ascii("\\}");
1748 delim = docstring(1, c);
1751 if (InsetMathBig::isBigInsetDelim(delim)) {
1752 // name + delim ared a valid InsetMathBig.
1753 // We can't use cur.macroModeClose() because
1754 // it does not handle delim.
1755 InsetMathUnknown * p = cur.activeMacro();
1758 cur.cell().erase(cur.pos());
1759 cur.plainInsert(MathAtom(
1760 new InsetMathBig(name.substr(1), delim)));
1763 } else if (name == "\\smash" && c == '[') {
1764 // We can't use cur.macroModeClose() because
1765 // it would create an InsetMathPhantom
1766 InsetMathUnknown * p = cur.activeMacro();
1768 interpretChar(cur, c);
1772 // leave macro mode and try again if necessary
1773 if (cur.macroModeClose()) {
1774 MathAtom const atom = cur.prevAtom();
1775 if (atom->asNestInset() && atom->isActive()) {
1777 cur.nextInset()->edit(cur, true);
1781 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1783 interpretChar(cur, c);
1788 // just clear selection on pressing the space bar
1789 if (cur.selection() && c == ' ') {
1790 cur.selection(false);
1795 //lyxerr << "starting with macro" << endl;
1796 bool reduced = cap::reduceSelectionToOneCell(cur);
1797 if (reduced || !cur.selection()) {
1798 cur.recordUndoInset();
1799 docstring const safe = cap::grabAndEraseSelection(cur);
1800 if (!cur.inRegexped())
1801 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1803 cur.niceInsert(createInsetMath("backslash", buf));
1811 if (currentMode() != InsetMath::MATH_MODE)
1817 if (currentMode() != InsetMath::MATH_MODE) {
1818 // insert spaces in text or undecided mode,
1819 // but suppress direct insertion of two spaces in a row
1820 // the still allows typing '<space>a<space>' and deleting the 'a', but
1821 // it is better than nothing...
1822 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1824 // FIXME: we have to enable full redraw here because of the
1825 // visual box corners that define the inset. If we know for
1826 // sure that we stay within the same cell we can optimize for
1828 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1832 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1833 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1834 // FIXME: we have to enable full redraw here because of the
1835 // visual box corners that define the inset. If we know for
1836 // sure that we stay within the same cell we can optimize for
1838 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1842 if (cur.popForward()) {
1843 // FIXME: we have to enable full redraw here because of the
1844 // visual box corners that define the inset. If we know for
1845 // sure that we stay within the same cell we can optimize for
1847 //cur.screenUpdateFlags(Update::FitCursor);
1851 // if we are at the very end, leave the formula
1852 return cur.pos() != cur.lastpos();
1855 // These should be treated differently when not in text mode:
1856 if (cur.inRegexped()) {
1859 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1866 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1869 cur.niceInsert(createInsetMath("sim", buf));
1875 } else if (currentMode() != InsetMath::TEXT_MODE) {
1877 cur.recordUndoInset();
1878 script(cur, false, save_selection);
1882 cur.recordUndoInset();
1883 script(cur, true, save_selection);
1887 cur.niceInsert(createInsetMath("sim", buf));
1890 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1891 MathAtom at = createInsetMath("text", buf);
1892 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1899 cur.niceInsert(createInsetMath("textasciicircum", buf));
1903 cur.niceInsert(createInsetMath("textasciitilde", buf));
1908 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1909 c == '%' || c == '_') {
1910 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1914 // no special circumstances, so insert the character without any fuss
1920 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1922 if (str == "\\limits" || str == "\\nolimits") {
1923 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1924 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1927 cur.message(bformat(_("Cannot apply %1$s here."), str));
1931 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1933 if (!cur.empty() && cur.pos() > 0 &&
1934 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1935 if (InsetMathBig::isBigInsetDelim(str)) {
1936 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1937 if (prev[0] == '\\') {
1938 prev = prev.substr(1);
1939 latexkeys const * l = in_word_set(prev);
1940 if (l && l->inset == "big") {
1941 cur.recordUndoSelection();
1942 cur.cell()[cur.pos() - 1] =
1943 MathAtom(new InsetMathBig(prev, str));
1953 bool InsetMathNest::script(Cursor & cur, bool up)
1955 return script(cur, up, docstring());
1959 bool InsetMathNest::script(Cursor & cur, bool up,
1960 docstring const & save_selection)
1962 // Hack to get \^ and \_ working
1963 //lyxerr << "handling script: up: " << up << endl;
1964 if (cur.inMacroMode() && cur.macroName() == "\\") {
1966 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1968 interpretChar(cur, '_');
1972 cur.macroModeClose();
1973 if (asScriptInset() && cur.idx() == 0) {
1974 // we are in a nucleus of a script inset, move to _our_ script
1975 InsetMathScript * inset = asScriptInset();
1976 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1978 cur.idx() = inset->idxOfScript(up);
1980 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1982 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1985 cur.idx() = inset->idxOfScript(up);
1986 cur.pos() = cur.lastpos();
1988 // convert the thing to our left to a scriptinset or create a new
1989 // one if in the very first position of the array
1990 if (cur.pos() == 0) {
1991 //lyxerr << "new scriptinset" << endl;
1992 cur.insert(new InsetMathScript(buffer_, up));
1994 //lyxerr << "converting prev atom " << endl;
1995 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1998 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1999 // See comment in MathParser.cpp for special handling of {}-bases
2005 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
2006 cur.niceInsert(save_selection);
2008 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2013 bool InsetMathNest::completionSupported(Cursor const & cur) const
2015 return cur.inMacroMode();
2019 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2021 return cur.inMacroMode();
2025 bool InsetMathNest::automaticInlineCompletion() const
2027 return lyxrc.completion_inline_math;
2031 bool InsetMathNest::automaticPopupCompletion() const
2033 return lyxrc.completion_popup_math;
2037 CompletionList const *
2038 InsetMathNest::createCompletionList(Cursor const & cur) const
2040 if (!cur.inMacroMode())
2043 return new MathCompletionList(cur);
2047 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2049 if (!cur.inMacroMode())
2052 return cur.activeMacro()->name();
2056 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2059 if (!cur.inMacroMode())
2062 // append completion to active macro
2063 InsetMathUnknown * inset = cur.activeMacro();
2064 inset->setName(inset->name() + s);
2069 // FIXME: this creates duplicates in the completion popup
2070 // which looks ugly. Moreover the changes the list lengths
2071 // which seems to confuse the popup as well.
2072 MathCompletionList::addToFavorites(inset->name());
2074 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2081 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2082 Dimension & dim) const
2084 Inset const * inset = cur.activeMacro();
2088 // get inset dimensions
2089 dim = cur.bv().coordCache().insets().dim(inset);
2090 // FIXME: these 3 are no accurate, but should depend on the font.
2091 // Now the popup jumps down if you enter a char with descent > 0.
2096 Point xy = cur.bv().coordCache().insets().xy(inset);
2102 ////////////////////////////////////////////////////////////////////
2104 MathCompletionList::MathCompletionList(Cursor const & cur)
2106 // fill it with macros from the buffer
2107 MacroNameSet macros;
2108 cur.buffer()->listMacroNames(macros);
2109 MacroNameSet::const_iterator it;
2110 for (it = macros.begin(); it != macros.end(); ++it) {
2111 if (cur.buffer()->getMacro(*it, cur, false))
2112 locals.push_back("\\" + *it);
2114 sort(locals.begin(), locals.end());
2116 if (!globals.empty())
2119 // fill in global macros
2121 MacroTable::globalMacros().getMacroNames(macros, false);
2122 //lyxerr << "Globals completion macros: ";
2123 for (it = macros.begin(); it != macros.end(); ++it) {
2124 //lyxerr << "\\" + *it << " ";
2125 globals.push_back("\\" + *it);
2127 //lyxerr << std::endl;
2129 // fill in global commands
2130 globals.push_back(from_ascii("\\boxed"));
2131 globals.push_back(from_ascii("\\fbox"));
2132 globals.push_back(from_ascii("\\framebox"));
2133 globals.push_back(from_ascii("\\makebox"));
2134 globals.push_back(from_ascii("\\kern"));
2135 globals.push_back(from_ascii("\\xhookrightarrow"));
2136 globals.push_back(from_ascii("\\xhookleftarrow"));
2137 globals.push_back(from_ascii("\\xrightarrow"));
2138 globals.push_back(from_ascii("\\xRightarrow"));
2139 globals.push_back(from_ascii("\\xrightharpoondown"));
2140 globals.push_back(from_ascii("\\xrightharpoonup"));
2141 globals.push_back(from_ascii("\\xrightleftharpoons"));
2142 globals.push_back(from_ascii("\\xleftarrow"));
2143 globals.push_back(from_ascii("\\xLeftarrow"));
2144 globals.push_back(from_ascii("\\xleftharpoondown"));
2145 globals.push_back(from_ascii("\\xleftharpoonup"));
2146 globals.push_back(from_ascii("\\xleftrightarrow"));
2147 globals.push_back(from_ascii("\\xLeftrightarrow"));
2148 globals.push_back(from_ascii("\\xleftrightharpoons"));
2149 globals.push_back(from_ascii("\\xmapsto"));
2150 globals.push_back(from_ascii("\\split"));
2151 globals.push_back(from_ascii("\\gathered"));
2152 globals.push_back(from_ascii("\\aligned"));
2153 globals.push_back(from_ascii("\\alignedat"));
2154 globals.push_back(from_ascii("\\cases"));
2155 globals.push_back(from_ascii("\\substack"));
2156 globals.push_back(from_ascii("\\xymatrix"));
2157 globals.push_back(from_ascii("\\Diagram"));
2158 globals.push_back(from_ascii("\\subarray"));
2159 globals.push_back(from_ascii("\\array"));
2160 globals.push_back(from_ascii("\\sqrt"));
2161 globals.push_back(from_ascii("\\root"));
2162 globals.push_back(from_ascii("\\tabular"));
2163 globals.push_back(from_ascii("\\sideset"));
2164 globals.push_back(from_ascii("\\stackrel"));
2165 globals.push_back(from_ascii("\\stackrelthree"));
2166 globals.push_back(from_ascii("\\binom"));
2167 globals.push_back(from_ascii("\\choose"));
2168 globals.push_back(from_ascii("\\brace"));
2169 globals.push_back(from_ascii("\\brack"));
2170 globals.push_back(from_ascii("\\frac"));
2171 globals.push_back(from_ascii("\\over"));
2172 globals.push_back(from_ascii("\\nicefrac"));
2173 globals.push_back(from_ascii("\\unitfrac"));
2174 globals.push_back(from_ascii("\\unitfracthree"));
2175 globals.push_back(from_ascii("\\unitone"));
2176 globals.push_back(from_ascii("\\unittwo"));
2177 globals.push_back(from_ascii("\\infer"));
2178 globals.push_back(from_ascii("\\atop"));
2179 globals.push_back(from_ascii("\\lefteqn"));
2180 globals.push_back(from_ascii("\\boldsymbol"));
2181 globals.push_back(from_ascii("\\bm"));
2182 globals.push_back(from_ascii("\\color"));
2183 globals.push_back(from_ascii("\\normalcolor"));
2184 globals.push_back(from_ascii("\\textcolor"));
2185 globals.push_back(from_ascii("\\cfrac"));
2186 globals.push_back(from_ascii("\\cfracleft"));
2187 globals.push_back(from_ascii("\\cfracright"));
2188 globals.push_back(from_ascii("\\dfrac"));
2189 globals.push_back(from_ascii("\\tfrac"));
2190 globals.push_back(from_ascii("\\dbinom"));
2191 globals.push_back(from_ascii("\\tbinom"));
2192 globals.push_back(from_ascii("\\hphantom"));
2193 globals.push_back(from_ascii("\\phantom"));
2194 globals.push_back(from_ascii("\\vphantom"));
2195 globals.push_back(from_ascii("\\cancel"));
2196 globals.push_back(from_ascii("\\bcancel"));
2197 globals.push_back(from_ascii("\\xcancel"));
2198 globals.push_back(from_ascii("\\cancelto"));
2199 globals.push_back(from_ascii("\\smash"));
2200 globals.push_back(from_ascii("\\mathclap"));
2201 globals.push_back(from_ascii("\\mathllap"));
2202 globals.push_back(from_ascii("\\mathrlap"));
2203 globals.push_back(from_ascii("\\ensuremath"));
2204 MathWordList const & words = mathedWordList();
2205 MathWordList::const_iterator it2;
2206 //lyxerr << "Globals completion commands: ";
2207 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2208 if (it2->second.inset != "macro" && !it2->second.hidden) {
2209 // macros are already read from MacroTable::globalMacros()
2210 globals.push_back('\\' + it2->first);
2211 //lyxerr << '\\' + it2->first << ' ';
2214 //lyxerr << std::endl;
2215 sort(globals.begin(), globals.end());
2219 MathCompletionList::~MathCompletionList()
2224 size_type MathCompletionList::size() const
2226 return locals.size() + globals.size();
2230 docstring const & MathCompletionList::data(size_t idx) const
2232 size_t lsize = locals.size();
2234 return globals[idx - lsize];
2240 std::string MathCompletionList::icon(size_t idx) const
2242 // get the latex command
2244 size_t lsize = locals.size();
2246 cmd = globals[idx - lsize];
2250 // get the icon name by stripping the backslash
2251 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2252 if (icon_name.empty())
2253 return std::string();
2254 return "math/" + to_utf8(icon_name);
2257 std::vector<docstring> MathCompletionList::globals;