]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
move everything into namespace lyx
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
28 #include "factory.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
32 #include "gettext.h"
33 #include "intl.h"
34 #include "insetiterator.h"
35 #include "language.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
38 #include "lyx_main.h"
39 #include "lyxfind.h"
40 #include "lyxfunc.h"
41 #include "lyxlayout.h"
42 #include "lyxtext.h"
43 #include "lyxtextclass.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "texrow.h"
51 #include "toc.h"
52 #include "undo.h"
53 #include "vspace.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
61
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
65
66 #include "graphics/Previews.h"
67
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
73
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
76
77 #include <functional>
78 #include <vector>
79
80
81 namespace lyx {
82
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
91
92 using std::distance;
93 using std::endl;
94 using std::istringstream;
95 using std::make_pair;
96 using std::min;
97 using std::max;
98 using std::mem_fun_ref;
99 using std::string;
100 using std::vector;
101
102 namespace Alert = frontend::Alert;
103
104 namespace {
105
106 unsigned int const saved_positions_num = 20;
107
108
109 /// Return an inset of this class if it exists at the current cursor position
110 template <class T>
111 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
112 {
113         T * inset = 0;
114         DocIterator it = cur;
115         if (it.nextInset() &&
116             it.nextInset()->lyxCode() == code) {
117                 inset = static_cast<T*>(it.nextInset());
118         }
119         return inset;
120 }
121
122 } // anon namespace
123
124
125 BufferView::BufferView()
126         : buffer_(0), wh_(0),
127           cursor_(*this),
128           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129           intl_(new Intl)
130 {
131         xsel_cache_.set = false;
132
133         saved_positions.resize(saved_positions_num);
134         // load saved bookmarks
135         Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
136         for (Session::BookmarkList::iterator bm = bmList.begin();
137                 bm != bmList.end(); ++bm)
138                 if (bm->get<0>() < saved_positions_num)
139                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
140         // and then clear them
141         bmList.clear();
142
143         intl_->initKeyMapper(lyxrc.use_kbmap);
144 }
145
146
147 BufferView::~BufferView()
148 {
149 }
150
151
152 Buffer * BufferView::buffer() const
153 {
154         return buffer_;
155 }
156
157
158 void BufferView::setBuffer(Buffer * b)
159 {
160         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
161                             << "[ b = " << b << "]" << endl;
162
163         if (buffer_) {
164                 // Save the actual cursor position and anchor inside the
165                 // buffer so that it can be restored in case we rechange
166                 // to this buffer later on.
167                 buffer_->saveCursor(cursor_.selectionBegin(),
168                                     cursor_.selectionEnd());
169                 // current buffer is going to be switched-off, save cursor pos
170                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
171                         boost::tie(cursor_.pit(), cursor_.pos()) );
172         }
173
174         // If we're quitting lyx, don't bother updating stuff
175         if (quitting) {
176                 buffer_ = 0;
177                 return;
178         }
179
180         // If we are closing current buffer, switch to the first in
181         // buffer list.
182         if (!b) {
183                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
184                                     << " No Buffer!" << endl;
185                 // We are closing the buffer, use the first buffer as current
186                 buffer_ = theBufferList().first();
187         } else {
188                 // Set current buffer
189                 buffer_ = b;
190         }
191
192         // Reset old cursor
193         cursor_ = LCursor(*this);
194         anchor_ref_ = 0;
195         offset_ref_ = 0;
196
197         if (buffer_) {
198                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
199                                     << "Buffer addr: " << buffer_ << endl;
200                 cursor_.push(buffer_->inset());
201                 cursor_.resetAnchor();
202                 buffer_->text().init(this);
203                 buffer_->text().setCurrentFont(cursor_);
204                 if (buffer_->getCursor().size() > 0 &&
205                     buffer_->getAnchor().size() > 0)
206                 {
207                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
208                         cursor_.resetAnchor();
209                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
210                         cursor_.setSelection();
211                 }
212         }
213
214         update();
215
216         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
217                 graphics::Previews::get().generateBufferPreviews(*buffer_);
218 }
219
220
221 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
222 {
223         // Get absolute path of file and add ".lyx"
224         // to the filename if necessary
225         string s = fileSearch(string(), filename, "lyx");
226
227         bool const found = !s.empty();
228
229         if (!found)
230                 s = filename;
231
232         // File already open?
233         if (theBufferList().exists(s)) {
234                 docstring const file = makeDisplayPath(s, 20);
235                 docstring text = bformat(_("The document %1$s is already "
236                                                      "loaded.\n\nDo you want to revert "
237                                                      "to the saved version?"), file);
238                 int const ret = Alert::prompt(_("Revert to saved document?"),
239                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
240
241                 if (ret != 0) {
242                         setBuffer(theBufferList().getBuffer(s));
243                         return true;
244                 }
245                 // FIXME: should be LFUN_REVERT
246                 if (!theBufferList().close(theBufferList().getBuffer(s), false))
247                         return false;
248                 // Fall through to new load. (Asger)
249         }
250
251         Buffer * b = 0;
252
253         if (found) {
254                 b = theBufferList().newBuffer(s);
255                 if (!lyx::loadLyXFile(b, s)) {
256                         theBufferList().release(b);
257                         return false;
258                 }
259         } else {
260                 docstring text = bformat(_("The document %1$s does not yet "
261                                                      "exist.\n\nDo you want to create "
262                                                      "a new document?"), from_utf8(s));
263                 int const ret = Alert::prompt(_("Create new document?"),
264                          text, 0, 1, _("&Create"), _("Cancel"));
265
266                 if (ret == 0) {
267                         b = newFile(s, string(), true);
268                         if (!b)
269                                 return false;
270                 } else
271                         return false;
272         }
273
274         setBuffer(b);
275         // Send the "errors" signal in case of parsing errors
276         b->errors("Parse");
277
278         // scroll to the position when the file was last closed
279         if (lyxrc.use_lastfilepos) {
280                 pit_type pit;
281                 pos_type pos;
282                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
283                 // I am not sure how to separate the following part to a function
284                 // so I will leave this to Lars.
285                 //
286                 // check pit since the document may be externally changed.
287                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
288                         ParIterator it = b->par_iterator_begin();
289                         ParIterator const end = b->par_iterator_end();
290                         for (; it != end; ++it)
291                                 if (it.pit() == pit) {
292                                         // restored pos may be bigger than it->size
293                                         setCursor(makeDocIterator(it, min(pos, it->size())));
294                                         update(Update::FitCursor);
295                                         break;
296                                 }
297                 }
298         }
299
300         if (tolastfiles)
301                 LyX::ref().session().addLastFile(b->fileName());
302
303         return true;
304 }
305
306
307 void BufferView::reload()
308 {
309         string const fn = buffer_->fileName();
310         if (theBufferList().close(buffer_, false))
311                 loadLyXFile(fn);
312 }
313
314
315 void BufferView::resize()
316 {
317         if (!buffer_)
318                 return;
319
320         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
321
322         buffer_->text().init(this);
323         update();
324         switchKeyMap();
325 }
326
327
328 bool BufferView::fitCursor()
329 {
330         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
331                 frontend::FontMetrics const & fm =
332                         theFontMetrics(cursor_.getFont());
333                 int const asc = fm.maxAscent();
334                 int const des = fm.maxDescent();
335                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
336                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
337                         return false;
338         }
339         center();
340         return true;
341 }
342
343
344 bool BufferView::multiParSel()
345 {
346         if (!cursor_.selection())
347                 return false;
348         bool ret = multiparsel_cache_;
349         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
350         // Either this, or previous selection spans paragraphs
351         return ret || multiparsel_cache_;
352 }
353
354
355 bool BufferView::update(Update::flags flags)
356 {
357         // This is close to a hot-path.
358         if (lyxerr.debugging(Debug::DEBUG)) {
359                 lyxerr[Debug::DEBUG]
360                         << BOOST_CURRENT_FUNCTION
361                         << "[fitcursor = " << (flags & Update::FitCursor)
362                         << ", forceupdate = " << (flags & Update::Force)
363                         << ", singlepar = " << (flags & Update::SinglePar)
364                         << "]  buffer: " << buffer_ << endl;
365         }
366
367         // Check needed to survive LyX startup
368         if (!buffer_)
369                 return false;
370
371         // Update macro store
372         buffer_->buildMacros();
373
374         // First drawing step
375         updateMetrics(flags & Update::SinglePar);
376
377         // The second drawing step is done in WorkArea::redraw() if needed.
378         bool const need_second_step =
379                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
380                 && (fitCursor() || multiParSel());
381
382         return need_second_step;
383 }
384
385
386 void BufferView::updateScrollbar()
387 {
388         if (!buffer_) {
389                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
390                                      << " no text in updateScrollbar" << endl;
391                 scrollbarParameters_.reset();
392                 return;
393         }
394
395         LyXText & t = buffer_->text();
396         int const parsize = int(t.paragraphs().size() - 1);
397         if (anchor_ref_ >  parsize)  {
398                 anchor_ref_ = parsize;
399                 offset_ref_ = 0;
400         }
401
402         lyxerr[Debug::GUI]
403                 << BOOST_CURRENT_FUNCTION
404                 << " Updating scrollbar: height: " << t.paragraphs().size()
405                 << " curr par: " << cursor_.bottom().pit()
406                 << " default height " << defaultRowHeight() << endl;
407
408         // It would be better to fix the scrollbar to understand
409         // values in [0..1] and divide everything by wh
410
411         // estimated average paragraph height:
412         if (wh_ == 0)
413                 wh_ = height_ / 4;
414         int h = t.getPar(anchor_ref_).height();
415
416         // Normalize anchor/offset (MV):
417         while (offset_ref_ > h && anchor_ref_ < parsize) {
418                 anchor_ref_++;
419                 offset_ref_ -= h;
420                 h = t.getPar(anchor_ref_).height();
421         }
422         // Look at paragraph heights on-screen
423         int sumh = 0;
424         int nh = 0;
425         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
426                 if (sumh > height_)
427                         break;
428                 int const h2 = t.getPar(pit).height();
429                 sumh += h2;
430                 nh++;
431         }
432         int const hav = sumh / nh;
433         // More realistic average paragraph height
434         if (hav > wh_)
435                 wh_ = hav;
436
437         scrollbarParameters_.height = (parsize + 1) * wh_;
438         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
439         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
440 }
441
442
443 ScrollbarParameters const & BufferView::scrollbarParameters() const
444 {
445         return scrollbarParameters_;
446 }
447
448
449 void BufferView::scrollDocView(int value)
450 {
451         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
452                            << "[ value = " << value << "]" << endl;
453
454         if (!buffer_)
455                 return;
456
457         LyXText & t = buffer_->text();
458
459         float const bar = value / float(wh_ * t.paragraphs().size());
460
461         anchor_ref_ = int(bar * t.paragraphs().size());
462         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
463                 anchor_ref_ = int(t.paragraphs().size()) - 1;
464         t.redoParagraph(anchor_ref_);
465         int const h = t.getPar(anchor_ref_).height();
466         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
467 }
468
469
470 void BufferView::setCursorFromScrollbar()
471 {
472         LyXText & t = buffer_->text();
473
474         int const height = 2 * defaultRowHeight();
475         int const first = height;
476         int const last = height_ - height;
477         LCursor & cur = cursor_;
478
479         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
480
481         switch (st) {
482         case bv_funcs::CUR_ABOVE:
483                 t.setCursorFromCoordinates(cur, 0, first);
484                 cur.clearSelection();
485                 break;
486         case bv_funcs::CUR_BELOW:
487                 t.setCursorFromCoordinates(cur, 0, last);
488                 cur.clearSelection();
489                 break;
490         case bv_funcs::CUR_INSIDE:
491                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
492                 int const newy = min(last, max(y, first));
493                 if (y != newy) {
494                         cur.reset(buffer_->inset());
495                         t.setCursorFromCoordinates(cur, 0, newy);
496                 }
497         }
498 }
499
500
501 Change const BufferView::getCurrentChange() const
502 {
503         if (!cursor_.selection())
504                 return Change(Change::UNCHANGED);
505
506         DocIterator dit = cursor_.selectionBegin();
507         return dit.paragraph().lookupChange(dit.pos());
508 }
509
510
511 void BufferView::savePosition(unsigned int i)
512 {
513         if (i >= saved_positions_num)
514                 return;
515         BOOST_ASSERT(cursor_.inTexted());
516         saved_positions[i] = Position(buffer_->fileName(),
517                                       cursor_.paragraph().id(),
518                                       cursor_.pos());
519         if (i > 0)
520                 // emit message signal.
521                 message(bformat(_("Saved bookmark %1$d"), i));
522 }
523
524
525 void BufferView::restorePosition(unsigned int i)
526 {
527         if (i >= saved_positions_num)
528                 return;
529
530         string const fname = saved_positions[i].filename;
531
532         cursor_.clearSelection();
533
534         if (fname != buffer_->fileName()) {
535                 Buffer * b = 0;
536                 if (theBufferList().exists(fname))
537                         b = theBufferList().getBuffer(fname);
538                 else {
539                         b = theBufferList().newBuffer(fname);
540                         // Don't ask, just load it
541                         lyx::loadLyXFile(b, fname);
542                 }
543                 if (b)
544                         setBuffer(b);
545         }
546
547         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
548         if (par == buffer_->par_iterator_end())
549                 return;
550
551         setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
552
553         if (i > 0)
554                 // emit message signal.
555                 message(bformat(_("Moved to bookmark %1$d"), i));
556 }
557
558
559 bool BufferView::isSavedPosition(unsigned int i)
560 {
561         return i < saved_positions_num && !saved_positions[i].filename.empty();
562 }
563
564 void BufferView::saveSavedPositions()
565 {
566         // save bookmarks. It is better to use the pit interface
567         // but I do not know how to effectively convert between
568         // par_id and pit.
569         for (unsigned int i=1; i < saved_positions_num; ++i) {
570                 if ( isSavedPosition(i) )
571                         LyX::ref().session().saveBookmark( boost::tie(
572                                 i,
573                                 saved_positions[i].filename,
574                                 saved_positions[i].par_id,
575                                 saved_positions[i].par_pos) );
576         }
577 }
578
579 void BufferView::switchKeyMap()
580 {
581         if (!lyxrc.rtl_support)
582                 return;
583
584         if (getLyXText()->real_current_font.isRightToLeft()) {
585                 if (intl_->keymap == Intl::PRIMARY)
586                         intl_->keyMapSec();
587         } else {
588                 if (intl_->keymap == Intl::SECONDARY)
589                         intl_->keyMapPrim();
590         }
591 }
592
593
594 int BufferView::workWidth() const
595 {
596         return width_;
597 }
598
599
600 void BufferView::center()
601 {
602         CursorSlice & bot = cursor_.bottom();
603         pit_type const pit = bot.pit();
604         bot.text()->redoParagraph(pit);
605         Paragraph const & par = bot.text()->paragraphs()[pit];
606         anchor_ref_ = pit;
607         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
608                 + par.ascent() - height_ / 2;
609 }
610
611
612 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
613 {
614         FuncStatus flag;
615
616         switch (cmd.action) {
617
618         case LFUN_UNDO:
619                 flag.enabled(!buffer_->undostack().empty());
620                 break;
621         case LFUN_REDO:
622                 flag.enabled(!buffer_->redostack().empty());
623                 break;
624         case LFUN_FILE_INSERT:
625         case LFUN_FILE_INSERT_ASCII_PARA:
626         case LFUN_FILE_INSERT_ASCII:
627         case LFUN_BOOKMARK_SAVE:
628                 // FIXME: Actually, these LFUNS should be moved to LyXText
629                 flag.enabled(cursor_.inTexted());
630                 break;
631         case LFUN_FONT_STATE:
632         case LFUN_LABEL_INSERT:
633         case LFUN_PARAGRAPH_GOTO:
634         // FIXME handle non-trivially
635         case LFUN_OUTLINE_UP:
636         case LFUN_OUTLINE_DOWN:
637         case LFUN_OUTLINE_IN:
638         case LFUN_OUTLINE_OUT:
639         case LFUN_NOTE_NEXT:
640         case LFUN_REFERENCE_NEXT:
641         case LFUN_WORD_FIND:
642         case LFUN_WORD_REPLACE:
643         case LFUN_MARK_OFF:
644         case LFUN_MARK_ON:
645         case LFUN_MARK_TOGGLE:
646         case LFUN_SCREEN_RECENTER:
647         case LFUN_BIBTEX_DATABASE_ADD:
648         case LFUN_BIBTEX_DATABASE_DEL:
649         case LFUN_WORDS_COUNT:
650         case LFUN_NEXT_INSET_TOGGLE:
651                 flag.enabled(true);
652                 break;
653
654         case LFUN_LABEL_GOTO: {
655                 flag.enabled(!cmd.argument().empty()
656                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
657                 break;
658         }
659
660         case LFUN_BOOKMARK_GOTO:
661                 flag.enabled(isSavedPosition(convert<unsigned int>(to_utf8(cmd.argument()))));
662                 break;
663
664         case LFUN_CHANGES_TRACK:
665                 flag.enabled(true);
666                 flag.setOnOff(buffer_->params().trackChanges);
667                 break;
668
669         case LFUN_CHANGES_OUTPUT: {
670                 OutputParams runparams;
671                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
672                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
673                 flag.setOnOff(buffer_->params().outputChanges);
674                 break;
675         }
676
677         case LFUN_CHANGES_MERGE:
678         case LFUN_CHANGE_NEXT:
679         case LFUN_ALL_CHANGES_ACCEPT:
680         case LFUN_ALL_CHANGES_REJECT:
681                 flag.enabled(buffer_); // FIXME: Change tracking (MG)
682                 break;
683
684         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
685                 flag.setOnOff(buffer_->params().compressed);
686                 break;
687         }
688
689         default:
690                 flag.enabled(false);
691         }
692
693         return flag;
694 }
695
696
697 bool BufferView::dispatch(FuncRequest const & cmd)
698 {
699         //lyxerr << BOOST_CURRENT_FUNCTION
700         //       << [ cmd = " << cmd << "]" << endl;
701
702         // Make sure that the cached BufferView is correct.
703         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
704                 << " action[" << cmd.action << ']'
705                 << " arg[" << to_utf8(cmd.argument()) << ']'
706                 << " x[" << cmd.x << ']'
707                 << " y[" << cmd.y << ']'
708                 << " button[" << cmd.button() << ']'
709                 << endl;
710
711         LCursor & cur = cursor_;
712
713         switch (cmd.action) {
714
715         case LFUN_UNDO:
716                 if (buffer_) {
717                         cur.message(_("Undo"));
718                         cur.clearSelection();
719                         if (!textUndo(*this))
720                                 cur.message(_("No further undo information"));
721                         update();
722                         switchKeyMap();
723                 }
724                 break;
725
726         case LFUN_REDO:
727                 if (buffer_) {
728                         cur.message(_("Redo"));
729                         cur.clearSelection();
730                         if (!textRedo(*this))
731                                 cur.message(_("No further redo information"));
732                         update();
733                         switchKeyMap();
734                 }
735                 break;
736
737         case LFUN_FILE_INSERT:
738                 // FIXME: We don't know the encoding of filenames
739                 menuInsertLyXFile(to_utf8(cmd.argument()));
740                 break;
741
742         case LFUN_FILE_INSERT_ASCII_PARA:
743                 // FIXME: We don't know the encoding of filenames
744                 insertAsciiFile(this, to_utf8(cmd.argument()), true);
745                 break;
746
747         case LFUN_FILE_INSERT_ASCII:
748                 // FIXME: We don't know the encoding of filenames
749                 insertAsciiFile(this, to_utf8(cmd.argument()), false);
750                 break;
751
752         case LFUN_FONT_STATE:
753                 cur.message(from_utf8(cur.currentState()));
754                 break;
755
756         case LFUN_BOOKMARK_SAVE:
757                 savePosition(convert<unsigned int>(to_utf8(cmd.argument())));
758                 break;
759
760         case LFUN_BOOKMARK_GOTO:
761                 restorePosition(convert<unsigned int>(to_utf8(cmd.argument())));
762                 break;
763
764         case LFUN_LABEL_GOTO: {
765                 docstring label = cmd.argument();
766                 if (label.empty()) {
767                         InsetRef * inset =
768                                 getInsetByCode<InsetRef>(cursor_,
769                                                          InsetBase::REF_CODE);
770                         if (inset) {
771                                 label = inset->getParam("reference");
772                                 savePosition(0);
773                         }
774                 }
775
776                 if (!label.empty())
777                         gotoLabel(label);
778                 break;
779         }
780
781         case LFUN_PARAGRAPH_GOTO: {
782                 int const id = convert<int>(to_utf8(cmd.argument()));
783                 ParIterator par = buffer_->getParFromID(id);
784                 if (par == buffer_->par_iterator_end()) {
785                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
786                                             << id << ']' << endl;
787                         break;
788                 } else {
789                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
790                                             << " found." << endl;
791                 }
792
793                 // Set the cursor
794                 setCursor(makeDocIterator(par, 0));
795
796                 update();
797                 switchKeyMap();
798                 break;
799         }
800
801         case LFUN_OUTLINE_UP:
802                 toc::outline(toc::Up, cursor_);
803                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
804                 updateLabels(*buffer_);
805                 break;
806         case LFUN_OUTLINE_DOWN:
807                 toc::outline(toc::Down, cursor_);
808                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
809                 updateLabels(*buffer_);
810                 break;
811         case LFUN_OUTLINE_IN:
812                 toc::outline(toc::In, cursor_);
813                 updateLabels(*buffer_);
814                 break;
815         case LFUN_OUTLINE_OUT:
816                 toc::outline(toc::Out, cursor_);
817                 updateLabels(*buffer_);
818                 break;
819
820         case LFUN_NOTE_NEXT:
821                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
822                 break;
823
824         case LFUN_REFERENCE_NEXT: {
825                 vector<InsetBase_code> tmp;
826                 tmp.push_back(InsetBase::LABEL_CODE);
827                 tmp.push_back(InsetBase::REF_CODE);
828                 bv_funcs::gotoInset(this, tmp, true);
829                 break;
830         }
831
832         case LFUN_CHANGES_TRACK:
833                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
834                 break;
835
836         case LFUN_CHANGES_OUTPUT: {
837                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
838                 break;
839         }
840
841         case LFUN_CHANGE_NEXT:
842                 findNextChange(this);
843                 break;
844
845         case LFUN_CHANGES_MERGE:
846                 if (findNextChange(this))
847                         showDialog("changes");
848                 break;
849
850         case LFUN_ALL_CHANGES_ACCEPT: {
851                 cursor_.reset(buffer_->inset());
852 #ifdef WITH_WARNINGS
853 #warning FIXME changes
854 #endif
855                 while (findNextChange(this))
856                         getLyXText()->acceptChange(cursor_);
857                 update();
858                 break;
859         }
860
861         case LFUN_ALL_CHANGES_REJECT: {
862                 cursor_.reset(buffer_->inset());
863 #ifdef WITH_WARNINGS
864 #warning FIXME changes
865 #endif
866                 while (findNextChange(this))
867                         getLyXText()->rejectChange(cursor_);
868                 break;
869         }
870
871         case LFUN_WORD_FIND:
872                 find(this, cmd);
873                 break;
874
875         case LFUN_WORD_REPLACE:
876                 replace(this, cmd);
877                 break;
878
879         case LFUN_MARK_OFF:
880                 cur.clearSelection();
881                 cur.resetAnchor();
882                 cur.message(from_utf8(N_("Mark off")));
883                 break;
884
885         case LFUN_MARK_ON:
886                 cur.clearSelection();
887                 cur.mark() = true;
888                 cur.resetAnchor();
889                 cur.message(from_utf8(N_("Mark on")));
890                 break;
891
892         case LFUN_MARK_TOGGLE:
893                 cur.clearSelection();
894                 if (cur.mark()) {
895                         cur.mark() = false;
896                         cur.message(from_utf8(N_("Mark removed")));
897                 } else {
898                         cur.mark() = true;
899                         cur.message(from_utf8(N_("Mark set")));
900                 }
901                 cur.resetAnchor();
902                 break;
903
904         case LFUN_SCREEN_RECENTER:
905                 center();
906                 break;
907
908         case LFUN_BIBTEX_DATABASE_ADD: {
909                 LCursor tmpcur = cursor_;
910                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
911                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
912                                                 InsetBase::BIBTEX_CODE);
913                 if (inset) {
914                         if (inset->addDatabase(to_utf8(cmd.argument())))
915                                 buffer_->updateBibfilesCache();
916                 }
917                 break;
918         }
919
920         case LFUN_BIBTEX_DATABASE_DEL: {
921                 LCursor tmpcur = cursor_;
922                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
923                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
924                                                 InsetBase::BIBTEX_CODE);
925                 if (inset) {
926                         if (inset->delDatabase(to_utf8(cmd.argument())))
927                                 buffer_->updateBibfilesCache();
928                 }
929                 break;
930         }
931
932         case LFUN_WORDS_COUNT: {
933                 DocIterator from, to;
934                 if (cur.selection()) {
935                         from = cur.selectionBegin();
936                         to = cur.selectionEnd();
937                 } else {
938                         from = doc_iterator_begin(buffer_->inset());
939                         to = doc_iterator_end(buffer_->inset());
940                 }
941                 int const count = countWords(from, to);
942                 docstring message;
943                 if (count != 1) {
944                         if (cur.selection())
945                                 message = bformat(_("%1$d words in selection."),
946                                           count);
947                                 else
948                                         message = bformat(_("%1$d words in document."),
949                                                           count);
950                 }
951                 else {
952                         if (cur.selection())
953                                 message = _("One word in selection.");
954                         else
955                                 message = _("One word in document.");
956                 }
957
958                 Alert::information(_("Count words"), message);
959         }
960                 break;
961
962         case LFUN_BUFFER_TOGGLE_COMPRESSION:
963                 // turn compression on/off
964                 buffer_->params().compressed = !buffer_->params().compressed;
965                 break;
966
967         case LFUN_NEXT_INSET_TOGGLE: {
968                 // this is the real function we want to invoke
969                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
970                 // if there is an inset at cursor, see whether it
971                 // wants to toggle.
972                 InsetBase * inset = cur.nextInset();
973                 if (inset && inset->isActive()) {
974                         LCursor tmpcur = cur;
975                         tmpcur.pushLeft(*inset);
976                         inset->dispatch(tmpcur, tmpcmd);
977                         if (tmpcur.result().dispatched()) {
978                                 cur.dispatched();
979                         }
980                 }
981                 // if it did not work, try the underlying inset.
982                 if (!cur.result().dispatched())
983                         cur.dispatch(tmpcmd);
984
985                 if (cur.result().dispatched())
986                         cur.clearSelection();
987
988                 break;
989         }
990
991         default:
992                 return false;
993         }
994
995         return true;
996 }
997
998
999 docstring const BufferView::requestSelection()
1000 {
1001         if (!buffer_)
1002                 return docstring();
1003
1004         LCursor & cur = cursor_;
1005
1006         if (!cur.selection()) {
1007                 xsel_cache_.set = false;
1008                 return docstring();
1009         }
1010
1011         if (!xsel_cache_.set ||
1012             cur.top() != xsel_cache_.cursor ||
1013             cur.anchor_.top() != xsel_cache_.anchor)
1014         {
1015                 xsel_cache_.cursor = cur.top();
1016                 xsel_cache_.anchor = cur.anchor_.top();
1017                 xsel_cache_.set = cur.selection();
1018                 return cur.selectionAsString(false);
1019         }
1020         return docstring();
1021 }
1022
1023
1024 void BufferView::clearSelection()
1025 {
1026         if (buffer_) {
1027                 cursor_.clearSelection();
1028                 xsel_cache_.set = false;
1029         }
1030 }
1031
1032
1033 void BufferView::workAreaResize(int width, int height)
1034 {
1035         bool const widthChange = width != width_;
1036         bool const heightChange = height != height_;
1037
1038         // Update from work area
1039         width_ = width;
1040         height_ = height;
1041
1042         if (buffer_ && widthChange) {
1043                 // The WorkArea content needs a resize
1044                 resize();
1045         }
1046
1047         if (widthChange || heightChange)
1048                 update();
1049 }
1050
1051
1052 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1053 {
1054         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1055
1056         // This is only called for mouse related events including
1057         // LFUN_FILE_OPEN generated by drag-and-drop.
1058         FuncRequest cmd = cmd0;
1059
1060         if (!buffer_)
1061                 return false;
1062
1063         LCursor cur(*this);
1064         cur.push(buffer_->inset());
1065         cur.selection() = cursor_.selection();
1066
1067         // Doesn't go through lyxfunc, so we need to update
1068         // the layout choice etc. ourselves
1069
1070         // E.g. Qt mouse press when no buffer
1071         if (!buffer_)
1072                 return false;
1073
1074         // Either the inset under the cursor or the
1075         // surrounding LyXText will handle this event.
1076
1077         // Build temporary cursor.
1078         cmd.y = min(max(cmd.y, -1), height_);
1079         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1080         //lyxerr << BOOST_CURRENT_FUNCTION
1081         //       << " * hit inset at tip: " << inset << endl;
1082         //lyxerr << BOOST_CURRENT_FUNCTION
1083         //       << " * created temp cursor:" << cur << endl;
1084
1085         // Put anchor at the same position.
1086         cur.resetAnchor();
1087
1088         // Try to dispatch to an non-editable inset near this position
1089         // via the temp cursor. If the inset wishes to change the real
1090         // cursor it has to do so explicitly by using
1091         //  cur.bv().cursor() = cur;  (or similar)
1092         if (inset)
1093                 inset->dispatch(cur, cmd);
1094
1095         // Now dispatch to the temporary cursor. If the real cursor should
1096         // be modified, the inset's dispatch has to do so explicitly.
1097         if (!cur.result().dispatched())
1098                 cur.dispatch(cmd);
1099
1100         if (cur.result().dispatched()) {
1101                 // Redraw if requested or necessary.
1102                 if (cur.result().update())
1103                         update(Update::FitCursor | Update::Force);
1104                 else
1105                         update(Update::FitCursor | Update::MultiParSel);
1106         }
1107
1108         return true;
1109 }
1110
1111
1112 void BufferView::scroll(int /*lines*/)
1113 {
1114 //      if (!buffer_)
1115 //              return;
1116 //
1117 //      LyXText const * t = &buffer_->text();
1118 //      int const line_height = defaultRowHeight();
1119 //
1120 //      // The new absolute coordinate
1121 //      int new_top_y = top_y() + lines * line_height;
1122 //
1123 //      // Restrict to a valid value
1124 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1125 //      new_top_y = std::max(0, new_top_y);
1126 //
1127 //      scrollDocView(new_top_y);
1128 //
1129 //      // Update the scrollbar.
1130 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1131 }
1132
1133
1134 void BufferView::setCursorFromRow(int row)
1135 {
1136         int tmpid = -1;
1137         int tmppos = -1;
1138
1139         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1140
1141         if (tmpid == -1)
1142                 buffer_->text().setCursor(cursor_, 0, 0);
1143         else
1144                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1145 }
1146
1147
1148 void BufferView::gotoLabel(docstring const & label)
1149 {
1150         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1151                 vector<docstring> labels;
1152                 it->getLabelList(*buffer_, labels);
1153                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1154                         setCursor(it);
1155                         update();
1156                         return;
1157                 }
1158         }
1159 }
1160
1161
1162 LyXText * BufferView::getLyXText()
1163 {
1164         LyXText * text = cursor_.innerText();
1165         BOOST_ASSERT(text);
1166         return text;
1167 }
1168
1169
1170 LyXText const * BufferView::getLyXText() const
1171 {
1172         LyXText const * text = cursor_.innerText();
1173         BOOST_ASSERT(text);
1174         return text;
1175 }
1176
1177
1178 int BufferView::workHeight() const
1179 {
1180         return height_;
1181 }
1182
1183
1184 void BufferView::setCursor(DocIterator const & dit)
1185 {
1186         size_t const n = dit.depth();
1187         for (size_t i = 0; i < n; ++i)
1188                 dit[i].inset().edit(cursor_, true);
1189
1190         cursor_.setCursor(dit);
1191         cursor_.selection() = false;
1192 }
1193
1194
1195 void BufferView::mouseSetCursor(LCursor & cur)
1196 {
1197         BOOST_ASSERT(&cur.bv() == this);
1198
1199         // Has the cursor just left the inset?
1200         bool badcursor = false;
1201         if (&cursor_.inset() != &cur.inset())
1202                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1203
1204         // do the dEPM magic if needed
1205         // FIXME: move this to InsetText::notifyCursorLeaves?
1206         if (!badcursor && cursor_.inTexted())
1207                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1208
1209         cursor_ = cur;
1210         cursor_.clearSelection();
1211         cursor_.setTargetX();
1212         finishUndo();
1213
1214 }
1215
1216
1217 void BufferView::putSelectionAt(DocIterator const & cur,
1218                                 int length, bool backwards)
1219 {
1220         cursor_.clearSelection();
1221
1222         setCursor(cur);
1223
1224         if (length) {
1225                 if (backwards) {
1226                         cursor_.pos() += length;
1227                         cursor_.setSelection(cursor_, -length);
1228                 } else
1229                         cursor_.setSelection(cursor_, length);
1230         }
1231 }
1232
1233
1234 LCursor & BufferView::cursor()
1235 {
1236         return cursor_;
1237 }
1238
1239
1240 LCursor const & BufferView::cursor() const
1241 {
1242         return cursor_;
1243 }
1244
1245
1246 pit_type BufferView::anchor_ref() const
1247 {
1248         return anchor_ref_;
1249 }
1250
1251
1252 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1253 {
1254         return metrics_info_;
1255 }
1256
1257
1258 void BufferView::updateMetrics(bool singlepar)
1259 {
1260         // FIXME (Abdel 19/10/2006):
1261         // There's something fishy in tabular. The coord_cache_ is not
1262         // correctly reconstructed when a character is trying to be inserted.
1263         // Not clearing out the coord_cache_ fixes the crash but there is a
1264         // bad side effect: buffer-begin and buffer-end do not update the screen.
1265         //
1266         // Remove old position cache
1267         coord_cache_.clear();
1268
1269         LyXText & buftext = buffer_->text();
1270         pit_type size = int(buftext.paragraphs().size());
1271
1272         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1273                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1274                 offset_ref_ = 0;
1275         }
1276
1277         pit_type const pit = anchor_ref_;
1278         int pit1 = pit;
1279         int pit2 = pit;
1280         size_t const npit = buftext.paragraphs().size();
1281
1282         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1283         // the (main text, not inset!) paragraph containing the cursor.
1284         // (if this paragraph contains insets etc., rebreaking will
1285         // recursively descend)
1286         if (!singlepar || pit == cursor_.bottom().pit())
1287                 buftext.redoParagraph(pit);
1288         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1289
1290         // Redo paragraphs above anchor if necessary; again, in Single Par
1291         // mode, only if we encounter the (main text) one having the cursor.
1292         int y1 = y0;
1293         while (y1 > 0 && pit1 > 0) {
1294                 y1 -= buftext.getPar(pit1).ascent();
1295                 --pit1;
1296                 if (!singlepar || pit1 == cursor_.bottom().pit())
1297                         buftext.redoParagraph(pit1);
1298                 y1 -= buftext.getPar(pit1).descent();
1299         }
1300
1301
1302         // Take care of ascent of first line
1303         y1 -= buftext.getPar(pit1).ascent();
1304
1305         // Normalize anchor for next time
1306         anchor_ref_ = pit1;
1307         offset_ref_ = -y1;
1308
1309         // Grey at the beginning is ugly
1310         if (pit1 == 0 && y1 > 0) {
1311                 y0 -= y1;
1312                 y1 = 0;
1313                 anchor_ref_ = 0;
1314         }
1315
1316         // Redo paragraphs below the anchor if necessary. Single par mode:
1317         // only the one containing the cursor if encountered.
1318         int y2 = y0;
1319         while (y2 < height_ && pit2 < int(npit) - 1) {
1320                 y2 += buftext.getPar(pit2).descent();
1321                 ++pit2;
1322                 if (!singlepar || pit2 == cursor_.bottom().pit())
1323                         buftext.redoParagraph(pit2);
1324                 y2 += buftext.getPar(pit2).ascent();
1325         }
1326
1327         // Take care of descent of last line
1328         y2 += buftext.getPar(pit2).descent();
1329
1330         // The coordinates of all these paragraphs are correct, cache them
1331         int y = y1;
1332         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1333         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1334                 Paragraph const & par = buftext.getPar(pit);
1335                 y += par.ascent();
1336                 parPos[pit] = Point(0, y);
1337                 if (singlepar && pit == cursor_.bottom().pit()) {
1338                         // In Single Paragraph mode, collect here the
1339                         // y1 and y2 of the (one) paragraph the cursor is in
1340                         y1 = y - par.ascent();
1341                         y2 = y + par.descent();
1342                 }
1343                 y += par.descent();
1344         }
1345
1346         if (singlepar) {
1347                 // collect cursor paragraph iter bounds
1348                 pit1 = cursor_.bottom().pit();
1349                 pit2 = cursor_.bottom().pit();
1350         }
1351
1352         lyxerr[Debug::DEBUG]
1353                 << BOOST_CURRENT_FUNCTION
1354                 << " y1: " << y1
1355                 << " y2: " << y2
1356                 << " pit1: " << pit1
1357                 << " pit2: " << pit2
1358                 << " npit: " << npit
1359                 << " singlepar: " << singlepar
1360                 << "size: " << size
1361                 << endl;
1362
1363         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1364
1365         if (lyxerr.debugging(Debug::WORKAREA)) {
1366                 coord_cache_.dump();
1367         }
1368 }
1369
1370
1371 void BufferView::menuInsertLyXFile(string const & filenm)
1372 {
1373         BOOST_ASSERT(cursor_.inTexted());
1374         string filename = filenm;
1375
1376         if (filename.empty()) {
1377                 // Launch a file browser
1378                 // FIXME UNICODE
1379                 string initpath = lyxrc.document_path;
1380
1381                 if (buffer_) {
1382                         string const trypath = buffer_->filePath();
1383                         // If directory is writeable, use this as default.
1384                         if (isDirWriteable(trypath))
1385                                 initpath = trypath;
1386                 }
1387
1388                 // FIXME UNICODE
1389                 FileDialog fileDlg(_("Select LyX document to insert"),
1390                         LFUN_FILE_INSERT,
1391                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1392                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1393
1394                 FileDialog::Result result =
1395                         fileDlg.open(from_utf8(initpath),
1396                                      FileFilterList(_("LyX Documents (*.lyx)")),
1397                                      docstring());
1398
1399                 if (result.first == FileDialog::Later)
1400                         return;
1401
1402                 // FIXME UNICODE
1403                 filename = to_utf8(result.second);
1404
1405                 // check selected filename
1406                 if (filename.empty()) {
1407                         // emit message signal.
1408                         message(_("Canceled."));
1409                         return;
1410                 }
1411         }
1412
1413         // Get absolute path of file and add ".lyx"
1414         // to the filename if necessary
1415         filename = fileSearch(string(), filename, "lyx");
1416
1417         docstring const disp_fn = makeDisplayPath(filename);
1418         // emit message signal.
1419         message(bformat(_("Inserting document %1$s..."), disp_fn));
1420
1421         docstring res;
1422         Buffer buf("", false);
1423         if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1424                 ErrorList & el = buffer_->errorList("Parse");
1425                 // Copy the inserted document error list into the current buffer one.
1426                 el = buf.errorList("Parse");
1427                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1428                                              buf.params().textclass, el);
1429                 res = _("Document %1$s inserted.");
1430         } else
1431                 res = _("Could not insert document %1$s");
1432
1433         // emit message signal.
1434         message(bformat(res, disp_fn));
1435         buffer_->errors("Parse");
1436         resize();
1437 }
1438
1439
1440 } // namespace lyx