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