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