2 * \file InsetMathNest.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathNest.h"
15 #include "InsetMathArray.h"
16 #include "InsetMathAMSArray.h"
17 #include "InsetMathBig.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathBrace.h"
20 #include "InsetMathChar.h"
21 #include "InsetMathColor.h"
22 #include "InsetMathComment.h"
23 #include "InsetMathDelim.h"
24 #include "InsetMathEnsureMath.h"
25 #include "InsetMathHull.h"
26 #include "InsetMathRef.h"
27 #include "InsetMathScript.h"
28 #include "InsetMathSpace.h"
29 #include "InsetMathSymbol.h"
30 #include "InsetMathUnknown.h"
31 #include "MathAutoCorrect.h"
32 #include "MathCompletionList.h"
34 #include "MathFactory.h"
35 #include "MathMacro.h"
36 #include "MathMacroArgument.h"
37 #include "MathParser.h"
38 #include "MathStream.h"
39 #include "MathSupport.h"
42 #include "BufferParams.h"
43 #include "BufferView.h"
44 #include "CoordCache.h"
46 #include "CutAndPaste.h"
47 #include "DispatchResult.h"
49 #include "FuncRequest.h"
50 #include "FuncStatus.h"
51 #include "LaTeXFeatures.h"
54 #include "MetricsInfo.h"
55 #include "OutputParams.h"
59 #include "frontends/Application.h"
60 #include "frontends/Clipboard.h"
61 #include "frontends/Painter.h"
62 #include "frontends/Selection.h"
64 #include "support/debug.h"
65 #include "support/docstream.h"
66 #include "support/gettext.h"
67 #include "support/lassert.h"
68 #include "support/lstrings.h"
69 #include "support/textutils.h"
75 using namespace lyx::support;
79 using cap::copySelection;
80 using cap::grabAndEraseSelection;
81 using cap::cutSelection;
82 using cap::replaceSelection;
83 using cap::selClearOrDel;
86 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
87 : InsetMath(buf), cells_(nargs), lock_(false)
93 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
94 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
98 InsetMathNest::~InsetMathNest()
100 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
101 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
102 for (; it != end; ++it)
104 it->first->clearLastInset(this);
108 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
110 cells_ = inset.cells_;
112 mouse_hover_.clear();
113 InsetMath::operator=(inset);
118 void InsetMathNest::setBuffer(Buffer & buffer)
120 InsetMath::setBuffer(buffer);
121 for (idx_type i = 0, n = nargs(); i != n; ++i) {
122 MathData & data = cell(i);
123 for (size_t j = 0; j != data.size(); ++j)
124 data[j].nucleus()->setBuffer(buffer);
129 InsetMath::idx_type InsetMathNest::nargs() const
131 return cells_.size();
135 void InsetMathNest::cursorPos(BufferView const & bv,
136 CursorSlice const & sl, bool /*boundary*/,
137 int & x, int & y) const
139 // FIXME: This is a hack. Ideally, the coord cache should not store
140 // absolute positions, but relative ones. This would mean to call
141 // setXY() not in MathData::draw(), but in the parent insets' draw()
142 // with the correctly adjusted x,y values. But this means that we'd have
143 // to touch all (math)inset's draw() methods. Right now, we'll store
144 // absolute value, and make them here relative, only to make them
145 // absolute again when actually drawing the cursor. What a mess.
146 LASSERT(&sl.inset() == this, return);
147 MathData const & ar = sl.cell();
148 CoordCache const & coord_cache = bv.coordCache();
149 if (!coord_cache.getArrays().has(&ar)) {
150 // this can (semi-)legally happen if we just created this cell
151 // and it never has been drawn before. So don't ASSERT.
152 //lyxerr << "no cached data for array " << &ar << endl;
157 Point const pt = coord_cache.getArrays().xy(&ar);
158 if (!coord_cache.getInsets().has(this)) {
160 //lyxerr << "no cached data for inset " << this << endl;
165 Point const pt2 = coord_cache.getInsets().xy(this);
166 //lyxerr << "retrieving position cache for MathData "
167 // << pt.x_ << ' ' << pt.y_ << endl;
168 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
170 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
171 // << " asc: " << ascent() << " des: " << descent()
172 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
173 // move cursor visually into empty cells ("blue rectangles");
179 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
182 for (auto const & cell : cells_) {
184 cell.metrics(m, dim);
189 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
191 for (idx_type i = 0, n = nargs(); i != n; ++i)
192 cell(i).updateBuffer(it, utype);
197 bool InsetMathNest::idxNext(Cursor & cur) const
199 LASSERT(&cur.inset() == this, return false);
200 if (cur.idx() == cur.lastidx())
208 bool InsetMathNest::idxForward(Cursor & cur) const
214 bool InsetMathNest::idxPrev(Cursor & cur) const
216 LASSERT(&cur.inset() == this, return false);
220 cur.pos() = cur.lastpos();
225 bool InsetMathNest::idxBackward(Cursor & cur) const
231 bool InsetMathNest::idxFirst(Cursor & cur) const
233 LASSERT(&cur.inset() == this, return false);
242 bool InsetMathNest::idxLast(Cursor & cur) const
244 LASSERT(&cur.inset() == this, return false);
247 cur.idx() = cur.lastidx();
248 cur.pos() = cur.lastpos();
253 void InsetMathNest::dump() const
255 odocstringstream oss;
256 otexrowstream ots(oss);
258 os << "---------------------------------------------\n";
261 for (idx_type i = 0, n = nargs(); i != n; ++i)
262 os << cell(i) << "\n";
263 os << "---------------------------------------------\n";
264 lyxerr << to_utf8(oss.str());
268 void InsetMathNest::draw(PainterInfo &, int, int) const
272 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
278 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
280 BufferView & bv = *pi.base.bv;
281 // this should use the x/y values given, not the cached values
282 Cursor & cur = bv.cursor();
283 if (!cur.selection())
285 if (&cur.inset() != this)
288 // FIXME: hack to get position cache warm
289 bool const original_drawing_state = pi.pain.isDrawingEnabled();
290 pi.pain.setDrawingEnabled(false);
292 pi.pain.setDrawingEnabled(original_drawing_state);
294 CursorSlice s1 = cur.selBegin();
295 CursorSlice s2 = cur.selEnd();
297 //lyxerr << "InsetMathNest::drawing selection: "
298 // << " s1: " << s1 << " s2: " << s2 << endl;
299 if (s1.idx() == s2.idx()) {
300 MathData const & c = cell(s1.idx());
301 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
302 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
303 int y1 = g.pos.y_ - g.dim.ascent();
304 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
305 int y2 = g.pos.y_ + g.dim.descent();
306 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
307 //lyxerr << "InsetMathNest::drawing selection 3: "
308 // << " x1: " << x1 << " x2: " << x2
309 // << " y1: " << y1 << " y2: " << y2 << endl;
311 for (idx_type i = 0; i < nargs(); ++i) {
312 if (idxBetween(i, s1.idx(), s2.idx())) {
313 MathData const & c = cell(i);
314 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
316 int y1 = g.pos.y_ - g.dim.ascent();
317 int x2 = g.pos.x_ + g.dim.width();
318 int y2 = g.pos.y_ + g.dim.descent();
319 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
326 void InsetMathNest::validate(LaTeXFeatures & features) const
328 for (idx_type i = 0; i < nargs(); ++i)
329 cell(i).validate(features);
333 void InsetMathNest::replace(ReplaceData & rep)
335 for (idx_type i = 0; i < nargs(); ++i)
336 cell(i).replace(rep);
340 bool InsetMathNest::contains(MathData const & ar) const
342 for (idx_type i = 0; i < nargs(); ++i)
343 if (cell(i).contains(ar))
349 bool InsetMathNest::lock() const
355 void InsetMathNest::lock(bool l)
361 bool InsetMathNest::isActive() const
367 MathData InsetMathNest::glue() const
370 for (size_t i = 0; i < nargs(); ++i)
376 void InsetMathNest::write(WriteStream & os) const
378 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
379 ModeSpecifier specifier(os, currentMode(), lockedMode());
380 docstring const latex_name = name();
381 os << '\\' << latex_name;
382 for (size_t i = 0; i < nargs(); ++i) {
383 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
384 os << '{' << cell(i) << '}';
387 os.pendingSpace(true);
388 if (lock_ && !os.latex()) {
390 os.pendingSpace(true);
395 void InsetMathNest::normalize(NormalStream & os) const
398 for (size_t i = 0; i < nargs(); ++i)
399 os << ' ' << cell(i);
404 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
406 WriteStream wi(os, runparams.moving_arg, true,
407 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
409 wi.strikeoutMath(runparams.inDeletedInset
410 && (!LaTeXFeatures::isAvailable("dvipost")
411 || (runparams.flavor != OutputParams::LATEX
412 && runparams.flavor != OutputParams::DVILUATEX)));
413 if (runparams.inulemcmd) {
414 wi.ulemCmd(WriteStream::UNDERLINE);
415 if (runparams.local_font) {
416 FontInfo f = runparams.local_font->fontInfo();
417 if (f.strikeout() == FONT_ON)
418 wi.ulemCmd(WriteStream::STRIKEOUT);
421 wi.canBreakLine(os.canBreakLine());
422 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
425 // Reset parbreak status after a math inset.
427 os.canBreakLine(wi.canBreakLine());
431 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
434 mouse_hover_[bv] = mouse_hover;
439 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
443 MathData & ar = cur.cell();
444 // remove base-only "scripts"
445 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
446 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
447 if (p && p->nargs() == 1) {
448 MathData ar = p->nuc();
451 cur.adjust(i, ar.size() - 1);
455 // glue adjacent font insets of the same kind
456 for (pos_type i = 0; i + 1 < size(); ++i) {
457 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
458 InsetMathFont const * q = operator[](i + 1)->asFontInset();
459 if (p && q && p->name() == q->name()) {
460 p->cell(0).append(q->cell(0));
470 void InsetMathNest::handleFont
471 (Cursor & cur, docstring const & arg, char const * const font)
473 handleFont(cur, arg, from_ascii(font));
477 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
478 docstring const & font)
480 cur.recordUndoSelection();
482 // this whole function is a hack and won't work for incremental font
484 if (cur.inset().asInsetMath()->name() == font)
485 cur.handleFont(to_utf8(font));
487 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
491 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
493 handleNest(cur, nest, docstring());
497 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
498 docstring const & arg)
500 CursorSlice i1 = cur.selBegin();
501 CursorSlice i2 = cur.selEnd();
502 if (!i1.inset().asInsetMath())
504 if (i1.idx() == i2.idx()) {
505 // the easy case where only one cell is selected
506 cur.handleNest(nest);
511 // multiple selected cells in a simple non-grid inset
512 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
513 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
518 cur.pos() = cur.lastpos();
521 // change font of cell
522 cur.handleNest(nest);
525 // cur is in the font inset now. If the loop continues,
526 // we need to get outside again for the next cell
527 if (i + 1 <= i2.idx())
533 // the complicated case with multiple selected cells in a grid
536 cap::region(i1, i2, r1, r2, c1, c2);
537 for (row_type row = r1; row <= r2; ++row) {
538 for (col_type col = c1; col <= c2; ++col) {
540 cur.idx() = i1.asInsetMath()->index(row, col);
543 cur.pos() = cur.lastpos();
547 cur.handleNest(nest);
550 // cur is in the font inset now. If the loop continues,
551 // we need to get outside again for the next cell
552 if (col + 1 <= c2 || row + 1 <= r2)
559 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
561 cur.recordUndoSelection();
564 font.fromString(to_utf8(arg), b);
565 if (font.fontInfo().color() != Color_inherit &&
566 font.fontInfo().color() != Color_ignore)
567 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
569 // FIXME: support other font changes here as well?
573 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
575 //LYXERR0("InsetMathNest: request: " << cmd);
577 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
579 FuncCode const act = cmd.action();
582 case LFUN_CLIPBOARD_PASTE:
583 parseflg |= Parse::VERBATIM;
586 if (cur.currentMode() != MATH_MODE)
587 parseflg |= Parse::TEXTMODE;
588 cur.recordUndoSelection();
589 cur.message(_("Paste"));
590 replaceSelection(cur);
592 if (cmd.argument().empty() && !theClipboard().isInternal())
593 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
596 idocstringstream is(cmd.argument());
598 topaste = cap::selection(n, buffer().params().documentClassPtr());
600 cur.niceInsert(topaste, parseflg, false);
601 cur.clearSelection(); // bug 393
602 cur.forceBufferUpdate();
609 cutSelection(cur, true, true);
610 cur.message(_("Cut"));
611 // Prevent stale position >= size crash
612 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
614 cur.forceBufferUpdate();
619 cur.message(_("Copy"));
622 case LFUN_MOUSE_PRESS:
623 lfunMousePress(cur, cmd);
626 case LFUN_MOUSE_MOTION:
627 lfunMouseMotion(cur, cmd);
630 case LFUN_MOUSE_RELEASE:
631 lfunMouseRelease(cur, cmd);
634 case LFUN_FINISHED_LEFT: // in math, left is backwards
635 case LFUN_FINISHED_BACKWARD:
636 cur.bv().cursor() = cur;
639 case LFUN_FINISHED_RIGHT: // in math, right is forward
640 case LFUN_FINISHED_FORWARD:
642 cur.bv().cursor() = cur;
645 case LFUN_WORD_RIGHT:
647 case LFUN_WORD_BACKWARD:
648 case LFUN_WORD_FORWARD:
649 case LFUN_CHAR_RIGHT:
651 case LFUN_CHAR_BACKWARD:
652 case LFUN_CHAR_FORWARD:
653 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
655 case LFUN_WORD_RIGHT_SELECT:
656 case LFUN_WORD_LEFT_SELECT:
657 case LFUN_WORD_BACKWARD_SELECT:
658 case LFUN_WORD_FORWARD_SELECT:
659 case LFUN_CHAR_RIGHT_SELECT:
660 case LFUN_CHAR_LEFT_SELECT:
661 case LFUN_CHAR_BACKWARD_SELECT:
662 case LFUN_CHAR_FORWARD_SELECT: {
663 // are we in a selection?
664 bool select = (act == LFUN_WORD_RIGHT_SELECT
665 || act == LFUN_WORD_LEFT_SELECT
666 || act == LFUN_WORD_BACKWARD_SELECT
667 || act == LFUN_WORD_FORWARD_SELECT
668 || act == LFUN_CHAR_RIGHT_SELECT
669 || act == LFUN_CHAR_LEFT_SELECT
670 || act == LFUN_CHAR_BACKWARD_SELECT
671 || act == LFUN_CHAR_FORWARD_SELECT);
673 bool word = (act == LFUN_WORD_RIGHT_SELECT
674 || act == LFUN_WORD_LEFT_SELECT
675 || act == LFUN_WORD_BACKWARD_SELECT
676 || act == LFUN_WORD_FORWARD_SELECT
677 || act == LFUN_WORD_RIGHT
678 || act == LFUN_WORD_LEFT
679 || act == LFUN_WORD_BACKWARD
680 || act == LFUN_WORD_FORWARD);
681 // are we moving forward or backwards?
682 // If the command was RIGHT or LEFT, then whether we're moving forward
683 // or backwards depends on the cursor movement mode (logical or visual):
684 // * in visual mode, since math is always LTR, right -> forward,
686 // * in logical mode, the mapping is determined by the
687 // reverseDirectionNeeded() function
690 FuncCode finish_lfun;
692 if (act == LFUN_CHAR_FORWARD
693 || act == LFUN_CHAR_FORWARD_SELECT
694 || act == LFUN_WORD_FORWARD
695 || act == LFUN_WORD_FORWARD_SELECT) {
697 finish_lfun = LFUN_FINISHED_FORWARD;
699 else if (act == LFUN_CHAR_BACKWARD
700 || act == LFUN_CHAR_BACKWARD_SELECT
701 || act == LFUN_WORD_BACKWARD
702 || act == LFUN_WORD_BACKWARD_SELECT) {
704 finish_lfun = LFUN_FINISHED_BACKWARD;
707 bool right = (act == LFUN_CHAR_RIGHT_SELECT
708 || act == LFUN_CHAR_RIGHT
709 || act == LFUN_WORD_RIGHT_SELECT
710 || act == LFUN_WORD_RIGHT);
711 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
717 finish_lfun = LFUN_FINISHED_RIGHT;
719 finish_lfun = LFUN_FINISHED_LEFT;
721 // Now that we know exactly what we want to do, let's do it!
722 cur.selHandle(select);
724 cur.macroModeClose();
725 // try moving forward or backwards as necessary...
726 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
727 // ... and if movement failed, then finish forward or backwards
729 cmd = FuncRequest(finish_lfun);
737 case LFUN_PARAGRAPH_UP:
738 case LFUN_PARAGRAPH_DOWN:
739 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
741 case LFUN_DOWN_SELECT:
743 case LFUN_PARAGRAPH_UP_SELECT:
744 case LFUN_PARAGRAPH_DOWN_SELECT: {
745 // close active macro
746 if (cur.inMacroMode()) {
747 cur.macroModeClose();
751 // stop/start the selection
752 bool select = act == LFUN_DOWN_SELECT
753 || act == LFUN_UP_SELECT
754 || act == LFUN_PARAGRAPH_DOWN_SELECT
755 || act == LFUN_PARAGRAPH_UP_SELECT;
756 cur.selHandle(select);
758 // handle autocorrect:
759 if (lyxrc.autocorrection_math && cur.autocorrect()) {
760 cur.autocorrect() = false;
761 cur.message(_("Autocorrect Off ('!' to enter)"));
765 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
766 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
767 bool successful = cur.upDownInMath(up);
771 if (cur.fixIfBroken())
772 // FIXME: Something bad happened. We pass the corrected Cursor
773 // instead of letting things go worse.
776 // We did not manage to move the cursor.
781 case LFUN_MOUSE_DOUBLE:
782 case LFUN_WORD_SELECT:
786 cur.pos() = cur.lastpos();
787 cur.bv().cursor() = cur;
790 case LFUN_MOUSE_TRIPLE:
795 cur.idx() = cur.lastidx();
796 cur.pos() = cur.lastpos();
797 cur.bv().cursor() = cur;
800 case LFUN_LINE_BEGIN:
801 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
803 case LFUN_LINE_BEGIN_SELECT:
804 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
805 act == LFUN_WORD_LEFT_SELECT ||
806 act == LFUN_LINE_BEGIN_SELECT);
807 cur.macroModeClose();
808 if (cur.pos() != 0) {
810 } else if (cur.col() != 0) {
811 cur.idx() -= cur.col();
813 } else if (cur.idx() != 0) {
817 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
823 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
825 case LFUN_LINE_END_SELECT:
826 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
827 act == LFUN_WORD_RIGHT_SELECT ||
828 act == LFUN_LINE_END_SELECT);
829 cur.macroModeClose();
831 if (cur.pos() != cur.lastpos()) {
832 cur.pos() = cur.lastpos();
833 } else if (ncols() && (cur.col() != cur.lastcol())) {
834 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
835 cur.pos() = cur.lastpos();
836 } else if (cur.idx() != cur.lastidx()) {
837 cur.idx() = cur.lastidx();
838 cur.pos() = cur.lastpos();
840 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
845 case LFUN_CELL_FORWARD:
846 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
847 cur.inset().idxNext(cur);
850 case LFUN_CELL_BACKWARD:
851 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
852 cur.inset().idxPrev(cur);
855 case LFUN_WORD_DELETE_BACKWARD:
856 case LFUN_CHAR_DELETE_BACKWARD:
858 // May affect external cell:
859 cur.recordUndoInset();
860 else if (!cur.inMacroMode())
861 cur.recordUndoSelection();
862 // if the inset can not be removed from within, delete it
863 if (!cur.backspace()) {
864 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
865 cur.innerText()->dispatch(cur, cmd);
869 case LFUN_WORD_DELETE_FORWARD:
870 case LFUN_CHAR_DELETE_FORWARD:
871 if (cur.pos() == cur.lastpos())
872 // May affect external cell:
873 cur.recordUndoInset();
875 cur.recordUndoSelection();
876 // if the inset can not be removed from within, delete it
878 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
879 cur.innerText()->dispatch(cur, cmd);
885 cur.clearSelection();
887 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
892 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
893 // that is traversed by a single <CursorLeft>/<CursorRight>.
894 case LFUN_INSET_TOGGLE:
900 case LFUN_SELF_INSERT:
901 if (cmd.argument().size() != 1) {
902 cur.recordUndoSelection();
903 docstring const arg = cmd.argument();
904 if (!interpretString(cur, arg))
908 // Don't record undo steps if we are in macro mode and thus
909 // cmd.argument is the next character of the macro name.
910 // Otherwise we'll get an invalid cursor if we undo after
911 // the macro was finished and the macro is a known command,
912 // e.g. sqrt. Cursor::macroModeClose replaces in this case
913 // the InsetMathUnknown with name "frac" by an empty
914 // InsetMathFrac -> a pos value > 0 is invalid.
915 // A side effect is that an undo before the macro is finished
916 // undoes the complete macro, not only the last character.
917 // At the time we hit '\' we are not in macro mode, still.
918 if (!cur.inMacroMode())
919 cur.recordUndoSelection();
921 // spacial handling of space. If we insert an inset
922 // via macro mode, we want to put the cursor inside it
923 // if relevant. Think typing "\frac<space>".
924 if (cmd.argument()[0] == ' '
925 && cur.inMacroMode() && cur.macroName() != "\\"
926 && cur.macroModeClose() && cur.pos() > 0) {
927 MathAtom const atom = cur.prevAtom();
928 if (atom->asNestInset() && atom->isActive()) {
930 cur.pushBackward(*cur.nextInset());
932 } else if (!interpretChar(cur, cmd.argument()[0])) {
933 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
938 //case LFUN_SERVER_GET_XY:
941 case LFUN_SERVER_SET_XY: {
942 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
945 istringstream is(to_utf8(cmd.argument()));
947 cur.setScreenPos(x, y);
951 // Special casing for superscript in case of LyX handling
953 case LFUN_ACCENT_CIRCUMFLEX:
954 if (cmd.argument().empty()) {
955 // do superscript if LyX handles
957 cur.recordUndoSelection();
958 script(cur, true, grabAndEraseSelection(cur));
962 case LFUN_ACCENT_UMLAUT:
963 case LFUN_ACCENT_ACUTE:
964 case LFUN_ACCENT_GRAVE:
965 case LFUN_ACCENT_BREVE:
966 case LFUN_ACCENT_DOT:
967 case LFUN_ACCENT_MACRON:
968 case LFUN_ACCENT_CARON:
969 case LFUN_ACCENT_TILDE:
970 case LFUN_ACCENT_CEDILLA:
971 case LFUN_ACCENT_CIRCLE:
972 case LFUN_ACCENT_UNDERDOT:
973 case LFUN_ACCENT_TIE:
974 case LFUN_ACCENT_OGONEK:
975 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
979 case LFUN_TEXTSTYLE_APPLY:
980 case LFUN_TEXTSTYLE_UPDATE:
981 handleFont2(cur, cmd.argument());
985 if (currentMode() != MATH_MODE)
986 handleFont(cur, cmd.argument(), "textbf");
988 handleFont(cur, cmd.argument(), "mathbf");
990 case LFUN_FONT_BOLDSYMBOL:
991 if (currentMode() != MATH_MODE)
992 handleFont(cur, cmd.argument(), "textbf");
994 handleFont(cur, cmd.argument(), "boldsymbol");
997 if (currentMode() != MATH_MODE)
998 handleFont(cur, cmd.argument(), "textsf");
1000 handleFont(cur, cmd.argument(), "mathsf");
1002 case LFUN_FONT_EMPH:
1003 if (currentMode() != MATH_MODE)
1004 handleFont(cur, cmd.argument(), "emph");
1006 handleFont(cur, cmd.argument(), "mathcal");
1008 case LFUN_FONT_ROMAN:
1009 if (currentMode() != MATH_MODE)
1010 handleFont(cur, cmd.argument(), "textrm");
1012 handleFont(cur, cmd.argument(), "mathrm");
1014 case LFUN_FONT_TYPEWRITER:
1015 if (currentMode() != MATH_MODE)
1016 handleFont(cur, cmd.argument(), "texttt");
1018 handleFont(cur, cmd.argument(), "mathtt");
1020 case LFUN_FONT_FRAK:
1021 handleFont(cur, cmd.argument(), "mathfrak");
1023 case LFUN_FONT_ITAL:
1024 if (currentMode() != MATH_MODE)
1025 handleFont(cur, cmd.argument(), "textit");
1027 handleFont(cur, cmd.argument(), "mathit");
1029 case LFUN_FONT_NOUN:
1030 if (currentMode() != MATH_MODE)
1031 // FIXME: should be "noun"
1032 handleFont(cur, cmd.argument(), "textsc");
1034 handleFont(cur, cmd.argument(), "mathbb");
1036 case LFUN_FONT_DEFAULT:
1037 handleFont(cur, cmd.argument(), "textnormal");
1039 case LFUN_FONT_UNDERLINE:
1041 cur.handleNest(createInsetMath("underline", cur.buffer()));
1044 case LFUN_MATH_MODE: {
1046 // ignore math-mode on when already in math mode
1047 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1049 cur.recordUndoSelection();
1050 cur.macroModeClose();
1051 docstring const save_selection = grabAndEraseSelection(cur);
1053 if (currentMode() != Inset::MATH_MODE)
1054 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1056 cur.plainInsert(createInsetMath("text", buffer_));
1058 cur.pushBackward(*cur.nextInset());
1059 cur.niceInsert(save_selection);
1060 cur.forceBufferUpdate();
1062 if (currentMode() == Inset::TEXT_MODE) {
1063 cur.recordUndoSelection();
1064 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1065 cur.message(_("create new math text environment ($...$)"));
1067 handleFont(cur, cmd.argument(), "textrm");
1068 cur.message(_("entered math text mode (textrm)"));
1074 case LFUN_REGEXP_MODE: {
1075 InsetMath * im = cur.inset().asInsetMath();
1077 InsetMathHull * i = im->asHullInset();
1078 if (i && i->getType() == hullRegexp) {
1079 cur.message(_("Already in regular expression mode"));
1083 cur.macroModeClose();
1084 docstring const save_selection = grabAndEraseSelection(cur);
1086 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1088 cur.pushBackward(*cur.nextInset());
1089 cur.niceInsert(save_selection);
1090 cur.message(_("Regular expression editor mode"));
1094 case LFUN_MATH_FONT_STYLE: {
1095 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1096 doDispatch(cur, fr);
1100 case LFUN_MATH_SIZE: {
1101 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1102 doDispatch(cur, fr);
1106 case LFUN_MATH_MATRIX: {
1112 idocstringstream is(cmd.argument());
1113 is >> m >> n >> v_align >> h_align;
1119 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1120 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1124 case LFUN_MATH_AMS_MATRIX: {
1128 docstring name = from_ascii("matrix");
1129 idocstringstream is(cmd.argument());
1130 is >> m >> n >> name;
1135 // check if we have a valid decoration
1136 if (name != "pmatrix" && name != "bmatrix"
1137 && name != "Bmatrix" && name != "vmatrix"
1138 && name != "Vmatrix" && name != "matrix")
1139 name = from_ascii("matrix");
1142 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1146 case LFUN_MATH_DELIM: {
1148 docstring rs = split(cmd.argument(), ls, ' ');
1149 // Reasonable default values
1155 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1159 case LFUN_MATH_BIGDELIM: {
1160 docstring const lname = from_utf8(cmd.getArg(0));
1161 docstring const ldelim = from_utf8(cmd.getArg(1));
1162 docstring const rname = from_utf8(cmd.getArg(2));
1163 docstring const rdelim = from_utf8(cmd.getArg(3));
1164 latexkeys const * l = in_word_set(lname);
1165 bool const have_l = l && l->inset == "big" &&
1166 InsetMathBig::isBigInsetDelim(ldelim);
1167 l = in_word_set(rname);
1168 bool const have_r = l && l->inset == "big" &&
1169 InsetMathBig::isBigInsetDelim(rdelim);
1170 // We mimic LFUN_MATH_DELIM in case we have an empty left
1171 // or right delimiter.
1172 if (have_l || have_r) {
1174 docstring const selection = grabAndEraseSelection(cur);
1177 cur.insert(MathAtom(new InsetMathBig(lname,
1179 // first insert the right delimiter and then go back
1180 // and re-insert the selection (bug 7088)
1182 cur.insert(MathAtom(new InsetMathBig(rname,
1186 cur.niceInsert(selection);
1188 // Don't call cur.undispatched() if we did nothing, this would
1189 // lead to infinite recursion via Text::dispatch().
1193 case LFUN_SPACE_INSERT: {
1194 cur.recordUndoSelection();
1195 string const name = cmd.getArg(0);
1196 if (name == "normal")
1197 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1198 else if (name == "protected")
1199 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1200 else if (name == "thin" || name == "med" || name == "thick")
1201 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1202 else if (name == "hfill*")
1203 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1204 else if (name == "quad" || name == "qquad" ||
1205 name == "enspace" || name == "enskip" ||
1206 name == "negthinspace" || name == "negmedspace" ||
1207 name == "negthickspace" || name == "hfill")
1208 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1209 else if (name == "hspace" || name == "hspace*") {
1210 string const len = cmd.getArg(1);
1211 if (len.empty() || !isValidLength(len)) {
1212 lyxerr << "LyX function 'space-insert " << name << "' "
1213 "needs a valid length argument." << endl;
1216 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1218 cur.insert(MathAtom(new InsetMathSpace));
1222 case LFUN_MATH_SPACE:
1223 cur.recordUndoSelection();
1224 if (cmd.argument().empty())
1225 cur.insert(MathAtom(new InsetMathSpace));
1227 string const name = cmd.getArg(0);
1228 string const len = cmd.getArg(1);
1229 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1233 case LFUN_ERT_INSERT:
1234 // interpret this as if a backslash was typed
1236 interpretChar(cur, '\\');
1239 case LFUN_MATH_SUBSCRIPT:
1240 // interpret this as if a _ was typed
1241 cur.recordUndoSelection();
1242 interpretChar(cur, '_');
1245 case LFUN_MATH_SUPERSCRIPT:
1246 // interpret this as if a ^ was typed
1247 cur.recordUndoSelection();
1248 interpretChar(cur, '^');
1251 case LFUN_MATH_MACRO_FOLD:
1252 case LFUN_MATH_MACRO_UNFOLD: {
1254 bool fold = act == LFUN_MATH_MACRO_FOLD;
1255 bool found = findMacroToFoldUnfold(it, fold);
1257 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1258 cur.recordUndoInset();
1267 case LFUN_QUOTE_INSERT:
1268 // interpret this as if a straight " was typed
1269 cur.recordUndoSelection();
1270 interpretChar(cur, '\"');
1273 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1274 // handling such that "self-insert" works on "arbitrary stuff" too, and
1275 // math-insert only handles special math things like "matrix".
1276 case LFUN_MATH_INSERT: {
1277 cur.recordUndoSelection();
1278 if (cmd.argument() == "^" || cmd.argument() == "_")
1279 interpretChar(cur, cmd.argument()[0]);
1282 asArray(cmd.argument(), ar);
1283 if (cur.selection() && ar.size() == 1
1284 && ar[0]->asNestInset()
1285 && ar[0]->asNestInset()->nargs() > 1)
1286 handleNest(cur, ar[0]);
1288 cur.niceInsert(cmd.argument());
1293 case LFUN_UNICODE_INSERT: {
1294 if (cmd.argument().empty())
1296 docstring hexstring = cmd.argument();
1297 if (isHex(hexstring)) {
1298 char_type c = hexToInt(hexstring);
1299 if (c >= 32 && c < 0x10ffff) {
1300 docstring s = docstring(1, c);
1301 FuncCode code = currentMode() == MATH_MODE ?
1302 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1303 lyx::dispatch(FuncRequest(code, s));
1309 case LFUN_DIALOG_SHOW_NEW_INSET: {
1310 docstring const & name = cmd.argument();
1312 if (name == "ref") {
1313 InsetMathRef tmp(buffer_, name);
1314 data = tmp.createDialogStr();
1315 cur.bv().showDialog(to_utf8(name), data);
1316 } else if (name == "mathspace") {
1317 cur.bv().showDialog(to_utf8(name));
1322 case LFUN_INSET_INSERT: {
1324 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1325 cur.recordUndoSelection();
1327 cur.forceBufferUpdate();
1332 case LFUN_INSET_DISSOLVE:
1333 if (!asHullInset()) {
1334 cur.recordUndoInset();
1340 InsetMath::doDispatch(cur, cmd);
1346 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1347 // look for macro to open/close, but stay in mathed
1348 for (; !it.empty(); it.pop_back()) {
1350 // go backward through the current cell
1351 Inset * inset = it.nextInset();
1352 while (inset && inset->asInsetMath()) {
1353 MathMacro * macro = inset->asInsetMath()->asMacro();
1355 // found the an macro to open/close?
1356 if (macro->folded() != fold)
1359 // Wrong folding state.
1360 // If this was the first we see in this slice, look further left,
1362 if (inset != it.nextInset())
1366 // go up if this was the left most position
1372 inset = it.nextInset();
1380 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1381 FuncStatus & flag) const
1383 // the font related toggles
1384 //string tc = "mathnormal";
1386 string const arg = to_utf8(cmd.argument());
1387 switch (cmd.action()) {
1388 case LFUN_INSET_MODIFY:
1389 flag.setEnabled(false);
1392 case LFUN_INSET_MODIFY:
1393 // FIXME: check temporarily disabled
1395 char align = mathcursor::valign();
1396 if (align == '\0') {
1400 if (cmd.argument().empty()) {
1404 if (!contains("tcb", cmd.argument()[0])) {
1408 flag.setOnOff(cmd.argument()[0] == align);
1411 /// We have to handle them since 1.4 blocks all unhandled actions
1412 case LFUN_FONT_ITAL:
1413 case LFUN_FONT_BOLD:
1414 case LFUN_FONT_BOLDSYMBOL:
1415 case LFUN_FONT_SANS:
1416 case LFUN_FONT_EMPH:
1417 case LFUN_FONT_TYPEWRITER:
1418 case LFUN_FONT_NOUN:
1419 case LFUN_FONT_ROMAN:
1420 case LFUN_FONT_DEFAULT:
1421 flag.setEnabled(true);
1424 // we just need to be in math mode to enable that
1425 case LFUN_MATH_SIZE:
1426 case LFUN_MATH_SPACE:
1427 case LFUN_MATH_EXTERN:
1428 flag.setEnabled(true);
1431 case LFUN_FONT_UNDERLINE:
1432 case LFUN_FONT_FRAK:
1433 flag.setEnabled(currentMode() != TEXT_MODE);
1436 case LFUN_MATH_FONT_STYLE: {
1437 bool const textarg =
1438 arg == "textbf" || arg == "textsf" ||
1439 arg == "textrm" || arg == "textmd" ||
1440 arg == "textit" || arg == "textsc" ||
1441 arg == "textsl" || arg == "textup" ||
1442 arg == "texttt" || arg == "textbb" ||
1443 arg == "textnormal";
1444 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1448 case LFUN_MATH_MODE:
1449 // forbid "math-mode on" in math mode to prevent irritating
1450 // behaviour of menu entries (bug 6709)
1451 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1454 case LFUN_MATH_INSERT:
1455 flag.setEnabled(currentMode() != TEXT_MODE);
1458 case LFUN_MATH_AMS_MATRIX:
1459 case LFUN_MATH_MATRIX:
1460 flag.setEnabled(currentMode() == MATH_MODE);
1463 case LFUN_INSET_INSERT: {
1464 // Don't test createMathInset_fromDialogStr(), since
1465 // getStatus is not called with a valid reference and the
1466 // dialog would not be applyable.
1467 string const name = cmd.getArg(0);
1468 flag.setEnabled(name == "ref" || name == "mathspace");
1472 case LFUN_DIALOG_SHOW_NEW_INSET: {
1473 docstring const & name = cmd.argument();
1474 if (name == "space")
1475 flag.setEnabled(false);
1480 case LFUN_MATH_DELIM:
1481 case LFUN_MATH_BIGDELIM:
1482 // Don't do this with multi-cell selections
1483 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1486 case LFUN_MATH_MACRO_FOLD:
1487 case LFUN_MATH_MACRO_UNFOLD: {
1489 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1490 flag.setEnabled(found);
1494 case LFUN_SPECIALCHAR_INSERT:
1495 case LFUN_SCRIPT_INSERT:
1496 // FIXME: These would probably make sense in math-text mode
1497 flag.setEnabled(false);
1500 case LFUN_CAPTION_INSERT:
1501 flag.setEnabled(false);
1504 case LFUN_SPACE_INSERT: {
1505 docstring const & name = cmd.argument();
1506 if (name == "visible")
1507 flag.setEnabled(false);
1511 case LFUN_INSET_DISSOLVE:
1512 flag.setEnabled(!asHullInset());
1516 docstring const & name = cmd.argument();
1517 if (name == "html" || name == "latex")
1518 flag.setEnabled(false);
1530 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1533 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1534 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1535 cur.idx() = enter_front ? 0 : cur.lastidx();
1536 cur.pos() = enter_front ? 0 : cur.lastpos();
1538 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1542 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1545 int dist_min = 1000000;
1546 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1547 int const d = cell(i).dist(cur.bv(), x, y);
1553 MathData & ar = cell(idx_min);
1555 cur.idx() = idx_min;
1556 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1558 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1559 if (dist_min == 0) {
1561 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1562 if (ar[i]->covers(cur.bv(), x, y))
1563 return ar[i].nucleus()->editXY(cur, x, y);
1569 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1571 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1572 BufferView & bv = cur.bv();
1573 if (cmd.button() == mouse_button::button3) {
1574 // Don't do anything if we right-click a
1575 // selection, a context menu will popup.
1576 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1577 && cur < bv.cursor().selectionEnd()) {
1578 cur.noScreenUpdate();
1582 bool do_selection = cmd.button() == mouse_button::button1
1583 && cmd.modifier() == ShiftModifier;
1584 bv.mouseSetCursor(cur, do_selection);
1585 if (cmd.button() == mouse_button::button1) {
1586 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1587 // Update the cursor update flags as needed:
1589 // Update::Decoration: tells to update the decoration
1590 // (visual box corners that define
1592 // Update::FitCursor: adjust the screen to the cursor
1593 // position if needed
1594 // cur.result().update(): don't overwrite previously set flags.
1595 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1596 | cur.result().screenUpdate());
1597 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1598 if (cap::selection()) {
1599 // See comment in Text::dispatch why we do this
1600 cap::copySelectionToStack();
1601 cmd = FuncRequest(LFUN_PASTE, "0");
1602 doDispatch(bv.cursor(), cmd);
1605 asArray(theSelection().get(), ar);
1606 bv.cursor().insert(ar);
1612 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1614 // only select with button 1
1615 if (cmd.button() != mouse_button::button1)
1618 Cursor & bvcur = cur.bv().cursor();
1620 // ignore motions deeper nested than the real anchor
1621 if (!bvcur.realAnchor().hasPart(cur)) {
1626 CursorSlice old = bvcur.top();
1628 // We continue with our existing selection or start a new one, so don't
1629 // reset the anchor.
1630 bvcur.setCursor(cur);
1631 // Did we actually move?
1632 if (cur.top() == old)
1633 // We didn't move one iota, so no need to change selection status
1634 // or update the screen.
1635 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1637 bvcur.setSelection();
1641 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1643 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1645 if (cmd.button() == mouse_button::button1) {
1646 if (!cur.selection())
1647 cur.noScreenUpdate();
1649 Cursor & bvcur = cur.bv().cursor();
1650 bvcur.selection(true);
1659 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1661 //lyxerr << "interpret 2: '" << c << "'" << endl;
1662 docstring save_selection;
1663 if (c == '^' || c == '_')
1664 save_selection = grabAndEraseSelection(cur);
1667 Buffer * buf = cur.buffer();
1670 if (cur.inMacroMode()) {
1671 docstring name = cur.macroName();
1673 /// are we currently typing '#1' or '#2' or...?
1674 if (name == "\\#") {
1677 if (n >= 1 && n <= 9)
1678 cur.insert(new MathMacroArgument(n));
1682 // do not finish macro for known * commands
1683 bool star_macro = c == '*'
1684 && (in_word_set(name.substr(1) + '*')
1685 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1686 if (isAlphaASCII(c) || star_macro) {
1687 cur.activeMacro()->setName(name + docstring(1, c));
1691 // handle 'special char' macros
1696 if (currentMode() != InsetMath::MATH_MODE)
1697 cur.niceInsert(createInsetMath("textbackslash", buf));
1699 cur.niceInsert(createInsetMath("backslash", buf));
1700 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1702 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1703 } else if (c == '{' || c == '%') {
1704 //using the saved selection as argument
1705 InsetMathUnknown * p = cur.activeMacro();
1707 MathData sel(cur.buffer());
1708 asArray(p->selection(), sel);
1711 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1713 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1714 } else if (c == '#') {
1715 LASSERT(cur.activeMacro(), return false);
1716 cur.activeMacro()->setName(name + docstring(1, c));
1719 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1724 // One character big delimiters. The others are handled in
1725 // interpretString().
1726 latexkeys const * l = in_word_set(name.substr(1));
1727 if (name[0] == '\\' && l && l->inset == "big") {
1731 delim = from_ascii("\\{");
1734 delim = from_ascii("\\}");
1737 delim = docstring(1, c);
1740 if (InsetMathBig::isBigInsetDelim(delim)) {
1741 // name + delim ared a valid InsetMathBig.
1742 // We can't use cur.macroModeClose() because
1743 // it does not handle delim.
1744 InsetMathUnknown * p = cur.activeMacro();
1747 cur.cell().erase(cur.pos());
1748 cur.plainInsert(MathAtom(
1749 new InsetMathBig(name.substr(1), delim)));
1752 } else if (name == "\\smash" && c == '[') {
1753 // We can't use cur.macroModeClose() because
1754 // it would create an InsetMathPhantom
1755 InsetMathUnknown * p = cur.activeMacro();
1757 interpretChar(cur, c);
1761 // leave macro mode and try again if necessary
1762 if (cur.macroModeClose()) {
1763 MathAtom const atom = cur.prevAtom();
1764 if (atom->asNestInset() && atom->isActive()) {
1766 cur.pushBackward(*cur.nextInset());
1770 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1772 interpretChar(cur, c);
1777 // leave autocorrect mode if necessary
1778 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1779 cur.autocorrect() = false;
1780 cur.message(_("Autocorrect Off ('!' to enter)"));
1783 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1784 cur.autocorrect() = true;
1785 cur.message(_("Autocorrect On (<space> to exit)"));
1789 // just clear selection on pressing the space bar
1790 if (cur.selection() && c == ' ') {
1791 cur.selection(false);
1796 //lyxerr << "starting with macro" << endl;
1797 bool reduced = cap::reduceSelectionToOneCell(cur);
1798 if (reduced || !cur.selection()) {
1799 cur.recordUndoInset();
1800 docstring const safe = cap::grabAndEraseSelection(cur);
1801 if (!cur.inRegexped())
1802 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1804 cur.niceInsert(createInsetMath("backslash", buf));
1812 if (currentMode() != InsetMath::MATH_MODE)
1818 if (currentMode() != InsetMath::MATH_MODE) {
1819 // insert spaces in text or undecided mode,
1820 // but suppress direct insertion of two spaces in a row
1821 // the still allows typing '<space>a<space>' and deleting the 'a', but
1822 // it is better than nothing...
1823 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1825 // FIXME: we have to enable full redraw here because of the
1826 // visual box corners that define the inset. If we know for
1827 // sure that we stay within the same cell we can optimize for
1829 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1833 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1834 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1835 // FIXME: we have to enable full redraw here because of the
1836 // visual box corners that define the inset. If we know for
1837 // sure that we stay within the same cell we can optimize for
1839 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1843 if (cur.popForward()) {
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::FitCursor);
1852 // if we are at the very end, leave the formula
1853 return cur.pos() != cur.lastpos();
1856 // These should be treated differently when not in text mode:
1857 if (cur.inRegexped()) {
1860 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1867 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1870 cur.niceInsert(createInsetMath("sim", buf));
1876 } else if (currentMode() != InsetMath::TEXT_MODE) {
1878 script(cur, false, save_selection);
1882 script(cur, true, save_selection);
1886 cur.niceInsert(createInsetMath("sim", buf));
1889 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1890 MathAtom at = createInsetMath("text", buf);
1891 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1898 cur.niceInsert(createInsetMath("textasciicircum", buf));
1902 cur.niceInsert(createInsetMath("textasciitilde", buf));
1907 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1908 c == '%' || c == '_') {
1909 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1914 // try auto-correction
1915 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1916 && math_autocorrect(cur.prevAtom(), c))
1919 // no special circumstances, so insert the character without any fuss
1921 if (lyxrc.autocorrection_math) {
1922 if (!cur.autocorrect())
1923 cur.message(_("Autocorrect Off ('!' to enter)"));
1925 cur.message(_("Autocorrect On (<space> to exit)"));
1931 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1933 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1935 if (!cur.empty() && cur.pos() > 0 &&
1936 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1937 if (InsetMathBig::isBigInsetDelim(str)) {
1938 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1939 if (prev[0] == '\\') {
1940 prev = prev.substr(1);
1941 latexkeys const * l = in_word_set(prev);
1942 if (l && l->inset == "big") {
1943 cur.cell()[cur.pos() - 1] =
1944 MathAtom(new InsetMathBig(prev, str));
1954 bool InsetMathNest::script(Cursor & cur, bool up)
1956 return script(cur, up, docstring());
1960 bool InsetMathNest::script(Cursor & cur, bool up,
1961 docstring const & save_selection)
1963 // Hack to get \^ and \_ working
1964 //lyxerr << "handling script: up: " << up << endl;
1965 if (cur.inMacroMode() && cur.macroName() == "\\") {
1967 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1969 interpretChar(cur, '_');
1973 cur.macroModeClose();
1974 if (asScriptInset() && cur.idx() == 0) {
1975 // we are in a nucleus of a script inset, move to _our_ script
1976 InsetMathScript * inset = asScriptInset();
1977 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1979 cur.idx() = inset->idxOfScript(up);
1981 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1983 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1986 cur.idx() = inset->idxOfScript(up);
1987 cur.pos() = cur.lastpos();
1989 // convert the thing to our left to a scriptinset or create a new
1990 // one if in the very first position of the array
1991 if (cur.pos() == 0) {
1992 //lyxerr << "new scriptinset" << endl;
1993 cur.insert(new InsetMathScript(buffer_, up));
1995 //lyxerr << "converting prev atom " << endl;
1996 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1999 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
2000 // See comment in MathParser.cpp for special handling of {}-bases
2006 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
2007 cur.niceInsert(save_selection);
2009 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2014 bool InsetMathNest::completionSupported(Cursor const & cur) const
2016 return cur.inMacroMode();
2020 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2022 return cur.inMacroMode();
2026 bool InsetMathNest::automaticInlineCompletion() const
2028 return lyxrc.completion_inline_math;
2032 bool InsetMathNest::automaticPopupCompletion() const
2034 return lyxrc.completion_popup_math;
2038 CompletionList const *
2039 InsetMathNest::createCompletionList(Cursor const & cur) const
2041 if (!cur.inMacroMode())
2044 return new MathCompletionList(cur);
2048 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2050 if (!cur.inMacroMode())
2053 return cur.activeMacro()->name();
2057 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2060 if (!cur.inMacroMode())
2063 // append completion to active macro
2064 InsetMathUnknown * inset = cur.activeMacro();
2065 inset->setName(inset->name() + s);
2070 // FIXME: this creates duplicates in the completion popup
2071 // which looks ugly. Moreover the changes the list lengths
2073 confuse the popup as well.
2074 MathCompletionList::addToFavorites(inset->name());
2076 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2083 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2084 Dimension & dim) const
2086 Inset const * inset = cur.activeMacro();
2090 // get inset dimensions
2091 dim = cur.bv().coordCache().insets().dim(inset);
2092 // FIXME: these 3 are no accurate, but should depend on the font.
2093 // Now the popup jumps down if you enter a char with descent > 0.
2098 Point xy = cur.bv().coordCache().insets().xy(inset);
2104 ////////////////////////////////////////////////////////////////////
2106 MathCompletionList::MathCompletionList(Cursor const & cur)
2108 // fill it with macros from the buffer
2109 MacroNameSet macros;
2110 cur.buffer()->listMacroNames(macros);
2111 MacroNameSet::const_iterator it;
2112 for (it = macros.begin(); it != macros.end(); ++it) {
2113 if (cur.buffer()->getMacro(*it, cur, false))
2114 locals.push_back("\\" + *it);
2116 sort(locals.begin(), locals.end());
2118 if (!globals.empty())
2121 // fill in global macros
2123 MacroTable::globalMacros().getMacroNames(macros, false);
2124 //lyxerr << "Globals completion macros: ";
2125 for (it = macros.begin(); it != macros.end(); ++it) {
2126 //lyxerr << "\\" + *it << " ";
2127 globals.push_back("\\" + *it);
2129 //lyxerr << std::endl;
2131 // fill in global commands
2132 globals.push_back(from_ascii("\\boxed"));
2133 globals.push_back(from_ascii("\\fbox"));
2134 globals.push_back(from_ascii("\\framebox"));
2135 globals.push_back(from_ascii("\\makebox"));
2136 globals.push_back(from_ascii("\\kern"));
2137 globals.push_back(from_ascii("\\xhookrightarrow"));
2138 globals.push_back(from_ascii("\\xhookleftarrow"));
2139 globals.push_back(from_ascii("\\xrightarrow"));
2140 globals.push_back(from_ascii("\\xRightarrow"));
2141 globals.push_back(from_ascii("\\xrightharpoondown"));
2142 globals.push_back(from_ascii("\\xrightharpoonup"));
2143 globals.push_back(from_ascii("\\xrightleftharpoons"));
2144 globals.push_back(from_ascii("\\xleftarrow"));
2145 globals.push_back(from_ascii("\\xLeftarrow"));
2146 globals.push_back(from_ascii("\\xleftharpoondown"));
2147 globals.push_back(from_ascii("\\xleftharpoonup"));
2148 globals.push_back(from_ascii("\\xleftrightarrow"));
2149 globals.push_back(from_ascii("\\xLeftrightarrow"));
2150 globals.push_back(from_ascii("\\xleftrightharpoons"));
2151 globals.push_back(from_ascii("\\xmapsto"));
2152 globals.push_back(from_ascii("\\split"));
2153 globals.push_back(from_ascii("\\gathered"));
2154 globals.push_back(from_ascii("\\aligned"));
2155 globals.push_back(from_ascii("\\alignedat"));
2156 globals.push_back(from_ascii("\\cases"));
2157 globals.push_back(from_ascii("\\substack"));
2158 globals.push_back(from_ascii("\\xymatrix"));
2159 globals.push_back(from_ascii("\\Diagram"));
2160 globals.push_back(from_ascii("\\subarray"));
2161 globals.push_back(from_ascii("\\array"));
2162 globals.push_back(from_ascii("\\sqrt"));
2163 globals.push_back(from_ascii("\\root"));
2164 globals.push_back(from_ascii("\\tabular"));
2165 globals.push_back(from_ascii("\\sideset"));
2166 globals.push_back(from_ascii("\\stackrel"));
2167 globals.push_back(from_ascii("\\stackrelthree"));
2168 globals.push_back(from_ascii("\\binom"));
2169 globals.push_back(from_ascii("\\choose"));
2170 globals.push_back(from_ascii("\\brace"));
2171 globals.push_back(from_ascii("\\brack"));
2172 globals.push_back(from_ascii("\\frac"));
2173 globals.push_back(from_ascii("\\over"));
2174 globals.push_back(from_ascii("\\nicefrac"));
2175 globals.push_back(from_ascii("\\unitfrac"));
2176 globals.push_back(from_ascii("\\unitfracthree"));
2177 globals.push_back(from_ascii("\\unitone"));
2178 globals.push_back(from_ascii("\\unittwo"));
2179 globals.push_back(from_ascii("\\infer"));
2180 globals.push_back(from_ascii("\\atop"));
2181 globals.push_back(from_ascii("\\lefteqn"));
2182 globals.push_back(from_ascii("\\boldsymbol"));
2183 globals.push_back(from_ascii("\\bm"));
2184 globals.push_back(from_ascii("\\color"));
2185 globals.push_back(from_ascii("\\normalcolor"));
2186 globals.push_back(from_ascii("\\textcolor"));
2187 globals.push_back(from_ascii("\\cfrac"));
2188 globals.push_back(from_ascii("\\cfracleft"));
2189 globals.push_back(from_ascii("\\cfracright"));
2190 globals.push_back(from_ascii("\\dfrac"));
2191 globals.push_back(from_ascii("\\tfrac"));
2192 globals.push_back(from_ascii("\\dbinom"));
2193 globals.push_back(from_ascii("\\tbinom"));
2194 globals.push_back(from_ascii("\\hphantom"));
2195 globals.push_back(from_ascii("\\phantom"));
2196 globals.push_back(from_ascii("\\vphantom"));
2197 globals.push_back(from_ascii("\\cancel"));
2198 globals.push_back(from_ascii("\\bcancel"));
2199 globals.push_back(from_ascii("\\xcancel"));
2200 globals.push_back(from_ascii("\\cancelto"));
2201 globals.push_back(from_ascii("\\smash"));
2202 globals.push_back(from_ascii("\\mathclap"));
2203 globals.push_back(from_ascii("\\mathllap"));
2204 globals.push_back(from_ascii("\\mathrlap"));
2205 globals.push_back(from_ascii("\\ensuremath"));
2206 MathWordList const & words = mathedWordList();
2207 MathWordList::const_iterator it2;
2208 //lyxerr << "Globals completion commands: ";
2209 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2210 if (it2->second.inset != "macro" && !it2->second.hidden) {
2211 // macros are already read from MacroTable::globalMacros()
2212 globals.push_back('\\' + it2->first);
2213 //lyxerr << '\\' + it2->first << ' ';
2216 //lyxerr << std::endl;
2217 sort(globals.begin(), globals.end());
2221 MathCompletionList::~MathCompletionList()
2226 size_type MathCompletionList::size() const
2228 return locals.size() + globals.size();
2232 docstring const & MathCompletionList::data(size_t idx) const
2234 size_t lsize = locals.size();
2236 return globals[idx - lsize];
2242 std::string MathCompletionList::icon(size_t idx) const
2244 // get the latex command
2246 size_t lsize = locals.size();
2248 cmd = globals[idx - lsize];
2252 // get the icon resource name by stripping the backslash
2253 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2254 if (icon_name.empty())
2255 return std::string();
2256 return "images/math/" + to_utf8(icon_name);
2259 std::vector<docstring> MathCompletionList::globals;