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"
47 #include "support/gettext.h"
49 #include "OutputParams.h"
51 #include "support/lstrings.h"
52 #include "support/textutils.h"
53 #include "support/docstream.h"
55 #include "frontends/Clipboard.h"
56 #include "frontends/Painter.h"
57 #include "frontends/Selection.h"
59 #include "FuncRequest.h"
64 using namespace lyx::support;
68 using cap::copySelection;
69 using cap::grabAndEraseSelection;
70 using cap::cutSelection;
71 using cap::replaceSelection;
72 using cap::selClearOrDel;
75 InsetMathNest::InsetMathNest(idx_type nargs)
76 : cells_(nargs), lock_(false), mouse_hover_(false)
80 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
81 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
86 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
88 cells_ = inset.cells_;
91 InsetMath::operator=(inset);
96 InsetMath::idx_type InsetMathNest::nargs() const
102 void InsetMathNest::cursorPos(BufferView const & bv,
103 CursorSlice const & sl, bool /*boundary*/,
104 int & x, int & y) const
106 // FIXME: This is a hack. Ideally, the coord cache should not store
107 // absolute positions, but relative ones. This would mean to call
108 // setXY() not in MathData::draw(), but in the parent insets' draw()
109 // with the correctly adjusted x,y values. But this means that we'd have
110 // to touch all (math)inset's draw() methods. Right now, we'll store
111 // absolute value, and make them here relative, only to make them
112 // absolute again when actually drawing the cursor. What a mess.
113 BOOST_ASSERT(&sl.inset() == this);
114 MathData const & ar = sl.cell();
115 CoordCache const & coord_cache = bv.coordCache();
116 if (!coord_cache.getArrays().has(&ar)) {
117 // this can (semi-)legally happen if we just created this cell
118 // and it never has been drawn before. So don't ASSERT.
119 //lyxerr << "no cached data for array " << &ar << endl;
124 Point const pt = coord_cache.getArrays().xy(&ar);
125 if (!coord_cache.getInsets().has(this)) {
127 //lyxerr << "no cached data for inset " << this << endl;
132 Point const pt2 = coord_cache.getInsets().xy(this);
133 //lyxerr << "retrieving position cache for MathData "
134 // << pt.x_ << ' ' << pt.y_ << endl;
135 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
137 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
138 // << " asc: " << ascent() << " des: " << descent()
139 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
140 // move cursor visually into empty cells ("blue rectangles");
146 void InsetMathNest::metrics(MetricsInfo const & mi) const
149 for (idx_type i = 0, n = nargs(); i != n; ++i) {
151 cell(i).metrics(m, dim);
156 bool InsetMathNest::idxNext(Cursor & cur) const
158 BOOST_ASSERT(&cur.inset() == this);
159 if (cur.idx() == cur.lastidx())
167 bool InsetMathNest::idxForward(Cursor & cur) const
173 bool InsetMathNest::idxPrev(Cursor & cur) const
175 BOOST_ASSERT(&cur.inset() == this);
179 cur.pos() = cur.lastpos();
184 bool InsetMathNest::idxBackward(Cursor & cur) const
190 bool InsetMathNest::idxFirst(Cursor & cur) const
192 BOOST_ASSERT(&cur.inset() == this);
201 bool InsetMathNest::idxLast(Cursor & cur) const
203 BOOST_ASSERT(&cur.inset() == this);
206 cur.idx() = cur.lastidx();
207 cur.pos() = cur.lastpos();
212 void InsetMathNest::dump() const
214 odocstringstream oss;
216 os << "---------------------------------------------\n";
219 for (idx_type i = 0, n = nargs(); i != n; ++i)
220 os << cell(i) << "\n";
221 os << "---------------------------------------------\n";
222 lyxerr << to_utf8(oss.str());
226 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
230 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
233 setPosCache(pi, x, y);
237 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
239 BufferView & bv = *pi.base.bv;
240 // this should use the x/y values given, not the cached values
241 Cursor & cur = bv.cursor();
242 if (!cur.selection())
244 if (&cur.inset() != this)
247 // FIXME: hack to get position cache warm
248 bool const original_drawing_state = pi.pain.isDrawingEnabled();
249 pi.pain.setDrawingEnabled(false);
251 pi.pain.setDrawingEnabled(original_drawing_state);
253 CursorSlice s1 = cur.selBegin();
254 CursorSlice s2 = cur.selEnd();
256 //lyxerr << "InsetMathNest::drawing selection: "
257 // << " s1: " << s1 << " s2: " << s2 << endl;
258 if (s1.idx() == s2.idx()) {
259 MathData const & c = cell(s1.idx());
260 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
261 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
262 int y1 = g.pos.y_ - g.dim.ascent();
263 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
264 int y2 = g.pos.y_ + g.dim.descent();
265 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
266 //lyxerr << "InsetMathNest::drawing selection 3: "
267 // << " x1: " << x1 << " x2: " << x2
268 // << " y1: " << y1 << " y2: " << y2 << endl;
270 for (idx_type i = 0; i < nargs(); ++i) {
271 if (idxBetween(i, s1.idx(), s2.idx())) {
272 MathData const & c = cell(i);
273 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
275 int y1 = g.pos.y_ - g.dim.ascent();
276 int x2 = g.pos.x_ + g.dim.width();
277 int y2 = g.pos.y_ + g.dim.descent();
278 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
285 void InsetMathNest::validate(LaTeXFeatures & features) const
287 for (idx_type i = 0; i < nargs(); ++i)
288 cell(i).validate(features);
292 void InsetMathNest::replace(ReplaceData & rep)
294 for (idx_type i = 0; i < nargs(); ++i)
295 cell(i).replace(rep);
299 bool InsetMathNest::contains(MathData const & ar) const
301 for (idx_type i = 0; i < nargs(); ++i)
302 if (cell(i).contains(ar))
308 bool InsetMathNest::lock() const
314 void InsetMathNest::lock(bool l)
320 bool InsetMathNest::isActive() const
326 MathData InsetMathNest::glue() const
329 for (size_t i = 0; i < nargs(); ++i)
335 void InsetMathNest::write(WriteStream & os) const
337 os << '\\' << name().c_str();
338 for (size_t i = 0; i < nargs(); ++i)
339 os << '{' << cell(i) << '}';
341 os.pendingSpace(true);
342 if (lock_ && !os.latex()) {
344 os.pendingSpace(true);
349 void InsetMathNest::normalize(NormalStream & os) const
351 os << '[' << name().c_str();
352 for (size_t i = 0; i < nargs(); ++i)
353 os << ' ' << cell(i);
358 int InsetMathNest::latex(Buffer const &, odocstream & os,
359 OutputParams const & runparams) const
361 WriteStream wi(os, runparams.moving_arg, true);
367 bool InsetMathNest::setMouseHover(bool mouse_hover)
369 mouse_hover_ = mouse_hover;
374 bool InsetMathNest::notifyCursorLeaves(Cursor & /*cur*/)
378 MathData & ar = cur.cell();
379 // remove base-only "scripts"
380 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
381 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
382 if (p && p->nargs() == 1) {
383 MathData ar = p->nuc();
386 cur.adjust(i, ar.size() - 1);
390 // glue adjacent font insets of the same kind
391 for (pos_type i = 0; i + 1 < size(); ++i) {
392 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
393 InsetMathFont const * q = operator[](i + 1)->asFontInset();
394 if (p && q && p->name() == q->name()) {
395 p->cell(0).append(q->cell(0));
405 void InsetMathNest::handleFont
406 (Cursor & cur, docstring const & arg, char const * const font)
408 handleFont(cur, arg, from_ascii(font));
412 void InsetMathNest::handleFont
413 (Cursor & cur, docstring const & arg, docstring const & font)
415 // this whole function is a hack and won't work for incremental font
418 if (cur.inset().asInsetMath()->name() == font) {
419 cur.recordUndoInset();
420 cur.handleFont(to_utf8(font));
423 cur.handleNest(createInsetMath(font));
429 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
434 font.fromString(to_utf8(arg), b);
435 if (font.fontInfo().color() != Color_inherit) {
436 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
437 cur.handleNest(at, 0);
442 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
444 //lyxerr << "InsetMathNest: request: " << cmd << endl;
445 //CursorSlice sl = cur.current();
447 switch (cmd.action) {
451 cur.message(_("Paste"));
452 replaceSelection(cur);
454 if (cmd.argument().empty() && !theClipboard().isInternal())
455 topaste = theClipboard().getAsText();
458 idocstringstream is(cmd.argument());
460 topaste = cap::getSelection(cur.buffer(), n);
462 cur.niceInsert(topaste);
463 cur.clearSelection(); // bug 393
470 cutSelection(cur, true, true);
471 cur.message(_("Cut"));
472 // Prevent stale position >= size crash
473 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
479 cur.message(_("Copy"));
482 case LFUN_MOUSE_PRESS:
483 lfunMousePress(cur, cmd);
486 case LFUN_MOUSE_MOTION:
487 lfunMouseMotion(cur, cmd);
490 case LFUN_MOUSE_RELEASE:
491 lfunMouseRelease(cur, cmd);
494 case LFUN_FINISHED_LEFT: // in math, left is backwards
495 case LFUN_FINISHED_BACKWARD:
496 cur.bv().cursor() = cur;
499 case LFUN_FINISHED_RIGHT: // in math, right is forward
500 case LFUN_FINISHED_FORWARD:
502 cur.bv().cursor() = cur;
505 case LFUN_CHAR_RIGHT:
507 case LFUN_CHAR_BACKWARD:
508 case LFUN_CHAR_FORWARD:
509 cur.updateFlags(Update::Decoration | Update::FitCursor);
510 case LFUN_CHAR_RIGHT_SELECT:
511 case LFUN_CHAR_LEFT_SELECT:
512 case LFUN_CHAR_BACKWARD_SELECT:
513 case LFUN_CHAR_FORWARD_SELECT: {
514 // are we in a selection?
515 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT
516 || cmd.action == LFUN_CHAR_LEFT_SELECT
517 || cmd.action == LFUN_CHAR_BACKWARD_SELECT
518 || cmd.action == LFUN_CHAR_FORWARD_SELECT);
519 // are we moving forward or backwards?
520 // If the command was RIGHT or LEFT, then whether we're moving forward
521 // or backwards depends on the cursor movement mode (logical or visual):
522 // * in visual mode, since math is always LTR, right -> forward,
524 // * in logical mode, the mapping is determined by the
525 // reverseDirectionNeeded() function
528 kb_action finish_lfun;
530 if (cmd.action == LFUN_CHAR_FORWARD
531 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
533 finish_lfun = LFUN_FINISHED_FORWARD;
535 else if (cmd.action == LFUN_CHAR_BACKWARD
536 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
538 finish_lfun = LFUN_FINISHED_BACKWARD;
541 bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
542 || cmd.action == LFUN_CHAR_RIGHT);
543 if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
549 finish_lfun = LFUN_FINISHED_RIGHT;
551 finish_lfun = LFUN_FINISHED_LEFT;
553 // Now that we know exactly what we want to do, let's do it!
554 cur.selHandle(select);
555 cur.autocorrect() = false;
557 cur.macroModeClose();
558 // try moving forward or backwards as necessary...
559 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
560 // ... and if movement failed, then finish forward or backwards
562 cmd = FuncRequest(finish_lfun);
570 cur.updateFlags(Update::Decoration | Update::FitCursor);
571 case LFUN_DOWN_SELECT:
572 case LFUN_UP_SELECT: {
573 // close active macro
574 if (cur.inMacroMode()) {
575 cur.macroModeClose();
579 // stop/start the selection
580 bool select = cmd.action == LFUN_DOWN_SELECT ||
581 cmd.action == LFUN_UP_SELECT;
582 cur.selHandle(select);
585 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
586 bool successful = cur.upDownInMath(up);
588 // notify left insets and give them chance to set update flags
589 lyx::notifyCursorLeaves(cur.beforeDispatchCursor(), cur);
594 if (cur.fixIfBroken())
595 // FIXME: Something bad happened. We pass the corrected Cursor
596 // instead of letting things go worse.
599 // We did not manage to move the cursor.
604 case LFUN_MOUSE_DOUBLE:
605 case LFUN_MOUSE_TRIPLE:
606 case LFUN_WORD_SELECT:
610 cur.selection() = true;
611 cur.pos() = cur.lastpos();
612 cur.idx() = cur.lastidx();
615 case LFUN_PARAGRAPH_UP:
616 case LFUN_PARAGRAPH_DOWN:
617 cur.updateFlags(Update::Decoration | Update::FitCursor);
618 case LFUN_PARAGRAPH_UP_SELECT:
619 case LFUN_PARAGRAPH_DOWN_SELECT:
622 case LFUN_LINE_BEGIN:
623 case LFUN_WORD_BACKWARD:
625 cur.updateFlags(Update::Decoration | Update::FitCursor);
626 case LFUN_LINE_BEGIN_SELECT:
627 case LFUN_WORD_BACKWARD_SELECT:
628 case LFUN_WORD_LEFT_SELECT:
629 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
630 cmd.action == LFUN_WORD_LEFT_SELECT ||
631 cmd.action == LFUN_LINE_BEGIN_SELECT);
632 cur.macroModeClose();
633 if (cur.pos() != 0) {
635 } else if (cur.col() != 0) {
636 cur.idx() -= cur.col();
638 } else if (cur.idx() != 0) {
642 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
647 case LFUN_WORD_FORWARD:
648 case LFUN_WORD_RIGHT:
650 cur.updateFlags(Update::Decoration | Update::FitCursor);
651 case LFUN_WORD_FORWARD_SELECT:
652 case LFUN_WORD_RIGHT_SELECT:
653 case LFUN_LINE_END_SELECT:
654 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
655 cmd.action == LFUN_WORD_RIGHT_SELECT ||
656 cmd.action == LFUN_LINE_END_SELECT);
657 cur.macroModeClose();
659 if (cur.pos() != cur.lastpos()) {
660 cur.pos() = cur.lastpos();
661 } else if (ncols() && (cur.col() != cur.lastcol())) {
662 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
663 cur.pos() = cur.lastpos();
664 } else if (cur.idx() != cur.lastidx()) {
665 cur.idx() = cur.lastidx();
666 cur.pos() = cur.lastpos();
668 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
673 case LFUN_SCREEN_UP_SELECT:
674 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
678 case LFUN_SCREEN_DOWN_SELECT:
679 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
683 case LFUN_CELL_FORWARD:
684 cur.updateFlags(Update::Decoration | Update::FitCursor);
685 cur.inset().idxNext(cur);
688 case LFUN_CELL_BACKWARD:
689 cur.updateFlags(Update::Decoration | Update::FitCursor);
690 cur.inset().idxPrev(cur);
693 case LFUN_WORD_DELETE_BACKWARD:
694 case LFUN_CHAR_DELETE_BACKWARD:
696 // May affect external cell:
697 cur.recordUndoInset();
700 // if the inset can not be removed from within, delete it
701 if (!cur.backspace()) {
702 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
703 cur.innerText()->dispatch(cur, cmd);
707 case LFUN_WORD_DELETE_FORWARD:
708 case LFUN_CHAR_DELETE_FORWARD:
709 if (cur.pos() == cur.lastpos())
710 // May affect external cell:
711 cur.recordUndoInset();
714 // if the inset can not be removed from within, delete it
716 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
717 cur.innerText()->dispatch(cur, cmd);
723 cur.clearSelection();
725 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
730 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
731 // that is traversed by a single <CursorLeft>/<CursorRight>.
732 case LFUN_INSET_TOGGLE:
738 case LFUN_SELF_INSERT:
739 if (cmd.argument().size() != 1) {
741 docstring const arg = cmd.argument();
742 if (!interpretString(cur, arg))
746 // Don't record undo steps if we are in macro mode and
747 // cmd.argument is the next character of the macro name.
748 // Otherwise we'll get an invalid cursor if we undo after
749 // the macro was finished and the macro is a known command,
750 // e.g. sqrt. Cursor::macroModeClose replaces in this case
751 // the InsetMathUnknown with name "frac" by an empty
752 // InsetMathFrac -> a pos value > 0 is invalid.
753 // A side effect is that an undo before the macro is finished
754 // undoes the complete macro, not only the last character.
755 if (!cur.inMacroMode())
758 // spacial handling of space. If we insert an inset
759 // via macro mode, we want to put the cursor inside it
760 // if relevant. Think typing "\frac<space>".
761 if (cmd.argument()[0] == ' '
762 && cur.inMacroMode() && cur.macroName() != "\\"
763 && cur.macroModeClose()) {
764 MathAtom const atom = cur.prevAtom();
765 if (atom->asNestInset() && atom->isActive()) {
767 cur.pushBackward(*cur.nextInset());
769 } else if (!interpretChar(cur, cmd.argument()[0])) {
770 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
775 //case LFUN_SERVER_GET_XY:
776 // sprintf(dispatch_buffer, "%d %d",);
779 case LFUN_SERVER_SET_XY: {
780 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
783 istringstream is(to_utf8(cmd.argument()));
785 cur.setScreenPos(x, y);
789 // Special casing for superscript in case of LyX handling
791 case LFUN_ACCENT_CIRCUMFLEX:
792 if (cmd.argument().empty()) {
793 // do superscript if LyX handles
796 script(cur, true, grabAndEraseSelection(cur));
800 case LFUN_ACCENT_UMLAUT:
801 case LFUN_ACCENT_ACUTE:
802 case LFUN_ACCENT_GRAVE:
803 case LFUN_ACCENT_BREVE:
804 case LFUN_ACCENT_DOT:
805 case LFUN_ACCENT_MACRON:
806 case LFUN_ACCENT_CARON:
807 case LFUN_ACCENT_TILDE:
808 case LFUN_ACCENT_CEDILLA:
809 case LFUN_ACCENT_CIRCLE:
810 case LFUN_ACCENT_UNDERDOT:
811 case LFUN_ACCENT_TIE:
812 case LFUN_ACCENT_OGONEK:
813 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
817 case LFUN_FONT_FREE_APPLY:
818 case LFUN_FONT_FREE_UPDATE:
819 handleFont2(cur, cmd.argument());
823 if (currentMode() == TEXT_MODE)
824 handleFont(cur, cmd.argument(), "textbf");
826 handleFont(cur, cmd.argument(), "mathbf");
829 if (currentMode() == TEXT_MODE)
830 handleFont(cur, cmd.argument(), "textsf");
832 handleFont(cur, cmd.argument(), "mathsf");
835 if (currentMode() == TEXT_MODE)
836 handleFont(cur, cmd.argument(), "emph");
838 handleFont(cur, cmd.argument(), "mathcal");
840 case LFUN_FONT_ROMAN:
841 if (currentMode() == TEXT_MODE)
842 handleFont(cur, cmd.argument(), "textrm");
844 handleFont(cur, cmd.argument(), "mathrm");
846 case LFUN_FONT_TYPEWRITER:
847 if (currentMode() == TEXT_MODE)
848 handleFont(cur, cmd.argument(), "texttt");
850 handleFont(cur, cmd.argument(), "mathtt");
853 handleFont(cur, cmd.argument(), "mathfrak");
856 if (currentMode() == TEXT_MODE)
857 handleFont(cur, cmd.argument(), "textit");
859 handleFont(cur, cmd.argument(), "mathit");
862 if (currentMode() == TEXT_MODE)
863 // FIXME: should be "noun"
864 handleFont(cur, cmd.argument(), "textsc");
866 handleFont(cur, cmd.argument(), "mathbb");
869 case LFUN_FONT_FREE_APPLY:
870 handleFont(cur, cmd.argument(), "textrm");
873 case LFUN_FONT_DEFAULT:
874 handleFont(cur, cmd.argument(), "textnormal");
877 case LFUN_MATH_MODE: {
879 // ignore math-mode on when already in math mode
880 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
882 cur.macroModeClose();
883 docstring const save_selection = grabAndEraseSelection(cur);
885 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
886 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
888 cur.pushBackward(*cur.nextInset());
889 cur.niceInsert(save_selection);
891 if (currentMode() == Inset::TEXT_MODE) {
892 cur.niceInsert(MathAtom(new InsetMathHull("simple")));
893 cur.message(_("create new math text environment ($...$)"));
895 handleFont(cur, cmd.argument(), "textrm");
896 cur.message(_("entered math text mode (textrm)"));
909 case LFUN_MATH_MATRIX: {
915 idocstringstream is(cmd.argument());
916 is >> m >> n >> v_align >> h_align;
923 MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
927 case LFUN_MATH_DELIM: {
929 docstring rs = split(cmd.argument(), ls, ' ');
930 // Reasonable default values
936 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
940 case LFUN_MATH_BIGDELIM: {
941 docstring const lname = from_utf8(cmd.getArg(0));
942 docstring const ldelim = from_utf8(cmd.getArg(1));
943 docstring const rname = from_utf8(cmd.getArg(2));
944 docstring const rdelim = from_utf8(cmd.getArg(3));
945 latexkeys const * l = in_word_set(lname);
946 bool const have_l = l && l->inset == "big" &&
947 InsetMathBig::isBigInsetDelim(ldelim);
948 l = in_word_set(rname);
949 bool const have_r = l && l->inset == "big" &&
950 InsetMathBig::isBigInsetDelim(rdelim);
951 // We mimic LFUN_MATH_DELIM in case we have an empty left
952 // or right delimiter.
953 if (have_l || have_r) {
955 docstring const selection = grabAndEraseSelection(cur);
958 cur.insert(MathAtom(new InsetMathBig(lname,
960 cur.niceInsert(selection);
962 cur.insert(MathAtom(new InsetMathBig(rname,
965 // Don't call cur.undispatched() if we did nothing, this would
966 // lead to infinite recursion via Text::dispatch().
970 case LFUN_SPACE_INSERT:
971 case LFUN_MATH_SPACE:
973 cur.insert(MathAtom(new InsetMathSpace(from_ascii(","))));
976 case LFUN_ERT_INSERT:
977 // interpret this as if a backslash was typed
979 interpretChar(cur, '\\');
982 case LFUN_MATH_SUBSCRIPT:
983 // interpret this as if a _ was typed
985 interpretChar(cur, '_');
988 case LFUN_MATH_SUPERSCRIPT:
989 // interpret this as if a ^ was typed
991 interpretChar(cur, '^');
994 case LFUN_MATH_MACRO_FOLD:
995 case LFUN_MATH_MACRO_UNFOLD: {
997 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
998 bool found = findMacroToFoldUnfold(it, fold);
1000 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1001 cur.recordUndoInset();
1010 case LFUN_QUOTE_INSERT:
1011 // interpret this as if a straight " was typed
1013 interpretChar(cur, '\"');
1016 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1017 // handling such that "self-insert" works on "arbitrary stuff" too, and
1018 // math-insert only handles special math things like "matrix".
1019 case LFUN_MATH_INSERT: {
1021 if (cmd.argument() == "^" || cmd.argument() == "_") {
1022 interpretChar(cur, cmd.argument()[0]);
1024 cur.niceInsert(cmd.argument());
1028 case LFUN_DIALOG_SHOW_NEW_INSET: {
1029 docstring const & name = cmd.argument();
1031 if (name == "ref") {
1032 InsetMathRef tmp(name);
1033 data = tmp.createDialogStr(to_utf8(name));
1035 cur.bv().showDialog(to_utf8(name), data);
1039 case LFUN_INSET_INSERT: {
1041 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1048 case LFUN_INSET_DISSOLVE:
1049 if (!asHullInset()) {
1050 cur.recordUndoInset();
1056 InsetMath::doDispatch(cur, cmd);
1062 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1063 // look for macro to open/close, but stay in mathed
1064 for (; !it.empty(); it.pop_back()) {
1066 // go backward through the current cell
1067 Inset * inset = it.nextInset();
1068 while (inset && inset->asInsetMath()) {
1069 MathMacro * macro = inset->asInsetMath()->asMacro();
1071 // found the an macro to open/close?
1072 if (macro->folded() != fold)
1075 // Wrong folding state.
1076 // If this was the first we see in this slice, look further left,
1078 if (inset != it.nextInset())
1082 // go up if this was the left most position
1088 inset = it.nextInset();
1096 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1097 FuncStatus & flag) const
1099 // the font related toggles
1100 //string tc = "mathnormal";
1102 string const arg = to_utf8(cmd.argument());
1103 switch (cmd.action) {
1104 case LFUN_TABULAR_FEATURE:
1105 flag.enabled(false);
1108 case LFUN_TABULAR_FEATURE:
1109 // FIXME: check temporarily disabled
1111 char align = mathcursor::valign();
1112 if (align == '\0') {
1116 if (cmd.argument().empty()) {
1120 if (!contains("tcb", cmd.argument()[0])) {
1124 flag.setOnOff(cmd.argument()[0] == align);
1127 /// We have to handle them since 1.4 blocks all unhandled actions
1128 case LFUN_FONT_ITAL:
1129 case LFUN_FONT_BOLD:
1130 case LFUN_FONT_SANS:
1131 case LFUN_FONT_EMPH:
1132 case LFUN_FONT_TYPEWRITER:
1133 case LFUN_FONT_NOUN:
1134 case LFUN_FONT_ROMAN:
1135 case LFUN_FONT_DEFAULT:
1138 case LFUN_MATH_MUTATE:
1139 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1140 flag.setOnOff(false);
1143 // we just need to be in math mode to enable that
1144 case LFUN_MATH_SIZE:
1145 case LFUN_MATH_SPACE:
1146 case LFUN_MATH_LIMITS:
1147 case LFUN_MATH_EXTERN:
1151 case LFUN_FONT_FRAK:
1152 flag.enabled(currentMode() != TEXT_MODE);
1155 case LFUN_MATH_INSERT: {
1156 bool const textarg =
1157 arg == "\\textbf" || arg == "\\textsf" ||
1158 arg == "\\textrm" || arg == "\\textmd" ||
1159 arg == "\\textit" || arg == "\\textsc" ||
1160 arg == "\\textsl" || arg == "\\textup" ||
1161 arg == "\\texttt" || arg == "\\textbb" ||
1162 arg == "\\textnormal";
1163 flag.enabled(currentMode() != TEXT_MODE || textarg);
1167 case LFUN_MATH_MATRIX:
1168 flag.enabled(currentMode() == MATH_MODE);
1171 case LFUN_INSET_INSERT: {
1172 // Don't test createMathInset_fromDialogStr(), since
1173 // getStatus is not called with a valid reference and the
1174 // dialog would not be applyable.
1175 string const name = cmd.getArg(0);
1176 flag.enabled(name == "ref");
1180 case LFUN_MATH_DELIM:
1181 case LFUN_MATH_BIGDELIM:
1182 // Don't do this with multi-cell selections
1183 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1186 case LFUN_MATH_MACRO_FOLD:
1187 case LFUN_MATH_MACRO_UNFOLD: {
1189 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1190 flag.enabled(found);
1194 case LFUN_SPECIALCHAR_INSERT:
1195 // FIXME: These would probably make sense in math-text mode
1196 flag.enabled(false);
1199 case LFUN_INSET_DISSOLVE:
1200 flag.enabled(!asHullInset());
1211 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1214 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1215 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1216 cur.idx() = enter_front ? 0 : cur.lastidx();
1217 cur.pos() = enter_front ? 0 : cur.lastpos();
1219 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1223 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1226 int dist_min = 1000000;
1227 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1228 int const d = cell(i).dist(cur.bv(), x, y);
1234 MathData & ar = cell(idx_min);
1236 cur.idx() = idx_min;
1237 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1239 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1240 if (dist_min == 0) {
1242 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1243 if (ar[i]->covers(cur.bv(), x, y))
1244 return ar[i].nucleus()->editXY(cur, x, y);
1250 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1252 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1253 BufferView & bv = cur.bv();
1254 bool do_selection = cmd.button() == mouse_button::button1
1255 && cmd.argument() == "region-select";
1256 bv.mouseSetCursor(cur, do_selection);
1257 if (cmd.button() == mouse_button::button1) {
1258 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1259 // Update the cursor update flags as needed:
1261 // Update::Decoration: tells to update the decoration
1262 // (visual box corners that define
1264 // Update::FitCursor: adjust the screen to the cursor
1265 // position if needed
1266 // cur.result().update(): don't overwrite previously set flags.
1267 cur.updateFlags(Update::Decoration | Update::FitCursor
1268 | cur.result().update());
1269 } else if (cmd.button() == mouse_button::button2) {
1270 if (cap::selection()) {
1271 // See comment in Text::dispatch why we do this
1272 cap::copySelectionToStack();
1273 cmd = FuncRequest(LFUN_PASTE, "0");
1274 doDispatch(bv.cursor(), cmd);
1277 asArray(theSelection().get(), ar);
1278 bv.cursor().insert(ar);
1284 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1286 // only select with button 1
1287 if (cmd.button() == mouse_button::button1) {
1288 Cursor & bvcur = cur.bv().cursor();
1289 if (bvcur.anchor_.hasPart(cur)) {
1290 //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1291 bvcur.setCursor(cur);
1292 bvcur.selection() = true;
1293 //lyxerr << "MOTION " << bvcur << endl;
1300 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1302 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1304 if (cmd.button() == mouse_button::button1) {
1305 if (!cur.selection())
1308 Cursor & bvcur = cur.bv().cursor();
1309 bvcur.selection() = true;
1318 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1320 //lyxerr << "interpret 2: '" << c << "'" << endl;
1321 docstring save_selection;
1322 if (c == '^' || c == '_')
1323 save_selection = grabAndEraseSelection(cur);
1328 if (cur.inMacroMode()) {
1329 docstring name = cur.macroName();
1331 /// are we currently typing '#1' or '#2' or...?
1332 if (name == "\\#") {
1335 if (n >= 1 && n <= 9)
1336 cur.insert(new MathMacroArgument(n));
1340 if (isAlphaASCII(c)) {
1341 cur.activeMacro()->setName(name + docstring(1, c));
1345 // handle 'special char' macros
1350 if (currentMode() == InsetMath::TEXT_MODE)
1351 cur.niceInsert(createInsetMath("textbackslash"));
1353 cur.niceInsert(createInsetMath("backslash"));
1354 } else if (c == '{') {
1356 cur.niceInsert(MathAtom(new InsetMathBrace));
1357 } else if (c == '%') {
1359 cur.niceInsert(MathAtom(new InsetMathComment));
1360 } else if (c == '#') {
1361 BOOST_ASSERT(cur.activeMacro());
1362 cur.activeMacro()->setName(name + docstring(1, c));
1365 cur.niceInsert(createInsetMath(docstring(1, c)));
1370 // One character big delimiters. The others are handled in
1371 // interpretString().
1372 latexkeys const * l = in_word_set(name.substr(1));
1373 if (name[0] == '\\' && l && l->inset == "big") {
1377 delim = from_ascii("\\{");
1380 delim = from_ascii("\\}");
1383 delim = docstring(1, c);
1386 if (InsetMathBig::isBigInsetDelim(delim)) {
1387 // name + delim ared a valid InsetMathBig.
1388 // We can't use cur.macroModeClose() because
1389 // it does not handle delim.
1390 InsetMathUnknown * p = cur.activeMacro();
1393 cur.cell().erase(cur.pos());
1394 cur.plainInsert(MathAtom(
1395 new InsetMathBig(name.substr(1), delim)));
1400 // leave macro mode and try again if necessary
1401 cur.macroModeClose();
1403 cur.niceInsert(MathAtom(new InsetMathBrace));
1405 interpretChar(cur, c);
1409 // This is annoying as one has to press <space> far too often.
1413 // leave autocorrect mode if necessary
1414 if (autocorrect() && c == ' ') {
1415 autocorrect() = false;
1420 // just clear selection on pressing the space bar
1421 if (cur.selection() && c == ' ') {
1422 cur.selection() = false;
1429 //lyxerr << "starting with macro" << endl;
1430 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), false)));
1435 if (currentMode() == InsetMath::TEXT_MODE)
1441 if (currentMode() == InsetMath::TEXT_MODE) {
1442 // insert spaces in text mode,
1443 // but suppress direct insertion of two spaces in a row
1444 // the still allows typing '<space>a<space>' and deleting the 'a', but
1445 // it is better than nothing...
1446 if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1448 // FIXME: we have to enable full redraw here because of the
1449 // visual box corners that define the inset. If we know for
1450 // sure that we stay within the same cell we can optimize for
1452 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1456 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1457 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1458 // FIXME: we have to enable full redraw here because of the
1459 // visual box corners that define the inset. If we know for
1460 // sure that we stay within the same cell we can optimize for
1462 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1466 if (cur.popForward()) {
1467 // FIXME: we have to enable full redraw here because of the
1468 // visual box corners that define the inset. If we know for
1469 // sure that we stay within the same cell we can optimize for
1471 //cur.updateFlags(Update::FitCursor);
1475 // if we are at the very end, leave the formula
1476 return cur.pos() != cur.lastpos();
1479 // These shouldn't work in text mode:
1480 if (currentMode() != InsetMath::TEXT_MODE) {
1482 script(cur, false, save_selection);
1486 script(cur, true, save_selection);
1490 cur.niceInsert(createInsetMath("sim"));
1495 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1496 c == '%' || c == '_' || c == '^') {
1497 cur.niceInsert(createInsetMath(docstring(1, c)));
1502 // try auto-correction
1503 //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1506 // no special circumstances, so insert the character without any fuss
1508 cur.autocorrect() = true;
1513 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1515 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1517 if (!cur.empty() && cur.pos() > 0 &&
1518 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1519 if (InsetMathBig::isBigInsetDelim(str)) {
1520 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1521 if (prev[0] == '\\') {
1522 prev = prev.substr(1);
1523 latexkeys const * l = in_word_set(prev);
1524 if (l && l->inset == "big") {
1525 cur.cell()[cur.pos() - 1] =
1526 MathAtom(new InsetMathBig(prev, str));
1536 bool InsetMathNest::script(Cursor & cur, bool up,
1537 docstring const & save_selection)
1539 // Hack to get \^ and \_ working
1540 //lyxerr << "handling script: up: " << up << endl;
1541 if (cur.inMacroMode() && cur.macroName() == "\\") {
1543 cur.niceInsert(createInsetMath("mathcircumflex"));
1545 interpretChar(cur, '_');
1549 cur.macroModeClose();
1550 if (asScriptInset() && cur.idx() == 0) {
1551 // we are in a nucleus of a script inset, move to _our_ script
1552 InsetMathScript * inset = asScriptInset();
1553 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1555 cur.idx() = inset->idxOfScript(up);
1557 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1559 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1562 cur.idx() = inset->idxOfScript(up);
1563 cur.pos() = cur.lastpos();
1565 // convert the thing to our left to a scriptinset or create a new
1566 // one if in the very first position of the array
1567 if (cur.pos() == 0) {
1568 //lyxerr << "new scriptinset" << endl;
1569 cur.insert(new InsetMathScript(up));
1571 //lyxerr << "converting prev atom " << endl;
1572 cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1575 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1576 // See comment in MathParser.cpp for special handling of {}-bases
1582 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1583 cur.niceInsert(save_selection);
1585 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1590 bool InsetMathNest::cursorMathForward(Cursor & cur)
1592 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1593 cur.pushBackward(*cur.nextAtom().nucleus());
1594 cur.inset().idxFirst(cur);
1597 if (cur.posForward() || idxForward(cur) || cur.selection())
1599 // try to pop forwards --- but don't pop out of math! leave that to
1601 int s = cur.depth() - 2;
1602 if (s >= 0 && cur[s].inset().asInsetMath())
1603 return cur.popForward();
1608 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1610 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1612 cur.push(*cur.nextAtom().nucleus());
1613 cur.inset().idxLast(cur);
1616 if (cur.posBackward() || idxBackward(cur) || cur.selection())
1618 // try to pop backwards --- but don't pop out of math! leave that to
1620 int s = cur.depth() - 2;
1621 if (s >= 0 && cur[s].inset().asInsetMath())
1622 return cur.popBackward();