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