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