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"
33 #include "MathFactory.h"
34 #include "InsetMathMacro.h"
35 #include "InsetMathMacroArgument.h"
36 #include "MathParser.h"
37 #include "MathStream.h"
38 #include "MathSupport.h"
41 #include "BufferParams.h"
42 #include "BufferView.h"
43 #include "CoordCache.h"
45 #include "CutAndPaste.h"
46 #include "DispatchResult.h"
48 #include "FuncRequest.h"
49 #include "FuncStatus.h"
50 #include "LaTeXFeatures.h"
53 #include "MetricsInfo.h"
54 #include "OutputParams.h"
58 #include "frontends/Application.h"
59 #include "frontends/Clipboard.h"
60 #include "frontends/Painter.h"
61 #include "frontends/Selection.h"
63 #include "support/debug.h"
64 #include "support/docstream.h"
65 #include "support/gettext.h"
66 #include "support/lassert.h"
67 #include "support/lstrings.h"
68 #include "support/textutils.h"
74 using namespace lyx::support;
78 using cap::copySelection;
79 using cap::grabAndEraseSelection;
80 using cap::cutSelection;
81 using cap::replaceSelection;
82 using cap::selClearOrDel;
85 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
86 : InsetMath(buf), cells_(nargs), lock_(false)
92 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
93 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
97 InsetMathNest::~InsetMathNest()
99 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
100 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
101 for (; it != end; ++it)
103 it->first->clearLastInset(this);
107 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
109 cells_ = inset.cells_;
111 mouse_hover_.clear();
112 InsetMath::operator=(inset);
117 void InsetMathNest::setBuffer(Buffer & buffer)
119 InsetMath::setBuffer(buffer);
120 for (MathData & data : cells_)
121 data.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, return);
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");
171 Dimension const dim = coord_cache.getArrays().dim(&ar);
177 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
180 for (auto const & cell : cells_) {
182 cell.metrics(m, dim);
187 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
189 for (idx_type i = 0, n = nargs(); i != n; ++i)
190 cell(i).updateBuffer(it, utype, deleted);
195 bool InsetMathNest::idxNext(Cursor & cur) const
197 LASSERT(&cur.inset() == this, return false);
198 if (cur.idx() == cur.lastidx())
206 bool InsetMathNest::idxForward(Cursor & cur) const
212 bool InsetMathNest::idxPrev(Cursor & cur) const
214 LASSERT(&cur.inset() == this, return false);
218 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
223 bool InsetMathNest::idxBackward(Cursor & cur) const
229 bool InsetMathNest::idxFirst(Cursor & cur) const
231 LASSERT(&cur.inset() == this, return false);
234 cur.idx() = firstIdx();
240 bool InsetMathNest::idxLast(Cursor & cur) const
242 LASSERT(&cur.inset() == this, return false);
245 cur.idx() = lastIdx();
246 cur.pos() = cur.lastpos();
251 void InsetMathNest::dump() const
253 odocstringstream oss;
254 otexrowstream ots(oss);
256 os << "---------------------------------------------\n";
259 for (idx_type i = 0, n = nargs(); i != n; ++i)
260 os << cell(i) << "\n";
261 os << "---------------------------------------------\n";
262 lyxerr << to_utf8(oss.str());
266 void InsetMathNest::draw(PainterInfo &, int, int) const
270 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
276 void InsetMathNest::validate(LaTeXFeatures & features) const
278 for (idx_type i = 0; i < nargs(); ++i)
279 cell(i).validate(features);
283 void InsetMathNest::replace(ReplaceData & rep)
285 for (idx_type i = 0; i < nargs(); ++i)
286 cell(i).replace(rep);
290 bool InsetMathNest::contains(MathData const & ar) const
292 for (idx_type i = 0; i < nargs(); ++i)
293 if (cell(i).contains(ar))
299 bool InsetMathNest::lock() const
305 void InsetMathNest::lock(bool l)
311 bool InsetMathNest::isActive() const
317 MathData InsetMathNest::glue() const
320 for (size_t i = 0; i < nargs(); ++i)
326 void InsetMathNest::write(WriteStream & os) const
328 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
329 ModeSpecifier specifier(os, currentMode(), lockedMode());
330 docstring const latex_name = name();
331 os << '\\' << latex_name;
332 os.inMathClass(asClassInset());
333 for (size_t i = 0; i < nargs(); ++i) {
334 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
335 os << '{' << cell(i) << '}';
338 os.pendingSpace(true);
339 if (lock_ && !os.latex()) {
341 os.pendingSpace(true);
343 os.inMathClass(false);
347 void InsetMathNest::normalize(NormalStream & os) const
350 for (size_t i = 0; i < nargs(); ++i)
351 os << ' ' << cell(i);
356 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
358 WriteStream wi(os, runparams.moving_arg, true,
359 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
361 wi.strikeoutMath(runparams.inDeletedInset);
362 if (runparams.inulemcmd) {
363 wi.ulemCmd(WriteStream::UNDERLINE);
364 if (runparams.local_font) {
365 FontInfo f = runparams.local_font->fontInfo();
366 if (f.strikeout() == FONT_ON)
367 wi.ulemCmd(WriteStream::STRIKEOUT);
370 wi.canBreakLine(os.canBreakLine());
371 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
374 // Reset parbreak and command termination status after a math inset.
376 os.canBreakLine(wi.canBreakLine());
377 os.terminateCommand(false);
381 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
384 mouse_hover_[bv] = mouse_hover;
389 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
393 MathData & ar = cur.cell();
394 // remove base-only "scripts"
395 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
396 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
397 if (p && p->nargs() == 1) {
398 MathData ar = p->nuc();
401 cur.adjust(i, ar.size() - 1);
405 // glue adjacent font insets of the same kind
406 for (pos_type i = 0; i + 1 < size(); ++i) {
407 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
408 InsetMathFont const * q = operator[](i + 1)->asFontInset();
409 if (p && q && p->name() == q->name()) {
410 p->cell(0).append(q->cell(0));
420 void InsetMathNest::handleFont
421 (Cursor & cur, docstring const & arg, char const * const font)
423 handleFont(cur, arg, from_ascii(font));
427 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
428 docstring const & font)
430 cur.recordUndoSelection();
432 // this whole function is a hack and won't work for incremental font
434 if (cur.inset().asInsetMath()->name() == font)
435 cur.handleFont(to_utf8(font));
437 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
441 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
443 handleNest(cur, nest, docstring());
447 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
448 docstring const & arg)
450 CursorSlice i1 = cur.selBegin();
451 CursorSlice i2 = cur.selEnd();
452 if (!i1.inset().asInsetMath())
454 if (i1.idx() == i2.idx()) {
455 // the easy case where only one cell is selected
456 cur.handleNest(nest);
461 // multiple selected cells in a simple non-grid inset
462 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
463 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
468 cur.pos() = cur.lastpos();
471 // change font of cell
472 cur.handleNest(nest);
475 // cur is in the font inset now. If the loop continues,
476 // we need to get outside again for the next cell
477 if (i + 1 <= i2.idx())
483 // the complicated case with multiple selected cells in a grid
486 cap::region(i1, i2, r1, r2, c1, c2);
487 for (row_type row = r1; row <= r2; ++row) {
488 for (col_type col = c1; col <= c2; ++col) {
490 cur.idx() = i1.asInsetMath()->index(row, col);
493 cur.pos() = cur.lastpos();
497 cur.handleNest(nest);
500 // cur is in the font inset now. If the loop continues,
501 // we need to get outside again for the next cell
502 if (col + 1 <= c2 || row + 1 <= r2)
509 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
511 cur.recordUndoSelection();
514 font.fromString(to_utf8(arg), b);
515 if (font.fontInfo().color() != Color_inherit &&
516 font.fontInfo().color() != Color_ignore)
517 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
519 // FIXME: support other font changes here as well?
522 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
524 //LYXERR0("InsetMathNest: request: " << cmd);
526 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
528 FuncCode const act = cmd.action();
531 case LFUN_CLIPBOARD_PASTE:
532 parseflg |= Parse::VERBATIM;
535 if (cur.currentMode() != MATH_MODE)
536 parseflg |= Parse::TEXTMODE;
537 cur.recordUndoSelection();
538 cur.message(_("Paste"));
539 replaceSelection(cur);
541 if (cmd.argument().empty() && !theClipboard().isInternal())
542 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
545 idocstringstream is(cmd.argument());
547 topaste = cap::selection(n, buffer().params().documentClassPtr());
549 cur.niceInsert(topaste, parseflg, false);
550 cur.clearSelection(); // bug 393
551 cur.forceBufferUpdate();
558 cutSelection(cur, true);
559 cur.message(_("Cut"));
560 // Prevent stale position >= size crash
561 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
563 cur.forceBufferUpdate();
568 cur.message(_("Copy"));
571 case LFUN_MOUSE_PRESS:
572 lfunMousePress(cur, cmd);
575 case LFUN_MOUSE_MOTION:
576 lfunMouseMotion(cur, cmd);
579 case LFUN_MOUSE_RELEASE:
580 lfunMouseRelease(cur, cmd);
583 case LFUN_FINISHED_LEFT: // in math, left is backwards
584 case LFUN_FINISHED_BACKWARD:
585 cur.bv().cursor() = cur;
588 case LFUN_FINISHED_RIGHT: // in math, right is forward
589 case LFUN_FINISHED_FORWARD:
591 cur.bv().cursor() = cur;
594 case LFUN_WORD_RIGHT:
596 case LFUN_WORD_BACKWARD:
597 case LFUN_WORD_FORWARD:
598 case LFUN_CHAR_RIGHT:
600 case LFUN_CHAR_BACKWARD:
601 case LFUN_CHAR_FORWARD:
602 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
604 case LFUN_WORD_RIGHT_SELECT:
605 case LFUN_WORD_LEFT_SELECT:
606 case LFUN_WORD_BACKWARD_SELECT:
607 case LFUN_WORD_FORWARD_SELECT:
608 case LFUN_CHAR_RIGHT_SELECT:
609 case LFUN_CHAR_LEFT_SELECT:
610 case LFUN_CHAR_BACKWARD_SELECT:
611 case LFUN_CHAR_FORWARD_SELECT: {
612 // are we in a selection?
613 bool select = (act == LFUN_WORD_RIGHT_SELECT
614 || act == LFUN_WORD_LEFT_SELECT
615 || act == LFUN_WORD_BACKWARD_SELECT
616 || act == LFUN_WORD_FORWARD_SELECT
617 || act == LFUN_CHAR_RIGHT_SELECT
618 || act == LFUN_CHAR_LEFT_SELECT
619 || act == LFUN_CHAR_BACKWARD_SELECT
620 || act == LFUN_CHAR_FORWARD_SELECT);
622 bool word = (act == LFUN_WORD_RIGHT_SELECT
623 || act == LFUN_WORD_LEFT_SELECT
624 || act == LFUN_WORD_BACKWARD_SELECT
625 || act == LFUN_WORD_FORWARD_SELECT
626 || act == LFUN_WORD_RIGHT
627 || act == LFUN_WORD_LEFT
628 || act == LFUN_WORD_BACKWARD
629 || act == LFUN_WORD_FORWARD);
630 // are we moving forward or backwards?
631 // If the command was RIGHT or LEFT, then whether we're moving forward
632 // or backwards depends on the cursor movement mode (logical or visual):
633 // * in visual mode, since math is always LTR, right -> forward,
635 // * in logical mode, the mapping is determined by the
636 // reverseDirectionNeeded() function
639 FuncCode finish_lfun;
641 if (act == LFUN_CHAR_FORWARD
642 || act == LFUN_CHAR_FORWARD_SELECT
643 || act == LFUN_WORD_FORWARD
644 || act == LFUN_WORD_FORWARD_SELECT) {
646 finish_lfun = LFUN_FINISHED_FORWARD;
648 else if (act == LFUN_CHAR_BACKWARD
649 || act == LFUN_CHAR_BACKWARD_SELECT
650 || act == LFUN_WORD_BACKWARD
651 || act == LFUN_WORD_BACKWARD_SELECT) {
653 finish_lfun = LFUN_FINISHED_BACKWARD;
656 bool right = (act == LFUN_CHAR_RIGHT_SELECT
657 || act == LFUN_CHAR_RIGHT
658 || act == LFUN_WORD_RIGHT_SELECT
659 || act == LFUN_WORD_RIGHT);
660 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
666 finish_lfun = LFUN_FINISHED_RIGHT;
668 finish_lfun = LFUN_FINISHED_LEFT;
670 // Now that we know exactly what we want to do, let's do it!
671 cur.selHandle(select);
673 cur.macroModeClose();
674 // try moving forward or backwards as necessary...
675 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
676 // ... and if movement failed, then finish forward or backwards
678 cmd = FuncRequest(finish_lfun);
686 case LFUN_PARAGRAPH_UP:
687 case LFUN_PARAGRAPH_DOWN:
688 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
690 case LFUN_DOWN_SELECT:
692 case LFUN_PARAGRAPH_UP_SELECT:
693 case LFUN_PARAGRAPH_DOWN_SELECT: {
694 // close active macro
695 if (cur.inMacroMode()) {
696 cur.macroModeClose();
700 // stop/start the selection
701 bool select = act == LFUN_DOWN_SELECT
702 || act == LFUN_UP_SELECT
703 || act == LFUN_PARAGRAPH_DOWN_SELECT
704 || act == LFUN_PARAGRAPH_UP_SELECT;
705 cur.selHandle(select);
708 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
709 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
710 bool successful = cur.upDownInMath(up);
714 if (cur.fixIfBroken())
715 // FIXME: Something bad happened. We pass the corrected Cursor
716 // instead of letting things go worse.
719 // We did not manage to move the cursor.
724 case LFUN_MOUSE_DOUBLE:
725 case LFUN_WORD_SELECT:
727 cur.bv().mouseSetCursor(cur);
728 cur.pos() = cur.lastpos();
729 cur.bv().mouseSetCursor(cur, true);
732 case LFUN_MOUSE_TRIPLE:
735 cur.bv().mouseSetCursor(cur);
736 cur.idx() = cur.lastidx();
737 cur.pos() = cur.lastpos();
738 cur.bv().mouseSetCursor(cur, true);
741 case LFUN_LINE_BEGIN:
742 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
744 case LFUN_LINE_BEGIN_SELECT:
745 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
746 act == LFUN_WORD_LEFT_SELECT ||
747 act == LFUN_LINE_BEGIN_SELECT);
748 cur.macroModeClose();
749 if (cur.pos() != 0) {
751 } else if (cur.col() != 0) {
752 cur.idx() -= cur.col();
754 } else if (cur.idx() != 0) {
758 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
764 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
766 case LFUN_LINE_END_SELECT:
767 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
768 act == LFUN_WORD_RIGHT_SELECT ||
769 act == LFUN_LINE_END_SELECT);
770 cur.macroModeClose();
772 if (cur.pos() != cur.lastpos()) {
773 cur.pos() = cur.lastpos();
774 } else if (ncols() && (cur.col() != cur.lastcol())) {
775 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
776 cur.pos() = cur.lastpos();
777 } else if (cur.idx() != cur.lastidx()) {
778 cur.idx() = cur.lastidx();
779 cur.pos() = cur.lastpos();
781 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
786 case LFUN_CELL_FORWARD:
787 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
788 cur.selHandle(false);
790 cur.macroModeClose();
791 if (!cur.inset().idxNext(cur)) {
792 cur.idx() = firstIdx();
797 case LFUN_CELL_BACKWARD:
798 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
799 cur.selHandle(false);
801 cur.macroModeClose();
802 if (!cur.inset().idxPrev(cur)) {
803 cur.idx() = lastIdx();
804 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
808 case LFUN_WORD_DELETE_BACKWARD:
809 case LFUN_CHAR_DELETE_BACKWARD:
811 // May affect external cell:
812 cur.recordUndoInset();
813 else if (!cur.inMacroMode())
814 cur.recordUndoSelection();
815 // if the inset can not be removed from within, delete it
816 if (!cur.backspace(cmd.getArg(0) == "force")) {
817 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
818 cur.innerText()->dispatch(cur, newcmd);
822 case LFUN_WORD_DELETE_FORWARD:
823 case LFUN_CHAR_DELETE_FORWARD:
824 if (cur.pos() == cur.lastpos())
825 // May affect external cell:
826 cur.recordUndoInset();
828 cur.recordUndoSelection();
829 // if the inset can not be removed from within, delete it
830 if (!cur.erase(cmd.getArg(0) == "force")) {
831 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
832 cur.innerText()->dispatch(cur, newcmd);
838 cur.clearSelection();
840 if (cur.inMacroMode())
841 cur.macroModeClose(true);
843 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
849 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
850 // that is traversed by a single <CursorLeft>/<CursorRight>.
851 case LFUN_INSET_TOGGLE:
857 case LFUN_SELF_INSERT:
858 // special case first for big delimiters
859 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
862 for (char_type c : cmd.argument()) {
863 // Don't record undo steps if we are in macro mode and thus
864 // cmd.argument is the next character of the macro name.
865 // Otherwise we'll get an invalid cursor if we undo after
866 // the macro was finished and the macro is a known command,
867 // e.g. sqrt. Cursor::macroModeClose replaces in this case
868 // the InsetMathUnknown with name "frac" by an empty
869 // InsetMathFrac -> a pos value > 0 is invalid.
870 // A side effect is that an undo before the macro is finished
871 // undoes the complete macro, not only the last character.
872 // At the time we hit '\' we are not in macro mode, still.
873 if (!cur.inMacroMode())
874 cur.recordUndoSelection();
876 // special handling of space. If we insert an inset
877 // via macro mode, we want to put the cursor inside it
878 // if relevant. Think typing "\frac<space>".
880 && cur.inMacroMode() && cur.macroName() != "\\"
881 && cur.macroModeClose() && cur.pos() > 0)
882 cur.editInsertedInset();
883 else if (!interpretChar(cur, c)) {
884 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
886 // FIXME: can we avoid skipping the end of the string?
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()));
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() != MATH_MODE)
940 handleFont(cur, cmd.argument(), "textbf");
942 handleFont(cur, cmd.argument(), "mathbf");
944 case LFUN_FONT_BOLDSYMBOL:
945 if (currentMode() != MATH_MODE)
946 handleFont(cur, cmd.argument(), "textbf");
948 handleFont(cur, cmd.argument(), "boldsymbol");
951 if (currentMode() != MATH_MODE)
952 handleFont(cur, cmd.argument(), "textsf");
954 handleFont(cur, cmd.argument(), "mathsf");
957 if (currentMode() != MATH_MODE)
958 handleFont(cur, cmd.argument(), "emph");
960 handleFont(cur, cmd.argument(), "mathcal");
962 case LFUN_FONT_ROMAN:
963 if (currentMode() != MATH_MODE)
964 handleFont(cur, cmd.argument(), "textrm");
966 handleFont(cur, cmd.argument(), "mathrm");
968 case LFUN_FONT_TYPEWRITER:
969 if (currentMode() != MATH_MODE)
970 handleFont(cur, cmd.argument(), "texttt");
972 handleFont(cur, cmd.argument(), "mathtt");
975 handleFont(cur, cmd.argument(), "mathfrak");
978 if (currentMode() != MATH_MODE)
979 handleFont(cur, cmd.argument(), "textit");
981 handleFont(cur, cmd.argument(), "mathit");
984 if (currentMode() != MATH_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");
993 case LFUN_FONT_UNDERLINE:
995 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 if (currentMode() != Inset::MATH_MODE)
1008 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1010 cur.plainInsert(createInsetMath("text", buffer_));
1012 cur.pushBackward(*cur.nextInset());
1013 cur.niceInsert(save_selection);
1014 cur.forceBufferUpdate();
1016 if (currentMode() == Inset::TEXT_MODE) {
1017 cur.recordUndoSelection();
1018 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1019 cur.message(_("create new math text environment ($...$)"));
1021 handleFont(cur, cmd.argument(), "textrm");
1022 cur.message(_("entered math text mode (textrm)"));
1028 case LFUN_REGEXP_MODE: {
1029 InsetMath * im = cur.inset().asInsetMath();
1031 InsetMathHull * i = im->asHullInset();
1032 if (i && i->getType() == hullRegexp) {
1033 cur.message(_("Already in regular expression mode"));
1037 cur.macroModeClose();
1038 docstring const save_selection = grabAndEraseSelection(cur);
1040 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1042 cur.pushBackward(*cur.nextInset());
1043 cur.niceInsert(save_selection);
1044 cur.message(_("Regular expression editor mode"));
1048 case LFUN_MATH_FONT_STYLE: {
1049 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1050 doDispatch(cur, fr);
1054 case LFUN_MATH_SIZE: {
1055 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1056 doDispatch(cur, fr);
1060 case LFUN_MATH_MATRIX: {
1066 idocstringstream is(cmd.argument());
1067 is >> m >> n >> v_align >> h_align;
1073 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1074 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1078 case LFUN_MATH_AMS_MATRIX: {
1082 docstring name = from_ascii("matrix");
1083 idocstringstream is(cmd.argument());
1084 is >> m >> n >> name;
1089 // check if we have a valid decoration
1090 if (name != "pmatrix" && name != "bmatrix"
1091 && name != "Bmatrix" && name != "vmatrix"
1092 && name != "Vmatrix" && name != "matrix"
1093 && name != "smallmatrix")
1094 name = from_ascii("matrix");
1097 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1101 case LFUN_MATH_DELIM: {
1103 docstring rs = split(cmd.argument(), ls, ' ');
1104 // Reasonable default values
1110 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1114 case LFUN_MATH_BIGDELIM: {
1115 docstring const lname = from_utf8(cmd.getArg(0));
1116 docstring const ldelim = from_utf8(cmd.getArg(1));
1117 docstring const rname = from_utf8(cmd.getArg(2));
1118 docstring const rdelim = from_utf8(cmd.getArg(3));
1119 latexkeys const * l = in_word_set(lname);
1120 bool const have_l = l && l->inset == "big" &&
1121 InsetMathBig::isBigInsetDelim(ldelim);
1122 l = in_word_set(rname);
1123 bool const have_r = l && l->inset == "big" &&
1124 InsetMathBig::isBigInsetDelim(rdelim);
1125 // We mimic LFUN_MATH_DELIM in case we have an empty left
1126 // or right delimiter.
1127 if (have_l || have_r) {
1129 docstring const selection = grabAndEraseSelection(cur);
1132 cur.insert(MathAtom(new InsetMathBig(lname,
1134 // first insert the right delimiter and then go back
1135 // and re-insert the selection (bug 7088)
1137 cur.insert(MathAtom(new InsetMathBig(rname,
1141 cur.niceInsert(selection);
1143 // Don't call cur.undispatched() if we did nothing, this would
1144 // lead to infinite recursion via Text::dispatch().
1148 case LFUN_SPACE_INSERT: {
1149 cur.recordUndoSelection();
1150 string const name = cmd.getArg(0);
1151 if (name == "normal")
1152 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1153 else if (name == "protected")
1154 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1155 else if (name == "thin" || name == "med" || name == "thick")
1156 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1157 else if (name == "hfill*")
1158 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1159 else if (name == "quad" || name == "qquad" ||
1160 name == "enspace" || name == "enskip" ||
1161 name == "negthinspace" || name == "negmedspace" ||
1162 name == "negthickspace" || name == "hfill")
1163 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1164 else if (name == "hspace" || name == "hspace*") {
1165 string const len = cmd.getArg(1);
1166 if (len.empty() || !isValidLength(len)) {
1167 lyxerr << "LyX function 'space-insert " << name << "' "
1168 "needs a valid length argument." << endl;
1171 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1173 cur.insert(MathAtom(new InsetMathSpace));
1177 case LFUN_MATH_SPACE:
1178 cur.recordUndoSelection();
1179 if (cmd.argument().empty())
1180 cur.insert(MathAtom(new InsetMathSpace));
1182 string const name = cmd.getArg(0);
1183 string const len = cmd.getArg(1);
1184 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1188 case LFUN_ERT_INSERT:
1189 // interpret this as if a backslash was typed
1191 interpretChar(cur, '\\');
1194 case LFUN_MATH_SUBSCRIPT:
1195 // interpret this as if a _ was typed
1196 cur.recordUndoSelection();
1197 interpretChar(cur, '_');
1200 case LFUN_MATH_SUPERSCRIPT:
1201 // interpret this as if a ^ was typed
1202 cur.recordUndoSelection();
1203 interpretChar(cur, '^');
1206 case LFUN_MATH_MACRO_FOLD:
1207 case LFUN_MATH_MACRO_UNFOLD: {
1209 bool fold = act == LFUN_MATH_MACRO_FOLD;
1210 bool found = findMacroToFoldUnfold(it, fold);
1212 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1213 cur.recordUndoInset();
1222 case LFUN_QUOTE_INSERT:
1223 // interpret this as if a straight " was typed
1224 cur.recordUndoSelection();
1225 interpretChar(cur, '\"');
1228 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1229 // handling such that "self-insert" works on "arbitrary stuff" too, and
1230 // math-insert only handles special math things like "matrix".
1231 case LFUN_MATH_INSERT: {
1232 cur.recordUndoSelection();
1233 if (cmd.argument() == "^" || cmd.argument() == "_")
1234 interpretChar(cur, cmd.argument()[0]);
1235 else if (!cur.selection())
1236 cur.niceInsert(cmd.argument());
1238 MathData ar(cur.buffer());
1239 asArray(cmd.argument(), ar);
1241 && ar[0]->asNestInset()
1242 && ar[0]->asNestInset()->nargs() > 1)
1243 handleNest(cur, ar[0]);
1245 cur.niceInsert(cmd.argument());
1250 case LFUN_DIALOG_SHOW_NEW_INSET: {
1251 docstring const & name = cmd.argument();
1253 if (name == "ref") {
1254 InsetMathRef tmp(buffer_, name);
1255 data = tmp.createDialogStr();
1256 cur.bv().showDialog(to_utf8(name), data);
1257 } else if (name == "mathspace") {
1258 cur.bv().showDialog(to_utf8(name));
1263 case LFUN_INSET_INSERT: {
1265 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1266 cur.recordUndoSelection();
1268 cur.forceBufferUpdate();
1273 case LFUN_INSET_DISSOLVE:
1274 if (!asHullInset()) {
1275 cur.recordUndoInset();
1280 case LFUN_MATH_LIMITS: {
1282 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1283 in = &cur.nextMath();
1284 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1285 in = &cur.prevMath();
1286 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1287 in = cur.cell().back().nucleus();
1288 // only when nucleus allows this
1291 cur.recordUndoInset();
1292 if (!cmd.argument().empty()) {
1293 if (cmd.argument() == "limits")
1295 else if (cmd.argument() == "nolimits")
1296 in->limits(NO_LIMITS);
1298 in->limits(AUTO_LIMITS);
1299 } else if (in->limits() == AUTO_LIMITS)
1300 in->limits(in->defaultLimits() == LIMITS ? NO_LIMITS : LIMITS);
1302 in->limits(AUTO_LIMITS);
1307 InsetMath::doDispatch(cur, cmd);
1313 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1314 // look for macro to open/close, but stay in mathed
1315 for (; !it.empty(); it.pop_back()) {
1317 // go backward through the current cell
1318 Inset * inset = it.nextInset();
1319 while (inset && inset->asInsetMath()) {
1320 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1322 // found the an macro to open/close?
1323 if (macro->folded() != fold)
1326 // Wrong folding state.
1327 // If this was the first we see in this slice, look further left,
1329 if (inset != it.nextInset())
1333 // go up if this was the left most position
1339 inset = it.nextInset();
1347 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1348 FuncStatus & flag) const
1350 // the font related toggles
1351 //string tc = "mathnormal";
1353 string const arg = to_utf8(cmd.argument());
1354 switch (cmd.action()) {
1356 case LFUN_INSET_MODIFY:
1357 // FIXME: check temporarily disabled
1359 char align = mathcursor::valign();
1360 if (align == '\0') {
1364 if (cmd.argument().empty()) {
1368 if (!contains("tcb", cmd.argument()[0])) {
1372 flag.setOnOff(cmd.argument()[0] == align);
1375 /// We have to handle them since 1.4 blocks all unhandled actions
1376 case LFUN_FONT_ITAL:
1377 case LFUN_FONT_BOLD:
1378 case LFUN_FONT_BOLDSYMBOL:
1379 case LFUN_FONT_SANS:
1380 case LFUN_FONT_EMPH:
1381 case LFUN_FONT_TYPEWRITER:
1382 case LFUN_FONT_NOUN:
1383 case LFUN_FONT_ROMAN:
1384 case LFUN_FONT_DEFAULT:
1385 flag.setEnabled(true);
1388 // we just need to be in math mode to enable that
1389 case LFUN_MATH_SIZE:
1390 case LFUN_MATH_SPACE:
1391 case LFUN_MATH_EXTERN:
1392 flag.setEnabled(true);
1395 case LFUN_FONT_UNDERLINE:
1396 case LFUN_FONT_FRAK:
1397 flag.setEnabled(currentMode() != TEXT_MODE);
1400 case LFUN_MATH_FONT_STYLE: {
1401 bool const textarg =
1402 arg == "textbf" || arg == "textsf" ||
1403 arg == "textrm" || arg == "textmd" ||
1404 arg == "textit" || arg == "textsc" ||
1405 arg == "textsl" || arg == "textup" ||
1406 arg == "texttt" || arg == "textbb" ||
1407 arg == "textnormal";
1408 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1412 case LFUN_MATH_MODE:
1413 // forbid "math-mode on" in math mode to prevent irritating
1414 // behaviour of menu entries (bug 6709)
1415 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1418 case LFUN_MATH_INSERT:
1419 flag.setEnabled(currentMode() != TEXT_MODE);
1422 case LFUN_MATH_AMS_MATRIX:
1423 case LFUN_MATH_MATRIX:
1424 flag.setEnabled(currentMode() == MATH_MODE);
1427 case LFUN_INSET_INSERT: {
1428 // Don't test createMathInset_fromDialogStr(), since
1429 // getStatus is not called with a valid reference and the
1430 // dialog would not be applicable.
1431 string const name = cmd.getArg(0);
1432 flag.setEnabled(name == "ref" || name == "mathspace");
1436 case LFUN_DIALOG_SHOW_NEW_INSET: {
1437 docstring const & name = cmd.argument();
1438 if (name == "space")
1439 flag.setEnabled(false);
1444 case LFUN_MATH_DELIM:
1445 case LFUN_MATH_BIGDELIM:
1446 // Don't do this with multi-cell selections
1447 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1450 case LFUN_MATH_MACRO_FOLD:
1451 case LFUN_MATH_MACRO_UNFOLD: {
1453 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1454 flag.setEnabled(found);
1458 case LFUN_SPECIALCHAR_INSERT:
1459 case LFUN_SCRIPT_INSERT:
1460 // FIXME: These would probably make sense in math-text mode
1461 flag.setEnabled(false);
1464 case LFUN_CAPTION_INSERT:
1465 flag.setEnabled(false);
1468 case LFUN_SPACE_INSERT: {
1469 docstring const & name = cmd.argument();
1470 if (name == "visible")
1471 flag.setEnabled(false);
1475 case LFUN_INSET_DISSOLVE:
1476 flag.setEnabled(!asHullInset());
1480 docstring const & name = cmd.argument();
1481 if (name == "html" || name == "latex")
1482 flag.setEnabled(false);
1486 case LFUN_MATH_LIMITS: {
1488 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1489 in = &cur.nextMath();
1490 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1491 in = &cur.prevMath();
1492 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1493 in = cur.cell().back().nucleus();
1495 if (!cmd.argument().empty()) {
1496 if (cmd.argument() == "limits")
1497 flag.setOnOff(in->limits() == LIMITS);
1498 else if (cmd.argument() == "nolimits")
1499 flag.setOnOff(in->limits() == NO_LIMITS);
1501 flag.setOnOff(in->limits() == AUTO_LIMITS);
1503 flag.setEnabled(true);
1505 flag.setEnabled(false);
1517 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1520 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1521 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1522 enter_front ? idxFirst(cur) : idxLast(cur);
1524 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1528 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1531 int dist_min = 1000000;
1532 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1533 int const d = cell(i).dist(cur.bv(), x, y);
1542 MathData & ar = cell(idx_min);
1544 cur.idx() = idx_min;
1545 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1547 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1548 if (dist_min == 0) {
1550 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1551 if (ar[i]->covers(cur.bv(), x, y))
1552 return ar[i].nucleus()->editXY(cur, x, y);
1558 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1560 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1561 BufferView & bv = cur.bv();
1562 if (cmd.button() == mouse_button::button3) {
1563 // Don't do anything if we right-click a
1564 // selection, a context menu will popup.
1565 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1566 && cur < bv.cursor().selectionEnd()) {
1567 cur.noScreenUpdate();
1572 // set cursor after the inset if x is nearer to that position (bug 9748)
1573 cur.moveToClosestEdge(cmd.x(), true);
1575 bool do_selection = cmd.button() == mouse_button::button1
1576 && cmd.modifier() == ShiftModifier;
1577 bv.mouseSetCursor(cur, do_selection);
1578 if (cmd.button() == mouse_button::button1) {
1579 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1580 // Update the cursor update flags as needed:
1582 // Update::Decoration: tells to update the decoration
1583 // (visual box corners that define
1585 // Update::FitCursor: adjust the screen to the cursor
1586 // position if needed
1587 // cur.result().update(): don't overwrite previously set flags.
1588 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1589 | cur.result().screenUpdate());
1590 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1591 if (cap::selection()) {
1592 // See comment in Text::dispatch why we do this
1593 cap::copySelectionToStack();
1594 cmd = FuncRequest(LFUN_PASTE, "0");
1595 doDispatch(bv.cursor(), cmd);
1598 asArray(theSelection().get(), ar);
1599 bv.cursor().insert(ar);
1605 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1607 // only select with button 1
1608 if (cmd.button() != mouse_button::button1)
1611 Cursor & bvcur = cur.bv().cursor();
1613 // ignore motions deeper nested than the real anchor
1614 if (!bvcur.realAnchor().hasPart(cur)) {
1619 // set cursor after the inset if x is nearer to that position (bug 9748)
1620 cur.moveToClosestEdge(cmd.x());
1622 CursorSlice old = bvcur.top();
1624 // We continue with our existing selection or start a new one, so don't
1625 // reset the anchor.
1626 bvcur.setCursor(cur);
1627 // Did we actually move?
1628 if (cur.top() == old)
1629 // We didn't move one iota, so no need to change selection status
1630 // or update the screen.
1631 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1633 bvcur.setSelection();
1637 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1639 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1641 if (cmd.button() == mouse_button::button1) {
1642 if (!cur.selection())
1643 cur.noScreenUpdate();
1645 Cursor & bvcur = cur.bv().cursor();
1646 bvcur.selection(true);
1655 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1657 // try auto-correction
1658 if (lyxrc.autocorrection_math && cur.pos() != 0
1659 && math_autocorrect(cur, c))
1662 //lyxerr << "interpret 2: '" << c << "'" << endl;
1663 docstring save_selection;
1664 if (c == '^' || c == '_')
1665 save_selection = grabAndEraseSelection(cur);
1668 Buffer * buf = cur.buffer();
1671 if (cur.inMacroMode()) {
1672 docstring name = cur.macroName();
1674 /// are we currently typing '#1' or '#2' or...?
1675 if (name == "\\#") {
1678 if (n >= 1 && n <= 9)
1679 cur.insert(new InsetMathMacroArgument(n));
1683 // do not finish macro for known * commands
1684 bool star_macro = c == '*'
1685 && (in_word_set(name.substr(1) + '*')
1686 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1687 if (isAlphaASCII(c) || star_macro) {
1688 cur.activeMacro()->setName(name + docstring(1, c));
1692 // handle 'special char' macros
1697 if (currentMode() != InsetMath::MATH_MODE)
1698 cur.niceInsert(createInsetMath("textbackslash", buf));
1700 cur.niceInsert(createInsetMath("backslash", buf));
1701 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1703 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1704 } else if (c == '{' || c == '%') {
1705 //using the saved selection as argument
1706 InsetMathUnknown * p = cur.activeMacro();
1708 MathData sel(cur.buffer());
1709 asArray(p->selection(), sel);
1712 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1714 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1715 } else if (c == '#') {
1716 LASSERT(cur.activeMacro(), return false);
1717 cur.activeMacro()->setName(name + docstring(1, c));
1720 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1725 // One character big delimiters. The others are handled in
1726 // interpretString().
1727 latexkeys const * l = in_word_set(name.substr(1));
1728 if (name[0] == '\\' && l && l->inset == "big") {
1732 delim = from_ascii("\\{");
1735 delim = from_ascii("\\}");
1738 delim = docstring(1, c);
1741 if (InsetMathBig::isBigInsetDelim(delim)) {
1742 // name + delim ared a valid InsetMathBig.
1743 // We can't use cur.macroModeClose() because
1744 // it does not handle delim.
1745 InsetMathUnknown * p = cur.activeMacro();
1748 cur.cell().erase(cur.pos());
1749 cur.plainInsert(MathAtom(
1750 new InsetMathBig(name.substr(1), delim)));
1753 } else if (name == "\\smash" && c == '[') {
1754 // We can't use cur.macroModeClose() because
1755 // it would create an InsetMathPhantom
1756 InsetMathUnknown * p = cur.activeMacro();
1758 interpretChar(cur, c);
1762 // leave macro mode and try again if necessary
1763 if (cur.macroModeClose()) {
1764 MathAtom const atom = cur.prevAtom();
1765 if (atom->asNestInset() && atom->isActive()) {
1767 cur.nextInset()->edit(cur, true);
1771 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1773 interpretChar(cur, c);
1778 // just clear selection on pressing the space bar
1779 if (cur.selection() && c == ' ') {
1780 cur.selection(false);
1785 //lyxerr << "starting with macro" << endl;
1786 bool reduced = cap::reduceSelectionToOneCell(cur);
1787 if (reduced || !cur.selection()) {
1788 cur.recordUndoInset();
1789 docstring const safe = cap::grabAndEraseSelection(cur);
1790 if (!cur.inRegexped())
1791 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1793 cur.niceInsert(createInsetMath("backslash", buf));
1801 if (currentMode() != InsetMath::MATH_MODE)
1807 if (currentMode() != InsetMath::MATH_MODE) {
1808 // insert spaces in text or undecided mode,
1809 // but suppress direct insertion of two spaces in a row
1810 // the still allows typing '<space>a<space>' and deleting the 'a', but
1811 // it is better than nothing...
1812 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1814 // FIXME: we have to enable full redraw here because of the
1815 // visual box corners that define the inset. If we know for
1816 // sure that we stay within the same cell we can optimize for
1818 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1822 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1823 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1824 // FIXME: we have to enable full redraw here because of the
1825 // visual box corners that define the inset. If we know for
1826 // sure that we stay within the same cell we can optimize for
1828 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1832 if (cur.popForward()) {
1833 // FIXME: we have to enable full redraw here because of the
1834 // visual box corners that define the inset. If we know for
1835 // sure that we stay within the same cell we can optimize for
1837 //cur.screenUpdateFlags(Update::FitCursor);
1841 // if we are at the very end, leave the formula
1842 return cur.pos() != cur.lastpos();
1845 // These should be treated differently when not in text mode:
1846 if (cur.inRegexped()) {
1849 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1856 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1859 cur.niceInsert(createInsetMath("sim", buf));
1865 } else if (currentMode() != InsetMath::TEXT_MODE) {
1867 script(cur, false, save_selection);
1871 script(cur, true, save_selection);
1875 cur.niceInsert(createInsetMath("sim", buf));
1878 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1879 MathAtom at = createInsetMath("text", buf);
1880 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1887 cur.niceInsert(createInsetMath("textasciicircum", buf));
1891 cur.niceInsert(createInsetMath("textasciitilde", buf));
1896 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1897 c == '%' || c == '_') {
1898 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1902 // no special circumstances, so insert the character without any fuss
1908 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1910 if (str == "\\limits" || str == "\\nolimits") {
1911 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1912 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1915 cur.message(bformat(_("Cannot apply %1$s here."), str));
1919 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1921 if (!cur.empty() && cur.pos() > 0 &&
1922 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1923 if (InsetMathBig::isBigInsetDelim(str)) {
1924 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1925 if (prev[0] == '\\') {
1926 prev = prev.substr(1);
1927 latexkeys const * l = in_word_set(prev);
1928 if (l && l->inset == "big") {
1929 cur.recordUndoSelection();
1930 cur.cell()[cur.pos() - 1] =
1931 MathAtom(new InsetMathBig(prev, str));
1941 bool InsetMathNest::script(Cursor & cur, bool up)
1943 return script(cur, up, docstring());
1947 bool InsetMathNest::script(Cursor & cur, bool up,
1948 docstring const & save_selection)
1950 // Hack to get \^ and \_ working
1951 //lyxerr << "handling script: up: " << up << endl;
1952 if (cur.inMacroMode() && cur.macroName() == "\\") {
1954 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1956 interpretChar(cur, '_');
1960 cur.macroModeClose();
1961 if (asScriptInset() && cur.idx() == 0) {
1962 // we are in a nucleus of a script inset, move to _our_ script
1963 InsetMathScript * inset = asScriptInset();
1964 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1966 cur.idx() = inset->idxOfScript(up);
1968 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1970 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1973 cur.idx() = inset->idxOfScript(up);
1974 cur.pos() = cur.lastpos();
1976 // convert the thing to our left to a scriptinset or create a new
1977 // one if in the very first position of the array
1978 if (cur.pos() == 0) {
1979 //lyxerr << "new scriptinset" << endl;
1980 cur.insert(new InsetMathScript(buffer_, up));
1982 //lyxerr << "converting prev atom " << endl;
1983 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1986 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1987 // See comment in MathParser.cpp for special handling of {}-bases
1993 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1994 cur.niceInsert(save_selection);
1996 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2001 bool InsetMathNest::completionSupported(Cursor const & cur) const
2003 return cur.inMacroMode();
2007 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2009 return cur.inMacroMode();
2013 bool InsetMathNest::automaticInlineCompletion() const
2015 return lyxrc.completion_inline_math;
2019 bool InsetMathNest::automaticPopupCompletion() const
2021 return lyxrc.completion_popup_math;
2025 CompletionList const *
2026 InsetMathNest::createCompletionList(Cursor const & cur) const
2028 if (!cur.inMacroMode())
2031 return new MathCompletionList(cur);
2035 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2037 if (!cur.inMacroMode())
2040 return cur.activeMacro()->name();
2044 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2047 if (!cur.inMacroMode())
2050 // append completion to active macro
2051 InsetMathUnknown * inset = cur.activeMacro();
2052 inset->setName(inset->name() + s);
2057 // FIXME: this creates duplicates in the completion popup
2058 // which looks ugly. Moreover the changes the list lengths
2059 // which seems to confuse the popup as well.
2060 MathCompletionList::addToFavorites(inset->name());
2062 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2069 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2070 Dimension & dim) const
2072 Inset const * inset = cur.activeMacro();
2076 // get inset dimensions
2077 dim = cur.bv().coordCache().insets().dim(inset);
2078 // FIXME: these 3 are no accurate, but should depend on the font.
2079 // Now the popup jumps down if you enter a char with descent > 0.
2084 Point xy = cur.bv().coordCache().insets().xy(inset);
2090 ////////////////////////////////////////////////////////////////////
2092 MathCompletionList::MathCompletionList(Cursor const & cur)
2094 // fill it with macros from the buffer
2095 MacroNameSet macros;
2096 cur.buffer()->listMacroNames(macros);
2097 MacroNameSet::const_iterator it;
2098 for (it = macros.begin(); it != macros.end(); ++it) {
2099 if (cur.buffer()->getMacro(*it, cur, false))
2100 locals.push_back("\\" + *it);
2102 sort(locals.begin(), locals.end());
2104 if (!globals.empty())
2107 // fill in global macros
2109 MacroTable::globalMacros().getMacroNames(macros, false);
2110 //lyxerr << "Globals completion macros: ";
2111 for (it = macros.begin(); it != macros.end(); ++it) {
2112 //lyxerr << "\\" + *it << " ";
2113 globals.push_back("\\" + *it);
2115 //lyxerr << std::endl;
2117 // fill in global commands
2118 globals.push_back(from_ascii("\\boxed"));
2119 globals.push_back(from_ascii("\\fbox"));
2120 globals.push_back(from_ascii("\\framebox"));
2121 globals.push_back(from_ascii("\\makebox"));
2122 globals.push_back(from_ascii("\\kern"));
2123 globals.push_back(from_ascii("\\xhookrightarrow"));
2124 globals.push_back(from_ascii("\\xhookleftarrow"));
2125 globals.push_back(from_ascii("\\xrightarrow"));
2126 globals.push_back(from_ascii("\\xRightarrow"));
2127 globals.push_back(from_ascii("\\xrightharpoondown"));
2128 globals.push_back(from_ascii("\\xrightharpoonup"));
2129 globals.push_back(from_ascii("\\xrightleftharpoons"));
2130 globals.push_back(from_ascii("\\xleftarrow"));
2131 globals.push_back(from_ascii("\\xLeftarrow"));
2132 globals.push_back(from_ascii("\\xleftharpoondown"));
2133 globals.push_back(from_ascii("\\xleftharpoonup"));
2134 globals.push_back(from_ascii("\\xleftrightarrow"));
2135 globals.push_back(from_ascii("\\xLeftrightarrow"));
2136 globals.push_back(from_ascii("\\xleftrightharpoons"));
2137 globals.push_back(from_ascii("\\xmapsto"));
2138 globals.push_back(from_ascii("\\split"));
2139 globals.push_back(from_ascii("\\gathered"));
2140 globals.push_back(from_ascii("\\aligned"));
2141 globals.push_back(from_ascii("\\alignedat"));
2142 globals.push_back(from_ascii("\\cases"));
2143 globals.push_back(from_ascii("\\substack"));
2144 globals.push_back(from_ascii("\\xymatrix"));
2145 globals.push_back(from_ascii("\\Diagram"));
2146 globals.push_back(from_ascii("\\subarray"));
2147 globals.push_back(from_ascii("\\array"));
2148 globals.push_back(from_ascii("\\sqrt"));
2149 globals.push_back(from_ascii("\\root"));
2150 globals.push_back(from_ascii("\\tabular"));
2151 globals.push_back(from_ascii("\\sideset"));
2152 globals.push_back(from_ascii("\\stackrel"));
2153 globals.push_back(from_ascii("\\stackrelthree"));
2154 globals.push_back(from_ascii("\\binom"));
2155 globals.push_back(from_ascii("\\choose"));
2156 globals.push_back(from_ascii("\\brace"));
2157 globals.push_back(from_ascii("\\brack"));
2158 globals.push_back(from_ascii("\\frac"));
2159 globals.push_back(from_ascii("\\over"));
2160 globals.push_back(from_ascii("\\nicefrac"));
2161 globals.push_back(from_ascii("\\unitfrac"));
2162 globals.push_back(from_ascii("\\unitfracthree"));
2163 globals.push_back(from_ascii("\\unitone"));
2164 globals.push_back(from_ascii("\\unittwo"));
2165 globals.push_back(from_ascii("\\infer"));
2166 globals.push_back(from_ascii("\\atop"));
2167 globals.push_back(from_ascii("\\lefteqn"));
2168 globals.push_back(from_ascii("\\boldsymbol"));
2169 globals.push_back(from_ascii("\\bm"));
2170 globals.push_back(from_ascii("\\color"));
2171 globals.push_back(from_ascii("\\normalcolor"));
2172 globals.push_back(from_ascii("\\textcolor"));
2173 globals.push_back(from_ascii("\\cfrac"));
2174 globals.push_back(from_ascii("\\cfracleft"));
2175 globals.push_back(from_ascii("\\cfracright"));
2176 globals.push_back(from_ascii("\\dfrac"));
2177 globals.push_back(from_ascii("\\tfrac"));
2178 globals.push_back(from_ascii("\\dbinom"));
2179 globals.push_back(from_ascii("\\tbinom"));
2180 globals.push_back(from_ascii("\\hphantom"));
2181 globals.push_back(from_ascii("\\phantom"));
2182 globals.push_back(from_ascii("\\vphantom"));
2183 globals.push_back(from_ascii("\\cancel"));
2184 globals.push_back(from_ascii("\\bcancel"));
2185 globals.push_back(from_ascii("\\xcancel"));
2186 globals.push_back(from_ascii("\\cancelto"));
2187 globals.push_back(from_ascii("\\smash"));
2188 globals.push_back(from_ascii("\\mathclap"));
2189 globals.push_back(from_ascii("\\mathllap"));
2190 globals.push_back(from_ascii("\\mathrlap"));
2191 globals.push_back(from_ascii("\\ensuremath"));
2192 MathWordList const & words = mathedWordList();
2193 MathWordList::const_iterator it2;
2194 //lyxerr << "Globals completion commands: ";
2195 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2196 if (it2->second.inset != "macro" && !it2->second.hidden) {
2197 // macros are already read from MacroTable::globalMacros()
2198 globals.push_back('\\' + it2->first);
2199 //lyxerr << '\\' + it2->first << ' ';
2202 //lyxerr << std::endl;
2203 sort(globals.begin(), globals.end());
2207 MathCompletionList::~MathCompletionList()
2212 size_type MathCompletionList::size() const
2214 return locals.size() + globals.size();
2218 docstring const & MathCompletionList::data(size_t idx) const
2220 size_t lsize = locals.size();
2222 return globals[idx - lsize];
2228 std::string MathCompletionList::icon(size_t idx) const
2230 // get the latex command
2232 size_t lsize = locals.size();
2234 cmd = globals[idx - lsize];
2238 // get the icon name by stripping the backslash
2239 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2240 if (icon_name.empty())
2241 return std::string();
2242 return "math/" + to_utf8(icon_name);
2245 std::vector<docstring> MathCompletionList::globals;