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)
190 for (idx_type i = 0, n = nargs(); i != n; ++i)
191 cell(i).updateBuffer(it, utype);
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 && (!LaTeXFeatures::isAvailable("dvipost")
362 || (runparams.flavor != OutputParams::LATEX
363 && runparams.flavor != OutputParams::DVILUATEX)));
364 if (runparams.inulemcmd) {
365 wi.ulemCmd(WriteStream::UNDERLINE);
366 if (runparams.local_font) {
367 FontInfo f = runparams.local_font->fontInfo();
368 if (f.strikeout() == FONT_ON)
369 wi.ulemCmd(WriteStream::STRIKEOUT);
372 wi.canBreakLine(os.canBreakLine());
373 Changer dummy = wi.changeRowEntry(TexRow::textEntry(runparams.lastid,
376 // Reset parbreak status after a math inset.
378 os.canBreakLine(wi.canBreakLine());
382 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
385 mouse_hover_[bv] = mouse_hover;
390 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
394 MathData & ar = cur.cell();
395 // remove base-only "scripts"
396 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
397 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
398 if (p && p->nargs() == 1) {
399 MathData ar = p->nuc();
402 cur.adjust(i, ar.size() - 1);
406 // glue adjacent font insets of the same kind
407 for (pos_type i = 0; i + 1 < size(); ++i) {
408 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
409 InsetMathFont const * q = operator[](i + 1)->asFontInset();
410 if (p && q && p->name() == q->name()) {
411 p->cell(0).append(q->cell(0));
421 void InsetMathNest::handleFont
422 (Cursor & cur, docstring const & arg, char const * const font)
424 handleFont(cur, arg, from_ascii(font));
428 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
429 docstring const & font)
431 cur.recordUndoSelection();
433 // this whole function is a hack and won't work for incremental font
435 if (cur.inset().asInsetMath()->name() == font)
436 cur.handleFont(to_utf8(font));
438 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
442 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
444 handleNest(cur, nest, docstring());
448 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
449 docstring const & arg)
451 CursorSlice i1 = cur.selBegin();
452 CursorSlice i2 = cur.selEnd();
453 if (!i1.inset().asInsetMath())
455 if (i1.idx() == i2.idx()) {
456 // the easy case where only one cell is selected
457 cur.handleNest(nest);
462 // multiple selected cells in a simple non-grid inset
463 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
464 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
469 cur.pos() = cur.lastpos();
472 // change font of cell
473 cur.handleNest(nest);
476 // cur is in the font inset now. If the loop continues,
477 // we need to get outside again for the next cell
478 if (i + 1 <= i2.idx())
484 // the complicated case with multiple selected cells in a grid
487 cap::region(i1, i2, r1, r2, c1, c2);
488 for (row_type row = r1; row <= r2; ++row) {
489 for (col_type col = c1; col <= c2; ++col) {
491 cur.idx() = i1.asInsetMath()->index(row, col);
494 cur.pos() = cur.lastpos();
498 cur.handleNest(nest);
501 // cur is in the font inset now. If the loop continues,
502 // we need to get outside again for the next cell
503 if (col + 1 <= c2 || row + 1 <= r2)
510 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
512 cur.recordUndoSelection();
515 font.fromString(to_utf8(arg), b);
516 if (font.fontInfo().color() != Color_inherit &&
517 font.fontInfo().color() != Color_ignore)
518 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
520 // FIXME: support other font changes here as well?
524 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
526 //LYXERR0("InsetMathNest: request: " << cmd);
528 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
530 FuncCode const act = cmd.action();
533 case LFUN_CLIPBOARD_PASTE:
534 parseflg |= Parse::VERBATIM;
537 if (cur.currentMode() != MATH_MODE)
538 parseflg |= Parse::TEXTMODE;
539 cur.recordUndoSelection();
540 cur.message(_("Paste"));
541 replaceSelection(cur);
543 if (cmd.argument().empty() && !theClipboard().isInternal())
544 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
547 idocstringstream is(cmd.argument());
549 topaste = cap::selection(n, buffer().params().documentClassPtr());
551 cur.niceInsert(topaste, parseflg, false);
552 cur.clearSelection(); // bug 393
553 cur.forceBufferUpdate();
560 cutSelection(cur, true);
561 cur.message(_("Cut"));
562 // Prevent stale position >= size crash
563 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
565 cur.forceBufferUpdate();
570 cur.message(_("Copy"));
573 case LFUN_MOUSE_PRESS:
574 lfunMousePress(cur, cmd);
577 case LFUN_MOUSE_MOTION:
578 lfunMouseMotion(cur, cmd);
581 case LFUN_MOUSE_RELEASE:
582 lfunMouseRelease(cur, cmd);
585 case LFUN_FINISHED_LEFT: // in math, left is backwards
586 case LFUN_FINISHED_BACKWARD:
587 cur.bv().cursor() = cur;
590 case LFUN_FINISHED_RIGHT: // in math, right is forward
591 case LFUN_FINISHED_FORWARD:
593 cur.bv().cursor() = cur;
596 case LFUN_WORD_RIGHT:
598 case LFUN_WORD_BACKWARD:
599 case LFUN_WORD_FORWARD:
600 case LFUN_CHAR_RIGHT:
602 case LFUN_CHAR_BACKWARD:
603 case LFUN_CHAR_FORWARD:
604 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
606 case LFUN_WORD_RIGHT_SELECT:
607 case LFUN_WORD_LEFT_SELECT:
608 case LFUN_WORD_BACKWARD_SELECT:
609 case LFUN_WORD_FORWARD_SELECT:
610 case LFUN_CHAR_RIGHT_SELECT:
611 case LFUN_CHAR_LEFT_SELECT:
612 case LFUN_CHAR_BACKWARD_SELECT:
613 case LFUN_CHAR_FORWARD_SELECT: {
614 // are we in a selection?
615 bool select = (act == LFUN_WORD_RIGHT_SELECT
616 || act == LFUN_WORD_LEFT_SELECT
617 || act == LFUN_WORD_BACKWARD_SELECT
618 || act == LFUN_WORD_FORWARD_SELECT
619 || act == LFUN_CHAR_RIGHT_SELECT
620 || act == LFUN_CHAR_LEFT_SELECT
621 || act == LFUN_CHAR_BACKWARD_SELECT
622 || act == LFUN_CHAR_FORWARD_SELECT);
624 bool word = (act == LFUN_WORD_RIGHT_SELECT
625 || act == LFUN_WORD_LEFT_SELECT
626 || act == LFUN_WORD_BACKWARD_SELECT
627 || act == LFUN_WORD_FORWARD_SELECT
628 || act == LFUN_WORD_RIGHT
629 || act == LFUN_WORD_LEFT
630 || act == LFUN_WORD_BACKWARD
631 || act == LFUN_WORD_FORWARD);
632 // are we moving forward or backwards?
633 // If the command was RIGHT or LEFT, then whether we're moving forward
634 // or backwards depends on the cursor movement mode (logical or visual):
635 // * in visual mode, since math is always LTR, right -> forward,
637 // * in logical mode, the mapping is determined by the
638 // reverseDirectionNeeded() function
641 FuncCode finish_lfun;
643 if (act == LFUN_CHAR_FORWARD
644 || act == LFUN_CHAR_FORWARD_SELECT
645 || act == LFUN_WORD_FORWARD
646 || act == LFUN_WORD_FORWARD_SELECT) {
648 finish_lfun = LFUN_FINISHED_FORWARD;
650 else if (act == LFUN_CHAR_BACKWARD
651 || act == LFUN_CHAR_BACKWARD_SELECT
652 || act == LFUN_WORD_BACKWARD
653 || act == LFUN_WORD_BACKWARD_SELECT) {
655 finish_lfun = LFUN_FINISHED_BACKWARD;
658 bool right = (act == LFUN_CHAR_RIGHT_SELECT
659 || act == LFUN_CHAR_RIGHT
660 || act == LFUN_WORD_RIGHT_SELECT
661 || act == LFUN_WORD_RIGHT);
662 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
668 finish_lfun = LFUN_FINISHED_RIGHT;
670 finish_lfun = LFUN_FINISHED_LEFT;
672 // Now that we know exactly what we want to do, let's do it!
673 cur.selHandle(select);
675 cur.macroModeClose();
676 // try moving forward or backwards as necessary...
677 if (!(forward ? cur.mathForward(word) : cur.mathBackward(word))) {
678 // ... and if movement failed, then finish forward or backwards
680 cmd = FuncRequest(finish_lfun);
688 case LFUN_PARAGRAPH_UP:
689 case LFUN_PARAGRAPH_DOWN:
690 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
692 case LFUN_DOWN_SELECT:
694 case LFUN_PARAGRAPH_UP_SELECT:
695 case LFUN_PARAGRAPH_DOWN_SELECT: {
696 // close active macro
697 if (cur.inMacroMode()) {
698 cur.macroModeClose();
702 // stop/start the selection
703 bool select = act == LFUN_DOWN_SELECT
704 || act == LFUN_UP_SELECT
705 || act == LFUN_PARAGRAPH_DOWN_SELECT
706 || act == LFUN_PARAGRAPH_UP_SELECT;
707 cur.selHandle(select);
710 bool up = act == LFUN_UP || act == LFUN_UP_SELECT
711 || act == LFUN_PARAGRAPH_UP || act == LFUN_PARAGRAPH_UP_SELECT;
712 bool successful = cur.upDownInMath(up);
716 if (cur.fixIfBroken())
717 // FIXME: Something bad happened. We pass the corrected Cursor
718 // instead of letting things go worse.
721 // We did not manage to move the cursor.
726 case LFUN_MOUSE_DOUBLE:
727 case LFUN_WORD_SELECT:
729 cur.bv().mouseSetCursor(cur);
730 cur.pos() = cur.lastpos();
731 cur.bv().mouseSetCursor(cur, true);
734 case LFUN_MOUSE_TRIPLE:
737 cur.bv().mouseSetCursor(cur);
738 cur.idx() = cur.lastidx();
739 cur.pos() = cur.lastpos();
740 cur.bv().mouseSetCursor(cur, true);
743 case LFUN_LINE_BEGIN:
744 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
746 case LFUN_LINE_BEGIN_SELECT:
747 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
748 act == LFUN_WORD_LEFT_SELECT ||
749 act == LFUN_LINE_BEGIN_SELECT);
750 cur.macroModeClose();
751 if (cur.pos() != 0) {
753 } else if (cur.col() != 0) {
754 cur.idx() -= cur.col();
756 } else if (cur.idx() != 0) {
760 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
766 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
768 case LFUN_LINE_END_SELECT:
769 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
770 act == LFUN_WORD_RIGHT_SELECT ||
771 act == LFUN_LINE_END_SELECT);
772 cur.macroModeClose();
774 if (cur.pos() != cur.lastpos()) {
775 cur.pos() = cur.lastpos();
776 } else if (ncols() && (cur.col() != cur.lastcol())) {
777 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
778 cur.pos() = cur.lastpos();
779 } else if (cur.idx() != cur.lastidx()) {
780 cur.idx() = cur.lastidx();
781 cur.pos() = cur.lastpos();
783 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
788 case LFUN_CELL_FORWARD:
789 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
790 cur.selHandle(false);
792 cur.macroModeClose();
793 if (!cur.inset().idxNext(cur)) {
794 cur.idx() = firstIdx();
799 case LFUN_CELL_BACKWARD:
800 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
801 cur.selHandle(false);
803 cur.macroModeClose();
804 if (!cur.inset().idxPrev(cur)) {
805 cur.idx() = lastIdx();
806 cur.pos() = lyxrc.mac_like_cursor_movement ? cur.lastpos() : 0;
810 case LFUN_WORD_DELETE_BACKWARD:
811 case LFUN_CHAR_DELETE_BACKWARD:
813 // May affect external cell:
814 cur.recordUndoInset();
815 else if (!cur.inMacroMode())
816 cur.recordUndoSelection();
817 // if the inset can not be removed from within, delete it
818 if (!cur.backspace(cmd.getArg(0) == "force")) {
819 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
820 cur.innerText()->dispatch(cur, newcmd);
824 case LFUN_WORD_DELETE_FORWARD:
825 case LFUN_CHAR_DELETE_FORWARD:
826 if (cur.pos() == cur.lastpos())
827 // May affect external cell:
828 cur.recordUndoInset();
830 cur.recordUndoSelection();
831 // if the inset can not be removed from within, delete it
832 if (!cur.erase(cmd.getArg(0) == "force")) {
833 FuncRequest newcmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD, "force");
834 cur.innerText()->dispatch(cur, newcmd);
840 cur.clearSelection();
842 if (cur.inMacroMode())
843 cur.macroModeClose(true);
845 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
851 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
852 // that is traversed by a single <CursorLeft>/<CursorRight>.
853 case LFUN_INSET_TOGGLE:
859 case LFUN_SELF_INSERT:
860 // special case first for big delimiters
861 if (cmd.argument().size() != 1 && interpretString(cur, cmd.argument()))
864 for (char_type c : cmd.argument()) {
865 // Don't record undo steps if we are in macro mode and thus
866 // cmd.argument is the next character of the macro name.
867 // Otherwise we'll get an invalid cursor if we undo after
868 // the macro was finished and the macro is a known command,
869 // e.g. sqrt. Cursor::macroModeClose replaces in this case
870 // the InsetMathUnknown with name "frac" by an empty
871 // InsetMathFrac -> a pos value > 0 is invalid.
872 // A side effect is that an undo before the macro is finished
873 // undoes the complete macro, not only the last character.
874 // At the time we hit '\' we are not in macro mode, still.
875 if (!cur.inMacroMode())
876 cur.recordUndoSelection();
878 // special handling of space. If we insert an inset
879 // via macro mode, we want to put the cursor inside it
880 // if relevant. Think typing "\frac<space>".
882 && cur.inMacroMode() && cur.macroName() != "\\"
883 && cur.macroModeClose() && cur.pos() > 0)
884 cur.editInsertedInset();
885 else if (!interpretChar(cur, c)) {
886 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
888 // FIXME: can we avoid skipping the end of the string?
894 //case LFUN_SERVER_GET_XY:
897 case LFUN_SERVER_SET_XY: {
898 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
901 istringstream is(to_utf8(cmd.argument()));
907 // Special casing for superscript in case of LyX handling
909 case LFUN_ACCENT_CIRCUMFLEX:
910 if (cmd.argument().empty()) {
911 // do superscript if LyX handles
913 cur.recordUndoSelection();
914 script(cur, true, grabAndEraseSelection(cur));
918 case LFUN_ACCENT_UMLAUT:
919 case LFUN_ACCENT_ACUTE:
920 case LFUN_ACCENT_GRAVE:
921 case LFUN_ACCENT_BREVE:
922 case LFUN_ACCENT_DOT:
923 case LFUN_ACCENT_MACRON:
924 case LFUN_ACCENT_CARON:
925 case LFUN_ACCENT_TILDE:
926 case LFUN_ACCENT_CEDILLA:
927 case LFUN_ACCENT_CIRCLE:
928 case LFUN_ACCENT_UNDERDOT:
929 case LFUN_ACCENT_TIE:
930 case LFUN_ACCENT_OGONEK:
931 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
935 case LFUN_TEXTSTYLE_APPLY:
936 case LFUN_TEXTSTYLE_UPDATE:
937 handleFont2(cur, cmd.argument());
941 if (currentMode() != MATH_MODE)
942 handleFont(cur, cmd.argument(), "textbf");
944 handleFont(cur, cmd.argument(), "mathbf");
946 case LFUN_FONT_BOLDSYMBOL:
947 if (currentMode() != MATH_MODE)
948 handleFont(cur, cmd.argument(), "textbf");
950 handleFont(cur, cmd.argument(), "boldsymbol");
953 if (currentMode() != MATH_MODE)
954 handleFont(cur, cmd.argument(), "textsf");
956 handleFont(cur, cmd.argument(), "mathsf");
959 if (currentMode() != MATH_MODE)
960 handleFont(cur, cmd.argument(), "emph");
962 handleFont(cur, cmd.argument(), "mathcal");
964 case LFUN_FONT_ROMAN:
965 if (currentMode() != MATH_MODE)
966 handleFont(cur, cmd.argument(), "textrm");
968 handleFont(cur, cmd.argument(), "mathrm");
970 case LFUN_FONT_TYPEWRITER:
971 if (currentMode() != MATH_MODE)
972 handleFont(cur, cmd.argument(), "texttt");
974 handleFont(cur, cmd.argument(), "mathtt");
977 handleFont(cur, cmd.argument(), "mathfrak");
980 if (currentMode() != MATH_MODE)
981 handleFont(cur, cmd.argument(), "textit");
983 handleFont(cur, cmd.argument(), "mathit");
986 if (currentMode() != MATH_MODE)
987 // FIXME: should be "noun"
988 handleFont(cur, cmd.argument(), "textsc");
990 handleFont(cur, cmd.argument(), "mathbb");
992 case LFUN_FONT_DEFAULT:
993 handleFont(cur, cmd.argument(), "textnormal");
995 case LFUN_FONT_UNDERLINE:
997 cur.handleNest(createInsetMath("underline", cur.buffer()));
1000 case LFUN_MATH_MODE: {
1002 // ignore math-mode on when already in math mode
1003 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1005 cur.recordUndoSelection();
1006 cur.macroModeClose();
1007 docstring const save_selection = grabAndEraseSelection(cur);
1009 if (currentMode() != Inset::MATH_MODE)
1010 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1012 cur.plainInsert(createInsetMath("text", buffer_));
1014 cur.pushBackward(*cur.nextInset());
1015 cur.niceInsert(save_selection);
1016 cur.forceBufferUpdate();
1018 if (currentMode() == Inset::TEXT_MODE) {
1019 cur.recordUndoSelection();
1020 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1021 cur.message(_("create new math text environment ($...$)"));
1023 handleFont(cur, cmd.argument(), "textrm");
1024 cur.message(_("entered math text mode (textrm)"));
1030 case LFUN_REGEXP_MODE: {
1031 InsetMath * im = cur.inset().asInsetMath();
1033 InsetMathHull * i = im->asHullInset();
1034 if (i && i->getType() == hullRegexp) {
1035 cur.message(_("Already in regular expression mode"));
1039 cur.macroModeClose();
1040 docstring const save_selection = grabAndEraseSelection(cur);
1042 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1044 cur.pushBackward(*cur.nextInset());
1045 cur.niceInsert(save_selection);
1046 cur.message(_("Regular expression editor mode"));
1050 case LFUN_MATH_FONT_STYLE: {
1051 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1052 doDispatch(cur, fr);
1056 case LFUN_MATH_SIZE: {
1057 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1058 doDispatch(cur, fr);
1062 case LFUN_MATH_MATRIX: {
1068 idocstringstream is(cmd.argument());
1069 is >> m >> n >> v_align >> h_align;
1075 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1076 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1080 case LFUN_MATH_AMS_MATRIX: {
1084 docstring name = from_ascii("matrix");
1085 idocstringstream is(cmd.argument());
1086 is >> m >> n >> name;
1091 // check if we have a valid decoration
1092 if (name != "pmatrix" && name != "bmatrix"
1093 && name != "Bmatrix" && name != "vmatrix"
1094 && name != "Vmatrix" && name != "matrix")
1095 name = from_ascii("matrix");
1098 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1102 case LFUN_MATH_DELIM: {
1104 docstring rs = split(cmd.argument(), ls, ' ');
1105 // Reasonable default values
1111 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1115 case LFUN_MATH_BIGDELIM: {
1116 docstring const lname = from_utf8(cmd.getArg(0));
1117 docstring const ldelim = from_utf8(cmd.getArg(1));
1118 docstring const rname = from_utf8(cmd.getArg(2));
1119 docstring const rdelim = from_utf8(cmd.getArg(3));
1120 latexkeys const * l = in_word_set(lname);
1121 bool const have_l = l && l->inset == "big" &&
1122 InsetMathBig::isBigInsetDelim(ldelim);
1123 l = in_word_set(rname);
1124 bool const have_r = l && l->inset == "big" &&
1125 InsetMathBig::isBigInsetDelim(rdelim);
1126 // We mimic LFUN_MATH_DELIM in case we have an empty left
1127 // or right delimiter.
1128 if (have_l || have_r) {
1130 docstring const selection = grabAndEraseSelection(cur);
1133 cur.insert(MathAtom(new InsetMathBig(lname,
1135 // first insert the right delimiter and then go back
1136 // and re-insert the selection (bug 7088)
1138 cur.insert(MathAtom(new InsetMathBig(rname,
1142 cur.niceInsert(selection);
1144 // Don't call cur.undispatched() if we did nothing, this would
1145 // lead to infinite recursion via Text::dispatch().
1149 case LFUN_SPACE_INSERT: {
1150 cur.recordUndoSelection();
1151 string const name = cmd.getArg(0);
1152 if (name == "normal")
1153 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1154 else if (name == "protected")
1155 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1156 else if (name == "thin" || name == "med" || name == "thick")
1157 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1158 else if (name == "hfill*")
1159 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1160 else if (name == "quad" || name == "qquad" ||
1161 name == "enspace" || name == "enskip" ||
1162 name == "negthinspace" || name == "negmedspace" ||
1163 name == "negthickspace" || name == "hfill")
1164 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1165 else if (name == "hspace" || name == "hspace*") {
1166 string const len = cmd.getArg(1);
1167 if (len.empty() || !isValidLength(len)) {
1168 lyxerr << "LyX function 'space-insert " << name << "' "
1169 "needs a valid length argument." << endl;
1172 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1174 cur.insert(MathAtom(new InsetMathSpace));
1178 case LFUN_MATH_SPACE:
1179 cur.recordUndoSelection();
1180 if (cmd.argument().empty())
1181 cur.insert(MathAtom(new InsetMathSpace));
1183 string const name = cmd.getArg(0);
1184 string const len = cmd.getArg(1);
1185 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1189 case LFUN_ERT_INSERT:
1190 // interpret this as if a backslash was typed
1192 interpretChar(cur, '\\');
1195 case LFUN_MATH_SUBSCRIPT:
1196 // interpret this as if a _ was typed
1197 cur.recordUndoSelection();
1198 interpretChar(cur, '_');
1201 case LFUN_MATH_SUPERSCRIPT:
1202 // interpret this as if a ^ was typed
1203 cur.recordUndoSelection();
1204 interpretChar(cur, '^');
1207 case LFUN_MATH_MACRO_FOLD:
1208 case LFUN_MATH_MACRO_UNFOLD: {
1210 bool fold = act == LFUN_MATH_MACRO_FOLD;
1211 bool found = findMacroToFoldUnfold(it, fold);
1213 InsetMathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1214 cur.recordUndoInset();
1223 case LFUN_QUOTE_INSERT:
1224 // interpret this as if a straight " was typed
1225 cur.recordUndoSelection();
1226 interpretChar(cur, '\"');
1229 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1230 // handling such that "self-insert" works on "arbitrary stuff" too, and
1231 // math-insert only handles special math things like "matrix".
1232 case LFUN_MATH_INSERT: {
1233 cur.recordUndoSelection();
1234 if (cmd.argument() == "^" || cmd.argument() == "_")
1235 interpretChar(cur, cmd.argument()[0]);
1238 asArray(cmd.argument(), ar);
1239 if (cur.selection() && ar.size() == 1
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();
1280 InsetMath::doDispatch(cur, cmd);
1286 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1287 // look for macro to open/close, but stay in mathed
1288 for (; !it.empty(); it.pop_back()) {
1290 // go backward through the current cell
1291 Inset * inset = it.nextInset();
1292 while (inset && inset->asInsetMath()) {
1293 InsetMathMacro * macro = inset->asInsetMath()->asMacro();
1295 // found the an macro to open/close?
1296 if (macro->folded() != fold)
1299 // Wrong folding state.
1300 // If this was the first we see in this slice, look further left,
1302 if (inset != it.nextInset())
1306 // go up if this was the left most position
1312 inset = it.nextInset();
1320 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1321 FuncStatus & flag) const
1323 // the font related toggles
1324 //string tc = "mathnormal";
1326 string const arg = to_utf8(cmd.argument());
1327 switch (cmd.action()) {
1328 case LFUN_INSET_MODIFY:
1329 flag.setEnabled(false);
1332 case LFUN_INSET_MODIFY:
1333 // FIXME: check temporarily disabled
1335 char align = mathcursor::valign();
1336 if (align == '\0') {
1340 if (cmd.argument().empty()) {
1344 if (!contains("tcb", cmd.argument()[0])) {
1348 flag.setOnOff(cmd.argument()[0] == align);
1351 /// We have to handle them since 1.4 blocks all unhandled actions
1352 case LFUN_FONT_ITAL:
1353 case LFUN_FONT_BOLD:
1354 case LFUN_FONT_BOLDSYMBOL:
1355 case LFUN_FONT_SANS:
1356 case LFUN_FONT_EMPH:
1357 case LFUN_FONT_TYPEWRITER:
1358 case LFUN_FONT_NOUN:
1359 case LFUN_FONT_ROMAN:
1360 case LFUN_FONT_DEFAULT:
1361 flag.setEnabled(true);
1364 // we just need to be in math mode to enable that
1365 case LFUN_MATH_SIZE:
1366 case LFUN_MATH_SPACE:
1367 case LFUN_MATH_EXTERN:
1368 flag.setEnabled(true);
1371 case LFUN_FONT_UNDERLINE:
1372 case LFUN_FONT_FRAK:
1373 flag.setEnabled(currentMode() != TEXT_MODE);
1376 case LFUN_MATH_FONT_STYLE: {
1377 bool const textarg =
1378 arg == "textbf" || arg == "textsf" ||
1379 arg == "textrm" || arg == "textmd" ||
1380 arg == "textit" || arg == "textsc" ||
1381 arg == "textsl" || arg == "textup" ||
1382 arg == "texttt" || arg == "textbb" ||
1383 arg == "textnormal";
1384 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1388 case LFUN_MATH_MODE:
1389 // forbid "math-mode on" in math mode to prevent irritating
1390 // behaviour of menu entries (bug 6709)
1391 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1394 case LFUN_MATH_INSERT:
1395 flag.setEnabled(currentMode() != TEXT_MODE);
1398 case LFUN_MATH_AMS_MATRIX:
1399 case LFUN_MATH_MATRIX:
1400 flag.setEnabled(currentMode() == MATH_MODE);
1403 case LFUN_INSET_INSERT: {
1404 // Don't test createMathInset_fromDialogStr(), since
1405 // getStatus is not called with a valid reference and the
1406 // dialog would not be applyable.
1407 string const name = cmd.getArg(0);
1408 flag.setEnabled(name == "ref" || name == "mathspace");
1412 case LFUN_DIALOG_SHOW_NEW_INSET: {
1413 docstring const & name = cmd.argument();
1414 if (name == "space")
1415 flag.setEnabled(false);
1420 case LFUN_MATH_DELIM:
1421 case LFUN_MATH_BIGDELIM:
1422 // Don't do this with multi-cell selections
1423 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1426 case LFUN_MATH_MACRO_FOLD:
1427 case LFUN_MATH_MACRO_UNFOLD: {
1429 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1430 flag.setEnabled(found);
1434 case LFUN_SPECIALCHAR_INSERT:
1435 case LFUN_SCRIPT_INSERT:
1436 // FIXME: These would probably make sense in math-text mode
1437 flag.setEnabled(false);
1440 case LFUN_CAPTION_INSERT:
1441 flag.setEnabled(false);
1444 case LFUN_SPACE_INSERT: {
1445 docstring const & name = cmd.argument();
1446 if (name == "visible")
1447 flag.setEnabled(false);
1451 case LFUN_INSET_DISSOLVE:
1452 flag.setEnabled(!asHullInset());
1456 docstring const & name = cmd.argument();
1457 if (name == "html" || name == "latex")
1458 flag.setEnabled(false);
1470 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1473 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_LEFT ||
1474 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1475 enter_front ? idxFirst(cur) : idxLast(cur);
1477 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1481 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1484 int dist_min = 1000000;
1485 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1486 int const d = cell(i).dist(cur.bv(), x, y);
1495 MathData & ar = cell(idx_min);
1497 cur.idx() = idx_min;
1498 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1500 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1501 if (dist_min == 0) {
1503 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1504 if (ar[i]->covers(cur.bv(), x, y))
1505 return ar[i].nucleus()->editXY(cur, x, y);
1511 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1513 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1514 BufferView & bv = cur.bv();
1515 if (cmd.button() == mouse_button::button3) {
1516 // Don't do anything if we right-click a
1517 // selection, a context menu will popup.
1518 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1519 && cur < bv.cursor().selectionEnd()) {
1520 cur.noScreenUpdate();
1525 // set cursor after the inset if x is nearer to that position (bug 9748)
1526 cur.moveToClosestEdge(cmd.x(), true);
1528 bool do_selection = cmd.button() == mouse_button::button1
1529 && cmd.modifier() == ShiftModifier;
1530 bv.mouseSetCursor(cur, do_selection);
1531 if (cmd.button() == mouse_button::button1) {
1532 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1533 // Update the cursor update flags as needed:
1535 // Update::Decoration: tells to update the decoration
1536 // (visual box corners that define
1538 // Update::FitCursor: adjust the screen to the cursor
1539 // position if needed
1540 // cur.result().update(): don't overwrite previously set flags.
1541 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1542 | cur.result().screenUpdate());
1543 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1544 if (cap::selection()) {
1545 // See comment in Text::dispatch why we do this
1546 cap::copySelectionToStack();
1547 cmd = FuncRequest(LFUN_PASTE, "0");
1548 doDispatch(bv.cursor(), cmd);
1551 asArray(theSelection().get(), ar);
1552 bv.cursor().insert(ar);
1558 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1560 // only select with button 1
1561 if (cmd.button() != mouse_button::button1)
1564 Cursor & bvcur = cur.bv().cursor();
1566 // ignore motions deeper nested than the real anchor
1567 if (!bvcur.realAnchor().hasPart(cur)) {
1572 // set cursor after the inset if x is nearer to that position (bug 9748)
1573 cur.moveToClosestEdge(cmd.x());
1575 CursorSlice old = bvcur.top();
1577 // We continue with our existing selection or start a new one, so don't
1578 // reset the anchor.
1579 bvcur.setCursor(cur);
1580 // Did we actually move?
1581 if (cur.top() == old)
1582 // We didn't move one iota, so no need to change selection status
1583 // or update the screen.
1584 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1586 bvcur.setSelection();
1590 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1592 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1594 if (cmd.button() == mouse_button::button1) {
1595 if (!cur.selection())
1596 cur.noScreenUpdate();
1598 Cursor & bvcur = cur.bv().cursor();
1599 bvcur.selection(true);
1608 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1610 // try auto-correction
1611 if (lyxrc.autocorrection_math && cur.pos() != 0
1612 && math_autocorrect(cur, c))
1615 //lyxerr << "interpret 2: '" << c << "'" << endl;
1616 docstring save_selection;
1617 if (c == '^' || c == '_')
1618 save_selection = grabAndEraseSelection(cur);
1621 Buffer * buf = cur.buffer();
1624 if (cur.inMacroMode()) {
1625 docstring name = cur.macroName();
1627 /// are we currently typing '#1' or '#2' or...?
1628 if (name == "\\#") {
1631 if (n >= 1 && n <= 9)
1632 cur.insert(new InsetMathMacroArgument(n));
1636 // do not finish macro for known * commands
1637 bool star_macro = c == '*'
1638 && (in_word_set(name.substr(1) + '*')
1639 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1640 if (isAlphaASCII(c) || star_macro) {
1641 cur.activeMacro()->setName(name + docstring(1, c));
1645 // handle 'special char' macros
1650 if (currentMode() != InsetMath::MATH_MODE)
1651 cur.niceInsert(createInsetMath("textbackslash", buf));
1653 cur.niceInsert(createInsetMath("backslash", buf));
1654 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1656 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1657 } else if (c == '{' || c == '%') {
1658 //using the saved selection as argument
1659 InsetMathUnknown * p = cur.activeMacro();
1661 MathData sel(cur.buffer());
1662 asArray(p->selection(), sel);
1665 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1667 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1668 } else if (c == '#') {
1669 LASSERT(cur.activeMacro(), return false);
1670 cur.activeMacro()->setName(name + docstring(1, c));
1673 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1678 // One character big delimiters. The others are handled in
1679 // interpretString().
1680 latexkeys const * l = in_word_set(name.substr(1));
1681 if (name[0] == '\\' && l && l->inset == "big") {
1685 delim = from_ascii("\\{");
1688 delim = from_ascii("\\}");
1691 delim = docstring(1, c);
1694 if (InsetMathBig::isBigInsetDelim(delim)) {
1695 // name + delim ared a valid InsetMathBig.
1696 // We can't use cur.macroModeClose() because
1697 // it does not handle delim.
1698 InsetMathUnknown * p = cur.activeMacro();
1701 cur.cell().erase(cur.pos());
1702 cur.plainInsert(MathAtom(
1703 new InsetMathBig(name.substr(1), delim)));
1706 } else if (name == "\\smash" && c == '[') {
1707 // We can't use cur.macroModeClose() because
1708 // it would create an InsetMathPhantom
1709 InsetMathUnknown * p = cur.activeMacro();
1711 interpretChar(cur, c);
1715 // leave macro mode and try again if necessary
1716 if (cur.macroModeClose()) {
1717 MathAtom const atom = cur.prevAtom();
1718 if (atom->asNestInset() && atom->isActive()) {
1720 cur.nextInset()->edit(cur, true);
1724 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1726 interpretChar(cur, c);
1731 // just clear selection on pressing the space bar
1732 if (cur.selection() && c == ' ') {
1733 cur.selection(false);
1738 //lyxerr << "starting with macro" << endl;
1739 bool reduced = cap::reduceSelectionToOneCell(cur);
1740 if (reduced || !cur.selection()) {
1741 cur.recordUndoInset();
1742 docstring const safe = cap::grabAndEraseSelection(cur);
1743 if (!cur.inRegexped())
1744 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1746 cur.niceInsert(createInsetMath("backslash", buf));
1754 if (currentMode() != InsetMath::MATH_MODE)
1760 if (currentMode() != InsetMath::MATH_MODE) {
1761 // insert spaces in text or undecided mode,
1762 // but suppress direct insertion of two spaces in a row
1763 // the still allows typing '<space>a<space>' and deleting the 'a', but
1764 // it is better than nothing...
1765 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1767 // FIXME: we have to enable full redraw here because of the
1768 // visual box corners that define the inset. If we know for
1769 // sure that we stay within the same cell we can optimize for
1771 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1775 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1776 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1777 // FIXME: we have to enable full redraw here because of the
1778 // visual box corners that define the inset. If we know for
1779 // sure that we stay within the same cell we can optimize for
1781 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1785 if (cur.popForward()) {
1786 // FIXME: we have to enable full redraw here because of the
1787 // visual box corners that define the inset. If we know for
1788 // sure that we stay within the same cell we can optimize for
1790 //cur.screenUpdateFlags(Update::FitCursor);
1794 // if we are at the very end, leave the formula
1795 return cur.pos() != cur.lastpos();
1798 // These should be treated differently when not in text mode:
1799 if (cur.inRegexped()) {
1802 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1809 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1812 cur.niceInsert(createInsetMath("sim", buf));
1818 } else if (currentMode() != InsetMath::TEXT_MODE) {
1820 script(cur, false, save_selection);
1824 script(cur, true, save_selection);
1828 cur.niceInsert(createInsetMath("sim", buf));
1831 if (currentMode() == InsetMath::MATH_MODE && Encodings::isUnicodeTextOnly(c)) {
1832 MathAtom at = createInsetMath("text", buf);
1833 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1840 cur.niceInsert(createInsetMath("textasciicircum", buf));
1844 cur.niceInsert(createInsetMath("textasciitilde", buf));
1849 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1850 c == '%' || c == '_') {
1851 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1855 // no special circumstances, so insert the character without any fuss
1861 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1863 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1865 if (!cur.empty() && cur.pos() > 0 &&
1866 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1867 if (InsetMathBig::isBigInsetDelim(str)) {
1868 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1869 if (prev[0] == '\\') {
1870 prev = prev.substr(1);
1871 latexkeys const * l = in_word_set(prev);
1872 if (l && l->inset == "big") {
1873 cur.recordUndoSelection();
1874 cur.cell()[cur.pos() - 1] =
1875 MathAtom(new InsetMathBig(prev, str));
1885 bool InsetMathNest::script(Cursor & cur, bool up)
1887 return script(cur, up, docstring());
1891 bool InsetMathNest::script(Cursor & cur, bool up,
1892 docstring const & save_selection)
1894 // Hack to get \^ and \_ working
1895 //lyxerr << "handling script: up: " << up << endl;
1896 if (cur.inMacroMode() && cur.macroName() == "\\") {
1898 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1900 interpretChar(cur, '_');
1904 cur.macroModeClose();
1905 if (asScriptInset() && cur.idx() == 0) {
1906 // we are in a nucleus of a script inset, move to _our_ script
1907 InsetMathScript * inset = asScriptInset();
1908 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1910 cur.idx() = inset->idxOfScript(up);
1912 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1914 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1917 cur.idx() = inset->idxOfScript(up);
1918 cur.pos() = cur.lastpos();
1920 // convert the thing to our left to a scriptinset or create a new
1921 // one if in the very first position of the array
1922 if (cur.pos() == 0) {
1923 //lyxerr << "new scriptinset" << endl;
1924 cur.insert(new InsetMathScript(buffer_, up));
1926 //lyxerr << "converting prev atom " << endl;
1927 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1930 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1931 // See comment in MathParser.cpp for special handling of {}-bases
1937 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1938 cur.niceInsert(save_selection);
1940 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1945 bool InsetMathNest::completionSupported(Cursor const & cur) const
1947 return cur.inMacroMode();
1951 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1953 return cur.inMacroMode();
1957 bool InsetMathNest::automaticInlineCompletion() const
1959 return lyxrc.completion_inline_math;
1963 bool InsetMathNest::automaticPopupCompletion() const
1965 return lyxrc.completion_popup_math;
1969 CompletionList const *
1970 InsetMathNest::createCompletionList(Cursor const & cur) const
1972 if (!cur.inMacroMode())
1975 return new MathCompletionList(cur);
1979 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1981 if (!cur.inMacroMode())
1984 return cur.activeMacro()->name();
1988 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1991 if (!cur.inMacroMode())
1994 // append completion to active macro
1995 InsetMathUnknown * inset = cur.activeMacro();
1996 inset->setName(inset->name() + s);
2001 // FIXME: this creates duplicates in the completion popup
2002 // which looks ugly. Moreover the changes the list lengths
2003 // which seems to confuse the popup as well.
2004 MathCompletionList::addToFavorites(inset->name());
2006 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2013 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2014 Dimension & dim) const
2016 Inset const * inset = cur.activeMacro();
2020 // get inset dimensions
2021 dim = cur.bv().coordCache().insets().dim(inset);
2022 // FIXME: these 3 are no accurate, but should depend on the font.
2023 // Now the popup jumps down if you enter a char with descent > 0.
2028 Point xy = cur.bv().coordCache().insets().xy(inset);
2034 ////////////////////////////////////////////////////////////////////
2036 MathCompletionList::MathCompletionList(Cursor const & cur)
2038 // fill it with macros from the buffer
2039 MacroNameSet macros;
2040 cur.buffer()->listMacroNames(macros);
2041 MacroNameSet::const_iterator it;
2042 for (it = macros.begin(); it != macros.end(); ++it) {
2043 if (cur.buffer()->getMacro(*it, cur, false))
2044 locals.push_back("\\" + *it);
2046 sort(locals.begin(), locals.end());
2048 if (!globals.empty())
2051 // fill in global macros
2053 MacroTable::globalMacros().getMacroNames(macros, false);
2054 //lyxerr << "Globals completion macros: ";
2055 for (it = macros.begin(); it != macros.end(); ++it) {
2056 //lyxerr << "\\" + *it << " ";
2057 globals.push_back("\\" + *it);
2059 //lyxerr << std::endl;
2061 // fill in global commands
2062 globals.push_back(from_ascii("\\boxed"));
2063 globals.push_back(from_ascii("\\fbox"));
2064 globals.push_back(from_ascii("\\framebox"));
2065 globals.push_back(from_ascii("\\makebox"));
2066 globals.push_back(from_ascii("\\kern"));
2067 globals.push_back(from_ascii("\\xhookrightarrow"));
2068 globals.push_back(from_ascii("\\xhookleftarrow"));
2069 globals.push_back(from_ascii("\\xrightarrow"));
2070 globals.push_back(from_ascii("\\xRightarrow"));
2071 globals.push_back(from_ascii("\\xrightharpoondown"));
2072 globals.push_back(from_ascii("\\xrightharpoonup"));
2073 globals.push_back(from_ascii("\\xrightleftharpoons"));
2074 globals.push_back(from_ascii("\\xleftarrow"));
2075 globals.push_back(from_ascii("\\xLeftarrow"));
2076 globals.push_back(from_ascii("\\xleftharpoondown"));
2077 globals.push_back(from_ascii("\\xleftharpoonup"));
2078 globals.push_back(from_ascii("\\xleftrightarrow"));
2079 globals.push_back(from_ascii("\\xLeftrightarrow"));
2080 globals.push_back(from_ascii("\\xleftrightharpoons"));
2081 globals.push_back(from_ascii("\\xmapsto"));
2082 globals.push_back(from_ascii("\\split"));
2083 globals.push_back(from_ascii("\\gathered"));
2084 globals.push_back(from_ascii("\\aligned"));
2085 globals.push_back(from_ascii("\\alignedat"));
2086 globals.push_back(from_ascii("\\cases"));
2087 globals.push_back(from_ascii("\\substack"));
2088 globals.push_back(from_ascii("\\xymatrix"));
2089 globals.push_back(from_ascii("\\Diagram"));
2090 globals.push_back(from_ascii("\\subarray"));
2091 globals.push_back(from_ascii("\\array"));
2092 globals.push_back(from_ascii("\\sqrt"));
2093 globals.push_back(from_ascii("\\root"));
2094 globals.push_back(from_ascii("\\tabular"));
2095 globals.push_back(from_ascii("\\sideset"));
2096 globals.push_back(from_ascii("\\stackrel"));
2097 globals.push_back(from_ascii("\\stackrelthree"));
2098 globals.push_back(from_ascii("\\binom"));
2099 globals.push_back(from_ascii("\\choose"));
2100 globals.push_back(from_ascii("\\brace"));
2101 globals.push_back(from_ascii("\\brack"));
2102 globals.push_back(from_ascii("\\frac"));
2103 globals.push_back(from_ascii("\\over"));
2104 globals.push_back(from_ascii("\\nicefrac"));
2105 globals.push_back(from_ascii("\\unitfrac"));
2106 globals.push_back(from_ascii("\\unitfracthree"));
2107 globals.push_back(from_ascii("\\unitone"));
2108 globals.push_back(from_ascii("\\unittwo"));
2109 globals.push_back(from_ascii("\\infer"));
2110 globals.push_back(from_ascii("\\atop"));
2111 globals.push_back(from_ascii("\\lefteqn"));
2112 globals.push_back(from_ascii("\\boldsymbol"));
2113 globals.push_back(from_ascii("\\bm"));
2114 globals.push_back(from_ascii("\\color"));
2115 globals.push_back(from_ascii("\\normalcolor"));
2116 globals.push_back(from_ascii("\\textcolor"));
2117 globals.push_back(from_ascii("\\cfrac"));
2118 globals.push_back(from_ascii("\\cfracleft"));
2119 globals.push_back(from_ascii("\\cfracright"));
2120 globals.push_back(from_ascii("\\dfrac"));
2121 globals.push_back(from_ascii("\\tfrac"));
2122 globals.push_back(from_ascii("\\dbinom"));
2123 globals.push_back(from_ascii("\\tbinom"));
2124 globals.push_back(from_ascii("\\hphantom"));
2125 globals.push_back(from_ascii("\\phantom"));
2126 globals.push_back(from_ascii("\\vphantom"));
2127 globals.push_back(from_ascii("\\cancel"));
2128 globals.push_back(from_ascii("\\bcancel"));
2129 globals.push_back(from_ascii("\\xcancel"));
2130 globals.push_back(from_ascii("\\cancelto"));
2131 globals.push_back(from_ascii("\\smash"));
2132 globals.push_back(from_ascii("\\mathclap"));
2133 globals.push_back(from_ascii("\\mathllap"));
2134 globals.push_back(from_ascii("\\mathrlap"));
2135 globals.push_back(from_ascii("\\ensuremath"));
2136 MathWordList const & words = mathedWordList();
2137 MathWordList::const_iterator it2;
2138 //lyxerr << "Globals completion commands: ";
2139 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2140 if (it2->second.inset != "macro" && !it2->second.hidden) {
2141 // macros are already read from MacroTable::globalMacros()
2142 globals.push_back('\\' + it2->first);
2143 //lyxerr << '\\' + it2->first << ' ';
2146 //lyxerr << std::endl;
2147 sort(globals.begin(), globals.end());
2151 MathCompletionList::~MathCompletionList()
2156 size_type MathCompletionList::size() const
2158 return locals.size() + globals.size();
2162 docstring const & MathCompletionList::data(size_t idx) const
2164 size_t lsize = locals.size();
2166 return globals[idx - lsize];
2172 std::string MathCompletionList::icon(size_t idx) const
2174 // get the latex command
2176 size_t lsize = locals.size();
2178 cmd = globals[idx - lsize];
2182 // get the icon resource name by stripping the backslash
2183 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2184 if (icon_name.empty())
2185 return std::string();
2186 return "images/math/" + to_utf8(icon_name);
2189 std::vector<docstring> MathCompletionList::globals;