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