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