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