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 "InsetMathMacro.h"
36 #include "InsetMathMacroArgument.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 (MathData & data : cells_)
122 data.setBuffer(buffer);
126 InsetMath::idx_type InsetMathNest::nargs() const
128 return cells_.size();
132 void InsetMathNest::cursorPos(BufferView const & bv,
133 CursorSlice const & sl, bool /*boundary*/,
134 int & x, int & y) const
136 // FIXME: This is a hack. Ideally, the coord cache should not store
137 // absolute positions, but relative ones. This would mean to call
138 // setXY() not in MathData::draw(), but in the parent insets' draw()
139 // with the correctly adjusted x,y values. But this means that we'd have
140 // to touch all (math)inset's draw() methods. Right now, we'll store
141 // absolute value, and make them here relative, only to make them
142 // absolute again when actually drawing the cursor. What a mess.
143 LASSERT(&sl.inset() == this, return);
144 MathData const & ar = sl.cell();
145 CoordCache const & coord_cache = bv.coordCache();
146 if (!coord_cache.getArrays().has(&ar)) {
147 // this can (semi-)legally happen if we just created this cell
148 // and it never has been drawn before. So don't ASSERT.
149 //lyxerr << "no cached data for array " << &ar << endl;
154 Point const pt = coord_cache.getArrays().xy(&ar);
155 if (!coord_cache.getInsets().has(this)) {
157 //lyxerr << "no cached data for inset " << this << endl;
162 Point const pt2 = coord_cache.getInsets().xy(this);
163 //lyxerr << "retrieving position cache for MathData "
164 // << pt.x_ << ' ' << pt.y_ << endl;
165 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
167 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
168 // << " asc: " << ascent() << " des: " << descent()
169 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
170 // move cursor visually into empty cells ("blue rectangles");
172 Dimension const dim = coord_cache.getArrays().dim(&ar);
178 void InsetMathNest::cellsMetrics(MetricsInfo const & mi) const
181 for (auto const & cell : cells_) {
183 cell.metrics(m, dim);
188 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
190 for (idx_type i = 0, n = nargs(); i != n; ++i)
191 cell(i).updateBuffer(it, utype, deleted);
196 bool InsetMathNest::idxNext(Cursor & cur) const
198 LASSERT(&cur.inset() == this, return false);
199 if (cur.idx() == cur.lastidx())
207 bool InsetMathNest::idxForward(Cursor & cur) const
213 bool InsetMathNest::idxPrev(Cursor & cur) const
215 LASSERT(&cur.inset() == this, return false);
219 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
224 bool InsetMathNest::idxBackward(Cursor & cur) const
230 bool InsetMathNest::idxFirst(Cursor & cur) const
232 LASSERT(&cur.inset() == this, return false);
235 cur.idx() = firstIdx();
241 bool InsetMathNest::idxLast(Cursor & cur) const
243 LASSERT(&cur.inset() == this, return false);
246 cur.idx() = lastIdx();
247 cur.pos() = cur.lastpos();
252 void InsetMathNest::dump() const
254 odocstringstream oss;
255 otexrowstream ots(oss);
257 os << "---------------------------------------------\n";
260 for (idx_type i = 0, n = nargs(); i != n; ++i)
261 os << cell(i) << "\n";
262 os << "---------------------------------------------\n";
263 lyxerr << to_utf8(oss.str());
267 void InsetMathNest::draw(PainterInfo &, int, int) const
271 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
277 void InsetMathNest::validate(LaTeXFeatures & features) const
279 for (idx_type i = 0; i < nargs(); ++i)
280 cell(i).validate(features);
284 void InsetMathNest::replace(ReplaceData & rep)
286 for (idx_type i = 0; i < nargs(); ++i)
287 cell(i).replace(rep);
291 bool InsetMathNest::contains(MathData const & ar) const
293 for (idx_type i = 0; i < nargs(); ++i)
294 if (cell(i).contains(ar))
300 bool InsetMathNest::lock() const
306 void InsetMathNest::lock(bool l)
312 bool InsetMathNest::isActive() const
318 MathData InsetMathNest::glue() const
321 for (size_t i = 0; i < nargs(); ++i)
327 void InsetMathNest::write(WriteStream & os) const
329 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
330 ModeSpecifier specifier(os, currentMode(), lockedMode());
331 docstring const latex_name = name();
332 os << '\\' << latex_name;
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);
346 void InsetMathNest::normalize(NormalStream & os) const
349 for (size_t i = 0; i < nargs(); ++i)
350 os << ' ' << cell(i);
355 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
357 WriteStream wi(os, runparams.moving_arg, true,
358 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
360 wi.strikeoutMath(runparams.inDeletedInset);
361 if (runparams.inulemcmd) {
362 wi.ulemCmd(WriteStream::UNDERLINE);
363 if (runparams.local_font) {
364 FontInfo f = runparams.local_font->fontInfo();
365 if (f.strikeout() == FONT_ON)
366 wi.ulemCmd(WriteStream::STRIKEOUT);
369 wi.canBreakLine(os.canBreakLine());
370 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
373 // Reset parbreak and command termination status after a math inset.
375 os.canBreakLine(wi.canBreakLine());
376 os.terminateCommand(false);
380 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
383 mouse_hover_[bv] = mouse_hover;
388 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
392 MathData & ar = cur.cell();
393 // remove base-only "scripts"
394 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
395 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
396 if (p && p->nargs() == 1) {
397 MathData ar = p->nuc();
400 cur.adjust(i, ar.size() - 1);
404 // glue adjacent font insets of the same kind
405 for (pos_type i = 0; i + 1 < size(); ++i) {
406 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
407 InsetMathFont const * q = operator[](i + 1)->asFontInset();
408 if (p && q && p->name() == q->name()) {
409 p->cell(0).append(q->cell(0));
419 void InsetMathNest::handleFont
420 (Cursor & cur, docstring const & arg, char const * const font)
422 handleFont(cur, arg, from_ascii(font));
426 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
427 docstring const & font)
429 cur.recordUndoSelection();
431 // this whole function is a hack and won't work for incremental font
433 if (cur.inset().asInsetMath()->name() == font)
434 cur.handleFont(to_utf8(font));
436 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
440 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
442 handleNest(cur, nest, docstring());
446 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
447 docstring const & arg)
449 CursorSlice i1 = cur.selBegin();
450 CursorSlice i2 = cur.selEnd();
451 if (!i1.inset().asInsetMath())
453 if (i1.idx() == i2.idx()) {
454 // the easy case where only one cell is selected
455 cur.handleNest(nest);
460 // multiple selected cells in a simple non-grid inset
461 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
462 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
467 cur.pos() = cur.lastpos();
470 // change font of cell
471 cur.handleNest(nest);
474 // cur is in the font inset now. If the loop continues,
475 // we need to get outside again for the next cell
476 if (i + 1 <= i2.idx())
482 // the complicated case with multiple selected cells in a grid
485 cap::region(i1, i2, r1, r2, c1, c2);
486 for (row_type row = r1; row <= r2; ++row) {
487 for (col_type col = c1; col <= c2; ++col) {
489 cur.idx() = i1.asInsetMath()->index(row, col);
492 cur.pos() = cur.lastpos();
496 cur.handleNest(nest);
499 // cur is in the font inset now. If the loop continues,
500 // we need to get outside again for the next cell
501 if (col + 1 <= c2 || row + 1 <= r2)
508 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
510 cur.recordUndoSelection();
513 font.fromString(to_utf8(arg), b);
514 if (font.fontInfo().color() != Color_inherit &&
515 font.fontInfo().color() != Color_ignore)
516 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
518 // FIXME: support other font changes here as well?
521 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
523 //LYXERR0("InsetMathNest: request: " << cmd);
525 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
527 FuncCode const act = cmd.action();
530 case LFUN_CLIPBOARD_PASTE:
531 parseflg |= Parse::VERBATIM;
534 if (cur.currentMode() != MATH_MODE)
535 parseflg |= Parse::TEXTMODE;
536 cur.recordUndoSelection();
537 cur.message(_("Paste"));
538 replaceSelection(cur);
540 if (cmd.argument().empty() && !theClipboard().isInternal())
541 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
544 idocstringstream is(cmd.argument());
546 topaste = cap::selection(n, buffer().params().documentClassPtr());
548 cur.niceInsert(topaste, parseflg, false);
549 cur.clearSelection(); // bug 393
550 cur.forceBufferUpdate();
557 cutSelection(cur, true);
558 cur.message(_("Cut"));
559 // Prevent stale position >= size crash
560 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
562 cur.forceBufferUpdate();
567 cur.message(_("Copy"));
570 case LFUN_MOUSE_PRESS:
571 lfunMousePress(cur, cmd);
574 case LFUN_MOUSE_MOTION:
575 lfunMouseMotion(cur, cmd);
578 case LFUN_MOUSE_RELEASE:
579 lfunMouseRelease(cur, cmd);
582 case LFUN_FINISHED_LEFT: // in math, left is backwards
583 case LFUN_FINISHED_BACKWARD:
584 cur.bv().cursor() = cur;
587 case LFUN_FINISHED_RIGHT: // in math, right is forward
588 case LFUN_FINISHED_FORWARD:
590 cur.bv().cursor() = cur;
593 case LFUN_WORD_RIGHT:
595 case LFUN_WORD_BACKWARD:
596 case LFUN_WORD_FORWARD:
597 case LFUN_CHAR_RIGHT:
599 case LFUN_CHAR_BACKWARD:
600 case LFUN_CHAR_FORWARD:
601 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
603 case LFUN_WORD_RIGHT_SELECT:
604 case LFUN_WORD_LEFT_SELECT:
605 case LFUN_WORD_BACKWARD_SELECT:
606 case LFUN_WORD_FORWARD_SELECT:
607 case LFUN_CHAR_RIGHT_SELECT:
608 case LFUN_CHAR_LEFT_SELECT:
609 case LFUN_CHAR_BACKWARD_SELECT:
610 case LFUN_CHAR_FORWARD_SELECT: {
611 // are we in a selection?
612 bool select = (act == LFUN_WORD_RIGHT_SELECT
613 || act == LFUN_WORD_LEFT_SELECT
614 || act == LFUN_WORD_BACKWARD_SELECT
615 || act == LFUN_WORD_FORWARD_SELECT
616 || act == LFUN_CHAR_RIGHT_SELECT
617 || act == LFUN_CHAR_LEFT_SELECT
618 || act == LFUN_CHAR_BACKWARD_SELECT
619 || act == LFUN_CHAR_FORWARD_SELECT);
621 bool word = (act == LFUN_WORD_RIGHT_SELECT
622 || act == LFUN_WORD_LEFT_SELECT
623 || act == LFUN_WORD_BACKWARD_SELECT
624 || act == LFUN_WORD_FORWARD_SELECT
625 || act == LFUN_WORD_RIGHT
626 || act == LFUN_WORD_LEFT
627 || act == LFUN_WORD_BACKWARD
628 || act == LFUN_WORD_FORWARD);
629 // are we moving forward or backwards?
630 // If the command was RIGHT or LEFT, then whether we're moving forward
631 // or backwards depends on the cursor movement mode (logical or visual):
632 // * in visual mode, since math is always LTR, right -> forward,
634 // * in logical mode, the mapping is determined by the
635 // reverseDirectionNeeded() function
638 FuncCode finish_lfun;
640 if (act == LFUN_CHAR_FORWARD
641 || act == LFUN_CHAR_FORWARD_SELECT
642 || act == LFUN_WORD_FORWARD
643 || act == LFUN_WORD_FORWARD_SELECT) {
645 finish_lfun = LFUN_FINISHED_FORWARD;
647 else if (act == LFUN_CHAR_BACKWARD
648 || act == LFUN_CHAR_BACKWARD_SELECT
649 || act == LFUN_WORD_BACKWARD
650 || act == LFUN_WORD_BACKWARD_SELECT) {
652 finish_lfun = LFUN_FINISHED_BACKWARD;
655 bool right = (act == LFUN_CHAR_RIGHT_SELECT
656 || act == LFUN_CHAR_RIGHT
657 || act == LFUN_WORD_RIGHT_SELECT
658 || act == LFUN_WORD_RIGHT);
659 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
665 finish_lfun = LFUN_FINISHED_RIGHT;
667 finish_lfun = LFUN_FINISHED_LEFT;
669 // Now that we know exactly what we want to do, let's do it!
670 cur.selHandle(select);
672 cur.macroModeClose();
673 // try moving forward or backwards as necessary...
674 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
675 // ... and if movement failed, then finish forward or backwards
677 cmd = FuncRequest(finish_lfun);
685 case LFUN_PARAGRAPH_UP:
686 case LFUN_PARAGRAPH_DOWN:
687 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
689 case LFUN_DOWN_SELECT:
691 case LFUN_PARAGRAPH_UP_SELECT:
692 case LFUN_PARAGRAPH_DOWN_SELECT: {
693 // close active macro
694 if (cur.inMacroMode()) {
695 cur.macroModeClose();
699 // stop/start the selection
700 bool select = act == LFUN_DOWN_SELECT
701 || act == LFUN_UP_SELECT
702 || act == LFUN_PARAGRAPH_DOWN_SELECT
703 || act == LFUN_PARAGRAPH_UP_SELECT;
704 cur.selHandle(select);
707 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
708 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
709 bool successful = cur.upDownInMath(up);
713 if (cur.fixIfBroken())
714 // FIXME: Something bad happened. We pass the corrected Cursor
715 // instead of letting things go worse.
718 // We did not manage to move the cursor.
723 case LFUN_MOUSE_DOUBLE:
724 case LFUN_WORD_SELECT:
726 cur.bv().mouseSetCursor(cur);
727 cur.pos() = cur.lastpos();
728 cur.bv().mouseSetCursor(cur, true);
731 case LFUN_MOUSE_TRIPLE:
734 cur.bv().mouseSetCursor(cur);
735 cur.idx() = cur.lastidx();
736 cur.pos() = cur.lastpos();
737 cur.bv().mouseSetCursor(cur, true);
740 case LFUN_LINE_BEGIN:
741 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
743 case LFUN_LINE_BEGIN_SELECT:
744 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
745 act == LFUN_WORD_LEFT_SELECT ||
746 act == LFUN_LINE_BEGIN_SELECT);
747 cur.macroModeClose();
748 if (cur.pos() != 0) {
750 } else if (cur.col() != 0) {
751 cur.idx() -= cur.col();
753 } else if (cur.idx() != 0) {
757 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
763 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
765 case LFUN_LINE_END_SELECT:
766 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
767 act == LFUN_WORD_RIGHT_SELECT ||
768 act == LFUN_LINE_END_SELECT);
769 cur.macroModeClose();
771 if (cur.pos() != cur.lastpos()) {
772 cur.pos() = cur.lastpos();
773 } else if (ncols() && (cur.col() != cur.lastcol())) {
774 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
775 cur.pos() = cur.lastpos();
776 } else if (cur.idx() != cur.lastidx()) {
777 cur.idx() = cur.lastidx();
778 cur.pos() = cur.lastpos();
780 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
785 case LFUN_CELL_FORWARD:
786 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
787 cur.selHandle(false);
789 cur.macroModeClose();
790 if (!cur.inset().idxNext(cur)) {
791 cur.idx() = firstIdx();
796 case LFUN_CELL_BACKWARD:
797 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
798 cur.selHandle(false);
800 cur.macroModeClose();
801 if (!cur.inset().idxPrev(cur)) {
802 cur.idx() = lastIdx();
803 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
807 case LFUN_WORD_DELETE_BACKWARD:
808 case LFUN_CHAR_DELETE_BACKWARD:
810 // May affect external cell:
811 cur.recordUndoInset();
812 else if (!cur.inMacroMode())
813 cur.recordUndoSelection();
814 // if the inset can not be removed from within, delete it
815 if (!cur.backspace(cmd.getArg(0) == "force")) {
816 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
817 cur.innerText()->dispatch(cur, newcmd);
821 case LFUN_WORD_DELETE_FORWARD:
822 case LFUN_CHAR_DELETE_FORWARD:
823 if (cur.pos() == cur.lastpos())
824 // May affect external cell:
825 cur.recordUndoInset();
827 cur.recordUndoSelection();
828 // if the inset can not be removed from within, delete it
829 if (!cur.erase(cmd.getArg(0) == "force")) {
830 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
831 cur.innerText()->dispatch(cur, newcmd);
837 cur.clearSelection();
839 if (cur.inMacroMode())
840 cur.macroModeClose(true);
842 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
848 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
849 // that is traversed by a single <CursorLeft>/<CursorRight>.
850 case LFUN_INSET_TOGGLE:
856 case LFUN_SELF_INSERT:
857 // special case first for big delimiters
858 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
861 for (char_type c : cmd.argument()) {
862 // Don't record undo steps if we are in macro mode and thus
863 // cmd.argument is the next character of the macro name.
864 // Otherwise we'll get an invalid cursor if we undo after
865 // the macro was finished and the macro is a known command,
866 // e.g. sqrt. Cursor::macroModeClose replaces in this case
867 // the InsetMathUnknown with name "frac" by an empty
868 // InsetMathFrac -> a pos value > 0 is invalid.
869 // A side effect is that an undo before the macro is finished
870 // undoes the complete macro, not only the last character.
871 // At the time we hit '\' we are not in macro mode, still.
872 if (!cur.inMacroMode())
873 cur.recordUndoSelection();
875 // special handling of space. If we insert an inset
876 // via macro mode, we want to put the cursor inside it
877 // if relevant. Think typing "\frac<space>".
879 && cur.inMacroMode() && cur.macroName() != "\\"
880 && cur.macroModeClose() && cur.pos() > 0)
881 cur.editInsertedInset();
882 else if (!interpretChar(cur, c)) {
883 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
885 // FIXME: can we avoid skipping the end of the string?
891 //case LFUN_SERVER_GET_XY:
894 case LFUN_SERVER_SET_XY: {
895 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
898 istringstream is(to_utf8(cmd.argument()));
904 // Special casing for superscript in case of LyX handling
906 case LFUN_ACCENT_CIRCUMFLEX:
907 if (cmd.argument().empty()) {
908 // do superscript if LyX handles
910 cur.recordUndoSelection();
911 script(cur, true, grabAndEraseSelection(cur));
915 case LFUN_ACCENT_UMLAUT:
916 case LFUN_ACCENT_ACUTE:
917 case LFUN_ACCENT_GRAVE:
918 case LFUN_ACCENT_BREVE:
919 case LFUN_ACCENT_DOT:
920 case LFUN_ACCENT_MACRON:
921 case LFUN_ACCENT_CARON:
922 case LFUN_ACCENT_TILDE:
923 case LFUN_ACCENT_CEDILLA:
924 case LFUN_ACCENT_CIRCLE:
925 case LFUN_ACCENT_UNDERDOT:
926 case LFUN_ACCENT_TIE:
927 case LFUN_ACCENT_OGONEK:
928 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
932 case LFUN_TEXTSTYLE_APPLY:
933 case LFUN_TEXTSTYLE_UPDATE:
934 handleFont2(cur, cmd.argument());
938 if (currentMode() != MATH_MODE)
939 handleFont(cur, cmd.argument(), "textbf");
941 handleFont(cur, cmd.argument(), "mathbf");
943 case LFUN_FONT_BOLDSYMBOL:
944 if (currentMode() != MATH_MODE)
945 handleFont(cur, cmd.argument(), "textbf");
947 handleFont(cur, cmd.argument(), "boldsymbol");
950 if (currentMode() != MATH_MODE)
951 handleFont(cur, cmd.argument(), "textsf");
953 handleFont(cur, cmd.argument(), "mathsf");
956 if (currentMode() != MATH_MODE)
957 handleFont(cur, cmd.argument(), "emph");
959 handleFont(cur, cmd.argument(), "mathcal");
961 case LFUN_FONT_ROMAN:
962 if (currentMode() != MATH_MODE)
963 handleFont(cur, cmd.argument(), "textrm");
965 handleFont(cur, cmd.argument(), "mathrm");
967 case LFUN_FONT_TYPEWRITER:
968 if (currentMode() != MATH_MODE)
969 handleFont(cur, cmd.argument(), "texttt");
971 handleFont(cur, cmd.argument(), "mathtt");
974 handleFont(cur, cmd.argument(), "mathfrak");
977 if (currentMode() != MATH_MODE)
978 handleFont(cur, cmd.argument(), "textit");
980 handleFont(cur, cmd.argument(), "mathit");
983 if (currentMode() != MATH_MODE)
984 // FIXME: should be "noun"
985 handleFont(cur, cmd.argument(), "textsc");
987 handleFont(cur, cmd.argument(), "mathbb");
989 case LFUN_FONT_DEFAULT:
990 handleFont(cur, cmd.argument(), "textnormal");
992 case LFUN_FONT_UNDERLINE:
994 cur.handleNest(createInsetMath("underline", cur.buffer()));
997 case LFUN_MATH_MODE: {
999 // ignore math-mode on when already in math mode
1000 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1002 cur.recordUndoSelection();
1003 cur.macroModeClose();
1004 docstring const save_selection = grabAndEraseSelection(cur);
1006 if (currentMode() != Inset::MATH_MODE)
1007 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1009 cur.plainInsert(createInsetMath("text", buffer_));
1011 cur.pushBackward(*cur.nextInset());
1012 cur.niceInsert(save_selection);
1013 cur.forceBufferUpdate();
1015 if (currentMode() == Inset::TEXT_MODE) {
1016 cur.recordUndoSelection();
1017 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1018 cur.message(_("create new math text environment ($...$)"));
1020 handleFont(cur, cmd.argument(), "textrm");
1021 cur.message(_("entered math text mode (textrm)"));
1027 case LFUN_REGEXP_MODE: {
1028 InsetMath * im = cur.inset().asInsetMath();
1030 InsetMathHull * i = im->asHullInset();
1031 if (i && i->getType() == hullRegexp) {
1032 cur.message(_("Already in regular expression mode"));
1036 cur.macroModeClose();
1037 docstring const save_selection = grabAndEraseSelection(cur);
1039 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1041 cur.pushBackward(*cur.nextInset());
1042 cur.niceInsert(save_selection);
1043 cur.message(_("Regular expression editor mode"));
1047 case LFUN_MATH_FONT_STYLE: {
1048 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1049 doDispatch(cur, fr);
1053 case LFUN_MATH_SIZE: {
1054 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1055 doDispatch(cur, fr);
1059 case LFUN_MATH_MATRIX: {
1065 idocstringstream is(cmd.argument());
1066 is >> m >> n >> v_align >> h_align;
1072 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1073 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1077 case LFUN_MATH_AMS_MATRIX: {
1081 docstring name = from_ascii("matrix");
1082 idocstringstream is(cmd.argument());
1083 is >> m >> n >> name;
1088 // check if we have a valid decoration
1089 if (name != "pmatrix" && name != "bmatrix"
1090 && name != "Bmatrix" && name != "vmatrix"
1091 && name != "Vmatrix" && name != "matrix"
1092 && name != "smallmatrix")
1093 name = from_ascii("matrix");
1096 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1100 case LFUN_MATH_DELIM: {
1102 docstring rs = split(cmd.argument(), ls, ' ');
1103 // Reasonable default values
1109 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1113 case LFUN_MATH_BIGDELIM: {
1114 docstring const lname = from_utf8(cmd.getArg(0));
1115 docstring const ldelim = from_utf8(cmd.getArg(1));
1116 docstring const rname = from_utf8(cmd.getArg(2));
1117 docstring const rdelim = from_utf8(cmd.getArg(3));
1118 latexkeys const * l = in_word_set(lname);
1119 bool const have_l = l && l->inset == "big" &&
1120 InsetMathBig::isBigInsetDelim(ldelim);
1121 l = in_word_set(rname);
1122 bool const have_r = l && l->inset == "big" &&
1123 InsetMathBig::isBigInsetDelim(rdelim);
1124 // We mimic LFUN_MATH_DELIM in case we have an empty left
1125 // or right delimiter.
1126 if (have_l || have_r) {
1128 docstring const selection = grabAndEraseSelection(cur);
1131 cur.insert(MathAtom(new InsetMathBig(lname,
1133 // first insert the right delimiter and then go back
1134 // and re-insert the selection (bug 7088)
1136 cur.insert(MathAtom(new InsetMathBig(rname,
1140 cur.niceInsert(selection);
1142 // Don't call cur.undispatched() if we did nothing, this would
1143 // lead to infinite recursion via Text::dispatch().
1147 case LFUN_SPACE_INSERT: {
1148 cur.recordUndoSelection();
1149 string const name = cmd.getArg(0);
1150 if (name == "normal")
1151 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1152 else if (name == "protected")
1153 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1154 else if (name == "thin" || name == "med" || name == "thick")
1155 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1156 else if (name == "hfill*")
1157 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1158 else if (name == "quad" || name == "qquad" ||
1159 name == "enspace" || name == "enskip" ||
1160 name == "negthinspace" || name == "negmedspace" ||
1161 name == "negthickspace" || name == "hfill")
1162 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1163 else if (name == "hspace" || name == "hspace*") {
1164 string const len = cmd.getArg(1);
1165 if (len.empty() || !isValidLength(len)) {
1166 lyxerr << "LyX function 'space-insert " << name << "' "
1167 "needs a valid length argument." << endl;
1170 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1172 cur.insert(MathAtom(new InsetMathSpace));
1176 case LFUN_MATH_SPACE:
1177 cur.recordUndoSelection();
1178 if (cmd.argument().empty())
1179 cur.insert(MathAtom(new InsetMathSpace));
1181 string const name = cmd.getArg(0);
1182 string const len = cmd.getArg(1);
1183 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1187 case LFUN_ERT_INSERT:
1188 // interpret this as if a backslash was typed
1190 interpretChar(cur, '\\');
1193 case LFUN_MATH_SUBSCRIPT:
1194 // interpret this as if a _ was typed
1195 cur.recordUndoSelection();
1196 interpretChar(cur, '_');
1199 case LFUN_MATH_SUPERSCRIPT:
1200 // interpret this as if a ^ was typed
1201 cur.recordUndoSelection();
1202 interpretChar(cur, '^');
1205 case LFUN_MATH_MACRO_FOLD:
1206 case LFUN_MATH_MACRO_UNFOLD: {
1208 bool fold = act == LFUN_MATH_MACRO_FOLD;
1209 bool found = findMacroToFoldUnfold(it, fold);
1211 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1212 cur.recordUndoInset();
1221 case LFUN_QUOTE_INSERT:
1222 // interpret this as if a straight " was typed
1223 cur.recordUndoSelection();
1224 interpretChar(cur, '\"');
1227 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1228 // handling such that "self-insert" works on "arbitrary stuff" too, and
1229 // math-insert only handles special math things like "matrix".
1230 case LFUN_MATH_INSERT: {
1231 cur.recordUndoSelection();
1232 if (cmd.argument() == "^" || cmd.argument() == "_")
1233 interpretChar(cur, cmd.argument()[0]);
1234 else if (!cur.selection())
1235 cur.niceInsert(cmd.argument());
1237 MathData ar(cur.buffer());
1238 asArray(cmd.argument(), ar);
1240 && ar[0]->asNestInset()
1241 && ar[0]->asNestInset()->nargs() > 1)
1242 handleNest(cur, ar[0]);
1244 cur.niceInsert(cmd.argument());
1249 case LFUN_DIALOG_SHOW_NEW_INSET: {
1250 docstring const & name = cmd.argument();
1252 if (name == "ref") {
1253 InsetMathRef tmp(buffer_, name);
1254 data = tmp.createDialogStr();
1255 cur.bv().showDialog(to_utf8(name), data);
1256 } else if (name == "mathspace") {
1257 cur.bv().showDialog(to_utf8(name));
1262 case LFUN_INSET_INSERT: {
1264 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1265 cur.recordUndoSelection();
1267 cur.forceBufferUpdate();
1272 case LFUN_INSET_DISSOLVE:
1273 if (!asHullInset()) {
1274 cur.recordUndoInset();
1279 case LFUN_MATH_LIMITS: {
1281 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1282 in = &cur.nextMath();
1283 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1284 in = &cur.prevMath();
1285 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1286 in = cur.cell().back().nucleus();
1287 // only when nucleus allows this
1290 cur.recordUndoInset();
1291 if (!cmd.argument().empty()) {
1292 if (cmd.argument() == "limits")
1294 else if (cmd.argument() == "nolimits")
1295 in->limits(NO_LIMITS);
1297 in->limits(AUTO_LIMITS);
1298 } else if (in->limits() == AUTO_LIMITS)
1299 in->limits(in->defaultLimits() == LIMITS ? NO_LIMITS : LIMITS);
1301 in->limits(AUTO_LIMITS);
1306 InsetMath::doDispatch(cur, cmd);
1312 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1313 // look for macro to open/close, but stay in mathed
1314 for (; !it.empty(); it.pop_back()) {
1316 // go backward through the current cell
1317 Inset * inset = it.nextInset();
1318 while (inset && inset->asInsetMath()) {
1319 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1321 // found the an macro to open/close?
1322 if (macro->folded() != fold)
1325 // Wrong folding state.
1326 // If this was the first we see in this slice, look further left,
1328 if (inset != it.nextInset())
1332 // go up if this was the left most position
1338 inset = it.nextInset();
1346 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1347 FuncStatus & flag) const
1349 // the font related toggles
1350 //string tc = "mathnormal";
1352 string const arg = to_utf8(cmd.argument());
1353 switch (cmd.action()) {
1355 case LFUN_INSET_MODIFY:
1356 // FIXME: check temporarily disabled
1358 char align = mathcursor::valign();
1359 if (align == '\0') {
1363 if (cmd.argument().empty()) {
1367 if (!contains("tcb", cmd.argument()[0])) {
1371 flag.setOnOff(cmd.argument()[0] == align);
1374 /// We have to handle them since 1.4 blocks all unhandled actions
1375 case LFUN_FONT_ITAL:
1376 case LFUN_FONT_BOLD:
1377 case LFUN_FONT_BOLDSYMBOL:
1378 case LFUN_FONT_SANS:
1379 case LFUN_FONT_EMPH:
1380 case LFUN_FONT_TYPEWRITER:
1381 case LFUN_FONT_NOUN:
1382 case LFUN_FONT_ROMAN:
1383 case LFUN_FONT_DEFAULT:
1384 flag.setEnabled(true);
1387 // we just need to be in math mode to enable that
1388 case LFUN_MATH_SIZE:
1389 case LFUN_MATH_SPACE:
1390 case LFUN_MATH_EXTERN:
1391 flag.setEnabled(true);
1394 case LFUN_FONT_UNDERLINE:
1395 case LFUN_FONT_FRAK:
1396 flag.setEnabled(currentMode() != TEXT_MODE);
1399 case LFUN_MATH_FONT_STYLE: {
1400 bool const textarg =
1401 arg == "textbf" || arg == "textsf" ||
1402 arg == "textrm" || arg == "textmd" ||
1403 arg == "textit" || arg == "textsc" ||
1404 arg == "textsl" || arg == "textup" ||
1405 arg == "texttt" || arg == "textbb" ||
1406 arg == "textnormal";
1407 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1411 case LFUN_MATH_MODE:
1412 // forbid "math-mode on" in math mode to prevent irritating
1413 // behaviour of menu entries (bug 6709)
1414 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1417 case LFUN_MATH_INSERT:
1418 flag.setEnabled(currentMode() != TEXT_MODE);
1421 case LFUN_MATH_AMS_MATRIX:
1422 case LFUN_MATH_MATRIX:
1423 flag.setEnabled(currentMode() == MATH_MODE);
1426 case LFUN_INSET_INSERT: {
1427 // Don't test createMathInset_fromDialogStr(), since
1428 // getStatus is not called with a valid reference and the
1429 // dialog would not be applicable.
1430 string const name = cmd.getArg(0);
1431 flag.setEnabled(name == "ref" || name == "mathspace");
1435 case LFUN_DIALOG_SHOW_NEW_INSET: {
1436 docstring const & name = cmd.argument();
1437 if (name == "space")
1438 flag.setEnabled(false);
1443 case LFUN_MATH_DELIM:
1444 case LFUN_MATH_BIGDELIM:
1445 // Don't do this with multi-cell selections
1446 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1449 case LFUN_MATH_MACRO_FOLD:
1450 case LFUN_MATH_MACRO_UNFOLD: {
1452 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1453 flag.setEnabled(found);
1457 case LFUN_SPECIALCHAR_INSERT:
1458 case LFUN_SCRIPT_INSERT:
1459 // FIXME: These would probably make sense in math-text mode
1460 flag.setEnabled(false);
1463 case LFUN_CAPTION_INSERT:
1464 flag.setEnabled(false);
1467 case LFUN_SPACE_INSERT: {
1468 docstring const & name = cmd.argument();
1469 if (name == "visible")
1470 flag.setEnabled(false);
1474 case LFUN_INSET_DISSOLVE:
1475 flag.setEnabled(!asHullInset());
1479 docstring const & name = cmd.argument();
1480 if (name == "html" || name == "latex")
1481 flag.setEnabled(false);
1485 case LFUN_MATH_LIMITS: {
1487 if (cur.pos() < cur.lastpos() && cur.nextMath().allowsLimitsChange())
1488 in = &cur.nextMath();
1489 else if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange())
1490 in = &cur.prevMath();
1491 else if (cur.lastpos() > 0 && cur.cell().back()->allowsLimitsChange())
1492 in = cur.cell().back().nucleus();
1494 if (!cmd.argument().empty()) {
1495 if (cmd.argument() == "limits")
1496 flag.setOnOff(in->limits() == LIMITS);
1497 else if (cmd.argument() == "nolimits")
1498 flag.setOnOff(in->limits() == NO_LIMITS);
1500 flag.setOnOff(in->limits() == AUTO_LIMITS);
1502 flag.setEnabled(true);
1504 flag.setEnabled(false);
1516 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1519 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1520 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1521 enter_front ? idxFirst(cur) : idxLast(cur);
1523 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1527 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1530 int dist_min = 1000000;
1531 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1532 int const d = cell(i).dist(cur.bv(), x, y);
1541 MathData & ar = cell(idx_min);
1543 cur.idx() = idx_min;
1544 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1546 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1547 if (dist_min == 0) {
1549 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1550 if (ar[i]->covers(cur.bv(), x, y))
1551 return ar[i].nucleus()->editXY(cur, x, y);
1557 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1559 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1560 BufferView & bv = cur.bv();
1561 if (cmd.button() == mouse_button::button3) {
1562 // Don't do anything if we right-click a
1563 // selection, a context menu will popup.
1564 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1565 && cur < bv.cursor().selectionEnd()) {
1566 cur.noScreenUpdate();
1571 // set cursor after the inset if x is nearer to that position (bug 9748)
1572 cur.moveToClosestEdge(cmd.x(), true);
1574 bool do_selection = cmd.button() == mouse_button::button1
1575 && cmd.modifier() == ShiftModifier;
1576 bv.mouseSetCursor(cur, do_selection);
1577 if (cmd.button() == mouse_button::button1) {
1578 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1579 // Update the cursor update flags as needed:
1581 // Update::Decoration: tells to update the decoration
1582 // (visual box corners that define
1584 // Update::FitCursor: adjust the screen to the cursor
1585 // position if needed
1586 // cur.result().update(): don't overwrite previously set flags.
1587 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1588 | cur.result().screenUpdate());
1589 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1590 if (cap::selection()) {
1591 // See comment in Text::dispatch why we do this
1592 cap::copySelectionToStack();
1593 cmd = FuncRequest(LFUN_PASTE, "0");
1594 doDispatch(bv.cursor(), cmd);
1597 asArray(theSelection().get(), ar);
1598 bv.cursor().insert(ar);
1604 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1606 // only select with button 1
1607 if (cmd.button() != mouse_button::button1)
1610 Cursor & bvcur = cur.bv().cursor();
1612 // ignore motions deeper nested than the real anchor
1613 if (!bvcur.realAnchor().hasPart(cur)) {
1618 // set cursor after the inset if x is nearer to that position (bug 9748)
1619 cur.moveToClosestEdge(cmd.x());
1621 CursorSlice old = bvcur.top();
1623 // We continue with our existing selection or start a new one, so don't
1624 // reset the anchor.
1625 bvcur.setCursor(cur);
1626 // Did we actually move?
1627 if (cur.top() == old)
1628 // We didn't move one iota, so no need to change selection status
1629 // or update the screen.
1630 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1632 bvcur.setSelection();
1636 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1638 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1640 if (cmd.button() == mouse_button::button1) {
1641 if (!cur.selection())
1642 cur.noScreenUpdate();
1644 Cursor & bvcur = cur.bv().cursor();
1645 bvcur.selection(true);
1654 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1656 // try auto-correction
1657 if (lyxrc.autocorrection_math && cur.pos() != 0
1658 && math_autocorrect(cur, 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 InsetMathMacroArgument(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.nextInset()->edit(cur, true);
1770 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1772 interpretChar(cur, c);
1777 // just clear selection on pressing the space bar
1778 if (cur.selection() && c == ' ') {
1779 cur.selection(false);
1784 //lyxerr << "starting with macro" << endl;
1785 bool reduced = cap::reduceSelectionToOneCell(cur);
1786 if (reduced || !cur.selection()) {
1787 cur.recordUndoInset();
1788 docstring const safe = cap::grabAndEraseSelection(cur);
1789 if (!cur.inRegexped())
1790 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1792 cur.niceInsert(createInsetMath("backslash", buf));
1800 if (currentMode() != InsetMath::MATH_MODE)
1806 if (currentMode() != InsetMath::MATH_MODE) {
1807 // insert spaces in text or undecided mode,
1808 // but suppress direct insertion of two spaces in a row
1809 // the still allows typing '<space>a<space>' and deleting the 'a', but
1810 // it is better than nothing...
1811 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1813 // FIXME: we have to enable full redraw here because of the
1814 // visual box corners that define the inset. If we know for
1815 // sure that we stay within the same cell we can optimize for
1817 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1821 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1822 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1823 // FIXME: we have to enable full redraw here because of the
1824 // visual box corners that define the inset. If we know for
1825 // sure that we stay within the same cell we can optimize for
1827 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1831 if (cur.popForward()) {
1832 // FIXME: we have to enable full redraw here because of the
1833 // visual box corners that define the inset. If we know for
1834 // sure that we stay within the same cell we can optimize for
1836 //cur.screenUpdateFlags(Update::FitCursor);
1840 // if we are at the very end, leave the formula
1841 return cur.pos() != cur.lastpos();
1844 // These should be treated differently when not in text mode:
1845 if (cur.inRegexped()) {
1848 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1855 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1858 cur.niceInsert(createInsetMath("sim", buf));
1864 } else if (currentMode() != InsetMath::TEXT_MODE) {
1866 script(cur, false, save_selection);
1870 script(cur, true, save_selection);
1874 cur.niceInsert(createInsetMath("sim", buf));
1877 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1878 MathAtom at = createInsetMath("text", buf);
1879 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1886 cur.niceInsert(createInsetMath("textasciicircum", buf));
1890 cur.niceInsert(createInsetMath("textasciitilde", buf));
1895 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1896 c == '%' || c == '_') {
1897 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1901 // no special circumstances, so insert the character without any fuss
1907 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1909 if (str == "\\limits" || str == "\\nolimits") {
1910 if (cur.pos() > 0 && cur.prevMath().allowsLimitsChange()) {
1911 cur.prevMath().limits(str == "\\limits" ? LIMITS : NO_LIMITS);
1914 cur.message(bformat(_("Cannot apply %1$s here."), str));
1918 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1920 if (!cur.empty() && cur.pos() > 0 &&
1921 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1922 if (InsetMathBig::isBigInsetDelim(str)) {
1923 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1924 if (prev[0] == '\\') {
1925 prev = prev.substr(1);
1926 latexkeys const * l = in_word_set(prev);
1927 if (l && l->inset == "big") {
1928 cur.recordUndoSelection();
1929 cur.cell()[cur.pos() - 1] =
1930 MathAtom(new InsetMathBig(prev, str));
1940 bool InsetMathNest::script(Cursor & cur, bool up)
1942 return script(cur, up, docstring());
1946 bool InsetMathNest::script(Cursor & cur, bool up,
1947 docstring const & save_selection)
1949 // Hack to get \^ and \_ working
1950 //lyxerr << "handling script: up: " << up << endl;
1951 if (cur.inMacroMode() && cur.macroName() == "\\") {
1953 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1955 interpretChar(cur, '_');
1959 cur.macroModeClose();
1960 if (asScriptInset() && cur.idx() == 0) {
1961 // we are in a nucleus of a script inset, move to _our_ script
1962 InsetMathScript * inset = asScriptInset();
1963 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1965 cur.idx() = inset->idxOfScript(up);
1967 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1969 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1972 cur.idx() = inset->idxOfScript(up);
1973 cur.pos() = cur.lastpos();
1975 // convert the thing to our left to a scriptinset or create a new
1976 // one if in the very first position of the array
1977 if (cur.pos() == 0) {
1978 //lyxerr << "new scriptinset" << endl;
1979 cur.insert(new InsetMathScript(buffer_, up));
1981 //lyxerr << "converting prev atom " << endl;
1982 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1985 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1986 // See comment in MathParser.cpp for special handling of {}-bases
1992 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1993 cur.niceInsert(save_selection);
1995 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
2000 bool InsetMathNest::completionSupported(Cursor const & cur) const
2002 return cur.inMacroMode();
2006 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
2008 return cur.inMacroMode();
2012 bool InsetMathNest::automaticInlineCompletion() const
2014 return lyxrc.completion_inline_math;
2018 bool InsetMathNest::automaticPopupCompletion() const
2020 return lyxrc.completion_popup_math;
2024 CompletionList const *
2025 InsetMathNest::createCompletionList(Cursor const & cur) const
2027 if (!cur.inMacroMode())
2030 return new MathCompletionList(cur);
2034 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2036 if (!cur.inMacroMode())
2039 return cur.activeMacro()->name();
2043 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2046 if (!cur.inMacroMode())
2049 // append completion to active macro
2050 InsetMathUnknown * inset = cur.activeMacro();
2051 inset->setName(inset->name() + s);
2056 // FIXME: this creates duplicates in the completion popup
2057 // which looks ugly. Moreover the changes the list lengths
2058 // which seems to confuse the popup as well.
2059 MathCompletionList::addToFavorites(inset->name());
2061 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2068 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2069 Dimension & dim) const
2071 Inset const * inset = cur.activeMacro();
2075 // get inset dimensions
2076 dim = cur.bv().coordCache().insets().dim(inset);
2077 // FIXME: these 3 are no accurate, but should depend on the font.
2078 // Now the popup jumps down if you enter a char with descent > 0.
2083 Point xy = cur.bv().coordCache().insets().xy(inset);
2089 ////////////////////////////////////////////////////////////////////
2091 MathCompletionList::MathCompletionList(Cursor const & cur)
2093 // fill it with macros from the buffer
2094 MacroNameSet macros;
2095 cur.buffer()->listMacroNames(macros);
2096 MacroNameSet::const_iterator it;
2097 for (it = macros.begin(); it != macros.end(); ++it) {
2098 if (cur.buffer()->getMacro(*it, cur, false))
2099 locals.push_back("\\" + *it);
2101 sort(locals.begin(), locals.end());
2103 if (!globals.empty())
2106 // fill in global macros
2108 MacroTable::globalMacros().getMacroNames(macros, false);
2109 //lyxerr << "Globals completion macros: ";
2110 for (it = macros.begin(); it != macros.end(); ++it) {
2111 //lyxerr << "\\" + *it << " ";
2112 globals.push_back("\\" + *it);
2114 //lyxerr << std::endl;
2116 // fill in global commands
2117 globals.push_back(from_ascii("\\boxed"));
2118 globals.push_back(from_ascii("\\fbox"));
2119 globals.push_back(from_ascii("\\framebox"));
2120 globals.push_back(from_ascii("\\makebox"));
2121 globals.push_back(from_ascii("\\kern"));
2122 globals.push_back(from_ascii("\\xhookrightarrow"));
2123 globals.push_back(from_ascii("\\xhookleftarrow"));
2124 globals.push_back(from_ascii("\\xrightarrow"));
2125 globals.push_back(from_ascii("\\xRightarrow"));
2126 globals.push_back(from_ascii("\\xrightharpoondown"));
2127 globals.push_back(from_ascii("\\xrightharpoonup"));
2128 globals.push_back(from_ascii("\\xrightleftharpoons"));
2129 globals.push_back(from_ascii("\\xleftarrow"));
2130 globals.push_back(from_ascii("\\xLeftarrow"));
2131 globals.push_back(from_ascii("\\xleftharpoondown"));
2132 globals.push_back(from_ascii("\\xleftharpoonup"));
2133 globals.push_back(from_ascii("\\xleftrightarrow"));
2134 globals.push_back(from_ascii("\\xLeftrightarrow"));
2135 globals.push_back(from_ascii("\\xleftrightharpoons"));
2136 globals.push_back(from_ascii("\\xmapsto"));
2137 globals.push_back(from_ascii("\\split"));
2138 globals.push_back(from_ascii("\\gathered"));
2139 globals.push_back(from_ascii("\\aligned"));
2140 globals.push_back(from_ascii("\\alignedat"));
2141 globals.push_back(from_ascii("\\cases"));
2142 globals.push_back(from_ascii("\\substack"));
2143 globals.push_back(from_ascii("\\xymatrix"));
2144 globals.push_back(from_ascii("\\Diagram"));
2145 globals.push_back(from_ascii("\\subarray"));
2146 globals.push_back(from_ascii("\\array"));
2147 globals.push_back(from_ascii("\\sqrt"));
2148 globals.push_back(from_ascii("\\root"));
2149 globals.push_back(from_ascii("\\tabular"));
2150 globals.push_back(from_ascii("\\sideset"));
2151 globals.push_back(from_ascii("\\stackrel"));
2152 globals.push_back(from_ascii("\\stackrelthree"));
2153 globals.push_back(from_ascii("\\binom"));
2154 globals.push_back(from_ascii("\\choose"));
2155 globals.push_back(from_ascii("\\brace"));
2156 globals.push_back(from_ascii("\\brack"));
2157 globals.push_back(from_ascii("\\frac"));
2158 globals.push_back(from_ascii("\\over"));
2159 globals.push_back(from_ascii("\\nicefrac"));
2160 globals.push_back(from_ascii("\\unitfrac"));
2161 globals.push_back(from_ascii("\\unitfracthree"));
2162 globals.push_back(from_ascii("\\unitone"));
2163 globals.push_back(from_ascii("\\unittwo"));
2164 globals.push_back(from_ascii("\\infer"));
2165 globals.push_back(from_ascii("\\atop"));
2166 globals.push_back(from_ascii("\\lefteqn"));
2167 globals.push_back(from_ascii("\\boldsymbol"));
2168 globals.push_back(from_ascii("\\bm"));
2169 globals.push_back(from_ascii("\\color"));
2170 globals.push_back(from_ascii("\\normalcolor"));
2171 globals.push_back(from_ascii("\\textcolor"));
2172 globals.push_back(from_ascii("\\cfrac"));
2173 globals.push_back(from_ascii("\\cfracleft"));
2174 globals.push_back(from_ascii("\\cfracright"));
2175 globals.push_back(from_ascii("\\dfrac"));
2176 globals.push_back(from_ascii("\\tfrac"));
2177 globals.push_back(from_ascii("\\dbinom"));
2178 globals.push_back(from_ascii("\\tbinom"));
2179 globals.push_back(from_ascii("\\hphantom"));
2180 globals.push_back(from_ascii("\\phantom"));
2181 globals.push_back(from_ascii("\\vphantom"));
2182 globals.push_back(from_ascii("\\cancel"));
2183 globals.push_back(from_ascii("\\bcancel"));
2184 globals.push_back(from_ascii("\\xcancel"));
2185 globals.push_back(from_ascii("\\cancelto"));
2186 globals.push_back(from_ascii("\\smash"));
2187 globals.push_back(from_ascii("\\mathclap"));
2188 globals.push_back(from_ascii("\\mathllap"));
2189 globals.push_back(from_ascii("\\mathrlap"));
2190 globals.push_back(from_ascii("\\ensuremath"));
2191 MathWordList const & words = mathedWordList();
2192 MathWordList::const_iterator it2;
2193 //lyxerr << "Globals completion commands: ";
2194 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2195 if (it2->second.inset != "macro" && !it2->second.hidden) {
2196 // macros are already read from MacroTable::globalMacros()
2197 globals.push_back('\\' + it2->first);
2198 //lyxerr << '\\' + it2->first << ' ';
2201 //lyxerr << std::endl;
2202 sort(globals.begin(), globals.end());
2206 MathCompletionList::~MathCompletionList()
2211 size_type MathCompletionList::size() const
2213 return locals.size() + globals.size();
2217 docstring const & MathCompletionList::data(size_t idx) const
2219 size_t lsize = locals.size();
2221 return globals[idx - lsize];
2227 std::string MathCompletionList::icon(size_t idx) const
2229 // get the latex command
2231 size_t lsize = locals.size();
2233 cmd = globals[idx - lsize];
2237 // get the icon name by stripping the backslash
2238 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2239 if (icon_name.empty())
2240 return std::string();
2241 return "math/" + to_utf8(icon_name);
2244 std::vector<docstring> MathCompletionList::globals;