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"
54 #include "OutputParams.h"
58 #include "frontends/Application.h"
59 #include "frontends/Clipboard.h"
60 #include "frontends/Painter.h"
61 #include "frontends/Selection.h"
63 #include "support/debug.h"
64 #include "support/docstream.h"
65 #include "support/gettext.h"
66 #include "support/lassert.h"
67 #include "support/lstrings.h"
68 #include "support/textutils.h"
74 using namespace lyx::support;
78 using cap::copySelection;
79 using cap::grabAndEraseSelection;
80 using cap::cutSelection;
81 using cap::replaceSelection;
82 using cap::selClearOrDel;
85 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
86 : InsetMath(buf), cells_(nargs), lock_(false)
88 // FIXME This should not really be necessary, but when we are
89 // initializing the table of global macros, we create macros
90 // with no associated Buffer.
96 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
97 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
101 InsetMathNest::~InsetMathNest()
103 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
104 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
105 for (; it != end; ++it)
107 it->first->clearLastInset(this);
111 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
113 cells_ = inset.cells_;
115 mouse_hover_.clear();
116 InsetMath::operator=(inset);
121 void InsetMathNest::setBuffer(Buffer & buffer)
123 InsetMath::setBuffer(buffer);
124 for (MathData & data : cells_)
125 data.setBuffer(buffer);
129 idx_type InsetMathNest::nargs() const
131 return cells_.size();
135 void InsetMathNest::cursorPos(BufferView const & bv,
136 CursorSlice const & sl, bool /*boundary*/,
137 int & x, int & y) const
139 // FIXME: This is a hack. Ideally, the coord cache should not store
140 // absolute positions, but relative ones. This would mean to call
141 // setXY() not in MathData::draw(), but in the parent insets' draw()
142 // with the correctly adjusted x,y values. But this means that we'd have
143 // to touch all (math)inset's draw() methods. Right now, we'll store
144 // absolute value, and make them here relative, only to make them
145 // absolute again when actually drawing the cursor. What a mess.
146 LASSERT(&sl.inset() == this, return);
147 MathData const & ar = sl.cell();
148 CoordCache const & coord_cache = bv.coordCache();
149 if (!coord_cache.getArrays().has(&ar)) {
150 // this can (semi-)legally happen if we just created this cell
151 // and it never has been drawn before. So don't ASSERT.
152 //lyxerr << "no cached data for array " << &ar << endl;
157 Point const pt = coord_cache.getArrays().xy(&ar);
158 if (!coord_cache.getInsets().has(this)) {
160 //lyxerr << "no cached data for inset " << this << endl;
165 Point const pt2 = coord_cache.getInsets().xy(this);
166 //lyxerr << "retrieving position cache for MathData "
167 // << pt.x_ << ' ' << pt.y_ << endl;
168 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
170 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
171 // << " asc: " << ascent() << " des: " << descent()
172 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
173 // move cursor visually into empty cells ("blue rectangles");
175 Dimension const dim = coord_cache.getArrays().dim(&ar);
181 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
184 for (auto const & cell : cells_) {
186 cell.metrics(m, dim);
191 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
193 for (idx_type i = 0, n = nargs(); i != n; ++i)
194 cell(i).updateBuffer(it, utype, deleted);
199 bool InsetMathNest::idxNext(Cursor & cur) const
201 LASSERT(&cur.inset() == this, return false);
202 if (cur.idx() == cur.lastidx())
210 bool InsetMathNest::idxForward(Cursor & cur) const
216 bool InsetMathNest::idxPrev(Cursor & cur) const
218 LASSERT(&cur.inset() == this, return false);
222 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
227 bool InsetMathNest::idxBackward(Cursor & cur) const
233 bool InsetMathNest::idxFirst(Cursor & cur) const
235 LASSERT(&cur.inset() == this, return false);
238 cur.idx() = firstIdx();
244 bool InsetMathNest::idxLast(Cursor & cur) const
246 LASSERT(&cur.inset() == this, return false);
249 cur.idx() = lastIdx();
250 cur.pos() = cur.lastpos();
255 void InsetMathNest::dump() const
257 odocstringstream oss;
258 otexrowstream ots(oss);
260 os << "---------------------------------------------\n";
263 for (idx_type i = 0, n = nargs(); i != n; ++i)
264 os << cell(i) << "\n";
265 os << "---------------------------------------------\n";
266 lyxerr << to_utf8(oss.str());
270 void InsetMathNest::draw(PainterInfo &, int, int) const
274 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
280 void InsetMathNest::validate(LaTeXFeatures & features) const
282 for (idx_type i = 0; i < nargs(); ++i)
283 cell(i).validate(features);
287 void InsetMathNest::replace(ReplaceData & rep)
289 for (idx_type i = 0; i < nargs(); ++i)
290 cell(i).replace(rep);
294 bool InsetMathNest::contains(MathData const & ar) const
296 for (idx_type i = 0; i < nargs(); ++i)
297 if (cell(i).contains(ar))
303 bool InsetMathNest::lock() const
309 void InsetMathNest::lock(bool l)
315 bool InsetMathNest::isActive() const
321 MathData InsetMathNest::glue() const
324 for (size_t i = 0; i < nargs(); ++i)
330 void InsetMathNest::write(WriteStream & os) const
332 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
333 ModeSpecifier specifier(os, currentMode(), lockedMode());
334 docstring const latex_name = name();
335 os << '\\' << latex_name;
336 os.inMathClass(asClassInset());
337 for (size_t i = 0; i < nargs(); ++i) {
338 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
339 os << '{' << cell(i) << '}';
342 os.pendingSpace(true);
343 if (lock_ && !os.latex()) {
345 os.pendingSpace(true);
347 os.inMathClass(false);
351 void InsetMathNest::normalize(NormalStream & os) const
354 for (size_t i = 0; i < nargs(); ++i)
355 os << ' ' << cell(i);
360 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
362 WriteStream wi(os, runparams.moving_arg, true,
363 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
365 wi.strikeoutMath(runparams.inDeletedInset);
366 if (runparams.inulemcmd) {
367 wi.ulemCmd(WriteStream::UNDERLINE);
368 if (runparams.local_font) {
369 FontInfo f = runparams.local_font->fontInfo();
370 if (f.strikeout() == FONT_ON)
371 wi.ulemCmd(WriteStream::STRIKEOUT);
374 wi.canBreakLine(os.canBreakLine());
375 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
378 // Reset parbreak and command termination status after a math inset.
380 os.canBreakLine(wi.canBreakLine());
381 os.terminateCommand(false);
385 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
388 mouse_hover_[bv] = mouse_hover;
393 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
397 MathData & ar = cur.cell();
398 // remove base-only "scripts"
399 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
400 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
401 if (p && p->nargs() == 1) {
402 MathData ar = p->nuc();
405 cur.adjust(i, ar.size() - 1);
409 // glue adjacent font insets of the same kind
410 for (pos_type i = 0; i + 1 < size(); ++i) {
411 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
412 InsetMathFont const * q = operator[](i + 1)->asFontInset();
413 if (p && q && p->name() == q->name()) {
414 p->cell(0).append(q->cell(0));
424 void InsetMathNest::handleFont
425 (Cursor & cur, docstring const & arg, char const * const font)
427 handleFont(cur, arg, from_ascii(font));
431 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
432 docstring const & font)
434 cur.recordUndoSelection();
436 // this whole function is a hack and won't work for incremental font
438 if (cur.inset().asInsetMath()->name() == font)
439 cur.handleFont(to_utf8(font));
441 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
445 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
447 handleNest(cur, nest, docstring());
451 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
452 docstring const & arg)
454 CursorSlice i1 = cur.selBegin();
455 CursorSlice i2 = cur.selEnd();
456 if (!i1.inset().asInsetMath())
458 if (i1.idx() == i2.idx()) {
459 // the easy case where only one cell is selected
460 cur.handleNest(nest);
465 // multiple selected cells in a simple non-grid inset
466 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
467 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
472 cur.pos() = cur.lastpos();
475 // change font of cell
476 cur.handleNest(nest);
479 // cur is in the font inset now. If the loop continues,
480 // we need to get outside again for the next cell
481 if (i + 1 <= i2.idx())
487 // the complicated case with multiple selected cells in a grid
490 cap::region(i1, i2, r1, r2, c1, c2);
491 for (row_type row = r1; row <= r2; ++row) {
492 for (col_type col = c1; col <= c2; ++col) {
494 cur.idx() = i1.asInsetMath()->index(row, col);
497 cur.pos() = cur.lastpos();
501 cur.handleNest(nest);
504 // cur is in the font inset now. If the loop continues,
505 // we need to get outside again for the next cell
506 if (col + 1 <= c2 || row + 1 <= r2)
513 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
515 cur.recordUndoSelection();
518 font.fromString(to_utf8(arg), b);
519 if (font.fontInfo().color() != Color_inherit &&
520 font.fontInfo().color() != Color_ignore)
521 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
523 // FIXME: support other font changes here as well?
526 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
528 //LYXERR0("InsetMathNest: request: " << cmd);
530 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
532 FuncCode const act = cmd.action();
535 case LFUN_CLIPBOARD_PASTE:
536 parseflg |= Parse::VERBATIM;
539 if (cur.currentMode() != MATH_MODE)
540 parseflg |= Parse::TEXTMODE;
541 cur.recordUndoSelection();
542 cur.message(_("Paste"));
543 replaceSelection(cur);
545 if (cmd.argument().empty() && !theClipboard().isInternal())
546 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
549 idocstringstream is(cmd.argument());
551 topaste = cap::selection(n, buffer().params().documentClassPtr());
553 cur.niceInsert(topaste, parseflg, false);
554 cur.clearSelection(); // bug 393
555 cur.forceBufferUpdate();
562 cutSelection(cur, true);
563 cur.message(_("Cut"));
564 // Prevent stale position >= size crash
565 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
567 cur.forceBufferUpdate();
572 cur.message(_("Copy"));
575 case LFUN_MOUSE_PRESS:
576 lfunMousePress(cur, cmd);
579 case LFUN_MOUSE_MOTION:
580 lfunMouseMotion(cur, cmd);
583 case LFUN_MOUSE_RELEASE:
584 lfunMouseRelease(cur, cmd);
587 case LFUN_FINISHED_LEFT: // in math, left is backwards
588 case LFUN_FINISHED_BACKWARD:
589 cur.bv().cursor() = cur;
592 case LFUN_FINISHED_RIGHT: // in math, right is forward
593 case LFUN_FINISHED_FORWARD:
595 cur.bv().cursor() = cur;
598 case LFUN_WORD_RIGHT:
600 case LFUN_WORD_BACKWARD:
601 case LFUN_WORD_FORWARD:
602 case LFUN_CHAR_RIGHT:
604 case LFUN_CHAR_BACKWARD:
605 case LFUN_CHAR_FORWARD:
606 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
608 case LFUN_WORD_RIGHT_SELECT:
609 case LFUN_WORD_LEFT_SELECT:
610 case LFUN_WORD_BACKWARD_SELECT:
611 case LFUN_WORD_FORWARD_SELECT:
612 case LFUN_CHAR_RIGHT_SELECT:
613 case LFUN_CHAR_LEFT_SELECT:
614 case LFUN_CHAR_BACKWARD_SELECT:
615 case LFUN_CHAR_FORWARD_SELECT: {
616 // are we in a selection?
617 bool select = (act == LFUN_WORD_RIGHT_SELECT
618 || act == LFUN_WORD_LEFT_SELECT
619 || act == LFUN_WORD_BACKWARD_SELECT
620 || act == LFUN_WORD_FORWARD_SELECT
621 || act == LFUN_CHAR_RIGHT_SELECT
622 || act == LFUN_CHAR_LEFT_SELECT
623 || act == LFUN_CHAR_BACKWARD_SELECT
624 || act == LFUN_CHAR_FORWARD_SELECT);
626 bool word = (act == LFUN_WORD_RIGHT_SELECT
627 || act == LFUN_WORD_LEFT_SELECT
628 || act == LFUN_WORD_BACKWARD_SELECT
629 || act == LFUN_WORD_FORWARD_SELECT
630 || act == LFUN_WORD_RIGHT
631 || act == LFUN_WORD_LEFT
632 || act == LFUN_WORD_BACKWARD
633 || act == LFUN_WORD_FORWARD);
634 // are we moving forward or backwards?
635 // If the command was RIGHT or LEFT, then whether we're moving forward
636 // or backwards depends on the cursor movement mode (logical or visual):
637 // * in visual mode, since math is always LTR, right -> forward,
639 // * in logical mode, the mapping is determined by the
640 // reverseDirectionNeeded() function
643 FuncCode finish_lfun;
645 if (act == LFUN_CHAR_FORWARD
646 || act == LFUN_CHAR_FORWARD_SELECT
647 || act == LFUN_WORD_FORWARD
648 || act == LFUN_WORD_FORWARD_SELECT) {
650 finish_lfun = LFUN_FINISHED_FORWARD;
652 else if (act == LFUN_CHAR_BACKWARD
653 || act == LFUN_CHAR_BACKWARD_SELECT
654 || act == LFUN_WORD_BACKWARD
655 || act == LFUN_WORD_BACKWARD_SELECT) {
657 finish_lfun = LFUN_FINISHED_BACKWARD;
660 bool right = (act == LFUN_CHAR_RIGHT_SELECT
661 || act == LFUN_CHAR_RIGHT
662 || act == LFUN_WORD_RIGHT_SELECT
663 || act == LFUN_WORD_RIGHT);
664 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
670 finish_lfun = LFUN_FINISHED_RIGHT;
672 finish_lfun = LFUN_FINISHED_LEFT;
674 // Now that we know exactly what we want to do, let's do it!
675 cur.selHandle(select);
677 cur.macroModeClose();
678 // try moving forward or backwards as necessary...
679 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
680 // ... and if movement failed, then finish forward or backwards
682 cmd = FuncRequest(finish_lfun);
690 case LFUN_PARAGRAPH_UP:
691 case LFUN_PARAGRAPH_DOWN:
692 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
694 case LFUN_DOWN_SELECT:
696 case LFUN_PARAGRAPH_UP_SELECT:
697 case LFUN_PARAGRAPH_DOWN_SELECT: {
698 // close active macro
699 if (cur.inMacroMode()) {
700 cur.macroModeClose();
704 // stop/start the selection
705 bool select = act == LFUN_DOWN_SELECT
706 || act == LFUN_UP_SELECT
707 || act == LFUN_PARAGRAPH_DOWN_SELECT
708 || act == LFUN_PARAGRAPH_UP_SELECT;
709 cur.selHandle(select);
712 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
713 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
714 bool successful = cur.upDownInMath(up);
718 if (cur.fixIfBroken())
719 // FIXME: Something bad happened. We pass the corrected Cursor
720 // instead of letting things go worse.
723 // We did not manage to move the cursor.
728 case LFUN_MOUSE_DOUBLE:
729 case LFUN_WORD_SELECT:
731 cur.bv().mouseSetCursor(cur);
732 cur.pos() = cur.lastpos();
733 cur.bv().mouseSetCursor(cur, true);
736 case LFUN_MOUSE_TRIPLE:
739 cur.bv().mouseSetCursor(cur);
740 cur.idx() = cur.lastidx();
741 cur.pos() = cur.lastpos();
742 cur.bv().mouseSetCursor(cur, true);
745 case LFUN_LINE_BEGIN:
746 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
748 case LFUN_LINE_BEGIN_SELECT:
749 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
750 act == LFUN_WORD_LEFT_SELECT ||
751 act == LFUN_LINE_BEGIN_SELECT);
752 cur.macroModeClose();
753 if (cur.pos() != 0) {
755 } else if (cur.col() != 0) {
756 cur.idx() -= cur.col();
758 } else if (cur.idx() != 0) {
762 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
768 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
770 case LFUN_LINE_END_SELECT:
771 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
772 act == LFUN_WORD_RIGHT_SELECT ||
773 act == LFUN_LINE_END_SELECT);
774 cur.macroModeClose();
776 if (cur.pos() != cur.lastpos()) {
777 cur.pos() = cur.lastpos();
778 } else if (ncols() && (cur.col() != cur.lastcol())) {
779 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
780 cur.pos() = cur.lastpos();
781 } else if (cur.idx() != cur.lastidx()) {
782 cur.idx() = cur.lastidx();
783 cur.pos() = cur.lastpos();
785 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
790 case LFUN_CELL_FORWARD:
791 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
792 cur.selHandle(false);
794 cur.macroModeClose();
795 if (!cur.inset().idxNext(cur)) {
796 cur.idx() = firstIdx();
801 case LFUN_CELL_BACKWARD:
802 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
803 cur.selHandle(false);
805 cur.macroModeClose();
806 if (!cur.inset().idxPrev(cur)) {
807 cur.idx() = lastIdx();
808 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
812 case LFUN_WORD_DELETE_BACKWARD:
813 case LFUN_CHAR_DELETE_BACKWARD:
815 // May affect external cell:
816 cur.recordUndoInset();
817 else if (!cur.inMacroMode())
818 cur.recordUndoSelection();
819 // if the inset can not be removed from within, delete it
820 if (!cur.backspace(cmd.getArg(0) == "force")) {
821 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
822 cur.innerText()->dispatch(cur, newcmd);
826 case LFUN_WORD_DELETE_FORWARD:
827 case LFUN_CHAR_DELETE_FORWARD:
828 if (cur.pos() == cur.lastpos())
829 // May affect external cell:
830 cur.recordUndoInset();
832 cur.recordUndoSelection();
833 // if the inset can not be removed from within, delete it
834 if (!cur.erase(cmd.getArg(0) == "force")) {
835 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
836 cur.innerText()->dispatch(cur, newcmd);
842 cur.clearSelection();
844 if (cur.inMacroMode())
845 cur.macroModeClose(true);
847 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
853 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
854 // that is traversed by a single <CursorLeft>/<CursorRight>.
855 case LFUN_INSET_TOGGLE:
861 case LFUN_SELF_INSERT:
862 // special case first for big delimiters
863 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
866 for (char_type c : cmd.argument()) {
867 // Don't record undo steps if we are in macro mode and thus
868 // cmd.argument is the next character of the macro name.
869 // Otherwise we'll get an invalid cursor if we undo after
870 // the macro was finished and the macro is a known command,
871 // e.g. sqrt. Cursor::macroModeClose replaces in this case
872 // the InsetMathUnknown with name "frac" by an empty
873 // InsetMathFrac -> a pos value > 0 is invalid.
874 // A side effect is that an undo before the macro is finished
875 // undoes the complete macro, not only the last character.
876 // At the time we hit '\' we are not in macro mode, still.
877 if (!cur.inMacroMode())
878 cur.recordUndoSelection();
880 // special handling of space. If we insert an inset
881 // via macro mode, we want to put the cursor inside it
882 // if relevant. Think typing "\frac<space>".
884 && cur.inMacroMode() && cur.macroName() != "\\"
885 && cur.macroModeClose() && cur.pos() > 0)
886 cur.editInsertedInset();
887 else if (!interpretChar(cur, c)) {
888 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
890 // FIXME: can we avoid skipping the end of the string?
896 //case LFUN_SERVER_GET_XY:
899 case LFUN_SERVER_SET_XY: {
900 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
903 istringstream is(to_utf8(cmd.argument()));
909 // Special casing for superscript in case of LyX handling
911 case LFUN_ACCENT_CIRCUMFLEX:
912 if (cmd.argument().empty()) {
913 // do superscript if LyX handles
915 cur.recordUndoSelection();
916 script(cur, true, grabAndEraseSelection(cur));
920 case LFUN_ACCENT_UMLAUT:
921 case LFUN_ACCENT_ACUTE:
922 case LFUN_ACCENT_GRAVE:
923 case LFUN_ACCENT_BREVE:
924 case LFUN_ACCENT_DOT:
925 case LFUN_ACCENT_MACRON:
926 case LFUN_ACCENT_CARON:
927 case LFUN_ACCENT_TILDE:
928 case LFUN_ACCENT_CEDILLA:
929 case LFUN_ACCENT_CIRCLE:
930 case LFUN_ACCENT_UNDERDOT:
931 case LFUN_ACCENT_TIE:
932 case LFUN_ACCENT_OGONEK:
933 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
937 case LFUN_TEXTSTYLE_APPLY:
938 case LFUN_TEXTSTYLE_UPDATE:
939 handleFont2(cur, cmd.argument());
943 if (currentMode() != MATH_MODE)
944 handleFont(cur, cmd.argument(), "textbf");
946 handleFont(cur, cmd.argument(), "mathbf");
948 case LFUN_FONT_BOLDSYMBOL:
949 if (currentMode() != MATH_MODE)
950 handleFont(cur, cmd.argument(), "textbf");
952 handleFont(cur, cmd.argument(), "boldsymbol");
955 if (currentMode() != MATH_MODE)
956 handleFont(cur, cmd.argument(), "textsf");
958 handleFont(cur, cmd.argument(), "mathsf");
961 if (currentMode() != MATH_MODE)
962 handleFont(cur, cmd.argument(), "emph");
964 handleFont(cur, cmd.argument(), "mathcal");
966 case LFUN_FONT_ROMAN:
967 if (currentMode() != MATH_MODE)
968 handleFont(cur, cmd.argument(), "textrm");
970 handleFont(cur, cmd.argument(), "mathrm");
972 case LFUN_FONT_TYPEWRITER:
973 if (currentMode() != MATH_MODE)
974 handleFont(cur, cmd.argument(), "texttt");
976 handleFont(cur, cmd.argument(), "mathtt");
979 handleFont(cur, cmd.argument(), "mathfrak");
982 if (currentMode() != MATH_MODE)
983 handleFont(cur, cmd.argument(), "textit");
985 handleFont(cur, cmd.argument(), "mathit");
988 if (currentMode() != MATH_MODE)
989 // FIXME: should be "noun"
990 handleFont(cur, cmd.argument(), "textsc");
992 handleFont(cur, cmd.argument(), "mathbb");
994 case LFUN_FONT_DEFAULT:
995 handleFont(cur, cmd.argument(), "textnormal");
997 case LFUN_FONT_UNDERLINE:
999 cur.handleNest(createInsetMath("underline", cur.buffer()));
1002 case LFUN_MATH_MODE: {
1004 // ignore math-mode on when already in math mode
1005 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1007 cur.recordUndoSelection();
1008 cur.macroModeClose();
1009 docstring const save_selection = grabAndEraseSelection(cur);
1011 if (currentMode() != Inset::MATH_MODE)
1012 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1014 cur.plainInsert(createInsetMath("text", buffer_));
1016 cur.pushBackward(*cur.nextInset());
1017 cur.niceInsert(save_selection);
1018 cur.forceBufferUpdate();
1020 if (currentMode() == Inset::TEXT_MODE) {
1021 cur.recordUndoSelection();
1022 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1023 cur.message(_("create new math text environment ($...$)"));
1025 handleFont(cur, cmd.argument(), "textrm");
1026 cur.message(_("entered math text mode (textrm)"));
1032 case LFUN_REGEXP_MODE: {
1033 InsetMath * im = cur.inset().asInsetMath();
1035 InsetMathHull * i = im->asHullInset();
1036 if (i && i->getType() == hullRegexp) {
1037 cur.message(_("Already in regular expression mode"));
1041 cur.macroModeClose();
1042 docstring const save_selection = grabAndEraseSelection(cur);
1044 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1046 cur.pushBackward(*cur.nextInset());
1047 cur.niceInsert(save_selection);
1048 cur.message(_("Regular expression editor mode"));
1052 case LFUN_MATH_FONT_STYLE: {
1053 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1054 doDispatch(cur, fr);
1058 case LFUN_MATH_SIZE: {
1059 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1060 doDispatch(cur, fr);
1064 case LFUN_MATH_MATRIX: {
1070 idocstringstream is(cmd.argument());
1071 is >> m >> n >> v_align >> h_align;
1077 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1078 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1082 case LFUN_MATH_AMS_MATRIX: {
1086 docstring name = from_ascii("matrix");
1087 idocstringstream is(cmd.argument());
1088 is >> m >> n >> name;
1093 // check if we have a valid decoration
1094 if (name != "pmatrix" && name != "bmatrix"
1095 && name != "Bmatrix" && name != "vmatrix"
1096 && name != "Vmatrix" && name != "matrix"
1097 && name != "smallmatrix")
1098 name = from_ascii("matrix");
1101 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1105 case LFUN_MATH_DELIM: {
1107 docstring rs = split(cmd.argument(), ls, ' ');
1108 // Reasonable default values
1114 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1118 case LFUN_MATH_BIGDELIM: {
1119 docstring const lname = from_utf8(cmd.getArg(0));
1120 docstring const ldelim = from_utf8(cmd.getArg(1));
1121 docstring const rname = from_utf8(cmd.getArg(2));
1122 docstring const rdelim = from_utf8(cmd.getArg(3));
1123 latexkeys const * l = in_word_set(lname);
1124 bool const have_l = l && l->inset == "big" &&
1125 InsetMathBig::isBigInsetDelim(ldelim);
1126 l = in_word_set(rname);
1127 bool const have_r = l && l->inset == "big" &&
1128 InsetMathBig::isBigInsetDelim(rdelim);
1129 // We mimic LFUN_MATH_DELIM in case we have an empty left
1130 // or right delimiter.
1131 if (have_l || have_r) {
1133 docstring const selection = grabAndEraseSelection(cur);
1136 cur.insert(MathAtom(new InsetMathBig(lname,
1138 // first insert the right delimiter and then go back
1139 // and re-insert the selection (bug 7088)
1141 cur.insert(MathAtom(new InsetMathBig(rname,
1145 cur.niceInsert(selection);
1147 // Don't call cur.undispatched() if we did nothing, this would
1148 // lead to infinite recursion via Text::dispatch().
1152 case LFUN_SPACE_INSERT: {
1153 cur.recordUndoSelection();
1154 string const name = cmd.getArg(0);
1155 if (name == "normal")
1156 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1157 else if (name == "protected")
1158 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1159 else if (name == "thin" || name == "med" || name == "thick")
1160 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1161 else if (name == "hfill*")
1162 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1163 else if (name == "quad" || name == "qquad" ||
1164 name == "enspace" || name == "enskip" ||
1165 name == "negthinspace" || name == "negmedspace" ||
1166 name == "negthickspace" || name == "hfill")
1167 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1168 else if (name == "hspace" || name == "hspace*") {
1169 string const len = cmd.getArg(1);
1170 if (len.empty() || !isValidLength(len)) {
1171 lyxerr << "LyX function 'space-insert " << name << "' "
1172 "needs a valid length argument." << endl;
1175 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1177 cur.insert(MathAtom(new InsetMathSpace));
1181 case LFUN_MATH_SPACE:
1182 cur.recordUndoSelection();
1183 if (cmd.argument().empty())
1184 cur.insert(MathAtom(new InsetMathSpace));
1186 string const name = cmd.getArg(0);
1187 string const len = cmd.getArg(1);
1188 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1192 case LFUN_ERT_INSERT:
1193 // interpret this as if a backslash was typed
1195 interpretChar(cur, '\\');
1198 case LFUN_MATH_SUBSCRIPT:
1199 // interpret this as if a _ was typed
1200 cur.recordUndoSelection();
1201 interpretChar(cur, '_');
1204 case LFUN_MATH_SUPERSCRIPT:
1205 // interpret this as if a ^ was typed
1206 cur.recordUndoSelection();
1207 interpretChar(cur, '^');
1210 case LFUN_MATH_MACRO_FOLD:
1211 case LFUN_MATH_MACRO_UNFOLD: {
1213 bool fold = act == LFUN_MATH_MACRO_FOLD;
1214 bool found = findMacroToFoldUnfold(it, fold);
1216 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1217 cur.recordUndoInset();
1226 case LFUN_QUOTE_INSERT:
1227 // interpret this as if a straight " was typed
1228 cur.recordUndoSelection();
1229 interpretChar(cur, '\"');
1232 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1233 // handling such that "self-insert" works on "arbitrary stuff" too, and
1234 // math-insert only handles special math things like "matrix".
1235 case LFUN_MATH_INSERT: {
1236 cur.recordUndoSelection();
1237 if (cmd.argument() == "^" || cmd.argument() == "_")
1238 interpretChar(cur, cmd.argument()[0]);
1239 else if (!cur.selection())
1240 cur.niceInsert(cmd.argument());
1242 MathData ar(cur.buffer());
1243 asArray(cmd.argument(), ar);
1245 && ar[0]->asNestInset()
1246 && ar[0]->asNestInset()->nargs() > 1)
1247 handleNest(cur, ar[0]);
1249 cur.niceInsert(cmd.argument());
1254 case LFUN_DIALOG_SHOW_NEW_INSET: {
1255 docstring const & name = cmd.argument();
1257 if (name == "ref") {
1258 InsetMathRef tmp(buffer_, name);
1259 data = tmp.createDialogStr();
1260 cur.bv().showDialog(to_utf8(name), data);
1261 } else if (name == "mathspace") {
1262 cur.bv().showDialog(to_utf8(name));
1267 case LFUN_INSET_INSERT: {
1269 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1270 cur.recordUndoSelection();
1272 cur.forceBufferUpdate();
1277 case LFUN_INSET_DISSOLVE:
1278 if (!asHullInset()) {
1279 cur.recordUndoInset();
1284 case LFUN_MATH_LIMITS: {
1286 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1287 in = &cur.nextMath();
1288 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1289 in = &cur.prevMath();
1290 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1291 in = cur.cell().back().nucleus();
1292 // only when nucleus allows this
1295 cur.recordUndoInset();
1296 if (!cmd.argument().empty()) {
1297 if (cmd.argument() == "limits")
1299 else if (cmd.argument() == "nolimits")
1300 in->limits(NO_LIMITS);
1302 in->limits(AUTO_LIMITS);
1303 } else if (in->limits() == AUTO_LIMITS)
1304 in->limits(in->defaultLimits() == LIMITS ? NO_LIMITS : LIMITS);
1306 in->limits(AUTO_LIMITS);
1311 InsetMath::doDispatch(cur, cmd);
1317 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1318 // look for macro to open/close, but stay in mathed
1319 for (; !it.empty(); it.pop_back()) {
1321 // go backward through the current cell
1322 Inset * inset = it.nextInset();
1323 while (inset && inset->asInsetMath()) {
1324 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1326 // found the an macro to open/close?
1327 if (macro->folded() != fold)
1330 // Wrong folding state.
1331 // If this was the first we see in this slice, look further left,
1333 if (inset != it.nextInset())
1337 // go up if this was the left most position
1343 inset = it.nextInset();
1351 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1352 FuncStatus & flag) const
1354 // the font related toggles
1355 //string tc = "mathnormal";
1357 string const arg = to_utf8(cmd.argument());
1358 switch (cmd.action()) {
1360 case LFUN_INSET_MODIFY:
1361 // FIXME: check temporarily disabled
1363 char align = mathcursor::valign();
1364 if (align == '\0') {
1368 if (cmd.argument().empty()) {
1372 if (!contains("tcb", cmd.argument()[0])) {
1376 flag.setOnOff(cmd.argument()[0] == align);
1379 /// We have to handle them since 1.4 blocks all unhandled actions
1380 case LFUN_FONT_ITAL:
1381 case LFUN_FONT_BOLD:
1382 case LFUN_FONT_BOLDSYMBOL:
1383 case LFUN_FONT_SANS:
1384 case LFUN_FONT_EMPH:
1385 case LFUN_FONT_TYPEWRITER:
1386 case LFUN_FONT_NOUN:
1387 case LFUN_FONT_ROMAN:
1388 case LFUN_FONT_DEFAULT:
1389 flag.setEnabled(true);
1392 // we just need to be in math mode to enable that
1393 case LFUN_MATH_SIZE:
1394 case LFUN_MATH_SPACE:
1395 case LFUN_MATH_EXTERN:
1396 flag.setEnabled(true);
1399 case LFUN_FONT_UNDERLINE:
1400 case LFUN_FONT_FRAK:
1401 flag.setEnabled(currentMode() != TEXT_MODE);
1404 case LFUN_MATH_FONT_STYLE: {
1405 bool const textarg =
1406 arg == "textbf" || arg == "textsf" ||
1407 arg == "textrm" || arg == "textmd" ||
1408 arg == "textit" || arg == "textsc" ||
1409 arg == "textsl" || arg == "textup" ||
1410 arg == "texttt" || arg == "textbb" ||
1411 arg == "textnormal";
1412 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1416 case LFUN_MATH_MODE:
1417 // forbid "math-mode on" in math mode to prevent irritating
1418 // behaviour of menu entries (bug 6709)
1419 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1422 case LFUN_MATH_INSERT:
1423 flag.setEnabled(currentMode() != TEXT_MODE);
1426 case LFUN_MATH_AMS_MATRIX:
1427 case LFUN_MATH_MATRIX:
1428 flag.setEnabled(currentMode() == MATH_MODE);
1431 case LFUN_INSET_INSERT: {
1432 // Don't test createMathInset_fromDialogStr(), since
1433 // getStatus is not called with a valid reference and the
1434 // dialog would not be applicable.
1435 string const name = cmd.getArg(0);
1436 flag.setEnabled(name == "ref" || name == "mathspace");
1440 case LFUN_DIALOG_SHOW_NEW_INSET: {
1441 docstring const & name = cmd.argument();
1442 if (name == "space")
1443 flag.setEnabled(false);
1448 case LFUN_MATH_DELIM:
1449 case LFUN_MATH_BIGDELIM:
1450 // Don't do this with multi-cell selections
1451 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1454 case LFUN_MATH_MACRO_FOLD:
1455 case LFUN_MATH_MACRO_UNFOLD: {
1457 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1458 flag.setEnabled(found);
1462 case LFUN_SPECIALCHAR_INSERT:
1463 case LFUN_SCRIPT_INSERT:
1464 // FIXME: These would probably make sense in math-text mode
1465 flag.setEnabled(false);
1468 case LFUN_CAPTION_INSERT:
1469 flag.setEnabled(false);
1472 case LFUN_SPACE_INSERT: {
1473 docstring const & name = cmd.argument();
1474 if (name == "visible")
1475 flag.setEnabled(false);
1479 case LFUN_INSET_DISSOLVE:
1480 flag.setEnabled(!asHullInset());
1484 docstring const & name = cmd.argument();
1485 if (name == "html" || name == "latex")
1486 flag.setEnabled(false);
1490 case LFUN_MATH_LIMITS: {
1492 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1493 in = &cur.nextMath();
1494 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1495 in = &cur.prevMath();
1496 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1497 in = cur.cell().back().nucleus();
1499 if (!cmd.argument().empty()) {
1500 if (cmd.argument() == "limits")
1501 flag.setOnOff(in->limits() == LIMITS);
1502 else if (cmd.argument() == "nolimits")
1503 flag.setOnOff(in->limits() == NO_LIMITS);
1505 flag.setOnOff(in->limits() == AUTO_LIMITS);
1507 flag.setEnabled(true);
1509 flag.setEnabled(false);
1521 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1524 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1525 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1526 enter_front ? idxFirst(cur) : idxLast(cur);
1528 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1532 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1535 int dist_min = 1000000;
1536 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1537 int const d = cell(i).dist(cur.bv(), x, y);
1546 MathData & ar = cell(idx_min);
1548 cur.idx() = idx_min;
1549 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1551 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1552 if (dist_min == 0) {
1554 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1555 if (ar[i]->covers(cur.bv(), x, y))
1556 return ar[i].nucleus()->editXY(cur, x, y);
1562 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1564 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1565 BufferView & bv = cur.bv();
1566 if (cmd.button() == mouse_button::button3) {
1567 // Don't do anything if we right-click a
1568 // selection, a context menu will popup.
1569 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1570 && cur < bv.cursor().selectionEnd()) {
1571 cur.noScreenUpdate();
1576 // set cursor after the inset if x is nearer to that position (bug 9748)
1577 cur.moveToClosestEdge(cmd.x(), true);
1579 bool do_selection = cmd.button() == mouse_button::button1
1580 && cmd.modifier() == ShiftModifier;
1581 bv.mouseSetCursor(cur, do_selection);
1582 if (cmd.button() == mouse_button::button1) {
1583 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1584 // Update the cursor update flags as needed:
1586 // Update::Decoration: tells to update the decoration
1587 // (visual box corners that define
1589 // Update::FitCursor: adjust the screen to the cursor
1590 // position if needed
1591 // cur.result().update(): don't overwrite previously set flags.
1592 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1593 | cur.result().screenUpdate());
1594 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1595 if (cap::selection()) {
1596 // See comment in Text::dispatch why we do this
1597 cap::copySelectionToStack();
1598 cmd = FuncRequest(LFUN_PASTE, "0");
1599 doDispatch(bv.cursor(), cmd);
1602 asArray(theSelection().get(), ar);
1603 bv.cursor().insert(ar);
1609 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1611 // only select with button 1
1612 if (cmd.button() != mouse_button::button1)
1615 Cursor & bvcur = cur.bv().cursor();
1617 // ignore motions deeper nested than the real anchor
1618 if (!bvcur.realAnchor().hasPart(cur)) {
1623 // set cursor after the inset if x is nearer to that position (bug 9748)
1624 cur.moveToClosestEdge(cmd.x());
1626 CursorSlice old = bvcur.top();
1628 // We continue with our existing selection or start a new one, so don't
1629 // reset the anchor.
1630 bvcur.setCursor(cur);
1631 // Did we actually move?
1632 if (cur.top() == old)
1633 // We didn't move one iota, so no need to change selection status
1634 // or update the screen.
1635 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1637 bvcur.setSelection();
1641 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1643 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1645 if (cmd.button() == mouse_button::button1) {
1646 if (!cur.selection())
1647 cur.noScreenUpdate();
1649 Cursor & bvcur = cur.bv().cursor();
1650 bvcur.selection(true);
1659 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1661 // try auto-correction
1662 if (lyxrc.autocorrection_math && cur.pos() != 0
1663 && math_autocorrect(cur, c))
1666 //lyxerr << "interpret 2: '" << c << "'" << endl;
1667 docstring save_selection;
1668 if (c == '^' || c == '_')
1669 save_selection = grabAndEraseSelection(cur);
1672 Buffer * buf = cur.buffer();
1675 if (cur.inMacroMode()) {
1676 docstring name = cur.macroName();
1678 /// are we currently typing '#1' or '#2' or...?
1679 if (name == "\\#") {
1682 if (n >= 1 && n <= 9)
1683 cur.insert(new InsetMathMacroArgument(n));
1687 // do not finish macro for known * commands
1688 bool star_macro = c == '*'
1689 && (in_word_set(name.substr(1) + '*')
1690 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1691 if (isAlphaASCII(c) || star_macro) {
1692 cur.activeMacro()->setName(name + docstring(1, c));
1696 // handle 'special char' macros
1701 if (currentMode() != InsetMath::MATH_MODE)
1702 cur.niceInsert(createInsetMath("textbackslash", buf));
1704 cur.niceInsert(createInsetMath("backslash", buf));
1705 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1707 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1708 } else if (c == '{' || c == '%') {
1709 //using the saved selection as argument
1710 InsetMathUnknown * p = cur.activeMacro();
1712 MathData sel(cur.buffer());
1713 asArray(p->selection(), sel);
1716 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1718 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1719 } else if (c == '#') {
1720 LASSERT(cur.activeMacro(), return false);
1721 cur.activeMacro()->setName(name + docstring(1, c));
1724 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1729 // One character big delimiters. The others are handled in
1730 // interpretString().
1731 latexkeys const * l = in_word_set(name.substr(1));
1732 if (name[0] == '\\' && l && l->inset == "big") {
1736 delim = from_ascii("\\{");
1739 delim = from_ascii("\\}");
1742 delim = docstring(1, c);
1745 if (InsetMathBig::isBigInsetDelim(delim)) {
1746 // name + delim ared a valid InsetMathBig.
1747 // We can't use cur.macroModeClose() because
1748 // it does not handle delim.
1749 InsetMathUnknown * p = cur.activeMacro();
1752 cur.cell().erase(cur.pos());
1753 cur.plainInsert(MathAtom(
1754 new InsetMathBig(name.substr(1), delim)));
1757 } else if (name == "\\smash" && c == '[') {
1758 // We can't use cur.macroModeClose() because
1759 // it would create an InsetMathPhantom
1760 InsetMathUnknown * p = cur.activeMacro();
1762 interpretChar(cur, c);
1766 // leave macro mode and try again if necessary
1767 if (cur.macroModeClose()) {
1768 MathAtom const atom = cur.prevAtom();
1769 if (atom->asNestInset() && atom->isActive()) {
1771 cur.nextInset()->edit(cur, true);
1775 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1777 interpretChar(cur, c);
1782 // just clear selection on pressing the space bar
1783 if (cur.selection() && c == ' ') {
1784 cur.selection(false);
1789 //lyxerr << "starting with macro" << endl;
1790 bool reduced = cap::reduceSelectionToOneCell(cur);
1791 if (reduced || !cur.selection()) {
1792 cur.recordUndoInset();
1793 docstring const safe = cap::grabAndEraseSelection(cur);
1794 if (!cur.inRegexped())
1795 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1797 cur.niceInsert(createInsetMath("backslash", buf));
1805 if (currentMode() != InsetMath::MATH_MODE)
1811 if (currentMode() != InsetMath::MATH_MODE) {
1812 // insert spaces in text or undecided mode,
1813 // but suppress direct insertion of two spaces in a row
1814 // the still allows typing '<space>a<space>' and deleting the 'a', but
1815 // it is better than nothing...
1816 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1818 // FIXME: we have to enable full redraw here because of the
1819 // visual box corners that define the inset. If we know for
1820 // sure that we stay within the same cell we can optimize for
1822 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1826 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1827 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1828 // FIXME: we have to enable full redraw here because of the
1829 // visual box corners that define the inset. If we know for
1830 // sure that we stay within the same cell we can optimize for
1832 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1836 if (cur.popForward()) {
1837 // FIXME: we have to enable full redraw here because of the
1838 // visual box corners that define the inset. If we know for
1839 // sure that we stay within the same cell we can optimize for
1841 //cur.screenUpdateFlags(Update::FitCursor);
1845 // if we are at the very end, leave the formula
1846 return cur.pos() != cur.lastpos();
1849 // These should be treated differently when not in text mode:
1850 if (cur.inRegexped()) {
1853 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1860 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1863 cur.niceInsert(createInsetMath("sim", buf));
1869 } else if (currentMode() != InsetMath::TEXT_MODE) {
1871 script(cur, false, save_selection);
1875 script(cur, true, save_selection);
1879 cur.niceInsert(createInsetMath("sim", buf));
1882 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1883 MathAtom at = createInsetMath("text", buf);
1884 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1891 cur.niceInsert(createInsetMath("textasciicircum", buf));
1895 cur.niceInsert(createInsetMath("textasciitilde", buf));
1900 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1901 c == '%' || c == '_') {
1902 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1906 // no special circumstances, so insert the character without any fuss
1912 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1914 if (str == "\\limits" || str == "\\nolimits") {
1915 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1916 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1919 cur.message(bformat(_("Cannot apply %1$s here."), str));
1923 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1925 if (!cur.empty() && cur.pos() > 0 &&
1926 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1927 if (InsetMathBig::isBigInsetDelim(str)) {
1928 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1929 if (prev[0] == '\\') {
1930 prev = prev.substr(1);
1931 latexkeys const * l = in_word_set(prev);
1932 if (l && l->inset == "big") {
1933 cur.recordUndoSelection();
1934 cur.cell()[cur.pos() - 1] =
1935 MathAtom(new InsetMathBig(prev, str));
1945 bool InsetMathNest::script(Cursor & cur, bool up)
1947 return script(cur, up, docstring());
1951 bool InsetMathNest::script(Cursor & cur, bool up,
1952 docstring const & save_selection)
1954 // Hack to get \^ and \_ working
1955 //lyxerr << "handling script: up: " << up << endl;
1956 if (cur.inMacroMode() && cur.macroName() == "\\") {
1958 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1960 interpretChar(cur, '_');
1964 cur.macroModeClose();
1965 if (asScriptInset() && cur.idx() == 0) {
1966 // we are in a nucleus of a script inset, move to _our_ script
1967 InsetMathScript * inset = asScriptInset();
1968 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1970 cur.idx() = inset->idxOfScript(up);
1972 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1974 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1977 cur.idx() = inset->idxOfScript(up);
1978 cur.pos() = cur.lastpos();
1980 // convert the thing to our left to a scriptinset or create a new
1981 // one if in the very first position of the array
1982 if (cur.pos() == 0) {
1983 //lyxerr << "new scriptinset" << endl;
1984 cur.insert(new InsetMathScript(buffer_, up));
1986 //lyxerr << "converting prev atom " << endl;
1987 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1990 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1991 // See comment in MathParser.cpp for special handling of {}-bases
1997 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1998 cur.niceInsert(save_selection);
2000 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2005 bool InsetMathNest::completionSupported(Cursor const & cur) const
2007 return cur.inMacroMode();
2011 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2013 return cur.inMacroMode();
2017 bool InsetMathNest::automaticInlineCompletion() const
2019 return lyxrc.completion_inline_math;
2023 bool InsetMathNest::automaticPopupCompletion() const
2025 return lyxrc.completion_popup_math;
2029 CompletionList const *
2030 InsetMathNest::createCompletionList(Cursor const & cur) const
2032 if (!cur.inMacroMode())
2035 return new MathCompletionList(cur);
2039 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2041 if (!cur.inMacroMode())
2044 return cur.activeMacro()->name();
2048 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2051 if (!cur.inMacroMode())
2054 // append completion to active macro
2055 InsetMathUnknown * inset = cur.activeMacro();
2056 inset->setName(inset->name() + s);
2061 // FIXME: this creates duplicates in the completion popup
2062 // which looks ugly. Moreover the changes the list lengths
2063 // which seems to confuse the popup as well.
2064 MathCompletionList::addToFavorites(inset->name());
2066 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2073 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2074 Dimension & dim) const
2076 Inset const * inset = cur.activeMacro();
2080 // get inset dimensions
2081 dim = cur.bv().coordCache().insets().dim(inset);
2082 // FIXME: these 3 are no accurate, but should depend on the font.
2083 // Now the popup jumps down if you enter a char with descent > 0.
2088 Point xy = cur.bv().coordCache().insets().xy(inset);
2094 ////////////////////////////////////////////////////////////////////
2096 MathCompletionList::MathCompletionList(Cursor const & cur)
2098 // fill it with macros from the buffer
2099 MacroNameSet macros;
2100 cur.buffer()->listMacroNames(macros);
2101 MacroNameSet::const_iterator it;
2102 for (it = macros.begin(); it != macros.end(); ++it) {
2103 if (cur.buffer()->getMacro(*it, cur, false))
2104 locals.push_back("\\" + *it);
2106 sort(locals.begin(), locals.end());
2108 if (!globals.empty())
2111 // fill in global macros
2113 MacroTable::globalMacros().getMacroNames(macros, false);
2114 //lyxerr << "Globals completion macros: ";
2115 for (it = macros.begin(); it != macros.end(); ++it) {
2116 //lyxerr << "\\" + *it << " ";
2117 globals.push_back("\\" + *it);
2119 //lyxerr << std::endl;
2121 // fill in global commands
2122 globals.push_back(from_ascii("\\boxed"));
2123 globals.push_back(from_ascii("\\fbox"));
2124 globals.push_back(from_ascii("\\framebox"));
2125 globals.push_back(from_ascii("\\makebox"));
2126 globals.push_back(from_ascii("\\kern"));
2127 globals.push_back(from_ascii("\\xhookrightarrow"));
2128 globals.push_back(from_ascii("\\xhookleftarrow"));
2129 globals.push_back(from_ascii("\\xrightarrow"));
2130 globals.push_back(from_ascii("\\xRightarrow"));
2131 globals.push_back(from_ascii("\\xrightharpoondown"));
2132 globals.push_back(from_ascii("\\xrightharpoonup"));
2133 globals.push_back(from_ascii("\\xrightleftharpoons"));
2134 globals.push_back(from_ascii("\\xleftarrow"));
2135 globals.push_back(from_ascii("\\xLeftarrow"));
2136 globals.push_back(from_ascii("\\xleftharpoondown"));
2137 globals.push_back(from_ascii("\\xleftharpoonup"));
2138 globals.push_back(from_ascii("\\xleftrightarrow"));
2139 globals.push_back(from_ascii("\\xLeftrightarrow"));
2140 globals.push_back(from_ascii("\\xleftrightharpoons"));
2141 globals.push_back(from_ascii("\\xmapsto"));
2142 globals.push_back(from_ascii("\\split"));
2143 globals.push_back(from_ascii("\\gathered"));
2144 globals.push_back(from_ascii("\\aligned"));
2145 globals.push_back(from_ascii("\\alignedat"));
2146 globals.push_back(from_ascii("\\cases"));
2147 globals.push_back(from_ascii("\\substack"));
2148 globals.push_back(from_ascii("\\xymatrix"));
2149 globals.push_back(from_ascii("\\Diagram"));
2150 globals.push_back(from_ascii("\\subarray"));
2151 globals.push_back(from_ascii("\\array"));
2152 globals.push_back(from_ascii("\\sqrt"));
2153 globals.push_back(from_ascii("\\root"));
2154 globals.push_back(from_ascii("\\tabular"));
2155 globals.push_back(from_ascii("\\sideset"));
2156 globals.push_back(from_ascii("\\stackrel"));
2157 globals.push_back(from_ascii("\\stackrelthree"));
2158 globals.push_back(from_ascii("\\binom"));
2159 globals.push_back(from_ascii("\\choose"));
2160 globals.push_back(from_ascii("\\brace"));
2161 globals.push_back(from_ascii("\\brack"));
2162 globals.push_back(from_ascii("\\frac"));
2163 globals.push_back(from_ascii("\\over"));
2164 globals.push_back(from_ascii("\\nicefrac"));
2165 globals.push_back(from_ascii("\\unitfrac"));
2166 globals.push_back(from_ascii("\\unitfracthree"));
2167 globals.push_back(from_ascii("\\unitone"));
2168 globals.push_back(from_ascii("\\unittwo"));
2169 globals.push_back(from_ascii("\\infer"));
2170 globals.push_back(from_ascii("\\atop"));
2171 globals.push_back(from_ascii("\\lefteqn"));
2172 globals.push_back(from_ascii("\\boldsymbol"));
2173 globals.push_back(from_ascii("\\bm"));
2174 globals.push_back(from_ascii("\\color"));
2175 globals.push_back(from_ascii("\\normalcolor"));
2176 globals.push_back(from_ascii("\\textcolor"));
2177 globals.push_back(from_ascii("\\cfrac"));
2178 globals.push_back(from_ascii("\\cfracleft"));
2179 globals.push_back(from_ascii("\\cfracright"));
2180 globals.push_back(from_ascii("\\dfrac"));
2181 globals.push_back(from_ascii("\\tfrac"));
2182 globals.push_back(from_ascii("\\dbinom"));
2183 globals.push_back(from_ascii("\\tbinom"));
2184 globals.push_back(from_ascii("\\hphantom"));
2185 globals.push_back(from_ascii("\\phantom"));
2186 globals.push_back(from_ascii("\\vphantom"));
2187 globals.push_back(from_ascii("\\cancel"));
2188 globals.push_back(from_ascii("\\bcancel"));
2189 globals.push_back(from_ascii("\\xcancel"));
2190 globals.push_back(from_ascii("\\cancelto"));
2191 globals.push_back(from_ascii("\\smash"));
2192 globals.push_back(from_ascii("\\mathclap"));
2193 globals.push_back(from_ascii("\\mathllap"));
2194 globals.push_back(from_ascii("\\mathrlap"));
2195 globals.push_back(from_ascii("\\ensuremath"));
2196 MathWordList const & words = mathedWordList();
2197 MathWordList::const_iterator it2;
2198 //lyxerr << "Globals completion commands: ";
2199 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2200 if (it2->second.inset != "macro" && !it2->second.hidden) {
2201 // macros are already read from MacroTable::globalMacros()
2202 globals.push_back('\\' + it2->first);
2203 //lyxerr << '\\' + it2->first << ' ';
2206 //lyxerr << std::endl;
2207 sort(globals.begin(), globals.end());
2211 MathCompletionList::~MathCompletionList()
2216 size_type MathCompletionList::size() const
2218 return locals.size() + globals.size();
2222 docstring const & MathCompletionList::data(size_t idx) const
2224 size_t lsize = locals.size();
2226 return globals[idx - lsize];
2232 std::string MathCompletionList::icon(size_t idx) const
2234 // get the latex command
2236 size_t lsize = locals.size();
2238 cmd = globals[idx - lsize];
2242 // get the icon name by stripping the backslash
2243 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2244 if (icon_name.empty())
2245 return std::string();
2246 return "math/" + to_utf8(icon_name);
2249 std::vector<docstring> MathCompletionList::globals;