2 * \file InsetMathNest.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
8 * Full author contact details are available in file CREDITS.
13 #include "InsetMathNest.h"
15 #include "InsetMathArray.h"
16 #include "InsetMathAMSArray.h"
17 #include "InsetMathBig.h"
18 #include "InsetMathBox.h"
19 #include "InsetMathBrace.h"
20 #include "InsetMathChar.h"
21 #include "InsetMathColor.h"
22 #include "InsetMathComment.h"
23 #include "InsetMathDelim.h"
24 #include "InsetMathEnsureMath.h"
25 #include "InsetMathHull.h"
26 #include "InsetMathRef.h"
27 #include "InsetMathScript.h"
28 #include "InsetMathSpace.h"
29 #include "InsetMathSymbol.h"
30 #include "InsetMathUnknown.h"
31 #include "MathAutoCorrect.h"
32 #include "MathCompletionList.h"
34 #include "MathFactory.h"
35 #include "MathMacro.h"
36 #include "MathMacroArgument.h"
37 #include "MathParser.h"
38 #include "MathStream.h"
39 #include "MathSupport.h"
42 #include "BufferParams.h"
43 #include "BufferView.h"
44 #include "CoordCache.h"
46 #include "CutAndPaste.h"
47 #include "DispatchResult.h"
49 #include "FuncRequest.h"
50 #include "FuncStatus.h"
53 #include "MetricsInfo.h"
54 #include "OutputParams.h"
57 #include "frontends/Application.h"
58 #include "frontends/Clipboard.h"
59 #include "frontends/Painter.h"
60 #include "frontends/Selection.h"
62 #include "support/debug.h"
63 #include "support/docstream.h"
64 #include "support/gettext.h"
65 #include "support/lassert.h"
66 #include "support/lstrings.h"
67 #include "support/textutils.h"
73 using namespace lyx::support;
77 using cap::copySelection;
78 using cap::grabAndEraseSelection;
79 using cap::cutSelection;
80 using cap::replaceSelection;
81 using cap::selClearOrDel;
84 InsetMathNest::InsetMathNest(Buffer * buf, idx_type nargs)
85 : InsetMath(buf), cells_(nargs), lock_(false)
91 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
92 : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_)
96 InsetMathNest::~InsetMathNest()
98 map<BufferView const *, bool>::iterator it = mouse_hover_.begin();
99 map<BufferView const *, bool>::iterator end = mouse_hover_.end();
100 for (; it != end; ++it)
102 it->first->clearLastInset(this);
106 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
108 cells_ = inset.cells_;
110 mouse_hover_.clear();
111 InsetMath::operator=(inset);
116 void InsetMathNest::setBuffer(Buffer & buffer)
118 InsetMath::setBuffer(buffer);
119 for (idx_type i = 0, n = nargs(); i != n; ++i) {
120 MathData & data = cell(i);
121 for (size_t j = 0; j != data.size(); ++j)
122 data[j].nucleus()->setBuffer(buffer);
127 InsetMath::idx_type InsetMathNest::nargs() const
129 return cells_.size();
133 void InsetMathNest::cursorPos(BufferView const & bv,
134 CursorSlice const & sl, bool /*boundary*/,
135 int & x, int & y) const
137 // FIXME: This is a hack. Ideally, the coord cache should not store
138 // absolute positions, but relative ones. This would mean to call
139 // setXY() not in MathData::draw(), but in the parent insets' draw()
140 // with the correctly adjusted x,y values. But this means that we'd have
141 // to touch all (math)inset's draw() methods. Right now, we'll store
142 // absolute value, and make them here relative, only to make them
143 // absolute again when actually drawing the cursor. What a mess.
144 LASSERT(&sl.inset() == this, return);
145 MathData const & ar = sl.cell();
146 CoordCache const & coord_cache = bv.coordCache();
147 if (!coord_cache.getArrays().has(&ar)) {
148 // this can (semi-)legally happen if we just created this cell
149 // and it never has been drawn before. So don't ASSERT.
150 //lyxerr << "no cached data for array " << &ar << endl;
155 Point const pt = coord_cache.getArrays().xy(&ar);
156 if (!coord_cache.getInsets().has(this)) {
158 //lyxerr << "no cached data for inset " << this << endl;
163 Point const pt2 = coord_cache.getInsets().xy(this);
164 //lyxerr << "retrieving position cache for MathData "
165 // << pt.x_ << ' ' << pt.y_ << endl;
166 x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
168 // lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
169 // << " asc: " << ascent() << " des: " << descent()
170 // << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
171 // move cursor visually into empty cells ("blue rectangles");
177 void InsetMathNest::metrics(MetricsInfo const & mi) const
180 for (idx_type i = 0, n = nargs(); i != n; ++i) {
182 cell(i).metrics(m, dim);
187 void InsetMathNest::updateBuffer(ParIterator const & it, UpdateType utype)
189 for (idx_type i = 0, n = nargs(); i != n; ++i)
190 cell(i).updateBuffer(it, utype);
195 bool InsetMathNest::idxNext(Cursor & cur) const
197 LASSERT(&cur.inset() == this, return false);
198 if (cur.idx() == cur.lastidx())
206 bool InsetMathNest::idxForward(Cursor & cur) const
212 bool InsetMathNest::idxPrev(Cursor & cur) const
214 LASSERT(&cur.inset() == this, return false);
218 cur.pos() = cur.lastpos();
223 bool InsetMathNest::idxBackward(Cursor & cur) const
229 bool InsetMathNest::idxFirst(Cursor & cur) const
231 LASSERT(&cur.inset() == this, return false);
240 bool InsetMathNest::idxLast(Cursor & cur) const
242 LASSERT(&cur.inset() == this, return false);
245 cur.idx() = cur.lastidx();
246 cur.pos() = cur.lastpos();
251 void InsetMathNest::dump() const
253 odocstringstream oss;
254 TexRow texrow(false);
255 otexrowstream ots(oss,texrow);
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 & pi, int x, int y) const
271 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
274 setPosCache(pi, x, y);
278 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
280 BufferView & bv = *pi.base.bv;
281 // this should use the x/y values given, not the cached values
282 Cursor & cur = bv.cursor();
283 if (!cur.selection())
285 if (&cur.inset() != this)
288 // FIXME: hack to get position cache warm
289 bool const original_drawing_state = pi.pain.isDrawingEnabled();
290 pi.pain.setDrawingEnabled(false);
292 pi.pain.setDrawingEnabled(original_drawing_state);
294 CursorSlice s1 = cur.selBegin();
295 CursorSlice s2 = cur.selEnd();
297 //lyxerr << "InsetMathNest::drawing selection: "
298 // << " s1: " << s1 << " s2: " << s2 << endl;
299 if (s1.idx() == s2.idx()) {
300 MathData const & c = cell(s1.idx());
301 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
302 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
303 int y1 = g.pos.y_ - g.dim.ascent();
304 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
305 int y2 = g.pos.y_ + g.dim.descent();
306 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
307 //lyxerr << "InsetMathNest::drawing selection 3: "
308 // << " x1: " << x1 << " x2: " << x2
309 // << " y1: " << y1 << " y2: " << y2 << endl;
311 for (idx_type i = 0; i < nargs(); ++i) {
312 if (idxBetween(i, s1.idx(), s2.idx())) {
313 MathData const & c = cell(i);
314 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
316 int y1 = g.pos.y_ - g.dim.ascent();
317 int x2 = g.pos.x_ + g.dim.width();
318 int y2 = g.pos.y_ + g.dim.descent();
319 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
326 void InsetMathNest::validate(LaTeXFeatures & features) const
328 for (idx_type i = 0; i < nargs(); ++i)
329 cell(i).validate(features);
333 void InsetMathNest::replace(ReplaceData & rep)
335 for (idx_type i = 0; i < nargs(); ++i)
336 cell(i).replace(rep);
340 bool InsetMathNest::contains(MathData const & ar) const
342 for (idx_type i = 0; i < nargs(); ++i)
343 if (cell(i).contains(ar))
349 bool InsetMathNest::lock() const
355 void InsetMathNest::lock(bool l)
361 bool InsetMathNest::isActive() const
367 MathData InsetMathNest::glue() const
370 for (size_t i = 0; i < nargs(); ++i)
376 void InsetMathNest::write(WriteStream & os) const
378 MathEnsurer ensurer(os, currentMode() == MATH_MODE);
379 ModeSpecifier specifier(os, currentMode(), lockedMode());
380 docstring const latex_name = name();
381 os << '\\' << latex_name;
382 for (size_t i = 0; i < nargs(); ++i) {
383 Changer dummy = os.changeRowEntry(TexRow::mathEntry(id(),i));
384 os << '{' << cell(i) << '}';
387 os.pendingSpace(true);
388 if (lock_ && !os.latex()) {
390 os.pendingSpace(true);
395 void InsetMathNest::normalize(NormalStream & os) const
398 for (size_t i = 0; i < nargs(); ++i)
399 os << ' ' << cell(i);
404 void InsetMathNest::latex(otexstream & os, OutputParams const & runparams) const
406 WriteStream wi(os, runparams.moving_arg, true,
407 runparams.dryrun ? WriteStream::wsDryrun : WriteStream::wsDefault,
409 wi.canBreakLine(os.canBreakLine());
410 Changer dummy = wi.changeRowEntry(os.texrow().textEntry(runparams.lastid,
413 // Reset parbreak status after a math inset.
415 os.canBreakLine(wi.canBreakLine());
419 bool InsetMathNest::setMouseHover(BufferView const * bv, bool mouse_hover)
422 mouse_hover_[bv] = mouse_hover;
427 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
431 MathData & ar = cur.cell();
432 // remove base-only "scripts"
433 for (pos_type i = 0; i + 1 < ar.size(); ++i) {
434 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
435 if (p && p->nargs() == 1) {
436 MathData ar = p->nuc();
439 cur.adjust(i, ar.size() - 1);
443 // glue adjacent font insets of the same kind
444 for (pos_type i = 0; i + 1 < size(); ++i) {
445 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
446 InsetMathFont const * q = operator[](i + 1)->asFontInset();
447 if (p && q && p->name() == q->name()) {
448 p->cell(0).append(q->cell(0));
458 void InsetMathNest::handleFont
459 (Cursor & cur, docstring const & arg, char const * const font)
461 handleFont(cur, arg, from_ascii(font));
465 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
466 docstring const & font)
468 cur.recordUndoSelection();
470 // this whole function is a hack and won't work for incremental font
472 if (cur.inset().asInsetMath()->name() == font)
473 cur.handleFont(to_utf8(font));
475 handleNest(cur, createInsetMath(font, cur.buffer()), arg);
479 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
481 handleNest(cur, nest, docstring());
485 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
486 docstring const & arg)
488 CursorSlice i1 = cur.selBegin();
489 CursorSlice i2 = cur.selEnd();
490 if (!i1.inset().asInsetMath())
492 if (i1.idx() == i2.idx()) {
493 // the easy case where only one cell is selected
494 cur.handleNest(nest);
499 // multiple selected cells in a simple non-grid inset
500 if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
501 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
506 cur.pos() = cur.lastpos();
509 // change font of cell
510 cur.handleNest(nest);
513 // cur is in the font inset now. If the loop continues,
514 // we need to get outside again for the next cell
515 if (i + 1 <= i2.idx())
521 // the complicated case with multiple selected cells in a grid
524 cap::region(i1, i2, r1, r2, c1, c2);
525 for (row_type row = r1; row <= r2; ++row) {
526 for (col_type col = c1; col <= c2; ++col) {
528 cur.idx() = i1.asInsetMath()->index(row, col);
531 cur.pos() = cur.lastpos();
535 cur.handleNest(nest);
538 // cur is in the font inset now. If the loop continues,
539 // we need to get outside again for the next cell
540 if (col + 1 <= c2 || row + 1 <= r2)
547 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
549 cur.recordUndoSelection();
552 font.fromString(to_utf8(arg), b);
553 if (font.fontInfo().color() != Color_inherit &&
554 font.fontInfo().color() != Color_ignore)
555 handleNest(cur, MathAtom(new InsetMathColor(buffer_, true, font.fontInfo().color())));
557 // FIXME: support other font changes here as well?
561 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
563 //LYXERR0("InsetMathNest: request: " << cmd);
565 Parse::flags parseflg = Parse::QUIET | Parse::USETEXT;
567 FuncCode const act = cmd.action();
570 case LFUN_CLIPBOARD_PASTE:
571 parseflg |= Parse::VERBATIM;
574 if (cur.currentMode() <= TEXT_MODE)
575 parseflg |= Parse::TEXTMODE;
576 cur.recordUndoSelection();
577 cur.message(_("Paste"));
578 replaceSelection(cur);
580 if (cmd.argument().empty() && !theClipboard().isInternal())
581 topaste = theClipboard().getAsText(frontend::Clipboard::PlainTextType);
584 idocstringstream is(cmd.argument());
586 topaste = cap::selection(n, buffer().params().documentClassPtr());
588 cur.niceInsert(topaste, parseflg, false);
589 cur.clearSelection(); // bug 393
590 cur.forceBufferUpdate();
597 cutSelection(cur, true, true);
598 cur.message(_("Cut"));
599 // Prevent stale position >= size crash
600 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
602 cur.forceBufferUpdate();
607 cur.message(_("Copy"));
610 case LFUN_MOUSE_PRESS:
611 lfunMousePress(cur, cmd);
614 case LFUN_MOUSE_MOTION:
615 lfunMouseMotion(cur, cmd);
618 case LFUN_MOUSE_RELEASE:
619 lfunMouseRelease(cur, cmd);
622 case LFUN_FINISHED_LEFT: // in math, left is backwards
623 case LFUN_FINISHED_BACKWARD:
624 cur.bv().cursor() = cur;
627 case LFUN_FINISHED_RIGHT: // in math, right is forward
628 case LFUN_FINISHED_FORWARD:
630 cur.bv().cursor() = cur;
633 case LFUN_CHAR_RIGHT:
635 case LFUN_CHAR_BACKWARD:
636 case LFUN_CHAR_FORWARD:
637 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
639 case LFUN_CHAR_RIGHT_SELECT:
640 case LFUN_CHAR_LEFT_SELECT:
641 case LFUN_CHAR_BACKWARD_SELECT:
642 case LFUN_CHAR_FORWARD_SELECT: {
643 // are we in a selection?
644 bool select = (act == LFUN_CHAR_RIGHT_SELECT
645 || act == LFUN_CHAR_LEFT_SELECT
646 || act == LFUN_CHAR_BACKWARD_SELECT
647 || act == LFUN_CHAR_FORWARD_SELECT);
648 // are we moving forward or backwards?
649 // If the command was RIGHT or LEFT, then whether we're moving forward
650 // or backwards depends on the cursor movement mode (logical or visual):
651 // * in visual mode, since math is always LTR, right -> forward,
653 // * in logical mode, the mapping is determined by the
654 // reverseDirectionNeeded() function
657 FuncCode finish_lfun;
659 if (act == LFUN_CHAR_FORWARD
660 || act == LFUN_CHAR_FORWARD_SELECT) {
662 finish_lfun = LFUN_FINISHED_FORWARD;
664 else if (act == LFUN_CHAR_BACKWARD
665 || act == LFUN_CHAR_BACKWARD_SELECT) {
667 finish_lfun = LFUN_FINISHED_BACKWARD;
670 bool right = (act == LFUN_CHAR_RIGHT_SELECT
671 || act == LFUN_CHAR_RIGHT);
672 if (lyxrc.visual_cursor || !cur.reverseDirectionNeeded())
678 finish_lfun = LFUN_FINISHED_RIGHT;
680 finish_lfun = LFUN_FINISHED_LEFT;
682 // Now that we know exactly what we want to do, let's do it!
683 cur.selHandle(select);
685 cur.macroModeClose();
686 // try moving forward or backwards as necessary...
687 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
688 // ... and if movement failed, then finish forward or backwards
690 cmd = FuncRequest(finish_lfun);
698 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
700 case LFUN_DOWN_SELECT:
701 case LFUN_UP_SELECT: {
702 // close active macro
703 if (cur.inMacroMode()) {
704 cur.macroModeClose();
708 // stop/start the selection
709 bool select = act == LFUN_DOWN_SELECT ||
710 act == LFUN_UP_SELECT;
711 cur.selHandle(select);
713 // handle autocorrect:
714 if (lyxrc.autocorrection_math && cur.autocorrect()) {
715 cur.autocorrect() = false;
716 cur.message(_("Autocorrect Off ('!' to enter)"));
720 bool up = act == LFUN_UP || act == LFUN_UP_SELECT;
721 bool successful = cur.upDownInMath(up);
725 if (cur.fixIfBroken())
726 // FIXME: Something bad happened. We pass the corrected Cursor
727 // instead of letting things go worse.
730 // We did not manage to move the cursor.
735 case LFUN_MOUSE_DOUBLE:
736 case LFUN_WORD_SELECT:
740 cur.pos() = cur.lastpos();
741 cur.bv().cursor() = cur;
744 case LFUN_MOUSE_TRIPLE:
749 cur.idx() = cur.lastidx();
750 cur.pos() = cur.lastpos();
751 cur.bv().cursor() = cur;
754 case LFUN_PARAGRAPH_UP:
755 case LFUN_PARAGRAPH_DOWN:
756 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
758 case LFUN_PARAGRAPH_UP_SELECT:
759 case LFUN_PARAGRAPH_DOWN_SELECT:
762 case LFUN_LINE_BEGIN:
763 case LFUN_WORD_BACKWARD:
765 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
767 case LFUN_LINE_BEGIN_SELECT:
768 case LFUN_WORD_BACKWARD_SELECT:
769 case LFUN_WORD_LEFT_SELECT:
770 cur.selHandle(act == LFUN_WORD_BACKWARD_SELECT ||
771 act == LFUN_WORD_LEFT_SELECT ||
772 act == LFUN_LINE_BEGIN_SELECT);
773 cur.macroModeClose();
774 if (cur.pos() != 0) {
776 } else if (cur.col() != 0) {
777 cur.idx() -= cur.col();
779 } else if (cur.idx() != 0) {
783 cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
788 case LFUN_WORD_FORWARD:
789 case LFUN_WORD_RIGHT:
791 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
793 case LFUN_WORD_FORWARD_SELECT:
794 case LFUN_WORD_RIGHT_SELECT:
795 case LFUN_LINE_END_SELECT:
796 cur.selHandle(act == LFUN_WORD_FORWARD_SELECT ||
797 act == LFUN_WORD_RIGHT_SELECT ||
798 act == LFUN_LINE_END_SELECT);
799 cur.macroModeClose();
801 if (cur.pos() != cur.lastpos()) {
802 cur.pos() = cur.lastpos();
803 } else if (ncols() && (cur.col() != cur.lastcol())) {
804 cur.idx() = cur.idx() - cur.col() + cur.lastcol();
805 cur.pos() = cur.lastpos();
806 } else if (cur.idx() != cur.lastidx()) {
807 cur.idx() = cur.lastidx();
808 cur.pos() = cur.lastpos();
810 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
815 case LFUN_CELL_FORWARD:
816 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
817 cur.inset().idxNext(cur);
820 case LFUN_CELL_BACKWARD:
821 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor);
822 cur.inset().idxPrev(cur);
825 case LFUN_WORD_DELETE_BACKWARD:
826 case LFUN_CHAR_DELETE_BACKWARD:
828 // May affect external cell:
829 cur.recordUndoInset();
830 else if (!cur.inMacroMode())
831 cur.recordUndoSelection();
832 // if the inset can not be removed from within, delete it
833 if (!cur.backspace()) {
834 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
835 cur.innerText()->dispatch(cur, cmd);
839 case LFUN_WORD_DELETE_FORWARD:
840 case LFUN_CHAR_DELETE_FORWARD:
841 if (cur.pos() == cur.lastpos())
842 // May affect external cell:
843 cur.recordUndoInset();
845 cur.recordUndoSelection();
846 // if the inset can not be removed from within, delete it
848 FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
849 cur.innerText()->dispatch(cur, cmd);
855 cur.clearSelection();
857 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
862 // 'Locks' the math inset. A 'locked' math inset behaves as a unit
863 // that is traversed by a single <CursorLeft>/<CursorRight>.
864 case LFUN_INSET_TOGGLE:
870 case LFUN_SELF_INSERT:
871 if (cmd.argument().size() != 1) {
872 cur.recordUndoSelection();
873 docstring const arg = cmd.argument();
874 if (!interpretString(cur, arg))
878 // Don't record undo steps if we are in macro mode and thus
879 // cmd.argument is the next character of the macro name.
880 // Otherwise we'll get an invalid cursor if we undo after
881 // the macro was finished and the macro is a known command,
882 // e.g. sqrt. Cursor::macroModeClose replaces in this case
883 // the InsetMathUnknown with name "frac" by an empty
884 // InsetMathFrac -> a pos value > 0 is invalid.
885 // A side effect is that an undo before the macro is finished
886 // undoes the complete macro, not only the last character.
887 // At the time we hit '\' we are not in macro mode, still.
888 if (!cur.inMacroMode())
889 cur.recordUndoSelection();
891 // spacial handling of space. If we insert an inset
892 // via macro mode, we want to put the cursor inside it
893 // if relevant. Think typing "\frac<space>".
894 if (cmd.argument()[0] == ' '
895 && cur.inMacroMode() && cur.macroName() != "\\"
896 && cur.macroModeClose() && cur.pos() > 0) {
897 MathAtom const atom = cur.prevAtom();
898 if (atom->asNestInset() && atom->isActive()) {
900 cur.pushBackward(*cur.nextInset());
902 } else if (!interpretChar(cur, cmd.argument()[0])) {
903 cmd = FuncRequest(LFUN_FINISHED_FORWARD);
908 //case LFUN_SERVER_GET_XY:
911 case LFUN_SERVER_SET_XY: {
912 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
915 istringstream is(to_utf8(cmd.argument()));
917 cur.setScreenPos(x, y);
921 // Special casing for superscript in case of LyX handling
923 case LFUN_ACCENT_CIRCUMFLEX:
924 if (cmd.argument().empty()) {
925 // do superscript if LyX handles
927 cur.recordUndoSelection();
928 script(cur, true, grabAndEraseSelection(cur));
932 case LFUN_ACCENT_UMLAUT:
933 case LFUN_ACCENT_ACUTE:
934 case LFUN_ACCENT_GRAVE:
935 case LFUN_ACCENT_BREVE:
936 case LFUN_ACCENT_DOT:
937 case LFUN_ACCENT_MACRON:
938 case LFUN_ACCENT_CARON:
939 case LFUN_ACCENT_TILDE:
940 case LFUN_ACCENT_CEDILLA:
941 case LFUN_ACCENT_CIRCLE:
942 case LFUN_ACCENT_UNDERDOT:
943 case LFUN_ACCENT_TIE:
944 case LFUN_ACCENT_OGONEK:
945 case LFUN_ACCENT_HUNGARIAN_UMLAUT:
949 case LFUN_TEXTSTYLE_APPLY:
950 case LFUN_TEXTSTYLE_UPDATE:
951 handleFont2(cur, cmd.argument());
955 if (currentMode() <= TEXT_MODE)
956 handleFont(cur, cmd.argument(), "textbf");
958 handleFont(cur, cmd.argument(), "mathbf");
960 case LFUN_FONT_BOLDSYMBOL:
961 if (currentMode() <= TEXT_MODE)
962 handleFont(cur, cmd.argument(), "textbf");
964 handleFont(cur, cmd.argument(), "boldsymbol");
967 if (currentMode() <= TEXT_MODE)
968 handleFont(cur, cmd.argument(), "textsf");
970 handleFont(cur, cmd.argument(), "mathsf");
973 if (currentMode() <= TEXT_MODE)
974 handleFont(cur, cmd.argument(), "emph");
976 handleFont(cur, cmd.argument(), "mathcal");
978 case LFUN_FONT_ROMAN:
979 if (currentMode() <= TEXT_MODE)
980 handleFont(cur, cmd.argument(), "textrm");
982 handleFont(cur, cmd.argument(), "mathrm");
984 case LFUN_FONT_TYPEWRITER:
985 if (currentMode() <= TEXT_MODE)
986 handleFont(cur, cmd.argument(), "texttt");
988 handleFont(cur, cmd.argument(), "mathtt");
991 handleFont(cur, cmd.argument(), "mathfrak");
994 if (currentMode() <= TEXT_MODE)
995 handleFont(cur, cmd.argument(), "textit");
997 handleFont(cur, cmd.argument(), "mathit");
1000 if (currentMode() <= TEXT_MODE)
1001 // FIXME: should be "noun"
1002 handleFont(cur, cmd.argument(), "textsc");
1004 handleFont(cur, cmd.argument(), "mathbb");
1006 case LFUN_FONT_DEFAULT:
1007 handleFont(cur, cmd.argument(), "textnormal");
1009 case LFUN_FONT_UNDERLINE:
1011 cur.handleNest(createInsetMath("underline", cur.buffer()));
1014 case LFUN_MATH_MODE: {
1016 // ignore math-mode on when already in math mode
1017 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
1019 cur.recordUndoSelection();
1020 cur.macroModeClose();
1021 docstring const save_selection = grabAndEraseSelection(cur);
1023 if (currentMode() <= Inset::TEXT_MODE)
1024 cur.plainInsert(MathAtom(new InsetMathEnsureMath(buffer_)));
1026 cur.plainInsert(createInsetMath("text", buffer_));
1028 cur.pushBackward(*cur.nextInset());
1029 cur.niceInsert(save_selection);
1030 cur.forceBufferUpdate();
1032 if (currentMode() == Inset::TEXT_MODE) {
1033 cur.recordUndoSelection();
1034 cur.niceInsert(MathAtom(new InsetMathHull("simple", cur.buffer())));
1035 cur.message(_("create new math text environment ($...$)"));
1037 handleFont(cur, cmd.argument(), "textrm");
1038 cur.message(_("entered math text mode (textrm)"));
1044 case LFUN_REGEXP_MODE: {
1045 InsetMath * im = cur.inset().asInsetMath();
1047 InsetMathHull * i = im->asHullInset();
1048 if (i && i->getType() == hullRegexp) {
1049 cur.message(_("Already in regular expression mode"));
1053 cur.macroModeClose();
1054 docstring const save_selection = grabAndEraseSelection(cur);
1056 cur.plainInsert(MathAtom(new InsetMathHull(buffer_, hullRegexp)));
1058 cur.pushBackward(*cur.nextInset());
1059 cur.niceInsert(save_selection);
1060 cur.message(_("Regular expression editor mode"));
1064 case LFUN_MATH_FONT_STYLE: {
1065 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, '\\' + cmd.argument());
1066 doDispatch(cur, fr);
1070 case LFUN_MATH_SIZE: {
1071 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
1072 doDispatch(cur, fr);
1076 case LFUN_MATH_MATRIX: {
1082 idocstringstream is(cmd.argument());
1083 is >> m >> n >> v_align >> h_align;
1089 cur.niceInsert(MathAtom(new InsetMathArray(buffer_,
1090 from_ascii("array"), m, n, (char)v_align[0], h_align)));
1094 case LFUN_MATH_AMS_MATRIX: {
1098 docstring name = from_ascii("matrix");
1099 idocstringstream is(cmd.argument());
1100 is >> m >> n >> name;
1105 // check if we have a valid decoration
1106 if (name != "pmatrix" && name != "bmatrix"
1107 && name != "Bmatrix" && name != "vmatrix"
1108 && name != "Vmatrix" && name != "matrix")
1109 name = from_ascii("matrix");
1112 MathAtom(new InsetMathAMSArray(buffer_, name, m, n)));
1116 case LFUN_MATH_DELIM: {
1118 docstring rs = split(cmd.argument(), ls, ' ');
1119 // Reasonable default values
1125 cur.handleNest(MathAtom(new InsetMathDelim(buffer_, ls, rs)));
1129 case LFUN_MATH_BIGDELIM: {
1130 docstring const lname = from_utf8(cmd.getArg(0));
1131 docstring const ldelim = from_utf8(cmd.getArg(1));
1132 docstring const rname = from_utf8(cmd.getArg(2));
1133 docstring const rdelim = from_utf8(cmd.getArg(3));
1134 latexkeys const * l = in_word_set(lname);
1135 bool const have_l = l && l->inset == "big" &&
1136 InsetMathBig::isBigInsetDelim(ldelim);
1137 l = in_word_set(rname);
1138 bool const have_r = l && l->inset == "big" &&
1139 InsetMathBig::isBigInsetDelim(rdelim);
1140 // We mimic LFUN_MATH_DELIM in case we have an empty left
1141 // or right delimiter.
1142 if (have_l || have_r) {
1144 docstring const selection = grabAndEraseSelection(cur);
1147 cur.insert(MathAtom(new InsetMathBig(lname,
1149 // first insert the right delimiter and then go back
1150 // and re-insert the selection (bug 7088)
1152 cur.insert(MathAtom(new InsetMathBig(rname,
1156 cur.niceInsert(selection);
1158 // Don't call cur.undispatched() if we did nothing, this would
1159 // lead to infinite recursion via Text::dispatch().
1163 case LFUN_SPACE_INSERT: {
1164 cur.recordUndoSelection();
1165 string const name = cmd.getArg(0);
1166 if (name == "normal")
1167 cur.insert(MathAtom(new InsetMathSpace(" ", "")));
1168 else if (name == "protected")
1169 cur.insert(MathAtom(new InsetMathSpace("~", "")));
1170 else if (name == "thin" || name == "med" || name == "thick")
1171 cur.insert(MathAtom(new InsetMathSpace(name + "space", "")));
1172 else if (name == "hfill*")
1173 cur.insert(MathAtom(new InsetMathSpace("hspace*{\\fill}", "")));
1174 else if (name == "quad" || name == "qquad" ||
1175 name == "enspace" || name == "enskip" ||
1176 name == "negthinspace" || name == "negmedspace" ||
1177 name == "negthickspace" || name == "hfill")
1178 cur.insert(MathAtom(new InsetMathSpace(name, "")));
1179 else if (name == "hspace" || name == "hspace*") {
1180 string const len = cmd.getArg(1);
1181 if (len.empty() || !isValidLength(len)) {
1182 lyxerr << "LyX function 'space-insert " << name << "' "
1183 "needs a valid length argument." << endl;
1186 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1188 cur.insert(MathAtom(new InsetMathSpace));
1192 case LFUN_MATH_SPACE:
1193 cur.recordUndoSelection();
1194 if (cmd.argument().empty())
1195 cur.insert(MathAtom(new InsetMathSpace));
1197 string const name = cmd.getArg(0);
1198 string const len = cmd.getArg(1);
1199 cur.insert(MathAtom(new InsetMathSpace(name, len)));
1203 case LFUN_ERT_INSERT:
1204 // interpret this as if a backslash was typed
1206 interpretChar(cur, '\\');
1209 case LFUN_MATH_SUBSCRIPT:
1210 // interpret this as if a _ was typed
1211 cur.recordUndoSelection();
1212 interpretChar(cur, '_');
1215 case LFUN_MATH_SUPERSCRIPT:
1216 // interpret this as if a ^ was typed
1217 cur.recordUndoSelection();
1218 interpretChar(cur, '^');
1221 case LFUN_MATH_MACRO_FOLD:
1222 case LFUN_MATH_MACRO_UNFOLD: {
1224 bool fold = act == LFUN_MATH_MACRO_FOLD;
1225 bool found = findMacroToFoldUnfold(it, fold);
1227 MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1228 cur.recordUndoInset();
1237 case LFUN_QUOTE_INSERT:
1238 // interpret this as if a straight " was typed
1239 cur.recordUndoSelection();
1240 interpretChar(cur, '\"');
1243 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1244 // handling such that "self-insert" works on "arbitrary stuff" too, and
1245 // math-insert only handles special math things like "matrix".
1246 case LFUN_MATH_INSERT: {
1247 cur.recordUndoSelection();
1248 if (cmd.argument() == "^" || cmd.argument() == "_")
1249 interpretChar(cur, cmd.argument()[0]);
1252 asArray(cmd.argument(), ar);
1253 if (cur.selection() && ar.size() == 1
1254 && ar[0]->asNestInset()
1255 && ar[0]->asNestInset()->nargs() > 1)
1256 handleNest(cur, ar[0]);
1258 cur.niceInsert(cmd.argument());
1263 case LFUN_UNICODE_INSERT: {
1264 if (cmd.argument().empty())
1266 docstring hexstring = cmd.argument();
1267 if (isHex(hexstring)) {
1268 char_type c = hexToInt(hexstring);
1269 if (c >= 32 && c < 0x10ffff) {
1270 docstring s = docstring(1, c);
1271 FuncCode code = currentMode() == MATH_MODE ?
1272 LFUN_MATH_INSERT : LFUN_SELF_INSERT;
1273 lyx::dispatch(FuncRequest(code, s));
1279 case LFUN_DIALOG_SHOW_NEW_INSET: {
1280 docstring const & name = cmd.argument();
1282 if (name == "ref") {
1283 InsetMathRef tmp(buffer_, name);
1284 data = tmp.createDialogStr();
1285 cur.bv().showDialog(to_utf8(name), data);
1286 } else if (name == "mathspace") {
1287 cur.bv().showDialog(to_utf8(name));
1292 case LFUN_INSET_INSERT: {
1294 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1295 cur.recordUndoSelection();
1297 cur.forceBufferUpdate();
1302 case LFUN_INSET_DISSOLVE:
1303 if (!asHullInset()) {
1304 cur.recordUndoInset();
1310 InsetMath::doDispatch(cur, cmd);
1316 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1317 // look for macro to open/close, but stay in mathed
1318 for (; !it.empty(); it.pop_back()) {
1320 // go backward through the current cell
1321 Inset * inset = it.nextInset();
1322 while (inset && inset->asInsetMath()) {
1323 MathMacro * macro = inset->asInsetMath()->asMacro();
1325 // found the an macro to open/close?
1326 if (macro->folded() != fold)
1329 // Wrong folding state.
1330 // If this was the first we see in this slice, look further left,
1332 if (inset != it.nextInset())
1336 // go up if this was the left most position
1342 inset = it.nextInset();
1350 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1351 FuncStatus & flag) const
1353 // the font related toggles
1354 //string tc = "mathnormal";
1356 string const arg = to_utf8(cmd.argument());
1357 switch (cmd.action()) {
1358 case LFUN_INSET_MODIFY:
1359 flag.setEnabled(false);
1362 case LFUN_INSET_MODIFY:
1363 // FIXME: check temporarily disabled
1365 char align = mathcursor::valign();
1366 if (align == '\0') {
1370 if (cmd.argument().empty()) {
1374 if (!contains("tcb", cmd.argument()[0])) {
1378 flag.setOnOff(cmd.argument()[0] == align);
1381 /// We have to handle them since 1.4 blocks all unhandled actions
1382 case LFUN_FONT_ITAL:
1383 case LFUN_FONT_BOLD:
1384 case LFUN_FONT_BOLDSYMBOL:
1385 case LFUN_FONT_SANS:
1386 case LFUN_FONT_EMPH:
1387 case LFUN_FONT_TYPEWRITER:
1388 case LFUN_FONT_NOUN:
1389 case LFUN_FONT_ROMAN:
1390 case LFUN_FONT_DEFAULT:
1391 flag.setEnabled(true);
1394 // we just need to be in math mode to enable that
1395 case LFUN_MATH_SIZE:
1396 case LFUN_MATH_SPACE:
1397 case LFUN_MATH_EXTERN:
1398 flag.setEnabled(true);
1401 case LFUN_FONT_UNDERLINE:
1402 case LFUN_FONT_FRAK:
1403 flag.setEnabled(currentMode() != TEXT_MODE);
1406 case LFUN_MATH_FONT_STYLE: {
1407 bool const textarg =
1408 arg == "textbf" || arg == "textsf" ||
1409 arg == "textrm" || arg == "textmd" ||
1410 arg == "textit" || arg == "textsc" ||
1411 arg == "textsl" || arg == "textup" ||
1412 arg == "texttt" || arg == "textbb" ||
1413 arg == "textnormal";
1414 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1418 case LFUN_MATH_MODE:
1419 // forbid "math-mode on" in math mode to prevent irritating
1420 // behaviour of menu entries (bug 6709)
1421 flag.setEnabled(currentMode() == TEXT_MODE || arg != "on");
1424 case LFUN_MATH_INSERT:
1425 flag.setEnabled(currentMode() != TEXT_MODE);
1428 case LFUN_MATH_AMS_MATRIX:
1429 case LFUN_MATH_MATRIX:
1430 flag.setEnabled(currentMode() == MATH_MODE);
1433 case LFUN_INSET_INSERT: {
1434 // Don't test createMathInset_fromDialogStr(), since
1435 // getStatus is not called with a valid reference and the
1436 // dialog would not be applyable.
1437 string const name = cmd.getArg(0);
1438 flag.setEnabled(name == "ref" || name == "mathspace");
1442 case LFUN_DIALOG_SHOW_NEW_INSET: {
1443 docstring const & name = cmd.argument();
1444 if (name == "space")
1445 flag.setEnabled(false);
1450 case LFUN_MATH_DELIM:
1451 case LFUN_MATH_BIGDELIM:
1452 // Don't do this with multi-cell selections
1453 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1456 case LFUN_MATH_MACRO_FOLD:
1457 case LFUN_MATH_MACRO_UNFOLD: {
1459 bool found = findMacroToFoldUnfold(it, cmd.action() == LFUN_MATH_MACRO_FOLD);
1460 flag.setEnabled(found);
1464 case LFUN_SPECIALCHAR_INSERT:
1465 case LFUN_SCRIPT_INSERT:
1466 // FIXME: These would probably make sense in math-text mode
1467 flag.setEnabled(false);
1470 case LFUN_CAPTION_INSERT:
1471 flag.setEnabled(false);
1474 case LFUN_SPACE_INSERT: {
1475 docstring const & name = cmd.argument();
1476 if (name == "visible")
1477 flag.setEnabled(false);
1481 case LFUN_INSET_DISSOLVE:
1482 flag.setEnabled(!asHullInset());
1486 docstring const & name = cmd.argument();
1487 if (name == "html" || name == "latex")
1488 flag.setEnabled(false);
1500 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1503 bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1504 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1505 cur.idx() = enter_front ? 0 : cur.lastidx();
1506 cur.pos() = enter_front ? 0 : cur.lastpos();
1508 //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1512 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1515 int dist_min = 1000000;
1516 for (idx_type i = 0, n = nargs(); i != n; ++i) {
1517 int const d = cell(i).dist(cur.bv(), x, y);
1523 MathData & ar = cell(idx_min);
1525 cur.idx() = idx_min;
1526 cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1528 //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1529 if (dist_min == 0) {
1531 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1532 if (ar[i]->covers(cur.bv(), x, y))
1533 return ar[i].nucleus()->editXY(cur, x, y);
1539 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1541 //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1542 BufferView & bv = cur.bv();
1543 if (cmd.button() == mouse_button::button3) {
1544 // Don't do anything if we right-click a
1545 // selection, a context menu will popup.
1546 if (bv.cursor().selection() && cur >= bv.cursor().selectionBegin()
1547 && cur < bv.cursor().selectionEnd()) {
1548 cur.noScreenUpdate();
1552 bool do_selection = cmd.button() == mouse_button::button1
1553 && cmd.modifier() == ShiftModifier;
1554 bv.mouseSetCursor(cur, do_selection);
1555 if (cmd.button() == mouse_button::button1) {
1556 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1557 // Update the cursor update flags as needed:
1559 // Update::Decoration: tells to update the decoration
1560 // (visual box corners that define
1562 // Update::FitCursor: adjust the screen to the cursor
1563 // position if needed
1564 // cur.result().update(): don't overwrite previously set flags.
1565 cur.screenUpdateFlags(Update::Decoration | Update::FitCursor
1566 | cur.result().screenUpdate());
1567 } else if (cmd.button() == mouse_button::button2 && lyxrc.mouse_middlebutton_paste) {
1568 if (cap::selection()) {
1569 // See comment in Text::dispatch why we do this
1570 cap::copySelectionToStack();
1571 cmd = FuncRequest(LFUN_PASTE, "0");
1572 doDispatch(bv.cursor(), cmd);
1575 asArray(theSelection().get(), ar);
1576 bv.cursor().insert(ar);
1582 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1584 // only select with button 1
1585 if (cmd.button() != mouse_button::button1)
1588 Cursor & bvcur = cur.bv().cursor();
1590 // ignore motions deeper nested than the real anchor
1591 if (!bvcur.realAnchor().hasPart(cur)) {
1596 CursorSlice old = bvcur.top();
1598 // We continue with our existing selection or start a new one, so don't
1599 // reset the anchor.
1600 bvcur.setCursor(cur);
1601 // Did we actually move?
1602 if (cur.top() == old)
1603 // We didn't move one iota, so no need to change selection status
1604 // or update the screen.
1605 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1607 bvcur.setSelection();
1611 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1613 //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1615 if (cmd.button() == mouse_button::button1) {
1616 if (!cur.selection())
1617 cur.noScreenUpdate();
1619 Cursor & bvcur = cur.bv().cursor();
1620 bvcur.selection(true);
1629 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1631 //lyxerr << "interpret 2: '" << c << "'" << endl;
1632 docstring save_selection;
1633 if (c == '^' || c == '_')
1634 save_selection = grabAndEraseSelection(cur);
1637 Buffer * buf = cur.buffer();
1640 if (cur.inMacroMode()) {
1641 docstring name = cur.macroName();
1643 /// are we currently typing '#1' or '#2' or...?
1644 if (name == "\\#") {
1647 if (n >= 1 && n <= 9)
1648 cur.insert(new MathMacroArgument(n));
1652 // do not finish macro for known * commands
1653 bool star_macro = c == '*'
1654 && (in_word_set(name.substr(1) + '*')
1655 || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1656 if (isAlphaASCII(c) || star_macro) {
1657 cur.activeMacro()->setName(name + docstring(1, c));
1661 // handle 'special char' macros
1666 if (currentMode() <= InsetMath::TEXT_MODE)
1667 cur.niceInsert(createInsetMath("textbackslash", buf));
1669 cur.niceInsert(createInsetMath("backslash", buf));
1670 } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1672 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1673 } else if (c == '{' || c == '%') {
1674 //using the saved selection as argument
1675 InsetMathUnknown * p = cur.activeMacro();
1677 MathData sel(cur.buffer());
1678 asArray(p->selection(), sel);
1681 cur.niceInsert(MathAtom(new InsetMathBrace(sel)));
1683 cur.niceInsert(MathAtom(new InsetMathComment(sel)));
1684 } else if (c == '#') {
1685 LASSERT(cur.activeMacro(), return false);
1686 cur.activeMacro()->setName(name + docstring(1, c));
1689 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1694 // One character big delimiters. The others are handled in
1695 // interpretString().
1696 latexkeys const * l = in_word_set(name.substr(1));
1697 if (name[0] == '\\' && l && l->inset == "big") {
1701 delim = from_ascii("\\{");
1704 delim = from_ascii("\\}");
1707 delim = docstring(1, c);
1710 if (InsetMathBig::isBigInsetDelim(delim)) {
1711 // name + delim ared a valid InsetMathBig.
1712 // We can't use cur.macroModeClose() because
1713 // it does not handle delim.
1714 InsetMathUnknown * p = cur.activeMacro();
1717 cur.cell().erase(cur.pos());
1718 cur.plainInsert(MathAtom(
1719 new InsetMathBig(name.substr(1), delim)));
1722 } else if (name == "\\smash" && c == '[') {
1723 // We can't use cur.macroModeClose() because
1724 // it would create an InsetMathPhantom
1725 InsetMathUnknown * p = cur.activeMacro();
1727 interpretChar(cur, c);
1731 // leave macro mode and try again if necessary
1732 if (cur.macroModeClose()) {
1733 MathAtom const atom = cur.prevAtom();
1734 if (atom->asNestInset() && atom->isActive()) {
1736 cur.pushBackward(*cur.nextInset());
1740 cur.niceInsert(MathAtom(new InsetMathBrace(buf)));
1742 interpretChar(cur, c);
1747 // leave autocorrect mode if necessary
1748 if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1749 cur.autocorrect() = false;
1750 cur.message(_("Autocorrect Off ('!' to enter)"));
1753 if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1754 cur.autocorrect() = true;
1755 cur.message(_("Autocorrect On (<space> to exit)"));
1759 // just clear selection on pressing the space bar
1760 if (cur.selection() && c == ' ') {
1761 cur.selection(false);
1766 //lyxerr << "starting with macro" << endl;
1767 bool reduced = cap::reduceSelectionToOneCell(cur);
1768 if (reduced || !cur.selection()) {
1769 cur.recordUndoInset();
1770 docstring const safe = cap::grabAndEraseSelection(cur);
1771 if (!cur.inRegexped())
1772 cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1774 cur.niceInsert(createInsetMath("backslash", buf));
1782 if (currentMode() <= InsetMath::TEXT_MODE)
1788 if (currentMode() <= InsetMath::TEXT_MODE) {
1789 // insert spaces in text or undecided mode,
1790 // but suppress direct insertion of two spaces in a row
1791 // the still allows typing '<space>a<space>' and deleting the 'a', but
1792 // it is better than nothing...
1793 if (cur.pos() == 0 || cur.prevAtom()->getChar() != ' ') {
1795 // FIXME: we have to enable full redraw here because of the
1796 // visual box corners that define the inset. If we know for
1797 // sure that we stay within the same cell we can optimize for
1799 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1803 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1804 cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1805 // FIXME: we have to enable full redraw here because of the
1806 // visual box corners that define the inset. If we know for
1807 // sure that we stay within the same cell we can optimize for
1809 //cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1813 if (cur.popForward()) {
1814 // FIXME: we have to enable full redraw here because of the
1815 // visual box corners that define the inset. If we know for
1816 // sure that we stay within the same cell we can optimize for
1818 //cur.screenUpdateFlags(Update::FitCursor);
1822 // if we are at the very end, leave the formula
1823 return cur.pos() != cur.lastpos();
1826 // These should be treated differently when not in text mode:
1827 if (cur.inRegexped()) {
1830 cur.niceInsert(createInsetMath("mathcircumflex", buf));
1837 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1840 cur.niceInsert(createInsetMath("sim", buf));
1846 } else if (currentMode() != InsetMath::TEXT_MODE) {
1848 script(cur, false, save_selection);
1852 script(cur, true, save_selection);
1856 cur.niceInsert(createInsetMath("sim", buf));
1859 if (currentMode() == InsetMath::MATH_MODE && !isAsciiOrMathAlpha(c)) {
1860 MathAtom at = createInsetMath("text", buf);
1861 at.nucleus()->cell(0).push_back(MathAtom(new InsetMathChar(c)));
1868 cur.niceInsert(createInsetMath("textasciicircum", buf));
1872 cur.niceInsert(createInsetMath("textasciitilde", buf));
1877 if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1878 c == '%' || c == '_') {
1879 cur.niceInsert(createInsetMath(docstring(1, c), buf));
1884 // try auto-correction
1885 if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0
1886 && math_autocorrect(cur.prevAtom(), c))
1889 // no special circumstances, so insert the character without any fuss
1891 if (lyxrc.autocorrection_math) {
1892 if (!cur.autocorrect())
1893 cur.message(_("Autocorrect Off ('!' to enter)"));
1895 cur.message(_("Autocorrect On (<space> to exit)"));
1901 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1903 // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1905 if (!cur.empty() && cur.pos() > 0 &&
1906 cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1907 if (InsetMathBig::isBigInsetDelim(str)) {
1908 docstring prev = asString(cur.cell()[cur.pos() - 1]);
1909 if (prev[0] == '\\') {
1910 prev = prev.substr(1);
1911 latexkeys const * l = in_word_set(prev);
1912 if (l && l->inset == "big") {
1913 cur.cell()[cur.pos() - 1] =
1914 MathAtom(new InsetMathBig(prev, str));
1924 bool InsetMathNest::script(Cursor & cur, bool up)
1926 return script(cur, up, docstring());
1930 bool InsetMathNest::script(Cursor & cur, bool up,
1931 docstring const & save_selection)
1933 // Hack to get \^ and \_ working
1934 //lyxerr << "handling script: up: " << up << endl;
1935 if (cur.inMacroMode() && cur.macroName() == "\\") {
1937 cur.niceInsert(createInsetMath("mathcircumflex", cur.buffer()));
1939 interpretChar(cur, '_');
1943 cur.macroModeClose();
1944 if (asScriptInset() && cur.idx() == 0) {
1945 // we are in a nucleus of a script inset, move to _our_ script
1946 InsetMathScript * inset = asScriptInset();
1947 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1949 cur.idx() = inset->idxOfScript(up);
1951 } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1953 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1956 cur.idx() = inset->idxOfScript(up);
1957 cur.pos() = cur.lastpos();
1959 // convert the thing to our left to a scriptinset or create a new
1960 // one if in the very first position of the array
1961 if (cur.pos() == 0) {
1962 //lyxerr << "new scriptinset" << endl;
1963 cur.insert(new InsetMathScript(buffer_, up));
1965 //lyxerr << "converting prev atom " << endl;
1966 cur.prevAtom() = MathAtom(new InsetMathScript(buffer_, cur.prevAtom(), up));
1969 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1970 // See comment in MathParser.cpp for special handling of {}-bases
1976 //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1977 cur.niceInsert(save_selection);
1979 //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1984 bool InsetMathNest::completionSupported(Cursor const & cur) const
1986 return cur.inMacroMode();
1990 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1992 return cur.inMacroMode();
1996 bool InsetMathNest::automaticInlineCompletion() const
1998 return lyxrc.completion_inline_math;
2002 bool InsetMathNest::automaticPopupCompletion() const
2004 return lyxrc.completion_popup_math;
2008 CompletionList const *
2009 InsetMathNest::createCompletionList(Cursor const & cur) const
2011 if (!cur.inMacroMode())
2014 return new MathCompletionList(cur);
2018 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
2020 if (!cur.inMacroMode())
2023 return cur.activeMacro()->name();
2027 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
2030 if (!cur.inMacroMode())
2033 // append completion to active macro
2034 InsetMathUnknown * inset = cur.activeMacro();
2035 inset->setName(inset->name() + s);
2040 // FIXME: this creates duplicates in the completion popup
2041 // which looks ugly. Moreover the changes the list lengths
2043 confuse the popup as well.
2044 MathCompletionList::addToFavorites(inset->name());
2046 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
2053 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
2054 Dimension & dim) const
2056 Inset const * inset = cur.activeMacro();
2060 // get inset dimensions
2061 dim = cur.bv().coordCache().insets().dim(inset);
2062 // FIXME: these 3 are no accurate, but should depend on the font.
2063 // Now the popup jumps down if you enter a char with descent > 0.
2068 Point xy = cur.bv().coordCache().insets().xy(inset);
2074 bool InsetMathNest::cursorMathForward(Cursor & cur)
2076 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
2077 cur.pushBackward(*cur.nextAtom().nucleus());
2078 cur.inset().idxFirst(cur);
2081 if (cur.posForward() || idxForward(cur))
2083 // try to pop forwards --- but don't pop out of math! leave that to
2085 int s = cur.depth() - 2;
2086 if (s >= 0 && cur[s].inset().asInsetMath())
2087 return cur.popForward();
2092 bool InsetMathNest::cursorMathBackward(Cursor & cur)
2094 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
2096 cur.push(*cur.nextAtom().nucleus());
2097 cur.inset().idxLast(cur);
2100 if (cur.posBackward() || idxBackward(cur))
2102 // try to pop backwards --- but don't pop out of math! leave that to
2104 int s = cur.depth() - 2;
2105 if (s >= 0 && cur[s].inset().asInsetMath())
2106 return cur.popBackward();
2111 ////////////////////////////////////////////////////////////////////
2113 MathCompletionList::MathCompletionList(Cursor const & cur)
2115 // fill it with macros from the buffer
2116 MacroNameSet macros;
2117 cur.buffer()->listMacroNames(macros);
2118 MacroNameSet::const_iterator it;
2119 for (it = macros.begin(); it != macros.end(); ++it) {
2120 if (cur.buffer()->getMacro(*it, cur, false))
2121 locals.push_back("\\" + *it);
2123 sort(locals.begin(), locals.end());
2125 if (!globals.empty())
2128 // fill in global macros
2130 MacroTable::globalMacros().getMacroNames(macros, false);
2131 //lyxerr << "Globals completion macros: ";
2132 for (it = macros.begin(); it != macros.end(); ++it) {
2133 //lyxerr << "\\" + *it << " ";
2134 globals.push_back("\\" + *it);
2136 //lyxerr << std::endl;
2138 // fill in global commands
2139 globals.push_back(from_ascii("\\boxed"));
2140 globals.push_back(from_ascii("\\fbox"));
2141 globals.push_back(from_ascii("\\framebox"));
2142 globals.push_back(from_ascii("\\makebox"));
2143 globals.push_back(from_ascii("\\kern"));
2144 globals.push_back(from_ascii("\\xhookrightarrow"));
2145 globals.push_back(from_ascii("\\xhookleftarrow"));
2146 globals.push_back(from_ascii("\\xrightarrow"));
2147 globals.push_back(from_ascii("\\xRightarrow"));
2148 globals.push_back(from_ascii("\\xrightharpoondown"));
2149 globals.push_back(from_ascii("\\xrightharpoonup"));
2150 globals.push_back(from_ascii("\\xrightleftharpoons"));
2151 globals.push_back(from_ascii("\\xleftarrow"));
2152 globals.push_back(from_ascii("\\xLeftarrow"));
2153 globals.push_back(from_ascii("\\xleftharpoondown"));
2154 globals.push_back(from_ascii("\\xleftharpoonup"));
2155 globals.push_back(from_ascii("\\xleftrightarrow"));
2156 globals.push_back(from_ascii("\\xLeftrightarrow"));
2157 globals.push_back(from_ascii("\\xleftrightharpoons"));
2158 globals.push_back(from_ascii("\\xmapsto"));
2159 globals.push_back(from_ascii("\\split"));
2160 globals.push_back(from_ascii("\\gathered"));
2161 globals.push_back(from_ascii("\\aligned"));
2162 globals.push_back(from_ascii("\\alignedat"));
2163 globals.push_back(from_ascii("\\cases"));
2164 globals.push_back(from_ascii("\\substack"));
2165 globals.push_back(from_ascii("\\xymatrix"));
2166 globals.push_back(from_ascii("\\Diagram"));
2167 globals.push_back(from_ascii("\\subarray"));
2168 globals.push_back(from_ascii("\\array"));
2169 globals.push_back(from_ascii("\\sqrt"));
2170 globals.push_back(from_ascii("\\root"));
2171 globals.push_back(from_ascii("\\tabular"));
2172 globals.push_back(from_ascii("\\sideset"));
2173 globals.push_back(from_ascii("\\stackrel"));
2174 globals.push_back(from_ascii("\\stackrelthree"));
2175 globals.push_back(from_ascii("\\binom"));
2176 globals.push_back(from_ascii("\\choose"));
2177 globals.push_back(from_ascii("\\brace"));
2178 globals.push_back(from_ascii("\\brack"));
2179 globals.push_back(from_ascii("\\frac"));
2180 globals.push_back(from_ascii("\\over"));
2181 globals.push_back(from_ascii("\\nicefrac"));
2182 globals.push_back(from_ascii("\\unitfrac"));
2183 globals.push_back(from_ascii("\\unitfracthree"));
2184 globals.push_back(from_ascii("\\unitone"));
2185 globals.push_back(from_ascii("\\unittwo"));
2186 globals.push_back(from_ascii("\\infer"));
2187 globals.push_back(from_ascii("\\atop"));
2188 globals.push_back(from_ascii("\\lefteqn"));
2189 globals.push_back(from_ascii("\\boldsymbol"));
2190 globals.push_back(from_ascii("\\bm"));
2191 globals.push_back(from_ascii("\\color"));
2192 globals.push_back(from_ascii("\\normalcolor"));
2193 globals.push_back(from_ascii("\\textcolor"));
2194 globals.push_back(from_ascii("\\cfrac"));
2195 globals.push_back(from_ascii("\\cfracleft"));
2196 globals.push_back(from_ascii("\\cfracright"));
2197 globals.push_back(from_ascii("\\dfrac"));
2198 globals.push_back(from_ascii("\\tfrac"));
2199 globals.push_back(from_ascii("\\dbinom"));
2200 globals.push_back(from_ascii("\\tbinom"));
2201 globals.push_back(from_ascii("\\hphantom"));
2202 globals.push_back(from_ascii("\\phantom"));
2203 globals.push_back(from_ascii("\\vphantom"));
2204 globals.push_back(from_ascii("\\cancel"));
2205 globals.push_back(from_ascii("\\bcancel"));
2206 globals.push_back(from_ascii("\\xcancel"));
2207 globals.push_back(from_ascii("\\cancelto"));
2208 globals.push_back(from_ascii("\\smash"));
2209 globals.push_back(from_ascii("\\mathclap"));
2210 globals.push_back(from_ascii("\\mathllap"));
2211 globals.push_back(from_ascii("\\mathrlap"));
2212 globals.push_back(from_ascii("\\ensuremath"));
2213 MathWordList const & words = mathedWordList();
2214 MathWordList::const_iterator it2;
2215 //lyxerr << "Globals completion commands: ";
2216 for (it2 = words.begin(); it2 != words.end(); ++it2) {
2217 if (it2->second.inset != "macro" && !it2->second.hidden) {
2218 // macros are already read from MacroTable::globalMacros()
2219 globals.push_back('\\' + it2->first);
2220 //lyxerr << '\\' + it2->first << ' ';
2223 //lyxerr << std::endl;
2224 sort(globals.begin(), globals.end());
2228 MathCompletionList::~MathCompletionList()
2233 size_type MathCompletionList::size() const
2235 return locals.size() + globals.size();
2239 docstring const & MathCompletionList::data(size_t idx) const
2241 size_t lsize = locals.size();
2243 return globals[idx - lsize];
2249 std::string MathCompletionList::icon(size_t idx) const
2251 // get the latex command
2253 size_t lsize = locals.size();
2255 cmd = globals[idx - lsize];
2259 // get the icon resource name by stripping the backslash
2260 docstring icon_name = frontend::Application::mathIcon(cmd.substr(1));
2261 if (icon_name.empty())
2262 return std::string();
2263 return "images/math/" + to_utf8(icon_name);
2266 std::vector<docstring> MathCompletionList::globals;