]> git.lyx.org Git - features.git/blob - src/mathed/InsetMathNest.cpp
Make autocorrect configurable in preferences file
[features.git] / src / mathed / InsetMathNest.cpp
1 /**
2  * \file InsetMathNest.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author André Pönitz
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetMathNest.h"
14
15 #include "InsetMathArray.h"
16 #include "InsetMathBig.h"
17 #include "InsetMathBox.h"
18 #include "InsetMathBrace.h"
19 #include "InsetMathColor.h"
20 #include "InsetMathComment.h"
21 #include "InsetMathDelim.h"
22 #include "InsetMathHull.h"
23 #include "InsetMathRef.h"
24 #include "InsetMathScript.h"
25 #include "InsetMathSpace.h"
26 #include "InsetMathSymbol.h"
27 #include "InsetMathUnknown.h"
28 #include "MathAutoCorrect.h"
29 #include "MathCompletionList.h"
30 #include "MathData.h"
31 #include "MathFactory.h"
32 #include "MathMacro.h"
33 #include "MathMacroArgument.h"
34 #include "MathParser.h"
35 #include "MathStream.h"
36 #include "MathSupport.h"
37
38 #include "Bidi.h"
39 #include "Buffer.h"
40 #include "BufferView.h"
41 #include "CoordCache.h"
42 #include "Cursor.h"
43 #include "CutAndPaste.h"
44 #include "DispatchResult.h"
45 #include "FuncRequest.h"
46 #include "FuncStatus.h"
47 #include "LyXFunc.h"
48 #include "LyXRC.h"
49 #include "OutputParams.h"
50 #include "Text.h"
51
52 #include "frontends/Clipboard.h"
53 #include "frontends/Painter.h"
54 #include "frontends/Selection.h"
55
56 #include "support/lassert.h"
57 #include "support/debug.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60 #include "support/textutils.h"
61 #include "support/docstream.h"
62
63 #include <algorithm>
64 #include <sstream>
65
66 using namespace std;
67 using namespace lyx::support;
68
69 namespace lyx {
70
71 using cap::copySelection;
72 using cap::grabAndEraseSelection;
73 using cap::cutSelection;
74 using cap::replaceSelection;
75 using cap::selClearOrDel;
76
77
78 InsetMathNest::InsetMathNest(idx_type nargs)
79         : cells_(nargs), lock_(false), mouse_hover_(false)
80 {}
81
82
83 InsetMathNest::InsetMathNest(InsetMathNest const & inset)
84         : InsetMath(inset), cells_(inset.cells_), lock_(inset.lock_),
85           mouse_hover_(false)
86 {}
87
88
89 InsetMathNest & InsetMathNest::operator=(InsetMathNest const & inset)
90 {
91         cells_ = inset.cells_;
92         lock_ = inset.lock_;
93         mouse_hover_ = false;
94         InsetMath::operator=(inset);
95         return *this;
96 }
97
98
99 InsetMath::idx_type InsetMathNest::nargs() const
100 {
101         return cells_.size();
102 }
103
104
105 void InsetMathNest::cursorPos(BufferView const & bv,
106                 CursorSlice const & sl, bool /*boundary*/,
107                 int & x, int & y) const
108 {
109 // FIXME: This is a hack. Ideally, the coord cache should not store
110 // absolute positions, but relative ones. This would mean to call
111 // setXY() not in MathData::draw(), but in the parent insets' draw()
112 // with the correctly adjusted x,y values. But this means that we'd have
113 // to touch all (math)inset's draw() methods. Right now, we'll store
114 // absolute value, and make them here relative, only to make them
115 // absolute again when actually drawing the cursor. What a mess.
116         LASSERT(&sl.inset() == this, /**/);
117         MathData const & ar = sl.cell();
118         CoordCache const & coord_cache = bv.coordCache();
119         if (!coord_cache.getArrays().has(&ar)) {
120                 // this can (semi-)legally happen if we just created this cell
121                 // and it never has been drawn before. So don't ASSERT.
122                 //lyxerr << "no cached data for array " << &ar << endl;
123                 x = 0;
124                 y = 0;
125                 return;
126         }
127         Point const pt = coord_cache.getArrays().xy(&ar);
128         if (!coord_cache.getInsets().has(this)) {
129                 // same as above
130                 //lyxerr << "no cached data for inset " << this << endl;
131                 x = 0;
132                 y = 0;
133                 return;
134         }
135         Point const pt2 = coord_cache.getInsets().xy(this);
136         //lyxerr << "retrieving position cache for MathData "
137         //      << pt.x_ << ' ' << pt.y_ << endl;
138         x = pt.x_ - pt2.x_ + ar.pos2x(&bv, sl.pos());
139         y = pt.y_ - pt2.y_;
140 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
141 //              << " asc: " << ascent() << "  des: " << descent()
142 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
143         // move cursor visually into empty cells ("blue rectangles");
144         if (ar.empty())
145                 x += 2;
146 }
147
148
149 void InsetMathNest::metrics(MetricsInfo const & mi) const
150 {
151         MetricsInfo m = mi;
152         for (idx_type i = 0, n = nargs(); i != n; ++i) {
153                 Dimension dim;
154                 cell(i).metrics(m, dim);
155         }
156 }
157
158
159 bool InsetMathNest::idxNext(Cursor & cur) const
160 {
161         LASSERT(&cur.inset() == this, /**/);
162         if (cur.idx() == cur.lastidx())
163                 return false;
164         ++cur.idx();
165         cur.pos() = 0;
166         return true;
167 }
168
169
170 bool InsetMathNest::idxForward(Cursor & cur) const
171 {
172         return idxNext(cur);
173 }
174
175
176 bool InsetMathNest::idxPrev(Cursor & cur) const
177 {
178         LASSERT(&cur.inset() == this, /**/);
179         if (cur.idx() == 0)
180                 return false;
181         --cur.idx();
182         cur.pos() = cur.lastpos();
183         return true;
184 }
185
186
187 bool InsetMathNest::idxBackward(Cursor & cur) const
188 {
189         return idxPrev(cur);
190 }
191
192
193 bool InsetMathNest::idxFirst(Cursor & cur) const
194 {
195         LASSERT(&cur.inset() == this, /**/);
196         if (nargs() == 0)
197                 return false;
198         cur.idx() = 0;
199         cur.pos() = 0;
200         return true;
201 }
202
203
204 bool InsetMathNest::idxLast(Cursor & cur) const
205 {
206         LASSERT(&cur.inset() == this, /**/);
207         if (nargs() == 0)
208                 return false;
209         cur.idx() = cur.lastidx();
210         cur.pos() = cur.lastpos();
211         return true;
212 }
213
214
215 void InsetMathNest::dump() const
216 {
217         odocstringstream oss;
218         WriteStream os(oss);
219         os << "---------------------------------------------\n";
220         write(os);
221         os << "\n";
222         for (idx_type i = 0, n = nargs(); i != n; ++i)
223                 os << cell(i) << "\n";
224         os << "---------------------------------------------\n";
225         lyxerr << to_utf8(oss.str());
226 }
227
228
229 void InsetMathNest::draw(PainterInfo & pi, int x, int y) const
230 {
231 #if 0
232         if (lock_)
233                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
234                                         Color_mathlockbg);
235 #endif
236         setPosCache(pi, x, y);
237 }
238
239
240 void InsetMathNest::drawSelection(PainterInfo & pi, int x, int y) const
241 {
242         BufferView & bv = *pi.base.bv;
243         // this should use the x/y values given, not the cached values
244         Cursor & cur = bv.cursor();
245         if (!cur.selection())
246                 return;
247         if (&cur.inset() != this)
248                 return;
249
250         // FIXME: hack to get position cache warm
251         bool const original_drawing_state = pi.pain.isDrawingEnabled();
252         pi.pain.setDrawingEnabled(false);
253         draw(pi, x, y);
254         pi.pain.setDrawingEnabled(original_drawing_state);
255
256         CursorSlice s1 = cur.selBegin();
257         CursorSlice s2 = cur.selEnd();
258
259         //lyxerr << "InsetMathNest::drawing selection: "
260         //      << " s1: " << s1 << " s2: " << s2 << endl;
261         if (s1.idx() == s2.idx()) {
262                 MathData const & c = cell(s1.idx());
263                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
264                 int x1 = g.pos.x_ + c.pos2x(pi.base.bv, s1.pos());
265                 int y1 = g.pos.y_ - g.dim.ascent();
266                 int x2 = g.pos.x_ + c.pos2x(pi.base.bv, s2.pos());
267                 int y2 = g.pos.y_ + g.dim.descent();
268                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
269         //lyxerr << "InsetMathNest::drawing selection 3: "
270         //      << " x1: " << x1 << " x2: " << x2
271         //      << " y1: " << y1 << " y2: " << y2 << endl;
272         } else {
273                 for (idx_type i = 0; i < nargs(); ++i) {
274                         if (idxBetween(i, s1.idx(), s2.idx())) {
275                                 MathData const & c = cell(i);
276                                 Geometry const & g = bv.coordCache().getArrays().geometry(&c);
277                                 int x1 = g.pos.x_;
278                                 int y1 = g.pos.y_ - g.dim.ascent();
279                                 int x2 = g.pos.x_ + g.dim.width();
280                                 int y2 = g.pos.y_ + g.dim.descent();
281                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, Color_selection);
282                         }
283                 }
284         }
285 }
286
287
288 void InsetMathNest::validate(LaTeXFeatures & features) const
289 {
290         for (idx_type i = 0; i < nargs(); ++i)
291                 cell(i).validate(features);
292 }
293
294
295 void InsetMathNest::replace(ReplaceData & rep)
296 {
297         for (idx_type i = 0; i < nargs(); ++i)
298                 cell(i).replace(rep);
299 }
300
301
302 bool InsetMathNest::contains(MathData const & ar) const
303 {
304         for (idx_type i = 0; i < nargs(); ++i)
305                 if (cell(i).contains(ar))
306                         return true;
307         return false;
308 }
309
310
311 bool InsetMathNest::lock() const
312 {
313         return lock_;
314 }
315
316
317 void InsetMathNest::lock(bool l)
318 {
319         lock_ = l;
320 }
321
322
323 bool InsetMathNest::isActive() const
324 {
325         return nargs() > 0;
326 }
327
328
329 MathData InsetMathNest::glue() const
330 {
331         MathData ar;
332         for (size_t i = 0; i < nargs(); ++i)
333                 ar.append(cell(i));
334         return ar;
335 }
336
337
338 void InsetMathNest::write(WriteStream & os) const
339 {
340         ModeSpecifier specifier(os, currentMode());
341         docstring const latex_name = name();
342         os << '\\' << latex_name;
343         for (size_t i = 0; i < nargs(); ++i)
344                 os << '{' << cell(i) << '}';
345         if (nargs() == 0)
346                 os.pendingSpace(true);
347         if (lock_ && !os.latex()) {
348                 os << "\\lyxlock";
349                 os.pendingSpace(true);
350         }
351 }
352
353
354 void InsetMathNest::normalize(NormalStream & os) const
355 {
356         os << '[' << name();
357         for (size_t i = 0; i < nargs(); ++i)
358                 os << ' ' << cell(i);
359         os << ']';
360 }
361
362
363 int InsetMathNest::latex(odocstream & os, OutputParams const & runparams) const
364 {
365         WriteStream wi(os, runparams.moving_arg, true, runparams.dryrun,
366                         runparams.encoding);
367         write(wi);
368         return wi.line();
369 }
370
371
372 bool InsetMathNest::setMouseHover(bool mouse_hover)
373 {
374         mouse_hover_ = mouse_hover;
375         return true;
376 }
377
378
379 bool InsetMathNest::notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
380 {
381         // FIXME: look here
382 #if 0
383         MathData & ar = cur.cell();
384         // remove base-only "scripts"
385         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
386                 InsetMathScript * p = operator[](i).nucleus()->asScriptInset();
387                 if (p && p->nargs() == 1) {
388                         MathData ar = p->nuc();
389                         erase(i);
390                         insert(i, ar);
391                         cur.adjust(i, ar.size() - 1);
392                 }
393         }
394
395         // glue adjacent font insets of the same kind
396         for (pos_type i = 0; i + 1 < size(); ++i) {
397                 InsetMathFont * p = operator[](i).nucleus()->asFontInset();
398                 InsetMathFont const * q = operator[](i + 1)->asFontInset();
399                 if (p && q && p->name() == q->name()) {
400                         p->cell(0).append(q->cell(0));
401                         erase(i + 1);
402                         cur.adjust(i, -1);
403                 }
404         }
405 #endif
406         return false;
407 }
408
409
410 void InsetMathNest::handleFont
411         (Cursor & cur, docstring const & arg, char const * const font)
412 {
413         handleFont(cur, arg, from_ascii(font));
414 }
415
416
417 void InsetMathNest::handleFont(Cursor & cur, docstring const & arg,
418         docstring const & font)
419 {
420         cur.recordUndoSelection();
421
422         // this whole function is a hack and won't work for incremental font
423         // changes...
424         if (cur.inset().asInsetMath()->name() == font)
425                 cur.handleFont(to_utf8(font));
426         else
427                 handleNest(cur, createInsetMath(font), arg);
428 }
429
430
431 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest)
432 {
433         handleNest(cur, nest, docstring());
434 }
435
436
437 void InsetMathNest::handleNest(Cursor & cur, MathAtom const & nest,
438         docstring const & arg)
439 {
440         CursorSlice i1 = cur.selBegin();
441         CursorSlice i2 = cur.selEnd();
442         if (!i1.inset().asInsetMath())
443                 return;
444         if (i1.idx() == i2.idx()) {
445                 // the easy case where only one cell is selected
446                 cur.handleNest(nest);
447                 cur.insert(arg);
448                 return;
449         }
450
451         // multiple selected cells in a simple non-grid inset
452         if (i1.asInsetMath()->nrows() == 0 || i1.asInsetMath()->ncols() == 0) {
453                 for (idx_type i = i1.idx(); i <= i2.idx(); ++i) {
454                         // select cell
455                         cur.idx() = i;
456                         cur.pos() = 0;
457                         cur.resetAnchor();
458                         cur.pos() = cur.lastpos();
459                         cur.setSelection();
460
461                         // change font of cell
462                         cur.handleNest(nest);
463                         cur.insert(arg);
464
465                         // cur is in the font inset now. If the loop continues,
466                         // we need to get outside again for the next cell
467                         if (i + 1 <= i2.idx())
468                                 cur.pop_back();
469                 }
470                 return;
471         }
472
473         // the complicated case with multiple selected cells in a grid
474         row_type r1, r2;
475         col_type c1, c2;
476         cap::region(i1, i2, r1, r2, c1, c2);
477         for (row_type row = r1; row <= r2; ++row) {
478                 for (col_type col = c1; col <= c2; ++col) {
479                         // select cell
480                         cur.idx() = i1.asInsetMath()->index(row, col);
481                         cur.pos() = 0;
482                         cur.resetAnchor();
483                         cur.pos() = cur.lastpos();
484                         cur.setSelection();
485
486                         //
487                         cur.handleNest(nest);
488                         cur.insert(arg);
489
490                         // cur is in the font inset now. If the loop continues,
491                         // we need to get outside again for the next cell
492                         if (col + 1 <= c2 || row + 1 <= r2)
493                                 cur.pop_back();
494                 }
495         }
496 }
497
498
499 void InsetMathNest::handleFont2(Cursor & cur, docstring const & arg)
500 {
501         cur.recordUndoSelection();
502         Font font;
503         bool b;
504         font.fromString(to_utf8(arg), b);
505         if (font.fontInfo().color() != Color_inherit &&
506             font.fontInfo().color() != Color_ignore)
507                 handleNest(cur, MathAtom(new InsetMathColor(true, font.fontInfo().color())));
508
509         // FIXME: support other font changes here as well?
510 }
511
512
513 void InsetMathNest::doDispatch(Cursor & cur, FuncRequest & cmd)
514 {
515         //lyxerr << "InsetMathNest: request: " << cmd << endl;
516
517         Parse::flags parseflg = Parse::QUIET;
518
519         switch (cmd.action) {
520
521         case LFUN_CLIPBOARD_PASTE:
522                 parseflg |= Parse::VERBATIM;
523                 // fall through
524         case LFUN_PASTE: {
525                 if (cur.currentMode() == TEXT_MODE)
526                         parseflg |= Parse::TEXTMODE;
527                 cur.recordUndoSelection();
528                 cur.message(_("Paste"));
529                 replaceSelection(cur);
530                 docstring topaste;
531                 if (cmd.argument().empty() && !theClipboard().isInternal())
532                         topaste = theClipboard().getAsText();
533                 else {
534                         size_t n = 0;
535                         idocstringstream is(cmd.argument());
536                         is >> n;
537                         topaste = cap::selection(n);
538                 }
539                 cur.niceInsert(topaste, parseflg);
540                 cur.clearSelection(); // bug 393
541                 cur.finishUndo();
542                 break;
543         }
544
545         case LFUN_CUT:
546                 cur.recordUndo();
547                 cutSelection(cur, true, true);
548                 cur.message(_("Cut"));
549                 // Prevent stale position >= size crash
550                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
551                 cur.normalize();
552                 break;
553
554         case LFUN_COPY:
555                 copySelection(cur);
556                 cur.message(_("Copy"));
557                 break;
558
559         case LFUN_MOUSE_PRESS:
560                 lfunMousePress(cur, cmd);
561                 break;
562
563         case LFUN_MOUSE_MOTION:
564                 lfunMouseMotion(cur, cmd);
565                 break;
566
567         case LFUN_MOUSE_RELEASE:
568                 lfunMouseRelease(cur, cmd);
569                 break;
570
571         case LFUN_FINISHED_LEFT: // in math, left is backwards
572         case LFUN_FINISHED_BACKWARD:
573                 cur.bv().cursor() = cur;
574                 break;
575
576         case LFUN_FINISHED_RIGHT: // in math, right is forward
577         case LFUN_FINISHED_FORWARD:
578                 ++cur.pos();
579                 cur.bv().cursor() = cur;
580                 break;
581
582         case LFUN_CHAR_RIGHT:
583         case LFUN_CHAR_LEFT:
584         case LFUN_CHAR_BACKWARD:
585         case LFUN_CHAR_FORWARD:
586                 cur.updateFlags(Update::Decoration | Update::FitCursor);
587         case LFUN_CHAR_RIGHT_SELECT:
588         case LFUN_CHAR_LEFT_SELECT:
589         case LFUN_CHAR_BACKWARD_SELECT:
590         case LFUN_CHAR_FORWARD_SELECT: {
591                 // are we in a selection?
592                 bool select = (cmd.action == LFUN_CHAR_RIGHT_SELECT
593                                            || cmd.action == LFUN_CHAR_LEFT_SELECT
594                                            || cmd.action == LFUN_CHAR_BACKWARD_SELECT
595                                            || cmd.action == LFUN_CHAR_FORWARD_SELECT);
596                 // are we moving forward or backwards?
597                 // If the command was RIGHT or LEFT, then whether we're moving forward
598                 // or backwards depends on the cursor movement mode (logical or visual):
599                 //  * in visual mode, since math is always LTR, right -> forward,
600                 //    left -> backwards
601                 //  * in logical mode, the mapping is determined by the
602                 //    reverseDirectionNeeded() function
603
604                 bool forward;
605                 FuncCode finish_lfun;
606
607                 if (cmd.action == LFUN_CHAR_FORWARD
608                                 || cmd.action == LFUN_CHAR_FORWARD_SELECT) {
609                         forward = true;
610                         finish_lfun = LFUN_FINISHED_FORWARD;
611                 }
612                 else if (cmd.action == LFUN_CHAR_BACKWARD
613                                 || cmd.action == LFUN_CHAR_BACKWARD_SELECT) {
614                         forward = false;
615                         finish_lfun = LFUN_FINISHED_BACKWARD;
616                 }
617                 else {
618                         bool right = (cmd.action == LFUN_CHAR_RIGHT_SELECT
619                                                   || cmd.action == LFUN_CHAR_RIGHT);
620                         if (lyxrc.visual_cursor || !reverseDirectionNeeded(cur))
621                                 forward = right;
622                         else
623                                 forward = !right;
624
625                         if (right)
626                                 finish_lfun = LFUN_FINISHED_RIGHT;
627                         else
628                                 finish_lfun = LFUN_FINISHED_LEFT;
629                 }
630                 // Now that we know exactly what we want to do, let's do it!
631                 cur.selHandle(select);
632                 cur.clearTargetX();
633                 cur.macroModeClose();
634                 // try moving forward or backwards as necessary...
635                 if (!(forward ? cursorMathForward(cur) : cursorMathBackward(cur))) {
636                         // ... and if movement failed, then finish forward or backwards
637                         // as necessary
638                         cmd = FuncRequest(finish_lfun);
639                         cur.undispatched();
640                 }
641                 break;
642         }
643
644         case LFUN_DOWN:
645         case LFUN_UP:
646                 cur.updateFlags(Update::Decoration | Update::FitCursor);
647         case LFUN_DOWN_SELECT:
648         case LFUN_UP_SELECT: {
649                 // close active macro
650                 if (cur.inMacroMode()) {
651                         cur.macroModeClose();
652                         break;
653                 }
654
655                 // stop/start the selection
656                 bool select = cmd.action == LFUN_DOWN_SELECT ||
657                         cmd.action == LFUN_UP_SELECT;
658                 cur.selHandle(select);
659
660                 // go up/down
661                 bool up = cmd.action == LFUN_UP || cmd.action == LFUN_UP_SELECT;
662                 bool successful = cur.upDownInMath(up);
663                 if (successful)
664                         break;
665
666                 if (cur.fixIfBroken())
667                         // FIXME: Something bad happened. We pass the corrected Cursor
668                         // instead of letting things go worse.
669                         break;
670
671                 // We did not manage to move the cursor.
672                 cur.undispatched();
673                 break;
674         }
675
676         case LFUN_MOUSE_DOUBLE:
677         case LFUN_MOUSE_TRIPLE:
678         case LFUN_WORD_SELECT:
679                 cur.pos() = 0;
680                 cur.idx() = 0;
681                 cur.resetAnchor();
682                 cur.setSelection(true);
683                 cur.pos() = cur.lastpos();
684                 cur.idx() = cur.lastidx();
685                 break;
686
687         case LFUN_PARAGRAPH_UP:
688         case LFUN_PARAGRAPH_DOWN:
689                 cur.updateFlags(Update::Decoration | Update::FitCursor);
690         case LFUN_PARAGRAPH_UP_SELECT:
691         case LFUN_PARAGRAPH_DOWN_SELECT:
692                 break;
693
694         case LFUN_LINE_BEGIN:
695         case LFUN_WORD_BACKWARD:
696         case LFUN_WORD_LEFT:
697                 cur.updateFlags(Update::Decoration | Update::FitCursor);
698         case LFUN_LINE_BEGIN_SELECT:
699         case LFUN_WORD_BACKWARD_SELECT:
700         case LFUN_WORD_LEFT_SELECT:
701                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
702                                 cmd.action == LFUN_WORD_LEFT_SELECT ||
703                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
704                 cur.macroModeClose();
705                 if (cur.pos() != 0) {
706                         cur.pos() = 0;
707                 } else if (cur.col() != 0) {
708                         cur.idx() -= cur.col();
709                         cur.pos() = 0;
710                 } else if (cur.idx() != 0) {
711                         cur.idx() = 0;
712                         cur.pos() = 0;
713                 } else {
714                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
715                         cur.undispatched();
716                 }
717                 break;
718
719         case LFUN_WORD_FORWARD:
720         case LFUN_WORD_RIGHT:
721         case LFUN_LINE_END:
722                 cur.updateFlags(Update::Decoration | Update::FitCursor);
723         case LFUN_WORD_FORWARD_SELECT:
724         case LFUN_WORD_RIGHT_SELECT:
725         case LFUN_LINE_END_SELECT:
726                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
727                                 cmd.action == LFUN_WORD_RIGHT_SELECT ||
728                                 cmd.action == LFUN_LINE_END_SELECT);
729                 cur.macroModeClose();
730                 cur.clearTargetX();
731                 if (cur.pos() != cur.lastpos()) {
732                         cur.pos() = cur.lastpos();
733                 } else if (ncols() && (cur.col() != cur.lastcol())) {
734                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
735                         cur.pos() = cur.lastpos();
736                 } else if (cur.idx() != cur.lastidx()) {
737                         cur.idx() = cur.lastidx();
738                         cur.pos() = cur.lastpos();
739                 } else {
740                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
741                         cur.undispatched();
742                 }
743                 break;
744
745         case LFUN_CELL_FORWARD:
746                 cur.updateFlags(Update::Decoration | Update::FitCursor);
747                 cur.inset().idxNext(cur);
748                 break;
749
750         case LFUN_CELL_BACKWARD:
751                 cur.updateFlags(Update::Decoration | Update::FitCursor);
752                 cur.inset().idxPrev(cur);
753                 break;
754
755         case LFUN_WORD_DELETE_BACKWARD:
756         case LFUN_CHAR_DELETE_BACKWARD:
757                 if (cur.pos() == 0)
758                         // May affect external cell:
759                         cur.recordUndoInset();
760                 else
761                         cur.recordUndoSelection();
762                 // if the inset can not be removed from within, delete it
763                 if (!cur.backspace()) {
764                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
765                         cur.innerText()->dispatch(cur, cmd);
766                 }
767                 break;
768
769         case LFUN_WORD_DELETE_FORWARD:
770         case LFUN_CHAR_DELETE_FORWARD:
771                 if (cur.pos() == cur.lastpos())
772                         // May affect external cell:
773                         cur.recordUndoInset();
774                 else
775                         cur.recordUndoSelection();
776                 // if the inset can not be removed from within, delete it
777                 if (!cur.erase()) {
778                         FuncRequest cmd = FuncRequest(LFUN_CHAR_DELETE_FORWARD);
779                         cur.innerText()->dispatch(cur, cmd);
780                 }
781                 break;
782
783         case LFUN_ESCAPE:
784                 if (cur.selection())
785                         cur.clearSelection();
786                 else  {
787                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
788                         cur.undispatched();
789                 }
790                 break;
791
792         // 'Locks' the math inset. A 'locked' math inset behaves as a unit
793         // that is traversed by a single <CursorLeft>/<CursorRight>.
794         case LFUN_INSET_TOGGLE:
795                 cur.recordUndo();
796                 lock(!lock());
797                 cur.popForward();
798                 break;
799
800         case LFUN_SELF_INSERT:
801                 if (cmd.argument().size() != 1) {
802                         cur.recordUndoSelection();
803                         docstring const arg = cmd.argument();
804                         if (!interpretString(cur, arg))
805                                 cur.insert(arg);
806                         break;
807                 }
808                 // Don't record undo steps if we are in macro mode and
809                 // cmd.argument is the next character of the macro name.
810                 // Otherwise we'll get an invalid cursor if we undo after
811                 // the macro was finished and the macro is a known command,
812                 // e.g. sqrt. Cursor::macroModeClose replaces in this case
813                 // the InsetMathUnknown with name "frac" by an empty
814                 // InsetMathFrac -> a pos value > 0 is invalid.
815                 // A side effect is that an undo before the macro is finished
816                 // undoes the complete macro, not only the last character.
817                 if (!cur.inMacroMode())
818                         cur.recordUndoSelection();
819
820                 // spacial handling of space. If we insert an inset
821                 // via macro mode, we want to put the cursor inside it
822                 // if relevant. Think typing "\frac<space>".
823                 if (cmd.argument()[0] == ' '
824                     && cur.inMacroMode() && cur.macroName() != "\\"
825                     && cur.macroModeClose()) {
826                         MathAtom const atom = cur.prevAtom();
827                         if (atom->asNestInset() && atom->isActive()) {
828                                 cur.posBackward();
829                                 cur.pushBackward(*cur.nextInset());
830                         }
831                 } else if (!interpretChar(cur, cmd.argument()[0])) {
832                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
833                         cur.undispatched();
834                 }
835                 break;
836
837         //case LFUN_SERVER_GET_XY:
838         //      break;
839
840         case LFUN_SERVER_SET_XY: {
841                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
842                 int x = 0;
843                 int y = 0;
844                 istringstream is(to_utf8(cmd.argument()));
845                 is >> x >> y;
846                 cur.setScreenPos(x, y);
847                 break;
848         }
849
850         // Special casing for superscript in case of LyX handling
851         // dead-keys:
852         case LFUN_ACCENT_CIRCUMFLEX:
853                 if (cmd.argument().empty()) {
854                         // do superscript if LyX handles
855                         // deadkeys
856                         cur.recordUndoSelection();
857                         script(cur, true, grabAndEraseSelection(cur));
858                 }
859                 break;
860
861         case LFUN_ACCENT_UMLAUT:
862         case LFUN_ACCENT_ACUTE:
863         case LFUN_ACCENT_GRAVE:
864         case LFUN_ACCENT_BREVE:
865         case LFUN_ACCENT_DOT:
866         case LFUN_ACCENT_MACRON:
867         case LFUN_ACCENT_CARON:
868         case LFUN_ACCENT_TILDE:
869         case LFUN_ACCENT_CEDILLA:
870         case LFUN_ACCENT_CIRCLE:
871         case LFUN_ACCENT_UNDERDOT:
872         case LFUN_ACCENT_TIE:
873         case LFUN_ACCENT_OGONEK:
874         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
875                 break;
876
877         //  Math fonts
878         case LFUN_TEXTSTYLE_APPLY:
879         case LFUN_TEXTSTYLE_UPDATE:
880                 handleFont2(cur, cmd.argument());
881                 break;
882
883         case LFUN_FONT_BOLD:
884                 if (currentMode() == TEXT_MODE)
885                         handleFont(cur, cmd.argument(), "textbf");
886                 else
887                         handleFont(cur, cmd.argument(), "mathbf");
888                 break;
889         case LFUN_FONT_BOLDSYMBOL:
890                 if (currentMode() == TEXT_MODE)
891                         handleFont(cur, cmd.argument(), "textbf");
892                 else
893                         handleFont(cur, cmd.argument(), "boldsymbol");
894                 break;
895         case LFUN_FONT_SANS:
896                 if (currentMode() == TEXT_MODE)
897                         handleFont(cur, cmd.argument(), "textsf");
898                 else
899                         handleFont(cur, cmd.argument(), "mathsf");
900                 break;
901         case LFUN_FONT_EMPH:
902                 if (currentMode() == TEXT_MODE)
903                         handleFont(cur, cmd.argument(), "emph");
904                 else
905                         handleFont(cur, cmd.argument(), "mathcal");
906                 break;
907         case LFUN_FONT_ROMAN:
908                 if (currentMode() == TEXT_MODE)
909                         handleFont(cur, cmd.argument(), "textrm");
910                 else
911                         handleFont(cur, cmd.argument(), "mathrm");
912                 break;
913         case LFUN_FONT_TYPEWRITER:
914                 if (currentMode() == TEXT_MODE)
915                         handleFont(cur, cmd.argument(), "texttt");
916                 else
917                         handleFont(cur, cmd.argument(), "mathtt");
918                 break;
919         case LFUN_FONT_FRAK:
920                 handleFont(cur, cmd.argument(), "mathfrak");
921                 break;
922         case LFUN_FONT_ITAL:
923                 if (currentMode() == TEXT_MODE)
924                         handleFont(cur, cmd.argument(), "textit");
925                 else
926                         handleFont(cur, cmd.argument(), "mathit");
927                 break;
928         case LFUN_FONT_NOUN:
929                 if (currentMode() == TEXT_MODE)
930                         // FIXME: should be "noun"
931                         handleFont(cur, cmd.argument(), "textsc");
932                 else
933                         handleFont(cur, cmd.argument(), "mathbb");
934                 break;
935         case LFUN_FONT_DEFAULT:
936                 handleFont(cur, cmd.argument(), "textnormal");
937                 break;
938
939         case LFUN_MATH_MODE: {
940 #if 1
941                 // ignore math-mode on when already in math mode
942                 if (currentMode() == Inset::MATH_MODE && cmd.argument() == "on")
943                         break;
944                 cur.recordUndoSelection();
945                 cur.macroModeClose();
946                 docstring const save_selection = grabAndEraseSelection(cur);
947                 selClearOrDel(cur);
948                 //cur.plainInsert(MathAtom(new InsetMathMBox(cur.bv())));
949                 cur.plainInsert(MathAtom(new InsetMathBox(from_ascii("mbox"))));
950                 cur.posBackward();
951                 cur.pushBackward(*cur.nextInset());
952                 cur.niceInsert(save_selection);
953 #else
954                 if (currentMode() == Inset::TEXT_MODE) {
955                         cur.recordUndoSelection();
956                         cur.niceInsert(MathAtom(new InsetMathHull("simple")));
957                         cur.message(_("create new math text environment ($...$)"));
958                 } else {
959                         handleFont(cur, cmd.argument(), "textrm");
960                         cur.message(_("entered math text mode (textrm)"));
961                 }
962 #endif
963                 break;
964         }
965
966         case LFUN_REGEXP_MODE: {
967                 InsetMathHull * i = dynamic_cast<InsetMathHull *>(cur.inset().asInsetMath());
968                 if (i && i->getType() == hullRegexp) {
969                         cur.message(_("Already in regexp mode"));
970                         break;
971                 }
972                 cur.macroModeClose();
973                 docstring const save_selection = grabAndEraseSelection(cur);
974                 selClearOrDel(cur);
975                 cur.plainInsert(MathAtom(new InsetMathHull(hullRegexp)));
976                 cur.posBackward();
977                 cur.pushBackward(*cur.nextInset());
978                 cur.niceInsert(save_selection);
979                 cur.message(_("Regexp editor mode"));
980                 break;
981         }
982
983         case LFUN_MATH_SIZE: {
984                 FuncRequest fr = FuncRequest(LFUN_MATH_INSERT, cmd.argument());
985                 doDispatch(cur, fr);
986                 break;
987         }
988
989         case LFUN_MATH_MATRIX: {
990                 cur.recordUndo();
991                 unsigned int m = 1;
992                 unsigned int n = 1;
993                 docstring v_align;
994                 docstring h_align;
995                 idocstringstream is(cmd.argument());
996                 is >> m >> n >> v_align >> h_align;
997                 if (m < 1)
998                         m = 1;
999                 if (n < 1)
1000                         n = 1;
1001                 v_align += 'c';
1002                 cur.niceInsert(
1003                         MathAtom(new InsetMathArray(from_ascii("array"), m, n, (char)v_align[0], h_align)));
1004                 break;
1005         }
1006
1007         case LFUN_MATH_DELIM: {
1008                 docstring ls;
1009                 docstring rs = split(cmd.argument(), ls, ' ');
1010                 // Reasonable default values
1011                 if (ls.empty())
1012                         ls = '(';
1013                 if (rs.empty())
1014                         rs = ')';
1015                 cur.recordUndo();
1016                 cur.handleNest(MathAtom(new InsetMathDelim(ls, rs)));
1017                 break;
1018         }
1019
1020         case LFUN_MATH_BIGDELIM: {
1021                 docstring const lname  = from_utf8(cmd.getArg(0));
1022                 docstring const ldelim = from_utf8(cmd.getArg(1));
1023                 docstring const rname  = from_utf8(cmd.getArg(2));
1024                 docstring const rdelim = from_utf8(cmd.getArg(3));
1025                 latexkeys const * l = in_word_set(lname);
1026                 bool const have_l = l && l->inset == "big" &&
1027                                     InsetMathBig::isBigInsetDelim(ldelim);
1028                 l = in_word_set(rname);
1029                 bool const have_r = l && l->inset == "big" &&
1030                                     InsetMathBig::isBigInsetDelim(rdelim);
1031                 // We mimic LFUN_MATH_DELIM in case we have an empty left
1032                 // or right delimiter.
1033                 if (have_l || have_r) {
1034                         cur.recordUndo();
1035                         docstring const selection = grabAndEraseSelection(cur);
1036                         selClearOrDel(cur);
1037                         if (have_l)
1038                                 cur.insert(MathAtom(new InsetMathBig(lname,
1039                                                                 ldelim)));
1040                         cur.niceInsert(selection);
1041                         if (have_r)
1042                                 cur.insert(MathAtom(new InsetMathBig(rname,
1043                                                                 rdelim)));
1044                 }
1045                 // Don't call cur.undispatched() if we did nothing, this would
1046                 // lead to infinite recursion via Text::dispatch().
1047                 break;
1048         }
1049
1050         case LFUN_SPACE_INSERT:
1051                 cur.recordUndoSelection();
1052                 cur.insert(MathAtom(new InsetMathSpace));
1053                 break;
1054
1055         case LFUN_MATH_SPACE:
1056                 cur.recordUndoSelection();
1057                 if (cmd.argument().empty())
1058                         cur.insert(MathAtom(new InsetMathSpace));
1059                 else {
1060                         string const name = cmd.getArg(0);
1061                         string const len = cmd.getArg(1);
1062                         cur.insert(MathAtom(new InsetMathSpace(name, len)));
1063                 }
1064                 break;
1065
1066         case LFUN_ERT_INSERT:
1067                 // interpret this as if a backslash was typed
1068                 cur.recordUndo();
1069                 interpretChar(cur, '\\');
1070                 break;
1071
1072         case LFUN_MATH_SUBSCRIPT:
1073                 // interpret this as if a _ was typed
1074                 cur.recordUndoSelection();
1075                 interpretChar(cur, '_');
1076                 break;
1077
1078         case LFUN_MATH_SUPERSCRIPT:
1079                 // interpret this as if a ^ was typed
1080                 cur.recordUndoSelection();
1081                 interpretChar(cur, '^');
1082                 break;
1083
1084         case LFUN_MATH_MACRO_FOLD:
1085         case LFUN_MATH_MACRO_UNFOLD: {
1086                 Cursor it = cur;
1087                 bool fold = cmd.action == LFUN_MATH_MACRO_FOLD;
1088                 bool found = findMacroToFoldUnfold(it, fold);
1089                 if (found) {
1090                         MathMacro * macro = it.nextInset()->asInsetMath()->asMacro();
1091                         cur.recordUndoInset();
1092                         if (fold)
1093                                 macro->fold(cur);
1094                         else
1095                                 macro->unfold(cur);
1096                 }
1097                 break;
1098         }
1099
1100         case LFUN_QUOTE_INSERT:
1101                 // interpret this as if a straight " was typed
1102                 cur.recordUndoSelection();
1103                 interpretChar(cur, '\"');
1104                 break;
1105
1106 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
1107 // handling such that "self-insert" works on "arbitrary stuff" too, and
1108 // math-insert only handles special math things like "matrix".
1109         case LFUN_MATH_INSERT: {
1110                 cur.recordUndoSelection();
1111                 if (cmd.argument() == "^" || cmd.argument() == "_")
1112                         interpretChar(cur, cmd.argument()[0]);
1113                 else {
1114                         MathData ar;
1115                         asArray(cmd.argument(), ar);
1116                         if (ar.size() == 1 && ar[0]->asNestInset()
1117                                         && ar[0]->asNestInset()->nargs() > 1)
1118                                 handleNest(cur, ar[0]);
1119                         else
1120                                 cur.niceInsert(cmd.argument());
1121                 }
1122                 break;
1123                 }
1124
1125         case LFUN_DIALOG_SHOW_NEW_INSET: {
1126                 docstring const & name = cmd.argument();
1127                 string data;
1128                 if (name == "ref") {
1129                         InsetMathRef tmp(name);
1130                         data = tmp.createDialogStr(to_utf8(name));
1131                 } else if (name == "mathspace") {
1132                         InsetMathSpace tmp;
1133                         data = tmp.createDialogStr();
1134                 }
1135                 cur.bv().showDialog(to_utf8(name), data);
1136                 break;
1137         }
1138
1139         case LFUN_INSET_INSERT: {
1140                 MathData ar;
1141                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1142                         cur.recordUndoSelection();
1143                         cur.insert(ar);
1144                 } else
1145                         cur.undispatched();
1146                 break;
1147         }
1148         case LFUN_INSET_DISSOLVE:
1149                 if (!asHullInset()) {
1150                         cur.recordUndoInset();
1151                         cur.pullArg();
1152                 }
1153                 break;
1154
1155         default:
1156                 InsetMath::doDispatch(cur, cmd);
1157                 break;
1158         }
1159 }
1160
1161
1162 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1163         // look for macro to open/close, but stay in mathed
1164         for (; !it.empty(); it.pop_back()) {
1165
1166                 // go backward through the current cell
1167                 Inset * inset = it.nextInset();
1168                 while (inset && inset->asInsetMath()) {
1169                         MathMacro * macro = inset->asInsetMath()->asMacro();
1170                         if (macro) {
1171                                 // found the an macro to open/close?
1172                                 if (macro->folded() != fold)
1173                                         return true;
1174
1175                                 // Wrong folding state.
1176                                 // If this was the first we see in this slice, look further left,
1177                                 // otherwise go up.
1178                                 if (inset != it.nextInset())
1179                                         break;
1180                         }
1181
1182                         // go up if this was the left most position
1183                         if (it.pos() == 0)
1184                                 break;
1185
1186                         // go left
1187                         it.pos()--;
1188                         inset = it.nextInset();
1189                 }
1190         }
1191
1192         return false;
1193 }
1194
1195
1196 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1197                 FuncStatus & flag) const
1198 {
1199         // the font related toggles
1200         //string tc = "mathnormal";
1201         bool ret = true;
1202         string const arg = to_utf8(cmd.argument());
1203         switch (cmd.action) {
1204         case LFUN_TABULAR_FEATURE:
1205                 flag.setEnabled(false);
1206                 break;
1207 #if 0
1208         case LFUN_TABULAR_FEATURE:
1209                 // FIXME: check temporarily disabled
1210                 // valign code
1211                 char align = mathcursor::valign();
1212                 if (align == '\0') {
1213                         enable = false;
1214                         break;
1215                 }
1216                 if (cmd.argument().empty()) {
1217                         flag.clear();
1218                         break;
1219                 }
1220                 if (!contains("tcb", cmd.argument()[0])) {
1221                         enable = false;
1222                         break;
1223                 }
1224                 flag.setOnOff(cmd.argument()[0] == align);
1225                 break;
1226 #endif
1227         /// We have to handle them since 1.4 blocks all unhandled actions
1228         case LFUN_FONT_ITAL:
1229         case LFUN_FONT_BOLD:
1230         case LFUN_FONT_BOLDSYMBOL:
1231         case LFUN_FONT_SANS:
1232         case LFUN_FONT_EMPH:
1233         case LFUN_FONT_TYPEWRITER:
1234         case LFUN_FONT_NOUN:
1235         case LFUN_FONT_ROMAN:
1236         case LFUN_FONT_DEFAULT:
1237                 flag.setEnabled(true);
1238                 break;
1239         case LFUN_MATH_MUTATE:
1240                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1241                 flag.setOnOff(false);
1242                 break;
1243
1244         // we just need to be in math mode to enable that
1245         case LFUN_MATH_SIZE:
1246         case LFUN_MATH_SPACE:
1247         case LFUN_MATH_LIMITS:
1248         case LFUN_MATH_EXTERN:
1249                 flag.setEnabled(true);
1250                 break;
1251
1252         case LFUN_FONT_FRAK:
1253                 flag.setEnabled(currentMode() != TEXT_MODE);
1254                 break;
1255
1256         case LFUN_MATH_INSERT: {
1257                 bool const textarg =
1258                         arg == "\\textbf"   || arg == "\\textsf" ||
1259                         arg == "\\textrm"   || arg == "\\textmd" ||
1260                         arg == "\\textit"   || arg == "\\textsc" ||
1261                         arg == "\\textsl"   || arg == "\\textup" ||
1262                         arg == "\\texttt"   || arg == "\\textbb" ||
1263                         arg == "\\textnormal";
1264                 flag.setEnabled(currentMode() != TEXT_MODE || textarg);
1265                 break;
1266         }
1267
1268         case LFUN_MATH_MATRIX:
1269                 flag.setEnabled(currentMode() == MATH_MODE);
1270                 break;
1271
1272         case LFUN_INSET_INSERT: {
1273                 // Don't test createMathInset_fromDialogStr(), since
1274                 // getStatus is not called with a valid reference and the
1275                 // dialog would not be applyable.
1276                 string const name = cmd.getArg(0);
1277                 flag.setEnabled(name == "ref" || name == "mathspace");
1278                 break;
1279         }
1280
1281         case LFUN_MATH_DELIM:
1282         case LFUN_MATH_BIGDELIM:
1283                 // Don't do this with multi-cell selections
1284                 flag.setEnabled(cur.selBegin().idx() == cur.selEnd().idx());
1285                 break;
1286
1287         case LFUN_MATH_MACRO_FOLD:
1288         case LFUN_MATH_MACRO_UNFOLD: {
1289                 Cursor it = cur;
1290                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1291                 flag.setEnabled(found);
1292                 break;
1293         }
1294
1295         case LFUN_SPECIALCHAR_INSERT:
1296                 // FIXME: These would probably make sense in math-text mode
1297                 flag.setEnabled(false);
1298                 break;
1299
1300         case LFUN_INSET_DISSOLVE:
1301                 flag.setEnabled(!asHullInset());
1302                 break;
1303
1304         default:
1305                 ret = false;
1306                 break;
1307         }
1308         return ret;
1309 }
1310
1311
1312 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1313 {
1314         cur.push(*this);
1315         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT ||
1316                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1317         cur.idx() = enter_front ? 0 : cur.lastidx();
1318         cur.pos() = enter_front ? 0 : cur.lastpos();
1319         cur.resetAnchor();
1320         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1321 }
1322
1323
1324 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1325 {
1326         int idx_min = 0;
1327         int dist_min = 1000000;
1328         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1329                 int const d = cell(i).dist(cur.bv(), x, y);
1330                 if (d < dist_min) {
1331                         dist_min = d;
1332                         idx_min = i;
1333                 }
1334         }
1335         MathData & ar = cell(idx_min);
1336         cur.push(*this);
1337         cur.idx() = idx_min;
1338         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1339
1340         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1341         if (dist_min == 0) {
1342                 // hit inside cell
1343                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1344                         if (ar[i]->covers(cur.bv(), x, y))
1345                                 return ar[i].nucleus()->editXY(cur, x, y);
1346         }
1347         return this;
1348 }
1349
1350
1351 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1352 {
1353         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1354         BufferView & bv = cur.bv();
1355         bool do_selection = cmd.button() == mouse_button::button1
1356                 && cmd.argument() == "region-select";
1357         bv.mouseSetCursor(cur, do_selection);
1358         if (cmd.button() == mouse_button::button1) {
1359                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1360                 // Update the cursor update flags as needed:
1361                 //
1362                 // Update::Decoration: tells to update the decoration
1363                 //                     (visual box corners that define
1364                 //                     the inset)/
1365                 // Update::FitCursor: adjust the screen to the cursor
1366                 //                    position if needed
1367                 // cur.result().update(): don't overwrite previously set flags.
1368                 cur.updateFlags(Update::Decoration | Update::FitCursor
1369                                 | cur.result().update());
1370         } else if (cmd.button() == mouse_button::button2) {
1371                 if (cap::selection()) {
1372                         // See comment in Text::dispatch why we do this
1373                         cap::copySelectionToStack();
1374                         cmd = FuncRequest(LFUN_PASTE, "0");
1375                         doDispatch(bv.cursor(), cmd);
1376                 } else {
1377                         MathData ar;
1378                         asArray(theSelection().get(), ar);
1379                         bv.cursor().insert(ar);
1380                 }
1381         }
1382 }
1383
1384
1385 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1386 {
1387         // only select with button 1
1388         if (cmd.button() == mouse_button::button1) {
1389                 Cursor & bvcur = cur.bv().cursor();
1390                 if (bvcur.anchor_.hasPart(cur)) {
1391                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1392                         bvcur.setCursor(cur);
1393                         bvcur.setSelection(true);
1394                         //lyxerr << "MOTION " << bvcur << endl;
1395                 } else
1396                         cur.undispatched();
1397         }
1398 }
1399
1400
1401 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1402 {
1403         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1404
1405         if (cmd.button() == mouse_button::button1) {
1406                 if (!cur.selection())
1407                         cur.noUpdate();
1408                 else {
1409                         Cursor & bvcur = cur.bv().cursor();
1410                         bvcur.setSelection(true);
1411                 }
1412                 return;
1413         }
1414
1415         cur.undispatched();
1416 }
1417
1418
1419 bool InsetMathNest::interpretChar(Cursor & cur, char_type const c)
1420 {
1421         //lyxerr << "interpret 2: '" << c << "'" << endl;
1422         docstring save_selection;
1423         if (c == '^' || c == '_')
1424                 save_selection = grabAndEraseSelection(cur);
1425
1426         cur.clearTargetX();
1427
1428         // handle macroMode
1429         if (cur.inMacroMode()) {
1430                 docstring name = cur.macroName();
1431
1432                 /// are we currently typing '#1' or '#2' or...?
1433                 if (name == "\\#") {
1434                         cur.backspace();
1435                         int n = c - '0';
1436                         if (n >= 1 && n <= 9)
1437                                 cur.insert(new MathMacroArgument(n));
1438                         return true;
1439                 }
1440
1441                 // do not finish macro for known * commands
1442                 MathWordList const & mwl = mathedWordList();
1443                 bool star_macro = c == '*'
1444                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1445                             || cur.buffer()->getMacro(name.substr(1) + "*", cur, true));
1446                 if (isAlphaASCII(c) || star_macro) {
1447                         cur.activeMacro()->setName(name + docstring(1, c));
1448                         return true;
1449                 }
1450
1451                 // handle 'special char' macros
1452                 if (name == "\\") {
1453                         // remove the '\\'
1454                         if (c == '\\') {
1455                                 cur.backspace();
1456                                 if (currentMode() == InsetMath::TEXT_MODE)
1457                                         cur.niceInsert(createInsetMath("textbackslash"));
1458                                 else
1459                                         cur.niceInsert(createInsetMath("backslash"));
1460                         } else if (c == '^' && currentMode() == InsetMath::MATH_MODE) {
1461                                 cur.backspace();
1462                                 cur.niceInsert(createInsetMath("mathcircumflex"));
1463                         } else if (c == '{') {
1464                                 cur.backspace();
1465                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1466                         } else if (c == '%') {
1467                                 cur.backspace();
1468                                 cur.niceInsert(MathAtom(new InsetMathComment));
1469                         } else if (c == '#') {
1470                                 LASSERT(cur.activeMacro(), /**/);
1471                                 cur.activeMacro()->setName(name + docstring(1, c));
1472                         } else {
1473                                 cur.backspace();
1474                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1475                         }
1476                         return true;
1477                 }
1478
1479                 // One character big delimiters. The others are handled in
1480                 // interpretString().
1481                 latexkeys const * l = in_word_set(name.substr(1));
1482                 if (name[0] == '\\' && l && l->inset == "big") {
1483                         docstring delim;
1484                         switch (c) {
1485                         case '{':
1486                                 delim = from_ascii("\\{");
1487                                 break;
1488                         case '}':
1489                                 delim = from_ascii("\\}");
1490                                 break;
1491                         default:
1492                                 delim = docstring(1, c);
1493                                 break;
1494                         }
1495                         if (InsetMathBig::isBigInsetDelim(delim)) {
1496                                 // name + delim ared a valid InsetMathBig.
1497                                 // We can't use cur.macroModeClose() because
1498                                 // it does not handle delim.
1499                                 InsetMathUnknown * p = cur.activeMacro();
1500                                 p->finalize();
1501                                 --cur.pos();
1502                                 cur.cell().erase(cur.pos());
1503                                 cur.plainInsert(MathAtom(
1504                                         new InsetMathBig(name.substr(1), delim)));
1505                                 return true;
1506                         }
1507                 }
1508
1509                 // leave macro mode and try again if necessary
1510                 cur.macroModeClose();
1511                 if (c == '{')
1512                         cur.niceInsert(MathAtom(new InsetMathBrace));
1513                 else if (c != ' ')
1514                         interpretChar(cur, c);
1515                 return true;
1516         }
1517
1518
1519         // leave autocorrect mode if necessary
1520         if (lyxrc.autocorrection_math && c == ' ' && cur.autocorrect()) {
1521                 cur.autocorrect() = false;
1522                 cur.message(_("Autocorrect Off ('!' to enter)"));
1523                 return true;
1524         } 
1525         if (lyxrc.autocorrection_math && c == '!' && !cur.autocorrect()) {
1526                 cur.autocorrect() = true;
1527                 cur.message(_("Autocorrect On (<space> to exit)"));
1528                 return true;
1529         }
1530
1531         // just clear selection on pressing the space bar
1532         if (cur.selection() && c == ' ') {
1533                 cur.setSelection(false);
1534                 return true;
1535         }
1536
1537         if (c == '\\') {
1538                 //lyxerr << "starting with macro" << endl;
1539                 bool reduced = cap::reduceSelectionToOneCell(cur);
1540                 if (reduced || !cur.selection()) {
1541                         docstring const safe = cap::grabAndEraseSelection(cur);
1542                         cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1543                 }
1544                 return true;
1545         }
1546
1547         selClearOrDel(cur);
1548
1549         if (c == '\n') {
1550                 if (currentMode() == InsetMath::TEXT_MODE)
1551                         cur.insert(c);
1552                 return true;
1553         }
1554
1555         if (c == ' ') {
1556                 if (currentMode() == InsetMath::TEXT_MODE) {
1557                         // insert spaces in text mode,
1558                         // but suppress direct insertion of two spaces in a row
1559                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1560                         // it is better than nothing...
1561                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1562                                 cur.insert(c);
1563                                 // FIXME: we have to enable full redraw here because of the
1564                                 // visual box corners that define the inset. If we know for
1565                                 // sure that we stay within the same cell we can optimize for
1566                                 // that using:
1567                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1568                         }
1569                         return true;
1570                 }
1571                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1572                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1573                         // FIXME: we have to enable full redraw here because of the
1574                         // visual box corners that define the inset. If we know for
1575                         // sure that we stay within the same cell we can optimize for
1576                         // that using:
1577                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1578                         return true;
1579                 }
1580
1581                 if (cur.popForward()) {
1582                         // FIXME: we have to enable full redraw here because of the
1583                         // visual box corners that define the inset. If we know for
1584                         // sure that we stay within the same cell we can optimize for
1585                         // that using:
1586                         //cur.updateFlags(Update::FitCursor);
1587                         return true;
1588                 }
1589
1590                 // if we are at the very end, leave the formula
1591                 return cur.pos() != cur.lastpos();
1592         }
1593
1594         // These should be treated differently when not in text mode:
1595         if (currentMode() != InsetMath::TEXT_MODE) {
1596                 if (c == '_') {
1597                         script(cur, false, save_selection);
1598                         return true;
1599                 }
1600                 if (c == '^') {
1601                         script(cur, true, save_selection);
1602                         return true;
1603                 }
1604                 if (c == '~') {
1605                         cur.niceInsert(createInsetMath("sim"));
1606                         return true;
1607                 }
1608         } else {
1609                 if (c == '^') {
1610                         cur.niceInsert(createInsetMath("textasciicircum"));
1611                         return true;
1612                 }
1613                 if (c == '~') {
1614                         cur.niceInsert(createInsetMath("textasciitilde"));
1615                         return true;
1616                 }
1617         }
1618
1619         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1620             c == '%' || c == '_') {
1621                 cur.niceInsert(createInsetMath(docstring(1, c)));
1622                 return true;
1623         }
1624
1625
1626         // try auto-correction
1627         if (lyxrc.autocorrection_math && cur.autocorrect() && cur.pos() != 0 && math_autocorrect(cur.prevAtom(), c))
1628                 return true;
1629
1630         // no special circumstances, so insert the character without any fuss
1631         cur.insert(c);
1632         if (lyxrc.autocorrection_math) {
1633                 if (!cur.autocorrect())
1634                         cur.message(_("Autocorrect Off ('!' to enter)"));
1635                 else
1636                         cur.message(_("Autocorrect On (<space> to exit)"));
1637         }
1638         return true;
1639 }
1640
1641
1642 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1643 {
1644         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1645         // possible
1646         if (!cur.empty() && cur.pos() > 0 &&
1647             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1648                 if (InsetMathBig::isBigInsetDelim(str)) {
1649                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1650                         if (prev[0] == '\\') {
1651                                 prev = prev.substr(1);
1652                                 latexkeys const * l = in_word_set(prev);
1653                                 if (l && l->inset == "big") {
1654                                         cur.cell()[cur.pos() - 1] =
1655                                                 MathAtom(new InsetMathBig(prev, str));
1656                                         return true;
1657                                 }
1658                         }
1659                 }
1660         }
1661         return false;
1662 }
1663
1664
1665 bool InsetMathNest::script(Cursor & cur, bool up)
1666 {
1667         return script(cur, up, docstring());
1668 }
1669
1670
1671 bool InsetMathNest::script(Cursor & cur, bool up,
1672                 docstring const & save_selection)
1673 {
1674         // Hack to get \^ and \_ working
1675         //lyxerr << "handling script: up: " << up << endl;
1676         if (cur.inMacroMode() && cur.macroName() == "\\") {
1677                 if (up)
1678                         cur.niceInsert(createInsetMath("mathcircumflex"));
1679                 else
1680                         interpretChar(cur, '_');
1681                 return true;
1682         }
1683
1684         cur.macroModeClose();
1685         if (asScriptInset() && cur.idx() == 0) {
1686                 // we are in a nucleus of a script inset, move to _our_ script
1687                 InsetMathScript * inset = asScriptInset();
1688                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1689                 inset->ensure(up);
1690                 cur.idx() = inset->idxOfScript(up);
1691                 cur.pos() = 0;
1692         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1693                 --cur.pos();
1694                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1695                 cur.push(*inset);
1696                 inset->ensure(up);
1697                 cur.idx() = inset->idxOfScript(up);
1698                 cur.pos() = cur.lastpos();
1699         } else {
1700                 // convert the thing to our left to a scriptinset or create a new
1701                 // one if in the very first position of the array
1702                 if (cur.pos() == 0) {
1703                         //lyxerr << "new scriptinset" << endl;
1704                         cur.insert(new InsetMathScript(up));
1705                 } else {
1706                         //lyxerr << "converting prev atom " << endl;
1707                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1708                 }
1709                 --cur.pos();
1710                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1711                 // See comment in MathParser.cpp for special handling of {}-bases
1712
1713                 cur.push(*inset);
1714                 cur.idx() = 1;
1715                 cur.pos() = 0;
1716         }
1717         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1718         cur.niceInsert(save_selection);
1719         cur.resetAnchor();
1720         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1721         return true;
1722 }
1723
1724
1725 bool InsetMathNest::completionSupported(Cursor const & cur) const
1726 {
1727         return cur.inMacroMode();
1728 }
1729
1730
1731 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1732 {
1733         return cur.inMacroMode();
1734 }
1735
1736
1737 bool InsetMathNest::automaticInlineCompletion() const
1738 {
1739         return lyxrc.completion_inline_math;
1740 }
1741
1742
1743 bool InsetMathNest::automaticPopupCompletion() const
1744 {
1745         return lyxrc.completion_popup_math;
1746 }
1747
1748
1749 CompletionList const *
1750 InsetMathNest::createCompletionList(Cursor const & cur) const
1751 {
1752         if (!cur.inMacroMode())
1753                 return 0;
1754
1755         return new MathCompletionList(cur);
1756 }
1757
1758
1759 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1760 {
1761         if (!cur.inMacroMode())
1762                 return docstring();
1763
1764         return cur.activeMacro()->name();
1765 }
1766
1767
1768 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1769                                      bool finished)
1770 {
1771         if (!cur.inMacroMode())
1772                 return false;
1773
1774         // append completion to active macro
1775         InsetMathUnknown * inset = cur.activeMacro();
1776         inset->setName(inset->name() + s);
1777
1778         // finish macro
1779         if (finished) {
1780 #if 0
1781                 // FIXME: this creates duplicates in the completion popup
1782                 // which looks ugly. Moreover the changes the list lengths
1783                 // which seems to
1784                 confuse the popup as well.
1785                 MathCompletionList::addToFavorites(inset->name());
1786 #endif
1787                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1788         }
1789
1790         return true;
1791 }
1792
1793
1794 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y,
1795                                         Dimension & dim) const
1796 {
1797         Inset const * inset = cur.activeMacro();
1798         if (!inset)
1799                 return;
1800
1801         // get inset dimensions
1802         dim = cur.bv().coordCache().insets().dim(inset);
1803         // FIXME: these 3 are no accurate, but should depend on the font.
1804         // Now the popup jumps down if you enter a char with descent > 0.
1805         dim.des += 3;
1806         dim.asc += 3;
1807
1808         // and position
1809         Point xy
1810         = cur.bv().coordCache().insets().xy(inset);
1811         x = xy.x_;
1812         y = xy.y_;
1813 }
1814
1815
1816 bool InsetMathNest::cursorMathForward(Cursor & cur)
1817 {
1818         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1819                 cur.pushBackward(*cur.nextAtom().nucleus());
1820                 cur.inset().idxFirst(cur);
1821                 return true;
1822         }
1823         if (cur.posForward() || idxForward(cur))
1824                 return true;
1825         // try to pop forwards --- but don't pop out of math! leave that to
1826         // the FINISH lfuns
1827         int s = cur.depth() - 2;
1828         if (s >= 0 && cur[s].inset().asInsetMath())
1829                 return cur.popForward();
1830         return false;
1831 }
1832
1833
1834 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1835 {
1836         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1837                 cur.posBackward();
1838                 cur.push(*cur.nextAtom().nucleus());
1839                 cur.inset().idxLast(cur);
1840                 return true;
1841         }
1842         if (cur.posBackward() || idxBackward(cur))
1843                 return true;
1844         // try to pop backwards --- but don't pop out of math! leave that to
1845         // the FINISH lfuns
1846         int s = cur.depth() - 2;
1847         if (s >= 0 && cur[s].inset().asInsetMath())
1848                 return cur.popBackward();
1849         return false;
1850 }
1851
1852
1853 ////////////////////////////////////////////////////////////////////
1854
1855 MathCompletionList::MathCompletionList(Cursor const & cur)
1856 {
1857         // fill it with macros from the buffer
1858         MacroNameSet macros;
1859         cur.buffer()->listMacroNames(macros);
1860         MacroNameSet::const_iterator it;
1861         for (it = macros.begin(); it != macros.end(); ++it) {
1862                 if (cur.buffer()->getMacro(*it, cur, false))
1863                         locals.push_back("\\" + *it);
1864         }
1865         sort(locals.begin(), locals.end());
1866
1867         if (globals.size() > 0)
1868                 return;
1869
1870         // fill in global macros
1871         macros.clear();
1872         MacroTable::globalMacros().getMacroNames(macros);
1873         //lyxerr << "Globals completion macros: ";
1874         for (it = macros.begin(); it != macros.end(); ++it) {
1875                 //lyxerr << "\\" + *it << " ";
1876                 globals.push_back("\\" + *it);
1877         }
1878         //lyxerr << std::endl;
1879
1880         // fill in global commands
1881         globals.push_back(from_ascii("\\boxed"));
1882         globals.push_back(from_ascii("\\fbox"));
1883         globals.push_back(from_ascii("\\framebox"));
1884         globals.push_back(from_ascii("\\makebox"));
1885         globals.push_back(from_ascii("\\kern"));
1886         globals.push_back(from_ascii("\\xrightarrow"));
1887         globals.push_back(from_ascii("\\xleftarrow"));
1888         globals.push_back(from_ascii("\\split"));
1889         globals.push_back(from_ascii("\\gathered"));
1890         globals.push_back(from_ascii("\\aligned"));
1891         globals.push_back(from_ascii("\\alignedat"));
1892         globals.push_back(from_ascii("\\cases"));
1893         globals.push_back(from_ascii("\\substack"));
1894         globals.push_back(from_ascii("\\xymatrix"));
1895         globals.push_back(from_ascii("\\subarray"));
1896         globals.push_back(from_ascii("\\array"));
1897         globals.push_back(from_ascii("\\sqrt"));
1898         globals.push_back(from_ascii("\\root"));
1899         globals.push_back(from_ascii("\\tabular"));
1900         globals.push_back(from_ascii("\\stackrel"));
1901         globals.push_back(from_ascii("\\binom"));
1902         globals.push_back(from_ascii("\\choose"));
1903         globals.push_back(from_ascii("\\brace"));
1904         globals.push_back(from_ascii("\\brack"));
1905         globals.push_back(from_ascii("\\frac"));
1906         globals.push_back(from_ascii("\\over"));
1907         globals.push_back(from_ascii("\\nicefrac"));
1908         globals.push_back(from_ascii("\\unitfrac"));
1909         globals.push_back(from_ascii("\\unitfracthree"));
1910         globals.push_back(from_ascii("\\unitone"));
1911         globals.push_back(from_ascii("\\unittwo"));
1912         globals.push_back(from_ascii("\\infer"));
1913         globals.push_back(from_ascii("\\atop"));
1914         globals.push_back(from_ascii("\\lefteqn"));
1915         globals.push_back(from_ascii("\\boldsymbol"));
1916         globals.push_back(from_ascii("\\bm"));
1917         globals.push_back(from_ascii("\\color"));
1918         globals.push_back(from_ascii("\\normalcolor"));
1919         globals.push_back(from_ascii("\\textcolor"));
1920         globals.push_back(from_ascii("\\dfrac"));
1921         globals.push_back(from_ascii("\\tfrac"));
1922         globals.push_back(from_ascii("\\dbinom"));
1923         globals.push_back(from_ascii("\\tbinom"));
1924         globals.push_back(from_ascii("\\hphantom"));
1925         globals.push_back(from_ascii("\\phantom"));
1926         globals.push_back(from_ascii("\\vphantom"));
1927         MathWordList const & words = mathedWordList();
1928         MathWordList::const_iterator it2;
1929         //lyxerr << "Globals completion commands: ";
1930         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1931                 globals.push_back("\\" + (*it2).first);
1932                 //lyxerr << "\\" + (*it2).first << " ";
1933         }
1934         //lyxerr << std::endl;
1935         sort(globals.begin(), globals.end());
1936 }
1937
1938
1939 MathCompletionList::~MathCompletionList()
1940 {
1941 }
1942
1943
1944 size_type MathCompletionList::size() const
1945 {
1946         return locals.size() + globals.size();
1947 }
1948
1949
1950 docstring const & MathCompletionList::data(size_t idx) const
1951 {
1952         size_t lsize = locals.size();
1953         if (idx >= lsize)
1954                 return globals[idx - lsize];
1955         else
1956                 return locals[idx];
1957 }
1958
1959
1960 std::string MathCompletionList::icon(size_t idx) const
1961 {
1962         // get the latex command
1963         docstring cmd;
1964         size_t lsize = locals.size();
1965         if (idx >= lsize)
1966                 cmd = globals[idx - lsize];
1967         else
1968                 cmd = locals[idx];
1969
1970         // get the icon resource name by stripping the backslash
1971         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1972 }
1973
1974 std::vector<docstring> MathCompletionList::globals;
1975
1976 } // namespace lyx