2 * \file InsetMathNest.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathNest.h"
15 #include "InsetMathArray.h"
16 #include "InsetMathAMSArray.h"
17 #include "InsetMathBig.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathBrace.h"
20 #include "InsetMathChar.h"
21 #include "InsetMathColor.h"
22 #include "InsetMathComment.h"
23 #include "InsetMathDelim.h"
24 #include "InsetMathEnsureMath.h"
25 #include "InsetMathHull.h"
26 #include "InsetMathRef.h"
27 #include "InsetMathScript.h"
28 #include "InsetMathSpace.h"
29 #include "InsetMathSymbol.h"
30 #include "InsetMathUnknown.h"
31 #include "MathAutoCorrect.h"
32 #include "MathCompletionList.h"
34 #include "MathFactory.h"
35 #include "MathMacro.h"
36 #include "MathMacroArgument.h"
37 #include "MathParser.h"
38 #include "MathStream.h"
39 #include "MathSupport.h"
42 #include "BufferParams.h"
43 #include "BufferView.h"
44 #include "CoordCache.h"
46 #include "CutAndPaste.h"
47 #include "DispatchResult.h"
49 #include "FuncRequest.h"
50 #include "FuncStatus.h"
51 #include "LaTeXFeatures.h"
54 #include "MetricsInfo.h"
55 #include "OutputParams.h"
59 #include "frontends/Application.h"
60 #include "frontends/Clipboard.h"
61 #include "frontends/Painter.h"
62 #include "frontends/Selection.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
75 using namespace lyx::support;
79 using cap::copySelection;
80 using cap::grabAndEraseSelection;
81 using cap::cutSelection;
82 using cap::replaceSelection;
83 using cap::selClearOrDel;
86 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
87 : InsetMath(buf), cells_(nargs), lock_(false)
93 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
94 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
98 InsetMathNest::~InsetMathNest()
100 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
101 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
102 for (; it != end; ++it)
104 it->first->clearLastInset(this);
108 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
110 cells_ = inset.cells_;
112 mouse_hover_.clear();
113 InsetMath::operator=(inset);
118 void InsetMathNest::setBuffer(Buffer & buffer)
120 InsetMath::setBuffer(buffer);
121 for (idx_type i = 0, n = nargs(); i != n; ++i) {
122 MathData & data = cell(i);
123 for (size_t j = 0; j != data.size(); ++j)
124 data[j].nucleus()->setBuffer(buffer);
129 InsetMath::idx_type InsetMathNest::nargs() const
131 return cells_.size();
135 void InsetMathNest::cursorPos(BufferView const & bv,
136 CursorSlice const & sl, bool /*boundary*/,
137 int & x, int & y) const
139 // FIXME: This is a hack. Ideally, the coord cache should not store
140 // absolute positions, but relative ones. This would mean to call
141 // setXY() not in MathData::draw(), but in the parent insets' draw()
142 // with the correctly adjusted x,y values. But this means that we'd have
143 // to touch all (math)inset's draw() methods. Right now, we'll store
144 // absolute value, and make them here relative, only to make them
145 // absolute again when actually drawing the cursor. What a mess.
146 LASSERT(&sl.inset() == this, return);
147 MathData const & ar = sl.cell();
148 CoordCache const & coord_cache = bv.coordCache();
149 if (!coord_cache.getArrays().has(&ar)) {
150 // this can (semi-)legally happen if we just created this cell
151 // and it never has been drawn before. So don't ASSERT.
152 //lyxerr << "no cached data for array " << &ar << endl;
157 Point const pt = coord_cache.getArrays().xy(&ar);
158 if (!coord_cache.getInsets().has(this)) {
160 //lyxerr << "no cached data for inset " << this << endl;
165 Point const pt2 = coord_cache.getInsets().xy(this);
166 //lyxerr << "retrieving position cache for MathData "
167 // << pt.x_ << ' ' << pt.y_ << endl;
168 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
170 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
171 // << " asc: " << ascent() << " des: " << descent()
172 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
173 // move cursor visually into empty cells ("blue rectangles");
179 void InsetMathNest::metrics(MetricsInfo const & mi) const
182 for (idx_type i = 0, n = nargs(); i != n; ++i) {
184 cell(i).metrics(m, dim);
189 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
191 for (idx_type i = 0, n = nargs(); i != n; ++i)
192 cell(i).updateBuffer(it, utype);
197 bool InsetMathNest::idxNext(Cursor & cur) const
199 LASSERT(&cur.inset() == this, return false);
200 if (cur.idx() == cur.lastidx())
208 bool InsetMathNest::idxForward(Cursor & cur) const
214 bool InsetMathNest::idxPrev(Cursor & cur) const
216 LASSERT(&cur.inset() == this, return false);
220 cur.pos() = cur.lastpos();
225 bool InsetMathNest::idxBackward(Cursor & cur) const
231 bool InsetMathNest::idxFirst(Cursor & cur) const
233 LASSERT(&cur.inset() == this, return false);
242 bool InsetMathNest::idxLast(Cursor & cur) const
244 LASSERT(&cur.inset() == this, return false);
247 cur.idx() = cur.lastidx();
248 cur.pos() = cur.lastpos();
253 void InsetMathNest::dump() const
255 odocstringstream oss;
256 otexrowstream ots(oss);
258 os << "---------------------------------------------\n";
261 for (idx_type i = 0, n = nargs(); i != n; ++i)
262 os << cell(i) << "\n";
263 os << "---------------------------------------------\n";
264 lyxerr << to_utf8(oss.str());
268 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
272 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
275 setPosCache(pi, x, y);
279 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
281 BufferView & bv = *pi.base.bv;
282 // this should use the x/y values given, not the cached values
283 Cursor & cur = bv.cursor();
284 if (!cur.selection())
286 if (&cur.inset() != this)
289 // FIXME: hack to get position cache warm
290 bool const original_drawing_state = pi.pain.isDrawingEnabled();
291 pi.pain.setDrawingEnabled(false);
293 pi.pain.setDrawingEnabled(original_drawing_state);
295 CursorSlice s1 = cur.selBegin();
296 CursorSlice s2 = cur.selEnd();
298 //lyxerr << "InsetMathNest::drawing selection: "
299 // << " s1: " << s1 << " s2: " << s2 << endl;
300 if (s1.idx() == s2.idx()) {
301 MathData const & c = cell(s1.idx());
302 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
303 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
304 int y1 = g.pos.y_ - g.dim.ascent();
305 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
306 int y2 = g.pos.y_ + g.dim.descent();
307 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
308 //lyxerr << "InsetMathNest::drawing selection 3: "
309 // << " x1: " << x1 << " x2: " << x2
310 // << " y1: " << y1 << " y2: " << y2 << endl;
312 for (idx_type i = 0; i < nargs(); ++i) {
313 if (idxBetween(i, s1.idx(), s2.idx())) {
314 MathData const & c = cell(i);
315 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
317 int y1 = g.pos.y_ - g.dim.ascent();
318 int x2 = g.pos.x_ + g.dim.width();
319 int y2 = g.pos.y_ + g.dim.descent();
320 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
327 void InsetMathNest::validate(LaTeXFeatures & features) const
329 for (idx_type i = 0; i < nargs(); ++i)
330 cell(i).validate(features);
334 void InsetMathNest::replace(ReplaceData & rep)
336 for (idx_type i = 0; i < nargs(); ++i)
337 cell(i).replace(rep);
341 bool InsetMathNest::contains(MathData const & ar) const
343 for (idx_type i = 0; i < nargs(); ++i)
344 if (cell(i).contains(ar))
350 bool InsetMathNest::lock() const
356 void InsetMathNest::lock(bool l)
362 bool InsetMathNest::isActive() const
368 MathData InsetMathNest::glue() const
371 for (size_t i = 0; i < nargs(); ++i)
377 void InsetMathNest::write(WriteStream & os) const
379 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
380 ModeSpecifier specifier(os, currentMode(), lockedMode());
381 docstring const latex_name = name();
382 os << '\\' << latex_name;
383 for (size_t i = 0; i < nargs(); ++i) {
384 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
385 os << '{' << cell(i) << '}';
388 os.pendingSpace(true);
389 if (lock_ && !os.latex()) {
391 os.pendingSpace(true);
396 void InsetMathNest::normalize(NormalStream & os) const
399 for (size_t i = 0; i < nargs(); ++i)
400 os << ' ' << cell(i);
405 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
407 WriteStream wi(os, runparams.moving_arg, true,
408 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
410 wi.strikeoutMath(runparams.inDeletedInset
411 && (!LaTeXFeatures::isAvailable("dvipost")
412 || (runparams.flavor != OutputParams::LATEX
413 && runparams.flavor != OutputParams::DVILUATEX)));
414 if (runparams.inulemcmd) {
415 wi.ulemCmd(WriteStream::UNDERLINE);
416 if (runparams.local_font) {
417 FontInfo f = runparams.local_font->fontInfo();
418 if (f.strikeout() == FONT_ON)
419 wi.ulemCmd(WriteStream::STRIKEOUT);
422 wi.canBreakLine(os.canBreakLine());
423 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
426 // Reset parbreak status after a math inset.
428 os.canBreakLine(wi.canBreakLine());
432 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
435 mouse_hover_[bv] = mouse_hover;
440 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
444 MathData & ar = cur.cell();
445 // remove base-only "scripts"
446 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
447 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
448 if (p && p->nargs() == 1) {
449 MathData ar = p->nuc();
452 cur.adjust(i, ar.size() - 1);
456 // glue adjacent font insets of the same kind
457 for (pos_type i = 0; i + 1 < size(); ++i) {
458 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
459 InsetMathFont const * q = operator[](i + 1)->asFontInset();
460 if (p && q && p->name() == q->name()) {
461 p->cell(0).append(q->cell(0));
471 void InsetMathNest::handleFont
472 (Cursor & cur, docstring const & arg, char const * const font)
474 handleFont(cur, arg, from_ascii(font));
478 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
479 docstring const & font)
481 cur.recordUndoSelection();
483 // this whole function is a hack and won't work for incremental font
485 if (cur.inset().asInsetMath()->name() == font)
486 cur.handleFont(to_utf8(font));
488 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
492 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
494 handleNest(cur, nest, docstring());
498 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
499 docstring const & arg)
501 CursorSlice i1 = cur.selBegin();
502 CursorSlice i2 = cur.selEnd();
503 if (!i1.inset().asInsetMath())
505 if (i1.idx() == i2.idx()) {
506 // the easy case where only one cell is selected
507 cur.handleNest(nest);
512 // multiple selected cells in a simple non-grid inset
513 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
514 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
519 cur.pos() = cur.lastpos();
522 // change font of cell
523 cur.handleNest(nest);
526 // cur is in the font inset now. If the loop continues,
527 // we need to get outside again for the next cell
528 if (i + 1 <= i2.idx())
534 // the complicated case with multiple selected cells in a grid
537 cap::region(i1, i2, r1, r2, c1, c2);
538 for (row_type row = r1; row <= r2; ++row) {
539 for (col_type col = c1; col <= c2; ++col) {
541 cur.idx() = i1.asInsetMath()->index(row, col);
544 cur.pos() = cur.lastpos();
548 cur.handleNest(nest);
551 // cur is in the font inset now. If the loop continues,
552 // we need to get outside again for the next cell
553 if (col + 1 <= c2 || row + 1 <= r2)
560 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
562 cur.recordUndoSelection();
565 font.fromString(to_utf8(arg), b);
566 if (font.fontInfo().color() != Color_inherit &&
567 font.fontInfo().color() != Color_ignore)
568 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
570 // FIXME: support other font changes here as well?
574 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
576 //LYXERR0("InsetMathNest: request: " << cmd);
578 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
580 FuncCode const act = cmd.action();
583 case LFUN_CLIPBOARD_PASTE:
584 parseflg |= Parse::VERBATIM;
587 if (cur.currentMode() <= TEXT_MODE)
588 parseflg |= Parse::TEXTMODE;
589 cur.recordUndoSelection();
590 cur.message(_("Paste"));
591 replaceSelection(cur);
593 if (cmd.argument().empty() && !theClipboard().isInternal())
594 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
597 idocstringstream is(cmd.argument());
599 topaste = cap::selection(n, buffer().params().documentClassPtr());
601 cur.niceInsert(topaste, parseflg, false);
602 cur.clearSelection(); // bug 393
603 cur.forceBufferUpdate();
610 cutSelection(cur, true, true);
611 cur.message(_("Cut"));
612 // Prevent stale position >= size crash
613 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
615 cur.forceBufferUpdate();
620 cur.message(_("Copy"));
623 case LFUN_MOUSE_PRESS:
624 lfunMousePress(cur, cmd);
627 case LFUN_MOUSE_MOTION:
628 lfunMouseMotion(cur, cmd);
631 case LFUN_MOUSE_RELEASE:
632 lfunMouseRelease(cur, cmd);
635 case LFUN_FINISHED_LEFT: // in math, left is backwards
636 case LFUN_FINISHED_BACKWARD:
637 cur.bv().cursor() = cur;
640 case LFUN_FINISHED_RIGHT: // in math, right is forward
641 case LFUN_FINISHED_FORWARD:
643 cur.bv().cursor() = cur;
646 case LFUN_CHAR_RIGHT:
648 case LFUN_CHAR_BACKWARD:
649 case LFUN_CHAR_FORWARD:
650 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
652 case LFUN_CHAR_RIGHT_SELECT:
653 case LFUN_CHAR_LEFT_SELECT:
654 case LFUN_CHAR_BACKWARD_SELECT:
655 case LFUN_CHAR_FORWARD_SELECT: {
656 // are we in a selection?
657 bool select = (act == LFUN_CHAR_RIGHT_SELECT
658 || act == LFUN_CHAR_LEFT_SELECT
659 || act == LFUN_CHAR_BACKWARD_SELECT
660 || act == LFUN_CHAR_FORWARD_SELECT);
661 // are we moving forward or backwards?
662 // If the command was RIGHT or LEFT, then whether we're moving forward
663 // or backwards depends on the cursor movement mode (logical or visual):
664 // * in visual mode, since math is always LTR, right -> forward,
666 // * in logical mode, the mapping is determined by the
667 // reverseDirectionNeeded() function
670 FuncCode finish_lfun;
672 if (act == LFUN_CHAR_FORWARD
673 || act == LFUN_CHAR_FORWARD_SELECT) {
675 finish_lfun = LFUN_FINISHED_FORWARD;
677 else if (act == LFUN_CHAR_BACKWARD
678 || act == LFUN_CHAR_BACKWARD_SELECT) {
680 finish_lfun = LFUN_FINISHED_BACKWARD;
683 bool right = (act == LFUN_CHAR_RIGHT_SELECT
684 || act == LFUN_CHAR_RIGHT);
685 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
691 finish_lfun = LFUN_FINISHED_RIGHT;
693 finish_lfun = LFUN_FINISHED_LEFT;
695 // Now that we know exactly what we want to do, let's do it!
696 cur.selHandle(select);
698 cur.macroModeClose();
699 // try moving forward or backwards as necessary...
700 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
701 // ... and if movement failed, then finish forward or backwards
703 cmd = FuncRequest(finish_lfun);
711 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
713 case LFUN_DOWN_SELECT:
714 case LFUN_UP_SELECT: {
715 // close active macro
716 if (cur.inMacroMode()) {
717 cur.macroModeClose();
721 // stop/start the selection
722 bool select = act == LFUN_DOWN_SELECT ||
723 act == LFUN_UP_SELECT;
724 cur.selHandle(select);
726 // handle autocorrect:
727 if (lyxrc.autocorrection_math && cur.autocorrect()) {
728 cur.autocorrect() = false;
729 cur.message(_("Autocorrect Off ('!' to enter)"));
733 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
734 bool successful = cur.upDownInMath(up);
738 if (cur.fixIfBroken())
739 // FIXME: Something bad happened. We pass the corrected Cursor
740 // instead of letting things go worse.
743 // We did not manage to move the cursor.
748 case LFUN_MOUSE_DOUBLE:
749 case LFUN_WORD_SELECT:
753 cur.pos() = cur.lastpos();
754 cur.bv().cursor() = cur;
757 case LFUN_MOUSE_TRIPLE:
762 cur.idx() = cur.lastidx();
763 cur.pos() = cur.lastpos();
764 cur.bv().cursor() = cur;
767 case LFUN_PARAGRAPH_UP:
768 case LFUN_PARAGRAPH_DOWN:
769 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
771 case LFUN_PARAGRAPH_UP_SELECT:
772 case LFUN_PARAGRAPH_DOWN_SELECT:
775 case LFUN_LINE_BEGIN:
776 case LFUN_WORD_BACKWARD:
778 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
780 case LFUN_LINE_BEGIN_SELECT:
781 case LFUN_WORD_BACKWARD_SELECT:
782 case LFUN_WORD_LEFT_SELECT:
783 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
784 act == LFUN_WORD_LEFT_SELECT ||
785 act == LFUN_LINE_BEGIN_SELECT);
786 cur.macroModeClose();
787 if (cur.pos() != 0) {
789 } else if (cur.col() != 0) {
790 cur.idx() -= cur.col();
792 } else if (cur.idx() != 0) {
796 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
801 case LFUN_WORD_FORWARD:
802 case LFUN_WORD_RIGHT:
804 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
806 case LFUN_WORD_FORWARD_SELECT:
807 case LFUN_WORD_RIGHT_SELECT:
808 case LFUN_LINE_END_SELECT:
809 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
810 act == LFUN_WORD_RIGHT_SELECT ||
811 act == LFUN_LINE_END_SELECT);
812 cur.macroModeClose();
814 if (cur.pos() != cur.lastpos()) {
815 cur.pos() = cur.lastpos();
816 } else if (ncols() && (cur.col() != cur.lastcol())) {
817 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
818 cur.pos() = cur.lastpos();
819 } else if (cur.idx() != cur.lastidx()) {
820 cur.idx() = cur.lastidx();
821 cur.pos() = cur.lastpos();
823 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
828 case LFUN_CELL_FORWARD:
829 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
830 cur.inset().idxNext(cur);
833 case LFUN_CELL_BACKWARD:
834 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
835 cur.inset().idxPrev(cur);
838 case LFUN_WORD_DELETE_BACKWARD:
839 case LFUN_CHAR_DELETE_BACKWARD:
841 // May affect external cell:
842 cur.recordUndoInset();
843 else if (!cur.inMacroMode())
844 cur.recordUndoSelection();
845 // if the inset can not be removed from within, delete it
846 if (!cur.backspace()) {
847 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
848 cur.innerText()->dispatch(cur, cmd);
852 case LFUN_WORD_DELETE_FORWARD:
853 case LFUN_CHAR_DELETE_FORWARD:
854 if (cur.pos() == cur.lastpos())
855 // May affect external cell:
856 cur.recordUndoInset();
858 cur.recordUndoSelection();
859 // if the inset can not be removed from within, delete it
861 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
862 cur.innerText()->dispatch(cur, cmd);
868 cur.clearSelection();
870 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
875 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
876 // that is traversed by a single <CursorLeft>/<CursorRight>.
877 case LFUN_INSET_TOGGLE:
883 case LFUN_SELF_INSERT:
884 if (cmd.argument().size() != 1) {
885 cur.recordUndoSelection();
886 docstring const arg = cmd.argument();
887 if (!interpretString(cur, arg))
891 // Don't record undo steps if we are in macro mode and thus
892 // cmd.argument is the next character of the macro name.
893 // Otherwise we'll get an invalid cursor if we undo after
894 // the macro was finished and the macro is a known command,
895 // e.g. sqrt. Cursor::macroModeClose replaces in this case
896 // the InsetMathUnknown with name "frac" by an empty
897 // InsetMathFrac -> a pos value > 0 is invalid.
898 // A side effect is that an undo before the macro is finished
899 // undoes the complete macro, not only the last character.
900 // At the time we hit '\' we are not in macro mode, still.
901 if (!cur.inMacroMode())
902 cur.recordUndoSelection();
904 // spacial handling of space. If we insert an inset
905 // via macro mode, we want to put the cursor inside it
906 // if relevant. Think typing "\frac<space>".
907 if (cmd.argument()[0] == ' '
908 && cur.inMacroMode() && cur.macroName() != "\\"
909 && cur.macroModeClose() && cur.pos() > 0) {
910 MathAtom const atom = cur.prevAtom();
911 if (atom->asNestInset() && atom->isActive()) {
913 cur.pushBackward(*cur.nextInset());
915 } else if (!interpretChar(cur, cmd.argument()[0])) {
916 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
921 //case LFUN_SERVER_GET_XY:
924 case LFUN_SERVER_SET_XY: {
925 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
928 istringstream is(to_utf8(cmd.argument()));
930 cur.setScreenPos(x, y);
934 // Special casing for superscript in case of LyX handling
936 case LFUN_ACCENT_CIRCUMFLEX:
937 if (cmd.argument().empty()) {
938 // do superscript if LyX handles
940 cur.recordUndoSelection();
941 script(cur, true, grabAndEraseSelection(cur));
945 case LFUN_ACCENT_UMLAUT:
946 case LFUN_ACCENT_ACUTE:
947 case LFUN_ACCENT_GRAVE:
948 case LFUN_ACCENT_BREVE:
949 case LFUN_ACCENT_DOT:
950 case LFUN_ACCENT_MACRON:
951 case LFUN_ACCENT_CARON:
952 case LFUN_ACCENT_TILDE:
953 case LFUN_ACCENT_CEDILLA:
954 case LFUN_ACCENT_CIRCLE:
955 case LFUN_ACCENT_UNDERDOT:
956 case LFUN_ACCENT_TIE:
957 case LFUN_ACCENT_OGONEK:
958 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
962 case LFUN_TEXTSTYLE_APPLY:
963 case LFUN_TEXTSTYLE_UPDATE:
964 handleFont2(cur, cmd.argument());
968 if (currentMode() <= TEXT_MODE)
969 handleFont(cur, cmd.argument(), "textbf");
971 handleFont(cur, cmd.argument(), "mathbf");
973 case LFUN_FONT_BOLDSYMBOL:
974 if (currentMode() <= TEXT_MODE)
975 handleFont(cur, cmd.argument(), "textbf");
977 handleFont(cur, cmd.argument(), "boldsymbol");
980 if (currentMode() <= TEXT_MODE)
981 handleFont(cur, cmd.argument(), "textsf");
983 handleFont(cur, cmd.argument(), "mathsf");
986 if (currentMode() <= TEXT_MODE)
987 handleFont(cur, cmd.argument(), "emph");
989 handleFont(cur, cmd.argument(), "mathcal");
991 case LFUN_FONT_ROMAN:
992 if (currentMode() <= TEXT_MODE)
993 handleFont(cur, cmd.argument(), "textrm");
995 handleFont(cur, cmd.argument(), "mathrm");
997 case LFUN_FONT_TYPEWRITER:
998 if (currentMode() <= TEXT_MODE)
999 handleFont(cur, cmd.argument(), "texttt");
1001 handleFont(cur, cmd.argument(), "mathtt");
1003 case LFUN_FONT_FRAK:
1004 handleFont(cur, cmd.argument(), "mathfrak");
1006 case LFUN_FONT_ITAL:
1007 if (currentMode() <= TEXT_MODE)
1008 handleFont(cur, cmd.argument(), "textit");
1010 handleFont(cur, cmd.argument(), "mathit");
1012 case LFUN_FONT_NOUN:
1013 if (currentMode() <= TEXT_MODE)
1014 // FIXME: should be "noun"
1015 handleFont(cur, cmd.argument(), "textsc");
1017 handleFont(cur, cmd.argument(), "mathbb");
1019 case LFUN_FONT_DEFAULT:
1020 handleFont(cur, cmd.argument(), "textnormal");
1022 case LFUN_FONT_UNDERLINE:
1024 cur.handleNest(createInsetMath("underline", cur.buffer()));
1027 case LFUN_MATH_MODE: {
1029 // ignore math-mode on when already in math mode
1030 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1032 cur.recordUndoSelection();
1033 cur.macroModeClose();
1034 docstring const save_selection = grabAndEraseSelection(cur);
1036 if (currentMode() <= Inset::TEXT_MODE)
1037 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1039 cur.plainInsert(createInsetMath("text", buffer_));
1041 cur.pushBackward(*cur.nextInset());
1042 cur.niceInsert(save_selection);
1043 cur.forceBufferUpdate();
1045 if (currentMode() == Inset::TEXT_MODE) {
1046 cur.recordUndoSelection();
1047 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1048 cur.message(_("create new math text environment ($...$)"));
1050 handleFont(cur, cmd.argument(), "textrm");
1051 cur.message(_("entered math text mode (textrm)"));
1057 case LFUN_REGEXP_MODE: {
1058 InsetMath * im = cur.inset().asInsetMath();
1060 InsetMathHull * i = im->asHullInset();
1061 if (i && i->getType() == hullRegexp) {
1062 cur.message(_("Already in regular expression mode"));
1066 cur.macroModeClose();
1067 docstring const save_selection = grabAndEraseSelection(cur);
1069 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1071 cur.pushBackward(*cur.nextInset());
1072 cur.niceInsert(save_selection);
1073 cur.message(_("Regular expression editor mode"));
1077 case LFUN_MATH_FONT_STYLE: {
1078 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1079 doDispatch(cur, fr);
1083 case LFUN_MATH_SIZE: {
1084 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1085 doDispatch(cur, fr);
1089 case LFUN_MATH_MATRIX: {
1095 idocstringstream is(cmd.argument());
1096 is >> m >> n >> v_align >> h_align;
1102 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1103 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1107 case LFUN_MATH_AMS_MATRIX: {
1111 docstring name = from_ascii("matrix");
1112 idocstringstream is(cmd.argument());
1113 is >> m >> n >> name;
1118 // check if we have a valid decoration
1119 if (name != "pmatrix" && name != "bmatrix"
1120 && name != "Bmatrix" && name != "vmatrix"
1121 && name != "Vmatrix" && name != "matrix")
1122 name = from_ascii("matrix");
1125 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1129 case LFUN_MATH_DELIM: {
1131 docstring rs = split(cmd.argument(), ls, ' ');
1132 // Reasonable default values
1138 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1142 case LFUN_MATH_BIGDELIM: {
1143 docstring const lname = from_utf8(cmd.getArg(0));
1144 docstring const ldelim = from_utf8(cmd.getArg(1));
1145 docstring const rname = from_utf8(cmd.getArg(2));
1146 docstring const rdelim = from_utf8(cmd.getArg(3));
1147 latexkeys const * l = in_word_set(lname);
1148 bool const have_l = l && l->inset == "big" &&
1149 InsetMathBig::isBigInsetDelim(ldelim);
1150 l = in_word_set(rname);
1151 bool const have_r = l && l->inset == "big" &&
1152 InsetMathBig::isBigInsetDelim(rdelim);
1153 // We mimic LFUN_MATH_DELIM in case we have an empty left
1154 // or right delimiter.
1155 if (have_l || have_r) {
1157 docstring const selection = grabAndEraseSelection(cur);
1160 cur.insert(MathAtom(new InsetMathBig(lname,
1162 // first insert the right delimiter and then go back
1163 // and re-insert the selection (bug 7088)
1165 cur.insert(MathAtom(new InsetMathBig(rname,
1169 cur.niceInsert(selection);
1171 // Don't call cur.undispatched() if we did nothing, this would
1172 // lead to infinite recursion via Text::dispatch().
1176 case LFUN_SPACE_INSERT: {
1177 cur.recordUndoSelection();
1178 string const name = cmd.getArg(0);
1179 if (name == "normal")
1180 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1181 else if (name == "protected")
1182 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1183 else if (name == "thin" || name == "med" || name == "thick")
1184 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1185 else if (name == "hfill*")
1186 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1187 else if (name == "quad" || name == "qquad" ||
1188 name == "enspace" || name == "enskip" ||
1189 name == "negthinspace" || name == "negmedspace" ||
1190 name == "negthickspace" || name == "hfill")
1191 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1192 else if (name == "hspace" || name == "hspace*") {
1193 string const len = cmd.getArg(1);
1194 if (len.empty() || !isValidLength(len)) {
1195 lyxerr << "LyX function 'space-insert " << name << "' "
1196 "needs a valid length argument." << endl;
1199 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1201 cur.insert(MathAtom(new InsetMathSpace));
1205 case LFUN_MATH_SPACE:
1206 cur.recordUndoSelection();
1207 if (cmd.argument().empty())
1208 cur.insert(MathAtom(new InsetMathSpace));
1210 string const name = cmd.getArg(0);
1211 string const len = cmd.getArg(1);
1212 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1216 case LFUN_ERT_INSERT:
1217 // interpret this as if a backslash was typed
1219 interpretChar(cur, '\\');
1222 case LFUN_MATH_SUBSCRIPT:
1223 // interpret this as if a _ was typed
1224 cur.recordUndoSelection();
1225 interpretChar(cur, '_');
1228 case LFUN_MATH_SUPERSCRIPT:
1229 // interpret this as if a ^ was typed
1230 cur.recordUndoSelection();
1231 interpretChar(cur, '^');
1234 case LFUN_MATH_MACRO_FOLD:
1235 case LFUN_MATH_MACRO_UNFOLD: {
1237 bool fold = act == LFUN_MATH_MACRO_FOLD;
1238 bool found = findMacroToFoldUnfold(it, fold);
1240 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1241 cur.recordUndoInset();
1250 case LFUN_QUOTE_INSERT:
1251 // interpret this as if a straight " was typed
1252 cur.recordUndoSelection();
1253 interpretChar(cur, '\"');
1256 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1257 // handling such that "self-insert" works on "arbitrary stuff" too, and
1258 // math-insert only handles special math things like "matrix".
1259 case LFUN_MATH_INSERT: {
1260 cur.recordUndoSelection();
1261 if (cmd.argument() == "^" || cmd.argument() == "_")
1262 interpretChar(cur, cmd.argument()[0]);
1265 asArray(cmd.argument(), ar);
1266 if (cur.selection() && ar.size() == 1
1267 && ar[0]->asNestInset()
1268 && ar[0]->asNestInset()->nargs() > 1)
1269 handleNest(cur, ar[0]);
1271 cur.niceInsert(cmd.argument());
1276 case LFUN_UNICODE_INSERT: {
1277 if (cmd.argument().empty())
1279 docstring hexstring = cmd.argument();
1280 if (isHex(hexstring)) {
1281 char_type c = hexToInt(hexstring);
1282 if (c >= 32 && c < 0x10ffff) {
1283 docstring s = docstring(1, c);
1284 FuncCode code = currentMode() == MATH_MODE ?
1285 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1286 lyx::dispatch(FuncRequest(code, s));
1292 case LFUN_DIALOG_SHOW_NEW_INSET: {
1293 docstring const & name = cmd.argument();
1295 if (name == "ref") {
1296 InsetMathRef tmp(buffer_, name);
1297 data = tmp.createDialogStr();
1298 cur.bv().showDialog(to_utf8(name), data);
1299 } else if (name == "mathspace") {
1300 cur.bv().showDialog(to_utf8(name));
1305 case LFUN_INSET_INSERT: {
1307 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1308 cur.recordUndoSelection();
1310 cur.forceBufferUpdate();
1315 case LFUN_INSET_DISSOLVE:
1316 if (!asHullInset()) {
1317 cur.recordUndoInset();
1323 InsetMath::doDispatch(cur, cmd);
1329 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1330 // look for macro to open/close, but stay in mathed
1331 for (; !it.empty(); it.pop_back()) {
1333 // go backward through the current cell
1334 Inset * inset = it.nextInset();
1335 while (inset && inset->asInsetMath()) {
1336 MathMacro * macro = inset->asInsetMath()->asMacro();
1338 // found the an macro to open/close?
1339 if (macro->folded() != fold)
1342 // Wrong folding state.
1343 // If this was the first we see in this slice, look further left,
1345 if (inset != it.nextInset())
1349 // go up if this was the left most position
1355 inset = it.nextInset();
1363 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1364 FuncStatus & flag) const
1366 // the font related toggles
1367 //string tc = "mathnormal";
1369 string const arg = to_utf8(cmd.argument());
1370 switch (cmd.action()) {
1371 case LFUN_INSET_MODIFY:
1372 flag.setEnabled(false);
1375 case LFUN_INSET_MODIFY:
1376 // FIXME: check temporarily disabled
1378 char align = mathcursor::valign();
1379 if (align == '\0') {
1383 if (cmd.argument().empty()) {
1387 if (!contains("tcb", cmd.argument()[0])) {
1391 flag.setOnOff(cmd.argument()[0] == align);
1394 /// We have to handle them since 1.4 blocks all unhandled actions
1395 case LFUN_FONT_ITAL:
1396 case LFUN_FONT_BOLD:
1397 case LFUN_FONT_BOLDSYMBOL:
1398 case LFUN_FONT_SANS:
1399 case LFUN_FONT_EMPH:
1400 case LFUN_FONT_TYPEWRITER:
1401 case LFUN_FONT_NOUN:
1402 case LFUN_FONT_ROMAN:
1403 case LFUN_FONT_DEFAULT:
1404 flag.setEnabled(true);
1407 // we just need to be in math mode to enable that
1408 case LFUN_MATH_SIZE:
1409 case LFUN_MATH_SPACE:
1410 case LFUN_MATH_EXTERN:
1411 flag.setEnabled(true);
1414 case LFUN_FONT_UNDERLINE:
1415 case LFUN_FONT_FRAK:
1416 flag.setEnabled(currentMode() != TEXT_MODE);
1419 case LFUN_MATH_FONT_STYLE: {
1420 bool const textarg =
1421 arg == "textbf" || arg == "textsf" ||
1422 arg == "textrm" || arg == "textmd" ||
1423 arg == "textit" || arg == "textsc" ||
1424 arg == "textsl" || arg == "textup" ||
1425 arg == "texttt" || arg == "textbb" ||
1426 arg == "textnormal";
1427 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1431 case LFUN_MATH_MODE:
1432 // forbid "math-mode on" in math mode to prevent irritating
1433 // behaviour of menu entries (bug 6709)
1434 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1437 case LFUN_MATH_INSERT:
1438 flag.setEnabled(currentMode() != TEXT_MODE);
1441 case LFUN_MATH_AMS_MATRIX:
1442 case LFUN_MATH_MATRIX:
1443 flag.setEnabled(currentMode() == MATH_MODE);
1446 case LFUN_INSET_INSERT: {
1447 // Don't test createMathInset_fromDialogStr(), since
1448 // getStatus is not called with a valid reference and the
1449 // dialog would not be applyable.
1450 string const name = cmd.getArg(0);
1451 flag.setEnabled(name == "ref" || name == "mathspace");
1455 case LFUN_DIALOG_SHOW_NEW_INSET: {
1456 docstring const & name = cmd.argument();
1457 if (name == "space")
1458 flag.setEnabled(false);
1463 case LFUN_MATH_DELIM:
1464 case LFUN_MATH_BIGDELIM:
1465 // Don't do this with multi-cell selections
1466 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1469 case LFUN_MATH_MACRO_FOLD:
1470 case LFUN_MATH_MACRO_UNFOLD: {
1472 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1473 flag.setEnabled(found);
1477 case LFUN_SPECIALCHAR_INSERT:
1478 case LFUN_SCRIPT_INSERT:
1479 // FIXME: These would probably make sense in math-text mode
1480 flag.setEnabled(false);
1483 case LFUN_CAPTION_INSERT:
1484 flag.setEnabled(false);
1487 case LFUN_SPACE_INSERT: {
1488 docstring const & name = cmd.argument();
1489 if (name == "visible")
1490 flag.setEnabled(false);
1494 case LFUN_INSET_DISSOLVE:
1495 flag.setEnabled(!asHullInset());
1499 docstring const & name = cmd.argument();
1500 if (name == "html" || name == "latex")
1501 flag.setEnabled(false);
1513 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1516 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1517 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1518 cur.idx() = enter_front ? 0 : cur.lastidx();
1519 cur.pos() = enter_front ? 0 : cur.lastpos();
1521 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1525 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1528 int dist_min = 1000000;
1529 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1530 int const d = cell(i).dist(cur.bv(), x, y);
1536 MathData & ar = cell(idx_min);
1538 cur.idx() = idx_min;
1539 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1541 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1542 if (dist_min == 0) {
1544 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1545 if (ar[i]->covers(cur.bv(), x, y))
1546 return ar[i].nucleus()->editXY(cur, x, y);
1552 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1554 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1555 BufferView & bv = cur.bv();
1556 if (cmd.button() == mouse_button::button3) {
1557 // Don't do anything if we right-click a
1558 // selection, a context menu will popup.
1559 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1560 && cur < bv.cursor().selectionEnd()) {
1561 cur.noScreenUpdate();
1565 bool do_selection = cmd.button() == mouse_button::button1
1566 && cmd.modifier() == ShiftModifier;
1567 bv.mouseSetCursor(cur, do_selection);
1568 if (cmd.button() == mouse_button::button1) {
1569 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1570 // Update the cursor update flags as needed:
1572 // Update::Decoration: tells to update the decoration
1573 // (visual box corners that define
1575 // Update::FitCursor: adjust the screen to the cursor
1576 // position if needed
1577 // cur.result().update(): don't overwrite previously set flags.
1578 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1579 | cur.result().screenUpdate());
1580 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1581 if (cap::selection()) {
1582 // See comment in Text::dispatch why we do this
1583 cap::copySelectionToStack();
1584 cmd = FuncRequest(LFUN_PASTE, "0");
1585 doDispatch(bv.cursor(), cmd);
1588 asArray(theSelection().get(), ar);
1589 bv.cursor().insert(ar);
1595 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1597 // only select with button 1
1598 if (cmd.button() != mouse_button::button1)
1601 Cursor & bvcur = cur.bv().cursor();
1603 // ignore motions deeper nested than the real anchor
1604 if (!bvcur.realAnchor().hasPart(cur)) {
1609 CursorSlice old = bvcur.top();
1611 // We continue with our existing selection or start a new one, so don't
1612 // reset the anchor.
1613 bvcur.setCursor(cur);
1614 // Did we actually move?
1615 if (cur.top() == old)
1616 // We didn't move one iota, so no need to change selection status
1617 // or update the screen.
1618 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1620 bvcur.setSelection();
1624 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1626 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1628 if (cmd.button() == mouse_button::button1) {
1629 if (!cur.selection())
1630 cur.noScreenUpdate();
1632 Cursor & bvcur = cur.bv().cursor();
1633 bvcur.selection(true);
1642 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1644 //lyxerr << "interpret 2: '" << c << "'" << endl;
1645 docstring save_selection;
1646 if (c == '^' || c == '_')
1647 save_selection = grabAndEraseSelection(cur);
1650 Buffer * buf = cur.buffer();
1653 if (cur.inMacroMode()) {
1654 docstring name = cur.macroName();
1656 /// are we currently typing '#1' or '#2' or...?
1657 if (name == "\\#") {
1660 if (n >= 1 && n <= 9)
1661 cur.insert(new MathMacroArgument(n));
1665 // do not finish macro for known * commands
1666 bool star_macro = c == '*'
1667 && (in_word_set(name.substr(1) + '*')
1668 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1669 if (isAlphaASCII(c) || star_macro) {
1670 cur.activeMacro()->setName(name + docstring(1, c));
1674 // handle 'special char' macros
1679 if (currentMode() <= InsetMath::TEXT_MODE)
1680 cur.niceInsert(createInsetMath("textbackslash", buf));
1682 cur.niceInsert(createInsetMath("backslash", buf));
1683 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1685 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1686 } else if (c == '{' || c == '%') {
1687 //using the saved selection as argument
1688 InsetMathUnknown * p = cur.activeMacro();
1690 MathData sel(cur.buffer());
1691 asArray(p->selection(), sel);
1694 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1696 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1697 } else if (c == '#') {
1698 LASSERT(cur.activeMacro(), return false);
1699 cur.activeMacro()->setName(name + docstring(1, c));
1702 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1707 // One character big delimiters. The others are handled in
1708 // interpretString().
1709 latexkeys const * l = in_word_set(name.substr(1));
1710 if (name[0] == '\\' && l && l->inset == "big") {
1714 delim = from_ascii("\\{");
1717 delim = from_ascii("\\}");
1720 delim = docstring(1, c);
1723 if (InsetMathBig::isBigInsetDelim(delim)) {
1724 // name + delim ared a valid InsetMathBig.
1725 // We can't use cur.macroModeClose() because
1726 // it does not handle delim.
1727 InsetMathUnknown * p = cur.activeMacro();
1730 cur.cell().erase(cur.pos());
1731 cur.plainInsert(MathAtom(
1732 new InsetMathBig(name.substr(1), delim)));
1735 } else if (name == "\\smash" && c == '[') {
1736 // We can't use cur.macroModeClose() because
1737 // it would create an InsetMathPhantom
1738 InsetMathUnknown * p = cur.activeMacro();
1740 interpretChar(cur, c);
1744 // leave macro mode and try again if necessary
1745 if (cur.macroModeClose()) {
1746 MathAtom const atom = cur.prevAtom();
1747 if (atom->asNestInset() && atom->isActive()) {
1749 cur.pushBackward(*cur.nextInset());
1753 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1755 interpretChar(cur, c);
1760 // leave autocorrect mode if necessary
1761 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1762 cur.autocorrect() = false;
1763 cur.message(_("Autocorrect Off ('!' to enter)"));
1766 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1767 cur.autocorrect() = true;
1768 cur.message(_("Autocorrect On (<space> to exit)"));
1772 // just clear selection on pressing the space bar
1773 if (cur.selection() && c == ' ') {
1774 cur.selection(false);
1779 //lyxerr << "starting with macro" << endl;
1780 bool reduced = cap::reduceSelectionToOneCell(cur);
1781 if (reduced || !cur.selection()) {
1782 cur.recordUndoInset();
1783 docstring const safe = cap::grabAndEraseSelection(cur);
1784 if (!cur.inRegexped())
1785 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1787 cur.niceInsert(createInsetMath("backslash", buf));
1795 if (currentMode() <= InsetMath::TEXT_MODE)
1801 if (currentMode() <= InsetMath::TEXT_MODE) {
1802 // insert spaces in text or undecided mode,
1803 // but suppress direct insertion of two spaces in a row
1804 // the still allows typing '<space>a<space>' and deleting the 'a', but
1805 // it is better than nothing...
1806 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1808 // FIXME: we have to enable full redraw here because of the
1809 // visual box corners that define the inset. If we know for
1810 // sure that we stay within the same cell we can optimize for
1812 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1816 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1817 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1818 // FIXME: we have to enable full redraw here because of the
1819 // visual box corners that define the inset. If we know for
1820 // sure that we stay within the same cell we can optimize for
1822 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1826 if (cur.popForward()) {
1827 // FIXME: we have to enable full redraw here because of the
1828 // visual box corners that define the inset. If we know for
1829 // sure that we stay within the same cell we can optimize for
1831 //cur.screenUpdateFlags(Update::FitCursor);
1835 // if we are at the very end, leave the formula
1836 return cur.pos() != cur.lastpos();
1839 // These should be treated differently when not in text mode:
1840 if (cur.inRegexped()) {
1843 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1850 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1853 cur.niceInsert(createInsetMath("sim", buf));
1859 } else if (currentMode() != InsetMath::TEXT_MODE) {
1861 script(cur, false, save_selection);
1865 script(cur, true, save_selection);
1869 cur.niceInsert(createInsetMath("sim", buf));
1872 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1873 MathAtom at = createInsetMath("text", buf);
1874 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1881 cur.niceInsert(createInsetMath("textasciicircum", buf));
1885 cur.niceInsert(createInsetMath("textasciitilde", buf));
1890 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1891 c == '%' || c == '_') {
1892 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1897 // try auto-correction
1898 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1899 && math_autocorrect(cur.prevAtom(), c))
1902 // no special circumstances, so insert the character without any fuss
1904 if (lyxrc.autocorrection_math) {
1905 if (!cur.autocorrect())
1906 cur.message(_("Autocorrect Off ('!' to enter)"));
1908 cur.message(_("Autocorrect On (<space> to exit)"));
1914 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1916 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1918 if (!cur.empty() && cur.pos() > 0 &&
1919 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1920 if (InsetMathBig::isBigInsetDelim(str)) {
1921 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1922 if (prev[0] == '\\') {
1923 prev = prev.substr(1);
1924 latexkeys const * l = in_word_set(prev);
1925 if (l && l->inset == "big") {
1926 cur.cell()[cur.pos() - 1] =
1927 MathAtom(new InsetMathBig(prev, str));
1937 bool InsetMathNest::script(Cursor & cur, bool up)
1939 return script(cur, up, docstring());
1943 bool InsetMathNest::script(Cursor & cur, bool up,
1944 docstring const & save_selection)
1946 // Hack to get \^ and \_ working
1947 //lyxerr << "handling script: up: " << up << endl;
1948 if (cur.inMacroMode() && cur.macroName() == "\\") {
1950 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1952 interpretChar(cur, '_');
1956 cur.macroModeClose();
1957 if (asScriptInset() && cur.idx() == 0) {
1958 // we are in a nucleus of a script inset, move to _our_ script
1959 InsetMathScript * inset = asScriptInset();
1960 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1962 cur.idx() = inset->idxOfScript(up);
1964 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1966 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1969 cur.idx() = inset->idxOfScript(up);
1970 cur.pos() = cur.lastpos();
1972 // convert the thing to our left to a scriptinset or create a new
1973 // one if in the very first position of the array
1974 if (cur.pos() == 0) {
1975 //lyxerr << "new scriptinset" << endl;
1976 cur.insert(new InsetMathScript(buffer_, up));
1978 //lyxerr << "converting prev atom " << endl;
1979 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1982 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1983 // See comment in MathParser.cpp for special handling of {}-bases
1989 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1990 cur.niceInsert(save_selection);
1992 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1997 bool InsetMathNest::completionSupported(Cursor const & cur) const
1999 return cur.inMacroMode();
2003 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2005 return cur.inMacroMode();
2009 bool InsetMathNest::automaticInlineCompletion() const
2011 return lyxrc.completion_inline_math;
2015 bool InsetMathNest::automaticPopupCompletion() const
2017 return lyxrc.completion_popup_math;
2021 CompletionList const *
2022 InsetMathNest::createCompletionList(Cursor const & cur) const
2024 if (!cur.inMacroMode())
2027 return new MathCompletionList(cur);
2031 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2033 if (!cur.inMacroMode())
2036 return cur.activeMacro()->name();
2040 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2043 if (!cur.inMacroMode())
2046 // append completion to active macro
2047 InsetMathUnknown * inset = cur.activeMacro();
2048 inset->setName(inset->name() + s);
2053 // FIXME: this creates duplicates in the completion popup
2054 // which looks ugly. Moreover the changes the list lengths
2056 confuse the popup as well.
2057 MathCompletionList::addToFavorites(inset->name());
2059 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2066 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2067 Dimension & dim) const
2069 Inset const * inset = cur.activeMacro();
2073 // get inset dimensions
2074 dim = cur.bv().coordCache().insets().dim(inset);
2075 // FIXME: these 3 are no accurate, but should depend on the font.
2076 // Now the popup jumps down if you enter a char with descent > 0.
2081 Point xy = cur.bv().coordCache().insets().xy(inset);
2087 bool InsetMathNest::cursorMathForward(Cursor & cur)
2089 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2090 cur.pushBackward(*cur.nextAtom().nucleus());
2091 cur.inset().idxFirst(cur);
2094 if (cur.posForward() || idxForward(cur))
2096 // try to pop forwards --- but don't pop out of math! leave that to
2098 int s = cur.depth() - 2;
2099 if (s >= 0 && cur[s].inset().asInsetMath())
2100 return cur.popForward();
2105 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2107 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2109 cur.push(*cur.nextAtom().nucleus());
2110 cur.inset().idxLast(cur);
2113 if (cur.posBackward() || idxBackward(cur))
2115 // try to pop backwards --- but don't pop out of math! leave that to
2117 int s = cur.depth() - 2;
2118 if (s >= 0 && cur[s].inset().asInsetMath())
2119 return cur.popBackward();
2124 ////////////////////////////////////////////////////////////////////
2126 MathCompletionList::MathCompletionList(Cursor const & cur)
2128 // fill it with macros from the buffer
2129 MacroNameSet macros;
2130 cur.buffer()->listMacroNames(macros);
2131 MacroNameSet::const_iterator it;
2132 for (it = macros.begin(); it != macros.end(); ++it) {
2133 if (cur.buffer()->getMacro(*it, cur, false))
2134 locals.push_back("\\" + *it);
2136 sort(locals.begin(), locals.end());
2138 if (!globals.empty())
2141 // fill in global macros
2143 MacroTable::globalMacros().getMacroNames(macros, false);
2144 //lyxerr << "Globals completion macros: ";
2145 for (it = macros.begin(); it != macros.end(); ++it) {
2146 //lyxerr << "\\" + *it << " ";
2147 globals.push_back("\\" + *it);
2149 //lyxerr << std::endl;
2151 // fill in global commands
2152 globals.push_back(from_ascii("\\boxed"));
2153 globals.push_back(from_ascii("\\fbox"));
2154 globals.push_back(from_ascii("\\framebox"));
2155 globals.push_back(from_ascii("\\makebox"));
2156 globals.push_back(from_ascii("\\kern"));
2157 globals.push_back(from_ascii("\\xhookrightarrow"));
2158 globals.push_back(from_ascii("\\xhookleftarrow"));
2159 globals.push_back(from_ascii("\\xrightarrow"));
2160 globals.push_back(from_ascii("\\xRightarrow"));
2161 globals.push_back(from_ascii("\\xrightharpoondown"));
2162 globals.push_back(from_ascii("\\xrightharpoonup"));
2163 globals.push_back(from_ascii("\\xrightleftharpoons"));
2164 globals.push_back(from_ascii("\\xleftarrow"));
2165 globals.push_back(from_ascii("\\xLeftarrow"));
2166 globals.push_back(from_ascii("\\xleftharpoondown"));
2167 globals.push_back(from_ascii("\\xleftharpoonup"));
2168 globals.push_back(from_ascii("\\xleftrightarrow"));
2169 globals.push_back(from_ascii("\\xLeftrightarrow"));
2170 globals.push_back(from_ascii("\\xleftrightharpoons"));
2171 globals.push_back(from_ascii("\\xmapsto"));
2172 globals.push_back(from_ascii("\\split"));
2173 globals.push_back(from_ascii("\\gathered"));
2174 globals.push_back(from_ascii("\\aligned"));
2175 globals.push_back(from_ascii("\\alignedat"));
2176 globals.push_back(from_ascii("\\cases"));
2177 globals.push_back(from_ascii("\\substack"));
2178 globals.push_back(from_ascii("\\xymatrix"));
2179 globals.push_back(from_ascii("\\Diagram"));
2180 globals.push_back(from_ascii("\\subarray"));
2181 globals.push_back(from_ascii("\\array"));
2182 globals.push_back(from_ascii("\\sqrt"));
2183 globals.push_back(from_ascii("\\root"));
2184 globals.push_back(from_ascii("\\tabular"));
2185 globals.push_back(from_ascii("\\sideset"));
2186 globals.push_back(from_ascii("\\stackrel"));
2187 globals.push_back(from_ascii("\\stackrelthree"));
2188 globals.push_back(from_ascii("\\binom"));
2189 globals.push_back(from_ascii("\\choose"));
2190 globals.push_back(from_ascii("\\brace"));
2191 globals.push_back(from_ascii("\\brack"));
2192 globals.push_back(from_ascii("\\frac"));
2193 globals.push_back(from_ascii("\\over"));
2194 globals.push_back(from_ascii("\\nicefrac"));
2195 globals.push_back(from_ascii("\\unitfrac"));
2196 globals.push_back(from_ascii("\\unitfracthree"));
2197 globals.push_back(from_ascii("\\unitone"));
2198 globals.push_back(from_ascii("\\unittwo"));
2199 globals.push_back(from_ascii("\\infer"));
2200 globals.push_back(from_ascii("\\atop"));
2201 globals.push_back(from_ascii("\\lefteqn"));
2202 globals.push_back(from_ascii("\\boldsymbol"));
2203 globals.push_back(from_ascii("\\bm"));
2204 globals.push_back(from_ascii("\\color"));
2205 globals.push_back(from_ascii("\\normalcolor"));
2206 globals.push_back(from_ascii("\\textcolor"));
2207 globals.push_back(from_ascii("\\cfrac"));
2208 globals.push_back(from_ascii("\\cfracleft"));
2209 globals.push_back(from_ascii("\\cfracright"));
2210 globals.push_back(from_ascii("\\dfrac"));
2211 globals.push_back(from_ascii("\\tfrac"));
2212 globals.push_back(from_ascii("\\dbinom"));
2213 globals.push_back(from_ascii("\\tbinom"));
2214 globals.push_back(from_ascii("\\hphantom"));
2215 globals.push_back(from_ascii("\\phantom"));
2216 globals.push_back(from_ascii("\\vphantom"));
2217 globals.push_back(from_ascii("\\cancel"));
2218 globals.push_back(from_ascii("\\bcancel"));
2219 globals.push_back(from_ascii("\\xcancel"));
2220 globals.push_back(from_ascii("\\cancelto"));
2221 globals.push_back(from_ascii("\\smash"));
2222 globals.push_back(from_ascii("\\mathclap"));
2223 globals.push_back(from_ascii("\\mathllap"));
2224 globals.push_back(from_ascii("\\mathrlap"));
2225 globals.push_back(from_ascii("\\ensuremath"));
2226 MathWordList const & words = mathedWordList();
2227 MathWordList::const_iterator it2;
2228 //lyxerr << "Globals completion commands: ";
2229 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2230 if (it2->second.inset != "macro" && !it2->second.hidden) {
2231 // macros are already read from MacroTable::globalMacros()
2232 globals.push_back('\\' + it2->first);
2233 //lyxerr << '\\' + it2->first << ' ';
2236 //lyxerr << std::endl;
2237 sort(globals.begin(), globals.end());
2241 MathCompletionList::~MathCompletionList()
2246 size_type MathCompletionList::size() const
2248 return locals.size() + globals.size();
2252 docstring const & MathCompletionList::data(size_t idx) const
2254 size_t lsize = locals.size();
2256 return globals[idx - lsize];
2262 std::string MathCompletionList::icon(size_t idx) const
2264 // get the latex command
2266 size_t lsize = locals.size();
2268 cmd = globals[idx - lsize];
2272 // get the icon resource name by stripping the backslash
2273 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2274 if (icon_name.empty())
2275 return std::string();
2276 return "images/math/" + to_utf8(icon_name);
2279 std::vector<docstring> MathCompletionList::globals;