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 "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "InsetMathDelim.h"
22 #include "InsetMathHull.h"
23 #include "InsetMathRef.h"
24 #include "InsetMathScript.h"
25 #include "InsetMathSpace.h"
26 #include "InsetMathSymbol.h"
27 #include "InsetMathUnknown.h"
29 #include "MathFactory.h"
30 #include "MathMacro.h"
31 #include "MathMacroArgument.h"
32 #include "MathParser.h"
33 #include "MathStream.h"
34 #include "MathSupport.h"
37 #include "BufferView.h"
38 #include "CoordCache.h"
40 #include "CutAndPaste.h"
41 #include "DispatchResult.h"
42 #include "FuncRequest.h"
43 #include "FuncStatus.h"
46 #include "OutputParams.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Painter.h"
51 #include "frontends/Selection.h"
53 #include "support/debug.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56 #include "support/textutils.h"
57 #include "support/docstream.h"
62 using namespace lyx::support;
66 using cap::copySelection;
67 using cap::grabAndEraseSelection;
68 using cap::cutSelection;
69 using cap::replaceSelection;
70 using cap::selClearOrDel;
73 InsetMathNest::InsetMathNest(idx_type nargs)
74 : cells_(nargs), lock_(false), mouse_hover_(false)
78 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
79 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
84 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
86 cells_ = inset.cells_;
89 InsetMath::operator=(inset);
94 InsetMath::idx_type InsetMathNest::nargs() const
100 void InsetMathNest::cursorPos(BufferView const & bv,
101 CursorSlice const & sl, bool /*boundary*/,
102 int & x, int & y) const
104 // FIXME: This is a hack. Ideally, the coord cache should not store
105 // absolute positions, but relative ones. This would mean to call
106 // setXY() not in MathData::draw(), but in the parent insets' draw()
107 // with the correctly adjusted x,y values. But this means that we'd have
108 // to touch all (math)inset's draw() methods. Right now, we'll store
109 // absolute value, and make them here relative, only to make them
110 // absolute again when actually drawing the cursor. What a mess.
111 BOOST_ASSERT(&sl.inset() == this);
112 MathData const & ar = sl.cell();
113 CoordCache const & coord_cache = bv.coordCache();
114 if (!coord_cache.getArrays().has(&ar)) {
115 // this can (semi-)legally happen if we just created this cell
116 // and it never has been drawn before. So don't ASSERT.
117 //lyxerr << "no cached data for array " << &ar << endl;
122 Point const pt = coord_cache.getArrays().xy(&ar);
123 if (!coord_cache.getInsets().has(this)) {
125 //lyxerr << "no cached data for inset " << this << endl;
130 Point const pt2 = coord_cache.getInsets().xy(this);
131 //lyxerr << "retrieving position cache for MathData "
132 // << pt.x_ << ' ' << pt.y_ << endl;
133 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
135 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
136 // << " asc: " << ascent() << " des: " << descent()
137 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
138 // move cursor visually into empty cells ("blue rectangles");
144 void InsetMathNest::metrics(MetricsInfo const & mi) const
147 for (idx_type i = 0, n = nargs(); i != n; ++i) {
149 cell(i).metrics(m, dim);
154 bool InsetMathNest::idxNext(Cursor & cur) const
156 BOOST_ASSERT(&cur.inset() == this);
157 if (cur.idx() == cur.lastidx())
165 bool InsetMathNest::idxForward(Cursor & cur) const
171 bool InsetMathNest::idxPrev(Cursor & cur) const
173 BOOST_ASSERT(&cur.inset() == this);
177 cur.pos() = cur.lastpos();
182 bool InsetMathNest::idxBackward(Cursor & cur) const
188 bool InsetMathNest::idxFirst(Cursor & cur) const
190 BOOST_ASSERT(&cur.inset() == this);
199 bool InsetMathNest::idxLast(Cursor & cur) const
201 BOOST_ASSERT(&cur.inset() == this);
204 cur.idx() = cur.lastidx();
205 cur.pos() = cur.lastpos();
210 void InsetMathNest::dump() const
212 odocstringstream oss;
214 os << "---------------------------------------------\n";
217 for (idx_type i = 0, n = nargs(); i != n; ++i)
218 os << cell(i) << "\n";
219 os << "---------------------------------------------\n";
220 lyxerr << to_utf8(oss.str());
224 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
228 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
231 setPosCache(pi, x, y);
235 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
237 BufferView & bv = *pi.base.bv;
238 // this should use the x/y values given, not the cached values
239 Cursor & cur = bv.cursor();
240 if (!cur.selection())
242 if (&cur.inset() != this)
245 // FIXME: hack to get position cache warm
246 bool const original_drawing_state = pi.pain.isDrawingEnabled();
247 pi.pain.setDrawingEnabled(false);
249 pi.pain.setDrawingEnabled(original_drawing_state);
251 CursorSlice s1 = cur.selBegin();
252 CursorSlice s2 = cur.selEnd();
254 //lyxerr << "InsetMathNest::drawing selection: "
255 // << " s1: " << s1 << " s2: " << s2 << endl;
256 if (s1.idx() == s2.idx()) {
257 MathData const & c = cell(s1.idx());
258 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
259 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
260 int y1 = g.pos.y_ - g.dim.ascent();
261 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
262 int y2 = g.pos.y_ + g.dim.descent();
263 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
264 //lyxerr << "InsetMathNest::drawing selection 3: "
265 // << " x1: " << x1 << " x2: " << x2
266 // << " y1: " << y1 << " y2: " << y2 << endl;
268 for (idx_type i = 0; i < nargs(); ++i) {
269 if (idxBetween(i, s1.idx(), s2.idx())) {
270 MathData const & c = cell(i);
271 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
273 int y1 = g.pos.y_ - g.dim.ascent();
274 int x2 = g.pos.x_ + g.dim.width();
275 int y2 = g.pos.y_ + g.dim.descent();
276 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
283 void InsetMathNest::validate(LaTeXFeatures & features) const
285 for (idx_type i = 0; i < nargs(); ++i)
286 cell(i).validate(features);
290 void InsetMathNest::replace(ReplaceData & rep)
292 for (idx_type i = 0; i < nargs(); ++i)
293 cell(i).replace(rep);
297 bool InsetMathNest::contains(MathData const & ar) const
299 for (idx_type i = 0; i < nargs(); ++i)
300 if (cell(i).contains(ar))
306 bool InsetMathNest::lock() const
312 void InsetMathNest::lock(bool l)
318 bool InsetMathNest::isActive() const
324 MathData InsetMathNest::glue() const
327 for (size_t i = 0; i < nargs(); ++i)
333 void InsetMathNest::write(WriteStream & os) const
335 os << '\\' << name().c_str();
336 for (size_t i = 0; i < nargs(); ++i)
337 os << '{' << cell(i) << '}';
339 os.pendingSpace(true);
340 if (lock_ && !os.latex()) {
342 os.pendingSpace(true);
347 void InsetMathNest::normalize(NormalStream & os) const
349 os << '[' << name().c_str();
350 for (size_t i = 0; i < nargs(); ++i)
351 os << ' ' << cell(i);
356 int InsetMathNest::latex(Buffer const &, odocstream & os,
357 OutputParams const & runparams) const
359 WriteStream wi(os, runparams.moving_arg, true);
365 bool InsetMathNest::setMouseHover(bool mouse_hover)
367 mouse_hover_ = mouse_hover;
372 bool InsetMathNest::notifyCursorLeaves(Cursor & /*cur*/)
376 MathData & ar = cur.cell();
377 // remove base-only "scripts"
378 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
379 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
380 if (p && p->nargs() == 1) {
381 MathData ar = p->nuc();
384 cur.adjust(i, ar.size() - 1);
388 // glue adjacent font insets of the same kind
389 for (pos_type i = 0; i + 1 < size(); ++i) {
390 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
391 InsetMathFont const * q = operator[](i + 1)->asFontInset();
392 if (p && q && p->name() == q->name()) {
393 p->cell(0).append(q->cell(0));
403 void InsetMathNest::handleFont
404 (Cursor & cur, docstring const & arg, char const * const font)
406 handleFont(cur, arg, from_ascii(font));
410 void InsetMathNest::handleFont
411 (Cursor & cur, docstring const & arg, docstring const & font)
413 // this whole function is a hack and won't work for incremental font
416 if (cur.inset().asInsetMath()->name() == font) {
417 cur.recordUndoInset();
418 cur.handleFont(to_utf8(font));
421 cur.handleNest(createInsetMath(font));
427 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
432 font.fromString(to_utf8(arg), b);
433 if (font.fontInfo().color() != Color_inherit) {
434 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
435 cur.handleNest(at, 0);
440 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
442 //lyxerr << "InsetMathNest: request: " << cmd << endl;
443 //CursorSlice sl = cur.current();
445 switch (cmd.action) {
449 cur.message(_("Paste"));
450 replaceSelection(cur);
452 if (cmd.argument().empty() && !theClipboard().isInternal())
453 topaste = theClipboard().getAsText();
456 idocstringstream is(cmd.argument());
458 topaste = cap::getSelection(cur.buffer(), n);
460 cur.niceInsert(topaste);
461 cur.clearSelection(); // bug 393
468 cutSelection(cur, true, true);
469 cur.message(_("Cut"));
470 // Prevent stale position >= size crash
471 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
477 cur.message(_("Copy"));
480 case LFUN_MOUSE_PRESS:
481 lfunMousePress(cur, cmd);
484 case LFUN_MOUSE_MOTION:
485 lfunMouseMotion(cur, cmd);
488 case LFUN_MOUSE_RELEASE:
489 lfunMouseRelease(cur, cmd);
492 case LFUN_FINISHED_LEFT: // in math, left is backwards
493 case LFUN_FINISHED_BACKWARD:
494 cur.bv().cursor() = cur;
497 case LFUN_FINISHED_RIGHT: // in math, right is forward
498 case LFUN_FINISHED_FORWARD:
500 cur.bv().cursor() = cur;
503 case LFUN_CHAR_RIGHT:
505 case LFUN_CHAR_BACKWARD:
506 case LFUN_CHAR_FORWARD:
507 cur.updateFlags(Update::Decoration | Update::FitCursor);
508 case LFUN_CHAR_RIGHT_SELECT:
509 case LFUN_CHAR_LEFT_SELECT:
510 case LFUN_CHAR_BACKWARD_SELECT:
511 case LFUN_CHAR_FORWARD_SELECT: {
512 // are we in a selection?
513 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT
514 || cmd.action == LFUN_CHAR_LEFT_SELECT
515 || cmd.action == LFUN_CHAR_BACKWARD_SELECT
516 || cmd.action == LFUN_CHAR_FORWARD_SELECT);
517 // are we moving forward or backwards?
518 // If the command was RIGHT or LEFT, then whether we're moving forward
519 // or backwards depends on the cursor movement mode (logical or visual):
520 // * in visual mode, since math is always LTR, right -> forward,
522 // * in logical mode, the mapping is determined by the
523 // reverseDirectionNeeded() function
526 kb_action finish_lfun;
528 if (cmd.action == LFUN_CHAR_FORWARD
529 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
531 finish_lfun = LFUN_FINISHED_FORWARD;
533 else if (cmd.action == LFUN_CHAR_BACKWARD
534 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
536 finish_lfun = LFUN_FINISHED_BACKWARD;
539 bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
540 || cmd.action == LFUN_CHAR_RIGHT);
541 if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
547 finish_lfun = LFUN_FINISHED_RIGHT;
549 finish_lfun = LFUN_FINISHED_LEFT;
551 // Now that we know exactly what we want to do, let's do it!
552 cur.selHandle(select);
553 cur.autocorrect() = false;
555 cur.macroModeClose();
556 // try moving forward or backwards as necessary...
557 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
558 // ... and if movement failed, then finish forward or backwards
560 cmd = FuncRequest(finish_lfun);
568 cur.updateFlags(Update::Decoration | Update::FitCursor);
569 case LFUN_DOWN_SELECT:
570 case LFUN_UP_SELECT: {
571 // close active macro
572 if (cur.inMacroMode()) {
573 cur.macroModeClose();
577 // stop/start the selection
578 bool select = cmd.action == LFUN_DOWN_SELECT ||
579 cmd.action == LFUN_UP_SELECT;
580 cur.selHandle(select);
583 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
584 bool successful = cur.upDownInMath(up);
586 // notify left insets and give them chance to set update flags
587 lyx::notifyCursorLeaves(cur.beforeDispatchCursor(), cur);
592 if (cur.fixIfBroken())
593 // FIXME: Something bad happened. We pass the corrected Cursor
594 // instead of letting things go worse.
597 // We did not manage to move the cursor.
602 case LFUN_MOUSE_DOUBLE:
603 case LFUN_MOUSE_TRIPLE:
604 case LFUN_WORD_SELECT:
608 cur.selection() = true;
609 cur.pos() = cur.lastpos();
610 cur.idx() = cur.lastidx();
613 case LFUN_PARAGRAPH_UP:
614 case LFUN_PARAGRAPH_DOWN:
615 cur.updateFlags(Update::Decoration | Update::FitCursor);
616 case LFUN_PARAGRAPH_UP_SELECT:
617 case LFUN_PARAGRAPH_DOWN_SELECT:
620 case LFUN_LINE_BEGIN:
621 case LFUN_WORD_BACKWARD:
623 cur.updateFlags(Update::Decoration | Update::FitCursor);
624 case LFUN_LINE_BEGIN_SELECT:
625 case LFUN_WORD_BACKWARD_SELECT:
626 case LFUN_WORD_LEFT_SELECT:
627 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
628 cmd.action == LFUN_WORD_LEFT_SELECT ||
629 cmd.action == LFUN_LINE_BEGIN_SELECT);
630 cur.macroModeClose();
631 if (cur.pos() != 0) {
633 } else if (cur.col() != 0) {
634 cur.idx() -= cur.col();
636 } else if (cur.idx() != 0) {
640 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
645 case LFUN_WORD_FORWARD:
646 case LFUN_WORD_RIGHT:
648 cur.updateFlags(Update::Decoration | Update::FitCursor);
649 case LFUN_WORD_FORWARD_SELECT:
650 case LFUN_WORD_RIGHT_SELECT:
651 case LFUN_LINE_END_SELECT:
652 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
653 cmd.action == LFUN_WORD_RIGHT_SELECT ||
654 cmd.action == LFUN_LINE_END_SELECT);
655 cur.macroModeClose();
657 if (cur.pos() != cur.lastpos()) {
658 cur.pos() = cur.lastpos();
659 } else if (ncols() && (cur.col() != cur.lastcol())) {
660 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
661 cur.pos() = cur.lastpos();
662 } else if (cur.idx() != cur.lastidx()) {
663 cur.idx() = cur.lastidx();
664 cur.pos() = cur.lastpos();
666 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
671 case LFUN_SCREEN_UP_SELECT:
672 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
676 case LFUN_SCREEN_DOWN_SELECT:
677 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
681 case LFUN_CELL_FORWARD:
682 cur.updateFlags(Update::Decoration | Update::FitCursor);
683 cur.inset().idxNext(cur);
686 case LFUN_CELL_BACKWARD:
687 cur.updateFlags(Update::Decoration | Update::FitCursor);
688 cur.inset().idxPrev(cur);
691 case LFUN_WORD_DELETE_BACKWARD:
692 case LFUN_CHAR_DELETE_BACKWARD:
694 // May affect external cell:
695 cur.recordUndoInset();
698 // if the inset can not be removed from within, delete it
699 if (!cur.backspace()) {
700 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
701 cur.innerText()->dispatch(cur, cmd);
705 case LFUN_WORD_DELETE_FORWARD:
706 case LFUN_CHAR_DELETE_FORWARD:
707 if (cur.pos() == cur.lastpos())
708 // May affect external cell:
709 cur.recordUndoInset();
712 // if the inset can not be removed from within, delete it
714 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
715 cur.innerText()->dispatch(cur, cmd);
721 cur.clearSelection();
723 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
728 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
729 // that is traversed by a single <CursorLeft>/<CursorRight>.
730 case LFUN_INSET_TOGGLE:
736 case LFUN_SELF_INSERT:
737 if (cmd.argument().size() != 1) {
739 docstring const arg = cmd.argument();
740 if (!interpretString(cur, arg))
744 // Don't record undo steps if we are in macro mode and
745 // cmd.argument is the next character of the macro name.
746 // Otherwise we'll get an invalid cursor if we undo after
747 // the macro was finished and the macro is a known command,
748 // e.g. sqrt. Cursor::macroModeClose replaces in this case
749 // the InsetMathUnknown with name "frac" by an empty
750 // InsetMathFrac -> a pos value > 0 is invalid.
751 // A side effect is that an undo before the macro is finished
752 // undoes the complete macro, not only the last character.
753 if (!cur.inMacroMode())
756 // spacial handling of space. If we insert an inset
757 // via macro mode, we want to put the cursor inside it
758 // if relevant. Think typing "\frac<space>".
759 if (cmd.argument()[0] == ' '
760 && cur.inMacroMode() && cur.macroName() != "\\"
761 && cur.macroModeClose()) {
762 MathAtom const atom = cur.prevAtom();
763 if (atom->asNestInset() && atom->isActive()) {
765 cur.pushBackward(*cur.nextInset());
767 } else if (!interpretChar(cur, cmd.argument()[0])) {
768 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
773 //case LFUN_SERVER_GET_XY:
774 // sprintf(dispatch_buffer, "%d %d",);
777 case LFUN_SERVER_SET_XY: {
778 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
781 istringstream is(to_utf8(cmd.argument()));
783 cur.setScreenPos(x, y);
787 // Special casing for superscript in case of LyX handling
789 case LFUN_ACCENT_CIRCUMFLEX:
790 if (cmd.argument().empty()) {
791 // do superscript if LyX handles
794 script(cur, true, grabAndEraseSelection(cur));
798 case LFUN_ACCENT_UMLAUT:
799 case LFUN_ACCENT_ACUTE:
800 case LFUN_ACCENT_GRAVE:
801 case LFUN_ACCENT_BREVE:
802 case LFUN_ACCENT_DOT:
803 case LFUN_ACCENT_MACRON:
804 case LFUN_ACCENT_CARON:
805 case LFUN_ACCENT_TILDE:
806 case LFUN_ACCENT_CEDILLA:
807 case LFUN_ACCENT_CIRCLE:
808 case LFUN_ACCENT_UNDERDOT:
809 case LFUN_ACCENT_TIE:
810 case LFUN_ACCENT_OGONEK:
811 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
815 case LFUN_FONT_FREE_APPLY:
816 case LFUN_FONT_FREE_UPDATE:
817 handleFont2(cur, cmd.argument());
821 if (currentMode() == TEXT_MODE)
822 handleFont(cur, cmd.argument(), "textbf");
824 handleFont(cur, cmd.argument(), "mathbf");
827 if (currentMode() == TEXT_MODE)
828 handleFont(cur, cmd.argument(), "textsf");
830 handleFont(cur, cmd.argument(), "mathsf");
833 if (currentMode() == TEXT_MODE)
834 handleFont(cur, cmd.argument(), "emph");
836 handleFont(cur, cmd.argument(), "mathcal");
838 case LFUN_FONT_ROMAN:
839 if (currentMode() == TEXT_MODE)
840 handleFont(cur, cmd.argument(), "textrm");
842 handleFont(cur, cmd.argument(), "mathrm");
844 case LFUN_FONT_TYPEWRITER:
845 if (currentMode() == TEXT_MODE)
846 handleFont(cur, cmd.argument(), "texttt");
848 handleFont(cur, cmd.argument(), "mathtt");
851 handleFont(cur, cmd.argument(), "mathfrak");
854 if (currentMode() == TEXT_MODE)
855 handleFont(cur, cmd.argument(), "textit");
857 handleFont(cur, cmd.argument(), "mathit");
860 if (currentMode() == TEXT_MODE)
861 // FIXME: should be "noun"
862 handleFont(cur, cmd.argument(), "textsc");
864 handleFont(cur, cmd.argument(), "mathbb");
867 case LFUN_FONT_FREE_APPLY:
868 handleFont(cur, cmd.argument(), "textrm");
871 case LFUN_FONT_DEFAULT:
872 handleFont(cur, cmd.argument(), "textnormal");
875 case LFUN_MATH_MODE: {
877 // ignore math-mode on when already in math mode
878 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
880 cur.macroModeClose();
881 docstring const save_selection = grabAndEraseSelection(cur);
883 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
884 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
886 cur.pushBackward(*cur.nextInset());
887 cur.niceInsert(save_selection);
889 if (currentMode() == Inset::TEXT_MODE) {
890 cur.niceInsert(MathAtom(new InsetMathHull("simple")));
891 cur.message(_("create new math text environment ($...$)"));
893 handleFont(cur, cmd.argument(), "textrm");
894 cur.message(_("entered math text mode (textrm)"));
907 case LFUN_MATH_MATRIX: {
913 idocstringstream is(cmd.argument());
914 is >> m >> n >> v_align >> h_align;
921 MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
925 case LFUN_MATH_DELIM: {
927 docstring rs = split(cmd.argument(), ls, ' ');
928 // Reasonable default values
934 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
938 case LFUN_MATH_BIGDELIM: {
939 docstring const lname = from_utf8(cmd.getArg(0));
940 docstring const ldelim = from_utf8(cmd.getArg(1));
941 docstring const rname = from_utf8(cmd.getArg(2));
942 docstring const rdelim = from_utf8(cmd.getArg(3));
943 latexkeys const * l = in_word_set(lname);
944 bool const have_l = l && l->inset == "big" &&
945 InsetMathBig::isBigInsetDelim(ldelim);
946 l = in_word_set(rname);
947 bool const have_r = l && l->inset == "big" &&
948 InsetMathBig::isBigInsetDelim(rdelim);
949 // We mimic LFUN_MATH_DELIM in case we have an empty left
950 // or right delimiter.
951 if (have_l || have_r) {
953 docstring const selection = grabAndEraseSelection(cur);
956 cur.insert(MathAtom(new InsetMathBig(lname,
958 cur.niceInsert(selection);
960 cur.insert(MathAtom(new InsetMathBig(rname,
963 // Don't call cur.undispatched() if we did nothing, this would
964 // lead to infinite recursion via Text::dispatch().
968 case LFUN_SPACE_INSERT:
969 case LFUN_MATH_SPACE:
971 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
974 case LFUN_ERT_INSERT:
975 // interpret this as if a backslash was typed
977 interpretChar(cur, '\\');
980 case LFUN_MATH_SUBSCRIPT:
981 // interpret this as if a _ was typed
983 interpretChar(cur, '_');
986 case LFUN_MATH_SUPERSCRIPT:
987 // interpret this as if a ^ was typed
989 interpretChar(cur, '^');
992 case LFUN_MATH_MACRO_FOLD:
993 case LFUN_MATH_MACRO_UNFOLD: {
995 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
996 bool found = findMacroToFoldUnfold(it, fold);
998 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
999 cur.recordUndoInset();
1008 case LFUN_QUOTE_INSERT:
1009 // interpret this as if a straight " was typed
1011 interpretChar(cur, '\"');
1014 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1015 // handling such that "self-insert" works on "arbitrary stuff" too, and
1016 // math-insert only handles special math things like "matrix".
1017 case LFUN_MATH_INSERT: {
1019 if (cmd.argument() == "^" || cmd.argument() == "_") {
1020 interpretChar(cur, cmd.argument()[0]);
1022 cur.niceInsert(cmd.argument());
1026 case LFUN_DIALOG_SHOW_NEW_INSET: {
1027 docstring const & name = cmd.argument();
1029 if (name == "ref") {
1030 InsetMathRef tmp(name);
1031 data = tmp.createDialogStr(to_utf8(name));
1033 cur.bv().showDialog(to_utf8(name), data);
1037 case LFUN_INSET_INSERT: {
1039 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1046 case LFUN_INSET_DISSOLVE:
1047 if (!asHullInset()) {
1048 cur.recordUndoInset();
1054 InsetMath::doDispatch(cur, cmd);
1060 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1061 // look for macro to open/close, but stay in mathed
1062 for (; !it.empty(); it.pop_back()) {
1064 // go backward through the current cell
1065 Inset * inset = it.nextInset();
1066 while (inset && inset->asInsetMath()) {
1067 MathMacro * macro = inset->asInsetMath()->asMacro();
1069 // found the an macro to open/close?
1070 if (macro->folded() != fold)
1073 // Wrong folding state.
1074 // If this was the first we see in this slice, look further left,
1076 if (inset != it.nextInset())
1080 // go up if this was the left most position
1086 inset = it.nextInset();
1094 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1095 FuncStatus & flag) const
1097 // the font related toggles
1098 //string tc = "mathnormal";
1100 string const arg = to_utf8(cmd.argument());
1101 switch (cmd.action) {
1102 case LFUN_TABULAR_FEATURE:
1103 flag.enabled(false);
1106 case LFUN_TABULAR_FEATURE:
1107 // FIXME: check temporarily disabled
1109 char align = mathcursor::valign();
1110 if (align == '\0') {
1114 if (cmd.argument().empty()) {
1118 if (!contains("tcb", cmd.argument()[0])) {
1122 flag.setOnOff(cmd.argument()[0] == align);
1125 /// We have to handle them since 1.4 blocks all unhandled actions
1126 case LFUN_FONT_ITAL:
1127 case LFUN_FONT_BOLD:
1128 case LFUN_FONT_SANS:
1129 case LFUN_FONT_EMPH:
1130 case LFUN_FONT_TYPEWRITER:
1131 case LFUN_FONT_NOUN:
1132 case LFUN_FONT_ROMAN:
1133 case LFUN_FONT_DEFAULT:
1136 case LFUN_MATH_MUTATE:
1137 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1138 flag.setOnOff(false);
1141 // we just need to be in math mode to enable that
1142 case LFUN_MATH_SIZE:
1143 case LFUN_MATH_SPACE:
1144 case LFUN_MATH_LIMITS:
1145 case LFUN_MATH_EXTERN:
1149 case LFUN_FONT_FRAK:
1150 flag.enabled(currentMode() != TEXT_MODE);
1153 case LFUN_MATH_INSERT: {
1154 bool const textarg =
1155 arg == "\\textbf" || arg == "\\textsf" ||
1156 arg == "\\textrm" || arg == "\\textmd" ||
1157 arg == "\\textit" || arg == "\\textsc" ||
1158 arg == "\\textsl" || arg == "\\textup" ||
1159 arg == "\\texttt" || arg == "\\textbb" ||
1160 arg == "\\textnormal";
1161 flag.enabled(currentMode() != TEXT_MODE || textarg);
1165 case LFUN_MATH_MATRIX:
1166 flag.enabled(currentMode() == MATH_MODE);
1169 case LFUN_INSET_INSERT: {
1170 // Don't test createMathInset_fromDialogStr(), since
1171 // getStatus is not called with a valid reference and the
1172 // dialog would not be applyable.
1173 string const name = cmd.getArg(0);
1174 flag.enabled(name == "ref");
1178 case LFUN_MATH_DELIM:
1179 case LFUN_MATH_BIGDELIM:
1180 // Don't do this with multi-cell selections
1181 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1184 case LFUN_MATH_MACRO_FOLD:
1185 case LFUN_MATH_MACRO_UNFOLD: {
1187 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1188 flag.enabled(found);
1192 case LFUN_SPECIALCHAR_INSERT:
1193 // FIXME: These would probably make sense in math-text mode
1194 flag.enabled(false);
1197 case LFUN_INSET_DISSOLVE:
1198 flag.enabled(!asHullInset());
1209 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1212 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1213 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1214 cur.idx() = enter_front ? 0 : cur.lastidx();
1215 cur.pos() = enter_front ? 0 : cur.lastpos();
1217 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1221 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1224 int dist_min = 1000000;
1225 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1226 int const d = cell(i).dist(cur.bv(), x, y);
1232 MathData & ar = cell(idx_min);
1234 cur.idx() = idx_min;
1235 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1237 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1238 if (dist_min == 0) {
1240 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1241 if (ar[i]->covers(cur.bv(), x, y))
1242 return ar[i].nucleus()->editXY(cur, x, y);
1248 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1250 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1251 BufferView & bv = cur.bv();
1252 bool do_selection = cmd.button() == mouse_button::button1
1253 && cmd.argument() == "region-select";
1254 bv.mouseSetCursor(cur, do_selection);
1255 if (cmd.button() == mouse_button::button1) {
1256 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1257 // Update the cursor update flags as needed:
1259 // Update::Decoration: tells to update the decoration
1260 // (visual box corners that define
1262 // Update::FitCursor: adjust the screen to the cursor
1263 // position if needed
1264 // cur.result().update(): don't overwrite previously set flags.
1265 cur.updateFlags(Update::Decoration | Update::FitCursor
1266 | cur.result().update());
1267 } else if (cmd.button() == mouse_button::button2) {
1268 if (cap::selection()) {
1269 // See comment in Text::dispatch why we do this
1270 cap::copySelectionToStack();
1271 cmd = FuncRequest(LFUN_PASTE, "0");
1272 doDispatch(bv.cursor(), cmd);
1275 asArray(theSelection().get(), ar);
1276 bv.cursor().insert(ar);
1282 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1284 // only select with button 1
1285 if (cmd.button() == mouse_button::button1) {
1286 Cursor & bvcur = cur.bv().cursor();
1287 if (bvcur.anchor_.hasPart(cur)) {
1288 //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1289 bvcur.setCursor(cur);
1290 bvcur.selection() = true;
1291 //lyxerr << "MOTION " << bvcur << endl;
1298 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1300 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1302 if (cmd.button() == mouse_button::button1) {
1303 if (!cur.selection())
1306 Cursor & bvcur = cur.bv().cursor();
1307 bvcur.selection() = true;
1316 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1318 //lyxerr << "interpret 2: '" << c << "'" << endl;
1319 docstring save_selection;
1320 if (c == '^' || c == '_')
1321 save_selection = grabAndEraseSelection(cur);
1326 if (cur.inMacroMode()) {
1327 docstring name = cur.macroName();
1329 /// are we currently typing '#1' or '#2' or...?
1330 if (name == "\\#") {
1333 if (n >= 1 && n <= 9)
1334 cur.insert(new MathMacroArgument(n));
1338 if (isAlphaASCII(c)) {
1339 cur.activeMacro()->setName(name + docstring(1, c));
1343 // handle 'special char' macros
1348 if (currentMode() == InsetMath::TEXT_MODE)
1349 cur.niceInsert(createInsetMath("textbackslash"));
1351 cur.niceInsert(createInsetMath("backslash"));
1352 } else if (c == '{') {
1354 cur.niceInsert(MathAtom(new InsetMathBrace));
1355 } else if (c == '%') {
1357 cur.niceInsert(MathAtom(new InsetMathComment));
1358 } else if (c == '#') {
1359 BOOST_ASSERT(cur.activeMacro());
1360 cur.activeMacro()->setName(name + docstring(1, c));
1363 cur.niceInsert(createInsetMath(docstring(1, c)));
1368 // One character big delimiters. The others are handled in
1369 // interpretString().
1370 latexkeys const * l = in_word_set(name.substr(1));
1371 if (name[0] == '\\' && l && l->inset == "big") {
1375 delim = from_ascii("\\{");
1378 delim = from_ascii("\\}");
1381 delim = docstring(1, c);
1384 if (InsetMathBig::isBigInsetDelim(delim)) {
1385 // name + delim ared a valid InsetMathBig.
1386 // We can't use cur.macroModeClose() because
1387 // it does not handle delim.
1388 InsetMathUnknown * p = cur.activeMacro();
1391 cur.cell().erase(cur.pos());
1392 cur.plainInsert(MathAtom(
1393 new InsetMathBig(name.substr(1), delim)));
1398 // leave macro mode and try again if necessary
1399 cur.macroModeClose();
1401 cur.niceInsert(MathAtom(new InsetMathBrace));
1403 interpretChar(cur, c);
1407 // This is annoying as one has to press <space> far too often.
1411 // leave autocorrect mode if necessary
1412 if (autocorrect() && c == ' ') {
1413 autocorrect() = false;
1418 // just clear selection on pressing the space bar
1419 if (cur.selection() && c == ' ') {
1420 cur.selection() = false;
1427 //lyxerr << "starting with macro" << endl;
1428 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1433 if (currentMode() == InsetMath::TEXT_MODE)
1439 if (currentMode() == InsetMath::TEXT_MODE) {
1440 // insert spaces in text mode,
1441 // but suppress direct insertion of two spaces in a row
1442 // the still allows typing '<space>a<space>' and deleting the 'a', but
1443 // it is better than nothing...
1444 if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1446 // FIXME: we have to enable full redraw here because of the
1447 // visual box corners that define the inset. If we know for
1448 // sure that we stay within the same cell we can optimize for
1450 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1454 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1455 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1456 // FIXME: we have to enable full redraw here because of the
1457 // visual box corners that define the inset. If we know for
1458 // sure that we stay within the same cell we can optimize for
1460 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1464 if (cur.popForward()) {
1465 // FIXME: we have to enable full redraw here because of the
1466 // visual box corners that define the inset. If we know for
1467 // sure that we stay within the same cell we can optimize for
1469 //cur.updateFlags(Update::FitCursor);
1473 // if we are at the very end, leave the formula
1474 return cur.pos() != cur.lastpos();
1477 // These shouldn't work in text mode:
1478 if (currentMode() != InsetMath::TEXT_MODE) {
1480 script(cur, false, save_selection);
1484 script(cur, true, save_selection);
1488 cur.niceInsert(createInsetMath("sim"));
1493 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1494 c == '%' || c == '_' || c == '^') {
1495 cur.niceInsert(createInsetMath(docstring(1, c)));
1500 // try auto-correction
1501 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1504 // no special circumstances, so insert the character without any fuss
1506 cur.autocorrect() = true;
1511 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1513 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1515 if (!cur.empty() && cur.pos() > 0 &&
1516 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1517 if (InsetMathBig::isBigInsetDelim(str)) {
1518 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1519 if (prev[0] == '\\') {
1520 prev = prev.substr(1);
1521 latexkeys const * l = in_word_set(prev);
1522 if (l && l->inset == "big") {
1523 cur.cell()[cur.pos() - 1] =
1524 MathAtom(new InsetMathBig(prev, str));
1534 bool InsetMathNest::script(Cursor & cur, bool up,
1535 docstring const & save_selection)
1537 // Hack to get \^ and \_ working
1538 //lyxerr << "handling script: up: " << up << endl;
1539 if (cur.inMacroMode() && cur.macroName() == "\\") {
1541 cur.niceInsert(createInsetMath("mathcircumflex"));
1543 interpretChar(cur, '_');
1547 cur.macroModeClose();
1548 if (asScriptInset() && cur.idx() == 0) {
1549 // we are in a nucleus of a script inset, move to _our_ script
1550 InsetMathScript * inset = asScriptInset();
1551 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1553 cur.idx() = inset->idxOfScript(up);
1555 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1557 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1560 cur.idx() = inset->idxOfScript(up);
1561 cur.pos() = cur.lastpos();
1563 // convert the thing to our left to a scriptinset or create a new
1564 // one if in the very first position of the array
1565 if (cur.pos() == 0) {
1566 //lyxerr << "new scriptinset" << endl;
1567 cur.insert(new InsetMathScript(up));
1569 //lyxerr << "converting prev atom " << endl;
1570 cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1573 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1574 // See comment in MathParser.cpp for special handling of {}-bases
1580 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1581 cur.niceInsert(save_selection);
1583 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1588 bool InsetMathNest::cursorMathForward(Cursor & cur)
1590 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1591 cur.pushBackward(*cur.nextAtom().nucleus());
1592 cur.inset().idxFirst(cur);
1595 if (cur.posForward() || idxForward(cur) || cur.selection())
1597 // try to pop forwards --- but don't pop out of math! leave that to
1599 int s = cur.depth() - 2;
1600 if (s >= 0 && cur[s].inset().asInsetMath())
1601 return cur.popForward();
1606 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1608 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1610 cur.push(*cur.nextAtom().nucleus());
1611 cur.inset().idxLast(cur);
1614 if (cur.posBackward() || idxBackward(cur) || cur.selection())
1616 // try to pop backwards --- but don't pop out of math! leave that to
1618 int s = cur.depth() - 2;
1619 if (s >= 0 && cur[s].inset().asInsetMath())
1620 return cur.popBackward();