]> git.lyx.org Git - lyx.git/blob - src/mathed/math_nestinset.C
Remove the now superseeded SConscript files, and some small missing parts to SConstruct
[lyx.git] / src / mathed / math_nestinset.C
1 /**
2  * \file math_nestinset.C
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 "math_nestinset.h"
14
15 #include "math_arrayinset.h"
16 #include "math_biginset.h"
17 #include "math_boxinset.h"
18 #include "math_braceinset.h"
19 #include "math_colorinset.h"
20 #include "math_commentinset.h"
21 #include "math_data.h"
22 #include "math_deliminset.h"
23 #include "math_factory.h"
24 #include "math_hullinset.h"
25 #include "math_mathmlstream.h"
26 #include "math_macroarg.h"
27 //#include "math_mboxinset.h"
28 #include "math_parser.h"
29 #include "math_scriptinset.h"
30 #include "math_spaceinset.h"
31 #include "math_symbolinset.h"
32 #include "math_support.h"
33 #include "math_unknowninset.h"
34 #include "ref_inset.h"
35
36 #include "BufferView.h"
37 #include "CutAndPaste.h"
38 #include "FuncStatus.h"
39 #include "LColor.h"
40 #include "bufferview_funcs.h"
41 #include "coordcache.h"
42 #include "cursor.h"
43 #include "debug.h"
44 #include "dispatchresult.h"
45 #include "funcrequest.h"
46 #include "gettext.h"
47 #include "outputparams.h"
48 #include "undo.h"
49
50 #include "support/lstrings.h"
51
52 #include "frontends/Dialogs.h"
53 #include "frontends/LyXView.h"
54 #include "frontends/Painter.h"
55 #include "frontends/nullpainter.h"
56
57 #include <sstream>
58
59 using lyx::cap::copySelection;
60 using lyx::cap::grabAndEraseSelection;
61 using lyx::cap::cutSelection;
62 using lyx::cap::replaceSelection;
63 using lyx::cap::selClearOrDel;
64
65 using std::endl;
66 using std::string;
67 using std::istringstream;
68
69
70 MathNestInset::MathNestInset(idx_type nargs)
71         : cells_(nargs), lock_(false)
72 {}
73
74
75 MathInset::idx_type MathNestInset::nargs() const
76 {
77         return cells_.size();
78 }
79
80
81 MathArray & MathNestInset::cell(idx_type i)
82 {
83         return cells_[i];
84 }
85
86
87 MathArray const & MathNestInset::cell(idx_type i) const
88 {
89         return cells_[i];
90 }
91
92
93 void MathNestInset::cursorPos(CursorSlice const & sl, bool /*boundary*/,
94         int & x, int & y) const
95 {
96 // FIXME: This is a hack. Ideally, the coord cache should not store
97 // absolute positions, but relative ones. This would mean to call
98 // setXY() not in MathArray::draw(), but in the parent insets' draw()
99 // with the correctly adjusted x,y values. But this means that we'd have
100 // to touch all (math)inset's draw() methods. Right now, we'll store
101 // absolute value, and make them here relative, only to make them
102 // absolute again when actually drawing the cursor. What a mess.
103         BOOST_ASSERT(ptr_cmp(&sl.inset(), this));
104         MathArray const & ar = sl.cell();
105         if (!theCoords.getArrays().has(&ar)) {
106                 // this can (semi-)legally happen if we just created this cell
107                 // and it never has been drawn before. So don't ASSERT.
108                 //lyxerr << "no cached data for array " << &ar << endl;
109                 x = 0;
110                 y = 0;
111                 return;
112         }
113         Point const pt = theCoords.getArrays().xy(&ar);
114         if (!theCoords.getInsets().has(this)) {
115                 // same as above
116                 //lyxerr << "no cached data for inset " << this << endl;
117                 x = 0;
118                 y = 0;
119                 return;
120         }
121         Point const pt2 = theCoords.getInsets().xy(this);
122         //lyxerr << "retrieving position cache for MathArray "
123         //      << pt.x_ << ' ' << pt.y_ << std::endl;
124         x = pt.x_ - pt2.x_ + ar.pos2x(sl.pos());
125         y = pt.y_ - pt2.y_;
126 //      lyxerr << "pt.y_ : " << pt.y_ << " pt2_.y_ : " << pt2.y_
127 //              << " asc: " << ascent() << "  des: " << descent()
128 //              << " ar.asc: " << ar.ascent() << " ar.des: " << ar.descent() << endl;
129         // move cursor visually into empty cells ("blue rectangles");
130         if (ar.empty())
131                 x += 2;
132 }
133
134
135 void MathNestInset::metrics(MetricsInfo const & mi) const
136 {
137         MetricsInfo m = mi;
138         for (idx_type i = 0, n = nargs(); i != n; ++i)
139                 cell(i).metrics(m);
140 }
141
142
143 bool MathNestInset::idxNext(LCursor & cur) const
144 {
145         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
146         if (cur.idx() == cur.lastidx())
147                 return false;
148         ++cur.idx();
149         cur.pos() = 0;
150         return true;
151 }
152
153
154 bool MathNestInset::idxRight(LCursor & cur) const
155 {
156         return idxNext(cur);
157 }
158
159
160 bool MathNestInset::idxPrev(LCursor & cur) const
161 {
162         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
163         if (cur.idx() == 0)
164                 return false;
165         --cur.idx();
166         cur.pos() = cur.lastpos();
167         return true;
168 }
169
170
171 bool MathNestInset::idxLeft(LCursor & cur) const
172 {
173         return idxPrev(cur);
174 }
175
176
177 bool MathNestInset::idxFirst(LCursor & cur) const
178 {
179         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
180         if (nargs() == 0)
181                 return false;
182         cur.idx() = 0;
183         cur.pos() = 0;
184         return true;
185 }
186
187
188 bool MathNestInset::idxLast(LCursor & cur) const
189 {
190         BOOST_ASSERT(ptr_cmp(&cur.inset(), this));
191         if (nargs() == 0)
192                 return false;
193         cur.idx() = cur.lastidx();
194         cur.pos() = cur.lastpos();
195         return true;
196 }
197
198
199 void MathNestInset::dump() const
200 {
201         WriteStream os(lyxerr);
202         os << "---------------------------------------------\n";
203         write(os);
204         os << "\n";
205         for (idx_type i = 0, n = nargs(); i != n; ++i)
206                 os << cell(i) << "\n";
207         os << "---------------------------------------------\n";
208 }
209
210
211 void MathNestInset::draw(PainterInfo & pi, int x, int y) const
212 {
213 #if 0
214         if (lock_)
215                 pi.pain.fillRectangle(x, y - ascent(), width(), height(),
216                                         LColor::mathlockbg);
217 #endif
218         setPosCache(pi, x, y);
219 }
220
221
222 void MathNestInset::drawSelection(PainterInfo & pi, int x, int y) const
223 {
224         // this should use the x/y values given, not the cached values
225         LCursor & cur = pi.base.bv->cursor();
226         if (!cur.selection())
227                 return;
228         if (!ptr_cmp(&cur.inset(), this))
229                 return;
230
231         // FIXME: hack to get position cache warm
232         static NullPainter nop;
233         PainterInfo pinop(pi);
234         pinop.pain = nop;
235         draw(pinop, x, y);
236
237         CursorSlice s1 = cur.selBegin();
238         CursorSlice s2 = cur.selEnd();
239         //lyxerr << "MathNestInset::drawing selection: "
240         //      << " s1: " << s1 << " s2: " << s2 << endl;
241         if (s1.idx() == s2.idx()) {
242                 MathArray const & c = cell(s1.idx());
243                 int x1 = c.xo() + c.pos2x(s1.pos());
244                 int y1 = c.yo() - c.ascent();
245                 int x2 = c.xo() + c.pos2x(s2.pos());
246                 int y2 = c.yo() + c.descent();
247                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
248         //lyxerr << "MathNestInset::drawing selection 3: "
249         //      << " x1: " << x1 << " x2: " << x2
250         //      << " y1: " << y1 << " y2: " << y2 << endl;
251         } else {
252                 for (idx_type i = 0; i < nargs(); ++i) {
253                         if (idxBetween(i, s1.idx(), s2.idx())) {
254                                 MathArray const & c = cell(i);
255                                 int x1 = c.xo();
256                                 int y1 = c.yo() - c.ascent();
257                                 int x2 = c.xo() + c.width();
258                                 int y2 = c.yo() + c.descent();
259                                 pi.pain.fillRectangle(x1, y1, x2 - x1, y2 - y1, LColor::selection);
260                         }
261                 }
262         }
263 }
264
265
266 void MathNestInset::validate(LaTeXFeatures & features) const
267 {
268         for (idx_type i = 0; i < nargs(); ++i)
269                 cell(i).validate(features);
270 }
271
272
273 void MathNestInset::replace(ReplaceData & rep)
274 {
275         for (idx_type i = 0; i < nargs(); ++i)
276                 cell(i).replace(rep);
277 }
278
279
280 bool MathNestInset::contains(MathArray const & ar) const
281 {
282         for (idx_type i = 0; i < nargs(); ++i)
283                 if (cell(i).contains(ar))
284                         return true;
285         return false;
286 }
287
288
289 bool MathNestInset::lock() const
290 {
291         return lock_;
292 }
293
294
295 void MathNestInset::lock(bool l)
296 {
297         lock_ = l;
298 }
299
300
301 bool MathNestInset::isActive() const
302 {
303         return nargs() > 0;
304 }
305
306
307 MathArray MathNestInset::glue() const
308 {
309         MathArray ar;
310         for (size_t i = 0; i < nargs(); ++i)
311                 ar.append(cell(i));
312         return ar;
313 }
314
315
316 void MathNestInset::write(WriteStream & os) const
317 {
318         os << '\\' << name().c_str();
319         for (size_t i = 0; i < nargs(); ++i)
320                 os << '{' << cell(i) << '}';
321         if (nargs() == 0)
322                 os.pendingSpace(true);
323         if (lock_ && !os.latex()) {
324                 os << "\\lyxlock";
325                 os.pendingSpace(true);
326         }
327 }
328
329
330 void MathNestInset::normalize(NormalStream & os) const
331 {
332         os << '[' << name().c_str();
333         for (size_t i = 0; i < nargs(); ++i)
334                 os << ' ' << cell(i);
335         os << ']';
336 }
337
338
339 int MathNestInset::latex(Buffer const &, std::ostream & os,
340                         OutputParams const & runparams) const
341 {
342         WriteStream wi(os, runparams.moving_arg, true);
343         write(wi);
344         return wi.line();
345 }
346
347
348 void MathNestInset::notifyCursorLeaves(LCursor & cur)
349 {
350 #ifdef WITH_WARNINGS
351 #warning look here
352 #endif
353 #if 0
354         MathArray & ar = cur.cell();
355         // remove base-only "scripts"
356         for (pos_type i = 0; i + 1 < ar.size(); ++i) {
357                 MathScriptInset * p = operator[](i).nucleus()->asScriptInset();
358                 if (p && p->nargs() == 1) {
359                         MathArray ar = p->nuc();
360                         erase(i);
361                         insert(i, ar);
362                         cur.adjust(i, ar.size() - 1);
363                 }
364         }
365
366         // glue adjacent font insets of the same kind
367         for (pos_type i = 0; i + 1 < size(); ++i) {
368                 MathFontInset * p = operator[](i).nucleus()->asFontInset();
369                 MathFontInset const * q = operator[](i + 1)->asFontInset();
370                 if (p && q && p->name() == q->name()) {
371                         p->cell(0).append(q->cell(0));
372                         erase(i + 1);
373                         cur.adjust(i, -1);
374                 }
375         }
376 #endif
377 }
378
379
380 void MathNestInset::handleFont
381         (LCursor & cur, string const & arg, string const & font)
382 {
383         // this whole function is a hack and won't work for incremental font
384         // changes...
385         recordUndo(cur, Undo::ATOMIC);
386
387         if (cur.inset().asMathInset()->name() == font)
388                 cur.handleFont(font);
389         else {
390                 cur.handleNest(createMathInset(font));
391                 cur.insert(arg);
392         }
393 }
394
395
396 void MathNestInset::handleFont2(LCursor & cur, string const & arg)
397 {
398         recordUndo(cur, Undo::ATOMIC);
399         LyXFont font;
400         bool b;
401         bv_funcs::string2font(arg, font, b);
402         if (font.color() != LColor::inherit) {
403                 MathAtom at = MathAtom(new MathColorInset(true, font.color()));
404                 cur.handleNest(at, 0);
405         }
406 }
407
408
409 void MathNestInset::doDispatch(LCursor & cur, FuncRequest & cmd)
410 {
411         //lyxerr << "MathNestInset: request: " << cmd << std::endl;
412         //CursorSlice sl = cur.current();
413
414         switch (cmd.action) {
415
416         case LFUN_PASTE: {
417                 recordUndo(cur);
418                 cur.message(_("Paste"));
419                 replaceSelection(cur);
420                 size_t n = 0;
421                 istringstream is(cmd.argument);
422                 is >> n;
423                 string const selection = lyx::cap::getSelection(cur.buffer(), n);
424                 cur.niceInsert(selection);
425                 cur.clearSelection(); // bug 393
426                 cur.bv().switchKeyMap();
427                 finishUndo();
428                 break;
429         }
430
431         case LFUN_CUT:
432                 recordUndo(cur);
433                 cutSelection(cur, true, true);
434                 cur.message(_("Cut"));
435                 // Prevent stale position >= size crash
436                 // Probably not necessary anymore, see eraseSelection (gb 2005-10-09)
437                 cur.normalize();
438                 break;
439
440         case LFUN_COPY:
441                 copySelection(cur);
442                 cur.message(_("Copy"));
443                 break;
444
445         case LFUN_MOUSE_PRESS:
446                 lfunMousePress(cur, cmd);
447                 break;
448
449         case LFUN_MOUSE_MOTION:
450                 lfunMouseMotion(cur, cmd);
451                 break;
452
453         case LFUN_MOUSE_RELEASE:
454                 lfunMouseRelease(cur, cmd);
455                 break;
456
457         case LFUN_FINISHED_LEFT:
458                 cur.bv().cursor() = cur;
459                 break;
460
461         case LFUN_FINISHED_RIGHT:
462                 ++cur.pos();
463                 cur.bv().cursor() = cur;
464                 break;
465
466         case LFUN_FINISHED_UP:
467                 cur.bv().cursor() = cur;
468                 break;
469
470         case LFUN_FINISHED_DOWN:
471                 ++cur.pos();
472                 cur.bv().cursor() = cur;
473                 break;
474
475         case LFUN_CHAR_FORWARD_SELECT:
476         case LFUN_CHAR_FORWARD:
477                 cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
478                 cur.autocorrect() = false;
479                 cur.clearTargetX();
480                 cur.macroModeClose();
481                 if (cur.pos() != cur.lastpos() && cur.openable(cur.nextAtom())) {
482                         cur.pushLeft(*cur.nextAtom().nucleus());
483                         cur.inset().idxFirst(cur);
484                 } else if (cur.posRight() || idxRight(cur)
485                         || cur.popRight() || cur.selection())
486                         ;
487                 else {
488                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
489                         cur.undispatched();
490                 }
491                 break;
492
493         case LFUN_CHAR_BACKWARD_SELECT:
494         case LFUN_CHAR_BACKWARD:
495                 cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
496                 cur.autocorrect() = false;
497                 cur.clearTargetX();
498                 cur.macroModeClose();
499                 if (cur.pos() != 0 && cur.openable(cur.prevAtom())) {
500                         cur.posLeft();
501                         cur.push(*cur.nextAtom().nucleus());
502                         cur.inset().idxLast(cur);
503                 } else if (cur.posLeft() || idxLeft(cur)
504                         || cur.popLeft() || cur.selection())
505                         ;
506                 else {
507                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
508                         cur.undispatched();
509                 }
510                 break;
511
512         case LFUN_UP_SELECT:
513         case LFUN_UP:
514                 // FIXME Tried to use clearTargetX and macroModeClose, crashed on cur.up()
515                 if (cur.inMacroMode()) {
516                         // Make Helge happy
517                         cur.macroModeClose();
518                         break;
519                 }
520                 cur.selHandle(cmd.action == LFUN_UP_SELECT);
521                 if (!cur.up()) {
522                         cmd = FuncRequest(LFUN_FINISHED_UP);
523                         cur.undispatched();
524                 }
525                 // fixes bug 1598. Please check!
526                 cur.normalize();
527                 break;
528
529         case LFUN_DOWN_SELECT:
530         case LFUN_DOWN:
531                 if (cur.inMacroMode()) {
532                         cur.macroModeClose();
533                         break;
534                 }
535                 cur.selHandle(cmd.action == LFUN_DOWN_SELECT);
536                 if (!cur.down()) {
537                         cmd = FuncRequest(LFUN_FINISHED_DOWN);
538                         cur.undispatched();
539                 }
540                 // fixes bug 1598. Please check!
541                 cur.normalize();
542                 break;
543
544         case LFUN_MOUSE_DOUBLE:
545         case LFUN_MOUSE_TRIPLE:
546         case LFUN_WORD_SELECT:
547                 cur.pos() = 0;
548                 cur.idx() = 0;
549                 cur.resetAnchor();
550                 cur.selection() = true;
551                 cur.pos() = cur.lastpos();
552                 cur.idx() = cur.lastidx();
553                 break;
554
555         case LFUN_PARAGRAPH_UP_SELECT:
556         case LFUN_PARAGRAPH_UP:
557         case LFUN_PARAGRAPH_DOWN_SELECT:
558         case LFUN_PARAGRAPH_DOWN:
559                 break;
560
561         case LFUN_LINE_BEGIN_SELECT:
562         case LFUN_LINE_BEGIN:
563         case LFUN_WORD_BACKWARD_SELECT:
564         case LFUN_WORD_BACKWARD:
565                 cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT ||
566                                 cmd.action == LFUN_LINE_BEGIN_SELECT);
567                 cur.macroModeClose();
568                 if (cur.pos() != 0) {
569                         cur.pos() = 0;
570                 } else if (cur.col() != 0) {
571                         cur.idx() -= cur.col();
572                         cur.pos() = 0;
573                 } else if (cur.idx() != 0) {
574                         cur.idx() = 0;
575                         cur.pos() = 0;
576                 } else {
577                         cmd = FuncRequest(LFUN_FINISHED_LEFT);
578                         cur.undispatched();
579                 }
580                 break;
581
582         case LFUN_WORD_FORWARD_SELECT:
583         case LFUN_WORD_FORWARD:
584         case LFUN_LINE_END_SELECT:
585         case LFUN_LINE_END:
586                 cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT ||
587                                 cmd.action == LFUN_LINE_END_SELECT);
588                 cur.macroModeClose();
589                 cur.clearTargetX();
590                 if (cur.pos() != cur.lastpos()) {
591                         cur.pos() = cur.lastpos();
592                 } else if (ncols() && (cur.col() != cur.lastcol())) {
593                         cur.idx() = cur.idx() - cur.col() + cur.lastcol();
594                         cur.pos() = cur.lastpos();
595                 } else if (cur.idx() != cur.lastidx()) {
596                         cur.idx() = cur.lastidx();
597                         cur.pos() = cur.lastpos();
598                 } else {
599                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
600                         cur.undispatched();
601                 }
602                 break;
603
604         case LFUN_SCREEN_UP_SELECT:
605         case LFUN_SCREEN_UP:
606                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
607                 cur.undispatched();
608                 break;
609
610         case LFUN_SCREEN_DOWN_SELECT:
611         case LFUN_SCREEN_DOWN:
612                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
613                 cur.undispatched();
614                 break;
615
616         case LFUN_CELL_FORWARD:
617                 cur.inset().idxNext(cur);
618                 break;
619
620         case LFUN_CELL_BACKWARD:
621                 cur.inset().idxPrev(cur);
622                 break;
623
624         case LFUN_WORD_DELETE_BACKWARD:
625         case LFUN_CHAR_DELETE_BACKWARD:
626                 if (cur.pos() == 0)
627                         // May affect external cell:
628                         recordUndoInset(cur, Undo::ATOMIC);
629                 else
630                         recordUndo(cur, Undo::ATOMIC);
631                 cur.backspace();
632                 break;
633
634         case LFUN_WORD_DELETE_FORWARD:
635         case LFUN_CHAR_DELETE_FORWARD:
636                 if (cur.pos() == cur.lastpos())
637                         // May affect external cell:
638                         recordUndoInset(cur, Undo::ATOMIC);
639                 else
640                         recordUndo(cur, Undo::ATOMIC);
641                 cur.erase();
642                 break;
643
644         case LFUN_ESCAPE:
645                 if (cur.selection())
646                         cur.clearSelection();
647                 else  {
648                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
649                         cur.undispatched();
650                 }
651                 break;
652
653         case LFUN_INSET_TOGGLE:
654                 recordUndo(cur);
655                 //lockToggle();
656                 if (cur.pos() != cur.lastpos()) {
657                         // toggle previous inset ...
658                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
659                 } else if (cur.popLeft() && cur.pos() != cur.lastpos()) {
660                         // ... or enclosing inset if we are in the last inset position
661                         cur.nextAtom().nucleus()->lock(!cur.nextAtom()->lock());
662                         ++cur.pos();
663                 }
664                 break;
665
666         case LFUN_SELF_INSERT:
667                 if (cmd.argument.size() != 1) {
668                         recordUndo(cur);
669                         if (!interpret(cur, cmd.argument))
670                                 cur.insert(cmd.argument);
671                         break;
672                 }
673                 // Don't record undo steps if we are in macro mode and
674                 // cmd.argument is the next character of the macro name.
675                 // Otherwise we'll get an invalid cursor if we undo after
676                 // the macro was finished and the macro is a known command,
677                 // e.g. sqrt. LCursor::macroModeClose replaces in this case
678                 // the MathUnknownInset with name "frac" by an empty
679                 // MathFracInset -> a pos value > 0 is invalid.
680                 // A side effect is that an undo before the macro is finished
681                 // undoes the complete macro, not only the last character.
682                 if (!cur.inMacroMode())
683                         recordUndo(cur);
684
685                 // spacial handling of space. If we insert an inset
686                 // via macro mode, we want to put the cursor inside it
687                 // if relevant. Think typing "\frac<space>".
688                 if (cmd.argument[0] == ' '
689                     && cur.inMacroMode() && cur.macroName() != "\\"
690                     && cur.macroModeClose()) {
691                         MathAtom const atom = cur.prevAtom();
692                         if (atom->asNestInset() && atom->nargs() > 0) {
693                                 cur.posLeft();
694                                 cur.pushLeft(*cur.nextInset());
695                         }
696                 } else if (!interpret(cur, cmd.argument[0])) {
697                         cmd = FuncRequest(LFUN_FINISHED_RIGHT);
698                         cur.undispatched();
699                 }
700                 break;
701
702         //case LFUN_SERVER_GET_XY:
703         //      sprintf(dispatch_buffer, "%d %d",);
704         //      break;
705
706         case LFUN_SERVER_SET_XY: {
707                 lyxerr << "LFUN_SERVER_SET_XY broken!" << endl;
708                 int x = 0;
709                 int y = 0;
710                 istringstream is(cmd.argument);
711                 is >> x >> y;
712                 cur.setScreenPos(x, y);
713                 break;
714         }
715
716         // Special casing for superscript in case of LyX handling
717         // dead-keys:
718         case LFUN_ACCENT_CIRCUMFLEX:
719                 if (cmd.argument.empty()) {
720                         // do superscript if LyX handles
721                         // deadkeys
722                         recordUndo(cur, Undo::ATOMIC);
723                         script(cur, true, grabAndEraseSelection(cur));
724                 }
725                 break;
726
727         case LFUN_ACCENT_UMLAUT:
728         case LFUN_ACCENT_ACUTE:
729         case LFUN_ACCENT_GRAVE:
730         case LFUN_ACCENT_BREVE:
731         case LFUN_ACCENT_DOT:
732         case LFUN_ACCENT_MACRON:
733         case LFUN_ACCENT_CARON:
734         case LFUN_ACCENT_TILDE:
735         case LFUN_ACCENT_CEDILLA:
736         case LFUN_ACCENT_CIRCLE:
737         case LFUN_ACCENT_UNDERDOT:
738         case LFUN_ACCENT_TIE:
739         case LFUN_ACCENT_OGONEK:
740         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
741                 break;
742
743         //  Math fonts
744         case LFUN_FONT_FREE_APPLY:
745         case LFUN_FONT_FREE_UPDATE:
746                 handleFont2(cur, cmd.argument);
747                 break;
748
749         case LFUN_FONT_BOLD:
750                 if (currentMode() == TEXT_MODE)
751                         handleFont(cur, cmd.argument, "textbf");
752                 else
753                         handleFont(cur, cmd.argument, "mathbf");
754                 break;
755         case LFUN_FONT_SANS:
756                 if (currentMode() == TEXT_MODE)
757                         handleFont(cur, cmd.argument, "textsf");
758                 else
759                         handleFont(cur, cmd.argument, "mathsf");
760                 break;
761         case LFUN_FONT_EMPH:
762                 if (currentMode() == TEXT_MODE)
763                         handleFont(cur, cmd.argument, "emph");
764                 else
765                         handleFont(cur, cmd.argument, "mathcal");
766                 break;
767         case LFUN_FONT_ROMAN:
768                 if (currentMode() == TEXT_MODE)
769                         handleFont(cur, cmd.argument, "textrm");
770                 else
771                         handleFont(cur, cmd.argument, "mathrm");
772                 break;
773         case LFUN_FONT_CODE:
774                 if (currentMode() == TEXT_MODE)
775                         handleFont(cur, cmd.argument, "texttt");
776                 else
777                         handleFont(cur, cmd.argument, "mathtt");
778                 break;
779         case LFUN_FONT_FRAK:
780                 handleFont(cur, cmd.argument, "mathfrak");
781                 break;
782         case LFUN_FONT_ITAL:
783                 if (currentMode() == TEXT_MODE)
784                         handleFont(cur, cmd.argument, "textit");
785                 else
786                         handleFont(cur, cmd.argument, "mathit");
787                 break;
788         case LFUN_FONT_NOUN:
789                 if (currentMode() == TEXT_MODE)
790                         // FIXME: should be "noun"
791                         handleFont(cur, cmd.argument, "textsc");
792                 else
793                         handleFont(cur, cmd.argument, "mathbb");
794                 break;
795         //case LFUN_FONT_FREE_APPLY:
796                 handleFont(cur, cmd.argument, "textrm");
797                 break;
798         case LFUN_FONT_DEFAULT:
799                 handleFont(cur, cmd.argument, "textnormal");
800                 break;
801
802         case LFUN_MATH_MODE: {
803 #if 1
804                 // ignore math-mode on when already in math mode
805                 if (currentMode() == InsetBase::MATH_MODE && cmd.argument == "on")
806                         break;
807                 cur.macroModeClose();
808                 string const save_selection = grabAndEraseSelection(cur);
809                 selClearOrDel(cur);
810                 //cur.plainInsert(MathAtom(new MathMBoxInset(cur.bv())));
811                 cur.plainInsert(MathAtom(new MathBoxInset("mbox")));
812                 cur.posLeft();
813                 cur.pushLeft(*cur.nextInset());
814                 cur.niceInsert(save_selection);
815 #else
816                 if (currentMode() == InsetBase::TEXT_MODE) {
817                         cur.niceInsert(MathAtom(new MathHullInset("simple")));
818                         cur.message(_("create new math text environment ($...$)"));
819                 } else {
820                         handleFont(cur, cmd.argument, "textrm");
821                         cur.message(_("entered math text mode (textrm)"));
822                 }
823 #endif
824                 break;
825         }
826
827         case LFUN_MATH_SIZE:
828 #if 0
829                 recordUndo(cur);
830                 cur.setSize(arg);
831 #endif
832                 break;
833
834         case LFUN_MATH_MATRIX: {
835                 recordUndo(cur, Undo::ATOMIC);
836                 unsigned int m = 1;
837                 unsigned int n = 1;
838                 string v_align;
839                 string h_align;
840                 istringstream is(cmd.argument);
841                 is >> m >> n >> v_align >> h_align;
842                 if (m < 1)
843                         m = 1;
844                 if (n < 1)
845                         n = 1;
846                 v_align += 'c';
847                 cur.niceInsert(
848                         MathAtom(new MathArrayInset("array", m, n, v_align[0], h_align)));
849                 break;
850         }
851
852         case LFUN_MATH_DELIM: {
853                 string ls;
854                 string rs = lyx::support::split(cmd.argument, ls, ' ');
855                 // Reasonable default values
856                 if (ls.empty())
857                         ls = '(';
858                 if (rs.empty())
859                         rs = ')';
860                 recordUndo(cur, Undo::ATOMIC);
861                 cur.handleNest(MathAtom(new MathDelimInset(ls, rs)));
862                 break;
863         }
864
865         case LFUN_MATH_BIGDELIM: {
866                 string const lname = cmd.getArg(0);
867                 string const ldelim = cmd.getArg(1);
868                 string const rname = cmd.getArg(2);
869                 string const rdelim = cmd.getArg(3);
870                 latexkeys const * l = in_word_set(lname);
871                 bool const have_l = l && l->inset == "big" &&
872                                     MathBigInset::isBigInsetDelim(ldelim);
873                 l = in_word_set(rname);
874                 bool const have_r = l && l->inset == "big" &&
875                                     MathBigInset::isBigInsetDelim(rdelim);
876                 // We mimic LFUN_MATH_DELIM in case we have an empty left
877                 // or right delimiter.
878                 if (have_l || have_r) {
879                         recordUndo(cur, Undo::ATOMIC);
880                         string const selection = grabAndEraseSelection(cur);
881                         selClearOrDel(cur);
882                         if (have_l)
883                                 cur.insert(MathAtom(new MathBigInset(lname,
884                                                                 ldelim)));
885                         cur.niceInsert(selection);
886                         if (have_r)
887                                 cur.insert(MathAtom(new MathBigInset(rname,
888                                                                 rdelim)));
889                 }
890                 // Don't call cur.undispatched() if we did nothing, this would
891                 // lead to infinite recursion via LyXText::dispatch().
892                 break;
893         }
894
895         case LFUN_SPACE_INSERT:
896         case LFUN_MATH_SPACE:
897                 recordUndo(cur, Undo::ATOMIC);
898                 cur.insert(MathAtom(new MathSpaceInset(",")));
899                 break;
900
901         case LFUN_ERT_INSERT:
902                 // interpret this as if a backslash was typed
903                 recordUndo(cur, Undo::ATOMIC);
904                 interpret(cur, '\\');
905                 break;
906
907         case LFUN_MATH_SUBSCRIPT:
908                 // interpret this as if a _ was typed
909                 recordUndo(cur, Undo::ATOMIC);
910                 interpret(cur, '_');
911                 break;
912
913         case LFUN_MATH_SUPERSCRIPT:
914                 // interpret this as if a ^ was typed
915                 recordUndo(cur, Undo::ATOMIC);
916                 interpret(cur, '^');
917                 break;
918
919 // FIXME: We probably should swap parts of "math-insert" and "self-insert"
920 // handling such that "self-insert" works on "arbitrary stuff" too, and
921 // math-insert only handles special math things like "matrix".
922         case LFUN_MATH_INSERT: {
923                 recordUndo(cur, Undo::ATOMIC);
924                 if (cmd.argument == "^" || cmd.argument == "_") {
925                         interpret(cur, cmd.argument[0]);
926                 } else
927                         cur.niceInsert(cmd.argument);
928                 break;
929                 }
930
931         case LFUN_DIALOG_SHOW_NEW_INSET: {
932                 string const & name = cmd.argument;
933                 string data;
934                 if (name == "ref") {
935                         RefInset tmp(name);
936                         data = tmp.createDialogStr(name);
937                 }
938                 cur.bv().owner()->getDialogs().show(name, data, 0);
939                 break;
940         }
941
942         default:
943                 MathDimInset::doDispatch(cur, cmd);
944                 break;
945         }
946 }
947
948
949 bool MathNestInset::getStatus(LCursor & cur, FuncRequest const & cmd,
950                 FuncStatus & flag) const
951 {
952         // the font related toggles
953         //string tc = "mathnormal";
954         bool ret = true;
955         string const arg = cmd.argument;
956         switch (cmd.action) {
957         case LFUN_TABULAR_FEATURE:
958                 flag.enabled(false);
959                 break;
960 #if 0
961         case LFUN_TABULAR_FEATURE:
962                 // FIXME: check temporarily disabled
963                 // valign code
964                 char align = mathcursor::valign();
965                 if (align == '\0') {
966                         enable = false;
967                         break;
968                 }
969                 if (cmd.argument.empty()) {
970                         flag.clear();
971                         break;
972                 }
973                 if (!contains("tcb", cmd.argument[0])) {
974                         enable = false;
975                         break;
976                 }
977                 flag.setOnOff(cmd.argument[0] == align);
978                 break;
979 #endif
980         /// We have to handle them since 1.4 blocks all unhandled actions
981         case LFUN_FONT_ITAL:
982         case LFUN_FONT_BOLD:
983         case LFUN_FONT_SANS:
984         case LFUN_FONT_EMPH:
985         case LFUN_FONT_CODE:
986         case LFUN_FONT_NOUN:
987         case LFUN_FONT_ROMAN:
988         case LFUN_FONT_DEFAULT:
989                 flag.enabled(true);
990                 break;
991         case LFUN_MATH_MUTATE:
992                 //flag.setOnOff(mathcursor::formula()->hullType() == cmd.argument);
993                 flag.setOnOff(false);
994                 break;
995
996         // we just need to be in math mode to enable that
997         case LFUN_MATH_SIZE:
998         case LFUN_MATH_SPACE:
999         case LFUN_MATH_LIMITS:
1000         case LFUN_MATH_NONUMBER:
1001         case LFUN_MATH_NUMBER:
1002         case LFUN_MATH_EXTERN:
1003                 flag.enabled(true);
1004                 break;
1005
1006         case LFUN_FONT_FRAK:
1007                 flag.enabled(currentMode() != TEXT_MODE);
1008                 break;
1009
1010         case LFUN_MATH_INSERT: {
1011                 bool const textarg =
1012                         arg == "\\textbf"   || arg == "\\textsf" ||
1013                         arg == "\\textrm"   || arg == "\\textmd" ||
1014                         arg == "\\textit"   || arg == "\\textsc" ||
1015                         arg == "\\textsl"   || arg == "\\textup" ||
1016                         arg == "\\texttt"   || arg == "\\textbb" ||
1017                         arg == "\\textnormal";
1018                 flag.enabled(currentMode() != TEXT_MODE || textarg);
1019                 break;
1020         }
1021
1022         case LFUN_MATH_MATRIX:
1023                 flag.enabled(currentMode() == MATH_MODE);
1024                 break;
1025
1026         case LFUN_MATH_DELIM:
1027         case LFUN_MATH_BIGDELIM:
1028                 // Don't do this with multi-cell selections
1029                 flag.enabled(cur.selBegin().idx() == cur.selEnd().idx());
1030                 break;
1031
1032         default:
1033                 ret = false;
1034                 break;
1035         }
1036         return ret;
1037 }
1038
1039
1040 void MathNestInset::edit(LCursor & cur, bool left)
1041 {
1042         cur.push(*this);
1043         cur.idx() = left ? 0 : cur.lastidx();
1044         cur.pos() = left ? 0 : cur.lastpos();
1045         cur.resetAnchor();
1046         //lyxerr << "MathNestInset::edit, cur:\n" << cur << endl;
1047 }
1048
1049
1050 InsetBase * MathNestInset::editXY(LCursor & cur, int x, int y)
1051 {
1052         int idx_min = 0;
1053         int dist_min = 1000000;
1054         for (idx_type i = 0, n = nargs(); i != n; ++i) {
1055                 int const d = cell(i).dist(x, y);
1056                 if (d < dist_min) {
1057                         dist_min = d;
1058                         idx_min = i;
1059                 }
1060         }
1061         MathArray & ar = cell(idx_min);
1062         cur.push(*this);
1063         cur.idx() = idx_min;
1064         cur.pos() = ar.x2pos(x - ar.xo());
1065         //lyxerr << "found cell : " << idx_min << " pos: " << cur.pos() << endl;
1066         if (dist_min == 0) {
1067                 // hit inside cell
1068                 for (pos_type i = 0, n = ar.size(); i < n; ++i)
1069                         if (ar[i]->covers(x, y))
1070                                 return ar[i].nucleus()->editXY(cur, x, y);
1071         }
1072         return this;
1073 }
1074
1075
1076 void MathNestInset::lfunMousePress(LCursor & cur, FuncRequest & cmd)
1077 {
1078         //lyxerr << "## lfunMousePress: buttons: " << cmd.button() << endl;
1079         if (cmd.button() == mouse_button::button1) {
1080                 //lyxerr << "## lfunMousePress: setting cursor to: " << cur << endl;
1081                 cur.bv().mouseSetCursor(cur);
1082         }
1083
1084         if (cmd.button() == mouse_button::button2) {
1085                 MathArray ar;
1086                 asArray(cur.bv().getClipboard(), ar);
1087                 cur.clearSelection();
1088                 editXY(cur, cmd.x, cmd.y);
1089                 cur.insert(ar);
1090                 cur.bv().update();
1091                 return;
1092         }
1093 }
1094
1095
1096 void MathNestInset::lfunMouseMotion(LCursor & cur, FuncRequest & cmd)
1097 {
1098         // only select with button 1
1099         if (cmd.button() == mouse_button::button1) {
1100                 LCursor & bvcur = cur.bv().cursor();
1101                 if (bvcur.anchor_.hasPart(cur)) {
1102                         //lyxerr << "## lfunMouseMotion: cursor: " << cur << endl;
1103                         bvcur.setCursor(cur);
1104                         bvcur.selection() = true;
1105                         //lyxerr << "MOTION " << bvcur << endl;
1106                 }
1107                 else {
1108                         cur.undispatched();
1109                 }
1110         }
1111 }
1112
1113
1114 void MathNestInset::lfunMouseRelease(LCursor & cur, FuncRequest & cmd)
1115 {
1116         //lyxerr << "## lfunMouseRelease: buttons: " << cmd.button() << endl;
1117
1118         if (cmd.button() == mouse_button::button1) {
1119                 //cur.bv().stuffClipboard(cur.grabSelection());
1120                 return;
1121         }
1122
1123         if (cmd.button() == mouse_button::button3) {
1124                 // try to dispatch to enclosed insets first
1125                 cur.bv().owner()->getDialogs().show("mathpanel");
1126                 return;
1127         }
1128
1129         cur.undispatched();
1130 }
1131
1132
1133 bool MathNestInset::interpret(LCursor & cur, char c)
1134 {
1135         //lyxerr << "interpret 2: '" << c << "'" << endl;
1136         string save_selection;
1137         if (c == '^' || c == '_')
1138                 save_selection = grabAndEraseSelection(cur);
1139
1140         cur.clearTargetX();
1141
1142         // handle macroMode
1143         if (cur.inMacroMode()) {
1144                 string name = cur.macroName();
1145
1146                 /// are we currently typing '#1' or '#2' or...?
1147                 if (name == "\\#") {
1148                         cur.backspace();
1149                         int n = c - '0';
1150                         if (n >= 1 && n <= 9)
1151                                 cur.insert(new MathMacroArgument(n));
1152                         return true;
1153                 }
1154
1155                 if (isalpha(c)) {
1156                         cur.activeMacro()->setName(name + c);
1157                         return true;
1158                 }
1159
1160                 // handle 'special char' macros
1161                 if (name == "\\") {
1162                         // remove the '\\'
1163                         if (c == '\\') {
1164                                 cur.backspace();
1165                                 if (currentMode() == MathInset::TEXT_MODE)
1166                                         cur.niceInsert(createMathInset("textbackslash"));
1167                                 else
1168                                         cur.niceInsert(createMathInset("backslash"));
1169                         } else if (c == '{') {
1170                                 cur.backspace();
1171                                 cur.niceInsert(MathAtom(new MathBraceInset));
1172                         } else if (c == '%') {
1173                                 cur.backspace();
1174                                 cur.niceInsert(MathAtom(new MathCommentInset));
1175                         } else if (c == '#') {
1176                                 BOOST_ASSERT(cur.activeMacro());
1177                                 cur.activeMacro()->setName(name + c);
1178                         } else {
1179                                 cur.backspace();
1180                                 cur.niceInsert(createMathInset(string(1, c)));
1181                         }
1182                         return true;
1183                 }
1184
1185                 // One character big delimiters. The others are handled in
1186                 // the other interpret() method.
1187                 latexkeys const * l = in_word_set(name.substr(1));
1188                 if (name[0] == '\\' && l && l->inset == "big") {
1189                         string delim;
1190                         switch (c) {
1191                         case '{':
1192                                 delim = "\\{";
1193                                 break;
1194                         case '}':
1195                                 delim = "\\}";
1196                                 break;
1197                         default:
1198                                 delim = string(1, c);
1199                                 break;
1200                         }
1201                         if (MathBigInset::isBigInsetDelim(delim)) {
1202                                 // name + delim ared a valid MathBigInset.
1203                                 // We can't use cur.macroModeClose() because
1204                                 // it does not handle delim.
1205                                 MathUnknownInset * p = cur.activeMacro();
1206                                 p->finalize();
1207                                 --cur.pos();
1208                                 cur.cell().erase(cur.pos());
1209                                 cur.plainInsert(MathAtom(
1210                                         new MathBigInset(name.substr(1), delim)));
1211                                 return true;
1212                         }
1213                 }
1214
1215                 // leave macro mode and try again if necessary
1216                 cur.macroModeClose();
1217                 if (c == '{')
1218                         cur.niceInsert(MathAtom(new MathBraceInset));
1219                 else if (c != ' ')
1220                         interpret(cur, c);
1221                 return true;
1222         }
1223
1224         // This is annoying as one has to press <space> far too often.
1225         // Disable it.
1226
1227 #if 0
1228                 // leave autocorrect mode if necessary
1229                 if (autocorrect() && c == ' ') {
1230                         autocorrect() = false;
1231                         return true;
1232                 }
1233 #endif
1234
1235         // just clear selection on pressing the space bar
1236         if (cur.selection() && c == ' ') {
1237                 cur.selection() = false;
1238                 return true;
1239         }
1240
1241         selClearOrDel(cur);
1242
1243         if (c == '\\') {
1244                 //lyxerr << "starting with macro" << endl;
1245                 cur.insert(MathAtom(new MathUnknownInset("\\", false)));
1246                 return true;
1247         }
1248
1249         if (c == '\n') {
1250                 if (currentMode() == MathInset::TEXT_MODE)
1251                         cur.insert(c);
1252                 return true;
1253         }
1254
1255         if (c == ' ') {
1256                 if (currentMode() == MathInset::TEXT_MODE) {
1257                         // insert spaces in text mode,
1258                         // but suppress direct insertion of two spaces in a row
1259                         // the still allows typing  '<space>a<space>' and deleting the 'a', but
1260                         // it is better than nothing...
1261                         if (!cur.pos() != 0 || cur.prevAtom()->getChar() != ' ')
1262                                 cur.insert(c);
1263                         return true;
1264                 }
1265                 if (cur.pos() != 0 && cur.prevAtom()->asSpaceInset()) {
1266                         cur.prevAtom().nucleus()->asSpaceInset()->incSpace();
1267                         return true;
1268                 }
1269                 if (cur.popRight())
1270                         return true;
1271                 // if are at the very end, leave the formula
1272                 return cur.pos() != cur.lastpos();
1273         }
1274
1275         // These shouldn't work in text mode:
1276         if (currentMode() != MathInset::TEXT_MODE) {
1277                 if (c == '_') {
1278                         script(cur, false, save_selection);
1279                         return true;
1280                 }
1281                 if (c == '^') {
1282                         script(cur, true, save_selection);
1283                         return true;
1284                 }
1285                 if (c == '~') {
1286                         cur.niceInsert(createMathInset("sim"));
1287                         return true;
1288                 }
1289         }
1290
1291         if (c == '{' || c == '}' || c == '&' || c == '$' || c == '#' ||
1292             c == '%' || c == '_' || c == '^') {
1293                 cur.niceInsert(createMathInset(string(1, c)));
1294                 return true;
1295         }
1296
1297
1298         // try auto-correction
1299         //if (autocorrect() && hasPrevAtom() && math_autocorrect(prevAtom(), c))
1300         //      return true;
1301
1302         // no special circumstances, so insert the character without any fuss
1303         cur.insert(c);
1304         cur.autocorrect() = true;
1305         return true;
1306 }
1307
1308
1309 bool MathNestInset::interpret(LCursor & cur, string const & str)
1310 {
1311         // Create a MathBigInset from cur.cell()[cur.pos() - 1] and t if
1312         // possible
1313         if (!cur.empty() && cur.pos() > 0 &&
1314             cur.cell()[cur.pos() - 1]->asUnknownInset()) {
1315                 if (MathBigInset::isBigInsetDelim(str)) {
1316                         string prev = asString(cur.cell()[cur.pos() - 1]);
1317                         if (prev[0] == '\\') {
1318                                 prev = prev.substr(1);
1319                                 latexkeys const * l = in_word_set(prev);
1320                                 if (l && l->inset == "big") {
1321                                         cur.cell()[cur.pos() - 1] =
1322                                                 MathAtom(new MathBigInset(prev, str));
1323                                         return true;
1324                                 }
1325                         }
1326                 }
1327         }
1328         return false;
1329 }
1330
1331
1332 bool MathNestInset::script(LCursor & cur, bool up, string const &
1333                 save_selection)
1334 {
1335         // Hack to get \^ and \_ working
1336         lyxerr << "handling script: up: " << up << endl;
1337         if (cur.inMacroMode() && cur.macroName() == "\\") {
1338                 if (up)
1339                         cur.niceInsert(createMathInset("mathcircumflex"));
1340                 else
1341                         interpret(cur, '_');
1342                 return true;
1343         }
1344
1345         cur.macroModeClose();
1346         if (asScriptInset() && cur.idx() == 0) {
1347                 // we are in a nucleus of a script inset, move to _our_ script
1348                 MathScriptInset * inset = asScriptInset();
1349                 lyxerr << " going to cell " << inset->idxOfScript(up) << endl;
1350                 inset->ensure(up);
1351                 cur.idx() = inset->idxOfScript(up);
1352                 cur.pos() = 0;
1353         } else if (cur.pos() != 0 && cur.prevAtom()->asScriptInset()) {
1354                 --cur.pos();
1355                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1356                 cur.push(*inset);
1357                 inset->ensure(up);
1358                 cur.idx() = inset->idxOfScript(up);
1359                 cur.pos() = cur.lastpos();
1360         } else {
1361                 // convert the thing to our left to a scriptinset or create a new
1362                 // one if in the very first position of the array
1363                 if (cur.pos() == 0) {
1364                         //lyxerr << "new scriptinset" << endl;
1365                         cur.insert(new MathScriptInset(up));
1366                 } else {
1367                         //lyxerr << "converting prev atom " << endl;
1368                         cur.prevAtom() = MathAtom(new MathScriptInset(cur.prevAtom(), up));
1369                 }
1370                 --cur.pos();
1371                 MathScriptInset * inset = cur.nextAtom().nucleus()->asScriptInset();
1372                 cur.push(*inset);
1373                 cur.idx() = 1;
1374                 cur.pos() = 0;
1375         }
1376         //lyxerr << "inserting selection 1:\n" << save_selection << endl;
1377         cur.niceInsert(save_selection);
1378         cur.resetAnchor();
1379         //lyxerr << "inserting selection 2:\n" << save_selection << endl;
1380         return true;
1381 }