]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
83a6430608f0adce2e1d947c6a8d681e46ad4e68
[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 "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyXFunc.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "paragraph_funcs.h"
45 #include "ParagraphParameters.h"
46 #include "TextClass.h"
47 #include "TextMetrics.h"
48 #include "VSpace.h"
49
50 #include "frontends/Application.h"
51 #include "frontends/Clipboard.h"
52 #include "frontends/LyXView.h"
53 #include "frontends/Selection.h"
54 #include "frontends/WorkArea.h"
55
56 #include "insets/InsetCollapsable.h"
57 #include "insets/InsetCommand.h"
58 #include "insets/InsetExternal.h"
59 #include "insets/InsetFloatList.h"
60 #include "insets/InsetGraphics.h"
61 #include "insets/InsetGraphicsParams.h"
62 #include "insets/InsetNewline.h"
63 #include "insets/InsetQuotes.h"
64 #include "insets/InsetSpecialChar.h"
65 #include "insets/InsetText.h"
66
67 #include "support/convert.h"
68 #include "support/debug.h"
69 #include "support/gettext.h"
70 #include "support/lstrings.h"
71 #include "support/lyxtime.h"
72 #include "support/os.h"
73
74 #include "mathed/InsetMathHull.h"
75 #include "mathed/MathMacroTemplate.h"
76
77 #include <boost/next_prior.hpp>
78
79 #include <clocale>
80 #include <sstream>
81
82 using namespace std;
83 using namespace lyx::support;
84
85 namespace lyx {
86
87 using cap::copySelection;
88 using cap::cutSelection;
89 using cap::pasteFromStack;
90 using cap::pasteClipboardText;
91 using cap::pasteClipboardGraphics;
92 using cap::replaceSelection;
93 using cap::grabAndEraseSelection;
94 using cap::selClearOrDel;
95
96 // globals...
97 static Font freefont(ignore_font, ignore_language);
98 static bool toggleall = false;
99
100 static void toggleAndShow(Cursor & cur, Text * text,
101         Font const & font, bool toggleall = true)
102 {
103         text->toggleFree(cur, font, toggleall);
104
105         if (font.language() != ignore_language ||
106             font.fontInfo().number() != FONT_IGNORE) {
107                 TextMetrics const & tm = cur.bv().textMetrics(text);
108                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
109                                                        cur.real_current_font))
110                         text->setCursor(cur, cur.pit(), cur.pos(),
111                                         false, !cur.boundary());
112         }
113 }
114
115
116 static void moveCursor(Cursor & cur, bool selecting)
117 {
118         if (selecting || cur.mark())
119                 cur.setSelection();
120 }
121
122
123 static void finishChange(Cursor & cur, bool selecting)
124 {
125         cur.finishUndo();
126         moveCursor(cur, selecting);
127 }
128
129
130 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
131 {
132         cur.recordUndo();
133         docstring sel = cur.selectionAsString(false);
134
135         // It may happen that sel is empty but there is a selection
136         replaceSelection(cur);
137
138         // Is this a valid formula?
139         bool valid = true;
140
141         if (sel.empty()) {
142 #ifdef ENABLE_ASSERTIONS
143                 const int old_pos = cur.pos();
144 #endif
145                 cur.insert(new InsetMathHull(hullSimple));
146 #ifdef ENABLE_ASSERTIONS
147                 LASSERT(old_pos == cur.pos(), /**/);
148 #endif
149                 cur.nextInset()->edit(cur, true);
150                 // don't do that also for LFUN_MATH_MODE
151                 // unless you want end up with always changing
152                 // to mathrm when opening an inlined inset --
153                 // I really hate "LyXfunc overloading"...
154                 if (display)
155                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
156                 // Avoid an unnecessary undo step if cmd.argument
157                 // is empty
158                 if (!cmd.argument().empty())
159                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
160                                                  cmd.argument()));
161         } else {
162                 // create a macro if we see "\\newcommand"
163                 // somewhere, and an ordinary formula
164                 // otherwise
165                 if (sel.find(from_ascii("\\newcommand")) == string::npos
166                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
167                                 && sel.find(from_ascii("\\def")) == string::npos)
168                 {
169                         InsetMathHull * formula = new InsetMathHull;
170                         string const selstr = to_utf8(sel);
171                         istringstream is(selstr);
172                         Lexer lex;
173                         lex.setStream(is);
174                         if (!formula->readQuiet(lex)) {
175                                 // No valid formula, let's try with delims
176                                 is.str("$" + selstr + "$");
177                                 lex.setStream(is);
178                                 if (!formula->readQuiet(lex)) {
179                                         // Still not valid, leave it as is
180                                         valid = false;
181                                         delete formula;
182                                         cur.insert(sel);
183                                 } else
184                                         cur.insert(formula);
185                         } else
186                                 cur.insert(formula);
187                 } else {
188                         cur.insert(new MathMacroTemplate(sel));
189                 }
190         }
191         if (valid)
192                 cur.message(from_utf8(N_("Math editor mode")));
193         else
194                 cur.message(from_utf8(N_("No valid math formula")));
195 }
196
197
198 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
199 {
200         BOOST_ASSERT(cmd.action == LFUN_REGEXP_MODE);
201         if (cur.inRegexped()) {
202                 cur.message(_("Already in regexp mode"));
203                 return;
204         }
205         cur.recordUndo();
206         docstring const save_selection = grabAndEraseSelection(cur);
207         selClearOrDel(cur);
208         // replaceSelection(cur);
209
210         cur.insert(new InsetMathHull(hullRegexp));
211         cur.nextInset()->edit(cur, true);
212         cur.niceInsert(save_selection);
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 bool doInsertInset(Cursor & cur, Text * text,
228         FuncRequest const & cmd, bool edit, bool pastesel)
229 {
230         Buffer & buffer = cur.bv().buffer();
231         BufferParams const & bparams = buffer.params();
232         Inset * inset = createInset(buffer, cmd);
233         if (!inset)
234                 return false;
235
236         if (InsetCollapsable * ci = inset->asInsetCollapsable())
237                 ci->setButtonLabel();
238
239         cur.recordUndo();
240         if (cmd.action == LFUN_INDEX_INSERT) {
241                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
242                 text->insertInset(cur, inset);
243                 if (edit)
244                         inset->edit(cur, true);
245                 // Now put this into inset
246                 cur.text()->insertStringAsLines(cur, ds);
247                 cur.leaveInset(*inset);
248                 return true;
249         }
250
251         bool gotsel = false;
252         if (cur.selection()) {
253                 cutSelection(cur, false, pastesel);
254                 cur.clearSelection();
255                 gotsel = true;
256         }
257         text->insertInset(cur, inset);
258
259         if (edit)
260                 inset->edit(cur, true);
261
262         if (!gotsel || !pastesel)
263                 return true;
264
265         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
266         cur.buffer()->errors("Paste");
267         cur.clearSelection(); // bug 393
268         cur.finishUndo();
269         InsetText * insetText = dynamic_cast<InsetText *>(inset);
270         if (insetText && (!insetText->allowMultiPar() || cur.lastpit() == 0)) {
271                 // reset first par to default
272                 cur.text()->paragraphs().begin()
273                         ->setPlainOrDefaultLayout(bparams.documentClass());
274                 cur.pos() = 0;
275                 cur.pit() = 0;
276                 // Merge multiple paragraphs -- hack
277                 while (cur.lastpit() > 0)
278                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
279                 cur.leaveInset(*inset);
280         } else {
281                 cur.leaveInset(*inset);
282                 // reset surrounding par to default
283                 DocumentClass const & dc = bparams.documentClass();
284                 docstring const layoutname = inset->usePlainLayout()
285                         ? dc.plainLayoutName()
286                         : dc.defaultLayoutName();
287                 text->setLayout(cur, layoutname);
288         }
289
290         return true;
291 }
292
293
294 string const freefont2string()
295 {
296         return freefont.toString(toggleall);
297 }
298
299
300 static void dragMove(Cursor & cur, int moveid, int movetoid)
301 {
302         // Create pointers to buffers
303         Buffer & buf_move = *cur.buffer();
304         DocIterator dit_move = buf_move.getParFromID(moveid);
305         DocIterator dit_dest = buf_move.getParFromID(movetoid);
306
307         pit_type & pit_move = dit_move.pit();
308         pit_type & pit_dest = dit_dest.pit();
309         ParagraphList & pars = dit_move.text()->paragraphs();
310
311         // Create references to the paragraphs to be moved
312         ParagraphList::iterator const bgn = pars.begin();
313         ParagraphList::iterator dest_start = boost::next(bgn, pit_dest);
314
315         // The first paragraph of the area to be copied:
316         ParagraphList::iterator start = boost::next(bgn, pit_move);
317         // The final paragraph of area to be copied:
318         ParagraphList::iterator finish = start;
319         ParagraphList::iterator const end = pars.end();
320
321         // Move out (down) from this section header
322         if (finish != end)
323                 ++finish;
324
325         // Seek the one (on same level) below
326         int const thistoclevel = start->layout().toclevel;
327         for (; finish != end; ++finish) {
328                 int const toclevel = finish->layout().toclevel;
329                 if (toclevel != Layout::NOT_IN_TOC
330                     && toclevel <= thistoclevel)
331                         break;
332         }
333
334         if (start == pars.begin() || start == dest_start)
335                 // Nothing to move
336                 return;
337
338         pars.insert(dest_start, start, finish);
339         pars.erase(start, finish);
340
341         // FIXME: This only really needs doing for the newly
342         // introduced paragraphs. Something like:
343         //      pit_type const numpars = distance(start, finish);
344         //      start = boost::next(bgn, pit);
345         //      finish = boost::next(start, numpars);
346         //      for (; start != finish; ++start)
347         //              start->setBuffer(buf);
348         // But while this seems to work, it is kind of fragile.
349         buf_move.inset().setBuffer(buf_move);
350 }
351
352
353 /// the type of outline operation
354 enum OutlineOp {
355         OutlineUp, // Move this header with text down
356         OutlineDown,   // Move this header with text up
357         OutlineIn, // Make this header deeper
358         OutlineOut // Make this header shallower
359 };
360
361
362 static void outline(OutlineOp mode, Cursor & cur)
363 {
364         Buffer & buf = *cur.buffer();
365         pit_type & pit = cur.pit();
366         ParagraphList & pars = buf.text().paragraphs();
367         ParagraphList::iterator const bgn = pars.begin();
368         // The first paragraph of the area to be copied:
369         ParagraphList::iterator start = boost::next(bgn, pit);
370         // The final paragraph of area to be copied:
371         ParagraphList::iterator finish = start;
372         ParagraphList::iterator const end = pars.end();
373
374         DocumentClass const & tc = buf.params().documentClass();
375
376         int const thistoclevel = start->layout().toclevel;
377         int toclevel;
378
379         // Move out (down) from this section header
380         if (finish != end)
381                 ++finish;
382
383         // Seek the one (on same level) below
384         for (; finish != end; ++finish) {
385                 toclevel = finish->layout().toclevel;
386                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
387                         break;
388         }
389
390         // Do we need to set insets' buffer_ members, because we copied
391         // some stuff? We'll assume we do and reset it otherwise.
392         bool set_buffers = true;
393
394         switch (mode) {
395                 case OutlineUp: {
396                         if (start == pars.begin())
397                                 // Nothing to move.
398                                 return;
399                         ParagraphList::iterator dest = start;
400                         // Move out (up) from this header
401                         if (dest == bgn)
402                                 return;
403                         // Search previous same-level header above
404                         do {
405                                 --dest;
406                                 toclevel = dest->layout().toclevel;
407                         } while(dest != bgn
408                                 && (toclevel == Layout::NOT_IN_TOC
409                                     || toclevel > thistoclevel));
410                         // Not found; do nothing
411                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
412                                 return;
413                         pit_type const newpit = distance(bgn, dest);
414                         pit_type const len = distance(start, finish);
415                         pit_type const deletepit = pit + len;
416                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
417                         pars.insert(dest, start, finish);
418                         start = boost::next(pars.begin(), deletepit);
419                         pit = newpit;
420                         pars.erase(start, finish);
421                         break;
422                 }
423                 case OutlineDown: {
424                         if (finish == end)
425                                 // Nothing to move.
426                                 return;
427                         // Go one down from *this* header:
428                         ParagraphList::iterator dest = boost::next(finish, 1);
429                         // Go further down to find header to insert in front of:
430                         for (; dest != end; ++dest) {
431                                 toclevel = dest->layout().toclevel;
432                                 if (toclevel != Layout::NOT_IN_TOC
433                                       && toclevel <= thistoclevel)
434                                         break;
435                         }
436                         // One such was found:
437                         pit_type newpit = distance(bgn, dest);
438                         pit_type const len = distance(start, finish);
439                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
440                         pars.insert(dest, start, finish);
441                         start = boost::next(bgn, pit);
442                         pit = newpit - len;
443                         pars.erase(start, finish);
444                         break;
445                 }
446                 case OutlineIn: {
447                         pit_type const len = distance(start, finish);
448                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
449                         for (; start != finish; ++start) {
450                                 toclevel = start->layout().toclevel;
451                                 if (toclevel == Layout::NOT_IN_TOC)
452                                         continue;
453                                 DocumentClass::const_iterator lit = tc.begin();
454                                 DocumentClass::const_iterator len = tc.end();
455                                 for (; lit != len; ++lit) {
456                                         if (lit->toclevel == toclevel + 1 &&
457                                             start->layout().labeltype == lit->labeltype) {
458                                                 start->setLayout(*lit);
459                                                 break;
460                                         }
461                                 }
462                         }
463                         set_buffers = false;
464                         break;
465                 }
466                 case OutlineOut: {
467                         pit_type const len = distance(start, finish);
468                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
469                         for (; start != finish; ++start) {
470                                 toclevel = start->layout().toclevel;
471                                 if (toclevel == Layout::NOT_IN_TOC)
472                                         continue;
473                                 DocumentClass::const_iterator lit = tc.begin();
474                                 DocumentClass::const_iterator len = tc.end();
475                                 for (; lit != len; ++lit) {
476                                         if (lit->toclevel == toclevel - 1 &&
477                                                 start->layout().labeltype == lit->labeltype) {
478                                                         start->setLayout(*lit);
479                                                         break;
480                                         }
481                                 }
482                         }
483                         set_buffers = false;
484                         break;
485                 }
486         }
487         if (set_buffers)
488                 // FIXME This only really needs doing for the newly introduced 
489                 // paragraphs. Something like:
490                 //      pit_type const numpars = distance(start, finish);
491                 //      start = boost::next(bgn, pit);
492                 //      finish = boost::next(start, numpars);
493                 //      for (; start != finish; ++start)
494                 //              start->setBuffer(buf);
495                 // But while this seems to work, it is kind of fragile.
496                 buf.inset().setBuffer(buf);
497 }
498
499
500 void Text::number(Cursor & cur)
501 {
502         FontInfo font = ignore_font;
503         font.setNumber(FONT_TOGGLE);
504         toggleAndShow(cur, this, Font(font, ignore_language));
505 }
506
507
508 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
509 {
510         return par.isRTL(buffer.params());
511 }
512
513
514 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
515 {
516         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
517
518         // Dispatch if the cursor is inside the text. It is not the
519         // case for context menus (bug 5797).
520         if (cur.text() != this) {
521                 cur.undispatched();
522                 return;
523         }
524
525         BufferView * bv = &cur.bv();
526         TextMetrics * tm = &bv->textMetrics(this);
527         if (!tm->contains(cur.pit())) {
528                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
529                 tm = &bv->textMetrics(this);
530         }
531
532         // FIXME: We use the update flag to indicates wether a singlePar or a
533         // full screen update is needed. We reset it here but shall we restore it
534         // at the end?
535         cur.noUpdate();
536
537         LASSERT(cur.text() == this, /**/);
538         CursorSlice oldTopSlice = cur.top();
539         bool oldBoundary = cur.boundary();
540         bool sel = cur.selection();
541         // Signals that, even if needsUpdate == false, an update of the
542         // cursor paragraph is required
543         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
544                 LyXAction::SingleParUpdate);
545         // Signals that a full-screen update is required
546         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
547                 LyXAction::NoUpdate) || singleParUpdate);
548
549         switch (cmd.action) {
550
551         case LFUN_PARAGRAPH_MOVE_DOWN: {
552                 pit_type const pit = cur.pit();
553                 recUndo(cur, pit, pit + 1);
554                 cur.finishUndo();
555                 swap(pars_[pit], pars_[pit + 1]);
556                 cur.buffer()->updateLabels();
557                 needsUpdate = true;
558                 ++cur.pit();
559                 break;
560         }
561
562         case LFUN_PARAGRAPH_MOVE_UP: {
563                 pit_type const pit = cur.pit();
564                 recUndo(cur, pit - 1, pit);
565                 cur.finishUndo();
566                 swap(pars_[pit], pars_[pit - 1]);
567                 cur.buffer()->updateLabels();
568                 --cur.pit();
569                 needsUpdate = true;
570                 break;
571         }
572
573         case LFUN_APPENDIX: {
574                 Paragraph & par = cur.paragraph();
575                 bool start = !par.params().startOfAppendix();
576
577 // FIXME: The code below only makes sense at top level.
578 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
579                 // ensure that we have only one start_of_appendix in this document
580                 // FIXME: this don't work for multipart document!
581                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
582                         if (pars_[tmp].params().startOfAppendix()) {
583                                 recUndo(cur, tmp);
584                                 pars_[tmp].params().startOfAppendix(false);
585                                 break;
586                         }
587                 }
588
589                 cur.recordUndo();
590                 par.params().startOfAppendix(start);
591
592                 // we can set the refreshing parameters now
593                 cur.buffer()->updateLabels();
594                 break;
595         }
596
597         case LFUN_WORD_DELETE_FORWARD:
598                 if (cur.selection())
599                         cutSelection(cur, true, false);
600                 else
601                         deleteWordForward(cur);
602                 finishChange(cur, false);
603                 break;
604
605         case LFUN_WORD_DELETE_BACKWARD:
606                 if (cur.selection())
607                         cutSelection(cur, true, false);
608                 else
609                         deleteWordBackward(cur);
610                 finishChange(cur, false);
611                 break;
612
613         case LFUN_LINE_DELETE:
614                 if (cur.selection())
615                         cutSelection(cur, true, false);
616                 else
617                         tm->deleteLineForward(cur);
618                 finishChange(cur, false);
619                 break;
620
621         case LFUN_BUFFER_BEGIN:
622         case LFUN_BUFFER_BEGIN_SELECT:
623                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
624                 if (cur.depth() == 1)
625                         needsUpdate |= cursorTop(cur);
626                 else
627                         cur.undispatched();
628                 cur.updateFlags(Update::FitCursor);
629                 break;
630
631         case LFUN_BUFFER_END:
632         case LFUN_BUFFER_END_SELECT:
633                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
634                 if (cur.depth() == 1)
635                         needsUpdate |= cursorBottom(cur);
636                 else
637                         cur.undispatched();
638                 cur.updateFlags(Update::FitCursor);
639                 break;
640
641         case LFUN_INSET_BEGIN:
642         case LFUN_INSET_BEGIN_SELECT:
643                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_BEGIN_SELECT);
644                 if (cur.depth() == 1 || cur.pos() > 0)
645                         needsUpdate |= cursorTop(cur);
646                 else
647                         cur.undispatched();
648                 cur.updateFlags(Update::FitCursor);
649                 break;
650
651         case LFUN_INSET_END:
652         case LFUN_INSET_END_SELECT:
653                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_END_SELECT);
654                 if (cur.depth() == 1 || cur.pos() < cur.lastpos())
655                         needsUpdate |= cursorBottom(cur);
656                 else
657                         cur.undispatched();
658                 cur.updateFlags(Update::FitCursor);
659                 break;
660
661         case LFUN_CHAR_FORWARD:
662         case LFUN_CHAR_FORWARD_SELECT:
663                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
664                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
665                 needsUpdate |= cursorForward(cur);
666
667                 if (!needsUpdate && oldTopSlice == cur.top()
668                                 && cur.boundary() == oldBoundary) {
669                         cur.undispatched();
670                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
671                 
672                         // we will probably be moving out the inset, so we should execute
673                         // the depm-mechanism, but only when the cursor has a place to 
674                         // go outside this inset, i.e. in a slice above.
675                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
676                                   && cur.pit() == cur.lastpit()) {
677                                 // The cursor hasn't changed yet. To give the 
678                                 // DEPM the possibility of doing something we must
679                                 // provide it with two different cursors.
680                                 Cursor dummy = cur;
681                                 dummy.pos() = dummy.pit() = 0;
682                                 cur.bv().checkDepm(dummy, cur);
683                         }
684                 }
685                 break;
686
687         case LFUN_CHAR_BACKWARD:
688         case LFUN_CHAR_BACKWARD_SELECT:
689                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
690                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
691                 needsUpdate |= cursorBackward(cur);
692
693                 if (!needsUpdate && oldTopSlice == cur.top()
694                         && cur.boundary() == oldBoundary) {
695                         cur.undispatched();
696                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
697
698                         // we will probably be moving out the inset, so we should execute
699                         // the depm-mechanism, but only when the cursor has a place to 
700                         // go outside this inset, i.e. in a slice above.
701                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
702                                 // The cursor hasn't changed yet. To give the 
703                                 // DEPM the possibility of doing something we must
704                                 // provide it with two different cursors.
705                                 Cursor dummy = cur;
706                                 dummy.pos() = cur.lastpos();
707                                 dummy.pit() = cur.lastpit();
708                                 cur.bv().checkDepm(dummy, cur);
709                         }
710                 }
711                 break;
712
713         case LFUN_CHAR_LEFT:
714         case LFUN_CHAR_LEFT_SELECT:
715                 if (lyxrc.visual_cursor) {
716                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
717                         needsUpdate |= cursorVisLeft(cur);
718                         if (!needsUpdate && oldTopSlice == cur.top()
719                                         && cur.boundary() == oldBoundary) {
720                                 cur.undispatched();
721                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
722                         }
723                 } else {
724                         if (reverseDirectionNeeded(cur)) {
725                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
726                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
727                         } else {
728                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
729                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
730                         }
731                         dispatch(cur, cmd);
732                         return;
733                 }
734                 break;
735
736         case LFUN_CHAR_RIGHT:
737         case LFUN_CHAR_RIGHT_SELECT:
738                 if (lyxrc.visual_cursor) {
739                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
740                         needsUpdate |= cursorVisRight(cur);
741                         if (!needsUpdate && oldTopSlice == cur.top()
742                                         && cur.boundary() == oldBoundary) {
743                                 cur.undispatched();
744                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
745                         }
746                 } else {
747                         if (reverseDirectionNeeded(cur)) {
748                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
749                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
750                         } else {
751                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
752                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
753                         }
754                         dispatch(cur, cmd);
755                         return;
756                 }
757                 break;
758
759
760         case LFUN_UP_SELECT:
761         case LFUN_DOWN_SELECT:
762         case LFUN_UP:
763         case LFUN_DOWN: {
764                 // stop/start the selection
765                 bool select = cmd.action == LFUN_DOWN_SELECT ||
766                         cmd.action == LFUN_UP_SELECT;
767
768                 // move cursor up/down
769                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
770                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
771
772                 if (!atFirstOrLastRow) {
773                         needsUpdate |= cur.selHandle(select);   
774                         cur.selHandle(select);
775                         cur.upDownInText(up, needsUpdate);
776                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
777                 } else {
778                         // if the cursor cannot be moved up or down do not remove
779                         // the selection right now, but wait for the next dispatch.
780                         if (select)
781                                 needsUpdate |= cur.selHandle(select);   
782                         cur.upDownInText(up, needsUpdate);
783                         cur.undispatched();
784                 }
785
786                 break;
787         }
788
789         case LFUN_PARAGRAPH_UP:
790         case LFUN_PARAGRAPH_UP_SELECT:
791                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
792                 needsUpdate |= cursorUpParagraph(cur);
793                 break;
794
795         case LFUN_PARAGRAPH_DOWN:
796         case LFUN_PARAGRAPH_DOWN_SELECT:
797                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
798                 needsUpdate |= cursorDownParagraph(cur);
799                 break;
800
801         case LFUN_LINE_BEGIN:
802         case LFUN_LINE_BEGIN_SELECT:
803                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
804                 needsUpdate |= tm->cursorHome(cur);
805                 break;
806
807         case LFUN_LINE_END:
808         case LFUN_LINE_END_SELECT:
809                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
810                 needsUpdate |= tm->cursorEnd(cur);
811                 break;
812
813         case LFUN_SECTION_SELECT: {
814                 Buffer const & buf = *cur.buffer();
815                 pit_type const pit = cur.pit();
816                 ParagraphList & pars = buf.text().paragraphs();
817                 ParagraphList::iterator bgn = pars.begin();
818                 // The first paragraph of the area to be selected:
819                 ParagraphList::iterator start = boost::next(bgn, pit);
820                 // The final paragraph of area to be selected:
821                 ParagraphList::iterator finish = start;
822                 ParagraphList::iterator end = pars.end();
823
824                 int const thistoclevel = start->layout().toclevel;
825                 if (thistoclevel == Layout::NOT_IN_TOC)
826                         break;
827
828                 cur.pos() = 0;
829                 Cursor const old_cur = cur;
830                 needsUpdate |= cur.selHandle(true);
831
832                 // Move out (down) from this section header
833                 if (finish != end)
834                         ++finish;
835
836                 // Seek the one (on same level) below
837                 for (; finish != end; ++finish, ++cur.pit()) {
838                         int const toclevel = finish->layout().toclevel;
839                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
840                                 break;
841                 }
842                 cur.pos() = cur.lastpos();
843                 
844                 needsUpdate |= cur != old_cur;
845                 break;
846         }
847
848         case LFUN_WORD_RIGHT:
849         case LFUN_WORD_RIGHT_SELECT:
850                 if (lyxrc.visual_cursor) {
851                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_RIGHT_SELECT);
852                         needsUpdate |= cursorVisRightOneWord(cur);
853                         if (!needsUpdate && oldTopSlice == cur.top()
854                                         && cur.boundary() == oldBoundary) {
855                                 cur.undispatched();
856                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
857                         }
858                 } else {
859                         if (reverseDirectionNeeded(cur)) {
860                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
861                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
862                         } else {
863                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
864                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
865                         }
866                         dispatch(cur, cmd);
867                         return;
868                 }
869                 break;
870
871         case LFUN_WORD_FORWARD:
872         case LFUN_WORD_FORWARD_SELECT:
873                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
874                 needsUpdate |= cursorForwardOneWord(cur);
875                 break;
876
877         case LFUN_WORD_LEFT:
878         case LFUN_WORD_LEFT_SELECT:
879                 if (lyxrc.visual_cursor) {
880                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_LEFT_SELECT);
881                         needsUpdate |= cursorVisLeftOneWord(cur);
882                         if (!needsUpdate && oldTopSlice == cur.top()
883                                         && cur.boundary() == oldBoundary) {
884                                 cur.undispatched();
885                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
886                         }
887                 } else {
888                         if (reverseDirectionNeeded(cur)) {
889                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
890                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
891                         } else {
892                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
893                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
894                         }
895                         dispatch(cur, cmd);
896                         return;
897                 }
898                 break;
899
900         case LFUN_WORD_BACKWARD:
901         case LFUN_WORD_BACKWARD_SELECT:
902                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
903                 needsUpdate |= cursorBackwardOneWord(cur);
904                 break;
905
906         case LFUN_WORD_SELECT: {
907                 selectWord(cur, WHOLE_WORD);
908                 finishChange(cur, true);
909                 break;
910         }
911
912         case LFUN_NEWLINE_INSERT: {
913                 InsetNewlineParams inp;
914                 docstring arg = cmd.argument();
915                 // this avoids a double undo
916                 // FIXME: should not be needed, ideally
917                 if (!cur.selection())
918                         cur.recordUndo();
919                 cap::replaceSelection(cur);
920                 if (arg == "linebreak")
921                         inp.kind = InsetNewlineParams::LINEBREAK;
922                 else
923                         inp.kind = InsetNewlineParams::NEWLINE;
924                 cur.insert(new InsetNewline(inp));
925                 cur.posForward();
926                 moveCursor(cur, false);
927                 break;
928         }
929
930         case LFUN_TAB_INSERT: {
931                 bool const multi_par_selection = cur.selection() &&
932                         cur.selBegin().pit() != cur.selEnd().pit();
933                 if (multi_par_selection) {
934                         // If there is a multi-paragraph selection, a tab is inserted
935                         // at the beginning of each paragraph.
936                         cur.recordUndoSelection();
937                         pit_type const pit_end = cur.selEnd().pit();
938                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
939                                 pars_[pit].insertChar(0, '\t', 
940                                                       bv->buffer().params().trackChanges);
941                                 // Update the selection pos to make sure the selection does not
942                                 // change as the inserted tab will increase the logical pos.
943                                 if (cur.anchor_.pit() == pit)
944                                         cur.anchor_.forwardPos();
945                                 if (cur.pit() == pit)
946                                         cur.forwardPos();
947                         }
948                         cur.finishUndo();
949                 } else {
950                         // Maybe we shouldn't allow tabs within a line, because they
951                         // are not (yet) aligned as one might do expect.
952                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
953                         dispatch(cur, cmd);     
954                 }
955                 break;
956         }
957
958         case LFUN_TAB_DELETE: {
959                 bool const tc = bv->buffer().params().trackChanges;
960                 if (cur.selection()) {
961                         // If there is a selection, a tab (if present) is removed from
962                         // the beginning of each paragraph.
963                         cur.recordUndoSelection();
964                         pit_type const pit_end = cur.selEnd().pit();
965                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
966                                 Paragraph & par = paragraphs()[pit];
967                                 if (par.getChar(0) == '\t') {
968                                         if (cur.pit() == pit)
969                                                 cur.posBackward();
970                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
971                                                 cur.anchor_.backwardPos();
972                                         
973                                         par.eraseChar(0, tc);
974                                 } else 
975                                         // If no tab was present, try to remove up to four spaces.
976                                         for (int n_spaces = 0;
977                                              par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
978                                                 if (cur.pit() == pit)
979                                                         cur.posBackward();
980                                                 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
981                                                         cur.anchor_.backwardPos();
982                                                 
983                                                 par.eraseChar(0, tc);
984                                         }
985                         }
986                         cur.finishUndo();
987                 } else {
988                         // If there is no selection, try to remove a tab or some spaces 
989                         // before the position of the cursor.
990                         Paragraph & par = paragraphs()[cur.pit()];
991                         pos_type const pos = cur.pos();
992                         
993                         if (pos == 0)
994                                 break;
995                         
996                         char_type const c = par.getChar(pos - 1);
997                         cur.recordUndo();
998                         if (c == '\t') {
999                                 cur.posBackward();
1000                                 par.eraseChar(cur.pos(), tc);
1001                         } else
1002                                 for (int n_spaces = 0; 
1003                                      cur.pos() > 0
1004                                              && par.getChar(cur.pos() - 1) == ' ' 
1005                                              && n_spaces < 4;
1006                                      ++n_spaces) {
1007                                         cur.posBackward();
1008                                         par.eraseChar(cur.pos(), tc);
1009                                 }
1010                         cur.finishUndo();
1011                 }
1012                 break;
1013         }
1014
1015         case LFUN_CHAR_DELETE_FORWARD:
1016                 if (!cur.selection()) {
1017                         if (cur.pos() == cur.paragraph().size())
1018                                 // Par boundary, force full-screen update
1019                                 singleParUpdate = false;
1020                         needsUpdate |= erase(cur);
1021                         cur.resetAnchor();
1022                         // It is possible to make it a lot faster still
1023                         // just comment out the line below...
1024                 } else {
1025                         cutSelection(cur, true, false);
1026                         singleParUpdate = false;
1027                 }
1028                 moveCursor(cur, false);
1029                 break;
1030
1031         case LFUN_CHAR_DELETE_BACKWARD:
1032                 if (!cur.selection()) {
1033                         if (bv->getIntl().getTransManager().backspace()) {
1034                                 // Par boundary, full-screen update
1035                                 if (cur.pos() == 0)
1036                                         singleParUpdate = false;
1037                                 needsUpdate |= backspace(cur);
1038                                 cur.resetAnchor();
1039                                 // It is possible to make it a lot faster still
1040                                 // just comment out the line below...
1041                         }
1042                 } else {
1043                         cutSelection(cur, true, false);
1044                         singleParUpdate = false;
1045                 }
1046                 break;
1047
1048         case LFUN_BREAK_PARAGRAPH:
1049                 cap::replaceSelection(cur);
1050                 breakParagraph(cur, cmd.argument() == "inverse");
1051                 cur.resetAnchor();
1052                 break;
1053
1054         case LFUN_INSET_INSERT: {
1055                 cur.recordUndo();
1056
1057                 // We have to avoid triggering InstantPreview loading
1058                 // before inserting into the document. See bug #5626.
1059                 bool loaded = bv->buffer().isFullyLoaded();
1060                 bv->buffer().setFullyLoaded(false);
1061                 Inset * inset = createInset(bv->buffer(), cmd);
1062                 bv->buffer().setFullyLoaded(loaded);
1063
1064                 if (inset) {
1065                         // FIXME (Abdel 01/02/2006):
1066                         // What follows would be a partial fix for bug 2154:
1067                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
1068                         // This automatically put the label inset _after_ a
1069                         // numbered section. It should be possible to extend the mechanism
1070                         // to any kind of LateX environement.
1071                         // The correct way to fix that bug would be at LateX generation.
1072                         // I'll let the code here for reference as it could be used for some
1073                         // other feature like "automatic labelling".
1074                         /*
1075                         Paragraph & par = pars_[cur.pit()];
1076                         if (inset->lyxCode() == LABEL_CODE
1077                                 && par.layout().labeltype == LABEL_COUNTER) {
1078                                 // Go to the end of the paragraph
1079                                 // Warning: Because of Change-Tracking, the last
1080                                 // position is 'size()' and not 'size()-1':
1081                                 cur.pos() = par.size();
1082                                 // Insert a new paragraph
1083                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1084                                 dispatch(cur, fr);
1085                         }
1086                         */
1087                         if (cur.selection())
1088                                 cutSelection(cur, true, false);
1089                         cur.insert(inset);
1090                         cur.posForward();
1091
1092                         // trigger InstantPreview now
1093                         if (inset->lyxCode() == EXTERNAL_CODE) {
1094                                 InsetExternal & ins =
1095                                         static_cast<InsetExternal &>(*inset);
1096                                 ins.updatePreview();
1097                         }
1098                 }
1099
1100                 break;
1101         }
1102
1103         case LFUN_INSET_DISSOLVE: {
1104                 // first, try if there's an inset at cursor
1105                 // FIXME: this first part should be moved to
1106                 // a LFUN_NEXT_INSET_DISSOLVE, or be called via
1107                 // some generic "next-inset inset-dissolve"
1108                 Inset * inset = cur.nextInset();
1109                 if (inset && inset->isActive()) {
1110                         Cursor tmpcur = cur;
1111                         tmpcur.pushBackward(*inset);
1112                         inset->dispatch(tmpcur, cmd);
1113                         if (tmpcur.result().dispatched()) {
1114                                 cur.dispatched();
1115                                 break;
1116                         }
1117                 }
1118                 // if it did not work, try the underlying inset
1119                 if (dissolveInset(cur)) {
1120                         needsUpdate = true;
1121                         break;
1122                 }
1123                 // if it did not work, do nothing.
1124                 break;
1125         }
1126
1127         case LFUN_SET_GRAPHICS_GROUP: {
1128                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1129                 if (!ins)
1130                         break;
1131
1132                 cur.recordUndo();
1133
1134                 string id = to_utf8(cmd.argument());
1135                 string grp = graphics::getGroupParams(bv->buffer(), id);
1136                 InsetGraphicsParams tmp, inspar = ins->getParams();
1137
1138                 if (id.empty())
1139                         inspar.groupId = to_utf8(cmd.argument());
1140                 else {
1141                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1142                         tmp.filename = inspar.filename;
1143                         inspar = tmp;
1144                 }
1145
1146                 ins->setParams(inspar);
1147         }
1148
1149         case LFUN_SPACE_INSERT:
1150                 if (cur.paragraph().layout().free_spacing)
1151                         insertChar(cur, ' ');
1152                 else {
1153                         doInsertInset(cur, this, cmd, false, false);
1154                         cur.posForward();
1155                 }
1156                 moveCursor(cur, false);
1157                 break;
1158
1159         case LFUN_SPECIALCHAR_INSERT: {
1160                 string const name = to_utf8(cmd.argument());
1161                 if (name == "hyphenation")
1162                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1163                 else if (name == "ligature-break")
1164                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1165                 else if (name == "slash")
1166                         specialChar(cur, InsetSpecialChar::SLASH);
1167                 else if (name == "nobreakdash")
1168                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1169                 else if (name == "dots")
1170                         specialChar(cur, InsetSpecialChar::LDOTS);
1171                 else if (name == "end-of-sentence")
1172                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1173                 else if (name == "menu-separator")
1174                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1175                 else if (name.empty())
1176                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1177                 else
1178                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1179                 break;
1180         }
1181
1182         case LFUN_WORD_UPCASE:
1183                 changeCase(cur, text_uppercase);
1184                 break;
1185
1186         case LFUN_WORD_LOWCASE:
1187                 changeCase(cur, text_lowercase);
1188                 break;
1189
1190         case LFUN_WORD_CAPITALIZE:
1191                 changeCase(cur, text_capitalization);
1192                 break;
1193
1194         case LFUN_CHARS_TRANSPOSE:
1195                 charsTranspose(cur);
1196                 break;
1197
1198         case LFUN_PASTE: {
1199                 cur.message(_("Paste"));
1200                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1201                 cap::replaceSelection(cur);
1202
1203                 // without argument?
1204                 string const arg = to_utf8(cmd.argument());
1205                 if (arg.empty()) {
1206                         if (theClipboard().isInternal())
1207                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1208                         else if (theClipboard().hasGraphicsContents() 
1209                                      && !theClipboard().hasTextContents())
1210                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1211                         else
1212                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1213                 } else if (isStrUnsignedInt(arg)) {
1214                         // we have a numerical argument
1215                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1216                                        convert<unsigned int>(arg));
1217                 } else {
1218                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1219                         if (arg == "pdf")
1220                                 type = Clipboard::PdfGraphicsType;
1221                         else if (arg == "png")
1222                                 type = Clipboard::PngGraphicsType;
1223                         else if (arg == "jpeg")
1224                                 type = Clipboard::JpegGraphicsType;
1225                         else if (arg == "linkback")
1226                                 type = Clipboard::LinkBackGraphicsType;
1227                         else if (arg == "emf")
1228                                 type = Clipboard::EmfGraphicsType;
1229                         else if (arg == "wmf")
1230                                 type = Clipboard::WmfGraphicsType;
1231
1232                         else
1233                                 LASSERT(false, /**/);
1234
1235                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1236                 }
1237
1238                 bv->buffer().errors("Paste");
1239                 cur.clearSelection(); // bug 393
1240                 cur.finishUndo();
1241                 break;
1242         }
1243
1244         case LFUN_CUT:
1245                 cutSelection(cur, true, true);
1246                 cur.message(_("Cut"));
1247                 break;
1248
1249         case LFUN_COPY:
1250                 copySelection(cur);
1251                 cur.message(_("Copy"));
1252                 break;
1253
1254         case LFUN_SERVER_GET_XY:
1255                 cur.message(from_utf8(
1256                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1257                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1258                 break;
1259
1260         case LFUN_SERVER_SET_XY: {
1261                 int x = 0;
1262                 int y = 0;
1263                 istringstream is(to_utf8(cmd.argument()));
1264                 is >> x >> y;
1265                 if (!is)
1266                         lyxerr << "SETXY: Could not parse coordinates in '"
1267                                << to_utf8(cmd.argument()) << endl;
1268                 else
1269                         tm->setCursorFromCoordinates(cur, x, y);
1270                 break;
1271         }
1272
1273         case LFUN_SERVER_GET_LAYOUT:
1274                 cur.message(cur.paragraph().layout().name());
1275                 break;
1276
1277         case LFUN_LAYOUT: {
1278                 docstring layout = cmd.argument();
1279                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1280
1281                 Paragraph const & para = cur.paragraph();
1282                 docstring const old_layout = para.layout().name();
1283                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1284
1285                 if (layout.empty())
1286                         layout = tclass.defaultLayoutName();
1287
1288                 if (para.forcePlainLayout())
1289                         // in this case only the empty layout is allowed
1290                         layout = tclass.plainLayoutName();
1291                 else if (para.usePlainLayout()) {
1292                         // in this case, default layout maps to empty layout
1293                         if (layout == tclass.defaultLayoutName())
1294                                 layout = tclass.plainLayoutName();
1295                 } else {
1296                         // otherwise, the empty layout maps to the default
1297                         if (layout == tclass.plainLayoutName())
1298                                 layout = tclass.defaultLayoutName();
1299                 }
1300
1301                 bool hasLayout = tclass.hasLayout(layout);
1302
1303                 // If the entry is obsolete, use the new one instead.
1304                 if (hasLayout) {
1305                         docstring const & obs = tclass[layout].obsoleted_by();
1306                         if (!obs.empty())
1307                                 layout = obs;
1308                 }
1309
1310                 if (!hasLayout) {
1311                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1312                                 from_utf8(N_(" not known")));
1313                         break;
1314                 }
1315
1316                 bool change_layout = (old_layout != layout);
1317
1318                 if (!change_layout && cur.selection() &&
1319                         cur.selBegin().pit() != cur.selEnd().pit())
1320                 {
1321                         pit_type spit = cur.selBegin().pit();
1322                         pit_type epit = cur.selEnd().pit() + 1;
1323                         while (spit != epit) {
1324                                 if (pars_[spit].layout().name() != old_layout) {
1325                                         change_layout = true;
1326                                         break;
1327                                 }
1328                                 ++spit;
1329                         }
1330                 }
1331
1332                 if (change_layout)
1333                         setLayout(cur, layout);
1334
1335                 break;
1336         }
1337
1338         case LFUN_CLIPBOARD_PASTE:
1339                 cur.clearSelection();
1340                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1341                                cmd.argument() == "paragraph");
1342                 bv->buffer().errors("Paste");
1343                 break;
1344
1345         case LFUN_PRIMARY_SELECTION_PASTE:
1346                 pasteString(cur, theSelection().get(),
1347                             cmd.argument() == "paragraph");
1348                 break;
1349
1350         case LFUN_SELECTION_PASTE:
1351                 // Copy the selection buffer to the clipboard stack,
1352                 // because we want it to appear in the "Edit->Paste
1353                 // recent" menu.
1354                 cap::copySelectionToStack();
1355                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1356                 bv->buffer().errors("Paste");
1357                 break;
1358
1359         case LFUN_UNICODE_INSERT: {
1360                 if (cmd.argument().empty())
1361                         break;
1362                 docstring hexstring = cmd.argument();
1363                 if (isHex(hexstring)) {
1364                         char_type c = hexToInt(hexstring);
1365                         if (c >= 32 && c < 0x10ffff) {
1366                                 lyxerr << "Inserting c: " << c << endl;
1367                                 docstring s = docstring(1, c);
1368                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1369                         }
1370                 }
1371                 break;
1372         }
1373
1374         case LFUN_QUOTE_INSERT: {
1375                 Paragraph & par = cur.paragraph();
1376                 pos_type pos = cur.pos();
1377                 BufferParams const & bufparams = bv->buffer().params();
1378                 Layout const & style = par.layout();
1379                 InsetLayout const & ilayout = cur.inset().getLayout();
1380                 if (!style.pass_thru && !ilayout.isPassThru()
1381                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1382                         // this avoids a double undo
1383                         // FIXME: should not be needed, ideally
1384                         if (!cur.selection())
1385                                 cur.recordUndo();
1386                         cap::replaceSelection(cur);
1387                         pos = cur.pos();
1388                         char_type c;
1389                         if (pos == 0)
1390                                 c = ' ';
1391                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1392                                 c = ' ';
1393                         else
1394                                 c = par.getChar(pos - 1);
1395                         string arg = to_utf8(cmd.argument());
1396                         cur.insert(new InsetQuotes(bv->buffer(), c, (arg == "single")
1397                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1398                         cur.posForward();
1399                 }
1400                 else
1401                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1402                 break;
1403         }
1404
1405         case LFUN_DATE_INSERT: {
1406                 string const format = cmd.argument().empty()
1407                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1408                 string const time = formatted_time(current_time(), format);
1409                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1410                 break;
1411         }
1412
1413         case LFUN_MOUSE_TRIPLE:
1414                 if (cmd.button() == mouse_button::button1) {
1415                         tm->cursorHome(cur);
1416                         cur.resetAnchor();
1417                         tm->cursorEnd(cur);
1418                         cur.setSelection();
1419                         bv->cursor() = cur;
1420                 }
1421                 break;
1422
1423         case LFUN_MOUSE_DOUBLE:
1424                 if (cmd.button() == mouse_button::button1) {
1425                         selectWord(cur, WHOLE_WORD_STRICT);
1426                         bv->cursor() = cur;
1427                 }
1428                 break;
1429
1430         // Single-click on work area
1431         case LFUN_MOUSE_PRESS:
1432                 // We are not marking a selection with the keyboard in any case.
1433                 cur.bv().cursor().setMark(false);
1434                 switch (cmd.button()) {
1435                 case mouse_button::button1:
1436                         // Set the cursor
1437                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1438                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1439                         break;
1440
1441                 case mouse_button::button2:
1442                         // Middle mouse pasting.
1443                         bv->mouseSetCursor(cur);
1444                         lyx::dispatch(
1445                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1446                                             "selection-paste ; primary-selection-paste paragraph"));
1447                         cur.noUpdate();
1448                         break;
1449
1450                 case mouse_button::button3: {
1451                         Cursor const & bvcur = cur.bv().cursor();
1452                         // Don't do anything if we right-click a
1453                         // selection, a context menu will popup.
1454                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1455                             && cur < bvcur.selectionEnd()) {
1456                                 cur.noUpdate();
1457                                 return;
1458                         }
1459                         if (!bv->mouseSetCursor(cur, false))
1460                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1461                         break;
1462                 }
1463
1464                 default:
1465                         break;
1466                 } // switch (cmd.button())
1467                 break;
1468
1469         case LFUN_MOUSE_MOTION: {
1470                 // Mouse motion with right or middle mouse do nothing for now.
1471                 if (cmd.button() != mouse_button::button1) {
1472                         cur.noUpdate();
1473                         return;
1474                 }
1475                 // ignore motions deeper nested than the real anchor
1476                 Cursor & bvcur = cur.bv().cursor();
1477                 if (!bvcur.anchor_.hasPart(cur)) {
1478                         cur.undispatched();
1479                         break;
1480                 }
1481                 CursorSlice old = bvcur.top();
1482
1483                 int const wh = bv->workHeight();
1484                 int const y = max(0, min(wh - 1, cmd.y));
1485
1486                 tm->setCursorFromCoordinates(cur, cmd.x, y);
1487                 cur.setTargetX(cmd.x);
1488                 if (cmd.y >= wh)
1489                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1490                 else if (cmd.y < 0)
1491                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1492                 // This is to allow jumping over large insets
1493                 if (cur.top() == old) {
1494                         if (cmd.y >= wh)
1495                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1496                         else if (cmd.y < 0)
1497                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1498                 }
1499                 // We continue with our existing selection or start a new one, so don't
1500                 // reset the anchor.
1501                 bvcur.setCursor(cur);
1502                 bvcur.setSelection(true);
1503                 if (cur.top() == old) {
1504                         // We didn't move one iota, so no need to update the screen.
1505                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1506                         //cur.noUpdate();
1507                         return;
1508                 }
1509                 break;
1510         }
1511
1512         case LFUN_MOUSE_RELEASE:
1513                 switch (cmd.button()) {
1514                 case mouse_button::button1:
1515                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1516                         // If there is a new selection, update persistent selection;
1517                         // otherwise, single click does not clear persistent selection
1518                         // buffer.
1519                         if (cur.selection()) {
1520                                 // Finish selection. If double click,
1521                                 // cur is moved to the end of word by
1522                                 // selectWord but bvcur is current
1523                                 // mouse position.
1524                                 cur.bv().cursor().setSelection();
1525                                 // We might have removed an empty but drawn selection
1526                                 // (probably a margin)
1527                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1528                         } else
1529                                 cur.noUpdate();
1530                         // FIXME: We could try to handle drag and drop of selection here.
1531                         return;
1532
1533                 case mouse_button::button2:
1534                         // Middle mouse pasting is handled at mouse press time,
1535                         // see LFUN_MOUSE_PRESS.
1536                         cur.noUpdate();
1537                         return;
1538
1539                 case mouse_button::button3:
1540                         // Cursor was set at LFUN_MOUSE_PRESS time.
1541                         // FIXME: If there is a selection we could try to handle a special
1542                         // drag & drop context menu.
1543                         cur.noUpdate();
1544                         return;
1545
1546                 case mouse_button::none:
1547                 case mouse_button::button4:
1548                 case mouse_button::button5:
1549                         break;
1550                 } // switch (cmd.button())
1551
1552                 break;
1553
1554         case LFUN_SELF_INSERT: {
1555                 if (cmd.argument().empty())
1556                         break;
1557
1558                 // Automatically delete the currently selected
1559                 // text and replace it with what is being
1560                 // typed in now. Depends on lyxrc settings
1561                 // "auto_region_delete", which defaults to
1562                 // true (on).
1563
1564                 if (lyxrc.auto_region_delete && cur.selection())
1565                         cutSelection(cur, false, false);
1566
1567                 cur.clearSelection();
1568
1569                 docstring::const_iterator cit = cmd.argument().begin();
1570                 docstring::const_iterator const end = cmd.argument().end();
1571                 for (; cit != end; ++cit)
1572                         bv->translateAndInsert(*cit, this, cur);
1573
1574                 cur.resetAnchor();
1575                 moveCursor(cur, false);
1576                 bv->bookmarkEditPosition();
1577                 break;
1578         }
1579
1580         case LFUN_HYPERLINK_INSERT: {
1581                 InsetCommandParams p(HYPERLINK_CODE);
1582                 docstring content;
1583                 if (cur.selection()) {
1584                         content = cur.selectionAsString(false);
1585                         cutSelection(cur, true, false);
1586                 }
1587                 p["target"] = (cmd.argument().empty()) ?
1588                         content : cmd.argument();
1589                 string const data = InsetCommand::params2string("href", p);
1590                 if (p["target"].empty()) {
1591                         bv->showDialog("href", data);
1592                 } else {
1593                         FuncRequest fr(LFUN_INSET_INSERT, data);
1594                         dispatch(cur, fr);
1595                 }
1596                 break;
1597         }
1598
1599         case LFUN_LABEL_INSERT: {
1600                 InsetCommandParams p(LABEL_CODE);
1601                 // Try to generate a valid label
1602                 p["name"] = (cmd.argument().empty()) ?
1603                         cur.getPossibleLabel() :
1604                         cmd.argument();
1605                 string const data = InsetCommand::params2string("label", p);
1606
1607                 if (cmd.argument().empty()) {
1608                         bv->showDialog("label", data);
1609                 } else {
1610                         FuncRequest fr(LFUN_INSET_INSERT, data);
1611                         dispatch(cur, fr);
1612                 }
1613                 break;
1614         }
1615
1616         case LFUN_INFO_INSERT: {
1617                 Inset * inset;
1618                 if (cmd.argument().empty() && cur.selection()) {
1619                         // if command argument is empty use current selection as parameter.
1620                         docstring ds = cur.selectionAsString(false);
1621                         cutSelection(cur, true, false);
1622                         FuncRequest cmd0(cmd, ds);
1623                         inset = createInset(cur.bv().buffer(), cmd0);
1624                 } else {
1625                         inset = createInset(cur.bv().buffer(), cmd);
1626                 }
1627                 if (!inset)
1628                         break;
1629                 cur.recordUndo();
1630                 insertInset(cur, inset);
1631                 cur.posForward();
1632                 break;
1633         }
1634         case LFUN_CAPTION_INSERT:
1635         case LFUN_FOOTNOTE_INSERT:
1636         case LFUN_NOTE_INSERT:
1637         case LFUN_FLEX_INSERT:
1638         case LFUN_BOX_INSERT:
1639         case LFUN_BRANCH_INSERT:
1640         case LFUN_PHANTOM_INSERT:
1641         case LFUN_ERT_INSERT:
1642         case LFUN_LISTING_INSERT:
1643         case LFUN_MARGINALNOTE_INSERT:
1644         case LFUN_OPTIONAL_INSERT:
1645         case LFUN_INDEX_INSERT:
1646                 // Open the inset, and move the current selection
1647                 // inside it.
1648                 doInsertInset(cur, this, cmd, true, true);
1649                 cur.posForward();
1650                 // Some insets are numbered, others are shown in the outline pane so
1651                 // let's update the labels and the toc backend.
1652                 bv->buffer().updateLabels();
1653                 break;
1654
1655         case LFUN_TABULAR_INSERT:
1656                 // if there were no arguments, just open the dialog
1657                 if (doInsertInset(cur, this, cmd, false, true))
1658                         cur.posForward();
1659                 else
1660                         bv->showDialog("tabularcreate");
1661
1662                 break;
1663
1664         case LFUN_FLOAT_INSERT:
1665         case LFUN_FLOAT_WIDE_INSERT:
1666         case LFUN_WRAP_INSERT: {
1667                 // will some text be moved into the inset?
1668                 bool content = cur.selection();
1669
1670                 doInsertInset(cur, this, cmd, true, true);
1671                 cur.posForward();
1672
1673                 // If some text is moved into the inset, doInsertInset 
1674                 // puts the cursor outside the inset. To insert the
1675                 // caption we put it back into the inset.
1676                 if (content)
1677                         cur.backwardPos();
1678
1679                 ParagraphList & pars = cur.text()->paragraphs();
1680
1681                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1682
1683                 // add a separate paragraph for the caption inset
1684                 pars.push_back(Paragraph());
1685                 pars.back().setInsetOwner(&pars[0].inInset());
1686                 pars.back().setPlainOrDefaultLayout(tclass);
1687                 int cap_pit = pars.size() - 1;
1688
1689                 // if an empty inset was created, we create an additional empty
1690                 // paragraph at the bottom so that the user can choose where to put
1691                 // the graphics (or table).
1692                 if (!content) {
1693                         pars.push_back(Paragraph());
1694                         pars.back().setInsetOwner(&pars[0].inInset());
1695                         pars.back().setPlainOrDefaultLayout(tclass);
1696                 }
1697
1698                 // reposition the cursor to the caption
1699                 cur.pit() = cap_pit;
1700                 cur.pos() = 0;
1701                 // FIXME: This Text/Cursor dispatch handling is a mess!
1702                 // We cannot use Cursor::dispatch here it needs access to up to
1703                 // date metrics.
1704                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1705                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1706                 bv->buffer().updateLabels();
1707                 cur.updateFlags(Update::Force);
1708                 // FIXME: When leaving the Float (or Wrap) inset we should
1709                 // delete any empty paragraph left above or below the
1710                 // caption.
1711                 break;
1712         }
1713
1714         case LFUN_NOMENCL_INSERT: {
1715                 InsetCommandParams p(NOMENCL_CODE);
1716                 if (cmd.argument().empty())
1717                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1718                 else
1719                         p["symbol"] = cmd.argument();
1720                 string const data = InsetCommand::params2string("nomenclature", p);
1721                 bv->showDialog("nomenclature", data);
1722                 break;
1723         }
1724
1725         case LFUN_INDEX_PRINT: {
1726                 InsetCommandParams p(INDEX_PRINT_CODE);
1727                 if (cmd.argument().empty())
1728                         p["type"] = from_ascii("idx");
1729                 else
1730                         p["type"] = cmd.argument();
1731                 string const data = InsetCommand::params2string("index_print", p);
1732                 FuncRequest fr(LFUN_INSET_INSERT, data);
1733                 dispatch(cur, fr);
1734                 break;
1735         }
1736         
1737         case LFUN_NOMENCL_PRINT:
1738         case LFUN_TOC_INSERT:
1739         case LFUN_LINE_INSERT:
1740         case LFUN_NEWPAGE_INSERT:
1741                 // do nothing fancy
1742                 doInsertInset(cur, this, cmd, false, false);
1743                 cur.posForward();
1744                 break;
1745
1746         case LFUN_DEPTH_DECREMENT:
1747                 changeDepth(cur, DEC_DEPTH);
1748                 break;
1749
1750         case LFUN_DEPTH_INCREMENT:
1751                 changeDepth(cur, INC_DEPTH);
1752                 break;
1753
1754         case LFUN_MATH_DISPLAY:
1755                 mathDispatch(cur, cmd, true);
1756                 break;
1757
1758         case LFUN_REGEXP_MODE:
1759                 regexpDispatch(cur, cmd);
1760                 break;
1761
1762         case LFUN_MATH_MODE:
1763                 if (cmd.argument() == "on")
1764                         // don't pass "on" as argument
1765                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1766                 else
1767                         mathDispatch(cur, cmd, false);
1768                 break;
1769
1770         case LFUN_MATH_MACRO:
1771                 if (cmd.argument().empty())
1772                         cur.errorMessage(from_utf8(N_("Missing argument")));
1773                 else {
1774                         string s = to_utf8(cmd.argument());
1775                         string const s1 = token(s, ' ', 1);
1776                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1777                         string const s2 = token(s, ' ', 2);
1778                         MacroType type = MacroTypeNewcommand;
1779                         if (s2 == "def")
1780                                 type = MacroTypeDef;
1781                         MathMacroTemplate * inset = new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type);
1782                         inset->setBuffer(bv->buffer());
1783                         insertInset(cur, inset);
1784
1785                         // enter macro inset and select the name
1786                         cur.push(*inset);
1787                         cur.top().pos() = cur.top().lastpos();
1788                         cur.resetAnchor();
1789                         cur.setSelection(true);
1790                         cur.top().pos() = 0;
1791                 }
1792                 break;
1793
1794         // passthrough hat and underscore outside mathed:
1795         case LFUN_MATH_SUBSCRIPT:
1796                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1797                 break;
1798         case LFUN_MATH_SUPERSCRIPT:
1799                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1800                 break;
1801
1802         case LFUN_MATH_INSERT:
1803         case LFUN_MATH_AMS_MATRIX:
1804         case LFUN_MATH_MATRIX:
1805         case LFUN_MATH_DELIM:
1806         case LFUN_MATH_BIGDELIM: {
1807                 cur.recordUndo();
1808                 cap::replaceSelection(cur);
1809                 cur.insert(new InsetMathHull(hullSimple));
1810                 checkAndActivateInset(cur, true);
1811                 LASSERT(cur.inMathed(), /**/);
1812                 cur.dispatch(cmd);
1813                 break;
1814         }
1815
1816         case LFUN_FONT_EMPH: {
1817                 Font font(ignore_font, ignore_language);
1818                 font.fontInfo().setEmph(FONT_TOGGLE);
1819                 toggleAndShow(cur, this, font);
1820                 break;
1821         }
1822
1823         case LFUN_FONT_ITAL: {
1824                 Font font(ignore_font, ignore_language);
1825                 font.fontInfo().setShape(ITALIC_SHAPE);
1826                 toggleAndShow(cur, this, font);
1827                 break;
1828         }
1829
1830         case LFUN_FONT_BOLD:
1831         case LFUN_FONT_BOLDSYMBOL: {
1832                 Font font(ignore_font, ignore_language);
1833                 font.fontInfo().setSeries(BOLD_SERIES);
1834                 toggleAndShow(cur, this, font);
1835                 break;
1836         }
1837
1838         case LFUN_FONT_NOUN: {
1839                 Font font(ignore_font, ignore_language);
1840                 font.fontInfo().setNoun(FONT_TOGGLE);
1841                 toggleAndShow(cur, this, font);
1842                 break;
1843         }
1844
1845         case LFUN_FONT_TYPEWRITER: {
1846                 Font font(ignore_font, ignore_language);
1847                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1848                 toggleAndShow(cur, this, font);
1849                 break;
1850         }
1851
1852         case LFUN_FONT_SANS: {
1853                 Font font(ignore_font, ignore_language);
1854                 font.fontInfo().setFamily(SANS_FAMILY);
1855                 toggleAndShow(cur, this, font);
1856                 break;
1857         }
1858
1859         case LFUN_FONT_ROMAN: {
1860                 Font font(ignore_font, ignore_language);
1861                 font.fontInfo().setFamily(ROMAN_FAMILY);
1862                 toggleAndShow(cur, this, font);
1863                 break;
1864         }
1865
1866         case LFUN_FONT_DEFAULT: {
1867                 Font font(inherit_font, ignore_language);
1868                 toggleAndShow(cur, this, font);
1869                 break;
1870         }
1871
1872         case LFUN_FONT_STRIKEOUT: {
1873                 Font font(ignore_font, ignore_language);
1874                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1875                 toggleAndShow(cur, this, font);
1876                 break;
1877         }
1878
1879         case LFUN_FONT_UULINE: {
1880                 Font font(ignore_font, ignore_language);
1881                 font.fontInfo().setUuline(FONT_TOGGLE);
1882                 toggleAndShow(cur, this, font);
1883                 break;
1884         }
1885
1886         case LFUN_FONT_UWAVE: {
1887                 Font font(ignore_font, ignore_language);
1888                 font.fontInfo().setUwave(FONT_TOGGLE);
1889                 toggleAndShow(cur, this, font);
1890                 break;
1891         }
1892
1893         case LFUN_FONT_UNDERLINE: {
1894                 Font font(ignore_font, ignore_language);
1895                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1896                 toggleAndShow(cur, this, font);
1897                 break;
1898         }
1899
1900         case LFUN_FONT_SIZE: {
1901                 Font font(ignore_font, ignore_language);
1902                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1903                 toggleAndShow(cur, this, font);
1904                 break;
1905         }
1906
1907         case LFUN_LANGUAGE: {
1908                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1909                 if (!lang)
1910                         break;
1911                 Font font(ignore_font, lang);
1912                 toggleAndShow(cur, this, font);
1913                 break;
1914         }
1915
1916         case LFUN_TEXTSTYLE_APPLY:
1917                 toggleAndShow(cur, this, freefont, toggleall);
1918                 cur.message(_("Character set"));
1919                 break;
1920
1921         // Set the freefont using the contents of \param data dispatched from
1922         // the frontends and apply it at the current cursor location.
1923         case LFUN_TEXTSTYLE_UPDATE: {
1924                 Font font;
1925                 bool toggle;
1926                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1927                         freefont = font;
1928                         toggleall = toggle;
1929                         toggleAndShow(cur, this, freefont, toggleall);
1930                         cur.message(_("Character set"));
1931                 } else {
1932                         lyxerr << "Argument not ok";
1933                 }
1934                 break;
1935         }
1936
1937         case LFUN_FINISHED_LEFT:
1938                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1939                 // We're leaving an inset, going left. If the inset is LTR, we're
1940                 // leaving from the front, so we should not move (remain at --- but
1941                 // not in --- the inset). If the inset is RTL, move left, without
1942                 // entering the inset itself; i.e., move to after the inset.
1943                 if (cur.paragraph().getFontSettings(
1944                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1945                         cursorVisLeft(cur, true);
1946                 break;
1947
1948         case LFUN_FINISHED_RIGHT:
1949                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1950                 // We're leaving an inset, going right. If the inset is RTL, we're
1951                 // leaving from the front, so we should not move (remain at --- but
1952                 // not in --- the inset). If the inset is LTR, move right, without
1953                 // entering the inset itself; i.e., move to after the inset.
1954                 if (!cur.paragraph().getFontSettings(
1955                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1956                         cursorVisRight(cur, true);
1957                 break;
1958
1959         case LFUN_FINISHED_BACKWARD:
1960                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1961                 break;
1962
1963         case LFUN_FINISHED_FORWARD:
1964                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1965                 ++cur.pos();
1966                 cur.setCurrentFont();
1967                 break;
1968
1969         case LFUN_LAYOUT_PARAGRAPH: {
1970                 string data;
1971                 params2string(cur.paragraph(), data);
1972                 data = "show\n" + data;
1973                 bv->showDialog("paragraph", data);
1974                 break;
1975         }
1976
1977         case LFUN_PARAGRAPH_UPDATE: {
1978                 string data;
1979                 params2string(cur.paragraph(), data);
1980
1981                 // Will the paragraph accept changes from the dialog?
1982                 bool const accept =
1983                         cur.inset().allowParagraphCustomization(cur.idx());
1984
1985                 data = "update " + convert<string>(accept) + '\n' + data;
1986                 bv->updateDialog("paragraph", data);
1987                 break;
1988         }
1989
1990         case LFUN_ACCENT_UMLAUT:
1991         case LFUN_ACCENT_CIRCUMFLEX:
1992         case LFUN_ACCENT_GRAVE:
1993         case LFUN_ACCENT_ACUTE:
1994         case LFUN_ACCENT_TILDE:
1995         case LFUN_ACCENT_CEDILLA:
1996         case LFUN_ACCENT_MACRON:
1997         case LFUN_ACCENT_DOT:
1998         case LFUN_ACCENT_UNDERDOT:
1999         case LFUN_ACCENT_UNDERBAR:
2000         case LFUN_ACCENT_CARON:
2001         case LFUN_ACCENT_BREVE:
2002         case LFUN_ACCENT_TIE:
2003         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2004         case LFUN_ACCENT_CIRCLE:
2005         case LFUN_ACCENT_OGONEK:
2006                 theLyXFunc().handleKeyFunc(cmd.action);
2007                 if (!cmd.argument().empty())
2008                         // FIXME: Are all these characters encoded in one byte in utf8?
2009                         bv->translateAndInsert(cmd.argument()[0], this, cur);
2010                 break;
2011
2012         case LFUN_FLOAT_LIST_INSERT: {
2013                 DocumentClass const & tclass = bv->buffer().params().documentClass();
2014                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
2015                         cur.recordUndo();
2016                         if (cur.selection())
2017                                 cutSelection(cur, true, false);
2018                         breakParagraph(cur);
2019
2020                         if (cur.lastpos() != 0) {
2021                                 cursorBackward(cur);
2022                                 breakParagraph(cur);
2023                         }
2024
2025                         docstring const laystr = cur.inset().usePlainLayout() ?
2026                                 tclass.plainLayoutName() :
2027                                 tclass.defaultLayoutName();
2028                         setLayout(cur, laystr);
2029                         ParagraphParameters p;
2030                         // FIXME If this call were replaced with one to clearParagraphParams(),
2031                         // then we could get rid of this method altogether.
2032                         setParagraphs(cur, p);
2033                         // FIXME This should be simplified when InsetFloatList takes a
2034                         // Buffer in its constructor.
2035                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
2036                         ifl->setBuffer(bv->buffer());
2037                         insertInset(cur, ifl);
2038                         cur.posForward();
2039                 } else {
2040                         lyxerr << "Non-existent float type: "
2041                                << to_utf8(cmd.argument()) << endl;
2042                 }
2043                 break;
2044         }
2045
2046         case LFUN_CHANGE_ACCEPT: {
2047                 acceptOrRejectChanges(cur, ACCEPT);
2048                 break;
2049         }
2050
2051         case LFUN_CHANGE_REJECT: {
2052                 acceptOrRejectChanges(cur, REJECT);
2053                 break;
2054         }
2055
2056         case LFUN_THESAURUS_ENTRY: {
2057                 docstring arg = cmd.argument();
2058                 if (arg.empty()) {
2059                         arg = cur.selectionAsString(false);
2060                         // FIXME
2061                         if (arg.size() > 100 || arg.empty()) {
2062                                 // Get word or selection
2063                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2064                                 arg = cur.selectionAsString(false);
2065                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2066                         }
2067                 }
2068                 bv->showDialog("thesaurus", to_utf8(arg));
2069                 break;
2070         }
2071
2072         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2073                 // Given data, an encoding of the ParagraphParameters
2074                 // generated in the Paragraph dialog, this function sets
2075                 // the current paragraph, or currently selected paragraphs,
2076                 // appropriately.
2077                 // NOTE: This function overrides all existing settings.
2078                 setParagraphs(cur, cmd.argument());
2079                 cur.message(_("Paragraph layout set"));
2080                 break;
2081         }
2082
2083         case LFUN_PARAGRAPH_PARAMS: {
2084                 // Given data, an encoding of the ParagraphParameters as we'd
2085                 // find them in a LyX file, this function modifies the current paragraph,
2086                 // or currently selected paragraphs.
2087                 // NOTE: This function only modifies, and does not override, existing
2088                 // settings.
2089                 setParagraphs(cur, cmd.argument(), true);
2090                 cur.message(_("Paragraph layout set"));
2091                 break;
2092         }
2093
2094         case LFUN_ESCAPE:
2095                 if (cur.selection()) {
2096                         cur.setSelection(false);
2097                 } else {
2098                         cur.undispatched();
2099                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2100                         // correct, but I'm not 100% sure -- dov, 071019
2101                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2102                 }
2103                 break;
2104
2105         case LFUN_OUTLINE_UP:
2106                 outline(OutlineUp, cur);
2107                 setCursor(cur, cur.pit(), 0);
2108                 cur.buffer()->updateLabels();
2109                 needsUpdate = true;
2110                 break;
2111
2112         case LFUN_OUTLINE_DOWN:
2113                 outline(OutlineDown, cur);
2114                 setCursor(cur, cur.pit(), 0);
2115                 cur.buffer()->updateLabels();
2116                 needsUpdate = true;
2117                 break;
2118
2119         case LFUN_OUTLINE_IN:
2120                 outline(OutlineIn, cur);
2121                 cur.buffer()->updateLabels();
2122                 needsUpdate = true;
2123                 break;
2124
2125         case LFUN_OUTLINE_OUT:
2126                 outline(OutlineOut, cur);
2127                 cur.buffer()->updateLabels();
2128                 needsUpdate = true;
2129                 break;
2130         
2131         case LFUN_OUTLINE_DRAGMOVE: {
2132                 int const move_id = convert<int>(cmd.getArg(0));
2133                 int const move_to_id = convert<int>(cmd.getArg(1));
2134                 dragMove(cur, move_id, move_to_id);
2135                 setCursor(cur, cur.pit(), 0);
2136                 cur.buffer()->updateLabels();
2137                 needsUpdate = true;
2138                 break;
2139         }
2140
2141         default:
2142                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2143                 cur.undispatched();
2144                 break;
2145         }
2146
2147         if (lyxrc.spellcheck_continuously && cur.inTexted())
2148                 // Take this opportunity to spellcheck current word.
2149                 cur.paragraph().isMisspelled(cur.pos());
2150
2151         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2152
2153         // FIXME: The cursor flag is reset two lines below
2154         // so we need to check here if some of the LFUN did touch that.
2155         // for now only Text::erase() and Text::backspace() do that.
2156         // The plan is to verify all the LFUNs and then to remove this
2157         // singleParUpdate boolean altogether.
2158         if (cur.result().update() & Update::Force) {
2159                 singleParUpdate = false;
2160                 needsUpdate = true;
2161         }
2162
2163         // FIXME: the following code should go in favor of fine grained
2164         // update flag treatment.
2165         if (singleParUpdate) {
2166                 // Inserting characters does not change par height in general. So, try
2167                 // to update _only_ this paragraph. BufferView will detect if a full
2168                 // metrics update is needed anyway.
2169                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
2170                 return;
2171         }
2172
2173         if (!needsUpdate
2174             && &oldTopSlice.inset() == &cur.inset()
2175             && oldTopSlice.idx() == cur.idx()
2176             && !sel // sel is a backup of cur.selection() at the beginning of the function.
2177             && !cur.selection())
2178                 // FIXME: it would be better if we could just do this
2179                 //
2180                 //if (cur.result().update() != Update::FitCursor)
2181                 //      cur.noUpdate();
2182                 //
2183                 // But some LFUNs do not set Update::FitCursor when needed, so we
2184                 // do it for all. This is not very harmfull as FitCursor will provoke
2185                 // a full redraw only if needed but still, a proper review of all LFUN
2186                 // should be done and this needsUpdate boolean can then be removed.
2187                 cur.updateFlags(Update::FitCursor);
2188         else
2189                 cur.updateFlags(Update::Force | Update::FitCursor);
2190 }
2191
2192
2193 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2194                         FuncStatus & flag) const
2195 {
2196         LASSERT(cur.text() == this, /**/);
2197
2198         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2199         bool enable = true;
2200         InsetCode code = NO_CODE;
2201
2202         switch (cmd.action) {
2203
2204         case LFUN_DEPTH_DECREMENT:
2205                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2206                 break;
2207
2208         case LFUN_DEPTH_INCREMENT:
2209                 enable = changeDepthAllowed(cur, INC_DEPTH);
2210                 break;
2211
2212         case LFUN_APPENDIX:
2213                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2214                 break;
2215
2216         case LFUN_DIALOG_SHOW_NEW_INSET:
2217                 if (cmd.argument() == "bibitem")
2218                         code = BIBITEM_CODE;
2219                 else if (cmd.argument() == "bibtex") {
2220                         code = BIBTEX_CODE;
2221                         // not allowed in description items
2222                         enable = !inDescriptionItem(cur);
2223                 }
2224                 else if (cmd.argument() == "box")
2225                         code = BOX_CODE;
2226                 else if (cmd.argument() == "branch")
2227                         code = BRANCH_CODE;
2228                 else if (cmd.argument() == "citation")
2229                         code = CITE_CODE;
2230                 else if (cmd.argument() == "ert")
2231                         code = ERT_CODE;
2232                 else if (cmd.argument() == "external")
2233                         code = EXTERNAL_CODE;
2234                 else if (cmd.argument() == "float")
2235                         code = FLOAT_CODE;
2236                 else if (cmd.argument() == "graphics")
2237                         code = GRAPHICS_CODE;
2238                 else if (cmd.argument() == "href")
2239                         code = HYPERLINK_CODE;
2240                 else if (cmd.argument() == "include")
2241                         code = INCLUDE_CODE;
2242                 else if (cmd.argument() == "index")
2243                         code = INDEX_CODE;
2244                 else if (cmd.argument() == "index_print")
2245                         code = INDEX_PRINT_CODE;
2246                 else if (cmd.argument() == "nomenclature")
2247                         code = NOMENCL_CODE;
2248                 else if (cmd.argument() == "nomencl_print")
2249                         code = NOMENCL_PRINT_CODE;
2250                 else if (cmd.argument() == "label")
2251                         code = LABEL_CODE;
2252                 else if (cmd.argument() == "note")
2253                         code = NOTE_CODE;
2254                 else if (cmd.argument() == "phantom")
2255                         code = PHANTOM_CODE;
2256                 else if (cmd.argument() == "ref")
2257                         code = REF_CODE;
2258                 else if (cmd.argument() == "space")
2259                         code = SPACE_CODE;
2260                 else if (cmd.argument() == "toc")
2261                         code = TOC_CODE;
2262                 else if (cmd.argument() == "vspace")
2263                         code = VSPACE_CODE;
2264                 else if (cmd.argument() == "wrap")
2265                         code = WRAP_CODE;
2266                 else if (cmd.argument() == "listings")
2267                         code = LISTINGS_CODE;
2268                 break;
2269
2270         case LFUN_ERT_INSERT:
2271                 code = ERT_CODE;
2272                 break;
2273         case LFUN_LISTING_INSERT:
2274                 code = LISTINGS_CODE;
2275                 // not allowed in description items
2276                 enable = !inDescriptionItem(cur);
2277                 break;
2278         case LFUN_FOOTNOTE_INSERT:
2279                 code = FOOT_CODE;
2280                 break;
2281         case LFUN_TABULAR_INSERT:
2282                 code = TABULAR_CODE;
2283                 break;
2284         case LFUN_MARGINALNOTE_INSERT:
2285                 code = MARGIN_CODE;
2286                 break;
2287         case LFUN_FLOAT_INSERT:
2288         case LFUN_FLOAT_WIDE_INSERT:
2289                 code = FLOAT_CODE;
2290                 // not allowed in description items
2291                 enable = !inDescriptionItem(cur);
2292                 break;
2293         case LFUN_WRAP_INSERT:
2294                 code = WRAP_CODE;
2295                 // not allowed in description items
2296                 enable = !inDescriptionItem(cur);
2297                 break;
2298         case LFUN_FLOAT_LIST_INSERT:
2299                 code = FLOAT_LIST_CODE;
2300                 // not allowed in description items
2301                 enable = !inDescriptionItem(cur);
2302                 break;
2303         case LFUN_CAPTION_INSERT:
2304                 code = CAPTION_CODE;
2305                 // not allowed in description items
2306                 enable = !inDescriptionItem(cur);
2307                 break;
2308         case LFUN_NOTE_INSERT:
2309                 code = NOTE_CODE;
2310                 // in commands (sections etc.) and description items,
2311                 // only Notes are allowed
2312                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2313                           (!cur.paragraph().layout().isCommand()
2314                            && !inDescriptionItem(cur)));
2315                 break;
2316         case LFUN_FLEX_INSERT: {
2317                 code = FLEX_CODE;
2318                 string s = cmd.getArg(0);
2319                 InsetLayout il =
2320                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2321                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2322                     il.lyxtype() != InsetLayout::CUSTOM &&
2323                     il.lyxtype() != InsetLayout::ELEMENT &&
2324                     il.lyxtype ()!= InsetLayout::STANDARD)
2325                         enable = false;
2326                 break;
2327                 }
2328         case LFUN_BOX_INSERT:
2329                 code = BOX_CODE;
2330                 break;
2331         case LFUN_BRANCH_INSERT:
2332                 code = BRANCH_CODE;
2333                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2334                     && cur.buffer()->params().branchlist().empty())
2335                         enable = false;
2336                 break;
2337         case LFUN_PHANTOM_INSERT:
2338                 code = PHANTOM_CODE;
2339                 break;
2340         case LFUN_LABEL_INSERT:
2341                 code = LABEL_CODE;
2342                 break;
2343         case LFUN_LINE_INSERT:
2344                 code = LINE_CODE;
2345                 break;
2346         case LFUN_INFO_INSERT:
2347                 code = INFO_CODE;
2348                 break;
2349         case LFUN_OPTIONAL_INSERT:
2350                 code = OPTARG_CODE;
2351                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2352                         < cur.paragraph().layout().optionalargs;
2353                 break;
2354         case LFUN_INDEX_INSERT:
2355                 code = INDEX_CODE;
2356                 break;
2357         case LFUN_INDEX_PRINT:
2358                 code = INDEX_PRINT_CODE;
2359                 // not allowed in description items
2360                 enable = !inDescriptionItem(cur);
2361                 break;
2362         case LFUN_NOMENCL_INSERT:
2363                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2364                         enable = false;
2365                         break;
2366                 }
2367                 code = NOMENCL_CODE;
2368                 break;
2369         case LFUN_NOMENCL_PRINT:
2370                 code = NOMENCL_PRINT_CODE;
2371                 // not allowed in description items
2372                 enable = !inDescriptionItem(cur);
2373                 break;
2374         case LFUN_TOC_INSERT:
2375                 code = TOC_CODE;
2376                 // not allowed in description items
2377                 enable = !inDescriptionItem(cur);
2378                 break;
2379         case LFUN_HYPERLINK_INSERT:
2380                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2381                         enable = false;
2382                         break;
2383                 }
2384                 code = HYPERLINK_CODE;
2385                 break;
2386         case LFUN_QUOTE_INSERT:
2387                 // always allow this, since we will inset a raw quote
2388                 // if an inset is not allowed.
2389                 break;
2390         case LFUN_SPECIALCHAR_INSERT:
2391                 code = SPECIALCHAR_CODE;
2392                 break;
2393         case LFUN_SPACE_INSERT:
2394                 // slight hack: we know this is allowed in math mode
2395                 if (cur.inTexted())
2396                         code = SPACE_CODE;
2397                 break;
2398
2399         case LFUN_MATH_INSERT:
2400         case LFUN_MATH_AMS_MATRIX:
2401         case LFUN_MATH_MATRIX:
2402         case LFUN_MATH_DELIM:
2403         case LFUN_MATH_BIGDELIM:
2404         case LFUN_MATH_DISPLAY:
2405         case LFUN_MATH_MODE:
2406         case LFUN_MATH_MACRO:
2407         case LFUN_MATH_SUBSCRIPT:
2408         case LFUN_MATH_SUPERSCRIPT:
2409                 code = MATH_HULL_CODE;
2410                 break;
2411
2412         case LFUN_INSET_MODIFY:
2413                 // We need to disable this, because we may get called for a
2414                 // tabular cell via
2415                 // InsetTabular::getStatus() -> InsetText::getStatus()
2416                 // and we don't handle LFUN_INSET_MODIFY.
2417                 enable = false;
2418                 break;
2419
2420         case LFUN_FONT_EMPH:
2421                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2422                 break;
2423
2424         case LFUN_FONT_ITAL:
2425                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2426                 break;
2427
2428         case LFUN_FONT_NOUN:
2429                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2430                 break;
2431
2432         case LFUN_FONT_BOLD:
2433         case LFUN_FONT_BOLDSYMBOL:
2434                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2435                 break;
2436
2437         case LFUN_FONT_SANS:
2438                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2439                 break;
2440
2441         case LFUN_FONT_ROMAN:
2442                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2443                 break;
2444
2445         case LFUN_FONT_TYPEWRITER:
2446                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2447                 break;
2448
2449         case LFUN_CUT:
2450         case LFUN_COPY:
2451                 enable = cur.selection();
2452                 break;
2453
2454         case LFUN_PASTE: {
2455                 if (cmd.argument().empty()) {
2456                         if (theClipboard().isInternal())
2457                                 enable = cap::numberOfSelections() > 0;
2458                         else
2459                                 enable = !theClipboard().empty();
2460                         break;
2461                 }
2462
2463                 // we have an argument
2464                 string const arg = to_utf8(cmd.argument());
2465                 if (isStrUnsignedInt(arg)) {
2466                         // it's a number and therefore means the internal stack
2467                         unsigned int n = convert<unsigned int>(arg);
2468                         enable = cap::numberOfSelections() > n;
2469                         break;
2470                 }
2471
2472                 // explicit graphics type?
2473                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2474                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2475                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2476                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2477                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2478                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2479                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2480                         enable = theClipboard().hasGraphicsContents(type);
2481                         break;
2482                 }
2483
2484                 // unknown argument
2485                 enable = false;
2486                 break;
2487          }
2488
2489         case LFUN_CLIPBOARD_PASTE:
2490                 enable = !theClipboard().empty();
2491                 break;
2492
2493         case LFUN_PRIMARY_SELECTION_PASTE:
2494                 enable = cur.selection() || !theSelection().empty();
2495                 break;
2496
2497         case LFUN_SELECTION_PASTE:
2498                 enable = cap::selection();
2499                 break;
2500
2501         case LFUN_PARAGRAPH_MOVE_UP:
2502                 enable = cur.pit() > 0 && !cur.selection();
2503                 break;
2504
2505         case LFUN_PARAGRAPH_MOVE_DOWN:
2506                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2507                 break;
2508
2509         case LFUN_INSET_DISSOLVE:
2510                 if (!cmd.argument().empty()) {
2511                         InsetLayout const & il = cur.inset().getLayout();
2512                         InsetLayout::InsetLyXType const type = 
2513                                         translateLyXType(to_utf8(cmd.argument()));
2514                         enable = cur.inset().lyxCode() == FLEX_CODE
2515                                  && il.lyxtype() == type;
2516                 } else {
2517                         enable = ((!isMainText(cur.bv().buffer())
2518                                       && cur.inset().nargs() == 1)
2519                                   || (cur.nextInset()
2520                                       && cur.nextInset()->nargs() == 1));
2521                 }
2522                 break;
2523
2524         case LFUN_CHANGE_ACCEPT:
2525         case LFUN_CHANGE_REJECT:
2526                 // In principle, these LFUNs should only be enabled if there
2527                 // is a change at the current position/in the current selection.
2528                 // However, without proper optimizations, this will inevitably
2529                 // result in unacceptable performance - just imagine a user who
2530                 // wants to select the complete content of a long document.
2531                 if (!cur.selection()) {
2532                         Change const & change = cur.paragraph().lookupChange(cur.pos());
2533                         enable = change.changed();
2534                 } else
2535                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2536                         // for selections.
2537                         enable = true;
2538                 break;
2539
2540         case LFUN_OUTLINE_UP:
2541         case LFUN_OUTLINE_DOWN:
2542         case LFUN_OUTLINE_IN:
2543         case LFUN_OUTLINE_OUT:
2544         case LFUN_OUTLINE_DRAGMOVE:
2545                 // FIXME: LyX is not ready for outlining within inset.
2546                 enable = isMainText(cur.bv().buffer())
2547                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2548                 break;
2549
2550         case LFUN_NEWLINE_INSERT:
2551                 // LaTeX restrictions (labels or empty par)
2552                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2553                 break;
2554
2555         case LFUN_TAB_INSERT:
2556         case LFUN_TAB_DELETE:
2557                 enable = cur.inset().getLayout().isPassThru();
2558                 break;
2559
2560         case LFUN_SET_GRAPHICS_GROUP: {
2561                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2562                 if (!ins)
2563                         enable = false;
2564                 else
2565                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2566                 break;
2567         }
2568
2569         case LFUN_NEWPAGE_INSERT:
2570                 // not allowed in description items
2571                 code = NEWPAGE_CODE;
2572                 enable = !inDescriptionItem(cur);
2573                 break;
2574
2575         case LFUN_DATE_INSERT: {
2576                 string const format = cmd.argument().empty()
2577                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2578                 enable = support::os::is_valid_strftime(format);
2579                 break;
2580         }
2581
2582         case LFUN_LANGUAGE:
2583                 enable = !cur.inset().getLayout().isPassThru();
2584
2585         case LFUN_BREAK_PARAGRAPH:
2586                 enable = cur.inset().getLayout().isMultiPar();
2587
2588         case LFUN_WORD_DELETE_FORWARD:
2589         case LFUN_WORD_DELETE_BACKWARD:
2590         case LFUN_LINE_DELETE:
2591         case LFUN_WORD_FORWARD:
2592         case LFUN_WORD_BACKWARD:
2593         case LFUN_WORD_RIGHT:
2594         case LFUN_WORD_LEFT:
2595         case LFUN_CHAR_FORWARD:
2596         case LFUN_CHAR_FORWARD_SELECT:
2597         case LFUN_CHAR_BACKWARD:
2598         case LFUN_CHAR_BACKWARD_SELECT:
2599         case LFUN_CHAR_LEFT:
2600         case LFUN_CHAR_LEFT_SELECT:
2601         case LFUN_CHAR_RIGHT:
2602         case LFUN_CHAR_RIGHT_SELECT:
2603         case LFUN_UP:
2604         case LFUN_UP_SELECT:
2605         case LFUN_DOWN:
2606         case LFUN_DOWN_SELECT:
2607         case LFUN_PARAGRAPH_UP_SELECT:
2608         case LFUN_PARAGRAPH_DOWN_SELECT:
2609         case LFUN_LINE_BEGIN_SELECT:
2610         case LFUN_LINE_END_SELECT:
2611         case LFUN_WORD_FORWARD_SELECT:
2612         case LFUN_WORD_BACKWARD_SELECT:
2613         case LFUN_WORD_RIGHT_SELECT:
2614         case LFUN_WORD_LEFT_SELECT:
2615         case LFUN_WORD_SELECT:
2616         case LFUN_SECTION_SELECT:
2617         case LFUN_PARAGRAPH_UP:
2618         case LFUN_PARAGRAPH_DOWN:
2619         case LFUN_LINE_BEGIN:
2620         case LFUN_LINE_END:
2621         case LFUN_CHAR_DELETE_FORWARD:
2622         case LFUN_CHAR_DELETE_BACKWARD:
2623         case LFUN_INSET_INSERT:
2624         case LFUN_WORD_UPCASE:
2625         case LFUN_WORD_LOWCASE:
2626         case LFUN_WORD_CAPITALIZE:
2627         case LFUN_CHARS_TRANSPOSE:
2628         case LFUN_SERVER_GET_XY:
2629         case LFUN_SERVER_SET_XY:
2630         case LFUN_SERVER_GET_LAYOUT:
2631         case LFUN_LAYOUT:
2632         case LFUN_SELF_INSERT:
2633         case LFUN_FONT_DEFAULT:
2634         case LFUN_FONT_UNDERLINE:
2635         case LFUN_FONT_STRIKEOUT:
2636         case LFUN_FONT_UULINE:
2637         case LFUN_FONT_UWAVE:
2638         case LFUN_FONT_SIZE:
2639         case LFUN_TEXTSTYLE_APPLY:
2640         case LFUN_TEXTSTYLE_UPDATE:
2641         case LFUN_LAYOUT_PARAGRAPH:
2642         case LFUN_PARAGRAPH_UPDATE:
2643         case LFUN_ACCENT_UMLAUT:
2644         case LFUN_ACCENT_CIRCUMFLEX:
2645         case LFUN_ACCENT_GRAVE:
2646         case LFUN_ACCENT_ACUTE:
2647         case LFUN_ACCENT_TILDE:
2648         case LFUN_ACCENT_CEDILLA:
2649         case LFUN_ACCENT_MACRON:
2650         case LFUN_ACCENT_DOT:
2651         case LFUN_ACCENT_UNDERDOT:
2652         case LFUN_ACCENT_UNDERBAR:
2653         case LFUN_ACCENT_CARON:
2654         case LFUN_ACCENT_BREVE:
2655         case LFUN_ACCENT_TIE:
2656         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2657         case LFUN_ACCENT_CIRCLE:
2658         case LFUN_ACCENT_OGONEK:
2659         case LFUN_THESAURUS_ENTRY:
2660         case LFUN_PARAGRAPH_PARAMS_APPLY:
2661         case LFUN_PARAGRAPH_PARAMS:
2662         case LFUN_ESCAPE:
2663         case LFUN_BUFFER_BEGIN:
2664         case LFUN_BUFFER_END:
2665         case LFUN_BUFFER_BEGIN_SELECT:
2666         case LFUN_BUFFER_END_SELECT:
2667         case LFUN_INSET_BEGIN:
2668         case LFUN_INSET_END:
2669         case LFUN_INSET_BEGIN_SELECT:
2670         case LFUN_INSET_END_SELECT:
2671         case LFUN_UNICODE_INSERT:
2672                 // these are handled in our dispatch()
2673                 enable = true;
2674                 break;
2675
2676         default:
2677                 return false;
2678         }
2679
2680         if (code != NO_CODE
2681             && (cur.empty() 
2682                 || !cur.inset().insetAllowed(code)
2683                 || cur.paragraph().layout().pass_thru))
2684                 enable = false;
2685
2686         switch (cmd.action) {
2687         case LFUN_ACCENT_ACUTE:
2688         case LFUN_ACCENT_BREVE:
2689         case LFUN_ACCENT_CARON:
2690         case LFUN_ACCENT_CEDILLA:
2691         case LFUN_ACCENT_CIRCLE:
2692         case LFUN_ACCENT_CIRCUMFLEX:
2693         case LFUN_ACCENT_DOT:
2694         case LFUN_ACCENT_GRAVE:
2695         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2696         case LFUN_ACCENT_MACRON:
2697         case LFUN_ACCENT_OGONEK:
2698         case LFUN_ACCENT_TIE:
2699         case LFUN_ACCENT_TILDE:
2700         case LFUN_ACCENT_UMLAUT:
2701         case LFUN_ACCENT_UNDERBAR:
2702         case LFUN_ACCENT_UNDERDOT:
2703         case LFUN_APPENDIX:
2704         case LFUN_DEPTH_DECREMENT:
2705         case LFUN_DEPTH_INCREMENT:
2706         case LFUN_FILE_INSERT:
2707         case LFUN_FONT_BOLD:
2708         case LFUN_FONT_BOLDSYMBOL:
2709         case LFUN_FONT_TYPEWRITER:
2710         case LFUN_FONT_DEFAULT:
2711         case LFUN_FONT_EMPH:
2712         case LFUN_FONT_NOUN:
2713         case LFUN_FONT_ROMAN:
2714         case LFUN_FONT_SANS:
2715         case LFUN_FONT_FRAK:
2716         case LFUN_FONT_ITAL:
2717         case LFUN_FONT_SIZE:
2718         case LFUN_FONT_STATE:
2719         case LFUN_FONT_UNDERLINE:
2720         case LFUN_FONT_STRIKEOUT:
2721         case LFUN_FONT_UULINE:
2722         case LFUN_FONT_UWAVE:
2723         case LFUN_LABEL_GOTO:
2724         case LFUN_LAYOUT_TABULAR:
2725         case LFUN_MENU_OPEN:
2726         case LFUN_NOACTION:
2727         case LFUN_NOTE_NEXT:
2728         case LFUN_REFERENCE_NEXT:
2729         case LFUN_SERVER_GOTO_FILE_ROW:
2730         case LFUN_SERVER_NOTIFY:
2731         case LFUN_SERVER_SET_XY:
2732         case LFUN_TEXTSTYLE_APPLY:
2733         case LFUN_TEXTSTYLE_UPDATE:
2734                 if (cur.inset().getLayout().isPassThru())
2735                         enable = false;
2736                 break;
2737         default:
2738                 break;
2739         }
2740
2741         flag.setEnabled(enable);
2742         return true;
2743 }
2744
2745
2746 void Text::pasteString(Cursor & cur, docstring const & clip,
2747                 bool asParagraphs)
2748 {
2749         cur.clearSelection();
2750         if (!clip.empty()) {
2751                 cur.recordUndo();
2752                 if (asParagraphs)
2753                         insertStringAsParagraphs(cur, clip);
2754                 else
2755                         insertStringAsLines(cur, clip);
2756         }
2757 }
2758
2759
2760 // FIXME: an item inset would make things much easier.
2761 bool Text::inDescriptionItem(Cursor & cur) const
2762 {
2763         Paragraph & par = cur.paragraph();
2764         pos_type const pos = cur.pos();
2765         pos_type const body_pos = par.beginOfBody();
2766
2767         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2768             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2769                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2770                 return false;
2771
2772         return (pos < body_pos
2773                 || (pos == body_pos
2774                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2775 }
2776
2777 } // namespace lyx