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