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