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 (MathData & data : cells_)
122 data.setBuffer(buffer);
126 InsetMath::idx_type InsetMathNest::nargs() const
128 return cells_.size();
132 void InsetMathNest::cursorPos(BufferView const & bv,
133 CursorSlice const & sl, bool /*boundary*/,
134 int & x, int & y) const
136 // FIXME: This is a hack. Ideally, the coord cache should not store
137 // absolute positions, but relative ones. This would mean to call
138 // setXY() not in MathData::draw(), but in the parent insets' draw()
139 // with the correctly adjusted x,y values. But this means that we'd have
140 // to touch all (math)inset's draw() methods. Right now, we'll store
141 // absolute value, and make them here relative, only to make them
142 // absolute again when actually drawing the cursor. What a mess.
143 LASSERT(&sl.inset() == this, return);
144 MathData const & ar = sl.cell();
145 CoordCache const & coord_cache = bv.coordCache();
146 if (!coord_cache.getArrays().has(&ar)) {
147 // this can (semi-)legally happen if we just created this cell
148 // and it never has been drawn before. So don't ASSERT.
149 //lyxerr << "no cached data for array " << &ar << endl;
154 Point const pt = coord_cache.getArrays().xy(&ar);
155 if (!coord_cache.getInsets().has(this)) {
157 //lyxerr << "no cached data for inset " << this << endl;
162 Point const pt2 = coord_cache.getInsets().xy(this);
163 //lyxerr << "retrieving position cache for MathData "
164 // << pt.x_ << ' ' << pt.y_ << endl;
165 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
167 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
168 // << " asc: " << ascent() << " des: " << descent()
169 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
170 // move cursor visually into empty cells ("blue rectangles");
172 Dimension const dim = coord_cache.getArrays().dim(&ar);
178 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
181 for (auto const & cell : cells_) {
183 cell.metrics(m, dim);
188 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
190 for (idx_type i = 0, n = nargs(); i != n; ++i)
191 cell(i).updateBuffer(it, utype);
196 bool InsetMathNest::idxNext(Cursor & cur) const
198 LASSERT(&cur.inset() == this, return false);
199 if (cur.idx() == cur.lastidx())
207 bool InsetMathNest::idxForward(Cursor & cur) const
213 bool InsetMathNest::idxPrev(Cursor & cur) const
215 LASSERT(&cur.inset() == this, return false);
219 cur.pos() = cur.lastpos();
224 bool InsetMathNest::idxBackward(Cursor & cur) const
230 bool InsetMathNest::idxFirst(Cursor & cur) const
232 LASSERT(&cur.inset() == this, return false);
241 bool InsetMathNest::idxLast(Cursor & cur) const
243 LASSERT(&cur.inset() == this, return false);
246 cur.idx() = cur.lastidx();
247 cur.pos() = cur.lastpos();
252 void InsetMathNest::dump() const
254 odocstringstream oss;
255 otexrowstream ots(oss);
257 os << "---------------------------------------------\n";
260 for (idx_type i = 0, n = nargs(); i != n; ++i)
261 os << cell(i) << "\n";
262 os << "---------------------------------------------\n";
263 lyxerr << to_utf8(oss.str());
267 void InsetMathNest::draw(PainterInfo &, int, int) const
271 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
277 void InsetMathNest::validate(LaTeXFeatures & features) const
279 for (idx_type i = 0; i < nargs(); ++i)
280 cell(i).validate(features);
284 void InsetMathNest::replace(ReplaceData & rep)
286 for (idx_type i = 0; i < nargs(); ++i)
287 cell(i).replace(rep);
291 bool InsetMathNest::contains(MathData const & ar) const
293 for (idx_type i = 0; i < nargs(); ++i)
294 if (cell(i).contains(ar))
300 bool InsetMathNest::lock() const
306 void InsetMathNest::lock(bool l)
312 bool InsetMathNest::isActive() const
318 MathData InsetMathNest::glue() const
321 for (size_t i = 0; i < nargs(); ++i)
327 void InsetMathNest::write(WriteStream & os) const
329 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
330 ModeSpecifier specifier(os, currentMode(), lockedMode());
331 docstring const latex_name = name();
332 os << '\\' << latex_name;
333 for (size_t i = 0; i < nargs(); ++i) {
334 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
335 os << '{' << cell(i) << '}';
338 os.pendingSpace(true);
339 if (lock_ && !os.latex()) {
341 os.pendingSpace(true);
346 void InsetMathNest::normalize(NormalStream & os) const
349 for (size_t i = 0; i < nargs(); ++i)
350 os << ' ' << cell(i);
355 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
357 WriteStream wi(os, runparams.moving_arg, true,
358 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
360 wi.strikeoutMath(runparams.inDeletedInset
361 && (!LaTeXFeatures::isAvailable("dvipost")
362 || (runparams.flavor != OutputParams::LATEX
363 && runparams.flavor != OutputParams::DVILUATEX)));
364 if (runparams.inulemcmd) {
365 wi.ulemCmd(WriteStream::UNDERLINE);
366 if (runparams.local_font) {
367 FontInfo f = runparams.local_font->fontInfo();
368 if (f.strikeout() == FONT_ON)
369 wi.ulemCmd(WriteStream::STRIKEOUT);
372 wi.canBreakLine(os.canBreakLine());
373 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
376 // Reset parbreak and command termination status after a math inset.
378 os.canBreakLine(wi.canBreakLine());
379 os.terminateCommand(false);
383 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
386 mouse_hover_[bv] = mouse_hover;
391 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
395 MathData & ar = cur.cell();
396 // remove base-only "scripts"
397 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
398 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
399 if (p && p->nargs() == 1) {
400 MathData ar = p->nuc();
403 cur.adjust(i, ar.size() - 1);
407 // glue adjacent font insets of the same kind
408 for (pos_type i = 0; i + 1 < size(); ++i) {
409 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
410 InsetMathFont const * q = operator[](i + 1)->asFontInset();
411 if (p && q && p->name() == q->name()) {
412 p->cell(0).append(q->cell(0));
422 void InsetMathNest::handleFont
423 (Cursor & cur, docstring const & arg, char const * const font)
425 handleFont(cur, arg, from_ascii(font));
429 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
430 docstring const & font)
432 cur.recordUndoSelection();
434 // this whole function is a hack and won't work for incremental font
436 if (cur.inset().asInsetMath()->name() == font)
437 cur.handleFont(to_utf8(font));
439 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
443 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
445 handleNest(cur, nest, docstring());
449 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
450 docstring const & arg)
452 CursorSlice i1 = cur.selBegin();
453 CursorSlice i2 = cur.selEnd();
454 if (!i1.inset().asInsetMath())
456 if (i1.idx() == i2.idx()) {
457 // the easy case where only one cell is selected
458 cur.handleNest(nest);
463 // multiple selected cells in a simple non-grid inset
464 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
465 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
470 cur.pos() = cur.lastpos();
473 // change font of cell
474 cur.handleNest(nest);
477 // cur is in the font inset now. If the loop continues,
478 // we need to get outside again for the next cell
479 if (i + 1 <= i2.idx())
485 // the complicated case with multiple selected cells in a grid
488 cap::region(i1, i2, r1, r2, c1, c2);
489 for (row_type row = r1; row <= r2; ++row) {
490 for (col_type col = c1; col <= c2; ++col) {
492 cur.idx() = i1.asInsetMath()->index(row, col);
495 cur.pos() = cur.lastpos();
499 cur.handleNest(nest);
502 // cur is in the font inset now. If the loop continues,
503 // we need to get outside again for the next cell
504 if (col + 1 <= c2 || row + 1 <= r2)
511 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
513 cur.recordUndoSelection();
516 font.fromString(to_utf8(arg), b);
517 if (font.fontInfo().color() != Color_inherit &&
518 font.fontInfo().color() != Color_ignore)
519 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
521 // FIXME: support other font changes here as well?
525 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
527 //LYXERR0("InsetMathNest: request: " << cmd);
529 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
531 FuncCode const act = cmd.action();
534 case LFUN_CLIPBOARD_PASTE:
535 parseflg |= Parse::VERBATIM;
538 if (cur.currentMode() != MATH_MODE)
539 parseflg |= Parse::TEXTMODE;
540 cur.recordUndoSelection();
541 cur.message(_("Paste"));
542 replaceSelection(cur);
544 if (cmd.argument().empty() && !theClipboard().isInternal())
545 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
548 idocstringstream is(cmd.argument());
550 topaste = cap::selection(n, buffer().params().documentClassPtr());
552 cur.niceInsert(topaste, parseflg, false);
553 cur.clearSelection(); // bug 393
554 cur.forceBufferUpdate();
561 cutSelection(cur, true);
562 cur.message(_("Cut"));
563 // Prevent stale position >= size crash
564 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
566 cur.forceBufferUpdate();
571 cur.message(_("Copy"));
574 case LFUN_MOUSE_PRESS:
575 lfunMousePress(cur, cmd);
578 case LFUN_MOUSE_MOTION:
579 lfunMouseMotion(cur, cmd);
582 case LFUN_MOUSE_RELEASE:
583 lfunMouseRelease(cur, cmd);
586 case LFUN_FINISHED_LEFT: // in math, left is backwards
587 case LFUN_FINISHED_BACKWARD:
588 cur.bv().cursor() = cur;
591 case LFUN_FINISHED_RIGHT: // in math, right is forward
592 case LFUN_FINISHED_FORWARD:
594 cur.bv().cursor() = cur;
597 case LFUN_WORD_RIGHT:
599 case LFUN_WORD_BACKWARD:
600 case LFUN_WORD_FORWARD:
601 case LFUN_CHAR_RIGHT:
603 case LFUN_CHAR_BACKWARD:
604 case LFUN_CHAR_FORWARD:
605 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
607 case LFUN_WORD_RIGHT_SELECT:
608 case LFUN_WORD_LEFT_SELECT:
609 case LFUN_WORD_BACKWARD_SELECT:
610 case LFUN_WORD_FORWARD_SELECT:
611 case LFUN_CHAR_RIGHT_SELECT:
612 case LFUN_CHAR_LEFT_SELECT:
613 case LFUN_CHAR_BACKWARD_SELECT:
614 case LFUN_CHAR_FORWARD_SELECT: {
615 // are we in a selection?
616 bool select = (act == LFUN_WORD_RIGHT_SELECT
617 || act == LFUN_WORD_LEFT_SELECT
618 || act == LFUN_WORD_BACKWARD_SELECT
619 || act == LFUN_WORD_FORWARD_SELECT
620 || act == LFUN_CHAR_RIGHT_SELECT
621 || act == LFUN_CHAR_LEFT_SELECT
622 || act == LFUN_CHAR_BACKWARD_SELECT
623 || act == LFUN_CHAR_FORWARD_SELECT);
625 bool word = (act == LFUN_WORD_RIGHT_SELECT
626 || act == LFUN_WORD_LEFT_SELECT
627 || act == LFUN_WORD_BACKWARD_SELECT
628 || act == LFUN_WORD_FORWARD_SELECT
629 || act == LFUN_WORD_RIGHT
630 || act == LFUN_WORD_LEFT
631 || act == LFUN_WORD_BACKWARD
632 || act == LFUN_WORD_FORWARD);
633 // are we moving forward or backwards?
634 // If the command was RIGHT or LEFT, then whether we're moving forward
635 // or backwards depends on the cursor movement mode (logical or visual):
636 // * in visual mode, since math is always LTR, right -> forward,
638 // * in logical mode, the mapping is determined by the
639 // reverseDirectionNeeded() function
642 FuncCode finish_lfun;
644 if (act == LFUN_CHAR_FORWARD
645 || act == LFUN_CHAR_FORWARD_SELECT
646 || act == LFUN_WORD_FORWARD
647 || act == LFUN_WORD_FORWARD_SELECT) {
649 finish_lfun = LFUN_FINISHED_FORWARD;
651 else if (act == LFUN_CHAR_BACKWARD
652 || act == LFUN_CHAR_BACKWARD_SELECT
653 || act == LFUN_WORD_BACKWARD
654 || act == LFUN_WORD_BACKWARD_SELECT) {
656 finish_lfun = LFUN_FINISHED_BACKWARD;
659 bool right = (act == LFUN_CHAR_RIGHT_SELECT
660 || act == LFUN_CHAR_RIGHT
661 || act == LFUN_WORD_RIGHT_SELECT
662 || act == LFUN_WORD_RIGHT);
663 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
669 finish_lfun = LFUN_FINISHED_RIGHT;
671 finish_lfun = LFUN_FINISHED_LEFT;
673 // Now that we know exactly what we want to do, let's do it!
674 cur.selHandle(select);
676 cur.macroModeClose();
677 // try moving forward or backwards as necessary...
678 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
679 // ... and if movement failed, then finish forward or backwards
681 cmd = FuncRequest(finish_lfun);
689 case LFUN_PARAGRAPH_UP:
690 case LFUN_PARAGRAPH_DOWN:
691 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
693 case LFUN_DOWN_SELECT:
695 case LFUN_PARAGRAPH_UP_SELECT:
696 case LFUN_PARAGRAPH_DOWN_SELECT: {
697 // close active macro
698 if (cur.inMacroMode()) {
699 cur.macroModeClose();
703 // stop/start the selection
704 bool select = act == LFUN_DOWN_SELECT
705 || act == LFUN_UP_SELECT
706 || act == LFUN_PARAGRAPH_DOWN_SELECT
707 || act == LFUN_PARAGRAPH_UP_SELECT;
708 cur.selHandle(select);
710 // handle autocorrect:
711 if (lyxrc.autocorrection_math && cur.autocorrect()) {
712 cur.autocorrect() = false;
713 cur.message(_("Autocorrect Off ('!' to enter)"));
717 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
718 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
719 bool successful = cur.upDownInMath(up);
723 if (cur.fixIfBroken())
724 // FIXME: Something bad happened. We pass the corrected Cursor
725 // instead of letting things go worse.
728 // We did not manage to move the cursor.
733 case LFUN_MOUSE_DOUBLE:
734 case LFUN_WORD_SELECT:
736 cur.bv().mouseSetCursor(cur);
737 cur.pos() = cur.lastpos();
738 cur.bv().mouseSetCursor(cur, true);
741 case LFUN_MOUSE_TRIPLE:
744 cur.bv().mouseSetCursor(cur);
745 cur.idx() = cur.lastidx();
746 cur.pos() = cur.lastpos();
747 cur.bv().mouseSetCursor(cur, true);
750 case LFUN_LINE_BEGIN:
751 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
753 case LFUN_LINE_BEGIN_SELECT:
754 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
755 act == LFUN_WORD_LEFT_SELECT ||
756 act == LFUN_LINE_BEGIN_SELECT);
757 cur.macroModeClose();
758 if (cur.pos() != 0) {
760 } else if (cur.col() != 0) {
761 cur.idx() -= cur.col();
763 } else if (cur.idx() != 0) {
767 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
773 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
775 case LFUN_LINE_END_SELECT:
776 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
777 act == LFUN_WORD_RIGHT_SELECT ||
778 act == LFUN_LINE_END_SELECT);
779 cur.macroModeClose();
781 if (cur.pos() != cur.lastpos()) {
782 cur.pos() = cur.lastpos();
783 } else if (ncols() && (cur.col() != cur.lastcol())) {
784 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
785 cur.pos() = cur.lastpos();
786 } else if (cur.idx() != cur.lastidx()) {
787 cur.idx() = cur.lastidx();
788 cur.pos() = cur.lastpos();
790 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
795 case LFUN_CELL_FORWARD:
796 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
797 cur.inset().idxNext(cur);
800 case LFUN_CELL_BACKWARD:
801 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
802 cur.inset().idxPrev(cur);
805 case LFUN_WORD_DELETE_BACKWARD:
806 case LFUN_CHAR_DELETE_BACKWARD:
808 // May affect external cell:
809 cur.recordUndoInset();
810 else if (!cur.inMacroMode())
811 cur.recordUndoSelection();
812 // if the inset can not be removed from within, delete it
813 if (!cur.backspace(cmd.getArg(0) == "force")) {
814 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
815 cur.innerText()->dispatch(cur, cmd);
819 case LFUN_WORD_DELETE_FORWARD:
820 case LFUN_CHAR_DELETE_FORWARD:
821 if (cur.pos() == cur.lastpos())
822 // May affect external cell:
823 cur.recordUndoInset();
825 cur.recordUndoSelection();
826 // if the inset can not be removed from within, delete it
827 if (!cur.erase(cmd.getArg(0) == "force")) {
828 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
829 cur.innerText()->dispatch(cur, cmd);
835 cur.clearSelection();
837 if (cur.inMacroMode())
838 cur.macroModeClose(true);
840 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
846 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
847 // that is traversed by a single <CursorLeft>/<CursorRight>.
848 case LFUN_INSET_TOGGLE:
854 case LFUN_SELF_INSERT:
855 // special case first for big delimiters
856 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
859 for (char_type c : cmd.argument()) {
860 // Don't record undo steps if we are in macro mode and thus
861 // cmd.argument is the next character of the macro name.
862 // Otherwise we'll get an invalid cursor if we undo after
863 // the macro was finished and the macro is a known command,
864 // e.g. sqrt. Cursor::macroModeClose replaces in this case
865 // the InsetMathUnknown with name "frac" by an empty
866 // InsetMathFrac -> a pos value > 0 is invalid.
867 // A side effect is that an undo before the macro is finished
868 // undoes the complete macro, not only the last character.
869 // At the time we hit '\' we are not in macro mode, still.
870 if (!cur.inMacroMode())
871 cur.recordUndoSelection();
873 // special handling of space. If we insert an inset
874 // via macro mode, we want to put the cursor inside it
875 // if relevant. Think typing "\frac<space>".
877 && cur.inMacroMode() && cur.macroName() != "\\"
878 && cur.macroModeClose() && cur.pos() > 0) {
879 MathAtom const atom = cur.prevAtom();
880 if (atom->asNestInset() && atom->isActive()) {
882 cur.pushBackward(*cur.nextInset());
884 } else if (!interpretChar(cur, c)) {
885 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
887 // FIXME: can we avoid skipping the end of the string?
893 //case LFUN_SERVER_GET_XY:
896 case LFUN_SERVER_SET_XY: {
897 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
900 istringstream is(to_utf8(cmd.argument()));
902 cur.setScreenPos(x, y);
906 // Special casing for superscript in case of LyX handling
908 case LFUN_ACCENT_CIRCUMFLEX:
909 if (cmd.argument().empty()) {
910 // do superscript if LyX handles
912 cur.recordUndoSelection();
913 script(cur, true, grabAndEraseSelection(cur));
917 case LFUN_ACCENT_UMLAUT:
918 case LFUN_ACCENT_ACUTE:
919 case LFUN_ACCENT_GRAVE:
920 case LFUN_ACCENT_BREVE:
921 case LFUN_ACCENT_DOT:
922 case LFUN_ACCENT_MACRON:
923 case LFUN_ACCENT_CARON:
924 case LFUN_ACCENT_TILDE:
925 case LFUN_ACCENT_CEDILLA:
926 case LFUN_ACCENT_CIRCLE:
927 case LFUN_ACCENT_UNDERDOT:
928 case LFUN_ACCENT_TIE:
929 case LFUN_ACCENT_OGONEK:
930 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
934 case LFUN_TEXTSTYLE_APPLY:
935 case LFUN_TEXTSTYLE_UPDATE:
936 handleFont2(cur, cmd.argument());
940 if (currentMode() != MATH_MODE)
941 handleFont(cur, cmd.argument(), "textbf");
943 handleFont(cur, cmd.argument(), "mathbf");
945 case LFUN_FONT_BOLDSYMBOL:
946 if (currentMode() != MATH_MODE)
947 handleFont(cur, cmd.argument(), "textbf");
949 handleFont(cur, cmd.argument(), "boldsymbol");
952 if (currentMode() != MATH_MODE)
953 handleFont(cur, cmd.argument(), "textsf");
955 handleFont(cur, cmd.argument(), "mathsf");
958 if (currentMode() != MATH_MODE)
959 handleFont(cur, cmd.argument(), "emph");
961 handleFont(cur, cmd.argument(), "mathcal");
963 case LFUN_FONT_ROMAN:
964 if (currentMode() != MATH_MODE)
965 handleFont(cur, cmd.argument(), "textrm");
967 handleFont(cur, cmd.argument(), "mathrm");
969 case LFUN_FONT_TYPEWRITER:
970 if (currentMode() != MATH_MODE)
971 handleFont(cur, cmd.argument(), "texttt");
973 handleFont(cur, cmd.argument(), "mathtt");
976 handleFont(cur, cmd.argument(), "mathfrak");
979 if (currentMode() != MATH_MODE)
980 handleFont(cur, cmd.argument(), "textit");
982 handleFont(cur, cmd.argument(), "mathit");
985 if (currentMode() != MATH_MODE)
986 // FIXME: should be "noun"
987 handleFont(cur, cmd.argument(), "textsc");
989 handleFont(cur, cmd.argument(), "mathbb");
991 case LFUN_FONT_DEFAULT:
992 handleFont(cur, cmd.argument(), "textnormal");
994 case LFUN_FONT_UNDERLINE:
996 cur.handleNest(createInsetMath("underline", cur.buffer()));
999 case LFUN_MATH_MODE: {
1001 // ignore math-mode on when already in math mode
1002 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1004 cur.recordUndoSelection();
1005 cur.macroModeClose();
1006 docstring const save_selection = grabAndEraseSelection(cur);
1008 if (currentMode() != Inset::MATH_MODE)
1009 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1011 cur.plainInsert(createInsetMath("text", buffer_));
1013 cur.pushBackward(*cur.nextInset());
1014 cur.niceInsert(save_selection);
1015 cur.forceBufferUpdate();
1017 if (currentMode() == Inset::TEXT_MODE) {
1018 cur.recordUndoSelection();
1019 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1020 cur.message(_("create new math text environment ($...$)"));
1022 handleFont(cur, cmd.argument(), "textrm");
1023 cur.message(_("entered math text mode (textrm)"));
1029 case LFUN_REGEXP_MODE: {
1030 InsetMath * im = cur.inset().asInsetMath();
1032 InsetMathHull * i = im->asHullInset();
1033 if (i && i->getType() == hullRegexp) {
1034 cur.message(_("Already in regular expression mode"));
1038 cur.macroModeClose();
1039 docstring const save_selection = grabAndEraseSelection(cur);
1041 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1043 cur.pushBackward(*cur.nextInset());
1044 cur.niceInsert(save_selection);
1045 cur.message(_("Regular expression editor mode"));
1049 case LFUN_MATH_FONT_STYLE: {
1050 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1051 doDispatch(cur, fr);
1055 case LFUN_MATH_SIZE: {
1056 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1057 doDispatch(cur, fr);
1061 case LFUN_MATH_MATRIX: {
1067 idocstringstream is(cmd.argument());
1068 is >> m >> n >> v_align >> h_align;
1074 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1075 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1079 case LFUN_MATH_AMS_MATRIX: {
1083 docstring name = from_ascii("matrix");
1084 idocstringstream is(cmd.argument());
1085 is >> m >> n >> name;
1090 // check if we have a valid decoration
1091 if (name != "pmatrix" && name != "bmatrix"
1092 && name != "Bmatrix" && name != "vmatrix"
1093 && name != "Vmatrix" && name != "matrix")
1094 name = from_ascii("matrix");
1097 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1101 case LFUN_MATH_DELIM: {
1103 docstring rs = split(cmd.argument(), ls, ' ');
1104 // Reasonable default values
1110 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1114 case LFUN_MATH_BIGDELIM: {
1115 docstring const lname = from_utf8(cmd.getArg(0));
1116 docstring const ldelim = from_utf8(cmd.getArg(1));
1117 docstring const rname = from_utf8(cmd.getArg(2));
1118 docstring const rdelim = from_utf8(cmd.getArg(3));
1119 latexkeys const * l = in_word_set(lname);
1120 bool const have_l = l && l->inset == "big" &&
1121 InsetMathBig::isBigInsetDelim(ldelim);
1122 l = in_word_set(rname);
1123 bool const have_r = l && l->inset == "big" &&
1124 InsetMathBig::isBigInsetDelim(rdelim);
1125 // We mimic LFUN_MATH_DELIM in case we have an empty left
1126 // or right delimiter.
1127 if (have_l || have_r) {
1129 docstring const selection = grabAndEraseSelection(cur);
1132 cur.insert(MathAtom(new InsetMathBig(lname,
1134 // first insert the right delimiter and then go back
1135 // and re-insert the selection (bug 7088)
1137 cur.insert(MathAtom(new InsetMathBig(rname,
1141 cur.niceInsert(selection);
1143 // Don't call cur.undispatched() if we did nothing, this would
1144 // lead to infinite recursion via Text::dispatch().
1148 case LFUN_SPACE_INSERT: {
1149 cur.recordUndoSelection();
1150 string const name = cmd.getArg(0);
1151 if (name == "normal")
1152 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1153 else if (name == "protected")
1154 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1155 else if (name == "thin" || name == "med" || name == "thick")
1156 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1157 else if (name == "hfill*")
1158 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1159 else if (name == "quad" || name == "qquad" ||
1160 name == "enspace" || name == "enskip" ||
1161 name == "negthinspace" || name == "negmedspace" ||
1162 name == "negthickspace" || name == "hfill")
1163 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1164 else if (name == "hspace" || name == "hspace*") {
1165 string const len = cmd.getArg(1);
1166 if (len.empty() || !isValidLength(len)) {
1167 lyxerr << "LyX function 'space-insert " << name << "' "
1168 "needs a valid length argument." << endl;
1171 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1173 cur.insert(MathAtom(new InsetMathSpace));
1177 case LFUN_MATH_SPACE:
1178 cur.recordUndoSelection();
1179 if (cmd.argument().empty())
1180 cur.insert(MathAtom(new InsetMathSpace));
1182 string const name = cmd.getArg(0);
1183 string const len = cmd.getArg(1);
1184 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1188 case LFUN_ERT_INSERT:
1189 // interpret this as if a backslash was typed
1191 interpretChar(cur, '\\');
1194 case LFUN_MATH_SUBSCRIPT:
1195 // interpret this as if a _ was typed
1196 cur.recordUndoSelection();
1197 interpretChar(cur, '_');
1200 case LFUN_MATH_SUPERSCRIPT:
1201 // interpret this as if a ^ was typed
1202 cur.recordUndoSelection();
1203 interpretChar(cur, '^');
1206 case LFUN_MATH_MACRO_FOLD:
1207 case LFUN_MATH_MACRO_UNFOLD: {
1209 bool fold = act == LFUN_MATH_MACRO_FOLD;
1210 bool found = findMacroToFoldUnfold(it, fold);
1212 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1213 cur.recordUndoInset();
1222 case LFUN_QUOTE_INSERT:
1223 // interpret this as if a straight " was typed
1224 cur.recordUndoSelection();
1225 interpretChar(cur, '\"');
1228 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1229 // handling such that "self-insert" works on "arbitrary stuff" too, and
1230 // math-insert only handles special math things like "matrix".
1231 case LFUN_MATH_INSERT: {
1232 cur.recordUndoSelection();
1233 if (cmd.argument() == "^" || cmd.argument() == "_")
1234 interpretChar(cur, cmd.argument()[0]);
1237 asArray(cmd.argument(), ar);
1238 if (cur.selection() && ar.size() == 1
1239 && ar[0]->asNestInset()
1240 && ar[0]->asNestInset()->nargs() > 1)
1241 handleNest(cur, ar[0]);
1243 cur.niceInsert(cmd.argument());
1248 case LFUN_DIALOG_SHOW_NEW_INSET: {
1249 docstring const & name = cmd.argument();
1251 if (name == "ref") {
1252 InsetMathRef tmp(buffer_, name);
1253 data = tmp.createDialogStr();
1254 cur.bv().showDialog(to_utf8(name), data);
1255 } else if (name == "mathspace") {
1256 cur.bv().showDialog(to_utf8(name));
1261 case LFUN_INSET_INSERT: {
1263 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1264 cur.recordUndoSelection();
1266 cur.forceBufferUpdate();
1271 case LFUN_INSET_DISSOLVE:
1272 if (!asHullInset()) {
1273 cur.recordUndoInset();
1279 InsetMath::doDispatch(cur, cmd);
1285 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1286 // look for macro to open/close, but stay in mathed
1287 for (; !it.empty(); it.pop_back()) {
1289 // go backward through the current cell
1290 Inset * inset = it.nextInset();
1291 while (inset && inset->asInsetMath()) {
1292 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1294 // found the an macro to open/close?
1295 if (macro->folded() != fold)
1298 // Wrong folding state.
1299 // If this was the first we see in this slice, look further left,
1301 if (inset != it.nextInset())
1305 // go up if this was the left most position
1311 inset = it.nextInset();
1319 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1320 FuncStatus & flag) const
1322 // the font related toggles
1323 //string tc = "mathnormal";
1325 string const arg = to_utf8(cmd.argument());
1326 switch (cmd.action()) {
1327 case LFUN_INSET_MODIFY:
1328 flag.setEnabled(false);
1331 case LFUN_INSET_MODIFY:
1332 // FIXME: check temporarily disabled
1334 char align = mathcursor::valign();
1335 if (align == '\0') {
1339 if (cmd.argument().empty()) {
1343 if (!contains("tcb", cmd.argument()[0])) {
1347 flag.setOnOff(cmd.argument()[0] == align);
1350 /// We have to handle them since 1.4 blocks all unhandled actions
1351 case LFUN_FONT_ITAL:
1352 case LFUN_FONT_BOLD:
1353 case LFUN_FONT_BOLDSYMBOL:
1354 case LFUN_FONT_SANS:
1355 case LFUN_FONT_EMPH:
1356 case LFUN_FONT_TYPEWRITER:
1357 case LFUN_FONT_NOUN:
1358 case LFUN_FONT_ROMAN:
1359 case LFUN_FONT_DEFAULT:
1360 flag.setEnabled(true);
1363 // we just need to be in math mode to enable that
1364 case LFUN_MATH_SIZE:
1365 case LFUN_MATH_SPACE:
1366 case LFUN_MATH_EXTERN:
1367 flag.setEnabled(true);
1370 case LFUN_FONT_UNDERLINE:
1371 case LFUN_FONT_FRAK:
1372 flag.setEnabled(currentMode() != TEXT_MODE);
1375 case LFUN_MATH_FONT_STYLE: {
1376 bool const textarg =
1377 arg == "textbf" || arg == "textsf" ||
1378 arg == "textrm" || arg == "textmd" ||
1379 arg == "textit" || arg == "textsc" ||
1380 arg == "textsl" || arg == "textup" ||
1381 arg == "texttt" || arg == "textbb" ||
1382 arg == "textnormal";
1383 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1387 case LFUN_MATH_MODE:
1388 // forbid "math-mode on" in math mode to prevent irritating
1389 // behaviour of menu entries (bug 6709)
1390 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1393 case LFUN_MATH_INSERT:
1394 flag.setEnabled(currentMode() != TEXT_MODE);
1397 case LFUN_MATH_AMS_MATRIX:
1398 case LFUN_MATH_MATRIX:
1399 flag.setEnabled(currentMode() == MATH_MODE);
1402 case LFUN_INSET_INSERT: {
1403 // Don't test createMathInset_fromDialogStr(), since
1404 // getStatus is not called with a valid reference and the
1405 // dialog would not be applyable.
1406 string const name = cmd.getArg(0);
1407 flag.setEnabled(name == "ref" || name == "mathspace");
1411 case LFUN_DIALOG_SHOW_NEW_INSET: {
1412 docstring const & name = cmd.argument();
1413 if (name == "space")
1414 flag.setEnabled(false);
1419 case LFUN_MATH_DELIM:
1420 case LFUN_MATH_BIGDELIM:
1421 // Don't do this with multi-cell selections
1422 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1425 case LFUN_MATH_MACRO_FOLD:
1426 case LFUN_MATH_MACRO_UNFOLD: {
1428 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1429 flag.setEnabled(found);
1433 case LFUN_SPECIALCHAR_INSERT:
1434 case LFUN_SCRIPT_INSERT:
1435 // FIXME: These would probably make sense in math-text mode
1436 flag.setEnabled(false);
1439 case LFUN_CAPTION_INSERT:
1440 flag.setEnabled(false);
1443 case LFUN_SPACE_INSERT: {
1444 docstring const & name = cmd.argument();
1445 if (name == "visible")
1446 flag.setEnabled(false);
1450 case LFUN_INSET_DISSOLVE:
1451 flag.setEnabled(!asHullInset());
1455 docstring const & name = cmd.argument();
1456 if (name == "html" || name == "latex")
1457 flag.setEnabled(false);
1469 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1472 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1473 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1474 cur.idx() = enter_front ? 0 : cur.lastidx();
1475 cur.pos() = enter_front ? 0 : cur.lastpos();
1477 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1481 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1484 int dist_min = 1000000;
1485 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1486 int const d = cell(i).dist(cur.bv(), x, y);
1495 MathData & ar = cell(idx_min);
1497 cur.idx() = idx_min;
1498 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1500 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1501 if (dist_min == 0) {
1503 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1504 if (ar[i]->covers(cur.bv(), x, y))
1505 return ar[i].nucleus()->editXY(cur, x, y);
1511 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1513 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1514 BufferView & bv = cur.bv();
1515 if (cmd.button() == mouse_button::button3) {
1516 // Don't do anything if we right-click a
1517 // selection, a context menu will popup.
1518 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1519 && cur < bv.cursor().selectionEnd()) {
1520 cur.noScreenUpdate();
1525 // set cursor after the inset if x is nearer to that position (bug 9748)
1526 cur.moveToClosestEdge(cmd.x(), true);
1528 bool do_selection = cmd.button() == mouse_button::button1
1529 && cmd.modifier() == ShiftModifier;
1530 bv.mouseSetCursor(cur, do_selection);
1531 if (cmd.button() == mouse_button::button1) {
1532 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1533 // Update the cursor update flags as needed:
1535 // Update::Decoration: tells to update the decoration
1536 // (visual box corners that define
1538 // Update::FitCursor: adjust the screen to the cursor
1539 // position if needed
1540 // cur.result().update(): don't overwrite previously set flags.
1541 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1542 | cur.result().screenUpdate());
1543 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1544 if (cap::selection()) {
1545 // See comment in Text::dispatch why we do this
1546 cap::copySelectionToStack();
1547 cmd = FuncRequest(LFUN_PASTE, "0");
1548 doDispatch(bv.cursor(), cmd);
1551 asArray(theSelection().get(), ar);
1552 bv.cursor().insert(ar);
1558 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1560 // only select with button 1
1561 if (cmd.button() != mouse_button::button1)
1564 Cursor & bvcur = cur.bv().cursor();
1566 // ignore motions deeper nested than the real anchor
1567 if (!bvcur.realAnchor().hasPart(cur)) {
1572 // set cursor after the inset if x is nearer to that position (bug 9748)
1573 cur.moveToClosestEdge(cmd.x());
1575 CursorSlice old = bvcur.top();
1577 // We continue with our existing selection or start a new one, so don't
1578 // reset the anchor.
1579 bvcur.setCursor(cur);
1580 // Did we actually move?
1581 if (cur.top() == old)
1582 // We didn't move one iota, so no need to change selection status
1583 // or update the screen.
1584 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1586 bvcur.setSelection();
1590 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1592 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1594 if (cmd.button() == mouse_button::button1) {
1595 if (!cur.selection())
1596 cur.noScreenUpdate();
1598 Cursor & bvcur = cur.bv().cursor();
1599 bvcur.selection(true);
1608 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1610 //lyxerr << "interpret 2: '" << c << "'" << endl;
1611 docstring save_selection;
1612 if (c == '^' || c == '_')
1613 save_selection = grabAndEraseSelection(cur);
1616 Buffer * buf = cur.buffer();
1619 if (cur.inMacroMode()) {
1620 docstring name = cur.macroName();
1622 /// are we currently typing '#1' or '#2' or...?
1623 if (name == "\\#") {
1626 if (n >= 1 && n <= 9)
1627 cur.insert(new InsetMathMacroArgument(n));
1631 // do not finish macro for known * commands
1632 bool star_macro = c == '*'
1633 && (in_word_set(name.substr(1) + '*')
1634 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1635 if (isAlphaASCII(c) || star_macro) {
1636 cur.activeMacro()->setName(name + docstring(1, c));
1640 // handle 'special char' macros
1645 if (currentMode() != InsetMath::MATH_MODE)
1646 cur.niceInsert(createInsetMath("textbackslash", buf));
1648 cur.niceInsert(createInsetMath("backslash", buf));
1649 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1651 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1652 } else if (c == '{' || c == '%') {
1653 //using the saved selection as argument
1654 InsetMathUnknown * p = cur.activeMacro();
1656 MathData sel(cur.buffer());
1657 asArray(p->selection(), sel);
1660 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1662 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1663 } else if (c == '#') {
1664 LASSERT(cur.activeMacro(), return false);
1665 cur.activeMacro()->setName(name + docstring(1, c));
1668 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1673 // One character big delimiters. The others are handled in
1674 // interpretString().
1675 latexkeys const * l = in_word_set(name.substr(1));
1676 if (name[0] == '\\' && l && l->inset == "big") {
1680 delim = from_ascii("\\{");
1683 delim = from_ascii("\\}");
1686 delim = docstring(1, c);
1689 if (InsetMathBig::isBigInsetDelim(delim)) {
1690 // name + delim ared a valid InsetMathBig.
1691 // We can't use cur.macroModeClose() because
1692 // it does not handle delim.
1693 InsetMathUnknown * p = cur.activeMacro();
1696 cur.cell().erase(cur.pos());
1697 cur.plainInsert(MathAtom(
1698 new InsetMathBig(name.substr(1), delim)));
1701 } else if (name == "\\smash" && c == '[') {
1702 // We can't use cur.macroModeClose() because
1703 // it would create an InsetMathPhantom
1704 InsetMathUnknown * p = cur.activeMacro();
1706 interpretChar(cur, c);
1710 // leave macro mode and try again if necessary
1711 if (cur.macroModeClose()) {
1712 MathAtom const atom = cur.prevAtom();
1713 if (atom->asNestInset() && atom->isActive()) {
1715 cur.pushBackward(*cur.nextInset());
1719 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1721 interpretChar(cur, c);
1726 // leave autocorrect mode if necessary
1727 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1728 cur.autocorrect() = false;
1729 cur.message(_("Autocorrect Off ('!' to enter)"));
1732 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1733 cur.autocorrect() = true;
1734 cur.message(_("Autocorrect On (<space> to exit)"));
1738 // just clear selection on pressing the space bar
1739 if (cur.selection() && c == ' ') {
1740 cur.selection(false);
1745 //lyxerr << "starting with macro" << endl;
1746 bool reduced = cap::reduceSelectionToOneCell(cur);
1747 if (reduced || !cur.selection()) {
1748 cur.recordUndoInset();
1749 docstring const safe = cap::grabAndEraseSelection(cur);
1750 if (!cur.inRegexped())
1751 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1753 cur.niceInsert(createInsetMath("backslash", buf));
1761 if (currentMode() != InsetMath::MATH_MODE)
1767 if (currentMode() != InsetMath::MATH_MODE) {
1768 // insert spaces in text or undecided mode,
1769 // but suppress direct insertion of two spaces in a row
1770 // the still allows typing '<space>a<space>' and deleting the 'a', but
1771 // it is better than nothing...
1772 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1774 // FIXME: we have to enable full redraw here because of the
1775 // visual box corners that define the inset. If we know for
1776 // sure that we stay within the same cell we can optimize for
1778 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1782 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1783 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1784 // FIXME: we have to enable full redraw here because of the
1785 // visual box corners that define the inset. If we know for
1786 // sure that we stay within the same cell we can optimize for
1788 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1792 if (cur.popForward()) {
1793 // FIXME: we have to enable full redraw here because of the
1794 // visual box corners that define the inset. If we know for
1795 // sure that we stay within the same cell we can optimize for
1797 //cur.screenUpdateFlags(Update::FitCursor);
1801 // if we are at the very end, leave the formula
1802 return cur.pos() != cur.lastpos();
1805 // These should be treated differently when not in text mode:
1806 if (cur.inRegexped()) {
1809 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1816 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1819 cur.niceInsert(createInsetMath("sim", buf));
1825 } else if (currentMode() != InsetMath::TEXT_MODE) {
1827 script(cur, false, save_selection);
1831 script(cur, true, save_selection);
1835 cur.niceInsert(createInsetMath("sim", buf));
1838 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1839 MathAtom at = createInsetMath("text", buf);
1840 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1847 cur.niceInsert(createInsetMath("textasciicircum", buf));
1851 cur.niceInsert(createInsetMath("textasciitilde", buf));
1856 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1857 c == '%' || c == '_') {
1858 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1863 // try auto-correction
1864 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1865 && math_autocorrect(cur.prevAtom(), c))
1868 // no special circumstances, so insert the character without any fuss
1870 if (lyxrc.autocorrection_math) {
1871 if (!cur.autocorrect())
1872 cur.message(_("Autocorrect Off ('!' to enter)"));
1874 cur.message(_("Autocorrect On (<space> to exit)"));
1880 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1882 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1884 if (!cur.empty() && cur.pos() > 0 &&
1885 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1886 if (InsetMathBig::isBigInsetDelim(str)) {
1887 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1888 if (prev[0] == '\\') {
1889 prev = prev.substr(1);
1890 latexkeys const * l = in_word_set(prev);
1891 if (l && l->inset == "big") {
1892 cur.recordUndoSelection();
1893 cur.cell()[cur.pos() - 1] =
1894 MathAtom(new InsetMathBig(prev, str));
1904 bool InsetMathNest::script(Cursor & cur, bool up)
1906 return script(cur, up, docstring());
1910 bool InsetMathNest::script(Cursor & cur, bool up,
1911 docstring const & save_selection)
1913 // Hack to get \^ and \_ working
1914 //lyxerr << "handling script: up: " << up << endl;
1915 if (cur.inMacroMode() && cur.macroName() == "\\") {
1917 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1919 interpretChar(cur, '_');
1923 cur.macroModeClose();
1924 if (asScriptInset() && cur.idx() == 0) {
1925 // we are in a nucleus of a script inset, move to _our_ script
1926 InsetMathScript * inset = asScriptInset();
1927 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1929 cur.idx() = inset->idxOfScript(up);
1931 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1933 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1936 cur.idx() = inset->idxOfScript(up);
1937 cur.pos() = cur.lastpos();
1939 // convert the thing to our left to a scriptinset or create a new
1940 // one if in the very first position of the array
1941 if (cur.pos() == 0) {
1942 //lyxerr << "new scriptinset" << endl;
1943 cur.insert(new InsetMathScript(buffer_, up));
1945 //lyxerr << "converting prev atom " << endl;
1946 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1949 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1950 // See comment in MathParser.cpp for special handling of {}-bases
1956 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1957 cur.niceInsert(save_selection);
1959 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1964 bool InsetMathNest::completionSupported(Cursor const & cur) const
1966 return cur.inMacroMode();
1970 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1972 return cur.inMacroMode();
1976 bool InsetMathNest::automaticInlineCompletion() const
1978 return lyxrc.completion_inline_math;
1982 bool InsetMathNest::automaticPopupCompletion() const
1984 return lyxrc.completion_popup_math;
1988 CompletionList const *
1989 InsetMathNest::createCompletionList(Cursor const & cur) const
1991 if (!cur.inMacroMode())
1994 return new MathCompletionList(cur);
1998 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2000 if (!cur.inMacroMode())
2003 return cur.activeMacro()->name();
2007 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2010 if (!cur.inMacroMode())
2013 // append completion to active macro
2014 InsetMathUnknown * inset = cur.activeMacro();
2015 inset->setName(inset->name() + s);
2020 // FIXME: this creates duplicates in the completion popup
2021 // which looks ugly. Moreover the changes the list lengths
2023 confuse the popup as well.
2024 MathCompletionList::addToFavorites(inset->name());
2026 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2033 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2034 Dimension & dim) const
2036 Inset const * inset = cur.activeMacro();
2040 // get inset dimensions
2041 dim = cur.bv().coordCache().insets().dim(inset);
2042 // FIXME: these 3 are no accurate, but should depend on the font.
2043 // Now the popup jumps down if you enter a char with descent > 0.
2048 Point xy = cur.bv().coordCache().insets().xy(inset);
2054 ////////////////////////////////////////////////////////////////////
2056 MathCompletionList::MathCompletionList(Cursor const & cur)
2058 // fill it with macros from the buffer
2059 MacroNameSet macros;
2060 cur.buffer()->listMacroNames(macros);
2061 MacroNameSet::const_iterator it;
2062 for (it = macros.begin(); it != macros.end(); ++it) {
2063 if (cur.buffer()->getMacro(*it, cur, false))
2064 locals.push_back("\\" + *it);
2066 sort(locals.begin(), locals.end());
2068 if (!globals.empty())
2071 // fill in global macros
2073 MacroTable::globalMacros().getMacroNames(macros, false);
2074 //lyxerr << "Globals completion macros: ";
2075 for (it = macros.begin(); it != macros.end(); ++it) {
2076 //lyxerr << "\\" + *it << " ";
2077 globals.push_back("\\" + *it);
2079 //lyxerr << std::endl;
2081 // fill in global commands
2082 globals.push_back(from_ascii("\\boxed"));
2083 globals.push_back(from_ascii("\\fbox"));
2084 globals.push_back(from_ascii("\\framebox"));
2085 globals.push_back(from_ascii("\\makebox"));
2086 globals.push_back(from_ascii("\\kern"));
2087 globals.push_back(from_ascii("\\xhookrightarrow"));
2088 globals.push_back(from_ascii("\\xhookleftarrow"));
2089 globals.push_back(from_ascii("\\xrightarrow"));
2090 globals.push_back(from_ascii("\\xRightarrow"));
2091 globals.push_back(from_ascii("\\xrightharpoondown"));
2092 globals.push_back(from_ascii("\\xrightharpoonup"));
2093 globals.push_back(from_ascii("\\xrightleftharpoons"));
2094 globals.push_back(from_ascii("\\xleftarrow"));
2095 globals.push_back(from_ascii("\\xLeftarrow"));
2096 globals.push_back(from_ascii("\\xleftharpoondown"));
2097 globals.push_back(from_ascii("\\xleftharpoonup"));
2098 globals.push_back(from_ascii("\\xleftrightarrow"));
2099 globals.push_back(from_ascii("\\xLeftrightarrow"));
2100 globals.push_back(from_ascii("\\xleftrightharpoons"));
2101 globals.push_back(from_ascii("\\xmapsto"));
2102 globals.push_back(from_ascii("\\split"));
2103 globals.push_back(from_ascii("\\gathered"));
2104 globals.push_back(from_ascii("\\aligned"));
2105 globals.push_back(from_ascii("\\alignedat"));
2106 globals.push_back(from_ascii("\\cases"));
2107 globals.push_back(from_ascii("\\substack"));
2108 globals.push_back(from_ascii("\\xymatrix"));
2109 globals.push_back(from_ascii("\\Diagram"));
2110 globals.push_back(from_ascii("\\subarray"));
2111 globals.push_back(from_ascii("\\array"));
2112 globals.push_back(from_ascii("\\sqrt"));
2113 globals.push_back(from_ascii("\\root"));
2114 globals.push_back(from_ascii("\\tabular"));
2115 globals.push_back(from_ascii("\\sideset"));
2116 globals.push_back(from_ascii("\\stackrel"));
2117 globals.push_back(from_ascii("\\stackrelthree"));
2118 globals.push_back(from_ascii("\\binom"));
2119 globals.push_back(from_ascii("\\choose"));
2120 globals.push_back(from_ascii("\\brace"));
2121 globals.push_back(from_ascii("\\brack"));
2122 globals.push_back(from_ascii("\\frac"));
2123 globals.push_back(from_ascii("\\over"));
2124 globals.push_back(from_ascii("\\nicefrac"));
2125 globals.push_back(from_ascii("\\unitfrac"));
2126 globals.push_back(from_ascii("\\unitfracthree"));
2127 globals.push_back(from_ascii("\\unitone"));
2128 globals.push_back(from_ascii("\\unittwo"));
2129 globals.push_back(from_ascii("\\infer"));
2130 globals.push_back(from_ascii("\\atop"));
2131 globals.push_back(from_ascii("\\lefteqn"));
2132 globals.push_back(from_ascii("\\boldsymbol"));
2133 globals.push_back(from_ascii("\\bm"));
2134 globals.push_back(from_ascii("\\color"));
2135 globals.push_back(from_ascii("\\normalcolor"));
2136 globals.push_back(from_ascii("\\textcolor"));
2137 globals.push_back(from_ascii("\\cfrac"));
2138 globals.push_back(from_ascii("\\cfracleft"));
2139 globals.push_back(from_ascii("\\cfracright"));
2140 globals.push_back(from_ascii("\\dfrac"));
2141 globals.push_back(from_ascii("\\tfrac"));
2142 globals.push_back(from_ascii("\\dbinom"));
2143 globals.push_back(from_ascii("\\tbinom"));
2144 globals.push_back(from_ascii("\\hphantom"));
2145 globals.push_back(from_ascii("\\phantom"));
2146 globals.push_back(from_ascii("\\vphantom"));
2147 globals.push_back(from_ascii("\\cancel"));
2148 globals.push_back(from_ascii("\\bcancel"));
2149 globals.push_back(from_ascii("\\xcancel"));
2150 globals.push_back(from_ascii("\\cancelto"));
2151 globals.push_back(from_ascii("\\smash"));
2152 globals.push_back(from_ascii("\\mathclap"));
2153 globals.push_back(from_ascii("\\mathllap"));
2154 globals.push_back(from_ascii("\\mathrlap"));
2155 globals.push_back(from_ascii("\\ensuremath"));
2156 MathWordList const & words = mathedWordList();
2157 MathWordList::const_iterator it2;
2158 //lyxerr << "Globals completion commands: ";
2159 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2160 if (it2->second.inset != "macro" && !it2->second.hidden) {
2161 // macros are already read from MacroTable::globalMacros()
2162 globals.push_back('\\' + it2->first);
2163 //lyxerr << '\\' + it2->first << ' ';
2166 //lyxerr << std::endl;
2167 sort(globals.begin(), globals.end());
2171 MathCompletionList::~MathCompletionList()
2176 size_type MathCompletionList::size() const
2178 return locals.size() + globals.size();
2182 docstring const & MathCompletionList::data(size_t idx) const
2184 size_t lsize = locals.size();
2186 return globals[idx - lsize];
2192 std::string MathCompletionList::icon(size_t idx) const
2194 // get the latex command
2196 size_t lsize = locals.size();
2198 cmd = globals[idx - lsize];
2202 // get the icon resource name by stripping the backslash
2203 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2204 if (icon_name.empty())
2205 return std::string();
2206 return "images/math/" + to_utf8(icon_name);
2209 std::vector<docstring> MathCompletionList::globals;