]> git.lyx.org Git - lyx.git/blob - src/mathed/InsetMathNest.cpp
8874b5b74050dd83110e5b7b3646d05c8c4bf50a
[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                                         && ar[0]->asNestInset()->nargs())
1079                                 handleNest(cur, ar[0]);
1080                         else
1081                                 cur.niceInsert(cmd.argument());
1082                 }
1083                 break;
1084                 }
1085
1086         case LFUN_DIALOG_SHOW_NEW_INSET: {
1087                 docstring const & name = cmd.argument();
1088                 string data;
1089                 if (name == "ref") {
1090                         InsetMathRef tmp(name);
1091                         data = tmp.createDialogStr(to_utf8(name));
1092                 }
1093                 cur.bv().showDialog(to_utf8(name), data);
1094                 break;
1095         }
1096
1097         case LFUN_INSET_INSERT: {
1098                 MathData ar;
1099                 if (createInsetMath_fromDialogStr(cmd.argument(), ar)) {
1100                         cur.recordUndoSelection();
1101                         cur.insert(ar);
1102                 } else
1103                         cur.undispatched();
1104                 break;
1105         }
1106         case LFUN_INSET_DISSOLVE:
1107                 if (!asHullInset()) {
1108                         cur.recordUndoInset();
1109                         cur.pullArg();
1110                 }
1111                 break;
1112
1113         default:
1114                 InsetMath::doDispatch(cur, cmd);
1115                 break;
1116         }
1117 }
1118
1119
1120 bool InsetMathNest::findMacroToFoldUnfold(Cursor & it, bool fold) const {
1121         // look for macro to open/close, but stay in mathed
1122         for (; !it.empty(); it.pop_back()) {
1123                         
1124                 // go backward through the current cell
1125                 Inset * inset = it.nextInset();
1126                 while (inset && inset->asInsetMath()) {
1127                         MathMacro * macro = inset->asInsetMath()->asMacro();
1128                         if (macro) {
1129                                 // found the an macro to open/close?
1130                                 if (macro->folded() != fold)
1131                                         return true;
1132                                 
1133                                 // Wrong folding state.
1134                                 // If this was the first we see in this slice, look further left,
1135                                 // otherwise go up.
1136                                 if (inset != it.nextInset())
1137                                         break;
1138                         }
1139                         
1140                         // go up if this was the left most position
1141                         if (it.pos() == 0)
1142                                 break;
1143                         
1144                         // go left
1145                         it.pos()--;
1146                         inset = it.nextInset();
1147                 }
1148         }
1149         
1150         return false;
1151 }
1152
1153
1154 bool InsetMathNest::getStatus(Cursor & cur, FuncRequest const & cmd,
1155                 FuncStatus & flag) const
1156 {
1157         // the font related toggles
1158         //string tc = "mathnormal";
1159         bool ret = true;
1160         string const arg = to_utf8(cmd.argument());
1161         switch (cmd.action) {
1162         case LFUN_TABULAR_FEATURE:
1163                 flag.enabled(false);
1164                 break;
1165 #if 0
1166         case LFUN_TABULAR_FEATURE:
1167                 // FIXME: check temporarily disabled
1168                 // valign code
1169                 char align = mathcursor::valign();
1170                 if (align == '\0') {
1171                         enable = false;
1172                         break;
1173                 }
1174                 if (cmd.argument().empty()) {
1175                         flag.clear();
1176                         break;
1177                 }
1178                 if (!contains("tcb", cmd.argument()[0])) {
1179                         enable = false;
1180                         break;
1181                 }
1182                 flag.setOnOff(cmd.argument()[0] == align);
1183                 break;
1184 #endif
1185         /// We have to handle them since 1.4 blocks all unhandled actions
1186         case LFUN_FONT_ITAL:
1187         case LFUN_FONT_BOLD:
1188         case LFUN_FONT_SANS:
1189         case LFUN_FONT_EMPH:
1190         case LFUN_FONT_TYPEWRITER:
1191         case LFUN_FONT_NOUN:
1192         case LFUN_FONT_ROMAN:
1193         case LFUN_FONT_DEFAULT:
1194                 flag.enabled(true);
1195                 break;
1196         case LFUN_MATH_MUTATE:
1197                 //flag.setOnOff(mathcursor::formula()->hullType() == to_utf8(cmd.argument()));
1198                 flag.setOnOff(false);
1199                 break;
1200
1201         // we just need to be in math mode to enable that
1202         case LFUN_MATH_SIZE:
1203         case LFUN_MATH_SPACE:
1204         case LFUN_MATH_LIMITS:
1205         case LFUN_MATH_EXTERN:
1206                 flag.enabled(true);
1207                 break;
1208
1209         case LFUN_FONT_FRAK:
1210                 flag.enabled(currentMode() != TEXT_MODE);
1211                 break;
1212
1213         case LFUN_MATH_INSERT: {
1214                 bool const textarg =
1215                         arg == "\\textbf"   || arg == "\\textsf" ||
1216                         arg == "\\textrm"   || arg == "\\textmd" ||
1217                         arg == "\\textit"   || arg == "\\textsc" ||
1218                         arg == "\\textsl"   || arg == "\\textup" ||
1219                         arg == "\\texttt"   || arg == "\\textbb" ||
1220                         arg == "\\textnormal";
1221                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1222                 break;
1223         }
1224
1225         case LFUN_MATH_MATRIX:
1226                 flag.enabled(currentMode() == MATH_MODE);
1227                 break;
1228
1229         case LFUN_INSET_INSERT: {
1230                 // Don't test createMathInset_fromDialogStr(), since
1231                 // getStatus is not called with a valid reference and the
1232                 // dialog would not be applyable.
1233                 string const name = cmd.getArg(0);
1234                 flag.enabled(name == "ref");
1235                 break;
1236         }
1237
1238         case LFUN_MATH_DELIM:
1239         case LFUN_MATH_BIGDELIM:
1240                 // Don't do this with multi-cell selections
1241                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1242                 break;
1243                 
1244         case LFUN_MATH_MACRO_FOLD:
1245         case LFUN_MATH_MACRO_UNFOLD: {
1246                 Cursor it = cur;
1247                 bool found = findMacroToFoldUnfold(it, cmd.action == LFUN_MATH_MACRO_FOLD);
1248                 flag.enabled(found);
1249                 break;
1250         }
1251                 
1252         case LFUN_SPECIALCHAR_INSERT:
1253                 // FIXME: These would probably make sense in math-text mode
1254                 flag.enabled(false);
1255                 break;
1256
1257         case LFUN_INSET_DISSOLVE:
1258                 flag.enabled(!asHullInset());
1259                 break;
1260
1261         default:
1262                 ret = false;
1263                 break;
1264         }
1265         return ret;
1266 }
1267
1268
1269 void InsetMathNest::edit(Cursor & cur, bool front, EntryDirection entry_from)
1270 {
1271         cur.push(*this);
1272         bool enter_front = (entry_from == Inset::ENTRY_DIRECTION_RIGHT || 
1273                 (entry_from == Inset::ENTRY_DIRECTION_IGNORE && front));
1274         cur.idx() = enter_front ? 0 : cur.lastidx();
1275         cur.pos() = enter_front ? 0 : cur.lastpos();
1276         cur.resetAnchor();
1277         //lyxerr << "InsetMathNest::edit, cur:\n" << cur << endl;
1278 }
1279
1280
1281 Inset * InsetMathNest::editXY(Cursor & cur, int x, int y)
1282 {
1283         int idx_min = 0;
1284         int dist_min = 1000000;
1285         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1286                 int const d = cell(i).dist(cur.bv(), x, y);
1287                 if (d < dist_min) {
1288                         dist_min = d;
1289                         idx_min = i;
1290                 }
1291         }
1292         MathData & ar = cell(idx_min);
1293         cur.push(*this);
1294         cur.idx() = idx_min;
1295         cur.pos() = ar.x2pos(&cur.bv(), x - ar.xo(cur.bv()));
1296
1297         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1298         if (dist_min == 0) {
1299                 // hit inside cell
1300                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1301                         if (ar[i]->covers(cur.bv(), x, y))
1302                                 return ar[i].nucleus()->editXY(cur, x, y);
1303         }
1304         return this;
1305 }
1306
1307
1308 void InsetMathNest::lfunMousePress(Cursor & cur, FuncRequest & cmd)
1309 {
1310         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1311         BufferView & bv = cur.bv();
1312         bool do_selection = cmd.button() == mouse_button::button1
1313                 && cmd.argument() == "region-select";
1314         bv.mouseSetCursor(cur, do_selection);
1315         if (cmd.button() == mouse_button::button1) {
1316                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1317                 // Update the cursor update flags as needed:
1318                 //
1319                 // Update::Decoration: tells to update the decoration
1320                 //                     (visual box corners that define
1321                 //                     the inset)/
1322                 // Update::FitCursor: adjust the screen to the cursor
1323                 //                    position if needed
1324                 // cur.result().update(): don't overwrite previously set flags.
1325                 cur.updateFlags(Update::Decoration | Update::FitCursor 
1326                                 | cur.result().update());
1327         } else if (cmd.button() == mouse_button::button2) {
1328                 if (cap::selection()) {
1329                         // See comment in Text::dispatch why we do this
1330                         cap::copySelectionToStack();
1331                         cmd = FuncRequest(LFUN_PASTE, "0");
1332                         doDispatch(bv.cursor(), cmd);
1333                 } else {
1334                         MathData ar;
1335                         asArray(theSelection().get(), ar);
1336                         bv.cursor().insert(ar);
1337                 }
1338         }
1339 }
1340
1341
1342 void InsetMathNest::lfunMouseMotion(Cursor & cur, FuncRequest & cmd)
1343 {
1344         // only select with button 1
1345         if (cmd.button() == mouse_button::button1) {
1346                 Cursor & bvcur = cur.bv().cursor();
1347                 if (bvcur.anchor_.hasPart(cur)) {
1348                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1349                         bvcur.setCursor(cur);
1350                         bvcur.selection() = true;
1351                         //lyxerr << "MOTION " << bvcur << endl;
1352                 } else
1353                         cur.undispatched();
1354         }
1355 }
1356
1357
1358 void InsetMathNest::lfunMouseRelease(Cursor & cur, FuncRequest & cmd)
1359 {
1360         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1361
1362         if (cmd.button() == mouse_button::button1) {
1363                 if (!cur.selection())
1364                         cur.noUpdate();
1365                 else {
1366                         Cursor & bvcur = cur.bv().cursor();
1367                         bvcur.selection() = true;
1368                 }
1369                 return;
1370         }
1371
1372         cur.undispatched();
1373 }
1374
1375
1376 bool InsetMathNest::interpretChar(Cursor & cur, char_type c)
1377 {
1378         //lyxerr << "interpret 2: '" << c << "'" << endl;
1379         docstring save_selection;
1380         if (c == '^' || c == '_')
1381                 save_selection = grabAndEraseSelection(cur);
1382
1383         cur.clearTargetX();
1384
1385         // handle macroMode
1386         if (cur.inMacroMode()) {
1387                 docstring name = cur.macroName();
1388
1389                 /// are we currently typing '#1' or '#2' or...?
1390                 if (name == "\\#") {
1391                         cur.backspace();
1392                         int n = c - '0';
1393                         if (n >= 1 && n <= 9)
1394                                 cur.insert(new MathMacroArgument(n));
1395                         return true;
1396                 }
1397
1398                 // do not finish macro for known * commands
1399                 MathWordList const & mwl = mathedWordList();
1400                 bool star_macro = c == '*'
1401                         && (mwl.find(name.substr(1) + "*") != mwl.end()
1402                             || cur.buffer().getMacro(name.substr(1) + "*", cur, true));
1403                 if (isAlphaASCII(c) || star_macro) {
1404                         cur.activeMacro()->setName(name + docstring(1, c));
1405                         return true;
1406                 }
1407
1408                 // handle 'special char' macros
1409                 if (name == "\\") {
1410                         // remove the '\\'
1411                         if (c == '\\') {
1412                                 cur.backspace();
1413                                 if (currentMode() == InsetMath::TEXT_MODE)
1414                                         cur.niceInsert(createInsetMath("textbackslash"));
1415                                 else
1416                                         cur.niceInsert(createInsetMath("backslash"));
1417                         } else if (c == '{') {
1418                                 cur.backspace();
1419                                 cur.niceInsert(MathAtom(new InsetMathBrace));
1420                         } else if (c == '%') {
1421                                 cur.backspace();
1422                                 cur.niceInsert(MathAtom(new InsetMathComment));
1423                         } else if (c == '#') {
1424                                 BOOST_ASSERT(cur.activeMacro());
1425                                 cur.activeMacro()->setName(name + docstring(1, c));
1426                         } else {
1427                                 cur.backspace();
1428                                 cur.niceInsert(createInsetMath(docstring(1, c)));
1429                         }
1430                         return true;
1431                 }
1432
1433                 // One character big delimiters. The others are handled in
1434                 // interpretString().
1435                 latexkeys const * l = in_word_set(name.substr(1));
1436                 if (name[0] == '\\' && l && l->inset == "big") {
1437                         docstring delim;
1438                         switch (c) {
1439                         case '{':
1440                                 delim = from_ascii("\\{");
1441                                 break;
1442                         case '}':
1443                                 delim = from_ascii("\\}");
1444                                 break;
1445                         default:
1446                                 delim = docstring(1, c);
1447                                 break;
1448                         }
1449                         if (InsetMathBig::isBigInsetDelim(delim)) {
1450                                 // name + delim ared a valid InsetMathBig.
1451                                 // We can't use cur.macroModeClose() because
1452                                 // it does not handle delim.
1453                                 InsetMathUnknown * p = cur.activeMacro();
1454                                 p->finalize();
1455                                 --cur.pos();
1456                                 cur.cell().erase(cur.pos());
1457                                 cur.plainInsert(MathAtom(
1458                                         new InsetMathBig(name.substr(1), delim)));
1459                                 return true;
1460                         }
1461                 }
1462
1463                 // leave macro mode and try again if necessary
1464                 cur.macroModeClose();
1465                 if (c == '{')
1466                         cur.niceInsert(MathAtom(new InsetMathBrace));
1467                 else if (c != ' ')
1468                         interpretChar(cur, c);
1469                 return true;
1470         }
1471
1472         // This is annoying as one has to press <space> far too often.
1473         // Disable it.
1474
1475 #if 0
1476                 // leave autocorrect mode if necessary
1477                 if (autocorrect() && c == ' ') {
1478                         autocorrect() = false;
1479                         return true;
1480                 }
1481 #endif
1482
1483         // just clear selection on pressing the space bar
1484         if (cur.selection() && c == ' ') {
1485                 cur.selection() = false;
1486                 return true;
1487         }
1488
1489         if (c == '\\') {
1490                 //lyxerr << "starting with macro" << endl;
1491                 bool reduced = cap::reduceSelectionToOneCell(cur);
1492                 if (reduced || !cur.selection()) {
1493                         docstring const safe = cap::grabAndEraseSelection(cur);
1494                         cur.insert(MathAtom(new InsetMathUnknown(from_ascii("\\"), safe, false)));
1495                 }
1496                 return true;
1497         }
1498
1499         selClearOrDel(cur);
1500
1501         if (c == '\n') {
1502                 if (currentMode() == InsetMath::TEXT_MODE)
1503                         cur.insert(c);
1504                 return true;
1505         }
1506
1507         if (c == ' ') {
1508                 if (currentMode() == InsetMath::TEXT_MODE) {
1509                         // insert spaces in text mode,
1510                         // but suppress direct insertion of two spaces in a row
1511                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1512                         // it is better than nothing...
1513                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ') {
1514                                 cur.insert(c);
1515                                 // FIXME: we have to enable full redraw here because of the
1516                                 // visual box corners that define the inset. If we know for
1517                                 // sure that we stay within the same cell we can optimize for
1518                                 // that using:
1519                                 //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1520                         }
1521                         return true;
1522                 }
1523                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1524                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1525                         // FIXME: we have to enable full redraw here because of the
1526                         // visual box corners that define the inset. If we know for
1527                         // sure that we stay within the same cell we can optimize for
1528                         // that using:
1529                         //cur.updateFlags(Update::SinglePar | Update::FitCursor);
1530                         return true;
1531                 }
1532
1533                 if (cur.popForward()) {
1534                         // FIXME: we have to enable full redraw here because of the
1535                         // visual box corners that define the inset. If we know for
1536                         // sure that we stay within the same cell we can optimize for
1537                         // that using:
1538                         //cur.updateFlags(Update::FitCursor);
1539                         return true;
1540                 }
1541
1542                 // if we are at the very end, leave the formula
1543                 return cur.pos() != cur.lastpos();
1544         }
1545
1546         // These shouldn't work in text mode:
1547         if (currentMode() != InsetMath::TEXT_MODE) {
1548                 if (c == '_') {
1549                         script(cur, false, save_selection);
1550                         return true;
1551                 }
1552                 if (c == '^') {
1553                         script(cur, true, save_selection);
1554                         return true;
1555                 }
1556                 if (c == '~') {
1557                         cur.niceInsert(createInsetMath("sim"));
1558                         return true;
1559                 }
1560         }
1561
1562         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1563             c == '%' || c == '_' || c == '^') {
1564                 cur.niceInsert(createInsetMath(docstring(1, c)));
1565                 return true;
1566         }
1567
1568
1569         // try auto-correction
1570         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1571         //      return true;
1572
1573         // no special circumstances, so insert the character without any fuss
1574         cur.insert(c);
1575         cur.autocorrect() = true;
1576         return true;
1577 }
1578
1579
1580 bool InsetMathNest::interpretString(Cursor & cur, docstring const & str)
1581 {
1582         // Create a InsetMathBig from cur.cell()[cur.pos() - 1] and t if
1583         // possible
1584         if (!cur.empty() && cur.pos() > 0 &&
1585             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1586                 if (InsetMathBig::isBigInsetDelim(str)) {
1587                         docstring prev = asString(cur.cell()[cur.pos() - 1]);
1588                         if (prev[0] == '\\') {
1589                                 prev = prev.substr(1);
1590                                 latexkeys const * l = in_word_set(prev);
1591                                 if (l && l->inset == "big") {
1592                                         cur.cell()[cur.pos() - 1] =
1593                                                 MathAtom(new InsetMathBig(prev, str));
1594                                         return true;
1595                                 }
1596                         }
1597                 }
1598         }
1599         return false;
1600 }
1601
1602
1603 bool InsetMathNest::script(Cursor & cur, bool up)
1604 {
1605         return script(cur, up, docstring());
1606 }
1607
1608
1609 bool InsetMathNest::script(Cursor & cur, bool up,
1610                 docstring const & save_selection)
1611 {
1612         // Hack to get \^ and \_ working
1613         //lyxerr << "handling script: up: " << up << endl;
1614         if (cur.inMacroMode() && cur.macroName() == "\\") {
1615                 if (up)
1616                         cur.niceInsert(createInsetMath("mathcircumflex"));
1617                 else
1618                         interpretChar(cur, '_');
1619                 return true;
1620         }
1621
1622         cur.macroModeClose();
1623         if (asScriptInset() && cur.idx() == 0) {
1624                 // we are in a nucleus of a script inset, move to _our_ script
1625                 InsetMathScript * inset = asScriptInset();
1626                 //lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1627                 inset->ensure(up);
1628                 cur.idx() = inset->idxOfScript(up);
1629                 cur.pos() = 0;
1630         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1631                 --cur.pos();
1632                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1633                 cur.push(*inset);
1634                 inset->ensure(up);
1635                 cur.idx() = inset->idxOfScript(up);
1636                 cur.pos() = cur.lastpos();
1637         } else {
1638                 // convert the thing to our left to a scriptinset or create a new
1639                 // one if in the very first position of the array
1640                 if (cur.pos() == 0) {
1641                         //lyxerr << "new scriptinset" << endl;
1642                         cur.insert(new InsetMathScript(up));
1643                 } else {
1644                         //lyxerr << "converting prev atom " << endl;
1645                         cur.prevAtom() = MathAtom(new InsetMathScript(cur.prevAtom(), up));
1646                 }
1647                 --cur.pos();
1648                 InsetMathScript * inset = cur.nextAtom().nucleus()->asScriptInset();
1649                 // See comment in MathParser.cpp for special handling of {}-bases
1650
1651                 cur.push(*inset);
1652                 cur.idx() = 1;
1653                 cur.pos() = 0;
1654         }
1655         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1656         cur.niceInsert(save_selection);
1657         cur.resetAnchor();
1658         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1659         return true;
1660 }
1661
1662
1663 bool InsetMathNest::completionSupported(Cursor const & cur) const
1664 {
1665         return cur.inMacroMode();
1666 }
1667
1668
1669 bool InsetMathNest::inlineCompletionSupported(Cursor const & cur) const
1670 {
1671         return cur.inMacroMode();
1672 }
1673
1674
1675 bool InsetMathNest::automaticInlineCompletion() const
1676 {
1677         return lyxrc.completion_inline_math;
1678 }
1679
1680
1681 bool InsetMathNest::automaticPopupCompletion() const
1682 {
1683         return lyxrc.completion_popup_math;
1684 }
1685
1686
1687 CompletionList const *
1688 InsetMathNest::createCompletionList(Cursor const & cur) const
1689 {
1690         if (!cur.inMacroMode())
1691                 return 0;
1692         
1693         return new MathCompletionList(cur);
1694 }
1695
1696
1697 docstring InsetMathNest::completionPrefix(Cursor const & cur) const
1698 {
1699         if (!cur.inMacroMode())
1700                 return docstring();
1701         
1702         return cur.activeMacro()->name();
1703 }
1704
1705
1706 bool InsetMathNest::insertCompletion(Cursor & cur, docstring const & s,
1707                                      bool finished)
1708 {
1709         if (!cur.inMacroMode())
1710                 return false;
1711
1712         // append completion to active macro
1713         InsetMathUnknown * inset = cur.activeMacro();
1714         inset->setName(inset->name() + s);
1715
1716         // finish macro
1717         if (finished) {
1718 #if 0
1719                 // FIXME: this creates duplicates in the completion popup
1720                 // which looks ugly. Moreover the changes the list lengths
1721                 // which seems to
1722                 confuse the popup as well.
1723                 MathCompletionList::addToFavorites(inset->name());
1724 #endif
1725                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, " "));
1726         }
1727
1728         return true;
1729 }
1730
1731
1732 void InsetMathNest::completionPosAndDim(Cursor const & cur, int & x, int & y, 
1733                                         Dimension & dim) const
1734 {
1735         Inset const * inset = cur.activeMacro();
1736         if (!inset)
1737                 return;
1738
1739         // get inset dimensions
1740         dim = cur.bv().coordCache().insets().dim(inset);
1741         // FIXME: these 3 are no accurate, but should depend on the font.
1742         // Now the popup jumps down if you enter a char with descent > 0.
1743         dim.des += 3;
1744         dim.asc += 3;
1745
1746         // and position
1747         Point xy
1748         = cur.bv().coordCache().insets().xy(inset);
1749         x = xy.x_;
1750         y = xy.y_;
1751 }
1752
1753
1754 bool InsetMathNest::cursorMathForward(Cursor & cur)
1755 {
1756         if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
1757                 cur.pushBackward(*cur.nextAtom().nucleus());
1758                 cur.inset().idxFirst(cur);
1759                 return true;
1760         } 
1761         if (cur.posForward() || idxForward(cur))
1762                 return true;
1763         // try to pop forwards --- but don't pop out of math! leave that to
1764         // the FINISH lfuns
1765         int s = cur.depth() - 2;
1766         if (s >= 0 && cur[s].inset().asInsetMath())
1767                 return cur.popForward();
1768         return false;
1769 }
1770
1771
1772 bool InsetMathNest::cursorMathBackward(Cursor & cur)
1773 {
1774         if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
1775                 cur.posBackward();
1776                 cur.push(*cur.nextAtom().nucleus());
1777                 cur.inset().idxLast(cur);
1778                 return true;
1779         } 
1780         if (cur.posBackward() || idxBackward(cur))
1781                 return true;
1782         // try to pop backwards --- but don't pop out of math! leave that to 
1783         // the FINISH lfuns
1784         int s = cur.depth() - 2;
1785         if (s >= 0 && cur[s].inset().asInsetMath())
1786                 return cur.popBackward();
1787         return false;
1788 }
1789
1790
1791 ////////////////////////////////////////////////////////////////////
1792
1793 MathCompletionList::MathCompletionList(Cursor const & cur)
1794 {
1795         // fill it with macros from the buffer
1796         MacroNameSet macros;
1797         cur.buffer().listMacroNames(macros);
1798         MacroNameSet::const_iterator it;
1799         for (it = macros.begin(); it != macros.end(); ++it) {
1800                 if (cur.buffer().getMacro(*it, cur, false))
1801                         locals.push_back("\\" + *it);
1802         }
1803         sort(locals.begin(), locals.end());
1804
1805         if (globals.size() > 0)
1806                 return;
1807
1808         // fill in global macros
1809         macros.clear();
1810         MacroTable::globalMacros().getMacroNames(macros);
1811         lyxerr << "Globals completion macros: ";
1812         for (it = macros.begin(); it != macros.end(); ++it) {
1813                 lyxerr << "\\" + *it << " ";
1814                 globals.push_back("\\" + *it);
1815         }
1816         lyxerr << std::endl;
1817
1818         // fill in global commands
1819         globals.push_back(from_ascii("\\boxed"));
1820         globals.push_back(from_ascii("\\fbox"));
1821         globals.push_back(from_ascii("\\framebox"));
1822         globals.push_back(from_ascii("\\makebox"));
1823         globals.push_back(from_ascii("\\kern"));
1824         globals.push_back(from_ascii("\\xrightarrow"));
1825         globals.push_back(from_ascii("\\xleftarrow"));
1826         globals.push_back(from_ascii("\\split"));
1827         globals.push_back(from_ascii("\\gathered"));
1828         globals.push_back(from_ascii("\\aligned"));
1829         globals.push_back(from_ascii("\\alignedat"));
1830         globals.push_back(from_ascii("\\cases"));
1831         globals.push_back(from_ascii("\\substack"));
1832         globals.push_back(from_ascii("\\subarray"));
1833         globals.push_back(from_ascii("\\array"));
1834         globals.push_back(from_ascii("\\sqrt"));
1835         globals.push_back(from_ascii("\\root"));
1836         globals.push_back(from_ascii("\\tabular"));
1837         globals.push_back(from_ascii("\\stackrel"));
1838         globals.push_back(from_ascii("\\binom"));
1839         globals.push_back(from_ascii("\\choose"));
1840         globals.push_back(from_ascii("\\brace"));
1841         globals.push_back(from_ascii("\\brack"));
1842         globals.push_back(from_ascii("\\frac"));
1843         globals.push_back(from_ascii("\\over"));
1844         globals.push_back(from_ascii("\\nicefrac"));
1845         globals.push_back(from_ascii("\\unitfrac"));
1846         globals.push_back(from_ascii("\\unitfracthree"));
1847         globals.push_back(from_ascii("\\unitone"));
1848         globals.push_back(from_ascii("\\unittwo"));
1849         globals.push_back(from_ascii("\\infer"));
1850         globals.push_back(from_ascii("\\atop"));
1851         globals.push_back(from_ascii("\\lefteqn"));
1852         globals.push_back(from_ascii("\\boldsymbol"));
1853         globals.push_back(from_ascii("\\bm"));
1854         globals.push_back(from_ascii("\\color"));
1855         globals.push_back(from_ascii("\\normalcolor"));
1856         globals.push_back(from_ascii("\\textcolor"));
1857         globals.push_back(from_ascii("\\dfrac"));
1858         globals.push_back(from_ascii("\\tfrac"));
1859         globals.push_back(from_ascii("\\dbinom"));
1860         globals.push_back(from_ascii("\\tbinom"));
1861         globals.push_back(from_ascii("\\hphantom"));
1862         globals.push_back(from_ascii("\\phantom"));
1863         globals.push_back(from_ascii("\\vphantom"));
1864         MathWordList const & words = mathedWordList();
1865         MathWordList::const_iterator it2;
1866         lyxerr << "Globals completion commands: ";
1867         for (it2 = words.begin(); it2 != words.end(); ++it2) {
1868                 globals.push_back("\\" + (*it2).first);
1869                 lyxerr << "\\" + (*it2).first << " ";
1870         }
1871         lyxerr << std::endl;
1872         sort(globals.begin(), globals.end());
1873 }
1874
1875
1876 MathCompletionList::~MathCompletionList()
1877 {
1878 }
1879
1880
1881 size_type MathCompletionList::size() const
1882 {
1883         return locals.size() + globals.size();
1884 }
1885
1886
1887 docstring const & MathCompletionList::data(size_t idx) const
1888 {
1889         size_t lsize = locals.size();
1890         if (idx >= lsize)
1891                 return globals[idx - lsize];
1892         else
1893                 return locals[idx];
1894 }
1895
1896
1897 std::string MathCompletionList::icon(size_t idx) const 
1898 {
1899         // get the latex command
1900         docstring cmd;
1901         size_t lsize = locals.size();
1902         if (idx >= lsize)
1903                 cmd = globals[idx - lsize];
1904         else
1905                 cmd = locals[idx];
1906         
1907         // get the icon resource name by stripping the backslash
1908         return "images/math/" + to_utf8(cmd.substr(1)) + ".png";
1909 }
1910
1911 std::vector<docstring> MathCompletionList::globals;
1912
1913 } // namespace lyx