]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
Change the interface to a paragraph's layout. We still store a LayoutPtr, but now...
[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 "Cursor.h"
29 #include "CutAndPaste.h"
30 #include "DispatchResult.h"
31 #include "ErrorList.h"
32 #include "factory.h"
33 #include "FuncRequest.h"
34 #include "InsetList.h"
35 #include "Intl.h"
36 #include "Language.h"
37 #include "Layout.h"
38 #include "LyXAction.h"
39 #include "LyXFunc.h"
40 #include "Lexer.h"
41 #include "LyXRC.h"
42 #include "Paragraph.h"
43 #include "paragraph_funcs.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include "insets/InsetCollapsable.h"
53 #include "insets/InsetCommand.h"
54 #include "insets/InsetFloatList.h"
55 #include "insets/InsetNewline.h"
56 #include "insets/InsetQuotes.h"
57 #include "insets/InsetSpecialChar.h"
58 #include "insets/InsetText.h"
59 #include "insets/InsetInfo.h"
60
61 #include "support/convert.h"
62 #include "support/debug.h"
63 #include "support/gettext.h"
64 #include "support/lstrings.h"
65 #include "support/lyxtime.h"
66
67 #include "mathed/InsetMathHull.h"
68 #include "mathed/MathMacroTemplate.h"
69
70 #include <boost/next_prior.hpp>
71
72 #include <clocale>
73 #include <sstream>
74
75 using namespace std;
76 using namespace lyx::support;
77
78 namespace lyx {
79
80 using cap::copySelection;
81 using cap::cutSelection;
82 using cap::pasteFromStack;
83 using cap::pasteClipboardText;
84 using cap::pasteClipboardGraphics;
85 using cap::replaceSelection;
86
87 // globals...
88 static Font freefont(ignore_font, ignore_language);
89 static bool toggleall = false;
90
91 static void toggleAndShow(Cursor & cur, Text * text,
92         Font const & font, bool toggleall = true)
93 {
94         text->toggleFree(cur, font, toggleall);
95
96         if (font.language() != ignore_language ||
97             font.fontInfo().number() != FONT_IGNORE) {
98                 TextMetrics const & tm = cur.bv().textMetrics(text);
99                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
100                                                        cur.real_current_font))
101                         text->setCursor(cur, cur.pit(), cur.pos(),
102                                         false, !cur.boundary());
103         }
104 }
105
106
107 static void moveCursor(Cursor & cur, bool selecting)
108 {
109         if (selecting || cur.mark())
110                 cur.setSelection();
111 }
112
113
114 static void finishChange(Cursor & cur, bool selecting)
115 {
116         cur.finishUndo();
117         moveCursor(cur, selecting);
118 }
119
120
121 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
122 {
123         cur.recordUndo();
124         docstring sel = cur.selectionAsString(false);
125
126         // It may happen that sel is empty but there is a selection
127         replaceSelection(cur);
128
129         if (sel.empty()) {
130 #ifdef ENABLE_ASSERTIONS
131                 const int old_pos = cur.pos();
132 #endif
133                 cur.insert(new InsetMathHull(hullSimple));
134                 BOOST_ASSERT(old_pos == cur.pos());
135                 cur.nextInset()->edit(cur, true);
136                 // don't do that also for LFUN_MATH_MODE
137                 // unless you want end up with always changing
138                 // to mathrm when opening an inlined inset --
139                 // I really hate "LyXfunc overloading"...
140                 if (display)
141                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
142                 // Avoid an unnecessary undo step if cmd.argument
143                 // is empty
144                 if (!cmd.argument().empty())
145                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
146                                                  cmd.argument()));
147         } else {
148                 // create a macro if we see "\\newcommand"
149                 // somewhere, and an ordinary formula
150                 // otherwise
151                 if (sel.find(from_ascii("\\newcommand")) == string::npos
152                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
153                                 && sel.find(from_ascii("\\def")) == string::npos)
154                 {
155                         InsetMathHull * formula = new InsetMathHull;
156                         istringstream is(to_utf8(sel));
157                         Lexer lex(0, 0);
158                         lex.setStream(is);
159                         formula->read(lex);
160                         if (formula->getType() == hullNone)
161                                 // Don't create pseudo formulas if
162                                 // delimiters are left out
163                                 formula->mutate(hullSimple);
164                         cur.insert(formula);
165                 } else {
166                         cur.insert(new MathMacroTemplate(sel));
167                 }
168         }
169         cur.message(from_utf8(N_("Math editor mode")));
170 }
171
172
173 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
174 {
175         cur.recordUndo();
176         cap::replaceSelection(cur);
177         cur.insert(new InsetSpecialChar(kind));
178         cur.posForward();
179 }
180
181
182 static bool doInsertInset(Cursor & cur, Text * text,
183         FuncRequest const & cmd, bool edit, bool pastesel)
184 {
185         Buffer & buffer = cur.bv().buffer();
186         BufferParams const & bparams = buffer.params();
187         Inset * inset = createInset(buffer, cmd);
188         if (!inset)
189                 return false;
190
191         if (InsetCollapsable * ci = inset->asInsetCollapsable())
192                 ci->setLayout(bparams);
193
194         cur.recordUndo();
195         if (cmd.action == LFUN_INDEX_INSERT) {
196                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
197                 text->insertInset(cur, inset);
198                 if (edit)
199                         inset->edit(cur, true);
200                 // Now put this into inset
201                 static_cast<InsetCollapsable *>(inset)->text_.insertStringAsParagraphs(cur, ds);
202                 return true;
203         }
204
205         bool gotsel = false;
206         if (cur.selection()) {
207                 lyx::dispatch(FuncRequest(LFUN_CUT));
208                 gotsel = true;
209         }
210         text->insertInset(cur, inset);
211
212         if (edit)
213                 inset->edit(cur, true);
214
215         if (!gotsel || !pastesel)
216                 return true;
217
218         lyx::dispatch(FuncRequest(LFUN_PASTE, "0"));
219         InsetText * insetText = dynamic_cast<InsetText *>(inset);
220         if (insetText && !insetText->allowMultiPar() || cur.lastpit() == 0) {
221                 // reset first par to default
222                 cur.text()->paragraphs().begin()
223                         ->setEmptyOrDefaultLayout(bparams.documentClass());
224                 cur.pos() = 0;
225                 cur.pit() = 0;
226                 // Merge multiple paragraphs -- hack
227                 while (cur.lastpit() > 0)
228                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
229         } else {
230                 // reset surrounding par to default
231                 docstring const layoutname = insetText->useEmptyLayout()
232                         ? bparams.documentClass().emptyLayoutName()
233                         : bparams.documentClass().defaultLayoutName();
234                 cur.leaveInset(*inset);
235                 text->setLayout(cur, layoutname);
236         }
237
238         return true;
239 }
240
241
242 string const freefont2string()
243 {
244         return freefont.toString(toggleall);
245 }
246
247
248 /// the type of outline operation
249 enum OutlineOp {
250         OutlineUp, // Move this header with text down
251         OutlineDown,   // Move this header with text up
252         OutlineIn, // Make this header deeper
253         OutlineOut // Make this header shallower
254 };
255
256
257 static void outline(OutlineOp mode, Cursor & cur)
258 {
259         Buffer & buf = cur.buffer();
260         pit_type & pit = cur.pit();
261         ParagraphList & pars = buf.text().paragraphs();
262         ParagraphList::iterator bgn = pars.begin();
263         // The first paragraph of the area to be copied:
264         ParagraphList::iterator start = boost::next(bgn, pit);
265         // The final paragraph of area to be copied:
266         ParagraphList::iterator finish = start;
267         ParagraphList::iterator end = pars.end();
268
269         DocumentClass const & tc = buf.params().documentClass();
270
271         int const thistoclevel = start->layout().toclevel;
272         int toclevel;
273
274         // Move out (down) from this section header
275         if (finish != end)
276                 ++finish;
277         // Seek the one (on same level) below
278         for (; finish != end; ++finish) {
279                 toclevel = finish->layout().toclevel;
280                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel) {
281                         break;
282                 }
283         }
284
285         switch (mode) {
286                 case OutlineUp: {
287                         ParagraphList::iterator dest = start;
288                         // Move out (up) from this header
289                         if (dest == bgn)
290                                 return;
291                         // Search previous same-level header above
292                         do {
293                                 --dest;
294                                 toclevel = dest->layout().toclevel;
295                         } while(dest != bgn
296                                 && (toclevel == Layout::NOT_IN_TOC
297                                     || toclevel > thistoclevel));
298                         // Not found; do nothing
299                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
300                                 return;
301                         pit_type const newpit = distance(bgn, dest);
302                         pit_type const len = distance(start, finish);
303                         pit_type const deletepit = pit + len;
304                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
305                         pars.insert(dest, start, finish);
306                         start = boost::next(pars.begin(), deletepit);
307                         pit = newpit;
308                         pars.erase(start, finish);
309                         return;
310                 }
311                 case OutlineDown: {
312                         ParagraphList::iterator dest = finish;
313                         // One such was found:
314                         pit_type newpit = distance(bgn, dest);
315                         pit_type const len = distance(start, finish);
316                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
317                         pars.insert(dest, start, finish);
318                         start = boost::next(bgn, pit);
319                         pit = newpit - len;
320                         pars.erase(start, finish);
321                         return;
322                 }
323                 case OutlineIn: {
324                         pit_type const len = distance(start, finish);
325                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
326                         for (; start != finish; ++start) {
327                                 toclevel = start->layout().toclevel;
328                                 if (toclevel == Layout::NOT_IN_TOC)
329                                         continue;
330                                 DocumentClass::const_iterator lit = tc.begin();
331                                 DocumentClass::const_iterator len = tc.end();
332                                 for (; lit != len; ++lit) {
333                                         if (lit->toclevel == toclevel + 1 &&
334                                             start->layout().labeltype == lit->labeltype) {
335                                                 start->setLayout(*lit);
336                                                 break;
337                                         }
338                                 }
339                         }
340                         return;
341                 }
342                 case OutlineOut: {
343                         pit_type const len = distance(start, finish);
344                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
345                         for (; start != finish; ++start) {
346                                 toclevel = start->layout().toclevel;
347                                 if (toclevel == Layout::NOT_IN_TOC)
348                                         continue;
349                                 DocumentClass::const_iterator lit = tc.begin();
350                                 DocumentClass::const_iterator len = tc.end();
351                                 for (; lit != len; ++lit) {
352                                         if (lit->toclevel == toclevel - 1 &&
353                                                 start->layout().labeltype == lit->labeltype) {
354                                                         start->setLayout(*lit);
355                                                         break;
356                                         }
357                                 }
358                         }
359                         return;
360                 }
361         }
362 }
363
364
365 void Text::number(Cursor & cur)
366 {
367         FontInfo font = ignore_font;
368         font.setNumber(FONT_TOGGLE);
369         toggleAndShow(cur, this, Font(font, ignore_language));
370 }
371
372
373 bool Text::isRTL(Buffer const & buffer, Paragraph const & par) const
374 {
375         return par.isRTL(buffer.params());
376 }
377
378
379 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
380 {
381         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
382
383         BufferView * bv = &cur.bv();
384         TextMetrics & tm = bv->textMetrics(this);
385         if (!tm.contains(cur.pit()))
386                 lyx::dispatch(FuncRequest(LFUN_SCREEN_RECENTER));
387
388         // FIXME: We use the update flag to indicates wether a singlePar or a
389         // full screen update is needed. We reset it here but shall we restore it
390         // at the end?
391         cur.noUpdate();
392
393         BOOST_ASSERT(cur.text() == this);
394         CursorSlice oldTopSlice = cur.top();
395         bool oldBoundary = cur.boundary();
396         bool sel = cur.selection();
397         // Signals that, even if needsUpdate == false, an update of the
398         // cursor paragraph is required
399         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
400                 LyXAction::SingleParUpdate);
401         // Signals that a full-screen update is required
402         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
403                 LyXAction::NoUpdate) || singleParUpdate);
404
405         switch (cmd.action) {
406
407         case LFUN_PARAGRAPH_MOVE_DOWN: {
408                 pit_type const pit = cur.pit();
409                 recUndo(cur, pit, pit + 1);
410                 cur.finishUndo();
411                 swap(pars_[pit], pars_[pit + 1]);
412                 updateLabels(cur.buffer());
413                 needsUpdate = true;
414                 ++cur.pit();
415                 break;
416         }
417
418         case LFUN_PARAGRAPH_MOVE_UP: {
419                 pit_type const pit = cur.pit();
420                 recUndo(cur, pit - 1, pit);
421                 cur.finishUndo();
422                 swap(pars_[pit], pars_[pit - 1]);
423                 updateLabels(cur.buffer());
424                 --cur.pit();
425                 needsUpdate = true;
426                 break;
427         }
428
429         case LFUN_APPENDIX: {
430                 Paragraph & par = cur.paragraph();
431                 bool start = !par.params().startOfAppendix();
432
433 // FIXME: The code below only makes sense at top level.
434 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
435                 // ensure that we have only one start_of_appendix in this document
436                 // FIXME: this don't work for multipart document!
437                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
438                         if (pars_[tmp].params().startOfAppendix()) {
439                                 recUndo(cur, tmp);
440                                 pars_[tmp].params().startOfAppendix(false);
441                                 break;
442                         }
443                 }
444
445                 cur.recordUndo();
446                 par.params().startOfAppendix(start);
447
448                 // we can set the refreshing parameters now
449                 updateLabels(cur.buffer());
450                 break;
451         }
452
453         case LFUN_WORD_DELETE_FORWARD:
454                 if (cur.selection()) {
455                         cutSelection(cur, true, false);
456                 } else
457                         deleteWordForward(cur);
458                 finishChange(cur, false);
459                 break;
460
461         case LFUN_WORD_DELETE_BACKWARD:
462                 if (cur.selection()) {
463                         cutSelection(cur, true, false);
464                 } else
465                         deleteWordBackward(cur);
466                 finishChange(cur, false);
467                 break;
468
469         case LFUN_LINE_DELETE:
470                 if (cur.selection()) {
471                         cutSelection(cur, true, false);
472                 } else
473                         tm.deleteLineForward(cur);
474                 finishChange(cur, false);
475                 break;
476
477         case LFUN_BUFFER_BEGIN:
478         case LFUN_BUFFER_BEGIN_SELECT:
479                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
480                 if (cur.depth() == 1) {
481                         needsUpdate |= cursorTop(cur);
482                 } else {
483                         cur.undispatched();
484                 }
485                 cur.updateFlags(Update::FitCursor);
486                 break;
487
488         case LFUN_BUFFER_END:
489         case LFUN_BUFFER_END_SELECT:
490                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
491                 if (cur.depth() == 1) {
492                         needsUpdate |= cursorBottom(cur);
493                 } else {
494                         cur.undispatched();
495                 }
496                 cur.updateFlags(Update::FitCursor);
497                 break;
498
499         case LFUN_CHAR_FORWARD:
500         case LFUN_CHAR_FORWARD_SELECT:
501                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
502                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
503                 needsUpdate |= cursorForward(cur);
504
505                 if (!needsUpdate && oldTopSlice == cur.top()
506                                 && cur.boundary() == oldBoundary) {
507                         cur.undispatched();
508                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
509                 }
510                 break;
511
512         case LFUN_CHAR_BACKWARD:
513         case LFUN_CHAR_BACKWARD_SELECT:
514                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
515                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
516                 needsUpdate |= cursorBackward(cur);
517
518                 if (!needsUpdate && oldTopSlice == cur.top()
519                         && cur.boundary() == oldBoundary) {
520                         cur.undispatched();
521                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
522                 }
523                 break;
524
525         case LFUN_CHAR_LEFT:
526         case LFUN_CHAR_LEFT_SELECT:
527                 if (lyxrc.visual_cursor) {
528                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
529                         needsUpdate |= cursorVisLeft(cur);
530                         if (!needsUpdate && oldTopSlice == cur.top()
531                                         && cur.boundary() == oldBoundary) {
532                                 cur.undispatched();
533                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
534                         }
535                 } else {
536                         if (reverseDirectionNeeded(cur)) {
537                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
538                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
539                         } else {
540                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ? 
541                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
542                         }
543                         dispatch(cur, cmd);
544                         return;
545                 }
546                 break;
547
548         case LFUN_CHAR_RIGHT:
549         case LFUN_CHAR_RIGHT_SELECT:
550                 if (lyxrc.visual_cursor) {
551                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
552                         needsUpdate |= cursorVisRight(cur);
553                         if (!needsUpdate && oldTopSlice == cur.top()
554                                         && cur.boundary() == oldBoundary) {
555                                 cur.undispatched();
556                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
557                         }
558                 } else {
559                         if (reverseDirectionNeeded(cur)) {
560                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
561                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
562                         } else {
563                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ? 
564                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
565                         }
566                         dispatch(cur, cmd);
567                         return;
568                 }
569                 break;
570                 
571
572         case LFUN_UP_SELECT:
573         case LFUN_DOWN_SELECT:
574         case LFUN_UP:
575         case LFUN_DOWN: {
576                 // stop/start the selection
577                 bool select = cmd.action == LFUN_DOWN_SELECT ||
578                         cmd.action == LFUN_UP_SELECT;
579                 cur.selHandle(select);
580                 
581                 // move cursor up/down
582                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
583                 bool const successful = cur.upDownInText(up, needsUpdate);
584                 if (successful) {
585                         // redraw if you leave mathed (for the decorations)
586                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
587                 } else
588                         cur.undispatched();
589                 
590                 break;
591         }
592
593         case LFUN_PARAGRAPH_UP:
594         case LFUN_PARAGRAPH_UP_SELECT:
595                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
596                 needsUpdate |= cursorUpParagraph(cur);
597                 break;
598
599         case LFUN_PARAGRAPH_DOWN:
600         case LFUN_PARAGRAPH_DOWN_SELECT:
601                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
602                 needsUpdate |= cursorDownParagraph(cur);
603                 break;
604
605         case LFUN_LINE_BEGIN:
606         case LFUN_LINE_BEGIN_SELECT:
607                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
608                 needsUpdate |= tm.cursorHome(cur);
609                 break;
610
611         case LFUN_LINE_END:
612         case LFUN_LINE_END_SELECT:
613                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
614                 needsUpdate |= tm.cursorEnd(cur);
615                 break;
616
617         case LFUN_WORD_RIGHT:
618         case LFUN_WORD_RIGHT_SELECT:
619                 //FIXME: for visual cursor mode, really move right
620                 if (reverseDirectionNeeded(cur)) {
621                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
622                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
623                 } else {
624                         cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
625                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
626                 }
627                 dispatch(cur, cmd);
628                 return;
629
630         case LFUN_WORD_FORWARD:
631         case LFUN_WORD_FORWARD_SELECT:
632                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
633                 needsUpdate |= cursorForwardOneWord(cur);
634                 break;
635
636         case LFUN_WORD_LEFT:
637         case LFUN_WORD_LEFT_SELECT:
638                 //FIXME: for visual cursor mode, really move left
639                 if (reverseDirectionNeeded(cur)) {
640                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
641                                         LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
642                 } else {
643                         cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
644                                         LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
645                 }
646                 dispatch(cur, cmd);
647                 return;
648
649         case LFUN_WORD_BACKWARD:
650         case LFUN_WORD_BACKWARD_SELECT:
651                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
652                 needsUpdate |= cursorBackwardOneWord(cur);
653                 break;
654
655         case LFUN_WORD_SELECT: {
656                 selectWord(cur, WHOLE_WORD);
657                 finishChange(cur, true);
658                 break;
659         }
660
661         case LFUN_NEW_LINE: {
662                 // Not allowed by LaTeX (labels or empty par)
663                 if (cur.pos() > cur.paragraph().beginOfBody()) {
664                         // this avoids a double undo
665                         // FIXME: should not be needed, ideally
666                         if (!cur.selection())
667                                 cur.recordUndo();
668                         cap::replaceSelection(cur);
669                         cur.insert(new InsetNewline);
670                         cur.posForward();
671                         moveCursor(cur, false);
672                 }
673                 break;
674         }
675         
676         case LFUN_LINE_BREAK: {
677                 // Not allowed by LaTeX (labels or empty par)
678                 if (cur.pos() > cur.paragraph().beginOfBody()) {
679                         // this avoids a double undo
680                         // FIXME: should not be needed, ideally
681                         if (!cur.selection())
682                                 cur.recordUndo();
683                         cap::replaceSelection(cur);
684                         cur.insert(new InsetLinebreak);
685                         cur.posForward();
686                         moveCursor(cur, false);
687                 }
688                 break;
689         }
690
691         case LFUN_CHAR_DELETE_FORWARD:
692                 if (!cur.selection()) {
693                         if (cur.pos() == cur.paragraph().size())
694                                 // Par boundary, force full-screen update
695                                 singleParUpdate = false;
696                         needsUpdate |= erase(cur);
697                         cur.resetAnchor();
698                         // It is possible to make it a lot faster still
699                         // just comment out the line below...
700                 } else {
701                         cutSelection(cur, true, false);
702                         singleParUpdate = false;
703                 }
704                 moveCursor(cur, false);
705                 break;
706
707         case LFUN_DELETE_FORWARD_SKIP:
708                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
709                 if (!cur.selection()) {
710                         if (cur.pos() == cur.lastpos()) {
711                                 cursorForward(cur);
712                                 cursorBackward(cur);
713                         }
714                         erase(cur);
715                         cur.resetAnchor();
716                 } else {
717                         cutSelection(cur, true, false);
718                 }
719                 break;
720
721
722         case LFUN_CHAR_DELETE_BACKWARD:
723                 if (!cur.selection()) {
724                         if (bv->getIntl().getTransManager().backspace()) {
725                                 // Par boundary, full-screen update
726                                 if (cur.pos() == 0)
727                                         singleParUpdate = false;
728                                 needsUpdate |= backspace(cur);
729                                 cur.resetAnchor();
730                                 // It is possible to make it a lot faster still
731                                 // just comment out the line below...
732                         }
733                 } else {
734                         cutSelection(cur, true, false);
735                         singleParUpdate = false;
736                 }
737                 break;
738
739         case LFUN_DELETE_BACKWARD_SKIP:
740                 // Reverse the effect of LFUN_BREAK_PARAGRAPH_SKIP.
741                 if (!cur.selection()) {
742                         // FIXME: look here
743                         //CursorSlice cur = cursor();
744                         backspace(cur);
745                         //anchor() = cur;
746                 } else {
747                         cutSelection(cur, true, false);
748                 }
749                 break;
750
751         case LFUN_BREAK_PARAGRAPH:
752                 cap::replaceSelection(cur);
753                 breakParagraph(cur, cmd.argument() == "inverse");
754                 cur.resetAnchor();
755                 break;
756
757         case LFUN_BREAK_PARAGRAPH_SKIP: {
758                 // When at the beginning of a paragraph, remove
759                 // indentation.  Otherwise, do the same as LFUN_BREAK_PARAGRAPH.
760                 cap::replaceSelection(cur);
761                 if (cur.pos() == 0)
762                         cur.paragraph().params().labelWidthString(docstring());
763                 else
764                         breakParagraph(cur, false);
765                 cur.resetAnchor();
766                 break;
767         }
768
769         // TODO
770         // With the creation of LFUN_PARAGRAPH_PARAMS, this is now redundant,
771         // as its duties can be performed there. Should it be removed??
772         // FIXME For now, it can just dispatch LFUN_PARAGRAPH_PARAMS...
773         case LFUN_PARAGRAPH_SPACING: {
774                 Paragraph & par = cur.paragraph();
775                 Spacing::Space cur_spacing = par.params().spacing().getSpace();
776                 string cur_value = "1.0";
777                 if (cur_spacing == Spacing::Other)
778                         cur_value = par.params().spacing().getValueAsString();
779
780                 istringstream is(to_utf8(cmd.argument()));
781                 string tmp;
782                 is >> tmp;
783                 Spacing::Space new_spacing = cur_spacing;
784                 string new_value = cur_value;
785                 if (tmp.empty()) {
786                         lyxerr << "Missing argument to `paragraph-spacing'"
787                                << endl;
788                 } else if (tmp == "single") {
789                         new_spacing = Spacing::Single;
790                 } else if (tmp == "onehalf") {
791                         new_spacing = Spacing::Onehalf;
792                 } else if (tmp == "double") {
793                         new_spacing = Spacing::Double;
794                 } else if (tmp == "other") {
795                         new_spacing = Spacing::Other;
796                         string tmpval = "0.0";
797                         is >> tmpval;
798                         lyxerr << "new_value = " << tmpval << endl;
799                         if (tmpval != "0.0")
800                                 new_value = tmpval;
801                 } else if (tmp == "default") {
802                         new_spacing = Spacing::Default;
803                 } else {
804                         lyxerr << to_utf8(_("Unknown spacing argument: "))
805                                << to_utf8(cmd.argument()) << endl;
806                 }
807                 if (cur_spacing != new_spacing || cur_value != new_value)
808                         par.params().spacing(Spacing(new_spacing, new_value));
809                 break;
810         }
811
812         case LFUN_INSET_INSERT: {
813                 cur.recordUndo();
814                 Inset * inset = createInset(bv->buffer(), cmd);
815                 if (inset) {
816                         // FIXME (Abdel 01/02/2006):
817                         // What follows would be a partial fix for bug 2154:
818                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
819                         // This automatically put the label inset _after_ a
820                         // numbered section. It should be possible to extend the mechanism
821                         // to any kind of LateX environement.
822                         // The correct way to fix that bug would be at LateX generation.
823                         // I'll let the code here for reference as it could be used for some
824                         // other feature like "automatic labelling".
825                         /*
826                         Paragraph & par = pars_[cur.pit()];
827                         if (inset->lyxCode() == LABEL_CODE
828                                 && par.layout().labeltype == LABEL_COUNTER) {
829                                 // Go to the end of the paragraph
830                                 // Warning: Because of Change-Tracking, the last
831                                 // position is 'size()' and not 'size()-1':
832                                 cur.pos() = par.size();
833                                 // Insert a new paragraph
834                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
835                                 dispatch(cur, fr);
836                         }
837                         */
838                         if (cur.selection())
839                                 cutSelection(cur, true, false);
840                         cur.insert(inset);
841                         cur.posForward();
842                 }
843                 break;
844         }
845
846         case LFUN_INSET_DISSOLVE:
847                 needsUpdate |= dissolveInset(cur);
848                 break;
849
850         case LFUN_INSET_SETTINGS:
851                 cur.inset().showInsetDialog(bv);
852                 break;
853
854         case LFUN_SPACE_INSERT:
855                 if (cur.paragraph().layout().free_spacing)
856                         insertChar(cur, ' ');
857                 else {
858                         doInsertInset(cur, this, cmd, false, false);
859                         cur.posForward();
860                 }
861                 moveCursor(cur, false);
862                 break;
863
864         case LFUN_SPECIALCHAR_INSERT: {
865                 string const name = to_utf8(cmd.argument());
866                 if (name == "hyphenation")
867                         specialChar(cur, InsetSpecialChar::HYPHENATION);
868                 else if (name == "ligature-break")
869                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
870                 else if (name == "slash")
871                         specialChar(cur, InsetSpecialChar::SLASH);
872                 else if (name == "nobreakdash")
873                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
874                 else if (name == "dots")
875                         specialChar(cur, InsetSpecialChar::LDOTS);
876                 else if (name == "end-of-sentence")
877                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
878                 else if (name == "menu-separator")
879                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
880                 else if (name.empty())
881                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
882                 else
883                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
884                 break;
885         }
886
887         case LFUN_WORD_UPCASE:
888                 changeCase(cur, text_uppercase);
889                 break;
890
891         case LFUN_WORD_LOWCASE:
892                 changeCase(cur, text_lowercase);
893                 break;
894
895         case LFUN_WORD_CAPITALIZE:
896                 changeCase(cur, text_capitalization);
897                 break;
898
899         case LFUN_CHARS_TRANSPOSE:
900                 charsTranspose(cur);
901                 break;
902
903         case LFUN_PASTE: {
904                 cur.message(_("Paste"));
905                 cap::replaceSelection(cur);
906
907                 // without argument?
908                 string const arg = to_utf8(cmd.argument());
909                 if (arg.empty()) {
910                         if (theClipboard().isInternal())
911                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
912                         else if (theClipboard().hasGraphicsContents())
913                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
914                         else
915                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
916                 } else if (isStrUnsignedInt(arg)) {
917                         // we have a numerical argument
918                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
919                                        convert<unsigned int>(arg));
920                 } else {
921                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
922                         if (arg == "pdf")
923                                 type = Clipboard::PdfGraphicsType;
924                         else if (arg == "png")
925                                 type = Clipboard::PngGraphicsType;
926                         else if (arg == "jpeg")
927                                 type = Clipboard::JpegGraphicsType;
928                         else if (arg == "linkback")
929                                 type = Clipboard::LinkBackGraphicsType;
930                         else
931                                 BOOST_ASSERT(false);
932
933                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
934                 }
935
936                 bv->buffer().errors("Paste");
937                 cur.clearSelection(); // bug 393
938                 cur.finishUndo();
939                 break;
940         }
941
942         case LFUN_CUT:
943                 cutSelection(cur, true, true);
944                 cur.message(_("Cut"));
945                 break;
946
947         case LFUN_COPY:
948                 copySelection(cur);
949                 cur.message(_("Copy"));
950                 break;
951
952         case LFUN_SERVER_GET_XY:
953                 cur.message(from_utf8(
954                         convert<string>(tm.cursorX(cur.top(), cur.boundary()))
955                         + ' ' + convert<string>(tm.cursorY(cur.top(), cur.boundary()))));
956                 break;
957
958         case LFUN_SERVER_SET_XY: {
959                 int x = 0;
960                 int y = 0;
961                 istringstream is(to_utf8(cmd.argument()));
962                 is >> x >> y;
963                 if (!is)
964                         lyxerr << "SETXY: Could not parse coordinates in '"
965                                << to_utf8(cmd.argument()) << endl;
966                 else
967                         tm.setCursorFromCoordinates(cur, x, y);
968                 break;
969         }
970
971         case LFUN_SERVER_GET_FONT:
972                 if (cur.current_font.fontInfo().shape() == ITALIC_SHAPE)
973                         cur.message(from_ascii("E"));
974                 else if (cur.current_font.fontInfo().shape() == SMALLCAPS_SHAPE)
975                         cur.message(from_ascii("N"));
976                 else
977                         cur.message(from_ascii("0"));
978                 break;
979
980         case LFUN_SERVER_GET_LAYOUT:
981                 cur.message(cur.paragraph().layout().name());
982                 break;
983
984         case LFUN_LAYOUT: {
985                 docstring layout = cmd.argument();
986                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
987
988                 Paragraph const & para = cur.paragraph();
989                 docstring const old_layout = para.layout().name();
990                 DocumentClass const & tclass = bv->buffer().params().documentClass();
991
992                 if (layout.empty())
993                         layout = tclass.defaultLayoutName();
994
995                 if (para.forceEmptyLayout()) 
996                         // in this case only the empty layout is allowed
997                         layout = tclass.emptyLayoutName();
998                 else if (para.useEmptyLayout()) {
999                         // in this case, default layout maps to empty layout 
1000                         if (layout == tclass.defaultLayoutName())
1001                                 layout = tclass.emptyLayoutName();
1002                 } else { 
1003                         // otherwise, the empty layout maps to the default
1004                         if (layout == tclass.emptyLayoutName())
1005                                 layout = tclass.defaultLayoutName();
1006                 }
1007
1008                 bool hasLayout = tclass.hasLayout(layout);
1009
1010                 // If the entry is obsolete, use the new one instead.
1011                 if (hasLayout) {
1012                         docstring const & obs = tclass[layout].obsoleted_by();
1013                         if (!obs.empty())
1014                                 layout = obs;
1015                 }
1016
1017                 if (!hasLayout) {
1018                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1019                                 from_utf8(N_(" not known")));
1020                         break;
1021                 }
1022
1023                 bool change_layout = (old_layout != layout);
1024
1025                 if (!change_layout && cur.selection() &&
1026                         cur.selBegin().pit() != cur.selEnd().pit())
1027                 {
1028                         pit_type spit = cur.selBegin().pit();
1029                         pit_type epit = cur.selEnd().pit() + 1;
1030                         while (spit != epit) {
1031                                 if (pars_[spit].layout().name() != old_layout) {
1032                                         change_layout = true;
1033                                         break;
1034                                 }
1035                                 ++spit;
1036                         }
1037                 }
1038
1039                 if (change_layout)
1040                         setLayout(cur, layout);
1041
1042                 break;
1043         }
1044
1045         case LFUN_CLIPBOARD_PASTE:
1046                 cur.clearSelection();
1047                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1048                                cmd.argument() == "paragraph");
1049                 bv->buffer().errors("Paste");
1050                 break;
1051
1052         case LFUN_PRIMARY_SELECTION_PASTE:
1053                 pasteString(cur, theSelection().get(),
1054                             cmd.argument() == "paragraph");
1055                 break;
1056
1057         case LFUN_UNICODE_INSERT: {
1058                 if (cmd.argument().empty())
1059                         break;
1060                 docstring hexstring = cmd.argument();
1061                 if (isHex(hexstring)) {
1062                         char_type c = hexToInt(hexstring);
1063                         if (c >= 32 && c < 0x10ffff) {
1064                                 lyxerr << "Inserting c: " << c << endl;
1065                                 docstring s = docstring(1, c);
1066                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1067                         }
1068                 }
1069                 break;
1070         }
1071
1072         case LFUN_QUOTE_INSERT: {
1073                 Paragraph & par = cur.paragraph();
1074                 pos_type pos = cur.pos();
1075                 BufferParams const & bufparams = bv->buffer().params();
1076                 Layout const & style = par.layout();
1077                 if (!style.pass_thru
1078                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1079                         // this avoids a double undo
1080                         // FIXME: should not be needed, ideally
1081                         if (!cur.selection())
1082                                 cur.recordUndo();
1083                         cap::replaceSelection(cur);
1084                         pos = cur.pos();
1085                         char_type c;
1086                         if (pos == 0)
1087                                 c = ' ';
1088                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1089                                 c = ' ';
1090                         else
1091                                 c = par.getChar(pos - 1);
1092                         string arg = to_utf8(cmd.argument());
1093                         if (arg == "single")
1094                                 cur.insert(new InsetQuotes(c,
1095                                     bufparams.quotes_language,
1096                                     InsetQuotes::SingleQ));
1097                         else
1098                                 cur.insert(new InsetQuotes(c,
1099                                     bufparams.quotes_language,
1100                                     InsetQuotes::DoubleQ));
1101                         cur.posForward();
1102                 }
1103                 else
1104                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1105                 break;
1106         }
1107
1108         case LFUN_DATE_INSERT: {
1109                 string const format = cmd.argument().empty()
1110                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1111                 string const time = formatted_time(current_time(), format);
1112                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1113                 break;
1114         }
1115
1116         case LFUN_MOUSE_TRIPLE:
1117                 if (cmd.button() == mouse_button::button1) {
1118                         tm.cursorHome(cur);
1119                         cur.resetAnchor();
1120                         tm.cursorEnd(cur);
1121                         cur.setSelection();
1122                         bv->cursor() = cur;
1123                 }
1124                 break;
1125
1126         case LFUN_MOUSE_DOUBLE:
1127                 if (cmd.button() == mouse_button::button1) {
1128                         selectWord(cur, WHOLE_WORD_STRICT);
1129                         bv->cursor() = cur;
1130                 }
1131                 break;
1132
1133         // Single-click on work area
1134         case LFUN_MOUSE_PRESS: {
1135                 // Right click on a footnote flag opens float menu
1136                 // FIXME: Why should we clear the selection in this case?
1137                 if (cmd.button() == mouse_button::button3)
1138                         cur.clearSelection();
1139
1140                 bool do_selection = cmd.button() == mouse_button::button1
1141                         && cmd.argument() == "region-select";
1142                 // Set the cursor
1143                 bool update = bv->mouseSetCursor(cur, do_selection);
1144
1145                 // Insert primary selection with middle mouse
1146                 // if there is a local selection in the current buffer,
1147                 // insert this
1148                 if (cmd.button() == mouse_button::button2) {
1149                         if (cap::selection()) {
1150                                 // Copy the selection buffer to the clipboard
1151                                 // stack, because we want it to appear in the
1152                                 // "Edit->Paste recent" menu.
1153                                 cap::copySelectionToStack();
1154
1155                                 cap::pasteSelection(bv->cursor(), 
1156                                                     bv->buffer().errorList("Paste"));
1157                                 bv->buffer().errors("Paste");
1158                                 bv->buffer().markDirty();
1159                                 bv->cursor().finishUndo();
1160                         } else {
1161                                 lyx::dispatch(FuncRequest(LFUN_PRIMARY_SELECTION_PASTE, "paragraph"));
1162                         }
1163                 }
1164
1165                 // we have to update after dEPM triggered
1166                 if (!update && cmd.button() == mouse_button::button1) {
1167                         needsUpdate = false;
1168                         cur.noUpdate();
1169                 }
1170
1171                 break;
1172         }
1173
1174         case LFUN_MOUSE_MOTION: {
1175                 // Only use motion with button 1
1176                 //if (cmd.button() != mouse_button::button1)
1177                 //      return false;
1178
1179                 // ignore motions deeper nested than the real anchor
1180                 Cursor & bvcur = cur.bv().cursor();
1181                 if (!bvcur.anchor_.hasPart(cur)) {
1182                         cur.undispatched();
1183                         break;
1184                 }
1185                 CursorSlice old = bvcur.top();
1186
1187                 int const wh = bv->workHeight();
1188                 int const y = max(0, min(wh - 1, cmd.y));
1189
1190                 tm.setCursorFromCoordinates(cur, cmd.x, y);
1191                 cur.setTargetX(cmd.x);
1192                 if (cmd.y >= wh)
1193                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1194                 else if (cmd.y < 0)
1195                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1196                 // This is to allow jumping over large insets
1197                 if (cur.top() == old) {
1198                         if (cmd.y >= wh)
1199                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1200                         else if (cmd.y < 0)
1201                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1202                 }
1203
1204                 if (cur.top() == old)
1205                         cur.noUpdate();
1206                 else {
1207                         // FIXME: This is brute force! But without it the selected
1208                         // area is not corrected updated while moving the mouse.
1209                         cur.updateFlags(Update::Force | Update::FitCursor);
1210                         // don't set anchor_
1211                         bvcur.setCursor(cur);
1212                         bvcur.selection() = true;
1213                         //lyxerr << "MOTION: " << bv->cursor() << endl;
1214                 }
1215                 break;
1216         }
1217
1218         case LFUN_MOUSE_RELEASE: {
1219                 if (cmd.button() == mouse_button::button2)
1220                         break;
1221
1222                 if (cmd.button() == mouse_button::button1) {
1223                         // if there is new selection, update persistent
1224                         // selection, otherwise, single click does not
1225                         // clear persistent selection buffer
1226                         if (cur.selection()) {
1227                                 // finish selection
1228                                 // if double click, cur is moved to the end of word by selectWord
1229                                 // but bvcur is current mouse position
1230                                 Cursor & bvcur = cur.bv().cursor();
1231                                 bvcur.selection() = true;
1232                         }
1233                         needsUpdate = false;
1234                         cur.noUpdate();
1235                 }
1236
1237                 break;
1238         }
1239
1240         case LFUN_SELF_INSERT: {
1241                 if (cmd.argument().empty())
1242                         break;
1243
1244                 // Automatically delete the currently selected
1245                 // text and replace it with what is being
1246                 // typed in now. Depends on lyxrc settings
1247                 // "auto_region_delete", which defaults to
1248                 // true (on).
1249
1250                 if (lyxrc.auto_region_delete && cur.selection())
1251                         cutSelection(cur, false, false);
1252
1253                 cur.clearSelection();
1254                 Font const old_font = cur.real_current_font;
1255
1256                 docstring::const_iterator cit = cmd.argument().begin();
1257                 docstring::const_iterator end = cmd.argument().end();
1258                 for (; cit != end; ++cit)
1259                         bv->translateAndInsert(*cit, this, cur);
1260
1261                 cur.resetAnchor();
1262                 moveCursor(cur, false);
1263                 break;
1264         }
1265
1266         case LFUN_HYPERLINK_INSERT: {
1267                 InsetCommandParams p(HYPERLINK_CODE);
1268                 docstring content;
1269                 if (cur.selection()) {
1270                         content = cur.selectionAsString(false);
1271                         cutSelection(cur, true, false);
1272                 }
1273                 p["target"] = (cmd.argument().empty()) ?
1274                         content : cmd.argument();
1275                 string const data = InsetCommandMailer::params2string("href", p);
1276                 if (p["target"].empty()) {
1277                         bv->showDialog("href", data);
1278                 } else {
1279                         FuncRequest fr(LFUN_INSET_INSERT, data);
1280                         dispatch(cur, fr);
1281                 }
1282                 break;
1283         }
1284
1285         case LFUN_LABEL_INSERT: {
1286                 InsetCommandParams p(LABEL_CODE);
1287                 // Try to generate a valid label
1288                 p["name"] = (cmd.argument().empty()) ?
1289                         cur.getPossibleLabel() :
1290                         cmd.argument();
1291                 string const data = InsetCommandMailer::params2string("label", p);
1292
1293                 if (cmd.argument().empty()) {
1294                         bv->showDialog("label", data);
1295                 } else {
1296                         FuncRequest fr(LFUN_INSET_INSERT, data);
1297                         dispatch(cur, fr);
1298                 }
1299                 break;
1300         }
1301
1302         case LFUN_INFO_INSERT: {
1303                 Inset * inset = createInset(cur.bv().buffer(), cmd);
1304                 if (!inset)
1305                         break;
1306                 // if an empty inset is created (cmd.argument() is empty)
1307                 // use current selection as parameter.
1308                 if (cmd.argument().empty() && cur.selection()) {
1309                         // use selected text as info to avoid a separate UI
1310                         docstring ds = cur.selectionAsString(false);
1311                         cutSelection(cur, true, false);
1312                         static_cast<InsetInfo *>(inset)->setInfo(to_utf8(ds));
1313                         static_cast<InsetInfo *>(inset)->updateInfo();
1314                 }
1315                 insertInset(cur, inset);
1316                 cur.posForward();
1317                 break;
1318         }
1319 #if 0
1320         case LFUN_LIST_INSERT:
1321 #endif
1322         case LFUN_CAPTION_INSERT:
1323         case LFUN_FOOTNOTE_INSERT:
1324         case LFUN_NOTE_INSERT:
1325         case LFUN_FLEX_INSERT:
1326         case LFUN_BOX_INSERT:
1327         case LFUN_BRANCH_INSERT:
1328         case LFUN_BIBITEM_INSERT:
1329         case LFUN_ERT_INSERT:
1330         case LFUN_LISTING_INSERT:
1331         case LFUN_MARGINALNOTE_INSERT:
1332         case LFUN_OPTIONAL_INSERT:
1333         case LFUN_ENVIRONMENT_INSERT:
1334         case LFUN_INDEX_INSERT:
1335                 // Open the inset, and move the current selection
1336                 // inside it.
1337                 doInsertInset(cur, this, cmd, true, true);
1338                 cur.posForward();
1339                 // Some insets are numbered, others are shown in the outline pane so
1340                 // let's update the labels and the toc backend.
1341                 updateLabels(bv->buffer());
1342                 break;
1343
1344         case LFUN_TABULAR_INSERT:
1345                 // if there were no arguments, just open the dialog
1346                 if (doInsertInset(cur, this, cmd, false, true))
1347                         cur.posForward();
1348                 else
1349                         bv->showDialog("tabularcreate");
1350
1351                 break;
1352
1353         case LFUN_FLOAT_INSERT:
1354         case LFUN_FLOAT_WIDE_INSERT:
1355         case LFUN_WRAP_INSERT: {
1356                 bool content = cur.selection();  // will some text be moved into the inset?
1357
1358                 doInsertInset(cur, this, cmd, true, true);
1359                 cur.posForward();
1360                 ParagraphList & pars = cur.text()->paragraphs();
1361
1362                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1363
1364                 // add a separate paragraph for the caption inset
1365                 pars.push_back(Paragraph());
1366                 pars.back().setInsetOwner(pars[0].inInset());
1367                 pars.back().setEmptyOrDefaultLayout(tclass);
1368                 int cap_pit = pars.size() - 1;
1369
1370                 // if an empty inset was created, we create an additional empty
1371                 // paragraph at the bottom so that the user can choose where to put
1372                 // the graphics (or table).
1373                 if (!content) {
1374                         pars.push_back(Paragraph());
1375                         pars.back().setInsetOwner(pars[0].inInset());
1376                         pars.back().setEmptyOrDefaultLayout(tclass);
1377                 }
1378
1379                 // reposition the cursor to the caption
1380                 cur.pit() = cap_pit;
1381                 cur.pos() = 0;
1382                 // FIXME: This Text/Cursor dispatch handling is a mess!
1383                 // We cannot use Cursor::dispatch here it needs access to up to
1384                 // date metrics.
1385                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1386                 cur.text()->dispatch(cur, cmd_caption);
1387                 cur.updateFlags(Update::Force);
1388                 // FIXME: When leaving the Float (or Wrap) inset we should
1389                 // delete any empty paragraph left above or below the
1390                 // caption.
1391                 break;
1392         }
1393
1394         case LFUN_NOMENCL_INSERT: {
1395                 FuncRequest cmd1 = cmd;
1396                 if (cmd.argument().empty())
1397                         cmd1 = FuncRequest(cmd,
1398                                 bv->cursor().innerText()->getStringToIndex(bv->cursor()));
1399                 Inset * inset = createInset(cur.bv().buffer(), cmd1);
1400                 if (!inset)
1401                         break;
1402                 cur.recordUndo();
1403                 cur.clearSelection();
1404                 insertInset(cur, inset);
1405                 // Show the dialog for the nomenclature entry, since the
1406                 // description entry still needs to be filled in.
1407                 if (cmd.action == LFUN_NOMENCL_INSERT)
1408                         inset->edit(cur, true);
1409                 cur.posForward();
1410                 break;
1411         }
1412
1413         case LFUN_INDEX_PRINT:
1414         case LFUN_NOMENCL_PRINT:
1415         case LFUN_TOC_INSERT:
1416         case LFUN_HFILL_INSERT:
1417         case LFUN_LINE_INSERT:
1418         case LFUN_NEWPAGE_INSERT:
1419         case LFUN_PAGEBREAK_INSERT:
1420         case LFUN_CLEARPAGE_INSERT:
1421         case LFUN_CLEARDOUBLEPAGE_INSERT:
1422                 // do nothing fancy
1423                 doInsertInset(cur, this, cmd, false, false);
1424                 cur.posForward();
1425                 break;
1426
1427         case LFUN_DEPTH_DECREMENT:
1428                 changeDepth(cur, DEC_DEPTH);
1429                 break;
1430
1431         case LFUN_DEPTH_INCREMENT:
1432                 changeDepth(cur, INC_DEPTH);
1433                 break;
1434
1435         case LFUN_MATH_DISPLAY:
1436                 mathDispatch(cur, cmd, true);
1437                 break;
1438
1439         case LFUN_MATH_IMPORT_SELECTION:
1440         case LFUN_MATH_MODE:
1441                 if (cmd.argument() == "on")
1442                         // don't pass "on" as argument
1443                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1444                 else
1445                         mathDispatch(cur, cmd, false);
1446                 break;
1447
1448         case LFUN_MATH_MACRO:
1449                 if (cmd.argument().empty())
1450                         cur.errorMessage(from_utf8(N_("Missing argument")));
1451                 else {
1452                         string s = to_utf8(cmd.argument());
1453                         string const s1 = token(s, ' ', 1);
1454                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1455                         string const s2 = token(s, ' ', 2);
1456                         MacroType type = MacroTypeNewcommand;
1457                         if (s2 == "def")
1458                                 type = MacroTypeDef;
1459                         cur.insert(new MathMacroTemplate(from_utf8(token(s, ' ', 0)), nargs, false, type));
1460                         //cur.nextInset()->edit(cur, true);
1461                 }
1462                 break;
1463
1464         // passthrough hat and underscore outside mathed:
1465         case LFUN_MATH_SUBSCRIPT:
1466                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1467                 break;
1468         case LFUN_MATH_SUPERSCRIPT:
1469                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1470                 break;
1471
1472         case LFUN_MATH_INSERT:
1473         case LFUN_MATH_MATRIX:
1474         case LFUN_MATH_DELIM:
1475         case LFUN_MATH_BIGDELIM: {
1476                 cap::replaceSelection(cur);
1477                 cur.insert(new InsetMathHull(hullSimple));
1478                 checkAndActivateInset(cur, true);
1479                 BOOST_ASSERT(cur.inMathed());
1480                 cur.dispatch(cmd);
1481                 break;
1482         }
1483
1484         case LFUN_FONT_EMPH: {
1485                 Font font(ignore_font, ignore_language);
1486                 font.fontInfo().setEmph(FONT_TOGGLE);
1487                 toggleAndShow(cur, this, font);
1488                 break;
1489         }
1490
1491         case LFUN_FONT_BOLD: {
1492                 Font font(ignore_font, ignore_language);
1493                 font.fontInfo().setSeries(BOLD_SERIES);
1494                 toggleAndShow(cur, this, font);
1495                 break;
1496         }
1497
1498         case LFUN_FONT_NOUN: {
1499                 Font font(ignore_font, ignore_language);
1500                 font.fontInfo().setNoun(FONT_TOGGLE);
1501                 toggleAndShow(cur, this, font);
1502                 break;
1503         }
1504
1505         case LFUN_FONT_TYPEWRITER: {
1506                 Font font(ignore_font, ignore_language);
1507                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1508                 toggleAndShow(cur, this, font);
1509                 break;
1510         }
1511
1512         case LFUN_FONT_SANS: {
1513                 Font font(ignore_font, ignore_language);
1514                 font.fontInfo().setFamily(SANS_FAMILY);
1515                 toggleAndShow(cur, this, font);
1516                 break;
1517         }
1518
1519         case LFUN_FONT_ROMAN: {
1520                 Font font(ignore_font, ignore_language);
1521                 font.fontInfo().setFamily(ROMAN_FAMILY);
1522                 toggleAndShow(cur, this, font);
1523                 break;
1524         }
1525
1526         case LFUN_FONT_DEFAULT: {
1527                 Font font(inherit_font, ignore_language);
1528                 toggleAndShow(cur, this, font);
1529                 break;
1530         }
1531
1532         case LFUN_FONT_UNDERLINE: {
1533                 Font font(ignore_font, ignore_language);
1534                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1535                 toggleAndShow(cur, this, font);
1536                 break;
1537         }
1538
1539         case LFUN_FONT_SIZE: {
1540                 Font font(ignore_font, ignore_language);
1541                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1542                 toggleAndShow(cur, this, font);
1543                 break;
1544         }
1545
1546         case LFUN_LANGUAGE: {
1547                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1548                 if (!lang)
1549                         break;
1550                 Font font(ignore_font, lang);
1551                 toggleAndShow(cur, this, font);
1552                 break;
1553         }
1554
1555         case LFUN_FONT_FREE_APPLY:
1556                 toggleAndShow(cur, this, freefont, toggleall);
1557                 cur.message(_("Character set"));
1558                 break;
1559
1560         // Set the freefont using the contents of \param data dispatched from
1561         // the frontends and apply it at the current cursor location.
1562         case LFUN_FONT_FREE_UPDATE: {
1563                 Font font;
1564                 bool toggle;
1565                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1566                         freefont = font;
1567                         toggleall = toggle;
1568                         toggleAndShow(cur, this, freefont, toggleall);
1569                         cur.message(_("Character set"));
1570                 } else {
1571                         lyxerr << "Argument not ok";
1572                 }
1573                 break;
1574         }
1575
1576         case LFUN_FINISHED_LEFT:
1577                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1578                 // We're leaving an inset, going left. If the inset is LTR, we're 
1579                 // leaving from the front, so we should not move (remain at --- but
1580                 // not in --- the inset). If the inset is RTL, move left, without 
1581                 // entering the inset itself; i.e., move to after the inset.
1582                 if (cur.paragraph().getFontSettings(
1583                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1584                         cursorVisLeft(cur, true);
1585                 break;
1586
1587         case LFUN_FINISHED_RIGHT:
1588                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1589                 // We're leaving an inset, going right. If the inset is RTL, we're 
1590                 // leaving from the front, so we should not move (remain at --- but
1591                 // not in --- the inset). If the inset is LTR, move right, without 
1592                 // entering the inset itself; i.e., move to after the inset.
1593                 if (!cur.paragraph().getFontSettings(
1594                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1595                         cursorVisRight(cur, true);
1596                 break;
1597
1598         case LFUN_FINISHED_BACKWARD:
1599                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1600                 break;
1601
1602         case LFUN_FINISHED_FORWARD:
1603                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1604                 ++cur.pos();
1605                 cur.setCurrentFont();
1606                 break;
1607
1608         case LFUN_LAYOUT_PARAGRAPH: {
1609                 string data;
1610                 params2string(cur.paragraph(), data);
1611                 data = "show\n" + data;
1612                 bv->showDialog("paragraph", data);
1613                 break;
1614         }
1615
1616         case LFUN_PARAGRAPH_UPDATE: {
1617                 string data;
1618                 params2string(cur.paragraph(), data);
1619
1620                 // Will the paragraph accept changes from the dialog?
1621                 bool const accept = 
1622                         cur.inset().allowParagraphCustomization(cur.idx());
1623
1624                 data = "update " + convert<string>(accept) + '\n' + data;
1625                 bv->updateDialog("paragraph", data);
1626                 break;
1627         }
1628
1629         case LFUN_ACCENT_UMLAUT:
1630         case LFUN_ACCENT_CIRCUMFLEX:
1631         case LFUN_ACCENT_GRAVE:
1632         case LFUN_ACCENT_ACUTE:
1633         case LFUN_ACCENT_TILDE:
1634         case LFUN_ACCENT_CEDILLA:
1635         case LFUN_ACCENT_MACRON:
1636         case LFUN_ACCENT_DOT:
1637         case LFUN_ACCENT_UNDERDOT:
1638         case LFUN_ACCENT_UNDERBAR:
1639         case LFUN_ACCENT_CARON:
1640         case LFUN_ACCENT_SPECIAL_CARON:
1641         case LFUN_ACCENT_BREVE:
1642         case LFUN_ACCENT_TIE:
1643         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1644         case LFUN_ACCENT_CIRCLE:
1645         case LFUN_ACCENT_OGONEK:
1646                 theLyXFunc().handleKeyFunc(cmd.action);
1647                 if (!cmd.argument().empty())
1648                         // FIXME: Are all these characters encoded in one byte in utf8?
1649                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1650                 break;
1651
1652         case LFUN_FLOAT_LIST: {
1653                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1654                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1655                         cur.recordUndo();
1656                         if (cur.selection())
1657                                 cutSelection(cur, true, false);
1658                         breakParagraph(cur);
1659
1660                         if (cur.lastpos() != 0) {
1661                                 cursorBackward(cur);
1662                                 breakParagraph(cur);
1663                         }
1664
1665                         //FIXME Check if this should be emptyLayout()
1666                         setLayout(cur, tclass.defaultLayoutName());
1667                         ParagraphParameters p;
1668                         setParagraphs(cur, p);
1669                         insertInset(cur, new InsetFloatList(to_utf8(cmd.argument())));
1670                         cur.posForward();
1671                 } else {
1672                         lyxerr << "Non-existent float type: "
1673                                << to_utf8(cmd.argument()) << endl;
1674                 }
1675                 break;
1676         }
1677
1678         case LFUN_CHANGE_ACCEPT: {
1679                 acceptOrRejectChanges(cur, ACCEPT);
1680                 break;
1681         }
1682
1683         case LFUN_CHANGE_REJECT: {
1684                 acceptOrRejectChanges(cur, REJECT);
1685                 break;
1686         }
1687
1688         case LFUN_THESAURUS_ENTRY: {
1689                 docstring arg = cmd.argument();
1690                 if (arg.empty()) {
1691                         arg = cur.selectionAsString(false);
1692                         // FIXME
1693                         if (arg.size() > 100 || arg.empty()) {
1694                                 // Get word or selection
1695                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
1696                                 arg = cur.selectionAsString(false);
1697                         }
1698                 }
1699                 bv->showDialog("thesaurus", to_utf8(arg));
1700                 break;
1701         }
1702
1703         case LFUN_PARAGRAPH_PARAMS_APPLY: {
1704                 // Given data, an encoding of the ParagraphParameters
1705                 // generated in the Paragraph dialog, this function sets
1706                 // the current paragraph, or currently selected paragraphs,
1707                 // appropriately. 
1708                 // NOTE: This function overrides all existing settings.
1709                 setParagraphs(cur, cmd.argument());
1710                 cur.message(_("Paragraph layout set"));
1711                 break;
1712         }
1713         
1714         case LFUN_PARAGRAPH_PARAMS: {
1715                 // Given data, an encoding of the ParagraphParameters as we'd
1716                 // find them in a LyX file, this function modifies the current paragraph, 
1717                 // or currently selected paragraphs. 
1718                 // NOTE: This function only modifies, and does not override, existing
1719                 // settings.
1720                 setParagraphs(cur, cmd.argument(), true);
1721                 cur.message(_("Paragraph layout set"));
1722                 break;
1723         }
1724
1725         case LFUN_ESCAPE:
1726                 if (cur.selection()) {
1727                         cur.selection() = false;
1728                 } else {
1729                         cur.undispatched();
1730                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
1731                         // correct, but I'm not 100% sure -- dov, 071019
1732                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
1733                 }
1734                 break;
1735
1736         case LFUN_OUTLINE_UP:
1737                 outline(OutlineUp, cur);
1738                 setCursor(cur, cur.pit(), 0);
1739                 updateLabels(cur.buffer());
1740                 needsUpdate = true;
1741                 break;
1742
1743         case LFUN_OUTLINE_DOWN:
1744                 outline(OutlineDown, cur);
1745                 setCursor(cur, cur.pit(), 0);
1746                 updateLabels(cur.buffer());
1747                 needsUpdate = true;
1748                 break;
1749
1750         case LFUN_OUTLINE_IN:
1751                 outline(OutlineIn, cur);
1752                 updateLabels(cur.buffer());
1753                 needsUpdate = true;
1754                 break;
1755
1756         case LFUN_OUTLINE_OUT:
1757                 outline(OutlineOut, cur);
1758                 updateLabels(cur.buffer());
1759                 needsUpdate = true;
1760                 break;
1761
1762         default:
1763                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
1764                 cur.undispatched();
1765                 break;
1766         }
1767
1768         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
1769
1770         // FIXME: The cursor flag is reset two lines below
1771         // so we need to check here if some of the LFUN did touch that.
1772         // for now only Text::erase() and Text::backspace() do that.
1773         // The plan is to verify all the LFUNs and then to remove this
1774         // singleParUpdate boolean altogether.
1775         if (cur.result().update() & Update::Force) {
1776                 singleParUpdate = false;
1777                 needsUpdate = true;
1778         }
1779
1780         // FIXME: the following code should go in favor of fine grained
1781         // update flag treatment.
1782         if (singleParUpdate) {
1783                 // Inserting characters does not change par height in general. So, try
1784                 // to update _only_ this paragraph. BufferView will detect if a full
1785                 // metrics update is needed anyway.
1786                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1787                 return;
1788         }
1789
1790         if (!needsUpdate
1791             && &oldTopSlice.inset() == &cur.inset()
1792             && oldTopSlice.idx() == cur.idx()
1793             && !sel // sel is a backup of cur.selection() at the biginning of the function.
1794             && !cur.selection())
1795                 // FIXME: it would be better if we could just do this
1796                 //
1797                 //if (cur.result().update() != Update::FitCursor)
1798                 //      cur.noUpdate();
1799                 //
1800                 // But some LFUNs do not set Update::FitCursor when needed, so we
1801                 // do it for all. This is not very harmfull as FitCursor will provoke
1802                 // a full redraw only if needed but still, a proper review of all LFUN
1803                 // should be done and this needsUpdate boolean can then be removed.
1804                 cur.updateFlags(Update::FitCursor);
1805         else
1806                 cur.updateFlags(Update::Force | Update::FitCursor);
1807 }
1808
1809
1810 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
1811                         FuncStatus & flag) const
1812 {
1813         BOOST_ASSERT(cur.text() == this);
1814
1815         Font const & font = cur.real_current_font;
1816         FontInfo const & fontinfo = font.fontInfo();
1817         bool enable = true;
1818         InsetCode code = NO_CODE;
1819
1820         switch (cmd.action) {
1821
1822         case LFUN_DEPTH_DECREMENT:
1823                 enable = changeDepthAllowed(cur, DEC_DEPTH);
1824                 break;
1825
1826         case LFUN_DEPTH_INCREMENT:
1827                 enable = changeDepthAllowed(cur, INC_DEPTH);
1828                 break;
1829
1830         case LFUN_APPENDIX:
1831                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
1832                 return true;
1833
1834         case LFUN_BIBITEM_INSERT:
1835                 enable = (cur.paragraph().layout().labeltype == LABEL_BIBLIO
1836                           && cur.pos() == 0);
1837                 break;
1838
1839         case LFUN_DIALOG_SHOW_NEW_INSET:
1840                 if (cmd.argument() == "bibitem")
1841                         code = BIBITEM_CODE;
1842                 else if (cmd.argument() == "bibtex")
1843                         code = BIBTEX_CODE;
1844                 else if (cmd.argument() == "box")
1845                         code = BOX_CODE;
1846                 else if (cmd.argument() == "branch")
1847                         code = BRANCH_CODE;
1848                 else if (cmd.argument() == "citation")
1849                         code = CITE_CODE;
1850                 else if (cmd.argument() == "ert")
1851                         code = ERT_CODE;
1852                 else if (cmd.argument() == "external")
1853                         code = EXTERNAL_CODE;
1854                 else if (cmd.argument() == "float")
1855                         code = FLOAT_CODE;
1856                 else if (cmd.argument() == "graphics")
1857                         code = GRAPHICS_CODE;
1858                 else if (cmd.argument() == "href")
1859                         code = HYPERLINK_CODE;
1860                 else if (cmd.argument() == "include")
1861                         code = INCLUDE_CODE;
1862                 else if (cmd.argument() == "index")
1863                         code = INDEX_CODE;
1864                 else if (cmd.argument() == "nomenclature")
1865                         code = NOMENCL_CODE;
1866                 else if (cmd.argument() == "label")
1867                         code = LABEL_CODE;
1868                 else if (cmd.argument() == "note")
1869                         code = NOTE_CODE;
1870                 else if (cmd.argument() == "ref")
1871                         code = REF_CODE;
1872                 else if (cmd.argument() == "toc")
1873                         code = TOC_CODE;
1874                 else if (cmd.argument() == "vspace")
1875                         code = VSPACE_CODE;
1876                 else if (cmd.argument() == "wrap")
1877                         code = WRAP_CODE;
1878                 else if (cmd.argument() == "listings")
1879                         code = LISTINGS_CODE;
1880                 break;
1881
1882         case LFUN_ERT_INSERT:
1883                 code = ERT_CODE;
1884                 break;
1885         case LFUN_LISTING_INSERT:
1886             code = LISTINGS_CODE;
1887                 break;
1888         case LFUN_FOOTNOTE_INSERT:
1889                 code = FOOT_CODE;
1890                 break;
1891         case LFUN_TABULAR_INSERT:
1892                 code = TABULAR_CODE;
1893                 break;
1894         case LFUN_MARGINALNOTE_INSERT:
1895                 code = MARGIN_CODE;
1896                 break;
1897         case LFUN_FLOAT_INSERT:
1898         case LFUN_FLOAT_WIDE_INSERT:
1899                 code = FLOAT_CODE;
1900                 break;
1901         case LFUN_WRAP_INSERT:
1902                 code = WRAP_CODE;
1903                 break;
1904         case LFUN_FLOAT_LIST:
1905                 code = FLOAT_LIST_CODE;
1906                 break;
1907 #if 0
1908         case LFUN_LIST_INSERT:
1909                 code = LIST_CODE;
1910                 break;
1911 #endif
1912         case LFUN_CAPTION_INSERT:
1913                 code = CAPTION_CODE;
1914                 break;
1915         case LFUN_NOTE_INSERT:
1916                 code = NOTE_CODE;
1917                 break;
1918         case LFUN_FLEX_INSERT: {
1919                 code = FLEX_CODE;
1920                 string s = cmd.getArg(0);
1921                 InsetLayout il = 
1922                         cur.buffer().params().documentClass().insetLayout(from_utf8(s));
1923                 if (il.lyxtype() != "charstyle" &&
1924                     il.lyxtype() != "custom" &&
1925                     il.lyxtype() != "element" &&
1926                     il.lyxtype ()!= "standard")
1927                         enable = false;
1928                 break;
1929                 }
1930         case LFUN_BOX_INSERT:
1931                 code = BOX_CODE;
1932                 break;
1933         case LFUN_BRANCH_INSERT:
1934                 code = BRANCH_CODE;
1935                 if (cur.buffer().masterBuffer()->params().branchlist().empty())
1936                         enable = false;
1937                 break;
1938         case LFUN_LABEL_INSERT:
1939                 code = LABEL_CODE;
1940                 break;
1941         case LFUN_INFO_INSERT:
1942                 code = INFO_CODE;
1943                 break;
1944         case LFUN_OPTIONAL_INSERT:
1945                 code = OPTARG_CODE;
1946                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
1947                         < cur.paragraph().layout().optionalargs;
1948                 break;
1949         case LFUN_ENVIRONMENT_INSERT:
1950                 code = BOX_CODE;
1951                 break;
1952         case LFUN_INDEX_INSERT:
1953                 code = INDEX_CODE;
1954                 break;
1955         case LFUN_INDEX_PRINT:
1956                 code = INDEX_PRINT_CODE;
1957                 break;
1958         case LFUN_NOMENCL_INSERT:
1959                 code = NOMENCL_CODE;
1960                 break;
1961         case LFUN_NOMENCL_PRINT:
1962                 code = NOMENCL_PRINT_CODE;
1963                 break;
1964         case LFUN_TOC_INSERT:
1965                 code = TOC_CODE;
1966                 break;
1967         case LFUN_HYPERLINK_INSERT:
1968                 code = HYPERLINK_CODE;
1969                 break;
1970         case LFUN_QUOTE_INSERT:
1971                 // always allow this, since we will inset a raw quote
1972                 // if an inset is not allowed.
1973                 break;
1974         case LFUN_HFILL_INSERT:
1975         case LFUN_SPECIALCHAR_INSERT:
1976                 code = SPECIALCHAR_CODE;
1977                 break;
1978         case LFUN_SPACE_INSERT:
1979                 // slight hack: we know this is allowed in math mode
1980                 if (cur.inTexted())
1981                         code = SPACE_CODE;
1982                 break;
1983
1984         case LFUN_INSET_MODIFY:
1985                 // We need to disable this, because we may get called for a
1986                 // tabular cell via
1987                 // InsetTabular::getStatus() -> InsetText::getStatus()
1988                 // and we don't handle LFUN_INSET_MODIFY.
1989                 enable = false;
1990                 break;
1991
1992         case LFUN_FONT_EMPH:
1993                 flag.setOnOff(fontinfo.emph() == FONT_ON);
1994                 return true;
1995
1996         case LFUN_FONT_NOUN:
1997                 flag.setOnOff(fontinfo.noun() == FONT_ON);
1998                 return true;
1999
2000         case LFUN_FONT_BOLD:
2001                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2002                 return true;
2003
2004         case LFUN_FONT_SANS:
2005                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2006                 return true;
2007
2008         case LFUN_FONT_ROMAN:
2009                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2010                 return true;
2011
2012         case LFUN_FONT_TYPEWRITER:
2013                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2014                 return true;
2015
2016         case LFUN_CUT:
2017         case LFUN_COPY:
2018                 enable = cur.selection();
2019                 break;
2020
2021         case LFUN_PASTE: {
2022                 if (cmd.argument().empty()) {
2023                         if (theClipboard().isInternal())
2024                                 enable = cap::numberOfSelections() > 0;
2025                         else
2026                                 enable = !theClipboard().empty();
2027                         break;
2028                 }
2029                 
2030                 // we have an argument
2031                 string const arg = to_utf8(cmd.argument());
2032                 if (isStrUnsignedInt(arg)) {
2033                         // it's a number and therefore means the internal stack
2034                         unsigned int n = convert<unsigned int>(arg);
2035                         enable = cap::numberOfSelections() > n;
2036                         break;
2037                 }
2038                 
2039                 // explicit graphics type?
2040                 if ((arg == "pdf" && theClipboard().hasGraphicsContents(Clipboard::PdfGraphicsType))
2041                     || (arg == "png" && theClipboard().hasGraphicsContents(Clipboard::PngGraphicsType))
2042                     || (arg == "jpeg" && theClipboard().hasGraphicsContents(Clipboard::JpegGraphicsType))
2043                     || (arg == "linkback" && theClipboard().hasGraphicsContents(Clipboard::LinkBackGraphicsType))) {
2044                         enable = true;
2045                         break;
2046                 }
2047                 
2048                 // unknown argument
2049                 enable = false;
2050                 break;
2051          }
2052
2053         case LFUN_CLIPBOARD_PASTE:
2054                 enable = !theClipboard().empty();
2055                 break;
2056
2057         case LFUN_PRIMARY_SELECTION_PASTE:
2058                 enable = cur.selection() || !theSelection().empty();
2059                 break;
2060
2061         case LFUN_PARAGRAPH_MOVE_UP:
2062                 enable = cur.pit() > 0 && !cur.selection();
2063                 break;
2064
2065         case LFUN_PARAGRAPH_MOVE_DOWN:
2066                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2067                 break;
2068
2069         case LFUN_INSET_DISSOLVE:
2070                 if (!cmd.argument().empty()) {
2071                         InsetLayout il = cur.inset().getLayout(cur.buffer().params());
2072                         enable = cur.inset().lyxCode() == FLEX_CODE
2073                                  && il.lyxtype() == to_utf8(cmd.argument());
2074                 } else {
2075                         enable = !isMainText(cur.bv().buffer()) 
2076                                  && cur.inset().nargs() == 1;
2077                 }
2078                 break;
2079
2080         case LFUN_CHANGE_ACCEPT:
2081         case LFUN_CHANGE_REJECT:
2082                 // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2083                 // In principle, these LFUNs should only be enabled if there
2084                 // is a change at the current position/in the current selection.
2085                 // However, without proper optimizations, this will inevitably
2086                 // result in unacceptable performance - just imagine a user who
2087                 // wants to select the complete content of a long document.
2088                 enable = true;
2089                 break;
2090
2091         case LFUN_OUTLINE_UP:
2092         case LFUN_OUTLINE_DOWN:
2093         case LFUN_OUTLINE_IN:
2094         case LFUN_OUTLINE_OUT:
2095                 enable = (cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC);
2096                 break;
2097
2098         case LFUN_WORD_DELETE_FORWARD:
2099         case LFUN_WORD_DELETE_BACKWARD:
2100         case LFUN_LINE_DELETE:
2101         case LFUN_WORD_FORWARD:
2102         case LFUN_WORD_BACKWARD:
2103         case LFUN_WORD_RIGHT:
2104         case LFUN_WORD_LEFT:
2105         case LFUN_CHAR_FORWARD:
2106         case LFUN_CHAR_FORWARD_SELECT:
2107         case LFUN_CHAR_BACKWARD:
2108         case LFUN_CHAR_BACKWARD_SELECT:
2109         case LFUN_CHAR_LEFT:
2110         case LFUN_CHAR_LEFT_SELECT:
2111         case LFUN_CHAR_RIGHT:
2112         case LFUN_CHAR_RIGHT_SELECT:
2113         case LFUN_UP:
2114         case LFUN_UP_SELECT:
2115         case LFUN_DOWN:
2116         case LFUN_DOWN_SELECT:
2117         case LFUN_PARAGRAPH_UP_SELECT:
2118         case LFUN_PARAGRAPH_DOWN_SELECT:
2119         case LFUN_LINE_BEGIN_SELECT:
2120         case LFUN_LINE_END_SELECT:
2121         case LFUN_WORD_FORWARD_SELECT:
2122         case LFUN_WORD_BACKWARD_SELECT:
2123         case LFUN_WORD_RIGHT_SELECT:
2124         case LFUN_WORD_LEFT_SELECT:
2125         case LFUN_WORD_SELECT:
2126         case LFUN_PARAGRAPH_UP:
2127         case LFUN_PARAGRAPH_DOWN:
2128         case LFUN_LINE_BEGIN:
2129         case LFUN_LINE_BREAK:
2130         case LFUN_LINE_END:
2131         case LFUN_NEW_LINE:
2132         case LFUN_CHAR_DELETE_FORWARD:
2133         case LFUN_DELETE_FORWARD_SKIP:
2134         case LFUN_CHAR_DELETE_BACKWARD:
2135         case LFUN_DELETE_BACKWARD_SKIP:
2136         case LFUN_BREAK_PARAGRAPH:
2137         case LFUN_BREAK_PARAGRAPH_SKIP:
2138         case LFUN_PARAGRAPH_SPACING:
2139         case LFUN_INSET_INSERT:
2140         case LFUN_WORD_UPCASE:
2141         case LFUN_WORD_LOWCASE:
2142         case LFUN_WORD_CAPITALIZE:
2143         case LFUN_CHARS_TRANSPOSE:
2144         case LFUN_SERVER_GET_XY:
2145         case LFUN_SERVER_SET_XY:
2146         case LFUN_SERVER_GET_FONT:
2147         case LFUN_SERVER_GET_LAYOUT:
2148         case LFUN_LAYOUT:
2149         case LFUN_DATE_INSERT:
2150         case LFUN_SELF_INSERT:
2151         case LFUN_LINE_INSERT:
2152         case LFUN_NEWPAGE_INSERT:
2153         case LFUN_PAGEBREAK_INSERT:
2154         case LFUN_CLEARPAGE_INSERT:
2155         case LFUN_CLEARDOUBLEPAGE_INSERT:
2156         case LFUN_MATH_DISPLAY:
2157         case LFUN_MATH_IMPORT_SELECTION:
2158         case LFUN_MATH_MODE:
2159         case LFUN_MATH_MACRO:
2160         case LFUN_MATH_MATRIX:
2161         case LFUN_MATH_DELIM:
2162         case LFUN_MATH_BIGDELIM:
2163         case LFUN_MATH_INSERT:
2164         case LFUN_MATH_SUBSCRIPT:
2165         case LFUN_MATH_SUPERSCRIPT:
2166         case LFUN_FONT_DEFAULT:
2167         case LFUN_FONT_UNDERLINE:
2168         case LFUN_FONT_SIZE:
2169         case LFUN_LANGUAGE:
2170         case LFUN_FONT_FREE_APPLY:
2171         case LFUN_FONT_FREE_UPDATE:
2172         case LFUN_LAYOUT_PARAGRAPH:
2173         case LFUN_PARAGRAPH_UPDATE:
2174         case LFUN_ACCENT_UMLAUT:
2175         case LFUN_ACCENT_CIRCUMFLEX:
2176         case LFUN_ACCENT_GRAVE:
2177         case LFUN_ACCENT_ACUTE:
2178         case LFUN_ACCENT_TILDE:
2179         case LFUN_ACCENT_CEDILLA:
2180         case LFUN_ACCENT_MACRON:
2181         case LFUN_ACCENT_DOT:
2182         case LFUN_ACCENT_UNDERDOT:
2183         case LFUN_ACCENT_UNDERBAR:
2184         case LFUN_ACCENT_CARON:
2185         case LFUN_ACCENT_SPECIAL_CARON:
2186         case LFUN_ACCENT_BREVE:
2187         case LFUN_ACCENT_TIE:
2188         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2189         case LFUN_ACCENT_CIRCLE:
2190         case LFUN_ACCENT_OGONEK:
2191         case LFUN_THESAURUS_ENTRY:
2192         case LFUN_PARAGRAPH_PARAMS_APPLY:
2193         case LFUN_PARAGRAPH_PARAMS:
2194         case LFUN_ESCAPE:
2195         case LFUN_BUFFER_END:
2196         case LFUN_BUFFER_BEGIN:
2197         case LFUN_BUFFER_BEGIN_SELECT:
2198         case LFUN_BUFFER_END_SELECT:
2199         case LFUN_UNICODE_INSERT:
2200                 // these are handled in our dispatch()
2201                 enable = true;
2202                 break;
2203
2204         default:
2205                 return false;
2206         }
2207
2208         if (code != NO_CODE
2209             && (cur.empty() || !cur.inset().insetAllowed(code)))
2210                 enable = false;
2211
2212         flag.enabled(enable);
2213         return true;
2214 }
2215
2216
2217 void Text::pasteString(Cursor & cur, docstring const & clip,
2218                 bool asParagraphs)
2219 {
2220         cur.clearSelection();
2221         if (!clip.empty()) {
2222                 cur.recordUndo();
2223                 if (asParagraphs)
2224                         insertStringAsParagraphs(cur, clip);
2225                 else
2226                         insertStringAsLines(cur, clip);
2227         }
2228 }
2229
2230 } // namespace lyx