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"
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"
53 #include "OutputParams.h"
56 #include "frontends/Application.h"
57 #include "frontends/Clipboard.h"
58 #include "frontends/Painter.h"
59 #include "frontends/Selection.h"
61 #include "support/lassert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
66 #include "support/docstream.h"
72 using namespace lyx::support;
76 using cap::copySelection;
77 using cap::grabAndEraseSelection;
78 using cap::cutSelection;
79 using cap::replaceSelection;
80 using cap::selClearOrDel;
83 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
84 : InsetMath(buf), cells_(nargs), lock_(false)
90 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
91 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
95 InsetMathNest::~InsetMathNest()
97 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
98 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
99 for (; it != end; ++it)
101 it->first->clearLastInset(this);
105 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
107 cells_ = inset.cells_;
109 mouse_hover_.clear();
110 InsetMath::operator=(inset);
115 void InsetMathNest::setBuffer(Buffer & buffer)
117 InsetMath::setBuffer(buffer);
118 for (idx_type i = 0, n = nargs(); i != n; ++i) {
119 MathData & data = cell(i);
120 for (size_t j = 0; j != data.size(); ++j)
121 data[j].nucleus()->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");
176 void InsetMathNest::metrics(MetricsInfo const & mi) const
179 for (idx_type i = 0, n = nargs(); i != n; ++i) {
181 cell(i).metrics(m, dim);
186 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
188 for (idx_type i = 0, n = nargs(); i != n; ++i)
189 cell(i).updateBuffer(it, utype);
194 bool InsetMathNest::idxNext(Cursor & cur) const
196 LASSERT(&cur.inset() == this, return false);
197 if (cur.idx() == cur.lastidx())
205 bool InsetMathNest::idxForward(Cursor & cur) const
211 bool InsetMathNest::idxPrev(Cursor & cur) const
213 LASSERT(&cur.inset() == this, return false);
217 cur.pos() = cur.lastpos();
222 bool InsetMathNest::idxBackward(Cursor & cur) const
228 bool InsetMathNest::idxFirst(Cursor & cur) const
230 LASSERT(&cur.inset() == this, return false);
239 bool InsetMathNest::idxLast(Cursor & cur) const
241 LASSERT(&cur.inset() == this, return false);
244 cur.idx() = cur.lastidx();
245 cur.pos() = cur.lastpos();
250 void InsetMathNest::dump() const
252 odocstringstream oss;
253 TexRow texrow(false);
254 otexrowstream ots(oss,texrow);
256 os << "---------------------------------------------\n";
259 for (idx_type i = 0, n = nargs(); i != n; ++i)
260 os << cell(i) << "\n";
261 os << "---------------------------------------------\n";
262 lyxerr << to_utf8(oss.str());
266 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
270 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
273 setPosCache(pi, x, y);
277 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
279 BufferView & bv = *pi.base.bv;
280 // this should use the x/y values given, not the cached values
281 Cursor & cur = bv.cursor();
282 if (!cur.selection())
284 if (&cur.inset() != this)
287 // FIXME: hack to get position cache warm
288 bool const original_drawing_state = pi.pain.isDrawingEnabled();
289 pi.pain.setDrawingEnabled(false);
291 pi.pain.setDrawingEnabled(original_drawing_state);
293 CursorSlice s1 = cur.selBegin();
294 CursorSlice s2 = cur.selEnd();
296 //lyxerr << "InsetMathNest::drawing selection: "
297 // << " s1: " << s1 << " s2: " << s2 << endl;
298 if (s1.idx() == s2.idx()) {
299 MathData const & c = cell(s1.idx());
300 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
301 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
302 int y1 = g.pos.y_ - g.dim.ascent();
303 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
304 int y2 = g.pos.y_ + g.dim.descent();
305 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
306 //lyxerr << "InsetMathNest::drawing selection 3: "
307 // << " x1: " << x1 << " x2: " << x2
308 // << " y1: " << y1 << " y2: " << y2 << endl;
310 for (idx_type i = 0; i < nargs(); ++i) {
311 if (idxBetween(i, s1.idx(), s2.idx())) {
312 MathData const & c = cell(i);
313 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
315 int y1 = g.pos.y_ - g.dim.ascent();
316 int x2 = g.pos.x_ + g.dim.width();
317 int y2 = g.pos.y_ + g.dim.descent();
318 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
325 void InsetMathNest::validate(LaTeXFeatures & features) const
327 for (idx_type i = 0; i < nargs(); ++i)
328 cell(i).validate(features);
332 void InsetMathNest::replace(ReplaceData & rep)
334 for (idx_type i = 0; i < nargs(); ++i)
335 cell(i).replace(rep);
339 bool InsetMathNest::contains(MathData const & ar) const
341 for (idx_type i = 0; i < nargs(); ++i)
342 if (cell(i).contains(ar))
348 bool InsetMathNest::lock() const
354 void InsetMathNest::lock(bool l)
360 bool InsetMathNest::isActive() const
366 MathData InsetMathNest::glue() const
369 for (size_t i = 0; i < nargs(); ++i)
375 void InsetMathNest::write(WriteStream & os) const
377 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
378 ModeSpecifier specifier(os, currentMode(), lockedMode());
379 docstring const latex_name = name();
380 os << '\\' << latex_name;
381 for (size_t i = 0; i < nargs(); ++i) {
382 os.pushRowEntry(TexRow::mathEntry(id(),i));
383 os << '{' << cell(i) << '}';
387 os.pendingSpace(true);
388 if (lock_ && !os.latex()) {
390 os.pendingSpace(true);
395 void InsetMathNest::normalize(NormalStream & os) const
398 for (size_t i = 0; i < nargs(); ++i)
399 os << ' ' << cell(i);
404 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
406 WriteStream wi(os, runparams.moving_arg, true,
407 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
409 wi.canBreakLine(os.canBreakLine());
410 if (runparams.lastid != -1) {
411 wi.pushRowEntry(os.texrow().textEntry(runparams.lastid,
417 // Reset parbreak status after a math inset.
419 os.canBreakLine(wi.canBreakLine());
423 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
426 mouse_hover_[bv] = mouse_hover;
431 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
435 MathData & ar = cur.cell();
436 // remove base-only "scripts"
437 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
438 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
439 if (p && p->nargs() == 1) {
440 MathData ar = p->nuc();
443 cur.adjust(i, ar.size() - 1);
447 // glue adjacent font insets of the same kind
448 for (pos_type i = 0; i + 1 < size(); ++i) {
449 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
450 InsetMathFont const * q = operator[](i + 1)->asFontInset();
451 if (p && q && p->name() == q->name()) {
452 p->cell(0).append(q->cell(0));
462 void InsetMathNest::handleFont
463 (Cursor & cur, docstring const & arg, char const * const font)
465 handleFont(cur, arg, from_ascii(font));
469 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
470 docstring const & font)
472 cur.recordUndoSelection();
474 // this whole function is a hack and won't work for incremental font
476 if (cur.inset().asInsetMath()->name() == font)
477 cur.handleFont(to_utf8(font));
479 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
483 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
485 handleNest(cur, nest, docstring());
489 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
490 docstring const & arg)
492 CursorSlice i1 = cur.selBegin();
493 CursorSlice i2 = cur.selEnd();
494 if (!i1.inset().asInsetMath())
496 if (i1.idx() == i2.idx()) {
497 // the easy case where only one cell is selected
498 cur.handleNest(nest);
503 // multiple selected cells in a simple non-grid inset
504 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
505 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
510 cur.pos() = cur.lastpos();
513 // change font of cell
514 cur.handleNest(nest);
517 // cur is in the font inset now. If the loop continues,
518 // we need to get outside again for the next cell
519 if (i + 1 <= i2.idx())
525 // the complicated case with multiple selected cells in a grid
528 cap::region(i1, i2, r1, r2, c1, c2);
529 for (row_type row = r1; row <= r2; ++row) {
530 for (col_type col = c1; col <= c2; ++col) {
532 cur.idx() = i1.asInsetMath()->index(row, col);
535 cur.pos() = cur.lastpos();
539 cur.handleNest(nest);
542 // cur is in the font inset now. If the loop continues,
543 // we need to get outside again for the next cell
544 if (col + 1 <= c2 || row + 1 <= r2)
551 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
553 cur.recordUndoSelection();
556 font.fromString(to_utf8(arg), b);
557 if (font.fontInfo().color() != Color_inherit &&
558 font.fontInfo().color() != Color_ignore)
559 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
561 // FIXME: support other font changes here as well?
565 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
567 //LYXERR0("InsetMathNest: request: " << cmd);
569 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
571 FuncCode const act = cmd.action();
574 case LFUN_CLIPBOARD_PASTE:
575 parseflg |= Parse::VERBATIM;
578 if (cur.currentMode() <= TEXT_MODE)
579 parseflg |= Parse::TEXTMODE;
580 cur.recordUndoSelection();
581 cur.message(_("Paste"));
582 replaceSelection(cur);
584 if (cmd.argument().empty() && !theClipboard().isInternal())
585 topaste = theClipboard().getAsText(Clipboard::PlainTextType);
588 idocstringstream is(cmd.argument());
590 topaste = cap::selection(n, buffer().params().documentClassPtr());
592 cur.niceInsert(topaste, parseflg, false);
593 cur.clearSelection(); // bug 393
594 cur.forceBufferUpdate();
601 cutSelection(cur, true, true);
602 cur.message(_("Cut"));
603 // Prevent stale position >= size crash
604 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
606 cur.forceBufferUpdate();
611 cur.message(_("Copy"));
614 case LFUN_MOUSE_PRESS:
615 lfunMousePress(cur, cmd);
618 case LFUN_MOUSE_MOTION:
619 lfunMouseMotion(cur, cmd);
622 case LFUN_MOUSE_RELEASE:
623 lfunMouseRelease(cur, cmd);
626 case LFUN_FINISHED_LEFT: // in math, left is backwards
627 case LFUN_FINISHED_BACKWARD:
628 cur.bv().cursor() = cur;
631 case LFUN_FINISHED_RIGHT: // in math, right is forward
632 case LFUN_FINISHED_FORWARD:
634 cur.bv().cursor() = cur;
637 case LFUN_CHAR_RIGHT:
639 case LFUN_CHAR_BACKWARD:
640 case LFUN_CHAR_FORWARD:
641 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
643 case LFUN_CHAR_RIGHT_SELECT:
644 case LFUN_CHAR_LEFT_SELECT:
645 case LFUN_CHAR_BACKWARD_SELECT:
646 case LFUN_CHAR_FORWARD_SELECT: {
647 // are we in a selection?
648 bool select = (act == LFUN_CHAR_RIGHT_SELECT
649 || act == LFUN_CHAR_LEFT_SELECT
650 || act == LFUN_CHAR_BACKWARD_SELECT
651 || act == LFUN_CHAR_FORWARD_SELECT);
652 // are we moving forward or backwards?
653 // If the command was RIGHT or LEFT, then whether we're moving forward
654 // or backwards depends on the cursor movement mode (logical or visual):
655 // * in visual mode, since math is always LTR, right -> forward,
657 // * in logical mode, the mapping is determined by the
658 // reverseDirectionNeeded() function
661 FuncCode finish_lfun;
663 if (act == LFUN_CHAR_FORWARD
664 || act == LFUN_CHAR_FORWARD_SELECT) {
666 finish_lfun = LFUN_FINISHED_FORWARD;
668 else if (act == LFUN_CHAR_BACKWARD
669 || act == LFUN_CHAR_BACKWARD_SELECT) {
671 finish_lfun = LFUN_FINISHED_BACKWARD;
674 bool right = (act == LFUN_CHAR_RIGHT_SELECT
675 || act == LFUN_CHAR_RIGHT);
676 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
682 finish_lfun = LFUN_FINISHED_RIGHT;
684 finish_lfun = LFUN_FINISHED_LEFT;
686 // Now that we know exactly what we want to do, let's do it!
687 cur.selHandle(select);
689 cur.macroModeClose();
690 // try moving forward or backwards as necessary...
691 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
692 // ... and if movement failed, then finish forward or backwards
694 cmd = FuncRequest(finish_lfun);
702 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
704 case LFUN_DOWN_SELECT:
705 case LFUN_UP_SELECT: {
706 // close active macro
707 if (cur.inMacroMode()) {
708 cur.macroModeClose();
712 // stop/start the selection
713 bool select = act == LFUN_DOWN_SELECT ||
714 act == LFUN_UP_SELECT;
715 cur.selHandle(select);
717 // handle autocorrect:
718 cur.autocorrect() = false;
719 cur.message(_("Autocorrect Off ('!' to enter)"));
722 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
723 bool successful = cur.upDownInMath(up);
727 if (cur.fixIfBroken())
728 // FIXME: Something bad happened. We pass the corrected Cursor
729 // instead of letting things go worse.
732 // We did not manage to move the cursor.
737 case LFUN_MOUSE_DOUBLE:
738 case LFUN_MOUSE_TRIPLE:
739 case LFUN_WORD_SELECT:
743 cur.setSelection(true);
744 cur.idx() = cur.lastidx();
745 cur.pos() = cur.lastpos();
746 cur.bv().cursor() = cur;
749 case LFUN_PARAGRAPH_UP:
750 case LFUN_PARAGRAPH_DOWN:
751 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
753 case LFUN_PARAGRAPH_UP_SELECT:
754 case LFUN_PARAGRAPH_DOWN_SELECT:
757 case LFUN_LINE_BEGIN:
758 case LFUN_WORD_BACKWARD:
760 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
762 case LFUN_LINE_BEGIN_SELECT:
763 case LFUN_WORD_BACKWARD_SELECT:
764 case LFUN_WORD_LEFT_SELECT:
765 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
766 act == LFUN_WORD_LEFT_SELECT ||
767 act == LFUN_LINE_BEGIN_SELECT);
768 cur.macroModeClose();
769 if (cur.pos() != 0) {
771 } else if (cur.col() != 0) {
772 cur.idx() -= cur.col();
774 } else if (cur.idx() != 0) {
778 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
783 case LFUN_WORD_FORWARD:
784 case LFUN_WORD_RIGHT:
786 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
788 case LFUN_WORD_FORWARD_SELECT:
789 case LFUN_WORD_RIGHT_SELECT:
790 case LFUN_LINE_END_SELECT:
791 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
792 act == LFUN_WORD_RIGHT_SELECT ||
793 act == LFUN_LINE_END_SELECT);
794 cur.macroModeClose();
796 if (cur.pos() != cur.lastpos()) {
797 cur.pos() = cur.lastpos();
798 } else if (ncols() && (cur.col() != cur.lastcol())) {
799 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
800 cur.pos() = cur.lastpos();
801 } else if (cur.idx() != cur.lastidx()) {
802 cur.idx() = cur.lastidx();
803 cur.pos() = cur.lastpos();
805 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
810 case LFUN_CELL_FORWARD:
811 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
812 cur.inset().idxNext(cur);
815 case LFUN_CELL_BACKWARD:
816 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
817 cur.inset().idxPrev(cur);
820 case LFUN_WORD_DELETE_BACKWARD:
821 case LFUN_CHAR_DELETE_BACKWARD:
823 // May affect external cell:
824 cur.recordUndoInset();
825 else if (!cur.inMacroMode())
826 cur.recordUndoSelection();
827 // if the inset can not be removed from within, delete it
828 if (!cur.backspace()) {
829 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
830 cur.innerText()->dispatch(cur, cmd);
834 case LFUN_WORD_DELETE_FORWARD:
835 case LFUN_CHAR_DELETE_FORWARD:
836 if (cur.pos() == cur.lastpos())
837 // May affect external cell:
838 cur.recordUndoInset();
840 cur.recordUndoSelection();
841 // if the inset can not be removed from within, delete it
843 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
844 cur.innerText()->dispatch(cur, cmd);
850 cur.clearSelection();
852 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
857 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
858 // that is traversed by a single <CursorLeft>/<CursorRight>.
859 case LFUN_INSET_TOGGLE:
865 case LFUN_SELF_INSERT:
866 if (cmd.argument().size() != 1) {
867 cur.recordUndoSelection();
868 docstring const arg = cmd.argument();
869 if (!interpretString(cur, arg))
873 // Don't record undo steps if we are in macro mode and thus
874 // cmd.argument is the next character of the macro name.
875 // Otherwise we'll get an invalid cursor if we undo after
876 // the macro was finished and the macro is a known command,
877 // e.g. sqrt. Cursor::macroModeClose replaces in this case
878 // the InsetMathUnknown with name "frac" by an empty
879 // InsetMathFrac -> a pos value > 0 is invalid.
880 // A side effect is that an undo before the macro is finished
881 // undoes the complete macro, not only the last character.
882 // At the time we hit '\' we are not in macro mode, still.
883 if (!cur.inMacroMode())
884 cur.recordUndoSelection();
886 // spacial handling of space. If we insert an inset
887 // via macro mode, we want to put the cursor inside it
888 // if relevant. Think typing "\frac<space>".
889 if (cmd.argument()[0] == ' '
890 && cur.inMacroMode() && cur.macroName() != "\\"
891 && cur.macroModeClose() && cur.pos() > 0) {
892 MathAtom const atom = cur.prevAtom();
893 if (atom->asNestInset() && atom->isActive()) {
895 cur.pushBackward(*cur.nextInset());
897 } else if (!interpretChar(cur, cmd.argument()[0])) {
898 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
903 //case LFUN_SERVER_GET_XY:
906 case LFUN_SERVER_SET_XY: {
907 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
910 istringstream is(to_utf8(cmd.argument()));
912 cur.setScreenPos(x, y);
916 // Special casing for superscript in case of LyX handling
918 case LFUN_ACCENT_CIRCUMFLEX:
919 if (cmd.argument().empty()) {
920 // do superscript if LyX handles
922 cur.recordUndoSelection();
923 script(cur, true, grabAndEraseSelection(cur));
927 case LFUN_ACCENT_UMLAUT:
928 case LFUN_ACCENT_ACUTE:
929 case LFUN_ACCENT_GRAVE:
930 case LFUN_ACCENT_BREVE:
931 case LFUN_ACCENT_DOT:
932 case LFUN_ACCENT_MACRON:
933 case LFUN_ACCENT_CARON:
934 case LFUN_ACCENT_TILDE:
935 case LFUN_ACCENT_CEDILLA:
936 case LFUN_ACCENT_CIRCLE:
937 case LFUN_ACCENT_UNDERDOT:
938 case LFUN_ACCENT_TIE:
939 case LFUN_ACCENT_OGONEK:
940 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
944 case LFUN_TEXTSTYLE_APPLY:
945 case LFUN_TEXTSTYLE_UPDATE:
946 handleFont2(cur, cmd.argument());
950 if (currentMode() <= TEXT_MODE)
951 handleFont(cur, cmd.argument(), "textbf");
953 handleFont(cur, cmd.argument(), "mathbf");
955 case LFUN_FONT_BOLDSYMBOL:
956 if (currentMode() <= TEXT_MODE)
957 handleFont(cur, cmd.argument(), "textbf");
959 handleFont(cur, cmd.argument(), "boldsymbol");
962 if (currentMode() <= TEXT_MODE)
963 handleFont(cur, cmd.argument(), "textsf");
965 handleFont(cur, cmd.argument(), "mathsf");
968 if (currentMode() <= TEXT_MODE)
969 handleFont(cur, cmd.argument(), "emph");
971 handleFont(cur, cmd.argument(), "mathcal");
973 case LFUN_FONT_ROMAN:
974 if (currentMode() <= TEXT_MODE)
975 handleFont(cur, cmd.argument(), "textrm");
977 handleFont(cur, cmd.argument(), "mathrm");
979 case LFUN_FONT_TYPEWRITER:
980 if (currentMode() <= TEXT_MODE)
981 handleFont(cur, cmd.argument(), "texttt");
983 handleFont(cur, cmd.argument(), "mathtt");
986 handleFont(cur, cmd.argument(), "mathfrak");
989 if (currentMode() <= TEXT_MODE)
990 handleFont(cur, cmd.argument(), "textit");
992 handleFont(cur, cmd.argument(), "mathit");
995 if (currentMode() <= TEXT_MODE)
996 // FIXME: should be "noun"
997 handleFont(cur, cmd.argument(), "textsc");
999 handleFont(cur, cmd.argument(), "mathbb");
1001 case LFUN_FONT_DEFAULT:
1002 handleFont(cur, cmd.argument(), "textnormal");
1004 case LFUN_FONT_UNDERLINE:
1006 cur.handleNest(createInsetMath("underline", cur.buffer()));
1009 case LFUN_MATH_MODE: {
1011 // ignore math-mode on when already in math mode
1012 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1014 cur.recordUndoSelection();
1015 cur.macroModeClose();
1016 docstring const save_selection = grabAndEraseSelection(cur);
1018 if (currentMode() <= Inset::TEXT_MODE)
1019 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1021 cur.plainInsert(createInsetMath("text", buffer_));
1023 cur.pushBackward(*cur.nextInset());
1024 cur.niceInsert(save_selection);
1025 cur.forceBufferUpdate();
1027 if (currentMode() == Inset::TEXT_MODE) {
1028 cur.recordUndoSelection();
1029 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1030 cur.message(_("create new math text environment ($...$)"));
1032 handleFont(cur, cmd.argument(), "textrm");
1033 cur.message(_("entered math text mode (textrm)"));
1039 case LFUN_REGEXP_MODE: {
1040 InsetMath * im = cur.inset().asInsetMath();
1042 InsetMathHull * i = im->asHullInset();
1043 if (i && i->getType() == hullRegexp) {
1044 cur.message(_("Already in regular expression mode"));
1048 cur.macroModeClose();
1049 docstring const save_selection = grabAndEraseSelection(cur);
1051 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1053 cur.pushBackward(*cur.nextInset());
1054 cur.niceInsert(save_selection);
1055 cur.message(_("Regular expression editor mode"));
1059 case LFUN_MATH_FONT_STYLE: {
1060 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1061 doDispatch(cur, fr);
1065 case LFUN_MATH_SIZE: {
1066 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1067 doDispatch(cur, fr);
1071 case LFUN_MATH_MATRIX: {
1077 idocstringstream is(cmd.argument());
1078 is >> m >> n >> v_align >> h_align;
1084 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1085 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1089 case LFUN_MATH_AMS_MATRIX: {
1093 docstring name = from_ascii("matrix");
1094 idocstringstream is(cmd.argument());
1095 is >> m >> n >> name;
1100 // check if we have a valid decoration
1101 if (name != "pmatrix" && name != "bmatrix"
1102 && name != "Bmatrix" && name != "vmatrix"
1103 && name != "Vmatrix" && name != "matrix")
1104 name = from_ascii("matrix");
1107 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1111 case LFUN_MATH_DELIM: {
1113 docstring rs = split(cmd.argument(), ls, ' ');
1114 // Reasonable default values
1120 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1124 case LFUN_MATH_BIGDELIM: {
1125 docstring const lname = from_utf8(cmd.getArg(0));
1126 docstring const ldelim = from_utf8(cmd.getArg(1));
1127 docstring const rname = from_utf8(cmd.getArg(2));
1128 docstring const rdelim = from_utf8(cmd.getArg(3));
1129 latexkeys const * l = in_word_set(lname);
1130 bool const have_l = l && l->inset == "big" &&
1131 InsetMathBig::isBigInsetDelim(ldelim);
1132 l = in_word_set(rname);
1133 bool const have_r = l && l->inset == "big" &&
1134 InsetMathBig::isBigInsetDelim(rdelim);
1135 // We mimic LFUN_MATH_DELIM in case we have an empty left
1136 // or right delimiter.
1137 if (have_l || have_r) {
1139 docstring const selection = grabAndEraseSelection(cur);
1142 cur.insert(MathAtom(new InsetMathBig(lname,
1144 // first insert the right delimiter and then go back
1145 // and re-insert the selection (bug 7088)
1147 cur.insert(MathAtom(new InsetMathBig(rname,
1151 cur.niceInsert(selection);
1153 // Don't call cur.undispatched() if we did nothing, this would
1154 // lead to infinite recursion via Text::dispatch().
1158 case LFUN_SPACE_INSERT: {
1159 cur.recordUndoSelection();
1160 string const name = cmd.getArg(0);
1161 if (name == "normal")
1162 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1163 else if (name == "protected")
1164 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1165 else if (name == "thin" || name == "med" || name == "thick")
1166 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1167 else if (name == "hfill*")
1168 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1169 else if (name == "quad" || name == "qquad" ||
1170 name == "enspace" || name == "enskip" ||
1171 name == "negthinspace" || name == "negmedspace" ||
1172 name == "negthickspace" || name == "hfill")
1173 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1174 else if (name == "hspace" || name == "hspace*") {
1175 string const len = cmd.getArg(1);
1176 if (len.empty() || !isValidLength(len)) {
1177 lyxerr << "LyX function 'space-insert " << name << "' "
1178 "needs a valid length argument." << endl;
1181 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1183 cur.insert(MathAtom(new InsetMathSpace));
1187 case LFUN_MATH_SPACE:
1188 cur.recordUndoSelection();
1189 if (cmd.argument().empty())
1190 cur.insert(MathAtom(new InsetMathSpace));
1192 string const name = cmd.getArg(0);
1193 string const len = cmd.getArg(1);
1194 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1198 case LFUN_ERT_INSERT:
1199 // interpret this as if a backslash was typed
1201 interpretChar(cur, '\\');
1204 case LFUN_MATH_SUBSCRIPT:
1205 // interpret this as if a _ was typed
1206 cur.recordUndoSelection();
1207 interpretChar(cur, '_');
1210 case LFUN_MATH_SUPERSCRIPT:
1211 // interpret this as if a ^ was typed
1212 cur.recordUndoSelection();
1213 interpretChar(cur, '^');
1216 case LFUN_MATH_MACRO_FOLD:
1217 case LFUN_MATH_MACRO_UNFOLD: {
1219 bool fold = act == LFUN_MATH_MACRO_FOLD;
1220 bool found = findMacroToFoldUnfold(it, fold);
1222 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1223 cur.recordUndoInset();
1232 case LFUN_QUOTE_INSERT:
1233 // interpret this as if a straight " was typed
1234 cur.recordUndoSelection();
1235 interpretChar(cur, '\"');
1238 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1239 // handling such that "self-insert" works on "arbitrary stuff" too, and
1240 // math-insert only handles special math things like "matrix".
1241 case LFUN_MATH_INSERT: {
1242 cur.recordUndoSelection();
1243 if (cmd.argument() == "^" || cmd.argument() == "_")
1244 interpretChar(cur, cmd.argument()[0]);
1247 asArray(cmd.argument(), ar);
1248 if (cur.selection() && ar.size() == 1
1249 && ar[0]->asNestInset()
1250 && ar[0]->asNestInset()->nargs() > 1)
1251 handleNest(cur, ar[0]);
1253 cur.niceInsert(cmd.argument());
1258 case LFUN_UNICODE_INSERT: {
1259 if (cmd.argument().empty())
1261 docstring hexstring = cmd.argument();
1262 if (isHex(hexstring)) {
1263 char_type c = hexToInt(hexstring);
1264 if (c >= 32 && c < 0x10ffff) {
1265 docstring s = docstring(1, c);
1266 FuncCode code = currentMode() == MATH_MODE ?
1267 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1268 lyx::dispatch(FuncRequest(code, s));
1274 case LFUN_DIALOG_SHOW_NEW_INSET: {
1275 docstring const & name = cmd.argument();
1277 if (name == "ref") {
1278 InsetMathRef tmp(buffer_, name);
1279 data = tmp.createDialogStr();
1280 cur.bv().showDialog(to_utf8(name), data);
1281 } else if (name == "mathspace") {
1282 cur.bv().showDialog(to_utf8(name));
1287 case LFUN_INSET_INSERT: {
1289 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1290 cur.recordUndoSelection();
1292 cur.forceBufferUpdate();
1297 case LFUN_INSET_DISSOLVE:
1298 if (!asHullInset()) {
1299 cur.recordUndoInset();
1305 InsetMath::doDispatch(cur, cmd);
1311 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1312 // look for macro to open/close, but stay in mathed
1313 for (; !it.empty(); it.pop_back()) {
1315 // go backward through the current cell
1316 Inset * inset = it.nextInset();
1317 while (inset && inset->asInsetMath()) {
1318 MathMacro * macro = inset->asInsetMath()->asMacro();
1320 // found the an macro to open/close?
1321 if (macro->folded() != fold)
1324 // Wrong folding state.
1325 // If this was the first we see in this slice, look further left,
1327 if (inset != it.nextInset())
1331 // go up if this was the left most position
1337 inset = it.nextInset();
1345 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1346 FuncStatus & flag) const
1348 // the font related toggles
1349 //string tc = "mathnormal";
1351 string const arg = to_utf8(cmd.argument());
1352 switch (cmd.action()) {
1353 case LFUN_INSET_MODIFY:
1354 flag.setEnabled(false);
1357 case LFUN_INSET_MODIFY:
1358 // FIXME: check temporarily disabled
1360 char align = mathcursor::valign();
1361 if (align == '\0') {
1365 if (cmd.argument().empty()) {
1369 if (!contains("tcb", cmd.argument()[0])) {
1373 flag.setOnOff(cmd.argument()[0] == align);
1376 /// We have to handle them since 1.4 blocks all unhandled actions
1377 case LFUN_FONT_ITAL:
1378 case LFUN_FONT_BOLD:
1379 case LFUN_FONT_BOLDSYMBOL:
1380 case LFUN_FONT_SANS:
1381 case LFUN_FONT_EMPH:
1382 case LFUN_FONT_TYPEWRITER:
1383 case LFUN_FONT_NOUN:
1384 case LFUN_FONT_ROMAN:
1385 case LFUN_FONT_DEFAULT:
1386 flag.setEnabled(true);
1389 // we just need to be in math mode to enable that
1390 case LFUN_MATH_SIZE:
1391 case LFUN_MATH_SPACE:
1392 case LFUN_MATH_EXTERN:
1393 flag.setEnabled(true);
1396 case LFUN_FONT_UNDERLINE:
1397 case LFUN_FONT_FRAK:
1398 flag.setEnabled(currentMode() != TEXT_MODE);
1401 case LFUN_MATH_FONT_STYLE: {
1402 bool const textarg =
1403 arg == "textbf" || arg == "textsf" ||
1404 arg == "textrm" || arg == "textmd" ||
1405 arg == "textit" || arg == "textsc" ||
1406 arg == "textsl" || arg == "textup" ||
1407 arg == "texttt" || arg == "textbb" ||
1408 arg == "textnormal";
1409 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1413 case LFUN_MATH_MODE:
1414 // forbid "math-mode on" in math mode to prevent irritating
1415 // behaviour of menu entries (bug 6709)
1416 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1419 case LFUN_MATH_INSERT:
1420 flag.setEnabled(currentMode() != TEXT_MODE);
1423 case LFUN_MATH_AMS_MATRIX:
1424 case LFUN_MATH_MATRIX:
1425 flag.setEnabled(currentMode() == MATH_MODE);
1428 case LFUN_INSET_INSERT: {
1429 // Don't test createMathInset_fromDialogStr(), since
1430 // getStatus is not called with a valid reference and the
1431 // dialog would not be applyable.
1432 string const name = cmd.getArg(0);
1433 flag.setEnabled(name == "ref" || name == "mathspace");
1437 case LFUN_DIALOG_SHOW_NEW_INSET: {
1438 docstring const & name = cmd.argument();
1439 if (name == "space")
1440 flag.setEnabled(false);
1445 case LFUN_MATH_DELIM:
1446 case LFUN_MATH_BIGDELIM:
1447 // Don't do this with multi-cell selections
1448 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1451 case LFUN_MATH_MACRO_FOLD:
1452 case LFUN_MATH_MACRO_UNFOLD: {
1454 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1455 flag.setEnabled(found);
1459 case LFUN_SPECIALCHAR_INSERT:
1460 case LFUN_SCRIPT_INSERT:
1461 // FIXME: These would probably make sense in math-text mode
1462 flag.setEnabled(false);
1465 case LFUN_CAPTION_INSERT:
1466 flag.setEnabled(false);
1469 case LFUN_SPACE_INSERT: {
1470 docstring const & name = cmd.argument();
1471 if (name == "visible")
1472 flag.setEnabled(false);
1476 case LFUN_INSET_DISSOLVE:
1477 flag.setEnabled(!asHullInset());
1481 docstring const & name = cmd.argument();
1482 if (name == "html" || name == "latex")
1483 flag.setEnabled(false);
1495 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1498 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1499 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1500 cur.idx() = enter_front ? 0 : cur.lastidx();
1501 cur.pos() = enter_front ? 0 : cur.lastpos();
1503 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1507 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1510 int dist_min = 1000000;
1511 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1512 int const d = cell(i).dist(cur.bv(), x, y);
1518 MathData & ar = cell(idx_min);
1520 cur.idx() = idx_min;
1521 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1523 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1524 if (dist_min == 0) {
1526 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1527 if (ar[i]->covers(cur.bv(), x, y))
1528 return ar[i].nucleus()->editXY(cur, x, y);
1534 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1536 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1537 BufferView & bv = cur.bv();
1538 if (cmd.button() == mouse_button::button3) {
1539 // Don't do anything if we right-click a
1540 // selection, a context menu will popup.
1541 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1542 && cur < bv.cursor().selectionEnd()) {
1543 cur.noScreenUpdate();
1547 bool do_selection = cmd.button() == mouse_button::button1
1548 && cmd.argument() == "region-select";
1549 bv.mouseSetCursor(cur, do_selection);
1550 if (cmd.button() == mouse_button::button1) {
1551 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1552 // Update the cursor update flags as needed:
1554 // Update::Decoration: tells to update the decoration
1555 // (visual box corners that define
1557 // Update::FitCursor: adjust the screen to the cursor
1558 // position if needed
1559 // cur.result().update(): don't overwrite previously set flags.
1560 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1561 | cur.result().screenUpdate());
1562 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1563 if (cap::selection()) {
1564 // See comment in Text::dispatch why we do this
1565 cap::copySelectionToStack();
1566 cmd = FuncRequest(LFUN_PASTE, "0");
1567 doDispatch(bv.cursor(), cmd);
1570 asArray(theSelection().get(), ar);
1571 bv.cursor().insert(ar);
1577 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1579 // only select with button 1
1580 if (cmd.button() != mouse_button::button1)
1583 Cursor & bvcur = cur.bv().cursor();
1585 // ignore motions deeper nested than the real anchor
1586 if (!bvcur.realAnchor().hasPart(cur)) {
1591 CursorSlice old = bvcur.top();
1593 // We continue with our existing selection or start a new one, so don't
1594 // reset the anchor.
1595 bvcur.setCursor(cur);
1596 // Did we actually move?
1597 if (cur.top() == old)
1598 // We didn't move one iota, so no need to change selection status
1599 // or update the screen.
1600 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1602 bvcur.setSelection();
1606 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1608 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1610 if (cmd.button() == mouse_button::button1) {
1611 if (!cur.selection())
1612 cur.noScreenUpdate();
1614 Cursor & bvcur = cur.bv().cursor();
1615 bvcur.setSelection(true);
1624 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1626 //lyxerr << "interpret 2: '" << c << "'" << endl;
1627 docstring save_selection;
1628 if (c == '^' || c == '_')
1629 save_selection = grabAndEraseSelection(cur);
1632 Buffer * buf = cur.buffer();
1635 if (cur.inMacroMode()) {
1636 docstring name = cur.macroName();
1638 /// are we currently typing '#1' or '#2' or...?
1639 if (name == "\\#") {
1642 if (n >= 1 && n <= 9)
1643 cur.insert(new MathMacroArgument(n));
1647 // do not finish macro for known * commands
1648 bool star_macro = c == '*'
1649 && (in_word_set(name.substr(1) + '*')
1650 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1651 if (isAlphaASCII(c) || star_macro) {
1652 cur.activeMacro()->setName(name + docstring(1, c));
1656 // handle 'special char' macros
1661 if (currentMode() <= InsetMath::TEXT_MODE)
1662 cur.niceInsert(createInsetMath("textbackslash", buf));
1664 cur.niceInsert(createInsetMath("backslash", buf));
1665 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1667 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1668 } else if (c == '{' || c == '%') {
1669 //using the saved selection as argument
1670 InsetMathUnknown * p = cur.activeMacro();
1672 MathData sel(cur.buffer());
1673 asArray(p->selection(), sel);
1676 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1678 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1679 } else if (c == '#') {
1680 LASSERT(cur.activeMacro(), return false);
1681 cur.activeMacro()->setName(name + docstring(1, c));
1684 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1689 // One character big delimiters. The others are handled in
1690 // interpretString().
1691 latexkeys const * l = in_word_set(name.substr(1));
1692 if (name[0] == '\\' && l && l->inset == "big") {
1696 delim = from_ascii("\\{");
1699 delim = from_ascii("\\}");
1702 delim = docstring(1, c);
1705 if (InsetMathBig::isBigInsetDelim(delim)) {
1706 // name + delim ared a valid InsetMathBig.
1707 // We can't use cur.macroModeClose() because
1708 // it does not handle delim.
1709 InsetMathUnknown * p = cur.activeMacro();
1712 cur.cell().erase(cur.pos());
1713 cur.plainInsert(MathAtom(
1714 new InsetMathBig(name.substr(1), delim)));
1717 } else if (name == "\\smash" && c == '[') {
1718 // We can't use cur.macroModeClose() because
1719 // it would create an InsetMathPhantom
1720 InsetMathUnknown * p = cur.activeMacro();
1722 interpretChar(cur, c);
1726 // leave macro mode and try again if necessary
1727 if (cur.macroModeClose()) {
1728 MathAtom const atom = cur.prevAtom();
1729 if (atom->asNestInset() && atom->isActive()) {
1731 cur.pushBackward(*cur.nextInset());
1735 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1737 interpretChar(cur, c);
1742 // leave autocorrect mode if necessary
1743 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1744 cur.autocorrect() = false;
1745 cur.message(_("Autocorrect Off ('!' to enter)"));
1748 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1749 cur.autocorrect() = true;
1750 cur.message(_("Autocorrect On (<space> to exit)"));
1754 // just clear selection on pressing the space bar
1755 if (cur.selection() && c == ' ') {
1756 cur.setSelection(false);
1761 //lyxerr << "starting with macro" << endl;
1762 bool reduced = cap::reduceSelectionToOneCell(cur);
1763 if (reduced || !cur.selection()) {
1764 cur.recordUndoInset();
1765 docstring const safe = cap::grabAndEraseSelection(cur);
1766 if (!cur.inRegexped())
1767 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1769 cur.niceInsert(createInsetMath("backslash", buf));
1777 if (currentMode() <= InsetMath::TEXT_MODE)
1783 if (currentMode() <= InsetMath::TEXT_MODE) {
1784 // insert spaces in text or undecided mode,
1785 // but suppress direct insertion of two spaces in a row
1786 // the still allows typing '<space>a<space>' and deleting the 'a', but
1787 // it is better than nothing...
1788 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1790 // FIXME: we have to enable full redraw here because of the
1791 // visual box corners that define the inset. If we know for
1792 // sure that we stay within the same cell we can optimize for
1794 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1798 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1799 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1800 // FIXME: we have to enable full redraw here because of the
1801 // visual box corners that define the inset. If we know for
1802 // sure that we stay within the same cell we can optimize for
1804 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1808 if (cur.popForward()) {
1809 // FIXME: we have to enable full redraw here because of the
1810 // visual box corners that define the inset. If we know for
1811 // sure that we stay within the same cell we can optimize for
1813 //cur.screenUpdateFlags(Update::FitCursor);
1817 // if we are at the very end, leave the formula
1818 return cur.pos() != cur.lastpos();
1821 // These should be treated differently when not in text mode:
1822 if (cur.inRegexped()) {
1825 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1832 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1835 cur.niceInsert(createInsetMath("sim", buf));
1841 } else if (currentMode() != InsetMath::TEXT_MODE) {
1843 script(cur, false, save_selection);
1847 script(cur, true, save_selection);
1851 cur.niceInsert(createInsetMath("sim", buf));
1854 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1855 MathAtom at = createInsetMath("text", buf);
1856 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1863 cur.niceInsert(createInsetMath("textasciicircum", buf));
1867 cur.niceInsert(createInsetMath("textasciitilde", buf));
1872 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1873 c == '%' || c == '_') {
1874 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1879 // try auto-correction
1880 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1881 && math_autocorrect(cur.prevAtom(), c))
1884 // no special circumstances, so insert the character without any fuss
1886 if (lyxrc.autocorrection_math) {
1887 if (!cur.autocorrect())
1888 cur.message(_("Autocorrect Off ('!' to enter)"));
1890 cur.message(_("Autocorrect On (<space> to exit)"));
1896 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1898 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1900 if (!cur.empty() && cur.pos() > 0 &&
1901 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1902 if (InsetMathBig::isBigInsetDelim(str)) {
1903 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1904 if (prev[0] == '\\') {
1905 prev = prev.substr(1);
1906 latexkeys const * l = in_word_set(prev);
1907 if (l && l->inset == "big") {
1908 cur.cell()[cur.pos() - 1] =
1909 MathAtom(new InsetMathBig(prev, str));
1919 bool InsetMathNest::script(Cursor & cur, bool up)
1921 return script(cur, up, docstring());
1925 bool InsetMathNest::script(Cursor & cur, bool up,
1926 docstring const & save_selection)
1928 // Hack to get \^ and \_ working
1929 //lyxerr << "handling script: up: " << up << endl;
1930 if (cur.inMacroMode() && cur.macroName() == "\\") {
1932 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1934 interpretChar(cur, '_');
1938 cur.macroModeClose();
1939 if (asScriptInset() && cur.idx() == 0) {
1940 // we are in a nucleus of a script inset, move to _our_ script
1941 InsetMathScript * inset = asScriptInset();
1942 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1944 cur.idx() = inset->idxOfScript(up);
1946 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1948 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1951 cur.idx() = inset->idxOfScript(up);
1952 cur.pos() = cur.lastpos();
1954 // convert the thing to our left to a scriptinset or create a new
1955 // one if in the very first position of the array
1956 if (cur.pos() == 0) {
1957 //lyxerr << "new scriptinset" << endl;
1958 cur.insert(new InsetMathScript(buffer_, up));
1960 //lyxerr << "converting prev atom " << endl;
1961 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1964 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1965 // See comment in MathParser.cpp for special handling of {}-bases
1971 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1972 cur.niceInsert(save_selection);
1974 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1979 bool InsetMathNest::completionSupported(Cursor const & cur) const
1981 return cur.inMacroMode();
1985 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1987 return cur.inMacroMode();
1991 bool InsetMathNest::automaticInlineCompletion() const
1993 return lyxrc.completion_inline_math;
1997 bool InsetMathNest::automaticPopupCompletion() const
1999 return lyxrc.completion_popup_math;
2003 CompletionList const *
2004 InsetMathNest::createCompletionList(Cursor const & cur) const
2006 if (!cur.inMacroMode())
2009 return new MathCompletionList(cur);
2013 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2015 if (!cur.inMacroMode())
2018 return cur.activeMacro()->name();
2022 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2025 if (!cur.inMacroMode())
2028 // append completion to active macro
2029 InsetMathUnknown * inset = cur.activeMacro();
2030 inset->setName(inset->name() + s);
2035 // FIXME: this creates duplicates in the completion popup
2036 // which looks ugly. Moreover the changes the list lengths
2038 confuse the popup as well.
2039 MathCompletionList::addToFavorites(inset->name());
2041 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2048 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2049 Dimension & dim) const
2051 Inset const * inset = cur.activeMacro();
2055 // get inset dimensions
2056 dim = cur.bv().coordCache().insets().dim(inset);
2057 // FIXME: these 3 are no accurate, but should depend on the font.
2058 // Now the popup jumps down if you enter a char with descent > 0.
2063 Point xy = cur.bv().coordCache().insets().xy(inset);
2069 bool InsetMathNest::cursorMathForward(Cursor & cur)
2071 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2072 cur.pushBackward(*cur.nextAtom().nucleus());
2073 cur.inset().idxFirst(cur);
2076 if (cur.posForward() || idxForward(cur))
2078 // try to pop forwards --- but don't pop out of math! leave that to
2080 int s = cur.depth() - 2;
2081 if (s >= 0 && cur[s].inset().asInsetMath())
2082 return cur.popForward();
2087 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2089 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2091 cur.push(*cur.nextAtom().nucleus());
2092 cur.inset().idxLast(cur);
2095 if (cur.posBackward() || idxBackward(cur))
2097 // try to pop backwards --- but don't pop out of math! leave that to
2099 int s = cur.depth() - 2;
2100 if (s >= 0 && cur[s].inset().asInsetMath())
2101 return cur.popBackward();
2106 ////////////////////////////////////////////////////////////////////
2108 MathCompletionList::MathCompletionList(Cursor const & cur)
2110 // fill it with macros from the buffer
2111 MacroNameSet macros;
2112 cur.buffer()->listMacroNames(macros);
2113 MacroNameSet::const_iterator it;
2114 for (it = macros.begin(); it != macros.end(); ++it) {
2115 if (cur.buffer()->getMacro(*it, cur, false))
2116 locals.push_back("\\" + *it);
2118 sort(locals.begin(), locals.end());
2120 if (!globals.empty())
2123 // fill in global macros
2125 MacroTable::globalMacros().getMacroNames(macros, false);
2126 //lyxerr << "Globals completion macros: ";
2127 for (it = macros.begin(); it != macros.end(); ++it) {
2128 //lyxerr << "\\" + *it << " ";
2129 globals.push_back("\\" + *it);
2131 //lyxerr << std::endl;
2133 // fill in global commands
2134 globals.push_back(from_ascii("\\boxed"));
2135 globals.push_back(from_ascii("\\fbox"));
2136 globals.push_back(from_ascii("\\framebox"));
2137 globals.push_back(from_ascii("\\makebox"));
2138 globals.push_back(from_ascii("\\kern"));
2139 globals.push_back(from_ascii("\\xhookrightarrow"));
2140 globals.push_back(from_ascii("\\xhookleftarrow"));
2141 globals.push_back(from_ascii("\\xrightarrow"));
2142 globals.push_back(from_ascii("\\xRightarrow"));
2143 globals.push_back(from_ascii("\\xrightharpoondown"));
2144 globals.push_back(from_ascii("\\xrightharpoonup"));
2145 globals.push_back(from_ascii("\\xrightleftharpoons"));
2146 globals.push_back(from_ascii("\\xleftarrow"));
2147 globals.push_back(from_ascii("\\xLeftarrow"));
2148 globals.push_back(from_ascii("\\xleftharpoondown"));
2149 globals.push_back(from_ascii("\\xleftharpoonup"));
2150 globals.push_back(from_ascii("\\xleftrightarrow"));
2151 globals.push_back(from_ascii("\\xLeftrightarrow"));
2152 globals.push_back(from_ascii("\\xleftrightharpoons"));
2153 globals.push_back(from_ascii("\\xmapsto"));
2154 globals.push_back(from_ascii("\\split"));
2155 globals.push_back(from_ascii("\\gathered"));
2156 globals.push_back(from_ascii("\\aligned"));
2157 globals.push_back(from_ascii("\\alignedat"));
2158 globals.push_back(from_ascii("\\cases"));
2159 globals.push_back(from_ascii("\\substack"));
2160 globals.push_back(from_ascii("\\xymatrix"));
2161 globals.push_back(from_ascii("\\Diagram"));
2162 globals.push_back(from_ascii("\\subarray"));
2163 globals.push_back(from_ascii("\\array"));
2164 globals.push_back(from_ascii("\\sqrt"));
2165 globals.push_back(from_ascii("\\root"));
2166 globals.push_back(from_ascii("\\tabular"));
2167 globals.push_back(from_ascii("\\sideset"));
2168 globals.push_back(from_ascii("\\stackrel"));
2169 globals.push_back(from_ascii("\\stackrelthree"));
2170 globals.push_back(from_ascii("\\binom"));
2171 globals.push_back(from_ascii("\\choose"));
2172 globals.push_back(from_ascii("\\brace"));
2173 globals.push_back(from_ascii("\\brack"));
2174 globals.push_back(from_ascii("\\frac"));
2175 globals.push_back(from_ascii("\\over"));
2176 globals.push_back(from_ascii("\\nicefrac"));
2177 globals.push_back(from_ascii("\\unitfrac"));
2178 globals.push_back(from_ascii("\\unitfracthree"));
2179 globals.push_back(from_ascii("\\unitone"));
2180 globals.push_back(from_ascii("\\unittwo"));
2181 globals.push_back(from_ascii("\\infer"));
2182 globals.push_back(from_ascii("\\atop"));
2183 globals.push_back(from_ascii("\\lefteqn"));
2184 globals.push_back(from_ascii("\\boldsymbol"));
2185 globals.push_back(from_ascii("\\bm"));
2186 globals.push_back(from_ascii("\\color"));
2187 globals.push_back(from_ascii("\\normalcolor"));
2188 globals.push_back(from_ascii("\\textcolor"));
2189 globals.push_back(from_ascii("\\cfrac"));
2190 globals.push_back(from_ascii("\\cfracleft"));
2191 globals.push_back(from_ascii("\\cfracright"));
2192 globals.push_back(from_ascii("\\dfrac"));
2193 globals.push_back(from_ascii("\\tfrac"));
2194 globals.push_back(from_ascii("\\dbinom"));
2195 globals.push_back(from_ascii("\\tbinom"));
2196 globals.push_back(from_ascii("\\hphantom"));
2197 globals.push_back(from_ascii("\\phantom"));
2198 globals.push_back(from_ascii("\\vphantom"));
2199 globals.push_back(from_ascii("\\cancel"));
2200 globals.push_back(from_ascii("\\bcancel"));
2201 globals.push_back(from_ascii("\\xcancel"));
2202 globals.push_back(from_ascii("\\cancelto"));
2203 globals.push_back(from_ascii("\\smash"));
2204 globals.push_back(from_ascii("\\mathclap"));
2205 globals.push_back(from_ascii("\\mathllap"));
2206 globals.push_back(from_ascii("\\mathrlap"));
2207 globals.push_back(from_ascii("\\ensuremath"));
2208 MathWordList const & words = mathedWordList();
2209 MathWordList::const_iterator it2;
2210 //lyxerr << "Globals completion commands: ";
2211 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2212 if (it2->second.inset != "macro" && !it2->second.hidden) {
2213 // macros are already read from MacroTable::globalMacros()
2214 globals.push_back('\\' + it2->first);
2215 //lyxerr << '\\' + it2->first << ' ';
2218 //lyxerr << std::endl;
2219 sort(globals.begin(), globals.end());
2223 MathCompletionList::~MathCompletionList()
2228 size_type MathCompletionList::size() const
2230 return locals.size() + globals.size();
2234 docstring const & MathCompletionList::data(size_t idx) const
2236 size_t lsize = locals.size();
2238 return globals[idx - lsize];
2244 std::string MathCompletionList::icon(size_t idx) const
2246 // get the latex command
2248 size_t lsize = locals.size();
2250 cmd = globals[idx - lsize];
2254 // get the icon resource name by stripping the backslash
2255 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2256 if (icon_name.empty())
2257 return std::string();
2258 return "images/math/" + to_utf8(icon_name);
2261 std::vector<docstring> MathCompletionList::globals;