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