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