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