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