]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Fix some group boxes.
[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(Paragraph const & par) const
566 {
567         Buffer const & buffer = owner_->buffer();
568         return par.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                 if (r > 2) {
2130                         // go into table
2131                         cur.backwardPos();
2132                         // move one cell up to middle cell
2133                         cur.up();
2134                         // now add the missing rows and columns
2135                         int const addrows = r - 3;
2136                         int const addcols = c - 1;
2137                         for (int i = 0 ; i < addrows ; ++i) {
2138                                 FuncRequest fr(LFUN_TABULAR_FEATURE, "append-row");
2139                                 lyx::dispatch(fr);
2140                         }
2141                         for (int i = 0 ; i < addcols ; ++i) {
2142                                 FuncRequest fr(LFUN_TABULAR_FEATURE, "append-column");
2143                                 lyx::dispatch(fr);
2144                         }
2145                         // go to first cell
2146                         cur.up();
2147                 } else {
2148                         // jump over table
2149                         cur.backwardChar();
2150                         // go to first cell
2151                         cur.forwardPos();
2152                 }
2153                 break;
2154         }
2155
2156         case LFUN_FLOAT_INSERT:
2157         case LFUN_FLOAT_WIDE_INSERT:
2158         case LFUN_WRAP_INSERT: {
2159                 // will some content be moved into the inset?
2160                 bool const content = cur.selection();
2161                 // does the content consist of multiple paragraphs?
2162                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2163
2164                 doInsertInset(cur, this, cmd, true, true);
2165                 cur.posForward();
2166
2167                 // If some single-par content is moved into the inset,
2168                 // doInsertInset puts the cursor outside the inset.
2169                 // To insert the caption we put it back into the inset.
2170                 // FIXME cleanup doInsertInset to avoid such dances!
2171                 if (content && singlepar)
2172                         cur.backwardPos();
2173
2174                 ParagraphList & pars = cur.text()->paragraphs();
2175
2176                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2177
2178                 // add a separate paragraph for the caption inset
2179                 pars.push_back(Paragraph());
2180                 pars.back().setInsetOwner(&cur.text()->inset());
2181                 pars.back().setPlainOrDefaultLayout(tclass);
2182                 int cap_pit = pars.size() - 1;
2183
2184                 // if an empty inset was created, we create an additional empty
2185                 // paragraph at the bottom so that the user can choose where to put
2186                 // the graphics (or table).
2187                 if (!content) {
2188                         pars.push_back(Paragraph());
2189                         pars.back().setInsetOwner(&cur.text()->inset());
2190                         pars.back().setPlainOrDefaultLayout(tclass);
2191                 }
2192
2193                 // reposition the cursor to the caption
2194                 cur.pit() = cap_pit;
2195                 cur.pos() = 0;
2196                 // FIXME: This Text/Cursor dispatch handling is a mess!
2197                 // We cannot use Cursor::dispatch here it needs access to up to
2198                 // date metrics.
2199                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2200                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2201                 cur.forceBufferUpdate();
2202                 cur.screenUpdateFlags(Update::Force);
2203                 // FIXME: When leaving the Float (or Wrap) inset we should
2204                 // delete any empty paragraph left above or below the
2205                 // caption.
2206                 break;
2207         }
2208
2209         case LFUN_NOMENCL_INSERT: {
2210                 InsetCommandParams p(NOMENCL_CODE);
2211                 if (cmd.argument().empty()) {
2212                         p["symbol"] = 
2213                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2214                         cur.clearSelection();
2215                 } else
2216                         p["symbol"] = cmd.argument();
2217                 string const data = InsetCommand::params2string(p);
2218                 bv->showDialog("nomenclature", data);
2219                 break;
2220         }
2221
2222         case LFUN_INDEX_PRINT: {
2223                 InsetCommandParams p(INDEX_PRINT_CODE);
2224                 if (cmd.argument().empty())
2225                         p["type"] = from_ascii("idx");
2226                 else
2227                         p["type"] = cmd.argument();
2228                 string const data = InsetCommand::params2string(p);
2229                 FuncRequest fr(LFUN_INSET_INSERT, data);
2230                 dispatch(cur, fr);
2231                 break;
2232         }
2233
2234         case LFUN_NOMENCL_PRINT:
2235         case LFUN_NEWPAGE_INSERT:
2236                 // do nothing fancy
2237                 doInsertInset(cur, this, cmd, false, false);
2238                 cur.posForward();
2239                 break;
2240
2241         case LFUN_SEPARATOR_INSERT: {
2242                 doInsertInset(cur, this, cmd, false, false);
2243                 cur.posForward();
2244                 // remove a following space
2245                 Paragraph & par = cur.paragraph();
2246                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2247                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2248                 break;
2249         }
2250
2251         case LFUN_DEPTH_DECREMENT:
2252                 changeDepth(cur, DEC_DEPTH);
2253                 break;
2254
2255         case LFUN_DEPTH_INCREMENT:
2256                 changeDepth(cur, INC_DEPTH);
2257                 break;
2258
2259         case LFUN_REGEXP_MODE:
2260                 regexpDispatch(cur, cmd);
2261                 break;
2262
2263         case LFUN_MATH_MODE: {
2264                 if (cmd.argument() == "on" || cmd.argument() == "") {
2265                         // don't pass "on" as argument
2266                         // (it would appear literally in the first cell)
2267                         docstring sel = cur.selectionAsString(false);
2268                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2269                         // create a macro template if we see "\\newcommand" somewhere, and
2270                         // an ordinary formula otherwise
2271                         if (!sel.empty()
2272                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2273                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2274                                         || sel.find(from_ascii("\\def")) != string::npos)
2275                                 && macro->fromString(sel)) {
2276                                 cur.recordUndo();
2277                                 replaceSelection(cur);
2278                                 cur.insert(macro);
2279                         } else {
2280                                 // no meaningful macro template was found
2281                                 delete macro;
2282                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2283                         }
2284                 } else
2285                         // The argument is meaningful
2286                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2287                         // has a different meaning in math mode
2288                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2289                 break;
2290         }
2291
2292         case LFUN_MATH_MACRO:
2293                 if (cmd.argument().empty())
2294                         cur.errorMessage(from_utf8(N_("Missing argument")));
2295                 else {
2296                         cur.recordUndo();
2297                         string s = to_utf8(cmd.argument());
2298                         string const s1 = token(s, ' ', 1);
2299                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2300                         string const s2 = token(s, ' ', 2);
2301                         MacroType type = MacroTypeNewcommand;
2302                         if (s2 == "def")
2303                                 type = MacroTypeDef;
2304                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2305                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2306                         inset->setBuffer(bv->buffer());
2307                         insertInset(cur, inset);
2308
2309                         // enter macro inset and select the name
2310                         cur.push(*inset);
2311                         cur.top().pos() = cur.top().lastpos();
2312                         cur.resetAnchor();
2313                         cur.selection(true);
2314                         cur.top().pos() = 0;
2315                 }
2316                 break;
2317
2318         case LFUN_MATH_DISPLAY:
2319         case LFUN_MATH_SUBSCRIPT:
2320         case LFUN_MATH_SUPERSCRIPT:
2321         case LFUN_MATH_INSERT:
2322         case LFUN_MATH_AMS_MATRIX:
2323         case LFUN_MATH_MATRIX:
2324         case LFUN_MATH_DELIM:
2325         case LFUN_MATH_BIGDELIM:
2326                 mathDispatch(cur, cmd);
2327                 break;
2328
2329         case LFUN_FONT_EMPH: {
2330                 Font font(ignore_font, ignore_language);
2331                 font.fontInfo().setEmph(FONT_TOGGLE);
2332                 toggleAndShow(cur, this, font);
2333                 break;
2334         }
2335
2336         case LFUN_FONT_ITAL: {
2337                 Font font(ignore_font, ignore_language);
2338                 font.fontInfo().setShape(ITALIC_SHAPE);
2339                 toggleAndShow(cur, this, font);
2340                 break;
2341         }
2342
2343         case LFUN_FONT_BOLD:
2344         case LFUN_FONT_BOLDSYMBOL: {
2345                 Font font(ignore_font, ignore_language);
2346                 font.fontInfo().setSeries(BOLD_SERIES);
2347                 toggleAndShow(cur, this, font);
2348                 break;
2349         }
2350
2351         case LFUN_FONT_NOUN: {
2352                 Font font(ignore_font, ignore_language);
2353                 font.fontInfo().setNoun(FONT_TOGGLE);
2354                 toggleAndShow(cur, this, font);
2355                 break;
2356         }
2357
2358         case LFUN_FONT_TYPEWRITER: {
2359                 Font font(ignore_font, ignore_language);
2360                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2361                 toggleAndShow(cur, this, font);
2362                 break;
2363         }
2364
2365         case LFUN_FONT_SANS: {
2366                 Font font(ignore_font, ignore_language);
2367                 font.fontInfo().setFamily(SANS_FAMILY);
2368                 toggleAndShow(cur, this, font);
2369                 break;
2370         }
2371
2372         case LFUN_FONT_ROMAN: {
2373                 Font font(ignore_font, ignore_language);
2374                 font.fontInfo().setFamily(ROMAN_FAMILY);
2375                 toggleAndShow(cur, this, font);
2376                 break;
2377         }
2378
2379         case LFUN_FONT_DEFAULT: {
2380                 Font font(inherit_font, ignore_language);
2381                 toggleAndShow(cur, this, font);
2382                 break;
2383         }
2384
2385         case LFUN_FONT_STRIKEOUT: {
2386                 Font font(ignore_font, ignore_language);
2387                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2388                 toggleAndShow(cur, this, font);
2389                 break;
2390         }
2391
2392         case LFUN_FONT_CROSSOUT: {
2393                 Font font(ignore_font, ignore_language);
2394                 font.fontInfo().setXout(FONT_TOGGLE);
2395                 toggleAndShow(cur, this, font);
2396                 break;
2397         }
2398
2399         case LFUN_FONT_UNDERUNDERLINE: {
2400                 Font font(ignore_font, ignore_language);
2401                 font.fontInfo().setUuline(FONT_TOGGLE);
2402                 toggleAndShow(cur, this, font);
2403                 break;
2404         }
2405
2406         case LFUN_FONT_UNDERWAVE: {
2407                 Font font(ignore_font, ignore_language);
2408                 font.fontInfo().setUwave(FONT_TOGGLE);
2409                 toggleAndShow(cur, this, font);
2410                 break;
2411         }
2412
2413         case LFUN_FONT_UNDERLINE: {
2414                 Font font(ignore_font, ignore_language);
2415                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2416                 toggleAndShow(cur, this, font);
2417                 break;
2418         }
2419
2420         case LFUN_FONT_SIZE: {
2421                 Font font(ignore_font, ignore_language);
2422                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2423                 toggleAndShow(cur, this, font);
2424                 break;
2425         }
2426
2427         case LFUN_LANGUAGE: {
2428                 string const lang_arg = cmd.getArg(0);
2429                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2430                 Language const * lang =
2431                         reset ? reset_language
2432                               : languages.getLanguage(lang_arg);
2433                 // we allow reset_language, which is 0, but only if it
2434                 // was requested via empty or "reset" arg.
2435                 if (!lang && !reset)
2436                         break;
2437                 bool const toggle = (cmd.getArg(1) != "set");
2438                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2439                 Font font(ignore_font, lang);
2440                 toggleAndShow(cur, this, font, toggle);
2441                 // We need a buffer update if we change the language
2442                 // of an info inset
2443                 if (cur.insetInSelection(INFO_CODE))
2444                         cur.forceBufferUpdate();
2445                 break;
2446         }
2447
2448         case LFUN_TEXTSTYLE_APPLY: {
2449                 unsigned int num = 0;
2450                 string const arg = to_utf8(cmd.argument());
2451                 // Argument?
2452                 if (!arg.empty()) {
2453                         if (isStrUnsignedInt(arg)) {
2454                                 num = convert<uint>(arg);
2455                                 if (num >= freeFonts.size()) {
2456                                         cur.message(_("Invalid argument (number exceeds stack size)!"));
2457                                         break;
2458                                 }
2459                         } else {
2460                                 cur.message(_("Invalid argument (must be a non-negative number)!"));
2461                                 break;
2462                         }
2463                 }
2464                 toggleAndShow(cur, this, freeFonts[num].second, toggleall);
2465                 cur.message(bformat(_("Text properties applied: %1$s"), freeFonts[num].first));
2466                 break;
2467         }
2468
2469         // Set the freefont using the contents of \param data dispatched from
2470         // the frontends and apply it at the current cursor location.
2471         case LFUN_TEXTSTYLE_UPDATE: {
2472                 Font font(ignore_font, ignore_language);
2473                 bool toggle;
2474                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2475                         docstring const props = font.stateText(&bv->buffer().params(), true);
2476                         freeFonts.push(make_pair(props, font));
2477                         toggleall = toggle;
2478                         toggleAndShow(cur, this, font, toggleall);
2479                         // We need a buffer update if we change the language
2480                         // of an info inset
2481                         if (cur.insetInSelection(INFO_CODE))
2482                                 cur.forceBufferUpdate();
2483                         cur.message(bformat(_("Text properties applied: %1$s"), props));
2484                 } else
2485                         LYXERR0("Invalid argument of textstyle-update");
2486                 break;
2487         }
2488
2489         case LFUN_FINISHED_LEFT:
2490                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2491                 // We're leaving an inset, going left. If the inset is LTR, we're
2492                 // leaving from the front, so we should not move (remain at --- but
2493                 // not in --- the inset). If the inset is RTL, move left, without
2494                 // entering the inset itself; i.e., move to after the inset.
2495                 if (cur.paragraph().getFontSettings(
2496                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2497                         cursorVisLeft(cur, true);
2498                 break;
2499
2500         case LFUN_FINISHED_RIGHT:
2501                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2502                 // We're leaving an inset, going right. If the inset is RTL, we're
2503                 // leaving from the front, so we should not move (remain at --- but
2504                 // not in --- the inset). If the inset is LTR, move right, without
2505                 // entering the inset itself; i.e., move to after the inset.
2506                 if (!cur.paragraph().getFontSettings(
2507                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2508                         cursorVisRight(cur, true);
2509                 break;
2510
2511         case LFUN_FINISHED_BACKWARD:
2512                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2513                 cur.setCurrentFont();
2514                 break;
2515
2516         case LFUN_FINISHED_FORWARD:
2517                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2518                 ++cur.pos();
2519                 cur.setCurrentFont();
2520                 break;
2521
2522         case LFUN_LAYOUT_PARAGRAPH: {
2523                 string data;
2524                 params2string(cur.paragraph(), data);
2525                 data = "show\n" + data;
2526                 bv->showDialog("paragraph", data);
2527                 break;
2528         }
2529
2530         case LFUN_PARAGRAPH_UPDATE: {
2531                 string data;
2532                 params2string(cur.paragraph(), data);
2533
2534                 // Will the paragraph accept changes from the dialog?
2535                 bool const accept =
2536                         cur.inset().allowParagraphCustomization(cur.idx());
2537
2538                 data = "update " + convert<string>(accept) + '\n' + data;
2539                 bv->updateDialog("paragraph", data);
2540                 break;
2541         }
2542
2543         case LFUN_ACCENT_UMLAUT:
2544         case LFUN_ACCENT_CIRCUMFLEX:
2545         case LFUN_ACCENT_GRAVE:
2546         case LFUN_ACCENT_ACUTE:
2547         case LFUN_ACCENT_TILDE:
2548         case LFUN_ACCENT_PERISPOMENI:
2549         case LFUN_ACCENT_CEDILLA:
2550         case LFUN_ACCENT_MACRON:
2551         case LFUN_ACCENT_DOT:
2552         case LFUN_ACCENT_UNDERDOT:
2553         case LFUN_ACCENT_UNDERBAR:
2554         case LFUN_ACCENT_CARON:
2555         case LFUN_ACCENT_BREVE:
2556         case LFUN_ACCENT_TIE:
2557         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2558         case LFUN_ACCENT_CIRCLE:
2559         case LFUN_ACCENT_OGONEK:
2560                 theApp()->handleKeyFunc(cmd.action());
2561                 if (!cmd.argument().empty())
2562                         // FIXME: Are all these characters encoded in one byte in utf8?
2563                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2564                 cur.screenUpdateFlags(Update::FitCursor);
2565                 break;
2566
2567         case LFUN_FLOAT_LIST_INSERT: {
2568                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2569                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2570                         cur.recordUndo();
2571                         if (cur.selection())
2572                                 cutSelection(cur, false);
2573                         breakParagraph(cur);
2574
2575                         if (cur.lastpos() != 0) {
2576                                 cursorBackward(cur);
2577                                 breakParagraph(cur);
2578                         }
2579
2580                         docstring const laystr = cur.inset().usePlainLayout() ?
2581                                 tclass.plainLayoutName() :
2582                                 tclass.defaultLayoutName();
2583                         setLayout(cur, laystr);
2584                         ParagraphParameters p;
2585                         // FIXME If this call were replaced with one to clearParagraphParams(),
2586                         // then we could get rid of this method altogether.
2587                         setParagraphs(cur, p);
2588                         // FIXME This should be simplified when InsetFloatList takes a
2589                         // Buffer in its constructor.
2590                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2591                         ifl->setBuffer(bv->buffer());
2592                         insertInset(cur, ifl);
2593                         cur.posForward();
2594                 } else {
2595                         lyxerr << "Non-existent float type: "
2596                                << to_utf8(cmd.argument()) << endl;
2597                 }
2598                 break;
2599         }
2600
2601         case LFUN_CHANGE_ACCEPT: {
2602                 acceptOrRejectChanges(cur, ACCEPT);
2603                 break;
2604         }
2605
2606         case LFUN_CHANGE_REJECT: {
2607                 acceptOrRejectChanges(cur, REJECT);
2608                 break;
2609         }
2610
2611         case LFUN_THESAURUS_ENTRY: {
2612                 Language const * language = cur.getFont().language();
2613                 docstring arg = cmd.argument();
2614                 if (arg.empty()) {
2615                         arg = cur.selectionAsString(false);
2616                         // FIXME
2617                         if (arg.size() > 100 || arg.empty()) {
2618                                 // Get word or selection
2619                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2620                                 arg = cur.selectionAsString(false);
2621                                 arg += " lang=" + from_ascii(language->lang());
2622                         }
2623                 } else {
2624                         string lang = cmd.getArg(1);
2625                         // This duplicates the code in GuiThesaurus::initialiseParams
2626                         if (prefixIs(lang, "lang=")) {
2627                                 language = languages.getLanguage(lang.substr(5));
2628                                 if (!language)
2629                                         language = cur.getFont().language();
2630                         }
2631                 }
2632                 string lang = language->code();
2633                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2634                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2635                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2636                                         _("The path to the thesaurus directory has not been specified.\n"
2637                                           "The thesaurus is not functional.\n"
2638                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2639                                           "instructions."));
2640                 }
2641                 bv->showDialog("thesaurus", to_utf8(arg));
2642                 break;
2643         }
2644
2645         case LFUN_SPELLING_ADD: {
2646                 Language const * language = getLanguage(cur, cmd.getArg(1));
2647                 docstring word = from_utf8(cmd.getArg(0));
2648                 if (word.empty()) {
2649                         word = cur.selectionAsString(false);
2650                         // FIXME
2651                         if (word.size() > 100 || word.empty()) {
2652                                 // Get word or selection
2653                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2654                                 word = cur.selectionAsString(false);
2655                         }
2656                 }
2657                 WordLangTuple wl(word, language);
2658                 theSpellChecker()->insert(wl);
2659                 break;
2660         }
2661
2662         case LFUN_SPELLING_IGNORE: {
2663                 Language const * language = getLanguage(cur, cmd.getArg(1));
2664                 docstring word = from_utf8(cmd.getArg(0));
2665                 if (word.empty()) {
2666                         word = cur.selectionAsString(false);
2667                         // FIXME
2668                         if (word.size() > 100 || word.empty()) {
2669                                 // Get word or selection
2670                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2671                                 word = cur.selectionAsString(false);
2672                         }
2673                 }
2674                 WordLangTuple wl(word, language);
2675                 theSpellChecker()->accept(wl);
2676                 break;
2677         }
2678
2679         case LFUN_SPELLING_REMOVE: {
2680                 Language const * language = getLanguage(cur, cmd.getArg(1));
2681                 docstring word = from_utf8(cmd.getArg(0));
2682                 if (word.empty()) {
2683                         word = cur.selectionAsString(false);
2684                         // FIXME
2685                         if (word.size() > 100 || word.empty()) {
2686                                 // Get word or selection
2687                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2688                                 word = cur.selectionAsString(false);
2689                         }
2690                 }
2691                 WordLangTuple wl(word, language);
2692                 theSpellChecker()->remove(wl);
2693                 break;
2694         }
2695
2696         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2697                 // Given data, an encoding of the ParagraphParameters
2698                 // generated in the Paragraph dialog, this function sets
2699                 // the current paragraph, or currently selected paragraphs,
2700                 // appropriately.
2701                 // NOTE: This function overrides all existing settings.
2702                 setParagraphs(cur, cmd.argument());
2703                 cur.message(_("Paragraph layout set"));
2704                 break;
2705         }
2706
2707         case LFUN_PARAGRAPH_PARAMS: {
2708                 // Given data, an encoding of the ParagraphParameters as we'd
2709                 // find them in a LyX file, this function modifies the current paragraph,
2710                 // or currently selected paragraphs.
2711                 // NOTE: This function only modifies, and does not override, existing
2712                 // settings.
2713                 setParagraphs(cur, cmd.argument(), true);
2714                 cur.message(_("Paragraph layout set"));
2715                 break;
2716         }
2717
2718         case LFUN_ESCAPE:
2719                 if (cur.selection()) {
2720                         cur.selection(false);
2721                 } else {
2722                         cur.undispatched();
2723                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2724                         // correct, but I'm not 100% sure -- dov, 071019
2725                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2726                 }
2727                 break;
2728
2729         case LFUN_OUTLINE_UP:
2730                 outline(OutlineUp, cur, this);
2731                 setCursor(cur, cur.pit(), 0);
2732                 cur.forceBufferUpdate();
2733                 needsUpdate = true;
2734                 break;
2735
2736         case LFUN_OUTLINE_DOWN:
2737                 outline(OutlineDown, cur, this);
2738                 setCursor(cur, cur.pit(), 0);
2739                 cur.forceBufferUpdate();
2740                 needsUpdate = true;
2741                 break;
2742
2743         case LFUN_OUTLINE_IN:
2744                 outline(OutlineIn, cur, this);
2745                 cur.forceBufferUpdate();
2746                 needsUpdate = true;
2747                 break;
2748
2749         case LFUN_OUTLINE_OUT:
2750                 outline(OutlineOut, cur, this);
2751                 cur.forceBufferUpdate();
2752                 needsUpdate = true;
2753                 break;
2754
2755         case LFUN_SERVER_GET_STATISTICS:
2756                 {
2757                         DocIterator from, to;
2758                         if (cur.selection()) {
2759                                 from = cur.selectionBegin();
2760                                 to = cur.selectionEnd();
2761                         } else {
2762                                 from = doc_iterator_begin(cur.buffer());
2763                                 to = doc_iterator_end(cur.buffer());
2764                         }
2765
2766                         cur.buffer()->updateStatistics(from, to);
2767                         string const arg0 = cmd.getArg(0);
2768                         if (arg0 == "words") {
2769                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2770                         } else if (arg0 == "chars") {
2771                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2772                         } else if (arg0 == "chars-space") {
2773                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2774                         } else {
2775                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2776                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2777                                 + convert<docstring>(cur.buffer()->charCount(true)));
2778                         }
2779                 }
2780                 break;
2781
2782         default:
2783                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2784                 cur.undispatched();
2785                 break;
2786         }
2787
2788         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2789
2790         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2791                 // Check for misspelled text
2792                 // The redraw is useful because of the painting of
2793                 // misspelled markers depends on the cursor position.
2794                 // Trigger a redraw for cursor moves inside misspelled text.
2795                 if (!cur.inTexted()) {
2796                         // move from regular text to math
2797                         needsUpdate = last_misspelled;
2798                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2799                         // move inside regular text
2800                         needsUpdate = last_misspelled
2801                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2802                 }
2803         }
2804
2805         // FIXME: The cursor flag is reset two lines below
2806         // so we need to check here if some of the LFUN did touch that.
2807         // for now only Text::erase() and Text::backspace() do that.
2808         // The plan is to verify all the LFUNs and then to remove this
2809         // singleParUpdate boolean altogether.
2810         if (cur.result().screenUpdate() & Update::Force) {
2811                 singleParUpdate = false;
2812                 needsUpdate = true;
2813         }
2814
2815         // FIXME: the following code should go in favor of fine grained
2816         // update flag treatment.
2817         if (singleParUpdate) {
2818                 // Inserting characters does not change par height in general. So, try
2819                 // to update _only_ this paragraph. BufferView will detect if a full
2820                 // metrics update is needed anyway.
2821                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2822                 return;
2823         }
2824         if (!needsUpdate
2825             && &oldTopSlice.inset() == &cur.inset()
2826             && oldTopSlice.idx() == cur.idx()
2827             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2828             && !cur.selection())
2829                 // FIXME: it would be better if we could just do this
2830                 //
2831                 //if (cur.result().update() != Update::FitCursor)
2832                 //      cur.noScreenUpdate();
2833                 //
2834                 // But some LFUNs do not set Update::FitCursor when needed, so we
2835                 // do it for all. This is not very harmfull as FitCursor will provoke
2836                 // a full redraw only if needed but still, a proper review of all LFUN
2837                 // should be done and this needsUpdate boolean can then be removed.
2838                 cur.screenUpdateFlags(Update::FitCursor);
2839         else
2840                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2841 }
2842
2843
2844 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2845                         FuncStatus & flag) const
2846 {
2847         LBUFERR(this == cur.text());
2848
2849         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2850         bool enable = true;
2851         bool allow_in_passthru = false;
2852         InsetCode code = NO_CODE;
2853         
2854         switch (cmd.action()) {
2855
2856         case LFUN_DEPTH_DECREMENT:
2857                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2858                 break;
2859
2860         case LFUN_DEPTH_INCREMENT:
2861                 enable = changeDepthAllowed(cur, INC_DEPTH);
2862                 break;
2863
2864         case LFUN_APPENDIX:
2865                 // FIXME We really should not allow this to be put, e.g.,
2866                 // in a footnote, or in ERT. But it would make sense in a
2867                 // branch, so I'm not sure what to do.
2868                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2869                 break;
2870
2871         case LFUN_DIALOG_SHOW_NEW_INSET:
2872                 if (cmd.argument() == "bibitem")
2873                         code = BIBITEM_CODE;
2874                 else if (cmd.argument() == "bibtex") {
2875                         code = BIBTEX_CODE;
2876                         // not allowed in description items
2877                         enable = !inDescriptionItem(cur);
2878                 }
2879                 else if (cmd.argument() == "box")
2880                         code = BOX_CODE;
2881                 else if (cmd.argument() == "branch")
2882                         code = BRANCH_CODE;
2883                 else if (cmd.argument() == "citation")
2884                         code = CITE_CODE;
2885                 else if (cmd.argument() == "ert")
2886                         code = ERT_CODE;
2887                 else if (cmd.argument() == "external")
2888                         code = EXTERNAL_CODE;
2889                 else if (cmd.argument() == "float")
2890                         code = FLOAT_CODE;
2891                 else if (cmd.argument() == "graphics")
2892                         code = GRAPHICS_CODE;
2893                 else if (cmd.argument() == "href")
2894                         code = HYPERLINK_CODE;
2895                 else if (cmd.argument() == "include")
2896                         code = INCLUDE_CODE;
2897                 else if (cmd.argument() == "index")
2898                         code = INDEX_CODE;
2899                 else if (cmd.argument() == "index_print")
2900                         code = INDEX_PRINT_CODE;
2901                 else if (cmd.argument() == "listings")
2902                         code = LISTINGS_CODE;
2903                 else if (cmd.argument() == "mathspace")
2904                         code = MATH_HULL_CODE;
2905                 else if (cmd.argument() == "nomenclature")
2906                         code = NOMENCL_CODE;
2907                 else if (cmd.argument() == "nomencl_print")
2908                         code = NOMENCL_PRINT_CODE;
2909                 else if (cmd.argument() == "label")
2910                         code = LABEL_CODE;
2911                 else if (cmd.argument() == "line")
2912                         code = LINE_CODE;
2913                 else if (cmd.argument() == "note")
2914                         code = NOTE_CODE;
2915                 else if (cmd.argument() == "phantom")
2916                         code = PHANTOM_CODE;
2917                 else if (cmd.argument() == "ref")
2918                         code = REF_CODE;
2919                 else if (cmd.argument() == "space")
2920                         code = SPACE_CODE;
2921                 else if (cmd.argument() == "toc")
2922                         code = TOC_CODE;
2923                 else if (cmd.argument() == "vspace")
2924                         code = VSPACE_CODE;
2925                 else if (cmd.argument() == "wrap")
2926                         code = WRAP_CODE;
2927                 break;
2928
2929         case LFUN_ERT_INSERT:
2930                 code = ERT_CODE;
2931                 break;
2932         case LFUN_LISTING_INSERT:
2933                 code = LISTINGS_CODE;
2934                 // not allowed in description items
2935                 enable = !inDescriptionItem(cur);
2936                 break;
2937         case LFUN_FOOTNOTE_INSERT:
2938                 code = FOOT_CODE;
2939                 break;
2940         case LFUN_TABULAR_INSERT:
2941                 code = TABULAR_CODE;
2942                 break;
2943         case LFUN_TABULAR_STYLE_INSERT:
2944                 code = TABULAR_CODE;
2945                 break;
2946         case LFUN_MARGINALNOTE_INSERT:
2947                 code = MARGIN_CODE;
2948                 break;
2949         case LFUN_FLOAT_INSERT:
2950         case LFUN_FLOAT_WIDE_INSERT:
2951                 // FIXME: If there is a selection, we should check whether there
2952                 // are floats in the selection, but this has performance issues, see
2953                 // LFUN_CHANGE_ACCEPT/REJECT.
2954                 code = FLOAT_CODE;
2955                 if (inDescriptionItem(cur))
2956                         // not allowed in description items
2957                         enable = false;
2958                 else {
2959                         InsetCode const inset_code = cur.inset().lyxCode();
2960
2961                         // algorithm floats cannot be put in another float
2962                         if (to_utf8(cmd.argument()) == "algorithm") {
2963                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2964                                 break;
2965                         }
2966
2967                         // for figures and tables: only allow in another
2968                         // float or wrap if it is of the same type and
2969                         // not a subfloat already
2970                         if(cur.inset().lyxCode() == code) {
2971                                 InsetFloat const & ins =
2972                                         static_cast<InsetFloat const &>(cur.inset());
2973                                 enable = ins.params().type == to_utf8(cmd.argument())
2974                                         && !ins.params().subfloat;
2975                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2976                                 InsetWrap const & ins =
2977                                         static_cast<InsetWrap const &>(cur.inset());
2978                                 enable = ins.params().type == to_utf8(cmd.argument());
2979                         }
2980                 }
2981                 break;
2982         case LFUN_WRAP_INSERT:
2983                 code = WRAP_CODE;
2984                 // not allowed in description items
2985                 enable = !inDescriptionItem(cur);
2986                 break;
2987         case LFUN_FLOAT_LIST_INSERT: {
2988                 code = FLOAT_LIST_CODE;
2989                 // not allowed in description items
2990                 enable = !inDescriptionItem(cur);
2991                 if (enable) {
2992                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2993                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2994                         // make sure we know about such floats
2995                         if (cit == floats.end() ||
2996                                         // and that we know how to generate a list of them
2997                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2998                                 flag.setUnknown(true);
2999                                 // probably not necessary, but...
3000                                 enable = false;
3001                         }
3002                 }
3003                 break;
3004         }
3005         case LFUN_CAPTION_INSERT: {
3006                 code = CAPTION_CODE;
3007                 string arg = cmd.getArg(0);
3008                 bool varia = arg != "Unnumbered"
3009                         && cur.inset().allowsCaptionVariation(arg);
3010                 // not allowed in description items,
3011                 // and in specific insets
3012                 enable = !inDescriptionItem(cur)
3013                         && (varia || arg.empty() || arg == "Standard");
3014                 break;
3015         }
3016         case LFUN_NOTE_INSERT:
3017                 code = NOTE_CODE;
3018                 break;
3019         case LFUN_FLEX_INSERT: {
3020                 code = FLEX_CODE;
3021                 string s = cmd.getArg(0);
3022                 InsetLayout il =
3023                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
3024                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
3025                     il.lyxtype() != InsetLayout::CUSTOM &&
3026                     il.lyxtype() != InsetLayout::ELEMENT &&
3027                     il.lyxtype ()!= InsetLayout::STANDARD)
3028                         enable = false;
3029                 break;
3030                 }
3031         case LFUN_BOX_INSERT:
3032                 code = BOX_CODE;
3033                 break;
3034         case LFUN_BRANCH_INSERT:
3035                 code = BRANCH_CODE;
3036                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
3037                     && cur.buffer()->params().branchlist().empty())
3038                         enable = false;
3039                 break;
3040         case LFUN_IPA_INSERT:
3041                 code = IPA_CODE;
3042                 break;
3043         case LFUN_PHANTOM_INSERT:
3044                 code = PHANTOM_CODE;
3045                 break;
3046         case LFUN_LABEL_INSERT:
3047                 code = LABEL_CODE;
3048                 break;
3049         case LFUN_INFO_INSERT:
3050                 code = INFO_CODE;
3051                 enable = cmd.argument().empty()
3052                         || infoparams.validateArgument(cur.buffer(), cmd.argument(), true);
3053                 break;
3054         case LFUN_ARGUMENT_INSERT: {
3055                 code = ARG_CODE;
3056                 allow_in_passthru = true;
3057                 string const arg = cmd.getArg(0);
3058                 if (arg.empty()) {
3059                         enable = false;
3060                         break;
3061                 }
3062                 Layout const & lay = cur.paragraph().layout();
3063                 Layout::LaTeXArgMap args = lay.args();
3064                 Layout::LaTeXArgMap::const_iterator const lait =
3065                                 args.find(arg);
3066                 if (lait != args.end()) {
3067                         enable = true;
3068                         pit_type pit = cur.pit();
3069                         pit_type lastpit = cur.pit();
3070                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
3071                                 // In a sequence of "merged" environment layouts, we only allow
3072                                 // non-item arguments once.
3073                                 lastpit = cur.lastpit();
3074                                 // get the first paragraph in sequence with this layout
3075                                 depth_type const current_depth = cur.paragraph().params().depth();
3076                                 while (true) {
3077                                         if (pit == 0)
3078                                                 break;
3079                                         Paragraph cpar = pars_[pit - 1];
3080                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
3081                                                 --pit;
3082                                         else
3083                                                 break;
3084                                 }
3085                         }
3086                         for (; pit <= lastpit; ++pit) {
3087                                 if (pars_[pit].layout() != lay)
3088                                         break;
3089                                 for (auto const & table : pars_[pit].insetList())
3090                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
3091                                                 if (ins->name() == arg) {
3092                                                         // we have this already
3093                                                         enable = false;
3094                                                         break;
3095                                                 }
3096                         }
3097                 } else
3098                         enable = false;
3099                 break;
3100         }
3101         case LFUN_INDEX_INSERT:
3102                 code = INDEX_CODE;
3103                 break;
3104         case LFUN_INDEX_PRINT:
3105                 code = INDEX_PRINT_CODE;
3106                 // not allowed in description items
3107                 enable = !inDescriptionItem(cur);
3108                 break;
3109         case LFUN_NOMENCL_INSERT:
3110                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3111                         enable = false;
3112                         break;
3113                 }
3114                 code = NOMENCL_CODE;
3115                 break;
3116         case LFUN_NOMENCL_PRINT:
3117                 code = NOMENCL_PRINT_CODE;
3118                 // not allowed in description items
3119                 enable = !inDescriptionItem(cur);
3120                 break;
3121         case LFUN_HREF_INSERT:
3122                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3123                         enable = false;
3124                         break;
3125                 }
3126                 code = HYPERLINK_CODE;
3127                 break;
3128         case LFUN_IPAMACRO_INSERT: {
3129                 string const arg = cmd.getArg(0);
3130                 if (arg == "deco")
3131                         code = IPADECO_CODE;
3132                 else
3133                         code = IPACHAR_CODE;
3134                 break;
3135         }
3136         case LFUN_QUOTE_INSERT:
3137                 // always allow this, since we will inset a raw quote
3138                 // if an inset is not allowed.
3139                 allow_in_passthru = true;
3140                 break;
3141         case LFUN_SPECIALCHAR_INSERT:
3142                 code = SPECIALCHAR_CODE;
3143                 break;
3144         case LFUN_SPACE_INSERT:
3145                 // slight hack: we know this is allowed in math mode
3146                 if (cur.inTexted())
3147                         code = SPACE_CODE;
3148                 break;
3149         case LFUN_PREVIEW_INSERT:
3150                 code = PREVIEW_CODE;
3151                 break;
3152         case LFUN_SCRIPT_INSERT:
3153                 code = SCRIPT_CODE;
3154                 break;
3155
3156         case LFUN_MATH_INSERT:
3157         case LFUN_MATH_AMS_MATRIX:
3158         case LFUN_MATH_MATRIX:
3159         case LFUN_MATH_DELIM:
3160         case LFUN_MATH_BIGDELIM:
3161         case LFUN_MATH_DISPLAY:
3162         case LFUN_MATH_MODE:
3163         case LFUN_MATH_MACRO:
3164         case LFUN_MATH_SUBSCRIPT:
3165         case LFUN_MATH_SUPERSCRIPT:
3166                 code = MATH_HULL_CODE;
3167                 break;
3168
3169         case LFUN_REGEXP_MODE:
3170                 code = MATH_HULL_CODE;
3171                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3172                 break;
3173
3174         case LFUN_INSET_MODIFY:
3175                 // We need to disable this, because we may get called for a
3176                 // tabular cell via
3177                 // InsetTabular::getStatus() -> InsetText::getStatus()
3178                 // and we don't handle LFUN_INSET_MODIFY.
3179                 enable = false;
3180                 break;
3181
3182         case LFUN_FONT_EMPH:
3183                 flag.setOnOff(fontinfo.emph() == FONT_ON);
3184                 enable = !cur.paragraph().isPassThru();
3185                 break;
3186
3187         case LFUN_FONT_ITAL:
3188                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3189                 enable = !cur.paragraph().isPassThru();
3190                 break;
3191
3192         case LFUN_FONT_NOUN:
3193                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3194                 enable = !cur.paragraph().isPassThru();
3195                 break;
3196
3197         case LFUN_FONT_BOLD:
3198         case LFUN_FONT_BOLDSYMBOL:
3199                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3200                 enable = !cur.paragraph().isPassThru();
3201                 break;
3202
3203         case LFUN_FONT_SANS:
3204                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3205                 enable = !cur.paragraph().isPassThru();
3206                 break;
3207
3208         case LFUN_FONT_ROMAN:
3209                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3210                 enable = !cur.paragraph().isPassThru();
3211                 break;
3212
3213         case LFUN_FONT_TYPEWRITER:
3214                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3215                 enable = !cur.paragraph().isPassThru();
3216                 break;
3217
3218         case LFUN_CUT:
3219         case LFUN_COPY:
3220                 enable = cur.selection();
3221                 break;
3222
3223         case LFUN_PASTE: {
3224                 if (cmd.argument().empty()) {
3225                         if (theClipboard().isInternal())
3226                                 enable = cap::numberOfSelections() > 0;
3227                         else
3228                                 enable = !theClipboard().empty();
3229                         break;
3230                 }
3231
3232                 // we have an argument
3233                 string const arg = to_utf8(cmd.argument());
3234                 if (isStrUnsignedInt(arg)) {
3235                         // it's a number and therefore means the internal stack
3236                         unsigned int n = convert<unsigned int>(arg);
3237                         enable = cap::numberOfSelections() > n;
3238                         break;
3239                 }
3240
3241                 // explicit text type?
3242                 if (arg == "html") {
3243                         // Do not enable for PlainTextType, since some tidying in the
3244                         // frontend is needed for HTML, which is too unsafe for plain text.
3245                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3246                         break;
3247                 } else if (arg == "latex") {
3248                         // LaTeX is usually not available on the clipboard with
3249                         // the correct MIME type, but in plain text.
3250                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3251                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3252                         break;
3253                 }
3254
3255                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3256                 if (arg == "pdf")
3257                         type = Clipboard::PdfGraphicsType;
3258                 else if (arg == "png")
3259                         type = Clipboard::PngGraphicsType;
3260                 else if (arg == "jpeg")
3261                         type = Clipboard::JpegGraphicsType;
3262                 else if (arg == "linkback")
3263                         type = Clipboard::LinkBackGraphicsType;
3264                 else if (arg == "emf")
3265                         type = Clipboard::EmfGraphicsType;
3266                 else if (arg == "wmf")
3267                         type = Clipboard::WmfGraphicsType;
3268                 else {
3269                         // unknown argument
3270                         LYXERR0("Unrecognized graphics type: " << arg);
3271                         // we don't want to assert if the user just mistyped the LFUN
3272                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3273                         enable = false;
3274                         break;
3275                 }
3276                 enable = theClipboard().hasGraphicsContents(type);
3277                 break;
3278         }
3279
3280         case LFUN_CLIPBOARD_PASTE:
3281         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3282                 enable = !theClipboard().empty();
3283                 break;
3284
3285         case LFUN_PRIMARY_SELECTION_PASTE:
3286                 enable = cur.selection() || !theSelection().empty();
3287                 break;
3288
3289         case LFUN_SELECTION_PASTE:
3290                 enable = cap::selection();
3291                 break;
3292
3293         case LFUN_PARAGRAPH_MOVE_UP:
3294                 enable = cur.pit() > 0 && !cur.selection();
3295                 break;
3296
3297         case LFUN_PARAGRAPH_MOVE_DOWN:
3298                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3299                 break;
3300
3301         case LFUN_CHANGE_ACCEPT:
3302         case LFUN_CHANGE_REJECT:
3303                 if (!cur.selection())
3304                         enable = cur.paragraph().isChanged(cur.pos());
3305                 else {
3306                         // will enable if there is a change in the selection
3307                         enable = false;
3308
3309                         // cheap improvement for efficiency: using cached
3310                         // buffer variable, if there is no change in the
3311                         // document, no need to check further.
3312                         if (!cur.buffer()->areChangesPresent())
3313                                 break;
3314
3315                         for (DocIterator it = cur.selectionBegin(); ; it.forwardPar()) {
3316                                 pos_type const beg = it.pos();
3317                                 pos_type end;
3318                                 bool const in_last_par = (it.pit() == cur.selectionEnd().pit() &&
3319                                                           it.idx() == cur.selectionEnd().idx());
3320                                 if (in_last_par)
3321                                         end = cur.selectionEnd().pos();
3322                                 else
3323                                         end = it.lastpos();
3324                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3325                                         enable = true;
3326                                         break;
3327                                 }
3328                                 if (in_last_par)
3329                                         break;
3330                         }
3331                 }
3332                 break;
3333
3334         case LFUN_OUTLINE_UP:
3335         case LFUN_OUTLINE_DOWN:
3336         case LFUN_OUTLINE_IN:
3337         case LFUN_OUTLINE_OUT:
3338                 // FIXME: LyX is not ready for outlining within inset.
3339                 enable = isMainText()
3340                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3341                 break;
3342
3343         case LFUN_NEWLINE_INSERT:
3344                 // LaTeX restrictions (labels or empty par)
3345                 enable = !cur.paragraph().isPassThru()
3346                         && cur.pos() > cur.paragraph().beginOfBody();
3347                 break;
3348
3349         case LFUN_SEPARATOR_INSERT:
3350                 // Always enabled for now
3351                 enable = true;
3352                 break;
3353
3354         case LFUN_TAB_INSERT:
3355         case LFUN_TAB_DELETE:
3356                 enable = cur.paragraph().isPassThru();
3357                 break;
3358
3359         case LFUN_GRAPHICS_SET_GROUP: {
3360                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3361                 if (!ins)
3362                         enable = false;
3363                 else
3364                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3365                 break;
3366         }
3367
3368         case LFUN_NEWPAGE_INSERT:
3369                 // not allowed in description items
3370                 code = NEWPAGE_CODE;
3371                 enable = !inDescriptionItem(cur);
3372                 break;
3373
3374         case LFUN_LANGUAGE:
3375                 enable = !cur.paragraph().isPassThru();
3376                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3377                 break;
3378
3379         case LFUN_PARAGRAPH_BREAK:
3380                 enable = inset().allowMultiPar();
3381                 break;
3382
3383         case LFUN_SPELLING_ADD:
3384         case LFUN_SPELLING_IGNORE:
3385         case LFUN_SPELLING_REMOVE:
3386                 enable = theSpellChecker() != NULL;
3387                 if (enable && !cmd.getArg(1).empty()) {
3388                         // validate explicitly given language
3389                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3390                         enable &= lang != NULL;
3391                 }
3392                 break;
3393
3394         case LFUN_LAYOUT:
3395         case LFUN_LAYOUT_TOGGLE: {
3396                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3397                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3398                 docstring const layout = resolveLayout(req_layout, cur);
3399
3400                 enable = !owner_->forcePlainLayout() && !layout.empty();
3401                 flag.setOnOff(isAlreadyLayout(layout, cur));
3402                 break;
3403         }
3404
3405         case LFUN_ENVIRONMENT_SPLIT: {
3406                 if (cmd.argument() == "outer") {
3407                         // check if we have an environment in our nesting hierarchy
3408                         bool res = false;
3409                         depth_type const current_depth = cur.paragraph().params().depth();
3410                         pit_type pit = cur.pit();
3411                         Paragraph cpar = pars_[pit];
3412                         while (true) {
3413                                 if (pit == 0 || cpar.params().depth() == 0)
3414                                         break;
3415                                 --pit;
3416                                 cpar = pars_[pit];
3417                                 if (cpar.params().depth() < current_depth)
3418                                         res = cpar.layout().isEnvironment();
3419                         }
3420                         enable = res;
3421                         break;
3422                 }
3423                 else if (cmd.argument() == "previous") {
3424                         // look if we have an environment in the previous par
3425                         pit_type pit = cur.pit();
3426                         Paragraph cpar = pars_[pit];
3427                         if (pit > 0) {
3428                                 --pit;
3429                                 cpar = pars_[pit];
3430                                 enable = cpar.layout().isEnvironment();
3431                                 break;
3432                         }
3433                         enable = false;
3434                         break;
3435                 }
3436                 else if (cur.paragraph().layout().isEnvironment()) {
3437                         enable = cmd.argument() == "before"
3438                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3439                         break;
3440                 }
3441                 enable = false;
3442                 break;
3443         }
3444
3445         case LFUN_LAYOUT_PARAGRAPH:
3446         case LFUN_PARAGRAPH_PARAMS:
3447         case LFUN_PARAGRAPH_PARAMS_APPLY:
3448         case LFUN_PARAGRAPH_UPDATE:
3449                 enable = owner_->allowParagraphCustomization();
3450                 break;
3451
3452         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3453         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3454         //  that cannot be handled by LaTeX but must be converted according
3455         //  to the definition in lib/unicodesymbols?
3456         case LFUN_ACCENT_ACUTE:
3457         case LFUN_ACCENT_BREVE:
3458         case LFUN_ACCENT_CARON:
3459         case LFUN_ACCENT_CEDILLA:
3460         case LFUN_ACCENT_CIRCLE:
3461         case LFUN_ACCENT_CIRCUMFLEX:
3462         case LFUN_ACCENT_DOT:
3463         case LFUN_ACCENT_GRAVE:
3464         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3465         case LFUN_ACCENT_MACRON:
3466         case LFUN_ACCENT_OGONEK:
3467         case LFUN_ACCENT_TIE:
3468         case LFUN_ACCENT_TILDE:
3469         case LFUN_ACCENT_PERISPOMENI:
3470         case LFUN_ACCENT_UMLAUT:
3471         case LFUN_ACCENT_UNDERBAR:
3472         case LFUN_ACCENT_UNDERDOT:
3473         case LFUN_FONT_FRAK:
3474         case LFUN_FONT_SIZE:
3475         case LFUN_FONT_STATE:
3476         case LFUN_FONT_UNDERLINE:
3477         case LFUN_FONT_STRIKEOUT:
3478         case LFUN_FONT_CROSSOUT:
3479         case LFUN_FONT_UNDERUNDERLINE:
3480         case LFUN_FONT_UNDERWAVE:
3481         case LFUN_TEXTSTYLE_UPDATE:
3482                 enable = !cur.paragraph().isPassThru();
3483                 break;
3484
3485         case LFUN_FONT_DEFAULT: {
3486                 Font font(inherit_font, ignore_language);
3487                 BufferParams const & bp = cur.buffer()->masterParams();
3488                 if (cur.selection()) {
3489                         enable = false;
3490                         // Check if we have a non-default font attribute
3491                         // in the selection range.
3492                         DocIterator const from = cur.selectionBegin();
3493                         DocIterator const to = cur.selectionEnd();
3494                         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
3495                                 if (!dit.inTexted()) {
3496                                         dit.forwardPos();
3497                                         continue;
3498                                 }
3499                                 Paragraph const & par = dit.paragraph();
3500                                 pos_type const pos = dit.pos();
3501                                 Font tmp = par.getFontSettings(bp, pos);
3502                                 if (tmp.fontInfo() != font.fontInfo()
3503                                     || tmp.language() != bp.language) {
3504                                         enable = true;
3505                                         break;
3506                                 }
3507                                 dit.forwardPos();
3508                         }
3509                         break;
3510                 }
3511                 // Disable if all is default already.
3512                 enable = (cur.current_font.fontInfo() != font.fontInfo()
3513                           || cur.current_font.language() != bp.language);
3514                 break;
3515         }
3516
3517         case LFUN_TEXTSTYLE_APPLY:
3518                 enable = !freeFonts.empty();
3519                 break;
3520
3521         case LFUN_WORD_DELETE_FORWARD:
3522         case LFUN_WORD_DELETE_BACKWARD:
3523         case LFUN_LINE_DELETE_FORWARD:
3524         case LFUN_WORD_FORWARD:
3525         case LFUN_WORD_BACKWARD:
3526         case LFUN_WORD_RIGHT:
3527         case LFUN_WORD_LEFT:
3528         case LFUN_CHAR_FORWARD:
3529         case LFUN_CHAR_FORWARD_SELECT:
3530         case LFUN_CHAR_BACKWARD:
3531         case LFUN_CHAR_BACKWARD_SELECT:
3532         case LFUN_CHAR_LEFT:
3533         case LFUN_CHAR_LEFT_SELECT:
3534         case LFUN_CHAR_RIGHT:
3535         case LFUN_CHAR_RIGHT_SELECT:
3536         case LFUN_UP:
3537         case LFUN_UP_SELECT:
3538         case LFUN_DOWN:
3539         case LFUN_DOWN_SELECT:
3540         case LFUN_PARAGRAPH_UP_SELECT:
3541         case LFUN_PARAGRAPH_DOWN_SELECT:
3542         case LFUN_LINE_BEGIN_SELECT:
3543         case LFUN_LINE_END_SELECT:
3544         case LFUN_WORD_FORWARD_SELECT:
3545         case LFUN_WORD_BACKWARD_SELECT:
3546         case LFUN_WORD_RIGHT_SELECT:
3547         case LFUN_WORD_LEFT_SELECT:
3548         case LFUN_WORD_SELECT:
3549         case LFUN_SECTION_SELECT:
3550         case LFUN_BUFFER_BEGIN:
3551         case LFUN_BUFFER_END:
3552         case LFUN_BUFFER_BEGIN_SELECT:
3553         case LFUN_BUFFER_END_SELECT:
3554         case LFUN_INSET_BEGIN:
3555         case LFUN_INSET_END:
3556         case LFUN_INSET_BEGIN_SELECT:
3557         case LFUN_INSET_END_SELECT:
3558         case LFUN_PARAGRAPH_UP:
3559         case LFUN_PARAGRAPH_DOWN:
3560         case LFUN_LINE_BEGIN:
3561         case LFUN_LINE_END:
3562         case LFUN_CHAR_DELETE_FORWARD:
3563         case LFUN_CHAR_DELETE_BACKWARD:
3564         case LFUN_WORD_UPCASE:
3565         case LFUN_WORD_LOWCASE:
3566         case LFUN_WORD_CAPITALIZE:
3567         case LFUN_CHARS_TRANSPOSE:
3568         case LFUN_SERVER_GET_XY:
3569         case LFUN_SERVER_SET_XY:
3570         case LFUN_SERVER_GET_LAYOUT:
3571         case LFUN_SELF_INSERT:
3572         case LFUN_UNICODE_INSERT:
3573         case LFUN_THESAURUS_ENTRY:
3574         case LFUN_ESCAPE:
3575         case LFUN_SERVER_GET_STATISTICS:
3576                 // these are handled in our dispatch()
3577                 enable = true;
3578                 break;
3579
3580         case LFUN_INSET_INSERT: {
3581                 string const type = cmd.getArg(0);
3582                 if (type == "toc") {
3583                         code = TOC_CODE;
3584                         // not allowed in description items
3585                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3586                         enable = !inDescriptionItem(cur);
3587                 } else {
3588                         enable = true;
3589                 }
3590                 break;
3591         }
3592
3593         case LFUN_SEARCH_IGNORE: {
3594                 bool const value = cmd.getArg(1) == "true";
3595                 setIgnoreFormat(cmd.getArg(0), value);
3596                 break;
3597         }
3598
3599         default:
3600                 return false;
3601         }
3602
3603         if (code != NO_CODE
3604             && (cur.empty()
3605                 || !cur.inset().insetAllowed(code)
3606                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3607                 enable = false;
3608
3609         flag.setEnabled(enable);
3610         return true;
3611 }
3612
3613
3614 void Text::pasteString(Cursor & cur, docstring const & clip,
3615                 bool asParagraphs)
3616 {
3617         if (!clip.empty()) {
3618                 cur.recordUndo();
3619                 if (asParagraphs)
3620                         insertStringAsParagraphs(cur, clip, cur.current_font);
3621                 else
3622                         insertStringAsLines(cur, clip, cur.current_font);
3623         }
3624 }
3625
3626
3627 // FIXME: an item inset would make things much easier.
3628 bool Text::inDescriptionItem(Cursor & cur) const
3629 {
3630         Paragraph & par = cur.paragraph();
3631         pos_type const pos = cur.pos();
3632         pos_type const body_pos = par.beginOfBody();
3633
3634         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3635             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3636                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3637                 return false;
3638
3639         return (pos < body_pos
3640                 || (pos == body_pos
3641                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3642 }
3643
3644
3645 std::vector<docstring> Text::getFreeFonts() const
3646 {
3647         vector<docstring> ffList;
3648
3649         FontStack::const_iterator cit = freeFonts.begin();
3650         FontStack::const_iterator end = freeFonts.end();
3651         for (; cit != end; ++cit)
3652                 // we do not use cit-> here because gcc 2.9x does not
3653                 // like it (JMarc)
3654                 ffList.push_back((*cit).first);
3655
3656         return ffList;
3657 }
3658
3659 } // namespace lyx