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