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