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");
175 Dimension const dim = coord_cache.getArrays().dim(&ar);
181 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
184 for (auto const & cell : cells_) {
186 cell.metrics(m, dim);
191 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
193 for (idx_type i = 0, n = nargs(); i != n; ++i)
194 cell(i).updateBuffer(it, utype);
199 bool InsetMathNest::idxNext(Cursor & cur) const
201 LASSERT(&cur.inset() == this, return false);
202 if (cur.idx() == cur.lastidx())
210 bool InsetMathNest::idxForward(Cursor & cur) const
216 bool InsetMathNest::idxPrev(Cursor & cur) const
218 LASSERT(&cur.inset() == this, return false);
222 cur.pos() = cur.lastpos();
227 bool InsetMathNest::idxBackward(Cursor & cur) const
233 bool InsetMathNest::idxFirst(Cursor & cur) const
235 LASSERT(&cur.inset() == this, return false);
244 bool InsetMathNest::idxLast(Cursor & cur) const
246 LASSERT(&cur.inset() == this, return false);
249 cur.idx() = cur.lastidx();
250 cur.pos() = cur.lastpos();
255 void InsetMathNest::dump() const
257 odocstringstream oss;
258 otexrowstream ots(oss);
260 os << "---------------------------------------------\n";
263 for (idx_type i = 0, n = nargs(); i != n; ++i)
264 os << cell(i) << "\n";
265 os << "---------------------------------------------\n";
266 lyxerr << to_utf8(oss.str());
270 void InsetMathNest::draw(PainterInfo &, int, int) const
274 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
280 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
282 BufferView & bv = *pi.base.bv;
283 // this should use the x/y values given, not the cached values
284 Cursor & cur = bv.cursor();
285 if (!cur.selection())
287 if (&cur.inset() != this)
290 // FIXME: hack to get position cache warm
291 bool const original_drawing_state = pi.pain.isDrawingEnabled();
292 pi.pain.setDrawingEnabled(false);
294 pi.pain.setDrawingEnabled(original_drawing_state);
296 CursorSlice s1 = cur.selBegin();
297 CursorSlice s2 = cur.selEnd();
299 //lyxerr << "InsetMathNest::drawing selection: "
300 // << " s1: " << s1 << " s2: " << s2 << endl;
301 if (s1.idx() == s2.idx()) {
302 MathData const & c = cell(s1.idx());
303 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
304 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
305 int y1 = g.pos.y_ - g.dim.ascent();
306 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
307 int y2 = g.pos.y_ + g.dim.descent();
308 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
309 //lyxerr << "InsetMathNest::drawing selection 3: "
310 // << " x1: " << x1 << " x2: " << x2
311 // << " y1: " << y1 << " y2: " << y2 << endl;
313 for (idx_type i = 0; i < nargs(); ++i) {
314 if (idxBetween(i, s1.idx(), s2.idx())) {
315 MathData const & c = cell(i);
316 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
318 int y1 = g.pos.y_ - g.dim.ascent();
319 int x2 = g.pos.x_ + g.dim.width();
320 int y2 = g.pos.y_ + g.dim.descent();
321 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
328 void InsetMathNest::validate(LaTeXFeatures & features) const
330 for (idx_type i = 0; i < nargs(); ++i)
331 cell(i).validate(features);
335 void InsetMathNest::replace(ReplaceData & rep)
337 for (idx_type i = 0; i < nargs(); ++i)
338 cell(i).replace(rep);
342 bool InsetMathNest::contains(MathData const & ar) const
344 for (idx_type i = 0; i < nargs(); ++i)
345 if (cell(i).contains(ar))
351 bool InsetMathNest::lock() const
357 void InsetMathNest::lock(bool l)
363 bool InsetMathNest::isActive() const
369 MathData InsetMathNest::glue() const
372 for (size_t i = 0; i < nargs(); ++i)
378 void InsetMathNest::write(WriteStream & os) const
380 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
381 ModeSpecifier specifier(os, currentMode(), lockedMode());
382 docstring const latex_name = name();
383 os << '\\' << latex_name;
384 for (size_t i = 0; i < nargs(); ++i) {
385 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
386 os << '{' << cell(i) << '}';
389 os.pendingSpace(true);
390 if (lock_ && !os.latex()) {
392 os.pendingSpace(true);
397 void InsetMathNest::normalize(NormalStream & os) const
400 for (size_t i = 0; i < nargs(); ++i)
401 os << ' ' << cell(i);
406 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
408 WriteStream wi(os, runparams.moving_arg, true,
409 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
411 wi.strikeoutMath(runparams.inDeletedInset
412 && (!LaTeXFeatures::isAvailable("dvipost")
413 || (runparams.flavor != OutputParams::LATEX
414 && runparams.flavor != OutputParams::DVILUATEX)));
415 if (runparams.inulemcmd) {
416 wi.ulemCmd(WriteStream::UNDERLINE);
417 if (runparams.local_font) {
418 FontInfo f = runparams.local_font->fontInfo();
419 if (f.strikeout() == FONT_ON)
420 wi.ulemCmd(WriteStream::STRIKEOUT);
423 wi.canBreakLine(os.canBreakLine());
424 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
427 // Reset parbreak status after a math inset.
429 os.canBreakLine(wi.canBreakLine());
433 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
436 mouse_hover_[bv] = mouse_hover;
441 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
445 MathData & ar = cur.cell();
446 // remove base-only "scripts"
447 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
448 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
449 if (p && p->nargs() == 1) {
450 MathData ar = p->nuc();
453 cur.adjust(i, ar.size() - 1);
457 // glue adjacent font insets of the same kind
458 for (pos_type i = 0; i + 1 < size(); ++i) {
459 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
460 InsetMathFont const * q = operator[](i + 1)->asFontInset();
461 if (p && q && p->name() == q->name()) {
462 p->cell(0).append(q->cell(0));
472 void InsetMathNest::handleFont
473 (Cursor & cur, docstring const & arg, char const * const font)
475 handleFont(cur, arg, from_ascii(font));
479 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
480 docstring const & font)
482 cur.recordUndoSelection();
484 // this whole function is a hack and won't work for incremental font
486 if (cur.inset().asInsetMath()->name() == font)
487 cur.handleFont(to_utf8(font));
489 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
493 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
495 handleNest(cur, nest, docstring());
499 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
500 docstring const & arg)
502 CursorSlice i1 = cur.selBegin();
503 CursorSlice i2 = cur.selEnd();
504 if (!i1.inset().asInsetMath())
506 if (i1.idx() == i2.idx()) {
507 // the easy case where only one cell is selected
508 cur.handleNest(nest);
513 // multiple selected cells in a simple non-grid inset
514 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
515 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
520 cur.pos() = cur.lastpos();
523 // change font of cell
524 cur.handleNest(nest);
527 // cur is in the font inset now. If the loop continues,
528 // we need to get outside again for the next cell
529 if (i + 1 <= i2.idx())
535 // the complicated case with multiple selected cells in a grid
538 cap::region(i1, i2, r1, r2, c1, c2);
539 for (row_type row = r1; row <= r2; ++row) {
540 for (col_type col = c1; col <= c2; ++col) {
542 cur.idx() = i1.asInsetMath()->index(row, col);
545 cur.pos() = cur.lastpos();
549 cur.handleNest(nest);
552 // cur is in the font inset now. If the loop continues,
553 // we need to get outside again for the next cell
554 if (col + 1 <= c2 || row + 1 <= r2)
561 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
563 cur.recordUndoSelection();
566 font.fromString(to_utf8(arg), b);
567 if (font.fontInfo().color() != Color_inherit &&
568 font.fontInfo().color() != Color_ignore)
569 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
571 // FIXME: support other font changes here as well?
575 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
577 //LYXERR0("InsetMathNest: request: " << cmd);
579 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
581 FuncCode const act = cmd.action();
584 case LFUN_CLIPBOARD_PASTE:
585 parseflg |= Parse::VERBATIM;
588 if (cur.currentMode() != MATH_MODE)
589 parseflg |= Parse::TEXTMODE;
590 cur.recordUndoSelection();
591 cur.message(_("Paste"));
592 replaceSelection(cur);
594 if (cmd.argument().empty() && !theClipboard().isInternal())
595 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
598 idocstringstream is(cmd.argument());
600 topaste = cap::selection(n, buffer().params().documentClassPtr());
602 cur.niceInsert(topaste, parseflg, false);
603 cur.clearSelection(); // bug 393
604 cur.forceBufferUpdate();
611 cutSelection(cur, true, true);
612 cur.message(_("Cut"));
613 // Prevent stale position >= size crash
614 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
616 cur.forceBufferUpdate();
621 cur.message(_("Copy"));
624 case LFUN_MOUSE_PRESS:
625 lfunMousePress(cur, cmd);
628 case LFUN_MOUSE_MOTION:
629 lfunMouseMotion(cur, cmd);
632 case LFUN_MOUSE_RELEASE:
633 lfunMouseRelease(cur, cmd);
636 case LFUN_FINISHED_LEFT: // in math, left is backwards
637 case LFUN_FINISHED_BACKWARD:
638 cur.bv().cursor() = cur;
641 case LFUN_FINISHED_RIGHT: // in math, right is forward
642 case LFUN_FINISHED_FORWARD:
644 cur.bv().cursor() = cur;
647 case LFUN_WORD_RIGHT:
649 case LFUN_WORD_BACKWARD:
650 case LFUN_WORD_FORWARD:
651 case LFUN_CHAR_RIGHT:
653 case LFUN_CHAR_BACKWARD:
654 case LFUN_CHAR_FORWARD:
655 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
657 case LFUN_WORD_RIGHT_SELECT:
658 case LFUN_WORD_LEFT_SELECT:
659 case LFUN_WORD_BACKWARD_SELECT:
660 case LFUN_WORD_FORWARD_SELECT:
661 case LFUN_CHAR_RIGHT_SELECT:
662 case LFUN_CHAR_LEFT_SELECT:
663 case LFUN_CHAR_BACKWARD_SELECT:
664 case LFUN_CHAR_FORWARD_SELECT: {
665 // are we in a selection?
666 bool select = (act == LFUN_WORD_RIGHT_SELECT
667 || act == LFUN_WORD_LEFT_SELECT
668 || act == LFUN_WORD_BACKWARD_SELECT
669 || act == LFUN_WORD_FORWARD_SELECT
670 || act == LFUN_CHAR_RIGHT_SELECT
671 || act == LFUN_CHAR_LEFT_SELECT
672 || act == LFUN_CHAR_BACKWARD_SELECT
673 || act == LFUN_CHAR_FORWARD_SELECT);
675 bool word = (act == LFUN_WORD_RIGHT_SELECT
676 || act == LFUN_WORD_LEFT_SELECT
677 || act == LFUN_WORD_BACKWARD_SELECT
678 || act == LFUN_WORD_FORWARD_SELECT
679 || act == LFUN_WORD_RIGHT
680 || act == LFUN_WORD_LEFT
681 || act == LFUN_WORD_BACKWARD
682 || act == LFUN_WORD_FORWARD);
683 // are we moving forward or backwards?
684 // If the command was RIGHT or LEFT, then whether we're moving forward
685 // or backwards depends on the cursor movement mode (logical or visual):
686 // * in visual mode, since math is always LTR, right -> forward,
688 // * in logical mode, the mapping is determined by the
689 // reverseDirectionNeeded() function
692 FuncCode finish_lfun;
694 if (act == LFUN_CHAR_FORWARD
695 || act == LFUN_CHAR_FORWARD_SELECT
696 || act == LFUN_WORD_FORWARD
697 || act == LFUN_WORD_FORWARD_SELECT) {
699 finish_lfun = LFUN_FINISHED_FORWARD;
701 else if (act == LFUN_CHAR_BACKWARD
702 || act == LFUN_CHAR_BACKWARD_SELECT
703 || act == LFUN_WORD_BACKWARD
704 || act == LFUN_WORD_BACKWARD_SELECT) {
706 finish_lfun = LFUN_FINISHED_BACKWARD;
709 bool right = (act == LFUN_CHAR_RIGHT_SELECT
710 || act == LFUN_CHAR_RIGHT
711 || act == LFUN_WORD_RIGHT_SELECT
712 || act == LFUN_WORD_RIGHT);
713 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
719 finish_lfun = LFUN_FINISHED_RIGHT;
721 finish_lfun = LFUN_FINISHED_LEFT;
723 // Now that we know exactly what we want to do, let's do it!
724 cur.selHandle(select);
726 cur.macroModeClose();
727 // try moving forward or backwards as necessary...
728 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
729 // ... and if movement failed, then finish forward or backwards
731 cmd = FuncRequest(finish_lfun);
739 case LFUN_PARAGRAPH_UP:
740 case LFUN_PARAGRAPH_DOWN:
741 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
743 case LFUN_DOWN_SELECT:
745 case LFUN_PARAGRAPH_UP_SELECT:
746 case LFUN_PARAGRAPH_DOWN_SELECT: {
747 // close active macro
748 if (cur.inMacroMode()) {
749 cur.macroModeClose();
753 // stop/start the selection
754 bool select = act == LFUN_DOWN_SELECT
755 || act == LFUN_UP_SELECT
756 || act == LFUN_PARAGRAPH_DOWN_SELECT
757 || act == LFUN_PARAGRAPH_UP_SELECT;
758 cur.selHandle(select);
760 // handle autocorrect:
761 if (lyxrc.autocorrection_math && cur.autocorrect()) {
762 cur.autocorrect() = false;
763 cur.message(_("Autocorrect Off ('!' to enter)"));
767 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
768 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
769 bool successful = cur.upDownInMath(up);
773 if (cur.fixIfBroken())
774 // FIXME: Something bad happened. We pass the corrected Cursor
775 // instead of letting things go worse.
778 // We did not manage to move the cursor.
783 case LFUN_MOUSE_DOUBLE:
784 case LFUN_WORD_SELECT:
788 cur.pos() = cur.lastpos();
789 cur.bv().cursor() = cur;
792 case LFUN_MOUSE_TRIPLE:
797 cur.idx() = cur.lastidx();
798 cur.pos() = cur.lastpos();
799 cur.bv().cursor() = cur;
802 case LFUN_LINE_BEGIN:
803 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
805 case LFUN_LINE_BEGIN_SELECT:
806 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
807 act == LFUN_WORD_LEFT_SELECT ||
808 act == LFUN_LINE_BEGIN_SELECT);
809 cur.macroModeClose();
810 if (cur.pos() != 0) {
812 } else if (cur.col() != 0) {
813 cur.idx() -= cur.col();
815 } else if (cur.idx() != 0) {
819 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
825 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
827 case LFUN_LINE_END_SELECT:
828 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
829 act == LFUN_WORD_RIGHT_SELECT ||
830 act == LFUN_LINE_END_SELECT);
831 cur.macroModeClose();
833 if (cur.pos() != cur.lastpos()) {
834 cur.pos() = cur.lastpos();
835 } else if (ncols() && (cur.col() != cur.lastcol())) {
836 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
837 cur.pos() = cur.lastpos();
838 } else if (cur.idx() != cur.lastidx()) {
839 cur.idx() = cur.lastidx();
840 cur.pos() = cur.lastpos();
842 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
847 case LFUN_CELL_FORWARD:
848 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
849 cur.inset().idxNext(cur);
852 case LFUN_CELL_BACKWARD:
853 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
854 cur.inset().idxPrev(cur);
857 case LFUN_WORD_DELETE_BACKWARD:
858 case LFUN_CHAR_DELETE_BACKWARD:
860 // May affect external cell:
861 cur.recordUndoInset();
862 else if (!cur.inMacroMode())
863 cur.recordUndoSelection();
864 // if the inset can not be removed from within, delete it
865 if (!cur.backspace(cmd.getArg(0) == "force")) {
866 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
867 cur.innerText()->dispatch(cur, cmd);
871 case LFUN_WORD_DELETE_FORWARD:
872 case LFUN_CHAR_DELETE_FORWARD:
873 if (cur.pos() == cur.lastpos())
874 // May affect external cell:
875 cur.recordUndoInset();
877 cur.recordUndoSelection();
878 // if the inset can not be removed from within, delete it
879 if (!cur.erase(cmd.getArg(0) == "force")) {
880 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
881 cur.innerText()->dispatch(cur, cmd);
887 cur.clearSelection();
889 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
894 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
895 // that is traversed by a single <CursorLeft>/<CursorRight>.
896 case LFUN_INSET_TOGGLE:
902 case LFUN_SELF_INSERT:
903 if (cmd.argument().size() != 1) {
904 cur.recordUndoSelection();
905 docstring const arg = cmd.argument();
906 if (!interpretString(cur, arg))
910 // Don't record undo steps if we are in macro mode and thus
911 // cmd.argument is the next character of the macro name.
912 // Otherwise we'll get an invalid cursor if we undo after
913 // the macro was finished and the macro is a known command,
914 // e.g. sqrt. Cursor::macroModeClose replaces in this case
915 // the InsetMathUnknown with name "frac" by an empty
916 // InsetMathFrac -> a pos value > 0 is invalid.
917 // A side effect is that an undo before the macro is finished
918 // undoes the complete macro, not only the last character.
919 // At the time we hit '\' we are not in macro mode, still.
920 if (!cur.inMacroMode())
921 cur.recordUndoSelection();
923 // spacial handling of space. If we insert an inset
924 // via macro mode, we want to put the cursor inside it
925 // if relevant. Think typing "\frac<space>".
926 if (cmd.argument()[0] == ' '
927 && cur.inMacroMode() && cur.macroName() != "\\"
928 && cur.macroModeClose() && cur.pos() > 0) {
929 MathAtom const atom = cur.prevAtom();
930 if (atom->asNestInset() && atom->isActive()) {
932 cur.pushBackward(*cur.nextInset());
934 } else if (!interpretChar(cur, cmd.argument()[0])) {
935 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
940 //case LFUN_SERVER_GET_XY:
943 case LFUN_SERVER_SET_XY: {
944 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
947 istringstream is(to_utf8(cmd.argument()));
949 cur.setScreenPos(x, y);
953 // Special casing for superscript in case of LyX handling
955 case LFUN_ACCENT_CIRCUMFLEX:
956 if (cmd.argument().empty()) {
957 // do superscript if LyX handles
959 cur.recordUndoSelection();
960 script(cur, true, grabAndEraseSelection(cur));
964 case LFUN_ACCENT_UMLAUT:
965 case LFUN_ACCENT_ACUTE:
966 case LFUN_ACCENT_GRAVE:
967 case LFUN_ACCENT_BREVE:
968 case LFUN_ACCENT_DOT:
969 case LFUN_ACCENT_MACRON:
970 case LFUN_ACCENT_CARON:
971 case LFUN_ACCENT_TILDE:
972 case LFUN_ACCENT_CEDILLA:
973 case LFUN_ACCENT_CIRCLE:
974 case LFUN_ACCENT_UNDERDOT:
975 case LFUN_ACCENT_TIE:
976 case LFUN_ACCENT_OGONEK:
977 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
981 case LFUN_TEXTSTYLE_APPLY:
982 case LFUN_TEXTSTYLE_UPDATE:
983 handleFont2(cur, cmd.argument());
987 if (currentMode() != MATH_MODE)
988 handleFont(cur, cmd.argument(), "textbf");
990 handleFont(cur, cmd.argument(), "mathbf");
992 case LFUN_FONT_BOLDSYMBOL:
993 if (currentMode() != MATH_MODE)
994 handleFont(cur, cmd.argument(), "textbf");
996 handleFont(cur, cmd.argument(), "boldsymbol");
999 if (currentMode() != MATH_MODE)
1000 handleFont(cur, cmd.argument(), "textsf");
1002 handleFont(cur, cmd.argument(), "mathsf");
1004 case LFUN_FONT_EMPH:
1005 if (currentMode() != MATH_MODE)
1006 handleFont(cur, cmd.argument(), "emph");
1008 handleFont(cur, cmd.argument(), "mathcal");
1010 case LFUN_FONT_ROMAN:
1011 if (currentMode() != MATH_MODE)
1012 handleFont(cur, cmd.argument(), "textrm");
1014 handleFont(cur, cmd.argument(), "mathrm");
1016 case LFUN_FONT_TYPEWRITER:
1017 if (currentMode() != MATH_MODE)
1018 handleFont(cur, cmd.argument(), "texttt");
1020 handleFont(cur, cmd.argument(), "mathtt");
1022 case LFUN_FONT_FRAK:
1023 handleFont(cur, cmd.argument(), "mathfrak");
1025 case LFUN_FONT_ITAL:
1026 if (currentMode() != MATH_MODE)
1027 handleFont(cur, cmd.argument(), "textit");
1029 handleFont(cur, cmd.argument(), "mathit");
1031 case LFUN_FONT_NOUN:
1032 if (currentMode() != MATH_MODE)
1033 // FIXME: should be "noun"
1034 handleFont(cur, cmd.argument(), "textsc");
1036 handleFont(cur, cmd.argument(), "mathbb");
1038 case LFUN_FONT_DEFAULT:
1039 handleFont(cur, cmd.argument(), "textnormal");
1041 case LFUN_FONT_UNDERLINE:
1043 cur.handleNest(createInsetMath("underline", cur.buffer()));
1046 case LFUN_MATH_MODE: {
1048 // ignore math-mode on when already in math mode
1049 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1051 cur.recordUndoSelection();
1052 cur.macroModeClose();
1053 docstring const save_selection = grabAndEraseSelection(cur);
1055 if (currentMode() != Inset::MATH_MODE)
1056 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1058 cur.plainInsert(createInsetMath("text", buffer_));
1060 cur.pushBackward(*cur.nextInset());
1061 cur.niceInsert(save_selection);
1062 cur.forceBufferUpdate();
1064 if (currentMode() == Inset::TEXT_MODE) {
1065 cur.recordUndoSelection();
1066 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1067 cur.message(_("create new math text environment ($...$)"));
1069 handleFont(cur, cmd.argument(), "textrm");
1070 cur.message(_("entered math text mode (textrm)"));
1076 case LFUN_REGEXP_MODE: {
1077 InsetMath * im = cur.inset().asInsetMath();
1079 InsetMathHull * i = im->asHullInset();
1080 if (i && i->getType() == hullRegexp) {
1081 cur.message(_("Already in regular expression mode"));
1085 cur.macroModeClose();
1086 docstring const save_selection = grabAndEraseSelection(cur);
1088 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1090 cur.pushBackward(*cur.nextInset());
1091 cur.niceInsert(save_selection);
1092 cur.message(_("Regular expression editor mode"));
1096 case LFUN_MATH_FONT_STYLE: {
1097 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1098 doDispatch(cur, fr);
1102 case LFUN_MATH_SIZE: {
1103 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1104 doDispatch(cur, fr);
1108 case LFUN_MATH_MATRIX: {
1114 idocstringstream is(cmd.argument());
1115 is >> m >> n >> v_align >> h_align;
1121 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1122 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1126 case LFUN_MATH_AMS_MATRIX: {
1130 docstring name = from_ascii("matrix");
1131 idocstringstream is(cmd.argument());
1132 is >> m >> n >> name;
1137 // check if we have a valid decoration
1138 if (name != "pmatrix" && name != "bmatrix"
1139 && name != "Bmatrix" && name != "vmatrix"
1140 && name != "Vmatrix" && name != "matrix")
1141 name = from_ascii("matrix");
1144 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1148 case LFUN_MATH_DELIM: {
1150 docstring rs = split(cmd.argument(), ls, ' ');
1151 // Reasonable default values
1157 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1161 case LFUN_MATH_BIGDELIM: {
1162 docstring const lname = from_utf8(cmd.getArg(0));
1163 docstring const ldelim = from_utf8(cmd.getArg(1));
1164 docstring const rname = from_utf8(cmd.getArg(2));
1165 docstring const rdelim = from_utf8(cmd.getArg(3));
1166 latexkeys const * l = in_word_set(lname);
1167 bool const have_l = l && l->inset == "big" &&
1168 InsetMathBig::isBigInsetDelim(ldelim);
1169 l = in_word_set(rname);
1170 bool const have_r = l && l->inset == "big" &&
1171 InsetMathBig::isBigInsetDelim(rdelim);
1172 // We mimic LFUN_MATH_DELIM in case we have an empty left
1173 // or right delimiter.
1174 if (have_l || have_r) {
1176 docstring const selection = grabAndEraseSelection(cur);
1179 cur.insert(MathAtom(new InsetMathBig(lname,
1181 // first insert the right delimiter and then go back
1182 // and re-insert the selection (bug 7088)
1184 cur.insert(MathAtom(new InsetMathBig(rname,
1188 cur.niceInsert(selection);
1190 // Don't call cur.undispatched() if we did nothing, this would
1191 // lead to infinite recursion via Text::dispatch().
1195 case LFUN_SPACE_INSERT: {
1196 cur.recordUndoSelection();
1197 string const name = cmd.getArg(0);
1198 if (name == "normal")
1199 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1200 else if (name == "protected")
1201 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1202 else if (name == "thin" || name == "med" || name == "thick")
1203 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1204 else if (name == "hfill*")
1205 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1206 else if (name == "quad" || name == "qquad" ||
1207 name == "enspace" || name == "enskip" ||
1208 name == "negthinspace" || name == "negmedspace" ||
1209 name == "negthickspace" || name == "hfill")
1210 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1211 else if (name == "hspace" || name == "hspace*") {
1212 string const len = cmd.getArg(1);
1213 if (len.empty() || !isValidLength(len)) {
1214 lyxerr << "LyX function 'space-insert " << name << "' "
1215 "needs a valid length argument." << endl;
1218 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1220 cur.insert(MathAtom(new InsetMathSpace));
1224 case LFUN_MATH_SPACE:
1225 cur.recordUndoSelection();
1226 if (cmd.argument().empty())
1227 cur.insert(MathAtom(new InsetMathSpace));
1229 string const name = cmd.getArg(0);
1230 string const len = cmd.getArg(1);
1231 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1235 case LFUN_ERT_INSERT:
1236 // interpret this as if a backslash was typed
1238 interpretChar(cur, '\\');
1241 case LFUN_MATH_SUBSCRIPT:
1242 // interpret this as if a _ was typed
1243 cur.recordUndoSelection();
1244 interpretChar(cur, '_');
1247 case LFUN_MATH_SUPERSCRIPT:
1248 // interpret this as if a ^ was typed
1249 cur.recordUndoSelection();
1250 interpretChar(cur, '^');
1253 case LFUN_MATH_MACRO_FOLD:
1254 case LFUN_MATH_MACRO_UNFOLD: {
1256 bool fold = act == LFUN_MATH_MACRO_FOLD;
1257 bool found = findMacroToFoldUnfold(it, fold);
1259 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1260 cur.recordUndoInset();
1269 case LFUN_QUOTE_INSERT:
1270 // interpret this as if a straight " was typed
1271 cur.recordUndoSelection();
1272 interpretChar(cur, '\"');
1275 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1276 // handling such that "self-insert" works on "arbitrary stuff" too, and
1277 // math-insert only handles special math things like "matrix".
1278 case LFUN_MATH_INSERT: {
1279 cur.recordUndoSelection();
1280 if (cmd.argument() == "^" || cmd.argument() == "_")
1281 interpretChar(cur, cmd.argument()[0]);
1284 asArray(cmd.argument(), ar);
1285 if (cur.selection() && ar.size() == 1
1286 && ar[0]->asNestInset()
1287 && ar[0]->asNestInset()->nargs() > 1)
1288 handleNest(cur, ar[0]);
1290 cur.niceInsert(cmd.argument());
1295 case LFUN_UNICODE_INSERT: {
1296 if (cmd.argument().empty())
1298 docstring hexstring = cmd.argument();
1299 if (isHex(hexstring)) {
1300 char_type c = hexToInt(hexstring);
1301 if (c >= 32 && c < 0x10ffff) {
1302 docstring s = docstring(1, c);
1303 FuncCode code = currentMode() == MATH_MODE ?
1304 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1305 lyx::dispatch(FuncRequest(code, s));
1311 case LFUN_DIALOG_SHOW_NEW_INSET: {
1312 docstring const & name = cmd.argument();
1314 if (name == "ref") {
1315 InsetMathRef tmp(buffer_, name);
1316 data = tmp.createDialogStr();
1317 cur.bv().showDialog(to_utf8(name), data);
1318 } else if (name == "mathspace") {
1319 cur.bv().showDialog(to_utf8(name));
1324 case LFUN_INSET_INSERT: {
1326 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1327 cur.recordUndoSelection();
1329 cur.forceBufferUpdate();
1334 case LFUN_INSET_DISSOLVE:
1335 if (!asHullInset()) {
1336 cur.recordUndoInset();
1342 InsetMath::doDispatch(cur, cmd);
1348 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1349 // look for macro to open/close, but stay in mathed
1350 for (; !it.empty(); it.pop_back()) {
1352 // go backward through the current cell
1353 Inset * inset = it.nextInset();
1354 while (inset && inset->asInsetMath()) {
1355 MathMacro * macro = inset->asInsetMath()->asMacro();
1357 // found the an macro to open/close?
1358 if (macro->folded() != fold)
1361 // Wrong folding state.
1362 // If this was the first we see in this slice, look further left,
1364 if (inset != it.nextInset())
1368 // go up if this was the left most position
1374 inset = it.nextInset();
1382 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1383 FuncStatus & flag) const
1385 // the font related toggles
1386 //string tc = "mathnormal";
1388 string const arg = to_utf8(cmd.argument());
1389 switch (cmd.action()) {
1390 case LFUN_INSET_MODIFY:
1391 flag.setEnabled(false);
1394 case LFUN_INSET_MODIFY:
1395 // FIXME: check temporarily disabled
1397 char align = mathcursor::valign();
1398 if (align == '\0') {
1402 if (cmd.argument().empty()) {
1406 if (!contains("tcb", cmd.argument()[0])) {
1410 flag.setOnOff(cmd.argument()[0] == align);
1413 /// We have to handle them since 1.4 blocks all unhandled actions
1414 case LFUN_FONT_ITAL:
1415 case LFUN_FONT_BOLD:
1416 case LFUN_FONT_BOLDSYMBOL:
1417 case LFUN_FONT_SANS:
1418 case LFUN_FONT_EMPH:
1419 case LFUN_FONT_TYPEWRITER:
1420 case LFUN_FONT_NOUN:
1421 case LFUN_FONT_ROMAN:
1422 case LFUN_FONT_DEFAULT:
1423 flag.setEnabled(true);
1426 // we just need to be in math mode to enable that
1427 case LFUN_MATH_SIZE:
1428 case LFUN_MATH_SPACE:
1429 case LFUN_MATH_EXTERN:
1430 flag.setEnabled(true);
1433 case LFUN_FONT_UNDERLINE:
1434 case LFUN_FONT_FRAK:
1435 flag.setEnabled(currentMode() != TEXT_MODE);
1438 case LFUN_MATH_FONT_STYLE: {
1439 bool const textarg =
1440 arg == "textbf" || arg == "textsf" ||
1441 arg == "textrm" || arg == "textmd" ||
1442 arg == "textit" || arg == "textsc" ||
1443 arg == "textsl" || arg == "textup" ||
1444 arg == "texttt" || arg == "textbb" ||
1445 arg == "textnormal";
1446 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1450 case LFUN_MATH_MODE:
1451 // forbid "math-mode on" in math mode to prevent irritating
1452 // behaviour of menu entries (bug 6709)
1453 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1456 case LFUN_MATH_INSERT:
1457 flag.setEnabled(currentMode() != TEXT_MODE);
1460 case LFUN_MATH_AMS_MATRIX:
1461 case LFUN_MATH_MATRIX:
1462 flag.setEnabled(currentMode() == MATH_MODE);
1465 case LFUN_INSET_INSERT: {
1466 // Don't test createMathInset_fromDialogStr(), since
1467 // getStatus is not called with a valid reference and the
1468 // dialog would not be applyable.
1469 string const name = cmd.getArg(0);
1470 flag.setEnabled(name == "ref" || name == "mathspace");
1474 case LFUN_DIALOG_SHOW_NEW_INSET: {
1475 docstring const & name = cmd.argument();
1476 if (name == "space")
1477 flag.setEnabled(false);
1482 case LFUN_MATH_DELIM:
1483 case LFUN_MATH_BIGDELIM:
1484 // Don't do this with multi-cell selections
1485 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1488 case LFUN_MATH_MACRO_FOLD:
1489 case LFUN_MATH_MACRO_UNFOLD: {
1491 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1492 flag.setEnabled(found);
1496 case LFUN_SPECIALCHAR_INSERT:
1497 case LFUN_SCRIPT_INSERT:
1498 // FIXME: These would probably make sense in math-text mode
1499 flag.setEnabled(false);
1502 case LFUN_CAPTION_INSERT:
1503 flag.setEnabled(false);
1506 case LFUN_SPACE_INSERT: {
1507 docstring const & name = cmd.argument();
1508 if (name == "visible")
1509 flag.setEnabled(false);
1513 case LFUN_INSET_DISSOLVE:
1514 flag.setEnabled(!asHullInset());
1518 docstring const & name = cmd.argument();
1519 if (name == "html" || name == "latex")
1520 flag.setEnabled(false);
1532 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1535 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1536 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1537 cur.idx() = enter_front ? 0 : cur.lastidx();
1538 cur.pos() = enter_front ? 0 : cur.lastpos();
1540 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1544 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1547 int dist_min = 1000000;
1548 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1549 int const d = cell(i).dist(cur.bv(), x, y);
1555 MathData & ar = cell(idx_min);
1557 cur.idx() = idx_min;
1558 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1560 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1561 if (dist_min == 0) {
1563 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1564 if (ar[i]->covers(cur.bv(), x, y))
1565 return ar[i].nucleus()->editXY(cur, x, y);
1571 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1573 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1574 BufferView & bv = cur.bv();
1575 if (cmd.button() == mouse_button::button3) {
1576 // Don't do anything if we right-click a
1577 // selection, a context menu will popup.
1578 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1579 && cur < bv.cursor().selectionEnd()) {
1580 cur.noScreenUpdate();
1585 // set cursor after the inset if x is nearer to that position (bug 9748)
1586 cur.moveToClosestEdge(cmd.x(), true);
1588 bool do_selection = cmd.button() == mouse_button::button1
1589 && cmd.modifier() == ShiftModifier;
1590 bv.mouseSetCursor(cur, do_selection);
1591 if (cmd.button() == mouse_button::button1) {
1592 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1593 // Update the cursor update flags as needed:
1595 // Update::Decoration: tells to update the decoration
1596 // (visual box corners that define
1598 // Update::FitCursor: adjust the screen to the cursor
1599 // position if needed
1600 // cur.result().update(): don't overwrite previously set flags.
1601 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1602 | cur.result().screenUpdate());
1603 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1604 if (cap::selection()) {
1605 // See comment in Text::dispatch why we do this
1606 cap::copySelectionToStack();
1607 cmd = FuncRequest(LFUN_PASTE, "0");
1608 doDispatch(bv.cursor(), cmd);
1611 asArray(theSelection().get(), ar);
1612 bv.cursor().insert(ar);
1618 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1620 // only select with button 1
1621 if (cmd.button() != mouse_button::button1)
1624 Cursor & bvcur = cur.bv().cursor();
1626 // ignore motions deeper nested than the real anchor
1627 if (!bvcur.realAnchor().hasPart(cur)) {
1632 // set cursor after the inset if x is nearer to that position (bug 9748)
1633 cur.moveToClosestEdge(cmd.x());
1635 CursorSlice old = bvcur.top();
1637 // We continue with our existing selection or start a new one, so don't
1638 // reset the anchor.
1639 bvcur.setCursor(cur);
1640 // Did we actually move?
1641 if (cur.top() == old)
1642 // We didn't move one iota, so no need to change selection status
1643 // or update the screen.
1644 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1646 bvcur.setSelection();
1650 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1652 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1654 if (cmd.button() == mouse_button::button1) {
1655 if (!cur.selection())
1656 cur.noScreenUpdate();
1658 Cursor & bvcur = cur.bv().cursor();
1659 bvcur.selection(true);
1668 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1670 //lyxerr << "interpret 2: '" << c << "'" << endl;
1671 docstring save_selection;
1672 if (c == '^' || c == '_')
1673 save_selection = grabAndEraseSelection(cur);
1676 Buffer * buf = cur.buffer();
1679 if (cur.inMacroMode()) {
1680 docstring name = cur.macroName();
1682 /// are we currently typing '#1' or '#2' or...?
1683 if (name == "\\#") {
1686 if (n >= 1 && n <= 9)
1687 cur.insert(new MathMacroArgument(n));
1691 // do not finish macro for known * commands
1692 bool star_macro = c == '*'
1693 && (in_word_set(name.substr(1) + '*')
1694 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1695 if (isAlphaASCII(c) || star_macro) {
1696 cur.activeMacro()->setName(name + docstring(1, c));
1700 // handle 'special char' macros
1705 if (currentMode() != InsetMath::MATH_MODE)
1706 cur.niceInsert(createInsetMath("textbackslash", buf));
1708 cur.niceInsert(createInsetMath("backslash", buf));
1709 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1711 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1712 } else if (c == '{' || c == '%') {
1713 //using the saved selection as argument
1714 InsetMathUnknown * p = cur.activeMacro();
1716 MathData sel(cur.buffer());
1717 asArray(p->selection(), sel);
1720 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1722 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1723 } else if (c == '#') {
1724 LASSERT(cur.activeMacro(), return false);
1725 cur.activeMacro()->setName(name + docstring(1, c));
1728 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1733 // One character big delimiters. The others are handled in
1734 // interpretString().
1735 latexkeys const * l = in_word_set(name.substr(1));
1736 if (name[0] == '\\' && l && l->inset == "big") {
1740 delim = from_ascii("\\{");
1743 delim = from_ascii("\\}");
1746 delim = docstring(1, c);
1749 if (InsetMathBig::isBigInsetDelim(delim)) {
1750 // name + delim ared a valid InsetMathBig.
1751 // We can't use cur.macroModeClose() because
1752 // it does not handle delim.
1753 InsetMathUnknown * p = cur.activeMacro();
1756 cur.cell().erase(cur.pos());
1757 cur.plainInsert(MathAtom(
1758 new InsetMathBig(name.substr(1), delim)));
1761 } else if (name == "\\smash" && c == '[') {
1762 // We can't use cur.macroModeClose() because
1763 // it would create an InsetMathPhantom
1764 InsetMathUnknown * p = cur.activeMacro();
1766 interpretChar(cur, c);
1770 // leave macro mode and try again if necessary
1771 if (cur.macroModeClose()) {
1772 MathAtom const atom = cur.prevAtom();
1773 if (atom->asNestInset() && atom->isActive()) {
1775 cur.pushBackward(*cur.nextInset());
1779 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1781 interpretChar(cur, c);
1786 // leave autocorrect mode if necessary
1787 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1788 cur.autocorrect() = false;
1789 cur.message(_("Autocorrect Off ('!' to enter)"));
1792 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1793 cur.autocorrect() = true;
1794 cur.message(_("Autocorrect On (<space> to exit)"));
1798 // just clear selection on pressing the space bar
1799 if (cur.selection() && c == ' ') {
1800 cur.selection(false);
1805 //lyxerr << "starting with macro" << endl;
1806 bool reduced = cap::reduceSelectionToOneCell(cur);
1807 if (reduced || !cur.selection()) {
1808 cur.recordUndoInset();
1809 docstring const safe = cap::grabAndEraseSelection(cur);
1810 if (!cur.inRegexped())
1811 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1813 cur.niceInsert(createInsetMath("backslash", buf));
1821 if (currentMode() != InsetMath::MATH_MODE)
1827 if (currentMode() != InsetMath::MATH_MODE) {
1828 // insert spaces in text or undecided mode,
1829 // but suppress direct insertion of two spaces in a row
1830 // the still allows typing '<space>a<space>' and deleting the 'a', but
1831 // it is better than nothing...
1832 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1834 // FIXME: we have to enable full redraw here because of the
1835 // visual box corners that define the inset. If we know for
1836 // sure that we stay within the same cell we can optimize for
1838 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1842 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1843 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1844 // FIXME: we have to enable full redraw here because of the
1845 // visual box corners that define the inset. If we know for
1846 // sure that we stay within the same cell we can optimize for
1848 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1852 if (cur.popForward()) {
1853 // FIXME: we have to enable full redraw here because of the
1854 // visual box corners that define the inset. If we know for
1855 // sure that we stay within the same cell we can optimize for
1857 //cur.screenUpdateFlags(Update::FitCursor);
1861 // if we are at the very end, leave the formula
1862 return cur.pos() != cur.lastpos();
1865 // These should be treated differently when not in text mode:
1866 if (cur.inRegexped()) {
1869 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1876 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1879 cur.niceInsert(createInsetMath("sim", buf));
1885 } else if (currentMode() != InsetMath::TEXT_MODE) {
1887 script(cur, false, save_selection);
1891 script(cur, true, save_selection);
1895 cur.niceInsert(createInsetMath("sim", buf));
1898 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1899 MathAtom at = createInsetMath("text", buf);
1900 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1907 cur.niceInsert(createInsetMath("textasciicircum", buf));
1911 cur.niceInsert(createInsetMath("textasciitilde", buf));
1916 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1917 c == '%' || c == '_') {
1918 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1923 // try auto-correction
1924 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1925 && math_autocorrect(cur.prevAtom(), c))
1928 // no special circumstances, so insert the character without any fuss
1930 if (lyxrc.autocorrection_math) {
1931 if (!cur.autocorrect())
1932 cur.message(_("Autocorrect Off ('!' to enter)"));
1934 cur.message(_("Autocorrect On (<space> to exit)"));
1940 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1942 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1944 if (!cur.empty() && cur.pos() > 0 &&
1945 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1946 if (InsetMathBig::isBigInsetDelim(str)) {
1947 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1948 if (prev[0] == '\\') {
1949 prev = prev.substr(1);
1950 latexkeys const * l = in_word_set(prev);
1951 if (l && l->inset == "big") {
1952 cur.cell()[cur.pos() - 1] =
1953 MathAtom(new InsetMathBig(prev, str));
1963 bool InsetMathNest::script(Cursor & cur, bool up)
1965 return script(cur, up, docstring());
1969 bool InsetMathNest::script(Cursor & cur, bool up,
1970 docstring const & save_selection)
1972 // Hack to get \^ and \_ working
1973 //lyxerr << "handling script: up: " << up << endl;
1974 if (cur.inMacroMode() && cur.macroName() == "\\") {
1976 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1978 interpretChar(cur, '_');
1982 cur.macroModeClose();
1983 if (asScriptInset() && cur.idx() == 0) {
1984 // we are in a nucleus of a script inset, move to _our_ script
1985 InsetMathScript * inset = asScriptInset();
1986 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1988 cur.idx() = inset->idxOfScript(up);
1990 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1992 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1995 cur.idx() = inset->idxOfScript(up);
1996 cur.pos() = cur.lastpos();
1998 // convert the thing to our left to a scriptinset or create a new
1999 // one if in the very first position of the array
2000 if (cur.pos() == 0) {
2001 //lyxerr << "new scriptinset" << endl;
2002 cur.insert(new InsetMathScript(buffer_, up));
2004 //lyxerr << "converting prev atom " << endl;
2005 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
2008 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2009 // See comment in MathParser.cpp for special handling of {}-bases
2015 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
2016 cur.niceInsert(save_selection);
2018 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2023 bool InsetMathNest::completionSupported(Cursor const & cur) const
2025 return cur.inMacroMode();
2029 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2031 return cur.inMacroMode();
2035 bool InsetMathNest::automaticInlineCompletion() const
2037 return lyxrc.completion_inline_math;
2041 bool InsetMathNest::automaticPopupCompletion() const
2043 return lyxrc.completion_popup_math;
2047 CompletionList const *
2048 InsetMathNest::createCompletionList(Cursor const & cur) const
2050 if (!cur.inMacroMode())
2053 return new MathCompletionList(cur);
2057 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2059 if (!cur.inMacroMode())
2062 return cur.activeMacro()->name();
2066 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2069 if (!cur.inMacroMode())
2072 // append completion to active macro
2073 InsetMathUnknown * inset = cur.activeMacro();
2074 inset->setName(inset->name() + s);
2079 // FIXME: this creates duplicates in the completion popup
2080 // which looks ugly. Moreover the changes the list lengths
2082 confuse the popup as well.
2083 MathCompletionList::addToFavorites(inset->name());
2085 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2092 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2093 Dimension & dim) const
2095 Inset const * inset = cur.activeMacro();
2099 // get inset dimensions
2100 dim = cur.bv().coordCache().insets().dim(inset);
2101 // FIXME: these 3 are no accurate, but should depend on the font.
2102 // Now the popup jumps down if you enter a char with descent > 0.
2107 Point xy = cur.bv().coordCache().insets().xy(inset);
2113 ////////////////////////////////////////////////////////////////////
2115 MathCompletionList::MathCompletionList(Cursor const & cur)
2117 // fill it with macros from the buffer
2118 MacroNameSet macros;
2119 cur.buffer()->listMacroNames(macros);
2120 MacroNameSet::const_iterator it;
2121 for (it = macros.begin(); it != macros.end(); ++it) {
2122 if (cur.buffer()->getMacro(*it, cur, false))
2123 locals.push_back("\\" + *it);
2125 sort(locals.begin(), locals.end());
2127 if (!globals.empty())
2130 // fill in global macros
2132 MacroTable::globalMacros().getMacroNames(macros, false);
2133 //lyxerr << "Globals completion macros: ";
2134 for (it = macros.begin(); it != macros.end(); ++it) {
2135 //lyxerr << "\\" + *it << " ";
2136 globals.push_back("\\" + *it);
2138 //lyxerr << std::endl;
2140 // fill in global commands
2141 globals.push_back(from_ascii("\\boxed"));
2142 globals.push_back(from_ascii("\\fbox"));
2143 globals.push_back(from_ascii("\\framebox"));
2144 globals.push_back(from_ascii("\\makebox"));
2145 globals.push_back(from_ascii("\\kern"));
2146 globals.push_back(from_ascii("\\xhookrightarrow"));
2147 globals.push_back(from_ascii("\\xhookleftarrow"));
2148 globals.push_back(from_ascii("\\xrightarrow"));
2149 globals.push_back(from_ascii("\\xRightarrow"));
2150 globals.push_back(from_ascii("\\xrightharpoondown"));
2151 globals.push_back(from_ascii("\\xrightharpoonup"));
2152 globals.push_back(from_ascii("\\xrightleftharpoons"));
2153 globals.push_back(from_ascii("\\xleftarrow"));
2154 globals.push_back(from_ascii("\\xLeftarrow"));
2155 globals.push_back(from_ascii("\\xleftharpoondown"));
2156 globals.push_back(from_ascii("\\xleftharpoonup"));
2157 globals.push_back(from_ascii("\\xleftrightarrow"));
2158 globals.push_back(from_ascii("\\xLeftrightarrow"));
2159 globals.push_back(from_ascii("\\xleftrightharpoons"));
2160 globals.push_back(from_ascii("\\xmapsto"));
2161 globals.push_back(from_ascii("\\split"));
2162 globals.push_back(from_ascii("\\gathered"));
2163 globals.push_back(from_ascii("\\aligned"));
2164 globals.push_back(from_ascii("\\alignedat"));
2165 globals.push_back(from_ascii("\\cases"));
2166 globals.push_back(from_ascii("\\substack"));
2167 globals.push_back(from_ascii("\\xymatrix"));
2168 globals.push_back(from_ascii("\\Diagram"));
2169 globals.push_back(from_ascii("\\subarray"));
2170 globals.push_back(from_ascii("\\array"));
2171 globals.push_back(from_ascii("\\sqrt"));
2172 globals.push_back(from_ascii("\\root"));
2173 globals.push_back(from_ascii("\\tabular"));
2174 globals.push_back(from_ascii("\\sideset"));
2175 globals.push_back(from_ascii("\\stackrel"));
2176 globals.push_back(from_ascii("\\stackrelthree"));
2177 globals.push_back(from_ascii("\\binom"));
2178 globals.push_back(from_ascii("\\choose"));
2179 globals.push_back(from_ascii("\\brace"));
2180 globals.push_back(from_ascii("\\brack"));
2181 globals.push_back(from_ascii("\\frac"));
2182 globals.push_back(from_ascii("\\over"));
2183 globals.push_back(from_ascii("\\nicefrac"));
2184 globals.push_back(from_ascii("\\unitfrac"));
2185 globals.push_back(from_ascii("\\unitfracthree"));
2186 globals.push_back(from_ascii("\\unitone"));
2187 globals.push_back(from_ascii("\\unittwo"));
2188 globals.push_back(from_ascii("\\infer"));
2189 globals.push_back(from_ascii("\\atop"));
2190 globals.push_back(from_ascii("\\lefteqn"));
2191 globals.push_back(from_ascii("\\boldsymbol"));
2192 globals.push_back(from_ascii("\\bm"));
2193 globals.push_back(from_ascii("\\color"));
2194 globals.push_back(from_ascii("\\normalcolor"));
2195 globals.push_back(from_ascii("\\textcolor"));
2196 globals.push_back(from_ascii("\\cfrac"));
2197 globals.push_back(from_ascii("\\cfracleft"));
2198 globals.push_back(from_ascii("\\cfracright"));
2199 globals.push_back(from_ascii("\\dfrac"));
2200 globals.push_back(from_ascii("\\tfrac"));
2201 globals.push_back(from_ascii("\\dbinom"));
2202 globals.push_back(from_ascii("\\tbinom"));
2203 globals.push_back(from_ascii("\\hphantom"));
2204 globals.push_back(from_ascii("\\phantom"));
2205 globals.push_back(from_ascii("\\vphantom"));
2206 globals.push_back(from_ascii("\\cancel"));
2207 globals.push_back(from_ascii("\\bcancel"));
2208 globals.push_back(from_ascii("\\xcancel"));
2209 globals.push_back(from_ascii("\\cancelto"));
2210 globals.push_back(from_ascii("\\smash"));
2211 globals.push_back(from_ascii("\\mathclap"));
2212 globals.push_back(from_ascii("\\mathllap"));
2213 globals.push_back(from_ascii("\\mathrlap"));
2214 globals.push_back(from_ascii("\\ensuremath"));
2215 MathWordList const & words = mathedWordList();
2216 MathWordList::const_iterator it2;
2217 //lyxerr << "Globals completion commands: ";
2218 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2219 if (it2->second.inset != "macro" && !it2->second.hidden) {
2220 // macros are already read from MacroTable::globalMacros()
2221 globals.push_back('\\' + it2->first);
2222 //lyxerr << '\\' + it2->first << ' ';
2225 //lyxerr << std::endl;
2226 sort(globals.begin(), globals.end());
2230 MathCompletionList::~MathCompletionList()
2235 size_type MathCompletionList::size() const
2237 return locals.size() + globals.size();
2241 docstring const & MathCompletionList::data(size_t idx) const
2243 size_t lsize = locals.size();
2245 return globals[idx - lsize];
2251 std::string MathCompletionList::icon(size_t idx) const
2253 // get the latex command
2255 size_t lsize = locals.size();
2257 cmd = globals[idx - lsize];
2261 // get the icon resource name by stripping the backslash
2262 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2263 if (icon_name.empty())
2264 return std::string();
2265 return "images/math/" + to_utf8(icon_name);
2268 std::vector<docstring> MathCompletionList::globals;