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