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