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