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