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"
42 #include "DispatchResult.h"
43 #include "FuncRequest.h"
44 #include "FuncStatus.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"
65 using cap::copySelection;
66 using cap::grabAndEraseSelection;
67 using cap::cutSelection;
68 using cap::replaceSelection;
69 using cap::selClearOrDel;
73 using std::istringstream;
76 InsetMathNest::InsetMathNest(idx_type nargs)
77 : cells_(nargs), lock_(false), mouse_hover_(false)
81 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
82 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
87 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
89 cells_ = inset.cells_;
92 InsetMath::operator=(inset);
97 InsetMath::idx_type InsetMathNest::nargs() const
103 void InsetMathNest::cursorPos(BufferView const & bv,
104 CursorSlice const & sl, bool /*boundary*/,
105 int & x, int & y) const
107 // FIXME: This is a hack. Ideally, the coord cache should not store
108 // absolute positions, but relative ones. This would mean to call
109 // setXY() not in MathData::draw(), but in the parent insets' draw()
110 // with the correctly adjusted x,y values. But this means that we'd have
111 // to touch all (math)inset's draw() methods. Right now, we'll store
112 // absolute value, and make them here relative, only to make them
113 // absolute again when actually drawing the cursor. What a mess.
114 BOOST_ASSERT(&sl.inset() == this);
115 MathData const & ar = sl.cell();
116 CoordCache const & coord_cache = bv.coordCache();
117 if (!coord_cache.getArrays().has(&ar)) {
118 // this can (semi-)legally happen if we just created this cell
119 // and it never has been drawn before. So don't ASSERT.
120 //lyxerr << "no cached data for array " << &ar << endl;
125 Point const pt = coord_cache.getArrays().xy(&ar);
126 if (!coord_cache.getInsets().has(this)) {
128 //lyxerr << "no cached data for inset " << this << endl;
133 Point const pt2 = coord_cache.getInsets().xy(this);
134 //lyxerr << "retrieving position cache for MathData "
135 // << pt.x_ << ' ' << pt.y_ << std::endl;
136 x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
138 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
139 // << " asc: " << ascent() << " des: " << descent()
140 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
141 // move cursor visually into empty cells ("blue rectangles");
147 void InsetMathNest::metrics(MetricsInfo const & mi) const
150 for (idx_type i = 0, n = nargs(); i != n; ++i) {
152 cell(i).metrics(m, dim);
157 bool InsetMathNest::idxNext(Cursor & cur) const
159 BOOST_ASSERT(&cur.inset() == this);
160 if (cur.idx() == cur.lastidx())
168 bool InsetMathNest::idxForward(Cursor & cur) const
174 bool InsetMathNest::idxPrev(Cursor & cur) const
176 BOOST_ASSERT(&cur.inset() == this);
180 cur.pos() = cur.lastpos();
185 bool InsetMathNest::idxBackward(Cursor & cur) const
191 bool InsetMathNest::idxFirst(Cursor & cur) const
193 BOOST_ASSERT(&cur.inset() == this);
202 bool InsetMathNest::idxLast(Cursor & cur) const
204 BOOST_ASSERT(&cur.inset() == this);
207 cur.idx() = cur.lastidx();
208 cur.pos() = cur.lastpos();
213 void InsetMathNest::dump() const
215 odocstringstream oss;
217 os << "---------------------------------------------\n";
220 for (idx_type i = 0, n = nargs(); i != n; ++i)
221 os << cell(i) << "\n";
222 os << "---------------------------------------------\n";
223 lyxerr << to_utf8(oss.str());
227 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
231 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
234 setPosCache(pi, x, y);
238 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
240 BufferView & bv = *pi.base.bv;
241 // this should use the x/y values given, not the cached values
242 Cursor & cur = bv.cursor();
243 if (!cur.selection())
245 if (&cur.inset() != this)
248 // FIXME: hack to get position cache warm
249 bool const original_drawing_state = pi.pain.isDrawingEnabled();
250 pi.pain.setDrawingEnabled(false);
252 pi.pain.setDrawingEnabled(original_drawing_state);
254 CursorSlice s1 = cur.selBegin();
255 CursorSlice s2 = cur.selEnd();
257 //lyxerr << "InsetMathNest::drawing selection: "
258 // << " s1: " << s1 << " s2: " << s2 << endl;
259 if (s1.idx() == s2.idx()) {
260 MathData const & c = cell(s1.idx());
261 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
262 int x1 = g.pos.x_ + c.pos2x(s1.pos());
263 int y1 = g.pos.y_ - g.dim.ascent();
264 int x2 = g.pos.x_ + c.pos2x(s2.pos());
265 int y2 = g.pos.y_ + g.dim.descent();
266 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
267 //lyxerr << "InsetMathNest::drawing selection 3: "
268 // << " x1: " << x1 << " x2: " << x2
269 // << " y1: " << y1 << " y2: " << y2 << endl;
271 for (idx_type i = 0; i < nargs(); ++i) {
272 if (idxBetween(i, s1.idx(), s2.idx())) {
273 MathData const & c = cell(i);
274 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
276 int y1 = g.pos.y_ - g.dim.ascent();
277 int x2 = g.pos.x_ + g.dim.width();
278 int y2 = g.pos.y_ + g.dim.descent();
279 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
286 void InsetMathNest::validate(LaTeXFeatures & features) const
288 for (idx_type i = 0; i < nargs(); ++i)
289 cell(i).validate(features);
293 void InsetMathNest::replace(ReplaceData & rep)
295 for (idx_type i = 0; i < nargs(); ++i)
296 cell(i).replace(rep);
300 bool InsetMathNest::contains(MathData const & ar) const
302 for (idx_type i = 0; i < nargs(); ++i)
303 if (cell(i).contains(ar))
309 bool InsetMathNest::lock() const
315 void InsetMathNest::lock(bool l)
321 bool InsetMathNest::isActive() const
327 MathData InsetMathNest::glue() const
330 for (size_t i = 0; i < nargs(); ++i)
336 void InsetMathNest::write(WriteStream & os) const
338 os << '\\' << name().c_str();
339 for (size_t i = 0; i < nargs(); ++i)
340 os << '{' << cell(i) << '}';
342 os.pendingSpace(true);
343 if (lock_ && !os.latex()) {
345 os.pendingSpace(true);
350 void InsetMathNest::normalize(NormalStream & os) const
352 os << '[' << name().c_str();
353 for (size_t i = 0; i < nargs(); ++i)
354 os << ' ' << cell(i);
359 int InsetMathNest::latex(Buffer const &, odocstream & os,
360 OutputParams const & runparams) const
362 WriteStream wi(os, runparams.moving_arg, true);
368 bool InsetMathNest::setMouseHover(bool mouse_hover)
370 mouse_hover_ = mouse_hover;
375 bool InsetMathNest::notifyCursorLeaves(Cursor & /*cur*/)
379 MathData & ar = cur.cell();
380 // remove base-only "scripts"
381 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
382 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
383 if (p && p->nargs() == 1) {
384 MathData ar = p->nuc();
387 cur.adjust(i, ar.size() - 1);
391 // glue adjacent font insets of the same kind
392 for (pos_type i = 0; i + 1 < size(); ++i) {
393 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
394 InsetMathFont const * q = operator[](i + 1)->asFontInset();
395 if (p && q && p->name() == q->name()) {
396 p->cell(0).append(q->cell(0));
406 void InsetMathNest::handleFont
407 (Cursor & cur, docstring const & arg, char const * const font)
409 handleFont(cur, arg, from_ascii(font));
413 void InsetMathNest::handleFont
414 (Cursor & cur, docstring const & arg, docstring const & font)
416 // this whole function is a hack and won't work for incremental font
419 if (cur.inset().asInsetMath()->name() == font) {
420 cur.recordUndoInset();
421 cur.handleFont(to_utf8(font));
424 cur.handleNest(createInsetMath(font));
430 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
435 font.fromString(to_utf8(arg), b);
436 if (font.fontInfo().color() != Color_inherit) {
437 MathAtom at = MathAtom(new InsetMathColor(true, font.fontInfo().color()));
438 cur.handleNest(at, 0);
443 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
445 //lyxerr << "InsetMathNest: request: " << cmd << std::endl;
446 //CursorSlice sl = cur.current();
448 switch (cmd.action) {
452 cur.message(_("Paste"));
453 replaceSelection(cur);
455 if (cmd.argument().empty() && !theClipboard().isInternal())
456 topaste = theClipboard().getAsText();
459 idocstringstream is(cmd.argument());
461 topaste = cap::getSelection(cur.buffer(), n);
463 cur.niceInsert(topaste);
464 cur.clearSelection(); // bug 393
471 cutSelection(cur, true, true);
472 cur.message(_("Cut"));
473 // Prevent stale position >= size crash
474 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
480 cur.message(_("Copy"));
483 case LFUN_MOUSE_PRESS:
484 lfunMousePress(cur, cmd);
487 case LFUN_MOUSE_MOTION:
488 lfunMouseMotion(cur, cmd);
491 case LFUN_MOUSE_RELEASE:
492 lfunMouseRelease(cur, cmd);
495 case LFUN_FINISHED_BACKWARD:
496 cur.bv().cursor() = cur;
499 case LFUN_FINISHED_FORWARD:
501 cur.bv().cursor() = cur;
504 case LFUN_CHAR_FORWARD:
505 cur.updateFlags(Update::Decoration | Update::FitCursor);
506 case LFUN_CHAR_FORWARD_SELECT:
507 cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
508 cur.autocorrect() = false;
510 cur.macroModeClose();
511 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
512 cur.pushBackward(*cur.nextAtom().nucleus());
513 cur.inset().idxFirst(cur);
514 } else if (cur.posForward() || idxForward(cur)
515 || cur.popForward() || cur.selection())
518 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
523 case LFUN_CHAR_BACKWARD:
524 cur.updateFlags(Update::Decoration | Update::FitCursor);
525 case LFUN_CHAR_BACKWARD_SELECT:
526 cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
527 cur.autocorrect() = false;
529 cur.macroModeClose();
530 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
532 cur.push(*cur.nextAtom().nucleus());
533 cur.inset().idxLast(cur);
534 } else if (cur.posBackward() || idxBackward(cur)
535 || cur.popBackward() || cur.selection())
538 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
543 case LFUN_CHAR_RIGHT:
544 case LFUN_CHAR_RIGHT_SELECT:
545 //FIXME: for visual cursor, really move right
546 if (reverseDirectionNeeded(cur))
547 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
548 LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
550 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
551 LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
552 doDispatch(cur, cmd);
556 case LFUN_CHAR_LEFT_SELECT:
557 //FIXME: for visual cursor, really move left
558 if (reverseDirectionNeeded(cur))
559 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
560 LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
562 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
563 LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
564 doDispatch(cur, cmd);
569 cur.updateFlags(Update::Decoration | Update::FitCursor);
570 case LFUN_DOWN_SELECT:
571 case LFUN_UP_SELECT: {
572 // close active macro
573 if (cur.inMacroMode()) {
574 cur.macroModeClose();
578 // stop/start the selection
579 bool select = cmd.action == LFUN_DOWN_SELECT ||
580 cmd.action == LFUN_UP_SELECT;
581 cur.selHandle(select);
584 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
585 bool successful = cur.upDownInMath(up);
587 // notify left insets and give them chance to set update flags
588 lyx::notifyCursorLeaves(cur.beforeDispatchCursor(), cur);
593 if (cur.fixIfBroken())
594 // FIXME: Something bad happened. We pass the corrected Cursor
595 // instead of letting things go worse.
598 // We did not manage to move the cursor.
603 case LFUN_MOUSE_DOUBLE:
604 case LFUN_MOUSE_TRIPLE:
605 case LFUN_WORD_SELECT:
609 cur.selection() = true;
610 cur.pos() = cur.lastpos();
611 cur.idx() = cur.lastidx();
614 case LFUN_PARAGRAPH_UP:
615 case LFUN_PARAGRAPH_DOWN:
616 cur.updateFlags(Update::Decoration | Update::FitCursor);
617 case LFUN_PARAGRAPH_UP_SELECT:
618 case LFUN_PARAGRAPH_DOWN_SELECT:
621 case LFUN_LINE_BEGIN:
622 case LFUN_WORD_BACKWARD:
624 cur.updateFlags(Update::Decoration | Update::FitCursor);
625 case LFUN_LINE_BEGIN_SELECT:
626 case LFUN_WORD_BACKWARD_SELECT:
627 case LFUN_WORD_LEFT_SELECT:
628 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
629 cmd.action == LFUN_WORD_LEFT_SELECT ||
630 cmd.action == LFUN_LINE_BEGIN_SELECT);
631 cur.macroModeClose();
632 if (cur.pos() != 0) {
634 } else if (cur.col() != 0) {
635 cur.idx() -= cur.col();
637 } else if (cur.idx() != 0) {
641 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
646 case LFUN_WORD_FORWARD:
647 case LFUN_WORD_RIGHT:
649 cur.updateFlags(Update::Decoration | Update::FitCursor);
650 case LFUN_WORD_FORWARD_SELECT:
651 case LFUN_WORD_RIGHT_SELECT:
652 case LFUN_LINE_END_SELECT:
653 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
654 cmd.action == LFUN_WORD_RIGHT_SELECT ||
655 cmd.action == LFUN_LINE_END_SELECT);
656 cur.macroModeClose();
658 if (cur.pos() != cur.lastpos()) {
659 cur.pos() = cur.lastpos();
660 } else if (ncols() && (cur.col() != cur.lastcol())) {
661 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
662 cur.pos() = cur.lastpos();
663 } else if (cur.idx() != cur.lastidx()) {
664 cur.idx() = cur.lastidx();
665 cur.pos() = cur.lastpos();
667 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
672 case LFUN_SCREEN_UP_SELECT:
673 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
677 case LFUN_SCREEN_DOWN_SELECT:
678 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
682 case LFUN_CELL_FORWARD:
683 cur.updateFlags(Update::Decoration | Update::FitCursor);
684 cur.inset().idxNext(cur);
687 case LFUN_CELL_BACKWARD:
688 cur.updateFlags(Update::Decoration | Update::FitCursor);
689 cur.inset().idxPrev(cur);
692 case LFUN_WORD_DELETE_BACKWARD:
693 case LFUN_CHAR_DELETE_BACKWARD:
695 // May affect external cell:
696 cur.recordUndoInset();
699 // if the inset can not be removed from within, delete it
700 if (!cur.backspace()) {
701 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
702 cur.innerText()->dispatch(cur, cmd);
706 case LFUN_WORD_DELETE_FORWARD:
707 case LFUN_CHAR_DELETE_FORWARD:
708 if (cur.pos() == cur.lastpos())
709 // May affect external cell:
710 cur.recordUndoInset();
713 // if the inset can not be removed from within, delete it
715 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
716 cur.innerText()->dispatch(cur, cmd);
722 cur.clearSelection();
724 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
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 = support::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);
999 it.nextInset()->asInsetMath()->asMacro()->fold(cur);
1001 it.nextInset()->asInsetMath()->asMacro()->unfold(cur);
1006 case LFUN_QUOTE_INSERT:
1007 // interpret this as if a straight " was typed
1009 interpretChar(cur, '\"');
1012 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1013 // handling such that "self-insert" works on "arbitrary stuff" too, and
1014 // math-insert only handles special math things like "matrix".
1015 case LFUN_MATH_INSERT: {
1017 if (cmd.argument() == "^" || cmd.argument() == "_") {
1018 interpretChar(cur, cmd.argument()[0]);
1020 cur.niceInsert(cmd.argument());
1024 case LFUN_DIALOG_SHOW_NEW_INSET: {
1025 docstring const & name = cmd.argument();
1027 if (name == "ref") {
1028 InsetMathRef tmp(name);
1029 data = tmp.createDialogStr(to_utf8(name));
1031 cur.bv().showDialog(to_utf8(name), data);
1035 case LFUN_INSET_INSERT: {
1037 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1044 case LFUN_INSET_DISSOLVE:
1045 if (!asHullInset()) {
1046 cur.recordUndoInset();
1052 InsetMath::doDispatch(cur, cmd);
1058 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1059 // look for macro to open/close, but stay in mathed
1060 for (; !it.empty(); it.pop_back()) {
1062 // go backward through the current cell
1063 Inset * inset = it.nextInset();
1064 while (inset && inset->asInsetMath()) {
1065 MathMacro * macro = inset->asInsetMath()->asMacro();
1067 // found the an macro to open/close?
1068 if (macro->folded() != fold)
1071 // Wrong folding state.
1072 // If this was the first we see in this slice, look further left,
1074 if (inset != it.nextInset())
1078 // go up if this was the left most position
1084 inset = it.nextInset();
1092 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1093 FuncStatus & flag) const
1095 // the font related toggles
1096 //string tc = "mathnormal";
1098 string const arg = to_utf8(cmd.argument());
1099 switch (cmd.action) {
1100 case LFUN_TABULAR_FEATURE:
1101 flag.enabled(false);
1104 case LFUN_TABULAR_FEATURE:
1105 // FIXME: check temporarily disabled
1107 char align = mathcursor::valign();
1108 if (align == '\0') {
1112 if (cmd.argument().empty()) {
1116 if (!contains("tcb", cmd.argument()[0])) {
1120 flag.setOnOff(cmd.argument()[0] == align);
1123 /// We have to handle them since 1.4 blocks all unhandled actions
1124 case LFUN_FONT_ITAL:
1125 case LFUN_FONT_BOLD:
1126 case LFUN_FONT_SANS:
1127 case LFUN_FONT_EMPH:
1128 case LFUN_FONT_TYPEWRITER:
1129 case LFUN_FONT_NOUN:
1130 case LFUN_FONT_ROMAN:
1131 case LFUN_FONT_DEFAULT:
1134 case LFUN_MATH_MUTATE:
1135 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1136 flag.setOnOff(false);
1139 // we just need to be in math mode to enable that
1140 case LFUN_MATH_SIZE:
1141 case LFUN_MATH_SPACE:
1142 case LFUN_MATH_LIMITS:
1143 case LFUN_MATH_NONUMBER:
1144 case LFUN_MATH_NUMBER:
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_HYPHENATION_POINT_INSERT:
1193 case LFUN_LIGATURE_BREAK_INSERT:
1194 case LFUN_MENU_SEPARATOR_INSERT:
1195 case LFUN_DOTS_INSERT:
1196 case LFUN_END_OF_SENTENCE_PERIOD_INSERT:
1197 // FIXME: These would probably make sense in math-text mode
1198 flag.enabled(false);
1201 case LFUN_INSET_DISSOLVE:
1202 flag.enabled(!asHullInset());
1213 void InsetMathNest::edit(Cursor & cur, bool left)
1216 cur.idx() = left ? 0 : cur.lastidx();
1217 cur.pos() = left ? 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(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;