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 "MathMacro.h"
36 #include "MathMacroArgument.h"
37 #include "MathParser.h"
38 #include "MathStream.h"
39 #include "MathSupport.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"
53 #include "OutputParams.h"
56 #include "frontends/Clipboard.h"
57 #include "frontends/Painter.h"
58 #include "frontends/Selection.h"
60 #include "support/lassert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
65 #include "support/docstream.h"
71 using namespace lyx::support;
75 using cap::copySelection;
76 using cap::grabAndEraseSelection;
77 using cap::cutSelection;
78 using cap::replaceSelection;
79 using cap::selClearOrDel;
82 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
83 : InsetMath(buf), cells_(nargs), lock_(false)
89 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
90 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
94 InsetMathNest::~InsetMathNest()
96 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
97 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
98 for (; it != end; ++it)
100 it->first->clearLastInset(this);
104 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
106 cells_ = inset.cells_;
108 mouse_hover_.clear();
109 InsetMath::operator=(inset);
114 void InsetMathNest::setBuffer(Buffer & buffer)
116 InsetMath::setBuffer(buffer);
117 for (idx_type i = 0, n = nargs(); i != n; ++i) {
118 MathData & data = cell(i);
119 for (size_t j = 0; j != data.size(); ++j)
120 data[j].nucleus()->setBuffer(buffer);
125 InsetMath::idx_type InsetMathNest::nargs() const
127 return cells_.size();
131 void InsetMathNest::cursorPos(BufferView const & bv,
132 CursorSlice const & sl, bool /*boundary*/,
133 int & x, int & y) const
135 // FIXME: This is a hack. Ideally, the coord cache should not store
136 // absolute positions, but relative ones. This would mean to call
137 // setXY() not in MathData::draw(), but in the parent insets' draw()
138 // with the correctly adjusted x,y values. But this means that we'd have
139 // to touch all (math)inset's draw() methods. Right now, we'll store
140 // absolute value, and make them here relative, only to make them
141 // absolute again when actually drawing the cursor. What a mess.
142 LASSERT(&sl.inset() == this, return);
143 MathData const & ar = sl.cell();
144 CoordCache const & coord_cache = bv.coordCache();
145 if (!coord_cache.getArrays().has(&ar)) {
146 // this can (semi-)legally happen if we just created this cell
147 // and it never has been drawn before. So don't ASSERT.
148 //lyxerr << "no cached data for array " << &ar << endl;
153 Point const pt = coord_cache.getArrays().xy(&ar);
154 if (!coord_cache.getInsets().has(this)) {
156 //lyxerr << "no cached data for inset " << this << endl;
161 Point const pt2 = coord_cache.getInsets().xy(this);
162 //lyxerr << "retrieving position cache for MathData "
163 // << pt.x_ << ' ' << pt.y_ << endl;
164 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
166 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
167 // << " asc: " << ascent() << " des: " << descent()
168 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
169 // move cursor visually into empty cells ("blue rectangles");
175 void InsetMathNest::metrics(MetricsInfo const & mi) const
178 for (idx_type i = 0, n = nargs(); i != n; ++i) {
180 cell(i).metrics(m, dim);
185 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
187 for (idx_type i = 0, n = nargs(); i != n; ++i)
188 cell(i).updateBuffer(it, utype);
193 bool InsetMathNest::idxNext(Cursor & cur) const
195 LASSERT(&cur.inset() == this, return false);
196 if (cur.idx() == cur.lastidx())
204 bool InsetMathNest::idxForward(Cursor & cur) const
210 bool InsetMathNest::idxPrev(Cursor & cur) const
212 LASSERT(&cur.inset() == this, return false);
216 cur.pos() = cur.lastpos();
221 bool InsetMathNest::idxBackward(Cursor & cur) const
227 bool InsetMathNest::idxFirst(Cursor & cur) const
229 LASSERT(&cur.inset() == this, return false);
238 bool InsetMathNest::idxLast(Cursor & cur) const
240 LASSERT(&cur.inset() == this, return false);
243 cur.idx() = cur.lastidx();
244 cur.pos() = cur.lastpos();
249 void InsetMathNest::dump() const
251 odocstringstream oss;
253 os << "---------------------------------------------\n";
256 for (idx_type i = 0, n = nargs(); i != n; ++i)
257 os << cell(i) << "\n";
258 os << "---------------------------------------------\n";
259 lyxerr << to_utf8(oss.str());
263 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
267 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
270 setPosCache(pi, x, y);
274 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
276 BufferView & bv = *pi.base.bv;
277 // this should use the x/y values given, not the cached values
278 Cursor & cur = bv.cursor();
279 if (!cur.selection())
281 if (&cur.inset() != this)
284 // FIXME: hack to get position cache warm
285 bool const original_drawing_state = pi.pain.isDrawingEnabled();
286 pi.pain.setDrawingEnabled(false);
288 pi.pain.setDrawingEnabled(original_drawing_state);
290 CursorSlice s1 = cur.selBegin();
291 CursorSlice s2 = cur.selEnd();
293 //lyxerr << "InsetMathNest::drawing selection: "
294 // << " s1: " << s1 << " s2: " << s2 << endl;
295 if (s1.idx() == s2.idx()) {
296 MathData const & c = cell(s1.idx());
297 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
298 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
299 int y1 = g.pos.y_ - g.dim.ascent();
300 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
301 int y2 = g.pos.y_ + g.dim.descent();
302 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
303 //lyxerr << "InsetMathNest::drawing selection 3: "
304 // << " x1: " << x1 << " x2: " << x2
305 // << " y1: " << y1 << " y2: " << y2 << endl;
307 for (idx_type i = 0; i < nargs(); ++i) {
308 if (idxBetween(i, s1.idx(), s2.idx())) {
309 MathData const & c = cell(i);
310 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
312 int y1 = g.pos.y_ - g.dim.ascent();
313 int x2 = g.pos.x_ + g.dim.width();
314 int y2 = g.pos.y_ + g.dim.descent();
315 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
322 void InsetMathNest::validate(LaTeXFeatures & features) const
324 for (idx_type i = 0; i < nargs(); ++i)
325 cell(i).validate(features);
329 void InsetMathNest::replace(ReplaceData & rep)
331 for (idx_type i = 0; i < nargs(); ++i)
332 cell(i).replace(rep);
336 bool InsetMathNest::contains(MathData const & ar) const
338 for (idx_type i = 0; i < nargs(); ++i)
339 if (cell(i).contains(ar))
345 bool InsetMathNest::lock() const
351 void InsetMathNest::lock(bool l)
357 bool InsetMathNest::isActive() const
363 MathData InsetMathNest::glue() const
366 for (size_t i = 0; i < nargs(); ++i)
372 void InsetMathNest::write(WriteStream & os) const
374 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
375 ModeSpecifier specifier(os, currentMode(), lockedMode());
376 docstring const latex_name = name();
377 os << '\\' << latex_name;
378 for (size_t i = 0; i < nargs(); ++i)
379 os << '{' << cell(i) << '}';
381 os.pendingSpace(true);
382 if (lock_ && !os.latex()) {
384 os.pendingSpace(true);
389 void InsetMathNest::normalize(NormalStream & os) const
392 for (size_t i = 0; i < nargs(); ++i)
393 os << ' ' << cell(i);
398 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
400 WriteStream wi(os.os(), runparams.moving_arg, true,
401 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
403 wi.canBreakLine(os.canBreakLine());
405 // Reset parbreak status after a math inset.
407 os.canBreakLine(wi.canBreakLine());
410 if (lf > 0 && runparams.lastid != -1) {
412 os.texrow().newline();
413 os.texrow().start(runparams.lastid, runparams.lastpos);
415 os.texrow().newlines(lf);
419 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
422 mouse_hover_[bv] = mouse_hover;
427 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
431 MathData & ar = cur.cell();
432 // remove base-only "scripts"
433 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
434 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
435 if (p && p->nargs() == 1) {
436 MathData ar = p->nuc();
439 cur.adjust(i, ar.size() - 1);
443 // glue adjacent font insets of the same kind
444 for (pos_type i = 0; i + 1 < size(); ++i) {
445 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
446 InsetMathFont const * q = operator[](i + 1)->asFontInset();
447 if (p && q && p->name() == q->name()) {
448 p->cell(0).append(q->cell(0));
458 void InsetMathNest::handleFont
459 (Cursor & cur, docstring const & arg, char const * const font)
461 handleFont(cur, arg, from_ascii(font));
465 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
466 docstring const & font)
468 cur.recordUndoSelection();
470 // this whole function is a hack and won't work for incremental font
472 if (cur.inset().asInsetMath()->name() == font)
473 cur.handleFont(to_utf8(font));
475 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
479 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
481 handleNest(cur, nest, docstring());
485 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
486 docstring const & arg)
488 CursorSlice i1 = cur.selBegin();
489 CursorSlice i2 = cur.selEnd();
490 if (!i1.inset().asInsetMath())
492 if (i1.idx() == i2.idx()) {
493 // the easy case where only one cell is selected
494 cur.handleNest(nest);
499 // multiple selected cells in a simple non-grid inset
500 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
501 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
506 cur.pos() = cur.lastpos();
509 // change font of cell
510 cur.handleNest(nest);
513 // cur is in the font inset now. If the loop continues,
514 // we need to get outside again for the next cell
515 if (i + 1 <= i2.idx())
521 // the complicated case with multiple selected cells in a grid
524 cap::region(i1, i2, r1, r2, c1, c2);
525 for (row_type row = r1; row <= r2; ++row) {
526 for (col_type col = c1; col <= c2; ++col) {
528 cur.idx() = i1.asInsetMath()->index(row, col);
531 cur.pos() = cur.lastpos();
535 cur.handleNest(nest);
538 // cur is in the font inset now. If the loop continues,
539 // we need to get outside again for the next cell
540 if (col + 1 <= c2 || row + 1 <= r2)
547 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
549 cur.recordUndoSelection();
552 font.fromString(to_utf8(arg), b);
553 if (font.fontInfo().color() != Color_inherit &&
554 font.fontInfo().color() != Color_ignore)
555 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
557 // FIXME: support other font changes here as well?
561 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
563 //LYXERR0("InsetMathNest: request: " << cmd);
565 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
567 FuncCode const act = cmd.action();
570 case LFUN_CLIPBOARD_PASTE:
571 parseflg |= Parse::VERBATIM;
574 if (cur.currentMode() <= TEXT_MODE)
575 parseflg |= Parse::TEXTMODE;
576 cur.recordUndoSelection();
577 cur.message(_("Paste"));
578 replaceSelection(cur);
580 if (cmd.argument().empty() && !theClipboard().isInternal())
581 topaste = theClipboard().getAsText(Clipboard::PlainTextType);
584 idocstringstream is(cmd.argument());
586 topaste = cap::selection(n);
588 cur.niceInsert(topaste, parseflg, false);
589 cur.clearSelection(); // bug 393
590 cur.forceBufferUpdate();
597 cutSelection(cur, true, true);
598 cur.message(_("Cut"));
599 // Prevent stale position >= size crash
600 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
602 cur.forceBufferUpdate();
607 cur.message(_("Copy"));
610 case LFUN_MOUSE_PRESS:
611 lfunMousePress(cur, cmd);
614 case LFUN_MOUSE_MOTION:
615 lfunMouseMotion(cur, cmd);
618 case LFUN_MOUSE_RELEASE:
619 lfunMouseRelease(cur, cmd);
622 case LFUN_FINISHED_LEFT: // in math, left is backwards
623 case LFUN_FINISHED_BACKWARD:
624 cur.bv().cursor() = cur;
627 case LFUN_FINISHED_RIGHT: // in math, right is forward
628 case LFUN_FINISHED_FORWARD:
630 cur.bv().cursor() = cur;
633 case LFUN_CHAR_RIGHT:
635 case LFUN_CHAR_BACKWARD:
636 case LFUN_CHAR_FORWARD:
637 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
638 case LFUN_CHAR_RIGHT_SELECT:
639 case LFUN_CHAR_LEFT_SELECT:
640 case LFUN_CHAR_BACKWARD_SELECT:
641 case LFUN_CHAR_FORWARD_SELECT: {
642 // are we in a selection?
643 bool select = (act == LFUN_CHAR_RIGHT_SELECT
644 || act == LFUN_CHAR_LEFT_SELECT
645 || act == LFUN_CHAR_BACKWARD_SELECT
646 || act == LFUN_CHAR_FORWARD_SELECT);
647 // are we moving forward or backwards?
648 // If the command was RIGHT or LEFT, then whether we're moving forward
649 // or backwards depends on the cursor movement mode (logical or visual):
650 // * in visual mode, since math is always LTR, right -> forward,
652 // * in logical mode, the mapping is determined by the
653 // reverseDirectionNeeded() function
656 FuncCode finish_lfun;
658 if (act == LFUN_CHAR_FORWARD
659 || act == LFUN_CHAR_FORWARD_SELECT) {
661 finish_lfun = LFUN_FINISHED_FORWARD;
663 else if (act == LFUN_CHAR_BACKWARD
664 || act == LFUN_CHAR_BACKWARD_SELECT) {
666 finish_lfun = LFUN_FINISHED_BACKWARD;
669 bool right = (act == LFUN_CHAR_RIGHT_SELECT
670 || act == LFUN_CHAR_RIGHT);
671 if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
677 finish_lfun = LFUN_FINISHED_RIGHT;
679 finish_lfun = LFUN_FINISHED_LEFT;
681 // Now that we know exactly what we want to do, let's do it!
682 cur.selHandle(select);
684 cur.macroModeClose();
685 // try moving forward or backwards as necessary...
686 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
687 // ... and if movement failed, then finish forward or backwards
689 cmd = FuncRequest(finish_lfun);
697 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
698 case LFUN_DOWN_SELECT:
699 case LFUN_UP_SELECT: {
700 // close active macro
701 if (cur.inMacroMode()) {
702 cur.macroModeClose();
706 // stop/start the selection
707 bool select = act == LFUN_DOWN_SELECT ||
708 act == LFUN_UP_SELECT;
709 cur.selHandle(select);
711 // handle autocorrect:
712 cur.autocorrect() = false;
713 cur.message(_("Autocorrect Off ('!' to enter)"));
716 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
717 bool successful = cur.upDownInMath(up);
721 if (cur.fixIfBroken())
722 // FIXME: Something bad happened. We pass the corrected Cursor
723 // instead of letting things go worse.
726 // We did not manage to move the cursor.
731 case LFUN_MOUSE_DOUBLE:
732 case LFUN_MOUSE_TRIPLE:
733 case LFUN_WORD_SELECT:
737 cur.setSelection(true);
738 cur.idx() = cur.lastidx();
739 cur.pos() = cur.lastpos();
740 cur.bv().cursor() = cur;
743 case LFUN_PARAGRAPH_UP:
744 case LFUN_PARAGRAPH_DOWN:
745 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
746 case LFUN_PARAGRAPH_UP_SELECT:
747 case LFUN_PARAGRAPH_DOWN_SELECT:
750 case LFUN_LINE_BEGIN:
751 case LFUN_WORD_BACKWARD:
753 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
754 case LFUN_LINE_BEGIN_SELECT:
755 case LFUN_WORD_BACKWARD_SELECT:
756 case LFUN_WORD_LEFT_SELECT:
757 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
758 act == LFUN_WORD_LEFT_SELECT ||
759 act == LFUN_LINE_BEGIN_SELECT);
760 cur.macroModeClose();
761 if (cur.pos() != 0) {
763 } else if (cur.col() != 0) {
764 cur.idx() -= cur.col();
766 } else if (cur.idx() != 0) {
770 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
775 case LFUN_WORD_FORWARD:
776 case LFUN_WORD_RIGHT:
778 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
779 case LFUN_WORD_FORWARD_SELECT:
780 case LFUN_WORD_RIGHT_SELECT:
781 case LFUN_LINE_END_SELECT:
782 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
783 act == LFUN_WORD_RIGHT_SELECT ||
784 act == LFUN_LINE_END_SELECT);
785 cur.macroModeClose();
787 if (cur.pos() != cur.lastpos()) {
788 cur.pos() = cur.lastpos();
789 } else if (ncols() && (cur.col() != cur.lastcol())) {
790 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
791 cur.pos() = cur.lastpos();
792 } else if (cur.idx() != cur.lastidx()) {
793 cur.idx() = cur.lastidx();
794 cur.pos() = cur.lastpos();
796 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
801 case LFUN_CELL_FORWARD:
802 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
803 cur.inset().idxNext(cur);
806 case LFUN_CELL_BACKWARD:
807 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
808 cur.inset().idxPrev(cur);
811 case LFUN_WORD_DELETE_BACKWARD:
812 case LFUN_CHAR_DELETE_BACKWARD:
814 // May affect external cell:
815 cur.recordUndoInset();
816 else if (!cur.inMacroMode())
817 cur.recordUndoSelection();
818 // if the inset can not be removed from within, delete it
819 if (!cur.backspace()) {
820 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
821 cur.innerText()->dispatch(cur, cmd);
825 case LFUN_WORD_DELETE_FORWARD:
826 case LFUN_CHAR_DELETE_FORWARD:
827 if (cur.pos() == cur.lastpos())
828 // May affect external cell:
829 cur.recordUndoInset();
831 cur.recordUndoSelection();
832 // if the inset can not be removed from within, delete it
834 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
835 cur.innerText()->dispatch(cur, cmd);
841 cur.clearSelection();
843 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 if (cmd.argument().size() != 1) {
858 cur.recordUndoSelection();
859 docstring const arg = cmd.argument();
860 if (!interpretString(cur, arg))
864 // Don't record undo steps if we are in macro mode and thus
865 // cmd.argument is the next character of the macro name.
866 // Otherwise we'll get an invalid cursor if we undo after
867 // the macro was finished and the macro is a known command,
868 // e.g. sqrt. Cursor::macroModeClose replaces in this case
869 // the InsetMathUnknown with name "frac" by an empty
870 // InsetMathFrac -> a pos value > 0 is invalid.
871 // A side effect is that an undo before the macro is finished
872 // undoes the complete macro, not only the last character.
873 // At the time we hit '\' we are not in macro mode, still.
874 if (!cur.inMacroMode())
875 cur.recordUndoSelection();
877 // spacial handling of space. If we insert an inset
878 // via macro mode, we want to put the cursor inside it
879 // if relevant. Think typing "\frac<space>".
880 if (cmd.argument()[0] == ' '
881 && cur.inMacroMode() && cur.macroName() != "\\"
882 && cur.macroModeClose() && cur.pos() > 0) {
883 MathAtom const atom = cur.prevAtom();
884 if (atom->asNestInset() && atom->isActive()) {
886 cur.pushBackward(*cur.nextInset());
888 } else if (!interpretChar(cur, cmd.argument()[0])) {
889 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
894 //case LFUN_SERVER_GET_XY:
897 case LFUN_SERVER_SET_XY: {
898 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
901 istringstream is(to_utf8(cmd.argument()));
903 cur.setScreenPos(x, y);
907 // Special casing for superscript in case of LyX handling
909 case LFUN_ACCENT_CIRCUMFLEX:
910 if (cmd.argument().empty()) {
911 // do superscript if LyX handles
913 cur.recordUndoSelection();
914 script(cur, true, grabAndEraseSelection(cur));
918 case LFUN_ACCENT_UMLAUT:
919 case LFUN_ACCENT_ACUTE:
920 case LFUN_ACCENT_GRAVE:
921 case LFUN_ACCENT_BREVE:
922 case LFUN_ACCENT_DOT:
923 case LFUN_ACCENT_MACRON:
924 case LFUN_ACCENT_CARON:
925 case LFUN_ACCENT_TILDE:
926 case LFUN_ACCENT_CEDILLA:
927 case LFUN_ACCENT_CIRCLE:
928 case LFUN_ACCENT_UNDERDOT:
929 case LFUN_ACCENT_TIE:
930 case LFUN_ACCENT_OGONEK:
931 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
935 case LFUN_TEXTSTYLE_APPLY:
936 case LFUN_TEXTSTYLE_UPDATE:
937 handleFont2(cur, cmd.argument());
941 if (currentMode() <= TEXT_MODE)
942 handleFont(cur, cmd.argument(), "textbf");
944 handleFont(cur, cmd.argument(), "mathbf");
946 case LFUN_FONT_BOLDSYMBOL:
947 if (currentMode() <= TEXT_MODE)
948 handleFont(cur, cmd.argument(), "textbf");
950 handleFont(cur, cmd.argument(), "boldsymbol");
953 if (currentMode() <= TEXT_MODE)
954 handleFont(cur, cmd.argument(), "textsf");
956 handleFont(cur, cmd.argument(), "mathsf");
959 if (currentMode() <= TEXT_MODE)
960 handleFont(cur, cmd.argument(), "emph");
962 handleFont(cur, cmd.argument(), "mathcal");
964 case LFUN_FONT_ROMAN:
965 if (currentMode() <= TEXT_MODE)
966 handleFont(cur, cmd.argument(), "textrm");
968 handleFont(cur, cmd.argument(), "mathrm");
970 case LFUN_FONT_TYPEWRITER:
971 if (currentMode() <= TEXT_MODE)
972 handleFont(cur, cmd.argument(), "texttt");
974 handleFont(cur, cmd.argument(), "mathtt");
977 handleFont(cur, cmd.argument(), "mathfrak");
980 if (currentMode() <= TEXT_MODE)
981 handleFont(cur, cmd.argument(), "textit");
983 handleFont(cur, cmd.argument(), "mathit");
986 if (currentMode() <= TEXT_MODE)
987 // FIXME: should be "noun"
988 handleFont(cur, cmd.argument(), "textsc");
990 handleFont(cur, cmd.argument(), "mathbb");
992 case LFUN_FONT_DEFAULT:
993 handleFont(cur, cmd.argument(), "textnormal");
996 case LFUN_FONT_UNDERLINE:
998 cur.handleNest(createInsetMath("underline", cur.buffer()));
1000 case LFUN_MATH_MODE: {
1002 // ignore math-mode on when already in math mode
1003 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1005 cur.recordUndoSelection();
1006 cur.macroModeClose();
1007 docstring const save_selection = grabAndEraseSelection(cur);
1009 if (currentMode() <= Inset::TEXT_MODE)
1010 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1012 cur.plainInsert(MathAtom(new InsetMathBox(buffer_, from_ascii("mbox"))));
1014 cur.pushBackward(*cur.nextInset());
1015 cur.niceInsert(save_selection);
1016 cur.forceBufferUpdate();
1018 if (currentMode() == Inset::TEXT_MODE) {
1019 cur.recordUndoSelection();
1020 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1021 cur.message(_("create new math text environment ($...$)"));
1023 handleFont(cur, cmd.argument(), "textrm");
1024 cur.message(_("entered math text mode (textrm)"));
1030 case LFUN_REGEXP_MODE: {
1031 InsetMath * im = cur.inset().asInsetMath();
1033 InsetMathHull * i = im->asHullInset();
1034 if (i && i->getType() == hullRegexp) {
1035 cur.message(_("Already in regular expression mode"));
1039 cur.macroModeClose();
1040 docstring const save_selection = grabAndEraseSelection(cur);
1042 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1044 cur.pushBackward(*cur.nextInset());
1045 cur.niceInsert(save_selection);
1046 cur.message(_("Regular expression editor mode"));
1050 case LFUN_MATH_FONT_STYLE: {
1051 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1052 doDispatch(cur, fr);
1056 case LFUN_MATH_SIZE: {
1057 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1058 doDispatch(cur, fr);
1062 case LFUN_MATH_MATRIX: {
1068 idocstringstream is(cmd.argument());
1069 is >> m >> n >> v_align >> h_align;
1075 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1076 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1080 case LFUN_MATH_AMS_MATRIX: {
1084 docstring name = from_ascii("matrix");
1085 idocstringstream is(cmd.argument());
1086 is >> m >> n >> name;
1091 // check if we have a valid decoration
1092 if (name != "pmatrix" && name != "bmatrix"
1093 && name != "Bmatrix" && name != "vmatrix"
1094 && name != "Vmatrix" && name != "matrix")
1095 name = from_ascii("matrix");
1098 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1102 case LFUN_MATH_DELIM: {
1104 docstring rs = split(cmd.argument(), ls, ' ');
1105 // Reasonable default values
1111 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1115 case LFUN_MATH_BIGDELIM: {
1116 docstring const lname = from_utf8(cmd.getArg(0));
1117 docstring const ldelim = from_utf8(cmd.getArg(1));
1118 docstring const rname = from_utf8(cmd.getArg(2));
1119 docstring const rdelim = from_utf8(cmd.getArg(3));
1120 latexkeys const * l = in_word_set(lname);
1121 bool const have_l = l && l->inset == "big" &&
1122 InsetMathBig::isBigInsetDelim(ldelim);
1123 l = in_word_set(rname);
1124 bool const have_r = l && l->inset == "big" &&
1125 InsetMathBig::isBigInsetDelim(rdelim);
1126 // We mimic LFUN_MATH_DELIM in case we have an empty left
1127 // or right delimiter.
1128 if (have_l || have_r) {
1130 docstring const selection = grabAndEraseSelection(cur);
1133 cur.insert(MathAtom(new InsetMathBig(lname,
1135 // first insert the right delimiter and then go back
1136 // and re-insert the selection (bug 7088)
1138 cur.insert(MathAtom(new InsetMathBig(rname,
1142 cur.niceInsert(selection);
1144 // Don't call cur.undispatched() if we did nothing, this would
1145 // lead to infinite recursion via Text::dispatch().
1149 case LFUN_SPACE_INSERT: {
1150 cur.recordUndoSelection();
1151 string const name = cmd.getArg(0);
1152 if (name == "normal")
1153 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1154 else if (name == "protected")
1155 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1156 else if (name == "thin" || name == "med" || name == "thick")
1157 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1158 else if (name == "hfill*")
1159 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1160 else if (name == "quad" || name == "qquad" ||
1161 name == "enspace" || name == "enskip" ||
1162 name == "negthinspace" || name == "negmedspace" ||
1163 name == "negthickspace" || name == "hfill")
1164 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1165 else if (name == "hspace" || name == "hspace*") {
1166 string const len = cmd.getArg(1);
1167 if (len.empty() || !isValidLength(len)) {
1168 lyxerr << "LyX function 'space-insert " << name << "' "
1169 "needs a valid length argument." << endl;
1172 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1174 cur.insert(MathAtom(new InsetMathSpace));
1178 case LFUN_MATH_SPACE:
1179 cur.recordUndoSelection();
1180 if (cmd.argument().empty())
1181 cur.insert(MathAtom(new InsetMathSpace));
1183 string const name = cmd.getArg(0);
1184 string const len = cmd.getArg(1);
1185 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1189 case LFUN_ERT_INSERT:
1190 // interpret this as if a backslash was typed
1192 interpretChar(cur, '\\');
1195 case LFUN_MATH_SUBSCRIPT:
1196 // interpret this as if a _ was typed
1197 cur.recordUndoSelection();
1198 interpretChar(cur, '_');
1201 case LFUN_MATH_SUPERSCRIPT:
1202 // interpret this as if a ^ was typed
1203 cur.recordUndoSelection();
1204 interpretChar(cur, '^');
1207 case LFUN_MATH_MACRO_FOLD:
1208 case LFUN_MATH_MACRO_UNFOLD: {
1210 bool fold = act == LFUN_MATH_MACRO_FOLD;
1211 bool found = findMacroToFoldUnfold(it, fold);
1213 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1214 cur.recordUndoInset();
1223 case LFUN_QUOTE_INSERT:
1224 // interpret this as if a straight " was typed
1225 cur.recordUndoSelection();
1226 interpretChar(cur, '\"');
1229 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1230 // handling such that "self-insert" works on "arbitrary stuff" too, and
1231 // math-insert only handles special math things like "matrix".
1232 case LFUN_MATH_INSERT: {
1233 cur.recordUndoSelection();
1234 if (cmd.argument() == "^" || cmd.argument() == "_")
1235 interpretChar(cur, cmd.argument()[0]);
1238 asArray(cmd.argument(), ar);
1239 if (cur.selection() && ar.size() == 1
1240 && ar[0]->asNestInset()
1241 && ar[0]->asNestInset()->nargs() > 1)
1242 handleNest(cur, ar[0]);
1244 cur.niceInsert(cmd.argument());
1249 case LFUN_UNICODE_INSERT: {
1250 if (cmd.argument().empty())
1252 docstring hexstring = cmd.argument();
1253 if (isHex(hexstring)) {
1254 char_type c = hexToInt(hexstring);
1255 if (c >= 32 && c < 0x10ffff) {
1256 docstring s = docstring(1, c);
1257 FuncCode code = currentMode() == MATH_MODE ?
1258 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1259 lyx::dispatch(FuncRequest(code, s));
1265 case LFUN_DIALOG_SHOW_NEW_INSET: {
1266 docstring const & name = cmd.argument();
1268 if (name == "ref") {
1269 InsetMathRef tmp(buffer_, name);
1270 data = tmp.createDialogStr();
1271 cur.bv().showDialog(to_utf8(name), data);
1272 } else if (name == "mathspace") {
1273 cur.bv().showDialog(to_utf8(name));
1278 case LFUN_INSET_INSERT: {
1280 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1281 cur.recordUndoSelection();
1283 cur.forceBufferUpdate();
1288 case LFUN_INSET_DISSOLVE:
1289 if (!asHullInset()) {
1290 cur.recordUndoInset();
1296 InsetMath::doDispatch(cur, cmd);
1302 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1303 // look for macro to open/close, but stay in mathed
1304 for (; !it.empty(); it.pop_back()) {
1306 // go backward through the current cell
1307 Inset * inset = it.nextInset();
1308 while (inset && inset->asInsetMath()) {
1309 MathMacro * macro = inset->asInsetMath()->asMacro();
1311 // found the an macro to open/close?
1312 if (macro->folded() != fold)
1315 // Wrong folding state.
1316 // If this was the first we see in this slice, look further left,
1318 if (inset != it.nextInset())
1322 // go up if this was the left most position
1328 inset = it.nextInset();
1336 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1337 FuncStatus & flag) const
1339 // the font related toggles
1340 //string tc = "mathnormal";
1342 string const arg = to_utf8(cmd.argument());
1343 switch (cmd.action()) {
1344 case LFUN_INSET_MODIFY:
1345 flag.setEnabled(false);
1348 case LFUN_INSET_MODIFY:
1349 // FIXME: check temporarily disabled
1351 char align = mathcursor::valign();
1352 if (align == '\0') {
1356 if (cmd.argument().empty()) {
1360 if (!contains("tcb", cmd.argument()[0])) {
1364 flag.setOnOff(cmd.argument()[0] == align);
1367 /// We have to handle them since 1.4 blocks all unhandled actions
1368 case LFUN_FONT_ITAL:
1369 case LFUN_FONT_BOLD:
1370 case LFUN_FONT_BOLDSYMBOL:
1371 case LFUN_FONT_SANS:
1372 case LFUN_FONT_EMPH:
1373 case LFUN_FONT_TYPEWRITER:
1374 case LFUN_FONT_NOUN:
1375 case LFUN_FONT_ROMAN:
1376 case LFUN_FONT_DEFAULT:
1377 flag.setEnabled(true);
1380 // we just need to be in math mode to enable that
1381 case LFUN_MATH_SIZE:
1382 case LFUN_MATH_SPACE:
1383 case LFUN_MATH_EXTERN:
1384 flag.setEnabled(true);
1387 case LFUN_FONT_UNDERLINE:
1388 case LFUN_FONT_FRAK:
1389 flag.setEnabled(currentMode() != TEXT_MODE);
1392 case LFUN_MATH_FONT_STYLE: {
1393 bool const textarg =
1394 arg == "textbf" || arg == "textsf" ||
1395 arg == "textrm" || arg == "textmd" ||
1396 arg == "textit" || arg == "textsc" ||
1397 arg == "textsl" || arg == "textup" ||
1398 arg == "texttt" || arg == "textbb" ||
1399 arg == "textnormal";
1400 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1404 case LFUN_MATH_MODE:
1405 // forbid "math-mode on" in math mode to prevent irritating
1406 // behaviour of menu entries (bug 6709)
1407 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1410 case LFUN_MATH_INSERT:
1411 flag.setEnabled(currentMode() != TEXT_MODE);
1414 case LFUN_MATH_AMS_MATRIX:
1415 case LFUN_MATH_MATRIX:
1416 flag.setEnabled(currentMode() == MATH_MODE);
1419 case LFUN_INSET_INSERT: {
1420 // Don't test createMathInset_fromDialogStr(), since
1421 // getStatus is not called with a valid reference and the
1422 // dialog would not be applyable.
1423 string const name = cmd.getArg(0);
1424 flag.setEnabled(name == "ref" || name == "mathspace");
1428 case LFUN_DIALOG_SHOW_NEW_INSET: {
1429 docstring const & name = cmd.argument();
1430 if (name == "space")
1431 flag.setEnabled(false);
1436 case LFUN_MATH_DELIM:
1437 case LFUN_MATH_BIGDELIM:
1438 // Don't do this with multi-cell selections
1439 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1442 case LFUN_MATH_MACRO_FOLD:
1443 case LFUN_MATH_MACRO_UNFOLD: {
1445 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1446 flag.setEnabled(found);
1450 case LFUN_SPECIALCHAR_INSERT:
1451 case LFUN_SCRIPT_INSERT:
1452 // FIXME: These would probably make sense in math-text mode
1453 flag.setEnabled(false);
1456 case LFUN_CAPTION_INSERT:
1457 flag.setEnabled(false);
1460 case LFUN_SPACE_INSERT: {
1461 docstring const & name = cmd.argument();
1462 if (name == "visible")
1463 flag.setEnabled(false);
1467 case LFUN_INSET_DISSOLVE:
1468 flag.setEnabled(!asHullInset());
1472 docstring const & name = cmd.argument();
1473 if (name == "html" || name == "latex")
1474 flag.setEnabled(false);
1486 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1489 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1490 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1491 cur.idx() = enter_front ? 0 : cur.lastidx();
1492 cur.pos() = enter_front ? 0 : cur.lastpos();
1494 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1498 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1501 int dist_min = 1000000;
1502 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1503 int const d = cell(i).dist(cur.bv(), x, y);
1509 MathData & ar = cell(idx_min);
1511 cur.idx() = idx_min;
1512 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1514 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1515 if (dist_min == 0) {
1517 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1518 if (ar[i]->covers(cur.bv(), x, y))
1519 return ar[i].nucleus()->editXY(cur, x, y);
1525 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1527 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1528 BufferView & bv = cur.bv();
1529 if (cmd.button() == mouse_button::button3) {
1530 // Don't do anything if we right-click a
1531 // selection, a context menu will popup.
1532 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1533 && cur < bv.cursor().selectionEnd()) {
1534 cur.noScreenUpdate();
1538 bool do_selection = cmd.button() == mouse_button::button1
1539 && cmd.argument() == "region-select";
1540 bv.mouseSetCursor(cur, do_selection);
1541 if (cmd.button() == mouse_button::button1) {
1542 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1543 // Update the cursor update flags as needed:
1545 // Update::Decoration: tells to update the decoration
1546 // (visual box corners that define
1548 // Update::FitCursor: adjust the screen to the cursor
1549 // position if needed
1550 // cur.result().update(): don't overwrite previously set flags.
1551 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1552 | cur.result().screenUpdate());
1553 } else if (cmd.button() == mouse_button::button2) {
1554 if (cap::selection()) {
1555 // See comment in Text::dispatch why we do this
1556 cap::copySelectionToStack();
1557 cmd = FuncRequest(LFUN_PASTE, "0");
1558 doDispatch(bv.cursor(), cmd);
1561 asArray(theSelection().get(), ar);
1562 bv.cursor().insert(ar);
1568 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1570 // only select with button 1
1571 if (cmd.button() != mouse_button::button1)
1574 Cursor & bvcur = cur.bv().cursor();
1576 // ignore motions deeper nested than the real anchor
1577 if (!bvcur.realAnchor().hasPart(cur)) {
1582 CursorSlice old = bvcur.top();
1584 // We continue with our existing selection or start a new one, so don't
1585 // reset the anchor.
1586 bvcur.setCursor(cur);
1587 // Did we actually move?
1588 if (cur.top() == old)
1589 // We didn't move one iota, so no need to change selection status
1590 // or update the screen.
1591 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1593 bvcur.setSelection();
1597 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1599 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1601 if (cmd.button() == mouse_button::button1) {
1602 if (!cur.selection())
1603 cur.noScreenUpdate();
1605 Cursor & bvcur = cur.bv().cursor();
1606 bvcur.setSelection(true);
1615 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1617 //lyxerr << "interpret 2: '" << c << "'" << endl;
1618 docstring save_selection;
1619 if (c == '^' || c == '_')
1620 save_selection = grabAndEraseSelection(cur);
1623 Buffer * buf = cur.buffer();
1626 if (cur.inMacroMode()) {
1627 docstring name = cur.macroName();
1629 /// are we currently typing '#1' or '#2' or...?
1630 if (name == "\\#") {
1633 if (n >= 1 && n <= 9)
1634 cur.insert(new MathMacroArgument(n));
1638 // do not finish macro for known * commands
1639 bool star_macro = c == '*'
1640 && (in_word_set(name.substr(1) + '*')
1641 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1642 if (isAlphaASCII(c) || star_macro) {
1643 cur.activeMacro()->setName(name + docstring(1, c));
1647 // handle 'special char' macros
1652 if (currentMode() <= InsetMath::TEXT_MODE)
1653 cur.niceInsert(createInsetMath("textbackslash", buf));
1655 cur.niceInsert(createInsetMath("backslash", buf));
1656 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1658 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1659 } else if (c == '{') {
1661 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1662 } else if (c == '%') {
1664 cur.niceInsert(MathAtom(new InsetMathComment(buf)));
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.setSelection(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::TEXT_MODE)
1769 if (currentMode() <= InsetMath::TEXT_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("backslash", buf));
1814 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1821 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1824 cur.niceInsert(createInsetMath("sim", buf));
1830 } else if (currentMode() != InsetMath::TEXT_MODE) {
1832 script(cur, false, save_selection);
1836 script(cur, true, save_selection);
1840 cur.niceInsert(createInsetMath("sim", buf));
1843 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1844 MathAtom at = createInsetMath("text", buf);
1845 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1852 cur.niceInsert(createInsetMath("textasciicircum", buf));
1856 cur.niceInsert(createInsetMath("textasciitilde", buf));
1861 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1862 c == '%' || c == '_') {
1863 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1868 // try auto-correction
1869 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1870 && math_autocorrect(cur.prevAtom(), c))
1873 // no special circumstances, so insert the character without any fuss
1875 if (lyxrc.autocorrection_math) {
1876 if (!cur.autocorrect())
1877 cur.message(_("Autocorrect Off ('!' to enter)"));
1879 cur.message(_("Autocorrect On (<space> to exit)"));
1885 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1887 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1889 if (!cur.empty() && cur.pos() > 0 &&
1890 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1891 if (InsetMathBig::isBigInsetDelim(str)) {
1892 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1893 if (prev[0] == '\\') {
1894 prev = prev.substr(1);
1895 latexkeys const * l = in_word_set(prev);
1896 if (l && l->inset == "big") {
1897 cur.cell()[cur.pos() - 1] =
1898 MathAtom(new InsetMathBig(prev, str));
1908 bool InsetMathNest::script(Cursor & cur, bool up)
1910 return script(cur, up, docstring());
1914 bool InsetMathNest::script(Cursor & cur, bool up,
1915 docstring const & save_selection)
1917 // Hack to get \^ and \_ working
1918 //lyxerr << "handling script: up: " << up << endl;
1919 if (cur.inMacroMode() && cur.macroName() == "\\") {
1921 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1923 interpretChar(cur, '_');
1927 cur.macroModeClose();
1928 if (asScriptInset() && cur.idx() == 0) {
1929 // we are in a nucleus of a script inset, move to _our_ script
1930 InsetMathScript * inset = asScriptInset();
1931 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1933 cur.idx() = inset->idxOfScript(up);
1935 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1937 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1940 cur.idx() = inset->idxOfScript(up);
1941 cur.pos() = cur.lastpos();
1943 // convert the thing to our left to a scriptinset or create a new
1944 // one if in the very first position of the array
1945 if (cur.pos() == 0) {
1946 //lyxerr << "new scriptinset" << endl;
1947 cur.insert(new InsetMathScript(buffer_, up));
1949 //lyxerr << "converting prev atom " << endl;
1950 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1953 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1954 // See comment in MathParser.cpp for special handling of {}-bases
1960 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1961 cur.niceInsert(save_selection);
1963 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1968 bool InsetMathNest::completionSupported(Cursor const & cur) const
1970 return cur.inMacroMode();
1974 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1976 return cur.inMacroMode();
1980 bool InsetMathNest::automaticInlineCompletion() const
1982 return lyxrc.completion_inline_math;
1986 bool InsetMathNest::automaticPopupCompletion() const
1988 return lyxrc.completion_popup_math;
1992 CompletionList const *
1993 InsetMathNest::createCompletionList(Cursor const & cur) const
1995 if (!cur.inMacroMode())
1998 return new MathCompletionList(cur);
2002 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2004 if (!cur.inMacroMode())
2007 return cur.activeMacro()->name();
2011 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2014 if (!cur.inMacroMode())
2017 // append completion to active macro
2018 InsetMathUnknown * inset = cur.activeMacro();
2019 inset->setName(inset->name() + s);
2024 // FIXME: this creates duplicates in the completion popup
2025 // which looks ugly. Moreover the changes the list lengths
2027 confuse the popup as well.
2028 MathCompletionList::addToFavorites(inset->name());
2030 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2037 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2038 Dimension & dim) const
2040 Inset const * inset = cur.activeMacro();
2044 // get inset dimensions
2045 dim = cur.bv().coordCache().insets().dim(inset);
2046 // FIXME: these 3 are no accurate, but should depend on the font.
2047 // Now the popup jumps down if you enter a char with descent > 0.
2052 Point xy = cur.bv().coordCache().insets().xy(inset);
2058 bool InsetMathNest::cursorMathForward(Cursor & cur)
2060 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2061 cur.pushBackward(*cur.nextAtom().nucleus());
2062 cur.inset().idxFirst(cur);
2065 if (cur.posForward() || idxForward(cur))
2067 // try to pop forwards --- but don't pop out of math! leave that to
2069 int s = cur.depth() - 2;
2070 if (s >= 0 && cur[s].inset().asInsetMath())
2071 return cur.popForward();
2076 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2078 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2080 cur.push(*cur.nextAtom().nucleus());
2081 cur.inset().idxLast(cur);
2084 if (cur.posBackward() || idxBackward(cur))
2086 // try to pop backwards --- but don't pop out of math! leave that to
2088 int s = cur.depth() - 2;
2089 if (s >= 0 && cur[s].inset().asInsetMath())
2090 return cur.popBackward();
2095 ////////////////////////////////////////////////////////////////////
2097 MathCompletionList::MathCompletionList(Cursor const & cur)
2099 // fill it with macros from the buffer
2100 MacroNameSet macros;
2101 cur.buffer()->listMacroNames(macros);
2102 MacroNameSet::const_iterator it;
2103 for (it = macros.begin(); it != macros.end(); ++it) {
2104 if (cur.buffer()->getMacro(*it, cur, false))
2105 locals.push_back("\\" + *it);
2107 sort(locals.begin(), locals.end());
2109 if (!globals.empty())
2112 // fill in global macros
2114 MacroTable::globalMacros().getMacroNames(macros);
2115 //lyxerr << "Globals completion macros: ";
2116 for (it = macros.begin(); it != macros.end(); ++it) {
2117 //lyxerr << "\\" + *it << " ";
2118 globals.push_back("\\" + *it);
2120 //lyxerr << std::endl;
2122 // fill in global commands
2123 globals.push_back(from_ascii("\\boxed"));
2124 globals.push_back(from_ascii("\\fbox"));
2125 globals.push_back(from_ascii("\\framebox"));
2126 globals.push_back(from_ascii("\\makebox"));
2127 globals.push_back(from_ascii("\\kern"));
2128 globals.push_back(from_ascii("\\xhookrightarrow"));
2129 globals.push_back(from_ascii("\\xhookleftarrow"));
2130 globals.push_back(from_ascii("\\xrightarrow"));
2131 globals.push_back(from_ascii("\\xRightarrow"));
2132 globals.push_back(from_ascii("\\xrightharpoondown"));
2133 globals.push_back(from_ascii("\\xrightharpoonup"));
2134 globals.push_back(from_ascii("\\xrightleftharpoons"));
2135 globals.push_back(from_ascii("\\xleftarrow"));
2136 globals.push_back(from_ascii("\\xLeftarrow"));
2137 globals.push_back(from_ascii("\\xleftharpoondown"));
2138 globals.push_back(from_ascii("\\xleftharpoonup"));
2139 globals.push_back(from_ascii("\\xleftrightarrow"));
2140 globals.push_back(from_ascii("\\xLeftrightarrow"));
2141 globals.push_back(from_ascii("\\xleftrightharpoons"));
2142 globals.push_back(from_ascii("\\xmapsto"));
2143 globals.push_back(from_ascii("\\split"));
2144 globals.push_back(from_ascii("\\gathered"));
2145 globals.push_back(from_ascii("\\aligned"));
2146 globals.push_back(from_ascii("\\alignedat"));
2147 globals.push_back(from_ascii("\\cases"));
2148 globals.push_back(from_ascii("\\substack"));
2149 globals.push_back(from_ascii("\\xymatrix"));
2150 globals.push_back(from_ascii("\\Diagram"));
2151 globals.push_back(from_ascii("\\subarray"));
2152 globals.push_back(from_ascii("\\array"));
2153 globals.push_back(from_ascii("\\sqrt"));
2154 globals.push_back(from_ascii("\\root"));
2155 globals.push_back(from_ascii("\\tabular"));
2156 globals.push_back(from_ascii("\\stackrel"));
2157 globals.push_back(from_ascii("\\stackrelthree"));
2158 globals.push_back(from_ascii("\\binom"));
2159 globals.push_back(from_ascii("\\choose"));
2160 globals.push_back(from_ascii("\\brace"));
2161 globals.push_back(from_ascii("\\brack"));
2162 globals.push_back(from_ascii("\\frac"));
2163 globals.push_back(from_ascii("\\over"));
2164 globals.push_back(from_ascii("\\nicefrac"));
2165 globals.push_back(from_ascii("\\unitfrac"));
2166 globals.push_back(from_ascii("\\unitfracthree"));
2167 globals.push_back(from_ascii("\\unitone"));
2168 globals.push_back(from_ascii("\\unittwo"));
2169 globals.push_back(from_ascii("\\infer"));
2170 globals.push_back(from_ascii("\\atop"));
2171 globals.push_back(from_ascii("\\lefteqn"));
2172 globals.push_back(from_ascii("\\boldsymbol"));
2173 globals.push_back(from_ascii("\\bm"));
2174 globals.push_back(from_ascii("\\color"));
2175 globals.push_back(from_ascii("\\normalcolor"));
2176 globals.push_back(from_ascii("\\textcolor"));
2177 globals.push_back(from_ascii("\\cfrac"));
2178 globals.push_back(from_ascii("\\cfracleft"));
2179 globals.push_back(from_ascii("\\cfracright"));
2180 globals.push_back(from_ascii("\\dfrac"));
2181 globals.push_back(from_ascii("\\tfrac"));
2182 globals.push_back(from_ascii("\\dbinom"));
2183 globals.push_back(from_ascii("\\tbinom"));
2184 globals.push_back(from_ascii("\\hphantom"));
2185 globals.push_back(from_ascii("\\phantom"));
2186 globals.push_back(from_ascii("\\vphantom"));
2187 globals.push_back(from_ascii("\\cancel"));
2188 globals.push_back(from_ascii("\\bcancel"));
2189 globals.push_back(from_ascii("\\xcancel"));
2190 globals.push_back(from_ascii("\\cancelto"));
2191 globals.push_back(from_ascii("\\smash"));
2192 globals.push_back(from_ascii("\\mathclap"));
2193 globals.push_back(from_ascii("\\mathllap"));
2194 globals.push_back(from_ascii("\\mathrlap"));
2195 MathWordList const & words = mathedWordList();
2196 MathWordList::const_iterator it2;
2197 //lyxerr << "Globals completion commands: ";
2198 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2199 if (it2->second.inset != "macro") {
2200 // macros are already read from MacroTable::globalMacros()
2201 globals.push_back('\\' + it2->first);
2202 //lyxerr << '\\' + it2->first << ' ';
2205 //lyxerr << std::endl;
2206 sort(globals.begin(), globals.end());
2210 MathCompletionList::~MathCompletionList()
2215 size_type MathCompletionList::size() const
2217 return locals.size() + globals.size();
2221 docstring const & MathCompletionList::data(size_t idx) const
2223 size_t lsize = locals.size();
2225 return globals[idx - lsize];
2231 std::string MathCompletionList::icon(size_t idx) const
2233 // get the latex command
2235 size_t lsize = locals.size();
2237 cmd = globals[idx - lsize];
2241 // get the icon resource name by stripping the backslash
2242 return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
2245 std::vector<docstring> MathCompletionList::globals;