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