2 * \file InsetMathNest.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathNest.h"
15 #include "InsetMathArray.h"
16 #include "InsetMathAMSArray.h"
17 #include "InsetMathBig.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathBrace.h"
20 #include "InsetMathChar.h"
21 #include "InsetMathColor.h"
22 #include "InsetMathComment.h"
23 #include "InsetMathDelim.h"
24 #include "InsetMathEnsureMath.h"
25 #include "InsetMathHull.h"
26 #include "InsetMathRef.h"
27 #include "InsetMathScript.h"
28 #include "InsetMathSpace.h"
29 #include "InsetMathSymbol.h"
30 #include "InsetMathUnknown.h"
31 #include "MathAutoCorrect.h"
32 #include "MathCompletionList.h"
33 #include "MathFactory.h"
34 #include "InsetMathMacro.h"
35 #include "InsetMathMacroArgument.h"
36 #include "MathParser.h"
37 #include "MathStream.h"
38 #include "MathSupport.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
43 #include "CoordCache.h"
45 #include "CutAndPaste.h"
46 #include "DispatchResult.h"
48 #include "FuncRequest.h"
49 #include "FuncStatus.h"
50 #include "LaTeXFeatures.h"
53 #include "MetricsInfo.h"
57 #include "frontends/Application.h"
58 #include "frontends/Clipboard.h"
59 #include "frontends/Painter.h"
60 #include "frontends/Selection.h"
62 #include "support/debug.h"
63 #include "support/docstream.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
73 using namespace lyx::support;
77 using cap::copySelection;
78 using cap::grabAndEraseSelection;
79 using cap::cutSelection;
80 using cap::replaceSelection;
81 using cap::selClearOrDel;
84 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
85 : InsetMath(buf), cells_(nargs), lock_(false)
87 // FIXME This should not really be necessary, but when we are
88 // initializing the table of global macros, we create macros
89 // with no associated Buffer.
95 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
96 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
100 InsetMathNest::~InsetMathNest()
102 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
103 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
104 for (; it != end; ++it)
106 it->first->clearLastInset(this);
110 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
112 cells_ = inset.cells_;
114 mouse_hover_.clear();
115 InsetMath::operator=(inset);
120 void InsetMathNest::setBuffer(Buffer & buffer)
122 InsetMath::setBuffer(buffer);
123 for (MathData & data : cells_)
124 data.setBuffer(buffer);
128 idx_type InsetMathNest::nargs() const
130 return cells_.size();
134 void InsetMathNest::cursorPos(BufferView const & bv,
135 CursorSlice const & sl, bool /*boundary*/,
136 int & x, int & y) const
138 // FIXME: This is a hack. Ideally, the coord cache should not store
139 // absolute positions, but relative ones. This would mean to call
140 // setXY() not in MathData::draw(), but in the parent insets' draw()
141 // with the correctly adjusted x,y values. But this means that we'd have
142 // to touch all (math)inset's draw() methods. Right now, we'll store
143 // absolute value, and make them here relative, only to make them
144 // absolute again when actually drawing the cursor. What a mess.
145 LASSERT(&sl.inset() == this, return);
146 MathData const & ar = sl.cell();
147 CoordCache const & coord_cache = bv.coordCache();
148 if (!coord_cache.getArrays().has(&ar)) {
149 // this can (semi-)legally happen if we just created this cell
150 // and it never has been drawn before. So don't ASSERT.
151 //lyxerr << "no cached data for array " << &ar << endl;
156 Point const pt = coord_cache.getArrays().xy(&ar);
157 if (!coord_cache.getInsets().has(this)) {
159 //lyxerr << "no cached data for inset " << this << endl;
164 Point const pt2 = coord_cache.getInsets().xy(this);
165 //lyxerr << "retrieving position cache for MathData "
166 // << pt.x_ << ' ' << pt.y_ << endl;
167 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
169 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
170 // << " asc: " << ascent() << " des: " << descent()
171 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
172 // move cursor visually into empty cells ("blue rectangles");
174 Dimension const dim = coord_cache.getArrays().dim(&ar);
180 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
183 for (auto const & cell : cells_) {
185 cell.metrics(m, dim);
190 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
192 for (idx_type i = 0, n = nargs(); i != n; ++i)
193 cell(i).updateBuffer(it, utype, deleted);
198 bool InsetMathNest::idxNext(Cursor & cur) const
200 LASSERT(&cur.inset() == this, return false);
201 if (cur.idx() == cur.lastidx())
209 bool InsetMathNest::idxForward(Cursor & cur) const
215 bool InsetMathNest::idxPrev(Cursor & cur) const
217 LASSERT(&cur.inset() == this, return false);
221 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
226 bool InsetMathNest::idxBackward(Cursor & cur) const
232 bool InsetMathNest::idxFirst(Cursor & cur) const
234 LASSERT(&cur.inset() == this, return false);
237 cur.idx() = firstIdx();
243 bool InsetMathNest::idxLast(Cursor & cur) const
245 LASSERT(&cur.inset() == this, return false);
248 cur.idx() = lastIdx();
249 cur.pos() = cur.lastpos();
254 void InsetMathNest::dump() const
256 odocstringstream oss;
257 otexrowstream ots(oss);
258 TeXMathStream os(ots);
259 os << "---------------------------------------------\n";
262 for (idx_type i = 0, n = nargs(); i != n; ++i)
263 os << cell(i) << "\n";
264 os << "---------------------------------------------\n";
265 lyxerr << to_utf8(oss.str());
269 void InsetMathNest::draw(PainterInfo &, int, int) const
273 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
279 void InsetMathNest::validate(LaTeXFeatures & features) const
281 for (idx_type i = 0; i < nargs(); ++i)
282 cell(i).validate(features);
286 void InsetMathNest::replace(ReplaceData & rep)
288 for (idx_type i = 0; i < nargs(); ++i)
289 cell(i).replace(rep);
293 bool InsetMathNest::contains(MathData const & ar) const
295 for (idx_type i = 0; i < nargs(); ++i)
296 if (cell(i).contains(ar))
302 bool InsetMathNest::lock() const
308 void InsetMathNest::lock(bool l)
314 bool InsetMathNest::isActive() const
320 MathData InsetMathNest::glue() const
323 for (size_t i = 0; i < nargs(); ++i)
329 void InsetMathNest::write(TeXMathStream & os) const
331 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
332 ModeSpecifier specifier(os, currentMode(), lockedMode());
333 docstring const latex_name = name();
334 os << '\\' << latex_name;
335 os.inMathClass(asClassInset());
336 for (size_t i = 0; i < nargs(); ++i) {
337 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
338 os << '{' << cell(i) << '}';
341 os.pendingSpace(true);
342 if (lock_ && !os.latex()) {
344 os.pendingSpace(true);
346 os.inMathClass(false);
350 void InsetMathNest::normalize(NormalStream & os) const
353 for (size_t i = 0; i < nargs(); ++i)
354 os << ' ' << cell(i);
359 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
361 TeXMathStream::OutputType ot;
362 if (runparams.for_search != OutputParams::NoSearch)
363 ot = TeXMathStream::wsSearchAdv;
364 else if (runparams.dryrun)
365 ot = TeXMathStream::wsDryrun;
367 ot = TeXMathStream::wsDefault;
368 TeXMathStream wi(os, runparams.moving_arg, true, ot,
370 wi.strikeoutMath(runparams.inDeletedInset);
371 if (runparams.inulemcmd) {
372 wi.ulemCmd(TeXMathStream::UNDERLINE);
373 if (runparams.local_font) {
374 FontInfo f = runparams.local_font->fontInfo();
375 if (f.strikeout() == FONT_ON)
376 wi.ulemCmd(TeXMathStream::STRIKEOUT);
379 wi.canBreakLine(os.canBreakLine());
380 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
383 // Reset parbreak and command termination status after a math inset.
385 os.canBreakLine(wi.canBreakLine());
386 os.terminateCommand(false);
390 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
393 mouse_hover_[bv] = mouse_hover;
398 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
402 MathData & ar = cur.cell();
403 // remove base-only "scripts"
404 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
405 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
406 if (p && p->nargs() == 1) {
407 MathData ar = p->nuc();
410 cur.adjust(i, ar.size() - 1);
414 // glue adjacent font insets of the same kind
415 for (pos_type i = 0; i + 1 < size(); ++i) {
416 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
417 InsetMathFont const * q = operator[](i + 1)->asFontInset();
418 if (p && q && p->name() == q->name()) {
419 p->cell(0).append(q->cell(0));
429 void InsetMathNest::handleFont
430 (Cursor & cur, docstring const & arg, char const * const font)
432 handleFont(cur, arg, from_ascii(font));
436 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
437 docstring const & font)
439 cur.recordUndoSelection();
441 // this whole function is a hack and won't work for incremental font
443 if (cur.inset().asInsetMath()->name() == font)
444 cur.handleFont(to_utf8(font));
446 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
450 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
452 handleNest(cur, nest, docstring());
456 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
457 docstring const & arg)
459 DocIterator const i1 = cur.selectionBegin();
460 DocIterator const i2 = cur.selectionEnd();
461 if (!i1.inset().asInsetMath())
463 if (i1.idx() == i2.idx()) {
464 // the easy case where only one cell is selected
465 cur.handleNest(nest);
470 // multiple selected cells in a simple non-grid inset
471 if (i1.inset().nrows() == 0 || i1.inset().ncols() == 0) {
472 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
478 cur.pos() = cur.lastpos();
482 cur.handleNest(nest);
488 // the complicated case with multiple selected cells in a grid
491 cap::region(i1.top(), i2.top(), r1, r2, c1, c2);
492 for (row_type row = r1; row <= r2; ++row) {
493 for (col_type col = c1; col <= c2; ++col) {
496 cur.idx() = i1.inset().index(row, col);
499 cur.pos() = cur.lastpos();
503 cur.handleNest(nest);
510 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
512 cur.recordUndoSelection();
515 font.fromString(to_utf8(arg), b);
516 if (font.fontInfo().color() != Color_inherit &&
517 font.fontInfo().color() != Color_ignore)
518 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
520 // FIXME: support other font changes here as well?
523 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
525 //LYXERR0("InsetMathNest: request: " << cmd);
527 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
529 FuncCode const act = cmd.action();
532 case LFUN_CLIPBOARD_PASTE:
533 parseflg |= Parse::VERBATIM;
536 if (cur.currentMode() != MATH_MODE)
537 parseflg |= Parse::TEXTMODE;
538 cur.recordUndoSelection();
539 cur.message(_("Paste"));
540 replaceSelection(cur);
542 if (cmd.argument().empty() && !theClipboard().isInternal())
543 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
546 idocstringstream is(cmd.argument());
548 topaste = cap::selection(n, make_pair(buffer().params().documentClassPtr(),
549 buffer().params().authors()));
551 cur.niceInsert(topaste, parseflg, false);
552 cur.clearSelection(); // bug 393
553 cur.forceBufferUpdate();
560 cutSelection(cur, true);
561 cur.message(_("Cut"));
562 // Prevent stale position >= size crash
563 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
565 cur.forceBufferUpdate();
568 case LFUN_MOUSE_PRESS:
569 lfunMousePress(cur, cmd);
572 case LFUN_MOUSE_MOTION:
573 lfunMouseMotion(cur, cmd);
576 case LFUN_MOUSE_RELEASE:
577 lfunMouseRelease(cur, cmd);
580 case LFUN_FINISHED_LEFT: // in math, left is backwards
581 case LFUN_FINISHED_BACKWARD:
582 cur.bv().cursor() = cur;
585 case LFUN_FINISHED_RIGHT: // in math, right is forward
586 case LFUN_FINISHED_FORWARD:
588 cur.bv().cursor() = cur;
591 case LFUN_WORD_RIGHT:
593 case LFUN_WORD_BACKWARD:
594 case LFUN_WORD_FORWARD:
595 case LFUN_CHAR_RIGHT:
597 case LFUN_CHAR_BACKWARD:
598 case LFUN_CHAR_FORWARD:
599 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
601 case LFUN_WORD_RIGHT_SELECT:
602 case LFUN_WORD_LEFT_SELECT:
603 case LFUN_WORD_BACKWARD_SELECT:
604 case LFUN_WORD_FORWARD_SELECT:
605 case LFUN_CHAR_RIGHT_SELECT:
606 case LFUN_CHAR_LEFT_SELECT:
607 case LFUN_CHAR_BACKWARD_SELECT:
608 case LFUN_CHAR_FORWARD_SELECT: {
609 // are we in a selection?
610 bool select = (act == LFUN_WORD_RIGHT_SELECT
611 || act == LFUN_WORD_LEFT_SELECT
612 || act == LFUN_WORD_BACKWARD_SELECT
613 || act == LFUN_WORD_FORWARD_SELECT
614 || act == LFUN_CHAR_RIGHT_SELECT
615 || act == LFUN_CHAR_LEFT_SELECT
616 || act == LFUN_CHAR_BACKWARD_SELECT
617 || act == LFUN_CHAR_FORWARD_SELECT);
619 bool word = (act == LFUN_WORD_RIGHT_SELECT
620 || act == LFUN_WORD_LEFT_SELECT
621 || act == LFUN_WORD_BACKWARD_SELECT
622 || act == LFUN_WORD_FORWARD_SELECT
623 || act == LFUN_WORD_RIGHT
624 || act == LFUN_WORD_LEFT
625 || act == LFUN_WORD_BACKWARD
626 || act == LFUN_WORD_FORWARD);
627 // are we moving forward or backwards?
628 // If the command was RIGHT or LEFT, then whether we're moving forward
629 // or backwards depends on the cursor movement mode (logical or visual):
630 // * in visual mode, since math is always LTR, right -> forward,
632 // * in logical mode, the mapping is determined by the
633 // reverseDirectionNeeded() function
636 FuncCode finish_lfun;
638 if (act == LFUN_CHAR_FORWARD
639 || act == LFUN_CHAR_FORWARD_SELECT
640 || act == LFUN_WORD_FORWARD
641 || act == LFUN_WORD_FORWARD_SELECT) {
643 finish_lfun = LFUN_FINISHED_FORWARD;
645 else if (act == LFUN_CHAR_BACKWARD
646 || act == LFUN_CHAR_BACKWARD_SELECT
647 || act == LFUN_WORD_BACKWARD
648 || act == LFUN_WORD_BACKWARD_SELECT) {
650 finish_lfun = LFUN_FINISHED_BACKWARD;
653 bool right = (act == LFUN_CHAR_RIGHT_SELECT
654 || act == LFUN_CHAR_RIGHT
655 || act == LFUN_WORD_RIGHT_SELECT
656 || act == LFUN_WORD_RIGHT);
657 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
663 finish_lfun = LFUN_FINISHED_RIGHT;
665 finish_lfun = LFUN_FINISHED_LEFT;
667 // Now that we know exactly what we want to do, let's do it!
668 cur.selHandle(select);
670 cur.macroModeClose();
671 // try moving forward or backwards as necessary...
672 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
673 // ... and if movement failed, then finish forward or backwards
675 cmd = FuncRequest(finish_lfun);
683 case LFUN_PARAGRAPH_UP:
684 case LFUN_PARAGRAPH_DOWN:
685 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
687 case LFUN_DOWN_SELECT:
689 case LFUN_PARAGRAPH_UP_SELECT:
690 case LFUN_PARAGRAPH_DOWN_SELECT: {
691 // close active macro
692 if (cur.inMacroMode()) {
693 cur.macroModeClose();
697 // stop/start the selection
698 bool select = act == LFUN_DOWN_SELECT
699 || act == LFUN_UP_SELECT
700 || act == LFUN_PARAGRAPH_DOWN_SELECT
701 || act == LFUN_PARAGRAPH_UP_SELECT;
702 cur.selHandle(select);
705 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
706 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
707 bool successful = cur.upDownInMath(up);
711 if (cur.fixIfBroken())
712 // FIXME: Something bad happened. We pass the corrected Cursor
713 // instead of letting things go worse.
716 // We did not manage to move the cursor.
721 case LFUN_MOUSE_DOUBLE:
722 case LFUN_WORD_SELECT:
724 cur.bv().mouseSetCursor(cur);
725 cur.pos() = cur.lastpos();
726 cur.bv().mouseSetCursor(cur, true);
729 case LFUN_MOUSE_TRIPLE:
732 cur.bv().mouseSetCursor(cur);
733 cur.idx() = cur.lastidx();
734 cur.pos() = cur.lastpos();
735 cur.bv().mouseSetCursor(cur, true);
738 case LFUN_LINE_BEGIN:
739 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
741 case LFUN_LINE_BEGIN_SELECT:
742 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
743 act == LFUN_WORD_LEFT_SELECT ||
744 act == LFUN_LINE_BEGIN_SELECT);
745 cur.macroModeClose();
746 if (cur.pos() != 0) {
748 } else if (cur.col() != 0) {
749 cur.idx() -= cur.col();
751 } else if (cur.idx() != 0) {
755 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
761 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
763 case LFUN_LINE_END_SELECT:
764 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
765 act == LFUN_WORD_RIGHT_SELECT ||
766 act == LFUN_LINE_END_SELECT);
767 cur.macroModeClose();
769 if (cur.pos() != cur.lastpos()) {
770 cur.pos() = cur.lastpos();
771 } else if (ncols() && (cur.col() != cur.lastcol())) {
772 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
773 cur.pos() = cur.lastpos();
774 } else if (cur.idx() != cur.lastidx()) {
775 cur.idx() = cur.lastidx();
776 cur.pos() = cur.lastpos();
778 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
783 case LFUN_CELL_FORWARD:
784 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
785 cur.selHandle(false);
787 cur.macroModeClose();
788 if (!cur.inset().idxNext(cur)) {
789 if (cur.lastidx() == 0)
792 cur.idx() = firstIdx();
798 case LFUN_CELL_BACKWARD:
799 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
800 cur.selHandle(false);
802 cur.macroModeClose();
803 if (!cur.inset().idxPrev(cur)) {
804 if (cur.lastidx() == 0)
807 cur.idx() = cur.lastidx();
808 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
813 case LFUN_WORD_DELETE_BACKWARD:
814 case LFUN_CHAR_DELETE_BACKWARD:
816 // May affect external cell:
817 cur.recordUndoInset();
818 else if (!cur.inMacroMode())
819 cur.recordUndoSelection();
820 // if the inset can not be removed from within, delete it
821 if (!cur.backspace(cmd.getArg(0) == "force")) {
822 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
823 cur.innerText()->dispatch(cur, newcmd);
827 case LFUN_WORD_DELETE_FORWARD:
828 case LFUN_CHAR_DELETE_FORWARD:
829 if (cur.pos() == cur.lastpos())
830 // May affect external cell:
831 cur.recordUndoInset();
833 cur.recordUndoSelection();
834 // if the inset can not be removed from within, delete it
835 if (!cur.erase(cmd.getArg(0) == "force")) {
836 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
837 cur.innerText()->dispatch(cur, newcmd);
843 cur.clearSelection();
845 if (cur.inMacroMode())
846 cur.macroModeClose(true);
848 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
854 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
855 // that is traversed by a single <CursorLeft>/<CursorRight>.
856 case LFUN_INSET_TOGGLE:
862 case LFUN_SELF_INSERT:
863 // special case first for big delimiters
864 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
867 for (char_type c : cmd.argument()) {
868 // Don't record undo steps if we are in macro mode and thus
869 // cmd.argument is the next character of the macro name.
870 // Otherwise we'll get an invalid cursor if we undo after
871 // the macro was finished and the macro is a known command,
872 // e.g. sqrt. Cursor::macroModeClose replaces in this case
873 // the InsetMathUnknown with name "frac" by an empty
874 // InsetMathFrac -> a pos value > 0 is invalid.
875 // A side effect is that an undo before the macro is finished
876 // undoes the complete macro, not only the last character.
877 // At the time we hit '\' we are not in macro mode, still.
878 if (!cur.inMacroMode())
879 cur.recordUndoSelection();
881 // special handling of space. If we insert an inset
882 // via macro mode, we want to put the cursor inside it
883 // if relevant. Think typing "\frac<space>".
885 && cur.inMacroMode() && cur.macroName() != "\\"
886 && cur.macroModeClose() && cur.pos() > 0)
887 cur.editInsertedInset();
888 else if (!interpretChar(cur, c)) {
889 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
891 // FIXME: can we avoid skipping the end of the string?
897 //case LFUN_SERVER_GET_XY:
900 case LFUN_SERVER_SET_XY: {
901 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
904 istringstream is(to_utf8(cmd.argument()));
910 // Special casing for superscript in case of LyX handling
912 case LFUN_ACCENT_CIRCUMFLEX:
913 if (cmd.argument().empty()) {
914 // do superscript if LyX handles
916 cur.recordUndoInset();
917 script(cur, true, grabAndEraseSelection(cur));
921 case LFUN_ACCENT_UMLAUT:
922 case LFUN_ACCENT_ACUTE:
923 case LFUN_ACCENT_GRAVE:
924 case LFUN_ACCENT_BREVE:
925 case LFUN_ACCENT_DOT:
926 case LFUN_ACCENT_MACRON:
927 case LFUN_ACCENT_CARON:
928 case LFUN_ACCENT_TILDE:
929 case LFUN_ACCENT_CEDILLA:
930 case LFUN_ACCENT_CIRCLE:
931 case LFUN_ACCENT_UNDERDOT:
932 case LFUN_ACCENT_TIE:
933 case LFUN_ACCENT_OGONEK:
934 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
938 case LFUN_TEXTSTYLE_APPLY:
939 case LFUN_TEXTSTYLE_UPDATE:
940 handleFont2(cur, cmd.argument());
944 if (currentMode() != MATH_MODE)
945 handleFont(cur, cmd.argument(), "textbf");
947 handleFont(cur, cmd.argument(), "mathbf");
949 case LFUN_FONT_BOLDSYMBOL:
950 if (currentMode() != MATH_MODE)
951 handleFont(cur, cmd.argument(), "textbf");
953 handleFont(cur, cmd.argument(), "boldsymbol");
956 if (currentMode() != MATH_MODE)
957 handleFont(cur, cmd.argument(), "textsf");
959 handleFont(cur, cmd.argument(), "mathsf");
962 if (currentMode() != MATH_MODE)
963 handleFont(cur, cmd.argument(), "emph");
965 handleFont(cur, cmd.argument(), "mathcal");
967 case LFUN_FONT_ROMAN:
968 if (currentMode() != MATH_MODE)
969 handleFont(cur, cmd.argument(), "textrm");
971 handleFont(cur, cmd.argument(), "mathrm");
973 case LFUN_FONT_TYPEWRITER:
974 if (currentMode() != MATH_MODE)
975 handleFont(cur, cmd.argument(), "texttt");
977 handleFont(cur, cmd.argument(), "mathtt");
980 handleFont(cur, cmd.argument(), "mathfrak");
983 if (currentMode() != MATH_MODE)
984 handleFont(cur, cmd.argument(), "textit");
986 handleFont(cur, cmd.argument(), "mathit");
989 if (currentMode() != MATH_MODE)
990 // FIXME: should be "noun"
991 handleFont(cur, cmd.argument(), "textsc");
993 handleFont(cur, cmd.argument(), "mathbb");
995 case LFUN_FONT_DEFAULT:
996 handleFont(cur, cmd.argument(), "textnormal");
998 case LFUN_FONT_UNDERLINE:
1000 cur.handleNest(createInsetMath("underline", cur.buffer()));
1003 case LFUN_MATH_MODE: {
1005 // ignore math-mode on when already in math mode
1006 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1008 cur.recordUndoSelection();
1009 cur.macroModeClose();
1010 docstring const save_selection = grabAndEraseSelection(cur);
1012 if (currentMode() != Inset::MATH_MODE)
1013 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1015 cur.plainInsert(createInsetMath("text", buffer_));
1017 cur.pushBackward(*cur.nextInset());
1018 cur.niceInsert(save_selection);
1019 cur.forceBufferUpdate();
1021 if (currentMode() == Inset::TEXT_MODE) {
1022 cur.recordUndoSelection();
1023 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1024 cur.message(_("create new math text environment ($...$)"));
1026 handleFont(cur, cmd.argument(), "textrm");
1027 cur.message(_("entered math text mode (textrm)"));
1033 case LFUN_REGEXP_MODE: {
1034 InsetMath * im = cur.inset().asInsetMath();
1036 InsetMathHull * i = im->asHullInset();
1037 if (i && i->getType() == hullRegexp) {
1038 cur.message(_("Already in regular expression mode"));
1042 cur.macroModeClose();
1043 docstring const save_selection = grabAndEraseSelection(cur);
1045 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1047 cur.pushBackward(*cur.nextInset());
1048 cur.niceInsert(save_selection);
1049 cur.message(_("Regular expression editor mode"));
1053 case LFUN_MATH_FONT_STYLE: {
1054 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1055 doDispatch(cur, fr);
1059 case LFUN_MATH_SIZE: {
1060 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1061 doDispatch(cur, fr);
1065 case LFUN_MATH_MATRIX: {
1071 idocstringstream is(cmd.argument());
1072 is >> m >> n >> v_align >> h_align;
1078 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1079 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1083 case LFUN_MATH_AMS_MATRIX: {
1087 docstring name = from_ascii("matrix");
1088 idocstringstream is(cmd.argument());
1089 is >> m >> n >> name;
1094 // check if we have a valid decoration
1095 if (name != "pmatrix" && name != "bmatrix"
1096 && name != "Bmatrix" && name != "vmatrix"
1097 && name != "Vmatrix" && name != "matrix"
1098 && name != "smallmatrix")
1099 name = from_ascii("matrix");
1102 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1106 case LFUN_MATH_DELIM: {
1108 docstring rs = split(cmd.argument(), ls, ' ');
1109 // Reasonable default values
1115 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1119 case LFUN_MATH_BIGDELIM: {
1120 docstring const lname = from_utf8(cmd.getArg(0));
1121 docstring const ldelim = from_utf8(cmd.getArg(1));
1122 docstring const rname = from_utf8(cmd.getArg(2));
1123 docstring const rdelim = from_utf8(cmd.getArg(3));
1124 latexkeys const * l = in_word_set(lname);
1125 bool const have_l = l && l->inset == "big" &&
1126 InsetMathBig::isBigInsetDelim(ldelim);
1127 l = in_word_set(rname);
1128 bool const have_r = l && l->inset == "big" &&
1129 InsetMathBig::isBigInsetDelim(rdelim);
1130 // We mimic LFUN_MATH_DELIM in case we have an empty left
1131 // or right delimiter.
1132 if (have_l || have_r) {
1134 docstring const selection = grabAndEraseSelection(cur);
1137 cur.insert(MathAtom(new InsetMathBig(lname,
1139 // first insert the right delimiter and then go back
1140 // and re-insert the selection (bug 7088)
1142 cur.insert(MathAtom(new InsetMathBig(rname,
1146 cur.niceInsert(selection);
1148 // Don't call cur.undispatched() if we did nothing, this would
1149 // lead to infinite recursion via Text::dispatch().
1153 case LFUN_SPACE_INSERT: {
1154 cur.recordUndoSelection();
1155 string const name = cmd.getArg(0);
1156 if (name == "normal")
1157 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1158 else if (name == "protected")
1159 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1160 else if (name == "thin" || name == "med" || name == "thick")
1161 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1162 else if (name == "hfill*")
1163 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1164 else if (name == "quad" || name == "qquad" ||
1165 name == "enspace" || name == "enskip" ||
1166 name == "negthinspace" || name == "negmedspace" ||
1167 name == "negthickspace" || name == "hfill")
1168 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1169 else if (name == "hspace" || name == "hspace*") {
1170 string const len = cmd.getArg(1);
1171 if (len.empty() || !isValidLength(len)) {
1172 lyxerr << "LyX function 'space-insert " << name << "' "
1173 "needs a valid length argument." << endl;
1176 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1178 cur.insert(MathAtom(new InsetMathSpace));
1182 case LFUN_MATH_SPACE:
1183 cur.recordUndoSelection();
1184 if (cmd.argument().empty())
1185 cur.insert(MathAtom(new InsetMathSpace));
1187 string const name = cmd.getArg(0);
1188 string const len = cmd.getArg(1);
1189 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1193 case LFUN_ERT_INSERT:
1194 // interpret this as if a backslash was typed
1196 interpretChar(cur, '\\');
1199 case LFUN_MATH_SUBSCRIPT:
1200 // interpret this as if a _ was typed
1201 cur.recordUndoSelection();
1202 interpretChar(cur, '_');
1205 case LFUN_MATH_SUPERSCRIPT:
1206 // interpret this as if a ^ was typed
1207 cur.recordUndoSelection();
1208 interpretChar(cur, '^');
1211 case LFUN_MATH_MACRO_FOLD:
1212 case LFUN_MATH_MACRO_UNFOLD: {
1214 bool fold = act == LFUN_MATH_MACRO_FOLD;
1215 bool found = findMacroToFoldUnfold(it, fold);
1217 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1218 cur.recordUndoInset();
1227 case LFUN_QUOTE_INSERT:
1228 // interpret this as if a straight " was typed
1229 cur.recordUndoSelection();
1230 interpretChar(cur, '\"');
1233 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1234 // handling such that "self-insert" works on "arbitrary stuff" too, and
1235 // math-insert only handles special math things like "matrix".
1236 case LFUN_MATH_INSERT: {
1237 cur.recordUndoSelection();
1238 if (cmd.argument() == "^" || cmd.argument() == "_")
1239 interpretChar(cur, cmd.argument()[0]);
1240 else if (!cur.selection())
1241 cur.niceInsert(cmd.argument());
1243 MathData ar(cur.buffer());
1244 asArray(cmd.argument(), ar);
1246 && ar[0]->asNestInset()
1247 && ar[0]->asNestInset()->nargs() > 1)
1248 handleNest(cur, ar[0]);
1250 cur.niceInsert(cmd.argument());
1255 case LFUN_DIALOG_SHOW_NEW_INSET: {
1256 docstring const & name = cmd.argument();
1258 if (name == "ref") {
1259 InsetMathRef tmp(buffer_, name);
1260 data = tmp.createDialogStr();
1261 cur.bv().showDialog(to_utf8(name), data);
1262 } else if (name == "mathspace") {
1263 cur.bv().showDialog(to_utf8(name));
1268 case LFUN_INSET_INSERT: {
1270 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1271 cur.recordUndoSelection();
1273 cur.forceBufferUpdate();
1278 case LFUN_INSET_DISSOLVE:
1279 if (!asHullInset()) {
1280 cur.recordUndoInset();
1285 case LFUN_MATH_LIMITS: {
1287 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1288 in = &cur.nextMath();
1289 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1290 in = &cur.prevMath();
1291 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1292 in = cur.cell().back().nucleus();
1293 // only when nucleus allows this
1296 cur.recordUndoInset();
1297 if (!cmd.argument().empty()) {
1298 if (cmd.argument() == "limits")
1300 else if (cmd.argument() == "nolimits")
1301 in->limits(NO_LIMITS);
1303 in->limits(AUTO_LIMITS);
1304 } else if (in->limits() != AUTO_LIMITS)
1305 in->limits(AUTO_LIMITS);
1306 else if (in->defaultLimits(cur.cell().displayStyle()) == LIMITS)
1307 in->limits(NO_LIMITS);
1313 case LFUN_PHANTOM_INSERT: {
1314 docstring const & arg = cmd.argument();
1316 if (arg == "Phantom")
1317 newarg = from_ascii("\\phantom");
1318 else if (arg == "HPhantom")
1319 newarg = from_ascii("\\hphantom");
1320 else if (arg == "VPhantom")
1321 newarg = from_ascii("\\vphantom");
1323 LYXERR0("Unknown phantom type " + newarg);
1325 FuncRequest const newfunc(LFUN_MATH_INSERT, newarg);
1326 lyx::dispatch(newfunc);
1332 InsetMath::doDispatch(cur, cmd);
1338 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1339 // look for macro to open/close, but stay in mathed
1340 for (; !it.empty(); it.pop_back()) {
1342 // go backward through the current cell
1343 Inset * inset = it.nextInset();
1344 while (inset && inset->asInsetMath()) {
1345 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1347 // found the an macro to open/close?
1348 if (macro->folded() != fold)
1351 // Wrong folding state.
1352 // If this was the first we see in this slice, look further left,
1354 if (inset != it.nextInset())
1358 // go up if this was the left most position
1364 inset = it.nextInset();
1372 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1373 FuncStatus & flag) const
1375 // the font related toggles
1376 //string tc = "mathnormal";
1378 string const arg = to_utf8(cmd.argument());
1379 switch (cmd.action()) {
1381 case LFUN_INSET_MODIFY:
1382 // FIXME: check temporarily disabled
1384 char align = mathcursor::valign();
1385 if (align == '\0') {
1389 if (cmd.argument().empty()) {
1393 if (!contains("tcb", cmd.argument()[0])) {
1397 flag.setOnOff(cmd.argument()[0] == align);
1400 /// We have to handle them since 1.4 blocks all unhandled actions
1401 case LFUN_FONT_ITAL:
1402 case LFUN_FONT_BOLD:
1403 case LFUN_FONT_BOLDSYMBOL:
1404 case LFUN_FONT_SANS:
1405 case LFUN_FONT_EMPH:
1406 case LFUN_FONT_TYPEWRITER:
1407 case LFUN_FONT_NOUN:
1408 case LFUN_FONT_ROMAN:
1409 case LFUN_FONT_DEFAULT:
1410 flag.setEnabled(true);
1413 // we just need to be in math mode to enable that
1414 case LFUN_MATH_SIZE:
1415 case LFUN_MATH_SPACE:
1416 case LFUN_MATH_EXTERN:
1417 flag.setEnabled(true);
1420 case LFUN_FONT_UNDERLINE:
1421 case LFUN_FONT_FRAK:
1422 flag.setEnabled(currentMode() != TEXT_MODE);
1425 case LFUN_MATH_FONT_STYLE: {
1426 bool const textarg =
1427 arg == "textbf" || arg == "textsf" ||
1428 arg == "textrm" || arg == "textmd" ||
1429 arg == "textit" || arg == "textsc" ||
1430 arg == "textsl" || arg == "textup" ||
1431 arg == "texttt" || arg == "textbb" ||
1432 arg == "textnormal";
1433 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1437 case LFUN_MATH_MODE:
1438 // forbid "math-mode on" in math mode to prevent irritating
1439 // behaviour of menu entries (bug 6709)
1440 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1443 case LFUN_MATH_INSERT:
1444 flag.setEnabled(currentMode() != TEXT_MODE);
1447 case LFUN_MATH_AMS_MATRIX:
1448 case LFUN_MATH_MATRIX:
1449 flag.setEnabled(currentMode() == MATH_MODE);
1452 case LFUN_INSET_INSERT: {
1453 // Don't test createMathInset_fromDialogStr(), since
1454 // getStatus is not called with a valid reference and the
1455 // dialog would not be applicable.
1456 string const name = cmd.getArg(0);
1457 flag.setEnabled(name == "ref" || name == "mathspace");
1461 case LFUN_DIALOG_SHOW_NEW_INSET: {
1462 docstring const & name = cmd.argument();
1463 if (name == "space")
1464 flag.setEnabled(false);
1469 case LFUN_MATH_DELIM:
1470 case LFUN_MATH_BIGDELIM:
1471 // Don't do this with multi-cell selections
1472 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1475 case LFUN_MATH_MACRO_FOLD:
1476 case LFUN_MATH_MACRO_UNFOLD: {
1478 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1479 flag.setEnabled(found);
1483 case LFUN_SPECIALCHAR_INSERT:
1484 case LFUN_SCRIPT_INSERT:
1485 // FIXME: These would probably make sense in math-text mode
1486 flag.setEnabled(false);
1489 case LFUN_CAPTION_INSERT:
1490 flag.setEnabled(false);
1493 case LFUN_SPACE_INSERT: {
1494 docstring const & name = cmd.argument();
1495 if (name == "visible")
1496 flag.setEnabled(false);
1500 case LFUN_INSET_DISSOLVE:
1501 flag.setEnabled(!asHullInset());
1505 docstring const & name = cmd.argument();
1506 if (name == "html" || name == "latex")
1507 flag.setEnabled(false);
1511 case LFUN_MATH_LIMITS: {
1513 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1514 in = &cur.nextMath();
1515 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1516 in = &cur.prevMath();
1517 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1518 in = cur.cell().back().nucleus();
1520 if (!cmd.argument().empty()) {
1521 if (cmd.argument() == "limits")
1522 flag.setOnOff(in->limits() == LIMITS);
1523 else if (cmd.argument() == "nolimits")
1524 flag.setOnOff(in->limits() == NO_LIMITS);
1526 flag.setOnOff(in->limits() == AUTO_LIMITS);
1528 flag.setEnabled(true);
1530 flag.setEnabled(false);
1542 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1545 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1546 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1547 enter_front ? idxFirst(cur) : idxLast(cur);
1549 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1553 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1556 int dist_min = 1000000;
1557 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1558 int const d = cell(i).dist(cur.bv(), x, y);
1567 MathData & ar = cell(idx_min);
1569 cur.idx() = idx_min;
1570 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1572 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1573 if (dist_min == 0) {
1575 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1576 if (ar[i]->covers(cur.bv(), x, y))
1577 return ar[i].nucleus()->editXY(cur, x, y);
1583 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1585 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1586 BufferView & bv = cur.bv();
1587 if (cmd.button() == mouse_button::button3) {
1588 // Don't do anything if we right-click a
1589 // selection, a context menu will popup.
1590 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1591 && cur < bv.cursor().selectionEnd()) {
1592 cur.noScreenUpdate();
1597 // set cursor after the inset if x is nearer to that position (bug 9748)
1598 cur.moveToClosestEdge(cmd.x(), true);
1600 bool do_selection = cmd.button() == mouse_button::button1
1601 && cmd.modifier() == ShiftModifier;
1602 bv.mouseSetCursor(cur, do_selection);
1603 if (cmd.button() == mouse_button::button1) {
1604 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1605 // Update the cursor update flags as needed:
1607 // Update::Decoration: tells to update the decoration
1608 // (visual box corners that define
1610 // Update::FitCursor: adjust the screen to the cursor
1611 // position if needed
1612 // cur.result().update(): don't overwrite previously set flags.
1613 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1614 | cur.result().screenUpdate());
1615 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1616 if (cap::selection()) {
1617 // See comment in Text::dispatch why we do this
1618 cap::copySelectionToStack();
1619 cmd = FuncRequest(LFUN_PASTE, "0");
1620 doDispatch(bv.cursor(), cmd);
1623 asArray(theSelection().get(), ar);
1624 bv.cursor().insert(ar);
1630 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1632 // only select with button 1
1633 if (cmd.button() != mouse_button::button1)
1636 Cursor & bvcur = cur.bv().cursor();
1638 // ignore motions deeper nested than the real anchor
1639 if (!bvcur.realAnchor().hasPart(cur)) {
1644 // set cursor after the inset if x is nearer to that position (bug 9748)
1645 cur.moveToClosestEdge(cmd.x());
1647 CursorSlice old = bvcur.top();
1649 // We continue with our existing selection or start a new one, so don't
1650 // reset the anchor.
1651 bvcur.setCursor(cur);
1652 // Did we actually move?
1653 if (cur.top() == old)
1654 // We didn't move one iota, so no need to change selection status
1655 // or update the screen.
1656 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1658 bvcur.setSelection();
1662 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1664 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1666 if (cmd.button() == mouse_button::button1) {
1667 if (!cur.selection())
1668 cur.noScreenUpdate();
1670 Cursor & bvcur = cur.bv().cursor();
1671 bvcur.selection(true);
1680 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1682 // try auto-correction
1683 if (lyxrc.autocorrection_math && cur.pos() != 0 && !cur.selection()
1684 && math_autocorrect(cur, c))
1687 //lyxerr << "interpret 2: '" << c << "'" << endl;
1688 docstring save_selection;
1689 if (c == '^' || c == '_')
1690 save_selection = grabAndEraseSelection(cur);
1693 Buffer * buf = cur.buffer();
1696 if (cur.inMacroMode()) {
1697 docstring name = cur.macroName();
1699 /// are we currently typing '#1' or '#2' or...?
1700 if (name == "\\#") {
1703 if (n >= 1 && n <= 9)
1704 cur.insert(new InsetMathMacroArgument(n));
1708 // do not finish macro for known * commands
1709 bool star_macro = c == '*'
1710 && (in_word_set(name.substr(1) + '*')
1711 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1712 if (isAlphaASCII(c) || star_macro) {
1713 cur.activeMacro()->setName(name + docstring(1, c));
1717 // handle 'special char' macros
1722 if (currentMode() != InsetMath::MATH_MODE)
1723 cur.niceInsert(createInsetMath("textbackslash", buf));
1725 cur.niceInsert(createInsetMath("backslash", buf));
1726 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1728 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1729 } else if (c == '{' || c == '%') {
1730 //using the saved selection as argument
1731 InsetMathUnknown * p = cur.activeMacro();
1733 MathData sel(cur.buffer());
1734 asArray(p->selection(), sel);
1737 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1739 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1740 } else if (c == '#') {
1741 LASSERT(cur.activeMacro(), return false);
1742 cur.activeMacro()->setName(name + docstring(1, c));
1745 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1750 // One character big delimiters. The others are handled in
1751 // interpretString().
1752 latexkeys const * l = in_word_set(name.substr(1));
1753 if (name[0] == '\\' && l && l->inset == "big") {
1757 delim = from_ascii("\\{");
1760 delim = from_ascii("\\}");
1763 delim = docstring(1, c);
1766 if (InsetMathBig::isBigInsetDelim(delim)) {
1767 // name + delim ared a valid InsetMathBig.
1768 // We can't use cur.macroModeClose() because
1769 // it does not handle delim.
1770 InsetMathUnknown * p = cur.activeMacro();
1773 cur.cell().erase(cur.pos());
1774 cur.plainInsert(MathAtom(
1775 new InsetMathBig(name.substr(1), delim)));
1778 } else if (name == "\\smash" && c == '[') {
1779 // We can't use cur.macroModeClose() because
1780 // it would create an InsetMathPhantom
1781 InsetMathUnknown * p = cur.activeMacro();
1783 interpretChar(cur, c);
1787 // leave macro mode and try again if necessary
1788 if (cur.macroModeClose()) {
1789 MathAtom const atom = cur.prevAtom();
1790 if (atom->asNestInset() && atom->isActive()) {
1792 cur.nextInset()->edit(cur, true);
1796 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1798 interpretChar(cur, c);
1803 // just clear selection on pressing the space bar
1804 if (cur.selection() && c == ' ') {
1805 cur.selection(false);
1810 //lyxerr << "starting with macro" << endl;
1811 bool reduced = cap::reduceSelectionToOneCell(cur);
1812 if (reduced || !cur.selection()) {
1813 cur.recordUndoInset();
1814 docstring const safe = cap::grabAndEraseSelection(cur);
1815 if (!cur.inRegexped())
1816 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1818 cur.niceInsert(createInsetMath("backslash", buf));
1826 if (currentMode() != InsetMath::MATH_MODE)
1832 if (currentMode() != InsetMath::MATH_MODE) {
1833 // insert spaces in text or undecided mode,
1834 // but suppress direct insertion of two spaces in a row
1835 // the still allows typing '<space>a<space>' and deleting the 'a', but
1836 // it is better than nothing...
1837 pos_type const pos = cur.pos();
1838 pos_type const lastpos = cur.lastpos();
1839 if ((pos == 0 && lastpos == 0)
1840 || (pos == 0 && cur.nextAtom()->getChar() != ' ')
1841 || (pos == lastpos && cur.prevAtom()->getChar() != ' ')
1842 || (pos > 0 && cur.prevAtom()->getChar() != ' '
1843 && cur.nextAtom()->getChar() != ' ')) {
1845 // FIXME: we have to enable full redraw here because of the
1846 // visual box corners that define the inset. If we know for
1847 // sure that we stay within the same cell we can optimize for
1849 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1853 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1854 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1855 // FIXME: we have to enable full redraw here because of the
1856 // visual box corners that define the inset. If we know for
1857 // sure that we stay within the same cell we can optimize for
1859 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1863 if (cur.popForward()) {
1864 // FIXME: we have to enable full redraw here because of the
1865 // visual box corners that define the inset. If we know for
1866 // sure that we stay within the same cell we can optimize for
1868 //cur.screenUpdateFlags(Update::FitCursor);
1872 // if we are at the very end, leave the formula
1873 return cur.pos() != cur.lastpos();
1876 // These should be treated differently when not in text mode:
1877 if (cur.inRegexped()) {
1880 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1887 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1890 cur.niceInsert(createInsetMath("sim", buf));
1896 } else if (currentMode() != InsetMath::TEXT_MODE) {
1898 cur.recordUndoInset();
1899 script(cur, false, save_selection);
1903 cur.recordUndoInset();
1904 script(cur, true, save_selection);
1908 cur.niceInsert(createInsetMath("sim", buf));
1911 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1912 MathAtom const atom(new InsetMathChar(c));
1913 if (cur.prevInset() && cur.prevInset()->asInsetMath()->name() == "text") {
1914 // reuse existing \text inset
1915 cur.prevInset()->asInsetMath()->cell(0).push_back(atom);
1917 MathAtom at = createInsetMath("text", buf);
1918 at.nucleus()->cell(0).push_back(atom);
1926 cur.niceInsert(createInsetMath("textasciicircum", buf));
1930 cur.niceInsert(createInsetMath("textasciitilde", buf));
1935 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1936 c == '%' || c == '_') {
1937 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1941 // no special circumstances, so insert the character without any fuss
1947 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1949 if (str == "\\limits" || str == "\\nolimits") {
1950 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1951 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1954 cur.message(bformat(_("Cannot apply %1$s here."), str));
1958 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1960 if (!cur.empty() && cur.pos() > 0 &&
1961 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1962 if (InsetMathBig::isBigInsetDelim(str)) {
1963 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1964 if (prev[0] == '\\') {
1965 prev = prev.substr(1);
1966 latexkeys const * l = in_word_set(prev);
1967 if (l && l->inset == "big") {
1968 cur.recordUndoSelection();
1969 cur.cell()[cur.pos() - 1] =
1970 MathAtom(new InsetMathBig(prev, str));
1980 bool InsetMathNest::script(Cursor & cur, bool up)
1982 return script(cur, up, docstring());
1986 bool InsetMathNest::script(Cursor & cur, bool up,
1987 docstring const & save_selection)
1989 // Hack to get \^ and \_ working
1990 //lyxerr << "handling script: up: " << up << endl;
1991 if (cur.inMacroMode() && cur.macroName() == "\\") {
1993 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1995 interpretChar(cur, '_');
1999 cur.macroModeClose();
2000 if (asScriptInset() && cur.idx() == 0) {
2001 // we are in a nucleus of a script inset, move to _our_ script
2002 InsetMathScript * inset = asScriptInset();
2003 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
2005 cur.idx() = inset->idxOfScript(up);
2007 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
2009 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2012 cur.idx() = inset->idxOfScript(up);
2013 cur.pos() = cur.lastpos();
2015 // convert the thing to our left to a scriptinset or create a new
2016 // one if in the very first position of the array
2017 if (cur.pos() == 0) {
2018 //lyxerr << "new scriptinset" << endl;
2019 cur.insert(new InsetMathScript(buffer_, up));
2021 //lyxerr << "converting prev atom " << endl;
2022 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
2025 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2026 // See comment in MathParser.cpp for special handling of {}-bases
2032 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
2033 cur.niceInsert(save_selection);
2035 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2040 bool InsetMathNest::completionSupported(Cursor const & cur) const
2042 return cur.inMacroMode();
2046 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2048 return cur.inMacroMode();
2052 bool InsetMathNest::automaticInlineCompletion() const
2054 return lyxrc.completion_inline_math;
2058 bool InsetMathNest::automaticPopupCompletion() const
2060 return lyxrc.completion_popup_math;
2064 CompletionList const *
2065 InsetMathNest::createCompletionList(Cursor const & cur) const
2067 if (!cur.inMacroMode())
2070 return new MathCompletionList(cur);
2074 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2076 if (!cur.inMacroMode())
2079 return cur.activeMacro()->name();
2083 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2086 if (!cur.inMacroMode())
2089 // append completion to active macro
2090 InsetMathUnknown * inset = cur.activeMacro();
2091 inset->setName(inset->name() + s);
2096 // FIXME: this creates duplicates in the completion popup
2097 // which looks ugly. Moreover the changes the list lengths
2098 // which seems to confuse the popup as well.
2099 MathCompletionList::addToFavorites(inset->name());
2101 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2108 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2109 Dimension & dim) const
2111 Inset const * inset = cur.activeMacro();
2115 // get inset dimensions
2116 dim = cur.bv().coordCache().insets().dim(inset);
2117 // FIXME: these 3 are no accurate, but should depend on the font.
2118 // Now the popup jumps down if you enter a char with descent > 0.
2123 Point xy = cur.bv().coordCache().insets().xy(inset);
2129 ////////////////////////////////////////////////////////////////////
2131 MathCompletionList::MathCompletionList(Cursor const & cur)
2133 // fill it with macros from the buffer
2134 MacroNameSet macros;
2135 cur.buffer()->listMacroNames(macros);
2136 MacroNameSet::const_iterator it;
2137 for (it = macros.begin(); it != macros.end(); ++it) {
2138 if (cur.buffer()->getMacro(*it, cur, false))
2139 locals.push_back("\\" + *it);
2141 sort(locals.begin(), locals.end());
2143 if (!globals.empty())
2146 // fill in global macros
2148 MacroTable::globalMacros().getMacroNames(macros, false);
2149 //lyxerr << "Globals completion macros: ";
2150 for (it = macros.begin(); it != macros.end(); ++it) {
2151 //lyxerr << "\\" + *it << " ";
2152 globals.push_back("\\" + *it);
2154 //lyxerr << std::endl;
2156 // fill in global commands
2157 globals.push_back(from_ascii("\\boxed"));
2158 globals.push_back(from_ascii("\\fbox"));
2159 globals.push_back(from_ascii("\\framebox"));
2160 globals.push_back(from_ascii("\\makebox"));
2161 globals.push_back(from_ascii("\\kern"));
2162 globals.push_back(from_ascii("\\xhookrightarrow"));
2163 globals.push_back(from_ascii("\\xhookleftarrow"));
2164 globals.push_back(from_ascii("\\xrightarrow"));
2165 globals.push_back(from_ascii("\\xRightarrow"));
2166 globals.push_back(from_ascii("\\xrightharpoondown"));
2167 globals.push_back(from_ascii("\\xrightharpoonup"));
2168 globals.push_back(from_ascii("\\xrightleftharpoons"));
2169 globals.push_back(from_ascii("\\xleftarrow"));
2170 globals.push_back(from_ascii("\\xLeftarrow"));
2171 globals.push_back(from_ascii("\\xleftharpoondown"));
2172 globals.push_back(from_ascii("\\xleftharpoonup"));
2173 globals.push_back(from_ascii("\\xleftrightarrow"));
2174 globals.push_back(from_ascii("\\xLeftrightarrow"));
2175 globals.push_back(from_ascii("\\xleftrightharpoons"));
2176 globals.push_back(from_ascii("\\xmapsto"));
2177 globals.push_back(from_ascii("\\split"));
2178 globals.push_back(from_ascii("\\gathered"));
2179 globals.push_back(from_ascii("\\aligned"));
2180 globals.push_back(from_ascii("\\alignedat"));
2181 globals.push_back(from_ascii("\\cases"));
2182 globals.push_back(from_ascii("\\substack"));
2183 globals.push_back(from_ascii("\\xymatrix"));
2184 globals.push_back(from_ascii("\\Diagram"));
2185 globals.push_back(from_ascii("\\subarray"));
2186 globals.push_back(from_ascii("\\array"));
2187 globals.push_back(from_ascii("\\sqrt"));
2188 globals.push_back(from_ascii("\\root"));
2189 globals.push_back(from_ascii("\\tabular"));
2190 globals.push_back(from_ascii("\\sideset"));
2191 globals.push_back(from_ascii("\\stackrel"));
2192 globals.push_back(from_ascii("\\stackrelthree"));
2193 globals.push_back(from_ascii("\\binom"));
2194 globals.push_back(from_ascii("\\choose"));
2195 globals.push_back(from_ascii("\\brace"));
2196 globals.push_back(from_ascii("\\brack"));
2197 globals.push_back(from_ascii("\\frac"));
2198 globals.push_back(from_ascii("\\over"));
2199 globals.push_back(from_ascii("\\nicefrac"));
2200 globals.push_back(from_ascii("\\unitfrac"));
2201 globals.push_back(from_ascii("\\unitfracthree"));
2202 globals.push_back(from_ascii("\\unitone"));
2203 globals.push_back(from_ascii("\\unittwo"));
2204 globals.push_back(from_ascii("\\infer"));
2205 globals.push_back(from_ascii("\\atop"));
2206 globals.push_back(from_ascii("\\lefteqn"));
2207 globals.push_back(from_ascii("\\boldsymbol"));
2208 globals.push_back(from_ascii("\\bm"));
2209 globals.push_back(from_ascii("\\color"));
2210 globals.push_back(from_ascii("\\normalcolor"));
2211 globals.push_back(from_ascii("\\textcolor"));
2212 globals.push_back(from_ascii("\\cfrac"));
2213 globals.push_back(from_ascii("\\cfracleft"));
2214 globals.push_back(from_ascii("\\cfracright"));
2215 globals.push_back(from_ascii("\\dfrac"));
2216 globals.push_back(from_ascii("\\tfrac"));
2217 globals.push_back(from_ascii("\\dbinom"));
2218 globals.push_back(from_ascii("\\tbinom"));
2219 globals.push_back(from_ascii("\\hphantom"));
2220 globals.push_back(from_ascii("\\phantom"));
2221 globals.push_back(from_ascii("\\vphantom"));
2222 globals.push_back(from_ascii("\\cancel"));
2223 globals.push_back(from_ascii("\\bcancel"));
2224 globals.push_back(from_ascii("\\xcancel"));
2225 globals.push_back(from_ascii("\\cancelto"));
2226 globals.push_back(from_ascii("\\smash"));
2227 globals.push_back(from_ascii("\\mathclap"));
2228 globals.push_back(from_ascii("\\mathllap"));
2229 globals.push_back(from_ascii("\\mathrlap"));
2230 globals.push_back(from_ascii("\\ensuremath"));
2231 MathWordList const & words = mathedWordList();
2232 MathWordList::const_iterator it2;
2233 //lyxerr << "Globals completion commands: ";
2234 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2235 if (it2->second.inset != "macro" && !it2->second.hidden) {
2236 // macros are already read from MacroTable::globalMacros()
2237 globals.push_back('\\' + it2->first);
2238 //lyxerr << '\\' + it2->first << ' ';
2241 //lyxerr << std::endl;
2242 sort(globals.begin(), globals.end());
2246 MathCompletionList::~MathCompletionList()
2251 size_type MathCompletionList::size() const
2253 return locals.size() + globals.size();
2257 docstring const & MathCompletionList::data(size_t idx) const
2259 size_t lsize = locals.size();
2261 return globals[idx - lsize];
2267 std::string MathCompletionList::icon(size_t idx) const
2269 // get the latex command
2271 size_t lsize = locals.size();
2273 cmd = globals[idx - lsize];
2277 // get the icon name by stripping the backslash
2278 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2279 if (icon_name.empty())
2280 return std::string();
2281 return "math/" + to_utf8(icon_name);
2284 std::vector<docstring> MathCompletionList::globals;