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"
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 "OutputParams.h"
56 #include "frontends/Clipboard.h"
57 #include "frontends/Painter.h"
58 #include "frontends/Selection.h"
60 #include "support/lassert.h"
61 #include "support/debug.h"
62 #include "support/gettext.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
65 #include "support/docstream.h"
71 using namespace lyx::support;
75 using cap::copySelection;
76 using cap::grabAndEraseSelection;
77 using cap::cutSelection;
78 using cap::replaceSelection;
79 using cap::selClearOrDel;
82 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
83 : InsetMath(buf), cells_(nargs), lock_(false)
89 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
90 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
94 InsetMathNest::~InsetMathNest()
96 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
97 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
98 for (; it != end; ++it)
100 it->first->clearLastInset(this);
104 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
106 cells_ = inset.cells_;
108 mouse_hover_.clear();
109 InsetMath::operator=(inset);
114 void InsetMathNest::setBuffer(Buffer & buffer)
116 InsetMath::setBuffer(buffer);
117 for (idx_type i = 0, n = nargs(); i != n; ++i) {
118 MathData & data = cell(i);
119 for (size_t j = 0; j != data.size(); ++j)
120 data[j].nucleus()->setBuffer(buffer);
125 InsetMath::idx_type InsetMathNest::nargs() const
127 return cells_.size();
131 void InsetMathNest::cursorPos(BufferView const & bv,
132 CursorSlice const & sl, bool /*boundary*/,
133 int & x, int & y) const
135 // FIXME: This is a hack. Ideally, the coord cache should not store
136 // absolute positions, but relative ones. This would mean to call
137 // setXY() not in MathData::draw(), but in the parent insets' draw()
138 // with the correctly adjusted x,y values. But this means that we'd have
139 // to touch all (math)inset's draw() methods. Right now, we'll store
140 // absolute value, and make them here relative, only to make them
141 // absolute again when actually drawing the cursor. What a mess.
142 LASSERT(&sl.inset() == this, /**/);
143 MathData const & ar = sl.cell();
144 CoordCache const & coord_cache = bv.coordCache();
145 if (!coord_cache.getArrays().has(&ar)) {
146 // this can (semi-)legally happen if we just created this cell
147 // and it never has been drawn before. So don't ASSERT.
148 //lyxerr << "no cached data for array " << &ar << endl;
153 Point const pt = coord_cache.getArrays().xy(&ar);
154 if (!coord_cache.getInsets().has(this)) {
156 //lyxerr << "no cached data for inset " << this << endl;
161 Point const pt2 = coord_cache.getInsets().xy(this);
162 //lyxerr << "retrieving position cache for MathData "
163 // << pt.x_ << ' ' << pt.y_ << endl;
164 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
166 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
167 // << " asc: " << ascent() << " des: " << descent()
168 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
169 // move cursor visually into empty cells ("blue rectangles");
175 void InsetMathNest::metrics(MetricsInfo const & mi) const
178 for (idx_type i = 0, n = nargs(); i != n; ++i) {
180 cell(i).metrics(m, dim);
185 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
187 for (idx_type i = 0, n = nargs(); i != n; ++i)
188 cell(i).updateBuffer(it, utype);
193 bool InsetMathNest::idxNext(Cursor & cur) const
195 LASSERT(&cur.inset() == this, /**/);
196 if (cur.idx() == cur.lastidx())
204 bool InsetMathNest::idxForward(Cursor & cur) const
210 bool InsetMathNest::idxPrev(Cursor & cur) const
212 LASSERT(&cur.inset() == this, /**/);
216 cur.pos() = cur.lastpos();
221 bool InsetMathNest::idxBackward(Cursor & cur) const
227 bool InsetMathNest::idxFirst(Cursor & cur) const
229 LASSERT(&cur.inset() == this, /**/);
238 bool InsetMathNest::idxLast(Cursor & cur) const
240 LASSERT(&cur.inset() == this, /**/);
243 cur.idx() = cur.lastidx();
244 cur.pos() = cur.lastpos();
249 void InsetMathNest::dump() const
251 odocstringstream oss;
253 os << "---------------------------------------------\n";
256 for (idx_type i = 0, n = nargs(); i != n; ++i)
257 os << cell(i) << "\n";
258 os << "---------------------------------------------\n";
259 lyxerr << to_utf8(oss.str());
263 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
267 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
270 setPosCache(pi, x, y);
274 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
276 BufferView & bv = *pi.base.bv;
277 // this should use the x/y values given, not the cached values
278 Cursor & cur = bv.cursor();
279 if (!cur.selection())
281 if (&cur.inset() != this)
284 // FIXME: hack to get position cache warm
285 bool const original_drawing_state = pi.pain.isDrawingEnabled();
286 pi.pain.setDrawingEnabled(false);
288 pi.pain.setDrawingEnabled(original_drawing_state);
290 CursorSlice s1 = cur.selBegin();
291 CursorSlice s2 = cur.selEnd();
293 //lyxerr << "InsetMathNest::drawing selection: "
294 // << " s1: " << s1 << " s2: " << s2 << endl;
295 if (s1.idx() == s2.idx()) {
296 MathData const & c = cell(s1.idx());
297 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
298 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
299 int y1 = g.pos.y_ - g.dim.ascent();
300 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
301 int y2 = g.pos.y_ + g.dim.descent();
302 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
303 //lyxerr << "InsetMathNest::drawing selection 3: "
304 // << " x1: " << x1 << " x2: " << x2
305 // << " y1: " << y1 << " y2: " << y2 << endl;
307 for (idx_type i = 0; i < nargs(); ++i) {
308 if (idxBetween(i, s1.idx(), s2.idx())) {
309 MathData const & c = cell(i);
310 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
312 int y1 = g.pos.y_ - g.dim.ascent();
313 int x2 = g.pos.x_ + g.dim.width();
314 int y2 = g.pos.y_ + g.dim.descent();
315 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
322 void InsetMathNest::validate(LaTeXFeatures & features) const
324 for (idx_type i = 0; i < nargs(); ++i)
325 cell(i).validate(features);
329 void InsetMathNest::replace(ReplaceData & rep)
331 for (idx_type i = 0; i < nargs(); ++i)
332 cell(i).replace(rep);
336 bool InsetMathNest::contains(MathData const & ar) const
338 for (idx_type i = 0; i < nargs(); ++i)
339 if (cell(i).contains(ar))
345 bool InsetMathNest::lock() const
351 void InsetMathNest::lock(bool l)
357 bool InsetMathNest::isActive() const
363 MathData InsetMathNest::glue() const
366 for (size_t i = 0; i < nargs(); ++i)
372 void InsetMathNest::write(WriteStream & os) const
374 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
375 ModeSpecifier specifier(os, currentMode(), lockedMode());
376 docstring const latex_name = name();
377 os << '\\' << latex_name;
378 for (size_t i = 0; i < nargs(); ++i)
379 os << '{' << cell(i) << '}';
381 os.pendingSpace(true);
382 if (lock_ && !os.latex()) {
384 os.pendingSpace(true);
389 void InsetMathNest::normalize(NormalStream & os) const
392 for (size_t i = 0; i < nargs(); ++i)
393 os << ' ' << cell(i);
398 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
400 WriteStream wi(os.os(), runparams.moving_arg, true,
401 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
403 wi.canBreakLine(os.canBreakLine());
405 os.canBreakLine(wi.canBreakLine());
408 if (lf > 0 && runparams.lastid != -1) {
410 os.texrow().newline();
411 os.texrow().start(runparams.lastid, runparams.lastpos);
413 os.texrow().newlines(lf);
417 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
420 mouse_hover_[bv] = mouse_hover;
425 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
429 MathData & ar = cur.cell();
430 // remove base-only "scripts"
431 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
432 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
433 if (p && p->nargs() == 1) {
434 MathData ar = p->nuc();
437 cur.adjust(i, ar.size() - 1);
441 // glue adjacent font insets of the same kind
442 for (pos_type i = 0; i + 1 < size(); ++i) {
443 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
444 InsetMathFont const * q = operator[](i + 1)->asFontInset();
445 if (p && q && p->name() == q->name()) {
446 p->cell(0).append(q->cell(0));
456 void InsetMathNest::handleFont
457 (Cursor & cur, docstring const & arg, char const * const font)
459 handleFont(cur, arg, from_ascii(font));
463 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
464 docstring const & font)
466 cur.recordUndoSelection();
468 // this whole function is a hack and won't work for incremental font
470 if (cur.inset().asInsetMath()->name() == font)
471 cur.handleFont(to_utf8(font));
473 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
477 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
479 handleNest(cur, nest, docstring());
483 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
484 docstring const & arg)
486 CursorSlice i1 = cur.selBegin();
487 CursorSlice i2 = cur.selEnd();
488 if (!i1.inset().asInsetMath())
490 if (i1.idx() == i2.idx()) {
491 // the easy case where only one cell is selected
492 cur.handleNest(nest);
497 // multiple selected cells in a simple non-grid inset
498 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
499 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
504 cur.pos() = cur.lastpos();
507 // change font of cell
508 cur.handleNest(nest);
511 // cur is in the font inset now. If the loop continues,
512 // we need to get outside again for the next cell
513 if (i + 1 <= i2.idx())
519 // the complicated case with multiple selected cells in a grid
522 cap::region(i1, i2, r1, r2, c1, c2);
523 for (row_type row = r1; row <= r2; ++row) {
524 for (col_type col = c1; col <= c2; ++col) {
526 cur.idx() = i1.asInsetMath()->index(row, col);
529 cur.pos() = cur.lastpos();
533 cur.handleNest(nest);
536 // cur is in the font inset now. If the loop continues,
537 // we need to get outside again for the next cell
538 if (col + 1 <= c2 || row + 1 <= r2)
545 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
547 cur.recordUndoSelection();
550 font.fromString(to_utf8(arg), b);
551 if (font.fontInfo().color() != Color_inherit &&
552 font.fontInfo().color() != Color_ignore)
553 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
555 // FIXME: support other font changes here as well?
559 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
561 //LYXERR0("InsetMathNest: request: " << cmd);
563 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
565 FuncCode const act = cmd.action();
568 case LFUN_CLIPBOARD_PASTE:
569 parseflg |= Parse::VERBATIM;
572 if (cur.currentMode() <= TEXT_MODE)
573 parseflg |= Parse::TEXTMODE;
574 cur.recordUndoSelection();
575 cur.message(_("Paste"));
576 replaceSelection(cur);
578 if (cmd.argument().empty() && !theClipboard().isInternal())
579 topaste = theClipboard().getAsText();
582 idocstringstream is(cmd.argument());
584 topaste = cap::selection(n);
586 cur.niceInsert(topaste, parseflg, false);
587 cur.clearSelection(); // bug 393
588 cur.forceBufferUpdate();
595 cutSelection(cur, true, true);
596 cur.message(_("Cut"));
597 // Prevent stale position >= size crash
598 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
600 cur.forceBufferUpdate();
605 cur.message(_("Copy"));
608 case LFUN_MOUSE_PRESS:
609 lfunMousePress(cur, cmd);
612 case LFUN_MOUSE_MOTION:
613 lfunMouseMotion(cur, cmd);
616 case LFUN_MOUSE_RELEASE:
617 lfunMouseRelease(cur, cmd);
620 case LFUN_FINISHED_LEFT: // in math, left is backwards
621 case LFUN_FINISHED_BACKWARD:
622 cur.bv().cursor() = cur;
625 case LFUN_FINISHED_RIGHT: // in math, right is forward
626 case LFUN_FINISHED_FORWARD:
628 cur.bv().cursor() = cur;
631 case LFUN_CHAR_RIGHT:
633 case LFUN_CHAR_BACKWARD:
634 case LFUN_CHAR_FORWARD:
635 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
636 case LFUN_CHAR_RIGHT_SELECT:
637 case LFUN_CHAR_LEFT_SELECT:
638 case LFUN_CHAR_BACKWARD_SELECT:
639 case LFUN_CHAR_FORWARD_SELECT: {
640 // are we in a selection?
641 bool select = (act == LFUN_CHAR_RIGHT_SELECT
642 || act == LFUN_CHAR_LEFT_SELECT
643 || act == LFUN_CHAR_BACKWARD_SELECT
644 || act == LFUN_CHAR_FORWARD_SELECT);
645 // are we moving forward or backwards?
646 // If the command was RIGHT or LEFT, then whether we're moving forward
647 // or backwards depends on the cursor movement mode (logical or visual):
648 // * in visual mode, since math is always LTR, right -> forward,
650 // * in logical mode, the mapping is determined by the
651 // reverseDirectionNeeded() function
654 FuncCode finish_lfun;
656 if (act == LFUN_CHAR_FORWARD
657 || act == LFUN_CHAR_FORWARD_SELECT) {
659 finish_lfun = LFUN_FINISHED_FORWARD;
661 else if (act == LFUN_CHAR_BACKWARD
662 || act == LFUN_CHAR_BACKWARD_SELECT) {
664 finish_lfun = LFUN_FINISHED_BACKWARD;
667 bool right = (act == LFUN_CHAR_RIGHT_SELECT
668 || act == LFUN_CHAR_RIGHT);
669 if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
675 finish_lfun = LFUN_FINISHED_RIGHT;
677 finish_lfun = LFUN_FINISHED_LEFT;
679 // Now that we know exactly what we want to do, let's do it!
680 cur.selHandle(select);
682 cur.macroModeClose();
683 // try moving forward or backwards as necessary...
684 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
685 // ... and if movement failed, then finish forward or backwards
687 cmd = FuncRequest(finish_lfun);
695 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
696 case LFUN_DOWN_SELECT:
697 case LFUN_UP_SELECT: {
698 // close active macro
699 if (cur.inMacroMode()) {
700 cur.macroModeClose();
704 // stop/start the selection
705 bool select = act == LFUN_DOWN_SELECT ||
706 act == LFUN_UP_SELECT;
707 cur.selHandle(select);
709 // handle autocorrect:
710 cur.autocorrect() = false;
711 cur.message(_("Autocorrect Off ('!' to enter)"));
714 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
715 bool successful = cur.upDownInMath(up);
719 if (cur.fixIfBroken())
720 // FIXME: Something bad happened. We pass the corrected Cursor
721 // instead of letting things go worse.
724 // We did not manage to move the cursor.
729 case LFUN_MOUSE_DOUBLE:
730 case LFUN_MOUSE_TRIPLE:
731 case LFUN_WORD_SELECT:
732 case LFUN_INSET_SELECT_ALL:
736 cur.setSelection(true);
737 cur.pos() = cur.lastpos();
738 cur.idx() = cur.lastidx();
741 case LFUN_PARAGRAPH_UP:
742 case LFUN_PARAGRAPH_DOWN:
743 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
744 case LFUN_PARAGRAPH_UP_SELECT:
745 case LFUN_PARAGRAPH_DOWN_SELECT:
748 case LFUN_LINE_BEGIN:
749 case LFUN_WORD_BACKWARD:
751 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
752 case LFUN_LINE_BEGIN_SELECT:
753 case LFUN_WORD_BACKWARD_SELECT:
754 case LFUN_WORD_LEFT_SELECT:
755 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
756 act == LFUN_WORD_LEFT_SELECT ||
757 act == LFUN_LINE_BEGIN_SELECT);
758 cur.macroModeClose();
759 if (cur.pos() != 0) {
761 } else if (cur.col() != 0) {
762 cur.idx() -= cur.col();
764 } else if (cur.idx() != 0) {
768 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
773 case LFUN_WORD_FORWARD:
774 case LFUN_WORD_RIGHT:
776 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
777 case LFUN_WORD_FORWARD_SELECT:
778 case LFUN_WORD_RIGHT_SELECT:
779 case LFUN_LINE_END_SELECT:
780 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
781 act == LFUN_WORD_RIGHT_SELECT ||
782 act == LFUN_LINE_END_SELECT);
783 cur.macroModeClose();
785 if (cur.pos() != cur.lastpos()) {
786 cur.pos() = cur.lastpos();
787 } else if (ncols() && (cur.col() != cur.lastcol())) {
788 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
789 cur.pos() = cur.lastpos();
790 } else if (cur.idx() != cur.lastidx()) {
791 cur.idx() = cur.lastidx();
792 cur.pos() = cur.lastpos();
794 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
799 case LFUN_CELL_FORWARD:
800 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
801 cur.inset().idxNext(cur);
804 case LFUN_CELL_BACKWARD:
805 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
806 cur.inset().idxPrev(cur);
809 case LFUN_WORD_DELETE_BACKWARD:
810 case LFUN_CHAR_DELETE_BACKWARD:
812 // May affect external cell:
813 cur.recordUndoInset();
814 else if (!cur.inMacroMode())
815 cur.recordUndoSelection();
816 // if the inset can not be removed from within, delete it
817 if (!cur.backspace()) {
818 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
819 cur.innerText()->dispatch(cur, cmd);
823 case LFUN_WORD_DELETE_FORWARD:
824 case LFUN_CHAR_DELETE_FORWARD:
825 if (cur.pos() == cur.lastpos())
826 // May affect external cell:
827 cur.recordUndoInset();
829 cur.recordUndoSelection();
830 // if the inset can not be removed from within, delete it
832 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
833 cur.innerText()->dispatch(cur, cmd);
839 cur.clearSelection();
841 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
846 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
847 // that is traversed by a single <CursorLeft>/<CursorRight>.
848 case LFUN_INSET_TOGGLE:
854 case LFUN_SELF_INSERT:
855 if (cmd.argument().size() != 1) {
856 cur.recordUndoSelection();
857 docstring const arg = cmd.argument();
858 if (!interpretString(cur, arg))
862 // Don't record undo steps if we are in macro mode and thus
863 // cmd.argument is the next character of the macro name.
864 // Otherwise we'll get an invalid cursor if we undo after
865 // the macro was finished and the macro is a known command,
866 // e.g. sqrt. Cursor::macroModeClose replaces in this case
867 // the InsetMathUnknown with name "frac" by an empty
868 // InsetMathFrac -> a pos value > 0 is invalid.
869 // A side effect is that an undo before the macro is finished
870 // undoes the complete macro, not only the last character.
871 // At the time we hit '\' we are not in macro mode, still.
872 if (!cur.inMacroMode())
873 cur.recordUndoSelection();
875 // spacial handling of space. If we insert an inset
876 // via macro mode, we want to put the cursor inside it
877 // if relevant. Think typing "\frac<space>".
878 if (cmd.argument()[0] == ' '
879 && cur.inMacroMode() && cur.macroName() != "\\"
880 && cur.macroModeClose() && cur.pos() > 0) {
881 MathAtom const atom = cur.prevAtom();
882 if (atom->asNestInset() && atom->isActive()) {
884 cur.pushBackward(*cur.nextInset());
886 } else if (!interpretChar(cur, cmd.argument()[0])) {
887 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
892 //case LFUN_SERVER_GET_XY:
895 case LFUN_SERVER_SET_XY: {
896 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
899 istringstream is(to_utf8(cmd.argument()));
901 cur.setScreenPos(x, y);
905 // Special casing for superscript in case of LyX handling
907 case LFUN_ACCENT_CIRCUMFLEX:
908 if (cmd.argument().empty()) {
909 // do superscript if LyX handles
911 cur.recordUndoSelection();
912 script(cur, true, grabAndEraseSelection(cur));
916 case LFUN_ACCENT_UMLAUT:
917 case LFUN_ACCENT_ACUTE:
918 case LFUN_ACCENT_GRAVE:
919 case LFUN_ACCENT_BREVE:
920 case LFUN_ACCENT_DOT:
921 case LFUN_ACCENT_MACRON:
922 case LFUN_ACCENT_CARON:
923 case LFUN_ACCENT_TILDE:
924 case LFUN_ACCENT_CEDILLA:
925 case LFUN_ACCENT_CIRCLE:
926 case LFUN_ACCENT_UNDERDOT:
927 case LFUN_ACCENT_TIE:
928 case LFUN_ACCENT_OGONEK:
929 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
933 case LFUN_TEXTSTYLE_APPLY:
934 case LFUN_TEXTSTYLE_UPDATE:
935 handleFont2(cur, cmd.argument());
939 if (currentMode() <= TEXT_MODE)
940 handleFont(cur, cmd.argument(), "textbf");
942 handleFont(cur, cmd.argument(), "mathbf");
944 case LFUN_FONT_BOLDSYMBOL:
945 if (currentMode() <= TEXT_MODE)
946 handleFont(cur, cmd.argument(), "textbf");
948 handleFont(cur, cmd.argument(), "boldsymbol");
951 if (currentMode() <= TEXT_MODE)
952 handleFont(cur, cmd.argument(), "textsf");
954 handleFont(cur, cmd.argument(), "mathsf");
957 if (currentMode() <= TEXT_MODE)
958 handleFont(cur, cmd.argument(), "emph");
960 handleFont(cur, cmd.argument(), "mathcal");
962 case LFUN_FONT_ROMAN:
963 if (currentMode() <= TEXT_MODE)
964 handleFont(cur, cmd.argument(), "textrm");
966 handleFont(cur, cmd.argument(), "mathrm");
968 case LFUN_FONT_TYPEWRITER:
969 if (currentMode() <= TEXT_MODE)
970 handleFont(cur, cmd.argument(), "texttt");
972 handleFont(cur, cmd.argument(), "mathtt");
975 handleFont(cur, cmd.argument(), "mathfrak");
978 if (currentMode() <= TEXT_MODE)
979 handleFont(cur, cmd.argument(), "textit");
981 handleFont(cur, cmd.argument(), "mathit");
984 if (currentMode() <= TEXT_MODE)
985 // FIXME: should be "noun"
986 handleFont(cur, cmd.argument(), "textsc");
988 handleFont(cur, cmd.argument(), "mathbb");
990 case LFUN_FONT_DEFAULT:
991 handleFont(cur, cmd.argument(), "textnormal");
994 case LFUN_FONT_UNDERLINE:
996 cur.handleNest(createInsetMath("underline", cur.buffer()));
998 case LFUN_MATH_MODE: {
1000 // ignore math-mode on when already in math mode
1001 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1003 cur.recordUndoSelection();
1004 cur.macroModeClose();
1005 docstring const save_selection = grabAndEraseSelection(cur);
1007 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
1008 if (currentMode() <= Inset::TEXT_MODE)
1009 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1011 cur.plainInsert(MathAtom(new InsetMathBox(buffer_, from_ascii("mbox"))));
1013 cur.pushBackward(*cur.nextInset());
1014 cur.niceInsert(save_selection);
1015 cur.forceBufferUpdate();
1017 if (currentMode() == Inset::TEXT_MODE) {
1018 cur.recordUndoSelection();
1019 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1020 cur.message(_("create new math text environment ($...$)"));
1022 handleFont(cur, cmd.argument(), "textrm");
1023 cur.message(_("entered math text mode (textrm)"));
1029 case LFUN_REGEXP_MODE: {
1030 InsetMath * im = cur.inset().asInsetMath();
1032 InsetMathHull * i = im->asHullInset();
1033 if (i && i->getType() == hullRegexp) {
1034 cur.message(_("Already in regular expression mode"));
1038 cur.macroModeClose();
1039 docstring const save_selection = grabAndEraseSelection(cur);
1041 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1043 cur.pushBackward(*cur.nextInset());
1044 cur.niceInsert(save_selection);
1045 cur.message(_("Regular expression editor mode"));
1049 case LFUN_MATH_FONT_STYLE: {
1050 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1051 doDispatch(cur, fr);
1055 case LFUN_MATH_SIZE: {
1056 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1057 doDispatch(cur, fr);
1061 case LFUN_MATH_MATRIX: {
1067 idocstringstream is(cmd.argument());
1068 is >> m >> n >> v_align >> h_align;
1074 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1075 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1079 case LFUN_MATH_AMS_MATRIX: {
1084 idocstringstream is(cmd.argument());
1085 is >> m >> n >> name;
1091 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1095 case LFUN_MATH_DELIM: {
1097 docstring rs = split(cmd.argument(), ls, ' ');
1098 // Reasonable default values
1104 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1108 case LFUN_MATH_BIGDELIM: {
1109 docstring const lname = from_utf8(cmd.getArg(0));
1110 docstring const ldelim = from_utf8(cmd.getArg(1));
1111 docstring const rname = from_utf8(cmd.getArg(2));
1112 docstring const rdelim = from_utf8(cmd.getArg(3));
1113 latexkeys const * l = in_word_set(lname);
1114 bool const have_l = l && l->inset == "big" &&
1115 InsetMathBig::isBigInsetDelim(ldelim);
1116 l = in_word_set(rname);
1117 bool const have_r = l && l->inset == "big" &&
1118 InsetMathBig::isBigInsetDelim(rdelim);
1119 // We mimic LFUN_MATH_DELIM in case we have an empty left
1120 // or right delimiter.
1121 if (have_l || have_r) {
1123 docstring const selection = grabAndEraseSelection(cur);
1126 cur.insert(MathAtom(new InsetMathBig(lname,
1128 // first insert the right delimiter and then go back
1129 // and re-insert the selection (bug 7088)
1131 cur.insert(MathAtom(new InsetMathBig(rname,
1135 cur.niceInsert(selection);
1137 // Don't call cur.undispatched() if we did nothing, this would
1138 // lead to infinite recursion via Text::dispatch().
1142 case LFUN_SPACE_INSERT: {
1143 cur.recordUndoSelection();
1144 string const name = cmd.getArg(0);
1145 if (name == "normal")
1146 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1147 else if (name == "protected")
1148 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1149 else if (name == "thin" || name == "med" || name == "thick")
1150 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1151 else if (name == "hfill*")
1152 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1153 else if (name == "quad" || name == "qquad" ||
1154 name == "enspace" || name == "enskip" ||
1155 name == "negthinspace" || name == "negmedspace" ||
1156 name == "negthickspace" || name == "hfill")
1157 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1158 else if (name == "hspace" || name == "hspace*") {
1159 string const len = cmd.getArg(1);
1160 if (len.empty() || !isValidLength(len)) {
1161 lyxerr << "LyX function 'space-insert " << name << "' "
1162 "needs a valid length argument." << endl;
1165 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1167 cur.insert(MathAtom(new InsetMathSpace));
1171 case LFUN_MATH_SPACE:
1172 cur.recordUndoSelection();
1173 if (cmd.argument().empty())
1174 cur.insert(MathAtom(new InsetMathSpace));
1176 string const name = cmd.getArg(0);
1177 string const len = cmd.getArg(1);
1178 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1182 case LFUN_ERT_INSERT:
1183 // interpret this as if a backslash was typed
1185 interpretChar(cur, '\\');
1188 case LFUN_MATH_SUBSCRIPT:
1189 // interpret this as if a _ was typed
1190 cur.recordUndoSelection();
1191 interpretChar(cur, '_');
1194 case LFUN_MATH_SUPERSCRIPT:
1195 // interpret this as if a ^ was typed
1196 cur.recordUndoSelection();
1197 interpretChar(cur, '^');
1200 case LFUN_MATH_MACRO_FOLD:
1201 case LFUN_MATH_MACRO_UNFOLD: {
1203 bool fold = act == LFUN_MATH_MACRO_FOLD;
1204 bool found = findMacroToFoldUnfold(it, fold);
1206 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1207 cur.recordUndoInset();
1216 case LFUN_QUOTE_INSERT:
1217 // interpret this as if a straight " was typed
1218 cur.recordUndoSelection();
1219 interpretChar(cur, '\"');
1222 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1223 // handling such that "self-insert" works on "arbitrary stuff" too, and
1224 // math-insert only handles special math things like "matrix".
1225 case LFUN_MATH_INSERT: {
1226 cur.recordUndoSelection();
1227 if (cmd.argument() == "^" || cmd.argument() == "_")
1228 interpretChar(cur, cmd.argument()[0]);
1231 asArray(cmd.argument(), ar);
1232 if (cur.selection() && ar.size() == 1
1233 && ar[0]->asNestInset()
1234 && ar[0]->asNestInset()->nargs() > 1)
1235 handleNest(cur, ar[0]);
1237 cur.niceInsert(cmd.argument());
1242 case LFUN_UNICODE_INSERT: {
1243 if (cmd.argument().empty())
1245 docstring hexstring = cmd.argument();
1246 if (isHex(hexstring)) {
1247 char_type c = hexToInt(hexstring);
1248 if (c >= 32 && c < 0x10ffff) {
1249 docstring s = docstring(1, c);
1250 FuncCode code = currentMode() == MATH_MODE ?
1251 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1252 lyx::dispatch(FuncRequest(code, s));
1258 case LFUN_DIALOG_SHOW_NEW_INSET: {
1259 docstring const & name = cmd.argument();
1261 if (name == "ref") {
1262 InsetMathRef tmp(buffer_, name);
1263 data = tmp.createDialogStr();
1264 cur.bv().showDialog(to_utf8(name), data);
1265 } else if (name == "mathspace") {
1266 cur.bv().showDialog(to_utf8(name));
1271 case LFUN_INSET_INSERT: {
1273 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1274 cur.recordUndoSelection();
1276 cur.forceBufferUpdate();
1281 case LFUN_INSET_DISSOLVE:
1282 if (!asHullInset()) {
1283 cur.recordUndoInset();
1289 InsetMath::doDispatch(cur, cmd);
1295 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1296 // look for macro to open/close, but stay in mathed
1297 for (; !it.empty(); it.pop_back()) {
1299 // go backward through the current cell
1300 Inset * inset = it.nextInset();
1301 while (inset && inset->asInsetMath()) {
1302 MathMacro * macro = inset->asInsetMath()->asMacro();
1304 // found the an macro to open/close?
1305 if (macro->folded() != fold)
1308 // Wrong folding state.
1309 // If this was the first we see in this slice, look further left,
1311 if (inset != it.nextInset())
1315 // go up if this was the left most position
1321 inset = it.nextInset();
1329 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1330 FuncStatus & flag) const
1332 // the font related toggles
1333 //string tc = "mathnormal";
1335 string const arg = to_utf8(cmd.argument());
1336 switch (cmd.action()) {
1337 case LFUN_INSET_MODIFY:
1338 flag.setEnabled(false);
1341 case LFUN_INSET_MODIFY:
1342 // FIXME: check temporarily disabled
1344 char align = mathcursor::valign();
1345 if (align == '\0') {
1349 if (cmd.argument().empty()) {
1353 if (!contains("tcb", cmd.argument()[0])) {
1357 flag.setOnOff(cmd.argument()[0] == align);
1360 /// We have to handle them since 1.4 blocks all unhandled actions
1361 case LFUN_FONT_ITAL:
1362 case LFUN_FONT_BOLD:
1363 case LFUN_FONT_BOLDSYMBOL:
1364 case LFUN_FONT_SANS:
1365 case LFUN_FONT_EMPH:
1366 case LFUN_FONT_TYPEWRITER:
1367 case LFUN_FONT_NOUN:
1368 case LFUN_FONT_ROMAN:
1369 case LFUN_FONT_DEFAULT:
1370 flag.setEnabled(true);
1373 // we just need to be in math mode to enable that
1374 case LFUN_MATH_SIZE:
1375 case LFUN_MATH_SPACE:
1376 case LFUN_MATH_EXTERN:
1377 flag.setEnabled(true);
1380 case LFUN_FONT_UNDERLINE:
1381 case LFUN_FONT_FRAK:
1382 flag.setEnabled(currentMode() != TEXT_MODE);
1385 case LFUN_MATH_FONT_STYLE: {
1386 bool const textarg =
1387 arg == "textbf" || arg == "textsf" ||
1388 arg == "textrm" || arg == "textmd" ||
1389 arg == "textit" || arg == "textsc" ||
1390 arg == "textsl" || arg == "textup" ||
1391 arg == "texttt" || arg == "textbb" ||
1392 arg == "textnormal";
1393 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1397 case LFUN_MATH_MODE:
1398 // forbid "math-mode on" in math mode to prevent irritating
1399 // behaviour of menu entries (bug 6709)
1400 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1403 case LFUN_MATH_INSERT:
1404 flag.setEnabled(currentMode() != TEXT_MODE);
1407 case LFUN_MATH_AMS_MATRIX:
1408 case LFUN_MATH_MATRIX:
1409 flag.setEnabled(currentMode() == MATH_MODE);
1412 case LFUN_INSET_INSERT: {
1413 // Don't test createMathInset_fromDialogStr(), since
1414 // getStatus is not called with a valid reference and the
1415 // dialog would not be applyable.
1416 string const name = cmd.getArg(0);
1417 flag.setEnabled(name == "ref" || name == "mathspace");
1421 case LFUN_DIALOG_SHOW_NEW_INSET: {
1422 docstring const & name = cmd.argument();
1423 if (name == "space")
1424 flag.setEnabled(false);
1429 case LFUN_MATH_DELIM:
1430 case LFUN_MATH_BIGDELIM:
1431 // Don't do this with multi-cell selections
1432 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1435 case LFUN_MATH_MACRO_FOLD:
1436 case LFUN_MATH_MACRO_UNFOLD: {
1438 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1439 flag.setEnabled(found);
1443 case LFUN_SPECIALCHAR_INSERT:
1444 case LFUN_SCRIPT_INSERT:
1445 // FIXME: These would probably make sense in math-text mode
1446 flag.setEnabled(false);
1449 case LFUN_CAPTION_INSERT:
1450 flag.setEnabled(false);
1453 case LFUN_SPACE_INSERT: {
1454 docstring const & name = cmd.argument();
1455 if (name == "visible")
1456 flag.setEnabled(false);
1460 case LFUN_INSET_DISSOLVE:
1461 flag.setEnabled(!asHullInset());
1472 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1475 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1476 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1477 cur.idx() = enter_front ? 0 : cur.lastidx();
1478 cur.pos() = enter_front ? 0 : cur.lastpos();
1480 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1484 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1487 int dist_min = 1000000;
1488 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1489 int const d = cell(i).dist(cur.bv(), x, y);
1495 MathData & ar = cell(idx_min);
1497 cur.idx() = idx_min;
1498 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1500 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1501 if (dist_min == 0) {
1503 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1504 if (ar[i]->covers(cur.bv(), x, y))
1505 return ar[i].nucleus()->editXY(cur, x, y);
1511 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1513 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1514 BufferView & bv = cur.bv();
1515 if (cmd.button() == mouse_button::button3) {
1516 // Don't do anything if we right-click a
1517 // selection, a context menu will popup.
1518 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1519 && cur < bv.cursor().selectionEnd()) {
1520 cur.noScreenUpdate();
1524 bool do_selection = cmd.button() == mouse_button::button1
1525 && cmd.argument() == "region-select";
1526 bv.mouseSetCursor(cur, do_selection);
1527 if (cmd.button() == mouse_button::button1) {
1528 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1529 // Update the cursor update flags as needed:
1531 // Update::Decoration: tells to update the decoration
1532 // (visual box corners that define
1534 // Update::FitCursor: adjust the screen to the cursor
1535 // position if needed
1536 // cur.result().update(): don't overwrite previously set flags.
1537 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1538 | cur.result().screenUpdate());
1539 } else if (cmd.button() == mouse_button::button2) {
1540 if (cap::selection()) {
1541 // See comment in Text::dispatch why we do this
1542 cap::copySelectionToStack();
1543 cmd = FuncRequest(LFUN_PASTE, "0");
1544 doDispatch(bv.cursor(), cmd);
1547 asArray(theSelection().get(), ar);
1548 bv.cursor().insert(ar);
1554 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1556 // only select with button 1
1557 if (cmd.button() == mouse_button::button1) {
1558 Cursor & bvcur = cur.bv().cursor();
1559 if (bvcur.realAnchor().hasPart(cur)) {
1560 //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1561 bvcur.setCursor(cur);
1562 bvcur.setSelection(true);
1563 //lyxerr << "MOTION " << bvcur << endl;
1570 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1572 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1574 if (cmd.button() == mouse_button::button1) {
1575 if (!cur.selection())
1576 cur.noScreenUpdate();
1578 Cursor & bvcur = cur.bv().cursor();
1579 bvcur.setSelection(true);
1588 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1590 //lyxerr << "interpret 2: '" << c << "'" << endl;
1591 docstring save_selection;
1592 if (c == '^' || c == '_')
1593 save_selection = grabAndEraseSelection(cur);
1596 Buffer * buf = cur.buffer();
1599 if (cur.inMacroMode()) {
1600 docstring name = cur.macroName();
1602 /// are we currently typing '#1' or '#2' or...?
1603 if (name == "\\#") {
1606 if (n >= 1 && n <= 9)
1607 cur.insert(new MathMacroArgument(n));
1611 // do not finish macro for known * commands
1612 MathWordList const & mwl = mathedWordList();
1613 bool star_macro = c == '*'
1614 && (mwl.find(name.substr(1) + "*") != mwl.end()
1615 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1616 if (isAlphaASCII(c) || star_macro) {
1617 cur.activeMacro()->setName(name + docstring(1, c));
1621 // handle 'special char' macros
1626 if (currentMode() <= InsetMath::TEXT_MODE)
1627 cur.niceInsert(createInsetMath("textbackslash", buf));
1629 cur.niceInsert(createInsetMath("backslash", buf));
1630 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1632 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1633 } else if (c == '{') {
1635 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1636 } else if (c == '%') {
1638 cur.niceInsert(MathAtom(new InsetMathComment(buf)));
1639 } else if (c == '#') {
1640 LASSERT(cur.activeMacro(), /**/);
1641 cur.activeMacro()->setName(name + docstring(1, c));
1644 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1649 // One character big delimiters. The others are handled in
1650 // interpretString().
1651 latexkeys const * l = in_word_set(name.substr(1));
1652 if (name[0] == '\\' && l && l->inset == "big") {
1656 delim = from_ascii("\\{");
1659 delim = from_ascii("\\}");
1662 delim = docstring(1, c);
1665 if (InsetMathBig::isBigInsetDelim(delim)) {
1666 // name + delim ared a valid InsetMathBig.
1667 // We can't use cur.macroModeClose() because
1668 // it does not handle delim.
1669 InsetMathUnknown * p = cur.activeMacro();
1672 cur.cell().erase(cur.pos());
1673 cur.plainInsert(MathAtom(
1674 new InsetMathBig(name.substr(1), delim)));
1679 // leave macro mode and try again if necessary
1680 if (cur.macroModeClose()) {
1681 MathAtom const atom = cur.prevAtom();
1682 if (atom->asNestInset() && atom->isActive()) {
1684 cur.pushBackward(*cur.nextInset());
1688 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1690 interpretChar(cur, c);
1695 // leave autocorrect mode if necessary
1696 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1697 cur.autocorrect() = false;
1698 cur.message(_("Autocorrect Off ('!' to enter)"));
1701 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1702 cur.autocorrect() = true;
1703 cur.message(_("Autocorrect On (<space> to exit)"));
1707 // just clear selection on pressing the space bar
1708 if (cur.selection() && c == ' ') {
1709 cur.setSelection(false);
1714 //lyxerr << "starting with macro" << endl;
1715 bool reduced = cap::reduceSelectionToOneCell(cur);
1716 if (reduced || !cur.selection()) {
1717 cur.recordUndoInset();
1718 docstring const safe = cap::grabAndEraseSelection(cur);
1719 if (!cur.inRegexped())
1720 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1722 cur.niceInsert(createInsetMath("backslash", buf));
1730 if (currentMode() <= InsetMath::TEXT_MODE)
1736 if (currentMode() <= InsetMath::TEXT_MODE) {
1737 // insert spaces in text or undecided mode,
1738 // but suppress direct insertion of two spaces in a row
1739 // the still allows typing '<space>a<space>' and deleting the 'a', but
1740 // it is better than nothing...
1741 if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1743 // FIXME: we have to enable full redraw here because of the
1744 // visual box corners that define the inset. If we know for
1745 // sure that we stay within the same cell we can optimize for
1747 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1751 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1752 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1753 // FIXME: we have to enable full redraw here because of the
1754 // visual box corners that define the inset. If we know for
1755 // sure that we stay within the same cell we can optimize for
1757 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1761 if (cur.popForward()) {
1762 // FIXME: we have to enable full redraw here because of the
1763 // visual box corners that define the inset. If we know for
1764 // sure that we stay within the same cell we can optimize for
1766 //cur.screenUpdateFlags(Update::FitCursor);
1770 // if we are at the very end, leave the formula
1771 return cur.pos() != cur.lastpos();
1774 // These should be treated differently when not in text mode:
1775 if (cur.inRegexped()) {
1778 cur.niceInsert(createInsetMath("backslash", buf));
1781 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1788 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1791 cur.niceInsert(createInsetMath("sim", buf));
1797 } else if (currentMode() != InsetMath::TEXT_MODE) {
1799 script(cur, false, save_selection);
1803 script(cur, true, save_selection);
1807 cur.niceInsert(createInsetMath("sim", buf));
1810 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1811 MathAtom at = createInsetMath("text", buf);
1812 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1819 cur.niceInsert(createInsetMath("textasciicircum", buf));
1823 cur.niceInsert(createInsetMath("textasciitilde", buf));
1828 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1829 c == '%' || c == '_') {
1830 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1835 // try auto-correction
1836 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1837 && math_autocorrect(cur.prevAtom(), c))
1840 // no special circumstances, so insert the character without any fuss
1842 if (lyxrc.autocorrection_math) {
1843 if (!cur.autocorrect())
1844 cur.message(_("Autocorrect Off ('!' to enter)"));
1846 cur.message(_("Autocorrect On (<space> to exit)"));
1852 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1854 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1856 if (!cur.empty() && cur.pos() > 0 &&
1857 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1858 if (InsetMathBig::isBigInsetDelim(str)) {
1859 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1860 if (prev[0] == '\\') {
1861 prev = prev.substr(1);
1862 latexkeys const * l = in_word_set(prev);
1863 if (l && l->inset == "big") {
1864 cur.cell()[cur.pos() - 1] =
1865 MathAtom(new InsetMathBig(prev, str));
1875 bool InsetMathNest::script(Cursor & cur, bool up)
1877 return script(cur, up, docstring());
1881 bool InsetMathNest::script(Cursor & cur, bool up,
1882 docstring const & save_selection)
1884 // Hack to get \^ and \_ working
1885 //lyxerr << "handling script: up: " << up << endl;
1886 if (cur.inMacroMode() && cur.macroName() == "\\") {
1888 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1890 interpretChar(cur, '_');
1894 cur.macroModeClose();
1895 if (asScriptInset() && cur.idx() == 0) {
1896 // we are in a nucleus of a script inset, move to _our_ script
1897 InsetMathScript * inset = asScriptInset();
1898 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1900 cur.idx() = inset->idxOfScript(up);
1902 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1904 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1907 cur.idx() = inset->idxOfScript(up);
1908 cur.pos() = cur.lastpos();
1910 // convert the thing to our left to a scriptinset or create a new
1911 // one if in the very first position of the array
1912 if (cur.pos() == 0) {
1913 //lyxerr << "new scriptinset" << endl;
1914 cur.insert(new InsetMathScript(buffer_, up));
1916 //lyxerr << "converting prev atom " << endl;
1917 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1920 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1921 // See comment in MathParser.cpp for special handling of {}-bases
1927 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1928 cur.niceInsert(save_selection);
1930 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1935 bool InsetMathNest::completionSupported(Cursor const & cur) const
1937 return cur.inMacroMode();
1941 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1943 return cur.inMacroMode();
1947 bool InsetMathNest::automaticInlineCompletion() const
1949 return lyxrc.completion_inline_math;
1953 bool InsetMathNest::automaticPopupCompletion() const
1955 return lyxrc.completion_popup_math;
1959 CompletionList const *
1960 InsetMathNest::createCompletionList(Cursor const & cur) const
1962 if (!cur.inMacroMode())
1965 return new MathCompletionList(cur);
1969 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1971 if (!cur.inMacroMode())
1974 return cur.activeMacro()->name();
1978 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1981 if (!cur.inMacroMode())
1984 // append completion to active macro
1985 InsetMathUnknown * inset = cur.activeMacro();
1986 inset->setName(inset->name() + s);
1991 // FIXME: this creates duplicates in the completion popup
1992 // which looks ugly. Moreover the changes the list lengths
1994 confuse the popup as well.
1995 MathCompletionList::addToFavorites(inset->name());
1997 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2004 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2005 Dimension & dim) const
2007 Inset const * inset = cur.activeMacro();
2011 // get inset dimensions
2012 dim = cur.bv().coordCache().insets().dim(inset);
2013 // FIXME: these 3 are no accurate, but should depend on the font.
2014 // Now the popup jumps down if you enter a char with descent > 0.
2019 Point xy = cur.bv().coordCache().insets().xy(inset);
2025 bool InsetMathNest::cursorMathForward(Cursor & cur)
2027 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2028 cur.pushBackward(*cur.nextAtom().nucleus());
2029 cur.inset().idxFirst(cur);
2032 if (cur.posForward() || idxForward(cur))
2034 // try to pop forwards --- but don't pop out of math! leave that to
2036 int s = cur.depth() - 2;
2037 if (s >= 0 && cur[s].inset().asInsetMath())
2038 return cur.popForward();
2043 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2045 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2047 cur.push(*cur.nextAtom().nucleus());
2048 cur.inset().idxLast(cur);
2051 if (cur.posBackward() || idxBackward(cur))
2053 // try to pop backwards --- but don't pop out of math! leave that to
2055 int s = cur.depth() - 2;
2056 if (s >= 0 && cur[s].inset().asInsetMath())
2057 return cur.popBackward();
2062 ////////////////////////////////////////////////////////////////////
2064 MathCompletionList::MathCompletionList(Cursor const & cur)
2066 // fill it with macros from the buffer
2067 MacroNameSet macros;
2068 cur.buffer()->listMacroNames(macros);
2069 MacroNameSet::const_iterator it;
2070 for (it = macros.begin(); it != macros.end(); ++it) {
2071 if (cur.buffer()->getMacro(*it, cur, false))
2072 locals.push_back("\\" + *it);
2074 sort(locals.begin(), locals.end());
2076 if (!globals.empty())
2079 // fill in global macros
2081 MacroTable::globalMacros().getMacroNames(macros);
2082 //lyxerr << "Globals completion macros: ";
2083 for (it = macros.begin(); it != macros.end(); ++it) {
2084 //lyxerr << "\\" + *it << " ";
2085 globals.push_back("\\" + *it);
2087 //lyxerr << std::endl;
2089 // fill in global commands
2090 globals.push_back(from_ascii("\\boxed"));
2091 globals.push_back(from_ascii("\\fbox"));
2092 globals.push_back(from_ascii("\\framebox"));
2093 globals.push_back(from_ascii("\\makebox"));
2094 globals.push_back(from_ascii("\\kern"));
2095 globals.push_back(from_ascii("\\xrightarrow"));
2096 globals.push_back(from_ascii("\\xleftarrow"));
2097 globals.push_back(from_ascii("\\split"));
2098 globals.push_back(from_ascii("\\gathered"));
2099 globals.push_back(from_ascii("\\aligned"));
2100 globals.push_back(from_ascii("\\alignedat"));
2101 globals.push_back(from_ascii("\\cases"));
2102 globals.push_back(from_ascii("\\substack"));
2103 globals.push_back(from_ascii("\\xymatrix"));
2104 globals.push_back(from_ascii("\\Diagram"));
2105 globals.push_back(from_ascii("\\subarray"));
2106 globals.push_back(from_ascii("\\array"));
2107 globals.push_back(from_ascii("\\sqrt"));
2108 globals.push_back(from_ascii("\\root"));
2109 globals.push_back(from_ascii("\\tabular"));
2110 globals.push_back(from_ascii("\\stackrel"));
2111 globals.push_back(from_ascii("\\stackrelthree"));
2112 globals.push_back(from_ascii("\\binom"));
2113 globals.push_back(from_ascii("\\choose"));
2114 globals.push_back(from_ascii("\\brace"));
2115 globals.push_back(from_ascii("\\brack"));
2116 globals.push_back(from_ascii("\\frac"));
2117 globals.push_back(from_ascii("\\over"));
2118 globals.push_back(from_ascii("\\nicefrac"));
2119 globals.push_back(from_ascii("\\unitfrac"));
2120 globals.push_back(from_ascii("\\unitfracthree"));
2121 globals.push_back(from_ascii("\\unitone"));
2122 globals.push_back(from_ascii("\\unittwo"));
2123 globals.push_back(from_ascii("\\infer"));
2124 globals.push_back(from_ascii("\\atop"));
2125 globals.push_back(from_ascii("\\lefteqn"));
2126 globals.push_back(from_ascii("\\boldsymbol"));
2127 globals.push_back(from_ascii("\\bm"));
2128 globals.push_back(from_ascii("\\color"));
2129 globals.push_back(from_ascii("\\normalcolor"));
2130 globals.push_back(from_ascii("\\textcolor"));
2131 globals.push_back(from_ascii("\\cfrac"));
2132 globals.push_back(from_ascii("\\cfracleft"));
2133 globals.push_back(from_ascii("\\cfracright"));
2134 globals.push_back(from_ascii("\\dfrac"));
2135 globals.push_back(from_ascii("\\tfrac"));
2136 globals.push_back(from_ascii("\\dbinom"));
2137 globals.push_back(from_ascii("\\tbinom"));
2138 globals.push_back(from_ascii("\\hphantom"));
2139 globals.push_back(from_ascii("\\phantom"));
2140 globals.push_back(from_ascii("\\vphantom"));
2141 globals.push_back(from_ascii("\\cancel"));
2142 globals.push_back(from_ascii("\\bcancel"));
2143 globals.push_back(from_ascii("\\xcancel"));
2144 globals.push_back(from_ascii("\\cancelto"));
2145 globals.push_back(from_ascii("\\smash"));
2146 globals.push_back(from_ascii("\\mathclap"));
2147 globals.push_back(from_ascii("\\mathllap"));
2148 globals.push_back(from_ascii("\\mathrlap"));
2149 MathWordList const & words = mathedWordList();
2150 MathWordList::const_iterator it2;
2151 //lyxerr << "Globals completion commands: ";
2152 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2153 globals.push_back("\\" + (*it2).first);
2154 //lyxerr << "\\" + (*it2).first << " ";
2156 //lyxerr << std::endl;
2157 sort(globals.begin(), globals.end());
2161 MathCompletionList::~MathCompletionList()
2166 size_type MathCompletionList::size() const
2168 return locals.size() + globals.size();
2172 docstring const & MathCompletionList::data(size_t idx) const
2174 size_t lsize = locals.size();
2176 return globals[idx - lsize];
2182 std::string MathCompletionList::icon(size_t idx) const
2184 // get the latex command
2186 size_t lsize = locals.size();
2188 cmd = globals[idx - lsize];
2192 // get the icon resource name by stripping the backslash
2193 return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
2196 std::vector<docstring> MathCompletionList::globals;