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