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