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