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"
53 #include "MetricsInfo.h"
54 #include "OutputParams.h"
57 #include "frontends/Application.h"
58 #include "frontends/Clipboard.h"
59 #include "frontends/Painter.h"
60 #include "frontends/Selection.h"
62 #include "support/lassert.h"
63 #include "support/debug.h"
64 #include "support/gettext.h"
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
67 #include "support/docstream.h"
73 using namespace lyx::support;
77 using cap::copySelection;
78 using cap::grabAndEraseSelection;
79 using cap::cutSelection;
80 using cap::replaceSelection;
81 using cap::selClearOrDel;
84 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
85 : InsetMath(buf), cells_(nargs), lock_(false)
91 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
92 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
96 InsetMathNest::~InsetMathNest()
98 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
99 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
100 for (; it != end; ++it)
102 it->first->clearLastInset(this);
106 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
108 cells_ = inset.cells_;
110 mouse_hover_.clear();
111 InsetMath::operator=(inset);
116 void InsetMathNest::setBuffer(Buffer & buffer)
118 InsetMath::setBuffer(buffer);
119 for (idx_type i = 0, n = nargs(); i != n; ++i) {
120 MathData & data = cell(i);
121 for (size_t j = 0; j != data.size(); ++j)
122 data[j].nucleus()->setBuffer(buffer);
127 InsetMath::idx_type InsetMathNest::nargs() const
129 return cells_.size();
133 void InsetMathNest::cursorPos(BufferView const & bv,
134 CursorSlice const & sl, bool /*boundary*/,
135 int & x, int & y) const
137 // FIXME: This is a hack. Ideally, the coord cache should not store
138 // absolute positions, but relative ones. This would mean to call
139 // setXY() not in MathData::draw(), but in the parent insets' draw()
140 // with the correctly adjusted x,y values. But this means that we'd have
141 // to touch all (math)inset's draw() methods. Right now, we'll store
142 // absolute value, and make them here relative, only to make them
143 // absolute again when actually drawing the cursor. What a mess.
144 LASSERT(&sl.inset() == this, return);
145 MathData const & ar = sl.cell();
146 CoordCache const & coord_cache = bv.coordCache();
147 if (!coord_cache.getArrays().has(&ar)) {
148 // this can (semi-)legally happen if we just created this cell
149 // and it never has been drawn before. So don't ASSERT.
150 //lyxerr << "no cached data for array " << &ar << endl;
155 Point const pt = coord_cache.getArrays().xy(&ar);
156 if (!coord_cache.getInsets().has(this)) {
158 //lyxerr << "no cached data for inset " << this << endl;
163 Point const pt2 = coord_cache.getInsets().xy(this);
164 //lyxerr << "retrieving position cache for MathData "
165 // << pt.x_ << ' ' << pt.y_ << endl;
166 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
168 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
169 // << " asc: " << ascent() << " des: " << descent()
170 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
171 // move cursor visually into empty cells ("blue rectangles");
177 void InsetMathNest::metrics(MetricsInfo const & mi) const
180 for (idx_type i = 0, n = nargs(); i != n; ++i) {
182 cell(i).metrics(m, dim);
187 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
189 for (idx_type i = 0, n = nargs(); i != n; ++i)
190 cell(i).updateBuffer(it, utype);
195 bool InsetMathNest::idxNext(Cursor & cur) const
197 LASSERT(&cur.inset() == this, return false);
198 if (cur.idx() == cur.lastidx())
206 bool InsetMathNest::idxForward(Cursor & cur) const
212 bool InsetMathNest::idxPrev(Cursor & cur) const
214 LASSERT(&cur.inset() == this, return false);
218 cur.pos() = cur.lastpos();
223 bool InsetMathNest::idxBackward(Cursor & cur) const
229 bool InsetMathNest::idxFirst(Cursor & cur) const
231 LASSERT(&cur.inset() == this, return false);
240 bool InsetMathNest::idxLast(Cursor & cur) const
242 LASSERT(&cur.inset() == this, return false);
245 cur.idx() = cur.lastidx();
246 cur.pos() = cur.lastpos();
251 void InsetMathNest::dump() const
253 odocstringstream oss;
254 TexRow texrow(false);
255 otexrowstream ots(oss,texrow);
257 os << "---------------------------------------------\n";
260 for (idx_type i = 0, n = nargs(); i != n; ++i)
261 os << cell(i) << "\n";
262 os << "---------------------------------------------\n";
263 lyxerr << to_utf8(oss.str());
267 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
271 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
274 setPosCache(pi, x, y);
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 os.pushRowEntry(TexRow::mathEntry(id(),i));
384 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.canBreakLine(os.canBreakLine());
411 if (runparams.lastid != -1) {
412 wi.pushRowEntry(os.texrow().textEntry(runparams.lastid,
418 // Reset parbreak status after a math inset.
420 os.canBreakLine(wi.canBreakLine());
424 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
427 mouse_hover_[bv] = mouse_hover;
432 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
436 MathData & ar = cur.cell();
437 // remove base-only "scripts"
438 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
439 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
440 if (p && p->nargs() == 1) {
441 MathData ar = p->nuc();
444 cur.adjust(i, ar.size() - 1);
448 // glue adjacent font insets of the same kind
449 for (pos_type i = 0; i + 1 < size(); ++i) {
450 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
451 InsetMathFont const * q = operator[](i + 1)->asFontInset();
452 if (p && q && p->name() == q->name()) {
453 p->cell(0).append(q->cell(0));
463 void InsetMathNest::handleFont
464 (Cursor & cur, docstring const & arg, char const * const font)
466 handleFont(cur, arg, from_ascii(font));
470 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
471 docstring const & font)
473 cur.recordUndoSelection();
475 // this whole function is a hack and won't work for incremental font
477 if (cur.inset().asInsetMath()->name() == font)
478 cur.handleFont(to_utf8(font));
480 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
484 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
486 handleNest(cur, nest, docstring());
490 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
491 docstring const & arg)
493 CursorSlice i1 = cur.selBegin();
494 CursorSlice i2 = cur.selEnd();
495 if (!i1.inset().asInsetMath())
497 if (i1.idx() == i2.idx()) {
498 // the easy case where only one cell is selected
499 cur.handleNest(nest);
504 // multiple selected cells in a simple non-grid inset
505 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
506 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
511 cur.pos() = cur.lastpos();
514 // change font of cell
515 cur.handleNest(nest);
518 // cur is in the font inset now. If the loop continues,
519 // we need to get outside again for the next cell
520 if (i + 1 <= i2.idx())
526 // the complicated case with multiple selected cells in a grid
529 cap::region(i1, i2, r1, r2, c1, c2);
530 for (row_type row = r1; row <= r2; ++row) {
531 for (col_type col = c1; col <= c2; ++col) {
533 cur.idx() = i1.asInsetMath()->index(row, col);
536 cur.pos() = cur.lastpos();
540 cur.handleNest(nest);
543 // cur is in the font inset now. If the loop continues,
544 // we need to get outside again for the next cell
545 if (col + 1 <= c2 || row + 1 <= r2)
552 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
554 cur.recordUndoSelection();
557 font.fromString(to_utf8(arg), b);
558 if (font.fontInfo().color() != Color_inherit &&
559 font.fontInfo().color() != Color_ignore)
560 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
562 // FIXME: support other font changes here as well?
566 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
568 //LYXERR0("InsetMathNest: request: " << cmd);
570 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
572 FuncCode const act = cmd.action();
575 case LFUN_CLIPBOARD_PASTE:
576 parseflg |= Parse::VERBATIM;
579 if (cur.currentMode() <= TEXT_MODE)
580 parseflg |= Parse::TEXTMODE;
581 cur.recordUndoSelection();
582 cur.message(_("Paste"));
583 replaceSelection(cur);
585 if (cmd.argument().empty() && !theClipboard().isInternal())
586 topaste = theClipboard().getAsText(Clipboard::PlainTextType);
589 idocstringstream is(cmd.argument());
591 topaste = cap::selection(n, buffer().params().documentClassPtr());
593 cur.niceInsert(topaste, parseflg, false);
594 cur.clearSelection(); // bug 393
595 cur.forceBufferUpdate();
602 cutSelection(cur, true, true);
603 cur.message(_("Cut"));
604 // Prevent stale position >= size crash
605 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
607 cur.forceBufferUpdate();
612 cur.message(_("Copy"));
615 case LFUN_MOUSE_PRESS:
616 lfunMousePress(cur, cmd);
619 case LFUN_MOUSE_MOTION:
620 lfunMouseMotion(cur, cmd);
623 case LFUN_MOUSE_RELEASE:
624 lfunMouseRelease(cur, cmd);
627 case LFUN_FINISHED_LEFT: // in math, left is backwards
628 case LFUN_FINISHED_BACKWARD:
629 cur.bv().cursor() = cur;
632 case LFUN_FINISHED_RIGHT: // in math, right is forward
633 case LFUN_FINISHED_FORWARD:
635 cur.bv().cursor() = cur;
638 case LFUN_CHAR_RIGHT:
640 case LFUN_CHAR_BACKWARD:
641 case LFUN_CHAR_FORWARD:
642 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
644 case LFUN_CHAR_RIGHT_SELECT:
645 case LFUN_CHAR_LEFT_SELECT:
646 case LFUN_CHAR_BACKWARD_SELECT:
647 case LFUN_CHAR_FORWARD_SELECT: {
648 // are we in a selection?
649 bool select = (act == LFUN_CHAR_RIGHT_SELECT
650 || act == LFUN_CHAR_LEFT_SELECT
651 || act == LFUN_CHAR_BACKWARD_SELECT
652 || act == LFUN_CHAR_FORWARD_SELECT);
653 // are we moving forward or backwards?
654 // If the command was RIGHT or LEFT, then whether we're moving forward
655 // or backwards depends on the cursor movement mode (logical or visual):
656 // * in visual mode, since math is always LTR, right -> forward,
658 // * in logical mode, the mapping is determined by the
659 // reverseDirectionNeeded() function
662 FuncCode finish_lfun;
664 if (act == LFUN_CHAR_FORWARD
665 || act == LFUN_CHAR_FORWARD_SELECT) {
667 finish_lfun = LFUN_FINISHED_FORWARD;
669 else if (act == LFUN_CHAR_BACKWARD
670 || act == LFUN_CHAR_BACKWARD_SELECT) {
672 finish_lfun = LFUN_FINISHED_BACKWARD;
675 bool right = (act == LFUN_CHAR_RIGHT_SELECT
676 || act == LFUN_CHAR_RIGHT);
677 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
683 finish_lfun = LFUN_FINISHED_RIGHT;
685 finish_lfun = LFUN_FINISHED_LEFT;
687 // Now that we know exactly what we want to do, let's do it!
688 cur.selHandle(select);
690 cur.macroModeClose();
691 // try moving forward or backwards as necessary...
692 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
693 // ... and if movement failed, then finish forward or backwards
695 cmd = FuncRequest(finish_lfun);
703 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
705 case LFUN_DOWN_SELECT:
706 case LFUN_UP_SELECT: {
707 // close active macro
708 if (cur.inMacroMode()) {
709 cur.macroModeClose();
713 // stop/start the selection
714 bool select = act == LFUN_DOWN_SELECT ||
715 act == LFUN_UP_SELECT;
716 cur.selHandle(select);
718 // handle autocorrect:
719 if (lyxrc.autocorrection_math && cur.autocorrect()) {
720 cur.autocorrect() = false;
721 cur.message(_("Autocorrect Off ('!' to enter)"));
725 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
726 bool successful = cur.upDownInMath(up);
730 if (cur.fixIfBroken())
731 // FIXME: Something bad happened. We pass the corrected Cursor
732 // instead of letting things go worse.
735 // We did not manage to move the cursor.
740 case LFUN_MOUSE_DOUBLE:
741 case LFUN_WORD_SELECT:
745 cur.pos() = cur.lastpos();
746 cur.bv().cursor() = cur;
749 case LFUN_MOUSE_TRIPLE:
754 cur.idx() = cur.lastidx();
755 cur.pos() = cur.lastpos();
756 cur.bv().cursor() = cur;
759 case LFUN_PARAGRAPH_UP:
760 case LFUN_PARAGRAPH_DOWN:
761 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
763 case LFUN_PARAGRAPH_UP_SELECT:
764 case LFUN_PARAGRAPH_DOWN_SELECT:
767 case LFUN_LINE_BEGIN:
768 case LFUN_WORD_BACKWARD:
770 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
772 case LFUN_LINE_BEGIN_SELECT:
773 case LFUN_WORD_BACKWARD_SELECT:
774 case LFUN_WORD_LEFT_SELECT:
775 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
776 act == LFUN_WORD_LEFT_SELECT ||
777 act == LFUN_LINE_BEGIN_SELECT);
778 cur.macroModeClose();
779 if (cur.pos() != 0) {
781 } else if (cur.col() != 0) {
782 cur.idx() -= cur.col();
784 } else if (cur.idx() != 0) {
788 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
793 case LFUN_WORD_FORWARD:
794 case LFUN_WORD_RIGHT:
796 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
798 case LFUN_WORD_FORWARD_SELECT:
799 case LFUN_WORD_RIGHT_SELECT:
800 case LFUN_LINE_END_SELECT:
801 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
802 act == LFUN_WORD_RIGHT_SELECT ||
803 act == LFUN_LINE_END_SELECT);
804 cur.macroModeClose();
806 if (cur.pos() != cur.lastpos()) {
807 cur.pos() = cur.lastpos();
808 } else if (ncols() && (cur.col() != cur.lastcol())) {
809 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
810 cur.pos() = cur.lastpos();
811 } else if (cur.idx() != cur.lastidx()) {
812 cur.idx() = cur.lastidx();
813 cur.pos() = cur.lastpos();
815 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
820 case LFUN_CELL_FORWARD:
821 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
822 cur.inset().idxNext(cur);
825 case LFUN_CELL_BACKWARD:
826 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
827 cur.inset().idxPrev(cur);
830 case LFUN_WORD_DELETE_BACKWARD:
831 case LFUN_CHAR_DELETE_BACKWARD:
833 // May affect external cell:
834 cur.recordUndoInset();
835 else if (!cur.inMacroMode())
836 cur.recordUndoSelection();
837 // if the inset can not be removed from within, delete it
838 if (!cur.backspace()) {
839 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
840 cur.innerText()->dispatch(cur, cmd);
844 case LFUN_WORD_DELETE_FORWARD:
845 case LFUN_CHAR_DELETE_FORWARD:
846 if (cur.pos() == cur.lastpos())
847 // May affect external cell:
848 cur.recordUndoInset();
850 cur.recordUndoSelection();
851 // if the inset can not be removed from within, delete it
853 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
854 cur.innerText()->dispatch(cur, cmd);
860 cur.clearSelection();
862 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
867 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
868 // that is traversed by a single <CursorLeft>/<CursorRight>.
869 case LFUN_INSET_TOGGLE:
875 case LFUN_SELF_INSERT:
876 if (cmd.argument().size() != 1) {
877 cur.recordUndoSelection();
878 docstring const arg = cmd.argument();
879 if (!interpretString(cur, arg))
883 // Don't record undo steps if we are in macro mode and thus
884 // cmd.argument is the next character of the macro name.
885 // Otherwise we'll get an invalid cursor if we undo after
886 // the macro was finished and the macro is a known command,
887 // e.g. sqrt. Cursor::macroModeClose replaces in this case
888 // the InsetMathUnknown with name "frac" by an empty
889 // InsetMathFrac -> a pos value > 0 is invalid.
890 // A side effect is that an undo before the macro is finished
891 // undoes the complete macro, not only the last character.
892 // At the time we hit '\' we are not in macro mode, still.
893 if (!cur.inMacroMode())
894 cur.recordUndoSelection();
896 // spacial handling of space. If we insert an inset
897 // via macro mode, we want to put the cursor inside it
898 // if relevant. Think typing "\frac<space>".
899 if (cmd.argument()[0] == ' '
900 && cur.inMacroMode() && cur.macroName() != "\\"
901 && cur.macroModeClose() && cur.pos() > 0) {
902 MathAtom const atom = cur.prevAtom();
903 if (atom->asNestInset() && atom->isActive()) {
905 cur.pushBackward(*cur.nextInset());
907 } else if (!interpretChar(cur, cmd.argument()[0])) {
908 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
913 //case LFUN_SERVER_GET_XY:
916 case LFUN_SERVER_SET_XY: {
917 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
920 istringstream is(to_utf8(cmd.argument()));
922 cur.setScreenPos(x, y);
926 // Special casing for superscript in case of LyX handling
928 case LFUN_ACCENT_CIRCUMFLEX:
929 if (cmd.argument().empty()) {
930 // do superscript if LyX handles
932 cur.recordUndoSelection();
933 script(cur, true, grabAndEraseSelection(cur));
937 case LFUN_ACCENT_UMLAUT:
938 case LFUN_ACCENT_ACUTE:
939 case LFUN_ACCENT_GRAVE:
940 case LFUN_ACCENT_BREVE:
941 case LFUN_ACCENT_DOT:
942 case LFUN_ACCENT_MACRON:
943 case LFUN_ACCENT_CARON:
944 case LFUN_ACCENT_TILDE:
945 case LFUN_ACCENT_CEDILLA:
946 case LFUN_ACCENT_CIRCLE:
947 case LFUN_ACCENT_UNDERDOT:
948 case LFUN_ACCENT_TIE:
949 case LFUN_ACCENT_OGONEK:
950 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
954 case LFUN_TEXTSTYLE_APPLY:
955 case LFUN_TEXTSTYLE_UPDATE:
956 handleFont2(cur, cmd.argument());
960 if (currentMode() <= TEXT_MODE)
961 handleFont(cur, cmd.argument(), "textbf");
963 handleFont(cur, cmd.argument(), "mathbf");
965 case LFUN_FONT_BOLDSYMBOL:
966 if (currentMode() <= TEXT_MODE)
967 handleFont(cur, cmd.argument(), "textbf");
969 handleFont(cur, cmd.argument(), "boldsymbol");
972 if (currentMode() <= TEXT_MODE)
973 handleFont(cur, cmd.argument(), "textsf");
975 handleFont(cur, cmd.argument(), "mathsf");
978 if (currentMode() <= TEXT_MODE)
979 handleFont(cur, cmd.argument(), "emph");
981 handleFont(cur, cmd.argument(), "mathcal");
983 case LFUN_FONT_ROMAN:
984 if (currentMode() <= TEXT_MODE)
985 handleFont(cur, cmd.argument(), "textrm");
987 handleFont(cur, cmd.argument(), "mathrm");
989 case LFUN_FONT_TYPEWRITER:
990 if (currentMode() <= TEXT_MODE)
991 handleFont(cur, cmd.argument(), "texttt");
993 handleFont(cur, cmd.argument(), "mathtt");
996 handleFont(cur, cmd.argument(), "mathfrak");
999 if (currentMode() <= TEXT_MODE)
1000 handleFont(cur, cmd.argument(), "textit");
1002 handleFont(cur, cmd.argument(), "mathit");
1004 case LFUN_FONT_NOUN:
1005 if (currentMode() <= TEXT_MODE)
1006 // FIXME: should be "noun"
1007 handleFont(cur, cmd.argument(), "textsc");
1009 handleFont(cur, cmd.argument(), "mathbb");
1011 case LFUN_FONT_DEFAULT:
1012 handleFont(cur, cmd.argument(), "textnormal");
1014 case LFUN_FONT_UNDERLINE:
1016 cur.handleNest(createInsetMath("underline", cur.buffer()));
1019 case LFUN_MATH_MODE: {
1021 // ignore math-mode on when already in math mode
1022 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1024 cur.recordUndoSelection();
1025 cur.macroModeClose();
1026 docstring const save_selection = grabAndEraseSelection(cur);
1028 if (currentMode() <= Inset::TEXT_MODE)
1029 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1031 cur.plainInsert(createInsetMath("text", buffer_));
1033 cur.pushBackward(*cur.nextInset());
1034 cur.niceInsert(save_selection);
1035 cur.forceBufferUpdate();
1037 if (currentMode() == Inset::TEXT_MODE) {
1038 cur.recordUndoSelection();
1039 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1040 cur.message(_("create new math text environment ($...$)"));
1042 handleFont(cur, cmd.argument(), "textrm");
1043 cur.message(_("entered math text mode (textrm)"));
1049 case LFUN_REGEXP_MODE: {
1050 InsetMath * im = cur.inset().asInsetMath();
1052 InsetMathHull * i = im->asHullInset();
1053 if (i && i->getType() == hullRegexp) {
1054 cur.message(_("Already in regular expression mode"));
1058 cur.macroModeClose();
1059 docstring const save_selection = grabAndEraseSelection(cur);
1061 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1063 cur.pushBackward(*cur.nextInset());
1064 cur.niceInsert(save_selection);
1065 cur.message(_("Regular expression editor mode"));
1069 case LFUN_MATH_FONT_STYLE: {
1070 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1071 doDispatch(cur, fr);
1075 case LFUN_MATH_SIZE: {
1076 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1077 doDispatch(cur, fr);
1081 case LFUN_MATH_MATRIX: {
1087 idocstringstream is(cmd.argument());
1088 is >> m >> n >> v_align >> h_align;
1094 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1095 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1099 case LFUN_MATH_AMS_MATRIX: {
1103 docstring name = from_ascii("matrix");
1104 idocstringstream is(cmd.argument());
1105 is >> m >> n >> name;
1110 // check if we have a valid decoration
1111 if (name != "pmatrix" && name != "bmatrix"
1112 && name != "Bmatrix" && name != "vmatrix"
1113 && name != "Vmatrix" && name != "matrix")
1114 name = from_ascii("matrix");
1117 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1121 case LFUN_MATH_DELIM: {
1123 docstring rs = split(cmd.argument(), ls, ' ');
1124 // Reasonable default values
1130 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1134 case LFUN_MATH_BIGDELIM: {
1135 docstring const lname = from_utf8(cmd.getArg(0));
1136 docstring const ldelim = from_utf8(cmd.getArg(1));
1137 docstring const rname = from_utf8(cmd.getArg(2));
1138 docstring const rdelim = from_utf8(cmd.getArg(3));
1139 latexkeys const * l = in_word_set(lname);
1140 bool const have_l = l && l->inset == "big" &&
1141 InsetMathBig::isBigInsetDelim(ldelim);
1142 l = in_word_set(rname);
1143 bool const have_r = l && l->inset == "big" &&
1144 InsetMathBig::isBigInsetDelim(rdelim);
1145 // We mimic LFUN_MATH_DELIM in case we have an empty left
1146 // or right delimiter.
1147 if (have_l || have_r) {
1149 docstring const selection = grabAndEraseSelection(cur);
1152 cur.insert(MathAtom(new InsetMathBig(lname,
1154 // first insert the right delimiter and then go back
1155 // and re-insert the selection (bug 7088)
1157 cur.insert(MathAtom(new InsetMathBig(rname,
1161 cur.niceInsert(selection);
1163 // Don't call cur.undispatched() if we did nothing, this would
1164 // lead to infinite recursion via Text::dispatch().
1168 case LFUN_SPACE_INSERT: {
1169 cur.recordUndoSelection();
1170 string const name = cmd.getArg(0);
1171 if (name == "normal")
1172 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1173 else if (name == "protected")
1174 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1175 else if (name == "thin" || name == "med" || name == "thick")
1176 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1177 else if (name == "hfill*")
1178 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1179 else if (name == "quad" || name == "qquad" ||
1180 name == "enspace" || name == "enskip" ||
1181 name == "negthinspace" || name == "negmedspace" ||
1182 name == "negthickspace" || name == "hfill")
1183 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1184 else if (name == "hspace" || name == "hspace*") {
1185 string const len = cmd.getArg(1);
1186 if (len.empty() || !isValidLength(len)) {
1187 lyxerr << "LyX function 'space-insert " << name << "' "
1188 "needs a valid length argument." << endl;
1191 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1193 cur.insert(MathAtom(new InsetMathSpace));
1197 case LFUN_MATH_SPACE:
1198 cur.recordUndoSelection();
1199 if (cmd.argument().empty())
1200 cur.insert(MathAtom(new InsetMathSpace));
1202 string const name = cmd.getArg(0);
1203 string const len = cmd.getArg(1);
1204 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1208 case LFUN_ERT_INSERT:
1209 // interpret this as if a backslash was typed
1211 interpretChar(cur, '\\');
1214 case LFUN_MATH_SUBSCRIPT:
1215 // interpret this as if a _ was typed
1216 cur.recordUndoSelection();
1217 interpretChar(cur, '_');
1220 case LFUN_MATH_SUPERSCRIPT:
1221 // interpret this as if a ^ was typed
1222 cur.recordUndoSelection();
1223 interpretChar(cur, '^');
1226 case LFUN_MATH_MACRO_FOLD:
1227 case LFUN_MATH_MACRO_UNFOLD: {
1229 bool fold = act == LFUN_MATH_MACRO_FOLD;
1230 bool found = findMacroToFoldUnfold(it, fold);
1232 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1233 cur.recordUndoInset();
1242 case LFUN_QUOTE_INSERT:
1243 // interpret this as if a straight " was typed
1244 cur.recordUndoSelection();
1245 interpretChar(cur, '\"');
1248 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1249 // handling such that "self-insert" works on "arbitrary stuff" too, and
1250 // math-insert only handles special math things like "matrix".
1251 case LFUN_MATH_INSERT: {
1252 cur.recordUndoSelection();
1253 if (cmd.argument() == "^" || cmd.argument() == "_")
1254 interpretChar(cur, cmd.argument()[0]);
1257 asArray(cmd.argument(), ar);
1258 if (cur.selection() && ar.size() == 1
1259 && ar[0]->asNestInset()
1260 && ar[0]->asNestInset()->nargs() > 1)
1261 handleNest(cur, ar[0]);
1263 cur.niceInsert(cmd.argument());
1268 case LFUN_UNICODE_INSERT: {
1269 if (cmd.argument().empty())
1271 docstring hexstring = cmd.argument();
1272 if (isHex(hexstring)) {
1273 char_type c = hexToInt(hexstring);
1274 if (c >= 32 && c < 0x10ffff) {
1275 docstring s = docstring(1, c);
1276 FuncCode code = currentMode() == MATH_MODE ?
1277 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1278 lyx::dispatch(FuncRequest(code, s));
1284 case LFUN_DIALOG_SHOW_NEW_INSET: {
1285 docstring const & name = cmd.argument();
1287 if (name == "ref") {
1288 InsetMathRef tmp(buffer_, name);
1289 data = tmp.createDialogStr();
1290 cur.bv().showDialog(to_utf8(name), data);
1291 } else if (name == "mathspace") {
1292 cur.bv().showDialog(to_utf8(name));
1297 case LFUN_INSET_INSERT: {
1299 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1300 cur.recordUndoSelection();
1302 cur.forceBufferUpdate();
1307 case LFUN_INSET_DISSOLVE:
1308 if (!asHullInset()) {
1309 cur.recordUndoInset();
1315 InsetMath::doDispatch(cur, cmd);
1321 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1322 // look for macro to open/close, but stay in mathed
1323 for (; !it.empty(); it.pop_back()) {
1325 // go backward through the current cell
1326 Inset * inset = it.nextInset();
1327 while (inset && inset->asInsetMath()) {
1328 MathMacro * macro = inset->asInsetMath()->asMacro();
1330 // found the an macro to open/close?
1331 if (macro->folded() != fold)
1334 // Wrong folding state.
1335 // If this was the first we see in this slice, look further left,
1337 if (inset != it.nextInset())
1341 // go up if this was the left most position
1347 inset = it.nextInset();
1355 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1356 FuncStatus & flag) const
1358 // the font related toggles
1359 //string tc = "mathnormal";
1361 string const arg = to_utf8(cmd.argument());
1362 switch (cmd.action()) {
1363 case LFUN_INSET_MODIFY:
1364 flag.setEnabled(false);
1367 case LFUN_INSET_MODIFY:
1368 // FIXME: check temporarily disabled
1370 char align = mathcursor::valign();
1371 if (align == '\0') {
1375 if (cmd.argument().empty()) {
1379 if (!contains("tcb", cmd.argument()[0])) {
1383 flag.setOnOff(cmd.argument()[0] == align);
1386 /// We have to handle them since 1.4 blocks all unhandled actions
1387 case LFUN_FONT_ITAL:
1388 case LFUN_FONT_BOLD:
1389 case LFUN_FONT_BOLDSYMBOL:
1390 case LFUN_FONT_SANS:
1391 case LFUN_FONT_EMPH:
1392 case LFUN_FONT_TYPEWRITER:
1393 case LFUN_FONT_NOUN:
1394 case LFUN_FONT_ROMAN:
1395 case LFUN_FONT_DEFAULT:
1396 flag.setEnabled(true);
1399 // we just need to be in math mode to enable that
1400 case LFUN_MATH_SIZE:
1401 case LFUN_MATH_SPACE:
1402 case LFUN_MATH_EXTERN:
1403 flag.setEnabled(true);
1406 case LFUN_FONT_UNDERLINE:
1407 case LFUN_FONT_FRAK:
1408 flag.setEnabled(currentMode() != TEXT_MODE);
1411 case LFUN_MATH_FONT_STYLE: {
1412 bool const textarg =
1413 arg == "textbf" || arg == "textsf" ||
1414 arg == "textrm" || arg == "textmd" ||
1415 arg == "textit" || arg == "textsc" ||
1416 arg == "textsl" || arg == "textup" ||
1417 arg == "texttt" || arg == "textbb" ||
1418 arg == "textnormal";
1419 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1423 case LFUN_MATH_MODE:
1424 // forbid "math-mode on" in math mode to prevent irritating
1425 // behaviour of menu entries (bug 6709)
1426 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1429 case LFUN_MATH_INSERT:
1430 flag.setEnabled(currentMode() != TEXT_MODE);
1433 case LFUN_MATH_AMS_MATRIX:
1434 case LFUN_MATH_MATRIX:
1435 flag.setEnabled(currentMode() == MATH_MODE);
1438 case LFUN_INSET_INSERT: {
1439 // Don't test createMathInset_fromDialogStr(), since
1440 // getStatus is not called with a valid reference and the
1441 // dialog would not be applyable.
1442 string const name = cmd.getArg(0);
1443 flag.setEnabled(name == "ref" || name == "mathspace");
1447 case LFUN_DIALOG_SHOW_NEW_INSET: {
1448 docstring const & name = cmd.argument();
1449 if (name == "space")
1450 flag.setEnabled(false);
1455 case LFUN_MATH_DELIM:
1456 case LFUN_MATH_BIGDELIM:
1457 // Don't do this with multi-cell selections
1458 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1461 case LFUN_MATH_MACRO_FOLD:
1462 case LFUN_MATH_MACRO_UNFOLD: {
1464 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1465 flag.setEnabled(found);
1469 case LFUN_SPECIALCHAR_INSERT:
1470 case LFUN_SCRIPT_INSERT:
1471 // FIXME: These would probably make sense in math-text mode
1472 flag.setEnabled(false);
1475 case LFUN_CAPTION_INSERT:
1476 flag.setEnabled(false);
1479 case LFUN_SPACE_INSERT: {
1480 docstring const & name = cmd.argument();
1481 if (name == "visible")
1482 flag.setEnabled(false);
1486 case LFUN_INSET_DISSOLVE:
1487 flag.setEnabled(!asHullInset());
1491 docstring const & name = cmd.argument();
1492 if (name == "html" || name == "latex")
1493 flag.setEnabled(false);
1505 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1508 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1509 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1510 cur.idx() = enter_front ? 0 : cur.lastidx();
1511 cur.pos() = enter_front ? 0 : cur.lastpos();
1513 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1517 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1520 int dist_min = 1000000;
1521 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1522 int const d = cell(i).dist(cur.bv(), x, y);
1528 MathData & ar = cell(idx_min);
1530 cur.idx() = idx_min;
1531 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1533 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1534 if (dist_min == 0) {
1536 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1537 if (ar[i]->covers(cur.bv(), x, y))
1538 return ar[i].nucleus()->editXY(cur, x, y);
1544 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1546 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1547 BufferView & bv = cur.bv();
1548 if (cmd.button() == mouse_button::button3) {
1549 // Don't do anything if we right-click a
1550 // selection, a context menu will popup.
1551 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1552 && cur < bv.cursor().selectionEnd()) {
1553 cur.noScreenUpdate();
1557 bool do_selection = cmd.button() == mouse_button::button1
1558 && cmd.argument() == "region-select";
1559 bv.mouseSetCursor(cur, do_selection);
1560 if (cmd.button() == mouse_button::button1) {
1561 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1562 // Update the cursor update flags as needed:
1564 // Update::Decoration: tells to update the decoration
1565 // (visual box corners that define
1567 // Update::FitCursor: adjust the screen to the cursor
1568 // position if needed
1569 // cur.result().update(): don't overwrite previously set flags.
1570 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1571 | cur.result().screenUpdate());
1572 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1573 if (cap::selection()) {
1574 // See comment in Text::dispatch why we do this
1575 cap::copySelectionToStack();
1576 cmd = FuncRequest(LFUN_PASTE, "0");
1577 doDispatch(bv.cursor(), cmd);
1580 asArray(theSelection().get(), ar);
1581 bv.cursor().insert(ar);
1587 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1589 // only select with button 1
1590 if (cmd.button() != mouse_button::button1)
1593 Cursor & bvcur = cur.bv().cursor();
1595 // ignore motions deeper nested than the real anchor
1596 if (!bvcur.realAnchor().hasPart(cur)) {
1601 CursorSlice old = bvcur.top();
1603 // We continue with our existing selection or start a new one, so don't
1604 // reset the anchor.
1605 bvcur.setCursor(cur);
1606 // Did we actually move?
1607 if (cur.top() == old)
1608 // We didn't move one iota, so no need to change selection status
1609 // or update the screen.
1610 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1612 bvcur.setSelection();
1616 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1618 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1620 if (cmd.button() == mouse_button::button1) {
1621 if (!cur.selection())
1622 cur.noScreenUpdate();
1624 Cursor & bvcur = cur.bv().cursor();
1625 bvcur.selection(true);
1634 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1636 //lyxerr << "interpret 2: '" << c << "'" << endl;
1637 docstring save_selection;
1638 if (c == '^' || c == '_')
1639 save_selection = grabAndEraseSelection(cur);
1642 Buffer * buf = cur.buffer();
1645 if (cur.inMacroMode()) {
1646 docstring name = cur.macroName();
1648 /// are we currently typing '#1' or '#2' or...?
1649 if (name == "\\#") {
1652 if (n >= 1 && n <= 9)
1653 cur.insert(new MathMacroArgument(n));
1657 // do not finish macro for known * commands
1658 bool star_macro = c == '*'
1659 && (in_word_set(name.substr(1) + '*')
1660 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1661 if (isAlphaASCII(c) || star_macro) {
1662 cur.activeMacro()->setName(name + docstring(1, c));
1666 // handle 'special char' macros
1671 if (currentMode() <= InsetMath::TEXT_MODE)
1672 cur.niceInsert(createInsetMath("textbackslash", buf));
1674 cur.niceInsert(createInsetMath("backslash", buf));
1675 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1677 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1678 } else if (c == '{' || c == '%') {
1679 //using the saved selection as argument
1680 InsetMathUnknown * p = cur.activeMacro();
1682 MathData sel(cur.buffer());
1683 asArray(p->selection(), sel);
1686 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1688 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1689 } else if (c == '#') {
1690 LASSERT(cur.activeMacro(), return false);
1691 cur.activeMacro()->setName(name + docstring(1, c));
1694 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1699 // One character big delimiters. The others are handled in
1700 // interpretString().
1701 latexkeys const * l = in_word_set(name.substr(1));
1702 if (name[0] == '\\' && l && l->inset == "big") {
1706 delim = from_ascii("\\{");
1709 delim = from_ascii("\\}");
1712 delim = docstring(1, c);
1715 if (InsetMathBig::isBigInsetDelim(delim)) {
1716 // name + delim ared a valid InsetMathBig.
1717 // We can't use cur.macroModeClose() because
1718 // it does not handle delim.
1719 InsetMathUnknown * p = cur.activeMacro();
1722 cur.cell().erase(cur.pos());
1723 cur.plainInsert(MathAtom(
1724 new InsetMathBig(name.substr(1), delim)));
1727 } else if (name == "\\smash" && c == '[') {
1728 // We can't use cur.macroModeClose() because
1729 // it would create an InsetMathPhantom
1730 InsetMathUnknown * p = cur.activeMacro();
1732 interpretChar(cur, c);
1736 // leave macro mode and try again if necessary
1737 if (cur.macroModeClose()) {
1738 MathAtom const atom = cur.prevAtom();
1739 if (atom->asNestInset() && atom->isActive()) {
1741 cur.pushBackward(*cur.nextInset());
1745 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1747 interpretChar(cur, c);
1752 // leave autocorrect mode if necessary
1753 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1754 cur.autocorrect() = false;
1755 cur.message(_("Autocorrect Off ('!' to enter)"));
1758 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1759 cur.autocorrect() = true;
1760 cur.message(_("Autocorrect On (<space> to exit)"));
1764 // just clear selection on pressing the space bar
1765 if (cur.selection() && c == ' ') {
1766 cur.selection(false);
1771 //lyxerr << "starting with macro" << endl;
1772 bool reduced = cap::reduceSelectionToOneCell(cur);
1773 if (reduced || !cur.selection()) {
1774 cur.recordUndoInset();
1775 docstring const safe = cap::grabAndEraseSelection(cur);
1776 if (!cur.inRegexped())
1777 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1779 cur.niceInsert(createInsetMath("backslash", buf));
1787 if (currentMode() <= InsetMath::TEXT_MODE)
1793 if (currentMode() <= InsetMath::TEXT_MODE) {
1794 // insert spaces in text or undecided mode,
1795 // but suppress direct insertion of two spaces in a row
1796 // the still allows typing '<space>a<space>' and deleting the 'a', but
1797 // it is better than nothing...
1798 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1800 // FIXME: we have to enable full redraw here because of the
1801 // visual box corners that define the inset. If we know for
1802 // sure that we stay within the same cell we can optimize for
1804 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1808 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1809 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1810 // FIXME: we have to enable full redraw here because of the
1811 // visual box corners that define the inset. If we know for
1812 // sure that we stay within the same cell we can optimize for
1814 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1818 if (cur.popForward()) {
1819 // FIXME: we have to enable full redraw here because of the
1820 // visual box corners that define the inset. If we know for
1821 // sure that we stay within the same cell we can optimize for
1823 //cur.screenUpdateFlags(Update::FitCursor);
1827 // if we are at the very end, leave the formula
1828 return cur.pos() != cur.lastpos();
1831 // These should be treated differently when not in text mode:
1832 if (cur.inRegexped()) {
1835 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1842 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1845 cur.niceInsert(createInsetMath("sim", buf));
1851 } else if (currentMode() != InsetMath::TEXT_MODE) {
1853 script(cur, false, save_selection);
1857 script(cur, true, save_selection);
1861 cur.niceInsert(createInsetMath("sim", buf));
1864 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1865 MathAtom at = createInsetMath("text", buf);
1866 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1873 cur.niceInsert(createInsetMath("textasciicircum", buf));
1877 cur.niceInsert(createInsetMath("textasciitilde", buf));
1882 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1883 c == '%' || c == '_') {
1884 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1889 // try auto-correction
1890 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1891 && math_autocorrect(cur.prevAtom(), c))
1894 // no special circumstances, so insert the character without any fuss
1896 if (lyxrc.autocorrection_math) {
1897 if (!cur.autocorrect())
1898 cur.message(_("Autocorrect Off ('!' to enter)"));
1900 cur.message(_("Autocorrect On (<space> to exit)"));
1906 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1908 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1910 if (!cur.empty() && cur.pos() > 0 &&
1911 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1912 if (InsetMathBig::isBigInsetDelim(str)) {
1913 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1914 if (prev[0] == '\\') {
1915 prev = prev.substr(1);
1916 latexkeys const * l = in_word_set(prev);
1917 if (l && l->inset == "big") {
1918 cur.cell()[cur.pos() - 1] =
1919 MathAtom(new InsetMathBig(prev, str));
1929 bool InsetMathNest::script(Cursor & cur, bool up)
1931 return script(cur, up, docstring());
1935 bool InsetMathNest::script(Cursor & cur, bool up,
1936 docstring const & save_selection)
1938 // Hack to get \^ and \_ working
1939 //lyxerr << "handling script: up: " << up << endl;
1940 if (cur.inMacroMode() && cur.macroName() == "\\") {
1942 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1944 interpretChar(cur, '_');
1948 cur.macroModeClose();
1949 if (asScriptInset() && cur.idx() == 0) {
1950 // we are in a nucleus of a script inset, move to _our_ script
1951 InsetMathScript * inset = asScriptInset();
1952 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1954 cur.idx() = inset->idxOfScript(up);
1956 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1958 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1961 cur.idx() = inset->idxOfScript(up);
1962 cur.pos() = cur.lastpos();
1964 // convert the thing to our left to a scriptinset or create a new
1965 // one if in the very first position of the array
1966 if (cur.pos() == 0) {
1967 //lyxerr << "new scriptinset" << endl;
1968 cur.insert(new InsetMathScript(buffer_, up));
1970 //lyxerr << "converting prev atom " << endl;
1971 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1974 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1975 // See comment in MathParser.cpp for special handling of {}-bases
1981 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1982 cur.niceInsert(save_selection);
1984 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1989 bool InsetMathNest::completionSupported(Cursor const & cur) const
1991 return cur.inMacroMode();
1995 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1997 return cur.inMacroMode();
2001 bool InsetMathNest::automaticInlineCompletion() const
2003 return lyxrc.completion_inline_math;
2007 bool InsetMathNest::automaticPopupCompletion() const
2009 return lyxrc.completion_popup_math;
2013 CompletionList const *
2014 InsetMathNest::createCompletionList(Cursor const & cur) const
2016 if (!cur.inMacroMode())
2019 return new MathCompletionList(cur);
2023 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2025 if (!cur.inMacroMode())
2028 return cur.activeMacro()->name();
2032 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2035 if (!cur.inMacroMode())
2038 // append completion to active macro
2039 InsetMathUnknown * inset = cur.activeMacro();
2040 inset->setName(inset->name() + s);
2045 // FIXME: this creates duplicates in the completion popup
2046 // which looks ugly. Moreover the changes the list lengths
2048 confuse the popup as well.
2049 MathCompletionList::addToFavorites(inset->name());
2051 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2058 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2059 Dimension & dim) const
2061 Inset const * inset = cur.activeMacro();
2065 // get inset dimensions
2066 dim = cur.bv().coordCache().insets().dim(inset);
2067 // FIXME: these 3 are no accurate, but should depend on the font.
2068 // Now the popup jumps down if you enter a char with descent > 0.
2073 Point xy = cur.bv().coordCache().insets().xy(inset);
2079 bool InsetMathNest::cursorMathForward(Cursor & cur)
2081 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2082 cur.pushBackward(*cur.nextAtom().nucleus());
2083 cur.inset().idxFirst(cur);
2086 if (cur.posForward() || idxForward(cur))
2088 // try to pop forwards --- but don't pop out of math! leave that to
2090 int s = cur.depth() - 2;
2091 if (s >= 0 && cur[s].inset().asInsetMath())
2092 return cur.popForward();
2097 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2099 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2101 cur.push(*cur.nextAtom().nucleus());
2102 cur.inset().idxLast(cur);
2105 if (cur.posBackward() || idxBackward(cur))
2107 // try to pop backwards --- but don't pop out of math! leave that to
2109 int s = cur.depth() - 2;
2110 if (s >= 0 && cur[s].inset().asInsetMath())
2111 return cur.popBackward();
2116 ////////////////////////////////////////////////////////////////////
2118 MathCompletionList::MathCompletionList(Cursor const & cur)
2120 // fill it with macros from the buffer
2121 MacroNameSet macros;
2122 cur.buffer()->listMacroNames(macros);
2123 MacroNameSet::const_iterator it;
2124 for (it = macros.begin(); it != macros.end(); ++it) {
2125 if (cur.buffer()->getMacro(*it, cur, false))
2126 locals.push_back("\\" + *it);
2128 sort(locals.begin(), locals.end());
2130 if (!globals.empty())
2133 // fill in global macros
2135 MacroTable::globalMacros().getMacroNames(macros, false);
2136 //lyxerr << "Globals completion macros: ";
2137 for (it = macros.begin(); it != macros.end(); ++it) {
2138 //lyxerr << "\\" + *it << " ";
2139 globals.push_back("\\" + *it);
2141 //lyxerr << std::endl;
2143 // fill in global commands
2144 globals.push_back(from_ascii("\\boxed"));
2145 globals.push_back(from_ascii("\\fbox"));
2146 globals.push_back(from_ascii("\\framebox"));
2147 globals.push_back(from_ascii("\\makebox"));
2148 globals.push_back(from_ascii("\\kern"));
2149 globals.push_back(from_ascii("\\xhookrightarrow"));
2150 globals.push_back(from_ascii("\\xhookleftarrow"));
2151 globals.push_back(from_ascii("\\xrightarrow"));
2152 globals.push_back(from_ascii("\\xRightarrow"));
2153 globals.push_back(from_ascii("\\xrightharpoondown"));
2154 globals.push_back(from_ascii("\\xrightharpoonup"));
2155 globals.push_back(from_ascii("\\xrightleftharpoons"));
2156 globals.push_back(from_ascii("\\xleftarrow"));
2157 globals.push_back(from_ascii("\\xLeftarrow"));
2158 globals.push_back(from_ascii("\\xleftharpoondown"));
2159 globals.push_back(from_ascii("\\xleftharpoonup"));
2160 globals.push_back(from_ascii("\\xleftrightarrow"));
2161 globals.push_back(from_ascii("\\xLeftrightarrow"));
2162 globals.push_back(from_ascii("\\xleftrightharpoons"));
2163 globals.push_back(from_ascii("\\xmapsto"));
2164 globals.push_back(from_ascii("\\split"));
2165 globals.push_back(from_ascii("\\gathered"));
2166 globals.push_back(from_ascii("\\aligned"));
2167 globals.push_back(from_ascii("\\alignedat"));
2168 globals.push_back(from_ascii("\\cases"));
2169 globals.push_back(from_ascii("\\substack"));
2170 globals.push_back(from_ascii("\\xymatrix"));
2171 globals.push_back(from_ascii("\\Diagram"));
2172 globals.push_back(from_ascii("\\subarray"));
2173 globals.push_back(from_ascii("\\array"));
2174 globals.push_back(from_ascii("\\sqrt"));
2175 globals.push_back(from_ascii("\\root"));
2176 globals.push_back(from_ascii("\\tabular"));
2177 globals.push_back(from_ascii("\\sideset"));
2178 globals.push_back(from_ascii("\\stackrel"));
2179 globals.push_back(from_ascii("\\stackrelthree"));
2180 globals.push_back(from_ascii("\\binom"));
2181 globals.push_back(from_ascii("\\choose"));
2182 globals.push_back(from_ascii("\\brace"));
2183 globals.push_back(from_ascii("\\brack"));
2184 globals.push_back(from_ascii("\\frac"));
2185 globals.push_back(from_ascii("\\over"));
2186 globals.push_back(from_ascii("\\nicefrac"));
2187 globals.push_back(from_ascii("\\unitfrac"));
2188 globals.push_back(from_ascii("\\unitfracthree"));
2189 globals.push_back(from_ascii("\\unitone"));
2190 globals.push_back(from_ascii("\\unittwo"));
2191 globals.push_back(from_ascii("\\infer"));
2192 globals.push_back(from_ascii("\\atop"));
2193 globals.push_back(from_ascii("\\lefteqn"));
2194 globals.push_back(from_ascii("\\boldsymbol"));
2195 globals.push_back(from_ascii("\\bm"));
2196 globals.push_back(from_ascii("\\color"));
2197 globals.push_back(from_ascii("\\normalcolor"));
2198 globals.push_back(from_ascii("\\textcolor"));
2199 globals.push_back(from_ascii("\\cfrac"));
2200 globals.push_back(from_ascii("\\cfracleft"));
2201 globals.push_back(from_ascii("\\cfracright"));
2202 globals.push_back(from_ascii("\\dfrac"));
2203 globals.push_back(from_ascii("\\tfrac"));
2204 globals.push_back(from_ascii("\\dbinom"));
2205 globals.push_back(from_ascii("\\tbinom"));
2206 globals.push_back(from_ascii("\\hphantom"));
2207 globals.push_back(from_ascii("\\phantom"));
2208 globals.push_back(from_ascii("\\vphantom"));
2209 globals.push_back(from_ascii("\\cancel"));
2210 globals.push_back(from_ascii("\\bcancel"));
2211 globals.push_back(from_ascii("\\xcancel"));
2212 globals.push_back(from_ascii("\\cancelto"));
2213 globals.push_back(from_ascii("\\smash"));
2214 globals.push_back(from_ascii("\\mathclap"));
2215 globals.push_back(from_ascii("\\mathllap"));
2216 globals.push_back(from_ascii("\\mathrlap"));
2217 globals.push_back(from_ascii("\\ensuremath"));
2218 MathWordList const & words = mathedWordList();
2219 MathWordList::const_iterator it2;
2220 //lyxerr << "Globals completion commands: ";
2221 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2222 if (it2->second.inset != "macro" && !it2->second.hidden) {
2223 // macros are already read from MacroTable::globalMacros()
2224 globals.push_back('\\' + it2->first);
2225 //lyxerr << '\\' + it2->first << ' ';
2228 //lyxerr << std::endl;
2229 sort(globals.begin(), globals.end());
2233 MathCompletionList::~MathCompletionList()
2238 size_type MathCompletionList::size() const
2240 return locals.size() + globals.size();
2244 docstring const & MathCompletionList::data(size_t idx) const
2246 size_t lsize = locals.size();
2248 return globals[idx - lsize];
2254 std::string MathCompletionList::icon(size_t idx) const
2256 // get the latex command
2258 size_t lsize = locals.size();
2260 cmd = globals[idx - lsize];
2264 // get the icon resource name by stripping the backslash
2265 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2266 if (icon_name.empty())
2267 return std::string();
2268 return "images/math/" + to_utf8(icon_name);
2271 std::vector<docstring> MathCompletionList::globals;