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