]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
tentative fix for #177; small things
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #ifdef __GNUG__
4 #pragma implementation
5 #endif
6
7 #include "BufferView_pimpl.h"
8 #include "WorkArea.h"
9 #include "lyxscreen.h"
10 #include "lyxtext.h"
11 #include "lyxrow.h"
12 #include "paragraph.h"
13 #include "LyXView.h"
14 #include "commandtags.h"
15 #include "lyxfunc.h"
16 #include "debug.h"
17 #include "font.h"
18 #include "bufferview_funcs.h"
19 #include "TextCache.h"
20 #include "bufferlist.h"
21 #include "lyxrc.h"
22 #include "intl.h"
23 // added for Dispatch functions
24 #include "lyx_cb.h"
25 #include "lyx_main.h"
26 #include "FloatList.h"
27 #include "gettext.h"
28 #include "ParagraphParameters.h"
29 #include "undo_funcs.h"
30 #include "lyxtextclasslist.h"
31
32 #include "frontends/Dialogs.h"
33 #include "frontends/Alert.h"
34 #include "frontends/FileDialog.h"
35
36 #include "insets/insetbib.h"
37 #include "insets/insettext.h"
38 #include "insets/inseturl.h"
39 #include "insets/insetlatexaccent.h"
40 #include "insets/insettoc.h"
41 #include "insets/insetref.h"
42 #include "insets/insetparent.h"
43 #include "insets/insetindex.h"
44 #include "insets/insetnote.h"
45 #include "insets/insetinclude.h"
46 #include "insets/insetcite.h"
47 #include "insets/insetert.h"
48 #include "insets/insetexternal.h"
49 #include "insets/insetgraphics.h"
50 #include "insets/insetfoot.h"
51 #include "insets/insetmarginal.h"
52 #include "insets/insetminipage.h"
53 #include "insets/insetfloat.h"
54 #include "insets/insettabular.h"
55 #if 0
56 #include "insets/insettheorem.h"
57 #include "insets/insetlist.h"
58 #endif
59 #include "insets/insetcaption.h"
60 #include "insets/insetfloatlist.h"
61 #include "insets/insetspecialchar.h"
62
63 #include "mathed/formulabase.h"
64
65 #include "support/LAssert.h"
66 #include "support/lstrings.h"
67 #include "support/filetools.h"
68 #include "support/lyxfunctional.h"
69
70 #include <ctime>
71 #include <unistd.h>
72 #include <sys/wait.h>
73 #include <clocale>
74
75
76 extern lyx::layout_type current_layout;
77
78 using std::vector;
79 using std::find_if;
80 using std::find;
81 using std::pair;
82 using std::endl;
83 using std::make_pair;
84 using std::min;
85 using SigC::slot;
86
87 using lyx::pos_type;
88 using lyx::layout_type;
89 using lyx::textclass_type;
90
91 /* the selection possible is needed, that only motion events are 
92  * used, where the bottom press event was on the drawing area too */
93 bool selection_possible = false;
94
95 extern BufferList bufferlist;
96 extern char ascii_type;
97
98 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
99
100
101 namespace {
102
103 const unsigned int saved_positions_num = 20;
104
105 inline
106 void waitForX()
107 {
108         XSync(fl_get_display(), 0);
109 }
110
111
112 void SetXtermCursor(Window win)
113 {
114         static Cursor cursor;
115         static bool cursor_undefined = true;
116         if (cursor_undefined) {
117                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
118                 XFlush(fl_get_display());
119                 cursor_undefined = false;
120         }
121         XDefineCursor(fl_get_display(), win, cursor);
122         XFlush(fl_get_display());
123 }
124
125 } // anon namespace
126
127
128 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
129              int xpos, int ypos, int width, int height)
130         : bv_(b), owner_(o), buffer_(0),
131           current_scrollbar_value(0), cursor_timeout(400),
132           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
133           inset_slept(false)
134 {
135         // Setup the signals
136         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
137         workarea_.workAreaExpose
138                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
139         workarea_.workAreaEnter
140                 .connect(slot(this, &BufferView::Pimpl::enterView));
141         workarea_.workAreaLeave
142                 .connect(slot(this, &BufferView::Pimpl::leaveView));
143         workarea_.workAreaButtonPress
144                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
145         workarea_.workAreaButtonRelease
146                 .connect(slot(this,
147                               &BufferView::Pimpl::workAreaButtonRelease));
148         workarea_.workAreaMotionNotify
149                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
150         workarea_.workAreaDoubleClick
151                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
152         workarea_.workAreaTripleClick
153                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
154         workarea_.workAreaKeyPress
155                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
156         workarea_.selectionRequested
157                 .connect(slot(this, &BufferView::Pimpl::selectionRequested)); 
158         workarea_.selectionLost
159                 .connect(slot(this, &BufferView::Pimpl::selectionLost));
160         
161         cursor_timeout.timeout.connect(slot(this,
162                                             &BufferView::Pimpl::cursorToggle));
163         cursor_timeout.start();
164         workarea_.setFocus();
165         saved_positions.resize(saved_positions_num);
166 }
167
168
169 Painter & BufferView::Pimpl::painter() 
170 {
171         return workarea_.getPainter();
172 }
173
174
175 void BufferView::Pimpl::buffer(Buffer * b)
176 {
177         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
178                             << b << ")" << endl;
179         if (buffer_) {
180                 insetSleep();
181                 buffer_->delUser(bv_);
182
183                 // Put the old text into the TextCache, but
184                 // only if the buffer is still loaded.
185                 // Also set the owner of the test to 0
186                 //              bv_->text->owner(0);
187                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
188                 if (lyxerr.debugging())
189                         textcache.show(lyxerr, "BufferView::buffer");
190                 
191                 bv_->text = 0;
192         }
193
194         // Set current buffer
195         buffer_ = b;
196
197         if (bufferlist.getState() == BufferList::CLOSING) return;
198         
199         // Nuke old image
200         // screen is always deleted when the buffer is changed.
201         screen_.reset(0);
202
203         // If we are closing the buffer, use the first buffer as current
204         if (!buffer_) {
205                 buffer_ = bufferlist.first();
206         }
207
208         if (buffer_) {
209                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
210                 buffer_->addUser(bv_);
211                 // If we don't have a text object for this, we make one
212                 if (bv_->text == 0) {
213                         resizeCurrentBuffer();
214                 } else {
215                         updateScreen();
216                         updateScrollbar();
217                 }
218                 bv_->text->first = screen_->topCursorVisible(bv_->text);
219                 owner_->updateMenubar();
220                 owner_->updateToolbar();
221                 // Similarly, buffer-dependent dialogs should be updated or
222                 // hidden. This should go here because some dialogs (eg ToC)
223                 // require bv_->text.
224                 owner_->getDialogs()->updateBufferDependent(true);
225                 redraw();
226                 insetWakeup();
227         } else {
228                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
229                 owner_->updateMenubar();
230                 owner_->updateToolbar();
231                 owner_->getDialogs()->hideBufferDependent();
232                 updateScrollbar();
233                 workarea_.redraw();
234
235                 // Also remove all remaining text's from the testcache.
236                 // (there should not be any!) (if there is any it is a
237                 // bug!)
238                 if (lyxerr.debugging())
239                         textcache.show(lyxerr, "buffer delete all");
240                 textcache.clear();
241         }
242         // should update layoutchoice even if we don't have a buffer.
243         owner_->updateLayoutChoice();
244
245         owner_->updateWindowTitle();
246 }
247
248
249 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
250 {
251         workarea_.resize(xpos, ypos, width, height);
252         update(bv_->text, SELECT);
253         redraw();
254 }
255
256
257 void BufferView::Pimpl::resize()
258 {
259         if (buffer_)
260                 resizeCurrentBuffer();
261 }
262
263
264 void BufferView::Pimpl::redraw()
265 {
266         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
267         workarea_.redraw();
268 }
269
270
271 bool BufferView::Pimpl::fitCursor()
272 {
273         lyx::Assert(screen_.get());
274
275         bool ret;
276
277         if (bv_->theLockingInset()) {
278                 bv_->theLockingInset()->fitInsetCursor(bv_);
279                 ret = true;
280         } else {
281                 ret = screen_->fitCursor(bv_->text, bv_);
282         }
283
284         bv_->owner()->getDialogs()->updateParagraph();
285         if (ret)
286             updateScrollbar();
287         return ret;
288 }
289
290
291 void BufferView::Pimpl::redoCurrentBuffer()
292 {
293         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
294         if (buffer_ && bv_->text) {
295                 resize();
296                 owner_->updateLayoutChoice();
297         }
298 }
299
300
301 int BufferView::Pimpl::resizeCurrentBuffer()
302 {
303         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
304         
305         Paragraph * par = 0;
306         Paragraph * selstartpar = 0;
307         Paragraph * selendpar = 0;
308         UpdatableInset * the_locking_inset = 0;
309         
310         pos_type pos = 0;
311         pos_type selstartpos = 0;
312         pos_type selendpos = 0;
313         bool selection = false;
314         bool mark_set  = false;
315
316         owner_->prohibitInput();
317
318         owner_->message(_("Formatting document..."));
319
320         if (bv_->text) {
321                 par = bv_->text->cursor.par();
322                 pos = bv_->text->cursor.pos();
323                 selstartpar = bv_->text->selection.start.par();
324                 selstartpos = bv_->text->selection.start.pos();
325                 selendpar = bv_->text->selection.end.par();
326                 selendpos = bv_->text->selection.end.pos();
327                 selection = bv_->text->selection.set();
328                 mark_set = bv_->text->selection.mark();
329                 the_locking_inset = bv_->theLockingInset();
330                 delete bv_->text;
331                 bv_->text = new LyXText(bv_);
332                 bv_->text->init(bv_);
333         } else {
334                 // See if we have a text in TextCache that fits
335                 // the new buffer_ with the correct width.
336                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
337                 if (bv_->text) {
338                         if (lyxerr.debugging()) {
339                                 lyxerr << "Found a LyXText that fits:\n";
340                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
341                         }
342                         // Set the owner of the newly found text
343                         //      bv_->text->owner(bv_);
344                         if (lyxerr.debugging())
345                                 textcache.show(lyxerr, "resizeCurrentBuffer");
346                 } else {
347                         bv_->text = new LyXText(bv_);
348                         bv_->text->init(bv_);
349                 }
350         }
351         updateScreen();
352
353         if (par) {
354                 bv_->text->selection.set(true);
355                 /* at this point just to avoid the Delete-Empty-Paragraph
356                  * Mechanism when setting the cursor */
357                 bv_->text->selection.mark(mark_set);
358                 if (selection) {
359                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
360                         bv_->text->selection.cursor = bv_->text->cursor;
361                         bv_->text->setCursor(bv_, selendpar, selendpos);
362                         bv_->text->setSelection(bv_);
363                         bv_->text->setCursor(bv_, par, pos);
364                 } else {
365                         bv_->text->setCursor(bv_, par, pos);
366                         bv_->text->selection.cursor = bv_->text->cursor;
367                         bv_->text->selection.set(false);
368                 }
369                 // remake the inset locking
370                 bv_->theLockingInset(the_locking_inset);
371         }
372         bv_->text->first = screen_->topCursorVisible(bv_->text);
373 #if 0
374         buffer_->resizeInsets(bv_);
375 #endif
376         // this will scroll the screen such that the cursor becomes visible
377         updateScrollbar();
378         redraw();
379
380         setState();
381         owner_->allowInput();
382
383         /// clear the "Formatting Document" message 
384         owner_->message("");
385
386         return 0;
387 }
388
389
390 void BufferView::Pimpl::updateScreen()
391 {
392         // Regenerate the screen.
393         screen_.reset(new LyXScreen(workarea_));
394 }
395
396
397 void BufferView::Pimpl::updateScrollbar()
398 {
399         /* If the text is smaller than the working area, the scrollbar
400          * maximum must be the working area height. No scrolling will 
401          * be possible */
402         if (!bv_->text) {
403                 workarea_.setScrollbar(0, 1.0);
404                 return;
405         }
406
407         long const text_height = bv_->text->height;
408         long const work_height = workarea_.height();
409
410         if (text_height <= work_height) {
411                 workarea_.setScrollbarBounds(0.0, 0.0);
412                 current_scrollbar_value = bv_->text->first;
413                 workarea_.setScrollbar(current_scrollbar_value, 1.0);
414                 return;
415         }
416         
417         double const lineh = bv_->text->defaultHeight();
418         double const slider_size =
419                 (text_height == 0) ? 1.0 : 1.0 / double(text_height);
420         
421         static long old_text_height;
422         static double old_lineh;
423         static double old_slider_size;
424
425         if (text_height != old_text_height) {
426                 workarea_.setScrollbarBounds(0.0,
427                                              text_height - work_height);
428                 old_text_height = text_height;
429         }
430         if (lineh != old_lineh) {
431                 workarea_.setScrollbarIncrements(lineh);
432                 old_lineh = lineh;
433         }
434         if (current_scrollbar_value != bv_->text->first
435             || slider_size != old_slider_size) {
436                 current_scrollbar_value = bv_->text->first;
437                 workarea_.setScrollbar(current_scrollbar_value, slider_size);
438                 old_slider_size = slider_size;
439         }
440 }
441
442
443 // Callback for scrollbar slider
444 void BufferView::Pimpl::scrollCB(double value)
445 {
446         if (!buffer_) return;
447
448         current_scrollbar_value = long(value);
449
450         if (current_scrollbar_value < 0)
451                 current_scrollbar_value = 0;
452    
453         if (!screen_.get())
454                 return;
455
456         screen_->draw(bv_->text, bv_, current_scrollbar_value);
457
458         if (!lyxrc.cursor_follows_scrollbar) {
459                 waitForX();
460                 return;
461         }
462  
463         LyXText * vbt = bv_->text;
464  
465         int const height = vbt->defaultHeight();
466         int const first = static_cast<int>((bv_->text->first + height));
467         int const last = static_cast<int>((bv_->text->first + workarea_.height() - height));
468
469         if (vbt->cursor.y() < first)
470                 vbt->setCursorFromCoordinates(bv_, 0, first);
471         else if (vbt->cursor.y() > last)
472                 vbt->setCursorFromCoordinates(bv_, 0, last);
473
474         waitForX();
475 }
476
477
478 int BufferView::Pimpl::scrollUp(long time)
479 {
480         if (!buffer_) return 0;
481         if (!screen_.get()) return 0;
482    
483         double value = workarea_.getScrollbarValue();
484    
485         if (value == 0) return 0;
486
487         float add_value =  (bv_->text->defaultHeight()
488                             + float(time) * float(time) * 0.125);
489    
490         if (add_value > workarea_.height())
491                 add_value = float(workarea_.height() -
492                                   bv_->text->defaultHeight());
493    
494         value -= add_value;
495
496         if (value < 0)
497                 value = 0;
498    
499         workarea_.setScrollbarValue(value);
500    
501         scrollCB(value); 
502         return 0;
503 }
504
505
506 int BufferView::Pimpl::scrollDown(long time)
507 {
508         if (!buffer_) return 0;
509         if (!screen_.get()) return 0;
510    
511         double value = workarea_.getScrollbarValue();
512         pair<float, float> p = workarea_.getScrollbarBounds();
513         double const max = p.second;
514         
515         if (value == max) return 0;
516
517         float add_value =  (bv_->text->defaultHeight()
518                             + float(time) * float(time) * 0.125);
519    
520         if (add_value > workarea_.height())
521                 add_value = float(workarea_.height() -
522                                   bv_->text->defaultHeight());
523    
524         value += add_value;
525    
526         if (value > max)
527                 value = max;
528
529         workarea_.setScrollbarValue(value);
530         
531         scrollCB(value); 
532         return 0;
533 }
534
535
536 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
537 {
538         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
539 }
540
541
542 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
543 {
544         // Only use motion with button 1
545         if (!(state & Button1MotionMask))
546                 return;
547
548         if (!buffer_ || !screen_.get()) return;
549
550         // Check for inset locking
551         if (bv_->theLockingInset()) {
552                 LyXCursor cursor = bv_->text->cursor;
553                 LyXFont font = bv_->text->getFont(buffer_,
554                                                   cursor.par(), cursor.pos());
555                 int width = bv_->theLockingInset()->width(bv_, font);
556                 int inset_x = font.isVisibleRightToLeft()
557                         ? cursor.x() - width : cursor.x();
558                 int start_x = inset_x + bv_->theLockingInset()->scroll();
559                 bv_->theLockingInset()->
560                         insetMotionNotify(bv_,
561                                           x - start_x,
562                                           y - cursor.y() + bv_->text->first,
563                                           state);
564                 return;
565         }
566    
567         /* The test for not selection possible is needed, that only motion
568            events are used, where the bottom press event was on
569            the drawing area too */
570         if (!selection_possible)
571                 return;
572  
573         screen_->hideCursor();
574
575         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first);
576       
577         if (!bv_->text->selection.set())
578                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
579       
580         bv_->text->setSelection(bv_);
581         screen_->toggleToggle(bv_->text, bv_);
582         fitCursor();
583         showCursor();
584 }
585
586
587 // Single-click on work area
588 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
589                                             unsigned int button)
590 {
591         if (!buffer_ || !screen_.get()) return;
592
593         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos);
594
595         // ok ok, this is a hack.
596         if (button == 4 || button == 5) {
597                 switch (button) {
598                 case 4:
599                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
600                         break;
601                 case 5:
602                         scrollDown(lyxrc.wheel_jump);
603                         break;
604                 }
605         }
606         
607         if (bv_->theLockingInset()) {
608                 // We are in inset locking mode
609                 
610                 /* Check whether the inset was hit. If not reset mode,
611                    otherwise give the event to the inset */
612                 if (inset_hit == bv_->theLockingInset()) {
613                         bv_->theLockingInset()->
614                                 insetButtonPress(bv_,xpos, ypos,button);
615                         return;
616                 } else {
617                         bv_->unlockInset(bv_->theLockingInset());
618                 }
619         }
620         
621         if (!inset_hit)
622                 selection_possible = true;
623         screen_->hideCursor();
624
625         int const screen_first = bv_->text->first;
626         
627         // Middle button press pastes if we have a selection
628         bool paste_internally = false;
629         if (button == 2
630             && bv_->text->selection.set()) {
631                 owner_->getLyXFunc()->dispatch(LFUN_COPY);
632                 paste_internally = true;
633         }
634         
635         // Clear the selection
636         screen_->toggleSelection(bv_->text, bv_);
637         bv_->text->clearSelection();
638         bv_->text->fullRebreak(bv_);
639         update();
640         updateScrollbar();
641         
642         // Single left click in math inset?
643         if (isHighlyEditableInset(inset_hit)) {
644                 // Highly editable inset, like math
645                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
646                 selection_possible = false;
647                 owner_->updateLayoutChoice();
648                 owner_->message(inset->editMessage());
649                 // IMO the inset has to be first in edit-mode and then we send the
650                 // button press. (Jug 20020222)
651                 inset->edit(bv_); //, xpos, ypos, button);
652                 inset->insetButtonPress(bv_, xpos, ypos, button);
653                 return;
654         } 
655         
656         // Right click on a footnote flag opens float menu
657         if (button == 3) { 
658                 selection_possible = false;
659                 return;
660         }
661         
662         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
663                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
664         finishUndo();
665         bv_->text->selection.cursor = bv_->text->cursor;
666         bv_->text->cursor.x_fix(bv_->text->cursor.x());
667         
668         owner_->updateLayoutChoice();
669         if (fitCursor()) {
670                 selection_possible = false;
671         }
672         
673         // Insert primary selection with middle mouse
674         // if there is a local selection in the current buffer,
675         // insert this
676         if (button == 2) {
677                 if (paste_internally)
678                         owner_->getLyXFunc()->dispatch(LFUN_PASTE);
679                 else
680                         owner_->getLyXFunc()->dispatch(LFUN_PASTESELECTION,
681                                                        "paragraph");
682                 selection_possible = false;
683                 return;
684         }
685 }
686
687
688 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
689 {
690         // select a word
691         if (!buffer_)
692                 return;
693
694         LyXText * text = bv_->getLyXText();
695
696         if (text->bv_owner && bv_->theLockingInset())
697                 return;
698
699         if (screen_.get() && button == 1) {
700                 if (text->bv_owner) {
701                         screen_->hideCursor();
702                         screen_->toggleSelection(text, bv_);
703                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
704                         screen_->toggleSelection(text, bv_, false);
705                 } else {
706                         text->selectWord(bv_, LyXText::WHOLE_WORD_STRICT);
707                 }
708                 /* This will fit the cursor on the screen
709                  * if necessary */
710                 update(text, BufferView::SELECT|BufferView::FITCUR);
711         }
712 }
713
714
715 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
716 {
717         // select a line
718         if (!buffer_)
719                 return;
720
721         LyXText * text = bv_->getLyXText();
722
723         if (text->bv_owner && bv_->theLockingInset())
724             return;
725
726         if (screen_.get() && (button == 1)) {
727                 if (text->bv_owner) {
728                         screen_->hideCursor();
729                         screen_->toggleSelection(text, bv_);
730                 }
731                 text->cursorHome(bv_);
732                 text->selection.cursor = text->cursor;
733                 text->cursorEnd(bv_);
734                 text->setSelection(bv_);
735                 if (text->bv_owner) {
736                         screen_->toggleSelection(text, bv_, false);
737                 }
738                 /* This will fit the cursor on the screen
739                  * if necessary */
740                 update(text, BufferView::SELECT|BufferView::FITCUR);
741         }
742 }
743
744
745 void BufferView::Pimpl::selectionRequested()
746 {
747         if (!available())
748                 return;
749  
750         string const sel(bv_->getLyXText()->selectionAsString(bv_->buffer(),
751                                                               false)); 
752         if (!sel.empty()) {
753                 workarea_.putClipboard(sel);
754         }
755 }
756
757  
758 void BufferView::Pimpl::selectionLost()
759 {
760         hideCursor();
761         toggleSelection();
762         bv_->getLyXText()->clearSelection();
763         showCursor(); 
764 }
765
766  
767 void BufferView::Pimpl::enterView()
768 {
769         if (active() && available()) {
770                 SetXtermCursor(workarea_.getWin());
771                 using_xterm_cursor = true;
772         }
773 }
774
775
776 void BufferView::Pimpl::leaveView()
777 {
778         if (using_xterm_cursor) {
779                 XUndefineCursor(fl_get_display(), workarea_.getWin());
780                 using_xterm_cursor = false;
781         }
782 }
783
784
785 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
786                                               unsigned int button)
787 {
788         if (!buffer_ || !screen_.get()) return;
789
790         // If we hit an inset, we have the inset coordinates in these
791         // and inset_hit points to the inset.  If we do not hit an
792         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
793         Inset * inset_hit = checkInsetHit(bv_->text, x, y);
794
795         if (bv_->theLockingInset()) {
796                 // We are in inset locking mode.
797
798                 /* LyX does a kind of work-area grabbing for insets.
799                    Only a ButtonPress Event outside the inset will 
800                    force a insetUnlock. */
801                 bv_->theLockingInset()->
802                         insetButtonRelease(bv_, x, y, button);
803                 return;
804         }
805         
806         selection_possible = false;
807         
808         if (button == 2)
809                 return;
810
811         // finish selection
812         if (button == 1) {
813                 workarea_.haveSelection(bv_->getLyXText()->selection.set());
814         }
815  
816         setState();
817         owner_->showState();
818         owner_->updateMenubar();
819         owner_->updateToolbar();
820
821         // Did we hit an editable inset?
822         if (inset_hit) {
823                 selection_possible = false;
824
825                 // if we reach this point with a selection, it
826                 // must mean we are currently selecting.
827                 // But we don't want to open the inset
828                 // because that is annoying for the user. 
829                 // So just pretend we didn't hit it.
830                 // this is OK because a "kosher" ButtonRelease
831                 // will follow a ButtonPress that clears
832                 // the selection.
833                 // Note this also fixes selection drawing
834                 // problems if we end up opening an inset
835                 if (bv_->getLyXText()->selection.set())
836                         return;
837  
838                 // CHECK fix this proper in 0.13
839                 // well, maybe 13.0 !!!!!!!!!
840
841                 // Following a ref shouldn't issue
842                 // a push on the undo-stack
843                 // anylonger, now that we have
844                 // keybindings for following
845                 // references and returning from
846                 // references.  IMHO though, it
847                 // should be the inset's own business
848                 // to push or not push on the undo
849                 // stack. They don't *have* to
850                 // alter the document...
851                 // (Joacim)
852                 // ...or maybe the SetCursorParUndo()
853                 // below isn't necessary at all anylonger?
854                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
855                         setCursorParUndo(bv_);
856                 }
857
858                 owner_->message(inset_hit->editMessage());
859
860                 if (isHighlyEditableInset(inset_hit)) {
861                         // Highly editable inset, like math
862                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
863                         inset->insetButtonRelease(bv_, x, y, button);
864                 } else {
865                         inset_hit->insetButtonRelease(bv_, x, y, button);
866                         inset_hit->edit(bv_, x, y, button);
867                 }
868                 return;
869         }
870
871         // Maybe we want to edit a bibitem ale970302
872         if (bv_->text->cursor.par()->bibkey && x < 20 + 
873             bibitemMaxWidth(bv_, textclasslist.
874                             TextClass(buffer_->
875                                       params.textclass).defaultfont())) {
876                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
877         }
878
879         return;
880 }
881
882
883 Box BufferView::Pimpl::insetDimensions(LyXText const & text,
884                                        LyXCursor const & cursor) const
885 {
886         Paragraph /*const*/ & par = *cursor.par();
887         pos_type const pos = cursor.pos();
888
889         lyx::Assert(par.getInset(pos));
890  
891         Inset const & inset(*par.getInset(pos));
892
893         LyXFont const & font = text.getFont(buffer_, &par, pos);
894  
895         int const width = inset.width(bv_, font);
896         int const inset_x = font.isVisibleRightToLeft()
897                 ? (cursor.x() - width) : cursor.x();
898  
899         return Box(
900                 inset_x + inset.scroll(),
901                 inset_x + width,
902                 cursor.y() - inset.ascent(bv_, font),
903                 cursor.y() + inset.descent(bv_, font));
904 }
905  
906  
907 Inset * BufferView::Pimpl::checkInset(LyXText const & text,
908                                       LyXCursor const & cursor,
909                                       int & x, int & y) const
910 {
911         pos_type const pos(cursor.pos());
912         Paragraph /*const*/ & par(*cursor.par());
913
914         if (pos >= par.size() || !par.isInset(pos)) {
915                 return 0;
916         }
917
918         Inset /*const*/ * inset = par.getInset(pos);
919  
920         if (!isEditableInset(inset)) {
921                 return 0;
922         }
923
924         Box b(insetDimensions(text, cursor));
925
926         if (!b.contained(x, y)) {
927                 lyxerr[Debug::GUI] << "Missed inset at x,y " << x << "," << y 
928                         << " box " << b << endl;
929                 return 0;
930         }
931  
932         text.setCursor(bv_, &par, pos, true);
933  
934         x -= b.x1;
935         // The origin of an inset is on the baseline
936         y -= (text.cursor.y());
937   
938         return inset;
939 }
940
941  
942 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y)
943 {
944         if (!screen_.get())
945                 return 0;
946   
947         int y_tmp = y + text->first;
948  
949         LyXCursor cursor;
950         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
951  
952         Inset * inset(checkInset(*text, cursor, x, y_tmp));
953
954         if (inset) {
955                 y = y_tmp;
956                 return inset;
957         }
958  
959         // look at previous position
960  
961         if (cursor.pos() == 0) {
962                 return 0;
963         }
964
965         // move back one
966         text->setCursor(bv_, cursor, cursor.par(), cursor.pos() - 1, true);
967
968         inset = checkInset(*text, cursor, x, y_tmp);
969         if (inset) {
970                 y = y_tmp;
971         }
972         return inset;
973 }
974
975
976 void BufferView::Pimpl::workAreaExpose()
977 {
978         static int work_area_width;
979         static unsigned int work_area_height;
980
981         bool const widthChange = workarea_.workWidth() != work_area_width;
982         bool const heightChange = workarea_.height() != work_area_height;
983
984         // update from work area
985         work_area_width = workarea_.workWidth();
986         work_area_height = workarea_.height();
987         if (buffer_ != 0) {
988                 if (widthChange) {
989                         // The visible LyXView need a resize
990                         owner_->resize();
991
992                         // Remove all texts from the textcache
993                         // This is not _really_ what we want to do. What
994                         // we really want to do is to delete in textcache
995                         // that does not have a BufferView with matching
996                         // width, but as long as we have only one BufferView
997                         // deleting all gives the same result.
998                         if (lyxerr.debugging())
999                                 textcache.show(lyxerr, "Expose delete all");
1000                         textcache.clear();
1001                 } else if (heightChange) {
1002                         // Rebuild image of current screen
1003                         updateScreen();
1004                         // fitCursor() ensures we don't jump back
1005                         // to the start of the document on vertical
1006                         // resize
1007                         fitCursor();
1008
1009                         // The main window size has changed, repaint most stuff
1010                         redraw();
1011                 } else if (screen_.get())
1012                     screen_->redraw(bv_->text, bv_);
1013         } else {
1014                 // Grey box when we don't have a buffer
1015                 workarea_.greyOut();
1016         }
1017
1018         // always make sure that the scrollbar is sane.
1019         updateScrollbar();
1020         owner_->updateLayoutChoice();
1021         return;
1022 }
1023
1024
1025 void BufferView::Pimpl::update()
1026 {
1027         if (screen_.get() &&
1028                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
1029         {
1030                 LyXText::text_status st = bv_->text->status();
1031                 screen_->update(bv_->text, bv_);
1032                 bool fitc = false;
1033                 while (bv_->text->status() == LyXText::CHANGED_IN_DRAW) {
1034                         if (bv_->text->fullRebreak(bv_)) {
1035                                 st = LyXText::NEED_MORE_REFRESH;
1036                                 bv_->text->setCursor(bv_, bv_->text->cursor.par(),
1037                                                                          bv_->text->cursor.pos());
1038                                 fitc = true;
1039                         }
1040                         bv_->text->status(bv_, st);
1041                         screen_->update(bv_->text, bv_);
1042                 }
1043                 // do this here instead of in the screen::update because of
1044                 // the above loop!
1045                 bv_->text->status(bv_, LyXText::UNCHANGED);
1046                 if (fitc)
1047                         fitCursor();
1048         }
1049 }
1050
1051 // Values used when calling update:
1052 // -3 - update
1053 // -2 - update, move sel_cursor if selection, fitcursor
1054 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
1055 //  0 - update, move sel_cursor if selection, fitcursor 
1056 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
1057 //  3 - update, move sel_cursor if selection
1058 //
1059 // update -
1060 // a simple redraw of the parts that need refresh
1061 //
1062 // move sel_cursor if selection -
1063 // the text's sel_cursor is moved if there is selection is progress
1064 //
1065 // fitcursor -
1066 // fitCursor() is called and the scrollbar updated
1067 //
1068 // mark dirty -
1069 // the buffer is marked dirty.
1070 //
1071 // enum {
1072 //       UPDATE = 0,
1073 //       SELECT = 1,
1074 //       FITCUR = 2,
1075 //       CHANGE = 4 
1076 // };
1077 //
1078 // UPDATE_ONLY = UPDATE;
1079 // UPDATE_SELECT = UPDATE | SELECT;
1080 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
1081 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
1082 //
1083 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
1084 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
1085 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1086 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
1087 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
1088
1089 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
1090 {
1091         owner_->updateLayoutChoice();
1092
1093         if (!text->selection.set() && (f & SELECT)) {
1094                 text->selection.cursor = text->cursor;
1095         }
1096
1097         text->fullRebreak(bv_);
1098
1099         if (text->inset_owner) {
1100                 text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1101             updateInset(text->inset_owner, false);
1102         } else {
1103             update();
1104         }
1105                 
1106         if ((f & FITCUR)) {
1107                 fitCursor();
1108         }
1109
1110         if ((f & CHANGE)) {
1111                 buffer_->markDirty();
1112         }
1113 }
1114
1115
1116 // Callback for cursor timer
1117 void BufferView::Pimpl::cursorToggle()
1118 {
1119         if (!buffer_) {
1120                 cursor_timeout.restart();
1121                 return;
1122         }
1123  
1124         if (!screen_.get()) {
1125                 cursor_timeout.restart();
1126                 return;
1127         }
1128
1129         /* FIXME */
1130         extern void reapSpellchecker(void);
1131         reapSpellchecker();
1132          
1133         if (!bv_->theLockingInset()) {
1134                 screen_->cursorToggle(bv_);
1135         } else {
1136                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1137         }
1138         
1139         cursor_timeout.restart();
1140 }
1141
1142
1143 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1144 {
1145         if (!text->cursor.row()->previous())
1146                 return;
1147         
1148         int y = text->first;
1149         if (text->inset_owner)
1150                 y += bv_->text->first;
1151         Row * cursorrow = text->cursor.row();
1152         text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1153         finishUndo();
1154         // This is to allow jumping over large insets
1155         if ((cursorrow == text->cursor.row()))
1156                 text->cursorUp(bv_);
1157         
1158         if (text->inset_owner ||
1159             text->cursor.row()->height() < workarea_.height())
1160                 screen_->draw(bv_->text, bv_,
1161                               text->cursor.y()
1162                               - text->cursor.row()->baseline()
1163                               + text->cursor.row()->height()
1164                               - workarea_.height() + 1);
1165         updateScrollbar();
1166 }
1167
1168
1169 void BufferView::Pimpl::cursorNext(LyXText * text)
1170 {
1171         if (!text->cursor.row()->next())
1172                 return;
1173         
1174         int y = text->first + workarea_.height();
1175 //      if (text->inset_owner)
1176 //              y += bv_->text->first;
1177         text->getRowNearY(y);
1178     
1179         Row * cursorrow = text->cursor.row();
1180         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1181         finishUndo();
1182         // This is to allow jumping over large insets
1183         if ((cursorrow == bv_->text->cursor.row()))
1184                 text->cursorDown(bv_);
1185         
1186         if (text->inset_owner ||
1187             text->cursor.row()->height() < workarea_.height())
1188                 screen_->draw(bv_->text, bv_, text->cursor.y() -
1189                               text->cursor.row()->baseline());
1190         updateScrollbar();
1191 }
1192
1193
1194 bool BufferView::Pimpl::available() const
1195 {
1196         if (buffer_ && bv_->text) return true;
1197         return false;
1198 }
1199
1200
1201 void BufferView::Pimpl::beforeChange(LyXText * text)
1202 {
1203         toggleSelection();
1204         text->clearSelection();
1205 }
1206
1207
1208 void BufferView::Pimpl::savePosition(unsigned int i)
1209 {
1210         if (i >= saved_positions_num)
1211                 return;
1212         saved_positions[i] = Position(buffer_->fileName(),
1213                                       bv_->text->cursor.par()->id(),
1214                                       bv_->text->cursor.pos());
1215         if (i > 0) {
1216                 ostringstream str;
1217                 str << _("Saved bookmark") << ' ' << i;
1218                 owner_->message(str.str().c_str());
1219         }
1220 }
1221
1222
1223 void BufferView::Pimpl::restorePosition(unsigned int i)
1224 {
1225         if (i >= saved_positions_num)
1226                 return;
1227
1228         string const fname = saved_positions[i].filename;
1229
1230         beforeChange(bv_->text);
1231
1232         if (fname != buffer_->fileName()) {
1233                 Buffer * b = bufferlist.exists(fname) ?
1234                         bufferlist.getBuffer(fname) :
1235                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1236                 if (b != 0) buffer(b);
1237         }
1238
1239         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1240         if (!par)
1241                 return;
1242
1243         bv_->text->setCursor(bv_, par,
1244                              min(par->size(), saved_positions[i].par_pos));
1245
1246         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1247         if (i > 0) {
1248                 ostringstream str;
1249                 str << _("Moved to bookmark") << ' ' << i;
1250                 owner_->message(str.str().c_str());
1251         }
1252 }
1253
1254
1255 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1256 {
1257         if (i >= saved_positions_num)
1258                 return false;
1259
1260         return !saved_positions[i].filename.empty();
1261 }
1262
1263
1264 void BufferView::Pimpl::setState()
1265 {
1266         if (!lyxrc.rtl_support)
1267                 return;
1268
1269         LyXText * text = bv_->getLyXText();
1270         if (text->real_current_font.isRightToLeft()) {
1271                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1272                         owner_->getIntl()->KeyMapSec();
1273         } else {
1274                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1275                         owner_->getIntl()->KeyMapPrim();
1276         }
1277 }
1278
1279
1280 void BufferView::Pimpl::insetSleep()
1281 {
1282         if (bv_->theLockingInset() && !inset_slept) {
1283                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1284                 bv_->theLockingInset()->insetUnlock(bv_);
1285                 inset_slept = true;
1286         }
1287 }
1288
1289
1290 void BufferView::Pimpl::insetWakeup()
1291 {
1292         if (bv_->theLockingInset() && inset_slept) {
1293                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1294                 inset_slept = false;
1295         }
1296 }
1297
1298
1299 void BufferView::Pimpl::insetUnlock()
1300 {
1301         if (bv_->theLockingInset()) {
1302                 if (!inset_slept)
1303                         bv_->theLockingInset()->insetUnlock(bv_);
1304                 bv_->theLockingInset(0);
1305                 finishUndo();
1306                 inset_slept = false;
1307         }
1308 }
1309
1310
1311 bool BufferView::Pimpl::focus() const
1312 {
1313         return workarea_.hasFocus();
1314 }
1315
1316
1317 void BufferView::Pimpl::focus(bool f)
1318 {
1319         if (f) workarea_.setFocus();
1320 }
1321
1322
1323 bool BufferView::Pimpl::active() const
1324 {
1325         return workarea_.active();
1326 }
1327
1328
1329 bool BufferView::Pimpl::belowMouse() const 
1330 {
1331         return workarea_.belowMouse();
1332 }
1333
1334
1335 void BufferView::Pimpl::showCursor()
1336 {
1337         if (screen_.get()) {
1338                 if (bv_->theLockingInset())
1339                         bv_->theLockingInset()->showInsetCursor(bv_);
1340                 else
1341                         screen_->showCursor(bv_->text, bv_);
1342         }
1343 }
1344
1345
1346 void BufferView::Pimpl::hideCursor()
1347 {
1348         if (screen_.get()) {
1349                 if (!bv_->theLockingInset())
1350 //                      bv_->theLockingInset()->hideInsetCursor(bv_);
1351 //              else
1352                         screen_->hideCursor();
1353         }
1354 }
1355
1356
1357 void BufferView::Pimpl::toggleSelection(bool b)
1358 {
1359         if (screen_.get()) {
1360                 if (bv_->theLockingInset())
1361                         bv_->theLockingInset()->toggleSelection(bv_, b);
1362                 screen_->toggleSelection(bv_->text, bv_, b);
1363         }
1364 }
1365
1366
1367 void BufferView::Pimpl::toggleToggle()
1368 {
1369         if (screen_.get())
1370                 screen_->toggleToggle(bv_->text, bv_);
1371 }
1372
1373
1374 void BufferView::Pimpl::center() 
1375 {
1376         beforeChange(bv_->text);
1377         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1378                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1379         } else {
1380                 screen_->draw(bv_->text, bv_, 0);
1381         }
1382         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1383         redraw();
1384 }
1385
1386
1387 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1388 {
1389         if (!buffer_) return;
1390
1391         screen_->hideCursor();
1392         beforeChange(bv_->text);
1393         
1394         string const clip(workarea_.getClipboard());
1395         
1396         if (clip.empty()) return;
1397
1398         if (asPara) {
1399                 bv_->getLyXText()->insertStringAsParagraphs(bv_, clip);
1400         } else {
1401                 bv_->getLyXText()->insertStringAsLines(bv_, clip);
1402         }
1403         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1404 }
1405
1406
1407 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1408 {
1409         workarea_.putClipboard(stuff);
1410 }
1411
1412
1413 /*
1414  * Dispatch functions for actions which can be valid for BufferView->text
1415  * and/or InsetText->text!!!
1416  */
1417
1418
1419 inline
1420 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1421 {
1422         LyXText * lt = bv_->getLyXText();
1423         
1424         if (selecting || lt->selection.mark()) {
1425                 lt->setSelection(bv_);
1426                 if (lt->bv_owner)
1427                         toggleToggle();
1428         }
1429         update(lt, BufferView::SELECT|BufferView::FITCUR);
1430         showCursor();
1431         
1432         /* ---> Everytime the cursor is moved, show the current font state. */
1433         // should this too me moved out of this func?
1434         //owner->showState();
1435         setState();
1436 }
1437
1438
1439 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1440 {
1441         LyXCursor cursor = bv_->getLyXText()->cursor;
1442         Buffer::inset_iterator it =
1443                 find_if(Buffer::inset_iterator(
1444                         cursor.par(), cursor.pos()),
1445                         buffer_->inset_iterator_end(),
1446                         lyx::compare_memfun(&Inset::lyxCode, code));
1447         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1448 }
1449
1450
1451 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1452 {
1453         string filename = filen;
1454
1455         if (filename.empty()) {
1456                 // Launch a file browser
1457                 string initpath = lyxrc.document_path;
1458
1459                 if (available()) {
1460                         string const trypath = owner_->buffer()->filePath();
1461                         // If directory is writeable, use this as default.
1462                         if (IsDirWriteable(trypath))
1463                                 initpath = trypath;
1464                 }
1465
1466                 FileDialog fileDlg(bv_->owner(),
1467                                    _("Select LyX document to insert"),
1468                         LFUN_FILE_INSERT,
1469                         make_pair(string(_("Documents|#o#O")),
1470                                   string(lyxrc.document_path)),
1471                         make_pair(string(_("Examples|#E#e")),
1472                                   string(AddPath(system_lyxdir, "examples"))));
1473
1474                 FileDialog::Result result =
1475                         fileDlg.Select(initpath,
1476                                        _("*.lyx| LyX Documents (*.lyx)"));
1477  
1478                 if (result.first == FileDialog::Later)
1479                         return;
1480
1481                 filename = result.second;
1482
1483                 // check selected filename
1484                 if (filename.empty()) {
1485                         owner_->message(_("Canceled."));
1486                         return;
1487                 }
1488         }
1489
1490         // get absolute path of file and add ".lyx" to the filename if
1491         // necessary
1492         filename = FileSearch(string(), filename, "lyx");
1493
1494         string const disp_fn(MakeDisplayPath(filename));
1495         
1496         ostringstream s1;
1497         s1 << _("Inserting document") << ' '
1498            << disp_fn << " ...";
1499         owner_->message(s1.str().c_str());
1500         bool const res = bv_->insertLyXFile(filename);
1501         if (res) {
1502                 ostringstream str;
1503                 str << _("Document") << ' ' << disp_fn
1504                     << ' ' << _("inserted.");
1505                 owner_->message(str.str().c_str());
1506         } else {
1507                 ostringstream str;
1508                 str << _("Could not insert document") << ' '
1509                     << disp_fn;
1510                 owner_->message(str.str().c_str());
1511         }
1512 }
1513
1514
1515 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1516 {
1517         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1518                               << action <<"] arg[" << argument << "]" << endl;
1519         
1520         switch (action) {
1521                 // --- Misc -------------------------------------------
1522         case LFUN_APPENDIX:
1523         {
1524                 if (available()) {
1525                         LyXText * lt = bv_->getLyXText();
1526                         lt->toggleAppendix(bv_);
1527                         update(lt,
1528                                BufferView::SELECT
1529                                | BufferView::FITCUR
1530                                | BufferView::CHANGE);
1531                 }
1532         }
1533         break;
1534
1535         case LFUN_TOC_INSERT:
1536         {
1537                 InsetCommandParams p;
1538                 p.setCmdName("tableofcontents");
1539                 Inset * inset = new InsetTOC(p);
1540                 if (!insertInset(inset, "Standard"))
1541                         delete inset;
1542                 break;
1543         }
1544                 
1545         case LFUN_SCROLL_INSET:
1546                 // this is not handled here as this funktion is only aktive
1547                 // if we have a locking_inset and that one is (or contains)
1548                 // a tabular-inset
1549                 break;
1550
1551         case LFUN_INSET_GRAPHICS:
1552         {
1553                 Inset * new_inset = new InsetGraphics;
1554                 if (!insertInset(new_inset)) {
1555                         delete new_inset;
1556                 } else {
1557                         // this is need because you don't use a inset->Edit()
1558                         updateInset(new_inset, true);
1559                         new_inset->edit(bv_);
1560                 }
1561                 break;
1562         }
1563                 
1564         case LFUN_PASTE:
1565                 bv_->paste();
1566                 setState();
1567                 break;
1568                 
1569         case LFUN_PASTESELECTION:
1570         {
1571                 bool asPara = false;
1572                 if (argument == "paragraph")
1573                         asPara = true;
1574                 pasteClipboard(asPara);
1575         }
1576         break;
1577         
1578         case LFUN_CUT:
1579                 bv_->cut();
1580                 break;
1581                 
1582         case LFUN_COPY:
1583                 bv_->copy();
1584                 break;
1585                 
1586         case LFUN_LAYOUT_COPY:
1587                 bv_->copyEnvironment();
1588                 break;
1589                 
1590         case LFUN_LAYOUT_PASTE:
1591                 bv_->pasteEnvironment();
1592                 setState();
1593                 break;
1594                 
1595         case LFUN_GOTOERROR:
1596                 gotoInset(Inset::ERROR_CODE, false);
1597                 break;
1598                 
1599         case LFUN_GOTONOTE:
1600                 gotoInset(Inset::IGNORE_CODE, false);
1601                 break;
1602
1603         case LFUN_REFERENCE_GOTO:
1604         {
1605                 vector<Inset::Code> tmp;
1606                 tmp.push_back(Inset::LABEL_CODE);
1607                 tmp.push_back(Inset::REF_CODE);
1608                 gotoInset(tmp, true);
1609                 break;
1610         }
1611
1612         case LFUN_HYPHENATION:
1613                 specialChar(InsetSpecialChar::HYPHENATION);
1614                 break;
1615                 
1616         case LFUN_LIGATURE_BREAK:
1617                 specialChar(InsetSpecialChar::LIGATURE_BREAK);
1618                 break;
1619                 
1620         case LFUN_LDOTS:
1621                 specialChar(InsetSpecialChar::LDOTS);
1622                 break;
1623                 
1624         case LFUN_END_OF_SENTENCE:
1625                 specialChar(InsetSpecialChar::END_OF_SENTENCE);
1626                 break;
1627
1628         case LFUN_MENU_SEPARATOR:
1629                 specialChar(InsetSpecialChar::MENU_SEPARATOR);
1630                 break;
1631                 
1632         case LFUN_HFILL:
1633                 hfill();
1634                 break;
1635                 
1636         case LFUN_DEPTH:
1637                 changeDepth(bv_, bv_->getLyXText(), 0);
1638                 break;
1639                 
1640         case LFUN_DEPTH_MIN:
1641                 changeDepth(bv_, bv_->getLyXText(), -1);
1642                 break;
1643                 
1644         case LFUN_DEPTH_PLUS:
1645                 changeDepth(bv_, bv_->getLyXText(), 1);
1646                 break;
1647                 
1648         case LFUN_FREE:
1649                 owner_->getDialogs()->setUserFreeFont();
1650                 break;
1651
1652         case LFUN_FILE_INSERT:
1653                 MenuInsertLyXFile(argument);
1654                 break;
1655         
1656         case LFUN_FILE_INSERT_ASCII_PARA:
1657                 InsertAsciiFile(bv_, argument, true);
1658                 break;
1659
1660         case LFUN_FILE_INSERT_ASCII:
1661                 InsertAsciiFile(bv_, argument, false);
1662                 break;
1663                 
1664         case LFUN_LAYOUT:
1665         {
1666                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1667                                     << argument << endl;
1668                 
1669                 // Derive layout number from given argument (string)
1670                 // and current buffer's textclass (number). */    
1671                 textclass_type tclass = buffer_->params.textclass;
1672                 pair <bool, layout_type> layout = 
1673                         textclasslist.NumberOfLayout(tclass, argument);
1674
1675                 // If the entry is obsolete, use the new one instead.
1676                 if (layout.first) {
1677                         string obs = textclasslist.Style(tclass, layout.second)
1678                                 .obsoleted_by();
1679                         if (!obs.empty()) 
1680                                 layout = textclasslist.NumberOfLayout(tclass, obs);
1681                 }
1682
1683                 // see if we found the layout number:
1684                 if (!layout.first) {
1685                         owner_->getLyXFunc()->setErrorMessage(
1686                                 string(N_("Layout ")) + argument +
1687                                 N_(" not known"));
1688                         break;
1689                 }
1690
1691                 if (current_layout != layout.second) {
1692                         LyXText * lt = bv_->getLyXText();
1693                         hideCursor();
1694                         current_layout = layout.second;
1695                         update(lt,
1696                                BufferView::SELECT
1697                                | BufferView::FITCUR);
1698                         lt->setLayout(bv_, layout.second);
1699                         owner_->setLayout(layout.second);
1700                         update(lt,
1701                                BufferView::SELECT
1702                                | BufferView::FITCUR
1703                                | BufferView::CHANGE);
1704                         setState();
1705                 }
1706         }
1707         break;
1708
1709         case LFUN_LANGUAGE:
1710                 lang(bv_, argument);
1711                 setState();
1712                 owner_->showState();
1713                 break;
1714
1715         case LFUN_EMPH:
1716                 emph(bv_);
1717                 owner_->showState();
1718                 break;
1719
1720         case LFUN_BOLD:
1721                 bold(bv_);
1722                 owner_->showState();
1723                 break;
1724                 
1725         case LFUN_NOUN:
1726                 noun(bv_);
1727                 owner_->showState();
1728                 break;
1729                 
1730         case LFUN_CODE:
1731                 code(bv_);
1732                 owner_->showState();
1733                 break;
1734                 
1735         case LFUN_SANS:
1736                 sans(bv_);
1737                 owner_->showState();
1738                 break;
1739                 
1740         case LFUN_ROMAN:
1741                 roman(bv_);
1742                 owner_->showState();
1743                 break;
1744                 
1745         case LFUN_DEFAULT:
1746                 styleReset(bv_);
1747                 owner_->showState();
1748                 break;
1749                 
1750         case LFUN_UNDERLINE:
1751                 underline(bv_);
1752                 owner_->showState();
1753                 break;
1754                 
1755         case LFUN_FONT_SIZE:
1756                 fontSize(bv_, argument);
1757                 owner_->showState();
1758                 break;
1759                 
1760         case LFUN_FONT_STATE:
1761                 owner_->getLyXFunc()->setMessage(currentState(bv_));
1762                 break;
1763                 
1764         case LFUN_UPCASE_WORD:
1765         {
1766                 LyXText * lt = bv_->getLyXText();
1767                 
1768                 update(lt,
1769                        BufferView::SELECT
1770                        | BufferView::FITCUR);
1771                 lt->changeCase(bv_, LyXText::text_uppercase);
1772                 if (lt->inset_owner)
1773                         updateInset(lt->inset_owner, true);
1774                 update(lt,
1775                        BufferView::SELECT
1776                        | BufferView::FITCUR
1777                        | BufferView::CHANGE);
1778         }
1779         break;
1780                 
1781         case LFUN_LOWCASE_WORD:
1782         {
1783                 LyXText * lt = bv_->getLyXText();
1784                 
1785                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1786                 lt->changeCase(bv_, LyXText::text_lowercase);
1787                 if (lt->inset_owner)
1788                         updateInset(lt->inset_owner, true);
1789                 update(lt,
1790                        BufferView::SELECT
1791                        | BufferView::FITCUR
1792                        | BufferView::CHANGE);
1793         }
1794         break;
1795                 
1796         case LFUN_CAPITALIZE_WORD:
1797         {
1798                 LyXText * lt = bv_->getLyXText();
1799                 
1800                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1801                 lt->changeCase(bv_, LyXText::text_capitalization);
1802                 if (lt->inset_owner)
1803                         updateInset(lt->inset_owner, true);
1804                 update(lt,
1805                        BufferView::SELECT
1806                        | BufferView::FITCUR
1807                        | BufferView::CHANGE);
1808         }
1809         break;
1810
1811         case LFUN_TRANSPOSE_CHARS:
1812         {
1813                 LyXText * lt = bv_->getLyXText();
1814                 
1815                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1816                 lt->transposeChars(*bv_);
1817                 if (lt->inset_owner)
1818                         updateInset(lt->inset_owner, true);
1819                 update(lt,
1820                        BufferView::SELECT
1821                        | BufferView::FITCUR
1822                        | BufferView::CHANGE);
1823         }
1824         break;
1825                 
1826                                           
1827         case LFUN_INSERT_LABEL:
1828                 MenuInsertLabel(bv_, argument);
1829                 break;
1830
1831         case LFUN_REF_INSERT:
1832                 if (argument.empty()) {
1833                         InsetCommandParams p("ref");
1834                         owner_->getDialogs()->createRef(p.getAsString());
1835                 } else {
1836                         InsetCommandParams p;
1837                         p.setFromString(argument);
1838
1839                         InsetRef * inset = new InsetRef(p, *buffer_);
1840                         if (!insertInset(inset))
1841                                 delete inset;
1842                         else
1843                                 updateInset(inset, true);
1844                 }
1845                 break;
1846
1847         case LFUN_BOOKMARK_SAVE:
1848                 savePosition(strToUnsignedInt(argument));
1849                 break;
1850
1851         case LFUN_BOOKMARK_GOTO:
1852                 restorePosition(strToUnsignedInt(argument));
1853                 break;
1854
1855         case LFUN_REF_GOTO:
1856         {
1857                 string label(argument);
1858                 if (label.empty()) {
1859                         InsetRef * inset = 
1860                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1861                         if (inset) {
1862                                 label = inset->getContents();
1863                                 savePosition(0);
1864                         }
1865                 }
1866                 
1867                 if (!label.empty()) {
1868                         //bv_->savePosition(0);
1869                         if (!bv_->gotoLabel(label))
1870                                 Alert::alert(_("Error"), 
1871                                            _("Couldn't find this label"), 
1872                                            _("in current document."));
1873                 }
1874         }
1875         break;
1876                 
1877                 // --- Cursor Movements -----------------------------
1878         case LFUN_RIGHT:
1879         {
1880                 LyXText * lt = bv_->getLyXText();
1881                 
1882                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1883                 if (!lt->selection.mark())
1884                         beforeChange(lt);
1885                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1886                 if (is_rtl)
1887                         lt->cursorLeft(bv_, false);
1888                 if (lt->cursor.pos() < lt->cursor.par()->size()
1889                     && lt->cursor.par()->isInset(lt->cursor.pos())
1890                     && isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1891                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1892                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1893                         if (is_rtl)
1894                                 tmpinset->edit(bv_, false);
1895                         else
1896                                 tmpinset->edit(bv_);
1897                         break;
1898                 }
1899                 if (!is_rtl)
1900                         lt->cursorRight(bv_, false);
1901                 finishUndo();
1902                 moveCursorUpdate(false);
1903                 owner_->showState();
1904         }
1905         break;
1906                 
1907         case LFUN_LEFT:
1908         {
1909                 // This is soooo ugly. Isn`t it possible to make
1910                 // it simpler? (Lgb)
1911                 LyXText * lt = bv_->getLyXText();
1912                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1913                 if (!lt->selection.mark())
1914                         beforeChange(lt);
1915                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1916                 LyXCursor const cur = lt->cursor;
1917                 if (!is_rtl)
1918                         lt->cursorLeft(bv_, false);
1919                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1920                     lt->cursor.pos() < lt->cursor.par()->size() &&
1921                     lt->cursor.par()->isInset(lt->cursor.pos()) &&
1922                     isHighlyEditableInset(lt->cursor.par()->getInset(lt->cursor.pos()))) {
1923                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1924                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1925                         if (is_rtl)
1926                                 tmpinset->edit(bv_);
1927                         else
1928                                 tmpinset->edit(bv_, false);
1929                         break;
1930                 }
1931                 if  (is_rtl)
1932                         lt->cursorRight(bv_, false);
1933
1934                 finishUndo();
1935                 moveCursorUpdate(false);
1936                 owner_->showState();
1937         }
1938         break;
1939                 
1940         case LFUN_UP:
1941         {
1942                 LyXText * lt = bv_->getLyXText();
1943                 
1944                 if (!lt->selection.mark())
1945                         beforeChange(lt);
1946                 update(lt, BufferView::UPDATE);
1947                 lt->cursorUp(bv_);
1948                 finishUndo();
1949                 moveCursorUpdate(false);
1950                 owner_->showState();
1951         }
1952         break;
1953                 
1954         case LFUN_DOWN:
1955         {
1956                 LyXText * lt = bv_->getLyXText();
1957                 
1958                 if (!lt->selection.mark())
1959                         beforeChange(lt);
1960                 update(lt, BufferView::UPDATE);
1961                 lt->cursorDown(bv_);
1962                 finishUndo();
1963                 moveCursorUpdate(false);
1964                 owner_->showState();
1965         }
1966         break;
1967
1968         case LFUN_UP_PARAGRAPH:
1969         {
1970                 LyXText * lt = bv_->getLyXText();
1971                 
1972                 if (!lt->selection.mark())
1973                         beforeChange(lt);
1974                 update(lt, BufferView::UPDATE);
1975                 lt->cursorUpParagraph(bv_);
1976                 finishUndo();
1977                 moveCursorUpdate(false);
1978                 owner_->showState();
1979         }
1980         break;
1981                 
1982         case LFUN_DOWN_PARAGRAPH:
1983         {
1984                 LyXText * lt = bv_->getLyXText();
1985                 
1986                 if (!lt->selection.mark())
1987                         beforeChange(lt);
1988                 update(lt, BufferView::UPDATE);
1989                 lt->cursorDownParagraph(bv_);
1990                 finishUndo();
1991                 moveCursorUpdate(false);
1992                 owner_->showState();
1993         }
1994         break;
1995                 
1996         case LFUN_PRIOR:
1997         {
1998                 LyXText * lt = bv_->getLyXText();
1999                 
2000                 if (!lt->selection.mark())
2001                         beforeChange(lt);
2002                 update(lt, BufferView::UPDATE);
2003                 cursorPrevious(lt);
2004                 finishUndo();
2005                 moveCursorUpdate(false);
2006                 owner_->showState();
2007         }
2008         break;
2009                 
2010         case LFUN_NEXT:
2011         {
2012                 LyXText * lt = bv_->getLyXText();
2013                 
2014                 if (!lt->selection.mark())
2015                         beforeChange(lt);
2016                 update(lt, BufferView::UPDATE);
2017                 cursorNext(lt);
2018                 finishUndo();
2019                 moveCursorUpdate(false);
2020                 owner_->showState();
2021         }
2022         break;
2023                 
2024         case LFUN_HOME:
2025         {
2026                 LyXText * lt = bv_->getLyXText();
2027                 
2028                 if (!lt->selection.mark())
2029                         beforeChange(lt);
2030                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2031                 lt->cursorHome(bv_);
2032                 finishUndo();
2033                 moveCursorUpdate(false);
2034                 owner_->showState();
2035         }
2036         break;
2037                 
2038         case LFUN_END:
2039         {
2040                 LyXText * lt = bv_->getLyXText();
2041                 
2042                 if (!lt->selection.mark())
2043                         beforeChange(lt);
2044                 update(lt,
2045                        BufferView::SELECT|BufferView::FITCUR);
2046                 lt->cursorEnd(bv_);
2047                 finishUndo();
2048                 moveCursorUpdate(false);
2049                 owner_->showState();
2050         }
2051         break;
2052                 
2053         case LFUN_SHIFT_TAB:
2054         case LFUN_TAB:
2055         {
2056                 LyXText * lt = bv_->getLyXText();
2057                 
2058                 if (!lt->selection.mark())
2059                         beforeChange(lt);
2060                 update(lt,
2061                        BufferView::SELECT|BufferView::FITCUR);
2062                 lt->cursorTab(bv_);
2063                 finishUndo();
2064                 moveCursorUpdate(false);
2065                 owner_->showState();
2066         }
2067         break;
2068                 
2069         case LFUN_WORDRIGHT:
2070         {
2071                 LyXText * lt = bv_->getLyXText();
2072                 
2073                 if (!lt->selection.mark())
2074                         beforeChange(lt);
2075                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2076                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2077                         lt->cursorLeftOneWord(bv_);
2078                 else
2079                         lt->cursorRightOneWord(bv_);
2080                 finishUndo();
2081                 moveCursorUpdate(false);
2082                 owner_->showState();
2083         }
2084         break;
2085                 
2086         case LFUN_WORDLEFT:
2087         {
2088                 LyXText * lt = bv_->getLyXText();
2089                 
2090                 if (!lt->selection.mark())
2091                         beforeChange(lt);
2092                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2093                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2094                         lt->cursorRightOneWord(bv_);
2095                 else
2096                         lt->cursorLeftOneWord(bv_);
2097                 finishUndo();
2098                 moveCursorUpdate(false);
2099                 owner_->showState();
2100         }
2101         break;
2102                 
2103         case LFUN_BEGINNINGBUF:
2104         {
2105                 LyXText * lt = bv_->getLyXText();
2106                 
2107                 if (!lt->selection.mark())
2108                         beforeChange(lt);
2109                 update(lt,
2110                        BufferView::SELECT|BufferView::FITCUR);
2111                 lt->cursorTop(bv_);
2112                 finishUndo();
2113                 moveCursorUpdate(false);
2114                 owner_->showState();
2115         }
2116         break;
2117                 
2118         case LFUN_ENDBUF:
2119         {
2120                 LyXText * lt = bv_->getLyXText();
2121                 
2122                 if (!lt->selection.mark())
2123                         beforeChange(lt);
2124                 update(lt,
2125                        BufferView::SELECT|BufferView::FITCUR);
2126                 lt->cursorBottom(bv_);
2127                 finishUndo();
2128                 moveCursorUpdate(false);
2129                 owner_->showState();
2130         }
2131         break;
2132       
2133                 /* cursor selection ---------------------------- */
2134         case LFUN_RIGHTSEL:
2135         {
2136                 LyXText * lt = bv_->getLyXText();
2137                 
2138                 update(lt,
2139                        BufferView::SELECT|BufferView::FITCUR);
2140                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2141                         lt->cursorLeft(bv_);
2142                 else
2143                         lt->cursorRight(bv_);
2144                 finishUndo();
2145                 moveCursorUpdate(true);
2146                 owner_->showState();
2147         }
2148         break;
2149                 
2150         case LFUN_LEFTSEL:
2151         {
2152                 LyXText * lt = bv_->getLyXText();
2153                 
2154                 update(lt,
2155                        BufferView::SELECT|BufferView::FITCUR);
2156                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2157                         lt->cursorRight(bv_);
2158                 else
2159                         lt->cursorLeft(bv_);
2160                 finishUndo();
2161                 moveCursorUpdate(true);
2162                 owner_->showState();
2163         }
2164         break;
2165                 
2166         case LFUN_UPSEL:
2167         {
2168                 LyXText * lt = bv_->getLyXText();
2169                 
2170                 update(lt,
2171                        BufferView::SELECT|BufferView::FITCUR);
2172                 lt->cursorUp(bv_);
2173                 finishUndo();
2174                 moveCursorUpdate(true);
2175                 owner_->showState();
2176         }
2177         break;
2178                 
2179         case LFUN_DOWNSEL:
2180         {
2181                 LyXText * lt = bv_->getLyXText();
2182                 
2183                 update(lt,
2184                        BufferView::SELECT|BufferView::FITCUR);
2185                 lt->cursorDown(bv_);
2186                 finishUndo();
2187                 moveCursorUpdate(true);
2188                 owner_->showState();
2189         }
2190         break;
2191
2192         case LFUN_UP_PARAGRAPHSEL:
2193         {
2194                 LyXText * lt = bv_->getLyXText();
2195                 
2196                 update(lt,
2197                        BufferView::SELECT|BufferView::FITCUR);
2198                 lt->cursorUpParagraph(bv_);
2199                 finishUndo();
2200                 moveCursorUpdate(true);
2201                 owner_->showState();
2202         }
2203         break;
2204                 
2205         case LFUN_DOWN_PARAGRAPHSEL:
2206         {
2207                 LyXText * lt = bv_->getLyXText();
2208                 
2209                 update(lt,
2210                        BufferView::SELECT|BufferView::FITCUR);
2211                 lt->cursorDownParagraph(bv_);
2212                 finishUndo();
2213                 moveCursorUpdate(true);
2214                 owner_->showState();
2215         }
2216         break;
2217                 
2218         case LFUN_PRIORSEL:
2219         {
2220                 LyXText * lt = bv_->getLyXText();
2221                 
2222                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2223                 cursorPrevious(lt);
2224                 finishUndo();
2225                 moveCursorUpdate(true);
2226                 owner_->showState();
2227         }
2228         break;
2229                 
2230         case LFUN_NEXTSEL:
2231         {
2232                 LyXText * lt = bv_->getLyXText();
2233                 
2234                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2235                 cursorNext(lt);
2236                 finishUndo();
2237                 moveCursorUpdate(true);
2238                 owner_->showState();
2239         }
2240         break;
2241                 
2242         case LFUN_HOMESEL:
2243         {
2244                 LyXText * lt = bv_->getLyXText();
2245                 
2246                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2247                 lt->cursorHome(bv_);
2248                 finishUndo();
2249                 moveCursorUpdate(true);
2250                 owner_->showState();
2251         }
2252         break;
2253                 
2254         case LFUN_ENDSEL:
2255         {
2256                 LyXText * lt = bv_->getLyXText();
2257                 
2258                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2259                 lt->cursorEnd(bv_);
2260                 finishUndo();
2261                 moveCursorUpdate(true);
2262                 owner_->showState();
2263         }
2264         break;
2265                 
2266         case LFUN_WORDRIGHTSEL:
2267         {
2268                 LyXText * lt = bv_->getLyXText();
2269                 
2270                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2271                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2272                         lt->cursorLeftOneWord(bv_);
2273                 else
2274                         lt->cursorRightOneWord(bv_);
2275                 finishUndo();
2276                 moveCursorUpdate(true);
2277                 owner_->showState();
2278         }
2279         break;
2280                 
2281         case LFUN_WORDLEFTSEL:
2282         {
2283                 LyXText * lt = bv_->getLyXText();
2284                 
2285                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2286                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2287                         lt->cursorRightOneWord(bv_);
2288                 else
2289                         lt->cursorLeftOneWord(bv_);
2290                 finishUndo();
2291                 moveCursorUpdate(true);
2292                 owner_->showState();
2293         }
2294         break;
2295                 
2296         case LFUN_BEGINNINGBUFSEL:
2297         {
2298                 LyXText * lt = bv_->getLyXText();
2299                 
2300                 if (lt->inset_owner)
2301                         break;
2302                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2303                 lt->cursorTop(bv_);
2304                 finishUndo();
2305                 moveCursorUpdate(true);
2306                 owner_->showState();
2307         }
2308         break;
2309                 
2310         case LFUN_ENDBUFSEL:
2311         {
2312                 LyXText * lt = bv_->getLyXText();
2313                 
2314                 if (lt->inset_owner)
2315                         break;
2316                 update(lt,
2317                        BufferView::SELECT|BufferView::FITCUR);
2318                 lt->cursorBottom(bv_);
2319                 finishUndo();
2320                 moveCursorUpdate(true);
2321                 owner_->showState();
2322         }
2323         break;
2324
2325                 // --- text changing commands ------------------------
2326         case LFUN_BREAKLINE:
2327         {
2328                 LyXText * lt = bv_->getLyXText();
2329
2330                 beforeChange(lt);
2331                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2332                 update(lt,
2333                        BufferView::SELECT
2334                        | BufferView::FITCUR
2335                        | BufferView::CHANGE);
2336                 moveCursorUpdate(false);
2337         }
2338         break;
2339                 
2340         case LFUN_PROTECTEDSPACE:
2341         {
2342                 LyXText * lt = bv_->getLyXText();
2343
2344                 LyXLayout const & style = textclasslist
2345                         .Style(buffer_->params.textclass,
2346                                lt->cursor.par()->getLayout());
2347
2348                 if (style.free_spacing) {
2349                         lt->insertChar(bv_, ' ');
2350                         update(lt,
2351                                BufferView::SELECT
2352                                | BufferView::FITCUR
2353                                | BufferView::CHANGE);
2354                 } else {
2355                         protectedBlank(lt);
2356                 }
2357                 moveCursorUpdate(false);
2358         }
2359         break;
2360                 
2361         case LFUN_SETMARK:
2362         {
2363                 LyXText * lt = bv_->getLyXText();
2364
2365                 if (lt->selection.mark()) {
2366                         beforeChange(lt);
2367                         update(lt,
2368                                BufferView::SELECT
2369                                | BufferView::FITCUR);
2370                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2371                 } else {
2372                         beforeChange(lt);
2373                         lt->selection.mark(true);
2374                         update(lt,
2375                                BufferView::SELECT
2376                                | BufferView::FITCUR);
2377                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2378                 }
2379                 lt->selection.cursor = lt->cursor;
2380         }
2381         break;
2382                 
2383         case LFUN_DELETE:
2384         {
2385                 LyXText * lt = bv_->getLyXText();
2386
2387                 if (!lt->selection.set()) {
2388                         lt->Delete(bv_);
2389                         lt->selection.cursor = lt->cursor;
2390                         update(lt,
2391                                BufferView::SELECT
2392                                | BufferView::FITCUR
2393                                | BufferView::CHANGE);
2394                         // It is possible to make it a lot faster still
2395                         // just comment out the line below...
2396                         showCursor();
2397                 } else {
2398                         bv_->cut(false);
2399                 }
2400                 moveCursorUpdate(false);
2401                 owner_->showState();
2402                 setState();
2403         }
2404         break;
2405
2406         case LFUN_DELETE_SKIP:
2407         {
2408                 LyXText * lt = bv_->getLyXText();
2409
2410                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2411                 
2412                 LyXCursor cursor = lt->cursor;
2413
2414                 if (!lt->selection.set()) {
2415                         if (cursor.pos() == cursor.par()->size()) {
2416                                 lt->cursorRight(bv_);
2417                                 cursor = lt->cursor;
2418                                 if (cursor.pos() == 0
2419                                     && !(cursor.par()->params().spaceTop()
2420                                          == VSpace (VSpace::NONE))) {
2421                                         lt->setParagraph
2422                                                 (bv_,
2423                                                  cursor.par()->params().lineTop(),
2424                                                  cursor.par()->params().lineBottom(),
2425                                                  cursor.par()->params().pagebreakTop(), 
2426                                                  cursor.par()->params().pagebreakBottom(),
2427                                                  VSpace(VSpace::NONE), 
2428                                                  cursor.par()->params().spaceBottom(),
2429                                                  cursor.par()->params().spacing(), 
2430                                                  cursor.par()->params().align(), 
2431                                                  cursor.par()->params().labelWidthString(), 0);
2432                                         lt->cursorLeft(bv_);
2433                                         update(lt, 
2434                                                BufferView::SELECT
2435                                                | BufferView::FITCUR
2436                                                | BufferView::CHANGE);
2437                                 } else {
2438                                         lt->cursorLeft(bv_);
2439                                         lt->Delete(bv_);
2440                                         lt->selection.cursor = lt->cursor;
2441                                         update(lt,
2442                                                BufferView::SELECT
2443                                                | BufferView::FITCUR
2444                                                | BufferView::CHANGE);
2445                                 }
2446                         } else {
2447                                 lt->Delete(bv_);
2448                                 lt->selection.cursor = lt->cursor;
2449                                 update(lt,
2450                                        BufferView::SELECT
2451                                        | BufferView::FITCUR
2452                                        | BufferView::CHANGE);
2453                         }
2454                 } else {
2455                         bv_->cut(false);
2456                 }
2457         }
2458         break;
2459
2460         /* -------> Delete word forward. */
2461         case LFUN_DELETE_WORD_FORWARD:
2462                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2463                 bv_->getLyXText()->deleteWordForward(bv_);
2464                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2465                 moveCursorUpdate(false);
2466                 owner_->showState();
2467                 break;
2468
2469                 /* -------> Delete word backward. */
2470         case LFUN_DELETE_WORD_BACKWARD:
2471         {
2472                 LyXText * lt = bv_->getLyXText();
2473                 
2474                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2475                 lt->deleteWordBackward(bv_);
2476                 update(lt,
2477                        BufferView::SELECT
2478                        | BufferView::FITCUR
2479                        | BufferView::CHANGE);
2480                 moveCursorUpdate(false);
2481                 owner_->showState();
2482         }
2483         break;
2484                 
2485                 /* -------> Kill to end of line. */
2486         case LFUN_DELETE_LINE_FORWARD:
2487         {
2488                 LyXText * lt = bv_->getLyXText();
2489                 
2490                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2491                 lt->deleteLineForward(bv_);
2492                 update(lt,
2493                        BufferView::SELECT
2494                        | BufferView::FITCUR
2495                        | BufferView::CHANGE);
2496                 moveCursorUpdate(false);
2497         }
2498         break;
2499                 
2500                 /* -------> Set mark off. */
2501         case LFUN_MARK_OFF:
2502         {
2503                 LyXText * lt = bv_->getLyXText();
2504                 
2505                 beforeChange(lt);
2506                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2507                 lt->selection.cursor = lt->cursor;
2508                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2509         }
2510         break;
2511
2512                 /* -------> Set mark on. */
2513         case LFUN_MARK_ON:
2514         {
2515                 LyXText * lt = bv_->getLyXText();
2516                 
2517                 beforeChange(lt);
2518                 lt->selection.mark(true);
2519                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2520                 lt->selection.cursor = lt->cursor;
2521                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2522         }
2523         break;
2524                 
2525         case LFUN_BACKSPACE:
2526         {
2527                 LyXText * lt = bv_->getLyXText();
2528                 
2529                 if (!lt->selection.set()) {
2530                         if (owner_->getIntl()->getTrans().backspace()) {
2531                                 lt->backspace(bv_);
2532                                 lt->selection.cursor = lt->cursor;
2533                                 update(lt,
2534                                        BufferView::SELECT
2535                                        | BufferView::FITCUR
2536                                        | BufferView::CHANGE);
2537                                 // It is possible to make it a lot faster still
2538                                 // just comment out the line below...
2539                                 showCursor();
2540                         }
2541                 } else {
2542                         bv_->cut(false);
2543                 }
2544                 owner_->showState();
2545                 setState();
2546         }
2547         break;
2548
2549         case LFUN_BACKSPACE_SKIP:
2550         {
2551                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2552                 LyXText * lt = bv_->getLyXText();
2553                 
2554                 LyXCursor cursor = lt->cursor;
2555                 
2556                 if (!lt->selection.set()) {
2557                         if (cursor.pos() == 0 
2558                             && !(cursor.par()->params().spaceTop() 
2559                                  == VSpace (VSpace::NONE))) {
2560                                 lt->setParagraph 
2561                                         (bv_,
2562                                          cursor.par()->params().lineTop(),      
2563                                          cursor.par()->params().lineBottom(),
2564                                          cursor.par()->params().pagebreakTop(), 
2565                                          cursor.par()->params().pagebreakBottom(),
2566                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2567                                          cursor.par()->params().spacing(), 
2568                                          cursor.par()->params().align(), 
2569                                          cursor.par()->params().labelWidthString(), 0);
2570                                 update(lt,
2571                                        BufferView::SELECT
2572                                        | BufferView::FITCUR
2573                                        | BufferView::CHANGE);
2574                         } else {
2575                                 lt->backspace(bv_);
2576                                 lt->selection.cursor = cursor;
2577                                 update(lt,
2578                                        BufferView::SELECT
2579                                        | BufferView::FITCUR
2580                                        | BufferView::CHANGE);
2581                         }
2582                 } else
2583                         bv_->cut(false);
2584         }
2585         break;
2586
2587         case LFUN_BREAKPARAGRAPH:
2588         {
2589                 LyXText * lt = bv_->getLyXText();
2590                 
2591                 beforeChange(lt);
2592                 lt->breakParagraph(bv_, 0);
2593                 update(lt,
2594                        BufferView::SELECT
2595                        | BufferView::FITCUR
2596                        | BufferView::CHANGE);
2597                 lt->selection.cursor = lt->cursor;
2598                 setState();
2599                 owner_->showState();
2600                 break;
2601         }
2602
2603         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2604         {
2605                 LyXText * lt = bv_->getLyXText();
2606                 
2607                 beforeChange(lt);
2608                 lt->breakParagraph(bv_, 1);
2609                 update(lt,
2610                        BufferView::SELECT
2611                        | BufferView::FITCUR
2612                        | BufferView::CHANGE);
2613                 lt->selection.cursor = lt->cursor;
2614                 setState();
2615                 owner_->showState();
2616                 break;
2617         }
2618         
2619         case LFUN_BREAKPARAGRAPH_SKIP:
2620         {
2621                 // When at the beginning of a paragraph, remove
2622                 // indentation and add a "defskip" at the top.
2623                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2624                 LyXText * lt = bv_->getLyXText();
2625                 
2626                 LyXCursor cursor = lt->cursor;
2627                 
2628                 beforeChange(lt);
2629                 if (cursor.pos() == 0) {
2630                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2631                                 lt->setParagraph
2632                                         (bv_,
2633                                          cursor.par()->params().lineTop(),
2634                                          cursor.par()->params().lineBottom(),
2635                                          cursor.par()->params().pagebreakTop(),
2636                                          cursor.par()->params().pagebreakBottom(),
2637                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2638                                          cursor.par()->params().spacing(),
2639                                          cursor.par()->params().align(),
2640                                          cursor.par()->params().labelWidthString(), 1);
2641                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2642                         } 
2643                 }
2644                 else {
2645                         lt->breakParagraph(bv_, 0);
2646                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2647                 }
2648
2649                 update(lt,
2650                        BufferView::SELECT
2651                        | BufferView::FITCUR
2652                        | BufferView::CHANGE);
2653                 lt->selection.cursor = cursor;
2654                 setState();
2655                 owner_->showState();
2656         }
2657         break;
2658
2659         case LFUN_PARAGRAPH_SPACING:
2660         {
2661                 LyXText * lt = bv_->getLyXText();
2662                 
2663                 Paragraph * par = lt->cursor.par();
2664                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2665                 float cur_value = 1.0;
2666                 if (cur_spacing == Spacing::Other) {
2667                         cur_value = par->params().spacing().getValue();
2668                 }
2669                 
2670                 istringstream istr(argument.c_str());
2671
2672                 string tmp;
2673                 istr >> tmp;
2674                 Spacing::Space new_spacing = cur_spacing;
2675                 float new_value = cur_value;
2676                 if (tmp.empty()) {
2677                         lyxerr << "Missing argument to `paragraph-spacing'"
2678                                << endl;
2679                 } else if (tmp == "single") {
2680                         new_spacing = Spacing::Single;
2681                 } else if (tmp == "onehalf") {
2682                         new_spacing = Spacing::Onehalf;
2683                 } else if (tmp == "double") {
2684                         new_spacing = Spacing::Double;
2685                 } else if (tmp == "other") {
2686                         new_spacing = Spacing::Other;
2687                         float tmpval = 0.0;
2688                         istr >> tmpval;
2689                         lyxerr << "new_value = " << tmpval << endl;
2690                         if (tmpval != 0.0)
2691                                 new_value = tmpval;
2692                 } else if (tmp == "default") {
2693                         new_spacing = Spacing::Default;
2694                 } else {
2695                         lyxerr << _("Unknown spacing argument: ")
2696                                << argument << endl;
2697                 }
2698                 if (cur_spacing != new_spacing || cur_value != new_value) {
2699                         par->params().spacing(Spacing(new_spacing, new_value));
2700                         lt->redoParagraph(bv_);
2701                         update(lt,
2702                                BufferView::SELECT
2703                                | BufferView::FITCUR
2704                                | BufferView::CHANGE);
2705                 }
2706         }
2707         break;
2708         
2709         case LFUN_INSET_TOGGLE:
2710         {
2711                 LyXText * lt = bv_->getLyXText();
2712                 hideCursor();
2713                 beforeChange(lt);
2714                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2715                 lt->toggleInset(bv_);
2716                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2717                 setState();
2718         }       
2719                 break;
2720
2721         case LFUN_QUOTE:
2722                 smartQuote();
2723                 break;
2724
2725         case LFUN_HTMLURL:
2726         case LFUN_URL:
2727         {
2728                 InsetCommandParams p;
2729                 if (action == LFUN_HTMLURL)
2730                         p.setCmdName("htmlurl");
2731                 else
2732                         p.setCmdName("url");
2733                 owner_->getDialogs()->createUrl(p.getAsString());
2734         }
2735         break;
2736         
2737         case LFUN_INSERT_URL:
2738         {
2739                 InsetCommandParams p;
2740                 p.setFromString(argument);
2741
2742                 InsetUrl * inset = new InsetUrl(p);
2743                 if (!insertInset(inset))
2744                         delete inset;
2745                 else
2746                         updateInset(inset, true);
2747         }
2748         break;
2749         
2750         case LFUN_INSET_TEXT:
2751                 insertAndEditInset(new InsetText);
2752                 break;
2753         
2754         case LFUN_INSET_ERT:
2755                 insertAndEditInset(new InsetERT);
2756                 break;
2757         
2758         case LFUN_INSET_EXTERNAL:
2759                 insertAndEditInset(new InsetExternal);
2760                 break;
2761         
2762         case LFUN_INSET_FOOTNOTE:
2763                 insertAndEditInset(new InsetFoot);
2764                 break;
2765
2766         case LFUN_INSET_MARGINAL:
2767                 insertAndEditInset(new InsetMarginal);
2768                 break;
2769
2770         case LFUN_INSET_MINIPAGE:
2771                 insertAndEditInset(new InsetMinipage);
2772                 break;
2773
2774         case LFUN_INSERT_NOTE:
2775                 insertAndEditInset(new InsetNote);
2776                 break;
2777
2778         case LFUN_INSET_FLOAT:
2779                 // check if the float type exist
2780                 if (floatList.typeExist(argument)) {
2781                         insertAndEditInset(new InsetFloat(argument));
2782                 } else {
2783                         lyxerr << "Non-existent float type: "
2784                                << argument << endl;
2785                 }
2786                 break;
2787
2788         case LFUN_INSET_WIDE_FLOAT:
2789         {
2790                 // check if the float type exist
2791                 if (floatList.typeExist(argument)) {
2792                         InsetFloat * new_inset = new InsetFloat(argument);
2793                         new_inset->wide(true);
2794                         if (insertInset(new_inset))
2795                                 new_inset->edit(bv_);
2796                         else
2797                                 delete new_inset;
2798                 } else {
2799                         lyxerr << "Non-existent float type: "
2800                                << argument << endl;
2801                 }
2802                 
2803         }
2804         break;
2805
2806 #if 0
2807         case LFUN_INSET_LIST:
2808                 insertAndEditInset(new InsetList);
2809                 break;
2810
2811         case LFUN_INSET_THEOREM:
2812                 insertAndEditInset(new InsetTheorem);
2813                 break;
2814 #endif
2815                 
2816         case LFUN_INSET_CAPTION:
2817         {
2818                 // Do we have a locking inset...
2819                 if (bv_->theLockingInset()) {
2820                         lyxerr << "Locking inset code: "
2821                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2822                         InsetCaption * new_inset = new InsetCaption;
2823                         new_inset->setOwner(bv_->theLockingInset());
2824                         new_inset->setAutoBreakRows(true);
2825                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2826                         new_inset->setFrameColor(0, LColor::captionframe);
2827                         if (insertInset(new_inset))
2828                                 new_inset->edit(bv_);
2829                         else
2830                                 delete new_inset;
2831                 }
2832         }
2833         break;
2834         
2835         case LFUN_INSET_TABULAR:
2836         {
2837                 int r = 2;
2838                 int c = 2;
2839                 if (!argument.empty())
2840                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2841                 InsetTabular * new_inset =
2842                         new InsetTabular(*buffer_, r, c);
2843                 bool const rtl =
2844                         bv_->getLyXText()->real_current_font.isRightToLeft();
2845                 if (!open_new_inset(new_inset, rtl))
2846                         delete new_inset;
2847         }
2848         break;
2849
2850         // --- lyxserver commands ----------------------------
2851
2852         case LFUN_CHARATCURSOR:
2853         {
2854                 pos_type pos = bv_->getLyXText()->cursor.pos();
2855                 if (pos < bv_->getLyXText()->cursor.par()->size())
2856                         owner_->getLyXFunc()->setMessage(
2857                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2858                 else
2859                         owner_->getLyXFunc()->setMessage("EOF");
2860         }
2861         break;
2862         
2863         case LFUN_GETXY:
2864                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2865                                                  + ' '
2866                                                  + tostr(bv_->getLyXText()->cursor.y()));
2867                 break;
2868                 
2869         case LFUN_SETXY:
2870         {
2871                 int x = 0;
2872                 int y = 0;
2873                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2874                         lyxerr << "SETXY: Could not parse coordinates in '"
2875                                << argument << std::endl;
2876                 }
2877                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2878         }
2879         break;
2880         
2881         case LFUN_GETLAYOUT:
2882                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout));
2883                 break;
2884                         
2885         case LFUN_GETFONT:
2886         {
2887                 LyXFont & font = bv_->getLyXText()->current_font;
2888                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2889                         owner_->getLyXFunc()->setMessage("E");
2890                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2891                         owner_->getLyXFunc()->setMessage("N");
2892                 else
2893                         owner_->getLyXFunc()->setMessage("0");
2894
2895         }
2896         break;
2897
2898         // --- accented characters ---------------------------
2899                 
2900         case LFUN_UMLAUT:
2901         case LFUN_CIRCUMFLEX:
2902         case LFUN_GRAVE:
2903         case LFUN_ACUTE:
2904         case LFUN_TILDE:
2905         case LFUN_CEDILLA:
2906         case LFUN_MACRON:
2907         case LFUN_DOT:
2908         case LFUN_UNDERDOT:
2909         case LFUN_UNDERBAR:
2910         case LFUN_CARON:
2911         case LFUN_SPECIAL_CARON:
2912         case LFUN_BREVE:
2913         case LFUN_TIE:
2914         case LFUN_HUNG_UMLAUT:
2915         case LFUN_CIRCLE:
2916         case LFUN_OGONEK:
2917                 if (argument.empty()) {
2918                         // As always...
2919                         owner_->getLyXFunc()->handleKeyFunc(action);
2920                 } else {
2921                         owner_->getLyXFunc()->handleKeyFunc(action);
2922                         owner_->getIntl()->getTrans()
2923                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
2924                         update(bv_->getLyXText(),
2925                                BufferView::SELECT
2926                                | BufferView::FITCUR
2927                                | BufferView::CHANGE);
2928                 }
2929                 break;
2930         
2931         case LFUN_MATH_MACRO:
2932                 mathDispatchMathMacro(bv_, argument);
2933                 break;
2934
2935         case LFUN_MATH_DELIM:     
2936                 mathDispatchMathDelim(bv_, argument);
2937                 break;
2938
2939         case LFUN_INSERT_MATRIX:
2940                 mathDispatchInsertMatrix(bv_, argument);
2941                 break;
2942
2943         case LFUN_INSERT_MATH:
2944                 mathDispatchInsertMath(bv_, argument);
2945                 break;
2946
2947         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2948                 mathDispatchMathImportSelection(bv_, argument);
2949                 break;
2950
2951         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2952                 mathDispatchMathDisplay(bv_, argument);
2953                 break;
2954
2955         case LFUN_MATH_MODE:             // Open or create an inlined math inset 
2956                 mathDispatchMathMode(bv_, argument);
2957                 break;
2958                 
2959         case LFUN_GREEK:                 // Insert a single greek letter
2960                 mathDispatchGreek(bv_, argument);
2961                 break;
2962                 
2963         case LFUN_CITATION_INSERT:
2964         {
2965                 InsetCommandParams p;
2966                 p.setFromString(argument);
2967
2968                 InsetCitation * inset = new InsetCitation(p);
2969                 if (!insertInset(inset))
2970                         delete inset;
2971                 else
2972                         updateInset(inset, true);
2973         }
2974         break;
2975                     
2976         case LFUN_INSERT_BIBTEX:
2977         {   
2978                 // ale970405+lasgoutt970425
2979                 // The argument can be up to two tokens separated 
2980                 // by a space. The first one is the bibstyle.
2981                 string const db       = token(argument, ' ', 0);
2982                 string const bibstyle = token(argument, ' ', 1);
2983
2984                 InsetCommandParams p("BibTeX", db, bibstyle);
2985                 InsetBibtex * inset = new InsetBibtex(p);
2986                 
2987                 if (insertInset(inset)) {
2988                         if (argument.empty())
2989                                 inset->edit(bv_);
2990                 } else
2991                         delete inset;
2992         }
2993         break;
2994                 
2995         // BibTeX data bases
2996         case LFUN_BIBDB_ADD:
2997         {
2998                 InsetBibtex * inset = 
2999                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3000                 if (inset) {
3001                         inset->addDatabase(argument);
3002                 }
3003         }
3004         break;
3005                     
3006         case LFUN_BIBDB_DEL:
3007         {
3008                 InsetBibtex * inset = 
3009                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3010                 if (inset) {
3011                         inset->delDatabase(argument);
3012                 }
3013         }
3014         break;
3015         
3016         case LFUN_BIBTEX_STYLE:
3017         {
3018                 InsetBibtex * inset = 
3019                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
3020                 if (inset) {
3021                         inset->setOptions(argument);
3022                 }
3023         }
3024         break;
3025                 
3026         case LFUN_INDEX_CREATE:
3027         {
3028                 InsetCommandParams p("index");
3029                 if (argument.empty()) {
3030                         string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3031                         p.setContents(idxstring);
3032                 } else {
3033                         p.setContents(argument);
3034                 }
3035
3036                 owner_->getDialogs()->createIndex(p.getAsString());
3037         }
3038         break;
3039                     
3040         case LFUN_INDEX_INSERT:
3041         {
3042                 InsetCommandParams p;
3043                 p.setFromString(argument);
3044                 InsetIndex * inset = new InsetIndex(p);
3045
3046                 if (!insertInset(inset))
3047                         delete inset;
3048                 else
3049                         updateInset(inset, true);
3050         }
3051         break;
3052                     
3053         case LFUN_INDEX_INSERT_LAST:
3054         {
3055                 string const idxstring(bv_->getLyXText()->getStringToIndex(bv_));
3056                 if (!idxstring.empty()) {
3057                         owner_->message(_("Word `")
3058                                         + idxstring + _(("' indexed.")));
3059                         InsetCommandParams p("index", idxstring);
3060                         InsetIndex * inset = new InsetIndex(p);
3061                         
3062                         if (!insertInset(inset))
3063                                 delete inset;
3064                         else
3065                                 updateInset(inset, true);
3066                 }
3067         }
3068         break;
3069
3070         case LFUN_INDEX_PRINT:
3071         {
3072                 InsetCommandParams p("printindex");
3073                 Inset * inset = new InsetPrintIndex(p);
3074                 if (!insertInset(inset, "Standard"))
3075                         delete inset;
3076         }
3077         break;
3078
3079         case LFUN_PARENTINSERT:
3080         {
3081                 lyxerr << "arg " << argument << endl;
3082                 InsetCommandParams p("lyxparent", argument);
3083                 Inset * inset = new InsetParent(p, *buffer_);
3084                 if (!insertInset(inset, "Standard"))
3085                         delete inset;
3086         }
3087                  
3088         break;
3089
3090         case LFUN_CHILD_INSERT:
3091         {
3092                 InsetInclude::Params p;
3093                 p.cparams.setFromString(argument);
3094                 p.masterFilename_ = buffer_->fileName();
3095
3096                 InsetInclude * inset = new InsetInclude(p);
3097                 if (!insertInset(inset))
3098                         delete inset;
3099                 else {
3100                         updateInset(inset, true);
3101                         bv_->owner()->getDialogs()->showInclude(inset);
3102                 }
3103         }
3104         break; 
3105
3106         case LFUN_FLOAT_LIST:
3107         {
3108                 // We should check the argument for validity. (Lgb)
3109                 Inset * inset = new InsetFloatList(argument);
3110                 if (!insertInset(inset, "Standard"))
3111                         delete inset;
3112         }
3113         break;
3114         
3115         case LFUN_THESAURUS_ENTRY:
3116         {
3117                 string arg = argument;
3118
3119                 if (arg.empty()) {
3120                         arg = bv_->getLyXText()->selectionAsString(buffer_,
3121                                                                    false);
3122  
3123                         // FIXME
3124                         if (arg.size() > 100 || arg.empty()) {
3125                                 // Get word or selection
3126                                 bv_->getLyXText()->selectWordWhenUnderCursor(bv_, LyXText::WHOLE_WORD);
3127                                 arg = bv_->getLyXText()->selectionAsString(buffer_, false);
3128                                 // FIXME: where is getLyXText()->unselect(bv_) ?
3129                         }
3130                 }
3131
3132                 bv_->owner()->getDialogs()->showThesaurus(arg);
3133         }
3134                 break;
3135  
3136         case LFUN_SELFINSERT:
3137         {
3138                 if (argument.empty()) break;
3139                 
3140                 /* Automatically delete the currently selected
3141                  * text and replace it with what is being
3142                  * typed in now. Depends on lyxrc settings
3143                  * "auto_region_delete", which defaults to
3144                  * true (on). */
3145
3146                 LyXText * lt = bv_->getLyXText();
3147                 
3148                 if (lyxrc.auto_region_delete) {
3149                         if (lt->selection.set()) {
3150                                 lt->cutSelection(bv_, false, false);
3151                                 bv_->update(lt,
3152                                             BufferView::SELECT
3153                                             | BufferView::FITCUR
3154                                             | BufferView::CHANGE);
3155                         }
3156                 }
3157                 
3158                 beforeChange(lt);
3159                 LyXFont const old_font(lt->real_current_font);
3160                 
3161                 string::const_iterator cit = argument.begin();
3162                 string::const_iterator end = argument.end();
3163                 for (; cit != end; ++cit) {
3164                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3165                 }
3166                 
3167                 bv_->update(lt,
3168                             BufferView::SELECT
3169                             | BufferView::FITCUR
3170                             | BufferView::CHANGE);
3171                 
3172                 lt->selection.cursor = lt->cursor;
3173                 moveCursorUpdate(false);
3174                 
3175                 // real_current_font.number can change so we need to
3176                 // update the minibuffer
3177                 if (old_font != lt->real_current_font)
3178                         owner_->showState();
3179                 //return string();
3180         }
3181         break;
3182
3183         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3184         {
3185                 time_t now_time_t = time(NULL);
3186                 struct tm * now_tm = localtime(&now_time_t);
3187                 setlocale(LC_TIME, "");
3188                 string arg;
3189                 if (!argument.empty())
3190                         arg = argument;
3191                 else 
3192                         arg = lyxrc.date_insert_format;
3193                 char datetmp[32];
3194                 int const datetmp_len =
3195                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3196
3197                 LyXText * lt = bv_->getLyXText();
3198                 
3199                 for (int i = 0; i < datetmp_len; i++) {
3200                         lt->insertChar(bv_, datetmp[i]);
3201                         update(lt,
3202                                BufferView::SELECT
3203                                | BufferView::FITCUR
3204                                | BufferView::CHANGE);
3205                 }
3206
3207                 lt->selection.cursor = lt->cursor;
3208                 moveCursorUpdate(false);
3209         }
3210         break;
3211
3212         case LFUN_UNKNOWN_ACTION:
3213                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3214                 break;
3215         
3216         default:
3217                 return false;
3218         } // end of switch
3219
3220         return true;
3221 }
3222
3223
3224 void BufferView::Pimpl::newline()
3225 {
3226         if (available()) {
3227                 LyXText * lt = bv_->getLyXText();
3228                 hideCursor();
3229                 update(lt,
3230                        BufferView::SELECT
3231                        | BufferView::FITCUR);
3232                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3233                 update(lt,
3234                        BufferView::SELECT
3235                        | BufferView::FITCUR
3236                        | BufferView::CHANGE);
3237         }
3238 }
3239
3240
3241 void BufferView::Pimpl::hfill()
3242 {
3243         if (available()) {
3244                 LyXText * lt = bv_->getLyXText();
3245                 hideCursor();
3246                 update(lt,
3247                        BufferView::SELECT
3248                        | BufferView::FITCUR);
3249                 lt->insertChar(bv_, Paragraph::META_HFILL);
3250                 update(lt,
3251                        BufferView::SELECT
3252                        | BufferView::FITCUR
3253                        | BufferView::CHANGE);
3254         }
3255 }
3256
3257
3258 void BufferView::Pimpl::protectedBlank(LyXText * lt)
3259 {
3260         if (available()) {
3261                 hideCursor();
3262                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3263                 InsetSpecialChar * new_inset =
3264                         new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
3265 #ifdef WITH_WARNINGS
3266 #warning Why is this code different from specialChar() below? (JMarc)
3267 // the code in specialChar is a generic version of what used to exist
3268 // for other special chars. I did not merge this case because of the
3269 // call to updateInset(), but what does it do?
3270 #endif
3271                 if (!insertInset(new_inset))
3272                         delete new_inset;
3273                 else
3274                         updateInset(new_inset, true);
3275         }
3276 }
3277
3278
3279 void BufferView::Pimpl::specialChar(InsetSpecialChar::Kind kind)
3280 {
3281         if (available()) {
3282                 LyXText * lt = bv_->getLyXText();
3283                 
3284                 hideCursor();
3285                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3286                 InsetSpecialChar * new_inset = 
3287                         new InsetSpecialChar(kind);
3288                 if (!insertInset(new_inset))
3289                         delete new_inset;
3290         }
3291 }
3292
3293
3294 void BufferView::Pimpl::smartQuote()
3295 {
3296         LyXText const * lt = bv_->getLyXText();
3297         Paragraph const * par = lt->cursor.par();
3298         pos_type pos = lt->cursor.pos();
3299         char c;
3300
3301         if (!pos
3302             || (par->isInset(pos - 1)
3303                 && par->getInset(pos - 1)->isSpace()))
3304                 c = ' ';
3305         else
3306                 c = par->getChar(pos - 1);
3307                 
3308
3309         hideCursor();
3310
3311         LyXLayout const & style = textclasslist.Style(
3312                 bv_->buffer()->params.textclass, par->getLayout());
3313         
3314         if (style.pass_thru ||
3315                 (!insertInset(new InsetQuotes(c, bv_->buffer()->params))))
3316                 bv_->owner()->getLyXFunc()->dispatch(LFUN_SELFINSERT, "\"");
3317 }
3318
3319
3320 void BufferView::Pimpl::insertAndEditInset(Inset * inset)
3321 {
3322         if (insertInset(inset))
3323                 inset->edit(bv_);
3324         else
3325                 delete inset;
3326 }
3327
3328  
3329 // Open and lock an updatable inset
3330 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3331 {
3332         LyXText * lt = bv_->getLyXText();
3333         
3334         beforeChange(lt);
3335         finishUndo();
3336         if (!insertInset(new_inset)) {
3337                 delete new_inset;
3338                 return false;
3339         }
3340         new_inset->edit(bv_, !behind);
3341         return true;
3342 }
3343
3344
3345 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3346 {
3347         // if we are in a locking inset we should try to insert the
3348         // inset there otherwise this is a illegal function now
3349         if (bv_->theLockingInset()) {
3350                 if (bv_->theLockingInset()->insetAllowed(inset))
3351                     return bv_->theLockingInset()->insertInset(bv_, inset);
3352                 return false;
3353         }
3354
3355         // not quite sure if we want this...
3356         setCursorParUndo(bv_);
3357         freezeUndo();
3358         
3359         beforeChange(bv_->text);
3360         if (!lout.empty()) {
3361                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3362                 bv_->text->breakParagraph(bv_);
3363                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3364
3365                 if (bv_->text->cursor.par()->size()) {
3366                         bv_->text->cursorLeft(bv_);
3367                         
3368                         bv_->text->breakParagraph(bv_);
3369                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3370                 }
3371
3372                 pair<bool, layout_type> lres =
3373                         textclasslist.NumberOfLayout(buffer_->params .textclass, lout);
3374                 layout_type lay = 0;
3375                 if (lres.first != false) {
3376                         // layout found
3377                         lay = lres.second;
3378                 } else {
3379                         // layout not fount using default "Standard" (0)
3380                         lay = 0;
3381                 }
3382                  
3383                 bv_->text->setLayout(bv_, lay);
3384                 
3385                 bv_->text->setParagraph(bv_, 0, 0,
3386                                    0, 0,
3387                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3388                                    Spacing(),
3389                                    LYX_ALIGN_LAYOUT, 
3390                                    string(),
3391                                    0);
3392                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3393         }
3394         
3395         bv_->text->insertInset(bv_, inset);
3396         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3397
3398         unFreezeUndo();
3399         return true;
3400 }
3401
3402
3403 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3404 {
3405         if (!inset)
3406                 return;
3407
3408         // first check for locking insets
3409         if (bv_->theLockingInset()) {
3410                 if (bv_->theLockingInset() == inset) {
3411                         if (bv_->text->updateInset(bv_, inset)) {
3412                                 update();
3413                                 if (mark_dirty) {
3414                                         buffer_->markDirty();
3415                                 }
3416                                 updateScrollbar();
3417                                 return;
3418                         }
3419                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3420                         if (bv_->text->updateInset(bv_,  bv_->theLockingInset())) {
3421                                 update();
3422                                 if (mark_dirty) {
3423                                         buffer_->markDirty();
3424                                 }
3425                                 updateScrollbar();
3426                                 return;
3427                         }
3428                 }
3429         }
3430   
3431         // then check the current buffer
3432         if (available()) {
3433                 hideCursor();
3434                 update(bv_->text, BufferView::UPDATE);
3435                 if (bv_->text->updateInset(bv_, inset)) {
3436                         if (mark_dirty) {
3437                                 update(bv_->text,
3438                                        BufferView::SELECT
3439                                        | BufferView::FITCUR
3440                                        | BufferView::CHANGE);
3441                         } else {
3442                                 update(bv_->text, SELECT);
3443                         }
3444                         return;
3445                 }
3446         }
3447 }
3448
3449
3450 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3451                                   bool same_content)
3452 {
3453         if (!available()) return;
3454         
3455         hideCursor();
3456         beforeChange(bv_->text);
3457         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3458         
3459         LyXCursor const & cursor = bv_->text->cursor;
3460  
3461         string contents;
3462         if (same_content &&
3463             cursor.par()->isInset(cursor.pos())) {
3464                 Inset const * inset = cursor.par()->getInset(cursor.pos());
3465                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3466                     != codes.end())
3467                         contents =
3468                                 static_cast<InsetCommand const *>(inset)->getContents();
3469         }
3470         
3471  
3472         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3473                 if (bv_->text->cursor.pos() 
3474                     || bv_->text->cursor.par() != bv_->text->ownerParagraph()) {
3475                         LyXCursor tmp = bv_->text->cursor;
3476                         bv_->text->cursor.par(bv_->text->ownerParagraph());
3477                         bv_->text->cursor.pos(0);
3478                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3479                                 bv_->text->cursor = tmp;
3480                                 bv_->owner()->message(_("No more insets"));
3481                         }
3482                 } else {
3483                         bv_->owner()->message(_("No more insets"));
3484                 }
3485         }
3486         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3487         bv_->text->selection.cursor = bv_->text->cursor;
3488 }
3489
3490
3491 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3492 {
3493         gotoInset(vector<Inset::Code>(1, code), same_content);
3494 }