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 "support/debug.h"
42 #include "DispatchResult.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.h"
46 #include "support/gettext.h"
48 #include "OutputParams.h"
50 #include "support/lstrings.h"
51 #include "support/textutils.h"
52 #include "support/docstream.h"
54 #include "frontends/Clipboard.h"
55 #include "frontends/Painter.h"
56 #include "frontends/Selection.h"
58 #include "FuncRequest.h"
63 using namespace lyx::support;
67 using cap::copySelection;
68 using cap::grabAndEraseSelection;
69 using cap::cutSelection;
70 using cap::replaceSelection;
71 using cap::selClearOrDel;
74 InsetMathNest::InsetMathNest(idx_type nargs)
75 : cells_(nargs), lock_(false), mouse_hover_(false)
79 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
80 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
85 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
87 cells_ = inset.cells_;
90 InsetMath::operator=(inset);
95 InsetMath::idx_type InsetMathNest::nargs() const
101 void InsetMathNest::cursorPos(BufferView const & bv,
102 CursorSlice const & sl, bool /*boundary*/,
103 int & x, int & y) const
105 // FIXME: This is a hack. Ideally, the coord cache should not store
106 // absolute positions, but relative ones. This would mean to call
107 // setXY() not in MathData::draw(), but in the parent insets' draw()
108 // with the correctly adjusted x,y values. But this means that we'd have
109 // to touch all (math)inset's draw() methods. Right now, we'll store
110 // absolute value, and make them here relative, only to make them
111 // absolute again when actually drawing the cursor. What a mess.
112 BOOST_ASSERT(&sl.inset() == this);
113 MathData const & ar = sl.cell();
114 CoordCache const & coord_cache = bv.coordCache();
115 if (!coord_cache.getArrays().has(&ar)) {
116 // this can (semi-)legally happen if we just created this cell
117 // and it never has been drawn before. So don't ASSERT.
118 //lyxerr << "no cached data for array " << &ar << endl;
123 Point const pt = coord_cache.getArrays().xy(&ar);
124 if (!coord_cache.getInsets().has(this)) {
126 //lyxerr << "no cached data for inset " << this << endl;
131 Point const pt2 = coord_cache.getInsets().xy(this);
132 //lyxerr << "retrieving position cache for MathData "
133 // << pt.x_ << ' ' << pt.y_ << endl;
134 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
136 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
137 // << " asc: " << ascent() << " des: " << descent()
138 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
139 // move cursor visually into empty cells ("blue rectangles");
145 void InsetMathNest::metrics(MetricsInfo const & mi) const
148 for (idx_type i = 0, n = nargs(); i != n; ++i) {
150 cell(i).metrics(m, dim);
155 bool InsetMathNest::idxNext(Cursor & cur) const
157 BOOST_ASSERT(&cur.inset() == this);
158 if (cur.idx() == cur.lastidx())
166 bool InsetMathNest::idxForward(Cursor & cur) const
172 bool InsetMathNest::idxPrev(Cursor & cur) const
174 BOOST_ASSERT(&cur.inset() == this);
178 cur.pos() = cur.lastpos();
183 bool InsetMathNest::idxBackward(Cursor & cur) const
189 bool InsetMathNest::idxFirst(Cursor & cur) const
191 BOOST_ASSERT(&cur.inset() == this);
200 bool InsetMathNest::idxLast(Cursor & cur) const
202 BOOST_ASSERT(&cur.inset() == this);
205 cur.idx() = cur.lastidx();
206 cur.pos() = cur.lastpos();
211 void InsetMathNest::dump() const
213 odocstringstream oss;
215 os << "---------------------------------------------\n";
218 for (idx_type i = 0, n = nargs(); i != n; ++i)
219 os << cell(i) << "\n";
220 os << "---------------------------------------------\n";
221 lyxerr << to_utf8(oss.str());
225 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
229 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
232 setPosCache(pi, x, y);
236 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
238 BufferView & bv = *pi.base.bv;
239 // this should use the x/y values given, not the cached values
240 Cursor & cur = bv.cursor();
241 if (!cur.selection())
243 if (&cur.inset() != this)
246 // FIXME: hack to get position cache warm
247 bool const original_drawing_state = pi.pain.isDrawingEnabled();
248 pi.pain.setDrawingEnabled(false);
250 pi.pain.setDrawingEnabled(original_drawing_state);
252 CursorSlice s1 = cur.selBegin();
253 CursorSlice s2 = cur.selEnd();
255 //lyxerr << "InsetMathNest::drawing selection: "
256 // << " s1: " << s1 << " s2: " << s2 << endl;
257 if (s1.idx() == s2.idx()) {
258 MathData const & c = cell(s1.idx());
259 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
260 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
261 int y1 = g.pos.y_ - g.dim.ascent();
262 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
263 int y2 = g.pos.y_ + g.dim.descent();
264 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
265 //lyxerr << "InsetMathNest::drawing selection 3: "
266 // << " x1: " << x1 << " x2: " << x2
267 // << " y1: " << y1 << " y2: " << y2 << endl;
269 for (idx_type i = 0; i < nargs(); ++i) {
270 if (idxBetween(i, s1.idx(), s2.idx())) {
271 MathData const & c = cell(i);
272 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
274 int y1 = g.pos.y_ - g.dim.ascent();
275 int x2 = g.pos.x_ + g.dim.width();
276 int y2 = g.pos.y_ + g.dim.descent();
277 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
284 void InsetMathNest::validate(LaTeXFeatures & features) const
286 for (idx_type i = 0; i < nargs(); ++i)
287 cell(i).validate(features);
291 void InsetMathNest::replace(ReplaceData & rep)
293 for (idx_type i = 0; i < nargs(); ++i)
294 cell(i).replace(rep);
298 bool InsetMathNest::contains(MathData const & ar) const
300 for (idx_type i = 0; i < nargs(); ++i)
301 if (cell(i).contains(ar))
307 bool InsetMathNest::lock() const
313 void InsetMathNest::lock(bool l)
319 bool InsetMathNest::isActive() const
325 MathData InsetMathNest::glue() const
328 for (size_t i = 0; i < nargs(); ++i)
334 void InsetMathNest::write(WriteStream & os) const
336 os << '\\' << name().c_str();
337 for (size_t i = 0; i < nargs(); ++i)
338 os << '{' << cell(i) << '}';
340 os.pendingSpace(true);
341 if (lock_ && !os.latex()) {
343 os.pendingSpace(true);
348 void InsetMathNest::normalize(NormalStream & os) const
350 os << '[' << name().c_str();
351 for (size_t i = 0; i < nargs(); ++i)
352 os << ' ' << cell(i);
357 int InsetMathNest::latex(Buffer const &, odocstream & os,
358 OutputParams const & runparams) const
360 WriteStream wi(os, runparams.moving_arg, true);
366 bool InsetMathNest::setMouseHover(bool mouse_hover)
368 mouse_hover_ = mouse_hover;
373 bool InsetMathNest::notifyCursorLeaves(Cursor & /*cur*/)
377 MathData & ar = cur.cell();
378 // remove base-only "scripts"
379 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
380 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
381 if (p && p->nargs() == 1) {
382 MathData ar = p->nuc();
385 cur.adjust(i, ar.size() - 1);
389 // glue adjacent font insets of the same kind
390 for (pos_type i = 0; i + 1 < size(); ++i) {
391 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
392 InsetMathFont const * q = operator[](i + 1)->asFontInset();
393 if (p && q && p->name() == q->name()) {
394 p->cell(0).append(q->cell(0));
404 void InsetMathNest::handleFont
405 (Cursor & cur, docstring const & arg, char const * const font)
407 handleFont(cur, arg, from_ascii(font));
411 void InsetMathNest::handleFont
412 (Cursor & cur, docstring const & arg, docstring const & font)
414 // this whole function is a hack and won't work for incremental font
417 if (cur.inset().asInsetMath()->name() == font) {
418 cur.recordUndoInset();
419 cur.handleFont(to_utf8(font));
422 cur.handleNest(createInsetMath(font));
428 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
433 font.fromString(to_utf8(arg), b);
434 if (font.fontInfo().color() != Color_inherit) {
435 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
436 cur.handleNest(at, 0);
441 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
443 //lyxerr << "InsetMathNest: request: " << cmd << endl;
444 //CursorSlice sl = cur.current();
446 switch (cmd.action) {
450 cur.message(_("Paste"));
451 replaceSelection(cur);
453 if (cmd.argument().empty() && !theClipboard().isInternal())
454 topaste = theClipboard().getAsText();
457 idocstringstream is(cmd.argument());
459 topaste = cap::getSelection(cur.buffer(), n);
461 cur.niceInsert(topaste);
462 cur.clearSelection(); // bug 393
469 cutSelection(cur, true, true);
470 cur.message(_("Cut"));
471 // Prevent stale position >= size crash
472 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
478 cur.message(_("Copy"));
481 case LFUN_MOUSE_PRESS:
482 lfunMousePress(cur, cmd);
485 case LFUN_MOUSE_MOTION:
486 lfunMouseMotion(cur, cmd);
489 case LFUN_MOUSE_RELEASE:
490 lfunMouseRelease(cur, cmd);
493 case LFUN_FINISHED_BACKWARD:
494 cur.bv().cursor() = cur;
497 case LFUN_FINISHED_FORWARD:
499 cur.bv().cursor() = cur;
502 case LFUN_CHAR_FORWARD:
503 cur.updateFlags(Update::Decoration | Update::FitCursor);
504 case LFUN_CHAR_FORWARD_SELECT:
505 cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
506 cur.autocorrect() = false;
508 cur.macroModeClose();
509 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
510 cur.pushBackward(*cur.nextAtom().nucleus());
511 cur.inset().idxFirst(cur);
512 } else if (cur.posForward() || idxForward(cur)
513 || cur.popForward() || cur.selection())
516 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
521 case LFUN_CHAR_BACKWARD:
522 cur.updateFlags(Update::Decoration | Update::FitCursor);
523 case LFUN_CHAR_BACKWARD_SELECT:
524 cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
525 cur.autocorrect() = false;
527 cur.macroModeClose();
528 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
530 cur.push(*cur.nextAtom().nucleus());
531 cur.inset().idxLast(cur);
532 } else if (cur.posBackward() || idxBackward(cur)
533 || cur.popBackward() || cur.selection())
536 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
541 case LFUN_CHAR_RIGHT:
542 case LFUN_CHAR_RIGHT_SELECT:
543 //FIXME: for visual cursor, really move right
544 if (reverseDirectionNeeded(cur))
545 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
546 LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
548 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
549 LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
550 doDispatch(cur, cmd);
554 case LFUN_CHAR_LEFT_SELECT:
555 //FIXME: for visual cursor, really move left
556 if (reverseDirectionNeeded(cur))
557 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
558 LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
560 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
561 LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
562 doDispatch(cur, cmd);
567 cur.updateFlags(Update::Decoration | Update::FitCursor);
568 case LFUN_DOWN_SELECT:
569 case LFUN_UP_SELECT: {
570 // close active macro
571 if (cur.inMacroMode()) {
572 cur.macroModeClose();
576 // stop/start the selection
577 bool select = cmd.action == LFUN_DOWN_SELECT ||
578 cmd.action == LFUN_UP_SELECT;
579 cur.selHandle(select);
582 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
583 bool successful = cur.upDownInMath(up);
585 // notify left insets and give them chance to set update flags
586 lyx::notifyCursorLeaves(cur.beforeDispatchCursor(), cur);
591 if (cur.fixIfBroken())
592 // FIXME: Something bad happened. We pass the corrected Cursor
593 // instead of letting things go worse.
596 // We did not manage to move the cursor.
601 case LFUN_MOUSE_DOUBLE:
602 case LFUN_MOUSE_TRIPLE:
603 case LFUN_WORD_SELECT:
607 cur.selection() = true;
608 cur.pos() = cur.lastpos();
609 cur.idx() = cur.lastidx();
612 case LFUN_PARAGRAPH_UP:
613 case LFUN_PARAGRAPH_DOWN:
614 cur.updateFlags(Update::Decoration | Update::FitCursor);
615 case LFUN_PARAGRAPH_UP_SELECT:
616 case LFUN_PARAGRAPH_DOWN_SELECT:
619 case LFUN_LINE_BEGIN:
620 case LFUN_WORD_BACKWARD:
622 cur.updateFlags(Update::Decoration | Update::FitCursor);
623 case LFUN_LINE_BEGIN_SELECT:
624 case LFUN_WORD_BACKWARD_SELECT:
625 case LFUN_WORD_LEFT_SELECT:
626 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
627 cmd.action == LFUN_WORD_LEFT_SELECT ||
628 cmd.action == LFUN_LINE_BEGIN_SELECT);
629 cur.macroModeClose();
630 if (cur.pos() != 0) {
632 } else if (cur.col() != 0) {
633 cur.idx() -= cur.col();
635 } else if (cur.idx() != 0) {
639 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
644 case LFUN_WORD_FORWARD:
645 case LFUN_WORD_RIGHT:
647 cur.updateFlags(Update::Decoration | Update::FitCursor);
648 case LFUN_WORD_FORWARD_SELECT:
649 case LFUN_WORD_RIGHT_SELECT:
650 case LFUN_LINE_END_SELECT:
651 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
652 cmd.action == LFUN_WORD_RIGHT_SELECT ||
653 cmd.action == LFUN_LINE_END_SELECT);
654 cur.macroModeClose();
656 if (cur.pos() != cur.lastpos()) {
657 cur.pos() = cur.lastpos();
658 } else if (ncols() && (cur.col() != cur.lastcol())) {
659 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
660 cur.pos() = cur.lastpos();
661 } else if (cur.idx() != cur.lastidx()) {
662 cur.idx() = cur.lastidx();
663 cur.pos() = cur.lastpos();
665 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
670 case LFUN_SCREEN_UP_SELECT:
671 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
675 case LFUN_SCREEN_DOWN_SELECT:
676 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
680 case LFUN_CELL_FORWARD:
681 cur.updateFlags(Update::Decoration | Update::FitCursor);
682 cur.inset().idxNext(cur);
685 case LFUN_CELL_BACKWARD:
686 cur.updateFlags(Update::Decoration | Update::FitCursor);
687 cur.inset().idxPrev(cur);
690 case LFUN_WORD_DELETE_BACKWARD:
691 case LFUN_CHAR_DELETE_BACKWARD:
693 // May affect external cell:
694 cur.recordUndoInset();
697 // if the inset can not be removed from within, delete it
698 if (!cur.backspace()) {
699 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
700 cur.innerText()->dispatch(cur, cmd);
704 case LFUN_WORD_DELETE_FORWARD:
705 case LFUN_CHAR_DELETE_FORWARD:
706 if (cur.pos() == cur.lastpos())
707 // May affect external cell:
708 cur.recordUndoInset();
711 // if the inset can not be removed from within, delete it
713 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
714 cur.innerText()->dispatch(cur, cmd);
720 cur.clearSelection();
722 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
727 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
728 // that is traversed by a single <CursorLeft>/<CursorRight>.
729 case LFUN_INSET_TOGGLE:
735 case LFUN_SELF_INSERT:
736 if (cmd.argument().size() != 1) {
738 docstring const arg = cmd.argument();
739 if (!interpretString(cur, arg))
743 // Don't record undo steps if we are in macro mode and
744 // cmd.argument is the next character of the macro name.
745 // Otherwise we'll get an invalid cursor if we undo after
746 // the macro was finished and the macro is a known command,
747 // e.g. sqrt. Cursor::macroModeClose replaces in this case
748 // the InsetMathUnknown with name "frac" by an empty
749 // InsetMathFrac -> a pos value > 0 is invalid.
750 // A side effect is that an undo before the macro is finished
751 // undoes the complete macro, not only the last character.
752 if (!cur.inMacroMode())
755 // spacial handling of space. If we insert an inset
756 // via macro mode, we want to put the cursor inside it
757 // if relevant. Think typing "\frac<space>".
758 if (cmd.argument()[0] == ' '
759 && cur.inMacroMode() && cur.macroName() != "\\"
760 && cur.macroModeClose()) {
761 MathAtom const atom = cur.prevAtom();
762 if (atom->asNestInset() && atom->isActive()) {
764 cur.pushBackward(*cur.nextInset());
766 } else if (!interpretChar(cur, cmd.argument()[0])) {
767 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
772 //case LFUN_SERVER_GET_XY:
773 // sprintf(dispatch_buffer, "%d %d",);
776 case LFUN_SERVER_SET_XY: {
777 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
780 istringstream is(to_utf8(cmd.argument()));
782 cur.setScreenPos(x, y);
786 // Special casing for superscript in case of LyX handling
788 case LFUN_ACCENT_CIRCUMFLEX:
789 if (cmd.argument().empty()) {
790 // do superscript if LyX handles
793 script(cur, true, grabAndEraseSelection(cur));
797 case LFUN_ACCENT_UMLAUT:
798 case LFUN_ACCENT_ACUTE:
799 case LFUN_ACCENT_GRAVE:
800 case LFUN_ACCENT_BREVE:
801 case LFUN_ACCENT_DOT:
802 case LFUN_ACCENT_MACRON:
803 case LFUN_ACCENT_CARON:
804 case LFUN_ACCENT_TILDE:
805 case LFUN_ACCENT_CEDILLA:
806 case LFUN_ACCENT_CIRCLE:
807 case LFUN_ACCENT_UNDERDOT:
808 case LFUN_ACCENT_TIE:
809 case LFUN_ACCENT_OGONEK:
810 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
814 case LFUN_FONT_FREE_APPLY:
815 case LFUN_FONT_FREE_UPDATE:
816 handleFont2(cur, cmd.argument());
820 if (currentMode() == TEXT_MODE)
821 handleFont(cur, cmd.argument(), "textbf");
823 handleFont(cur, cmd.argument(), "mathbf");
826 if (currentMode() == TEXT_MODE)
827 handleFont(cur, cmd.argument(), "textsf");
829 handleFont(cur, cmd.argument(), "mathsf");
832 if (currentMode() == TEXT_MODE)
833 handleFont(cur, cmd.argument(), "emph");
835 handleFont(cur, cmd.argument(), "mathcal");
837 case LFUN_FONT_ROMAN:
838 if (currentMode() == TEXT_MODE)
839 handleFont(cur, cmd.argument(), "textrm");
841 handleFont(cur, cmd.argument(), "mathrm");
843 case LFUN_FONT_TYPEWRITER:
844 if (currentMode() == TEXT_MODE)
845 handleFont(cur, cmd.argument(), "texttt");
847 handleFont(cur, cmd.argument(), "mathtt");
850 handleFont(cur, cmd.argument(), "mathfrak");
853 if (currentMode() == TEXT_MODE)
854 handleFont(cur, cmd.argument(), "textit");
856 handleFont(cur, cmd.argument(), "mathit");
859 if (currentMode() == TEXT_MODE)
860 // FIXME: should be "noun"
861 handleFont(cur, cmd.argument(), "textsc");
863 handleFont(cur, cmd.argument(), "mathbb");
866 case LFUN_FONT_FREE_APPLY:
867 handleFont(cur, cmd.argument(), "textrm");
870 case LFUN_FONT_DEFAULT:
871 handleFont(cur, cmd.argument(), "textnormal");
874 case LFUN_MATH_MODE: {
876 // ignore math-mode on when already in math mode
877 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
879 cur.macroModeClose();
880 docstring const save_selection = grabAndEraseSelection(cur);
882 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
883 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
885 cur.pushBackward(*cur.nextInset());
886 cur.niceInsert(save_selection);
888 if (currentMode() == Inset::TEXT_MODE) {
889 cur.niceInsert(MathAtom(new InsetMathHull("simple")));
890 cur.message(_("create new math text environment ($...$)"));
892 handleFont(cur, cmd.argument(), "textrm");
893 cur.message(_("entered math text mode (textrm)"));
906 case LFUN_MATH_MATRIX: {
912 idocstringstream is(cmd.argument());
913 is >> m >> n >> v_align >> h_align;
920 MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
924 case LFUN_MATH_DELIM: {
926 docstring rs = split(cmd.argument(), ls, ' ');
927 // Reasonable default values
933 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
937 case LFUN_MATH_BIGDELIM: {
938 docstring const lname = from_utf8(cmd.getArg(0));
939 docstring const ldelim = from_utf8(cmd.getArg(1));
940 docstring const rname = from_utf8(cmd.getArg(2));
941 docstring const rdelim = from_utf8(cmd.getArg(3));
942 latexkeys const * l = in_word_set(lname);
943 bool const have_l = l && l->inset == "big" &&
944 InsetMathBig::isBigInsetDelim(ldelim);
945 l = in_word_set(rname);
946 bool const have_r = l && l->inset == "big" &&
947 InsetMathBig::isBigInsetDelim(rdelim);
948 // We mimic LFUN_MATH_DELIM in case we have an empty left
949 // or right delimiter.
950 if (have_l || have_r) {
952 docstring const selection = grabAndEraseSelection(cur);
955 cur.insert(MathAtom(new InsetMathBig(lname,
957 cur.niceInsert(selection);
959 cur.insert(MathAtom(new InsetMathBig(rname,
962 // Don't call cur.undispatched() if we did nothing, this would
963 // lead to infinite recursion via Text::dispatch().
967 case LFUN_SPACE_INSERT:
968 case LFUN_MATH_SPACE:
970 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
973 case LFUN_ERT_INSERT:
974 // interpret this as if a backslash was typed
976 interpretChar(cur, '\\');
979 case LFUN_MATH_SUBSCRIPT:
980 // interpret this as if a _ was typed
982 interpretChar(cur, '_');
985 case LFUN_MATH_SUPERSCRIPT:
986 // interpret this as if a ^ was typed
988 interpretChar(cur, '^');
991 case LFUN_MATH_MACRO_FOLD:
992 case LFUN_MATH_MACRO_UNFOLD: {
994 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
995 bool found = findMacroToFoldUnfold(it, fold);
997 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
998 cur.recordUndoInset();
1007 case LFUN_QUOTE_INSERT:
1008 // interpret this as if a straight " was typed
1010 interpretChar(cur, '\"');
1013 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1014 // handling such that "self-insert" works on "arbitrary stuff" too, and
1015 // math-insert only handles special math things like "matrix".
1016 case LFUN_MATH_INSERT: {
1018 if (cmd.argument() == "^" || cmd.argument() == "_") {
1019 interpretChar(cur, cmd.argument()[0]);
1021 cur.niceInsert(cmd.argument());
1025 case LFUN_DIALOG_SHOW_NEW_INSET: {
1026 docstring const & name = cmd.argument();
1028 if (name == "ref") {
1029 InsetMathRef tmp(name);
1030 data = tmp.createDialogStr(to_utf8(name));
1032 cur.bv().showDialog(to_utf8(name), data);
1036 case LFUN_INSET_INSERT: {
1038 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1045 case LFUN_INSET_DISSOLVE:
1046 if (!asHullInset()) {
1047 cur.recordUndoInset();
1053 InsetMath::doDispatch(cur, cmd);
1059 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1060 // look for macro to open/close, but stay in mathed
1061 for (; !it.empty(); it.pop_back()) {
1063 // go backward through the current cell
1064 Inset * inset = it.nextInset();
1065 while (inset && inset->asInsetMath()) {
1066 MathMacro * macro = inset->asInsetMath()->asMacro();
1068 // found the an macro to open/close?
1069 if (macro->folded() != fold)
1072 // Wrong folding state.
1073 // If this was the first we see in this slice, look further left,
1075 if (inset != it.nextInset())
1079 // go up if this was the left most position
1085 inset = it.nextInset();
1093 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1094 FuncStatus & flag) const
1096 // the font related toggles
1097 //string tc = "mathnormal";
1099 string const arg = to_utf8(cmd.argument());
1100 switch (cmd.action) {
1101 case LFUN_TABULAR_FEATURE:
1102 flag.enabled(false);
1105 case LFUN_TABULAR_FEATURE:
1106 // FIXME: check temporarily disabled
1108 char align = mathcursor::valign();
1109 if (align == '\0') {
1113 if (cmd.argument().empty()) {
1117 if (!contains("tcb", cmd.argument()[0])) {
1121 flag.setOnOff(cmd.argument()[0] == align);
1124 /// We have to handle them since 1.4 blocks all unhandled actions
1125 case LFUN_FONT_ITAL:
1126 case LFUN_FONT_BOLD:
1127 case LFUN_FONT_SANS:
1128 case LFUN_FONT_EMPH:
1129 case LFUN_FONT_TYPEWRITER:
1130 case LFUN_FONT_NOUN:
1131 case LFUN_FONT_ROMAN:
1132 case LFUN_FONT_DEFAULT:
1135 case LFUN_MATH_MUTATE:
1136 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1137 flag.setOnOff(false);
1140 // we just need to be in math mode to enable that
1141 case LFUN_MATH_SIZE:
1142 case LFUN_MATH_SPACE:
1143 case LFUN_MATH_LIMITS:
1144 case LFUN_MATH_EXTERN:
1148 case LFUN_FONT_FRAK:
1149 flag.enabled(currentMode() != TEXT_MODE);
1152 case LFUN_MATH_INSERT: {
1153 bool const textarg =
1154 arg == "\\textbf" || arg == "\\textsf" ||
1155 arg == "\\textrm" || arg == "\\textmd" ||
1156 arg == "\\textit" || arg == "\\textsc" ||
1157 arg == "\\textsl" || arg == "\\textup" ||
1158 arg == "\\texttt" || arg == "\\textbb" ||
1159 arg == "\\textnormal";
1160 flag.enabled(currentMode() != TEXT_MODE || textarg);
1164 case LFUN_MATH_MATRIX:
1165 flag.enabled(currentMode() == MATH_MODE);
1168 case LFUN_INSET_INSERT: {
1169 // Don't test createMathInset_fromDialogStr(), since
1170 // getStatus is not called with a valid reference and the
1171 // dialog would not be applyable.
1172 string const name = cmd.getArg(0);
1173 flag.enabled(name == "ref");
1177 case LFUN_MATH_DELIM:
1178 case LFUN_MATH_BIGDELIM:
1179 // Don't do this with multi-cell selections
1180 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1183 case LFUN_MATH_MACRO_FOLD:
1184 case LFUN_MATH_MACRO_UNFOLD: {
1186 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1187 flag.enabled(found);
1191 case LFUN_SPECIALCHAR_INSERT:
1192 // FIXME: These would probably make sense in math-text mode
1193 flag.enabled(false);
1196 case LFUN_INSET_DISSOLVE:
1197 flag.enabled(!asHullInset());
1208 void InsetMathNest::edit(Cursor & cur, bool left)
1211 cur.idx() = left ? 0 : cur.lastidx();
1212 cur.pos() = left ? 0 : cur.lastpos();
1214 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1218 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1221 int dist_min = 1000000;
1222 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1223 int const d = cell(i).dist(cur.bv(), x, y);
1229 MathData & ar = cell(idx_min);
1231 cur.idx() = idx_min;
1232 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1234 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1235 if (dist_min == 0) {
1237 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1238 if (ar[i]->covers(cur.bv(), x, y))
1239 return ar[i].nucleus()->editXY(cur, x, y);
1245 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1247 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1248 BufferView & bv = cur.bv();
1249 bool do_selection = cmd.button() == mouse_button::button1
1250 && cmd.argument() == "region-select";
1251 bv.mouseSetCursor(cur, do_selection);
1252 if (cmd.button() == mouse_button::button1) {
1253 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1254 // Update the cursor update flags as needed:
1256 // Update::Decoration: tells to update the decoration
1257 // (visual box corners that define
1259 // Update::FitCursor: adjust the screen to the cursor
1260 // position if needed
1261 // cur.result().update(): don't overwrite previously set flags.
1262 cur.updateFlags(Update::Decoration | Update::FitCursor
1263 | cur.result().update());
1264 } else if (cmd.button() == mouse_button::button2) {
1265 if (cap::selection()) {
1266 // See comment in Text::dispatch why we do this
1267 cap::copySelectionToStack();
1268 cmd = FuncRequest(LFUN_PASTE, "0");
1269 doDispatch(bv.cursor(), cmd);
1272 asArray(theSelection().get(), ar);
1273 bv.cursor().insert(ar);
1279 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1281 // only select with button 1
1282 if (cmd.button() == mouse_button::button1) {
1283 Cursor & bvcur = cur.bv().cursor();
1284 if (bvcur.anchor_.hasPart(cur)) {
1285 //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1286 bvcur.setCursor(cur);
1287 bvcur.selection() = true;
1288 //lyxerr << "MOTION " << bvcur << endl;
1295 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1297 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1299 if (cmd.button() == mouse_button::button1) {
1300 if (!cur.selection())
1303 Cursor & bvcur = cur.bv().cursor();
1304 bvcur.selection() = true;
1313 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1315 //lyxerr << "interpret 2: '" << c << "'" << endl;
1316 docstring save_selection;
1317 if (c == '^' || c == '_')
1318 save_selection = grabAndEraseSelection(cur);
1323 if (cur.inMacroMode()) {
1324 docstring name = cur.macroName();
1326 /// are we currently typing '#1' or '#2' or...?
1327 if (name == "\\#") {
1330 if (n >= 1 && n <= 9)
1331 cur.insert(new MathMacroArgument(n));
1335 if (isAlphaASCII(c)) {
1336 cur.activeMacro()->setName(name + docstring(1, c));
1340 // handle 'special char' macros
1345 if (currentMode() == InsetMath::TEXT_MODE)
1346 cur.niceInsert(createInsetMath("textbackslash"));
1348 cur.niceInsert(createInsetMath("backslash"));
1349 } else if (c == '{') {
1351 cur.niceInsert(MathAtom(new InsetMathBrace));
1352 } else if (c == '%') {
1354 cur.niceInsert(MathAtom(new InsetMathComment));
1355 } else if (c == '#') {
1356 BOOST_ASSERT(cur.activeMacro());
1357 cur.activeMacro()->setName(name + docstring(1, c));
1360 cur.niceInsert(createInsetMath(docstring(1, c)));
1365 // One character big delimiters. The others are handled in
1366 // interpretString().
1367 latexkeys const * l = in_word_set(name.substr(1));
1368 if (name[0] == '\\' && l && l->inset == "big") {
1372 delim = from_ascii("\\{");
1375 delim = from_ascii("\\}");
1378 delim = docstring(1, c);
1381 if (InsetMathBig::isBigInsetDelim(delim)) {
1382 // name + delim ared a valid InsetMathBig.
1383 // We can't use cur.macroModeClose() because
1384 // it does not handle delim.
1385 InsetMathUnknown * p = cur.activeMacro();
1388 cur.cell().erase(cur.pos());
1389 cur.plainInsert(MathAtom(
1390 new InsetMathBig(name.substr(1), delim)));
1395 // leave macro mode and try again if necessary
1396 cur.macroModeClose();
1398 cur.niceInsert(MathAtom(new InsetMathBrace));
1400 interpretChar(cur, c);
1404 // This is annoying as one has to press <space> far too often.
1408 // leave autocorrect mode if necessary
1409 if (autocorrect() && c == ' ') {
1410 autocorrect() = false;
1415 // just clear selection on pressing the space bar
1416 if (cur.selection() && c == ' ') {
1417 cur.selection() = false;
1424 //lyxerr << "starting with macro" << endl;
1425 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1430 if (currentMode() == InsetMath::TEXT_MODE)
1436 if (currentMode() == InsetMath::TEXT_MODE) {
1437 // insert spaces in text mode,
1438 // but suppress direct insertion of two spaces in a row
1439 // the still allows typing '<space>a<space>' and deleting the 'a', but
1440 // it is better than nothing...
1441 if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1443 // FIXME: we have to enable full redraw here because of the
1444 // visual box corners that define the inset. If we know for
1445 // sure that we stay within the same cell we can optimize for
1447 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1451 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1452 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1453 // FIXME: we have to enable full redraw here because of the
1454 // visual box corners that define the inset. If we know for
1455 // sure that we stay within the same cell we can optimize for
1457 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1461 if (cur.popForward()) {
1462 // FIXME: we have to enable full redraw here because of the
1463 // visual box corners that define the inset. If we know for
1464 // sure that we stay within the same cell we can optimize for
1466 //cur.updateFlags(Update::FitCursor);
1470 // if we are at the very end, leave the formula
1471 return cur.pos() != cur.lastpos();
1474 // These shouldn't work in text mode:
1475 if (currentMode() != InsetMath::TEXT_MODE) {
1477 script(cur, false, save_selection);
1481 script(cur, true, save_selection);
1485 cur.niceInsert(createInsetMath("sim"));
1490 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1491 c == '%' || c == '_' || c == '^') {
1492 cur.niceInsert(createInsetMath(docstring(1, c)));
1497 // try auto-correction
1498 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1501 // no special circumstances, so insert the character without any fuss
1503 cur.autocorrect() = true;
1508 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1510 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1512 if (!cur.empty() && cur.pos() > 0 &&
1513 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1514 if (InsetMathBig::isBigInsetDelim(str)) {
1515 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1516 if (prev[0] == '\\') {
1517 prev = prev.substr(1);
1518 latexkeys const * l = in_word_set(prev);
1519 if (l && l->inset == "big") {
1520 cur.cell()[cur.pos() - 1] =
1521 MathAtom(new InsetMathBig(prev, str));
1531 bool InsetMathNest::script(Cursor & cur, bool up,
1532 docstring const & save_selection)
1534 // Hack to get \^ and \_ working
1535 //lyxerr << "handling script: up: " << up << endl;
1536 if (cur.inMacroMode() && cur.macroName() == "\\") {
1538 cur.niceInsert(createInsetMath("mathcircumflex"));
1540 interpretChar(cur, '_');
1544 cur.macroModeClose();
1545 if (asScriptInset() && cur.idx() == 0) {
1546 // we are in a nucleus of a script inset, move to _our_ script
1547 InsetMathScript * inset = asScriptInset();
1548 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1550 cur.idx() = inset->idxOfScript(up);
1552 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1554 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1557 cur.idx() = inset->idxOfScript(up);
1558 cur.pos() = cur.lastpos();
1560 // convert the thing to our left to a scriptinset or create a new
1561 // one if in the very first position of the array
1562 if (cur.pos() == 0) {
1563 //lyxerr << "new scriptinset" << endl;
1564 cur.insert(new InsetMathScript(up));
1566 //lyxerr << "converting prev atom " << endl;
1567 cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1570 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1571 // See comment in MathParser.cpp for special handling of {}-bases
1577 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1578 cur.niceInsert(save_selection);
1580 //lyxerr << "inserting selection 2:\n" << save_selection << endl;