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"
34 #include "MathFactory.h"
35 #include "InsetMathMacro.h"
36 #include "InsetMathMacroArgument.h"
37 #include "MathParser.h"
38 #include "MathStream.h"
39 #include "MathSupport.h"
42 #include "BufferParams.h"
43 #include "BufferView.h"
44 #include "CoordCache.h"
46 #include "CutAndPaste.h"
47 #include "DispatchResult.h"
49 #include "FuncRequest.h"
50 #include "FuncStatus.h"
51 #include "LaTeXFeatures.h"
54 #include "MetricsInfo.h"
55 #include "OutputParams.h"
59 #include "frontends/Application.h"
60 #include "frontends/Clipboard.h"
61 #include "frontends/Painter.h"
62 #include "frontends/Selection.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
75 using namespace lyx::support;
79 using cap::copySelection;
80 using cap::grabAndEraseSelection;
81 using cap::cutSelection;
82 using cap::replaceSelection;
83 using cap::selClearOrDel;
86 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
87 : InsetMath(buf), cells_(nargs), lock_(false)
93 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
94 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
98 InsetMathNest::~InsetMathNest()
100 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
101 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
102 for (; it != end; ++it)
104 it->first->clearLastInset(this);
108 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
110 cells_ = inset.cells_;
112 mouse_hover_.clear();
113 InsetMath::operator=(inset);
118 void InsetMathNest::setBuffer(Buffer & buffer)
120 InsetMath::setBuffer(buffer);
121 for (idx_type i = 0, n = nargs(); i != n; ++i) {
122 MathData & data = cell(i);
123 for (size_t j = 0; j != data.size(); ++j)
124 data[j].nucleus()->setBuffer(buffer);
129 InsetMath::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)
193 for (idx_type i = 0, n = nargs(); i != n; ++i)
194 cell(i).updateBuffer(it, utype);
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() = cur.lastpos();
227 bool InsetMathNest::idxBackward(Cursor & cur) const
233 bool InsetMathNest::idxFirst(Cursor & cur) const
235 LASSERT(&cur.inset() == this, return false);
244 bool InsetMathNest::idxLast(Cursor & cur) const
246 LASSERT(&cur.inset() == this, return false);
249 cur.idx() = cur.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 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);
349 void InsetMathNest::normalize(NormalStream & os) const
352 for (size_t i = 0; i < nargs(); ++i)
353 os << ' ' << cell(i);
358 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
360 WriteStream wi(os, runparams.moving_arg, true,
361 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
363 wi.strikeoutMath(runparams.inDeletedInset
364 && (!LaTeXFeatures::isAvailable("dvipost")
365 || (runparams.flavor != OutputParams::LATEX
366 && runparams.flavor != OutputParams::DVILUATEX)));
367 if (runparams.inulemcmd) {
368 wi.ulemCmd(WriteStream::UNDERLINE);
369 if (runparams.local_font) {
370 FontInfo f = runparams.local_font->fontInfo();
371 if (f.strikeout() == FONT_ON)
372 wi.ulemCmd(WriteStream::STRIKEOUT);
375 wi.canBreakLine(os.canBreakLine());
376 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
379 // Reset parbreak status after a math inset.
381 os.canBreakLine(wi.canBreakLine());
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?
527 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
529 //LYXERR0("InsetMathNest: request: " << cmd);
531 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
533 FuncCode const act = cmd.action();
536 case LFUN_CLIPBOARD_PASTE:
537 parseflg |= Parse::VERBATIM;
540 if (cur.currentMode() != MATH_MODE)
541 parseflg |= Parse::TEXTMODE;
542 cur.recordUndoSelection();
543 cur.message(_("Paste"));
544 replaceSelection(cur);
546 if (cmd.argument().empty() && !theClipboard().isInternal())
547 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
550 idocstringstream is(cmd.argument());
552 topaste = cap::selection(n, buffer().params().documentClassPtr());
554 cur.niceInsert(topaste, parseflg, false);
555 cur.clearSelection(); // bug 393
556 cur.forceBufferUpdate();
563 cutSelection(cur, true);
564 cur.message(_("Cut"));
565 // Prevent stale position >= size crash
566 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
568 cur.forceBufferUpdate();
573 cur.message(_("Copy"));
576 case LFUN_MOUSE_PRESS:
577 lfunMousePress(cur, cmd);
580 case LFUN_MOUSE_MOTION:
581 lfunMouseMotion(cur, cmd);
584 case LFUN_MOUSE_RELEASE:
585 lfunMouseRelease(cur, cmd);
588 case LFUN_FINISHED_LEFT: // in math, left is backwards
589 case LFUN_FINISHED_BACKWARD:
590 cur.bv().cursor() = cur;
593 case LFUN_FINISHED_RIGHT: // in math, right is forward
594 case LFUN_FINISHED_FORWARD:
596 cur.bv().cursor() = cur;
599 case LFUN_WORD_RIGHT:
601 case LFUN_WORD_BACKWARD:
602 case LFUN_WORD_FORWARD:
603 case LFUN_CHAR_RIGHT:
605 case LFUN_CHAR_BACKWARD:
606 case LFUN_CHAR_FORWARD:
607 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
609 case LFUN_WORD_RIGHT_SELECT:
610 case LFUN_WORD_LEFT_SELECT:
611 case LFUN_WORD_BACKWARD_SELECT:
612 case LFUN_WORD_FORWARD_SELECT:
613 case LFUN_CHAR_RIGHT_SELECT:
614 case LFUN_CHAR_LEFT_SELECT:
615 case LFUN_CHAR_BACKWARD_SELECT:
616 case LFUN_CHAR_FORWARD_SELECT: {
617 // are we in a selection?
618 bool select = (act == LFUN_WORD_RIGHT_SELECT
619 || act == LFUN_WORD_LEFT_SELECT
620 || act == LFUN_WORD_BACKWARD_SELECT
621 || act == LFUN_WORD_FORWARD_SELECT
622 || act == LFUN_CHAR_RIGHT_SELECT
623 || act == LFUN_CHAR_LEFT_SELECT
624 || act == LFUN_CHAR_BACKWARD_SELECT
625 || act == LFUN_CHAR_FORWARD_SELECT);
627 bool word = (act == LFUN_WORD_RIGHT_SELECT
628 || act == LFUN_WORD_LEFT_SELECT
629 || act == LFUN_WORD_BACKWARD_SELECT
630 || act == LFUN_WORD_FORWARD_SELECT
631 || act == LFUN_WORD_RIGHT
632 || act == LFUN_WORD_LEFT
633 || act == LFUN_WORD_BACKWARD
634 || act == LFUN_WORD_FORWARD);
635 // are we moving forward or backwards?
636 // If the command was RIGHT or LEFT, then whether we're moving forward
637 // or backwards depends on the cursor movement mode (logical or visual):
638 // * in visual mode, since math is always LTR, right -> forward,
640 // * in logical mode, the mapping is determined by the
641 // reverseDirectionNeeded() function
644 FuncCode finish_lfun;
646 if (act == LFUN_CHAR_FORWARD
647 || act == LFUN_CHAR_FORWARD_SELECT
648 || act == LFUN_WORD_FORWARD
649 || act == LFUN_WORD_FORWARD_SELECT) {
651 finish_lfun = LFUN_FINISHED_FORWARD;
653 else if (act == LFUN_CHAR_BACKWARD
654 || act == LFUN_CHAR_BACKWARD_SELECT
655 || act == LFUN_WORD_BACKWARD
656 || act == LFUN_WORD_BACKWARD_SELECT) {
658 finish_lfun = LFUN_FINISHED_BACKWARD;
661 bool right = (act == LFUN_CHAR_RIGHT_SELECT
662 || act == LFUN_CHAR_RIGHT
663 || act == LFUN_WORD_RIGHT_SELECT
664 || act == LFUN_WORD_RIGHT);
665 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
671 finish_lfun = LFUN_FINISHED_RIGHT;
673 finish_lfun = LFUN_FINISHED_LEFT;
675 // Now that we know exactly what we want to do, let's do it!
676 cur.selHandle(select);
678 cur.macroModeClose();
679 // try moving forward or backwards as necessary...
680 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
681 // ... and if movement failed, then finish forward or backwards
683 cmd = FuncRequest(finish_lfun);
691 case LFUN_PARAGRAPH_UP:
692 case LFUN_PARAGRAPH_DOWN:
693 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
695 case LFUN_DOWN_SELECT:
697 case LFUN_PARAGRAPH_UP_SELECT:
698 case LFUN_PARAGRAPH_DOWN_SELECT: {
699 // close active macro
700 if (cur.inMacroMode()) {
701 cur.macroModeClose();
705 // stop/start the selection
706 bool select = act == LFUN_DOWN_SELECT
707 || act == LFUN_UP_SELECT
708 || act == LFUN_PARAGRAPH_DOWN_SELECT
709 || act == LFUN_PARAGRAPH_UP_SELECT;
710 cur.selHandle(select);
712 // handle autocorrect:
713 if (lyxrc.autocorrection_math && cur.autocorrect()) {
714 cur.autocorrect() = false;
715 cur.message(_("Autocorrect Off ('!' to enter)"));
719 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
720 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
721 bool successful = cur.upDownInMath(up);
725 if (cur.fixIfBroken())
726 // FIXME: Something bad happened. We pass the corrected Cursor
727 // instead of letting things go worse.
730 // We did not manage to move the cursor.
735 case LFUN_MOUSE_DOUBLE:
736 case LFUN_WORD_SELECT:
738 cur.bv().mouseSetCursor(cur);
739 cur.pos() = cur.lastpos();
740 cur.bv().mouseSetCursor(cur, true);
743 case LFUN_MOUSE_TRIPLE:
746 cur.bv().mouseSetCursor(cur);
747 cur.idx() = cur.lastidx();
748 cur.pos() = cur.lastpos();
749 cur.bv().mouseSetCursor(cur, true);
752 case LFUN_LINE_BEGIN:
753 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
755 case LFUN_LINE_BEGIN_SELECT:
756 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
757 act == LFUN_WORD_LEFT_SELECT ||
758 act == LFUN_LINE_BEGIN_SELECT);
759 cur.macroModeClose();
760 if (cur.pos() != 0) {
762 } else if (cur.col() != 0) {
763 cur.idx() -= cur.col();
765 } else if (cur.idx() != 0) {
769 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
775 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
777 case LFUN_LINE_END_SELECT:
778 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
779 act == LFUN_WORD_RIGHT_SELECT ||
780 act == LFUN_LINE_END_SELECT);
781 cur.macroModeClose();
783 if (cur.pos() != cur.lastpos()) {
784 cur.pos() = cur.lastpos();
785 } else if (ncols() && (cur.col() != cur.lastcol())) {
786 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
787 cur.pos() = cur.lastpos();
788 } else if (cur.idx() != cur.lastidx()) {
789 cur.idx() = cur.lastidx();
790 cur.pos() = cur.lastpos();
792 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
797 case LFUN_CELL_FORWARD:
798 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
799 cur.inset().idxNext(cur);
802 case LFUN_CELL_BACKWARD:
803 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
804 cur.inset().idxPrev(cur);
807 case LFUN_WORD_DELETE_BACKWARD:
808 case LFUN_CHAR_DELETE_BACKWARD:
810 // May affect external cell:
811 cur.recordUndoInset();
812 else if (!cur.inMacroMode())
813 cur.recordUndoSelection();
814 // if the inset can not be removed from within, delete it
815 if (!cur.backspace(cmd.getArg(0) == "force")) {
816 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
817 cur.innerText()->dispatch(cur, cmd);
821 case LFUN_WORD_DELETE_FORWARD:
822 case LFUN_CHAR_DELETE_FORWARD:
823 if (cur.pos() == cur.lastpos())
824 // May affect external cell:
825 cur.recordUndoInset();
827 cur.recordUndoSelection();
828 // if the inset can not be removed from within, delete it
829 if (!cur.erase(cmd.getArg(0) == "force")) {
830 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
831 cur.innerText()->dispatch(cur, cmd);
837 cur.clearSelection();
839 if (cur.inMacroMode())
840 cur.macroModeClose(true);
842 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
848 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
849 // that is traversed by a single <CursorLeft>/<CursorRight>.
850 case LFUN_INSET_TOGGLE:
856 case LFUN_SELF_INSERT:
857 // special case first for big delimiters
858 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
861 for (char_type c : cmd.argument()) {
862 // Don't record undo steps if we are in macro mode and thus
863 // cmd.argument is the next character of the macro name.
864 // Otherwise we'll get an invalid cursor if we undo after
865 // the macro was finished and the macro is a known command,
866 // e.g. sqrt. Cursor::macroModeClose replaces in this case
867 // the InsetMathUnknown with name "frac" by an empty
868 // InsetMathFrac -> a pos value > 0 is invalid.
869 // A side effect is that an undo before the macro is finished
870 // undoes the complete macro, not only the last character.
871 // At the time we hit '\' we are not in macro mode, still.
872 if (!cur.inMacroMode())
873 cur.recordUndoSelection();
875 // special handling of space. If we insert an inset
876 // via macro mode, we want to put the cursor inside it
877 // if relevant. Think typing "\frac<space>".
879 && cur.inMacroMode() && cur.macroName() != "\\"
880 && cur.macroModeClose() && cur.pos() > 0) {
881 MathAtom const atom = cur.prevAtom();
882 if (atom->asNestInset() && atom->isActive()) {
884 cur.pushBackward(*cur.nextInset());
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()));
904 cur.setScreenPos(x, y);
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 = from_ascii("matrix");
1099 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1103 case LFUN_MATH_DELIM: {
1105 docstring rs = split(cmd.argument(), ls, ' ');
1106 // Reasonable default values
1112 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1116 case LFUN_MATH_BIGDELIM: {
1117 docstring const lname = from_utf8(cmd.getArg(0));
1118 docstring const ldelim = from_utf8(cmd.getArg(1));
1119 docstring const rname = from_utf8(cmd.getArg(2));
1120 docstring const rdelim = from_utf8(cmd.getArg(3));
1121 latexkeys const * l = in_word_set(lname);
1122 bool const have_l = l && l->inset == "big" &&
1123 InsetMathBig::isBigInsetDelim(ldelim);
1124 l = in_word_set(rname);
1125 bool const have_r = l && l->inset == "big" &&
1126 InsetMathBig::isBigInsetDelim(rdelim);
1127 // We mimic LFUN_MATH_DELIM in case we have an empty left
1128 // or right delimiter.
1129 if (have_l || have_r) {
1131 docstring const selection = grabAndEraseSelection(cur);
1134 cur.insert(MathAtom(new InsetMathBig(lname,
1136 // first insert the right delimiter and then go back
1137 // and re-insert the selection (bug 7088)
1139 cur.insert(MathAtom(new InsetMathBig(rname,
1143 cur.niceInsert(selection);
1145 // Don't call cur.undispatched() if we did nothing, this would
1146 // lead to infinite recursion via Text::dispatch().
1150 case LFUN_SPACE_INSERT: {
1151 cur.recordUndoSelection();
1152 string const name = cmd.getArg(0);
1153 if (name == "normal")
1154 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1155 else if (name == "protected")
1156 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1157 else if (name == "thin" || name == "med" || name == "thick")
1158 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1159 else if (name == "hfill*")
1160 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1161 else if (name == "quad" || name == "qquad" ||
1162 name == "enspace" || name == "enskip" ||
1163 name == "negthinspace" || name == "negmedspace" ||
1164 name == "negthickspace" || name == "hfill")
1165 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1166 else if (name == "hspace" || name == "hspace*") {
1167 string const len = cmd.getArg(1);
1168 if (len.empty() || !isValidLength(len)) {
1169 lyxerr << "LyX function 'space-insert " << name << "' "
1170 "needs a valid length argument." << endl;
1173 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1175 cur.insert(MathAtom(new InsetMathSpace));
1179 case LFUN_MATH_SPACE:
1180 cur.recordUndoSelection();
1181 if (cmd.argument().empty())
1182 cur.insert(MathAtom(new InsetMathSpace));
1184 string const name = cmd.getArg(0);
1185 string const len = cmd.getArg(1);
1186 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1190 case LFUN_ERT_INSERT:
1191 // interpret this as if a backslash was typed
1193 interpretChar(cur, '\\');
1196 case LFUN_MATH_SUBSCRIPT:
1197 // interpret this as if a _ was typed
1198 cur.recordUndoSelection();
1199 interpretChar(cur, '_');
1202 case LFUN_MATH_SUPERSCRIPT:
1203 // interpret this as if a ^ was typed
1204 cur.recordUndoSelection();
1205 interpretChar(cur, '^');
1208 case LFUN_MATH_MACRO_FOLD:
1209 case LFUN_MATH_MACRO_UNFOLD: {
1211 bool fold = act == LFUN_MATH_MACRO_FOLD;
1212 bool found = findMacroToFoldUnfold(it, fold);
1214 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1215 cur.recordUndoInset();
1224 case LFUN_QUOTE_INSERT:
1225 // interpret this as if a straight " was typed
1226 cur.recordUndoSelection();
1227 interpretChar(cur, '\"');
1230 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1231 // handling such that "self-insert" works on "arbitrary stuff" too, and
1232 // math-insert only handles special math things like "matrix".
1233 case LFUN_MATH_INSERT: {
1234 cur.recordUndoSelection();
1235 if (cmd.argument() == "^" || cmd.argument() == "_")
1236 interpretChar(cur, cmd.argument()[0]);
1239 asArray(cmd.argument(), ar);
1240 if (cur.selection() && ar.size() == 1
1241 && ar[0]->asNestInset()
1242 && ar[0]->asNestInset()->nargs() > 1)
1243 handleNest(cur, ar[0]);
1245 cur.niceInsert(cmd.argument());
1250 case LFUN_DIALOG_SHOW_NEW_INSET: {
1251 docstring const & name = cmd.argument();
1253 if (name == "ref") {
1254 InsetMathRef tmp(buffer_, name);
1255 data = tmp.createDialogStr();
1256 cur.bv().showDialog(to_utf8(name), data);
1257 } else if (name == "mathspace") {
1258 cur.bv().showDialog(to_utf8(name));
1263 case LFUN_INSET_INSERT: {
1265 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1266 cur.recordUndoSelection();
1268 cur.forceBufferUpdate();
1273 case LFUN_INSET_DISSOLVE:
1274 if (!asHullInset()) {
1275 cur.recordUndoInset();
1281 InsetMath::doDispatch(cur, cmd);
1287 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1288 // look for macro to open/close, but stay in mathed
1289 for (; !it.empty(); it.pop_back()) {
1291 // go backward through the current cell
1292 Inset * inset = it.nextInset();
1293 while (inset && inset->asInsetMath()) {
1294 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1296 // found the an macro to open/close?
1297 if (macro->folded() != fold)
1300 // Wrong folding state.
1301 // If this was the first we see in this slice, look further left,
1303 if (inset != it.nextInset())
1307 // go up if this was the left most position
1313 inset = it.nextInset();
1321 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1322 FuncStatus & flag) const
1324 // the font related toggles
1325 //string tc = "mathnormal";
1327 string const arg = to_utf8(cmd.argument());
1328 switch (cmd.action()) {
1329 case LFUN_INSET_MODIFY:
1330 flag.setEnabled(false);
1333 case LFUN_INSET_MODIFY:
1334 // FIXME: check temporarily disabled
1336 char align = mathcursor::valign();
1337 if (align == '\0') {
1341 if (cmd.argument().empty()) {
1345 if (!contains("tcb", cmd.argument()[0])) {
1349 flag.setOnOff(cmd.argument()[0] == align);
1352 /// We have to handle them since 1.4 blocks all unhandled actions
1353 case LFUN_FONT_ITAL:
1354 case LFUN_FONT_BOLD:
1355 case LFUN_FONT_BOLDSYMBOL:
1356 case LFUN_FONT_SANS:
1357 case LFUN_FONT_EMPH:
1358 case LFUN_FONT_TYPEWRITER:
1359 case LFUN_FONT_NOUN:
1360 case LFUN_FONT_ROMAN:
1361 case LFUN_FONT_DEFAULT:
1362 flag.setEnabled(true);
1365 // we just need to be in math mode to enable that
1366 case LFUN_MATH_SIZE:
1367 case LFUN_MATH_SPACE:
1368 case LFUN_MATH_EXTERN:
1369 flag.setEnabled(true);
1372 case LFUN_FONT_UNDERLINE:
1373 case LFUN_FONT_FRAK:
1374 flag.setEnabled(currentMode() != TEXT_MODE);
1377 case LFUN_MATH_FONT_STYLE: {
1378 bool const textarg =
1379 arg == "textbf" || arg == "textsf" ||
1380 arg == "textrm" || arg == "textmd" ||
1381 arg == "textit" || arg == "textsc" ||
1382 arg == "textsl" || arg == "textup" ||
1383 arg == "texttt" || arg == "textbb" ||
1384 arg == "textnormal";
1385 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1389 case LFUN_MATH_MODE:
1390 // forbid "math-mode on" in math mode to prevent irritating
1391 // behaviour of menu entries (bug 6709)
1392 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1395 case LFUN_MATH_INSERT:
1396 flag.setEnabled(currentMode() != TEXT_MODE);
1399 case LFUN_MATH_AMS_MATRIX:
1400 case LFUN_MATH_MATRIX:
1401 flag.setEnabled(currentMode() == MATH_MODE);
1404 case LFUN_INSET_INSERT: {
1405 // Don't test createMathInset_fromDialogStr(), since
1406 // getStatus is not called with a valid reference and the
1407 // dialog would not be applyable.
1408 string const name = cmd.getArg(0);
1409 flag.setEnabled(name == "ref" || name == "mathspace");
1413 case LFUN_DIALOG_SHOW_NEW_INSET: {
1414 docstring const & name = cmd.argument();
1415 if (name == "space")
1416 flag.setEnabled(false);
1421 case LFUN_MATH_DELIM:
1422 case LFUN_MATH_BIGDELIM:
1423 // Don't do this with multi-cell selections
1424 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1427 case LFUN_MATH_MACRO_FOLD:
1428 case LFUN_MATH_MACRO_UNFOLD: {
1430 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1431 flag.setEnabled(found);
1435 case LFUN_SPECIALCHAR_INSERT:
1436 case LFUN_SCRIPT_INSERT:
1437 // FIXME: These would probably make sense in math-text mode
1438 flag.setEnabled(false);
1441 case LFUN_CAPTION_INSERT:
1442 flag.setEnabled(false);
1445 case LFUN_SPACE_INSERT: {
1446 docstring const & name = cmd.argument();
1447 if (name == "visible")
1448 flag.setEnabled(false);
1452 case LFUN_INSET_DISSOLVE:
1453 flag.setEnabled(!asHullInset());
1457 docstring const & name = cmd.argument();
1458 if (name == "html" || name == "latex")
1459 flag.setEnabled(false);
1471 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1474 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1475 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1476 cur.idx() = enter_front ? 0 : cur.lastidx();
1477 cur.pos() = enter_front ? 0 : cur.lastpos();
1479 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1483 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1486 int dist_min = 1000000;
1487 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1488 int const d = cell(i).dist(cur.bv(), x, y);
1497 MathData & ar = cell(idx_min);
1499 cur.idx() = idx_min;
1500 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1502 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1503 if (dist_min == 0) {
1505 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1506 if (ar[i]->covers(cur.bv(), x, y))
1507 return ar[i].nucleus()->editXY(cur, x, y);
1513 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1515 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1516 BufferView & bv = cur.bv();
1517 if (cmd.button() == mouse_button::button3) {
1518 // Don't do anything if we right-click a
1519 // selection, a context menu will popup.
1520 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1521 && cur < bv.cursor().selectionEnd()) {
1522 cur.noScreenUpdate();
1527 // set cursor after the inset if x is nearer to that position (bug 9748)
1528 cur.moveToClosestEdge(cmd.x(), true);
1530 bool do_selection = cmd.button() == mouse_button::button1
1531 && cmd.modifier() == ShiftModifier;
1532 bv.mouseSetCursor(cur, do_selection);
1533 if (cmd.button() == mouse_button::button1) {
1534 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1535 // Update the cursor update flags as needed:
1537 // Update::Decoration: tells to update the decoration
1538 // (visual box corners that define
1540 // Update::FitCursor: adjust the screen to the cursor
1541 // position if needed
1542 // cur.result().update(): don't overwrite previously set flags.
1543 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1544 | cur.result().screenUpdate());
1545 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1546 if (cap::selection()) {
1547 // See comment in Text::dispatch why we do this
1548 cap::copySelectionToStack();
1549 cmd = FuncRequest(LFUN_PASTE, "0");
1550 doDispatch(bv.cursor(), cmd);
1553 asArray(theSelection().get(), ar);
1554 bv.cursor().insert(ar);
1560 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1562 // only select with button 1
1563 if (cmd.button() != mouse_button::button1)
1566 Cursor & bvcur = cur.bv().cursor();
1568 // ignore motions deeper nested than the real anchor
1569 if (!bvcur.realAnchor().hasPart(cur)) {
1574 // set cursor after the inset if x is nearer to that position (bug 9748)
1575 cur.moveToClosestEdge(cmd.x());
1577 CursorSlice old = bvcur.top();
1579 // We continue with our existing selection or start a new one, so don't
1580 // reset the anchor.
1581 bvcur.setCursor(cur);
1582 // Did we actually move?
1583 if (cur.top() == old)
1584 // We didn't move one iota, so no need to change selection status
1585 // or update the screen.
1586 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1588 bvcur.setSelection();
1592 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1594 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1596 if (cmd.button() == mouse_button::button1) {
1597 if (!cur.selection())
1598 cur.noScreenUpdate();
1600 Cursor & bvcur = cur.bv().cursor();
1601 bvcur.selection(true);
1610 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1612 //lyxerr << "interpret 2: '" << c << "'" << endl;
1613 docstring save_selection;
1614 if (c == '^' || c == '_')
1615 save_selection = grabAndEraseSelection(cur);
1618 Buffer * buf = cur.buffer();
1621 if (cur.inMacroMode()) {
1622 docstring name = cur.macroName();
1624 /// are we currently typing '#1' or '#2' or...?
1625 if (name == "\\#") {
1628 if (n >= 1 && n <= 9)
1629 cur.insert(new InsetMathMacroArgument(n));
1633 // do not finish macro for known * commands
1634 bool star_macro = c == '*'
1635 && (in_word_set(name.substr(1) + '*')
1636 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1637 if (isAlphaASCII(c) || star_macro) {
1638 cur.activeMacro()->setName(name + docstring(1, c));
1642 // handle 'special char' macros
1647 if (currentMode() != InsetMath::MATH_MODE)
1648 cur.niceInsert(createInsetMath("textbackslash", buf));
1650 cur.niceInsert(createInsetMath("backslash", buf));
1651 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1653 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1654 } else if (c == '{' || c == '%') {
1655 //using the saved selection as argument
1656 InsetMathUnknown * p = cur.activeMacro();
1658 MathData sel(cur.buffer());
1659 asArray(p->selection(), sel);
1662 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1664 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1665 } else if (c == '#') {
1666 LASSERT(cur.activeMacro(), return false);
1667 cur.activeMacro()->setName(name + docstring(1, c));
1670 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1675 // One character big delimiters. The others are handled in
1676 // interpretString().
1677 latexkeys const * l = in_word_set(name.substr(1));
1678 if (name[0] == '\\' && l && l->inset == "big") {
1682 delim = from_ascii("\\{");
1685 delim = from_ascii("\\}");
1688 delim = docstring(1, c);
1691 if (InsetMathBig::isBigInsetDelim(delim)) {
1692 // name + delim ared a valid InsetMathBig.
1693 // We can't use cur.macroModeClose() because
1694 // it does not handle delim.
1695 InsetMathUnknown * p = cur.activeMacro();
1698 cur.cell().erase(cur.pos());
1699 cur.plainInsert(MathAtom(
1700 new InsetMathBig(name.substr(1), delim)));
1703 } else if (name == "\\smash" && c == '[') {
1704 // We can't use cur.macroModeClose() because
1705 // it would create an InsetMathPhantom
1706 InsetMathUnknown * p = cur.activeMacro();
1708 interpretChar(cur, c);
1712 // leave macro mode and try again if necessary
1713 if (cur.macroModeClose()) {
1714 MathAtom const atom = cur.prevAtom();
1715 if (atom->asNestInset() && atom->isActive()) {
1717 cur.pushBackward(*cur.nextInset());
1721 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1723 interpretChar(cur, c);
1728 // leave autocorrect mode if necessary
1729 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1730 cur.autocorrect() = false;
1731 cur.message(_("Autocorrect Off ('!' to enter)"));
1734 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1735 cur.autocorrect() = true;
1736 cur.message(_("Autocorrect On (<space> to exit)"));
1740 // just clear selection on pressing the space bar
1741 if (cur.selection() && c == ' ') {
1742 cur.selection(false);
1747 //lyxerr << "starting with macro" << endl;
1748 bool reduced = cap::reduceSelectionToOneCell(cur);
1749 if (reduced || !cur.selection()) {
1750 cur.recordUndoInset();
1751 docstring const safe = cap::grabAndEraseSelection(cur);
1752 if (!cur.inRegexped())
1753 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1755 cur.niceInsert(createInsetMath("backslash", buf));
1763 if (currentMode() != InsetMath::MATH_MODE)
1769 if (currentMode() != InsetMath::MATH_MODE) {
1770 // insert spaces in text or undecided mode,
1771 // but suppress direct insertion of two spaces in a row
1772 // the still allows typing '<space>a<space>' and deleting the 'a', but
1773 // it is better than nothing...
1774 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1776 // FIXME: we have to enable full redraw here because of the
1777 // visual box corners that define the inset. If we know for
1778 // sure that we stay within the same cell we can optimize for
1780 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1784 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1785 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1786 // FIXME: we have to enable full redraw here because of the
1787 // visual box corners that define the inset. If we know for
1788 // sure that we stay within the same cell we can optimize for
1790 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1794 if (cur.popForward()) {
1795 // FIXME: we have to enable full redraw here because of the
1796 // visual box corners that define the inset. If we know for
1797 // sure that we stay within the same cell we can optimize for
1799 //cur.screenUpdateFlags(Update::FitCursor);
1803 // if we are at the very end, leave the formula
1804 return cur.pos() != cur.lastpos();
1807 // These should be treated differently when not in text mode:
1808 if (cur.inRegexped()) {
1811 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1818 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1821 cur.niceInsert(createInsetMath("sim", buf));
1827 } else if (currentMode() != InsetMath::TEXT_MODE) {
1829 script(cur, false, save_selection);
1833 script(cur, true, save_selection);
1837 cur.niceInsert(createInsetMath("sim", buf));
1840 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1841 MathAtom at = createInsetMath("text", buf);
1842 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1849 cur.niceInsert(createInsetMath("textasciicircum", buf));
1853 cur.niceInsert(createInsetMath("textasciitilde", buf));
1858 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1859 c == '%' || c == '_') {
1860 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1865 // try auto-correction
1866 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1867 && math_autocorrect(cur.prevAtom(), c))
1870 // no special circumstances, so insert the character without any fuss
1872 if (lyxrc.autocorrection_math) {
1873 if (!cur.autocorrect())
1874 cur.message(_("Autocorrect Off ('!' to enter)"));
1876 cur.message(_("Autocorrect On (<space> to exit)"));
1882 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1884 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1886 if (!cur.empty() && cur.pos() > 0 &&
1887 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1888 if (InsetMathBig::isBigInsetDelim(str)) {
1889 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1890 if (prev[0] == '\\') {
1891 prev = prev.substr(1);
1892 latexkeys const * l = in_word_set(prev);
1893 if (l && l->inset == "big") {
1894 cur.recordUndoSelection();
1895 cur.cell()[cur.pos() - 1] =
1896 MathAtom(new InsetMathBig(prev, str));
1906 bool InsetMathNest::script(Cursor & cur, bool up)
1908 return script(cur, up, docstring());
1912 bool InsetMathNest::script(Cursor & cur, bool up,
1913 docstring const & save_selection)
1915 // Hack to get \^ and \_ working
1916 //lyxerr << "handling script: up: " << up << endl;
1917 if (cur.inMacroMode() && cur.macroName() == "\\") {
1919 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1921 interpretChar(cur, '_');
1925 cur.macroModeClose();
1926 if (asScriptInset() && cur.idx() == 0) {
1927 // we are in a nucleus of a script inset, move to _our_ script
1928 InsetMathScript * inset = asScriptInset();
1929 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1931 cur.idx() = inset->idxOfScript(up);
1933 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1935 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1938 cur.idx() = inset->idxOfScript(up);
1939 cur.pos() = cur.lastpos();
1941 // convert the thing to our left to a scriptinset or create a new
1942 // one if in the very first position of the array
1943 if (cur.pos() == 0) {
1944 //lyxerr << "new scriptinset" << endl;
1945 cur.insert(new InsetMathScript(buffer_, up));
1947 //lyxerr << "converting prev atom " << endl;
1948 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1951 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1952 // See comment in MathParser.cpp for special handling of {}-bases
1958 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1959 cur.niceInsert(save_selection);
1961 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1966 bool InsetMathNest::completionSupported(Cursor const & cur) const
1968 return cur.inMacroMode();
1972 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1974 return cur.inMacroMode();
1978 bool InsetMathNest::automaticInlineCompletion() const
1980 return lyxrc.completion_inline_math;
1984 bool InsetMathNest::automaticPopupCompletion() const
1986 return lyxrc.completion_popup_math;
1990 CompletionList const *
1991 InsetMathNest::createCompletionList(Cursor const & cur) const
1993 if (!cur.inMacroMode())
1996 return new MathCompletionList(cur);
2000 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2002 if (!cur.inMacroMode())
2005 return cur.activeMacro()->name();
2009 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2012 if (!cur.inMacroMode())
2015 // append completion to active macro
2016 InsetMathUnknown * inset = cur.activeMacro();
2017 inset->setName(inset->name() + s);
2022 // FIXME: this creates duplicates in the completion popup
2023 // which looks ugly. Moreover the changes the list lengths
2025 confuse the popup as well.
2026 MathCompletionList::addToFavorites(inset->name());
2028 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2035 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2036 Dimension & dim) const
2038 Inset const * inset = cur.activeMacro();
2042 // get inset dimensions
2043 dim = cur.bv().coordCache().insets().dim(inset);
2044 // FIXME: these 3 are no accurate, but should depend on the font.
2045 // Now the popup jumps down if you enter a char with descent > 0.
2050 Point xy = cur.bv().coordCache().insets().xy(inset);
2056 ////////////////////////////////////////////////////////////////////
2058 MathCompletionList::MathCompletionList(Cursor const & cur)
2060 // fill it with macros from the buffer
2061 MacroNameSet macros;
2062 cur.buffer()->listMacroNames(macros);
2063 MacroNameSet::const_iterator it;
2064 for (it = macros.begin(); it != macros.end(); ++it) {
2065 if (cur.buffer()->getMacro(*it, cur, false))
2066 locals.push_back("\\" + *it);
2068 sort(locals.begin(), locals.end());
2070 if (!globals.empty())
2073 // fill in global macros
2075 MacroTable::globalMacros().getMacroNames(macros, false);
2076 //lyxerr << "Globals completion macros: ";
2077 for (it = macros.begin(); it != macros.end(); ++it) {
2078 //lyxerr << "\\" + *it << " ";
2079 globals.push_back("\\" + *it);
2081 //lyxerr << std::endl;
2083 // fill in global commands
2084 globals.push_back(from_ascii("\\boxed"));
2085 globals.push_back(from_ascii("\\fbox"));
2086 globals.push_back(from_ascii("\\framebox"));
2087 globals.push_back(from_ascii("\\makebox"));
2088 globals.push_back(from_ascii("\\kern"));
2089 globals.push_back(from_ascii("\\xhookrightarrow"));
2090 globals.push_back(from_ascii("\\xhookleftarrow"));
2091 globals.push_back(from_ascii("\\xrightarrow"));
2092 globals.push_back(from_ascii("\\xRightarrow"));
2093 globals.push_back(from_ascii("\\xrightharpoondown"));
2094 globals.push_back(from_ascii("\\xrightharpoonup"));
2095 globals.push_back(from_ascii("\\xrightleftharpoons"));
2096 globals.push_back(from_ascii("\\xleftarrow"));
2097 globals.push_back(from_ascii("\\xLeftarrow"));
2098 globals.push_back(from_ascii("\\xleftharpoondown"));
2099 globals.push_back(from_ascii("\\xleftharpoonup"));
2100 globals.push_back(from_ascii("\\xleftrightarrow"));
2101 globals.push_back(from_ascii("\\xLeftrightarrow"));
2102 globals.push_back(from_ascii("\\xleftrightharpoons"));
2103 globals.push_back(from_ascii("\\xmapsto"));
2104 globals.push_back(from_ascii("\\split"));
2105 globals.push_back(from_ascii("\\gathered"));
2106 globals.push_back(from_ascii("\\aligned"));
2107 globals.push_back(from_ascii("\\alignedat"));
2108 globals.push_back(from_ascii("\\cases"));
2109 globals.push_back(from_ascii("\\substack"));
2110 globals.push_back(from_ascii("\\xymatrix"));
2111 globals.push_back(from_ascii("\\Diagram"));
2112 globals.push_back(from_ascii("\\subarray"));
2113 globals.push_back(from_ascii("\\array"));
2114 globals.push_back(from_ascii("\\sqrt"));
2115 globals.push_back(from_ascii("\\root"));
2116 globals.push_back(from_ascii("\\tabular"));
2117 globals.push_back(from_ascii("\\sideset"));
2118 globals.push_back(from_ascii("\\stackrel"));
2119 globals.push_back(from_ascii("\\stackrelthree"));
2120 globals.push_back(from_ascii("\\binom"));
2121 globals.push_back(from_ascii("\\choose"));
2122 globals.push_back(from_ascii("\\brace"));
2123 globals.push_back(from_ascii("\\brack"));
2124 globals.push_back(from_ascii("\\frac"));
2125 globals.push_back(from_ascii("\\over"));
2126 globals.push_back(from_ascii("\\nicefrac"));
2127 globals.push_back(from_ascii("\\unitfrac"));
2128 globals.push_back(from_ascii("\\unitfracthree"));
2129 globals.push_back(from_ascii("\\unitone"));
2130 globals.push_back(from_ascii("\\unittwo"));
2131 globals.push_back(from_ascii("\\infer"));
2132 globals.push_back(from_ascii("\\atop"));
2133 globals.push_back(from_ascii("\\lefteqn"));
2134 globals.push_back(from_ascii("\\boldsymbol"));
2135 globals.push_back(from_ascii("\\bm"));
2136 globals.push_back(from_ascii("\\color"));
2137 globals.push_back(from_ascii("\\normalcolor"));
2138 globals.push_back(from_ascii("\\textcolor"));
2139 globals.push_back(from_ascii("\\cfrac"));
2140 globals.push_back(from_ascii("\\cfracleft"));
2141 globals.push_back(from_ascii("\\cfracright"));
2142 globals.push_back(from_ascii("\\dfrac"));
2143 globals.push_back(from_ascii("\\tfrac"));
2144 globals.push_back(from_ascii("\\dbinom"));
2145 globals.push_back(from_ascii("\\tbinom"));
2146 globals.push_back(from_ascii("\\hphantom"));
2147 globals.push_back(from_ascii("\\phantom"));
2148 globals.push_back(from_ascii("\\vphantom"));
2149 globals.push_back(from_ascii("\\cancel"));
2150 globals.push_back(from_ascii("\\bcancel"));
2151 globals.push_back(from_ascii("\\xcancel"));
2152 globals.push_back(from_ascii("\\cancelto"));
2153 globals.push_back(from_ascii("\\smash"));
2154 globals.push_back(from_ascii("\\mathclap"));
2155 globals.push_back(from_ascii("\\mathllap"));
2156 globals.push_back(from_ascii("\\mathrlap"));
2157 globals.push_back(from_ascii("\\ensuremath"));
2158 MathWordList const & words = mathedWordList();
2159 MathWordList::const_iterator it2;
2160 //lyxerr << "Globals completion commands: ";
2161 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2162 if (it2->second.inset != "macro" && !it2->second.hidden) {
2163 // macros are already read from MacroTable::globalMacros()
2164 globals.push_back('\\' + it2->first);
2165 //lyxerr << '\\' + it2->first << ' ';
2168 //lyxerr << std::endl;
2169 sort(globals.begin(), globals.end());
2173 MathCompletionList::~MathCompletionList()
2178 size_type MathCompletionList::size() const
2180 return locals.size() + globals.size();
2184 docstring const & MathCompletionList::data(size_t idx) const
2186 size_t lsize = locals.size();
2188 return globals[idx - lsize];
2194 std::string MathCompletionList::icon(size_t idx) const
2196 // get the latex command
2198 size_t lsize = locals.size();
2200 cmd = globals[idx - lsize];
2204 // get the icon resource name by stripping the backslash
2205 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2206 if (icon_name.empty())
2207 return std::string();
2208 return "images/math/" + to_utf8(icon_name);
2211 std::vector<docstring> MathCompletionList::globals;