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);
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(WriteStream & 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 WriteStream wi(os, runparams.moving_arg, true,
362 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
364 wi.strikeoutMath(runparams.inDeletedInset);
365 if (runparams.inulemcmd) {
366 wi.ulemCmd(WriteStream::UNDERLINE);
367 if (runparams.local_font) {
368 FontInfo f = runparams.local_font->fontInfo();
369 if (f.strikeout() == FONT_ON)
370 wi.ulemCmd(WriteStream::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 CursorSlice i1 = cur.selBegin();
454 CursorSlice i2 = cur.selEnd();
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.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
466 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
471 cur.pos() = cur.lastpos();
474 // change font of cell
475 cur.handleNest(nest);
478 // cur is in the font inset now. If the loop continues,
479 // we need to get outside again for the next cell
480 if (i + 1 <= i2.idx())
486 // the complicated case with multiple selected cells in a grid
489 cap::region(i1, i2, r1, r2, c1, c2);
490 for (row_type row = r1; row <= r2; ++row) {
491 for (col_type col = c1; col <= c2; ++col) {
493 cur.idx() = i1.asInsetMath()->index(row, col);
496 cur.pos() = cur.lastpos();
500 cur.handleNest(nest);
503 // cur is in the font inset now. If the loop continues,
504 // we need to get outside again for the next cell
505 if (col + 1 <= c2 || row + 1 <= r2)
512 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
514 cur.recordUndoSelection();
517 font.fromString(to_utf8(arg), b);
518 if (font.fontInfo().color() != Color_inherit &&
519 font.fontInfo().color() != Color_ignore)
520 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
522 // FIXME: support other font changes here as well?
525 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
527 //LYXERR0("InsetMathNest: request: " << cmd);
529 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
531 FuncCode const act = cmd.action();
534 case LFUN_CLIPBOARD_PASTE:
535 parseflg |= Parse::VERBATIM;
538 if (cur.currentMode() != MATH_MODE)
539 parseflg |= Parse::TEXTMODE;
540 cur.recordUndoSelection();
541 cur.message(_("Paste"));
542 replaceSelection(cur);
544 if (cmd.argument().empty() && !theClipboard().isInternal())
545 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
548 idocstringstream is(cmd.argument());
550 topaste = cap::selection(n, buffer().params().documentClassPtr());
552 cur.niceInsert(topaste, parseflg, false);
553 cur.clearSelection(); // bug 393
554 cur.forceBufferUpdate();
561 cutSelection(cur, true);
562 cur.message(_("Cut"));
563 // Prevent stale position >= size crash
564 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
566 cur.forceBufferUpdate();
571 cur.message(_("Copy"));
574 case LFUN_MOUSE_PRESS:
575 lfunMousePress(cur, cmd);
578 case LFUN_MOUSE_MOTION:
579 lfunMouseMotion(cur, cmd);
582 case LFUN_MOUSE_RELEASE:
583 lfunMouseRelease(cur, cmd);
586 case LFUN_FINISHED_LEFT: // in math, left is backwards
587 case LFUN_FINISHED_BACKWARD:
588 cur.bv().cursor() = cur;
591 case LFUN_FINISHED_RIGHT: // in math, right is forward
592 case LFUN_FINISHED_FORWARD:
594 cur.bv().cursor() = cur;
597 case LFUN_WORD_RIGHT:
599 case LFUN_WORD_BACKWARD:
600 case LFUN_WORD_FORWARD:
601 case LFUN_CHAR_RIGHT:
603 case LFUN_CHAR_BACKWARD:
604 case LFUN_CHAR_FORWARD:
605 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
607 case LFUN_WORD_RIGHT_SELECT:
608 case LFUN_WORD_LEFT_SELECT:
609 case LFUN_WORD_BACKWARD_SELECT:
610 case LFUN_WORD_FORWARD_SELECT:
611 case LFUN_CHAR_RIGHT_SELECT:
612 case LFUN_CHAR_LEFT_SELECT:
613 case LFUN_CHAR_BACKWARD_SELECT:
614 case LFUN_CHAR_FORWARD_SELECT: {
615 // are we in a selection?
616 bool select = (act == LFUN_WORD_RIGHT_SELECT
617 || act == LFUN_WORD_LEFT_SELECT
618 || act == LFUN_WORD_BACKWARD_SELECT
619 || act == LFUN_WORD_FORWARD_SELECT
620 || act == LFUN_CHAR_RIGHT_SELECT
621 || act == LFUN_CHAR_LEFT_SELECT
622 || act == LFUN_CHAR_BACKWARD_SELECT
623 || act == LFUN_CHAR_FORWARD_SELECT);
625 bool word = (act == LFUN_WORD_RIGHT_SELECT
626 || act == LFUN_WORD_LEFT_SELECT
627 || act == LFUN_WORD_BACKWARD_SELECT
628 || act == LFUN_WORD_FORWARD_SELECT
629 || act == LFUN_WORD_RIGHT
630 || act == LFUN_WORD_LEFT
631 || act == LFUN_WORD_BACKWARD
632 || act == LFUN_WORD_FORWARD);
633 // are we moving forward or backwards?
634 // If the command was RIGHT or LEFT, then whether we're moving forward
635 // or backwards depends on the cursor movement mode (logical or visual):
636 // * in visual mode, since math is always LTR, right -> forward,
638 // * in logical mode, the mapping is determined by the
639 // reverseDirectionNeeded() function
642 FuncCode finish_lfun;
644 if (act == LFUN_CHAR_FORWARD
645 || act == LFUN_CHAR_FORWARD_SELECT
646 || act == LFUN_WORD_FORWARD
647 || act == LFUN_WORD_FORWARD_SELECT) {
649 finish_lfun = LFUN_FINISHED_FORWARD;
651 else if (act == LFUN_CHAR_BACKWARD
652 || act == LFUN_CHAR_BACKWARD_SELECT
653 || act == LFUN_WORD_BACKWARD
654 || act == LFUN_WORD_BACKWARD_SELECT) {
656 finish_lfun = LFUN_FINISHED_BACKWARD;
659 bool right = (act == LFUN_CHAR_RIGHT_SELECT
660 || act == LFUN_CHAR_RIGHT
661 || act == LFUN_WORD_RIGHT_SELECT
662 || act == LFUN_WORD_RIGHT);
663 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
669 finish_lfun = LFUN_FINISHED_RIGHT;
671 finish_lfun = LFUN_FINISHED_LEFT;
673 // Now that we know exactly what we want to do, let's do it!
674 cur.selHandle(select);
676 cur.macroModeClose();
677 // try moving forward or backwards as necessary...
678 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
679 // ... and if movement failed, then finish forward or backwards
681 cmd = FuncRequest(finish_lfun);
689 case LFUN_PARAGRAPH_UP:
690 case LFUN_PARAGRAPH_DOWN:
691 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
693 case LFUN_DOWN_SELECT:
695 case LFUN_PARAGRAPH_UP_SELECT:
696 case LFUN_PARAGRAPH_DOWN_SELECT: {
697 // close active macro
698 if (cur.inMacroMode()) {
699 cur.macroModeClose();
703 // stop/start the selection
704 bool select = act == LFUN_DOWN_SELECT
705 || act == LFUN_UP_SELECT
706 || act == LFUN_PARAGRAPH_DOWN_SELECT
707 || act == LFUN_PARAGRAPH_UP_SELECT;
708 cur.selHandle(select);
711 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
712 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
713 bool successful = cur.upDownInMath(up);
717 if (cur.fixIfBroken())
718 // FIXME: Something bad happened. We pass the corrected Cursor
719 // instead of letting things go worse.
722 // We did not manage to move the cursor.
727 case LFUN_MOUSE_DOUBLE:
728 case LFUN_WORD_SELECT:
730 cur.bv().mouseSetCursor(cur);
731 cur.pos() = cur.lastpos();
732 cur.bv().mouseSetCursor(cur, true);
735 case LFUN_MOUSE_TRIPLE:
738 cur.bv().mouseSetCursor(cur);
739 cur.idx() = cur.lastidx();
740 cur.pos() = cur.lastpos();
741 cur.bv().mouseSetCursor(cur, true);
744 case LFUN_LINE_BEGIN:
745 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
747 case LFUN_LINE_BEGIN_SELECT:
748 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
749 act == LFUN_WORD_LEFT_SELECT ||
750 act == LFUN_LINE_BEGIN_SELECT);
751 cur.macroModeClose();
752 if (cur.pos() != 0) {
754 } else if (cur.col() != 0) {
755 cur.idx() -= cur.col();
757 } else if (cur.idx() != 0) {
761 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
767 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
769 case LFUN_LINE_END_SELECT:
770 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
771 act == LFUN_WORD_RIGHT_SELECT ||
772 act == LFUN_LINE_END_SELECT);
773 cur.macroModeClose();
775 if (cur.pos() != cur.lastpos()) {
776 cur.pos() = cur.lastpos();
777 } else if (ncols() && (cur.col() != cur.lastcol())) {
778 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
779 cur.pos() = cur.lastpos();
780 } else if (cur.idx() != cur.lastidx()) {
781 cur.idx() = cur.lastidx();
782 cur.pos() = cur.lastpos();
784 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
789 case LFUN_CELL_FORWARD:
790 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
791 cur.selHandle(false);
793 cur.macroModeClose();
794 if (!cur.inset().idxNext(cur)) {
795 cur.idx() = firstIdx();
800 case LFUN_CELL_BACKWARD:
801 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
802 cur.selHandle(false);
804 cur.macroModeClose();
805 if (!cur.inset().idxPrev(cur)) {
806 cur.idx() = lastIdx();
807 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
811 case LFUN_WORD_DELETE_BACKWARD:
812 case LFUN_CHAR_DELETE_BACKWARD:
814 // May affect external cell:
815 cur.recordUndoInset();
816 else if (!cur.inMacroMode())
817 cur.recordUndoSelection();
818 // if the inset can not be removed from within, delete it
819 if (!cur.backspace(cmd.getArg(0) == "force")) {
820 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
821 cur.innerText()->dispatch(cur, newcmd);
825 case LFUN_WORD_DELETE_FORWARD:
826 case LFUN_CHAR_DELETE_FORWARD:
827 if (cur.pos() == cur.lastpos())
828 // May affect external cell:
829 cur.recordUndoInset();
831 cur.recordUndoSelection();
832 // if the inset can not be removed from within, delete it
833 if (!cur.erase(cmd.getArg(0) == "force")) {
834 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
835 cur.innerText()->dispatch(cur, newcmd);
841 cur.clearSelection();
843 if (cur.inMacroMode())
844 cur.macroModeClose(true);
846 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
852 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
853 // that is traversed by a single <CursorLeft>/<CursorRight>.
854 case LFUN_INSET_TOGGLE:
860 case LFUN_SELF_INSERT:
861 // special case first for big delimiters
862 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
865 for (char_type c : cmd.argument()) {
866 // Don't record undo steps if we are in macro mode and thus
867 // cmd.argument is the next character of the macro name.
868 // Otherwise we'll get an invalid cursor if we undo after
869 // the macro was finished and the macro is a known command,
870 // e.g. sqrt. Cursor::macroModeClose replaces in this case
871 // the InsetMathUnknown with name "frac" by an empty
872 // InsetMathFrac -> a pos value > 0 is invalid.
873 // A side effect is that an undo before the macro is finished
874 // undoes the complete macro, not only the last character.
875 // At the time we hit '\' we are not in macro mode, still.
876 if (!cur.inMacroMode())
877 cur.recordUndoSelection();
879 // special handling of space. If we insert an inset
880 // via macro mode, we want to put the cursor inside it
881 // if relevant. Think typing "\frac<space>".
883 && cur.inMacroMode() && cur.macroName() != "\\"
884 && cur.macroModeClose() && cur.pos() > 0)
885 cur.editInsertedInset();
886 else if (!interpretChar(cur, c)) {
887 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
889 // FIXME: can we avoid skipping the end of the string?
895 //case LFUN_SERVER_GET_XY:
898 case LFUN_SERVER_SET_XY: {
899 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
902 istringstream is(to_utf8(cmd.argument()));
908 // Special casing for superscript in case of LyX handling
910 case LFUN_ACCENT_CIRCUMFLEX:
911 if (cmd.argument().empty()) {
912 // do superscript if LyX handles
914 cur.recordUndoSelection();
915 script(cur, true, grabAndEraseSelection(cur));
919 case LFUN_ACCENT_UMLAUT:
920 case LFUN_ACCENT_ACUTE:
921 case LFUN_ACCENT_GRAVE:
922 case LFUN_ACCENT_BREVE:
923 case LFUN_ACCENT_DOT:
924 case LFUN_ACCENT_MACRON:
925 case LFUN_ACCENT_CARON:
926 case LFUN_ACCENT_TILDE:
927 case LFUN_ACCENT_CEDILLA:
928 case LFUN_ACCENT_CIRCLE:
929 case LFUN_ACCENT_UNDERDOT:
930 case LFUN_ACCENT_TIE:
931 case LFUN_ACCENT_OGONEK:
932 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
936 case LFUN_TEXTSTYLE_APPLY:
937 case LFUN_TEXTSTYLE_UPDATE:
938 handleFont2(cur, cmd.argument());
942 if (currentMode() != MATH_MODE)
943 handleFont(cur, cmd.argument(), "textbf");
945 handleFont(cur, cmd.argument(), "mathbf");
947 case LFUN_FONT_BOLDSYMBOL:
948 if (currentMode() != MATH_MODE)
949 handleFont(cur, cmd.argument(), "textbf");
951 handleFont(cur, cmd.argument(), "boldsymbol");
954 if (currentMode() != MATH_MODE)
955 handleFont(cur, cmd.argument(), "textsf");
957 handleFont(cur, cmd.argument(), "mathsf");
960 if (currentMode() != MATH_MODE)
961 handleFont(cur, cmd.argument(), "emph");
963 handleFont(cur, cmd.argument(), "mathcal");
965 case LFUN_FONT_ROMAN:
966 if (currentMode() != MATH_MODE)
967 handleFont(cur, cmd.argument(), "textrm");
969 handleFont(cur, cmd.argument(), "mathrm");
971 case LFUN_FONT_TYPEWRITER:
972 if (currentMode() != MATH_MODE)
973 handleFont(cur, cmd.argument(), "texttt");
975 handleFont(cur, cmd.argument(), "mathtt");
978 handleFont(cur, cmd.argument(), "mathfrak");
981 if (currentMode() != MATH_MODE)
982 handleFont(cur, cmd.argument(), "textit");
984 handleFont(cur, cmd.argument(), "mathit");
987 if (currentMode() != MATH_MODE)
988 // FIXME: should be "noun"
989 handleFont(cur, cmd.argument(), "textsc");
991 handleFont(cur, cmd.argument(), "mathbb");
993 case LFUN_FONT_DEFAULT:
994 handleFont(cur, cmd.argument(), "textnormal");
996 case LFUN_FONT_UNDERLINE:
998 cur.handleNest(createInsetMath("underline", cur.buffer()));
1001 case LFUN_MATH_MODE: {
1003 // ignore math-mode on when already in math mode
1004 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1006 cur.recordUndoSelection();
1007 cur.macroModeClose();
1008 docstring const save_selection = grabAndEraseSelection(cur);
1010 if (currentMode() != Inset::MATH_MODE)
1011 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1013 cur.plainInsert(createInsetMath("text", buffer_));
1015 cur.pushBackward(*cur.nextInset());
1016 cur.niceInsert(save_selection);
1017 cur.forceBufferUpdate();
1019 if (currentMode() == Inset::TEXT_MODE) {
1020 cur.recordUndoSelection();
1021 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1022 cur.message(_("create new math text environment ($...$)"));
1024 handleFont(cur, cmd.argument(), "textrm");
1025 cur.message(_("entered math text mode (textrm)"));
1031 case LFUN_REGEXP_MODE: {
1032 InsetMath * im = cur.inset().asInsetMath();
1034 InsetMathHull * i = im->asHullInset();
1035 if (i && i->getType() == hullRegexp) {
1036 cur.message(_("Already in regular expression mode"));
1040 cur.macroModeClose();
1041 docstring const save_selection = grabAndEraseSelection(cur);
1043 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1045 cur.pushBackward(*cur.nextInset());
1046 cur.niceInsert(save_selection);
1047 cur.message(_("Regular expression editor mode"));
1051 case LFUN_MATH_FONT_STYLE: {
1052 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1053 doDispatch(cur, fr);
1057 case LFUN_MATH_SIZE: {
1058 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1059 doDispatch(cur, fr);
1063 case LFUN_MATH_MATRIX: {
1069 idocstringstream is(cmd.argument());
1070 is >> m >> n >> v_align >> h_align;
1076 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1077 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1081 case LFUN_MATH_AMS_MATRIX: {
1085 docstring name = from_ascii("matrix");
1086 idocstringstream is(cmd.argument());
1087 is >> m >> n >> name;
1092 // check if we have a valid decoration
1093 if (name != "pmatrix" && name != "bmatrix"
1094 && name != "Bmatrix" && name != "vmatrix"
1095 && name != "Vmatrix" && name != "matrix"
1096 && name != "smallmatrix")
1097 name = from_ascii("matrix");
1100 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1104 case LFUN_MATH_DELIM: {
1106 docstring rs = split(cmd.argument(), ls, ' ');
1107 // Reasonable default values
1113 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1117 case LFUN_MATH_BIGDELIM: {
1118 docstring const lname = from_utf8(cmd.getArg(0));
1119 docstring const ldelim = from_utf8(cmd.getArg(1));
1120 docstring const rname = from_utf8(cmd.getArg(2));
1121 docstring const rdelim = from_utf8(cmd.getArg(3));
1122 latexkeys const * l = in_word_set(lname);
1123 bool const have_l = l && l->inset == "big" &&
1124 InsetMathBig::isBigInsetDelim(ldelim);
1125 l = in_word_set(rname);
1126 bool const have_r = l && l->inset == "big" &&
1127 InsetMathBig::isBigInsetDelim(rdelim);
1128 // We mimic LFUN_MATH_DELIM in case we have an empty left
1129 // or right delimiter.
1130 if (have_l || have_r) {
1132 docstring const selection = grabAndEraseSelection(cur);
1135 cur.insert(MathAtom(new InsetMathBig(lname,
1137 // first insert the right delimiter and then go back
1138 // and re-insert the selection (bug 7088)
1140 cur.insert(MathAtom(new InsetMathBig(rname,
1144 cur.niceInsert(selection);
1146 // Don't call cur.undispatched() if we did nothing, this would
1147 // lead to infinite recursion via Text::dispatch().
1151 case LFUN_SPACE_INSERT: {
1152 cur.recordUndoSelection();
1153 string const name = cmd.getArg(0);
1154 if (name == "normal")
1155 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1156 else if (name == "protected")
1157 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1158 else if (name == "thin" || name == "med" || name == "thick")
1159 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1160 else if (name == "hfill*")
1161 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1162 else if (name == "quad" || name == "qquad" ||
1163 name == "enspace" || name == "enskip" ||
1164 name == "negthinspace" || name == "negmedspace" ||
1165 name == "negthickspace" || name == "hfill")
1166 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1167 else if (name == "hspace" || name == "hspace*") {
1168 string const len = cmd.getArg(1);
1169 if (len.empty() || !isValidLength(len)) {
1170 lyxerr << "LyX function 'space-insert " << name << "' "
1171 "needs a valid length argument." << endl;
1174 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1176 cur.insert(MathAtom(new InsetMathSpace));
1180 case LFUN_MATH_SPACE:
1181 cur.recordUndoSelection();
1182 if (cmd.argument().empty())
1183 cur.insert(MathAtom(new InsetMathSpace));
1185 string const name = cmd.getArg(0);
1186 string const len = cmd.getArg(1);
1187 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1191 case LFUN_ERT_INSERT:
1192 // interpret this as if a backslash was typed
1194 interpretChar(cur, '\\');
1197 case LFUN_MATH_SUBSCRIPT:
1198 // interpret this as if a _ was typed
1199 cur.recordUndoSelection();
1200 interpretChar(cur, '_');
1203 case LFUN_MATH_SUPERSCRIPT:
1204 // interpret this as if a ^ was typed
1205 cur.recordUndoSelection();
1206 interpretChar(cur, '^');
1209 case LFUN_MATH_MACRO_FOLD:
1210 case LFUN_MATH_MACRO_UNFOLD: {
1212 bool fold = act == LFUN_MATH_MACRO_FOLD;
1213 bool found = findMacroToFoldUnfold(it, fold);
1215 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1216 cur.recordUndoInset();
1225 case LFUN_QUOTE_INSERT:
1226 // interpret this as if a straight " was typed
1227 cur.recordUndoSelection();
1228 interpretChar(cur, '\"');
1231 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1232 // handling such that "self-insert" works on "arbitrary stuff" too, and
1233 // math-insert only handles special math things like "matrix".
1234 case LFUN_MATH_INSERT: {
1235 cur.recordUndoSelection();
1236 if (cmd.argument() == "^" || cmd.argument() == "_")
1237 interpretChar(cur, cmd.argument()[0]);
1238 else if (!cur.selection())
1239 cur.niceInsert(cmd.argument());
1241 MathData ar(cur.buffer());
1242 asArray(cmd.argument(), ar);
1244 && ar[0]->asNestInset()
1245 && ar[0]->asNestInset()->nargs() > 1)
1246 handleNest(cur, ar[0]);
1248 cur.niceInsert(cmd.argument());
1253 case LFUN_DIALOG_SHOW_NEW_INSET: {
1254 docstring const & name = cmd.argument();
1256 if (name == "ref") {
1257 InsetMathRef tmp(buffer_, name);
1258 data = tmp.createDialogStr();
1259 cur.bv().showDialog(to_utf8(name), data);
1260 } else if (name == "mathspace") {
1261 cur.bv().showDialog(to_utf8(name));
1266 case LFUN_INSET_INSERT: {
1268 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1269 cur.recordUndoSelection();
1271 cur.forceBufferUpdate();
1276 case LFUN_INSET_DISSOLVE:
1277 if (!asHullInset()) {
1278 cur.recordUndoInset();
1283 case LFUN_MATH_LIMITS: {
1285 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1286 in = &cur.nextMath();
1287 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1288 in = &cur.prevMath();
1289 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1290 in = cur.cell().back().nucleus();
1291 // only when nucleus allows this
1294 cur.recordUndoInset();
1295 if (!cmd.argument().empty()) {
1296 if (cmd.argument() == "limits")
1298 else if (cmd.argument() == "nolimits")
1299 in->limits(NO_LIMITS);
1301 in->limits(AUTO_LIMITS);
1302 } else if (in->limits() == AUTO_LIMITS)
1303 in->limits(in->defaultLimits() == LIMITS ? NO_LIMITS : LIMITS);
1305 in->limits(AUTO_LIMITS);
1310 InsetMath::doDispatch(cur, cmd);
1316 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1317 // look for macro to open/close, but stay in mathed
1318 for (; !it.empty(); it.pop_back()) {
1320 // go backward through the current cell
1321 Inset * inset = it.nextInset();
1322 while (inset && inset->asInsetMath()) {
1323 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1325 // found the an macro to open/close?
1326 if (macro->folded() != fold)
1329 // Wrong folding state.
1330 // If this was the first we see in this slice, look further left,
1332 if (inset != it.nextInset())
1336 // go up if this was the left most position
1342 inset = it.nextInset();
1350 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1351 FuncStatus & flag) const
1353 // the font related toggles
1354 //string tc = "mathnormal";
1356 string const arg = to_utf8(cmd.argument());
1357 switch (cmd.action()) {
1359 case LFUN_INSET_MODIFY:
1360 // FIXME: check temporarily disabled
1362 char align = mathcursor::valign();
1363 if (align == '\0') {
1367 if (cmd.argument().empty()) {
1371 if (!contains("tcb", cmd.argument()[0])) {
1375 flag.setOnOff(cmd.argument()[0] == align);
1378 /// We have to handle them since 1.4 blocks all unhandled actions
1379 case LFUN_FONT_ITAL:
1380 case LFUN_FONT_BOLD:
1381 case LFUN_FONT_BOLDSYMBOL:
1382 case LFUN_FONT_SANS:
1383 case LFUN_FONT_EMPH:
1384 case LFUN_FONT_TYPEWRITER:
1385 case LFUN_FONT_NOUN:
1386 case LFUN_FONT_ROMAN:
1387 case LFUN_FONT_DEFAULT:
1388 flag.setEnabled(true);
1391 // we just need to be in math mode to enable that
1392 case LFUN_MATH_SIZE:
1393 case LFUN_MATH_SPACE:
1394 case LFUN_MATH_EXTERN:
1395 flag.setEnabled(true);
1398 case LFUN_FONT_UNDERLINE:
1399 case LFUN_FONT_FRAK:
1400 flag.setEnabled(currentMode() != TEXT_MODE);
1403 case LFUN_MATH_FONT_STYLE: {
1404 bool const textarg =
1405 arg == "textbf" || arg == "textsf" ||
1406 arg == "textrm" || arg == "textmd" ||
1407 arg == "textit" || arg == "textsc" ||
1408 arg == "textsl" || arg == "textup" ||
1409 arg == "texttt" || arg == "textbb" ||
1410 arg == "textnormal";
1411 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1415 case LFUN_MATH_MODE:
1416 // forbid "math-mode on" in math mode to prevent irritating
1417 // behaviour of menu entries (bug 6709)
1418 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1421 case LFUN_MATH_INSERT:
1422 flag.setEnabled(currentMode() != TEXT_MODE);
1425 case LFUN_MATH_AMS_MATRIX:
1426 case LFUN_MATH_MATRIX:
1427 flag.setEnabled(currentMode() == MATH_MODE);
1430 case LFUN_INSET_INSERT: {
1431 // Don't test createMathInset_fromDialogStr(), since
1432 // getStatus is not called with a valid reference and the
1433 // dialog would not be applicable.
1434 string const name = cmd.getArg(0);
1435 flag.setEnabled(name == "ref" || name == "mathspace");
1439 case LFUN_DIALOG_SHOW_NEW_INSET: {
1440 docstring const & name = cmd.argument();
1441 if (name == "space")
1442 flag.setEnabled(false);
1447 case LFUN_MATH_DELIM:
1448 case LFUN_MATH_BIGDELIM:
1449 // Don't do this with multi-cell selections
1450 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1453 case LFUN_MATH_MACRO_FOLD:
1454 case LFUN_MATH_MACRO_UNFOLD: {
1456 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1457 flag.setEnabled(found);
1461 case LFUN_SPECIALCHAR_INSERT:
1462 case LFUN_SCRIPT_INSERT:
1463 // FIXME: These would probably make sense in math-text mode
1464 flag.setEnabled(false);
1467 case LFUN_CAPTION_INSERT:
1468 flag.setEnabled(false);
1471 case LFUN_SPACE_INSERT: {
1472 docstring const & name = cmd.argument();
1473 if (name == "visible")
1474 flag.setEnabled(false);
1478 case LFUN_INSET_DISSOLVE:
1479 flag.setEnabled(!asHullInset());
1483 docstring const & name = cmd.argument();
1484 if (name == "html" || name == "latex")
1485 flag.setEnabled(false);
1489 case LFUN_MATH_LIMITS: {
1491 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1492 in = &cur.nextMath();
1493 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1494 in = &cur.prevMath();
1495 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1496 in = cur.cell().back().nucleus();
1498 if (!cmd.argument().empty()) {
1499 if (cmd.argument() == "limits")
1500 flag.setOnOff(in->limits() == LIMITS);
1501 else if (cmd.argument() == "nolimits")
1502 flag.setOnOff(in->limits() == NO_LIMITS);
1504 flag.setOnOff(in->limits() == AUTO_LIMITS);
1506 flag.setEnabled(true);
1508 flag.setEnabled(false);
1520 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1523 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1524 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1525 enter_front ? idxFirst(cur) : idxLast(cur);
1527 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1531 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1534 int dist_min = 1000000;
1535 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1536 int const d = cell(i).dist(cur.bv(), x, y);
1545 MathData & ar = cell(idx_min);
1547 cur.idx() = idx_min;
1548 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1550 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1551 if (dist_min == 0) {
1553 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1554 if (ar[i]->covers(cur.bv(), x, y))
1555 return ar[i].nucleus()->editXY(cur, x, y);
1561 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1563 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1564 BufferView & bv = cur.bv();
1565 if (cmd.button() == mouse_button::button3) {
1566 // Don't do anything if we right-click a
1567 // selection, a context menu will popup.
1568 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1569 && cur < bv.cursor().selectionEnd()) {
1570 cur.noScreenUpdate();
1575 // set cursor after the inset if x is nearer to that position (bug 9748)
1576 cur.moveToClosestEdge(cmd.x(), true);
1578 bool do_selection = cmd.button() == mouse_button::button1
1579 && cmd.modifier() == ShiftModifier;
1580 bv.mouseSetCursor(cur, do_selection);
1581 if (cmd.button() == mouse_button::button1) {
1582 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1583 // Update the cursor update flags as needed:
1585 // Update::Decoration: tells to update the decoration
1586 // (visual box corners that define
1588 // Update::FitCursor: adjust the screen to the cursor
1589 // position if needed
1590 // cur.result().update(): don't overwrite previously set flags.
1591 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1592 | cur.result().screenUpdate());
1593 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1594 if (cap::selection()) {
1595 // See comment in Text::dispatch why we do this
1596 cap::copySelectionToStack();
1597 cmd = FuncRequest(LFUN_PASTE, "0");
1598 doDispatch(bv.cursor(), cmd);
1601 asArray(theSelection().get(), ar);
1602 bv.cursor().insert(ar);
1608 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1610 // only select with button 1
1611 if (cmd.button() != mouse_button::button1)
1614 Cursor & bvcur = cur.bv().cursor();
1616 // ignore motions deeper nested than the real anchor
1617 if (!bvcur.realAnchor().hasPart(cur)) {
1622 // set cursor after the inset if x is nearer to that position (bug 9748)
1623 cur.moveToClosestEdge(cmd.x());
1625 CursorSlice old = bvcur.top();
1627 // We continue with our existing selection or start a new one, so don't
1628 // reset the anchor.
1629 bvcur.setCursor(cur);
1630 // Did we actually move?
1631 if (cur.top() == old)
1632 // We didn't move one iota, so no need to change selection status
1633 // or update the screen.
1634 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1636 bvcur.setSelection();
1640 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1642 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1644 if (cmd.button() == mouse_button::button1) {
1645 if (!cur.selection())
1646 cur.noScreenUpdate();
1648 Cursor & bvcur = cur.bv().cursor();
1649 bvcur.selection(true);
1658 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1660 // try auto-correction
1661 if (lyxrc.autocorrection_math && cur.pos() != 0
1662 && math_autocorrect(cur, c))
1665 //lyxerr << "interpret 2: '" << c << "'" << endl;
1666 docstring save_selection;
1667 if (c == '^' || c == '_')
1668 save_selection = grabAndEraseSelection(cur);
1671 Buffer * buf = cur.buffer();
1674 if (cur.inMacroMode()) {
1675 docstring name = cur.macroName();
1677 /// are we currently typing '#1' or '#2' or...?
1678 if (name == "\\#") {
1681 if (n >= 1 && n <= 9)
1682 cur.insert(new InsetMathMacroArgument(n));
1686 // do not finish macro for known * commands
1687 bool star_macro = c == '*'
1688 && (in_word_set(name.substr(1) + '*')
1689 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1690 if (isAlphaASCII(c) || star_macro) {
1691 cur.activeMacro()->setName(name + docstring(1, c));
1695 // handle 'special char' macros
1700 if (currentMode() != InsetMath::MATH_MODE)
1701 cur.niceInsert(createInsetMath("textbackslash", buf));
1703 cur.niceInsert(createInsetMath("backslash", buf));
1704 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1706 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1707 } else if (c == '{' || c == '%') {
1708 //using the saved selection as argument
1709 InsetMathUnknown * p = cur.activeMacro();
1711 MathData sel(cur.buffer());
1712 asArray(p->selection(), sel);
1715 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1717 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1718 } else if (c == '#') {
1719 LASSERT(cur.activeMacro(), return false);
1720 cur.activeMacro()->setName(name + docstring(1, c));
1723 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1728 // One character big delimiters. The others are handled in
1729 // interpretString().
1730 latexkeys const * l = in_word_set(name.substr(1));
1731 if (name[0] == '\\' && l && l->inset == "big") {
1735 delim = from_ascii("\\{");
1738 delim = from_ascii("\\}");
1741 delim = docstring(1, c);
1744 if (InsetMathBig::isBigInsetDelim(delim)) {
1745 // name + delim ared a valid InsetMathBig.
1746 // We can't use cur.macroModeClose() because
1747 // it does not handle delim.
1748 InsetMathUnknown * p = cur.activeMacro();
1751 cur.cell().erase(cur.pos());
1752 cur.plainInsert(MathAtom(
1753 new InsetMathBig(name.substr(1), delim)));
1756 } else if (name == "\\smash" && c == '[') {
1757 // We can't use cur.macroModeClose() because
1758 // it would create an InsetMathPhantom
1759 InsetMathUnknown * p = cur.activeMacro();
1761 interpretChar(cur, c);
1765 // leave macro mode and try again if necessary
1766 if (cur.macroModeClose()) {
1767 MathAtom const atom = cur.prevAtom();
1768 if (atom->asNestInset() && atom->isActive()) {
1770 cur.nextInset()->edit(cur, true);
1774 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1776 interpretChar(cur, c);
1781 // just clear selection on pressing the space bar
1782 if (cur.selection() && c == ' ') {
1783 cur.selection(false);
1788 //lyxerr << "starting with macro" << endl;
1789 bool reduced = cap::reduceSelectionToOneCell(cur);
1790 if (reduced || !cur.selection()) {
1791 cur.recordUndoInset();
1792 docstring const safe = cap::grabAndEraseSelection(cur);
1793 if (!cur.inRegexped())
1794 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1796 cur.niceInsert(createInsetMath("backslash", buf));
1804 if (currentMode() != InsetMath::MATH_MODE)
1810 if (currentMode() != InsetMath::MATH_MODE) {
1811 // insert spaces in text or undecided mode,
1812 // but suppress direct insertion of two spaces in a row
1813 // the still allows typing '<space>a<space>' and deleting the 'a', but
1814 // it is better than nothing...
1815 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1817 // FIXME: we have to enable full redraw here because of the
1818 // visual box corners that define the inset. If we know for
1819 // sure that we stay within the same cell we can optimize for
1821 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1825 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1826 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1827 // FIXME: we have to enable full redraw here because of the
1828 // visual box corners that define the inset. If we know for
1829 // sure that we stay within the same cell we can optimize for
1831 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1835 if (cur.popForward()) {
1836 // FIXME: we have to enable full redraw here because of the
1837 // visual box corners that define the inset. If we know for
1838 // sure that we stay within the same cell we can optimize for
1840 //cur.screenUpdateFlags(Update::FitCursor);
1844 // if we are at the very end, leave the formula
1845 return cur.pos() != cur.lastpos();
1848 // These should be treated differently when not in text mode:
1849 if (cur.inRegexped()) {
1852 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1859 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1862 cur.niceInsert(createInsetMath("sim", buf));
1868 } else if (currentMode() != InsetMath::TEXT_MODE) {
1870 script(cur, false, save_selection);
1874 script(cur, true, save_selection);
1878 cur.niceInsert(createInsetMath("sim", buf));
1881 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1882 MathAtom at = createInsetMath("text", buf);
1883 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1890 cur.niceInsert(createInsetMath("textasciicircum", buf));
1894 cur.niceInsert(createInsetMath("textasciitilde", buf));
1899 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1900 c == '%' || c == '_') {
1901 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1905 // no special circumstances, so insert the character without any fuss
1911 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1913 if (str == "\\limits" || str == "\\nolimits") {
1914 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1915 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1918 cur.message(bformat(_("Cannot apply %1$s here."), str));
1922 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1924 if (!cur.empty() && cur.pos() > 0 &&
1925 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1926 if (InsetMathBig::isBigInsetDelim(str)) {
1927 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1928 if (prev[0] == '\\') {
1929 prev = prev.substr(1);
1930 latexkeys const * l = in_word_set(prev);
1931 if (l && l->inset == "big") {
1932 cur.recordUndoSelection();
1933 cur.cell()[cur.pos() - 1] =
1934 MathAtom(new InsetMathBig(prev, str));
1944 bool InsetMathNest::script(Cursor & cur, bool up)
1946 return script(cur, up, docstring());
1950 bool InsetMathNest::script(Cursor & cur, bool up,
1951 docstring const & save_selection)
1953 // Hack to get \^ and \_ working
1954 //lyxerr << "handling script: up: " << up << endl;
1955 if (cur.inMacroMode() && cur.macroName() == "\\") {
1957 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1959 interpretChar(cur, '_');
1963 cur.macroModeClose();
1964 if (asScriptInset() && cur.idx() == 0) {
1965 // we are in a nucleus of a script inset, move to _our_ script
1966 InsetMathScript * inset = asScriptInset();
1967 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1969 cur.idx() = inset->idxOfScript(up);
1971 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1973 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1976 cur.idx() = inset->idxOfScript(up);
1977 cur.pos() = cur.lastpos();
1979 // convert the thing to our left to a scriptinset or create a new
1980 // one if in the very first position of the array
1981 if (cur.pos() == 0) {
1982 //lyxerr << "new scriptinset" << endl;
1983 cur.insert(new InsetMathScript(buffer_, up));
1985 //lyxerr << "converting prev atom " << endl;
1986 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1989 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1990 // See comment in MathParser.cpp for special handling of {}-bases
1996 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1997 cur.niceInsert(save_selection);
1999 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2004 bool InsetMathNest::completionSupported(Cursor const & cur) const
2006 return cur.inMacroMode();
2010 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2012 return cur.inMacroMode();
2016 bool InsetMathNest::automaticInlineCompletion() const
2018 return lyxrc.completion_inline_math;
2022 bool InsetMathNest::automaticPopupCompletion() const
2024 return lyxrc.completion_popup_math;
2028 CompletionList const *
2029 InsetMathNest::createCompletionList(Cursor const & cur) const
2031 if (!cur.inMacroMode())
2034 return new MathCompletionList(cur);
2038 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2040 if (!cur.inMacroMode())
2043 return cur.activeMacro()->name();
2047 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2050 if (!cur.inMacroMode())
2053 // append completion to active macro
2054 InsetMathUnknown * inset = cur.activeMacro();
2055 inset->setName(inset->name() + s);
2060 // FIXME: this creates duplicates in the completion popup
2061 // which looks ugly. Moreover the changes the list lengths
2062 // which seems to confuse the popup as well.
2063 MathCompletionList::addToFavorites(inset->name());
2065 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2072 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2073 Dimension & dim) const
2075 Inset const * inset = cur.activeMacro();
2079 // get inset dimensions
2080 dim = cur.bv().coordCache().insets().dim(inset);
2081 // FIXME: these 3 are no accurate, but should depend on the font.
2082 // Now the popup jumps down if you enter a char with descent > 0.
2087 Point xy = cur.bv().coordCache().insets().xy(inset);
2093 ////////////////////////////////////////////////////////////////////
2095 MathCompletionList::MathCompletionList(Cursor const & cur)
2097 // fill it with macros from the buffer
2098 MacroNameSet macros;
2099 cur.buffer()->listMacroNames(macros);
2100 MacroNameSet::const_iterator it;
2101 for (it = macros.begin(); it != macros.end(); ++it) {
2102 if (cur.buffer()->getMacro(*it, cur, false))
2103 locals.push_back("\\" + *it);
2105 sort(locals.begin(), locals.end());
2107 if (!globals.empty())
2110 // fill in global macros
2112 MacroTable::globalMacros().getMacroNames(macros, false);
2113 //lyxerr << "Globals completion macros: ";
2114 for (it = macros.begin(); it != macros.end(); ++it) {
2115 //lyxerr << "\\" + *it << " ";
2116 globals.push_back("\\" + *it);
2118 //lyxerr << std::endl;
2120 // fill in global commands
2121 globals.push_back(from_ascii("\\boxed"));
2122 globals.push_back(from_ascii("\\fbox"));
2123 globals.push_back(from_ascii("\\framebox"));
2124 globals.push_back(from_ascii("\\makebox"));
2125 globals.push_back(from_ascii("\\kern"));
2126 globals.push_back(from_ascii("\\xhookrightarrow"));
2127 globals.push_back(from_ascii("\\xhookleftarrow"));
2128 globals.push_back(from_ascii("\\xrightarrow"));
2129 globals.push_back(from_ascii("\\xRightarrow"));
2130 globals.push_back(from_ascii("\\xrightharpoondown"));
2131 globals.push_back(from_ascii("\\xrightharpoonup"));
2132 globals.push_back(from_ascii("\\xrightleftharpoons"));
2133 globals.push_back(from_ascii("\\xleftarrow"));
2134 globals.push_back(from_ascii("\\xLeftarrow"));
2135 globals.push_back(from_ascii("\\xleftharpoondown"));
2136 globals.push_back(from_ascii("\\xleftharpoonup"));
2137 globals.push_back(from_ascii("\\xleftrightarrow"));
2138 globals.push_back(from_ascii("\\xLeftrightarrow"));
2139 globals.push_back(from_ascii("\\xleftrightharpoons"));
2140 globals.push_back(from_ascii("\\xmapsto"));
2141 globals.push_back(from_ascii("\\split"));
2142 globals.push_back(from_ascii("\\gathered"));
2143 globals.push_back(from_ascii("\\aligned"));
2144 globals.push_back(from_ascii("\\alignedat"));
2145 globals.push_back(from_ascii("\\cases"));
2146 globals.push_back(from_ascii("\\substack"));
2147 globals.push_back(from_ascii("\\xymatrix"));
2148 globals.push_back(from_ascii("\\Diagram"));
2149 globals.push_back(from_ascii("\\subarray"));
2150 globals.push_back(from_ascii("\\array"));
2151 globals.push_back(from_ascii("\\sqrt"));
2152 globals.push_back(from_ascii("\\root"));
2153 globals.push_back(from_ascii("\\tabular"));
2154 globals.push_back(from_ascii("\\sideset"));
2155 globals.push_back(from_ascii("\\stackrel"));
2156 globals.push_back(from_ascii("\\stackrelthree"));
2157 globals.push_back(from_ascii("\\binom"));
2158 globals.push_back(from_ascii("\\choose"));
2159 globals.push_back(from_ascii("\\brace"));
2160 globals.push_back(from_ascii("\\brack"));
2161 globals.push_back(from_ascii("\\frac"));
2162 globals.push_back(from_ascii("\\over"));
2163 globals.push_back(from_ascii("\\nicefrac"));
2164 globals.push_back(from_ascii("\\unitfrac"));
2165 globals.push_back(from_ascii("\\unitfracthree"));
2166 globals.push_back(from_ascii("\\unitone"));
2167 globals.push_back(from_ascii("\\unittwo"));
2168 globals.push_back(from_ascii("\\infer"));
2169 globals.push_back(from_ascii("\\atop"));
2170 globals.push_back(from_ascii("\\lefteqn"));
2171 globals.push_back(from_ascii("\\boldsymbol"));
2172 globals.push_back(from_ascii("\\bm"));
2173 globals.push_back(from_ascii("\\color"));
2174 globals.push_back(from_ascii("\\normalcolor"));
2175 globals.push_back(from_ascii("\\textcolor"));
2176 globals.push_back(from_ascii("\\cfrac"));
2177 globals.push_back(from_ascii("\\cfracleft"));
2178 globals.push_back(from_ascii("\\cfracright"));
2179 globals.push_back(from_ascii("\\dfrac"));
2180 globals.push_back(from_ascii("\\tfrac"));
2181 globals.push_back(from_ascii("\\dbinom"));
2182 globals.push_back(from_ascii("\\tbinom"));
2183 globals.push_back(from_ascii("\\hphantom"));
2184 globals.push_back(from_ascii("\\phantom"));
2185 globals.push_back(from_ascii("\\vphantom"));
2186 globals.push_back(from_ascii("\\cancel"));
2187 globals.push_back(from_ascii("\\bcancel"));
2188 globals.push_back(from_ascii("\\xcancel"));
2189 globals.push_back(from_ascii("\\cancelto"));
2190 globals.push_back(from_ascii("\\smash"));
2191 globals.push_back(from_ascii("\\mathclap"));
2192 globals.push_back(from_ascii("\\mathllap"));
2193 globals.push_back(from_ascii("\\mathrlap"));
2194 globals.push_back(from_ascii("\\ensuremath"));
2195 MathWordList const & words = mathedWordList();
2196 MathWordList::const_iterator it2;
2197 //lyxerr << "Globals completion commands: ";
2198 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2199 if (it2->second.inset != "macro" && !it2->second.hidden) {
2200 // macros are already read from MacroTable::globalMacros()
2201 globals.push_back('\\' + it2->first);
2202 //lyxerr << '\\' + it2->first << ' ';
2205 //lyxerr << std::endl;
2206 sort(globals.begin(), globals.end());
2210 MathCompletionList::~MathCompletionList()
2215 size_type MathCompletionList::size() const
2217 return locals.size() + globals.size();
2221 docstring const & MathCompletionList::data(size_t idx) const
2223 size_t lsize = locals.size();
2225 return globals[idx - lsize];
2231 std::string MathCompletionList::icon(size_t idx) const
2233 // get the latex command
2235 size_t lsize = locals.size();
2237 cmd = globals[idx - lsize];
2241 // get the icon name by stripping the backslash
2242 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2243 if (icon_name.empty())
2244 return std::string();
2245 return "math/" + to_utf8(icon_name);
2248 std::vector<docstring> MathCompletionList::globals;