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