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