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