]> git.lyx.org Git - features.git/blob - src/Text3.cpp
LFUN_TEXTSTYLE_UPDATE: Do not force any unspecified settings.
[features.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().isCommand()
1259                     && pars_[prev].layout() != par.layout()
1260                     && pars_[prev].layout().isEnvironment()
1261                     && !nextpar.isEnvSeparator(nextpar.beginOfBody())) {
1262                         if (par.layout().isEnvironment()
1263                             && pars_[prev].getDepth() == par.getDepth()) {
1264                                 docstring const layout = par.layout().name();
1265                                 DocumentClass const & tc = bv->buffer().params().documentClass();
1266                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, tc.plainLayout().name()));
1267                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1268                                 lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1269                                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1270                         } else {
1271                                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1272                                 breakParagraph(cur);
1273                         }
1274                         Font const f(inherit_font, cur.current_font.language());
1275                         pars_[cur.pit() - 1].resetFonts(f);
1276                 } else {
1277                         if (par.isEnvSeparator(cur.pos()) && cmd.getArg(1) != "ignoresep")
1278                                 cur.posForward();
1279                         breakParagraph(cur, cmd.getArg(0) == "inverse");
1280                 }
1281                 cur.resetAnchor();
1282                 // If we have a list and autoinsert item insets,
1283                 // insert them now.
1284                 Layout::LaTeXArgMap args = par.layout().args();
1285                 for (auto const & thearg : args) {
1286                         Layout::latexarg arg = thearg.second;
1287                         if (arg.autoinsert && prefixIs(thearg.first, "item:")) {
1288                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, thearg.first);
1289                                 lyx::dispatch(cmd2);
1290                         }
1291                 }
1292                 break;
1293         }
1294
1295         case LFUN_INSET_INSERT: {
1296                 cur.recordUndo();
1297
1298                 // We have to avoid triggering InstantPreview loading
1299                 // before inserting into the document. See bug #5626.
1300                 bool loaded = bv->buffer().isFullyLoaded();
1301                 bv->buffer().setFullyLoaded(false);
1302                 Inset * inset = createInset(&bv->buffer(), cmd);
1303                 bv->buffer().setFullyLoaded(loaded);
1304
1305                 if (inset) {
1306                         // FIXME (Abdel 01/02/2006):
1307                         // What follows would be a partial fix for bug 2154:
1308                         //   http://www.lyx.org/trac/ticket/2154
1309                         // This automatically put the label inset _after_ a
1310                         // numbered section. It should be possible to extend the mechanism
1311                         // to any kind of LateX environement.
1312                         // The correct way to fix that bug would be at LateX generation.
1313                         // I'll let the code here for reference as it could be used for some
1314                         // other feature like "automatic labelling".
1315                         /*
1316                         Paragraph & par = pars_[cur.pit()];
1317                         if (inset->lyxCode() == LABEL_CODE
1318                                 && !par.layout().counter.empty()) {
1319                                 // Go to the end of the paragraph
1320                                 // Warning: Because of Change-Tracking, the last
1321                                 // position is 'size()' and not 'size()-1':
1322                                 cur.pos() = par.size();
1323                                 // Insert a new paragraph
1324                                 FuncRequest fr(LFUN_PARAGRAPH_BREAK);
1325                                 dispatch(cur, fr);
1326                         }
1327                         */
1328                         if (cur.selection())
1329                                 cutSelection(cur, false);
1330                         cur.insert(inset);
1331                         cur.forceBufferUpdate();
1332                         if (inset->editable() && inset->asInsetText())
1333                                 inset->edit(cur, true);
1334                         else
1335                                 cur.posForward();
1336
1337                         // trigger InstantPreview now
1338                         if (inset->lyxCode() == EXTERNAL_CODE) {
1339                                 InsetExternal & ins =
1340                                         static_cast<InsetExternal &>(*inset);
1341                                 ins.updatePreview();
1342                         }
1343                 }
1344
1345                 break;
1346         }
1347
1348         case LFUN_INSET_DISSOLVE: {
1349                 if (dissolveInset(cur)) {
1350                         needsUpdate = true;
1351                         cur.forceBufferUpdate();
1352                 }
1353                 break;
1354         }
1355
1356         case LFUN_GRAPHICS_SET_GROUP: {
1357                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1358                 if (!ins)
1359                         break;
1360
1361                 cur.recordUndo();
1362
1363                 string id = to_utf8(cmd.argument());
1364                 string grp = graphics::getGroupParams(bv->buffer(), id);
1365                 InsetGraphicsParams tmp, inspar = ins->getParams();
1366
1367                 if (id.empty())
1368                         inspar.groupId = to_utf8(cmd.argument());
1369                 else {
1370                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1371                         tmp.filename = inspar.filename;
1372                         inspar = tmp;
1373                 }
1374
1375                 ins->setParams(inspar);
1376                 break;
1377         }
1378
1379         case LFUN_SPACE_INSERT:
1380                 if (cur.paragraph().layout().free_spacing)
1381                         insertChar(cur, ' ');
1382                 else {
1383                         doInsertInset(cur, this, cmd, false, false);
1384                         cur.posForward();
1385                 }
1386                 moveCursor(cur, false);
1387                 break;
1388
1389         case LFUN_SPECIALCHAR_INSERT: {
1390                 string const name = to_utf8(cmd.argument());
1391                 if (name == "hyphenation")
1392                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1393                 else if (name == "allowbreak")
1394                         specialChar(cur, InsetSpecialChar::ALLOWBREAK);
1395                 else if (name == "ligature-break")
1396                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1397                 else if (name == "slash")
1398                         specialChar(cur, InsetSpecialChar::SLASH);
1399                 else if (name == "nobreakdash")
1400                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1401                 else if (name == "dots")
1402                         specialChar(cur, InsetSpecialChar::LDOTS);
1403                 else if (name == "end-of-sentence")
1404                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1405                 else if (name == "menu-separator")
1406                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1407                 else if (name == "lyx")
1408                         specialChar(cur, InsetSpecialChar::PHRASE_LYX);
1409                 else if (name == "tex")
1410                         specialChar(cur, InsetSpecialChar::PHRASE_TEX);
1411                 else if (name == "latex")
1412                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX);
1413                 else if (name == "latex2e")
1414                         specialChar(cur, InsetSpecialChar::PHRASE_LATEX2E);
1415                 else if (name.empty())
1416                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1417                 else
1418                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1419                 break;
1420         }
1421
1422         case LFUN_IPAMACRO_INSERT: {
1423                 string const arg = cmd.getArg(0);
1424                 if (arg == "deco") {
1425                         // Open the inset, and move the current selection
1426                         // inside it.
1427                         doInsertInset(cur, this, cmd, true, true);
1428                         cur.posForward();
1429                         // Some insets are numbered, others are shown in the outline pane so
1430                         // let's update the labels and the toc backend.
1431                         cur.forceBufferUpdate();
1432                         break;
1433                 }
1434                 if (arg == "tone-falling")
1435                         ipaChar(cur, InsetIPAChar::TONE_FALLING);
1436                 else if (arg == "tone-rising")
1437                         ipaChar(cur, InsetIPAChar::TONE_RISING);
1438                 else if (arg == "tone-high-rising")
1439                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING);
1440                 else if (arg == "tone-low-rising")
1441                         ipaChar(cur, InsetIPAChar::TONE_LOW_RISING);
1442                 else if (arg == "tone-high-rising-falling")
1443                         ipaChar(cur, InsetIPAChar::TONE_HIGH_RISING_FALLING);
1444                 else if (arg.empty())
1445                         lyxerr << "LyX function 'ipamacro-insert' needs an argument." << endl;
1446                 else
1447                         lyxerr << "Wrong argument for LyX function 'ipamacro-insert'." << endl;
1448                 break;
1449         }
1450
1451         case LFUN_WORD_UPCASE:
1452                 changeCase(cur, text_uppercase, cmd.getArg(0) == "partial");
1453                 break;
1454
1455         case LFUN_WORD_LOWCASE:
1456                 changeCase(cur, text_lowercase, cmd.getArg(0) == "partial");
1457                 break;
1458
1459         case LFUN_WORD_CAPITALIZE:
1460                 changeCase(cur, text_capitalization, cmd.getArg(0) == "partial");
1461                 break;
1462
1463         case LFUN_CHARS_TRANSPOSE:
1464                 charsTranspose(cur);
1465                 break;
1466
1467         case LFUN_PASTE: {
1468                 cur.message(_("Paste"));
1469                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), break);
1470                 cap::replaceSelection(cur);
1471
1472                 // without argument?
1473                 string const arg = to_utf8(cmd.argument());
1474                 if (arg.empty()) {
1475                         bool tryGraphics = true;
1476                         if (theClipboard().isInternal())
1477                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1478                         else if (theClipboard().hasTextContents()) {
1479                                 if (pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1480                                                        true, Clipboard::AnyTextType))
1481                                         tryGraphics = false;
1482                         }
1483                         if (tryGraphics && theClipboard().hasGraphicsContents())
1484                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1485                 } else if (isStrUnsignedInt(arg)) {
1486                         // we have a numerical argument
1487                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1488                                        convert<unsigned int>(arg));
1489                 } else if (arg == "html" || arg == "latex") {
1490                         Clipboard::TextType type = (arg == "html") ?
1491                                 Clipboard::HtmlTextType : Clipboard::LaTeXTextType;
1492                         pasteClipboardText(cur, bv->buffer().errorList("Paste"), true, type);
1493                 } else {
1494                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1495                         if (arg == "pdf")
1496                                 type = Clipboard::PdfGraphicsType;
1497                         else if (arg == "png")
1498                                 type = Clipboard::PngGraphicsType;
1499                         else if (arg == "jpeg")
1500                                 type = Clipboard::JpegGraphicsType;
1501                         else if (arg == "linkback")
1502                                 type = Clipboard::LinkBackGraphicsType;
1503                         else if (arg == "emf")
1504                                 type = Clipboard::EmfGraphicsType;
1505                         else if (arg == "wmf")
1506                                 type = Clipboard::WmfGraphicsType;
1507                         else
1508                                 // we also check in getStatus()
1509                                 LYXERR0("Unrecognized graphics type: " << arg);
1510
1511                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1512                 }
1513
1514                 bv->buffer().errors("Paste");
1515                 cur.clearSelection(); // bug 393
1516                 cur.finishUndo();
1517                 break;
1518         }
1519
1520         case LFUN_CUT:
1521                 cutSelection(cur, true);
1522                 cur.message(_("Cut"));
1523                 break;
1524
1525         case LFUN_COPY:
1526                 copySelection(cur);
1527                 cur.message(_("Copy"));
1528                 break;
1529
1530         case LFUN_SERVER_GET_XY:
1531                 cur.message(from_utf8(
1532                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1533                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1534                 break;
1535
1536         case LFUN_SERVER_SET_XY: {
1537                 int x = 0;
1538                 int y = 0;
1539                 istringstream is(to_utf8(cmd.argument()));
1540                 is >> x >> y;
1541                 if (!is)
1542                         lyxerr << "SETXY: Could not parse coordinates in '"
1543                                << to_utf8(cmd.argument()) << endl;
1544                 else
1545                         tm->setCursorFromCoordinates(cur, x, y);
1546                 break;
1547         }
1548
1549         case LFUN_SERVER_GET_LAYOUT:
1550                 cur.message(cur.paragraph().layout().name());
1551                 break;
1552
1553         case LFUN_LAYOUT:
1554         case LFUN_LAYOUT_TOGGLE: {
1555                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
1556                 docstring req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
1557                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(req_layout));
1558
1559                 docstring layout = resolveLayout(req_layout, cur);
1560                 if (layout.empty()) {
1561                         cur.errorMessage(from_utf8(N_("Layout ")) + req_layout +
1562                                 from_utf8(N_(" not known")));
1563                         break;
1564                 }
1565
1566                 docstring const old_layout = cur.paragraph().layout().name();
1567                 bool change_layout = !isAlreadyLayout(layout, cur);
1568
1569                 if (cmd.action() == LFUN_LAYOUT_TOGGLE && !change_layout) {
1570                         change_layout = true;
1571                         layout = resolveLayout(docstring(), cur);
1572                 }
1573
1574                 if (change_layout) {
1575                         setLayout(cur, layout);
1576                         if (cur.pit() > 0 && !ignoreautonests) {
1577                                 set<docstring> const & autonests =
1578                                                 pars_[cur.pit() - 1].layout().autonests();
1579                                 set<docstring> const & autonested =
1580                                                 pars_[cur.pit()].layout().isAutonestedBy();
1581                                 if (autonests.find(layout) != autonests.end()
1582                                                 || autonested.find(old_layout) != autonested.end())
1583                                         lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1584                         }
1585                 }
1586
1587                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1588                 for (auto const & la_pair : tclass[layout].args()) {
1589                         Layout::latexarg const & arg = la_pair.second;
1590                         if (arg.autoinsert) {
1591                                 FuncRequest const cmd2(LFUN_ARGUMENT_INSERT, la_pair.first);
1592                                 lyx::dispatch(cmd2);
1593                         }
1594                 }
1595
1596                 break;
1597         }
1598
1599         case LFUN_ENVIRONMENT_SPLIT: {
1600                 bool const outer = cmd.argument() == "outer";
1601                 bool const previous = cmd.argument() == "previous";
1602                 bool const before = cmd.argument() == "before";
1603                 bool const normal = cmd.argument().empty();
1604                 Paragraph const & para = cur.paragraph();
1605                 docstring layout;
1606                 if (para.layout().isEnvironment())
1607                         layout = para.layout().name();
1608                 depth_type split_depth = cur.paragraph().params().depth();
1609                 depth_type nextpar_depth = 0;
1610                 if (outer || previous) {
1611                         // check if we have an environment in our scope
1612                         pit_type pit = cur.pit();
1613                         Paragraph cpar = pars_[pit];
1614                         while (true) {
1615                                 if (pit == 0)
1616                                         break;
1617                                 --pit;
1618                                 cpar = pars_[pit];
1619                                 if (layout.empty() && previous
1620                                     && cpar.layout().isEnvironment()
1621                                     && cpar.params().depth() <= split_depth)
1622                                         layout = cpar.layout().name();
1623                                 if (cpar.params().depth() < split_depth
1624                                     && cpar.layout().isEnvironment()) {
1625                                                 if (!previous)
1626                                                         layout = cpar.layout().name();
1627                                                 split_depth = cpar.params().depth();
1628                                 }
1629                                 if (cpar.params().depth() == 0)
1630                                         break;
1631                         }
1632                 }
1633                 if ((outer || normal) && cur.pit() < cur.lastpit()) {
1634                         // save nesting of following paragraph
1635                         Paragraph cpar = pars_[cur.pit() + 1];
1636                         nextpar_depth = cpar.params().depth();
1637                 }
1638                 if (before)
1639                         cur.top().setPitPos(cur.pit(), 0);
1640                 if (before || cur.pos() > 0)
1641                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK));
1642                 else if (previous && cur.nextInset() && cur.nextInset()->lyxCode() == SEPARATOR_CODE)
1643                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1644                 if (outer) {
1645                         while (cur.paragraph().params().depth() > split_depth)
1646                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_DECREMENT));
1647                 }
1648                 DocumentClass const & tc = bv->buffer().params().documentClass();
1649                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, from_ascii("\"") + tc.plainLayout().name()
1650                                           + from_ascii("\" ignoreautonests")));
1651                 // FIXME: Bibitem mess!
1652                 if (cur.prevInset() && cur.prevInset()->lyxCode() == BIBITEM_CODE)
1653                         lyx::dispatch(FuncRequest(LFUN_CHAR_DELETE_BACKWARD));
1654                 lyx::dispatch(FuncRequest(LFUN_SEPARATOR_INSERT, "plain"));
1655                 if (before) {
1656                         cur.backwardPos();
1657                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse ignoresep"));
1658                         while (cur.paragraph().params().depth() < split_depth)
1659                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1660                 }
1661                 else
1662                         lyx::dispatch(FuncRequest(LFUN_PARAGRAPH_BREAK, "inverse"));
1663                 lyx::dispatch(FuncRequest(LFUN_LAYOUT, layout));
1664                 if ((outer || normal) && nextpar_depth > 0) {
1665                         // restore nesting of following paragraph
1666                         DocIterator scur = cur;
1667                         depth_type const max_depth = cur.paragraph().params().depth() + 1;
1668                         cur.forwardPar();
1669                         while (cur.paragraph().params().depth() < min(nextpar_depth, max_depth)) {
1670                                 depth_type const olddepth = cur.paragraph().params().depth();
1671                                 lyx::dispatch(FuncRequest(LFUN_DEPTH_INCREMENT));
1672                                 if (olddepth == cur.paragraph().params().depth())
1673                                         // leave loop if no incrementation happens
1674                                         break;
1675                         }
1676                         cur.setCursor(scur);
1677                 }
1678
1679                 break;
1680         }
1681
1682         case LFUN_CLIPBOARD_PASTE:
1683                 cap::replaceSelection(cur);
1684                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1685                                cmd.argument() == "paragraph");
1686                 bv->buffer().errors("Paste");
1687                 break;
1688
1689         case LFUN_CLIPBOARD_PASTE_SIMPLE:
1690                 cap::replaceSelection(cur);
1691                 pasteSimpleText(cur, cmd.argument() == "paragraph");
1692                 break;
1693
1694         case LFUN_PRIMARY_SELECTION_PASTE:
1695                 cap::replaceSelection(cur);
1696                 pasteString(cur, theSelection().get(),
1697                             cmd.argument() == "paragraph");
1698                 break;
1699
1700         case LFUN_SELECTION_PASTE:
1701                 // Copy the selection buffer to the clipboard stack,
1702                 // because we want it to appear in the "Edit->Paste
1703                 // recent" menu.
1704                 cap::replaceSelection(cur);
1705                 cap::copySelectionToStack();
1706                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1707                 bv->buffer().errors("Paste");
1708                 break;
1709
1710         case LFUN_QUOTE_INSERT: {
1711                 cap::replaceSelection(cur);
1712                 cur.recordUndo();
1713
1714                 Paragraph const & par = cur.paragraph();
1715                 pos_type pos = cur.pos();
1716                 // Ignore deleted text before cursor
1717                 while (pos > 0 && par.isDeleted(pos - 1))
1718                         --pos;
1719
1720                 bool const inner = (cmd.getArg(0) == "single" || cmd.getArg(0) == "inner");
1721
1722                 // Guess quote side.
1723                 // A space triggers an opening quote. This is passed if the preceding
1724                 // char/inset is a space or at paragraph start.
1725                 char_type c = ' ';
1726                 if (pos > 0 && !par.isSpace(pos - 1)) {
1727                         if (cur.prevInset() && cur.prevInset()->lyxCode() == QUOTE_CODE) {
1728                                 // If an opening double quotation mark precedes, and this
1729                                 // is a single quote, make it opening as well
1730                                 InsetQuotes & ins =
1731                                         static_cast<InsetQuotes &>(*cur.prevInset());
1732                                 string const type = ins.getType();
1733                                 if (!suffixIs(type, "ld") || !inner)
1734                                         c = par.getChar(pos - 1);
1735                         }
1736                         else if (!cur.prevInset()
1737                             || (cur.prevInset() && cur.prevInset()->isChar()))
1738                                 // If a char precedes, pass that and let InsetQuote decide
1739                                 c = par.getChar(pos - 1);
1740                         else {
1741                                 while (pos > 0) {
1742                                         if (par.getInset(pos - 1)
1743                                             && !par.getInset(pos - 1)->isPartOfTextSequence()) {
1744                                                 // skip "invisible" insets
1745                                                 --pos;
1746                                                 continue;
1747                                         }
1748                                         c = par.getChar(pos - 1);
1749                                         break;
1750                                 }
1751                         }
1752                 }
1753                 InsetQuotesParams::QuoteLevel const quote_level = inner
1754                                 ? InsetQuotesParams::SecondaryQuotes : InsetQuotesParams::PrimaryQuotes;
1755                 cur.insert(new InsetQuotes(cur.buffer(), c, quote_level, cmd.getArg(1), cmd.getArg(2)));
1756                 cur.buffer()->updateBuffer();
1757                 cur.posForward();
1758                 break;
1759         }
1760
1761         case LFUN_MOUSE_TRIPLE:
1762                 if (cmd.button() == mouse_button::button1) {
1763                         tm->cursorHome(cur);
1764                         cur.resetAnchor();
1765                         tm->cursorEnd(cur);
1766                         cur.setSelection();
1767                         bv->cursor() = cur;
1768                 }
1769                 break;
1770
1771         case LFUN_MOUSE_DOUBLE:
1772                 if (cmd.button() == mouse_button::button1) {
1773                         selectWord(cur, WHOLE_WORD);
1774                         bv->cursor() = cur;
1775                 }
1776                 break;
1777
1778         // Single-click on work area
1779         case LFUN_MOUSE_PRESS: {
1780                 // We are not marking a selection with the keyboard in any case.
1781                 Cursor & bvcur = cur.bv().cursor();
1782                 bvcur.setMark(false);
1783                 switch (cmd.button()) {
1784                 case mouse_button::button1:
1785                         if (!bvcur.selection())
1786                                 // Set the cursor
1787                                 bvcur.resetAnchor();
1788                         if (!bv->mouseSetCursor(cur, cmd.modifier() == ShiftModifier))
1789                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1790                         if (bvcur.wordSelection())
1791                                 selectWord(bvcur, WHOLE_WORD);
1792                         break;
1793
1794                 case mouse_button::button2:
1795                         if (lyxrc.mouse_middlebutton_paste) {
1796                                 // Middle mouse pasting.
1797                                 bv->mouseSetCursor(cur);
1798                                 lyx::dispatch(
1799                                         FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1800                                                     "selection-paste ; primary-selection-paste paragraph"));
1801                         }
1802                         cur.noScreenUpdate();
1803                         break;
1804
1805                 case mouse_button::button3: {
1806                         // Don't do anything if we right-click a
1807                         // selection, a context menu will popup.
1808                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1809                             && cur < bvcur.selectionEnd()) {
1810                                 cur.noScreenUpdate();
1811                                 return;
1812                         }
1813                         if (!bv->mouseSetCursor(cur, false))
1814                                 cur.screenUpdateFlags(Update::FitCursor);
1815                         break;
1816                 }
1817
1818                 default:
1819                         break;
1820                 } // switch (cmd.button())
1821                 break;
1822         }
1823         case LFUN_MOUSE_MOTION: {
1824                 // Mouse motion with right or middle mouse do nothing for now.
1825                 if (cmd.button() != mouse_button::button1) {
1826                         cur.noScreenUpdate();
1827                         return;
1828                 }
1829                 // ignore motions deeper nested than the real anchor
1830                 Cursor & bvcur = cur.bv().cursor();
1831                 if (!bvcur.realAnchor().hasPart(cur)) {
1832                         cur.undispatched();
1833                         break;
1834                 }
1835                 CursorSlice old = bvcur.top();
1836
1837                 int const wh = bv->workHeight();
1838                 int const y = max(0, min(wh - 1, cmd.y()));
1839
1840                 tm->setCursorFromCoordinates(cur, cmd.x(), y);
1841                 cur.setTargetX(cmd.x());
1842                 // Don't allow selecting a separator inset
1843                 if (cur.pos() && cur.paragraph().isEnvSeparator(cur.pos() - 1))
1844                         cur.posBackward();
1845                 if (cmd.y() >= wh)
1846                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1847                 else if (cmd.y() < 0)
1848                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1849                 // This is to allow jumping over large insets
1850                 if (cur.top() == old) {
1851                         if (cmd.y() >= wh)
1852                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1853                         else if (cmd.y() < 0)
1854                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1855                 }
1856                 // We continue with our existing selection or start a new one, so don't
1857                 // reset the anchor.
1858                 bvcur.setCursor(cur);
1859                 bvcur.selection(true);
1860                 bvcur.setCurrentFont();
1861                 if (cur.top() == old) {
1862                         // We didn't move one iota, so no need to update the screen.
1863                         cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1864                         //cur.noScreenUpdate();
1865                         return;
1866                 }
1867                 break;
1868         }
1869
1870         case LFUN_MOUSE_RELEASE:
1871                 switch (cmd.button()) {
1872                 case mouse_button::button1:
1873                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1874                         // If there is a new selection, update persistent selection;
1875                         // otherwise, single click does not clear persistent selection
1876                         // buffer.
1877                         if (cur.selection()) {
1878                                 // Finish selection. If double click,
1879                                 // cur is moved to the end of word by
1880                                 // selectWord but bvcur is current
1881                                 // mouse position.
1882                                 cur.bv().cursor().setSelection();
1883                                 // We might have removed an empty but drawn selection
1884                                 // (probably a margin)
1885                                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
1886                         } else
1887                                 cur.noScreenUpdate();
1888                         // FIXME: We could try to handle drag and drop of selection here.
1889                         return;
1890
1891                 case mouse_button::button2:
1892                         // Middle mouse pasting is handled at mouse press time,
1893                         // see LFUN_MOUSE_PRESS.
1894                         cur.noScreenUpdate();
1895                         return;
1896
1897                 case mouse_button::button3:
1898                         // Cursor was set at LFUN_MOUSE_PRESS time.
1899                         // FIXME: If there is a selection we could try to handle a special
1900                         // drag & drop context menu.
1901                         cur.noScreenUpdate();
1902                         return;
1903
1904                 case mouse_button::none:
1905                 case mouse_button::button4:
1906                 case mouse_button::button5:
1907                         break;
1908                 } // switch (cmd.button())
1909
1910                 break;
1911
1912         case LFUN_SELF_INSERT: {
1913                 if (cmd.argument().empty())
1914                         break;
1915
1916                 // Automatically delete the currently selected
1917                 // text and replace it with what is being
1918                 // typed in now. Depends on lyxrc settings
1919                 // "auto_region_delete", which defaults to
1920                 // true (on).
1921
1922                 if (lyxrc.auto_region_delete && cur.selection())
1923                         cutSelection(cur, false);
1924                 cur.clearSelection();
1925
1926                 for (char_type c : cmd.argument())
1927                         bv->translateAndInsert(c, this, cur);
1928
1929                 cur.resetAnchor();
1930                 moveCursor(cur, false);
1931                 cur.markNewWordPosition();
1932                 bv->bookmarkEditPosition();
1933                 break;
1934         }
1935
1936         case LFUN_HREF_INSERT: {
1937                 docstring content = cmd.argument();
1938                 if (content.empty() && cur.selection())
1939                         content = cur.selectionAsString(false);
1940
1941                 InsetCommandParams p(HYPERLINK_CODE);
1942                 if (!content.empty()){
1943                         // if it looks like a link, we'll put it as target,
1944                         // otherwise as name (bug #8792).
1945
1946                         // We can't do:
1947                         //   regex_match(to_utf8(content), matches, link_re)
1948                         // because smatch stores pointers to the substrings rather
1949                         // than making copies of them. And those pointers become
1950                         // invalid after regex_match returns, since it is then
1951                         // being given a temporary object. (Thanks to Georg for
1952                         // figuring that out.)
1953                         regex const link_re("^([a-z]+):.*");
1954                         smatch matches;
1955                         string const c = to_utf8(lowercase(content));
1956
1957                         if (c.substr(0,7) == "mailto:") {
1958                                 p["target"] = content;
1959                                 p["type"] = from_ascii("mailto:");
1960                         } else if (regex_match(c, matches, link_re)) {
1961                                 p["target"] = content;
1962                                 string protocol = matches.str(1);
1963                                 if (protocol == "file")
1964                                         p["type"] = from_ascii("file:");
1965                         } else
1966                                 p["name"] = content;
1967                 }
1968                 string const data = InsetCommand::params2string(p);
1969
1970                 // we need to have a target. if we already have one, then
1971                 // that gets used at the default for the name, too, which
1972                 // is probably what is wanted.
1973                 if (p["target"].empty()) {
1974                         bv->showDialog("href", data);
1975                 } else {
1976                         FuncRequest fr(LFUN_INSET_INSERT, data);
1977                         dispatch(cur, fr);
1978                 }
1979                 break;
1980         }
1981
1982         case LFUN_LABEL_INSERT: {
1983                 InsetCommandParams p(LABEL_CODE);
1984                 // Try to generate a valid label
1985                 p["name"] = (cmd.argument().empty()) ?
1986                         cur.getPossibleLabel() :
1987                         cmd.argument();
1988                 string const data = InsetCommand::params2string(p);
1989
1990                 if (cmd.argument().empty()) {
1991                         bv->showDialog("label", data);
1992                 } else {
1993                         FuncRequest fr(LFUN_INSET_INSERT, data);
1994                         dispatch(cur, fr);
1995                 }
1996                 break;
1997         }
1998
1999         case LFUN_INFO_INSERT: {
2000                 if (cmd.argument().empty()) {
2001                         bv->showDialog("info", cur.current_font.language()->lang());
2002                 } else {
2003                         Inset * inset;
2004                         inset = createInset(cur.buffer(), cmd);
2005                         if (!inset)
2006                                 break;
2007                         cur.recordUndo();
2008                         insertInset(cur, inset);
2009                         cur.forceBufferUpdate();
2010                         cur.posForward();
2011                 }
2012                 break;
2013         }
2014         case LFUN_CAPTION_INSERT:
2015         case LFUN_FOOTNOTE_INSERT:
2016         case LFUN_NOTE_INSERT:
2017         case LFUN_BOX_INSERT:
2018         case LFUN_BRANCH_INSERT:
2019         case LFUN_PHANTOM_INSERT:
2020         case LFUN_ERT_INSERT:
2021         case LFUN_LISTING_INSERT:
2022         case LFUN_MARGINALNOTE_INSERT:
2023         case LFUN_ARGUMENT_INSERT:
2024         case LFUN_INDEX_INSERT:
2025         case LFUN_PREVIEW_INSERT:
2026         case LFUN_SCRIPT_INSERT:
2027         case LFUN_IPA_INSERT:
2028                 // Open the inset, and move the current selection
2029                 // inside it.
2030                 doInsertInset(cur, this, cmd, true, true);
2031                 cur.posForward();
2032                 // Some insets are numbered, others are shown in the outline pane so
2033                 // let's update the labels and the toc backend.
2034                 cur.forceBufferUpdate();
2035                 break;
2036
2037         case LFUN_FLEX_INSERT: {
2038                 // Open the inset, and move the current selection
2039                 // inside it.
2040                 bool const sel = cur.selection();
2041                 doInsertInset(cur, this, cmd, true, true);
2042                 // Insert auto-insert arguments
2043                 bool autoargs = false;
2044                 Layout::LaTeXArgMap args = cur.inset().getLayout().latexargs();
2045                 Layout::LaTeXArgMap::const_iterator lait = args.begin();
2046                 Layout::LaTeXArgMap::const_iterator const laend = args.end();
2047                 for (; lait != laend; ++lait) {
2048                         Layout::latexarg arg = (*lait).second;
2049                         if (arg.autoinsert) {
2050                                 // The cursor might have been invalidated by the replaceSelection.
2051                                 cur.buffer()->changed(true);
2052                                 FuncRequest cmd2(LFUN_ARGUMENT_INSERT, (*lait).first);
2053                                 lyx::dispatch(cmd2);
2054                                 autoargs = true;
2055                         }
2056                 }
2057                 if (!autoargs) {
2058                         if (sel)
2059                                 cur.leaveInset(cur.inset());
2060                         cur.posForward();
2061                 }
2062                 // Some insets are numbered, others are shown in the outline pane so
2063                 // let's update the labels and the toc backend.
2064                 cur.forceBufferUpdate();
2065                 break;
2066         }
2067
2068         case LFUN_TABULAR_INSERT:
2069                 // if there were no arguments, just open the dialog
2070                 if (doInsertInset(cur, this, cmd, false, true))
2071                         cur.posForward();
2072                 else
2073                         bv->showDialog("tabularcreate");
2074
2075                 break;
2076
2077         case LFUN_FLOAT_INSERT:
2078         case LFUN_FLOAT_WIDE_INSERT:
2079         case LFUN_WRAP_INSERT: {
2080                 // will some content be moved into the inset?
2081                 bool const content = cur.selection();
2082                 // does the content consist of multiple paragraphs?
2083                 bool const singlepar = (cur.selBegin().pit() == cur.selEnd().pit());
2084
2085                 doInsertInset(cur, this, cmd, true, true);
2086                 cur.posForward();
2087
2088                 // If some single-par content is moved into the inset,
2089                 // doInsertInset puts the cursor outside the inset.
2090                 // To insert the caption we put it back into the inset.
2091                 // FIXME cleanup doInsertInset to avoid such dances!
2092                 if (content && singlepar)
2093                         cur.backwardPos();
2094
2095                 ParagraphList & pars = cur.text()->paragraphs();
2096
2097                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2098
2099                 // add a separate paragraph for the caption inset
2100                 pars.push_back(Paragraph());
2101                 pars.back().setInsetOwner(&cur.text()->inset());
2102                 pars.back().setPlainOrDefaultLayout(tclass);
2103                 int cap_pit = pars.size() - 1;
2104
2105                 // if an empty inset was created, we create an additional empty
2106                 // paragraph at the bottom so that the user can choose where to put
2107                 // the graphics (or table).
2108                 if (!content) {
2109                         pars.push_back(Paragraph());
2110                         pars.back().setInsetOwner(&cur.text()->inset());
2111                         pars.back().setPlainOrDefaultLayout(tclass);
2112                 }
2113
2114                 // reposition the cursor to the caption
2115                 cur.pit() = cap_pit;
2116                 cur.pos() = 0;
2117                 // FIXME: This Text/Cursor dispatch handling is a mess!
2118                 // We cannot use Cursor::dispatch here it needs access to up to
2119                 // date metrics.
2120                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
2121                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
2122                 cur.forceBufferUpdate();
2123                 cur.screenUpdateFlags(Update::Force);
2124                 // FIXME: When leaving the Float (or Wrap) inset we should
2125                 // delete any empty paragraph left above or below the
2126                 // caption.
2127                 break;
2128         }
2129
2130         case LFUN_NOMENCL_INSERT: {
2131                 InsetCommandParams p(NOMENCL_CODE);
2132                 if (cmd.argument().empty()) {
2133                         p["symbol"] = 
2134                                 bv->cursor().innerText()->getStringForDialog(bv->cursor());
2135                         cur.clearSelection();
2136                 } else
2137                         p["symbol"] = cmd.argument();
2138                 string const data = InsetCommand::params2string(p);
2139                 bv->showDialog("nomenclature", data);
2140                 break;
2141         }
2142
2143         case LFUN_INDEX_PRINT: {
2144                 InsetCommandParams p(INDEX_PRINT_CODE);
2145                 if (cmd.argument().empty())
2146                         p["type"] = from_ascii("idx");
2147                 else
2148                         p["type"] = cmd.argument();
2149                 string const data = InsetCommand::params2string(p);
2150                 FuncRequest fr(LFUN_INSET_INSERT, data);
2151                 dispatch(cur, fr);
2152                 break;
2153         }
2154
2155         case LFUN_NOMENCL_PRINT:
2156         case LFUN_NEWPAGE_INSERT:
2157                 // do nothing fancy
2158                 doInsertInset(cur, this, cmd, false, false);
2159                 cur.posForward();
2160                 break;
2161
2162         case LFUN_SEPARATOR_INSERT: {
2163                 doInsertInset(cur, this, cmd, false, false);
2164                 cur.posForward();
2165                 // remove a following space
2166                 Paragraph & par = cur.paragraph();
2167                 if (cur.pos() != cur.lastpos() && par.isLineSeparator(cur.pos()))
2168                     par.eraseChar(cur.pos(), cur.buffer()->params().track_changes);
2169                 break;
2170         }
2171
2172         case LFUN_DEPTH_DECREMENT:
2173                 changeDepth(cur, DEC_DEPTH);
2174                 break;
2175
2176         case LFUN_DEPTH_INCREMENT:
2177                 changeDepth(cur, INC_DEPTH);
2178                 break;
2179
2180         case LFUN_REGEXP_MODE:
2181                 regexpDispatch(cur, cmd);
2182                 break;
2183
2184         case LFUN_MATH_MODE: {
2185                 if (cmd.argument() == "on" || cmd.argument() == "") {
2186                         // don't pass "on" as argument
2187                         // (it would appear literally in the first cell)
2188                         docstring sel = cur.selectionAsString(false);
2189                         InsetMathMacroTemplate * macro = new InsetMathMacroTemplate(cur.buffer());
2190                         // create a macro template if we see "\\newcommand" somewhere, and
2191                         // an ordinary formula otherwise
2192                         if (!sel.empty()
2193                                 && (sel.find(from_ascii("\\newcommand")) != string::npos
2194                                         || sel.find(from_ascii("\\newlyxcommand")) != string::npos
2195                                         || sel.find(from_ascii("\\def")) != string::npos)
2196                                 && macro->fromString(sel)) {
2197                                 cur.recordUndo();
2198                                 replaceSelection(cur);
2199                                 cur.insert(macro);
2200                         } else {
2201                                 // no meaningful macro template was found
2202                                 delete macro;
2203                                 mathDispatch(cur,FuncRequest(LFUN_MATH_MODE));
2204                         }
2205                 } else
2206                         // The argument is meaningful
2207                         // We replace cmd with LFUN_MATH_INSERT because LFUN_MATH_MODE
2208                         // has a different meaning in math mode
2209                         mathDispatch(cur, FuncRequest(LFUN_MATH_INSERT,cmd.argument()));
2210                 break;
2211         }
2212
2213         case LFUN_MATH_MACRO:
2214                 if (cmd.argument().empty())
2215                         cur.errorMessage(from_utf8(N_("Missing argument")));
2216                 else {
2217                         cur.recordUndo();
2218                         string s = to_utf8(cmd.argument());
2219                         string const s1 = token(s, ' ', 1);
2220                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
2221                         string const s2 = token(s, ' ', 2);
2222                         MacroType type = MacroTypeNewcommand;
2223                         if (s2 == "def")
2224                                 type = MacroTypeDef;
2225                         InsetMathMacroTemplate * inset = new InsetMathMacroTemplate(cur.buffer(),
2226                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
2227                         inset->setBuffer(bv->buffer());
2228                         insertInset(cur, inset);
2229
2230                         // enter macro inset and select the name
2231                         cur.push(*inset);
2232                         cur.top().pos() = cur.top().lastpos();
2233                         cur.resetAnchor();
2234                         cur.selection(true);
2235                         cur.top().pos() = 0;
2236                 }
2237                 break;
2238
2239         case LFUN_MATH_DISPLAY:
2240         case LFUN_MATH_SUBSCRIPT:
2241         case LFUN_MATH_SUPERSCRIPT:
2242         case LFUN_MATH_INSERT:
2243         case LFUN_MATH_AMS_MATRIX:
2244         case LFUN_MATH_MATRIX:
2245         case LFUN_MATH_DELIM:
2246         case LFUN_MATH_BIGDELIM:
2247                 mathDispatch(cur, cmd);
2248                 break;
2249
2250         case LFUN_FONT_EMPH: {
2251                 Font font(ignore_font, ignore_language);
2252                 font.fontInfo().setEmph(FONT_TOGGLE);
2253                 toggleAndShow(cur, this, font);
2254                 break;
2255         }
2256
2257         case LFUN_FONT_ITAL: {
2258                 Font font(ignore_font, ignore_language);
2259                 font.fontInfo().setShape(ITALIC_SHAPE);
2260                 toggleAndShow(cur, this, font);
2261                 break;
2262         }
2263
2264         case LFUN_FONT_BOLD:
2265         case LFUN_FONT_BOLDSYMBOL: {
2266                 Font font(ignore_font, ignore_language);
2267                 font.fontInfo().setSeries(BOLD_SERIES);
2268                 toggleAndShow(cur, this, font);
2269                 break;
2270         }
2271
2272         case LFUN_FONT_NOUN: {
2273                 Font font(ignore_font, ignore_language);
2274                 font.fontInfo().setNoun(FONT_TOGGLE);
2275                 toggleAndShow(cur, this, font);
2276                 break;
2277         }
2278
2279         case LFUN_FONT_TYPEWRITER: {
2280                 Font font(ignore_font, ignore_language);
2281                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
2282                 toggleAndShow(cur, this, font);
2283                 break;
2284         }
2285
2286         case LFUN_FONT_SANS: {
2287                 Font font(ignore_font, ignore_language);
2288                 font.fontInfo().setFamily(SANS_FAMILY);
2289                 toggleAndShow(cur, this, font);
2290                 break;
2291         }
2292
2293         case LFUN_FONT_ROMAN: {
2294                 Font font(ignore_font, ignore_language);
2295                 font.fontInfo().setFamily(ROMAN_FAMILY);
2296                 toggleAndShow(cur, this, font);
2297                 break;
2298         }
2299
2300         case LFUN_FONT_DEFAULT: {
2301                 Font font(inherit_font, ignore_language);
2302                 toggleAndShow(cur, this, font);
2303                 break;
2304         }
2305
2306         case LFUN_FONT_STRIKEOUT: {
2307                 Font font(ignore_font, ignore_language);
2308                 font.fontInfo().setStrikeout(FONT_TOGGLE);
2309                 toggleAndShow(cur, this, font);
2310                 break;
2311         }
2312
2313         case LFUN_FONT_CROSSOUT: {
2314                 Font font(ignore_font, ignore_language);
2315                 font.fontInfo().setXout(FONT_TOGGLE);
2316                 toggleAndShow(cur, this, font);
2317                 break;
2318         }
2319
2320         case LFUN_FONT_UNDERUNDERLINE: {
2321                 Font font(ignore_font, ignore_language);
2322                 font.fontInfo().setUuline(FONT_TOGGLE);
2323                 toggleAndShow(cur, this, font);
2324                 break;
2325         }
2326
2327         case LFUN_FONT_UNDERWAVE: {
2328                 Font font(ignore_font, ignore_language);
2329                 font.fontInfo().setUwave(FONT_TOGGLE);
2330                 toggleAndShow(cur, this, font);
2331                 break;
2332         }
2333
2334         case LFUN_FONT_UNDERLINE: {
2335                 Font font(ignore_font, ignore_language);
2336                 font.fontInfo().setUnderbar(FONT_TOGGLE);
2337                 toggleAndShow(cur, this, font);
2338                 break;
2339         }
2340
2341         case LFUN_FONT_SIZE: {
2342                 Font font(ignore_font, ignore_language);
2343                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
2344                 toggleAndShow(cur, this, font);
2345                 break;
2346         }
2347
2348         case LFUN_LANGUAGE: {
2349                 string const lang_arg = cmd.getArg(0);
2350                 bool const reset = (lang_arg.empty() || lang_arg == "reset");
2351                 Language const * lang =
2352                         reset ? reset_language
2353                               : languages.getLanguage(lang_arg);
2354                 // we allow reset_language, which is 0, but only if it
2355                 // was requested via empty or "reset" arg.
2356                 if (!lang && !reset)
2357                         break;
2358                 bool const toggle = (cmd.getArg(1) != "set");
2359                 selectWordWhenUnderCursor(cur, WHOLE_WORD_STRICT);
2360                 Font font(ignore_font, lang);
2361                 toggleAndShow(cur, this, font, toggle);
2362                 // We need a buffer update if we change the language
2363                 // of an info inset
2364                 if (cur.insetInSelection(INFO_CODE))
2365                         cur.forceBufferUpdate();
2366                 break;
2367         }
2368
2369         case LFUN_TEXTSTYLE_APPLY: {
2370                 unsigned int num = 0;
2371                 string const arg = to_utf8(cmd.argument());
2372                 // Argument?
2373                 if (!arg.empty()) {
2374                         if (isStrUnsignedInt(arg)) {
2375                                 num = convert<uint>(arg);
2376                                 if (num >= freeFonts.size()) {
2377                                         cur.message(_("Invalid argument (number exceeds stack size)!"));
2378                                         break;
2379                                 }
2380                         } else {
2381                                 cur.message(_("Invalid argument (must be a non-negative number)!"));
2382                                 break;
2383                         }
2384                 }
2385                 toggleAndShow(cur, this, freeFonts[num].second, toggleall);
2386                 cur.message(bformat(_("Text properties applied: %1$s"), freeFonts[num].first));
2387                 break;
2388         }
2389
2390         // Set the freefont using the contents of \param data dispatched from
2391         // the frontends and apply it at the current cursor location.
2392         case LFUN_TEXTSTYLE_UPDATE: {
2393                 Font font(ignore_font, ignore_language);
2394                 bool toggle;
2395                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
2396                         docstring const props = font.stateText(&bv->buffer().params(), true);
2397                         freeFonts.push(make_pair(props, font));
2398                         toggleall = toggle;
2399                         toggleAndShow(cur, this, font, toggleall);
2400                         // We need a buffer update if we change the language
2401                         // of an info inset
2402                         if (cur.insetInSelection(INFO_CODE))
2403                                 cur.forceBufferUpdate();
2404                         cur.message(bformat(_("Text properties applied: %1$s"), props));
2405                 } else
2406                         LYXERR0("Invalid argument of textstyle-update");
2407                 break;
2408         }
2409
2410         case LFUN_FINISHED_LEFT:
2411                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
2412                 // We're leaving an inset, going left. If the inset is LTR, we're
2413                 // leaving from the front, so we should not move (remain at --- but
2414                 // not in --- the inset). If the inset is RTL, move left, without
2415                 // entering the inset itself; i.e., move to after the inset.
2416                 if (cur.paragraph().getFontSettings(
2417                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2418                         cursorVisLeft(cur, true);
2419                 break;
2420
2421         case LFUN_FINISHED_RIGHT:
2422                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
2423                 // We're leaving an inset, going right. If the inset is RTL, we're
2424                 // leaving from the front, so we should not move (remain at --- but
2425                 // not in --- the inset). If the inset is LTR, move right, without
2426                 // entering the inset itself; i.e., move to after the inset.
2427                 if (!cur.paragraph().getFontSettings(
2428                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
2429                         cursorVisRight(cur, true);
2430                 break;
2431
2432         case LFUN_FINISHED_BACKWARD:
2433                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
2434                 cur.setCurrentFont();
2435                 break;
2436
2437         case LFUN_FINISHED_FORWARD:
2438                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
2439                 ++cur.pos();
2440                 cur.setCurrentFont();
2441                 break;
2442
2443         case LFUN_LAYOUT_PARAGRAPH: {
2444                 string data;
2445                 params2string(cur.paragraph(), data);
2446                 data = "show\n" + data;
2447                 bv->showDialog("paragraph", data);
2448                 break;
2449         }
2450
2451         case LFUN_PARAGRAPH_UPDATE: {
2452                 string data;
2453                 params2string(cur.paragraph(), data);
2454
2455                 // Will the paragraph accept changes from the dialog?
2456                 bool const accept =
2457                         cur.inset().allowParagraphCustomization(cur.idx());
2458
2459                 data = "update " + convert<string>(accept) + '\n' + data;
2460                 bv->updateDialog("paragraph", data);
2461                 break;
2462         }
2463
2464         case LFUN_ACCENT_UMLAUT:
2465         case LFUN_ACCENT_CIRCUMFLEX:
2466         case LFUN_ACCENT_GRAVE:
2467         case LFUN_ACCENT_ACUTE:
2468         case LFUN_ACCENT_TILDE:
2469         case LFUN_ACCENT_PERISPOMENI:
2470         case LFUN_ACCENT_CEDILLA:
2471         case LFUN_ACCENT_MACRON:
2472         case LFUN_ACCENT_DOT:
2473         case LFUN_ACCENT_UNDERDOT:
2474         case LFUN_ACCENT_UNDERBAR:
2475         case LFUN_ACCENT_CARON:
2476         case LFUN_ACCENT_BREVE:
2477         case LFUN_ACCENT_TIE:
2478         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2479         case LFUN_ACCENT_CIRCLE:
2480         case LFUN_ACCENT_OGONEK:
2481                 theApp()->handleKeyFunc(cmd.action());
2482                 if (!cmd.argument().empty())
2483                         // FIXME: Are all these characters encoded in one byte in utf8?
2484                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2485                 cur.screenUpdateFlags(Update::FitCursor);
2486                 break;
2487
2488         case LFUN_FLOAT_LIST_INSERT: {
2489                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2490                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2491                         cur.recordUndo();
2492                         if (cur.selection())
2493                                 cutSelection(cur, false);
2494                         breakParagraph(cur);
2495
2496                         if (cur.lastpos() != 0) {
2497                                 cursorBackward(cur);
2498                                 breakParagraph(cur);
2499                         }
2500
2501                         docstring const laystr = cur.inset().usePlainLayout() ?
2502                                 tclass.plainLayoutName() :
2503                                 tclass.defaultLayoutName();
2504                         setLayout(cur, laystr);
2505                         ParagraphParameters p;
2506                         // FIXME If this call were replaced with one to clearParagraphParams(),
2507                         // then we could get rid of this method altogether.
2508                         setParagraphs(cur, p);
2509                         // FIXME This should be simplified when InsetFloatList takes a
2510                         // Buffer in its constructor.
2511                         InsetFloatList * ifl = new InsetFloatList(cur.buffer(), to_utf8(cmd.argument()));
2512                         ifl->setBuffer(bv->buffer());
2513                         insertInset(cur, ifl);
2514                         cur.posForward();
2515                 } else {
2516                         lyxerr << "Non-existent float type: "
2517                                << to_utf8(cmd.argument()) << endl;
2518                 }
2519                 break;
2520         }
2521
2522         case LFUN_CHANGE_ACCEPT: {
2523                 acceptOrRejectChanges(cur, ACCEPT);
2524                 break;
2525         }
2526
2527         case LFUN_CHANGE_REJECT: {
2528                 acceptOrRejectChanges(cur, REJECT);
2529                 break;
2530         }
2531
2532         case LFUN_THESAURUS_ENTRY: {
2533                 Language const * language = cur.getFont().language();
2534                 docstring arg = cmd.argument();
2535                 if (arg.empty()) {
2536                         arg = cur.selectionAsString(false);
2537                         // FIXME
2538                         if (arg.size() > 100 || arg.empty()) {
2539                                 // Get word or selection
2540                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2541                                 arg = cur.selectionAsString(false);
2542                                 arg += " lang=" + from_ascii(language->lang());
2543                         }
2544                 } else {
2545                         string lang = cmd.getArg(1);
2546                         // This duplicates the code in GuiThesaurus::initialiseParams
2547                         if (prefixIs(lang, "lang=")) {
2548                                 language = languages.getLanguage(lang.substr(5));
2549                                 if (!language)
2550                                         language = cur.getFont().language();
2551                         }
2552                 }
2553                 string lang = language->code();
2554                 if (lyxrc.thesaurusdir_path.empty() && !thesaurus.thesaurusInstalled(from_ascii(lang))) {
2555                         LYXERR(Debug::ACTION, "Command " << cmd << ". Thesaurus not found for language " << lang);
2556                         frontend::Alert::warning(_("Path to thesaurus directory not set!"),
2557                                         _("The path to the thesaurus directory has not been specified.\n"
2558                                           "The thesaurus is not functional.\n"
2559                                           "Please refer to sec. 6.15.1 of the User's Guide for setup\n"
2560                                           "instructions."));
2561                 }
2562                 bv->showDialog("thesaurus", to_utf8(arg));
2563                 break;
2564         }
2565
2566         case LFUN_SPELLING_ADD: {
2567                 Language const * language = getLanguage(cur, cmd.getArg(1));
2568                 docstring word = from_utf8(cmd.getArg(0));
2569                 if (word.empty()) {
2570                         word = cur.selectionAsString(false);
2571                         // FIXME
2572                         if (word.size() > 100 || word.empty()) {
2573                                 // Get word or selection
2574                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2575                                 word = cur.selectionAsString(false);
2576                         }
2577                 }
2578                 WordLangTuple wl(word, language);
2579                 theSpellChecker()->insert(wl);
2580                 break;
2581         }
2582
2583         case LFUN_SPELLING_IGNORE: {
2584                 Language const * language = getLanguage(cur, cmd.getArg(1));
2585                 docstring word = from_utf8(cmd.getArg(0));
2586                 if (word.empty()) {
2587                         word = cur.selectionAsString(false);
2588                         // FIXME
2589                         if (word.size() > 100 || word.empty()) {
2590                                 // Get word or selection
2591                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2592                                 word = cur.selectionAsString(false);
2593                         }
2594                 }
2595                 WordLangTuple wl(word, language);
2596                 theSpellChecker()->accept(wl);
2597                 break;
2598         }
2599
2600         case LFUN_SPELLING_REMOVE: {
2601                 Language const * language = getLanguage(cur, cmd.getArg(1));
2602                 docstring word = from_utf8(cmd.getArg(0));
2603                 if (word.empty()) {
2604                         word = cur.selectionAsString(false);
2605                         // FIXME
2606                         if (word.size() > 100 || word.empty()) {
2607                                 // Get word or selection
2608                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2609                                 word = cur.selectionAsString(false);
2610                         }
2611                 }
2612                 WordLangTuple wl(word, language);
2613                 theSpellChecker()->remove(wl);
2614                 break;
2615         }
2616
2617         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2618                 // Given data, an encoding of the ParagraphParameters
2619                 // generated in the Paragraph dialog, this function sets
2620                 // the current paragraph, or currently selected paragraphs,
2621                 // appropriately.
2622                 // NOTE: This function overrides all existing settings.
2623                 setParagraphs(cur, cmd.argument());
2624                 cur.message(_("Paragraph layout set"));
2625                 break;
2626         }
2627
2628         case LFUN_PARAGRAPH_PARAMS: {
2629                 // Given data, an encoding of the ParagraphParameters as we'd
2630                 // find them in a LyX file, this function modifies the current paragraph,
2631                 // or currently selected paragraphs.
2632                 // NOTE: This function only modifies, and does not override, existing
2633                 // settings.
2634                 setParagraphs(cur, cmd.argument(), true);
2635                 cur.message(_("Paragraph layout set"));
2636                 break;
2637         }
2638
2639         case LFUN_ESCAPE:
2640                 if (cur.selection()) {
2641                         cur.selection(false);
2642                 } else {
2643                         cur.undispatched();
2644                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2645                         // correct, but I'm not 100% sure -- dov, 071019
2646                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2647                 }
2648                 break;
2649
2650         case LFUN_OUTLINE_UP:
2651                 outline(OutlineUp, cur, this);
2652                 setCursor(cur, cur.pit(), 0);
2653                 cur.forceBufferUpdate();
2654                 needsUpdate = true;
2655                 break;
2656
2657         case LFUN_OUTLINE_DOWN:
2658                 outline(OutlineDown, cur, this);
2659                 setCursor(cur, cur.pit(), 0);
2660                 cur.forceBufferUpdate();
2661                 needsUpdate = true;
2662                 break;
2663
2664         case LFUN_OUTLINE_IN:
2665                 outline(OutlineIn, cur, this);
2666                 cur.forceBufferUpdate();
2667                 needsUpdate = true;
2668                 break;
2669
2670         case LFUN_OUTLINE_OUT:
2671                 outline(OutlineOut, cur, this);
2672                 cur.forceBufferUpdate();
2673                 needsUpdate = true;
2674                 break;
2675
2676         case LFUN_SERVER_GET_STATISTICS:
2677                 {
2678                         DocIterator from, to;
2679                         if (cur.selection()) {
2680                                 from = cur.selectionBegin();
2681                                 to = cur.selectionEnd();
2682                         } else {
2683                                 from = doc_iterator_begin(cur.buffer());
2684                                 to = doc_iterator_end(cur.buffer());
2685                         }
2686
2687                         cur.buffer()->updateStatistics(from, to);
2688                         string const arg0 = cmd.getArg(0);
2689                         if (arg0 == "words") {
2690                                 cur.message(convert<docstring>(cur.buffer()->wordCount()));
2691                         } else if (arg0 == "chars") {
2692                                 cur.message(convert<docstring>(cur.buffer()->charCount(false)));
2693                         } else if (arg0 == "chars-space") {
2694                                 cur.message(convert<docstring>(cur.buffer()->charCount(true)));
2695                         } else {
2696                                 cur.message(convert<docstring>(cur.buffer()->wordCount()) + " "
2697                                 + convert<docstring>(cur.buffer()->charCount(false)) + " "
2698                                 + convert<docstring>(cur.buffer()->charCount(true)));
2699                         }
2700                 }
2701                 break;
2702
2703         default:
2704                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2705                 cur.undispatched();
2706                 break;
2707         }
2708
2709         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2710
2711         if (lyxrc.spellcheck_continuously && !needsUpdate) {
2712                 // Check for misspelled text
2713                 // The redraw is useful because of the painting of
2714                 // misspelled markers depends on the cursor position.
2715                 // Trigger a redraw for cursor moves inside misspelled text.
2716                 if (!cur.inTexted()) {
2717                         // move from regular text to math
2718                         needsUpdate = last_misspelled;
2719                 } else if (oldTopSlice != cur.top() || oldBoundary != cur.boundary()) {
2720                         // move inside regular text
2721                         needsUpdate = last_misspelled
2722                                 || cur.paragraph().isMisspelled(cur.pos(), true);
2723                 }
2724         }
2725
2726         // FIXME: The cursor flag is reset two lines below
2727         // so we need to check here if some of the LFUN did touch that.
2728         // for now only Text::erase() and Text::backspace() do that.
2729         // The plan is to verify all the LFUNs and then to remove this
2730         // singleParUpdate boolean altogether.
2731         if (cur.result().screenUpdate() & Update::Force) {
2732                 singleParUpdate = false;
2733                 needsUpdate = true;
2734         }
2735
2736         // FIXME: the following code should go in favor of fine grained
2737         // update flag treatment.
2738         if (singleParUpdate) {
2739                 // Inserting characters does not change par height in general. So, try
2740                 // to update _only_ this paragraph. BufferView will detect if a full
2741                 // metrics update is needed anyway.
2742                 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
2743                 return;
2744         }
2745         if (!needsUpdate
2746             && &oldTopSlice.inset() == &cur.inset()
2747             && oldTopSlice.idx() == cur.idx()
2748             && !oldSelection // oldSelection is a backup of cur.selection() at the beginning of the function.
2749             && !cur.selection())
2750                 // FIXME: it would be better if we could just do this
2751                 //
2752                 //if (cur.result().update() != Update::FitCursor)
2753                 //      cur.noScreenUpdate();
2754                 //
2755                 // But some LFUNs do not set Update::FitCursor when needed, so we
2756                 // do it for all. This is not very harmfull as FitCursor will provoke
2757                 // a full redraw only if needed but still, a proper review of all LFUN
2758                 // should be done and this needsUpdate boolean can then be removed.
2759                 cur.screenUpdateFlags(Update::FitCursor);
2760         else
2761                 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
2762 }
2763
2764
2765 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2766                         FuncStatus & flag) const
2767 {
2768         LBUFERR(this == cur.text());
2769
2770         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2771         bool enable = true;
2772         bool allow_in_passthru = false;
2773         InsetCode code = NO_CODE;
2774
2775         switch (cmd.action()) {
2776
2777         case LFUN_DEPTH_DECREMENT:
2778                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2779                 break;
2780
2781         case LFUN_DEPTH_INCREMENT:
2782                 enable = changeDepthAllowed(cur, INC_DEPTH);
2783                 break;
2784
2785         case LFUN_APPENDIX:
2786                 // FIXME We really should not allow this to be put, e.g.,
2787                 // in a footnote, or in ERT. But it would make sense in a
2788                 // branch, so I'm not sure what to do.
2789                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2790                 break;
2791
2792         case LFUN_DIALOG_SHOW_NEW_INSET:
2793                 if (cmd.argument() == "bibitem")
2794                         code = BIBITEM_CODE;
2795                 else if (cmd.argument() == "bibtex") {
2796                         code = BIBTEX_CODE;
2797                         // not allowed in description items
2798                         enable = !inDescriptionItem(cur);
2799                 }
2800                 else if (cmd.argument() == "box")
2801                         code = BOX_CODE;
2802                 else if (cmd.argument() == "branch")
2803                         code = BRANCH_CODE;
2804                 else if (cmd.argument() == "citation")
2805                         code = CITE_CODE;
2806                 else if (cmd.argument() == "ert")
2807                         code = ERT_CODE;
2808                 else if (cmd.argument() == "external")
2809                         code = EXTERNAL_CODE;
2810                 else if (cmd.argument() == "float")
2811                         code = FLOAT_CODE;
2812                 else if (cmd.argument() == "graphics")
2813                         code = GRAPHICS_CODE;
2814                 else if (cmd.argument() == "href")
2815                         code = HYPERLINK_CODE;
2816                 else if (cmd.argument() == "include")
2817                         code = INCLUDE_CODE;
2818                 else if (cmd.argument() == "index")
2819                         code = INDEX_CODE;
2820                 else if (cmd.argument() == "index_print")
2821                         code = INDEX_PRINT_CODE;
2822                 else if (cmd.argument() == "listings")
2823                         code = LISTINGS_CODE;
2824                 else if (cmd.argument() == "mathspace")
2825                         code = MATH_HULL_CODE;
2826                 else if (cmd.argument() == "nomenclature")
2827                         code = NOMENCL_CODE;
2828                 else if (cmd.argument() == "nomencl_print")
2829                         code = NOMENCL_PRINT_CODE;
2830                 else if (cmd.argument() == "label")
2831                         code = LABEL_CODE;
2832                 else if (cmd.argument() == "line")
2833                         code = LINE_CODE;
2834                 else if (cmd.argument() == "note")
2835                         code = NOTE_CODE;
2836                 else if (cmd.argument() == "phantom")
2837                         code = PHANTOM_CODE;
2838                 else if (cmd.argument() == "ref")
2839                         code = REF_CODE;
2840                 else if (cmd.argument() == "space")
2841                         code = SPACE_CODE;
2842                 else if (cmd.argument() == "toc")
2843                         code = TOC_CODE;
2844                 else if (cmd.argument() == "vspace")
2845                         code = VSPACE_CODE;
2846                 else if (cmd.argument() == "wrap")
2847                         code = WRAP_CODE;
2848                 break;
2849
2850         case LFUN_ERT_INSERT:
2851                 code = ERT_CODE;
2852                 break;
2853         case LFUN_LISTING_INSERT:
2854                 code = LISTINGS_CODE;
2855                 // not allowed in description items
2856                 enable = !inDescriptionItem(cur);
2857                 break;
2858         case LFUN_FOOTNOTE_INSERT:
2859                 code = FOOT_CODE;
2860                 break;
2861         case LFUN_TABULAR_INSERT:
2862                 code = TABULAR_CODE;
2863                 break;
2864         case LFUN_MARGINALNOTE_INSERT:
2865                 code = MARGIN_CODE;
2866                 break;
2867         case LFUN_FLOAT_INSERT:
2868         case LFUN_FLOAT_WIDE_INSERT:
2869                 // FIXME: If there is a selection, we should check whether there
2870                 // are floats in the selection, but this has performance issues, see
2871                 // LFUN_CHANGE_ACCEPT/REJECT.
2872                 code = FLOAT_CODE;
2873                 if (inDescriptionItem(cur))
2874                         // not allowed in description items
2875                         enable = false;
2876                 else {
2877                         InsetCode const inset_code = cur.inset().lyxCode();
2878
2879                         // algorithm floats cannot be put in another float
2880                         if (to_utf8(cmd.argument()) == "algorithm") {
2881                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2882                                 break;
2883                         }
2884
2885                         // for figures and tables: only allow in another
2886                         // float or wrap if it is of the same type and
2887                         // not a subfloat already
2888                         if(cur.inset().lyxCode() == code) {
2889                                 InsetFloat const & ins =
2890                                         static_cast<InsetFloat const &>(cur.inset());
2891                                 enable = ins.params().type == to_utf8(cmd.argument())
2892                                         && !ins.params().subfloat;
2893                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2894                                 InsetWrap const & ins =
2895                                         static_cast<InsetWrap const &>(cur.inset());
2896                                 enable = ins.params().type == to_utf8(cmd.argument());
2897                         }
2898                 }
2899                 break;
2900         case LFUN_WRAP_INSERT:
2901                 code = WRAP_CODE;
2902                 // not allowed in description items
2903                 enable = !inDescriptionItem(cur);
2904                 break;
2905         case LFUN_FLOAT_LIST_INSERT: {
2906                 code = FLOAT_LIST_CODE;
2907                 // not allowed in description items
2908                 enable = !inDescriptionItem(cur);
2909                 if (enable) {
2910                         FloatList const & floats = cur.buffer()->params().documentClass().floats();
2911                         FloatList::const_iterator cit = floats[to_ascii(cmd.argument())];
2912                         // make sure we know about such floats
2913                         if (cit == floats.end() ||
2914                                         // and that we know how to generate a list of them
2915                             (!cit->second.usesFloatPkg() && cit->second.listCommand().empty())) {
2916                                 flag.setUnknown(true);
2917                                 // probably not necessary, but...
2918                                 enable = false;
2919                         }
2920                 }
2921                 break;
2922         }
2923         case LFUN_CAPTION_INSERT: {
2924                 code = CAPTION_CODE;
2925                 string arg = cmd.getArg(0);
2926                 bool varia = arg != "Unnumbered"
2927                         && cur.inset().allowsCaptionVariation(arg);
2928                 // not allowed in description items,
2929                 // and in specific insets
2930                 enable = !inDescriptionItem(cur)
2931                         && (varia || arg.empty() || arg == "Standard");
2932                 break;
2933         }
2934         case LFUN_NOTE_INSERT:
2935                 code = NOTE_CODE;
2936                 break;
2937         case LFUN_FLEX_INSERT: {
2938                 code = FLEX_CODE;
2939                 string s = cmd.getArg(0);
2940                 InsetLayout il =
2941                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2942                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2943                     il.lyxtype() != InsetLayout::CUSTOM &&
2944                     il.lyxtype() != InsetLayout::ELEMENT &&
2945                     il.lyxtype ()!= InsetLayout::STANDARD)
2946                         enable = false;
2947                 break;
2948                 }
2949         case LFUN_BOX_INSERT:
2950                 code = BOX_CODE;
2951                 break;
2952         case LFUN_BRANCH_INSERT:
2953                 code = BRANCH_CODE;
2954                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2955                     && cur.buffer()->params().branchlist().empty())
2956                         enable = false;
2957                 break;
2958         case LFUN_IPA_INSERT:
2959                 code = IPA_CODE;
2960                 break;
2961         case LFUN_PHANTOM_INSERT:
2962                 code = PHANTOM_CODE;
2963                 break;
2964         case LFUN_LABEL_INSERT:
2965                 code = LABEL_CODE;
2966                 break;
2967         case LFUN_INFO_INSERT:
2968                 code = INFO_CODE;
2969                 enable = cmd.argument().empty()
2970                         || infoparams.validateArgument(cur.buffer(), cmd.argument(), true);
2971                 break;
2972         case LFUN_ARGUMENT_INSERT: {
2973                 code = ARG_CODE;
2974                 allow_in_passthru = true;
2975                 string const arg = cmd.getArg(0);
2976                 if (arg.empty()) {
2977                         enable = false;
2978                         break;
2979                 }
2980                 Layout const & lay = cur.paragraph().layout();
2981                 Layout::LaTeXArgMap args = lay.args();
2982                 Layout::LaTeXArgMap::const_iterator const lait =
2983                                 args.find(arg);
2984                 if (lait != args.end()) {
2985                         enable = true;
2986                         pit_type pit = cur.pit();
2987                         pit_type lastpit = cur.pit();
2988                         if (lay.isEnvironment() && !prefixIs(arg, "item:")) {
2989                                 // In a sequence of "merged" environment layouts, we only allow
2990                                 // non-item arguments once.
2991                                 lastpit = cur.lastpit();
2992                                 // get the first paragraph in sequence with this layout
2993                                 depth_type const current_depth = cur.paragraph().params().depth();
2994                                 while (true) {
2995                                         if (pit == 0)
2996                                                 break;
2997                                         Paragraph cpar = pars_[pit - 1];
2998                                         if (cpar.layout() == lay && cpar.params().depth() == current_depth)
2999                                                 --pit;
3000                                         else
3001                                                 break;
3002                                 }
3003                         }
3004                         for (; pit <= lastpit; ++pit) {
3005                                 if (pars_[pit].layout() != lay)
3006                                         break;
3007                                 for (auto const & table : pars_[pit].insetList())
3008                                         if (InsetArgument const * ins = table.inset->asInsetArgument())
3009                                                 if (ins->name() == arg) {
3010                                                         // we have this already
3011                                                         enable = false;
3012                                                         break;
3013                                                 }
3014                         }
3015                 } else
3016                         enable = false;
3017                 break;
3018         }
3019         case LFUN_INDEX_INSERT:
3020                 code = INDEX_CODE;
3021                 break;
3022         case LFUN_INDEX_PRINT:
3023                 code = INDEX_PRINT_CODE;
3024                 // not allowed in description items
3025                 enable = !inDescriptionItem(cur);
3026                 break;
3027         case LFUN_NOMENCL_INSERT:
3028                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3029                         enable = false;
3030                         break;
3031                 }
3032                 code = NOMENCL_CODE;
3033                 break;
3034         case LFUN_NOMENCL_PRINT:
3035                 code = NOMENCL_PRINT_CODE;
3036                 // not allowed in description items
3037                 enable = !inDescriptionItem(cur);
3038                 break;
3039         case LFUN_HREF_INSERT:
3040                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
3041                         enable = false;
3042                         break;
3043                 }
3044                 code = HYPERLINK_CODE;
3045                 break;
3046         case LFUN_IPAMACRO_INSERT: {
3047                 string const arg = cmd.getArg(0);
3048                 if (arg == "deco")
3049                         code = IPADECO_CODE;
3050                 else
3051                         code = IPACHAR_CODE;
3052                 break;
3053         }
3054         case LFUN_QUOTE_INSERT:
3055                 // always allow this, since we will inset a raw quote
3056                 // if an inset is not allowed.
3057                 allow_in_passthru = true;
3058                 break;
3059         case LFUN_SPECIALCHAR_INSERT:
3060                 code = SPECIALCHAR_CODE;
3061                 break;
3062         case LFUN_SPACE_INSERT:
3063                 // slight hack: we know this is allowed in math mode
3064                 if (cur.inTexted())
3065                         code = SPACE_CODE;
3066                 break;
3067         case LFUN_PREVIEW_INSERT:
3068                 code = PREVIEW_CODE;
3069                 break;
3070         case LFUN_SCRIPT_INSERT:
3071                 code = SCRIPT_CODE;
3072                 break;
3073
3074         case LFUN_MATH_INSERT:
3075         case LFUN_MATH_AMS_MATRIX:
3076         case LFUN_MATH_MATRIX:
3077         case LFUN_MATH_DELIM:
3078         case LFUN_MATH_BIGDELIM:
3079         case LFUN_MATH_DISPLAY:
3080         case LFUN_MATH_MODE:
3081         case LFUN_MATH_MACRO:
3082         case LFUN_MATH_SUBSCRIPT:
3083         case LFUN_MATH_SUPERSCRIPT:
3084                 code = MATH_HULL_CODE;
3085                 break;
3086
3087         case LFUN_REGEXP_MODE:
3088                 code = MATH_HULL_CODE;
3089                 enable = cur.buffer()->isInternal() && !cur.inRegexped();
3090                 break;
3091
3092         case LFUN_INSET_MODIFY:
3093                 // We need to disable this, because we may get called for a
3094                 // tabular cell via
3095                 // InsetTabular::getStatus() -> InsetText::getStatus()
3096                 // and we don't handle LFUN_INSET_MODIFY.
3097                 enable = false;
3098                 break;
3099
3100         case LFUN_FONT_EMPH:
3101                 flag.setOnOff(fontinfo.emph() == FONT_ON);
3102                 enable = !cur.paragraph().isPassThru();
3103                 break;
3104
3105         case LFUN_FONT_ITAL:
3106                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
3107                 enable = !cur.paragraph().isPassThru();
3108                 break;
3109
3110         case LFUN_FONT_NOUN:
3111                 flag.setOnOff(fontinfo.noun() == FONT_ON);
3112                 enable = !cur.paragraph().isPassThru();
3113                 break;
3114
3115         case LFUN_FONT_BOLD:
3116         case LFUN_FONT_BOLDSYMBOL:
3117                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
3118                 enable = !cur.paragraph().isPassThru();
3119                 break;
3120
3121         case LFUN_FONT_SANS:
3122                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
3123                 enable = !cur.paragraph().isPassThru();
3124                 break;
3125
3126         case LFUN_FONT_ROMAN:
3127                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
3128                 enable = !cur.paragraph().isPassThru();
3129                 break;
3130
3131         case LFUN_FONT_TYPEWRITER:
3132                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
3133                 enable = !cur.paragraph().isPassThru();
3134                 break;
3135
3136         case LFUN_CUT:
3137         case LFUN_COPY:
3138                 enable = cur.selection();
3139                 break;
3140
3141         case LFUN_PASTE: {
3142                 if (cmd.argument().empty()) {
3143                         if (theClipboard().isInternal())
3144                                 enable = cap::numberOfSelections() > 0;
3145                         else
3146                                 enable = !theClipboard().empty();
3147                         break;
3148                 }
3149
3150                 // we have an argument
3151                 string const arg = to_utf8(cmd.argument());
3152                 if (isStrUnsignedInt(arg)) {
3153                         // it's a number and therefore means the internal stack
3154                         unsigned int n = convert<unsigned int>(arg);
3155                         enable = cap::numberOfSelections() > n;
3156                         break;
3157                 }
3158
3159                 // explicit text type?
3160                 if (arg == "html") {
3161                         // Do not enable for PlainTextType, since some tidying in the
3162                         // frontend is needed for HTML, which is too unsafe for plain text.
3163                         enable = theClipboard().hasTextContents(Clipboard::HtmlTextType);
3164                         break;
3165                 } else if (arg == "latex") {
3166                         // LaTeX is usually not available on the clipboard with
3167                         // the correct MIME type, but in plain text.
3168                         enable = theClipboard().hasTextContents(Clipboard::PlainTextType) ||
3169                                  theClipboard().hasTextContents(Clipboard::LaTeXTextType);
3170                         break;
3171                 }
3172
3173                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
3174                 if (arg == "pdf")
3175                         type = Clipboard::PdfGraphicsType;
3176                 else if (arg == "png")
3177                         type = Clipboard::PngGraphicsType;
3178                 else if (arg == "jpeg")
3179                         type = Clipboard::JpegGraphicsType;
3180                 else if (arg == "linkback")
3181                         type = Clipboard::LinkBackGraphicsType;
3182                 else if (arg == "emf")
3183                         type = Clipboard::EmfGraphicsType;
3184                 else if (arg == "wmf")
3185                         type = Clipboard::WmfGraphicsType;
3186                 else {
3187                         // unknown argument
3188                         LYXERR0("Unrecognized graphics type: " << arg);
3189                         // we don't want to assert if the user just mistyped the LFUN
3190                         LATTEST(cmd.origin() != FuncRequest::INTERNAL);
3191                         enable = false;
3192                         break;
3193                 }
3194                 enable = theClipboard().hasGraphicsContents(type);
3195                 break;
3196         }
3197
3198         case LFUN_CLIPBOARD_PASTE:
3199         case LFUN_CLIPBOARD_PASTE_SIMPLE:
3200                 enable = !theClipboard().empty();
3201                 break;
3202
3203         case LFUN_PRIMARY_SELECTION_PASTE:
3204                 enable = cur.selection() || !theSelection().empty();
3205                 break;
3206
3207         case LFUN_SELECTION_PASTE:
3208                 enable = cap::selection();
3209                 break;
3210
3211         case LFUN_PARAGRAPH_MOVE_UP:
3212                 enable = cur.pit() > 0 && !cur.selection();
3213                 break;
3214
3215         case LFUN_PARAGRAPH_MOVE_DOWN:
3216                 enable = cur.pit() < cur.lastpit() && !cur.selection();
3217                 break;
3218
3219         case LFUN_CHANGE_ACCEPT:
3220         case LFUN_CHANGE_REJECT:
3221                 if (!cur.selection())
3222                         enable = cur.paragraph().isChanged(cur.pos());
3223                 else {
3224                         // will enable if there is a change in the selection
3225                         enable = false;
3226
3227                         // cheap improvement for efficiency: using cached
3228                         // buffer variable, if there is no change in the
3229                         // document, no need to check further.
3230                         if (!cur.buffer()->areChangesPresent())
3231                                 break;
3232
3233                         for (DocIterator it = cur.selectionBegin(); ; it.forwardPar()) {
3234                                 pos_type const beg = it.pos();
3235                                 pos_type end;
3236                                 bool const in_last_par = (it.pit() == cur.selectionEnd().pit());
3237                                 if (in_last_par)
3238                                         end = cur.selectionEnd().pos();
3239                                 else
3240                                         end = it.lastpos();
3241                                 if (beg != end && it.paragraph().isChanged(beg, end)) {
3242                                         enable = true;
3243                                         break;
3244                                 }
3245                                 if (in_last_par)
3246                                         break;
3247                         }
3248                 }
3249                 break;
3250
3251         case LFUN_OUTLINE_UP:
3252         case LFUN_OUTLINE_DOWN:
3253         case LFUN_OUTLINE_IN:
3254         case LFUN_OUTLINE_OUT:
3255                 // FIXME: LyX is not ready for outlining within inset.
3256                 enable = isMainText()
3257                         && cur.buffer()->text().getTocLevel(cur.pit()) != Layout::NOT_IN_TOC;
3258                 break;
3259
3260         case LFUN_NEWLINE_INSERT:
3261                 // LaTeX restrictions (labels or empty par)
3262                 enable = !cur.paragraph().isPassThru()
3263                         && cur.pos() > cur.paragraph().beginOfBody();
3264                 break;
3265
3266         case LFUN_SEPARATOR_INSERT:
3267                 // Always enabled for now
3268                 enable = true;
3269                 break;
3270
3271         case LFUN_TAB_INSERT:
3272         case LFUN_TAB_DELETE:
3273                 enable = cur.paragraph().isPassThru();
3274                 break;
3275
3276         case LFUN_GRAPHICS_SET_GROUP: {
3277                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
3278                 if (!ins)
3279                         enable = false;
3280                 else
3281                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
3282                 break;
3283         }
3284
3285         case LFUN_NEWPAGE_INSERT:
3286                 // not allowed in description items
3287                 code = NEWPAGE_CODE;
3288                 enable = !inDescriptionItem(cur);
3289                 break;
3290
3291         case LFUN_LANGUAGE:
3292                 enable = !cur.paragraph().isPassThru();
3293                 flag.setOnOff(cmd.getArg(0) == cur.real_current_font.language()->lang());
3294                 break;
3295
3296         case LFUN_PARAGRAPH_BREAK:
3297                 enable = inset().allowMultiPar();
3298                 break;
3299
3300         case LFUN_SPELLING_ADD:
3301         case LFUN_SPELLING_IGNORE:
3302         case LFUN_SPELLING_REMOVE:
3303                 enable = theSpellChecker() != NULL;
3304                 if (enable && !cmd.getArg(1).empty()) {
3305                         // validate explicitly given language
3306                         Language const * const lang = const_cast<Language *>(languages.getLanguage(cmd.getArg(1)));
3307                         enable &= lang != NULL;
3308                 }
3309                 break;
3310
3311         case LFUN_LAYOUT:
3312         case LFUN_LAYOUT_TOGGLE: {
3313                 bool const ignoreautonests = cmd.getArg(1) == "ignoreautonests";
3314                 docstring const req_layout = ignoreautonests ? from_utf8(cmd.getArg(0)) : cmd.argument();
3315                 docstring const layout = resolveLayout(req_layout, cur);
3316
3317                 enable = !owner_->forcePlainLayout() && !layout.empty();
3318                 flag.setOnOff(isAlreadyLayout(layout, cur));
3319                 break;
3320         }
3321
3322         case LFUN_ENVIRONMENT_SPLIT: {
3323                 if (cmd.argument() == "outer") {
3324                         // check if we have an environment in our nesting hierarchy
3325                         bool res = false;
3326                         depth_type const current_depth = cur.paragraph().params().depth();
3327                         pit_type pit = cur.pit();
3328                         Paragraph cpar = pars_[pit];
3329                         while (true) {
3330                                 if (pit == 0 || cpar.params().depth() == 0)
3331                                         break;
3332                                 --pit;
3333                                 cpar = pars_[pit];
3334                                 if (cpar.params().depth() < current_depth)
3335                                         res = cpar.layout().isEnvironment();
3336                         }
3337                         enable = res;
3338                         break;
3339                 }
3340                 else if (cmd.argument() == "previous") {
3341                         // look if we have an environment in the previous par
3342                         pit_type pit = cur.pit();
3343                         Paragraph cpar = pars_[pit];
3344                         if (pit > 0) {
3345                                 --pit;
3346                                 cpar = pars_[pit];
3347                                 enable = cpar.layout().isEnvironment();
3348                                 break;
3349                         }
3350                         enable = false;
3351                         break;
3352                 }
3353                 else if (cur.paragraph().layout().isEnvironment()) {
3354                         enable = cmd.argument() == "before"
3355                                 || cur.pos() > 0 || !isFirstInSequence(cur.pit());
3356                         break;
3357                 }
3358                 enable = false;
3359                 break;
3360         }
3361
3362         case LFUN_LAYOUT_PARAGRAPH:
3363         case LFUN_PARAGRAPH_PARAMS:
3364         case LFUN_PARAGRAPH_PARAMS_APPLY:
3365         case LFUN_PARAGRAPH_UPDATE:
3366                 enable = owner_->allowParagraphCustomization();
3367                 break;
3368
3369         // FIXME: why are accent lfuns forbidden with pass_thru layouts?
3370         //  Because they insert COMBINING DIACRITICAL Unicode characters,
3371         //  that cannot be handled by LaTeX but must be converted according
3372         //  to the definition in lib/unicodesymbols?
3373         case LFUN_ACCENT_ACUTE:
3374         case LFUN_ACCENT_BREVE:
3375         case LFUN_ACCENT_CARON:
3376         case LFUN_ACCENT_CEDILLA:
3377         case LFUN_ACCENT_CIRCLE:
3378         case LFUN_ACCENT_CIRCUMFLEX:
3379         case LFUN_ACCENT_DOT:
3380         case LFUN_ACCENT_GRAVE:
3381         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
3382         case LFUN_ACCENT_MACRON:
3383         case LFUN_ACCENT_OGONEK:
3384         case LFUN_ACCENT_TIE:
3385         case LFUN_ACCENT_TILDE:
3386         case LFUN_ACCENT_PERISPOMENI:
3387         case LFUN_ACCENT_UMLAUT:
3388         case LFUN_ACCENT_UNDERBAR:
3389         case LFUN_ACCENT_UNDERDOT:
3390         case LFUN_FONT_FRAK:
3391         case LFUN_FONT_SIZE:
3392         case LFUN_FONT_STATE:
3393         case LFUN_FONT_UNDERLINE:
3394         case LFUN_FONT_STRIKEOUT:
3395         case LFUN_FONT_CROSSOUT:
3396         case LFUN_FONT_UNDERUNDERLINE:
3397         case LFUN_FONT_UNDERWAVE:
3398         case LFUN_TEXTSTYLE_UPDATE:
3399                 enable = !cur.paragraph().isPassThru();
3400                 break;
3401
3402         case LFUN_FONT_DEFAULT: {
3403                 Font font(inherit_font, ignore_language);
3404                 BufferParams const & bp = cur.buffer()->masterParams();
3405                 if (cur.selection()) {
3406                         enable = false;
3407                         // Check if we have a non-default font attribute
3408                         // in the selection range.
3409                         DocIterator const from = cur.selectionBegin();
3410                         DocIterator const to = cur.selectionEnd();
3411                         for (DocIterator dit = from ; dit != to && !dit.atEnd(); ) {
3412                                 if (!dit.inTexted()) {
3413                                         dit.forwardPos();
3414                                         continue;
3415                                 }
3416                                 Paragraph const & par = dit.paragraph();
3417                                 pos_type const pos = dit.pos();
3418                                 Font tmp = par.getFontSettings(bp, pos);
3419                                 if (tmp.fontInfo() != font.fontInfo()
3420                                     || tmp.language() != bp.language) {
3421                                         enable = true;
3422                                         break;
3423                                 }
3424                                 dit.forwardPos();
3425                         }
3426                         break;
3427                 }
3428                 // Disable if all is default already.
3429                 enable = (cur.current_font.fontInfo() != font.fontInfo()
3430                           || cur.current_font.language() != bp.language);
3431                 break;
3432         }
3433
3434         case LFUN_TEXTSTYLE_APPLY:
3435                 enable = !freeFonts.empty();
3436                 break;
3437
3438         case LFUN_WORD_DELETE_FORWARD:
3439         case LFUN_WORD_DELETE_BACKWARD:
3440         case LFUN_LINE_DELETE_FORWARD:
3441         case LFUN_WORD_FORWARD:
3442         case LFUN_WORD_BACKWARD:
3443         case LFUN_WORD_RIGHT:
3444         case LFUN_WORD_LEFT:
3445         case LFUN_CHAR_FORWARD:
3446         case LFUN_CHAR_FORWARD_SELECT:
3447         case LFUN_CHAR_BACKWARD:
3448         case LFUN_CHAR_BACKWARD_SELECT:
3449         case LFUN_CHAR_LEFT:
3450         case LFUN_CHAR_LEFT_SELECT:
3451         case LFUN_CHAR_RIGHT:
3452         case LFUN_CHAR_RIGHT_SELECT:
3453         case LFUN_UP:
3454         case LFUN_UP_SELECT:
3455         case LFUN_DOWN:
3456         case LFUN_DOWN_SELECT:
3457         case LFUN_PARAGRAPH_UP_SELECT:
3458         case LFUN_PARAGRAPH_DOWN_SELECT:
3459         case LFUN_LINE_BEGIN_SELECT:
3460         case LFUN_LINE_END_SELECT:
3461         case LFUN_WORD_FORWARD_SELECT:
3462         case LFUN_WORD_BACKWARD_SELECT:
3463         case LFUN_WORD_RIGHT_SELECT:
3464         case LFUN_WORD_LEFT_SELECT:
3465         case LFUN_WORD_SELECT:
3466         case LFUN_SECTION_SELECT:
3467         case LFUN_BUFFER_BEGIN:
3468         case LFUN_BUFFER_END:
3469         case LFUN_BUFFER_BEGIN_SELECT:
3470         case LFUN_BUFFER_END_SELECT:
3471         case LFUN_INSET_BEGIN:
3472         case LFUN_INSET_END:
3473         case LFUN_INSET_BEGIN_SELECT:
3474         case LFUN_INSET_END_SELECT:
3475         case LFUN_PARAGRAPH_UP:
3476         case LFUN_PARAGRAPH_DOWN:
3477         case LFUN_LINE_BEGIN:
3478         case LFUN_LINE_END:
3479         case LFUN_CHAR_DELETE_FORWARD:
3480         case LFUN_CHAR_DELETE_BACKWARD:
3481         case LFUN_WORD_UPCASE:
3482         case LFUN_WORD_LOWCASE:
3483         case LFUN_WORD_CAPITALIZE:
3484         case LFUN_CHARS_TRANSPOSE:
3485         case LFUN_SERVER_GET_XY:
3486         case LFUN_SERVER_SET_XY:
3487         case LFUN_SERVER_GET_LAYOUT:
3488         case LFUN_SELF_INSERT:
3489         case LFUN_UNICODE_INSERT:
3490         case LFUN_THESAURUS_ENTRY:
3491         case LFUN_ESCAPE:
3492         case LFUN_SERVER_GET_STATISTICS:
3493                 // these are handled in our dispatch()
3494                 enable = true;
3495                 break;
3496
3497         case LFUN_INSET_INSERT: {
3498                 string const type = cmd.getArg(0);
3499                 if (type == "toc") {
3500                         code = TOC_CODE;
3501                         // not allowed in description items
3502                         //FIXME: couldn't this be merged in Inset::insetAllowed()?
3503                         enable = !inDescriptionItem(cur);
3504                 } else {
3505                         enable = true;
3506                 }
3507                 break;
3508         }
3509
3510         case LFUN_SEARCH_IGNORE: {
3511                 bool const value = cmd.getArg(1) == "true";
3512                 setIgnoreFormat(cmd.getArg(0), value);
3513                 break;
3514         }
3515
3516         default:
3517                 return false;
3518         }
3519
3520         if (code != NO_CODE
3521             && (cur.empty()
3522                 || !cur.inset().insetAllowed(code)
3523                 || (cur.paragraph().layout().pass_thru && !allow_in_passthru)))
3524                 enable = false;
3525
3526         flag.setEnabled(enable);
3527         return true;
3528 }
3529
3530
3531 void Text::pasteString(Cursor & cur, docstring const & clip,
3532                 bool asParagraphs)
3533 {
3534         if (!clip.empty()) {
3535                 cur.recordUndo();
3536                 if (asParagraphs)
3537                         insertStringAsParagraphs(cur, clip, cur.current_font);
3538                 else
3539                         insertStringAsLines(cur, clip, cur.current_font);
3540         }
3541 }
3542
3543
3544 // FIXME: an item inset would make things much easier.
3545 bool Text::inDescriptionItem(Cursor & cur) const
3546 {
3547         Paragraph & par = cur.paragraph();
3548         pos_type const pos = cur.pos();
3549         pos_type const body_pos = par.beginOfBody();
3550
3551         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
3552             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
3553                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
3554                 return false;
3555
3556         return (pos < body_pos
3557                 || (pos == body_pos
3558                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
3559 }
3560
3561
3562 std::vector<docstring> Text::getFreeFonts() const
3563 {
3564         vector<docstring> ffList;
3565
3566         FontStack::const_iterator cit = freeFonts.begin();
3567         FontStack::const_iterator end = freeFonts.end();
3568         for (; cit != end; ++cit)
3569                 // we do not use cit-> here because gcc 2.9x does not
3570                 // like it (JMarc)
3571                 ffList.push_back((*cit).first);
3572
3573         return ffList;
3574 }
3575
3576 } // namespace lyx