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