]> git.lyx.org Git - features.git/blob - src/Text3.cpp
5c726f97c9a140cfad3b906a778a770175efd917
[features.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyXFunc.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "VSpace.h"
49
50 #include "frontends/Application.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/LyXView.h"
53 #include "frontends/Selection.h"
54 #include "frontends/WorkArea.h"
55
56 #include "insets/InsetCollapsable.h"
57 #include "insets/InsetCommand.h"
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetFloatList.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetGraphicsParams.h"
62 #include "insets/InsetNewline.h"
63 #include "insets/InsetQuotes.h"
64 #include "insets/InsetSpecialChar.h"
65 #include "insets/InsetText.h"
66
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/gettext.h"
70 #include "support/lstrings.h"
71 #include "support/lyxtime.h"
72 #include "support/os.h"
73
74 #include "mathed/InsetMathHull.h"
75 #include "mathed/MathMacroTemplate.h"
76
77 #include <boost/next_prior.hpp>
78
79 #include <clocale>
80 #include <sstream>
81
82 using namespace std;
83 using namespace lyx::support;
84
85 namespace lyx {
86
87 using cap::copySelection;
88 using cap::cutSelection;
89 using cap::pasteFromStack;
90 using cap::pasteClipboardText;
91 using cap::pasteClipboardGraphics;
92 using cap::replaceSelection;
93 using cap::grabAndEraseSelection;
94 using cap::selClearOrDel;
95
96 // globals...
97 static Font freefont(ignore_font, ignore_language);
98 static bool toggleall = false;
99
100 static void toggleAndShow(Cursor & cur, Text * text,
101         Font const & font, bool toggleall = true)
102 {
103         text->toggleFree(cur, font, toggleall);
104
105         if (font.language() != ignore_language ||
106             font.fontInfo().number() != FONT_IGNORE) {
107                 TextMetrics const & tm = cur.bv().textMetrics(text);
108                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
109                                                        cur.real_current_font))
110                         text->setCursor(cur, cur.pit(), cur.pos(),
111                                         false, !cur.boundary());
112         }
113 }
114
115
116 static void moveCursor(Cursor & cur, bool selecting)
117 {
118         if (selecting || cur.mark())
119                 cur.setSelection();
120 }
121
122
123 static void finishChange(Cursor & cur, bool selecting)
124 {
125         cur.finishUndo();
126         moveCursor(cur, selecting);
127 }
128
129
130 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
131 {
132         cur.recordUndo();
133         docstring sel = cur.selectionAsString(false);
134
135         // It may happen that sel is empty but there is a selection
136         replaceSelection(cur);
137
138         // Is this a valid formula?
139         bool valid = true;
140
141         if (sel.empty()) {
142 #ifdef ENABLE_ASSERTIONS
143                 const int old_pos = cur.pos();
144 #endif
145                 cur.insert(new InsetMathHull(hullSimple));
146 #ifdef ENABLE_ASSERTIONS
147                 LASSERT(old_pos == cur.pos(), /**/);
148 #endif
149                 cur.nextInset()->edit(cur, true);
150                 // don't do that also for LFUN_MATH_MODE
151                 // unless you want end up with always changing
152                 // to mathrm when opening an inlined inset --
153                 // I really hate "LyXfunc overloading"...
154                 if (display)
155                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
156                 // Avoid an unnecessary undo step if cmd.argument
157                 // is empty
158                 if (!cmd.argument().empty())
159                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
160                                                  cmd.argument()));
161         } else {
162                 // create a macro if we see "\\newcommand"
163                 // somewhere, and an ordinary formula
164                 // otherwise
165                 if (sel.find(from_ascii("\\newcommand")) == string::npos
166                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
167                                 && sel.find(from_ascii("\\def")) == string::npos)
168                 {
169                         InsetMathHull * formula = new InsetMathHull;
170                         string const selstr = to_utf8(sel);
171                         istringstream is(selstr);
172                         Lexer lex;
173                         lex.setStream(is);
174                         if (!formula->readQuiet(lex)) {
175                                 // No valid formula, let's try with delims
176                                 is.str("$" + selstr + "$");
177                                 lex.setStream(is);
178                                 if (!formula->readQuiet(lex)) {
179                                         // Still not valid, leave it as is
180                                         valid = false;
181                                         delete formula;
182                                         cur.insert(sel);
183                                 } else
184                                         cur.insert(formula);
185                         } else
186                                 cur.insert(formula);
187                 } else {
188                         cur.insert(new MathMacroTemplate(sel));
189                 }
190         }
191         if (valid)
192                 cur.message(from_utf8(N_("Math editor mode")));
193         else
194                 cur.message(from_utf8(N_("No valid math formula")));
195 }
196
197
198 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
199 {
200         BOOST_ASSERT(cmd.action == LFUN_REGEXP_MODE);
201         if (cur.inRegexped()) {
202                 cur.message(_("Already in regexp mode"));
203                 return;
204         }
205         cur.recordUndo();
206         docstring const save_selection = grabAndEraseSelection(cur);
207         selClearOrDel(cur);
208         // replaceSelection(cur);
209
210         cur.insert(new InsetMathHull(hullRegexp));
211         cur.nextInset()->edit(cur, true);
212         cur.niceInsert(save_selection);
213
214         cur.message(_("Regexp editor mode"));
215 }
216
217
218 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
219 {
220         cur.recordUndo();
221         cap::replaceSelection(cur);
222         cur.insert(new InsetSpecialChar(kind));
223         cur.posForward();
224 }
225
226
227 static bool doInsertInset(Cursor & cur, Text * text,
228         FuncRequest const & cmd, bool edit, bool pastesel)
229 {
230         Buffer & buffer = cur.bv().buffer();
231         BufferParams const & bparams = buffer.params();
232         Inset * inset = createInset(buffer, cmd);
233         if (!inset)
234                 return false;
235
236         cur.recordUndo();
237         if (cmd.action == LFUN_INDEX_INSERT) {
238                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
239                 text->insertInset(cur, inset);
240                 if (edit)
241                         inset->edit(cur, true);
242                 // Now put this into inset
243                 cur.text()->insertStringAsLines(cur, ds);
244                 cur.leaveInset(*inset);
245                 return true;
246         }
247
248         bool gotsel = false;
249         if (cur.selection()) {
250                 cutSelection(cur, false, pastesel);
251                 cur.clearSelection();
252                 gotsel = true;
253         }
254         text->insertInset(cur, inset);
255
256         if (edit)
257                 inset->edit(cur, true);
258
259         if (!gotsel || !pastesel)
260                 return true;
261
262         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
263         cur.buffer()->errors("Paste");
264         cur.clearSelection(); // bug 393
265         cur.finishUndo();
266         InsetText * insetText = dynamic_cast<InsetText *>(inset);
267         if (insetText && (!insetText->allowMultiPar() || cur.lastpit() == 0)) {
268                 // reset first par to default
269                 cur.text()->paragraphs().begin()
270                         ->setPlainOrDefaultLayout(bparams.documentClass());
271                 cur.pos() = 0;
272                 cur.pit() = 0;
273                 // Merge multiple paragraphs -- hack
274                 while (cur.lastpit() > 0)
275                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
276                 cur.leaveInset(*inset);
277         } else {
278                 cur.leaveInset(*inset);
279                 // reset surrounding par to default
280                 DocumentClass const & dc = bparams.documentClass();
281                 docstring const layoutname = inset->usePlainLayout()
282                         ? dc.plainLayoutName()
283                         : dc.defaultLayoutName();
284                 text->setLayout(cur, layoutname);
285         }
286
287         return true;
288 }
289
290
291 string const freefont2string()
292 {
293         return freefont.toString(toggleall);
294 }
295
296
297 static void dragMove(Cursor & cur, int moveid, int movetoid)
298 {
299         // Create pointers to buffers
300         Buffer & buf_move = *cur.buffer();
301         DocIterator dit_move = buf_move.getParFromID(moveid);
302         DocIterator dit_dest = buf_move.getParFromID(movetoid);
303
304         pit_type & pit_move = dit_move.pit();
305         pit_type & pit_dest = dit_dest.pit();
306         ParagraphList & pars = dit_move.text()->paragraphs();
307
308         // Create references to the paragraphs to be moved
309         ParagraphList::iterator const bgn = pars.begin();
310         ParagraphList::iterator dest_start = boost::next(bgn, pit_dest);
311
312         // The first paragraph of the area to be copied:
313         ParagraphList::iterator start = boost::next(bgn, pit_move);
314         // The final paragraph of area to be copied:
315         ParagraphList::iterator finish = start;
316         ParagraphList::iterator const end = pars.end();
317
318         // Move out (down) from this section header
319         if (finish != end)
320                 ++finish;
321
322         // Seek the one (on same level) below
323         int const thistoclevel = start->layout().toclevel;
324         for (; finish != end; ++finish) {
325                 int const toclevel = finish->layout().toclevel;
326                 if (toclevel != Layout::NOT_IN_TOC
327                     && toclevel <= thistoclevel)
328                         break;
329         }
330
331         if (start == pars.begin() || start == dest_start)
332                 // Nothing to move
333                 return;
334
335         pars.insert(dest_start, start, finish);
336         pars.erase(start, finish);
337
338         // FIXME: This only really needs doing for the newly
339         // introduced paragraphs. Something like:
340         //      pit_type const numpars = distance(start, finish);
341         //      start = boost::next(bgn, pit);
342         //      finish = boost::next(start, numpars);
343         //      for (; start != finish; ++start)
344         //              start->setBuffer(buf);
345         // But while this seems to work, it is kind of fragile.
346         buf_move.inset().setBuffer(buf_move);
347 }
348
349
350 /// the type of outline operation
351 enum OutlineOp {
352         OutlineUp, // Move this header with text down
353         OutlineDown,   // Move this header with text up
354         OutlineIn, // Make this header deeper
355         OutlineOut // Make this header shallower
356 };
357
358
359 static void outline(OutlineOp mode, Cursor & cur)
360 {
361         Buffer & buf = *cur.buffer();
362         pit_type & pit = cur.pit();
363         ParagraphList & pars = buf.text().paragraphs();
364         ParagraphList::iterator const bgn = pars.begin();
365         // The first paragraph of the area to be copied:
366         ParagraphList::iterator start = boost::next(bgn, pit);
367         // The final paragraph of area to be copied:
368         ParagraphList::iterator finish = start;
369         ParagraphList::iterator const end = pars.end();
370
371         DocumentClass const & tc = buf.params().documentClass();
372
373         int const thistoclevel = start->layout().toclevel;
374         int toclevel;
375
376         // Move out (down) from this section header
377         if (finish != end)
378                 ++finish;
379
380         // Seek the one (on same level) below
381         for (; finish != end; ++finish) {
382                 toclevel = finish->layout().toclevel;
383                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
384                         break;
385         }
386
387         // Do we need to set insets' buffer_ members, because we copied
388         // some stuff? We'll assume we do and reset it otherwise.
389         bool set_buffers = true;
390
391         switch (mode) {
392                 case OutlineUp: {
393                         if (start == pars.begin())
394                                 // Nothing to move.
395                                 return;
396                         ParagraphList::iterator dest = start;
397                         // Move out (up) from this header
398                         if (dest == bgn)
399                                 return;
400                         // Search previous same-level header above
401                         do {
402                                 --dest;
403                                 toclevel = dest->layout().toclevel;
404                         } while(dest != bgn
405                                 && (toclevel == Layout::NOT_IN_TOC
406                                     || toclevel > thistoclevel));
407                         // Not found; do nothing
408                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
409                                 return;
410                         pit_type const newpit = distance(bgn, dest);
411                         pit_type const len = distance(start, finish);
412                         pit_type const deletepit = pit + len;
413                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
414                         pars.insert(dest, start, finish);
415                         start = boost::next(pars.begin(), deletepit);
416                         pit = newpit;
417                         pars.erase(start, finish);
418                         break;
419                 }
420                 case OutlineDown: {
421                         if (finish == end)
422                                 // Nothing to move.
423                                 return;
424                         // Go one down from *this* header:
425                         ParagraphList::iterator dest = boost::next(finish, 1);
426                         // Go further down to find header to insert in front of:
427                         for (; dest != end; ++dest) {
428                                 toclevel = dest->layout().toclevel;
429                                 if (toclevel != Layout::NOT_IN_TOC
430                                       && toclevel <= thistoclevel)
431                                         break;
432                         }
433                         // One such was found:
434                         pit_type newpit = distance(bgn, dest);
435                         pit_type const len = distance(start, finish);
436                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
437                         pars.insert(dest, start, finish);
438                         start = boost::next(bgn, pit);
439                         pit = newpit - len;
440                         pars.erase(start, finish);
441                         break;
442                 }
443                 case OutlineIn: {
444                         pit_type const len = distance(start, finish);
445                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
446                         for (; start != finish; ++start) {
447                                 toclevel = start->layout().toclevel;
448                                 if (toclevel == Layout::NOT_IN_TOC)
449                                         continue;
450                                 DocumentClass::const_iterator lit = tc.begin();
451                                 DocumentClass::const_iterator len = tc.end();
452                                 for (; lit != len; ++lit) {
453                                         if (lit->toclevel == toclevel + 1 &&
454                                             start->layout().labeltype == lit->labeltype) {
455                                                 start->setLayout(*lit);
456                                                 break;
457                                         }
458                                 }
459                         }
460                         set_buffers = false;
461                         break;
462                 }
463                 case OutlineOut: {
464                         pit_type const len = distance(start, finish);
465                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
466                         for (; start != finish; ++start) {
467                                 toclevel = start->layout().toclevel;
468                                 if (toclevel == Layout::NOT_IN_TOC)
469                                         continue;
470                                 DocumentClass::const_iterator lit = tc.begin();
471                                 DocumentClass::const_iterator len = tc.end();
472                                 for (; lit != len; ++lit) {
473                                         if (lit->toclevel == toclevel - 1 &&
474                                                 start->layout().labeltype == lit->labeltype) {
475                                                         start->setLayout(*lit);
476                                                         break;
477                                         }
478                                 }
479                         }
480                         set_buffers = false;
481                         break;
482                 }
483         }
484         if (set_buffers)
485                 // FIXME This only really needs doing for the newly introduced 
486                 // paragraphs. Something like:
487                 //      pit_type const numpars = distance(start, finish);
488                 //      start = boost::next(bgn, pit);
489                 //      finish = boost::next(start, numpars);
490                 //      for (; start != finish; ++start)
491                 //              start->setBuffer(buf);
492                 // But while this seems to work, it is kind of fragile.
493                 buf.inset().setBuffer(buf);
494 }
495
496
497 void Text::number(Cursor & cur)
498 {
499         FontInfo font = ignore_font;
500         font.setNumber(FONT_TOGGLE);
501         toggleAndShow(cur, this, Font(font, ignore_language));
502 }
503
504
505 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
506 {
507         return par.isRTL(buffer.params());
508 }
509
510
511 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
512 {
513         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
514
515         // Dispatch if the cursor is inside the text. It is not the
516         // case for context menus (bug 5797).
517         if (cur.text() != this) {
518                 cur.undispatched();
519                 return;
520         }
521
522         BufferView * bv = &cur.bv();
523         TextMetrics * tm = &bv->textMetrics(this);
524         if (!tm->contains(cur.pit())) {
525                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
526                 tm = &bv->textMetrics(this);
527         }
528
529         // FIXME: We use the update flag to indicates wether a singlePar or a
530         // full screen update is needed. We reset it here but shall we restore it
531         // at the end?
532         cur.noUpdate();
533
534         LASSERT(cur.text() == this, /**/);
535         CursorSlice oldTopSlice = cur.top();
536         bool oldBoundary = cur.boundary();
537         bool sel = cur.selection();
538         // Signals that, even if needsUpdate == false, an update of the
539         // cursor paragraph is required
540         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
541                 LyXAction::SingleParUpdate);
542         // Signals that a full-screen update is required
543         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
544                 LyXAction::NoUpdate) || singleParUpdate);
545
546         switch (cmd.action) {
547
548         case LFUN_PARAGRAPH_MOVE_DOWN: {
549                 pit_type const pit = cur.pit();
550                 recUndo(cur, pit, pit + 1);
551                 cur.finishUndo();
552                 swap(pars_[pit], pars_[pit + 1]);
553                 cur.buffer()->updateLabels();
554                 needsUpdate = true;
555                 ++cur.pit();
556                 break;
557         }
558
559         case LFUN_PARAGRAPH_MOVE_UP: {
560                 pit_type const pit = cur.pit();
561                 recUndo(cur, pit - 1, pit);
562                 cur.finishUndo();
563                 swap(pars_[pit], pars_[pit - 1]);
564                 cur.buffer()->updateLabels();
565                 --cur.pit();
566                 needsUpdate = true;
567                 break;
568         }
569
570         case LFUN_APPENDIX: {
571                 Paragraph & par = cur.paragraph();
572                 bool start = !par.params().startOfAppendix();
573
574 // FIXME: The code below only makes sense at top level.
575 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
576                 // ensure that we have only one start_of_appendix in this document
577                 // FIXME: this don't work for multipart document!
578                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
579                         if (pars_[tmp].params().startOfAppendix()) {
580                                 recUndo(cur, tmp);
581                                 pars_[tmp].params().startOfAppendix(false);
582                                 break;
583                         }
584                 }
585
586                 cur.recordUndo();
587                 par.params().startOfAppendix(start);
588
589                 // we can set the refreshing parameters now
590                 cur.buffer()->updateLabels();
591                 break;
592         }
593
594         case LFUN_WORD_DELETE_FORWARD:
595                 if (cur.selection())
596                         cutSelection(cur, true, false);
597                 else
598                         deleteWordForward(cur);
599                 finishChange(cur, false);
600                 break;
601
602         case LFUN_WORD_DELETE_BACKWARD:
603                 if (cur.selection())
604                         cutSelection(cur, true, false);
605                 else
606                         deleteWordBackward(cur);
607                 finishChange(cur, false);
608                 break;
609
610         case LFUN_LINE_DELETE:
611                 if (cur.selection())
612                         cutSelection(cur, true, false);
613                 else
614                         tm->deleteLineForward(cur);
615                 finishChange(cur, false);
616                 break;
617
618         case LFUN_BUFFER_BEGIN:
619         case LFUN_BUFFER_BEGIN_SELECT:
620                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
621                 if (cur.depth() == 1)
622                         needsUpdate |= cursorTop(cur);
623                 else
624                         cur.undispatched();
625                 cur.updateFlags(Update::FitCursor);
626                 break;
627
628         case LFUN_BUFFER_END:
629         case LFUN_BUFFER_END_SELECT:
630                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
631                 if (cur.depth() == 1)
632                         needsUpdate |= cursorBottom(cur);
633                 else
634                         cur.undispatched();
635                 cur.updateFlags(Update::FitCursor);
636                 break;
637
638         case LFUN_INSET_BEGIN:
639         case LFUN_INSET_BEGIN_SELECT:
640                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_BEGIN_SELECT);
641                 if (cur.depth() == 1 || cur.pos() > 0)
642                         needsUpdate |= cursorTop(cur);
643                 else
644                         cur.undispatched();
645                 cur.updateFlags(Update::FitCursor);
646                 break;
647
648         case LFUN_INSET_END:
649         case LFUN_INSET_END_SELECT:
650                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_END_SELECT);
651                 if (cur.depth() == 1 || cur.pos() < cur.lastpos())
652                         needsUpdate |= cursorBottom(cur);
653                 else
654                         cur.undispatched();
655                 cur.updateFlags(Update::FitCursor);
656                 break;
657
658         case LFUN_CHAR_FORWARD:
659         case LFUN_CHAR_FORWARD_SELECT:
660                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
661                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
662                 needsUpdate |= cursorForward(cur);
663
664                 if (!needsUpdate && oldTopSlice == cur.top()
665                                 && cur.boundary() == oldBoundary) {
666                         cur.undispatched();
667                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
668                 
669                         // we will probably be moving out the inset, so we should execute
670                         // the depm-mechanism, but only when the cursor has a place to 
671                         // go outside this inset, i.e. in a slice above.
672                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
673                                   && cur.pit() == cur.lastpit()) {
674                                 // The cursor hasn't changed yet. To give the 
675                                 // DEPM the possibility of doing something we must
676                                 // provide it with two different cursors.
677                                 Cursor dummy = cur;
678                                 dummy.pos() = dummy.pit() = 0;
679                                 cur.bv().checkDepm(dummy, cur);
680                         }
681                 }
682                 break;
683
684         case LFUN_CHAR_BACKWARD:
685         case LFUN_CHAR_BACKWARD_SELECT:
686                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
687                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
688                 needsUpdate |= cursorBackward(cur);
689
690                 if (!needsUpdate && oldTopSlice == cur.top()
691                         && cur.boundary() == oldBoundary) {
692                         cur.undispatched();
693                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
694
695                         // we will probably be moving out the inset, so we should execute
696                         // the depm-mechanism, but only when the cursor has a place to 
697                         // go outside this inset, i.e. in a slice above.
698                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
699                                 // The cursor hasn't changed yet. To give the 
700                                 // DEPM the possibility of doing something we must
701                                 // provide it with two different cursors.
702                                 Cursor dummy = cur;
703                                 dummy.pos() = cur.lastpos();
704                                 dummy.pit() = cur.lastpit();
705                                 cur.bv().checkDepm(dummy, cur);
706                         }
707                 }
708                 break;
709
710         case LFUN_CHAR_LEFT:
711         case LFUN_CHAR_LEFT_SELECT:
712                 if (lyxrc.visual_cursor) {
713                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
714                         needsUpdate |= cursorVisLeft(cur);
715                         if (!needsUpdate && oldTopSlice == cur.top()
716                                         && cur.boundary() == oldBoundary) {
717                                 cur.undispatched();
718                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
719                         }
720                 } else {
721                         if (reverseDirectionNeeded(cur)) {
722                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
723                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
724                         } else {
725                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
726                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
727                         }
728                         dispatch(cur, cmd);
729                         return;
730                 }
731                 break;
732
733         case LFUN_CHAR_RIGHT:
734         case LFUN_CHAR_RIGHT_SELECT:
735                 if (lyxrc.visual_cursor) {
736                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
737                         needsUpdate |= cursorVisRight(cur);
738                         if (!needsUpdate && oldTopSlice == cur.top()
739                                         && cur.boundary() == oldBoundary) {
740                                 cur.undispatched();
741                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
742                         }
743                 } else {
744                         if (reverseDirectionNeeded(cur)) {
745                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
746                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
747                         } else {
748                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
749                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
750                         }
751                         dispatch(cur, cmd);
752                         return;
753                 }
754                 break;
755
756
757         case LFUN_UP_SELECT:
758         case LFUN_DOWN_SELECT:
759         case LFUN_UP:
760         case LFUN_DOWN: {
761                 // stop/start the selection
762                 bool select = cmd.action == LFUN_DOWN_SELECT ||
763                         cmd.action == LFUN_UP_SELECT;
764
765                 // move cursor up/down
766                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
767                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
768
769                 if (!atFirstOrLastRow) {
770                         needsUpdate |= cur.selHandle(select);   
771                         cur.selHandle(select);
772                         cur.upDownInText(up, needsUpdate);
773                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
774                 } else {
775                         // if the cursor cannot be moved up or down do not remove
776                         // the selection right now, but wait for the next dispatch.
777                         if (select)
778                                 needsUpdate |= cur.selHandle(select);   
779                         cur.upDownInText(up, needsUpdate);
780                         cur.undispatched();
781                 }
782
783                 break;
784         }
785
786         case LFUN_PARAGRAPH_UP:
787         case LFUN_PARAGRAPH_UP_SELECT:
788                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
789                 needsUpdate |= cursorUpParagraph(cur);
790                 break;
791
792         case LFUN_PARAGRAPH_DOWN:
793         case LFUN_PARAGRAPH_DOWN_SELECT:
794                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
795                 needsUpdate |= cursorDownParagraph(cur);
796                 break;
797
798         case LFUN_LINE_BEGIN:
799         case LFUN_LINE_BEGIN_SELECT:
800                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
801                 needsUpdate |= tm->cursorHome(cur);
802                 break;
803
804         case LFUN_LINE_END:
805         case LFUN_LINE_END_SELECT:
806                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
807                 needsUpdate |= tm->cursorEnd(cur);
808                 break;
809
810         case LFUN_SECTION_SELECT: {
811                 Buffer const & buf = *cur.buffer();
812                 pit_type const pit = cur.pit();
813                 ParagraphList & pars = buf.text().paragraphs();
814                 ParagraphList::iterator bgn = pars.begin();
815                 // The first paragraph of the area to be selected:
816                 ParagraphList::iterator start = boost::next(bgn, pit);
817                 // The final paragraph of area to be selected:
818                 ParagraphList::iterator finish = start;
819                 ParagraphList::iterator end = pars.end();
820
821                 int const thistoclevel = start->layout().toclevel;
822                 if (thistoclevel == Layout::NOT_IN_TOC)
823                         break;
824
825                 cur.pos() = 0;
826                 Cursor const old_cur = cur;
827                 needsUpdate |= cur.selHandle(true);
828
829                 // Move out (down) from this section header
830                 if (finish != end)
831                         ++finish;
832
833                 // Seek the one (on same level) below
834                 for (; finish != end; ++finish, ++cur.pit()) {
835                         int const toclevel = finish->layout().toclevel;
836                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
837                                 break;
838                 }
839                 cur.pos() = cur.lastpos();
840                 
841                 needsUpdate |= cur != old_cur;
842                 break;
843         }
844
845         case LFUN_WORD_RIGHT:
846         case LFUN_WORD_RIGHT_SELECT:
847                 if (lyxrc.visual_cursor) {
848                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_RIGHT_SELECT);
849                         needsUpdate |= cursorVisRightOneWord(cur);
850                         if (!needsUpdate && oldTopSlice == cur.top()
851                                         && cur.boundary() == oldBoundary) {
852                                 cur.undispatched();
853                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
854                         }
855                 } else {
856                         if (reverseDirectionNeeded(cur)) {
857                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
858                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
859                         } else {
860                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
861                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
862                         }
863                         dispatch(cur, cmd);
864                         return;
865                 }
866                 break;
867
868         case LFUN_WORD_FORWARD:
869         case LFUN_WORD_FORWARD_SELECT:
870                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
871                 needsUpdate |= cursorForwardOneWord(cur);
872                 break;
873
874         case LFUN_WORD_LEFT:
875         case LFUN_WORD_LEFT_SELECT:
876                 if (lyxrc.visual_cursor) {
877                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_LEFT_SELECT);
878                         needsUpdate |= cursorVisLeftOneWord(cur);
879                         if (!needsUpdate && oldTopSlice == cur.top()
880                                         && cur.boundary() == oldBoundary) {
881                                 cur.undispatched();
882                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
883                         }
884                 } else {
885                         if (reverseDirectionNeeded(cur)) {
886                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
887                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
888                         } else {
889                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
890                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
891                         }
892                         dispatch(cur, cmd);
893                         return;
894                 }
895                 break;
896
897         case LFUN_WORD_BACKWARD:
898         case LFUN_WORD_BACKWARD_SELECT:
899                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
900                 needsUpdate |= cursorBackwardOneWord(cur);
901                 break;
902
903         case LFUN_WORD_SELECT: {
904                 selectWord(cur, WHOLE_WORD);
905                 finishChange(cur, true);
906                 break;
907         }
908
909         case LFUN_NEWLINE_INSERT: {
910                 InsetNewlineParams inp;
911                 docstring arg = cmd.argument();
912                 // this avoids a double undo
913                 // FIXME: should not be needed, ideally
914                 if (!cur.selection())
915                         cur.recordUndo();
916                 cap::replaceSelection(cur);
917                 if (arg == "linebreak")
918                         inp.kind = InsetNewlineParams::LINEBREAK;
919                 else
920                         inp.kind = InsetNewlineParams::NEWLINE;
921                 cur.insert(new InsetNewline(inp));
922                 cur.posForward();
923                 moveCursor(cur, false);
924                 break;
925         }
926
927         case LFUN_CHAR_DELETE_FORWARD:
928                 if (!cur.selection()) {
929                         if (cur.pos() == cur.paragraph().size())
930                                 // Par boundary, force full-screen update
931                                 singleParUpdate = false;
932                         needsUpdate |= erase(cur);
933                         cur.resetAnchor();
934                         // It is possible to make it a lot faster still
935                         // just comment out the line below...
936                 } else {
937                         cutSelection(cur, true, false);
938                         singleParUpdate = false;
939                 }
940                 moveCursor(cur, false);
941                 break;
942
943         case LFUN_CHAR_DELETE_BACKWARD:
944                 if (!cur.selection()) {
945                         if (bv->getIntl().getTransManager().backspace()) {
946                                 // Par boundary, full-screen update
947                                 if (cur.pos() == 0)
948                                         singleParUpdate = false;
949                                 needsUpdate |= backspace(cur);
950                                 cur.resetAnchor();
951                                 // It is possible to make it a lot faster still
952                                 // just comment out the line below...
953                         }
954                 } else {
955                         cutSelection(cur, true, false);
956                         singleParUpdate = false;
957                 }
958                 break;
959
960         case LFUN_BREAK_PARAGRAPH:
961                 cap::replaceSelection(cur);
962                 breakParagraph(cur, cmd.argument() == "inverse");
963                 cur.resetAnchor();
964                 break;
965
966         // TODO
967         // With the creation of LFUN_PARAGRAPH_PARAMS, this is now redundant,
968         // as its duties can be performed there. Should it be removed??
969         // FIXME For now, it can just dispatch LFUN_PARAGRAPH_PARAMS...
970         case LFUN_PARAGRAPH_SPACING: {
971                 Paragraph & par = cur.paragraph();
972                 Spacing::Space cur_spacing = par.params().spacing().getSpace();
973                 string cur_value = "1.0";
974                 if (cur_spacing == Spacing::Other)
975                         cur_value = par.params().spacing().getValueAsString();
976
977                 istringstream is(to_utf8(cmd.argument()));
978                 string tmp;
979                 is >> tmp;
980                 Spacing::Space new_spacing = cur_spacing;
981                 string new_value = cur_value;
982                 if (tmp.empty()) {
983                         lyxerr << "Missing argument to `paragraph-spacing'"
984                                << endl;
985                 } else if (tmp == "single") {
986                         new_spacing = Spacing::Single;
987                 } else if (tmp == "onehalf") {
988                         new_spacing = Spacing::Onehalf;
989                 } else if (tmp == "double") {
990                         new_spacing = Spacing::Double;
991                 } else if (tmp == "other") {
992                         new_spacing = Spacing::Other;
993                         string tmpval = "0.0";
994                         is >> tmpval;
995                         lyxerr << "new_value = " << tmpval << endl;
996                         if (tmpval != "0.0")
997                                 new_value = tmpval;
998                 } else if (tmp == "default") {
999                         new_spacing = Spacing::Default;
1000                 } else {
1001                         lyxerr << to_utf8(_("Unknown spacing argument: "))
1002                                << to_utf8(cmd.argument()) << endl;
1003                 }
1004                 if (cur_spacing != new_spacing || cur_value != new_value)
1005                         par.params().spacing(Spacing(new_spacing, new_value));
1006                 break;
1007         }
1008
1009         case LFUN_INSET_INSERT: {
1010                 cur.recordUndo();
1011
1012                 // We have to avoid triggering InstantPreview loading
1013                 // before inserting into the document. See bug #5626.
1014                 bool loaded = bv->buffer().isFullyLoaded();
1015                 bv->buffer().setFullyLoaded(false);
1016                 Inset * inset = createInset(bv->buffer(), cmd);
1017                 bv->buffer().setFullyLoaded(loaded);
1018
1019                 if (inset) {
1020                         // FIXME (Abdel 01/02/2006):
1021                         // What follows would be a partial fix for bug 2154:
1022                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
1023                         // This automatically put the label inset _after_ a
1024                         // numbered section. It should be possible to extend the mechanism
1025                         // to any kind of LateX environement.
1026                         // The correct way to fix that bug would be at LateX generation.
1027                         // I'll let the code here for reference as it could be used for some
1028                         // other feature like "automatic labelling".
1029                         /*
1030                         Paragraph & par = pars_[cur.pit()];
1031                         if (inset->lyxCode() == LABEL_CODE
1032                                 && par.layout().labeltype == LABEL_COUNTER) {
1033                                 // Go to the end of the paragraph
1034                                 // Warning: Because of Change-Tracking, the last
1035                                 // position is 'size()' and not 'size()-1':
1036                                 cur.pos() = par.size();
1037                                 // Insert a new paragraph
1038                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1039                                 dispatch(cur, fr);
1040                         }
1041                         */
1042                         if (cur.selection())
1043                                 cutSelection(cur, true, false);
1044                         cur.insert(inset);
1045                         cur.posForward();
1046
1047                         // trigger InstantPreview now
1048                         if (inset->lyxCode() == EXTERNAL_CODE) {
1049                                 InsetExternal & ins =
1050                                         static_cast<InsetExternal &>(*inset);
1051                                 ins.updatePreview();
1052                         }
1053                 }
1054
1055                 break;
1056         }
1057
1058         case LFUN_INSET_DISSOLVE: {
1059                 // first, try if there's an inset at cursor
1060                 // FIXME: this first part should be moved to
1061                 // a LFUN_NEXT_INSET_DISSOLVE, or be called via
1062                 // some generic "next-inset inset-dissolve"
1063                 Inset * inset = cur.nextInset();
1064                 if (inset && inset->isActive()) {
1065                         Cursor tmpcur = cur;
1066                         tmpcur.pushBackward(*inset);
1067                         inset->dispatch(tmpcur, cmd);
1068                         if (tmpcur.result().dispatched()) {
1069                                 cur.dispatched();
1070                                 break;
1071                         }
1072                 }
1073                 // if it did not work, try the underlying inset
1074                 if (dissolveInset(cur)) {
1075                         needsUpdate = true;
1076                         break;
1077                 }
1078                 // if it did not work, do nothing.
1079                 break;
1080         }
1081
1082         case LFUN_SET_GRAPHICS_GROUP: {
1083                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1084                 if (!ins)
1085                         break;
1086
1087                 cur.recordUndo();
1088
1089                 string id = to_utf8(cmd.argument());
1090                 string grp = graphics::getGroupParams(bv->buffer(), id);
1091                 InsetGraphicsParams tmp, inspar = ins->getParams();
1092
1093                 if (id.empty())
1094                         inspar.groupId = to_utf8(cmd.argument());
1095                 else {
1096                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1097                         tmp.filename = inspar.filename;
1098                         inspar = tmp;
1099                 }
1100
1101                 ins->setParams(inspar);
1102         }
1103
1104         case LFUN_SPACE_INSERT:
1105                 if (cur.paragraph().layout().free_spacing)
1106                         insertChar(cur, ' ');
1107                 else {
1108                         doInsertInset(cur, this, cmd, false, false);
1109                         cur.posForward();
1110                 }
1111                 moveCursor(cur, false);
1112                 break;
1113
1114         case LFUN_SPECIALCHAR_INSERT: {
1115                 string const name = to_utf8(cmd.argument());
1116                 if (name == "hyphenation")
1117                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1118                 else if (name == "ligature-break")
1119                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1120                 else if (name == "slash")
1121                         specialChar(cur, InsetSpecialChar::SLASH);
1122                 else if (name == "nobreakdash")
1123                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1124                 else if (name == "dots")
1125                         specialChar(cur, InsetSpecialChar::LDOTS);
1126                 else if (name == "end-of-sentence")
1127                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1128                 else if (name == "menu-separator")
1129                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1130                 else if (name.empty())
1131                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1132                 else
1133                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1134                 break;
1135         }
1136
1137         case LFUN_WORD_UPCASE:
1138                 changeCase(cur, text_uppercase);
1139                 break;
1140
1141         case LFUN_WORD_LOWCASE:
1142                 changeCase(cur, text_lowercase);
1143                 break;
1144
1145         case LFUN_WORD_CAPITALIZE:
1146                 changeCase(cur, text_capitalization);
1147                 break;
1148
1149         case LFUN_CHARS_TRANSPOSE:
1150                 charsTranspose(cur);
1151                 break;
1152
1153         case LFUN_PASTE: {
1154                 cur.message(_("Paste"));
1155                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1156                 cap::replaceSelection(cur);
1157
1158                 // without argument?
1159                 string const arg = to_utf8(cmd.argument());
1160                 if (arg.empty()) {
1161                         if (theClipboard().isInternal())
1162                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1163                         else if (theClipboard().hasGraphicsContents() 
1164                                      && !theClipboard().hasTextContents())
1165                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1166                         else
1167                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1168                 } else if (isStrUnsignedInt(arg)) {
1169                         // we have a numerical argument
1170                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1171                                        convert<unsigned int>(arg));
1172                 } else {
1173                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1174                         if (arg == "pdf")
1175                                 type = Clipboard::PdfGraphicsType;
1176                         else if (arg == "png")
1177                                 type = Clipboard::PngGraphicsType;
1178                         else if (arg == "jpeg")
1179                                 type = Clipboard::JpegGraphicsType;
1180                         else if (arg == "linkback")
1181                                 type = Clipboard::LinkBackGraphicsType;
1182                         else if (arg == "emf")
1183                                 type = Clipboard::EmfGraphicsType;
1184                         else if (arg == "wmf")
1185                                 type = Clipboard::WmfGraphicsType;
1186
1187                         else
1188                                 LASSERT(false, /**/);
1189
1190                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1191                 }
1192
1193                 bv->buffer().errors("Paste");
1194                 cur.clearSelection(); // bug 393
1195                 cur.finishUndo();
1196                 break;
1197         }
1198
1199         case LFUN_CUT:
1200                 cutSelection(cur, true, true);
1201                 cur.message(_("Cut"));
1202                 break;
1203
1204         case LFUN_COPY:
1205                 copySelection(cur);
1206                 cur.message(_("Copy"));
1207                 break;
1208
1209         case LFUN_SERVER_GET_XY:
1210                 cur.message(from_utf8(
1211                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1212                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1213                 break;
1214
1215         case LFUN_SERVER_SET_XY: {
1216                 int x = 0;
1217                 int y = 0;
1218                 istringstream is(to_utf8(cmd.argument()));
1219                 is >> x >> y;
1220                 if (!is)
1221                         lyxerr << "SETXY: Could not parse coordinates in '"
1222                                << to_utf8(cmd.argument()) << endl;
1223                 else
1224                         tm->setCursorFromCoordinates(cur, x, y);
1225                 break;
1226         }
1227
1228         case LFUN_SERVER_GET_LAYOUT:
1229                 cur.message(cur.paragraph().layout().name());
1230                 break;
1231
1232         case LFUN_LAYOUT: {
1233                 docstring layout = cmd.argument();
1234                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1235
1236                 Paragraph const & para = cur.paragraph();
1237                 docstring const old_layout = para.layout().name();
1238                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1239
1240                 if (layout.empty())
1241                         layout = tclass.defaultLayoutName();
1242
1243                 if (para.forcePlainLayout())
1244                         // in this case only the empty layout is allowed
1245                         layout = tclass.plainLayoutName();
1246                 else if (para.usePlainLayout()) {
1247                         // in this case, default layout maps to empty layout
1248                         if (layout == tclass.defaultLayoutName())
1249                                 layout = tclass.plainLayoutName();
1250                 } else {
1251                         // otherwise, the empty layout maps to the default
1252                         if (layout == tclass.plainLayoutName())
1253                                 layout = tclass.defaultLayoutName();
1254                 }
1255
1256                 bool hasLayout = tclass.hasLayout(layout);
1257
1258                 // If the entry is obsolete, use the new one instead.
1259                 if (hasLayout) {
1260                         docstring const & obs = tclass[layout].obsoleted_by();
1261                         if (!obs.empty())
1262                                 layout = obs;
1263                 }
1264
1265                 if (!hasLayout) {
1266                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1267                                 from_utf8(N_(" not known")));
1268                         break;
1269                 }
1270
1271                 bool change_layout = (old_layout != layout);
1272
1273                 if (!change_layout && cur.selection() &&
1274                         cur.selBegin().pit() != cur.selEnd().pit())
1275                 {
1276                         pit_type spit = cur.selBegin().pit();
1277                         pit_type epit = cur.selEnd().pit() + 1;
1278                         while (spit != epit) {
1279                                 if (pars_[spit].layout().name() != old_layout) {
1280                                         change_layout = true;
1281                                         break;
1282                                 }
1283                                 ++spit;
1284                         }
1285                 }
1286
1287                 if (change_layout)
1288                         setLayout(cur, layout);
1289
1290                 break;
1291         }
1292
1293         case LFUN_CLIPBOARD_PASTE:
1294                 cur.clearSelection();
1295                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1296                                cmd.argument() == "paragraph");
1297                 bv->buffer().errors("Paste");
1298                 break;
1299
1300         case LFUN_PRIMARY_SELECTION_PASTE:
1301                 pasteString(cur, theSelection().get(),
1302                             cmd.argument() == "paragraph");
1303                 break;
1304
1305         case LFUN_SELECTION_PASTE:
1306                 // Copy the selection buffer to the clipboard stack,
1307                 // because we want it to appear in the "Edit->Paste
1308                 // recent" menu.
1309                 cap::copySelectionToStack();
1310                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1311                 bv->buffer().errors("Paste");
1312                 break;
1313
1314         case LFUN_UNICODE_INSERT: {
1315                 if (cmd.argument().empty())
1316                         break;
1317                 docstring hexstring = cmd.argument();
1318                 if (isHex(hexstring)) {
1319                         char_type c = hexToInt(hexstring);
1320                         if (c >= 32 && c < 0x10ffff) {
1321                                 lyxerr << "Inserting c: " << c << endl;
1322                                 docstring s = docstring(1, c);
1323                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1324                         }
1325                 }
1326                 break;
1327         }
1328
1329         case LFUN_QUOTE_INSERT: {
1330                 Paragraph & par = cur.paragraph();
1331                 pos_type pos = cur.pos();
1332                 BufferParams const & bufparams = bv->buffer().params();
1333                 Layout const & style = par.layout();
1334                 InsetLayout const & ilayout = cur.inset().getLayout();
1335                 if (!style.pass_thru && !ilayout.isPassThru()
1336                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1337                         // this avoids a double undo
1338                         // FIXME: should not be needed, ideally
1339                         if (!cur.selection())
1340                                 cur.recordUndo();
1341                         cap::replaceSelection(cur);
1342                         pos = cur.pos();
1343                         char_type c;
1344                         if (pos == 0)
1345                                 c = ' ';
1346                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1347                                 c = ' ';
1348                         else
1349                                 c = par.getChar(pos - 1);
1350                         string arg = to_utf8(cmd.argument());
1351                         cur.insert(new InsetQuotes(bv->buffer(), c, (arg == "single")
1352                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1353                         cur.posForward();
1354                 }
1355                 else
1356                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1357                 break;
1358         }
1359
1360         case LFUN_DATE_INSERT: {
1361                 string const format = cmd.argument().empty()
1362                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1363                 string const time = formatted_time(current_time(), format);
1364                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1365                 break;
1366         }
1367
1368         case LFUN_MOUSE_TRIPLE:
1369                 if (cmd.button() == mouse_button::button1) {
1370                         tm->cursorHome(cur);
1371                         cur.resetAnchor();
1372                         tm->cursorEnd(cur);
1373                         cur.setSelection();
1374                         bv->cursor() = cur;
1375                 }
1376                 break;
1377
1378         case LFUN_MOUSE_DOUBLE:
1379                 if (cmd.button() == mouse_button::button1) {
1380                         selectWord(cur, WHOLE_WORD_STRICT);
1381                         bv->cursor() = cur;
1382                 }
1383                 break;
1384
1385         // Single-click on work area
1386         case LFUN_MOUSE_PRESS:
1387                 // We are not marking a selection with the keyboard in any case.
1388                 cur.bv().cursor().setMark(false);
1389                 switch (cmd.button()) {
1390                 case mouse_button::button1:
1391                         // Set the cursor
1392                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1393                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1394                         break;
1395
1396                 case mouse_button::button2:
1397                         // Middle mouse pasting.
1398                         bv->mouseSetCursor(cur);
1399                         lyx::dispatch(
1400                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1401                                             "selection-paste ; primary-selection-paste paragraph"));
1402                         cur.noUpdate();
1403                         break;
1404
1405                 case mouse_button::button3: {
1406                         Cursor const & bvcur = cur.bv().cursor();
1407                         // Don't do anything if we right-click a
1408                         // selection, a context menu will popup.
1409                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1410                             && cur < bvcur.selectionEnd()) {
1411                                 cur.noUpdate();
1412                                 return;
1413                         }
1414                         if (!bv->mouseSetCursor(cur, false))
1415                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1416                         break;
1417                 }
1418
1419                 default:
1420                         break;
1421                 } // switch (cmd.button())
1422                 break;
1423
1424         case LFUN_MOUSE_MOTION: {
1425                 // Mouse motion with right or middle mouse do nothing for now.
1426                 if (cmd.button() != mouse_button::button1) {
1427                         cur.noUpdate();
1428                         return;
1429                 }
1430                 // ignore motions deeper nested than the real anchor
1431                 Cursor & bvcur = cur.bv().cursor();
1432                 if (!bvcur.anchor_.hasPart(cur)) {
1433                         cur.undispatched();
1434                         break;
1435                 }
1436                 CursorSlice old = bvcur.top();
1437
1438                 int const wh = bv->workHeight();
1439                 int const y = max(0, min(wh - 1, cmd.y));
1440
1441                 tm->setCursorFromCoordinates(cur, cmd.x, y);
1442                 cur.setTargetX(cmd.x);
1443                 if (cmd.y >= wh)
1444                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1445                 else if (cmd.y < 0)
1446                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1447                 // This is to allow jumping over large insets
1448                 if (cur.top() == old) {
1449                         if (cmd.y >= wh)
1450                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1451                         else if (cmd.y < 0)
1452                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1453                 }
1454                 // We continue with our existing selection or start a new one, so don't
1455                 // reset the anchor.
1456                 bvcur.setCursor(cur);
1457                 bvcur.setSelection(true);
1458                 if (cur.top() == old) {
1459                         // We didn't move one iota, so no need to update the screen.
1460                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1461                         //cur.noUpdate();
1462                         return;
1463                 }
1464                 break;
1465         }
1466
1467         case LFUN_MOUSE_RELEASE:
1468                 switch (cmd.button()) {
1469                 case mouse_button::button1:
1470                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1471                         // If there is a new selection, update persistent selection;
1472                         // otherwise, single click does not clear persistent selection
1473                         // buffer.
1474                         if (cur.selection()) {
1475                                 // Finish selection. If double click,
1476                                 // cur is moved to the end of word by
1477                                 // selectWord but bvcur is current
1478                                 // mouse position.
1479                                 cur.bv().cursor().setSelection();
1480                                 // We might have removed an empty but drawn selection
1481                                 // (probably a margin)
1482                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1483                         } else
1484                                 cur.noUpdate();
1485                         // FIXME: We could try to handle drag and drop of selection here.
1486                         return;
1487
1488                 case mouse_button::button2:
1489                         // Middle mouse pasting is handled at mouse press time,
1490                         // see LFUN_MOUSE_PRESS.
1491                         cur.noUpdate();
1492                         return;
1493
1494                 case mouse_button::button3:
1495                         // Cursor was set at LFUN_MOUSE_PRESS time.
1496                         // FIXME: If there is a selection we could try to handle a special
1497                         // drag & drop context menu.
1498                         cur.noUpdate();
1499                         return;
1500
1501                 case mouse_button::none:
1502                 case mouse_button::button4:
1503                 case mouse_button::button5:
1504                         break;
1505                 } // switch (cmd.button())
1506
1507                 break;
1508
1509         case LFUN_SELF_INSERT: {
1510                 if (cmd.argument().empty())
1511                         break;
1512
1513                 // Automatically delete the currently selected
1514                 // text and replace it with what is being
1515                 // typed in now. Depends on lyxrc settings
1516                 // "auto_region_delete", which defaults to
1517                 // true (on).
1518
1519                 if (lyxrc.auto_region_delete && cur.selection())
1520                         cutSelection(cur, false, false);
1521
1522                 cur.clearSelection();
1523
1524                 docstring::const_iterator cit = cmd.argument().begin();
1525                 docstring::const_iterator const end = cmd.argument().end();
1526                 for (; cit != end; ++cit)
1527                         bv->translateAndInsert(*cit, this, cur);
1528
1529                 cur.resetAnchor();
1530                 moveCursor(cur, false);
1531                 bv->bookmarkEditPosition();
1532                 break;
1533         }
1534
1535         case LFUN_HYPERLINK_INSERT: {
1536                 InsetCommandParams p(HYPERLINK_CODE);
1537                 docstring content;
1538                 if (cur.selection()) {
1539                         content = cur.selectionAsString(false);
1540                         cutSelection(cur, true, false);
1541                 }
1542                 p["target"] = (cmd.argument().empty()) ?
1543                         content : cmd.argument();
1544                 string const data = InsetCommand::params2string("href", p);
1545                 if (p["target"].empty()) {
1546                         bv->showDialog("href", data);
1547                 } else {
1548                         FuncRequest fr(LFUN_INSET_INSERT, data);
1549                         dispatch(cur, fr);
1550                 }
1551                 break;
1552         }
1553
1554         case LFUN_LABEL_INSERT: {
1555                 InsetCommandParams p(LABEL_CODE);
1556                 // Try to generate a valid label
1557                 p["name"] = (cmd.argument().empty()) ?
1558                         cur.getPossibleLabel() :
1559                         cmd.argument();
1560                 string const data = InsetCommand::params2string("label", p);
1561
1562                 if (cmd.argument().empty()) {
1563                         bv->showDialog("label", data);
1564                 } else {
1565                         FuncRequest fr(LFUN_INSET_INSERT, data);
1566                         dispatch(cur, fr);
1567                 }
1568                 break;
1569         }
1570
1571         case LFUN_INFO_INSERT: {
1572                 Inset * inset;
1573                 if (cmd.argument().empty() && cur.selection()) {
1574                         // if command argument is empty use current selection as parameter.
1575                         docstring ds = cur.selectionAsString(false);
1576                         cutSelection(cur, true, false);
1577                         FuncRequest cmd0(cmd, ds);
1578                         inset = createInset(cur.bv().buffer(), cmd0);
1579                 } else {
1580                         inset = createInset(cur.bv().buffer(), cmd);
1581                 }
1582                 if (!inset)
1583                         break;
1584                 cur.recordUndo();
1585                 insertInset(cur, inset);
1586                 cur.posForward();
1587                 break;
1588         }
1589         case LFUN_CAPTION_INSERT:
1590         case LFUN_FOOTNOTE_INSERT:
1591         case LFUN_NOTE_INSERT:
1592         case LFUN_FLEX_INSERT:
1593         case LFUN_BOX_INSERT:
1594         case LFUN_BRANCH_INSERT:
1595         case LFUN_PHANTOM_INSERT:
1596         case LFUN_ERT_INSERT:
1597         case LFUN_LISTING_INSERT:
1598         case LFUN_MARGINALNOTE_INSERT:
1599         case LFUN_OPTIONAL_INSERT:
1600         case LFUN_INDEX_INSERT:
1601                 // Open the inset, and move the current selection
1602                 // inside it.
1603                 doInsertInset(cur, this, cmd, true, true);
1604                 cur.posForward();
1605                 // Some insets are numbered, others are shown in the outline pane so
1606                 // let's update the labels and the toc backend.
1607                 bv->buffer().updateLabels();
1608                 break;
1609
1610         case LFUN_TABULAR_INSERT:
1611                 // if there were no arguments, just open the dialog
1612                 if (doInsertInset(cur, this, cmd, false, true))
1613                         cur.posForward();
1614                 else
1615                         bv->showDialog("tabularcreate");
1616
1617                 break;
1618
1619         case LFUN_FLOAT_INSERT:
1620         case LFUN_FLOAT_WIDE_INSERT:
1621         case LFUN_WRAP_INSERT: {
1622                 // will some text be moved into the inset?
1623                 bool content = cur.selection();
1624
1625                 doInsertInset(cur, this, cmd, true, true);
1626                 cur.posForward();
1627
1628                 // If some text is moved into the inset, doInsertInset 
1629                 // puts the cursor outside the inset. To insert the
1630                 // caption we put it back into the inset.
1631                 if (content)
1632                         cur.backwardPos();
1633
1634                 ParagraphList & pars = cur.text()->paragraphs();
1635
1636                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1637
1638                 // add a separate paragraph for the caption inset
1639                 pars.push_back(Paragraph());
1640                 pars.back().setInsetOwner(&pars[0].inInset());
1641                 pars.back().setPlainOrDefaultLayout(tclass);
1642                 int cap_pit = pars.size() - 1;
1643
1644                 // if an empty inset was created, we create an additional empty
1645                 // paragraph at the bottom so that the user can choose where to put
1646                 // the graphics (or table).
1647                 if (!content) {
1648                         pars.push_back(Paragraph());
1649                         pars.back().setInsetOwner(&pars[0].inInset());
1650                         pars.back().setPlainOrDefaultLayout(tclass);
1651                 }
1652
1653                 // reposition the cursor to the caption
1654                 cur.pit() = cap_pit;
1655                 cur.pos() = 0;
1656                 // FIXME: This Text/Cursor dispatch handling is a mess!
1657                 // We cannot use Cursor::dispatch here it needs access to up to
1658                 // date metrics.
1659                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1660                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1661                 bv->buffer().updateLabels();
1662                 cur.updateFlags(Update::Force);
1663                 // FIXME: When leaving the Float (or Wrap) inset we should
1664                 // delete any empty paragraph left above or below the
1665                 // caption.
1666                 break;
1667         }
1668
1669         case LFUN_NOMENCL_INSERT: {
1670                 InsetCommandParams p(NOMENCL_CODE);
1671                 if (cmd.argument().empty())
1672                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1673                 else
1674                         p["symbol"] = cmd.argument();
1675                 string const data = InsetCommand::params2string("nomenclature", p);
1676                 bv->showDialog("nomenclature", data);
1677                 break;
1678         }
1679
1680         case LFUN_INDEX_PRINT: {
1681                 InsetCommandParams p(INDEX_PRINT_CODE);
1682                 if (cmd.argument().empty())
1683                         p["type"] = from_ascii("idx");
1684                 else
1685                         p["type"] = cmd.argument();
1686                 string const data = InsetCommand::params2string("index_print", p);
1687                 FuncRequest fr(LFUN_INSET_INSERT, data);
1688                 dispatch(cur, fr);
1689                 break;
1690         }
1691         
1692         case LFUN_NOMENCL_PRINT:
1693         case LFUN_TOC_INSERT:
1694         case LFUN_LINE_INSERT:
1695         case LFUN_NEWPAGE_INSERT:
1696                 // do nothing fancy
1697                 doInsertInset(cur, this, cmd, false, false);
1698                 cur.posForward();
1699                 break;
1700
1701         case LFUN_DEPTH_DECREMENT:
1702                 changeDepth(cur, DEC_DEPTH);
1703                 break;
1704
1705         case LFUN_DEPTH_INCREMENT:
1706                 changeDepth(cur, INC_DEPTH);
1707                 break;
1708
1709         case LFUN_MATH_DISPLAY:
1710                 mathDispatch(cur, cmd, true);
1711                 break;
1712
1713         case LFUN_REGEXP_MODE:
1714                 regexpDispatch(cur, cmd);
1715                 break;
1716
1717         case LFUN_MATH_MODE:
1718                 if (cmd.argument() == "on")
1719                         // don't pass "on" as argument
1720                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1721                 else
1722                         mathDispatch(cur, cmd, false);
1723                 break;
1724
1725         case LFUN_MATH_MACRO:
1726                 if (cmd.argument().empty())
1727                         cur.errorMessage(from_utf8(N_("Missing argument")));
1728                 else {
1729                         string s = to_utf8(cmd.argument());
1730                         string const s1 = token(s, ' ', 1);
1731                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1732                         string const s2 = token(s, ' ', 2);
1733                         MacroType type = MacroTypeNewcommand;
1734                         if (s2 == "def")
1735                                 type = MacroTypeDef;
1736                         MathMacroTemplate * inset = new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type);
1737                         inset->setBuffer(bv->buffer());
1738                         insertInset(cur, inset);
1739
1740                         // enter macro inset and select the name
1741                         cur.push(*inset);
1742                         cur.top().pos() = cur.top().lastpos();
1743                         cur.resetAnchor();
1744                         cur.setSelection(true);
1745                         cur.top().pos() = 0;
1746                 }
1747                 break;
1748
1749         // passthrough hat and underscore outside mathed:
1750         case LFUN_MATH_SUBSCRIPT:
1751                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1752                 break;
1753         case LFUN_MATH_SUPERSCRIPT:
1754                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1755                 break;
1756
1757         case LFUN_MATH_INSERT:
1758         case LFUN_MATH_AMS_MATRIX:
1759         case LFUN_MATH_MATRIX:
1760         case LFUN_MATH_DELIM:
1761         case LFUN_MATH_BIGDELIM: {
1762                 cur.recordUndo();
1763                 cap::replaceSelection(cur);
1764                 cur.insert(new InsetMathHull(hullSimple));
1765                 checkAndActivateInset(cur, true);
1766                 LASSERT(cur.inMathed(), /**/);
1767                 cur.dispatch(cmd);
1768                 break;
1769         }
1770
1771         case LFUN_FONT_EMPH: {
1772                 Font font(ignore_font, ignore_language);
1773                 font.fontInfo().setEmph(FONT_TOGGLE);
1774                 toggleAndShow(cur, this, font);
1775                 break;
1776         }
1777
1778         case LFUN_FONT_ITAL: {
1779                 Font font(ignore_font, ignore_language);
1780                 font.fontInfo().setShape(ITALIC_SHAPE);
1781                 toggleAndShow(cur, this, font);
1782                 break;
1783         }
1784
1785         case LFUN_FONT_BOLD:
1786         case LFUN_FONT_BOLDSYMBOL: {
1787                 Font font(ignore_font, ignore_language);
1788                 font.fontInfo().setSeries(BOLD_SERIES);
1789                 toggleAndShow(cur, this, font);
1790                 break;
1791         }
1792
1793         case LFUN_FONT_NOUN: {
1794                 Font font(ignore_font, ignore_language);
1795                 font.fontInfo().setNoun(FONT_TOGGLE);
1796                 toggleAndShow(cur, this, font);
1797                 break;
1798         }
1799
1800         case LFUN_FONT_TYPEWRITER: {
1801                 Font font(ignore_font, ignore_language);
1802                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1803                 toggleAndShow(cur, this, font);
1804                 break;
1805         }
1806
1807         case LFUN_FONT_SANS: {
1808                 Font font(ignore_font, ignore_language);
1809                 font.fontInfo().setFamily(SANS_FAMILY);
1810                 toggleAndShow(cur, this, font);
1811                 break;
1812         }
1813
1814         case LFUN_FONT_ROMAN: {
1815                 Font font(ignore_font, ignore_language);
1816                 font.fontInfo().setFamily(ROMAN_FAMILY);
1817                 toggleAndShow(cur, this, font);
1818                 break;
1819         }
1820
1821         case LFUN_FONT_DEFAULT: {
1822                 Font font(inherit_font, ignore_language);
1823                 toggleAndShow(cur, this, font);
1824                 break;
1825         }
1826
1827         case LFUN_FONT_STRIKEOUT: {
1828                 Font font(ignore_font, ignore_language);
1829                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1830                 toggleAndShow(cur, this, font);
1831                 break;
1832         }
1833
1834         case LFUN_FONT_UULINE: {
1835                 Font font(ignore_font, ignore_language);
1836                 font.fontInfo().setUuline(FONT_TOGGLE);
1837                 toggleAndShow(cur, this, font);
1838                 break;
1839         }
1840
1841         case LFUN_FONT_UWAVE: {
1842                 Font font(ignore_font, ignore_language);
1843                 font.fontInfo().setUwave(FONT_TOGGLE);
1844                 toggleAndShow(cur, this, font);
1845                 break;
1846         }
1847
1848         case LFUN_FONT_UNDERLINE: {
1849                 Font font(ignore_font, ignore_language);
1850                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1851                 toggleAndShow(cur, this, font);
1852                 break;
1853         }
1854
1855         case LFUN_FONT_SIZE: {
1856                 Font font(ignore_font, ignore_language);
1857                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1858                 toggleAndShow(cur, this, font);
1859                 break;
1860         }
1861
1862         case LFUN_LANGUAGE: {
1863                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1864                 if (!lang)
1865                         break;
1866                 Font font(ignore_font, lang);
1867                 toggleAndShow(cur, this, font);
1868                 break;
1869         }
1870
1871         case LFUN_TEXTSTYLE_APPLY:
1872                 toggleAndShow(cur, this, freefont, toggleall);
1873                 cur.message(_("Character set"));
1874                 break;
1875
1876         // Set the freefont using the contents of \param data dispatched from
1877         // the frontends and apply it at the current cursor location.
1878         case LFUN_TEXTSTYLE_UPDATE: {
1879                 Font font;
1880                 bool toggle;
1881                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1882                         freefont = font;
1883                         toggleall = toggle;
1884                         toggleAndShow(cur, this, freefont, toggleall);
1885                         cur.message(_("Character set"));
1886                 } else {
1887                         lyxerr << "Argument not ok";
1888                 }
1889                 break;
1890         }
1891
1892         case LFUN_FINISHED_LEFT:
1893                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1894                 // We're leaving an inset, going left. If the inset is LTR, we're
1895                 // leaving from the front, so we should not move (remain at --- but
1896                 // not in --- the inset). If the inset is RTL, move left, without
1897                 // entering the inset itself; i.e., move to after the inset.
1898                 if (cur.paragraph().getFontSettings(
1899                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1900                         cursorVisLeft(cur, true);
1901                 break;
1902
1903         case LFUN_FINISHED_RIGHT:
1904                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1905                 // We're leaving an inset, going right. If the inset is RTL, we're
1906                 // leaving from the front, so we should not move (remain at --- but
1907                 // not in --- the inset). If the inset is LTR, move right, without
1908                 // entering the inset itself; i.e., move to after the inset.
1909                 if (!cur.paragraph().getFontSettings(
1910                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1911                         cursorVisRight(cur, true);
1912                 break;
1913
1914         case LFUN_FINISHED_BACKWARD:
1915                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1916                 break;
1917
1918         case LFUN_FINISHED_FORWARD:
1919                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1920                 ++cur.pos();
1921                 cur.setCurrentFont();
1922                 break;
1923
1924         case LFUN_LAYOUT_PARAGRAPH: {
1925                 string data;
1926                 params2string(cur.paragraph(), data);
1927                 data = "show\n" + data;
1928                 bv->showDialog("paragraph", data);
1929                 break;
1930         }
1931
1932         case LFUN_PARAGRAPH_UPDATE: {
1933                 string data;
1934                 params2string(cur.paragraph(), data);
1935
1936                 // Will the paragraph accept changes from the dialog?
1937                 bool const accept =
1938                         cur.inset().allowParagraphCustomization(cur.idx());
1939
1940                 data = "update " + convert<string>(accept) + '\n' + data;
1941                 bv->updateDialog("paragraph", data);
1942                 break;
1943         }
1944
1945         case LFUN_ACCENT_UMLAUT:
1946         case LFUN_ACCENT_CIRCUMFLEX:
1947         case LFUN_ACCENT_GRAVE:
1948         case LFUN_ACCENT_ACUTE:
1949         case LFUN_ACCENT_TILDE:
1950         case LFUN_ACCENT_CEDILLA:
1951         case LFUN_ACCENT_MACRON:
1952         case LFUN_ACCENT_DOT:
1953         case LFUN_ACCENT_UNDERDOT:
1954         case LFUN_ACCENT_UNDERBAR:
1955         case LFUN_ACCENT_CARON:
1956         case LFUN_ACCENT_BREVE:
1957         case LFUN_ACCENT_TIE:
1958         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1959         case LFUN_ACCENT_CIRCLE:
1960         case LFUN_ACCENT_OGONEK:
1961                 theLyXFunc().handleKeyFunc(cmd.action);
1962                 if (!cmd.argument().empty())
1963                         // FIXME: Are all these characters encoded in one byte in utf8?
1964                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1965                 break;
1966
1967         case LFUN_FLOAT_LIST_INSERT: {
1968                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1969                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1970                         cur.recordUndo();
1971                         if (cur.selection())
1972                                 cutSelection(cur, true, false);
1973                         breakParagraph(cur);
1974
1975                         if (cur.lastpos() != 0) {
1976                                 cursorBackward(cur);
1977                                 breakParagraph(cur);
1978                         }
1979
1980                         docstring const laystr = cur.inset().usePlainLayout() ?
1981                                 tclass.plainLayoutName() :
1982                                 tclass.defaultLayoutName();
1983                         setLayout(cur, laystr);
1984                         ParagraphParameters p;
1985                         // FIXME If this call were replaced with one to clearParagraphParams(),
1986                         // then we could get rid of this method altogether.
1987                         setParagraphs(cur, p);
1988                         // FIXME This should be simplified when InsetFloatList takes a
1989                         // Buffer in its constructor.
1990                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
1991                         ifl->setBuffer(bv->buffer());
1992                         insertInset(cur, ifl);
1993                         cur.posForward();
1994                 } else {
1995                         lyxerr << "Non-existent float type: "
1996                                << to_utf8(cmd.argument()) << endl;
1997                 }
1998                 break;
1999         }
2000
2001         case LFUN_CHANGE_ACCEPT: {
2002                 acceptOrRejectChanges(cur, ACCEPT);
2003                 break;
2004         }
2005
2006         case LFUN_CHANGE_REJECT: {
2007                 acceptOrRejectChanges(cur, REJECT);
2008                 break;
2009         }
2010
2011         case LFUN_THESAURUS_ENTRY: {
2012                 docstring arg = cmd.argument();
2013                 if (arg.empty()) {
2014                         arg = cur.selectionAsString(false);
2015                         // FIXME
2016                         if (arg.size() > 100 || arg.empty()) {
2017                                 // Get word or selection
2018                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2019                                 arg = cur.selectionAsString(false);
2020                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2021                         }
2022                 }
2023                 bv->showDialog("thesaurus", to_utf8(arg));
2024                 break;
2025         }
2026
2027         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2028                 // Given data, an encoding of the ParagraphParameters
2029                 // generated in the Paragraph dialog, this function sets
2030                 // the current paragraph, or currently selected paragraphs,
2031                 // appropriately.
2032                 // NOTE: This function overrides all existing settings.
2033                 setParagraphs(cur, cmd.argument());
2034                 cur.message(_("Paragraph layout set"));
2035                 break;
2036         }
2037
2038         case LFUN_PARAGRAPH_PARAMS: {
2039                 // Given data, an encoding of the ParagraphParameters as we'd
2040                 // find them in a LyX file, this function modifies the current paragraph,
2041                 // or currently selected paragraphs.
2042                 // NOTE: This function only modifies, and does not override, existing
2043                 // settings.
2044                 setParagraphs(cur, cmd.argument(), true);
2045                 cur.message(_("Paragraph layout set"));
2046                 break;
2047         }
2048
2049         case LFUN_ESCAPE:
2050                 if (cur.selection()) {
2051                         cur.setSelection(false);
2052                 } else {
2053                         cur.undispatched();
2054                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2055                         // correct, but I'm not 100% sure -- dov, 071019
2056                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2057                 }
2058                 break;
2059
2060         case LFUN_OUTLINE_UP:
2061                 outline(OutlineUp, cur);
2062                 setCursor(cur, cur.pit(), 0);
2063                 cur.buffer()->updateLabels();
2064                 needsUpdate = true;
2065                 break;
2066
2067         case LFUN_OUTLINE_DOWN:
2068                 outline(OutlineDown, cur);
2069                 setCursor(cur, cur.pit(), 0);
2070                 cur.buffer()->updateLabels();
2071                 needsUpdate = true;
2072                 break;
2073
2074         case LFUN_OUTLINE_IN:
2075                 outline(OutlineIn, cur);
2076                 cur.buffer()->updateLabels();
2077                 needsUpdate = true;
2078                 break;
2079
2080         case LFUN_OUTLINE_OUT:
2081                 outline(OutlineOut, cur);
2082                 cur.buffer()->updateLabels();
2083                 needsUpdate = true;
2084                 break;
2085         
2086         case LFUN_OUTLINE_DRAGMOVE: {
2087                 int const move_id = convert<int>(cmd.getArg(0));
2088                 int const move_to_id = convert<int>(cmd.getArg(1));
2089                 dragMove(cur, move_id, move_to_id);
2090                 setCursor(cur, cur.pit(), 0);
2091                 cur.buffer()->updateLabels();
2092                 needsUpdate = true;
2093                 break;
2094         }
2095
2096         default:
2097                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2098                 cur.undispatched();
2099                 break;
2100         }
2101
2102         if (lyxrc.spellcheck_continuously && cur.inTexted())
2103                 // Take this opportunity to spellcheck current word.
2104                 cur.paragraph().isMisspelled(cur.pos());
2105
2106         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2107
2108         // FIXME: The cursor flag is reset two lines below
2109         // so we need to check here if some of the LFUN did touch that.
2110         // for now only Text::erase() and Text::backspace() do that.
2111         // The plan is to verify all the LFUNs and then to remove this
2112         // singleParUpdate boolean altogether.
2113         if (cur.result().update() & Update::Force) {
2114                 singleParUpdate = false;
2115                 needsUpdate = true;
2116         }
2117
2118         // FIXME: the following code should go in favor of fine grained
2119         // update flag treatment.
2120         if (singleParUpdate) {
2121                 // Inserting characters does not change par height in general. So, try
2122                 // to update _only_ this paragraph. BufferView will detect if a full
2123                 // metrics update is needed anyway.
2124                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
2125                 return;
2126         }
2127
2128         if (!needsUpdate
2129             && &oldTopSlice.inset() == &cur.inset()
2130             && oldTopSlice.idx() == cur.idx()
2131             && !sel // sel is a backup of cur.selection() at the biginning of the function.
2132             && !cur.selection())
2133                 // FIXME: it would be better if we could just do this
2134                 //
2135                 //if (cur.result().update() != Update::FitCursor)
2136                 //      cur.noUpdate();
2137                 //
2138                 // But some LFUNs do not set Update::FitCursor when needed, so we
2139                 // do it for all. This is not very harmfull as FitCursor will provoke
2140                 // a full redraw only if needed but still, a proper review of all LFUN
2141                 // should be done and this needsUpdate boolean can then be removed.
2142                 cur.updateFlags(Update::FitCursor);
2143         else
2144                 cur.updateFlags(Update::Force | Update::FitCursor);
2145 }
2146
2147
2148 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2149                         FuncStatus & flag) const
2150 {
2151         LASSERT(cur.text() == this, /**/);
2152
2153         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2154         bool enable = true;
2155         InsetCode code = NO_CODE;
2156
2157         switch (cmd.action) {
2158
2159         case LFUN_DEPTH_DECREMENT:
2160                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2161                 break;
2162
2163         case LFUN_DEPTH_INCREMENT:
2164                 enable = changeDepthAllowed(cur, INC_DEPTH);
2165                 break;
2166
2167         case LFUN_APPENDIX:
2168                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2169                 break;
2170
2171         case LFUN_DIALOG_SHOW_NEW_INSET:
2172                 if (cmd.argument() == "bibitem")
2173                         code = BIBITEM_CODE;
2174                 else if (cmd.argument() == "bibtex") {
2175                         code = BIBTEX_CODE;
2176                         // not allowed in description items
2177                         enable = !inDescriptionItem(cur);
2178                 }
2179                 else if (cmd.argument() == "box")
2180                         code = BOX_CODE;
2181                 else if (cmd.argument() == "branch")
2182                         code = BRANCH_CODE;
2183                 else if (cmd.argument() == "citation")
2184                         code = CITE_CODE;
2185                 else if (cmd.argument() == "ert")
2186                         code = ERT_CODE;
2187                 else if (cmd.argument() == "external")
2188                         code = EXTERNAL_CODE;
2189                 else if (cmd.argument() == "float")
2190                         code = FLOAT_CODE;
2191                 else if (cmd.argument() == "graphics")
2192                         code = GRAPHICS_CODE;
2193                 else if (cmd.argument() == "href")
2194                         code = HYPERLINK_CODE;
2195                 else if (cmd.argument() == "include")
2196                         code = INCLUDE_CODE;
2197                 else if (cmd.argument() == "index")
2198                         code = INDEX_CODE;
2199                 else if (cmd.argument() == "index_print")
2200                         code = INDEX_PRINT_CODE;
2201                 else if (cmd.argument() == "nomenclature")
2202                         code = NOMENCL_CODE;
2203                 else if (cmd.argument() == "nomencl_print")
2204                         code = NOMENCL_PRINT_CODE;
2205                 else if (cmd.argument() == "label")
2206                         code = LABEL_CODE;
2207                 else if (cmd.argument() == "note")
2208                         code = NOTE_CODE;
2209                 else if (cmd.argument() == "phantom")
2210                         code = PHANTOM_CODE;
2211                 else if (cmd.argument() == "ref")
2212                         code = REF_CODE;
2213                 else if (cmd.argument() == "space")
2214                         code = SPACE_CODE;
2215                 else if (cmd.argument() == "toc")
2216                         code = TOC_CODE;
2217                 else if (cmd.argument() == "vspace")
2218                         code = VSPACE_CODE;
2219                 else if (cmd.argument() == "wrap")
2220                         code = WRAP_CODE;
2221                 else if (cmd.argument() == "listings")
2222                         code = LISTINGS_CODE;
2223                 break;
2224
2225         case LFUN_ERT_INSERT:
2226                 code = ERT_CODE;
2227                 break;
2228         case LFUN_LISTING_INSERT:
2229                 code = LISTINGS_CODE;
2230                 // not allowed in description items
2231                 enable = !inDescriptionItem(cur);
2232                 break;
2233         case LFUN_FOOTNOTE_INSERT:
2234                 code = FOOT_CODE;
2235                 break;
2236         case LFUN_TABULAR_INSERT:
2237                 code = TABULAR_CODE;
2238                 break;
2239         case LFUN_MARGINALNOTE_INSERT:
2240                 code = MARGIN_CODE;
2241                 break;
2242         case LFUN_FLOAT_INSERT:
2243         case LFUN_FLOAT_WIDE_INSERT:
2244                 code = FLOAT_CODE;
2245                 // not allowed in description items
2246                 enable = !inDescriptionItem(cur);
2247                 break;
2248         case LFUN_WRAP_INSERT:
2249                 code = WRAP_CODE;
2250                 // not allowed in description items
2251                 enable = !inDescriptionItem(cur);
2252                 break;
2253         case LFUN_FLOAT_LIST_INSERT:
2254                 code = FLOAT_LIST_CODE;
2255                 // not allowed in description items
2256                 enable = !inDescriptionItem(cur);
2257                 break;
2258         case LFUN_CAPTION_INSERT:
2259                 code = CAPTION_CODE;
2260                 // not allowed in description items
2261                 enable = !inDescriptionItem(cur);
2262                 break;
2263         case LFUN_NOTE_INSERT:
2264                 code = NOTE_CODE;
2265                 // in commands (sections etc.) and description items,
2266                 // only Notes are allowed
2267                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2268                           (!cur.paragraph().layout().isCommand()
2269                            && !inDescriptionItem(cur)));
2270                 break;
2271         case LFUN_FLEX_INSERT: {
2272                 code = FLEX_CODE;
2273                 string s = cmd.getArg(0);
2274                 InsetLayout il =
2275                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2276                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2277                     il.lyxtype() != InsetLayout::CUSTOM &&
2278                     il.lyxtype() != InsetLayout::ELEMENT &&
2279                     il.lyxtype ()!= InsetLayout::STANDARD)
2280                         enable = false;
2281                 break;
2282                 }
2283         case LFUN_BOX_INSERT:
2284                 code = BOX_CODE;
2285                 break;
2286         case LFUN_BRANCH_INSERT:
2287                 code = BRANCH_CODE;
2288                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2289                     && cur.buffer()->params().branchlist().empty())
2290                         enable = false;
2291                 break;
2292         case LFUN_PHANTOM_INSERT:
2293                 code = PHANTOM_CODE;
2294                 break;
2295         case LFUN_LABEL_INSERT:
2296                 code = LABEL_CODE;
2297                 break;
2298         case LFUN_INFO_INSERT:
2299                 code = INFO_CODE;
2300                 break;
2301         case LFUN_OPTIONAL_INSERT:
2302                 code = OPTARG_CODE;
2303                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2304                         < cur.paragraph().layout().optionalargs;
2305                 break;
2306         case LFUN_INDEX_INSERT:
2307                 code = INDEX_CODE;
2308                 break;
2309         case LFUN_INDEX_PRINT:
2310                 code = INDEX_PRINT_CODE;
2311                 // not allowed in description items
2312                 enable = !inDescriptionItem(cur);
2313                 break;
2314         case LFUN_NOMENCL_INSERT:
2315                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2316                         enable = false;
2317                         break;
2318                 }
2319                 code = NOMENCL_CODE;
2320                 break;
2321         case LFUN_NOMENCL_PRINT:
2322                 code = NOMENCL_PRINT_CODE;
2323                 // not allowed in description items
2324                 enable = !inDescriptionItem(cur);
2325                 break;
2326         case LFUN_TOC_INSERT:
2327                 code = TOC_CODE;
2328                 // not allowed in description items
2329                 enable = !inDescriptionItem(cur);
2330                 break;
2331         case LFUN_HYPERLINK_INSERT:
2332                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2333                         enable = false;
2334                         break;
2335                 }
2336                 code = HYPERLINK_CODE;
2337                 break;
2338         case LFUN_QUOTE_INSERT:
2339                 // always allow this, since we will inset a raw quote
2340                 // if an inset is not allowed.
2341                 break;
2342         case LFUN_SPECIALCHAR_INSERT:
2343                 code = SPECIALCHAR_CODE;
2344                 break;
2345         case LFUN_SPACE_INSERT:
2346                 // slight hack: we know this is allowed in math mode
2347                 if (cur.inTexted())
2348                         code = SPACE_CODE;
2349                 break;
2350
2351         case LFUN_INSET_MODIFY:
2352                 // We need to disable this, because we may get called for a
2353                 // tabular cell via
2354                 // InsetTabular::getStatus() -> InsetText::getStatus()
2355                 // and we don't handle LFUN_INSET_MODIFY.
2356                 enable = false;
2357                 break;
2358
2359         case LFUN_FONT_EMPH:
2360                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2361                 break;
2362
2363         case LFUN_FONT_ITAL:
2364                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2365                 break;
2366
2367         case LFUN_FONT_NOUN:
2368                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2369                 break;
2370
2371         case LFUN_FONT_BOLD:
2372         case LFUN_FONT_BOLDSYMBOL:
2373                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2374                 break;
2375
2376         case LFUN_FONT_SANS:
2377                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2378                 break;
2379
2380         case LFUN_FONT_ROMAN:
2381                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2382                 break;
2383
2384         case LFUN_FONT_TYPEWRITER:
2385                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2386                 break;
2387
2388         case LFUN_CUT:
2389         case LFUN_COPY:
2390                 enable = cur.selection();
2391                 break;
2392
2393         case LFUN_PASTE: {
2394                 if (cmd.argument().empty()) {
2395                         if (theClipboard().isInternal())
2396                                 enable = cap::numberOfSelections() > 0;
2397                         else
2398                                 enable = !theClipboard().empty();
2399                         break;
2400                 }
2401
2402                 // we have an argument
2403                 string const arg = to_utf8(cmd.argument());
2404                 if (isStrUnsignedInt(arg)) {
2405                         // it's a number and therefore means the internal stack
2406                         unsigned int n = convert<unsigned int>(arg);
2407                         enable = cap::numberOfSelections() > n;
2408                         break;
2409                 }
2410
2411                 // explicit graphics type?
2412                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2413                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2414                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2415                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2416                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2417                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2418                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2419                         enable = theClipboard().hasGraphicsContents(type);
2420                         break;
2421                 }
2422
2423                 // unknown argument
2424                 enable = false;
2425                 break;
2426          }
2427
2428         case LFUN_CLIPBOARD_PASTE:
2429                 enable = !theClipboard().empty();
2430                 break;
2431
2432         case LFUN_PRIMARY_SELECTION_PASTE:
2433                 enable = cur.selection() || !theSelection().empty();
2434                 break;
2435
2436         case LFUN_SELECTION_PASTE:
2437                 enable = cap::selection();
2438                 break;
2439
2440         case LFUN_PARAGRAPH_MOVE_UP:
2441                 enable = cur.pit() > 0 && !cur.selection();
2442                 break;
2443
2444         case LFUN_PARAGRAPH_MOVE_DOWN:
2445                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2446                 break;
2447
2448         case LFUN_INSET_DISSOLVE:
2449                 if (!cmd.argument().empty()) {
2450                         InsetLayout const & il = cur.inset().getLayout();
2451                         InsetLayout::InsetLyXType const type = 
2452                                         translateLyXType(to_utf8(cmd.argument()));
2453                         enable = cur.inset().lyxCode() == FLEX_CODE
2454                                  && il.lyxtype() == type;
2455                 } else {
2456                         enable = ((!isMainText(cur.bv().buffer())
2457                                       && cur.inset().nargs() == 1)
2458                                   || (cur.nextInset()
2459                                       && cur.nextInset()->nargs() == 1));
2460                 }
2461                 break;
2462
2463         case LFUN_CHANGE_ACCEPT:
2464         case LFUN_CHANGE_REJECT:
2465                 // In principle, these LFUNs should only be enabled if there
2466                 // is a change at the current position/in the current selection.
2467                 // However, without proper optimizations, this will inevitably
2468                 // result in unacceptable performance - just imagine a user who
2469                 // wants to select the complete content of a long document.
2470                 if (!cur.selection()) {
2471                         Change const & change = cur.paragraph().lookupChange(cur.pos());
2472                         enable = change.changed();
2473                 } else
2474                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2475                         // for selections.
2476                         enable = true;
2477                 break;
2478
2479         case LFUN_OUTLINE_UP:
2480         case LFUN_OUTLINE_DOWN:
2481         case LFUN_OUTLINE_IN:
2482         case LFUN_OUTLINE_OUT:
2483         case LFUN_OUTLINE_DRAGMOVE:
2484                 // FIXME: LyX is not ready for outlining within inset.
2485                 enable = isMainText(cur.bv().buffer())
2486                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2487                 break;
2488
2489         case LFUN_NEWLINE_INSERT:
2490                 // LaTeX restrictions (labels or empty par)
2491                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2492                 break;
2493
2494         case LFUN_SET_GRAPHICS_GROUP: {
2495                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2496                 if (!ins)
2497                         enable = false;
2498                 else
2499                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2500                 break;
2501         }
2502
2503         case LFUN_NEWPAGE_INSERT:
2504                 // not allowed in description items
2505                 enable = !inDescriptionItem(cur);
2506                 break;
2507
2508         case LFUN_MATH_INSERT:
2509         case LFUN_MATH_AMS_MATRIX:
2510         case LFUN_MATH_MATRIX:
2511         case LFUN_MATH_DELIM:
2512         case LFUN_MATH_BIGDELIM:
2513                 // not allowed in ERT, for example.
2514                 enable = cur.inset().insetAllowed(MATH_CODE);
2515                 break;
2516
2517         case LFUN_DATE_INSERT: {
2518                 string const format = cmd.argument().empty()
2519                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2520                 enable = support::os::is_valid_strftime(format);
2521                 break;
2522         }
2523
2524         case LFUN_WORD_DELETE_FORWARD:
2525         case LFUN_WORD_DELETE_BACKWARD:
2526         case LFUN_LINE_DELETE:
2527         case LFUN_WORD_FORWARD:
2528         case LFUN_WORD_BACKWARD:
2529         case LFUN_WORD_RIGHT:
2530         case LFUN_WORD_LEFT:
2531         case LFUN_CHAR_FORWARD:
2532         case LFUN_CHAR_FORWARD_SELECT:
2533         case LFUN_CHAR_BACKWARD:
2534         case LFUN_CHAR_BACKWARD_SELECT:
2535         case LFUN_CHAR_LEFT:
2536         case LFUN_CHAR_LEFT_SELECT:
2537         case LFUN_CHAR_RIGHT:
2538         case LFUN_CHAR_RIGHT_SELECT:
2539         case LFUN_UP:
2540         case LFUN_UP_SELECT:
2541         case LFUN_DOWN:
2542         case LFUN_DOWN_SELECT:
2543         case LFUN_PARAGRAPH_UP_SELECT:
2544         case LFUN_PARAGRAPH_DOWN_SELECT:
2545         case LFUN_LINE_BEGIN_SELECT:
2546         case LFUN_LINE_END_SELECT:
2547         case LFUN_WORD_FORWARD_SELECT:
2548         case LFUN_WORD_BACKWARD_SELECT:
2549         case LFUN_WORD_RIGHT_SELECT:
2550         case LFUN_WORD_LEFT_SELECT:
2551         case LFUN_WORD_SELECT:
2552         case LFUN_SECTION_SELECT:
2553         case LFUN_PARAGRAPH_UP:
2554         case LFUN_PARAGRAPH_DOWN:
2555         case LFUN_LINE_BEGIN:
2556         case LFUN_LINE_END:
2557         case LFUN_CHAR_DELETE_FORWARD:
2558         case LFUN_CHAR_DELETE_BACKWARD:
2559         case LFUN_BREAK_PARAGRAPH:
2560         case LFUN_PARAGRAPH_SPACING:
2561         case LFUN_INSET_INSERT:
2562         case LFUN_WORD_UPCASE:
2563         case LFUN_WORD_LOWCASE:
2564         case LFUN_WORD_CAPITALIZE:
2565         case LFUN_CHARS_TRANSPOSE:
2566         case LFUN_SERVER_GET_XY:
2567         case LFUN_SERVER_SET_XY:
2568         case LFUN_SERVER_GET_LAYOUT:
2569         case LFUN_LAYOUT:
2570         case LFUN_SELF_INSERT:
2571         case LFUN_LINE_INSERT:
2572         case LFUN_MATH_DISPLAY:
2573         case LFUN_MATH_MODE:
2574         case LFUN_MATH_MACRO:
2575         case LFUN_MATH_SUBSCRIPT:
2576         case LFUN_MATH_SUPERSCRIPT:
2577         case LFUN_FONT_DEFAULT:
2578         case LFUN_FONT_UNDERLINE:
2579         case LFUN_FONT_STRIKEOUT:
2580         case LFUN_FONT_UULINE:
2581         case LFUN_FONT_UWAVE:
2582         case LFUN_FONT_SIZE:
2583         case LFUN_LANGUAGE:
2584         case LFUN_TEXTSTYLE_APPLY:
2585         case LFUN_TEXTSTYLE_UPDATE:
2586         case LFUN_LAYOUT_PARAGRAPH:
2587         case LFUN_PARAGRAPH_UPDATE:
2588         case LFUN_ACCENT_UMLAUT:
2589         case LFUN_ACCENT_CIRCUMFLEX:
2590         case LFUN_ACCENT_GRAVE:
2591         case LFUN_ACCENT_ACUTE:
2592         case LFUN_ACCENT_TILDE:
2593         case LFUN_ACCENT_CEDILLA:
2594         case LFUN_ACCENT_MACRON:
2595         case LFUN_ACCENT_DOT:
2596         case LFUN_ACCENT_UNDERDOT:
2597         case LFUN_ACCENT_UNDERBAR:
2598         case LFUN_ACCENT_CARON:
2599         case LFUN_ACCENT_BREVE:
2600         case LFUN_ACCENT_TIE:
2601         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2602         case LFUN_ACCENT_CIRCLE:
2603         case LFUN_ACCENT_OGONEK:
2604         case LFUN_THESAURUS_ENTRY:
2605         case LFUN_PARAGRAPH_PARAMS_APPLY:
2606         case LFUN_PARAGRAPH_PARAMS:
2607         case LFUN_ESCAPE:
2608         case LFUN_BUFFER_BEGIN:
2609         case LFUN_BUFFER_END:
2610         case LFUN_BUFFER_BEGIN_SELECT:
2611         case LFUN_BUFFER_END_SELECT:
2612         case LFUN_INSET_BEGIN:
2613         case LFUN_INSET_END:
2614         case LFUN_INSET_BEGIN_SELECT:
2615         case LFUN_INSET_END_SELECT:
2616         case LFUN_UNICODE_INSERT:
2617                 // these are handled in our dispatch()
2618                 enable = true;
2619                 break;
2620
2621         default:
2622                 return false;
2623         }
2624
2625         if (code != NO_CODE
2626             && (cur.empty() || !cur.inset().insetAllowed(code)))
2627                 enable = false;
2628
2629         flag.setEnabled(enable);
2630         return true;
2631 }
2632
2633
2634 void Text::pasteString(Cursor & cur, docstring const & clip,
2635                 bool asParagraphs)
2636 {
2637         cur.clearSelection();
2638         if (!clip.empty()) {
2639                 cur.recordUndo();
2640                 if (asParagraphs)
2641                         insertStringAsParagraphs(cur, clip);
2642                 else
2643                         insertStringAsLines(cur, clip);
2644         }
2645 }
2646
2647
2648 // FIXME: an item inset would make things much easier.
2649 bool Text::inDescriptionItem(Cursor & cur) const
2650 {
2651         Paragraph & par = cur.paragraph();
2652         pos_type const pos = cur.pos();
2653         pos_type const body_pos = par.beginOfBody();
2654
2655         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2656             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2657                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2658                 return false;
2659
2660         return (pos < body_pos
2661                 || (pos == body_pos
2662                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2663 }
2664
2665 } // namespace lyx