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 &, int, int) const
272 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
278 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
280 BufferView & bv = *pi.base.bv;
281 // this should use the x/y values given, not the cached values
282 Cursor & cur = bv.cursor();
283 if (!cur.selection())
285 if (&cur.inset() != this)
288 // FIXME: hack to get position cache warm
289 bool const original_drawing_state = pi.pain.isDrawingEnabled();
290 pi.pain.setDrawingEnabled(false);
292 pi.pain.setDrawingEnabled(original_drawing_state);
294 CursorSlice s1 = cur.selBegin();
295 CursorSlice s2 = cur.selEnd();
297 //lyxerr << "InsetMathNest::drawing selection: "
298 // << " s1: " << s1 << " s2: " << s2 << endl;
299 if (s1.idx() == s2.idx()) {
300 MathData const & c = cell(s1.idx());
301 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
302 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
303 int y1 = g.pos.y_ - g.dim.ascent();
304 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
305 int y2 = g.pos.y_ + g.dim.descent();
306 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
307 //lyxerr << "InsetMathNest::drawing selection 3: "
308 // << " x1: " << x1 << " x2: " << x2
309 // << " y1: " << y1 << " y2: " << y2 << endl;
311 for (idx_type i = 0; i < nargs(); ++i) {
312 if (idxBetween(i, s1.idx(), s2.idx())) {
313 MathData const & c = cell(i);
314 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
316 int y1 = g.pos.y_ - g.dim.ascent();
317 int x2 = g.pos.x_ + g.dim.width();
318 int y2 = g.pos.y_ + g.dim.descent();
319 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
326 void InsetMathNest::validate(LaTeXFeatures & features) const
328 for (idx_type i = 0; i < nargs(); ++i)
329 cell(i).validate(features);
333 void InsetMathNest::replace(ReplaceData & rep)
335 for (idx_type i = 0; i < nargs(); ++i)
336 cell(i).replace(rep);
340 bool InsetMathNest::contains(MathData const & ar) const
342 for (idx_type i = 0; i < nargs(); ++i)
343 if (cell(i).contains(ar))
349 bool InsetMathNest::lock() const
355 void InsetMathNest::lock(bool l)
361 bool InsetMathNest::isActive() const
367 MathData InsetMathNest::glue() const
370 for (size_t i = 0; i < nargs(); ++i)
376 void InsetMathNest::write(WriteStream & os) const
378 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
379 ModeSpecifier specifier(os, currentMode(), lockedMode());
380 docstring const latex_name = name();
381 os << '\\' << latex_name;
382 for (size_t i = 0; i < nargs(); ++i) {
383 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
384 os << '{' << cell(i) << '}';
387 os.pendingSpace(true);
388 if (lock_ && !os.latex()) {
390 os.pendingSpace(true);
395 void InsetMathNest::normalize(NormalStream & os) const
398 for (size_t i = 0; i < nargs(); ++i)
399 os << ' ' << cell(i);
404 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
406 WriteStream wi(os, runparams.moving_arg, true,
407 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
409 wi.strikeoutMath(runparams.inDeletedInset
410 && (!LaTeXFeatures::isAvailable("dvipost")
411 || (runparams.flavor != OutputParams::LATEX
412 && runparams.flavor != OutputParams::DVILUATEX)));
413 if (runparams.inulemcmd) {
414 wi.ulemCmd(WriteStream::UNDERLINE);
415 if (runparams.local_font) {
416 FontInfo f = runparams.local_font->fontInfo();
417 if (f.strikeout() == FONT_ON)
418 wi.ulemCmd(WriteStream::STRIKEOUT);
421 wi.canBreakLine(os.canBreakLine());
422 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
425 // Reset parbreak status after a math inset.
427 os.canBreakLine(wi.canBreakLine());
431 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
434 mouse_hover_[bv] = mouse_hover;
439 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
443 MathData & ar = cur.cell();
444 // remove base-only "scripts"
445 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
446 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
447 if (p && p->nargs() == 1) {
448 MathData ar = p->nuc();
451 cur.adjust(i, ar.size() - 1);
455 // glue adjacent font insets of the same kind
456 for (pos_type i = 0; i + 1 < size(); ++i) {
457 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
458 InsetMathFont const * q = operator[](i + 1)->asFontInset();
459 if (p && q && p->name() == q->name()) {
460 p->cell(0).append(q->cell(0));
470 void InsetMathNest::handleFont
471 (Cursor & cur, docstring const & arg, char const * const font)
473 handleFont(cur, arg, from_ascii(font));
477 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
478 docstring const & font)
480 cur.recordUndoSelection();
482 // this whole function is a hack and won't work for incremental font
484 if (cur.inset().asInsetMath()->name() == font)
485 cur.handleFont(to_utf8(font));
487 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
491 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
493 handleNest(cur, nest, docstring());
497 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
498 docstring const & arg)
500 CursorSlice i1 = cur.selBegin();
501 CursorSlice i2 = cur.selEnd();
502 if (!i1.inset().asInsetMath())
504 if (i1.idx() == i2.idx()) {
505 // the easy case where only one cell is selected
506 cur.handleNest(nest);
511 // multiple selected cells in a simple non-grid inset
512 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
513 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
518 cur.pos() = cur.lastpos();
521 // change font of cell
522 cur.handleNest(nest);
525 // cur is in the font inset now. If the loop continues,
526 // we need to get outside again for the next cell
527 if (i + 1 <= i2.idx())
533 // the complicated case with multiple selected cells in a grid
536 cap::region(i1, i2, r1, r2, c1, c2);
537 for (row_type row = r1; row <= r2; ++row) {
538 for (col_type col = c1; col <= c2; ++col) {
540 cur.idx() = i1.asInsetMath()->index(row, col);
543 cur.pos() = cur.lastpos();
547 cur.handleNest(nest);
550 // cur is in the font inset now. If the loop continues,
551 // we need to get outside again for the next cell
552 if (col + 1 <= c2 || row + 1 <= r2)
559 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
561 cur.recordUndoSelection();
564 font.fromString(to_utf8(arg), b);
565 if (font.fontInfo().color() != Color_inherit &&
566 font.fontInfo().color() != Color_ignore)
567 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
569 // FIXME: support other font changes here as well?
573 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
575 //LYXERR0("InsetMathNest: request: " << cmd);
577 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
579 FuncCode const act = cmd.action();
582 case LFUN_CLIPBOARD_PASTE:
583 parseflg |= Parse::VERBATIM;
586 if (cur.currentMode() <= TEXT_MODE)
587 parseflg |= Parse::TEXTMODE;
588 cur.recordUndoSelection();
589 cur.message(_("Paste"));
590 replaceSelection(cur);
592 if (cmd.argument().empty() && !theClipboard().isInternal())
593 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
596 idocstringstream is(cmd.argument());
598 topaste = cap::selection(n, buffer().params().documentClassPtr());
600 cur.niceInsert(topaste, parseflg, false);
601 cur.clearSelection(); // bug 393
602 cur.forceBufferUpdate();
609 cutSelection(cur, true, true);
610 cur.message(_("Cut"));
611 // Prevent stale position >= size crash
612 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
614 cur.forceBufferUpdate();
619 cur.message(_("Copy"));
622 case LFUN_MOUSE_PRESS:
623 lfunMousePress(cur, cmd);
626 case LFUN_MOUSE_MOTION:
627 lfunMouseMotion(cur, cmd);
630 case LFUN_MOUSE_RELEASE:
631 lfunMouseRelease(cur, cmd);
634 case LFUN_FINISHED_LEFT: // in math, left is backwards
635 case LFUN_FINISHED_BACKWARD:
636 cur.bv().cursor() = cur;
639 case LFUN_FINISHED_RIGHT: // in math, right is forward
640 case LFUN_FINISHED_FORWARD:
642 cur.bv().cursor() = cur;
645 case LFUN_CHAR_RIGHT:
647 case LFUN_CHAR_BACKWARD:
648 case LFUN_CHAR_FORWARD:
649 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
651 case LFUN_CHAR_RIGHT_SELECT:
652 case LFUN_CHAR_LEFT_SELECT:
653 case LFUN_CHAR_BACKWARD_SELECT:
654 case LFUN_CHAR_FORWARD_SELECT: {
655 // are we in a selection?
656 bool select = (act == LFUN_CHAR_RIGHT_SELECT
657 || act == LFUN_CHAR_LEFT_SELECT
658 || act == LFUN_CHAR_BACKWARD_SELECT
659 || act == LFUN_CHAR_FORWARD_SELECT);
660 // are we moving forward or backwards?
661 // If the command was RIGHT or LEFT, then whether we're moving forward
662 // or backwards depends on the cursor movement mode (logical or visual):
663 // * in visual mode, since math is always LTR, right -> forward,
665 // * in logical mode, the mapping is determined by the
666 // reverseDirectionNeeded() function
669 FuncCode finish_lfun;
671 if (act == LFUN_CHAR_FORWARD
672 || act == LFUN_CHAR_FORWARD_SELECT) {
674 finish_lfun = LFUN_FINISHED_FORWARD;
676 else if (act == LFUN_CHAR_BACKWARD
677 || act == LFUN_CHAR_BACKWARD_SELECT) {
679 finish_lfun = LFUN_FINISHED_BACKWARD;
682 bool right = (act == LFUN_CHAR_RIGHT_SELECT
683 || act == LFUN_CHAR_RIGHT);
684 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
690 finish_lfun = LFUN_FINISHED_RIGHT;
692 finish_lfun = LFUN_FINISHED_LEFT;
694 // Now that we know exactly what we want to do, let's do it!
695 cur.selHandle(select);
697 cur.macroModeClose();
698 // try moving forward or backwards as necessary...
699 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
700 // ... and if movement failed, then finish forward or backwards
702 cmd = FuncRequest(finish_lfun);
710 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
712 case LFUN_DOWN_SELECT:
713 case LFUN_UP_SELECT: {
714 // close active macro
715 if (cur.inMacroMode()) {
716 cur.macroModeClose();
720 // stop/start the selection
721 bool select = act == LFUN_DOWN_SELECT ||
722 act == LFUN_UP_SELECT;
723 cur.selHandle(select);
725 // handle autocorrect:
726 if (lyxrc.autocorrection_math && cur.autocorrect()) {
727 cur.autocorrect() = false;
728 cur.message(_("Autocorrect Off ('!' to enter)"));
732 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
733 bool successful = cur.upDownInMath(up);
737 if (cur.fixIfBroken())
738 // FIXME: Something bad happened. We pass the corrected Cursor
739 // instead of letting things go worse.
742 // We did not manage to move the cursor.
747 case LFUN_MOUSE_DOUBLE:
748 case LFUN_WORD_SELECT:
752 cur.pos() = cur.lastpos();
753 cur.bv().cursor() = cur;
756 case LFUN_MOUSE_TRIPLE:
761 cur.idx() = cur.lastidx();
762 cur.pos() = cur.lastpos();
763 cur.bv().cursor() = cur;
766 case LFUN_PARAGRAPH_UP:
767 case LFUN_PARAGRAPH_DOWN:
768 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
770 case LFUN_PARAGRAPH_UP_SELECT:
771 case LFUN_PARAGRAPH_DOWN_SELECT:
774 case LFUN_LINE_BEGIN:
775 case LFUN_WORD_BACKWARD:
777 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
779 case LFUN_LINE_BEGIN_SELECT:
780 case LFUN_WORD_BACKWARD_SELECT:
781 case LFUN_WORD_LEFT_SELECT:
782 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
783 act == LFUN_WORD_LEFT_SELECT ||
784 act == LFUN_LINE_BEGIN_SELECT);
785 cur.macroModeClose();
786 if (cur.pos() != 0) {
788 } else if (cur.col() != 0) {
789 cur.idx() -= cur.col();
791 } else if (cur.idx() != 0) {
795 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
800 case LFUN_WORD_FORWARD:
801 case LFUN_WORD_RIGHT:
803 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
805 case LFUN_WORD_FORWARD_SELECT:
806 case LFUN_WORD_RIGHT_SELECT:
807 case LFUN_LINE_END_SELECT:
808 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
809 act == LFUN_WORD_RIGHT_SELECT ||
810 act == LFUN_LINE_END_SELECT);
811 cur.macroModeClose();
813 if (cur.pos() != cur.lastpos()) {
814 cur.pos() = cur.lastpos();
815 } else if (ncols() && (cur.col() != cur.lastcol())) {
816 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
817 cur.pos() = cur.lastpos();
818 } else if (cur.idx() != cur.lastidx()) {
819 cur.idx() = cur.lastidx();
820 cur.pos() = cur.lastpos();
822 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
827 case LFUN_CELL_FORWARD:
828 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
829 cur.inset().idxNext(cur);
832 case LFUN_CELL_BACKWARD:
833 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
834 cur.inset().idxPrev(cur);
837 case LFUN_WORD_DELETE_BACKWARD:
838 case LFUN_CHAR_DELETE_BACKWARD:
840 // May affect external cell:
841 cur.recordUndoInset();
842 else if (!cur.inMacroMode())
843 cur.recordUndoSelection();
844 // if the inset can not be removed from within, delete it
845 if (!cur.backspace()) {
846 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
847 cur.innerText()->dispatch(cur, cmd);
851 case LFUN_WORD_DELETE_FORWARD:
852 case LFUN_CHAR_DELETE_FORWARD:
853 if (cur.pos() == cur.lastpos())
854 // May affect external cell:
855 cur.recordUndoInset();
857 cur.recordUndoSelection();
858 // if the inset can not be removed from within, delete it
860 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
861 cur.innerText()->dispatch(cur, cmd);
867 cur.clearSelection();
869 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
874 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
875 // that is traversed by a single <CursorLeft>/<CursorRight>.
876 case LFUN_INSET_TOGGLE:
882 case LFUN_SELF_INSERT:
883 if (cmd.argument().size() != 1) {
884 cur.recordUndoSelection();
885 docstring const arg = cmd.argument();
886 if (!interpretString(cur, arg))
890 // Don't record undo steps if we are in macro mode and thus
891 // cmd.argument is the next character of the macro name.
892 // Otherwise we'll get an invalid cursor if we undo after
893 // the macro was finished and the macro is a known command,
894 // e.g. sqrt. Cursor::macroModeClose replaces in this case
895 // the InsetMathUnknown with name "frac" by an empty
896 // InsetMathFrac -> a pos value > 0 is invalid.
897 // A side effect is that an undo before the macro is finished
898 // undoes the complete macro, not only the last character.
899 // At the time we hit '\' we are not in macro mode, still.
900 if (!cur.inMacroMode())
901 cur.recordUndoSelection();
903 // spacial handling of space. If we insert an inset
904 // via macro mode, we want to put the cursor inside it
905 // if relevant. Think typing "\frac<space>".
906 if (cmd.argument()[0] == ' '
907 && cur.inMacroMode() && cur.macroName() != "\\"
908 && cur.macroModeClose() && cur.pos() > 0) {
909 MathAtom const atom = cur.prevAtom();
910 if (atom->asNestInset() && atom->isActive()) {
912 cur.pushBackward(*cur.nextInset());
914 } else if (!interpretChar(cur, cmd.argument()[0])) {
915 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
920 //case LFUN_SERVER_GET_XY:
923 case LFUN_SERVER_SET_XY: {
924 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
927 istringstream is(to_utf8(cmd.argument()));
929 cur.setScreenPos(x, y);
933 // Special casing for superscript in case of LyX handling
935 case LFUN_ACCENT_CIRCUMFLEX:
936 if (cmd.argument().empty()) {
937 // do superscript if LyX handles
939 cur.recordUndoSelection();
940 script(cur, true, grabAndEraseSelection(cur));
944 case LFUN_ACCENT_UMLAUT:
945 case LFUN_ACCENT_ACUTE:
946 case LFUN_ACCENT_GRAVE:
947 case LFUN_ACCENT_BREVE:
948 case LFUN_ACCENT_DOT:
949 case LFUN_ACCENT_MACRON:
950 case LFUN_ACCENT_CARON:
951 case LFUN_ACCENT_TILDE:
952 case LFUN_ACCENT_CEDILLA:
953 case LFUN_ACCENT_CIRCLE:
954 case LFUN_ACCENT_UNDERDOT:
955 case LFUN_ACCENT_TIE:
956 case LFUN_ACCENT_OGONEK:
957 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
961 case LFUN_TEXTSTYLE_APPLY:
962 case LFUN_TEXTSTYLE_UPDATE:
963 handleFont2(cur, cmd.argument());
967 if (currentMode() <= TEXT_MODE)
968 handleFont(cur, cmd.argument(), "textbf");
970 handleFont(cur, cmd.argument(), "mathbf");
972 case LFUN_FONT_BOLDSYMBOL:
973 if (currentMode() <= TEXT_MODE)
974 handleFont(cur, cmd.argument(), "textbf");
976 handleFont(cur, cmd.argument(), "boldsymbol");
979 if (currentMode() <= TEXT_MODE)
980 handleFont(cur, cmd.argument(), "textsf");
982 handleFont(cur, cmd.argument(), "mathsf");
985 if (currentMode() <= TEXT_MODE)
986 handleFont(cur, cmd.argument(), "emph");
988 handleFont(cur, cmd.argument(), "mathcal");
990 case LFUN_FONT_ROMAN:
991 if (currentMode() <= TEXT_MODE)
992 handleFont(cur, cmd.argument(), "textrm");
994 handleFont(cur, cmd.argument(), "mathrm");
996 case LFUN_FONT_TYPEWRITER:
997 if (currentMode() <= TEXT_MODE)
998 handleFont(cur, cmd.argument(), "texttt");
1000 handleFont(cur, cmd.argument(), "mathtt");
1002 case LFUN_FONT_FRAK:
1003 handleFont(cur, cmd.argument(), "mathfrak");
1005 case LFUN_FONT_ITAL:
1006 if (currentMode() <= TEXT_MODE)
1007 handleFont(cur, cmd.argument(), "textit");
1009 handleFont(cur, cmd.argument(), "mathit");
1011 case LFUN_FONT_NOUN:
1012 if (currentMode() <= TEXT_MODE)
1013 // FIXME: should be "noun"
1014 handleFont(cur, cmd.argument(), "textsc");
1016 handleFont(cur, cmd.argument(), "mathbb");
1018 case LFUN_FONT_DEFAULT:
1019 handleFont(cur, cmd.argument(), "textnormal");
1021 case LFUN_FONT_UNDERLINE:
1023 cur.handleNest(createInsetMath("underline", cur.buffer()));
1026 case LFUN_MATH_MODE: {
1028 // ignore math-mode on when already in math mode
1029 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1031 cur.recordUndoSelection();
1032 cur.macroModeClose();
1033 docstring const save_selection = grabAndEraseSelection(cur);
1035 if (currentMode() <= Inset::TEXT_MODE)
1036 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1038 cur.plainInsert(createInsetMath("text", buffer_));
1040 cur.pushBackward(*cur.nextInset());
1041 cur.niceInsert(save_selection);
1042 cur.forceBufferUpdate();
1044 if (currentMode() == Inset::TEXT_MODE) {
1045 cur.recordUndoSelection();
1046 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1047 cur.message(_("create new math text environment ($...$)"));
1049 handleFont(cur, cmd.argument(), "textrm");
1050 cur.message(_("entered math text mode (textrm)"));
1056 case LFUN_REGEXP_MODE: {
1057 InsetMath * im = cur.inset().asInsetMath();
1059 InsetMathHull * i = im->asHullInset();
1060 if (i && i->getType() == hullRegexp) {
1061 cur.message(_("Already in regular expression mode"));
1065 cur.macroModeClose();
1066 docstring const save_selection = grabAndEraseSelection(cur);
1068 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1070 cur.pushBackward(*cur.nextInset());
1071 cur.niceInsert(save_selection);
1072 cur.message(_("Regular expression editor mode"));
1076 case LFUN_MATH_FONT_STYLE: {
1077 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1078 doDispatch(cur, fr);
1082 case LFUN_MATH_SIZE: {
1083 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1084 doDispatch(cur, fr);
1088 case LFUN_MATH_MATRIX: {
1094 idocstringstream is(cmd.argument());
1095 is >> m >> n >> v_align >> h_align;
1101 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1102 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1106 case LFUN_MATH_AMS_MATRIX: {
1110 docstring name = from_ascii("matrix");
1111 idocstringstream is(cmd.argument());
1112 is >> m >> n >> name;
1117 // check if we have a valid decoration
1118 if (name != "pmatrix" && name != "bmatrix"
1119 && name != "Bmatrix" && name != "vmatrix"
1120 && name != "Vmatrix" && name != "matrix")
1121 name = from_ascii("matrix");
1124 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1128 case LFUN_MATH_DELIM: {
1130 docstring rs = split(cmd.argument(), ls, ' ');
1131 // Reasonable default values
1137 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1141 case LFUN_MATH_BIGDELIM: {
1142 docstring const lname = from_utf8(cmd.getArg(0));
1143 docstring const ldelim = from_utf8(cmd.getArg(1));
1144 docstring const rname = from_utf8(cmd.getArg(2));
1145 docstring const rdelim = from_utf8(cmd.getArg(3));
1146 latexkeys const * l = in_word_set(lname);
1147 bool const have_l = l && l->inset == "big" &&
1148 InsetMathBig::isBigInsetDelim(ldelim);
1149 l = in_word_set(rname);
1150 bool const have_r = l && l->inset == "big" &&
1151 InsetMathBig::isBigInsetDelim(rdelim);
1152 // We mimic LFUN_MATH_DELIM in case we have an empty left
1153 // or right delimiter.
1154 if (have_l || have_r) {
1156 docstring const selection = grabAndEraseSelection(cur);
1159 cur.insert(MathAtom(new InsetMathBig(lname,
1161 // first insert the right delimiter and then go back
1162 // and re-insert the selection (bug 7088)
1164 cur.insert(MathAtom(new InsetMathBig(rname,
1168 cur.niceInsert(selection);
1170 // Don't call cur.undispatched() if we did nothing, this would
1171 // lead to infinite recursion via Text::dispatch().
1175 case LFUN_SPACE_INSERT: {
1176 cur.recordUndoSelection();
1177 string const name = cmd.getArg(0);
1178 if (name == "normal")
1179 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1180 else if (name == "protected")
1181 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1182 else if (name == "thin" || name == "med" || name == "thick")
1183 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1184 else if (name == "hfill*")
1185 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1186 else if (name == "quad" || name == "qquad" ||
1187 name == "enspace" || name == "enskip" ||
1188 name == "negthinspace" || name == "negmedspace" ||
1189 name == "negthickspace" || name == "hfill")
1190 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1191 else if (name == "hspace" || name == "hspace*") {
1192 string const len = cmd.getArg(1);
1193 if (len.empty() || !isValidLength(len)) {
1194 lyxerr << "LyX function 'space-insert " << name << "' "
1195 "needs a valid length argument." << endl;
1198 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1200 cur.insert(MathAtom(new InsetMathSpace));
1204 case LFUN_MATH_SPACE:
1205 cur.recordUndoSelection();
1206 if (cmd.argument().empty())
1207 cur.insert(MathAtom(new InsetMathSpace));
1209 string const name = cmd.getArg(0);
1210 string const len = cmd.getArg(1);
1211 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1215 case LFUN_ERT_INSERT:
1216 // interpret this as if a backslash was typed
1218 interpretChar(cur, '\\');
1221 case LFUN_MATH_SUBSCRIPT:
1222 // interpret this as if a _ was typed
1223 cur.recordUndoSelection();
1224 interpretChar(cur, '_');
1227 case LFUN_MATH_SUPERSCRIPT:
1228 // interpret this as if a ^ was typed
1229 cur.recordUndoSelection();
1230 interpretChar(cur, '^');
1233 case LFUN_MATH_MACRO_FOLD:
1234 case LFUN_MATH_MACRO_UNFOLD: {
1236 bool fold = act == LFUN_MATH_MACRO_FOLD;
1237 bool found = findMacroToFoldUnfold(it, fold);
1239 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1240 cur.recordUndoInset();
1249 case LFUN_QUOTE_INSERT:
1250 // interpret this as if a straight " was typed
1251 cur.recordUndoSelection();
1252 interpretChar(cur, '\"');
1255 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1256 // handling such that "self-insert" works on "arbitrary stuff" too, and
1257 // math-insert only handles special math things like "matrix".
1258 case LFUN_MATH_INSERT: {
1259 cur.recordUndoSelection();
1260 if (cmd.argument() == "^" || cmd.argument() == "_")
1261 interpretChar(cur, cmd.argument()[0]);
1264 asArray(cmd.argument(), ar);
1265 if (cur.selection() && ar.size() == 1
1266 && ar[0]->asNestInset()
1267 && ar[0]->asNestInset()->nargs() > 1)
1268 handleNest(cur, ar[0]);
1270 cur.niceInsert(cmd.argument());
1275 case LFUN_UNICODE_INSERT: {
1276 if (cmd.argument().empty())
1278 docstring hexstring = cmd.argument();
1279 if (isHex(hexstring)) {
1280 char_type c = hexToInt(hexstring);
1281 if (c >= 32 && c < 0x10ffff) {
1282 docstring s = docstring(1, c);
1283 FuncCode code = currentMode() == MATH_MODE ?
1284 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1285 lyx::dispatch(FuncRequest(code, s));
1291 case LFUN_DIALOG_SHOW_NEW_INSET: {
1292 docstring const & name = cmd.argument();
1294 if (name == "ref") {
1295 InsetMathRef tmp(buffer_, name);
1296 data = tmp.createDialogStr();
1297 cur.bv().showDialog(to_utf8(name), data);
1298 } else if (name == "mathspace") {
1299 cur.bv().showDialog(to_utf8(name));
1304 case LFUN_INSET_INSERT: {
1306 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1307 cur.recordUndoSelection();
1309 cur.forceBufferUpdate();
1314 case LFUN_INSET_DISSOLVE:
1315 if (!asHullInset()) {
1316 cur.recordUndoInset();
1322 InsetMath::doDispatch(cur, cmd);
1328 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1329 // look for macro to open/close, but stay in mathed
1330 for (; !it.empty(); it.pop_back()) {
1332 // go backward through the current cell
1333 Inset * inset = it.nextInset();
1334 while (inset && inset->asInsetMath()) {
1335 MathMacro * macro = inset->asInsetMath()->asMacro();
1337 // found the an macro to open/close?
1338 if (macro->folded() != fold)
1341 // Wrong folding state.
1342 // If this was the first we see in this slice, look further left,
1344 if (inset != it.nextInset())
1348 // go up if this was the left most position
1354 inset = it.nextInset();
1362 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1363 FuncStatus & flag) const
1365 // the font related toggles
1366 //string tc = "mathnormal";
1368 string const arg = to_utf8(cmd.argument());
1369 switch (cmd.action()) {
1370 case LFUN_INSET_MODIFY:
1371 flag.setEnabled(false);
1374 case LFUN_INSET_MODIFY:
1375 // FIXME: check temporarily disabled
1377 char align = mathcursor::valign();
1378 if (align == '\0') {
1382 if (cmd.argument().empty()) {
1386 if (!contains("tcb", cmd.argument()[0])) {
1390 flag.setOnOff(cmd.argument()[0] == align);
1393 /// We have to handle them since 1.4 blocks all unhandled actions
1394 case LFUN_FONT_ITAL:
1395 case LFUN_FONT_BOLD:
1396 case LFUN_FONT_BOLDSYMBOL:
1397 case LFUN_FONT_SANS:
1398 case LFUN_FONT_EMPH:
1399 case LFUN_FONT_TYPEWRITER:
1400 case LFUN_FONT_NOUN:
1401 case LFUN_FONT_ROMAN:
1402 case LFUN_FONT_DEFAULT:
1403 flag.setEnabled(true);
1406 // we just need to be in math mode to enable that
1407 case LFUN_MATH_SIZE:
1408 case LFUN_MATH_SPACE:
1409 case LFUN_MATH_EXTERN:
1410 flag.setEnabled(true);
1413 case LFUN_FONT_UNDERLINE:
1414 case LFUN_FONT_FRAK:
1415 flag.setEnabled(currentMode() != TEXT_MODE);
1418 case LFUN_MATH_FONT_STYLE: {
1419 bool const textarg =
1420 arg == "textbf" || arg == "textsf" ||
1421 arg == "textrm" || arg == "textmd" ||
1422 arg == "textit" || arg == "textsc" ||
1423 arg == "textsl" || arg == "textup" ||
1424 arg == "texttt" || arg == "textbb" ||
1425 arg == "textnormal";
1426 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1430 case LFUN_MATH_MODE:
1431 // forbid "math-mode on" in math mode to prevent irritating
1432 // behaviour of menu entries (bug 6709)
1433 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1436 case LFUN_MATH_INSERT:
1437 flag.setEnabled(currentMode() != TEXT_MODE);
1440 case LFUN_MATH_AMS_MATRIX:
1441 case LFUN_MATH_MATRIX:
1442 flag.setEnabled(currentMode() == MATH_MODE);
1445 case LFUN_INSET_INSERT: {
1446 // Don't test createMathInset_fromDialogStr(), since
1447 // getStatus is not called with a valid reference and the
1448 // dialog would not be applyable.
1449 string const name = cmd.getArg(0);
1450 flag.setEnabled(name == "ref" || name == "mathspace");
1454 case LFUN_DIALOG_SHOW_NEW_INSET: {
1455 docstring const & name = cmd.argument();
1456 if (name == "space")
1457 flag.setEnabled(false);
1462 case LFUN_MATH_DELIM:
1463 case LFUN_MATH_BIGDELIM:
1464 // Don't do this with multi-cell selections
1465 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1468 case LFUN_MATH_MACRO_FOLD:
1469 case LFUN_MATH_MACRO_UNFOLD: {
1471 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1472 flag.setEnabled(found);
1476 case LFUN_SPECIALCHAR_INSERT:
1477 case LFUN_SCRIPT_INSERT:
1478 // FIXME: These would probably make sense in math-text mode
1479 flag.setEnabled(false);
1482 case LFUN_CAPTION_INSERT:
1483 flag.setEnabled(false);
1486 case LFUN_SPACE_INSERT: {
1487 docstring const & name = cmd.argument();
1488 if (name == "visible")
1489 flag.setEnabled(false);
1493 case LFUN_INSET_DISSOLVE:
1494 flag.setEnabled(!asHullInset());
1498 docstring const & name = cmd.argument();
1499 if (name == "html" || name == "latex")
1500 flag.setEnabled(false);
1512 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1515 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1516 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1517 cur.idx() = enter_front ? 0 : cur.lastidx();
1518 cur.pos() = enter_front ? 0 : cur.lastpos();
1520 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1524 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1527 int dist_min = 1000000;
1528 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1529 int const d = cell(i).dist(cur.bv(), x, y);
1535 MathData & ar = cell(idx_min);
1537 cur.idx() = idx_min;
1538 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1540 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1541 if (dist_min == 0) {
1543 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1544 if (ar[i]->covers(cur.bv(), x, y))
1545 return ar[i].nucleus()->editXY(cur, x, y);
1551 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1553 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1554 BufferView & bv = cur.bv();
1555 if (cmd.button() == mouse_button::button3) {
1556 // Don't do anything if we right-click a
1557 // selection, a context menu will popup.
1558 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1559 && cur < bv.cursor().selectionEnd()) {
1560 cur.noScreenUpdate();
1564 bool do_selection = cmd.button() == mouse_button::button1
1565 && cmd.modifier() == ShiftModifier;
1566 bv.mouseSetCursor(cur, do_selection);
1567 if (cmd.button() == mouse_button::button1) {
1568 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1569 // Update the cursor update flags as needed:
1571 // Update::Decoration: tells to update the decoration
1572 // (visual box corners that define
1574 // Update::FitCursor: adjust the screen to the cursor
1575 // position if needed
1576 // cur.result().update(): don't overwrite previously set flags.
1577 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1578 | cur.result().screenUpdate());
1579 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1580 if (cap::selection()) {
1581 // See comment in Text::dispatch why we do this
1582 cap::copySelectionToStack();
1583 cmd = FuncRequest(LFUN_PASTE, "0");
1584 doDispatch(bv.cursor(), cmd);
1587 asArray(theSelection().get(), ar);
1588 bv.cursor().insert(ar);
1594 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1596 // only select with button 1
1597 if (cmd.button() != mouse_button::button1)
1600 Cursor & bvcur = cur.bv().cursor();
1602 // ignore motions deeper nested than the real anchor
1603 if (!bvcur.realAnchor().hasPart(cur)) {
1608 CursorSlice old = bvcur.top();
1610 // We continue with our existing selection or start a new one, so don't
1611 // reset the anchor.
1612 bvcur.setCursor(cur);
1613 // Did we actually move?
1614 if (cur.top() == old)
1615 // We didn't move one iota, so no need to change selection status
1616 // or update the screen.
1617 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1619 bvcur.setSelection();
1623 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1625 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1627 if (cmd.button() == mouse_button::button1) {
1628 if (!cur.selection())
1629 cur.noScreenUpdate();
1631 Cursor & bvcur = cur.bv().cursor();
1632 bvcur.selection(true);
1641 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1643 //lyxerr << "interpret 2: '" << c << "'" << endl;
1644 docstring save_selection;
1645 if (c == '^' || c == '_')
1646 save_selection = grabAndEraseSelection(cur);
1649 Buffer * buf = cur.buffer();
1652 if (cur.inMacroMode()) {
1653 docstring name = cur.macroName();
1655 /// are we currently typing '#1' or '#2' or...?
1656 if (name == "\\#") {
1659 if (n >= 1 && n <= 9)
1660 cur.insert(new MathMacroArgument(n));
1664 // do not finish macro for known * commands
1665 bool star_macro = c == '*'
1666 && (in_word_set(name.substr(1) + '*')
1667 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1668 if (isAlphaASCII(c) || star_macro) {
1669 cur.activeMacro()->setName(name + docstring(1, c));
1673 // handle 'special char' macros
1678 if (currentMode() <= InsetMath::TEXT_MODE)
1679 cur.niceInsert(createInsetMath("textbackslash", buf));
1681 cur.niceInsert(createInsetMath("backslash", buf));
1682 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1684 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1685 } else if (c == '{' || c == '%') {
1686 //using the saved selection as argument
1687 InsetMathUnknown * p = cur.activeMacro();
1689 MathData sel(cur.buffer());
1690 asArray(p->selection(), sel);
1693 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1695 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1696 } else if (c == '#') {
1697 LASSERT(cur.activeMacro(), return false);
1698 cur.activeMacro()->setName(name + docstring(1, c));
1701 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1706 // One character big delimiters. The others are handled in
1707 // interpretString().
1708 latexkeys const * l = in_word_set(name.substr(1));
1709 if (name[0] == '\\' && l && l->inset == "big") {
1713 delim = from_ascii("\\{");
1716 delim = from_ascii("\\}");
1719 delim = docstring(1, c);
1722 if (InsetMathBig::isBigInsetDelim(delim)) {
1723 // name + delim ared a valid InsetMathBig.
1724 // We can't use cur.macroModeClose() because
1725 // it does not handle delim.
1726 InsetMathUnknown * p = cur.activeMacro();
1729 cur.cell().erase(cur.pos());
1730 cur.plainInsert(MathAtom(
1731 new InsetMathBig(name.substr(1), delim)));
1734 } else if (name == "\\smash" && c == '[') {
1735 // We can't use cur.macroModeClose() because
1736 // it would create an InsetMathPhantom
1737 InsetMathUnknown * p = cur.activeMacro();
1739 interpretChar(cur, c);
1743 // leave macro mode and try again if necessary
1744 if (cur.macroModeClose()) {
1745 MathAtom const atom = cur.prevAtom();
1746 if (atom->asNestInset() && atom->isActive()) {
1748 cur.pushBackward(*cur.nextInset());
1752 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1754 interpretChar(cur, c);
1759 // leave autocorrect mode if necessary
1760 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1761 cur.autocorrect() = false;
1762 cur.message(_("Autocorrect Off ('!' to enter)"));
1765 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1766 cur.autocorrect() = true;
1767 cur.message(_("Autocorrect On (<space> to exit)"));
1771 // just clear selection on pressing the space bar
1772 if (cur.selection() && c == ' ') {
1773 cur.selection(false);
1778 //lyxerr << "starting with macro" << endl;
1779 bool reduced = cap::reduceSelectionToOneCell(cur);
1780 if (reduced || !cur.selection()) {
1781 cur.recordUndoInset();
1782 docstring const safe = cap::grabAndEraseSelection(cur);
1783 if (!cur.inRegexped())
1784 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1786 cur.niceInsert(createInsetMath("backslash", buf));
1794 if (currentMode() <= InsetMath::TEXT_MODE)
1800 if (currentMode() <= InsetMath::TEXT_MODE) {
1801 // insert spaces in text or undecided mode,
1802 // but suppress direct insertion of two spaces in a row
1803 // the still allows typing '<space>a<space>' and deleting the 'a', but
1804 // it is better than nothing...
1805 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1807 // FIXME: we have to enable full redraw here because of the
1808 // visual box corners that define the inset. If we know for
1809 // sure that we stay within the same cell we can optimize for
1811 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1815 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1816 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1817 // FIXME: we have to enable full redraw here because of the
1818 // visual box corners that define the inset. If we know for
1819 // sure that we stay within the same cell we can optimize for
1821 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1825 if (cur.popForward()) {
1826 // FIXME: we have to enable full redraw here because of the
1827 // visual box corners that define the inset. If we know for
1828 // sure that we stay within the same cell we can optimize for
1830 //cur.screenUpdateFlags(Update::FitCursor);
1834 // if we are at the very end, leave the formula
1835 return cur.pos() != cur.lastpos();
1838 // These should be treated differently when not in text mode:
1839 if (cur.inRegexped()) {
1842 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1849 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1852 cur.niceInsert(createInsetMath("sim", buf));
1858 } else if (currentMode() != InsetMath::TEXT_MODE) {
1860 script(cur, false, save_selection);
1864 script(cur, true, save_selection);
1868 cur.niceInsert(createInsetMath("sim", buf));
1871 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1872 MathAtom at = createInsetMath("text", buf);
1873 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1880 cur.niceInsert(createInsetMath("textasciicircum", buf));
1884 cur.niceInsert(createInsetMath("textasciitilde", buf));
1889 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1890 c == '%' || c == '_') {
1891 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1896 // try auto-correction
1897 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1898 && math_autocorrect(cur.prevAtom(), c))
1901 // no special circumstances, so insert the character without any fuss
1903 if (lyxrc.autocorrection_math) {
1904 if (!cur.autocorrect())
1905 cur.message(_("Autocorrect Off ('!' to enter)"));
1907 cur.message(_("Autocorrect On (<space> to exit)"));
1913 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1915 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1917 if (!cur.empty() && cur.pos() > 0 &&
1918 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1919 if (InsetMathBig::isBigInsetDelim(str)) {
1920 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1921 if (prev[0] == '\\') {
1922 prev = prev.substr(1);
1923 latexkeys const * l = in_word_set(prev);
1924 if (l && l->inset == "big") {
1925 cur.cell()[cur.pos() - 1] =
1926 MathAtom(new InsetMathBig(prev, str));
1936 bool InsetMathNest::script(Cursor & cur, bool up)
1938 return script(cur, up, docstring());
1942 bool InsetMathNest::script(Cursor & cur, bool up,
1943 docstring const & save_selection)
1945 // Hack to get \^ and \_ working
1946 //lyxerr << "handling script: up: " << up << endl;
1947 if (cur.inMacroMode() && cur.macroName() == "\\") {
1949 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1951 interpretChar(cur, '_');
1955 cur.macroModeClose();
1956 if (asScriptInset() && cur.idx() == 0) {
1957 // we are in a nucleus of a script inset, move to _our_ script
1958 InsetMathScript * inset = asScriptInset();
1959 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1961 cur.idx() = inset->idxOfScript(up);
1963 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1965 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1968 cur.idx() = inset->idxOfScript(up);
1969 cur.pos() = cur.lastpos();
1971 // convert the thing to our left to a scriptinset or create a new
1972 // one if in the very first position of the array
1973 if (cur.pos() == 0) {
1974 //lyxerr << "new scriptinset" << endl;
1975 cur.insert(new InsetMathScript(buffer_, up));
1977 //lyxerr << "converting prev atom " << endl;
1978 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1981 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1982 // See comment in MathParser.cpp for special handling of {}-bases
1988 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1989 cur.niceInsert(save_selection);
1991 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1996 bool InsetMathNest::completionSupported(Cursor const & cur) const
1998 return cur.inMacroMode();
2002 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2004 return cur.inMacroMode();
2008 bool InsetMathNest::automaticInlineCompletion() const
2010 return lyxrc.completion_inline_math;
2014 bool InsetMathNest::automaticPopupCompletion() const
2016 return lyxrc.completion_popup_math;
2020 CompletionList const *
2021 InsetMathNest::createCompletionList(Cursor const & cur) const
2023 if (!cur.inMacroMode())
2026 return new MathCompletionList(cur);
2030 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2032 if (!cur.inMacroMode())
2035 return cur.activeMacro()->name();
2039 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2042 if (!cur.inMacroMode())
2045 // append completion to active macro
2046 InsetMathUnknown * inset = cur.activeMacro();
2047 inset->setName(inset->name() + s);
2052 // FIXME: this creates duplicates in the completion popup
2053 // which looks ugly. Moreover the changes the list lengths
2055 confuse the popup as well.
2056 MathCompletionList::addToFavorites(inset->name());
2058 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2065 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2066 Dimension & dim) const
2068 Inset const * inset = cur.activeMacro();
2072 // get inset dimensions
2073 dim = cur.bv().coordCache().insets().dim(inset);
2074 // FIXME: these 3 are no accurate, but should depend on the font.
2075 // Now the popup jumps down if you enter a char with descent > 0.
2080 Point xy = cur.bv().coordCache().insets().xy(inset);
2086 bool InsetMathNest::cursorMathForward(Cursor & cur)
2088 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2089 cur.pushBackward(*cur.nextAtom().nucleus());
2090 cur.inset().idxFirst(cur);
2093 if (cur.posForward() || idxForward(cur))
2095 // try to pop forwards --- but don't pop out of math! leave that to
2097 int s = cur.depth() - 2;
2098 if (s >= 0 && cur[s].inset().asInsetMath())
2099 return cur.popForward();
2104 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2106 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2108 cur.push(*cur.nextAtom().nucleus());
2109 cur.inset().idxLast(cur);
2112 if (cur.posBackward() || idxBackward(cur))
2114 // try to pop backwards --- but don't pop out of math! leave that to
2116 int s = cur.depth() - 2;
2117 if (s >= 0 && cur[s].inset().asInsetMath())
2118 return cur.popBackward();
2123 ////////////////////////////////////////////////////////////////////
2125 MathCompletionList::MathCompletionList(Cursor const & cur)
2127 // fill it with macros from the buffer
2128 MacroNameSet macros;
2129 cur.buffer()->listMacroNames(macros);
2130 MacroNameSet::const_iterator it;
2131 for (it = macros.begin(); it != macros.end(); ++it) {
2132 if (cur.buffer()->getMacro(*it, cur, false))
2133 locals.push_back("\\" + *it);
2135 sort(locals.begin(), locals.end());
2137 if (!globals.empty())
2140 // fill in global macros
2142 MacroTable::globalMacros().getMacroNames(macros, false);
2143 //lyxerr << "Globals completion macros: ";
2144 for (it = macros.begin(); it != macros.end(); ++it) {
2145 //lyxerr << "\\" + *it << " ";
2146 globals.push_back("\\" + *it);
2148 //lyxerr << std::endl;
2150 // fill in global commands
2151 globals.push_back(from_ascii("\\boxed"));
2152 globals.push_back(from_ascii("\\fbox"));
2153 globals.push_back(from_ascii("\\framebox"));
2154 globals.push_back(from_ascii("\\makebox"));
2155 globals.push_back(from_ascii("\\kern"));
2156 globals.push_back(from_ascii("\\xhookrightarrow"));
2157 globals.push_back(from_ascii("\\xhookleftarrow"));
2158 globals.push_back(from_ascii("\\xrightarrow"));
2159 globals.push_back(from_ascii("\\xRightarrow"));
2160 globals.push_back(from_ascii("\\xrightharpoondown"));
2161 globals.push_back(from_ascii("\\xrightharpoonup"));
2162 globals.push_back(from_ascii("\\xrightleftharpoons"));
2163 globals.push_back(from_ascii("\\xleftarrow"));
2164 globals.push_back(from_ascii("\\xLeftarrow"));
2165 globals.push_back(from_ascii("\\xleftharpoondown"));
2166 globals.push_back(from_ascii("\\xleftharpoonup"));
2167 globals.push_back(from_ascii("\\xleftrightarrow"));
2168 globals.push_back(from_ascii("\\xLeftrightarrow"));
2169 globals.push_back(from_ascii("\\xleftrightharpoons"));
2170 globals.push_back(from_ascii("\\xmapsto"));
2171 globals.push_back(from_ascii("\\split"));
2172 globals.push_back(from_ascii("\\gathered"));
2173 globals.push_back(from_ascii("\\aligned"));
2174 globals.push_back(from_ascii("\\alignedat"));
2175 globals.push_back(from_ascii("\\cases"));
2176 globals.push_back(from_ascii("\\substack"));
2177 globals.push_back(from_ascii("\\xymatrix"));
2178 globals.push_back(from_ascii("\\Diagram"));
2179 globals.push_back(from_ascii("\\subarray"));
2180 globals.push_back(from_ascii("\\array"));
2181 globals.push_back(from_ascii("\\sqrt"));
2182 globals.push_back(from_ascii("\\root"));
2183 globals.push_back(from_ascii("\\tabular"));
2184 globals.push_back(from_ascii("\\sideset"));
2185 globals.push_back(from_ascii("\\stackrel"));
2186 globals.push_back(from_ascii("\\stackrelthree"));
2187 globals.push_back(from_ascii("\\binom"));
2188 globals.push_back(from_ascii("\\choose"));
2189 globals.push_back(from_ascii("\\brace"));
2190 globals.push_back(from_ascii("\\brack"));
2191 globals.push_back(from_ascii("\\frac"));
2192 globals.push_back(from_ascii("\\over"));
2193 globals.push_back(from_ascii("\\nicefrac"));
2194 globals.push_back(from_ascii("\\unitfrac"));
2195 globals.push_back(from_ascii("\\unitfracthree"));
2196 globals.push_back(from_ascii("\\unitone"));
2197 globals.push_back(from_ascii("\\unittwo"));
2198 globals.push_back(from_ascii("\\infer"));
2199 globals.push_back(from_ascii("\\atop"));
2200 globals.push_back(from_ascii("\\lefteqn"));
2201 globals.push_back(from_ascii("\\boldsymbol"));
2202 globals.push_back(from_ascii("\\bm"));
2203 globals.push_back(from_ascii("\\color"));
2204 globals.push_back(from_ascii("\\normalcolor"));
2205 globals.push_back(from_ascii("\\textcolor"));
2206 globals.push_back(from_ascii("\\cfrac"));
2207 globals.push_back(from_ascii("\\cfracleft"));
2208 globals.push_back(from_ascii("\\cfracright"));
2209 globals.push_back(from_ascii("\\dfrac"));
2210 globals.push_back(from_ascii("\\tfrac"));
2211 globals.push_back(from_ascii("\\dbinom"));
2212 globals.push_back(from_ascii("\\tbinom"));
2213 globals.push_back(from_ascii("\\hphantom"));
2214 globals.push_back(from_ascii("\\phantom"));
2215 globals.push_back(from_ascii("\\vphantom"));
2216 globals.push_back(from_ascii("\\cancel"));
2217 globals.push_back(from_ascii("\\bcancel"));
2218 globals.push_back(from_ascii("\\xcancel"));
2219 globals.push_back(from_ascii("\\cancelto"));
2220 globals.push_back(from_ascii("\\smash"));
2221 globals.push_back(from_ascii("\\mathclap"));
2222 globals.push_back(from_ascii("\\mathllap"));
2223 globals.push_back(from_ascii("\\mathrlap"));
2224 globals.push_back(from_ascii("\\ensuremath"));
2225 MathWordList const & words = mathedWordList();
2226 MathWordList::const_iterator it2;
2227 //lyxerr << "Globals completion commands: ";
2228 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2229 if (it2->second.inset != "macro" && !it2->second.hidden) {
2230 // macros are already read from MacroTable::globalMacros()
2231 globals.push_back('\\' + it2->first);
2232 //lyxerr << '\\' + it2->first << ' ';
2235 //lyxerr << std::endl;
2236 sort(globals.begin(), globals.end());
2240 MathCompletionList::~MathCompletionList()
2245 size_type MathCompletionList::size() const
2247 return locals.size() + globals.size();
2251 docstring const & MathCompletionList::data(size_t idx) const
2253 size_t lsize = locals.size();
2255 return globals[idx - lsize];
2261 std::string MathCompletionList::icon(size_t idx) const
2263 // get the latex command
2265 size_t lsize = locals.size();
2267 cmd = globals[idx - lsize];
2271 // get the icon resource name by stripping the backslash
2272 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2273 if (icon_name.empty())
2274 return std::string();
2275 return "images/math/" + to_utf8(icon_name);
2278 std::vector<docstring> MathCompletionList::globals;