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