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