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